From 6934c6d48e7cd2765f0b329bb1d2f3c9f788ee82 Mon Sep 17 00:00:00 2001 From: Bob Dempsey Date: Thu, 4 Sep 2014 16:38:09 -0500 Subject: [PATCH 1/7] 3.5 GPL commit --- ChangeLog | 445 - INSTALL | 45 +- Makefile.am | 43 +- Makefile.in | 58 +- README | 153 +- README.md | 23 +- aclocal.m4 | 190 - build/Build.bat | 82 - build/BuildCalpontVersion.bat | 18 - build/CMakeLists.txt | 155 - build/CalpontVersion.txt.in | 13 - build/CopyLog.sh | 15 - build/CopyToCalweb.bat | 5 - build/InfiniDB.sln | 1199 -- build/Nightly.bat | 80 - build/README.md | 21 - build/Switch.bat | 36 - build/bb_fix_rules.sh | 9 + build/bb_pre_build.sh | 36 - build/build-boost-win.bat | 11 - build/build-branch.mysql | 47 - build/build-genii.mysql | 47 - build/build_rpms | 95 +- build/calpont.spec.in | 400 + build/clean | 3 +- build/infinidb.spec.in | 628 - build/make_src_tar | 130 +- build/nightly-mini-tester.sh | 53 +- build/nightlyDiff.sh | 52 - build/releasenum | 6 +- build/src-build | 138 - build_mysql.sh | 59 + config.h.in | 9 - configure | 1149 +- configure.ac | 107 +- dbcon/Makefile.am | 28 +- dbcon/Makefile.in | 42 +- dbcon/ddlpackage/Makefile.am | 4 + dbcon/ddlpackage/Makefile.in | 50 +- dbcon/ddlpackage/altertable.cpp | 2 +- dbcon/ddlpackage/columndef.cpp | 2 +- dbcon/ddlpackage/createindex.cpp | 2 +- dbcon/ddlpackage/createtable.cpp | 2 +- dbcon/ddlpackage/ddl-gram-win.cpp | 914 +- dbcon/ddlpackage/ddl-gram-win.h | 47 +- dbcon/ddlpackage/ddl-scan-win.cpp | 600 +- dbcon/ddlpackage/ddl.l | 7 +- dbcon/ddlpackage/ddl.y | 72 +- dbcon/ddlpackage/ddlpkg.cpp | 57 +- dbcon/ddlpackage/ddlpkg.h | 255 +- dbcon/ddlpackage/dropindex.cpp | 2 +- dbcon/ddlpackage/droptable.cpp | 2 +- dbcon/ddlpackage/libddlpackage.vcxproj | 236 - .../ddlpackage/libddlpackage.vcxproj.filters | 81 - dbcon/ddlpackage/serialize.cpp | 8 +- dbcon/ddlpackage/sqlparser.cpp | 2 +- dbcon/ddlpackage/sqlparser.h | 2 +- dbcon/ddlpackage/sqlstatement.cpp | 4 +- dbcon/ddlpackage/sqlstatementlist.cpp | 2 +- dbcon/ddlpackage/tabledef.cpp | 2 +- dbcon/ddlpackageproc/Makefile.am | 4 + dbcon/ddlpackageproc/Makefile.in | 50 +- dbcon/ddlpackageproc/altertableprocessor.cpp | 579 +- dbcon/ddlpackageproc/altertableprocessor.h | 25 +- dbcon/ddlpackageproc/createindexprocessor.cpp | 14 +- dbcon/ddlpackageproc/createindexprocessor.h | 2 +- dbcon/ddlpackageproc/createtableprocessor.cpp | 341 +- dbcon/ddlpackageproc/createtableprocessor.h | 7 +- dbcon/ddlpackageproc/ddlindexpopulator.cpp | 6 +- dbcon/ddlpackageproc/ddlindexpopulator.h | 16 +- dbcon/ddlpackageproc/ddlpackageprocessor.cpp | 1236 +- dbcon/ddlpackageproc/ddlpackageprocessor.h | 114 +- .../ddlpackageprocessorfactory.cpp | 2 +- .../ddlpackageprocessorfactory.h | 2 +- dbcon/ddlpackageproc/dropindexprocessor.cpp | 2 +- dbcon/ddlpackageproc/dropindexprocessor.h | 2 +- .../ddlpackageproc/droppartitionprocessor.cpp | 59 +- dbcon/ddlpackageproc/droppartitionprocessor.h | 3 +- dbcon/ddlpackageproc/droptableprocessor.cpp | 1854 +- dbcon/ddlpackageproc/droptableprocessor.h | 6 +- dbcon/ddlpackageproc/libddlpackageproc.rc | 102 - .../ddlpackageproc/libddlpackageproc.vcxproj | 355 - .../libddlpackageproc.vcxproj.filters | 71 - .../ddlpackageproc/markpartitionprocessor.cpp | 24 +- dbcon/ddlpackageproc/markpartitionprocessor.h | 4 +- dbcon/ddlpackageproc/resource.h | 14 - .../restorepartitionprocessor.cpp | 24 +- .../restorepartitionprocessor.h | 3 +- dbcon/dmlpackage/Makefile.am | 4 + dbcon/dmlpackage/Makefile.in | 50 +- dbcon/dmlpackage/calpontdmlfactory.cpp | 29 +- dbcon/dmlpackage/calpontdmlfactory.h | 2 +- dbcon/dmlpackage/calpontdmlpackage.cpp | 2 +- dbcon/dmlpackage/calpontdmlpackage.h | 193 +- dbcon/dmlpackage/commanddmlpackage.cpp | 33 +- dbcon/dmlpackage/commanddmlpackage.h | 2 +- dbcon/dmlpackage/deletedmlpackage.cpp | 24 +- dbcon/dmlpackage/deletedmlpackage.h | 2 +- dbcon/dmlpackage/dml-scan-win.cpp | 79 +- dbcon/dmlpackage/dmlcolumn.cpp | 8 +- dbcon/dmlpackage/dmlcolumn.h | 2 +- dbcon/dmlpackage/dmlobject.cpp | 2 +- dbcon/dmlpackage/dmlobject.h | 2 +- dbcon/dmlpackage/dmlpackage.h | 2 +- dbcon/dmlpackage/dmlparser.cpp | 2 +- dbcon/dmlpackage/dmlparser.h | 2 +- dbcon/dmlpackage/dmlpkg.cpp | 2 +- dbcon/dmlpackage/dmlpkg.h | 2 +- dbcon/dmlpackage/dmltable.cpp | 2 +- dbcon/dmlpackage/dmltable.h | 2 +- dbcon/dmlpackage/insertdmlpackage.cpp | 79 +- dbcon/dmlpackage/insertdmlpackage.h | 2 +- dbcon/dmlpackage/libdmlpackage.vcxproj | 240 - .../dmlpackage/libdmlpackage.vcxproj.filters | 111 - dbcon/dmlpackage/mysqldmlstatement.cpp | 2 +- dbcon/dmlpackage/mysqldmlstatement.h | 2 +- dbcon/dmlpackage/oracledmlstatement.cpp | 2 +- dbcon/dmlpackage/oracledmlstatement.h | 2 +- dbcon/dmlpackage/row.cpp | 2 +- dbcon/dmlpackage/row.h | 2 +- dbcon/dmlpackage/updatedmlpackage.cpp | 32 +- dbcon/dmlpackage/updatedmlpackage.h | 2 +- dbcon/dmlpackage/vendordmlstatement.cpp | 2 +- dbcon/dmlpackage/vendordmlstatement.h | 2 +- dbcon/dmlpackageproc/Makefile.am | 6 + dbcon/dmlpackageproc/Makefile.in | 60 +- dbcon/dmlpackageproc/autoincrementdata.cpp | 28 +- dbcon/dmlpackageproc/autoincrementdata.h | 36 +- .../commandpackageprocessor.cpp | 376 +- .../dmlpackageproc/commandpackageprocessor.h | 5 +- .../dmlpackageproc/deletepackageprocessor.cpp | 268 +- dbcon/dmlpackageproc/deletepackageprocessor.h | 13 +- dbcon/dmlpackageproc/dmlpackageprocessor.cpp | 218 +- dbcon/dmlpackageproc/dmlpackageprocessor.h | 77 +- .../dmlpackageprocessorfactory.cpp | 2 +- .../dmlpackageprocessorfactory.h | 2 +- .../dmlpackageproc/insertpackageprocessor.cpp | 601 +- dbcon/dmlpackageproc/insertpackageprocessor.h | 32 +- dbcon/dmlpackageproc/libdmlpackageproc.rc | 102 - .../dmlpackageproc/libdmlpackageproc.vcxproj | 361 - .../libdmlpackageproc.vcxproj.filters | 71 - dbcon/dmlpackageproc/resource.h | 14 - dbcon/dmlpackageproc/tablelockdata.cpp | 201 +- dbcon/dmlpackageproc/tablelockdata.h | 122 +- .../dmlpackageproc/updatepackageprocessor.cpp | 252 +- dbcon/dmlpackageproc/updatepackageprocessor.h | 12 +- dbcon/doc/calpontsystemcatalog.h | 2 +- dbcon/doc/readme | 0 dbcon/execplan/Makefile.am | 56 +- dbcon/execplan/Makefile.in | 128 +- dbcon/execplan/aggregatecolumn.cpp | 449 +- dbcon/execplan/aggregatecolumn.h | 245 +- dbcon/execplan/arithmeticcolumn.cpp | 80 +- dbcon/execplan/arithmeticcolumn.h | 66 +- dbcon/execplan/arithmeticoperator.cpp | 52 +- dbcon/execplan/arithmeticoperator.h | 29 +- dbcon/execplan/blocksize.h | 2 +- dbcon/execplan/calpontexecutionplan.cpp | 2 +- dbcon/execplan/calpontexecutionplan.h | 2 +- .../execplan/calpontexecutionplanfactory.cpp | 2 +- dbcon/execplan/calpontexecutionplanfactory.h | 2 +- dbcon/execplan/calpontselectexecutionplan.cpp | 542 +- dbcon/execplan/calpontselectexecutionplan.h | 276 +- dbcon/execplan/calpontsystemcatalog.cpp | 206 +- dbcon/execplan/calpontsystemcatalog.h | 1616 +- dbcon/execplan/clientrotator.cpp | 399 +- dbcon/execplan/clientrotator.h | 160 +- dbcon/execplan/columnresult.h | 6 +- dbcon/execplan/constantcolumn.cpp | 73 +- dbcon/execplan/constantcolumn.h | 179 +- dbcon/execplan/constantfilter.cpp | 181 +- dbcon/execplan/constantfilter.h | 71 +- dbcon/execplan/existsfilter.cpp | 2 +- dbcon/execplan/existsfilter.h | 2 +- dbcon/execplan/exp_templates.h | 6 +- dbcon/execplan/expressionparser.cpp | 5 +- dbcon/execplan/expressionparser.h | 3 +- dbcon/execplan/expressiontree.h | 382 + dbcon/execplan/filter.cpp | 13 +- dbcon/execplan/filter.h | 51 +- dbcon/execplan/functioncolumn.cpp | 395 +- dbcon/execplan/functioncolumn.h | 128 +- dbcon/execplan/groupconcatcolumn.cpp | 51 +- dbcon/execplan/groupconcatcolumn.h | 6 +- dbcon/execplan/intervalcolumn.cpp | 79 - dbcon/execplan/intervalcolumn.h | 113 - dbcon/execplan/libexecplan.vcxproj | 290 - dbcon/execplan/libexecplan.vcxproj.filters | 249 - dbcon/execplan/logicoperator.cpp | 2 +- dbcon/execplan/logicoperator.h | 2 +- dbcon/execplan/mysqlexecutionplan.cpp | 2 +- dbcon/execplan/mysqlexecutionplan.h | 2 +- dbcon/execplan/njlcolumnresult.h | 2 +- dbcon/execplan/objectidmanager.cpp | 6 +- dbcon/execplan/objectidmanager.h | 10 +- dbcon/execplan/objectreader.cpp | 54 +- dbcon/execplan/objectreader.h | 34 +- dbcon/execplan/operator.cpp | 2 +- dbcon/execplan/operator.h | 5 +- dbcon/execplan/oracleexecutionplan.cpp | 2 +- dbcon/execplan/oracleexecutionplan.h | 2 +- dbcon/execplan/outerjoinonfilter.cpp | 2 +- dbcon/execplan/outerjoinonfilter.h | 2 +- dbcon/execplan/parsetree.h | 581 +- dbcon/execplan/predicateoperator.cpp | 46 +- dbcon/execplan/predicateoperator.h | 47 +- dbcon/execplan/pseudocolumn.cpp | 268 - dbcon/execplan/pseudocolumn.h | 166 - dbcon/execplan/range.cpp | 2 +- dbcon/execplan/range.h | 2 +- dbcon/execplan/returnedcolumn.cpp | 51 +- dbcon/execplan/returnedcolumn.h | 105 +- dbcon/execplan/rowcolumn.cpp | 21 +- dbcon/execplan/rowcolumn.h | 6 +- dbcon/execplan/selectfilter.cpp | 10 +- dbcon/execplan/selectfilter.h | 2 +- dbcon/execplan/sessionmanager.cpp | 6 +- dbcon/execplan/sessionmanager.h | 35 +- dbcon/execplan/sessionmonitor.cpp | 4 +- dbcon/execplan/sessionmonitor.h | 4 +- dbcon/execplan/simplecolumn.cpp | 507 +- dbcon/execplan/simplecolumn.h | 177 +- dbcon/execplan/simplecolumn_decimal.h | 23 +- dbcon/execplan/simplecolumn_int.h | 30 +- dbcon/execplan/simplecolumn_uint.h | 245 - dbcon/execplan/simplefilter.cpp | 396 +- dbcon/execplan/simplefilter.h | 134 +- dbcon/execplan/simplescalarfilter.cpp | 10 +- dbcon/execplan/simplescalarfilter.h | 42 +- dbcon/execplan/tdriver-oid.cpp | 2 +- dbcon/execplan/tdriver-sm.cpp | 4 +- dbcon/execplan/tdriver.cpp | 4 +- dbcon/execplan/treenode.cpp | 32 +- dbcon/execplan/treenode.h | 229 +- dbcon/execplan/treenodeimpl.cpp | 2 +- dbcon/execplan/treenodeimpl.h | 2 +- dbcon/execplan/vendorexecutionplan.cpp | 2 +- dbcon/execplan/vendorexecutionplan.h | 2 +- dbcon/execplan/windowfunctioncolumn.cpp | 572 - dbcon/execplan/windowfunctioncolumn.h | 265 - dbcon/joblist/Makefile.am | 13 +- dbcon/joblist/Makefile.in | 88 +- dbcon/joblist/aggregatefilterstep.cpp | 714 + dbcon/joblist/aggregator.cpp | 230 + dbcon/joblist/aggregator.h | 177 + dbcon/joblist/anydatalist.cpp | 4 +- dbcon/joblist/bandeddl.h | 32 +- dbcon/joblist/batchprimitiveprocessor-jl.cpp | 404 +- dbcon/joblist/batchprimitiveprocessor-jl.h | 100 +- dbcon/joblist/batchprimitivestep.cpp | 2715 +++ dbcon/joblist/bdlwrapper.h | 198 + dbcon/joblist/bpp-jl.h | 6 +- dbcon/joblist/bucketdl.h | 144 +- dbcon/joblist/bucketreuse.cpp | 307 + dbcon/joblist/bucketreuse.h | 231 + dbcon/joblist/bucketreusestep.cpp | 224 + dbcon/joblist/columncommand-jl.cpp | 227 +- dbcon/joblist/columncommand-jl.h | 31 +- dbcon/joblist/command-jl.cpp | 63 +- dbcon/joblist/command-jl.h | 100 +- dbcon/joblist/constantdatalist.h | 120 + dbcon/joblist/crossenginestep.cpp | 381 +- dbcon/joblist/crossenginestep.h | 79 +- dbcon/joblist/datalist.h | 26 +- dbcon/joblist/datalistimpl.h | 44 +- dbcon/joblist/deliverystep.cpp | 688 + dbcon/joblist/deliverywsdl.cpp | 148 + dbcon/joblist/deliverywsdl.h | 146 + dbcon/joblist/dictstep-jl.cpp | 8 +- dbcon/joblist/dictstep-jl.h | 6 +- dbcon/joblist/diskjoinstep.cpp | 547 - dbcon/joblist/diskjoinstep.h | 132 - dbcon/joblist/distributedenginecomm.cpp | 398 +- dbcon/joblist/distributedenginecomm.h | 103 +- dbcon/joblist/elementcompression.h | 12 +- dbcon/joblist/elementtype.cpp | 50 +- dbcon/joblist/elementtype.h | 124 +- dbcon/joblist/errorinfo.h | 53 - dbcon/joblist/expressionstep.cpp | 518 +- dbcon/joblist/expressionstep.h | 98 +- dbcon/joblist/fifo-bench.cpp | 592 + dbcon/joblist/fifo.h | 48 +- dbcon/joblist/filtercommand-jl.cpp | 4 +- dbcon/joblist/filtercommand-jl.h | 4 +- dbcon/joblist/filteroperation.cpp | 304 + dbcon/joblist/filteroperation.h | 93 + dbcon/joblist/filterstep.cpp | 72 +- dbcon/joblist/groupconcat.cpp | 237 +- dbcon/joblist/groupconcat.h | 30 +- dbcon/joblist/hashjoin.cpp | 1895 ++ dbcon/joblist/hashjoin.h | 308 + dbcon/joblist/jl_logger.cpp | 19 +- dbcon/joblist/jl_logger.h | 5 +- dbcon/joblist/jlf_common.cpp | 454 +- dbcon/joblist/jlf_common.h | 217 +- dbcon/joblist/jlf_execplantojoblist.cpp | 1097 +- dbcon/joblist/jlf_execplantojoblist.h | 2 +- dbcon/joblist/jlf_graphics.cpp | 25 +- dbcon/joblist/jlf_graphics.h | 2 +- dbcon/joblist/jlf_subquery.cpp | 180 +- dbcon/joblist/jlf_tuplejoblist.cpp | 1522 +- dbcon/joblist/jlf_tuplejoblist.h | 56 +- dbcon/joblist/joblist.cpp | 367 +- dbcon/joblist/joblist.h | 30 +- dbcon/joblist/joblistfactory.cpp | 394 +- dbcon/joblist/joblistfactory.h | 14 +- dbcon/joblist/joblisttypes.h | 26 +- dbcon/joblist/jobstep.cpp | 249 +- dbcon/joblist/jobstep.h | 353 +- dbcon/joblist/jobstepassociation.cpp | 2 +- dbcon/joblist/largedatalist.h | 76 +- dbcon/joblist/largehashjoin.cpp | 82 +- dbcon/joblist/largehashjoin.h | 38 +- dbcon/joblist/lbidlist.cpp | 379 +- dbcon/joblist/lbidlist.h | 48 +- dbcon/joblist/libjoblist.rc | 102 - dbcon/joblist/libjoblist.vcxproj | 474 - dbcon/joblist/libjoblist.vcxproj.filters | 374 - dbcon/joblist/limitedorderby.cpp | 372 +- dbcon/joblist/limitedorderby.h | 151 +- dbcon/joblist/passthrucommand-jl.cpp | 12 +- dbcon/joblist/passthrucommand-jl.h | 8 +- dbcon/joblist/passthrustep.cpp | 78 +- dbcon/joblist/pcolscan.cpp | 361 +- dbcon/joblist/pcolstep.cpp | 219 +- dbcon/joblist/pdictionary.cpp | 69 +- dbcon/joblist/pdictionaryscan.cpp | 390 +- dbcon/joblist/pidxlist.cpp | 487 + dbcon/joblist/pidxlist.h | 176 + dbcon/joblist/pidxwalk.cpp | 578 + dbcon/joblist/pidxwalk.h | 215 + dbcon/joblist/pnljoin.cpp | 405 + dbcon/joblist/primitivemsg.cpp | 2 +- dbcon/joblist/primitivemsg.h | 60 +- dbcon/joblist/primitivestep.h | 813 +- dbcon/joblist/profiling.cpp | 233 + dbcon/joblist/profiling.h | 134 + dbcon/joblist/pseudocc-jl.cpp | 78 - dbcon/joblist/pseudocc-jl.h | 43 - dbcon/joblist/reducestep.cpp | 783 + dbcon/joblist/resource.h | 14 - dbcon/joblist/resourcedistributor.cpp | 25 +- dbcon/joblist/resourcedistributor.h | 35 +- dbcon/joblist/resourcemanager.cpp | 170 +- dbcon/joblist/resourcemanager.h | 148 +- dbcon/joblist/rowestimator.cpp | 207 +- dbcon/joblist/rowestimator.h | 57 +- dbcon/joblist/rtscommand-jl.cpp | 8 +- dbcon/joblist/rtscommand-jl.h | 6 +- dbcon/joblist/stopwatch.cpp | 211 + dbcon/joblist/subquerystep.cpp | 174 +- dbcon/joblist/subquerystep.h | 184 +- dbcon/joblist/subquerytransformer.cpp | 231 +- dbcon/joblist/subquerytransformer.h | 23 +- dbcon/joblist/swsdl.h | 386 + dbcon/joblist/tableband.cpp | 616 + dbcon/joblist/tableband.h | 163 + dbcon/joblist/tablecolumn.cpp | 44 +- dbcon/joblist/tablecolumn.h | 18 +- dbcon/joblist/tdriver-agg.cpp | 54 +- dbcon/joblist/tdriver-bdl.cpp | 24 +- dbcon/joblist/tdriver-bru.cpp | 2 +- dbcon/joblist/tdriver-datalist.cpp | 50 +- dbcon/joblist/tdriver-dec.cpp | 2 +- dbcon/joblist/tdriver-deliver.cpp | 18 +- dbcon/joblist/tdriver-filter.cpp | 2 +- dbcon/joblist/tdriver-function.cpp | 24 +- dbcon/joblist/tdriver-hashjoin.cpp | 2 +- dbcon/joblist/tdriver-index.cpp | 2 +- dbcon/joblist/tdriver-jobstep.cpp | 2 +- dbcon/joblist/tdriver-pdict.cpp | 6 +- dbcon/joblist/tdriver-tableband.cpp | 559 + dbcon/joblist/tdriver-zdl.cpp | 58 +- dbcon/joblist/tdriver1.cpp | 2 +- dbcon/joblist/tdriver2.cpp | 2 +- dbcon/joblist/threadsafequeue.h | 24 +- dbcon/joblist/timeset.h | 16 +- dbcon/joblist/timestamp.cpp | 15 +- dbcon/joblist/timestamp.h | 10 +- dbcon/joblist/tuple-bps.cpp | 1731 +- dbcon/joblist/tupleaggregatestep.cpp | 1336 +- dbcon/joblist/tupleaggregatestep.h | 114 +- dbcon/joblist/tupleannexstep.cpp | 349 +- dbcon/joblist/tupleannexstep.h | 51 +- dbcon/joblist/tupleconstantstep.cpp | 303 +- dbcon/joblist/tupleconstantstep.h | 87 +- dbcon/joblist/tuplehashjoin.cpp | 1215 +- dbcon/joblist/tuplehashjoin.h | 211 +- dbcon/joblist/tuplehavingstep.cpp | 132 +- dbcon/joblist/tuplehavingstep.h | 14 +- dbcon/joblist/tupleunion.cpp | 541 +- dbcon/joblist/tupleunion.h | 90 +- dbcon/joblist/tuplewsdl.cpp | 413 + dbcon/joblist/tuplewsdl.h | 370 + dbcon/joblist/unionstep.cpp | 853 + dbcon/joblist/unique32generator.cpp | 2 +- dbcon/joblist/unique32generator.h | 2 +- dbcon/joblist/virtualtable.cpp | 43 +- dbcon/joblist/virtualtable.h | 18 +- dbcon/joblist/windowfunctionstep.cpp | 1515 -- dbcon/joblist/windowfunctionstep.h | 222 - dbcon/joblist/wsdl.h | 353 + dbcon/joblist/zdl.h | 1109 + dbcon/mysql/CMakeLists.txt | 155 - dbcon/mysql/Makefile.am | 14 +- dbcon/mysql/Makefile.am.mysql | 194 - dbcon/mysql/Makefile.in | 114 +- dbcon/mysql/calsetuserpriority.sql | 2 +- dbcon/mysql/calshowprocesslist.sql | 2 +- dbcon/mysql/configure.in | 2892 +++ dbcon/mysql/field.h | 2182 ++ dbcon/mysql/ha_autoi.cpp | 6 +- dbcon/mysql/ha_calpont.cpp | 33 +- dbcon/mysql/ha_calpont.h | 24 +- dbcon/mysql/ha_calpont_ddl.cpp | 983 +- dbcon/mysql/ha_calpont_dml.cpp | 964 +- dbcon/mysql/ha_calpont_execplan.cpp | 1801 +- dbcon/mysql/ha_calpont_impl.cpp | 2052 +- dbcon/mysql/ha_calpont_impl.h | 6 +- dbcon/mysql/ha_calpont_impl_if.h | 169 +- dbcon/mysql/ha_calpont_partition.cpp | 614 +- dbcon/mysql/ha_calpont_udf.cpp | 2 +- dbcon/mysql/ha_exists_sub.cpp | 30 +- dbcon/mysql/ha_from_sub.cpp | 253 +- dbcon/mysql/ha_in_sub.cpp | 51 +- dbcon/mysql/ha_pseudocolumn.cpp | 574 - dbcon/mysql/ha_scalar_sub.cpp | 57 +- dbcon/mysql/ha_select_sub.cpp | 22 +- dbcon/mysql/ha_view.cpp | 11 +- dbcon/mysql/ha_view.h | 2 +- dbcon/mysql/ha_window_function.cpp | 438 - dbcon/mysql/handler.cc | 4883 +++++ dbcon/mysql/idb_mysql.h | 19 - dbcon/mysql/include/my_base.h | 571 + dbcon/mysql/include/my_sys.h | 997 + dbcon/mysql/include/mysql_com.h | 522 + dbcon/mysql/install_calpont_mysql.sh | 64 +- dbcon/mysql/item.cc | 7711 +++++++ dbcon/mysql/item.h | 3133 +++ dbcon/mysql/item_cmpfunc.cc | 5344 +++++ dbcon/mysql/item_cmpfunc.h | 1725 ++ dbcon/mysql/item_func.cc | 6194 ++++++ dbcon/mysql/item_func.h | 1722 ++ dbcon/mysql/item_strfunc.cc | 3558 ++++ dbcon/mysql/item_strfunc.h | 850 + dbcon/mysql/item_sum.cc | 3622 ++++ dbcon/mysql/item_sum.h | 1283 ++ dbcon/mysql/item_timefunc.cc | 3420 ++++ dbcon/mysql/item_timefunc.h | 1033 + dbcon/mysql/lex.h | 637 + dbcon/mysql/libcalmysql.rc | 102 - dbcon/mysql/libcalmysql.vcxproj | 401 - dbcon/mysql/libcalmysql.vcxproj.filters | 116 - dbcon/mysql/log.cc | 5713 ++++++ dbcon/mysql/log.h | 589 + dbcon/mysql/my.cnf | 35 +- dbcon/mysql/mysql-Calpont | 21 +- dbcon/mysql/mysql_priv.h | 2562 +++ dbcon/mysql/mysqld.cc | 8958 ++++++++ dbcon/mysql/mysys/my_handler_errors.h | 72 + dbcon/mysql/resource.h | 14 - dbcon/mysql/schemaSync.pl | 42 +- dbcon/mysql/set_var.cc | 4300 ++++ dbcon/mysql/sm.cpp | 460 - dbcon/mysql/sm.h | 279 - dbcon/mysql/sp_head.h | 1341 ++ dbcon/mysql/sql_base.cc | 9098 +++++++++ dbcon/mysql/sql_class.cc | 3886 ++++ dbcon/mysql/sql_class.h | 3152 +++ dbcon/mysql/sql_delete.cc | 1170 ++ dbcon/mysql/sql_insert.cc | 3851 ++++ dbcon/mysql/sql_parse.cc | 8570 ++++++++ dbcon/mysql/sql_prepare.cc | 3631 ++++ dbcon/mysql/sql_select.cc | 16975 ++++++++++++++++ dbcon/mysql/sql_table.cc | 7979 ++++++++ dbcon/mysql/sql_update.cc | 2138 ++ dbcon/mysql/sql_yacc.yy | 13569 ++++++++++++ dbcon/mysql/table.h | 1742 ++ dbcon/sm/Makefile.am | 38 + dbcon/sm/Makefile.in | 533 + dbcon/sm/sm.cpp | 555 + dbcon/sm/sm.h | 328 + dbcon/sm/tdriver.cpp | 22 + ddlproc/DDLProc.rc | 102 - ddlproc/DDLProc.vcxproj | 351 - ddlproc/DDLProc.vcxproj.filters | 41 - ddlproc/Makefile.am | 26 +- ddlproc/Makefile.in | 40 +- ddlproc/ddlproc.cpp | 8 +- ddlproc/ddlprocessor.cpp | 684 +- ddlproc/ddlprocessor.h | 8 +- ddlproc/resource.h | 14 - decomsvr/DecomSvr.rc | 102 - decomsvr/DecomSvr.vcxproj | 290 - decomsvr/DecomSvr.vcxproj.filters | 35 - decomsvr/Makefile.am | 19 +- decomsvr/Makefile.in | 33 +- decomsvr/resource.h | 14 - decomsvr/server.cpp | 137 +- dmlib/Makefile.am | 37 + dmlib/dm.c | 256 + dmlib/dm.h | 101 + dmlib/tdriver.c | 280 + dmlproc/DMLProc.rc | 102 - dmlproc/DMLProc.vcxproj | 370 - dmlproc/DMLProc.vcxproj.filters | 53 - dmlproc/Makefile.am | 26 +- dmlproc/Makefile.in | 40 +- dmlproc/batchinsertprocessor.cpp | 910 +- dmlproc/batchinsertprocessor.h | 171 +- dmlproc/dmlproc.cpp | 154 +- dmlproc/dmlproc.h | 2 +- dmlproc/dmlprocessor.cpp | 917 +- dmlproc/dmlprocessor.h | 33 +- dmlproc/dmlresultbuffer.cpp | 2 +- dmlproc/dmlresultbuffer.h | 2 +- dmlproc/resource.h | 14 - exemgr/ExeMgr.rc | 102 - exemgr/ExeMgr.vcxproj | 357 - exemgr/ExeMgr.vcxproj.filters | 44 - exemgr/Makefile.am | 28 +- exemgr/Makefile.in | 47 +- exemgr/activestatementcounter.cpp | 46 +- exemgr/activestatementcounter.h | 13 +- exemgr/main.cpp | 634 +- exemgr/procstat.cpp | 128 + exemgr/procstat.h | 64 + exemgr/resource.h | 14 - m4/compilerflags.m4 | 15 - make_rpms | 140 + net-snmp/Makefile.am | 2 +- net-snmp/Makefile.in | 361 - net-snmp/net-snmp-5.2.1.2/CalpontConfigure.sh | 56 +- .../agent/helpers/row_merge.c | 5 +- .../agent/mibgroup/agent/nsDebug.c | 7 +- .../if-mib/data_access/interface_common.c | 4 +- .../mibgroup/tcp-mib/data_access/Makefile | 26 - net-snmp/net-snmp-5.2.1.2/dist/Makefile | 133 - .../include/net-snmp/library/snmp_logging.h | 2 +- net-snmp/net-snmp-5.2.1.2/snmplib/md5.c | 4 - .../net-snmp-5.2.1.2/snmplib/snmp_logging.c | 8 +- oam/Makefile.am | 28 +- oam/Makefile.in | 42 +- oam/cloud/IDBInstanceCmds.sh | 228 +- oam/cloud/Makefile.am | 29 - oam/cloud/Makefile.in | 400 - oam/etc/AlarmConfig.xml | 19 +- oam/etc/Calpont.xml | 450 +- oam/etc/Calpont.xml.singleserver | 47 +- oam/etc/ConsoleCmds.xml | 54 +- oam/etc/Makefile.am | 26 +- oam/etc/Makefile.in | 40 +- oam/etc/ProcessConfig.xml | 16 +- oam/etc/ProcessConfig.xml.singleserver | 38 +- oam/install_scripts/Makefile.am | 43 +- oam/install_scripts/Makefile.in | 55 +- oam/install_scripts/binary_installer.sh | 215 +- oam/install_scripts/calpontAlias | 15 +- oam/install_scripts/calpontInstall.sh | 66 +- oam/install_scripts/calpontLogRotate | 8 +- oam/install_scripts/calpontSyslog | 12 +- oam/install_scripts/calpontUninstall.sh | 28 +- oam/install_scripts/dbhealth.sh | 45 + oam/install_scripts/dbhealth.sql | 18 + oam/install_scripts/director_installer.sh | 334 +- oam/install_scripts/displayJobGraph.sh | 48 + oam/install_scripts/infinidb | 436 +- oam/install_scripts/infinidb.def | 5 +- oam/install_scripts/install-infinidb.sh | 311 +- oam/install_scripts/master-rep-infinidb.sh | 109 - oam/install_scripts/module_installer.sh | 58 +- oam/install_scripts/myCnf-exclude-args.text | 2 - oam/install_scripts/myCnf-include-args.text | 6 - oam/install_scripts/patch_installer.sh | 4 +- oam/install_scripts/performance_installer.sh | 384 +- oam/install_scripts/post-install | 335 +- oam/install_scripts/post-mysql-install | 57 +- oam/install_scripts/post-mysqld-install | 69 +- oam/install_scripts/postInstall.sh | 14 +- oam/install_scripts/pre-uninstall | 25 +- oam/install_scripts/remote_command.sh | 53 +- oam/install_scripts/remote_command_verify.sh | 53 - oam/install_scripts/remote_installer.sh | 16 +- oam/install_scripts/remote_scp_get.sh | 34 +- oam/install_scripts/remote_scp_put.sh | 10 +- oam/install_scripts/rsync.sh | 19 +- oam/install_scripts/slave-rep-infinidb.sh | 124 - oam/install_scripts/startupTests.sh | 2 +- oam/install_scripts/syslogSetup.sh | 22 +- oam/install_scripts/system_installer.sh | 108 +- oam/install_scripts/user_installer.sh | 563 +- oam/install_scripts/xm_installer.sh | 26 +- oam/oamcpp/COPYING | 340 - oam/oamcpp/Makefile.am | 28 +- oam/oamcpp/Makefile.in | 44 +- oam/oamcpp/liboamcpp.cpp | 860 +- oam/oamcpp/liboamcpp.h | 405 +- oam/oamcpp/liboamcpp.rc | 102 - oam/oamcpp/liboamcpp.vcxproj | 246 - oam/oamcpp/liboamcpp.vcxproj.filters | 48 - oam/oamcpp/oamcache.cpp | 107 +- oam/oamcpp/oamcache.h | 10 +- oam/oamcpp/resource.h | 14 - oam/post/Makefile.am | 26 +- oam/post/Makefile.in | 40 +- oam/post/functions | 2 +- oam/post/test-001.sh | 17 +- oam/post/test-002.sh | 2 +- oam/post/test-003.sh | 2 +- oam/post/test-004.sh | 2 +- oam/replaytxnlog/Makefile.am | 26 +- oam/replaytxnlog/Makefile.in | 542 + oam/replaytxnlog/replaytxnlog.cpp | 6 +- oamapps/Makefile.am | 29 +- oamapps/Makefile.in | 44 +- oamapps/calpont-console/Makefile.am | 22 + .../calpontConsole.cpp | 2441 +-- .../calpontConsole.h | 21 +- oamapps/calpont-console/tdriver.cpp | 312 + oamapps/calpontConsole/Makefile.am | 39 - oamapps/calpontConsole/Makefile.in | 529 - oamapps/calpontConsole/tdriver.cpp | 329 - oamapps/calpontDB/Makefile.am | 17 - oamapps/calpontDB/Makefile.in | 529 - oamapps/calpontDB/calpontDB.cpp | 17 - oamapps/calpontSupport/Makefile.am | 48 - oamapps/calpontSupport/Makefile.in | 564 - oamapps/calpontSupport/alarmReport.sh | 36 - oamapps/calpontSupport/analytics/create.sql | 26 - oamapps/calpontSupport/analytics/track.sh | 37 - oamapps/calpontSupport/approximateRowCount.sh | 62 - oamapps/calpontSupport/bulklogReport.sh | 38 - oamapps/calpontSupport/calpontSupport.bat | 227 - oamapps/calpontSupport/calpontSupport.cpp | 1024 - oamapps/calpontSupport/configReport.sh | 64 - oamapps/calpontSupport/findStranded.sh | 40 - oamapps/calpontSupport/getMinMax.sh | 132 - oamapps/calpontSupport/hadoopReport.sh | 69 - oamapps/calpontSupport/hardwareReport.sh | 101 - oamapps/calpontSupport/logReport.sh | 27 - oamapps/calpontSupport/minMaxCheck.sh | 170 - oamapps/calpontSupport/resourceReport.sh | 74 - oamapps/calpontSupport/softwareReport.sh | 53 - oamapps/calpontSupport/sqlLogs.sh | 225 - oamapps/hardwareMonitor/hardwareMonitor.cpp | 17 - oamapps/hardwareMonitor/hardwareMonitor.h | 17 - oamapps/logUtils/Makefile.am | 12 + oamapps/logUtils/dbprof.pl | 2066 ++ oamapps/postConfigure/Makefile.am | 25 +- oamapps/postConfigure/Makefile.in | 680 - oamapps/postConfigure/amazonConfig-1pm.xml | 107 - oamapps/postConfigure/amazonConfig.xml | 38 +- oamapps/postConfigure/amazonInstaller.cpp | 726 +- oamapps/postConfigure/helpers.cpp | 435 +- oamapps/postConfigure/helpers.h | 41 +- oamapps/postConfigure/installer.cpp | 178 +- oamapps/postConfigure/mycnfUpgrade.cpp | 160 - oamapps/postConfigure/patchInstaller.cpp | 17 - oamapps/postConfigure/postConfigure.cpp | 1897 +- oamapps/replayTransactionLog/Makefile.am | 26 +- oamapps/replayTransactionLog/Makefile.in | 520 + oamapps/replayTransactionLog/tdriver.cpp | 18 +- oamapps/resourceMonitor/hardwareMonitor.cpp | 17 - oamapps/resourceMonitor/resourceMonitor.cpp | 19 +- oamapps/resourceMonitor/tdriver.cpp | 19 +- oamapps/sendtrap/Makefile.am | 39 - oamapps/sendtrap/Makefile.in | 529 - oamapps/sendtrap/sendtrap.cpp | 24 +- oamapps/serverMonitor/Makefile.am | 17 - oamapps/serverMonitor/Makefile.in | 660 - oamapps/serverMonitor/UMAutoSync.cpp | 19 +- oamapps/serverMonitor/cpuMonitor.cpp | 26 +- oamapps/serverMonitor/dbhealthMonitor.cpp | 17 - oamapps/serverMonitor/diskMonitor.cpp | 23 +- oamapps/serverMonitor/hardwareMonitor.cpp | 17 - oamapps/serverMonitor/main.cpp | 142 +- oamapps/serverMonitor/memoryMonitor.cpp | 133 +- oamapps/serverMonitor/msgProcessor.cpp | 43 +- oamapps/serverMonitor/procmonMonitor.cpp | 17 - oamapps/serverMonitor/serverMonitor.cpp | 17 - oamapps/serverMonitor/serverMonitor.h | 17 - oamapps/sessionWalker/Makefile.am | 17 - oamapps/sessionWalker/Makefile.in | 529 - oamapps/sessionWalker/sessionwalker.cpp | 19 +- oamapps/sessionWalker/tdriver.cpp | 21 +- oamapps/traphandler/Makefile.am | 17 - oamapps/traphandler/Makefile.in | 529 - oamapps/traphandler/tdriver.cpp | 19 +- oamapps/traphandler/trapHandler.cpp | 821 +- primitives/Makefile.am | 26 +- primitives/Makefile.in | 40 +- primitives/blockcache/Makefile.am | 26 +- primitives/blockcache/Makefile.in | 40 +- primitives/blockcache/bcTest.cpp | 30 +- primitives/blockcache/blockcacheclient.cpp | 2 +- primitives/blockcache/blockcacheclient.h | 16 +- .../blockcache/blockrequestprocessor.cpp | 130 +- primitives/blockcache/blockrequestprocessor.h | 17 +- .../blockcache/fileblockrequestqueue.cpp | 2 +- primitives/blockcache/fileblockrequestqueue.h | 6 +- primitives/blockcache/filebuffer.cpp | 6 +- primitives/blockcache/filebuffer.h | 10 +- primitives/blockcache/filebuffermgr.cpp | 26 +- primitives/blockcache/filebuffermgr.h | 10 +- primitives/blockcache/filerequest.cpp | 6 +- primitives/blockcache/filerequest.h | 10 +- primitives/blockcache/iomanager.cpp | 766 +- primitives/blockcache/iomanager.h | 9 +- primitives/blockcache/stats.cpp | 4 +- primitives/blockcache/stats.h | 2 +- primitives/blockcache/tdriver.cpp | 22 +- primitives/linux-port/Makefile.am | 27 +- primitives/linux-port/Makefile.in | 58 +- primitives/linux-port/column.cpp | 1286 +- primitives/linux-port/dictionary.cpp | 45 +- primitives/linux-port/index.cpp | 25 +- primitives/linux-port/primitiveprocessor.cpp | 6 +- primitives/linux-port/primitiveprocessor.h | 88 +- primitives/linux-port/print_dictblock.cpp | 8 +- primitives/linux-port/tdriver.cpp | 894 +- primitives/primproc/Makefile.am | 31 +- primitives/primproc/Makefile.in | 97 +- primitives/primproc/PrimProc.rc | 102 - primitives/primproc/PrimProc.vcxproj | 447 - primitives/primproc/PrimProc.vcxproj.filters | 182 - .../primproc/batchprimitiveprocessor.cpp | 1410 +- primitives/primproc/batchprimitiveprocessor.h | 111 +- primitives/primproc/bpp.h | 6 +- primitives/primproc/bppseeder.cpp | 71 +- primitives/primproc/bppseeder.h | 15 +- primitives/primproc/bppsendthread.cpp | 58 +- primitives/primproc/bppsendthread.h | 16 +- primitives/primproc/columncommand.cpp | 608 +- primitives/primproc/columncommand.h | 36 +- primitives/primproc/command.cpp | 43 +- primitives/primproc/command.h | 155 +- primitives/primproc/dictstep.cpp | 206 +- primitives/primproc/dictstep.h | 23 +- primitives/primproc/filtercommand.cpp | 115 +- primitives/primproc/filtercommand.h | 4 +- primitives/primproc/logger.cpp | 2 +- primitives/primproc/monitorprocmem.cpp | 283 + primitives/primproc/monitorprocmem.h | 118 + primitives/primproc/passthrucommand.cpp | 17 +- primitives/primproc/passthrucommand.h | 6 +- primitives/primproc/primitiveserver.cpp | 2555 +-- primitives/primproc/primitiveserver.h | 116 +- primitives/primproc/primproc.cpp | 261 +- primitives/primproc/primproc.h | 6 +- primitives/primproc/pseudocc.cpp | 215 - primitives/primproc/pseudocc.h | 127 - primitives/primproc/resource.h | 14 - primitives/primproc/rowaggregation.cpp | 1 + primitives/primproc/rowaggregation.h | 1 + primitives/primproc/rowgroup.cpp | 1 + primitives/primproc/rowgroup.h | 1 + primitives/primproc/rtscommand.cpp | 22 +- primitives/primproc/rtscommand.h | 6 +- primitives/primproc/tdriver.cpp | 2 +- primitives/primproc/udf.cpp | 2 +- primitives/primproc/umsocketselector.h | 2 +- primitives/udf/Makefile.sdk | 35 + primitives/udf/caludf.cpp | 77 + primitives/udf/caludf.h | 29 + procmgr/Makefile.am | 19 +- procmgr/Makefile.in | 545 - procmgr/main.cpp | 385 +- procmgr/processmanager.cpp | 1781 +- procmgr/processmanager.h | 34 +- procmon/Makefile.am | 17 - procmon/Makefile.in | 545 - procmon/main.cpp | 311 +- procmon/processmonitor.cpp | 1213 +- procmon/processmonitor.h | 44 +- rules.mak | 17 +- snmpd/Makefile.am | 26 +- snmpd/Makefile.in | 40 +- snmpd/etc/Makefile.am | 26 +- snmpd/etc/Makefile.in | 40 +- snmpd/snmpmanager/Makefile.am | 26 +- snmpd/snmpmanager/Makefile.in | 40 +- snmpd/snmpmanager/alarm.h | 2 +- snmpd/snmpmanager/snmpglobal.h | 9 +- snmpd/snmpmanager/snmpmanager.h | 6 + tools/Makefile.am | 29 +- tools/Makefile.in | 43 +- tools/bincvt/li2bin.cpp | 239 - tools/brmtest/Makefile.am | 23 - tools/brmtest/brmtest.cpp | 645 - tools/brmtest/locks.cpp | 80 - tools/cfread/Makefile.am | 25 - tools/cfread/cfread.cpp | 176 - tools/cfread/mtread.cpp | 269 - tools/clearShm/Makefile.am | 26 +- tools/clearShm/Makefile.in | 40 +- tools/clearShm/clearShm.vcxproj | 256 - tools/clearShm/clearShm.vcxproj.filters | 22 - tools/clearShm/main.cpp | 2 +- tools/cleartablelock/Makefile.am | 30 +- tools/cleartablelock/Makefile.in | 44 +- tools/cleartablelock/cleartablelock.cpp | 25 +- tools/cleartablelock/cleartablelock.vcxproj | 316 - .../cleartablelock.vcxproj.filters | 30 - tools/cleartablelock/cleartablelockthread.cpp | 2 +- tools/cleartablelock/cleartablelockthread.h | 2 +- tools/configMgt/CalpontSystems.xml | 137 - tools/configMgt/Makefile.am | 48 - tools/configMgt/Makefile.in | 580 - tools/configMgt/README | 43 - tools/configMgt/autoBuilder | 119 - tools/configMgt/autoConfigure.cpp | 1811 -- tools/configMgt/autoInstaller.cpp | 903 - tools/configMgt/autoPackager | 109 - tools/configMgt/autoReleaseNotes.sh | 81 - tools/configMgt/autoReleaseNotes_branch.sh | 90 - tools/configMgt/beetlejuice_installer.sh | 219 - .../configMgt/beetlejuice_installer_3rpms.sh | 259 - tools/configMgt/buildCalpontPackages.sh | 48 - tools/configMgt/buildDatdupPackages.sh | 47 - tools/configMgt/buildTester.sh | 475 - tools/configMgt/calpont-build | 102 - tools/configMgt/configure.cpp | 1541 -- tools/configMgt/datdup-build | 44 - tools/configMgt/dm_parent_installer.sh | 197 - tools/configMgt/dm_parent_installer_v3.sh | 191 - tools/configMgt/mysql-build-branch | 8 - tools/configMgt/mysql-build-genii | 8 - tools/configMgt/parent_binary_installer.sh | 213 - tools/configMgt/parent_binary_installer_v3.sh | 212 - tools/configMgt/parent_installer.sh | 365 - tools/configMgt/pm_parent_installer.sh | 184 - tools/configMgt/pm_parent_installer_v3.sh | 179 - tools/configMgt/recreateBranch.sh | 53 - tools/configMgt/remote_command.sh | 52 - tools/configMgt/remote_command_test.sh | 47 - tools/configMgt/remote_scp_get.sh | 38 - tools/configMgt/rpm_txt.sh | 32 - tools/configMgt/stackReleaseChecker.cpp | 176 - tools/configMgt/svnQuery.cpp | 195 - tools/cplogger/Makefile.am | 30 +- tools/cplogger/Makefile.in | 44 +- tools/cplogger/cplogger.vcxproj | 257 - tools/cplogger/cplogger.vcxproj.filters | 22 - tools/cplogger/main.cpp | 9 +- tools/dbbuilder/Makefile.am | 26 +- tools/dbbuilder/Makefile.in | 40 +- tools/dbbuilder/dbbuilder.cpp | 47 +- tools/dbbuilder/dbbuilder.h | 3 +- tools/dbbuilder/dbbuilder.vcxproj | 320 - tools/dbbuilder/dbbuilder.vcxproj.filters | 33 - tools/dbbuilder/systemcatalog.cpp | 147 +- tools/dbbuilder/systemcatalog.h | 2 +- tools/dbbuilder/tpchpopulate.cpp | 2 +- tools/dbbuilder/tpchpopulate.h | 2 +- tools/dbbuilder/tpchschema.cpp | 2 +- tools/dbbuilder/tpchschema.h | 2 +- tools/dbloadxml/Makefile.am | 26 +- tools/dbloadxml/Makefile.in | 40 +- tools/dbloadxml/colxml.cpp | 60 +- tools/dbloadxml/colxml.rc | 102 - tools/dbloadxml/colxml.vcxproj | 337 - tools/dbloadxml/colxml.vcxproj.filters | 38 - tools/dbloadxml/inputmgr.cpp | 26 +- tools/dbloadxml/inputmgr.h | 2 +- tools/dbloadxml/resource.h | 14 - tools/ddlcleanup/Makefile.am | 26 +- tools/ddlcleanup/Makefile.in | 40 +- tools/ddlcleanup/ddlcleanup.vcxproj | 324 - tools/ddlcleanup/ddlcleanup.vcxproj.filters | 22 - tools/ddldriver/Makefile.am | 39 - tools/ddldriver/ddldriver.cpp | 133 - tools/dmldriver/Makefile.am | 39 - tools/dmldriver/dmldriver.cpp | 198 - tools/dmldriver/dmlif.cpp | 333 - tools/dmldriver/dmlif.h | 70 - tools/dmldriver/tpchrf2.cpp | 78 - tools/dmldriver/tpchrf2.h | 56 - tools/editem/Makefile.am | 26 +- tools/editem/Makefile.in | 40 +- tools/editem/editem.cpp | 187 +- tools/editem/editem.vcxproj | 312 - tools/editem/editem.vcxproj.filters | 22 - tools/evalidx/Makefile.am | 25 - tools/evalidx/checkidx.py | 98 - tools/evalidx/evalidx.cpp | 355 - tools/fixdate/fixdate.cpp | 167 - tools/getConfig/Makefile.am | 30 +- tools/getConfig/Makefile.in | 44 +- tools/getConfig/getConfig.vcxproj | 251 - tools/getConfig/getConfig.vcxproj.filters | 22 - tools/getConfig/main.cpp | 89 +- tools/hdfsCheck/hdfsCheck.cpp | 774 - tools/idb_comp/main.cpp | 255 - tools/idbmeminfo/Makefile.am | 26 +- tools/idbmeminfo/Makefile.in | 40 +- tools/idbmeminfo/idbmeminfo.cpp | 6 + tools/notificationTester/client.cpp | 21 - tools/notificationTester/main.cpp | 289 - tools/pingproc/pingproc.cpp | 2160 -- tools/qfe/Makefile.am | 51 - tools/qfe/bison-win.cpp | 2071 -- tools/qfe/bison-win.h | 85 - tools/qfe/cli.cpp | 172 - tools/qfe/cseputils.cpp | 149 - tools/qfe/cseputils.h | 46 - tools/qfe/ddlstmts.cpp | 80 - tools/qfe/ddlstmts.h | 14 - tools/qfe/lex-win.cpp | 1760 -- tools/qfe/parsequery.cpp | 93 - tools/qfe/parsequery.h | 16 - tools/qfe/qfe-cli.py | 51 - tools/qfe/qfelexer.lpp | 65 - tools/qfe/qfeparser.ypp | 306 - tools/qfe/returnedrows.cpp | 97 - tools/qfe/returnedrows.h | 15 - tools/qfe/scanner.bat | 6 - tools/qfe/sendcsep.cpp | 55 - tools/qfe/sendcsep.h | 17 - tools/qfe/server.cpp | 462 - tools/qfe/socketio.cpp | 202 - tools/qfe/socketio.h | 36 - tools/qfe/socktype.h | 21 - tools/rebuildEM/main.cpp | 313 - tools/reserveStacks/create.sql | 73 - tools/reserveStacks/index.html | 38 - tools/reserveStacks/procs.sql | 184 - tools/reserveStacks/results.php | 21 - tools/reserveStacks/stack | 82 - tools/reserveStacks/stack.php | 106 - .../reserveStacks/stackReservationResult.php | 45 - tools/sendPlan/Makefile.am | 22 - tools/sendPlan/sendplan.cpp | 378 - tools/setConfig/Makefile.am | 26 +- tools/setConfig/Makefile.in | 40 +- tools/setConfig/configxml.sh | 70 +- tools/setConfig/setConfig.vcxproj | 314 - tools/setConfig/setConfig.vcxproj.filters | 22 - tools/snconvert/snconvert.pl | 132 - tools/updateGenii/listRepos.pl | 58 - tools/updateGenii/test.dat | 14 - tools/updateGenii/updateGenii.pl | 186 - tools/valprint/valprint.cpp | 48 - tools/vbgen/Makefile.am | 39 - tools/vbgen/myrand.cpp | 27 - tools/vbgen/myrand.h | 34 - tools/vbgen/vbgen.cpp | 72 - tools/viewtablelock/Makefile.am | 26 +- tools/viewtablelock/Makefile.in | 40 +- tools/viewtablelock/viewtablelock.cpp | 2 +- tools/viewtablelock/viewtablelock.vcxproj | 312 - .../viewtablelock.vcxproj.filters | 22 - utils/Makefile.am | 38 +- utils/Makefile.in | 49 +- utils/autoconf/INSTALL | 45 +- utils/autoconf/Makefile.am | 43 +- utils/autoconf/README | 153 +- utils/autoconf/build_mysql.sh | 59 + utils/autoconf/configure.ac | 107 +- utils/autoconf/m4/compilerflags.m4 | 15 - utils/autoconf/make_rpms | 140 + utils/batchloader/Makefile.am | 26 +- utils/batchloader/Makefile.in | 40 +- utils/batchloader/batchloader.cpp | 189 +- utils/batchloader/batchloader.h | 58 +- utils/batchloader/libbatchloader.vcxproj | 209 - .../libbatchloader.vcxproj.filters | 27 - utils/boost_idb/Makefile.am | 2832 ++- utils/boost_idb/Makefile.in | 2922 ++- utils/boost_idb/README | 10 +- utils/boost_idb/boost/algorithm/clamp.hpp | 175 - .../boost/algorithm/cxx11/all_of.hpp | 91 - .../boost/algorithm/cxx11/any_of.hpp | 90 - .../boost/algorithm/cxx11/copy_if.hpp | 136 - .../boost/algorithm/cxx11/copy_n.hpp | 44 - .../boost/algorithm/cxx11/find_if_not.hpp | 60 - .../boost_idb/boost/algorithm/cxx11/iota.hpp | 74 - .../boost/algorithm/cxx11/is_partitioned.hpp | 65 - .../boost/algorithm/cxx11/is_permutation.hpp | 248 - .../boost/algorithm/cxx11/is_sorted.hpp | 287 - .../boost/algorithm/cxx11/none_of.hpp | 88 - .../boost/algorithm/cxx11/one_of.hpp | 82 - .../boost/algorithm/cxx11/partition_copy.hpp | 78 - .../boost/algorithm/cxx11/partition_point.hpp | 72 - .../boost_idb/boost/algorithm/cxx14/equal.hpp | 97 - .../boost/algorithm/cxx14/is_permutation.hpp | 130 - .../boost/algorithm/cxx14/mismatch.hpp | 65 - utils/boost_idb/boost/algorithm/gather.hpp | 123 - utils/boost_idb/boost/algorithm/hex.hpp | 261 - .../boost/algorithm/minmax_element.hpp | 6 +- .../boost/algorithm/searching/boyer_moore.hpp | 268 - .../searching/boyer_moore_horspool.hpp | 199 - .../algorithm/searching/detail/bm_traits.hpp | 105 - .../algorithm/searching/detail/debugging.hpp | 30 - .../searching/knuth_morris_pratt.hpp | 258 - .../boost/algorithm/string/concept.hpp | 2 +- .../algorithm/string/detail/case_conv.hpp | 6 +- .../string/detail/classification.hpp | 4 +- .../algorithm/string/detail/find_format.hpp | 52 +- .../string/detail/find_format_all.hpp | 58 +- .../string/detail/find_format_store.hpp | 4 +- .../algorithm/string/detail/find_iterator.hpp | 2 +- .../boost/algorithm/string/detail/finder.hpp | 9 +- .../algorithm/string/detail/finder_regex.hpp | 6 +- .../algorithm/string/detail/formatter.hpp | 27 +- .../boost/algorithm/string/detail/util.hpp | 2 +- .../boost/algorithm/string/erase.hpp | 2 +- .../boost_idb/boost/algorithm/string/find.hpp | 14 +- .../boost/algorithm/string/find_format.hpp | 2 +- .../boost/algorithm/string/find_iterator.hpp | 14 +- .../boost/algorithm/string/finder.hpp | 2 +- .../boost/algorithm/string/formatter.hpp | 27 +- .../boost/algorithm/string/iter_find.hpp | 8 +- .../boost/algorithm/string/predicate.hpp | 2 +- .../algorithm/string/predicate_facade.hpp | 2 +- .../boost/algorithm/string/regex.hpp | 2 +- .../algorithm/string/regex_find_format.hpp | 2 +- .../boost/algorithm/string/replace.hpp | 2 +- .../boost_idb/boost/algorithm/string/trim.hpp | 14 +- .../boost/algorithm/string/trim_all.hpp | 217 - .../boost/algorithm/string_regex.hpp | 2 +- utils/boost_idb/boost/aligned_storage.hpp | 181 + utils/boost_idb/boost/any.hpp | 144 +- utils/boost_idb/boost/array.hpp | 84 +- utils/boost_idb/boost/asio.hpp | 100 + utils/boost_idb/boost/assert.hpp | 109 +- utils/boost_idb/boost/atomic.hpp | 18 - utils/boost_idb/boost/atomic/atomic.hpp | 232 - utils/boost_idb/boost/atomic/detail/base.hpp | 605 - .../boost/atomic/detail/cas128strong.hpp | 286 - .../boost/atomic/detail/cas32strong.hpp | 939 - .../boost/atomic/detail/cas32weak.hpp | 1017 - .../boost/atomic/detail/cas64strong-ptr.hpp | 247 - .../boost/atomic/detail/cas64strong.hpp | 264 - .../boost_idb/boost/atomic/detail/config.hpp | 16 - .../boost/atomic/detail/gcc-alpha.hpp | 368 - .../boost/atomic/detail/gcc-armv6plus.hpp | 255 - .../boost/atomic/detail/gcc-atomic.hpp | 1204 -- .../boost_idb/boost/atomic/detail/gcc-cas.hpp | 160 - .../boost_idb/boost/atomic/detail/gcc-ppc.hpp | 2952 --- .../boost/atomic/detail/gcc-sparcv9.hpp | 1333 -- .../boost_idb/boost/atomic/detail/gcc-x86.hpp | 2017 -- .../boost/atomic/detail/generic-cas.hpp | 206 - .../boost/atomic/detail/interlocked.hpp | 203 - utils/boost_idb/boost/atomic/detail/link.hpp | 50 - .../boost/atomic/detail/linux-arm.hpp | 190 - .../boost/atomic/detail/lockpool.hpp | 91 - .../boost/atomic/detail/platform.hpp | 71 - .../atomic/detail/type-classification.hpp | 45 - .../boost_idb/boost/atomic/detail/windows.hpp | 1669 -- utils/boost_idb/boost/bimap.hpp | 19 + utils/boost_idb/boost/bind/bind.hpp | 2 +- utils/boost_idb/boost/blank.hpp | 106 + utils/boost_idb/boost/blank_fwd.hpp | 22 + utils/boost_idb/boost/cast.hpp | 107 + utils/boost_idb/boost/chrono.hpp | 20 - utils/boost_idb/boost/chrono/ceil.hpp | 36 - utils/boost_idb/boost/chrono/chrono.hpp | 15 - utils/boost_idb/boost/chrono/chrono_io.hpp | 34 - utils/boost_idb/boost/chrono/clock_string.hpp | 25 - utils/boost_idb/boost/chrono/config.hpp | 220 - .../boost/chrono/detail/inlined/chrono.hpp | 44 - .../chrono/detail/inlined/mac/chrono.hpp | 241 - .../detail/inlined/mac/process_cpu_clocks.hpp | 331 - .../detail/inlined/mac/thread_clock.hpp | 15 - .../chrono/detail/inlined/posix/chrono.hpp | 120 - .../inlined/posix/process_cpu_clocks.hpp | 353 - .../detail/inlined/posix/thread_clock.hpp | 91 - .../detail/inlined/process_cpu_clocks.hpp | 45 - .../chrono/detail/inlined/thread_clock.hpp | 44 - .../chrono/detail/inlined/win/chrono.hpp | 139 - .../detail/inlined/win/process_cpu_clocks.hpp | 276 - .../detail/inlined/win/thread_clock.hpp | 102 - .../chrono/detail/is_evenly_divisible_by.hpp | 31 - .../detail/no_warning/signed_unsigned_cmp.hpp | 54 - .../boost/chrono/detail/scan_keyword.hpp | 163 - .../boost/chrono/detail/static_assert.hpp | 30 - .../boost_idb/boost/chrono/detail/system.hpp | 29 - utils/boost_idb/boost/chrono/duration.hpp | 794 - utils/boost_idb/boost/chrono/floor.hpp | 34 - utils/boost_idb/boost/chrono/include.hpp | 23 - .../boost/chrono/io/duration_get.hpp | 547 - .../boost_idb/boost/chrono/io/duration_io.hpp | 225 - .../boost/chrono/io/duration_put.hpp | 264 - .../boost/chrono/io/duration_style.hpp | 35 - .../boost/chrono/io/duration_units.hpp | 1003 - .../boost/chrono/io/ios_base_state.hpp | 151 - .../boost/chrono/io/time_point_get.hpp | 330 - .../boost/chrono/io/time_point_io.hpp | 1231 -- .../boost/chrono/io/time_point_put.hpp | 261 - .../boost/chrono/io/time_point_units.hpp | 244 - utils/boost_idb/boost/chrono/io/timezone.hpp | 30 - .../chrono/io/utility/ios_base_state_ptr.hpp | 435 - .../boost/chrono/io/utility/manip_base.hpp | 101 - .../boost/chrono/io/utility/to_string.hpp | 50 - .../boost/chrono/io_v1/chrono_io.hpp | 637 - .../boost/chrono/process_cpu_clocks.hpp | 510 - utils/boost_idb/boost/chrono/round.hpp | 55 - .../boost_idb/boost/chrono/system_clocks.hpp | 233 - utils/boost_idb/boost/chrono/thread_clock.hpp | 75 - utils/boost_idb/boost/chrono/time_point.hpp | 380 - .../chrono/typeof/boost/chrono/chrono.hpp | 32 - .../boost/chrono/typeof/boost/ratio.hpp | 24 - utils/boost_idb/boost/circular_buffer.hpp | 74 + utils/boost_idb/boost/circular_buffer_fwd.hpp | 43 + .../concept/detail/backward_compatibility.hpp | 2 +- utils/boost_idb/boost/concept_check.hpp | 176 +- .../boost_idb/boost/concept_check/borland.hpp | 25 - .../boost_idb/boost/concept_check/general.hpp | 82 - .../boost/concept_check/has_constraints.hpp | 31 - utils/boost_idb/boost/concept_check/msvc.hpp | 90 - utils/boost_idb/boost/config.hpp | 19 +- utils/boost_idb/boost/config/auto_link.hpp | 115 +- .../boost/config/compiler/borland.hpp | 70 +- .../boost_idb/boost/config/compiler/clang.hpp | 189 +- .../boost/config/compiler/codegear.hpp | 52 +- .../boost/config/compiler/common_edg.hpp | 81 +- .../boost_idb/boost/config/compiler/cray.hpp | 65 - .../boost/config/compiler/digitalmars.hpp | 73 +- utils/boost_idb/boost/config/compiler/gcc.hpp | 222 +- .../boost/config/compiler/gcc_xml.hpp | 60 +- .../boost/config/compiler/hp_acc.hpp | 73 +- .../boost_idb/boost/config/compiler/intel.hpp | 153 +- .../boost/config/compiler/metrowerks.hpp | 72 +- utils/boost_idb/boost/config/compiler/mpw.hpp | 62 +- .../boost_idb/boost/config/compiler/nvcc.hpp | 71 + .../boost/config/compiler/pathscale.hpp | 83 - utils/boost_idb/boost/config/compiler/pgi.hpp | 109 +- .../boost/config/compiler/sunpro_cc.hpp | 74 +- .../boost_idb/boost/config/compiler/vacpp.hpp | 112 +- .../boost/config/compiler/visualc.hpp | 266 +- .../boost_idb/boost/config/platform/cray.hpp | 18 - .../boost/config/platform/cygwin.hpp | 3 - .../boost_idb/boost/config/platform/linux.hpp | 5 - .../boost_idb/boost/config/platform/macos.hpp | 9 +- .../boost/config/platform/symbian.hpp | 7 +- .../boost/config/platform/vxworks.hpp | 368 +- .../boost_idb/boost/config/platform/win32.hpp | 12 +- .../boost/config/select_compiler_config.hpp | 49 +- .../boost/config/select_platform_config.hpp | 6 +- .../boost/config/select_stdlib_config.hpp | 10 +- .../boost/config/stdlib/dinkumware.hpp | 64 +- .../boost_idb/boost/config/stdlib/libcomo.hpp | 47 +- .../boost_idb/boost/config/stdlib/libcpp.hpp | 37 - .../boost/config/stdlib/libstdcpp3.hpp | 86 +- .../boost_idb/boost/config/stdlib/modena.hpp | 47 +- utils/boost_idb/boost/config/stdlib/msl.hpp | 47 +- .../boost/config/stdlib/roguewave.hpp | 53 +- utils/boost_idb/boost/config/stdlib/sgi.hpp | 58 +- .../boost_idb/boost/config/stdlib/stlport.hpp | 61 +- utils/boost_idb/boost/config/stdlib/vacpp.hpp | 57 +- utils/boost_idb/boost/config/suffix.hpp | 484 +- .../boost/config/warning_disable.hpp | 2 +- .../boost/container/allocator_traits.hpp | 405 - .../boost/container/container_fwd.hpp | 182 - utils/boost_idb/boost/container/deque.hpp | 1992 -- .../detail/adaptive_node_pool_impl.hpp | 874 - .../container/detail/advanced_insert_int.hpp | 393 - .../boost/container/detail/algorithms.hpp | 90 - .../detail/allocator_version_traits.hpp | 167 - .../boost/container/detail/config_begin.hpp | 50 - .../boost/container/detail/config_end.hpp | 17 - .../boost/container/detail/destroyers.hpp | 376 - .../boost/container/detail/flat_tree.hpp | 1026 - .../container/detail/function_detector.hpp | 88 - .../boost/container/detail/iterators.hpp | 812 - .../boost/container/detail/memory_util.hpp | 83 - .../boost_idb/boost/container/detail/mpl.hpp | 160 - .../detail/multiallocation_chain.hpp | 286 - .../container/detail/node_alloc_holder.hpp | 387 - .../boost_idb/boost/container/detail/pair.hpp | 354 - .../boost/container/detail/preprocessor.hpp | 232 - .../container/detail/transform_iterator.hpp | 176 - .../boost_idb/boost/container/detail/tree.hpp | 1085 - .../boost/container/detail/type_traits.hpp | 210 - .../boost/container/detail/utilities.hpp | 1180 -- .../boost/container/detail/value_init.hpp | 45 - .../boost/container/detail/version_type.hpp | 92 - .../boost/container/detail/workaround.hpp | 50 - utils/boost_idb/boost/container/flat_map.hpp | 1705 -- utils/boost_idb/boost/container/flat_set.hpp | 1428 -- utils/boost_idb/boost/container/list.hpp | 1384 -- utils/boost_idb/boost/container/map.hpp | 1532 -- .../boost/container/scoped_allocator.hpp | 1534 -- .../boost/container/scoped_allocator_fwd.hpp | 83 - utils/boost_idb/boost/container/set.hpp | 1298 -- utils/boost_idb/boost/container/slist.hpp | 1627 -- .../boost/container/stable_vector.hpp | 1907 -- .../boost/container/static_vector.hpp | 1091 - utils/boost_idb/boost/container/string.hpp | 2834 --- .../boost/container/throw_exception.hpp | 110 - utils/boost_idb/boost/container/vector.hpp | 2684 --- utils/boost_idb/boost/crc.hpp | 1110 + utils/boost_idb/boost/cstdint.hpp | 219 +- utils/boost_idb/boost/cstdlib.hpp | 41 + utils/boost_idb/boost/current_function.hpp | 3 +- utils/boost_idb/boost/date_time.hpp | 2 +- .../boost/date_time/adjust_functors.hpp | 2 +- .../boost/date_time/c_local_time_adjustor.hpp | 2 +- utils/boost_idb/boost/date_time/c_time.hpp | 18 +- .../boost/date_time/compiler_config.hpp | 28 +- .../boost/date_time/constrained_value.hpp | 2 +- utils/boost_idb/boost/date_time/date.hpp | 6 +- .../boost/date_time/date_clock_device.hpp | 2 +- utils/boost_idb/boost/date_time/date_defs.hpp | 2 +- .../boost/date_time/date_duration.hpp | 18 +- .../boost/date_time/date_duration_types.hpp | 2 +- .../boost_idb/boost/date_time/date_facet.hpp | 11 +- .../boost/date_time/date_format_simple.hpp | 2 +- .../boost/date_time/date_formatting.hpp | 12 +- .../date_time/date_formatting_limited.hpp | 2 +- .../date_time/date_formatting_locales.hpp | 2 +- .../date_time/date_generator_formatter.hpp | 2 +- .../boost/date_time/date_generator_parser.hpp | 2 +- .../boost/date_time/date_generators.hpp | 70 +- .../boost/date_time/date_iterator.hpp | 30 +- .../boost/date_time/date_names_put.hpp | 52 +- .../boost/date_time/date_parsing.hpp | 4 +- utils/boost_idb/boost/date_time/dst_rules.hpp | 4 +- .../date_time/dst_transition_generators.hpp | 2 +- .../boost/date_time/filetime_functions.hpp | 8 +- .../boost/date_time/format_date_parser.hpp | 30 +- .../boost/date_time/gregorian/conversion.hpp | 2 +- .../boost/date_time/gregorian/formatters.hpp | 2 +- .../gregorian/formatters_limited.hpp | 2 +- .../date_time/gregorian/greg_calendar.hpp | 2 +- .../boost/date_time/gregorian/greg_date.hpp | 2 +- .../boost/date_time/gregorian/greg_day.hpp | 2 +- .../date_time/gregorian/greg_day_of_year.hpp | 2 +- .../date_time/gregorian/greg_duration.hpp | 2 +- .../gregorian/greg_duration_types.hpp | 2 +- .../boost/date_time/gregorian/greg_facet.hpp | 2 +- .../boost/date_time/gregorian/greg_month.hpp | 2 +- .../date_time/gregorian/greg_serialize.hpp | 55 +- .../date_time/gregorian/greg_weekday.hpp | 2 +- .../boost/date_time/gregorian/greg_year.hpp | 2 +- .../boost/date_time/gregorian/greg_ymd.hpp | 2 +- .../boost/date_time/gregorian/gregorian.hpp | 2 +- .../date_time/gregorian/gregorian_io.hpp | 2 +- .../date_time/gregorian/gregorian_types.hpp | 2 +- .../boost/date_time/gregorian/parsers.hpp | 2 +- .../boost/date_time/gregorian_calendar.hpp | 2 +- .../boost/date_time/gregorian_calendar.ipp | 4 +- .../boost_idb/boost/date_time/int_adapter.hpp | 2 +- .../boost_idb/boost/date_time/iso_format.hpp | 2 +- .../boost/date_time/local_time/conversion.hpp | 2 +- .../date_time/local_time/custom_time_zone.hpp | 14 +- .../local_time/date_duration_operators.hpp | 2 +- .../local_time/dst_transition_day_rules.hpp | 2 +- .../date_time/local_time/local_date_time.hpp | 4 +- .../boost/date_time/local_time/local_time.hpp | 2 +- .../date_time/local_time/local_time_io.hpp | 2 +- .../date_time/local_time/local_time_types.hpp | 2 +- .../date_time/local_time/posix_time_zone.hpp | 4 +- .../date_time/local_time/tz_database.hpp | 2 +- .../boost/date_time/local_time_adjustor.hpp | 2 +- .../boost/date_time/local_timezone_defs.hpp | 2 +- .../boost/date_time/locale_config.hpp | 2 +- .../boost/date_time/microsec_time_clock.hpp | 2 +- .../boost/date_time/parse_format_base.hpp | 2 +- utils/boost_idb/boost/date_time/period.hpp | 2 +- .../boost/date_time/period_formatter.hpp | 10 +- .../boost/date_time/period_parser.hpp | 2 +- .../boost/date_time/posix_time/conversion.hpp | 2 +- .../posix_time/date_duration_operators.hpp | 2 +- .../boost/date_time/posix_time/posix_time.hpp | 2 +- .../posix_time/posix_time_config.hpp | 4 +- .../posix_time/posix_time_duration.hpp | 2 +- .../date_time/posix_time/posix_time_io.hpp | 2 +- .../posix_time/posix_time_legacy_io.hpp | 2 +- .../posix_time/posix_time_system.hpp | 2 +- .../boost/date_time/posix_time/ptime.hpp | 2 +- .../date_time/posix_time/time_formatters.hpp | 2 +- .../posix_time/time_formatters_limited.hpp | 2 +- .../date_time/posix_time/time_parsers.hpp | 2 +- .../date_time/posix_time/time_period.hpp | 2 +- .../date_time/posix_time/time_serialize.hpp | 28 +- .../boost/date_time/special_defs.hpp | 2 +- .../date_time/special_values_formatter.hpp | 2 +- .../boost/date_time/string_convert.hpp | 2 +- .../boost/date_time/string_parse_tree.hpp | 2 +- .../boost/date_time/strings_from_facet.hpp | 8 +- utils/boost_idb/boost/date_time/time.hpp | 2 +- .../boost_idb/boost/date_time/time_clock.hpp | 2 +- utils/boost_idb/boost/date_time/time_defs.hpp | 2 +- .../boost/date_time/time_duration.hpp | 23 +- .../boost_idb/boost/date_time/time_facet.hpp | 206 +- .../date_time/time_formatting_streams.hpp | 2 +- .../boost/date_time/time_iterator.hpp | 34 +- .../boost/date_time/time_parsing.hpp | 9 +- .../date_time/time_resolution_traits.hpp | 2 +- .../boost/date_time/time_system_counted.hpp | 2 +- .../boost/date_time/time_system_split.hpp | 2 +- .../boost/date_time/time_zone_base.hpp | 18 +- .../boost/date_time/time_zone_names.hpp | 2 +- .../boost_idb/boost/date_time/tz_db_base.hpp | 27 +- .../boost/date_time/wrapping_int.hpp | 54 +- .../boost/date_time/year_month_day.hpp | 2 +- .../boost/detail/atomic_redef_macros.hpp | 19 - .../boost/detail/atomic_undef_macros.hpp | 39 - utils/boost_idb/boost/detail/bitmask.hpp | 47 - utils/boost_idb/boost/detail/call_traits.hpp | 20 +- .../boost_idb/boost/detail/container_fwd.hpp | 109 +- utils/boost_idb/boost/detail/endian.hpp | 71 +- utils/boost_idb/boost/detail/fenv.hpp | 74 - utils/boost_idb/boost/detail/interlocked.hpp | 114 +- .../boost/detail/is_function_ref_tester.hpp | 3 +- utils/boost_idb/boost/detail/is_sorted.hpp | 56 - .../boost/detail/lightweight_main.hpp | 36 - .../boost/detail/lightweight_test.hpp | 131 +- .../boost/detail/scoped_enum_emulation.hpp | 351 +- .../boost/detail/utf8_codecvt_facet.ipp | 285 - .../boost/detail/winapi/GetCurrentProcess.hpp | 29 - .../boost/detail/winapi/GetCurrentThread.hpp | 38 - .../boost/detail/winapi/GetLastError.hpp | 31 - .../boost/detail/winapi/GetProcessTimes.hpp | 39 - .../boost/detail/winapi/GetThreadTimes.hpp | 37 - .../boost/detail/winapi/LocalFree.hpp | 33 - .../boost/detail/winapi/basic_types.hpp | 116 - .../detail/winapi/directory_management.hpp | 46 - utils/boost_idb/boost/detail/winapi/dll.hpp | 55 - .../boost/detail/winapi/error_handling.hpp | 93 - .../boost/detail/winapi/file_management.hpp | 130 - .../boost_idb/boost/detail/winapi/handles.hpp | 40 - .../boost_idb/boost/detail/winapi/memory.hpp | 60 - .../boost_idb/boost/detail/winapi/process.hpp | 37 - .../boost/detail/winapi/security.hpp | 65 - .../boost/detail/winapi/synchronization.hpp | 146 - .../boost_idb/boost/detail/winapi/system.hpp | 52 - .../boost_idb/boost/detail/winapi/thread.hpp | 49 - utils/boost_idb/boost/detail/winapi/time.hpp | 85 - .../boost_idb/boost/detail/winapi/timers.hpp | 44 - utils/boost_idb/boost/dynamic_bitset.hpp | 17 + utils/boost_idb/boost/dynamic_bitset_fwd.hpp | 25 + utils/boost_idb/boost/exception/all.hpp | 2 +- .../exception/current_exception_cast.hpp | 2 +- .../exception/detail/attribute_noreturn.hpp | 2 +- .../detail/clone_current_exception.hpp | 56 - .../exception/detail/error_info_impl.hpp | 9 +- .../boost/exception/detail/exception_ptr.hpp | 334 +- .../exception/detail/is_output_streamable.hpp | 2 +- .../exception/detail/object_hex_dump.hpp | 2 +- .../boost/exception/detail/type_info.hpp | 18 +- .../exception/diagnostic_information.hpp | 91 +- .../boost/exception/errinfo_errno.hpp | 2 +- .../exception/errinfo_nested_exception.hpp | 5 +- .../boost_idb/boost/exception/error_info.hpp | 3 - utils/boost_idb/boost/exception/exception.hpp | 55 +- .../boost/exception/get_error_info.hpp | 2 +- utils/boost_idb/boost/exception/info.hpp | 28 +- .../boost_idb/boost/exception/info_tuple.hpp | 26 +- utils/boost_idb/boost/exception/to_string.hpp | 7 +- .../boost/exception/to_string_stub.hpp | 10 +- utils/boost_idb/boost/filesystem.hpp | 26 +- utils/boost_idb/boost/filesystem/config.hpp | 103 +- .../boost/filesystem/convenience.hpp | 64 +- .../boost_idb/boost/filesystem/exception.hpp | 37 +- utils/boost_idb/boost/filesystem/fstream.hpp | 180 +- .../boost_idb/boost/filesystem/operations.hpp | 1094 +- utils/boost_idb/boost/filesystem/path.hpp | 756 +- .../boost/filesystem/path_traits.hpp | 235 - .../boost_idb/boost/filesystem/v2/config.hpp | 96 + .../boost/filesystem/v2/convenience.hpp | 338 + .../boost/filesystem/v2/exception.hpp | 9 + .../boost_idb/boost/filesystem/v2/fstream.hpp | 612 + .../boost/filesystem/v2/operations.hpp | 1244 ++ utils/boost_idb/boost/filesystem/v2/path.hpp | 1572 ++ utils/boost_idb/boost/flyweight.hpp | 22 + utils/boost_idb/boost/foreach.hpp | 1104 + utils/boost_idb/boost/foreach_fwd.hpp | 51 + utils/boost_idb/boost/function.hpp | 4 +- .../boost/function/function_base.hpp | 24 +- .../boost/function/function_template.hpp | 125 +- .../boost/function_types/components.hpp | 431 - .../boost/function_types/config/cc_names.hpp | 31 - .../boost/function_types/config/compiler.hpp | 116 - .../boost/function_types/config/config.hpp | 59 - .../function_types/detail/class_transform.hpp | 62 - .../function_types/detail/classifier.hpp | 82 - .../detail/classifier_impl/arity10_0.hpp | 55 - .../detail/classifier_impl/arity10_1.hpp | 52 - .../detail/classifier_impl/arity20_0.hpp | 53 - .../detail/classifier_impl/arity20_1.hpp | 53 - .../detail/classifier_impl/arity30_0.hpp | 53 - .../detail/classifier_impl/arity30_1.hpp | 53 - .../detail/classifier_impl/arity40_0.hpp | 53 - .../detail/classifier_impl/arity40_1.hpp | 53 - .../detail/classifier_impl/arity50_0.hpp | 53 - .../detail/classifier_impl/arity50_1.hpp | 52 - .../detail/classifier_impl/master.hpp | 33 - .../detail/components_as_mpl_sequence.hpp | 138 - .../detail/components_impl/arity10_0.hpp | 132 - .../detail/components_impl/arity10_1.hpp | 122 - .../detail/components_impl/arity20_0.hpp | 123 - .../detail/components_impl/arity20_1.hpp | 123 - .../detail/components_impl/arity30_0.hpp | 123 - .../detail/components_impl/arity30_1.hpp | 123 - .../detail/components_impl/arity40_0.hpp | 123 - .../detail/components_impl/arity40_1.hpp | 123 - .../detail/components_impl/arity50_0.hpp | 123 - .../detail/components_impl/arity50_1.hpp | 123 - .../detail/components_impl/master.hpp | 61 - .../boost/function_types/detail/cv_traits.hpp | 134 - .../detail/encoding/aliases_def.hpp | 16 - .../detail/encoding/aliases_undef.hpp | 16 - .../function_types/detail/encoding/def.hpp | 51 - .../function_types/detail/encoding/undef.hpp | 38 - .../function_types/detail/pp_arity_loop.hpp | 149 - .../detail/pp_cc_loop/master.hpp | 136 - .../detail/pp_cc_loop/preprocessed.hpp | 120 - .../boost/function_types/detail/pp_loop.hpp | 80 - .../detail/pp_retag_default_cc/master.hpp | 103 - .../pp_retag_default_cc/preprocessed.hpp | 59 - .../function_types/detail/pp_tags/cc_tag.hpp | 17 - .../function_types/detail/pp_tags/master.hpp | 126 - .../detail/pp_tags/preprocessed.hpp | 77 - .../detail/pp_variate_loop/master.hpp | 152 - .../detail/pp_variate_loop/preprocessed.hpp | 283 - .../detail/retag_default_cc.hpp | 23 - .../function_types/detail/synthesize.hpp | 79 - .../detail/synthesize_impl/arity10_0.hpp | 334 - .../detail/synthesize_impl/arity10_1.hpp | 326 - .../detail/synthesize_impl/arity20_0.hpp | 517 - .../detail/synthesize_impl/arity20_1.hpp | 527 - .../detail/synthesize_impl/arity30_0.hpp | 717 - .../detail/synthesize_impl/arity30_1.hpp | 727 - .../detail/synthesize_impl/arity40_0.hpp | 917 - .../detail/synthesize_impl/arity40_1.hpp | 927 - .../detail/synthesize_impl/arity50_0.hpp | 1117 - .../detail/synthesize_impl/arity50_1.hpp | 1127 - .../detail/synthesize_impl/master.hpp | 87 - .../function_types/detail/to_sequence.hpp | 47 - .../boost/function_types/function_arity.hpp | 38 - .../boost/function_types/function_pointer.hpp | 32 - .../function_types/function_reference.hpp | 32 - .../boost/function_types/function_type.hpp | 29 - .../function_types/is_callable_builtin.hpp | 35 - .../boost/function_types/is_function.hpp | 34 - .../function_types/is_function_pointer.hpp | 34 - .../function_types/is_function_reference.hpp | 34 - .../is_member_function_pointer.hpp | 33 - .../is_member_object_pointer.hpp | 34 - .../function_types/is_member_pointer.hpp | 34 - .../is_nonmember_callable_builtin.hpp | 35 - .../member_function_pointer.hpp | 33 - .../function_types/member_object_pointer.hpp | 34 - .../boost/function_types/parameter_types.hpp | 55 - .../boost/function_types/property_tags.hpp | 149 - .../boost/function_types/result_type.hpp | 50 - .../boost/functional/detail/container_fwd.hpp | 19 + .../boost/functional/forward_adapter.hpp | 4 +- .../hash/detail/float_functions.hpp | 90 - .../functional/hash/detail/hash_float.hpp | 200 +- .../hash/detail/hash_float_generic.hpp | 91 + .../functional/hash/detail/hash_float_x86.hpp | 56 + .../boost/functional/hash/extensions.hpp | 111 +- .../boost_idb/boost/functional/hash/hash.hpp | 220 +- .../lightweight_forward_adapter.hpp | 4 +- .../boost/functional/overloaded_function.hpp | 311 - .../functional/overloaded_function/config.hpp | 50 - .../overloaded_function/detail/base.hpp | 86 - .../detail/function_type.hpp | 85 - utils/boost_idb/boost/generator_iterator.hpp | 80 + utils/boost_idb/boost/get_pointer.hpp | 19 +- utils/boost_idb/boost/implicit_cast.hpp | 29 + utils/boost_idb/boost/indirect_reference.hpp | 43 + utils/boost_idb/boost/integer.hpp | 34 +- utils/boost_idb/boost/integer_traits.hpp | 4 +- .../interprocess/allocators/adaptive_pool.hpp | 128 +- .../interprocess/allocators/allocator.hpp | 119 +- .../allocators/cached_adaptive_pool.hpp | 78 +- .../allocators/cached_node_allocator.hpp | 73 +- .../allocators/detail/adaptive_node_pool.hpp | 38 +- .../allocators/detail/allocator_common.hpp | 294 +- .../allocators/detail/node_pool.hpp | 32 +- .../allocators/detail/node_tools.hpp | 6 +- .../allocators/node_allocator.hpp | 124 +- .../allocators/private_adaptive_pool.hpp | 96 +- .../allocators/private_node_allocator.hpp | 99 +- .../interprocess/anonymous_shared_memory.hpp | 18 +- .../containers/allocation_type.hpp | 4 +- .../containers/container/container_fwd.hpp | 187 + .../containers/container/deque.hpp | 1488 ++ .../detail/adaptive_node_pool_impl.hpp | 641 + .../container/detail/advanced_insert_int.hpp | 385 + .../container/detail/algorithms.hpp | 215 + .../container/detail/allocation_type.hpp | 16 +- .../container/detail/config_begin.hpp | 145 + .../container/detail/config_end.hpp | 17 + .../container/detail/destroyers.hpp | 154 + .../containers/container/detail/flat_tree.hpp | 875 + .../containers/container/detail/iterators.hpp | 545 + .../container/detail/math_functions.hpp | 13 +- .../containers/container/detail/mpl.hpp | 152 + .../detail/multiallocation_chain.hpp | 245 + .../container/detail/node_alloc_holder.hpp | 501 + .../container/detail/node_pool_impl.hpp | 121 +- .../containers/container/detail/pair.hpp | 212 + .../container/detail/pool_common.hpp | 12 +- .../container/detail/preprocessor.hpp | 141 + .../container/detail/stored_ref.hpp | 92 + .../container/detail/transform_iterator.hpp | 176 + .../containers/container/detail/tree.hpp | 1035 + .../container/detail/type_traits.hpp | 166 + .../containers/container/detail/utilities.hpp | 148 + .../container/detail/value_init.hpp | 43 + .../detail/variadic_templates_tools.hpp | 24 +- .../container/detail/version_type.hpp | 91 + .../container/detail/workaround.hpp | 24 + .../containers/container/flat_map.hpp | 1429 ++ .../containers/container/flat_set.hpp | 1245 ++ .../containers/container/list.hpp | 1371 ++ .../interprocess/containers/container/map.hpp | 1286 ++ .../interprocess/containers/container/set.hpp | 1155 ++ .../containers/container/slist.hpp | 1532 ++ .../containers/container/stable_vector.hpp | 1329 ++ .../containers/container/string.hpp | 2315 +++ .../containers/container/vector.hpp | 1936 ++ .../containers/containers_fwd.hpp | 6 +- .../boost/interprocess/containers/deque.hpp | 4 +- .../interprocess/containers/flat_map.hpp | 4 +- .../interprocess/containers/flat_set.hpp | 4 +- .../boost/interprocess/containers/list.hpp | 4 +- .../boost/interprocess/containers/map.hpp | 4 +- .../boost/interprocess/containers/pair.hpp | 7 +- .../boost/interprocess/containers/set.hpp | 4 +- .../boost/interprocess/containers/slist.hpp | 4 +- .../interprocess/containers/stable_vector.hpp | 4 +- .../boost/interprocess/containers/string.hpp | 4 +- .../boost/interprocess/containers/vector.hpp | 4 +- .../interprocess/containers/version_type.hpp | 8 +- .../boost/interprocess/creation_tags.hpp | 6 +- .../boost/interprocess/detail/atomic.hpp | 387 +- .../boost/interprocess/detail/cast_tags.hpp | 6 +- .../interprocess/detail/config_begin.hpp | 3 +- .../boost/interprocess/detail/config_end.hpp | 2 +- .../detail/config_external_begin.hpp | 18 - .../detail/config_external_end.hpp | 12 - .../detail/file_locking_helpers.hpp | 298 - .../interprocess/detail/file_wrapper.hpp | 55 +- .../detail/in_place_interface.hpp | 11 +- .../detail/intermodule_singleton.hpp | 1002 +- .../detail/intermodule_singleton_common.hpp | 499 - .../detail/interprocess_tester.hpp | 6 +- .../interprocess/detail/intersegment_ptr.hpp | 185 +- .../detail/managed_global_memory.hpp | 115 - .../detail/managed_memory_impl.hpp | 296 +- .../detail/managed_multi_shared_memory.hpp | 132 +- .../detail/managed_open_or_create_impl.hpp | 271 +- .../interprocess/detail/math_functions.hpp | 10 +- .../boost/interprocess/detail/min_max.hpp | 6 +- .../boost/interprocess/detail/move.hpp | 1147 +- .../boost/interprocess/detail/mpl.hpp | 26 +- .../detail/multi_segment_services.hpp | 4 +- .../boost/interprocess/detail/named_proxy.hpp | 74 +- .../interprocess/detail/os_file_functions.hpp | 133 +- .../detail/os_thread_functions.hpp | 391 +- .../interprocess/detail/pointer_type.hpp | 10 +- .../detail/portable_intermodule_singleton.hpp | 356 - .../detail/posix_time_types_wrk.hpp | 4 +- .../interprocess/detail/preprocessor.hpp | 182 +- .../boost/interprocess/detail/ptime_wrk.hpp | 4 +- .../interprocess/detail/robust_emulation.hpp | 74 +- .../detail/segment_manager_helper.hpp | 205 +- .../interprocess/detail/tmp_dir_helpers.hpp | 173 +- .../detail/transform_iterator.hpp | 12 +- .../boost/interprocess/detail/type_traits.hpp | 102 +- .../boost/interprocess/detail/utilities.hpp | 126 +- .../detail/variadic_templates_tools.hpp | 10 +- .../boost/interprocess/detail/win32_api.hpp | 1564 +- .../detail/windows_intermodule_singleton.hpp | 309 - .../boost/interprocess/detail/workaround.hpp | 185 +- .../interprocess/detail/xsi_shared_memory.hpp | 222 + .../detail/xsi_shared_memory_device.hpp | 75 +- .../detail/xsi_shared_memory_file_wrapper.hpp | 80 - utils/boost_idb/boost/interprocess/errors.hpp | 25 +- .../boost/interprocess/exceptions.hpp | 2 +- .../boost/interprocess/file_mapping.hpp | 58 +- .../interprocess/indexes/flat_map_index.hpp | 4 +- .../boost/interprocess/indexes/iset_index.hpp | 28 +- .../indexes/iunordered_set_index.hpp | 85 +- .../boost/interprocess/indexes/map_index.hpp | 16 +- .../boost/interprocess/indexes/null_index.hpp | 4 +- .../indexes/unordered_map_index.hpp | 10 +- .../boost/interprocess/interprocess_fwd.hpp | 49 +- .../boost/interprocess/ipc/message_queue.hpp | 703 +- .../interprocess/managed_external_buffer.hpp | 46 +- .../interprocess/managed_heap_memory.hpp | 50 +- .../interprocess/managed_mapped_file.hpp | 103 +- .../interprocess/managed_shared_memory.hpp | 116 +- .../managed_windows_shared_memory.hpp | 91 +- .../managed_xsi_shared_memory.hpp | 205 - .../boost/interprocess/mapped_region.hpp | 778 +- .../mem_algo/detail/mem_algo_common.hpp | 416 +- .../mem_algo/detail/multi_simple_seq_fit.hpp | 10 +- .../detail/multi_simple_seq_fit_impl.hpp | 253 +- .../mem_algo/detail/simple_seq_fit_impl.hpp | 410 +- .../interprocess/mem_algo/rbtree_best_fit.hpp | 746 +- .../interprocess/mem_algo/simple_seq_fit.hpp | 16 +- .../boost/interprocess/offset_ptr.hpp | 724 +- .../boost/interprocess/permissions.hpp | 33 +- .../boost/interprocess/segment_manager.hpp | 467 +- .../interprocess/shared_memory_object.hpp | 160 +- .../boost/interprocess/smart_ptr/deleter.hpp | 22 +- .../smart_ptr/detail/shared_count.hpp | 80 +- .../smart_ptr/detail/sp_counted_base.hpp | 2 +- .../detail/sp_counted_base_atomic.hpp | 16 +- .../smart_ptr/detail/sp_counted_impl.hpp | 56 +- .../smart_ptr/enable_shared_from_this.hpp | 8 +- .../interprocess/smart_ptr/intrusive_ptr.hpp | 54 +- .../interprocess/smart_ptr/scoped_ptr.hpp | 32 +- .../interprocess/smart_ptr/shared_ptr.hpp | 182 +- .../interprocess/smart_ptr/unique_ptr.hpp | 102 +- .../boost/interprocess/smart_ptr/weak_ptr.hpp | 35 +- .../interprocess/streams/bufferstream.hpp | 193 +- .../interprocess/streams/vectorstream.hpp | 167 +- .../sync/detail/condition_algorithm_8a.hpp | 394 - .../sync/detail/condition_any_algorithm.hpp | 224 - .../boost/interprocess/sync/detail/locks.hpp | 66 - .../interprocess_barrier.hpp | 0 .../sync/emulation/interprocess_condition.hpp | 200 + .../sync/emulation/interprocess_semaphore.hpp | 75 + .../interprocess/sync/emulation/mutex.hpp | 114 + .../named_creation_functor.hpp | 22 +- .../sync/emulation/recursive_mutex.hpp | 167 + .../boost/interprocess/sync/file_lock.hpp | 88 +- .../sync/interprocess_barrier.hpp | 115 + .../sync/interprocess_condition.hpp | 123 +- .../sync/interprocess_condition_any.hpp | 129 - .../interprocess/sync/interprocess_mutex.hpp | 98 +- .../sync/interprocess_recursive_mutex.hpp | 79 +- .../sync/interprocess_semaphore.hpp | 80 +- .../sync/interprocess_sharable_mutex.hpp | 347 - .../sync/interprocess_upgradable_mutex.hpp | 227 +- .../boost/interprocess/sync/lock_options.hpp | 2 +- .../boost/interprocess/sync/mutex_family.hpp | 6 +- .../interprocess/sync/named_condition.hpp | 262 +- .../interprocess/sync/named_condition_any.hpp | 151 - .../boost/interprocess/sync/named_mutex.hpp | 140 +- .../sync/named_recursive_mutex.hpp | 72 +- .../interprocess/sync/named_semaphore.hpp | 115 +- .../sync/named_sharable_mutex.hpp | 230 - .../sync/named_upgradable_mutex.hpp | 133 +- .../boost/interprocess/sync/null_mutex.hpp | 2 +- .../interprocess/sync/posix/condition.hpp | 191 - .../sync/posix/interprocess_barrier.hpp | 45 + .../sync/posix/interprocess_condition.hpp | 82 + .../sync/posix/interprocess_mutex.hpp | 111 + .../posix/interprocess_recursive_mutex.hpp | 112 + .../sync/posix/interprocess_semaphore.hpp | 49 + .../boost/interprocess/sync/posix/mutex.hpp | 155 - .../interprocess/sync/posix/named_mutex.hpp | 116 - .../sync/posix/named_semaphore.hpp | 84 - .../sync/posix/pthread_helpers.hpp | 28 +- .../sync/posix/ptime_to_timespec.hpp | 6 +- .../sync/posix/recursive_mutex.hpp | 143 - .../interprocess/sync/posix/semaphore.hpp | 63 - .../sync/posix/semaphore_wrapper.hpp | 170 +- .../boost/interprocess/sync/scoped_lock.hpp | 68 +- .../boost/interprocess/sync/sharable_lock.hpp | 44 +- .../interprocess/sync/shm/named_condition.hpp | 235 - .../sync/shm/named_condition_any.hpp | 191 - .../interprocess/sync/shm/named_mutex.hpp | 183 - .../sync/shm/named_recursive_mutex.hpp | 173 - .../interprocess/sync/shm/named_semaphore.hpp | 140 - .../sync/shm/named_upgradable_mutex.hpp | 371 - .../interprocess/sync/spin/condition.hpp | 292 - .../boost/interprocess/sync/spin/mutex.hpp | 117 - .../sync/spin/recursive_mutex.hpp | 175 - .../interprocess/sync/spin/semaphore.hpp | 111 - .../boost/interprocess/sync/spin/wait.hpp | 181 - .../interprocess/sync/upgradable_lock.hpp | 42 +- .../interprocess/sync/windows/condition.hpp | 117 - .../boost/interprocess/sync/windows/mutex.hpp | 114 - .../sync/windows/named_condition.hpp | 34 - .../sync/windows/named_condition_any.hpp | 241 - .../interprocess/sync/windows/named_mutex.hpp | 175 - .../sync/windows/named_recursive_mutex.hpp | 58 - .../sync/windows/named_semaphore.hpp | 178 - .../interprocess/sync/windows/named_sync.hpp | 215 - .../sync/windows/recursive_mutex.hpp | 43 - .../interprocess/sync/windows/semaphore.hpp | 113 - .../interprocess/sync/windows/sync_utils.hpp | 236 - .../sync/windows/winapi_mutex_wrapper.hpp | 163 - .../sync/windows/winapi_semaphore_wrapper.hpp | 198 - .../sync/xsi/simple_xsi_semaphore.hpp | 11 - .../interprocess/sync/xsi/xsi_named_mutex.hpp | 34 +- .../interprocess/windows_shared_memory.hpp | 73 +- .../boost_idb/boost/interprocess/xsi_key.hpp | 87 - .../boost/interprocess/xsi_shared_memory.hpp | 201 - utils/boost_idb/boost/intrusive/any_hook.hpp | 345 - utils/boost_idb/boost/intrusive/avl_set.hpp | 924 - .../boost/intrusive/avl_set_hook.hpp | 297 - utils/boost_idb/boost/intrusive/avltree.hpp | 538 - .../boost/intrusive/avltree_algorithms.hpp | 591 - utils/boost_idb/boost/intrusive/bs_set.hpp | 922 - .../boost_idb/boost/intrusive/bs_set_hook.hpp | 290 - utils/boost_idb/boost/intrusive/bstree.hpp | 2014 -- .../boost/intrusive/bstree_algorithms.hpp | 1988 -- .../intrusive/circular_list_algorithms.hpp | 424 - .../intrusive/circular_slist_algorithms.hpp | 415 - .../intrusive/derivation_value_traits.hpp | 70 - .../detail/any_node_and_algorithms.hpp | 297 - .../boost/intrusive/detail/assert.hpp | 41 - .../boost/intrusive/detail/avltree_node.hpp | 197 - .../detail/clear_on_destructor_base.hpp | 40 - .../detail/common_slist_algorithms.hpp | 102 - .../boost/intrusive/detail/config_begin.hpp | 52 - .../boost/intrusive/detail/config_end.hpp | 15 - .../intrusive/detail/ebo_functor_holder.hpp | 95 - .../intrusive/detail/function_detector.hpp | 88 - .../boost/intrusive/detail/generic_hook.hpp | 194 - .../has_member_function_callable_with.hpp | 357 - .../boost/intrusive/detail/hashtable_node.hpp | 307 - .../detail/is_stateful_value_traits.hpp | 77 - .../boost/intrusive/detail/list_node.hpp | 166 - .../boost/intrusive/detail/memory_util.hpp | 292 - .../boost_idb/boost/intrusive/detail/mpl.hpp | 376 - .../intrusive/detail/parent_from_member.hpp | 117 - .../boost/intrusive/detail/preprocessor.hpp | 52 - .../boost/intrusive/detail/rbtree_node.hpp | 203 - .../boost/intrusive/detail/slist_node.hpp | 142 - .../intrusive/detail/transform_iterator.hpp | 173 - .../boost/intrusive/detail/tree_node.hpp | 188 - .../boost/intrusive/detail/utilities.hpp | 1072 - .../boost/intrusive/detail/workaround.hpp | 26 - utils/boost_idb/boost/intrusive/hashtable.hpp | 3145 --- .../boost/intrusive/intrusive_fwd.hpp | 572 - .../intrusive/linear_slist_algorithms.hpp | 338 - utils/boost_idb/boost/intrusive/link_mode.hpp | 46 - utils/boost_idb/boost/intrusive/list.hpp | 1511 -- utils/boost_idb/boost/intrusive/list_hook.hpp | 290 - .../boost/intrusive/member_value_traits.hpp | 70 - utils/boost_idb/boost/intrusive/options.hpp | 840 - .../boost/intrusive/parent_from_member.hpp | 42 - .../boost/intrusive/pointer_plus_bits.hpp | 86 - .../boost/intrusive/pointer_traits.hpp | 265 - .../boost/intrusive/priority_compare.hpp | 56 - utils/boost_idb/boost/intrusive/rbtree.hpp | 534 - .../boost/intrusive/rbtree_algorithms.hpp | 547 - utils/boost_idb/boost/intrusive/set.hpp | 923 - utils/boost_idb/boost/intrusive/set_hook.hpp | 300 - utils/boost_idb/boost/intrusive/sg_set.hpp | 948 - utils/boost_idb/boost/intrusive/sgtree.hpp | 966 - .../boost/intrusive/sgtree_algorithms.hpp | 372 - utils/boost_idb/boost/intrusive/slist.hpp | 2223 -- .../boost_idb/boost/intrusive/slist_hook.hpp | 294 - utils/boost_idb/boost/intrusive/splay_set.hpp | 1060 - .../boost/intrusive/splay_set_hook.hpp | 286 - utils/boost_idb/boost/intrusive/splaytree.hpp | 695 - .../boost/intrusive/splaytree_algorithms.hpp | 683 - utils/boost_idb/boost/intrusive/treap.hpp | 1173 -- .../boost/intrusive/treap_algorithms.hpp | 640 - utils/boost_idb/boost/intrusive/treap_set.hpp | 981 - .../boost/intrusive/trivial_value_traits.hpp | 46 - .../boost/intrusive/unordered_set.hpp | 2160 -- .../boost/intrusive/unordered_set_hook.hpp | 438 - .../boost/io/detail/quoted_manip.hpp | 190 - .../boost_idb/boost/iostreams/categories.hpp | 175 - utils/boost_idb/boost/iostreams/chain.hpp | 598 - .../boost_idb/boost/iostreams/char_traits.hpp | 73 - .../boost/iostreams/checked_operations.hpp | 158 - utils/boost_idb/boost/iostreams/close.hpp | 259 - .../boost/iostreams/code_converter.hpp | 425 - utils/boost_idb/boost/iostreams/combine.hpp | 260 - utils/boost_idb/boost/iostreams/compose.hpp | 494 - utils/boost_idb/boost/iostreams/concepts.hpp | 129 - utils/boost_idb/boost/iostreams/constants.hpp | 42 - utils/boost_idb/boost/iostreams/copy.hpp | 252 - .../boost/iostreams/detail/absolute_path.hpp | 46 - .../boost/iostreams/detail/access_control.hpp | 87 - .../detail/adapter/concept_adapter.hpp | 287 - .../detail/adapter/device_adapter.hpp | 67 - .../detail/adapter/direct_adapter.hpp | 281 - .../detail/adapter/filter_adapter.hpp | 69 - .../iostreams/detail/adapter/mode_adapter.hpp | 123 - .../detail/adapter/non_blocking_adapter.hpp | 59 - .../adapter/output_iterator_adapter.hpp | 41 - .../detail/adapter/range_adapter.hpp | 187 - .../boost/iostreams/detail/add_facet.hpp | 49 - .../boost/iostreams/detail/bool_trait_def.hpp | 49 - .../broken_overload_resolution/forward.hpp | 31 - .../broken_overload_resolution/stream.hpp | 184 - .../stream_buffer.hpp | 189 - .../boost/iostreams/detail/buffer.hpp | 200 - .../boost/iostreams/detail/call_traits.hpp | 32 - .../boost/iostreams/detail/char_traits.hpp | 63 - .../boost/iostreams/detail/codecvt_helper.hpp | 237 - .../boost/iostreams/detail/codecvt_holder.hpp | 63 - .../iostreams/detail/config/auto_link.hpp | 49 - .../boost/iostreams/detail/config/bzip2.hpp | 48 - .../boost/iostreams/detail/config/codecvt.hpp | 80 - .../detail/config/disable_warnings.hpp | 30 - .../iostreams/detail/config/dyn_link.hpp | 37 - .../detail/config/enable_warnings.hpp | 18 - .../boost/iostreams/detail/config/fpos.hpp | 31 - .../boost/iostreams/detail/config/gcc.hpp | 27 - .../boost/iostreams/detail/config/limits.hpp | 19 - .../detail/config/overload_resolution.hpp | 32 - .../boost/iostreams/detail/config/rtl.hpp | 72 - .../detail/config/unreachable_return.hpp | 25 - .../iostreams/detail/config/wide_streams.hpp | 55 - .../iostreams/detail/config/windows_posix.hpp | 25 - .../boost/iostreams/detail/config/zlib.hpp | 50 - .../boost/iostreams/detail/counted_array.hpp | 64 - .../iostreams/detail/current_directory.hpp | 65 - .../boost/iostreams/detail/default_arg.hpp | 25 - .../boost/iostreams/detail/dispatch.hpp | 41 - .../boost/iostreams/detail/double_object.hpp | 114 - .../iostreams/detail/enable_if_stream.hpp | 32 - .../boost/iostreams/detail/error.hpp | 45 - .../boost/iostreams/detail/execute.hpp | 135 - .../boost/iostreams/detail/file_handle.hpp | 32 - .../boost/iostreams/detail/forward.hpp | 124 - .../boost/iostreams/detail/fstream.hpp | 33 - .../boost/iostreams/detail/functional.hpp | 189 - .../boost_idb/boost/iostreams/detail/ios.hpp | 66 - .../boost/iostreams/detail/iostream.hpp | 34 - .../iostreams/detail/is_dereferenceable.hpp | 85 - .../iostreams/detail/is_iterator_range.hpp | 49 - .../boost/iostreams/detail/newline.hpp | 32 - .../boost/iostreams/detail/optional.hpp | 114 - .../boost/iostreams/detail/param_type.hpp | 27 - .../boost_idb/boost/iostreams/detail/path.hpp | 214 - .../boost_idb/boost/iostreams/detail/push.hpp | 154 - .../boost/iostreams/detail/push_params.hpp | 21 - .../boost/iostreams/detail/resolve.hpp | 235 - .../boost/iostreams/detail/restrict_impl.hpp | 482 - .../boost/iostreams/detail/select.hpp | 86 - .../boost/iostreams/detail/select_by_size.hpp | 161 - .../boost/iostreams/detail/streambuf.hpp | 34 - .../iostreams/detail/streambuf/chainbuf.hpp | 116 - .../detail/streambuf/direct_streambuf.hpp | 313 - .../detail/streambuf/indirect_streambuf.hpp | 432 - .../detail/streambuf/linked_streambuf.hpp | 114 - .../boost/iostreams/detail/system_failure.hpp | 84 - .../iostreams/detail/template_params.hpp | 26 - .../iostreams/detail/translate_int_type.hpp | 62 - .../boost/iostreams/detail/vc6/close.hpp | 129 - .../boost/iostreams/detail/vc6/read.hpp | 238 - .../boost/iostreams/detail/vc6/write.hpp | 159 - .../boost/iostreams/detail/wrap_unwrap.hpp | 127 - .../boost/iostreams/device/array.hpp | 144 - .../boost/iostreams/device/back_inserter.hpp | 41 - .../boost_idb/boost/iostreams/device/file.hpp | 191 - .../iostreams/device/file_descriptor.hpp | 318 - .../boost/iostreams/device/mapped_file.hpp | 599 - .../boost_idb/boost/iostreams/device/null.hpp | 66 - .../boost/iostreams/filter/aggregate.hpp | 168 - .../boost/iostreams/filter/bzip2.hpp | 414 - .../boost/iostreams/filter/counter.hpp | 82 - .../boost_idb/boost/iostreams/filter/grep.hpp | 109 - .../boost_idb/boost/iostreams/filter/gzip.hpp | 757 - .../boost_idb/boost/iostreams/filter/line.hpp | 227 - .../boost/iostreams/filter/newline.hpp | 442 - .../boost/iostreams/filter/regex.hpp | 98 - .../boost/iostreams/filter/stdio.hpp | 84 - .../boost/iostreams/filter/symmetric.hpp | 310 - .../boost_idb/boost/iostreams/filter/test.hpp | 322 - .../boost_idb/boost/iostreams/filter/zlib.hpp | 427 - .../boost/iostreams/filtering_stream.hpp | 166 - .../boost/iostreams/filtering_streambuf.hpp | 70 - utils/boost_idb/boost/iostreams/flush.hpp | 125 - utils/boost_idb/boost/iostreams/get.hpp | 17 - utils/boost_idb/boost/iostreams/imbue.hpp | 82 - .../boost/iostreams/input_sequence.hpp | 72 - utils/boost_idb/boost/iostreams/invert.hpp | 167 - .../boost_idb/boost/iostreams/operations.hpp | 26 - .../boost/iostreams/operations_fwd.hpp | 41 - .../boost/iostreams/optimal_buffer_size.hpp | 87 - .../boost/iostreams/output_sequence.hpp | 72 - utils/boost_idb/boost/iostreams/pipeline.hpp | 128 - .../boost_idb/boost/iostreams/positioning.hpp | 117 - utils/boost_idb/boost/iostreams/put.hpp | 17 - utils/boost_idb/boost/iostreams/putback.hpp | 17 - utils/boost_idb/boost/iostreams/read.hpp | 247 - utils/boost_idb/boost/iostreams/restrict.hpp | 26 - utils/boost_idb/boost/iostreams/seek.hpp | 180 - utils/boost_idb/boost/iostreams/skip.hpp | 112 - utils/boost_idb/boost/iostreams/slice.hpp | 28 - utils/boost_idb/boost/iostreams/stream.hpp | 151 - .../boost/iostreams/stream_buffer.hpp | 116 - utils/boost_idb/boost/iostreams/tee.hpp | 232 - utils/boost_idb/boost/iostreams/traits.hpp | 391 - .../boost_idb/boost/iostreams/traits_fwd.hpp | 111 - utils/boost_idb/boost/iostreams/write.hpp | 171 - utils/boost_idb/boost/iterator.hpp | 2 +- .../iterator/function_input_iterator.hpp | 160 - .../boost/iterator/iterator_adaptor.hpp | 8 +- .../boost/iterator/iterator_facade.hpp | 80 +- .../boost/iterator/reverse_iterator.hpp | 2 +- .../boost/iterator/transform_iterator.hpp | 25 +- .../boost_idb/boost/iterator/zip_iterator.hpp | 2 +- utils/boost_idb/boost/last_value.hpp | 54 + utils/boost_idb/boost/lexical_cast.hpp | 2963 +-- utils/boost_idb/boost/limits.hpp | 2 +- utils/boost_idb/boost/make_shared.hpp | 17 + .../math/bindings/detail/big_digamma.hpp | 295 - .../math/bindings/detail/big_lanczos.hpp | 777 - .../boost_idb/boost/math/bindings/e_float.hpp | 809 - utils/boost_idb/boost/math/bindings/mpfr.hpp | 946 - .../boost_idb/boost/math/bindings/mpreal.hpp | 898 - utils/boost_idb/boost/math/bindings/rr.hpp | 884 - utils/boost_idb/boost/math/common_factor.hpp | 16 - .../boost_idb/boost/math/common_factor_ct.hpp | 180 - .../boost_idb/boost/math/common_factor_rt.hpp | 530 - utils/boost_idb/boost/math/complex.hpp | 32 - utils/boost_idb/boost/math/complex/acos.hpp | 245 - utils/boost_idb/boost/math/complex/acosh.hpp | 34 - utils/boost_idb/boost/math/complex/asin.hpp | 252 - utils/boost_idb/boost/math/complex/asinh.hpp | 32 - utils/boost_idb/boost/math/complex/atan.hpp | 36 - utils/boost_idb/boost/math/complex/atanh.hpp | 214 - .../boost_idb/boost/math/complex/details.hpp | 96 - utils/boost_idb/boost/math/complex/fabs.hpp | 23 - .../boost/math/concepts/distributions.hpp | 491 - .../boost/math/concepts/real_concept.hpp | 451 - .../boost/math/concepts/real_type_concept.hpp | 122 - .../boost/math/concepts/std_real_concept.hpp | 396 - .../math/constants/calculate_constants.hpp | 968 - .../boost/math/constants/constants.hpp | 334 - .../boost/math/constants/generate.hpp | 76 - utils/boost_idb/boost/math/constants/info.hpp | 163 - utils/boost_idb/boost/math/distributions.hpp | 51 - .../boost/math/distributions/bernoulli.hpp | 336 - .../boost/math/distributions/beta.hpp | 541 - .../boost/math/distributions/binomial.hpp | 728 - .../boost/math/distributions/cauchy.hpp | 362 - .../boost/math/distributions/chi_squared.hpp | 355 - .../boost/math/distributions/complement.hpp | 195 - .../detail/common_error_handling.hpp | 194 - .../detail/derived_accessors.hpp | 163 - .../distributions/detail/generic_mode.hpp | 149 - .../distributions/detail/generic_quantile.hpp | 91 - .../detail/hypergeometric_cdf.hpp | 100 - .../detail/hypergeometric_pdf.hpp | 488 - .../detail/hypergeometric_quantile.hpp | 199 - .../detail/inv_discrete_quantile.hpp | 561 - .../boost/math/distributions/exponential.hpp | 269 - .../math/distributions/extreme_value.hpp | 297 - .../math/distributions/find_location.hpp | 146 - .../boost/math/distributions/find_scale.hpp | 211 - .../boost/math/distributions/fisher_f.hpp | 387 - .../boost/math/distributions/fwd.hpp | 146 - .../boost/math/distributions/gamma.hpp | 349 - .../boost/math/distributions/geometric.hpp | 516 - .../math/distributions/hypergeometric.hpp | 293 - .../distributions/inverse_chi_squared.hpp | 391 - .../math/distributions/inverse_gamma.hpp | 461 - .../math/distributions/inverse_gaussian.hpp | 512 - .../boost/math/distributions/laplace.hpp | 312 - .../boost/math/distributions/logistic.hpp | 299 - .../boost/math/distributions/lognormal.hpp | 341 - .../math/distributions/negative_binomial.hpp | 588 - .../math/distributions/non_central_beta.hpp | 925 - .../distributions/non_central_chi_squared.hpp | 996 - .../math/distributions/non_central_f.hpp | 409 - .../math/distributions/non_central_t.hpp | 1202 -- .../boost/math/distributions/normal.hpp | 321 - .../boost/math/distributions/pareto.hpp | 444 - .../boost/math/distributions/poisson.hpp | 527 - .../boost/math/distributions/rayleigh.hpp | 297 - .../boost/math/distributions/skew_normal.hpp | 719 - .../boost/math/distributions/students_t.hpp | 490 - .../boost/math/distributions/triangular.hpp | 523 - .../boost/math/distributions/uniform.hpp | 379 - .../boost/math/distributions/weibull.hpp | 395 - utils/boost_idb/boost/math/octonion.hpp | 4754 ----- .../boost/math/policies/error_handling.hpp | 719 - .../boost_idb/boost/math/policies/policy.hpp | 992 - utils/boost_idb/boost/math/quaternion.hpp | 1924 -- .../boost/math/special_functions.hpp | 64 - .../boost/math/special_functions/acosh.hpp | 115 - .../boost/math/special_functions/airy.hpp | 437 - .../boost/math/special_functions/asinh.hpp | 117 - .../boost/math/special_functions/atanh.hpp | 128 - .../boost/math/special_functions/bessel.hpp | 766 - .../boost/math/special_functions/beta.hpp | 1490 -- .../boost/math/special_functions/binomial.hpp | 81 - .../boost/math/special_functions/cbrt.hpp | 180 - .../boost/math/special_functions/cos_pi.hpp | 68 - .../detail/airy_ai_bi_zero.hpp | 160 - .../special_functions/detail/bessel_i0.hpp | 132 - .../special_functions/detail/bessel_i1.hpp | 136 - .../special_functions/detail/bessel_ik.hpp | 445 - .../special_functions/detail/bessel_j0.hpp | 193 - .../special_functions/detail/bessel_j1.hpp | 199 - .../special_functions/detail/bessel_jn.hpp | 134 - .../special_functions/detail/bessel_jy.hpp | 578 - .../detail/bessel_jy_asym.hpp | 205 - .../detail/bessel_jy_series.hpp | 261 - .../detail/bessel_jy_zero.hpp | 617 - .../special_functions/detail/bessel_k0.hpp | 152 - .../special_functions/detail/bessel_k1.hpp | 148 - .../special_functions/detail/bessel_kn.hpp | 85 - .../special_functions/detail/bessel_y0.hpp | 224 - .../special_functions/detail/bessel_y1.hpp | 196 - .../special_functions/detail/bessel_yn.hpp | 104 - .../math/special_functions/detail/erf_inv.hpp | 521 - .../special_functions/detail/fp_traits.hpp | 570 - .../special_functions/detail/gamma_inva.hpp | 233 - .../special_functions/detail/ibeta_inv_ab.hpp | 324 - .../detail/ibeta_inverse.hpp | 993 - .../math/special_functions/detail/iconv.hpp | 42 - .../detail/igamma_inverse.hpp | 551 - .../special_functions/detail/igamma_large.hpp | 768 - .../special_functions/detail/lanczos_sse2.hpp | 204 - .../special_functions/detail/lgamma_small.hpp | 522 - .../special_functions/detail/round_fwd.hpp | 93 - .../detail/t_distribution_inv.hpp | 549 - .../detail/unchecked_factorial.hpp | 435 - .../boost/math/special_functions/digamma.hpp | 479 - .../boost/math/special_functions/ellint_1.hpp | 188 - .../boost/math/special_functions/ellint_2.hpp | 169 - .../boost/math/special_functions/ellint_3.hpp | 319 - .../math/special_functions/ellint_rc.hpp | 115 - .../math/special_functions/ellint_rd.hpp | 130 - .../math/special_functions/ellint_rf.hpp | 132 - .../math/special_functions/ellint_rj.hpp | 180 - .../boost/math/special_functions/erf.hpp | 1155 -- .../boost/math/special_functions/expint.hpp | 1671 -- .../boost/math/special_functions/expm1.hpp | 343 - .../math/special_functions/factorials.hpp | 239 - .../math/special_functions/fpclassify.hpp | 606 - .../boost/math/special_functions/gamma.hpp | 1704 -- .../boost/math/special_functions/hankel.hpp | 179 - .../boost/math/special_functions/hermite.hpp | 76 - .../boost/math/special_functions/hypot.hpp | 86 - .../special_functions/jacobi_elliptic.hpp | 320 - .../boost/math/special_functions/laguerre.hpp | 139 - .../boost/math/special_functions/lanczos.hpp | 1296 -- .../boost/math/special_functions/legendre.hpp | 194 - .../boost/math/special_functions/log1p.hpp | 503 - .../boost/math/special_functions/math_fwd.hpp | 1408 -- .../boost/math/special_functions/modf.hpp | 70 - .../boost/math/special_functions/next.hpp | 490 - .../nonfinite_num_facets.hpp | 592 - .../boost/math/special_functions/owens_t.hpp | 1061 - .../boost/math/special_functions/pow.hpp | 140 - .../boost/math/special_functions/powm1.hpp | 61 - .../boost/math/special_functions/prime.hpp | 1219 -- .../boost/math/special_functions/round.hpp | 93 - .../boost/math/special_functions/sign.hpp | 150 - .../boost/math/special_functions/sin_pi.hpp | 70 - .../boost/math/special_functions/sinc.hpp | 145 - .../boost/math/special_functions/sinhc.hpp | 167 - .../special_functions/spherical_harmonic.hpp | 204 - .../boost/math/special_functions/sqrt1pm1.hpp | 48 - .../boost/math/special_functions/trunc.hpp | 96 - .../boost/math/special_functions/zeta.hpp | 995 - .../boost/math/tools/big_constant.hpp | 67 - utils/boost_idb/boost/math/tools/config.hpp | 352 - .../tools/detail/polynomial_horner1_10.hpp | 84 - .../tools/detail/polynomial_horner1_11.hpp | 90 - .../tools/detail/polynomial_horner1_12.hpp | 96 - .../tools/detail/polynomial_horner1_13.hpp | 102 - .../tools/detail/polynomial_horner1_14.hpp | 108 - .../tools/detail/polynomial_horner1_15.hpp | 114 - .../tools/detail/polynomial_horner1_16.hpp | 120 - .../tools/detail/polynomial_horner1_17.hpp | 126 - .../tools/detail/polynomial_horner1_18.hpp | 132 - .../tools/detail/polynomial_horner1_19.hpp | 138 - .../tools/detail/polynomial_horner1_2.hpp | 36 - .../tools/detail/polynomial_horner1_20.hpp | 144 - .../tools/detail/polynomial_horner1_3.hpp | 42 - .../tools/detail/polynomial_horner1_4.hpp | 48 - .../tools/detail/polynomial_horner1_5.hpp | 54 - .../tools/detail/polynomial_horner1_6.hpp | 60 - .../tools/detail/polynomial_horner1_7.hpp | 66 - .../tools/detail/polynomial_horner1_8.hpp | 72 - .../tools/detail/polynomial_horner1_9.hpp | 78 - .../tools/detail/polynomial_horner2_10.hpp | 90 - .../tools/detail/polynomial_horner2_11.hpp | 97 - .../tools/detail/polynomial_horner2_12.hpp | 104 - .../tools/detail/polynomial_horner2_13.hpp | 111 - .../tools/detail/polynomial_horner2_14.hpp | 118 - .../tools/detail/polynomial_horner2_15.hpp | 125 - .../tools/detail/polynomial_horner2_16.hpp | 132 - .../tools/detail/polynomial_horner2_17.hpp | 139 - .../tools/detail/polynomial_horner2_18.hpp | 146 - .../tools/detail/polynomial_horner2_19.hpp | 153 - .../tools/detail/polynomial_horner2_2.hpp | 48 - .../tools/detail/polynomial_horner2_20.hpp | 160 - .../tools/detail/polynomial_horner2_3.hpp | 48 - .../tools/detail/polynomial_horner2_4.hpp | 48 - .../tools/detail/polynomial_horner2_5.hpp | 55 - .../tools/detail/polynomial_horner2_6.hpp | 62 - .../tools/detail/polynomial_horner2_7.hpp | 69 - .../tools/detail/polynomial_horner2_8.hpp | 76 - .../tools/detail/polynomial_horner2_9.hpp | 83 - .../tools/detail/polynomial_horner3_10.hpp | 156 - .../tools/detail/polynomial_horner3_11.hpp | 181 - .../tools/detail/polynomial_horner3_12.hpp | 208 - .../tools/detail/polynomial_horner3_13.hpp | 237 - .../tools/detail/polynomial_horner3_14.hpp | 268 - .../tools/detail/polynomial_horner3_15.hpp | 301 - .../tools/detail/polynomial_horner3_16.hpp | 336 - .../tools/detail/polynomial_horner3_17.hpp | 373 - .../tools/detail/polynomial_horner3_18.hpp | 412 - .../tools/detail/polynomial_horner3_19.hpp | 453 - .../tools/detail/polynomial_horner3_2.hpp | 48 - .../tools/detail/polynomial_horner3_20.hpp | 496 - .../tools/detail/polynomial_horner3_3.hpp | 48 - .../tools/detail/polynomial_horner3_4.hpp | 48 - .../tools/detail/polynomial_horner3_5.hpp | 61 - .../tools/detail/polynomial_horner3_6.hpp | 76 - .../tools/detail/polynomial_horner3_7.hpp | 93 - .../tools/detail/polynomial_horner3_8.hpp | 112 - .../tools/detail/polynomial_horner3_9.hpp | 133 - .../math/tools/detail/rational_horner1_10.hpp | 138 - .../math/tools/detail/rational_horner1_11.hpp | 150 - .../math/tools/detail/rational_horner1_12.hpp | 162 - .../math/tools/detail/rational_horner1_13.hpp | 174 - .../math/tools/detail/rational_horner1_14.hpp | 186 - .../math/tools/detail/rational_horner1_15.hpp | 198 - .../math/tools/detail/rational_horner1_16.hpp | 210 - .../math/tools/detail/rational_horner1_17.hpp | 222 - .../math/tools/detail/rational_horner1_18.hpp | 234 - .../math/tools/detail/rational_horner1_19.hpp | 246 - .../math/tools/detail/rational_horner1_2.hpp | 42 - .../math/tools/detail/rational_horner1_20.hpp | 258 - .../math/tools/detail/rational_horner1_3.hpp | 54 - .../math/tools/detail/rational_horner1_4.hpp | 66 - .../math/tools/detail/rational_horner1_5.hpp | 78 - .../math/tools/detail/rational_horner1_6.hpp | 90 - .../math/tools/detail/rational_horner1_7.hpp | 102 - .../math/tools/detail/rational_horner1_8.hpp | 114 - .../math/tools/detail/rational_horner1_9.hpp | 126 - .../math/tools/detail/rational_horner2_10.hpp | 144 - .../math/tools/detail/rational_horner2_11.hpp | 160 - .../math/tools/detail/rational_horner2_12.hpp | 176 - .../math/tools/detail/rational_horner2_13.hpp | 192 - .../math/tools/detail/rational_horner2_14.hpp | 208 - .../math/tools/detail/rational_horner2_15.hpp | 224 - .../math/tools/detail/rational_horner2_16.hpp | 240 - .../math/tools/detail/rational_horner2_17.hpp | 256 - .../math/tools/detail/rational_horner2_18.hpp | 272 - .../math/tools/detail/rational_horner2_19.hpp | 288 - .../math/tools/detail/rational_horner2_2.hpp | 48 - .../math/tools/detail/rational_horner2_20.hpp | 304 - .../math/tools/detail/rational_horner2_3.hpp | 48 - .../math/tools/detail/rational_horner2_4.hpp | 48 - .../math/tools/detail/rational_horner2_5.hpp | 64 - .../math/tools/detail/rational_horner2_6.hpp | 80 - .../math/tools/detail/rational_horner2_7.hpp | 96 - .../math/tools/detail/rational_horner2_8.hpp | 112 - .../math/tools/detail/rational_horner2_9.hpp | 128 - .../math/tools/detail/rational_horner3_10.hpp | 396 - .../math/tools/detail/rational_horner3_11.hpp | 482 - .../math/tools/detail/rational_horner3_12.hpp | 576 - .../math/tools/detail/rational_horner3_13.hpp | 678 - .../math/tools/detail/rational_horner3_14.hpp | 788 - .../math/tools/detail/rational_horner3_15.hpp | 906 - .../math/tools/detail/rational_horner3_16.hpp | 1032 - .../math/tools/detail/rational_horner3_17.hpp | 1166 -- .../math/tools/detail/rational_horner3_18.hpp | 1308 -- .../math/tools/detail/rational_horner3_19.hpp | 1458 -- .../math/tools/detail/rational_horner3_2.hpp | 48 - .../math/tools/detail/rational_horner3_20.hpp | 1616 -- .../math/tools/detail/rational_horner3_3.hpp | 48 - .../math/tools/detail/rational_horner3_4.hpp | 48 - .../math/tools/detail/rational_horner3_5.hpp | 86 - .../math/tools/detail/rational_horner3_6.hpp | 132 - .../math/tools/detail/rational_horner3_7.hpp | 186 - .../math/tools/detail/rational_horner3_8.hpp | 248 - .../math/tools/detail/rational_horner3_9.hpp | 318 - utils/boost_idb/boost/math/tools/fraction.hpp | 252 - utils/boost_idb/boost/math/tools/minima.hpp | 152 - .../boost_idb/boost/math/tools/polynomial.hpp | 323 - .../boost_idb/boost/math/tools/precision.hpp | 335 - .../boost_idb/boost/math/tools/promotion.hpp | 175 - utils/boost_idb/boost/math/tools/rational.hpp | 333 - .../boost_idb/boost/math/tools/real_cast.hpp | 29 - utils/boost_idb/boost/math/tools/remez.hpp | 667 - utils/boost_idb/boost/math/tools/roots.hpp | 542 - utils/boost_idb/boost/math/tools/series.hpp | 158 - utils/boost_idb/boost/math/tools/solve.hpp | 79 - utils/boost_idb/boost/math/tools/stats.hpp | 88 - utils/boost_idb/boost/math/tools/test.hpp | 334 - .../boost_idb/boost/math/tools/test_data.hpp | 767 - .../boost/math/tools/toms748_solve.hpp | 585 - utils/boost_idb/boost/math/tools/traits.hpp | 111 - utils/boost_idb/boost/math/tools/tuple.hpp | 112 - utils/boost_idb/boost/math/tools/user.hpp | 97 - .../boost_idb/boost/math/tools/workaround.hpp | 38 - utils/boost_idb/boost/math/tr1.hpp | 1115 - utils/boost_idb/boost/math/tr1_c_macros.ipp | 810 - utils/boost_idb/boost/move/algorithm.hpp | 274 - utils/boost_idb/boost/move/core.hpp | 339 - .../boost/move/detail/config_begin.hpp | 23 - .../boost/move/detail/config_end.hpp | 20 - .../boost/move/detail/meta_utils.hpp | 158 - .../boost/move/detail/move_helpers.hpp | 177 - utils/boost_idb/boost/move/iterator.hpp | 298 - utils/boost_idb/boost/move/move.hpp | 27 - utils/boost_idb/boost/move/traits.hpp | 150 - utils/boost_idb/boost/move/utility.hpp | 194 - utils/boost_idb/boost/mpi.hpp | 35 + utils/boost_idb/boost/mpl/O1_size.hpp | 2 +- utils/boost_idb/boost/mpl/O1_size_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/accumulate.hpp | 2 +- utils/boost_idb/boost/mpl/advance.hpp | 2 +- utils/boost_idb/boost/mpl/advance_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/alias.hpp | 2 +- utils/boost_idb/boost/mpl/always.hpp | 2 +- utils/boost_idb/boost/mpl/and.hpp | 2 +- utils/boost_idb/boost/mpl/apply.hpp | 2 +- utils/boost_idb/boost/mpl/apply_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/apply_wrap.hpp | 2 +- utils/boost_idb/boost/mpl/arg.hpp | 2 +- utils/boost_idb/boost/mpl/arg_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/arithmetic.hpp | 2 +- utils/boost_idb/boost/mpl/as_sequence.hpp | 2 +- utils/boost_idb/boost/mpl/assert.hpp | 76 +- utils/boost_idb/boost/mpl/at.hpp | 2 +- utils/boost_idb/boost/mpl/at_fwd.hpp | 2 +- .../boost_idb/boost/mpl/aux_/O1_size_impl.hpp | 2 +- .../boost_idb/boost/mpl/aux_/adl_barrier.hpp | 2 +- .../boost/mpl/aux_/advance_backward.hpp | 2 +- .../boost/mpl/aux_/advance_forward.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/apply_1st.hpp | 2 +- .../boost_idb/boost/mpl/aux_/arg_typedef.hpp | 2 +- .../boost/mpl/aux_/arithmetic_op.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/arity.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/arity_spec.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/at_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/back_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/basic_bind.hpp | 2 +- .../boost/mpl/aux_/begin_end_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/clear_impl.hpp | 2 +- .../boost/mpl/aux_/common_name_wknd.hpp | 2 +- .../boost/mpl/aux_/comparison_op.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/config/adl.hpp | 2 +- .../boost/mpl/aux_/config/arrays.hpp | 2 +- .../boost_idb/boost/mpl/aux_/config/bind.hpp | 2 +- .../boost/mpl/aux_/config/compiler.hpp | 2 +- .../boost_idb/boost/mpl/aux_/config/ctps.hpp | 2 +- .../boost/mpl/aux_/config/dependent_nttp.hpp | 2 +- .../mpl/aux_/config/dmc_ambiguous_ctps.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/config/dtp.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/config/eti.hpp | 2 +- .../boost/mpl/aux_/config/forwarding.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/config/gcc.hpp | 2 +- .../boost/mpl/aux_/config/has_apply.hpp | 2 +- .../boost/mpl/aux_/config/has_xxx.hpp | 2 +- .../boost/mpl/aux_/config/integral.hpp | 2 +- .../boost_idb/boost/mpl/aux_/config/intel.hpp | 2 +- .../boost/mpl/aux_/config/lambda.hpp | 2 +- .../boost_idb/boost/mpl/aux_/config/msvc.hpp | 2 +- .../boost/mpl/aux_/config/msvc_typename.hpp | 2 +- .../boost_idb/boost/mpl/aux_/config/nttp.hpp | 2 +- .../boost/mpl/aux_/config/operators.hpp | 2 +- .../mpl/aux_/config/overload_resolution.hpp | 2 +- .../boost/mpl/aux_/config/pp_counter.hpp | 2 +- .../boost/mpl/aux_/config/preprocessor.hpp | 2 +- .../boost/mpl/aux_/config/static_constant.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/config/ttp.hpp | 2 +- .../boost/mpl/aux_/config/typeof.hpp | 2 +- .../mpl/aux_/config/use_preprocessed.hpp | 2 +- .../boost/mpl/aux_/config/workaround.hpp | 2 +- .../boost/mpl/aux_/contains_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/count_args.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/count_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/empty_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/erase_impl.hpp | 2 +- .../boost/mpl/aux_/erase_key_impl.hpp | 2 +- .../boost_idb/boost/mpl/aux_/filter_iter.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/fold_impl.hpp | 2 +- .../boost/mpl/aux_/fold_impl_body.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/fold_op.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/fold_pred.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/front_impl.hpp | 2 +- .../boost_idb/boost/mpl/aux_/full_lambda.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/has_apply.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/has_begin.hpp | 2 +- .../boost_idb/boost/mpl/aux_/has_key_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/has_rebind.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/has_size.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/has_tag.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/has_type.hpp | 2 +- .../boost/mpl/aux_/include_preprocessed.hpp | 2 +- .../boost_idb/boost/mpl/aux_/insert_impl.hpp | 2 +- .../boost/mpl/aux_/insert_range_impl.hpp | 2 +- .../boost/mpl/aux_/inserter_algorithm.hpp | 2 +- .../boost/mpl/aux_/integral_wrapper.hpp | 2 +- .../boost/mpl/aux_/is_msvc_eti_arg.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/iter_apply.hpp | 2 +- .../boost/mpl/aux_/iter_fold_if_impl.hpp | 2 +- .../boost/mpl/aux_/iter_fold_impl.hpp | 2 +- .../boost/mpl/aux_/iter_push_front.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/joint_iter.hpp | 2 +- .../boost/mpl/aux_/lambda_arity_param.hpp | 2 +- .../boost/mpl/aux_/lambda_no_ctps.hpp | 2 +- .../boost_idb/boost/mpl/aux_/lambda_spec.hpp | 2 +- .../boost/mpl/aux_/lambda_support.hpp | 2 +- .../boost_idb/boost/mpl/aux_/largest_int.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/logical_op.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/msvc_dtw.hpp | 2 +- .../boost/mpl/aux_/msvc_eti_base.hpp | 2 +- .../boost/mpl/aux_/msvc_is_class.hpp | 2 +- .../boost/mpl/aux_/msvc_never_true.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/msvc_type.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/na.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/na_assert.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/na_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/na_spec.hpp | 2 +- .../boost/mpl/aux_/nested_type_wknd.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/nttp_decl.hpp | 2 +- .../boost/mpl/aux_/numeric_cast_utils.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/numeric_op.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/order_impl.hpp | 2 +- .../boost/mpl/aux_/overload_names.hpp | 2 +- .../boost_idb/boost/mpl/aux_/partition_op.hpp | 2 +- .../boost/mpl/aux_/pop_back_impl.hpp | 2 +- .../boost/mpl/aux_/pop_front_impl.hpp | 2 +- .../boost/mpl/aux_/preprocessor/add.hpp | 2 +- .../mpl/aux_/preprocessor/def_params_tail.hpp | 2 +- .../mpl/aux_/preprocessor/default_params.hpp | 2 +- .../boost/mpl/aux_/preprocessor/enum.hpp | 2 +- .../mpl/aux_/preprocessor/ext_params.hpp | 2 +- .../mpl/aux_/preprocessor/filter_params.hpp | 2 +- .../boost/mpl/aux_/preprocessor/is_seq.hpp | 2 +- .../boost/mpl/aux_/preprocessor/params.hpp | 2 +- .../aux_/preprocessor/partial_spec_params.hpp | 2 +- .../boost/mpl/aux_/preprocessor/range.hpp | 2 +- .../boost/mpl/aux_/preprocessor/repeat.hpp | 2 +- .../boost/mpl/aux_/preprocessor/sub.hpp | 2 +- .../mpl/aux_/preprocessor/token_equal.hpp | 2 +- .../boost/mpl/aux_/preprocessor/tuple.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/ptr_to_ref.hpp | 2 +- .../boost/mpl/aux_/push_back_impl.hpp | 2 +- .../boost/mpl/aux_/push_front_impl.hpp | 2 +- .../boost/mpl/aux_/range_c/O1_size.hpp | 2 +- .../boost_idb/boost/mpl/aux_/range_c/back.hpp | 2 +- .../boost/mpl/aux_/range_c/empty.hpp | 2 +- .../boost/mpl/aux_/range_c/front.hpp | 2 +- .../boost/mpl/aux_/range_c/iterator.hpp | 2 +- .../boost_idb/boost/mpl/aux_/range_c/size.hpp | 2 +- .../boost_idb/boost/mpl/aux_/range_c/tag.hpp | 2 +- .../boost/mpl/aux_/reverse_fold_impl.hpp | 2 +- .../boost/mpl/aux_/reverse_fold_impl_body.hpp | 2 +- .../boost/mpl/aux_/reverse_iter_fold_impl.hpp | 2 +- .../boost/mpl/aux_/sequence_wrapper.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/shift_op.hpp | 2 +- .../boost/mpl/aux_/single_element_iter.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/size_impl.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/sort_impl.hpp | 2 +- .../boost_idb/boost/mpl/aux_/static_cast.hpp | 2 +- .../boost/mpl/aux_/template_arity.hpp | 2 +- .../boost/mpl/aux_/template_arity_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/test.hpp | 2 +- .../boost_idb/boost/mpl/aux_/test/assert.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/test/data.hpp | 2 +- .../boost/mpl/aux_/test/test_case.hpp | 2 +- .../boost/mpl/aux_/traits_lambda_spec.hpp | 2 +- .../boost/mpl/aux_/transform_iter.hpp | 2 +- .../boost_idb/boost/mpl/aux_/type_wrapper.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/unwrap.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/value_wknd.hpp | 2 +- utils/boost_idb/boost/mpl/aux_/yes_no.hpp | 2 +- utils/boost_idb/boost/mpl/back.hpp | 2 +- utils/boost_idb/boost/mpl/back_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/back_inserter.hpp | 2 +- utils/boost_idb/boost/mpl/base.hpp | 2 +- utils/boost_idb/boost/mpl/begin.hpp | 2 +- utils/boost_idb/boost/mpl/begin_end.hpp | 2 +- utils/boost_idb/boost/mpl/begin_end_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/bind.hpp | 2 +- utils/boost_idb/boost/mpl/bind_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/bitand.hpp | 2 +- utils/boost_idb/boost/mpl/bitor.hpp | 2 +- utils/boost_idb/boost/mpl/bitwise.hpp | 2 +- utils/boost_idb/boost/mpl/bitxor.hpp | 2 +- utils/boost_idb/boost/mpl/bool.hpp | 2 +- utils/boost_idb/boost/mpl/bool_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/clear.hpp | 2 +- utils/boost_idb/boost/mpl/clear_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/comparison.hpp | 2 +- utils/boost_idb/boost/mpl/contains.hpp | 2 +- utils/boost_idb/boost/mpl/contains_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/copy.hpp | 2 +- utils/boost_idb/boost/mpl/copy_if.hpp | 2 +- utils/boost_idb/boost/mpl/count.hpp | 2 +- utils/boost_idb/boost/mpl/count_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/count_if.hpp | 2 +- utils/boost_idb/boost/mpl/deque.hpp | 2 +- utils/boost_idb/boost/mpl/deref.hpp | 2 +- utils/boost_idb/boost/mpl/distance.hpp | 2 +- utils/boost_idb/boost/mpl/distance_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/divides.hpp | 2 +- utils/boost_idb/boost/mpl/empty.hpp | 2 +- utils/boost_idb/boost/mpl/empty_base.hpp | 2 +- utils/boost_idb/boost/mpl/empty_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/empty_sequence.hpp | 2 +- utils/boost_idb/boost/mpl/end.hpp | 2 +- utils/boost_idb/boost/mpl/equal.hpp | 2 +- utils/boost_idb/boost/mpl/equal_to.hpp | 2 +- utils/boost_idb/boost/mpl/erase.hpp | 2 +- utils/boost_idb/boost/mpl/erase_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/erase_key.hpp | 2 +- utils/boost_idb/boost/mpl/erase_key_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/eval_if.hpp | 2 +- utils/boost_idb/boost/mpl/filter_view.hpp | 2 +- utils/boost_idb/boost/mpl/find.hpp | 2 +- utils/boost_idb/boost/mpl/find_if.hpp | 2 +- utils/boost_idb/boost/mpl/fold.hpp | 2 +- utils/boost_idb/boost/mpl/for_each.hpp | 2 +- utils/boost_idb/boost/mpl/front.hpp | 2 +- utils/boost_idb/boost/mpl/front_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/front_inserter.hpp | 2 +- utils/boost_idb/boost/mpl/greater.hpp | 2 +- utils/boost_idb/boost/mpl/greater_equal.hpp | 2 +- utils/boost_idb/boost/mpl/has_key.hpp | 2 +- utils/boost_idb/boost/mpl/has_key_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/has_xxx.hpp | 2 +- utils/boost_idb/boost/mpl/identity.hpp | 2 +- utils/boost_idb/boost/mpl/if.hpp | 2 +- utils/boost_idb/boost/mpl/index_if.hpp | 2 +- utils/boost_idb/boost/mpl/index_of.hpp | 2 +- utils/boost_idb/boost/mpl/inherit.hpp | 2 +- .../boost_idb/boost/mpl/inherit_linearly.hpp | 2 +- utils/boost_idb/boost/mpl/insert.hpp | 2 +- utils/boost_idb/boost/mpl/insert_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/insert_range.hpp | 2 +- .../boost_idb/boost/mpl/insert_range_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/inserter.hpp | 2 +- utils/boost_idb/boost/mpl/int.hpp | 2 +- utils/boost_idb/boost/mpl/int_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/integral_c.hpp | 2 +- utils/boost_idb/boost/mpl/integral_c_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/integral_c_tag.hpp | 2 +- utils/boost_idb/boost/mpl/is_placeholder.hpp | 2 +- utils/boost_idb/boost/mpl/is_sequence.hpp | 2 +- utils/boost_idb/boost/mpl/iter_fold.hpp | 2 +- utils/boost_idb/boost/mpl/iter_fold_if.hpp | 2 +- .../boost_idb/boost/mpl/iterator_category.hpp | 2 +- utils/boost_idb/boost/mpl/iterator_range.hpp | 2 +- utils/boost_idb/boost/mpl/iterator_tags.hpp | 2 +- utils/boost_idb/boost/mpl/joint_view.hpp | 2 +- utils/boost_idb/boost/mpl/key_type.hpp | 2 +- utils/boost_idb/boost/mpl/key_type_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/lambda.hpp | 2 +- utils/boost_idb/boost/mpl/lambda_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/less.hpp | 2 +- utils/boost_idb/boost/mpl/less_equal.hpp | 2 +- utils/boost_idb/boost/mpl/limits/arity.hpp | 2 +- utils/boost_idb/boost/mpl/limits/list.hpp | 2 +- utils/boost_idb/boost/mpl/limits/map.hpp | 2 +- utils/boost_idb/boost/mpl/limits/set.hpp | 2 +- .../boost_idb/boost/mpl/limits/unrolling.hpp | 2 +- utils/boost_idb/boost/mpl/limits/vector.hpp | 2 +- utils/boost_idb/boost/mpl/list.hpp | 2 +- .../boost_idb/boost/mpl/list/aux_/O1_size.hpp | 2 +- .../boost/mpl/list/aux_/begin_end.hpp | 2 +- utils/boost_idb/boost/mpl/list/aux_/clear.hpp | 2 +- utils/boost_idb/boost/mpl/list/aux_/empty.hpp | 2 +- utils/boost_idb/boost/mpl/list/aux_/front.hpp | 2 +- .../mpl/list/aux_/include_preprocessed.hpp | 2 +- utils/boost_idb/boost/mpl/list/aux_/item.hpp | 2 +- .../boost/mpl/list/aux_/iterator.hpp | 2 +- .../boost/mpl/list/aux_/numbered.hpp | 2 +- .../boost/mpl/list/aux_/numbered_c.hpp | 2 +- .../boost/mpl/list/aux_/pop_front.hpp | 2 +- .../boost/mpl/list/aux_/push_back.hpp | 2 +- .../boost/mpl/list/aux_/push_front.hpp | 2 +- utils/boost_idb/boost/mpl/list/aux_/size.hpp | 2 +- utils/boost_idb/boost/mpl/list/aux_/tag.hpp | 2 +- utils/boost_idb/boost/mpl/list/list0.hpp | 2 +- utils/boost_idb/boost/mpl/list/list0_c.hpp | 2 +- utils/boost_idb/boost/mpl/list/list10.hpp | 2 +- utils/boost_idb/boost/mpl/list/list10_c.hpp | 2 +- utils/boost_idb/boost/mpl/list/list20.hpp | 2 +- utils/boost_idb/boost/mpl/list/list20_c.hpp | 2 +- utils/boost_idb/boost/mpl/list/list30.hpp | 2 +- utils/boost_idb/boost/mpl/list/list30_c.hpp | 2 +- utils/boost_idb/boost/mpl/list/list40.hpp | 2 +- utils/boost_idb/boost/mpl/list/list40_c.hpp | 2 +- utils/boost_idb/boost/mpl/list/list50.hpp | 2 +- utils/boost_idb/boost/mpl/list/list50_c.hpp | 2 +- utils/boost_idb/boost/mpl/list_c.hpp | 2 +- utils/boost_idb/boost/mpl/logical.hpp | 2 +- utils/boost_idb/boost/mpl/long.hpp | 2 +- utils/boost_idb/boost/mpl/long_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/lower_bound.hpp | 2 +- utils/boost_idb/boost/mpl/map.hpp | 2 +- .../boost_idb/boost/mpl/map/aux_/at_impl.hpp | 2 +- .../boost/mpl/map/aux_/begin_end_impl.hpp | 2 +- .../boost/mpl/map/aux_/clear_impl.hpp | 2 +- .../boost/mpl/map/aux_/contains_impl.hpp | 2 +- .../boost/mpl/map/aux_/empty_impl.hpp | 2 +- .../boost/mpl/map/aux_/erase_impl.hpp | 2 +- .../boost/mpl/map/aux_/erase_key_impl.hpp | 2 +- .../boost/mpl/map/aux_/has_key_impl.hpp | 2 +- .../mpl/map/aux_/include_preprocessed.hpp | 2 +- .../boost/mpl/map/aux_/insert_impl.hpp | 2 +- utils/boost_idb/boost/mpl/map/aux_/item.hpp | 2 +- .../boost_idb/boost/mpl/map/aux_/iterator.hpp | 2 +- .../boost/mpl/map/aux_/key_type_impl.hpp | 2 +- utils/boost_idb/boost/mpl/map/aux_/map0.hpp | 2 +- .../boost_idb/boost/mpl/map/aux_/numbered.hpp | 2 +- .../boost/mpl/map/aux_/size_impl.hpp | 2 +- utils/boost_idb/boost/mpl/map/aux_/tag.hpp | 2 +- .../boost/mpl/map/aux_/value_type_impl.hpp | 2 +- utils/boost_idb/boost/mpl/map/map0.hpp | 2 +- utils/boost_idb/boost/mpl/map/map10.hpp | 2 +- utils/boost_idb/boost/mpl/map/map20.hpp | 2 +- utils/boost_idb/boost/mpl/map/map30.hpp | 2 +- utils/boost_idb/boost/mpl/map/map40.hpp | 2 +- utils/boost_idb/boost/mpl/map/map50.hpp | 2 +- utils/boost_idb/boost/mpl/math/fixed_c.hpp | 2 +- utils/boost_idb/boost/mpl/math/is_even.hpp | 2 +- utils/boost_idb/boost/mpl/math/rational_c.hpp | 2 +- utils/boost_idb/boost/mpl/max.hpp | 2 +- utils/boost_idb/boost/mpl/max_element.hpp | 2 +- utils/boost_idb/boost/mpl/min.hpp | 2 +- utils/boost_idb/boost/mpl/min_element.hpp | 2 +- utils/boost_idb/boost/mpl/min_max.hpp | 2 +- utils/boost_idb/boost/mpl/minus.hpp | 2 +- utils/boost_idb/boost/mpl/modulus.hpp | 2 +- utils/boost_idb/boost/mpl/multiplies.hpp | 2 +- .../boost/mpl/multiset/aux_/count_impl.hpp | 2 +- .../boost/mpl/multiset/aux_/insert_impl.hpp | 2 +- .../boost/mpl/multiset/aux_/item.hpp | 2 +- .../boost/mpl/multiset/aux_/multiset0.hpp | 2 +- .../boost_idb/boost/mpl/multiset/aux_/tag.hpp | 2 +- .../boost/mpl/multiset/multiset0.hpp | 2 +- utils/boost_idb/boost/mpl/negate.hpp | 2 +- utils/boost_idb/boost/mpl/next.hpp | 2 +- utils/boost_idb/boost/mpl/next_prior.hpp | 2 +- utils/boost_idb/boost/mpl/not.hpp | 2 +- utils/boost_idb/boost/mpl/not_equal_to.hpp | 2 +- utils/boost_idb/boost/mpl/numeric_cast.hpp | 2 +- utils/boost_idb/boost/mpl/or.hpp | 2 +- utils/boost_idb/boost/mpl/order.hpp | 2 +- utils/boost_idb/boost/mpl/order_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/pair.hpp | 2 +- utils/boost_idb/boost/mpl/pair_view.hpp | 2 +- utils/boost_idb/boost/mpl/partition.hpp | 2 +- utils/boost_idb/boost/mpl/placeholders.hpp | 2 +- utils/boost_idb/boost/mpl/plus.hpp | 2 +- utils/boost_idb/boost/mpl/pop_back.hpp | 2 +- utils/boost_idb/boost/mpl/pop_back_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/pop_front.hpp | 2 +- utils/boost_idb/boost/mpl/pop_front_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/print.hpp | 2 +- utils/boost_idb/boost/mpl/prior.hpp | 2 +- utils/boost_idb/boost/mpl/protect.hpp | 2 +- utils/boost_idb/boost/mpl/push_back.hpp | 2 +- utils/boost_idb/boost/mpl/push_back_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/push_front.hpp | 2 +- utils/boost_idb/boost/mpl/push_front_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/quote.hpp | 2 +- utils/boost_idb/boost/mpl/range_c.hpp | 2 +- utils/boost_idb/boost/mpl/remove.hpp | 2 +- utils/boost_idb/boost/mpl/remove_if.hpp | 2 +- utils/boost_idb/boost/mpl/replace.hpp | 2 +- utils/boost_idb/boost/mpl/replace_if.hpp | 2 +- utils/boost_idb/boost/mpl/reverse.hpp | 2 +- utils/boost_idb/boost/mpl/reverse_fold.hpp | 2 +- .../boost_idb/boost/mpl/reverse_iter_fold.hpp | 2 +- utils/boost_idb/boost/mpl/same_as.hpp | 2 +- utils/boost_idb/boost/mpl/sequence_tag.hpp | 2 +- .../boost_idb/boost/mpl/sequence_tag_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/set.hpp | 2 +- .../boost_idb/boost/mpl/set/aux_/at_impl.hpp | 2 +- .../boost/mpl/set/aux_/begin_end_impl.hpp | 2 +- .../boost/mpl/set/aux_/clear_impl.hpp | 2 +- .../boost/mpl/set/aux_/empty_impl.hpp | 2 +- .../boost/mpl/set/aux_/erase_impl.hpp | 2 +- .../boost/mpl/set/aux_/erase_key_impl.hpp | 2 +- .../boost/mpl/set/aux_/has_key_impl.hpp | 2 +- .../mpl/set/aux_/include_preprocessed.hpp | 2 +- .../boost/mpl/set/aux_/insert_impl.hpp | 2 +- utils/boost_idb/boost/mpl/set/aux_/item.hpp | 2 +- .../boost_idb/boost/mpl/set/aux_/iterator.hpp | 2 +- .../boost/mpl/set/aux_/key_type_impl.hpp | 2 +- .../boost_idb/boost/mpl/set/aux_/numbered.hpp | 2 +- .../boost/mpl/set/aux_/numbered_c.hpp | 2 +- utils/boost_idb/boost/mpl/set/aux_/set0.hpp | 2 +- .../boost/mpl/set/aux_/size_impl.hpp | 2 +- utils/boost_idb/boost/mpl/set/aux_/tag.hpp | 2 +- .../boost/mpl/set/aux_/value_type_impl.hpp | 2 +- utils/boost_idb/boost/mpl/set/set0.hpp | 2 +- utils/boost_idb/boost/mpl/set/set0_c.hpp | 2 +- utils/boost_idb/boost/mpl/set/set10.hpp | 2 +- utils/boost_idb/boost/mpl/set/set10_c.hpp | 2 +- utils/boost_idb/boost/mpl/set/set20.hpp | 2 +- utils/boost_idb/boost/mpl/set/set20_c.hpp | 2 +- utils/boost_idb/boost/mpl/set/set30.hpp | 2 +- utils/boost_idb/boost/mpl/set/set30_c.hpp | 2 +- utils/boost_idb/boost/mpl/set/set40.hpp | 2 +- utils/boost_idb/boost/mpl/set/set40_c.hpp | 2 +- utils/boost_idb/boost/mpl/set/set50.hpp | 2 +- utils/boost_idb/boost/mpl/set/set50_c.hpp | 2 +- utils/boost_idb/boost/mpl/set_c.hpp | 2 +- utils/boost_idb/boost/mpl/shift_left.hpp | 2 +- utils/boost_idb/boost/mpl/shift_right.hpp | 2 +- utils/boost_idb/boost/mpl/single_view.hpp | 2 +- utils/boost_idb/boost/mpl/size.hpp | 2 +- utils/boost_idb/boost/mpl/size_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/size_t.hpp | 2 +- utils/boost_idb/boost/mpl/size_t_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/sizeof.hpp | 2 +- utils/boost_idb/boost/mpl/sort.hpp | 2 +- .../boost_idb/boost/mpl/stable_partition.hpp | 2 +- utils/boost_idb/boost/mpl/switch.hpp | 2 +- utils/boost_idb/boost/mpl/tag.hpp | 2 +- utils/boost_idb/boost/mpl/times.hpp | 2 +- utils/boost_idb/boost/mpl/transform.hpp | 2 +- utils/boost_idb/boost/mpl/transform_view.hpp | 2 +- utils/boost_idb/boost/mpl/unique.hpp | 2 +- utils/boost_idb/boost/mpl/unpack_args.hpp | 2 +- utils/boost_idb/boost/mpl/upper_bound.hpp | 2 +- utils/boost_idb/boost/mpl/value_type.hpp | 2 +- utils/boost_idb/boost/mpl/value_type_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/vector.hpp | 2 +- .../boost/mpl/vector/aux_/O1_size.hpp | 2 +- utils/boost_idb/boost/mpl/vector/aux_/at.hpp | 2 +- .../boost_idb/boost/mpl/vector/aux_/back.hpp | 2 +- .../boost/mpl/vector/aux_/begin_end.hpp | 2 +- .../boost_idb/boost/mpl/vector/aux_/clear.hpp | 2 +- .../boost_idb/boost/mpl/vector/aux_/empty.hpp | 2 +- .../boost_idb/boost/mpl/vector/aux_/front.hpp | 2 +- .../mpl/vector/aux_/include_preprocessed.hpp | 2 +- .../boost_idb/boost/mpl/vector/aux_/item.hpp | 2 +- .../boost/mpl/vector/aux_/iterator.hpp | 2 +- .../boost/mpl/vector/aux_/numbered.hpp | 2 +- .../boost/mpl/vector/aux_/numbered_c.hpp | 2 +- .../boost/mpl/vector/aux_/pop_back.hpp | 2 +- .../boost/mpl/vector/aux_/pop_front.hpp | 2 +- .../boost/mpl/vector/aux_/push_back.hpp | 2 +- .../boost/mpl/vector/aux_/push_front.hpp | 2 +- .../boost_idb/boost/mpl/vector/aux_/size.hpp | 2 +- utils/boost_idb/boost/mpl/vector/aux_/tag.hpp | 2 +- .../boost/mpl/vector/aux_/vector0.hpp | 2 +- utils/boost_idb/boost/mpl/vector/vector0.hpp | 2 +- .../boost_idb/boost/mpl/vector/vector0_c.hpp | 2 +- utils/boost_idb/boost/mpl/vector/vector10.hpp | 2 +- .../boost_idb/boost/mpl/vector/vector10_c.hpp | 2 +- utils/boost_idb/boost/mpl/vector/vector20.hpp | 2 +- .../boost_idb/boost/mpl/vector/vector20_c.hpp | 2 +- utils/boost_idb/boost/mpl/vector/vector30.hpp | 2 +- .../boost_idb/boost/mpl/vector/vector30_c.hpp | 2 +- utils/boost_idb/boost/mpl/vector/vector40.hpp | 2 +- .../boost_idb/boost/mpl/vector/vector40_c.hpp | 2 +- utils/boost_idb/boost/mpl/vector/vector50.hpp | 2 +- .../boost_idb/boost/mpl/vector/vector50_c.hpp | 2 +- utils/boost_idb/boost/mpl/vector_c.hpp | 2 +- utils/boost_idb/boost/mpl/void.hpp | 2 +- utils/boost_idb/boost/mpl/void_fwd.hpp | 2 +- utils/boost_idb/boost/mpl/zip_view.hpp | 2 +- utils/boost_idb/boost/multi_array.hpp | 499 + .../boost_idb/boost/multi_index_container.hpp | 1143 ++ .../boost/multi_index_container_fwd.hpp | 121 + utils/boost_idb/boost/non_type.hpp | 27 + utils/boost_idb/boost/noncopyable.hpp | 18 +- utils/boost_idb/boost/nondet_random.hpp | 142 + utils/boost_idb/boost/none.hpp | 2 +- .../boost/numeric/conversion/bounds.hpp | 24 - .../boost/numeric/conversion/cast.hpp | 61 - .../numeric/conversion/conversion_traits.hpp | 39 - .../boost/numeric/conversion/converter.hpp | 68 - .../numeric/conversion/converter_policies.hpp | 194 - .../numeric/conversion/detail/bounds.hpp | 58 - .../conversion/detail/conversion_traits.hpp | 97 - .../numeric/conversion/detail/converter.hpp | 602 - .../conversion/detail/int_float_mixture.hpp | 72 - .../conversion/detail/is_subranged.hpp | 234 - .../boost/numeric/conversion/detail/meta.hpp | 120 - .../conversion/detail/numeric_cast_traits.hpp | 138 - .../conversion/detail/old_numeric_cast.hpp | 339 - .../numeric_cast_traits_common.hpp | 1741 -- .../numeric_cast_traits_long_long.hpp | 347 - .../conversion/detail/sign_mixture.hpp | 72 - .../conversion/detail/udt_builtin_mixture.hpp | 69 - .../numeric/conversion/int_float_mixture.hpp | 30 - .../conversion/int_float_mixture_enum.hpp | 29 - .../boost/numeric/conversion/is_subranged.hpp | 27 - .../conversion/numeric_cast_traits.hpp | 31 - .../boost/numeric/conversion/sign_mixture.hpp | 30 - .../numeric/conversion/sign_mixture_enum.hpp | 29 - .../conversion/udt_builtin_mixture.hpp | 28 - .../conversion/udt_builtin_mixture_enum.hpp | 26 - utils/boost_idb/boost/numeric/interval.hpp | 32 - .../boost/numeric/interval/arith.hpp | 305 - .../boost/numeric/interval/arith2.hpp | 305 - .../boost/numeric/interval/arith3.hpp | 69 - .../boost/numeric/interval/checking.hpp | 130 - .../boost/numeric/interval/compare.hpp | 19 - .../numeric/interval/compare/certain.hpp | 113 - .../numeric/interval/compare/explicit.hpp | 248 - .../interval/compare/lexicographic.hpp | 122 - .../numeric/interval/compare/possible.hpp | 113 - .../boost/numeric/interval/compare/set.hpp | 101 - .../numeric/interval/compare/tribool.hpp | 138 - .../boost/numeric/interval/constants.hpp | 85 - .../detail/alpha_rounding_control.hpp | 113 - .../interval/detail/bcc_rounding_control.hpp | 57 - .../boost/numeric/interval/detail/bugs.hpp | 79 - .../interval/detail/c99_rounding_control.hpp | 50 - .../detail/c99sub_rounding_control.hpp | 43 - .../numeric/interval/detail/division.hpp | 194 - .../interval/detail/ia64_rounding_control.hpp | 83 - .../interval/detail/interval_prototype.hpp | 41 - .../interval/detail/msvc_rounding_control.hpp | 100 - .../interval/detail/ppc_rounding_control.hpp | 99 - .../detail/sparc_rounding_control.hpp | 112 - .../numeric/interval/detail/test_input.hpp | 76 - .../interval/detail/x86_rounding_control.hpp | 108 - .../detail/x86gcc_rounding_control.hpp | 51 - .../boost/numeric/interval/ext/integer.hpp | 70 - .../ext/x86_fast_rounding_control.hpp | 70 - .../boost/numeric/interval/hw_rounding.hpp | 70 - .../boost/numeric/interval/interval.hpp | 450 - utils/boost_idb/boost/numeric/interval/io.hpp | 41 - .../boost/numeric/interval/limits.hpp | 51 - .../boost/numeric/interval/policies.hpp | 75 - .../boost/numeric/interval/rounded_arith.hpp | 120 - .../boost/numeric/interval/rounded_transc.hpp | 140 - .../boost/numeric/interval/rounding.hpp | 101 - .../boost/numeric/interval/transc.hpp | 232 - .../boost/numeric/interval/utility.hpp | 337 - utils/boost_idb/boost/numeric/odeint.hpp | 75 - .../numeric/odeint/algebra/array_algebra.hpp | 265 - .../odeint/algebra/default_operations.hpp | 602 - .../odeint/algebra/detail/for_each.hpp | 165 - .../numeric/odeint/algebra/detail/macros.hpp | 43 - .../numeric/odeint/algebra/detail/reduce.hpp | 67 - .../numeric/odeint/algebra/fusion_algebra.hpp | 186 - .../numeric/odeint/algebra/range_algebra.hpp | 159 - .../odeint/algebra/vector_space_algebra.hpp | 156 - .../boost_idb/boost/numeric/odeint/config.hpp | 47 - .../odeint/external/gsl/gsl_wrapper.hpp | 229 - .../odeint/external/mkl/mkl_operations.hpp | 181 - .../external/mtl4/implicit_euler_mtl4.hpp | 162 - .../odeint/external/mtl4/mtl4_resize.hpp | 133 - .../odeint/external/thrust/thrust_algebra.hpp | 198 - .../external/thrust/thrust_operations.hpp | 252 - .../odeint/external/thrust/thrust_resize.hpp | 119 - .../odeint/external/vexcl/vexcl_resize.hpp | 92 - .../external/viennacl/viennacl_operations.hpp | 245 - .../external/viennacl/viennacl_resize.hpp | 65 - .../integrate/detail/integrate_adaptive.hpp | 154 - .../integrate/detail/integrate_const.hpp | 159 - .../integrate/detail/integrate_n_steps.hpp | 156 - .../integrate/detail/integrate_times.hpp | 166 - .../numeric/odeint/integrate/integrate.hpp | 105 - .../odeint/integrate/integrate_adaptive.hpp | 127 - .../odeint/integrate/integrate_const.hpp | 156 - .../odeint/integrate/integrate_n_steps.hpp | 124 - .../odeint/integrate/integrate_times.hpp | 131 - .../odeint/integrate/null_observer.hpp | 38 - .../odeint/integrate/observer_collection.hpp | 56 - .../odeint/stepper/adams_bashforth.hpp | 416 - .../stepper/adams_bashforth_moulton.hpp | 258 - .../numeric/odeint/stepper/adams_moulton.hpp | 195 - .../stepper/base/algebra_stepper_base.hpp | 91 - .../base/explicit_error_stepper_base.hpp | 560 - .../base/explicit_error_stepper_fsal_base.hpp | 658 - .../stepper/base/explicit_stepper_base.hpp | 383 - .../base/symplectic_rkn_stepper_base.hpp | 433 - .../numeric/odeint/stepper/bulirsch_stoer.hpp | 623 - .../stepper/bulirsch_stoer_dense_out.hpp | 812 - .../odeint/stepper/controlled_runge_kutta.hpp | 939 - .../odeint/stepper/controlled_step_result.hpp | 42 - .../stepper/dense_output_runge_kutta.hpp | 461 - .../detail/adams_bashforth_call_algebra.hpp | 151 - .../detail/adams_bashforth_coefficients.hpp | 168 - .../detail/adams_moulton_call_algebra.hpp | 142 - .../detail/adams_moulton_coefficients.hpp | 168 - .../stepper/detail/generic_rk_algorithm.hpp | 246 - .../detail/generic_rk_call_algebra.hpp | 263 - .../stepper/detail/generic_rk_operations.hpp | 252 - .../odeint/stepper/detail/rotating_buffer.hpp | 84 - .../boost/numeric/odeint/stepper/euler.hpp | 164 - .../stepper/explicit_error_generic_rk.hpp | 252 - .../odeint/stepper/explicit_generic_rk.hpp | 243 - .../numeric/odeint/stepper/generation.hpp | 36 - .../generation_controlled_runge_kutta.hpp | 53 - .../generation_dense_output_runge_kutta.hpp | 54 - .../generation/generation_rosenbrock4.hpp | 72 - .../generation_runge_kutta_cash_karp54.hpp | 47 - ...ration_runge_kutta_cash_karp54_classic.hpp | 48 - .../generation_runge_kutta_dopri5.hpp | 56 - .../generation_runge_kutta_fehlberg78.hpp | 46 - .../stepper/generation/make_controlled.hpp | 81 - .../stepper/generation/make_dense_output.hpp | 78 - .../numeric/odeint/stepper/implicit_euler.hpp | 169 - .../odeint/stepper/modified_midpoint.hpp | 312 - .../numeric/odeint/stepper/rosenbrock4.hpp | 345 - .../odeint/stepper/rosenbrock4_controller.hpp | 208 - .../stepper/rosenbrock4_dense_output.hpp | 199 - .../numeric/odeint/stepper/runge_kutta4.hpp | 179 - .../odeint/stepper/runge_kutta4_classic.hpp | 220 - .../stepper/runge_kutta_cash_karp54.hpp | 229 - .../runge_kutta_cash_karp54_classic.hpp | 286 - .../odeint/stepper/runge_kutta_dopri5.hpp | 400 - .../odeint/stepper/runge_kutta_fehlberg78.hpp | 372 - .../odeint/stepper/stepper_categories.hpp | 68 - .../odeint/stepper/symplectic_euler.hpp | 134 - .../symplectic_rkn_sb3a_m4_mclachlan.hpp | 154 - .../stepper/symplectic_rkn_sb3a_mclachlan.hpp | 158 - .../boost/numeric/odeint/util/bind.hpp | 53 - .../boost/numeric/odeint/util/copy.hpp | 75 - .../numeric/odeint/util/detail/is_range.hpp | 133 - .../odeint/util/detail/less_with_sign.hpp | 53 - .../boost/numeric/odeint/util/is_pair.hpp | 45 - .../numeric/odeint/util/is_resizeable.hpp | 84 - .../boost/numeric/odeint/util/resize.hpp | 107 - .../boost/numeric/odeint/util/resizer.hpp | 93 - .../numeric/odeint/util/same_instance.hpp | 56 - .../boost/numeric/odeint/util/same_size.hpp | 105 - .../numeric/odeint/util/state_wrapper.hpp | 50 - .../numeric/odeint/util/ublas_wrapper.hpp | 260 - .../boost/numeric/odeint/util/unit_helper.hpp | 152 - .../numeric/odeint/util/unwrap_reference.hpp | 87 - .../boost/numeric/odeint/version.hpp | 55 - .../boost/numeric/ublas/assignment.hpp | 1281 -- .../boost_idb/boost/numeric/ublas/banded.hpp | 2071 -- utils/boost_idb/boost/numeric/ublas/blas.hpp | 499 - .../boost/numeric/ublas/detail/concepts.hpp | 1540 -- .../boost/numeric/ublas/detail/config.hpp | 294 - .../numeric/ublas/detail/definitions.hpp | 212 - .../numeric/ublas/detail/documentation.hpp | 33 - .../boost/numeric/ublas/detail/duff.hpp | 56 - .../boost/numeric/ublas/detail/iterator.hpp | 1436 -- .../numeric/ublas/detail/matrix_assign.hpp | 1633 -- .../boost/numeric/ublas/detail/raw.hpp | 878 - .../ublas/detail/returntype_deduction.hpp | 174 - .../boost/numeric/ublas/detail/temporary.hpp | 33 - .../numeric/ublas/detail/vector_assign.hpp | 571 - .../boost_idb/boost/numeric/ublas/doxydoc.hpp | 58 - .../boost/numeric/ublas/exception.hpp | 297 - .../ublas/experimental/sparse_view.hpp | 316 - .../boost/numeric/ublas/expression_types.hpp | 506 - .../boost/numeric/ublas/functional.hpp | 2063 -- utils/boost_idb/boost/numeric/ublas/fwd.hpp | 217 - .../boost/numeric/ublas/hermitian.hpp | 2457 --- utils/boost_idb/boost/numeric/ublas/io.hpp | 355 - utils/boost_idb/boost/numeric/ublas/lu.hpp | 351 - .../boost_idb/boost/numeric/ublas/matrix.hpp | 4390 ---- .../boost/numeric/ublas/matrix_expression.hpp | 4952 ----- .../boost/numeric/ublas/matrix_proxy.hpp | 5113 ----- .../boost/numeric/ublas/matrix_sparse.hpp | 5421 ----- .../boost/numeric/ublas/operation.hpp | 851 - .../boost/numeric/ublas/operation/begin.hpp | 318 - .../boost/numeric/ublas/operation/c_array.hpp | 41 - .../boost/numeric/ublas/operation/end.hpp | 318 - .../numeric/ublas/operation/num_columns.hpp | 45 - .../numeric/ublas/operation/num_rows.hpp | 44 - .../boost/numeric/ublas/operation/size.hpp | 350 - .../boost/numeric/ublas/operation_blocked.hpp | 266 - .../boost/numeric/ublas/operation_sparse.hpp | 198 - .../boost/numeric/ublas/operations.hpp | 26 - .../boost_idb/boost/numeric/ublas/storage.hpp | 1918 -- .../boost/numeric/ublas/storage_sparse.hpp | 562 - .../boost/numeric/ublas/symmetric.hpp | 2134 -- utils/boost_idb/boost/numeric/ublas/tags.hpp | 37 - .../boost_idb/boost/numeric/ublas/traits.hpp | 752 - .../boost/numeric/ublas/traits/c_array.hpp | 110 - .../ublas/traits/const_iterator_type.hpp | 127 - .../numeric/ublas/traits/iterator_type.hpp | 126 - .../boost/numeric/ublas/triangular.hpp | 2604 --- .../boost_idb/boost/numeric/ublas/vector.hpp | 2077 -- .../boost/numeric/ublas/vector_expression.hpp | 1671 -- .../boost/numeric/ublas/vector_of_vector.hpp | 1258 -- .../boost/numeric/ublas/vector_proxy.hpp | 1647 -- .../boost/numeric/ublas/vector_sparse.hpp | 2167 -- utils/boost_idb/boost/operators.hpp | 4 +- utils/boost_idb/boost/optional/optional.hpp | 229 +- .../boost_idb/boost/optional/optional_fwd.hpp | 9 +- .../boost_idb/boost/optional/optional_io.hpp | 32 +- utils/boost_idb/boost/parameter.hpp | 21 + .../boost_idb/boost/pending/bucket_sorter.hpp | 134 - .../boost/pending/container_traits.hpp | 561 - utils/boost_idb/boost/pending/cstddef.hpp | 16 - .../boost/pending/detail/disjoint_sets.hpp | 88 - .../boost/pending/detail/int_iterator.hpp | 74 - .../boost/pending/detail/property.hpp | 21 - .../boost_idb/boost/pending/disjoint_sets.hpp | 220 - .../boost/pending/fenced_priority_queue.hpp | 152 - .../boost/pending/fibonacci_heap.hpp | 271 - .../boost_idb/boost/pending/indirect_cmp.hpp | 87 - .../boost_idb/boost/pending/integer_log2.hpp | 112 - utils/boost_idb/boost/pending/is_heap.hpp | 62 - .../boost/pending/iterator_adaptors.hpp | 6 - .../boost/pending/iterator_tests.hpp | 268 - utils/boost_idb/boost/pending/lowest_bit.hpp | 39 - .../boost_idb/boost/pending/mutable_heap.hpp | 64 - .../boost_idb/boost/pending/mutable_queue.hpp | 135 - utils/boost_idb/boost/pending/property.hpp | 270 - .../boost/pending/property_serialize.hpp | 70 - utils/boost_idb/boost/pending/queue.hpp | 118 - .../boost_idb/boost/pending/relaxed_heap.hpp | 644 - utils/boost_idb/boost/pending/stringtok.hpp | 116 - utils/boost_idb/boost/pointer_cast.hpp | 45 + utils/boost_idb/boost/pointer_to_other.hpp | 55 + utils/boost_idb/boost/predef.h | 19 - utils/boost_idb/boost/predef/architecture.h | 30 - .../boost/predef/architecture/alpha.h | 60 - .../boost_idb/boost/predef/architecture/arm.h | 58 - .../boost/predef/architecture/blackfin.h | 47 - .../boost/predef/architecture/convex.h | 67 - .../boost/predef/architecture/ia64.h | 49 - .../boost/predef/architecture/m68k.h | 83 - .../boost/predef/architecture/mips.h | 74 - .../boost/predef/architecture/parisc.h | 65 - .../boost_idb/boost/predef/architecture/ppc.h | 73 - .../boost/predef/architecture/pyramid.h | 43 - .../boost/predef/architecture/rs6k.h | 56 - .../boost/predef/architecture/sparc.h | 55 - .../boost/predef/architecture/superh.h | 68 - .../boost/predef/architecture/sys370.h | 44 - .../boost/predef/architecture/sys390.h | 44 - .../boost_idb/boost/predef/architecture/x86.h | 38 - .../boost/predef/architecture/x86/32.h | 87 - .../boost/predef/architecture/x86/64.h | 50 - utils/boost_idb/boost/predef/architecture/z.h | 43 - utils/boost_idb/boost/predef/compiler.h | 41 - .../boost_idb/boost/predef/compiler/borland.h | 53 - utils/boost_idb/boost/predef/compiler/clang.h | 46 - .../boost_idb/boost/predef/compiler/comeau.h | 51 - .../boost_idb/boost/predef/compiler/compaq.h | 56 - utils/boost_idb/boost/predef/compiler/diab.h | 46 - .../boost/predef/compiler/digitalmars.h | 46 - .../boost_idb/boost/predef/compiler/dignus.h | 46 - utils/boost_idb/boost/predef/compiler/edg.h | 46 - .../boost_idb/boost/predef/compiler/ekopath.h | 47 - utils/boost_idb/boost/predef/compiler/gcc.h | 54 - .../boost_idb/boost/predef/compiler/gcc_xml.h | 42 - .../boost/predef/compiler/greenhills.h | 56 - .../boost_idb/boost/predef/compiler/hp_acc.h | 51 - utils/boost_idb/boost/predef/compiler/iar.h | 46 - utils/boost_idb/boost/predef/compiler/ibm.h | 62 - utils/boost_idb/boost/predef/compiler/intel.h | 55 - utils/boost_idb/boost/predef/compiler/kai.h | 46 - utils/boost_idb/boost/predef/compiler/llvm.h | 43 - .../boost/predef/compiler/metaware.h | 43 - .../boost/predef/compiler/metrowerks.h | 67 - .../boost/predef/compiler/microtec.h | 43 - utils/boost_idb/boost/predef/compiler/mpw.h | 53 - utils/boost_idb/boost/predef/compiler/palm.h | 46 - utils/boost_idb/boost/predef/compiler/pgi.h | 50 - .../boost/predef/compiler/sgi_mipspro.h | 56 - .../boost_idb/boost/predef/compiler/sunpro.h | 56 - .../boost_idb/boost/predef/compiler/tendra.h | 43 - .../boost_idb/boost/predef/compiler/visualc.h | 64 - .../boost_idb/boost/predef/compiler/watcom.h | 46 - .../boost_idb/boost/predef/detail/_cassert.h | 17 - .../boost/predef/detail/_exception.h | 15 - .../boost/predef/detail/endian_compat.h | 26 - .../boost/predef/detail/os_detected.h | 10 - utils/boost_idb/boost/predef/detail/test.h | 17 - utils/boost_idb/boost/predef/language.h | 15 - utils/boost_idb/boost/predef/language/objc.h | 43 - utils/boost_idb/boost/predef/language/stdc.h | 54 - .../boost_idb/boost/predef/language/stdcpp.h | 124 - utils/boost_idb/boost/predef/library.h | 14 - utils/boost_idb/boost/predef/library/c.h | 18 - .../boost/predef/library/c/_prefix.h | 13 - utils/boost_idb/boost/predef/library/c/gnu.h | 62 - utils/boost_idb/boost/predef/library/c/uc.h | 48 - utils/boost_idb/boost/predef/library/c/vms.h | 48 - utils/boost_idb/boost/predef/library/c/zos.h | 57 - utils/boost_idb/boost/predef/library/std.h | 23 - .../boost/predef/library/std/_prefix.h | 23 - .../boost_idb/boost/predef/library/std/cxx.h | 47 - .../boost/predef/library/std/dinkumware.h | 53 - .../boost/predef/library/std/libcomo.h | 48 - .../boost/predef/library/std/modena.h | 46 - .../boost_idb/boost/predef/library/std/msl.h | 54 - .../boost/predef/library/std/roguewave.h | 57 - .../boost_idb/boost/predef/library/std/sgi.h | 52 - .../boost/predef/library/std/stdcpp3.h | 54 - .../boost/predef/library/std/stlport.h | 60 - .../boost/predef/library/std/vacpp.h | 45 - utils/boost_idb/boost/predef/make.h | 87 - utils/boost_idb/boost/predef/os.h | 28 - utils/boost_idb/boost/predef/os/aix.h | 67 - utils/boost_idb/boost/predef/os/amigaos.h | 47 - utils/boost_idb/boost/predef/os/android.h | 46 - utils/boost_idb/boost/predef/os/beos.h | 46 - utils/boost_idb/boost/predef/os/bsd.h | 95 - utils/boost_idb/boost/predef/os/bsd/bsdi.h | 48 - .../boost_idb/boost/predef/os/bsd/dragonfly.h | 50 - utils/boost_idb/boost/predef/os/bsd/free.h | 60 - utils/boost_idb/boost/predef/os/bsd/net.h | 84 - utils/boost_idb/boost/predef/os/bsd/open.h | 171 - utils/boost_idb/boost/predef/os/cygwin.h | 46 - utils/boost_idb/boost/predef/os/hpux.h | 48 - utils/boost_idb/boost/predef/os/irix.h | 47 - utils/boost_idb/boost/predef/os/linux.h | 47 - utils/boost_idb/boost/predef/os/macos.h | 58 - utils/boost_idb/boost/predef/os/os400.h | 46 - utils/boost_idb/boost/predef/os/qnxnto.h | 60 - utils/boost_idb/boost/predef/os/solaris.h | 47 - utils/boost_idb/boost/predef/os/unix.h | 79 - utils/boost_idb/boost/predef/os/vms.h | 53 - utils/boost_idb/boost/predef/os/windows.h | 51 - utils/boost_idb/boost/predef/other.h | 14 - utils/boost_idb/boost/predef/other/endian.h | 205 - utils/boost_idb/boost/predef/platform.h | 14 - utils/boost_idb/boost/predef/platform/mingw.h | 59 - utils/boost_idb/boost/predef/version_number.h | 54 - utils/boost_idb/boost/preprocessor/array.hpp | 13 +- .../boost/preprocessor/array/enum.hpp | 33 - .../boost/preprocessor/array/to_list.hpp | 33 - .../boost/preprocessor/array/to_seq.hpp | 33 - .../boost/preprocessor/array/to_tuple.hpp | 22 - utils/boost_idb/boost/preprocessor/cat.hpp | 4 +- .../boost/preprocessor/config/config.hpp | 43 +- .../boost/preprocessor/config/limits.hpp | 3 +- .../boost/preprocessor/facilities.hpp | 10 +- .../preprocessor/facilities/overload.hpp | 25 - .../iteration/detail/iter/forward1.hpp | 6 +- .../iteration/detail/iter/forward2.hpp | 6 +- .../iteration/detail/iter/forward3.hpp | 6 +- .../iteration/detail/iter/forward4.hpp | 6 +- .../iteration/detail/iter/forward5.hpp | 6 +- .../boost/preprocessor/iteration/iterate.hpp | 6 +- .../boost_idb/boost/preprocessor/library.hpp | 10 +- utils/boost_idb/boost/preprocessor/list.hpp | 2 - .../boost/preprocessor/list/to_array.hpp | 123 - .../boost/preprocessor/list/to_seq.hpp | 32 - utils/boost_idb/boost/preprocessor/seq.hpp | 10 +- .../boost_idb/boost/preprocessor/seq/cat.hpp | 9 +- .../seq/detail/binary_transform.hpp | 40 - .../boost_idb/boost/preprocessor/seq/size.hpp | 1 + .../boost/preprocessor/seq/to_list.hpp | 29 - utils/boost_idb/boost/preprocessor/tuple.hpp | 4 - .../boost/preprocessor/tuple/eat.hpp | 117 +- .../boost/preprocessor/tuple/elem.hpp | 516 +- .../boost/preprocessor/tuple/enum.hpp | 22 - .../boost/preprocessor/tuple/rem.hpp | 157 +- .../boost/preprocessor/tuple/reverse.hpp | 126 +- .../boost/preprocessor/tuple/size.hpp | 28 - .../boost/preprocessor/tuple/to_array.hpp | 37 - .../boost/preprocessor/tuple/to_list.hpp | 126 +- .../boost/preprocessor/tuple/to_seq.hpp | 132 +- .../boost_idb/boost/preprocessor/variadic.hpp | 23 - .../boost/preprocessor/variadic/elem.hpp | 94 - .../boost/preprocessor/variadic/size.hpp | 30 - .../boost/preprocessor/variadic/to_array.hpp | 32 - .../boost/preprocessor/variadic/to_list.hpp | 25 - .../boost/preprocessor/variadic/to_seq.hpp | 25 - .../boost/preprocessor/variadic/to_tuple.hpp | 24 - utils/boost_idb/boost/program_options.hpp | 25 + utils/boost_idb/boost/progress.hpp | 4 +- .../boost/ptr_container/indirect_fun.hpp | 34 +- utils/boost_idb/boost/python.hpp | 73 + utils/boost_idb/boost/random.hpp | 63 +- .../boost/random/additive_combine.hpp | 283 - .../boost/random/bernoulli_distribution.hpp | 197 - .../boost/random/binomial_distribution.hpp | 422 - .../boost/random/cauchy_distribution.hpp | 214 - .../boost/random/chi_squared_distribution.hpp | 209 - .../boost/random/detail/auto_link.hpp | 42 - .../boost_idb/boost/random/detail/config.hpp | 18 - .../boost/random/detail/const_mod.hpp | 216 - .../boost/random/detail/disable_warnings.hpp | 23 - .../boost/random/detail/enable_warnings.hpp | 18 - .../boost/random/detail/generator_bits.hpp | 36 - .../random/detail/generator_seed_seq.hpp | 40 - .../boost/random/detail/integer_log2.hpp | 84 - .../boost/random/detail/iterator_mixin.hpp | 45 - .../boost/random/detail/large_arithmetic.hpp | 122 - .../boost/random/detail/operators.hpp | 84 - .../boost/random/detail/ptr_helper.hpp | 94 - utils/boost_idb/boost/random/detail/seed.hpp | 114 - .../boost/random/detail/seed_impl.hpp | 397 - .../random/detail/signed_unsigned_tools.hpp | 89 - .../boost/random/detail/uniform_int_float.hpp | 76 - .../boost/random/detail/vector_io.hpp | 75 - .../boost_idb/boost/random/discard_block.hpp | 240 - .../boost/random/discrete_distribution.hpp | 453 - .../boost/random/exponential_distribution.hpp | 182 - .../random/extreme_value_distribution.hpp | 177 - .../boost/random/fisher_f_distribution.hpp | 183 - .../boost/random/gamma_distribution.hpp | 292 - .../boost/random/generate_canonical.hpp | 97 - .../boost/random/geometric_distribution.hpp | 267 - .../boost/random/independent_bits.hpp | 260 - .../boost/random/inversive_congruential.hpp | 267 - .../boost/random/lagged_fibonacci.hpp | 536 - .../boost/random/linear_congruential.hpp | 466 - .../boost/random/linear_feedback_shift.hpp | 217 - .../boost/random/lognormal_distribution.hpp | 254 - .../boost/random/mersenne_twister.hpp | 545 - .../random/negative_binomial_distribution.hpp | 220 - .../boost/random/normal_distribution.hpp | 223 - .../piecewise_constant_distribution.hpp | 466 - .../random/piecewise_linear_distribution.hpp | 530 - .../boost/random/poisson_distribution.hpp | 360 - .../boost_idb/boost/random/random_device.hpp | 142 - .../boost/random/random_number_generator.hpp | 73 - utils/boost_idb/boost/random/ranlux.hpp | 99 - utils/boost_idb/boost/random/seed_seq.hpp | 118 - .../boost_idb/boost/random/shuffle_order.hpp | 269 - .../boost_idb/boost/random/shuffle_output.hpp | 51 - .../boost/random/student_t_distribution.hpp | 180 - .../boost/random/subtract_with_carry.hpp | 613 - utils/boost_idb/boost/random/taus88.hpp | 45 - .../boost/random/triangle_distribution.hpp | 232 - utils/boost_idb/boost/random/uniform_01.hpp | 277 - utils/boost_idb/boost/random/uniform_int.hpp | 99 - .../boost/random/uniform_int_distribution.hpp | 400 - .../boost/random/uniform_on_sphere.hpp | 229 - utils/boost_idb/boost/random/uniform_real.hpp | 82 - .../random/uniform_real_distribution.hpp | 239 - .../boost/random/uniform_smallint.hpp | 288 - .../boost/random/variate_generator.hpp | 122 - .../boost/random/weibull_distribution.hpp | 177 - utils/boost_idb/boost/random/xor_combine.hpp | 207 - .../boost/range/adaptor/adjacent_filtered.hpp | 238 - .../boost/range/adaptor/argument_fwd.hpp | 80 - .../boost_idb/boost/range/adaptor/copied.hpp | 58 - .../boost/range/adaptor/define_adaptor.hpp | 109 - .../boost/range/adaptor/filtered.hpp | 101 - .../boost_idb/boost/range/adaptor/indexed.hpp | 159 - .../boost/range/adaptor/indirected.hpp | 88 - utils/boost_idb/boost/range/adaptor/map.hpp | 187 - .../boost/range/adaptor/replaced.hpp | 134 - .../boost/range/adaptor/replaced_if.hpp | 136 - .../boost/range/adaptor/reversed.hpp | 90 - .../boost_idb/boost/range/adaptor/sliced.hpp | 82 - .../boost_idb/boost/range/adaptor/strided.hpp | 350 - .../boost/range/adaptor/tokenized.hpp | 137 - .../boost/range/adaptor/transformed.hpp | 104 - .../boost/range/adaptor/type_erased.hpp | 184 - .../boost_idb/boost/range/adaptor/uniqued.hpp | 90 - utils/boost_idb/boost/range/adaptors.hpp | 0 utils/boost_idb/boost/range/algorithm.hpp | 0 .../boost/range/algorithm/adjacent_find.hpp | 0 .../boost/range/algorithm/binary_search.hpp | 0 .../boost/range/algorithm/copy_backward.hpp | 0 .../boost_idb/boost/range/algorithm/count.hpp | 0 .../boost/range/algorithm/count_if.hpp | 0 .../boost_idb/boost/range/algorithm/equal.hpp | 20 +- .../boost/range/algorithm/equal_range.hpp | 0 .../boost_idb/boost/range/algorithm/fill.hpp | 0 .../boost/range/algorithm/fill_n.hpp | 0 .../boost_idb/boost/range/algorithm/find.hpp | 0 .../boost/range/algorithm/find_end.hpp | 0 .../boost/range/algorithm/find_first_of.hpp | 0 .../boost/range/algorithm/find_if.hpp | 0 .../boost/range/algorithm/for_each.hpp | 66 +- .../boost/range/algorithm/generate.hpp | 0 .../boost/range/algorithm/heap_algorithm.hpp | 0 .../boost/range/algorithm/inplace_merge.hpp | 0 .../algorithm/lexicographical_compare.hpp | 0 .../boost/range/algorithm/lower_bound.hpp | 0 .../boost/range/algorithm/max_element.hpp | 0 .../boost_idb/boost/range/algorithm/merge.hpp | 0 .../boost/range/algorithm/min_element.hpp | 0 .../boost/range/algorithm/mismatch.hpp | 0 .../boost/range/algorithm/nth_element.hpp | 0 .../boost/range/algorithm/partial_sort.hpp | 0 .../range/algorithm/partial_sort_copy.hpp | 0 .../boost/range/algorithm/partition.hpp | 0 .../boost/range/algorithm/permutation.hpp | 0 .../boost/range/algorithm/random_shuffle.hpp | 0 .../boost/range/algorithm/remove.hpp | 0 .../boost/range/algorithm/remove_copy.hpp | 0 .../boost/range/algorithm/remove_copy_if.hpp | 0 .../boost/range/algorithm/remove_if.hpp | 0 .../boost/range/algorithm/replace.hpp | 0 .../boost/range/algorithm/replace_copy.hpp | 0 .../boost/range/algorithm/replace_copy_if.hpp | 0 .../boost/range/algorithm/replace_if.hpp | 0 .../boost/range/algorithm/reverse.hpp | 0 .../boost/range/algorithm/reverse_copy.hpp | 0 .../boost/range/algorithm/rotate.hpp | 0 .../boost/range/algorithm/rotate_copy.hpp | 0 .../boost/range/algorithm/search.hpp | 0 .../boost/range/algorithm/search_n.hpp | 233 +- .../boost/range/algorithm/set_algorithm.hpp | 0 .../boost_idb/boost/range/algorithm/sort.hpp | 0 .../range/algorithm/stable_partition.hpp | 0 .../boost/range/algorithm/stable_sort.hpp | 0 .../boost/range/algorithm/swap_ranges.hpp | 0 .../boost/range/algorithm/transform.hpp | 2 +- .../boost/range/algorithm/unique.hpp | 0 .../boost/range/algorithm/unique_copy.hpp | 0 .../boost/range/algorithm/upper_bound.hpp | 0 utils/boost_idb/boost/range/algorithm_ext.hpp | 0 .../boost/range/algorithm_ext/copy_n.hpp | 53 - .../boost/range/algorithm_ext/erase.hpp | 61 - .../boost/range/algorithm_ext/for_each.hpp | 86 - .../boost/range/algorithm_ext/insert.hpp | 42 - .../boost/range/algorithm_ext/iota.hpp | 54 - .../boost/range/algorithm_ext/is_sorted.hpp | 57 - .../boost/range/algorithm_ext/overwrite.hpp | 84 - .../boost/range/algorithm_ext/push_back.hpp | 40 - .../boost/range/algorithm_ext/push_front.hpp | 40 - utils/boost_idb/boost/range/any_range.hpp | 205 - utils/boost_idb/boost/range/as_literal.hpp | 2 +- utils/boost_idb/boost/range/begin.hpp | 23 +- utils/boost_idb/boost/range/combine.hpp | 8 - utils/boost_idb/boost/range/concepts.hpp | 47 +- .../boost_idb/boost/range/counting_range.hpp | 13 +- .../boost/range/detail/any_iterator.hpp | 588 - .../range/detail/any_iterator_buffer.hpp | 117 - .../range/detail/any_iterator_interface.hpp | 262 - .../range/detail/any_iterator_wrapper.hpp | 592 - utils/boost_idb/boost/range/detail/begin.hpp | 28 +- .../range/detail/collection_traits_detail.hpp | 8 +- .../detail/demote_iterator_traversal_tag.hpp | 16 +- .../boost/range/detail/detail_str.hpp | 4 +- utils/boost_idb/boost/range/detail/end.hpp | 37 +- .../range/detail/extract_optional_type.hpp | 2 +- .../boost/range/detail/join_iterator.hpp | 32 +- .../boost/range/detail/misc_concept.hpp | 0 .../boost/range/detail/range_return.hpp | 0 .../boost/range/detail/safe_bool.hpp | 72 - .../boost/range/detail/size_type.hpp | 33 +- utils/boost_idb/boost/range/empty.hpp | 2 +- utils/boost_idb/boost/range/end.hpp | 23 +- .../boost/range/has_range_iterator.hpp | 62 - utils/boost_idb/boost/range/irange.hpp | 20 +- utils/boost_idb/boost/range/istream_range.hpp | 18 +- .../boost/range/iterator_range_core.hpp | 137 +- .../boost/range/iterator_range_io.hpp | 4 +- utils/boost_idb/boost/range/join.hpp | 8 - utils/boost_idb/boost/range/metafunctions.hpp | 1 - utils/boost_idb/boost/range/numeric.hpp | 2 +- utils/boost_idb/boost/range/size.hpp | 28 +- utils/boost_idb/boost/range/size_type.hpp | 56 +- utils/boost_idb/boost/range/sub_range.hpp | 51 +- utils/boost_idb/boost/ratio.hpp | 14 - utils/boost_idb/boost/ratio/config.hpp | 92 - .../boost_idb/boost/ratio/detail/mpl/abs.hpp | 89 - .../boost_idb/boost/ratio/detail/mpl/gcd.hpp | 124 - .../boost_idb/boost/ratio/detail/mpl/lcm.hpp | 126 - .../boost_idb/boost/ratio/detail/mpl/sign.hpp | 89 - .../boost/ratio/detail/overflow_helpers.hpp | 367 - .../boost_idb/boost/ratio/detail/ratio_io.hpp | 1045 - utils/boost_idb/boost/ratio/include.hpp | 16 - utils/boost_idb/boost/ratio/mpl/abs.hpp | 30 - .../boost_idb/boost/ratio/mpl/arithmetic.hpp | 22 - .../boost_idb/boost/ratio/mpl/comparison.hpp | 19 - utils/boost_idb/boost/ratio/mpl/divides.hpp | 30 - utils/boost_idb/boost/ratio/mpl/equal_to.hpp | 30 - utils/boost_idb/boost/ratio/mpl/gcd.hpp | 30 - utils/boost_idb/boost/ratio/mpl/greater.hpp | 30 - .../boost/ratio/mpl/greater_equal.hpp | 30 - utils/boost_idb/boost/ratio/mpl/lcm.hpp | 30 - utils/boost_idb/boost/ratio/mpl/less.hpp | 30 - .../boost_idb/boost/ratio/mpl/less_equal.hpp | 30 - utils/boost_idb/boost/ratio/mpl/minus.hpp | 30 - utils/boost_idb/boost/ratio/mpl/negate.hpp | 30 - .../boost/ratio/mpl/not_equal_to.hpp | 30 - .../boost/ratio/mpl/numeric_cast.hpp | 31 - utils/boost_idb/boost/ratio/mpl/plus.hpp | 30 - .../boost/ratio/mpl/rational_c_tag.hpp | 25 - .../boost/ratio/mpl/rational_constant.hpp | 15 - utils/boost_idb/boost/ratio/mpl/sign.hpp | 30 - utils/boost_idb/boost/ratio/mpl/times.hpp | 30 - utils/boost_idb/boost/ratio/ratio.hpp | 233 - utils/boost_idb/boost/ratio/ratio_fwd.hpp | 84 - utils/boost_idb/boost/ratio/ratio_io.hpp | 824 - .../boost/ratio/ratio_static_string.hpp | 631 - utils/boost_idb/boost/rational.hpp | 12 +- utils/boost_idb/boost/regex/concepts.hpp | 2 - utils/boost_idb/boost/regex/config.hpp | 11 +- utils/boost_idb/boost/regex/icu.hpp | 34 +- .../boost/regex/pending/object_cache.hpp | 4 +- .../boost/regex/pending/static_mutex.hpp | 15 +- .../boost/regex/pending/unicode_iterator.hpp | 102 +- utils/boost_idb/boost/regex/user.hpp | 3 - .../boost_idb/boost/regex/v4/basic_regex.hpp | 19 +- .../boost/regex/v4/basic_regex_creator.hpp | 107 +- .../boost/regex/v4/basic_regex_parser.hpp | 125 +- .../boost/regex/v4/cpp_regex_traits.hpp | 17 +- utils/boost_idb/boost/regex/v4/instances.hpp | 7 +- .../boost/regex/v4/match_results.hpp | 5 +- .../boost_idb/boost/regex/v4/perl_matcher.hpp | 5 +- .../boost/regex/v4/perl_matcher_common.hpp | 6 - .../regex/v4/perl_matcher_non_recursive.hpp | 35 +- .../boost/regex/v4/perl_matcher_recursive.hpp | 16 +- .../boost_idb/boost/regex/v4/regex_format.hpp | 25 +- .../boost/regex/v4/regex_iterator.hpp | 2 +- .../boost_idb/boost/regex/v4/regex_split.hpp | 2 +- .../boost/regex/v4/regex_traits_defaults.hpp | 34 +- .../regex/v4/u32regex_token_iterator.hpp | 6 +- utils/boost_idb/boost/scope_exit.hpp | 267 + .../boost/shared_container_iterator.hpp | 62 + utils/boost_idb/boost/signal.hpp | 358 + utils/boost_idb/boost/signals.hpp | 10 + utils/boost_idb/boost/signals2.hpp | 23 + utils/boost_idb/boost/smart_ptr.hpp | 6 - .../boost/smart_ptr/allocate_shared_array.hpp | 250 - .../detail/allocate_array_helper.hpp | 169 - .../boost/smart_ptr/detail/array_deleter.hpp | 124 - .../boost/smart_ptr/detail/array_traits.hpp | 53 - .../boost/smart_ptr/detail/array_utility.hpp | 178 - .../smart_ptr/detail/make_array_helper.hpp | 157 - .../boost/smart_ptr/detail/operator_bool.hpp | 25 +- .../boost/smart_ptr/detail/shared_count.hpp | 165 +- .../boost/smart_ptr/detail/sp_convertible.hpp | 15 - .../smart_ptr/detail/sp_counted_base.hpp | 21 +- .../detail/sp_counted_base_acc_ia64.hpp | 1 - .../smart_ptr/detail/sp_counted_base_aix.hpp | 143 - .../detail/sp_counted_base_cw_ppc.hpp | 1 - .../detail/sp_counted_base_cw_x86.hpp | 1 - .../detail/sp_counted_base_gcc_ia64.hpp | 1 - .../detail/sp_counted_base_gcc_mips.hpp | 10 - .../detail/sp_counted_base_gcc_ppc.hpp | 1 - .../detail/sp_counted_base_gcc_sparc.hpp | 1 - .../detail/sp_counted_base_gcc_x86.hpp | 1 - .../smart_ptr/detail/sp_counted_base_nt.hpp | 1 - .../smart_ptr/detail/sp_counted_base_pt.hpp | 1 - .../detail/sp_counted_base_snc_ps3.hpp | 162 - .../detail/sp_counted_base_solaris.hpp | 1 - .../smart_ptr/detail/sp_counted_base_spin.hpp | 1 - .../smart_ptr/detail/sp_counted_base_sync.hpp | 1 - .../detail/sp_counted_base_vacpp_ppc.hpp | 151 - .../smart_ptr/detail/sp_counted_base_w32.hpp | 1 - .../smart_ptr/detail/sp_counted_impl.hpp | 27 +- .../boost/smart_ptr/detail/sp_forward.hpp | 39 - .../boost/smart_ptr/detail/sp_has_sync.hpp | 26 +- .../boost/smart_ptr/detail/sp_if_array.hpp | 31 - .../boost/smart_ptr/detail/sp_nullptr_t.hpp | 45 - .../boost/smart_ptr/detail/spinlock.hpp | 5 +- .../smart_ptr/detail/spinlock_gcc_arm.hpp | 41 +- .../boost/smart_ptr/detail/spinlock_pool.hpp | 4 - .../boost/smart_ptr/detail/yield_k.hpp | 1 + .../smart_ptr/enable_shared_from_raw.hpp | 144 - .../smart_ptr/enable_shared_from_this.hpp | 8 +- .../smart_ptr/enable_shared_from_this2.hpp | 132 + .../boost/smart_ptr/intrusive_ptr.hpp | 57 +- .../boost/smart_ptr/intrusive_ref_counter.hpp | 187 - .../boost_idb/boost/smart_ptr/make_shared.hpp | 496 +- .../boost/smart_ptr/make_shared_array.hpp | 247 - .../boost/smart_ptr/make_shared_object.hpp | 1032 - .../boost_idb/boost/smart_ptr/owner_less.hpp | 57 - .../boost/smart_ptr/scoped_array.hpp | 39 +- .../boost_idb/boost/smart_ptr/scoped_ptr.hpp | 36 +- .../boost/smart_ptr/shared_array.hpp | 179 +- .../boost_idb/boost/smart_ptr/shared_ptr.hpp | 600 +- utils/boost_idb/boost/smart_ptr/weak_ptr.hpp | 93 +- utils/boost_idb/boost/spirit.hpp | 27 + utils/boost_idb/boost/static_assert.hpp | 91 +- utils/boost_idb/boost/strong_typedef.hpp | 66 + utils/boost_idb/boost/system/config.hpp | 17 - utils/boost_idb/boost/system/error_code.hpp | 144 +- utils/boost_idb/boost/system/system_error.hpp | 6 +- utils/boost_idb/boost/thread/barrier.hpp | 222 +- .../boost/thread/completion_latch.hpp | 233 - utils/boost_idb/boost/thread/condition.hpp | 7 +- utils/boost_idb/boost/thread/cv_status.hpp | 26 - .../boost/thread/detail/async_func.hpp | 571 - .../boost_idb/boost/thread/detail/config.hpp | 358 +- .../boost_idb/boost/thread/detail/counter.hpp | 106 - .../boost_idb/boost/thread/detail/delete.hpp | 57 - .../boost_idb/boost/thread/detail/invoke.hpp | 1351 -- .../boost/thread/detail/is_convertible.hpp | 49 - .../boost/thread/detail/lockable_wrapper.hpp | 45 - utils/boost_idb/boost/thread/detail/log.hpp | 83 - .../thread/detail/make_tuple_indices.hpp | 224 - .../boost_idb/boost/thread/detail/memory.hpp | 157 - utils/boost_idb/boost/thread/detail/move.hpp | 212 +- .../boost/thread/detail/platform.hpp | 4 +- .../boost_idb/boost/thread/detail/thread.hpp | 641 +- .../boost/thread/detail/thread_group.hpp | 64 +- .../thread/detail/thread_interruption.hpp | 28 +- utils/boost_idb/boost/thread/exceptions.hpp | 229 +- .../boost/thread/externally_locked.hpp | 351 - .../boost/thread/externally_locked_stream.hpp | 170 - utils/boost_idb/boost/thread/future.hpp | 4026 +--- .../boost/thread/future_error_code.hpp | 61 - .../boost/thread/is_locked_by_this_thread.hpp | 39 - utils/boost_idb/boost/thread/latch.hpp | 167 - .../boost/thread/lock_algorithms.hpp | 468 - .../boost_idb/boost/thread/lock_concepts.hpp | 197 - .../boost_idb/boost/thread/lock_factories.hpp | 78 - utils/boost_idb/boost/thread/lock_guard.hpp | 88 - utils/boost_idb/boost/thread/lock_options.hpp | 31 - utils/boost_idb/boost/thread/lock_traits.hpp | 45 - utils/boost_idb/boost/thread/lock_types.hpp | 1230 -- .../boost/thread/lockable_adapter.hpp | 226 - .../boost/thread/lockable_concepts.hpp | 157 - .../boost/thread/lockable_traits.hpp | 207 - utils/boost_idb/boost/thread/locks.hpp | 1583 +- utils/boost_idb/boost/thread/mutex.hpp | 34 +- utils/boost_idb/boost/thread/null_mutex.hpp | 243 - utils/boost_idb/boost/thread/once.hpp | 15 +- .../boost_idb/boost/thread/poly_lockable.hpp | 68 - .../boost/thread/poly_lockable_adapter.hpp | 89 - .../boost/thread/poly_shared_lockable.hpp | 135 - .../thread/poly_shared_lockable_adapter.hpp | 170 - .../thread/pthread/condition_variable.hpp | 291 +- .../thread/pthread/condition_variable_fwd.hpp | 199 +- .../boost_idb/boost/thread/pthread/mutex.hpp | 224 +- utils/boost_idb/boost/thread/pthread/once.hpp | 543 +- .../boost/thread/pthread/once_atomic.hpp | 313 - .../boost/thread/pthread/recursive_mutex.hpp | 148 +- .../boost/thread/pthread/shared_mutex.hpp | 527 +- .../thread/pthread/shared_mutex_assert.hpp | 724 - .../boost/thread/pthread/thread_data.hpp | 154 +- .../thread/pthread/thread_heap_alloc.hpp | 8 +- .../boost/thread/pthread/timespec.hpp | 108 +- .../boost/thread/recursive_mutex.hpp | 45 +- utils/boost_idb/boost/thread/reverse_lock.hpp | 59 - .../boost_idb/boost/thread/scoped_thread.hpp | 283 - .../boost/thread/shared_lock_guard.hpp | 53 - utils/boost_idb/boost/thread/shared_mutex.hpp | 32 +- utils/boost_idb/boost/thread/strict_lock.hpp | 235 - .../boost/thread/sync_bounded_queue.hpp | 600 - utils/boost_idb/boost/thread/sync_queue.hpp | 513 - .../boost/thread/synchronized_value.hpp | 1068 - .../boost_idb/boost/thread/testable_mutex.hpp | 152 - utils/boost_idb/boost/thread/thread.hpp | 15 +- .../boost/thread/thread_functors.hpp | 57 - utils/boost_idb/boost/thread/thread_guard.hpp | 46 - utils/boost_idb/boost/thread/thread_only.hpp | 29 - .../boost/thread/v2/shared_mutex.hpp | 1062 - utils/boost_idb/boost/thread/v2/thread.hpp | 83 - .../thread/win32/basic_recursive_mutex.hpp | 64 +- .../boost/thread/win32/basic_timed_mutex.hpp | 97 +- .../boost/thread/win32/condition_variable.hpp | 278 +- .../boost/thread/win32/interlocked_read.hpp | 20 +- .../boost/thread/win32/mfc_thread_init.hpp | 40 - utils/boost_idb/boost/thread/win32/mutex.hpp | 21 +- utils/boost_idb/boost/thread/win32/once.hpp | 987 +- .../boost/thread/win32/recursive_mutex.hpp | 22 +- .../boost/thread/win32/shared_mutex.hpp | 345 +- .../boost/thread/win32/thread_data.hpp | 173 +- .../boost/thread/win32/thread_heap_alloc.hpp | 81 +- .../boost/thread/win32/thread_primitives.hpp | 105 +- utils/boost_idb/boost/thread/xtime.hpp | 15 +- utils/boost_idb/boost/throw_exception.hpp | 20 +- utils/boost_idb/boost/timer/config.hpp | 53 - utils/boost_idb/boost/timer/timer.hpp | 138 - utils/boost_idb/boost/token_functions.hpp | 68 +- .../boost/tuple/detail/tuple_basic.hpp | 321 +- .../detail/tuple_basic_no_partial_spec.hpp | 24 - utils/boost_idb/boost/tuple/tuple_io.hpp | 43 - utils/boost_idb/boost/type_traits.hpp | 12 +- .../type_traits/add_lvalue_reference.hpp | 2 +- .../boost/type_traits/add_reference.hpp | 2 +- .../type_traits/add_rvalue_reference.hpp | 15 +- .../boost/type_traits/alignment_of.hpp | 2 +- .../boost/type_traits/common_type.hpp | 34 +- utils/boost_idb/boost/type_traits/config.hpp | 2 +- .../type_traits/detail/bool_trait_def.hpp | 29 +- .../type_traits/detail/bool_trait_undef.hpp | 5 +- .../type_traits/detail/common_type_imp.hpp | 81 +- .../type_traits/detail/cv_traits_impl.hpp | 2 +- .../detail/has_binary_operator.hpp | 229 - .../detail/has_postfix_operator.hpp | 202 - .../detail/has_prefix_operator.hpp | 210 - .../detail/is_function_ptr_tester.hpp | 2 +- .../type_traits/detail/size_t_trait_def.hpp | 10 +- .../type_traits/detail/size_t_trait_undef.hpp | 2 +- .../type_traits/detail/type_trait_def.hpp | 10 +- .../type_traits/detail/type_trait_undef.hpp | 2 +- .../boost/type_traits/function_traits.hpp | 2 +- .../boost/type_traits/has_bit_and.hpp | 49 - .../boost/type_traits/has_bit_and_assign.hpp | 55 - .../boost/type_traits/has_bit_or.hpp | 49 - .../boost/type_traits/has_bit_or_assign.hpp | 55 - .../boost/type_traits/has_bit_xor.hpp | 49 - .../boost/type_traits/has_bit_xor_assign.hpp | 55 - .../boost/type_traits/has_complement.hpp | 32 - .../boost/type_traits/has_dereference.hpp | 31 - .../boost/type_traits/has_divides.hpp | 40 - .../boost/type_traits/has_divides_assign.hpp | 47 - .../boost/type_traits/has_equal_to.hpp | 49 - .../boost/type_traits/has_greater.hpp | 49 - .../boost/type_traits/has_greater_equal.hpp | 49 - .../boost/type_traits/has_left_shift.hpp | 49 - .../type_traits/has_left_shift_assign.hpp | 55 - .../boost_idb/boost/type_traits/has_less.hpp | 49 - .../boost/type_traits/has_less_equal.hpp | 49 - .../boost/type_traits/has_logical_and.hpp | 40 - .../boost/type_traits/has_logical_not.hpp | 23 - .../boost/type_traits/has_logical_or.hpp | 40 - .../boost_idb/boost/type_traits/has_minus.hpp | 60 - .../boost/type_traits/has_minus_assign.hpp | 65 - .../boost/type_traits/has_modulus.hpp | 49 - .../boost/type_traits/has_modulus_assign.hpp | 55 - .../boost/type_traits/has_multiplies.hpp | 40 - .../type_traits/has_multiplies_assign.hpp | 47 - .../boost/type_traits/has_negate.hpp | 25 - .../boost/type_traits/has_not_equal_to.hpp | 49 - .../boost/type_traits/has_nothrow_assign.hpp | 16 +- .../type_traits/has_nothrow_constructor.hpp | 24 +- .../boost/type_traits/has_nothrow_copy.hpp | 24 +- .../boost/type_traits/has_operator.hpp | 51 - .../boost_idb/boost/type_traits/has_plus.hpp | 54 - .../boost/type_traits/has_plus_assign.hpp | 66 - .../boost/type_traits/has_post_decrement.hpp | 40 - .../boost/type_traits/has_post_increment.hpp | 40 - .../boost/type_traits/has_pre_decrement.hpp | 40 - .../boost/type_traits/has_pre_increment.hpp | 40 - .../boost/type_traits/has_right_shift.hpp | 49 - .../type_traits/has_right_shift_assign.hpp | 55 - .../boost/type_traits/has_trivial_assign.hpp | 17 +- .../type_traits/has_trivial_constructor.hpp | 8 - .../boost/type_traits/has_trivial_copy.hpp | 25 +- .../type_traits/has_trivial_destructor.hpp | 17 +- .../type_traits/has_trivial_move_assign.hpp | 57 - .../has_trivial_move_constructor.hpp | 57 - .../boost/type_traits/has_unary_minus.hpp | 25 - .../boost/type_traits/has_unary_plus.hpp | 23 - .../type_traits/has_virtual_destructor.hpp | 4 - .../boost/type_traits/integral_promotion.hpp | 20 +- .../boost/type_traits/intrinsics.hpp | 186 +- .../boost/type_traits/is_abstract.hpp | 2 +- .../boost_idb/boost/type_traits/is_array.hpp | 2 +- .../boost_idb/boost/type_traits/is_const.hpp | 12 +- .../boost/type_traits/is_convertible.hpp | 106 +- .../type_traits/is_copy_constructible.hpp | 122 - .../boost_idb/boost/type_traits/is_empty.hpp | 16 +- utils/boost_idb/boost/type_traits/is_enum.hpp | 2 +- .../boost/type_traits/is_function.hpp | 13 +- .../boost/type_traits/is_fundamental.hpp | 2 +- .../boost/type_traits/is_integral.hpp | 13 +- .../is_member_function_pointer.hpp | 4 +- .../boost/type_traits/is_member_pointer.hpp | 4 +- .../is_nothrow_move_assignable.hpp | 84 - .../is_nothrow_move_constructible.hpp | 84 - utils/boost_idb/boost/type_traits/is_pod.hpp | 18 +- .../boost/type_traits/is_pointer.hpp | 4 +- .../boost/type_traits/is_rvalue_reference.hpp | 2 +- .../boost_idb/boost/type_traits/is_union.hpp | 8 - .../boost/type_traits/is_unsigned.hpp | 2 +- .../boost/type_traits/is_virtual_base_of.hpp | 8 +- .../boost/type_traits/is_volatile.hpp | 12 +- .../boost/type_traits/make_signed.hpp | 16 - .../boost/type_traits/make_unsigned.hpp | 16 - .../boost/type_traits/msvc/typeof.hpp | 4 +- utils/boost_idb/boost/type_traits/promote.hpp | 2 +- .../boost/type_traits/remove_const.hpp | 2 +- .../boost_idb/boost/type_traits/remove_cv.hpp | 9 +- .../boost/type_traits/remove_pointer.hpp | 53 +- .../boost/type_traits/remove_reference.hpp | 6 +- .../boost/type_traits/remove_volatile.hpp | 2 +- .../boost/type_traits/type_with_alignment.hpp | 10 +- .../boost/typeof/dmc/typeof_impl.hpp | 100 - .../boost_idb/boost/typeof/encode_decode.hpp | 61 - .../boost/typeof/encode_decode_params.hpp | 34 - .../boost/typeof/incr_registration_group.hpp | 14 - utils/boost_idb/boost/typeof/int_encoding.hpp | 118 - .../boost/typeof/integral_template_param.hpp | 80 - utils/boost_idb/boost/typeof/message.hpp | 8 - utils/boost_idb/boost/typeof/modifiers.hpp | 121 - .../boost/typeof/msvc/typeof_impl.hpp | 283 - utils/boost_idb/boost/typeof/native.hpp | 60 - .../boost/typeof/pointers_data_members.hpp | 38 - .../boost/typeof/register_functions.hpp | 50 - .../typeof/register_functions_iterate.hpp | 135 - .../boost/typeof/register_fundamental.hpp | 62 - .../boost/typeof/register_mem_functions.hpp | 32 - utils/boost_idb/boost/typeof/std/bitset.hpp | 15 - utils/boost_idb/boost/typeof/std/complex.hpp | 15 - utils/boost_idb/boost/typeof/std/deque.hpp | 17 - utils/boost_idb/boost/typeof/std/fstream.hpp | 27 - .../boost_idb/boost/typeof/std/functional.hpp | 55 - utils/boost_idb/boost/typeof/std/iostream.hpp | 18 - utils/boost_idb/boost/typeof/std/istream.hpp | 21 - utils/boost_idb/boost/typeof/std/iterator.hpp | 58 - utils/boost_idb/boost/typeof/std/list.hpp | 17 - utils/boost_idb/boost/typeof/std/locale.hpp | 40 - utils/boost_idb/boost/typeof/std/map.hpp | 23 - utils/boost_idb/boost/typeof/std/memory.hpp | 17 - utils/boost_idb/boost/typeof/std/ostream.hpp | 18 - utils/boost_idb/boost/typeof/std/queue.hpp | 17 - utils/boost_idb/boost/typeof/std/set.hpp | 22 - utils/boost_idb/boost/typeof/std/sstream.hpp | 32 - utils/boost_idb/boost/typeof/std/stack.hpp | 17 - .../boost_idb/boost/typeof/std/streambuf.hpp | 17 - utils/boost_idb/boost/typeof/std/string.hpp | 24 - utils/boost_idb/boost/typeof/std/utility.hpp | 15 - utils/boost_idb/boost/typeof/std/valarray.hpp | 21 - utils/boost_idb/boost/typeof/std/vector.hpp | 17 - .../boost/typeof/template_encoding.hpp | 160 - .../boost/typeof/template_template_param.hpp | 149 - .../boost_idb/boost/typeof/type_encoding.hpp | 27 - .../boost/typeof/type_template_param.hpp | 37 - utils/boost_idb/boost/typeof/typeof.hpp | 218 - utils/boost_idb/boost/typeof/typeof_impl.hpp | 186 - utils/boost_idb/boost/typeof/unsupported.hpp | 29 - utils/boost_idb/boost/typeof/vector.hpp | 166 - utils/boost_idb/boost/typeof/vector100.hpp | 321 - utils/boost_idb/boost/typeof/vector150.hpp | 471 - utils/boost_idb/boost/typeof/vector200.hpp | 621 - utils/boost_idb/boost/typeof/vector50.hpp | 171 - utils/boost_idb/boost/units/absolute.hpp | 153 + .../boost_idb/boost/units/base_dimension.hpp | 97 + utils/boost_idb/boost/units/base_unit.hpp | 118 + .../units/base_units/angle/arcminute.hpp | 36 + .../units/base_units/angle/arcsecond.hpp | 37 + .../boost/units/base_units/angle/degree.hpp | 27 + .../boost/units/base_units/angle/gradian.hpp | 27 + .../boost/units/base_units/angle/radian.hpp | 48 + .../units/base_units/angle/revolution.hpp | 36 + .../units/base_units/angle/steradian.hpp | 48 + .../astronomical/astronomical_unit.hpp | 27 + .../base_units/astronomical/light_day.hpp | 39 + .../base_units/astronomical/light_hour.hpp | 39 + .../base_units/astronomical/light_minute.hpp | 39 + .../base_units/astronomical/light_second.hpp | 27 + .../base_units/astronomical/light_year.hpp | 39 + .../units/base_units/astronomical/parsec.hpp | 27 + .../boost/units/base_units/cgs/biot.hpp | 31 + .../boost/units/base_units/cgs/centimeter.hpp | 31 + .../boost/units/base_units/cgs/gram.hpp | 49 + .../units/base_units/imperial/conversions.hpp | 46 + .../units/base_units/imperial/drachm.hpp | 39 + .../units/base_units/imperial/fluid_ounce.hpp | 39 + .../boost/units/base_units/imperial/foot.hpp | 39 + .../units/base_units/imperial/furlong.hpp | 39 + .../units/base_units/imperial/gallon.hpp | 40 + .../boost/units/base_units/imperial/gill.hpp | 40 + .../boost/units/base_units/imperial/grain.hpp | 39 + .../base_units/imperial/hundredweight.hpp | 39 + .../boost/units/base_units/imperial/inch.hpp | 39 + .../units/base_units/imperial/league.hpp | 39 + .../boost/units/base_units/imperial/mile.hpp | 39 + .../boost/units/base_units/imperial/ounce.hpp | 39 + .../boost/units/base_units/imperial/pint.hpp | 29 + .../boost/units/base_units/imperial/pound.hpp | 34 + .../boost/units/base_units/imperial/quart.hpp | 40 + .../units/base_units/imperial/quarter.hpp | 39 + .../boost/units/base_units/imperial/stone.hpp | 39 + .../boost/units/base_units/imperial/thou.hpp | 39 + .../boost/units/base_units/imperial/ton.hpp | 40 + .../boost/units/base_units/imperial/yard.hpp | 32 + .../units/base_units/metric/angstrom.hpp | 37 + .../boost/units/base_units/metric/are.hpp | 19 + .../units/base_units/metric/atmosphere.hpp | 19 + .../boost/units/base_units/metric/bar.hpp | 19 + .../boost/units/base_units/metric/barn.hpp | 19 + .../boost/units/base_units/metric/day.hpp | 39 + .../boost/units/base_units/metric/fermi.hpp | 36 + .../boost/units/base_units/metric/hectare.hpp | 19 + .../boost/units/base_units/metric/hour.hpp | 37 + .../boost/units/base_units/metric/knot.hpp | 19 + .../boost/units/base_units/metric/liter.hpp | 19 + .../boost/units/base_units/metric/micron.hpp | 36 + .../boost/units/base_units/metric/minute.hpp | 37 + .../boost/units/base_units/metric/mmHg.hpp | 19 + .../units/base_units/metric/nautical_mile.hpp | 36 + .../boost/units/base_units/metric/ton.hpp | 39 + .../boost/units/base_units/metric/torr.hpp | 19 + .../boost/units/base_units/metric/year.hpp | 38 + .../boost/units/base_units/si/ampere.hpp | 48 + .../boost/units/base_units/si/candela.hpp | 48 + .../boost/units/base_units/si/kelvin.hpp | 48 + .../boost/units/base_units/si/kilogram.hpp | 31 + .../boost/units/base_units/si/meter.hpp | 50 + .../boost/units/base_units/si/mole.hpp | 48 + .../boost/units/base_units/si/second.hpp | 48 + .../units/base_units/temperature/celsius.hpp | 48 + .../base_units/temperature/conversions.hpp | 42 + .../base_units/temperature/fahrenheit.hpp | 48 + .../boost/units/base_units/us/cup.hpp | 39 + .../boost/units/base_units/us/dram.hpp | 39 + .../boost/units/base_units/us/fluid_dram.hpp | 39 + .../boost/units/base_units/us/fluid_ounce.hpp | 39 + .../boost/units/base_units/us/foot.hpp | 39 + .../boost/units/base_units/us/gallon.hpp | 39 + .../boost/units/base_units/us/gill.hpp | 39 + .../boost/units/base_units/us/grain.hpp | 39 + .../units/base_units/us/hundredweight.hpp | 40 + .../boost/units/base_units/us/inch.hpp | 39 + .../boost/units/base_units/us/mil.hpp | 39 + .../boost/units/base_units/us/mile.hpp | 39 + .../boost/units/base_units/us/minim.hpp | 39 + .../boost/units/base_units/us/ounce.hpp | 39 + .../boost/units/base_units/us/pint.hpp | 28 + .../boost/units/base_units/us/pound.hpp | 32 + .../boost/units/base_units/us/pound_force.hpp | 32 + .../boost/units/base_units/us/quart.hpp | 39 + .../boost/units/base_units/us/tablespoon.hpp | 39 + .../boost/units/base_units/us/teaspoon.hpp | 39 + .../boost/units/base_units/us/ton.hpp | 39 + .../boost/units/base_units/us/yard.hpp | 32 + utils/boost_idb/boost/units/cmath.hpp | 676 + utils/boost_idb/boost/units/config.hpp | 105 + utils/boost_idb/boost/units/conversion.hpp | 183 + .../boost/units/derived_dimension.hpp | 208 + .../boost/units/detail/absolute_impl.hpp | 104 + .../boost/units/detail/cmath_impl.hpp | 154 + .../boost/units/detail/conversion_impl.hpp | 458 + .../boost_idb/boost/units/detail/dim_impl.hpp | 90 + .../boost/units/detail/dimension_impl.hpp | 347 + .../boost/units/detail/dimension_list.hpp | 133 + .../boost/units/detail/dimensionless_unit.hpp | 88 + .../units/detail/heterogeneous_conversion.hpp | 309 + .../boost/units/detail/linear_algebra.hpp | 1060 + utils/boost_idb/boost/units/detail/one.hpp | 109 + .../boost_idb/boost/units/detail/ordinal.hpp | 49 + .../units/detail/prevent_redefinition.hpp | 54 + .../boost/units/detail/push_front_if.hpp | 48 + .../boost/units/detail/push_front_or_add.hpp | 84 + utils/boost_idb/boost/units/detail/sort.hpp | 109 + .../units/detail/static_rational_power.hpp | 206 + .../boost_idb/boost/units/detail/unscale.hpp | 234 + .../boost_idb/boost/units/detail/utility.hpp | 104 + utils/boost_idb/boost/units/dim.hpp | 167 + utils/boost_idb/boost/units/dimension.hpp | 150 + .../boost/units/dimensionless_quantity.hpp | 37 + .../boost/units/dimensionless_type.hpp | 55 + .../boost/units/dimensionless_unit.hpp | 37 + utils/boost_idb/boost/units/get_dimension.hpp | 54 + utils/boost_idb/boost/units/get_system.hpp | 51 + .../boost/units/heterogeneous_system.hpp | 428 + .../boost/units/homogeneous_system.hpp | 105 + utils/boost_idb/boost/units/io.hpp | 1014 + utils/boost_idb/boost/units/is_dim.hpp | 42 + .../boost/units/is_dimension_list.hpp | 47 + .../boost/units/is_dimensionless.hpp | 47 + .../boost/units/is_dimensionless_quantity.hpp | 34 + .../boost/units/is_dimensionless_unit.hpp | 34 + utils/boost_idb/boost/units/is_quantity.hpp | 42 + .../boost/units/is_quantity_of_dimension.hpp | 42 + .../boost/units/is_quantity_of_system.hpp | 42 + utils/boost_idb/boost/units/is_unit.hpp | 41 + .../boost/units/is_unit_of_dimension.hpp | 46 + .../boost/units/is_unit_of_system.hpp | 46 + utils/boost_idb/boost/units/lambda.hpp | 593 + utils/boost_idb/boost/units/limits.hpp | 69 + .../boost/units/make_scaled_unit.hpp | 60 + utils/boost_idb/boost/units/make_system.hpp | 145 + utils/boost_idb/boost/units/operators.hpp | 164 + .../boost/units/physical_dimensions.hpp | 90 + .../physical_dimensions/absorbed_dose.hpp | 30 + .../physical_dimensions/acceleration.hpp | 30 + .../units/physical_dimensions/action.hpp | 32 + .../units/physical_dimensions/activity.hpp | 28 + .../units/physical_dimensions/amount.hpp | 49 + .../angular_acceleration.hpp | 30 + .../physical_dimensions/angular_momentum.hpp | 34 + .../physical_dimensions/angular_velocity.hpp | 30 + .../boost/units/physical_dimensions/area.hpp | 28 + .../units/physical_dimensions/capacitance.hpp | 34 + .../units/physical_dimensions/conductance.hpp | 34 + .../physical_dimensions/conductivity.hpp | 34 + .../units/physical_dimensions/current.hpp | 49 + .../physical_dimensions/dose_equivalent.hpp | 30 + .../physical_dimensions/dynamic_viscosity.hpp | 32 + .../physical_dimensions/electric_charge.hpp | 30 + .../electric_potential.hpp | 34 + .../units/physical_dimensions/energy.hpp | 32 + .../physical_dimensions/energy_density.hpp | 32 + .../boost/units/physical_dimensions/force.hpp | 32 + .../units/physical_dimensions/frequency.hpp | 28 + .../physical_dimensions/heat_capacity.hpp | 34 + .../units/physical_dimensions/illuminance.hpp | 32 + .../units/physical_dimensions/impedance.hpp | 34 + .../units/physical_dimensions/inductance.hpp | 34 + .../kinematic_viscosity.hpp | 30 + .../units/physical_dimensions/length.hpp | 49 + .../units/physical_dimensions/luminance.hpp | 30 + .../physical_dimensions/luminous_flux.hpp | 30 + .../luminous_intensity.hpp | 49 + .../magnetic_field_intensity.hpp | 30 + .../physical_dimensions/magnetic_flux.hpp | 34 + .../magnetic_flux_density.hpp | 32 + .../boost/units/physical_dimensions/mass.hpp | 49 + .../physical_dimensions/mass_density.hpp | 30 + .../physical_dimensions/molar_energy.hpp | 34 + .../molar_heat_capacity.hpp | 36 + .../physical_dimensions/moment_of_inertia.hpp | 32 + .../units/physical_dimensions/momentum.hpp | 32 + .../physical_dimensions/permeability.hpp | 34 + .../physical_dimensions/permittivity.hpp | 34 + .../units/physical_dimensions/plane_angle.hpp | 49 + .../boost/units/physical_dimensions/power.hpp | 32 + .../units/physical_dimensions/pressure.hpp | 32 + .../units/physical_dimensions/reluctance.hpp | 34 + .../units/physical_dimensions/resistance.hpp | 34 + .../units/physical_dimensions/resistivity.hpp | 34 + .../units/physical_dimensions/solid_angle.hpp | 49 + .../physical_dimensions/specific_energy.hpp | 30 + .../specific_heat_capacity.hpp | 32 + .../physical_dimensions/specific_volume.hpp | 30 + .../units/physical_dimensions/stress.hpp | 32 + .../physical_dimensions/surface_density.hpp | 30 + .../physical_dimensions/surface_tension.hpp | 31 + .../units/physical_dimensions/temperature.hpp | 49 + .../thermal_conductivity.hpp | 34 + .../boost/units/physical_dimensions/time.hpp | 49 + .../units/physical_dimensions/torque.hpp | 34 + .../units/physical_dimensions/velocity.hpp | 30 + .../units/physical_dimensions/volume.hpp | 28 + .../units/physical_dimensions/wavenumber.hpp | 28 + utils/boost_idb/boost/units/pow.hpp | 112 + utils/boost_idb/boost/units/quantity.hpp | 1218 ++ utils/boost_idb/boost/units/reduce_unit.hpp | 41 + utils/boost_idb/boost/units/scale.hpp | 143 + .../boost/units/scaled_base_unit.hpp | 146 + .../boost_idb/boost/units/static_constant.hpp | 57 + .../boost_idb/boost/units/static_rational.hpp | 349 + .../boost/units/systems/abstract.hpp | 139 + .../boost/units/systems/angle/degrees.hpp | 43 + .../boost/units/systems/angle/gradians.hpp | 43 + .../boost/units/systems/angle/revolutions.hpp | 43 + utils/boost_idb/boost/units/systems/cgs.hpp | 44 + .../boost/units/systems/cgs/acceleration.hpp | 34 + .../boost/units/systems/cgs/area.hpp | 36 + .../boost/units/systems/cgs/base.hpp | 46 + .../boost/units/systems/cgs/current.hpp | 33 + .../boost/units/systems/cgs/dimensionless.hpp | 30 + .../units/systems/cgs/dynamic_viscosity.hpp | 33 + .../boost/units/systems/cgs/energy.hpp | 34 + .../boost/units/systems/cgs/force.hpp | 34 + .../boost/units/systems/cgs/frequency.hpp | 31 + .../boost_idb/boost/units/systems/cgs/io.hpp | 50 + .../units/systems/cgs/kinematic_viscosity.hpp | 34 + .../boost/units/systems/cgs/length.hpp | 35 + .../boost/units/systems/cgs/mass.hpp | 36 + .../boost/units/systems/cgs/mass_density.hpp | 31 + .../boost/units/systems/cgs/momentum.hpp | 31 + .../boost/units/systems/cgs/power.hpp | 31 + .../boost/units/systems/cgs/pressure.hpp | 34 + .../boost/units/systems/cgs/time.hpp | 33 + .../boost/units/systems/cgs/velocity.hpp | 36 + .../boost/units/systems/cgs/volume.hpp | 36 + .../boost/units/systems/cgs/wavenumber.hpp | 38 + .../boost/units/systems/detail/constants.hpp | 201 + utils/boost_idb/boost/units/systems/si.hpp | 77 + .../boost/units/systems/si/absorbed_dose.hpp | 34 + .../boost/units/systems/si/acceleration.hpp | 36 + .../boost/units/systems/si/action.hpp | 31 + .../boost/units/systems/si/activity.hpp | 34 + .../boost/units/systems/si/amount.hpp | 33 + .../units/systems/si/angular_acceleration.hpp | 31 + .../units/systems/si/angular_momentum.hpp | 31 + .../units/systems/si/angular_velocity.hpp | 34 + .../boost_idb/boost/units/systems/si/area.hpp | 39 + .../boost_idb/boost/units/systems/si/base.hpp | 56 + .../boost/units/systems/si/capacitance.hpp | 34 + .../units/systems/si/catalytic_activity.hpp | 37 + .../systems/si/codata/alpha_constants.hpp | 65 + .../si/codata/atomic-nuclear_constants.hpp | 56 + .../systems/si/codata/deuteron_constants.hpp | 81 + .../si/codata/electromagnetic_constants.hpp | 74 + .../systems/si/codata/electron_constants.hpp | 105 + .../systems/si/codata/helion_constants.hpp | 77 + .../systems/si/codata/muon_constants.hpp | 83 + .../systems/si/codata/neutron_constants.hpp | 83 + .../si/codata/physico-chemical_constants.hpp | 78 + .../systems/si/codata/proton_constants.hpp | 97 + .../units/systems/si/codata/tau_constants.hpp | 71 + .../systems/si/codata/triton_constants.hpp | 79 + .../units/systems/si/codata/typedefs.hpp | 79 + .../systems/si/codata/universal_constants.hpp | 80 + .../units/systems/si/codata_constants.hpp | 19 + .../boost/units/systems/si/conductance.hpp | 36 + .../boost/units/systems/si/conductivity.hpp | 31 + .../boost/units/systems/si/current.hpp | 33 + .../boost/units/systems/si/dimensionless.hpp | 30 + .../units/systems/si/dose_equivalent.hpp | 34 + .../units/systems/si/dynamic_viscosity.hpp | 31 + .../units/systems/si/electric_charge.hpp | 34 + .../units/systems/si/electric_potential.hpp | 34 + .../boost/units/systems/si/energy.hpp | 34 + .../boost/units/systems/si/force.hpp | 34 + .../boost/units/systems/si/frequency.hpp | 33 + .../boost/units/systems/si/illuminance.hpp | 33 + .../boost/units/systems/si/impedance.hpp | 31 + .../boost/units/systems/si/inductance.hpp | 34 + utils/boost_idb/boost/units/systems/si/io.hpp | 88 + .../units/systems/si/kinematic_viscosity.hpp | 31 + .../boost/units/systems/si/length.hpp | 35 + .../boost/units/systems/si/luminous_flux.hpp | 34 + .../units/systems/si/luminous_intensity.hpp | 33 + .../systems/si/magnetic_field_intensity.hpp | 31 + .../boost/units/systems/si/magnetic_flux.hpp | 34 + .../systems/si/magnetic_flux_density.hpp | 34 + .../boost_idb/boost/units/systems/si/mass.hpp | 35 + .../boost/units/systems/si/mass_density.hpp | 36 + .../units/systems/si/moment_of_inertia.hpp | 31 + .../boost/units/systems/si/momentum.hpp | 31 + .../boost/units/systems/si/permeability.hpp | 31 + .../boost/units/systems/si/permittivity.hpp | 31 + .../boost/units/systems/si/plane_angle.hpp | 33 + .../boost/units/systems/si/power.hpp | 34 + .../boost/units/systems/si/prefixes.hpp | 77 + .../boost/units/systems/si/pressure.hpp | 49 + .../boost/units/systems/si/reluctance.hpp | 31 + .../boost/units/systems/si/resistance.hpp | 34 + .../boost/units/systems/si/resistivity.hpp | 31 + .../boost/units/systems/si/solid_angle.hpp | 33 + .../units/systems/si/surface_density.hpp | 36 + .../units/systems/si/surface_tension.hpp | 34 + .../boost/units/systems/si/temperature.hpp | 33 + .../boost_idb/boost/units/systems/si/time.hpp | 33 + .../boost/units/systems/si/torque.hpp | 34 + .../boost/units/systems/si/velocity.hpp | 36 + .../boost/units/systems/si/volume.hpp | 36 + .../boost/units/systems/si/wavenumber.hpp | 36 + .../units/systems/temperature/celsius.hpp | 40 + .../units/systems/temperature/fahrenheit.hpp | 41 + utils/boost_idb/boost/units/unit.hpp | 440 + utils/boost_idb/boost/units/units_fwd.hpp | 73 + .../unordered/detail/allocator_helpers.hpp | 237 + .../boost/unordered/detail/config.hpp | 22 + .../boost/unordered/detail/hash_table.hpp | 309 + .../unordered/detail/hash_table_impl.hpp | 2348 +++ .../boost_idb/boost/unordered/detail/move.hpp | 228 + .../boost/unordered/unordered_map.hpp | 837 + .../boost/unordered/unordered_map_fwd.hpp | 53 + .../boost/unordered/unordered_set.hpp | 794 + .../boost/unordered/unordered_set_fwd.hpp | 51 + utils/boost_idb/boost/unordered_map.hpp | 18 + utils/boost_idb/boost/unordered_set.hpp | 18 + utils/boost_idb/boost/utility.hpp | 1 - utils/boost_idb/boost/utility/addressof.hpp | 4 +- .../boost/utility/base_from_member.hpp | 73 +- utils/boost_idb/boost/utility/declval.hpp | 36 +- .../utility/detail/result_of_iterate.hpp | 161 +- .../boost_idb/boost/utility/empty_deleter.hpp | 43 - .../boost/utility/explicit_operator_bool.hpp | 128 - .../boost_idb/boost/utility/identity_type.hpp | 46 - utils/boost_idb/boost/utility/result_of.hpp | 119 +- utils/boost_idb/boost/utility/string_ref.hpp | 536 - .../boost/utility/string_ref_fwd.hpp | 37 - utils/boost_idb/boost/uuid/name_generator.hpp | 125 - utils/boost_idb/boost/uuid/nil_generator.hpp | 34 - .../boost_idb/boost/uuid/random_generator.hpp | 119 - utils/boost_idb/boost/uuid/seed_rng.hpp | 266 - utils/boost_idb/boost/uuid/sha1.hpp | 231 - .../boost_idb/boost/uuid/string_generator.hpp | 185 - utils/boost_idb/boost/uuid/uuid.hpp | 221 - .../boost_idb/boost/uuid/uuid_generators.hpp | 19 - utils/boost_idb/boost/uuid/uuid_io.hpp | 198 - utils/boost_idb/boost/uuid/uuid_serialize.hpp | 20 - utils/boost_idb/boost/variant.hpp | 27 + .../boost_idb/boost/variant/apply_visitor.hpp | 20 + utils/boost_idb/boost/variant/bad_visit.hpp | 41 + .../variant/detail/apply_visitor_binary.hpp | 172 + .../variant/detail/apply_visitor_delayed.hpp | 85 + .../variant/detail/apply_visitor_unary.hpp | 79 + .../boost/variant/detail/backup_holder.hpp | 94 + .../boost/variant/detail/bool_trait_def.hpp | 30 + .../boost/variant/detail/bool_trait_undef.hpp | 21 + .../boost/variant/detail/cast_storage.hpp | 48 + .../boost_idb/boost/variant/detail/config.hpp | 38 + .../boost/variant/detail/enable_recursive.hpp | 162 + .../variant/detail/enable_recursive_fwd.hpp | 116 + .../boost/variant/detail/forced_return.hpp | 104 + .../variant/detail/generic_result_type.hpp | 88 + .../boost/variant/detail/has_nothrow_move.hpp | 106 + .../boost/variant/detail/has_trivial_move.hpp | 100 + .../boost/variant/detail/initializer.hpp | 265 + .../variant/detail/make_variant_list.hpp | 60 + utils/boost_idb/boost/variant/detail/move.hpp | 166 + .../boost/variant/detail/over_sequence.hpp | 95 + .../boost/variant/detail/substitute.hpp | 231 + .../boost/variant/detail/substitute_fwd.hpp | 59 + .../boost/variant/detail/variant_io.hpp | 92 + .../boost/variant/detail/visitation_impl.hpp | 286 + utils/boost_idb/boost/variant/get.hpp | 202 + .../boost/variant/recursive_variant.hpp | 182 + .../boost/variant/recursive_wrapper.hpp | 123 + .../boost/variant/recursive_wrapper_fwd.hpp | 147 + .../boost/variant/static_visitor.hpp | 97 + utils/boost_idb/boost/variant/variant.hpp | 1828 ++ utils/boost_idb/boost/variant/variant_fwd.hpp | 253 + utils/boost_idb/boost/variant/visitor_ptr.hpp | 116 + utils/boost_idb/boost/version.hpp | 7 +- utils/boost_idb/boost/wave.hpp | 23 + utils/boost_idb/c_regex_traits.cpp | 21 +- utils/boost_idb/codecvt_error_category.cpp | 84 - utils/boost_idb/cregex.cpp | 17 +- utils/boost_idb/date_generators.cpp | 38 + utils/boost_idb/error_code.cpp | 89 +- utils/boost_idb/fileiter.cpp | 12 +- utils/boost_idb/future.cpp | 63 - utils/boost_idb/greg_month.cpp | 10 +- utils/boost_idb/greg_names.hpp | 2 +- utils/boost_idb/greg_weekday.cpp | 50 + utils/boost_idb/gregorian_types.cpp | 62 + utils/boost_idb/internals.hpp | 35 - .../libs/detail/utf8_codecvt_facet.cpp | 285 + utils/boost_idb/local_free_on_destruction.hpp | 40 - utils/boost_idb/once.cpp | 59 +- utils/boost_idb/once_atomic.cpp | 90 - utils/boost_idb/operations.cpp | 3124 ++- utils/boost_idb/path.cpp | 1010 +- utils/boost_idb/path_traits.cpp | 200 - utils/boost_idb/portability.cpp | 56 +- utils/boost_idb/posix_api.cpp | 11 +- utils/boost_idb/posix_time_types.cpp | 35 + utils/boost_idb/regex.cpp | 17 +- utils/boost_idb/regex_raw_buffer.cpp | 4 +- utils/boost_idb/thread.cpp | 399 +- utils/boost_idb/timeconv.inl | 38 +- utils/boost_idb/tss_null.cpp | 38 - utils/boost_idb/unique_path.cpp | 142 - utils/boost_idb/utf8_codecvt_facet.cpp | 11 +- .../detail => }/utf8_codecvt_facet.hpp | 0 utils/boost_idb/w32_regex_traits.cpp | 12 +- utils/boost_idb/wc_regex_traits.cpp | 21 +- utils/boost_idb/wide_posix_api.cpp | 16 +- utils/boost_idb/windows_file_codecvt.cpp | 75 - utils/cacheutils/Makefile.am | 26 +- utils/cacheutils/Makefile.in | 40 +- utils/cacheutils/cacheutils.cpp | 53 +- utils/cacheutils/cacheutils.h | 7 +- utils/cacheutils/libcacheutils.vcxproj | 216 - .../cacheutils/libcacheutils.vcxproj.filters | 27 - utils/common/Makefile.am | 33 +- utils/common/Makefile.in | 54 +- utils/common/MonitorProcMem.cpp | 193 - utils/common/MonitorProcMem.h | 123 - utils/common/atomicops.h | 169 - utils/common/branchpred.h | 35 - utils/common/cgroupconfigurator.cpp | 485 - utils/common/cgroupconfigurator.h | 71 - utils/common/fixedallocator.cpp | 32 +- utils/common/fixedallocator.h | 15 +- utils/common/hasher.h | 58 +- utils/common/libcommon.vcxproj | 232 - utils/common/libcommon.vcxproj.filters | 69 - utils/common/nullvaluemanip.cpp | 169 - utils/common/nullvaluemanip.h | 34 - utils/common/simpleallocator.h | 2 +- utils/common/stlpoolallocator.h | 8 +- utils/compress/Makefile.am | 34 +- utils/compress/Makefile.in | 178 +- utils/compress/idbcompress.cpp | 51 +- utils/compress/idbcompress.h | 70 +- utils/compress/libcompress-ent.vcxproj | 245 - .../compress/libcompress-ent.vcxproj.filters | 60 - utils/compress/snappy-config-win.h | 35 +- utils/compress/snappy-config.h | 35 +- utils/compress/snappy-internal.h | 4 +- utils/compress/snappy-stubs-internal.cpp | 42 - utils/compress/snappy-stubs-internal.h | 85 +- utils/compress/snappy-stubs-public.h | 17 +- utils/compress/snappy.cpp | 347 +- utils/compress/snappy.h | 47 +- utils/compress/version1.cpp | 30 +- utils/compress/version1.h | 17 - utils/configcpp/Makefile.am | 26 +- utils/configcpp/Makefile.in | 40 +- utils/configcpp/configcpp.cpp | 123 +- utils/configcpp/configcpp.h | 37 +- utils/configcpp/libconfigcpp.rc | 102 - utils/configcpp/libconfigcpp.vcxproj | 303 - utils/configcpp/libconfigcpp.vcxproj.filters | 59 - utils/configcpp/md5/Makefile.am | 14 - utils/configcpp/md5/md32_common.h | 415 - utils/configcpp/md5/md5.h | 116 - utils/configcpp/md5/md5_dgst.c | 183 - utils/configcpp/md5/md5_locl.h | 132 - utils/configcpp/md5/md5_one.c | 101 - utils/configcpp/md5/mem_clr.c | 76 - utils/configcpp/resource.h | 14 - utils/configcpp/versionnumber.h | 8 - utils/configcpp/writeonce.cpp | 2 +- utils/configcpp/writeonce.h | 2 +- utils/configcpp/xmlparser.cpp | 48 - utils/configcpp/xmlparser.h | 5 - utils/dataconvert/Makefile.am | 26 +- utils/dataconvert/Makefile.in | 40 +- utils/dataconvert/dataconvert.cpp | 1681 +- utils/dataconvert/dataconvert.h | 164 +- utils/dataconvert/libdataconvert.vcxproj | 220 - .../libdataconvert.vcxproj.filters | 27 - utils/dataconvert/tdriver.cpp | 82 +- utils/ddlcleanup/Makefile.am | 26 +- utils/ddlcleanup/Makefile.in | 40 +- utils/ddlcleanup/ddlcleanuputil.cpp | 338 +- utils/ddlcleanup/ddlcleanuputil.h | 2 +- utils/ddlcleanup/libddlcleanup.vcxproj | 222 - .../ddlcleanup/libddlcleanup.vcxproj.filters | 27 - utils/funcexp/Makefile.am | 28 +- utils/funcexp/Makefile.in | 75 +- utils/funcexp/func_abs.cpp | 10 +- utils/funcexp/func_add_time.cpp | 18 +- utils/funcexp/func_ascii.cpp | 4 +- utils/funcexp/func_between.cpp | 35 +- utils/funcexp/func_bitand.cpp | 11 +- utils/funcexp/func_bitwise.cpp | 46 +- utils/funcexp/func_case.cpp | 29 +- utils/funcexp/func_cast.cpp | 398 +- utils/funcexp/func_ceil.cpp | 159 +- utils/funcexp/func_char.cpp | 166 +- utils/funcexp/func_char_length.cpp | 12 +- utils/funcexp/func_coalesce.cpp | 14 +- utils/funcexp/func_concat.cpp | 35 +- utils/funcexp/func_concat_ws.cpp | 4 +- utils/funcexp/func_conv.cpp | 34 +- utils/funcexp/func_crc32.cpp | 4 +- utils/funcexp/func_date.cpp | 14 +- utils/funcexp/func_date_add.cpp | 621 +- utils/funcexp/func_date_format.cpp | 88 +- utils/funcexp/func_day.cpp | 2 +- utils/funcexp/func_dayname.cpp | 8 +- utils/funcexp/func_dayofweek.cpp | 4 +- utils/funcexp/func_dayofyear.cpp | 5 +- utils/funcexp/func_div.cpp | 22 +- utils/funcexp/func_elt.cpp | 4 +- utils/funcexp/func_exp.cpp | 2 +- utils/funcexp/func_extract.cpp | 135 +- utils/funcexp/func_find_in_set.cpp | 8 +- utils/funcexp/func_floor.cpp | 142 +- utils/funcexp/func_from_days.cpp | 51 +- utils/funcexp/func_from_unixtime.cpp | 33 +- utils/funcexp/func_greatest.cpp | 35 +- utils/funcexp/func_hex.cpp | 28 +- utils/funcexp/func_hour.cpp | 2 +- utils/funcexp/func_idbpartition.cpp | 70 - utils/funcexp/func_if.cpp | 15 +- utils/funcexp/func_ifnull.cpp | 4 +- utils/funcexp/func_in.cpp | 44 +- utils/funcexp/func_inet_aton.cpp | 16 +- utils/funcexp/func_inet_ntoa.cpp | 55 +- utils/funcexp/func_insert.cpp | 79 +- utils/funcexp/func_instr.cpp | 2 +- utils/funcexp/func_isnull.cpp | 5 +- utils/funcexp/func_last_day.cpp | 1 - utils/funcexp/func_lcase.cpp | 6 +- utils/funcexp/func_least.cpp | 16 +- utils/funcexp/func_left.cpp | 4 +- utils/funcexp/func_length.cpp | 2 +- utils/funcexp/func_lpad.cpp | 138 +- utils/funcexp/func_ltrim.cpp | 7 +- utils/funcexp/func_makedate.cpp | 27 +- utils/funcexp/func_maketime.cpp | 21 +- utils/funcexp/func_math.cpp | 176 +- utils/funcexp/func_md5.cpp | 4 +- utils/funcexp/func_microsecond.cpp | 18 + utils/funcexp/func_minute.cpp | 2 +- utils/funcexp/func_mod.cpp | 28 +- utils/funcexp/func_month.cpp | 2 +- utils/funcexp/func_monthname.cpp | 2 +- utils/funcexp/func_nullif.cpp | 108 +- utils/funcexp/func_period_diff.cpp | 6 +- utils/funcexp/func_pow.cpp | 2 +- utils/funcexp/func_quarter.cpp | 2 +- utils/funcexp/func_rand.cpp | 2 +- utils/funcexp/func_regexp.cpp | 24 +- utils/funcexp/func_replace.cpp | 8 +- utils/funcexp/func_reverse.cpp | 6 +- utils/funcexp/func_right.cpp | 4 +- utils/funcexp/func_round.cpp | 60 +- utils/funcexp/func_rpad.cpp | 116 +- utils/funcexp/func_rtrim.cpp | 10 +- utils/funcexp/func_sec_to_time.cpp | 47 +- utils/funcexp/func_second.cpp | 2 +- utils/funcexp/func_sign.cpp | 2 +- utils/funcexp/func_str_to_date.cpp | 422 +- utils/funcexp/func_strcmp.cpp | 4 +- utils/funcexp/func_substr.cpp | 6 +- utils/funcexp/func_substring_index.cpp | 4 +- utils/funcexp/func_sysdate.cpp | 2 +- utils/funcexp/func_time.cpp | 2 +- utils/funcexp/func_time_format.cpp | 4 +- utils/funcexp/func_time_to_sec.cpp | 20 +- utils/funcexp/func_timediff.cpp | 24 +- utils/funcexp/func_timestampdiff.cpp | 30 +- utils/funcexp/func_to_days.cpp | 10 +- utils/funcexp/func_trim.cpp | 15 +- utils/funcexp/func_truncate.cpp | 55 +- utils/funcexp/func_ucase.cpp | 6 +- utils/funcexp/func_unhex.cpp | 10 +- utils/funcexp/func_unix_timestamp.cpp | 8 +- utils/funcexp/func_week.cpp | 13 +- utils/funcexp/func_weekday.cpp | 6 +- utils/funcexp/func_year.cpp | 2 +- utils/funcexp/func_yearweek.cpp | 13 +- utils/funcexp/funcexp.cpp | 59 +- utils/funcexp/funcexp.h | 2 +- utils/funcexp/funcexpwrapper.cpp | 10 +- utils/funcexp/funcexpwrapper.h | 10 +- utils/funcexp/funchelpers.h | 1002 +- utils/funcexp/functor.cpp | 21 +- utils/funcexp/functor.h | 10 +- utils/funcexp/functor_all.h | 14 +- utils/funcexp/functor_bool.h | 2 +- utils/funcexp/functor_dtm.h | 2 +- utils/funcexp/functor_export.h | 2 +- utils/funcexp/functor_int.h | 29 +- utils/funcexp/functor_real.h | 41 +- utils/funcexp/functor_str.h | 26 +- utils/funcexp/libfuncexp.vcxproj | 332 - utils/funcexp/libfuncexp.vcxproj.filters | 369 - utils/funcexp/tdriver.cpp | 329 +- utils/funcexp/timeextract.h | 451 - utils/funcexp/utf8.h | 34 - utils/funcexp/utf8/checked.h | 327 - utils/funcexp/utf8/core.h | 323 - utils/funcexp/utf8/unchecked.h | 228 - utils/funcexp/utils_utf8.h | 51 +- utils/idbdatafile/BufferedFile.cpp | 266 - utils/idbdatafile/BufferedFile.h | 65 - utils/idbdatafile/BufferedFileFactory.h | 41 - utils/idbdatafile/FileFactoryBase.h | 34 - utils/idbdatafile/IDBDataFile.cpp | 57 - utils/idbdatafile/IDBDataFile.h | 235 - utils/idbdatafile/IDBFactory.cpp | 118 - utils/idbdatafile/IDBFactory.h | 121 - utils/idbdatafile/IDBFileSystem.cpp | 32 - utils/idbdatafile/IDBFileSystem.h | 140 - utils/idbdatafile/IDBLogger.cpp | 215 - utils/idbdatafile/IDBLogger.h | 72 - utils/idbdatafile/IDBPolicy.cpp | 231 - utils/idbdatafile/IDBPolicy.h | 216 - utils/idbdatafile/Makefile.am | 57 - utils/idbdatafile/Makefile.in | 571 - utils/idbdatafile/PosixFileSystem.cpp | 201 - utils/idbdatafile/PosixFileSystem.h | 44 - utils/idbdatafile/UnbufferedFile.cpp | 306 - utils/idbdatafile/UnbufferedFile.h | 64 - utils/idbdatafile/UnbufferedFileFactory.h | 41 - utils/idbdatafile/idbdatafile.vcxproj | 242 - utils/idbdatafile/idbdatafile.vcxproj.filters | 81 - utils/idbdatafile/largefile64.h | 46 - utils/idbdatafile/tdriver.cpp | 1512 -- utils/idbdatafile/tdriver1.cpp | 34 - utils/idbdatafile/utility.h | 118 - utils/idbhdfs/FOSS-EXCEPTION.txt | 67 - utils/idbhdfs/Makefile.am | 43 - utils/idbhdfs/Makefile.in | 545 - utils/idbhdfs/hdfs-12/Makefile.am | 57 - utils/idbhdfs/hdfs-12/Makefile.in | 633 - utils/idbhdfs/hdfs-12/hdfs.h | 475 - utils/idbhdfs/hdfs-12/libhdfs.so | Bin 122188 -> 0 bytes utils/idbhdfs/hdfs-12/setenv-hdfs-12 | 216 - utils/idbhdfs/hdfs-20/Makefile.am | 57 - utils/idbhdfs/hdfs-20/Makefile.in | 633 - utils/idbhdfs/hdfs-20/hdfs.h | 656 - utils/idbhdfs/hdfs-20/libhdfs.so | Bin 50280 -> 0 bytes utils/idbhdfs/hdfs-20/setenv-hdfs-20 | 181 - utils/idbhdfs/hdfs-shared/HdfsFile.cpp | 324 - utils/idbhdfs/hdfs-shared/HdfsFile.h | 81 - utils/idbhdfs/hdfs-shared/HdfsFileFactory.h | 83 - utils/idbhdfs/hdfs-shared/HdfsFileSystem.cpp | 194 - utils/idbhdfs/hdfs-shared/HdfsFileSystem.h | 62 - utils/idbhdfs/hdfs-shared/HdfsFsCache.cpp | 57 - utils/idbhdfs/hdfs-shared/HdfsFsCache.h | 63 - utils/idbhdfs/hdfs-shared/HdfsPlugin.cpp | 45 - .../hdfs-shared/HdfsRdwrFileBuffer.cpp | 300 - .../idbhdfs/hdfs-shared/HdfsRdwrFileBuffer.h | 77 - .../idbhdfs/hdfs-shared/HdfsRdwrMemBuffer.cpp | 479 - utils/idbhdfs/hdfs-shared/HdfsRdwrMemBuffer.h | 99 - .../hadoop/db/IDBFileInputFormat.java | 369 +- .../hadoop/db/InfiniDBConfiguration.java | 713 +- .../hadoop/db/InfiniDBInputFormat.java | 885 +- .../hadoop/db/InfiniDBOutputFormat.java | 279 +- .../hadoop/example/InfiniDBOutputDriver.java | 171 +- .../hadoop/example/InfiniDoopDriver.java | 175 +- .../hadoop/example/InfiniDoopInputMapper.java | 81 +- .../hadoop/example/InfiniDoopMapper.java | 85 +- .../hadoop/example/InfiniDoopRecord.java | 121 +- utils/jemalloc/Makefile.am | 19 +- utils/jemalloc/Makefile.in | 375 - utils/jemalloc/jemalloc-3.3.0.tar.gz | Bin 335781 -> 0 bytes utils/joiner/Makefile.am | 30 +- utils/joiner/Makefile.in | 47 +- utils/joiner/btree.h | 2284 --- utils/joiner/btree_container.h | 349 - utils/joiner/btree_map.h | 130 - utils/joiner/btree_set.h | 121 - utils/joiner/joiner.cpp | 12 + utils/joiner/joiner.h | 12 + utils/joiner/joinpartition.cpp | 762 - utils/joiner/joinpartition.h | 167 - utils/joiner/libjoiner.vcxproj | 222 - utils/joiner/libjoiner.vcxproj.filters | 39 - utils/joiner/tuplejoiner.cpp | 621 +- utils/joiner/tuplejoiner.h | 132 +- utils/joiner/type_traits_hm | 196 - utils/libxml/nanohttp.c | 2 +- utils/loggingcpp/ErrorMessage.txt | 50 +- utils/loggingcpp/Makefile.am | 26 +- utils/loggingcpp/Makefile.in | 40 +- utils/loggingcpp/MessageFile.txt | 7 - utils/loggingcpp/SubsystemIDs.txt | 4 +- utils/loggingcpp/errorcodes.cpp | 3 +- utils/loggingcpp/errorcodes.h | 3 +- utils/loggingcpp/errorids.h | 43 - utils/loggingcpp/exceptclasses.h | 64 +- utils/loggingcpp/genErrId.pl | 16 +- utils/loggingcpp/genMsgId.pl | 16 +- utils/loggingcpp/idberrorinfo.cpp | 20 +- utils/loggingcpp/idberrorinfo.h | 7 +- utils/loggingcpp/libloggingcpp.vcxproj | 222 - .../loggingcpp/libloggingcpp.vcxproj.filters | 75 - utils/loggingcpp/logger.cpp | 6 +- utils/loggingcpp/logger.h | 2 +- utils/loggingcpp/loggingid.h | 2 +- utils/loggingcpp/message.cpp | 2 +- utils/loggingcpp/messageids.h | 7 - utils/loggingcpp/messagelog.cpp | 36 +- utils/loggingcpp/messagelog.h | 2 +- utils/loggingcpp/messageobj.h | 10 +- utils/loggingcpp/sqllogger.h | 6 +- utils/loggingcpp/stopwatch.cpp | 10 +- utils/loggingcpp/stopwatch.h | 4 +- utils/loggingcpp/tdriver.cpp | 2 +- utils/messageqcpp/Makefile.am | 32 +- utils/messageqcpp/Makefile.in | 50 +- utils/messageqcpp/bytestream.cpp | 229 +- utils/messageqcpp/bytestream.h | 210 +- utils/messageqcpp/cli.cpp | 2 +- utils/messageqcpp/clientsocket.h | 104 + utils/messageqcpp/compressed_iss.cpp | 239 - utils/messageqcpp/compressed_iss.h | 61 - utils/messageqcpp/inetstreamsocket.cpp | 98 +- utils/messageqcpp/inetstreamsocket.h | 49 +- utils/messageqcpp/iosocket.cpp | 9 +- utils/messageqcpp/iosocket.h | 41 +- utils/messageqcpp/libmessageqcpp.vcxproj | 230 - .../libmessageqcpp.vcxproj.filters | 69 - utils/messageqcpp/messagequeue.cpp | 134 +- utils/messageqcpp/messagequeue.h | 51 +- utils/messageqcpp/serversocket.h | 2 +- utils/messageqcpp/socket.h | 36 +- utils/messageqcpp/socketparms.cpp | 2 +- utils/messageqcpp/socketparms.h | 2 +- utils/messageqcpp/srv.cpp | 2 +- utils/messageqcpp/tdriver.cpp | 415 +- utils/multicast/Makefile.am | 26 +- utils/multicast/Makefile.in | 533 + utils/multicast/impl.cpp | 6 +- utils/multicast/impl.h | 4 +- utils/multicast/libmulticast.vcxproj | 210 - utils/multicast/libmulticast.vcxproj.filters | 27 - utils/multicast/multicast.cpp | 2 +- utils/multicast/multicast.h | 2 +- utils/mysqlcl_idb/Makefile.am | 26 +- utils/mysqlcl_idb/Makefile.in | 40 +- utils/mysqlcl_idb/libdrizzle-2.0/drizzle.h | 1 + utils/mysqlcl_idb/libmysqlcl_idb.vcxproj | 235 - .../libmysqlcl_idb.vcxproj.filters | 171 - utils/mysqlcl_idb/tdriver-works.cpp | 122 - utils/mysqlcl_idb/tdriver.cpp | 114 - utils/mysqlcl_idb/tdriver1.cpp | 53 - utils/net-snmp/Makefile.in | 670 - utils/net-snmp/types.h | 8 +- utils/querystats/Makefile.am | 26 +- utils/querystats/Makefile.in | 40 +- utils/querystats/libquerystats.vcxproj | 219 - .../querystats/libquerystats.vcxproj.filters | 27 - utils/querystats/querystats.cpp | 92 +- utils/querystats/querystats.h | 24 +- utils/querytele/Makefile.am | 46 - utils/querytele/Makefile.in | 559 - utils/querytele/QueryTeleService.cpp | 748 - utils/querytele/QueryTeleService.h | 437 - utils/querytele/libquerytele.vcxproj | 234 - utils/querytele/libquerytele.vcxproj.filters | 63 - utils/querytele/querystepparms.h | 43 - utils/querytele/querytele.cpp | 59 - utils/querytele/querytele.h | 31 - utils/querytele/querytele.thrift | 139 - utils/querytele/querytele_constants.cpp | 17 - utils/querytele/querytele_constants.h | 24 - utils/querytele/querytele_types.cpp | 989 - utils/querytele/querytele_types.h | 719 - utils/querytele/queryteleclient.cpp | 263 - utils/querytele/queryteleclient.h | 82 - utils/querytele/queryteleprotoimpl.cpp | 389 - utils/querytele/queryteleprotoimpl.h | 51 - utils/querytele/queryteleserverparms.h | 45 - utils/querytele/serverdriver.cpp | 196 - utils/querytele/tdriver.cpp | 71 - utils/querytele/telestats.h | 192 - utils/rowgroup/Makefile.am | 26 +- utils/rowgroup/Makefile.in | 40 +- utils/rowgroup/librowgroup.vcxproj | 226 - utils/rowgroup/librowgroup.vcxproj.filters | 33 - utils/rowgroup/rowaggregation.cpp | 1188 +- utils/rowgroup/rowaggregation.h | 221 +- utils/rowgroup/rowgroup.cpp | 984 +- utils/rowgroup/rowgroup.h | 1177 +- utils/rwlock/Makefile.am | 26 +- utils/rwlock/Makefile.in | 40 +- utils/rwlock/librwlock.vcxproj | 221 - utils/rwlock/librwlock.vcxproj.filters | 33 - utils/rwlock/rwlock.cpp | 90 +- utils/rwlock/rwlock.h | 12 +- utils/rwlock/tdriver-rw.cpp | 80 +- utils/startup/Makefile.am | 26 +- utils/startup/Makefile.in | 40 +- utils/startup/libidbboot.vcxproj | 189 - utils/startup/libidbboot.vcxproj.filters | 27 - utils/testbc/fileblockrequestqueue.h | 4 +- utils/testbc/filebuffer.cpp | 4 +- utils/testbc/filebuffer.h | 10 +- utils/testbc/filebuffermgr.h | 2 +- utils/testbc/iomanager.cpp | 4 +- utils/testbc/iomanager.h | 6 +- utils/testbc/testbc.cpp | 10 +- utils/testbc/testbc2.cpp | 10 +- utils/testbc/testbc3.cpp | 8 +- utils/threadpool/Makefile.am | 26 +- utils/threadpool/Makefile.in | 40 +- utils/threadpool/libthreadpool.vcxproj | 222 - .../threadpool/libthreadpool.vcxproj.filters | 39 - utils/threadpool/prioritythreadpool.cpp | 22 +- utils/threadpool/prioritythreadpool.h | 20 +- utils/threadpool/tdriver.cpp | 2 +- utils/threadpool/threadpool.cpp | 21 +- utils/threadpool/threadpool.h | 10 +- utils/threadpool/weightedthreadpool.h | 4 +- utils/thrift/Makefile.am | 48 - utils/thrift/Makefile.in | 603 - utils/thrift/README | 6 - utils/thrift/libthrift.vcxproj | 296 - utils/thrift/libthrift.vcxproj.filters | 292 - utils/thrift/thrift/TApplicationException.cpp | 80 - utils/thrift/thrift/TApplicationException.h | 115 - utils/thrift/thrift/TDispatchProcessor.h | 142 - utils/thrift/thrift/TLogging.h | 193 - utils/thrift/thrift/TProcessor.h | 233 - utils/thrift/thrift/TReflectionLocal.h | 96 - utils/thrift/thrift/Thrift.cpp | 125 - utils/thrift/thrift/Thrift.h | 202 - .../thrift/async/TAsyncBufferProcessor.h | 46 - utils/thrift/thrift/async/TAsyncChannel.h | 66 - .../thrift/async/TAsyncDispatchProcessor.h | 149 - utils/thrift/thrift/async/TAsyncProcessor.h | 97 - .../thrift/async/TAsyncProtocolProcessor.h | 57 - .../thrift/async/TEvhttpClientChannel.h | 76 - utils/thrift/thrift/async/TEvhttpServer.h | 71 - .../thrift/concurrency/BoostThreadFactory.h | 75 - utils/thrift/thrift/concurrency/Exception.h | 64 - .../thrift/concurrency/FunctionRunner.h | 121 - utils/thrift/thrift/concurrency/Monitor.h | 130 - utils/thrift/thrift/concurrency/Mutex.h | 188 - .../concurrency/PlatformThreadFactory.h | 44 - .../thrift/concurrency/PosixThreadFactory.h | 130 - .../thrift/concurrency/StdThreadFactory.h | 72 - utils/thrift/thrift/concurrency/Thread.h | 152 - .../thrift/thrift/concurrency/ThreadManager.h | 202 - .../thrift/thrift/concurrency/TimerManager.h | 130 - utils/thrift/thrift/concurrency/Util.h | 152 - utils/thrift/thrift/config.h | 427 - utils/thrift/thrift/cxxfunctional.h | 126 - utils/thrift/thrift/processor/PeekProcessor.h | 78 - .../thrift/thrift/processor/StatsProcessor.h | 266 - .../thrift/processor/TMultiplexedProcessor.h | 218 - utils/thrift/thrift/protocol/TBase64Utils.h | 42 - .../thrift/thrift/protocol/TBinaryProtocol.h | 282 - .../thrift/protocol/TBinaryProtocol.tcc | 465 - .../thrift/thrift/protocol/TCompactProtocol.h | 289 - .../thrift/protocol/TCompactProtocol.tcc | 818 - utils/thrift/thrift/protocol/TDebugProtocol.h | 227 - utils/thrift/thrift/protocol/TDenseProtocol.h | 254 - utils/thrift/thrift/protocol/TJSONProtocol.h | 339 - .../thrift/protocol/TMultiplexedProtocol.h | 103 - utils/thrift/thrift/protocol/TProtocol.h | 697 - .../thrift/protocol/TProtocolDecorator.h | 133 - .../thrift/protocol/TProtocolException.h | 104 - utils/thrift/thrift/protocol/TProtocolTap.h | 188 - .../thrift/thrift/protocol/TVirtualProtocol.h | 564 - utils/thrift/thrift/qt/TQIODeviceTransport.h | 64 - utils/thrift/thrift/qt/TQTcpServer.h | 72 - .../thrift/thrift/server/TNonblockingServer.h | 944 - utils/thrift/thrift/server/TServer.h | 315 - utils/thrift/thrift/server/TSimpleServer.cpp | 153 - utils/thrift/thrift/server/TSimpleServer.h | 102 - .../thrift/thrift/server/TThreadPoolServer.h | 136 - utils/thrift/thrift/server/TThreadedServer.h | 145 - utils/thrift/thrift/thrift-config.h | 24 - .../thrift/thrift/transport/PlatformSocket.h | 96 - .../thrift/transport/TBufferTransports.cpp | 391 - .../thrift/transport/TBufferTransports.h | 735 - utils/thrift/thrift/transport/TFDTransport.h | 75 - .../thrift/thrift/transport/TFileTransport.h | 474 - utils/thrift/thrift/transport/THttpClient.h | 49 - utils/thrift/thrift/transport/THttpServer.h | 64 - .../thrift/thrift/transport/THttpTransport.h | 107 - utils/thrift/thrift/transport/TPipe.h | 96 - utils/thrift/thrift/transport/TPipeServer.h | 93 - .../thrift/transport/TSSLServerSocket.h | 59 - utils/thrift/thrift/transport/TSSLSocket.h | 315 - .../thrift/thrift/transport/TServerSocket.cpp | 490 - utils/thrift/thrift/transport/TServerSocket.h | 86 - .../thrift/transport/TServerTransport.h | 92 - .../thrift/transport/TShortReadTransport.h | 97 - .../thrift/transport/TSimpleFileTransport.h | 41 - utils/thrift/thrift/transport/TSocket.cpp | 813 - utils/thrift/thrift/transport/TSocket.h | 309 - utils/thrift/thrift/transport/TSocketPool.h | 196 - utils/thrift/thrift/transport/TTransport.h | 270 - .../thrift/transport/TTransportException.h | 115 - .../thrift/thrift/transport/TTransportUtils.h | 330 - .../thrift/transport/TVirtualTransport.h | 146 - .../thrift/thrift/transport/TZlibTransport.h | 249 - utils/thrift/thrift/windows/GetTimeOfDay.cpp | 112 - utils/thrift/thrift/windows/GetTimeOfDay.h | 43 - utils/thrift/thrift/windows/Operators.h | 40 - utils/thrift/thrift/windows/SocketPair.h | 37 - utils/thrift/thrift/windows/StdAfx.h | 0 .../thrift/windows/TWinsockSingleton.cpp | 73 - .../thrift/thrift/windows/TWinsockSingleton.h | 88 - utils/thrift/thrift/windows/TargetVersion.h | 0 utils/thrift/thrift/windows/WinFcntl.cpp | 104 - utils/thrift/thrift/windows/WinFcntl.h | 48 - utils/thrift/thrift/windows/config.h | 90 - utils/thrift/thrift/windows/force_inc.h | 0 utils/udfsdk/Makefile.am | 19 +- utils/udfsdk/Makefile.in | 543 - utils/udfsdk/Makefile.sdk | 32 + utils/udfsdk/README.txt | 24 +- utils/udfsdk/libudf_mysql.rc | 102 - utils/udfsdk/libudf_mysql.vcxproj | 261 - utils/udfsdk/libudf_mysql.vcxproj.filters | 32 - utils/udfsdk/libudfsdk.rc | 102 - utils/udfsdk/libudfsdk.vcxproj | 285 - utils/udfsdk/libudfsdk.vcxproj.filters | 35 - utils/udfsdk/make_sdk.sh | 9 + utils/udfsdk/resource.h | 14 - utils/udfsdk/udfinfinidb.cpp | 401 - utils/udfsdk/udfmysql.cpp | 179 - utils/udfsdk/udfsdk.cpp | 543 + utils/udfsdk/udfsdk.h | 17 - utils/windowfunction/Makefile.am | 63 - utils/windowfunction/Makefile.in | 590 - utils/windowfunction/framebound.cpp | 88 - utils/windowfunction/framebound.h | 127 - utils/windowfunction/frameboundrange.cpp | 368 - utils/windowfunction/frameboundrange.h | 208 - utils/windowfunction/frameboundrow.cpp | 154 - utils/windowfunction/frameboundrow.h | 152 - utils/windowfunction/idborderby.cpp | 466 - utils/windowfunction/idborderby.h | 263 - .../windowfunction/libwindowfunction.vcxproj | 246 - .../libwindowfunction.vcxproj.filters | 129 - utils/windowfunction/wf_count.cpp | 158 - utils/windowfunction/wf_count.h | 57 - utils/windowfunction/wf_lead_lag.cpp | 273 - utils/windowfunction/wf_lead_lag.h | 62 - utils/windowfunction/wf_min_max.cpp | 164 - utils/windowfunction/wf_min_max.h | 55 - utils/windowfunction/wf_nth_value.cpp | 253 - utils/windowfunction/wf_nth_value.h | 60 - utils/windowfunction/wf_ntile.cpp | 162 - utils/windowfunction/wf_ntile.h | 57 - utils/windowfunction/wf_percentile.cpp | 344 - utils/windowfunction/wf_percentile.h | 58 - utils/windowfunction/wf_ranking.cpp | 150 - utils/windowfunction/wf_ranking.h | 56 - utils/windowfunction/wf_row_number.cpp | 96 - utils/windowfunction/wf_row_number.h | 55 - utils/windowfunction/wf_stats.cpp | 210 - utils/windowfunction/wf_stats.h | 57 - utils/windowfunction/wf_sum_avg.cpp | 291 - utils/windowfunction/wf_sum_avg.h | 60 - utils/windowfunction/windowframe.cpp | 90 - utils/windowfunction/windowframe.h | 100 - utils/windowfunction/windowfunction.cpp | 240 - utils/windowfunction/windowfunction.h | 125 - utils/windowfunction/windowfunctiontype.cpp | 571 - utils/windowfunction/windowfunctiontype.h | 214 - utils/winport/Calpont.xml | 25 +- utils/winport/Makefile.am | 37 - utils/winport/Makefile.in | 458 - utils/winport/WinSyslog.cpp | 298 - utils/winport/WinSyslog.h | 79 - utils/winport/bootstrap.cpp | 656 +- utils/winport/bootstrap.vcxproj | 266 - utils/winport/bootstrap.vcxproj.filters | 42 - utils/winport/fixup.cpp | 913 +- utils/winport/glob.c | 18 - utils/winport/grepit.cpp | 60 +- utils/winport/idb_32_community.nsi | 416 + utils/winport/idb_64_community.nsi | 418 + utils/winport/idb_64_enterprise-Debug.nsi | 452 - utils/winport/idb_64_enterprise.nsi | 288 +- utils/winport/idb_64_standard.nsi | 443 - utils/winport/idb_getopt.cpp | 2 +- utils/winport/idb_getopt.h | 2 +- utils/winport/idbmysql.bat | 1 - utils/winport/inttypes.h | 31 - utils/winport/libwinport.vcxproj | 236 - utils/winport/libwinport.vcxproj.filters | 78 - utils/winport/my.ini | 5 +- utils/winport/resource.h | 14 - utils/winport/stdint.h | 63 + utils/winport/strtoll.c | 40 +- utils/winport/sysinfo.cpp | 108 - utils/winport/sysinfo.h | 39 - utils/winport/syslog.h | 80 +- utils/winport/unistd.h | 271 +- utils/winport/win_setup_mysql_part4.sql | 11 - utils/winport/win_setup_mysql_part5.sql | 3 - utils/winport/winfinidb.cpp | 95 +- utils/winport/winfinidb.rc | 102 - utils/winport/winfinidb.vcxproj | 269 - utils/winport/winfinidb.vcxproj.filters | 32 - utils/winport/winport.cpp | 383 +- utils/winport/winport.h | 25 - versioning/BRM/Makefile.am | 50 +- versioning/BRM/Makefile.in | 76 +- versioning/BRM/autoincrementmanager.cpp | 12 +- versioning/BRM/autoincrementmanager.h | 6 +- versioning/BRM/autoinctest.cpp | 7 +- versioning/BRM/blockresolutionmanager.cpp | 31 +- versioning/BRM/blockresolutionmanager.h | 10 +- versioning/BRM/brm.h | 2 +- versioning/BRM/brmtypes.cpp | 78 +- versioning/BRM/brmtypes.h | 106 +- versioning/BRM/controllernode.rc | 102 - versioning/BRM/controllernode.vcxproj | 335 - versioning/BRM/controllernode.vcxproj.filters | 38 - versioning/BRM/copylocks.cpp | 162 +- versioning/BRM/copylocks.h | 16 +- versioning/BRM/copylocktest.cpp | 3 - versioning/BRM/cvt_em.cpp | 6 +- versioning/BRM/dbrm.cpp | 505 +- versioning/BRM/dbrm.h | 202 +- versioning/BRM/dbrmctl.cpp | 6 +- versioning/BRM/dbrmctl.vcxproj | 297 - versioning/BRM/dbrmctl.vcxproj.filters | 27 - versioning/BRM/extentmap.cpp | 2701 +-- versioning/BRM/extentmap.h | 277 +- versioning/BRM/ipcs-pat.c | 718 + versioning/BRM/lbidresourcegraph.cpp | 2 +- versioning/BRM/lbidresourcegraph.h | 2 +- versioning/BRM/libbrm.rc | 102 - versioning/BRM/libbrm.vcxproj | 292 - versioning/BRM/libbrm.vcxproj.filters | 162 - versioning/BRM/load_brm.cpp | 17 +- versioning/BRM/load_brm.vcxproj | 306 - versioning/BRM/load_brm.vcxproj.filters | 22 - versioning/BRM/load_brm64.cpp | 5 +- versioning/BRM/load_em.cpp | 5 +- versioning/BRM/lock_grabber.cpp | 87 - versioning/BRM/lock_state.cpp | 66 - versioning/BRM/logicalpartition.cpp | 24 +- versioning/BRM/logicalpartition.h | 2 +- versioning/BRM/masterdbrmnode.cpp | 124 +- versioning/BRM/masterdbrmnode.h | 2 +- versioning/BRM/masternode.cpp | 6 +- versioning/BRM/mastersegmenttable.cpp | 29 +- versioning/BRM/mastersegmenttable.h | 2 +- versioning/BRM/oidserver.cpp | 479 +- versioning/BRM/oidserver.h | 15 +- versioning/BRM/print_journal.cpp | 57 + versioning/BRM/reset_locks.cpp | 23 +- versioning/BRM/reset_locks.vcxproj | 310 - versioning/BRM/reset_locks.vcxproj.filters | 22 - versioning/BRM/resource.h | 14 - versioning/BRM/resourcenode.cpp | 2 +- versioning/BRM/resourcenode.h | 2 +- versioning/BRM/rgnode.cpp | 2 +- versioning/BRM/rgnode.h | 2 +- versioning/BRM/rollback.cpp | 4 +- versioning/BRM/rwlockmonitor.cpp | 2 +- versioning/BRM/rwlockmonitor.h | 6 +- versioning/BRM/save_brm.cpp | 51 +- versioning/BRM/save_brm.vcxproj | 310 - versioning/BRM/save_brm.vcxproj.filters | 22 - versioning/BRM/sessionmanagerserver.cpp | 340 +- versioning/BRM/sessionmanagerserver.h | 67 +- versioning/BRM/shmkeys.cpp | 4 +- versioning/BRM/shmkeys.h | 5 +- versioning/BRM/slavecomm.cpp | 325 +- versioning/BRM/slavecomm.h | 17 +- versioning/BRM/slavedbrmnode.cpp | 225 +- versioning/BRM/slavedbrmnode.h | 54 +- versioning/BRM/slavenode.cpp | 5 +- versioning/BRM/tablelockserver.cpp | 130 +- versioning/BRM/tablelockserver.h | 2 +- versioning/BRM/tablelocktest.cpp | 4 +- versioning/BRM/tdriver-brm.cpp | 128 +- versioning/BRM/tdriver-dbrm.cpp | 30 +- versioning/BRM/tdriver-dbrm2.cpp | 98 +- versioning/BRM/tdriver-load.cpp | 30 +- versioning/BRM/tdriver.cpp | 54 +- versioning/BRM/tracer.cpp | 2 +- versioning/BRM/tracer.h | 2 +- versioning/BRM/transactionnode.cpp | 2 +- versioning/BRM/transactionnode.h | 2 +- versioning/BRM/undoable.cpp | 2 +- versioning/BRM/undoable.h | 2 +- versioning/BRM/vbbm.cpp | 414 +- versioning/BRM/vbbm.h | 21 +- versioning/BRM/vss.cpp | 360 +- versioning/BRM/vss.h | 28 +- versioning/BRM/workernode.rc | 102 - versioning/BRM/workernode.vcxproj | 336 - versioning/BRM/workernode.vcxproj.filters | 32 - versioning/Makefile.am | 26 +- versioning/Makefile.in | 40 +- writeengine/Makefile.am | 26 +- writeengine/Makefile.in | 40 +- writeengine/build/we_rules.mak | 2 - writeengine/bulk/Makefile.am | 28 +- writeengine/bulk/Makefile.in | 42 +- writeengine/bulk/cpimport.cpp | 348 +- writeengine/bulk/cpimport.rc | 100 - writeengine/bulk/cpimport.vcxproj | 375 - writeengine/bulk/cpimport.vcxproj.filters | 146 - writeengine/bulk/resource.h | 14 - writeengine/bulk/we_brmreporter.cpp | 122 +- writeengine/bulk/we_brmreporter.h | 30 +- writeengine/bulk/we_bulkload.cpp | 374 +- writeengine/bulk/we_bulkload.h | 55 +- writeengine/bulk/we_bulkloadbuffer.cpp | 1255 +- writeengine/bulk/we_bulkloadbuffer.h | 60 +- writeengine/bulk/we_bulkstatus.cpp | 20 +- writeengine/bulk/we_bulkstatus.h | 8 +- writeengine/bulk/we_colbuf.cpp | 8 +- writeengine/bulk/we_colbuf.h | 10 +- writeengine/bulk/we_colbufcompressed.cpp | 127 +- writeengine/bulk/we_colbufcompressed.h | 4 +- writeengine/bulk/we_colbufmgr.cpp | 14 +- writeengine/bulk/we_colbufmgr.h | 16 +- writeengine/bulk/we_colbufmgrdctnry.cpp | 10 +- writeengine/bulk/we_colbufsec.cpp | 2 +- writeengine/bulk/we_colbufsec.h | 2 +- writeengine/bulk/we_colextinf.cpp | 54 +- writeengine/bulk/we_colextinf.h | 29 +- writeengine/bulk/we_colopbulk.cpp | 16 +- writeengine/bulk/we_colopbulk.h | 14 +- writeengine/bulk/we_columnautoinc.cpp | 56 +- writeengine/bulk/we_columnautoinc.h | 24 +- writeengine/bulk/we_columninfo.cpp | 200 +- writeengine/bulk/we_columninfo.h | 112 +- writeengine/bulk/we_columninfocompressed.cpp | 332 +- writeengine/bulk/we_columninfocompressed.h | 4 +- writeengine/bulk/we_extentstripealloc.cpp | 2 +- writeengine/bulk/we_extentstripealloc.h | 2 +- writeengine/bulk/we_tableinfo.cpp | 478 +- writeengine/bulk/we_tableinfo.h | 76 +- writeengine/bulk/we_tempxmlgendata.cpp | 2 +- writeengine/bulk/we_tempxmlgendata.h | 2 +- writeengine/bulk/we_workers.cpp | 2 +- writeengine/client/Makefile.am | 26 +- writeengine/client/Makefile.in | 40 +- writeengine/client/libweclient.vcxproj | 216 - .../client/libweclient.vcxproj.filters | 39 - writeengine/client/we_clients.cpp | 153 +- writeengine/client/we_clients.h | 63 +- writeengine/client/we_ddlcommandclient.cpp | 5 +- writeengine/client/we_dmlcommandclient.cpp | 2 +- writeengine/cpimport/Makefile.am | 38 + writeengine/cpimport/Makefile.in | 504 + writeengine/cpimport/main.cpp | 114 + writeengine/dictionary/Makefile.am | 26 +- writeengine/dictionary/Makefile.in | 40 +- writeengine/dictionary/qdctnry.cpp | 18 +- writeengine/dictionary/tdctnry.cpp | 10 +- writeengine/dictionary/we_dctnry.cpp | 759 +- writeengine/dictionary/we_dctnry.h | 79 +- writeengine/dictionary/we_dctnrystore.cpp | 2 +- writeengine/dictionary/we_dctnrystore.h | 2 +- writeengine/index/Makefile.am | 26 +- writeengine/index/Makefile.in | 40 +- writeengine/index/qindex.cpp | 88 +- writeengine/index/tindex.cpp | 130 +- writeengine/index/we_freemgr.cpp | 46 +- writeengine/index/we_freemgr.h | 2 +- writeengine/index/we_indexlist.cpp | 12 +- writeengine/index/we_indexlist.h | 118 +- writeengine/index/we_indexlist_common.cpp | 2132 +- .../index/we_indexlist_find_delete.cpp | 28 +- .../index/we_indexlist_multiple_narray.cpp | 8 +- writeengine/index/we_indexlist_narray.cpp | 14 +- .../index/we_indexlist_update_hdr_sub.cpp | 4 +- writeengine/index/we_indextree.cpp | 44 +- writeengine/index/we_indextree.h | 34 +- writeengine/libwriteengine.rc | 102 - writeengine/libwriteengine.vcxproj | 392 - writeengine/libwriteengine.vcxproj.filters | 206 - writeengine/redistribute/Makefile.am | 26 +- writeengine/redistribute/Makefile.in | 40 +- writeengine/redistribute/we_redistribute.cpp | 2 +- writeengine/redistribute/we_redistribute.h | 2 +- .../redistribute/we_redistributecontrol.cpp | 8 +- .../redistribute/we_redistributecontrol.h | 3 +- .../we_redistributecontrolthread.cpp | 2 +- .../we_redistributecontrolthread.h | 2 +- writeengine/redistribute/we_redistributedef.h | 13 +- .../we_redistributeworkerthread.cpp | 262 +- .../we_redistributeworkerthread.h | 9 +- writeengine/resource.h | 14 - writeengine/server/Makefile.am | 29 +- writeengine/server/Makefile.in | 47 +- writeengine/server/WriteEngineServer.rc | 102 - writeengine/server/WriteEngineServer.vcxproj | 392 - .../server/WriteEngineServer.vcxproj.filters | 119 - writeengine/server/resource.h | 14 - writeengine/server/we_brmrprtparser.cpp | 60 +- writeengine/server/we_brmrprtparser.h | 167 +- writeengine/server/we_cleartablelockcmd.cpp | 35 +- writeengine/server/we_cleartablelockcmd.h | 2 +- writeengine/server/we_cpifeederthread.cpp | 424 +- writeengine/server/we_cpifeederthread.h | 47 +- writeengine/server/we_dataloader.cpp | 162 +- writeengine/server/we_dataloader.h | 42 +- writeengine/server/we_ddlcommandproc.cpp | 1991 +- writeengine/server/we_ddlcommandproc.h | 14 +- writeengine/server/we_ddlcommon.h | 121 +- writeengine/server/we_dmlcommandproc.cpp | 3030 ++- writeengine/server/we_dmlcommandproc.h | 31 +- writeengine/server/we_getfilesizes.cpp | 359 - writeengine/server/we_getfilesizes.h | 78 - writeengine/server/we_message_handlers.h | 2 +- writeengine/server/we_messages.h | 8 +- writeengine/server/we_msg1.cpp | 47 +- writeengine/server/we_msg2.cpp | 47 +- writeengine/server/we_observer.cpp | 47 +- writeengine/server/we_observer.h | 47 +- writeengine/server/we_readthread.cpp | 1278 +- writeengine/server/we_readthread.h | 38 +- writeengine/server/we_server.cpp | 20 +- writeengine/shared/Makefile.am | 28 +- writeengine/shared/Makefile.in | 42 +- writeengine/shared/tshared.cpp | 32 +- writeengine/shared/we_blockop.cpp | 62 +- writeengine/shared/we_blockop.h | 14 +- writeengine/shared/we_brm.cpp | 573 +- writeengine/shared/we_brm.h | 262 +- writeengine/shared/we_bulkrollbackfile.cpp | 105 +- writeengine/shared/we_bulkrollbackfile.h | 50 +- .../shared/we_bulkrollbackfilecompressed.cpp | 120 +- .../shared/we_bulkrollbackfilecompressed.h | 43 +- .../we_bulkrollbackfilecompressedhdfs.cpp | 284 - .../we_bulkrollbackfilecompressedhdfs.h | 139 - writeengine/shared/we_bulkrollbackmgr.cpp | 663 +- writeengine/shared/we_bulkrollbackmgr.h | 53 +- writeengine/shared/we_cache.cpp | 4 +- writeengine/shared/we_cache.h | 16 +- writeengine/shared/we_chunkmanager.cpp | 1186 +- writeengine/shared/we_chunkmanager.h | 107 +- writeengine/shared/we_config.cpp | 101 +- writeengine/shared/we_config.h | 16 +- writeengine/shared/we_confirmhdfsdbfile.cpp | 823 - writeengine/shared/we_confirmhdfsdbfile.h | 139 - writeengine/shared/we_convertor.cpp | 267 +- writeengine/shared/we_convertor.h | 21 +- writeengine/shared/we_dbfileop.cpp | 70 +- writeengine/shared/we_dbfileop.h | 61 +- writeengine/shared/we_dbrootextenttracker.cpp | 255 +- writeengine/shared/we_dbrootextenttracker.h | 76 +- writeengine/shared/we_define.cpp | 14 +- writeengine/shared/we_define.h | 13 +- writeengine/shared/we_fileop.cpp | 781 +- writeengine/shared/we_fileop.h | 173 +- writeengine/shared/we_index.h | 162 +- writeengine/shared/we_log.cpp | 4 +- writeengine/shared/we_log.h | 4 +- writeengine/shared/we_rbmetawriter.cpp | 475 +- writeengine/shared/we_rbmetawriter.h | 56 +- writeengine/shared/we_simplesyslog.cpp | 6 +- writeengine/shared/we_simplesyslog.h | 4 +- writeengine/shared/we_stats.cpp | 2 +- writeengine/shared/we_stats.h | 2 +- writeengine/shared/we_type.h | 125 +- writeengine/shared/we_typeext.h | 30 +- writeengine/splitter/Makefile.am | 26 +- writeengine/splitter/Makefile.in | 40 +- writeengine/splitter/resource.h | 14 - writeengine/splitter/splitter.rc | 101 - writeengine/splitter/splitter.vcxproj | 341 - writeengine/splitter/splitter.vcxproj.filters | 80 - writeengine/splitter/we_brmupdater.cpp | 69 +- writeengine/splitter/we_brmupdater.h | 55 +- writeengine/splitter/we_cmdargs.cpp | 322 +- writeengine/splitter/we_cmdargs.h | 70 +- writeengine/splitter/we_filereadthread.cpp | 125 +- writeengine/splitter/we_filereadthread.h | 48 +- writeengine/splitter/we_respreadthread.cpp | 141 +- writeengine/splitter/we_respreadthread.h | 47 +- writeengine/splitter/we_sdhandler.cpp | 630 +- writeengine/splitter/we_sdhandler.h | 646 +- writeengine/splitter/we_splclient.cpp | 951 +- writeengine/splitter/we_splclient.h | 63 +- writeengine/splitter/we_splitterapp.cpp | 112 +- writeengine/splitter/we_splitterapp.h | 47 +- writeengine/splitter/we_tablelockgrabber.cpp | 57 +- writeengine/splitter/we_tablelockgrabber.h | 47 +- writeengine/splitter/we_xmlgetter.cpp | 184 +- writeengine/splitter/we_xmlgetter.h | 56 +- writeengine/wrapper/Makefile.am | 28 +- writeengine/wrapper/Makefile.in | 60 +- writeengine/wrapper/tdriver.cpp | 58 +- writeengine/wrapper/we_colop.cpp | 715 +- writeengine/wrapper/we_colop.h | 52 +- writeengine/wrapper/we_colopcompress.cpp | 56 +- writeengine/wrapper/we_colopcompress.h | 36 +- writeengine/wrapper/we_dctnrycompress.cpp | 27 +- writeengine/wrapper/we_dctnrycompress.h | 20 +- writeengine/wrapper/we_tablemetadata.cpp | 218 +- writeengine/wrapper/we_tablemetadata.h | 190 +- writeengine/wrapper/writeengine.cpp | 2526 +-- writeengine/wrapper/writeengine.h | 171 +- writeengine/xml/Makefile.am | 26 +- writeengine/xml/Makefile.in | 40 +- writeengine/xml/we_xmlgendata.cpp | 4 +- writeengine/xml/we_xmlgendata.h | 12 +- writeengine/xml/we_xmlgenproc.cpp | 16 +- writeengine/xml/we_xmlgenproc.h | 2 +- writeengine/xml/we_xmljob.cpp | 141 +- writeengine/xml/we_xmljob.h | 5 +- writeengine/xml/we_xmlop.cpp | 2 +- writeengine/xml/we_xmlop.h | 2 +- writeengine/xml/we_xmltag.h | 2 +- 4900 files changed, 329101 insertions(+), 617461 deletions(-) delete mode 100755 build/Build.bat delete mode 100644 build/BuildCalpontVersion.bat delete mode 100644 build/CMakeLists.txt delete mode 100644 build/CalpontVersion.txt.in delete mode 100644 build/CopyLog.sh delete mode 100644 build/CopyToCalweb.bat delete mode 100644 build/InfiniDB.sln delete mode 100644 build/Nightly.bat delete mode 100644 build/README.md delete mode 100644 build/Switch.bat create mode 100755 build/bb_fix_rules.sh delete mode 100755 build/bb_pre_build.sh delete mode 100644 build/build-boost-win.bat delete mode 100755 build/build-branch.mysql delete mode 100755 build/build-genii.mysql create mode 100644 build/calpont.spec.in delete mode 100644 build/infinidb.spec.in mode change 100755 => 100644 build/make_src_tar delete mode 100755 build/nightlyDiff.sh delete mode 100755 build/src-build create mode 100755 build_mysql.sh delete mode 100644 dbcon/ddlpackage/libddlpackage.vcxproj delete mode 100644 dbcon/ddlpackage/libddlpackage.vcxproj.filters delete mode 100644 dbcon/ddlpackageproc/libddlpackageproc.rc delete mode 100644 dbcon/ddlpackageproc/libddlpackageproc.vcxproj delete mode 100644 dbcon/ddlpackageproc/libddlpackageproc.vcxproj.filters delete mode 100644 dbcon/ddlpackageproc/resource.h delete mode 100644 dbcon/dmlpackage/libdmlpackage.vcxproj delete mode 100644 dbcon/dmlpackage/libdmlpackage.vcxproj.filters delete mode 100644 dbcon/dmlpackageproc/libdmlpackageproc.rc delete mode 100644 dbcon/dmlpackageproc/libdmlpackageproc.vcxproj delete mode 100644 dbcon/dmlpackageproc/libdmlpackageproc.vcxproj.filters delete mode 100644 dbcon/dmlpackageproc/resource.h delete mode 100644 dbcon/doc/readme create mode 100644 dbcon/execplan/expressiontree.h delete mode 100644 dbcon/execplan/intervalcolumn.cpp delete mode 100644 dbcon/execplan/intervalcolumn.h delete mode 100644 dbcon/execplan/libexecplan.vcxproj delete mode 100644 dbcon/execplan/libexecplan.vcxproj.filters delete mode 100644 dbcon/execplan/pseudocolumn.cpp delete mode 100644 dbcon/execplan/pseudocolumn.h delete mode 100644 dbcon/execplan/simplecolumn_uint.h delete mode 100644 dbcon/execplan/windowfunctioncolumn.cpp delete mode 100644 dbcon/execplan/windowfunctioncolumn.h create mode 100644 dbcon/joblist/aggregatefilterstep.cpp create mode 100644 dbcon/joblist/aggregator.cpp create mode 100644 dbcon/joblist/aggregator.h create mode 100644 dbcon/joblist/batchprimitivestep.cpp create mode 100644 dbcon/joblist/bdlwrapper.h create mode 100644 dbcon/joblist/bucketreuse.cpp create mode 100644 dbcon/joblist/bucketreuse.h create mode 100644 dbcon/joblist/bucketreusestep.cpp create mode 100644 dbcon/joblist/constantdatalist.h create mode 100644 dbcon/joblist/deliverystep.cpp create mode 100644 dbcon/joblist/deliverywsdl.cpp create mode 100644 dbcon/joblist/deliverywsdl.h delete mode 100644 dbcon/joblist/diskjoinstep.cpp delete mode 100644 dbcon/joblist/diskjoinstep.h delete mode 100644 dbcon/joblist/errorinfo.h create mode 100644 dbcon/joblist/fifo-bench.cpp create mode 100644 dbcon/joblist/filteroperation.cpp create mode 100644 dbcon/joblist/filteroperation.h create mode 100644 dbcon/joblist/hashjoin.cpp create mode 100644 dbcon/joblist/hashjoin.h delete mode 100644 dbcon/joblist/libjoblist.rc delete mode 100644 dbcon/joblist/libjoblist.vcxproj delete mode 100644 dbcon/joblist/libjoblist.vcxproj.filters create mode 100644 dbcon/joblist/pidxlist.cpp create mode 100644 dbcon/joblist/pidxlist.h create mode 100644 dbcon/joblist/pidxwalk.cpp create mode 100644 dbcon/joblist/pidxwalk.h create mode 100644 dbcon/joblist/pnljoin.cpp create mode 100644 dbcon/joblist/profiling.cpp create mode 100644 dbcon/joblist/profiling.h delete mode 100644 dbcon/joblist/pseudocc-jl.cpp delete mode 100644 dbcon/joblist/pseudocc-jl.h create mode 100644 dbcon/joblist/reducestep.cpp delete mode 100644 dbcon/joblist/resource.h create mode 100644 dbcon/joblist/stopwatch.cpp create mode 100644 dbcon/joblist/swsdl.h create mode 100644 dbcon/joblist/tableband.cpp create mode 100644 dbcon/joblist/tableband.h create mode 100644 dbcon/joblist/tdriver-tableband.cpp create mode 100644 dbcon/joblist/tuplewsdl.cpp create mode 100644 dbcon/joblist/tuplewsdl.h create mode 100644 dbcon/joblist/unionstep.cpp delete mode 100644 dbcon/joblist/windowfunctionstep.cpp delete mode 100644 dbcon/joblist/windowfunctionstep.h create mode 100644 dbcon/joblist/wsdl.h create mode 100644 dbcon/joblist/zdl.h delete mode 100644 dbcon/mysql/CMakeLists.txt delete mode 100644 dbcon/mysql/Makefile.am.mysql create mode 100644 dbcon/mysql/configure.in create mode 100644 dbcon/mysql/field.h delete mode 100644 dbcon/mysql/ha_pseudocolumn.cpp delete mode 100644 dbcon/mysql/ha_window_function.cpp create mode 100644 dbcon/mysql/handler.cc create mode 100644 dbcon/mysql/include/my_base.h create mode 100644 dbcon/mysql/include/my_sys.h create mode 100644 dbcon/mysql/include/mysql_com.h create mode 100644 dbcon/mysql/item.cc create mode 100644 dbcon/mysql/item.h create mode 100644 dbcon/mysql/item_cmpfunc.cc create mode 100644 dbcon/mysql/item_cmpfunc.h create mode 100644 dbcon/mysql/item_func.cc create mode 100644 dbcon/mysql/item_func.h create mode 100644 dbcon/mysql/item_strfunc.cc create mode 100644 dbcon/mysql/item_strfunc.h create mode 100644 dbcon/mysql/item_sum.cc create mode 100644 dbcon/mysql/item_sum.h create mode 100644 dbcon/mysql/item_timefunc.cc create mode 100644 dbcon/mysql/item_timefunc.h create mode 100644 dbcon/mysql/lex.h delete mode 100644 dbcon/mysql/libcalmysql.rc delete mode 100644 dbcon/mysql/libcalmysql.vcxproj delete mode 100644 dbcon/mysql/libcalmysql.vcxproj.filters create mode 100644 dbcon/mysql/log.cc create mode 100644 dbcon/mysql/log.h create mode 100644 dbcon/mysql/mysql_priv.h create mode 100644 dbcon/mysql/mysqld.cc create mode 100644 dbcon/mysql/mysys/my_handler_errors.h delete mode 100644 dbcon/mysql/resource.h create mode 100644 dbcon/mysql/set_var.cc delete mode 100644 dbcon/mysql/sm.cpp delete mode 100644 dbcon/mysql/sm.h create mode 100644 dbcon/mysql/sp_head.h create mode 100644 dbcon/mysql/sql_base.cc create mode 100644 dbcon/mysql/sql_class.cc create mode 100644 dbcon/mysql/sql_class.h create mode 100644 dbcon/mysql/sql_delete.cc create mode 100644 dbcon/mysql/sql_insert.cc create mode 100644 dbcon/mysql/sql_parse.cc create mode 100644 dbcon/mysql/sql_prepare.cc create mode 100644 dbcon/mysql/sql_select.cc create mode 100644 dbcon/mysql/sql_table.cc create mode 100644 dbcon/mysql/sql_update.cc create mode 100644 dbcon/mysql/sql_yacc.yy create mode 100644 dbcon/mysql/table.h create mode 100644 dbcon/sm/Makefile.am create mode 100644 dbcon/sm/Makefile.in create mode 100644 dbcon/sm/sm.cpp create mode 100644 dbcon/sm/sm.h create mode 100644 dbcon/sm/tdriver.cpp delete mode 100644 ddlproc/DDLProc.rc delete mode 100644 ddlproc/DDLProc.vcxproj delete mode 100644 ddlproc/DDLProc.vcxproj.filters delete mode 100644 ddlproc/resource.h delete mode 100644 decomsvr/DecomSvr.rc delete mode 100644 decomsvr/DecomSvr.vcxproj delete mode 100644 decomsvr/DecomSvr.vcxproj.filters delete mode 100644 decomsvr/resource.h create mode 100644 dmlib/Makefile.am create mode 100644 dmlib/dm.c create mode 100644 dmlib/dm.h create mode 100644 dmlib/tdriver.c delete mode 100644 dmlproc/DMLProc.rc delete mode 100644 dmlproc/DMLProc.vcxproj delete mode 100644 dmlproc/DMLProc.vcxproj.filters delete mode 100644 dmlproc/resource.h delete mode 100644 exemgr/ExeMgr.rc delete mode 100644 exemgr/ExeMgr.vcxproj delete mode 100644 exemgr/ExeMgr.vcxproj.filters create mode 100644 exemgr/procstat.cpp create mode 100644 exemgr/procstat.h delete mode 100644 exemgr/resource.h delete mode 100644 m4/compilerflags.m4 create mode 100755 make_rpms delete mode 100644 net-snmp/Makefile.in delete mode 100644 net-snmp/net-snmp-5.2.1.2/agent/mibgroup/tcp-mib/data_access/Makefile delete mode 100644 net-snmp/net-snmp-5.2.1.2/dist/Makefile delete mode 100644 oam/cloud/Makefile.am delete mode 100644 oam/cloud/Makefile.in mode change 100755 => 100644 oam/etc/Calpont.xml create mode 100644 oam/install_scripts/dbhealth.sh create mode 100644 oam/install_scripts/dbhealth.sql create mode 100755 oam/install_scripts/displayJobGraph.sh delete mode 100644 oam/install_scripts/master-rep-infinidb.sh delete mode 100644 oam/install_scripts/myCnf-exclude-args.text delete mode 100644 oam/install_scripts/myCnf-include-args.text mode change 100755 => 100644 oam/install_scripts/post-install delete mode 100755 oam/install_scripts/remote_command_verify.sh mode change 100755 => 100644 oam/install_scripts/rsync.sh delete mode 100644 oam/install_scripts/slave-rep-infinidb.sh delete mode 100644 oam/oamcpp/COPYING delete mode 100644 oam/oamcpp/liboamcpp.rc delete mode 100644 oam/oamcpp/liboamcpp.vcxproj delete mode 100644 oam/oamcpp/liboamcpp.vcxproj.filters delete mode 100644 oam/oamcpp/resource.h create mode 100644 oam/replaytxnlog/Makefile.in create mode 100644 oamapps/calpont-console/Makefile.am rename oamapps/{calpontConsole => calpont-console}/calpontConsole.cpp (81%) rename oamapps/{calpontConsole => calpont-console}/calpontConsole.h (79%) create mode 100644 oamapps/calpont-console/tdriver.cpp delete mode 100644 oamapps/calpontConsole/Makefile.am delete mode 100644 oamapps/calpontConsole/Makefile.in delete mode 100644 oamapps/calpontConsole/tdriver.cpp delete mode 100644 oamapps/calpontDB/Makefile.in delete mode 100644 oamapps/calpontSupport/Makefile.am delete mode 100644 oamapps/calpontSupport/Makefile.in delete mode 100755 oamapps/calpontSupport/alarmReport.sh delete mode 100644 oamapps/calpontSupport/analytics/create.sql delete mode 100755 oamapps/calpontSupport/analytics/track.sh delete mode 100755 oamapps/calpontSupport/approximateRowCount.sh delete mode 100755 oamapps/calpontSupport/bulklogReport.sh delete mode 100644 oamapps/calpontSupport/calpontSupport.bat delete mode 100644 oamapps/calpontSupport/calpontSupport.cpp delete mode 100755 oamapps/calpontSupport/configReport.sh delete mode 100755 oamapps/calpontSupport/findStranded.sh delete mode 100755 oamapps/calpontSupport/getMinMax.sh delete mode 100755 oamapps/calpontSupport/hadoopReport.sh delete mode 100755 oamapps/calpontSupport/hardwareReport.sh delete mode 100755 oamapps/calpontSupport/logReport.sh delete mode 100755 oamapps/calpontSupport/minMaxCheck.sh delete mode 100755 oamapps/calpontSupport/resourceReport.sh delete mode 100755 oamapps/calpontSupport/softwareReport.sh delete mode 100755 oamapps/calpontSupport/sqlLogs.sh create mode 100644 oamapps/logUtils/Makefile.am create mode 100755 oamapps/logUtils/dbprof.pl delete mode 100644 oamapps/postConfigure/Makefile.in delete mode 100644 oamapps/postConfigure/amazonConfig-1pm.xml delete mode 100644 oamapps/postConfigure/mycnfUpgrade.cpp create mode 100644 oamapps/replayTransactionLog/Makefile.in delete mode 100644 oamapps/sendtrap/Makefile.am delete mode 100644 oamapps/sendtrap/Makefile.in delete mode 100644 oamapps/serverMonitor/Makefile.in delete mode 100644 oamapps/sessionWalker/Makefile.in delete mode 100644 oamapps/traphandler/Makefile.in delete mode 100644 primitives/primproc/PrimProc.rc delete mode 100644 primitives/primproc/PrimProc.vcxproj delete mode 100644 primitives/primproc/PrimProc.vcxproj.filters create mode 100644 primitives/primproc/monitorprocmem.cpp create mode 100644 primitives/primproc/monitorprocmem.h delete mode 100644 primitives/primproc/pseudocc.cpp delete mode 100644 primitives/primproc/pseudocc.h delete mode 100644 primitives/primproc/resource.h create mode 120000 primitives/primproc/rowaggregation.cpp create mode 120000 primitives/primproc/rowaggregation.h create mode 120000 primitives/primproc/rowgroup.cpp create mode 120000 primitives/primproc/rowgroup.h create mode 100644 primitives/udf/Makefile.sdk create mode 100644 primitives/udf/caludf.cpp create mode 100644 primitives/udf/caludf.h delete mode 100644 procmgr/Makefile.in delete mode 100644 procmon/Makefile.in delete mode 100644 tools/bincvt/li2bin.cpp delete mode 100644 tools/brmtest/Makefile.am delete mode 100644 tools/brmtest/brmtest.cpp delete mode 100644 tools/brmtest/locks.cpp delete mode 100644 tools/cfread/Makefile.am delete mode 100644 tools/cfread/cfread.cpp delete mode 100644 tools/cfread/mtread.cpp delete mode 100644 tools/clearShm/clearShm.vcxproj delete mode 100644 tools/clearShm/clearShm.vcxproj.filters delete mode 100644 tools/cleartablelock/cleartablelock.vcxproj delete mode 100644 tools/cleartablelock/cleartablelock.vcxproj.filters delete mode 100644 tools/configMgt/CalpontSystems.xml delete mode 100644 tools/configMgt/Makefile.am delete mode 100644 tools/configMgt/Makefile.in delete mode 100644 tools/configMgt/README delete mode 100755 tools/configMgt/autoBuilder delete mode 100644 tools/configMgt/autoConfigure.cpp delete mode 100644 tools/configMgt/autoInstaller.cpp delete mode 100644 tools/configMgt/autoPackager delete mode 100755 tools/configMgt/autoReleaseNotes.sh delete mode 100644 tools/configMgt/autoReleaseNotes_branch.sh delete mode 100755 tools/configMgt/beetlejuice_installer.sh delete mode 100755 tools/configMgt/beetlejuice_installer_3rpms.sh delete mode 100755 tools/configMgt/buildCalpontPackages.sh delete mode 100755 tools/configMgt/buildDatdupPackages.sh delete mode 100755 tools/configMgt/buildTester.sh delete mode 100755 tools/configMgt/calpont-build delete mode 100644 tools/configMgt/configure.cpp delete mode 100755 tools/configMgt/datdup-build delete mode 100755 tools/configMgt/dm_parent_installer.sh delete mode 100755 tools/configMgt/dm_parent_installer_v3.sh delete mode 100755 tools/configMgt/mysql-build-branch delete mode 100755 tools/configMgt/mysql-build-genii delete mode 100755 tools/configMgt/parent_binary_installer.sh delete mode 100755 tools/configMgt/parent_binary_installer_v3.sh delete mode 100755 tools/configMgt/parent_installer.sh delete mode 100755 tools/configMgt/pm_parent_installer.sh delete mode 100755 tools/configMgt/pm_parent_installer_v3.sh delete mode 100755 tools/configMgt/recreateBranch.sh delete mode 100755 tools/configMgt/remote_command.sh delete mode 100755 tools/configMgt/remote_command_test.sh delete mode 100755 tools/configMgt/remote_scp_get.sh delete mode 100755 tools/configMgt/rpm_txt.sh delete mode 100644 tools/configMgt/stackReleaseChecker.cpp delete mode 100644 tools/configMgt/svnQuery.cpp delete mode 100644 tools/cplogger/cplogger.vcxproj delete mode 100644 tools/cplogger/cplogger.vcxproj.filters delete mode 100644 tools/dbbuilder/dbbuilder.vcxproj delete mode 100644 tools/dbbuilder/dbbuilder.vcxproj.filters delete mode 100644 tools/dbloadxml/colxml.rc delete mode 100644 tools/dbloadxml/colxml.vcxproj delete mode 100644 tools/dbloadxml/colxml.vcxproj.filters delete mode 100644 tools/dbloadxml/resource.h delete mode 100644 tools/ddlcleanup/ddlcleanup.vcxproj delete mode 100644 tools/ddlcleanup/ddlcleanup.vcxproj.filters delete mode 100644 tools/ddldriver/Makefile.am delete mode 100644 tools/ddldriver/ddldriver.cpp delete mode 100644 tools/dmldriver/Makefile.am delete mode 100644 tools/dmldriver/dmldriver.cpp delete mode 100644 tools/dmldriver/dmlif.cpp delete mode 100644 tools/dmldriver/dmlif.h delete mode 100644 tools/dmldriver/tpchrf2.cpp delete mode 100644 tools/dmldriver/tpchrf2.h delete mode 100644 tools/editem/editem.vcxproj delete mode 100644 tools/editem/editem.vcxproj.filters delete mode 100644 tools/evalidx/Makefile.am delete mode 100755 tools/evalidx/checkidx.py delete mode 100644 tools/evalidx/evalidx.cpp delete mode 100644 tools/fixdate/fixdate.cpp delete mode 100644 tools/getConfig/getConfig.vcxproj delete mode 100644 tools/getConfig/getConfig.vcxproj.filters delete mode 100644 tools/hdfsCheck/hdfsCheck.cpp delete mode 100644 tools/idb_comp/main.cpp delete mode 100644 tools/notificationTester/client.cpp delete mode 100644 tools/notificationTester/main.cpp delete mode 100644 tools/pingproc/pingproc.cpp delete mode 100644 tools/qfe/Makefile.am delete mode 100644 tools/qfe/bison-win.cpp delete mode 100644 tools/qfe/bison-win.h delete mode 100644 tools/qfe/cli.cpp delete mode 100644 tools/qfe/cseputils.cpp delete mode 100644 tools/qfe/cseputils.h delete mode 100644 tools/qfe/ddlstmts.cpp delete mode 100644 tools/qfe/ddlstmts.h delete mode 100644 tools/qfe/lex-win.cpp delete mode 100644 tools/qfe/parsequery.cpp delete mode 100644 tools/qfe/parsequery.h delete mode 100755 tools/qfe/qfe-cli.py delete mode 100644 tools/qfe/qfelexer.lpp delete mode 100644 tools/qfe/qfeparser.ypp delete mode 100644 tools/qfe/returnedrows.cpp delete mode 100644 tools/qfe/returnedrows.h delete mode 100644 tools/qfe/scanner.bat delete mode 100644 tools/qfe/sendcsep.cpp delete mode 100644 tools/qfe/sendcsep.h delete mode 100644 tools/qfe/server.cpp delete mode 100644 tools/qfe/socketio.cpp delete mode 100644 tools/qfe/socketio.h delete mode 100644 tools/qfe/socktype.h delete mode 100644 tools/rebuildEM/main.cpp delete mode 100644 tools/reserveStacks/create.sql delete mode 100644 tools/reserveStacks/index.html delete mode 100644 tools/reserveStacks/procs.sql delete mode 100644 tools/reserveStacks/results.php delete mode 100755 tools/reserveStacks/stack delete mode 100644 tools/reserveStacks/stack.php delete mode 100644 tools/reserveStacks/stackReservationResult.php delete mode 100644 tools/sendPlan/Makefile.am delete mode 100644 tools/sendPlan/sendplan.cpp delete mode 100644 tools/setConfig/setConfig.vcxproj delete mode 100644 tools/setConfig/setConfig.vcxproj.filters delete mode 100755 tools/snconvert/snconvert.pl delete mode 100755 tools/updateGenii/listRepos.pl delete mode 100644 tools/updateGenii/test.dat delete mode 100755 tools/updateGenii/updateGenii.pl delete mode 100644 tools/valprint/valprint.cpp delete mode 100644 tools/vbgen/Makefile.am delete mode 100644 tools/vbgen/myrand.cpp delete mode 100644 tools/vbgen/myrand.h delete mode 100644 tools/vbgen/vbgen.cpp delete mode 100644 tools/viewtablelock/viewtablelock.vcxproj delete mode 100644 tools/viewtablelock/viewtablelock.vcxproj.filters create mode 100755 utils/autoconf/build_mysql.sh delete mode 100644 utils/autoconf/m4/compilerflags.m4 create mode 100755 utils/autoconf/make_rpms delete mode 100644 utils/batchloader/libbatchloader.vcxproj delete mode 100644 utils/batchloader/libbatchloader.vcxproj.filters delete mode 100644 utils/boost_idb/boost/algorithm/clamp.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/all_of.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/any_of.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/copy_if.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/copy_n.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/find_if_not.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/iota.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/is_partitioned.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/is_permutation.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/is_sorted.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/none_of.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/one_of.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/partition_copy.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx11/partition_point.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx14/equal.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx14/is_permutation.hpp delete mode 100644 utils/boost_idb/boost/algorithm/cxx14/mismatch.hpp delete mode 100644 utils/boost_idb/boost/algorithm/gather.hpp delete mode 100644 utils/boost_idb/boost/algorithm/hex.hpp delete mode 100644 utils/boost_idb/boost/algorithm/searching/boyer_moore.hpp delete mode 100644 utils/boost_idb/boost/algorithm/searching/boyer_moore_horspool.hpp delete mode 100644 utils/boost_idb/boost/algorithm/searching/detail/bm_traits.hpp delete mode 100644 utils/boost_idb/boost/algorithm/searching/detail/debugging.hpp delete mode 100644 utils/boost_idb/boost/algorithm/searching/knuth_morris_pratt.hpp delete mode 100644 utils/boost_idb/boost/algorithm/string/trim_all.hpp create mode 100644 utils/boost_idb/boost/aligned_storage.hpp create mode 100644 utils/boost_idb/boost/asio.hpp delete mode 100644 utils/boost_idb/boost/atomic.hpp delete mode 100644 utils/boost_idb/boost/atomic/atomic.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/base.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/cas128strong.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/cas32strong.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/cas32weak.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/cas64strong-ptr.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/cas64strong.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/config.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-alpha.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-armv6plus.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-atomic.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-cas.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-ppc.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-sparcv9.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/gcc-x86.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/generic-cas.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/interlocked.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/link.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/linux-arm.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/lockpool.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/platform.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/type-classification.hpp delete mode 100644 utils/boost_idb/boost/atomic/detail/windows.hpp create mode 100644 utils/boost_idb/boost/bimap.hpp create mode 100644 utils/boost_idb/boost/blank.hpp create mode 100644 utils/boost_idb/boost/blank_fwd.hpp create mode 100644 utils/boost_idb/boost/cast.hpp delete mode 100644 utils/boost_idb/boost/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/ceil.hpp delete mode 100644 utils/boost_idb/boost/chrono/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/chrono_io.hpp delete mode 100644 utils/boost_idb/boost/chrono/clock_string.hpp delete mode 100644 utils/boost_idb/boost/chrono/config.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/mac/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/mac/process_cpu_clocks.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/mac/thread_clock.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/posix/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/posix/process_cpu_clocks.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/posix/thread_clock.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/process_cpu_clocks.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/thread_clock.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/win/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/win/process_cpu_clocks.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/inlined/win/thread_clock.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/is_evenly_divisible_by.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/no_warning/signed_unsigned_cmp.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/scan_keyword.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/static_assert.hpp delete mode 100644 utils/boost_idb/boost/chrono/detail/system.hpp delete mode 100644 utils/boost_idb/boost/chrono/duration.hpp delete mode 100644 utils/boost_idb/boost/chrono/floor.hpp delete mode 100644 utils/boost_idb/boost/chrono/include.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/duration_get.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/duration_io.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/duration_put.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/duration_style.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/duration_units.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/ios_base_state.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/time_point_get.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/time_point_io.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/time_point_put.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/time_point_units.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/timezone.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/utility/ios_base_state_ptr.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/utility/manip_base.hpp delete mode 100644 utils/boost_idb/boost/chrono/io/utility/to_string.hpp delete mode 100644 utils/boost_idb/boost/chrono/io_v1/chrono_io.hpp delete mode 100644 utils/boost_idb/boost/chrono/process_cpu_clocks.hpp delete mode 100644 utils/boost_idb/boost/chrono/round.hpp delete mode 100644 utils/boost_idb/boost/chrono/system_clocks.hpp delete mode 100644 utils/boost_idb/boost/chrono/thread_clock.hpp delete mode 100644 utils/boost_idb/boost/chrono/time_point.hpp delete mode 100644 utils/boost_idb/boost/chrono/typeof/boost/chrono/chrono.hpp delete mode 100644 utils/boost_idb/boost/chrono/typeof/boost/ratio.hpp create mode 100644 utils/boost_idb/boost/circular_buffer.hpp create mode 100644 utils/boost_idb/boost/circular_buffer_fwd.hpp delete mode 100644 utils/boost_idb/boost/concept_check/borland.hpp delete mode 100644 utils/boost_idb/boost/concept_check/general.hpp delete mode 100644 utils/boost_idb/boost/concept_check/has_constraints.hpp delete mode 100644 utils/boost_idb/boost/concept_check/msvc.hpp delete mode 100644 utils/boost_idb/boost/config/compiler/cray.hpp delete mode 100644 utils/boost_idb/boost/config/compiler/pathscale.hpp delete mode 100644 utils/boost_idb/boost/config/platform/cray.hpp delete mode 100644 utils/boost_idb/boost/config/stdlib/libcpp.hpp delete mode 100644 utils/boost_idb/boost/container/allocator_traits.hpp delete mode 100644 utils/boost_idb/boost/container/container_fwd.hpp delete mode 100644 utils/boost_idb/boost/container/deque.hpp delete mode 100644 utils/boost_idb/boost/container/detail/adaptive_node_pool_impl.hpp delete mode 100644 utils/boost_idb/boost/container/detail/advanced_insert_int.hpp delete mode 100644 utils/boost_idb/boost/container/detail/algorithms.hpp delete mode 100644 utils/boost_idb/boost/container/detail/allocator_version_traits.hpp delete mode 100644 utils/boost_idb/boost/container/detail/config_begin.hpp delete mode 100644 utils/boost_idb/boost/container/detail/config_end.hpp delete mode 100644 utils/boost_idb/boost/container/detail/destroyers.hpp delete mode 100644 utils/boost_idb/boost/container/detail/flat_tree.hpp delete mode 100644 utils/boost_idb/boost/container/detail/function_detector.hpp delete mode 100644 utils/boost_idb/boost/container/detail/iterators.hpp delete mode 100644 utils/boost_idb/boost/container/detail/memory_util.hpp delete mode 100644 utils/boost_idb/boost/container/detail/mpl.hpp delete mode 100644 utils/boost_idb/boost/container/detail/multiallocation_chain.hpp delete mode 100644 utils/boost_idb/boost/container/detail/node_alloc_holder.hpp delete mode 100644 utils/boost_idb/boost/container/detail/pair.hpp delete mode 100644 utils/boost_idb/boost/container/detail/preprocessor.hpp delete mode 100644 utils/boost_idb/boost/container/detail/transform_iterator.hpp delete mode 100644 utils/boost_idb/boost/container/detail/tree.hpp delete mode 100644 utils/boost_idb/boost/container/detail/type_traits.hpp delete mode 100644 utils/boost_idb/boost/container/detail/utilities.hpp delete mode 100644 utils/boost_idb/boost/container/detail/value_init.hpp delete mode 100644 utils/boost_idb/boost/container/detail/version_type.hpp delete mode 100644 utils/boost_idb/boost/container/detail/workaround.hpp delete mode 100644 utils/boost_idb/boost/container/flat_map.hpp delete mode 100644 utils/boost_idb/boost/container/flat_set.hpp delete mode 100644 utils/boost_idb/boost/container/list.hpp delete mode 100644 utils/boost_idb/boost/container/map.hpp delete mode 100644 utils/boost_idb/boost/container/scoped_allocator.hpp delete mode 100644 utils/boost_idb/boost/container/scoped_allocator_fwd.hpp delete mode 100644 utils/boost_idb/boost/container/set.hpp delete mode 100644 utils/boost_idb/boost/container/slist.hpp delete mode 100644 utils/boost_idb/boost/container/stable_vector.hpp delete mode 100644 utils/boost_idb/boost/container/static_vector.hpp delete mode 100644 utils/boost_idb/boost/container/string.hpp delete mode 100644 utils/boost_idb/boost/container/throw_exception.hpp delete mode 100644 utils/boost_idb/boost/container/vector.hpp create mode 100644 utils/boost_idb/boost/crc.hpp create mode 100644 utils/boost_idb/boost/cstdlib.hpp delete mode 100644 utils/boost_idb/boost/detail/atomic_redef_macros.hpp delete mode 100644 utils/boost_idb/boost/detail/atomic_undef_macros.hpp delete mode 100644 utils/boost_idb/boost/detail/bitmask.hpp delete mode 100644 utils/boost_idb/boost/detail/fenv.hpp delete mode 100644 utils/boost_idb/boost/detail/is_sorted.hpp delete mode 100644 utils/boost_idb/boost/detail/lightweight_main.hpp delete mode 100644 utils/boost_idb/boost/detail/utf8_codecvt_facet.ipp delete mode 100644 utils/boost_idb/boost/detail/winapi/GetCurrentProcess.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/GetCurrentThread.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/GetLastError.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/GetProcessTimes.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/GetThreadTimes.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/LocalFree.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/basic_types.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/directory_management.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/dll.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/error_handling.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/file_management.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/handles.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/memory.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/process.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/security.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/synchronization.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/system.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/thread.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/time.hpp delete mode 100644 utils/boost_idb/boost/detail/winapi/timers.hpp create mode 100644 utils/boost_idb/boost/dynamic_bitset.hpp create mode 100644 utils/boost_idb/boost/dynamic_bitset_fwd.hpp delete mode 100644 utils/boost_idb/boost/exception/detail/clone_current_exception.hpp delete mode 100644 utils/boost_idb/boost/filesystem/path_traits.hpp create mode 100644 utils/boost_idb/boost/filesystem/v2/config.hpp create mode 100644 utils/boost_idb/boost/filesystem/v2/convenience.hpp create mode 100644 utils/boost_idb/boost/filesystem/v2/exception.hpp create mode 100644 utils/boost_idb/boost/filesystem/v2/fstream.hpp create mode 100644 utils/boost_idb/boost/filesystem/v2/operations.hpp create mode 100644 utils/boost_idb/boost/filesystem/v2/path.hpp create mode 100644 utils/boost_idb/boost/flyweight.hpp create mode 100644 utils/boost_idb/boost/foreach.hpp create mode 100644 utils/boost_idb/boost/foreach_fwd.hpp delete mode 100644 utils/boost_idb/boost/function_types/components.hpp delete mode 100644 utils/boost_idb/boost/function_types/config/cc_names.hpp delete mode 100644 utils/boost_idb/boost/function_types/config/compiler.hpp delete mode 100644 utils/boost_idb/boost/function_types/config/config.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/class_transform.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/classifier_impl/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_as_mpl_sequence.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity10_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity10_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity20_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity20_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity30_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity30_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity40_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity40_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity50_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/arity50_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/components_impl/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/cv_traits.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/encoding/aliases_def.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/encoding/aliases_undef.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/encoding/def.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/encoding/undef.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_arity_loop.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_cc_loop/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_cc_loop/preprocessed.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_loop.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/preprocessed.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_tags/cc_tag.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_tags/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_tags/preprocessed.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_variate_loop/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/pp_variate_loop/preprocessed.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/retag_default_cc.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_0.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_1.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/synthesize_impl/master.hpp delete mode 100644 utils/boost_idb/boost/function_types/detail/to_sequence.hpp delete mode 100644 utils/boost_idb/boost/function_types/function_arity.hpp delete mode 100644 utils/boost_idb/boost/function_types/function_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/function_reference.hpp delete mode 100644 utils/boost_idb/boost/function_types/function_type.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_callable_builtin.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_function.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_function_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_function_reference.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_member_function_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_member_object_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_member_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/is_nonmember_callable_builtin.hpp delete mode 100644 utils/boost_idb/boost/function_types/member_function_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/member_object_pointer.hpp delete mode 100644 utils/boost_idb/boost/function_types/parameter_types.hpp delete mode 100644 utils/boost_idb/boost/function_types/property_tags.hpp delete mode 100644 utils/boost_idb/boost/function_types/result_type.hpp create mode 100644 utils/boost_idb/boost/functional/detail/container_fwd.hpp create mode 100644 utils/boost_idb/boost/functional/hash/detail/hash_float_generic.hpp create mode 100644 utils/boost_idb/boost/functional/hash/detail/hash_float_x86.hpp delete mode 100644 utils/boost_idb/boost/functional/overloaded_function.hpp delete mode 100644 utils/boost_idb/boost/functional/overloaded_function/config.hpp delete mode 100644 utils/boost_idb/boost/functional/overloaded_function/detail/base.hpp delete mode 100644 utils/boost_idb/boost/functional/overloaded_function/detail/function_type.hpp create mode 100644 utils/boost_idb/boost/generator_iterator.hpp create mode 100644 utils/boost_idb/boost/implicit_cast.hpp create mode 100644 utils/boost_idb/boost/indirect_reference.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/container_fwd.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/deque.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/adaptive_node_pool_impl.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/advanced_insert_int.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/algorithms.hpp rename utils/boost_idb/boost/{ => interprocess/containers}/container/detail/allocation_type.hpp (80%) create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/config_begin.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/config_end.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/destroyers.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/flat_tree.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/iterators.hpp rename utils/boost_idb/boost/{ => interprocess/containers}/container/detail/math_functions.hpp (90%) create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/mpl.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/multiallocation_chain.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/node_alloc_holder.hpp rename utils/boost_idb/boost/{ => interprocess/containers}/container/detail/node_pool_impl.hpp (78%) create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/pair.hpp rename utils/boost_idb/boost/{ => interprocess/containers}/container/detail/pool_common.hpp (79%) create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/preprocessor.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/stored_ref.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/transform_iterator.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/tree.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/type_traits.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/utilities.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/value_init.hpp rename utils/boost_idb/boost/{ => interprocess/containers}/container/detail/variadic_templates_tools.hpp (87%) create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/version_type.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/detail/workaround.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/flat_map.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/flat_set.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/list.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/map.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/set.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/slist.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/stable_vector.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/string.hpp create mode 100644 utils/boost_idb/boost/interprocess/containers/container/vector.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/config_external_begin.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/config_external_end.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/file_locking_helpers.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/intermodule_singleton_common.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/managed_global_memory.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/portable_intermodule_singleton.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/windows_intermodule_singleton.hpp create mode 100644 utils/boost_idb/boost/interprocess/detail/xsi_shared_memory.hpp delete mode 100644 utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_file_wrapper.hpp delete mode 100644 utils/boost_idb/boost/interprocess/managed_xsi_shared_memory.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/detail/condition_algorithm_8a.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/detail/condition_any_algorithm.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/detail/locks.hpp rename utils/boost_idb/boost/interprocess/sync/{spin => emulation}/interprocess_barrier.hpp (100%) create mode 100644 utils/boost_idb/boost/interprocess/sync/emulation/interprocess_condition.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/emulation/interprocess_semaphore.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/emulation/mutex.hpp rename utils/boost_idb/boost/interprocess/sync/{shm => emulation}/named_creation_functor.hpp (82%) create mode 100644 utils/boost_idb/boost/interprocess/sync/emulation/recursive_mutex.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/interprocess_barrier.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/interprocess_condition_any.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/interprocess_sharable_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/named_condition_any.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/named_sharable_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/posix/condition.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/posix/interprocess_barrier.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/posix/interprocess_condition.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/posix/interprocess_mutex.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp create mode 100644 utils/boost_idb/boost/interprocess/sync/posix/interprocess_semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/posix/mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/posix/named_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/posix/named_semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/posix/recursive_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/posix/semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/shm/named_condition.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/shm/named_condition_any.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/shm/named_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/shm/named_recursive_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/shm/named_semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/shm/named_upgradable_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/spin/condition.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/spin/mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/spin/recursive_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/spin/semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/spin/wait.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/condition.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/named_condition.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/named_condition_any.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/named_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/named_recursive_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/named_semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/named_sync.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/recursive_mutex.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/semaphore.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/sync_utils.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/winapi_mutex_wrapper.hpp delete mode 100644 utils/boost_idb/boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp delete mode 100644 utils/boost_idb/boost/interprocess/xsi_key.hpp delete mode 100644 utils/boost_idb/boost/interprocess/xsi_shared_memory.hpp delete mode 100644 utils/boost_idb/boost/intrusive/any_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/avl_set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/avl_set_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/avltree.hpp delete mode 100644 utils/boost_idb/boost/intrusive/avltree_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/bs_set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/bs_set_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/bstree.hpp delete mode 100644 utils/boost_idb/boost/intrusive/bstree_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/circular_list_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/circular_slist_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/derivation_value_traits.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/any_node_and_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/assert.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/avltree_node.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/clear_on_destructor_base.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/common_slist_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/config_begin.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/config_end.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/ebo_functor_holder.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/function_detector.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/generic_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/has_member_function_callable_with.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/hashtable_node.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/is_stateful_value_traits.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/list_node.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/memory_util.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/mpl.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/parent_from_member.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/preprocessor.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/rbtree_node.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/slist_node.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/transform_iterator.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/tree_node.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/utilities.hpp delete mode 100644 utils/boost_idb/boost/intrusive/detail/workaround.hpp delete mode 100644 utils/boost_idb/boost/intrusive/hashtable.hpp delete mode 100644 utils/boost_idb/boost/intrusive/intrusive_fwd.hpp delete mode 100644 utils/boost_idb/boost/intrusive/linear_slist_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/link_mode.hpp delete mode 100644 utils/boost_idb/boost/intrusive/list.hpp delete mode 100644 utils/boost_idb/boost/intrusive/list_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/member_value_traits.hpp delete mode 100644 utils/boost_idb/boost/intrusive/options.hpp delete mode 100644 utils/boost_idb/boost/intrusive/parent_from_member.hpp delete mode 100644 utils/boost_idb/boost/intrusive/pointer_plus_bits.hpp delete mode 100644 utils/boost_idb/boost/intrusive/pointer_traits.hpp delete mode 100644 utils/boost_idb/boost/intrusive/priority_compare.hpp delete mode 100644 utils/boost_idb/boost/intrusive/rbtree.hpp delete mode 100644 utils/boost_idb/boost/intrusive/rbtree_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/set_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/sg_set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/sgtree.hpp delete mode 100644 utils/boost_idb/boost/intrusive/sgtree_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/slist.hpp delete mode 100644 utils/boost_idb/boost/intrusive/slist_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/splay_set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/splay_set_hook.hpp delete mode 100644 utils/boost_idb/boost/intrusive/splaytree.hpp delete mode 100644 utils/boost_idb/boost/intrusive/splaytree_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/treap.hpp delete mode 100644 utils/boost_idb/boost/intrusive/treap_algorithms.hpp delete mode 100644 utils/boost_idb/boost/intrusive/treap_set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/trivial_value_traits.hpp delete mode 100644 utils/boost_idb/boost/intrusive/unordered_set.hpp delete mode 100644 utils/boost_idb/boost/intrusive/unordered_set_hook.hpp delete mode 100644 utils/boost_idb/boost/io/detail/quoted_manip.hpp delete mode 100644 utils/boost_idb/boost/iostreams/categories.hpp delete mode 100644 utils/boost_idb/boost/iostreams/chain.hpp delete mode 100644 utils/boost_idb/boost/iostreams/char_traits.hpp delete mode 100644 utils/boost_idb/boost/iostreams/checked_operations.hpp delete mode 100644 utils/boost_idb/boost/iostreams/close.hpp delete mode 100644 utils/boost_idb/boost/iostreams/code_converter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/combine.hpp delete mode 100644 utils/boost_idb/boost/iostreams/compose.hpp delete mode 100644 utils/boost_idb/boost/iostreams/concepts.hpp delete mode 100644 utils/boost_idb/boost/iostreams/constants.hpp delete mode 100644 utils/boost_idb/boost/iostreams/copy.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/absolute_path.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/access_control.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/concept_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/device_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/direct_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/filter_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/mode_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/non_blocking_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/output_iterator_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/adapter/range_adapter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/add_facet.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/bool_trait_def.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/broken_overload_resolution/forward.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/broken_overload_resolution/stream.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/broken_overload_resolution/stream_buffer.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/buffer.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/call_traits.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/char_traits.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/codecvt_helper.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/codecvt_holder.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/auto_link.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/bzip2.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/codecvt.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/disable_warnings.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/dyn_link.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/enable_warnings.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/fpos.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/gcc.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/limits.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/overload_resolution.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/rtl.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/unreachable_return.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/wide_streams.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/windows_posix.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/config/zlib.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/counted_array.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/current_directory.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/default_arg.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/dispatch.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/double_object.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/enable_if_stream.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/error.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/execute.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/file_handle.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/forward.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/fstream.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/functional.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/ios.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/iostream.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/is_dereferenceable.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/is_iterator_range.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/newline.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/optional.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/param_type.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/path.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/push.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/push_params.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/resolve.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/restrict_impl.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/select.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/select_by_size.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/streambuf.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/streambuf/chainbuf.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/streambuf/direct_streambuf.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/streambuf/indirect_streambuf.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/streambuf/linked_streambuf.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/system_failure.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/template_params.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/translate_int_type.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/vc6/close.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/vc6/read.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/vc6/write.hpp delete mode 100644 utils/boost_idb/boost/iostreams/detail/wrap_unwrap.hpp delete mode 100644 utils/boost_idb/boost/iostreams/device/array.hpp delete mode 100644 utils/boost_idb/boost/iostreams/device/back_inserter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/device/file.hpp delete mode 100644 utils/boost_idb/boost/iostreams/device/file_descriptor.hpp delete mode 100644 utils/boost_idb/boost/iostreams/device/mapped_file.hpp delete mode 100644 utils/boost_idb/boost/iostreams/device/null.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/aggregate.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/bzip2.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/counter.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/grep.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/gzip.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/line.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/newline.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/regex.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/stdio.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/symmetric.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/test.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filter/zlib.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filtering_stream.hpp delete mode 100644 utils/boost_idb/boost/iostreams/filtering_streambuf.hpp delete mode 100644 utils/boost_idb/boost/iostreams/flush.hpp delete mode 100644 utils/boost_idb/boost/iostreams/get.hpp delete mode 100644 utils/boost_idb/boost/iostreams/imbue.hpp delete mode 100644 utils/boost_idb/boost/iostreams/input_sequence.hpp delete mode 100644 utils/boost_idb/boost/iostreams/invert.hpp delete mode 100644 utils/boost_idb/boost/iostreams/operations.hpp delete mode 100644 utils/boost_idb/boost/iostreams/operations_fwd.hpp delete mode 100644 utils/boost_idb/boost/iostreams/optimal_buffer_size.hpp delete mode 100644 utils/boost_idb/boost/iostreams/output_sequence.hpp delete mode 100644 utils/boost_idb/boost/iostreams/pipeline.hpp delete mode 100644 utils/boost_idb/boost/iostreams/positioning.hpp delete mode 100644 utils/boost_idb/boost/iostreams/put.hpp delete mode 100644 utils/boost_idb/boost/iostreams/putback.hpp delete mode 100644 utils/boost_idb/boost/iostreams/read.hpp delete mode 100644 utils/boost_idb/boost/iostreams/restrict.hpp delete mode 100644 utils/boost_idb/boost/iostreams/seek.hpp delete mode 100644 utils/boost_idb/boost/iostreams/skip.hpp delete mode 100644 utils/boost_idb/boost/iostreams/slice.hpp delete mode 100644 utils/boost_idb/boost/iostreams/stream.hpp delete mode 100644 utils/boost_idb/boost/iostreams/stream_buffer.hpp delete mode 100644 utils/boost_idb/boost/iostreams/tee.hpp delete mode 100644 utils/boost_idb/boost/iostreams/traits.hpp delete mode 100644 utils/boost_idb/boost/iostreams/traits_fwd.hpp delete mode 100644 utils/boost_idb/boost/iostreams/write.hpp delete mode 100644 utils/boost_idb/boost/iterator/function_input_iterator.hpp create mode 100644 utils/boost_idb/boost/last_value.hpp create mode 100644 utils/boost_idb/boost/make_shared.hpp delete mode 100644 utils/boost_idb/boost/math/bindings/detail/big_digamma.hpp delete mode 100644 utils/boost_idb/boost/math/bindings/detail/big_lanczos.hpp delete mode 100644 utils/boost_idb/boost/math/bindings/e_float.hpp delete mode 100644 utils/boost_idb/boost/math/bindings/mpfr.hpp delete mode 100644 utils/boost_idb/boost/math/bindings/mpreal.hpp delete mode 100644 utils/boost_idb/boost/math/bindings/rr.hpp delete mode 100644 utils/boost_idb/boost/math/common_factor.hpp delete mode 100644 utils/boost_idb/boost/math/common_factor_ct.hpp delete mode 100644 utils/boost_idb/boost/math/common_factor_rt.hpp delete mode 100644 utils/boost_idb/boost/math/complex.hpp delete mode 100644 utils/boost_idb/boost/math/complex/acos.hpp delete mode 100644 utils/boost_idb/boost/math/complex/acosh.hpp delete mode 100644 utils/boost_idb/boost/math/complex/asin.hpp delete mode 100644 utils/boost_idb/boost/math/complex/asinh.hpp delete mode 100644 utils/boost_idb/boost/math/complex/atan.hpp delete mode 100644 utils/boost_idb/boost/math/complex/atanh.hpp delete mode 100644 utils/boost_idb/boost/math/complex/details.hpp delete mode 100644 utils/boost_idb/boost/math/complex/fabs.hpp delete mode 100644 utils/boost_idb/boost/math/concepts/distributions.hpp delete mode 100644 utils/boost_idb/boost/math/concepts/real_concept.hpp delete mode 100644 utils/boost_idb/boost/math/concepts/real_type_concept.hpp delete mode 100644 utils/boost_idb/boost/math/concepts/std_real_concept.hpp delete mode 100644 utils/boost_idb/boost/math/constants/calculate_constants.hpp delete mode 100644 utils/boost_idb/boost/math/constants/constants.hpp delete mode 100644 utils/boost_idb/boost/math/constants/generate.hpp delete mode 100644 utils/boost_idb/boost/math/constants/info.hpp delete mode 100644 utils/boost_idb/boost/math/distributions.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/bernoulli.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/beta.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/binomial.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/cauchy.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/chi_squared.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/complement.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/common_error_handling.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/derived_accessors.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/generic_mode.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/generic_quantile.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/hypergeometric_cdf.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/hypergeometric_pdf.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/hypergeometric_quantile.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/detail/inv_discrete_quantile.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/exponential.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/extreme_value.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/find_location.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/find_scale.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/fisher_f.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/fwd.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/gamma.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/geometric.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/hypergeometric.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/inverse_chi_squared.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/inverse_gamma.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/inverse_gaussian.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/laplace.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/logistic.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/lognormal.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/negative_binomial.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/non_central_beta.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/non_central_chi_squared.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/non_central_f.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/non_central_t.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/normal.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/pareto.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/poisson.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/rayleigh.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/skew_normal.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/students_t.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/triangular.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/uniform.hpp delete mode 100644 utils/boost_idb/boost/math/distributions/weibull.hpp delete mode 100644 utils/boost_idb/boost/math/octonion.hpp delete mode 100644 utils/boost_idb/boost/math/policies/error_handling.hpp delete mode 100644 utils/boost_idb/boost/math/policies/policy.hpp delete mode 100644 utils/boost_idb/boost/math/quaternion.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/acosh.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/airy.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/asinh.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/atanh.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/bessel.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/beta.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/binomial.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/cbrt.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/cos_pi.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/airy_ai_bi_zero.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_i0.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_i1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_ik.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_j0.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_j1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_jn.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_jy.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_jy_asym.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_jy_series.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_jy_zero.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_k0.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_k1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_kn.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_y0.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_y1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/bessel_yn.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/erf_inv.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/fp_traits.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/gamma_inva.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/ibeta_inv_ab.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/ibeta_inverse.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/iconv.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/igamma_inverse.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/igamma_large.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/lanczos_sse2.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/lgamma_small.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/round_fwd.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/t_distribution_inv.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/detail/unchecked_factorial.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/digamma.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_2.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_3.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_rc.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_rd.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_rf.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/ellint_rj.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/erf.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/expint.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/expm1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/factorials.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/fpclassify.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/gamma.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/hankel.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/hermite.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/hypot.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/jacobi_elliptic.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/laguerre.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/lanczos.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/legendre.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/log1p.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/math_fwd.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/modf.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/next.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/nonfinite_num_facets.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/owens_t.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/pow.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/powm1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/prime.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/round.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/sign.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/sin_pi.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/sinc.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/sinhc.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/spherical_harmonic.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/sqrt1pm1.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/trunc.hpp delete mode 100644 utils/boost_idb/boost/math/special_functions/zeta.hpp delete mode 100644 utils/boost_idb/boost/math/tools/big_constant.hpp delete mode 100644 utils/boost_idb/boost/math/tools/config.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_10.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_11.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_12.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_13.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_14.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_15.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_16.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_17.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_18.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_19.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_2.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_20.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_3.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_4.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_5.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_6.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_7.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_8.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner1_9.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_10.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_11.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_12.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_13.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_14.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_15.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_16.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_17.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_18.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_19.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_2.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_20.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_3.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_4.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_5.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_6.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_7.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_8.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner2_9.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_10.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_11.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_12.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_13.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_14.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_15.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_16.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_17.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_18.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_19.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_2.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_20.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_3.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_4.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_5.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_6.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_7.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_8.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/polynomial_horner3_9.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_10.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_11.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_12.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_13.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_14.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_15.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_16.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_17.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_18.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_19.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_2.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_20.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_3.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_4.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_5.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_6.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_7.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_8.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner1_9.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_10.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_11.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_12.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_13.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_14.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_15.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_16.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_17.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_18.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_19.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_2.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_20.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_3.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_4.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_5.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_6.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_7.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_8.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner2_9.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_10.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_11.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_12.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_13.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_14.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_15.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_16.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_17.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_18.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_19.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_2.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_20.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_3.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_4.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_5.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_6.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_7.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_8.hpp delete mode 100644 utils/boost_idb/boost/math/tools/detail/rational_horner3_9.hpp delete mode 100644 utils/boost_idb/boost/math/tools/fraction.hpp delete mode 100644 utils/boost_idb/boost/math/tools/minima.hpp delete mode 100644 utils/boost_idb/boost/math/tools/polynomial.hpp delete mode 100644 utils/boost_idb/boost/math/tools/precision.hpp delete mode 100644 utils/boost_idb/boost/math/tools/promotion.hpp delete mode 100644 utils/boost_idb/boost/math/tools/rational.hpp delete mode 100644 utils/boost_idb/boost/math/tools/real_cast.hpp delete mode 100644 utils/boost_idb/boost/math/tools/remez.hpp delete mode 100644 utils/boost_idb/boost/math/tools/roots.hpp delete mode 100644 utils/boost_idb/boost/math/tools/series.hpp delete mode 100644 utils/boost_idb/boost/math/tools/solve.hpp delete mode 100644 utils/boost_idb/boost/math/tools/stats.hpp delete mode 100644 utils/boost_idb/boost/math/tools/test.hpp delete mode 100644 utils/boost_idb/boost/math/tools/test_data.hpp delete mode 100644 utils/boost_idb/boost/math/tools/toms748_solve.hpp delete mode 100644 utils/boost_idb/boost/math/tools/traits.hpp delete mode 100644 utils/boost_idb/boost/math/tools/tuple.hpp delete mode 100644 utils/boost_idb/boost/math/tools/user.hpp delete mode 100644 utils/boost_idb/boost/math/tools/workaround.hpp delete mode 100644 utils/boost_idb/boost/math/tr1.hpp delete mode 100644 utils/boost_idb/boost/math/tr1_c_macros.ipp delete mode 100644 utils/boost_idb/boost/move/algorithm.hpp delete mode 100644 utils/boost_idb/boost/move/core.hpp delete mode 100644 utils/boost_idb/boost/move/detail/config_begin.hpp delete mode 100644 utils/boost_idb/boost/move/detail/config_end.hpp delete mode 100644 utils/boost_idb/boost/move/detail/meta_utils.hpp delete mode 100644 utils/boost_idb/boost/move/detail/move_helpers.hpp delete mode 100644 utils/boost_idb/boost/move/iterator.hpp delete mode 100644 utils/boost_idb/boost/move/move.hpp delete mode 100644 utils/boost_idb/boost/move/traits.hpp delete mode 100644 utils/boost_idb/boost/move/utility.hpp create mode 100644 utils/boost_idb/boost/mpi.hpp create mode 100644 utils/boost_idb/boost/multi_array.hpp create mode 100644 utils/boost_idb/boost/multi_index_container.hpp create mode 100644 utils/boost_idb/boost/multi_index_container_fwd.hpp create mode 100644 utils/boost_idb/boost/non_type.hpp create mode 100644 utils/boost_idb/boost/nondet_random.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/bounds.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/cast.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/conversion_traits.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/converter.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/converter_policies.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/bounds.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/conversion_traits.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/converter.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/int_float_mixture.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/is_subranged.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/meta.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/numeric_cast_traits.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/old_numeric_cast.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/preprocessed/numeric_cast_traits_common.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/preprocessed/numeric_cast_traits_long_long.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/sign_mixture.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/detail/udt_builtin_mixture.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/int_float_mixture.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/int_float_mixture_enum.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/is_subranged.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/numeric_cast_traits.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/sign_mixture.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/sign_mixture_enum.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/udt_builtin_mixture.hpp delete mode 100644 utils/boost_idb/boost/numeric/conversion/udt_builtin_mixture_enum.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/arith.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/arith2.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/arith3.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/checking.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare/certain.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare/explicit.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare/lexicographic.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare/possible.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare/set.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/compare/tribool.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/constants.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/alpha_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/bcc_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/bugs.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/c99_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/c99sub_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/division.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/ia64_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/interval_prototype.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/msvc_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/ppc_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/sparc_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/test_input.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/x86_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/detail/x86gcc_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/ext/integer.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/ext/x86_fast_rounding_control.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/hw_rounding.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/interval.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/io.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/limits.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/policies.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/rounded_arith.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/rounded_transc.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/rounding.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/transc.hpp delete mode 100644 utils/boost_idb/boost/numeric/interval/utility.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/array_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/default_operations.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/detail/for_each.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/detail/macros.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/detail/reduce.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/fusion_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/range_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/algebra/vector_space_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/config.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/gsl/gsl_wrapper.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/mkl/mkl_operations.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/mtl4/implicit_euler_mtl4.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/mtl4/mtl4_resize.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/thrust/thrust_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/thrust/thrust_operations.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/thrust/thrust_resize.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/vexcl/vexcl_resize.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/viennacl/viennacl_operations.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/external/viennacl/viennacl_resize.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/detail/integrate_adaptive.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/detail/integrate_const.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/detail/integrate_n_steps.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/detail/integrate_times.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/integrate.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/integrate_adaptive.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/integrate_const.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/integrate_n_steps.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/integrate_times.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/null_observer.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/integrate/observer_collection.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/adams_bashforth.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/adams_bashforth_moulton.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/adams_moulton.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/base/algebra_stepper_base.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/base/explicit_error_stepper_base.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/base/explicit_error_stepper_fsal_base.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/base/explicit_stepper_base.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/base/symplectic_rkn_stepper_base.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/bulirsch_stoer.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/controlled_runge_kutta.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/controlled_step_result.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/adams_bashforth_call_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/adams_bashforth_coefficients.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/adams_moulton_call_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/generic_rk_algorithm.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/generic_rk_call_algebra.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/generic_rk_operations.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/detail/rotating_buffer.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/euler.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/explicit_error_generic_rk.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/explicit_generic_rk.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_controlled_runge_kutta.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_dense_output_runge_kutta.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_rosenbrock4.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_runge_kutta_cash_karp54.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_runge_kutta_cash_karp54_classic.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_runge_kutta_dopri5.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/generation_runge_kutta_fehlberg78.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/make_controlled.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/generation/make_dense_output.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/implicit_euler.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/modified_midpoint.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/rosenbrock4.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/rosenbrock4_controller.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/rosenbrock4_dense_output.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/runge_kutta4.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/runge_kutta4_classic.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/runge_kutta_cash_karp54_classic.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/stepper_categories.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/symplectic_euler.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_m4_mclachlan.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/bind.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/copy.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/detail/is_range.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/detail/less_with_sign.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/is_pair.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/is_resizeable.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/resize.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/resizer.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/same_instance.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/same_size.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/state_wrapper.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/ublas_wrapper.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/unit_helper.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/util/unwrap_reference.hpp delete mode 100644 utils/boost_idb/boost/numeric/odeint/version.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/assignment.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/banded.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/blas.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/concepts.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/config.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/definitions.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/documentation.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/duff.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/iterator.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/matrix_assign.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/raw.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/returntype_deduction.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/temporary.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/detail/vector_assign.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/doxydoc.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/exception.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/experimental/sparse_view.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/expression_types.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/functional.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/fwd.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/hermitian.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/io.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/lu.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/matrix.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/matrix_expression.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/matrix_proxy.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/matrix_sparse.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation/begin.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation/c_array.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation/end.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation/num_columns.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation/num_rows.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation/size.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation_blocked.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operation_sparse.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/operations.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/storage.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/storage_sparse.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/symmetric.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/tags.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/traits.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/traits/c_array.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/traits/const_iterator_type.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/traits/iterator_type.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/triangular.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/vector.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/vector_expression.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/vector_of_vector.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/vector_proxy.hpp delete mode 100644 utils/boost_idb/boost/numeric/ublas/vector_sparse.hpp create mode 100644 utils/boost_idb/boost/parameter.hpp delete mode 100644 utils/boost_idb/boost/pending/bucket_sorter.hpp delete mode 100644 utils/boost_idb/boost/pending/container_traits.hpp delete mode 100644 utils/boost_idb/boost/pending/cstddef.hpp delete mode 100644 utils/boost_idb/boost/pending/detail/disjoint_sets.hpp delete mode 100644 utils/boost_idb/boost/pending/detail/int_iterator.hpp delete mode 100644 utils/boost_idb/boost/pending/detail/property.hpp delete mode 100644 utils/boost_idb/boost/pending/disjoint_sets.hpp delete mode 100644 utils/boost_idb/boost/pending/fenced_priority_queue.hpp delete mode 100644 utils/boost_idb/boost/pending/fibonacci_heap.hpp delete mode 100644 utils/boost_idb/boost/pending/indirect_cmp.hpp delete mode 100644 utils/boost_idb/boost/pending/integer_log2.hpp delete mode 100644 utils/boost_idb/boost/pending/is_heap.hpp delete mode 100644 utils/boost_idb/boost/pending/iterator_adaptors.hpp delete mode 100644 utils/boost_idb/boost/pending/iterator_tests.hpp delete mode 100644 utils/boost_idb/boost/pending/lowest_bit.hpp delete mode 100644 utils/boost_idb/boost/pending/mutable_heap.hpp delete mode 100644 utils/boost_idb/boost/pending/mutable_queue.hpp delete mode 100644 utils/boost_idb/boost/pending/property.hpp delete mode 100644 utils/boost_idb/boost/pending/property_serialize.hpp delete mode 100644 utils/boost_idb/boost/pending/queue.hpp delete mode 100644 utils/boost_idb/boost/pending/relaxed_heap.hpp delete mode 100644 utils/boost_idb/boost/pending/stringtok.hpp create mode 100644 utils/boost_idb/boost/pointer_cast.hpp create mode 100644 utils/boost_idb/boost/pointer_to_other.hpp delete mode 100644 utils/boost_idb/boost/predef.h delete mode 100644 utils/boost_idb/boost/predef/architecture.h delete mode 100644 utils/boost_idb/boost/predef/architecture/alpha.h delete mode 100644 utils/boost_idb/boost/predef/architecture/arm.h delete mode 100644 utils/boost_idb/boost/predef/architecture/blackfin.h delete mode 100644 utils/boost_idb/boost/predef/architecture/convex.h delete mode 100644 utils/boost_idb/boost/predef/architecture/ia64.h delete mode 100644 utils/boost_idb/boost/predef/architecture/m68k.h delete mode 100644 utils/boost_idb/boost/predef/architecture/mips.h delete mode 100644 utils/boost_idb/boost/predef/architecture/parisc.h delete mode 100644 utils/boost_idb/boost/predef/architecture/ppc.h delete mode 100644 utils/boost_idb/boost/predef/architecture/pyramid.h delete mode 100644 utils/boost_idb/boost/predef/architecture/rs6k.h delete mode 100644 utils/boost_idb/boost/predef/architecture/sparc.h delete mode 100644 utils/boost_idb/boost/predef/architecture/superh.h delete mode 100644 utils/boost_idb/boost/predef/architecture/sys370.h delete mode 100644 utils/boost_idb/boost/predef/architecture/sys390.h delete mode 100644 utils/boost_idb/boost/predef/architecture/x86.h delete mode 100644 utils/boost_idb/boost/predef/architecture/x86/32.h delete mode 100644 utils/boost_idb/boost/predef/architecture/x86/64.h delete mode 100644 utils/boost_idb/boost/predef/architecture/z.h delete mode 100644 utils/boost_idb/boost/predef/compiler.h delete mode 100644 utils/boost_idb/boost/predef/compiler/borland.h delete mode 100644 utils/boost_idb/boost/predef/compiler/clang.h delete mode 100644 utils/boost_idb/boost/predef/compiler/comeau.h delete mode 100644 utils/boost_idb/boost/predef/compiler/compaq.h delete mode 100644 utils/boost_idb/boost/predef/compiler/diab.h delete mode 100644 utils/boost_idb/boost/predef/compiler/digitalmars.h delete mode 100644 utils/boost_idb/boost/predef/compiler/dignus.h delete mode 100644 utils/boost_idb/boost/predef/compiler/edg.h delete mode 100644 utils/boost_idb/boost/predef/compiler/ekopath.h delete mode 100644 utils/boost_idb/boost/predef/compiler/gcc.h delete mode 100644 utils/boost_idb/boost/predef/compiler/gcc_xml.h delete mode 100644 utils/boost_idb/boost/predef/compiler/greenhills.h delete mode 100644 utils/boost_idb/boost/predef/compiler/hp_acc.h delete mode 100644 utils/boost_idb/boost/predef/compiler/iar.h delete mode 100644 utils/boost_idb/boost/predef/compiler/ibm.h delete mode 100644 utils/boost_idb/boost/predef/compiler/intel.h delete mode 100644 utils/boost_idb/boost/predef/compiler/kai.h delete mode 100644 utils/boost_idb/boost/predef/compiler/llvm.h delete mode 100644 utils/boost_idb/boost/predef/compiler/metaware.h delete mode 100644 utils/boost_idb/boost/predef/compiler/metrowerks.h delete mode 100644 utils/boost_idb/boost/predef/compiler/microtec.h delete mode 100644 utils/boost_idb/boost/predef/compiler/mpw.h delete mode 100644 utils/boost_idb/boost/predef/compiler/palm.h delete mode 100644 utils/boost_idb/boost/predef/compiler/pgi.h delete mode 100644 utils/boost_idb/boost/predef/compiler/sgi_mipspro.h delete mode 100644 utils/boost_idb/boost/predef/compiler/sunpro.h delete mode 100644 utils/boost_idb/boost/predef/compiler/tendra.h delete mode 100644 utils/boost_idb/boost/predef/compiler/visualc.h delete mode 100644 utils/boost_idb/boost/predef/compiler/watcom.h delete mode 100644 utils/boost_idb/boost/predef/detail/_cassert.h delete mode 100644 utils/boost_idb/boost/predef/detail/_exception.h delete mode 100644 utils/boost_idb/boost/predef/detail/endian_compat.h delete mode 100644 utils/boost_idb/boost/predef/detail/os_detected.h delete mode 100644 utils/boost_idb/boost/predef/detail/test.h delete mode 100644 utils/boost_idb/boost/predef/language.h delete mode 100644 utils/boost_idb/boost/predef/language/objc.h delete mode 100644 utils/boost_idb/boost/predef/language/stdc.h delete mode 100644 utils/boost_idb/boost/predef/language/stdcpp.h delete mode 100644 utils/boost_idb/boost/predef/library.h delete mode 100644 utils/boost_idb/boost/predef/library/c.h delete mode 100644 utils/boost_idb/boost/predef/library/c/_prefix.h delete mode 100644 utils/boost_idb/boost/predef/library/c/gnu.h delete mode 100644 utils/boost_idb/boost/predef/library/c/uc.h delete mode 100644 utils/boost_idb/boost/predef/library/c/vms.h delete mode 100644 utils/boost_idb/boost/predef/library/c/zos.h delete mode 100644 utils/boost_idb/boost/predef/library/std.h delete mode 100644 utils/boost_idb/boost/predef/library/std/_prefix.h delete mode 100644 utils/boost_idb/boost/predef/library/std/cxx.h delete mode 100644 utils/boost_idb/boost/predef/library/std/dinkumware.h delete mode 100644 utils/boost_idb/boost/predef/library/std/libcomo.h delete mode 100644 utils/boost_idb/boost/predef/library/std/modena.h delete mode 100644 utils/boost_idb/boost/predef/library/std/msl.h delete mode 100644 utils/boost_idb/boost/predef/library/std/roguewave.h delete mode 100644 utils/boost_idb/boost/predef/library/std/sgi.h delete mode 100644 utils/boost_idb/boost/predef/library/std/stdcpp3.h delete mode 100644 utils/boost_idb/boost/predef/library/std/stlport.h delete mode 100644 utils/boost_idb/boost/predef/library/std/vacpp.h delete mode 100644 utils/boost_idb/boost/predef/make.h delete mode 100644 utils/boost_idb/boost/predef/os.h delete mode 100644 utils/boost_idb/boost/predef/os/aix.h delete mode 100644 utils/boost_idb/boost/predef/os/amigaos.h delete mode 100644 utils/boost_idb/boost/predef/os/android.h delete mode 100644 utils/boost_idb/boost/predef/os/beos.h delete mode 100644 utils/boost_idb/boost/predef/os/bsd.h delete mode 100644 utils/boost_idb/boost/predef/os/bsd/bsdi.h delete mode 100644 utils/boost_idb/boost/predef/os/bsd/dragonfly.h delete mode 100644 utils/boost_idb/boost/predef/os/bsd/free.h delete mode 100644 utils/boost_idb/boost/predef/os/bsd/net.h delete mode 100644 utils/boost_idb/boost/predef/os/bsd/open.h delete mode 100644 utils/boost_idb/boost/predef/os/cygwin.h delete mode 100644 utils/boost_idb/boost/predef/os/hpux.h delete mode 100644 utils/boost_idb/boost/predef/os/irix.h delete mode 100644 utils/boost_idb/boost/predef/os/linux.h delete mode 100644 utils/boost_idb/boost/predef/os/macos.h delete mode 100644 utils/boost_idb/boost/predef/os/os400.h delete mode 100644 utils/boost_idb/boost/predef/os/qnxnto.h delete mode 100644 utils/boost_idb/boost/predef/os/solaris.h delete mode 100644 utils/boost_idb/boost/predef/os/unix.h delete mode 100644 utils/boost_idb/boost/predef/os/vms.h delete mode 100644 utils/boost_idb/boost/predef/os/windows.h delete mode 100644 utils/boost_idb/boost/predef/other.h delete mode 100644 utils/boost_idb/boost/predef/other/endian.h delete mode 100644 utils/boost_idb/boost/predef/platform.h delete mode 100644 utils/boost_idb/boost/predef/platform/mingw.h delete mode 100644 utils/boost_idb/boost/predef/version_number.h delete mode 100644 utils/boost_idb/boost/preprocessor/array/enum.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/array/to_list.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/array/to_seq.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/array/to_tuple.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/facilities/overload.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/list/to_array.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/list/to_seq.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/seq/detail/binary_transform.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/seq/to_list.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/tuple/enum.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/tuple/size.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/tuple/to_array.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic/elem.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic/size.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic/to_array.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic/to_list.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic/to_seq.hpp delete mode 100644 utils/boost_idb/boost/preprocessor/variadic/to_tuple.hpp create mode 100644 utils/boost_idb/boost/program_options.hpp create mode 100644 utils/boost_idb/boost/python.hpp delete mode 100644 utils/boost_idb/boost/random/additive_combine.hpp delete mode 100644 utils/boost_idb/boost/random/bernoulli_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/binomial_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/cauchy_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/chi_squared_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/detail/auto_link.hpp delete mode 100644 utils/boost_idb/boost/random/detail/config.hpp delete mode 100644 utils/boost_idb/boost/random/detail/const_mod.hpp delete mode 100644 utils/boost_idb/boost/random/detail/disable_warnings.hpp delete mode 100644 utils/boost_idb/boost/random/detail/enable_warnings.hpp delete mode 100644 utils/boost_idb/boost/random/detail/generator_bits.hpp delete mode 100644 utils/boost_idb/boost/random/detail/generator_seed_seq.hpp delete mode 100644 utils/boost_idb/boost/random/detail/integer_log2.hpp delete mode 100644 utils/boost_idb/boost/random/detail/iterator_mixin.hpp delete mode 100644 utils/boost_idb/boost/random/detail/large_arithmetic.hpp delete mode 100644 utils/boost_idb/boost/random/detail/operators.hpp delete mode 100644 utils/boost_idb/boost/random/detail/ptr_helper.hpp delete mode 100644 utils/boost_idb/boost/random/detail/seed.hpp delete mode 100644 utils/boost_idb/boost/random/detail/seed_impl.hpp delete mode 100644 utils/boost_idb/boost/random/detail/signed_unsigned_tools.hpp delete mode 100644 utils/boost_idb/boost/random/detail/uniform_int_float.hpp delete mode 100644 utils/boost_idb/boost/random/detail/vector_io.hpp delete mode 100644 utils/boost_idb/boost/random/discard_block.hpp delete mode 100644 utils/boost_idb/boost/random/discrete_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/exponential_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/extreme_value_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/fisher_f_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/gamma_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/generate_canonical.hpp delete mode 100644 utils/boost_idb/boost/random/geometric_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/independent_bits.hpp delete mode 100644 utils/boost_idb/boost/random/inversive_congruential.hpp delete mode 100644 utils/boost_idb/boost/random/lagged_fibonacci.hpp delete mode 100644 utils/boost_idb/boost/random/linear_congruential.hpp delete mode 100644 utils/boost_idb/boost/random/linear_feedback_shift.hpp delete mode 100644 utils/boost_idb/boost/random/lognormal_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/mersenne_twister.hpp delete mode 100644 utils/boost_idb/boost/random/negative_binomial_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/normal_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/piecewise_constant_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/piecewise_linear_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/poisson_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/random_device.hpp delete mode 100644 utils/boost_idb/boost/random/random_number_generator.hpp delete mode 100644 utils/boost_idb/boost/random/ranlux.hpp delete mode 100644 utils/boost_idb/boost/random/seed_seq.hpp delete mode 100644 utils/boost_idb/boost/random/shuffle_order.hpp delete mode 100644 utils/boost_idb/boost/random/shuffle_output.hpp delete mode 100644 utils/boost_idb/boost/random/student_t_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/subtract_with_carry.hpp delete mode 100644 utils/boost_idb/boost/random/taus88.hpp delete mode 100644 utils/boost_idb/boost/random/triangle_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_01.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_int.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_int_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_on_sphere.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_real.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_real_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/uniform_smallint.hpp delete mode 100644 utils/boost_idb/boost/random/variate_generator.hpp delete mode 100644 utils/boost_idb/boost/random/weibull_distribution.hpp delete mode 100644 utils/boost_idb/boost/random/xor_combine.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/adjacent_filtered.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/argument_fwd.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/copied.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/define_adaptor.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/filtered.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/indexed.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/indirected.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/map.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/replaced.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/replaced_if.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/reversed.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/sliced.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/strided.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/tokenized.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/transformed.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/type_erased.hpp delete mode 100644 utils/boost_idb/boost/range/adaptor/uniqued.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/adaptors.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/adjacent_find.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/binary_search.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/copy_backward.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/count.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/count_if.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/equal.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/equal_range.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/fill.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/fill_n.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/find.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/find_end.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/find_first_of.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/find_if.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/for_each.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/generate.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/heap_algorithm.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/inplace_merge.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/lexicographical_compare.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/lower_bound.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/max_element.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/merge.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/min_element.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/mismatch.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/nth_element.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/partial_sort.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/partial_sort_copy.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/partition.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/permutation.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/random_shuffle.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/remove.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/remove_copy.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/remove_copy_if.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/remove_if.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/replace.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/replace_copy.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/replace_copy_if.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/replace_if.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/reverse.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/reverse_copy.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/rotate.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/rotate_copy.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/search.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/search_n.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/set_algorithm.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/sort.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/stable_partition.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/stable_sort.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/swap_ranges.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/transform.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/unique.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/unique_copy.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm/upper_bound.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/algorithm_ext.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/copy_n.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/erase.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/for_each.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/insert.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/iota.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/is_sorted.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/overwrite.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/push_back.hpp delete mode 100644 utils/boost_idb/boost/range/algorithm_ext/push_front.hpp delete mode 100644 utils/boost_idb/boost/range/any_range.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/combine.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/counting_range.hpp delete mode 100644 utils/boost_idb/boost/range/detail/any_iterator.hpp delete mode 100644 utils/boost_idb/boost/range/detail/any_iterator_buffer.hpp delete mode 100644 utils/boost_idb/boost/range/detail/any_iterator_interface.hpp delete mode 100644 utils/boost_idb/boost/range/detail/any_iterator_wrapper.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/detail/demote_iterator_traversal_tag.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/detail/extract_optional_type.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/detail/misc_concept.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/detail/range_return.hpp delete mode 100644 utils/boost_idb/boost/range/detail/safe_bool.hpp delete mode 100644 utils/boost_idb/boost/range/has_range_iterator.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/istream_range.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/iterator_range_core.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/iterator_range_io.hpp mode change 100644 => 100755 utils/boost_idb/boost/range/numeric.hpp delete mode 100644 utils/boost_idb/boost/ratio.hpp delete mode 100644 utils/boost_idb/boost/ratio/config.hpp delete mode 100644 utils/boost_idb/boost/ratio/detail/mpl/abs.hpp delete mode 100644 utils/boost_idb/boost/ratio/detail/mpl/gcd.hpp delete mode 100644 utils/boost_idb/boost/ratio/detail/mpl/lcm.hpp delete mode 100644 utils/boost_idb/boost/ratio/detail/mpl/sign.hpp delete mode 100644 utils/boost_idb/boost/ratio/detail/overflow_helpers.hpp delete mode 100644 utils/boost_idb/boost/ratio/detail/ratio_io.hpp delete mode 100644 utils/boost_idb/boost/ratio/include.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/abs.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/arithmetic.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/comparison.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/divides.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/equal_to.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/gcd.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/greater.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/greater_equal.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/lcm.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/less.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/less_equal.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/minus.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/negate.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/not_equal_to.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/numeric_cast.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/plus.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/rational_c_tag.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/rational_constant.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/sign.hpp delete mode 100644 utils/boost_idb/boost/ratio/mpl/times.hpp delete mode 100644 utils/boost_idb/boost/ratio/ratio.hpp delete mode 100644 utils/boost_idb/boost/ratio/ratio_fwd.hpp delete mode 100644 utils/boost_idb/boost/ratio/ratio_io.hpp delete mode 100644 utils/boost_idb/boost/ratio/ratio_static_string.hpp create mode 100644 utils/boost_idb/boost/scope_exit.hpp create mode 100644 utils/boost_idb/boost/shared_container_iterator.hpp create mode 100644 utils/boost_idb/boost/signal.hpp create mode 100644 utils/boost_idb/boost/signals.hpp create mode 100644 utils/boost_idb/boost/signals2.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/allocate_shared_array.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/allocate_array_helper.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/array_deleter.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/array_traits.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/array_utility.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/make_array_helper.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/sp_counted_base_aix.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/sp_forward.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/sp_if_array.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/detail/sp_nullptr_t.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/enable_shared_from_raw.hpp create mode 100644 utils/boost_idb/boost/smart_ptr/enable_shared_from_this2.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/intrusive_ref_counter.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/make_shared_array.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/make_shared_object.hpp delete mode 100644 utils/boost_idb/boost/smart_ptr/owner_less.hpp create mode 100644 utils/boost_idb/boost/spirit.hpp create mode 100644 utils/boost_idb/boost/strong_typedef.hpp delete mode 100644 utils/boost_idb/boost/thread/completion_latch.hpp delete mode 100644 utils/boost_idb/boost/thread/cv_status.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/async_func.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/counter.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/delete.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/invoke.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/is_convertible.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/lockable_wrapper.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/log.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/make_tuple_indices.hpp delete mode 100644 utils/boost_idb/boost/thread/detail/memory.hpp delete mode 100644 utils/boost_idb/boost/thread/externally_locked.hpp delete mode 100644 utils/boost_idb/boost/thread/externally_locked_stream.hpp delete mode 100644 utils/boost_idb/boost/thread/future_error_code.hpp delete mode 100644 utils/boost_idb/boost/thread/is_locked_by_this_thread.hpp delete mode 100644 utils/boost_idb/boost/thread/latch.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_algorithms.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_concepts.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_factories.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_guard.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_options.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_traits.hpp delete mode 100644 utils/boost_idb/boost/thread/lock_types.hpp delete mode 100644 utils/boost_idb/boost/thread/lockable_adapter.hpp delete mode 100644 utils/boost_idb/boost/thread/lockable_concepts.hpp delete mode 100644 utils/boost_idb/boost/thread/lockable_traits.hpp delete mode 100644 utils/boost_idb/boost/thread/null_mutex.hpp delete mode 100644 utils/boost_idb/boost/thread/poly_lockable.hpp delete mode 100644 utils/boost_idb/boost/thread/poly_lockable_adapter.hpp delete mode 100644 utils/boost_idb/boost/thread/poly_shared_lockable.hpp delete mode 100644 utils/boost_idb/boost/thread/poly_shared_lockable_adapter.hpp delete mode 100644 utils/boost_idb/boost/thread/pthread/once_atomic.hpp delete mode 100644 utils/boost_idb/boost/thread/pthread/shared_mutex_assert.hpp delete mode 100644 utils/boost_idb/boost/thread/reverse_lock.hpp delete mode 100644 utils/boost_idb/boost/thread/scoped_thread.hpp delete mode 100644 utils/boost_idb/boost/thread/shared_lock_guard.hpp delete mode 100644 utils/boost_idb/boost/thread/strict_lock.hpp delete mode 100644 utils/boost_idb/boost/thread/sync_bounded_queue.hpp delete mode 100644 utils/boost_idb/boost/thread/sync_queue.hpp delete mode 100644 utils/boost_idb/boost/thread/synchronized_value.hpp delete mode 100644 utils/boost_idb/boost/thread/testable_mutex.hpp delete mode 100644 utils/boost_idb/boost/thread/thread_functors.hpp delete mode 100644 utils/boost_idb/boost/thread/thread_guard.hpp delete mode 100644 utils/boost_idb/boost/thread/thread_only.hpp delete mode 100644 utils/boost_idb/boost/thread/v2/shared_mutex.hpp delete mode 100644 utils/boost_idb/boost/thread/v2/thread.hpp delete mode 100644 utils/boost_idb/boost/thread/win32/mfc_thread_init.hpp delete mode 100644 utils/boost_idb/boost/timer/config.hpp delete mode 100644 utils/boost_idb/boost/timer/timer.hpp delete mode 100644 utils/boost_idb/boost/type_traits/detail/has_binary_operator.hpp delete mode 100644 utils/boost_idb/boost/type_traits/detail/has_postfix_operator.hpp delete mode 100644 utils/boost_idb/boost/type_traits/detail/has_prefix_operator.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_bit_and.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_bit_and_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_bit_or.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_bit_or_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_bit_xor.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_bit_xor_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_complement.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_dereference.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_divides.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_divides_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_equal_to.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_greater.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_greater_equal.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_left_shift.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_left_shift_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_less.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_less_equal.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_logical_and.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_logical_not.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_logical_or.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_minus.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_minus_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_modulus.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_modulus_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_multiplies.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_multiplies_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_negate.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_not_equal_to.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_operator.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_plus.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_plus_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_post_decrement.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_post_increment.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_pre_decrement.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_pre_increment.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_right_shift.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_right_shift_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_trivial_move_assign.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_trivial_move_constructor.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_unary_minus.hpp delete mode 100644 utils/boost_idb/boost/type_traits/has_unary_plus.hpp delete mode 100644 utils/boost_idb/boost/type_traits/is_copy_constructible.hpp delete mode 100644 utils/boost_idb/boost/type_traits/is_nothrow_move_assignable.hpp delete mode 100644 utils/boost_idb/boost/type_traits/is_nothrow_move_constructible.hpp delete mode 100644 utils/boost_idb/boost/typeof/dmc/typeof_impl.hpp delete mode 100644 utils/boost_idb/boost/typeof/encode_decode.hpp delete mode 100644 utils/boost_idb/boost/typeof/encode_decode_params.hpp delete mode 100644 utils/boost_idb/boost/typeof/incr_registration_group.hpp delete mode 100644 utils/boost_idb/boost/typeof/int_encoding.hpp delete mode 100644 utils/boost_idb/boost/typeof/integral_template_param.hpp delete mode 100644 utils/boost_idb/boost/typeof/message.hpp delete mode 100644 utils/boost_idb/boost/typeof/modifiers.hpp delete mode 100644 utils/boost_idb/boost/typeof/msvc/typeof_impl.hpp delete mode 100644 utils/boost_idb/boost/typeof/native.hpp delete mode 100644 utils/boost_idb/boost/typeof/pointers_data_members.hpp delete mode 100644 utils/boost_idb/boost/typeof/register_functions.hpp delete mode 100644 utils/boost_idb/boost/typeof/register_functions_iterate.hpp delete mode 100644 utils/boost_idb/boost/typeof/register_fundamental.hpp delete mode 100644 utils/boost_idb/boost/typeof/register_mem_functions.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/bitset.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/complex.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/deque.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/fstream.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/functional.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/iostream.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/istream.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/iterator.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/list.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/locale.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/map.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/memory.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/ostream.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/queue.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/set.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/sstream.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/stack.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/streambuf.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/string.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/utility.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/valarray.hpp delete mode 100644 utils/boost_idb/boost/typeof/std/vector.hpp delete mode 100644 utils/boost_idb/boost/typeof/template_encoding.hpp delete mode 100644 utils/boost_idb/boost/typeof/template_template_param.hpp delete mode 100644 utils/boost_idb/boost/typeof/type_encoding.hpp delete mode 100644 utils/boost_idb/boost/typeof/type_template_param.hpp delete mode 100644 utils/boost_idb/boost/typeof/typeof.hpp delete mode 100644 utils/boost_idb/boost/typeof/typeof_impl.hpp delete mode 100644 utils/boost_idb/boost/typeof/unsupported.hpp delete mode 100644 utils/boost_idb/boost/typeof/vector.hpp delete mode 100644 utils/boost_idb/boost/typeof/vector100.hpp delete mode 100644 utils/boost_idb/boost/typeof/vector150.hpp delete mode 100644 utils/boost_idb/boost/typeof/vector200.hpp delete mode 100644 utils/boost_idb/boost/typeof/vector50.hpp create mode 100644 utils/boost_idb/boost/units/absolute.hpp create mode 100644 utils/boost_idb/boost/units/base_dimension.hpp create mode 100644 utils/boost_idb/boost/units/base_unit.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/arcminute.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/arcsecond.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/degree.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/gradian.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/radian.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/revolution.hpp create mode 100644 utils/boost_idb/boost/units/base_units/angle/steradian.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/astronomical_unit.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/light_day.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/light_hour.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/light_minute.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/light_second.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/light_year.hpp create mode 100644 utils/boost_idb/boost/units/base_units/astronomical/parsec.hpp create mode 100644 utils/boost_idb/boost/units/base_units/cgs/biot.hpp create mode 100644 utils/boost_idb/boost/units/base_units/cgs/centimeter.hpp create mode 100644 utils/boost_idb/boost/units/base_units/cgs/gram.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/conversions.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/drachm.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/fluid_ounce.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/foot.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/furlong.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/gallon.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/gill.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/grain.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/hundredweight.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/inch.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/league.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/mile.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/ounce.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/pint.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/pound.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/quart.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/quarter.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/stone.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/thou.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/ton.hpp create mode 100644 utils/boost_idb/boost/units/base_units/imperial/yard.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/angstrom.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/are.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/atmosphere.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/bar.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/barn.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/day.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/fermi.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/hectare.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/hour.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/knot.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/liter.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/micron.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/minute.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/mmHg.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/nautical_mile.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/ton.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/torr.hpp create mode 100644 utils/boost_idb/boost/units/base_units/metric/year.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/ampere.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/candela.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/kelvin.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/kilogram.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/meter.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/mole.hpp create mode 100644 utils/boost_idb/boost/units/base_units/si/second.hpp create mode 100644 utils/boost_idb/boost/units/base_units/temperature/celsius.hpp create mode 100644 utils/boost_idb/boost/units/base_units/temperature/conversions.hpp create mode 100644 utils/boost_idb/boost/units/base_units/temperature/fahrenheit.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/cup.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/dram.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/fluid_dram.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/fluid_ounce.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/foot.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/gallon.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/gill.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/grain.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/hundredweight.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/inch.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/mil.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/mile.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/minim.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/ounce.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/pint.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/pound.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/pound_force.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/quart.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/tablespoon.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/teaspoon.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/ton.hpp create mode 100644 utils/boost_idb/boost/units/base_units/us/yard.hpp create mode 100644 utils/boost_idb/boost/units/cmath.hpp create mode 100644 utils/boost_idb/boost/units/config.hpp create mode 100644 utils/boost_idb/boost/units/conversion.hpp create mode 100644 utils/boost_idb/boost/units/derived_dimension.hpp create mode 100644 utils/boost_idb/boost/units/detail/absolute_impl.hpp create mode 100644 utils/boost_idb/boost/units/detail/cmath_impl.hpp create mode 100644 utils/boost_idb/boost/units/detail/conversion_impl.hpp create mode 100644 utils/boost_idb/boost/units/detail/dim_impl.hpp create mode 100644 utils/boost_idb/boost/units/detail/dimension_impl.hpp create mode 100644 utils/boost_idb/boost/units/detail/dimension_list.hpp create mode 100644 utils/boost_idb/boost/units/detail/dimensionless_unit.hpp create mode 100644 utils/boost_idb/boost/units/detail/heterogeneous_conversion.hpp create mode 100644 utils/boost_idb/boost/units/detail/linear_algebra.hpp create mode 100644 utils/boost_idb/boost/units/detail/one.hpp create mode 100644 utils/boost_idb/boost/units/detail/ordinal.hpp create mode 100644 utils/boost_idb/boost/units/detail/prevent_redefinition.hpp create mode 100644 utils/boost_idb/boost/units/detail/push_front_if.hpp create mode 100644 utils/boost_idb/boost/units/detail/push_front_or_add.hpp create mode 100644 utils/boost_idb/boost/units/detail/sort.hpp create mode 100644 utils/boost_idb/boost/units/detail/static_rational_power.hpp create mode 100644 utils/boost_idb/boost/units/detail/unscale.hpp create mode 100644 utils/boost_idb/boost/units/detail/utility.hpp create mode 100644 utils/boost_idb/boost/units/dim.hpp create mode 100644 utils/boost_idb/boost/units/dimension.hpp create mode 100644 utils/boost_idb/boost/units/dimensionless_quantity.hpp create mode 100644 utils/boost_idb/boost/units/dimensionless_type.hpp create mode 100644 utils/boost_idb/boost/units/dimensionless_unit.hpp create mode 100644 utils/boost_idb/boost/units/get_dimension.hpp create mode 100644 utils/boost_idb/boost/units/get_system.hpp create mode 100644 utils/boost_idb/boost/units/heterogeneous_system.hpp create mode 100644 utils/boost_idb/boost/units/homogeneous_system.hpp create mode 100644 utils/boost_idb/boost/units/io.hpp create mode 100644 utils/boost_idb/boost/units/is_dim.hpp create mode 100644 utils/boost_idb/boost/units/is_dimension_list.hpp create mode 100644 utils/boost_idb/boost/units/is_dimensionless.hpp create mode 100644 utils/boost_idb/boost/units/is_dimensionless_quantity.hpp create mode 100644 utils/boost_idb/boost/units/is_dimensionless_unit.hpp create mode 100644 utils/boost_idb/boost/units/is_quantity.hpp create mode 100644 utils/boost_idb/boost/units/is_quantity_of_dimension.hpp create mode 100644 utils/boost_idb/boost/units/is_quantity_of_system.hpp create mode 100644 utils/boost_idb/boost/units/is_unit.hpp create mode 100644 utils/boost_idb/boost/units/is_unit_of_dimension.hpp create mode 100644 utils/boost_idb/boost/units/is_unit_of_system.hpp create mode 100644 utils/boost_idb/boost/units/lambda.hpp create mode 100644 utils/boost_idb/boost/units/limits.hpp create mode 100644 utils/boost_idb/boost/units/make_scaled_unit.hpp create mode 100644 utils/boost_idb/boost/units/make_system.hpp create mode 100644 utils/boost_idb/boost/units/operators.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/absorbed_dose.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/acceleration.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/action.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/activity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/amount.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/angular_acceleration.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/angular_momentum.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/angular_velocity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/area.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/capacitance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/conductance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/conductivity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/current.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/dose_equivalent.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/dynamic_viscosity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/electric_charge.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/electric_potential.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/energy.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/energy_density.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/force.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/frequency.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/heat_capacity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/illuminance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/impedance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/inductance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/kinematic_viscosity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/length.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/luminance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/luminous_flux.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/luminous_intensity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/magnetic_field_intensity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/magnetic_flux.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/magnetic_flux_density.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/mass.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/mass_density.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/molar_energy.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/molar_heat_capacity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/moment_of_inertia.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/momentum.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/permeability.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/permittivity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/plane_angle.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/power.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/pressure.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/reluctance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/resistance.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/resistivity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/solid_angle.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/specific_energy.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/specific_heat_capacity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/specific_volume.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/stress.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/surface_density.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/surface_tension.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/temperature.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/thermal_conductivity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/time.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/torque.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/velocity.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/volume.hpp create mode 100644 utils/boost_idb/boost/units/physical_dimensions/wavenumber.hpp create mode 100644 utils/boost_idb/boost/units/pow.hpp create mode 100644 utils/boost_idb/boost/units/quantity.hpp create mode 100644 utils/boost_idb/boost/units/reduce_unit.hpp create mode 100644 utils/boost_idb/boost/units/scale.hpp create mode 100644 utils/boost_idb/boost/units/scaled_base_unit.hpp create mode 100644 utils/boost_idb/boost/units/static_constant.hpp create mode 100644 utils/boost_idb/boost/units/static_rational.hpp create mode 100644 utils/boost_idb/boost/units/systems/abstract.hpp create mode 100644 utils/boost_idb/boost/units/systems/angle/degrees.hpp create mode 100644 utils/boost_idb/boost/units/systems/angle/gradians.hpp create mode 100644 utils/boost_idb/boost/units/systems/angle/revolutions.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/acceleration.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/area.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/base.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/current.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/dimensionless.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/dynamic_viscosity.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/energy.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/force.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/frequency.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/io.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/kinematic_viscosity.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/length.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/mass.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/mass_density.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/momentum.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/power.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/pressure.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/time.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/velocity.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/volume.hpp create mode 100644 utils/boost_idb/boost/units/systems/cgs/wavenumber.hpp create mode 100644 utils/boost_idb/boost/units/systems/detail/constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/absorbed_dose.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/acceleration.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/action.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/activity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/amount.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/angular_acceleration.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/angular_momentum.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/angular_velocity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/area.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/base.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/capacitance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/catalytic_activity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/alpha_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/atomic-nuclear_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/deuteron_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/electromagnetic_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/electron_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/helion_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/muon_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/neutron_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/physico-chemical_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/proton_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/tau_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/triton_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/typedefs.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata/universal_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/codata_constants.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/conductance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/conductivity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/current.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/dimensionless.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/dose_equivalent.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/dynamic_viscosity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/electric_charge.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/electric_potential.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/energy.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/force.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/frequency.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/illuminance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/impedance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/inductance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/io.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/kinematic_viscosity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/length.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/luminous_flux.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/luminous_intensity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/magnetic_field_intensity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/magnetic_flux.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/magnetic_flux_density.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/mass.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/mass_density.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/moment_of_inertia.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/momentum.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/permeability.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/permittivity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/plane_angle.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/power.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/prefixes.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/pressure.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/reluctance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/resistance.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/resistivity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/solid_angle.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/surface_density.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/surface_tension.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/temperature.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/time.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/torque.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/velocity.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/volume.hpp create mode 100644 utils/boost_idb/boost/units/systems/si/wavenumber.hpp create mode 100644 utils/boost_idb/boost/units/systems/temperature/celsius.hpp create mode 100644 utils/boost_idb/boost/units/systems/temperature/fahrenheit.hpp create mode 100644 utils/boost_idb/boost/units/unit.hpp create mode 100644 utils/boost_idb/boost/units/units_fwd.hpp create mode 100644 utils/boost_idb/boost/unordered/detail/allocator_helpers.hpp create mode 100644 utils/boost_idb/boost/unordered/detail/config.hpp create mode 100644 utils/boost_idb/boost/unordered/detail/hash_table.hpp create mode 100644 utils/boost_idb/boost/unordered/detail/hash_table_impl.hpp create mode 100644 utils/boost_idb/boost/unordered/detail/move.hpp create mode 100644 utils/boost_idb/boost/unordered/unordered_map.hpp create mode 100644 utils/boost_idb/boost/unordered/unordered_map_fwd.hpp create mode 100644 utils/boost_idb/boost/unordered/unordered_set.hpp create mode 100644 utils/boost_idb/boost/unordered/unordered_set_fwd.hpp create mode 100644 utils/boost_idb/boost/unordered_map.hpp create mode 100644 utils/boost_idb/boost/unordered_set.hpp delete mode 100644 utils/boost_idb/boost/utility/empty_deleter.hpp delete mode 100644 utils/boost_idb/boost/utility/explicit_operator_bool.hpp delete mode 100644 utils/boost_idb/boost/utility/identity_type.hpp delete mode 100644 utils/boost_idb/boost/utility/string_ref.hpp delete mode 100644 utils/boost_idb/boost/utility/string_ref_fwd.hpp delete mode 100644 utils/boost_idb/boost/uuid/name_generator.hpp delete mode 100644 utils/boost_idb/boost/uuid/nil_generator.hpp delete mode 100644 utils/boost_idb/boost/uuid/random_generator.hpp delete mode 100644 utils/boost_idb/boost/uuid/seed_rng.hpp delete mode 100644 utils/boost_idb/boost/uuid/sha1.hpp delete mode 100644 utils/boost_idb/boost/uuid/string_generator.hpp delete mode 100644 utils/boost_idb/boost/uuid/uuid.hpp delete mode 100644 utils/boost_idb/boost/uuid/uuid_generators.hpp delete mode 100644 utils/boost_idb/boost/uuid/uuid_io.hpp delete mode 100644 utils/boost_idb/boost/uuid/uuid_serialize.hpp create mode 100644 utils/boost_idb/boost/variant.hpp create mode 100644 utils/boost_idb/boost/variant/apply_visitor.hpp create mode 100644 utils/boost_idb/boost/variant/bad_visit.hpp create mode 100644 utils/boost_idb/boost/variant/detail/apply_visitor_binary.hpp create mode 100644 utils/boost_idb/boost/variant/detail/apply_visitor_delayed.hpp create mode 100644 utils/boost_idb/boost/variant/detail/apply_visitor_unary.hpp create mode 100644 utils/boost_idb/boost/variant/detail/backup_holder.hpp create mode 100644 utils/boost_idb/boost/variant/detail/bool_trait_def.hpp create mode 100644 utils/boost_idb/boost/variant/detail/bool_trait_undef.hpp create mode 100644 utils/boost_idb/boost/variant/detail/cast_storage.hpp create mode 100644 utils/boost_idb/boost/variant/detail/config.hpp create mode 100644 utils/boost_idb/boost/variant/detail/enable_recursive.hpp create mode 100644 utils/boost_idb/boost/variant/detail/enable_recursive_fwd.hpp create mode 100644 utils/boost_idb/boost/variant/detail/forced_return.hpp create mode 100644 utils/boost_idb/boost/variant/detail/generic_result_type.hpp create mode 100644 utils/boost_idb/boost/variant/detail/has_nothrow_move.hpp create mode 100644 utils/boost_idb/boost/variant/detail/has_trivial_move.hpp create mode 100644 utils/boost_idb/boost/variant/detail/initializer.hpp create mode 100644 utils/boost_idb/boost/variant/detail/make_variant_list.hpp create mode 100644 utils/boost_idb/boost/variant/detail/move.hpp create mode 100644 utils/boost_idb/boost/variant/detail/over_sequence.hpp create mode 100644 utils/boost_idb/boost/variant/detail/substitute.hpp create mode 100644 utils/boost_idb/boost/variant/detail/substitute_fwd.hpp create mode 100644 utils/boost_idb/boost/variant/detail/variant_io.hpp create mode 100644 utils/boost_idb/boost/variant/detail/visitation_impl.hpp create mode 100644 utils/boost_idb/boost/variant/get.hpp create mode 100644 utils/boost_idb/boost/variant/recursive_variant.hpp create mode 100644 utils/boost_idb/boost/variant/recursive_wrapper.hpp create mode 100644 utils/boost_idb/boost/variant/recursive_wrapper_fwd.hpp create mode 100644 utils/boost_idb/boost/variant/static_visitor.hpp create mode 100644 utils/boost_idb/boost/variant/variant.hpp create mode 100644 utils/boost_idb/boost/variant/variant_fwd.hpp create mode 100644 utils/boost_idb/boost/variant/visitor_ptr.hpp create mode 100644 utils/boost_idb/boost/wave.hpp delete mode 100644 utils/boost_idb/codecvt_error_category.cpp create mode 100644 utils/boost_idb/date_generators.cpp delete mode 100644 utils/boost_idb/future.cpp create mode 100644 utils/boost_idb/greg_weekday.cpp create mode 100644 utils/boost_idb/gregorian_types.cpp delete mode 100644 utils/boost_idb/internals.hpp create mode 100644 utils/boost_idb/libs/detail/utf8_codecvt_facet.cpp delete mode 100644 utils/boost_idb/local_free_on_destruction.hpp delete mode 100644 utils/boost_idb/once_atomic.cpp delete mode 100644 utils/boost_idb/path_traits.cpp create mode 100644 utils/boost_idb/posix_time_types.cpp delete mode 100644 utils/boost_idb/tss_null.cpp delete mode 100644 utils/boost_idb/unique_path.cpp rename utils/boost_idb/{boost/filesystem/detail => }/utf8_codecvt_facet.hpp (100%) delete mode 100644 utils/boost_idb/windows_file_codecvt.cpp delete mode 100644 utils/cacheutils/libcacheutils.vcxproj delete mode 100644 utils/cacheutils/libcacheutils.vcxproj.filters delete mode 100644 utils/common/MonitorProcMem.cpp delete mode 100644 utils/common/MonitorProcMem.h delete mode 100644 utils/common/atomicops.h delete mode 100644 utils/common/branchpred.h delete mode 100644 utils/common/cgroupconfigurator.cpp delete mode 100644 utils/common/cgroupconfigurator.h delete mode 100644 utils/common/libcommon.vcxproj delete mode 100644 utils/common/libcommon.vcxproj.filters delete mode 100644 utils/common/nullvaluemanip.cpp delete mode 100644 utils/common/nullvaluemanip.h delete mode 100644 utils/compress/libcompress-ent.vcxproj delete mode 100644 utils/compress/libcompress-ent.vcxproj.filters delete mode 100644 utils/compress/snappy-stubs-internal.cpp delete mode 100644 utils/configcpp/libconfigcpp.rc delete mode 100644 utils/configcpp/libconfigcpp.vcxproj delete mode 100644 utils/configcpp/libconfigcpp.vcxproj.filters delete mode 100644 utils/configcpp/md5/Makefile.am delete mode 100644 utils/configcpp/md5/md32_common.h delete mode 100644 utils/configcpp/md5/md5.h delete mode 100644 utils/configcpp/md5/md5_dgst.c delete mode 100644 utils/configcpp/md5/md5_locl.h delete mode 100644 utils/configcpp/md5/md5_one.c delete mode 100644 utils/configcpp/md5/mem_clr.c delete mode 100644 utils/configcpp/resource.h delete mode 100644 utils/configcpp/versionnumber.h delete mode 100644 utils/dataconvert/libdataconvert.vcxproj delete mode 100644 utils/dataconvert/libdataconvert.vcxproj.filters delete mode 100644 utils/ddlcleanup/libddlcleanup.vcxproj delete mode 100644 utils/ddlcleanup/libddlcleanup.vcxproj.filters delete mode 100644 utils/funcexp/func_idbpartition.cpp delete mode 100644 utils/funcexp/libfuncexp.vcxproj delete mode 100644 utils/funcexp/libfuncexp.vcxproj.filters delete mode 100644 utils/funcexp/timeextract.h delete mode 100644 utils/funcexp/utf8.h delete mode 100644 utils/funcexp/utf8/checked.h delete mode 100644 utils/funcexp/utf8/core.h delete mode 100644 utils/funcexp/utf8/unchecked.h delete mode 100644 utils/idbdatafile/BufferedFile.cpp delete mode 100644 utils/idbdatafile/BufferedFile.h delete mode 100644 utils/idbdatafile/BufferedFileFactory.h delete mode 100644 utils/idbdatafile/FileFactoryBase.h delete mode 100644 utils/idbdatafile/IDBDataFile.cpp delete mode 100644 utils/idbdatafile/IDBDataFile.h delete mode 100644 utils/idbdatafile/IDBFactory.cpp delete mode 100644 utils/idbdatafile/IDBFactory.h delete mode 100644 utils/idbdatafile/IDBFileSystem.cpp delete mode 100644 utils/idbdatafile/IDBFileSystem.h delete mode 100644 utils/idbdatafile/IDBLogger.cpp delete mode 100644 utils/idbdatafile/IDBLogger.h delete mode 100644 utils/idbdatafile/IDBPolicy.cpp delete mode 100644 utils/idbdatafile/IDBPolicy.h delete mode 100644 utils/idbdatafile/Makefile.am delete mode 100644 utils/idbdatafile/Makefile.in delete mode 100644 utils/idbdatafile/PosixFileSystem.cpp delete mode 100644 utils/idbdatafile/PosixFileSystem.h delete mode 100644 utils/idbdatafile/UnbufferedFile.cpp delete mode 100644 utils/idbdatafile/UnbufferedFile.h delete mode 100644 utils/idbdatafile/UnbufferedFileFactory.h delete mode 100644 utils/idbdatafile/idbdatafile.vcxproj delete mode 100644 utils/idbdatafile/idbdatafile.vcxproj.filters delete mode 100644 utils/idbdatafile/largefile64.h delete mode 100644 utils/idbdatafile/tdriver.cpp delete mode 100644 utils/idbdatafile/tdriver1.cpp delete mode 100644 utils/idbdatafile/utility.h delete mode 100644 utils/idbhdfs/FOSS-EXCEPTION.txt delete mode 100644 utils/idbhdfs/Makefile.am delete mode 100644 utils/idbhdfs/Makefile.in delete mode 100644 utils/idbhdfs/hdfs-12/Makefile.am delete mode 100644 utils/idbhdfs/hdfs-12/Makefile.in delete mode 100644 utils/idbhdfs/hdfs-12/hdfs.h delete mode 100644 utils/idbhdfs/hdfs-12/libhdfs.so delete mode 100755 utils/idbhdfs/hdfs-12/setenv-hdfs-12 delete mode 100644 utils/idbhdfs/hdfs-20/Makefile.am delete mode 100644 utils/idbhdfs/hdfs-20/Makefile.in delete mode 100644 utils/idbhdfs/hdfs-20/hdfs.h delete mode 100755 utils/idbhdfs/hdfs-20/libhdfs.so delete mode 100755 utils/idbhdfs/hdfs-20/setenv-hdfs-20 delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFile.cpp delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFile.h delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFileFactory.h delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFileSystem.cpp delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFileSystem.h delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFsCache.cpp delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsFsCache.h delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsPlugin.cpp delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsRdwrFileBuffer.cpp delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsRdwrFileBuffer.h delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsRdwrMemBuffer.cpp delete mode 100644 utils/idbhdfs/hdfs-shared/HdfsRdwrMemBuffer.h delete mode 100644 utils/jemalloc/Makefile.in delete mode 100644 utils/jemalloc/jemalloc-3.3.0.tar.gz delete mode 100644 utils/joiner/btree.h delete mode 100644 utils/joiner/btree_container.h delete mode 100644 utils/joiner/btree_map.h delete mode 100644 utils/joiner/btree_set.h delete mode 100644 utils/joiner/joinpartition.cpp delete mode 100644 utils/joiner/joinpartition.h delete mode 100644 utils/joiner/libjoiner.vcxproj delete mode 100644 utils/joiner/libjoiner.vcxproj.filters delete mode 100644 utils/joiner/type_traits_hm delete mode 100644 utils/loggingcpp/libloggingcpp.vcxproj delete mode 100644 utils/loggingcpp/libloggingcpp.vcxproj.filters create mode 100644 utils/messageqcpp/clientsocket.h delete mode 100644 utils/messageqcpp/compressed_iss.cpp delete mode 100644 utils/messageqcpp/compressed_iss.h delete mode 100644 utils/messageqcpp/libmessageqcpp.vcxproj delete mode 100644 utils/messageqcpp/libmessageqcpp.vcxproj.filters create mode 100644 utils/multicast/Makefile.in delete mode 100644 utils/multicast/libmulticast.vcxproj delete mode 100644 utils/multicast/libmulticast.vcxproj.filters delete mode 100644 utils/mysqlcl_idb/libmysqlcl_idb.vcxproj delete mode 100644 utils/mysqlcl_idb/libmysqlcl_idb.vcxproj.filters delete mode 100644 utils/mysqlcl_idb/tdriver-works.cpp delete mode 100644 utils/mysqlcl_idb/tdriver.cpp delete mode 100644 utils/mysqlcl_idb/tdriver1.cpp delete mode 100644 utils/net-snmp/Makefile.in delete mode 100644 utils/querystats/libquerystats.vcxproj delete mode 100644 utils/querystats/libquerystats.vcxproj.filters delete mode 100644 utils/querytele/Makefile.am delete mode 100644 utils/querytele/Makefile.in delete mode 100644 utils/querytele/QueryTeleService.cpp delete mode 100644 utils/querytele/QueryTeleService.h delete mode 100644 utils/querytele/libquerytele.vcxproj delete mode 100644 utils/querytele/libquerytele.vcxproj.filters delete mode 100644 utils/querytele/querystepparms.h delete mode 100644 utils/querytele/querytele.cpp delete mode 100644 utils/querytele/querytele.h delete mode 100644 utils/querytele/querytele.thrift delete mode 100644 utils/querytele/querytele_constants.cpp delete mode 100644 utils/querytele/querytele_constants.h delete mode 100644 utils/querytele/querytele_types.cpp delete mode 100644 utils/querytele/querytele_types.h delete mode 100644 utils/querytele/queryteleclient.cpp delete mode 100644 utils/querytele/queryteleclient.h delete mode 100644 utils/querytele/queryteleprotoimpl.cpp delete mode 100644 utils/querytele/queryteleprotoimpl.h delete mode 100644 utils/querytele/queryteleserverparms.h delete mode 100644 utils/querytele/serverdriver.cpp delete mode 100644 utils/querytele/tdriver.cpp delete mode 100644 utils/querytele/telestats.h delete mode 100644 utils/rowgroup/librowgroup.vcxproj delete mode 100644 utils/rowgroup/librowgroup.vcxproj.filters delete mode 100644 utils/rwlock/librwlock.vcxproj delete mode 100644 utils/rwlock/librwlock.vcxproj.filters delete mode 100644 utils/startup/libidbboot.vcxproj delete mode 100644 utils/startup/libidbboot.vcxproj.filters delete mode 100644 utils/threadpool/libthreadpool.vcxproj delete mode 100644 utils/threadpool/libthreadpool.vcxproj.filters delete mode 100644 utils/thrift/Makefile.am delete mode 100644 utils/thrift/Makefile.in delete mode 100644 utils/thrift/README delete mode 100644 utils/thrift/libthrift.vcxproj delete mode 100644 utils/thrift/libthrift.vcxproj.filters delete mode 100644 utils/thrift/thrift/TApplicationException.cpp delete mode 100644 utils/thrift/thrift/TApplicationException.h delete mode 100644 utils/thrift/thrift/TDispatchProcessor.h delete mode 100644 utils/thrift/thrift/TLogging.h delete mode 100644 utils/thrift/thrift/TProcessor.h delete mode 100644 utils/thrift/thrift/TReflectionLocal.h delete mode 100644 utils/thrift/thrift/Thrift.cpp delete mode 100644 utils/thrift/thrift/Thrift.h delete mode 100644 utils/thrift/thrift/async/TAsyncBufferProcessor.h delete mode 100644 utils/thrift/thrift/async/TAsyncChannel.h delete mode 100644 utils/thrift/thrift/async/TAsyncDispatchProcessor.h delete mode 100644 utils/thrift/thrift/async/TAsyncProcessor.h delete mode 100644 utils/thrift/thrift/async/TAsyncProtocolProcessor.h delete mode 100644 utils/thrift/thrift/async/TEvhttpClientChannel.h delete mode 100644 utils/thrift/thrift/async/TEvhttpServer.h delete mode 100644 utils/thrift/thrift/concurrency/BoostThreadFactory.h delete mode 100644 utils/thrift/thrift/concurrency/Exception.h delete mode 100644 utils/thrift/thrift/concurrency/FunctionRunner.h delete mode 100644 utils/thrift/thrift/concurrency/Monitor.h delete mode 100644 utils/thrift/thrift/concurrency/Mutex.h delete mode 100644 utils/thrift/thrift/concurrency/PlatformThreadFactory.h delete mode 100644 utils/thrift/thrift/concurrency/PosixThreadFactory.h delete mode 100644 utils/thrift/thrift/concurrency/StdThreadFactory.h delete mode 100644 utils/thrift/thrift/concurrency/Thread.h delete mode 100644 utils/thrift/thrift/concurrency/ThreadManager.h delete mode 100644 utils/thrift/thrift/concurrency/TimerManager.h delete mode 100644 utils/thrift/thrift/concurrency/Util.h delete mode 100644 utils/thrift/thrift/config.h delete mode 100644 utils/thrift/thrift/cxxfunctional.h delete mode 100644 utils/thrift/thrift/processor/PeekProcessor.h delete mode 100644 utils/thrift/thrift/processor/StatsProcessor.h delete mode 100644 utils/thrift/thrift/processor/TMultiplexedProcessor.h delete mode 100644 utils/thrift/thrift/protocol/TBase64Utils.h delete mode 100644 utils/thrift/thrift/protocol/TBinaryProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TBinaryProtocol.tcc delete mode 100644 utils/thrift/thrift/protocol/TCompactProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TCompactProtocol.tcc delete mode 100644 utils/thrift/thrift/protocol/TDebugProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TDenseProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TJSONProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TMultiplexedProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TProtocol.h delete mode 100644 utils/thrift/thrift/protocol/TProtocolDecorator.h delete mode 100644 utils/thrift/thrift/protocol/TProtocolException.h delete mode 100644 utils/thrift/thrift/protocol/TProtocolTap.h delete mode 100644 utils/thrift/thrift/protocol/TVirtualProtocol.h delete mode 100644 utils/thrift/thrift/qt/TQIODeviceTransport.h delete mode 100644 utils/thrift/thrift/qt/TQTcpServer.h delete mode 100644 utils/thrift/thrift/server/TNonblockingServer.h delete mode 100644 utils/thrift/thrift/server/TServer.h delete mode 100644 utils/thrift/thrift/server/TSimpleServer.cpp delete mode 100644 utils/thrift/thrift/server/TSimpleServer.h delete mode 100644 utils/thrift/thrift/server/TThreadPoolServer.h delete mode 100644 utils/thrift/thrift/server/TThreadedServer.h delete mode 100644 utils/thrift/thrift/thrift-config.h delete mode 100644 utils/thrift/thrift/transport/PlatformSocket.h delete mode 100644 utils/thrift/thrift/transport/TBufferTransports.cpp delete mode 100644 utils/thrift/thrift/transport/TBufferTransports.h delete mode 100644 utils/thrift/thrift/transport/TFDTransport.h delete mode 100644 utils/thrift/thrift/transport/TFileTransport.h delete mode 100644 utils/thrift/thrift/transport/THttpClient.h delete mode 100644 utils/thrift/thrift/transport/THttpServer.h delete mode 100644 utils/thrift/thrift/transport/THttpTransport.h delete mode 100644 utils/thrift/thrift/transport/TPipe.h delete mode 100644 utils/thrift/thrift/transport/TPipeServer.h delete mode 100644 utils/thrift/thrift/transport/TSSLServerSocket.h delete mode 100644 utils/thrift/thrift/transport/TSSLSocket.h delete mode 100644 utils/thrift/thrift/transport/TServerSocket.cpp delete mode 100644 utils/thrift/thrift/transport/TServerSocket.h delete mode 100644 utils/thrift/thrift/transport/TServerTransport.h delete mode 100644 utils/thrift/thrift/transport/TShortReadTransport.h delete mode 100644 utils/thrift/thrift/transport/TSimpleFileTransport.h delete mode 100644 utils/thrift/thrift/transport/TSocket.cpp delete mode 100644 utils/thrift/thrift/transport/TSocket.h delete mode 100644 utils/thrift/thrift/transport/TSocketPool.h delete mode 100644 utils/thrift/thrift/transport/TTransport.h delete mode 100644 utils/thrift/thrift/transport/TTransportException.h delete mode 100644 utils/thrift/thrift/transport/TTransportUtils.h delete mode 100644 utils/thrift/thrift/transport/TVirtualTransport.h delete mode 100644 utils/thrift/thrift/transport/TZlibTransport.h delete mode 100644 utils/thrift/thrift/windows/GetTimeOfDay.cpp delete mode 100644 utils/thrift/thrift/windows/GetTimeOfDay.h delete mode 100644 utils/thrift/thrift/windows/Operators.h delete mode 100644 utils/thrift/thrift/windows/SocketPair.h delete mode 100644 utils/thrift/thrift/windows/StdAfx.h delete mode 100644 utils/thrift/thrift/windows/TWinsockSingleton.cpp delete mode 100644 utils/thrift/thrift/windows/TWinsockSingleton.h delete mode 100644 utils/thrift/thrift/windows/TargetVersion.h delete mode 100644 utils/thrift/thrift/windows/WinFcntl.cpp delete mode 100644 utils/thrift/thrift/windows/WinFcntl.h delete mode 100644 utils/thrift/thrift/windows/config.h delete mode 100644 utils/thrift/thrift/windows/force_inc.h delete mode 100644 utils/udfsdk/Makefile.in create mode 100644 utils/udfsdk/Makefile.sdk delete mode 100644 utils/udfsdk/libudf_mysql.rc delete mode 100644 utils/udfsdk/libudf_mysql.vcxproj delete mode 100644 utils/udfsdk/libudf_mysql.vcxproj.filters delete mode 100644 utils/udfsdk/libudfsdk.rc delete mode 100644 utils/udfsdk/libudfsdk.vcxproj delete mode 100644 utils/udfsdk/libudfsdk.vcxproj.filters create mode 100755 utils/udfsdk/make_sdk.sh delete mode 100644 utils/udfsdk/resource.h delete mode 100644 utils/udfsdk/udfinfinidb.cpp delete mode 100644 utils/udfsdk/udfmysql.cpp create mode 100644 utils/udfsdk/udfsdk.cpp delete mode 100644 utils/windowfunction/Makefile.am delete mode 100644 utils/windowfunction/Makefile.in delete mode 100644 utils/windowfunction/framebound.cpp delete mode 100644 utils/windowfunction/framebound.h delete mode 100644 utils/windowfunction/frameboundrange.cpp delete mode 100644 utils/windowfunction/frameboundrange.h delete mode 100644 utils/windowfunction/frameboundrow.cpp delete mode 100644 utils/windowfunction/frameboundrow.h delete mode 100644 utils/windowfunction/idborderby.cpp delete mode 100644 utils/windowfunction/idborderby.h delete mode 100644 utils/windowfunction/libwindowfunction.vcxproj delete mode 100644 utils/windowfunction/libwindowfunction.vcxproj.filters delete mode 100644 utils/windowfunction/wf_count.cpp delete mode 100644 utils/windowfunction/wf_count.h delete mode 100644 utils/windowfunction/wf_lead_lag.cpp delete mode 100644 utils/windowfunction/wf_lead_lag.h delete mode 100644 utils/windowfunction/wf_min_max.cpp delete mode 100644 utils/windowfunction/wf_min_max.h delete mode 100644 utils/windowfunction/wf_nth_value.cpp delete mode 100644 utils/windowfunction/wf_nth_value.h delete mode 100644 utils/windowfunction/wf_ntile.cpp delete mode 100644 utils/windowfunction/wf_ntile.h delete mode 100644 utils/windowfunction/wf_percentile.cpp delete mode 100644 utils/windowfunction/wf_percentile.h delete mode 100644 utils/windowfunction/wf_ranking.cpp delete mode 100644 utils/windowfunction/wf_ranking.h delete mode 100644 utils/windowfunction/wf_row_number.cpp delete mode 100644 utils/windowfunction/wf_row_number.h delete mode 100644 utils/windowfunction/wf_stats.cpp delete mode 100644 utils/windowfunction/wf_stats.h delete mode 100644 utils/windowfunction/wf_sum_avg.cpp delete mode 100644 utils/windowfunction/wf_sum_avg.h delete mode 100644 utils/windowfunction/windowframe.cpp delete mode 100644 utils/windowfunction/windowframe.h delete mode 100644 utils/windowfunction/windowfunction.cpp delete mode 100644 utils/windowfunction/windowfunction.h delete mode 100644 utils/windowfunction/windowfunctiontype.cpp delete mode 100644 utils/windowfunction/windowfunctiontype.h delete mode 100644 utils/winport/Makefile.am delete mode 100644 utils/winport/Makefile.in delete mode 100644 utils/winport/WinSyslog.cpp delete mode 100644 utils/winport/WinSyslog.h delete mode 100644 utils/winport/bootstrap.vcxproj delete mode 100644 utils/winport/bootstrap.vcxproj.filters create mode 100644 utils/winport/idb_32_community.nsi create mode 100644 utils/winport/idb_64_community.nsi delete mode 100644 utils/winport/idb_64_enterprise-Debug.nsi delete mode 100644 utils/winport/idb_64_standard.nsi delete mode 100644 utils/winport/inttypes.h delete mode 100644 utils/winport/libwinport.vcxproj delete mode 100644 utils/winport/libwinport.vcxproj.filters delete mode 100644 utils/winport/resource.h create mode 100644 utils/winport/stdint.h delete mode 100644 utils/winport/sysinfo.cpp delete mode 100644 utils/winport/sysinfo.h delete mode 100644 utils/winport/winfinidb.rc delete mode 100644 utils/winport/winfinidb.vcxproj delete mode 100644 utils/winport/winfinidb.vcxproj.filters delete mode 100644 utils/winport/winport.h delete mode 100644 versioning/BRM/controllernode.rc delete mode 100644 versioning/BRM/controllernode.vcxproj delete mode 100644 versioning/BRM/controllernode.vcxproj.filters delete mode 100644 versioning/BRM/dbrmctl.vcxproj delete mode 100644 versioning/BRM/dbrmctl.vcxproj.filters create mode 100644 versioning/BRM/ipcs-pat.c delete mode 100644 versioning/BRM/libbrm.rc delete mode 100644 versioning/BRM/libbrm.vcxproj delete mode 100644 versioning/BRM/libbrm.vcxproj.filters delete mode 100644 versioning/BRM/load_brm.vcxproj delete mode 100644 versioning/BRM/load_brm.vcxproj.filters delete mode 100644 versioning/BRM/lock_grabber.cpp delete mode 100644 versioning/BRM/lock_state.cpp create mode 100644 versioning/BRM/print_journal.cpp delete mode 100644 versioning/BRM/reset_locks.vcxproj delete mode 100644 versioning/BRM/reset_locks.vcxproj.filters delete mode 100644 versioning/BRM/resource.h delete mode 100644 versioning/BRM/save_brm.vcxproj delete mode 100644 versioning/BRM/save_brm.vcxproj.filters delete mode 100644 versioning/BRM/workernode.rc delete mode 100644 versioning/BRM/workernode.vcxproj delete mode 100644 versioning/BRM/workernode.vcxproj.filters delete mode 100644 writeengine/bulk/cpimport.rc delete mode 100644 writeengine/bulk/cpimport.vcxproj delete mode 100644 writeengine/bulk/cpimport.vcxproj.filters delete mode 100644 writeengine/bulk/resource.h delete mode 100644 writeengine/client/libweclient.vcxproj delete mode 100644 writeengine/client/libweclient.vcxproj.filters create mode 100644 writeengine/cpimport/Makefile.am create mode 100644 writeengine/cpimport/Makefile.in create mode 100644 writeengine/cpimport/main.cpp delete mode 100644 writeengine/libwriteengine.rc delete mode 100644 writeengine/libwriteengine.vcxproj delete mode 100644 writeengine/libwriteengine.vcxproj.filters delete mode 100644 writeengine/resource.h delete mode 100644 writeengine/server/WriteEngineServer.rc delete mode 100644 writeengine/server/WriteEngineServer.vcxproj delete mode 100644 writeengine/server/WriteEngineServer.vcxproj.filters delete mode 100644 writeengine/server/resource.h delete mode 100644 writeengine/server/we_getfilesizes.cpp delete mode 100644 writeengine/server/we_getfilesizes.h delete mode 100644 writeengine/shared/we_bulkrollbackfilecompressedhdfs.cpp delete mode 100644 writeengine/shared/we_bulkrollbackfilecompressedhdfs.h delete mode 100644 writeengine/shared/we_confirmhdfsdbfile.cpp delete mode 100644 writeengine/shared/we_confirmhdfsdbfile.h delete mode 100644 writeengine/splitter/resource.h delete mode 100644 writeengine/splitter/splitter.rc delete mode 100644 writeengine/splitter/splitter.vcxproj delete mode 100644 writeengine/splitter/splitter.vcxproj.filters diff --git a/ChangeLog b/ChangeLog index c5d2c361..e69de29b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,445 +0,0 @@ -/*********************************************************************** -* -* Copyright (C) 2013 InfiniDB Corp -* All Rights Reserved -* -***********************************************************************/ - -July 7, 2014 -Version 4.6 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description -1505 Implement temp file based LargeHashJoin for tuple joins -3683 Allow function(column) = function(column) join -5308 Improve performance of load data infile and insert into select from - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Short Description - -3858 While "load data infile" is in progress, PrimProc fails to read compressed chunk and retries for more than a minute -4295 CPimport Mode 2: Should check for input files on all PMs before starting loading -4737 Distributed cpimport does not support a list of import files to a single table -4789 InfiniDB came up normally after encountering an critical sessionManager::rollback() error -5134 Source package: After compilation and installation, InfiniDB reported lib not found error during startup -5140 second and subsequent load data infiles have 30 second delay with auto increment -5523 Mysql is resetting when running a query on a information_schema.table and an InfiniDB table. -5727 Improve logging around controllernode start up -5756 After a failed addModule command movePmDbrootConfig did not fail -5758 when amazon UM modules are removed, their associated EBS storages are not removed -5761 Support additional versions of Java for Hadoop installations -5762 Need a method to handle MySQL port conflict on a multi-server install -5773 Startsystem is failing when shutdown has not completed. -5847 IDB-2021 on query using multiple pseudo column functions against same column and aggregation -5848 No CP elimination from idbPartition(col) in the where clause -5865 ERROR 138 (HY000): IDB-1000: 'orders' and 'sub-query' are not joined on a query with an or condition and not in condition -5891 getsystemdisk reporting minus value -5894 Performance issue when inserting a value in an autoincrement column -5930 Not in group by error on query grouping by idbPm and idbDbRoot functions -5931 current builds do not support a non-root / hdfs install -5946 load data infile error: ERROR 122 (HY000): CAL0006: Error verifying compression headers -5947 calonlinealter always creates non compressed columns -5950 getModuleHostNames command on AWS returned a segmentation fault error -5954 calpontSupport for Windows does not recognize options -5958 Query with a subselect is getting an assertion error -5963 configxml.sh fails to set CrossEngineSupport Password from the default setting -5978 crash with prepared statements -5987 hadoop test failed on install, hadoop not install where setenv was looking and not a parcel -5992 Bulk load fails on long schema name, long table name, and long column name combination. -5993 IDB-2016: Non supported item 'c2' on the GROUP BY list. -5996 Table reporting errors after a LDI -5997 standard mysql and infinidb mysql incorrectly starting/stopping each other -6000 New MySQL port test is insufficient -6001 cpimport performance improvement for tables with many dictionary columns -6005 addModule command failed to add an UM -6010 InfiniDB mysql replication doesn't work when UM mysql Port address is not 3306 -6013 HW 2.1 testing with 4.5.1-2 - different JAVA_HOME's are setup -6017 Queries with "where date(col) in (select dtCol)" not finding rows -6026 Prevent potential infinite loops reading input in postConfigure -6027 post-install message for a non-root hadoop install is incorrect.. -6029 when autocommit off, batchinsert set hwm of dictionary store file to 0 -6041 When loading 4160825419 rows cpimport reported as -134141877 rows -6044 'union all' query generates tupleconstantstep.cpp@731: assertion 'fRowConst.getSize() == fRowOut.getSize()' failed -6061 window function returned incorrect results -6066 query with alias is returning IDB-3009: Unknown column error. -6073 setenv scripts issues on Ubuntu - -/*********************************************************************** -* -* Copyright (C) 2013 InfiniDB Corp -* All Rights Reserved -* -***********************************************************************/ - -June 23, 2014 -Version 4.5.1 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description - - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Short Description - -4438 Implement -j option with simple usage to create a specific job log file -4638 Update from 2.2.x to 3.0 is not supported with multiple dbroots -5501 update with subquery using a view with an order by receives an error when using infinidb tables -5523 Mysql is resetting when running a query on a information_schema.table and an InfiniDB table. -5739 install-infinidb.sh script should be removed -5756 After a failed addModule command movePmDbrootConfig did not fail -5758 when amazon UM modules are removed, their associated EBS storages aren't -5761 Add support for additional Java versions with installation on HDFS -5762 Need a method to handle MySQL port conflict on a multi-server install -5785 While running a complex query a Control C aborts the query but may not clear ExeMgr memory -5804 mysql reset occurring following an install when /dev/shm permissions were not set correctly -5838 no prompt postConfigure does not work when mysql password is required. -5873 install failure - No Calpont.xml: failed to be written in config api -5881 with replication, delete with idbpm(colname) in where clause failed with an error. -5884 query returns incorrect results when using an on clause filter involving a table not directly involved in the outer join -5887 " Incorrect results of Is Null " -5891 getsystemdisk returns minus value -5893 Pseudo column functions return an "BPS not created 1" error when used as the 2nd expression in a where clause -5896 getConfig has no linefeed after returning value -5900 PrimProc crashes if NumBlocksPct has '%' in value -5903 startsystem reported successful system start when mysqld aborted -5904 Changing dbroot-to-pm assignment during postConfigure causes double-mounted storage devices -5906 Diagnostic messages logged in the err.log file during new installation -5907 After installation, a rsync error was report in UM1 but the stack seems to be in working state -5908 4.5 non-root install problems -5909 On a stack with replication and local query enabled, rerunning postConfigure caused the two features to become disabled -5910 Object names > 64 cause replication errors -5913 Renaming an autoincrement column is resetting the next value -5915 On hadoop system, SYSTABLE's update was not flushed to disk when implementing split dbroots for systables -5916 query using a view on a view causes ERROR 2013 (HY000): Lost connection to MySQL server during query -5917 non-root gluster / hadoop installs fail - storage types not being offered in postConfigure -5919 Warning of future deprecated "default-character-set" setting on Windows install -5923 ERROR 122 (HY000): Lost connection to DDLProc -5925 Add the two new options to postConfigure -h -5932 Queries with limits sometimes set the extent map min / max incorrectly -5943 mysql daemon fails to start on pm2 of a non-root install local-query configured system -5944 Incorrect schema name in error message -5946 load data infile error: ERROR 122 (HY000): CAL0006: Error verifying compression headers -5947 calonlinealter always creates non compressed columns -5956 Error Code: 138 IDB-2015: Sorting length exceeded when using a view -5958 Query with a subselect is getting an assertion error -5973 large system (1um-30pm) failing to start, ProcMgr incorrect stopping with ProcMons not active -5981 postconfigure upgrade when enabling local-query fails -5983 all the hdfs settings are not in the .bashrc file after install -5993 IDB-2016: Non supported item 'c2' on the GROUP BY list. -5996 Table reporting errors after a LDI -6001 cpimport performance improvement for tables with many dictionary columns -6029 with autocommit off, batchinsert set hwm of dictionary store file to 0 - -/*********************************************************************** -* -* Copyright (C) 2013 InfiniDB Corp -* All Rights Reserved -* -***********************************************************************/ - -March 31, 2014 -Version 4.5 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description - -4021 Selectable pseudo columns for row/PM identification -4578 Upgrade to latest MySQL 5.1.73 -5572 Optimizations to cpimport with Hadoop -5634 Optimization: Project only the necessary columns from views with union all or union -5635 Optimization: Use partition elimination for from clause sub queries and views with union / union all -5657 Local PM query interface -5660 Local PM Sqoop Import -5740 Enable use of MySQL Replication on UMs with InfiniDB -5799 Enhancement request to not provide information when performing a non-hadoop install on a system with hadoop - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Short Description - -5443 An error is not issued when changing a column's datatype -5444 alter table will not allow an autoincrement column to be renamed. -5611 Windows MySQL doesn't build out of github -5640 Hadoop: dumpcol and eval returned a java error with stack trace when non-existing file is supplied -5647 cpimport -i option doesn't work with modes 1 and 2 -5745 hadoop: unknown bulk rollback error on 4PM stack -5748 startsystem failure when user-module is disabled -5805 Query with avg windowing function returning the average at the wrong decimal scale -5806 cpimport loads data incorrectly on a multi-server stack when the table has a mix of compressed and non-compressed columns -5807 concat producing an incorrect count when using a view -5808 colxml error reported on Windows system. -5811 selecting from a view which has a cross engine join produces an ERROR 122 (HY000): fatal error executing query in crossengine client lib(17)(17) -5817 addModule / altersystem-enablemodule fails on amazon with InfiniDB 4.x -5819 Calpont.xml and Calpont.xml.singleserver do not have the same parameters. -5820 Inconsistent rounding on percentile_cont windowing function -5861 post-install reported to have run the setenv-hdfs-12 script on a CDH 4 install -5864 Include calpontSupport in the standard edition -5874 Reset of ProcessMonitor on PM2 on a combo system left mysqld as man_offline - - - - -/*********************************************************************** -* -* Copyright (C) 2014 InfiniDB Corp -* All Rights Reserved -* -***********************************************************************/ - -April 14, 2014 -Version 4.0.3 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description - - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Short Description - -4638 Update from 2.2.x to 3.0 is not supported with multiple dbroots -5610 The MySQL front end no longer outputs a descriptive messages when version buffer is full -5748 startsystem failure when user-module is disabled -5778 Distributed import error message for auto increment overflow is not friendly -5793 Remove O/S version checking in glusterconf -5801 Queries with string comparison in where clause occasionally causes a PM to hang -5805 Query with avg windowing function returning the average at the wrong decimal scale -5806 cpimport loads data incorrectly on a multi-server stack when the table has a mix of compressed and non-compressed columns -5807 concat producing an incorrect count when using a view -5808 colxml error reported on Windows system. -5810 update doesn't flush string file with table oid 3000 -5811 selecting from a view which has a cross engine join produces an ERROR 122 (HY000): fatal error executing query in crossengine client lib(17)(17) -5817 addModule / altersystem-enablemodule fails on amazon 4.x -5820 Inconsistent rounding on percentile_cont windowing function -5821 PM join with F & E in-join filter + a UM join will crash ExeMgr -5823 System hung when running concurrent queries with autocommit off -5838 no prompt postConfigure does not work when mysql password is required. -5874 Reset of ProcessMonitor on PM2 on a combo system left mysqld as man_offline -5877 After loading 1 extent worth of data into a table, select count(*) failed. -5882 cleartablelock fails on a multi server system. -5884 query returns incorrect results when using an on clause filter involving a table not directly involved in the outer join -5887 " Incorrect results of Is Null " -5870 select following delete statement is encountering a rid error. -5896 getConfig has no linefeed after returning value -5900 PrimProc crashes if NumBlocksPct has '%' in value -5904 Changing dbroot-to-pm assignment during postConfigure causes double-mounted storage devices -5915 On hadoop system, SYSTABLE's update was not flushed to disk when implementing split dbroots for systables -5916 query using a view on a view causes ERROR 2013 (HY000): Lost connection to MySQL server during query -5917 non-root gluster / hadoop installs fail - storage types not being offered in postConfigure -5932 Queries with limits sometimes set the extent map min / max incorrectly - - - - -/*********************************************************************** -* -* Copyright (C) 2013 Calpont Corp -* All Rights Reserved -* -***********************************************************************/ - -February 10, 2014 -Version 4.0.2 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description - -5760 Hadoop with Cloudera parcel-based install -5769 Optimization to not preallocate database column files in HDFS -5732 Add ability to report compressed bytes used rather than file size on disk - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Short Description - -2437 When expression results in data overflow, no error or warning was returned -4930 no prompt install on AWS had an error when it did not use the volume information. -5363 HAVING statement regression on 4.0 with COUNT DISTINCT -5383 NOT NULL constraint cpimport issues -5604 cpimport jobs hanging on HDFS installs -5617 Invalid Package error reported during the running of calpontSupport - incorrect error message -5636 query gives ERROR 1054 (42S22): Unknown column -5678 ERROR 138 (HY000): 'date_last_update_tk' isn't in tuple. -5682 HDFS updating a row that was inserted sometimes does not update the row -5687 TIMESTAMPADD(SECOND,2147483647, returns incorrect information. -5696 insert statement not providing a warning for truncated data -5697 IDB produces different results for equivalent calculations -5705 hadoop: HdfsFileSystem::listDirectory() not returning all files in directory; bulk rollback not deleting db files -5712 left('unsigned int',6) provides incorrect result -5715 incorrect calculation provided in result set -5716 union sql statement not displaying correct result -5717 create table with invalid Infinidb option does not provide an error or warning -5718 cross engine join results in ERROR 122 (HY000): InetStreamSocket::readToMagic: Remote is closed -5721 amazon upgrade 4.0.0 to 4.0.1 issues -5722 cpimport failing on table to PM17; not handling a boundary case where 2 DBRoots have partial HWM extents -5726 amazon 3.6.3 to 4.0.1 upgrade issue - the ebs storage data not given in postConfigure -5728 update Server cpu-info and disk scheduler in calpontSupport output -5733 databaseSizeReport doesn't report the size of dictionary string files in calpontsys tables -5735 Launching simultaneous databaseSizeReports at virtually the same time can sometimes yield incorrect results -5749 addModule for failed on Amazon system - user_installer password error -5750 dbrm halt/resumes need to be put around the load of dbrm files -5752 ERROR 138 (HY000) at line 2: Sub-query failed: error code 2003 error for query that exceeded TotalUmMemory -5753 When PrimProc restarts, DML statement didn't reset the connections to PrimProc in connector -5757 addModule for UM failed on Amazon system - remote_command error -5759 Must use -p option for hadoop fs -mkdir when creating /usr/local/Calpont -5764 select count(*) from a complex view is returning an incorrect answer. -5765 truncate statement does not show schema in the debug.log -5767 'create table' creates table in front end when spaces are in the table name. -5775 Windows does not log when PrimProc goes down or restarts -5777 LAG function returns invalid answer on a float column - - - - -/*********************************************************************** -* -* Copyright (C) 2013 Calpont Corp -* All Rights Reserved -* -***********************************************************************/ - -December 2, 2013 -Version 4.0.1 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description - -5619 Support VPC environment with AMI - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Short Description - -4996 removeDbroot should be disabled when GlusterFS is configured -5268 Incorrect date_format answer from infindb table -5402 OAM getSystemStatus message in Windows log -5429 LDI updated casual partitioning min/max values for an extent when where is no update to the actual column value. -5454 assignDbrootPmConfig needs to error out when the system is shutdown -5463 calpontSupport is not including the -c option when -a is selected. -5499 'Memory leak of ExeMgr' -5529 _CpNoTf_ is reported in results set -5549 update on two columns with an AND causes mysql reset -5555 HDFS tools installed on non-Hadoop system -5558 Issuing Ctrl-C on a repetitive OAM command will set terminal session to echo off -5566 hdfs error message printed to screen in calpontConsole - run before hdfs is up -5573 hadoop: update a string column is very slow. -5588 Delete statement left table locked. -5596 postConfigure/glusterconf is creating gluster brick directories owned by root user -5614 "hdfsCheck failed" message logged in crit.log when the stack came up normal -5621 can't create large (20+ pm) amazon systems using 4.0 AMI -5626 PrimProc crash running on HDFS -5628 Bug joining against unsigned tinyint data type -5631 After applying the row_number() function the table content is going to be lost. -5638 issue with using a constant in group by column -5642 system hung during distributed import -5646 Left outer join on varchar column and date datetime column to date column not returning all matching rows -5651 Query wrapped in a select * () returns invalid results. -5652 alter table add dictionary column doesn’t set Number of allocated blocks correctly -5667 Gluster Install with debian - 'glusterctl status' returns with NOTINSTALLED -5669 gluster install - dbroot setup in gluster was mismatched to OAM setup per pm -5670 DecomSrv is restarting after upgrade to 4.0 -5672 dbroot gets unmounted during upgrade when a softlink is used and disk type is internal -5681 cpimport sometimes fails during concurrent query / import test on HDFS -5683 HdfsRdwrMemBuffer: unable to write all bytes error in cpimport -5689 rename table leaves table inaccessible in HDFS - -/*********************************************************************** -* -* Copyright (C) 2013 Calpont Corp -* All Rights Reserved -* -***********************************************************************/ - -October 15, 2013 -Version 4.0 - - -ENHANCEMENTS INCLUDED IN THIS RELEASE -------------------------------------- -Enh # Short Description - -3581 Optimize Memory Utilization for wide string columns -4531 Add support for Windowing Functions -4568 Add ability to report database, schema, and table sizes -4901 Improve performance of concat function -4902 Improve performance of insert() and replace() string functions -4919 Improve performance of makedate() and maketime() functions -4920 Improve performance of adddate(), date_add(), subdate(), date_sub() functions. -5087 Enhance InfiniDB to support over 32 PMs. -5208 Change the Status Updates messages to have state show an ASCII value -5237 Remove restriction preventing user from dropping a logical partition (segment file) in the last physical partition for a DBRoot -5243 Add setting in Calpont.xml for enable/disable corefiles -5300 calpontSupport script performance improvement and additional features -5316 Include schema name in SQL statement debug log entries -5410 Add support for InfiniDB on Apache Hadoop -5414 Add Infinidb support for Apache Sqoop -5421 Add support for running InfiniDB under a Linux Control Group - - - -ISSUES RESOLVED IN THIS RELEASE -------------------------------- -Bug # Launchpad Short Description - -2871 Exceeding aggregation limits can block session -4208 'drop table' cannot delete files on NFS -4345 Specific SQL statements exhausts memory in seconds -4552 1025340 Load data infile and cpimport produce different results - 1025247 -4757 Incorrect results with correlated subquery -4774 Port Data Duplication to debian & Ubuntu -5160 Incorrect result on query with "DATE(IF(t1.`end_date` - INTERVAL 30 DAY < t1.`start_date`, t1.`start_date`, t1.`end_date` - INTERVAL 30 DAY))" expression -5222 Update errors out when dealing with out-of-range date and datetime values -5256 OAM ops returning without DDLProc fully up -5269 swap limit exceeded and not cleared by OAM restart of the system -5272 cast function returns incorrect result -5274 alter table add column returned "Constraints are currently not supported in InfiniDB" error -5287 system came up Active while a pm was disabled and dbroot was assigned to it -5299 stopsystem with Force Option is incorrectly resetting dbrm and save_brm too early -5301 startsystem command system status ended up in MAN_OFFLINE instead of ACTIVE -5304 Windows command prompt exit hangs after cpimport on upgraded database from 3.0.x and earlier -5321 Delete from table command fails when pm1 is down on a combo 2pm system -5322 query failed after disabling and enabling partitions -5323 Backup error opening column file for OID-3132 on a multi node cpimport -5331 select calshowpartitions not showing limits incorrectly for char fields in empty table -5332 shutdownSystem command incorrectly reported 'success' -5349 ERR : Backup error for column file error message occurred running cpimport -5356 Default syslog.conf to the asynchronous option -5374 Data mismatch occurred running query via view -5379 LPAD is not functioning correctly when using a Japanese character -5391 ERROR 138 (HY000): IDB-1000: 'c1, c2' and 'c3' are not joined error message on a query -5392 Reset invalid locale alarm when locale has been corrected -5426 calshowprocesslist issue hard-coded to look for host in first 13 bytes -5427 Distributed cpimport not handling connection failure with WriteEngineServer -5429 Load data infile cleared the min/max values for an extent that was not updated -5436 ERROR 122 (HY000): CAL0001: Alter table Failed: AlterTableProcessor::addColumn Failed to set offset in a compressed data file. -5438 query filters issue -5447 cpimport is reporting that -i is an invalid option -5448 Bug in date_add() with InfiniDB table -5455 PrimProc resets during a particular sql statement -5463 calpontSupport is not including the -c option when -a is selected. -5481 Maintain DBBC/NumThreads setting through upgrade -5488 PrimProc hangs when DecomSvr dies -5494 calpontSupport -a option is not capturing the logs from PM1 -5495 DB occasionally hangs querying old data loaded in 3.5.0 or prior release - diff --git a/INSTALL b/INSTALL index 0f12f143..05699fc4 100644 --- a/INSTALL +++ b/INSTALL @@ -4,46 +4,49 @@ Installation Instructions Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005 Free Software Foundation, Inc. -Copyright (C) 2014 InfiniDB, Inc. +Copyright (C) 2009-2012 Calpont Corp. This file is free documentation; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. -InfiniDB, Inc. also gives unlimited permission to copy, distribute and +Calpont Corp. also gives unlimited permission to copy, distribute and modify it. -Basic Installation from source +Basic Installation from Source ============================== -**** InfiniDB source build instructions **** +**** Calpont infinidb source build instructions **** -Consult the generic installation instructions +Patch MySQL with Calpont extensions and get it built. +You need to determine the root directory for the MySQL installation. +A suggestion is $HOME. Now we can build MySQL/Calpont: + +./build_mysql.sh --prefix=$HOME + +Now we can build infinidb. Consult the generic installation instructions that follow for detailed information. The short version is: -cd $HOME -git clone http://github.com/infinidb/mysql -git clone http://github.com/infinidb/infinidb --- or -- -tar -zxf -cd mysql -./configure --prefix=$HOME -make -make install -cd ../infinidb ./configure --prefix=$HOME make make install -This will create a directory called Calpont in $HOME which conatins +This will create a directory called Calpont in $HOME which contains all the software you need. -Install the InfiniDB software into /usr/local (for example) by copying +Install the Calpont software into /usr/local (for example) by copying the entire Calpont directory tree there. +If you would like to do an RPM install, you can build RPM's with: +./make_rpms + After untaring the sofware or installing the RPM's, setup the software -to run (this script needs to run with root privileges). Check the Installation -Guide for addition details on using postConfigure: -/usr/local/Calpont/bin/postConfigure +to run (this script needs to run with root privileges): +/usr/local/Calpont/bin/install-infinidb.sh + +Start the database: +service infinidb start +or: +/usr/local/Calpont/bin/infinidb start Setup some aliases: . /usr/local/Calpont/bin/calpontAlias @@ -76,10 +79,8 @@ And check the import: calpontmysql calpont select * from caltest; - That's it. Enjoy. - These are generic installation instructions. The `configure' shell script attempts to guess correct values for diff --git a/Makefile.am b/Makefile.am index 055f5bb8..efdf8f0c 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ @@ -39,13 +39,12 @@ all-local: bootstrap $(MAKE) -C ddlpackage install; \ $(MAKE) -C ddlpackageproc install; \ $(MAKE) -C dmlpackage install; \ - $(MAKE) -C dmlpackageproc install + $(MAKE) -C dmlpackageproc install; \ + $(MAKE) -C sm install cd dbcon && $(MAKE) && $(MAKE) install cd exemgr && $(MAKE) && $(MAKE) install cd ddlproc && $(MAKE) && $(MAKE) install cd dmlproc && $(MAKE) && $(MAKE) install - cd procmon && $(MAKE) && $(MAKE) install - cd procmgr && $(MAKE) && $(MAKE) install cd oamapps && $(MAKE) && $(MAKE) install cd decomsvr && $(MAKE) && $(MAKE) install cd primitives && $(MAKE) && $(MAKE) install @@ -68,18 +67,24 @@ leakcheck: docs: bootstrap: - ./build/genVersion.sh --prefix=$(prefix) + ./build/genVersion.sh --prefix=@prefix@/Calpont for subdir in dbcon ddlproc dmlproc exemgr mysql net-snmp oam \ - oamapps decomsvr primitives procmgr procmon qa snmpd tools utils versioning \ + oamapps decomsvr primitives snmpd tools utils versioning \ writeengine ; do \ if test -f $$subdir/Makefile; then \ $(MAKE) BOOTSTRAP=1 -C $$subdir bootstrap || exit $$?; \ fi; \ done +install: install-data-am + $(INSTALL) -m0644 COPYING @prefix@/Calpont + $(INSTALL) -m0644 INSTALL @prefix@/Calpont + $(INSTALL) -m0644 README @prefix@/Calpont + $(INSTALL) -m0644 build/releasenum @prefix@/Calpont + clean: clean-am for subdir in dbcon ddlproc dmlproc exemgr mysql net-snmp oam \ - oamapps decomsvr primitives procmgr procmon qa snmpd tools utils versioning \ + oamapps decomsvr primitives snmpd tools utils versioning \ writeengine ; do \ if test -f $$subdir/Makefile; then \ $(MAKE) BOOTSTRAP=1 -C $$subdir clean || exit $$?; \ diff --git a/Makefile.in b/Makefile.in index 46e8139c..6d30c154 100644 --- a/Makefile.in +++ b/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ srcdir = @srcdir@ @@ -61,9 +61,8 @@ DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ missing subdir = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ @@ -143,9 +142,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -187,7 +183,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -201,11 +196,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -419,7 +409,6 @@ check-am: all-am check: check-am all-am: Makefile config.h all-local installdirs: -install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am @@ -525,13 +514,12 @@ all-local: bootstrap $(MAKE) -C ddlpackage install; \ $(MAKE) -C ddlpackageproc install; \ $(MAKE) -C dmlpackage install; \ - $(MAKE) -C dmlpackageproc install + $(MAKE) -C dmlpackageproc install; \ + $(MAKE) -C sm install cd dbcon && $(MAKE) && $(MAKE) install cd exemgr && $(MAKE) && $(MAKE) install cd ddlproc && $(MAKE) && $(MAKE) install cd dmlproc && $(MAKE) && $(MAKE) install - cd procmon && $(MAKE) && $(MAKE) install - cd procmgr && $(MAKE) && $(MAKE) install cd oamapps && $(MAKE) && $(MAKE) install cd decomsvr && $(MAKE) && $(MAKE) install cd primitives && $(MAKE) && $(MAKE) install @@ -554,18 +542,24 @@ leakcheck: docs: bootstrap: - ./build/genVersion.sh --prefix=$(prefix) + ./build/genVersion.sh --prefix=@prefix@/Calpont for subdir in dbcon ddlproc dmlproc exemgr mysql net-snmp oam \ - oamapps decomsvr primitives procmgr procmon qa snmpd tools utils versioning \ + oamapps decomsvr primitives snmpd tools utils versioning \ writeengine ; do \ if test -f $$subdir/Makefile; then \ $(MAKE) BOOTSTRAP=1 -C $$subdir bootstrap || exit $$?; \ fi; \ done +install: install-data-am + $(INSTALL) -m0644 COPYING @prefix@/Calpont + $(INSTALL) -m0644 INSTALL @prefix@/Calpont + $(INSTALL) -m0644 README @prefix@/Calpont + $(INSTALL) -m0644 build/releasenum @prefix@/Calpont + clean: clean-am for subdir in dbcon ddlproc dmlproc exemgr mysql net-snmp oam \ - oamapps decomsvr primitives procmgr procmon qa snmpd tools utils versioning \ + oamapps decomsvr primitives snmpd tools utils versioning \ writeengine ; do \ if test -f $$subdir/Makefile; then \ $(MAKE) BOOTSTRAP=1 -C $$subdir clean || exit $$?; \ diff --git a/README b/README index 2aa1663a..5610d453 100644 --- a/README +++ b/README @@ -2,144 +2,39 @@ To build the software from source, consult the file INSTALL. Brief Install Instructions: -1. Install the 3 Calpont InfiniDB RPMs. -2. Install and start the software, run: /usr/local/Calpont/bin/postConfigure -3. Setup some aliases: . /usr/local/Calpont/bin/calpontAlias -4. Connect to MySQL: idbmysql -5. Try the test in step 12 below +1. Install the 3 Calpont infinidb RPMs or unpack the binary tar file into /usr/local. +2. Setup the software to run: /usr/local/Calpont/bin/install-infinidb.sh +3. Start the Database: service infinidb start + or /usr/local/Calpont/bin/infinidb start +4. Setup some aliases: . /usr/local/Calpont/bin/calpontAlias +5. Run the following upgrade script to create calponsys schema and upgrade the syscolumn table: /usr/local/Calpont/bin/upgrade-infinidb.sh +6. Connect to MySQL: idbmysql - -Detailed Installation Instructions: - -1. Download the package calpont-2.2.0-2.x86_64.rpm.tar.gz (RHEL5 64-BIT) - to the server where you are installing Calpont. - -2. Obtain root user access. - -3. Unpack the tarball, which will generate 4 RPMs. - - tar xvf calpont-2.2.0-2.x86_64.rpm.tar.gz - -4. Install the 3 RPMs in this order, the Calpont InfiniDB software will be installed in - /usr/local/Calpont. - - rpm -ivh infinidb-libs-2.2.0-2.x86_64.rpm - rpm -ivh infinidb-platform-2.2.0-2.x86_64.rpm - rpm -ivh infinidb-mysql-2.2.0-2.x86_64.rpm - rpm -ivh infinidb-storage-engine-2.2.0-2.x86_64.rpm - -5a.To configure and run on a single server system utilizing local disk storage, - run install script: - - /usr/local/Calpont/bin/postConfigure - -5b.To configure and run on a multi-server system and/or to utilize a SAN storage - system, follow the instructions in the Calpont InfiniDB Installation Guide. - - /usr/local/Calpont/bin/postConfigure - -6. Ports utilized by the Calpont InfiniDB Software - - The Calpont MySQL daemon utilizes port 3306. To use a different port, update - the 2 locations in the following file: - - /usr/local/Calpont/mysql/my.cnf - - port = 3306 - port = 3306 - - You must reserve the following ports to run the Calpont InfiniDB Software: - - 8600 - 8622, 8700, and 8800 - -7. Setup some aliases: -. /usr/local/Calpont/bin/calpontAlias - -8. To manually start and stop the Calpont InfiniDB Software as the root user run: - - cc startSystem - - To stop the Calpont Software, run: - - cc stopSystem - -9. To start/stop the Calpont InfiniDB Software during system boot/shutdown use the - chkconfig command - - /sbin/chkconfig --add infinidb - /sbin/chkconfig infinidb on - -10. After the Calpont InfiniDB Software has been started, use the following command to - connect to the Calpont OAM Console and watch for the System to go to the - ACTIVE status. The follow will repeatedly run the OAM command getsysteminfo - every 5 seconds. - - calpontOAMconsole getsysteminfo -r - - Here is an example display from a Single Server Install: - - System and Module statuses - - Component Status Last Status Change - ------------ ---------------------- ------------------------ - System ACTIVE Mon Apr 6 18:07:14 2009 - - Module dm1 ACTIVE Mon Apr 6 18:07:12 2009 - - Calpont Process statuses - - Process Module Status Last Status Change Process ID - ------------------ ------ ------------ ------------------------ ---------- - ProcessMonitor dm1 ACTIVE Mon Apr 6 18:06:41 2009 12753 - ProcessManager dm1 ACTIVE Mon Apr 6 18:06:46 2009 12954 - SNMPTrapDaemon dm1 ACTIVE Mon Apr 6 18:06:41 2009 12963 - SNMPAgent dm1 ACTIVE Mon Apr 6 18:06:50 2009 13565 - ServerMonitor dm1 ACTIVE Mon Apr 6 18:06:55 2009 13635 - DBRMWorkerNode dm1 ACTIVE Mon Apr 6 18:06:51 2009 13640 - DBRMControllerNode dm1 ACTIVE Mon Apr 6 18:06:52 2009 13645 - ExeMgr dm1 ACTIVE Mon Apr 6 18:07:05 2009 14578 - PrimProc dm1 ACTIVE Mon Apr 6 18:07:03 2009 13842 - DDLProc dm1 ACTIVE Mon Apr 6 18:07:10 2009 14936 - DMLProc dm1 ACTIVE Mon Apr 6 18:07:13 2009 15114 - - Active Alarm Counts: Critical = 0, Major = 0, Minor = 0, Warning = 0, Info = 0 - - Once the System status is ACTIVE, enter the following to exit back to the - UNIX prompt: - - CNTR - - Or to get back Calpont OAM Console Prompt,enter the following: - - CNTR - -11. Use the following command to access the Calpont InfiniDB MySQL console: - - idbmysql - - Example output: - - Welcome to the Mysql monitor. Commands end with ; or \g. - Your Mysql connection id is 1 - Server version: 5.1.26-Calpont-log Source distribution - - Type 'help;' or '\h' for help. Type '\c' to clear the buffer. - - mysql> - -12. Run the following upgrade script to create calponsys schema and upgrade the syscolumn table: /usr/local/Calpont/bin/upgrade-infinidb.sh - -13. As an example to get you started, try this: +7. As an example to get you started, try this: create database calpont; use calpont; create table caltest (col1 int, col2 int) engine=infinidb; show create table caltest; + set autocommit=0; insert into caltest values (1, 2); insert into caltest values (3, 4); commit; select * from caltest; -14. Consult the Admin Guide and Syntax Guide for additional information on how - to get started. +Note: +Examine the output of the show create table command carefully and +make sure the table is in fact a calpont table. + +If the table is MyISAM type: + +drop table caltest; +install plugin infinidb soname 'libcalmysql.so'; + +and retry the example. +To uninstall infinidb: + service infinidb stop + or /usr/local/Calpont/bin/infinidb stop + chkconfig --del infinidb + rm -rf /usr/local/Calpont diff --git a/README.md b/README.md index 491472ce..eb9da70a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# This is InfiniDB 4.6.1 +# This is InfiniDB 3.5 ## Build prerequisites To build InfiniDB from source you will need: - * a CentOS/RHEL 5/6, debian 6/7 or Ubuntu 12/14 linux host configured for software development + * a CentOS/RHEL 5/6, debian 6/7 or Ubuntu 10/12 linux host configured for software development Along with a working C++ compiler and GNU software development tools you will need the following extra packages: @@ -20,29 +20,18 @@ Along with a working C++ compiler and GNU software development tools you will ne mkdir infinidb-src cd infinidb-src -### InfiniDB MySQL - - wget -Omysql-4.6.1-1.tar.gz https://github.com/infinidb/mysql/archive/4.6.1-1.tar.gz - tar -zxf mysql-4.6.1-1.tar.gz - ln -s mysql-4.6.1-1 mysql - cd mysql - ./configure --prefix=$HOME/infinidb/mysql - make - make install - ### InfiniDB - cd .. - wget -Oinfinidb-4.6.1-1.tar.gz https://github.com/infinidb/infinidb/archive/4.6.1-1.tar.gz - tar -zxf infinidb-4.6.1-1.tar.gz - ln -s infinidb-4.6.1-1 infinidb + wget -Oinfinidb-3.5.tar.gz https://github.com/infinidb/infinidb/archive/3.5.tar.gz + tar -zxf infinidb-3.5.tar.gz + ln -s infinidb-3.5 infinidb cd infinidb ./configure --prefix=$HOME/infinidb make make install This will leave you with `$HOME/infinidb` as a binary tree. Follow the Binary Download -instructions in the InfiniDB 4.6 Installation Guide (available on http://www.infinidb.co/). +instructions in the InfiniDB 3.5 Installation Guide (available on http://www.infinidb.co/). ## How to Contribute * You may submit your contributions via GitHub pull requests. diff --git a/aclocal.m4 b/aclocal.m4 index 66eddf23..f582e394 100644 --- a/aclocal.m4 +++ b/aclocal.m4 @@ -6410,195 +6410,6 @@ AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ]) -# Configure paths for LIBXML2 -# Mike Hommey 2004-06-19 -# use CPPFLAGS instead of CFLAGS -# Toshio Kuratomi 2001-04-21 -# Adapted from: -# Configure paths for GLIB -# Owen Taylor 97-11-3 - -dnl AM_PATH_XML2([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]]) -dnl Test for XML, and define XML_CPPFLAGS and XML_LIBS -dnl -AC_DEFUN([AM_PATH_XML2],[ -AC_ARG_WITH(xml-prefix, - [ --with-xml-prefix=PFX Prefix where libxml is installed (optional)], - xml_config_prefix="$withval", xml_config_prefix="") -AC_ARG_WITH(xml-exec-prefix, - [ --with-xml-exec-prefix=PFX Exec prefix where libxml is installed (optional)], - xml_config_exec_prefix="$withval", xml_config_exec_prefix="") -AC_ARG_ENABLE(xmltest, - [ --disable-xmltest Do not try to compile and run a test LIBXML program],, - enable_xmltest=yes) - - if test x$xml_config_exec_prefix != x ; then - xml_config_args="$xml_config_args" - if test x${XML2_CONFIG+set} != xset ; then - XML2_CONFIG=$xml_config_exec_prefix/bin/xml2-config - fi - fi - if test x$xml_config_prefix != x ; then - xml_config_args="$xml_config_args --prefix=$xml_config_prefix" - if test x${XML2_CONFIG+set} != xset ; then - XML2_CONFIG=$xml_config_prefix/bin/xml2-config - fi - fi - - AC_PATH_PROG(XML2_CONFIG, xml2-config, no) - min_xml_version=ifelse([$1], ,2.0.0,[$1]) - AC_MSG_CHECKING(for libxml - version >= $min_xml_version) - no_xml="" - if test "$XML2_CONFIG" = "no" ; then - no_xml=yes - else - XML_CPPFLAGS=`$XML2_CONFIG $xml_config_args --cflags` - XML_LIBS=`$XML2_CONFIG $xml_config_args --libs` - xml_config_major_version=`$XML2_CONFIG $xml_config_args --version | \ - sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'` - xml_config_minor_version=`$XML2_CONFIG $xml_config_args --version | \ - sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'` - xml_config_micro_version=`$XML2_CONFIG $xml_config_args --version | \ - sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'` - if test "x$enable_xmltest" = "xyes" ; then - ac_save_CPPFLAGS="$CPPFLAGS" - ac_save_LIBS="$LIBS" - CPPFLAGS="$CPPFLAGS $XML_CPPFLAGS" - LIBS="$XML_LIBS $LIBS" -dnl -dnl Now check if the installed libxml is sufficiently new. -dnl (Also sanity checks the results of xml2-config to some extent) -dnl - rm -f conf.xmltest - AC_TRY_RUN([ -#include -#include -#include -#include - -int -main() -{ - int xml_major_version, xml_minor_version, xml_micro_version; - int major, minor, micro; - char *tmp_version; - - system("touch conf.xmltest"); - - /* Capture xml2-config output via autoconf/configure variables */ - /* HP/UX 9 (%@#!) writes to sscanf strings */ - tmp_version = (char *)strdup("$min_xml_version"); - if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, µ) != 3) { - printf("%s, bad version string from xml2-config\n", "$min_xml_version"); - exit(1); - } - free(tmp_version); - - /* Capture the version information from the header files */ - tmp_version = (char *)strdup(LIBXML_DOTTED_VERSION); - if (sscanf(tmp_version, "%d.%d.%d", &xml_major_version, &xml_minor_version, &xml_micro_version) != 3) { - printf("%s, bad version string from libxml includes\n", "LIBXML_DOTTED_VERSION"); - exit(1); - } - free(tmp_version); - - /* Compare xml2-config output to the libxml headers */ - if ((xml_major_version != $xml_config_major_version) || - (xml_minor_version != $xml_config_minor_version) || - (xml_micro_version != $xml_config_micro_version)) - { - printf("*** libxml header files (version %d.%d.%d) do not match\n", - xml_major_version, xml_minor_version, xml_micro_version); - printf("*** xml2-config (version %d.%d.%d)\n", - $xml_config_major_version, $xml_config_minor_version, $xml_config_micro_version); - return 1; - } -/* Compare the headers to the library to make sure we match */ - /* Less than ideal -- doesn't provide us with return value feedback, - * only exits if there's a serious mismatch between header and library. - */ - LIBXML_TEST_VERSION; - - /* Test that the library is greater than our minimum version */ - if ((xml_major_version > major) || - ((xml_major_version == major) && (xml_minor_version > minor)) || - ((xml_major_version == major) && (xml_minor_version == minor) && - (xml_micro_version >= micro))) - { - return 0; - } - else - { - printf("\n*** An old version of libxml (%d.%d.%d) was found.\n", - xml_major_version, xml_minor_version, xml_micro_version); - printf("*** You need a version of libxml newer than %d.%d.%d. The latest version of\n", - major, minor, micro); - printf("*** libxml is always available from ftp://ftp.xmlsoft.org.\n"); - printf("***\n"); - printf("*** If you have already installed a sufficiently new version, this error\n"); - printf("*** probably means that the wrong copy of the xml2-config shell script is\n"); - printf("*** being found. The easiest way to fix this is to remove the old version\n"); - printf("*** of LIBXML, but you can also set the XML2_CONFIG environment to point to the\n"); - printf("*** correct copy of xml2-config. (In this case, you will have to\n"); - printf("*** modify your LD_LIBRARY_PATH enviroment variable, or edit /etc/ld.so.conf\n"); - printf("*** so that the correct libraries are found at run-time))\n"); - } - return 1; -} -],, no_xml=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) - CPPFLAGS="$ac_save_CPPFLAGS" - LIBS="$ac_save_LIBS" - fi - fi - - if test "x$no_xml" = x ; then - AC_MSG_RESULT(yes (version $xml_config_major_version.$xml_config_minor_version.$xml_config_micro_version)) - ifelse([$2], , :, [$2]) - else - AC_MSG_RESULT(no) - if test "$XML2_CONFIG" = "no" ; then - echo "*** The xml2-config script installed by LIBXML could not be found" - echo "*** If libxml was installed in PREFIX, make sure PREFIX/bin is in" - echo "*** your path, or set the XML2_CONFIG environment variable to the" - echo "*** full path to xml2-config." - else - if test -f conf.xmltest ; then - : - else - echo "*** Could not run libxml test program, checking why..." - CPPFLAGS="$CPPFLAGS $XML_CPPFLAGS" - LIBS="$LIBS $XML_LIBS" - AC_TRY_LINK([ -#include -#include -], [ LIBXML_TEST_VERSION; return 0;], - [ echo "*** The test program compiled, but did not run. This usually means" - echo "*** that the run-time linker is not finding LIBXML or finding the wrong" - echo "*** version of LIBXML. If it is not finding LIBXML, you'll need to set your" - echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" - echo "*** to the installed location Also, make sure you have run ldconfig if that" - echo "*** is required on your system" - echo "***" - echo "*** If you have an old version installed, it is best to remove it, although" - echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH" ], - [ echo "*** The test program failed to compile or link. See the file config.log for the" - echo "*** exact error that occured. This usually means LIBXML was incorrectly installed" - echo "*** or that you have moved LIBXML since it was installed. In the latter case, you" - echo "*** may want to edit the xml2-config script: $XML2_CONFIG" ]) - CPPFLAGS="$ac_save_CPPFLAGS" - LIBS="$ac_save_LIBS" - fi - fi - - XML_CPPFLAGS="" - XML_LIBS="" - ifelse([$3], , :, [$3]) - fi - AC_SUBST(XML_CPPFLAGS) - AC_SUBST(XML_LIBS) - rm -f conf.xmltest -]) - # Copyright (C) 2002, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation @@ -7436,6 +7247,5 @@ AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR -m4_include([m4/compilerflags.m4]) m4_include([m4/functions.m4]) m4_include([m4/install.m4]) diff --git a/build/Build.bat b/build/Build.bat deleted file mode 100755 index 0ee1bea3..00000000 --- a/build/Build.bat +++ /dev/null @@ -1,82 +0,0 @@ -::@echo off - -set branch=%1 -set basedir=\InfiniDB_%branch% -IF "%branch%" == "" ( - set branch=develop - set basedir=\InfiniDB -) -IF "%branch%" == "trunk" ( - set branch=develop - set basedir=\InfiniDB -) -echo %branch% - -echo building %basedir% - -echo ====================================== -echo updating mysql source -cd %basedir%\mysql -git checkout %branch% -git stash -git pull -git stash pop - -echo ====================================== -echo updating InfiniDB source -cd %basedir%\genii -git checkout %branch% -git pull origin_http %branch% -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER - -echo ====================================== -echo Building mysql -cd %basedir%\mysql -MSBuild /M:8 /t:rebuild /p:Configuration="Release" /p:Platform="x64" mysql.sln -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER - -echo ====================================== -echo Building InfiniDB -cd %basedir%\genii\build -MSBuild /M:8 /t:rebuild /p:Configuration="EnterpriseRelease" /p:Platform="x64" InfiniDB.sln -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER - -echo ====================================== -echo Building infindb-ent -cd %basedir%\infinidb-ent\build -call Build.bat -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -cd %basedir%\genii\build - -echo ====================================== -echo Building CalpontVersion.txt -call BuildCalpontVersion.bat - -echo ====================================== -echo Building the Standard Installer -makensis ..\utils\winport\idb_64_standard.nsi -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER - -echo ====================================== -echo Building the Enterprise Installer -makensis ..\utils\winport\idb_64_enterprise.nsi -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -echo. - -echo Build complete -GOTO QUIT - -:ERROR_HANDLER -echo. -echo ====================================== -echo Error occured. InfiniDB not built - -cd %basedir%\genii\build -exit /B 1 - -:QUIT -echo ====================================== -cd %basedir%\genii\build -echo compiled at %date% %time% -echo nightly build complete - diff --git a/build/BuildCalpontVersion.bat b/build/BuildCalpontVersion.bat deleted file mode 100644 index b2e8c62d..00000000 --- a/build/BuildCalpontVersion.bat +++ /dev/null @@ -1,18 +0,0 @@ -for /f "delims= skip=1" %%x in (releasenum) do (set "%%x") -set packager="%USERNAME% <%USERNAME%@calpont.com>" -echo %packager% -set builddate="%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2% %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2%" -set buildmachine=%computername% -copy /Y .\CalpontVersion.txt.in ..\utils\winport\CalpontVersion.txt -sed -i -e s/@@PACKAGER@@/%packager%/ ..\utils\winport\CalpontVersion.txt -sed -i -e s/@@BUILDDATE@@/%builddate%/ ..\utils\winport\CalpontVersion.txt -sed -i -e s/@@VERSION@@/%version%/ ..\utils\winport\CalpontVersion.txt -sed -i -e s/@@RELEASE@@/%release%/ ..\utils\winport\CalpontVersion.txt -sed -i -e s/@@BUILDMACHINE@@/%buildmachine%/ ..\utils\winport\CalpontVersion.txt -:: For some unknown reason, sed removes permissions. Put them back. -icacls ..\utils\winport\CalpontVersion.txt /grant SYSTEM:F administrators:F -cd .. -git status | grep "On branch" >> utils\winport\CalpontVersion.txt -git log -1 | head -3 | egrep "^(commit|Date)" >> utils\winport\CalpontVersion.txt - -cd build diff --git a/build/CMakeLists.txt b/build/CMakeLists.txt deleted file mode 100644 index b28fab8b..00000000 --- a/build/CMakeLists.txt +++ /dev/null @@ -1,155 +0,0 @@ -# Copyright (C) 2006 MySQL AB -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; version 2 of the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -INCLUDE("${PROJECT_SOURCE_DIR}/win/mysql_manifest.cmake") - -SET(CMAKE_CXX_FLAGS_DEBUG - "${CMAKE_CXX_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX -DUSE_SYMDIR /Zi") -SET(CMAKE_C_FLAGS_DEBUG - "${CMAKE_C_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX -DUSE_SYMDIR /Zi") -SET(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /MAP /MAPINFO:EXPORTS") - -INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include - ${CMAKE_SOURCE_DIR}/extra/yassl/include - ${CMAKE_SOURCE_DIR}/sql - ${CMAKE_SOURCE_DIR}/regex - ${CMAKE_SOURCE_DIR}/zlib -) - -SET_SOURCE_FILES_PROPERTIES(${CMAKE_SOURCE_DIR}/sql/sql_yacc.h - ${CMAKE_SOURCE_DIR}/sql/sql_yacc.cc - ${CMAKE_SOURCE_DIR}/include/mysql_version.h - ${CMAKE_SOURCE_DIR}/sql/sql_builtin.cc - ${CMAKE_SOURCE_DIR}/sql/lex_hash.h - ${PROJECT_SOURCE_DIR}/include/mysqld_error.h - ${PROJECT_SOURCE_DIR}/include/mysqld_ername.h - ${PROJECT_SOURCE_DIR}/include/sql_state.h - PROPERTIES GENERATED 1) - -ADD_DEFINITIONS(-DMYSQL_SERVER -D_CONSOLE -DHAVE_DLOPEN -DHAVE_EVENT_SCHEDULER) - - -SET (SQL_SOURCE - ../sql-common/client.c derror.cc des_key_file.cc - discover.cc ../libmysql/errmsg.c field.cc field_conv.cc - filesort.cc gstream.cc - ha_partition.cc - handler.cc hash_filo.cc hash_filo.h - hostname.cc init.cc item.cc item_buff.cc item_cmpfunc.cc - item_create.cc item_func.cc item_geofunc.cc item_row.cc - item_strfunc.cc item_subselect.cc item_sum.cc item_timefunc.cc - item_window_function.cc item_create_window_function.cc - key.cc log.cc lock.cc message.rc - log_event.cc rpl_record.cc rpl_reporting.cc - log_event_old.cc rpl_record_old.cc - message.h mf_iocache.cc my_decimal.cc ../sql-common/my_time.c - mysqld.cc net_serv.cc - nt_servc.cc nt_servc.h opt_range.cc opt_range.h opt_sum.cc - ../sql-common/pack.c parse_file.cc password.c procedure.cc - protocol.cc records.cc repl_failsafe.cc rpl_filter.cc set_var.cc - slave.cc sp.cc sp_cache.cc sp_head.cc sp_pcontext.cc - sp_rcontext.cc spatial.cc sql_acl.cc sql_analyse.cc sql_base.cc - sql_cache.cc sql_class.cc sql_client.cc sql_crypt.cc sql_crypt.h - sql_cursor.cc sql_db.cc sql_delete.cc sql_derived.cc sql_do.cc - sql_error.cc sql_handler.cc sql_help.cc sql_insert.cc sql_lex.cc - sql_list.cc sql_load.cc sql_manager.cc sql_map.cc sql_parse.cc - sql_partition.cc sql_plugin.cc sql_prepare.cc sql_rename.cc - sql_repl.cc sql_select.cc sql_show.cc sql_state.c sql_string.cc - sql_table.cc sql_test.cc sql_trigger.cc sql_udf.cc sql_union.cc - sql_update.cc sql_view.cc strfunc.cc table.cc thr_malloc.cc - time.cc tztime.cc uniques.cc unireg.cc item_xmlfunc.cc - rpl_tblmap.cc sql_binlog.cc event_scheduler.cc event_data_objects.cc - event_queue.cc event_db_repository.cc - sql_tablespace.cc events.cc ../sql-common/my_user.c - partition_info.cc rpl_utility.cc rpl_injector.cc sql_locale.cc - rpl_rli.cc rpl_mi.cc sql_servers.cc - sql_connect.cc scheduler.cc - sql_profile.cc event_parse_data.cc - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.cc - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.h - ${PROJECT_SOURCE_DIR}/include/mysqld_error.h - ${PROJECT_SOURCE_DIR}/include/mysqld_ername.h - ${PROJECT_SOURCE_DIR}/include/sql_state.h - ${PROJECT_SOURCE_DIR}/include/mysql_version.h - ${PROJECT_SOURCE_DIR}/sql/sql_builtin.cc - ${PROJECT_SOURCE_DIR}/sql/lex_hash.h) -ADD_LIBRARY(sql ${SQL_SOURCE}) - -IF (NOT EXISTS cmake_dummy.cc) - FILE (WRITE cmake_dummy.cc "") -ENDIF (NOT EXISTS cmake_dummy.cc) -ADD_EXECUTABLE(mysqld cmake_dummy.cc) - -SET_TARGET_PROPERTIES(mysqld PROPERTIES OUTPUT_NAME mysqld${MYSQLD_EXE_SUFFIX}) -SET_TARGET_PROPERTIES(mysqld PROPERTIES ENABLE_EXPORTS TRUE) - -SET (MYSQLD_CORE_LIBS mysys zlib dbug strings yassl taocrypt vio regex sql) -TARGET_LINK_LIBRARIES(mysqld ${MYSQLD_CORE_LIBS} ${MYSQLD_STATIC_ENGINE_LIBS}) -TARGET_LINK_LIBRARIES(mysqld ws2_32.lib) - - -IF(MSVC AND NOT WITHOUT_DYNAMIC_PLUGINS) - # Set module definition file. Also use non-incremental linker, - # incremental appears to crash from time to time,if used with /DEF option - SET_TARGET_PROPERTIES(mysqld PROPERTIES LINK_FLAGS "/DEF:mysqld.def /INCREMENTAL:NO") - - FOREACH (CORELIB ${MYSQLD_CORE_LIBS}) - GET_TARGET_PROPERTY(LOC ${CORELIB} LOCATION) - FILE(TO_NATIVE_PATH ${LOC} LOC) - SET (LIB_LOCATIONS ${LIB_LOCATIONS} ${LOC}) - ENDFOREACH (CORELIB ${MYSQLD_CORE_LIBS}) - - ADD_CUSTOM_COMMAND(TARGET mysqld PRE_LINK - COMMAND cscript ARGS //nologo ${PROJECT_SOURCE_DIR}/win/create_def_file.js - ${PLATFORM} ${LIB_LOCATIONS} > mysqld.def - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/sql) -ENDIF(MSVC AND NOT WITHOUT_DYNAMIC_PLUGINS) - -ADD_DEPENDENCIES(sql GenError) - -# Sql Parser custom command -ADD_CUSTOM_COMMAND( - OUTPUT ${PROJECT_SOURCE_DIR}/sql/sql_yacc.h - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.cc - COMMAND bison ARGS -y -p MYSQL --defines=sql_yacc.h - --output=sql_yacc.cc sql_yacc.yy - DEPENDS ${PROJECT_SOURCE_DIR}/sql/sql_yacc.yy) - - -# Gen_lex_hash -ADD_EXECUTABLE(gen_lex_hash gen_lex_hash.cc) -TARGET_LINK_LIBRARIES(gen_lex_hash debug dbug mysqlclient wsock32) -GET_TARGET_PROPERTY(GEN_LEX_HASH_EXE gen_lex_hash LOCATION) -ADD_CUSTOM_COMMAND( - OUTPUT ${PROJECT_SOURCE_DIR}/sql/lex_hash.h - COMMAND ${GEN_LEX_HASH_EXE} ARGS > lex_hash.h - DEPENDS ${GEN_LEX_HASH_EXE}) - -ADD_CUSTOM_TARGET( - GenServerSource ALL - DEPENDS ${PROJECT_SOURCE_DIR}/sql/sql_yacc.h - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.cc - ${PROJECT_SOURCE_DIR}/sql/message.h - ${PROJECT_SOURCE_DIR}/sql/message.rc - ${PROJECT_SOURCE_DIR}/sql/lex_hash.h) - -ADD_DEPENDENCIES(mysqld GenServerSource) - -# Remove the auto-generated files as part of 'Clean Solution' -SET_DIRECTORY_PROPERTIES(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES - "lex_hash.h;sql_yacc.h;sql_yacc.cc;mysqld.def") - -ADD_LIBRARY(udf_example MODULE udf_example.c udf_example.def) -ADD_DEPENDENCIES(udf_example strings GenError) -TARGET_LINK_LIBRARIES(udf_example strings wsock32) diff --git a/build/CalpontVersion.txt.in b/build/CalpontVersion.txt.in deleted file mode 100644 index 161d08c0..00000000 --- a/build/CalpontVersion.txt.in +++ /dev/null @@ -1,13 +0,0 @@ -Name : infinidb Relocations: (not relocatable) -Version : @@VERSION@@ Vendor: InfiniDB, Inc. -Release : @@RELEASE@@ Build Date: @@BUILDDATE@@ -Install Date: @@INSTALLDATE@@ Build Host: @@BUILDMACHINE@@.calpont.com -Group : Applications -Size : 750449506 License: Copyright (c) 2014 InfiniDB, Inc., all rights reserved -Signature : (none) -Packager : @@PACKAGER@@ -URL : http://www.infinidb.co/ -Summary : InfiniDB software for Windows - -InfiniDB binary files - diff --git a/build/CopyLog.sh b/build/CopyLog.sh deleted file mode 100644 index 89680866..00000000 --- a/build/CopyLog.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/expect -f -#@echo off -spawn scp /InfiniDB/genii/mysql/queries/nightly/srvswdev11/go.log root@srvnightly:/tmp/srvbldwin1-genii-queryTester.log - -expect { - -re "authenticity" { send "yes\r" - expect { - -re "word: " { send "$PASSWORD\r" } abort - -re "passphrase" { send "$PASSWORD\r" } abort - } - } - -re "word: " { send "Calpont1\r" } abort - } -expect "*\r" -expect "\r" \ No newline at end of file diff --git a/build/CopyToCalweb.bat b/build/CopyToCalweb.bat deleted file mode 100644 index 058af793..00000000 --- a/build/CopyToCalweb.bat +++ /dev/null @@ -1,5 +0,0 @@ -set dailydirname=genii-%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2% -xcopy /i /y \InfiniDB\genii\utils\winport\InfiniDB64.exe \\calweb\shared\\Iterations\Latest\packages\ -xcopy /i /y \InfiniDB\genii\utils\winport\InfiniDB64.exe \\calweb\shared\\Iterations\nightly\%dailydirname%\packages\ -xcopy /i /y \InfiniDB\genii\utils\winport\InfiniDB64-ent.exe \\calweb\shared\\Iterations\Latest\packages\ -xcopy /i /y \InfiniDB\genii\utils\winport\InfiniDB64-ent.exe \\calweb\shared\\Iterations\nightly\%dailydirname%\packages\ diff --git a/build/InfiniDB.sln b/build/InfiniDB.sln deleted file mode 100644 index 7ec57774..00000000 --- a/build/InfiniDB.sln +++ /dev/null @@ -1,1199 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExeMgr", "..\exemgr\ExeMgr.vcxproj", "{1CE8E777-042F-48E2-B146-2B411E14F765}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libconfigcpp", "..\utils\configcpp\libconfigcpp.vcxproj", "{C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmessageqcpp", "..\utils\messageqcpp\libmessageqcpp.vcxproj", "{226D1F60-1E33-401B-A333-D583AF69B86E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwinport", "..\utils\winport\libwinport.vcxproj", "{4F0851D3-B782-4F12-B748-73EFA2DA586B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcommon", "..\utils\common\libcommon.vcxproj", "{004899A2-3CAB-4796-B030-34A20AC285C9}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libthreadpool", "..\utils\threadpool\libthreadpool.vcxproj", "{2BE469D2-D854-4480-BFE0-34DE89C557B2}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjoiner", "..\utils\joiner\libjoiner.vcxproj", "{FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjoblist", "..\dbcon\joblist\libjoblist.vcxproj", "{CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}" - ProjectSection(ProjectDependencies) = postProject - {2BE469D2-D854-4480-BFE0-34DE89C557B2} = {2BE469D2-D854-4480-BFE0-34DE89C557B2} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "librowgroup", "..\utils\rowgroup\librowgroup.vcxproj", "{054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libexecplan", "..\dbcon\execplan\libexecplan.vcxproj", "{FFCCE773-27FA-4F4D-9E28-2208BE6348DA}" - ProjectSection(ProjectDependencies) = postProject - {2BE469D2-D854-4480-BFE0-34DE89C557B2} = {2BE469D2-D854-4480-BFE0-34DE89C557B2} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwriteengine", "..\writeengine\libwriteengine.vcxproj", "{414A47EB-55E3-4251-99B0-95D86FE5580D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libdataconvert", "..\utils\dataconvert\libdataconvert.vcxproj", "{AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libfuncexp", "..\utils\funcexp\libfuncexp.vcxproj", "{9AE60D66-99F6-4CCB-902D-3814A12AE0A9}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbrm", "..\versioning\BRM\libbrm.vcxproj", "{A13E870A-7A9E-4027-8E17-204398225361}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "librwlock", "..\utils\rwlock\librwlock.vcxproj", "{5362725E-BB90-44A3-9D13-3DE9B5041AD2}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liboamcpp", "..\oam\oamcpp\liboamcpp.vcxproj", "{8F7C9B67-639C-468F-8C5A-EB5F2E944E64}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libloggingcpp", "..\utils\loggingcpp\libloggingcpp.vcxproj", "{07230DF5-10E9-469E-8075-C0978C0460AD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "workernode", "..\versioning\BRM\workernode.vcxproj", "{AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "load_brm", "..\versioning\BRM\load_brm.vcxproj", "{B77B5FD1-8CA3-40F6-BA61-2FE51D074119}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "controllernode", "..\versioning\BRM\controllernode.vcxproj", "{A9298547-2C38-4116-9063-D09F72A85F43}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "editem", "..\tools\editem\editem.vcxproj", "{E9417C0B-D839-46E2-A2A8-439E6087E873}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcacheutils", "..\utils\cacheutils\libcacheutils.vcxproj", "{B44BE805-2019-4FCB-B213-45F1D7A73CCD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dbbuilder", "..\tools\dbbuilder\dbbuilder.vcxproj", "{F767A00A-1063-4C0A-B8E3-A27E3F332724}" - ProjectSection(ProjectDependencies) = postProject - {2BE469D2-D854-4480-BFE0-34DE89C557B2} = {2BE469D2-D854-4480-BFE0-34DE89C557B2} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libddlpackage", "..\dbcon\ddlpackage\libddlpackage.vcxproj", "{033C6CBA-D984-483F-ADC8-825BE20A699D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libddlpackageproc", "..\dbcon\ddlpackageproc\libddlpackageproc.vcxproj", "{19142D9E-7660-445C-B85D-98E722DFFEA5}" - ProjectSection(ProjectDependencies) = postProject - {2BE469D2-D854-4480-BFE0-34DE89C557B2} = {2BE469D2-D854-4480-BFE0-34DE89C557B2} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libdmlpackage", "..\dbcon\dmlpackage\libdmlpackage.vcxproj", "{B9045BCA-0955-4C5E-BCA4-5EE516838119}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libdmlpackageproc", "..\dbcon\dmlpackageproc\libdmlpackageproc.vcxproj", "{C78DD512-FCA0-4B8A-A531-376E33C9FBB7}" - ProjectSection(ProjectDependencies) = postProject - {2BE469D2-D854-4480-BFE0-34DE89C557B2} = {2BE469D2-D854-4480-BFE0-34DE89C557B2} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "save_brm", "..\versioning\BRM\save_brm.vcxproj", "{D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PrimProc", "..\primitives\primproc\PrimProc.vcxproj", "{C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DDLProc", "..\ddlproc\DDLProc.vcxproj", "{EE6E6244-93A6-4014-A947-EFCB779B87B6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DMLProc", "..\dmlproc\DMLProc.vcxproj", "{10EFDC01-9720-45A3-9290-7C394B459CB0}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "colxml", "..\tools\dbloadxml\colxml.vcxproj", "{635981B1-9353-4102-935B-177432EDC072}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cpimport", "..\writeengine\bulk\cpimport.vcxproj", "{36549A0A-BF9F-4642-92E7-FAA10061BD34}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "winfinidb", "..\utils\winport\winfinidb.vcxproj", "{DCB5C215-2F35-4439-B94E-C818E0921385}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bootstrap", "..\utils\winport\bootstrap.vcxproj", "{BCC9E913-1C3D-492B-B245-8F43B4F30C1C}" - ProjectSection(ProjectDependencies) = postProject - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B} = {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B} - {004899A2-3CAB-4796-B030-34A20AC285C9} = {004899A2-3CAB-4796-B030-34A20AC285C9} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "clearShm", "..\tools\clearShm\clearShm.vcxproj", "{E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}" - ProjectSection(ProjectDependencies) = postProject - {004899A2-3CAB-4796-B030-34A20AC285C9} = {004899A2-3CAB-4796-B030-34A20AC285C9} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "viewtablelock", "..\tools\viewtablelock\viewtablelock.vcxproj", "{DC26E3DB-B3E6-469E-869D-3FA5FC026C20}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cleartablelock", "..\tools\cleartablelock\cleartablelock.vcxproj", "{F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ddlcleanup", "..\tools\ddlcleanup\ddlcleanup.vcxproj", "{71C00ACF-619C-407D-8A69-995CD27F7809}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "getConfig", "..\tools\getConfig\getConfig.vcxproj", "{1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "setConfig", "..\tools\setConfig\setConfig.vcxproj", "{13E96B71-0854-4EA5-A7ED-0950AE10C858}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cplogger", "..\tools\cplogger\cplogger.vcxproj", "{6B8C806F-46F7-412F-9FB1-78DFA505597E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcompress-ent", "..\utils\compress\libcompress-ent.vcxproj", "{0B72A604-0755-4E2C-B74B-C93564847114}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dbrmctl", "..\versioning\BRM\dbrmctl.vcxproj", "{E4A08BD5-5F31-499B-A61D-68E4924D9F60}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "reset_locks", "..\versioning\BRM\reset_locks.vcxproj", "{DB67EB06-04F1-4615-9095-3E5F02DD7008}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WriteEngineServer", "..\writeengine\server\WriteEngineServer.vcxproj", "{85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "splitter", "..\writeengine\splitter\splitter.vcxproj", "{B160A65B-D07D-4CCD-A0FD-6A0800E9F595}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libweclient", "..\writeengine\client\libweclient.vcxproj", "{4BC37219-E09D-4133-98C4-CF0386657DF6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libddlcleanup", "..\utils\ddlcleanup\libddlcleanup.vcxproj", "{E95FECB8-1B06-41FF-8E1D-40B7E6841765}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbatchloader", "..\utils\batchloader\libbatchloader.vcxproj", "{35D6295B-4A83-4E6E-BAB0-70ADF19AE822}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libidbboot", "..\utils\startup\libidbboot.vcxproj", "{B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libquerystats", "..\utils\querystats\libquerystats.vcxproj", "{3238CD73-8FFD-44A7-AA5F-815BEEF8F402}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DecomSvr", "..\decomsvr\DecomSvr.vcxproj", "{E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libwindowfunction", "..\utils\windowfunction\libwindowfunction.vcxproj", "{0DD34627-B046-4415-80CF-D0FBA4E069CB}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libidbdatafile", "..\utils\idbdatafile\idbdatafile.vcxproj", "{4C8231D7-7A87-4650-AA9C-D7650C1D03EE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcalmysql", "..\dbcon\mysql\libcalmysql.vcxproj", "{0049D0FD-6479-442C-B53A-F4C7FF7AD34F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmysqlcl_idb", "..\utils\mysqlcl_idb\libmysqlcl_idb.vcxproj", "{0BBAEACB-3336-4406-ACFB-255669A3B9CF}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libudf_mysql", "..\utils\udfsdk\libudf_mysql.vcxproj", "{51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libudfsdk", "..\utils\udfsdk\libudfsdk.vcxproj", "{021A7045-6334-478F-9A4C-79F8200B504A}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libthrift", "..\utils\thrift\libthrift.vcxproj", "{E9A8354A-5317-479F-8A7B-C4596666D0BE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libquerytele", "..\utils\querytele\libquerytele.vcxproj", "{599E3C29-63BA-4F25-AEAE-BF413AD93312}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - EnterpriseRelease|Mixed Platforms = EnterpriseRelease|Mixed Platforms - EnterpriseRelease|Win32 = EnterpriseRelease|Win32 - EnterpriseRelease|x64 = EnterpriseRelease|x64 - Release|Mixed Platforms = Release|Mixed Platforms - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {1CE8E777-042F-48E2-B146-2B411E14F765}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Debug|Win32.ActiveCfg = Debug|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Debug|Win32.Build.0 = Debug|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Debug|x64.ActiveCfg = Debug|x64 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Debug|x64.Build.0 = Debug|x64 - {1CE8E777-042F-48E2-B146-2B411E14F765}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {1CE8E777-042F-48E2-B146-2B411E14F765}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Release|Mixed Platforms.Build.0 = Release|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Release|Win32.ActiveCfg = Release|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Release|Win32.Build.0 = Release|Win32 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Release|x64.ActiveCfg = Release|x64 - {1CE8E777-042F-48E2-B146-2B411E14F765}.Release|x64.Build.0 = Release|x64 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Debug|Win32.ActiveCfg = Debug|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Debug|Win32.Build.0 = Debug|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Debug|x64.ActiveCfg = Debug|x64 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Debug|x64.Build.0 = Debug|x64 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Release|Mixed Platforms.Build.0 = Release|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Release|Win32.ActiveCfg = Release|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Release|Win32.Build.0 = Release|Win32 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Release|x64.ActiveCfg = Release|x64 - {C543C9A1-B4E0-4BAD-9FC2-2AFEEA952FC5}.Release|x64.Build.0 = Release|x64 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Debug|Win32.ActiveCfg = Debug|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Debug|Win32.Build.0 = Debug|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Debug|x64.ActiveCfg = Debug|x64 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Debug|x64.Build.0 = Debug|x64 - {226D1F60-1E33-401B-A333-D583AF69B86E}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {226D1F60-1E33-401B-A333-D583AF69B86E}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Release|Mixed Platforms.Build.0 = Release|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Release|Win32.ActiveCfg = Release|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Release|Win32.Build.0 = Release|Win32 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Release|x64.ActiveCfg = Release|x64 - {226D1F60-1E33-401B-A333-D583AF69B86E}.Release|x64.Build.0 = Release|x64 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Debug|Win32.ActiveCfg = Debug|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Debug|Win32.Build.0 = Debug|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Debug|x64.ActiveCfg = Debug|x64 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Debug|x64.Build.0 = Debug|x64 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Release|Mixed Platforms.Build.0 = Release|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Release|Win32.ActiveCfg = Release|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Release|Win32.Build.0 = Release|Win32 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Release|x64.ActiveCfg = Release|x64 - {4F0851D3-B782-4F12-B748-73EFA2DA586B}.Release|x64.Build.0 = Release|x64 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Debug|Win32.ActiveCfg = Debug|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Debug|Win32.Build.0 = Debug|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Debug|x64.ActiveCfg = Debug|x64 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Debug|x64.Build.0 = Debug|x64 - {004899A2-3CAB-4796-B030-34A20AC285C9}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {004899A2-3CAB-4796-B030-34A20AC285C9}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Release|Mixed Platforms.Build.0 = Release|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Release|Win32.ActiveCfg = Release|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Release|Win32.Build.0 = Release|Win32 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Release|x64.ActiveCfg = Release|x64 - {004899A2-3CAB-4796-B030-34A20AC285C9}.Release|x64.Build.0 = Release|x64 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Debug|Win32.ActiveCfg = Debug|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Debug|Win32.Build.0 = Debug|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Debug|x64.ActiveCfg = Debug|x64 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Debug|x64.Build.0 = Debug|x64 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Release|Mixed Platforms.Build.0 = Release|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Release|Win32.ActiveCfg = Release|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Release|Win32.Build.0 = Release|Win32 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Release|x64.ActiveCfg = Release|x64 - {2BE469D2-D854-4480-BFE0-34DE89C557B2}.Release|x64.Build.0 = Release|x64 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Debug|Win32.ActiveCfg = Debug|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Debug|Win32.Build.0 = Debug|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Debug|x64.ActiveCfg = Debug|x64 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Debug|x64.Build.0 = Debug|x64 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Release|Mixed Platforms.Build.0 = Release|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Release|Win32.ActiveCfg = Release|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Release|Win32.Build.0 = Release|Win32 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Release|x64.ActiveCfg = Release|x64 - {FC0BA86E-2CC2-4CE8-AC62-16B662FE5B29}.Release|x64.Build.0 = Release|x64 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Debug|Win32.ActiveCfg = Debug|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Debug|Win32.Build.0 = Debug|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Debug|x64.ActiveCfg = Debug|x64 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Debug|x64.Build.0 = Debug|x64 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Release|Mixed Platforms.Build.0 = Release|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Release|Win32.ActiveCfg = Release|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Release|Win32.Build.0 = Release|Win32 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Release|x64.ActiveCfg = Release|x64 - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2}.Release|x64.Build.0 = Release|x64 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Debug|Win32.ActiveCfg = Debug|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Debug|Win32.Build.0 = Debug|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Debug|x64.ActiveCfg = Debug|x64 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Debug|x64.Build.0 = Debug|x64 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Release|Mixed Platforms.Build.0 = Release|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Release|Win32.ActiveCfg = Release|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Release|Win32.Build.0 = Release|Win32 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Release|x64.ActiveCfg = Release|x64 - {054CFC82-A54E-4EA5-8CE7-1281D2ED9ECE}.Release|x64.Build.0 = Release|x64 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Debug|Win32.ActiveCfg = Debug|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Debug|Win32.Build.0 = Debug|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Debug|x64.ActiveCfg = Debug|x64 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Debug|x64.Build.0 = Debug|x64 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Release|Mixed Platforms.Build.0 = Release|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Release|Win32.ActiveCfg = Release|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Release|Win32.Build.0 = Release|Win32 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Release|x64.ActiveCfg = Release|x64 - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA}.Release|x64.Build.0 = Release|x64 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Debug|Win32.ActiveCfg = Debug|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Debug|Win32.Build.0 = Debug|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Debug|x64.ActiveCfg = Debug|x64 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Debug|x64.Build.0 = Debug|x64 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Release|Mixed Platforms.Build.0 = Release|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Release|Win32.ActiveCfg = Release|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Release|Win32.Build.0 = Release|Win32 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Release|x64.ActiveCfg = Release|x64 - {414A47EB-55E3-4251-99B0-95D86FE5580D}.Release|x64.Build.0 = Release|x64 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Debug|Win32.ActiveCfg = Debug|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Debug|Win32.Build.0 = Debug|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Debug|x64.ActiveCfg = Debug|x64 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Debug|x64.Build.0 = Debug|x64 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Release|Mixed Platforms.Build.0 = Release|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Release|Win32.ActiveCfg = Release|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Release|Win32.Build.0 = Release|Win32 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Release|x64.ActiveCfg = Release|x64 - {AB342A0E-604E-4BBC-B43E-08DF3FA37F9B}.Release|x64.Build.0 = Release|x64 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Debug|Win32.ActiveCfg = Debug|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Debug|Win32.Build.0 = Debug|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Debug|x64.ActiveCfg = Debug|x64 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Debug|x64.Build.0 = Debug|x64 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Release|Mixed Platforms.Build.0 = Release|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Release|Win32.ActiveCfg = Release|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Release|Win32.Build.0 = Release|Win32 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Release|x64.ActiveCfg = Release|x64 - {9AE60D66-99F6-4CCB-902D-3814A12AE0A9}.Release|x64.Build.0 = Release|x64 - {A13E870A-7A9E-4027-8E17-204398225361}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Debug|Win32.ActiveCfg = Debug|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Debug|Win32.Build.0 = Debug|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Debug|x64.ActiveCfg = Debug|x64 - {A13E870A-7A9E-4027-8E17-204398225361}.Debug|x64.Build.0 = Debug|x64 - {A13E870A-7A9E-4027-8E17-204398225361}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {A13E870A-7A9E-4027-8E17-204398225361}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {A13E870A-7A9E-4027-8E17-204398225361}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Release|Mixed Platforms.Build.0 = Release|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Release|Win32.ActiveCfg = Release|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Release|Win32.Build.0 = Release|Win32 - {A13E870A-7A9E-4027-8E17-204398225361}.Release|x64.ActiveCfg = Release|x64 - {A13E870A-7A9E-4027-8E17-204398225361}.Release|x64.Build.0 = Release|x64 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Debug|Win32.ActiveCfg = Debug|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Debug|Win32.Build.0 = Debug|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Debug|x64.ActiveCfg = Debug|x64 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Debug|x64.Build.0 = Debug|x64 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Release|Mixed Platforms.Build.0 = Release|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Release|Win32.ActiveCfg = Release|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Release|Win32.Build.0 = Release|Win32 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Release|x64.ActiveCfg = Release|x64 - {5362725E-BB90-44A3-9D13-3DE9B5041AD2}.Release|x64.Build.0 = Release|x64 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Debug|Win32.ActiveCfg = Debug|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Debug|Win32.Build.0 = Debug|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Debug|x64.ActiveCfg = Debug|x64 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Debug|x64.Build.0 = Debug|x64 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Release|Mixed Platforms.Build.0 = Release|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Release|Win32.ActiveCfg = Release|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Release|Win32.Build.0 = Release|Win32 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Release|x64.ActiveCfg = Release|x64 - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64}.Release|x64.Build.0 = Release|x64 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Debug|Win32.ActiveCfg = Debug|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Debug|Win32.Build.0 = Debug|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Debug|x64.ActiveCfg = Debug|x64 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Debug|x64.Build.0 = Debug|x64 - {07230DF5-10E9-469E-8075-C0978C0460AD}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {07230DF5-10E9-469E-8075-C0978C0460AD}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Release|Mixed Platforms.Build.0 = Release|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Release|Win32.ActiveCfg = Release|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Release|Win32.Build.0 = Release|Win32 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Release|x64.ActiveCfg = Release|x64 - {07230DF5-10E9-469E-8075-C0978C0460AD}.Release|x64.Build.0 = Release|x64 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Debug|Win32.ActiveCfg = Debug|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Debug|Win32.Build.0 = Debug|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Debug|x64.ActiveCfg = Debug|x64 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Debug|x64.Build.0 = Debug|x64 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Release|Mixed Platforms.Build.0 = Release|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Release|Win32.ActiveCfg = Release|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Release|Win32.Build.0 = Release|Win32 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Release|x64.ActiveCfg = Release|x64 - {AB35CD02-BACD-4E11-8FBC-106DFD9AB1FC}.Release|x64.Build.0 = Release|x64 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Debug|Win32.ActiveCfg = Debug|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Debug|Win32.Build.0 = Debug|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Debug|x64.ActiveCfg = Debug|x64 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Debug|x64.Build.0 = Debug|x64 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Release|Mixed Platforms.Build.0 = Release|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Release|Win32.ActiveCfg = Release|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Release|Win32.Build.0 = Release|Win32 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Release|x64.ActiveCfg = Release|x64 - {B77B5FD1-8CA3-40F6-BA61-2FE51D074119}.Release|x64.Build.0 = Release|x64 - {A9298547-2C38-4116-9063-D09F72A85F43}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Debug|Win32.ActiveCfg = Debug|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Debug|Win32.Build.0 = Debug|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Debug|x64.ActiveCfg = Debug|x64 - {A9298547-2C38-4116-9063-D09F72A85F43}.Debug|x64.Build.0 = Debug|x64 - {A9298547-2C38-4116-9063-D09F72A85F43}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {A9298547-2C38-4116-9063-D09F72A85F43}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {A9298547-2C38-4116-9063-D09F72A85F43}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Release|Mixed Platforms.Build.0 = Release|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Release|Win32.ActiveCfg = Release|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Release|Win32.Build.0 = Release|Win32 - {A9298547-2C38-4116-9063-D09F72A85F43}.Release|x64.ActiveCfg = Release|x64 - {A9298547-2C38-4116-9063-D09F72A85F43}.Release|x64.Build.0 = Release|x64 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Debug|Win32.ActiveCfg = Debug|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Debug|Win32.Build.0 = Debug|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Debug|x64.ActiveCfg = Debug|x64 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Debug|x64.Build.0 = Debug|x64 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Release|Mixed Platforms.Build.0 = Release|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Release|Win32.ActiveCfg = Release|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Release|Win32.Build.0 = Release|Win32 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Release|x64.ActiveCfg = Release|x64 - {E9417C0B-D839-46E2-A2A8-439E6087E873}.Release|x64.Build.0 = Release|x64 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Debug|Win32.ActiveCfg = Debug|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Debug|Win32.Build.0 = Debug|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Debug|x64.ActiveCfg = Debug|x64 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Debug|x64.Build.0 = Debug|x64 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Release|Mixed Platforms.Build.0 = Release|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Release|Win32.ActiveCfg = Release|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Release|Win32.Build.0 = Release|Win32 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Release|x64.ActiveCfg = Release|x64 - {B44BE805-2019-4FCB-B213-45F1D7A73CCD}.Release|x64.Build.0 = Release|x64 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Debug|Win32.ActiveCfg = Debug|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Debug|Win32.Build.0 = Debug|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Debug|x64.ActiveCfg = Debug|x64 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Debug|x64.Build.0 = Debug|x64 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Release|Mixed Platforms.Build.0 = Release|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Release|Win32.ActiveCfg = Release|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Release|Win32.Build.0 = Release|Win32 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Release|x64.ActiveCfg = Release|x64 - {F767A00A-1063-4C0A-B8E3-A27E3F332724}.Release|x64.Build.0 = Release|x64 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Debug|Win32.ActiveCfg = Debug|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Debug|Win32.Build.0 = Debug|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Debug|x64.ActiveCfg = Debug|x64 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Debug|x64.Build.0 = Debug|x64 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Release|Mixed Platforms.Build.0 = Release|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Release|Win32.ActiveCfg = Release|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Release|Win32.Build.0 = Release|Win32 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Release|x64.ActiveCfg = Release|x64 - {033C6CBA-D984-483F-ADC8-825BE20A699D}.Release|x64.Build.0 = Release|x64 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Debug|Win32.ActiveCfg = Debug|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Debug|Win32.Build.0 = Debug|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Debug|x64.ActiveCfg = Debug|x64 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Debug|x64.Build.0 = Debug|x64 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Release|Mixed Platforms.Build.0 = Release|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Release|Win32.ActiveCfg = Release|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Release|Win32.Build.0 = Release|Win32 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Release|x64.ActiveCfg = Release|x64 - {19142D9E-7660-445C-B85D-98E722DFFEA5}.Release|x64.Build.0 = Release|x64 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Debug|Win32.ActiveCfg = Debug|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Debug|Win32.Build.0 = Debug|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Debug|x64.ActiveCfg = Debug|x64 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Debug|x64.Build.0 = Debug|x64 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Release|Mixed Platforms.Build.0 = Release|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Release|Win32.ActiveCfg = Release|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Release|Win32.Build.0 = Release|Win32 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Release|x64.ActiveCfg = Release|x64 - {B9045BCA-0955-4C5E-BCA4-5EE516838119}.Release|x64.Build.0 = Release|x64 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Debug|Win32.ActiveCfg = Debug|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Debug|Win32.Build.0 = Debug|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Debug|x64.ActiveCfg = Debug|x64 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Debug|x64.Build.0 = Debug|x64 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Release|Mixed Platforms.Build.0 = Release|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Release|Win32.ActiveCfg = Release|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Release|Win32.Build.0 = Release|Win32 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Release|x64.ActiveCfg = Release|x64 - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7}.Release|x64.Build.0 = Release|x64 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Debug|Win32.ActiveCfg = Debug|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Debug|Win32.Build.0 = Debug|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Debug|x64.ActiveCfg = Debug|x64 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Debug|x64.Build.0 = Debug|x64 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Release|Mixed Platforms.Build.0 = Release|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Release|Win32.ActiveCfg = Release|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Release|Win32.Build.0 = Release|Win32 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Release|x64.ActiveCfg = Release|x64 - {D1A9BAEF-7612-403A-ACEC-CD6DF09A3F8D}.Release|x64.Build.0 = Release|x64 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Debug|Win32.ActiveCfg = Debug|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Debug|Win32.Build.0 = Debug|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Debug|x64.ActiveCfg = Debug|x64 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Debug|x64.Build.0 = Debug|x64 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Release|Mixed Platforms.Build.0 = Release|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Release|Win32.ActiveCfg = Release|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Release|Win32.Build.0 = Release|Win32 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Release|x64.ActiveCfg = Release|x64 - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E}.Release|x64.Build.0 = Release|x64 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Debug|Win32.ActiveCfg = Debug|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Debug|Win32.Build.0 = Debug|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Debug|x64.ActiveCfg = Debug|x64 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Debug|x64.Build.0 = Debug|x64 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Release|Mixed Platforms.Build.0 = Release|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Release|Win32.ActiveCfg = Release|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Release|Win32.Build.0 = Release|Win32 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Release|x64.ActiveCfg = Release|x64 - {EE6E6244-93A6-4014-A947-EFCB779B87B6}.Release|x64.Build.0 = Release|x64 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Debug|Win32.ActiveCfg = Debug|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Debug|Win32.Build.0 = Debug|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Debug|x64.ActiveCfg = Debug|x64 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Debug|x64.Build.0 = Debug|x64 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Release|Mixed Platforms.Build.0 = Release|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Release|Win32.ActiveCfg = Release|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Release|Win32.Build.0 = Release|Win32 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Release|x64.ActiveCfg = Release|x64 - {10EFDC01-9720-45A3-9290-7C394B459CB0}.Release|x64.Build.0 = Release|x64 - {635981B1-9353-4102-935B-177432EDC072}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Debug|Win32.ActiveCfg = Debug|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Debug|Win32.Build.0 = Debug|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Debug|x64.ActiveCfg = Debug|x64 - {635981B1-9353-4102-935B-177432EDC072}.Debug|x64.Build.0 = Debug|x64 - {635981B1-9353-4102-935B-177432EDC072}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {635981B1-9353-4102-935B-177432EDC072}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {635981B1-9353-4102-935B-177432EDC072}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {635981B1-9353-4102-935B-177432EDC072}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {635981B1-9353-4102-935B-177432EDC072}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {635981B1-9353-4102-935B-177432EDC072}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Release|Mixed Platforms.Build.0 = Release|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Release|Win32.ActiveCfg = Release|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Release|Win32.Build.0 = Release|Win32 - {635981B1-9353-4102-935B-177432EDC072}.Release|x64.ActiveCfg = Release|x64 - {635981B1-9353-4102-935B-177432EDC072}.Release|x64.Build.0 = Release|x64 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Debug|Win32.ActiveCfg = Debug|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Debug|Win32.Build.0 = Debug|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Debug|x64.ActiveCfg = Debug|x64 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Debug|x64.Build.0 = Debug|x64 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Release|Mixed Platforms.Build.0 = Release|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Release|Win32.ActiveCfg = Release|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Release|Win32.Build.0 = Release|Win32 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Release|x64.ActiveCfg = Release|x64 - {36549A0A-BF9F-4642-92E7-FAA10061BD34}.Release|x64.Build.0 = Release|x64 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Debug|Win32.ActiveCfg = Debug|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Debug|Win32.Build.0 = Debug|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Debug|x64.ActiveCfg = Debug|x64 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Debug|x64.Build.0 = Debug|x64 - {DCB5C215-2F35-4439-B94E-C818E0921385}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {DCB5C215-2F35-4439-B94E-C818E0921385}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Release|Mixed Platforms.Build.0 = Release|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Release|Win32.ActiveCfg = Release|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Release|Win32.Build.0 = Release|Win32 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Release|x64.ActiveCfg = Release|x64 - {DCB5C215-2F35-4439-B94E-C818E0921385}.Release|x64.Build.0 = Release|x64 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Debug|Win32.ActiveCfg = Debug|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Debug|Win32.Build.0 = Debug|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Debug|x64.ActiveCfg = Debug|x64 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Debug|x64.Build.0 = Debug|x64 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Release|Mixed Platforms.Build.0 = Release|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Release|Win32.ActiveCfg = Release|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Release|Win32.Build.0 = Release|Win32 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Release|x64.ActiveCfg = Release|x64 - {BCC9E913-1C3D-492B-B245-8F43B4F30C1C}.Release|x64.Build.0 = Release|x64 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Debug|Win32.ActiveCfg = Debug|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Debug|Win32.Build.0 = Debug|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Debug|x64.ActiveCfg = Debug|x64 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Debug|x64.Build.0 = Debug|x64 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Release|Mixed Platforms.Build.0 = Release|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Release|Win32.ActiveCfg = Release|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Release|Win32.Build.0 = Release|Win32 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Release|x64.ActiveCfg = Release|x64 - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F}.Release|x64.Build.0 = Release|x64 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Debug|Win32.ActiveCfg = Debug|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Debug|Win32.Build.0 = Debug|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Debug|x64.ActiveCfg = Debug|x64 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Debug|x64.Build.0 = Debug|x64 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Release|Mixed Platforms.Build.0 = Release|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Release|Win32.ActiveCfg = Release|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Release|Win32.Build.0 = Release|Win32 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Release|x64.ActiveCfg = Release|x64 - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20}.Release|x64.Build.0 = Release|x64 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Debug|Win32.ActiveCfg = Debug|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Debug|Win32.Build.0 = Debug|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Debug|x64.ActiveCfg = Debug|x64 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Debug|x64.Build.0 = Debug|x64 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Release|Mixed Platforms.Build.0 = Release|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Release|Win32.ActiveCfg = Release|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Release|Win32.Build.0 = Release|Win32 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Release|x64.ActiveCfg = Release|x64 - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13}.Release|x64.Build.0 = Release|x64 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Debug|Win32.ActiveCfg = Debug|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Debug|Win32.Build.0 = Debug|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Debug|x64.ActiveCfg = Debug|x64 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Debug|x64.Build.0 = Debug|x64 - {71C00ACF-619C-407D-8A69-995CD27F7809}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {71C00ACF-619C-407D-8A69-995CD27F7809}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Release|Mixed Platforms.Build.0 = Release|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Release|Win32.ActiveCfg = Release|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Release|Win32.Build.0 = Release|Win32 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Release|x64.ActiveCfg = Release|x64 - {71C00ACF-619C-407D-8A69-995CD27F7809}.Release|x64.Build.0 = Release|x64 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Debug|Win32.ActiveCfg = Debug|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Debug|Win32.Build.0 = Debug|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Debug|x64.ActiveCfg = Debug|x64 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Debug|x64.Build.0 = Debug|x64 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Release|Mixed Platforms.Build.0 = Release|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Release|Win32.ActiveCfg = Release|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Release|Win32.Build.0 = Release|Win32 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Release|x64.ActiveCfg = Release|x64 - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3}.Release|x64.Build.0 = Release|x64 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Debug|Win32.ActiveCfg = Debug|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Debug|Win32.Build.0 = Debug|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Debug|x64.ActiveCfg = Debug|x64 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Debug|x64.Build.0 = Debug|x64 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Release|Mixed Platforms.Build.0 = Release|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Release|Win32.ActiveCfg = Release|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Release|Win32.Build.0 = Release|Win32 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Release|x64.ActiveCfg = Release|x64 - {13E96B71-0854-4EA5-A7ED-0950AE10C858}.Release|x64.Build.0 = Release|x64 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Debug|Win32.ActiveCfg = Debug|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Debug|Win32.Build.0 = Debug|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Debug|x64.ActiveCfg = Debug|x64 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Debug|x64.Build.0 = Debug|x64 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Release|Mixed Platforms.Build.0 = Release|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Release|Win32.ActiveCfg = Release|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Release|Win32.Build.0 = Release|Win32 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Release|x64.ActiveCfg = Release|x64 - {6B8C806F-46F7-412F-9FB1-78DFA505597E}.Release|x64.Build.0 = Release|x64 - {0B72A604-0755-4E2C-B74B-C93564847114}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.Debug|Win32.ActiveCfg = Debug|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.Debug|x64.ActiveCfg = Debug|x64 - {0B72A604-0755-4E2C-B74B-C93564847114}.Debug|x64.Build.0 = Debug|x64 - {0B72A604-0755-4E2C-B74B-C93564847114}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {0B72A604-0755-4E2C-B74B-C93564847114}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {0B72A604-0755-4E2C-B74B-C93564847114}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.Release|Mixed Platforms.Build.0 = Release|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.Release|Win32.ActiveCfg = Release|Win32 - {0B72A604-0755-4E2C-B74B-C93564847114}.Release|x64.ActiveCfg = Release|x64 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Debug|Win32.ActiveCfg = Debug|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Debug|x64.ActiveCfg = Debug|x64 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Debug|x64.Build.0 = Debug|x64 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.EnterpriseRelease|Win32.ActiveCfg = Release|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Release|Mixed Platforms.Build.0 = Release|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Release|Win32.ActiveCfg = Release|Win32 - {E4A08BD5-5F31-499B-A61D-68E4924D9F60}.Release|x64.ActiveCfg = Release|x64 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Debug|Win32.ActiveCfg = Debug|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Debug|x64.ActiveCfg = Debug|x64 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Debug|x64.Build.0 = Debug|x64 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.EnterpriseRelease|Win32.ActiveCfg = Release|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Release|Mixed Platforms.Build.0 = Release|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Release|Win32.ActiveCfg = Release|Win32 - {DB67EB06-04F1-4615-9095-3E5F02DD7008}.Release|x64.ActiveCfg = Release|x64 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Debug|Win32.ActiveCfg = Debug|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Debug|Win32.Build.0 = Debug|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Debug|x64.ActiveCfg = Debug|x64 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Debug|x64.Build.0 = Debug|x64 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Release|Mixed Platforms.Build.0 = Release|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Release|Win32.ActiveCfg = Release|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Release|Win32.Build.0 = Release|Win32 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Release|x64.ActiveCfg = Release|x64 - {85C9D0FD-0C04-47DB-9AF3-B71BE89A3034}.Release|x64.Build.0 = Release|x64 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Debug|Win32.ActiveCfg = Debug|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Debug|Win32.Build.0 = Debug|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Debug|x64.ActiveCfg = Debug|x64 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Debug|x64.Build.0 = Debug|x64 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Release|Mixed Platforms.Build.0 = Release|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Release|Win32.ActiveCfg = Release|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Release|Win32.Build.0 = Release|Win32 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Release|x64.ActiveCfg = Release|x64 - {B160A65B-D07D-4CCD-A0FD-6A0800E9F595}.Release|x64.Build.0 = Release|x64 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Debug|Win32.ActiveCfg = Debug|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Debug|Win32.Build.0 = Debug|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Debug|x64.ActiveCfg = Debug|x64 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Debug|x64.Build.0 = Debug|x64 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Release|Mixed Platforms.Build.0 = Release|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Release|Win32.ActiveCfg = Release|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Release|Win32.Build.0 = Release|Win32 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Release|x64.ActiveCfg = Release|x64 - {4BC37219-E09D-4133-98C4-CF0386657DF6}.Release|x64.Build.0 = Release|x64 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Debug|Win32.ActiveCfg = Debug|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Debug|Win32.Build.0 = Debug|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Debug|x64.ActiveCfg = Debug|x64 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Debug|x64.Build.0 = Debug|x64 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Release|Mixed Platforms.Build.0 = Release|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Release|Win32.ActiveCfg = Release|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Release|Win32.Build.0 = Release|Win32 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Release|x64.ActiveCfg = Release|x64 - {E95FECB8-1B06-41FF-8E1D-40B7E6841765}.Release|x64.Build.0 = Release|x64 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Debug|Win32.ActiveCfg = Debug|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Debug|Win32.Build.0 = Debug|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Debug|x64.ActiveCfg = Debug|x64 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Debug|x64.Build.0 = Debug|x64 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Release|Mixed Platforms.Build.0 = Release|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Release|Win32.ActiveCfg = Release|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Release|Win32.Build.0 = Release|Win32 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Release|x64.ActiveCfg = Release|x64 - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822}.Release|x64.Build.0 = Release|x64 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Debug|Win32.ActiveCfg = Debug|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Debug|Win32.Build.0 = Debug|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Debug|x64.ActiveCfg = Debug|x64 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Debug|x64.Build.0 = Debug|x64 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Release|Mixed Platforms.Build.0 = Release|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Release|Win32.ActiveCfg = Release|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Release|Win32.Build.0 = Release|Win32 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Release|x64.ActiveCfg = Release|x64 - {B62B74B4-4621-4CF2-AC06-FB84D9CCA66F}.Release|x64.Build.0 = Release|x64 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Debug|Win32.ActiveCfg = Debug|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Debug|Win32.Build.0 = Debug|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Debug|x64.ActiveCfg = Debug|x64 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Debug|x64.Build.0 = Debug|x64 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Release|Mixed Platforms.Build.0 = Release|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Release|Win32.ActiveCfg = Release|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Release|Win32.Build.0 = Release|Win32 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Release|x64.ActiveCfg = Release|x64 - {3238CD73-8FFD-44A7-AA5F-815BEEF8F402}.Release|x64.Build.0 = Release|x64 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Debug|Win32.ActiveCfg = Debug|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Debug|Win32.Build.0 = Debug|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Debug|x64.ActiveCfg = Debug|x64 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Debug|x64.Build.0 = Debug|x64 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.EnterpriseRelease|Win32.ActiveCfg = Release|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Release|Mixed Platforms.Build.0 = Release|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Release|Win32.ActiveCfg = Release|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Release|Win32.Build.0 = Release|Win32 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Release|x64.ActiveCfg = Release|x64 - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F}.Release|x64.Build.0 = Release|x64 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Debug|Win32.ActiveCfg = Debug|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Debug|Win32.Build.0 = Debug|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Debug|x64.ActiveCfg = Debug|x64 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Debug|x64.Build.0 = Debug|x64 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.EnterpriseRelease|Win32.Build.0 = EnterpriseRelease|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Release|Mixed Platforms.Build.0 = Release|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Release|Win32.ActiveCfg = Release|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Release|Win32.Build.0 = Release|Win32 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Release|x64.ActiveCfg = Release|x64 - {0DD34627-B046-4415-80CF-D0FBA4E069CB}.Release|x64.Build.0 = Release|x64 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Debug|Win32.ActiveCfg = Debug|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Debug|Win32.Build.0 = Debug|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Debug|x64.ActiveCfg = Debug|x64 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Debug|x64.Build.0 = Debug|x64 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.EnterpriseRelease|Win32.Build.0 = EnterpriseRelease|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Release|Mixed Platforms.Build.0 = Release|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Release|Win32.ActiveCfg = Release|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Release|Win32.Build.0 = Release|Win32 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Release|x64.ActiveCfg = Release|x64 - {4C8231D7-7A87-4650-AA9C-D7650C1D03EE}.Release|x64.Build.0 = Release|x64 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Debug|Win32.ActiveCfg = Debug|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Debug|Win32.Build.0 = Debug|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Debug|x64.ActiveCfg = Debug|x64 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Debug|x64.Build.0 = Debug|x64 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.EnterpriseRelease|Win32.Build.0 = EnterpriseRelease|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Release|Mixed Platforms.Build.0 = Release|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Release|Win32.ActiveCfg = Release|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Release|Win32.Build.0 = Release|Win32 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Release|x64.ActiveCfg = Release|x64 - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F}.Release|x64.Build.0 = Release|x64 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Debug|Win32.ActiveCfg = Debug|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Debug|Win32.Build.0 = Debug|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Debug|x64.ActiveCfg = Debug|x64 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Debug|x64.Build.0 = Debug|x64 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.EnterpriseRelease|Win32.Build.0 = EnterpriseRelease|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Release|Mixed Platforms.Build.0 = Release|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Release|Win32.ActiveCfg = Release|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Release|Win32.Build.0 = Release|Win32 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Release|x64.ActiveCfg = Release|x64 - {0BBAEACB-3336-4406-ACFB-255669A3B9CF}.Release|x64.Build.0 = Release|x64 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Debug|Win32.ActiveCfg = Debug|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Debug|Win32.Build.0 = Debug|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Debug|x64.ActiveCfg = Debug|x64 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Debug|x64.Build.0 = Debug|x64 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.EnterpriseRelease|Win32.Build.0 = EnterpriseRelease|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Release|Mixed Platforms.Build.0 = Release|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Release|Win32.ActiveCfg = Release|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Release|Win32.Build.0 = Release|Win32 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Release|x64.ActiveCfg = Release|x64 - {51ACB58A-6581-482E-BEBE-B85D0BB5A1ED}.Release|x64.Build.0 = Release|x64 - {021A7045-6334-478F-9A4C-79F8200B504A}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Debug|Win32.ActiveCfg = Debug|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Debug|Win32.Build.0 = Debug|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Debug|x64.ActiveCfg = Debug|x64 - {021A7045-6334-478F-9A4C-79F8200B504A}.Debug|x64.Build.0 = Debug|x64 - {021A7045-6334-478F-9A4C-79F8200B504A}.EnterpriseRelease|Mixed Platforms.ActiveCfg = EnterpriseRelease|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.EnterpriseRelease|Mixed Platforms.Build.0 = EnterpriseRelease|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.EnterpriseRelease|Win32.ActiveCfg = EnterpriseRelease|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.EnterpriseRelease|Win32.Build.0 = EnterpriseRelease|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {021A7045-6334-478F-9A4C-79F8200B504A}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {021A7045-6334-478F-9A4C-79F8200B504A}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Release|Mixed Platforms.Build.0 = Release|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Release|Win32.ActiveCfg = Release|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Release|Win32.Build.0 = Release|Win32 - {021A7045-6334-478F-9A4C-79F8200B504A}.Release|x64.ActiveCfg = Release|x64 - {021A7045-6334-478F-9A4C-79F8200B504A}.Release|x64.Build.0 = Release|x64 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Debug|Win32.ActiveCfg = Debug|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Debug|Win32.Build.0 = Debug|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Debug|x64.ActiveCfg = Debug|x64 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Debug|x64.Build.0 = Debug|x64 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.EnterpriseRelease|Mixed Platforms.ActiveCfg = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.EnterpriseRelease|Mixed Platforms.Build.0 = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.EnterpriseRelease|Win32.ActiveCfg = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.EnterpriseRelease|Win32.Build.0 = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Release|Mixed Platforms.Build.0 = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Release|Win32.ActiveCfg = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Release|Win32.Build.0 = Release|Win32 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Release|x64.ActiveCfg = Release|x64 - {E9A8354A-5317-479F-8A7B-C4596666D0BE}.Release|x64.Build.0 = Release|x64 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Debug|Mixed Platforms.Build.0 = Debug|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Debug|Win32.ActiveCfg = Debug|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Debug|Win32.Build.0 = Debug|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Debug|x64.ActiveCfg = Debug|x64 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Debug|x64.Build.0 = Debug|x64 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.EnterpriseRelease|Mixed Platforms.ActiveCfg = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.EnterpriseRelease|Mixed Platforms.Build.0 = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.EnterpriseRelease|Win32.ActiveCfg = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.EnterpriseRelease|Win32.Build.0 = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.EnterpriseRelease|x64.ActiveCfg = EnterpriseRelease|x64 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.EnterpriseRelease|x64.Build.0 = EnterpriseRelease|x64 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Release|Mixed Platforms.ActiveCfg = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Release|Mixed Platforms.Build.0 = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Release|Win32.ActiveCfg = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Release|Win32.Build.0 = Release|Win32 - {599E3C29-63BA-4F25-AEAE-BF413AD93312}.Release|x64.ActiveCfg = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/build/Nightly.bat b/build/Nightly.bat deleted file mode 100644 index 63014d63..00000000 --- a/build/Nightly.bat +++ /dev/null @@ -1,80 +0,0 @@ -:: This nightly script is customized for srvbldwin1 -:: It probably needs to be modified if used for other machines -:: Nightly.bat needs be moved to c:\ and run from there. - -::@echo off - -:: If there's a command line branch, use it. -set branch=%1 -IF "%1" == "" ( -:: No command line, use file - FOR /F %%i IN (branch.txt) DO set branch=%%i -) -echo %branch% -IF "%branch%" == "trunk" ( - set basedir=\InfiniDB -) ELSE ( - set basedir=\InfiniDB_%branch% -) - -:: Setup branch.txt for next run -:: default is to run trunk next -set nextrun=trunk -echo %nextrun% -IF "%branch%" == "trunk" set nextrun=4.0 -echo %nextrun% -IF "%branch%" == "4.0" set nextrun=4.5 -echo %nextrun% -echo %nextrun% > branch.txt - -echo Building %branch% at %basedir% - -:: Checkout the server -bash %basedir%\genii\tools\reserveStacks\stack reserve srvbldwin1 nightly f:/Calpont - -:: create a time with a leading zero if hour < 10 -set MYTIME=%TIME: =0% -set archivedirname=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%@%MYTIME:~0,2%.%MYTIME:~3,2%.%MYTIME:~6,2% - -echo Building the application -cd %basedir%\genii\build - -call Build.bat %branch% -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER - -echo Running the installer -cd %basedir%\genii\utils\winport -InfiniDB64-ent.exe /S /D=f:\Calpont -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -cd \ - -echo Waiting for InfiniDB service to boot -call svcwait.bat -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -echo InfiniDB service is ready - -echo copying the installer to calweb -call %basedir%\genii\build\CopyToCalweb.bat - -echo running the nightly test scripts -cd %basedir%\genii\mysql\queries\nightly\srvswdev11 -bash ./go.sh f:/Calpont -GOTO QUIT - -:ERROR_HANDLER -echo. -echo Build error occured. Nightly tests not run >> build.log -cd \ -expect %basedir%/genii/build/CopyLog.sh -xcopy build.log f:\nightly\build_log\%archivedirname%\ -bash %basedir%\genii\tools\reserveStacks\stack release srvbldwin1 nightly f:/Calpont -exit 1 - -:QUIT -echo nightly tests complete >> go.log -echo %date% %time% >> go.log -cd \ -expect %basedir%/genii/build/CopyLog.sh -xcopy build.log f:\nightly\build_log\%archivedirname%\ -bash %basedir%\genii\tools\reserveStacks\stack release srvbldwin1 nightly f:/Calpont -:END \ No newline at end of file diff --git a/build/README.md b/build/README.md deleted file mode 100644 index a5b17794..00000000 --- a/build/README.md +++ /dev/null @@ -1,21 +0,0 @@ -This is InfiniDB 4.0. -===================== - -To build InfiniDB from source you will need: - - * a CentOS/RHEL 5/6, debian 5/6 or Ubuntu 10/12 linux host configured for software development - -Along with a working C++ compiler and GNU software development tools you will need the following extra packages: - - * expect - * zlib-devel - * ncurses-devel - * libxml2-devel - * readline-devel - -Clone or download this repository. - - git clone https://github.com/infinidb/infinidb - cd infinidb - ./build/src-build --prefix=$HOME - diff --git a/build/Switch.bat b/build/Switch.bat deleted file mode 100644 index 9bd4e6e2..00000000 --- a/build/Switch.bat +++ /dev/null @@ -1,36 +0,0 @@ -::@echo off -IF NOT EXIST C:\InfiniDB_3.6\NUL GOTO SWITCH_to_trunk -IF NOT EXIST C:\InfiniDB_4.0\NUL GOTO SWITCH_to_3.6 -IF NOT EXIST C:\InfiniDB_trunk\NUL GOTO SWITCH_to_4.0 - -:SWITCH_to_trunk -echo switching to trunk -REN "\InfiniDB" "InfiniDB_3.6" -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -REN "\InfiniDB_trunk" "InfiniDB" -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -echo Switched to InfiniDB trunk -GOTO COMPLETE - -:SWITCH_to_3.6 -echo switching to 3.6 -REN "\InfiniDB" "InfiniDB_4.0" -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -REN "\InfiniDB_3.6" "InfiniDB" -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -echo Switched to InfiniDB 3.6 -GOTO COMPLETE - -:SWITCH_to_4.0 -echo switching to 4.0 -REN "\InfiniDB" "InfiniDB_trunk" -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -REN "\InfiniDB_4.0" "InfiniDB" -IF %ERRORLEVEL% NEQ 0 GOTO ERROR_HANDLER -echo Switched to InfiniDB 4.0 -GOTO COMPLETE - -:ERROR_HANDLER -echo failed to switch - -:COMPLETE diff --git a/build/bb_fix_rules.sh b/build/bb_fix_rules.sh new file mode 100755 index 00000000..9db7fb36 --- /dev/null +++ b/build/bb_fix_rules.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# $Id$ + +test -f rules.tmpl || exit 1 + +mv -f rules.tmpl temp +sed 's/^DEBUG_FLAGS=.*$/DEBUG_FLAGS=-g0 -O3 -fno-strict-aliasing/g' rules.tmpl +rm -f temp + diff --git a/build/bb_pre_build.sh b/build/bb_pre_build.sh deleted file mode 100755 index 2d0948c7..00000000 --- a/build/bb_pre_build.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash - -prefix="$1" - -if [ -z "$prefix" ]; then - echo "usage: $0 destdir" 1>&2 - exit 1 -fi - -rm -rf infinidb mysql infinidb-ent - -git clone http://srvgip1.calpont.com/repos/infinidb.git -cd infinidb -git checkout develop -cd .. - -git clone https://github.com/infinidb/mysql.git -cd mysql -git checkout develop -cd .. - -git clone http://srvgip1.calpont.com/repos/infinidb-ent.git -cd infinidb-ent -git checkout develop -cd .. - -cd infinidb - -mkdir -p export/{include,lib,etc,share,bin,sbin,post} - -cp -r utils/autoconf/* . -autoreconf -libtoolize --force --install - -./configure --prefix=$prefix - diff --git a/build/build-boost-win.bat b/build/build-boost-win.bat deleted file mode 100644 index e4620edc..00000000 --- a/build/build-boost-win.bat +++ /dev/null @@ -1,11 +0,0 @@ -REM You need to uncomment one of these sections below at a time -REM Then you need to copy the libs from stage to \InfiniDB -REM -REM build just 64-bit release libs -REM b2 --clean -b2 --with-date_time --with-filesystem --with-regex --with-system --with-thread --with-chrono address-model=64 variant=release stage - -REM build just 64-bit debug libs -REM bjam --clean -REM bjam --with-date_time --with-filesystem --with-regex --with-system --with-thread address-model=64 variant=debug stage - diff --git a/build/build-branch.mysql b/build/build-branch.mysql deleted file mode 100755 index 165f7439..00000000 --- a/build/build-branch.mysql +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -branch=$1 - -prefix=/usr/local/Calpont -extra_ld_flags="-Wl,-rpath -Wl,$prefix/mysql/lib/mysql -Wl,-rpath -Wl,$prefix/lib" - -export LD_LIBRARY_PATH=/usr/local/gcc45/lib64:/usr/local/gmp43/lib:/usr/local/mpfr24/lib:/usr/local/mpc08/lib -export PATH=/usr/local/gcc45/bin:/usr/local/bin:/bin:/usr/bin -export CC=/usr/local/gcc45/bin/gcc -export CXX=/usr/local/gcc45/bin/g++ - -cd $HOME -updateGenii.pl -b $branch > updateBranch-$branch.log 2>&1 -rm -rf mysql-5.1.39 -tar -zxf mysql-5.1.39.tar.gz -cd mysql-5.1.39 -cp $HOME/$branch/dbcon/mysql/configure.in . -cd sql -cp $HOME/$branch/dbcon/mysql/*.yy . -cp $HOME/$branch/dbcon/mysql/*.h . -cp $HOME/$branch/dbcon/mysql/*.cc . -if [ -f $HOME/$branch/dbcon/mysql/Makefile.am.mysql ]; then - cp $HOME/$branch/dbcon/mysql/Makefile.am.mysql Makefile.am -fi -if [ -f $HOME/$branch/utils/loggingcpp/errorids.h ]; then - cp $HOME/$branch/utils/loggingcpp/errorids.h . -fi -cd .. - -for extras in include mysys; do - if [ -d $HOME/$branch/dbcon/mysql/$extras ]; then - cp $HOME/$branch/dbcon/mysql/$extras/*.h $extras - fi -done - -autoreconf -./configure --prefix=$prefix/mysql --without-libedit --with-readline \ - --with-plugins=csv,heap,myisam,myisammrg,partition --with-mysqld-ldflags="$extra_ld_flags" \ - --with-client-ldflags="$extra_ld_flags" --with-extra-charsets=all --with-ssl -(make && make install) > $HOME/make-branch-$branch.log 2>&1 -cd $HOME/$branch/dbcon/mysql -cp files.lst $prefix/mysql -cp install_calpont_mysql.sh $prefix/mysql -cp my.cnf $prefix/mysql -cp mysql-Calpont $prefix/mysql - diff --git a/build/build-genii.mysql b/build/build-genii.mysql deleted file mode 100755 index 2ac0b091..00000000 --- a/build/build-genii.mysql +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -branch=genii - -prefix=/usr/local/Calpont -extra_ld_flags="-Wl,-rpath -Wl,$prefix/mysql/lib/mysql -Wl,-rpath -Wl,$prefix/lib" - -export LD_LIBRARY_PATH=/usr/local/gcc45/lib64:/usr/local/gmp43/lib:/usr/local/mpfr24/lib:/usr/local/mpc08/lib -export PATH=/usr/local/gcc45/bin:/usr/local/bin:/bin:/usr/bin -export CC=/usr/local/gcc45/bin/gcc -export CXX=/usr/local/gcc45/bin/g++ - -cd $HOME -updateGenii.pl > updateGenii.log 2>&1 -rm -rf mysql-5.1.39 -tar -zxf mysql-5.1.39.tar.gz -cd mysql-5.1.39 -cp $HOME/$branch/dbcon/mysql/configure.in . -cd sql -cp $HOME/$branch/dbcon/mysql/*.yy . -cp $HOME/$branch/dbcon/mysql/*.h . -cp $HOME/$branch/dbcon/mysql/*.cc . -if [ -f $HOME/$branch/dbcon/mysql/Makefile.am.mysql ]; then - cp $HOME/$branch/dbcon/mysql/Makefile.am.mysql Makefile.am -fi -if [ -f $HOME/$branch/utils/loggingcpp/errorids.h ]; then - cp $HOME/$branch/utils/loggingcpp/errorids.h . -fi -cd .. - -for extras in include mysys; do - if [ -d $HOME/$branch/dbcon/mysql/$extras ]; then - cp $HOME/$branch/dbcon/mysql/$extras/*.h $extras - fi -done - -autoreconf -./configure --prefix=$prefix/mysql --without-libedit --with-readline \ - --with-plugins=csv,heap,myisam,myisammrg,partition --with-mysqld-ldflags="$extra_ld_flags" \ - --with-client-ldflags="$extra_ld_flags" --with-extra-charsets=all --with-ssl -(make && make install) > $HOME/make-$branch.log 2>&1 -cd $HOME/$branch/dbcon/mysql -cp files.lst $prefix/mysql -cp install_calpont_mysql.sh $prefix/mysql -cp my.cnf $prefix/mysql -cp mysql-Calpont $prefix/mysql - diff --git a/build/build_rpms b/build/build_rpms index d85895d9..8d6b1fc9 100755 --- a/build/build_rpms +++ b/build/build_rpms @@ -1,31 +1,27 @@ #!/bin/bash # -# $Id: build_rpms 1734 2012-10-25 18:07:16Z dhill $ +# $Id: build_rpms 1735 2012-10-25 18:07:50Z dhill $ # -verbose=0 -mysqldir=/usr/local/Calpont/mysql - -usage() -{ -cat <&2 - fi + ;; + \? | *) echo $usage + exit 1 + ;; + esac done +shift $((OPTIND - 1)) #try to find project root while [ ! -d dbcon ]; do @@ -45,7 +41,7 @@ fi . ./build/releasenum # make the install package -buildroot=$HOME/rpm/BUILD/infinidb-$version-$release +buildroot=$HOME/rpm/BUILD/calpont-$version-$release rm -rf $buildroot mkdir -p $buildroot @@ -54,15 +50,7 @@ tar -cf - --exclude 'export/include' --exclude 'export/*.tar' export | tar -C $b mv $buildroot/export $buildroot/Calpont #get mysql server files -if [ ! -d $mysqldir ]; then - echo -e "\nDidn't find MySQL install: $mysqldir!" 1>&2 - exit 1 -fi -pushd $mysqldir > /dev/null -if [ ! -f files.lst ]; then - echo -e "\nDidn't find files.lst in $mysqldir!" 1>&2 - exit 1 -fi +pushd /usr/local/Calpont/mysql > /dev/null mkdir -p $buildroot/Calpont/mysql cpio -pdmu --quiet $buildroot/Calpont/mysql < files.lst popd >/dev/null @@ -86,7 +74,7 @@ for file in bulkload.sh cleanup.sh dbbuilder.sh dbload.sh cpimport.sh bulkloadp. done rm -f $buildroot/Calpont/lib/libidbboot.a -rm -f $buildroot/Calpont/lib/libiberty.a +rm -f $buildroot/Calpont/bin/amazonInstaller mkdir -p $HOME/rpm/BUILD $HOME/rpm/RPMS $HOME/rpm/SRPMS $HOME/rpm/SPECS $HOME/rpm/tmp @@ -96,6 +84,20 @@ if [ ! -f $HOME/.rpmmacros ]; then %_tmppath $HOME/rpm/tmp # Change to 1 if you want to abort on unpackaged files %_unpackaged_files_terminate_build 0 +# Don't build debuginfo packages +%debug_package %{nil} +# Turn off post install step that strips symbols +%__os_install_post %{nil} +# Turn off perl module probes +%__perl_requires %{nil} +EOD +fi + +egrep -qs __perl_requires $HOME/.rpmmacros +if [ $? -ne 0 ]; then + cat >> $HOME/.rpmmacros </tmp/rpmbuild.out.$$ 2>&1 +rpmbuild $target -ba $HOME/rpm/SPECS/calpont.spec >/tmp/rpmbuild.out.$$ 2>&1 rc=$? echo done. -if [ $verbose -gt 0 -o $rc -ne 0 ]; then +if [ $vflg -gt 0 -o $rc -ne 0 ]; then cat /tmp/rpmbuild.out.$$ fi -grep Wrote: /tmp/rpmbuild.out.$$ +if [ $gflg -eq 0 ]; then + rm -f $HOME/rpm/RPMS/x86_64/calpont-datdup-*.x86_64.rpm +fi rm -f /tmp/*.$$ diff --git a/build/calpont.spec.in b/build/calpont.spec.in new file mode 100644 index 00000000..c8ee3353 --- /dev/null +++ b/build/calpont.spec.in @@ -0,0 +1,400 @@ +# +# $Id$ +# +Summary: Calpont InfiniDB community software +Name: calpont +@@VERSION@@ +@@RELEASE@@ +Vendor: Calpont Corp. +URL: http://www.calpont.com/ +@@PACKAGER@@ +Group: Applications +License: GPL +BuildRoot: %{_tmppath}/%{name}-%{release}-buildroot +%ifarch x86_64 +Provides: libconfigcpp.so()(64bit), libddlpackage.so()(64bit), libddlpackageproc.so()(64bit), libdmlpackage.so()(64bit), libdmlpackageproc.so()(64bit), libexecplan.so()(64bit), libloggingcpp.so()(64bit), libmessageqcpp.so()(64bit), liboamcpp.so()(64bit), libsnmpmanager.so()(64bit), libthreadpool.so()(64bit), libwriteengine.so()(64bit), libbrm.so()(64bit), librwlock.so()(64bit), libfuncexp.so()(64bit), libjoblist.so()(64bit), libdataconvert.so()(64bit), libsm.so()(64bit), libjoiner.so()(64bit), librowgroup.so()(64bit), libcacheutils.so()(64bit), libreplaytxnlog.so()(64bit), libmulticast.so()(64bit), libcommon.so()(64bit), libboost_idb.so()(64bit), libwriteengineclient.so()(64bit), libddlcleanuputil.so()(64bit) libmysqlcl_idb.so()(64bit), libbatchloader.so()(64bit), libwriteengineredistribute.so()(64bit), libquerystats.so()(64bit) +%else +Provides: libconfigcpp.so, libddlpackage.so, libddlpackageproc.so, libdmlpackage.so, libdmlpackageproc.so, libexecplan.so, libloggingcpp.so, libmessageqcpp.so, liboamcpp.so, libsnmpmanager.so, libthreadpool.so, libwriteengine.so, libbrm.so, librwlock.so, libfuncexp.so, libjoblist.so, libdataconvert.so, libsm.so, libjoiner.so, librowgroup.so, libcacheutils.so, libreplaytxnlog.so, libmulticast.so, libcommon.so, libboost_idb.so, libddlcleanuputil.so, libwriteengineclient.so libmysqlcl_idb.so, libwriteengineredistribute.so, libquerystats.so +%endif + +%description +Copyright (c) 2012 Calpont Corp., all rights reserved +Calpont InfiniDB community binary files +@@BUILDINFO@@ + +%package mysql +Summary: Calpont InfiniDB community software MySQL connector +Group: Applications +Requires: calpont = %{version}, calpont-mysqld >= 3.5 +%ifarch x86_64 +Provides: libcalmysql.so()(64bit) +%else +Provides: libcalmysql.so +%endif + +%description mysql +Calpont InfiniDB community MySQL connector binary files + +%package mysqld +Summary: Calpont InfiniDB community software MySQL server +Group: Applications + +%description mysqld +Calpont InfiniDB community MySQL 5.1.39 server binary files + +%prep + +%build + +%install +mkdir -p %{buildroot}/usr/local +tar -C $RPM_BUILD_DIR/%{name}-%{version}-%{release} -cf - . | tar -C %{buildroot}/usr/local -xf - + +%clean +rm -rf $RPM_BUILD_ROOT $RPM_BUILD_DIR/%{name}-%{version}-%{release} + +%changelog + +%files +%defattr(-, root, root) + +/usr/local/Calpont/COPYING +/usr/local/Calpont/README +/usr/local/Calpont/INSTALL +/usr/local/Calpont/releasenum + +/usr/local/Calpont/local/module + +/usr/local/Calpont/bin/DDLProc +/usr/local/Calpont/bin/ExeMgr +/usr/local/Calpont/bin/DMLProc +/usr/local/Calpont/bin/WriteEngineServer +/usr/local/Calpont/bin/cpimport +/usr/local/Calpont/bin/post-install +/usr/local/Calpont/bin/post-mysql-install +/usr/local/Calpont/bin/post-mysqld-install +/usr/local/Calpont/bin/pre-uninstall +/usr/local/Calpont/bin/PrimProc +/usr/local/Calpont/bin/DecomSvr +/usr/local/Calpont/bin/calpontLogRotate +/usr/local/Calpont/bin/transactionLog +/usr/local/Calpont/bin/ReplayTransactionLog +/usr/local/Calpont/bin/transactionLogArchiver.sh +/usr/local/Calpont/bin/startupTests.sh +/usr/local/Calpont/bin/run.sh +/usr/local/Calpont/bin/upgrade-infinidb.sh +/usr/local/Calpont/bin/os_check.sh +/usr/local/Calpont/bin/calpontSyslog +/usr/local/Calpont/bin/calpontSyslog-ng +/usr/local/Calpont/bin/syslogSetup.sh +# Tools... +/usr/local/Calpont/bin/dbbuilder +/usr/local/Calpont/bin/dumpcol +/usr/local/Calpont/bin/oid2file +/usr/local/Calpont/bin/editem +/usr/local/Calpont/bin/evalcol +/usr/local/Calpont/bin/cpimport.bin +/usr/local/Calpont/bin/load_brm +/usr/local/Calpont/bin/save_brm +/usr/local/Calpont/bin/dbrmctl +/usr/local/Calpont/bin/controllernode +/usr/local/Calpont/bin/reset_locks +/usr/local/Calpont/bin/rollback +/usr/local/Calpont/bin/workernode +/usr/local/Calpont/bin/colxml +/usr/local/Calpont/bin/getConfig +/usr/local/Calpont/bin/SesMgr +/usr/local/Calpont/bin/dumpVss +/usr/local/Calpont/bin/editTxn +/usr/local/Calpont/bin/dumpobm +/usr/local/Calpont/bin/file2oid.pl +/usr/local/Calpont/bin/cplogger +/usr/local/Calpont/bin/clearShm +/usr/local/Calpont/bin/setConfig +/usr/local/Calpont/bin/configxml.sh +/usr/local/Calpont/bin/infinidb +/usr/local/Calpont/bin/install-infinidb.sh +/usr/local/Calpont/bin/calpontAlias +/usr/local/Calpont/bin/viewtablelock +/usr/local/Calpont/bin/cleartablelock +/usr/local/Calpont/bin/ddlcleanup +/usr/local/Calpont/bin/idbmeminfo +/usr/local/Calpont/bin/print_journal +/usr/local/Calpont/bin/infinidb.def +/usr/local/Calpont/bin/redistributeDB +# +%config /usr/local/Calpont/etc/Calpont.xml +%config /usr/local/Calpont/etc/ConsoleCmds.xml +%config /usr/local/Calpont/etc/ProcessConfig.xml +%config /usr/local/Calpont/etc/Calpont.xml.singleserver +%config /usr/local/Calpont/etc/ProcessConfig.xml.singleserver +# +/usr/local/Calpont/etc/MessageFile.txt +/usr/local/Calpont/etc/ErrorMessage.txt +# +%config %attr(0666, root, root) /usr/local/Calpont/etc/AlarmConfig.xml +# +/usr/local/Calpont/lib/libconfigcpp.so.1.0.0 +/usr/local/Calpont/lib/libddlpackageproc.so.1.0.0 +/usr/local/Calpont/lib/libddlpackage.so.1.0.0 +/usr/local/Calpont/lib/libdmlpackageproc.so.1.0.0 +/usr/local/Calpont/lib/libdmlpackage.so.1.0.0 +/usr/local/Calpont/lib/libexecplan.so.1.0.0 +/usr/local/Calpont/lib/libfuncexp.so.1.0.0 +/usr/local/Calpont/lib/libjoblist.so.1.0.0 +/usr/local/Calpont/lib/libjoiner.so.1.0.0 +/usr/local/Calpont/lib/libloggingcpp.so.1.0.0 +/usr/local/Calpont/lib/libmessageqcpp.so.1.0.0 +/usr/local/Calpont/lib/liboamcpp.so.1.0.0 +/usr/local/Calpont/lib/libreplaytxnlog.so.1.0.0 +/usr/local/Calpont/lib/libsnmpmanager.so.1.0.0 +/usr/local/Calpont/lib/libthreadpool.so.1.0.0 +/usr/local/Calpont/lib/libwriteengine.so.1.0.0 +/usr/local/Calpont/lib/libwriteengineclient.so.1.0.0 +/usr/local/Calpont/lib/libsm.so.1.0.0 +/usr/local/Calpont/lib/libbrm.so.1.0.0 +/usr/local/Calpont/lib/librwlock.so.1.0.0 +/usr/local/Calpont/lib/libdataconvert.so.1.0.0 +/usr/local/Calpont/lib/librowgroup.so.1.0.0 +/usr/local/Calpont/lib/libcacheutils.so.1.0.0 +/usr/local/Calpont/lib/libmulticast.so.1.0.0 +/usr/local/Calpont/lib/libcommon.so.1.0.0 +/usr/local/Calpont/lib/libboost_idb.so.1.0.0 +/usr/local/Calpont/lib/libddlcleanuputil.so.1.0.0 +/usr/local/Calpont/lib/libmysqlcl_idb.so.1.0.0 +/usr/local/Calpont/lib/libbatchloader.so.1.0.0 +/usr/local/Calpont/lib/libwriteengineredistribute.so.1.0.0 +/usr/local/Calpont/lib/libquerystats.so.1.0.0 +/usr/local/Calpont/lib/libjemalloc.so.3.3.0 +# +# +/usr/local/Calpont/post/functions +/usr/local/Calpont/post/test-001.sh +/usr/local/Calpont/post/test-002.sh +/usr/local/Calpont/post/test-003.sh +/usr/local/Calpont/post/test-004.sh +# +%files mysql +/usr/local/Calpont/lib/libcalmysql.so.1.0.0 +# +%files mysqld +/usr/local/Calpont/mysql/lib/mysql/libmysqlclient.so.16.0.0 +/usr/local/Calpont/mysql/lib/mysql/libmysqlclient_r.so.16.0.0 +/usr/local/Calpont/mysql/lib/mysql/plugin/ha_federated.so.0.0.0 +/usr/local/Calpont/mysql/lib/mysql/plugin/ha_blackhole.so.0.0.0 +/usr/local/Calpont/mysql/lib/mysql/plugin/ha_archive.so.0.0.0 +/usr/local/Calpont/mysql/lib/mysql/plugin/ha_innodb.so.0.0.0 +/usr/local/Calpont/mysql/lib/mysql/plugin/ha_innodb_plugin.so.0.0.0 +/usr/local/Calpont/mysql/libexec/mysqlmanager +/usr/local/Calpont/mysql/libexec/mysqld +/usr/local/Calpont/mysql/bin/mysql_find_rows +/usr/local/Calpont/mysql/bin/mysqlbug +/usr/local/Calpont/mysql/bin/innochecksum +/usr/local/Calpont/mysql/bin/mysql_secure_installation +/usr/local/Calpont/mysql/bin/resolve_stack_dump +/usr/local/Calpont/mysql/bin/my_print_defaults +/usr/local/Calpont/mysql/bin/mysql_waitpid +/usr/local/Calpont/mysql/bin/resolveip +/usr/local/Calpont/mysql/bin/perror +/usr/local/Calpont/mysql/bin/myisamlog +/usr/local/Calpont/mysql/bin/mysql +/usr/local/Calpont/mysql/bin/myisamchk +/usr/local/Calpont/mysql/bin/mysql_fix_privilege_tables +/usr/local/Calpont/mysql/bin/mysql_upgrade +/usr/local/Calpont/mysql/bin/mysqlcheck +/usr/local/Calpont/mysql/bin/myisampack +/usr/local/Calpont/mysql/bin/mysql_setpermission +/usr/local/Calpont/mysql/bin/mysqladmin +/usr/local/Calpont/mysql/bin/mysqlslap +/usr/local/Calpont/mysql/bin/mysql_zap +/usr/local/Calpont/mysql/bin/mysqldump +/usr/local/Calpont/mysql/bin/mysqld_safe +/usr/local/Calpont/mysql/bin/mysqlshow +/usr/local/Calpont/mysql/bin/mysqltest +/usr/local/Calpont/mysql/bin/mysql_config +/usr/local/Calpont/mysql/bin/mysql_client_test +/usr/local/Calpont/mysql/bin/mysqlbinlog +/usr/local/Calpont/mysql/bin/mysqld_multi +/usr/local/Calpont/mysql/bin/mysqlaccess +/usr/local/Calpont/mysql/bin/mysql_install_db +/usr/local/Calpont/mysql/bin/msql2mysql +/usr/local/Calpont/mysql/bin/mysqlimport +/usr/local/Calpont/mysql/bin/replace +/usr/local/Calpont/mysql/bin/mysql_convert_table_format +/usr/local/Calpont/mysql/bin/myisam_ftdump +/usr/local/Calpont/mysql/bin/mysql_tzinfo_to_sql +/usr/local/Calpont/mysql/bin/mysql_fix_extensions +/usr/local/Calpont/mysql/bin/mysqldumpslow +/usr/local/Calpont/mysql/bin/mysqlhotcopy +/usr/local/Calpont/mysql/share/mysql/config.small.ini +/usr/local/Calpont/mysql/share/mysql/romanian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/korean/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/norwegian-ny/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/binary-configure +/usr/local/Calpont/mysql/share/mysql/french/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/greek/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/mysql-log-rotate +/usr/local/Calpont/mysql/share/mysql/mysql_system_tables_data.sql +/usr/local/Calpont/mysql/share/mysql/russian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/mysql.server +/usr/local/Calpont/mysql/share/mysql/mi_test_all.res +/usr/local/Calpont/mysql/share/mysql/danish/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/portuguese/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/mysql_fix_privilege_tables.sql +/usr/local/Calpont/mysql/share/mysql/italian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/mi_test_all +/usr/local/Calpont/mysql/share/mysql/mysql_system_tables.sql +/usr/local/Calpont/mysql/share/mysql/my-innodb-heavy-4G.cnf +/usr/local/Calpont/mysql/share/mysql/norwegian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/fill_help_tables.sql +/usr/local/Calpont/mysql/share/mysql/spanish/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/ndb-config-2-node.ini +/usr/local/Calpont/mysql/share/mysql/slovak/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/mysql_test_data_timezone.sql +/usr/local/Calpont/mysql/share/mysql/czech/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/english/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/hungarian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/mysqld_multi.server +/usr/local/Calpont/mysql/share/mysql/estonian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/german/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/errmsg.txt +/usr/local/Calpont/mysql/share/mysql/swedish/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/dutch/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/charsets/cp866.xml +/usr/local/Calpont/mysql/share/mysql/charsets/hebrew.xml +/usr/local/Calpont/mysql/share/mysql/charsets/latin2.xml +/usr/local/Calpont/mysql/share/mysql/charsets/armscii8.xml +/usr/local/Calpont/mysql/share/mysql/charsets/latin7.xml +/usr/local/Calpont/mysql/share/mysql/charsets/geostd8.xml +/usr/local/Calpont/mysql/share/mysql/charsets/latin5.xml +/usr/local/Calpont/mysql/share/mysql/charsets/swe7.xml +/usr/local/Calpont/mysql/share/mysql/charsets/keybcs2.xml +/usr/local/Calpont/mysql/share/mysql/charsets/cp1257.xml +/usr/local/Calpont/mysql/share/mysql/charsets/macroman.xml +/usr/local/Calpont/mysql/share/mysql/charsets/cp1251.xml +/usr/local/Calpont/mysql/share/mysql/charsets/cp1256.xml +/usr/local/Calpont/mysql/share/mysql/charsets/macce.xml +/usr/local/Calpont/mysql/share/mysql/charsets/dec8.xml +/usr/local/Calpont/mysql/share/mysql/charsets/latin1.xml +/usr/local/Calpont/mysql/share/mysql/charsets/greek.xml +/usr/local/Calpont/mysql/share/mysql/charsets/cp850.xml +/usr/local/Calpont/mysql/share/mysql/charsets/hp8.xml +/usr/local/Calpont/mysql/share/mysql/charsets/cp852.xml +/usr/local/Calpont/mysql/share/mysql/charsets/koi8r.xml +/usr/local/Calpont/mysql/share/mysql/charsets/README +/usr/local/Calpont/mysql/share/mysql/charsets/cp1250.xml +/usr/local/Calpont/mysql/share/mysql/charsets/koi8u.xml +/usr/local/Calpont/mysql/share/mysql/charsets/Index.xml +/usr/local/Calpont/mysql/share/mysql/charsets/ascii.xml +/usr/local/Calpont/mysql/share/mysql/config.medium.ini +/usr/local/Calpont/mysql/share/mysql/my-huge.cnf +/usr/local/Calpont/mysql/share/mysql/polish/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/my-medium.cnf +/usr/local/Calpont/mysql/share/mysql/my-large.cnf +/usr/local/Calpont/mysql/share/mysql/config.huge.ini +/usr/local/Calpont/mysql/share/mysql/ukrainian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/serbian/errmsg.sys +/usr/local/Calpont/mysql/share/mysql/my-small.cnf +/usr/local/Calpont/mysql/share/mysql/japanese/errmsg.sys +/usr/local/Calpont/mysql/mysql-Calpont +/usr/local/Calpont/mysql/install_calpont_mysql.sh +/usr/local/Calpont/mysql/syscatalog_mysql.sql +/usr/local/Calpont/mysql/dumpcat_mysql.sql +/usr/local/Calpont/mysql/dumpcat.pl +/usr/local/Calpont/mysql/calsetuserpriority.sql +/usr/local/Calpont/mysql/calremoveuserpriority.sql +/usr/local/Calpont/mysql/calshowprocesslist.sql + +%config /usr/local/Calpont/mysql/my.cnf + + +# Scriptlets +# for an install, pre & post run with $1 set to 1 +# for an erase, preun & postun run with $1 set to 0 +# for an upgrade, pre & post run first, with $1 set to 2 then the _old_ preun & postun run with $1 set to 1 + +%post +rpmmode=install +if [ "$1" -eq "$1" 2> /dev/null ]; then + if [ $1 -ne 1 ]; then + rpmmode=upgrade + fi +fi + +prefix=/usr/local + +#test -f /usr/local/Calpont/mysql/my.cnf && \ +# test -x /usr/local/Calpont/bin/post-mysqld-install && \ +# /usr/local/Calpont/bin/post-mysqld-install --prefix=$prefix --rpmmode=$rpmmode +test -x /usr/local/Calpont/bin/post-install && /usr/local/Calpont/bin/post-install --prefix=$prefix --rpmmode=$rpmmode + +echo "Calpont RPM install completed" + +%post mysql +rpmmode=install +if [ "$1" -eq "$1" 2> /dev/null ]; then + if [ $1 -ne 1 ]; then + rpmmode=upgrade + fi +fi + +prefix=/usr/local + +#test -x /usr/local/Calpont/bin/post-mysql-install && /usr/local/Calpont/bin/post-mysql-install --prefix=$prefix #--rpmmode=$rpmmode + +echo "Calpont RPM install completed" + +%post mysqld +rpmmode=install +if [ "$1" -eq "$1" 2> /dev/null ]; then + if [ $1 -ne 1 ]; then + rpmmode=upgrade + fi +fi + +prefix=/usr/local + +#test -x /usr/local/Calpont/bin/post-mysqld-install && /usr/local/Calpont/bin/post-mysqld-install --prefix=$prefix #--rpmmode=$rpmmode + +echo "Calpont RPM install completed" + +%preun +rpmmode=upgrade +if [ "$1" -eq "$1" 2> /dev/null ]; then + if [ $1 -ne 1 ]; then + rpmmode=erase + fi +else + rpmmode=erase +fi + +if [ $rpmmode = erase ]; then + test -x /usr/local/Calpont/bin/pre-uninstall && /usr/local/Calpont/bin/pre-uninstall + rm -f /etc/init.d/infinidb +fi + +exit 0 + +%preun mysqld +rpmmode=upgrade +if [ "$1" -eq "$1" 2> /dev/null ]; then + if [ $1 -ne 1 ]; then + rpmmode=erase + fi +else + rpmmode=erase +fi + +if [ $rpmmode = erase ]; then + /etc/init.d/mysql-Calpont stop > /dev/null 2>&1 + if [ -x /sbin/chkconfig ]; then + /sbin/chkconfig mysql-Calpont off > /dev/null 2>&1 + /sbin/chkconfig --del mysql-Calpont > /dev/null 2>&1 + elif [ -x /usr/sbin/update-rc.d ]; then + /usr/sbin/update-rc.d -f mysql-Calpont remove > /dev/null 2>&1 + fi + rm -f /etc/init.d/mysql-Calpont +fi + +exit 0 + diff --git a/build/clean b/build/clean index d85e3b61..ed866fb0 100755 --- a/build/clean +++ b/build/clean @@ -1,12 +1,13 @@ #!/bin/sh # -# $Id: clean 1843 2013-03-14 21:43:13Z pleblanc $ +# $Id: clean 1844 2013-03-15 14:25:45Z pleblanc $ # for x in \ dbcon \ ddlproc \ decomsvr \ +dmlib \ dmlproc \ exemgr \ mysql \ diff --git a/build/infinidb.spec.in b/build/infinidb.spec.in deleted file mode 100644 index 4705988f..00000000 --- a/build/infinidb.spec.in +++ /dev/null @@ -1,628 +0,0 @@ -# -# $Id$ -# -Summary: InfiniDB software -Name: infinidb -@@VERSION@@ -@@RELEASE@@ -Vendor: InfiniDB, Inc. -URL: http://www.calpont.com/ -@@PACKAGER@@ -Group: Applications -License: Copyright (c) 2014 InfiniDB, Inc., all rights reserved; redistributable under the terms of the GPL, see the file COPYING for details. -BuildRoot: %{_tmppath}/%{name}-%{release}-buildroot - -%description -InfiniDB software meta-package - -%package platform -Summary: InfiniDB software binaries -Group: Applications -Obsoletes: calpont -Requires: expect, infinidb-libs - -%description platform -InfiniDB binary files -@@BUILDINFO@@ - -%package libs -Summary: InfiniDB software libraries -Group: Applications -Obsoletes: calpont - -%description libs -InfiniDB libraries - -%package enterprise -Summary: InfiniDB Enterprise software binaries -Group: Applications -Obsoletes: calpont -Requires: infinidb-libs, infinidb-platform -License: Proprietary; Copyright (c) 2014 InfiniDB, Inc., all rights reserved - -%description enterprise -InfiniDB Enterprise binary files - -%package storage-engine -Summary: InfiniDB software MySQL connector -Group: Applications -Obsoletes: calpont-mysql -Requires: infinidb-libs - -%description storage-engine -InfiniDB MySQL connector binary files - -%package mysql -Summary: InfiniDB software MySQL server -Group: Applications -Obsoletes: calpont-mysqld - -%description mysql -InfiniDB/MySQL 5.1.73 server binary files - -%prep -%define _use_internal_dependency_generator 0 -%define __find_requires %{nil} -%define __os_install_post %{nil} -%define debug_package %{nil} - -%build - -%install -mkdir -p %{buildroot}/usr/local -tar -C $RPM_BUILD_DIR/%{name}-%{version}-%{release} -cf - . | tar -C %{buildroot}/usr/local -xf - - -%clean -rm -rf $RPM_BUILD_ROOT $RPM_BUILD_DIR/%{name}-%{version}-%{release} - -%changelog - -%files platform -%defattr(-, root, root) - -/usr/local/Calpont/bin/DDLProc -/usr/local/Calpont/bin/ExeMgr -/usr/local/Calpont/bin/ProcMgr -/usr/local/Calpont/bin/ProcMon -/usr/local/Calpont/bin/DMLProc -/usr/local/Calpont/bin/WriteEngineServer -/usr/local/Calpont/bin/cpimport -/usr/local/Calpont/bin/post-install -/usr/local/Calpont/bin/post-mysql-install -/usr/local/Calpont/bin/post-mysqld-install -/usr/local/Calpont/bin/pre-uninstall -/usr/local/Calpont/bin/PrimProc -/usr/local/Calpont/bin/DecomSvr -/usr/local/Calpont/bin/upgrade-infinidb.sh -/usr/local/Calpont/bin/run.sh -/usr/local/Calpont/bin/infinidb -/usr/local/Calpont/bin/calpontSyslog -/usr/local/Calpont/bin/calpontSyslog-ng -/usr/local/Calpont/bin/syslogSetup.sh -/usr/local/Calpont/bin/cplogger -/usr/local/Calpont/bin/infinidb.def -/usr/local/Calpont/bin/dbbuilder -/usr/local/Calpont/bin/cpimport.bin -/usr/local/Calpont/bin/load_brm -/usr/local/Calpont/bin/save_brm -/usr/local/Calpont/bin/dbrmctl -/usr/local/Calpont/bin/controllernode -/usr/local/Calpont/bin/reset_locks -/usr/local/Calpont/bin/workernode -/usr/local/Calpont/bin/colxml -/usr/local/Calpont/bin/clearShm -/usr/local/Calpont/bin/viewtablelock -/usr/local/Calpont/bin/cleartablelock -/usr/local/Calpont/bin/calpontConsole -/usr/local/Calpont/bin/trapHandler -/usr/local/Calpont/bin/remote_command.sh -/usr/local/Calpont/bin/postConfigure -/usr/local/Calpont/bin/calpontLogRotate -/usr/local/Calpont/bin/transactionLog -/usr/local/Calpont/bin/calpontDBWrite -/usr/local/Calpont/bin/transactionLogArchiver.sh -/usr/local/Calpont/bin/system_installer.sh -/usr/local/Calpont/bin/installer -/usr/local/Calpont/bin/module_installer.sh -/usr/local/Calpont/bin/patchInstaller -/usr/local/Calpont/bin/patch_installer.sh -/usr/local/Calpont/bin/xm_installer.sh -/usr/local/Calpont/bin/calpontUninstall.sh -/usr/local/Calpont/bin/director_installer.sh -/usr/local/Calpont/bin/user_installer.sh -/usr/local/Calpont/bin/performance_installer.sh -/usr/local/Calpont/bin/startupTests.sh -/usr/local/Calpont/bin/os_check.sh -/usr/local/Calpont/bin/sendtrap -/usr/local/Calpont/bin/remote_scp_put.sh -/usr/local/Calpont/bin/remotessh.exp -/usr/local/Calpont/bin/ServerMonitor -/usr/local/Calpont/bin/master-rep-infinidb.sh -/usr/local/Calpont/bin/slave-rep-infinidb.sh -/usr/local/Calpont/bin/rsync.sh -/usr/local/Calpont/bin/calpontSupport -/usr/local/Calpont/bin/hardwareReport.sh -/usr/local/Calpont/bin/softwareReport.sh -/usr/local/Calpont/bin/configReport.sh -/usr/local/Calpont/bin/logReport.sh -/usr/local/Calpont/bin/bulklogReport.sh -/usr/local/Calpont/bin/resourceReport.sh -/usr/local/Calpont/bin/hadoopReport.sh -/usr/local/Calpont/bin/alarmReport.sh -/usr/local/Calpont/bin/amazonInstaller -/usr/local/Calpont/bin/remote_command_verify.sh - -# -%config /usr/local/Calpont/etc/Calpont.xml -%config /usr/local/Calpont/etc/ConsoleCmds.xml -%config /usr/local/Calpont/etc/ProcessConfig.xml -%config /usr/local/Calpont/etc/snmpd.conf -%config /usr/local/Calpont/etc/snmptrapd.conf -%config /usr/local/Calpont/etc/Calpont.xml.singleserver -%config /usr/local/Calpont/etc/ProcessConfig.xml.singleserver -%config /usr/local/Calpont/etc/snmpd.conf.singleserver -%config /usr/local/Calpont/etc/snmptrapd.conf.singleserver -# -/usr/local/Calpont/etc/MessageFile.txt -/usr/local/Calpont/etc/ErrorMessage.txt -# -%attr(0666, root, root) /usr/local/Calpont/local/module -# -/usr/local/Calpont/releasenum -/usr/local/Calpont/COPYING - -# Tools... -/usr/local/Calpont/bin/rollback -/usr/local/Calpont/bin/editem -/usr/local/Calpont/bin/getConfig -/usr/local/Calpont/bin/setConfig -/usr/local/Calpont/bin/setenv-hdfs-12 -/usr/local/Calpont/bin/setenv-hdfs-20 -/usr/local/Calpont/bin/hdfsCheck -/usr/local/Calpont/bin/configxml.sh -/usr/local/Calpont/bin/remote_scp_get.sh -/usr/local/Calpont/bin/calpontAlias -/usr/local/Calpont/bin/autoConfigure -/usr/local/Calpont/bin/ddlcleanup -/usr/local/Calpont/bin/idbmeminfo -/usr/local/Calpont/bin/IDBInstanceCmds.sh -/usr/local/Calpont/bin/IDBVolumeCmds.sh -/usr/local/Calpont/bin/binary_installer.sh -/usr/local/Calpont/bin/myCnf-include-args.text -/usr/local/Calpont/bin/myCnf-exclude-args.text -/usr/local/Calpont/bin/mycnfUpgrade - -/usr/local/Calpont/sbin/snmpd -/usr/local/Calpont/sbin/snmptrapd -%config %attr(0666, root, root) /usr/local/Calpont/etc/AlarmConfig.xml -# -%config /usr/local/Calpont/local/snmpdx.conf -%config /usr/local/Calpont/local/snmpdx.conf.singleserver -# -/usr/local/Calpont/share/snmp/mibs/AGENTX-MIB.txt -/usr/local/Calpont/share/snmp/mibs/CALPONT-MIB.txt -/usr/local/Calpont/share/snmp/mibs/DISMAN-EVENT-MIB.txt -/usr/local/Calpont/share/snmp/mibs/DISMAN-SCHEDULE-MIB.txt -/usr/local/Calpont/share/snmp/mibs/DISMAN-SCRIPT-MIB.txt -/usr/local/Calpont/share/snmp/mibs/EtherLike-MIB.txt -/usr/local/Calpont/share/snmp/mibs/HCNUM-TC.txt -/usr/local/Calpont/share/snmp/mibs/HOST-RESOURCES-MIB.txt -/usr/local/Calpont/share/snmp/mibs/HOST-RESOURCES-TYPES.txt -/usr/local/Calpont/share/snmp/mibs/IANA-ADDRESS-FAMILY-NUMBERS-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IANAifType-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IANA-LANGUAGE-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IANA-RTPROTO-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IF-INVERTED-STACK-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IF-MIB.txt -/usr/local/Calpont/share/snmp/mibs/INET-ADDRESS-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IP-FORWARD-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IPV6-ICMP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IPV6-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IPV6-TCP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/IPV6-TC.txt -/usr/local/Calpont/share/snmp/mibs/IPV6-UDP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/NET-SNMP-AGENT-MIB.txt -/usr/local/Calpont/share/snmp/mibs/NET-SNMP-EXAMPLES-MIB.txt -/usr/local/Calpont/share/snmp/mibs/NET-SNMP-EXTEND-MIB.txt -/usr/local/Calpont/share/snmp/mibs/NET-SNMP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/NET-SNMP-TC.txt -/usr/local/Calpont/share/snmp/mibs/NOTIFICATION-LOG-MIB.txt -/usr/local/Calpont/share/snmp/mibs/RFC1155-SMI.txt -/usr/local/Calpont/share/snmp/mibs/RFC1213-MIB.txt -/usr/local/Calpont/share/snmp/mibs/RFC-1215.txt -/usr/local/Calpont/share/snmp/mibs/RMON-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SMUX-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-COMMUNITY-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-FRAMEWORK-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-MPD-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-NOTIFICATION-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-PROXY-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-TARGET-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-USER-BASED-SM-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-USM-AES-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-USM-DH-OBJECTS-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMPv2-CONF.txt -/usr/local/Calpont/share/snmp/mibs/SNMPv2-MIB.txt -/usr/local/Calpont/share/snmp/mibs/SNMPv2-SMI.txt -/usr/local/Calpont/share/snmp/mibs/SNMPv2-TC.txt -/usr/local/Calpont/share/snmp/mibs/SNMPv2-TM.txt -/usr/local/Calpont/share/snmp/mibs/SNMP-VIEW-BASED-ACM-MIB.txt -/usr/local/Calpont/share/snmp/mibs/TCP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/TRANSPORT-ADDRESS-MIB.txt -/usr/local/Calpont/share/snmp/mibs/UCD-DEMO-MIB.txt -/usr/local/Calpont/share/snmp/mibs/UCD-DISKIO-MIB.txt -/usr/local/Calpont/share/snmp/mibs/UCD-DLMOD-MIB.txt -/usr/local/Calpont/share/snmp/mibs/UCD-IPFWACC-MIB.txt -/usr/local/Calpont/share/snmp/mibs/UCD-SNMP-MIB.txt -/usr/local/Calpont/share/snmp/mibs/UDP-MIB.txt -# -/usr/local/Calpont/post/functions -/usr/local/Calpont/post/test-001.sh -/usr/local/Calpont/post/test-002.sh -/usr/local/Calpont/post/test-003.sh -/usr/local/Calpont/post/test-004.sh - -%files enterprise -%defattr(-, root, root) -/usr/local/Calpont/bin/displayJobGraph.sh -/usr/local/Calpont/bin/dbhealth.sh -/usr/local/Calpont/bin/dbhealth.sql - -# Tools... -/usr/local/Calpont/bin/dumpcol -/usr/local/Calpont/bin/oid2file -/usr/local/Calpont/bin/evalcol -/usr/local/Calpont/bin/SesMgr -/usr/local/Calpont/bin/dumpVss -/usr/local/Calpont/bin/editTxn -/usr/local/Calpont/bin/dbprof.pl -/usr/local/Calpont/bin/dumpobm -/usr/local/Calpont/bin/file2oid.pl -/usr/local/Calpont/bin/print_journal -/usr/local/Calpont/bin/healthcheck -/usr/local/Calpont/bin/glusterctl -/usr/local/Calpont/bin/glusteradd -/usr/local/Calpont/bin/glusterconf -/usr/local/Calpont/bin/redistributeDB -/usr/local/Calpont/bin/databaseSizeReport -/usr/local/Calpont/bin/gdb -# -/usr/local/Calpont/tools/copy2here.sh -/usr/local/Calpont/tools/getlogs.sh -/usr/local/Calpont/tools/getmodules.sh -/usr/local/Calpont/tools/getps.sh -/usr/local/Calpont/tools/getsar.sh -/usr/local/Calpont/tools/getuserinput.sh -/usr/local/Calpont/tools/prat -/usr/local/Calpont/tools/prat.sh -/usr/local/Calpont/tools/ps -/usr/local/Calpont/tools/pscollect -/usr/local/Calpont/tools/README -/usr/local/Calpont/tools/tarfiles.sh -# -%files libs -%defattr(-, root, root) - -/usr/local/Calpont/lib/libconfigcpp.so.1.0.0 -/usr/local/Calpont/lib/libddlpackageproc.so.1.0.0 -/usr/local/Calpont/lib/libddlpackage.so.1.0.0 -/usr/local/Calpont/lib/libdmlpackageproc.so.1.0.0 -/usr/local/Calpont/lib/libdmlpackage.so.1.0.0 -/usr/local/Calpont/lib/libexecplan.so.1.0.0 -/usr/local/Calpont/lib/libfuncexp.so.1.0.0 -/usr/local/Calpont/lib/libudfsdk.so.1.0.0 -/usr/local/Calpont/lib/libjoblist.so.1.0.0 -/usr/local/Calpont/lib/libjoiner.so.1.0.0 -/usr/local/Calpont/lib/libloggingcpp.so.1.0.0 -/usr/local/Calpont/lib/libmessageqcpp.so.1.0.0 -/usr/local/Calpont/lib/libnetsnmpagent.so.5.2.1 -/usr/local/Calpont/lib/libnetsnmphelpers.so.5.2.1 -/usr/local/Calpont/lib/libnetsnmpmibs.so.5.2.1 -/usr/local/Calpont/lib/libnetsnmp.so.5.2.1 -/usr/local/Calpont/lib/libnetsnmptrapd.so.5.2.1 -/usr/local/Calpont/lib/liboamcpp.so.1.0.0 -/usr/local/Calpont/lib/libsnmpmanager.so.1.0.0 -/usr/local/Calpont/lib/libthreadpool.so.1.0.0 -/usr/local/Calpont/lib/libwindowfunction.so.1.0.0 -/usr/local/Calpont/lib/libwriteengine.so.1.0.0 -/usr/local/Calpont/lib/libwriteengineclient.so.1.0.0 -/usr/local/Calpont/lib/libbrm.so.1.0.0 -/usr/local/Calpont/lib/librwlock.so.1.0.0 -/usr/local/Calpont/lib/libdataconvert.so.1.0.0 -/usr/local/Calpont/lib/librowgroup.so.1.0.0 -/usr/local/Calpont/lib/libcacheutils.so.1.0.0 -/usr/local/Calpont/lib/libcommon.so.1.0.0 -/usr/local/Calpont/lib/libboost_idb.so.1.0.0 -/usr/local/Calpont/lib/libcompress.so.1.0.0 -/usr/local/Calpont/lib/libddlcleanuputil.so.1.0.0 -/usr/local/Calpont/lib/libbatchloader.so.1.0.0 -/usr/local/Calpont/lib/libmysqlcl_idb.so.1.0.0 -/usr/local/Calpont/lib/libquerystats.so.1.0.0 -/usr/local/Calpont/lib/libwriteengineredistribute.so.1.0.0 -/usr/local/Calpont/lib/libjemalloc.so.3.3.0 -/usr/local/Calpont/lib/libidbdatafile.so.1.0.0 -/usr/local/Calpont/lib/hdfs-20.so -/usr/local/Calpont/lib/hdfs-12.so -/usr/local/Calpont/lib/libgcc_s.so.1 -/usr/local/Calpont/lib/libstdc++.so.6.0.14 -/usr/local/Calpont/lib/libthrift.so.1.0.0 -/usr/local/Calpont/lib/libquerytele.so.1.0.0 - -%files storage-engine -/usr/local/Calpont/lib/libcalmysql.so.1.0.0 -/usr/local/Calpont/lib/libudf_mysql.so.1.0.0 - -%files mysql -/usr/local/Calpont/mysql/lib/mysql/libmysqlclient.so.16.0.0 -/usr/local/Calpont/mysql/lib/mysql/libmysqlclient_r.so.16.0.0 -/usr/local/Calpont/mysql/lib/mysql/plugin/ha_federated.so.0.0.0 -/usr/local/Calpont/mysql/lib/mysql/plugin/ha_blackhole.so.0.0.0 -/usr/local/Calpont/mysql/lib/mysql/plugin/ha_archive.so.0.0.0 -/usr/local/Calpont/mysql/lib/mysql/plugin/ha_innodb.so.0.0.0 -/usr/local/Calpont/mysql/lib/mysql/plugin/ha_innodb_plugin.so.0.0.0 -/usr/local/Calpont/mysql/libexec/mysqlmanager -/usr/local/Calpont/mysql/libexec/mysqld -/usr/local/Calpont/mysql/bin/mysql_find_rows -/usr/local/Calpont/mysql/bin/mysqlbug -/usr/local/Calpont/mysql/bin/innochecksum -/usr/local/Calpont/mysql/bin/mysql_secure_installation -/usr/local/Calpont/mysql/bin/resolve_stack_dump -/usr/local/Calpont/mysql/bin/my_print_defaults -/usr/local/Calpont/mysql/bin/mysql_waitpid -/usr/local/Calpont/mysql/bin/resolveip -/usr/local/Calpont/mysql/bin/perror -/usr/local/Calpont/mysql/bin/myisamlog -/usr/local/Calpont/mysql/bin/mysql -/usr/local/Calpont/mysql/bin/myisamchk -/usr/local/Calpont/mysql/bin/mysql_fix_privilege_tables -/usr/local/Calpont/mysql/bin/mysql_upgrade -/usr/local/Calpont/mysql/bin/mysqlcheck -/usr/local/Calpont/mysql/bin/myisampack -/usr/local/Calpont/mysql/bin/mysql_setpermission -/usr/local/Calpont/mysql/bin/mysqladmin -/usr/local/Calpont/mysql/bin/mysqlslap -/usr/local/Calpont/mysql/bin/mysql_zap -/usr/local/Calpont/mysql/bin/mysqldump -/usr/local/Calpont/mysql/bin/mysqld_safe -/usr/local/Calpont/mysql/bin/mysqlshow -/usr/local/Calpont/mysql/bin/mysqltest -/usr/local/Calpont/mysql/bin/mysql_config -/usr/local/Calpont/mysql/bin/mysql_client_test -/usr/local/Calpont/mysql/bin/mysqlbinlog -/usr/local/Calpont/mysql/bin/mysqld_multi -/usr/local/Calpont/mysql/bin/mysqlaccess -/usr/local/Calpont/mysql/bin/mysql_install_db -/usr/local/Calpont/mysql/bin/msql2mysql -/usr/local/Calpont/mysql/bin/mysqlimport -/usr/local/Calpont/mysql/bin/replace -/usr/local/Calpont/mysql/bin/mysql_convert_table_format -/usr/local/Calpont/mysql/bin/myisam_ftdump -/usr/local/Calpont/mysql/bin/mysql_tzinfo_to_sql -/usr/local/Calpont/mysql/bin/mysql_fix_extensions -/usr/local/Calpont/mysql/bin/mysqldumpslow -/usr/local/Calpont/mysql/bin/mysqlhotcopy -/usr/local/Calpont/mysql/share/mysql/config.small.ini -/usr/local/Calpont/mysql/share/mysql/romanian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/korean/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/norwegian-ny/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/binary-configure -/usr/local/Calpont/mysql/share/mysql/french/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/greek/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/mysql-log-rotate -/usr/local/Calpont/mysql/share/mysql/mysql_system_tables_data.sql -/usr/local/Calpont/mysql/share/mysql/russian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/mysql.server -/usr/local/Calpont/mysql/share/mysql/mi_test_all.res -/usr/local/Calpont/mysql/share/mysql/danish/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/portuguese/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/mysql_fix_privilege_tables.sql -/usr/local/Calpont/mysql/share/mysql/italian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/mi_test_all -/usr/local/Calpont/mysql/share/mysql/mysql_system_tables.sql -/usr/local/Calpont/mysql/share/mysql/my-innodb-heavy-4G.cnf -/usr/local/Calpont/mysql/share/mysql/norwegian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/fill_help_tables.sql -/usr/local/Calpont/mysql/share/mysql/spanish/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/ndb-config-2-node.ini -/usr/local/Calpont/mysql/share/mysql/slovak/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/mysql_test_data_timezone.sql -/usr/local/Calpont/mysql/share/mysql/czech/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/english/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/hungarian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/mysqld_multi.server -/usr/local/Calpont/mysql/share/mysql/estonian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/german/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/errmsg.txt -/usr/local/Calpont/mysql/share/mysql/swedish/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/dutch/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/charsets/cp866.xml -/usr/local/Calpont/mysql/share/mysql/charsets/hebrew.xml -/usr/local/Calpont/mysql/share/mysql/charsets/latin2.xml -/usr/local/Calpont/mysql/share/mysql/charsets/armscii8.xml -/usr/local/Calpont/mysql/share/mysql/charsets/latin7.xml -/usr/local/Calpont/mysql/share/mysql/charsets/geostd8.xml -/usr/local/Calpont/mysql/share/mysql/charsets/latin5.xml -/usr/local/Calpont/mysql/share/mysql/charsets/swe7.xml -/usr/local/Calpont/mysql/share/mysql/charsets/keybcs2.xml -/usr/local/Calpont/mysql/share/mysql/charsets/cp1257.xml -/usr/local/Calpont/mysql/share/mysql/charsets/macroman.xml -/usr/local/Calpont/mysql/share/mysql/charsets/cp1251.xml -/usr/local/Calpont/mysql/share/mysql/charsets/cp1256.xml -/usr/local/Calpont/mysql/share/mysql/charsets/macce.xml -/usr/local/Calpont/mysql/share/mysql/charsets/dec8.xml -/usr/local/Calpont/mysql/share/mysql/charsets/latin1.xml -/usr/local/Calpont/mysql/share/mysql/charsets/greek.xml -/usr/local/Calpont/mysql/share/mysql/charsets/cp850.xml -/usr/local/Calpont/mysql/share/mysql/charsets/hp8.xml -/usr/local/Calpont/mysql/share/mysql/charsets/cp852.xml -/usr/local/Calpont/mysql/share/mysql/charsets/koi8r.xml -/usr/local/Calpont/mysql/share/mysql/charsets/README -/usr/local/Calpont/mysql/share/mysql/charsets/cp1250.xml -/usr/local/Calpont/mysql/share/mysql/charsets/koi8u.xml -/usr/local/Calpont/mysql/share/mysql/charsets/Index.xml -/usr/local/Calpont/mysql/share/mysql/charsets/ascii.xml -/usr/local/Calpont/mysql/share/mysql/config.medium.ini -/usr/local/Calpont/mysql/share/mysql/my-huge.cnf -/usr/local/Calpont/mysql/share/mysql/polish/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/my-medium.cnf -/usr/local/Calpont/mysql/share/mysql/my-large.cnf -/usr/local/Calpont/mysql/share/mysql/config.huge.ini -/usr/local/Calpont/mysql/share/mysql/ukrainian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/serbian/errmsg.sys -/usr/local/Calpont/mysql/share/mysql/my-small.cnf -/usr/local/Calpont/mysql/share/mysql/japanese/errmsg.sys -/usr/local/Calpont/mysql/mysql-Calpont -/usr/local/Calpont/mysql/install_calpont_mysql.sh -/usr/local/Calpont/mysql/syscatalog_mysql.sql -/usr/local/Calpont/mysql/dumpcat_mysql.sql -/usr/local/Calpont/mysql/dumpcat.pl -/usr/local/Calpont/mysql/calsetuserpriority.sql -/usr/local/Calpont/mysql/calremoveuserpriority.sql -/usr/local/Calpont/mysql/calshowprocesslist.sql - -%config /usr/local/Calpont/mysql/my.cnf - -# -# Scriptlets -# for an install, pre & post run with $1 set to 1 -# for an erase, preun & postun run with $1 set to 0 -# for an upgrade, pre & post run first, with $1 set to 2 then the _old_ preun & postun run with $1 set to 1 - -%post platform -rpmmode=install -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=upgrade - fi -fi - -prefix=/usr/local - -test -x /usr/local/Calpont/bin/post-install && /usr/local/Calpont/bin/post-install --prefix=$prefix --rpmmode=$rpmmode - -echo "InfinIDB RPM install completed" - -%post libs -rpmmode=install -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=upgrade - fi -fi - -prefix=/usr/local - -echo "InfinIDB RPM install completed" - -%post storage-engine -rpmmode=install -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=upgrade - fi -fi - -prefix=/usr/local - -echo "InfinIDB RPM install completed" - -%post mysql -rpmmode=install -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=upgrade - fi -fi - -prefix=/usr/local - -echo "InfinIDB RPM install completed" - -%post enterprise -rpmmode=install -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=upgrade - fi -fi - -prefix=/usr/local - -echo "InfinIDB RPM install completed" - -%preun platform -rpmmode=upgrade -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=erase - fi -else - rpmmode=erase -fi - -if [ $rpmmode = erase ]; then - test -x /usr/local/Calpont/bin/pre-uninstall && /usr/local/Calpont/bin/pre-uninstall -fi - -exit 0 - -%preun libs -rpmmode=upgrade -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=erase - fi -else - rpmmode=erase -fi - -exit 0 - -%preun storage-engine -rpmmode=upgrade -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=erase - fi -else - rpmmode=erase -fi - -exit 0 - -%preun enterprise -rpmmode=upgrade -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=erase - fi -else - rpmmode=erase -fi - -exit 0 - -%preun mysql -rpmmode=upgrade -if [ "$1" -eq "$1" 2> /dev/null ]; then - if [ $1 -ne 1 ]; then - rpmmode=erase - fi -else - rpmmode=erase -fi - -if [ $rpmmode = erase ]; then - /etc/init.d/mysql-Calpont stop > /dev/null 2>&1 - if [ -x /sbin/chkconfig ]; then - /sbin/chkconfig mysql-Calpont off > /dev/null 2>&1 - /sbin/chkconfig --del mysql-Calpont > /dev/null 2>&1 - elif [ -x /usr/sbin/update-rc.d ]; then - /usr/sbin/update-rc.d -f mysql-Calpont remove > /dev/null 2>&1 - fi - rm -f /etc/init.d/mysql-Calpont -fi - -exit 0 - diff --git a/build/make_src_tar b/build/make_src_tar old mode 100755 new mode 100644 index 0000c358..1138995e --- a/build/make_src_tar +++ b/build/make_src_tar @@ -1,6 +1,6 @@ #!/bin/bash # -# $Id: make_src_tar 1932 2013-06-20 18:26:27Z dhill $ +# $Id: make_src_tar 1836 2013-02-15 15:11:15Z dhill $ # # basedir is the working dir for all the activity @@ -9,8 +9,12 @@ basedir=$HOME vname= # ofile is the output tar file name and is relative to a hidden dir, so it should be absolute ofile= -# branch is the branch to checkout (develop by default) +# branch is the branch to checkout (trunk by default) branch= +# normally we make a community src dist +enterprise=0 +# where to get the MySQL code from +mysqltar=/net/srvengcm1/Calpont/exports/MySQL/mysql-5.1.39.tar.gz for arg in "$@"; do if [ $(expr -- "$arg" : '--basedir=') -eq 10 ]; then basedir="$(echo $arg | awk -F= '{print $2}')" @@ -20,11 +24,25 @@ for arg in "$@"; do ofile="$(echo $arg | awk -F= '{print $2}')" elif [ $(expr -- "$arg" : '--branch=') -eq 9 ]; then branch="$(echo $arg | awk -F= '{print $2}')" + elif [ $(expr -- "$arg" : '--enterprise') -eq 12 ]; then + enterprise=1 + elif [ $(expr -- "$arg" : '--mysqltar=') -eq 11 ]; then + mysqltar="$(echo $arg | awk -F= '{print $2}')" else echo "ignoring unknown argument: $arg" 1>&2 fi done +if [ ! -x /usr/local/bin/updateGenii.pl ]; then + echo "Did not find updateGenii.pl!" 1>&2 + exit 1 +fi + +if [ ! -f $mysqltar ]; then + echo "Did not find $mysqltar!" 1>&2 + exit 1 +fi + if [ -f releasenum ]; then . releasenum elif [ -f build/releasenum ]; then @@ -34,9 +52,9 @@ else fi if [ -z "$version" ]; then - echo "Version defaulting to 4.0-develop" - version=4.0 - release=develop + echo "Version defaulting to 2.3-trunk" + version=2.3 + release=trunk fi if [ -z "$release" ]; then @@ -45,7 +63,11 @@ fi blddir=bld.$$ if [ -z "$vname" ]; then - vname=infinidb-${version} + if [ $enterprise -eq 0 ]; then + vname=calpont-infinidb-${version} + else + vname=calpont-infinidb-ent-${version} + fi fi if [ -z "$ofile" ]; then ofile=${basedir}/${vname}-${release}.src.tar.gz @@ -64,55 +86,104 @@ branch_arg= if [ ! -z "$branch" ]; then branch_arg="-b $branch" else - branch=develop + branch=trunk fi -echo -n "getting git source from $branch..." -git clone http://srvengcm1.calpont.com/repos/infinidb.git infinidb -cd infinidb -git checkout $branch +echo -n "getting SVN source from $branch..." +updateGenii.pl -r $co_dir $branch_arg >/dev/null 2>&1 echo "done." test -d build || exit 1 -echo -n "cleaning git source for " +echo -n "cleaning SVN source for " +if [ $enterprise -eq 0 ]; then + echo -n "open source " +else + echo -n "enterprise " +fi echo -n "release..." -rm -rf .git .gitignore +rm -rf .git* rm -rf qa export rm -f rules.mak find . -name Makefile | xargs rm -f find . -name \*.xmi | xargs rm -f rm -f dbcon/joblist/bandeddl.h.set dbcon/joblist/bandeddl.h.vector primitives/blockcache/iomanager.cpp.single-read \ primitives/udf/Makefile.sdk +if [ $enterprise -eq 0 ]; then + for file in $(find . -name \*.os); do + mv -f ${file} ${file%.os} + done +else + find . -name \*.os | xargs rm -f +fi rm -rf utils/scenarios +if [ $enterprise -eq 0 ]; then + rm -rf procmgr + rm -rf procmon + cd oamapps + rm -rf calpont-console hardwareMonitor postConfigure resourceMonitor sessionWalker calpontDB \ + logUtils serverMonitor traphandler sendtrap glusterconf + cd .. +fi cd mysql rm -rf scripts queries storage/maria cd .. rm -rf writeengine/test/* rm -rf utils/net-snmp-built-libs -rm -rf utils/multicast +cd utils/multicast +rm -f config.h impl.h participants.h socklib.h threads.h udpc-protoc.h util.h impl.cpp mc_fifo.h produconsum.h statistics.h udp-sender.h udpcast.h +cd ../.. rm -rf utils/openpgm rm -rf tools/reserveStacks -rm -rf dbcon/doc dbcon/ingres dbcon/plsql -cd tools -rm -rf brmtest dataPump evalidx fixdate nettest pgm pingproc rebuildEM snconvert updateGenii valprint -rm -rf cfread dbgen dbgen-ssb ddldriver dmldriver idb_comp sendPlan vbgen -cd .. -rm -rf utils/libstatgrab utils/libxml utils/testbc utils/configcpp/md5 -echo "done." +if [ $enterprise -eq 0 ]; then + cp oam/etc/Calpont.xml oam/etc/Calpont.xml.singleserver + cd tools + for dir in sendPlan cfread ddldriver calpontSupport prat configMgt idb_comp vbgen; do + rm -rf $dir + done + cd .. + cd build + for file in README bChanges.sh bb_fix_rules.sh branchIt.pl branchMerge.pl build_rpms checkForMods.sh \ + copyBranch.pl deleteBranch.pl makeBranch.pl makeTag.pl make_src_tar svndiff.pl svnmerge.pl tagIt.pl; do + rm -f $file + done + cd .. + cd oam/install_scripts + for file in calpont calpontInstall.sh calpontUninstall.sh crontab director_installer.sh install-calpont.sh \ + module_installer.sh oracle patch_installer.sh performance_installer.sh postInstall.sh \ + remote_command.sh remote_installer.sh remote_scp_get.sh system_installer.sh user_installer.sh \ + xm_installer.sh displayJobGraph.sh S99Infinidb binary_installer.sh; do + rm -f $file + done + cd ../.. + rm -rf net-snmp utils/net-snmp utils/libstatgrab utils/boost_thread utils/libxml + rm -f build/mini-tests.sh build/nightly-mini-tester.sh + rm -f oam/oamcpp/license.* + rm -f dbcon/mysql/ha_calpont_partition.cpp dbcon/mysql/ha_view.* dbcon/mysql/ha_autoi.* + rm -rf utils/udfsdk + cd utils/compress + for file in *; do + if [ $file != idbcompress.h -a $file != Makefile.am ]; then + rm -f $file + fi + done + cd ../.. + cd tools + rm -rf brmtest dataPump evalidx fixdate nettest pgm pingproc rebuildEM snconvert updateGenii valprint + cd .. + rm -f utils/winport/idb_64_enterprise.nsi + rm -f utils/winport/win_setup_mysql_part4.sql + rm -rf tools/notificationTester +fi -cd .. +echo "done." echo -n "getting MySQL..." -git clone https://github.com/infinidb/mysql mysql -cd mysql -git checkout $branch +tar -zxf $mysqltar +rm -f mysql-5.1.*/config.h.in~ echo "done." -cd .. - echo -n "building tarball..." -cd infinidb cp -r utils/autoconf/* . cp INSTALL INSTALL.keep cp install-sh install-sh.keep @@ -122,9 +193,6 @@ rm -f INSTALL install-sh mv INSTALL.keep INSTALL mv install-sh.keep install-sh cd .. -ln -s infinidb/INSTALL -ln -s infinidb/README -cd .. tar -zcf $ofile $vname echo "done." diff --git a/build/nightly-mini-tester.sh b/build/nightly-mini-tester.sh index 01b25dd5..4dc063b5 100755 --- a/build/nightly-mini-tester.sh +++ b/build/nightly-mini-tester.sh @@ -1,7 +1,5 @@ #!/bin/bash -NO_NONROOT_SUDO=yes -export NO_NONROOT_SUDO prefix=/usr/local builddir= for arg in "$@"; do @@ -19,13 +17,12 @@ if [ -z "$builddir" ]; then exit 1 fi -if [ ! -d ${builddir}/export/Calpont ]; then - echo "I did't find a Calpont dir in ${builddir}/export!" 1>&2 +if [ ! -d ${builddir}/Calpont ]; then + echo "I did't find a Calpont dir in ${builddir}!" 1>&2 exit 1 fi # stop any current procs -${prefix}/Calpont/bin/calpontConsole shutdownsystem y if [ -x ${prefix}/Calpont/bin/infinidb ]; then ${prefix}/Calpont/bin/infinidb stop fi @@ -54,7 +51,7 @@ rm -rf ${prefix}/Calpont 2>/dev/null # (we'll leave the logging stuff in place for now) # install the binaries -tar -C ${builddir}/export -cf - Calpont | tar -C ${prefix} -xf - +tar -C ${builddir} -cf - Calpont | tar -C ${prefix} -xf - if [ $? -ne 0 ]; then echo "There was a problem installing the binaries!" 1>&2 exit 1 @@ -63,41 +60,37 @@ fi find ${prefix}/Calpont -type d | xargs chmod +rx find ${prefix}/Calpont -type f | xargs chmod +r -mkdir -p ${prefix}/Calpont/data1/systemFiles/dbrm - -if [ ! -e ${prefix}/Calpont/lib/libjemalloc.so ]; then - pushd ${prefix}/Calpont/lib >/dev/null - ln -s libjemalloc.so.1 libjemalloc.so - popd >/dev/null -fi - -if [ ! -f ${prefix}/Calpont/etc/Calpont.xml.rpmsave ]; then - cp ${prefix}/Calpont/etc/Calpont.xml.singleserver ${prefix}/Calpont/etc/Calpont.xml.rpmsave -fi - -if [ ! -f ${prefix}/Calpont/mysql/my.cnf ]; then - cp ${builddir}/dbcon/mysql/my.cnf ${prefix}/Calpont/mysql -fi - #fix the port numbers sed -i -e 's/port.*=.*3306/port=14406/' ${prefix}/Calpont/mysql/my.cnf # configure the s/w -${prefix}/Calpont/bin/postConfigure -n +if [ ! -x ${prefix}/Calpont/bin/install-infinidb.sh ]; then + echo "There was a problem configuring the s/w!" 1>&2 + exit 1 +fi +${prefix}/Calpont/bin/install-infinidb.sh 2>/dev/null + +# really install MySQL +${prefix}/Calpont/mysql/bin/mysql_install_db --defaults-file=${prefix}/Calpont/mysql/my.cnf >/dev/null + +#fix pp blocks +sed -i -e 's?.*?46?' ${prefix}/Calpont/etc/Calpont.xml -# restart (argh) -#${prefix}/Calpont/bin/calpontConsole RestartSystem y +# start the system +${prefix}/Calpont/bin/infinidb start -sleep 30 -pkill DMLProc -sleep 30 +#really start MySQL +${prefix}/Calpont/mysql/mysql-Calpont start +sleep 10 +${prefix}/Calpont/mysql/install_calpont_mysql.sh +${prefix}/Calpont/bin/upgrade-infinidb.sh doupgrade # perform the tests -if [ ! -x ${builddir}/build/mini-tests.sh ]; then +if [ ! -x ${builddir}/mini-tests.sh ]; then echo "There was a problem trying to start testing the s/w!" 1>&2 exit 1 fi -${builddir}/build/mini-tests.sh --prefix=${prefix} +${builddir}/mini-tests.sh --prefix=${prefix} if [ $? -ne 0 ]; then echo "There were problems running the tests!" 1>&2 exit 1 diff --git a/build/nightlyDiff.sh b/build/nightlyDiff.sh deleted file mode 100755 index 0e3c1c5a..00000000 --- a/build/nightlyDiff.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash -# $Id$ -# -# displays the changes in git develop for yesterday - -usage() -{ - echo "usage: nightlyDiff.sh [-sfh] [-d days] [-b branch]" - echo " -h display this help" - echo " -s display only a summary of the files changed" - echo " -f display fancy diffstat" - echo " -d days go back days days" -# echo " -b branch display changes for branch branch instead of develop" -} - -urlencode() -{ - local arg - arg="$1" - while [[ "$arg" =~ ^([0-9a-zA-Z/:_\.\-]*)([^0-9a-zA-Z/:_\.\-])(.*) ]] ; do - echo -n "${BASH_REMATCH[1]}" - printf "%%%X" "'${BASH_REMATCH[2]}'" - arg="${BASH_REMATCH[3]}" - done - echo -n "$arg" -} - -DAYSAGO=1 -BRANCH=develop -while getopts ":sfhd:b:" options; do - case $options in - s ) SUMMARY_ONLY="--name-only" ;; - f ) FANCY="--stat" ;; - d ) DAYSAGO=$OPTARG ;; - b ) BRANCH=$OPTARG ; echo "-b doesn't work yet" 1>&2; exit 1 ;; - h ) usage; exit 0 ;; - * ) usage; exit 1 ;; - esac -done - -secs=$(($(date +%s)-60*60*24*DAYSAGO)) - -dt1=$(date --date=@$secs +%Y-%m-%d) - -BRANCH=$(urlencode "$BRANCH") - -if [ $BRANCH != develop ]; then - BRANCH=branches/$BRANCH -fi - -git diff $SUMMARY_ONLY $FANCY "$BRANCH@{${dt1} 00:00:00}..$BRANCH@{${dt1} 23:59:59}" - diff --git a/build/releasenum b/build/releasenum index 6534ac6a..55cf6b17 100644 --- a/build/releasenum +++ b/build/releasenum @@ -1,5 +1,3 @@ -# - -version=4.6.1 -release=1 +version=3.5 +release=0 diff --git a/build/src-build b/build/src-build deleted file mode 100755 index d5470d30..00000000 --- a/build/src-build +++ /dev/null @@ -1,138 +0,0 @@ -#!/bin/bash - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -prefix=/usr/local -for arg in "$@"; do - if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then - prefix="`echo $arg | awk -F= '{print $2}'`" - else - echo "ignoring unknown argument: $arg" 1>&2 - fi -done - -if [ ! -d build ]; then - echo "No build directory found, giving up. (maybe you're not in the right directory?)" 1>&2 - exit 1 -fi - -bison --version >/dev/null 2>&1 -if [ $? -ne 0 ]; then - echo "No 'bison' program installed, giving up." 1>&2 - exit 1 -fi -flex --version >/dev/null 2>&1 -if [ $? -ne 0 ]; then - echo "No 'flex' program installed, giving up." 1>&2 - exit 1 -fi -autoreconf --version >/dev/null 2>&1 -if [ $? -ne 0 ]; then - echo "No 'autoreconf' program installed, giving up." 1>&2 - exit 1 -fi -expect -v >/dev/null 2>&1 -if [ $? -ne 0 ]; then - echo "No 'expect' program installed, giving up." 1>&2 - exit 1 -fi - -mysqldir= -for testdir in ./mysql ./mysql-master ../mysql ../mysql-master; do - if [ -d $testdir ]; then - mysqldir=$testdir - break - fi -done - -if [ -z "$mysqldir" ]; then - echo "Didn't find a MySQL tree, looking for a ZIP file..." - for testfile in ./mysql-master.zip ../mysql-master.zip; do - if [ -f $testfile ]; then - unzip -qq $testfile - break - fi - done - for testdir in ./mysql ./mysql-master; do - if [ -d $testdir ]; then - mysqldir=$testdir - break - fi - done -fi - -if [ -z "$mysqldir" ]; then - echo "Didn't find a MySQL tree and didn't find a ZIP file. Going to github..." - git --version >/dev/null 2>&1 - if [ $? -ne 0 ]; then - echo "No 'git' program installed, giving up (maybe you could download infinidb-mysql?)." 1>&2 - exit 1 - fi - git clone https://github.com/infinidb/mysql --branch=master --quiet - if [ $? -ne 0 ]; then - echo "Cloning from github didn't work, giving up." 1>&2 - exit 1 - fi - if [ ! -x ./mysql/idbbuild.sh ]; then - echo "Didn't find mysql build script, giving up." 1>&2 - exit 1 - fi - mysqldir=./mysql -fi - -echo "Using MySQL tree in $mysqldir" - -echo "Building MySQL..." - -( cd $mysqldir; - ./idbbuild.sh --prefix=$prefix/Calpont && make install ) >./mysql_build.log 2>&1 - -if [ $? -ne 0 -o ! -x $prefix/Calpont/mysql/libexec/mysqld ]; then - echo "Something went wrong building MySQL, giving up. (check ./mysql_build.log)" 1>&2 - exit 1 -fi - -if [ $mysqldir = "./mysql" -o $mysqldir = "./mysql-master" ]; then - ( bn=$(basename $(pwd)); cd ..; ln -s $bn/$mysqldir mysql ) >/dev/null 2>&1 -fi - -if [ ! -f ../mysql/include/mysql_version.h ]; then - echo "Couldn't find mysql_version.h in ../mysql/include, giving up." 1>&2 - exit 1 -fi - -echo "Building InfiniDB..." - -( cp -r utils/autoconf/* .; - autoreconf; - libtoolize --force --install; - mv -f $mysqldir/Makefile $mysqldir/Makefile.bak; - ./configure --prefix=$prefix && make && make install ) >./infinidb_build.log 2>&1 - -if [ $? -ne 0 -o ! -x $prefix/Calpont/bin/PrimProc ]; then - echo "Something went wrong building InfiniDB, giving up. (check ./infinidb_build.log)" 1>&2 - exit 1 -fi - -cp dbcon/mysql/my.cnf $prefix/Calpont/mysql -cp utils/jemalloc/libjemalloc.so.3.3.0 $prefix/Calpont/lib/libjemalloc.so - -echo "InfiniDB binaries and libs are in $prefix/Calpont" - -exit 0 - diff --git a/build_mysql.sh b/build_mysql.sh new file mode 100755 index 00000000..99856788 --- /dev/null +++ b/build_mysql.sh @@ -0,0 +1,59 @@ +#!/bin/bash + +mysqldir=mysql-5.1.39 + +prefix=/usr/local +withdebug= +for arg in "$@"; do + if [ $(expr -- "$arg" : '--prefix=') -eq 9 ]; then + prefix="$(echo $arg | awk -F= '{print $2}')" + elif [ $(expr -- "$arg" : '--with-debug') -eq 12 ]; then + withdebug=--with-debug + else + echo "ignoring unknown argument: $arg" 1>&2 + fi +done + +if [ ! -d $mysqldir ]; then + echo "Didn't find required MySQL install directory: $mysqldir" 1>&2 + exit 1 +fi + +cd $mysqldir + +if [ ! -d ../dbcon/mysql ]; then + echo "Didn't find required MySQL patch source directory: ../dbcon/mysql" 1>&2 + exit 1 +fi + +for file in configure.in; do + cp ../dbcon/mysql/$file . +done + +pushd ../dbcon/mysql >/dev/null +filelist=$(ls -1 *.cc *.h *.yy | sed -e '/^ha_/d' -e '/^idb_/d') +popd >/dev/null +for file in $filelist; do + cp ../dbcon/mysql/$file sql +done +cp ../dbcon/mysql/include/*.h include +cp ../dbcon/mysql/mysys/*.h mysys + +autoreconf --force --install +./configure --prefix="$prefix/Calpont/mysql" $withdebug --without-libedit --with-readline --with-client-ldflags="-Wl,-rpath -Wl,/usr/local/Calpont/mysql/lib/mysql" + +make || exit 1 +make install + +cp ../dbcon/mysql/my.cnf $prefix/Calpont/mysql + +for dir in \ +docs \ +man \ +mysql-test \ +sql-bench +do + rm -rf $prefix/Calpont/mysql/$dir +done +rm -rf $prefix/Calpont/mysql/share/man + diff --git a/config.h.in b/config.h.in index b14d8105..1fc91e6d 100644 --- a/config.h.in +++ b/config.h.in @@ -108,9 +108,6 @@ /* Define to 1 if you have the `mkdir' function. */ #undef HAVE_MKDIR -/* Define to 1 if you have the header file. */ -#undef HAVE_NCURSES_H - /* Define to 1 if you have the header file. */ #undef HAVE_NETDB_H @@ -123,9 +120,6 @@ /* Define to 1 if the system has the type `ptrdiff_t'. */ #undef HAVE_PTRDIFF_T -/* Define to 1 if you have the header file. */ -#undef HAVE_READLINE_READLINE_H - /* Define to 1 if you have the `regcomp' function. */ #undef HAVE_REGCOMP @@ -274,9 +268,6 @@ /* Define to 1 if `vfork' works. */ #undef HAVE_WORKING_VFORK -/* Define to 1 if you have the header file. */ -#undef HAVE_ZLIB_H - /* Define to 1 if the system has the type `_Bool'. */ #undef HAVE__BOOL diff --git a/configure b/configure index ff9d7ee8..7121ce08 100755 --- a/configure +++ b/configure @@ -1,8 +1,8 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.59 for infinidb 4.6.1. +# Generated by GNU Autoconf 2.59 for Calpont 1.0.0. # -# Report bugs to . +# Report bugs to . # # Copyright (C) 2003 Free Software Foundation, Inc. # This configure script is free software; the Free Software Foundation @@ -421,11 +421,11 @@ SHELL=${CONFIG_SHELL-/bin/sh} : ${ac_max_here_lines=38} # Identity of this package. -PACKAGE_NAME='infinidb' -PACKAGE_TARNAME='infinidb' -PACKAGE_VERSION='4.6.1' -PACKAGE_STRING='infinidb 4.6.1' -PACKAGE_BUGREPORT='support@infinidb.co' +PACKAGE_NAME='Calpont' +PACKAGE_TARNAME='calpont' +PACKAGE_VERSION='1.0.0' +PACKAGE_STRING='Calpont 1.0.0' +PACKAGE_BUGREPORT='support@calpont.com' ac_default_prefix=/usr/local # Factoring default headers for most tests. @@ -465,7 +465,7 @@ ac_includes_default="\ # include #endif" -ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot AMTAR am__tar am__untar CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE CXX CXXFLAGS ac_ct_CXX CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE build build_cpu build_vendor build_os host host_cpu host_vendor host_os SED EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL LEX LEXLIB LEX_OUTPUT_ROOT YACC ALLOCA LIBOBJS POW_LIB XML2_CONFIG XML_CPPFLAGS XML_LIBS idb_cppflags idb_cxxflags idb_cflags idbinstall idb_ldflags march_flags etcdir sharedir postdir localdir mysqldir mibdir netsnmpdir netsnmpsysdir netsnmpmachdir netsnmplibrdir netsnmpagntdir toolsdir netsnmp_libs idb_common_libs idb_oam_libs idb_brm_libs idb_exec_libs idb_write_libs idb_common_includes idb_common_ldflags LTLIBOBJS' +ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot AMTAR am__tar am__untar CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE CXX CXXFLAGS ac_ct_CXX CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE build build_cpu build_vendor build_os host host_cpu host_vendor host_os SED EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL LEX LEXLIB LEX_OUTPUT_ROOT YACC ALLOCA LIBOBJS POW_LIB idb_cppflags idb_cxxflags idb_cflags idb_ldflags march_flags etcdir sharedir postdir localdir mysqldir toolsdir mibdir netsnmp_libs idb_common_libs idb_oam_libs idb_brm_libs idb_exec_libs idb_write_libs idb_common_includes idb_common_ldflags LTLIBOBJS' ac_subst_files='' # Initialize some variables set by options. @@ -954,7 +954,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures infinidb 4.6.1 to adapt to many kinds of systems. +\`configure' configures Calpont 1.0.0 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1020,7 +1020,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of infinidb 4.6.1:";; + short | recursive ) echo "Configuration of Calpont 1.0.0:";; esac cat <<\_ACEOF @@ -1036,7 +1036,6 @@ Optional Features: --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) - --disable-xmltest Do not try to compile and run a test LIBXML program Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] @@ -1046,8 +1045,6 @@ Optional Packages: both] --with-tags[=TAGS] include additional configurations [automatic] - --with-xml-prefix=PFX Prefix where libxml is installed (optional) - --with-xml-exec-prefix=PFX Exec prefix where libxml is installed (optional) --with-debug include debugging symbols/no optimization Some influential environment variables: @@ -1067,7 +1064,7 @@ Some influential environment variables: Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. -Report bugs to . +Report bugs to . _ACEOF fi @@ -1163,7 +1160,7 @@ fi test -n "$ac_init_help" && exit 0 if $ac_init_version; then cat <<\_ACEOF -infinidb configure 4.6.1 +Calpont configure 1.0.0 generated by GNU Autoconf 2.59 Copyright (C) 2003 Free Software Foundation, Inc. @@ -1177,7 +1174,7 @@ cat >&5 <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by infinidb $as_me 4.6.1, which was +It was created by Calpont $as_me 1.0.0, which was generated by GNU Autoconf 2.59. Invocation command line was $ $0 $@ @@ -1832,8 +1829,8 @@ fi # Define the identity of the package. - PACKAGE='infinidb' - VERSION='4.6.1' + PACKAGE='calpont' + VERSION='1.0.0' cat >>confdefs.h <<_ACEOF @@ -4176,7 +4173,7 @@ ia64-*-hpux*) ;; *-*-irix6*) # Find out which ABI we are using. - echo '#line 4179 "configure"' > conftest.$ac_ext + echo '#line 4176 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -4954,7 +4951,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -5311,7 +5308,7 @@ fi # Provide some information about the compiler. -echo "$as_me:5314:" \ +echo "$as_me:5311:" \ "checking for Fortran 77 compiler version" >&5 ac_compiler=`set X $ac_compile; echo $2` { (eval echo "$as_me:$LINENO: \"$ac_compiler --version &5\"") >&5 @@ -6374,11 +6371,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6377: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6374: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:6381: \$? = $ac_status" >&5 + echo "$as_me:6378: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -6642,11 +6639,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6645: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6642: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:6649: \$? = $ac_status" >&5 + echo "$as_me:6646: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -6746,11 +6743,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6749: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6746: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:6753: \$? = $ac_status" >&5 + echo "$as_me:6750: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -8215,7 +8212,7 @@ linux*) libsuff= case "$host_cpu" in x86_64*|s390x*|powerpc64*) - echo '#line 8218 "configure"' > conftest.$ac_ext + echo '#line 8215 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -9112,7 +9109,7 @@ else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext < conftest.$ac_ext <&5) + (eval echo "\"\$as_me:11555: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:11562: \$? = $ac_status" >&5 + echo "$as_me:11559: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -11659,11 +11656,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:11662: $lt_compile\"" >&5) + (eval echo "\"\$as_me:11659: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:11666: \$? = $ac_status" >&5 + echo "$as_me:11663: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -12195,7 +12192,7 @@ linux*) libsuff= case "$host_cpu" in x86_64*|s390x*|powerpc64*) - echo '#line 12198 "configure"' > conftest.$ac_ext + echo '#line 12195 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -13253,11 +13250,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:13256: $lt_compile\"" >&5) + (eval echo "\"\$as_me:13253: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:13260: \$? = $ac_status" >&5 + echo "$as_me:13257: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -13357,11 +13354,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:13360: $lt_compile\"" >&5) + (eval echo "\"\$as_me:13357: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:13364: \$? = $ac_status" >&5 + echo "$as_me:13361: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -14806,7 +14803,7 @@ linux*) libsuff= case "$host_cpu" in x86_64*|s390x*|powerpc64*) - echo '#line 14809 "configure"' > conftest.$ac_ext + echo '#line 14806 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -15584,11 +15581,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:15587: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15584: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:15591: \$? = $ac_status" >&5 + echo "$as_me:15588: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -15852,11 +15849,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:15855: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15852: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:15859: \$? = $ac_status" >&5 + echo "$as_me:15856: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -15956,11 +15953,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:15959: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15956: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:15963: \$? = $ac_status" >&5 + echo "$as_me:15960: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -17425,7 +17422,7 @@ linux*) libsuff= case "$host_cpu" in x86_64*|s390x*|powerpc64*) - echo '#line 17428 "configure"' > conftest.$ac_ext + echo '#line 17425 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -20113,7 +20110,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -21620,7 +21617,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -21791,7 +21788,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -22275,7 +22272,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -22589,7 +22586,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -23053,7 +23050,7 @@ echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precede ( cat <<\_ASBOX ## ---------------------------------- ## -## Report this to support@infinidb.co ## +## Report this to support@calpont.com ## ## ---------------------------------- ## _ASBOX ) | @@ -24490,953 +24487,9 @@ fi done - - -# Check whether --with-xml-prefix or --without-xml-prefix was given. -if test "${with_xml_prefix+set}" = set; then - withval="$with_xml_prefix" - xml_config_prefix="$withval" -else - xml_config_prefix="" -fi; - -# Check whether --with-xml-exec-prefix or --without-xml-exec-prefix was given. -if test "${with_xml_exec_prefix+set}" = set; then - withval="$with_xml_exec_prefix" - xml_config_exec_prefix="$withval" -else - xml_config_exec_prefix="" -fi; -# Check whether --enable-xmltest or --disable-xmltest was given. -if test "${enable_xmltest+set}" = set; then - enableval="$enable_xmltest" - -else - enable_xmltest=yes -fi; - - if test x$xml_config_exec_prefix != x ; then - xml_config_args="$xml_config_args" - if test x${XML2_CONFIG+set} != xset ; then - XML2_CONFIG=$xml_config_exec_prefix/bin/xml2-config - fi - fi - if test x$xml_config_prefix != x ; then - xml_config_args="$xml_config_args --prefix=$xml_config_prefix" - if test x${XML2_CONFIG+set} != xset ; then - XML2_CONFIG=$xml_config_prefix/bin/xml2-config - fi - fi - - # Extract the first word of "xml2-config", so it can be a program name with args. -set dummy xml2-config; ac_word=$2 -echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 -if test "${ac_cv_path_XML2_CONFIG+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $XML2_CONFIG in - [\\/]* | ?:[\\/]*) - ac_cv_path_XML2_CONFIG="$XML2_CONFIG" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_XML2_CONFIG="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done - - test -z "$ac_cv_path_XML2_CONFIG" && ac_cv_path_XML2_CONFIG="no" - ;; -esac -fi -XML2_CONFIG=$ac_cv_path_XML2_CONFIG - -if test -n "$XML2_CONFIG"; then - echo "$as_me:$LINENO: result: $XML2_CONFIG" >&5 -echo "${ECHO_T}$XML2_CONFIG" >&6 -else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 -fi - - min_xml_version=2.6.26 - echo "$as_me:$LINENO: checking for libxml - version >= $min_xml_version" >&5 -echo $ECHO_N "checking for libxml - version >= $min_xml_version... $ECHO_C" >&6 - no_xml="" - if test "$XML2_CONFIG" = "no" ; then - no_xml=yes - else - XML_CPPFLAGS=`$XML2_CONFIG $xml_config_args --cflags` - XML_LIBS=`$XML2_CONFIG $xml_config_args --libs` - xml_config_major_version=`$XML2_CONFIG $xml_config_args --version | \ - sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\1/'` - xml_config_minor_version=`$XML2_CONFIG $xml_config_args --version | \ - sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\2/'` - xml_config_micro_version=`$XML2_CONFIG $xml_config_args --version | \ - sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\3/'` - if test "x$enable_xmltest" = "xyes" ; then - ac_save_CPPFLAGS="$CPPFLAGS" - ac_save_LIBS="$LIBS" - CPPFLAGS="$CPPFLAGS $XML_CPPFLAGS" - LIBS="$XML_LIBS $LIBS" - rm -f conf.xmltest - if test "$cross_compiling" = yes; then - echo $ac_n "cross compiling; assumed OK... $ac_c" -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include -#include -#include - -int -main() -{ - int xml_major_version, xml_minor_version, xml_micro_version; - int major, minor, micro; - char *tmp_version; - - system("touch conf.xmltest"); - - /* Capture xml2-config output via autoconf/configure variables */ - /* HP/UX 9 (%@#!) writes to sscanf strings */ - tmp_version = (char *)strdup("$min_xml_version"); - if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, µ) != 3) { - printf("%s, bad version string from xml2-config\n", "$min_xml_version"); - exit(1); - } - free(tmp_version); - - /* Capture the version information from the header files */ - tmp_version = (char *)strdup(LIBXML_DOTTED_VERSION); - if (sscanf(tmp_version, "%d.%d.%d", &xml_major_version, &xml_minor_version, &xml_micro_version) != 3) { - printf("%s, bad version string from libxml includes\n", "LIBXML_DOTTED_VERSION"); - exit(1); - } - free(tmp_version); - - /* Compare xml2-config output to the libxml headers */ - if ((xml_major_version != $xml_config_major_version) || - (xml_minor_version != $xml_config_minor_version) || - (xml_micro_version != $xml_config_micro_version)) - { - printf("*** libxml header files (version %d.%d.%d) do not match\n", - xml_major_version, xml_minor_version, xml_micro_version); - printf("*** xml2-config (version %d.%d.%d)\n", - $xml_config_major_version, $xml_config_minor_version, $xml_config_micro_version); - return 1; - } -/* Compare the headers to the library to make sure we match */ - /* Less than ideal -- doesn't provide us with return value feedback, - * only exits if there's a serious mismatch between header and library. - */ - LIBXML_TEST_VERSION; - - /* Test that the library is greater than our minimum version */ - if ((xml_major_version > major) || - ((xml_major_version == major) && (xml_minor_version > minor)) || - ((xml_major_version == major) && (xml_minor_version == minor) && - (xml_micro_version >= micro))) - { - return 0; - } - else - { - printf("\n*** An old version of libxml (%d.%d.%d) was found.\n", - xml_major_version, xml_minor_version, xml_micro_version); - printf("*** You need a version of libxml newer than %d.%d.%d. The latest version of\n", - major, minor, micro); - printf("*** libxml is always available from ftp://ftp.xmlsoft.org.\n"); - printf("***\n"); - printf("*** If you have already installed a sufficiently new version, this error\n"); - printf("*** probably means that the wrong copy of the xml2-config shell script is\n"); - printf("*** being found. The easiest way to fix this is to remove the old version\n"); - printf("*** of LIBXML, but you can also set the XML2_CONFIG environment to point to the\n"); - printf("*** correct copy of xml2-config. (In this case, you will have to\n"); - printf("*** modify your LD_LIBRARY_PATH enviroment variable, or edit /etc/ld.so.conf\n"); - printf("*** so that the correct libraries are found at run-time))\n"); - } - return 1; -} - -_ACEOF -rm -f conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -no_xml=yes -fi -rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - CPPFLAGS="$ac_save_CPPFLAGS" - LIBS="$ac_save_LIBS" - fi - fi - - if test "x$no_xml" = x ; then - echo "$as_me:$LINENO: result: yes (version $xml_config_major_version.$xml_config_minor_version.$xml_config_micro_version)" >&5 -echo "${ECHO_T}yes (version $xml_config_major_version.$xml_config_minor_version.$xml_config_micro_version)" >&6 - : - else - echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 - if test "$XML2_CONFIG" = "no" ; then - echo "*** The xml2-config script installed by LIBXML could not be found" - echo "*** If libxml was installed in PREFIX, make sure PREFIX/bin is in" - echo "*** your path, or set the XML2_CONFIG environment variable to the" - echo "*** full path to xml2-config." - else - if test -f conf.xmltest ; then - : - else - echo "*** Could not run libxml test program, checking why..." - CPPFLAGS="$CPPFLAGS $XML_CPPFLAGS" - LIBS="$LIBS $XML_LIBS" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include - -int -main () -{ - LIBXML_TEST_VERSION; return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 - (eval $ac_link) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest$ac_exeext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - echo "*** The test program compiled, but did not run. This usually means" - echo "*** that the run-time linker is not finding LIBXML or finding the wrong" - echo "*** version of LIBXML. If it is not finding LIBXML, you'll need to set your" - echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" - echo "*** to the installed location Also, make sure you have run ldconfig if that" - echo "*** is required on your system" - echo "***" - echo "*** If you have an old version installed, it is best to remove it, although" - echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - echo "*** The test program failed to compile or link. See the file config.log for the" - echo "*** exact error that occured. This usually means LIBXML was incorrectly installed" - echo "*** or that you have moved LIBXML since it was installed. In the latter case, you" - echo "*** may want to edit the xml2-config script: $XML2_CONFIG" -fi -rm -f conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - CPPFLAGS="$ac_save_CPPFLAGS" - LIBS="$ac_save_LIBS" - fi - fi - - XML_CPPFLAGS="" - XML_LIBS="" - : - fi - - - rm -f conf.xmltest - -if test "x$XML_CPPFLAGS" = "x"; then - { { echo "$as_me:$LINENO: error: Could not find a usable libxml2 development environment!" >&5 -echo "$as_me: error: Could not find a usable libxml2 development environment!" >&2;} - { (exit 1); exit 1; }; } -fi - - -for ac_header in zlib.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 -else - # Is the header compilable? -echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -ac_header_compiler=no -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6 - -# Is the header present? -echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_cxx_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag - else - ac_cpp_err= - fi -else - ac_cpp_err=yes -fi -if test -z "$ac_cpp_err"; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi -rm -f conftest.err conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6 - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_cxx_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( - cat <<\_ASBOX -## ---------------------------------- ## -## Report this to support@infinidb.co ## -## ---------------------------------- ## -_ASBOX - ) | - sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - -if test "x$ac_cv_header_zlib_h" != "xyes"; then - { { echo "$as_me:$LINENO: error: Could not find a usable zlib development environment!" >&5 -echo "$as_me: error: Could not find a usable zlib development environment!" >&2;} - { (exit 1); exit 1; }; } -fi - - -for ac_header in readline/readline.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 -else - # Is the header compilable? -echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -ac_header_compiler=no -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6 - -# Is the header present? -echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_cxx_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag - else - ac_cpp_err= - fi -else - ac_cpp_err=yes -fi -if test -z "$ac_cpp_err"; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi -rm -f conftest.err conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6 - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_cxx_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( - cat <<\_ASBOX -## ---------------------------------- ## -## Report this to support@infinidb.co ## -## ---------------------------------- ## -_ASBOX - ) | - sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - -if test "x$ac_cv_header_readline_readline_h" != "xyes"; then - { { echo "$as_me:$LINENO: error: Could not find a usable readline development environment!" >&5 -echo "$as_me: error: Could not find a usable readline development environment!" >&2;} - { (exit 1); exit 1; }; } -fi - - -for ac_header in ncurses.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 -else - # Is the header compilable? -echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -ac_header_compiler=no -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6 - -# Is the header present? -echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 - (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null; then - if test -s conftest.err; then - ac_cpp_err=$ac_cxx_preproc_warn_flag - ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag - else - ac_cpp_err= - fi -else - ac_cpp_err=yes -fi -if test -z "$ac_cpp_err"; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi -rm -f conftest.err conftest.$ac_ext -echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6 - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_cxx_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( - cat <<\_ASBOX -## ---------------------------------- ## -## Report this to support@infinidb.co ## -## ---------------------------------- ## -_ASBOX - ) | - sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 -if eval "test \"\${$as_ac_Header+set}\" = set"; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 -echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - -if test "x$ac_cv_header_ncurses_h" != "xyes"; then - { { echo "$as_me:$LINENO: error: Could not find a usable ncurses development environment!" >&5 -echo "$as_me: error: Could not find a usable ncurses development environment!" >&2;} - { (exit 1); exit 1; }; } -fi - - echo "$as_me:$LINENO: checking if $CXX supports -Wno-unused-local-typedefs" >&5 -echo $ECHO_N "checking if $CXX supports -Wno-unused-local-typedefs... $ECHO_C" >&6 - ac_saved_cxxflags="$CXXFLAGS" - CXXFLAGS="-Werror -Wno-unused-local-typedefs" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6 - cxx_extra_flags="$cxx_extra_flags -Wno-unused-local-typedefs" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 - -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - CXXFLAGS="$ac_saved_cxxflags" - - echo "$as_me:$LINENO: checking if $CXX supports -Wno-unused-result" >&5 -echo $ECHO_N "checking if $CXX supports -Wno-unused-result... $ECHO_C" >&6 - ac_saved_cxxflags="$CXXFLAGS" - CXXFLAGS="-Werror -Wno-unused-result" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6 - cxx_extra_flags="$cxx_extra_flags -Wno-unused-result" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 - -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - CXXFLAGS="$ac_saved_cxxflags" - - echo "$as_me:$LINENO: checking if $CXX supports -Wno-format" >&5 -echo $ECHO_N "checking if $CXX supports -Wno-format... $ECHO_C" >&6 - ac_saved_cxxflags="$CXXFLAGS" - CXXFLAGS="-Werror -Wno-format" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && - { ac_try='test -z "$ac_cxx_werror_flag" - || test ! -s conftest.err' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; } && - { ac_try='test -s conftest.$ac_objext' - { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 - (eval $ac_try) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6 - cxx_extra_flags="$cxx_extra_flags -Wno-format" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6 - -fi -rm -f conftest.err conftest.$ac_objext conftest.$ac_ext - CXXFLAGS="$ac_saved_cxxflags" - - echo "$as_me:$LINENO: checking whether to enable debugging" >&5 echo $ECHO_N "checking whether to enable debugging... $ECHO_C" >&6 -idb_cppflags=' ' +idb_cppflags='-DSKIP_SNMP -DSKIP_UDF -DSKIP_IDB_COMPRESSION -DCOMMUNITY_KEYRANGE -DSKIP_VIEW -DSKIP_INSERT_SELECT -DSKIP_AUTOI -DSKIP_OAM_INIT' # Check whether --with-debug or --without-debug was given. @@ -25452,16 +24505,14 @@ if test "x$with_debug" = "xyes"; then echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else - idb_cxxflags="-g0 -O3 -fno-strict-aliasing -Wall $cxx_extra_flags" + idb_cxxflags='-g0 -O3 -fno-strict-aliasing -Wall' idb_cflags='-g0 -O3 -fno-strict-aliasing -Wall' echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi -idbinstall='${prefix}' - -idb_ldflags='-Wl,--rpath -Wl,${idbinstall}/lib -Wl,--no-as-needed -Wl,--add-needed' +idb_ldflags='-Wl,--rpath -Wl,/usr/local/Calpont/lib -Wl,--no-as-needed -Wl,--add-needed' echo "$as_me:$LINENO: checking for CPU architecture" >&5 @@ -25479,62 +24530,52 @@ echo "${ECHO_T}x86_64" >&6 fi -libdir='${idbinstall}/lib' - -bindir='${idbinstall}/bin' - -includedir='${idbinstall}/include' - -etcdir='${idbinstall}/etc' +libdir='${prefix}/Calpont/lib' -sysconfdir='${idbinstall}/etc' +bindir='${prefix}/Calpont/bin' -mandir='${idbinstall}/man' +includedir='${prefix}/Calpont/include' -sbindir='${idbinstall}/sbin' +etcdir='${prefix}/Calpont/etc' -sharedir='${idbinstall}/share' +sysconfdir='${prefix}/Calpont/etc' -postdir='${idbinstall}/post' +mandir='${prefix}/Calpont/man' -localdir='${idbinstall}/local' +sbindir='${prefix}/Calpont/sbin' -mysqldir='${idbinstall}/mysql' +sharedir='${prefix}/Calpont/share' -mibdir='${idbinstall}/share/snmp/mibs' +postdir='${prefix}/Calpont/post' -netsnmpdir='${idbinstall}/include/net-snmp' +localdir='${prefix}/Calpont/local' -netsnmpsysdir='${idbinstall}/include/net-snmp/system' +mysqldir='${prefix}/Calpont/mysql' -netsnmpmachdir='${idbinstall}/include/net-snmp/machine' +toolsdir='${prefix}/Calpont/tools' -netsnmplibrdir='${idbinstall}/include/net-snmp/library' +mibdir='${prefix}/Calpont/share/snmp/mibs' -netsnmpagntdir='${idbinstall}/include/net-snmp/agent' -toolsdir='${idbinstall}/tools' - - -netsnmp_libs='-lnetsnmpmibs -lnetsnmpagent -lnetsnmp -lnetsnmpmibs -lnetsnmphelpers' +netsnmp_libs=' ' idb_common_libs='-lmessageqcpp -lloggingcpp -lconfigcpp -lidbboot -lboost_idb -lxml2 -lpthread -lrt' idb_oam_libs='-loamcpp -lsnmpmanager ${netsnmp_libs}' -idb_brm_libs='-lbrm -lidbdatafile -lcacheutils -lrwlock ${idb_oam_libs} ${idb_common_libs}' +idb_brm_libs='-lbrm -lrwlock -lcacheutils ${idb_oam_libs} ${idb_common_libs}' -idb_exec_libs='-ljoblist -lexecplan -lwindowfunction -ljoiner -lrowgroup -lfuncexp -ludfsdk -ldataconvert -lcommon -lcompress -lmysqlcl_idb -lquerystats -lquerytele -lthrift -lthreadpool ${idb_brm_libs}' +idb_exec_libs='-ljoblist -lexecplan -ljoiner -lrowgroup -lmulticast -lfuncexp -ldataconvert -lcommon -lmysqlcl_idb -lquerystats ${idb_brm_libs}' -idb_write_libs='-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lidbdatafile -lcacheutils ${idb_exec_libs}' +idb_write_libs='-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lcacheutils ${idb_exec_libs}' -idb_common_includes='-I${idbinstall}/include -I/usr/local/include -I/usr/local/include/libxml2 -I/usr/include/libxml2' +idb_common_includes='-I${prefix}/Calpont/include -I/usr/local/include -I/usr/local/include/libxml2 -I/usr/include/libxml2' -idb_common_ldflags='-L${idbinstall}/lib -L/usr/local/lib' +idb_common_ldflags='-L${prefix}/Calpont/lib -L/usr/local/lib' - ac_config_files="$ac_config_files Makefile utils/Makefile utils/boost_idb/Makefile utils/startup/Makefile utils/common/Makefile utils/configcpp/Makefile utils/loggingcpp/Makefile utils/messageqcpp/Makefile utils/threadpool/Makefile utils/rwlock/Makefile utils/dataconvert/Makefile utils/joiner/Makefile utils/rowgroup/Makefile utils/cacheutils/Makefile utils/net-snmp/Makefile utils/funcexp/Makefile utils/udfsdk/Makefile utils/compress/Makefile utils/ddlcleanup/Makefile utils/batchloader/Makefile utils/mysqlcl_idb/Makefile utils/querystats/Makefile utils/jemalloc/Makefile utils/windowfunction/Makefile utils/idbdatafile/Makefile utils/idbhdfs/Makefile utils/idbhdfs/hdfs-12/Makefile utils/idbhdfs/hdfs-20/Makefile utils/winport/Makefile utils/thrift/Makefile utils/querytele/Makefile exemgr/Makefile ddlproc/Makefile dbcon/Makefile dbcon/ddlpackage/Makefile dbcon/ddlpackageproc/Makefile dbcon/dmlpackage/Makefile dbcon/dmlpackageproc/Makefile dbcon/execplan/Makefile dbcon/joblist/Makefile dbcon/mysql/Makefile dmlproc/Makefile oam/Makefile oam/etc/Makefile oam/install_scripts/Makefile oam/oamcpp/Makefile oam/post/Makefile oam/cloud/Makefile oamapps/Makefile oamapps/calpontConsole/Makefile oamapps/calpontDB/Makefile oamapps/postConfigure/Makefile oamapps/serverMonitor/Makefile oamapps/sessionWalker/Makefile oamapps/traphandler/Makefile oamapps/sendtrap/Makefile oamapps/calpontSupport/Makefile primitives/Makefile primitives/blockcache/Makefile primitives/linux-port/Makefile primitives/primproc/Makefile decomsvr/Makefile procmgr/Makefile procmon/Makefile snmpd/Makefile snmpd/etc/Makefile snmpd/snmpmanager/Makefile tools/Makefile tools/editem/Makefile tools/cplogger/Makefile tools/clearShm/Makefile tools/setConfig/Makefile tools/getConfig/Makefile tools/dbbuilder/Makefile tools/dbloadxml/Makefile tools/configMgt/Makefile tools/viewtablelock/Makefile tools/cleartablelock/Makefile tools/ddlcleanup/Makefile tools/idbmeminfo/Makefile versioning/Makefile versioning/BRM/Makefile writeengine/Makefile writeengine/shared/Makefile writeengine/index/Makefile writeengine/dictionary/Makefile writeengine/wrapper/Makefile writeengine/xml/Makefile writeengine/bulk/Makefile writeengine/client/Makefile writeengine/splitter/Makefile writeengine/server/Makefile writeengine/redistribute/Makefile net-snmp/Makefile" + ac_config_files="$ac_config_files Makefile utils/Makefile utils/boost_idb/Makefile utils/startup/Makefile utils/common/Makefile utils/configcpp/Makefile utils/loggingcpp/Makefile utils/messageqcpp/Makefile utils/threadpool/Makefile utils/rwlock/Makefile utils/dataconvert/Makefile utils/joiner/Makefile utils/rowgroup/Makefile utils/cacheutils/Makefile utils/multicast/Makefile utils/funcexp/Makefile utils/compress/Makefile utils/ddlcleanup/Makefile utils/batchloader/Makefile utils/mysqlcl_idb/Makefile utils/querystats/Makefile exemgr/Makefile ddlproc/Makefile dbcon/Makefile dbcon/ddlpackage/Makefile dbcon/ddlpackageproc/Makefile dbcon/dmlpackage/Makefile dbcon/dmlpackageproc/Makefile dbcon/execplan/Makefile dbcon/joblist/Makefile dbcon/mysql/Makefile dbcon/sm/Makefile dmlproc/Makefile oam/Makefile oam/etc/Makefile oam/install_scripts/Makefile oam/oamcpp/Makefile oam/post/Makefile oam/replaytxnlog/Makefile oamapps/Makefile oamapps/replayTransactionLog/Makefile primitives/Makefile primitives/blockcache/Makefile primitives/linux-port/Makefile primitives/primproc/Makefile decomsvr/Makefile snmpd/Makefile snmpd/etc/Makefile snmpd/snmpmanager/Makefile tools/Makefile tools/editem/Makefile tools/cplogger/Makefile tools/clearShm/Makefile tools/setConfig/Makefile tools/getConfig/Makefile tools/dbbuilder/Makefile tools/dbloadxml/Makefile tools/viewtablelock/Makefile tools/cleartablelock/Makefile tools/ddlcleanup/Makefile tools/idbmeminfo/Makefile versioning/Makefile versioning/BRM/Makefile writeengine/Makefile writeengine/shared/Makefile writeengine/index/Makefile writeengine/dictionary/Makefile writeengine/wrapper/Makefile writeengine/xml/Makefile writeengine/bulk/Makefile writeengine/client/Makefile writeengine/splitter/Makefile writeengine/server/Makefile writeengine/cpimport/Makefile writeengine/redistribute/Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure @@ -25919,7 +24960,7 @@ _ASBOX } >&5 cat >&5 <<_CSEOF -This file was extended by infinidb $as_me 4.6.1, which was +This file was extended by Calpont $as_me 1.0.0, which was generated by GNU Autoconf 2.59. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -25985,7 +25026,7 @@ _ACEOF cat >>$CONFIG_STATUS <<_ACEOF ac_cs_version="\\ -infinidb config.status 4.6.1 +Calpont config.status 1.0.0 configured by $0, generated by GNU Autoconf 2.59, with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\" @@ -26109,23 +25150,13 @@ do "utils/joiner/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/joiner/Makefile" ;; "utils/rowgroup/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/rowgroup/Makefile" ;; "utils/cacheutils/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/cacheutils/Makefile" ;; - "utils/net-snmp/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/net-snmp/Makefile" ;; + "utils/multicast/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/multicast/Makefile" ;; "utils/funcexp/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/funcexp/Makefile" ;; - "utils/udfsdk/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/udfsdk/Makefile" ;; "utils/compress/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/compress/Makefile" ;; "utils/ddlcleanup/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/ddlcleanup/Makefile" ;; "utils/batchloader/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/batchloader/Makefile" ;; "utils/mysqlcl_idb/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/mysqlcl_idb/Makefile" ;; "utils/querystats/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/querystats/Makefile" ;; - "utils/jemalloc/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/jemalloc/Makefile" ;; - "utils/windowfunction/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/windowfunction/Makefile" ;; - "utils/idbdatafile/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/idbdatafile/Makefile" ;; - "utils/idbhdfs/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/idbhdfs/Makefile" ;; - "utils/idbhdfs/hdfs-12/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/idbhdfs/hdfs-12/Makefile" ;; - "utils/idbhdfs/hdfs-20/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/idbhdfs/hdfs-20/Makefile" ;; - "utils/winport/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/winport/Makefile" ;; - "utils/thrift/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/thrift/Makefile" ;; - "utils/querytele/Makefile" ) CONFIG_FILES="$CONFIG_FILES utils/querytele/Makefile" ;; "exemgr/Makefile" ) CONFIG_FILES="$CONFIG_FILES exemgr/Makefile" ;; "ddlproc/Makefile" ) CONFIG_FILES="$CONFIG_FILES ddlproc/Makefile" ;; "dbcon/Makefile" ) CONFIG_FILES="$CONFIG_FILES dbcon/Makefile" ;; @@ -26136,29 +25167,21 @@ do "dbcon/execplan/Makefile" ) CONFIG_FILES="$CONFIG_FILES dbcon/execplan/Makefile" ;; "dbcon/joblist/Makefile" ) CONFIG_FILES="$CONFIG_FILES dbcon/joblist/Makefile" ;; "dbcon/mysql/Makefile" ) CONFIG_FILES="$CONFIG_FILES dbcon/mysql/Makefile" ;; + "dbcon/sm/Makefile" ) CONFIG_FILES="$CONFIG_FILES dbcon/sm/Makefile" ;; "dmlproc/Makefile" ) CONFIG_FILES="$CONFIG_FILES dmlproc/Makefile" ;; "oam/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/Makefile" ;; "oam/etc/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/etc/Makefile" ;; "oam/install_scripts/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/install_scripts/Makefile" ;; "oam/oamcpp/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/oamcpp/Makefile" ;; "oam/post/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/post/Makefile" ;; - "oam/cloud/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/cloud/Makefile" ;; + "oam/replaytxnlog/Makefile" ) CONFIG_FILES="$CONFIG_FILES oam/replaytxnlog/Makefile" ;; "oamapps/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/Makefile" ;; - "oamapps/calpontConsole/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/calpontConsole/Makefile" ;; - "oamapps/calpontDB/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/calpontDB/Makefile" ;; - "oamapps/postConfigure/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/postConfigure/Makefile" ;; - "oamapps/serverMonitor/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/serverMonitor/Makefile" ;; - "oamapps/sessionWalker/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/sessionWalker/Makefile" ;; - "oamapps/traphandler/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/traphandler/Makefile" ;; - "oamapps/sendtrap/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/sendtrap/Makefile" ;; - "oamapps/calpontSupport/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/calpontSupport/Makefile" ;; + "oamapps/replayTransactionLog/Makefile" ) CONFIG_FILES="$CONFIG_FILES oamapps/replayTransactionLog/Makefile" ;; "primitives/Makefile" ) CONFIG_FILES="$CONFIG_FILES primitives/Makefile" ;; "primitives/blockcache/Makefile" ) CONFIG_FILES="$CONFIG_FILES primitives/blockcache/Makefile" ;; "primitives/linux-port/Makefile" ) CONFIG_FILES="$CONFIG_FILES primitives/linux-port/Makefile" ;; "primitives/primproc/Makefile" ) CONFIG_FILES="$CONFIG_FILES primitives/primproc/Makefile" ;; "decomsvr/Makefile" ) CONFIG_FILES="$CONFIG_FILES decomsvr/Makefile" ;; - "procmgr/Makefile" ) CONFIG_FILES="$CONFIG_FILES procmgr/Makefile" ;; - "procmon/Makefile" ) CONFIG_FILES="$CONFIG_FILES procmon/Makefile" ;; "snmpd/Makefile" ) CONFIG_FILES="$CONFIG_FILES snmpd/Makefile" ;; "snmpd/etc/Makefile" ) CONFIG_FILES="$CONFIG_FILES snmpd/etc/Makefile" ;; "snmpd/snmpmanager/Makefile" ) CONFIG_FILES="$CONFIG_FILES snmpd/snmpmanager/Makefile" ;; @@ -26170,7 +25193,6 @@ do "tools/getConfig/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/getConfig/Makefile" ;; "tools/dbbuilder/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/dbbuilder/Makefile" ;; "tools/dbloadxml/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/dbloadxml/Makefile" ;; - "tools/configMgt/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/configMgt/Makefile" ;; "tools/viewtablelock/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/viewtablelock/Makefile" ;; "tools/cleartablelock/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/cleartablelock/Makefile" ;; "tools/ddlcleanup/Makefile" ) CONFIG_FILES="$CONFIG_FILES tools/ddlcleanup/Makefile" ;; @@ -26187,8 +25209,8 @@ do "writeengine/client/Makefile" ) CONFIG_FILES="$CONFIG_FILES writeengine/client/Makefile" ;; "writeengine/splitter/Makefile" ) CONFIG_FILES="$CONFIG_FILES writeengine/splitter/Makefile" ;; "writeengine/server/Makefile" ) CONFIG_FILES="$CONFIG_FILES writeengine/server/Makefile" ;; + "writeengine/cpimport/Makefile" ) CONFIG_FILES="$CONFIG_FILES writeengine/cpimport/Makefile" ;; "writeengine/redistribute/Makefile" ) CONFIG_FILES="$CONFIG_FILES writeengine/redistribute/Makefile" ;; - "net-snmp/Makefile" ) CONFIG_FILES="$CONFIG_FILES net-snmp/Makefile" ;; "$ac_config_libobj_dir/fnmatch.h" ) CONFIG_LINKS="$CONFIG_LINKS $ac_config_libobj_dir/fnmatch.h:$ac_config_libobj_dir/fnmatch_.h" ;; "depfiles" ) CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "config.h" ) CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; @@ -26351,13 +25373,9 @@ s,@YACC@,$YACC,;t t s,@ALLOCA@,$ALLOCA,;t t s,@LIBOBJS@,$LIBOBJS,;t t s,@POW_LIB@,$POW_LIB,;t t -s,@XML2_CONFIG@,$XML2_CONFIG,;t t -s,@XML_CPPFLAGS@,$XML_CPPFLAGS,;t t -s,@XML_LIBS@,$XML_LIBS,;t t s,@idb_cppflags@,$idb_cppflags,;t t s,@idb_cxxflags@,$idb_cxxflags,;t t s,@idb_cflags@,$idb_cflags,;t t -s,@idbinstall@,$idbinstall,;t t s,@idb_ldflags@,$idb_ldflags,;t t s,@march_flags@,$march_flags,;t t s,@etcdir@,$etcdir,;t t @@ -26365,13 +25383,8 @@ s,@sharedir@,$sharedir,;t t s,@postdir@,$postdir,;t t s,@localdir@,$localdir,;t t s,@mysqldir@,$mysqldir,;t t -s,@mibdir@,$mibdir,;t t -s,@netsnmpdir@,$netsnmpdir,;t t -s,@netsnmpsysdir@,$netsnmpsysdir,;t t -s,@netsnmpmachdir@,$netsnmpmachdir,;t t -s,@netsnmplibrdir@,$netsnmplibrdir,;t t -s,@netsnmpagntdir@,$netsnmpagntdir,;t t s,@toolsdir@,$toolsdir,;t t +s,@mibdir@,$mibdir,;t t s,@netsnmp_libs@,$netsnmp_libs,;t t s,@idb_common_libs@,$idb_common_libs,;t t s,@idb_oam_libs@,$idb_oam_libs,;t t diff --git a/configure.ac b/configure.ac index e13e5cbe..371b055f 100644 --- a/configure.ac +++ b/configure.ac @@ -3,7 +3,7 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) -AC_INIT(infinidb, 4.6.1, support@infinidb.co) +AC_INIT(Calpont, 1.0.0, support@calpont.com) ### we don't want the deault CXXFLAGS set by AC_INIT, but we do want to allow the user to set them SAVE_CXXFLAGS= if test -n "$CXXFLAGS"; then @@ -91,32 +91,8 @@ AC_FUNC_STRTOD AC_FUNC_UTIME_NULL AC_CHECK_FUNCS([alarm dup2 floor ftime ftruncate gethostbyname getpagesize gettimeofday inet_ntoa isascii localtime_r memchr memmove memset mkdir pow regcomp rmdir select setenv setlocale socket strcasecmp strchr strcspn strdup strerror strrchr strspn strstr strtol strtoul strtoull utime]) -AM_PATH_XML2([2.6.26]) -if test "x$XML_CPPFLAGS" = "x"; then - AC_MSG_ERROR([Could not find a usable libxml2 development environment!]) -fi - -AC_CHECK_HEADERS([zlib.h]) -if test "x$ac_cv_header_zlib_h" != "xyes"; then - AC_MSG_ERROR([Could not find a usable zlib development environment!]) -fi - -AC_CHECK_HEADERS([readline/readline.h]) -if test "x$ac_cv_header_readline_readline_h" != "xyes"; then - AC_MSG_ERROR([Could not find a usable readline development environment!]) -fi - -AC_CHECK_HEADERS([ncurses.h]) -if test "x$ac_cv_header_ncurses_h" != "xyes"; then - AC_MSG_ERROR([Could not find a usable ncurses development environment!]) -fi - -CXX_FLAG_CHECK([-Wno-unused-local-typedefs]) -CXX_FLAG_CHECK([-Wno-unused-result]) -CXX_FLAG_CHECK([-Wno-format]) - AC_MSG_CHECKING(whether to enable debugging) -AC_SUBST([idb_cppflags], [' ']) +AC_SUBST([idb_cppflags], ['-DSKIP_SNMP -DSKIP_UDF -DSKIP_IDB_COMPRESSION -DCOMMUNITY_KEYRANGE -DSKIP_VIEW -DSKIP_INSERT_SELECT -DSKIP_AUTOI -DSKIP_OAM_INIT']) AC_ARG_WITH([debug], AS_HELP_STRING([--with-debug],[include debugging symbols/no optimization])) if test "x$with_debug" = "xyes"; then @@ -124,12 +100,11 @@ if test "x$with_debug" = "xyes"; then AC_SUBST([idb_cflags],['-ggdb3 -Wall -DSAFE_MUTEX -DINFINIDB_DEBUG']) AC_MSG_RESULT(yes) else - AC_SUBST([idb_cxxflags],["-g0 -O3 -fno-strict-aliasing -Wall $cxx_extra_flags"]) + AC_SUBST([idb_cxxflags],['-g0 -O3 -fno-strict-aliasing -Wall']) AC_SUBST([idb_cflags],['-g0 -O3 -fno-strict-aliasing -Wall']) AC_MSG_RESULT(no) fi -AC_SUBST([idbinstall], ['${prefix}']) -AC_SUBST([idb_ldflags],['-Wl,--rpath -Wl,${idbinstall}/lib -Wl,--no-as-needed -Wl,--add-needed']) +AC_SUBST([idb_ldflags],['-Wl,--rpath -Wl,/usr/local/Calpont/lib -Wl,--no-as-needed -Wl,--add-needed']) AC_MSG_CHECKING(for CPU architecture) uname=`uname -m` @@ -138,34 +113,29 @@ AS_IF( [AC_SUBST([march_flags], [' '])] [AC_MSG_RESULT(x86_64)] ) -AC_SUBST([libdir], ['${idbinstall}/lib']) -AC_SUBST([bindir], ['${idbinstall}/bin']) -AC_SUBST([includedir], ['${idbinstall}/include']) -AC_SUBST([etcdir], ['${idbinstall}/etc']) -AC_SUBST([sysconfdir], ['${idbinstall}/etc']) -AC_SUBST([mandir], ['${idbinstall}/man']) -AC_SUBST([sbindir], ['${idbinstall}/sbin']) -AC_SUBST([sharedir], ['${idbinstall}/share']) -AC_SUBST([postdir], ['${idbinstall}/post']) -AC_SUBST([localdir], ['${idbinstall}/local']) -AC_SUBST([mysqldir], ['${idbinstall}/mysql']) -AC_SUBST([mibdir], ['${idbinstall}/share/snmp/mibs']) -AC_SUBST([netsnmpdir], ['${idbinstall}/include/net-snmp']) -AC_SUBST([netsnmpsysdir], ['${idbinstall}/include/net-snmp/system']) -AC_SUBST([netsnmpmachdir], ['${idbinstall}/include/net-snmp/machine']) -AC_SUBST([netsnmplibrdir], ['${idbinstall}/include/net-snmp/library']) -AC_SUBST([netsnmpagntdir], ['${idbinstall}/include/net-snmp/agent']) -AC_SUBST([toolsdir], ['${idbinstall}/tools']) - -AC_SUBST([netsnmp_libs], ['-lnetsnmpmibs -lnetsnmpagent -lnetsnmp -lnetsnmpmibs -lnetsnmphelpers']) +AC_SUBST([libdir], ['${prefix}/Calpont/lib']) +AC_SUBST([bindir], ['${prefix}/Calpont/bin']) +AC_SUBST([includedir], ['${prefix}/Calpont/include']) +AC_SUBST([etcdir], ['${prefix}/Calpont/etc']) +AC_SUBST([sysconfdir], ['${prefix}/Calpont/etc']) +AC_SUBST([mandir], ['${prefix}/Calpont/man']) +AC_SUBST([sbindir], ['${prefix}/Calpont/sbin']) +AC_SUBST([sharedir], ['${prefix}/Calpont/share']) +AC_SUBST([postdir], ['${prefix}/Calpont/post']) +AC_SUBST([localdir], ['${prefix}/Calpont/local']) +AC_SUBST([mysqldir], ['${prefix}/Calpont/mysql']) +AC_SUBST([toolsdir], ['${prefix}/Calpont/tools']) +AC_SUBST([mibdir], ['${prefix}/Calpont/share/snmp/mibs']) + +AC_SUBST([netsnmp_libs], [' ']) AC_SUBST([idb_common_libs], ['-lmessageqcpp -lloggingcpp -lconfigcpp -lidbboot -lboost_idb -lxml2 -lpthread -lrt']) AC_SUBST([idb_oam_libs], ['-loamcpp -lsnmpmanager ${netsnmp_libs}']) -AC_SUBST([idb_brm_libs], ['-lbrm -lidbdatafile -lcacheutils -lrwlock ${idb_oam_libs} ${idb_common_libs}']) -AC_SUBST([idb_exec_libs], ['-ljoblist -lexecplan -lwindowfunction -ljoiner -lrowgroup -lfuncexp -ludfsdk -ldataconvert -lcommon -lcompress -lmysqlcl_idb -lquerystats -lquerytele -lthrift -lthreadpool ${idb_brm_libs}']) -AC_SUBST([idb_write_libs], ['-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lidbdatafile -lcacheutils ${idb_exec_libs}']) -AC_SUBST([idb_common_includes], ['-I${idbinstall}/include -I/usr/local/include -I/usr/local/include/libxml2 -I/usr/include/libxml2']) -AC_SUBST([idb_common_ldflags], ['-L${idbinstall}/lib -L/usr/local/lib']) +AC_SUBST([idb_brm_libs], ['-lbrm -lrwlock -lcacheutils ${idb_oam_libs} ${idb_common_libs}']) +AC_SUBST([idb_exec_libs], ['-ljoblist -lexecplan -ljoiner -lrowgroup -lmulticast -lfuncexp -ldataconvert -lcommon -lmysqlcl_idb -lquerystats ${idb_brm_libs}']) +AC_SUBST([idb_write_libs], ['-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lcacheutils ${idb_exec_libs}']) +AC_SUBST([idb_common_includes], ['-I${prefix}/Calpont/include -I/usr/local/include -I/usr/local/include/libxml2 -I/usr/include/libxml2']) +AC_SUBST([idb_common_ldflags], ['-L${prefix}/Calpont/lib -L/usr/local/lib']) AC_CONFIG_FILES([ Makefile @@ -182,23 +152,13 @@ AC_CONFIG_FILES([ utils/joiner/Makefile utils/rowgroup/Makefile utils/cacheutils/Makefile - utils/net-snmp/Makefile + utils/multicast/Makefile utils/funcexp/Makefile - utils/udfsdk/Makefile utils/compress/Makefile utils/ddlcleanup/Makefile utils/batchloader/Makefile utils/mysqlcl_idb/Makefile utils/querystats/Makefile - utils/jemalloc/Makefile - utils/windowfunction/Makefile - utils/idbdatafile/Makefile - utils/idbhdfs/Makefile - utils/idbhdfs/hdfs-12/Makefile - utils/idbhdfs/hdfs-20/Makefile - utils/winport/Makefile - utils/thrift/Makefile - utils/querytele/Makefile exemgr/Makefile ddlproc/Makefile dbcon/Makefile @@ -209,29 +169,21 @@ AC_CONFIG_FILES([ dbcon/execplan/Makefile dbcon/joblist/Makefile dbcon/mysql/Makefile + dbcon/sm/Makefile dmlproc/Makefile oam/Makefile oam/etc/Makefile oam/install_scripts/Makefile oam/oamcpp/Makefile oam/post/Makefile - oam/cloud/Makefile + oam/replaytxnlog/Makefile oamapps/Makefile - oamapps/calpontConsole/Makefile - oamapps/calpontDB/Makefile - oamapps/postConfigure/Makefile - oamapps/serverMonitor/Makefile - oamapps/sessionWalker/Makefile - oamapps/traphandler/Makefile - oamapps/sendtrap/Makefile - oamapps/calpontSupport/Makefile + oamapps/replayTransactionLog/Makefile primitives/Makefile primitives/blockcache/Makefile primitives/linux-port/Makefile primitives/primproc/Makefile decomsvr/Makefile - procmgr/Makefile - procmon/Makefile snmpd/Makefile snmpd/etc/Makefile snmpd/snmpmanager/Makefile @@ -243,7 +195,6 @@ AC_CONFIG_FILES([ tools/getConfig/Makefile tools/dbbuilder/Makefile tools/dbloadxml/Makefile - tools/configMgt/Makefile tools/viewtablelock/Makefile tools/cleartablelock/Makefile tools/ddlcleanup/Makefile @@ -260,7 +211,7 @@ AC_CONFIG_FILES([ writeengine/client/Makefile writeengine/splitter/Makefile writeengine/server/Makefile + writeengine/cpimport/Makefile writeengine/redistribute/Makefile - net-snmp/Makefile ]) AC_OUTPUT diff --git a/dbcon/Makefile.am b/dbcon/Makefile.am index 52cba841..4436cfd6 100644 --- a/dbcon/Makefile.am +++ b/dbcon/Makefile.am @@ -1,23 +1,23 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 861 2009-04-02 14:14:12Z rdempsey $ -SUBDIRS = ddlpackage ddlpackageproc dmlpackage dmlpackageproc execplan joblist mysql +SUBDIRS = ddlpackage ddlpackageproc dmlpackage dmlpackageproc execplan joblist sm mysql test: diff --git a/dbcon/Makefile.in b/dbcon/Makefile.in index a1144e33..462c131c 100644 --- a/dbcon/Makefile.in +++ b/dbcon/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 861 2009-04-02 14:14:12Z rdempsey $ srcdir = @srcdir@ @@ -57,9 +57,8 @@ host_triplet = @host@ subdir = dbcon DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -209,7 +199,7 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ -SUBDIRS = ddlpackage ddlpackageproc dmlpackage dmlpackageproc execplan joblist mysql +SUBDIRS = ddlpackage ddlpackageproc dmlpackage dmlpackageproc execplan joblist sm mysql all: all-recursive .SUFFIXES: diff --git a/dbcon/ddlpackage/Makefile.am b/dbcon/ddlpackage/Makefile.am index a8dc0aff..f91f705a 100644 --- a/dbcon/ddlpackage/Makefile.am +++ b/dbcon/ddlpackage/Makefile.am @@ -14,6 +14,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) diff --git a/dbcon/ddlpackage/Makefile.in b/dbcon/ddlpackage/Makefile.in index 55e3be48..0ccad2a0 100644 --- a/dbcon/ddlpackage/Makefile.in +++ b/dbcon/ddlpackage/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -41,9 +60,8 @@ subdir = dbcon/ddlpackage DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -142,9 +160,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -186,7 +201,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -200,11 +214,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -215,23 +224,6 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) diff --git a/dbcon/ddlpackage/altertable.cpp b/dbcon/ddlpackage/altertable.cpp index bf3e4442..5d727c21 100644 --- a/dbcon/ddlpackage/altertable.cpp +++ b/dbcon/ddlpackage/altertable.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: altertable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: altertable.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/columndef.cpp b/dbcon/ddlpackage/columndef.cpp index 80602ea6..c694768b 100644 --- a/dbcon/ddlpackage/columndef.cpp +++ b/dbcon/ddlpackage/columndef.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: columndef.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: columndef.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/createindex.cpp b/dbcon/ddlpackage/createindex.cpp index e1a578e8..dfae1e54 100644 --- a/dbcon/ddlpackage/createindex.cpp +++ b/dbcon/ddlpackage/createindex.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: createindex.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: createindex.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/createtable.cpp b/dbcon/ddlpackage/createtable.cpp index 1ded7fde..a44562be 100644 --- a/dbcon/ddlpackage/createtable.cpp +++ b/dbcon/ddlpackage/createtable.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: createtable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: createtable.cpp 8793 2012-08-07 20:13:39Z dhall $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/ddl-gram-win.cpp b/dbcon/ddlpackage/ddl-gram-win.cpp index 5fc8baf7..1f2b8858 100644 --- a/dbcon/ddlpackage/ddl-gram-win.cpp +++ b/dbcon/ddlpackage/ddl-gram-win.cpp @@ -180,30 +180,29 @@ char* copy_string(const char *str); TINYINT = 314, TO = 315, UNIQUE = 316, - UNSIGNED = 317, - UPDATE = 318, - USER = 319, - SESSION_USER = 320, - SYSTEM_USER = 321, - VARCHAR = 322, - VARBINARY = 323, - VARYING = 324, - WITH = 325, - ZONE = 326, - DOUBLE = 327, - IDB_FLOAT = 328, - REAL = 329, - CHARSET = 330, - IDB_IF = 331, - EXISTS = 332, - CHANGE = 333, - TRUNCATE = 334, - IDENT = 335, - FCONST = 336, - SCONST = 337, - CP_SEARCH_CONDITION_TEXT = 338, - ICONST = 339, - DATE = 340 + UPDATE = 317, + USER = 318, + SESSION_USER = 319, + SYSTEM_USER = 320, + VARCHAR = 321, + VARBINARY = 322, + VARYING = 323, + WITH = 324, + ZONE = 325, + DOUBLE = 326, + IDB_FLOAT = 327, + REAL = 328, + CHARSET = 329, + IF = 330, + EXISTS = 331, + CHANGE = 332, + TRUNCATE = 333, + IDENT = 334, + FCONST = 335, + SCONST = 336, + CP_SEARCH_CONDITION_TEXT = 337, + ICONST = 338, + DATE = 339 }; #endif @@ -471,20 +470,20 @@ union yyalloc /* YYFINAL -- State number of the termination state. */ #define YYFINAL 23 /* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 387 +#define YYLAST 380 /* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 93 +#define YYNTOKENS 92 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 76 /* YYNRULES -- Number of rules. */ -#define YYNRULES 229 +#define YYNRULES 218 /* YYNRULES -- Number of states. */ -#define YYNSTATES 396 +#define YYNSTATES 385 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 -#define YYMAXUTOK 340 +#define YYMAXUTOK 339 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) @@ -495,10 +494,10 @@ static const yytype_uint8 yytranslate[] = 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 92, - 87, 88, 2, 2, 89, 2, 91, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 86, - 2, 90, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 91, + 86, 87, 2, 2, 88, 2, 90, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 85, + 2, 89, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, @@ -525,8 +524,7 @@ static const yytype_uint8 yytranslate[] = 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, - 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - 85 + 75, 76, 77, 78, 79, 80, 81, 82, 83, 84 }; #if YYDEBUG @@ -552,128 +550,122 @@ static const yytype_uint16 yyprhs[] = 574, 577, 582, 584, 585, 588, 591, 593, 594, 596, 599, 602, 605, 607, 610, 612, 614, 619, 623, 625, 627, 632, 637, 643, 649, 654, 659, 661, 663, 666, - 670, 673, 677, 680, 684, 687, 690, 693, 696, 699, - 703, 707, 711, 715, 719, 723, 729, 730, 734, 735, - 738, 742, 745, 749, 752, 756, 760, 766, 767, 769, - 771, 773, 775, 777, 781, 785, 786, 790, 791, 795, - 800, 806, 811, 817, 819, 821, 822, 828, 834, 836 + 669, 672, 675, 678, 681, 684, 687, 691, 697, 698, + 702, 703, 706, 709, 712, 716, 722, 723, 725, 727, + 729, 731, 733, 737, 741, 742, 746, 747, 751, 756, + 762, 767, 773, 775, 777, 778, 784, 790, 792 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int16 yyrhs[] = { - 94, 0, -1, 95, -1, 95, 86, 96, -1, 96, - -1, 125, -1, 102, -1, 99, -1, 97, -1, 100, - -1, 104, -1, -1, 29, 57, 98, 134, -1, 29, - 57, 98, 134, 10, 19, -1, 76, 77, -1, -1, - 29, 34, 134, -1, 20, 34, 134, 48, 134, 87, - 111, 88, 101, -1, 20, 61, 34, 134, 48, 134, - 87, 111, 88, 101, -1, 123, -1, -1, 20, 57, - 103, 133, 87, 105, 88, 123, -1, 20, 57, 103, - 133, 87, 105, 88, -1, 76, 44, 77, -1, -1, - 79, 57, 134, -1, 79, 134, -1, 106, -1, 105, - 89, 106, -1, 139, -1, 107, -1, 18, 108, 109, - 145, -1, 108, 109, 145, -1, 137, -1, -1, 110, - -1, 113, -1, 151, -1, 112, 87, 111, 88, -1, - 136, -1, 111, 89, 136, -1, 51, 38, -1, 61, - -1, 31, 38, 87, 111, 88, 52, 133, 87, 111, - 88, 114, 116, -1, 115, -1, -1, 39, 115, -1, - 32, -1, 49, -1, 117, -1, -1, 120, 118, -1, - 121, 119, -1, 121, -1, -1, 120, -1, -1, 48, - 63, 122, -1, 48, 28, 122, -1, 10, -1, 55, + 93, 0, -1, 94, -1, 94, 85, 95, -1, 95, + -1, 124, -1, 101, -1, 98, -1, 96, -1, 99, + -1, 103, -1, -1, 29, 57, 97, 133, -1, 29, + 57, 97, 133, 10, 19, -1, 75, 76, -1, -1, + 29, 34, 133, -1, 20, 34, 133, 48, 133, 86, + 110, 87, 100, -1, 20, 61, 34, 133, 48, 133, + 86, 110, 87, 100, -1, 122, -1, -1, 20, 57, + 102, 132, 86, 104, 87, 122, -1, 20, 57, 102, + 132, 86, 104, 87, -1, 75, 44, 76, -1, -1, + 78, 57, 133, -1, 78, 133, -1, 105, -1, 104, + 88, 105, -1, 138, -1, 106, -1, 18, 107, 108, + 144, -1, 107, 108, 144, -1, 136, -1, -1, 109, + -1, 112, -1, 150, -1, 111, 86, 110, 87, -1, + 135, -1, 110, 88, 135, -1, 51, 38, -1, 61, + -1, 31, 38, 86, 110, 87, 52, 132, 86, 110, + 87, 113, 115, -1, 114, -1, -1, 39, 114, -1, + 32, -1, 49, -1, 116, -1, -1, 119, 117, -1, + 120, 118, -1, 120, -1, -1, 119, -1, -1, 48, + 62, 121, -1, 48, 28, 121, -1, 10, -1, 55, 45, -1, 55, 25, -1, 43, 3, -1, 54, -1, - 124, -1, 123, 124, -1, 30, 90, 80, -1, 40, - 90, 84, -1, 41, 90, 84, -1, 17, 90, 152, - -1, 17, 152, -1, 6, 90, 84, -1, 25, 75, - 90, 80, -1, 25, 11, 55, 90, 80, -1, 5, - 57, 133, 126, -1, 5, 57, 133, 126, 17, 152, - -1, 127, -1, 126, 89, 127, -1, 126, 127, -1, - 135, -1, 165, -1, 167, -1, 131, -1, 130, -1, - 132, -1, 128, -1, 129, -1, 42, 136, 142, -1, - 42, 15, 136, 142, -1, 78, 136, 136, 142, -1, - 78, 136, 136, 142, 138, -1, 78, 15, 136, 136, - 142, -1, 78, 15, 136, 136, 142, 138, -1, 78, - 136, 136, 142, 143, -1, 78, 15, 136, 136, 142, - 143, -1, 78, 136, 136, 142, 143, 138, -1, 78, - 15, 136, 136, 142, 143, 138, -1, 78, 136, 136, - 142, 141, -1, 78, 15, 136, 136, 142, 141, -1, - 78, 136, 136, 142, 141, 138, -1, 78, 15, 136, - 136, 142, 141, 138, -1, 78, 136, 136, 142, 143, - 141, -1, 78, 15, 136, 136, 142, 143, 141, -1, - 78, 136, 136, 142, 141, 143, -1, 78, 15, 136, - 136, 142, 141, 143, -1, 78, 136, 136, 142, 143, - 141, 138, -1, 78, 15, 136, 136, 142, 143, 141, - 138, -1, 78, 136, 136, 142, 141, 143, 138, -1, - 78, 15, 136, 136, 142, 141, 143, 138, -1, 29, - 18, 137, 166, -1, 4, 107, -1, 53, 133, -1, - 53, 60, 133, -1, 134, -1, 80, 91, 80, -1, - 80, -1, 4, 139, -1, 4, 15, 139, -1, 4, - 87, 105, 88, -1, 4, 15, 87, 105, 88, -1, - 85, -1, 80, -1, 80, -1, 17, 152, -1, 136, - 142, 140, -1, 136, 142, 140, 143, -1, 136, 142, - 140, 141, 143, -1, 136, 142, 140, 141, -1, 136, - 142, 140, 138, -1, 136, 142, 140, 143, 138, -1, - 136, 142, 140, 141, 143, 138, -1, 136, 142, 140, - 143, 141, -1, 136, 142, 140, 143, 141, 138, -1, - 136, 142, 140, 141, 138, -1, -1, 45, -1, 25, - 161, -1, 25, 45, -1, 25, 64, -1, 25, 21, - -1, 25, 65, -1, 25, 66, -1, 153, -1, 154, - -1, 155, -1, 162, -1, 9, -1, 14, -1, 144, - -1, 143, 144, -1, 150, 145, -1, 18, 137, 150, - 145, -1, 146, -1, -1, 149, 147, -1, 26, 149, - -1, 148, -1, -1, 26, -1, 35, 27, -1, 35, + 123, -1, 122, 123, -1, 30, 89, 79, -1, 40, + 89, 83, -1, 41, 89, 83, -1, 17, 89, 151, + -1, 17, 151, -1, 6, 89, 83, -1, 25, 74, + 89, 79, -1, 25, 11, 55, 89, 79, -1, 5, + 57, 132, 125, -1, 5, 57, 132, 125, 17, 151, + -1, 126, -1, 125, 88, 126, -1, 125, 126, -1, + 134, -1, 164, -1, 166, -1, 130, -1, 129, -1, + 131, -1, 127, -1, 128, -1, 42, 135, 141, -1, + 42, 15, 135, 141, -1, 77, 135, 135, 141, -1, + 77, 135, 135, 141, 137, -1, 77, 15, 135, 135, + 141, -1, 77, 15, 135, 135, 141, 137, -1, 77, + 135, 135, 141, 142, -1, 77, 15, 135, 135, 141, + 142, -1, 77, 135, 135, 141, 142, 137, -1, 77, + 15, 135, 135, 141, 142, 137, -1, 77, 135, 135, + 141, 140, -1, 77, 15, 135, 135, 141, 140, -1, + 77, 135, 135, 141, 140, 137, -1, 77, 15, 135, + 135, 141, 140, 137, -1, 77, 135, 135, 141, 142, + 140, -1, 77, 15, 135, 135, 141, 142, 140, -1, + 77, 135, 135, 141, 140, 142, -1, 77, 15, 135, + 135, 141, 140, 142, -1, 77, 135, 135, 141, 142, + 140, 137, -1, 77, 15, 135, 135, 141, 142, 140, + 137, -1, 77, 135, 135, 141, 140, 142, 137, -1, + 77, 15, 135, 135, 141, 140, 142, 137, -1, 29, + 18, 136, 165, -1, 4, 106, -1, 53, 132, -1, + 53, 60, 132, -1, 133, -1, 79, 90, 79, -1, + 79, -1, 4, 138, -1, 4, 15, 138, -1, 4, + 86, 104, 87, -1, 4, 15, 86, 104, 87, -1, + 84, -1, 79, -1, 79, -1, 17, 151, -1, 135, + 141, 139, -1, 135, 141, 139, 142, -1, 135, 141, + 139, 140, 142, -1, 135, 141, 139, 140, -1, 135, + 141, 139, 137, -1, 135, 141, 139, 142, 137, -1, + 135, 141, 139, 140, 142, 137, -1, 135, 141, 139, + 142, 140, -1, 135, 141, 139, 142, 140, 137, -1, + 135, 141, 139, 140, 137, -1, -1, 45, -1, 25, + 160, -1, 25, 45, -1, 25, 63, -1, 25, 21, + -1, 25, 64, -1, 25, 65, -1, 152, -1, 153, + -1, 154, -1, 161, -1, 9, -1, 14, -1, 143, + -1, 142, 143, -1, 149, 144, -1, 18, 136, 149, + 144, -1, 145, -1, -1, 148, 146, -1, 26, 148, + -1, 147, -1, -1, 26, -1, 35, 27, -1, 35, 33, -1, 44, 45, -1, 61, -1, 51, 38, -1, - 6, -1, 151, -1, 13, 87, 83, 88, -1, 92, - 82, 92, -1, 12, -1, 11, -1, 12, 87, 84, - 88, -1, 11, 87, 84, 88, -1, 12, 69, 87, - 84, 88, -1, 11, 69, 87, 84, 88, -1, 67, - 87, 84, 88, -1, 68, 87, 84, 88, -1, 156, - -1, 159, -1, 47, 157, -1, 47, 157, 62, -1, - 24, 157, -1, 24, 157, 62, -1, 46, 157, -1, - 46, 157, 62, -1, 37, 158, -1, 36, 158, -1, - 56, 158, -1, 59, 158, -1, 7, 158, -1, 37, - 158, 62, -1, 36, 158, 62, -1, 56, 158, 62, - -1, 59, 158, 62, -1, 7, 158, 62, -1, 87, - 84, 88, -1, 87, 84, 89, 84, 88, -1, -1, - 87, 84, 88, -1, -1, 72, 160, -1, 72, 160, - 62, -1, 74, 160, -1, 74, 160, 62, -1, 73, - 160, -1, 73, 160, 62, -1, 87, 84, 88, -1, - 87, 84, 89, 84, 88, -1, -1, 84, -1, 152, - -1, 81, -1, 22, -1, 85, -1, 58, 163, 164, - -1, 87, 84, 88, -1, -1, 70, 58, 71, -1, - -1, 29, 136, 166, -1, 29, 15, 136, 166, -1, - 29, 15, 87, 111, 88, -1, 29, 87, 111, 88, - -1, 29, 16, 87, 111, 88, -1, 10, -1, 54, - -1, -1, 5, 168, 136, 55, 141, -1, 5, 168, - 136, 29, 25, -1, 15, -1, -1 + 6, -1, 150, -1, 13, 86, 82, 87, -1, 91, + 81, 91, -1, 12, -1, 11, -1, 12, 86, 83, + 87, -1, 11, 86, 83, 87, -1, 12, 68, 86, + 83, 87, -1, 11, 68, 86, 83, 87, -1, 66, + 86, 83, 87, -1, 67, 86, 83, 87, -1, 155, + -1, 158, -1, 47, 156, -1, 24, 156, -1, 46, + 156, -1, 37, 157, -1, 36, 157, -1, 56, 157, + -1, 59, 157, -1, 7, 157, -1, 86, 83, 87, + -1, 86, 83, 88, 83, 87, -1, -1, 86, 83, + 87, -1, -1, 71, 159, -1, 73, 159, -1, 72, + 159, -1, 86, 83, 87, -1, 86, 83, 88, 83, + 87, -1, -1, 83, -1, 151, -1, 80, -1, 22, + -1, 84, -1, 58, 162, 163, -1, 86, 83, 87, + -1, -1, 69, 58, 70, -1, -1, 29, 135, 165, + -1, 29, 15, 135, 165, -1, 29, 15, 86, 110, + 87, -1, 29, 86, 110, 87, -1, 29, 16, 86, + 110, 87, -1, 10, -1, 54, -1, -1, 5, 167, + 135, 55, 140, -1, 5, 167, 135, 29, 25, -1, + 15, -1, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { - 0, 202, 202, 207, 217, 234, 235, 236, 237, 238, - 239, 240, 244, 245, 252, 253, 257, 263, 268, 276, - 277, 281, 286, 293, 294, 298, 299, 303, 309, 317, - 318, 322, 328, 336, 337, 341, 342, 343, 347, 357, - 362, 370, 371, 375, 382, 383, 387, 391, 392, 396, - 397, 401, 407, 416, 417, 421, 422, 426, 430, 434, - 435, 436, 437, 438, 442, 448, 457, 459, 461, 463, - 465, 467, 472, 474, 478, 482, 489, 501, 506, 514, - 515, 516, 517, 518, 519, 520, 521, 526, 529, 535, - 537, 539, 541, 543, 545, 547, 549, 551, 553, 555, - 557, 559, 561, 563, 565, 567, 569, 571, 573, 578, - 585, 589, 590, 594, 598, 599, 611, 612, 613, 614, - 618, 619, 623, 627, 630, 634, 638, 642, 646, 650, - 654, 658, 662, 666, 672, 675, 679, 683, 684, 685, - 686, 687, 691, 692, 693, 694, 695, 700, 709, 714, - 722, 733, 748, 749, 753, 758, 772, 773, 777, 788, - 789, 793, 794, 795, 796, 797, 801, 805, 809, 814, - 819, 824, 829, 835, 841, 849, 857, 858, 862, 868, - 874, 880, 886, 892, 898, 903, 908, 913, 918, 923, - 928, 933, 938, 943, 951, 952, 953, 957, 958, 962, - 967, 972, 977, 982, 987, 995, 997, 998, 1002, 1003, - 1004, 1008, 1014, 1020, 1029, 1030, 1034, 1035, 1039, 1040, - 1041, 1042, 1043, 1047, 1048, 1049, 1053, 1054, 1058, 1059 + 0, 217, 217, 222, 232, 249, 250, 251, 252, 253, + 254, 255, 259, 260, 267, 268, 272, 278, 283, 291, + 292, 296, 301, 308, 309, 313, 314, 318, 324, 332, + 333, 337, 343, 351, 352, 356, 357, 358, 362, 372, + 377, 385, 386, 390, 397, 398, 402, 406, 407, 411, + 412, 416, 422, 431, 432, 436, 437, 441, 445, 449, + 450, 451, 452, 453, 457, 463, 472, 474, 476, 478, + 480, 482, 487, 489, 493, 497, 504, 516, 521, 529, + 530, 531, 532, 533, 534, 535, 536, 541, 544, 550, + 552, 554, 556, 558, 560, 562, 564, 566, 568, 570, + 572, 574, 576, 578, 580, 582, 584, 586, 588, 593, + 600, 604, 605, 609, 613, 614, 626, 627, 628, 629, + 633, 634, 638, 642, 645, 649, 653, 657, 661, 665, + 669, 673, 677, 681, 687, 690, 694, 698, 699, 700, + 701, 702, 706, 707, 708, 709, 710, 715, 724, 729, + 737, 748, 763, 764, 768, 773, 787, 788, 792, 803, + 804, 808, 809, 810, 811, 812, 816, 820, 824, 829, + 834, 839, 844, 850, 856, 864, 872, 873, 877, 883, + 889, 895, 900, 905, 910, 915, 923, 924, 925, 929, + 930, 934, 939, 944, 952, 954, 955, 959, 960, 961, + 965, 971, 977, 986, 987, 991, 992, 996, 997, 998, + 999, 1000, 1004, 1005, 1006, 1010, 1011, 1015, 1016 }; #endif @@ -691,10 +683,10 @@ static const char *const yytname[] = "IDB_INT", "INTEGER", "KEY", "MATCH", "MAX_ROWS", "MIN_ROWS", "MODIFY", "NO", "NOT", "NULL_TOK", "NUMBER", "NUMERIC", "ON", "PARTIAL", "PRECISION", "PRIMARY", "REFERENCES", "RENAME", "RESTRICT", "SET", - "SMALLINT", "TABLE", "TIME", "TINYINT", "TO", "UNIQUE", "UNSIGNED", - "UPDATE", "USER", "SESSION_USER", "SYSTEM_USER", "VARCHAR", "VARBINARY", - "VARYING", "WITH", "ZONE", "DOUBLE", "IDB_FLOAT", "REAL", "CHARSET", - "IDB_IF", "EXISTS", "CHANGE", "TRUNCATE", "IDENT", "FCONST", "SCONST", + "SMALLINT", "TABLE", "TIME", "TINYINT", "TO", "UNIQUE", "UPDATE", "USER", + "SESSION_USER", "SYSTEM_USER", "VARCHAR", "VARBINARY", "VARYING", "WITH", + "ZONE", "DOUBLE", "IDB_FLOAT", "REAL", "CHARSET", "IF", "EXISTS", + "CHANGE", "TRUNCATE", "IDENT", "FCONST", "SCONST", "CP_SEARCH_CONDITION_TEXT", "ICONST", "DATE", "';'", "'('", "')'", "','", "'='", "'.'", "'\\''", "$accept", "stmtblock", "stmtmulti", "stmt", "drop_table_statement", "opt_if_exists", "drop_index_statement", @@ -737,37 +729,36 @@ static const yytype_uint16 yytoknum[] = 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, - 335, 336, 337, 338, 339, 340, 59, 40, 41, 44, - 61, 46, 39 + 335, 336, 337, 338, 339, 59, 40, 41, 44, 61, + 46, 39 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { - 0, 93, 94, 95, 95, 96, 96, 96, 96, 96, - 96, 96, 97, 97, 98, 98, 99, 100, 100, 101, - 101, 102, 102, 103, 103, 104, 104, 105, 105, 106, - 106, 107, 107, 108, 108, 109, 109, 109, 110, 111, - 111, 112, 112, 113, 114, 114, 115, 115, 115, 116, - 116, 117, 117, 118, 118, 119, 119, 120, 121, 122, - 122, 122, 122, 122, 123, 123, 124, 124, 124, 124, - 124, 124, 124, 124, 125, 125, 126, 126, 126, 127, - 127, 127, 127, 127, 127, 127, 127, 128, 128, 129, - 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, - 129, 129, 129, 129, 129, 129, 129, 129, 129, 130, - 131, 132, 132, 133, 134, 134, 135, 135, 135, 135, - 136, 136, 137, 138, 139, 139, 139, 139, 139, 139, - 139, 139, 139, 139, 140, 140, 141, 141, 141, 141, - 141, 141, 142, 142, 142, 142, 142, 142, 143, 143, - 144, 144, 145, 145, 146, 146, 147, 147, 148, 149, - 149, 150, 150, 150, 150, 150, 151, 152, 153, 153, - 153, 153, 153, 153, 153, 154, 155, 155, 156, 156, - 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, - 156, 156, 156, 156, 157, 157, 157, 158, 158, 159, - 159, 159, 159, 159, 159, 160, 160, 160, 161, 161, - 161, 162, 162, 162, 163, 163, 164, 164, 165, 165, - 165, 165, 165, 166, 166, 166, 167, 167, 168, 168 + 0, 92, 93, 94, 94, 95, 95, 95, 95, 95, + 95, 95, 96, 96, 97, 97, 98, 99, 99, 100, + 100, 101, 101, 102, 102, 103, 103, 104, 104, 105, + 105, 106, 106, 107, 107, 108, 108, 108, 109, 110, + 110, 111, 111, 112, 113, 113, 114, 114, 114, 115, + 115, 116, 116, 117, 117, 118, 118, 119, 120, 121, + 121, 121, 121, 121, 122, 122, 123, 123, 123, 123, + 123, 123, 123, 123, 124, 124, 125, 125, 125, 126, + 126, 126, 126, 126, 126, 126, 126, 127, 127, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, + 130, 131, 131, 132, 133, 133, 134, 134, 134, 134, + 135, 135, 136, 137, 138, 138, 138, 138, 138, 138, + 138, 138, 138, 138, 139, 139, 140, 140, 140, 140, + 140, 140, 141, 141, 141, 141, 141, 141, 142, 142, + 143, 143, 144, 144, 145, 145, 146, 146, 147, 148, + 148, 149, 149, 149, 149, 149, 150, 151, 152, 152, + 152, 152, 152, 152, 152, 153, 154, 154, 155, 155, + 155, 155, 155, 155, 155, 155, 156, 156, 156, 157, + 157, 158, 158, 158, 159, 159, 159, 160, 160, 160, + 161, 161, 161, 162, 162, 163, 163, 164, 164, 164, + 164, 164, 165, 165, 165, 166, 166, 167, 167 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ @@ -790,12 +781,11 @@ static const yytype_uint8 yyr2[] = 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 4, 1, 0, 2, 2, 1, 0, 1, 2, 2, 2, 1, 2, 1, 1, 4, 3, 1, 1, - 4, 4, 5, 5, 4, 4, 1, 1, 2, 3, - 2, 3, 2, 3, 2, 2, 2, 2, 2, 3, - 3, 3, 3, 3, 3, 5, 0, 3, 0, 2, - 3, 2, 3, 2, 3, 3, 5, 0, 1, 1, - 1, 1, 1, 3, 3, 0, 3, 0, 3, 4, - 5, 4, 5, 1, 1, 0, 5, 5, 1, 0 + 4, 4, 5, 5, 4, 4, 1, 1, 2, 2, + 2, 2, 2, 2, 2, 2, 3, 5, 0, 3, + 0, 2, 2, 2, 3, 5, 0, 1, 1, 1, + 1, 1, 3, 3, 0, 3, 0, 3, 4, 5, + 4, 5, 1, 1, 0, 5, 5, 1, 0 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state @@ -806,116 +796,114 @@ static const yytype_uint8 yydefact[] = 11, 0, 0, 0, 0, 0, 2, 4, 8, 7, 9, 6, 10, 5, 0, 0, 24, 0, 0, 15, 0, 115, 26, 1, 11, 0, 113, 0, 0, 0, - 0, 16, 0, 0, 25, 0, 3, 34, 229, 0, + 0, 16, 0, 0, 25, 0, 3, 34, 218, 0, 0, 0, 0, 74, 76, 85, 86, 83, 82, 84, 79, 80, 81, 0, 0, 0, 0, 14, 12, 114, 0, 34, 121, 120, 34, 110, 0, 0, 33, 116, - 228, 0, 0, 0, 0, 121, 0, 225, 0, 0, + 217, 0, 0, 0, 0, 121, 0, 214, 0, 0, 0, 111, 0, 0, 0, 0, 78, 0, 23, 34, 0, 0, 34, 117, 122, 0, 0, 27, 30, 29, - 0, 0, 0, 42, 153, 35, 0, 36, 37, 198, - 146, 169, 168, 147, 211, 196, 198, 198, 196, 196, - 198, 215, 198, 0, 0, 207, 207, 207, 212, 134, - 142, 143, 144, 176, 177, 145, 0, 0, 225, 0, - 225, 0, 39, 223, 224, 218, 0, 87, 112, 0, + 0, 0, 0, 42, 153, 35, 0, 36, 37, 190, + 146, 169, 168, 147, 200, 188, 190, 190, 188, 188, + 190, 204, 190, 0, 0, 196, 196, 196, 201, 134, + 142, 143, 144, 176, 177, 145, 0, 0, 214, 0, + 214, 0, 39, 212, 213, 207, 0, 87, 112, 0, 0, 0, 75, 77, 0, 0, 0, 13, 0, 153, 118, 34, 0, 0, 41, 0, 0, 32, 152, 157, - 0, 0, 188, 0, 0, 0, 0, 0, 180, 185, - 184, 182, 178, 186, 0, 217, 187, 0, 0, 0, - 199, 203, 201, 135, 124, 0, 0, 0, 219, 0, - 109, 221, 0, 88, 0, 89, 0, 0, 22, 0, + 0, 0, 185, 0, 0, 0, 0, 0, 179, 182, + 181, 180, 178, 183, 0, 206, 184, 0, 0, 0, + 191, 193, 192, 135, 124, 0, 0, 0, 208, 0, + 109, 210, 0, 88, 0, 89, 0, 0, 22, 0, 119, 31, 28, 0, 0, 155, 159, 160, 158, 154, - 156, 0, 0, 193, 0, 0, 0, 0, 0, 181, - 190, 189, 183, 179, 191, 0, 0, 213, 192, 0, - 0, 0, 200, 204, 202, 164, 0, 0, 0, 0, - 0, 162, 128, 127, 125, 148, 153, 165, 227, 226, - 220, 222, 40, 91, 90, 97, 93, 167, 20, 0, - 0, 0, 0, 0, 0, 21, 64, 0, 166, 0, - 38, 197, 0, 171, 0, 170, 194, 0, 214, 0, - 174, 175, 205, 0, 123, 0, 139, 137, 138, 140, - 141, 210, 208, 209, 136, 161, 163, 133, 126, 129, - 131, 149, 150, 92, 98, 94, 99, 103, 95, 101, - 17, 19, 0, 0, 70, 0, 0, 0, 0, 0, - 65, 20, 0, 173, 172, 0, 216, 0, 153, 130, - 132, 100, 104, 96, 102, 107, 105, 71, 69, 0, - 0, 66, 67, 68, 18, 0, 195, 206, 151, 108, - 106, 0, 72, 0, 73, 0, 0, 45, 47, 0, - 48, 50, 44, 46, 0, 43, 49, 54, 56, 0, - 0, 0, 51, 53, 0, 52, 55, 59, 0, 63, - 0, 58, 57, 62, 61, 60 + 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 202, 0, 0, 0, 164, 0, 0, 0, 0, 0, + 162, 128, 127, 125, 148, 153, 165, 216, 215, 209, + 211, 40, 91, 90, 97, 93, 167, 20, 0, 0, + 0, 0, 0, 0, 21, 64, 0, 166, 0, 38, + 189, 0, 171, 0, 170, 186, 0, 203, 0, 174, + 175, 194, 0, 123, 0, 139, 137, 138, 140, 141, + 199, 197, 198, 136, 161, 163, 133, 126, 129, 131, + 149, 150, 92, 98, 94, 99, 103, 95, 101, 17, + 19, 0, 0, 70, 0, 0, 0, 0, 0, 65, + 20, 0, 173, 172, 0, 205, 0, 153, 130, 132, + 100, 104, 96, 102, 107, 105, 71, 69, 0, 0, + 66, 67, 68, 18, 0, 187, 195, 151, 108, 106, + 0, 72, 0, 73, 0, 0, 45, 47, 0, 48, + 50, 44, 46, 0, 43, 49, 54, 56, 0, 0, + 0, 51, 53, 0, 52, 55, 59, 0, 63, 0, + 58, 57, 62, 61, 60 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { - -1, 5, 6, 7, 8, 33, 9, 10, 320, 11, + -1, 5, 6, 7, 8, 33, 9, 10, 309, 11, 29, 12, 96, 97, 98, 66, 104, 105, 141, 106, - 107, 371, 372, 375, 376, 382, 385, 377, 378, 391, - 321, 276, 13, 43, 44, 45, 46, 47, 48, 49, - 25, 26, 50, 142, 68, 252, 99, 194, 253, 129, - 254, 255, 167, 168, 219, 220, 169, 256, 257, 152, - 130, 131, 132, 133, 178, 172, 134, 190, 304, 135, - 185, 237, 51, 145, 52, 71 + 107, 360, 361, 364, 365, 371, 374, 366, 367, 380, + 310, 265, 13, 43, 44, 45, 46, 47, 48, 49, + 25, 26, 50, 142, 68, 241, 99, 194, 242, 129, + 243, 244, 167, 168, 219, 220, 169, 245, 246, 152, + 130, 131, 132, 133, 178, 172, 134, 190, 293, 135, + 185, 230, 51, 145, 52, 71 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ -#define YYPACT_NINF -270 +#define YYPACT_NINF -254 static const yytype_int16 yypact[] = { - 34, -44, 107, 30, 53, 40, -21, -270, -270, -270, - -270, -270, -270, -270, 9, 9, 20, 74, 9, 42, - 9, 58, -270, -270, 34, 3, -270, 117, 127, 9, - 9, -270, 97, 9, -270, 104, -270, 35, 172, 82, - 21, 43, 27, 100, -270, -270, -270, -270, -270, -270, - -270, -270, -270, 9, 114, 109, 174, -270, 210, -270, - 168, 145, 115, -270, 29, -270, 124, 136, -270, -270, - -270, -56, 178, 141, 145, -270, -56, 23, -56, 136, - 9, -270, -56, -56, 162, 3, -270, 150, -270, 29, - 9, 237, 29, -270, -270, 124, 123, -270, -270, -270, - 173, 226, 228, -270, 76, -270, 207, -270, -270, 208, - -270, -59, 83, -270, -270, 211, 208, 208, 211, 211, - 208, 212, 208, 213, 214, 215, 215, 215, -270, 244, - -270, -270, -270, -270, -270, -270, 38, -56, 23, -56, - 23, 154, -270, -270, -270, -270, 136, -270, -270, -56, - 136, 221, -270, -270, -56, 179, 217, -270, 181, 76, - -270, 29, 222, 219, -270, 261, 130, -270, -270, 271, - -56, 223, 246, 224, 225, 227, 229, 231, 248, 250, - 254, 255, 256, 257, 236, 251, 260, 239, 240, 241, - 265, 266, 267, -270, 180, 305, 306, 183, -270, 185, - -270, -270, -56, -270, 136, 180, 242, 187, 209, -56, - -270, -270, -270, 245, -56, -270, -270, -270, -270, -270, - -270, 189, 247, -270, 252, 249, 258, 253, 193, -270, - -270, -270, -270, -270, -270, 259, 274, -270, -270, 262, - 263, 195, -270, -270, -270, -270, 162, 145, 135, 293, - 301, -270, -270, 200, 180, -270, 76, -270, -270, -270, - -270, -270, -270, 180, -270, 200, 180, -270, 209, 264, - 98, 0, 268, 269, 270, 209, -270, 197, -270, 199, - -270, -270, 273, -270, 275, -270, -270, 272, -270, 277, - -270, -270, -270, 278, -270, 201, -270, -270, -270, -270, - -270, -270, -270, -270, -270, -270, -270, -270, 200, -270, - 323, -270, -270, -270, 200, 180, -270, 200, -270, 323, - -270, 209, 280, 162, -270, 288, 276, 285, 283, 284, - -270, 209, 292, -270, -270, 281, -270, 282, 76, -270, - -270, -270, 200, -270, 323, -270, -270, -270, -270, 286, - 291, -270, -270, -270, -270, 9, -270, -270, -270, -270, - -270, 294, -270, 290, -270, -56, 202, 191, -270, 191, - -270, 297, -270, -270, -1, -270, -270, 298, 304, 192, - 192, 321, -270, -270, 309, -270, -270, -270, 350, -270, - 99, -270, -270, -270, -270, -270 + 69, 36, 164, -20, -37, 123, 51, -254, -254, -254, + -254, -254, -254, -254, 71, 71, 85, 119, 71, 88, + 71, 82, -254, -254, 69, 101, -254, 127, 149, 71, + 71, -254, 128, 71, -254, 152, -254, 6, 223, 130, + 18, 8, 25, 78, -254, -254, -254, -254, -254, -254, + -254, -254, -254, 71, 172, 173, 218, -254, 240, -254, + 143, 196, 146, -254, -8, -254, 179, 115, -254, -254, + -254, 112, 158, 201, 196, -254, 112, 16, 112, 115, + 71, -254, 112, 112, 197, 101, -254, 203, -254, -8, + 71, 263, -8, -254, -254, 179, 102, -254, -254, -254, + 204, 253, 254, -254, 114, -254, 207, -254, -254, 208, + -254, 70, 90, -254, -254, 209, 208, 208, 209, 209, + 208, 210, 208, 212, 213, 214, 214, 214, -254, 252, + -254, -254, -254, -254, -254, -254, 0, 112, 16, 112, + 16, 136, -254, -254, -254, -254, 115, -254, -254, 112, + 115, 220, -254, -254, 112, 147, 216, -254, 169, 114, + -254, -8, 221, 219, -254, 269, 3, -254, -254, 280, + 112, 224, -254, 222, 226, 225, 227, 229, -254, -254, + -254, -254, -254, -254, 230, 245, -254, 233, 234, 235, + -254, -254, -254, -254, 188, 294, 295, 174, -254, 177, + -254, -254, 112, -254, 115, 188, 231, 180, 211, 112, + -254, -254, -254, 236, 112, -254, -254, -254, -254, -254, + -254, 182, 237, 238, 239, 242, 241, 184, 243, 271, + -254, 244, 246, 186, -254, 197, 196, 120, 282, 296, + -254, -254, 202, 188, -254, 114, -254, -254, -254, -254, + -254, -254, 188, -254, 202, 188, -254, 211, 247, 10, + 17, 248, 249, 250, 211, -254, 189, -254, 191, -254, + -254, 255, -254, 256, -254, -254, 257, -254, 262, -254, + -254, -254, 258, -254, 151, -254, -254, -254, -254, -254, + -254, -254, -254, -254, -254, -254, -254, 202, -254, 318, + -254, -254, -254, 202, 188, -254, 202, -254, 318, -254, + 211, 261, 197, -254, 290, 259, 267, 264, 266, -254, + 211, 298, -254, -254, 265, -254, 268, 114, -254, -254, + -254, 202, -254, 318, -254, -254, -254, -254, 270, 272, + -254, -254, -254, -254, 71, -254, -254, -254, -254, -254, + 274, -254, 275, -254, 112, 193, 194, -254, 194, -254, + 306, -254, -254, 72, -254, -254, 308, 309, 125, 125, + 330, -254, -254, 300, -254, -254, -254, 357, -254, 87, + -254, -254, -254, -254, -254 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { - -270, -270, -270, 331, -270, -270, -270, -270, 26, -270, - -270, -270, 62, 218, 336, 314, 287, -270, -136, -270, - -270, -270, 11, -270, -270, -270, -270, 6, 1, 7, - 175, -269, -270, -270, -28, -270, -270, -270, -270, -270, - -29, 5, -270, -23, -70, -183, 79, -270, -175, -74, - -179, -223, -157, -270, -270, -270, 216, 90, -5, -202, - -270, -270, -270, -270, 161, 116, -270, 166, -270, -270, - -270, -270, -270, 119, -270, -270 + -254, -254, -254, 339, -254, -254, -254, -254, 44, -254, + -254, -254, -45, 205, 328, 307, 276, -254, -136, -254, + -254, -254, 9, -254, -254, -254, -254, 2, 4, 5, + 167, -253, -254, -254, -18, -254, -254, -254, -254, -254, + -29, 28, -254, -33, -69, -189, 43, -254, -183, -71, + -190, -220, -157, -254, -254, -254, 215, 89, 30, -218, + -254, -254, -254, -254, 165, 138, -254, 159, -254, -254, + -254, -254, -254, 107, -254, -254 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If @@ -925,134 +913,133 @@ static const yytype_int16 yypgoto[] = #define YYTABLE_NINF -123 static const yytype_int16 yytable[] = { - 55, 197, 211, 199, 140, 147, 330, 37, 38, 22, - 173, 325, 81, 14, 67, 86, 77, 79, 207, 83, - 27, 259, 264, 31, 75, 34, 266, 379, 174, 63, - 265, 311, 39, 143, 221, 56, 78, 67, 58, 1, - 23, 67, 82, 311, 294, 40, 303, 61, 136, 138, - 60, 148, 330, 61, 2, 146, 41, 153, 87, 149, - 150, 108, 380, 3, 18, 24, 67, 195, 324, 67, - 307, 309, 203, 277, 308, 326, 205, 144, 279, 310, - 313, 42, 316, 318, 315, 311, 317, 19, 314, 21, - 108, 319, 311, 196, 311, 156, 28, 72, 73, 312, - 74, 75, 165, 80, 37, 38, 63, 75, 30, 62, - 20, 166, 63, 4, 63, 62, 69, 84, 32, 311, - 63, 348, 64, 21, 394, 339, 204, 340, -122, 39, - 263, 341, 343, 21, 345, 342, 346, 100, 67, 93, - 344, 15, 40, 109, 395, 110, -122, 111, 112, 35, - 113, 155, 175, 41, 158, 101, 296, 216, 114, 359, - 115, 360, 75, 217, 16, 53, -122, 63, 17, 76, - 176, 54, 116, 117, 57, 102, -122, 295, 42, 262, - 297, 358, 118, 119, 59, 103, 245, 70, 323, 85, - 151, 88, 120, 100, 121, 122, 89, 246, 247, 298, - 299, 300, 387, 123, 124, 248, 245, 245, 125, 126, - 127, 160, 161, 100, 100, 269, 301, 246, 247, 302, - 91, 128, 90, 368, 249, 94, 270, 151, 139, 366, - 369, 250, 179, 180, 271, 388, 183, 154, 186, 272, - 370, 251, 201, 202, 249, 249, 389, 390, 75, 273, - 274, 250, 250, 63, 151, 92, 157, 198, 75, 200, - 162, 251, 251, 63, 163, 137, 164, 208, 161, 210, - 161, 260, 202, 261, 202, 268, 202, 280, 202, 181, - 182, 286, 287, 292, 293, 331, 202, 332, 202, 193, - 367, 202, 191, 192, 170, 171, 166, 218, 177, 184, - 187, 188, 189, 206, 209, 213, 214, 222, 223, 225, - 229, 224, 230, 227, 226, 228, 231, 232, 233, 234, - 235, 236, 238, 239, 240, 241, 363, 242, 243, 244, - 258, 248, 289, 278, 267, 281, 282, 283, 305, 306, - 246, 285, 284, 349, 355, 374, 381, 288, 336, 379, - 290, 291, 384, 393, 322, 36, 335, 354, 327, 328, - 329, 333, 337, 334, 347, 351, 350, 352, 353, 356, - 357, 362, 380, 65, 364, 95, 361, 365, 383, 212, - 373, 215, 159, 275, 386, 338, 0, 392 + 55, 197, 211, 199, 67, 140, 77, 79, 147, 83, + 61, 319, 81, 248, 18, 255, 253, 283, 207, 292, + 20, 60, 254, 300, 61, 86, 143, 67, 314, 195, + 216, 67, 22, 78, 221, 300, 217, 19, 136, 138, + 82, 313, 21, 27, 155, 146, 31, 158, 34, 149, + 150, 148, 297, 296, 298, 196, 67, 319, 56, 67, + 299, 58, 304, 302, 306, 305, 307, 153, 80, 303, + 144, 62, 308, 266, 1, 203, 63, 300, 268, 205, + 69, 87, 37, 38, 300, 62, 300, 21, 301, 2, + 63, 315, 64, 14, 337, 84, 108, 75, 3, 312, + 368, 151, 63, 93, 75, 37, 38, 39, 328, 63, + 329, 300, 383, 331, 330, 332, 204, 334, 156, 335, + 40, 333, 109, 23, 110, 108, 111, 112, 67, 113, + 39, 41, 384, 252, 369, 376, 24, 114, 173, 115, + 165, 285, 348, 40, 349, 72, 73, 4, 74, 166, + 21, 116, 117, 30, 41, 42, 174, 234, 175, -122, + 28, 118, 119, 32, 100, 286, 85, 284, 377, 251, + 347, 120, 35, 121, 122, 53, 176, -122, 42, 378, + 379, 123, 124, 287, 288, 289, 125, 126, 127, 160, + 161, 75, 100, 54, 234, 238, 63, -122, 15, 128, + 290, 100, 239, 291, 57, 235, 236, -122, 234, 75, + 101, 151, 240, 237, 63, 100, 76, 258, 355, 235, + 236, 16, 75, 201, 202, 17, 357, 63, 259, 92, + 102, 59, 238, 358, 208, 161, 260, 75, 70, 239, + 103, 261, 63, 359, 137, 198, 238, 200, 88, 240, + 91, 262, 263, 239, 179, 180, 210, 161, 183, 89, + 186, 249, 202, 240, 250, 202, 90, 257, 202, 269, + 202, 275, 276, 281, 282, 94, 320, 202, 321, 202, + 356, 202, 157, 181, 182, 191, 192, 139, 151, 154, + 162, 163, 164, 170, 171, 177, 184, 193, 187, 188, + 189, 206, 209, 213, 166, 214, 218, 222, 223, 224, + 226, 225, 227, 228, 229, 352, 231, 232, 233, 247, + 237, 271, 256, 267, 270, 273, 272, 294, 274, 278, + 277, 279, 325, 280, 295, 235, 311, 316, 317, 318, + 324, 326, 322, 323, 336, 338, 340, 341, 339, 342, + 344, 351, 345, 353, 363, 346, 370, 373, 368, 350, + 382, 354, 369, 36, 343, 65, 212, 362, 95, 375, + 372, 159, 0, 327, 381, 264, 0, 0, 0, 0, + 215 }; static const yytype_int16 yycheck[] = { - 29, 137, 159, 139, 74, 79, 275, 4, 5, 4, - 69, 11, 41, 57, 37, 43, 39, 40, 154, 42, - 15, 196, 205, 18, 80, 20, 205, 28, 87, 85, - 205, 254, 29, 10, 170, 30, 15, 60, 33, 5, - 0, 64, 15, 266, 246, 42, 248, 18, 71, 72, - 15, 80, 321, 18, 20, 78, 53, 85, 53, 82, - 83, 66, 63, 29, 34, 86, 89, 29, 270, 92, - 253, 254, 146, 209, 253, 75, 150, 54, 214, 254, - 263, 78, 265, 266, 263, 308, 265, 57, 263, 80, - 95, 266, 315, 55, 317, 90, 76, 15, 16, 256, - 18, 80, 26, 60, 4, 5, 85, 80, 34, 80, - 57, 35, 85, 79, 85, 80, 37, 17, 76, 342, - 85, 323, 87, 80, 25, 308, 149, 310, 13, 29, - 204, 314, 315, 80, 317, 314, 319, 13, 161, 60, - 315, 34, 42, 7, 45, 9, 31, 11, 12, 91, - 14, 89, 69, 53, 92, 31, 21, 27, 22, 342, - 24, 344, 80, 33, 57, 48, 51, 85, 61, 87, - 87, 44, 36, 37, 77, 51, 61, 247, 78, 202, - 45, 338, 46, 47, 80, 61, 6, 15, 90, 89, - 92, 77, 56, 13, 58, 59, 87, 17, 18, 64, - 65, 66, 10, 67, 68, 25, 6, 6, 72, 73, - 74, 88, 89, 13, 13, 6, 81, 17, 18, 84, - 10, 85, 48, 32, 44, 80, 17, 92, 87, 365, - 39, 51, 116, 117, 25, 43, 120, 87, 122, 30, - 49, 61, 88, 89, 44, 44, 54, 55, 80, 40, - 41, 51, 51, 85, 92, 87, 19, 138, 80, 140, - 87, 61, 61, 85, 38, 87, 38, 88, 89, 88, - 89, 88, 89, 88, 89, 88, 89, 88, 89, 118, - 119, 88, 89, 88, 89, 88, 89, 88, 89, 45, - 88, 89, 126, 127, 87, 87, 35, 26, 87, 87, - 87, 87, 87, 82, 87, 83, 87, 84, 62, 84, - 62, 87, 62, 84, 87, 84, 62, 62, 62, 62, - 84, 70, 62, 84, 84, 84, 355, 62, 62, 62, - 25, 25, 58, 88, 92, 88, 84, 88, 45, 38, - 17, 88, 84, 55, 52, 48, 48, 88, 71, 28, - 88, 88, 48, 3, 90, 24, 84, 331, 90, 90, - 90, 88, 84, 88, 84, 80, 90, 84, 84, 88, - 88, 80, 63, 37, 80, 61, 90, 87, 377, 161, - 369, 165, 95, 208, 378, 295, -1, 380 + 29, 137, 159, 139, 37, 74, 39, 40, 79, 42, + 18, 264, 41, 196, 34, 205, 205, 235, 154, 237, + 57, 15, 205, 243, 18, 43, 10, 60, 11, 29, + 27, 64, 4, 15, 170, 255, 33, 57, 71, 72, + 15, 259, 79, 15, 89, 78, 18, 92, 20, 82, + 83, 80, 242, 242, 243, 55, 89, 310, 30, 92, + 243, 33, 252, 252, 254, 254, 255, 85, 60, 252, + 54, 79, 255, 209, 5, 146, 84, 297, 214, 150, + 37, 53, 4, 5, 304, 79, 306, 79, 245, 20, + 84, 74, 86, 57, 312, 17, 66, 79, 29, 89, + 28, 91, 84, 60, 79, 4, 5, 29, 297, 84, + 299, 331, 25, 303, 303, 304, 149, 306, 90, 308, + 42, 304, 7, 0, 9, 95, 11, 12, 161, 14, + 29, 53, 45, 204, 62, 10, 85, 22, 68, 24, + 26, 21, 331, 42, 333, 15, 16, 78, 18, 35, + 79, 36, 37, 34, 53, 77, 86, 6, 68, 13, + 75, 46, 47, 75, 13, 45, 88, 236, 43, 202, + 327, 56, 90, 58, 59, 48, 86, 31, 77, 54, + 55, 66, 67, 63, 64, 65, 71, 72, 73, 87, + 88, 79, 13, 44, 6, 44, 84, 51, 34, 84, + 80, 13, 51, 83, 76, 17, 18, 61, 6, 79, + 31, 91, 61, 25, 84, 13, 86, 6, 354, 17, + 18, 57, 79, 87, 88, 61, 32, 84, 17, 86, + 51, 79, 44, 39, 87, 88, 25, 79, 15, 51, + 61, 30, 84, 49, 86, 138, 44, 140, 76, 61, + 10, 40, 41, 51, 116, 117, 87, 88, 120, 86, + 122, 87, 88, 61, 87, 88, 48, 87, 88, 87, + 88, 87, 88, 87, 88, 79, 87, 88, 87, 88, + 87, 88, 19, 118, 119, 126, 127, 86, 91, 86, + 86, 38, 38, 86, 86, 86, 86, 45, 86, 86, + 86, 81, 86, 82, 35, 86, 26, 83, 86, 83, + 83, 86, 83, 83, 69, 344, 83, 83, 83, 25, + 25, 83, 91, 87, 87, 83, 87, 45, 87, 58, + 87, 87, 70, 87, 38, 17, 89, 89, 89, 89, + 83, 83, 87, 87, 83, 55, 79, 83, 89, 83, + 52, 79, 87, 79, 48, 87, 48, 48, 28, 89, + 3, 86, 62, 24, 320, 37, 161, 358, 61, 367, + 366, 95, -1, 284, 369, 208, -1, -1, -1, -1, + 165 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { - 0, 5, 20, 29, 79, 94, 95, 96, 97, 99, - 100, 102, 104, 125, 57, 34, 57, 61, 34, 57, - 57, 80, 134, 0, 86, 133, 134, 134, 76, 103, - 34, 134, 76, 98, 134, 91, 96, 4, 5, 29, - 42, 53, 78, 126, 127, 128, 129, 130, 131, 132, - 135, 165, 167, 48, 44, 133, 134, 77, 134, 80, - 15, 18, 80, 85, 87, 107, 108, 136, 137, 139, - 15, 168, 15, 16, 18, 80, 87, 136, 15, 136, - 60, 133, 15, 136, 17, 89, 127, 134, 77, 87, - 48, 10, 87, 139, 80, 108, 105, 106, 107, 139, - 13, 31, 51, 61, 109, 110, 112, 113, 151, 7, + 0, 5, 20, 29, 78, 93, 94, 95, 96, 98, + 99, 101, 103, 124, 57, 34, 57, 61, 34, 57, + 57, 79, 133, 0, 85, 132, 133, 133, 75, 102, + 34, 133, 75, 97, 133, 90, 95, 4, 5, 29, + 42, 53, 77, 125, 126, 127, 128, 129, 130, 131, + 134, 164, 166, 48, 44, 132, 133, 76, 133, 79, + 15, 18, 79, 84, 86, 106, 107, 135, 136, 138, + 15, 167, 15, 16, 18, 79, 86, 135, 15, 135, + 60, 132, 15, 135, 17, 88, 126, 133, 76, 86, + 48, 10, 86, 138, 79, 107, 104, 105, 106, 138, + 13, 31, 51, 61, 108, 109, 111, 112, 150, 7, 9, 11, 12, 14, 22, 24, 36, 37, 46, 47, - 56, 58, 59, 67, 68, 72, 73, 74, 85, 142, - 153, 154, 155, 156, 159, 162, 136, 87, 136, 87, - 137, 111, 136, 10, 54, 166, 136, 142, 133, 136, - 136, 92, 152, 127, 87, 105, 134, 19, 105, 109, - 88, 89, 87, 38, 38, 26, 35, 145, 146, 149, - 87, 87, 158, 69, 87, 69, 87, 87, 157, 158, - 158, 157, 157, 158, 87, 163, 158, 87, 87, 87, - 160, 160, 160, 45, 140, 29, 55, 111, 166, 111, - 166, 88, 89, 142, 136, 142, 82, 111, 88, 87, - 88, 145, 106, 83, 87, 149, 27, 33, 26, 147, - 148, 111, 84, 62, 87, 84, 87, 84, 84, 62, - 62, 62, 62, 62, 62, 84, 70, 164, 62, 84, - 84, 84, 62, 62, 62, 6, 17, 18, 25, 44, - 51, 61, 138, 141, 143, 144, 150, 151, 25, 141, - 88, 88, 136, 142, 138, 141, 143, 92, 88, 6, - 17, 25, 30, 40, 41, 123, 124, 111, 88, 111, - 88, 88, 84, 88, 84, 88, 88, 89, 88, 58, - 88, 88, 88, 89, 152, 137, 21, 45, 64, 65, - 66, 81, 84, 152, 161, 45, 38, 138, 143, 138, - 141, 144, 145, 138, 141, 143, 138, 143, 138, 141, - 101, 123, 90, 90, 152, 11, 75, 90, 90, 90, - 124, 88, 88, 88, 88, 84, 71, 84, 150, 138, - 138, 138, 143, 138, 141, 138, 138, 84, 152, 55, - 90, 80, 84, 84, 101, 52, 88, 88, 145, 138, - 138, 90, 80, 133, 80, 87, 111, 88, 32, 39, - 49, 114, 115, 115, 48, 116, 117, 120, 121, 28, - 63, 48, 118, 121, 48, 119, 120, 10, 43, 54, - 55, 122, 122, 3, 25, 45 + 56, 58, 59, 66, 67, 71, 72, 73, 84, 141, + 152, 153, 154, 155, 158, 161, 135, 86, 135, 86, + 136, 110, 135, 10, 54, 165, 135, 141, 132, 135, + 135, 91, 151, 126, 86, 104, 133, 19, 104, 108, + 87, 88, 86, 38, 38, 26, 35, 144, 145, 148, + 86, 86, 157, 68, 86, 68, 86, 86, 156, 157, + 157, 156, 156, 157, 86, 162, 157, 86, 86, 86, + 159, 159, 159, 45, 139, 29, 55, 110, 165, 110, + 165, 87, 88, 141, 135, 141, 81, 110, 87, 86, + 87, 144, 105, 82, 86, 148, 27, 33, 26, 146, + 147, 110, 83, 86, 83, 86, 83, 83, 83, 69, + 163, 83, 83, 83, 6, 17, 18, 25, 44, 51, + 61, 137, 140, 142, 143, 149, 150, 25, 140, 87, + 87, 135, 141, 137, 140, 142, 91, 87, 6, 17, + 25, 30, 40, 41, 122, 123, 110, 87, 110, 87, + 87, 83, 87, 83, 87, 87, 88, 87, 58, 87, + 87, 87, 88, 151, 136, 21, 45, 63, 64, 65, + 80, 83, 151, 160, 45, 38, 137, 142, 137, 140, + 143, 144, 137, 140, 142, 137, 142, 137, 140, 100, + 122, 89, 89, 151, 11, 74, 89, 89, 89, 123, + 87, 87, 87, 87, 83, 70, 83, 149, 137, 137, + 137, 142, 137, 140, 137, 137, 83, 151, 55, 89, + 79, 83, 83, 100, 52, 87, 87, 144, 137, 137, + 89, 79, 132, 79, 86, 110, 87, 32, 39, 49, + 113, 114, 114, 48, 115, 116, 119, 120, 28, 62, + 48, 117, 120, 48, 118, 119, 10, 43, 54, 55, + 121, 121, 3, 25, 45 }; #define yyerrok (yyerrstatus = 0) @@ -2757,15 +2744,6 @@ yyparse () case 179: - { - (yyvsp[(2) - (3)].columnType)->fType = DDL_UNSIGNED_NUMERIC; - (yyvsp[(2) - (3)].columnType)->fLength = DDLDatatypeLength[DDL_UNSIGNED_NUMERIC]; - (yyval.columnType) = (yyvsp[(2) - (3)].columnType); - ;} - break; - - case 180: - { (yyvsp[(2) - (2)].columnType)->fType = DDL_DECIMAL; /* $2->fLength = DDLDatatypeLength[DDL_DECIMAL]; */ @@ -2773,16 +2751,7 @@ yyparse () ;} break; - case 181: - - { - (yyvsp[(2) - (3)].columnType)->fType = DDL_UNSIGNED_DECIMAL; -/* $3->fLength = DDLDatatypeLength[DDL_DECIMAL]; */ - (yyval.columnType) = (yyvsp[(2) - (3)].columnType); - ;} - break; - - case 182: + case 180: { (yyvsp[(2) - (2)].columnType)->fType = DDL_DECIMAL; @@ -2791,32 +2760,23 @@ yyparse () ;} break; - case 183: - - { - (yyvsp[(2) - (3)].columnType)->fType = DDL_UNSIGNED_DECIMAL; - (yyvsp[(2) - (3)].columnType)->fLength = DDLDatatypeLength[DDL_UNSIGNED_DECIMAL]; - (yyval.columnType) = (yyvsp[(2) - (3)].columnType); - ;} - break; - - case 184: + case 181: { - (yyval.columnType) = new ColumnType(DDL_INT); + (yyval.columnType) = new ColumnType(DDL_INTEGER); (yyval.columnType)->fLength = DDLDatatypeLength[DDL_INT]; ;} break; - case 185: + case 182: { - (yyval.columnType) = new ColumnType(DDL_INT); + (yyval.columnType) = new ColumnType(DDL_INTEGER); (yyval.columnType)->fLength = DDLDatatypeLength[DDL_INT]; ;} break; - case 186: + case 183: { (yyval.columnType) = new ColumnType(DDL_SMALLINT); @@ -2824,7 +2784,7 @@ yyparse () ;} break; - case 187: + case 184: { (yyval.columnType) = new ColumnType(DDL_TINYINT); @@ -2832,7 +2792,7 @@ yyparse () ;} break; - case 188: + case 185: { (yyval.columnType) = new ColumnType(DDL_BIGINT); @@ -2840,72 +2800,32 @@ yyparse () ;} break; - case 189: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_INT); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_INT]; - ;} - break; - - case 190: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_INT); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_INT]; - ;} - break; - - case 191: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_SMALLINT); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_SMALLINT]; - ;} - break; - - case 192: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_TINYINT); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_TINYINT]; - ;} - break; - - case 193: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_BIGINT); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_BIGINT]; - ;} - break; - - case 194: + case 186: {(yyval.columnType) = new ColumnType(atoi((yyvsp[(2) - (3)].str)), 0);;} break; - case 195: + case 187: {(yyval.columnType) = new ColumnType(atoi((yyvsp[(2) - (5)].str)), atoi((yyvsp[(4) - (5)].str)));;} break; - case 196: + case 188: {(yyval.columnType) = new ColumnType(10,0);;} break; - case 197: + case 189: {(yyval.str) = NULL;;} break; - case 198: + case 190: {(yyval.str) = NULL;;} break; - case 199: + case 191: { (yyval.columnType) = new ColumnType(DDL_DOUBLE); @@ -2913,15 +2833,7 @@ yyparse () ;} break; - case 200: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_DOUBLE); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_DOUBLE]; - ;} - break; - - case 201: + case 192: { (yyval.columnType) = new ColumnType(DDL_DOUBLE); @@ -2929,15 +2841,7 @@ yyparse () ;} break; - case 202: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_DOUBLE); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_DOUBLE]; - ;} - break; - - case 203: + case 193: { (yyval.columnType) = new ColumnType(DDL_FLOAT); @@ -2945,30 +2849,22 @@ yyparse () ;} break; - case 204: - - { - (yyval.columnType) = new ColumnType(DDL_UNSIGNED_FLOAT); - (yyval.columnType)->fLength = DDLDatatypeLength[DDL_FLOAT]; - ;} - break; - - case 205: + case 194: {(yyval.str) = NULL;;} break; - case 206: + case 195: {(yyval.str) = NULL;;} break; - case 207: + case 196: {(yyval.str) = NULL;;} break; - case 211: + case 200: { (yyval.columnType) = new ColumnType(DDL_DATETIME); @@ -2976,7 +2872,7 @@ yyparse () ;} break; - case 212: + case 201: { (yyval.columnType) = new ColumnType(DDL_DATE); @@ -2984,7 +2880,7 @@ yyparse () ;} break; - case 213: + case 202: { (yyval.columnType) = new ColumnType(DDL_DATETIME); @@ -2994,72 +2890,72 @@ yyparse () ;} break; - case 214: + case 203: {(yyval.ival) = atoi((yyvsp[(2) - (3)].str));;} break; - case 215: + case 204: {(yyval.ival) = -1;;} break; - case 216: + case 205: {(yyval.flag) = true;;} break; - case 217: + case 206: {(yyval.flag) = false;;} break; - case 218: + case 207: {(yyval.ata) = new AtaDropColumn((yyvsp[(2) - (3)].str), (yyvsp[(3) - (3)].refActionCode));;} break; - case 219: + case 208: {(yyval.ata) = new AtaDropColumn((yyvsp[(3) - (4)].str), (yyvsp[(4) - (4)].refActionCode));;} break; - case 220: + case 209: {(yyval.ata) = new AtaDropColumns((yyvsp[(4) - (5)].columnNameList));;} break; - case 221: + case 210: {(yyval.ata) = new AtaDropColumns((yyvsp[(3) - (4)].columnNameList));;} break; - case 222: + case 211: {(yyval.ata) = new AtaDropColumns((yyvsp[(4) - (5)].columnNameList));;} break; - case 223: + case 212: {(yyval.refActionCode) = DDL_CASCADE;;} break; - case 224: + case 213: {(yyval.refActionCode) = DDL_RESTRICT;;} break; - case 225: + case 214: {(yyval.refActionCode) = DDL_NO_ACTION;;} break; - case 226: + case 215: {(yyval.ata) = new AtaSetColumnDefault((yyvsp[(3) - (5)].str), (yyvsp[(5) - (5)].colDefault));;} break; - case 227: + case 216: {(yyval.ata) = new AtaDropColumnDefault((yyvsp[(3) - (5)].str));;} break; diff --git a/dbcon/ddlpackage/ddl-gram-win.h b/dbcon/ddlpackage/ddl-gram-win.h index 31ab6aa1..dccf99db 100644 --- a/dbcon/ddlpackage/ddl-gram-win.h +++ b/dbcon/ddlpackage/ddl-gram-win.h @@ -98,30 +98,29 @@ TINYINT = 314, TO = 315, UNIQUE = 316, - UNSIGNED = 317, - UPDATE = 318, - USER = 319, - SESSION_USER = 320, - SYSTEM_USER = 321, - VARCHAR = 322, - VARBINARY = 323, - VARYING = 324, - WITH = 325, - ZONE = 326, - DOUBLE = 327, - IDB_FLOAT = 328, - REAL = 329, - CHARSET = 330, - IDB_IF = 331, - EXISTS = 332, - CHANGE = 333, - TRUNCATE = 334, - IDENT = 335, - FCONST = 336, - SCONST = 337, - CP_SEARCH_CONDITION_TEXT = 338, - ICONST = 339, - DATE = 340 + UPDATE = 317, + USER = 318, + SESSION_USER = 319, + SYSTEM_USER = 320, + VARCHAR = 321, + VARBINARY = 322, + VARYING = 323, + WITH = 324, + ZONE = 325, + DOUBLE = 326, + IDB_FLOAT = 327, + REAL = 328, + CHARSET = 329, + IF = 330, + EXISTS = 331, + CHANGE = 332, + TRUNCATE = 333, + IDENT = 334, + FCONST = 335, + SCONST = 336, + CP_SEARCH_CONDITION_TEXT = 337, + ICONST = 338, + DATE = 339 }; #endif diff --git a/dbcon/ddlpackage/ddl-scan-win.cpp b/dbcon/ddlpackage/ddl-scan-win.cpp index 197c77b3..d92e567e 100644 --- a/dbcon/ddlpackage/ddl-scan-win.cpp +++ b/dbcon/ddlpackage/ddl-scan-win.cpp @@ -1,34 +1,19 @@ -#define yy_create_buffer ddl_create_buffer -#define yy_delete_buffer ddl_delete_buffer -#define yy_scan_buffer ddl_scan_buffer -#define yy_scan_string ddl_scan_string -#define yy_scan_bytes ddl_scan_bytes -#define yy_flex_debug ddl_flex_debug -#define yy_init_buffer ddl_init_buffer -#define yy_flush_buffer ddl_flush_buffer -#define yy_load_buffer_state ddl_load_buffer_state -#define yy_switch_to_buffer ddl_switch_to_buffer -#define yyin ddlin -#define yyleng ddlleng -#define yylex ddllex -#define yyout ddlout -#define yyrestart ddlrestart -#define yytext ddltext - -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include - - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ #ifdef c_plusplus #ifndef __cplusplus #define __cplusplus @@ -302,54 +287,52 @@ static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); *yy_cp = '\0'; \ yy_c_buf_p = yy_cp; -#define YY_NUM_RULES 85 -#define YY_END_OF_BUFFER 86 -static yyconst short int yy_accept[393] = +#define YY_NUM_RULES 84 +#define YY_END_OF_BUFFER 85 +static yyconst short int yy_accept[386] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 86, 85, 81, 80, 83, 13, 83, 83, 83, 16, - 82, 84, 82, 82, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 82, 82, 82, 82, 82, 82, 10, - 12, 85, 11, 85, 14, 15, 81, 0, 16, 81, - 17, 17, 16, 0, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 82, 75, 82, 82, 82, 82, 82, - 82, 48, 82, 52, 82, 82, 82, 82, 82, 82, - 82, 82, 65, 82, 82, 82, 82, 82, 0, 11, - - 0, 14, 81, 17, 0, 18, 82, 2, 82, 82, - 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, - 29, 82, 82, 82, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 41, 43, 82, 82, 82, 82, 49, - 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, - 61, 82, 82, 82, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 82, 82, 82, 82, 6, 82, 82, - 82, 82, 82, 82, 26, 82, 82, 82, 82, 82, - 34, 82, 82, 82, 82, 37, 82, 82, 82, 82, - 82, 82, 82, 82, 50, 82, 82, 82, 82, 73, - - 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, - 82, 82, 69, 82, 82, 82, 3, 82, 82, 82, - 82, 82, 82, 9, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 82, 82, 82, 82, 71, 82, 82, - 39, 82, 82, 44, 82, 82, 82, 82, 82, 82, - 82, 82, 82, 82, 82, 82, 82, 63, 82, 82, - 82, 82, 82, 82, 82, 1, 82, 8, 82, 77, - 82, 82, 20, 82, 82, 24, 82, 82, 82, 82, - 82, 33, 72, 35, 76, 82, 82, 82, 82, 82, - 82, 47, 82, 82, 82, 82, 82, 57, 82, 82, - - 82, 82, 82, 82, 66, 82, 68, 82, 82, 82, - 5, 82, 74, 21, 19, 82, 82, 82, 28, 30, - 82, 82, 36, 82, 82, 42, 82, 82, 51, 53, - 82, 55, 82, 82, 82, 82, 82, 64, 82, 82, - 82, 70, 82, 82, 82, 82, 27, 82, 32, 82, - 82, 45, 46, 82, 82, 58, 82, 62, 82, 78, - 67, 82, 82, 7, 82, 82, 82, 38, 40, 54, - 82, 82, 82, 79, 82, 22, 82, 31, 56, 82, - 82, 82, 23, 82, 82, 60, 82, 25, 59, 82, - 4, 0 - + 85, 84, 80, 79, 82, 13, 82, 82, 82, 16, + 81, 83, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 10, + 12, 84, 11, 84, 14, 15, 80, 16, 80, 17, + 17, 16, 0, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 81, 74, 81, 81, 81, 81, 81, 81, + 48, 81, 52, 81, 81, 81, 81, 81, 81, 81, + 81, 65, 81, 81, 81, 81, 81, 0, 11, 0, + + 14, 80, 17, 0, 18, 81, 2, 81, 81, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 29, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 41, 43, 81, 81, 81, 81, 49, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 61, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 81, 81, 81, 6, 81, 81, 81, 81, + 81, 81, 26, 81, 81, 81, 81, 81, 34, 81, + 81, 81, 81, 37, 81, 81, 81, 81, 81, 81, + 81, 81, 50, 81, 81, 81, 81, 72, 81, 81, + + 81, 81, 81, 81, 81, 81, 81, 81, 81, 68, + 81, 81, 81, 3, 81, 81, 81, 81, 81, 81, + 9, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 81, 81, 70, 81, 81, 39, 81, 81, + 44, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 81, 81, 81, 63, 81, 81, 81, 81, 81, + 81, 1, 81, 8, 81, 76, 81, 81, 20, 81, + 81, 24, 81, 81, 81, 81, 81, 33, 71, 35, + 75, 81, 81, 81, 81, 81, 81, 47, 81, 81, + 81, 81, 81, 57, 81, 81, 81, 81, 81, 81, + + 66, 67, 81, 81, 81, 5, 81, 73, 21, 19, + 81, 81, 81, 28, 30, 81, 81, 36, 81, 81, + 42, 81, 81, 51, 53, 81, 55, 81, 81, 81, + 81, 81, 64, 81, 81, 69, 81, 81, 81, 81, + 27, 81, 32, 81, 81, 45, 46, 81, 81, 58, + 81, 62, 81, 77, 81, 81, 7, 81, 81, 81, + 38, 40, 54, 81, 81, 81, 78, 81, 22, 81, + 31, 56, 81, 81, 81, 23, 81, 81, 60, 81, + 25, 59, 81, 4, 0 } ; static yyconst int yy_ec[256] = @@ -392,212 +375,210 @@ static yyconst int yy_meta[41] = 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } ; -static yyconst short int yy_base[400] = +static yyconst short int yy_base[393] = { 0, - 0, 0, 33, 35, 428, 427, 428, 427, 426, 425, - 431, 438, 43, 46, 438, 438, 39, 42, 417, 44, - 0, 438, 40, 405, 45, 49, 31, 36, 56, 408, - 64, 53, 398, 57, 406, 67, 75, 67, 409, 438, - 438, 415, 438, 416, 438, 438, 100, 409, 80, 0, - 93, 96, 98, 104, 0, 386, 401, 384, 383, 395, - 382, 103, 93, 395, 381, 378, 106, 376, 381, 388, - 385, 378, 374, 379, 0, 377, 106, 364, 93, 374, - 383, 366, 107, 0, 367, 116, 110, 103, 383, 364, - 380, 367, 0, 359, 118, 375, 373, 359, 382, 438, - - 383, 438, 0, 130, 376, 375, 363, 0, 366, 355, - 360, 365, 116, 364, 345, 352, 345, 362, 344, 356, - 351, 131, 354, 356, 341, 347, 336, 353, 348, 340, - 346, 345, 329, 343, 0, 344, 347, 346, 335, 0, - 331, 337, 321, 337, 326, 326, 332, 335, 315, 315, - 0, 321, 312, 319, 305, 315, 311, 318, 325, 307, - 136, 309, 305, 323, 307, 319, 312, 130, 307, 304, - 311, 295, 294, 308, 292, 298, 289, 291, 288, 295, - 0, 292, 285, 284, 294, 0, 298, 277, 291, 292, - 290, 279, 278, 289, 0, 276, 284, 283, 290, 0, - - 272, 276, 270, 278, 274, 280, 279, 274, 279, 260, - 273, 259, 0, 269, 269, 262, 0, 266, 254, 269, - 267, 268, 265, 0, 255, 254, 249, 261, 251, 255, - 262, 250, 243, 255, 254, 253, 238, 0, 249, 246, - 0, 253, 248, 0, 237, 236, 225, 240, 247, 228, - 228, 240, 239, 234, 227, 232, 227, 0, 225, 237, - 232, 222, 230, 220, 232, 0, 218, 0, 226, 0, - 210, 209, 209, 207, 225, 0, 205, 211, 211, 202, - 139, 0, 0, 0, 0, 207, 219, 207, 200, 194, - 193, 0, 212, 202, 204, 187, 197, 0, 207, 195, - - 194, 208, 186, 185, 0, 199, 0, 202, 184, 198, - 0, 195, 0, 0, 0, 190, 199, 192, 0, 0, - 194, 191, 0, 174, 181, 0, 173, 172, 0, 0, - 175, 0, 186, 168, 188, 166, 164, 0, 179, 179, - 164, 0, 163, 162, 165, 157, 0, 165, 0, 171, - 150, 0, 0, 160, 168, 0, 151, 0, 152, 0, - 0, 145, 164, 0, 148, 147, 143, 0, 0, 0, - 128, 127, 140, 0, 130, 123, 136, 0, 0, 128, - 96, 92, 0, 64, 53, 0, 45, 0, 0, 36, - 0, 438, 164, 167, 170, 59, 173, 176, 179 + 0, 0, 33, 35, 418, 417, 418, 417, 416, 415, + 421, 428, 43, 46, 428, 428, 407, 40, 406, 42, + 0, 428, 38, 394, 36, 47, 29, 34, 50, 397, + 57, 46, 387, 59, 395, 63, 69, 55, 398, 428, + 428, 404, 428, 405, 428, 428, 92, 77, 0, 85, + 87, 96, 100, 0, 376, 391, 374, 373, 385, 372, + 98, 92, 385, 371, 368, 104, 366, 371, 378, 375, + 368, 364, 369, 0, 367, 82, 354, 88, 364, 373, + 356, 101, 0, 357, 106, 116, 99, 373, 354, 370, + 357, 0, 349, 360, 364, 362, 348, 371, 428, 372, + + 428, 0, 122, 365, 364, 352, 0, 355, 344, 349, + 354, 107, 353, 334, 341, 334, 351, 333, 345, 340, + 123, 343, 345, 330, 336, 325, 342, 337, 329, 335, + 334, 318, 332, 0, 333, 336, 335, 324, 0, 320, + 326, 310, 326, 315, 315, 321, 324, 304, 304, 0, + 310, 301, 308, 294, 304, 300, 315, 297, 129, 299, + 295, 313, 297, 309, 302, 122, 297, 294, 301, 285, + 284, 298, 282, 288, 279, 281, 278, 285, 0, 282, + 275, 274, 284, 0, 288, 267, 281, 282, 280, 269, + 268, 279, 0, 266, 274, 273, 280, 0, 262, 266, + + 260, 268, 264, 270, 269, 264, 269, 250, 250, 0, + 260, 260, 253, 0, 257, 245, 260, 258, 259, 256, + 0, 246, 245, 240, 252, 242, 246, 253, 241, 234, + 246, 245, 244, 229, 0, 240, 237, 0, 244, 239, + 0, 228, 227, 216, 231, 238, 219, 219, 231, 230, + 225, 218, 223, 218, 0, 216, 228, 223, 222, 212, + 224, 0, 210, 0, 218, 0, 202, 201, 201, 199, + 217, 0, 197, 203, 203, 194, 128, 0, 0, 0, + 0, 199, 211, 199, 192, 186, 185, 0, 204, 194, + 196, 179, 189, 0, 199, 187, 186, 200, 178, 177, + + 0, 0, 195, 177, 191, 0, 188, 0, 0, 0, + 183, 192, 185, 0, 0, 187, 184, 0, 167, 174, + 0, 166, 165, 0, 0, 168, 0, 179, 161, 181, + 159, 157, 0, 172, 158, 0, 157, 156, 159, 151, + 0, 159, 0, 165, 144, 0, 0, 154, 162, 0, + 145, 0, 146, 0, 139, 158, 0, 142, 142, 155, + 0, 0, 0, 139, 121, 134, 0, 125, 118, 131, + 0, 0, 129, 108, 104, 0, 82, 79, 0, 75, + 0, 0, 53, 0, 428, 156, 159, 162, 57, 165, + 168, 171 } ; -static yyconst short int yy_def[400] = +static yyconst short int yy_def[393] = { 0, - 392, 1, 393, 393, 394, 394, 395, 395, 393, 393, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 396, 392, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 392, - 392, 397, 392, 398, 392, 392, 392, 392, 392, 399, - 392, 392, 392, 392, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 397, 392, - - 398, 392, 399, 392, 392, 392, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 0, 392, 392, 392, 392, 392, 392, 392 + 385, 1, 386, 386, 387, 387, 388, 388, 386, 386, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 389, 385, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 385, + 385, 390, 385, 391, 385, 385, 385, 385, 392, 385, + 385, 385, 385, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 390, 385, 391, + + 385, 392, 385, 385, 385, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 0, 385, 385, 385, 385, 385, + 385, 385 } ; -static yyconst short int yy_nxt[479] = +static yyconst short int yy_nxt[469] = { 0, 12, 13, 14, 13, 12, 15, 16, 15, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 21, 21, 29, 21, 30, 21, 31, 32, 33, 34, 21, 35, 36, 37, 38, 39, 21, 21, 21, 40, 41, 40, 41, 47, 47, 47, 47, 47, 47, - 48, 49, 50, 48, 49, 52, 53, 56, 57, 70, - 61, 55, 72, 54, 66, 73, 58, 62, 67, 71, - 391, 74, 85, 390, 63, 59, 75, 64, 68, 79, - 65, 69, 82, 76, 77, 389, 88, 80, 83, 86, - 91, 48, 49, 81, 89, 95, 388, 96, 92, 54, - - 97, 47, 47, 47, 93, 51, 90, 94, 104, 52, - 53, 387, 54, 105, 105, 54, 106, 54, 113, 115, - 116, 117, 114, 121, 132, 146, 122, 136, 386, 133, - 147, 137, 123, 141, 142, 144, 150, 151, 148, 145, - 134, 157, 104, 149, 167, 222, 177, 385, 168, 54, - 178, 158, 214, 215, 321, 384, 383, 382, 322, 381, - 380, 379, 378, 223, 12, 12, 12, 42, 42, 42, - 44, 44, 44, 99, 99, 99, 101, 101, 101, 103, - 377, 103, 376, 375, 374, 373, 372, 371, 370, 369, - 368, 367, 366, 365, 364, 363, 362, 361, 360, 359, - - 358, 357, 356, 355, 354, 353, 352, 351, 350, 349, - 348, 347, 346, 345, 344, 343, 342, 341, 340, 339, - 338, 337, 336, 335, 334, 333, 332, 331, 330, 329, - 328, 327, 326, 325, 324, 323, 320, 319, 318, 317, - 316, 315, 314, 313, 312, 311, 310, 309, 308, 307, - 306, 305, 304, 303, 302, 301, 300, 299, 298, 297, - 296, 295, 294, 293, 292, 291, 290, 289, 288, 287, - 286, 285, 284, 283, 282, 281, 280, 279, 278, 277, - 276, 275, 274, 273, 272, 271, 270, 269, 268, 267, - 266, 265, 264, 263, 262, 261, 260, 259, 258, 257, - - 256, 255, 254, 253, 252, 251, 250, 249, 248, 247, - 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, - 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, - 226, 225, 224, 221, 220, 219, 218, 217, 216, 213, - 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, - 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, - 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, - 182, 181, 180, 179, 176, 175, 174, 173, 172, 171, - 170, 169, 166, 165, 164, 163, 162, 106, 106, 102, - 100, 161, 160, 159, 156, 155, 154, 153, 152, 143, - - 140, 139, 138, 135, 131, 130, 129, 128, 127, 126, - 125, 124, 120, 119, 118, 112, 111, 110, 109, 108, - 107, 51, 102, 100, 98, 87, 84, 78, 60, 51, - 392, 46, 46, 45, 45, 43, 43, 11, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392 + 49, 60, 48, 51, 52, 55, 56, 69, 61, 54, + 71, 53, 65, 72, 57, 62, 66, 70, 63, 73, + 74, 64, 78, 58, 84, 81, 67, 75, 76, 68, + 79, 82, 87, 94, 90, 95, 80, 384, 96, 48, + 88, 85, 91, 47, 47, 47, 53, 50, 92, 103, + + 131, 93, 89, 383, 53, 132, 53, 51, 52, 104, + 104, 382, 105, 112, 381, 53, 133, 113, 114, 115, + 116, 120, 135, 380, 121, 143, 136, 140, 141, 144, + 122, 145, 149, 150, 103, 165, 146, 219, 175, 166, + 379, 53, 176, 316, 147, 211, 212, 317, 378, 148, + 377, 376, 375, 374, 373, 220, 12, 12, 12, 42, + 42, 42, 44, 44, 44, 98, 98, 98, 100, 100, + 100, 102, 372, 102, 371, 370, 369, 368, 367, 366, + 365, 364, 363, 362, 361, 360, 359, 358, 357, 356, + 355, 354, 353, 352, 351, 350, 349, 348, 347, 346, + + 345, 344, 343, 342, 341, 340, 339, 338, 337, 336, + 335, 334, 333, 332, 331, 330, 329, 328, 327, 326, + 325, 324, 323, 322, 321, 320, 319, 318, 315, 314, + 313, 312, 311, 310, 309, 308, 307, 306, 305, 304, + 303, 302, 301, 300, 299, 298, 297, 296, 295, 294, + 293, 292, 291, 290, 289, 288, 287, 286, 285, 284, + 283, 282, 281, 280, 279, 278, 277, 276, 275, 274, + 273, 272, 271, 270, 269, 268, 267, 266, 265, 264, + 263, 262, 261, 260, 259, 258, 257, 256, 255, 254, + 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, + + 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, + 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, + 223, 222, 221, 218, 217, 216, 215, 214, 213, 210, + 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, + 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, + 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, + 179, 178, 177, 174, 173, 172, 171, 170, 169, 168, + 167, 164, 163, 162, 161, 160, 105, 105, 101, 99, + 159, 158, 157, 156, 155, 154, 153, 152, 151, 142, + 139, 138, 137, 134, 130, 129, 128, 127, 126, 125, + + 124, 123, 119, 118, 117, 111, 110, 109, 108, 107, + 106, 101, 99, 97, 86, 83, 77, 59, 50, 48, + 385, 46, 46, 45, 45, 43, 43, 11, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385 } ; -static yyconst short int yy_chk[479] = +static yyconst short int yy_chk[469] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 4, 4, 13, 13, 13, 14, 14, 14, - 17, 17, 18, 18, 18, 20, 20, 23, 23, 27, - 25, 396, 28, 20, 26, 28, 23, 25, 26, 27, - 390, 28, 34, 387, 25, 23, 29, 25, 26, 31, - 25, 26, 32, 29, 29, 385, 36, 31, 32, 34, - 37, 49, 49, 31, 36, 38, 384, 38, 37, 49, - - 38, 47, 47, 47, 37, 51, 36, 37, 52, 53, - 53, 382, 51, 54, 54, 52, 54, 53, 62, 63, - 63, 63, 62, 67, 77, 87, 67, 79, 381, 77, - 87, 79, 67, 83, 83, 86, 88, 88, 87, 86, - 77, 95, 104, 87, 113, 168, 122, 380, 113, 104, - 122, 95, 161, 161, 281, 377, 376, 375, 281, 373, - 372, 371, 367, 168, 393, 393, 393, 394, 394, 394, - 395, 395, 395, 397, 397, 397, 398, 398, 398, 399, - 366, 399, 365, 363, 362, 359, 357, 355, 354, 351, - 350, 348, 346, 345, 344, 343, 341, 340, 339, 337, - - 336, 335, 334, 333, 331, 328, 327, 325, 324, 322, - 321, 318, 317, 316, 312, 310, 309, 308, 306, 304, - 303, 302, 301, 300, 299, 297, 296, 295, 294, 293, - 291, 290, 289, 288, 287, 286, 280, 279, 278, 277, - 275, 274, 273, 272, 271, 269, 267, 265, 264, 263, - 262, 261, 260, 259, 257, 256, 255, 254, 253, 252, - 251, 250, 249, 248, 247, 246, 245, 243, 242, 240, - 239, 237, 236, 235, 234, 233, 232, 231, 230, 229, - 228, 227, 226, 225, 223, 222, 221, 220, 219, 218, - 216, 215, 214, 212, 211, 210, 209, 208, 207, 206, - - 205, 204, 203, 202, 201, 199, 198, 197, 196, 194, - 193, 192, 191, 190, 189, 188, 187, 185, 184, 183, - 182, 180, 179, 178, 177, 176, 175, 174, 173, 172, - 171, 170, 169, 167, 166, 165, 164, 163, 162, 160, - 159, 158, 157, 156, 155, 154, 153, 152, 150, 149, - 148, 147, 146, 145, 144, 143, 142, 141, 139, 138, - 137, 136, 134, 133, 132, 131, 130, 129, 128, 127, - 126, 125, 124, 123, 121, 120, 119, 118, 117, 116, - 115, 114, 112, 111, 110, 109, 107, 106, 105, 101, - 99, 98, 97, 96, 94, 92, 91, 90, 89, 85, - - 82, 81, 80, 78, 76, 74, 73, 72, 71, 70, - 69, 68, 66, 65, 64, 61, 60, 59, 58, 57, - 56, 48, 44, 42, 39, 35, 33, 30, 24, 19, - 11, 10, 9, 8, 7, 6, 5, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392, 392, 392, - 392, 392, 392, 392, 392, 392, 392, 392 + 18, 25, 18, 20, 20, 23, 23, 27, 25, 389, + 28, 20, 26, 28, 23, 25, 26, 27, 25, 28, + 29, 25, 31, 23, 34, 32, 26, 29, 29, 26, + 31, 32, 36, 38, 37, 38, 31, 383, 38, 48, + 36, 34, 37, 47, 47, 47, 48, 50, 37, 51, + + 76, 37, 36, 380, 50, 76, 51, 52, 52, 53, + 53, 378, 53, 61, 377, 52, 76, 61, 62, 62, + 62, 66, 78, 375, 66, 85, 78, 82, 82, 85, + 66, 86, 87, 87, 103, 112, 86, 166, 121, 112, + 374, 103, 121, 277, 86, 159, 159, 277, 373, 86, + 370, 369, 368, 366, 365, 166, 386, 386, 386, 387, + 387, 387, 388, 388, 388, 390, 390, 390, 391, 391, + 391, 392, 364, 392, 360, 359, 358, 356, 355, 353, + 351, 349, 348, 345, 344, 342, 340, 339, 338, 337, + 335, 334, 332, 331, 330, 329, 328, 326, 323, 322, + + 320, 319, 317, 316, 313, 312, 311, 307, 305, 304, + 303, 300, 299, 298, 297, 296, 295, 293, 292, 291, + 290, 289, 287, 286, 285, 284, 283, 282, 276, 275, + 274, 273, 271, 270, 269, 268, 267, 265, 263, 261, + 260, 259, 258, 257, 256, 254, 253, 252, 251, 250, + 249, 248, 247, 246, 245, 244, 243, 242, 240, 239, + 237, 236, 234, 233, 232, 231, 230, 229, 228, 227, + 226, 225, 224, 223, 222, 220, 219, 218, 217, 216, + 215, 213, 212, 211, 209, 208, 207, 206, 205, 204, + 203, 202, 201, 200, 199, 197, 196, 195, 194, 192, + + 191, 190, 189, 188, 187, 186, 185, 183, 182, 181, + 180, 178, 177, 176, 175, 174, 173, 172, 171, 170, + 169, 168, 167, 165, 164, 163, 162, 161, 160, 158, + 157, 156, 155, 154, 153, 152, 151, 149, 148, 147, + 146, 145, 144, 143, 142, 141, 140, 138, 137, 136, + 135, 133, 132, 131, 130, 129, 128, 127, 126, 125, + 124, 123, 122, 120, 119, 118, 117, 116, 115, 114, + 113, 111, 110, 109, 108, 106, 105, 104, 100, 98, + 97, 96, 95, 94, 93, 91, 90, 89, 88, 84, + 81, 80, 79, 77, 75, 73, 72, 71, 70, 69, + + 68, 67, 65, 64, 63, 60, 59, 58, 57, 56, + 55, 44, 42, 39, 35, 33, 30, 24, 19, 17, + 11, 10, 9, 8, 7, 6, 5, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385, 385, 385, + 385, 385, 385, 385, 385, 385, 385, 385 } ; static yy_state_type yy_last_accepting_state; @@ -612,23 +593,38 @@ static char *yy_last_accepting_cpos; #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #define INITIAL 0 -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ -/* $Id: ddl.l 9341 2013-03-27 14:10:35Z chao $ */ +/* + +Copyright (C) 2009-2012 Calpont Corporation. + +Use of and access to the Calpont InfiniDB Community software is subject to the +terms and conditions of the Calpont Open Source License Agreement. Use of and +access to the Calpont InfiniDB Enterprise software is subject to the terms and +conditions of the Calpont End User License Agreement. + +This program is distributed in the hope that it will be useful, and unless +otherwise noted on your license agreement, WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +Please refer to the Calpont Open Source License Agreement and the Calpont End +User License Agreement for more details. + +You should have received a copy of either the Calpont Open Source License +Agreement or the Calpont End User License Agreement along with this program; if +not, it is your responsibility to review the terms and conditions of the proper +Calpont license agreement by visiting http://www.calpont.com for the Calpont +InfiniDB Enterprise End User License Agreement or http://www.infinidb.org for +the Calpont InfiniDB Community Calpont Open Source License Agreement. + +Calpont may make changes to these license agreements from time to time. When +these changes are made, Calpont will make a new copy of the Calpont End User +License Agreement available at http://www.calpont.com and a new copy of the +Calpont Open Source License Agreement available at http:///www.infinidb.org. +You understand and agree that if you use the Program after the date on which +the license agreement authorizing your use has changed, Calpont will treat your +use as acceptance of the updated License. + +*/ +/* $Id: ddl.l 8618 2012-06-07 22:27:04Z chao $ */ #include #include #include @@ -861,13 +857,13 @@ YY_DECL while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 393 ) + if ( yy_current_state >= 386 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } - while ( yy_base[yy_current_state] != 438 ); + while ( yy_base[yy_current_state] != 428 ); yy_find_action: yy_act = yy_accept[yy_current_state]; @@ -1165,83 +1161,79 @@ YY_RULE_SETUP YY_BREAK case 67: YY_RULE_SETUP -{return UNSIGNED;} +{return UPDATE;} YY_BREAK case 68: YY_RULE_SETUP -{return UPDATE;} +{return USER;} YY_BREAK case 69: YY_RULE_SETUP -{return USER;} +{return VARCHAR;} YY_BREAK case 70: YY_RULE_SETUP -{return VARCHAR;} +{return IDB_FLOAT;} YY_BREAK case 71: YY_RULE_SETUP -{return IDB_FLOAT;} +{return DOUBLE;} YY_BREAK case 72: YY_RULE_SETUP -{return DOUBLE;} +{return REAL;} YY_BREAK case 73: YY_RULE_SETUP -{return REAL;} +{return CHARSET;} YY_BREAK case 74: YY_RULE_SETUP -{return CHARSET;} +{return IF;} YY_BREAK case 75: YY_RULE_SETUP -{return IDB_IF;} - YY_BREAK -case 76: -YY_RULE_SETUP {return EXISTS;} YY_BREAK -case 77: +case 76: YY_RULE_SETUP {return CHANGE;} YY_BREAK -case 78: +case 77: YY_RULE_SETUP {return TRUNCATE;} YY_BREAK -case 79: +case 78: YY_RULE_SETUP {return VARBINARY;} YY_BREAK -case 80: +case 79: YY_RULE_SETUP { lineno++;} YY_BREAK -case 81: +case 80: YY_RULE_SETUP { /* ignore */ } YY_BREAK -case 82: +case 81: YY_RULE_SETUP {ddllval.str = scanner_copy(ddltext); return IDENT;} YY_BREAK -case 83: +case 82: YY_RULE_SETUP { return ddltext[0]; } YY_BREAK -case 84: +case 83: YY_RULE_SETUP { /* ignore */ } YY_BREAK -case 85: +case 84: YY_RULE_SETUP ECHO; YY_BREAK @@ -1540,7 +1532,7 @@ static yy_state_type yy_get_previous_state() while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 393 ) + if ( yy_current_state >= 386 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; @@ -1575,11 +1567,11 @@ yy_state_type yy_current_state; while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 393 ) + if ( yy_current_state >= 386 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 392); + yy_is_jam = (yy_current_state == 385); return yy_is_jam ? 0 : yy_current_state; } diff --git a/dbcon/ddlpackage/ddl.l b/dbcon/ddlpackage/ddl.l index 64218bb3..5bd52034 100644 --- a/dbcon/ddlpackage/ddl.l +++ b/dbcon/ddlpackage/ddl.l @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -/* $Id: ddl.l 9341 2013-03-27 14:10:35Z chao $ */ +/* $Id: ddl.l 8706 2012-07-13 16:25:50Z rdempsey $ */ %{ #include #include @@ -63,7 +63,7 @@ ident_cont [A-Za-z\200-\377_0-9\$] identifier {ident_start}{ident_cont}* integer [-+]?{digit}+ -decimal ([-+]?({digit}*\.{digit}+)|({digit}+\.{digit}*)) +decimal (({digit}*\.{digit}+)|({digit}+\.{digit}*)) real ({integer}|{decimal})[Ee][-+]?{digit}+ realfail1 ({integer}|{decimal})[Ee] realfail2 ({integer}|{decimal})[Ee][-+] @@ -142,7 +142,6 @@ TABLE {return TABLE;} TINYINT {return TINYINT;} TO {return TO;} UNIQUE {return UNIQUE;} -UNSIGNED {return UNSIGNED;} UPDATE {return UPDATE;} USER {return USER;} VARCHAR {return VARCHAR;} @@ -150,7 +149,7 @@ FLOAT {return IDB_FLOAT;} DOUBLE {return DOUBLE;} REAL {return REAL;} CHARSET {return CHARSET;} -IF {return IDB_IF;} +IF {return IF;} EXISTS {return EXISTS;} CHANGE {return CHANGE;} TRUNCATE {return TRUNCATE;} diff --git a/dbcon/ddlpackage/ddl.y b/dbcon/ddlpackage/ddl.y index 1013f575..70d0e8ff 100644 --- a/dbcon/ddlpackage/ddl.y +++ b/dbcon/ddlpackage/ddl.y @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -/* $Id: ddl.y 9314 2013-03-19 17:39:25Z dhall $ */ +/* $Id: ddl.y 8706 2012-07-13 16:25:50Z rdempsey $ */ /* This describes a substantial subset of SQL92 DDL with some enhancements from various vendors. Most of the nomenclature in the grammar is drawn from SQL92. @@ -113,8 +113,8 @@ DECIMAL DEFAULT DEFERRABLE DEFERRED IDB_DELETE DROP ENGINE FOREIGN FULL IMMEDIATE INDEX INITIALLY IDB_INT INTEGER KEY MATCH MAX_ROWS MIN_ROWS MODIFY NO NOT NULL_TOK NUMBER NUMERIC ON PARTIAL PRECISION PRIMARY REFERENCES RENAME RESTRICT SET SMALLINT TABLE TIME -TINYINT TO UNIQUE UNSIGNED UPDATE USER SESSION_USER SYSTEM_USER VARCHAR VARBINARY -VARYING WITH ZONE DOUBLE IDB_FLOAT REAL CHARSET IDB_IF EXISTS CHANGE TRUNCATE +TINYINT TO UNIQUE UPDATE USER SESSION_USER SYSTEM_USER VARCHAR VARBINARY +VARYING WITH ZONE DOUBLE IDB_FLOAT REAL CHARSET IF EXISTS CHANGE TRUNCATE %token IDENT FCONST SCONST CP_SEARCH_CONDITION_TEXT ICONST DATE @@ -249,7 +249,7 @@ drop_table_statement: ; opt_if_exists: - IDB_IF EXISTS {$$ = NULL;} + IF EXISTS {$$ = NULL;} | {$$ = NULL;} ; @@ -290,7 +290,7 @@ create_table_statement: ; opt_if_not_exists: - IDB_IF NOT EXISTS {$$ = NULL;} + IF NOT EXISTS {$$ = NULL;} | {$$ = NULL;} ; @@ -865,44 +865,26 @@ exact_numeric_type: $2->fLength = DDLDatatypeLength[DDL_NUMERIC]; $$ = $2; } - | NUMERIC opt_precision_scale UNSIGNED - { - $2->fType = DDL_UNSIGNED_NUMERIC; - $2->fLength = DDLDatatypeLength[DDL_UNSIGNED_NUMERIC]; - $$ = $2; - } | DECIMAL opt_precision_scale { $2->fType = DDL_DECIMAL; /* $2->fLength = DDLDatatypeLength[DDL_DECIMAL]; */ $$ = $2; } - | DECIMAL opt_precision_scale UNSIGNED - { - $2->fType = DDL_UNSIGNED_DECIMAL; -/* $3->fLength = DDLDatatypeLength[DDL_DECIMAL]; */ - $$ = $2; - } | NUMBER opt_precision_scale { $2->fType = DDL_DECIMAL; $2->fLength = DDLDatatypeLength[DDL_DECIMAL]; $$ = $2; } - | NUMBER opt_precision_scale UNSIGNED - { - $2->fType = DDL_UNSIGNED_DECIMAL; - $2->fLength = DDLDatatypeLength[DDL_UNSIGNED_DECIMAL]; - $$ = $2; - } | INTEGER opt_display_width { - $$ = new ColumnType(DDL_INT); + $$ = new ColumnType(DDL_INTEGER); $$->fLength = DDLDatatypeLength[DDL_INT]; } | IDB_INT opt_display_width { - $$ = new ColumnType(DDL_INT); + $$ = new ColumnType(DDL_INTEGER); $$->fLength = DDLDatatypeLength[DDL_INT]; } | SMALLINT opt_display_width @@ -920,31 +902,6 @@ exact_numeric_type: $$ = new ColumnType(DDL_BIGINT); $$->fLength = DDLDatatypeLength[DDL_BIGINT]; } - | INTEGER opt_display_width UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_INT); - $$->fLength = DDLDatatypeLength[DDL_INT]; - } - | IDB_INT opt_display_width UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_INT); - $$->fLength = DDLDatatypeLength[DDL_INT]; - } - | SMALLINT opt_display_width UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_SMALLINT); - $$->fLength = DDLDatatypeLength[DDL_SMALLINT]; - } - | TINYINT opt_display_width UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_TINYINT); - $$->fLength = DDLDatatypeLength[DDL_TINYINT]; - } - | BIGINT opt_display_width UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_BIGINT); - $$->fLength = DDLDatatypeLength[DDL_BIGINT]; - } ; /* Bug 1570, change default scale to 0 from -1 */ opt_precision_scale: @@ -964,31 +921,16 @@ approximate_numeric_type: $$ = new ColumnType(DDL_DOUBLE); $$->fLength = DDLDatatypeLength[DDL_DOUBLE]; } - | DOUBLE opt_display_precision_scale_null UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_DOUBLE); - $$->fLength = DDLDatatypeLength[DDL_DOUBLE]; - } | REAL opt_display_precision_scale_null { $$ = new ColumnType(DDL_DOUBLE); $$->fLength = DDLDatatypeLength[DDL_DOUBLE]; } - | REAL opt_display_precision_scale_null UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_DOUBLE); - $$->fLength = DDLDatatypeLength[DDL_DOUBLE]; - } | IDB_FLOAT opt_display_precision_scale_null { $$ = new ColumnType(DDL_FLOAT); $$->fLength = DDLDatatypeLength[DDL_FLOAT]; } - | IDB_FLOAT opt_display_precision_scale_null UNSIGNED - { - $$ = new ColumnType(DDL_UNSIGNED_FLOAT); - $$->fLength = DDLDatatypeLength[DDL_FLOAT]; - } ; opt_display_precision_scale_null: diff --git a/dbcon/ddlpackage/ddlpkg.cpp b/dbcon/ddlpackage/ddlpkg.cpp index cd6c8009..00e9767e 100644 --- a/dbcon/ddlpackage/ddlpkg.cpp +++ b/dbcon/ddlpackage/ddlpkg.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ddlpkg.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: ddlpkg.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -82,6 +82,7 @@ namespace ddlpackage } } + ColumnType::ColumnType(int prec, int scale) : fType(DDL_INVALID_DATATYPE), fLength(0), @@ -92,7 +93,7 @@ namespace ddlpackage fLength = precision_width(fPrecision); } - ColumnType::ColumnType(int type) : + ColumnType::ColumnType(int type) : fType(type), fLength(0), fScale(0), @@ -101,29 +102,24 @@ namespace ddlpackage switch ( type ) { case DDL_TINYINT: - case DDL_UNSIGNED_TINYINT: fPrecision = 3; break; case DDL_SMALLINT: - case DDL_UNSIGNED_SMALLINT: fPrecision = 5; break; case DDL_INT: - case DDL_UNSIGNED_INT: - case DDL_MEDINT: + case DDL_MEDINT: fPrecision = 10; break; case DDL_BIGINT: - fPrecision = 19; - case DDL_UNSIGNED_BIGINT: - fPrecision = 20; + fPrecision = 19; break; default: fPrecision = 10; break; } } -#if 0 + ColumnType::ColumnType(int type, int length, int precision, int scale, int compressiontype, const char* autoIncrement, int64_t nextValue, bool withTimezone) : fType(type) , fLength(length), @@ -135,7 +131,7 @@ namespace ddlpackage fNextvalue(nextValue) { } -#endif + ColumnConstraintDef::ColumnConstraintDef(DDL_CONSTRAINTS type) : SchemaObject(), fDeferrable(false), @@ -166,43 +162,4 @@ namespace ddlpackage << "d=" << ReferentialActionStrings[ref.fOnDelete]; return os; } - - void ColumnDef::convertDecimal() - { - //@Bug 2089 decimal precision default to 10 if 0 is used. - if (fType->fPrecision <= 0) - fType->fPrecision = 10; - - if (fType->fPrecision == -1 || fType->fPrecision == 0) - { - fType->fType = DDL_BIGINT; - fType->fLength = 8; - fType->fScale = 0; - } - else if ((fType->fPrecision > 0) && (fType->fPrecision < 3)) - { - //dataType = CalpontSystemCatalog::TINYINT; - fType->fType = DDL_TINYINT; - fType->fLength = 1; - } - - else if (fType->fPrecision < 5 && (fType->fPrecision > 2)) - { - //dataType = CalpontSystemCatalog::SMALLINT; - fType->fType = DDL_SMALLINT; - fType->fLength = 2; - } - else if (fType->fPrecision > 4 && fType->fPrecision < 10) - { - //dataType = CalpontSystemCatalog::INT; - fType->fType = DDL_INT; - fType->fLength = 4; - } - else if (fType->fPrecision > 9 && fType->fPrecision < 19) - { - //dataType = CalpontSystemCatalog::BIGINT; - fType->fType = DDL_BIGINT; - fType->fLength = 8; - } - } } diff --git a/dbcon/ddlpackage/ddlpkg.h b/dbcon/ddlpackage/ddlpkg.h index 56a804b5..0473cecb 100644 --- a/dbcon/ddlpackage/ddlpkg.h +++ b/dbcon/ddlpackage/ddlpkg.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ddlpkg.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: ddlpkg.h 8926 2012-09-25 21:56:32Z zzhu $ * * ***********************************************************************/ @@ -65,6 +65,7 @@ struct ColumnDef; struct ColumnDefaultValue; struct ColumnType; struct QualifiedName; +struct TableDef; struct CreateTableStatement; struct SqlStatementList; struct SqlStatement; @@ -72,7 +73,6 @@ struct ColumnConstraintDef; struct TableConstraintDef; struct SchemaObject; struct ReferentialAction; -struct TableDef; typedef SqlStatement DDLPkg; @@ -220,15 +220,6 @@ enum DDL_DATATYPES { DDL_NUMERIC, DDL_NUMBER, DDL_INTEGER, - DDL_UNSIGNED_TINYINT, - DDL_UNSIGNED_SMALLINT, - DDL_UNSIGNED_MEDINT, - DDL_UNSIGNED_INT, - DDL_UNSIGNED_BIGINT, - DDL_UNSIGNED_DECIMAL, - DDL_UNSIGNED_FLOAT, - DDL_UNSIGNED_DOUBLE, - DDL_UNSIGNED_NUMERIC, DDL_INVALID_DATATYPE }; @@ -256,15 +247,6 @@ const std::string DDLDatatypeString[] = "numeric", "number", "integer", - "unsigned-tinyint", - "unsigned-smallint", - "unsigned-medint", - "unsigned-int", - "unsigned-bigint", - "unsigned-decimal", - "unsigned-float", - "unsigned-double", - "unsigned-numeric", "" }; @@ -289,35 +271,26 @@ const std::string AlterActionString[] = */ const int DDLDatatypeLength[] = { - 1, // BIT - 1, // TINYINT - 1, // CHAR - 2, // SMALLINT - 2, // DECIMAL - 4, // MEDINT - 4, // INT - 4, // FLOAT - 4, // DATE - 8, // BIGINT - 8, // DOUBLE - 8, // DATETIME - 8, // VARCHAR - 8, // VARBINAR - 8, // CLOB - 8, // BLOB - 4, // REAL - 2, // NUMERIC - 4, // NUMBER - 4, // INTEGER - 1, // UNSIGNED_TINYINT, - 2, // UNSIGNED_SMALLINT, - 4, // UNSIGNED_MEDINT, - 4, // UNSIGNED_INT, - 8, // UNSIGNED_BIGINT, - 2, // UNSIGNED_DECIMAL, - 4, // UNSIGNED_FLOAT, - 8, // UNSIGNED_DOUBLE, - 2, // UNSIGNED_NUMERIC, + 1, // BIT + 1, // TINYINT + 1, // CHAR + 2, // SMALLINT + 2, // DECIMAL + 4, // MEDINT + 4, // INT + 4, // FLOAT + 4, // DATE + 8, // BIGINT + 8, // DOUBLE + 8, // DATETIME + 8, // VARCHAR + 8, // VARBINARY + 8, // CLOB + 8, // BLOB + 4, // REAL + 2, // NUMERIC + 4, // NUMBER + 4, // INTEGER -1 // INVALID LENGTH }; @@ -425,7 +398,7 @@ struct SqlStatement * Right now this var is initialized from a counter. At some point we need * to serialize/unserialize it from a byte stream. */ - uint32_t fSessionID; + u_int32_t fSessionID; /** @brief The original sql string */ @@ -475,78 +448,6 @@ struct SqlStatementList -/** @brief Stores catalog, schema, object names. - * - * ddl.y does not yet support catalog. So, expect catalog - * qualified names to fail parsing for the moment. - */ -struct QualifiedName -{ - /** @brief Deserialize from ByteStream */ - EXPORT virtual int unserialize(messageqcpp::ByteStream& bs); - - /** @brief Serialize to ByteStream */ - EXPORT virtual int serialize(messageqcpp::ByteStream& bs); - - - QualifiedName() - {} - - EXPORT QualifiedName(const char* name); - EXPORT QualifiedName(const char* name, const char* schema); - EXPORT QualifiedName(const char* name, const char* schema, const char* catalog); - - virtual ~QualifiedName() - {} - - std::string fCatalog; - std::string fName; - std::string fSchema; -}; - - - -/** TableDef represents a table definition. - */ -struct TableDef : public SchemaObject -{ - /** @brief Deserialize from ByteStream */ - EXPORT virtual int unserialize(messageqcpp::ByteStream& bs); - - /** @brief Serialize to ByteStream */ - EXPORT virtual int serialize(messageqcpp::ByteStream& bs); - - - TableDef() : fQualifiedName(0) - {} - - EXPORT TableDef(QualifiedName* name, TableElementList* elements, TableOptionMap* options); - - /** @brief TableDef ctor. - * ctor - */ - TableDef( QualifiedName *name, - ColumnDefList columns, - TableConstraintDefList constraints, int tableWithAutoinc) : - fQualifiedName (name), - fColumns (columns), - fConstraints (constraints) - - - {} - - EXPORT virtual ~TableDef(); - - QualifiedName* fQualifiedName; - - ColumnDefList fColumns; - TableConstraintDefList fConstraints; - - TableOptionMap fOptions; -}; - - - /** @brief Represents the create table statement * * @note It takes possession of the TableDef given to it. @@ -571,12 +472,6 @@ struct CreateTableStatement : public SqlStatement /** @brief Dump to stdout. */ EXPORT virtual std::ostream& put(std::ostream& os) const; - std::string schemaName() const - { - if (!fTableDef || !fTableDef->fQualifiedName) return "UNKNOWN"; - return fTableDef->fQualifiedName->fSchema; - } - TableDef* fTableDef; ///< The table defintion. }; @@ -977,6 +872,11 @@ struct ColumnType EXPORT ColumnType(int type); + /** @brief This constructor is used by Dharma interface to + create a ColumnType object easily */ + + EXPORT ColumnType(int type, int length, int precision, int scale, int compressiontype, const char* autoIncrement, int64_t nextValue, bool withTimezone = false); + virtual ~ColumnType() {} @@ -1000,7 +900,7 @@ struct ColumnType std::string fAutoincrement; - uint64_t fNextvalue; + long long fNextvalue; }; @@ -1102,7 +1002,7 @@ struct ColumnDef : public SchemaObject ColumnDefaultValue *defaultValue, const char * comment=NULL); /** @brief ColumnDef ctor. - * ctor */ + * Convenient ctor for Dharma use */ ColumnDef(const char *name, ColumnType* type, ColumnConstraintList constraints, @@ -1113,8 +1013,6 @@ struct ColumnDef : public SchemaObject fDefaultValue (defaultValue) {} - void convertDecimal(); - /** @brief Never NULL since all Columns must have a type. */ ColumnType* fType; @@ -1322,6 +1220,78 @@ struct TableCheckConstraintDef : public TableConstraintDef +/** TableDef represents a table definition. + */ +struct TableDef : public SchemaObject +{ + /** @brief Deserialize from ByteStream */ + EXPORT virtual int unserialize(messageqcpp::ByteStream& bs); + + /** @brief Serialize to ByteStream */ + EXPORT virtual int serialize(messageqcpp::ByteStream& bs); + + + TableDef() : fQualifiedName(0) + {} + + EXPORT TableDef(QualifiedName* name, TableElementList* elements, TableOptionMap* options); + + /** @brief TableDef ctor. + * Convenient ctor for Dharma use + */ + TableDef( QualifiedName *name, + ColumnDefList columns, + TableConstraintDefList constraints, int tableWithAutoinc) : + fQualifiedName (name), + fColumns (columns), + fConstraints (constraints) + + + {} + + EXPORT virtual ~TableDef(); + + QualifiedName* fQualifiedName; + + ColumnDefList fColumns; + TableConstraintDefList fConstraints; + + TableOptionMap fOptions; +}; + + + +/** @brief Stores catalog, schema, object names. + * + * ddl.y does not yet support catalog. So, expect catalog + * qualified names to fail parsing for the moment. + */ +struct QualifiedName +{ + /** @brief Deserialize from ByteStream */ + EXPORT virtual int unserialize(messageqcpp::ByteStream& bs); + + /** @brief Serialize to ByteStream */ + EXPORT virtual int serialize(messageqcpp::ByteStream& bs); + + + QualifiedName() + {} + + EXPORT QualifiedName(const char* name); + EXPORT QualifiedName(const char* name, const char* schema); + EXPORT QualifiedName(const char* name, const char* schema, const char* catalog); + + virtual ~QualifiedName() + {} + + std::string fCatalog; + std::string fName; + std::string fSchema; +}; + + + /** @brief Represents the alter table command. * * All forms of alter_table_statements are represented as @@ -1348,12 +1318,6 @@ struct AlterTableStatement : public SqlStatement /** @brief Delete members. */ EXPORT virtual ~AlterTableStatement(); - std::string schemaName() const - { - if (!fTableName) return "UNKNOWN"; - return fTableName->fSchema; - } - QualifiedName* fTableName; AlterTableActionList fActions; }; @@ -1464,13 +1428,6 @@ struct DropTableStatement : public SqlStatement { delete fTableName; } - - std::string schemaName() const - { - if (!fTableName) return "UNKNOWN"; - return fTableName->fSchema; - } - QualifiedName *fTableName; bool fCascade; }; @@ -1497,16 +1454,8 @@ struct TruncTableStatement : public SqlStatement { delete fTableName; } - - std::string schemaName() const - { - if (!fTableName) return "UNKNOWN"; - return fTableName->fSchema; - } - QualifiedName *fTableName; }; - /** @brief Represents the mark partition out of service statement * */ diff --git a/dbcon/ddlpackage/dropindex.cpp b/dbcon/ddlpackage/dropindex.cpp index 5d6c2efe..5969d71b 100644 --- a/dbcon/ddlpackage/dropindex.cpp +++ b/dbcon/ddlpackage/dropindex.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dropindex.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dropindex.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/droptable.cpp b/dbcon/ddlpackage/droptable.cpp index 071a236e..18e7a4a0 100644 --- a/dbcon/ddlpackage/droptable.cpp +++ b/dbcon/ddlpackage/droptable.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: droptable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: droptable.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/libddlpackage.vcxproj b/dbcon/ddlpackage/libddlpackage.vcxproj deleted file mode 100644 index f9f6e00a..00000000 --- a/dbcon/ddlpackage/libddlpackage.vcxproj +++ /dev/null @@ -1,236 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {033C6CBA-D984-483F-ADC8-825BE20A699D} - libddlpackage - - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - Compiling DDL scanner files ... - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - Compiling DDL scanner files ... - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dbcon/ddlpackage/libddlpackage.vcxproj.filters b/dbcon/ddlpackage/libddlpackage.vcxproj.filters deleted file mode 100644 index fc56e228..00000000 --- a/dbcon/ddlpackage/libddlpackage.vcxproj.filters +++ /dev/null @@ -1,81 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/dbcon/ddlpackage/serialize.cpp b/dbcon/ddlpackage/serialize.cpp index 395f7e47..d7e1f322 100644 --- a/dbcon/ddlpackage/serialize.cpp +++ b/dbcon/ddlpackage/serialize.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: serialize.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: serialize.cpp 8926 2012-09-25 21:56:32Z zzhu $ * * ***********************************************************************/ @@ -489,7 +489,7 @@ int MarkPartitionStatement::unserialize(ByteStream& bytestream) uint32_t size = 0; bytestream >> size; BRM::LogicalPartition part; - for (uint32_t i = 0; i < size; i++) + for (uint i = 0; i < size; i++) { part.unserialize(bytestream); fPartitions.insert(part); @@ -550,7 +550,7 @@ int DropPartitionStatement::unserialize(ByteStream& bytestream) uint32_t size = 0; bytestream >> size; BRM::LogicalPartition part; - for (uint32_t i = 0; i < size; i++) + for (uint i = 0; i < size; i++) { part.unserialize(bytestream); fPartitions.insert(part); @@ -609,7 +609,7 @@ int RestorePartitionStatement::unserialize(ByteStream& bytestream) uint32_t size = 0; bytestream >> size; BRM::LogicalPartition part; - for (uint32_t i = 0; i < size; i++) + for (uint i = 0; i < size; i++) { part.unserialize(bytestream); fPartitions.insert(part); diff --git a/dbcon/ddlpackage/sqlparser.cpp b/dbcon/ddlpackage/sqlparser.cpp index bbcd4c06..df9c2be0 100644 --- a/dbcon/ddlpackage/sqlparser.cpp +++ b/dbcon/ddlpackage/sqlparser.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: sqlparser.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: sqlparser.cpp 8706 2012-07-13 16:25:50Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/sqlparser.h b/dbcon/ddlpackage/sqlparser.h index 77e19fde..d0507c5b 100644 --- a/dbcon/ddlpackage/sqlparser.h +++ b/dbcon/ddlpackage/sqlparser.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: sqlparser.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: sqlparser.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/sqlstatement.cpp b/dbcon/ddlpackage/sqlstatement.cpp index f77aa9de..a0fd3f3c 100644 --- a/dbcon/ddlpackage/sqlstatement.cpp +++ b/dbcon/ddlpackage/sqlstatement.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: sqlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: sqlstatement.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -28,7 +28,7 @@ namespace ddlpackage { using namespace std; - static uint32_t sessionID = 1; + static u_int32_t sessionID = 1; SqlStatement::SqlStatement() { diff --git a/dbcon/ddlpackage/sqlstatementlist.cpp b/dbcon/ddlpackage/sqlstatementlist.cpp index edff48cb..27a72a4c 100644 --- a/dbcon/ddlpackage/sqlstatementlist.cpp +++ b/dbcon/ddlpackage/sqlstatementlist.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: sqlstatementlist.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: sqlstatementlist.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackage/tabledef.cpp b/dbcon/ddlpackage/tabledef.cpp index d38756da..fb1681dc 100644 --- a/dbcon/ddlpackage/tabledef.cpp +++ b/dbcon/ddlpackage/tabledef.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: tabledef.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: tabledef.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackageproc/Makefile.am b/dbcon/ddlpackageproc/Makefile.am index 2e08bfaf..c0cbd037 100644 --- a/dbcon/ddlpackageproc/Makefile.am +++ b/dbcon/ddlpackageproc/Makefile.am @@ -14,6 +14,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) diff --git a/dbcon/ddlpackageproc/Makefile.in b/dbcon/ddlpackageproc/Makefile.in index 1f33e520..61187065 100644 --- a/dbcon/ddlpackageproc/Makefile.in +++ b/dbcon/ddlpackageproc/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -41,9 +60,8 @@ subdir = dbcon/ddlpackageproc DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -141,9 +159,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -185,7 +200,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -199,11 +213,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -214,23 +223,6 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) diff --git a/dbcon/ddlpackageproc/altertableprocessor.cpp b/dbcon/ddlpackageproc/altertableprocessor.cpp index b38d0b24..97107ca1 100644 --- a/dbcon/ddlpackageproc/altertableprocessor.cpp +++ b/dbcon/ddlpackageproc/altertableprocessor.cpp @@ -15,50 +15,37 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: altertableprocessor.cpp 9744 2013-08-07 03:32:19Z bwilkinson $ +// $Id: altertableprocessor.cpp 9178 2013-01-04 20:15:58Z pleblanc $ /** @file */ -#include -#include -#include -#include -using namespace std; - -#include - +#define ALTERTABLEPROC_DLLEXPORT #include "altertableprocessor.h" - +#undef ALTERTABLEPROC_DLLEXPORT +#include "sessionmanager.h" #include "brm.h" -using namespace BRM; +#include +using namespace boost::algorithm; -#include "calpontsystemcatalog.h" +#include "messagelog.h" +#include "sqllogger.h" +#include "cacheutils.h" +using namespace cacheutils; +#include +#include +using namespace std; using namespace execplan; - -#include "ddlpkg.h" using namespace ddlpackage; - -#include "sqllogger.h" -#include "messagelog.h" using namespace logging; - +using namespace BRM; #include "we_messages.h" #include "we_ddlcommandclient.h" using namespace WriteEngine; - #include "oamcache.h" using namespace oam; - #include "bytestream.h" using namespace messageqcpp; -#include "cacheutils.h" -using namespace cacheutils; - -#include "IDBDataFile.h" -#include "IDBPolicy.h" -using namespace idbdatafile; - //TODO: this should be in a common header somewhere struct extentInfo { @@ -71,6 +58,10 @@ struct extentInfo namespace { +const int MAX_INT = numeric_limits::max(); +const short MAX_TINYINT = numeric_limits::max(); //127; +const short MAX_SMALLINT = numeric_limits::max(); //32767; +const long long MAX_BIGINT = numeric_limits::max();//9223372036854775807LL bool typesAreSame(const CalpontSystemCatalog::ColType& colType, const ColumnType& newType) { @@ -82,13 +73,8 @@ bool typesAreSame(const CalpontSystemCatalog::ColType& colType, const ColumnType case (CalpontSystemCatalog::TINYINT): if (newType.fType == DDL_TINYINT && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; - //@Bug 5443 Not allow user change data type. //Not sure this is possible... - //if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && - // colType.scale == newType.fScale) return true; - break; - case (CalpontSystemCatalog::UTINYINT): - if (newType.fType == DDL_UNSIGNED_TINYINT && colType.precision == newType.fPrecision && + if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; break; case (CalpontSystemCatalog::CHAR): @@ -97,68 +83,43 @@ bool typesAreSame(const CalpontSystemCatalog::ColType& colType, const ColumnType case (CalpontSystemCatalog::SMALLINT): if (newType.fType == DDL_SMALLINT && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; - //if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && - // colType.scale == newType.fScale) return true; - break; - case (CalpontSystemCatalog::USMALLINT): - if (newType.fType == DDL_UNSIGNED_SMALLINT && colType.precision == newType.fPrecision && + if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; break; + // Don't think there can be such a type in syscat right now... case (CalpontSystemCatalog::DECIMAL): - if ((newType.fType == DDL_DECIMAL || newType.fType == DDL_NUMERIC) && - colType.precision == newType.fPrecision && colType.scale == newType.fScale) - return true; + if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && + colType.scale == newType.fScale) return true; break; - case (CalpontSystemCatalog::UDECIMAL): - if ((newType.fType == DDL_UNSIGNED_DECIMAL || newType.fType == DDL_UNSIGNED_NUMERIC) && - colType.precision == newType.fPrecision && colType.scale == newType.fScale) - return true; - break; // Don't think there can be such a type in syscat right now... case (CalpontSystemCatalog::MEDINT): if (newType.fType == DDL_MEDINT && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; - //@Bug 5443 Not allow user change data type. - //if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && - // colType.scale == newType.fScale) return true; + if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && + colType.scale == newType.fScale) return true; break; case (CalpontSystemCatalog::INT): - if (newType.fType == DDL_INT && colType.precision == newType.fPrecision && + if (newType.fType == DDL_INTEGER && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; - //if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && - // colType.scale == newType.fScale) return true; - break; - case (CalpontSystemCatalog::UINT): - if (newType.fType == DDL_UNSIGNED_INT && colType.precision == newType.fPrecision && + if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; break; case (CalpontSystemCatalog::FLOAT): if (newType.fType == DDL_FLOAT) return true; break; - case (CalpontSystemCatalog::UFLOAT): - if (newType.fType == DDL_UNSIGNED_FLOAT) return true; - break; case (CalpontSystemCatalog::DATE): if (newType.fType == DDL_DATE) return true; break; case (CalpontSystemCatalog::BIGINT): if (newType.fType == DDL_BIGINT && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; - //@Bug 5443 Not allow user change data type. //decimal is mapped to bigint in syscat - //if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && - // colType.scale == newType.fScale) return true; - break; - case (CalpontSystemCatalog::UBIGINT): - if (newType.fType == DDL_UNSIGNED_BIGINT && colType.precision == newType.fPrecision && + if (newType.fType == DDL_DECIMAL && colType.precision == newType.fPrecision && colType.scale == newType.fScale) return true; break; case (CalpontSystemCatalog::DOUBLE): if (newType.fType == DDL_DOUBLE) return true; break; - case (CalpontSystemCatalog::UDOUBLE): - if (newType.fType == DDL_UNSIGNED_DOUBLE) return true; - break; case (CalpontSystemCatalog::DATETIME): if (newType.fType == DDL_DATETIME) return true; break; @@ -212,7 +173,7 @@ AlterTableProcessor::DDLResult AlterTableProcessor::processPackage(ddlpackage::A uint64_t tableLockId = 0; DETAIL_INFO(alterTableStmt); int rc = 0; - rc = fDbrm->isReadWrite(); + rc = fDbrm.isReadWrite(); if (rc != 0 ) { logging::Message::Args args; @@ -225,40 +186,12 @@ AlterTableProcessor::DDLResult AlterTableProcessor::processPackage(ddlpackage::A return result; } //@Bug 4538. Log the sql statement before grabbing tablelock - string stmt = alterTableStmt.fSql + "|" + (alterTableStmt.fTableName)->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, alterTableStmt.fSessionID, txnID.id); + SQLLogger logger(alterTableStmt.fSql, fDDLLoggingId, alterTableStmt.fSessionID, txnID.id); VERBOSE_INFO("Getting current txnID"); OamCache * oamcache = OamCache::makeOamCache(); std::vector moduleIds = oamcache->getModuleIds(); - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - logging::Message::Args args; - logging::Message message(9); - args.add(ex.what()); - message.format(args); - result.result = ALTER_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - catch ( ... ) - { - logging::Message::Args args; - logging::Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = ALTER_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - + uint64_t uniqueId = fDbrm.getUnique64(); fWEClient->addQueue(uniqueId); try { @@ -272,20 +205,20 @@ AlterTableProcessor::DDLResult AlterTableProcessor::processPackage(ddlpackage::A execplan::CalpontSystemCatalog::ROPair roPair; roPair = systemCatalogPtr->tableRID(tableName); - uint32_t processID = ::getpid(); + u_int32_t processID = ::getpid(); int32_t txnid = txnID.id; int32_t sessionId = alterTableStmt.fSessionID; std::string processName("DDLProc"); int i = 0; - std::vector pms; + std::vector pms; for (unsigned i=0; i < moduleIds.size(); i++) { - pms.push_back((uint32_t)moduleIds[i]); + pms.push_back((uint)moduleIds[i]); } try { - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); } catch (std::exception&) { @@ -322,7 +255,7 @@ AlterTableProcessor::DDLResult AlterTableProcessor::processPackage(ddlpackage::A txnid = txnID.id; sessionId = alterTableStmt.fSessionID;; processName = "DDLProc"; - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); } catch (std::exception&) { @@ -457,9 +390,11 @@ AlterTableProcessor::DDLResult AlterTableProcessor::processPackage(ddlpackage::A { rollBackAlter("encountered unknown exception. ", txnID, alterTableStmt.fSessionID, result, uniqueId); } + //release table lock try { - (void)fDbrm->releaseTableLock(tableLockId); + bool lockReleased = true; + lockReleased = fDbrm.releaseTableLock(tableLockId); //cout << "table lock " << tableLockId << " is released" << endl; } catch (std::exception&) @@ -483,7 +418,7 @@ AlterTableProcessor::DDLResult AlterTableProcessor::processPackage(ddlpackage::A } void AlterTableProcessor::rollBackAlter(const string& error, BRM::TxnID txnID, - int sessionId, DDLResult& result, uint64_t uniqueId) + int sessionId, DDLResult& result, u_int64_t uniqueId) { DETAIL_INFO("Rolling back transaction"); cerr << "AltertableProcessor::processPackage: " << error << endl; @@ -502,7 +437,7 @@ void AlterTableProcessor::rollBackAlter(const string& error, BRM::TxnID txnID, result.message = message; } -void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, +void AlterTableProcessor::addColumn (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::ColumnDef* columnDefPtr, ddlpackage::QualifiedName& inTableName, const uint64_t uniqueId) { std::string err("AlterTableProcessor::addColumn "); @@ -513,9 +448,10 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem ByteStream::byte tmp8; int rc = 0; std::string errorMsg; - uint16_t dbRoot; - BRM::OID_t sysOid = 1021; + u_int16_t dbRoot; + BRM::OID_t sysOid = 1001; bool isDict = false; + //@Bug 4111. Check whether the column exists in calpont systable boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); @@ -548,15 +484,15 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem throw std::runtime_error(err); } - + if ((columnDefPtr->fType->fType == CalpontSystemCatalog::CHAR && columnDefPtr->fType->fLength > 8) || (columnDefPtr->fType->fType == CalpontSystemCatalog::VARCHAR && columnDefPtr->fType->fLength > 7) || (columnDefPtr->fType->fType == CalpontSystemCatalog::VARBINARY && columnDefPtr->fType->fLength > 7)) { isDict = true; } - //Find out where syscolumn are - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); + //Find out where systables are + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) throw std::runtime_error("Error while calling getSysCatDBRoot "); @@ -660,12 +596,12 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem else bs << (uint32_t) 0; - bs << (uint8_t) alterFlag; + bs << (u_int8_t) alterFlag; bs << (uint32_t) totalColumns; columnDefPtr->serialize(bs); //send to WES to process try { - fWEClient->write(bs, (uint32_t)pmNum); + fWEClient->write(bs, (uint)pmNum); while (1) { bsIn.reset(new ByteStream()); @@ -705,13 +641,6 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem if ((columnDefPtr->fType->fAutoincrement).compare("y") == 0) { //update systable autoincrement column - sysOid = 1001; - //Find out where systable is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - throw std::runtime_error("Error while calling getSysCatDBRoot "); - - pmNum = (*dbRootPMMap)[dbRoot]; bs.restart(); bs << (ByteStream::byte) WE_SVR_UPDATE_SYSTABLE_AUTO; bs << uniqueId; @@ -723,7 +652,7 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem //send to WES to process try { - fWEClient->write(bs, (uint32_t)pmNum); + fWEClient->write(bs, (uint)pmNum); while (1) { bsIn.reset(new ByteStream()); @@ -759,8 +688,7 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem throw std::runtime_error(errorMsg); //start a sequence in controller - fDbrm->startAISequence(fStartingColOID, columnDefPtr->fType->fNextvalue, columnDefPtr->fType->fLength, - convertDataType(columnDefPtr->fType->fType)); + fDbrm.startAISequence(fStartingColOID, columnDefPtr->fType->fNextvalue, columnDefPtr->fType->fLength); } //@Bug 4176. save oids to a log file for cleanup after fail over. @@ -794,9 +722,9 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem //If there is atleast one existing column then use that as a reference to initialize the new column rows. //get dbroot information - //fDbrm->getStartExtent((*column_iterator).oid, dbroot, partitionNum, true); + //fDbrm.getStartExtent((*column_iterator).oid, dbroot, partitionNum, true); - rc = fDbrm->getOutOfServicePartitions(column_iterator->oid, outOfSerPar); + rc = fDbrm.getOutOfServicePartitions(column_iterator->oid, outOfSerPar); if (rc != 0) { @@ -810,13 +738,15 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem int dataType1; dataType1 = convertDataType(columnDefPtr->fType->fType); - if (dataType1 == CalpontSystemCatalog::DECIMAL || - dataType1 == CalpontSystemCatalog::UDECIMAL) + if (dataType1 == CalpontSystemCatalog::DECIMAL) //Bug 4107 { - columnDefPtr->convertDecimal(); + convertDecimal(columnDefPtr); } - CalpontSystemCatalog::ColDataType dataType = convertDataType(columnDefPtr->fType->fType); + WriteEngine::ColDataType dataType = + static_cast(convertDataType(columnDefPtr->fType->fType)); + WriteEngine::ColDataType refColDataType = + static_cast(convertDataType(column_iterator->colType.colDataType)); if ((columnDefPtr->fType->fAutoincrement).compare("y") == 0) { @@ -836,8 +766,6 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem bs << (ByteStream::byte) dataType; bs << (ByteStream::byte) autoincrement; bs << (uint32_t) columnDefPtr->fType->fLength; - bs << (uint32_t) columnDefPtr->fType->fScale; - bs << (uint32_t) columnDefPtr->fType->fPrecision; std::string tmpStr(""); if (columnDefPtr->fDefaultValue) { @@ -848,93 +776,94 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem bs << (ByteStream::byte) columnDefPtr->fType->fCompressiontype; //ref column info bs << (uint32_t) column_iterator->oid; - bs << (ByteStream::byte) column_iterator->colType.colDataType; + bs << (ByteStream::byte) refColDataType; bs << (uint32_t) column_iterator->colType.colWidth; bs << (ByteStream::byte) column_iterator->colType.compressionType; //cout << "sending command fillcolumn " << endl; - uint32_t msgRecived = 0; - fWEClient->write_to_all(bs); - bsIn.reset(new ByteStream()); - while (1) - { - if (msgRecived == fPMCount) - break; - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - rc = NETWORK_ERROR; - break; - } - else { - *bsIn >> tmp8; - *bsIn >> errorMsg; - rc = tmp8; - //cout << "Got error code from WES " << rc << endl; - if (rc != 0) - break; - else - msgRecived++; - } - } - if (rc != 0) //delete the newly created files before erroring out - { - bs.restart(); - bs << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; - bs << uniqueId; - bs << (uint32_t) oidList.size(); - for (uint32_t i=0; i < oidList.size(); i++) - { - bs << (uint32_t) oidList[i]; - } - - uint32_t msgRecived = 0; - try { - fWEClient->write_to_all(bs); - bsIn.reset(new ByteStream()); - ByteStream::byte tmp8; - while (1) - { - if (msgRecived == fWEClient->getPmCount()) - break; - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server while dropping column files"; - break; - } - else { - *bsIn >> tmp8; - rc = tmp8; - if (rc != 0) { - *bsIn >> errorMsg; - break; - } - else - msgRecived++; - } - } - } - catch (runtime_error& ex) //write error - { - rc = NETWORK_ERROR; - errorMsg = ex.what(); - } - catch (...) - { - rc = NETWORK_ERROR; - errorMsg = " Unknown exception caught while dropping column files."; - } - - if ( rc == 0 ) { - fWEClient->removeQueue(uniqueId); - deleteLogFile(DROPTABLE_LOG, ropair.objnum, uniqueId); - fWEClient->addQueue(uniqueId); - } - throw std::runtime_error(errorMsg); - } - - //Update nextVal + uint msgRecived = 0; + fWEClient->write_to_all(bs); + bsIn.reset(new ByteStream()); + while (1) + { + if (msgRecived == fPMCount) + break; + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + rc = NETWORK_ERROR; + break; + } + else { + *bsIn >> tmp8; + *bsIn >> errorMsg; + rc = tmp8; + //cout << "Got error code from WES " << rc << endl; + if (rc != 0) + break; + else + msgRecived++; + } + } + if (rc != 0) //delete the newly created files before erroring out + { + bs.restart(); + bs << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; + bs << uniqueId; + bs << (uint32_t) oidList.size(); + for (uint i=0; i < oidList.size(); i++) + { + bs << (uint32_t) oidList[i]; + } + + uint msgRecived = 0; + try { + fWEClient->write_to_all(bs); + bsIn.reset(new ByteStream()); + ByteStream::byte tmp8; + while (1) + { + if (msgRecived == fWEClient->getPmCount()) + break; + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + rc = NETWORK_ERROR; + errorMsg = "Lost connection to Write Engine Server while dropping column files"; + break; + } + else { + *bsIn >> tmp8; + rc = tmp8; + if (rc != 0) { + *bsIn >> errorMsg; + break; + } + else + msgRecived++; + } + } + } + catch (runtime_error& ex) //write error + { + rc = NETWORK_ERROR; + errorMsg = ex.what(); + } + catch (...) + { + rc = NETWORK_ERROR; + errorMsg = " Unknown exception caught while dropping column files."; + } + + if ( rc == 0 ) { + fWEClient->removeQueue(uniqueId); + deleteLogFile(DROPTABLE_LOG, ropair.objnum, uniqueId); + fWEClient->addQueue(uniqueId); + } + + throw std::runtime_error(errorMsg); + } + + //Update nextVal break; } //Update nextVal @@ -965,11 +894,7 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem if (validNextVal) { WE_DDLCommandClient ddlClient; - uint8_t rc = 0; - if (idbdatafile::IDBPolicy::useHdfs()) - rc = ddlClient.UpdateSyscolumnNextval(fStartingColOID, nextValInController,txnID); - else - rc = ddlClient.UpdateSyscolumnNextval(fStartingColOID, nextValInController,sessionID); + uint8_t rc = ddlClient.UpdateSyscolumnNextval(fStartingColOID, nextValInController,sessionID); aDbrm.releaseAILock(fStartingColOID); if (rc!=0) throw std::runtime_error("Update SYSCAT next value failed"); @@ -983,9 +908,8 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem } std::vector oidList; oidList.push_back(fStartingColOID); - if (outOfSerPar.size() > 0) - rc = fDbrm->markPartitionForDeletion(oidList, outOfSerPar, errorMsg); + rc = fDbrm.markPartitionForDeletion(oidList, outOfSerPar, errorMsg); if (rc != 0) { @@ -998,7 +922,7 @@ void AlterTableProcessor::addColumn (uint32_t sessionID, execplan::CalpontSystem fWEClient->addQueue(uniqueId); } -void AlterTableProcessor::dropColumn (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, +void AlterTableProcessor::dropColumn (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropColumn& ataDropColumn, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId) { // 1. Get the OIDs for the column @@ -1024,13 +948,13 @@ void AlterTableProcessor::dropColumn (uint32_t sessionID, execplan::CalpontSyste systemCatalogPtr->identity(CalpontSystemCatalog::EC); std::string err; execplan::CalpontSystemCatalog::ROPair roPair; - CalpontSystemCatalog::OID oid; + CalpontSystemCatalog::OID oid; CalpontSystemCatalog::ColType colType; try { roPair = systemCatalogPtr->tableRID( tableName ); - - oid = systemCatalogPtr->lookupOID(tableColName); - colType = systemCatalogPtr->colType(oid); + + oid = systemCatalogPtr->lookupOID(tableColName); + colType = systemCatalogPtr->colType(oid); } catch (std::exception& ex) { @@ -1041,17 +965,17 @@ void AlterTableProcessor::dropColumn (uint32_t sessionID, execplan::CalpontSyste bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSCOLUMN_ROW; bytestream << uniqueId; bytestream << sessionID; - bytestream << (uint32_t)txnID; + bytestream << (u_int32_t)txnID; bytestream << fTableName.fSchema; bytestream << fTableName.fName; bytestream << ataDropColumn.fColumnName; std::string errorMsg; - uint16_t dbRoot; - BRM::OID_t sysOid = 1021; + u_int16_t dbRoot; + BRM::OID_t sysOid = 1001; ByteStream::byte rc = 0; - //Find out where syscolumn is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); + //Find out where systable is + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) throw std::runtime_error("Error while calling getSysCatDBRoot "); @@ -1063,7 +987,7 @@ void AlterTableProcessor::dropColumn (uint32_t sessionID, execplan::CalpontSyste pmNum = (*dbRootPMMap)[dbRoot]; try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DDL_DEBUG cout << "Alter table drop column sending WE_SVR_DELETE_SYSCOLUMN_ROW to pm " << pmNum << endl; #endif @@ -1107,24 +1031,17 @@ cout << "Alter table drop column got unknown exception" << endl; //Update SYSTABLE if (colType.autoincrement) { - sysOid = 1001; - //Find out where systable is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - throw std::runtime_error("Error while calling getSysCatDBRoot "); - - pmNum = (*dbRootPMMap)[dbRoot]; bytestream.restart(); bytestream << (ByteStream::byte)WE_SVR_UPDATE_SYSTABLE_AUTO; bytestream << uniqueId; bytestream << sessionID; - bytestream << (uint32_t)txnID; + bytestream << (u_int32_t)txnID; bytestream << fTableName.fSchema; bytestream << fTableName.fName; - bytestream << (uint32_t) 0; //autoincrement off + bytestream << (u_int32_t) 0; //autoincrement off try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DDL_DEBUG cout << "Alter table drop column sending WE_SVR_UPDATE_SYSTABLE_AUTO to pm " << pmNum << endl; #endif @@ -1171,20 +1088,12 @@ cout << "Alter table drop column got unknown exception" << endl; bytestream << (ByteStream::byte)WE_SVR_UPDATE_SYSCOLUMN_COLPOS; bytestream << uniqueId; bytestream << sessionID; - bytestream << (uint32_t)txnID; + bytestream << (u_int32_t)txnID; bytestream << fTableName.fSchema; bytestream << fTableName.fName; - bytestream << (uint32_t) colPos; - sysOid = 1021; - //Find out where syscolumn is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - throw std::runtime_error("Error while calling getSysCatDBRoot "); - - pmNum = (*dbRootPMMap)[dbRoot]; - + bytestream << (u_int32_t) colPos; try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DDL_DEBUG cout << "Alter table drop column sending WE_SVR_UPDATE_SYSTABLE_AUTO to pm " << pmNum << endl; #endif @@ -1230,13 +1139,8 @@ cout << "Alter table drop column got unknown exception" << endl; aTxnID.id= txnID; aTxnID.valid= true; commitTransaction(uniqueId, aTxnID); - - // Bug 4208 Drop the PrimProcFDCache before droping the column files - // FOr Windows, this ensures (most likely) that the column files have - // no open handles to hinder the deletion of the files. - rc = cacheutils::dropPrimProcFdCache(); - - VERBOSE_INFO("Removing column files"); + + VERBOSE_INFO("Removing column files"); //Drop files std::vector oidList; bytestream.restart(); @@ -1257,7 +1161,7 @@ cout << "Alter table drop column got unknown exception" << endl; oidList.push_back(oid); } //Save the oids to a file - uint32_t msgRecived = 0; + uint msgRecived = 0; bool fileDropped = true; try { createWriteDropLogFile( roPair.objnum, uniqueId, oidList ); @@ -1313,17 +1217,17 @@ cout << "create table got unknown exception" << endl; //Flush primProc cache rc = cacheutils::flushOIDsFromCache( oidList ); //Delete extents from extent map - rc = fDbrm->deleteOIDs(oidList); + rc = fDbrm.deleteOIDs(oidList); if (fileDropped) - { - fWEClient->removeQueue(uniqueId); - deleteLogFile(DROPTABLE_LOG, roPair.objnum, uniqueId); - fWEClient->addQueue(uniqueId); - } + { + fWEClient->removeQueue(uniqueId); + deleteLogFile(DROPTABLE_LOG, roPair.objnum, uniqueId); + fWEClient->addQueue(uniqueId); + } } -void AlterTableProcessor::dropColumns (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, +void AlterTableProcessor::dropColumns (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropColumns& ataDropColumns, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId) { SUMMARY_INFO("AlterTableProcessor::dropColumns"); @@ -1361,7 +1265,7 @@ void AlterTableProcessor::dropColumns (uint32_t sessionID, execplan::CalpontSyst } } -void AlterTableProcessor::addTableConstraint (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaAddTableConstraint& ataAddTableConstraint, ddlpackage::QualifiedName& fTableName) +void AlterTableProcessor::addTableConstraint (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaAddTableConstraint& ataAddTableConstraint, ddlpackage::QualifiedName& fTableName) { /*TODO: Check if existing row satisfy the constraint. If not, the constraint will not be added. */ @@ -1389,7 +1293,7 @@ void AlterTableProcessor::addTableConstraint (uint32_t sessionID, execplan::Calp } } -void AlterTableProcessor::setColumnDefault (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, +void AlterTableProcessor::setColumnDefault (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaSetColumnDefault& ataSetColumnDefault, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId) { SUMMARY_INFO("AlterTableProcessor::setColumnDefault"); @@ -1399,11 +1303,11 @@ void AlterTableProcessor::setColumnDefault (uint32_t sessionID, execplan::Calpon SUMMARY_INFO("AlterTableProcessor::setColumnDefault"); ByteStream bs; std::string errorMsg; - uint16_t dbRoot; - BRM::OID_t sysOid = 1021; + u_int16_t dbRoot; + BRM::OID_t sysOid = 1001; ByteStream::byte rc = 0; - //Find out where syscolumns - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); + //Find out where systable is + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) throw std::runtime_error("Error while calling getSysCatDBRoot"); @@ -1434,7 +1338,7 @@ void AlterTableProcessor::setColumnDefault (uint32_t sessionID, execplan::Calpon //send to WES to process try { - fWEClient->write(bs, (uint32_t)pmNum); + fWEClient->write(bs, (uint)pmNum); while (1) { bsIn.reset(new ByteStream()); @@ -1468,7 +1372,7 @@ void AlterTableProcessor::setColumnDefault (uint32_t sessionID, execplan::Calpon if (rc != 0) throw std::runtime_error(errorMsg); } -void AlterTableProcessor::dropColumnDefault (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, +void AlterTableProcessor::dropColumnDefault (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropColumnDefault& ataDropColumnDefault, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId) { SUMMARY_INFO("AlterTableProcessor::setColumnDefault"); @@ -1478,11 +1382,11 @@ void AlterTableProcessor::dropColumnDefault (uint32_t sessionID, execplan::Calpo SUMMARY_INFO("AlterTableProcessor::setColumnDefault"); ByteStream bs; std::string errorMsg; - uint16_t dbRoot; - BRM::OID_t sysOid = 1021; + u_int16_t dbRoot; + BRM::OID_t sysOid = 1001; ByteStream::byte rc = 0; - //Find out where syscolumn is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); + //Find out where systable is + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) throw std::runtime_error("Error while calling getSysCatDBRoot"); @@ -1510,7 +1414,7 @@ void AlterTableProcessor::dropColumnDefault (uint32_t sessionID, execplan::Calpo //send to WES to process try { - fWEClient->write(bs, (uint32_t)pmNum); + fWEClient->write(bs, (uint)pmNum); while (1) { bsIn.reset(new ByteStream()); @@ -1546,7 +1450,7 @@ void AlterTableProcessor::dropColumnDefault (uint32_t sessionID, execplan::Calpo } #if 0 -void AlterTableProcessor::dropTableConstraint (uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropTableConstraint& ataDropTableConstraint, ddlpackage::QualifiedName& fTableName) +void AlterTableProcessor::dropTableConstraint (u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropTableConstraint& ataDropTableConstraint, ddlpackage::QualifiedName& fTableName) { /*Steps tp drop table constraint 1. Delete the ConstraintName from SYSCONSTRAINT @@ -1655,20 +1559,20 @@ void AlterTableProcessor::renameTable (uint32_t sessionID, execplan::CalpontSyst throw std::runtime_error("The new tablename is already in use."); ByteStream bytestream; - bytestream << (ByteStream::byte)WE_SVR_UPDATE_SYSTABLE_TABLENAME; + bytestream << (ByteStream::byte)WE_SVR_UPDATE_SYSTABLES_TABLENAME; bytestream << uniqueId; bytestream << sessionID; - bytestream << (uint32_t)txnID; + bytestream << (u_int32_t)txnID; bytestream << fTableName.fSchema; bytestream << fTableName.fName; bytestream << ataRenameTable.fQualifiedName->fName; std::string errorMsg; - uint16_t dbRoot; + u_int16_t dbRoot; BRM::OID_t sysOid = 1001; ByteStream::byte rc = 0; //Find out where systable is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) throw std::runtime_error("Error while calling getSysCatDBRoot"); @@ -1680,7 +1584,7 @@ void AlterTableProcessor::renameTable (uint32_t sessionID, execplan::CalpontSyst pmNum = (*dbRootPMMap)[dbRoot]; try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DDL_DEBUG cout << "Rename table sending WE_SVR_UPDATE_SYSTABLE_TABLENAME to pm " << pmNum << endl; #endif @@ -1718,65 +1622,6 @@ cout << "create table got unknown exception" << endl; #endif } - if (rc != 0) - throw std::runtime_error(errorMsg); - - //update SYSCOLUMN - bytestream.restart(); - bytestream << (ByteStream::byte)WE_SVR_UPDATE_SYSCOLUMN_TABLENAME; - bytestream << uniqueId; - bytestream << sessionID; - bytestream << (uint32_t)txnID; - bytestream << fTableName.fSchema; - bytestream << fTableName.fName; - bytestream << ataRenameTable.fQualifiedName->fName; - sysOid = 1021; - //Find out where syscolumn is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - throw std::runtime_error("Error while calling getSysCatDBRoot"); - - pmNum = (*dbRootPMMap)[dbRoot]; - try - { - fWEClient->write(bytestream, (unsigned)pmNum); -#ifdef IDB_DDL_DEBUG -cout << "Rename table sending WE_SVR_UPDATE_SYSCOLUMN_TABLENAME to pm " << pmNum << endl; -#endif - while (1) - { - bsIn.reset(new ByteStream()); - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; - break; - } - else { - *bsIn >> rc; - *bsIn >> errorMsg; - break; - } - } - } - catch (runtime_error& ex) //write error - { -#ifdef IDB_DDL_DEBUG -cout << "create table got exception" << ex.what() << endl; -#endif - rc = NETWORK_ERROR; - errorMsg = ex.what(); - } - catch (...) - { - rc = NETWORK_ERROR; - errorMsg = " Unknown exception caught while updating SYSTABLE."; -#ifdef IDB_DDL_DEBUG -cout << "create table got unknown exception" << endl; -#endif - } - if (rc != 0) throw std::runtime_error(errorMsg); } @@ -1795,11 +1640,11 @@ void AlterTableProcessor::renameColumn(uint32_t sessionID, execplan::CalpontSyst ByteStream bs; std::string errorMsg; - uint16_t dbRoot; + u_int16_t dbRoot; BRM::OID_t sysOid = 1001; ByteStream::byte rc = 0; //Find out where systable is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) throw std::runtime_error("Error while calling getSysCatDBRoot"); @@ -1856,7 +1701,6 @@ void AlterTableProcessor::renameColumn(uint32_t sessionID, execplan::CalpontSyst throw std::runtime_error(oss.str().c_str()); } //Check whether SYSTABLE needs to be updated - CalpontSystemCatalog::TableInfo tblInfo = systemCatalogPtr->tableInfo(tableName); if (((tblInfo.tablewithautoincr == 1) && (colType.autoincrement) && (ataRenameColumn.fNewType->fAutoincrement.compare("n") == 0)) || ((tblInfo.tablewithautoincr == 0) && (ataRenameColumn.fNewType->fAutoincrement.compare("y") == 0))) @@ -1876,7 +1720,7 @@ void AlterTableProcessor::renameColumn(uint32_t sessionID, execplan::CalpontSyst //send to WES to process try { - fWEClient->write(bs, (uint32_t)pmNum); + fWEClient->write(bs, (uint)pmNum); while (1) { bsIn.reset(new ByteStream()); @@ -1911,20 +1755,17 @@ void AlterTableProcessor::renameColumn(uint32_t sessionID, execplan::CalpontSyst throw std::runtime_error(errorMsg); //change a sequence in controller - if ((!(tblInfo.tablewithautoincr == 1) || (colType.autoincrement)) && (ataRenameColumn.fNewType->fAutoincrement.compare("y") == 0)) + if (ataRenameColumn.fNewType->fAutoincrement.compare("y") == 0) { - fDbrm->startAISequence(ropair.objnum, ataRenameColumn.fNewType->fNextvalue, ataRenameColumn.fNewType->fLength, - convertDataType(ataRenameColumn.fNewType->fType)); - //Reset it in case there is a sequence already - fDbrm->resetAISequence(ropair.objnum, ataRenameColumn.fNewType->fNextvalue); + fDbrm.startAISequence(ropair.objnum, ataRenameColumn.fNewType->fNextvalue, ataRenameColumn.fNewType->fLength); + //Reset it incase there is a sequence already + fDbrm.resetAISequence(ropair.objnum, ataRenameColumn.fNewType->fNextvalue); } } - else if ((tblInfo.tablewithautoincr == 1) && (colType.autoincrement) && (ataRenameColumn.fNewType->fAutoincrement.compare("y") == 0)) - {} else { - fDbrm->resetAISequence(ropair.objnum, 0); + fDbrm.resetAISequence(ropair.objnum, 0); } //Update SYSCOLUMN @@ -1938,18 +1779,12 @@ void AlterTableProcessor::renameColumn(uint32_t sessionID, execplan::CalpontSyst bs << ataRenameColumn.fName; bs << ataRenameColumn.fNewName; bs << ataRenameColumn.fNewType->fAutoincrement; - //@Bug 5913. for autoincrement column, find the next value from SYSCOLUMN - long long nextVal = ataRenameColumn.fNewType->fNextvalue; - if ((tblInfo.tablewithautoincr == 1) && (colType.autoincrement) && (ataRenameColumn.fNewType->fAutoincrement.compare("y") == 0)) - nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); - - - bs << (uint64_t) nextVal; + bs << (uint64_t) ataRenameColumn.fNewType->fNextvalue; uint32_t nullable = 1; string defaultValue(""); if (ataRenameColumn.fConstraints.size() > 0) { - for (uint32_t j=0; j < ataRenameColumn.fConstraints.size(); j++) + for (uint j=0; j < ataRenameColumn.fConstraints.size(); j++) { if (ataRenameColumn.fConstraints[j]->fConstraintType == DDL_NOT_NULL) { @@ -1963,16 +1798,10 @@ void AlterTableProcessor::renameColumn(uint32_t sessionID, execplan::CalpontSyst defaultValue = ataRenameColumn.fDefaultValue->fValue; bs << defaultValue; - sysOid = 1021; - //Find out where syscolumn is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - throw std::runtime_error("Error while calling getSysCatDBRoot"); - - pmNum = (*dbRootPMMap)[dbRoot]; + //send to WES to process try { - fWEClient->write(bs, (uint32_t)pmNum); + fWEClient->write(bs, (uint)pmNum); while (1) { bsIn.reset(new ByteStream()); diff --git a/dbcon/ddlpackageproc/altertableprocessor.h b/dbcon/ddlpackageproc/altertableprocessor.h index 434c76f4..d5f86c34 100644 --- a/dbcon/ddlpackageproc/altertableprocessor.h +++ b/dbcon/ddlpackageproc/altertableprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: altertableprocessor.h 9303 2013-03-07 16:07:12Z chao $ + * $Id: altertableprocessor.h 9058 2012-11-07 15:35:08Z chao $ * * ***********************************************************************/ @@ -26,7 +26,7 @@ #include "ddlpackageprocessor.h" -#if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(ALTERTABLEPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -41,7 +41,6 @@ namespace ddlpackageprocessor class AlterTableProcessor : public DDLPackageProcessor { public: - AlterTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} /** @brief process an alter table statement * * @param alterTableStmt the AlterTableStatement @@ -53,7 +52,7 @@ namespace ddlpackageprocessor * @param addColumn the AtaAddColumn object * @param fTableName the QualifiedName of the table */ - EXPORT void addColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void addColumn(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::ColumnDef* columnDefPtr, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); @@ -63,7 +62,7 @@ namespace ddlpackageprocessor * @param ataDropColumn the AtaDropColumn object * @param fTableName the QualifiedName for the table */ - EXPORT void dropColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void dropColumn(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropColumn& ataDropColumn, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); @@ -73,7 +72,7 @@ namespace ddlpackageprocessor * @param ataDropColumns the AtaDropColumn object * @param fTableName the QualifiedName for the table */ - EXPORT void dropColumns(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void dropColumns(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropColumns& ataDropColumns, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId ); @@ -83,7 +82,7 @@ namespace ddlpackageprocessor * @param ataAddTableConstraint the AtaDropColumn object * @param fTableName the QualifiedName for the table */ - EXPORT void addTableConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void addTableConstraint(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaAddTableConstraint& ataAddTableConstraint, ddlpackage::QualifiedName& fTableName ); @@ -93,7 +92,7 @@ namespace ddlpackageprocessor * @param ataSetColumnDefault the AtaSetColumnDefault object * @param fTableName the QualifiedName for the table */ - EXPORT void setColumnDefault(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void setColumnDefault(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaSetColumnDefault& ataSetColumnDefault, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId ); @@ -103,7 +102,7 @@ namespace ddlpackageprocessor * @param ataDropColumnDefault the AtaDropColumnDefault object * @param fTableName the QualifiedName for the table */ - EXPORT void dropColumnDefault(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void dropColumnDefault(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropColumnDefault& ataDropColumnDefault, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId ); @@ -113,7 +112,7 @@ namespace ddlpackageprocessor * @param ataDropTableConstraint the AtaDropTableConstraint object * @param fTableName the QualifiedName for the table */ - EXPORT void dropTableConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void dropTableConstraint(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaDropTableConstraint& ataDropTableConstraint, ddlpackage::QualifiedName& fTableName ); /** @brief rename a table @@ -122,7 +121,7 @@ namespace ddlpackageprocessor * @param ataRenameTable the AtaRenameTable object * @param fTableName the QualifiedName for the table */ - EXPORT void renameTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + EXPORT void renameTable(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaRenameTable& ataRenameTable, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); @@ -132,12 +131,12 @@ namespace ddlpackageprocessor * @param ataRenameColumn the AtaRenameColumn object * @param fTableName the QualifiedName for the table */ - EXPORT void renameColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + EXPORT void renameColumn(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, ddlpackage::AtaRenameColumn& ataRenameColumn, ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); protected: - void rollBackAlter(const std::string& error, BRM::TxnID txnID, int sessionId, DDLResult& result, uint64_t uniqueId); + void rollBackAlter(const std::string& error, BRM::TxnID txnID, int sessionId, DDLResult& result, u_int64_t uniqueId); private: diff --git a/dbcon/ddlpackageproc/createindexprocessor.cpp b/dbcon/ddlpackageproc/createindexprocessor.cpp index 1b8f9da6..610123cc 100644 --- a/dbcon/ddlpackageproc/createindexprocessor.cpp +++ b/dbcon/ddlpackageproc/createindexprocessor.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: createindexprocessor.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: createindexprocessor.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -240,9 +240,9 @@ try colStruct.dataOid = column.oid; colStruct.colWidth = column.colType.colWidth > 8 ? 8 : column.colType.colWidth; - colStruct.tokenFlag = false; - colStruct.tokenFlag = column.colType.colWidth > 8 ? true : false; - colStruct.colDataType = column.colType.colDataType; + colStruct.tokenFlag = false; + colStruct.tokenFlag = column.colType.colWidth > 8 ? true : false; + colStruct.colDataType = static_cast(column.colType.colDataType); if (column.colType.colWidth > 8 && !isNull) { @@ -343,9 +343,9 @@ try colStructCol.dataOid = column.oid; colStructCol.colWidth = column.colType.colWidth > 8 ? 8 : column.colType.colWidth; - colStructCol.tokenFlag = false; - colStructCol.tokenFlag = column.colType.colWidth > 8 ? true : false; - colStructCol.colDataType = column.colType.colDataType; + colStructCol.tokenFlag = false; + colStructCol.tokenFlag = column.colType.colWidth > 8 ? true : false; + colStructCol.colDataType = static_cast(column.colType.colDataType); if (column.colType.colWidth > 8 && !isNull) { diff --git a/dbcon/ddlpackageproc/createindexprocessor.h b/dbcon/ddlpackageproc/createindexprocessor.h index b77e7c38..8e6ca98d 100644 --- a/dbcon/ddlpackageproc/createindexprocessor.h +++ b/dbcon/ddlpackageproc/createindexprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: createindexprocessor.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: createindexprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackageproc/createtableprocessor.cpp b/dbcon/ddlpackageproc/createtableprocessor.cpp index 640f63e4..6e6c5db8 100644 --- a/dbcon/ddlpackageproc/createtableprocessor.cpp +++ b/dbcon/ddlpackageproc/createtableprocessor.cpp @@ -15,34 +15,28 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: createtableprocessor.cpp 9627 2013-06-18 13:59:21Z rdempsey $ - -#include -#include -using namespace std; - -#include +// $Id: createtableprocessor.cpp 9066 2012-11-13 21:37:23Z chao $ +#define DDLPKGCREATETABLEPROC_DLLEXPORT #include "createtableprocessor.h" - -#include "ddlpkg.h" -using namespace ddlpackage; - +#undef DDLPKGCREATETABLEPROC_DLLEXPORT +#include "sessionmanager.h" +#include "messagelog.h" +#include +#include "sqllogger.h" #include "we_messages.h" -using namespace WriteEngine; - -#include "oamcache.h" -using namespace oam; - #include "bytestream.h" +#include "oamcache.h" using namespace messageqcpp; - -#include "calpontsystemcatalog.h" +using namespace boost::algorithm; +using namespace std; using namespace execplan; - -#include "sqllogger.h" -#include "messagelog.h" +using namespace ddlpackage; using namespace logging; +using namespace BRM; +using namespace WriteEngine; +using namespace oam; +using namespace boost; namespace ddlpackageprocessor { @@ -58,11 +52,11 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( txnID.valid= fTxnid.valid; result.result = NO_ERROR; int rc1 = 0; - rc1 = fDbrm->isReadWrite(); + rc1 = fDbrm.isReadWrite(); if (rc1 != 0 ) { - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Unable to execute the statement due to DBRM is read only"); message.format(args); result.result = CREATE_ERROR; @@ -107,8 +101,8 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( //release transaction fSessionManager.rolledback(txnID); // Return the error for display to user - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add(ie.what()); message.format(args); result.result = CREATE_ERROR; @@ -124,8 +118,8 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( //release transaction fSessionManager.rolledback(txnID); // Return the error for display to user - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add(ie.what()); message.format(args); result.result = CREATE_ERROR; @@ -138,8 +132,8 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( //release transaction fSessionManager.rolledback(txnID); // Return the error for display to user - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add(ex.what()); message.format(args); result.result = CREATE_ERROR; @@ -151,8 +145,8 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( //release transaction fSessionManager.rolledback(txnID); // Return the error for display to user - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Unknown exception caught when checking if the table name is already in use."); message.format(args); result.result = CREATE_ERROR; @@ -171,8 +165,8 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( if (roPair.objnum < 3000) goto keepGoing; #endif - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Internal create table error for"); args.add(tableName.toString()); args.add(": table already exists"); @@ -191,8 +185,7 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( // Start a new transaction VERBOSE_INFO("Starting a new transaction"); - string stmt = createTableStmt.fSql + "|" + tableDef.fQualifiedName->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, createTableStmt.fSessionID, txnID.id); + SQLLogger logger(createTableStmt.fSql, fDDLLoggingId, createTableStmt.fSessionID, txnID.id); std::string err; @@ -200,34 +193,7 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( OamCache * oamcache = OamCache::makeOamCache(); string errorMsg; //get a unique number - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - Message::Args args; - Message message(9); - args.add(ex.what()); - message.format(args); - result.result = CREATE_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - catch ( ... ) - { - Message::Args args; - Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = CREATE_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - + uint64_t uniqueId = fDbrm.getUnique64(); fWEClient->addQueue(uniqueId); try { @@ -235,8 +201,8 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( VERBOSE_INFO("Allocating object ID for table"); // Allocate a object ID for each column we are about to create VERBOSE_INFO("Allocating object IDs for columns"); - uint32_t numColumns = tableDef.fColumns.size(); - uint32_t numDictCols = 0; + u_int32_t numColumns = tableDef.fColumns.size(); + u_int32_t numDictCols = 0; for (unsigned i=0; i < numColumns; i++) { int dataType; @@ -254,155 +220,64 @@ cout << "Create table allocOIDs got the stating oid " << fStartingColOID << endl { result.result = CREATE_ERROR; errorMsg = "Error in getting objectid from oidmanager."; - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Create table failed due to "); args.add(errorMsg); - message.format(args); result.message = message; fSessionManager.rolledback(txnID); return result; } - // Write the table metadata to the systemtable - VERBOSE_INFO("Writing meta data to SYSTABLE"); + // Write the tables metadata to the system catalog + VERBOSE_INFO("Writing meta data to SYSTABLES"); ByteStream bytestream; bytestream << (ByteStream::byte)WE_SVR_WRITE_SYSTABLE; bytestream << uniqueId; - bytestream << (uint32_t) createTableStmt.fSessionID; - bytestream << (uint32_t)txnID.id; - bytestream << (uint32_t)fStartingColOID; - bytestream << (uint32_t)createTableStmt.fTableWithAutoi; - uint16_t dbRoot; - BRM::OID_t sysOid = 1001; - //Find out where systable is - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - { - result.result =(ResultCode) rc; - Message::Args args; - Message message(9); - args.add("Error while calling getSysCatDBRoot "); - args.add(errorMsg); - message.format(args); - result.message = message; - //release transaction - fSessionManager.rolledback(txnID); - return result; - } - - int pmNum = 1; - bytestream << (uint32_t)dbRoot; - tableDef.serialize(bytestream); - boost::shared_ptr bsIn; - boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); - pmNum = (*dbRootPMMap)[dbRoot]; - try - { - fWEClient->write(bytestream, (unsigned)pmNum); -#ifdef IDB_DDL_DEBUG -cout << "create table sending We_SVR_WRITE_SYSTABLE to pm " << pmNum << endl; -#endif - while (1) - { - bsIn.reset(new ByteStream()); - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; - break; - } - else { - *bsIn >> rc; - if (rc != 0) { - errorMsg.clear(); - *bsIn >> errorMsg; -#ifdef IDB_DDL_DEBUG -cout << "Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl; -#endif - } - break; - } - } - } - catch (runtime_error& ex) //write error - { -#ifdef IDB_DDL_DEBUG -cout << "create table got exception" << ex.what() << endl; -#endif - rc = NETWORK_ERROR; - errorMsg = ex.what(); - } - catch (...) - { - rc = NETWORK_ERROR; -#ifdef IDB_DDL_DEBUG -cout << "create table got unknown exception" << endl; -#endif - } + bytestream << (u_int32_t) createTableStmt.fSessionID; + bytestream << (u_int32_t)txnID.id; + bytestream << (u_int32_t)fStartingColOID; + bytestream << (u_int32_t)createTableStmt.fTableWithAutoi; - if (rc != 0) - { - result.result =(ResultCode) rc; - Message::Args args; - Message message(9); - args.add("Create table failed due to "); - args.add(errorMsg); - message.format( args ); - result.message = message; - if (rc != NETWORK_ERROR) - { - rollBackTransaction( uniqueId, txnID, createTableStmt.fSessionID ); //What to do with the error code - } - //release transaction - fSessionManager.rolledback(txnID); - return result; - } - - VERBOSE_INFO("Writing meta data to SYSCOLUMN"); - bytestream.restart(); - bytestream << (ByteStream::byte)WE_SVR_WRITE_CREATE_SYSCOLUMN; - bytestream << uniqueId; - bytestream << (uint32_t) createTableStmt.fSessionID; - bytestream << (uint32_t)txnID.id; bytestream << numColumns; for (unsigned i = 0; i getSysCatDBRoot(sysOid, dbRoot); + bytestream << (u_int32_t)colPos; + + u_int16_t dbRoot; + BRM::OID_t sysOid = 1001; + //Find out where systable is + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); if (rc != 0) { result.result =(ResultCode) rc; - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Error while calling getSysCatDBRoot "); args.add(errorMsg); - message.format(args); result.message = message; //release transaction fSessionManager.rolledback(txnID); return result; } - - bytestream << (uint32_t)dbRoot; + int pmNum = 1; + bytestream << (u_int32_t)dbRoot; tableDef.serialize(bytestream); + boost::shared_ptr bsIn; + boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); pmNum = (*dbRootPMMap)[dbRoot]; try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DDL_DEBUG cout << "create table sending We_SVR_WRITE_SYSTABLE to pm " << pmNum << endl; #endif @@ -448,8 +323,8 @@ cout << "create table got unknown exception" << endl; if (rc != 0) { result.result =(ResultCode) rc; - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Create table failed due to "); args.add(errorMsg); message.format( args ); @@ -481,7 +356,6 @@ cout << "create table got unknown exception" << endl; bytestream.restart(); bytestream << (ByteStream::byte)WE_SVR_WRITE_CREATETABLEFILES; bytestream << uniqueId; - bytestream << (uint32_t)txnID.id; bytestream << (numColumns + numDictCols); unsigned colNum = 0; unsigned dictNum = 0; @@ -489,9 +363,8 @@ cout << "create table got unknown exception" << endl; { colDefPtr = *iter; - CalpontSystemCatalog::ColDataType dataType = convertDataType(colDefPtr->fType->fType); - if (dataType == CalpontSystemCatalog::DECIMAL || - dataType == CalpontSystemCatalog::UDECIMAL) + int dataType1 = convertDataType(colDefPtr->fType->fType); + if (dataType1 == CalpontSystemCatalog::DECIMAL) { if (colDefPtr->fType->fPrecision == -1 || colDefPtr->fType->fPrecision == 0) { @@ -515,22 +388,23 @@ cout << "create table got unknown exception" << endl; colDefPtr->fType->fLength = 8; } } + WriteEngine::ColDataType dataType = static_cast(dataType1); bytestream << (fStartingColOID + (colNum++) + 1); - bytestream << (uint8_t) dataType; - bytestream << (uint8_t) false; + bytestream << (u_int8_t) dataType; + bytestream << (u_int8_t) false; bytestream << (uint32_t) colDefPtr->fType->fLength; - bytestream << (uint16_t) useDBRoot; + bytestream << (u_int16_t) useDBRoot; bytestream << (uint32_t) colDefPtr->fType->fCompressiontype; - if ( (dataType == CalpontSystemCatalog::CHAR && colDefPtr->fType->fLength > 8) || - (dataType == CalpontSystemCatalog::VARCHAR && colDefPtr->fType->fLength > 7) || - (dataType == CalpontSystemCatalog::VARBINARY && colDefPtr->fType->fLength > 7) ) + if ( (dataType == WriteEngine::CHAR && colDefPtr->fType->fLength > 8) || + (dataType == WriteEngine::VARCHAR && colDefPtr->fType->fLength > 7) || + (dataType == WriteEngine::VARBINARY && colDefPtr->fType->fLength > 7) ) { bytestream << (uint32_t) (fStartingColOID+numColumns+(dictNum++)+1); - bytestream << (uint8_t) dataType; - bytestream << (uint8_t) true; + bytestream << (u_int8_t) dataType; + bytestream << (u_int8_t) true; bytestream << (uint32_t) colDefPtr->fType->fLength; - bytestream << (uint16_t) useDBRoot; + bytestream << (u_int16_t) useDBRoot; bytestream << (uint32_t) colDefPtr->fType->fCompressiontype; } ++iter; @@ -553,8 +427,8 @@ cout << "create table got unknown exception" << endl; catch (std::exception& ex) { result.result =(ResultCode) rc; - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Create table failed due to "); args.add(ex.what()); message.format( args ); @@ -618,9 +492,6 @@ cout << "Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl; break; } } - //@Bug 5464. Delete from extent map. - fDbrm->deleteOIDs(oidList); - } } catch (runtime_error&) @@ -642,13 +513,13 @@ cout << "Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl; } // Log the DDL statement. - logDDL(createTableStmt.fSessionID, txnID.id, createTableStmt.fSql, createTableStmt.fOwner); + logging::logDDL(createTableStmt.fSessionID, txnID.id, createTableStmt.fSql, createTableStmt.fOwner); } catch (std::exception& ex) { result.result = CREATE_ERROR; - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Create table failed due to "); args.add(ex.what()); message.format( args ); @@ -661,8 +532,8 @@ cout << "Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl; if (rc !=0) { result.result = CREATE_ERROR; - Message::Args args; - Message message(9); + logging::Message::Args args; + logging::Message message(9); args.add("Create table failed due to "); args.add(errorMsg); message.format( args ); @@ -676,8 +547,8 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t { cerr << "CreatetableProcessor::processPackage: " << error << endl; - Message::Args args; - Message message(1); + logging::Message::Args args; + logging::Message message(1); args.add("Create table Failed: "); args.add(error); args.add(""); @@ -704,8 +575,8 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t } catch (std::exception& ex) { - Message::Args args; - Message message(6); + logging::Message::Args args; + logging::Message message(6); args.add(ex.what()); message.format(args); result.message = message; @@ -713,15 +584,22 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t } catch (...) { - Message::Args args; - Message message(6); + logging::Message::Args args; + logging::Message message(6); args.add("Unknown exception"); message.format(args); result.message = message; result.result = CREATE_ERROR; //cout << "returnOIDs error" << endl; } + IndexOIDList::const_iterator idxoid_iter = fIndexOIDList.begin(); + while (idxoid_iter != fIndexOIDList.end()) + { + IndexOID idxOID = *idxoid_iter; + (void)0; + ++idxoid_iter; + } DictionaryOIDList::const_iterator dictoid_iter = fDictionaryOIDList.begin(); while (dictoid_iter != fDictionaryOIDList.end()) { @@ -734,5 +612,42 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t fSessionManager.rolledback(txnID); } -} // namespace ddlpackageprocessor +/* +void CreateTableProcessor::createIndexFiles(DDLResult& result, ddlpackage::TableDef& tableDef) +{ + SUMMARY_INFO("CreateTableProcessor::createIndexFiles"); + + if (result.result != NO_ERROR) + return; + + int error = NO_ERROR; + + IndexOIDList::const_iterator iter = fIndexOIDList.begin(); + while (iter != fIndexOIDList.end()) + { + IndexOID idxOID = *iter; + + error = fWriteEngine.createIndex(idxOID.treeOID, idxOID.listOID); + if (error != WriteEngine::NO_ERROR) + { + logging::Message::Args args; + logging::Message message(9); + args.add("Error creating index file: "); + args.add(idxOID.treeOID); + args.add("error number: "); + args.add(error); + message.format(args); + + result.result = CREATE_ERROR; + result.message = message; + + break; + } + + ++iter; + } + +} +*/ +} // namespace ddlpackageprocessor // vim:ts=4 sw=4: diff --git a/dbcon/ddlpackageproc/createtableprocessor.h b/dbcon/ddlpackageproc/createtableprocessor.h index a31e1c14..bdc24a1c 100644 --- a/dbcon/ddlpackageproc/createtableprocessor.h +++ b/dbcon/ddlpackageproc/createtableprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: createtableprocessor.h 9303 2013-03-07 16:07:12Z chao $ + * $Id: createtableprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -26,7 +26,7 @@ #include "ddlpackageprocessor.h" -#if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(DDLPKGCREATETABLEPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -42,8 +42,7 @@ namespace ddlpackageprocessor class CreateTableProcessor : public DDLPackageProcessor { public: - - CreateTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} + /** @brief process a create table statement * * @param createTableStmt the CreateTableStatement diff --git a/dbcon/ddlpackageproc/ddlindexpopulator.cpp b/dbcon/ddlpackageproc/ddlindexpopulator.cpp index dd0a0519..af04397e 100644 --- a/dbcon/ddlpackageproc/ddlindexpopulator.cpp +++ b/dbcon/ddlpackageproc/ddlindexpopulator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: ddlindexpopulator.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: ddlindexpopulator.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -168,14 +168,14 @@ namespace ddlpackageprocessor idx.listOid = fIdxOID.listOID; idx.multiColFlag = cols > 1; CalpontSystemCatalog::ColType coltype = csc->colType(cr->ColumnOID()); - idx.idxDataType = static_cast(coltype.colDataType); + idx.idxDataType = static_cast(coltype.colDataType); if (isDictionaryType(coltype) ) { idx.idxWidth = fTOKENSIZE; idx.idxType = WR_CHAR; }//@bug 410: index sizes are either 1, 4 or 8 - else if (exeplan::isCharType(coltype)) + else if (isCharType(coltype)) { if (1 == coltype.colWidth) idx.idxWidth = 1; else idx.idxWidth = (coltype.colWidth > 4) ? 8 : 4; diff --git a/dbcon/ddlpackageproc/ddlindexpopulator.h b/dbcon/ddlpackageproc/ddlindexpopulator.h index e97f7c9e..84ceb35b 100644 --- a/dbcon/ddlpackageproc/ddlindexpopulator.h +++ b/dbcon/ddlpackageproc/ddlindexpopulator.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: ddlindexpopulator.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: ddlindexpopulator.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -62,7 +62,7 @@ class DDLIndexPopulator */ DDLIndexPopulator(WriteEngine::WriteEngineWrapper* writeEngine, execplan::SessionManager* sessionManager, - uint32_t sessionID, + u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLPackageProcessor::DDLResult& result, const DDLPackageProcessor::IndexOID& idxOID, @@ -157,6 +157,12 @@ class DDLIndexPopulator */ void makeCsep(execplan::CalpontSelectExecutionPlan& csep); + bool isCharType(const execplan::CalpontSystemCatalog::ColType& colType) + { + return ( execplan::CalpontSystemCatalog::CHAR == colType.colDataType + || execplan::CalpontSystemCatalog::VARCHAR == colType.colDataType ); + } + /** @brief return if ColumnResult string type * * Uses same logic as ColumnResult from type to return getStringData (true) @@ -168,9 +174,7 @@ class DDLIndexPopulator return (type == execplan::CalpontSystemCatalog::CHAR || type == execplan::CalpontSystemCatalog::VARCHAR || type == execplan::CalpontSystemCatalog::FLOAT - || type == execplan::CalpontSystemCatalog::DOUBLE - || type == execplan::CalpontSystemCatalog::UFLOAT - || type == execplan::CalpontSystemCatalog::UDOUBLE ); + || type == execplan::CalpontSystemCatalog::DOUBLE ); } /** @brief converts column result data @@ -245,7 +249,7 @@ class DDLIndexPopulator WriteEngine::WriteEngineWrapper* fWriteEngine; execplan::SessionManager* fSessionManager; - uint32_t fSessionID; + u_int32_t fSessionID; execplan::CalpontSystemCatalog::SCN fTxnID; DDLPackageProcessor::DDLResult fResult; DDLPackageProcessor::IndexOID fIdxOID; diff --git a/dbcon/ddlpackageproc/ddlpackageprocessor.cpp b/dbcon/ddlpackageproc/ddlpackageprocessor.cpp index 8e95fd22..1b475757 100644 --- a/dbcon/ddlpackageproc/ddlpackageprocessor.cpp +++ b/dbcon/ddlpackageproc/ddlpackageprocessor.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: ddlpackageprocessor.cpp 9627 2013-06-18 13:59:21Z rdempsey $ +// $Id: ddlpackageprocessor.cpp 9058 2012-11-07 15:35:08Z chao $ #include #include @@ -24,7 +24,9 @@ #include using namespace std; +#define DDLPKGPROC_DLLEXPORT #include "ddlpackageprocessor.h" +#undef DDLPKGPROC_DLLEXPORT #include "dataconvert.h" using namespace dataconvert; @@ -82,12 +84,9 @@ namespace ddlpackageprocessor { DDLPackageProcessor::~DDLPackageProcessor() -{ - //cout << "in DDLPackageProcessor destructor " << this << endl; - delete fWEClient; -} +{} -void DDLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string schema,std::string table, +void DDLPackageProcessor::getColumnsForTable(u_int32_t sessionID, std::string schema,std::string table, ColumnList& colList) { @@ -132,111 +131,78 @@ void DDLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string sc } -execplan::CalpontSystemCatalog::ColDataType DDLPackageProcessor::convertDataType(int dataType) +int DDLPackageProcessor::convertDataType(int dataType) { - execplan::CalpontSystemCatalog::ColDataType colDataType; + int calpontDataType; switch (dataType) { case ddlpackage::DDL_CHAR: - colDataType = CalpontSystemCatalog::CHAR; + calpontDataType = CalpontSystemCatalog::CHAR; break; case ddlpackage::DDL_VARCHAR: - colDataType = CalpontSystemCatalog::VARCHAR; + calpontDataType = CalpontSystemCatalog::VARCHAR; break; case ddlpackage::DDL_VARBINARY: - colDataType = CalpontSystemCatalog::VARBINARY; + calpontDataType = CalpontSystemCatalog::VARBINARY; break; case ddlpackage::DDL_BIT: - colDataType = CalpontSystemCatalog::BIT; + calpontDataType = CalpontSystemCatalog::BIT; break; case ddlpackage::DDL_REAL: case ddlpackage::DDL_DECIMAL: case ddlpackage::DDL_NUMERIC: case ddlpackage::DDL_NUMBER: - colDataType = CalpontSystemCatalog::DECIMAL; + calpontDataType = CalpontSystemCatalog::DECIMAL; break; case ddlpackage::DDL_FLOAT: - colDataType = CalpontSystemCatalog::FLOAT; + calpontDataType = CalpontSystemCatalog::FLOAT; break; case ddlpackage::DDL_DOUBLE: - colDataType = CalpontSystemCatalog::DOUBLE; + calpontDataType = CalpontSystemCatalog::DOUBLE; break; case ddlpackage::DDL_INT: case ddlpackage::DDL_INTEGER: - colDataType = CalpontSystemCatalog::INT; + calpontDataType = CalpontSystemCatalog::INT; break; case ddlpackage::DDL_BIGINT: - colDataType = CalpontSystemCatalog::BIGINT; + calpontDataType = CalpontSystemCatalog::BIGINT; break; case ddlpackage::DDL_MEDINT: - colDataType = CalpontSystemCatalog::MEDINT; + calpontDataType = CalpontSystemCatalog::MEDINT; break; case ddlpackage::DDL_SMALLINT: - colDataType = CalpontSystemCatalog::SMALLINT; + calpontDataType = CalpontSystemCatalog::SMALLINT; break; case ddlpackage::DDL_TINYINT: - colDataType = CalpontSystemCatalog::TINYINT; + calpontDataType = CalpontSystemCatalog::TINYINT; break; - case ddlpackage::DDL_UNSIGNED_DECIMAL: - case ddlpackage::DDL_UNSIGNED_NUMERIC: - colDataType = CalpontSystemCatalog::UDECIMAL; - break; - - case ddlpackage::DDL_UNSIGNED_FLOAT: - colDataType = CalpontSystemCatalog::UFLOAT; - break; - - case ddlpackage::DDL_UNSIGNED_DOUBLE: - colDataType = CalpontSystemCatalog::UDOUBLE; - break; - - case ddlpackage::DDL_UNSIGNED_INT: - colDataType = CalpontSystemCatalog::UINT; - break; - - case ddlpackage::DDL_UNSIGNED_BIGINT: - colDataType = CalpontSystemCatalog::UBIGINT; - break; - - case ddlpackage::DDL_UNSIGNED_MEDINT: - colDataType = CalpontSystemCatalog::UMEDINT; - break; - - case ddlpackage::DDL_UNSIGNED_SMALLINT: - colDataType = CalpontSystemCatalog::USMALLINT; - break; - - case ddlpackage::DDL_UNSIGNED_TINYINT: - colDataType = CalpontSystemCatalog::UTINYINT; - break; - case ddlpackage::DDL_DATE: - colDataType = CalpontSystemCatalog::DATE; + calpontDataType = CalpontSystemCatalog::DATE; break; case ddlpackage::DDL_DATETIME: - colDataType = CalpontSystemCatalog::DATETIME; + calpontDataType = CalpontSystemCatalog::DATETIME; break; case ddlpackage::DDL_CLOB: - colDataType = CalpontSystemCatalog::CLOB; + calpontDataType = CalpontSystemCatalog::CLOB; break; case ddlpackage::DDL_BLOB: - colDataType = CalpontSystemCatalog::BLOB; + calpontDataType = CalpontSystemCatalog::BLOB; break; default: @@ -244,7 +210,7 @@ execplan::CalpontSystemCatalog::ColDataType DDLPackageProcessor::convertDataType } - return colDataType; + return calpontDataType; } std::string DDLPackageProcessor::buildTableConstraintName(const int oid, @@ -404,9 +370,8 @@ DDLPackageProcessor::getNullValueForType(const execplan::CalpontSystemCatalog::C break; case execplan::CalpontSystemCatalog::DECIMAL: - case execplan::CalpontSystemCatalog::UDECIMAL: { - if (colType.colWidth <= 4) + if (colType.colWidth <= execplan::CalpontSystemCatalog::FOUR_BYTE) { short smallintvalue = joblist::SMALLINTNULL; value = smallintvalue; @@ -429,7 +394,6 @@ DDLPackageProcessor::getNullValueForType(const execplan::CalpontSystemCatalog::C } break; case execplan::CalpontSystemCatalog::FLOAT: - case execplan::CalpontSystemCatalog::UFLOAT: { uint32_t jlfloatnull = joblist::FLOATNULL; float* fp = reinterpret_cast(&jlfloatnull); @@ -438,7 +402,6 @@ DDLPackageProcessor::getNullValueForType(const execplan::CalpontSystemCatalog::C break; case execplan::CalpontSystemCatalog::DOUBLE: - case execplan::CalpontSystemCatalog::UDOUBLE: { uint64_t jldoublenull = joblist::DOUBLENULL; double* dp = reinterpret_cast(&jldoublenull); @@ -489,8 +452,7 @@ DDLPackageProcessor::getNullValueForType(const execplan::CalpontSystemCatalog::C } break; - - case execplan::CalpontSystemCatalog::VARCHAR: + case execplan::CalpontSystemCatalog::VARCHAR: { std::string charnull; if (colType.colWidth == execplan::CalpontSystemCatalog::ONE_BYTE) @@ -513,8 +475,7 @@ DDLPackageProcessor::getNullValueForType(const execplan::CalpontSystemCatalog::C } break; - - case execplan::CalpontSystemCatalog::VARBINARY: + case execplan::CalpontSystemCatalog::VARBINARY: { std::string charnull; if (colType.colWidth == execplan::CalpontSystemCatalog::ONE_BYTE) @@ -538,35 +499,6 @@ DDLPackageProcessor::getNullValueForType(const execplan::CalpontSystemCatalog::C } break; - case execplan::CalpontSystemCatalog::UTINYINT: - { - uint8_t utinyintvalue = joblist::UTINYINTNULL; - value = utinyintvalue; - - } - break; - - case execplan::CalpontSystemCatalog::USMALLINT: - { - uint16_t usmallintvalue = joblist::USMALLINTNULL; - value = usmallintvalue; - } - break; - - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UINT: - { - uint32_t uintvalue = joblist::UINTNULL; - value = uintvalue; - } - break; - - case execplan::CalpontSystemCatalog::UBIGINT: - { - uint64_t ubigint = joblist::UBIGINTNULL; - value = ubigint; - } - break; default: throw std::runtime_error("getNullValueForType: unkown column data type"); @@ -677,7 +609,7 @@ boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN memcpy(dictTuple.sigValue, str.c_str(), str.length()); dictTuple.sigSize = str.length(); int error = NO_ERROR; - if (NO_ERROR != (error = fWriteEngine.tokenize(txnID, dictStruct, dictTuple, false))) // @bug 5572 HDFS tmp file + if (NO_ERROR != (error = fWriteEngine.tokenize(txnID, dictStruct, dictTuple))) { WErrorCodes ec; throw std::runtime_error("WE: Tokenization failed " + ec.errorString(error)); @@ -702,6 +634,960 @@ boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN return value; } +void DDLPackageProcessor::writeSysTableMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, + ddlpackage::TableDef& tableDef, uint32_t tableWithAutoi) +{ + std::string err("DDLPackageProcessor::writeSysTableMetaData "); + SUMMARY_INFO(err); + + if (result.result != NO_ERROR) + return; + + WriteEngine::ColTuple colTuple; + WriteEngine::ColStruct colStruct; + WriteEngine::ColStructList colStructs; + WriteEngine::ColTupleList colTuples; + WriteEngine::dictStr dctColTuples; + WriteEngine::DctnryStruct dctnryStruct; + WriteEngine::ColValueList colValuesList; + WriteEngine::DctnryStructList dctnryStructList; + WriteEngine::DictStrList dctnryValueList; + WriteEngine::RIDList ridList; + CalpontSystemCatalog::TableName tableName; + CalpontSystemCatalog::ROPair sysTableROPair; + boost::shared_ptr systemCatalogPtr; + ColumnList columns; + ColumnList::const_iterator column_iterator; + DDLColumn column; + int error = 0; + bool isNull = false; + + tableName.schema = CALPONT_SCHEMA; + tableName.table = SYSTABLE_TABLE; + + systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + + try + { + sysTableROPair = systemCatalogPtr->tableRID(tableName); + + getColumnsForTable(sessionID, tableName.schema,tableName.table, columns); + + column_iterator = columns.begin(); + std::string tmpStr(""); + while (column_iterator != columns.end()) + { + + column = *column_iterator; + boost::to_lower(column.tableColName.column); + isNull = false; + + if (TABLENAME_COL == column.tableColName.column) + { + std::string tablename = tableDef.fQualifiedName->fName; + boost::to_lower(tablename); + colTuple.data = tablename; + tmpStr = tablename; + } + else if (SCHEMA_COL == column.tableColName.column) + { + std::string schema = tableDef.fQualifiedName->fSchema; + boost::to_lower(schema); + colTuple.data = schema; + tmpStr = schema; + } + else if (OBJECTID_COL == column.tableColName.column) + { + colTuple.data = fTableOID; + } + else if (CREATEDATE_COL == column.tableColName.column) + { + date d(day_clock::universal_day()); + std::string date = to_iso_string(d); + Date aDay; + int intvalue; + std::string s = date.substr(0, 4); + if (from_string(intvalue, s, std::dec)) + { + aDay.year = intvalue; + } + s = date.substr(4, 2); + if (from_string(intvalue, s, std::dec)) + { + aDay.month = intvalue; + } + s = date.substr(6, 2); + if (from_string(intvalue, s, std::dec)) + { + aDay.day = intvalue; + } + + colTuple.data = *(reinterpret_cast (&aDay)); + + } + else if (INIT_COL == column.tableColName.column) + { + TableOptionMap::const_iterator options_iter = tableDef.fOptions.find("initial"); + if (options_iter != tableDef.fOptions.end()) + { + colTuple.data = options_iter->second; + } + else + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + } + else if (NEXT_COL == column.tableColName.column) + { + TableOptionMap::const_iterator options_iter = tableDef.fOptions.find("next"); + if (options_iter != tableDef.fOptions.end()) + { + colTuple.data = options_iter->second; + } + else + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + } + else if (AUTOINC_COL == column.tableColName.column) + { + colTuple.data = tableWithAutoi; + } + else + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + + colStruct.dataOid = column.oid; + colStruct.colWidth = column.colType.colWidth > 8 ? 8 : column.colType.colWidth; + colStruct.tokenFlag = false; + colStruct.tokenFlag = column.colType.colWidth > 8 ? true : false; + colStruct.colDataType = (WriteEngine::ColDataType)column.colType.colDataType; + if (colStruct.tokenFlag) + { + dctnryStruct.dctnryOid = column.colType.ddn.dictOID; + dctnryStruct.columnOid = column.oid; + } + else + { + dctnryStruct.dctnryOid = 0; + dctnryStruct.columnOid = column.oid; + } + + colStructs.push_back(colStruct); + + colTuples.push_back(colTuple); + + dctColTuples.push_back (tmpStr); + + colValuesList.push_back(colTuples); + + dctnryStructList.push_back (dctnryStruct); + + dctnryValueList.push_back (dctColTuples); + + + colTuples.pop_back(); + dctColTuples.pop_back(); + + ++column_iterator; + } + //fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3); + if (0 != colStructs.size()) + { + error = fWriteEngine.insertColumnRec_SYS(txnID, colStructs, colValuesList, + dctnryStructList, dctnryValueList); + + if (error != WriteEngine::NO_ERROR) + { + if (error == ERR_BRM_WR_VB_ENTRY) + { + throw std::runtime_error("WE: Error writing to BRM."); + } + else + { + WErrorCodes ec; + throw std::runtime_error("WE: Error updating calpont.systable:" + ec.errorString(error)); + } + } + } + } + catch (std::exception& ex) + { + err += ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err += "Unknown exception caught"; + throw std::runtime_error(err); + } +} + +void DDLPackageProcessor::writeSysColumnMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, + ColumnDefList& tableDefCols, ddlpackage::QualifiedName& qualifiedName, + int colpos, bool alterFlag) +{ + std::string err("DDLPackageProcessor::writeSysColumnMetaData "); + SUMMARY_INFO(err); + + if (result.result != NO_ERROR) + return; + + WriteEngine::ColStruct colStruct; + WriteEngine::ColTuple colTuple; + WriteEngine::ColStructList colStructs; + WriteEngine::ColTupleList colTuples; + WriteEngine::DctColTupleList dctColTuples; + WriteEngine::ColValueList colValuesList; + WriteEngine::RIDList ridList; + WriteEngine::DctnryStruct dctnryStruct; + WriteEngine::dictStr dctnryTuple; + WriteEngine::DctnryStructList dctnryStructList; + WriteEngine::DictStrList dctnryValueList; + + CalpontSystemCatalog::TableName tableName; + + ColumnList columns; + ColumnList::const_iterator column_iterator; + ColumnDef* colDefPtr = 0; + ColumnDefList::const_iterator iter; + DDLColumn column; + int error = 0; + int startPos = colpos; + bool isNull = false; + + tableName.schema = CALPONT_SCHEMA; + tableName.table = SYSCOLUMN_TABLE; + + getColumnsForTable(sessionID, tableName.schema,tableName.table, columns); + unsigned int numCols = columns.size(); + //WriteEngine::ColTupleList colList[numCols]; + //ColTupleList is NOT POD, so let's try this: + std::vector colList; + //WriteEngine::dictStr dctColList[numCols]; + std::vector dctColList; + iter = tableDefCols.begin(); + //colpos = 0; + std::string tmpStr(""); + for (unsigned int ii = 0; ii < numCols; ii++) + { + colList.push_back(WriteEngine::ColTupleList()); + dctColList.push_back(WriteEngine::dictStr()); + } + try + { + while (iter != tableDefCols.end()) + { + colDefPtr = *iter; + + DictOID dictOID; + + + int dataType; + dataType = convertDataType(colDefPtr->fType->fType); + if (dataType == CalpontSystemCatalog::DECIMAL) + { + if (colDefPtr->fType->fPrecision < colDefPtr->fType->fScale) + { + ostringstream os; + os << "Syntax error: scale should be less than precision, precision: " << colDefPtr->fType->fPrecision << " scale: " << colDefPtr->fType->fScale; + throw std::runtime_error(os.str()); + +/* logging::Message::Args args; + logging::Message message(9); + result.result = CREATE_ERROR; + + args.add("Syntax error: "); + args.add("scale should be less than precision"); + message.format(args); + result.message = message; + return;*/ + } + } + if (dataType == CalpontSystemCatalog::DECIMAL) + { + //@Bug 2089 decimal precision default to 10 if 0 is used. + if (colDefPtr->fType->fPrecision <= 0) + colDefPtr->fType->fPrecision = 10; + + if (colDefPtr->fType->fPrecision == -1 || colDefPtr->fType->fPrecision == 0) + { + //dataType = CalpontSystemCatalog::BIGINT; + colDefPtr->fType->fType = DDL_BIGINT; + colDefPtr->fType->fLength = 8; + colDefPtr->fType->fScale = 0; + } + else if ((colDefPtr->fType->fPrecision > 0) && (colDefPtr->fType->fPrecision < 3)) + { + //dataType = CalpontSystemCatalog::TINYINT; + colDefPtr->fType->fType = DDL_TINYINT; + colDefPtr->fType->fLength = 1; + } + + else if (colDefPtr->fType->fPrecision < 5 && (colDefPtr->fType->fPrecision > 2)) + { + //dataType = CalpontSystemCatalog::SMALLINT; + colDefPtr->fType->fType = DDL_SMALLINT; + colDefPtr->fType->fLength = 2; + } + else if (colDefPtr->fType->fPrecision > 4 && colDefPtr->fType->fPrecision < 10) + { + //dataType = CalpontSystemCatalog::INT; + colDefPtr->fType->fType = DDL_INT; + colDefPtr->fType->fLength = 4; + } + else if (colDefPtr->fType->fPrecision > 9 && colDefPtr->fType->fPrecision < 19) + { + //dataType = CalpontSystemCatalog::BIGINT; + colDefPtr->fType->fType = DDL_BIGINT; + colDefPtr->fType->fLength = 8; + } + else + { + /*@Bug 1959 InfiniDB does not support DECIMAL and NUMERIC column that is + greater than 8 bytes. */ + ostringstream os; + os << "DECIMAL and NUMERIC column precision greater than 18 is not supported by InfiniDB."; + throw std::runtime_error(os.str()); + } + + } + + bool hasDict = false; + if ( (dataType == CalpontSystemCatalog::CHAR && colDefPtr->fType->fLength > 8) || + (dataType == CalpontSystemCatalog::VARCHAR && colDefPtr->fType->fLength > 7) || + (dataType == CalpontSystemCatalog::VARBINARY && colDefPtr->fType->fLength > 7) ) + { + hasDict = true; + dictOID.compressionType = colDefPtr->fType->fCompressiontype; + dictOID.colWidth = colDefPtr->fType->fLength; + + //@Bug 2534. Take away the limit of 255 and set the limit to 8000. + if (colDefPtr->fType->fLength > 8000) + { + ostringstream os; + os << "char, varchar and varbinary length may not exceed 8000"; + throw std::runtime_error(os.str()); + } + } + else if (dataType == CalpontSystemCatalog::VARBINARY && colDefPtr->fType->fLength <= 7) + { + ostringstream os; + os << "varbinary length may not be less than 8"; + throw std::runtime_error(os.str()); + } + + + if (hasDict) + { + execplan::ObjectIDManager fObjectIDManager; + int startOID = fObjectIDManager.allocOIDs(1); + dictOID.dictOID = startOID; + dictOID.listOID = 0; + dictOID.treeOID = 0; + + fDictionaryOIDList.push_back(dictOID); + } + unsigned int i = 0; + column_iterator = columns.begin(); + while (column_iterator != columns.end()) + { + column = *column_iterator; + boost::to_lower(column.tableColName.column); + + isNull = false; + + if (SCHEMA_COL == column.tableColName.column) + { + boost::to_lower(qualifiedName.fSchema); + colTuple.data = qualifiedName.fSchema; + tmpStr = qualifiedName.fSchema; + } + else if (TABLENAME_COL == column.tableColName.column) + { + boost::to_lower(qualifiedName.fName); + colTuple.data = qualifiedName.fName; + tmpStr = qualifiedName.fName; + } + else if (COLNAME_COL == column.tableColName.column) + { + boost::to_lower(colDefPtr->fName); + colTuple.data = colDefPtr->fName; + tmpStr = colDefPtr->fName; + } + else if (OBJECTID_COL == column.tableColName.column) + { + if (alterFlag) + colTuple.data = fStartingColOID; + else + colTuple.data = fStartingColOID + colpos; + } + else if (DATATYPE_COL == column.tableColName.column) + { + colTuple.data = dataType; + } + else if (COLUMNLEN_COL == column.tableColName.column) + { + //@Bug 2089 Disallow zero length char and varch column to be created + if (dataType == CalpontSystemCatalog::CHAR || + dataType == CalpontSystemCatalog::VARCHAR || + dataType == CalpontSystemCatalog::VARBINARY) + { + if (colDefPtr->fType->fLength <= 0) + { + ostringstream os; + os << "char, varchar and varbinary length must be greater than zero"; + throw std::runtime_error(os.str()); + } + } + colTuple.data = colDefPtr->fType->fLength; + } + else if (COLUMNPOS_COL == column.tableColName.column) + { + colTuple.data = colpos; + } + else if (DEFAULTVAL_COL == column.tableColName.column) + { + if (colDefPtr->fDefaultValue) + { + colTuple.data = colDefPtr->fDefaultValue->fValue; + tmpStr = colDefPtr->fDefaultValue->fValue; + } + else + { + tmpStr=""; + //colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + + } + else if (NULLABLE_COL == column.tableColName.column) + { + int nullable = 1; + ColumnConstraintList& colConstraints = colDefPtr->fConstraints; + ColumnConstraintList::const_iterator constraint_iter = colConstraints.begin(); + while (constraint_iter != colConstraints.end()) + { + ColumnConstraintDef* consDefPtr = *constraint_iter; + if (consDefPtr->fConstraintType == ddlpackage::DDL_NOT_NULL) + { + nullable = 0; + break; + } + ++constraint_iter; + } + colTuple.data = nullable; + } + else if (SCALE_COL == column.tableColName.column) + { + colTuple.data = colDefPtr->fType->fScale; + } + else if (PRECISION_COL == column.tableColName.column) + { + colTuple.data = colDefPtr->fType->fPrecision; + } + else if (DICTOID_COL == column.tableColName.column) + { + if (hasDict) + { + colTuple.data = dictOID.dictOID; + } + else + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + } + else if (LISTOBJID_COL == column.tableColName.column) + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + else if (TREEOBJID_COL == column.tableColName.column) + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + else if (MINVAL_COL == column.tableColName.column) + { + tmpStr=""; + isNull = true; + } + else if (MAXVAL_COL == column.tableColName.column) + { + tmpStr=""; + isNull = true; + } + else if (COMPRESSIONTYPE_COL == column.tableColName.column) + { + colTuple.data = colDefPtr->fType->fCompressiontype; + } + else if (AUTOINC_COL == column.tableColName.column) + { + //cout << "autoincrement= " << colDefPtr->fType->fAutoincrement << endl; + colTuple.data = colDefPtr->fType->fAutoincrement; + + } + else if (NEXTVALUE_COL == column.tableColName.column) + { + colTuple.data = colDefPtr->fType->fNextvalue; + } + else + { + colTuple.data = getNullValueForType(column.colType); + isNull = true; + } + + colStruct.dataOid = column.oid; + colStruct.colWidth = column.colType.colWidth > 8 ? 8 : column.colType.colWidth; + colStruct.tokenFlag = false; + colStruct.tokenFlag = column.colType.colWidth > 8 ? true : false; + colStruct.colDataType = static_cast(column.colType.colDataType); + + if (colStruct.tokenFlag) + { + dctnryStruct.dctnryOid = column.colType.ddn.dictOID; + dctnryStruct.columnOid = column.oid; + } + else + { + dctnryStruct.dctnryOid = 0; + dctnryStruct.columnOid = column.oid; + } + + + if (colpos == startPos) + { + colStructs.push_back(colStruct); + dctnryStructList.push_back (dctnryStruct); + } + colList[i].push_back(colTuple); + //colList.push_back(WriteEngine::ColTupleList()); + //colList.back().push_back(colTuple); + dctColList[i].push_back(tmpStr); + //dctColList.push_back(WriteEngine::dictStr()); + //dctColList.back().push_back(tmpStr); + ++i; + ++column_iterator; + } + + ++colpos; + ++iter; + } + + idbassert(colList.size() >= numCols); + idbassert(dctColList.size() >= numCols); + + if (0 != colStructs.size()) + { + //FIXME: Is there a cleaner way to do this? Isn't colValuesList the same as colList after this? + for (unsigned int n = 0; n < numCols; n++) + { + colValuesList.push_back(colList[n]); + dctnryValueList.push_back(dctColList[n]); + } + //fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3); + error = fWriteEngine.insertColumnRec_SYS(txnID, colStructs, colValuesList, + dctnryStructList, dctnryValueList); + + if (error != WriteEngine::NO_ERROR) + { + if (error == ERR_BRM_WR_VB_ENTRY) + { + throw std::runtime_error( + "writeSysColumnMetaData WE: Error writing to BRM."); + } + else + { + WErrorCodes ec; + throw std::runtime_error( + "WE: Error updating calpont.syscolumn. " + ec.errorString(error)); +// err = "Error updating calpont.syscolumn. error number = " + error; + } + } + } + + } + catch (std::exception& ex) + { + err += ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err += "Unknown exception caught"; + throw std::runtime_error(err); + } +} + +void DDLPackageProcessor::removeSysTableMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + DDLResult& result, + ddlpackage::QualifiedName& tableName) +{ + + SUMMARY_INFO("DDLPackageProcessor::removeSysTableMetaData"); + + if (result.result != NO_ERROR) + return; + std::string err; + ddlpackage::QualifiedName sysCatalogTableName; + sysCatalogTableName.fSchema = CALPONT_SCHEMA; + sysCatalogTableName.fName = SYSTABLE_TABLE; + + CalpontSystemCatalog::TableName userTableName; + userTableName.schema = tableName.fSchema; + userTableName.table = tableName.fName; + + boost::shared_ptr systemCatalogPtr; + systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + try + { + CalpontSystemCatalog::ROPair userTableROPair = systemCatalogPtr->tableRID(userTableName); + if (userTableROPair.rid == std::numeric_limits::max()) + { + err = "RowID is not valid "; + throw std::runtime_error(err); + } + // cout << "RID for table " << userTableName.schema << "." << userTableName.table << " = " << userTableROPair.rid << endl; + removeRowFromSysCatalog(sessionID, txnID, result, sysCatalogTableName, userTableROPair.rid); + } + catch (std::exception& ex) + { + err = ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err = "Unknown exception caught"; + throw std::runtime_error(err); + } +} + +void DDLPackageProcessor::removeSysColMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + DDLResult& result, + ddlpackage::QualifiedName& tableName) +{ + SUMMARY_INFO("DDLPackageProcessor::removeSysColMetaData"); + + if (result.result != NO_ERROR) + return; + + ddlpackage::QualifiedName sysCatalogTableName; + sysCatalogTableName.fSchema = CALPONT_SCHEMA; + sysCatalogTableName.fName = SYSCOLUMN_TABLE; + + CalpontSystemCatalog::TableName userTableName; + userTableName.schema = tableName.fSchema; + userTableName.table = tableName.fName; + + boost::shared_ptr systemCatalogPtr; + systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + std::string err; + try + { + execplan::CalpontSystemCatalog::RIDList colRidList = systemCatalogPtr->columnRIDs(userTableName); + + removeRowsFromSysCatalog(sessionID, txnID, result, sysCatalogTableName, colRidList); + } + catch (std::exception& ex) + { + err = ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err = "Unknown exception caught"; + throw std::runtime_error(err); + } + +} + +void DDLPackageProcessor::removeColSysColMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + DDLResult& result, + ddlpackage::QualifiedName& columnInfo) +{ + SUMMARY_INFO("DDLPackageProcessor::removeColSysColMetaData"); + + if (result.result != NO_ERROR) + return; + + ddlpackage::QualifiedName sysCatalogTableName; + sysCatalogTableName.fSchema = CALPONT_SCHEMA; + sysCatalogTableName.fName = SYSCOLUMN_TABLE; + + CalpontSystemCatalog::TableColName userColName; + userColName.schema = columnInfo.fSchema; + userColName.table = columnInfo.fCatalog; + userColName.column = columnInfo.fName; + + boost::shared_ptr systemCatalogPtr; + systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + std::string err; + try + { + execplan::CalpontSystemCatalog::ROPair colRO = systemCatalogPtr->columnRID(userColName); + execplan::CalpontSystemCatalog::RIDList colRidList; + colRidList.push_back(colRO); + removeRowsFromSysCatalog(sessionID, txnID, result, sysCatalogTableName, colRidList); + } + catch (std::exception& ex) + { + err = ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err = "Unknown exception caught"; + throw std::runtime_error(err); + } +} + +void DDLPackageProcessor::removeRowFromSysCatalog(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + const DDLResult& result, + ddlpackage::QualifiedName& sysCatalogTableName, + WriteEngine::RID& rid) +{ + + SUMMARY_INFO("DDLPackageProcessor::removeRowFromSysCatalog"); + + if (result.result != NO_ERROR) + return; + + CalpontSystemCatalog::RIDList colRidList; + CalpontSystemCatalog::ROPair roPair; + std::string err; + roPair.objnum = 0; + roPair.rid = rid; + colRidList.push_back(roPair); + try + { + removeRowsFromSysCatalog(sessionID, txnID, result,sysCatalogTableName,colRidList); + } + catch (std::exception& ex) + { + err = ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err = "Unknown exception caught"; + throw std::runtime_error(err); + } + +} + +void DDLPackageProcessor::removeRowsFromSysCatalog(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + const DDLResult& result, + ddlpackage::QualifiedName& sysCatalogTableName, + execplan::CalpontSystemCatalog::RIDList& colRidList) +{ + + SUMMARY_INFO("DDLPackageProcessor::removeRowsFromSysCatalog"); + + if (result.result != NO_ERROR) + return; + + WriteEngine::ColStruct colStruct; + WriteEngine::ColStructList colStructs; + std::vector colExtentsStruct; + std::vector colValuesList; + WriteEngine::RIDList ridList; + std::vector ridLists; + DDLColumn column; + + execplan::CalpontSystemCatalog::RIDList::const_iterator colrid_iterator = colRidList.begin(); + while (colrid_iterator != colRidList.end()) + { + WriteEngine::RID rid = (*colrid_iterator).rid; + ridList.push_back(rid); + ++colrid_iterator; + } + + ColumnList columns; + getColumnsForTable(sessionID, sysCatalogTableName.fSchema, sysCatalogTableName.fName, columns); + + ColumnList::const_iterator column_iterator = columns.begin(); + while (column_iterator != columns.end()) + { + column = *column_iterator; + colStruct.dataOid = column.oid; + colStruct.colWidth = column.colType.colWidth > 8 ? 8 : column.colType.colWidth; + colStruct.colDataType = static_cast(column.colType.colDataType); + + colStructs.push_back(colStruct); + + ++column_iterator; + } + colExtentsStruct.push_back(colStructs); + ridLists.push_back(ridList); + std::string err; + try + { + if (0 != colStructs.size() && 0 != ridLists[0].size()) + { + int error = fWriteEngine.deleteRow(txnID, colExtentsStruct, colValuesList, ridLists); + if (error != WriteEngine::NO_ERROR) + { + err = "WE:Error removing rows from " + sysCatalogTableName.fName ; + throw std::runtime_error(err); + } + } + } + catch (std::exception& ex) + { + err = ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err = "Unknown exception caught"; + throw std::runtime_error(err); + } + +} + +void DDLPackageProcessor::createDictionaryFiles(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, const int useDBRoot) +{ + std::string err("DDLPackageProcessor::createDictionaryFiles "); + SUMMARY_INFO(err); + + if (result.result != NO_ERROR) + return; + + int error = NO_ERROR; + + DictionaryOIDList::const_iterator iter = fDictionaryOIDList.begin(); + try + { + while (iter != fDictionaryOIDList.end()) + { + DictOID dictOID = *iter; + error = fWriteEngine.createDctnry(txnID, dictOID.dictOID, + dictOID.colWidth, useDBRoot, 0, 0, dictOID.compressionType); + if (error != WriteEngine::NO_ERROR) + { + WErrorCodes ec; + ostringstream oss; + oss << "WE: Error creating dictionary file for oid " << dictOID.dictOID + << "; " << ec.errorString(error) << endl; + throw std::runtime_error (oss.str()); + } + ++iter; + } + } + catch (std::exception& ex) + { + err += ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err += "Unknown exception caught"; + throw std::runtime_error(err); + } + +} + + +void DDLPackageProcessor::createColumnFiles(execplan::CalpontSystemCatalog::SCN txnID, + const DDLResult& result, + ddlpackage::ColumnDefList& tableDefCols, + const int useDBRoot, const uint32_t partitionNum) +{ + std::string err("DDLPackageProcessor::createColumnFiles "); + SUMMARY_INFO(err); + + if (result.result != NO_ERROR) + return; + + //ColumnDefList& tableDefCols = tableDef.fColumns; + ColumnDefList::const_iterator iter = tableDefCols.begin(); + int colpos = 0, error = NO_ERROR; + ColumnDef* colDefPtr; + try + { + while (iter != tableDefCols.end()) + { + colDefPtr = *iter; + + WriteEngine::ColDataType dataType = static_cast( + convertDataType(colDefPtr->fType->fType)); + + error = fWriteEngine.createColumn(txnID, fStartingColOID + colpos, dataType, + colDefPtr->fType->fLength, useDBRoot, partitionNum, + colDefPtr->fType->fCompressiontype); + + if (error != WriteEngine::NO_ERROR) + { + WErrorCodes ec; + ostringstream oss; + oss << "WE: Error creating column file for oid " << (fStartingColOID + colpos) << "; " << ec.errorString(error) << endl; + throw std::runtime_error (oss.str()); + } + ++colpos; + ++iter; + } + } + catch (std::exception& ex) + { + err += ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err += "Unknown exception caught"; + throw std::runtime_error(err); + } +} + + +void DDLPackageProcessor::createIndexFiles(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result) +{ +/* std::string err("DDLPackageProcessor::createIndexFiles "); + SUMMARY_INFO(err); + + if (result.result != NO_ERROR) + return; + + int error = NO_ERROR; + + IndexOIDList::const_iterator iter = fIndexOIDList.begin(); + try + { + while (iter != fIndexOIDList.end()) + { + IndexOID idxOID = *iter; + + error = -1; + if (error != WriteEngine::NO_ERROR) + { + WErrorCodes ec; + throw std::runtime_error("WE: Error creating index files: tree file " + getFileName(idxOID.treeOID) + " list file " + getFileName(idxOID.listOID) + ". " + ec.errorString(error)); + } + ++iter; + } + } + catch (std::exception& ex) + { + err += ex.what(); + throw std::runtime_error(err); + } + catch (...) + { + err += "Unknown exception caught"; + throw std::runtime_error(err); + } + */ +} + + void DDLPackageProcessor::flushPrimprocCache(std::vector& oidList) { SUMMARY_INFO("DDLPackageProcessor::flushPrimprocCache"); @@ -743,8 +1629,12 @@ void DDLPackageProcessor::flushPrimprocCache(std::vector systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(1); @@ -838,25 +1728,24 @@ void DDLPackageProcessor::createFiles(CalpontSystemCatalog::TableName aTableName ByteStream bytestream; boost::shared_ptr bsIn; bytestream << (ByteStream::byte)WE_SVR_WRITE_CREATETABLEFILES; - bytestream << (uint32_t)1; bytestream << uniqueId; bytestream << numOids; for (unsigned col = 0; col < ridList.size(); col++) { colType = systemCatalogPtr->colType(ridList[col].objnum); bytestream << (uint32_t) ridList[col].objnum; - bytestream << (uint8_t) colType.colDataType; - bytestream << (uint8_t) false; + bytestream << (u_int8_t) colType.colDataType; + bytestream << (u_int8_t) false; bytestream << (uint32_t) colType.colWidth; - bytestream << (uint16_t) useDBRoot; + bytestream << (u_int16_t) useDBRoot; bytestream << (uint32_t) colType.compressionType; if (colType.ddn.dictOID > 3000) { bytestream << (uint32_t) colType.ddn.dictOID; - bytestream << (uint8_t) colType.colDataType; - bytestream << (uint8_t) true; + bytestream << (u_int8_t) colType.colDataType; + bytestream << (u_int8_t) true; bytestream << (uint32_t) colType.colWidth; - bytestream << (uint16_t) useDBRoot; + bytestream << (u_int16_t) useDBRoot; bytestream << (uint32_t) colType.compressionType; } } @@ -868,7 +1757,7 @@ void DDLPackageProcessor::createFiles(CalpontSystemCatalog::TableName aTableName boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); int pmNum = (*dbRootPMMap)[useDBRoot]; - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); bsIn.reset(new ByteStream()); while (1) @@ -926,7 +1815,7 @@ void DDLPackageProcessor::removePartitionFiles(std::vector partInfos; - for (uint32_t i = 0; i < oidList.size(); i++) + for (uint i = 0; i < oidList.size(); i++) { bs << (uint32_t)oidList[i]; // add oid to LogicalPartition to form PartitionInfo @@ -940,11 +1829,11 @@ void DDLPackageProcessor::removePartitionFiles(std::vectorwrite_to_all(bs); - uint32_t pmCount = fWEClient->getPmCount(); + uint pmCount = fWEClient->getPmCount(); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -987,7 +1876,7 @@ void DDLPackageProcessor::removeExtents(std::vectordeleteOIDs(oidList); + err = fDbrm.deleteOIDs(oidList); if (err) { string errMsg; @@ -998,7 +1887,7 @@ void DDLPackageProcessor::removeExtents(std::vector& oidList) + u_int64_t uniqueId, std::vector& oidList) { SUMMARY_INFO("DDLPackageProcessor::createWriteDropLogFile"); //For shared nothing, the meta files are created under data1 with controllernode. @@ -1007,19 +1896,19 @@ void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog: OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length()); int parentId = atoi(OAMParentModuleName.c_str()); ByteStream bytestream; - uint8_t rc = 0; + u_int8_t rc = 0; std::string errorMsg; boost::shared_ptr bsIn; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPTABLE; bytestream << uniqueId; - bytestream << (uint32_t)tableOid; - bytestream << (uint32_t) oidList.size(); - for (uint32_t i=0; i < oidList.size(); i++) + bytestream << (u_int32_t)tableOid; + bytestream << (u_int32_t) oidList.size(); + for (u_int32_t i=0; i < oidList.size(); i++) { - bytestream << (uint32_t)oidList[i]; + bytestream << (u_int32_t)oidList[i]; } try { - fWEClient->write(bytestream, (uint32_t)parentId); + fWEClient->write(bytestream, (uint)parentId); while (1) { bsIn.reset(new ByteStream()); @@ -1054,7 +1943,7 @@ void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog: throw std::runtime_error(errorMsg); } -void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId) +void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontSystemCatalog::OID tableOid, u_int64_t uniqueId) { SUMMARY_INFO("DDLPackageProcessor::deleteLogFile"); OamCache * oamcache = OamCache::makeOamCache(); @@ -1062,16 +1951,16 @@ void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontS OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length()); int parentId = atoi(OAMParentModuleName.c_str()); ByteStream bytestream; - uint8_t rc = 0; + u_int8_t rc = 0; std::string errorMsg; fWEClient->addQueue(uniqueId); boost::shared_ptr bsIn; bytestream << (ByteStream::byte)WE_SVR_DELETE_DDLLOG; bytestream << uniqueId; - bytestream << (uint32_t) fileType; - bytestream << (uint32_t)tableOid; + bytestream << (u_int32_t) fileType; + bytestream << (u_int32_t)tableOid; try { - fWEClient->write(bytestream, (uint32_t)parentId); + fWEClient->write(bytestream, (uint)parentId); while (1) { bsIn.reset(new ByteStream()); @@ -1108,18 +1997,16 @@ void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontS } } -void DDLPackageProcessor::fetchLogFile(TableLogInfo & tableLogInfos, uint64_t uniqueId) +void DDLPackageProcessor::fetchLogFile(TableLogInfo & tableLogInfos, u_int64_t uniqueId) { SUMMARY_INFO("DDLPackageProcessor::fetchLogFile"); OamCache * oamcache = OamCache::makeOamCache(); std::string OAMParentModuleName = oamcache->getOAMParentModuleName(); - //Use a sensible default so that substr doesn't throw... - if (OAMParentModuleName.empty()) - OAMParentModuleName = "pm1"; - int parentId = atoi(OAMParentModuleName.substr(2, OAMParentModuleName.length()).c_str()); + OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length()); + int parentId = atoi(OAMParentModuleName.c_str()); ByteStream bytestream; - uint8_t rc = 0; - uint32_t tmp32, tableOid, numOids, numPartitions; + u_int8_t rc = 0; + u_int32_t tmp32, tableOid, numOids, numPartitions; LogFileType logFileType; std::string errorMsg; fWEClient->addQueue(uniqueId); @@ -1127,7 +2014,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo & tableLogInfos, uint64_t un bytestream << (ByteStream::byte)WE_SVR_FETCH_DDL_LOGS; bytestream << uniqueId; try { - fWEClient->write(bytestream, (uint32_t)parentId); + fWEClient->write(bytestream, (uint)parentId); while (1) { bsIn.reset(new ByteStream()); @@ -1193,7 +2080,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo & tableLogInfos, uint64_t un void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCatalog::OID tableOid, const PartitionNums& partitionNums, - std::vector& oidList, uint64_t uniqueId) + std::vector& oidList, u_int64_t uniqueId) { SUMMARY_INFO("DDLPackageProcessor::createWritePartitionLogFile"); fWEClient->addQueue(uniqueId); @@ -1204,23 +2091,23 @@ void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCat boost::shared_ptr bsIn; ByteStream bytestream; std::string errorMsg; - uint8_t rc = 0; + u_int8_t rc = 0; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPPARTITION; bytestream << uniqueId; - bytestream << (uint32_t)tableOid; + bytestream << (u_int32_t)tableOid; bytestream << (uint32_t) partitionNums.size(); PartitionNums::const_iterator it; for (it = partitionNums.begin(); it != partitionNums.end(); ++it) (*it).serialize(bytestream); - bytestream << (uint32_t) oidList.size(); - for (uint32_t i=0; i < oidList.size(); i++) + bytestream << (u_int32_t) oidList.size(); + for (u_int32_t i=0; i < oidList.size(); i++) { - bytestream << (uint32_t)oidList[i]; + bytestream << (u_int32_t)oidList[i]; } try { - fWEClient->write(bytestream, (uint32_t)parentId); + fWEClient->write(bytestream, (uint)parentId); while (1) { bsIn.reset(new ByteStream()); @@ -1255,7 +2142,7 @@ void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCat throw std::runtime_error(errorMsg); } -void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId, std::vector& oidList) +void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, u_int64_t uniqueId, std::vector& oidList) { SUMMARY_INFO("DDLPackageProcessor::createWriteTruncateTableLogFile"); //For shared nothing, the meta files are created under data1 with controllernode. @@ -1264,19 +2151,19 @@ void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSyste OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length()); int parentId = atoi(OAMParentModuleName.c_str()); ByteStream bytestream; - uint8_t rc = 0; + u_int8_t rc = 0; std::string errorMsg; boost::shared_ptr bsIn; bytestream << (ByteStream::byte)WE_SVR_WRITE_TRUNCATE; bytestream << uniqueId; - bytestream << (uint32_t)tableOid; - bytestream << (uint32_t) oidList.size(); - for (uint32_t i=0; i < oidList.size(); i++) + bytestream << (u_int32_t)tableOid; + bytestream << (u_int32_t) oidList.size(); + for (u_int32_t i=0; i < oidList.size(); i++) { - bytestream << (uint32_t)oidList[i]; + bytestream << (u_int32_t)oidList[i]; } try { - fWEClient->write(bytestream, (uint32_t)parentId); + fWEClient->write(bytestream, (uint)parentId); while (1) { bsIn.reset(new ByteStream()); @@ -1311,7 +2198,6 @@ void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSyste throw std::runtime_error(errorMsg); } -#if 0 void DDLPackageProcessor::createOpenTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, execplan::CalpontSystemCatalog::TableName tableName) { SUMMARY_INFO("DDLPackageProcessor::createOpenTruncateTableLogFile"); @@ -1415,7 +2301,7 @@ void DDLPackageProcessor::updateSyscolumns(execplan::CalpontSystemCatalog::SCN t colStruct.dataOid = OID_SYSCOLUMN_COLUMNPOS; colStruct.colWidth = 4; colStruct.tokenFlag = false; - colStruct.colDataType = CalpontSystemCatalog::INT; + colStruct.colDataType = WriteEngine::INT; colStructs.push_back(colStruct); int error; std::string err; @@ -1444,8 +2330,6 @@ void DDLPackageProcessor::updateSyscolumns(execplan::CalpontSystemCatalog::SCN t } } - -#endif void DDLPackageProcessor::returnOIDs(execplan::CalpontSystemCatalog::RIDList& ridList, execplan::CalpontSystemCatalog::DictOIDList& dictOIDList) { @@ -1494,7 +2378,7 @@ void DDLPackageProcessor::returnOIDs(execplan::CalpontSystemCatalog::RIDList& ri } } -void DDLPackageProcessor::findColumnData(uint32_t sessionID, execplan::CalpontSystemCatalog::TableName& systableName, +void DDLPackageProcessor::findColumnData(u_int32_t sessionID, execplan::CalpontSystemCatalog::TableName& systableName, const std::string& colName, DDLColumn& sysCol) { @@ -1570,14 +2454,14 @@ void DDLPackageProcessor::convertRidToColumn(uint64_t& rid, unsigned& dbRoot, un rid = relRidInThisExtent + numExtentsInThisSegPart * extentRows; } -int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID) +int DDLPackageProcessor::rollBackTransaction(u_int64_t uniqueId, BRM::TxnID txnID, u_int32_t sessionID) { ByteStream bytestream; bytestream << (ByteStream::byte) WE_SVR_ROLLBACK_BLOCKS; bytestream << uniqueId; bytestream << sessionID; - bytestream << (uint32_t)txnID.id; - uint32_t msgRecived = 0; + bytestream << (u_int32_t)txnID.id; + uint msgRecived = 0; fWEClient->write_to_all(bytestream); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -1614,7 +2498,7 @@ int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID bytestream << (ByteStream::byte) WE_SVR_ROLLBACK_VERSION; bytestream << uniqueId; bytestream << sessionID; - bytestream << (uint32_t) txnID.id; + bytestream << (u_int32_t) txnID.id; fWEClient->write_to_all(bytestream); bsIn.reset(new ByteStream()); msgRecived = 0; @@ -1645,12 +2529,50 @@ int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID return rc; } -int DDLPackageProcessor::commitTransaction(uint64_t uniqueId, BRM::TxnID txnID) +int DDLPackageProcessor::commitTransaction(u_int64_t uniqueId, BRM::TxnID txnID) { - int rc = fDbrm->vbCommit(txnID.id); + int rc = fDbrm.vbCommit(txnID.id); return rc; } +void DDLPackageProcessor::convertDecimal (ColumnDef* colDefPtr) +{ + //@Bug 2089 decimal precision default to 10 if 0 is used. + if (colDefPtr->fType->fPrecision <= 0) + colDefPtr->fType->fPrecision = 10; + + if (colDefPtr->fType->fPrecision == -1 || colDefPtr->fType->fPrecision == 0) + { + colDefPtr->fType->fType = DDL_BIGINT; + colDefPtr->fType->fLength = 8; + colDefPtr->fType->fScale = 0; + } + else if ((colDefPtr->fType->fPrecision > 0) && (colDefPtr->fType->fPrecision < 3)) + { + //dataType = CalpontSystemCatalog::TINYINT; + colDefPtr->fType->fType = DDL_TINYINT; + colDefPtr->fType->fLength = 1; + } + + else if (colDefPtr->fType->fPrecision < 5 && (colDefPtr->fType->fPrecision > 2)) + { + //dataType = CalpontSystemCatalog::SMALLINT; + colDefPtr->fType->fType = DDL_SMALLINT; + colDefPtr->fType->fLength = 2; + } + else if (colDefPtr->fType->fPrecision > 4 && colDefPtr->fType->fPrecision < 10) + { + //dataType = CalpontSystemCatalog::INT; + colDefPtr->fType->fType = DDL_INT; + colDefPtr->fType->fLength = 4; + } + else if (colDefPtr->fType->fPrecision > 9 && colDefPtr->fType->fPrecision < 19) + { + //dataType = CalpontSystemCatalog::BIGINT; + colDefPtr->fType->fType = DDL_BIGINT; + colDefPtr->fType->fLength = 8; + } +} } // namespace // vim:ts=4 sw=4: diff --git a/dbcon/ddlpackageproc/ddlpackageprocessor.h b/dbcon/ddlpackageproc/ddlpackageprocessor.h index 9e72d461..6ad76d1b 100644 --- a/dbcon/ddlpackageproc/ddlpackageprocessor.h +++ b/dbcon/ddlpackageproc/ddlpackageprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: ddlpackageprocessor.h 9627 2013-06-18 13:59:21Z rdempsey $ + * $Id: ddlpackageprocessor.h 9038 2012-10-29 22:13:24Z zzhu $ * * ***********************************************************************/ @@ -24,7 +24,6 @@ #ifndef DDLPACKAGEPROCESSOR_H #define DDLPACKAGEPROCESSOR_H -#include #include #include #include @@ -44,15 +43,14 @@ #include "we_define.h" #include "writeengine.h" #include "columnresult.h" +#include "brmtypes.h" #include "we_clients.h" #include "liboamcpp.h" - #if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT #endif - //#define IDB_DDL_DEBUG namespace ddlpackageprocessor { @@ -222,7 +220,7 @@ class DDLPackageProcessor unsigned int size() {return static_cast(sysDataVec.size());} int findColumn(const execplan::CalpontSystemCatalog::OID& columnOID) { - for(uint32_t i = 0; i < sysDataVec.size(); i++) { + for(uint i = 0; i < sysDataVec.size(); i++) { if(sysDataVec[i]->ColumnOID() == columnOID) { return i; } @@ -234,12 +232,10 @@ class DDLPackageProcessor /** @brief constructor */ - DDLPackageProcessor(BRM::DBRM* aDbrm) : fStartingColOID(0), fDDLLoggingId(23), fDebugLevel( NONE ) + DDLPackageProcessor() : fStartingColOID(0), fDDLLoggingId(23), fDebugLevel( NONE ) { - fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DDLPROC); + fWEClient = WriteEngine::WEClients::instance(WriteEngine::WEClients::DDLPROC); fPMCount = fWEClient->getPmCount(); - fDbrm = aDbrm; - //std::cout << "in DDLPackageProcessor constructor " << this << std::endl; } /** @brief destructor @@ -327,7 +323,7 @@ class DDLPackageProcessor std::vector& oidList, uint64_t uniqueId); - // EXPORT void createOpenTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, execplan::CalpontSystemCatalog::TableName tableName); + EXPORT void createOpenTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, execplan::CalpontSystemCatalog::TableName tableName); /** @brief create and open log file to log a truncae table information * @@ -363,7 +359,7 @@ class DDLPackageProcessor * * @param dateType the parsed ddl data type */ - execplan::CalpontSystemCatalog::ColDataType convertDataType(int dataType); + int convertDataType(int dataType); /** @brief get the null representation for the given column type * @@ -430,8 +426,8 @@ class DDLPackageProcessor * @param result the result of the operation * @param tableDef the table definition */ - //void writeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, - // ddlpackage::TableDef& tableDef, uint32_t tableWithAutoi=0); + void writeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, + ddlpackage::TableDef& tableDef, uint32_t tableWithAutoi=0); /** @brief write the table columns meta data to the SYSCOLUMN table * @@ -440,9 +436,9 @@ class DDLPackageProcessor * @param tableDefCols the table columns definition * @param qualifiedName the name of catalog, schema, object names */ - //void writeSysColumnMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, - // ddlpackage::ColumnDefList& tableDefCols, - // ddlpackage::QualifiedName& qualifiedName, int colpos, bool alterFlag=false ); + void writeSysColumnMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, + ddlpackage::ColumnDefList& tableDefCols, + ddlpackage::QualifiedName& qualifiedName, int colpos, bool alterFlag=false ); /** @brief write the table constraint meta data to the SYSCONSTRAINT table * @@ -451,7 +447,7 @@ class DDLPackageProcessor * @param constraintList the table constrain list * @param qualifiedName the name of catalog, schema, object names */ - // void writeTableSysConstraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + // void writeTableSysConstraintMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // ddlpackage::TableConstraintDefList& constraintList, ddlpackage::QualifiedName& // qualifiedName, bool alterFlag=false ); /** @brief write the table constraint meta data to the SYSCONSTRAINTCOL table @@ -461,7 +457,7 @@ class DDLPackageProcessor * @param constraintList the table constrain list * @param qualifiedName the name of catalog, schema, object names */ - // void writeTableSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + // void writeTableSysConstraintColMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, // const DDLResult& result, ddlpackage::TableConstraintDefList& constraintList, // ddlpackage::QualifiedName& qualifiedName, bool alterFlag=false ); @@ -472,7 +468,7 @@ class DDLPackageProcessor * @param constraintList the table constrain list * @param qualifiedName the name of catalog, schema, object names */ -// void writeColumnSysConstraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, +// void writeColumnSysConstraintMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, // ddlpackage::ColumnDefList& tableDefCols, // ddlpackage::QualifiedName& qualifiedName ); @@ -482,7 +478,7 @@ class DDLPackageProcessor * @param result the result of the operation * @param tableDef the table definition */ -// void writeColumnSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, +// void writeColumnSysConstraintColMetaData(u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, // const DDLResult& result, ddlpackage::ColumnDefList& tableDefCols, // ddlpackage::QualifiedName& qualifiedName); @@ -495,10 +491,10 @@ class DDLPackageProcessor * @param consDef the table constraint * @param indexName name of the index */ - // void writeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, - // ddlpackage::QualifiedName& qualifiedName, - // ddlpackage::DDL_CONSTRAINTS type, - // std::string& indexName, bool multicol, bool alterFlag=false); + void writeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, + ddlpackage::QualifiedName& qualifiedName, + ddlpackage::DDL_CONSTRAINTS type, + std::string& indexName, bool multicol, bool alterFlag=false); /** @brief write the index meta data to the SYSINDEXCOL table * @@ -508,10 +504,10 @@ class DDLPackageProcessor * @param constraintCols the list of columns in this index * @param indexName name of the index */ - // void writeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, -//ddlpackage::QualifiedName& qualifiedName, - // ddlpackage::ColumnNameList& constraintCols, - // std::string& indexName, bool alterFlag=false); + void writeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, + ddlpackage::QualifiedName& qualifiedName, + ddlpackage::ColumnNameList& constraintCols, + std::string& indexName, bool alterFlag=false); /** @brief remove all indexes for the supplied table from the SYSINDEX table * @@ -519,8 +515,8 @@ class DDLPackageProcessor * @param result the result of the operation * @param tableName the qualified name of the table */ - //void removeSysIndexMetaDataForTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, - // DDLResult& result, ddlpackage::QualifiedName& tableName); + void removeSysIndexMetaDataForTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + DDLResult& result, ddlpackage::QualifiedName& tableName); /** @brief remove all index columns for the supplied table from the SYSINDEXCOL table * @@ -528,8 +524,8 @@ class DDLPackageProcessor * @param result the result of the operation * @param tableName the qualified name of the table */ - // void removeSysIndexColMetaDataForTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, - // DDLResult& result, ddlpackage::QualifiedName& tableName); + void removeSysIndexColMetaDataForTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + DDLResult& result, ddlpackage::QualifiedName& tableName); /** @brief remove an index from the SYSINDEX table * @@ -537,8 +533,8 @@ class DDLPackageProcessor * @param result the result of the operation * @param indexName the qualified name of the index */ - // void removeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& indexName); + void removeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& indexName); /** @brief remove index columns from the SYSINDEXCOL table * @@ -546,8 +542,8 @@ class DDLPackageProcessor * @param result the result of the operation * @param indexName the qualified name of the index */ - // void removeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& indexName); + void removeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& indexName); /** @brief remove the table meta data from the SYSTABLE table * @@ -555,8 +551,8 @@ class DDLPackageProcessor * @param result the result of the operation * @param tableName the qualified name of the table to remove */ - // void removeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& tableName); + void removeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& tableName); /** @brief remove the column meta data from the SYSCOLUMN table * @@ -565,8 +561,8 @@ class DDLPackageProcessor * @param tableName the qualified name of the table whose columns * are to be removed */ - // void removeSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& tableName); + void removeSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& tableName); /** @brief remove the column meta data from the SYSCOLUMN table * @@ -575,8 +571,8 @@ class DDLPackageProcessor * @param columnInfo the qualified name of the column * to be removed */ - // void removeColSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& columnInfo); + void removeColSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& columnInfo); /** @brief remove the constraint meta data from the SYSCONSTRAINT table * @@ -585,8 +581,8 @@ class DDLPackageProcessor * @param tableName the qualified name of the table whose constraints * are to be removed */ - // void removeSysContraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& tableName); + void removeSysContraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& tableName); /** @brief remove the constraint meta data from the SYSCONSTRAINT table * @@ -594,9 +590,9 @@ class DDLPackageProcessor * @param result the result of the operation * @param indexName the index name to be removed */ - // void removeSysIndexMetaDataForIndex(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, - // DDLResult& result, - // execplan::CalpontSystemCatalog::IndexNameList& indexNameList); + void removeSysIndexMetaDataForIndex(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, + DDLResult& result, + execplan::CalpontSystemCatalog::IndexNameList& indexNameList); /** @brief remove the column constraint meta data from the SYSCONSTRAINTCOL table * @@ -605,16 +601,15 @@ class DDLPackageProcessor * @param tableName the qualified name of the table whose column constraints * are to be removed */ - // void removeSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, - // ddlpackage::QualifiedName& tableName); + void removeSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, + ddlpackage::QualifiedName& tableName); /** @brief remove the column constraint meta data from the SYSCONSTRAINT table * * @param txnID the transaction id * @param result the result of the operation * @param constrintNames the names of the constraints * are to be removed - */ -#if 0 + */ void removeSysContraintMetaDataForConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, execplan::CalpontSystemCatalog::IndexNameList& constrintNames); @@ -644,6 +639,13 @@ class DDLPackageProcessor void createColumnFiles(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, ddlpackage::ColumnDefList& tableDefCols, const int useDBRoot, const uint32_t partitionNum=0); + /** @brief create the physical index files + * + * @param txnID the transaction id + * @param result the result of the operation + */ + void createIndexFiles(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result); + /** @brief update the SYSCOLUMN table * * @param txnID the transaction id @@ -665,7 +667,7 @@ class DDLPackageProcessor */ void removeIndexFiles(execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, execplan::CalpontSystemCatalog::IndexOIDList& idxOIDList); -#endif + /** @brief return the OIDs used by the database objects * @@ -674,7 +676,7 @@ class DDLPackageProcessor */ void returnOIDs(execplan::CalpontSystemCatalog::RIDList& ridList, execplan::CalpontSystemCatalog::DictOIDList& dictOIDList); - + /** * @brief convert a columns data, represnted as a string, to it's native * data type @@ -757,13 +759,14 @@ class DDLPackageProcessor WriteEngine::WriteEngineWrapper fWriteEngine; - BRM::DBRM* fDbrm; + BRM::DBRM fDbrm; execplan::SessionManager fSessionManager; - uint32_t fPMCount; + uint fPMCount; WriteEngine::WEClients* fWEClient; + IndexOIDList fIndexOIDList; DictionaryOIDList fDictionaryOIDList; // store oids used during table and index creation @@ -801,6 +804,7 @@ class DDLPackageProcessor int rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID); int commitTransaction(uint64_t uniqueId, BRM::TxnID txnID); + void convertDecimal (ddlpackage::ColumnDef* colDefPtr); private: /** @brief clean beginning and ending glitches and spaces from string diff --git a/dbcon/ddlpackageproc/ddlpackageprocessorfactory.cpp b/dbcon/ddlpackageproc/ddlpackageprocessorfactory.cpp index b1280fa3..ad573f23 100644 --- a/dbcon/ddlpackageproc/ddlpackageprocessorfactory.cpp +++ b/dbcon/ddlpackageproc/ddlpackageprocessorfactory.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ddlpackageprocessorfactory.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: ddlpackageprocessorfactory.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackageproc/ddlpackageprocessorfactory.h b/dbcon/ddlpackageproc/ddlpackageprocessorfactory.h index 99b6eb41..2ed7edfb 100644 --- a/dbcon/ddlpackageproc/ddlpackageprocessorfactory.h +++ b/dbcon/ddlpackageproc/ddlpackageprocessorfactory.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ddlpackageprocessorfactory.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: ddlpackageprocessorfactory.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackageproc/dropindexprocessor.cpp b/dbcon/ddlpackageproc/dropindexprocessor.cpp index 38883ead..f3bfde0b 100644 --- a/dbcon/ddlpackageproc/dropindexprocessor.cpp +++ b/dbcon/ddlpackageproc/dropindexprocessor.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dropindexprocessor.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dropindexprocessor.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackageproc/dropindexprocessor.h b/dbcon/ddlpackageproc/dropindexprocessor.h index 635dfae5..dbb4ae42 100644 --- a/dbcon/ddlpackageproc/dropindexprocessor.h +++ b/dbcon/ddlpackageproc/dropindexprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dropindexprocessor.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dropindexprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/ddlpackageproc/droppartitionprocessor.cpp b/dbcon/ddlpackageproc/droppartitionprocessor.cpp index ad3de775..6535acf8 100644 --- a/dbcon/ddlpackageproc/droppartitionprocessor.cpp +++ b/dbcon/ddlpackageproc/droppartitionprocessor.cpp @@ -20,7 +20,9 @@ * * ***********************************************************************/ +#define DROPPARTITIONPROC_DLLEXPORT #include "droppartitionprocessor.h" +#undef DROPPARTITIONPROC_DLLEXPORT #include "messagelog.h" #include "sqllogger.h" @@ -51,7 +53,7 @@ namespace ddlpackageprocessor VERBOSE_INFO("Getting current txnID"); int rc = 0; - rc = fDbrm->isReadWrite(); + rc = fDbrm.isReadWrite(); BRM::TxnID txnID; txnID.id= fTxnid.id; txnID.valid= fTxnid.valid; @@ -73,40 +75,11 @@ namespace ddlpackageprocessor CalpontSystemCatalog::DictOIDList dictOIDList; execplan::CalpontSystemCatalog::ROPair roPair; uint32_t processID = 0; - uint64_t uniqueID = 0; + u_int64_t uniqueID = 0; uint32_t sessionID = dropPartitionStmt.fSessionID; std::string processName("DDLProc"); - uint64_t uniqueId = 0; - - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - logging::Message::Args args; - logging::Message message(9); - args.add(ex.what()); - message.format(args); - result.result = ALTER_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - catch ( ... ) - { - logging::Message::Args args; - logging::Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = ALTER_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - - string stmt = dropPartitionStmt.fSql + "|" + dropPartitionStmt.fTableName->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, sessionID, txnID.id); + u_int64_t uniqueId = fDbrm.getUnique64(); + SQLLogger logger(dropPartitionStmt.fSql, fDDLLoggingId, sessionID, txnID.id); try { @@ -127,14 +100,14 @@ namespace ddlpackageprocessor processID = ::getpid(); oam::OamCache * oamcache = OamCache::makeOamCache(); std::vector pmList = oamcache->getModuleIds(); - std::vector pms; + std::vector pms; for (unsigned i=0; i < pmList.size(); i++) { - pms.push_back((uint32_t)pmList[i]); + pms.push_back((uint)pmList[i]); } try { - uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); + uniqueID = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { @@ -178,7 +151,7 @@ namespace ddlpackageprocessor processName = "DDLProc"; try { - uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); + uniqueID = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { @@ -235,7 +208,7 @@ namespace ddlpackageprocessor //Mark the partition disabled from extent map string emsg; - rc = fDbrm->markPartitionForDeletion( oidList, dropPartitionStmt.fPartitions, emsg); + rc = fDbrm.markPartitionForDeletion( oidList, dropPartitionStmt.fPartitions, emsg); if (rc != 0 && rc !=BRM::ERR_PARTITION_DISABLED && rc != BRM::ERR_INVALID_OP_LAST_PARTITION && rc != BRM::ERR_NOT_EXIST_PARTITION) @@ -247,7 +220,7 @@ namespace ddlpackageprocessor set outOfServicePartitions; // only log partitions that are successfully marked disabled. - rc = fDbrm->getOutOfServicePartitions(oidList[0], outOfServicePartitions); + rc = fDbrm.getOutOfServicePartitions(oidList[0], outOfServicePartitions); if (rc != 0) { @@ -275,7 +248,7 @@ namespace ddlpackageprocessor //Remove the partition from extent map emsg.clear(); - rc = fDbrm->deletePartition( oidList, dropPartitionStmt.fPartitions, emsg); + rc = fDbrm.deletePartition( oidList, dropPartitionStmt.fPartitions, emsg); if ( rc != 0 ) throw std::runtime_error(emsg); } @@ -296,7 +269,7 @@ namespace ddlpackageprocessor result.result = DROP_ERROR; result.message = message; try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; @@ -320,7 +293,7 @@ namespace ddlpackageprocessor result.result = DROP_ERROR; result.message = message; try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; @@ -334,7 +307,7 @@ namespace ddlpackageprocessor //Remove the log file //release the transaction try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); deleteLogFile(DROPPART_LOG, roPair.objnum, uniqueId); } catch (std::exception&) { diff --git a/dbcon/ddlpackageproc/droppartitionprocessor.h b/dbcon/ddlpackageproc/droppartitionprocessor.h index 905ccb3b..810d573b 100644 --- a/dbcon/ddlpackageproc/droppartitionprocessor.h +++ b/dbcon/ddlpackageproc/droppartitionprocessor.h @@ -26,7 +26,7 @@ #include "ddlpackageprocessor.h" -#if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(DROPPARTITIONPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -41,7 +41,6 @@ namespace ddlpackageprocessor class DropPartitionProcessor : public DDLPackageProcessor { public: - DropPartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} /** @brief process a drop table statement * * @param dropTableStmt the drop table statement diff --git a/dbcon/ddlpackageproc/droptableprocessor.cpp b/dbcon/ddlpackageproc/droptableprocessor.cpp index 7c2c27a6..e8696d0d 100644 --- a/dbcon/ddlpackageproc/droptableprocessor.cpp +++ b/dbcon/ddlpackageproc/droptableprocessor.cpp @@ -16,899 +16,403 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: droptableprocessor.cpp 9744 2013-08-07 03:32:19Z bwilkinson $ + * $Id: droptableprocessor.cpp 8923 2012-09-19 18:14:01Z dcathey $ * * ***********************************************************************/ -#include -#include -#include -using namespace std; - +#define DROPTABLEPROC_DLLEXPORT #include "droptableprocessor.h" +#undef DROPTABLEPROC_DLLEXPORT +#include "messagelog.h" +#include "sqllogger.h" +#include "cacheutils.h" #include "we_messages.h" +#include "bytestream.h" #include "we_ddlcommandclient.h" -using namespace WriteEngine; - -#include "cacheutils.h" +#include "oamcache.h" using namespace cacheutils; - -#include "bytestream.h" -using namespace messageqcpp; - -#include "sqllogger.h" -#include "messagelog.h" -using namespace logging; - -#include "calpontsystemcatalog.h" +using namespace std; using namespace execplan; - -#include "oamcache.h" +using namespace logging; +using namespace WriteEngine; +using namespace messageqcpp; using namespace oam; +using namespace boost; namespace ddlpackageprocessor { -DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::DropTableStatement& dropTableStmt) -{ - SUMMARY_INFO("DropTableProcessor::processPackage"); - - DDLResult result; - result.result = NO_ERROR; - std::string err; - VERBOSE_INFO(dropTableStmt); - - // Commit current transaction. - // all DDL statements cause an implicit commit - VERBOSE_INFO("Getting current txnID"); - ByteStream::byte rc = 0; - BRM::TxnID txnID; - txnID.id= fTxnid.id; - txnID.valid= fTxnid.valid; - int rc1 = 0; - rc1= fDbrm->isReadWrite(); - if (rc1 != 0 ) - { - Message::Args args; - Message message(9); - args.add("Unable to execute the statement due to DBRM is read only"); - message.format(args); - result.result = DROP_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - - string stmt = dropTableStmt.fSql + "|" + dropTableStmt.fTableName->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, dropTableStmt.fSessionID, txnID.id); - - std::vector oidList; - CalpontSystemCatalog::RIDList tableColRidList; - CalpontSystemCatalog::DictOIDList dictOIDList; - execplan::CalpontSystemCatalog::ROPair roPair; - std::string errorMsg; - ByteStream bytestream; - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - Message::Args args; - Message message(9); - args.add(ex.what()); - message.format(args); - result.result = DROP_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - catch ( ... ) - { - Message::Args args; - Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = DROP_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - - fWEClient->addQueue(uniqueId); - int pmNum = 1; - boost::shared_ptr bsIn; - uint64_t tableLockId = 0; - OamCache* oamcache = OamCache::makeOamCache(); - std::vector moduleIds = oamcache->getModuleIds(); - try - { - //check table lock - boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropTableStmt.fSessionID); - systemCatalogPtr->identity(CalpontSystemCatalog::EC); - systemCatalogPtr->sessionID(dropTableStmt.fSessionID); - CalpontSystemCatalog::TableName tableName; - tableName.schema = dropTableStmt.fTableName->fSchema; - tableName.table = dropTableStmt.fTableName->fName; - roPair = systemCatalogPtr->tableRID( tableName ); + DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::DropTableStatement& dropTableStmt) + { + SUMMARY_INFO("DropTableProcessor::processPackage"); + + DDLResult result; + result.result = NO_ERROR; + std::string err; + VERBOSE_INFO(dropTableStmt); - uint32_t processID = ::getpid(); - int32_t txnid = txnID.id; - int32_t sessionId = dropTableStmt.fSessionID; - std::string processName("DDLProc"); - int i = 0; - - std::vector pms; - for (unsigned i=0; i < moduleIds.size(); i++) - { - pms.push_back((uint32_t)moduleIds[i]); - } - - try { - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); - } - catch (std::exception&) + // Commit current transaction. + // all DDL statements cause an implicit commit + VERBOSE_INFO("Getting current txnID"); + ByteStream::byte rc = 0; + BRM::TxnID txnID; + txnID.id= fTxnid.id; + txnID.valid= fTxnid.valid; + int rc1 = 0; + rc1= fDbrm.isReadWrite(); + if (rc1 != 0 ) { - throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + logging::Message::Args args; + logging::Message message(9); + args.add("Unable to execute the statement due to DBRM is read only"); + message.format(args); + result.result = DROP_ERROR; + result.message = message; + fSessionManager.rolledback(txnID); + return result; } - if ( tableLockId == 0 ) - { - int waitPeriod = 10; - int sleepTime = 100; // sleep 100 milliseconds between checks - int numTries = 10; // try 10 times per second - waitPeriod = WriteEngine::Config::getWaitPeriod(); - numTries = waitPeriod * 10; - struct timespec rm_ts; - - rm_ts.tv_sec = sleepTime/1000; - rm_ts.tv_nsec = sleepTime%1000 *1000000; + SQLLogger logger(dropTableStmt.fSql, fDDLLoggingId, dropTableStmt.fSessionID, txnID.id); + + std::vector oidList; + CalpontSystemCatalog::RIDList tableColRidList; + CalpontSystemCatalog::DictOIDList dictOIDList; + execplan::CalpontSystemCatalog::ROPair roPair; + std::string errorMsg; + ByteStream bytestream; + uint64_t uniqueId = fDbrm.getUnique64(); + fWEClient->addQueue(uniqueId); + int pmNum = 1; + boost::shared_ptr bsIn; + uint64_t tableLockId = 0; + OamCache * oamcache = OamCache::makeOamCache(); + std::vector moduleIds = oamcache->getModuleIds(); + bool lockReleased = true; + try + { + //check table lock + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropTableStmt.fSessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + systemCatalogPtr->sessionID(dropTableStmt.fSessionID); + CalpontSystemCatalog::TableName tableName; + tableName.schema = dropTableStmt.fTableName->fSchema; + tableName.table = dropTableStmt.fTableName->fName; + roPair = systemCatalogPtr->tableRID( tableName ); - for (; i < numTries; i++) + u_int32_t processID = ::getpid(); + int32_t txnid = txnID.id; + int32_t sessionId = dropTableStmt.fSessionID; + std::string processName("DDLProc"); + int i = 0; + + std::vector pms; + for (unsigned i=0; i < moduleIds.size(); i++) { + pms.push_back((uint)moduleIds[i]); + } + + try { + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + } + catch (std::exception&) + { + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + } + + if ( tableLockId == 0 ) + { + int waitPeriod = 10; + int sleepTime = 100; // sleep 100 milliseconds between checks + int numTries = 10; // try 10 times per second + waitPeriod = Config::getWaitPeriod(); + numTries = waitPeriod * 10; + struct timespec rm_ts; + + rm_ts.tv_sec = sleepTime/1000; + rm_ts.tv_nsec = sleepTime%1000 *1000000; + + for (; i < numTries; i++) + { #ifdef _MSC_VER - Sleep(rm_ts.tv_sec * 1000); + Sleep(rm_ts.tv_sec * 1000); #else - struct timespec abs_ts; - do - { - abs_ts.tv_sec = rm_ts.tv_sec; - abs_ts.tv_nsec = rm_ts.tv_nsec; - } - while(nanosleep(&abs_ts,&rm_ts) < 0); + struct timespec abs_ts; + do + { + abs_ts.tv_sec = rm_ts.tv_sec; + abs_ts.tv_nsec = rm_ts.tv_nsec; + } + while(nanosleep(&abs_ts,&rm_ts) < 0); #endif - try { - processID = ::getpid(); - txnid = txnID.id; - sessionId = dropTableStmt.fSessionID;; - processName = "DDLProc"; - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + try { + processID = ::getpid(); + txnid = txnID.id; + sessionId = dropTableStmt.fSessionID;; + processName = "DDLProc"; + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + } + catch (std::exception&) + { + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + } + + if (tableLockId > 0) + break; } - catch (std::exception&) + if (i >= numTries) //error out { - throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - - if (tableLockId > 0) - break; + logging::Message::Args args; + args.add(processName); + args.add((uint64_t)processID); + args.add(sessionId); + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); + } } - if (i >= numTries) //error out - { - Message::Args args; - args.add(processName); - args.add((uint64_t)processID); - args.add(sessionId); - throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); - } - } - - // 1. Get the OIDs for the columns - // 2. Get the OIDs for the dictionaries - // 3. Save the OIDs to a log file - // 4. Remove the Table from SYSTABLE - // 5. Remove the columns from SYSCOLUMN - // 6. Commit the changes made to systables - // 7. Flush PrimProc Cache - // 8. Update extent map - // 9. Remove the column and dictionary files - // 10.Return the OIDs + + // 1. Get the OIDs for the columns + // 2. Get the OIDs for the dictionaries + // 3. Save the OIDs to a log file + // 4. Remove the Table from SYSTABLE + // 5. Remove the columns from SYSCOLUMN + // 6. Commit the changes made to systables + // 7. Flush PrimProc Cache + // 8. Update extent map + // 9. Remove the column and dictionary files + // 10.Return the OIDs - CalpontSystemCatalog::TableName userTableName; - userTableName.schema = dropTableStmt.fTableName->fSchema; - userTableName.table = dropTableStmt.fTableName->fName; + CalpontSystemCatalog::TableName userTableName; + userTableName.schema = dropTableStmt.fTableName->fSchema; + userTableName.table = dropTableStmt.fTableName->fName; - tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); + tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); - dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); - Oam oam; + dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); + Oam oam; - //Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format - for ( unsigned i=0; i < tableColRidList.size(); i++ ) - { - if ( tableColRidList[i].objnum > 3000 ) - oidList.push_back( tableColRidList[i].objnum ); - } - for ( unsigned i=0; i < dictOIDList.size(); i++ ) - { - if ( dictOIDList[i].dictOID > 3000 ) - oidList.push_back( dictOIDList[i].dictOID ); - } - - //get a unique number - VERBOSE_INFO("Removing the SYSTABLE meta data"); + //Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format + for ( unsigned i=0; i < tableColRidList.size(); i++ ) + { + if ( tableColRidList[i].objnum > 3000 ) + oidList.push_back( tableColRidList[i].objnum ); + } + for ( unsigned i=0; i < dictOIDList.size(); i++ ) + { + if ( dictOIDList[i].dictOID > 3000 ) + oidList.push_back( dictOIDList[i].dictOID ); + } + + //get a unique number + VERBOSE_INFO("Removing the SYSTABLE meta data"); #ifdef IDB_DDL_DEBUG cout << "Removing the SYSTABLEs meta data" << endl; #endif - bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSTABLE; - bytestream << uniqueId; - bytestream << (uint32_t) dropTableStmt.fSessionID; - bytestream << (uint32_t)txnID.id; - bytestream << dropTableStmt.fTableName->fSchema; - bytestream << dropTableStmt.fTableName->fName; - - //Find out where systable is - BRM::OID_t sysOid = 1001; - ByteStream::byte rc = 0; - - uint16_t dbRoot; - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - { - result.result =(ResultCode) rc; - Message::Args args; - Message message(9); - args.add("Error while calling getSysCatDBRoot"); - args.add(errorMsg); - result.message = message; - //release transaction - fSessionManager.rolledback(txnID); - return result; - } - - boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); - pmNum = (*dbRootPMMap)[dbRoot]; - try - { - //cout << "deleting systable entries with txnid " << txnID.id << endl; - fWEClient->write(bytestream, (uint32_t)pmNum); -#ifdef IDB_DDL_DEBUG -cout << "Drop table sending WE_SVR_DELETE_SYSTABLES to pm " << pmNum << endl; -#endif - while (1) + bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSTABLES; + bytestream << uniqueId; + bytestream << (u_int32_t) dropTableStmt.fSessionID; + bytestream << (u_int32_t)txnID.id; + bytestream << dropTableStmt.fTableName->fSchema; + bytestream << dropTableStmt.fTableName->fName; + + //Find out where systable is + BRM::OID_t sysOid = 1001; + ByteStream::byte rc = 0; + + u_int16_t dbRoot; + rc = fDbrm.getSysCatDBRoot(sysOid, dbRoot); + if (rc != 0) { - bsIn.reset(new ByteStream()); - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; - break; - } - else { - *bsIn >> rc; - if (rc != 0) { - *bsIn >> errorMsg; - } - break; - } + result.result =(ResultCode) rc; + logging::Message::Args args; + logging::Message message(9); + args.add("Error while calling getSysCatDBRoot"); + args.add(errorMsg); + result.message = message; + //release transaction + fSessionManager.rolledback(txnID); + return result; } - } - catch (runtime_error& ex) //write error - { -#ifdef IDB_DDL_DEBUG -cout << "Drop table got exception" << endl; -#endif - rc = NETWORK_ERROR; - errorMsg = ex.what(); - } - catch (...) - { - rc = NETWORK_ERROR; -#ifdef IDB_DDL_DEBUG -cout << "Drop table got unknown exception" << endl; -#endif - } - - if (rc != 0) - { - Message::Args args; - Message message(9); - args.add("Error in dropping table from systables."); - args.add(errorMsg); - message.format(args); - result.result = (ResultCode)rc; - result.message = message; - //release table lock and session - fSessionManager.rolledback(txnID); - (void)fDbrm->releaseTableLock(tableLockId); - fWEClient->removeQueue(uniqueId); - return result; - } - - //remove from syscolumn - bytestream.restart(); - bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSCOLUMN; - bytestream << uniqueId; - bytestream << (uint32_t) dropTableStmt.fSessionID; - bytestream << (uint32_t)txnID.id; - bytestream << dropTableStmt.fTableName->fSchema; - bytestream << dropTableStmt.fTableName->fName; - - //Find out where syscolumn is - sysOid = 1021; - rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); - if (rc != 0) - { - result.result =(ResultCode) rc; - Message::Args args; - Message message(9); - args.add("Error while calling getSysCatDBRoot"); - args.add(errorMsg); - result.message = message; - //release transaction - fSessionManager.rolledback(txnID); - return result; - } - - pmNum = (*dbRootPMMap)[dbRoot]; - try - { - //cout << "deleting systable entries with txnid " << txnID.id << endl; - fWEClient->write(bytestream, (unsigned)pmNum); + + boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); + pmNum = (*dbRootPMMap)[dbRoot]; + try + { + //cout << "deleting systable entries with txnid " << txnID.id << endl; + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DDL_DEBUG cout << "Drop table sending WE_SVR_DELETE_SYSTABLES to pm " << pmNum << endl; #endif - while (1) - { - bsIn.reset(new ByteStream()); - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error + while (1) { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; - break; - } - else { - *bsIn >> rc; - if (rc != 0) { - *bsIn >> errorMsg; + bsIn.reset(new ByteStream()); + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + rc = NETWORK_ERROR; + errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; + break; + } + else { + *bsIn >> rc; + if (rc != 0) { + *bsIn >> errorMsg; + } + break; } - break; } } - } - catch (runtime_error& ex) //write error - { + catch (runtime_error& ex) //write error + { #ifdef IDB_DDL_DEBUG cout << "Drop table got exception" << endl; #endif - rc = NETWORK_ERROR; - errorMsg = ex.what(); - } - catch (...) - { - rc = NETWORK_ERROR; + rc = NETWORK_ERROR; + errorMsg = ex.what(); + } + catch (...) + { + rc = NETWORK_ERROR; #ifdef IDB_DDL_DEBUG cout << "Drop table got unknown exception" << endl; #endif - } - - if (rc != 0) - { - Message::Args args; - Message message(9); - args.add("Error in dropping table from systables."); - args.add(errorMsg); - message.format(args); - result.result = (ResultCode)rc; - result.message = message; - //release table lock and session - fSessionManager.rolledback(txnID); - (void)fDbrm->releaseTableLock(tableLockId); - fWEClient->removeQueue(uniqueId); - return result; - } - - rc = commitTransaction(uniqueId, txnID); - //cout << "commiting transaction " << txnID.id << " and valid is " << txnID.valid << endl; - if (rc != 0) - fSessionManager.rolledback(txnID); - else - fSessionManager.committed(txnID); - - if (rc != 0) - { - Message::Args args; - Message message(9); - ostringstream oss; - oss << " Commit failed with error code " << rc; - args.add(oss.str()); - fSessionManager.rolledback(txnID); - (void)fDbrm->releaseTableLock(tableLockId); - message.format(args); - result.result = (ResultCode)rc; - result.message = message; - fWEClient->removeQueue(uniqueId); - return result; - } + } - // Log the DDL statement - logDDL(dropTableStmt.fSessionID, txnID.id, dropTableStmt.fSql, dropTableStmt.fOwner); - } - catch (std::exception& ex) - { - result.result = DROP_ERROR; - Message::Args args; - Message message(9); - args.add("Drop table failed due to "); - args.add(ex.what()); - fSessionManager.rolledback(txnID); - try { - (void)fDbrm->releaseTableLock(tableLockId); - } - catch (std::exception&) - { - args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - message.format( args ); - result.message = message; - fWEClient->removeQueue(uniqueId); - return result; - } - catch (...) - { - result.result = DROP_ERROR; - errorMsg = "Error in getting information from system catalog or from dbrm."; - Message::Args args; - Message message(9); - args.add("Drop table failed due to "); - args.add(errorMsg); - fSessionManager.rolledback(txnID); - try { - (void)fDbrm->releaseTableLock(tableLockId); - } - catch (std::exception&) - { - args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - message.format( args ); - result.message = message; - fWEClient->removeQueue(uniqueId); - return result; - } - - try { - (void)fDbrm->releaseTableLock(tableLockId); - } - catch (std::exception&) - { - result.result = DROP_ERROR; - Message::Args args; - Message message(9); - args.add("Drop table failed due to "); - args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - fSessionManager.rolledback(txnID); - message.format( args ); - result.message = message; - fWEClient->removeQueue(uniqueId); - return result; - } - - //Save the oids to a file - try { - createWriteDropLogFile( roPair.objnum, uniqueId, oidList ); - } - catch (std::exception& ex) - { - result.result = WARNING; - Message::Args args; - Message message(9); - args.add("Drop table failed due to "); - args.add(ex.what()); - message.format(args); - result.message = message; - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - return result; - } - // Bug 4208 Drop the PrimProcFDCache before droping the column files - // FOr Windows, this ensures (most likely) that the column files have - // no open handles to hinder the deletion of the files. - rc = cacheutils::dropPrimProcFdCache(); - - //Drop files - bytestream.restart(); - bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; - bytestream << uniqueId; - bytestream << (uint32_t) oidList.size(); - for (unsigned i=0; i < oidList.size(); i++) - { - bytestream << (uint32_t) oidList[i]; - } -#ifdef IDB_DDL_DEBUG -cout << "Drop table removing column files" << endl; -#endif - uint32_t msgRecived = 0; - try { - fWEClient->write_to_all(bytestream); - - bsIn.reset(new ByteStream()); - ByteStream::byte tmp8; - while (1) - { - if (msgRecived == fWEClient->getPmCount()) - break; - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error + if (rc != 0) { - rc = NETWORK_ERROR; + logging::Message::Args args; + logging::Message message(9); + args.add("Error in dropping table from systables."); + args.add(errorMsg); + message.format(args); + result.result = (ResultCode)rc; + result.message = message; + //release table lock and session + fSessionManager.rolledback(txnID); + lockReleased = fDbrm.releaseTableLock(tableLockId); fWEClient->removeQueue(uniqueId); - break; - } - else { - *bsIn >> tmp8; - rc = tmp8; - if (rc != 0) { - *bsIn >> errorMsg; - fWEClient->removeQueue(uniqueId); - break; - } + return result; + } + + rc = commitTransaction(uniqueId, txnID); + //cout << "commiting transaction " << txnID.id << " and valid is " << txnID.valid << endl; + if (rc != 0) + fSessionManager.rolledback(txnID); else - msgRecived++; + fSessionManager.committed(txnID); + + if (rc != 0) + { + logging::Message::Args args; + logging::Message message(9); + ostringstream oss; + oss << " Commit failed with error code " << rc; + args.add(oss.str()); + fSessionManager.rolledback(txnID); + bool lockReleased = true; + lockReleased = fDbrm.releaseTableLock(tableLockId); + message.format(args); + result.result = (ResultCode)rc; + result.message = message; + fWEClient->removeQueue(uniqueId); + return result; } - } - } - catch (std::exception& ex) - { - result.result = WARNING; - Message::Args args; - Message message(9); - args.add("Drop table failed due to "); - args.add(ex.what()); - message.format(args); - result.message = message; - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - return result; - } - catch (...) - { - result.result = WARNING; - errorMsg = "Error in getting information from system catalog or from dbrm."; - Message::Args args; - Message message(9); - args.add("Drop table failed due to "); - args.add(errorMsg); - message.format(args); - result.message = message; - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - return result; - } - //Drop PrimProc FD cache - rc = cacheutils::dropPrimProcFdCache(); - //Flush primProc cache - rc = cacheutils::flushOIDsFromCache( oidList ); - //Delete extents from extent map - rc = fDbrm->deleteOIDs(oidList); - - if (rc != 0) - { - Message::Args args; - Message message(1); - args.add("Table dropped with warning "); - args.add( "Remove from extent map failed." ); - args.add(""); - args.add(""); - message.format( args ); - - result.result = WARNING; - result.message = message; - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - return result; - } - - //Remove the log file - fWEClient->removeQueue(uniqueId); - deleteLogFile(DROPTABLE_LOG, roPair.objnum, uniqueId); - //release the transaction - //fSessionManager.committed(txnID); - returnOIDs( tableColRidList, dictOIDList ); - return result; - -} - -TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::TruncTableStatement& truncTableStmt) -{ - SUMMARY_INFO("TruncTableProcessor::processPackage"); - // 1. lock the table - // 2. Get the OIDs for the columns - // 3. Get the OIDs for the dictionaries - // 4. Save the OIDs - // 5. Disable all partitions - // 6. Remove the column and dictionary files - // 7. Flush PrimProc Cache - // 8. Update extent map - // 9. Use the OIDs to create new column and dictionary files with abbreviate extent - // 10 Update next value if the table has autoincrement column - - DDLResult result; - result.result = NO_ERROR; - std::string err; - VERBOSE_INFO(truncTableStmt); - - // @Bug 4150. Check dbrm status before doing anything to the table. - int rc = 0; - rc = fDbrm->isReadWrite(); - BRM::TxnID txnID; - txnID.id= fTxnid.id; - txnID.valid= fTxnid.valid; - if (rc != 0 ) - { - Message::Args args; - Message message(9); - args.add("Unable to execute the statement due to DBRM is read only"); - message.format(args); - result.result = DROP_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - - //@Bug 5765 log the schema. - string stmt = truncTableStmt.fSql + "|" + truncTableStmt.fTableName->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, truncTableStmt.fSessionID, txnID.id); - - std::vector columnOidList; - std::vector allOidList; - CalpontSystemCatalog::RIDList tableColRidList; - CalpontSystemCatalog::DictOIDList dictOIDList; - execplan::CalpontSystemCatalog::ROPair roPair; - std::string processName("DDLProc"); - uint32_t processID = ::getpid();; - int32_t txnid = txnID.id; - boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(truncTableStmt.fSessionID); - systemCatalogPtr->identity(CalpontSystemCatalog::EC); - systemCatalogPtr->sessionID(truncTableStmt.fSessionID); - CalpontSystemCatalog::TableInfo tableInfo; - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - Message::Args args; - Message message(9); - args.add(ex.what()); - message.format(args); - result.result = DROP_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - catch ( ... ) - { - Message::Args args; - Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = DROP_ERROR; - result.message = message; - fSessionManager.rolledback(txnID); - return result; - } - fWEClient->addQueue(uniqueId); - int pmNum = 1; - boost::shared_ptr bsIn; - string errorMsg; - uint32_t autoIncColOid = 0; - uint64_t tableLockId = 0; - OamCache * oamcache = OamCache::makeOamCache(); - std::vector moduleIds = oamcache->getModuleIds(); - try - { - //check table lock - - CalpontSystemCatalog::TableName tableName; - tableName.schema = truncTableStmt.fTableName->fSchema; - tableName.table = truncTableStmt.fTableName->fName; - roPair = systemCatalogPtr->tableRID( tableName ); - int32_t sessionId = truncTableStmt.fSessionID; - std::string processName("DDLProc"); - int i = 0; - std::vector pms; - for (unsigned i=0; i < moduleIds.size(); i++) - { - pms.push_back((uint32_t)moduleIds[i]); - } - try { - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + // Log the DDL statement + logging::logDDL(dropTableStmt.fSessionID, txnID.id, dropTableStmt.fSql, dropTableStmt.fOwner); } - catch (std::exception&) - { - throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - - if ( tableLockId == 0 ) + catch (std::exception& ex) { - int waitPeriod = 10; - int sleepTime = 100; // sleep 100 milliseconds between checks - int numTries = 10; // try 10 times per second - waitPeriod = Config::getWaitPeriod(); - numTries = waitPeriod * 10; - struct timespec rm_ts; - - rm_ts.tv_sec = sleepTime/1000; - rm_ts.tv_nsec = sleepTime%1000 *1000000; - - for (; i < numTries; i++) - { -#ifdef _MSC_VER - Sleep(rm_ts.tv_sec * 1000); -#else - struct timespec abs_ts; - do - { - abs_ts.tv_sec = rm_ts.tv_sec; - abs_ts.tv_nsec = rm_ts.tv_nsec; - } - while(nanosleep(&abs_ts,&rm_ts) < 0); -#endif - try { - processID = ::getpid(); - txnid = txnID.id; - sessionId = truncTableStmt.fSessionID; - processName = "DDLProc"; - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); - } - catch (std::exception&) - { - throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - - if (tableLockId > 0) - break; + result.result = DROP_ERROR; + logging::Message::Args args; + logging::Message message(9); + args.add("Drop table failed due to "); + args.add(ex.what()); + fSessionManager.rolledback(txnID); + try { + lockReleased = fDbrm.releaseTableLock(tableLockId); } - if (i >= numTries) //error out + catch (std::exception&) { - Message::Args args; - args.add(processName); - args.add((uint64_t)processID); - args.add(sessionId); - throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); - } + args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + } + message.format( args ); + result.message = message; + fWEClient->removeQueue(uniqueId); + return result; } - CalpontSystemCatalog::TableName userTableName; - userTableName.schema = truncTableStmt.fTableName->fSchema; - userTableName.table = truncTableStmt.fTableName->fName; - - tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); - - dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); - for ( unsigned i=0; i < tableColRidList.size(); i++ ) + catch (...) { - if ( tableColRidList[i].objnum > 3000 ) + result.result = DROP_ERROR; + errorMsg = "Error in getting information from system catalog or from dbrm."; + logging::Message::Args args; + logging::Message message(9); + args.add("Drop table failed due to "); + args.add(errorMsg); + fSessionManager.rolledback(txnID); + try { + lockReleased = fDbrm.releaseTableLock(tableLockId); + } + catch (std::exception&) { - columnOidList.push_back( tableColRidList[i].objnum ); - allOidList.push_back( tableColRidList[i].objnum ); + args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); } + message.format( args ); + result.message = message; + fWEClient->removeQueue(uniqueId); + return result; } - for ( unsigned i=0; i < dictOIDList.size(); i++ ) - { - if ( dictOIDList[i].dictOID > 3000 ) - allOidList.push_back( dictOIDList[i].dictOID ); - } - //Check whether the table has autoincrement column - tableInfo = systemCatalogPtr->tableInfo(userTableName); - } - catch (std::exception& ex) - { - cerr << "TruncateTableProcessor::processPackage: " << ex.what() << endl; - - Message::Args args; - Message message(9); - args.add("Truncate table failed: "); - args.add( ex.what() ); - args.add(""); - fSessionManager.rolledback(txnID); - try { - (void)fDbrm->releaseTableLock(tableLockId); - } - catch (std::exception&) - { - args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - fWEClient->removeQueue(uniqueId); - message.format( args ); - - result.result = TRUNC_ERROR; - result.message = message; - return result; - } - catch (...) - { - cerr << "TruncateTableProcessor::processPackage: caught unknown exception!" << endl; - Message::Args args; - Message message(1); - args.add("Truncate table failed: "); - args.add( "encountered unkown exception" ); - args.add(""); try { - (void)fDbrm->releaseTableLock(tableLockId); + lockReleased = fDbrm.releaseTableLock(tableLockId); } catch (std::exception&) { + result.result = DROP_ERROR; + logging::Message::Args args; + logging::Message message(9); + args.add("Drop table failed due to "); args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - } - fWEClient->removeQueue(uniqueId); - message.format( args ); - - result.result = TRUNC_ERROR; - result.message = message; - return result; - } - - //Save the oids to a file - try { - createWriteTruncateTableLogFile( roPair.objnum, uniqueId, allOidList); - } - catch (std::exception& ex) - { - Message::Args args; - Message message(9); - args.add("Truncate table failed due to "); - args.add(ex.what()); - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - message.format( args ); - //@bug 4515 Release the tablelock as nothing has done to this table. + fSessionManager.rolledback(txnID); + message.format( args ); + result.message = message; + fWEClient->removeQueue(uniqueId); + return result; + } + + //Save the oids to a file try { - (void)fDbrm->releaseTableLock(tableLockId); + createWriteDropLogFile( roPair.objnum, uniqueId, oidList ); } - catch (std::exception&) {} - result.result = TRUNC_ERROR; - result.message = message; - return result; - } - - ByteStream bytestream; - ByteStream::byte tmp8; - try { - //Disable extents first - int rc1 = fDbrm->markAllPartitionForDeletion( allOidList); - if (rc1 != 0) + catch (std::exception& ex) { - string errMsg; - BRM::errString(rc, errMsg); - throw std::runtime_error(errMsg); + result.result = WARNING; + logging::Message::Args args; + logging::Message message(9); + args.add("Drop table failed due to "); + args.add(ex.what()); + result.message = message; + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); + return result; } - - // Bug 4208 Drop the PrimProcFDCache before droping the column files - // FOr Windows, this ensures (most likely) that the column files have - // no open handles to hinder the deletion of the files. - rc = cacheutils::dropPrimProcFdCache(); - - VERBOSE_INFO("Removing files"); + //Drop files + bytestream.restart(); bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; bytestream << uniqueId; - bytestream << (uint32_t) allOidList.size(); - for (unsigned i=0; i < allOidList.size(); i++) + bytestream << (uint32_t) oidList.size(); + for (unsigned i=0; i < oidList.size(); i++) { - bytestream << (uint32_t) allOidList[i]; + bytestream << (uint32_t) oidList[i]; } - - uint32_t msgRecived = 0; +#ifdef IDB_DDL_DEBUG +cout << "Drop table removing column files" << endl; +#endif + uint msgRecived = 0; try { fWEClient->write_to_all(bytestream); bsIn.reset(new ByteStream()); - + ByteStream::byte tmp8; while (1) { if (msgRecived == fWEClient->getPmCount()) @@ -935,261 +439,593 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T } catch (std::exception& ex) { - Message::Args args; - Message message(9); - args.add("Truncate table failed due to "); + result.result = WARNING; + logging::Message::Args args; + logging::Message message(9); + args.add("Drop table failed due to "); args.add(ex.what()); - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - message.format( args ); - - result.result = TRUNC_ERROR; result.message = message; - deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); return result; } catch (...) { - result.result = DROP_ERROR; + result.result = WARNING; errorMsg = "Error in getting information from system catalog or from dbrm."; - Message::Args args; - Message message(9); - args.add("Truncate table failed due to "); + logging::Message::Args args; + logging::Message message(9); + args.add("Drop table failed due to "); args.add(errorMsg); - fSessionManager.rolledback(txnID); - fWEClient->removeQueue(uniqueId); - message.format( args ); - - result.result = TRUNC_ERROR; result.message = message; - deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); return result; } //Drop PrimProc FD cache rc = cacheutils::dropPrimProcFdCache(); //Flush primProc cache - rc = cacheutils::flushOIDsFromCache( allOidList ); + rc = cacheutils::flushOIDsFromCache( oidList ); //Delete extents from extent map - rc = fDbrm->deleteOIDs(allOidList); - + rc = fDbrm.deleteOIDs(oidList); + if (rc != 0) { - Message::Args args; - Message message(1); - args.add("Table truncated with warning "); - args.add( "Remove from extent map failed." ); - args.add(""); - args.add(""); - message.format( args ); + logging::Message::Args args; + logging::Message message(1); + args.add("Table dropped with warning "); + args.add( "Remove from extent map failed." ); + args.add(""); + args.add(""); + message.format( args ); - result.result = WARNING; - result.message = message; - fSessionManager.rolledback(txnID); + result.result = WARNING; + result.message = message; + fSessionManager.rolledback(txnID); fWEClient->removeQueue(uniqueId); return result; } - //Get the number of tables in the database, the current table is included. - int tableCount = systemCatalogPtr->getTableCount(); - Oam oam; - //Calculate which dbroot the columns should start - DBRootConfigList dbRootList = oamcache->getDBRootNums(); - - uint16_t useDBRootIndex = tableCount % dbRootList.size(); - //Find out the dbroot# corresponding the useDBRootIndex from oam - uint16_t useDBRoot = dbRootList[useDBRootIndex]; - - bytestream.restart(); - bytestream << (ByteStream::byte) WE_SVR_WRITE_CREATETABLEFILES; - bytestream << uniqueId; - bytestream << (uint32_t)txnID.id; - uint32_t numOids = columnOidList.size() + dictOIDList.size(); - bytestream << numOids; - CalpontSystemCatalog::ColType colType; + //Remove the log file + fWEClient->removeQueue(uniqueId); + deleteLogFile(DROPTABLE_LOG, roPair.objnum, uniqueId); + //release the transaction + //fSessionManager.committed(txnID); + returnOIDs( tableColRidList, dictOIDList ); + return result; + + } + + TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::TruncTableStatement& truncTableStmt) + { + SUMMARY_INFO("TruncTableProcessor::processPackage"); + // 1. lock the table + // 2. Get the OIDs for the columns + // 3. Get the OIDs for the dictionaries + // 4. Save the OIDs + // 5. Disable all partitions + // 6. Remove the column and dictionary files + // 7. Flush PrimProc Cache + // 8. Update extent map + // 9. Use the OIDs to create new column and dictionary files with abbreviate extent + // 10 Update next value if the table has autoincrement column - for (unsigned col = 0; col < columnOidList.size(); col++) + DDLResult result; + result.result = NO_ERROR; + std::string err; + VERBOSE_INFO(truncTableStmt); + + // @Bug 4150. Check dbrm status before doing anything to the table. + int rc = 0; + rc = fDbrm.isReadWrite(); + BRM::TxnID txnID; + txnID.id= fTxnid.id; + txnID.valid= fTxnid.valid; + if (rc != 0 ) { - colType = systemCatalogPtr->colType(columnOidList[col]); - if (colType.autoincrement) - autoIncColOid = colType.columnOID; - bytestream << (uint32_t)columnOidList[col]; - bytestream << (uint8_t) colType.colDataType; - bytestream << (uint8_t) false; - bytestream << (uint32_t) colType.colWidth; - bytestream << (uint16_t) useDBRoot; - bytestream << (uint32_t) colType.compressionType; + logging::Message::Args args; + logging::Message message(9); + args.add("Unable to execute the statement due to DBRM is read only"); + message.format(args); + result.result = DROP_ERROR; + result.message = message; + fSessionManager.rolledback(txnID); + return result; + } + + SQLLogger logger(truncTableStmt.fSql, fDDLLoggingId, truncTableStmt.fSessionID, txnID.id); + + std::vector columnOidList; + std::vector allOidList; + CalpontSystemCatalog::RIDList tableColRidList; + CalpontSystemCatalog::DictOIDList dictOIDList; + execplan::CalpontSystemCatalog::ROPair roPair; + std::string processName("DDLProc"); + u_int32_t processID = ::getpid();; + int32_t txnid = txnID.id; + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(truncTableStmt.fSessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + systemCatalogPtr->sessionID(truncTableStmt.fSessionID); + CalpontSystemCatalog::TableInfo tableInfo; + uint64_t uniqueId = fDbrm.getUnique64(); + fWEClient->addQueue(uniqueId); + int pmNum = 1; + boost::shared_ptr bsIn; + string errorMsg; + uint32_t autoIncColOid = 0; + uint64_t tableLockId = 0; + OamCache * oamcache = OamCache::makeOamCache(); + std::vector moduleIds = oamcache->getModuleIds(); + bool lockReleased = true; + try + { + //check table lock + + CalpontSystemCatalog::TableName tableName; + tableName.schema = truncTableStmt.fTableName->fSchema; + tableName.table = truncTableStmt.fTableName->fName; + roPair = systemCatalogPtr->tableRID( tableName ); + int32_t sessionId = truncTableStmt.fSessionID; + std::string processName("DDLProc"); + int i = 0; + + std::vector pms; + for (unsigned i=0; i < moduleIds.size(); i++) + { + pms.push_back((uint)moduleIds[i]); + } + try { + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + } + catch (std::exception&) + { + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + } + + if ( tableLockId == 0 ) + { + int waitPeriod = 10; + int sleepTime = 100; // sleep 100 milliseconds between checks + int numTries = 10; // try 10 times per second + waitPeriod = Config::getWaitPeriod(); + numTries = waitPeriod * 10; + struct timespec rm_ts; + + rm_ts.tv_sec = sleepTime/1000; + rm_ts.tv_nsec = sleepTime%1000 *1000000; + + for (; i < numTries; i++) + { +#ifdef _MSC_VER + Sleep(rm_ts.tv_sec * 1000); +#else + struct timespec abs_ts; + do + { + abs_ts.tv_sec = rm_ts.tv_sec; + abs_ts.tv_nsec = rm_ts.tv_nsec; + } + while(nanosleep(&abs_ts,&rm_ts) < 0); +#endif + try { + processID = ::getpid(); + txnid = txnID.id; + sessionId = truncTableStmt.fSessionID; + processName = "DDLProc"; + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); + } + catch (std::exception&) + { + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + } + + if (tableLockId > 0) + break; + } + if (i >= numTries) //error out + { + logging::Message::Args args; + args.add(processName); + args.add((uint64_t)processID); + args.add(sessionId); + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); + } + } + CalpontSystemCatalog::TableName userTableName; + userTableName.schema = truncTableStmt.fTableName->fSchema; + userTableName.table = truncTableStmt.fTableName->fName; + + tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); + + dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); + for ( unsigned i=0; i < tableColRidList.size(); i++ ) + { + if ( tableColRidList[i].objnum > 3000 ) + { + columnOidList.push_back( tableColRidList[i].objnum ); + allOidList.push_back( tableColRidList[i].objnum ); + } + } + for ( unsigned i=0; i < dictOIDList.size(); i++ ) + { + if ( dictOIDList[i].dictOID > 3000 ) + allOidList.push_back( dictOIDList[i].dictOID ); + } + //Check whether the table has autoincrement column + tableInfo = systemCatalogPtr->tableInfo(userTableName); } + catch (std::exception& ex) + { + cerr << "TruncateTableProcessor::processPackage: " << ex.what() << endl; - for (unsigned col = 0; col errorMsg(ERR_HARD_FAILURE)); + } + fWEClient->removeQueue(uniqueId); + message.format( args ); + + result.result = TRUNC_ERROR; + result.message = message; + return result; + } + catch (...) { - colType = systemCatalogPtr->colTypeDct(dictOIDList[col].dictOID); - bytestream << (uint32_t) dictOIDList[col].dictOID; - bytestream << (uint8_t) colType.colDataType; - bytestream << (uint8_t) true; - bytestream << (uint32_t) colType.colWidth; - bytestream << (uint16_t) useDBRoot; - bytestream << (uint32_t) colType.compressionType; + cerr << "TruncateTableProcessor::processPackage: caught unknown exception!" << endl; + + logging::Message::Args args; + logging::Message message(1); + args.add("Truncate table failed: "); + args.add( "encountered unkown exception" ); + args.add(""); + try { + lockReleased = fDbrm.releaseTableLock(tableLockId); + } + catch (std::exception&) + { + args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + } + fWEClient->removeQueue(uniqueId); + message.format( args ); + + result.result = TRUNC_ERROR; + result.message = message; + return result; } - boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); - pmNum = (*dbRootPMMap)[useDBRoot]; - try + //Save the oids to a file + try { + createWriteTruncateTableLogFile( roPair.objnum, uniqueId, allOidList); + } + catch (std::exception& ex) { -#ifdef IDB_DDL_DEBUG -cout << "Truncate table sending We_SVR_WRITE_CREATETABLEFILES to pm " << pmNum << endl; -#endif - fWEClient->write(bytestream, pmNum); - while (1) + logging::Message::Args args; + logging::Message message(9); + args.add("Truncate table failed due to "); + args.add(ex.what()); + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); + message.format( args ); + //@bug 4515 Release the tablelock as nothing has done to this table. + try { + lockReleased = fDbrm.releaseTableLock(tableLockId); + } + catch (std::exception&) {} + result.result = TRUNC_ERROR; + result.message = message; + return result; + } + + ByteStream bytestream; + ByteStream::byte tmp8; + try { + //Disable extents first + int rc1 = fDbrm.markAllPartitionForDeletion( allOidList); + if (rc1 != 0) { + string errMsg; + BRM::errString(rc, errMsg); + throw std::runtime_error(errMsg); + } + + VERBOSE_INFO("Removing files"); + bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; + bytestream << uniqueId; + bytestream << (uint32_t) allOidList.size(); + for (unsigned i=0; i < allOidList.size(); i++) + { + bytestream << (uint32_t) allOidList[i]; + } + + uint msgRecived = 0; + try { + fWEClient->write_to_all(bytestream); + bsIn.reset(new ByteStream()); - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error + + while (1) { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; - break; - } - else { - *bsIn >> tmp8; - rc = tmp8; - if (rc != 0) { - *bsIn >> errorMsg; + if (msgRecived == fWEClient->getPmCount()) + break; + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + rc = NETWORK_ERROR; + fWEClient->removeQueue(uniqueId); + break; + } + else { + *bsIn >> tmp8; + rc = tmp8; + if (rc != 0) { + *bsIn >> errorMsg; + fWEClient->removeQueue(uniqueId); + break; + } + else + msgRecived++; } - break; } } + catch (std::exception& ex) + { + logging::Message::Args args; + logging::Message message(9); + args.add("Truncate table failed due to "); + args.add(ex.what()); + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); + message.format( args ); + + result.result = TRUNC_ERROR; + result.message = message; + deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); + return result; + } + catch (...) + { + result.result = DROP_ERROR; + errorMsg = "Error in getting information from system catalog or from dbrm."; + logging::Message::Args args; + logging::Message message(9); + args.add("Truncate table failed due to "); + args.add(errorMsg); + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); + message.format( args ); + + result.result = TRUNC_ERROR; + result.message = message; + deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); + return result; + } + //Drop PrimProc FD cache + rc = cacheutils::dropPrimProcFdCache(); + //Flush primProc cache + rc = cacheutils::flushOIDsFromCache( allOidList ); + //Delete extents from extent map + rc = fDbrm.deleteOIDs(allOidList); - if (rc != 0) { - //drop the newly created files - bytestream.restart(); - bytestream << (ByteStream::byte) WE_SVR_WRITE_DROPFILES; - bytestream << uniqueId; - bytestream << (uint32_t)(allOidList.size()); - for (unsigned i = 0; i < (allOidList.size()); i++) - { - bytestream << (uint32_t)(allOidList[i]); - } + if (rc != 0) + { + logging::Message::Args args; + logging::Message message(1); + args.add("Table truncated with warning "); + args.add( "Remove from extent map failed." ); + args.add(""); + args.add(""); + message.format( args ); + + result.result = WARNING; + result.message = message; + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); + return result; + } + + //Get the number of tables in the database, the current table is included. + int tableCount = systemCatalogPtr->getTableCount(); + Oam oam; + //Calculate which dbroot the columns should start + DBRootConfigList dbRootList = oamcache->getDBRootNums(); + + uint16_t useDBRootIndex = tableCount % dbRootList.size(); + //Find out the dbroot# corresponding the useDBRootIndex from oam + uint16_t useDBRoot = dbRootList[useDBRootIndex]; + + bytestream.restart(); + bytestream << (ByteStream::byte) WE_SVR_WRITE_CREATETABLEFILES; + bytestream << uniqueId; + uint32_t numOids = columnOidList.size() + dictOIDList.size(); + bytestream << numOids; + CalpontSystemCatalog::ColType colType; + + for (unsigned col = 0; col < columnOidList.size(); col++) + { + colType = systemCatalogPtr->colType(columnOidList[col]); + if (colType.autoincrement) + autoIncColOid = colType.columnOID; + bytestream << (uint32_t)columnOidList[col]; + bytestream << (u_int8_t) colType.colDataType; + bytestream << (u_int8_t) false; + bytestream << (uint32_t) colType.colWidth; + bytestream << (u_int16_t) useDBRoot; + bytestream << (uint32_t) colType.compressionType; + } + + for (unsigned col = 0; col colTypeDct(dictOIDList[col].dictOID); + bytestream << (uint32_t) dictOIDList[col].dictOID; + bytestream << (u_int8_t) colType.colDataType; + bytestream << (u_int8_t) true; + bytestream << (uint32_t) colType.colWidth; + bytestream << (u_int16_t) useDBRoot; + bytestream << (uint32_t) colType.compressionType; + } + + boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); + pmNum = (*dbRootPMMap)[useDBRoot]; + try + { +#ifdef IDB_DDL_DEBUG +cout << "Truncate table sending We_SVR_WRITE_CREATETABLEFILES to pm " << pmNum << endl; +#endif fWEClient->write(bytestream, pmNum); while (1) { bsIn.reset(new ByteStream()); fWEClient->read(uniqueId, bsIn); if ( bsIn->length() == 0 ) //read error - { + { + rc = NETWORK_ERROR; + errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; break; } else { *bsIn >> tmp8; - //rc = tmp8; + rc = tmp8; + if (rc != 0) { + *bsIn >> errorMsg; + } break; } } - Message::Args args; - Message message(1); - args.add( "Truncate table failed." ); - args.add( errorMsg); - args.add(""); - message.format( args ); + + if (rc != 0) { + //drop the newly created files + bytestream.restart(); + bytestream << (ByteStream::byte) WE_SVR_WRITE_DROPFILES; + bytestream << uniqueId; + bytestream << (uint32_t)(allOidList.size()); + for (unsigned i = 0; i < (allOidList.size()); i++) + { + bytestream << (uint32_t)(allOidList[i]); + } + fWEClient->write(bytestream, pmNum); + while (1) + { + bsIn.reset(new ByteStream()); + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + break; + } + else { + *bsIn >> tmp8; + //rc = tmp8; + break; + } + } + logging::Message::Args args; + logging::Message message(1); + args.add( "Truncate table failed." ); + args.add( errorMsg); + args.add(""); + message.format( args ); - result.result = TRUNC_ERROR; - result.message = message; - //rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); - fSessionManager.rolledback(txnID); - return result; - } - } - catch (runtime_error&) - { - rc = NETWORK_ERROR; - errorMsg = "Lost connection to Write Engine Server"; + result.result = TRUNC_ERROR; + result.message = message; + //rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); + fSessionManager.rolledback(txnID); + return result; + } + } + catch (runtime_error&) + { + rc = NETWORK_ERROR; + errorMsg = "Lost connection to Write Engine Server"; + } } - } + catch (std::exception& ex) + { #ifdef _MSC_VER - catch (std::exception&) - { - //FIXME: Windows can't delete a file that's still open by another process - } + //FIXME: Windows can't delete a file that's still open by another process #else - catch (std::exception& ex) - { - Message::Args args; - Message message(1); - args.add( "Truncate table failed." ); - args.add( ex.what() ); - args.add(""); - message.format( args ); + logging::Message::Args args; + logging::Message message(1); + args.add( "Truncate table failed." ); + args.add( ex.what() ); + args.add(""); + message.format( args ); - result.result = TRUNC_ERROR; - result.message = message; - //rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); - fSessionManager.rolledback(txnID); - return result; - } + result.result = TRUNC_ERROR; + result.message = message; + //rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); + fSessionManager.rolledback(txnID); + return result; #endif - catch ( ... ) - { - Message::Args args; - Message message(1); - args.add("Truncate table failed: "); - args.add( "Remove column files failed." ); - args.add(""); - args.add(""); - message.format( args ); + } + catch ( ... ) + { + logging::Message::Args args; + logging::Message message(1); + args.add("Truncate table failed: "); + args.add( "Remove column files failed." ); + args.add(""); + args.add(""); + message.format( args ); - result.result = TRUNC_ERROR; - result.message = message; - //rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); - fSessionManager.rolledback(txnID); - return result; - } - if (rc != 0) - { - rollBackTransaction( uniqueId, txnID, truncTableStmt.fSessionID); //What to do with the error code - fSessionManager.rolledback(txnID); - } - - //Check whether the table has autoincrement column - if (tableInfo.tablewithautoincr == 1) - { - //reset nextvalue to 1 - WE_DDLCommandClient commandClient; - rc = commandClient.UpdateSyscolumnNextval(autoIncColOid,1); - } - // Log the DDL statement - logDDL(truncTableStmt.fSessionID, txnID.id, truncTableStmt.fSql, truncTableStmt.fOwner); - try { - (void)fDbrm->releaseTableLock(tableLockId); - } - catch (std::exception&) - { - Message::Args args; - Message message(1); - args.add("Table truncated with warning "); - args.add( "Release table failed." ); - args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - args.add(""); - message.format( args ); + result.result = TRUNC_ERROR; + result.message = message; + //rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); + fSessionManager.rolledback(txnID); + return result; + } + if (rc != 0) + { + rollBackTransaction( uniqueId, txnID, truncTableStmt.fSessionID); //What to do with the error code + fSessionManager.rolledback(txnID); + } + + //Check whether the table has autoincrement column + if (tableInfo.tablewithautoincr == 1) + { + //reset nextvalue to 1 + WE_DDLCommandClient commandClient; + rc = commandClient.UpdateSyscolumnNextval(autoIncColOid,1); + } + // Log the DDL statement + logging::logDDL(truncTableStmt.fSessionID, txnID.id, truncTableStmt.fSql, truncTableStmt.fOwner); + try { + lockReleased = fDbrm.releaseTableLock(tableLockId); + } + catch (std::exception&) + { + logging::Message::Args args; + logging::Message message(1); + args.add("Table truncated with warning "); + args.add( "Release table failed." ); + args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + args.add(""); + message.format( args ); - result.result = WARNING; - result.message = message; - fSessionManager.rolledback(txnID); + result.result = WARNING; + result.message = message; + fSessionManager.rolledback(txnID); + fWEClient->removeQueue(uniqueId); + } + //release the transaction + fSessionManager.committed(txnID); fWEClient->removeQueue(uniqueId); - } - //release the transaction - fSessionManager.committed(txnID); - fWEClient->removeQueue(uniqueId); - //Remove the log file - try { - deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); - } - catch ( ... ) - { - } - - return result; -} - -} //namespace ddlpackageprocessor + //Remove the log file + try { + deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); + } + catch ( ... ) + { + } -// vim:ts=4 sw=4: + return result; + } +} diff --git a/dbcon/ddlpackageproc/droptableprocessor.h b/dbcon/ddlpackageproc/droptableprocessor.h index 01430bb2..38a5d76c 100644 --- a/dbcon/ddlpackageproc/droptableprocessor.h +++ b/dbcon/ddlpackageproc/droptableprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: droptableprocessor.h 9303 2013-03-07 16:07:12Z chao $ + * $Id: droptableprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -26,7 +26,7 @@ #include "ddlpackageprocessor.h" -#if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(DROPTABLEPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -41,7 +41,6 @@ namespace ddlpackageprocessor class DropTableProcessor : public DDLPackageProcessor { public: - DropTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} /** @brief process a drop table statement * * @param dropTableStmt the drop table statement @@ -61,7 +60,6 @@ namespace ddlpackageprocessor class TruncTableProcessor : public DDLPackageProcessor { public: - TruncTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} /** @brief process a truncate table statement * * @param truncTableStmt the truncate table statement diff --git a/dbcon/ddlpackageproc/libddlpackageproc.rc b/dbcon/ddlpackageproc/libddlpackageproc.rc deleted file mode 100644 index abf70abc..00000000 --- a/dbcon/ddlpackageproc/libddlpackageproc.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB DDL API" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "libddlpackageproc" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "libddlpackageproc.dll" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/dbcon/ddlpackageproc/libddlpackageproc.vcxproj b/dbcon/ddlpackageproc/libddlpackageproc.vcxproj deleted file mode 100644 index 462d2b99..00000000 --- a/dbcon/ddlpackageproc/libddlpackageproc.vcxproj +++ /dev/null @@ -1,355 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {19142D9E-7660-445C-B85D-98E722DFFEA5} - libddlpackageproc - - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DDLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DDLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DDLPKGPROC_DLLEXPORT;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DDLPKGPROC_DLLEXPORT;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DDL API" $(SolutionDir)..\..x64\Release\libddlpackageproc.dll - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DDLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DDLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DDL API" $(SolutionDir)..\..\x64\EnterpriseRelease\libddlpackageproc.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {4bc37219-e09d-4133-98c4-cf0386657df6} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - {033c6cba-d984-483f-adc8-825be20a699d} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - - - - \ No newline at end of file diff --git a/dbcon/ddlpackageproc/libddlpackageproc.vcxproj.filters b/dbcon/ddlpackageproc/libddlpackageproc.vcxproj.filters deleted file mode 100644 index 8603534f..00000000 --- a/dbcon/ddlpackageproc/libddlpackageproc.vcxproj.filters +++ /dev/null @@ -1,71 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/dbcon/ddlpackageproc/markpartitionprocessor.cpp b/dbcon/ddlpackageproc/markpartitionprocessor.cpp index dc535a82..1fe4a928 100644 --- a/dbcon/ddlpackageproc/markpartitionprocessor.cpp +++ b/dbcon/ddlpackageproc/markpartitionprocessor.cpp @@ -20,7 +20,9 @@ * * ***********************************************************************/ +#define DDLPKGMARKPARTITIONPROC_DLLEXPORT #include "markpartitionprocessor.h" +#undef DDLPKGMARKPARTITIONPROC_DLLEXPORT #include "messagelog.h" #include "sqllogger.h" @@ -49,7 +51,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack txnID.valid= fTxnid.valid; int rc = 0; - rc = fDbrm->isReadWrite(); + rc = fDbrm.isReadWrite(); if (rc != 0 ) { logging::Message::Args args; @@ -65,9 +67,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::DictOIDList dictOIDList; std::string processName("DDLProc"); - - string stmt = markPartitionStmt.fSql + "|" + markPartitionStmt.fTableName->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, markPartitionStmt.fSessionID, txnID.id); + SQLLogger logger(markPartitionStmt.fSql, fDDLLoggingId, markPartitionStmt.fSessionID, txnID.id); uint32_t processID = 0; uint64_t uniqueID = 0; @@ -93,14 +93,14 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack processID = ::getpid(); oam::OamCache * oamcache = OamCache::makeOamCache(); std::vector pmList = oamcache->getModuleIds(); - std::vector pms; + std::vector pms; for (unsigned i=0; i < pmList.size(); i++) { - pms.push_back((uint32_t)pmList[i]); + pms.push_back((uint)pmList[i]); } try { - uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); + uniqueID = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { @@ -143,7 +143,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack processName = "DDLProc"; try { - uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); + uniqueID = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { @@ -199,7 +199,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack //Remove the partition from extent map string emsg; - rc = fDbrm->markPartitionForDeletion( oidList, markPartitionStmt.fPartitions, emsg); + rc = fDbrm.markPartitionForDeletion( oidList, markPartitionStmt.fPartitions, emsg); if ( rc != 0 ) { throw std::runtime_error(emsg); @@ -222,7 +222,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack result.message = message; try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; @@ -246,7 +246,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack result.result = DROP_ERROR; result.message = message; try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; @@ -258,7 +258,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack // Log the DDL statement logging::logDDL(markPartitionStmt.fSessionID, 0, markPartitionStmt.fSql, markPartitionStmt.fOwner); try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; diff --git a/dbcon/ddlpackageproc/markpartitionprocessor.h b/dbcon/ddlpackageproc/markpartitionprocessor.h index 4f5708f7..ae684e9c 100644 --- a/dbcon/ddlpackageproc/markpartitionprocessor.h +++ b/dbcon/ddlpackageproc/markpartitionprocessor.h @@ -26,7 +26,7 @@ #include "ddlpackageprocessor.h" -#if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(DDLPKGMARKPARTITIONPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -42,7 +42,7 @@ namespace ddlpackageprocessor class MarkPartitionProcessor : public DDLPackageProcessor { public: - MarkPartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} + /** @brief process a create table statement * * @param createTableStmt the CreateTableStatement diff --git a/dbcon/ddlpackageproc/resource.h b/dbcon/ddlpackageproc/resource.h deleted file mode 100644 index 9173430b..00000000 --- a/dbcon/ddlpackageproc/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by libddlpackageproc.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/dbcon/ddlpackageproc/restorepartitionprocessor.cpp b/dbcon/ddlpackageproc/restorepartitionprocessor.cpp index 15e31a03..764cebb6 100644 --- a/dbcon/ddlpackageproc/restorepartitionprocessor.cpp +++ b/dbcon/ddlpackageproc/restorepartitionprocessor.cpp @@ -20,7 +20,9 @@ * * ***********************************************************************/ +#define RESTOREPARTITIONPROC_DLLEXPORT #include "restorepartitionprocessor.h" +#undef RESTOREPARTITIONPROC_DLLEXPORT #include "messagelog.h" #include "sqllogger.h" @@ -48,7 +50,7 @@ namespace ddlpackageprocessor txnID.valid= fTxnid.valid; int rc = 0; - rc = fDbrm->isReadWrite(); + rc = fDbrm.isReadWrite(); if (rc != 0 ) { logging::Message::Args args; @@ -65,9 +67,7 @@ namespace ddlpackageprocessor CalpontSystemCatalog::DictOIDList dictOIDList; std::string processName("DDLProc"); - string stmt = restorePartitionStmt.fSql + "|" + restorePartitionStmt.fTableName->fSchema +"|"; - SQLLogger logger(stmt, fDDLLoggingId, restorePartitionStmt.fSessionID, txnID.id); - + SQLLogger logger(restorePartitionStmt.fSql, fDDLLoggingId, restorePartitionStmt.fSessionID, txnID.id); uint32_t processID = 0; uint64_t uniqueID = 0; uint32_t sessionID = restorePartitionStmt.fSessionID; @@ -92,14 +92,14 @@ namespace ddlpackageprocessor processID = ::getpid(); oam::OamCache * oamcache = oam::OamCache::makeOamCache(); std::vector pmList = oamcache->getModuleIds(); - std::vector pms; + std::vector pms; for (unsigned i=0; i < pmList.size(); i++) { - pms.push_back((uint32_t)pmList[i]); + pms.push_back((uint)pmList[i]); } try { - uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); + uniqueID = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { @@ -142,7 +142,7 @@ namespace ddlpackageprocessor processName = "DDLProc"; try { - uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); + uniqueID = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { @@ -198,7 +198,7 @@ namespace ddlpackageprocessor //Remove the partition from extent map string emsg; - rc = fDbrm->restorePartition( oidList, restorePartitionStmt.fPartitions, emsg); + rc = fDbrm.restorePartition( oidList, restorePartitionStmt.fPartitions, emsg); if ( rc != 0 ) { throw std::runtime_error(emsg); @@ -219,7 +219,7 @@ namespace ddlpackageprocessor result.message = message; try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; @@ -243,7 +243,7 @@ namespace ddlpackageprocessor result.result = DROP_ERROR; result.message = message; try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; @@ -255,7 +255,7 @@ namespace ddlpackageprocessor // Log the DDL statement logging::logDDL(restorePartitionStmt.fSessionID, txnID.id, restorePartitionStmt.fSql, restorePartitionStmt.fOwner); try { - fDbrm->releaseTableLock(uniqueID); + fDbrm.releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; diff --git a/dbcon/ddlpackageproc/restorepartitionprocessor.h b/dbcon/ddlpackageproc/restorepartitionprocessor.h index 1b5cf62c..61ce5878 100644 --- a/dbcon/ddlpackageproc/restorepartitionprocessor.h +++ b/dbcon/ddlpackageproc/restorepartitionprocessor.h @@ -26,7 +26,7 @@ #include "ddlpackageprocessor.h" -#if defined(_MSC_VER) && defined(DDLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(RESTOREPARTITIONPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -41,7 +41,6 @@ namespace ddlpackageprocessor class RestorePartitionProcessor : public DDLPackageProcessor { public: - RestorePartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm){} /** @brief process a drop table statement * * @param dropTableStmt the drop table statement diff --git a/dbcon/dmlpackage/Makefile.am b/dbcon/dmlpackage/Makefile.am index 8d101d42..4238ea65 100644 --- a/dbcon/dmlpackage/Makefile.am +++ b/dbcon/dmlpackage/Makefile.am @@ -14,6 +14,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) diff --git a/dbcon/dmlpackage/Makefile.in b/dbcon/dmlpackage/Makefile.in index 400ee0c4..631fa305 100644 --- a/dbcon/dmlpackage/Makefile.in +++ b/dbcon/dmlpackage/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -41,9 +60,8 @@ subdir = dbcon/dmlpackage DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -143,9 +161,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -187,7 +202,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -201,11 +215,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -216,23 +225,6 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) diff --git a/dbcon/dmlpackage/calpontdmlfactory.cpp b/dbcon/dmlpackage/calpontdmlfactory.cpp index 52644d5f..79e532fc 100644 --- a/dbcon/dmlpackage/calpontdmlfactory.cpp +++ b/dbcon/dmlpackage/calpontdmlfactory.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: calpontdmlfactory.cpp 9642 2013-06-24 14:57:42Z rdempsey $ + * $Id: calpontdmlfactory.cpp 8707 2012-07-13 19:08:12Z rdempsey $ * * ***********************************************************************/ @@ -49,6 +49,7 @@ boost::mutex CalpontDMLFactory::fParserLock; dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpackage::VendorDMLStatement& vpackage, std::string defaultSchema /*= ""*/) { + int retval = 1; CalpontDMLPackage* packagePtr = 0; try { @@ -68,6 +69,12 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka const ParseTree &ptree = parser.getParseTree(); SqlStatement* statementPtr = ptree[0]; +#ifdef DML_PACKAGE_DEBUG + //std::cout << ptree; + //std::cout << statementPtr->getQueryString(); + //std::cout << endl; +#endif + int dmlStatementType = statementPtr->getStatementType(); switch (dmlStatementType) @@ -76,26 +83,26 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka packagePtr = new InsertDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(), ptree.fSqlText, vpackage.get_SessionID() ); packagePtr->set_SQLStatement(dmlStatement); - (void)packagePtr->buildFromSqlStatement(*statementPtr); + retval = packagePtr->buildFromSqlStatement(*statementPtr); break; case DML_UPDATE: packagePtr = new UpdateDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(), ptree.fSqlText, vpackage.get_SessionID() ); packagePtr->set_SQLStatement(dmlStatement); - (void)packagePtr->buildFromSqlStatement(*statementPtr); + retval = packagePtr->buildFromSqlStatement(*statementPtr); break; case DML_DELETE: packagePtr = new DeleteDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(), ptree.fSqlText, vpackage.get_SessionID() ); packagePtr->set_SQLStatement(dmlStatement); - (void)packagePtr->buildFromSqlStatement(*statementPtr); + retval = packagePtr->buildFromSqlStatement(*statementPtr); break; case DML_COMMAND: packagePtr = new CommandDMLPackage(ptree.fSqlText, vpackage.get_SessionID()); - (void)packagePtr->buildFromSqlStatement(*statementPtr); + retval = packagePtr->buildFromSqlStatement(*statementPtr); break; default: @@ -121,6 +128,7 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromBuffer(dmlpackage::VendorDMLStatement& vpackage) { + int retval = 1; CalpontDMLPackage* packagePtr = 0; try { @@ -129,19 +137,19 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromBuffe { case DML_INSERT: packagePtr = new InsertDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID()); - (void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer + retval = packagePtr->buildFromBuffer(vpackage.get_DataBuffer (),vpackage.get_Columns(), vpackage.get_Rows()); break; case DML_UPDATE: packagePtr = new UpdateDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),vpackage.get_DMLStatement(), vpackage.get_SessionID()); - (void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer + retval = packagePtr->buildFromBuffer(vpackage.get_DataBuffer (),vpackage.get_Columns(), vpackage.get_Rows()); break; case DML_DELETE: packagePtr = new DeleteDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),vpackage.get_DMLStatement(), vpackage.get_SessionID()); - (void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer + retval = packagePtr->buildFromBuffer(vpackage.get_DataBuffer (),vpackage.get_Columns(), vpackage.get_Rows()); break; case DML_COMMAND: @@ -166,6 +174,7 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromBuffe dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(dmlpackage::VendorDMLStatement& vpackage) { + int retval = 1; CalpontDMLPackage* packagePtr = 0; try { @@ -174,7 +183,7 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromMysql { case DML_INSERT: packagePtr = new InsertDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID()); - (void)packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(), vpackage.get_Columns(), vpackage.get_Rows()); + retval = packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(), vpackage.get_Columns(), vpackage.get_Rows()); break; case DML_COMMAND: packagePtr = new CommandDMLPackage(vpackage.get_DMLStatement(), vpackage.get_SessionID() ); @@ -182,7 +191,7 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromMysql case DML_DELETE: packagePtr = new DeleteDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID() ); - (void)packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(), vpackage.get_Columns(), vpackage.get_Rows()); + retval = packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(), vpackage.get_Columns(), vpackage.get_Rows()); break; default: cerr << "makeCalpontDMLPackage: invalid statement type" << endl; diff --git a/dbcon/dmlpackage/calpontdmlfactory.h b/dbcon/dmlpackage/calpontdmlfactory.h index ec47b2ca..b29af539 100644 --- a/dbcon/dmlpackage/calpontdmlfactory.h +++ b/dbcon/dmlpackage/calpontdmlfactory.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: calpontdmlfactory.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: calpontdmlfactory.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/calpontdmlpackage.cpp b/dbcon/dmlpackage/calpontdmlpackage.cpp index 634b5c06..c61700fd 100644 --- a/dbcon/dmlpackage/calpontdmlpackage.cpp +++ b/dbcon/dmlpackage/calpontdmlpackage.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: calpontdmlpackage.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: calpontdmlpackage.cpp 8817 2012-08-15 18:52:12Z dhall $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/calpontdmlpackage.h b/dbcon/dmlpackage/calpontdmlpackage.h index 01e94068..5759cb86 100644 --- a/dbcon/dmlpackage/calpontdmlpackage.h +++ b/dbcon/dmlpackage/calpontdmlpackage.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: calpontdmlpackage.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: calpontdmlpackage.h 8817 2012-08-15 18:52:12Z dhall $ * * ***********************************************************************/ @@ -25,8 +25,6 @@ #ifndef CALPONTDMLPACKAGE_H #define CALPONTDMLPACKAGE_H #include -#include - #include "bytestream.h" #include "dmlpackage.h" #include "dmltable.h" @@ -86,152 +84,160 @@ namespace dmlpackage * @param sqlStatement the parsed SqlStatement */ virtual int buildFromSqlStatement( SqlStatement& sqlStatement ) = 0; - - /** @brief build a CalpontDMLPackage from valuelist built from mysql table fields + + /** @brief build a CalpontDMLPackage from valuelist built from mysql table fields * * @param tableValuesMap the value list for each column in the table - * @param colNameList the column name for each column - * @param columns number of columns in the table - * @param rows number of rows to be touched + * @param colNameList the column name for each column + * @param columns number of columns in the table + * @param rows number of rows to be touched */ - virtual int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows) = 0; + virtual int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows) = 0; /** @brief get the table object */ - DMLTable* get_Table() { return fTable; } + inline DMLTable* get_Table() { return fTable; } /** @brief set the DML statement (the parsed statement) * * @param statement the dml statement to set */ - void set_DMLStatement( const std::string& statement ) { fDMLStatement = statement; } + inline void set_DMLStatement( const std::string& statement ) + { fDMLStatement = statement; } /** @brief get the DML statement (the parsed statement) */ - const std::string get_DMLStatement() const { return fDMLStatement; } + inline const std::string get_DMLStatement() const { return fDMLStatement; } /** @brief set the SQL statement (the original SQL statement) * * @param statement the SQL statement to set (the original SQL statement with quotes) */ - void set_SQLStatement( const std::string& statement ) { fSQLStatement = statement; } + inline void set_SQLStatement( const std::string& statement ) + { fSQLStatement = statement; } /** @brief get the SQL statement (the original SQL statement) */ - const std::string get_SQLStatement() const { return fSQLStatement; } - - /** @brief get the logging flag - */ - const bool get_Logging() const { return fLogging; } - - /** @brief set the logging flag + inline const std::string get_SQLStatement() const { return fSQLStatement; } + + /** @brief get the logging flag + */ + inline const bool get_Logging() const { return fLogging; } + + /** @brief set the logging flag * * @param logging the logging flag to set */ - void set_Logging( bool logging ) { fLogging = logging; } - - /** @brief get the logending flag - */ - const bool get_Logending() const { return fLogending; } - - /** @brief set the logending flag + inline void set_Logging( bool logging ) + { + fLogging = logging; + } + + /** @brief get the logending flag + */ + inline const bool get_Logending() const { return fLogending; } + + /** @brief set the logending flag * * @param logending the logending flag to set */ - void set_Logending( bool logending ) { fLogending = logending; } - - /** @brief get the isFromCol flag - */ - const bool get_IsFromCol() const { return fIsFromCol; } - - /** @brief set the update column from column flag + inline void set_Logending( bool logending ) + { + fLogending = logending; + } + + /** @brief get the isFromCol flag + */ + inline const bool get_IsFromCol() const { return fIsFromCol; } + + /** @brief set the update column from column flag * * @param logging the logging flag to set */ - void set_IsFromCol ( bool isFromCol ) { fIsFromCol = isFromCol; } + inline void set_IsFromCol ( bool isFromCol ) + { + fIsFromCol = isFromCol; + } /** @brief set the Table name * * @param tableName the name to set */ - void set_TableName( std::string& tableName ) - { - fTableName = tableName; - if(fTable != 0) - fTable->set_TableName(tableName); - } + inline void set_TableName( std::string& tableName ) + { + fTableName = tableName; + if(fTable != 0) + fTable->set_TableName(tableName); + } /** @brief get the Table name */ - const std::string get_TableName() const { return fTableName; } + inline const std::string get_TableName() const { return fTableName; } /** @brief set the Schema name * * @param the schema to set */ - void set_SchemaName( std::string& schemaName ) - { - fSchemaName = schemaName; - if(fTable != 0) - fTable->set_SchemaName(schemaName); - } + inline void set_SchemaName( std::string& schemaName ) + { + fSchemaName = schemaName; + if(fTable != 0) + fTable->set_SchemaName(schemaName); + } /** @brief get the Schema name */ - const std::string get_SchemaName() const { return fSchemaName; } + inline const std::string get_SchemaName() const { return fSchemaName; } /** @brief does this dml statement have a filter */ - bool HasFilter() const { return fHasFilter; } - void HasFilter( bool hasFilter) { fHasFilter = hasFilter; } + inline bool HasFilter() const { return fHasFilter; } + inline void HasFilter( bool hasFilter) { fHasFilter = hasFilter; } /** @brief get the filter statement */ - const std::string get_QueryString() const { return fQueryString; } + inline const std::string get_QueryString() const { return fQueryString; } /** @brief set the sessionID associated with this package */ - void set_SessionID( int sessionID ) { fSessionID = sessionID; } + inline void set_SessionID( int sessionID ) { fSessionID = sessionID; } /** @brief get the sessionID associated with this package */ - int get_SessionID() const { return fSessionID; } - - /** @brief set the transaction ID associated with this package + inline int get_SessionID() const { return fSessionID; } + + /** @brief set the transaction ID associated with this package */ - void set_TxnID( execplan::CalpontSystemCatalog::SCN txnID ) { fTxnId = txnID; } + inline void set_TxnID( execplan::CalpontSystemCatalog::SCN txnID ) { fTxnId = txnID; } /** @brief get the transaction ID associated with this package */ - execplan::CalpontSystemCatalog::SCN get_TxnID() const { return fTxnId; } - /** @brief set the chunkmanager associated with this package + inline execplan::CalpontSystemCatalog::SCN get_TxnID() const { return fTxnId; } + /** @brief set the chunkmanager associated with this package */ - void set_ChunkManager( WriteEngine::ChunkManager* cm ) { fCM = cm; } + inline void set_ChunkManager( WriteEngine::ChunkManager* cm ) { fCM = cm; } /** @brief get the chunkmanager associated with this package */ - WriteEngine::ChunkManager* get_ChunkManager() const { return fCM; } - - /** @brief get the ExecutionPlan associated with this package - */ - boost::shared_ptr get_ExecutionPlan() - { - return fPlan; - } - - bool get_isInsertSelect() { return fIsInsertSelect; } - void set_isInsertSelect( const bool isInsertSelect ) { fIsInsertSelect = isInsertSelect; } - - bool get_isBatchInsert() { return fIsBatchInsert; } - void set_isBatchInsert( const bool isBatchInsert ) { fIsBatchInsert = isBatchInsert; } - - bool get_isAutocommitOn() { return fIsAutocommitOn; } - void set_isAutocommitOn( const bool isAutocommitOn ) { fIsAutocommitOn = isAutocommitOn; } - uint32_t getTableOid() { return fTableOid; } - void setTableOid( const uint32_t tableOid ) { fTableOid = tableOid; } - - void uuid(const boost::uuids::uuid& uuid) { fUuid = uuid; } - const boost::uuids::uuid& uuid() const { return fUuid; } - + inline WriteEngine::ChunkManager* get_ChunkManager() const { return fCM; } + /** @brief get the ExecutionPlan associated with this package + */ + inline boost::shared_ptr get_ExecutionPlan() + { + return fPlan; + } + + inline bool get_isInsertSelect() { return fIsInsertSelect; } + inline void set_isInsertSelect( const bool isInsertSelect ) { fIsInsertSelect = isInsertSelect; } + + inline bool get_isBatchInsert() { return fIsBatchInsert; } + inline void set_isBatchInsert( const bool isBatchInsert ) { fIsBatchInsert = isBatchInsert; } + + inline bool get_isAutocommitOn() { return fIsAutocommitOn; } + inline void set_isAutocommitOn( const bool isAutocommitOn ) { fIsAutocommitOn = isAutocommitOn; } + + inline uint32_t getTableOid() { return fTableOid; } + inline void setTableOid( const uint32_t tableOid ) { fTableOid = tableOid; } + protected: void initializeTable(); @@ -242,20 +248,19 @@ namespace dmlpackage std::string fSQLStatement; std::string fQueryString; int fSessionID; - boost::uuids::uuid fUuid; - execplan::CalpontSystemCatalog::SCN fTxnId; - boost::shared_ptr fPlan; + execplan::CalpontSystemCatalog::SCN fTxnId; + boost::shared_ptr fPlan; DMLTable *fTable; bool fHasFilter; - bool fLogging; - bool fLogending; - bool fIsFromCol; + bool fLogging; + bool fLogending; + bool fIsFromCol; std::string StripLeadingWhitespace( std::string value ); - bool fIsInsertSelect; - bool fIsBatchInsert; - bool fIsAutocommitOn; - uint32_t fTableOid; - WriteEngine::ChunkManager* fCM; + bool fIsInsertSelect; + bool fIsBatchInsert; + bool fIsAutocommitOn; + uint32_t fTableOid; + WriteEngine::ChunkManager* fCM; }; } #endif //CALPONTDMLPACKAGE_H diff --git a/dbcon/dmlpackage/commanddmlpackage.cpp b/dbcon/dmlpackage/commanddmlpackage.cpp index a2ddfa18..b6e1414d 100644 --- a/dbcon/dmlpackage/commanddmlpackage.cpp +++ b/dbcon/dmlpackage/commanddmlpackage.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: commanddmlpackage.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: commanddmlpackage.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -52,16 +52,14 @@ namespace dmlpackage messageqcpp::ByteStream::quadbyte session_id = fSessionID; bytestream << session_id; - bytestream << fUuid; - bytestream << fDMLStatement; bytestream << fSQLStatement; // for cleartablelock, this is table lockID - bytestream << (uint8_t)fLogging; - bytestream << fSchemaName; - bytestream << fTableName; - bytestream << fTableOid; - bytestream << static_cast(fIsAutocommitOn); - bytestream << static_cast(fIsBatchInsert); + bytestream << (uint8_t)fLogging; + bytestream << fSchemaName; + bytestream << fTableName; + bytestream << fTableOid; + bytestream << static_cast(fIsAutocommitOn); + bytestream << static_cast(fIsBatchInsert); return retval; } @@ -72,18 +70,17 @@ namespace dmlpackage messageqcpp::ByteStream::quadbyte session_id; bytestream >> session_id; fSessionID = session_id; - bytestream >> fUuid; bytestream >> fDMLStatement; bytestream >> fSQLStatement; // for cleartablelock, this is table lockID - uint8_t logging; - bytestream >> logging; - fLogging = (logging != 0); - bytestream >> fSchemaName; - bytestream >> fTableName; - bytestream >> fTableOid; - bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsAutocommitOn); - bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsBatchInsert); + uint8_t logging; + bytestream >> logging; + fLogging = (logging != 0); + bytestream >> fSchemaName; + bytestream >> fTableName; + bytestream >> fTableOid; + bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsAutocommitOn); + bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsBatchInsert); return retval; } diff --git a/dbcon/dmlpackage/commanddmlpackage.h b/dbcon/dmlpackage/commanddmlpackage.h index bbd45f38..5e5034ca 100644 --- a/dbcon/dmlpackage/commanddmlpackage.h +++ b/dbcon/dmlpackage/commanddmlpackage.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: commanddmlpackage.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: commanddmlpackage.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/deletedmlpackage.cpp b/dbcon/dmlpackage/deletedmlpackage.cpp index a6858c0c..ffd8d314 100644 --- a/dbcon/dmlpackage/deletedmlpackage.cpp +++ b/dbcon/dmlpackage/deletedmlpackage.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: deletedmlpackage.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: deletedmlpackage.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -62,8 +62,6 @@ int DeleteDMLPackage::write(messageqcpp::ByteStream& bytestream) messageqcpp::ByteStream::quadbyte hasFilter = fHasFilter; bytestream << hasFilter; - bytestream << fUuid; - bytestream << fDMLStatement; bytestream << fSQLStatement; bytestream << fSchemaName; @@ -94,8 +92,6 @@ int DeleteDMLPackage::read(messageqcpp::ByteStream& bytestream) bytestream >> hasFilter; fHasFilter = (hasFilter != 0); - bytestream >> fUuid; - std::string dmlStatement; bytestream >> fDMLStatement; bytestream >> fSQLStatement; @@ -191,26 +187,26 @@ int DeleteDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows int DeleteDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows ) { - int retval = 1; + int retval = 1; initializeTable(); - //The row already built from MySql parser. -/* Row *aRowPtr = new Row(); - std::string colName; - std::vector colValList; - for (int j = 0; j < columns; j++) + //The row already built from MySql parser. +/* Row *aRowPtr = new Row(); + std::string colName; + std::vector colValList; + for (int j = 0; j < columns; j++) { //Build a column list colName = colNameList[j]; - + colValList = tableValuesMap[j]; DMLColumn* aColumn = new DMLColumn(colName, colValList, false); (aRowPtr->get_ColumnList()).push_back(aColumn); } - //build a row list for a table + //build a row list for a table fTable->get_RowList().push_back(aRowPtr); */ - return retval; + return retval; } } // namespace dmlpackage diff --git a/dbcon/dmlpackage/deletedmlpackage.h b/dbcon/dmlpackage/deletedmlpackage.h index 8ba70889..bdbc8204 100644 --- a/dbcon/dmlpackage/deletedmlpackage.h +++ b/dbcon/dmlpackage/deletedmlpackage.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: deletedmlpackage.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: deletedmlpackage.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dml-scan-win.cpp b/dbcon/dmlpackage/dml-scan-win.cpp index 7b83ccec..c30d7da1 100644 --- a/dbcon/dmlpackage/dml-scan-win.cpp +++ b/dbcon/dmlpackage/dml-scan-win.cpp @@ -1,34 +1,19 @@ -#define yy_create_buffer dml_create_buffer -#define yy_delete_buffer dml_delete_buffer -#define yy_scan_buffer dml_scan_buffer -#define yy_scan_string dml_scan_string -#define yy_scan_bytes dml_scan_bytes -#define yy_flex_debug dml_flex_debug -#define yy_init_buffer dml_init_buffer -#define yy_flush_buffer dml_flush_buffer -#define yy_load_buffer_state dml_load_buffer_state -#define yy_switch_to_buffer dml_switch_to_buffer -#define yyin dmlin -#define yyleng dmlleng -#define yylex dmllex -#define yyout dmlout -#define yyrestart dmlrestart -#define yytext dmltext - -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include - - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ #ifdef c_plusplus #ifndef __cplusplus #define __cplusplus @@ -613,8 +598,38 @@ static char *yy_last_accepting_cpos; #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #define INITIAL 0 +/* -/* $Id: dml.l 8707 2012-07-13 19:08:12Z rdempsey $ */ +Copyright (C) 2009-2012 Calpont Corporation. + +Use of and access to the Calpont InfiniDB Community software is subject to the +terms and conditions of the Calpont Open Source License Agreement. Use of and +access to the Calpont InfiniDB Enterprise software is subject to the terms and +conditions of the Calpont End User License Agreement. + +This program is distributed in the hope that it will be useful, and unless +otherwise noted on your license agreement, WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +Please refer to the Calpont Open Source License Agreement and the Calpont End +User License Agreement for more details. + +You should have received a copy of either the Calpont Open Source License +Agreement or the Calpont End User License Agreement along with this program; if +not, it is your responsibility to review the terms and conditions of the proper +Calpont license agreement by visiting http://www.calpont.com for the Calpont +InfiniDB Enterprise End User License Agreement or http://www.infinidb.org for +the Calpont InfiniDB Community Calpont Open Source License Agreement. + +Calpont may make changes to these license agreements from time to time. When +these changes are made, Calpont will make a new copy of the Calpont End User +License Agreement available at http://www.calpont.com and a new copy of the +Calpont Open Source License Agreement available at http:///www.infinidb.org. +You understand and agree that if you use the Program after the date on which +the license agreement authorizing your use has changed, Calpont will treat your +use as acceptance of the updated License. + +*/ +/* $Id: dml.l 8436 2012-04-04 18:18:21Z rdempsey $ */ #include #include #include diff --git a/dbcon/dmlpackage/dmlcolumn.cpp b/dbcon/dmlpackage/dmlcolumn.cpp index 9bd0f67a..ad61be34 100644 --- a/dbcon/dmlpackage/dmlcolumn.cpp +++ b/dbcon/dmlpackage/dmlcolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlcolumn.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmlcolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -97,7 +97,7 @@ int DMLColumn::write(messageqcpp::ByteStream& bytestream) { int retval = 1; bytestream << fName; - bytestream << static_cast(fisNULL); + bytestream << static_cast(fisNULL); uint32_t vectorSize = fColValuesList.size(); bytestream << vectorSize; if (vectorSize > 0 ) @@ -110,8 +110,8 @@ int DMLColumn::write(messageqcpp::ByteStream& bytestream) } else bytestream << fData; //deprecated. - //bytestream << static_cast(fisNULL); - bytestream << static_cast(fIsFromCol); + //bytestream << static_cast(fisNULL); + bytestream << static_cast(fIsFromCol); bytestream <<(uint32_t)fFuncScale; return retval; } diff --git a/dbcon/dmlpackage/dmlcolumn.h b/dbcon/dmlpackage/dmlcolumn.h index 343f14ea..2ced783a 100644 --- a/dbcon/dmlpackage/dmlcolumn.h +++ b/dbcon/dmlpackage/dmlcolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlcolumn.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmlcolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlobject.cpp b/dbcon/dmlpackage/dmlobject.cpp index ce317f28..243c264d 100644 --- a/dbcon/dmlpackage/dmlobject.cpp +++ b/dbcon/dmlpackage/dmlobject.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlobject.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmlobject.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlobject.h b/dbcon/dmlpackage/dmlobject.h index 38558530..411ae098 100644 --- a/dbcon/dmlpackage/dmlobject.h +++ b/dbcon/dmlpackage/dmlobject.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlobject.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmlobject.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlpackage.h b/dbcon/dmlpackage/dmlpackage.h index 541585da..9386c4c2 100644 --- a/dbcon/dmlpackage/dmlpackage.h +++ b/dbcon/dmlpackage/dmlpackage.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlpackage.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dmlpackage.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlparser.cpp b/dbcon/dmlpackage/dmlparser.cpp index 79b27397..7acaabe2 100644 --- a/dbcon/dmlpackage/dmlparser.cpp +++ b/dbcon/dmlpackage/dmlparser.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlparser.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dmlparser.cpp 8707 2012-07-13 19:08:12Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlparser.h b/dbcon/dmlpackage/dmlparser.h index 29a5f2c4..db0360cf 100644 --- a/dbcon/dmlpackage/dmlparser.h +++ b/dbcon/dmlpackage/dmlparser.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlparser.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dmlparser.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlpkg.cpp b/dbcon/dmlpackage/dmlpkg.cpp index 8f0c89db..57bd1af6 100644 --- a/dbcon/dmlpackage/dmlpkg.cpp +++ b/dbcon/dmlpackage/dmlpkg.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlpkg.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dmlpkg.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmlpkg.h b/dbcon/dmlpackage/dmlpkg.h index 37bebd5b..7bbe3569 100644 --- a/dbcon/dmlpackage/dmlpkg.h +++ b/dbcon/dmlpackage/dmlpkg.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlpkg.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: dmlpkg.h 8775 2012-08-01 16:12:11Z dhall $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmltable.cpp b/dbcon/dmlpackage/dmltable.cpp index c7bd8fec..d3e14765 100644 --- a/dbcon/dmlpackage/dmltable.cpp +++ b/dbcon/dmlpackage/dmltable.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmltable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmltable.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/dmltable.h b/dbcon/dmlpackage/dmltable.h index 0f622ba8..d32d37c6 100644 --- a/dbcon/dmlpackage/dmltable.h +++ b/dbcon/dmlpackage/dmltable.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmltable.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmltable.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/insertdmlpackage.cpp b/dbcon/dmlpackage/insertdmlpackage.cpp index 9caf5eb3..e4f2f3d0 100644 --- a/dbcon/dmlpackage/insertdmlpackage.cpp +++ b/dbcon/dmlpackage/insertdmlpackage.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: insertdmlpackage.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: insertdmlpackage.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -57,22 +57,20 @@ int InsertDMLPackage::write(messageqcpp::ByteStream& bytestream) messageqcpp::ByteStream::quadbyte session_id = fSessionID; bytestream << session_id; - bytestream << fUuid; - bytestream << fDMLStatement; bytestream << fDMLStatement; bytestream << fSchemaName; - bytestream << (uint8_t)fLogging; - bytestream << (uint8_t)fLogending; + bytestream << (uint8_t)fLogging; + bytestream << (uint8_t)fLogending; if (fTable != 0) { retval = fTable->write(bytestream); } - bytestream << fTableOid; - bytestream << static_cast(fIsInsertSelect); - bytestream << static_cast(fIsBatchInsert); - bytestream << static_cast(fIsAutocommitOn); - + bytestream << fTableOid; + bytestream << static_cast(fIsInsertSelect); + bytestream << static_cast(fIsBatchInsert); + bytestream << static_cast(fIsAutocommitOn); + return retval; } @@ -83,25 +81,24 @@ int InsertDMLPackage::read(messageqcpp::ByteStream& bytestream) messageqcpp::ByteStream::quadbyte session_id; bytestream >> session_id; fSessionID = session_id; - bytestream >> fUuid; std::string dmlStatement; bytestream >> fDMLStatement; - bytestream >> fSQLStatement; + bytestream >> fSQLStatement; bytestream >> fSchemaName; - uint8_t logging; - bytestream >> logging; - fLogging = (logging != 0); - uint8_t logending; - bytestream >> logending; - fLogending = (logending != 0); - + uint8_t logging; + bytestream >> logging; + fLogging = (logging != 0); + uint8_t logending; + bytestream >> logending; + fLogending = (logending != 0); + fTable = new DMLTable(); retval = fTable->read(bytestream); - bytestream >> fTableOid; - bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsInsertSelect); - bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsBatchInsert); - bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsAutocommitOn); + bytestream >> fTableOid; + bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsInsertSelect); + bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsBatchInsert); + bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsAutocommitOn); return retval; } @@ -153,27 +150,27 @@ int InsertDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows int InsertDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows ) { - int retval = 1; + int retval = 1; initializeTable(); - Row *aRowPtr = new Row(); - std::string colName; - std::vector colValList; - for (int j = 0; j < columns; j++) + Row *aRowPtr = new Row(); + std::string colName; + std::vector colValList; + for (int j = 0; j < columns; j++) { //Build a column list colName = colNameList[j]; - + colValList = tableValuesMap[j]; DMLColumn* aColumn = new DMLColumn(colName, colValList, false); (aRowPtr->get_ColumnList()).push_back(aColumn); } - //build a row list for a table + //build a row list for a table fTable->get_RowList().push_back(aRowPtr); - aRowPtr = NULL; - delete aRowPtr; - return retval; + aRowPtr = NULL; + delete aRowPtr; + return retval; } int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement) @@ -187,7 +184,7 @@ int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement) throw runtime_error("insertStmt.fValuesOrQueryPtr == NULL"); initializeTable(); - bool isNULL = false; + bool isNULL = false; // only if we don't have a select statement if (0 == insertStmt.fValuesOrQueryPtr->fQuerySpecPtr) { @@ -222,13 +219,13 @@ int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement) { colValue = *iter; if ( strcasecmp(colValue.c_str(), "NULL") == 0) - { - isNULL = true; - } - else - { - isNULL = false; - } + { + isNULL = true; + } + else + { + isNULL = false; + } DMLColumn *aColumn = new DMLColumn(colName,colValue, isNULL); (aRow->get_ColumnList()).push_back(aColumn); diff --git a/dbcon/dmlpackage/insertdmlpackage.h b/dbcon/dmlpackage/insertdmlpackage.h index 9f890dad..ed1a179a 100644 --- a/dbcon/dmlpackage/insertdmlpackage.h +++ b/dbcon/dmlpackage/insertdmlpackage.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: insertdmlpackage.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: insertdmlpackage.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/libdmlpackage.vcxproj b/dbcon/dmlpackage/libdmlpackage.vcxproj deleted file mode 100644 index ba5282f8..00000000 --- a/dbcon/dmlpackage/libdmlpackage.vcxproj +++ /dev/null @@ -1,240 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {B9045BCA-0955-4C5E-BCA4-5EE516838119} - libdmlpackage - - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - true - MachineX86 - - - - - X64 - - - Disabled - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dbcon/dmlpackage/libdmlpackage.vcxproj.filters b/dbcon/dmlpackage/libdmlpackage.vcxproj.filters deleted file mode 100644 index 2da0e80b..00000000 --- a/dbcon/dmlpackage/libdmlpackage.vcxproj.filters +++ /dev/null @@ -1,111 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/dbcon/dmlpackage/mysqldmlstatement.cpp b/dbcon/dmlpackage/mysqldmlstatement.cpp index 2a02464e..70140d26 100644 --- a/dbcon/dmlpackage/mysqldmlstatement.cpp +++ b/dbcon/dmlpackage/mysqldmlstatement.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: mysqldmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: mysqldmlstatement.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/mysqldmlstatement.h b/dbcon/dmlpackage/mysqldmlstatement.h index 8a761908..3fd6bd03 100644 --- a/dbcon/dmlpackage/mysqldmlstatement.h +++ b/dbcon/dmlpackage/mysqldmlstatement.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: mysqldmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: mysqldmlstatement.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/oracledmlstatement.cpp b/dbcon/dmlpackage/oracledmlstatement.cpp index b79ccad9..e9bf1787 100644 --- a/dbcon/dmlpackage/oracledmlstatement.cpp +++ b/dbcon/dmlpackage/oracledmlstatement.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: oracledmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: oracledmlstatement.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/oracledmlstatement.h b/dbcon/dmlpackage/oracledmlstatement.h index df350c8b..48d2f4e5 100644 --- a/dbcon/dmlpackage/oracledmlstatement.h +++ b/dbcon/dmlpackage/oracledmlstatement.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: oracledmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: oracledmlstatement.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/row.cpp b/dbcon/dmlpackage/row.cpp index fb8cb0bd..3fa94e9f 100644 --- a/dbcon/dmlpackage/row.cpp +++ b/dbcon/dmlpackage/row.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: row.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: row.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/row.h b/dbcon/dmlpackage/row.h index 921ba079..6dc77941 100644 --- a/dbcon/dmlpackage/row.h +++ b/dbcon/dmlpackage/row.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: row.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: row.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/updatedmlpackage.cpp b/dbcon/dmlpackage/updatedmlpackage.cpp index de634d32..e7b35e2e 100644 --- a/dbcon/dmlpackage/updatedmlpackage.cpp +++ b/dbcon/dmlpackage/updatedmlpackage.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: updatedmlpackage.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: updatedmlpackage.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -61,12 +61,10 @@ int UpdateDMLPackage::write(messageqcpp::ByteStream& bytestream) messageqcpp::ByteStream::quadbyte hasFilter = fHasFilter; bytestream << hasFilter; - bytestream << fUuid; - bytestream << fDMLStatement; bytestream << fSQLStatement; bytestream << fSchemaName; - bytestream << (uint8_t)fIsFromCol; + bytestream << (uint8_t)fIsFromCol; if (fTable != 0) { retval = fTable->write(bytestream); @@ -74,7 +72,7 @@ int UpdateDMLPackage::write(messageqcpp::ByteStream& bytestream) if(fHasFilter) { bytestream += *(fPlan.get()); - } + } return retval; } @@ -94,15 +92,13 @@ int UpdateDMLPackage::read(messageqcpp::ByteStream& bytestream) bytestream >> hasFilter; fHasFilter = (hasFilter != 0); - bytestream >> fUuid; - std::string dmlStatement; bytestream >> fDMLStatement; bytestream >> fSQLStatement; bytestream >> fSchemaName; - uint8_t isFromCol; - bytestream >> isFromCol; - fIsFromCol = (isFromCol != 0); + uint8_t isFromCol; + bytestream >> isFromCol; + fIsFromCol = (isFromCol != 0); fTable = new DMLTable(); retval = fTable->read(bytestream); if(fHasFilter) @@ -208,25 +204,25 @@ int UpdateDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows } int UpdateDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows ) { - int retval = 1; + int retval = 1; initializeTable(); - Row *aRowPtr = new Row(); - std::string colName; - std::vector colValList; - for (int j = 0; j < columns; j++) + Row *aRowPtr = new Row(); + std::string colName; + std::vector colValList; + for (int j = 0; j < columns; j++) { //Build a column list colName = colNameList[j]; - + colValList = tableValuesMap[j]; DMLColumn* aColumn = new DMLColumn(colName, colValList, false); (aRowPtr->get_ColumnList()).push_back(aColumn); } - //build a row list for a table + //build a row list for a table fTable->get_RowList().push_back(aRowPtr); - return retval; + return retval; } void UpdateDMLPackage::buildUpdateFromMysqlBuffer(UpdateSqlStatement& updateStmt) diff --git a/dbcon/dmlpackage/updatedmlpackage.h b/dbcon/dmlpackage/updatedmlpackage.h index f67c24ac..0e3b2daa 100644 --- a/dbcon/dmlpackage/updatedmlpackage.h +++ b/dbcon/dmlpackage/updatedmlpackage.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: updatedmlpackage.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: updatedmlpackage.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/vendordmlstatement.cpp b/dbcon/dmlpackage/vendordmlstatement.cpp index 0d680df2..4fe2fc0e 100644 --- a/dbcon/dmlpackage/vendordmlstatement.cpp +++ b/dbcon/dmlpackage/vendordmlstatement.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: vendordmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: vendordmlstatement.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackage/vendordmlstatement.h b/dbcon/dmlpackage/vendordmlstatement.h index e9f499a0..a90123cd 100644 --- a/dbcon/dmlpackage/vendordmlstatement.h +++ b/dbcon/dmlpackage/vendordmlstatement.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: vendordmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: vendordmlstatement.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackageproc/Makefile.am b/dbcon/dmlpackageproc/Makefile.am index fd409ae4..8576ed5c 100644 --- a/dbcon/dmlpackageproc/Makefile.am +++ b/dbcon/dmlpackageproc/Makefile.am @@ -14,6 +14,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) @@ -21,6 +25,7 @@ AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) lib_LTLIBRARIES = libdmlpackageproc.la libdmlpackageproc_la_SOURCES = deletepackageprocessor.cpp \ dmlpackageprocessor.cpp \ +dmlpackageprocessorfactory.cpp \ insertpackageprocessor.cpp \ updatepackageprocessor.cpp \ commandpackageprocessor.cpp \ @@ -28,6 +33,7 @@ autoincrementdata.cpp \ tablelockdata.cpp include_HEADERS = deletepackageprocessor.h \ dmlpackageprocessor.h \ +dmlpackageprocessorfactory.h \ insertpackageprocessor.h \ updatepackageprocessor.h \ commandpackageprocessor.h\ diff --git a/dbcon/dmlpackageproc/Makefile.in b/dbcon/dmlpackageproc/Makefile.in index 29a5d9ec..629d7329 100644 --- a/dbcon/dmlpackageproc/Makefile.in +++ b/dbcon/dmlpackageproc/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -41,9 +60,8 @@ subdir = dbcon/dmlpackageproc DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -60,9 +78,10 @@ libLTLIBRARIES_INSTALL = $(INSTALL) LTLIBRARIES = $(lib_LTLIBRARIES) libdmlpackageproc_la_LIBADD = am_libdmlpackageproc_la_OBJECTS = deletepackageprocessor.lo \ - dmlpackageprocessor.lo insertpackageprocessor.lo \ - updatepackageprocessor.lo commandpackageprocessor.lo \ - autoincrementdata.lo tablelockdata.lo + dmlpackageprocessor.lo dmlpackageprocessorfactory.lo \ + insertpackageprocessor.lo updatepackageprocessor.lo \ + commandpackageprocessor.lo autoincrementdata.lo \ + tablelockdata.lo libdmlpackageproc_la_OBJECTS = $(am_libdmlpackageproc_la_OBJECTS) DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp @@ -141,9 +160,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -185,7 +201,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -199,11 +214,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -214,23 +224,6 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) @@ -238,6 +231,7 @@ AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) lib_LTLIBRARIES = libdmlpackageproc.la libdmlpackageproc_la_SOURCES = deletepackageprocessor.cpp \ dmlpackageprocessor.cpp \ +dmlpackageprocessorfactory.cpp \ insertpackageprocessor.cpp \ updatepackageprocessor.cpp \ commandpackageprocessor.cpp \ @@ -246,6 +240,7 @@ tablelockdata.cpp include_HEADERS = deletepackageprocessor.h \ dmlpackageprocessor.h \ +dmlpackageprocessorfactory.h \ insertpackageprocessor.h \ updatepackageprocessor.h \ commandpackageprocessor.h\ @@ -325,6 +320,7 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/commandpackageprocessor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/deletepackageprocessor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dmlpackageprocessor.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dmlpackageprocessorfactory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/insertpackageprocessor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tablelockdata.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/updatepackageprocessor.Plo@am__quote@ diff --git a/dbcon/dmlpackageproc/autoincrementdata.cpp b/dbcon/dmlpackageproc/autoincrementdata.cpp index 4159a7b3..9f4c656e 100644 --- a/dbcon/dmlpackageproc/autoincrementdata.cpp +++ b/dbcon/dmlpackageproc/autoincrementdata.cpp @@ -1,19 +1,19 @@ -/* Copyright (C) 2014 InfiniDB, Inc. +/* + Copyright (C) 2009-2012 Calpont Corporation. - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ // $Id: autoincrementdata.h 525 2010-01-19 23:18:05Z xlou $ // @@ -52,7 +52,7 @@ AutoincrementData* AutoincrementData::makeAutoincrementData(uint32_t sessionID) } /* static */ -void AutoincrementData::removeAutoincrementData(uint32_t sessionID) +void AutoincrementData::removeAutoincrementData(u_int32_t sessionID) { boost::mutex::scoped_lock lock(map_mutex); AutoincDataMap::iterator it = fAutoincDataMap.find(sessionID); diff --git a/dbcon/dmlpackageproc/autoincrementdata.h b/dbcon/dmlpackageproc/autoincrementdata.h index bc824a2b..fbd7d98a 100644 --- a/dbcon/dmlpackageproc/autoincrementdata.h +++ b/dbcon/dmlpackageproc/autoincrementdata.h @@ -1,22 +1,22 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id$ +/* + Copyright (C) 2009-2012 Calpont Corporation. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// $Id: activestatementcounter.h 525 2010-01-19 23:18:05Z xlou $ +// /** @file */ #ifndef AUTOINCREMENTDATA_H__ diff --git a/dbcon/dmlpackageproc/commandpackageprocessor.cpp b/dbcon/dmlpackageproc/commandpackageprocessor.cpp index 17d0868f..1cb54274 100644 --- a/dbcon/dmlpackageproc/commandpackageprocessor.cpp +++ b/dbcon/dmlpackageproc/commandpackageprocessor.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: commandpackageprocessor.cpp 9613 2013-06-12 15:44:24Z dhall $ + * $Id: commandpackageprocessor.cpp 8923 2012-09-19 18:14:01Z dcathey $ * * ***********************************************************************/ @@ -27,7 +27,9 @@ #include #include +#define COMMANDPKGPROC_DLLEXPORT #include "commandpackageprocessor.h" +#undef COMMANDPKGPROC_DLLEXPORT #include "messagelog.h" #include "dbrm.h" #include "sqllogger.h" @@ -46,6 +48,30 @@ using namespace logging; using namespace boost; using namespace BRM; +namespace +{ +void invalidateCPData(CalpontSystemCatalog::SCN txnid) +{ + scoped_ptr dbrmp(new DBRM()); + vector lbidList; + dbrmp->getUncommittedExtentLBIDs(static_cast(txnid), lbidList); + vector::const_iterator iter = lbidList.begin(); + vector::const_iterator end = lbidList.end(); + CPInfoList_t cpInfos; + CPInfo aInfo; + while (iter != end) + { + aInfo.firstLbid = *iter; + aInfo.max = numeric_limits::min(); + aInfo.min = numeric_limits::max(); + aInfo.seqNum = -1; + cpInfos.push_back(aInfo); + ++iter; + } + dbrmp->setExtentsMaxMin(cpInfos); +} +} + namespace dmlpackageprocessor { // Tracks active cleartablelock commands by storing set of table lock IDs @@ -67,37 +93,10 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) boost::algorithm::to_upper(stmt); trim(stmt); fSessionID = cpackage.get_SessionID(); - BRM::TxnID txnid = fSessionManager.getTxnID(cpackage.get_SessionID()); - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - logging::Message::Args args; - logging::Message message(9); - args.add(ex.what()); - message.format(args); - result.result = COMMAND_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - catch ( ... ) - { - logging::Message::Args args; - logging::Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = COMMAND_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - + uint64_t uniqueId = fDbrm.getUnique64(); string errorMsg; bool queRemoved = false; + BRM::TxnID txnid = fSessionManager.getTxnID(cpackage.get_SessionID()); logging::LoggingID lid(20); logging::MessageLog ml(lid); LoggingID logid( DMLLoggingId, fSessionID, txnid.id); @@ -122,7 +121,7 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) if ((txnid.valid)) { vector lbidList; - fDbrm->getUncommittedExtentLBIDs(static_cast(txnid.id), lbidList); + fDbrm.getUncommittedExtentLBIDs(static_cast(txnid.id), lbidList); bool cpInvalidated = false; //cout << "get a valid txnid " << txnid.id << " and stmt is " << stmt << " and isBachinsert is " << cpackage.get_isBatchInsert() << endl; if ((stmt == "COMMIT") && (cpackage.get_isBatchInsert())) @@ -131,57 +130,50 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); CalpontSystemCatalog::TableName tableName; tableName = systemCatalogPtr->tableName(cpackage.getTableOid()); - try - { - uint64_t nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); - if (nextVal != AUTOINCR_SATURATED) //need to update syscolumn - { - //get autoincrement column oid - int32_t columnOid = systemCatalogPtr->autoColumOid(tableName); - //get the current nextVal from controller - scoped_ptr aDbrm(new DBRM()); - uint64_t nextValInController = 0; - bool validNextVal = false; - aDbrm->getAILock(columnOid); - nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); //in case it has changed - validNextVal = aDbrm->getAIValue(columnOid, &nextValInController); - if ((validNextVal) && (nextValInController > nextVal)) - { - fWEClient->removeQueue(uniqueId); - queRemoved = true; - WE_DDLCommandClient ddlClient; - uint8_t rc = ddlClient.UpdateSyscolumnNextval(columnOid, nextValInController); - //@bug 5894. Need release lock. - aDbrm->releaseAILock(columnOid); - if (rc != 0) - throw std::runtime_error("Error in UpdateSyscolumnNextval"); - } - else - aDbrm->releaseAILock(columnOid); - } - } - catch (std::exception& ex) - { - //Rollback transaction - rollBackTransaction(uniqueId, txnid, fSessionID, errorMsg); - fSessionManager.rolledback( txnid ); - throw std::runtime_error(ex.what()); - } + long long nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); + if (nextVal > 0) //neet to update syscolumn + { + //get autoincrement column oid + int32_t columnOid = systemCatalogPtr->autoColumOid(tableName); + //get the current nextVal from controller + DBRM aDbrm; + uint64_t nextValInController = 0; + bool validNextVal = false; + try { + aDbrm.getAILock(columnOid); + nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); //in case it has changed + validNextVal = aDbrm.getAIValue(columnOid, &nextValInController); + } + catch (std::exception& ex) + { + //Rollback transaction + rollBackTransaction(uniqueId, txnid, fSessionID, errorMsg); + fSessionManager.rolledback( txnid ); + throw std::runtime_error(ex.what()); + } + if ((validNextVal) && (nextValInController > (uint64_t)nextVal)) + { + fWEClient->removeQueue(uniqueId); + queRemoved = true; + WE_DDLCommandClient ddlClient; + uint8_t rc = ddlClient.UpdateSyscolumnNextval(columnOid, nextValInController); + if (rc != 0) + throw std::runtime_error("Error in UpdateSyscolumnNextval"); + } + } //systemCatalogPtr->updateColinfoCache(nextValMap); int weRc = 0; if (cpackage.get_isAutocommitOn()) { weRc = commitBatchAutoOnTransaction(uniqueId, txnid, cpackage.getTableOid(), errorMsg); - if (weRc != 0) - BRM::errString(weRc, errorMsg); cpInvalidated = true; } else { - weRc = fDbrm->vbCommit(txnid.id); + weRc = fDbrm.vbCommit(txnid.id); if (weRc != 0) BRM::errString(weRc, errorMsg); - //weRc = commitBatchAutoOffTransaction(uniqueId, txnid, cpackage.getTableOid(), errorMsg); + weRc = commitBatchAutoOffTransaction(uniqueId, txnid, cpackage.getTableOid(), errorMsg); } if (weRc != 0) @@ -199,7 +191,7 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); CalpontSystemCatalog::TableName tableName; uint32_t tableOid = cpackage.getTableOid(); - std::vector tableLocks = fDbrm->getAllTableLocks(); + std::vector tableLocks = fDbrm.getAllTableLocks(); if (tableOid == 0) //special case: transaction commit for autocommit off and not following a dml statement immediately { TablelockData * tablelockData = TablelockData::makeTablelockData(fSessionID); @@ -213,49 +205,48 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) if ( iter != tablelockMap.end() ) { tableName = systemCatalogPtr->tableName(tableLocks[k].tableOID); - try - { - uint64_t nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); - if (nextVal != AUTOINCR_SATURATED) //neet to update syscolumn - { - //get autoincrement column oid - int32_t columnOid = systemCatalogPtr->autoColumOid(tableName); - //get the current nextVal from controller - scoped_ptr aDbrm(new DBRM()); - uint64_t nextValInController = 0; - bool validNextVal = false; - aDbrm->getAILock(columnOid); + long long nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); + if (nextVal > 0) //neet to update syscolumn + { + //get autoincrement column oid + int32_t columnOid = systemCatalogPtr->autoColumOid(tableName); + //get the current nextVal from controller + DBRM aDbrm; + uint64_t nextValInController = 0; + bool validNextVal = false; + try { + aDbrm.getAILock(columnOid); nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); //in case it has changed - validNextVal = aDbrm->getAIValue(columnOid, &nextValInController); + validNextVal = aDbrm.getAIValue(columnOid, &nextValInController); + } + catch (std::exception& ex) + { + //Rollback transaction, release tablelock + rollBackTransaction(uniqueId, txnid, fSessionID, errorMsg); + fDbrm.releaseTableLock(iter->second); + fSessionManager.rolledback( txnid ); + throw std::runtime_error(ex.what()); + } - if ((validNextVal) && (nextValInController > (uint64_t)nextVal)) - { - fWEClient->removeQueue(uniqueId); - - queRemoved = true; - WE_DDLCommandClient ddlClient; - uint8_t rc = ddlClient.UpdateSyscolumnNextval(columnOid, nextValInController,fSessionID); - aDbrm->releaseAILock(columnOid); - if (rc != 0) - { - //for now - fSessionManager.committed( txnid ); - throw std::runtime_error("Error in UpdateSyscolumnNextval"); - } - } - else - aDbrm->releaseAILock(columnOid); - } + if ((validNextVal) && (nextValInController > (uint64_t)nextVal)) + { + fWEClient->removeQueue(uniqueId); + + queRemoved = true; + WE_DDLCommandClient ddlClient; + uint8_t rc = ddlClient.UpdateSyscolumnNextval(columnOid, nextValInController,fSessionID); + aDbrm.releaseAILock(columnOid); + if (rc != 0) + { + //for now + fSessionManager.committed( txnid ); + throw std::runtime_error("Error in UpdateSyscolumnNextval"); + } + } + else + aDbrm.releaseAILock(columnOid); } - catch (std::exception& ex) - { - //Rollback transaction, release tablelock - rollBackTransaction(uniqueId, txnid, fSessionID, errorMsg); - fDbrm->releaseTableLock(iter->second); - fSessionManager.rolledback( txnid ); - throw std::runtime_error(ex.what()); - } } } } @@ -265,57 +256,56 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) if (tableOid >= 3000) { tableName = systemCatalogPtr->tableName(tableOid); - try - { - uint64_t nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); - if (nextVal != AUTOINCR_SATURATED) //need to update syscolumn - { - //get autoincrement column oid - int32_t columnOid = systemCatalogPtr->autoColumOid(tableName); - //get the current nextVal from controller - scoped_ptr aDbrm(new DBRM()); - uint64_t nextValInController = 0; - bool validNextVal = false; - aDbrm->getAILock(columnOid); - nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); //in case it has changed - validNextVal = aDbrm->getAIValue(columnOid, &nextValInController); - if ((validNextVal) && (nextValInController > (uint64_t)nextVal)) - { - fWEClient->removeQueue(uniqueId); - - queRemoved = true; - WE_DDLCommandClient ddlClient; - uint8_t rc = ddlClient.UpdateSyscolumnNextval(columnOid, nextValInController,fSessionID); - aDbrm->releaseAILock(columnOid); - if (rc != 0) - { - //for now - fSessionManager.committed( txnid ); - throw std::runtime_error("Error in UpdateSyscolumnNextval"); - } - } - else - aDbrm->releaseAILock(columnOid); - } + long long nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); + if (nextVal > 0) //neet to update syscolumn + { + //get autoincrement column oid + int32_t columnOid = systemCatalogPtr->autoColumOid(tableName); + //get the current nextVal from controller + DBRM aDbrm; + uint64_t nextValInController = 0; + bool validNextVal = false; + try { + aDbrm.getAILock(columnOid); + nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); //in case it has changed + validNextVal = aDbrm.getAIValue(columnOid, &nextValInController); + } + catch (std::exception& ex) + { + //Rollback transaction, release tablelock + rollBackTransaction(uniqueId, txnid, fSessionID, errorMsg); + for ( unsigned k=0; k < tableLocks.size(); k++) + { + if ( tableLocks[k].tableOID == tableOid ) + { + try { + fDbrm.releaseTableLock(tableLocks[k].id); + } + catch (std::exception&) + {} + } + } + fSessionManager.rolledback( txnid ); + throw std::runtime_error(ex.what()); + } + if ((validNextVal) && (nextValInController > (uint64_t)nextVal)) + { + fWEClient->removeQueue(uniqueId); + + queRemoved = true; + WE_DDLCommandClient ddlClient; + uint8_t rc = ddlClient.UpdateSyscolumnNextval(columnOid, nextValInController,fSessionID); + aDbrm.releaseAILock(columnOid); + if (rc != 0) + { + //for now + fSessionManager.committed( txnid ); + throw std::runtime_error("Error in UpdateSyscolumnNextval"); + } + } + else + aDbrm.releaseAILock(columnOid); } - catch (std::exception& ex) - { - //Rollback transaction, release tablelock - rollBackTransaction(uniqueId, txnid, fSessionID, errorMsg); - for ( unsigned k=0; k < tableLocks.size(); k++) - { - if ( tableLocks[k].tableOID == tableOid ) - { - try { - fDbrm->releaseTableLock(tableLocks[k].id); - } - catch (std::exception&) - {} - } - } - fSessionManager.rolledback( txnid ); - throw std::runtime_error(ex.what()); - } } } int weRc = commitTransaction(uniqueId, txnid ); @@ -342,7 +332,28 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) if (weRc == 0) { //@Bug 4560 invalidate cp first as bulkrollback will truncate the newly added lbids. - fDbrm->invalidateUncommittedExtentLBIDs(0, &lbidList); + vector::const_iterator iter = lbidList.begin(); + vector::const_iterator end = lbidList.end(); + CPInfoList_t cpInfos; + CPInfo aInfo; + while (iter != end) + { + aInfo.firstLbid = *iter; + aInfo.max = numeric_limits::min(); + aInfo.min = numeric_limits::max(); + aInfo.seqNum = -1; + cpInfos.push_back(aInfo); + ++iter; + } + std::vector allHwm; + std::vector mergeCPDataArgs; + int brmRc = fDbrm.bulkSetHWMAndCP(allHwm, cpInfos, mergeCPDataArgs, 0); + if (brmRc != 0) + { + string errMsg; + BRM::errString(brmRc, errMsg); + throw std::runtime_error(errMsg); + } cpInvalidated = true; weRc = rollBackBatchAutoOnTransaction(uniqueId, txnid, fSessionID, cpackage.getTableOid(), errorMsg); @@ -358,7 +369,7 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) //@Bug 4524. Don't set to readonly. Just error out. WErrorCodes ec; ostringstream oss; - oss << "ROLLBACK batch insert failed due to: " << "(" << weRc << ")" << ec.errorString(weRc); + oss << "ROLLBACK failed due to: " << ec.errorString(weRc); //Log to error log logging::Message::Args args1; logging::Message message1(2); @@ -395,7 +406,28 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) if (!cpInvalidated) { - fDbrm->invalidateUncommittedExtentLBIDs(0, &lbidList); + vector::const_iterator iter = lbidList.begin(); + vector::const_iterator end = lbidList.end(); + CPInfoList_t cpInfos; + CPInfo aInfo; + while (iter != end) + { + aInfo.firstLbid = *iter; + aInfo.max = numeric_limits::min(); + aInfo.min = numeric_limits::max(); + aInfo.seqNum = -1; + cpInfos.push_back(aInfo); + ++iter; + } + std::vector allHwm; + std::vector mergeCPDataArgs; + int brmRc = fDbrm.bulkSetHWMAndCP(allHwm, cpInfos, mergeCPDataArgs, 0); + if (brmRc != 0) + { + string errMsg; + BRM::errString(brmRc, errMsg); + throw std::runtime_error(errMsg); + } } } } @@ -481,7 +513,7 @@ CommandPackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) { try { - lockReleased = fDbrm->releaseTableLock(it->second); + lockReleased = fDbrm.releaseTableLock(it->second); //cout << "releasing tablelock " << it->second << endl; } catch (std::exception& ex) @@ -555,7 +587,7 @@ void CommandPackageProcessor::viewTableLock( // Get list of table locks for the requested table std::vector tableLocks; - tableLocks = fDbrm->getAllTableLocks(); + tableLocks = fDbrm.getAllTableLocks(); // Make preliminary pass through the table locks in order to determine our // output column widths based on the data. Min column widths are based on @@ -760,7 +792,7 @@ void CommandPackageProcessor::clearTableLock( uint64_t uniqueId, try { // Make sure BRM is in READ-WRITE state before starting - int brmRc = fDbrm->isReadWrite( ); + int brmRc = fDbrm.isReadWrite( ); if (brmRc != BRM::ERR_OK) { std::string brmErrMsg; @@ -887,7 +919,7 @@ void CommandPackageProcessor::clearTableLock( uint64_t uniqueId, // We ignore the return stateChange flag. if (!bErrFlag) { - fDbrm->changeState( tableLockID, BRM::CLEANUP ); + fDbrm.changeState( tableLockID, BRM::CLEANUP ); } } // end of (lockInfo.state == BRM::LOADING) @@ -956,7 +988,7 @@ void CommandPackageProcessor::clearTableLock( uint64_t uniqueId, // We ignore return release flag from releaseTableLock(). if (!bErrFlag) { - fDbrm->releaseTableLock( tableLockID ); + fDbrm.releaseTableLock( tableLockID ); } } } @@ -1031,7 +1063,7 @@ void CommandPackageProcessor::establishTableLockToClear( uint64_t tableLockID, boost::mutex::scoped_lock lock( fActiveClearTableLockCmdMutex ); // Get current table lock info - bool getLockInfo = fDbrm->getTableLockInfo(tableLockID, &lockInfo); + bool getLockInfo = fDbrm.getTableLockInfo(tableLockID, &lockInfo); if (!getLockInfo) { @@ -1039,7 +1071,7 @@ void CommandPackageProcessor::establishTableLockToClear( uint64_t tableLockID, } std::string processName("DMLProc clearTableLock"); - uint32_t processID = ::getpid(); + u_int32_t processID = ::getpid(); // See if another thread is executing a cleartablelock cmd for this table if ((lockInfo.ownerName == processName) && @@ -1060,7 +1092,7 @@ void CommandPackageProcessor::establishTableLockToClear( uint64_t tableLockID, // from a DMLProc lock used for inserts, updates, etc. int32_t sessionID = fSessionID; int32_t txnid = -1; - bool ownerChanged = fDbrm->changeOwner( + bool ownerChanged = fDbrm.changeOwner( tableLockID, processName, processID, sessionID, txnid); if (!ownerChanged) { diff --git a/dbcon/dmlpackageproc/commandpackageprocessor.h b/dbcon/dmlpackageproc/commandpackageprocessor.h index 05baf058..b3d8eb6c 100644 --- a/dbcon/dmlpackageproc/commandpackageprocessor.h +++ b/dbcon/dmlpackageproc/commandpackageprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: commandpackageprocessor.h 9302 2013-03-07 16:06:59Z chao $ +* $Id: commandpackageprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -34,7 +34,7 @@ #include #include -#if defined(_MSC_VER) && defined(DMLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(COMMANDPKGPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -50,7 +50,6 @@ class CommandPackageProcessor : public DMLPackageProcessor { public: - CommandPackageProcessor(BRM::DBRM* aDbrm, uint32_t sid) : DMLPackageProcessor(aDbrm, sid){} /** @brief process an CommandDMLPackage * * @param cpackage the CommandDMLPackage to process diff --git a/dbcon/dmlpackageproc/deletepackageprocessor.cpp b/dbcon/dmlpackageproc/deletepackageprocessor.cpp index 58a4f356..d724dd35 100644 --- a/dbcon/dmlpackageproc/deletepackageprocessor.cpp +++ b/dbcon/dmlpackageproc/deletepackageprocessor.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: deletepackageprocessor.cpp 9673 2013-07-09 15:59:49Z chao $ + * $Id: deletepackageprocessor.cpp 9138 2012-12-11 20:13:47Z chao $ * * ***********************************************************************/ @@ -24,7 +24,9 @@ #include #include using namespace std; +#define DELETEPKGPROC_DLLEXPORT #include "deletepackageprocessor.h" +#undef DELETEPKGPROC_DLLEXPORT #include "writeengine.h" #include "joblistfactory.h" #include "messagelog.h" @@ -54,8 +56,10 @@ using namespace BRM; using namespace rowgroup; using namespace messageqcpp; using namespace oam; + namespace dmlpackageprocessor { + std::map pmStateDel; DMLPackageProcessor::DMLResult DeletePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) { @@ -64,41 +68,11 @@ namespace dmlpackageprocessor DMLResult result; result.result = NO_ERROR; BRM::TxnID txnid; - // set-up the transaction - txnid.id = cpackage.get_TxnID(); - txnid.valid = true; fSessionID = cpackage.get_SessionID(); //StopWatch timer; VERBOSE_INFO("DeletePackageProcessor is processing CalpontDMLPackage ..."); TablelockData * tablelockData = TablelockData::makeTablelockData(fSessionID); - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - logging::Message::Args args; - logging::Message message(9); - args.add(ex.what()); - message.format(args); - result.result = DELETE_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - catch ( ... ) - { - logging::Message::Args args; - logging::Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = DELETE_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - + uint64_t uniqueId = fDbrm.getUnique64(); uint64_t tableLockId = 0; // get the table object from the package DMLTable* tablePtr = cpackage.get_Table(); @@ -109,36 +83,40 @@ namespace dmlpackageprocessor aTableName.table = tableName; aTableName.schema = schemaName; fWEClient->addQueue(uniqueId); - execplan::CalpontSystemCatalog::ROPair roPair; try { - string stmt = cpackage.get_SQLStatement() + "|" + schemaName + "|"; - SQLLogger sqlLogger(stmt, DMLLoggingId, fSessionID, txnid.id); + // set-up the transaction + txnid.id = cpackage.get_TxnID(); + txnid.valid = true; + + SQLLogger sqlLogger(cpackage.get_SQLStatement(), DMLLoggingId, fSessionID, txnid.id); if ( 0 != tablePtr ) { + + execplan::CalpontSystemCatalog::ROPair roPair; roPair = csc->tableRID(aTableName); tableLockId = tablelockData->getTablelockId(roPair.objnum); //check whether this table is locked already for this session if (tableLockId == 0) { //cout << "tablelock is not found in cache " << endl; - uint32_t processID = ::getpid(); + u_int32_t processID = ::getpid(); int32_t txnId = txnid.id; std::string processName("DMLProc"); int32_t sessionId = fSessionID; int i = 0; OamCache * oamcache = OamCache::makeOamCache(); std::vector pmList = oamcache->getModuleIds(); - std::vector pms; + std::vector pms; for (unsigned i=0; i < pmList.size(); i++) { - pms.push_back((uint32_t)pmList[i]); + pms.push_back((uint)pmList[i]); } try { - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { @@ -175,7 +153,7 @@ namespace dmlpackageprocessor txnId = txnid.id; sessionId = fSessionID; processName = "DMLProc"; - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { @@ -188,7 +166,7 @@ namespace dmlpackageprocessor if (i >= numTries) //error out { - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; logging::Message::Args args; args.add(processName); args.add((uint64_t)processID); @@ -216,24 +194,16 @@ namespace dmlpackageprocessor colType = csc->colType(roPair.objnum); if (colType.autoincrement) { - try - { - uint64_t nextVal = csc->nextAutoIncrValue(aTableName); - fDbrm->startAISequence(roPair.objnum, nextVal, colType.colWidth, colType.colDataType); - break; //Only one autoincrement column per table - } - catch (std::exception& ex) - { - result.result = DELETE_ERROR; - throw std::runtime_error(ex.what()); - } + uint64_t nextVal = csc->nextAutoIncrValue(aTableName); + fDbrm.startAISequence(roPair.objnum, nextVal, colType.colWidth); + break; //Only one autoincrement column per table } ++rid_iterator; } uint64_t rowsProcessed = 0; - rowsProcessed = fixUpRows(cpackage, result, uniqueId, roPair.objnum); + rowsProcessed = fixUpRows(cpackage, result, uniqueId); //@Bug 4994 Cancelled job is not error if (result.result == JOB_CANCELED) throw std::runtime_error("Query execution was interrupted"); @@ -262,7 +232,7 @@ namespace dmlpackageprocessor { cerr << "DeletePackageProcessor::processPackage: caught unknown exception!" << endl; logging::Message::Args args; - logging::Message message(7); + logging::Message message(6); args.add( "Delete Failed: "); args.add( "encountered unknown exception" ); args.add(result.message.msg()); @@ -274,61 +244,9 @@ namespace dmlpackageprocessor } //timer.finish(); //@Bug 1886,2870 Flush VM cache only once per statement. - std::map oids; - int rc = 0; - if (result.result == NO_ERROR) - { - rc = flushDataFiles( result.result, oids, uniqueId, txnid, roPair.objnum); - if (rc != NO_ERROR) - { - cerr << "UpdatePackageProcessor::processPackage: write data to disk failed" << endl; - if (!fRollbackPending) - { - logging::Message::Args args; - logging::Message message(7); - args.add("Delete Failed: "); - args.add("error when writing data to disk"); - args.add(""); - args.add(""); - message.format(args); + std::map oids; + flushDataFiles(0, oids, uniqueId, txnid); - result.result = UPDATE_ERROR; - result.message = message; - } - result.rowCount = 0; - rc = endTransaction(uniqueId, txnid, false); - if ( (rc != NO_ERROR) && (!fRollbackPending)) - { - logging::Message::Args args; - logging::Message message(7); - args.add("Delete Failed: "); - args.add("error when cleaning up data files"); - args.add(""); - args.add(""); - message.format(args); - - result.result = UPDATE_ERROR; - result.message = message; - result.rowCount = 0; - - } - } - else - { - if (fRollbackPending) - rc = endTransaction(uniqueId, txnid, false); - else - rc = endTransaction(uniqueId, txnid, true); - } - } - else - { - rc = flushDataFiles( result.result, oids, uniqueId, txnid, roPair.objnum); - result.rowCount = 0; - rc = endTransaction(uniqueId, txnid, false); - } - - if (fRollbackPending) { result.result = JOB_CANCELED; @@ -343,26 +261,58 @@ namespace dmlpackageprocessor return result; } - uint64_t DeletePackageProcessor::fixUpRows (dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId, const uint32_t tableOid) + uint64_t DeletePackageProcessor::fixUpRows (dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId) { ByteStream msg, msgBk, emsgBs; - rowgroup::RGData rgData; ByteStream::quadbyte qb = 4; msg << qb; boost::scoped_ptr rowGroup; uint64_t rowsProcessed = 0; - uint32_t dbroot = 1; + uint dbroot = 1; bool metaData = false; oam::OamCache * oamCache = oam::OamCache::makeOamCache(); std::vector fPMs = oamCache->getModuleIds(); - std::map pmStateDel; - //boost::scoped_ptr fExeMgr; - //fExeMgr.reset( new messageqcpp::MessageQueueClient("ExeMgr1")); + try { +#if !defined(_MSC_VER) && !defined(SKIP_OAM_INIT) + //@Bug 4495 check PM status first + std::vector tmpPMs; + for (unsigned i=0; iwrite(msg); fExeMgr->write(*(cpackage.get_ExecutionPlan())); //cout << "sending to ExeMgr plan with length " << (cpackage.get_ExecutionPlan())->length() << endl; @@ -381,7 +331,7 @@ namespace dmlpackageprocessor args.add("Update Failed: "); args.add("Lost connection to ExeMgr"); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; return rowsProcessed; } @@ -405,7 +355,7 @@ namespace dmlpackageprocessor args.add("Delete Failed: "); args.add(emsgStr); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; return rowsProcessed; } @@ -430,7 +380,7 @@ namespace dmlpackageprocessor args.add("Delete Failed: "); args.add("Lost connection to ExeMgr"); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; //return rowsProcessed; break; @@ -442,7 +392,7 @@ namespace dmlpackageprocessor //This is meta data, need to send to all PMs. metaData = true; //cout << "sending meta data" << endl; - err = processRowgroup(msgBk, result, uniqueId, cpackage, pmStateDel, metaData, dbroot); + err = processRowgroup(msgBk, result, uniqueId, cpackage, metaData, dbroot); rowGroup.reset(new rowgroup::RowGroup()); rowGroup->deserialize(msg); qb = 100; @@ -454,15 +404,11 @@ namespace dmlpackageprocessor continue; } - // XXXST: take out the 'true' when all jobsteps have been made st-compatible - uint32_t amount = rgData.deserialize(msg, true); - rowGroup->setData(&rgData); - //rowGroup->setData(const_cast(msg.buf())); + rowGroup->setData(const_cast(msg.buf())); err = (rowGroup->getStatus() != 0); if (err) { - msgBk.advance(amount); - //msgBk.advance(rowGroup->getDataSize()); + msgBk.advance(rowGroup->getDataSize()); string errorMsg; msgBk >> errorMsg; logging::Message::Args args; @@ -470,10 +416,10 @@ namespace dmlpackageprocessor args.add("Delete Failed: "); args.add(errorMsg); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; DMLResult tmpResult; - receiveAll( tmpResult, uniqueId, fPMs, pmStateDel, tableOid); + receiveAll( tmpResult, uniqueId, fPMs); //@Bug 4358 get rid of broken pipe error. //msg.restart(); //msg << qb; @@ -481,26 +427,26 @@ namespace dmlpackageprocessor //return rowsProcessed; break; } - if (rowGroup->getRGData() == NULL) + if (rowGroup->getData() == NULL) { msg.restart(); } if (rowGroup->getRowCount() == 0) //done fetching { - err = receiveAll( result, uniqueId, fPMs, pmStateDel, tableOid); + err = receiveAll( result, uniqueId, fPMs); //return rowsProcessed; break; } - if (rowGroup->getBaseRid() == (uint64_t) (-1)) + if (rowGroup->getBaseRid() == (uint64_t) (-1 & ~0x1fff)) { continue; // @bug4247, not valid row ids, may from small side outer } dbroot = rowGroup->getDBRoot(); - err = processRowgroup(msgBk, result, uniqueId, cpackage, pmStateDel, metaData, dbroot); + err = processRowgroup(msgBk, result, uniqueId, cpackage, metaData, dbroot); if (err) { DMLResult tmpResult; - receiveAll( tmpResult, uniqueId, fPMs, pmStateDel, tableOid); + receiveAll( tmpResult, uniqueId, fPMs); //@Bug 4358 get rid of broken pipe error. //msg.restart(); //msg << qb; @@ -530,7 +476,7 @@ namespace dmlpackageprocessor // Clean out the pipe; DMLResult tmpResult; - receiveAll( tmpResult, uniqueId, fPMs, pmStateDel, tableOid); + receiveAll( tmpResult, uniqueId, fPMs); } if (!err) @@ -564,12 +510,8 @@ namespace dmlpackageprocessor args.add("Delete Failed: "); args.add(ex.what()); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; - qb = 0; - msg.restart(); - msg << qb; - fExeMgr->write(msg); return rowsProcessed; } catch ( ... ) @@ -580,12 +522,8 @@ namespace dmlpackageprocessor args.add("Update Failed: "); args.add("Unknown error caught when communicating with ExeMgr"); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; - qb = 0; - msg.restart(); - msg << qb; - fExeMgr->write(msg); return rowsProcessed; } @@ -593,7 +531,7 @@ namespace dmlpackageprocessor } bool DeletePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& result, const uint64_t uniqueId, - dmlpackage::CalpontDMLPackage& cpackage, std::map& pmStateDel, bool isMeta, uint32_t dbroot) + dmlpackage::CalpontDMLPackage& cpackage, bool isMeta, uint dbroot) { bool rc = false; //cout << "Get dbroot " << dbroot << endl; @@ -603,13 +541,13 @@ bool DeletePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& bytestream << (ByteStream::byte)WE_SVR_DELETE; bytestream << uniqueId; bytestream << (ByteStream::quadbyte) pmNum; - bytestream << uint32_t(cpackage.get_SessionID()); + bytestream << u_int32_t(cpackage.get_SessionID()); bytestream << (ByteStream::quadbyte) cpackage.get_TxnID(); bytestream << tablePtr->get_SchemaName(); bytestream << tablePtr->get_TableName(); bytestream += aRowGroup; //cout << "sending rows to pm " << pmNum << " with msg length " << bytestream.length() << endl; - uint32_t msgRecived = 0; + uint msgRecived = 0; boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); ByteStream::byte tmp8; @@ -622,7 +560,7 @@ bool DeletePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& fWEClient->write_to_all(bytestream); while (1) { - if (msgRecived == fWEClient->getPmCount()) + if (msgRecived == fPMCount) break; fWEClient->read(uniqueId, bsIn); if ( bsIn->length() == 0 ) //read error @@ -647,7 +585,7 @@ bool DeletePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& if (pmStateDel[pmNum]) { try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); //cout << "sent tp pm " << pmNum<& fPMs, - std::map& pmStateDel, const uint32_t tableOid) +bool DeletePackageProcessor::receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs) { //check how many message we need to receive - uint32_t messagesNotReceived = 0; + uint messagesNotReceived = 0; bool err = false; for (unsigned i=0; i bsIn; - uint32_t msgReceived = 0; - ByteStream::byte tmp8; - string errorMsg; if (messagesNotReceived > 0) { LoggingID logid( DMLLoggingId, fSessionID, fSessionID); - if ( messagesNotReceived > fWEClient->getPmCount()) + if ( messagesNotReceived > fPMCount) { logging::Message::Args args1; logging::Message msg(1); @@ -774,13 +707,17 @@ bool DeletePackageProcessor::receiveAll(DMLResult& result, const uint64_t unique args.add("Update Failed: "); args.add("One of WriteEngineServer went away."); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; return err; } + boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); + ByteStream::byte tmp8; + string errorMsg; ByteStream::quadbyte tmp32; + uint msgReceived = 0; uint64_t blocksChanged = 0; while (1) @@ -822,7 +759,7 @@ bool DeletePackageProcessor::receiveAll(DMLResult& result, const uint64_t unique args.add("Delete Failed: "); args.add(ex.what()); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; break; } @@ -834,13 +771,12 @@ bool DeletePackageProcessor::receiveAll(DMLResult& result, const uint64_t unique args.add("Delete Failed: "); args.add("Unknown error caught when communicating with WES"); message.format(args); - result.result = DELETE_ERROR; + result.result = UPDATE_ERROR; result.message = message; break; } } } - return err; } } // namespace dmlpackageprocessor diff --git a/dbcon/dmlpackageproc/deletepackageprocessor.h b/dbcon/dmlpackageproc/deletepackageprocessor.h index 3d39330a..5c75ff03 100644 --- a/dbcon/dmlpackageproc/deletepackageprocessor.h +++ b/dbcon/dmlpackageproc/deletepackageprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: deletepackageprocessor.h 9302 2013-03-07 16:06:59Z chao $ + * $Id: deletepackageprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -32,7 +32,7 @@ #include #include "joblist.h" -#if defined(_MSC_VER) && defined(DMLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(DELETEPKGPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -49,7 +49,7 @@ class DeletePackageProcessor : public DMLPackageProcessor public: - DeletePackageProcessor(BRM::DBRM* aDbrm, uint32_t sid) : DMLPackageProcessor(aDbrm, sid){} + DeletePackageProcessor() : DMLPackageProcessor(){} /** @brief process a DeleteDMLPackage * * @param cpackage the delete dml package to process @@ -71,16 +71,15 @@ class DeletePackageProcessor : public DMLPackageProcessor WriteEngine::RIDList& rowIDList, WriteEngine::ColValueList& colOldValuesList, DMLResult& result); */ - bool processRowgroup(messageqcpp::ByteStream & aRowGroup, DMLResult& result, const uint64_t uniqueId, dmlpackage::CalpontDMLPackage& cpackage, std::map& pmStateDel, - bool isMeta = false, uint32_t dbroot=1); + bool processRowgroup(messageqcpp::ByteStream & aRowGroup, DMLResult& result, const uint64_t uniqueId, dmlpackage::CalpontDMLPackage& cpackage, bool isMeta = false, uint dbroot=1); /** @brief add all rows if we have no filter for the delete * * @param tablePtr a pointer to the table that is being operated on */ - uint64_t fixUpRows(dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId, const uint32_t tableOid); - bool receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs, std::map& pmStateDel, const uint32_t tableOid); + uint64_t fixUpRows(dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId); + bool receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs); //bandListsByExtent bandListsMap; diff --git a/dbcon/dmlpackageproc/dmlpackageprocessor.cpp b/dbcon/dmlpackageproc/dmlpackageprocessor.cpp index fd296af7..cab2969d 100644 --- a/dbcon/dmlpackageproc/dmlpackageprocessor.cpp +++ b/dbcon/dmlpackageproc/dmlpackageprocessor.cpp @@ -16,11 +16,13 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlpackageprocessor.cpp 9673 2013-07-09 15:59:49Z chao $ + * $Id: dmlpackageprocessor.cpp 8953 2012-10-05 20:44:08Z dhall $ * * ***********************************************************************/ +#define DMLPKGPROC_DLLEXPORT #include "dmlpackageprocessor.h" +#undef DMLPKGPROC_DLLEXPORT #include using namespace std; @@ -63,19 +65,17 @@ const SOP opeq(new Operator("=")); const SOP opne(new Operator("<>")); const SOP opor(new Operator("or")); const SOP opand(new Operator("and")); +const int MAX_INT = numeric_limits::max(); +const short MAX_TINYINT = numeric_limits::max(); //127; +const short MAX_SMALLINT = numeric_limits::max(); //32767; +const long long MAX_BIGINT = numeric_limits::max();//9223372036854775807LL } namespace dmlpackageprocessor { DMLPackageProcessor::~DMLPackageProcessor() - { - //cout << "In DMLPackageProcessor destructor " << this << endl; - if (fWEClient) - delete fWEClient; - if (fExeMgr) - delete fExeMgr; - } + { } //@bug 397 void DMLPackageProcessor::cleanString(string& s) @@ -97,7 +97,7 @@ void DMLPackageProcessor::cleanString(string& s) s = s.substr(1, s.length()-2); } } -#if 0 + boost::any DMLPackageProcessor::tokenizeData( execplan::CalpontSystemCatalog::SCN txnID, execplan::CalpontSystemCatalog::ColType colType, const std::string& data, DMLResult& result, bool isNULL ) @@ -158,7 +158,7 @@ boost::any DMLPackageProcessor::tokenizeData( execplan::CalpontSystemCatalog::SC } return value; } -#endif + void DMLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string schema, std::string table, dmlpackage::ColumnList& colList) { @@ -222,7 +222,7 @@ void DMLPackageProcessor::convertRidToColumn(uint64_t& rid, unsigned& dbRoot, un } -string DMLPackageProcessor::projectTableErrCodeToMsg(uint32_t ec) +string DMLPackageProcessor::projectTableErrCodeToMsg(uint ec) { if (ec < 1000) // pre IDB error code { @@ -236,6 +236,60 @@ string DMLPackageProcessor::projectTableErrCodeToMsg(uint32_t ec) return IDBErrorInfo::instance()->errorMsg(ec); } +bool DMLPackageProcessor::validateNextValue(execplan::CalpontSystemCatalog::ColType colType, int64_t value, + bool& offByOne) +{ + bool validValue = true; + offByOne = false; + switch (colType.colDataType) + { + case CalpontSystemCatalog::BIGINT: + { + if (value > MAX_BIGINT) + { + validValue = false; + if ((value-1) == MAX_BIGINT) + offByOne = true; + } + break; + } + case CalpontSystemCatalog::INT: + { + if (value > MAX_INT) + { + validValue = false; + if ((value-1) == MAX_INT) + offByOne = true; + } + break; + } + case CalpontSystemCatalog::SMALLINT: + { + if (value > MAX_SMALLINT) + { + validValue = false; + if ((value-1) == MAX_SMALLINT) + offByOne = true; + } + break; + } + case CalpontSystemCatalog::TINYINT: + { + if (value > MAX_TINYINT) + { + validValue = false; + if ((value-1) == MAX_TINYINT) + offByOne = true; + } + break; + } + default: + validValue = false; + break; + } + return validValue; +} + bool DMLPackageProcessor::validateVarbinaryVal( std::string & inStr) { bool invalid = false; @@ -253,7 +307,7 @@ bool DMLPackageProcessor::validateVarbinaryVal( std::string & inStr) int DMLPackageProcessor::commitTransaction(uint64_t uniqueId, BRM::TxnID txnID) { - int rc = fDbrm->vbCommit(txnID.id); + int rc = fDbrm.vbCommit(txnID.id); return rc; } @@ -265,15 +319,12 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID BRM::LBIDRange range; int rc = 0; //Check BRM status before processing. - rc = fDbrm->isReadWrite(); + rc = fDbrm.isReadWrite(); if (rc != 0 ) { - std::string brmMsg; - errorMsg = "Can't read DBRM isReadWrite [ "; - BRM::errString(rc, brmMsg); - errorMsg += brmMsg; - errorMsg += "]"; + BRM::errString(rc, errorMsg); return rc; + } ByteStream bytestream; @@ -283,7 +334,7 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID bytestream << uniqueId; bytestream << sessionID; bytestream << (uint32_t)txnID.id; - uint32_t msgRecived = 0; + uint msgRecived = 0; try { fWEClient->write_to_all(bytestream); boost::shared_ptr bsIn; @@ -297,7 +348,6 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID if ( bsIn->length() == 0 ) //read error { rc = NETWORK_ERROR; - errorMsg = "Network error reading WEClient"; fWEClient->removeQueue(uniqueId); //cout << "erroring out remove queue id " << uniqueId << endl; break; @@ -306,12 +356,7 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID *bsIn >> tmp8; rc = tmp8; if (rc != 0) { - char szrc[20]; *bsIn >> errorMsg; - errorMsg += " (WriteEngine returns error "; - sprintf(szrc, "%d", rc); - errorMsg += szrc; - errorMsg += ")"; fWEClient->removeQueue(uniqueId); cout << "erroring out remove queue id " << uniqueId << endl; break; @@ -328,7 +373,6 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID errorMsg += e.what(); fWEClient->removeQueue(uniqueId); cout << "erroring out remove queue id " << uniqueId << endl; - //delete fWEClient; return rc; } catch ( ... ) @@ -337,28 +381,22 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID errorMsg = "Unknown exception caught while rolling back transaction."; fWEClient->removeQueue(uniqueId); cout << "erroring out remove queue id " << uniqueId << endl; - //delete fWEClient; return rc; } if (rc != 0) { - //delete fWEClient; return rc; } fWEClient->removeQueue(uniqueId); - //delete fWEClient; // cout << "success. remove queue id " << uniqueId << endl; - rc = fDbrm->getUncommittedLBIDs(txnID.id, lbidList); + rc = fDbrm.getUncommittedLBIDs(txnID.id, lbidList); if (rc != 0 ) { - std::string brmMsg; - errorMsg = "DBRM getUncommittedLBIDs [ "; - BRM::errString(rc, brmMsg); - errorMsg += brmMsg; - errorMsg += "]"; - return rc; + BRM::errString(rc, errorMsg); + return rc; + } for(size_t i = 0; i < lbidList.size(); i++) { @@ -366,16 +404,13 @@ int DMLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID range.size = 1; lbidRangeList.push_back(range); } - rc = fDbrm->vbRollback(txnID.id, lbidRangeList); + rc = fDbrm.vbRollback(txnID.id, lbidRangeList); if (rc != 0 ) { - std::string brmMsg; - errorMsg = "DBRM vbRollback [ "; - BRM::errString(rc, brmMsg); - errorMsg += brmMsg; - errorMsg += "]"; - return rc; + BRM::errString(rc, errorMsg); + return rc; + } return rc; @@ -385,6 +420,7 @@ int DMLPackageProcessor::commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::Tx { //collect hwm info from all pms and set them here. remove table metadata if all successful ByteStream bytestream; + //cout << "commiting batch insert " << endl; fWEClient->addQueue(uniqueId); bytestream << (ByteStream::byte)WE_SVR_COMMIT_BATCH_AUTO_ON; bytestream << uniqueId; @@ -392,7 +428,7 @@ int DMLPackageProcessor::commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::Tx bytestream << tableOid; bytestream << fSessionID; - uint32_t msgRecived = 0; + uint msgRecived = 0; fWEClient->write_to_all(bytestream); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -453,17 +489,7 @@ int DMLPackageProcessor::commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::Tx //cout << "setting hwm allHwm size " << allHwm.size() << endl; vector lbidList; - if (idbdatafile::IDBPolicy::useHdfs()) - { - BRM::LBID_t startLbid; - for ( unsigned i=0; i < allHwm.size(); i++) - { - rc = fDbrm->lookupLocalStartLbid(allHwm[i].oid, allHwm[i].partNum, allHwm[i].segNum, allHwm[i].hwm, startLbid); - lbidList.push_back(startLbid); - } - } - else - fDbrm->getUncommittedExtentLBIDs(static_cast(txnID.id), lbidList); + fDbrm.getUncommittedExtentLBIDs(static_cast(txnID.id), lbidList); vector::const_iterator iter = lbidList.begin(); vector::const_iterator end = lbidList.end(); BRM::CPInfoList_t cpInfos; @@ -471,15 +497,14 @@ int DMLPackageProcessor::commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::Tx while (iter != end) { aInfo.firstLbid = *iter; - aInfo.max = numeric_limits::min(); // Not used - aInfo.min = numeric_limits::max(); // Not used + aInfo.max = numeric_limits::min(); + aInfo.min = numeric_limits::max(); aInfo.seqNum = -1; cpInfos.push_back(aInfo); ++iter; } std::vector mergeCPDataArgs; - rc = fDbrm->bulkSetHWMAndCP(allHwm, cpInfos, mergeCPDataArgs, txnID.id); - fDbrm->takeSnapshot(); + rc = fDbrm.bulkSetHWMAndCP(allHwm, cpInfos, mergeCPDataArgs, txnID.id); //Set tablelock to rollforward remove meta files if (rc != 0) @@ -490,7 +515,7 @@ int DMLPackageProcessor::commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::Tx uint64_t tablelockId = tablelockData->getTablelockId(tableOid); try { - stateChanged = fDbrm->changeState(tablelockId, BRM::CLEANUP); + stateChanged = fDbrm.changeState(tablelockId, BRM::CLEANUP); } catch (std::exception&) { @@ -505,7 +530,6 @@ int DMLPackageProcessor::commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::Tx //@Bug 4517 Remove meta data failure doesn't stop tablelock releasing. bytestream << (ByteStream::byte)WE_SVR_BATCH_AUTOON_REMOVE_META; bytestream << uniqueId; - bytestream << tableOid; msgRecived = 0; fWEClient->write_to_all(bytestream); while (1) @@ -535,10 +559,10 @@ int DMLPackageProcessor::rollBackBatchAutoOnTransaction(uint64_t uniqueId, BRM:: //Bulkrollback, rollback blocks, vbrollback, change state, remove meta file //cout << "In rollBackBatchAutoOnTransaction" << endl; std::vector tableLocks; - tableLocks = fDbrm->getAllTableLocks(); + tableLocks = fDbrm.getAllTableLocks(); //cout << " Got all tablelocks" << endl; unsigned idx=0; - string ownerName ("DMLProc batchinsert"); + string ownerName ("DMLProc"); uint64_t tableLockId = 0; int rc = 0; for (; idxwrite_to_all(bytestream); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -602,7 +626,7 @@ int DMLPackageProcessor::rollBackBatchAutoOnTransaction(uint64_t uniqueId, BRM:: bool stateChanged = true; //cout << "changing tablelock state" << endl; try { - stateChanged = fDbrm->changeState(tableLockId, BRM::CLEANUP); + stateChanged = fDbrm.changeState(tableLockId, BRM::CLEANUP); } catch (std::exception&) { @@ -620,7 +644,6 @@ int DMLPackageProcessor::rollBackBatchAutoOnTransaction(uint64_t uniqueId, BRM:: bytestream.restart(); bytestream << (ByteStream::byte)WE_SVR_BATCH_AUTOON_REMOVE_META; bytestream << uniqueId; - bytestream << tableOid; msgRecived = 0; fWEClient->write_to_all(bytestream); while (1) @@ -631,14 +654,14 @@ int DMLPackageProcessor::rollBackBatchAutoOnTransaction(uint64_t uniqueId, BRM:: if ( bsIn->length() == 0 ) //read error { fWEClient->removeQueue(uniqueId); - //cout << "erroring out remove queue id " << uniqueId << endl; + cout << "erroring out remove queue id " << uniqueId << endl; break; } else { *bsIn >> tmp8; msgRecived++; } - } + } fWEClient->removeQueue(uniqueId); return rc; } @@ -646,10 +669,10 @@ int DMLPackageProcessor::rollBackBatchAutoOnTransaction(uint64_t uniqueId, BRM:: int DMLPackageProcessor::commitBatchAutoOffTransaction(uint64_t uniqueId, BRM::TxnID txnID, const uint32_t tableOid, std::string & errorMsg) { std::vector tableLocks; - tableLocks = fDbrm->getAllTableLocks(); + tableLocks = fDbrm.getAllTableLocks(); //cout << " Got all tablelocks" << endl; unsigned idx=0; - string ownerName ("DMLProc batchinsert"); + string ownerName ("DMLProc"); uint64_t tableLockId = 0; int rc = 0; boost::shared_ptr bsIn; @@ -675,7 +698,7 @@ int DMLPackageProcessor::commitBatchAutoOffTransaction(uint64_t uniqueId, BRM::T bool stateChanged = true; //cout << "changing tablelock state" << endl; try { - stateChanged = fDbrm->changeState(tableLockId, BRM::CLEANUP); + stateChanged = fDbrm.changeState(tableLockId, BRM::CLEANUP); } catch (std::exception&) { @@ -693,8 +716,7 @@ int DMLPackageProcessor::commitBatchAutoOffTransaction(uint64_t uniqueId, BRM::T fWEClient->addQueue(uniqueId); bytestream << (ByteStream::byte)WE_SVR_BATCH_AUTOON_REMOVE_META; bytestream << uniqueId; - bytestream << tableOid; - uint32_t msgRecived = 0; + uint msgRecived = 0; fWEClient->write_to_all(bytestream); while (1) { @@ -725,7 +747,7 @@ int DMLPackageProcessor::rollBackBatchAutoOffTransaction(uint64_t uniqueId, BRM: bytestream << sessionID; bytestream << (uint32_t)txnID.id; bytestream << tableOid; - uint32_t msgRecived = 0; + uint msgRecived = 0; fWEClient->write_to_all(bytestream); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -759,7 +781,7 @@ int DMLPackageProcessor::rollBackBatchAutoOffTransaction(uint64_t uniqueId, BRM: return rc; } -int DMLPackageProcessor::flushDataFiles (int rcIn, std::map & columnOids, uint64_t uniqueId, BRM::TxnID txnID, uint32_t tableOid) +int DMLPackageProcessor::flushDataFiles (int rcIn, std::map & columnOids, uint64_t uniqueId, BRM::TxnID txnID) { //cout <<"in flushDataFiles" << endl; ByteStream bytestream; @@ -767,8 +789,7 @@ int DMLPackageProcessor::flushDataFiles (int rcIn, std::map & columnOid bytestream << uniqueId; bytestream << (uint32_t) rcIn; bytestream << (uint32_t)txnID.id; - bytestream << tableOid; - uint32_t msgRecived = 0; + uint msgRecived = 0; fWEClient->write_to_all(bytestream); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -804,48 +825,5 @@ int DMLPackageProcessor::flushDataFiles (int rcIn, std::map & columnOid return rc; } -int DMLPackageProcessor::endTransaction (uint64_t uniqueId, BRM::TxnID txnID, bool success) -{ -//cout <<"in flushDataFiles" << endl; - ByteStream bytestream; - bytestream << (ByteStream::byte) WE_END_TRANSACTION; - bytestream << uniqueId; - bytestream << (uint32_t)txnID.id; - bytestream << (ByteStream::byte)success; - uint32_t msgRecived = 0; - fWEClient->write_to_all(bytestream); - boost::shared_ptr bsIn; - bsIn.reset(new ByteStream()); - int rc = 0; - ByteStream::byte tmp8; - std::string errorMsg; - try { - while (1) - { - if (msgRecived == fWEClient->getPmCount()) - break; - fWEClient->read(uniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - rc = NETWORK_ERROR; - break; - } - else { - *bsIn >> tmp8; - rc = tmp8; - if (rc != 0) { - *bsIn >> errorMsg; - break; - } - else - msgRecived++; - } - } - } - catch (std::exception&) { - } - - return rc; -} } // vim:ts=4 sw=4: diff --git a/dbcon/dmlpackageproc/dmlpackageprocessor.h b/dbcon/dmlpackageproc/dmlpackageprocessor.h index 5751dcb4..3de11fcd 100644 --- a/dbcon/dmlpackageproc/dmlpackageprocessor.h +++ b/dbcon/dmlpackageproc/dmlpackageprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: dmlpackageprocessor.h 9673 2013-07-09 15:59:49Z chao $ + * $Id: dmlpackageprocessor.h 8839 2012-08-28 21:49:45Z dhall $ * * ***********************************************************************/ @@ -42,7 +42,6 @@ #include "liboamcpp.h" #include "oamcache.h" #include "querystats.h" -#include "clientrotator.h" #if defined(_MSC_VER) && defined(DMLPKGPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) @@ -150,25 +149,13 @@ class DMLPackageProcessor /** @brief ctor */ - DMLPackageProcessor(BRM::DBRM* aDbrm, uint32_t sid) : fEC(0), DMLLoggingId(21), fRollbackPending(false), fDebugLevel(NONE) + DMLPackageProcessor() : fEC(0), DMLLoggingId(21), fRollbackPending(false), fDebugLevel(NONE) { - try { - fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DMLPROC); - //std::cout << "In DMLPackageProcessor constructor " << this << std::endl; + fWEClient = WriteEngine::WEClients::instance(WriteEngine::WEClients::DMLPROC); fPMCount = fWEClient->getPmCount(); - } - catch (...) - { - std::cout << "Cannot make connection to WES" << std::endl; - } - + fExeMgr.reset(new messageqcpp::MessageQueueClient("ExeMgr1")); oam::OamCache * oamCache = oam::OamCache::makeOamCache(); fDbRootPMMap = oamCache->getDBRootToPMMap(); - fDbrm = aDbrm; - fSessionID = sid; - fExeMgr = new execplan::ClientRotator(fSessionID, "ExeMgr"); - //std::cout << " fSessionID is " << fSessionID << std::endl; - fExeMgr->connect(0.005); } @@ -185,7 +172,7 @@ class DMLPackageProcessor * @brief Get debug level */ inline const DebugLevel getDebugLevel() const { return fDebugLevel; } - //int rollBackTransaction(uint64_t uniqueId, uint32_t txnID, uint32_t sessionID, std::string & errorMsg); + //int rollBackTransaction(u_int64_t uniqueId, u_int32_t txnID, u_int32_t sessionID, std::string & errorMsg); /** * @brief Set debug level */ @@ -206,7 +193,7 @@ class DMLPackageProcessor EXPORT int rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID, std::string & errorMsg); - EXPORT int rollBackBatchAutoOnTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID, const uint32_t tableOid, std::string & errorMsg); + EXPORT int rollBackBatchAutoOnTransaction(u_int64_t uniqueId, BRM::TxnID txnID, u_int32_t sessionID, const u_int32_t tableOid, std::string & errorMsg); /** * @brief convert a columns data, represnted as a string, to it's native * data type @@ -278,7 +265,7 @@ class DMLPackageProcessor * @param updateFlag 0: delete, 1: update, 2 insert * @param colNameList the updated column names, only valid for update SQL statement */ - bool updateIndexes( uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const std::string& schema, + bool updateIndexes( u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const std::string& schema, const std::string& table,const dmlpackage::RowList& rows, DMLResult& result, std::vector ridList, WriteEngine::ColValueList& colValuesList, std::vector& colNameList, const char updateFlag, @@ -302,7 +289,7 @@ class DMLPackageProcessor * @param rows the lists of rows to check column constraints on * @param result the result structure */ - bool violatesConstraints( uint32_t sessionID, const std::string& schema, const std::string& table, + bool violatesConstraints( u_int32_t sessionID, const std::string& schema, const std::string& table, const dmlpackage::RowList& rows, DMLResult& result ); /** @brief validate that the column does not violate a unique constraint @@ -354,14 +341,14 @@ class DMLPackageProcessor * @param rows the lists of rows to check column constraints on * @param result the result structure */ - bool violatesPKRefConnstraint ( uint32_t sessionID, + bool violatesPKRefConnstraint ( u_int32_t sessionID, const std::string& schema, const std::string& table, const dmlpackage::RowList& rows, const WriteEngine::ColValueList& oldValueList, DMLResult& result ); - bool violatesPKRefConnstraint ( uint32_t sessionID, + bool violatesPKRefConnstraint ( u_int32_t sessionID, const std::string& schema, const std::string& table, std::vector& rowIDList, @@ -396,7 +383,7 @@ class DMLPackageProcessor * @param rows the lists of rows to check column constraints on * @param result the result structure */ - bool violatesUpdtRefConstraints( uint32_t sessionID, + bool violatesUpdtRefConstraints( u_int32_t sessionID, const std::string& schema, const std::string& table, const dmlpackage::RowList& rows, @@ -416,13 +403,22 @@ class DMLPackageProcessor DMLResult& result ); + /** + * @brief tokenize a columns data + * + * @param type the columns database type + * @param data the columns string representation of it's data + */ + boost::any tokenizeData( execplan::CalpontSystemCatalog::SCN txnID, execplan::CalpontSystemCatalog::ColType, + const std::string& data, DMLResult& result, bool isNULL ); + /** @brief get the column list for the supplied table * * @param schema the schema name * @param table the table name * @param colList ColumnList to fill with the columns for the supplied table */ - void getColumnsForTable( uint32_t sessionID, std::string schema, std::string table, dmlpackage::ColumnList& colList ); + void getColumnsForTable( u_int32_t sessionID, std::string schema, std::string table, dmlpackage::ColumnList& colList ); /** @brief convert absolute rid to relative rid in a segement file * @@ -432,7 +428,7 @@ class DMLPackageProcessor * @param startDBRoot the dbroot this table starts * @param dbrootCnt the number of dbroot in db */ - void convertRidToColumn(uint64_t& rid, unsigned& dbRoot, unsigned& partition, + void convertRidToColumn(u_int64_t& rid, unsigned& dbRoot, unsigned& partition, unsigned& segment, unsigned filesPerColumnPartition, unsigned extentsPerSegmentFile, unsigned extentRows, unsigned startDBRoot, unsigned dbrootCnt, @@ -457,33 +453,36 @@ class DMLPackageProcessor * @param ec in:the error code received * @returns error string */ - std::string projectTableErrCodeToMsg(uint32_t ec); + std::string projectTableErrCodeToMsg(uint ec); -// bool validateNextValue(execplan::CalpontSystemCatalog::ColType colType, int64_t value, bool & offByOne); + bool validateNextValue(execplan::CalpontSystemCatalog::ColType colType, int64_t value, bool & offByOne); bool validateVarbinaryVal( std::string & inStr); - int commitTransaction(uint64_t uniqueId, BRM::TxnID txnID); - int commitBatchAutoOnTransaction(uint64_t uniqueId, BRM::TxnID txnID, const uint32_t tableOid, std::string & errorMsg); - int commitBatchAutoOffTransaction(uint64_t uniqueId, BRM::TxnID txnID, const uint32_t tableOid, std::string & errorMsg); - int rollBackBatchAutoOffTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID, const uint32_t tableOid, std::string & errorMsg); - int flushDataFiles (int rc, std::map & columnOids, uint64_t uniqueId, BRM::TxnID txnID, uint32_t tableOid); - int endTransaction (uint64_t uniqueId, BRM::TxnID txnID, bool success); - + int commitTransaction(u_int64_t uniqueId, BRM::TxnID txnID); + int commitBatchAutoOnTransaction(u_int64_t uniqueId, BRM::TxnID txnID, const u_int32_t tableOid, std::string & errorMsg); + int commitBatchAutoOffTransaction(u_int64_t uniqueId, BRM::TxnID txnID, const u_int32_t tableOid, std::string & errorMsg); + int rollBackBatchAutoOffTransaction(u_int64_t uniqueId, BRM::TxnID txnID, u_int32_t sessionID, const u_int32_t tableOid, std::string & errorMsg); + int flushDataFiles (int rc, std::map & columnOids, u_int64_t uniqueId, BRM::TxnID txnID); + + /** @brief the write engine wrapper interface + */ + WriteEngine::WriteEngineWrapper fWriteEngine; + /** @brief the Session Manager interface */ execplan::SessionManager fSessionManager; joblist::DistributedEngineComm *fEC; joblist::ResourceManager* fRM; char* strlower(char* in); - uint32_t fSessionID; + u_int32_t fSessionID; const unsigned DMLLoggingId; - uint32_t fPMCount; + uint fPMCount; WriteEngine::WEClients* fWEClient; - BRM::DBRM* fDbrm; + BRM::DBRM fDbrm; + boost::shared_ptr fExeMgr; boost::shared_ptr > fDbRootPMMap; oam::Oam fOam; bool fRollbackPending; // When set, any derived object should stop what it's doing and cleanup in preparation for a Rollback - execplan::ClientRotator* fExeMgr; private: diff --git a/dbcon/dmlpackageproc/dmlpackageprocessorfactory.cpp b/dbcon/dmlpackageproc/dmlpackageprocessorfactory.cpp index 80b76b19..91b5c26e 100644 --- a/dbcon/dmlpackageproc/dmlpackageprocessorfactory.cpp +++ b/dbcon/dmlpackageproc/dmlpackageprocessorfactory.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlpackageprocessorfactory.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmlpackageprocessorfactory.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackageproc/dmlpackageprocessorfactory.h b/dbcon/dmlpackageproc/dmlpackageprocessorfactory.h index 98a00534..91994274 100644 --- a/dbcon/dmlpackageproc/dmlpackageprocessorfactory.h +++ b/dbcon/dmlpackageproc/dmlpackageprocessorfactory.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlpackageprocessorfactory.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: dmlpackageprocessorfactory.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/dmlpackageproc/insertpackageprocessor.cpp b/dbcon/dmlpackageproc/insertpackageprocessor.cpp index 61bae74d..d39a07ca 100644 --- a/dbcon/dmlpackageproc/insertpackageprocessor.cpp +++ b/dbcon/dmlpackageproc/insertpackageprocessor.cpp @@ -16,13 +16,15 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: insertpackageprocessor.cpp 9642 2013-06-24 14:57:42Z rdempsey $ + * $Id: insertpackageprocessor.cpp 8943 2012-10-03 19:20:49Z chao $ * * ***********************************************************************/ #include +#define INSERTPKGPROC_DLLEXPORT #include "insertpackageprocessor.h" #include "autoincrementdata.h" +#undef INSERTPKGPROC_DLLEXPORT #include #include #include @@ -57,70 +59,71 @@ namespace dmlpackageprocessor DMLResult result; result.result = NO_ERROR; BRM::TxnID txnid; - // set-up the transaction - txnid.id = cpackage.get_TxnID(); - txnid.valid = true; + fSessionID = cpackage.get_SessionID(); - DMLTable *tablePtr = cpackage.get_Table(); - LoggingID logid( DMLLoggingId, fSessionID, txnid.id); logging::Message::Args args1; logging::Message msg(1); args1.add("Start SQL statement: "); - ostringstream oss; - oss << cpackage.get_SQLStatement() << "; |" << tablePtr->get_SchemaName()<<"|"; - args1.add(oss.str()); - + args1.add(cpackage.get_SQLStatement()); msg.format( args1 ); Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); //WriteEngine::ChunkManager* cm = cpackage.get_ChunkManager(); //fWriteEngine.setChunkManager(cm); - //std::map oids; + //std::map oids; VERBOSE_INFO("Processing Insert DML Package..."); - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - logging::Message::Args args; - logging::Message message(9); - args.add(ex.what()); - message.format(args); - result.result = INSERT_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - catch ( ... ) - { - logging::Message::Args args; - logging::Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = INSERT_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } + uint64_t uniqueId = fDbrm.getUnique64(); uint64_t tableLockId = 0; int rc = 0; std::string errorMsg; OamCache * oamcache = OamCache::makeOamCache(); std::vector moduleIds = oamcache->getModuleIds(); - std::vector pms; + std::vector pms; try { +#if !defined(_MSC_VER) && !defined(SKIP_OAM_INIT) + //@Bug 4495 check PM status first + for (unsigned int i=0; i systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); //cout << "DMLProc using syscatptr:sessionid = " << systemCatalogPtr <<":" << fSessionID<< endl; CalpontSystemCatalog::TableName tableName; @@ -134,19 +137,20 @@ namespace dmlpackageprocessor tableName.schema = tablePtr->get_SchemaName(); tableName.table = tablePtr->get_TableName(); roPair = systemCatalogPtr->tableRID( tableName ); - + CalpontSystemCatalog::TableInfo tableInfo = systemCatalogPtr->tableInfo(tableName); + tableLockId = tablelockData->getTablelockId(roPair.objnum); //check whether this table is locked already for this session if (tableLockId == 0) { //cout << "tablelock is not found in cache, getting from dbrm" << endl; - uint32_t processID = ::getpid(); + u_int32_t processID = ::getpid(); int32_t txnId = txnid.id; int32_t sessionId = fSessionID; std::string processName("DMLProc"); int i = 0; try { - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { @@ -183,7 +187,7 @@ namespace dmlpackageprocessor txnId = txnid.id; sessionId = fSessionID; processName = "DMLProc"; - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { @@ -204,33 +208,27 @@ namespace dmlpackageprocessor } } } - //cout << " tablelock is obtained with id " << tableLockId << endl; tablelockData->setTablelock(roPair.objnum, tableLockId); - int pmNum = 0; - - // Select PM to receive the row. - // 1. Get BRM information - // 2. Find the DBRoot with the fewest in-service blocks. - // DBRoots having no blocks are excluded - // 3. Map the selected DBRoot to the corresponding PM + int pmNum = 1; + //find the shortest dbroot to send the row CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(tableName, true); std::vector allInfo (pms.size()); for (unsigned i = 0; i < pms.size(); i++) { - rc = fDbrm->getDbRootHWMInfo((ridList[0].objnum), pms[i], allInfo[i]); - if ( rc !=0 ) //@Bug 4760. - { - result.result = INSERT_ERROR; - ostringstream oss; - oss << "Error getting extent information for table " << tableName.table; - throw std::runtime_error(oss.str()); - } + rc = fDbrm.getDbRootHWMInfo((ridList[0].objnum), pms[i], allInfo[i]); + if ( rc != 0) + break; + } + + if ( rc !=0 ) //@Bug 4760. + { + result.result = INSERT_ERROR; + ostringstream oss; + oss << "There is no extent information for table " << tableName.table; + throw std::runtime_error(oss.str()); } - - // Find DBRoot with fewest blocks; if all DBRoots - // have 0 blocks, then we select the first DBRoot BRM::EmDbRootHWMInfo tmp; bool tmpSet = false; for (unsigned i=0; i < allInfo.size(); i++) @@ -239,62 +237,50 @@ namespace dmlpackageprocessor for (unsigned j=0; j < emDbRootHWMInfos.size(); j++) { + if (emDbRootHWMInfos[j].totalBlocks == 0) + continue; + if (!tmpSet) { tmp = emDbRootHWMInfos[j]; tmpSet = true; + continue; } - else if (emDbRootHWMInfos[j].totalBlocks > 0) + if ( tmp > emDbRootHWMInfos[j] ) { - if ((emDbRootHWMInfos[j].totalBlocks < tmp.totalBlocks) || - (tmp.totalBlocks == 0)) - { - tmp = emDbRootHWMInfos[j]; - } + tmp = emDbRootHWMInfos[j]; } } } - - // Select the PM to receive the row - uint32_t dbroot; - if (tmpSet) - { - dbroot = tmp.dbRoot; - boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); - pmNum = (*dbRootPMMap)[dbroot]; - //@Bug 4760. validate pm value - if (pmNum == 0) - { - result.result = INSERT_ERROR; - ostringstream oss; - oss << "Error mapping extent/DBRoot to PM for table " << tableName.table; - throw std::runtime_error(oss.str()); - } - } - else + uint32_t dbroot = tmp.dbRoot; + boost::shared_ptr > dbRootPMMap = oamcache->getDBRootToPMMap(); + pmNum = (*dbRootPMMap)[dbroot]; + + //@Bug 4760. validate pm value + if (pmNum == 0) { result.result = INSERT_ERROR; ostringstream oss; oss << "There is no extent information for table " << tableName.table; throw std::runtime_error(oss.str()); } - //This is for single insert only. Batch insert is handled in dmlprocessor. + //get a unique number //cout << "fWEClient = " << fWEClient << endl; fWEClient->addQueue(uniqueId); ByteStream bytestream; - bytestream << (uint8_t)WE_SVR_SINGLE_INSERT; + bytestream << (ByteStream::byte)WE_SVR_SINGLE_INSERT; bytestream << uniqueId; - bytestream << (uint32_t)txnid.id; - bytestream << dbroot; + bytestream << (ByteStream::quadbyte) txnid.id; + bytestream << (ByteStream::quadbyte)dbroot; cpackage.write(bytestream); boost::shared_ptr bsIn; ByteStream::byte rc1; try { - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); #ifdef IDB_DML_DEBUG cout << "Single insert sending WE_SVR_SINGLE_INSERT to pm " << pmNum << endl; #endif @@ -331,6 +317,7 @@ cout << "Single insert got exception" << ex.what() << endl; cout << "Single insert got unknown exception" << endl; #endif } + // Log the insert statement. LoggingID logid( DMLLoggingId, fSessionID, txnid.id); logging::Message::Args args1; @@ -375,7 +362,6 @@ cout << "Single insert got unknown exception" << endl; result.result = INSERT_ERROR; result.message = message; } - if (( rc !=0) && (rc != IDBRANGE_WARNING)) { logging::Message::Args args; @@ -388,23 +374,428 @@ cout << "Single insert got unknown exception" << endl; result.result = INSERT_ERROR; result.message = message; } - else if (rc == IDBRANGE_WARNING) - { - logging::Message::Args args; - logging::Message message(1); - args.add(errorMsg); - args.add(""); - args.add(""); - message.format(args); - result.result = IDBRANGE_WARNING; - result.message = message; - } - fWEClient->removeQueue(uniqueId); VERBOSE_INFO("Finished Processing Insert DML Package"); return result; } + bool InsertPackageProcessor::insertRows(u_int32_t sessionID, + CalpontSystemCatalog::SCN txnID, + const std::string & schema, + const std::string & table, + const dmlpackage::RowList & rows, + DMLResult & result, long long & nextVal, long long & originalNextVal, CalpontSystemCatalog::ColType & autoColType, + bool insertSelect) + { + SUMMARY_INFO("InsertPackageProcessor::insertRows"); + + bool retval = true; + WriteEngine::ColStructList colStructs; + WriteEngine::DctnryStructList dctnryStructList; + WriteEngine::DctnryValueList dctnryValueList; + WriteEngine::ColValueList colValuesList; + WriteEngine::DictStrList dicStringList ; + CalpontSystemCatalog::TableName tableName; + CalpontSystemCatalog::TableColName tableColName; + tableName.table = tableColName.table = table; + tableName.schema = tableColName.schema = schema; + + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + + AutoincrementData *autoincrementData = AutoincrementData::makeAutoincrementData(fSessionID); + + VERBOSE_INFO("Inserting Row(s)..."); + + if (rows.size()) + { + Row *rowPtr = rows.at(0); + ColumnList columns = rowPtr->get_ColumnList(); + ColumnList::const_iterator column_iterator = columns.begin(); + while (column_iterator != columns.end() && true == retval) + { + DMLColumn *columnPtr = *column_iterator; + tableColName.column = columnPtr->get_Name(); + CalpontSystemCatalog::ROPair roPair = systemCatalogPtr->columnRID(tableColName); + + CalpontSystemCatalog::OID oid = systemCatalogPtr->lookupOID(tableColName); + + CalpontSystemCatalog::ColType colType; + colType = systemCatalogPtr->colType(oid); + if (colType.autoincrement) + { + nextVal = autoincrementData->getNextValue(oid); + if (nextVal <= 0) + { + //get from systables + nextVal= systemCatalogPtr->nextAutoIncrValue(tableName); + } + originalNextVal = nextVal; + } + + WriteEngine::ColStruct colStruct; + WriteEngine::DctnryStruct dctnryStruct; + colStruct.dataOid = roPair.objnum; + colStruct.tokenFlag = false; + colStruct.fCompressionType = colType.compressionType; + // Token + if ( isDictCol(colType) ) + { + colStruct.colWidth = 8; + colStruct.tokenFlag = true; + } + else + { + colStruct.colWidth = colType.colWidth; + } + colStruct.colDataType = (WriteEngine::ColDataType) colType.colDataType; + + if (colStruct.tokenFlag) + { + dctnryStruct.dctnryOid = colType.ddn.dictOID; + dctnryStruct.columnOid = colStruct.dataOid; + dctnryStruct.fCompressionType = colType.compressionType; + dctnryStruct.colWidth = colType.colWidth; + } + else + { + dctnryStruct.dctnryOid = 0; + dctnryStruct.columnOid = colStruct.dataOid; + dctnryStruct.fCompressionType = colType.compressionType; + dctnryStruct.colWidth = colType.colWidth; + } + + colStructs.push_back(colStruct); + dctnryStructList.push_back(dctnryStruct); + + ++column_iterator; + } + + unsigned int numcols = rowPtr->get_NumberOfColumns(); + std::string tmpStr(""); + for (unsigned int i = 0; i < numcols; i++) + { + + WriteEngine::ColTupleList colTuples; + WriteEngine::DctColTupleList dctColTuples; + RowList::const_iterator row_iterator = rows.begin(); + while (row_iterator != rows.end()) + { + Row *rowPtr = *row_iterator; + const DMLColumn *columnPtr = rowPtr->get_ColumnAt(i); + VERBOSE_INFO("Looking up OID for:"); + VERBOSE_INFO(columnPtr->get_Name().c_str()); + + tableColName.column = columnPtr->get_Name(); + CalpontSystemCatalog::OID oid = systemCatalogPtr->lookupOID(tableColName); + + CalpontSystemCatalog::ColType colType; + colType = systemCatalogPtr->colType(oid); + + boost::any datavalue; + bool isNULL = false; + bool pushWarning = false; + std::vector origVals; + origVals = columnPtr->get_DataVector(); + WriteEngine::dictStr dicStrings; + // token + if ( isDictCol(colType) ) + { + for ( uint32_t i=0; i < origVals.size(); i++ ) + { + tmpStr = origVals[i]; + if ( tmpStr.length() == 0 ) + isNULL = true; + else + isNULL = false; + +/* if ( isNULL && (colType.constraintType == NOTNULL_CONSTRAINT)) + { + retval = false; + result.result = INSERT_ERROR; + Message::Args args; + args.add(tableColName.column); + result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_VIOLATE_NOT_NULL, args)); + return retval; + } +*/ + if ( tmpStr.length() > (unsigned int)colType.colWidth ) + { + tmpStr = tmpStr.substr(0, colType.colWidth); + if ( !pushWarning ) + pushWarning = true; + } + WriteEngine::ColTuple colTuple; + colTuple.data = datavalue; + + colTuples.push_back(colTuple); + //@Bug 2515. Only pass string values to write engine + dicStrings.push_back( tmpStr ); + } + colValuesList.push_back(colTuples); + //@Bug 2515. Only pass string values to write engine + dicStringList.push_back( dicStrings ); + } + else + { + string x; + std::string indata; + for ( uint32_t i=0; i < origVals.size(); i++ ) + { + indata = origVals[i]; + if ( indata.length() == 0 ) + isNULL = true; + else + isNULL = false; + + //Error outon null value if the column has not null constraint. +/* if ( isNULL && (colType.constraintType == NOTNULL_CONSTRAINT)) + { + retval = false; + result.result = INSERT_ERROR; + Message::Args args; + args.add(tableColName.column); + result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_VIOLATE_NOT_NULL, args)); + return retval; + } +*/ + //check if autoincrement column and value is 0 or null + if (colType.autoincrement && ( isNULL || (indata.compare("0")==0))) + { + if (nextVal <= 0) + throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_EXCEED_LIMIT)); + + ostringstream oss; + oss << nextVal++; + indata = oss.str(); + isNULL = false; + autoColType = colType; + } + try + { + datavalue = DataConvert::convertColumnData(colType, indata, pushWarning, isNULL); + } + catch(exception & ex) + { + cerr << "InsertPackageProcessor::processPackage: " << ex.what() << endl; + //cout << "The value is " << indata << " and coltype is " << colType.colDataType<< endl; + logging::Message::Args args; + logging::Message message(1); + args.add("Insert Failed:"); + args.add(ex.what()); + args.add(""); + args.add(""); + message.format(args); + x = ex.what(); + result.result = INSERT_ERROR; + result.message = message; + } + //@Bug 1806 + if (result.result != NO_ERROR && result.result != IDBRANGE_WARNING) + { + //throw std::runtime_error("Invalid data"); + throw std::runtime_error(x); + } + if ( pushWarning && ( result.result != IDBRANGE_WARNING ) ) + result.result = IDBRANGE_WARNING; + + WriteEngine::ColTuple colTuple; + colTuple.data = datavalue; + + colTuples.push_back(colTuple); + //@Bug 2515. Only pass string values to write engine + dicStrings.push_back( tmpStr ); + } + colValuesList.push_back(colTuples); + dicStringList.push_back( dicStrings ); + } + ++row_iterator; + } + } + } + + VERBOSE_INFO("Invoking writeEngine.insertColumnRec"); + // call the write engine to write all the rows + int error = NO_ERROR; + //fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3); + if (colValuesList[0].size() > 0) + { + if (NO_ERROR != + (error = fWriteEngine.insertColumnRec_Single(txnID, colStructs, colValuesList, dctnryStructList, dicStringList))) + { + retval = false; + // build the logging message + logging::Message::Args args; + logging::Message message(1); + args.add("Insert failed on the "); + args.add(tableName.table); + args.add("table. It was due to: "); + WErrorCodes ec; + args.add(ec.errorString(error)); + message.format(args); + if (error == ERR_BRM_DEAD_LOCK) + { + result.result = DEAD_LOCK_ERROR; + result.message = message; + } + else if ( error == ERR_BRM_VB_OVERFLOW ) + { + result.result = VB_OVERFLOW_ERROR; + result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_VERSIONBUFFER_OVERFLOW)); + } + else + { + result.result = INSERT_ERROR; + result.message = message; + } + } + } + + return retval; + } + + bool InsertPackageProcessor::fixupColumns(u_int32_t sessionID, + const std::string & schema, + const std::string & table, + const dmlpackage::RowList & rows, DMLResult & result) + { + + SUMMARY_INFO("InsertPackageProcessor::fixupColumns"); + + VERBOSE_INFO("Add missing columns to row(s)..."); + bool retval = true; + if (rows.size()) + { + ColumnList addedColumns; + + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + systemCatalogPtr->identity(CalpontSystemCatalog::EC); + systemCatalogPtr->sessionID(fSessionID); + + Row *rowPtr = rows.at(0); + + CalpontSystemCatalog::TableName tableName; + tableName.schema = schema; + tableName.table = table; + + // get the column count from the row and the system catalog + // if they match we are done + unsigned int colcount = rowPtr->get_NumberOfColumns(); + //@Bug 1341. Added useCache flag to take advantage of cache. + CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(tableName, true); + typedef std::vector < CalpontSystemCatalog::OID > objnumList; + objnumList oidList; + //@bug 1396 Sort oidlist according to column position + CalpontSystemCatalog::ColType colType; + oidList.resize(ridList.size()); + for (unsigned int i = 0; i < ridList.size(); i++) + { + colType = systemCatalogPtr->colType(ridList[i].objnum); + oidList[colType.colPosition] = ridList[i].objnum; + } + //@Bug 1274 oid can be reused and will not be inorder + //@Bug 1304. systables are hard coded. + // if ( oidList[0] < 3000 ) + // sort(oidList.begin(), oidList.end()); + if (ridList.size() > colcount) + { + // else we need to add null columns values to complete the row + // for each column in the system catalog + RowList::const_iterator row_iterator = rows.begin(); + while (row_iterator != rows.end()) + { + Row *rowPtr = *row_iterator; + ColumnList columns = rowPtr->get_ColumnList(); + + objnumList::const_iterator rid_iterator = oidList.begin(); + while (rid_iterator != oidList.end()) + { + //CalpontSystemCatalog::OID obj = *rid_iterator; + CalpontSystemCatalog::OID oid = *rid_iterator; + + CalpontSystemCatalog::ColType colType; + colType = systemCatalogPtr->colType(oid); + + CalpontSystemCatalog::TableColName tableColName; + tableColName = systemCatalogPtr->colName(oid); + + ColumnList::const_iterator column_iterator = columns.begin(); + bool found = false; + + while (column_iterator != columns.end()) + { + DMLColumn *columnPtr = *column_iterator; + std::string columnName = columnPtr->get_Name(); + boost::algorithm::to_lower(columnName); + if (tableColName.column == columnName) + { + VERBOSE_INFO("Found column:"); + VERBOSE_INFO(tableColName.column.c_str()); + + found = true; + break; + } + ++column_iterator; + } + // if not add it + if (!found) + { + VERBOSE_INFO("Column not found in row:"); + VERBOSE_INFO(tableColName.column.c_str()); + VERBOSE_INFO("Adding column:"); + VERBOSE_INFO(tableColName.column.c_str()); + bool isNULL = true; + rowPtr->get_ColumnList().push_back(new DMLColumn(tableColName.column, "NULL", isNULL)); + } + + ++rid_iterator; + + } + + ++row_iterator; + } + } + else if ((ridList.size() == colcount) && ((rowPtr->get_ColumnList()[0]->get_Name()) == "")) + { + VERBOSE_INFO("No column name in row:"); + //std::string value; + RowList::const_iterator row_iterator = rows.begin(); + while (row_iterator != rows.end()) + { + Row *rowPtr = *row_iterator; + ColumnList columns = rowPtr->get_ColumnList(); + + objnumList::const_iterator rid_iterator = oidList.begin(); + unsigned int j = 0; + while (rid_iterator != oidList.end()) + { + CalpontSystemCatalog::OID obj = *rid_iterator; + CalpontSystemCatalog::OID oid = obj; + + CalpontSystemCatalog::ColType colType; + colType = systemCatalogPtr->colType(oid); + + CalpontSystemCatalog::TableColName tableColName; + tableColName = systemCatalogPtr->colName(oid); + + ColumnList::const_iterator column_iterator = columns.begin(); + //DMLColumn* columnPtr = *column_iterator; + VERBOSE_INFO("Adding column:"); + VERBOSE_INFO(tableColName.column.c_str()); + //value = columnPtr->get_Data(); + rowPtr->get_ColumnList()[j]->set_Name(tableColName.column); + ++rid_iterator; + j++; + } + + ++row_iterator; + } + + } + } + return retval; + } + } // namespace dmlpackageprocessor // vim:ts=4 sw=4: diff --git a/dbcon/dmlpackageproc/insertpackageprocessor.h b/dbcon/dmlpackageproc/insertpackageprocessor.h index 0c83d6d7..d33097bd 100644 --- a/dbcon/dmlpackageproc/insertpackageprocessor.h +++ b/dbcon/dmlpackageproc/insertpackageprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: insertpackageprocessor.h 9473 2013-05-02 15:15:44Z dcathey $ +* $Id: insertpackageprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -32,7 +32,7 @@ #include "dataconvert.h" #include "we_chunkmanager.h" -#if defined(_MSC_VER) && defined(DMLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(INSERTPKGPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -48,8 +48,6 @@ class InsertPackageProcessor : public DMLPackageProcessor { public: - InsertPackageProcessor(BRM::DBRM* aDbrm, uint32_t sid) : DMLPackageProcessor(aDbrm, sid) { - } /** @brief process an InsertDMLPackage * * @param cpackage the InsertDMLPackage to process @@ -59,6 +57,32 @@ class InsertPackageProcessor : public DMLPackageProcessor protected: private: + /** @brief insert one or more rows + * + * @param txnID the transaction ID + * @param schema the schema name + * @param table the table name + * @param rows the list of rows + * @param ridList upon return contains the list of inserted Row id(s) + * @param colValuesList upon return contains the updated values + * @param result the result of the operation + */ + bool insertRows( u_int32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const std::string& schema, const std::string& table, + const dmlpackage::RowList& rows, DMLResult& result, long long & nextVal, long long & originalNextVal, execplan::CalpontSystemCatalog::ColType & autoColType, + bool insertSelect = false ); + + + + /** @brief add any columns that were not supplied in the insert statement + * + * @param schema the schema name + * @param table the table name + * @param rows the lists of rows add any missing columns + * @param result the result of the operation + */ + bool fixupColumns( u_int32_t sessionID, const std::string& schema, const std::string& table, + const dmlpackage::RowList& rows, DMLResult& result ); + //u_int32_t fSessionID; }; diff --git a/dbcon/dmlpackageproc/libdmlpackageproc.rc b/dbcon/dmlpackageproc/libdmlpackageproc.rc deleted file mode 100644 index c8bbca74..00000000 --- a/dbcon/dmlpackageproc/libdmlpackageproc.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB DML API" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "libdmlpackageproc" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "libdmlpackageproc.dll" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/dbcon/dmlpackageproc/libdmlpackageproc.vcxproj b/dbcon/dmlpackageproc/libdmlpackageproc.vcxproj deleted file mode 100644 index 8b73de2a..00000000 --- a/dbcon/dmlpackageproc/libdmlpackageproc.vcxproj +++ /dev/null @@ -1,361 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {C78DD512-FCA0-4B8A-A531-376E33C9FBB7} - libdmlpackageproc - - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DMLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DMLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DMLPKGPROC_DLLEXPORT;SKIP_IDB_COMPRESSION;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DMLPKGPROC_DLLEXPORT;SKIP_IDB_COMPRESSION;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DML API" $(SolutionDir)..\..x64\Release\libdmlpackageproc.dll - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DMLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - DMLPKGPROC_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DML API" $(SolutionDir)..\..\x64\EnterpriseRelease\libdmlpackageproc.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {0bbaeacb-3336-4406-acfb-255669a3b9cf} - - - {3238cd73-8ffd-44a7-aa5f-815beef8f402} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {4bc37219-e09d-4133-98c4-cf0386657df6} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - {b9045bca-0955-4c5e-bca4-5ee516838119} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - - - - \ No newline at end of file diff --git a/dbcon/dmlpackageproc/libdmlpackageproc.vcxproj.filters b/dbcon/dmlpackageproc/libdmlpackageproc.vcxproj.filters deleted file mode 100644 index fd2b4997..00000000 --- a/dbcon/dmlpackageproc/libdmlpackageproc.vcxproj.filters +++ /dev/null @@ -1,71 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/dbcon/dmlpackageproc/resource.h b/dbcon/dmlpackageproc/resource.h deleted file mode 100644 index 43a95058..00000000 --- a/dbcon/dmlpackageproc/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by libdmlpackageproc.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/dbcon/dmlpackageproc/tablelockdata.cpp b/dbcon/dmlpackageproc/tablelockdata.cpp index 5d00bfe3..71105134 100644 --- a/dbcon/dmlpackageproc/tablelockdata.cpp +++ b/dbcon/dmlpackageproc/tablelockdata.cpp @@ -1,102 +1,99 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: tablelockdata.h 525 2010-01-19 23:18:05Z xlou $ -// -/** @file */ - -#include -#include -using namespace std; - -#include -#include -#include -using namespace boost; - -#include "tablelockdata.h" - -namespace dmlpackageprocessor -{ - -/*static*/ -boost::mutex TablelockData::map_mutex; -/*static*/ -TablelockData::TablelockDataMap TablelockData::fTablelockDataMap; -/* static */ -TablelockData* TablelockData::makeTablelockData(uint32_t sessionID) -{ - boost::mutex::scoped_lock lock(map_mutex); - TablelockData* instance; - TablelockDataMap::const_iterator it = fTablelockDataMap.find(sessionID); - - if (it == fTablelockDataMap.end()) - { - instance = new TablelockData(); - fTablelockDataMap[sessionID] = instance; - return instance; - } - - return it->second; -} - -/* static */ -void TablelockData::removeTablelockData(uint32_t sessionID) -{ - boost::mutex::scoped_lock lock(map_mutex); - TablelockDataMap::iterator it = fTablelockDataMap.find(sessionID); - if (it != fTablelockDataMap.end()) - { - delete (*it).second; - fTablelockDataMap.erase(it); - } -} - -TablelockData::TablelockData() -{ -} -TablelockData::~TablelockData() -{ -} - -void TablelockData::setTablelock(uint32_t tableOid, uint64_t tablelockId) -{ - boost::mutex::scoped_lock lk(fOIDTablelock); - fOIDTablelockMap[tableOid] = tablelockId; -} - -uint64_t TablelockData::getTablelockId(uint32_t tableOid) -{ - boost::mutex::scoped_lock lk(fOIDTablelock); - uint64_t tablelockId = 0; - OIDTablelock::iterator it = fOIDTablelockMap.find(tableOid); - if (it != fOIDTablelockMap.end()) - { - tablelockId = it->second; - } - return tablelockId; -} - -TablelockData::OIDTablelock & TablelockData::getOidTablelockMap() -{ - boost::mutex::scoped_lock lk(fOIDTablelock); - - return fOIDTablelockMap; -} - -} -// vim:ts=4 sw=4: +/* + Copyright (C) 2009-2012 Calpont Corporation. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// $Id: tablelockdata.h 525 2010-01-19 23:18:05Z xlou $ +// +/** @file */ + +#include +#include +using namespace std; + +#include +#include +#include +using namespace boost; + +#define DMLTBLLCKDAT_DLLEXPORT +#include "tablelockdata.h" +#undef DMLTBLLCKDAT_DLLEXPORT + +/*static*/ +boost::mutex TablelockData::map_mutex; +/*static*/ +TablelockData::TablelockDataMap TablelockData::fTablelockDataMap; +/* static */ +TablelockData* TablelockData::makeTablelockData(uint32_t sessionID) +{ + boost::mutex::scoped_lock lock(map_mutex); + TablelockData* instance; + TablelockDataMap::const_iterator it = fTablelockDataMap.find(sessionID); + + if (it == fTablelockDataMap.end()) + { + instance = new TablelockData(); + fTablelockDataMap[sessionID] = instance; + return instance; + } + + return it->second; +} + +/* static */ +void TablelockData::removeTablelockData(u_int32_t sessionID) +{ + boost::mutex::scoped_lock lock(map_mutex); + TablelockDataMap::iterator it = fTablelockDataMap.find(sessionID); + if (it != fTablelockDataMap.end()) + { + delete (*it).second; + fTablelockDataMap.erase(it); + } +} + +TablelockData::TablelockData() +{ +} +TablelockData::~TablelockData() +{ +} + +void TablelockData::setTablelock(uint32_t tableOid, uint64_t tablelockId) +{ + boost::mutex::scoped_lock lk(fOIDTablelock); + fOIDTablelockMap[tableOid] = tablelockId; +} + +uint64_t TablelockData::getTablelockId(uint32_t tableOid) +{ + boost::mutex::scoped_lock lk(fOIDTablelock); + uint64_t tablelockId = 0; + OIDTablelock::iterator it = fOIDTablelockMap.find(tableOid); + if (it != fOIDTablelockMap.end()) + { + tablelockId = it->second; + } + return tablelockId; +} + +TablelockData::OIDTablelock & TablelockData::getOidTablelockMap() +{ + boost::mutex::scoped_lock lk(fOIDTablelock); + + return fOIDTablelockMap; +} +// vim:ts=4 sw=4: diff --git a/dbcon/dmlpackageproc/tablelockdata.h b/dbcon/dmlpackageproc/tablelockdata.h index d4c43e40..42cfd4a2 100644 --- a/dbcon/dmlpackageproc/tablelockdata.h +++ b/dbcon/dmlpackageproc/tablelockdata.h @@ -1,68 +1,62 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id$ - -/** @file */ - -#ifndef TABLELOCKDATA_H__ -#define TABLELOCKDATA_H__ - -#include - -#include -#include - -#if defined(_MSC_VER) && defined(DMLPKGPROC_DLLEXPORT) +/* + Copyright (C) 2009-2012 Calpont Corporation. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// $Id: activestatementcounter.h 525 2010-01-19 23:18:05Z xlou $ +// +/** @file */ + +#ifndef TABLELOCKDATA_H__ +#define TABLELOCKDATA_H__ + +#include + +#include +#include + +#if defined(_MSC_VER) && defined(DMLTBLLCKDAT_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT #endif - -namespace dmlpackageprocessor -{ - -class TablelockData -{ -public: - typedef std::map TablelockDataMap; - typedef std::map OIDTablelock; - EXPORT static TablelockData* makeTablelockData(uint32_t sessionID = 0); - EXPORT static void removeTablelockData(uint32_t sessionID = 0); - EXPORT void setTablelock(uint32_t tableOid, uint64_t tablelockId); - EXPORT uint64_t getTablelockId(uint32_t tableOid); - OIDTablelock & getOidTablelockMap(); - -private: - /** Constuctors */ - explicit TablelockData(); - explicit TablelockData(const TablelockData& rhs); - ~TablelockData(); - - static boost::mutex map_mutex; - static TablelockDataMap fTablelockDataMap; - OIDTablelock fOIDTablelockMap; - boost::mutex fOIDTablelock; -}; - -} - -#undef EXPORT - -#endif -// vim:ts=4 sw=4: - + +class TablelockData +{ +public: + typedef std::map TablelockDataMap; + typedef std::map OIDTablelock; + EXPORT static TablelockData* makeTablelockData(uint32_t sessionID = 0); + EXPORT static void removeTablelockData(uint32_t sessionID = 0); + EXPORT void setTablelock(uint32_t tableOid, uint64_t tablelockId); + EXPORT uint64_t getTablelockId(uint32_t tableOid); + OIDTablelock & getOidTablelockMap(); + +private: + /** Constuctors */ + explicit TablelockData(); + explicit TablelockData(const TablelockData& rhs); + ~TablelockData(); + + static boost::mutex map_mutex; + static TablelockDataMap fTablelockDataMap; + OIDTablelock fOIDTablelockMap; + boost::mutex fOIDTablelock; +}; + +#undef EXPORT + +#endif +// vim:ts=4 sw=4: diff --git a/dbcon/dmlpackageproc/updatepackageprocessor.cpp b/dbcon/dmlpackageproc/updatepackageprocessor.cpp index d5e5ebf2..f48d05ef 100644 --- a/dbcon/dmlpackageproc/updatepackageprocessor.cpp +++ b/dbcon/dmlpackageproc/updatepackageprocessor.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: updatepackageprocessor.cpp 9673 2013-07-09 15:59:49Z chao $ +// $Id: updatepackageprocessor.cpp 9138 2012-12-11 20:13:47Z chao $ #include #include @@ -26,7 +26,9 @@ #include #include using namespace std; +#define UPDATEPKGPROC_DLLEXPORT #include "updatepackageprocessor.h" +#undef UPDATEPKGPROC_DLLEXPORT #include "writeengine.h" #include "joblistfactory.h" #include "messagelog.h" @@ -59,7 +61,7 @@ using namespace oam; //#define PROFILE 1 namespace dmlpackageprocessor { - +std::map pmState; //StopWatch timer; DMLPackageProcessor::DMLResult @@ -72,40 +74,10 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) result.result = NO_ERROR; result.rowCount = 0; BRM::TxnID txnid; - // set-up the transaction - txnid.id = cpackage.get_TxnID(); - txnid.valid = true; fSessionID = cpackage.get_SessionID(); VERBOSE_INFO("Processing Update DML Package..."); TablelockData * tablelockData = TablelockData::makeTablelockData(fSessionID); - uint64_t uniqueId = 0; - //Bug 5070. Added exception handling - try { - uniqueId = fDbrm->getUnique64(); - } - catch (std::exception& ex) - { - logging::Message::Args args; - logging::Message message(9); - args.add(ex.what()); - message.format(args); - result.result = UPDATE_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - catch ( ... ) - { - logging::Message::Args args; - logging::Message message(9); - args.add("Unknown error occured while getting unique number."); - message.format(args); - result.result = UPDATE_ERROR; - result.message = message; - fSessionManager.rolledback(txnid); - return result; - } - + uint64_t uniqueId = fDbrm.getUnique64(); uint64_t tableLockId = 0; boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); CalpontSystemCatalog::TableName tableName; @@ -114,19 +86,19 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) tableName.schema = tablePtr->get_SchemaName(); tableName.table = tablePtr->get_TableName(); fWEClient->addQueue(uniqueId); - execplan::CalpontSystemCatalog::ROPair roPair; //#ifdef PROFILE // StopWatch timer; //#endif try { + // set-up the transaction + txnid.id = cpackage.get_TxnID(); + txnid.valid = true; LoggingID logid( DMLLoggingId, fSessionID, txnid.id); logging::Message::Args args1; logging::Message msg(1); args1.add("Start SQL statement: "); - ostringstream oss; - oss << cpackage.get_SQLStatement() << "|" << tablePtr->get_SchemaName()<<"|"; - args1.add(oss.str()); + args1.add(cpackage.get_SQLStatement()); msg.format( args1 ); logging::Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); @@ -143,27 +115,29 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) fWEClient->removeQueue(uniqueId); return result; } + + execplan::CalpontSystemCatalog::ROPair roPair; roPair = systemCatalogPtr->tableRID(tableName); tableLockId = tablelockData->getTablelockId(roPair.objnum); //check whether this table is locked already for this session if (tableLockId == 0) { //cout << "tablelock is not found in cache, getting from dbrm" << endl; - uint32_t processID = ::getpid(); + u_int32_t processID = ::getpid(); int32_t txnId = txnid.id; int32_t sessionId = fSessionID; std::string processName("DMLProc"); int i = 0; OamCache * oamcache = OamCache::makeOamCache(); std::vector pmList = oamcache->getModuleIds(); - std::vector pms; + std::vector pms; for (unsigned i=0; i < pmList.size(); i++) { - pms.push_back((uint32_t)pmList[i]); + pms.push_back((uint)pmList[i]); } try { - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { @@ -200,7 +174,7 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) txnId = txnid.id; sessionId = fSessionID; processName = "DMLProc"; - tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + tableLockId = fDbrm.getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { @@ -239,17 +213,9 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) colType = systemCatalogPtr->colType(roPair.objnum); if (colType.autoincrement) { - try - { - uint64_t nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); - fDbrm->startAISequence(roPair.objnum, nextVal, colType.colWidth, colType.colDataType); - break; //Only one autoincrement column per table - } - catch (std::exception& ex) - { - result.result = UPDATE_ERROR; - throw std::runtime_error(ex.what()); - } + uint64_t nextVal = systemCatalogPtr->nextAutoIncrValue(tableName); + fDbrm.startAISequence(roPair.objnum, nextVal, colType.colWidth); + break; //Only one autoincrement column per table } ++rid_iterator; } @@ -257,7 +223,7 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) uint64_t rowsProcessed = 0; if (!fRollbackPending) { - rowsProcessed = fixUpRows(cpackage, result, uniqueId, roPair.objnum); + rowsProcessed = fixUpRows(cpackage, result, uniqueId); } //@Bug 4994 Cancelled job is not error @@ -323,57 +289,29 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) // timer.finish(); //@Bug 1886,2870 Flush VM cache only once per statement. send to all PMs. //WriteEngineWrapper writeEngine; - std::map oids; - int rc = 0; + std::map oids; if (result.result == NO_ERROR || result.result == IDBRANGE_WARNING) { - if ((rc = flushDataFiles(NO_ERROR, oids, uniqueId, txnid, roPair.objnum)) != NO_ERROR) + if (flushDataFiles(NO_ERROR, oids, uniqueId, txnid) != NO_ERROR) { - cerr << "UpdatePackageProcessor::processPackage: write data to disk failed" << endl; - if (!fRollbackPending) - { - logging::Message::Args args; - logging::Message message(7); - args.add("Update Failed: "); - args.add("error when writing data to disk"); - args.add(""); - args.add(""); - message.format(args); + cerr << "UpdatePackageProcessor::processPackage: write data to disk failed" << endl; + logging::Message::Args args; + logging::Message message(7); + args.add("Update Failed: "); + args.add("error when writing data to disk"); + args.add(""); + args.add(""); + message.format(args); - result.result = UPDATE_ERROR; - result.message = message; - result.rowCount = 0; - } - rc = endTransaction(uniqueId, txnid, false); + result.result = UPDATE_ERROR; + result.message = message; + result.rowCount = 0; } - else - { - if (fRollbackPending) - rc = endTransaction(uniqueId, txnid, false); - else - rc = endTransaction(uniqueId, txnid, true); - if (( rc != NO_ERROR) && (!fRollbackPending)) - { - logging::Message::Args args; - logging::Message message(7); - args.add("Update Failed: "); - args.add("error when cleaning up data files"); - args.add(""); - args.add(""); - message.format(args); - - result.result = UPDATE_ERROR; - result.message = message; - result.rowCount = 0; - - } - } } else { - //@Bug 4563. Always flush. error is already set - rc = flushDataFiles(result.result, oids, uniqueId, txnid, roPair.objnum); - rc = endTransaction(uniqueId, txnid, false); + //@Bug 4563. Always flush. + flushDataFiles(NO_ERROR, oids, uniqueId, txnid); } //timer.finish(); @@ -395,28 +333,57 @@ UpdatePackageProcessor::processPackage(dmlpackage::CalpontDMLPackage& cpackage) return result; } -uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, - const uint64_t uniqueId, const uint32_t tableOid) +uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId) { ByteStream msg, msgBk, emsgBs; - RGData rgData; - uint32_t qb = 4; + ByteStream::quadbyte qb = 4; msg << qb; boost::scoped_ptr rowGroup; - uint64_t rowsProcessed = 0; - uint32_t dbroot = 1; + uint64_t rowsProcessed = 0; + uint dbroot = 1; bool metaData = false; oam::OamCache * oamCache = oam::OamCache::makeOamCache(); std::vector fPMs = oamCache->getModuleIds(); - std::map pmState; - //boost::scoped_ptr fExeMgr; - //fExeMgr.reset( new messageqcpp::MessageQueueClient("ExeMgr1")); + try { +#if !defined(_MSC_VER) && !defined(SKIP_OAM_INIT) + //@Bug 4495 check PM status first + std::vector tmpPMs; + for (unsigned i=0; iwrite(msg); fExeMgr->write(*(cpackage.get_ExecutionPlan())); @@ -426,7 +393,7 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka msg = fExeMgr->read(); //error handling emsgBs = fExeMgr->read(); string emsg; - uint32_t qb; + ByteStream::quadbyte qb; if (emsgBs.length() == 0) { @@ -499,7 +466,7 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka metaData = true; //cout << "sending meta data" << endl; //timer.start("Meta"); - err = processRowgroup(msgBk, result, uniqueId, cpackage, pmState, metaData, dbroot); + err = processRowgroup(msgBk, result, uniqueId, cpackage, metaData, dbroot); rowGroup.reset(new rowgroup::RowGroup()); rowGroup->deserialize(msg); qb = 100; @@ -510,14 +477,12 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka //timer.stop("Meta"); continue; } - uint32_t amount = rgData.deserialize(msg, true); - rowGroup->setData(&rgData); - //rowGroup->setData(const_cast(msg.buf())); + + rowGroup->setData(const_cast(msg.buf())); err = (rowGroup->getStatus() != 0); if (err) { - msgBk.advance(amount); - //msgBk.advance(rowGroup->getDataSize()); + msgBk.advance(rowGroup->getDataSize()); string errorMsg; msgBk >> errorMsg; logging::Message::Args args; @@ -528,7 +493,7 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka result.result = UPDATE_ERROR; result.message = message; DMLResult tmpResult; - receiveAll( tmpResult, uniqueId, fPMs, pmState, tableOid); + receiveAll( tmpResult, uniqueId, fPMs); /* qb = 100; //@Bug 4358 get rid of broken pipe error. msg.restart(); @@ -539,7 +504,7 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka //err = true; break; } - if (rowGroup->getRGData() == NULL) + if (rowGroup->getData() == NULL) { msg.restart(); } @@ -547,18 +512,18 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka { //timer.finish(); //need to receive all response - err = receiveAll( result, uniqueId, fPMs, pmState, tableOid); + err = receiveAll( result, uniqueId, fPMs); //return rowsProcessed; break; } - if (rowGroup->getBaseRid() == (uint64_t) (-1)) + if (rowGroup->getBaseRid() == (uint64_t) (-1 & ~0x1fff)) { continue; // @bug4247, not valid row ids, may from small side outer } dbroot = rowGroup->getDBRoot(); //cout << "dbroot in the rowgroup is " << dbroot << endl; //timer.start("processRowgroup"); - err = processRowgroup(msgBk, result, uniqueId, cpackage, pmState, metaData, dbroot); + err = processRowgroup(msgBk, result, uniqueId, cpackage, metaData, dbroot); //timer.stop("processRowgroup"); if (err) { //timer.finish(); @@ -570,7 +535,7 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka logging::Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg1, logid); DMLResult tmpResult; - receiveAll( tmpResult, uniqueId, fPMs, pmState, tableOid); + receiveAll( tmpResult, uniqueId, fPMs); logging::Message::Args args2; logging::Message msg2(1); args2.add("SQL statement erroring out, received all messages from WES"); @@ -607,7 +572,7 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka // Clean out the pipe; DMLResult tmpResult; - receiveAll( tmpResult, uniqueId, fPMs, pmState, tableOid); + receiveAll( tmpResult, uniqueId, fPMs); } // get stats from ExeMgr if (!err) @@ -643,10 +608,6 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka message.format(args); result.result = UPDATE_ERROR; result.message = message; - qb = 0; - msg.restart(); - msg << qb; - fExeMgr->write(msg); return rowsProcessed; } catch ( ... ) @@ -659,10 +620,6 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka message.format(args); result.result = UPDATE_ERROR; result.message = message; - qb = 0; - msg.restart(); - msg << qb; - fExeMgr->write(msg); return rowsProcessed; } //timer.finish(); @@ -670,25 +627,25 @@ uint64_t UpdatePackageProcessor::fixUpRows(dmlpackage::CalpontDMLPackage& cpacka } bool UpdatePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& result, const uint64_t uniqueId, - dmlpackage::CalpontDMLPackage& cpackage, std::map& pmState, bool isMeta, uint32_t dbroot) + dmlpackage::CalpontDMLPackage& cpackage, bool isMeta, uint dbroot) { bool rc = false; //cout << "Get dbroot " << dbroot << endl; - uint32_t pmNum = (*fDbRootPMMap)[dbroot]; + int pmNum = (*fDbRootPMMap)[dbroot]; ByteStream bytestream; - bytestream << (uint8_t)WE_SVR_UPDATE; + bytestream << (ByteStream::byte)WE_SVR_UPDATE; bytestream << uniqueId; - bytestream << pmNum; - bytestream << (uint32_t)cpackage.get_TxnID(); + bytestream << (ByteStream::quadbyte) pmNum; + bytestream << (ByteStream::quadbyte) cpackage.get_TxnID(); bytestream += aRowGroup; //cout << "sending rows to pm " << pmNum << " with msg length " << bytestream.length() << endl; - uint32_t msgRecived = 0; + uint msgRecived = 0; boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); ByteStream::byte tmp8; string errorMsg; - uint32_t tmp32; + ByteStream::quadbyte tmp32; uint64_t blocksChanged = 0; if (isMeta) //send to all PMs @@ -731,7 +688,7 @@ bool UpdatePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& { try { //cout << "sending rows to pm " << pmNum << " with msg length " << bytestream.length() << endl; - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); pmState[pmNum] = false; } catch (runtime_error& ex) //write error @@ -770,8 +727,7 @@ bool UpdatePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& errorMsg = "Lost connection to Write Engine Server while updating"; throw std::runtime_error(errorMsg); } - else - { + else { *bsIn >> tmp8; *bsIn >> errorMsg; if (tmp8 == IDBRANGE_WARNING) @@ -793,14 +749,13 @@ bool UpdatePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& pmState[tmp32] = true; *bsIn >> blocksChanged; result.stats.fBlocksChanged += blocksChanged; - if (rc != 0) - { + if (rc != 0) { throw std::runtime_error(errorMsg); } - if (tmp32 == (uint32_t)pmNum) + if ( tmp32 == (uint)pmNum ) { //cout << "sending rows to pm " << pmNum << " with msg length " << bytestream.length() << endl; - fWEClient->write(bytestream, (uint32_t)pmNum); + fWEClient->write(bytestream, (uint)pmNum); pmState[pmNum] = false; break; } @@ -835,11 +790,10 @@ bool UpdatePackageProcessor::processRowgroup(ByteStream & aRowGroup, DMLResult& return rc; } -bool UpdatePackageProcessor::receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs, - std::map& pmState, const uint32_t tableOid) +bool UpdatePackageProcessor::receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs) { //check how many message we need to receive - uint32_t messagesNotReceived = 0; + uint messagesNotReceived = 0; bool err = false; for (unsigned i=0; i bsIn; - ByteStream::byte tmp8; - string errorMsg; - uint32_t msgReceived = 0; if (messagesNotReceived > 0) { LoggingID logid( DMLLoggingId, fSessionID, fSessionID); @@ -876,8 +826,12 @@ bool UpdatePackageProcessor::receiveAll(DMLResult& result, const uint64_t unique return err; } + boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); + ByteStream::byte tmp8; + string errorMsg; ByteStream::quadbyte tmp32; + uint msgReceived = 0; uint64_t blocksChanged = 0; while (1) diff --git a/dbcon/dmlpackageproc/updatepackageprocessor.h b/dbcon/dmlpackageproc/updatepackageprocessor.h index eaaa8747..0e21858a 100644 --- a/dbcon/dmlpackageproc/updatepackageprocessor.h +++ b/dbcon/dmlpackageproc/updatepackageprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: updatepackageprocessor.h 9302 2013-03-07 16:06:59Z chao $ + * $Id: updatepackageprocessor.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -29,7 +29,7 @@ #include #include "joblist.h" -#if defined(_MSC_VER) && defined(DMLPKGPROC_DLLEXPORT) +#if defined(_MSC_VER) && defined(UPDATEPKGPROC_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -45,7 +45,7 @@ class UpdatePackageProcessor : public DMLPackageProcessor { public: - UpdatePackageProcessor(BRM::DBRM* aDbrm, uint32_t sid) : DMLPackageProcessor(aDbrm, sid) { + UpdatePackageProcessor() : DMLPackageProcessor() { } /** @brief process an UpdateDMLPackage * @@ -62,7 +62,7 @@ class UpdatePackageProcessor : public DMLPackageProcessor * @param result the result of the operation * @return rows processed */ - uint64_t fixUpRows(dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId, const uint32_t tableOid); + uint64_t fixUpRows(dmlpackage::CalpontDMLPackage& cpackage, DMLResult& result, const uint64_t uniqueId); /** @brief send row group to the PM to process @@ -71,8 +71,8 @@ class UpdatePackageProcessor : public DMLPackageProcessor * @param result the result of the operation * @return the error code */ - bool processRowgroup(messageqcpp::ByteStream & aRowGroup, DMLResult& result, const uint64_t uniqueId, dmlpackage::CalpontDMLPackage& cpackage, std::map& pmState, bool isMeta = false, uint32_t dbroot=1); - bool receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs, std::map& pmState, const uint32_t tableOid); + bool processRowgroup(messageqcpp::ByteStream & aRowGroup, DMLResult& result, const uint64_t uniqueId, dmlpackage::CalpontDMLPackage& cpackage, bool isMeta = false, uint dbroot=1); + bool receiveAll(DMLResult& result, const uint64_t uniqueId, std::vector& fPMs); }; } diff --git a/dbcon/doc/calpontsystemcatalog.h b/dbcon/doc/calpontsystemcatalog.h index ae7b2449..be40ede2 100644 --- a/dbcon/doc/calpontsystemcatalog.h +++ b/dbcon/doc/calpontsystemcatalog.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontsystemcatalog.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: calpontsystemcatalog.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/doc/readme b/dbcon/doc/readme deleted file mode 100644 index e69de29b..00000000 diff --git a/dbcon/execplan/Makefile.am b/dbcon/execplan/Makefile.am index b4b674de..ba20511c 100644 --- a/dbcon/execplan/Makefile.am +++ b/dbcon/execplan/Makefile.am @@ -14,6 +14,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) @@ -22,28 +26,20 @@ lib_LTLIBRARIES = libexecplan.la libexecplan_la_SOURCES = calpontsystemcatalog.cpp \ aggregatecolumn.cpp \ arithmeticcolumn.cpp \ -arithmeticoperator.cpp \ calpontexecutionplan.cpp \ calpontexecutionplanfactory.cpp \ calpontselectexecutionplan.cpp \ -clientrotator.cpp \ constantcolumn.cpp \ -constantfilter.cpp \ existsfilter.cpp \ -expressionparser.cpp \ filter.cpp \ functioncolumn.cpp \ groupconcatcolumn.cpp \ -intervalcolumn.cpp \ -logicoperator.cpp \ mysqlexecutionplan.cpp \ objectidmanager.cpp \ objectreader.cpp \ operator.cpp \ -oracleexecutionplan.cpp \ outerjoinonfilter.cpp \ -predicateoperator.cpp \ -pseudocolumn.cpp \ +oracleexecutionplan.cpp \ range.cpp \ returnedcolumn.cpp \ rowcolumn.cpp \ @@ -52,56 +48,56 @@ sessionmanager.cpp \ simplecolumn.cpp \ simplefilter.cpp \ simplescalarfilter.cpp \ +vendorexecutionplan.cpp \ treenode.cpp \ +expressionparser.cpp \ treenodeimpl.cpp \ -vendorexecutionplan.cpp \ -windowfunctioncolumn.cpp - +constantfilter.cpp \ +clientrotator.cpp \ +arithmeticoperator.cpp \ +logicoperator.cpp \ +predicateoperator.cpp include_HEADERS = aggregatecolumn.h \ arithmeticcolumn.h \ -arithmeticoperator.h \ -blocksize.h \ calpontexecutionplanfactory.h \ calpontexecutionplan.h \ -calpontsystemcatalog.h \ calpontselectexecutionplan.h \ -clientrotator.h \ columnresult.h \ constantcolumn.h \ -constantfilter.h \ existsfilter.h \ -expressionparser.h \ -exp_templates.h \ filter.h \ functioncolumn.h \ groupconcatcolumn.h \ -intervalcolumn.h \ -logicoperator.h \ mysqlexecutionplan.h \ njlcolumnresult.h \ objectidmanager.h \ objectreader.h \ operator.h \ -oracleexecutionplan.h \ outerjoinonfilter.h \ -parsetree.h \ -predicateoperator.h \ -pseudocolumn.h \ +oracleexecutionplan.h \ range.h \ returnedcolumn.h \ rowcolumn.h \ selectfilter.h \ sessionmanager.h \ simplecolumn.h \ -simplecolumn_decimal.h \ -simplecolumn_int.h \ -simplecolumn_uint.h \ simplefilter.h \ simplescalarfilter.h \ +vendorexecutionplan.h \ +calpontsystemcatalog.h \ treenode.h \ +parsetree.h \ +expressionparser.h \ treenodeimpl.h \ -vendorexecutionplan.h \ -windowfunctioncolumn.h +constantfilter.h \ +clientrotator.h \ +blocksize.h \ +exp_templates.h \ +arithmeticoperator.h \ +logicoperator.h \ +predicateoperator.h \ +simplecolumn_int.h \ +simplecolumn_decimal.h test: diff --git a/dbcon/execplan/Makefile.in b/dbcon/execplan/Makefile.in index 2cc08045..ccea2335 100644 --- a/dbcon/execplan/Makefile.in +++ b/dbcon/execplan/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -41,9 +60,8 @@ subdir = dbcon/execplan DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -60,19 +78,17 @@ libLTLIBRARIES_INSTALL = $(INSTALL) LTLIBRARIES = $(lib_LTLIBRARIES) libexecplan_la_LIBADD = am_libexecplan_la_OBJECTS = calpontsystemcatalog.lo aggregatecolumn.lo \ - arithmeticcolumn.lo arithmeticoperator.lo \ - calpontexecutionplan.lo calpontexecutionplanfactory.lo \ - calpontselectexecutionplan.lo clientrotator.lo \ - constantcolumn.lo constantfilter.lo existsfilter.lo \ - expressionparser.lo filter.lo functioncolumn.lo \ - groupconcatcolumn.lo intervalcolumn.lo logicoperator.lo \ - mysqlexecutionplan.lo objectidmanager.lo objectreader.lo \ - operator.lo oracleexecutionplan.lo outerjoinonfilter.lo \ - predicateoperator.lo pseudocolumn.lo range.lo \ - returnedcolumn.lo rowcolumn.lo selectfilter.lo \ - sessionmanager.lo simplecolumn.lo simplefilter.lo \ - simplescalarfilter.lo treenode.lo treenodeimpl.lo \ - vendorexecutionplan.lo windowfunctioncolumn.lo + arithmeticcolumn.lo calpontexecutionplan.lo \ + calpontexecutionplanfactory.lo calpontselectexecutionplan.lo \ + constantcolumn.lo existsfilter.lo filter.lo functioncolumn.lo \ + groupconcatcolumn.lo mysqlexecutionplan.lo objectidmanager.lo \ + objectreader.lo operator.lo outerjoinonfilter.lo \ + oracleexecutionplan.lo range.lo returnedcolumn.lo rowcolumn.lo \ + selectfilter.lo sessionmanager.lo simplecolumn.lo \ + simplefilter.lo simplescalarfilter.lo vendorexecutionplan.lo \ + treenode.lo expressionparser.lo treenodeimpl.lo \ + constantfilter.lo clientrotator.lo arithmeticoperator.lo \ + logicoperator.lo predicateoperator.lo libexecplan_la_OBJECTS = $(am_libexecplan_la_OBJECTS) DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp @@ -151,9 +167,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -195,7 +208,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -209,11 +221,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -224,23 +231,6 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) @@ -249,28 +239,20 @@ lib_LTLIBRARIES = libexecplan.la libexecplan_la_SOURCES = calpontsystemcatalog.cpp \ aggregatecolumn.cpp \ arithmeticcolumn.cpp \ -arithmeticoperator.cpp \ calpontexecutionplan.cpp \ calpontexecutionplanfactory.cpp \ calpontselectexecutionplan.cpp \ -clientrotator.cpp \ constantcolumn.cpp \ -constantfilter.cpp \ existsfilter.cpp \ -expressionparser.cpp \ filter.cpp \ functioncolumn.cpp \ groupconcatcolumn.cpp \ -intervalcolumn.cpp \ -logicoperator.cpp \ mysqlexecutionplan.cpp \ objectidmanager.cpp \ objectreader.cpp \ operator.cpp \ -oracleexecutionplan.cpp \ outerjoinonfilter.cpp \ -predicateoperator.cpp \ -pseudocolumn.cpp \ +oracleexecutionplan.cpp \ range.cpp \ returnedcolumn.cpp \ rowcolumn.cpp \ @@ -279,56 +261,57 @@ sessionmanager.cpp \ simplecolumn.cpp \ simplefilter.cpp \ simplescalarfilter.cpp \ +vendorexecutionplan.cpp \ treenode.cpp \ +expressionparser.cpp \ treenodeimpl.cpp \ -vendorexecutionplan.cpp \ -windowfunctioncolumn.cpp +constantfilter.cpp \ +clientrotator.cpp \ +arithmeticoperator.cpp \ +logicoperator.cpp \ +predicateoperator.cpp include_HEADERS = aggregatecolumn.h \ arithmeticcolumn.h \ -arithmeticoperator.h \ -blocksize.h \ calpontexecutionplanfactory.h \ calpontexecutionplan.h \ -calpontsystemcatalog.h \ calpontselectexecutionplan.h \ -clientrotator.h \ columnresult.h \ constantcolumn.h \ -constantfilter.h \ existsfilter.h \ -expressionparser.h \ -exp_templates.h \ filter.h \ functioncolumn.h \ groupconcatcolumn.h \ -intervalcolumn.h \ -logicoperator.h \ mysqlexecutionplan.h \ njlcolumnresult.h \ objectidmanager.h \ objectreader.h \ operator.h \ -oracleexecutionplan.h \ outerjoinonfilter.h \ -parsetree.h \ -predicateoperator.h \ -pseudocolumn.h \ +oracleexecutionplan.h \ range.h \ returnedcolumn.h \ rowcolumn.h \ selectfilter.h \ sessionmanager.h \ simplecolumn.h \ -simplecolumn_decimal.h \ -simplecolumn_int.h \ -simplecolumn_uint.h \ simplefilter.h \ simplescalarfilter.h \ +vendorexecutionplan.h \ +calpontsystemcatalog.h \ treenode.h \ +parsetree.h \ +expressionparser.h \ treenodeimpl.h \ -vendorexecutionplan.h \ -windowfunctioncolumn.h +constantfilter.h \ +clientrotator.h \ +blocksize.h \ +exp_templates.h \ +arithmeticoperator.h \ +logicoperator.h \ +predicateoperator.h \ +simplecolumn_int.h \ +simplecolumn_decimal.h all: all-am @@ -414,7 +397,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filter.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/functioncolumn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/groupconcatcolumn.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/intervalcolumn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/logicoperator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mysqlexecutionplan.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/objectidmanager.Plo@am__quote@ @@ -423,7 +405,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/oracleexecutionplan.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/outerjoinonfilter.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/predicateoperator.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pseudocolumn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/range.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/returnedcolumn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rowcolumn.Plo@am__quote@ @@ -435,7 +416,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/treenode.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/treenodeimpl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vendorexecutionplan.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/windowfunctioncolumn.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ diff --git a/dbcon/execplan/aggregatecolumn.cpp b/dbcon/execplan/aggregatecolumn.cpp index 1cb30c01..2c6e7898 100644 --- a/dbcon/execplan/aggregatecolumn.cpp +++ b/dbcon/execplan/aggregatecolumn.cpp @@ -16,16 +16,14 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: aggregatecolumn.cpp 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: aggregatecolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ #include #include -using namespace std; -#include -using namespace boost; +using namespace std; #include "bytestream.h" using namespace messageqcpp; @@ -70,19 +68,17 @@ void getAggCols(execplan::ParseTree* n, void* obj) * Constructors/Destructors */ AggregateColumn::AggregateColumn(): - fAggOp(NOOP), - fAsc(false) + fAsc(false) { } -AggregateColumn::AggregateColumn(const uint32_t sessionID): - ReturnedColumn(sessionID), - fAggOp(NOOP), - fAsc(false) +AggregateColumn::AggregateColumn(const u_int32_t sessionID): + ReturnedColumn(sessionID), + fAsc(false) { } -AggregateColumn::AggregateColumn(const AggOp aggOp, ReturnedColumn* parm, const uint32_t sessionID): +AggregateColumn::AggregateColumn(const AggOp aggOp, ReturnedColumn* parm, const u_int32_t sessionID): ReturnedColumn(sessionID), fAggOp(aggOp), fAsc(false), @@ -91,7 +87,7 @@ AggregateColumn::AggregateColumn(const AggOp aggOp, ReturnedColumn* parm, const fFunctionParms.reset(parm); } -AggregateColumn::AggregateColumn(const AggOp aggOp, const string& content, const uint32_t sessionID): +AggregateColumn::AggregateColumn(const AggOp aggOp, const string& content, const u_int32_t sessionID): ReturnedColumn(sessionID), fAggOp(aggOp), fAsc(false), @@ -102,58 +98,68 @@ AggregateColumn::AggregateColumn(const AggOp aggOp, const string& content, const } // deprecated constructor. use function name as string -AggregateColumn::AggregateColumn(const std::string& functionName, ReturnedColumn* parm, const uint32_t sessionID): - ReturnedColumn(sessionID), - fFunctionName(functionName), - fAggOp(NOOP), - fAsc(false), - fData(functionName + "(" + parm->data() + ")") +AggregateColumn::AggregateColumn(const std::string& functionName, ReturnedColumn* parm, const u_int32_t sessionID): + ReturnedColumn(sessionID), + fFunctionName(functionName), + fAsc(false), + fData(functionName + "(" + parm->data() + ")") { fFunctionParms.reset(parm); } - + // deprecated constructor. use function name as string -AggregateColumn::AggregateColumn(const string& functionName, const string& content, const uint32_t sessionID): - ReturnedColumn(sessionID), - fFunctionName(functionName), - fAggOp(NOOP), - fAsc(false), - fData(functionName + "(" + content + ")") +AggregateColumn::AggregateColumn(const string& functionName, const string& content, const u_int32_t sessionID): + ReturnedColumn(sessionID), + fFunctionName (functionName), + fAsc(false), + fData(functionName + "(" + content + ")") { // TODO: need to handle distinct fFunctionParms.reset(new ArithmeticColumn(content)); } -AggregateColumn::AggregateColumn( const AggregateColumn& rhs, const uint32_t sessionID ): +AggregateColumn::AggregateColumn( const AggregateColumn& rhs, const u_int32_t sessionID ): ReturnedColumn(rhs, sessionID), fFunctionName (rhs.fFunctionName), fAggOp(rhs.fAggOp), fFunctionParms(rhs.fFunctionParms), - fTableAlias(rhs.tableAlias()), - fAsc(rhs.asc()), - fData(rhs.data()), + fTableAlias (rhs.tableAlias()), + fAsc (rhs.asc()), + fData (rhs.data()), fConstCol(rhs.fConstCol) { fAlias = rhs.alias(); } +AggregateColumn::~AggregateColumn() +{ +} + /** * Methods */ +void AggregateColumn::functionName(const string& functionName) +{ + fFunctionName = functionName; +} + +void AggregateColumn::functionParms(const SRCP& functionParms) +{ + fFunctionParms = functionParms; +} + const string AggregateColumn::toString() const { ostringstream output; - output << "AggregateColumn " << data() << endl; + output << "AggregateColumn " << data() << endl; output << "func/distinct: " << (int)fAggOp << "/" << fDistinct << endl; output << "expressionId=" << fExpressionId << endl; if (fAlias.length() > 0) output << "/Alias: " << fAlias << endl; if (fFunctionParms == 0) - output << "No arguments" << endl; + output << "No arguments"; else - output << *fFunctionParms << endl; - if (fConstCol) - output << *fConstCol; + output << *fFunctionParms; return output.str(); } @@ -166,18 +172,18 @@ ostream& operator<<(ostream& output, const AggregateColumn& rhs) void AggregateColumn::serialize(messageqcpp::ByteStream& b) const { CalpontSelectExecutionPlan::ReturnedColumnList::const_iterator rcit; - b << (uint8_t) ObjectReader::AGGREGATECOLUMN; + b << (u_int8_t) ObjectReader::AGGREGATECOLUMN; ReturnedColumn::serialize(b); b << fFunctionName; - b << static_cast(fAggOp); + b << static_cast(fAggOp); if (fFunctionParms == 0) - b << (uint8_t) ObjectReader::NULL_CLASS; + b << (u_int8_t) ObjectReader::NULL_CLASS; else fFunctionParms->serialize(b); - b << static_cast(fGroupByColList.size()); + b << static_cast(fGroupByColList.size()); for (rcit = fGroupByColList.begin(); rcit != fGroupByColList.end(); ++rcit) (*rcit)->serialize(b); - b << static_cast(fProjectColList.size()); + b << static_cast(fProjectColList.size()); for (rcit = fProjectColList.begin(); rcit != fProjectColList.end(); ++rcit) (*rcit)->serialize(b); b << fData; @@ -185,9 +191,9 @@ void AggregateColumn::serialize(messageqcpp::ByteStream& b) const b << fTableAlias; b << static_cast(fAsc); if (fConstCol.get() == 0) - b << (uint8_t) ObjectReader::NULL_CLASS; + b << (u_int8_t) ObjectReader::NULL_CLASS; else - fConstCol->serialize(b); + fConstCol->serialize(b); } void AggregateColumn::unserialize(messageqcpp::ByteStream& b) @@ -203,19 +209,19 @@ void AggregateColumn::unserialize(messageqcpp::ByteStream& b) dynamic_cast(ObjectReader::createTreeNode(b))); messageqcpp::ByteStream::quadbyte size; - messageqcpp::ByteStream::quadbyte i; - ReturnedColumn *rc; + messageqcpp::ByteStream::quadbyte i; + ReturnedColumn *rc; b >> size; for (i = 0; i < size; i++) { rc = dynamic_cast(ObjectReader::createTreeNode(b)); - SRCP srcp(rc); + SRCP srcp(rc); fGroupByColList.push_back(srcp); } b >> size; for (i = 0; i < size; i++) { rc = dynamic_cast(ObjectReader::createTreeNode(b)); - SRCP srcp(rc); + SRCP srcp(rc); fProjectColList.push_back(srcp); } b >> fData; @@ -249,7 +255,7 @@ bool AggregateColumn::operator==(const AggregateColumn& t) const //if (fAlias != t.fAlias) // return false; if (fTableAlias != t.fTableAlias) - return false; + return false; if (fData != t.fData) return false; if (fAsc != t.fAsc) @@ -282,249 +288,190 @@ bool AggregateColumn::operator!=(const TreeNode* t) const return !(*this == t); } -bool AggregateColumn::hasAggregate() -{ - fAggColumnList.push_back(this); - return true; -} - void AggregateColumn::evaluate(Row& row, bool& isNull) { switch (fResultType.colDataType) { - case CalpontSystemCatalog::DATE: - if (row.equals<4>(DATENULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getUintField<4>(fInputIndex); - break; - case CalpontSystemCatalog::DATETIME: - if (row.equals<8>(DATETIMENULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getUintField<8>(fInputIndex); - break; - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::STRINT: - switch (row.getColumnWidth(fInputIndex)) + case CalpontSystemCatalog::DATE: { - case 1: - if (row.equals<1>(CHAR1NULL, fInputIndex)) + if (row.equals<4>(DATENULL, fInputIndex)) isNull = true; else - fResult.origIntVal = row.getUintField<1>(fInputIndex); + fResult.intVal = row.getUintField<4>(fInputIndex); break; - case 2: - if (row.equals<2>(CHAR2NULL, fInputIndex)) + } + case CalpontSystemCatalog::DATETIME: + { + if (row.equals<8>(DATETIMENULL, fInputIndex)) isNull = true; else - fResult.origIntVal = row.getUintField<2>(fInputIndex); + fResult.intVal = row.getUintField<8>(fInputIndex); break; - case 3: - case 4: - if (row.equals<4>(CHAR4NULL, fInputIndex)) - isNull = true; + } + case CalpontSystemCatalog::CHAR: + case CalpontSystemCatalog::VARCHAR: + case CalpontSystemCatalog::STRINT: + { + switch (row.getColumnWidth(fInputIndex)) + { + case 1: + if (row.equals<1>(CHAR1NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<1>(fInputIndex); + break; + case 2: + if (row.equals<2>(CHAR2NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<2>(fInputIndex); + break; + case 3: + case 4: + if (row.equals<4>(CHAR4NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<4>(fInputIndex); + break; + case 5: + case 6: + case 7: + case 8: + if (row.equals<8>(CHAR8NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<8>(fInputIndex); + break; + default: + if (row.equals(CPNULLSTRMARK, fInputIndex)) + isNull = true; + else + fResult.strVal = row.getStringField(fInputIndex); + // stringColVal is padded with '\0' to colWidth so can't use str.length() + if (strlen(fResult.strVal.c_str()) == 0) + isNull = true; + break; + } + if (fResultType.colDataType == CalpontSystemCatalog::STRINT) + fResult.intVal = uint64ToStr(fResult.origIntVal); else - fResult.origIntVal = row.getUintField<4>(fInputIndex); + fResult.intVal = atoll((char*)&fResult.origIntVal); break; - case 5: - case 6: - case 7: - case 8: - if (row.equals<8>(CHAR8NULL, fInputIndex)) + } + case CalpontSystemCatalog::BIGINT: + { + if (row.equals<8>(BIGINTNULL, fInputIndex)) isNull = true; else - fResult.origIntVal = row.getUintField<8>(fInputIndex); + fResult.intVal = row.getIntField<8>(fInputIndex); break; - default: - if (row.equals(CPNULLSTRMARK, fInputIndex)) + } + case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::MEDINT: + { + if (row.equals<4>(INTNULL, fInputIndex)) isNull = true; else - fResult.strVal = row.getStringField(fInputIndex); - // stringColVal is padded with '\0' to colWidth so can't use str.length() - if (strlen(fResult.strVal.c_str()) == 0) + fResult.intVal = row.getIntField<4>(fInputIndex); + break; + } + case CalpontSystemCatalog::SMALLINT: + { + if (row.equals<2>(SMALLINTNULL, fInputIndex)) isNull = true; + else + fResult.intVal = row.getIntField<2>(fInputIndex); break; } - if (fResultType.colDataType == CalpontSystemCatalog::STRINT) - fResult.intVal = uint64ToStr(fResult.origIntVal); - else - fResult.intVal = atoll((char*)&fResult.origIntVal); - break; - case CalpontSystemCatalog::BIGINT: - if (row.equals<8>(BIGINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<8>(fInputIndex); - break; - case CalpontSystemCatalog::UBIGINT: - if (row.equals<8>(UBIGINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<8>(fInputIndex); - break; - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::MEDINT: - if (row.equals<4>(INTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<4>(fInputIndex); - break; - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UMEDINT: - if (row.equals<4>(UINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<4>(fInputIndex); - break; - case CalpontSystemCatalog::SMALLINT: - if (row.equals<2>(SMALLINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<2>(fInputIndex); - break; - case CalpontSystemCatalog::USMALLINT: - if (row.equals<2>(USMALLINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<2>(fInputIndex); - break; - case CalpontSystemCatalog::TINYINT: - if (row.equals<1>(TINYINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<1>(fInputIndex); - break; - case CalpontSystemCatalog::UTINYINT: - if (row.equals<1>(UTINYINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<1>(fInputIndex); - break; - //In this case, we're trying to load a double output column with float data. This is the - // case when you do sum(floatcol), e.g. - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - if (row.equals<4>(FLOATNULL, fInputIndex)) - isNull = true; - else - fResult.floatVal = row.getFloatField(fInputIndex); - break; - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - if (row.equals<8>(DOUBLENULL, fInputIndex)) - isNull = true; - else - fResult.doubleVal = row.getDoubleField(fInputIndex); - break; - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: - switch (fResultType.colWidth) + case CalpontSystemCatalog::TINYINT: { - case 1: if (row.equals<1>(TINYINTNULL, fInputIndex)) isNull = true; else - { - fResult.decimalVal.value = row.getIntField<1>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } + fResult.intVal = row.getIntField<1>(fInputIndex); break; - case 2: - if (row.equals<2>(SMALLINTNULL, fInputIndex)) + } + //In this case, we're trying to load a double output column with float data. This is the + // case when you do sum(floatcol), e.g. + case CalpontSystemCatalog::FLOAT: + { + if (row.equals<4>(FLOATNULL, fInputIndex)) isNull = true; else - { - fResult.decimalVal.value = row.getIntField<2>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } + fResult.floatVal = row.getFloatField(fInputIndex); break; - case 4: - if (row.equals<4>(INTNULL, fInputIndex)) + } + case CalpontSystemCatalog::DOUBLE: + { + if (row.equals<8>(DOUBLENULL, fInputIndex)) isNull = true; else - { - fResult.decimalVal.value = row.getIntField<4>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } + fResult.doubleVal = row.getDoubleField(fInputIndex); break; - default: + } + case CalpontSystemCatalog::DECIMAL: + { + switch (fResultType.colWidth) + { + case 1: + { + if (row.equals<1>(TINYINTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = row.getIntField<1>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + case 2: + { + if (row.equals<2>(SMALLINTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = row.getIntField<2>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + case 4: + { + if (row.equals<4>(INTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = row.getIntField<4>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + default: + { + if (row.equals<8>(BIGINTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = (int64_t)row.getUintField<8>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + } + break; + } + case CalpontSystemCatalog::VARBINARY: + isNull = true; + break; + default: // treat as int64 + { if (row.equals<8>(BIGINTNULL, fInputIndex)) isNull = true; else - { - fResult.decimalVal.value = (int64_t)row.getUintField<8>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } + fResult.intVal = row.getUintField<8>(fInputIndex); break; } - break; - case CalpontSystemCatalog::VARBINARY: - isNull = true; - break; - default: // treat as int64 - if (row.equals<8>(BIGINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getUintField<8>(fInputIndex); - break; } } -/*static*/ -AggregateColumn::AggOp AggregateColumn::agname2num(const string& agname) -{ -/* - NOOP = 0, - COUNT_ASTERISK, - COUNT, - SUM, - AVG, - MIN, - MAX, - CONSTANT, - DISTINCT_COUNT, - DISTINCT_SUM, - DISTINCT_AVG, - STDDEV_POP, - STDDEV_SAMP, - VAR_POP, - VAR_SAMP, - BIT_AND, - BIT_OR, - BIT_XOR, - GROUP_CONCAT -*/ - string lfn(agname); - algorithm::to_lower(lfn); - if (lfn == "count(*)") - return COUNT_ASTERISK; - if (lfn == "count") - return COUNT; - if (lfn == "sum") - return SUM; - if (lfn == "avg") - return AVG; - if (lfn == "min") - return MIN; - if (lfn == "max") - return MAX; - if (lfn == "std") - return STDDEV_POP; - if (lfn == "stddev_pop") - return STDDEV_POP; - if (lfn == "stddev_samp") - return STDDEV_SAMP; - if (lfn == "stddev") - return STDDEV_POP; - if (lfn == "var_pop") - return VAR_POP; - if (lfn == "var_samp") - return VAR_SAMP; - if (lfn == "variance") - return VAR_POP; - return NOOP; -} - } // namespace execplan diff --git a/dbcon/execplan/aggregatecolumn.h b/dbcon/execplan/aggregatecolumn.h index 74e47683..4d0c57a1 100644 --- a/dbcon/execplan/aggregatecolumn.h +++ b/dbcon/execplan/aggregatecolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: aggregatecolumn.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: aggregatecolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -36,20 +36,16 @@ class ByteStream; /** * Namespace */ -namespace execplan { - +namespace execplan { /** * @brief A class to represent a aggregate return column - * + * * This class is a specialization of class ReturnedColumn that * handles an aggregate function call (e.g., SUM, COUNT, MIN, MAX). */ class AggregateColumn : public ReturnedColumn { public: - /** - * AggOp enum - */ enum AggOp { NOOP = 0, @@ -73,132 +69,84 @@ class AggregateColumn : public ReturnedColumn { GROUP_CONCAT }; - /** - * typedef - */ typedef std::vector ColumnList; - /* - * Constructors - */ /** - * ctor + * Constructors */ AggregateColumn(); + + AggregateColumn(const u_int32_t sessionID); - /** - * ctor - */ - AggregateColumn(const uint32_t sessionID); - - /** - * ctor - */ - AggregateColumn(const AggOp aggop, ReturnedColumn* parm, const uint32_t sessionID=0); - - /** - * ctor - */ - AggregateColumn(const AggOp aggop, const std::string& content, const uint32_t sessionID=0); - - /** - * ctor - */ - AggregateColumn(const std::string& functionName, ReturnedColumn* parm, const uint32_t sessionID=0); - - /** - * ctor - */ - AggregateColumn(const std::string& functionName, const std::string& content, const uint32_t sessionID=0); - - /** - * ctor - */ - AggregateColumn( const AggregateColumn& rhs, const uint32_t sessionID=0 ); + AggregateColumn(const AggOp aggop, ReturnedColumn* parm, const u_int32_t sessionID=0); + + AggregateColumn(const AggOp aggop, const std::string& content, const u_int32_t sessionID=0); + AggregateColumn(const std::string& functionName, ReturnedColumn* parm, const u_int32_t sessionID=0); + + AggregateColumn(const std::string& functionName, const std::string& content, const u_int32_t sessionID=0); + + AggregateColumn( const AggregateColumn& rhs, const u_int32_t sessionID=0 ); + /** * Destructors */ - virtual ~AggregateColumn() { } - + virtual ~AggregateColumn(); + /** * Accessor Methods */ - virtual const std::string functionName() const + inline virtual const std::string& functionName() const { return fFunctionName; } - - /** - * accessor - */ - virtual void functionName(const std::string& functionName) - { - fFunctionName = functionName; - } - - /** - * accessor - */ - virtual const uint8_t aggOp() const {return fAggOp;} - /** - * accessor - */ - virtual void aggOp(const uint8_t aggOp) {fAggOp = aggOp;} - + + virtual void functionName(const std::string& functionName); + + virtual const u_int8_t aggOp() const {return fAggOp;} + virtual void aggOp(const u_int8_t aggOp) {fAggOp = aggOp;} + /** get function parms * * set the function parms from this object */ - virtual const SRCP functionParms() const + virtual const SRCP& functionParms() const { return fFunctionParms; } - + /** set function parms * * set the function parms for this object */ - virtual void functionParms(const SRCP& functionParms) - { - fFunctionParms = functionParms; - } - - /** return a copy of this pointer + virtual void functionParms(const SRCP& functionParms); + + /** return a copy of this pointer * * deep copy of this pointer and return the copy - */ + */ inline virtual AggregateColumn* clone() const { return new AggregateColumn (*this); } - - /** - * table alias name - */ - virtual const std::string tableAlias() const { return fTableAlias; } + /** - * table alias name - */ + * table alias name + */ + virtual const std::string& tableAlias() const { return fTableAlias; } virtual void tableAlias (const std::string& tableAlias) { fTableAlias = tableAlias; } - - /** - * ASC flag - */ + + /** + * ASC flag + */ inline virtual const bool asc() const { return fAsc; } - /** - * ASC flag - */ - inline virtual void asc(const bool asc) { fAsc = asc; } + inline virtual void asc(const bool asc) { fAsc = asc; } /** * fData: SQL representation of this object */ virtual const std::string data() const { return fData; } - /** - * fData: SQL representation of this object - */ virtual void data(const std::string& data) { fData = data; } - + /** * Overloaded stream operator */ @@ -208,166 +156,115 @@ class AggregateColumn : public ReturnedColumn { * Serialize interface */ virtual void serialize(messageqcpp::ByteStream&) const; - /** - * Serialize interface - */ virtual void unserialize(messageqcpp::ByteStream&); - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise - */ + */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const AggregateColumn& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const AggregateColumn& t) const; - + /** @brief push back arg to group by column list*/ virtual void addGroupByCol(SRCP ac) {fGroupByColList.push_back(ac);} - + /** @brief push back arg to project by column list*/ virtual void addProjectCol(SRCP ac) {fProjectColList.push_back(ac);} - - /** - * accessor - */ virtual const ColumnList& groupByColList() const { return fGroupByColList;} - /** - * accessor - */ virtual const ColumnList& projectColList() const { return fProjectColList;} - + /** @brief constant argument for aggregate with constant */ - inline const SRCP constCol() const { return fConstCol; } - /** - * accessor - */ - inline void constCol(const SRCP& constCol) { fConstCol = constCol; } - - /** - * convert an aggregate name to an AggOp enum - */ - static AggOp agname2num(const std::string&); - - virtual bool hasAggregate(); - virtual bool hasWindowFunc() {return false;} + inline const SRCP& constCol() const { return fConstCol; } + inline void constCol(const SRCP& constCol) { fConstCol = constCol; } protected: std::string fFunctionName; // deprecated field - uint8_t fAggOp; + u_int8_t fAggOp; /** * A ReturnedColumn objects that are the arguments to this function */ SRCP fFunctionParms; - + /** table alias * A string to represent table alias name which contains this column - */ + */ std:: string fTableAlias; - + /** * Flag to indicate asc or desc order for order by column */ - bool fAsc; + bool fAsc; std::string fData; ColumnList fGroupByColList; ColumnList fProjectColList; SRCP fConstCol; - -public: + /*********************************************************** * F&E framework * ***********************************************************/ - /** - * F&E - */ - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) - { +public: + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull) + { evaluate(row, isNull); - return TreeNode::getStrVal(); + return TreeNode::getStrVal(); } - - /** - * F&E - */ - virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { + + virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) + { evaluate(row, isNull); - return TreeNode::getIntVal(); + return TreeNode::getIntVal(); } - - /** - * F&E - */ - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getUintVal(); - } - - /** - * F&E - */ + virtual float getFloatVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getFloatVal(); } - - /** - * F&E - */ - virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) + + virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); - return TreeNode::getDoubleVal(); + return TreeNode::getDoubleVal(); } - - /** - * F&E - */ + virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getDecimalVal(); } - /** - * F&E - */ virtual int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getDateIntVal(); } - /** - * F&E - */ virtual int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getDatetimeIntVal(); } - + private: void evaluate(rowgroup::Row& row, bool& isNull); }; @@ -381,6 +278,6 @@ std::ostream& operator<<(std::ostream& os, const AggregateColumn& rhs); */ void getAggCols(ParseTree* n, void* obj); -} //namespace execplan +} #endif //AGGREGATECOLUMN_H diff --git a/dbcon/execplan/arithmeticcolumn.cpp b/dbcon/execplan/arithmeticcolumn.cpp index 5c12f7e5..7a5fa123 100644 --- a/dbcon/execplan/arithmeticcolumn.cpp +++ b/dbcon/execplan/arithmeticcolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: arithmeticcolumn.cpp 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: arithmeticcolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -32,14 +32,12 @@ using namespace std; #include "operator.h" #include "bytestream.h" using namespace messageqcpp; - #include "objectreader.h" #include "expressionparser.h" #include "calpontselectexecutionplan.h" #include "treenodeimpl.h" #include "functioncolumn.h" #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" namespace { /** print the tree @@ -63,7 +61,7 @@ ArithmeticColumn::ArithmeticColumn(): fExpression (0) {} -ArithmeticColumn::ArithmeticColumn(const string& sql, const uint32_t sessionID): +ArithmeticColumn::ArithmeticColumn(const string& sql, const u_int32_t sessionID): ReturnedColumn(sessionID), fData(sql), fExpression(0) @@ -71,7 +69,7 @@ ArithmeticColumn::ArithmeticColumn(const string& sql, const uint32_t sessionID): buildTree(); } -ArithmeticColumn::ArithmeticColumn(const ArithmeticColumn& rhs, const uint32_t sessionID): +ArithmeticColumn::ArithmeticColumn(const ArithmeticColumn& rhs, const u_int32_t sessionID): ReturnedColumn(rhs, sessionID), fTableAlias (rhs.fTableAlias), fAsc (rhs.fAsc), @@ -83,8 +81,6 @@ ArithmeticColumn::ArithmeticColumn(const ArithmeticColumn& rhs, const uint32_t s fExpression->walk(getSimpleCols, &fSimpleColumnList); fAggColumnList.clear(); fExpression->walk(getAggCols, &fAggColumnList); - fWindowFunctionColumnList.clear(); - fExpression->walk(getWindowFunctionCols, &fWindowFunctionColumnList); } ArithmeticColumn::~ArithmeticColumn() @@ -296,9 +292,7 @@ const string ArithmeticColumn::toString() const if (fAlias.length() > 0) oss << "Alias: " << fAlias << endl; if (fExpression != 0) fExpression->walk(walkfn, oss); oss << "expressionId=" << fExpressionId << endl; - oss << "joinInfo=" << fJoinInfo << " returnAll=" << fReturnAll << " sequence#=" << fSequence << endl; - oss << "resultType=" << colDataTypeToString(fResultType.colDataType) << "|" << fResultType.colWidth << -endl; + oss << "resultType=" << fResultType.colDataType << "|" << fResultType.colWidth << endl; return oss.str(); } @@ -324,11 +318,10 @@ void ArithmeticColumn::unserialize(messageqcpp::ByteStream& b) b >> reinterpret_cast< ByteStream::doublebyte&>(fAsc); fSimpleColumnList.clear(); + fAggColumnList.clear(); fExpression->walk(getSimpleCols, &fSimpleColumnList); fAggColumnList.clear(); fExpression->walk(getAggCols, &fAggColumnList); - fWindowFunctionColumnList.clear(); - fExpression->walk(getWindowFunctionCols, &fWindowFunctionColumnList); } bool ArithmeticColumn::operator==(const ArithmeticColumn& t) const @@ -374,68 +367,5 @@ bool ArithmeticColumn::operator!=(const TreeNode* t) const return (!(*this == t)); } -bool ArithmeticColumn::hasAggregate() -{ - if (fHasAggregate) return true; - fAggColumnList.clear(); - fExpression->walk(getAggCols, &fAggColumnList); - if (!fAggColumnList.empty()) - fHasAggregate = true; - return fHasAggregate; -} - -bool ArithmeticColumn::hasWindowFunc() -{ - fWindowFunctionColumnList.clear(); - fExpression->walk(getWindowFunctionCols, &fWindowFunctionColumnList); - if (fWindowFunctionColumnList.empty()) - return false; - return true; -} - -void ArithmeticColumn::setDerivedTable() -{ - if (hasAggregate()) - { - fDerivedTable = ""; - return; - } - if (fExpression) - { - fExpression->setDerivedTable(); - fDerivedTable = fExpression->derivedTable(); - } -} - -void ArithmeticColumn::replaceRealCol(std::vector& derivedColList) -{ - if (fExpression) - replaceRefCol(fExpression, derivedColList); -} - -void ArithmeticColumn::setSimpleColumnList() -{ - fSimpleColumnList.clear(); - fExpression->walk(getSimpleCols, &fSimpleColumnList); -} - -bool ArithmeticColumn::singleTable(CalpontSystemCatalog::TableAliasName& tan) -{ - tan.clear(); - setSimpleColumnList(); - for (uint32_t i = 0; i < fSimpleColumnList.size(); i++) - { - CalpontSystemCatalog::TableAliasName stan(fSimpleColumnList[i]->schemaName(), - fSimpleColumnList[i]->tableName(), - fSimpleColumnList[i]->tableAlias(), - fSimpleColumnList[i]->viewName()); - if (tan.table.empty()) - tan = stan; - else if (stan != tan) - return false; - } - return true; -} - } // namespace diff --git a/dbcon/execplan/arithmeticcolumn.h b/dbcon/execplan/arithmeticcolumn.h index a7ab779e..aec7a45b 100644 --- a/dbcon/execplan/arithmeticcolumn.h +++ b/dbcon/execplan/arithmeticcolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: arithmeticcolumn.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: arithmeticcolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -34,24 +34,24 @@ /** * Namespace */ -namespace execplan { +namespace execplan { class SimpleColumn; class AggregateColumn; /** * @brief A class to represent a arithmetic expression return column - * + * * This class is a specialization of class ReturnedColumn that * handles an arithmetic expression. */ class ArithmeticColumn : public ReturnedColumn { public: ArithmeticColumn(); - ArithmeticColumn( const std::string& sql, const uint32_t sessionID=0 ); - ArithmeticColumn( const ArithmeticColumn& rhs, const uint32_t sessionID=0 ); + ArithmeticColumn( const std::string& sql, const u_int32_t sessionID=0 ); + ArithmeticColumn( const ArithmeticColumn& rhs, const u_int32_t sessionID=0 ); virtual ~ArithmeticColumn(); - inline ParseTree* expression() const + inline const ParseTree* expression() const { return fExpression; } @@ -81,22 +81,22 @@ class ArithmeticColumn : public ReturnedColumn { */ void expression (ParseTree*& expression); - /** + /** * get asc flag */ inline const bool asc() const { return fAsc; } - /** + /** * set asc flag */ inline void asc(const bool asc) { fAsc = asc; } - /** + /** * get SQL representation of this object */ virtual const std::string data() const { return fData; } - /** + /** * set SQL representation of this object */ virtual void data(const std::string data) { fData = data; } @@ -141,7 +141,7 @@ class ArithmeticColumn : public ReturnedColumn { * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. @@ -149,30 +149,13 @@ class ArithmeticColumn : public ReturnedColumn { */ bool operator!=(const ArithmeticColumn& t) const; - virtual bool hasAggregate(); - virtual bool hasWindowFunc(); - - virtual void setDerivedTable(); - virtual void replaceRealCol(std::vector&); - virtual const std::vector& simpleColumnList() const - { return fSimpleColumnList; } - virtual void setSimpleColumnList(); - - /** - * Return the table that the column arguments belong to. - * - * @return tablename, if all arguments belong to one table - * empty string "", if multiple tables are involved in this func - */ - virtual bool singleTable(CalpontSystemCatalog::TableAliasName& tan); - private: std::string fTableAlias; // table alias for this column bool fAsc; // asc flag for order by column std::string fData; /** build expression tree - * + * * this function is called by the constructor. the incomming * sql string is parsed and tokenized and built into a * parse tree. @@ -180,7 +163,7 @@ class ArithmeticColumn : public ReturnedColumn { void buildTree(); /** get next token from expression - * + * * this is a util function used by buildTree(). next token string * is retrived from expression from curPos, until end char. * return the retrived token. curPos reference is updated to the @@ -191,30 +174,25 @@ class ArithmeticColumn : public ReturnedColumn { /*********************************************************** * F&E framework * ***********************************************************/ -public: - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) - { - return fExpression->getStrVal(row, isNull); +public: + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull) + { + return fExpression->getStrVal(row, isNull); } - virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { + virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) + { return fExpression->getIntVal(row, isNull); } - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { - return fExpression->getUintVal(row, isNull); - } - virtual float getFloatVal(rowgroup::Row& row, bool& isNull) { return fExpression->getFloatVal(row, isNull); } - virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) + virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) { - return fExpression->getDoubleVal(row, isNull); + return fExpression->getDoubleVal(row, isNull); } virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) @@ -248,6 +226,6 @@ class ArithmeticColumn : public ReturnedColumn { */ std::ostream& operator<<(std::ostream& output, const ArithmeticColumn& rhs); -} +} #endif //ARITHMETICCOLUMN_H diff --git a/dbcon/execplan/arithmeticoperator.cpp b/dbcon/execplan/arithmeticoperator.cpp index b16b0dbe..84043f35 100644 --- a/dbcon/execplan/arithmeticoperator.cpp +++ b/dbcon/execplan/arithmeticoperator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: arithmeticoperator.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: arithmeticoperator.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -29,11 +29,11 @@ using namespace std; namespace { - + /**@brief util struct for converting string to lower case */ struct to_lower { - char operator() (char c) const { return tolower(c); } + char operator() (char c) const { return tolower(c); } }; //Trim any leading/trailing ws @@ -51,7 +51,7 @@ const string lrtrim(const string& in) } namespace execplan { - + /** * Constructors/Destructors */ @@ -61,7 +61,7 @@ ArithmeticOperator::ArithmeticOperator() : Operator() ArithmeticOperator::ArithmeticOperator(const string& operatorName):Operator(operatorName) { -} +} ArithmeticOperator::ArithmeticOperator(const ArithmeticOperator& rhs):Operator(rhs) { @@ -78,12 +78,12 @@ ArithmeticOperator:: ~ArithmeticOperator() /** * friend function */ -ostream& operator<<(ostream &output, const ArithmeticOperator& rhs) +ostream& operator<<(ostream &output, const ArithmeticOperator& rhs) { output << rhs.toString(); output << "opType=" << rhs.operationType().colDataType << endl; return output; -} +} /** * The serialization interface @@ -148,7 +148,7 @@ void ArithmeticOperator::operationType(const Type& l, const Type& r) fOperationType.scale = l.scale; break; default: - fOperationType.colDataType = execplan::CalpontSystemCatalog::DOUBLE; + fOperationType.colDataType = execplan::CalpontSystemCatalog::DOUBLE; } } else if (r.colDataType == execplan::CalpontSystemCatalog::DECIMAL) @@ -170,38 +170,20 @@ void ArithmeticOperator::operationType(const Type& l, const Type& r) fOperationType.scale = r.scale; break; default: - fOperationType.colDataType = execplan::CalpontSystemCatalog::DOUBLE; + fOperationType.colDataType = execplan::CalpontSystemCatalog::DOUBLE; } } else if ((l.colDataType == execplan::CalpontSystemCatalog::INT || - l.colDataType == execplan::CalpontSystemCatalog::MEDINT || - l.colDataType == execplan::CalpontSystemCatalog::TINYINT || - l.colDataType == execplan::CalpontSystemCatalog::BIGINT) && - (r.colDataType == execplan::CalpontSystemCatalog::INT || - r.colDataType == execplan::CalpontSystemCatalog::MEDINT || - r.colDataType == execplan::CalpontSystemCatalog::TINYINT || - r.colDataType == execplan::CalpontSystemCatalog::BIGINT)) + l.colDataType == execplan::CalpontSystemCatalog::MEDINT || + l.colDataType == execplan::CalpontSystemCatalog::TINYINT || + l.colDataType == execplan::CalpontSystemCatalog::BIGINT) && + (r.colDataType == execplan::CalpontSystemCatalog::INT || + r.colDataType == execplan::CalpontSystemCatalog::MEDINT || + r.colDataType == execplan::CalpontSystemCatalog::TINYINT || + r.colDataType == execplan::CalpontSystemCatalog::BIGINT)) fOperationType.colDataType = execplan::CalpontSystemCatalog::BIGINT; else - fOperationType.colDataType = execplan::CalpontSystemCatalog::DOUBLE; + fOperationType.colDataType = execplan::CalpontSystemCatalog::DOUBLE; } #endif - -void ArithmeticOperator::adjustResultType(const CalpontSystemCatalog::ColType& m) -{ - if (m.colDataType != CalpontSystemCatalog::DECIMAL) - { - fResultType = m; - } - else - { - CalpontSystemCatalog::ColType n; - n.colDataType = CalpontSystemCatalog::DOUBLE; - n.scale = m.scale; // @bug5736, save the original decimal scale - n.precision = -1; // @bug5736, indicate this double is for decimal math - n.colWidth = 8; - fResultType = n; - } -} - } // namespace diff --git a/dbcon/execplan/arithmeticoperator.h b/dbcon/execplan/arithmeticoperator.h index 5861fc27..beaf690d 100644 --- a/dbcon/execplan/arithmeticoperator.h +++ b/dbcon/execplan/arithmeticoperator.h @@ -95,7 +95,7 @@ class ArithmeticOperator : public Operator { ***********************************************************/ inline virtual void evaluate(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop); - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { evaluate(row, isNull, lop, rop); return TreeNode::getStrVal(); @@ -105,11 +105,6 @@ class ArithmeticOperator : public Operator { evaluate(row, isNull, lop, rop); return TreeNode::getIntVal(); } - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull,ParseTree* lop, ParseTree* rop) - { - evaluate(row, isNull, lop, rop); - return TreeNode::getUintVal(); - } virtual float getFloatVal(rowgroup::Row& row, bool& isNull,ParseTree* lop, ParseTree* rop) { evaluate(row, isNull, lop, rop); @@ -123,19 +118,6 @@ class ArithmeticOperator : public Operator { virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { evaluate(row, isNull, lop, rop); - - // @bug5736, double type with precision -1 indicates that this type is for decimal math, - // the original decimal scale is stored in scale field, which is no use for double. - if (fResultType.colDataType == CalpontSystemCatalog::DOUBLE && fResultType.precision == -1) - { - IDB_Decimal rv; - rv.scale = fResultType.scale; - rv.precision = 15; - rv.value = (int64_t)(TreeNode::getDoubleVal() * IDB_pow[rv.scale]); - - return rv; - } - return TreeNode::getDecimalVal(); } virtual int32_t getDateIntVal(rowgroup::Row& row, bool& isNull,ParseTree* lop, ParseTree* rop) @@ -153,7 +135,6 @@ class ArithmeticOperator : public Operator { evaluate(row, isNull, lop, rop); return TreeNode::getBoolVal(); } - void adjustResultType(const CalpontSystemCatalog::ColType& m); private: template @@ -175,19 +156,11 @@ inline void ArithmeticOperator::evaluate(rowgroup::Row& row, bool& isNull, Parse case execplan::CalpontSystemCatalog::TINYINT: fResult.intVal = execute(lop->getIntVal(row, isNull), rop->getIntVal(row, isNull), isNull); break; - case execplan::CalpontSystemCatalog::UBIGINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::USMALLINT: - case execplan::CalpontSystemCatalog::UTINYINT: - fResult.uintVal = execute(lop->getUintVal(row, isNull), rop->getUintVal(row, isNull), isNull); - break; case execplan::CalpontSystemCatalog::DOUBLE: case execplan::CalpontSystemCatalog::FLOAT: fResult.doubleVal = execute(lop->getDoubleVal(row, isNull), rop->getDoubleVal(row, isNull), isNull); break; case execplan::CalpontSystemCatalog::DECIMAL: - case execplan::CalpontSystemCatalog::UDECIMAL: execute (fResult.decimalVal, lop->getDecimalVal(row, isNull), rop->getDecimalVal(row, isNull), isNull); break; default: diff --git a/dbcon/execplan/blocksize.h b/dbcon/execplan/blocksize.h index f61cee5c..58c91db7 100644 --- a/dbcon/execplan/blocksize.h +++ b/dbcon/execplan/blocksize.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: blocksize.h 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: blocksize.h 8436 2012-04-04 18:18:21Z rdempsey $ #ifndef EXECPLAN_BLOCKSIZE_H_ #define EXECPLAN_BLOCKSIZE_H_ diff --git a/dbcon/execplan/calpontexecutionplan.cpp b/dbcon/execplan/calpontexecutionplan.cpp index d491cf42..e308875d 100644 --- a/dbcon/execplan/calpontexecutionplan.cpp +++ b/dbcon/execplan/calpontexecutionplan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontexecutionplan.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: calpontexecutionplan.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/calpontexecutionplan.h b/dbcon/execplan/calpontexecutionplan.h index 6fc99a0d..5d1662f8 100644 --- a/dbcon/execplan/calpontexecutionplan.h +++ b/dbcon/execplan/calpontexecutionplan.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontexecutionplan.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: calpontexecutionplan.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/calpontexecutionplanfactory.cpp b/dbcon/execplan/calpontexecutionplanfactory.cpp index a1c7521c..ee53a66a 100644 --- a/dbcon/execplan/calpontexecutionplanfactory.cpp +++ b/dbcon/execplan/calpontexecutionplanfactory.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontexecutionplanfactory.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: calpontexecutionplanfactory.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/calpontexecutionplanfactory.h b/dbcon/execplan/calpontexecutionplanfactory.h index 7a317e0a..3315062d 100644 --- a/dbcon/execplan/calpontexecutionplanfactory.h +++ b/dbcon/execplan/calpontexecutionplanfactory.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontexecutionplanfactory.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: calpontexecutionplanfactory.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/calpontselectexecutionplan.cpp b/dbcon/execplan/calpontselectexecutionplan.cpp index dd393d2d..4e0b5813 100644 --- a/dbcon/execplan/calpontselectexecutionplan.cpp +++ b/dbcon/execplan/calpontselectexecutionplan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontselectexecutionplan.cpp 9576 2013-05-29 21:02:11Z zzhu $ +* $Id: calpontselectexecutionplan.cpp 8777 2012-08-01 21:52:34Z zzhu $ * * ***********************************************************************/ @@ -24,8 +24,6 @@ #include using namespace std; -#include - #include "bytestream.h" using namespace messageqcpp; @@ -36,9 +34,6 @@ using namespace messageqcpp; #include "simplecolumn.h" #include "querystats.h" -#include "querytele.h" -using namespace querytele; - namespace { template struct deleter : public unary_function @@ -50,202 +45,173 @@ template struct deleter : public unary_function namespace execplan { - + /** Static */ CalpontSelectExecutionPlan::ColumnMap CalpontSelectExecutionPlan::fColMap; +string CalpontSelectExecutionPlan::fSchemaName; +string CalpontSelectExecutionPlan::fTableName; /** * Constructors/Destructors */ CalpontSelectExecutionPlan::CalpontSelectExecutionPlan(const int location): - fLocalQuery (GLOBAL_QUERY), - fFilters (0), - fHaving (0), - fLocation (location), - fDependent (false), - fTxnID(-1), - fTraceFlags(TRACE_NONE), - fStatementID(0), - fDistinct(false), - fOverrideLargeSideEstimate(false), - fDistinctUnionNum(0), - fSubType(MAIN_SELECT), - fLimitStart(0), - fLimitNum(-1), - fHasOrderBy(false), - fStringScanThreshold(ULONG_MAX), - fQueryType(SELECT), - fPriority(querystats::DEFAULT_USER_PRIORITY_LEVEL), - fStringTableThreshold(20), - fDJSSmallSideLimit(0), - fDJSLargeSideLimit(0), - fDJSPartitionSize(100 * 1024 * 1024), // 100MB mem usage for disk based join, - fUMMemLimit(numeric_limits::max()), - fIsDML(false) -{ - fUuid = QueryTeleClient::genUUID(); -} + fFilters (0), + fHaving (0), + fLocation (location), + fDependent (false), + fTraceFlags(TRACE_NONE), + fStatementID(0), + fDistinct(false), + fOverrideLargeSideEstimate(false), + fDistinctUnionNum(0), + fSubType(MAIN_SELECT), + fLimitStart(0), + fLimitNum(-1), + fHasOrderBy(false), + fStringScanThreshold(ULONG_MAX), + fQueryType(SELECT), + fPriority(querystats::DEFAULT_USER_PRIORITY_LEVEL) +{} CalpontSelectExecutionPlan::CalpontSelectExecutionPlan( const ReturnedColumnList& returnedCols, - ParseTree* filters, - const SelectList& subSelects, - const GroupByColumnList& groupByCols, - ParseTree* having, - const OrderByColumnList& orderByCols, - const string alias, - const int location, - const bool dependent) : - fLocalQuery (GLOBAL_QUERY), - fReturnedCols (returnedCols), - fFilters (filters), - fSubSelects (subSelects), - fGroupByCols (groupByCols), - fHaving (having), - fOrderByCols (orderByCols), - fTableAlias (alias), - fLocation (location), - fDependent (dependent), - fTxnID(-1), - fTraceFlags(TRACE_NONE), - fStatementID(0), - fDistinct(false), - fOverrideLargeSideEstimate(false), - fDistinctUnionNum(0), - fSubType(MAIN_SELECT), - fLimitStart(0), - fLimitNum(-1), - fHasOrderBy(false), - fStringScanThreshold(ULONG_MAX), - fQueryType(SELECT), - fPriority(querystats::DEFAULT_USER_PRIORITY_LEVEL), - fStringTableThreshold(20), - fDJSSmallSideLimit(0), - fDJSLargeSideLimit(0), - fDJSPartitionSize(100 * 1024 * 1024), // 100MB mem usage for disk based join - fUMMemLimit(numeric_limits::max()), - fIsDML(false) -{ - fUuid = QueryTeleClient::genUUID(); -} + ParseTree* filters, + const SelectList& subSelects, + const GroupByColumnList& groupByCols, + ParseTree* having, + const OrderByColumnList& orderByCols, + const string alias, + const int location, + const bool dependent) : + fReturnedCols (returnedCols), + fFilters (filters), + fSubSelects (subSelects), + fGroupByCols (groupByCols), + fHaving (having), + fOrderByCols (orderByCols), + fTableAlias (alias), + fLocation (location), + fDependent (dependent), + fTraceFlags(TRACE_NONE), + fStatementID(0), + fDistinct(false), + fOverrideLargeSideEstimate(false), + fDistinctUnionNum(0), + fSubType(MAIN_SELECT), + fLimitStart(0), + fLimitNum(-1), + fHasOrderBy(false), + fStringScanThreshold(ULONG_MAX), + fQueryType(SELECT), + fPriority(querystats::DEFAULT_USER_PRIORITY_LEVEL) +{} CalpontSelectExecutionPlan::CalpontSelectExecutionPlan (string data) : - fLocalQuery (GLOBAL_QUERY), - fData(data), - fTxnID(-1), - fTraceFlags(TRACE_NONE), - fStatementID(0), - fDistinct(false), - fOverrideLargeSideEstimate(false), - fDistinctUnionNum(0), - fSubType(MAIN_SELECT), - fLimitStart(0), - fLimitNum(-1), - fHasOrderBy(false), - fStringScanThreshold(ULONG_MAX), - fQueryType(SELECT), - fPriority(querystats::DEFAULT_USER_PRIORITY_LEVEL), - fStringTableThreshold(20), - fDJSSmallSideLimit(0), - fDJSLargeSideLimit(0), - fDJSPartitionSize(100 * 1024 * 1024), // 100MB mem usage for disk based join - fUMMemLimit(numeric_limits::max()), - fIsDML(false) -{ - fUuid = QueryTeleClient::genUUID(); -} + fData(data), + fTraceFlags(TRACE_NONE), + fStatementID(0), + fDistinct(false), + fOverrideLargeSideEstimate(false), + fDistinctUnionNum(0), + fSubType(MAIN_SELECT), + fLimitStart(0), + fLimitNum(-1), + fHasOrderBy(false), + fStringScanThreshold(ULONG_MAX), + fQueryType(SELECT), + fPriority(querystats::DEFAULT_USER_PRIORITY_LEVEL) +{ // TODO: big parsing +} CalpontSelectExecutionPlan::~CalpontSelectExecutionPlan() { if (fFilters != NULL) - delete fFilters; - if (fHaving != NULL) - delete fHaving; + delete fFilters; + if (fHaving != NULL) + delete fHaving; fFilters = NULL; fHaving = NULL; } - + /** * Methods */ void CalpontSelectExecutionPlan::filterTokenList( FilterTokenList& filterTokenList) { - fFilterTokenList = filterTokenList; - - Parser parser; - std::vector tokens; - Token t; - - for (unsigned int i = 0; i < filterTokenList.size(); i++) - { - t.value = filterTokenList[i]; - tokens.push_back(t); - } - if (tokens.size() > 0) - filters(parser.parse(tokens.begin(), tokens.end())); + fFilterTokenList = filterTokenList; + + Parser parser; + std::vector tokens; + Token t; + + for (unsigned int i = 0; i < filterTokenList.size(); i++) + { + t.value = filterTokenList[i]; + tokens.push_back(t); + } + if (tokens.size() > 0) + filters(parser.parse(tokens.begin(), tokens.end())); } void CalpontSelectExecutionPlan::havingTokenList( const FilterTokenList& havingTokenList) { - fHavingTokenList = havingTokenList; - - Parser parser; - std::vector tokens; - Token t; - - for (unsigned int i = 0; i < havingTokenList.size(); i++) - { - t.value = havingTokenList[i]; - tokens.push_back(t); - } - if (tokens.size() > 0) - having(parser.parse(tokens.begin(), tokens.end())); + fHavingTokenList = havingTokenList; + + Parser parser; + std::vector tokens; + Token t; + + for (unsigned int i = 0; i < havingTokenList.size(); i++) + { + t.value = havingTokenList[i]; + tokens.push_back(t); + } + if (tokens.size() > 0) + having(parser.parse(tokens.begin(), tokens.end())); } -string CalpontSelectExecutionPlan::toString() const +ostream &operator<< (ostream &output, const CalpontSelectExecutionPlan &cep) { - ostringstream output; - output << ">SELECT " ; - if (distinct()) + if (cep.distinct()) output << "DISTINCT "; - output << "limit: " << limitStart() << " - " << limitNum() << endl; - - switch (location()) + output << "limit: " << cep.limitStart() << " - " << cep.limitNum() << endl; + + switch (cep.location()) { case CalpontSelectExecutionPlan::MAIN: - output << "MAIN" << endl; - break; - case CalpontSelectExecutionPlan::FROM: - output << "FROM" << endl; - break; - case CalpontSelectExecutionPlan::WHERE: - output << "WHERE" << endl; - break; - case CalpontSelectExecutionPlan::HAVING: - output << "HAVING" << endl; - break; - } - + output << "MAIN" << endl; + break; + case CalpontSelectExecutionPlan::FROM: + output << "FROM" << endl; + break; + case CalpontSelectExecutionPlan::WHERE: + output << "WHERE" << endl; + break; + case CalpontSelectExecutionPlan::HAVING: + output << "HAVING" << endl; + break; + } + // Returned Column - CalpontSelectExecutionPlan::ReturnedColumnList retCols = returnedCols(); + CalpontSelectExecutionPlan::ReturnedColumnList retCols = cep.returnedCols(); output << ">>Returned Columns" << endl; - uint32_t seq = 0; + uint seq = 0; for (unsigned int i = 0; i < retCols.size(); i++) { output << *retCols[i] << endl; if (retCols[i]->colSource() & SELECT_SUB) { output << "select sub -- " << endl; - CalpontSelectExecutionPlan *plan = dynamic_cast(fSelectSubList[seq++].get()); + CalpontSelectExecutionPlan *plan = dynamic_cast(cep.fSelectSubList[seq++].get()); if (plan) - output << "{" << *plan << "}" << endl; + output << "{" << *plan << "}" << endl; } } - + // From Clause - CalpontSelectExecutionPlan::TableList tables = tableList(); + CalpontSelectExecutionPlan::TableList tables = cep.tableList(); output << ">>From Tables" << endl; seq = 0; for (unsigned int i = 0; i < tables.size(); i++) @@ -254,77 +220,69 @@ string CalpontSelectExecutionPlan::toString() const if (tables[i].schema.length() == 0 && tables[i].table.length() == 0) { output << "derived table - " << tables[i].alias << endl; - CalpontSelectExecutionPlan *plan = dynamic_cast(fDerivedTableList[seq++].get()); + CalpontSelectExecutionPlan *plan = dynamic_cast(cep.fDerivedTableList[seq++].get()); if (plan) - output << "{" << *plan << "}" << endl; + output << "{" << *plan << "}" << endl; } else { output << tables[i] << endl; } } - + // Filters output << ">>Filters" << endl; - if (filters() != 0) - filters()->walk (ParseTree::print, output); - else - output << "empty filter tree" << endl; - + if (cep.filters() != 0) + cep.filters()->walk (ParseTree::print, output); + else + output << "empty filter tree" << endl; + // Group by columns - const CalpontSelectExecutionPlan::GroupByColumnList& gbc = groupByCols(); - if (gbc.size() > 0) + CalpontSelectExecutionPlan::GroupByColumnList groupByCols = cep.groupByCols(); + if (groupByCols.size() > 0) { - output << ">>Group By Columns" << endl; - for (unsigned int i = 0; i < gbc.size(); i++) - output << *gbc[i] << endl; + output << ">>Group By Columns" << endl; + for (unsigned int i = 0; i < groupByCols.size(); i++) + output << *groupByCols[i] << endl; } - + // Having - if (having() != 0) + if (cep.having() != 0) { output << ">>Having" << endl; - having()->walk (ParseTree::print, output); + cep.having()->walk (ParseTree::print, output); } - + // Order by columns - const CalpontSelectExecutionPlan::OrderByColumnList& obc = orderByCols(); - if (obc.size() > 0) + CalpontSelectExecutionPlan::OrderByColumnList orderByCols = cep.orderByCols(); + if (orderByCols.size() > 0) { output << ">>Order By Columns" << endl; - for (unsigned int i = 0; i < obc.size(); i++) - output << *obc[i] << endl; - } - output << "SessionID: " << fSessionID << endl; - output << "TxnID: " << fTxnID << endl; - output << "VerID: " << fVerID << endl; - output << "TraceFlags: " << fTraceFlags << endl; - output << "StatementID: " << fStatementID << endl; - output << "DistUnionNum: " << (int)fDistinctUnionNum << endl; - output << "Limit: " << fLimitStart << " - " << fLimitNum << endl; - output << "String table threshold: " << fStringTableThreshold << endl; - + for (unsigned int i = 0; i < orderByCols.size(); i++) + output << *orderByCols[i] << endl; + } + output << "SessionID: " << cep.fSessionID << endl; + output << "TxnID: " << cep.fTxnID << endl; + output << "VerID: " << cep.fVerID << endl; + output << "TraceFlags: " << cep.fTraceFlags << endl; + output << "StatementID: " << cep.fStatementID << endl; + output << "DistUnionNum: " << (int)cep.fDistinctUnionNum << endl; + output << "Limit: " << cep.fLimitStart << " - " << cep.fLimitNum << endl; + output << "--- Column Map ---" << endl; CalpontSelectExecutionPlan::ColumnMap::const_iterator iter; - for (iter = columnMap().begin(); iter != columnMap().end(); iter++) + for (iter = cep.columnMap().begin(); iter != cep.columnMap().end(); iter++) output << (*iter).first << " : " << (*iter).second << endl; - output << "UUID: " << fUuid << endl; - output << "QueryType: " << queryType() << endl; - - if (!unionVec().empty()) - output << "\n--- Union Unit ---" << endl; - for (unsigned i = 0; i < unionVec().size(); i++) - { - CalpontSelectExecutionPlan *plan = - dynamic_cast(unionVec()[i].get()); - if (plan) - output << "{" << *plan << "}\n" << endl; - } + + return output; +} - return output.str(); +const std::string CalpontSelectExecutionPlan::queryType() const +{ + return queryTypeToString(fQueryType); } -string CalpontSelectExecutionPlan::queryTypeToString(const uint32_t queryType) +std::string CalpontSelectExecutionPlan::queryTypeToString(const uint queryType) { switch (queryType) { @@ -356,98 +314,89 @@ void CalpontSelectExecutionPlan::serialize(messageqcpp::ByteStream& b) const vector::const_iterator it; ColumnMap::const_iterator mapiter; TableList::const_iterator tit; - + b << static_cast(ObjectReader::CALPONTSELECTEXECUTIONPLAN); - - b << static_cast(fReturnedCols.size()); + + b << static_cast(fReturnedCols.size()); for (rcit = fReturnedCols.begin(); rcit != fReturnedCols.end(); ++rcit) (*rcit)->serialize(b); - - b << static_cast(fTableList.size()); + + b << static_cast(fTableList.size()); for (tit = fTableList.begin(); tit != fTableList.end(); ++tit) { (*tit).serialize(b); } ObjectReader::writeParseTree(fFilters, b); - - b << static_cast(fSubSelects.size()); - for (uint32_t i = 0; i < fSubSelects.size(); i++) + + b << static_cast(fSubSelects.size()); + for (uint i = 0; i < fSubSelects.size(); i++) fSubSelects[i]->serialize(b); - - b << static_cast(fGroupByCols.size()); + + b << static_cast(fGroupByCols.size()); for (rcit = fGroupByCols.begin(); rcit != fGroupByCols.end(); ++rcit) (*rcit)->serialize(b); - ObjectReader::writeParseTree(fHaving, b); - - b << static_cast(fOrderByCols.size()); + ObjectReader::writeParseTree(fHaving, b); + + b << static_cast(fOrderByCols.size()); for (rcit = fOrderByCols.begin(); rcit != fOrderByCols.end(); ++rcit) (*rcit)->serialize(b); - - b << static_cast(fColumnMap.size()); - for (mapiter = fColumnMap.begin(); mapiter != fColumnMap.end(); ++mapiter) - { - b << (*mapiter).first; - (*mapiter).second->serialize(b); - } - - b << static_cast(frmParms.size()); - for (RMParmVec::const_iterator it = frmParms.begin(); it != frmParms.end(); ++it) - { - b << it->sessionId; - b << it->id; + + b << static_cast(fColumnMap.size()); + for (mapiter = fColumnMap.begin(); mapiter != fColumnMap.end(); ++mapiter) + { + b << (*mapiter).first; + (*mapiter).second->serialize(b); + } + + b << static_cast(frmParms.size()); + for (RMParmVec::const_iterator it = frmParms.begin(); it != frmParms.end(); ++it) + { + b << it->sessionId; + b << it->id; b << it->value; - } - + } + b << fTableAlias; - b << static_cast(fLocation); - - b << static_cast< ByteStream::byte>(fDependent); - + b << static_cast(fLocation); + + b << static_cast< ByteStream::byte>(fDependent); + // ? not sure if this needs to be added b << fData; b << static_cast(fSessionID); b << static_cast(fTxnID); - b << fVerID; + b << static_cast(fVerID); b << fTraceFlags; b << fStatementID; - b << static_cast(fDistinct); + b << static_cast(fDistinct); b << static_cast(fOverrideLargeSideEstimate); - + // for union b << (uint8_t)fDistinctUnionNum; b << (uint32_t)fUnionVec.size(); - for (uint32_t i = 0; i < fUnionVec.size(); i++) + for (uint i = 0; i < fUnionVec.size(); i++) fUnionVec[i]->serialize(b); - + b << (uint64_t)fSubType; - + // for FROM subquery b << static_cast(fDerivedTableList.size()); - for (uint32_t i = 0; i < fDerivedTableList.size(); i++) + for (uint i = 0; i < fDerivedTableList.size(); i++) fDerivedTableList[i]->serialize(b); - + b << (uint64_t)fLimitStart; b << (uint64_t)fLimitNum; b << static_cast(fHasOrderBy); - + b << static_cast(fSelectSubList.size()); - for (uint32_t i = 0; i < fSelectSubList.size(); i++) + for (uint i = 0; i < fSelectSubList.size(); i++) fSelectSubList[i]->serialize(b); b << (uint64_t)fStringScanThreshold; b << (uint32_t)fQueryType; b << fPriority; - b << fStringTableThreshold; - b << fSchemaName; - b << fLocalQuery; - b << fUuid; - b << fDJSSmallSideLimit; - b << fDJSLargeSideLimit; - b << fDJSPartitionSize; - b << fUMMemLimit; - b << (uint8_t) fIsDML; } void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) @@ -455,22 +404,21 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) ReturnedColumn *rc; CalpontExecutionPlan *cep; string colName; - uint8_t tmp8; - + ObjectReader::checkType(b, ObjectReader::CALPONTSELECTEXECUTIONPLAN); - + // erase elements, otherwise vectors contain null pointers fReturnedCols.clear(); fSubSelects.clear(); fGroupByCols.clear(); fOrderByCols.clear(); fTableList.clear(); - fColumnMap.clear(); - fUnionVec.clear(); + fColumnMap.clear(); + fUnionVec.clear(); frmParms.clear(); fDerivedTableList.clear(); fSelectSubList.clear(); - + if (fFilters != 0) { delete fFilters; fFilters = 0; @@ -489,7 +437,7 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) SRCP srcp(rc); fReturnedCols.push_back(srcp); } - + b >> size; CalpontSystemCatalog::TableAliasName tan; for (i = 0; i < size; i++) @@ -497,31 +445,31 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) tan.unserialize(b); fTableList.push_back(tan); } - + fFilters = ObjectReader::createParseTree(b); - + b >> size; for (i = 0; i < size; i++) { cep = ObjectReader::createExecutionPlan(b); fSubSelects.push_back(SCEP(cep)); } - + b >> size; for (i = 0; i < size; i++) { rc = dynamic_cast(ObjectReader::createTreeNode(b)); SRCP srcp(rc); fGroupByCols.push_back(srcp); } - - fHaving = ObjectReader::createParseTree(b); - + + fHaving = ObjectReader::createParseTree(b); + b >> size; for (i = 0; i < size; i++) { rc = dynamic_cast(ObjectReader::createTreeNode(b)); SRCP srcp(rc); fOrderByCols.push_back(srcp); } - + b >> size; for (i = 0; i < size; i++) { b >> colName; @@ -540,23 +488,23 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) b >> memory; frmParms.push_back(RMParam(sessionId, id, memory)); } - + b >> fTableAlias; - b >> reinterpret_cast(fLocation); - b >> reinterpret_cast< ByteStream::byte&>(fDependent); - + b >> reinterpret_cast(fLocation); + b >> reinterpret_cast< ByteStream::byte&>(fDependent); + // ? not sure if this needs to be added b >> fData; b >> reinterpret_cast(fSessionID); b >> reinterpret_cast(fTxnID); - b >> fVerID; + b >> reinterpret_cast(fVerID); b >> fTraceFlags; b >> fStatementID; - b >> reinterpret_cast< ByteStream::byte&>(fDistinct); + b >> reinterpret_cast< ByteStream::byte&>(fDistinct); uint8_t val; b >> reinterpret_cast(val); fOverrideLargeSideEstimate = (val != 0); - + // for union b >> (uint8_t&)(fDistinctUnionNum); b >> size; @@ -566,7 +514,7 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) fUnionVec.push_back(SCEP(cep)); } b >> (uint64_t&)fSubType; - + // for FROM subquery b >> size; for (i = 0; i < size; i++) @@ -574,10 +522,10 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) cep = ObjectReader::createExecutionPlan(b); fDerivedTableList.push_back(SCEP(cep)); } - + b >> (uint64_t&)fLimitStart; b >> (uint64_t&)fLimitNum; - b >> reinterpret_cast< ByteStream::byte&>(fHasOrderBy); + b >> reinterpret_cast< ByteStream::byte&>(fHasOrderBy); // for SELECT subquery b >> size; @@ -590,16 +538,6 @@ void CalpontSelectExecutionPlan::unserialize(messageqcpp::ByteStream& b) b >> (uint64_t&)fStringScanThreshold; b >> (uint32_t&)fQueryType; b >> fPriority; - b >> fStringTableThreshold; - b >> fSchemaName; - b >> fLocalQuery; - b >> fUuid; - b >> fDJSSmallSideLimit; - b >> fDJSLargeSideLimit; - b >> fDJSPartitionSize; - b >> fUMMemLimit; - b >> tmp8; - fIsDML = tmp8; } bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) const @@ -607,13 +545,13 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) // If we use this outside the serialization tests, we should // reorder these comparisons to speed up the common case - + ReturnedColumnList::const_iterator rcit; ReturnedColumnList::const_iterator rcit2; vector::const_iterator it, it2; SelectList::const_iterator sit, sit2; ColumnMap::const_iterator map_it, map_it2; - + //fReturnedCols if (fReturnedCols.size() != t.fReturnedCols.size()) return false; @@ -621,7 +559,7 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) rcit != fReturnedCols.end(); ++rcit, ++rcit2) if (**rcit != **rcit2) return false; - + //fFilters if (fFilters != NULL && t.fFilters != NULL) { if (*fFilters != *t.fFilters) @@ -629,7 +567,7 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) } else if (fFilters != NULL || t.fFilters != NULL) return false; - + //fSubSelects if (fSubSelects.size() != t.fSubSelects.size()) return false; @@ -637,7 +575,7 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) sit != fSubSelects.end(); ++sit, ++sit2) if (*((*sit).get()) != (*sit2).get()) return false; - + //fGroupByCols if (fGroupByCols.size() != t.fGroupByCols.size()) return false; @@ -645,15 +583,15 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) rcit != fGroupByCols.end(); ++rcit, ++rcit2) if (**rcit != **rcit2) return false; - + //fHaving if (fHaving != NULL && t.fHaving != NULL) { if (*fHaving != *t.fHaving) return false; } else if (fHaving != NULL || t.fHaving != NULL) - return false; - + return false; + //fOrderByCols if (fOrderByCols.size() != t.fOrderByCols.size()) return false; @@ -661,7 +599,7 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) rcit != fOrderByCols.end(); ++rcit, ++rcit2) if (**rcit != **rcit2) return false; - + //fColumnMap if (fColumnMap.size() != t.fColumnMap.size()) return false; @@ -669,7 +607,7 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) map_it != fColumnMap.end(); ++map_it, ++map_it2) if (*(map_it->second) != *(map_it2->second)) return false; - + if (fTableAlias != t.fTableAlias) return false; if (fLocation != t.fLocation) @@ -684,16 +622,6 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) return false; if (fPriority != t.fPriority) return false; - if (fStringTableThreshold != t.fStringTableThreshold) - return false; - if (fDJSSmallSideLimit != t.fDJSSmallSideLimit) - return false; - if (fDJSLargeSideLimit != t.fDJSLargeSideLimit) - return false; - if (fDJSPartitionSize != t.fDJSPartitionSize) - return false; - if (fUMMemLimit != t.fUMMemLimit) - return false; return true; } @@ -701,7 +629,7 @@ bool CalpontSelectExecutionPlan::operator==(const CalpontSelectExecutionPlan& t) bool CalpontSelectExecutionPlan::operator==(const CalpontExecutionPlan* t) const { const CalpontSelectExecutionPlan *ac; - + ac = dynamic_cast(t); if (ac == NULL) return false; @@ -736,7 +664,7 @@ void CalpontSelectExecutionPlan::rmParms (const RMParmVec& parms) frmParms.clear(); frmParms.assign(parms.begin(), parms.end()); -} +} } // namespace execplan diff --git a/dbcon/execplan/calpontselectexecutionplan.h b/dbcon/execplan/calpontselectexecutionplan.h index f77d5c0f..f5e8174e 100644 --- a/dbcon/execplan/calpontselectexecutionplan.h +++ b/dbcon/execplan/calpontselectexecutionplan.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: calpontselectexecutionplan.h 9576 2013-05-29 21:02:11Z zzhu $ +* $Id: calpontselectexecutionplan.h 8731 2012-07-23 18:47:07Z pleblanc $ * * ***********************************************************************/ @@ -28,15 +28,12 @@ #include #include -#include - #include "exp_templates.h" #include "calpontexecutionplan.h" #include "returnedcolumn.h" #include "filter.h" #include "expressionparser.h" #include "calpontsystemcatalog.h" -#include "brmtypes.h" #ifndef __GNUC__ # ifndef __attribute__ @@ -47,7 +44,7 @@ /** * Namespace */ -namespace execplan { +namespace execplan { enum RM_PARMS { @@ -64,8 +61,6 @@ struct RMParam uint64_t value; }; -typedef boost::shared_ptr SCSEP; - /** * @brief A class to represent calpont select execution plan * @@ -74,6 +69,11 @@ typedef boost::shared_ptr SCSEP; */ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { +/** + * Overloaded stream operator + */ +friend std::ostream &operator<< (std::ostream &, const CalpontSelectExecutionPlan &); + /** * Public stuff */ @@ -92,8 +92,8 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { typedef std::vector SelectList; typedef std::vector RMParmVec; - - // query type of this select plan. + + // query type of this select plan. #undef DELETE //Windows defines this... enum IDB_QUERYTYPE { @@ -107,7 +107,7 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { INSERT, LOAD_DATA_INFILE }; - + enum SE_LOCATION { MAIN, @@ -115,17 +115,17 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { WHERE, HAVING }; - + /** subselect type */ - enum SE_SubSelectType + enum SE_SubSelectType { - MAIN_SELECT, + MAIN_SELECT, SINGLEROW_SUBS, EXISTS_SUBS, - NOT_EXISTS_SUBS, - IN_SUBS, + NOT_EXISTS_SUBS, + IN_SUBS, NOT_IN_SUBS, - ALL_SUBS, + ALL_SUBS, ANY_SUBS, FROM_SUBS, SELECT_SUBS, @@ -155,18 +155,11 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { TRACE_TUPLE_OFF = 0x8000, /*!< Enable MySQL table interface */ }; - enum IDB_LOCAL_QUERY - { - GLOBAL_QUERY = 0, /*!< Standard processing */ - LOCAL_QUERY = 1, /*!< Use local ExeMgr and local PrimProc */ - LOCAL_UM = 2, /*!< Use local ExeMgr with global PrimProc*/ - }; - /** * Constructors */ - CalpontSelectExecutionPlan(const int location = MAIN); - + CalpontSelectExecutionPlan(const int location = MAIN); + CalpontSelectExecutionPlan(const ReturnedColumnList& returnedCols, ParseTree* filters, const SelectList& subSelects, @@ -178,16 +171,16 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { const bool dependent); CalpontSelectExecutionPlan (const std::string data); - + /** * Destructors */ virtual ~CalpontSelectExecutionPlan(); - + /** * Access and mutator methods */ - + /** * returned column list */ @@ -196,12 +189,6 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { void returnedCols (const ReturnedColumnList& returnedCols) { fReturnedCols = returnedCols; } - /** - * Are we in local PM only query mode? - */ - const uint32_t localQuery() const { return fLocalQuery; } - void localQuery (const uint32_t localQuery) { fLocalQuery = localQuery; } - /** * filters parse tree */ @@ -216,69 +203,69 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { */ //const FilterTokenList& filterTokenList() const { return fFilterTokenList;} void filterTokenList (FilterTokenList& filterTokenList); - + /** * sub select list */ - const SelectList& subSelects() const { return fSubSelects; } + const SelectList& subSelects() const { return fSubSelects; } void subSelects (const SelectList& subSelects){ fSubSelects = subSelects; } - + /** * group by column list */ - const GroupByColumnList& groupByCols() const { return fGroupByCols; } - GroupByColumnList& groupByCols() { return fGroupByCols; } - void groupByCols( const GroupByColumnList& groupByCols) + const GroupByColumnList& groupByCols() const { return fGroupByCols; } + GroupByColumnList& groupByCols() { return fGroupByCols; } + void groupByCols( const GroupByColumnList& groupByCols) { fGroupByCols = groupByCols; } - + /** * order by column list */ - const OrderByColumnList& orderByCols() const { return fOrderByCols; } - OrderByColumnList& orderByCols() { return fOrderByCols; } + const OrderByColumnList& orderByCols() const { return fOrderByCols; } + OrderByColumnList& orderByCols() { return fOrderByCols; } void orderByCols( const OrderByColumnList& orderByCols) { fOrderByCols = orderByCols; } - + /** * table alias */ - const std::string& tableAlias() const { return fTableAlias; } + const std::string& tableAlias() const { return fTableAlias; } void tableAlias (const std::string& tableAlias) { fTableAlias = tableAlias; } - + /** * location of this select */ const int location () const { return fLocation; } void location (const int location) { fLocation = location; } - + /** - * dependence of this select + * depentence of this select */ const bool dependent() const { return fDependent; } void dependent (const bool dependent) { fDependent = dependent; } - + /** * having filter parse tree */ inline const ParseTree* having() const { return fHaving; } inline ParseTree* having() { return fHaving; } - inline void having (ParseTree* having) { fHaving = having; } - + inline void having (ParseTree* having) { fHaving = having; } + /** having filter token list * Set filter list field and build filters tree from the filter list * This is an alternative way to build filter tree. Hide the parser * from the user - */ + */ const FilterTokenList& havingTokenList() const { return fHavingTokenList; } void havingTokenList (const FilterTokenList& havingTokenList); - + /** column map * all the columns appeared on query */ const ColumnMap& columnMap() const {return fColumnMap;} - + /** assign the static fColMap to non-static fColumnMap. map-wise copy */ - void columnMap (const ColumnMap& columnMap); + void columnMap (const ColumnMap& columnMap); /** assign a regular map object to non-static fColumnMap. pure assignment */ // @note this is to fix memory leak in CSC, becasue no static map is needed there. @@ -289,32 +276,32 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { */ const std::string data() const { return fData; } void data ( const std::string data ) { fData = data; } - + /** session id * */ const uint32_t sessionID() const { return fSessionID; } void sessionID ( const uint32_t sessionID ) { fSessionID = sessionID; } - + /** transaction id * */ const int txnID() const { return fTxnID; } void txnID ( const int txnID ) { fTxnID = txnID; } - + /** version id * */ - const BRM::QueryContext verID() const { return fVerID; } - void verID ( const BRM::QueryContext verID ) { fVerID = verID; } - + const CalpontSystemCatalog::SCN verID() const { return fVerID; } + void verID ( const CalpontSystemCatalog::SCN verID ) { fVerID = verID; } + inline static ColumnMap& colMap() {return fColMap;} - - inline std::string& schemaName() { return fSchemaName; } - inline void schemaName(const std::string& schemaName) { fSchemaName = schemaName; } - - inline std::string& tableName() { return fTableName; } - inline void tableName(const std::string& tableName) { fTableName = tableName; } + + inline static std::string& schemaName() { return fSchemaName; } + inline static void schemaName(const std::string& schemaName) { fSchemaName = schemaName; } + + inline static std::string& tableName() { return fTableName; } + inline static void tableName(const std::string& tableName) { fTableName = tableName; } inline void traceOn(bool traceOn) __attribute__((deprecated)) { if (traceOn) fTraceFlags |= TRACE_LOG; else fTraceFlags &= ~TRACE_LOG; } @@ -327,79 +314,55 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { void statementID (const uint32_t statementID) {fStatementID = statementID;} const RMParmVec& rmParms() { return frmParms; } - void rmParms (const RMParmVec& parms); - + void rmParms (const RMParmVec& parms); + const TableList& tableList() const { return fTableList; } void tableList (const TableList& tableList) { fTableList = tableList; } - + const SelectList& derivedTableList() const { return fDerivedTableList; } void derivedTableList(SelectList& derivedTableList) { fDerivedTableList = derivedTableList; } - + const bool distinct() const {return fDistinct;} void distinct(const bool distinct) {fDistinct = distinct;} - + void overrideLargeSideEstimate (const bool over) {fOverrideLargeSideEstimate = over;} const bool overrideLargeSideEstimate() const { return fOverrideLargeSideEstimate; } - + void unionVec(const SelectList& unionVec) { fUnionVec = unionVec; } const SelectList& unionVec() const { return fUnionVec; } SelectList& unionVec() { return fUnionVec; } - + void distinctUnionNum(const uint8_t distinctUnionNum) { fDistinctUnionNum = distinctUnionNum; } const uint8_t distinctUnionNum() const { return fDistinctUnionNum; } - + void subType(const uint64_t subType) { fSubType = subType; } const uint64_t subType() const { return fSubType; } - + void derivedTbAlias(const std::string derivedTbAlias) { fDerivedTbAlias = derivedTbAlias; } const std::string derivedTbAlias() const { return fDerivedTbAlias; } - + void limitStart(const uint64_t limitStart) { fLimitStart = limitStart; } const uint64_t limitStart() const { return fLimitStart; } - + void limitNum(const uint64_t limitNum) { fLimitNum = limitNum; } const uint64_t limitNum() const { return fLimitNum; } - + void hasOrderBy(const bool hasOrderBy) { fHasOrderBy = hasOrderBy; } const bool hasOrderBy() const { return fHasOrderBy; } - + void selectSubList(const SelectList& selectSubList) { fSelectSubList = selectSubList; } const SelectList& selectSubList() const { return fSelectSubList; } - - void subSelectList(const std::vector& subSelectList) { fSubSelectList = subSelectList; } - const std::vector& subSelectList() const { return fSubSelectList; } - + void stringScanThreshold(uint64_t n) { fStringScanThreshold = n; } uint64_t stringScanThreshold() const { return fStringScanThreshold; } - + // query type. return string for easy stats insert - void queryType(const uint32_t queryType) { fQueryType = queryType; } - const std::string queryType() const { return queryTypeToString(fQueryType); } - static std::string queryTypeToString(const uint32_t queryType); - - void priority(uint32_t p) { fPriority = p; } - uint32_t priority() const { return fPriority; } - - void stringTableThreshold(uint32_t t) { fStringTableThreshold = t; } - uint32_t stringTableThreshold() const { return fStringTableThreshold; } - - void uuid(const boost::uuids::uuid& uuid) { fUuid = uuid; } - const boost::uuids::uuid& uuid() const { return fUuid; } - - void djsSmallSideLimit(uint64_t l) { fDJSSmallSideLimit = l; } - uint64_t djsSmallSideLimit() { return fDJSSmallSideLimit; } - - void djsLargeSideLimit(uint64_t l) { fDJSLargeSideLimit = l; } - uint64_t djsLargeSideLimit() { return fDJSLargeSideLimit; } - - void djsPartitionSize(uint64_t l) { fDJSPartitionSize = l; } - uint64_t djsPartitionSize() { return fDJSPartitionSize; } - - void umMemLimit(uint64_t l) { fUMMemLimit = l; } - int64_t umMemLimit() { return fUMMemLimit; } - - void isDML(bool b) { fIsDML = b; } - bool isDML() { return fIsDML; } + void queryType(const uint queryType) { fQueryType = queryType; } + const std::string queryType() const; + static std::string queryTypeToString(const uint queryType); + + void priority(uint p) { fPriority = p; } + uint priority() { return fPriority; } /** * The serialization interface @@ -409,28 +372,28 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { */ virtual void serialize(messageqcpp::ByteStream&) const; virtual void unserialize(messageqcpp::ByteStream&); - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const CalpontExecutionPlan* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const CalpontSelectExecutionPlan& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const CalpontExecutionPlan* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. @@ -438,21 +401,6 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { */ virtual bool operator!=(const CalpontSelectExecutionPlan& t) const; - /** @brief Return a string rep of the CSEP - * - * Return a string rep of the CSEP - * @return a string - */ - virtual std::string toString() const; - - /** @brief Is this an internal query? - * - * Is this an internal query (a syscat query performed on behalf of another query) - * FIXME: add a setter and make this work for really big session ids - * @return true/false - */ - virtual bool isInternal() const { return ((fSessionID & 0x80000000) != 0); } - /** * Protected stuff */ @@ -461,7 +409,7 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { * Fields */ /** - * + * */ /** * Constructors @@ -476,12 +424,7 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { * Private stuff */ private: - - /** - * If set, then the local PM only option is turned on - */ - uint32_t fLocalQuery; - + /** * A list of ReturnedColumn objects */ @@ -509,7 +452,7 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { /** * A list of group by columns */ - GroupByColumnList fGroupByCols; + GroupByColumnList fGroupByCols; /** * A tree of having clause condition associated with group by clause */ @@ -517,11 +460,11 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { /** * A list of order by columns */ - OrderByColumnList fOrderByCols; + OrderByColumnList fOrderByCols; /** * Table or alias name for subselect in FROM clause */ - std::string fTableAlias; + std::string fTableAlias; /** * An enum indicating the location of this select statement in the enclosing select statement */ @@ -530,20 +473,19 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { * A flag indicating if this sub-select is dependent on the enclosing query or is constant */ bool fDependent; - - /** + + /** * SQL representation of this execution plan */ std::string fData; static ColumnMap fColMap; // for getplan to use. class-wise map ColumnMap fColumnMap; // for ExeMgr to use. not shared between objects - + uint32_t fSessionID; int fTxnID; // SQLEngine only needs the ID value - BRM::QueryContext fVerID; - // @bug5316. remove static - std::string fSchemaName; - std::string fTableName; + CalpontSystemCatalog::SCN fVerID; + static std::string fSchemaName; /// @bug #393. table access schema and table name + static std::string fTableName; /// @bug #393 uint32_t fTraceFlags; /** @@ -554,56 +496,38 @@ class CalpontSelectExecutionPlan : public CalpontExecutionPlan { RMParmVec frmParms; TableList fTableList; SelectList fDerivedTableList; - + bool fDistinct; bool fOverrideLargeSideEstimate; - + // for union SelectList fUnionVec; uint8_t fDistinctUnionNum; - + // for subselect uint64_t fSubType; std::string fDerivedTbAlias; - + // for limit uint64_t fLimitStart; uint64_t fLimitNum; - + // for parent select order by bool fHasOrderBy; - + // for Select clause subquery SelectList fSelectSubList; // @bug3321, for string scan blocks uint64_t fStringScanThreshold; - + // query type - uint32_t fQueryType; - - uint32_t fPriority; - uint32_t fStringTableThreshold; - - // Derived table involved in the query. For derived table optimization - std::vector fSubSelectList; + uint fQueryType; - boost::uuids::uuid fUuid; - - /* Disk-based join vars */ - uint64_t fDJSSmallSideLimit; - uint64_t fDJSLargeSideLimit; - uint64_t fDJSPartitionSize; - int64_t fUMMemLimit; - bool fIsDML; + uint fPriority; }; -/** - * Output stream operator - */ - -inline std::ostream& operator<<(std::ostream& os, const CalpontSelectExecutionPlan& rhs) - { os << rhs.toString(); return os; } +typedef boost::shared_ptr SCSEP; } #endif //CALPONTSELECTEXECUTIONPLAN_H diff --git a/dbcon/execplan/calpontsystemcatalog.cpp b/dbcon/execplan/calpontsystemcatalog.cpp index 8c400e11..dbbc61e1 100644 --- a/dbcon/execplan/calpontsystemcatalog.cpp +++ b/dbcon/execplan/calpontsystemcatalog.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: calpontsystemcatalog.cpp 9594 2013-06-04 18:19:21Z pleblanc $ + * $Id: calpontsystemcatalog.cpp 8993 2012-10-16 15:59:46Z wweeks $ * * ***********************************************************************/ @@ -154,30 +154,6 @@ const string colDataTypeToString(CalpontSystemCatalog::ColDataType cdt) case CalpontSystemCatalog::BLOB: return "blob"; break; - case CalpontSystemCatalog::UTINYINT: - return "utinyint"; - break; - case CalpontSystemCatalog::USMALLINT: - return "usmallint"; - break; - case CalpontSystemCatalog::UDECIMAL: - return "udecimal"; - break; - case CalpontSystemCatalog::UMEDINT: - return "umedint"; - break; - case CalpontSystemCatalog::UINT: - return "uint32_t"; - break; - case CalpontSystemCatalog::UFLOAT: - return "ufloat"; - break; - case CalpontSystemCatalog::UBIGINT: - return "ubigint"; - break; - case CalpontSystemCatalog::UDOUBLE: - return "udouble"; - break; default: break; } @@ -275,13 +251,6 @@ bool CalpontSystemCatalog::TableColName::operator<(const TableColName& rhs) cons return false; } -const string CalpontSystemCatalog::TableColName::toString() const -{ - string os; - os = schema + '.' + table + '.' + column; - return os; -} - bool CalpontSystemCatalog::TableName::operator<(const TableName& rhs) const { if (schema < rhs.schema) @@ -299,14 +268,6 @@ bool CalpontSystemCatalog::TableName::operator<(const TableName& rhs) const return false; } -void CalpontSystemCatalog::TableAliasName::clear() -{ - schema.clear(); - table.clear(); - alias.clear(); - view.clear(); -} - bool CalpontSystemCatalog::TableAliasName::operator<(const TableAliasName& rhs) const { if (schema < rhs.schema) @@ -625,12 +586,12 @@ void CalpontSystemCatalog::getSysData (CalpontSelectExecutionPlan& csep, txnID.valid = true; } - BRM::QueryContext verID, oldVerID; + CalpontSystemCatalog::SCN verID, oldVerID; verID = fSessionManager->verID(); oldTxnID = csep.txnID(); csep.txnID(txnID.id); oldVerID = csep.verID(); - csep.verID(verID); + csep.verID(verID); //We need to use a session ID that's separate from the actual query SID, because the dbcon runs queries // in the middle of receiving data bands for the real query. //TODO: we really need a flag or something to identify this as a syscat query: there are assumptions made @@ -708,7 +669,7 @@ void CalpontSystemCatalog::getSysData_EC(CalpontSelectExecutionPlan& csep, uint32_t tableOID = IDB_VTABLE_ID; ByteStream bs; - uint32_t status; + uint status; ResourceManager rm(true); DistributedEngineComm* fEc = DistributedEngineComm::instance(rm); @@ -741,16 +702,11 @@ void CalpontSystemCatalog::getSysData_EC(CalpontSelectExecutionPlan& csep, TupleJobList* tjlp = dynamic_cast(jl.get()); idbassert(tjlp); RowGroup rowGroup = tjlp->getOutputRowGroup(); - RGData rgData; while (true) { bs.restart(); - uint32_t rowCount = jl->projectTable(tableOID, bs); - - // XXXST: take out the 'true' when all jobsteps have been made st-compatible. - rgData.deserialize(bs, true); - rowGroup.setData(&rgData); - //rowGroup.setData(const_cast(bs.buf())); + uint rowCount = jl->projectTable(tableOID, bs); + rowGroup.setData(const_cast(bs.buf())); if ((status = rowGroup.getStatus()) != 0) { if (status >= 1000) // new error system @@ -797,7 +753,6 @@ void CalpontSystemCatalog::getSysData_FE(const CalpontSelectExecutionPlan& csep, bs << qb; fExeMgr->write(bs); boost::scoped_ptr rowGroup; - RGData rgData; msg.restart(); bs.restart(); @@ -843,16 +798,13 @@ void CalpontSystemCatalog::getSysData_FE(const CalpontSelectExecutionPlan& csep, } else { - // XXXST - rgData.deserialize(bs, true); - rowGroup->setData(&rgData); - //rowGroup->setData(const_cast(bs.buf())); + rowGroup->setData(const_cast(bs.buf())); } if ((status = rowGroup->getStatus()) != 0) { if (status >= 1000) // new error system { - //bs.advance(rowGroup->getDataSize()); + bs.advance(rowGroup->getDataSize()); bs >> emsgStr; throw IDBExcept(emsgStr, rowGroup->getStatus()); } else @@ -891,9 +843,7 @@ const CalpontSystemCatalog::ColType CalpontSystemCatalog::colType(const OID& Oid { Colinfomap::const_iterator iter = fColinfomap.find(Oid); if (iter != fColinfomap.end()) - { return iter->second; - } } lk3.unlock(); @@ -993,7 +943,7 @@ const CalpontSystemCatalog::ColType CalpontSystemCatalog::colType(const OID& Oid // Filters SimpleFilter *f1 = new SimpleFilter (opeq, col[1]->clone(), - new ConstantColumn((int64_t)Oid, ConstantColumn::NUM)); + new ConstantColumn(Oid, ConstantColumn::NUM)); filterTokenList.push_back(f1); csep.filterTokenList(filterTokenList); @@ -1073,6 +1023,7 @@ const CalpontSystemCatalog::ColType CalpontSystemCatalog::colType(const OID& Oid ct.columnOID = Oid; } + // populate colinfomap cache and oidbitmap lk3.lock(); boost::mutex::scoped_lock lk2(fOIDmapLock); @@ -1139,7 +1090,7 @@ const CalpontSystemCatalog::ColType CalpontSystemCatalog::colTypeDct(const OID& // Filters SimpleFilter *f1 = new SimpleFilter (opeq, col[1]->clone(), - new ConstantColumn((int64_t)dictOid, ConstantColumn::NUM)); + new ConstantColumn(dictOid, ConstantColumn::NUM)); filterTokenList.push_back(f1); csep.filterTokenList(filterTokenList); @@ -1208,7 +1159,7 @@ const CalpontSystemCatalog::TableColName CalpontSystemCatalog::colName(const OID SimpleColumn *c2 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+SCHEMA_COL, fSessionID); SimpleColumn *c3 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+TABLENAME_COL, fSessionID); SimpleColumn *c4 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+COLNAME_COL, fSessionID); - + SRCP srcp; srcp.reset(c1); colMap.insert(CMVT_(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+OBJECTID_COL, srcp)); @@ -1239,9 +1190,8 @@ const CalpontSystemCatalog::TableColName CalpontSystemCatalog::colName(const OID // Filters SimpleFilter *f1 = new SimpleFilter (opeq, c1->clone(), - new ConstantColumn((int64_t)oid, ConstantColumn::NUM)); + new ConstantColumn(oid, ConstantColumn::NUM)); filterTokenList.push_back(f1); - csep.filterTokenList(filterTokenList); ostringstream oss; @@ -1275,90 +1225,8 @@ const CalpontSystemCatalog::TableColName CalpontSystemCatalog::colName(const OID return tableColName; } -const CalpontSystemCatalog::TableColName CalpontSystemCatalog::dictColName(const OID& oid) -{ - if (oid >= 3000) - DEBUG << "Enter dictColName: " << oid; - - TableColName tableColName; - - // invalid oid - if (oid < 1000) - return tableColName; - - //Check whether cache needs to be flushed - if ( oid >= 3000) { - checkSysCatVer(); - } - - // SQL statement: select schema, tablename, columnname from syscolumn where dictobjectid = oid; - CalpontSelectExecutionPlan csep; - CalpontSelectExecutionPlan::ReturnedColumnList returnedColumnList; - CalpontSelectExecutionPlan::FilterTokenList filterTokenList; - CalpontSelectExecutionPlan::ColumnMap colMap; - - SimpleColumn *c1 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+DICTOID_COL, fSessionID); - SimpleColumn *c2 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+SCHEMA_COL, fSessionID); - SimpleColumn *c3 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+TABLENAME_COL, fSessionID); - SimpleColumn *c4 = new SimpleColumn(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+COLNAME_COL, fSessionID); - - SRCP srcp; - srcp.reset(c1); - colMap.insert(CMVT_(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+DICTOID_COL, srcp)); - srcp.reset(c2); - colMap.insert(CMVT_(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+SCHEMA_COL, srcp)); - srcp.reset(c3); - colMap.insert(CMVT_(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+TABLENAME_COL, srcp)); - srcp.reset(c4); - colMap.insert(CMVT_(CALPONT_SCHEMA+"."+SYSCOLUMN_TABLE+"."+COLNAME_COL, srcp)); - csep.columnMapNonStatic(colMap); - - srcp.reset(c2->clone()); - returnedColumnList.push_back(srcp); - srcp.reset(c3->clone()); - returnedColumnList.push_back(srcp); - srcp.reset(c4->clone()); - returnedColumnList.push_back(srcp); - csep.returnedCols(returnedColumnList); - - OID oid2 = DICTOID_SYSCOLUMN_SCHEMA; - OID oid3 = DICTOID_SYSCOLUMN_TABLENAME; - OID oid4 = DICTOID_SYSCOLUMN_COLNAME; - - // Filters - SimpleFilter *f1 = new SimpleFilter (opeq, - c1->clone(), - new ConstantColumn((int64_t)oid, ConstantColumn::NUM)); - filterTokenList.push_back(f1); - - csep.filterTokenList(filterTokenList); - - ostringstream oss; - oss << "select schema,tablename,columnname from syscolumn where dictobjectid=" << oid << - " --colName/"; - if (fIdentity == EC) oss << "EC"; - else oss << "FE"; - csep.data(oss.str()); - NJLSysDataList sysDataList; - getSysData (csep, sysDataList, SYSCOLUMN_TABLE); - - vector::const_iterator it; - for (it = sysDataList.begin(); it != sysDataList.end(); it++) - { - if ((*it)->ColumnOID() == oid2) - tableColName.schema = (*it)->GetStringData(0); - else if ((*it)->ColumnOID() == oid3) - tableColName.table = (*it)->GetStringData(0); - else if ((*it)->ColumnOID() == oid4) - tableColName.column = (*it)->GetStringData(0); - } - if (oid > 3000) - DEBUG << "|" << tableColName.schema << "|" << tableColName.table << "|" << tableColName.column << endl; - - return tableColName; -} -const uint64_t CalpontSystemCatalog::nextAutoIncrValue ( TableName aTableName) +const int64_t CalpontSystemCatalog::nextAutoIncrValue ( TableName aTableName) { transform( aTableName.schema.begin(), aTableName.schema.end(), aTableName.schema.begin(), to_lower() ); transform( aTableName.table.begin(), aTableName.table.end(), aTableName.table.begin(), to_lower() ); @@ -1369,11 +1237,11 @@ const uint64_t CalpontSystemCatalog::nextAutoIncrValue ( TableName aTableName) } catch (runtime_error& /*ex*/) { - throw; + return -2; } if (tbInfo.tablewithautoincr == NO_AUTOINCRCOL) - return AUTOINCR_SATURATED; + return 0; //Build a plan to get current nextvalue: select nextvalue from syscolumn where schema = tableName.schema and tablename = tableName.table and autoincrement='y'; CalpontSelectExecutionPlan csep; @@ -1433,7 +1301,6 @@ const uint64_t CalpontSystemCatalog::nextAutoIncrValue ( TableName aTableName) if (fIdentity == EC) oss << "EC"; else oss << "FE"; csep.data(oss.str()); - NJLSysDataList sysDataList; try { getSysData(csep, sysDataList, SYSCOLUMN_TABLE); @@ -1442,14 +1309,14 @@ const uint64_t CalpontSystemCatalog::nextAutoIncrValue ( TableName aTableName) { throw runtime_error ( e.what() ); } - uint64_t nextVal = AUTOINCR_SATURATED; + int64_t nextVal = 0; vector::const_iterator it; for (it = sysDataList.begin(); it != sysDataList.end(); it++) { if ((*it)->ColumnOID() == oid[3]) { - nextVal = static_cast(((*it)->GetData(0))); + nextVal = ((*it)->GetData(0)); } } @@ -1588,7 +1455,7 @@ const CalpontSystemCatalog::ROPair CalpontSystemCatalog::nextAutoIncrRid ( const // Filters SimpleFilter *f1 = new SimpleFilter (opeq, col[0]->clone(), - new ConstantColumn((int64_t)columnoid, ConstantColumn::LITERAL)); + new ConstantColumn(columnoid, ConstantColumn::LITERAL)); filterTokenList.push_back(f1); csep.filterTokenList(filterTokenList); @@ -1638,7 +1505,7 @@ const CalpontSystemCatalog::SCN CalpontSystemCatalog::scn(void) const #endif /* static */ -boost::shared_ptr CalpontSystemCatalog::makeCalpontSystemCatalog(uint32_t sessionID) +boost::shared_ptr CalpontSystemCatalog::makeCalpontSystemCatalog(u_int32_t sessionID) { boost::mutex::scoped_lock lock(map_mutex); boost::shared_ptr instance; @@ -1680,7 +1547,7 @@ boost::shared_ptr CalpontSystemCatalog::makeCalpontSystemC } /* static */ -void CalpontSystemCatalog::removeCalpontSystemCatalog(uint32_t sessionID) +void CalpontSystemCatalog::removeCalpontSystemCatalog(u_int32_t sessionID) { boost::mutex::scoped_lock lock(map_mutex); DEBUG << "remove calpont system catalog for session " << sessionID << endl; @@ -1744,7 +1611,7 @@ CalpontSystemCatalog::CalpontSystemCatalog(): buildSysOIDmap(); buildSysTablemap(); buildSysDctmap(); - fSyscatSCN = fSessionManager->sysCatVerID().currentScn; + fSyscatSCN = fSessionManager->sysCatVerID(); } CalpontSystemCatalog::~CalpontSystemCatalog() @@ -3064,7 +2931,7 @@ const CalpontSystemCatalog::TableName CalpontSystemCatalog::tableName(const OID& // Filters SimpleFilter *f1 = new SimpleFilter (opeq, c1->clone(), - new ConstantColumn((int64_t)tableoid, ConstantColumn::NUM)); + new ConstantColumn(tableoid, ConstantColumn::NUM)); filterTokenList.push_back(f1); csep.filterTokenList(filterTokenList); @@ -3195,8 +3062,6 @@ const CalpontSystemCatalog::ROPair CalpontSystemCatalog::tableRID(const TableNam ostringstream oss; oss << "select objectid from systable where schema='" << aTableName.schema << "' and tablename='" << aTableName.table << "' --tableRID/"; - - csep.data(oss.str()); //@bug 6078. Log the statement if (fIdentity == EC) oss << "EC"; else oss << "FE"; NJLSysDataList sysDataList; @@ -5158,7 +5023,7 @@ void CalpontSystemCatalog::getSchemaInfo(const string& in_schema) // populate colinfo cache //boost::mutex::scoped_lock lk3(fColinfomapLock); - for (uint32_t i = 0; i < ctList.size(); i++) + for (uint i = 0; i < ctList.size(); i++) fColinfomap[ctList[i].columnOID] = ctList[i]; //lk3.unlock(); // populate tbinfomap @@ -5198,7 +5063,7 @@ ostream& operator<<(ostream& os, const CalpontSystemCatalog::TableAliasName& rhs ostream& operator<<(ostream& os, const CalpontSystemCatalog::TableColName& rhs) { - os << rhs.toString(); + os << rhs.schema << '.' << rhs.table << '.' << rhs.column; return os; } @@ -5226,7 +5091,7 @@ void CalpontSystemCatalog::flushCache() buildSysDctmap(); lk4.unlock(); - fSyscatSCN = fSessionManager->sysCatVerID().currentScn; + fSyscatSCN = fSessionManager->sysCatVerID(); //cout << "Cache flushed and current sysCatVerID is " << newScn << endl; } @@ -5252,11 +5117,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.scale = 0; aCol.precision = 10; aCol.compressionType = 0; - - ResourceManager rm; - if( rm.useHdfs() ) - aCol.compressionType = 2; - DictOID notDict; // @bug 4433 - Increase object width from 64 to 128 for schema names, table names, and column names. @@ -5266,7 +5126,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSTABLE_TABLENAME; aCol.ddn.listOID = LISTOID_SYSTABLE_TABLENAME; aCol.ddn.treeOID = TREEOID_SYSTABLE_TABLENAME; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition = 0; aCol.columnOID = OID_SYSTABLE_TABLENAME; fColinfomap[aCol.columnOID] = aCol; @@ -5277,7 +5136,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSTABLE_SCHEMA; aCol.ddn.listOID = LISTOID_SYSTABLE_SCHEMA; aCol.ddn.treeOID = TREEOID_SYSTABLE_SCHEMA; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition++; aCol.columnOID = OID_SYSTABLE_SCHEMA; fColinfomap[aCol.columnOID] = aCol; @@ -5362,7 +5220,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSCOLUMN_SCHEMA; aCol.ddn.listOID = LISTOID_SYSCOLUMN_SCHEMA; aCol.ddn.treeOID = TREEOID_SYSCOLUMN_SCHEMA; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition = 0; aCol.columnOID = OID_SYSCOLUMN_SCHEMA; fColinfomap[aCol.columnOID] = aCol; @@ -5373,7 +5230,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSCOLUMN_TABLENAME; aCol.ddn.listOID = LISTOID_SYSCOLUMN_TABLENAME; aCol.ddn.treeOID = TREEOID_SYSCOLUMN_TABLENAME; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition++; aCol.columnOID = OID_SYSCOLUMN_TABLENAME; fColinfomap[aCol.columnOID] = aCol; @@ -5384,7 +5240,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSCOLUMN_COLNAME; aCol.ddn.listOID = LISTOID_SYSCOLUMN_COLNAME; aCol.ddn.treeOID = TREEOID_SYSCOLUMN_COLNAME; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition++; aCol.columnOID = OID_SYSCOLUMN_COLNAME; fColinfomap[aCol.columnOID] = aCol; @@ -5459,7 +5314,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSCOLUMN_DEFAULTVAL; aCol.ddn.listOID = LISTOID_SYSCOLUMN_DEFAULTVAL; aCol.ddn.treeOID = TREEOID_SYSCOLUMN_DEFAULTVAL; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition++; aCol.columnOID = OID_SYSCOLUMN_DEFAULTVAL; fColinfomap[aCol.columnOID] = aCol; @@ -5518,7 +5372,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSCOLUMN_MINVALUE; aCol.ddn.listOID = LISTOID_SYSCOLUMN_MINVALUE; aCol.ddn.treeOID = TREEOID_SYSCOLUMN_MINVALUE; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition++; aCol.columnOID = OID_SYSCOLUMN_MINVALUE; fColinfomap[aCol.columnOID] = aCol; @@ -5529,7 +5382,6 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.ddn.dictOID = DICTOID_SYSCOLUMN_MAXVALUE; aCol.ddn.listOID = LISTOID_SYSCOLUMN_MAXVALUE; aCol.ddn.treeOID = TREEOID_SYSCOLUMN_MAXVALUE; - aCol.ddn.compressionType = aCol.compressionType; aCol.colPosition++; aCol.columnOID = OID_SYSCOLUMN_MAXVALUE; fColinfomap[aCol.columnOID] = aCol; @@ -5544,7 +5396,7 @@ void CalpontSystemCatalog::buildSysColinfomap() aCol.colWidth = 8; aCol.constraintType = NOTNULL_CONSTRAINT; - aCol.colDataType = UBIGINT; + aCol.colDataType = BIGINT; aCol.ddn = notDict; aCol.colPosition++; aCol.columnOID = OID_SYSCOLUMN_NEXTVALUE; @@ -5609,11 +5461,11 @@ void CalpontSystemCatalog::buildSysDctmap() void CalpontSystemCatalog::checkSysCatVer() { - SCN newScn = fSessionManager->sysCatVerID().currentScn; + SCN newScn = fSessionManager->sysCatVerID(); if (newScn < 0) { fSessionManager.reset(new SessionManager()); - newScn = fSessionManager->sysCatVerID().currentScn; + newScn = fSessionManager->sysCatVerID(); } boost::mutex::scoped_lock sysCatLk(fSyscatSCNLock); if ( fSyscatSCN != newScn ) { diff --git a/dbcon/execplan/calpontsystemcatalog.h b/dbcon/execplan/calpontsystemcatalog.h index 2e90b9cf..8305595d 100644 --- a/dbcon/execplan/calpontsystemcatalog.h +++ b/dbcon/execplan/calpontsystemcatalog.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: calpontsystemcatalog.h 9474 2013-05-02 15:28:09Z rdempsey $ + * $Id: calpontsystemcatalog.h 9056 2012-11-06 20:15:42Z rdempsey $ * * ***********************************************************************/ @@ -36,54 +36,18 @@ #include #include #include -#include #include "we_typeext.h" #include "columnresult.h" #include "bytestream.h" -#include "joblisttypes.h" -#include "stdexcept" #undef min #undef max -#ifdef _MSC_VER -#define __attribute__(x) -#endif - -namespace -{ - const int64_t MIN_TINYINT __attribute__ ((unused)) = std::numeric_limits::min()+2; //-126; - const int64_t MAX_TINYINT __attribute__ ((unused)) = std::numeric_limits::max(); //127; - const int64_t MIN_SMALLINT __attribute__ ((unused)) = std::numeric_limits::min()+2; //-32766; - const int64_t MAX_SMALLINT __attribute__ ((unused)) = std::numeric_limits::max(); //32767; - const int64_t MIN_INT __attribute__ ((unused)) = std::numeric_limits::min()+2; //-2147483646; - const int64_t MAX_INT __attribute__ ((unused)) = std::numeric_limits::max(); //2147483647; - const int64_t MIN_BIGINT __attribute__ ((unused)) = std::numeric_limits::min()+2; //-9223372036854775806LL; - const int64_t MAX_BIGINT __attribute__ ((unused)) = std::numeric_limits::max(); //9223372036854775807 - - const uint64_t MIN_UINT __attribute__ ((unused)) = 0; - const uint64_t MIN_UTINYINT __attribute__ ((unused)) = 0; - const uint64_t MIN_USMALLINT __attribute__ ((unused)) = 0; - const uint64_t MIN_UBIGINT __attribute__ ((unused)) = 0; - const uint64_t MAX_UINT __attribute__ ((unused)) = std::numeric_limits::max()-2; //4294967293 - const uint64_t MAX_UTINYINT __attribute__ ((unused)) = std::numeric_limits::max()-2; //253; - const uint64_t MAX_USMALLINT __attribute__ ((unused)) = std::numeric_limits::max()-2; //65533; - const uint64_t MAX_UBIGINT __attribute__ ((unused)) = std::numeric_limits::max()-2; //18446744073709551613 - - const float MAX_FLOAT __attribute__ ((unused)) = std::numeric_limits::max(); //3.402823466385289e+38 - const float MIN_FLOAT __attribute__ ((unused)) = -std::numeric_limits::max(); - const double MAX_DOUBLE __attribute__ ((unused)) = std::numeric_limits::max(); //1.7976931348623157e+308 - const double MIN_DOUBLE __attribute__ ((unused)) = -std::numeric_limits::max(); - - - const uint64_t AUTOINCR_SATURATED __attribute__ ((unused)) = std::numeric_limits::max(); -} - class ExecPlanTest; namespace messageqcpp { - class MessageQueueClient; + class MessageQueueClient; } // This is now set in the calpont xml file @@ -107,60 +71,51 @@ const int32_t IDB_VTABLE_ID=CNX_VTABLE_ID; class CalpontSystemCatalog { public: - - /** static calpontsystemcatalog instance map. one instance per session - * TODO: should be one per transaction - */ - typedef std::map > CatalogMap; - - /** Server Identity - * - */ - enum Identity { EC = 0, FE }; - - /** the set of Calpont column widths - * - */ - enum ColWidth { ONE_BIT, ONE_BYTE, TWO_BYTE, THREE_BYTE, FOUR_BYTE, FIVE_BYTE, SIX_BYTE, SEVEN_BYTE, EIGHT_BYTE }; - - /** the set of Calpont column data types - * - */ - enum ColDataType - { - BIT, /*!< BIT type */ - TINYINT, /*!< TINYINT type */ - CHAR, /*!< CHAR type */ - SMALLINT, /*!< SMALLINT type */ - DECIMAL, /*!< DECIMAL type */ - MEDINT, /*!< MEDINT type */ - INT, /*!< INT type */ - FLOAT, /*!< FLOAT type */ - DATE, /*!< DATE type */ - BIGINT, /*!< BIGINT type */ - DOUBLE, /*!< DOUBLE type */ - DATETIME, /*!< DATETIME type */ - VARCHAR, /*!< VARCHAR type */ - VARBINARY, /*!< VARBINARY type */ - CLOB, /*!< CLOB type */ - BLOB, /*!< BLOB type */ - UTINYINT, /*!< Unsigned TINYINT type */ - USMALLINT, /*!< Unsigned SMALLINT type */ - UDECIMAL, /*!< Unsigned DECIMAL type */ - UMEDINT, /*!< Unsigned MEDINT type */ - UINT, /*!< Unsigned INT type */ - UFLOAT, /*!< Unsigned FLOAT type */ - UBIGINT, /*!< Unsigned BIGINT type */ - UDOUBLE, /*!< Unsigned DOUBLE type */ - NUM_OF_COL_DATA_TYPE, - LONGDOUBLE, /* @bug3241, dev and variance calculation only */ - STRINT /* @bug3532, string as int for fast comparison */ - }; - - /** the set of column constraint types - * - */ - enum ConstraintType + + /** static calpontsystemcatalog instance map. one instance per session + * TODO: should be one per transaction + */ + typedef std::map > CatalogMap; + + /** Server Identity + * + */ + enum Identity { EC = 0, FE }; + + /** the set of Calpont column widths + * + */ + enum ColWidth { ONE_BIT, ONE_BYTE, TWO_BYTE, THREE_BYTE, FOUR_BYTE, FIVE_BYTE, SIX_BYTE, SEVEN_BYTE, EIGHT_BYTE }; + + /** the set of Calpont column data types + * + */ + enum ColDataType + { + BIT=WriteEngine::BIT, /*!< BIT type */ + TINYINT=WriteEngine::TINYINT, /*!< TINYINT type */ + CHAR=WriteEngine::CHAR, /*!< CHAR type */ + SMALLINT=WriteEngine::SMALLINT, /*!< SMALLINT type */ + DECIMAL=WriteEngine::DECIMAL, /*!< DECIMAL type */ + MEDINT=WriteEngine::MEDINT, /*!< MEDINT type */ + INT=WriteEngine::INT, /*!< INT type */ + FLOAT=WriteEngine::FLOAT, /*!< FLOAT type */ + DATE=WriteEngine::DATE, /*!< DATE type */ + BIGINT=WriteEngine::BIGINT, /*!< BIGINT type */ + DOUBLE=WriteEngine::DOUBLE, /*!< DOUBLE type */ + DATETIME=WriteEngine::DATETIME, /*!< DATETIME type */ + VARCHAR=WriteEngine::VARCHAR, /*!< VARCHAR type */ + VARBINARY=WriteEngine::VARBINARY, /*!< VARBINARY type */ + CLOB=WriteEngine::CLOB, /*!< CLOB type */ + BLOB=WriteEngine::BLOB, /*!< BLOB type */ + LONGDOUBLE, /* @bug3241, dev and variance calculation only */ + STRINT /* @bug3532, string as int for fast comparison */ + }; + + /** the set of column constraint types + * + */ + enum ConstraintType { NO_CONSTRAINT, UNIQUE_CONSTRAINT, @@ -170,67 +125,65 @@ class CalpontSystemCatalog REFERENCE_CONSTRAINT, DEFAULT_CONSTRAINT }; - + enum CompressionType { NO_COMPRESSION, COMPRESSION1, COMPRESSION2 }; - + enum AutoincrColumn { NO_AUTOINCRCOL, AUTOINCRCOL }; - - /** the type of an object number - * - * @todo TODO: OIDs aren't really signed. This should be fixed. - */ - typedef int32_t OID; - - /** @brief a structure to hold a dictionary's - * object ids - */ - struct DictOID - { - DictOID() : dictOID(0), listOID(0), treeOID(0), compressionType(0) { } - OID dictOID; - OID listOID; - OID treeOID; + + /** the type of an object number + * + * @todo TODO: OIDs aren't really signed. This should be fixed. + */ + typedef int32_t OID; + + /** @brief a structure to hold a dictionary's + * object ids + */ + struct DictOID + { + DictOID() : dictOID(0), listOID(0), treeOID(0), compressionType(0) { } + OID dictOID; + OID listOID; + OID treeOID; int compressionType; - bool operator==(const DictOID& t) const - { - if (dictOID != t.dictOID) - return false; - if (listOID != t.listOID) - return false; - if (treeOID != t.treeOID) - return false; + bool operator==(const DictOID& t) const + { + if (dictOID != t.dictOID) + return false; + if (listOID != t.listOID) + return false; + if (treeOID != t.treeOID) + return false; if (compressionType != t.compressionType) return false; - return true; - } - bool operator!=(const DictOID& t) const - { - return !(*this == t); - } - }; - - /** the type of a list of ColumnResult as returned from getSysData - */ - typedef std::vector NJLSysDataVector; - struct NJLSysDataList - { - // If we used an unorderedmap, we might improve performance. - // Maybe. - NJLSysDataVector sysDataVec; - NJLSysDataList(){}; - ~NJLSysDataList(); - NJLSysDataVector::const_iterator begin() const {return sysDataVec.begin();} - NJLSysDataVector::const_iterator end() const {return sysDataVec.end();} - void push_back(ColumnResult* cr) {sysDataVec.push_back(cr);} + return true; + } + bool operator!=(const DictOID& t) const + { + return !(*this == t); + } + }; + + /** the type of a list of ColumnResult as returned from getSysData + */ + typedef std::vector NJLSysDataVector; + struct NJLSysDataList + { + NJLSysDataVector sysDataVec; + NJLSysDataList(){}; + ~NJLSysDataList(); + NJLSysDataVector::const_iterator begin() const {return sysDataVec.begin();} + NJLSysDataVector::const_iterator end() const {return sysDataVec.end();} + void push_back(ColumnResult* cr) {sysDataVec.push_back(cr);} NJLSysDataVector::size_type size() const {return sysDataVec.size();} NJLSysDataVector::size_type findColumn(const OID& columnOID) const { @@ -239,34 +192,34 @@ class CalpontSystemCatalog return i; return -1; } - }; - - /** the type of a list of dictionary OIDs - */ - typedef std::vector DictOIDList; - - /** the structure returned by colType - * - * defaultValue is only meaningful when constraintType == DEFAULT_CONSTRAINT - */ - struct ColType - { - ColType() : colWidth(0), constraintType(NO_CONSTRAINT), colDataType(MEDINT), defaultValue(""), colPosition(-1), scale(0), precision(-1), compressionType(NO_COMPRESSION), columnOID(0), + }; + + /** the type of a list of dictionary OIDs + */ + typedef std::vector DictOIDList; + + /** the structure returned by colType + * + * defaultValue is only meaningful when constraintType == DEFAULT_CONSTRAINT + */ + struct ColType + { + ColType() : colWidth(0), constraintType(NO_CONSTRAINT), colDataType(MEDINT), defaultValue(""), colPosition(-1), scale(0), precision(-1), compressionType(NO_COMPRESSION), columnOID(0), autoincrement(0), nextvalue(0){ } - int32_t colWidth; - ConstraintType constraintType; - ColDataType colDataType; - DictOID ddn; - std::string defaultValue; - int32_t colPosition; // temporally put here. may need to have ColInfo struct later - int32_t scale; //number after decimal points - int32_t precision; + int32_t colWidth; + ConstraintType constraintType; + ColDataType colDataType; + DictOID ddn; + std::string defaultValue; + int32_t colPosition; // temporally put here. may need to have ColInfo struct later + int32_t scale; //number after decimal points + int32_t precision; int32_t compressionType; - OID columnOID; - bool autoincrement; //set to true if SYSCOLUMN autoincrement is �y� - uint64_t nextvalue; //next autoincrement value - - ColType(const ColType& rhs) + OID columnOID; + bool autoincrement; //set to true if SYSCOLUMN autoincrement is �y� + int64_t nextvalue; //next autoincrement value + + ColType(const ColType& rhs) { colWidth = rhs.colWidth; constraintType = rhs.constraintType; @@ -280,28 +233,26 @@ class CalpontSystemCatalog columnOID = rhs.columnOID; autoincrement = rhs.autoincrement; nextvalue = rhs.nextvalue; - - } - // for F&E use. only serialize necessary info for now - void serialize (messageqcpp::ByteStream& b) const - { - b << (uint32_t)colDataType; - b << (uint32_t)colWidth; - b << (uint32_t)scale; - b << (uint32_t)precision; - b << (uint32_t)compressionType; - } - - void unserialize (messageqcpp::ByteStream& b) - { - uint32_t val; - b >> (uint32_t&)val; - colDataType = (ColDataType)val; - b >> (uint32_t&)colWidth; - b >> (uint32_t&)scale; - b >> (uint32_t&)precision; - b >> (uint32_t&)compressionType; + } + // for F&E use. only serialize necessary info for now + void serialize (messageqcpp::ByteStream& b) const + { + b << (uint32_t)colDataType; + b << (uint32_t)colWidth; + b << (uint32_t)scale; + b << (uint32_t)precision; + } + + void unserialize (messageqcpp::ByteStream& b) + { + uint32_t val; + b >> (uint32_t&)val; + colDataType = (ColDataType)val; + b >> (uint32_t&)colWidth; + b >> (uint32_t&)scale; + b >> (uint32_t&)precision; + } const std::string toString() const; @@ -331,551 +282,537 @@ class CalpontSystemCatalog return !(*this == t); } - }; - - /** the structure of a table infomation - * - * this structure holds table related info. More in the future - */ - struct TableInfo - { - TableInfo() : numOfCols(0), tablewithautoincr(NO_AUTOINCRCOL) { } - int numOfCols; - int tablewithautoincr; - }; - - /** the type of a Row ID - * - * @todo TODO: RIDs aren't really signed. This should be fixed. - */ - //@bug 1866 match RID to writeengine, uint64_t - typedef WriteEngine::RID RID; - - /** - * - */ - - /** the type of a pair - * - * @todo TODO: the rid field in this structure does not make sense. the structure is equalivent - * to OID and therefore will be deprecated soon. - */ - //@bug 1866 changed rid default to 0; RID matches writeengine rid, uint64_t - struct ROPair - { - ROPair() : rid(std::numeric_limits::max()), objnum(0) { } - RID rid; - OID objnum; - }; - - /** the type of a list of Object ID's - * - * @todo TODO: the rid field in this structure does not make sense. the structure is equalivent - * to OID and therefore will be deprecated soon. - */ - typedef std::vector RIDList; - - /** the type of a pair - * - */ - struct IndexOID - { - OID objnum; - OID listOID; - bool multiColFlag; - }; + }; + + /** the structure of a table infomation + * + * this structure holds table related info. More in the future + */ + struct TableInfo + { + TableInfo() : numOfCols(0), tablewithautoincr(NO_AUTOINCRCOL) { } + int numOfCols; + int tablewithautoincr; + }; + + /** the type of a Row ID + * + * @todo TODO: RIDs aren't really signed. This should be fixed. + */ +//@bug 1866 match RID to writeengine, uint64_t + typedef WriteEngine::RID RID; + + /** + * + */ + + /** the type of a pair + * + * @todo TODO: the rid field in this structure does not make sense. the structure is equalivent + * to OID and therefore will be deprecated soon. + */ +//@bug 1866 changed rid default to 0; RID matches writeengine rid, uint64_t + struct ROPair + { + ROPair() : rid(std::numeric_limits::max()), objnum(0) { } + RID rid; + OID objnum; + }; + + /** the type of a list of Object ID's + * + * @todo TODO: the rid field in this structure does not make sense. the structure is equalivent + * to OID and therefore will be deprecated soon. + */ + typedef std::vector RIDList; + + /** the type of a pair + * + */ + struct IndexOID + { + OID objnum; + OID listOID; + bool multiColFlag; + }; /** the type of a list of Index OIDs - */ - typedef std::vector IndexOIDList; - - /** the structure for libcalmysql to use. Alias is taken account to the identity of tables. - * - */ - struct TableAliasName - { - TableAliasName ():fIsInfiniDB (true) {} - TableAliasName (std::string sch, std::string tb, std::string al) : - schema (sch), table (tb), alias (al), fIsInfiniDB(true) {} - TableAliasName (std::string sch, std::string tb, std::string al, std::string v) : - schema (sch), table (tb), alias (al), view(v), fIsInfiniDB(true) {} - std::string schema; - std::string table; - std::string alias; - std::string view; - bool fIsInfiniDB; - void clear(); - bool operator<(const TableAliasName& rhs) const; - bool operator>=(const TableAliasName& rhs) const { return !(*this < rhs); } - bool operator==(const TableAliasName& rhs) const - { return (schema == rhs.schema && - table == rhs.table && - alias == rhs.alias && - view == rhs.view && - fIsInfiniDB == rhs.fIsInfiniDB); } - bool operator!=(const TableAliasName& rhs) const { return !(*this == rhs); } - void serialize(messageqcpp::ByteStream&) const; - void unserialize(messageqcpp::ByteStream&); - friend std::ostream& operator<<(std::ostream& os, const TableAliasName& rhs); - }; - - /** the structure passed into various RID methods - * - */ - struct TableName - { - TableName() {} - TableName(std::string sch, std::string tb) : - schema(sch), table(tb) {} - TableName(const TableAliasName& tan): schema(tan.schema), table(tan.table) {} - std::string schema; - std::string table; - bool operator<(const TableName& rhs) const; - bool operator>=(const TableName& rhs) const { return !(*this < rhs); } - bool operator==(const TableName& rhs) const - { return (schema == rhs.schema && table == rhs.table); } - bool operator!=(const TableName& rhs) const { return !(*this == rhs); } + */ + typedef std::vector IndexOIDList; + + /** the structure for libcalmysql to use. Alias is taken account to the identity of tables. + * + */ + struct TableAliasName + { + TableAliasName ():fIsInfiniDB (true) {} + TableAliasName (std::string sch, std::string tb, std::string al) : + schema (sch), table (tb), alias (al), fIsInfiniDB(true) {} + std::string schema; + std::string table; + std::string alias; + std::string view; + bool fIsInfiniDB; + bool operator<(const TableAliasName& rhs) const; + bool operator>=(const TableAliasName& rhs) const { return !(*this < rhs); } + bool operator==(const TableAliasName& rhs) const + { return (schema == rhs.schema && + table == rhs.table && + alias == rhs.alias && + view == rhs.view && + fIsInfiniDB == rhs.fIsInfiniDB); } + bool operator!=(const TableAliasName& rhs) const { return !(*this == rhs); } + void serialize(messageqcpp::ByteStream&) const; + void unserialize(messageqcpp::ByteStream&); + friend std::ostream& operator<<(std::ostream& os, const TableAliasName& rhs); + }; + + /** the structure passed into various RID methods + * + */ + struct TableName + { + TableName() {} + TableName(std::string sch, std::string tb) : + schema(sch), table(tb) {} + TableName(const TableAliasName& tan): schema(tan.schema), table(tan.table) {} + std::string schema; + std::string table; + bool operator<(const TableName& rhs) const; + bool operator>=(const TableName& rhs) const { return !(*this < rhs); } + bool operator==(const TableName& rhs) const + { return (schema == rhs.schema && table == rhs.table); } + bool operator!=(const TableName& rhs) const { return !(*this == rhs); } const std::string toString() const; - friend std::ostream& operator<<(std::ostream& os, const TableName& rhs) + friend std::ostream& operator<<(std::ostream& os, const TableName& rhs) { os << rhs.toString(); return os; } - }; - - /** the structure passed into get RID for Index values - * - */ - struct IndexName - { - std::string schema; - std::string table; - std::string index; - bool multiColFlag; - bool operator<(const IndexName& rhs) const; - }; - - /** the structure of a constraint infomation */ - struct ConstraintInfo - { - ConstraintInfo():constraintType(NO_CONSTRAINT){} - int constraintType; - IndexName constraintName; - std::string constraintText; - std::string referenceSchema; // for foreign key constraint - std::string referenceTable; // for foreign key constraint - std::string referencePKName; // for foreign key constraint - std::string constraintStatus; - }; - - /** the structure passed into lookupOID - * - */ - struct TableColName - { - std::string schema; - std::string table; - std::string column; - bool operator<(const TableColName& rhs) const; - const std::string toString() const; - friend std::ostream& operator<<(std::ostream& os, const TableColName& rhs); - }; + }; + + /** the structure passed into get RID for Index values + * + */ + struct IndexName + { + std::string schema; + std::string table; + std::string index; + bool multiColFlag; + bool operator<(const IndexName& rhs) const; + }; + + /** the structure of a constraint infomation */ + struct ConstraintInfo + { + ConstraintInfo():constraintType(NO_CONSTRAINT){} + int constraintType; + IndexName constraintName; + std::string constraintText; + std::string referenceSchema; // for foreign key constraint + std::string referenceTable; // for foreign key constraint + std::string referencePKName; // for foreign key constraint + std::string constraintStatus; + }; + + /** the structure passed into lookupOID + * + */ + struct TableColName + { + std::string schema; + std::string table; + std::string column; + bool operator<(const TableColName& rhs) const; + friend std::ostream& operator<<(std::ostream& os, const TableColName& rhs); + }; typedef std::vector IndexNameList; typedef std::vector TableColNameList; - /** the type of a System Change Number - * - */ - typedef int SCN; - - /** the type of an index number - * - */ - typedef int INDNUM; - - /** the type returned by makeCalpontSystemCatalog() - * - */ - typedef boost::shared_ptr SPCSC; - - /** looks up a column's OID in the System Catalog - * - * For a unique table_name.column_name return the internal OID - */ - const OID lookupOID(const TableColName& tableColName); - - /** returns the column type attribute(s) for a column - * - * return the various column attributes for a given OID - */ - const ColType colType(const OID& oid); - - /** returns the column type attribute(s) for a column gived a dictionary OID - * - * return the same thing as colType does for the corresponding token OID - */ - const ColType colTypeDct(const OID& dictOid); - - /** returns the table column name for a column - * - * return the table column name for a given OID: - */ - const TableColName colName(const OID& oid); - /** returns the table column name for a dictionary column - * - * return the table column name for a given OID: - */ - const TableColName dictColName(const OID& oid); - + /** the type of a System Change Number + * + */ + typedef int SCN; + + /** the type of an index number + * + */ + typedef int INDNUM; + + /** looks up a column's OID in the System Catalog + * + * For a unique table_name.column_name return the internal OID + */ + const OID lookupOID(const TableColName& tableColName); + + /** returns the column type attribute(s) for a column + * + * return the various column attributes for a given OID + */ + const ColType colType(const OID& oid); + + /** returns the column type attribute(s) for a column gived a dictionary OID + * + * return the same thing as colType does for the corresponding token OID + */ + const ColType colTypeDct(const OID& dictOid); + + /** returns the table column name for a column + * + * return the table column name for a given OID: + */ + const TableColName colName(const OID& oid); + /** returns the next value of autoincrement for the table - * - * return the next value of autoincrement for a given table: - * AUTOINCR_SATURATED: limit exceeded + * + * return the next value of autoincrement for a given table: + * -2: No such table found + * <0: exceed limit * 0: Autoincrement does not exist for this table - * Throws runtime_error if no such table found - */ - const uint64_t nextAutoIncrValue ( TableName tableName); + */ + const int64_t nextAutoIncrValue ( TableName tableName); /** returns the rid of next autoincrement value for the table oid - * - * return the rid of next value of autoincrement for a given table: - */ - const ROPair nextAutoIncrRid ( const OID& oid); + * + * return the ird of next value of autoincrement for a given table: + */ + const ROPair nextAutoIncrRid ( const OID& oid); /** returns the oid of autoincrement column for the table - * - * return the oid of autoincrement column for a given table: - */ + * + * return the oid of autoincrement column for a given table: + */ int32_t autoColumOid(TableName tableName); - - /** returns the columns bitmap file object number - * - * return the bitmap file object number for a given OID: - */ - const OID colBitmap(const OID& oid) const; - - /** return the current SCN - * - * returns the current System Change Number (for versioning support) - */ - const SCN scn(void) const; - - /** return the RID's of the indexes for a table - * - * returns a list of the RID's of the indexes for a table - */ - const RIDList indexRIDs(const TableName& tableName); + + /** returns the columns bitmap file object number + * + * return the bitmap file object number for a given OID: + */ + const OID colBitmap(const OID& oid) const; + + /** return the current SCN + * + * returns the current System Change Number (for versioning support) + */ + const SCN scn(void) const; + + /** return the RID's of the indexes for a table + * + * returns a list of the RID's of the indexes for a table + */ + const RIDList indexRIDs(const TableName& tableName); /** return the total number of columns for a table - * - * returns the total number of columns for a table - */ - const int colNumbers(const TableName& tableName); - - /** return the RID's of the colindexes for a table - * - * returns a list of the RID's of the colindexes for a table - */ - const RIDList indexColRIDs(const TableName& tableName); - - /** return the RID's of the index columns (SYSINDEXCOL) for a index - * - * returns a list of the RID's of the colindexes for a index - */ - const RIDList indexColRIDs(const IndexName& indexName); - - /** return the RID's of the constraints for a table - * - * returns a list of the RID's of the constraints for a table - */ - const RIDList constraintRIDs(const TableName& tableName); - - /** return the RID of the constraint for a ConstrainName - * - * returns a RID of the constraint for a ConstrainName fron table SYSCONSTRAINT - */ - const RID constraintRID(const std::string constraintName); - - /** return the list of IndexName for a given TableColName - * - * return the list of IndexName for a given TableColName from table SYSCONSTRAINTCOL - */ - const IndexNameList colValueSysconstraint (const TableColName& colName, bool useCache=false); - - /** return the RID's of the colconstraints for a table - * - * returns a list of the RID's of the colconstraints for a table - */ - const RIDList constraintColRIDs(const TableName& tableName); - - /** return the RID of the colconstraint for a column - * - * returns the RID of the colconstraints for a column - */ - const RID constraintColRID(const TableColName& tableColName); - - /** return the value for the given RID and column name from table SYSCONSTRAINTCOL - * - * returns the column value for the given RID a column name fron table SYSCONSTRAINTCOL - */ - const std::string colValueSysconstraintCol (const TableColName& colName); - - /** return the RID of the constraint for a ConstrainName - * - * returns a RID of the constraint for a ConstrainName fron table SYSCONSTRAINTCOL - */ - const RIDList constraintColRID(const std::string constraintName); - - /** return the ROPair of the column - * - * @note the RID field in ROPair does not make sense. the purpose of this function is to - * return OID. Therefore it's duplicate to lookupOID function. This function is to be - * deprecated. - */ - const ROPair columnRID(const TableColName& tableColName); - - /** return the RID's of the columns for a table - * - * returns a list of the RID's of the columns for a table - */ - const RIDList columnRIDs(const TableName& tableName, bool useCache=false); - - /** return the RID of the table - * - * returns the RID of the table - */ - const ROPair tableRID(const TableName& tableName); - - /** return the RID of the index for a table - * - * returns the RID of the indexes for a table - */ - const ROPair indexRID(const IndexName& indexName); - /** return the INDEX NAME list for a table - * - * returns the index name list for a table - */ - const IndexNameList indexNames(const TableName& tableName); - /** return the column names for a index - * - * returns the column name list for a index - */ - const TableColNameList indexColNames ( const IndexName& indexName); - - /** return the column names for a index - * - * returns the column name list for a index - */ - const TableColNameList constraintColNames ( const std::string constraintName); - - /** return the value for the given RID and column name from table SYSINDEX - * - * returns the column value for the given RID a column name fron table SYSINDEX - */ - const std::string colValueSysindex (const TableColName& colName); - - /** return the RID of the colindexe for a table - * - * returns the RID's of the colindexe for a table - */ - const RIDList indexColRID(const IndexName& indexName); - - /** return the RID of the colindexe for a table - * - * returns the RID's of the colindexe for a table - */ - const ROPair indexColRID(const TableColName& tableColName); - - /** return the value for the given RID and column name from table SYSINDEX - * - * returns the column value for the given RID a column name fron table SYSINDEX - */ - const IndexNameList colValueSysindexCol (const TableColName& colName); - - /** looks up a Table Name for a Index in the System Catalog - * - * For a unique Index return the Table Name Structure - */ - const TableName lookupTableForIndex(const std::string indexName, const std::string schema); - - /** looks up a index oid for a Index in the System Catalog - * - * For an index name return index OID - */ - const IndexOID lookupIndexNbr(const IndexName& indexName); - - /** look up an Index Number for the given table column name - * - * If an index exists for the table and column return its number - * @note if one column belongs to multiple index, this function will get confused. - * for now, assume one column belongs to just one index. In the future getPlan - * should give index name therefore this function will be deprecated. - */ - const IndexOID lookupIndexNbr(const TableColName& tableColName); + * + * returns the total number of columns for a table + */ + const int colNumbers(const TableName& tableName); + + /** return the RID's of the colindexes for a table + * + * returns a list of the RID's of the colindexes for a table + */ + const RIDList indexColRIDs(const TableName& tableName); + + /** return the RID's of the index columns (SYSINDEXCOL) for a index + * + * returns a list of the RID's of the colindexes for a index + */ + const RIDList indexColRIDs(const IndexName& indexName); + + /** return the RID's of the constraints for a table + * + * returns a list of the RID's of the constraints for a table + */ + const RIDList constraintRIDs(const TableName& tableName); + + /** return the RID of the constraint for a ConstrainName + * + * returns a RID of the constraint for a ConstrainName fron table SYSCONSTRAINT + */ + const RID constraintRID(const std::string constraintName); + + /** return the list of IndexName for a given TableColName + * + * return the list of IndexName for a given TableColName from table SYSCONSTRAINTCOL + */ + const IndexNameList colValueSysconstraint (const TableColName& colName, bool useCache=false); + + /** return the RID's of the colconstraints for a table + * + * returns a list of the RID's of the colconstraints for a table + */ + const RIDList constraintColRIDs(const TableName& tableName); + + /** return the RID of the colconstraint for a column + * + * returns the RID of the colconstraints for a column + */ + const RID constraintColRID(const TableColName& tableColName); + + /** return the value for the given RID and column name from table SYSCONSTRAINTCOL + * + * returns the column value for the given RID a column name fron table SYSCONSTRAINTCOL + */ + const std::string colValueSysconstraintCol (const TableColName& colName); + + /** return the RID of the constraint for a ConstrainName + * + * returns a RID of the constraint for a ConstrainName fron table SYSCONSTRAINTCOL + */ + const RIDList constraintColRID(const std::string constraintName); + + /** return the ROPair of the column + * + * @note the RID field in ROPair does not make sense. the purpose of this function is to + * return OID. Therefore it's duplicate to lookupOID function. This function is to be + * deprecated. + */ + const ROPair columnRID(const TableColName& tableColName); + + /** return the RID's of the columns for a table + * + * returns a list of the RID's of the columns for a table + */ + const RIDList columnRIDs(const TableName& tableName, bool useCache=false); + + /** return the RID of the table + * + * returns the RID of the table + */ + const ROPair tableRID(const TableName& tableName); + + /** return the RID of the index for a table + * + * returns the RID of the indexes for a table + */ + const ROPair indexRID(const IndexName& indexName); + /** return the INDEX NAME list for a table + * + * returns the index name list for a table + */ + const IndexNameList indexNames(const TableName& tableName); + /** return the column names for a index + * + * returns the column name list for a index + */ + const TableColNameList indexColNames ( const IndexName& indexName); + + /** return the column names for a index + * + * returns the column name list for a index + */ + const TableColNameList constraintColNames ( const std::string constraintName); + + /** return the value for the given RID and column name from table SYSINDEX + * + * returns the column value for the given RID a column name fron table SYSINDEX + */ + const std::string colValueSysindex (const TableColName& colName); + + /** return the RID of the colindexe for a table + * + * returns the RID's of the colindexe for a table + */ + const RIDList indexColRID(const IndexName& indexName); + + /** return the RID of the colindexe for a table + * + * returns the RID's of the colindexe for a table + */ + const ROPair indexColRID(const TableColName& tableColName); + + /** return the value for the given RID and column name from table SYSINDEX + * + * returns the column value for the given RID a column name fron table SYSINDEX + */ + const IndexNameList colValueSysindexCol (const TableColName& colName); + + /** looks up a Table Name for a Index in the System Catalog + * + * For a unique Index return the Table Name Structure + */ + const TableName lookupTableForIndex(const std::string indexName, const std::string schema); + + /** looks up a index oid for a Index in the System Catalog + * + * For an index name return index OID + */ + const IndexOID lookupIndexNbr(const IndexName& indexName); + + /** look up an Index Number for the given table column name + * + * If an index exists for the table and column return its number + * @note if one column belongs to multiple index, this function will get confused. + * for now, assume one column belongs to just one index. In the future getPlan + * should give index name therefore this function will be deprecated. + */ + const IndexOID lookupIndexNbr(const TableColName& tableColName); /** return the list of Index OIDs for the given table - * - * returns the list of Index OIDs for a table - */ - const IndexOIDList indexOIDs(const TableName& tableName); - - /** return the list of Dictionary OIDs for the given table - * - * returns the list of Dictionary OIDs for a table - */ - const DictOIDList dictOIDs(const TableName& tableName); - - /** Update column OID. This is for testing DDL and DML only - * and will go away once READ works - */ - void storeColOID (void) ; - - /** Update dictionary OIDs. This is for testing DDL and DML only - * and will go away once READ works - */ - void storeDictOID (void) ; - - /** Update index OIDs. This is for testing DDL and DML only - * and will go away once READ works - */ - void storeIndexOID (void) ; - - /** Reload dictionary OIDs, index OIDs, column OID. This is for testing DDL and DML only - * and will go away once READ works - */ - void updateColInfo (void) ; - - /** returns a pointer to the System Catalog singleton per session - * TODO: may need to change to one instance per transaction - * @parm sessionID to map the key of catalog map - */ - static SPCSC makeCalpontSystemCatalog(uint32_t sessionID = 0); - - /** remove and delete the instance map to the sessionid - * @param sessionID - */ - static void removeCalpontSystemCatalog(uint32_t sessionID = 0); - /** sessionid access and mutator methods - * - */ - const uint32_t sessionID() const { return fSessionID; } - void sessionID (uint32_t sessionID) { fSessionID = sessionID; } - /** identity access and mutator methods - * - */ - const int identity() const { return fIdentity; } - void identity (int identity) { fIdentity = identity; } - - /** return the column position - * - * return the column position for a given OID - */ - const int colPosition (const OID& oid); - /** return primary key name for the given table */ - const std::string primaryKeyName (const TableName& tableName ); - /** return the table info - * - * return the table info for a given TableName - */ - const TableInfo tableInfo (const TableName& tb); - /** return the table name for a give table oid */ - const TableName tableName (const OID& oid); - /** return the list of tables for a given schema */ - const std::vector< std::pair > getTables (const std::string schema = ""); - /** return the number of tables in the whole database */ - const int getTableCount (); - /** return the constraint info for a given constraint */ - const ConstraintInfo constraintInfo (const IndexName& constraintName); - /** return the constraintName list for a given referencePKName */ - const IndexNameList referenceConstraints (const IndexName& referencePKName); - - // @bug 682 - void getSchemaInfo(const std::string& schema); - + * + * returns the list of Index OIDs for a table + */ + const IndexOIDList indexOIDs(const TableName& tableName); + + /** return the list of Dictionary OIDs for the given table + * + * returns the list of Dictionary OIDs for a table + */ + const DictOIDList dictOIDs(const TableName& tableName); + + /** Update column OID. This is for testing DDL and DML only + * and will go away once READ works + */ + void storeColOID (void) ; + + /** Update dictionary OIDs. This is for testing DDL and DML only + * and will go away once READ works + */ + void storeDictOID (void) ; + + /** Update index OIDs. This is for testing DDL and DML only + * and will go away once READ works + */ + void storeIndexOID (void) ; + + /** Reload dictionary OIDs, index OIDs, column OID. This is for testing DDL and DML only + * and will go away once READ works + */ + void updateColInfo (void) ; + + /** returns a pointer to the System Catalog singleton per session + * TODO: may need to change to one instance per transaction + * @parm sessionID to map the key of catalog map + */ + static boost::shared_ptr makeCalpontSystemCatalog(uint32_t sessionID = 0); + + /** remove and delete the instance map to the sessionid + * @param sessionID + */ + static void removeCalpontSystemCatalog(uint32_t sessionID = 0); + /** sessionid access and mutator methods + * + */ + const uint32_t sessionID() const { return fSessionID; } + void sessionID (uint32_t sessionID) { fSessionID = sessionID; } + /** identity access and mutator methods + * + */ + const int identity() const { return fIdentity; } + void identity (int identity) { fIdentity = identity; } + + /** return the column position + * + * return the column position for a given OID + */ + const int colPosition (const OID& oid); + /** return primary key name for the given table */ + const std::string primaryKeyName (const TableName& tableName ); + /** return the table info + * + * return the table info for a given TableName + */ + const TableInfo tableInfo (const TableName& tb); + /** return the table name for a give table oid */ + const TableName tableName (const OID& oid); + /** return the list of tables for a given schema */ + const std::vector< std::pair > getTables (const std::string schema = ""); + /** return the number of tables in the whole database */ + const int getTableCount (); + /** return the constraint info for a given constraint */ + const ConstraintInfo constraintInfo (const IndexName& constraintName); + /** return the constraintName list for a given referencePKName */ + const IndexNameList referenceConstraints (const IndexName& referencePKName); + + // @bug 682 + void getSchemaInfo(const std::string& schema); + typedef std::map OIDNextvalMap; void updateColinfoCache(OIDNextvalMap & oidNextvalMap); - void flushCache(); + void flushCache(); /** Convert a MySQL thread id to an InfiniDB session id */ static uint32_t idb_tid2sid(const uint32_t tid); friend class ::ExecPlanTest; - /** Destructor */ - ~CalpontSystemCatalog(); + /** Destructor */ + ~CalpontSystemCatalog(); private: - /** Constuctors */ - explicit CalpontSystemCatalog(); - explicit CalpontSystemCatalog(const CalpontSystemCatalog& rhs); - - - CalpontSystemCatalog& operator=(const CalpontSystemCatalog& rhs); - - /** get system data */ - void getSysData (execplan::CalpontSelectExecutionPlan&, NJLSysDataList&, const std::string& sysTableName); - /** get system data for Front End */ - void getSysData_FE(const execplan::CalpontSelectExecutionPlan&, NJLSysDataList&, const std::string& sysTableName); - /** get system data for Engine Controller */ - void getSysData_EC(execplan::CalpontSelectExecutionPlan&, NJLSysDataList&, const std::string& sysTableName); - - void buildSysColinfomap(); - void buildSysOIDmap(); - void buildSysTablemap(); - void buildSysDctmap(); - - void checkSysCatVer(); + /** Constuctors */ + explicit CalpontSystemCatalog(); + explicit CalpontSystemCatalog(const CalpontSystemCatalog& rhs); + + + CalpontSystemCatalog& operator=(const CalpontSystemCatalog& rhs); + + /** get system data */ + void getSysData (execplan::CalpontSelectExecutionPlan&, NJLSysDataList&, const std::string& sysTableName); + /** get system data for Front End */ + void getSysData_FE(const execplan::CalpontSelectExecutionPlan&, NJLSysDataList&, const std::string& sysTableName); + /** get system data for Engine Controller */ + void getSysData_EC(execplan::CalpontSelectExecutionPlan&, NJLSysDataList&, const std::string& sysTableName); + + void buildSysColinfomap(); + void buildSysOIDmap(); + void buildSysTablemap(); + void buildSysDctmap(); + + void checkSysCatVer(); static boost::mutex map_mutex; - static CatalogMap fCatalogMap; - - typedef std::map OIDmap; - OIDmap fOIDmap; - boost::mutex fOIDmapLock; //Also locks fColRIDmap - - typedef std::map Tablemap; - Tablemap fTablemap; - - typedef std::map Colinfomap; - Colinfomap fColinfomap; - boost::mutex fColinfomapLock; - - /** this structure is used by ddl only. it cache the rid for rows in syscolumn - that match the tableColName */ - typedef std::map ColRIDmap; - ColRIDmap fColRIDmap; - - /** this structure is used by ddl only. it cache the rid for rows in systable - that match the tableName */ - typedef std::map TableRIDmap; - TableRIDmap fTableRIDmap; - - - // this structure may combine with Tablemap, where RID is added to TalbeInfo struct - typedef std::map TableInfoMap; - TableInfoMap fTableInfoMap; - boost::mutex fTableInfoMapLock; - - typedef std::map ColIndexListmap; - ColIndexListmap fColIndexListmap; - boost::mutex fColIndexListmapLock; - - typedef std::map DctTokenMap; - DctTokenMap fDctTokenMap; - boost::mutex fDctTokenMapLock; + static CatalogMap fCatalogMap; + + typedef std::map OIDmap; + OIDmap fOIDmap; + boost::mutex fOIDmapLock; //Also locks fColRIDmap + + typedef std::map Tablemap; + Tablemap fTablemap; + + typedef std::map Colinfomap; + Colinfomap fColinfomap; + boost::mutex fColinfomapLock; + + /** this structure is used by ddl only. it cache the rid for rows in syscolumn + that match the tableColName */ + typedef std::map ColRIDmap; + ColRIDmap fColRIDmap; + + /** this structure is used by ddl only. it cache the rid for rows in systable + that match the tableName */ + typedef std::map TableRIDmap; + TableRIDmap fTableRIDmap; + + + // this structure may combine with Tablemap, where RID is added to TalbeInfo struct + typedef std::map TableInfoMap; + TableInfoMap fTableInfoMap; + boost::mutex fTableInfoMapLock; + + typedef std::map ColIndexListmap; + ColIndexListmap fColIndexListmap; + boost::mutex fColIndexListmapLock; + + typedef std::map DctTokenMap; + DctTokenMap fDctTokenMap; + boost::mutex fDctTokenMapLock; typedef std::map TableNameMap; TableNameMap fTableNameMap; boost::mutex fTableNameMapLock; - ClientRotator* fExeMgr; - uint32_t fSessionID; - uint32_t fTxn; - int fIdentity; - std::set fSchemaCache; - boost::mutex fSchemaCacheLock; - //Cache flush - boost::mutex fSyscatSCNLock; - SCN fSyscatSCN; + ClientRotator* fExeMgr; + uint32_t fSessionID; + uint32_t fTxn; + int fIdentity; + std::set fSchemaCache; + boost::mutex fSchemaCacheLock; + //Cache flush + boost::mutex fSyscatSCNLock; + SCN fSyscatSCN; static uint32_t fModuleID; }; @@ -888,184 +825,9 @@ const CalpontSystemCatalog::TableColName make_tcn(const std::string& s, const st */ const CalpontSystemCatalog::TableName make_table(const std::string& s, const std::string& t); const CalpontSystemCatalog::TableAliasName make_aliastable(const std::string& s, const std::string& t, const std::string& a, - const bool fIsInfiniDB = true); + const bool fIsInfiniDB = true); const CalpontSystemCatalog::TableAliasName make_aliasview(const std::string& s, const std::string& t, const std::string& a, const std::string& v, const bool fIsInfiniDB = true); -/** convenience function to determine if column type is a char - * type - */ -inline bool isCharType(const execplan::CalpontSystemCatalog::ColDataType type) -{ - return (execplan::CalpontSystemCatalog::VARCHAR == type || execplan::CalpontSystemCatalog::CHAR == type); -} - -/** convenience function to determine if column type is an - * unsigned type - */ -inline bool isUnsigned(const execplan::CalpontSystemCatalog::ColDataType type) -{ - switch (type) - { - case execplan::CalpontSystemCatalog::UTINYINT: - case execplan::CalpontSystemCatalog::USMALLINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UBIGINT: - return true; - default: - return false; - } -} - -inline bool isSignedInteger(const execplan::CalpontSystemCatalog::ColDataType type) -{ - switch (type) - { - case execplan::CalpontSystemCatalog::TINYINT: - case execplan::CalpontSystemCatalog::SMALLINT: - case execplan::CalpontSystemCatalog::MEDINT: - case execplan::CalpontSystemCatalog::INT: - case execplan::CalpontSystemCatalog::BIGINT: - return true; - default: - return false; - } -} - -inline bool isNull(int64_t val, const execplan::CalpontSystemCatalog::ColType& ct) -{ - bool ret = false; - - switch (ct.colDataType) - { - case execplan::CalpontSystemCatalog::TINYINT: - { - if ((int8_t) joblist::TINYINTNULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::CHAR: - { - int colWidth = ct.colWidth; - if (colWidth <= 8) - { - if ((colWidth == 1) && ((int8_t) joblist::CHAR1NULL == val)) ret = true ; - else if ((colWidth == 2) && ((int16_t) joblist::CHAR2NULL == val)) ret = true; - else if ((colWidth < 5) && ((int32_t) joblist::CHAR4NULL == val)) ret = true; - else if ((int64_t) joblist::CHAR8NULL == val) ret = true; - } - else - { - throw std::logic_error("Not a int column."); - } - break; - } - case execplan::CalpontSystemCatalog::SMALLINT: - { - if ((int16_t) joblist::SMALLINTNULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::DECIMAL: - case execplan::CalpontSystemCatalog::UDECIMAL: - { - switch (ct.colWidth) - { - case 1: - { - if ((int8_t)joblist::TINYINTNULL == val) ret = true; - break; - } - case 2: - { - if ((int16_t)joblist::SMALLINTNULL == val) ret = true; - break; - } - case 4: - { - if ((int32_t)joblist::INTNULL == val) ret = true; - break; - } - default: - { - if ((int64_t)joblist::BIGINTNULL == val) ret = true; - break; - } - } - } - case execplan::CalpontSystemCatalog::DOUBLE: - case execplan::CalpontSystemCatalog::UDOUBLE: - { - if ((int64_t)joblist::DOUBLENULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::MEDINT: - case execplan::CalpontSystemCatalog::INT: - { - if ((int32_t)joblist::INTNULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::FLOAT: - case execplan::CalpontSystemCatalog::UFLOAT: - { - if ((int32_t)joblist::FLOATNULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::DATE: - { - if ((int32_t) joblist::DATENULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::BIGINT: - { - if ((int64_t)joblist::BIGINTNULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::DATETIME: - { - if ((int64_t)joblist::DATETIMENULL == val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::VARCHAR: - { - int colWidth = ct.colWidth; - if (colWidth <= 8) - { - if ((colWidth < 3) && ((int16_t) joblist::CHAR2NULL == val)) ret = true; - else if ((colWidth < 5) && ((int32_t) joblist::CHAR4NULL == val)) ret = true; - else if ((int64_t)joblist::CHAR8NULL == val) ret = true; - } - else - { - throw std::logic_error("Not a int column."); - } - break; - } - case execplan::CalpontSystemCatalog::UTINYINT: - { - if (joblist::UTINYINTNULL == (uint8_t)val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::USMALLINT: - { - if (joblist::USMALLINTNULL == (uint16_t)val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UINT: - { - if (joblist::UINTNULL == (uint32_t)val) ret = true; - break; - } - case execplan::CalpontSystemCatalog::UBIGINT: - { - if (joblist::UBIGINTNULL == (uint64_t)val) ret = true; - break; - } - default: - break; - } - - return ret; -} /** constants for system table names */ @@ -1116,46 +878,46 @@ const std::string NEXTVALUE_COL = "nextvalue"; /***************************************************** * System tables OID definition ******************************************************/ -const int SYSTABLE_BASE = 1000; /** @brief SYSTABLE table base */ -const int SYSTABLE_DICT_BASE = 2000; /** @brief SYSTABLE table dictionary files base */ -const int SYSCOLUMN_BASE = 1020; /** @brief SYSCOLUMN table base */ -const int SYSCOLUMN_DICT_BASE = 2060; /** @brief SYSCOLUMN table dictionary files base */ +const int SYSTABLE_BASE = 1000; /** @brief SYSTABLE table base */ +const int SYSTABLE_DICT_BASE = 2000; /** @brief SYSTABLE table dictionary files base */ +const int SYSCOLUMN_BASE = 1020; /** @brief SYSCOLUMN table base */ +const int SYSCOLUMN_DICT_BASE = 2060; /** @brief SYSCOLUMN table dictionary files base */ /***************************************************** * SYSTABLE columns OID definition ******************************************************/ -const int OID_SYSTABLE_TABLENAME = SYSTABLE_BASE + 1; /** @brief TABLENAME column */ -const int OID_SYSTABLE_SCHEMA = SYSTABLE_BASE + 2; /** @brief SCHEMA column */ -const int OID_SYSTABLE_OBJECTID = SYSTABLE_BASE + 3; /** @brief OBJECTID column */ -const int OID_SYSTABLE_CREATEDATE = SYSTABLE_BASE + 4; /** @brief CREATEDATE column */ -const int OID_SYSTABLE_LASTUPDATE = SYSTABLE_BASE + 5; /** @brief LASTUPDATE column */ -const int OID_SYSTABLE_INIT = SYSTABLE_BASE + 6; /** @brief INIT column */ -const int OID_SYSTABLE_NEXT = SYSTABLE_BASE + 7; /** @brief NEXT column */ -const int OID_SYSTABLE_NUMOFROWS = SYSTABLE_BASE + 8; /** @brief total num of rows column */ -const int OID_SYSTABLE_AVGROWLEN = SYSTABLE_BASE + 9; /** @brief avg. row length column */ -const int OID_SYSTABLE_NUMOFBLOCKS = SYSTABLE_BASE + 10; /** @brief num. of blocks column */ -const int OID_SYSTABLE_AUTOINCREMENT = SYSTABLE_BASE + 11; /** @brief AUTOINCREMENT column */ +const int OID_SYSTABLE_TABLENAME = SYSTABLE_BASE + 1; /** @brief TABLENAME column */ +const int OID_SYSTABLE_SCHEMA = SYSTABLE_BASE + 2; /** @brief SCHEMA column */ +const int OID_SYSTABLE_OBJECTID = SYSTABLE_BASE + 3; /** @brief OBJECTID column */ +const int OID_SYSTABLE_CREATEDATE = SYSTABLE_BASE + 4; /** @brief CREATEDATE column */ +const int OID_SYSTABLE_LASTUPDATE = SYSTABLE_BASE + 5; /** @brief LASTUPDATE column */ +const int OID_SYSTABLE_INIT = SYSTABLE_BASE + 6; /** @brief INIT column */ +const int OID_SYSTABLE_NEXT = SYSTABLE_BASE + 7; /** @brief NEXT column */ +const int OID_SYSTABLE_NUMOFROWS = SYSTABLE_BASE + 8; /** @brief total num of rows column */ +const int OID_SYSTABLE_AVGROWLEN = SYSTABLE_BASE + 9; /** @brief avg. row length column */ +const int OID_SYSTABLE_NUMOFBLOCKS = SYSTABLE_BASE + 10; /** @brief num. of blocks column */ +const int OID_SYSTABLE_AUTOINCREMENT = SYSTABLE_BASE + 11; /** @brief AUTOINCREMENT column */ const int SYSTABLE_MAX = SYSTABLE_BASE + 12; // be sure this is one more than the highest # /***************************************************** * SYSCOLUMN columns OID definition ******************************************************/ -const int OID_SYSCOLUMN_SCHEMA = SYSCOLUMN_BASE + 1; /** @brief SCHEMA column */ -const int OID_SYSCOLUMN_TABLENAME = SYSCOLUMN_BASE + 2; /** @brief TABLENAME column */ -const int OID_SYSCOLUMN_COLNAME = SYSCOLUMN_BASE + 3; /** @brief COLNAME column */ -const int OID_SYSCOLUMN_OBJECTID = SYSCOLUMN_BASE + 4; /** @brief OBJECTID column */ -const int OID_SYSCOLUMN_DICTOID = SYSCOLUMN_BASE + 5; /** @brief DICTOID column */ -const int OID_SYSCOLUMN_LISTOBJID = SYSCOLUMN_BASE + 6; /** @brief LISTOBJID column */ -const int OID_SYSCOLUMN_TREEOBJID = SYSCOLUMN_BASE + 7; /** @brief TREEOBJID column */ -const int OID_SYSCOLUMN_DATATYPE = SYSCOLUMN_BASE + 8; /** @brief DATATYPE column */ -const int OID_SYSCOLUMN_COLUMNLEN = SYSCOLUMN_BASE + 9; /** @brief COLUMNLEN column */ -const int OID_SYSCOLUMN_COLUMNPOS = SYSCOLUMN_BASE + 10; /** @brief COLUMNPOS column */ -const int OID_SYSCOLUMN_LASTUPDATE = SYSCOLUMN_BASE + 11; /** @brief LASTUPDATE column */ -const int OID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_BASE + 12; /** @brief DEFAULTVAL column */ -const int OID_SYSCOLUMN_NULLABLE = SYSCOLUMN_BASE + 13; /** @brief NULLABLE column */ -const int OID_SYSCOLUMN_SCALE = SYSCOLUMN_BASE + 14; /** @brief SCALE column */ -const int OID_SYSCOLUMN_PRECISION = SYSCOLUMN_BASE + 15; /** @brief PRECISION column */ -const int OID_SYSCOLUMN_AUTOINC = SYSCOLUMN_BASE + 16; /** @brief AUTOINC column */ +const int OID_SYSCOLUMN_SCHEMA = SYSCOLUMN_BASE + 1; /** @brief SCHEMA column */ +const int OID_SYSCOLUMN_TABLENAME = SYSCOLUMN_BASE + 2; /** @brief TABLENAME column */ +const int OID_SYSCOLUMN_COLNAME = SYSCOLUMN_BASE + 3; /** @brief COLNAME column */ +const int OID_SYSCOLUMN_OBJECTID = SYSCOLUMN_BASE + 4; /** @brief OBJECTID column */ +const int OID_SYSCOLUMN_DICTOID = SYSCOLUMN_BASE + 5; /** @brief DICTOID column */ +const int OID_SYSCOLUMN_LISTOBJID = SYSCOLUMN_BASE + 6; /** @brief LISTOBJID column */ +const int OID_SYSCOLUMN_TREEOBJID = SYSCOLUMN_BASE + 7; /** @brief TREEOBJID column */ +const int OID_SYSCOLUMN_DATATYPE = SYSCOLUMN_BASE + 8; /** @brief DATATYPE column */ +const int OID_SYSCOLUMN_COLUMNLEN = SYSCOLUMN_BASE + 9; /** @brief COLUMNLEN column */ +const int OID_SYSCOLUMN_COLUMNPOS = SYSCOLUMN_BASE + 10; /** @brief COLUMNPOS column */ +const int OID_SYSCOLUMN_LASTUPDATE = SYSCOLUMN_BASE + 11; /** @brief LASTUPDATE column */ +const int OID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_BASE + 12; /** @brief DEFAULTVAL column */ +const int OID_SYSCOLUMN_NULLABLE = SYSCOLUMN_BASE + 13; /** @brief NULLABLE column */ +const int OID_SYSCOLUMN_SCALE = SYSCOLUMN_BASE + 14; /** @brief SCALE column */ +const int OID_SYSCOLUMN_PRECISION = SYSCOLUMN_BASE + 15; /** @brief PRECISION column */ +const int OID_SYSCOLUMN_AUTOINC = SYSCOLUMN_BASE + 16; /** @brief AUTOINC column */ const int OID_SYSCOLUMN_DISTCOUNT = SYSCOLUMN_BASE + 17; /** @brief Num of distinct value col */ const int OID_SYSCOLUMN_NULLCOUNT = SYSCOLUMN_BASE + 18; /** @brief Num of null value col */ const int OID_SYSCOLUMN_MINVALUE = SYSCOLUMN_BASE + 19; /** @brief min value col */ @@ -1167,35 +929,35 @@ const int SYSCOLUMN_MAX = SYSCOLUMN_BASE + 23; // be sure this is one more t /***************************************************** * SYSTABLE columns dictionary OID definition ******************************************************/ -const int DICTOID_SYSTABLE_TABLENAME = SYSTABLE_DICT_BASE + 1; /** @brief TABLENAME column DICTOID*/ -const int LISTOID_SYSTABLE_TABLENAME = SYSTABLE_DICT_BASE + 2; /** @brief TABLENAME column LISTOID*/ -const int TREEOID_SYSTABLE_TABLENAME = SYSTABLE_DICT_BASE + 3; /** @brief TABLENAME column TREEOID*/ -const int DICTOID_SYSTABLE_SCHEMA = SYSTABLE_DICT_BASE + 4; /** @brief SCHEMA column DICTOID*/ -const int LISTOID_SYSTABLE_SCHEMA = SYSTABLE_DICT_BASE + 5; /** @brief SCHEMA column LISTOID*/ -const int TREEOID_SYSTABLE_SCHEMA = SYSTABLE_DICT_BASE + 6; /** @brief SCHEMA column TREEOID*/ +const int DICTOID_SYSTABLE_TABLENAME = SYSTABLE_DICT_BASE + 1; /** @brief TABLENAME column DICTOID*/ +const int LISTOID_SYSTABLE_TABLENAME = SYSTABLE_DICT_BASE + 2; /** @brief TABLENAME column LISTOID*/ +const int TREEOID_SYSTABLE_TABLENAME = SYSTABLE_DICT_BASE + 3; /** @brief TABLENAME column TREEOID*/ +const int DICTOID_SYSTABLE_SCHEMA = SYSTABLE_DICT_BASE + 4; /** @brief SCHEMA column DICTOID*/ +const int LISTOID_SYSTABLE_SCHEMA = SYSTABLE_DICT_BASE + 5; /** @brief SCHEMA column LISTOID*/ +const int TREEOID_SYSTABLE_SCHEMA = SYSTABLE_DICT_BASE + 6; /** @brief SCHEMA column TREEOID*/ const int SYSTABLE_DICT_MAX = SYSTABLE_DICT_BASE + 7; // be sure this is one more than the highest # /***************************************************** * SYSCOLUMN columns dictionary OID definition ******************************************************/ -const int DICTOID_SYSCOLUMN_SCHEMA = SYSCOLUMN_DICT_BASE + 1; /** @brief SCHEMA column DICTOID*/ -const int LISTOID_SYSCOLUMN_SCHEMA = SYSCOLUMN_DICT_BASE + 2; /** @brief SCHEMA column LISTOID*/ -const int TREEOID_SYSCOLUMN_SCHEMA = SYSCOLUMN_DICT_BASE + 3; /** @brief SCHEMA column TREEOID*/ -const int DICTOID_SYSCOLUMN_TABLENAME = SYSCOLUMN_DICT_BASE + 4; /** @brief TABLENAME column DICTOID*/ -const int LISTOID_SYSCOLUMN_TABLENAME = SYSCOLUMN_DICT_BASE + 5; /** @brief TABLENAME column LISTOID*/ -const int TREEOID_SYSCOLUMN_TABLENAME = SYSCOLUMN_DICT_BASE + 6; /** @brief TABLENAME column TREEOID*/ -const int DICTOID_SYSCOLUMN_COLNAME = SYSCOLUMN_DICT_BASE + 7; /** @brief COLNAME column DICTOID*/ -const int LISTOID_SYSCOLUMN_COLNAME = SYSCOLUMN_DICT_BASE + 8; /** @brief COLNAME column LISTOID*/ -const int TREEOID_SYSCOLUMN_COLNAME = SYSCOLUMN_DICT_BASE + 9; /** @brief COLNAME column TREEOID*/ -const int DICTOID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_DICT_BASE + 10; /** @brief DEFAULTVAL column DICTOID*/ -const int LISTOID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_DICT_BASE + 11; /** @brief DEFAULTVAL column LISTOID*/ -const int TREEOID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_DICT_BASE + 12; /** @brief DEFAULTVAL column TREEOID*/ -const int DICTOID_SYSCOLUMN_MINVALUE = SYSCOLUMN_DICT_BASE + 13; /** @brief MINVAL column DICTOID*/ -const int LISTOID_SYSCOLUMN_MINVALUE = SYSCOLUMN_DICT_BASE + 14; /** @brief MINVAL column LISTOID*/ -const int TREEOID_SYSCOLUMN_MINVALUE = SYSCOLUMN_DICT_BASE + 15; /** @brief MINVAL column TREEOID*/ -const int DICTOID_SYSCOLUMN_MAXVALUE = SYSCOLUMN_DICT_BASE + 16; /** @brief MAXVAL column DICTOID*/ -const int LISTOID_SYSCOLUMN_MAXVALUE = SYSCOLUMN_DICT_BASE + 17; /** @brief MAXVAL column LISTOID*/ -const int TREEOID_SYSCOLUMN_MAXVALUE = SYSCOLUMN_DICT_BASE + 18; /** @brief MAXVAL column TREEOID*/ +const int DICTOID_SYSCOLUMN_SCHEMA = SYSCOLUMN_DICT_BASE + 1; /** @brief SCHEMA column DICTOID*/ +const int LISTOID_SYSCOLUMN_SCHEMA = SYSCOLUMN_DICT_BASE + 2; /** @brief SCHEMA column LISTOID*/ +const int TREEOID_SYSCOLUMN_SCHEMA = SYSCOLUMN_DICT_BASE + 3; /** @brief SCHEMA column TREEOID*/ +const int DICTOID_SYSCOLUMN_TABLENAME = SYSCOLUMN_DICT_BASE + 4; /** @brief TABLENAME column DICTOID*/ +const int LISTOID_SYSCOLUMN_TABLENAME = SYSCOLUMN_DICT_BASE + 5; /** @brief TABLENAME column LISTOID*/ +const int TREEOID_SYSCOLUMN_TABLENAME = SYSCOLUMN_DICT_BASE + 6; /** @brief TABLENAME column TREEOID*/ +const int DICTOID_SYSCOLUMN_COLNAME = SYSCOLUMN_DICT_BASE + 7; /** @brief COLNAME column DICTOID*/ +const int LISTOID_SYSCOLUMN_COLNAME = SYSCOLUMN_DICT_BASE + 8; /** @brief COLNAME column LISTOID*/ +const int TREEOID_SYSCOLUMN_COLNAME = SYSCOLUMN_DICT_BASE + 9; /** @brief COLNAME column TREEOID*/ +const int DICTOID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_DICT_BASE + 10; /** @brief DEFAULTVAL column DICTOID*/ +const int LISTOID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_DICT_BASE + 11; /** @brief DEFAULTVAL column LISTOID*/ +const int TREEOID_SYSCOLUMN_DEFAULTVAL = SYSCOLUMN_DICT_BASE + 12; /** @brief DEFAULTVAL column TREEOID*/ +const int DICTOID_SYSCOLUMN_MINVALUE = SYSCOLUMN_DICT_BASE + 13; /** @brief MINVAL column DICTOID*/ +const int LISTOID_SYSCOLUMN_MINVALUE = SYSCOLUMN_DICT_BASE + 14; /** @brief MINVAL column LISTOID*/ +const int TREEOID_SYSCOLUMN_MINVALUE = SYSCOLUMN_DICT_BASE + 15; /** @brief MINVAL column TREEOID*/ +const int DICTOID_SYSCOLUMN_MAXVALUE = SYSCOLUMN_DICT_BASE + 16; /** @brief MAXVAL column DICTOID*/ +const int LISTOID_SYSCOLUMN_MAXVALUE = SYSCOLUMN_DICT_BASE + 17; /** @brief MAXVAL column LISTOID*/ +const int TREEOID_SYSCOLUMN_MAXVALUE = SYSCOLUMN_DICT_BASE + 18; /** @brief MAXVAL column TREEOID*/ const int SYSCOLUMN_DICT_MAX = SYSCOLUMN_DICT_BASE + 19; // be sure this is one more than the highest # std::vector getAllSysCatOIDs(); @@ -1205,10 +967,8 @@ std::vector getAllSysCatOIDs(); */ std::ostream& operator<<(std::ostream& os, const CalpontSystemCatalog::ColType& rhs); -const std::string colDataTypeToString(CalpontSystemCatalog::ColDataType cdt); - } //namespace execplan -#endif //EXECPLAN_CALPONTSYSTEMCATALOG_H +#endif //EXECPLAN_CALPONTSYSTEMCATALOG_H // vim:ts=4 sw=4: diff --git a/dbcon/execplan/clientrotator.cpp b/dbcon/execplan/clientrotator.cpp index 3fc45a7e..1676da1c 100644 --- a/dbcon/execplan/clientrotator.cpp +++ b/dbcon/execplan/clientrotator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /********************************************************************* - * $Id: clientrotator.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: clientrotator.cpp 8908 2012-09-18 18:50:03Z zzhu $ * * ***********************************************************************/ @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -45,233 +44,189 @@ using namespace messageqcpp; #include "loggingid.h" using namespace logging; -#include "installdir.h" - #include "clientrotator.h" #define LOG_TO_CERR namespace execplan { - -const string LOCAL_EXEMGR_IP = "127.0.0.1"; -const uint64_t LOCAL_EXEMGR_PORT = 8601; - -string ClientRotator::getModule() -{ - string installDir = startup::StartUp::installDir(); - string fileName = installDir + "/local/module"; - string module; - ifstream moduleFile (fileName.c_str()); - - if (moduleFile.is_open()) - getline (moduleFile, module); - moduleFile.close(); - return module; -} - -ostream& operator<<(ostream& output, const ClientRotator& rhs) -{ - output << __FILE__ << rhs.fName << "\t" << rhs.fSessionId << endl; - return output; -} - -ClientRotator::ClientRotator(uint32_t sid, const std::string& name, bool localQuery) : - fName(name), fSessionId(sid), fClient(0), fClients(), fCf(Config::makeConfig()), - fDebug(0), fLocalQuery(localQuery) -{ - if (! fCf) - throw runtime_error((string)__FILE__ + ": No configuration file"); - fDebug = static_cast(Config::fromText(fCf->getConfig("CalpontConnector", "DebugLevel"))); -} - -void ClientRotator::loadClients() -{ - //This object is statically allocated somewhere. We need to reload the config file here - // to search the extproc env for changes made after libcalora.so is loaded. - fCf = Config::makeConfig(); - - string pmWithUMStr = fCf->getConfig("Installation", "PMwithUM"); - bool pmWithUM = (pmWithUMStr == "y" || pmWithUMStr == "Y"); - - // check current module type - if (!fLocalQuery && pmWithUM) - { - string module = getModule(); - if (!module.empty() && (module[0] == 'P' || module[0] == 'p')) - fLocalQuery = true; - } - - // connect to loopback ExeMgr for local query set up - if (fLocalQuery) - { - fClient = new MessageQueueClient(LOCAL_EXEMGR_IP, LOCAL_EXEMGR_PORT); - return; - } - - stringstream ss(fName); - size_t pos = fName.length(); - string str; - int i = 1; - do + ostream& operator<<(ostream& output, const ClientRotator& rhs) + { + output << __FILE__ << rhs.fName << "\t" << rhs.fSessionId << endl; + return output; + } + + ClientRotator::ClientRotator(u_int32_t sid, const std::string& name) : + fName(name), fSessionId(sid), fClient(0), fClients(), fCf(Config::makeConfig()), fDebug(0) + { + if (! fCf) + throw runtime_error((string)__FILE__ + ": No configuration file"); + fDebug = static_cast(Config::fromText(fCf->getConfig("CalpontConnector", "DebugLevel"))); + } + + + void ClientRotator::loadClients() + { + //This object is statically allocated somewhere. We need to reload the config file here + // to search the extproc env for changes made after libcalora.so is loaded. + fCf = Config::makeConfig(); + + stringstream ss(fName); + size_t pos = fName.length(); + string str; + int i = 1; + do + { + ss.seekp(pos); + ss << i++; + str = fCf->getConfig(ss.str(), "Port"); + if (str.length() ) fClients.push_back(ss.str()); + } while ( str.length() ); + if (fClients.empty()) + throw runtime_error((string)__FILE__ + ": No configuration tags for " + fName + "\n"); + + } + + void ClientRotator::resetClient() { - ss.seekp(pos); - ss << i++; - str = fCf->getConfig(ss.str(), "Port"); - if (str.length() ) + try //one more time... { - string moduleStr = fCf->getConfig(ss.str(), "Module"); - // "if the system is not running in a 'PM with UM' config, the module type is unspecified, or the - // module is specified as a UM, use it" - if (!pmWithUM || moduleStr.empty() || moduleStr[0] == 'u' || moduleStr[0] == 'U') - fClients.push_back(ss.str()); + delete fClient; + fClient = 0; + connectList(fSessionId % fClients.size()); + //fClient->write(msg); } - } while ( str.length() ); - if (fClients.empty()) - throw runtime_error((string)__FILE__ + ": No configuration tags for " + fName + "\n"); -} - -void ClientRotator::resetClient() -{ - try //one more time... - { - delete fClient; - fClient = 0; - connectList(); - //fClient->write(msg); - } - catch (std::exception &e) - { - /* Can't fail silently */ - writeToLog(__LINE__, e.what(), true); + catch (std::exception &e) + { + /* Can't fail silently */ + writeToLog(__LINE__, e.what(), true); #ifdef LOG_TO_CERR - cerr << "ClientRotator::write() failed: " << e.what() << endl; + cerr << "ClientRotator::write() failed: " << e.what() << endl; #endif - throw; + throw; + } } -} -void ClientRotator::write(const ByteStream& msg) -{ - if (!fClient) - connect(); - try - { - fClient->write(msg); - return; - } - catch (std::exception& e) - { - resetClient(); - string errmsg = "ClientRotator caught exception: " + string(e.what()); - cout << errmsg << endl; - throw runtime_error(errmsg); - } - catch (...) + void ClientRotator::write(const ByteStream& msg) { - resetClient(); - string errmsg = "ClientRotator caught unknown exception"; - cout << errmsg << endl; - throw runtime_error(errmsg); - } -} - -ByteStream ClientRotator::read() -{ - mutex::scoped_lock lk(fClientLock); - - ByteStream bs; - if (!fClient) - connect(); + if (!fClient) + connect(); - try - { - bs = fClient->read(); - return bs; - } - catch (std::exception& e) - { - resetClient(); - string errmsg = "ClientRotator caught exception: " + string(e.what()); - cout << errmsg << endl; - throw runtime_error(errmsg); + try + { + fClient->write(msg); + return; + } + catch (std::exception& e) + { + resetClient(); + string errmsg = "ClientRotator caught exception: " + string(e.what()); + cout << errmsg << endl; + throw runtime_error(errmsg); + } + catch (...) + { + resetClient(); + string errmsg = "ClientRotator caught unknown exception"; + cout << errmsg << endl; + throw runtime_error(errmsg); + } } - catch (...) + + ByteStream ClientRotator::read() { - resetClient(); - string errmsg = "ClientRotator caught unknown exception"; - cout << errmsg << endl; - throw runtime_error(errmsg); - } + mutex::scoped_lock lk(fClientLock); + + ByteStream bs; + + if (!fClient) + connect(); + + try + { + bs = fClient->read(); + return bs; + } + catch (std::exception& e) + { + resetClient(); + string errmsg = "ClientRotator caught exception: " + string(e.what()); + cout << errmsg << endl; + throw runtime_error(errmsg); + } + catch (...) + { + resetClient(); + string errmsg = "ClientRotator caught unknown exception"; + cout << errmsg << endl; + throw runtime_error(errmsg); + } #if 0 - try //one more time... - { - delete fClient; - fClient = 0; - connectList(); - bs = fClient->read(); - return bs; - } - catch (std::exception &e) - { + try //one more time... + { + delete fClient; + fClient = 0; + connectList(fSessionId % fClients.size()); + bs = fClient->read(); + return bs; + } + catch (std::exception &e) + { /* Can't fail silently */ writeToLog(__LINE__, e.what(), true); #ifdef LOG_TO_CERR cerr << "ClientRotator::read() failed: " << e.what() << endl; #endif throw; - } + } #endif - return bs; -} + return bs; + } -void ClientRotator::connect(double timeout) -{ - if (fClient) return; - if (fClients.empty()) - loadClients(); + void ClientRotator::connect(double timeout) + { - if (fClient) return; + if (fClients.empty()) + loadClients(); - size_t idx = fSessionId % fClients.size(); - bool connected = false; + if (fClient) + { + return; + } - try - { + size_t idx = fSessionId % fClients.size(); + bool connected = false; + + try + { connected = exeConnect(fClients.at(idx)); - } - catch (... ) - { - } - - if (!connected) - { - if (fLocalQuery) - loadClients(); - else - connectList(timeout); + } + catch (... ) + { } -} + if (!connected) + connectList(idx, timeout); -bool ClientRotator::exeConnect( const string& clientName ) -{ - fClient = new messageqcpp::MessageQueueClient( clientName, fCf); + } - if (fDebug > 12) - { - stringstream ss; + bool ClientRotator::exeConnect( const string& clientName ) + { + fClient = new messageqcpp::MessageQueueClient( clientName, fCf); + if (fDebug > 12) + { + stringstream ss; ss << fSessionId; #ifdef LOG_TO_CERR cerr << "Connecting to " << clientName << " with sessionId " << ss.str() << endl; #endif - writeToLog( __LINE__, "Connecting to " + clientName + " with sessionId " + ss.str(), 0); - } + writeToLog( __LINE__, "Connecting to " + clientName + " with sessionId " + ss.str(), 0); + } try { - if (!fClient->connect()) + if (!fClient->connect()) { delete fClient; fClient = 0; @@ -284,57 +239,55 @@ bool ClientRotator::exeConnect( const string& clientName ) return false; } return true; -} + } -void ClientRotator::connectList(double timeout) -{ - if (fClient) return; - if (fLocalQuery || fClients.empty()) - loadClients(); + void ClientRotator::connectList(size_t idx, double timeout) + { + if (fClient) return; - if (fLocalQuery) return; + if (fClients.empty()) + loadClients(); - idbassert(!fClients.empty()); - uint16_t idx = fSessionId % fClients.size(); - if (++idx >= fClients.size() ) + if (++idx >= fClients.size() ) idx = 0; - timer runTime; - while ( runTime.elapsed() < timeout) + timer runTime; + while ( runTime.elapsed() < timeout) + { + try { - try - { - if (exeConnect(fClients.at(idx++))) - return; - if (fClients.size() == idx) - idx = 0; - } - catch (... ) - { } + if (exeConnect(fClients.at(idx++))) + return; + if (fClients.size() == idx) + idx = 0; } + catch (... ) + { } + } #ifdef LOG_TO_CERR cerr << "Could not get a " << fName << " connection.\n"; #endif - writeToLog(__LINE__, "Could not get a " + fName + " connection.", 1); - throw runtime_error((string)__FILE__ + ": Could not get a connection to a " + fName); -} - -void ClientRotator::writeToLog(int line, const string& msg, bool critical) const -{ - LoggingID lid(05); - MessageLog ml(lid); - Message::Args args; - Message m(0); - args.add(__FILE__); + writeToLog(__LINE__, "Could not get a " + fName + " connection.", 1); + throw runtime_error((string)__FILE__ + ": Could not get a connection to a " + fName); + } + + void ClientRotator::writeToLog(int line, const string& msg, bool critical) const + { + LoggingID lid(05); + MessageLog ml(lid); + Message::Args args; + Message m(0); + args.add(__FILE__); args.add("@"); args.add(line); - args.add(msg); - m.format(args); + args.add(msg); + m.format(args); if (critical) - ml.logCriticalMessage(m); + ml.logCriticalMessage(m); else if (fDebug) ml.logDebugMessage(m); -} + } + } // vim:ts=4 sw=4: diff --git a/dbcon/execplan/clientrotator.h b/dbcon/execplan/clientrotator.h index acb48196..c7b1aa4a 100644 --- a/dbcon/execplan/clientrotator.h +++ b/dbcon/execplan/clientrotator.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /********************************************************************* - * $Id: clientrotator.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: clientrotator.h 8908 2012-09-18 18:50:03Z zzhu $ * * ***********************************************************************/ @@ -43,13 +43,13 @@ namespace execplan class ClientRotator { public: - /** @brief ctor + /** @brief ctor */ - ClientRotator(uint32_t sid, const std::string& name, bool localQuery=false); + ClientRotator(uint32_t sid, const std::string& name); - /** @brief dtor + /** @brief dtor */ - ~ClientRotator() + ~ClientRotator() { if (fClient) { @@ -58,22 +58,22 @@ class ClientRotator } } - /** @brief connnect - * - * Try connecting to client based on session id. If no connection, - * try connectList. - * @param timeout in seconds. - */ - void connect(double timeout=50); - - /** @brief write - * - * Write msg to fClient. If unsuccessful, get new connection with - * connectList and write. - */ - void write(const messageqcpp::ByteStream& msg); - - /** @brief shutdown + /** @brief connnect + * + * Try connecting to client based on session id. If no connection, + * try connectList. + * @param timeout in seconds. + */ + void connect(double timeout=50); + + /** @brief write + * + * Write msg to fClient. If unsuccessful, get new connection with + * connectList and write. + */ + void write(const messageqcpp::ByteStream& msg); + + /** @brief shutdown */ void shutdown() { @@ -85,76 +85,72 @@ class ClientRotator } } - /** @brief read + /** @brief read */ - messageqcpp::ByteStream read(); + messageqcpp::ByteStream read(); - /** @brief getClient + /** @brief getClient */ - messageqcpp::MessageQueueClient* getClient() const { return fClient; } + messageqcpp::MessageQueueClient* getClient() const { return fClient; } - /** @brief getSessionId + /** @brief getSessionId */ - uint32_t getSessionId() const { return fSessionId; } + uint32_t getSessionId() const { return fSessionId; } - /** @brief setSessionId + /** @brief setSessionId */ - void setSessionId(uint32_t sid) { fSessionId = sid; } - - friend std::ostream& operator<<(std::ostream& output, const ClientRotator& rhs); - - /** @brief reset fClient */ - void resetClient(); - - bool localQuery() { return fLocalQuery; } - void localQuery(bool localQuery) { fLocalQuery = localQuery; } - static std::string getModule(); - -private: - - //Not copyable - ClientRotator(const ClientRotator& ); - ClientRotator& operator=(const ClientRotator& ); - - /** @brief load Clients - * - * Put all entries for client name tag from config file into client list - */ - void loadClients(); - - /** @brief execute connect - * - * Make connection and return success. - */ - bool exeConnect(const std::string& clientName ); - - /** @brief connnect to list - * - * Try connecting to next client on list - * until timeout lapses. Then throw exception. - */ - void connectList(double timeout=0.005); - - /** @brief write to message log - * - * writes message with file name to debug or - * critical log. - */ - void writeToLog(int line, const std::string& msg, bool critical) const; - - const std::string fName; - uint32_t fSessionId; - messageqcpp::MessageQueueClient* fClient; - typedef std::vector ClientList; - ClientList fClients; - config::Config* fCf; - int fDebug; - boost::mutex fClientLock; - bool fLocalQuery; + void setSessionId(uint32_t sid) { fSessionId = sid; } + + friend std::ostream& operator<<(std::ostream& output, const ClientRotator& rhs); + + /** @brief reset fClient */ + void resetClient(); + + + private: + + //Not copyable + ClientRotator(const ClientRotator& ); + ClientRotator& operator=(const ClientRotator& ); + + /** @brief load Clients + * + * Put all entries for client name tag from config file into client list + */ + void loadClients(); + + /** @brief execute connect + * + * Make connection and return success. + */ + bool exeConnect(const std::string& clientName ); + + /** @brief connnect to list + * + * Try connecting to next client on list + * until timeout lapses. Then throw exception. + */ + void connectList(size_t idx = 0, double timeout=0.005); + + /** @brief write to message log + * + * writes message with file name to debug or + * critical log. + */ + void writeToLog(int line, const std::string& msg, bool critical) const; + + const std::string fName; + uint32_t fSessionId; + messageqcpp::MessageQueueClient* fClient; + typedef std::vector ClientList; + ClientList fClients; + config::Config* fCf; + int fDebug; + boost::mutex fClientLock; }; -} // namespace -#endif +} // namespace +#endif // vim:ts=4 sw=4: diff --git a/dbcon/execplan/columnresult.h b/dbcon/execplan/columnresult.h index 9f165d10..e8bd6bfd 100644 --- a/dbcon/execplan/columnresult.h +++ b/dbcon/execplan/columnresult.h @@ -46,13 +46,13 @@ class ColumnResult ColumnResult() : oid(0), dcount(0) { } // the other defaults are OK. - int64_t GetData(uint32_t index) const + int64_t GetData(uint index) const { return intData[index]; } void PutData(int64_t d) { intData.push_back(d); dcount++; } - const std::string& GetStringData(uint32_t index) const + const std::string& GetStringData(uint index) const { return stringData[index]; } void PutStringData(const std::string& s) @@ -64,7 +64,7 @@ class ColumnResult void SetColumnOID(int o) { oid = o; } - uint64_t GetRid(uint32_t index) const + uint64_t GetRid(uint index) const { return rids[index]; } void PutRid(uint64_t rid) diff --git a/dbcon/execplan/constantcolumn.cpp b/dbcon/execplan/constantcolumn.cpp index fce3825b..620c0fe0 100644 --- a/dbcon/execplan/constantcolumn.cpp +++ b/dbcon/execplan/constantcolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: constantcolumn.cpp 9474 2013-05-02 15:28:09Z rdempsey $ +* $Id: constantcolumn.cpp 9261 2013-02-06 20:59:01Z xlou $ * * ***********************************************************************/ @@ -31,7 +31,6 @@ using namespace std; using namespace messageqcpp; #include "dataconvert.h" -#include "calpontsystemcatalog.h" namespace execplan { /** @@ -55,14 +54,10 @@ ConstantColumn::ConstantColumn(const string& sql, TYPE type) : { memcpy(tmp, sql.c_str(), sql.length()); memset(tmp+sql.length(), 0, 8); - fResult.uintVal = uint64ToStr(*((uint64_t *) tmp)); - fResult.intVal = (int64_t)fResult.uintVal; + fResult.intVal = uint64ToStr(*((uint64_t *) tmp)); } else - { fResult.intVal = atoll(sql.c_str()); - fResult.uintVal = strtoull(sql.c_str(), NULL, 0); - } fResult.floatVal = atof(sql.c_str()); fResult.doubleVal = atof(sql.c_str()); @@ -75,14 +70,7 @@ ConstantColumn::ConstantColumn(const string& sql, TYPE type) : // @bug 3381, default null item to integer type. if (fType == ConstantColumn::NULLDATA) { - if (fResult.uintVal > (uint64_t)MAX_BIGINT) - { - fResultType.colDataType = CalpontSystemCatalog::UBIGINT; - } - else - { - fResultType.colDataType = CalpontSystemCatalog::BIGINT; - } + fResultType.colDataType = CalpontSystemCatalog::BIGINT; fResultType.colWidth = 8; } else @@ -101,7 +89,6 @@ ConstantColumn::ConstantColumn(const string& sql, const double val) : fResult.strVal = sql; fResult.doubleVal = val; fResult.intVal = (int64_t)val; - fResult.uintVal = (uint64_t)val; fResult.floatVal = (float)val; // decimal for constant should be constructed by the caller and call the decimal constructor fResult.decimalVal.value = fResult.intVal; @@ -119,7 +106,6 @@ ConstantColumn::ConstantColumn(const string& sql, const int64_t val, TYPE type) { fResult.strVal = sql; fResult.intVal = val; - fResult.uintVal = (uint64_t)fResult.intVal; fResult.floatVal = (float)fResult.intVal; fResult.doubleVal = (double)fResult.intVal; fResult.decimalVal.value = fResult.intVal; @@ -128,23 +114,6 @@ ConstantColumn::ConstantColumn(const string& sql, const int64_t val, TYPE type) fResultType.colWidth = 8; } -ConstantColumn::ConstantColumn(const string& sql, const uint64_t val, TYPE type) : - ReturnedColumn(), - fConstval(sql), - fType(type), - fData(sql) -{ - fResult.strVal = sql; - fResult.uintVal = val; - fResult.intVal = (int64_t)fResult.uintVal; - fResult.floatVal = (float)fResult.uintVal; - fResult.doubleVal = (double)fResult.uintVal; - fResult.decimalVal.value = fResult.uintVal; - fResult.decimalVal.scale = 0; - fResultType.colDataType = CalpontSystemCatalog::UBIGINT; - fResultType.colWidth = 8; -} - ConstantColumn::ConstantColumn(const string& sql, const IDB_Decimal& val) : ReturnedColumn(), fConstval(sql), @@ -152,8 +121,7 @@ ConstantColumn::ConstantColumn(const string& sql, const IDB_Decimal& val) : fData(sql) { fResult.strVal = sql; - fResult.intVal = (int64_t)atoll(sql.c_str()); - fResult.uintVal = strtoull(sql.c_str(), NULL, 0); + fResult.intVal = (int64_t)atol(sql.c_str()); fResult.floatVal = atof(sql.c_str()); fResult.doubleVal = atof(sql.c_str()); fResult.decimalVal = val; @@ -196,7 +164,6 @@ ConstantColumn::ConstantColumn(const int64_t val, TYPE type) : fData = oss.str(); fResult.strVal = fData; fResult.intVal = val; - fResult.uintVal = (uint64_t)fResult.intVal; fResult.floatVal = (float)fResult.intVal; fResult.doubleVal = (double)fResult.intVal; fResult.decimalVal.value = fResult.intVal; @@ -205,25 +172,6 @@ ConstantColumn::ConstantColumn(const int64_t val, TYPE type) : fResultType.colWidth = 8; } -ConstantColumn::ConstantColumn(const uint64_t val, TYPE type) : - ReturnedColumn(), - fType(type) -{ - ostringstream oss; - oss << val; - fConstval = oss.str(); - fData = oss.str(); - fResult.strVal = fData; - fResult.intVal = (int64_t)val; - fResult.uintVal = val; - fResult.floatVal = (float)fResult.uintVal; - fResult.doubleVal = (double)fResult.uintVal; - fResult.decimalVal.value = fResult.uintVal; - fResult.decimalVal.scale = 0; - fResultType.colDataType = CalpontSystemCatalog::UBIGINT; - fResultType.colWidth = 8; -} - ConstantColumn::~ConstantColumn() { #ifndef _MSC_VER @@ -235,7 +183,7 @@ ConstantColumn::~ConstantColumn() const string ConstantColumn::toString() const { ostringstream oss; - oss << "ConstantColumn: " << fConstval << " intVal=" << fResult.intVal << " uintVal=" << fResult.uintVal; + oss << "ConstantColumn: " << fConstval << " intVal=" << fResult.intVal; oss << '('; if (fType == LITERAL) oss << 'l'; @@ -244,7 +192,6 @@ const string ConstantColumn::toString() const else oss << "null"; oss << ')'; - oss << " resultType=" << colDataTypeToString(fResultType.colDataType); if (fAlias.length() > 0) oss << "/Alias: " << fAlias; return oss.str(); } @@ -267,12 +214,11 @@ void ConstantColumn::serialize(messageqcpp::ByteStream& b) const b << (ObjectReader::id_t) ObjectReader::CONSTANTCOLUMN; ReturnedColumn::serialize(b); b << fConstval; - b << (uint32_t) fType; + b << (u_int32_t) fType; //b << fAlias; b << fData; b << static_cast(fReturnAll); b << (uint64_t)fResult.intVal; - b << fResult.uintVal; b << (*(uint64_t*)(&fResult.doubleVal)); b << (*(uint32_t*)(&fResult.floatVal)); b << (uint8_t)fResult.boolVal; @@ -290,13 +236,15 @@ void ConstantColumn::unserialize(messageqcpp::ByteStream& b) //uint64_t val; b >> fConstval; - b >> (uint32_t&) fType; + b >> (u_int32_t&) fType; b >> fData; b >> reinterpret_cast< ByteStream::doublebyte&>(fReturnAll); b >> (uint64_t&)fResult.intVal; - b >> fResult.uintVal; + b >> (uint64_t&)fResult.doubleVal; + b >> (uint32_t&)fResult.floatVal; + b >> (uint8_t&)fResult.boolVal; b >> fResult.strVal; b >> (uint64_t&)fResult.decimalVal.value; @@ -358,4 +306,3 @@ void ConstantColumn::constructRegex() } } -// vim:ts=4 sw=4: diff --git a/dbcon/execplan/constantcolumn.h b/dbcon/execplan/constantcolumn.h index a03330e2..181809b2 100644 --- a/dbcon/execplan/constantcolumn.h +++ b/dbcon/execplan/constantcolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: constantcolumn.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: constantcolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -35,10 +35,11 @@ class ByteStream; /** * Namespace */ -namespace execplan { +namespace execplan { +class CalpontSystemCatalog; /** * @brief A class to represent a constant return column - * + * * This class is a specialization of class ReturnedColumn that * handles a constant column such as number and literal string. */ @@ -52,208 +53,114 @@ class ConstantColumn : public ReturnedColumn { NULLDATA }; - /** - * ctor - */ ConstantColumn(); - /** - * ctor - */ ConstantColumn(const std::string& sql, TYPE type = LITERAL); - /** - * ctor - */ ConstantColumn(const int64_t val, TYPE type = NUM); //deprecate - /** - * ctor - */ - ConstantColumn(const uint64_t val, TYPE type = NUM); // deprecate - //There are more ctors below... - - /** - * dtor - */ + virtual ~ConstantColumn(); - - /* - * Accessor Methods - */ + /** - * accessor + * Accessor Methods */ inline unsigned int type() const { return fType; } - /** - * accessor - */ inline void type (unsigned int type) { fType = type; } - /** - * accessor - */ inline const std::string& constval() const { return fConstval; } - /** - * accessor - */ inline void constval(const std::string& constval) { fConstval = constval; } - /** - * accessor - */ virtual const std::string data() const; - /** - * accessor - */ virtual void data(const std::string data) { fData = data; } - /** - * accessor - */ virtual const std::string toString() const; - - /** return a copy of this pointer + + /** return a copy of this pointer * * deep copy of this pointer and return the copy - */ + */ inline virtual ConstantColumn* clone() const {return new ConstantColumn (*this);} - - /* - * The serialization interface - */ + /** - * serialize + * The serialization interface */ virtual void serialize(messageqcpp::ByteStream&) const; - /** - * unserialize - */ virtual void unserialize(messageqcpp::ByteStream&); - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise - */ + */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ bool operator==(const ConstantColumn& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ bool operator!=(const ConstantColumn& t) const; - - virtual bool hasWindowFunc() {return false;} - - /** Constant column on the filte can always be moved into derived table */ - virtual void setDerivedTable() { fDerivedTable = "*"; } - + private: std::string fConstval; - int fType; - std::string fData; - + int fType; + std::string fData; + /*********************************************************** * F&E framework * ***********************************************************/ -public: - /** - * ctor - */ +public: ConstantColumn(const std::string& sql, const double val); - /** - * ctor - */ ConstantColumn(const std::string& sql, const int64_t val, TYPE type = NUM); - /** - * ctor - */ - ConstantColumn(const std::string& sql, const uint64_t val, TYPE type = NUM); - /** - * ctor - */ ConstantColumn(const std::string& sql, const IDB_Decimal& val); - /** - * copy ctor - */ ConstantColumn(const ConstantColumn& rhs); - /** - * F&E - */ virtual void evaluate(rowgroup::Row& row) {} - /** - * F&E - */ virtual void constructRegex(); - /** - * F&E - */ + virtual bool getBoolVal(rowgroup::Row& row, bool& isNull) { isNull = isNull || (fType == NULLDATA); - return TreeNode::getBoolVal(); + return TreeNode::getBoolVal(); } - /** - * F&E - */ - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) - { + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull) + { isNull = isNull || (fType == NULLDATA); - return fResult.strVal; + return fResult.strVal; } - /** - * F&E - */ - virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { + + virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) + { isNull = isNull || (fType == NULLDATA); return fResult.intVal; } - /** - * F&E - */ - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { - isNull = isNull || (fType == NULLDATA); - return fResult.uintVal; - } - /** - * F&E - */ + virtual float getFloatVal(rowgroup::Row& row, bool& isNull) { isNull = isNull || (fType == NULLDATA); return fResult.floatVal; } - /** - * F&E - */ - virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) + + virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) { isNull = isNull || (fType == NULLDATA); - return fResult.doubleVal; + return fResult.doubleVal; } - /** - * F&E - */ + virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) { isNull = isNull || (fType == NULLDATA); return fResult.decimalVal; } - /** - * F&E - */ + virtual int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) { isNull = isNull || (fType == NULLDATA); @@ -264,9 +171,7 @@ class ConstantColumn : public ReturnedColumn { } return fResult.intVal; } - /** - * F&E - */ + virtual int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) { isNull = isNull || (fType == NULLDATA); @@ -277,13 +182,9 @@ class ConstantColumn : public ReturnedColumn { } return fResult.intVal; } - /** - * F&E - */ + inline float getFloatVal() const { return fResult.floatVal; } - /** - * F&E - */ + inline double getDoubleVal() const { return fResult.doubleVal; } }; @@ -293,6 +194,6 @@ class ConstantColumn : public ReturnedColumn { */ std::ostream& operator<<(std::ostream& output, const ConstantColumn& rhs); -} +} #endif //CONSTANTCOLUMN_H diff --git a/dbcon/execplan/constantfilter.cpp b/dbcon/execplan/constantfilter.cpp index 79e79773..3ddd9131 100644 --- a/dbcon/execplan/constantfilter.cpp +++ b/dbcon/execplan/constantfilter.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: constantfilter.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: constantfilter.cpp 8526 2012-05-17 02:28:10Z xlou $ * * ***********************************************************************/ @@ -35,7 +35,6 @@ using namespace std; #include "bytestream.h" #include "objectreader.h" #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" namespace { template struct deleter : public unary_function @@ -54,41 +53,34 @@ ConstantFilter::ConstantFilter() ConstantFilter::ConstantFilter(const SOP& op, ReturnedColumn* lhs, ReturnedColumn* rhs) { - SSFP ssfp(new SimpleFilter(op, lhs, rhs)); - fFilterList.push_back(ssfp); - SimpleColumn* sc = dynamic_cast(lhs); - fCol.reset(sc->clone()); + SSFP ssfp(new SimpleFilter(op, lhs, rhs)); + fFilterList.push_back(ssfp); + SimpleColumn* sc = dynamic_cast(lhs); + fCol.reset(sc->clone()); } ConstantFilter::ConstantFilter(SimpleFilter* sf) { - SSFP ssfp(sf); - fFilterList.push_back(ssfp); - const SimpleColumn* sc = dynamic_cast(sf->lhs()); - fCol.reset(sc->clone()); + SSFP ssfp(sf); + fFilterList.push_back(ssfp); + const SimpleColumn* sc = dynamic_cast(sf->lhs()); + fCol.reset(sc->clone()); } -ConstantFilter::ConstantFilter(const ConstantFilter& rhs): +ConstantFilter::ConstantFilter(const ConstantFilter& rhs): fOp(rhs.fOp), fCol(rhs.fCol) { fFilterList.clear(); fSimpleColumnList.clear(); - fWindowFunctionColumnList.clear(); SSFP ssfp; - for (uint32_t i = 0; i < rhs.fFilterList.size(); i++) + for (uint i = 0; i < rhs.fFilterList.size(); i++) { ssfp.reset(rhs.fFilterList[i]->clone()); fFilterList.push_back(ssfp); - fSimpleColumnList.insert(fSimpleColumnList.end(), - ssfp->simpleColumnList().begin(), - ssfp->simpleColumnList().end()); - fAggColumnList.insert(fAggColumnList.end(), - ssfp->aggColumnList().begin(), - ssfp->aggColumnList().end()); - fWindowFunctionColumnList.insert(fWindowFunctionColumnList.end(), - ssfp->windowfunctionColumnList().begin(), - ssfp->windowfunctionColumnList().end()); + fSimpleColumnList.insert(fSimpleColumnList.end(), + ssfp->simpleColumnList().begin(), + ssfp->simpleColumnList().end()); } } @@ -99,7 +91,7 @@ ConstantFilter::~ConstantFilter() /** * Methods */ - + const string ConstantFilter::toString() const { ostringstream output; @@ -107,31 +99,34 @@ const string ConstantFilter::toString() const if (fOp) output << " " << *fOp << endl; if (!fFunctionName.empty()) output << " Func: " << fFunctionName << endl; if (fCol) output << " " << *fCol << endl; - for (unsigned int i = 0; idata(); + // if (fFilterList.size() != 0) + // return string(out + " " + fFilterList.front()->lhs()->data()); + // return "ConstantFilter"; + //return fData; +//} + ostream& operator<<(ostream& output, const ConstantFilter& rhs) { + /* + output << rhs.op()->toString() << endl; + output << rhs.col()->toString() << endl; + for (unsigned int i = 0; i < rhs.filterList().size(); i++) + output << rhs.filterList()[i]->toString() << endl; + return output;*/ output << rhs.toString(); return output; } -bool ConstantFilter::hasAggregate() -{ - fAggColumnList.clear(); - for (uint32_t i = 0; i < fFilterList.size(); i++) - { - if (fFilterList[i]->hasAggregate()) - { - return true; - } - } - return false; -} - void ConstantFilter::serialize(messageqcpp::ByteStream& b) const { FilterList::const_iterator it; @@ -142,42 +137,38 @@ void ConstantFilter::serialize(messageqcpp::ByteStream& b) const else b << static_cast(ObjectReader::NULL_CLASS); if (fCol != NULL) - fCol->serialize(b); - else - b << static_cast(ObjectReader::NULL_CLASS); - b << static_cast(fFilterList.size()); + fCol->serialize(b); + else + b << static_cast(ObjectReader::NULL_CLASS); + b << static_cast(fFilterList.size()); for (it = fFilterList.begin(); it != fFilterList.end(); it++) (*it)->serialize(b); b << fFunctionName; } - + void ConstantFilter::unserialize(messageqcpp::ByteStream& b) { - uint32_t size, i; + u_int32_t size, i; ObjectReader::checkType(b, ObjectReader::CONSTANTFILTER); - SimpleFilter *sf; - + SimpleFilter *sc; + Filter::unserialize(b); fOp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); - fCol.reset(dynamic_cast(ObjectReader::createTreeNode(b))); + fCol.reset(dynamic_cast(ObjectReader::createTreeNode(b))); b >> size; fFilterList.clear(); fSimpleColumnList.clear(); fAggColumnList.clear(); - fWindowFunctionColumnList.clear(); for (i = 0; i < size; i++) { - sf = dynamic_cast(ObjectReader::createTreeNode(b)); - SSFP ssfp(sf); + sc = dynamic_cast(ObjectReader::createTreeNode(b)); + SSFP ssfp(sc); fFilterList.push_back(ssfp); - fSimpleColumnList.insert(fSimpleColumnList.end(), - ssfp->simpleColumnList().begin(), - ssfp->simpleColumnList().end()); - fAggColumnList.insert(fAggColumnList.end(), - ssfp->aggColumnList().begin(), - ssfp->aggColumnList().end()); - fWindowFunctionColumnList.insert(fWindowFunctionColumnList.end(), - ssfp->windowfunctionColumnList().begin(), - ssfp->windowfunctionColumnList().end()); + fSimpleColumnList.insert(fSimpleColumnList.end(), + ssfp->simpleColumnList().begin(), + ssfp->simpleColumnList().end()); + fAggColumnList.insert(fAggColumnList.end(), + ssfp->aggColumnList().begin(), + ssfp->aggColumnList().end()); } b >> fFunctionName; } @@ -191,24 +182,24 @@ bool ConstantFilter::operator==(const ConstantFilter& t) const f2 = static_cast(&t); if (*f1 != *f2) return false; - + if (fOp != NULL) { if (*fOp != *t.fOp) return false; } else if (t.fOp != NULL) return false; - + //fFilterList if (fFilterList.size() != t.fFilterList.size()) return false; for (it = fFilterList.begin(), it2 = t.fFilterList.begin(); it != fFilterList.end(); ++it, ++it2) - { - if (**it != **it2) - return false; - } - + { + if (**it != **it2) + return false; + } + return true; } @@ -232,41 +223,31 @@ bool ConstantFilter::operator!=(const TreeNode* t) const return (!(*this == t)); } -void ConstantFilter::setDerivedTable() -{ - if (fCol->hasAggregate()) - { - fDerivedTable = ""; - return; - } - fDerivedTable = fCol->derivedTable(); +Filter* ConstantFilter::combinable(Filter* f, Operator *op) +{ + if (typeid(*f) == typeid(SimpleFilter)) + { + SimpleFilter *sf = dynamic_cast(f); + return sf->combinable(this, op); + } + + // constant filter may have NULL fOp, when it's equalivant to a pure simple filter + if (typeid(ConstantFilter) == typeid(*f) && + (!fOp || fOp->data().compare(op->data()) == 0 )) + { + ConstantFilter *cf = dynamic_cast(f); + if (cf && ( !cf->op() || !fOp || fOp->data().compare(cf->op()->data()) == 0 ) + && fCol->sameColumn(cf->col().get())) + { + for (unsigned int i = 0; i < cf->filterList().size(); i++) + fFilterList.push_back(cf->filterList()[i]); + fOp.reset(op); + return this; + } + } + + return NULL; } -void ConstantFilter::replaceRealCol(std::vector& derivedColList) -{ - ReturnedColumn* tmp = derivedColList[fCol->colPosition()]->clone(); - fCol.reset(tmp); - for (unsigned i = 0; i < fFilterList.size(); i++) - fFilterList[i]->replaceRealCol(derivedColList); -} - -const std::vector& ConstantFilter::simpleColumnList() -{ - return fSimpleColumnList; -} - -void ConstantFilter::setSimpleColumnList() -{ - fSimpleColumnList.clear(); - for (uint32_t i = 0; i < fFilterList.size(); i++) - { - fFilterList[i]->setSimpleColumnList(); - fSimpleColumnList.insert(fSimpleColumnList.end(), - fFilterList[i]->simpleColumnList().begin(), - fFilterList[i]->simpleColumnList().end()); - } -} - - } // namespace execplan // vim:ts=4 sw=4: diff --git a/dbcon/execplan/constantfilter.h b/dbcon/execplan/constantfilter.h index 6924085b..92c11620 100644 --- a/dbcon/execplan/constantfilter.h +++ b/dbcon/execplan/constantfilter.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: constantfilter.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: constantfilter.h 8816 2012-08-15 18:51:49Z dhall $ * * ***********************************************************************/ @@ -36,12 +36,11 @@ /** * Namespace */ -namespace execplan { +namespace execplan { class ReturnedColumn; class AggregateColumn; -class WindowFunctionColumn; - + /** * @brief A class to represent a simple column op constant predicate * @@ -51,7 +50,7 @@ class WindowFunctionColumn; * same column. All the simple filters are connected by the same * operator (either "and" or "or"). This class is introduced for * easy operation combine for primitive processor. - */ + */ class ConstantFilter : public Filter { public: @@ -69,12 +68,12 @@ class ConstantFilter : public Filter { //not needed yet //ConstantFilter(const ConstantFilter& rhs); - + /** * Destructors */ virtual ~ConstantFilter(); - + /** * Accessor Methods */ @@ -82,14 +81,14 @@ class ConstantFilter : public Filter { void filterList( const FilterList& filterList) {fFilterList = filterList; } const SOP& op() const {return fOp;} void op(const SOP& op){fOp = op;} - const SRCP& col() const {return fCol;} - void col(const SRCP& col) {fCol = col;} - + const SSC& col() const {return fCol;} + void col(const SSC& col) {fCol = col;} + /** * Operations */ - void pushFilter (SimpleFilter* sf) {SSFP ssfp(sf); fFilterList.push_back(ssfp);} - + void pushFilter (SimpleFilter* sf) {SSFP ssfp(sf); fFilterList.push_back(ssfp);} + //virtual const std::string data() const; virtual const std::string toString() const; @@ -98,35 +97,35 @@ class ConstantFilter : public Filter { */ virtual void serialize(messageqcpp::ByteStream&) const; virtual void unserialize(messageqcpp::ByteStream&); - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ bool operator==(const ConstantFilter& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ bool operator!=(const ConstantFilter& t) const; - + /** @brief test if this filter can be combined with the argument filter * This is for operation combine optimization * @param f the filter that this fiter tries to combine with @@ -135,8 +134,7 @@ class ConstantFilter : public Filter { * @return a filter(constantfilter) if successfully combined. otherwise * return NULL */ - // Used by Oracle frontend, deprecated now. - //virtual Filter* combinable(Filter* f, Operator* op); + virtual Filter* combinable(Filter* f, Operator* op); /** get function name * @@ -150,16 +148,12 @@ class ConstantFilter : public Filter { */ void functionName(const std::string& functionName) { fFunctionName = functionName; } - void setDerivedTable(); - virtual void replaceRealCol(std::vector&); - virtual bool hasAggregate(); - private: - SOP fOp; /// connect operator (and or) + SOP fOp; /// connect operator (and or) FilterList fFilterList; /// vector of simple filters - SRCP fCol; /// the common column + SSC fCol; /// the common column std::string fFunctionName; /// function name - + /*********************************************************** * F&E framework * ***********************************************************/ @@ -169,21 +163,18 @@ class ConstantFilter : public Filter { { return new ConstantFilter (*this); } - - inline virtual bool getBoolVal(rowgroup::Row& row, bool& isNull); - + + inline virtual bool getBoolVal(rowgroup::Row& row, bool& isNull); + // get all simple columns involved in this column - const std::vector& simpleColumnList(); - // walk through the constant filter operands to re-populate fSimpleColumnList - void setSimpleColumnList(); - + const std::vector& simpleColumnList() const { return fSimpleColumnList; } + // get all aggregate columns involved in this column const std::vector& aggColumnList() const { return fAggColumnList; } private: - std::vector fSimpleColumnList; - std::vector fAggColumnList; - std::vector fWindowFunctionColumnList; + std::vector fSimpleColumnList; + std::vector fAggColumnList; }; inline bool ConstantFilter::getBoolVal(rowgroup::Row& row, bool& isNull) @@ -191,12 +182,12 @@ inline bool ConstantFilter::getBoolVal(rowgroup::Row& row, bool& isNull) switch(fOp->op()) { case OP_AND: - for (uint32_t i = 0; i < fFilterList.size(); i++) + for (uint i = 0; i < fFilterList.size(); i++) if (!fFilterList[i]->getBoolVal(row, isNull)) return false; return true; case OP_OR: - for (uint32_t i = 0; i < fFilterList.size(); i++) + for (uint i = 0; i < fFilterList.size(); i++) if (fFilterList[i]->getBoolVal(row, isNull)) return true; return false; @@ -208,9 +199,9 @@ inline bool ConstantFilter::getBoolVal(rowgroup::Row& row, bool& isNull) } } } - + std::ostream& operator<<(std::ostream& output, const ConstantFilter& rhs); -} +} #endif //CONSTANTFILTER_H diff --git a/dbcon/execplan/existsfilter.cpp b/dbcon/execplan/existsfilter.cpp index 6e0185d8..0100ae16 100644 --- a/dbcon/execplan/existsfilter.cpp +++ b/dbcon/execplan/existsfilter.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: existsfilter.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: existsfilter.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/existsfilter.h b/dbcon/execplan/existsfilter.h index 924010b2..447fcb51 100644 --- a/dbcon/execplan/existsfilter.h +++ b/dbcon/execplan/existsfilter.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: existsfilter.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: existsfilter.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/exp_templates.h b/dbcon/execplan/exp_templates.h index 5f998963..00100f3d 100644 --- a/dbcon/execplan/exp_templates.h +++ b/dbcon/execplan/exp_templates.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: exp_templates.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: exp_templates.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -569,11 +569,7 @@ namespace expression { Operand parse(InputIterator first, InputIterator last) { try { -#if _MSC_VER > 1600 - return std::_Copy_impl(first, last, start());} -#else return std::copy(first, last, start());} -#endif catch (const std::runtime_error&) { m_policy.cleanup(operandStack, operatorStack); throw; diff --git a/dbcon/execplan/expressionparser.cpp b/dbcon/execplan/expressionparser.cpp index c6a00183..191d1f24 100644 --- a/dbcon/execplan/expressionparser.cpp +++ b/dbcon/execplan/expressionparser.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: expressionparser.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: expressionparser.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -45,9 +45,8 @@ ExpressionParser::~ExpressionParser() void ExpressionParser::invalid_operator_position(TreeNode* oper) { - std::string str = oper->data(); delete oper; - throw std::runtime_error ("Invalid operator position: " + str + "\n"); + throw std::runtime_error ("Invalid operator position: " + oper->data() + "\n"); } void ExpressionParser::invalid_operator_position(const Token& oper) diff --git a/dbcon/execplan/expressionparser.h b/dbcon/execplan/expressionparser.h index 0c1e92d3..a5ca5d4a 100644 --- a/dbcon/execplan/expressionparser.h +++ b/dbcon/execplan/expressionparser.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: expressionparser.h 9633 2013-06-19 13:36:01Z rdempsey $ +* $Id: expressionparser.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -42,6 +42,7 @@ namespace execplan { /** * type define */ +//typedef ExpressionTree ParseTree; typedef std::stack OperandStack; typedef std::stack OperatorStack; diff --git a/dbcon/execplan/expressiontree.h b/dbcon/execplan/expressiontree.h new file mode 100644 index 00000000..39755bd8 --- /dev/null +++ b/dbcon/execplan/expressiontree.h @@ -0,0 +1,382 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: expressiontree.h 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ +/** @file */ + +#ifndef EXPRESSIONTREE_H +#define EXPRESSIONTREE_H + +#include +#include +#include "treenode.h" + +namespace rowgroup { + class Row; +} + +namespace execplan { + +/** + * @brief A template class template to represent an expression tree + * + * This class is a simple binary tree implementation which + * represents an expression tree. The expression can be used + * for both arithmetic and logical expression. + * Please note that to use this template class T can only be pointers. + */ + +template +class ExpressionTree +{ + +public: + /** + * Constructor / Destructor + */ + ExpressionTree(); + ExpressionTree(const T& data); + ExpressionTree(const ExpressionTree& rhs); + virtual ~ExpressionTree(); + + /** + * Access methods + */ + inline void left(ExpressionTree* expressionTree) + { fLeft = expressionTree; } + + inline const ExpressionTree* left() const + { return fLeft; } + + inline void right(ExpressionTree* expressionTree) + { fRight = expressionTree; } + + inline const ExpressionTree* right() const + { return fRight; } + + inline void data(const T& data) + { fData = data; } + + inline const T& data() const + { return fData; } + + /** walk the tree + * + * postfix walking of a const tree + */ + void walk(void (*fn)( ExpressionTree*& n)) const; + + /** walk the tree + * + * postfix walking of a non-const tree. This is for deleting the tree + */ + void walk(void (*fn)( const ExpressionTree* n)) const; + + /** output the tree + * + * take ostream argument to walk and output the tree + */ + void walk(void (*fn)(const ExpressionTree* n, std::ostream& output), std::ostream& output) const; + + /** output the tree + * + * take user argument to walk and output the tree + */ + void walk(void (*fn)(const ExpressionTree* n, void* obj), void* object) const; + + /** output the tree + * + * take user argument to walk and output the tree + */ + void walk(void (*fn)(ExpressionTree* n, void* obj), void* object) const; + + /** assignment operator + * + */ + ExpressionTree& operator=(const ExpressionTree& rhs); + + /** deep copy of a tree + * + * copy src tree on top of dest tree. Dest tree is destroyed before copy + * takes place. Src tree still owns the tree data, though. Assume tree node + * are pointers. + */ + void copyTree (const ExpressionTree &src); + + /** destroy a tree + * + * destroy a tree where tree nodes are pointers + */ + inline void destroyPointerTree () { walk (deleter); } + + /** destroy a tree + * + * destroy a tree where tree nodes are values + */ + static void destroyTree (ExpressionTree *root); + + /** draw the tree using dot + * + * this function is mostly for debug purpose, where T represent a TreeNode + * pointer + */ + void drawTree(std::string filename); + + /** print the tree + * + * this function is mostly for debug purpose, where T represent a TreeNode + * pointer + */ + inline static void print(const ExpressionTree* n, std::ostream& output) + { + output << *n->data() << std::endl; + } + + /** delete treenode + * + * delete fData of a tree node, and then delete the treenode + */ + inline static void deleter( ExpressionTree*& n) + { + delete n->fData; + n->fData = 0; + delete n; + n = 0; + } + + // F&E framework. Tree nodes are only TreeNode* + //void evaluate (rowgroup::Row& row) {} + std::string getStrVal(rowgroup::Row& row) + { + evaluate(row); + return (reinterpret_cast(fData))->getStrVal(row); + } + int64_t getIntVal(rowgroup::Row& row) + { + evaluate(row); + return (reinterpret_cast(fData))->getIntVal(row); + } + float getFloatVal(rowgroup::Row& row) + { + evaluate(row); + return (reinterpret_cast(fData))->getFloatVal(row); + } + double getDoubleVal(rowgroup::Row& row) + { + evaluate(row); + return (reinterpret_cast(fData))->getDoubleVal(row); + } + IDB_Decimal& getDecimalVal(rowgroup::Row& row) + { + evaluate(row); + return (reinterpret_cast(fData))->getDecimalVal(row); + } + bool getBoolVal(rowgroup::Row& row) + { + evaluate(row); + return (reinterpret_cast(fData))->getBoolVal(row); + } + +private: + T fData; + ExpressionTree* fLeft; + ExpressionTree* fRight; + + /** draw the tree + * + * this function is used by draw tree to print out dot file + */ + static void draw(const ExpressionTree* n, std::ostream& dotFile); + // F&E framework + void evaluate (rowgroup::Row& row); + +}; + +/** + * Class Definition + */ +template +ExpressionTree::ExpressionTree() : + fData(), fLeft(0), fRight(0) + +{ +} + +template +ExpressionTree::ExpressionTree(const T& data) : + fData(data), fLeft(0), fRight(0) +{ +} + +template +ExpressionTree::ExpressionTree(const ExpressionTree& rhs): + fData(), fLeft(0), fRight(0) +{ + copyTree(rhs); +} + +template +ExpressionTree::~ExpressionTree() +{ +} + +template +void ExpressionTree::walk(void (*fn)( ExpressionTree*& n)) const +{ + if (fLeft != 0) fLeft->walk(fn); + if (fRight != 0) fRight->walk(fn); + ExpressionTree* temp = const_cast*>(this); + fn (temp); +} + +template +void ExpressionTree::walk(void (*fn)( const ExpressionTree* n)) const +{ + if (fLeft != 0) fLeft->walk(fn); + if (fRight != 0) fRight->walk(fn); + fn (this); +} + +template +void ExpressionTree::walk(void (*fn)(const ExpressionTree* n, std::ostream& output), std::ostream& output) const +{ + if (fLeft != 0) fLeft->walk(fn, output); + if (fRight != 0) fRight->walk(fn, output); + fn(this, output); +} + +template +void ExpressionTree::walk(void (*fn)(const ExpressionTree* n, void* obj), void* obj) const +{ + if (fLeft != 0) fLeft->walk(fn, obj); + if (fRight != 0) fRight->walk(fn, obj); + fn(this, obj); +} + +template +void ExpressionTree::walk(void (*fn)(ExpressionTree* n, void* obj), void* obj) const +{ + if (fLeft != 0) fLeft->walk(fn, obj); + if (fRight != 0) fRight->walk(fn, obj); + fn(const_cast*>(this), obj); +} + +template +ExpressionTree& ExpressionTree::operator=(const ExpressionTree& rhs) +{ + if (this != &rhs) + { + copyTree(*this, rhs); + } + return *this; +} + +template +void ExpressionTree::copyTree(const ExpressionTree &src) +{ + if (fLeft != NULL) + fLeft->destroyPointerTree(); + if (fRight != NULL) + fRight->destroyPointerTree(); + fLeft = NULL; + fRight = NULL; + + if (src.left() != NULL) + { + fLeft = new ExpressionTree(); + fLeft->copyTree(*(src.left())); + } + if (src.right() != NULL) + { + fRight = new ExpressionTree(); + fRight->copyTree(*(src.right())); + } + + delete fData; + if (src.data() == NULL) + fData = NULL; + else + fData = src.data()->clone(); +} + +template +void ExpressionTree::destroyTree(ExpressionTree* root) +{ + if (root == NULL) + return; + if (root->left() != NULL) + { + destroyTree (root->fLeft); + } + if (root->right() != NULL) + { + destroyTree (root->fRight); + } + delete root; + root = 0; +} + +template +void ExpressionTree::draw(const ExpressionTree* n, std::ostream& dotFile) +{ + const ExpressionTree* r; + const ExpressionTree* l; + l = n->left(); + r = n->right(); + + if (l != 0) + dotFile << "n" << (u_long)n << " -> " << "n" << (u_long)l << std::endl; + if (r != 0) + dotFile << "n" << (u_long)n << " -> " << "n" << (u_long)r << std::endl; + dotFile << "n" << (u_long)n << " [label=\"" + << n->data()->data() << "\"]" << std::endl; +} + +template +void ExpressionTree::drawTree(std::string filename) +{ + std::ofstream dotFile (filename.c_str(), std::ios::out); + + dotFile << "digraph G {" << std::endl; + walk (draw, dotFile); + dotFile << "}" << std::endl; + + dotFile.close(); +} + +template +void ExpressionTree::evaluate(rowgroup::Row& row) +{ + // Non-leaf node is operator. leaf node is SimpleFilter for logical expression, + // or ReturnedColumn for arithmetical expression. + if (fLight && fRight) + { + Operator* = reinterpret_cast(fData); + } + if (!fLight && !fRight) + { + + } +} + +} // namespace + +#endif diff --git a/dbcon/execplan/filter.cpp b/dbcon/execplan/filter.cpp index 386acd25..62145211 100644 --- a/dbcon/execplan/filter.cpp +++ b/dbcon/execplan/filter.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: filter.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: filter.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -97,6 +97,17 @@ bool Filter::operator!=(const TreeNode* t) const return (!(*this == t)); } +Filter* Filter::combinable(Filter* f, Operator* op) +{ + SimpleFilter *sf = dynamic_cast(f); + if (sf) + return sf->combinable(this, op); + ConstantFilter *cf = dynamic_cast(f); + if (cf) + return cf->combinable(this, op); + return NULL; +} + /** * Friend function */ diff --git a/dbcon/execplan/filter.h b/dbcon/execplan/filter.h index 74b4cc0b..09db61ce 100644 --- a/dbcon/execplan/filter.h +++ b/dbcon/execplan/filter.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: filter.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: filter.h 8816 2012-08-15 18:51:49Z dhall $ * * ***********************************************************************/ @@ -36,12 +36,12 @@ class ByteStream; /** * Namespace */ -namespace execplan { +namespace execplan { class Operator; /** @brief A class to represent a generic filter predicate - * + * * ******************************* Abstract Class **************************** * Filter does not have any pure virtual methods, but its author * defined it as an abstract class, so you should not use it directly. @@ -63,7 +63,7 @@ class Filter : public TreeNode { Filter(const std::string& sql); // not needed yet //Filter(const Filter& rhs); - + /** * Destructors */ @@ -71,7 +71,7 @@ class Filter : public TreeNode { /** * Accessor Methods */ - + /** * Operations */ @@ -79,50 +79,50 @@ class Filter : public TreeNode { virtual const std::string data() const { return fData; } virtual void data(const std::string data) { fData = data; } - + /** return a copy of this pointer * * deep copy of this pointer and return the copy - */ + */ inline virtual Filter* clone() const { return new Filter (*this); - } - + } + /** * The serialization interface */ - virtual void serialize(messageqcpp::ByteStream&) const; - virtual void unserialize(messageqcpp::ByteStream&); + virtual void serialize(messageqcpp::ByteStream&) const; + virtual void unserialize(messageqcpp::ByteStream&); /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ - virtual bool operator==(const TreeNode* t) const; - + virtual bool operator==(const TreeNode* t) const; + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ - bool operator==(const Filter& t) const; - + bool operator==(const Filter& t) const; + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ - virtual bool operator!=(const TreeNode* t) const; - + virtual bool operator!=(const TreeNode* t) const; + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ - bool operator!=(const Filter& t) const; - + bool operator!=(const Filter& t) const; + /** @brief test if this filter can be combined with the argument filter * This is for operation combine optimization * @param f the filter that this fiter tries to combine with @@ -130,15 +130,14 @@ class Filter : public TreeNode { * two filters is constantFilter, need to make sure operator is consistant. * @return a filter(constantfilter) if successfully combined. otherwise * return NULL - * For Oracle front end. Deprecated now. */ - //virtual Filter* combinable(Filter* f, Operator* op); - virtual uint64_t cardinality () const { return fCardinality; } - virtual void cardinality (const uint64_t cardinality) { fCardinality = cardinality;} - + virtual Filter* combinable(Filter* f, Operator* op); + virtual uint64_t cardinality () const { return fCardinality; } + virtual void cardinality (const uint64_t cardinality) { fCardinality = cardinality;} + protected: uint64_t fCardinality; - + private: //default okay //Filter& operator=(const Filter& rhs); @@ -149,6 +148,6 @@ class Filter : public TreeNode { std::ostream& operator<<(std::ostream& os, const Filter& rhs); -} +} #endif //EXECPLAN_FILTER_H diff --git a/dbcon/execplan/functioncolumn.cpp b/dbcon/execplan/functioncolumn.cpp index 2316557a..3d9007e7 100644 --- a/dbcon/execplan/functioncolumn.cpp +++ b/dbcon/execplan/functioncolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: functioncolumn.cpp 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: functioncolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -38,7 +38,6 @@ using namespace boost; #include "calpontselectexecutionplan.h" #include "simplefilter.h" #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" #include "funcexp.h" #include "functor_export.h" @@ -55,43 +54,36 @@ namespace execplan { FunctionColumn::FunctionColumn() {} -FunctionColumn::FunctionColumn(string& funcName): - fFunctionName(funcName) -{} - -FunctionColumn::FunctionColumn(const string& functionName, const string& funcParmsInString, const uint32_t sessionID): - ReturnedColumn(sessionID), - fFunctionName(functionName), - fData (functionName + "(" + funcParmsInString + ")"), - fFunctor(0) +FunctionColumn::FunctionColumn(const string& functionName, const string& funcParmsInString, const u_int32_t sessionID): + ReturnedColumn(sessionID), + fFunctionName(functionName), + fData (functionName + "(" + funcParmsInString + ")"), + fFunctor(0) { - funcParms (funcParmsInString); + functionParms (funcParmsInString); } -FunctionColumn::FunctionColumn( const FunctionColumn& rhs, const uint32_t sessionID): - ReturnedColumn(rhs, sessionID), - fFunctionName(rhs.functionName()), - fTableAlias (rhs.tableAlias()), - fData (rhs.data()), - fFunctor(rhs.fFunctor) +FunctionColumn::FunctionColumn( const FunctionColumn& rhs, const u_int32_t sessionID): + ReturnedColumn(rhs, sessionID), + fFunctionName(rhs.functionName()), + fTableAlias (rhs.tableAlias()), + fData (rhs.data()), + fFunctor(rhs.fFunctor) { fFunctionParms.clear(); fSimpleColumnList.clear(); fAggColumnList.clear(); - fWindowFunctionColumnList.clear(); - SPTP pt; - - for (uint32_t i = 0; i < rhs.fFunctionParms.size(); i++) + + for (uint i = 0; i < rhs.fFunctionParms.size(); i++) { pt.reset(new ParseTree (*(rhs.fFunctionParms[i]))); fFunctionParms.push_back(pt); pt->walk(getSimpleCols, &fSimpleColumnList); pt->walk(getAggCols, &fAggColumnList); - pt->walk(getWindowFunctionCols, &fWindowFunctionColumnList); } fAlias = rhs.alias(); -} +} FunctionColumn::~FunctionColumn() {} @@ -108,15 +100,14 @@ ostream& operator<<(ostream& output, const FunctionColumn& rhs) const string FunctionColumn::toString() const { - ostringstream output; + ostringstream output; output << "FunctionColumn: " << fFunctionName << endl; if (fAlias.length() > 0) output << "/Alias: " << fAlias; output << "expressionId=" << fExpressionId << endl; - output << "joinInfo=" << fJoinInfo << " returnAll=" << fReturnAll << " sequence#=" << fSequence << endl; - output << "resultType=" << colDataTypeToString(fResultType.colDataType) << "|" << fResultType.colWidth << endl; - output << "operationType=" << colDataTypeToString(fOperationType.colDataType) << endl; + output << "resultType=" << fResultType.colDataType << "|" << fResultType.colWidth << endl; + output << "operationType=" << fOperationType.colDataType << endl; output << "function parm: " << endl; - for (uint32_t i = 0; i < fFunctionParms.size(); i++) + for (uint i = 0; i < fFunctionParms.size(); i++) output << fFunctionParms[i]->data()->toString() << endl; return output.str(); } @@ -126,163 +117,162 @@ const string FunctionColumn::data() const return fData; } -void FunctionColumn::funcParms (const string& funcParmsInString) +void FunctionColumn::functionParms (const string& funcParmsInString) { - // special process to interval function. make the passed in string one literal constant - if (fFunctionName.compare("interval") == 0) - { - SPTP sptp(new ParseTree(new ConstantColumn(funcParmsInString, ConstantColumn::LITERAL))); - fFunctionParms.push_back(sptp); - return; - } - - // try to replace the comma and space in '' to avoid string conflict - // @bug #396 for space delimited function arguments. - string funcParam = funcParmsInString; - string::size_type pos1 = 0; - string::size_type pos2 = 0; - string::size_type pos3 = 0; - while (pos2 < funcParam.length() && pos1 != string::npos) - { - pos1 = funcParam.find_first_of("'", pos2); - pos2 = funcParam.find_first_of("'", pos1+1); - pos3 = funcParam.find_first_of(", ", pos1); - if (pos3 < pos2) - { - if (funcParam[pos3] == ',') - funcParam.replace(pos3, 1, "^"); - else if (funcParam[pos3] == ' ') - funcParam[pos3] = 0x1f; // special char to replace space in quotes - } - pos2++; - } - - // also replace the comma and space in () to avoid function conflict - unsigned int par = 0; - for (unsigned int i = 0; i < funcParam.length(); i++) - { - if (funcParam[i] == '(') - par++; - if (funcParam[i] == ')') - par--; - if (funcParam[i] == ',' && par != 0) - funcParam.replace(i, 1, "^"); - if (funcParam[i] == ' ' && par != 0) - funcParam[i] = 0x1f; - } - - typedef boost::tokenizer > tokenizer; - boost::char_separator sep(", "); - tokenizer tokens(funcParam, sep); - - for (tokenizer::iterator tok_iter = tokens.begin(); - tok_iter != tokens.end(); ++tok_iter) - { - string tok = (*tok_iter); - // remove the to_upper line. don't know why have it in the first place. for bug #320 - //to_upper(tok); - - // take off the trailing and ending spaces - std::string::size_type first = tok.find_first_not_of(" "); - tok = tok.substr(first, tok.find_last_not_of(" ")-first+1); - - // recover '^' to ',' and recover 0x1f to ' ' - for (unsigned int i = 0; i < tok.length(); i++) - { - if (tok[i] == '^') tok[i] = ','; - if (tok[i] == 0x1f) tok[i] = ' '; - } - - // parse argument - if (tok[0] == '\'' && tok[tok.length()-1] == '\'') - { - // take off quotes - first = tok.find_first_not_of("'"); - tok = tok.substr(first, tok.find_last_not_of("'")-first+1); - SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::LITERAL))); - fFunctionParms.push_back(cc); - } - else if (tok.find("+", 0) != string::npos || - tok.find("-", 0) != string::npos || - tok.find("*", 0) != string::npos || - tok.find("/", 0) != string::npos || - tok.find("^", 0) != string::npos || - tok.find("(", 0) != string::npos || - tok.find(")", 0) != string::npos) - { - SPTP ac(new ParseTree(new ArithmeticColumn(tok))); - fFunctionParms.push_back(ac); - } - else if (isdigit(tok[0]) || tok[0] == '.') - { - SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::NUM))); - fFunctionParms.push_back(cc); - } - else if (strcasecmp(tok.c_str(), "NULL") == 0) - { - SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::NULLDATA))); - fFunctionParms.push_back(cc); - } - // map keyword to constant column - else if (strcasecmp(tok.c_str(), "FROM") == 0 || - strcasecmp(tok.c_str(), "TO") == 0) - { - SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::LITERAL))); - fFunctionParms.push_back(cc); - } - // simplecolumn - else - { - SPTP sc(new ParseTree(new SimpleColumn(tok, fSessionID))); - fFunctionParms.push_back(sc); - } - } + // special process to interval function. make the passed in string one literal constant + if (fFunctionName.compare("interval") == 0) + { + SPTP sptp(new ParseTree(new ConstantColumn(funcParmsInString, ConstantColumn::LITERAL))); + fFunctionParms.push_back(sptp); + return; + } + + // try to replace the comma and space in '' to avoid string conflict + // @bug #396 for space delimited function arguments. + string funcParam = funcParmsInString; + string::size_type pos1 = 0; + string::size_type pos2 = 0; + string::size_type pos3 = 0; + while (pos2 < funcParam.length() && pos1 != string::npos) + { + pos1 = funcParam.find_first_of("'", pos2); + pos2 = funcParam.find_first_of("'", pos1+1); + pos3 = funcParam.find_first_of(", ", pos1); + if (pos3 < pos2) + { + if (funcParam[pos3] == ',') + funcParam.replace(pos3, 1, "^"); + else if (funcParam[pos3] == ' ') + funcParam[pos3] = 0x1f; // special char to replace space in quotes + } + pos2++; + } + + // also replace the comma and space in () to avoid function conflict + unsigned int par = 0; + for (unsigned int i = 0; i < funcParam.length(); i++) + { + if (funcParam[i] == '(') + par++; + if (funcParam[i] == ')') + par--; + if (funcParam[i] == ',' && par != 0) + funcParam.replace(i, 1, "^"); + if (funcParam[i] == ' ' && par != 0) + funcParam[i] = 0x1f; + } + + typedef boost::tokenizer > tokenizer; + boost::char_separator sep(", "); + tokenizer tokens(funcParam, sep); + + for (tokenizer::iterator tok_iter = tokens.begin(); + tok_iter != tokens.end(); ++tok_iter) + { + string tok = (*tok_iter); + // remove the to_upper line. don't know why have it in the first place. for bug #320 + //to_upper(tok); + + // take off the trailing and ending spaces + std::string::size_type first = tok.find_first_not_of(" "); + tok = tok.substr(first, tok.find_last_not_of(" ")-first+1); + + // recover '^' to ',' and recover 0x1f to ' ' + for (unsigned int i = 0; i < tok.length(); i++) + { + if (tok[i] == '^') tok[i] = ','; + if (tok[i] == 0x1f) tok[i] = ' '; + } + + // parse argument + if (tok[0] == '\'' && tok[tok.length()-1] == '\'') + { + // take off quotes + first = tok.find_first_not_of("'"); + tok = tok.substr(first, tok.find_last_not_of("'")-first+1); + SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::LITERAL))); + fFunctionParms.push_back(cc); + } + else if (tok.find("+", 0) != string::npos || + tok.find("-", 0) != string::npos || + tok.find("*", 0) != string::npos || + tok.find("/", 0) != string::npos || + tok.find("^", 0) != string::npos || + tok.find("(", 0) != string::npos || + tok.find(")", 0) != string::npos) + { + SPTP ac(new ParseTree(new ArithmeticColumn(tok))); + fFunctionParms.push_back(ac); + } + else if (isdigit(tok[0]) || tok[0] == '.') + { + SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::NUM))); + fFunctionParms.push_back(cc); + } + else if (strcasecmp(tok.c_str(), "NULL") == 0) + { + SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::NULLDATA))); + fFunctionParms.push_back(cc); + } + // map keyword to constant column + else if (strcasecmp(tok.c_str(), "FROM") == 0 || + strcasecmp(tok.c_str(), "TO") == 0) + { + SPTP cc(new ParseTree(new ConstantColumn(tok, ConstantColumn::LITERAL))); + fFunctionParms.push_back(cc); + } + // simplecolumn + else + { + SPTP sc(new ParseTree(new SimpleColumn(tok, fSessionID))); + fFunctionParms.push_back(sc); + } + } + } void FunctionColumn::serialize(messageqcpp::ByteStream& b) const -{ +{ b << (ObjectReader::id_t) ObjectReader::FUNCTIONCOLUMN; ReturnedColumn::serialize(b); b << fFunctionName; - b << static_cast(fFunctionParms.size()); - for (uint32_t i = 0; i < fFunctionParms.size(); i++) - ObjectReader::writeParseTree(fFunctionParms[i].get(), b); + b << static_cast(fFunctionParms.size()); + for (uint i = 0; i < fFunctionParms.size(); i++) + ObjectReader::writeParseTree(fFunctionParms[i].get(), b); b << fTableAlias; b << fData; } void FunctionColumn::unserialize(messageqcpp::ByteStream& b) { - uint32_t size, i; + u_int32_t size, i; //SRCP rc; SPTP pt; - FunctionParm::iterator it; + FunctionParm::iterator it; fFunctionParms.erase(fFunctionParms.begin(), fFunctionParms.end()); fSimpleColumnList.clear(); fAggColumnList.clear(); - fWindowFunctionColumnList.clear(); ObjectReader::checkType(b, ObjectReader::FUNCTIONCOLUMN); ReturnedColumn::unserialize(b); b >> fFunctionName; - + b >> size; - for (i = 0; i < size; i++) + for (i = 0; i < size; i++) { pt.reset(ObjectReader::createParseTree(b)); fFunctionParms.push_back(pt); pt->walk(getSimpleCols, &fSimpleColumnList); pt->walk(getAggCols, &fAggColumnList); - pt->walk(getWindowFunctionCols, &fWindowFunctionColumnList); } b >> fTableAlias; b >> fData; FuncExp* funcExp = FuncExp::instance(); fFunctor = funcExp->getFunctor(fFunctionName); - + // @bug 3506. Special treatment for rand() function. reset the seed Func_rand* rand = dynamic_cast(fFunctor); if (rand) @@ -292,9 +282,9 @@ void FunctionColumn::unserialize(messageqcpp::ByteStream& b) bool FunctionColumn::operator==(const FunctionColumn& t) const { // this is not being used. compilation error. - + const ReturnedColumn *rc1, *rc2; - FunctionParm::const_iterator it, it2; + FunctionParm::const_iterator it, it2; rc1 = static_cast(this); rc2 = static_cast(&t); @@ -304,15 +294,15 @@ bool FunctionColumn::operator==(const FunctionColumn& t) const return false; if (fFunctionParms.size() != t.fFunctionParms.size()) return false; - for (it = fFunctionParms.begin(), it2 = t.fFunctionParms.begin(); - it != fFunctionParms.end(); - ++it, ++it2) - if (**it != **it2) - return false; + for (it = fFunctionParms.begin(), it2 = t.fFunctionParms.begin(); + it != fFunctionParms.end(); + ++it, ++it2) + if (**it != **it2) + return false; // if (fAlias != t.fAlias) // return false; if (fTableAlias != t.fTableAlias) - return false; + return false; if (fData != t.fData) return false; return true; @@ -339,91 +329,4 @@ bool FunctionColumn::operator!=(const TreeNode* t) const return (!(*this == t)); } -bool FunctionColumn::hasAggregate() -{ - if (fHasAggregate) return true; - fAggColumnList.clear(); - for (uint32_t i = 0; i < fFunctionParms.size(); i++) - fFunctionParms[i]->walk(getAggCols, &fAggColumnList); - - if (!fAggColumnList.empty()) - fHasAggregate = true; - return fHasAggregate; -} - -bool FunctionColumn::hasWindowFunc() -{ - fWindowFunctionColumnList.clear(); - for (uint32_t i = 0; i < fFunctionParms.size(); i++) - fFunctionParms[i]->walk(getWindowFunctionCols, &fWindowFunctionColumnList); - - if (fWindowFunctionColumnList.empty()) - return false; - return true; -} - -void FunctionColumn::setDerivedTable() -{ - if (hasAggregate()) - { - fDerivedTable = ""; - return; - } - - setSimpleColumnList(); - string derivedTableAlias = ""; - for (uint32_t i = 0; i < fSimpleColumnList.size(); i++) - { - SimpleColumn* sc = fSimpleColumnList[i]; - sc->setDerivedTable(); - if (sc->derivedTable() != derivedTableAlias) - { - if (derivedTableAlias == "") - { - derivedTableAlias = sc->tableName(); - } - else - { - derivedTableAlias = ""; - break; - } - } - } - fDerivedTable = derivedTableAlias; -} - -void FunctionColumn::replaceRealCol(CalpontSelectExecutionPlan::ReturnedColumnList& derivedColList) -{ - for (uint i = 0; i < fFunctionParms.size(); i++) - { - ParseTree *pt = fFunctionParms[i].get(); - replaceRefCol(pt, derivedColList); - } -} - -void FunctionColumn::setSimpleColumnList() -{ - fSimpleColumnList.clear(); - for (uint i = 0; i < fFunctionParms.size(); i++) - fFunctionParms[i]->walk(getSimpleCols, &fSimpleColumnList); -} - -bool FunctionColumn::singleTable(CalpontSystemCatalog::TableAliasName& tan) -{ - tan.clear(); - setSimpleColumnList(); - for (uint i = 0; i < fSimpleColumnList.size(); i++) - { - CalpontSystemCatalog::TableAliasName stan(fSimpleColumnList[i]->schemaName(), - fSimpleColumnList[i]->tableName(), - fSimpleColumnList[i]->tableAlias(), - fSimpleColumnList[i]->viewName()); - if (tan.table.empty()) - tan = stan; - else if (stan != tan) - return false; - } - return true; -} - -} //namespace +} //namespace diff --git a/dbcon/execplan/functioncolumn.h b/dbcon/execplan/functioncolumn.h index fe1c1ef3..c337108a 100644 --- a/dbcon/execplan/functioncolumn.h +++ b/dbcon/execplan/functioncolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: functioncolumn.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: functioncolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -38,11 +38,14 @@ class ByteStream; /** * Namespace */ -namespace execplan { +namespace execplan { + class SimpleColumn; + class AggregateColumn; + /** * @brief A class to represent a functional column - * + * * This class is a specialization of class ReturnedColumn that * handles a functional column like "extract(...)" and "substr(...)" */ @@ -50,11 +53,10 @@ class FunctionColumn : public ReturnedColumn { public: FunctionColumn(); - FunctionColumn(std::string& funcName); - FunctionColumn(const std::string& functionName, const std::string& funcParmsInString, const uint32_t sessionID = 0); - FunctionColumn( const FunctionColumn& rhs, const uint32_t sessionID = 0); + FunctionColumn(const std::string& functionName, const std::string& funcParmsInString, const u_int32_t sessionID = 0); + FunctionColumn( const FunctionColumn& rhs, const u_int32_t sessionID = 0); virtual ~FunctionColumn(); - + /** get function name * * get the function name for this function column @@ -63,7 +65,7 @@ class FunctionColumn : public ReturnedColumn { { return fFunctionName; } - + /** set function name * * set the function name for this function column @@ -72,7 +74,7 @@ class FunctionColumn : public ReturnedColumn { { fFunctionName = functionName; } - + /** get function parameters * * get the function parameters for this function column. @@ -82,103 +84,86 @@ class FunctionColumn : public ReturnedColumn { { return fFunctionParms; } - + /** set function parameters * * set the function parameters for this function column. */ - void functionParms(const funcexp::FunctionParm& functionParms) + void funcParms(const funcexp::FunctionParm& functionParms) { fFunctionParms = functionParms; } - + /** set function parameters * * set the function parameters for this function column. * pass in the functionParms with parenthesis as one string. - * tokenize the string with ' ' or ',' and form a vector of + * tokenize the string with ' ' or ',' and form a vector of * parameters in string. */ - void funcParms(const std::string& funcParmsInString); - + void functionParms(const std::string& funcParmsInString); + /** get table alias name * - * get the table alias name for this function + * get the table alias name for this aggregate function */ inline const std::string& tableAlias () const { return fTableAlias; } - + /** set table alias name * - * set the table alias name for this function + * set the table alias name for this aggregate function */ inline void tableAlias (const std::string& tableAlias) { fTableAlias = tableAlias; } - + virtual const std::string data() const; virtual void data(const std::string data) { fData = data; } virtual const std::string toString() const; - + /** return a copy of this pointer * * deep copy of this pointer and return the copy - */ + */ inline virtual FunctionColumn* clone() const { return new FunctionColumn (*this); } - + /** * The serialization interface */ virtual void serialize(messageqcpp::ByteStream&) const; virtual void unserialize(messageqcpp::ByteStream&); - - virtual bool hasAggregate(); - virtual bool hasWindowFunc(); - virtual void setDerivedTable(); - virtual void replaceRealCol(std::vector&); - virtual const std::vector& simpleColumnList() const - { return fSimpleColumnList; } - - virtual void setSimpleColumnList(); - /** - * Return the tableAlias name of the table that the column arguments belong to. - * - * @param TableAliasName that will be set in the function - * @return true, if all arguments belong to one table - * false, if multiple tables are involved in the function - */ - virtual bool singleTable(CalpontSystemCatalog::TableAliasName& tan); - + private: /** * Fields */ - std::string fFunctionName; /// function name - std::string fTableAlias; /// table alias which has the column - std::string fData; /// SQL representation - + std::string fFunctionName; /// function name + std::string fTableAlias; /// table alias which has the column + std::string fData; /// SQL representation + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ bool operator==(const FunctionColumn& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. @@ -187,63 +172,58 @@ class FunctionColumn : public ReturnedColumn { bool operator!=(const FunctionColumn& t) const; /*********************************************************** - * F&E framework * + * F&E framework * ***********************************************************/ public: - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) - { - fResult.strVal = fFunctor->getStrVal(row, fFunctionParms, isNull, fOperationType); - return fResult.strVal; + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull) + { + return fFunctor->getStrVal(row, fFunctionParms, isNull, fOperationType); } - virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { + virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) + { return fFunctor->getIntVal(row, fFunctionParms, isNull, fOperationType); } - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { - return fFunctor->getUintVal(row, fFunctionParms, isNull, fOperationType); - } virtual float getFloatVal(rowgroup::Row& row, bool& isNull) { return fFunctor->getFloatVal(row, fFunctionParms, isNull, fOperationType); } - virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) + virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) { return fFunctor->getDoubleVal(row, fFunctionParms, isNull, fOperationType); - } + } virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) { IDB_Decimal decimal = fFunctor->getDecimalVal(row, fFunctionParms, isNull, fOperationType); if (fResultType.scale == decimal.scale) return decimal; - + if (fResultType.scale > decimal.scale) decimal.value *= IDB_pow[fResultType.scale-decimal.scale]; - else - decimal.value = (int64_t)(decimal.value > 0 ? - (double)decimal.value/IDB_pow[decimal.scale-fResultType.scale] + 0.5 : - (double)decimal.value/IDB_pow[decimal.scale-fResultType.scale] - 0.5); + else + decimal.value = (int64_t)(decimal.value > 0 ? + (double)decimal.value/IDB_pow[decimal.scale-fResultType.scale] + 0.5 : + (double)decimal.value/IDB_pow[decimal.scale-fResultType.scale] - 0.5); decimal.scale = fResultType.scale; decimal.precision = fResultType.precision; return decimal; } - virtual bool getBoolVal(rowgroup::Row& row, bool& isNull) + virtual bool getBoolVal(rowgroup::Row& row, bool& isNull) { return fFunctor->getBoolVal(row, fFunctionParms, isNull, fOperationType); } - virtual int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) - { + virtual int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) + { return fFunctor->getDateIntVal(row, fFunctionParms, isNull, fOperationType); } - virtual int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) - { + virtual int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) + { return fFunctor->getDatetimeIntVal(row, fFunctionParms, isNull, fOperationType); } + - -private: +private: funcexp::FunctionParm fFunctionParms; - funcexp::Func* fFunctor; /// functor to execute this function + funcexp::Func* fFunctor; // functor to execute this function }; /** @@ -251,6 +231,6 @@ class FunctionColumn : public ReturnedColumn { */ std::ostream& operator<<(std::ostream& output, const FunctionColumn& rhs); -} +} #endif //FUNCTIONCOLUMN_H diff --git a/dbcon/execplan/groupconcatcolumn.cpp b/dbcon/execplan/groupconcatcolumn.cpp index f5b50160..44947141 100644 --- a/dbcon/execplan/groupconcatcolumn.cpp +++ b/dbcon/execplan/groupconcatcolumn.cpp @@ -1,20 +1,27 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - +/* + Copyright (C) 2009-2012 Calpont Corporation. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/*********************************************************************** +* $Id: groupconcatcolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +* +* Copyright (C) 2009-2012 Calpont Corporation +* All Rights Reserved +* +***********************************************************************/ #include #include @@ -46,12 +53,12 @@ GroupConcatColumn::GroupConcatColumn(): { } -GroupConcatColumn::GroupConcatColumn(const uint32_t sessionID): +GroupConcatColumn::GroupConcatColumn(const u_int32_t sessionID): AggregateColumn(sessionID) { } -GroupConcatColumn::GroupConcatColumn(const GroupConcatColumn& rhs, const uint32_t sessionID): +GroupConcatColumn::GroupConcatColumn(const GroupConcatColumn& rhs, const u_int32_t sessionID): AggregateColumn(dynamic_cast(rhs)), fOrderCols(rhs.fOrderCols), fSeparator(rhs.fSeparator) @@ -72,7 +79,7 @@ const string GroupConcatColumn::toString() const output << "GroupConcatColumn " << data() << endl; output << AggregateColumn::toString() << endl; output << "Group Concat Order Columns: " << endl; - for (uint32_t i = 0; i < fOrderCols.size(); i++) + for (uint i = 0; i < fOrderCols.size(); i++) { output << *fOrderCols[i]; } @@ -88,7 +95,7 @@ ostream& operator<<(ostream& output, const GroupConcatColumn& rhs) void GroupConcatColumn::serialize(messageqcpp::ByteStream& b) const { - b << (uint8_t) ObjectReader::GROUPCONCATCOLUMN; + b << (u_int8_t) ObjectReader::GROUPCONCATCOLUMN; AggregateColumn::serialize(b); CalpontSelectExecutionPlan::ReturnedColumnList::const_iterator rcit; @@ -123,7 +130,7 @@ bool GroupConcatColumn::operator==(const GroupConcatColumn& t) const rc2 = static_cast(&t); if (*rc1 != *rc2) return false; - for (uint32_t i = 0; i < fOrderCols.size(); i++) + for (uint i = 0; i < fOrderCols.size(); i++) { if (fOrderCols[i].get() != NULL) { diff --git a/dbcon/execplan/groupconcatcolumn.h b/dbcon/execplan/groupconcatcolumn.h index 03c88ace..2b26fbd0 100644 --- a/dbcon/execplan/groupconcatcolumn.h +++ b/dbcon/execplan/groupconcatcolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: groupconcatcolumn.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: groupconcatcolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -52,9 +52,9 @@ class GroupConcatColumn : public AggregateColumn { */ GroupConcatColumn(); - GroupConcatColumn(const uint32_t sessionID); + GroupConcatColumn(const u_int32_t sessionID); - GroupConcatColumn(const GroupConcatColumn& rhs, const uint32_t sessionID=0); + GroupConcatColumn(const GroupConcatColumn& rhs, const u_int32_t sessionID=0); /** * Destructors diff --git a/dbcon/execplan/intervalcolumn.cpp b/dbcon/execplan/intervalcolumn.cpp deleted file mode 100644 index a075fb17..00000000 --- a/dbcon/execplan/intervalcolumn.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: intervalcolumn.cpp 9414 2013-04-22 22:18:30Z xlou $ -* -* -***********************************************************************/ - -#include -#include -#include -using namespace std; - -#include -#include -using namespace boost; - -#include "intervalcolumn.h" -using namespace funcexp; - -#ifdef _MSC_VER -#define strcasecmp stricmp -#endif - -namespace execplan { - -/** - * Constructors/Destructors - */ -IntervalColumn::IntervalColumn() -{} - -IntervalColumn::IntervalColumn(SRCP& val, int intervalType): - fVal(val->clone()), fIntervalType(intervalType) -{ - cout << "intervalType=" << fIntervalType << endl; - } - -IntervalColumn::IntervalColumn( const IntervalColumn& rhs, const uint32_t sessionID): - ReturnedColumn(rhs, sessionID), - fVal(rhs.val()), - fIntervalType(rhs.intervalType()) -{} - -/** - * Methods - */ -const string IntervalColumn::toString() const -{ - ostringstream output; - output << "INTERVAL" << endl; - if (fVal) - output << fVal->toString(); - output << " IntervalType=" << fIntervalType << endl; - return output.str(); -} - -ostream& operator<<(ostream& output, const IntervalColumn& rhs) -{ - output << rhs.toString(); - return output; -} - -} //namespace diff --git a/dbcon/execplan/intervalcolumn.h b/dbcon/execplan/intervalcolumn.h deleted file mode 100644 index d138fbcf..00000000 --- a/dbcon/execplan/intervalcolumn.h +++ /dev/null @@ -1,113 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: intervalcolumn.h 9679 2013-07-11 22:32:03Z zzhu $ -* -* -***********************************************************************/ - -/** @file */ - -#ifndef INTERVALCOLUMN_H -#define INTERVALCOLUMN_H -#include -#include -#include - -#include "returnedcolumn.h" -#include "functor.h" - -namespace messageqcpp { -class ByteStream; -} - -/** - * Namespace - */ -namespace execplan { -/** - * @brief A class to represent a functional column - * - * This class is a specialization of class ReturnedColumn that - * handles a window function. - */ -class IntervalColumn : public ReturnedColumn { - -public: - - /* from my_time.h */ - enum interval_type - { - INTERVAL_YEAR, INTERVAL_QUARTER, INTERVAL_MONTH, INTERVAL_WEEK, INTERVAL_DAY, - INTERVAL_HOUR, INTERVAL_MINUTE, INTERVAL_SECOND, INTERVAL_MICROSECOND, - INTERVAL_YEAR_MONTH, INTERVAL_DAY_HOUR, INTERVAL_DAY_MINUTE, - INTERVAL_DAY_SECOND, INTERVAL_HOUR_MINUTE, INTERVAL_HOUR_SECOND, - INTERVAL_MINUTE_SECOND, INTERVAL_DAY_MICROSECOND, INTERVAL_HOUR_MICROSECOND, - INTERVAL_MINUTE_MICROSECOND, INTERVAL_SECOND_MICROSECOND, INTERVAL_LAST - }; - - IntervalColumn(); - IntervalColumn(SRCP&, int); - IntervalColumn(const IntervalColumn& rhs, const uint32_t sessionID = 0); - virtual ~IntervalColumn() {} - const SRCP& val() const - { - return fVal; - } - void val(const SRCP& val) - { - fVal = val; - } - const int intervalType() const - { - return fIntervalType; - } - void intervalType(int intervalType) - { - fIntervalType = intervalType; - } - const std::string toString() const; - inline virtual IntervalColumn* clone() const - { - return new IntervalColumn (*this); - } - - virtual bool hasAggregate() {return false;} - virtual bool hasWindowFunc() {return false;} - -private: - /** - * Fields - */ - SRCP fVal; - int fIntervalType; - - // okay to be private for now. - virtual bool operator==(const TreeNode* t) const { return false; } - bool operator==(const IntervalColumn& t) const; - virtual bool operator!=(const TreeNode* t) const { return false; } - bool operator!=(const IntervalColumn& t) const; -}; - -/** -* ostream operator -*/ -std::ostream& operator<<(std::ostream& output, const IntervalColumn& rhs); - -} -#endif //INTERVALCOLUMN_H diff --git a/dbcon/execplan/libexecplan.vcxproj b/dbcon/execplan/libexecplan.vcxproj deleted file mode 100644 index 04b4cfa1..00000000 --- a/dbcon/execplan/libexecplan.vcxproj +++ /dev/null @@ -1,290 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {FFCCE773-27FA-4F4D-9E28-2208BE6348DA} - libexecplan - - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dbcon/execplan/libexecplan.vcxproj.filters b/dbcon/execplan/libexecplan.vcxproj.filters deleted file mode 100644 index 40251303..00000000 --- a/dbcon/execplan/libexecplan.vcxproj.filters +++ /dev/null @@ -1,249 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/dbcon/execplan/logicoperator.cpp b/dbcon/execplan/logicoperator.cpp index 9c12d27a..6cf67609 100644 --- a/dbcon/execplan/logicoperator.cpp +++ b/dbcon/execplan/logicoperator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: logicoperator.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: logicoperator.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/logicoperator.h b/dbcon/execplan/logicoperator.h index b444a484..8fc0036f 100644 --- a/dbcon/execplan/logicoperator.h +++ b/dbcon/execplan/logicoperator.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: logicoperator.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: logicoperator.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/mysqlexecutionplan.cpp b/dbcon/execplan/mysqlexecutionplan.cpp index 4560ef35..a4472020 100644 --- a/dbcon/execplan/mysqlexecutionplan.cpp +++ b/dbcon/execplan/mysqlexecutionplan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: mysqlexecutionplan.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: mysqlexecutionplan.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/mysqlexecutionplan.h b/dbcon/execplan/mysqlexecutionplan.h index fc6193c1..3964da97 100644 --- a/dbcon/execplan/mysqlexecutionplan.h +++ b/dbcon/execplan/mysqlexecutionplan.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: mysqlexecutionplan.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: mysqlexecutionplan.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/njlcolumnresult.h b/dbcon/execplan/njlcolumnresult.h index 1f28bdba..d9d94fb8 100644 --- a/dbcon/execplan/njlcolumnresult.h +++ b/dbcon/execplan/njlcolumnresult.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: njlcolumnresult.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: njlcolumnresult.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ /** @file */ diff --git a/dbcon/execplan/objectidmanager.cpp b/dbcon/execplan/objectidmanager.cpp index 341a9d45..265a8c11 100644 --- a/dbcon/execplan/objectidmanager.cpp +++ b/dbcon/execplan/objectidmanager.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: objectidmanager.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: objectidmanager.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ @@ -121,12 +121,12 @@ int ObjectIDManager::allocOID() return allocOIDs(1); } -int ObjectIDManager::allocVBOID(uint32_t dbroot) +int ObjectIDManager::allocVBOID(uint dbroot) { return dbrm.allocVBOID(dbroot); } -int ObjectIDManager::getDBRootOfVBOID(uint32_t vboid) +int ObjectIDManager::getDBRootOfVBOID(uint vboid) { return dbrm.getDBRootOfVBOID(vboid); } diff --git a/dbcon/execplan/objectidmanager.h b/dbcon/execplan/objectidmanager.h index a2f036ff..f1c5d8ad 100644 --- a/dbcon/execplan/objectidmanager.h +++ b/dbcon/execplan/objectidmanager.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: objectidmanager.h 9744 2013-08-07 03:32:19Z bwilkinson $ + * $Id: objectidmanager.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ @@ -67,10 +67,10 @@ class ObjectIDManager * * @return Returns -1 on all errors. */ - int allocVBOID(uint32_t dbroot); + int allocVBOID(uint dbroot); /** @brief Returns the DBRoot of the given version buffer OID, or -1 on error. */ - int getDBRootOfVBOID(uint32_t vboid); + int getDBRootOfVBOID(uint vboid); /** @brief Returns the VB OID -> DB Root mapping. ret[0] = dbroot of VB OID 0 * @@ -130,7 +130,7 @@ class ObjectIDManager * @param offset the offset to start reading at * @param size the number of bytes to read into buf */ - void readData(uint8_t* buf, off64_t offset, int size) const; + void readData(uint8_t* buf, off_t offset, int size) const; /** @brief Reliably writes data to the bitmap file * @@ -141,7 +141,7 @@ class ObjectIDManager * @param offset the offset to start writing at * @param size the number of bytes to write */ - void writeData(uint8_t* buf, off64_t offset, int size) const; + void writeData(uint8_t* buf, off_t offset, int size) const; /** @brief If there is no bitmap file yet, this is used to make one * diff --git a/dbcon/execplan/objectreader.cpp b/dbcon/execplan/objectreader.cpp index 816aa6d1..06fa55a3 100644 --- a/dbcon/execplan/objectreader.cpp +++ b/dbcon/execplan/objectreader.cpp @@ -17,7 +17,7 @@ /***************************************************************************** * - * $Id: objectreader.cpp 9559 2013-05-22 17:58:13Z xlou $ + * $Id: objectreader.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ @@ -25,10 +25,6 @@ * Implements ObjectReader */ -#include -#include -#include - #include "treenode.h" #include "returnedcolumn.h" #include "aggregatecolumn.h" @@ -38,7 +34,6 @@ #include "rowcolumn.h" #include "simplecolumn.h" #include "simplecolumn_int.h" -#include "simplecolumn_uint.h" #include "simplecolumn_decimal.h" #include "filter.h" #include "existsfilter.h" @@ -48,10 +43,8 @@ #include "simplescalarfilter.h" #include "operator.h" #include "arithmeticoperator.h" -#include "windowfunctioncolumn.h" #include "logicoperator.h" #include "predicateoperator.h" -#include "pseudocolumn.h" #include "treenodeimpl.h" #include "calpontexecutionplan.h" #include "calpontselectexecutionplan.h" @@ -71,11 +64,14 @@ TreeNode* ObjectReader::createTreeNode(messageqcpp::ByteStream& b) { CLASSID id = ZERO; TreeNode* ret; - b.peek(reinterpret_cast(id)); + b.peek(reinterpret_cast(id)); switch(id) { case TREENODEIMPL: ret = new TreeNodeImpl(); break; +// case RETURNEDCOLUMN: +// ret = new ReturnedColumn(); +// break; case SIMPLECOLUMN: ret = new SimpleColumn(); break; @@ -91,18 +87,6 @@ TreeNode* ObjectReader::createTreeNode(messageqcpp::ByteStream& b) { case SIMPLECOLUMN_INT1: ret = new SimpleColumn_INT<1>(); break; - case SIMPLECOLUMN_UINT2: - ret = new SimpleColumn_UINT<2>(); - break; - case SIMPLECOLUMN_UINT4: - ret = new SimpleColumn_UINT<4>(); - break; - case SIMPLECOLUMN_UINT8: - ret = new SimpleColumn_UINT<8>(); - break; - case SIMPLECOLUMN_UINT1: - ret = new SimpleColumn_UINT<1>(); - break; case SIMPLECOLUMN_DECIMAL2: ret = new SimpleColumn_Decimal<2>(); break; @@ -133,12 +117,6 @@ TreeNode* ObjectReader::createTreeNode(messageqcpp::ByteStream& b) { case ROWCOLUMN: ret = new RowColumn(); break; - case WINDOWFUNCTIONCOLUMN: - ret = new WindowFunctionColumn(); - break; - case PSEUDOCOLUMN: - ret = new PseudoColumn(); - break; case FILTER: ret = new Filter(); break; @@ -176,13 +154,8 @@ TreeNode* ObjectReader::createTreeNode(messageqcpp::ByteStream& b) { b >> (id_t&) id; //eat the ID return NULL; default: - { - ostringstream oss; - oss << "Bad type: " << (int)id << ". Stream out of sync? (1)"; - throw UnserializeException(oss.str()); - break; - } - } + throw UnserializeException("Bad type. Stream out of sync?"); + }; ret->unserialize(b); return ret; @@ -202,12 +175,7 @@ CalpontExecutionPlan* ObjectReader::createExecutionPlan(messageqcpp::ByteStream& b >> reinterpret_cast(id); return NULL; default: - { - ostringstream oss; - oss << "Bad type: " << (int)id << ". Stream out of sync? (2)"; - throw UnserializeException(oss.str()); - break; - } + throw UnserializeException("Bad type. Stream out of sync?"); } ret->unserialize(b); return ret; @@ -269,10 +237,6 @@ void ObjectReader::checkType(messageqcpp::ByteStream& b, const CLASSID id) throw UnserializeException("Not a FunctionColumn"); case ROWCOLUMN: throw UnserializeException("Not a RowColumn"); - case WINDOWFUNCTIONCOLUMN: - throw UnserializeException("Not a WindowFunctionColumn"); - case PSEUDOCOLUMN: - throw UnserializeException("Not a PseudoColumn"); case FILTER: throw UnserializeException("Not a Filter"); case CONDITIONFILTER: @@ -299,7 +263,7 @@ void ObjectReader::checkType(messageqcpp::ByteStream& b, const CLASSID id) return; } -ObjectReader::UnserializeException::UnserializeException(string msg) +ObjectReader::UnserializeException::UnserializeException(std::string msg) throw() : fWhat(msg) { } diff --git a/dbcon/execplan/objectreader.h b/dbcon/execplan/objectreader.h index 718709cf..799c74bf 100644 --- a/dbcon/execplan/objectreader.h +++ b/dbcon/execplan/objectreader.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: objectreader.h 9633 2013-06-19 13:36:01Z rdempsey $ + * $Id: objectreader.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ @@ -68,7 +68,7 @@ class ObjectReader { enum CLASSID { ZERO, // an appropriate initializer NULL_CLASS, // to denote that some member is NULL - + /**** TreeNodes */ TREENODE, TREENODEIMPL, @@ -79,18 +79,12 @@ class ObjectReader { CONSTANTCOLUMN, FUNCTIONCOLUMN, ROWCOLUMN, - WINDOWFUNCTIONCOLUMN, - PSEUDOCOLUMN, - + SIMPLECOLUMN, SIMPLECOLUMN_INT1, SIMPLECOLUMN_INT2, SIMPLECOLUMN_INT4, SIMPLECOLUMN_INT8, - SIMPLECOLUMN_UINT1, - SIMPLECOLUMN_UINT2, - SIMPLECOLUMN_UINT4, - SIMPLECOLUMN_UINT8, SIMPLECOLUMN_DECIMAL1, SIMPLECOLUMN_DECIMAL2, SIMPLECOLUMN_DECIMAL4, @@ -109,14 +103,14 @@ class ObjectReader { LOGICOPERATOR, /**** /TreeNodes */ - + PARSETREE, CALPONTSELECTEXECUTIONPLAN, CONSTANTFILTER, OUTERJOINONFILTER, }; - typedef uint8_t id_t; //expand as necessary + typedef u_int8_t id_t; //expand as necessary /** @brief Creates a new TreeNode object from the ByteStream * @@ -124,30 +118,34 @@ class ObjectReader { * @return A newly allocated TreeNode */ static TreeNode* createTreeNode(messageqcpp::ByteStream& b); - + /** @brief Creates a new ParseTree from the ByteStream * + * @note This is much faster than a version that creates a fully + * generalized ExpressionTree but is obviously less flexible. * @param b The ByteStream to create it from * @return A newly allocated ParseTree */ static ParseTree* createParseTree(messageqcpp::ByteStream& b); - + /** @brief Creates a new CalpontExecutionPlan from the ByteStream * * @param b The ByteStream to create it from * @return A newly allocated CalpontExecutionPlan */ static CalpontExecutionPlan* createExecutionPlan(messageqcpp::ByteStream& b); - + /** @brief Serialize() for ParseTrees * - * This function effectively serializes a ParseTree. + * This function effectively serializes a ParseTree. It is not part + * of ExpressionTree because it cannot be easily generalized for all + * possible instantiations. * @param tree The ParseTree to write out * @param b The ByteStream to write tree to */ - static void writeParseTree(const ParseTree* tree, - messageqcpp::ByteStream& b); - + static void writeParseTree(const ParseTree* tree, + messageqcpp::ByteStream& b); + /** @brief Verify the type of the next object in the ByteStream * * @param b The ByteStream to read from diff --git a/dbcon/execplan/operator.cpp b/dbcon/execplan/operator.cpp index 9d25fa3f..e4c8f3e9 100644 --- a/dbcon/execplan/operator.cpp +++ b/dbcon/execplan/operator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: operator.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: operator.cpp 8570 2012-05-29 22:29:11Z zzhu $ * * ***********************************************************************/ diff --git a/dbcon/execplan/operator.h b/dbcon/execplan/operator.h index 1444f259..2d855575 100644 --- a/dbcon/execplan/operator.h +++ b/dbcon/execplan/operator.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: operator.h 9635 2013-06-19 21:42:30Z bwilkinson $ +* $Id: operator.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -146,9 +146,8 @@ class Operator : public TreeNode { virtual void evaluate(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) {} // The following methods should be pure virtual. Currently too many instanslization exists. - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.strVal; } + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.strVal; } virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.intVal; } - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.uintVal; } virtual float getFloatVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.floatVal; } virtual double getDoubleVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.doubleVal; } virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull, ParseTree* lop, ParseTree* rop) { return fResult.decimalVal; } diff --git a/dbcon/execplan/oracleexecutionplan.cpp b/dbcon/execplan/oracleexecutionplan.cpp index 63a06af5..76911e7e 100644 --- a/dbcon/execplan/oracleexecutionplan.cpp +++ b/dbcon/execplan/oracleexecutionplan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: oracleexecutionplan.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: oracleexecutionplan.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/oracleexecutionplan.h b/dbcon/execplan/oracleexecutionplan.h index cbe9c945..722e48e4 100644 --- a/dbcon/execplan/oracleexecutionplan.h +++ b/dbcon/execplan/oracleexecutionplan.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: oracleexecutionplan.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: oracleexecutionplan.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/outerjoinonfilter.cpp b/dbcon/execplan/outerjoinonfilter.cpp index 7430a7b6..1e42f148 100644 --- a/dbcon/execplan/outerjoinonfilter.cpp +++ b/dbcon/execplan/outerjoinonfilter.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: outerjoinonfilter.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: outerjoinonfilter.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/outerjoinonfilter.h b/dbcon/execplan/outerjoinonfilter.h index a5d45187..8a5bbd28 100644 --- a/dbcon/execplan/outerjoinonfilter.h +++ b/dbcon/execplan/outerjoinonfilter.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: outerjoinonfilter.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: outerjoinonfilter.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/parsetree.h b/dbcon/execplan/parsetree.h index 8b698bdc..1c0d564b 100644 --- a/dbcon/execplan/parsetree.h +++ b/dbcon/execplan/parsetree.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: parsetree.h 9635 2013-06-19 21:42:30Z bwilkinson $ +* $Id: parsetree.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -41,238 +41,220 @@ namespace execplan { * * This class is a simple binary tree implementation which * represents an expression tree. The expression can be used - * for both arithmetic and logical expression. - * Please note that to use this template class T can only be pointers. + * for both arithmetic and logical expression. + * Please note that to use this template class T can only be pointers. */ - + class ParseTree { public: - /** - * Constructor / Destructor - */ - inline ParseTree(); - inline ParseTree(TreeNode* data); - inline ParseTree(const ParseTree& rhs); - inline virtual ~ParseTree(); - - /** - * Access methods - */ - inline void left(ParseTree* expressionTree) - { fLeft = expressionTree; } - - inline void left(TreeNode* node) - { - ParseTree* pt = new ParseTree(node); - left(pt); - } - - inline ParseTree* left() const - { return fLeft; } - - inline void right(ParseTree* expressionTree) - { fRight = expressionTree; } - - inline void right(TreeNode* node) - { - ParseTree* pt = new ParseTree(node); - right(pt); - } - - inline ParseTree* right() const - { return fRight; } - - inline void data(TreeNode* data) - { fData = data; } - - inline TreeNode* data() const - { return fData; } - - /** walk the tree - * - * postfix walking of a const tree - */ - inline void walk(void (*fn)( ParseTree* n)) const; - - /** walk the tree - * - * postfix walking of a non-const tree. This is for deleting the tree - */ - inline void walk(void (*fn)( const ParseTree* n)) const; - - /** output the tree - * - * take ostream argument to walk and output the tree - */ - inline void walk(void (*fn)(const ParseTree* n, std::ostream& output), std::ostream& output) const; - - /** output the tree - * - * take user argument to walk and output the tree - */ - inline void walk(void (*fn)(const ParseTree* n, void* obj), void* object) const; - - /** output the tree - * - * take user argument to walk and output the tree - */ - inline void walk(void (*fn)(ParseTree* n, void* obj), void* object) const; - - /** output the tree to string - * for debug purpose - */ - inline std::string toString() const; - - /** assignment operator - * - */ - inline ParseTree& operator=(const ParseTree& rhs); - - /** deep copy of a tree - * - * copy src tree on top of dest tree. Dest tree is destroyed before copy - * takes place. Src tree still owns the tree data, though. Assume tree node - * are pointers. - */ - inline void copyTree (const ParseTree &src); - - /** destroy a tree - * - * destroy a tree where tree nodes are values - */ - inline static void destroyTree (ParseTree *root); - - /** draw the tree using dot - * - * this function is mostly for debug purpose, where T represent a TreeNode - * pointer - */ - inline void drawTree(std::string filename); - - /** print the tree - * - * this function is mostly for debug purpose, where T represent a TreeNode - * pointer - */ - inline static void print(const ParseTree* n, std::ostream& output) - { - output << *n->data() << std::endl; - } - - /** delete treenode - * - * delete fData of a tree node, and then delete the treenode - */ - inline static void deleter( ParseTree*& n) - { - delete n->fData; - n->fData = 0; - delete n; - n = 0; - } - - inline void derivedTable (const std::string& derivedTable) - { fDerivedTable = derivedTable; } - - inline std::string& derivedTable() - { return fDerivedTable; } - - inline void setDerivedTable(); + /** + * Constructor / Destructor + */ + inline ParseTree(); + inline ParseTree(TreeNode* data); + inline ParseTree(const ParseTree& rhs); + inline virtual ~ParseTree(); + + /** + * Access methods + */ + inline void left(ParseTree* expressionTree) + { fLeft = expressionTree; } + + inline void left(TreeNode* node) + { + ParseTree* pt = new ParseTree(node); + left(pt); + } + + inline ParseTree* left() const + { return fLeft; } + + inline void right(ParseTree* expressionTree) + { fRight = expressionTree; } + + inline void right(TreeNode* node) + { + ParseTree* pt = new ParseTree(node); + right(pt); + } + + inline ParseTree* right() const + { return fRight; } + + inline void data(TreeNode* data) + { fData = data; } + + inline TreeNode* data() const + { return fData; } + + /** walk the tree + * + * postfix walking of a const tree + */ + inline void walk(void (*fn)( ParseTree*& n)) const; + + /** walk the tree + * + * postfix walking of a non-const tree. This is for deleting the tree + */ + inline void walk(void (*fn)( const ParseTree* n)) const; + + /** output the tree + * + * take ostream argument to walk and output the tree + */ + inline void walk(void (*fn)(const ParseTree* n, std::ostream& output), std::ostream& output) const; + + /** output the tree + * + * take user argument to walk and output the tree + */ + inline void walk(void (*fn)(const ParseTree* n, void* obj), void* object) const; + + /** output the tree + * + * take user argument to walk and output the tree + */ + inline void walk(void (*fn)(ParseTree* n, void* obj), void* object) const; + + /** output the tree to string + * for debug purpose + */ + inline std::string toString() const; + + /** assignment operator + * + */ + inline ParseTree& operator=(const ParseTree& rhs); + + /** deep copy of a tree + * + * copy src tree on top of dest tree. Dest tree is destroyed before copy + * takes place. Src tree still owns the tree data, though. Assume tree node + * are pointers. + */ + inline void copyTree (const ParseTree &src); + + /** destroy a tree + * + * destroy a tree where tree nodes are values + */ + inline static void destroyTree (ParseTree *root); + + /** draw the tree using dot + * + * this function is mostly for debug purpose, where T represent a TreeNode + * pointer + */ + inline void drawTree(std::string filename); + + /** print the tree + * + * this function is mostly for debug purpose, where T represent a TreeNode + * pointer + */ + inline static void print(const ParseTree* n, std::ostream& output) + { + output << *n->data() << std::endl; + } + + /** delete treenode + * + * delete fData of a tree node, and then delete the treenode + */ + inline static void deleter( ParseTree*& n) + { + delete n->fData; + n->fData = 0; + delete n; + n = 0; + } private: - TreeNode* fData; - ParseTree* fLeft; - ParseTree* fRight; - std::string fDerivedTable; - + TreeNode* fData; + ParseTree* fLeft; + ParseTree* fRight; + /********************************************************************** - * F&E Framework * - **********************************************************************/ + * F&E Framework * + **********************************************************************/ public: - inline const std::string& getStrVal(rowgroup::Row& row, bool& isNull) + inline std::string getStrVal(rowgroup::Row& row, bool& isNull) { if (fLeft && fRight) return (reinterpret_cast(fData))->getStrVal(row, isNull, fLeft, fRight); else return fData->getStrVal(row, isNull); - } - - inline int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { + } + + inline int64_t getIntVal(rowgroup::Row& row, bool& isNull) + { if (fLeft && fRight) return (reinterpret_cast(fData))->getIntVal(row, isNull, fLeft, fRight); else return fData->getIntVal(row, isNull); - } - - inline uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { - if (fLeft && fRight) - return (reinterpret_cast(fData))->getUintVal(row, isNull, fLeft, fRight); - else - return fData->getUintVal(row, isNull); - } - - inline float getFloatVal(rowgroup::Row& row, bool& isNull) - { + } + + inline float getFloatVal(rowgroup::Row& row, bool& isNull) + { if (fLeft && fRight) return (reinterpret_cast(fData))->getFloatVal(row, isNull, fLeft, fRight); else return fData->getFloatVal(row, isNull); - } - + } + inline double getDoubleVal(rowgroup::Row& row, bool& isNull) - { + { if (fLeft && fRight) return (reinterpret_cast(fData))->getDoubleVal(row, isNull, fLeft, fRight); else return fData->getDoubleVal(row, isNull); - } - - inline IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) - { + } + + inline IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) + { if (fLeft && fRight) return (reinterpret_cast(fData))->getDecimalVal(row, isNull, fLeft, fRight); else return fData->getDecimalVal(row, isNull); - } - - inline bool getBoolVal(rowgroup::Row& row, bool& isNull) - { + } + + inline bool getBoolVal(rowgroup::Row& row, bool& isNull) + { if (fLeft && fRight) return (reinterpret_cast(fData))->getBoolVal(row, isNull, fLeft, fRight); else return fData->getBoolVal(row, isNull); } - - inline int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) - { + + inline int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) + { if (fLeft && fRight) return (reinterpret_cast(fData))->getDateIntVal(row, isNull, fLeft, fRight); else return fData->getDateIntVal(row, isNull); } - - inline int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) - { + + inline int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) + { if (fLeft && fRight) return (reinterpret_cast(fData))->getDatetimeIntVal(row, isNull, fLeft, fRight); else return fData->getDatetimeIntVal(row, isNull); } - -private: - /** draw the tree - * - * this function is used by draw tree to print out dot file - */ - static void draw(const ParseTree* n, std::ostream& dotFile); - - // F&E framework - void evaluate (rowgroup::Row& row, bool& isNull); + +private: + /** draw the tree + * + * this function is used by draw tree to print out dot file + */ + static void draw(const ParseTree* n, std::ostream& dotFile); + // F&E framework + void evaluate (rowgroup::Row& row, bool& isNull); }; @@ -285,27 +267,19 @@ namespace execplan { * Class Definition */ inline ParseTree::ParseTree() : - fData(0), fLeft(0), fRight(0), fDerivedTable("") + fData(0), fLeft(0), fRight(0) { } inline ParseTree::ParseTree(TreeNode* data) : - fData(data), - fLeft(0), - fRight(0) + fData(data), fLeft(0), fRight(0) { - // bug5984. Need to validate data to be not null - if (data) - fDerivedTable = data->derivedTable(); } inline ParseTree::ParseTree(const ParseTree& rhs): - fData(0), - fLeft(0), - fRight(0), - fDerivedTable(rhs.fDerivedTable) + fData(0), fLeft(0), fRight(0) { - copyTree(rhs); + copyTree(rhs); } inline ParseTree::~ParseTree() @@ -324,33 +298,33 @@ inline ParseTree::~ParseTree() fData = NULL; } -inline void ParseTree::walk(void (*fn)( ParseTree* n)) const +inline void ParseTree::walk(void (*fn)( ParseTree*& n)) const { - if (fLeft != 0) fLeft->walk(fn); - if (fRight != 0) fRight->walk(fn); - ParseTree* temp = const_cast(this); - fn (temp); + if (fLeft != 0) fLeft->walk(fn); + if (fRight != 0) fRight->walk(fn); + ParseTree* temp = const_cast(this); + fn (temp); } inline void ParseTree::walk(void (*fn)( const ParseTree* n)) const { - if (fLeft != 0) fLeft->walk(fn); - if (fRight != 0) fRight->walk(fn); - fn (this); + if (fLeft != 0) fLeft->walk(fn); + if (fRight != 0) fRight->walk(fn); + fn (this); } inline void ParseTree::walk(void (*fn)(const ParseTree* n, std::ostream& output), std::ostream& output) const { - if (fLeft != 0) fLeft->walk(fn, output); - if (fRight != 0) fRight->walk(fn, output); - fn(this, output); + if (fLeft != 0) fLeft->walk(fn, output); + if (fRight != 0) fRight->walk(fn, output); + fn(this, output); } inline void ParseTree::walk(void (*fn)(const ParseTree* n, void* obj), void* obj) const { - if (fLeft != 0) fLeft->walk(fn, obj); - if (fRight != 0) fRight->walk(fn, obj); - fn(this, obj); + if (fLeft != 0) fLeft->walk(fn, obj); + if (fRight != 0) fRight->walk(fn, obj); + fn(this, obj); } inline std::string ParseTree::toString() const @@ -362,93 +336,93 @@ inline std::string ParseTree::toString() const inline void ParseTree::walk(void (*fn)(ParseTree* n, void* obj), void* obj) const { - if (fLeft != 0) fLeft->walk(fn, obj); - if (fRight != 0) fRight->walk(fn, obj); - fn(const_cast(this), obj); + if (fLeft != 0) fLeft->walk(fn, obj); + if (fRight != 0) fRight->walk(fn, obj); + fn(const_cast(this), obj); } inline ParseTree& ParseTree::operator=(const ParseTree& rhs) { - if (this != &rhs) - { - //copyTree(*this, rhs); - copyTree(rhs); - } - return *this; + if (this != &rhs) + { + //copyTree(*this, rhs); + copyTree(rhs); + } + return *this; } inline void ParseTree::copyTree(const ParseTree &src) { - if (fLeft != NULL) - delete fLeft; - if (fRight != NULL) - delete fRight; - fLeft = NULL; - fRight = NULL; - - if (src.left() != NULL) - { - fLeft = new ParseTree(); - fLeft->copyTree(*(src.left())); - } - if (src.right() != NULL) - { - fRight = new ParseTree(); - fRight->copyTree(*(src.right())); - } - - delete fData; - if (src.data() == NULL) - fData = NULL; - else - fData = src.data()->clone(); -} + if (fLeft != NULL) + delete fLeft; + if (fRight != NULL) + delete fRight; + fLeft = NULL; + fRight = NULL; + + if (src.left() != NULL) + { + fLeft = new ParseTree(); + fLeft->copyTree(*(src.left())); + } + if (src.right() != NULL) + { + fRight = new ParseTree(); + fRight->copyTree(*(src.right())); + } + + delete fData; + if (src.data() == NULL) + fData = NULL; + else + fData = src.data()->clone(); +} inline void ParseTree::destroyTree(ParseTree* root) { - if (root == NULL) - return; - if (root->left() != NULL) - { - destroyTree (root->fLeft); - } - if (root->right() != NULL) - { - destroyTree (root->fRight); - } - delete root; - root = 0; + if (root == NULL) + return; + if (root->left() != NULL) + { + destroyTree (root->fLeft); + } + if (root->right() != NULL) + { + destroyTree (root->fRight); + } + delete root; + root = 0; } inline void ParseTree::draw(const ParseTree* n, std::ostream& dotFile) { - const ParseTree* r; - const ParseTree* l; - l = n->left(); - r = n->right(); - - if (l != 0) - dotFile << "n" << (void*)n << " -> " << "n" << (void*)l << std::endl; - if (r != 0) - dotFile << "n" << (void*)n << " -> " << "n" << (void*)r << std::endl; - dotFile << "n" << (void*)n << " [label=\"" - << n->data()->data() << "\"]" << std::endl; + const ParseTree* r; + const ParseTree* l; + l = n->left(); + r = n->right(); + + if (l != 0) + dotFile << "n" << (u_long)n << " -> " << "n" << (u_long)l << std::endl; + if (r != 0) + dotFile << "n" << (u_long)n << " -> " << "n" << (u_long)r << std::endl; + dotFile << "n" << (u_long)n << " [label=\"" + << n->data()->data() << "\"]" << std::endl; } -inline void ParseTree::drawTree(std::string filename) +inline void ParseTree::drawTree(std::string filename) { - std::ofstream dotFile (filename.c_str(), std::ios::out); - - dotFile << "digraph G {" << std::endl; - walk (draw, dotFile); - dotFile << "}" << std::endl; - - dotFile.close(); + std::ofstream dotFile (filename.c_str(), std::ios::out); + + dotFile << "digraph G {" << std::endl; + walk (draw, dotFile); + dotFile << "}" << std::endl; + + dotFile.close(); } inline void ParseTree::evaluate(rowgroup::Row& row, bool& isNull) { - // Non-leaf node is operator. leaf node is SimpleFilter for logical expression, + // Non-leaf node is operator. leaf node is SimpleFilter for logical expression, // or ReturnedColumn for arithmetical expression. if (fLeft && fRight) { @@ -461,59 +435,6 @@ inline void ParseTree::evaluate(rowgroup::Row& row, bool& isNull) } } -inline void ParseTree::setDerivedTable() -{ - std::string lDerivedTable = ""; - std::string rDerivedTable = ""; - - if (fLeft) - { - fLeft->setDerivedTable(); - lDerivedTable = fLeft->derivedTable(); - } - else - { - lDerivedTable = "*"; - } - - if (fRight) - { - fRight->setDerivedTable(); - rDerivedTable = fRight->derivedTable(); - } - else - { - rDerivedTable = "*"; - } - - Operator *op = dynamic_cast(fData); - if (op) - { - if (lDerivedTable == "*") - { - fDerivedTable = rDerivedTable; - } - else if (rDerivedTable == "*") - { - fDerivedTable = lDerivedTable; - } - else if (lDerivedTable == rDerivedTable) - { - fDerivedTable = lDerivedTable; // should be the same as rhs - } - else - { - fDerivedTable = ""; - } - } - else - { - fData->setDerivedTable(); - fDerivedTable = fData->derivedTable(); - fDerivedTable = fData->derivedTable(); - } -} - typedef boost::shared_ptr SPTP; } // namespace diff --git a/dbcon/execplan/predicateoperator.cpp b/dbcon/execplan/predicateoperator.cpp index f3294e1c..2ee0566c 100644 --- a/dbcon/execplan/predicateoperator.cpp +++ b/dbcon/execplan/predicateoperator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: predicateoperator.cpp 9306 2013-03-12 15:49:11Z rdempsey $ +* $Id: predicateoperator.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -225,13 +225,11 @@ void PredicateOperator::setOpType(Type& l, Type& r) break; } } - else if (l.colDataType == execplan::CalpontSystemCatalog::DECIMAL || - l.colDataType == execplan::CalpontSystemCatalog::UDECIMAL) + else if (l.colDataType == execplan::CalpontSystemCatalog::DECIMAL) { switch (r.colDataType) { case execplan::CalpontSystemCatalog::DECIMAL: - case execplan::CalpontSystemCatalog::UDECIMAL: { // should following the result type that MySQL gives fOperationType = l; @@ -242,10 +240,6 @@ void PredicateOperator::setOpType(Type& l, Type& r) case execplan::CalpontSystemCatalog::MEDINT: case execplan::CalpontSystemCatalog::TINYINT: case execplan::CalpontSystemCatalog::BIGINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UTINYINT: - case execplan::CalpontSystemCatalog::UBIGINT: fOperationType.colDataType = execplan::CalpontSystemCatalog::DECIMAL; fOperationType.scale = l.scale; fOperationType.colWidth = 8; @@ -255,13 +249,11 @@ void PredicateOperator::setOpType(Type& l, Type& r) fOperationType.colWidth = 8; } } - else if (r.colDataType == execplan::CalpontSystemCatalog::DECIMAL || - r.colDataType == execplan::CalpontSystemCatalog::UDECIMAL) + else if (r.colDataType == execplan::CalpontSystemCatalog::DECIMAL) { switch (l.colDataType) { case execplan::CalpontSystemCatalog::DECIMAL: - case execplan::CalpontSystemCatalog::UDECIMAL: { // should following the result type that MySQL gives based on the following logic? // @NOTE is this trustable? @@ -272,10 +264,6 @@ void PredicateOperator::setOpType(Type& l, Type& r) case execplan::CalpontSystemCatalog::MEDINT: case execplan::CalpontSystemCatalog::TINYINT: case execplan::CalpontSystemCatalog::BIGINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UTINYINT: - case execplan::CalpontSystemCatalog::UBIGINT: fOperationType.colDataType = execplan::CalpontSystemCatalog::DECIMAL; fOperationType.scale = r.scale; fOperationType.colWidth = 8; @@ -285,20 +273,20 @@ void PredicateOperator::setOpType(Type& l, Type& r) fOperationType.colWidth = 8; } } - // If both sides are unsigned, use UBIGINT as result type, otherwise - // "promote" to BIGINT. - else if (isUnsigned(l.colDataType) && isUnsigned(r.colDataType)) - { - fOperationType.colDataType = execplan::CalpontSystemCatalog::UBIGINT; - fOperationType.colWidth = 8; - } - else if ((isSignedInteger(l.colDataType) && isUnsigned(r.colDataType)) || - (isUnsigned(l.colDataType) && isSignedInteger(r.colDataType)) || - (isSignedInteger(l.colDataType) && isSignedInteger(r.colDataType))) - { - fOperationType.colDataType = execplan::CalpontSystemCatalog::BIGINT; - fOperationType.colWidth = 8; - } + else if ((l.colDataType == execplan::CalpontSystemCatalog::INT || + l.colDataType == execplan::CalpontSystemCatalog::SMALLINT || + l.colDataType == execplan::CalpontSystemCatalog::MEDINT || + l.colDataType == execplan::CalpontSystemCatalog::TINYINT || + l.colDataType == execplan::CalpontSystemCatalog::BIGINT) && + (r.colDataType == execplan::CalpontSystemCatalog::INT || + r.colDataType == execplan::CalpontSystemCatalog::SMALLINT || + r.colDataType == execplan::CalpontSystemCatalog::MEDINT || + r.colDataType == execplan::CalpontSystemCatalog::TINYINT || + r.colDataType == execplan::CalpontSystemCatalog::BIGINT)) + { + fOperationType.colDataType = execplan::CalpontSystemCatalog::BIGINT; + fOperationType.colWidth = 8; + } else if ((l.colDataType == execplan::CalpontSystemCatalog::CHAR || l.colDataType == execplan::CalpontSystemCatalog::VARCHAR) && (r.colDataType == execplan::CalpontSystemCatalog::CHAR || diff --git a/dbcon/execplan/predicateoperator.h b/dbcon/execplan/predicateoperator.h index 8964d994..cef9a286 100644 --- a/dbcon/execplan/predicateoperator.h +++ b/dbcon/execplan/predicateoperator.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: predicateoperator.h 9667 2013-07-08 16:37:10Z bpaul $ +* $Id: predicateoperator.h 9669 2013-07-08 19:49:36Z bpaul $ * * ***********************************************************************/ @@ -108,7 +108,7 @@ class PredicateOperator : public Operator { private: template inline bool numericCompare(result_t op1, result_t op2); - inline bool strCompare(const std::string& op1, const std::string& op2); + inline bool strCompare(std::string op1, std::string op2); }; inline bool PredicateOperator::getBoolVal(rowgroup::Row& row, bool& isNull, ReturnedColumn* lop, ReturnedColumn* rop) @@ -121,7 +121,7 @@ inline bool PredicateOperator::getBoolVal(rowgroup::Row& row, bool& isNull, Retu // Ugh. The strings returned by getStrVal have null padding out to the col width. boost::regex // considers these nulls significant, but they're not in the pattern, so we need to strip // them off... - const std::string& v = lop->getStrVal(row, isNull); + std::string v = lop->getStrVal(row, isNull); char* c = (char*)alloca(v.length() + 1); memcpy(c, v.c_str(), v.length()); c[v.length()] = 0; @@ -187,42 +187,8 @@ inline bool PredicateOperator::getBoolVal(rowgroup::Row& row, bool& isNull, Retu return numericCompare(val1, rop->getIntVal(row, isNull)) && !isNull; } - case execplan::CalpontSystemCatalog::UBIGINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UTINYINT: - case execplan::CalpontSystemCatalog::USMALLINT: - { - if (fOp == OP_ISNULL) - { - lop->getUintVal(row, isNull); - bool ret = isNull; - isNull = false; - return ret; - } - - if (fOp == OP_ISNOTNULL) - { - lop->getUintVal(row, isNull); - bool ret = isNull; - isNull = false; - return !ret; - } - - if (isNull) - return false; - - uint64_t val1 = lop->getUintVal(row, isNull); - if (isNull) - return false; - - return numericCompare(val1, rop->getUintVal(row, isNull)) && !isNull; - } - - case execplan::CalpontSystemCatalog::FLOAT: - case execplan::CalpontSystemCatalog::UFLOAT: case execplan::CalpontSystemCatalog::DOUBLE: - case execplan::CalpontSystemCatalog::UDOUBLE: + case execplan::CalpontSystemCatalog::FLOAT: { if (fOp == OP_ISNULL) { @@ -251,7 +217,6 @@ inline bool PredicateOperator::getBoolVal(rowgroup::Row& row, bool& isNull, Retu } case execplan::CalpontSystemCatalog::DECIMAL: - case execplan::CalpontSystemCatalog::UDECIMAL: { if (fOp == OP_ISNULL) { @@ -357,7 +322,7 @@ inline bool PredicateOperator::getBoolVal(rowgroup::Row& row, bool& isNull, Retu if (isNull) return false; - const std::string& val1 = lop->getStrVal(row, isNull); + std::string val1 = lop->getStrVal(row, isNull); if (isNull) return false; @@ -407,7 +372,7 @@ inline bool PredicateOperator::numericCompare(result_t op1, result_t op2) } } -inline bool PredicateOperator::strCompare(const std::string& op1, const std::string& op2) +inline bool PredicateOperator::strCompare(std::string op1, std::string op2) { switch (fOp) { diff --git a/dbcon/execplan/pseudocolumn.cpp b/dbcon/execplan/pseudocolumn.cpp deleted file mode 100644 index c39f5802..00000000 --- a/dbcon/execplan/pseudocolumn.cpp +++ /dev/null @@ -1,268 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: pseudocolumn.cpp 9576 2013-05-29 21:02:11Z zzhu $ -* -* -***********************************************************************/ - -#include -#include -#include -using namespace std; - -#include - -#include "bytestream.h" -using namespace messageqcpp; - -#include "objectreader.h" -#include "pseudocolumn.h" - -namespace execplan -{ - -/** - * Constructors/Destructors - */ -PseudoColumn::PseudoColumn(): - SimpleColumn(), - fPseudoType (PSEUDO_UNKNOWN) -{} - -PseudoColumn::PseudoColumn(const uint32_t pseudoType): - SimpleColumn(), - fPseudoType(pseudoType) -{} - -PseudoColumn::PseudoColumn(const string& token, - const uint32_t pseudoType, - const uint32_t sessionID): - SimpleColumn(token, sessionID), - fPseudoType(pseudoType) -{ - adjustResultType(); -} - -PseudoColumn::PseudoColumn(const string& schemaName, - const string& tableName, - const string& columnName, - const uint32_t pseudoType, - const uint32_t sessionID): - SimpleColumn(schemaName, tableName, columnName, sessionID), - fPseudoType(pseudoType) - -{} - -PseudoColumn::PseudoColumn(const string& schemaName, - const string& tableName, - const string& columnName, - const bool isInfiniDB, - const uint32_t pseudoType, - const uint32_t sessionID): - SimpleColumn(schemaName, tableName, columnName, isInfiniDB, sessionID), - fPseudoType(pseudoType) -{ - adjustResultType(); -} - -PseudoColumn::PseudoColumn (const SimpleColumn& rhs, - const uint32_t pseudoType, - const uint32_t sessionID): - SimpleColumn(rhs, sessionID), - fPseudoType(pseudoType) -{ - adjustResultType(); -} - -PseudoColumn::PseudoColumn(const PseudoColumn& rhs, const uint32_t sessionID): - SimpleColumn(rhs, sessionID), - fPseudoType (rhs.pseudoType()) -{ - adjustResultType(); -} - - - -PseudoColumn::~PseudoColumn() -{} - -/** - * Methods - */ - -PseudoColumn& PseudoColumn::operator=(const PseudoColumn& rhs) -{ - if (this != &rhs) - { - fTableName = rhs.tableName(); - fColumnName = rhs.columnName(); - fOid = rhs.oid(); - fSchemaName = rhs.schemaName(); - fAlias = rhs.alias(); - fTableAlias = rhs.tableAlias(); - fAsc = rhs.asc(); - fIndexName = rhs.indexName(); - fViewName = rhs.viewName(); - fData = rhs.data(); - fSequence = rhs.sequence(); - fDistinct = rhs.distinct(); - fIsInfiniDB = rhs.isInfiniDB(); - fPseudoType = rhs.pseudoType(); - } - - return *this; -} - -ostream& operator<<(ostream& output, const PseudoColumn& rhs) -{ - output << rhs.toString(); - - return output; -} - -const string PseudoColumn::toString() const -{ - ostringstream output; - output << "PseudoColumn " << data() << endl; - - output << "SimpleColumn " << data() << endl; - output << " s/t/c/v/o/ct/TA/CA/RA/#/card/join/source/engine: " << schemaName() << '/' - << tableName() << '/' - << columnName() << '/' - << viewName() << '/' - << oid() << '/' - << colDataTypeToString(fResultType.colDataType) << '/' - << tableAlias() << '/' - << alias() << '/' - << returnAll() << '/' - << sequence() << '/' - << cardinality() << '/' - << joinInfo() << '/' - << colSource() << '/' - << (isInfiniDB()? "InfiniDB" : "ForeignEngine") << endl; - - output << "Pseudotype=" << fPseudoType << endl; - return output.str(); -} - -void PseudoColumn::serialize(messageqcpp::ByteStream& b) const -{ - b << (ObjectReader::id_t) ObjectReader::PSEUDOCOLUMN; - SimpleColumn::serialize(b); - b << static_cast(fPseudoType); -} - -void PseudoColumn::unserialize(messageqcpp::ByteStream& b) -{ - ObjectReader::checkType(b, ObjectReader::PSEUDOCOLUMN); - SimpleColumn::unserialize(b); - b >> reinterpret_cast< ByteStream::quadbyte&>(fPseudoType); -} - -bool PseudoColumn::operator==(const PseudoColumn& t) const -{ - const SimpleColumn *rc1, *rc2; - - rc1 = static_cast(this); - rc2 = static_cast(&t); - if (*rc1 != *rc2) - return false; - if (fPseudoType != t.fPseudoType) - return false; - return true; -} - -bool PseudoColumn::operator==(const TreeNode* t) const -{ - const PseudoColumn *pc; - - pc = dynamic_cast(t); - if (pc == NULL) - return false; - return *this == *pc; -} - -bool PseudoColumn::operator!=(const PseudoColumn& t) const -{ - return !(*this == t); -} - -bool PseudoColumn::operator!=(const TreeNode* t) const -{ - return !(*this == t); -} - -uint32_t PseudoColumn::pseudoNameToType (string& name) -{ - if (boost::iequals(name, "idbpm")) - return PSEUDO_PM; - if (boost::iequals(name, "idbdbroot")) - return PSEUDO_DBROOT; - if (boost::iequals(name, "idbextentrelativerid")) - return PSEUDO_EXTENTRELATIVERID; - if (boost::iequals(name, "idbsegment")) - return PSEUDO_SEGMENT; - if (boost::iequals(name, "idbsegmentdir")) - return PSEUDO_SEGMENTDIR; - if (boost::iequals(name, "idbextentmin")) - return PSEUDO_EXTENTMIN; - if (boost::iequals(name, "idbextentmax")) - return PSEUDO_EXTENTMAX; - if (boost::iequals(name, "idbblockid")) - return PSEUDO_BLOCKID; - if (boost::iequals(name, "idbextentid")) - return PSEUDO_EXTENTID; - if (boost::iequals(name, "idbpartition")) - return PSEUDO_PARTITION; - if (boost::iequals(name, "idblocalpm")) - return PSEUDO_LOCALPM; - return PSEUDO_UNKNOWN; -} - -void PseudoColumn::adjustResultType() -{ - switch (fPseudoType) - { - case PSEUDO_EXTENTRELATIVERID: - case PSEUDO_DBROOT: - case PSEUDO_PM: - case PSEUDO_SEGMENT: - case PSEUDO_SEGMENTDIR: - case PSEUDO_BLOCKID: - case PSEUDO_EXTENTID: - { - fResultType.colDataType = CalpontSystemCatalog::BIGINT; - fResultType.colWidth = 8; - break; - } - case PSEUDO_PARTITION: - { - fResultType.colDataType = CalpontSystemCatalog::VARCHAR; - fResultType.colWidth = 256; - break; - } - default: - { - // same type of pseudocolumn arg - } - } - -} - -} // namespace execplan diff --git a/dbcon/execplan/pseudocolumn.h b/dbcon/execplan/pseudocolumn.h deleted file mode 100644 index e56ef8c4..00000000 --- a/dbcon/execplan/pseudocolumn.h +++ /dev/null @@ -1,166 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: simplecolumn.h 9679 2013-07-11 22:32:03Z zzhu $ -* -* -***********************************************************************/ -/** @file */ - -#ifndef PSEUDOCOLUMN_H -#define PSEUDOCOLUMN_H -#include -#include "simplecolumn.h" - -namespace messageqcpp { -class ByteStream; -} - -/** - * Namespace - */ -namespace execplan { - -const uint32_t PSEUDO_UNKNOWN = 0; -const uint32_t PSEUDO_EXTENTRELATIVERID = 1; -const uint32_t PSEUDO_DBROOT = 2; -const uint32_t PSEUDO_PM = 3; -const uint32_t PSEUDO_SEGMENT = 4; -const uint32_t PSEUDO_SEGMENTDIR = 5; -const uint32_t PSEUDO_EXTENTMIN = 6; -const uint32_t PSEUDO_EXTENTMAX = 7; -const uint32_t PSEUDO_BLOCKID = 8; -const uint32_t PSEUDO_EXTENTID = 9; -const uint32_t PSEUDO_PARTITION = 10; -const uint32_t PSEUDO_LOCALPM = 11; - -/** - * @brief A class to represent a pseudo column - * - * This class is a specialization of class SimpleColumn that handles - * a pseudocolumn. - */ -class PseudoColumn : public SimpleColumn { - -public: - - /** - * Constructors - */ - PseudoColumn(); - PseudoColumn(const uint32_t pseudoType); - PseudoColumn(const std::string& token, - const uint32_t pseudoType, - const uint32_t sessionID = 0); - PseudoColumn(const std::string& schema, - const std::string& table, - const std::string& col, - const uint32_t pseudoType, - const uint32_t sessionID = 0); - PseudoColumn(const std::string& schema, - const std::string& table, - const std::string& col, - const bool isInfiniDB, - const uint32_t pseudoType, - const uint32_t sessionID = 0); - PseudoColumn(const SimpleColumn& rhs, const uint32_t pseudoType, const uint32_t sessionID = 0); - PseudoColumn(const PseudoColumn& rhs, const uint32_t sessionID = 0); - - /** - * Destructor - */ - virtual ~PseudoColumn(); - - /** return a copy of this pointer - * - * deep copy of this pointer and return the copy - */ - inline virtual PseudoColumn* clone() const - { - return new PseudoColumn (*this); - } - - /** - * Overloaded assignment operator - */ - PseudoColumn& operator=(const PseudoColumn& rhs); - - /** - * Accessor and mutator - */ - const uint32_t pseudoType() const - { - return fPseudoType; - } - - void pseudoType (const uint32_t pseudoType) - { - fPseudoType = pseudoType; - } - - /** - * The serialize interface - */ - virtual void serialize(messageqcpp::ByteStream&) const; - virtual void unserialize(messageqcpp::ByteStream&); - - virtual const std::string toString() const; - - /** @brief Do a deep, strict (as opposed to semantic) equivalence test - * - * Do a deep, strict (as opposed to semantic) equivalence test. - * @return true iff every member of t is a duplicate copy of every member of this; false otherwise - */ - virtual bool operator==(const TreeNode* t) const; - - /** @brief Do a deep, strict (as opposed to semantic) equivalence test - * - * Do a deep, strict (as opposed to semantic) equivalence test. - * @return true iff every member of t is a duplicate copy of every member of this; false otherwise - */ - bool operator==(const PseudoColumn& t) const; - - /** @brief Do a deep, strict (as opposed to semantic) equivalence test - * - * Do a deep, strict (as opposed to semantic) equivalence test. - * @return false iff every member of t is a duplicate copy of every member of this; true otherwise - */ - virtual bool operator!=(const TreeNode* t) const; - - /** @brief Do a deep, strict (as opposed to semantic) equivalence test - * - * Do a deep, strict (as opposed to semantic) equivalence test. - * @return false iff every member of t is a duplicate copy of every member of this; true otherwise - */ - bool operator!=(const PseudoColumn& t) const; - - static uint32_t pseudoNameToType(std::string& name); - - -private: - /** - * Fields - */ - uint32_t fPseudoType; - void adjustResultType(); -}; - -} // namespace execplan - -#endif //PSEUDOCOLUMN_H - diff --git a/dbcon/execplan/range.cpp b/dbcon/execplan/range.cpp index 859de25e..e8541b14 100644 --- a/dbcon/execplan/range.cpp +++ b/dbcon/execplan/range.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: range.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: range.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/range.h b/dbcon/execplan/range.h index 1ca2094b..9240294c 100644 --- a/dbcon/execplan/range.h +++ b/dbcon/execplan/range.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: range.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: range.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/returnedcolumn.cpp b/dbcon/execplan/returnedcolumn.cpp index f3b7f9a1..814251be 100644 --- a/dbcon/execplan/returnedcolumn.cpp +++ b/dbcon/execplan/returnedcolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: returnedcolumn.cpp 9413 2013-04-22 22:03:42Z zzhu $ +* $Id: returnedcolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -43,14 +43,12 @@ ReturnedColumn::ReturnedColumn(): fReturnAll (false), fDistinct(false), fJoinInfo(0), fAsc(true), - fNullsFirst(true), fOrderPos((uint64_t)-1), fColSource(0), fColPosition(-1), - fHasAggregate(false), fInputIndex(-1), fOutputIndex(-1), - fExpressionId ((uint32_t)-1) + fExpressionId ((uint)-1) { } @@ -62,19 +60,17 @@ ReturnedColumn::ReturnedColumn(const string& sql): fDistinct(false), fJoinInfo(0), fAsc(true), - fNullsFirst(true), fOrderPos((uint64_t)-1), fColSource(0), fColPosition(-1), - fHasAggregate(false), fData(sql), fInputIndex(-1), fOutputIndex(-1), - fExpressionId ((uint32_t)-1) + fExpressionId ((uint)-1) { } -ReturnedColumn::ReturnedColumn(const uint32_t sessionID, const bool returnAll): +ReturnedColumn::ReturnedColumn(const u_int32_t sessionID, const bool returnAll): fReturnAll(returnAll), fSessionID(sessionID), fSequence(-1), @@ -82,18 +78,16 @@ ReturnedColumn::ReturnedColumn(const uint32_t sessionID, const bool returnAll): fDistinct(false), fJoinInfo(0), fAsc(true), - fNullsFirst(true), fOrderPos((uint64_t)-1), fColSource(0), fColPosition(-1), - fHasAggregate(false), fInputIndex(-1), fOutputIndex(-1), - fExpressionId ((uint32_t)-1) + fExpressionId ((uint)-1) { } -ReturnedColumn::ReturnedColumn(const ReturnedColumn& rhs, const uint32_t sessionID): +ReturnedColumn::ReturnedColumn(const ReturnedColumn& rhs, const u_int32_t sessionID): TreeNode(rhs), fReturnAll(rhs.fReturnAll), fSessionID(sessionID), @@ -102,11 +96,9 @@ ReturnedColumn::ReturnedColumn(const ReturnedColumn& rhs, const uint32_t session fDistinct(rhs.fDistinct), fJoinInfo(rhs.fJoinInfo), fAsc(rhs.fAsc), - fNullsFirst(rhs.fNullsFirst), fOrderPos(rhs.fOrderPos), fColSource(rhs.fColSource), fColPosition(rhs.fColPosition), - fHasAggregate(rhs.fHasAggregate), fData(rhs.fData), fInputIndex(rhs.fInputIndex), fOutputIndex(rhs.fOutputIndex), @@ -135,15 +127,13 @@ void ReturnedColumn::serialize(messageqcpp::ByteStream& b) const b << fAlias; b << (uint8_t)fDistinct; b << (uint64_t)fJoinInfo; - b << (uint8_t)fAsc; - b << (uint8_t)fNullsFirst; + b << static_cast(fAsc); b << (uint64_t)fOrderPos; b << (uint64_t)fColSource; - b << (int64_t)fColPosition; + b << (uint64_t)fColPosition; b << (uint32_t)fInputIndex; b << (uint32_t)fOutputIndex; - b << (int32_t)fSequence; - b << (uint8_t)fReturnAll; + b << (uint32_t)fSequence; fResultType.serialize(b); fOperationType.serialize(b); b << (uint32_t)fExpressionId; @@ -157,15 +147,13 @@ void ReturnedColumn::unserialize(messageqcpp::ByteStream& b) b >> fAlias; b >> (uint8_t&)fDistinct; b >> (uint64_t&)fJoinInfo; - b >> (uint8_t&)fAsc; - b >> (uint8_t&)fNullsFirst; + b >> reinterpret_cast< ByteStream::doublebyte&>(fAsc); b >> (uint64_t&)fOrderPos; b >> (uint64_t&)fColSource; - b >> (int64_t&)fColPosition; + b >> (uint64_t&)fColPosition; b >> (uint32_t&)fInputIndex; b >> (uint32_t&)fOutputIndex; - b >> (int32_t&)fSequence; - b >> (uint8_t&)fReturnAll; + b >> (uint32_t&)fSequence; fResultType.unserialize(b); fOperationType.unserialize(b); b >> (uint32_t&)fExpressionId; @@ -185,8 +173,6 @@ bool ReturnedColumn::operator==(const ReturnedColumn& t) const return false; if (fAsc != t.fAsc) return false; - if (fNullsFirst != t.fNullsFirst) - return false; //if (fOrderPos != t.fOrderPos) // return false; if (fInputIndex != t.fInputIndex) @@ -231,18 +217,7 @@ const string ReturnedColumn::data() const const string ReturnedColumn::toString() const { - ostringstream oss; - oss << ">ReturnedColumn " << fJoinInfo << "<" << endl; - return oss.str(); + return string(">ReturnedColumn<"); } -// All columns that may have simple column added to the list need to implement -// this function. Default behavior is to have no SC added to the list so -// fSimpleColumnList will be cleared. -void ReturnedColumn::setSimpleColumnList() -{ - fSimpleColumnList.clear(); -} - - } // namespace execplan diff --git a/dbcon/execplan/returnedcolumn.h b/dbcon/execplan/returnedcolumn.h index 4b10f918..fd45639f 100644 --- a/dbcon/execplan/returnedcolumn.h +++ b/dbcon/execplan/returnedcolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: returnedcolumn.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: returnedcolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -32,6 +32,8 @@ #include "treenode.h" #include "calpontsystemcatalog.h" +//#include "exceptclasses.h" +//#include "dataconvert.h" namespace messageqcpp { class ByteStream; @@ -66,11 +68,6 @@ const uint64_t CORRELATED_JOIN = 0x0008; */ class SimpleColumn; class AggregateColumn; -class WindowFunctionColumn; -class ReturnedColumn; -class CalpontSelectExecutionPlan; - -typedef boost::shared_ptr SRCP; /** * @brief class ReturnedColumn @@ -84,8 +81,8 @@ class ReturnedColumn : public TreeNode { */ ReturnedColumn(); ReturnedColumn(const std::string& sql); - ReturnedColumn(const uint32_t sessionID, const bool returnAll = false); - ReturnedColumn(const ReturnedColumn& rhs, const uint32_t sessionID = 0); + ReturnedColumn(const u_int32_t sessionID, const bool returnAll = false); + ReturnedColumn(const ReturnedColumn& rhs, const u_int32_t sessionID = 0); /** * Destructors @@ -101,11 +98,11 @@ class ReturnedColumn : public TreeNode { virtual const bool returnAll() const {return fReturnAll;} virtual void returnAll(const bool returnAll) { fReturnAll = returnAll; } - const uint32_t sessionID() const {return fSessionID;} - void sessionID(const uint32_t sessionID) { fSessionID = sessionID; } + const u_int32_t sessionID() const {return fSessionID;} + void sessionID(const u_int32_t sessionID) { fSessionID = sessionID; } - inline const int32_t sequence() const {return fSequence;} - inline void sequence(const int32_t sequence) {fSequence = sequence;} + inline const uint32_t sequence() const {return fSequence;} + inline void sequence(const uint32_t sequence) {fSequence = sequence;} inline const std::string& alias() const { return fAlias; } inline void alias(const std::string& alias) { fAlias = alias; } @@ -116,8 +113,8 @@ class ReturnedColumn : public TreeNode { virtual bool distinct() const { return fDistinct;} virtual void distinct(const bool distinct) { fDistinct=distinct; } - const uint32_t expressionId() const { return fExpressionId; } - void expressionId(const uint32_t expressionId) { fExpressionId = expressionId; } + const uint expressionId() const { return fExpressionId; } + void expressionId(const uint expressionId) { fExpressionId = expressionId; } virtual uint64_t joinInfo() const { return fJoinInfo; } virtual void joinInfo(const uint64_t joinInfo) { fJoinInfo = joinInfo; } @@ -125,21 +122,14 @@ class ReturnedColumn : public TreeNode { virtual const bool asc() const { return fAsc; } virtual void asc(const bool asc) { fAsc = asc; } - virtual const bool nullsFirst() const { return fNullsFirst; } - virtual void nullsFirst(const bool nullsFirst) { fNullsFirst = nullsFirst; } - virtual uint64_t orderPos() const { return fOrderPos; } virtual void orderPos(const uint64_t orderPos) { fOrderPos = orderPos; } virtual uint64_t colSource() const { return fColSource; } virtual void colSource(const uint64_t colSource) { fColSource = colSource; } - - virtual int64_t colPosition() const { return fColPosition; } - virtual void colPosition(const int64_t colPosition) { fColPosition = colPosition; } - - // Columns that may have aggregate column involved should implement this interface. - virtual bool hasAggregate() { return fHasAggregate;} - virtual void hasAggregate(bool hasAgg) { fHasAggregate = hasAgg; } + + virtual uint64_t colPosition() const { return fColPosition; } + virtual void colPosition(const uint64_t colPosition) { fColPosition = colPosition; } /** * Operations @@ -191,60 +181,29 @@ class ReturnedColumn : public TreeNode { virtual bool sameColumn(const ReturnedColumn* rc) const {return (fData.compare(rc->data()) == 0);} - virtual const std::vector& simpleColumnList() const + // get all simple columns involved in this expression + const std::vector& simpleColumnList() const { return fSimpleColumnList; } - /* @brief traverse this ReturnedColumn and re-populate fSimpleColumnList. - * - * @note all ReturnedColumns that may have simple column arguments added - * to the list need to implement thhis function. - */ - virtual void setSimpleColumnList(); - - // get all aggregate column list in this expression + // get & set aggregate column list in this expression const std::vector& aggColumnList() const { return fAggColumnList; } - // get all window function column list in this expression - const std::vector& windowfunctionColumnList() const - { return fWindowFunctionColumnList; } - - /* @brief if this column is or contains window function column - * - * @note after this function call fWindowFunctionColumnList is populated - */ - virtual bool hasWindowFunc() = 0; - - virtual void replaceRealCol(std::vector&){} - - /** - * Return the tableAlias name of the table that the column arguments belong to. - * - * @param TableAliasName that will be set in the function - * @return true, if all arguments belong to one table - * false, if multiple tables are involved in the function - */ - virtual bool singleTable(CalpontSystemCatalog::TableAliasName& tan) - { return false; } - protected: // return all flag set if the other column is outer join column (+) bool fReturnAll; uint32_t fSessionID; - int32_t fSequence; /// column sequence on the SELECT mapped to the correlated joins + uint32_t fSequence; /// column sequence on the SELECT mapped to the correlated joins uint64_t fCardinality; - std::string fAlias; /// column alias + std::string fAlias; /// column alias bool fDistinct; uint64_t fJoinInfo; - bool fAsc; /// for order by column - bool fNullsFirst; /// for window function - uint64_t fOrderPos; /// for order by and group by column - uint64_t fColSource; /// from which subquery - int64_t fColPosition; /// the column position in the source subquery + bool fAsc; /// for order by column + uint64_t fOrderPos; /// for order by and group by column + uint64_t fColSource; /// from which subquery + uint64_t fColPosition; /// the column position in the source subquery std::vector fSimpleColumnList; std::vector fAggColumnList; - std::vector fWindowFunctionColumnList; - bool fHasAggregate; /// connector internal use. no need to serialize private: std::string fData; @@ -253,18 +212,20 @@ class ReturnedColumn : public TreeNode { * F&E framework * ******************************************************************/ public: - const uint32_t inputIndex() const { return fInputIndex; } - void inputIndex ( const uint32_t inputIndex ) { fInputIndex = inputIndex; } - const uint32_t outputIndex() const { return fOutputIndex; } - void outputIndex ( const uint32_t outputIndex ) { fOutputIndex = outputIndex; } + const uint inputIndex() const { return fInputIndex; } + void inputIndex ( const uint inputIndex ) { fInputIndex = inputIndex; } + const uint outputIndex() const { return fOutputIndex; } + void outputIndex ( const uint outputIndex ) { fOutputIndex = outputIndex; } protected: - std::string fErrMsg; /// error occured in evaluation - uint32_t fInputIndex; /// index to the input rowgroup - uint32_t fOutputIndex; /// index to the output rowgroup - uint32_t fExpressionId; /// unique id for this expression + std::string fErrMsg; // error occured in evaluation + uint32_t fInputIndex; // index to the input rowgroup + uint32_t fOutputIndex; // index to the output rowgroup + uint fExpressionId; // unique id for this expression }; +typedef boost::shared_ptr SRCP; + std::ostream& operator<<(std::ostream& os, const ReturnedColumn& rhs); } diff --git a/dbcon/execplan/rowcolumn.cpp b/dbcon/execplan/rowcolumn.cpp index 29cccff2..ea931a2e 100644 --- a/dbcon/execplan/rowcolumn.cpp +++ b/dbcon/execplan/rowcolumn.cpp @@ -66,7 +66,7 @@ RowColumn::RowColumn (const RowColumn& rhs, const uint32_t sessionID): fColumnVec.clear(); //fColumnVec = rhs.fColumnVec; SRCP srcp; - for (uint32_t i = 0; i < rhs.fColumnVec.size(); i++) + for (uint i = 0; i < rhs.fColumnVec.size(); i++) { srcp.reset(rhs.fColumnVec[i]->clone()); fColumnVec.push_back(srcp); @@ -102,7 +102,7 @@ const string RowColumn::toString() const { ostringstream output; output << "RowColumn" << endl; - for (uint32_t i = 0; i < fColumnVec.size(); i++) + for (uint i = 0; i < fColumnVec.size(); i++) output << fColumnVec[i]->toString(); return output.str(); @@ -113,7 +113,7 @@ void RowColumn::serialize(messageqcpp::ByteStream& b) const b << (ObjectReader::id_t) ObjectReader::ROWCOLUMN; ReturnedColumn::serialize(b); b << (uint32_t)fColumnVec.size(); - for (uint32_t i = 0; i < fColumnVec.size(); i++) + for (uint i = 0; i < fColumnVec.size(); i++) fColumnVec[i]->serialize(b); } @@ -125,7 +125,7 @@ void RowColumn::unserialize(messageqcpp::ByteStream& b) uint32_t size; SRCP srcp; b >> (uint32_t&)size; - for (uint32_t i = 0; i < size; i++) + for (uint i = 0; i < size; i++) { srcp.reset(dynamic_cast((ObjectReader::createTreeNode(b)))); fColumnVec.push_back(srcp); @@ -136,7 +136,7 @@ bool RowColumn::operator==(const RowColumn& t) const { if (fColumnVec.size() != t.columnVec().size()) return false; - for (uint32_t i = 0; i < fColumnVec.size(); i++) + for (uint i = 0; i < fColumnVec.size(); i++) { if (fColumnVec[i].get() != NULL) { @@ -172,15 +172,4 @@ bool RowColumn::operator!=(const TreeNode* t) const return !(*this == t); } -ostream& operator<<(ostream &output, const SubSelect& ss) -{ - output << ss.toString() << endl; - return output; -} - -const string SubSelect::toString() const -{ - return string(">SubSelect<"); -} - } // namespace execplan diff --git a/dbcon/execplan/rowcolumn.h b/dbcon/execplan/rowcolumn.h index db5ad025..714f26df 100644 --- a/dbcon/execplan/rowcolumn.h +++ b/dbcon/execplan/rowcolumn.h @@ -14,6 +14,7 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + /*********************************************************************** * $Id: rowcolumn.h 6309 2010-03-04 19:33:12Z zzhu $ * @@ -126,8 +127,6 @@ class RowColumn : public ReturnedColumn { * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ bool operator!=(const RowColumn& t) const; - virtual bool hasAggregate() {return false;} - virtual bool hasWindowFunc() {return false;} private: /** @@ -144,9 +143,6 @@ class SubSelect : public ReturnedColumn SubSelect(): ReturnedColumn() {} ~SubSelect() {} SubSelect* clone() const { return new SubSelect(); } - virtual bool hasAggregate() {return false;} - virtual bool hasWindowFunc() {return false;} - virtual const std::string toString() const; }; diff --git a/dbcon/execplan/selectfilter.cpp b/dbcon/execplan/selectfilter.cpp index 73c858e2..5757fb57 100644 --- a/dbcon/execplan/selectfilter.cpp +++ b/dbcon/execplan/selectfilter.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: selectfilter.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: selectfilter.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -65,7 +65,7 @@ const string SelectFilter::toString() const { ostringstream oss; oss << "SelectFilter " << "returnedColPos=" << fReturnedColPos << endl; - for (uint32_t i = 0; i < fCols.size(); i++) + for (uint i = 0; i < fCols.size(); i++) oss << fCols[i]->toString(); oss << fOp->toString() << endl; oss << *(fSub.get()); @@ -83,7 +83,7 @@ void SelectFilter::serialize(messageqcpp::ByteStream& b) const b << static_cast(ObjectReader::SELECTFILTER); Filter::serialize(b); b << static_cast(fCols.size()); - for (uint32_t i = 0; i < fCols.size(); i++) + for (uint i = 0; i < fCols.size(); i++) { if (fCols[i] != NULL) fCols[i]->serialize(b); @@ -110,7 +110,7 @@ void SelectFilter::unserialize(messageqcpp::ByteStream& b) uint32_t size; SRCP srcp; b >> size; - for (uint32_t i = 0; i < size; i++) + for (uint i = 0; i < size; i++) { srcp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); fCols.push_back(srcp); @@ -130,7 +130,7 @@ bool SelectFilter::operator==(const SelectFilter& t) const return false; if (fCols.size() != t.fCols.size()) return false; - for (uint32_t i = 0; i < fCols.size(); i++) + for (uint i = 0; i < fCols.size(); i++) { if (fCols[i] != NULL) { if (*(fCols[i]) != *(t.fCols[i])) diff --git a/dbcon/execplan/selectfilter.h b/dbcon/execplan/selectfilter.h index 4467ac79..caded936 100644 --- a/dbcon/execplan/selectfilter.h +++ b/dbcon/execplan/selectfilter.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: selectfilter.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: selectfilter.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/sessionmanager.cpp b/dbcon/execplan/sessionmanager.cpp index 70c9f701..8ebce7ca 100644 --- a/dbcon/execplan/sessionmanager.cpp +++ b/dbcon/execplan/sessionmanager.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: sessionmanager.cpp 9215 2013-01-24 18:40:12Z pleblanc $ + * $Id: sessionmanager.cpp 8924 2012-09-19 18:25:54Z pleblanc $ * ****************************************************************************/ @@ -69,12 +69,12 @@ SessionManager::~SessionManager() { } -const QueryContext SessionManager::verID() +const CalpontSystemCatalog::SCN SessionManager::verID() { return dbrm.verID(); } -const QueryContext SessionManager::sysCatVerID() +const CalpontSystemCatalog::SCN SessionManager::sysCatVerID() { return dbrm.sysCatVerID(); } diff --git a/dbcon/execplan/sessionmanager.h b/dbcon/execplan/sessionmanager.h index b5100da6..f259118c 100644 --- a/dbcon/execplan/sessionmanager.h +++ b/dbcon/execplan/sessionmanager.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: sessionmanager.h 9215 2013-01-24 18:40:12Z pleblanc $ + * $Id: sessionmanager.h 8924 2012-09-19 18:25:54Z pleblanc $ * *****************************************************************************/ @@ -29,6 +29,7 @@ #include "calpontsystemcatalog.h" #include "brm.h" +#include "brmtypes.h" #include "boost/shared_array.hpp" namespace execplan { @@ -76,6 +77,34 @@ class SessionManager { /** @brief SID = Session ID */ typedef uint32_t SID; + /** @brief A type describing a single transaction ID */ +// struct _TxnID { + /// The TransactionID number +// CalpontSystemCatalog::SCN id; + /// True iff the id is valid. +// bool valid; +// _TxnID(); +// }; + /** @brief A type describing a single transaction ID */ +// typedef struct _TxnID TxnID; + + /** @brief A type associating a session with a transaction */ +// struct _SIDTIDEntry { + /// The Transaction ID. txnid.valid determines whether or not this SIDTIDEntry is valid +// TxnID txnid; + /// The session doing the transaction +// SID sessionid; + /// tableOID the table OID involved in the transaction or cpimport +// CalpontSystemCatalog::OID tableOID; + /// processID the process ID which locked the table, only valid when table is locked. +// u_int32_t processID; + ///processName the process name which locked the table, only valid when table is locked. +// std::string processName; + +// _SIDTIDEntry(); +// }; + /** @brief A type associating a session with a transaction */ +// typedef struct _SIDTIDEntry SIDTIDEntry; /** @brief Constructor * @@ -111,13 +140,13 @@ class SessionManager { * * Gets the current version ID. */ - const BRM::QueryContext verID(); + const CalpontSystemCatalog::SCN verID(void); /** @brief Gets the current systemcatalog version ID * * Gets the current systemcatalog version ID. */ - const BRM::QueryContext sysCatVerID(); + const CalpontSystemCatalog::SCN sysCatVerID(void); /** @brief Gets a new Transaction ID * diff --git a/dbcon/execplan/sessionmonitor.cpp b/dbcon/execplan/sessionmonitor.cpp index 5526dc8e..bee21785 100644 --- a/dbcon/execplan/sessionmonitor.cpp +++ b/dbcon/execplan/sessionmonitor.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: sessionmonitor.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: sessionmonitor.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ @@ -273,7 +273,7 @@ void SessionMonitor::copyPreviousSegment() bool SessionMonitor::readMonitorDataFromFile(const std::string filename) { int err = 0; - uint32_t headerSize = 2*sizeof(int); + uint headerSize = 2*sizeof(int); char* data = reinterpret_cast(&fPrevSegment); int fd = open(filename.c_str(), O_RDONLY); diff --git a/dbcon/execplan/sessionmonitor.h b/dbcon/execplan/sessionmonitor.h index 9e144b89..8af3b472 100644 --- a/dbcon/execplan/sessionmonitor.h +++ b/dbcon/execplan/sessionmonitor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: sessionmonitor.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: sessionmonitor.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ @@ -199,7 +199,7 @@ class SessionMonitor { // the second is used to block processes when there are too many concurrent txns int fsems; int fshmid; // shared memory segment id - uint32_t fuid; // user id used to create the shared memory key + u_int32_t fuid; // user id used to create the shared memory key SessionManager sm; diff --git a/dbcon/execplan/simplecolumn.cpp b/dbcon/execplan/simplecolumn.cpp index 2799c05e..ffd5a65e 100644 --- a/dbcon/execplan/simplecolumn.cpp +++ b/dbcon/execplan/simplecolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: simplecolumn.cpp 9576 2013-05-29 21:02:11Z zzhu $ +* $Id: simplecolumn.cpp 8565 2012-05-28 20:48:07Z xlou $ * * ***********************************************************************/ @@ -49,7 +49,6 @@ using namespace joblist; #include "simplefilter.h" #include "aggregatecolumn.h" #include "constantfilter.h" -#include "windowfunction.h" namespace execplan { @@ -64,84 +63,33 @@ void getSimpleCols(execplan::ParseTree* n, void* obj) SimpleFilter *sf = dynamic_cast(tn); ConstantFilter *cf = dynamic_cast(tn); if (sc) - { list->push_back(sc); - } else if (fc) - { - fc->setSimpleColumnList(); list->insert(list->end(), fc->simpleColumnList().begin(), fc->simpleColumnList().end()); - } else if (ac) - { - ac->setSimpleColumnList(); list->insert(list->end(), ac->simpleColumnList().begin(), ac->simpleColumnList().end()); - } else if (sf) - { - sf->setSimpleColumnList(); list->insert(list->end(), sf->simpleColumnList().begin(), sf->simpleColumnList().end()); - } else if (cf) - { - cf->setSimpleColumnList(); list->insert(list->end(), cf->simpleColumnList().begin(), cf->simpleColumnList().end()); - } -} - -ParseTree* replaceRefCol(ParseTree*& n, CalpontSelectExecutionPlan::ReturnedColumnList& derivedColList) -{ - ParseTree *lhs = n->left(); - ParseTree *rhs = n->right(); - - if (lhs) - n->left(replaceRefCol(lhs, derivedColList)); - if (rhs) - n->right(replaceRefCol(rhs, derivedColList)); - SimpleFilter *sf = dynamic_cast(n->data()); - ConstantFilter *cf = dynamic_cast(n->data()); - ReturnedColumn *rc = dynamic_cast(n->data()); - if (sf) - { - sf->replaceRealCol(derivedColList); - } - else if (cf) - { - cf->replaceRealCol(derivedColList); - } - else if (rc) - { - SimpleColumn* sc = dynamic_cast(rc); - if (sc) - { - ReturnedColumn* tmp = derivedColList[sc->colPosition()]->clone(); - delete sc; - n->data(tmp); - } - else - { - rc->replaceRealCol(derivedColList); - } - } - return n; } /** * Constructors/Destructors */ SimpleColumn::SimpleColumn(): - ReturnedColumn(), - fOid (0), - fIsInfiniDB (true) + ReturnedColumn(), + fOid (0), + fIsInfiniDB (true) { fDistinct=false; } -SimpleColumn::SimpleColumn(const string& token, const uint32_t sessionID): - ReturnedColumn(sessionID), - fOid (0), - fData(token), - fIsInfiniDB (true) +SimpleColumn::SimpleColumn(const string& token, const u_int32_t sessionID): + ReturnedColumn(sessionID), + fOid (0), + fData(token), + fIsInfiniDB (true) { parse (token); setOID(); @@ -149,38 +97,40 @@ SimpleColumn::SimpleColumn(const string& token, const uint32_t sessionID): } SimpleColumn::SimpleColumn(const string& schemaName, - const string& tableName, - const string& columnName, - const uint32_t sessionID): - ReturnedColumn(sessionID), - fSchemaName (schemaName), - fTableName (tableName), - fColumnName (columnName), - fIsInfiniDB (true) + const string& tableName, + const string& columnName, + const u_int32_t sessionID): + ReturnedColumn(sessionID), + fSchemaName (schemaName), + fTableName (tableName), + fColumnName (columnName), + fIsInfiniDB (true) { setOID(); fDistinct=false; + fAsc=false; } SimpleColumn::SimpleColumn(const string& schemaName, - const string& tableName, - const string& columnName, - const bool isInfiniDB, - const uint32_t sessionID): - ReturnedColumn(sessionID), - fSchemaName (schemaName), - fTableName (tableName), - fColumnName (columnName), - fIsInfiniDB (isInfiniDB) + const string& tableName, + const string& columnName, + const bool isInfiniDB, + const u_int32_t sessionID): + ReturnedColumn(sessionID), + fSchemaName (schemaName), + fTableName (tableName), + fColumnName (columnName), + fIsInfiniDB (isInfiniDB) { if (isInfiniDB) setOID(); fDistinct=false; + fAsc=false; } -SimpleColumn::SimpleColumn (const SimpleColumn& rhs,const uint32_t sessionID): - ReturnedColumn(rhs, sessionID), - fSchemaName (rhs.schemaName()), +SimpleColumn::SimpleColumn (const SimpleColumn& rhs,const u_int32_t sessionID): + ReturnedColumn(rhs, sessionID), + fSchemaName (rhs.schemaName()), fTableName (rhs.tableName()), fColumnName (rhs.columnName()), fOid (rhs.oid()), @@ -194,6 +144,7 @@ SimpleColumn::SimpleColumn (const SimpleColumn& rhs,const uint32_t sessionID): SimpleColumn::~SimpleColumn() {} + /** * Methods */ @@ -240,86 +191,94 @@ const string SimpleColumn::toString() const { ostringstream output; output << "SimpleColumn " << data() << endl; - output << " s/t/c/v/o/ct/TA/CA/RA/#/card/join/source/engine/colPos: " << schemaName() << '/' - << tableName() << '/' - << columnName() << '/' - << viewName() << '/' - << oid() << '/' - << colDataTypeToString(fResultType.colDataType) << '/' - << tableAlias() << '/' - << alias() << '/' - << returnAll() << '/' - << sequence() << '/' - << cardinality() << '/' - << joinInfo() << '/' - << colSource() << '/' - << (isInfiniDB()? "InfiniDB" : "ForeignEngine") << '/' - << colPosition() << endl; + output << " s/t/c/v/o/TA/CA/RA/#/card/join/source/engine: " << schemaName() << '/' + << tableName() << '/' + << columnName() << '/' + << viewName() << '/' + << oid() << '/' + << tableAlias() << '/' + << alias() << '/' + << returnAll() << '/' + << (int32_t)sequence() << '/' + << cardinality() << '/' + << joinInfo() << '/' + << colSource() << '/' + << (isInfiniDB()? "InfiniDB" : "ForeignEngine") << endl; return output.str(); } void SimpleColumn::parse(const string& token) { - // get schema name, table name and column name for token. - string::size_type pos = token.find_first_of(".", 0); - - // if no '.' in column name, consider it a function name; - if (pos == string::npos) - { - fData = token; - fColumnName = token; - return; - } - fSchemaName = token.substr(0, pos); - - string::size_type newPos = token.find_first_of(".", pos+1); - if (newPos == string::npos) - { - // only one '.' in column name, consider table.col pattern - fTableName = fSchemaName; - fColumnName = token.substr(pos+1, token.length()); - return; - } - - fTableName = token.substr(pos+1, newPos-pos-1); - fColumnName = token.substr(newPos+1, token.length()); + // get schema name, table name and column name for token. + string::size_type pos = token.find_first_of(".", 0); + + // if no '.' in column name, consider it a function name; + if (pos == string::npos) + { + fData = token; + fColumnName = token; + return; + } + fSchemaName = token.substr(0, pos); + + string::size_type newPos = token.find_first_of(".", pos+1); + if (newPos == string::npos) + { + // only one '.' in column name, consider table.col pattern + fTableName = fSchemaName; + fColumnName = token.substr(pos+1, token.length()); + return; + } + + fTableName = token.substr(pos+1, newPos-pos-1); + fColumnName = token.substr(newPos+1, token.length()); } void SimpleColumn::setOID() { - boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); - CalpontSystemCatalog::TableColName tcn; - tcn = make_tcn(fSchemaName, fTableName, fColumnName); - - fOid = csc->lookupOID (tcn); - if (fOid == -1) - { - // get colMap from CalpontSelectExecutionPlan - // and try to map the schema and table name - CalpontSelectExecutionPlan::ColumnMap::iterator iter; - CalpontSelectExecutionPlan::ColumnMap colMap = CalpontSelectExecutionPlan::colMap(); - - // if this is the only column name exist in the map, return it ?? - for (iter = colMap.find(fColumnName); iter != colMap.end(); ++iter) - { - SRCP srcp = iter->second; - SimpleColumn* scp = dynamic_cast(srcp.get()); - if (colMap.count(fColumnName) == 1 || - scp->tableName().compare(fTableName) == 0) - { - fOid = scp->oid(); - //@bug 221 fix - fTableName = scp->tableName(); - fSchemaName = scp->schemaName(); - //@info assign tableAlias also. watch for other conflict - fTableAlias = scp->tableAlias(); - fResultType = scp->resultType(); - return; - } - } - } - fResultType = csc->colType(fOid); + boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); + CalpontSystemCatalog::TableColName tcn; + // @bug #393 + if (fSchemaName.length() == 0 || fTableName.length() == 0) + tcn = make_tcn(CalpontSelectExecutionPlan::schemaName(), CalpontSelectExecutionPlan::tableName(), fColumnName); + else + tcn = make_tcn(fSchemaName, fTableName, fColumnName); + + fOid = csc->lookupOID (tcn); + if (fOid != -1) + { + if (fSchemaName.length() == 0 || fTableName.length() == 0) + { + fSchemaName = CalpontSelectExecutionPlan::schemaName(); + fTableName = CalpontSelectExecutionPlan::tableName(); + } + } + else + { + // get colMap from CalpontSelectExecutionPlan + // and try to map the schema and table name + CalpontSelectExecutionPlan::ColumnMap::iterator iter; + CalpontSelectExecutionPlan::ColumnMap colMap = CalpontSelectExecutionPlan::colMap(); + + // if this is the only column name exist in the map, return it ?? + for (iter = colMap.find(fColumnName); iter != colMap.end(); ++iter) + { + SRCP srcp = iter->second; + SimpleColumn* scp = dynamic_cast(srcp.get()); + if (colMap.count(fColumnName) == 1 || + scp->tableName().compare(fTableName) == 0) + { + fOid = scp->oid(); + //@bug 221 fix + fTableName = scp->tableName(); + fSchemaName = scp->schemaName(); + //@info assign tableAlias also. watch for other conflict + fTableAlias = scp->tableAlias(); + return; + } + } + } } void SimpleColumn::serialize(messageqcpp::ByteStream& b) const @@ -335,6 +294,7 @@ void SimpleColumn::serialize(messageqcpp::ByteStream& b) const b << fData; //b << fAlias; b << fTableAlias; + b << static_cast(fReturnAll); b << (uint32_t) fSequence; b << static_cast(fIsInfiniDB); } @@ -352,6 +312,7 @@ void SimpleColumn::unserialize(messageqcpp::ByteStream& b) b >> fData; //b >> fAlias; b >> fTableAlias; + b >> reinterpret_cast< ByteStream::doublebyte&>(fReturnAll); b >> (uint32_t&) fSequence; b >> reinterpret_cast< ByteStream::doublebyte&>(fIsInfiniDB); } @@ -371,9 +332,9 @@ bool SimpleColumn::operator==(const SimpleColumn& t) const if (fColumnName != t.fColumnName) return false; if (fIndexName != t.fIndexName) - return false; + return false; if (fViewName != t.fViewName) - return false; + return false; if (fOid != t.fOid) return false; if (fData != t.fData) @@ -381,11 +342,11 @@ bool SimpleColumn::operator==(const SimpleColumn& t) const if (fAlias != t.fAlias) return false; if (fTableAlias != t.fTableAlias) - return false; + return false; if (fAsc != t.fAsc) return false; if (fReturnAll != t.fReturnAll) - return false; + return false; if (fIsInfiniDB != t.fIsInfiniDB) return false; return true; @@ -413,64 +374,36 @@ bool SimpleColumn::operator!=(const TreeNode* t) const bool SimpleColumn::sameColumn(const ReturnedColumn* rc) const { - /** NOTE: Operations can still be merged on different table alias */ - const SimpleColumn *sc = dynamic_cast(rc); - if (!sc) return false; - return (fSchemaName.compare(sc->schemaName()) == 0 && - fTableName.compare(sc->tableName()) == 0 && - fColumnName.compare(sc->columnName()) == 0 && - fTableAlias.compare(sc->tableAlias()) == 0 && - fViewName.compare(sc->viewName()) == 0 && - fIsInfiniDB == sc->isInfiniDB()); -} - -void SimpleColumn::setDerivedTable() -{ - if (hasAggregate()) - { - fDerivedTable = ""; - return; - } - - // fDerivedTable is set at the parsing phase - if (!fSchemaName.empty()) - fDerivedTable = ""; - // @todo make aggregate filter to having clause. not optimize it for now - if (fDerivedRefCol && - (dynamic_cast(fDerivedRefCol) || - dynamic_cast(fDerivedRefCol))) - fDerivedTable = ""; -} - -bool SimpleColumn::singleTable(CalpontSystemCatalog::TableAliasName& tan) -{ - tan.table = fTableName; - tan.schema = fSchemaName; - tan.view = fViewName; - tan.alias = fTableAlias; - return true; + /** NOTE: Operations can still be merged on different table alias */ + const SimpleColumn *sc = dynamic_cast(rc); + if (!sc) return false; + return (fSchemaName.compare(sc->schemaName()) == 0 && + fTableName.compare(sc->tableName()) == 0 && + fColumnName.compare(sc->columnName()) == 0 && + fTableAlias.compare(sc->tableAlias()) == 0 && + fViewName.compare(sc->viewName()) == 0 && + fIsInfiniDB == sc->isInfiniDB()); } - // @todo move to inline void SimpleColumn::evaluate(Row& row, bool& isNull) { - bool isNull2 = row.isNullValue(fInputIndex); - if (isNull2) { - isNull = true; - return; - } - switch (fResultType.colDataType) { case CalpontSystemCatalog::DATE: { - fResult.intVal = row.getUintField<4>(fInputIndex); + if (row.equals<4>(DATENULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getUintField<4>(fInputIndex); break; } case CalpontSystemCatalog::DATETIME: { - fResult.intVal = row.getUintField<8>(fInputIndex); + if (row.equals<8>(DATETIMENULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getUintField<8>(fInputIndex); break; } case CalpontSystemCatalog::CHAR: @@ -480,34 +413,42 @@ void SimpleColumn::evaluate(Row& row, bool& isNull) switch (row.getColumnWidth(fInputIndex)) { case 1: - { - fResult.origIntVal = row.getUintField<1>(fInputIndex); + if (row.equals<1>(CHAR1NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<1>(fInputIndex); break; - } case 2: - { - fResult.origIntVal = row.getUintField<2>(fInputIndex); + if (row.equals<2>(CHAR2NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<2>(fInputIndex); break; - } case 3: case 4: - { - fResult.origIntVal = row.getUintField<4>(fInputIndex); + if (row.equals<4>(CHAR4NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<4>(fInputIndex); break; - } case 5: case 6: case 7: case 8: - { - fResult.origIntVal = row.getUintField<8>(fInputIndex); + if (row.equals<8>(CHAR8NULL, fInputIndex)) + isNull = true; + else + fResult.origIntVal = row.getUintField<8>(fInputIndex); break; - } default: - { - fResult.strVal = row.getStringField(fInputIndex); + if (row.equals(CPNULLSTRMARK, fInputIndex)) + isNull = true; + else + fResult.strVal = row.getStringField(fInputIndex); + // stringColVal is padded with '\0' to colWidth so can't use str.length() + if (strlen(fResult.strVal.c_str()) == 0) + isNull = true; break; - } } if (fResultType.colDataType == CalpontSystemCatalog::STRINT) fResult.intVal = uint64ToStr(fResult.origIntVal); @@ -517,100 +458,118 @@ void SimpleColumn::evaluate(Row& row, bool& isNull) } case CalpontSystemCatalog::BIGINT: { - fResult.intVal = row.getIntField<8>(fInputIndex); + if (row.equals<8>(BIGINTNULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getIntField<8>(fInputIndex); break; } case CalpontSystemCatalog::INT: case CalpontSystemCatalog::MEDINT: { - fResult.intVal = row.getIntField<4>(fInputIndex); + if (row.equals<4>(INTNULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getIntField<4>(fInputIndex); break; } case CalpontSystemCatalog::SMALLINT: { - fResult.intVal = row.getIntField<2>(fInputIndex); + if (row.equals<2>(SMALLINTNULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getIntField<2>(fInputIndex); break; } case CalpontSystemCatalog::TINYINT: { - fResult.intVal = row.getIntField<1>(fInputIndex); + if (row.equals<1>(TINYINTNULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getIntField<1>(fInputIndex); break; } //In this case, we're trying to load a double output column with float data. This is the // case when you do sum(floatcol), e.g. case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { - fResult.floatVal = row.getFloatField(fInputIndex); + if (row.equals<4>(FLOATNULL, fInputIndex)) + isNull = true; + else + fResult.floatVal = row.getFloatField(fInputIndex); break; } case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { - fResult.doubleVal = row.getDoubleField(fInputIndex); + if (row.equals<8>(DOUBLENULL, fInputIndex)) + isNull = true; + else + fResult.doubleVal = row.getDoubleField(fInputIndex); break; } case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { - switch (fResultType.colWidth) - { - case 1: + switch (fResultType.colWidth) { - fResult.decimalVal.value = row.getIntField<1>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - break; + case 1: + { + if (row.equals<1>(TINYINTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = row.getIntField<1>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + case 2: + { + if (row.equals<2>(SMALLINTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = row.getIntField<2>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + case 4: + { + if (row.equals<4>(INTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = row.getIntField<4>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } + default: + { + if (row.equals<8>(BIGINTNULL, fInputIndex)) + isNull = true; + else + { + fResult.decimalVal.value = (int64_t)row.getUintField<8>(fInputIndex); + fResult.decimalVal.scale = (unsigned)fResultType.scale; + } + break; + } } - case 2: - { - fResult.decimalVal.value = row.getIntField<2>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - break; - } - case 4: - { - fResult.decimalVal.value = row.getIntField<4>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - break; - } - default: - { - fResult.decimalVal.value = (int64_t)row.getUintField<8>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - break; - } - } break; } case CalpontSystemCatalog::VARBINARY: - { - fResult.strVal = row.getVarBinaryStringField(fInputIndex); - break; - } - case CalpontSystemCatalog::UBIGINT: - { - fResult.uintVal = row.getUintField<8>(fInputIndex); - break; - } - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UMEDINT: - { - fResult.uintVal = row.getUintField<4>(fInputIndex); - break; - } - case CalpontSystemCatalog::USMALLINT: - { - fResult.uintVal = row.getUintField<2>(fInputIndex); - break; - } - case CalpontSystemCatalog::UTINYINT: - { - fResult.uintVal = row.getUintField<1>(fInputIndex); + if (row.isNullValue(fInputIndex)) + isNull = true; + else + fResult.strVal = row.getVarBinaryStringField(fInputIndex); break; - } default: // treat as int64 { - fResult.intVal = row.getUintField<8>(fInputIndex); + if (row.equals<8>(BIGINTNULL, fInputIndex)) + isNull = true; + else + fResult.intVal = row.getUintField<8>(fInputIndex); break; } } diff --git a/dbcon/execplan/simplecolumn.h b/dbcon/execplan/simplecolumn.h index 3ce378bc..add82d0e 100644 --- a/dbcon/execplan/simplecolumn.h +++ b/dbcon/execplan/simplecolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: simplecolumn.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: simplecolumn.h 8536 2012-05-21 21:27:17Z zzhu $ * * ***********************************************************************/ @@ -31,7 +31,6 @@ #include "treenode.h" #include "calpontsystemcatalog.h" #include "dataconvert.h" -#include "calpontselectexecutionplan.h" namespace messageqcpp { class ByteStream; @@ -40,87 +39,82 @@ class ByteStream; /** * Namespace */ -namespace execplan { +namespace execplan { class ParseTree; /** * @brief A class to represent a simple returned column - * + * * This class is a specialization of class ReturnedColumn that handles * a column name. */ class SimpleColumn : public ReturnedColumn { public: - + /** * Constructors - */ + */ SimpleColumn(); - SimpleColumn(const std::string& token, - const uint32_t sessionID = 0); - SimpleColumn(const std::string& schema, - const std::string& table, - const std::string& col, - const uint32_t sessionID = 0); - SimpleColumn(const std::string& schema, - const std::string& table, - const std::string& col, - const bool isInfiniDB, - const uint32_t sessionID = 0); - SimpleColumn(const SimpleColumn& rhs, const uint32_t sessionID = 0); - + SimpleColumn(const std::string& token, const u_int32_t sessionID = 0); + SimpleColumn(const std::string& schema, const std::string& table, const std::string& col, const u_int32_t sessionID = 0); + SimpleColumn(const std::string& schema, const std::string& table, + const std::string& col, + const bool isInfiniDB, + const u_int32_t sessionID = 0); + SimpleColumn(const SimpleColumn& rhs, const u_int32_t sessionID = 0); + /** * Destructor */ virtual ~SimpleColumn(); - + /** * Accessor Methods */ inline const std::string& schemaName() const { - return fSchemaName; + return fSchemaName; } - + inline void schemaName(const std::string& schemaName) { - fSchemaName = schemaName; + fSchemaName = schemaName; } - + inline const std::string& tableName() const { return fTableName; } - + inline void tableName(const std::string& tableName) { - fTableName = tableName; + fTableName = tableName; } - + inline const std::string& columnName() const { return fColumnName; } - + inline void columnName(const std::string& columnName) { - fColumnName = columnName; + fColumnName = columnName; } - + inline const CalpontSystemCatalog::OID& oid() const { - return fOid; + return fOid; } - + inline void oid (const CalpontSystemCatalog::OID& oid) { - fOid = oid; + fOid = oid; } - + virtual const std::string data() const; virtual void data(const std::string data) { fData = data; } - + inline const std::string& tableAlias() const { return fTableAlias; } inline void tableAlias(const std::string& tableAlias) { fTableAlias = tableAlias; } inline const std::string& indexName() const {return fIndexName;} @@ -129,20 +123,20 @@ class SimpleColumn : public ReturnedColumn { inline void viewName(const std::string& viewName) {fViewName = viewName;} inline const bool isInfiniDB() const { return fIsInfiniDB; } inline void isInfiniDB(const bool isInfiniDB) { fIsInfiniDB = isInfiniDB; } - + /** return a copy of this pointer * * deep copy of this pointer and return the copy - */ + */ inline virtual SimpleColumn* clone() const { - return new SimpleColumn (*this); - } + return new SimpleColumn (*this); + } /** * Overloaded assignment operator */ SimpleColumn& operator=(const SimpleColumn& rhs); - + /** * The serialize interface */ @@ -150,151 +144,119 @@ class SimpleColumn : public ReturnedColumn { virtual void unserialize(messageqcpp::ByteStream&); virtual const std::string toString() const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ bool operator==(const SimpleColumn& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ bool operator!=(const SimpleColumn& t) const; - + /** @brief check if this column is the same as the argument */ virtual bool sameColumn(const ReturnedColumn* rc) const; - + /** @brief return column type of this column (could be of any engine type) */ const CalpontSystemCatalog::ColType& colType() const { return fResultType; } - /** @brief set the column's OID from the syscat */ - void setOID(); - - virtual bool hasWindowFunc() {return false;} - - void setDerivedTable(); - -/** - * Return the tableAlias name of the table that the column arguments belong to. - * - * @param TableAliasName that will be set in the function - * @return true, if all arguments belong to one table - * false, if multiple tables are involved in the function - */ - virtual bool singleTable(CalpontSystemCatalog::TableAliasName& tan); - -protected: +private: /** * Fields */ std::string fSchemaName; /// schema name - std::string fTableName; /// table name - std::string fColumnName; /// column name + std::string fTableName; /// table name + std::string fColumnName; /// column name CalpontSystemCatalog::OID fOid; /// column TCN number std::string fTableAlias; /// table alias std::string fData; /// index name. for oracle use. deprecated - std::string fIndexName; + std::string fIndexName; // if belong to view, view name is non-empty std::string fViewName; bool fIsInfiniDB; /** @brief parse SimpleColumn text - * + * * parse the incomming sql text to construct a SimpleColumn object. * used by the constructor. */ void parse(const std::string& sql); + + /** @brief get tcn for this column */ + void setOID(); /*********************************************************** * F&E framework * ***********************************************************/ public: - virtual void evaluate(rowgroup::Row& row, bool& isNull); + virtual void evaluate(rowgroup::Row& row, bool& isNull); virtual bool getBoolVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getBoolVal(); } - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) - { + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull) + { evaluate(row, isNull); - return TreeNode::getStrVal(); + return TreeNode::getStrVal(); } - - virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getIntVal(); - } - - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { + + virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) + { evaluate(row, isNull); - return TreeNode::getUintVal(); + return TreeNode::getIntVal(); } - + virtual float getFloatVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getFloatVal(); } - - virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) + + virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); - return TreeNode::getDoubleVal(); + return TreeNode::getDoubleVal(); } - + virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); - - // @bug5736, double type with precision -1 indicates that this type is for decimal math, - // the original decimal scale is stored in scale field, which is no use for double. - if (fResultType.colDataType == CalpontSystemCatalog::DOUBLE && fResultType.precision == -1) - { - IDB_Decimal rv; - rv.scale = fResultType.scale; - rv.precision = 15; - rv.value = (int64_t)(TreeNode::getDoubleVal() * IDB_pow[rv.scale]); - - return rv; - } - return TreeNode::getDecimalVal(); } - + inline int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) { evaluate(row, isNull); return TreeNode::getDateIntVal(); } - - inline int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getDatetimeIntVal(); - } - + + inline int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) + { + evaluate(row, isNull); + return TreeNode::getDatetimeIntVal(); + } + }; typedef boost::shared_ptr SSC; @@ -308,7 +270,6 @@ std::ostream& operator<<(std::ostream& output, const SimpleColumn& rhs); * utility function to extract all simple columns from a parse tree */ void getSimpleCols(ParseTree* n, void* obj); -ParseTree* replaceRefCol(ParseTree*& n, CalpontSelectExecutionPlan::ReturnedColumnList&); } #endif //SIMPLECOLUMN_H diff --git a/dbcon/execplan/simplecolumn_decimal.h b/dbcon/execplan/simplecolumn_decimal.h index 23c8ab56..a5ecb0b5 100644 --- a/dbcon/execplan/simplecolumn_decimal.h +++ b/dbcon/execplan/simplecolumn_decimal.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: simplecolumn_decimal.h 9635 2013-06-19 21:42:30Z bwilkinson $ +* $Id: simplecolumn_decimal.h 8536 2012-05-21 21:27:17Z zzhu $ * * ***********************************************************************/ @@ -53,13 +53,13 @@ class SimpleColumn_Decimal : public SimpleColumn { /** Constructors */ SimpleColumn_Decimal(); - SimpleColumn_Decimal(const std::string& token, const uint32_t sessionID = 0); + SimpleColumn_Decimal(const std::string& token, const u_int32_t sessionID = 0); SimpleColumn_Decimal(const std::string& schema, const std::string& table, const std::string& col, const bool isInfiniDB, - const uint32_t sessionID = 0); - SimpleColumn_Decimal(const SimpleColumn& rhs, const uint32_t sessionID = 0); + const u_int32_t sessionID = 0); + SimpleColumn_Decimal(const SimpleColumn& rhs, const u_int32_t sessionID = 0); /** Destructor */ virtual ~SimpleColumn_Decimal(){} @@ -70,7 +70,7 @@ class SimpleColumn_Decimal : public SimpleColumn { } /** Evaluate methods */ - virtual inline const std::string& getStrVal(rowgroup::Row& row, bool& isNull); + virtual inline std::string getStrVal(rowgroup::Row& row, bool& isNull); virtual inline int64_t getIntVal(rowgroup::Row& row, bool& isNull); virtual inline float getFloatVal(rowgroup::Row& row, bool& isNull); virtual inline double getDoubleVal(rowgroup::Row& row, bool& isNull); @@ -93,7 +93,7 @@ SimpleColumn_Decimal::SimpleColumn_Decimal():SimpleColumn() } template -SimpleColumn_Decimal::SimpleColumn_Decimal(const std::string& token, const uint32_t sessionID): +SimpleColumn_Decimal::SimpleColumn_Decimal(const std::string& token, const u_int32_t sessionID): SimpleColumn(token, sessionID) { setNullVal(); @@ -104,14 +104,14 @@ SimpleColumn_Decimal::SimpleColumn_Decimal(const std::string& schema, const std::string& table, const std::string& col, const bool isInfiniDB, - const uint32_t sessionID) : + const u_int32_t sessionID) : SimpleColumn(schema, table, col, isInfiniDB, sessionID) { setNullVal(); } template -SimpleColumn_Decimal::SimpleColumn_Decimal(const SimpleColumn& rhs, const uint32_t sessionID): +SimpleColumn_Decimal::SimpleColumn_Decimal(const SimpleColumn& rhs, const u_int32_t sessionID): SimpleColumn(rhs,sessionID) { setNullVal(); @@ -140,11 +140,10 @@ void SimpleColumn_Decimal::setNullVal() } template -inline const std::string& SimpleColumn_Decimal:: getStrVal(rowgroup::Row& row, bool& isNull) +inline std::string SimpleColumn_Decimal:: getStrVal(rowgroup::Row& row, bool& isNull) { - dataconvert::DataConvert::decimalToString((int64_t)row.getIntField(fInputIndex), fResultType.scale, tmp, 22, fResultType.colDataType); - fResult.strVal = std::string(tmp); - return fResult.strVal; + dataconvert::DataConvert::decimalToString((int64_t)row.getIntField(fInputIndex), fResultType.scale, tmp, 22); + return std::string(tmp); } template diff --git a/dbcon/execplan/simplecolumn_int.h b/dbcon/execplan/simplecolumn_int.h index ffb91832..2b7c0181 100644 --- a/dbcon/execplan/simplecolumn_int.h +++ b/dbcon/execplan/simplecolumn_int.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: simplecolumn_int.h 9635 2013-06-19 21:42:30Z bwilkinson $ +* $Id: simplecolumn_int.h 8536 2012-05-21 21:27:17Z zzhu $ * * ***********************************************************************/ @@ -51,13 +51,13 @@ class SimpleColumn_INT : public SimpleColumn { /** Constructors */ SimpleColumn_INT(); - SimpleColumn_INT(const std::string& token, const uint32_t sessionID = 0); + SimpleColumn_INT(const std::string& token, const u_int32_t sessionID = 0); SimpleColumn_INT(const std::string& schema, const std::string& table, const std::string& col, const bool isInfiniDB, - const uint32_t sessionID = 0); - SimpleColumn_INT(const SimpleColumn& rhs, const uint32_t sessionID = 0); + const u_int32_t sessionID = 0); + SimpleColumn_INT(const SimpleColumn& rhs, const u_int32_t sessionID = 0); /** Destructor */ virtual ~SimpleColumn_INT(){} @@ -68,9 +68,8 @@ class SimpleColumn_INT : public SimpleColumn { } /** Evaluate methods */ - virtual inline const std::string& getStrVal(rowgroup::Row& row, bool& isNull); + virtual inline std::string getStrVal(rowgroup::Row& row, bool& isNull); virtual inline int64_t getIntVal(rowgroup::Row& row, bool& isNull); - virtual inline uint64_t getUintVal(rowgroup::Row& row, bool& isNull); virtual inline float getFloatVal(rowgroup::Row& row, bool& isNull); virtual inline double getDoubleVal(rowgroup::Row& row, bool& isNull); virtual inline IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull); @@ -92,7 +91,7 @@ SimpleColumn_INT::SimpleColumn_INT():SimpleColumn() } template -SimpleColumn_INT::SimpleColumn_INT(const std::string& token, const uint32_t sessionID): +SimpleColumn_INT::SimpleColumn_INT(const std::string& token, const u_int32_t sessionID): SimpleColumn(token, sessionID) { setNullVal(); @@ -103,14 +102,14 @@ SimpleColumn_INT::SimpleColumn_INT(const std::string& schema, const std::string& table, const std::string& col, const bool isInfiniDB, - const uint32_t sessionID) : + const u_int32_t sessionID) : SimpleColumn(schema, table, col, isInfiniDB, sessionID) { setNullVal(); } template -SimpleColumn_INT::SimpleColumn_INT(const SimpleColumn& rhs, const uint32_t sessionID): +SimpleColumn_INT::SimpleColumn_INT(const SimpleColumn& rhs, const u_int32_t sessionID): SimpleColumn(rhs,sessionID) { setNullVal(); @@ -139,7 +138,7 @@ void SimpleColumn_INT::setNullVal() } template -inline const std::string& SimpleColumn_INT:: getStrVal(rowgroup::Row& row, bool& isNull) +inline std::string SimpleColumn_INT:: getStrVal(rowgroup::Row& row, bool& isNull) { if (row.equals(fNullVal, fInputIndex)) isNull = true; @@ -151,8 +150,7 @@ inline const std::string& SimpleColumn_INT:: getStrVal(rowgroup::Row& row, snprintf(tmp, 20, "%ld", (int64_t)row.getIntField(fInputIndex)); #endif } - fResult.strVal = std::string(tmp); - return fResult.strVal; + return std::string(tmp); } template @@ -163,14 +161,6 @@ inline int64_t SimpleColumn_INT:: getIntVal(rowgroup::Row& row, bool& isNul return (int64_t)row.getIntField(fInputIndex); } -template -inline uint64_t SimpleColumn_INT:: getUintVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - return (uint64_t)row.getIntField(fInputIndex); -} - template inline float SimpleColumn_INT::getFloatVal(rowgroup::Row& row, bool& isNull) { diff --git a/dbcon/execplan/simplecolumn_uint.h b/dbcon/execplan/simplecolumn_uint.h deleted file mode 100644 index 138d605e..00000000 --- a/dbcon/execplan/simplecolumn_uint.h +++ /dev/null @@ -1,245 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: simplecolumn_uint.h 8536 2012-05-21 21:27:17Z dhall $ -* -* -***********************************************************************/ -/** @file */ - -#ifndef SIMPLECOLUMNUINT_H -#define SIMPLECOLUMNUINT_H -#include - -#include "simplecolumn.h" -#include "objectreader.h" -#include "joblisttypes.h" -#include "rowgroup.h" - -/** - * Namespace - */ -namespace execplan { -/** - * @brief A class to represent a simple returned column - * - * This class is a specialization of class ReturnedColumn that handles - * a column name. - */ -template -class SimpleColumn_UINT : public SimpleColumn { - -/** - * Public stuff - */ -public: - - /** Constructors */ - SimpleColumn_UINT(); - SimpleColumn_UINT(const std::string& token, const uint32_t sessionID = 0); - SimpleColumn_UINT(const std::string& schema, - const std::string& table, - const std::string& col, - const bool isInfiniDB, - const uint32_t sessionID = 0); - SimpleColumn_UINT(const SimpleColumn& rhs, const uint32_t sessionID = 0); - - /** Destructor */ - virtual ~SimpleColumn_UINT(){} - - inline virtual SimpleColumn_UINT* clone() const - { - return new SimpleColumn_UINT (*this); - } - - /** Evaluate methods */ - virtual inline const std::string& getStrVal(rowgroup::Row& row, bool& isNull); - virtual inline int64_t getIntVal(rowgroup::Row& row, bool& isNull); - virtual inline uint64_t getUintVal(rowgroup::Row& row, bool& isNull); - virtual inline float getFloatVal(rowgroup::Row& row, bool& isNull); - virtual inline double getDoubleVal(rowgroup::Row& row, bool& isNull); - virtual inline IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull); - - /** The serialize interface */ - virtual void serialize(messageqcpp::ByteStream&) const; - virtual void unserialize(messageqcpp::ByteStream&); - uint64_t fNullVal; - -private: - void setNullVal(); - -}; - -template -SimpleColumn_UINT::SimpleColumn_UINT():SimpleColumn() -{ - setNullVal(); -} - -template -SimpleColumn_UINT::SimpleColumn_UINT(const std::string& token, const uint32_t sessionID): - SimpleColumn(token, sessionID) -{ - setNullVal(); -} - -template -SimpleColumn_UINT::SimpleColumn_UINT(const std::string& schema, - const std::string& table, - const std::string& col, - const bool isInfiniDB, - const uint32_t sessionID) : - SimpleColumn(schema, table, col, isInfiniDB, sessionID) -{ - setNullVal(); -} - -template -SimpleColumn_UINT::SimpleColumn_UINT(const SimpleColumn& rhs, const uint32_t sessionID): - SimpleColumn(rhs,sessionID) -{ - setNullVal(); -} - -template -void SimpleColumn_UINT::setNullVal() -{ - switch (len) - { - case 8: - fNullVal = joblist::UBIGINTNULL; - break; - case 4: - fNullVal = joblist::UINTNULL; - break; - case 2: - fNullVal = joblist::USMALLINTNULL; - break; - case 1: - fNullVal = joblist::UTINYINTNULL; - break; - default: - fNullVal = joblist::UBIGINTNULL; - } -} - -template -inline const std::string& SimpleColumn_UINT:: getStrVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - else - { -#ifndef __LP64__ - snprintf(tmp, 21, "%llu", row.getUintField(fInputIndex)); -#else - snprintf(tmp, 21, "%lu", row.getUintField(fInputIndex)); -#endif - } - fResult.strVal = std::string(tmp); - return fResult.strVal; -} - -template -inline int64_t SimpleColumn_UINT:: getIntVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - return (int64_t)row.getUintField(fInputIndex); -} - -template -inline uint64_t SimpleColumn_UINT:: getUintVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - return (uint64_t)row.getUintField(fInputIndex); -} - -template -inline float SimpleColumn_UINT::getFloatVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - return (float)row.getUintField(fInputIndex); -} - -template -inline double SimpleColumn_UINT::getDoubleVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - return (double)row.getUintField(fInputIndex); -} - -template -inline IDB_Decimal SimpleColumn_UINT::getDecimalVal(rowgroup::Row& row, bool& isNull) -{ - if (row.equals(fNullVal, fInputIndex)) - isNull = true; - fResult.decimalVal.value = (uint64_t)row.getUintField(fInputIndex); - fResult.decimalVal.precision = 65; - fResult.decimalVal.scale = 0; - return fResult.decimalVal; -} - -template -void SimpleColumn_UINT::serialize(messageqcpp::ByteStream& b) const -{ - switch (len) - { - case 1: - b << (ObjectReader::id_t) ObjectReader::SIMPLECOLUMN_UINT1; - break; - case 2: - b << (ObjectReader::id_t) ObjectReader::SIMPLECOLUMN_UINT2; - break; - case 4: - b << (ObjectReader::id_t) ObjectReader::SIMPLECOLUMN_UINT4; - break; - case 8: - b << (ObjectReader::id_t) ObjectReader::SIMPLECOLUMN_UINT8; - break; - } - SimpleColumn::serialize(b); -} - -template -void SimpleColumn_UINT::unserialize(messageqcpp::ByteStream& b) -{ - switch (len) - { - case 1: - ObjectReader::checkType(b, ObjectReader::SIMPLECOLUMN_UINT1); - break; - case 2: - ObjectReader::checkType(b, ObjectReader::SIMPLECOLUMN_UINT2); - break; - case 4: - ObjectReader::checkType(b, ObjectReader::SIMPLECOLUMN_UINT4); - break; - case 8: - ObjectReader::checkType(b, ObjectReader::SIMPLECOLUMN_UINT8); - break; - } - SimpleColumn::unserialize(b); -} - -} -#endif //SIMPLECOLUMN_INT_H - diff --git a/dbcon/execplan/simplefilter.cpp b/dbcon/execplan/simplefilter.cpp index 692da751..29540532 100644 --- a/dbcon/execplan/simplefilter.cpp +++ b/dbcon/execplan/simplefilter.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: simplefilter.cpp 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: simplefilter.cpp 9261 2013-02-06 20:59:01Z xlou $ * * ***********************************************************************/ @@ -38,7 +38,6 @@ using namespace std; #include "arithmeticcolumn.h" #include "simplefilter.h" #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" namespace execplan { @@ -56,7 +55,7 @@ SimpleFilter::SimpleFilter(): SimpleFilter::SimpleFilter(const string& sql): Filter(sql) { - parse(sql); + parse(sql); } SimpleFilter::SimpleFilter(const SOP& op, ReturnedColumn* lhs, ReturnedColumn* rhs) : @@ -72,76 +71,54 @@ SimpleFilter::SimpleFilter(const SimpleFilter& rhs) : { fLhs = rhs.lhs()->clone(); fRhs = rhs.rhs()->clone(); - + + // populate simple column list fSimpleColumnList.clear(); - fAggColumnList.clear(); - fWindowFunctionColumnList.clear(); - SimpleColumn *lsc = dynamic_cast(fLhs); FunctionColumn *lfc = dynamic_cast(fLhs); ArithmeticColumn *lac = dynamic_cast(fLhs); - WindowFunctionColumn *laf = dynamic_cast(fLhs); - AggregateColumn *lagc = dynamic_cast(fLhs); + AggregateColumn *lag = dynamic_cast(fLhs); SimpleColumn *rsc = dynamic_cast(fRhs); FunctionColumn *rfc = dynamic_cast(fRhs); ArithmeticColumn *rac = dynamic_cast(fRhs); - AggregateColumn *ragc = dynamic_cast(fRhs); - WindowFunctionColumn *raf = dynamic_cast(fRhs); - + AggregateColumn *rag = dynamic_cast(fRhs); + if (lsc) { fSimpleColumnList.push_back(lsc); } - else if (lagc) - { - fAggColumnList.push_back(lagc); - } else if (lfc) - { + { fSimpleColumnList.insert(fSimpleColumnList.end(), lfc->simpleColumnList().begin(), lfc->simpleColumnList().end()); fAggColumnList.insert(fAggColumnList.end(), lfc->aggColumnList().begin(), lfc->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), lfc->windowfunctionColumnList().begin(), lfc->windowfunctionColumnList().end()); } else if (lac) { fSimpleColumnList.insert(fSimpleColumnList.end(), lac->simpleColumnList().begin(), lac->simpleColumnList().end()); - fAggColumnList.insert(fAggColumnList.end(), lac->aggColumnList().begin(), lac->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), lac->windowfunctionColumnList().begin(), lac->windowfunctionColumnList().end()); + fAggColumnList.insert(fAggColumnList.end(), lac->aggColumnList().begin(), lac->aggColumnList().end()); } - else if (laf) + else if (lag) { - fWindowFunctionColumnList.push_back(laf); + fAggColumnList.push_back(lag); } - + if (rsc) { fSimpleColumnList.push_back(rsc); } - else if (ragc) - { - fAggColumnList.push_back(ragc); - } else if (rfc) { - fSimpleColumnList.insert - (fSimpleColumnList.end(), rfc->simpleColumnList().begin(), rfc->simpleColumnList().end()); - fAggColumnList.insert - (fAggColumnList.end(), rfc->aggColumnList().begin(), rfc->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), rfc->windowfunctionColumnList().begin(), rfc->windowfunctionColumnList().end()); + fSimpleColumnList.insert(fSimpleColumnList.end(), rfc->simpleColumnList().begin(), rfc->simpleColumnList().end()); + fAggColumnList.insert(fAggColumnList.end(), rfc->aggColumnList().begin(), rfc->aggColumnList().end()); } else if (rac) { fSimpleColumnList.insert(fSimpleColumnList.end(), rac->simpleColumnList().begin(), rac->simpleColumnList().end()); fAggColumnList.insert(fAggColumnList.end(), rac->aggColumnList().begin(), rac->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), rac->windowfunctionColumnList().begin(), rac->windowfunctionColumnList().end()); } - else if (raf) + else if (rag) { - fWindowFunctionColumnList.push_back(raf); + fAggColumnList.push_back(rag); } } @@ -155,7 +132,7 @@ SimpleFilter::~SimpleFilter() /** * Methods */ - + void SimpleFilter::lhs(ReturnedColumn* lhs) { fLhs = lhs; @@ -208,34 +185,34 @@ const string SimpleFilter::toString() const void SimpleFilter::parse(string sql) { - fLhs = 0; - fRhs = 0; - string delimiter[7] = {">=", "<=", "<>", "!=", "=", "<", ">"}; - string::size_type pos; - for (int i = 0; i < 7; i++) - { - pos = sql.find(delimiter[i], 0); - if (pos == string::npos) - continue; - fOp.reset(new Operator (delimiter[i])); - string lhs = sql.substr(0, pos); - if (lhs.at(0) == ' ') - lhs = lhs.substr(1, pos); - if (lhs.at(lhs.length()-1) == ' ') - lhs = lhs.substr(0, pos-1); - fLhs = new SimpleColumn(lhs); - - pos = pos + delimiter[i].length(); - string rhs = sql.substr(pos,sql.length()); - if (rhs.at(0) == ' ') - rhs = rhs.substr(1, pos); - if (rhs.at(rhs.length()-1) == ' ') - rhs = rhs.substr(0, pos-1); - fRhs = new SimpleColumn (rhs); - break; - } - if (fLhs == NULL || fRhs == NULL) - throw runtime_error ("invalid sql for simple filter\n" ); + fLhs = 0; + fRhs = 0; + string delimiter[7] = {">=", "<=", "<>", "!=", "=", "<", ">"}; + string::size_type pos; + for (int i = 0; i < 7; i++) + { + pos = sql.find(delimiter[i], 0); + if (pos == string::npos) + continue; + fOp.reset(new Operator (delimiter[i])); + string lhs = sql.substr(0, pos); + if (lhs.at(0) == ' ') + lhs = lhs.substr(1, pos); + if (lhs.at(lhs.length()-1) == ' ') + lhs = lhs.substr(0, pos-1); + fLhs = new SimpleColumn(lhs); + + pos = pos + delimiter[i].length(); + string rhs = sql.substr(pos,sql.length()); + if (rhs.at(0) == ' ') + rhs = rhs.substr(1, pos); + if (rhs.at(rhs.length()-1) == ' ') + rhs = rhs.substr(0, pos-1); + fRhs = new SimpleColumn (rhs); + break; + } + if (fLhs == NULL || fRhs == NULL) + throw runtime_error ("invalid sql for simple filter\n" ); } ostream& operator<<(ostream& output, const SimpleFilter& rhs) @@ -260,14 +237,14 @@ void SimpleFilter::serialize(messageqcpp::ByteStream& b) const fRhs->serialize(b); else b << static_cast(ObjectReader::NULL_CLASS); - b << static_cast(fIndexFlag); - b << static_cast(fJoinFlag); + b << static_cast(fIndexFlag); + b << static_cast(fJoinFlag); } - + void SimpleFilter::unserialize(messageqcpp::ByteStream& b) { ObjectReader::checkType(b, ObjectReader::SIMPLEFILTER); - + //delete fOp; delete fLhs; delete fRhs; @@ -275,23 +252,19 @@ void SimpleFilter::unserialize(messageqcpp::ByteStream& b) fOp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); fLhs = dynamic_cast(ObjectReader::createTreeNode(b)); fRhs = dynamic_cast(ObjectReader::createTreeNode(b)); - b >> reinterpret_cast(fIndexFlag); - b >> reinterpret_cast(fJoinFlag); - + b >> reinterpret_cast(fIndexFlag); + b >> reinterpret_cast(fJoinFlag); + fSimpleColumnList.clear(); fAggColumnList.clear(); - fWindowFunctionColumnList.clear(); - SimpleColumn *lsc = dynamic_cast(fLhs); FunctionColumn *lfc = dynamic_cast(fLhs); ArithmeticColumn *lac = dynamic_cast(fLhs); - WindowFunctionColumn *laf = dynamic_cast(fLhs); AggregateColumn *lagc = dynamic_cast(fLhs); SimpleColumn *rsc = dynamic_cast(fRhs); FunctionColumn *rfc = dynamic_cast(fRhs); ArithmeticColumn *rac = dynamic_cast(fRhs); AggregateColumn *ragc = dynamic_cast(fRhs); - WindowFunctionColumn *raf = dynamic_cast(fRhs); if (lsc) { @@ -303,25 +276,14 @@ void SimpleFilter::unserialize(messageqcpp::ByteStream& b) } else if (lfc) { - lfc->setSimpleColumnList(); fSimpleColumnList.insert(fSimpleColumnList.end(), lfc->simpleColumnList().begin(), lfc->simpleColumnList().end()); fAggColumnList.insert(fAggColumnList.end(), lfc->aggColumnList().begin(), lfc->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), lfc->windowfunctionColumnList().begin(), lfc->windowfunctionColumnList().end()); } else if (lac) { - lac->setSimpleColumnList(); fSimpleColumnList.insert(fSimpleColumnList.end(), lac->simpleColumnList().begin(), lac->simpleColumnList().end()); - fAggColumnList.insert(fAggColumnList.end(), lac->aggColumnList().begin(), lac->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), lac->windowfunctionColumnList().begin(), lac->windowfunctionColumnList().end()); - } - else if (laf) - { - fWindowFunctionColumnList.push_back(laf); - } - + fAggColumnList.insert(fAggColumnList.end(), lac->aggColumnList().begin(), lac->aggColumnList().end()); + } if (rsc) { fSimpleColumnList.push_back(rsc); @@ -332,27 +294,15 @@ void SimpleFilter::unserialize(messageqcpp::ByteStream& b) } else if (rfc) { - rfc->setSimpleColumnList(); - fSimpleColumnList.insert - (fSimpleColumnList.end(), rfc->simpleColumnList().begin(), rfc->simpleColumnList().end()); - fAggColumnList.insert - (fAggColumnList.end(), rfc->aggColumnList().begin(), rfc->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), rfc->windowfunctionColumnList().begin(), rfc->windowfunctionColumnList().end()); + fSimpleColumnList.insert(fSimpleColumnList.end(), rfc->simpleColumnList().begin(), rfc->simpleColumnList().end()); + fAggColumnList.insert(fAggColumnList.end(), rfc->aggColumnList().begin(), rfc->aggColumnList().end()); } else if (rac) { - rac->setSimpleColumnList(); fSimpleColumnList.insert(fSimpleColumnList.end(), rac->simpleColumnList().begin(), rac->simpleColumnList().end()); - fAggColumnList.insert(fAggColumnList.end(), rac->aggColumnList().begin(), rac->aggColumnList().end()); - fWindowFunctionColumnList.insert - (fWindowFunctionColumnList.end(), rac->windowfunctionColumnList().begin(), rac->windowfunctionColumnList().end()); - } - else if (raf) - { - fWindowFunctionColumnList.push_back(raf); + fAggColumnList.insert(fAggColumnList.end(), rac->aggColumnList().begin(), rac->aggColumnList().end()); } - + // construct regex constant for like operator if (fOp->op() == OP_LIKE || fOp->op() == OP_NOTLIKE) { @@ -373,34 +323,34 @@ bool SimpleFilter::operator==(const SimpleFilter& t) const f2 = static_cast(&t); if (*f1 != *f2) return false; - + if (fOp != NULL) { if (*fOp != *t.fOp) return false; } else if (t.fOp != NULL) return false; - + if (fLhs != NULL) { if (*fLhs != t.fLhs) return false; } else if (t.fLhs != NULL) return false; - + if (fRhs != NULL) { if (*fRhs != t.fRhs) return false; } else if (t.fRhs != NULL) return false; - + else if (fIndexFlag != t.fIndexFlag) - return false; - + return false; + else if (fJoinFlag != t.fJoinFlag) - return false; - + return false; + return true; } @@ -426,29 +376,66 @@ bool SimpleFilter::operator!=(const TreeNode* t) const bool SimpleFilter::pureFilter() { - if (typeid (*fLhs) == typeid(ConstantColumn) && - typeid (*fRhs) != typeid(ConstantColumn)) - { - // make sure constantCol sit on right hand side - ReturnedColumn* temp = fLhs; - fLhs = fRhs; - fRhs = temp; - // also switch indexFlag - if (fIndexFlag == SimpleFilter::LEFT) fIndexFlag = SimpleFilter::RIGHT; - else if (fIndexFlag == SimpleFilter::RIGHT) fIndexFlag = SimpleFilter::LEFT; - return true; - } - if (typeid (*fRhs) == typeid(ConstantColumn) && - typeid (*fLhs) != typeid(ConstantColumn)) - return true; - return false; + if (typeid (*fLhs) == typeid(ConstantColumn) && + typeid (*fRhs) != typeid(ConstantColumn)) + { + // make sure constantCol sit on right hand side + ReturnedColumn* temp = fLhs; + fLhs = fRhs; + fRhs = temp; + // also switch indexFlag + if (fIndexFlag == SimpleFilter::LEFT) fIndexFlag = SimpleFilter::RIGHT; + else if (fIndexFlag == SimpleFilter::RIGHT) fIndexFlag = SimpleFilter::LEFT; + return true; + } + if (typeid (*fRhs) == typeid(ConstantColumn) && + typeid (*fLhs) != typeid(ConstantColumn)) + return true; + return false; +} + +Filter* SimpleFilter::combinable(Filter* f, Operator *op) +{ + if (!pureFilter()) return NULL; + if (typeid(*f) == typeid(SimpleFilter)) + { + SimpleFilter *sf = dynamic_cast(f); + if (sf->pureFilter() && fLhs->sameColumn(sf->lhs())) + { + ConstantFilter *cf = new ConstantFilter(this); + cf->pushFilter(sf); + SOP sop(op); + cf->op(sop); + return cf; + } + } + if (typeid(*f) == typeid(ConstantFilter)) + { + ConstantFilter *cf = dynamic_cast(f); + if (fLhs->sameColumn(cf->col().get()) && ( !cf->op() || cf->op()->data().compare(op->data())==0)) + { + cf->pushFilter(this); + if (!cf->op()) + { + SOP sop(op); + cf->op(sop); + } + else + { + delete op; + } + return cf; + } + } + + return NULL; } void SimpleFilter::convertConstant() { if (fOp->op() == OP_ISNULL || fOp->op() == OP_ISNOTNULL) return; - + ConstantColumn *lcc = dynamic_cast(fLhs); ConstantColumn *rcc = dynamic_cast(fRhs); if (lcc) @@ -484,7 +471,7 @@ void SimpleFilter::convertConstant() } if (rcc) { - Result result = rcc->result(); + Result result = rcc->result(); if (fLhs->resultType().colDataType == CalpontSystemCatalog::DATE) { if (rcc->constval().empty()) @@ -515,145 +502,4 @@ void SimpleFilter::convertConstant() } } -void SimpleFilter::setDerivedTable() -{ - string lDerivedTable = ""; - string rDerivedTable = ""; - if (hasAggregate()) - return; - - if (fLhs) - { - fLhs->setDerivedTable(); - lDerivedTable = fLhs->derivedTable(); - } - else - { - lDerivedTable = "*"; - } - - if (fRhs) - { - fRhs->setDerivedTable(); - rDerivedTable = fRhs->derivedTable(); - } - else - { - rDerivedTable = "*"; - } - - if (lDerivedTable == "*") - { - fDerivedTable = rDerivedTable; - } - else if (rDerivedTable == "*") - { - fDerivedTable = lDerivedTable; - } - else if (lDerivedTable == rDerivedTable) - { - fDerivedTable = lDerivedTable; // should be the same as rhs - } - else - { - fDerivedTable = ""; - } -} - -void SimpleFilter::replaceRealCol(CalpontSelectExecutionPlan::ReturnedColumnList& derivedColList) -{ - SimpleColumn *sc = NULL; - if (fLhs) - { - sc = dynamic_cast(fLhs); - if (sc) - { - ReturnedColumn* tmp = derivedColList[sc->colPosition()]->clone(); - delete fLhs; - fLhs = tmp; - } - else - { - fLhs->replaceRealCol(derivedColList); - } - } - if (fRhs) - { - sc = dynamic_cast(fRhs); - if (sc) - { - ReturnedColumn* tmp = derivedColList[sc->colPosition()]->clone(); - delete fRhs; - fRhs = tmp; - } - else - { - fRhs->replaceRealCol(derivedColList); - } - } -} - -const std::vector& SimpleFilter::simpleColumnList() -{ - return fSimpleColumnList; -} - -void SimpleFilter::setSimpleColumnList() -{ - SimpleColumn *lsc = dynamic_cast(fLhs); - SimpleColumn *rsc = dynamic_cast(fRhs); - fSimpleColumnList.clear(); - - if (lsc) - { - fSimpleColumnList.push_back(lsc); - } - else if (fLhs) - { - fLhs->setSimpleColumnList(); - fSimpleColumnList.insert - (fSimpleColumnList.end(), fLhs->simpleColumnList().begin(), fLhs->simpleColumnList().end()); - } - - if (rsc) - { - fSimpleColumnList.push_back(rsc); - } - else if (fRhs) - { - fRhs->setSimpleColumnList(); - fSimpleColumnList.insert - (fSimpleColumnList.end(), fRhs->simpleColumnList().begin(), fRhs->simpleColumnList().end()); - } -} - -bool SimpleFilter::hasAggregate() -{ - AggregateColumn *lac = dynamic_cast(fLhs); - AggregateColumn *rac = dynamic_cast(fRhs); - fAggColumnList.clear(); - - if (lac) - { - return true; - } - else if (fLhs) - { - if (fLhs->hasAggregate()) - return true; - } - - if (rac) - { - return true; - } - else if (fRhs) - { - if (fRhs->hasAggregate()) - return true; - } - return false; -} - - } // namespace execplan diff --git a/dbcon/execplan/simplefilter.h b/dbcon/execplan/simplefilter.h index 944c5e25..b75aa771 100644 --- a/dbcon/execplan/simplefilter.h +++ b/dbcon/execplan/simplefilter.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: simplefilter.h 9679 2013-07-11 22:32:03Z zzhu $ +* $Id: simplefilter.h 8816 2012-08-15 18:51:49Z dhall $ * * ***********************************************************************/ @@ -35,64 +35,63 @@ /** * Namespace */ -namespace execplan { +namespace execplan { class AggregateColumn; - class WindowFunctionColumn; - + /** * @brief A class to represent a simple WHERE clause predicate * - * This class is a specialization of class Filter that handles simple + * This class is a specialization of class Filter that handles simple * binary operation WHERE clauses, e.g. last_name = ‘SMITH’. - */ + */ class SimpleFilter : public Filter { public: - /** index flag */ - enum IndexFlag - { - NOINDEX = 0, - LEFT, - RIGHT, - BOTH - }; - - enum JoinFlag - { - EQUA = 0, - ANTI, - SEMI - }; + /** index flag */ + enum IndexFlag + { + NOINDEX = 0, + LEFT, + RIGHT, + BOTH + }; + + enum JoinFlag + { + EQUA = 0, + ANTI, + SEMI + }; SimpleFilter(); SimpleFilter(const std::string& sql); SimpleFilter(const SOP& op, ReturnedColumn* lhs, ReturnedColumn* rhs); SimpleFilter(const SimpleFilter& rhs); - + virtual ~SimpleFilter(); - + inline virtual SimpleFilter* clone() const { - return new SimpleFilter (*this); + return new SimpleFilter (*this); } - + const SOP& op() const { return fOp; } - + void op(const SOP& op) { fOp = op; } - + inline ReturnedColumn* lhs() const { return fLhs; } - + virtual const std::string data() const; - + /** assign fLhs * * this call takes over the ownership of the input pointer. Caller needs @@ -100,12 +99,12 @@ class SimpleFilter : public Filter { * delete the pointer accidentally. */ void lhs(ReturnedColumn* lhs); - + inline ReturnedColumn* rhs() const { return fRhs; } - + /** assign fRhs * * this call takes over the ownership of the pointer rhs. Called need @@ -113,7 +112,7 @@ class SimpleFilter : public Filter { * delete the pointer accidentally. */ void rhs(ReturnedColumn* rhs); - + virtual const std::string toString() const; /** @@ -121,76 +120,71 @@ class SimpleFilter : public Filter { */ virtual void serialize(messageqcpp::ByteStream&) const; virtual void unserialize(messageqcpp::ByteStream&); - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ bool operator==(const SimpleFilter& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ bool operator!=(const SimpleFilter& t) const; - + /** @brief determin if this simple filter is a pure filter (col/const) */ bool pureFilter(); - + /** @brief test if this filter can be combined with the argument filter * This is for operation combine optimization * @param f the filter that this fiter tries to combine with * @param op the operator that connects the two filters. if one or both of the * two filters is constantFilter, need to make sure operator is consistant. * @return a filter(constantfilter) if successfully combined. otherwise - * return NULL - * For Oracle Frontend use. Deprecated now. + * return NULL */ - //virtual Filter* combinable(Filter* f, Operator* op); - - /** @brief assign indexflag to indicate which side col is index */ - void indexFlag (const int indexFlag) {fIndexFlag = indexFlag;} - const int indexFlag() const {return fIndexFlag;} - - /** @brief assign joinflag to indicate which join type */ - void joinFlag (const int joinFlag) {fJoinFlag = joinFlag;} - const int joinFlag() const {return fJoinFlag;} - - /** @brief this function is called by the connector to set constant values according to the compare type */ - void convertConstant(); - - void setDerivedTable(); - - virtual void replaceRealCol(std::vector&); - + virtual Filter* combinable(Filter* f, Operator* op); + + /** @brief assign indexflag to indicate which side col is index */ + void indexFlag (const int indexFlag) {fIndexFlag = indexFlag;} + const int indexFlag() const {return fIndexFlag;} + + /** @brief assign joinflag to indicate which join type */ + void joinFlag (const int joinFlag) {fJoinFlag = joinFlag;} + const int joinFlag() const {return fJoinFlag;} + + /** @brief this function is called by the connector to set constant values according to the compare type */ + void convertConstant(); + private: - SOP fOp; /// operator + SOP fOp; /// operator ReturnedColumn *fLhs; /// left operand ReturnedColumn *fRhs; /// right operand - int fIndexFlag; /// which side col is index - int fJoinFlag; /// hash join type + int fIndexFlag; /// which side col is index + int fJoinFlag; /// hash join type void parse (std::string); - + /*********************************************************** - * F&E framework * + * F&E framework * ***********************************************************/ public: inline virtual bool getBoolVal(rowgroup::Row& row, bool& isNull); @@ -198,22 +192,14 @@ class SimpleFilter : public Filter { inline virtual double getDoubleVal(rowgroup::Row& row, bool& isNull); // get all simple columns involved in this column - const std::vector& simpleColumnList(); - // walk through the simple filter operands to re-populate fSimpleColumnList - void setSimpleColumnList(); - // walk through the simple filter operands to check existence of aggregate - bool hasAggregate(); - + const std::vector& simpleColumnList() const { return fSimpleColumnList; } + // get all aggregate columns involved in this column const std::vector& aggColumnList() const { return fAggColumnList; } - - // get all window function columns involved in this column - const std::vector& windowfunctionColumnList() const { return fWindowFunctionColumnList; } - + private: std::vector fSimpleColumnList; std::vector fAggColumnList; - std::vector fWindowFunctionColumnList; }; inline bool SimpleFilter::getBoolVal(rowgroup::Row& row, bool& isNull) @@ -235,6 +221,6 @@ typedef boost::shared_ptr SSFP; std::ostream& operator<<(std::ostream& output, const SimpleFilter& rhs); -} +} #endif //SIMPLEFILTER_H diff --git a/dbcon/execplan/simplescalarfilter.cpp b/dbcon/execplan/simplescalarfilter.cpp index b8cef43c..47572902 100644 --- a/dbcon/execplan/simplescalarfilter.cpp +++ b/dbcon/execplan/simplescalarfilter.cpp @@ -59,7 +59,7 @@ const string SimpleScalarFilter::toString() const { ostringstream oss; oss << "SimpleScalarFilter" << endl; - for (uint32_t i = 0; i < fCols.size(); i++) + for (uint i = 0; i < fCols.size(); i++) oss << fCols[i]->toString(); oss << fOp->toString() << endl; oss << *(fSub.get()); @@ -76,8 +76,8 @@ void SimpleScalarFilter::serialize(messageqcpp::ByteStream& b) const { b << static_cast(ObjectReader::SIMPLESCALARFILTER); Filter::serialize(b); - b << static_cast(fCols.size()); - for (uint32_t i = 0; i < fCols.size(); i++) + b << static_cast(fCols.size()); + for (uint i = 0; i < fCols.size(); i++) { if (fCols[i] != NULL) fCols[i]->serialize(b); @@ -103,7 +103,7 @@ void SimpleScalarFilter::unserialize(messageqcpp::ByteStream& b) b >> size; fCols.clear(); SRCP srcp; - for (uint32_t i = 0; i < size; i++) + for (uint i = 0; i < size; i++) { srcp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); fCols.push_back(srcp); @@ -122,7 +122,7 @@ bool SimpleScalarFilter::operator==(const SimpleScalarFilter& t) const return false; if (fCols.size() != t.fCols.size()) return false; - for (uint32_t i = 0; i < fCols.size(); i++) + for (uint i = 0; i < fCols.size(); i++) { if (fCols[i].get() != NULL) { if (*(fCols[i].get()) != *(t.fCols[i]).get()) diff --git a/dbcon/execplan/simplescalarfilter.h b/dbcon/execplan/simplescalarfilter.h index c43d69fa..15fe4aaa 100644 --- a/dbcon/execplan/simplescalarfilter.h +++ b/dbcon/execplan/simplescalarfilter.h @@ -36,11 +36,11 @@ /** * Namespace */ -namespace execplan { +namespace execplan { /** * @brief A class to represent a non-correlated scalar sub select filter * - * the sub select can always be resolved first and this scalar filter can be + * the sub select can always be resolved first and this scalar filter can be * treated as a constant filter */ class SimpleScalarFilter : public Filter { @@ -48,7 +48,7 @@ class SimpleScalarFilter : public Filter { * Public stuff */ public: - + /** * Constructors */ @@ -56,17 +56,17 @@ class SimpleScalarFilter : public Filter { SimpleScalarFilter(const SimpleScalarFilter& rhs); /** Constructors - * + * * pass all parts in ctor * @note SimpleFilter takes ownership of all these pointers */ SimpleScalarFilter(const std::vector& cols, const SOP& op, SCSEP& sub); - + /** * Destructors */ virtual ~SimpleScalarFilter(); - + /** * Accessor Methods */ @@ -74,48 +74,48 @@ class SimpleScalarFilter : public Filter { { return fCols; } - + void cols(const std::vector& cols) { fCols = cols; } - + inline const SOP& op() const { return fOp; } - + inline void op (const SOP& op) { fOp = op; } - + inline const SCSEP& sub() const { return fSub; } - + inline void sub(SCSEP& sub) { fSub = sub; } virtual const std::string toString() const; - + virtual inline const std::string data() const {return fData;} virtual inline void data( const std::string data ) {fData = data;} - + /** * The serialization interface */ virtual void serialize(messageqcpp::ByteStream&) const; virtual void unserialize(messageqcpp::ByteStream&); - + /** return a copy of this pointer * * deep copy of this pointer and return the copy - */ + */ inline virtual SimpleScalarFilter* clone() const { return new SimpleScalarFilter (*this); - } + } /** @brief Do a deep, strict (as opposed to semantic) equivalence test * @@ -123,28 +123,28 @@ class SimpleScalarFilter : public Filter { * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ virtual bool operator==(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return true iff every member of t is a duplicate copy of every member of this; false otherwise */ bool operator==(const SimpleScalarFilter& t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ virtual bool operator!=(const TreeNode* t) const; - + /** @brief Do a deep, strict (as opposed to semantic) equivalence test * * Do a deep, strict (as opposed to semantic) equivalence test. * @return false iff every member of t is a duplicate copy of every member of this; true otherwise */ bool operator!=(const SimpleScalarFilter& t) const; - + private: //default okay? //SelectFilter& operator=(const SelectFilter& rhs); @@ -157,6 +157,6 @@ class SimpleScalarFilter : public Filter { std::ostream& operator<<(std::ostream& output, const SimpleScalarFilter& rhs); -} +} #endif //SELECTFILTER_H diff --git a/dbcon/execplan/tdriver-oid.cpp b/dbcon/execplan/tdriver-oid.cpp index 65c1c740..333d7d21 100644 --- a/dbcon/execplan/tdriver-oid.cpp +++ b/dbcon/execplan/tdriver-oid.cpp @@ -189,7 +189,7 @@ void* OIDManClient(void *arg) ObjectIDManager o; const int sizecap = 5; int op, size, tmp; - uint32_t seed; + u_int32_t seed; int threadnum = reinterpret_cast(arg); struct entry { diff --git a/dbcon/execplan/tdriver-sm.cpp b/dbcon/execplan/tdriver-sm.cpp index f7c5e54a..20f49e0a 100644 --- a/dbcon/execplan/tdriver-sm.cpp +++ b/dbcon/execplan/tdriver-sm.cpp @@ -52,13 +52,13 @@ static void* SMRunner(void* arg) { SessionManager *sm; int op; - uint32_t seed, sessionnum; + u_int32_t seed, sessionnum; SessionManager::TxnID tmp; int tNum = reinterpret_cast(arg); struct entry { SessionManager::TxnID tid; - uint32_t sessionnum; + u_int32_t sessionnum; struct entry *next; }; diff --git a/dbcon/execplan/tdriver.cpp b/dbcon/execplan/tdriver.cpp index 91a328ce..39a6a82d 100644 --- a/dbcon/execplan/tdriver.cpp +++ b/dbcon/execplan/tdriver.cpp @@ -1350,7 +1350,7 @@ int createTxns(const int& start, const int& end) { verifyLen=manager->verifySize(); for (int idx = first; idxnewTxnID((uint32_t)idx+1000); + managerTxns[idx] = manager->newTxnID((u_int32_t)idx+1000); CPPUNIT_ASSERT(managerTxns[idx].id>0); CPPUNIT_ASSERT(managerTxns[idx].valid==true); verifyLen=manager->verifySize(); @@ -1426,7 +1426,7 @@ void MonitorTestPlan_1() { monitor = new SessionMonitor(); // read Monitor data toTxns.clear(); toTxns = monitor->timedOutTxns(); // get timed out txns - CPPUNIT_ASSERT(toTxns.size()==(uint32_t)txnCntIncr*idx); + CPPUNIT_ASSERT(toTxns.size()==(uint)txnCntIncr*idx); delete monitor; } diff --git a/dbcon/execplan/treenode.cpp b/dbcon/execplan/treenode.cpp index 7e690a5d..9832d19f 100644 --- a/dbcon/execplan/treenode.cpp +++ b/dbcon/execplan/treenode.cpp @@ -16,17 +16,15 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: treenode.cpp 9317 2013-03-19 21:37:22Z dhall $ +* $Id: treenode.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ /** @file */ -#include #include #include #include -#include #include "bytestream.h" #include "treenode.h" @@ -38,30 +36,22 @@ namespace execplan{ /** * Constructors/Destructors */ -TreeNode::TreeNode(): fDerivedTable(""), - fRefCount(0), - fDerivedRefCol(NULL) -{ memset(tmp, 0, 312); } +TreeNode::TreeNode() {} TreeNode::TreeNode(const TreeNode& rhs): - fResult(rhs.fResult), - fResultType(rhs.resultType()), - fOperationType(rhs.operationType()), - fRegex (rhs.regex()), - fDerivedTable (rhs.derivedTable()), - fRefCount(rhs.refCount()), - fDerivedRefCol(rhs.derivedRefCol()) -{ memcpy(tmp, rhs.tmp, 312); } + fResult(rhs.fResult), + fResultType(rhs.resultType()), + fOperationType(rhs.operationType()), + fRegex (rhs.regex()) {} TreeNode::~TreeNode() {} -void TreeNode::resultType ( const execplan::CalpontSystemCatalog::ColType& resultType) -{ - fResultType = resultType; - +void TreeNode::resultType ( const execplan::CalpontSystemCatalog::ColType& resultType) +{ + fResultType = resultType; + // set scale/precision for the result - if (fResultType.colDataType == execplan::CalpontSystemCatalog::DECIMAL || - fResultType.colDataType == execplan::CalpontSystemCatalog::UDECIMAL) + if (fResultType.colDataType == execplan::CalpontSystemCatalog::DECIMAL) { fResult.decimalVal.scale = fResultType.scale; fResult.decimalVal.precision = fResultType.precision; diff --git a/dbcon/execplan/treenode.h b/dbcon/execplan/treenode.h index 4aff18fb..ac47bc77 100644 --- a/dbcon/execplan/treenode.h +++ b/dbcon/execplan/treenode.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: treenode.h 9635 2013-06-19 21:42:30Z bwilkinson $ +// $Id: treenode.h 9261 2013-02-06 20:59:01Z xlou $ /** @file */ @@ -170,7 +170,7 @@ struct IDB_Decimal } int64_t value; - int8_t scale; // 0~18 + int8_t scale; // 0~18 uint8_t precision; // 1~18 }; typedef IDB_Decimal CNX_Decimal; @@ -190,19 +190,19 @@ typedef IDB_Regex CNX_Regex; typedef boost::shared_ptr SP_IDB_Regex; typedef SP_IDB_Regex SP_CNX_Regex; -/** Trim trailing 0 from val. All insignificant zeroes to the right of the - * decimal point are removed. Also, the decimal point is not included on - * whole numbers. It works like %g flag with printf, but always print +/** Trim trailing 0 from val. All insignificant zeroes to the right of the + * decimal point are removed. Also, the decimal point is not included on + * whole numbers. It works like %g flag with printf, but always print * double value in fixed-point notation. * - * @parm val valid double value in fixed-point notation from printf %f. + * @parm val valid double value in fixed-point notation from printf %f. * No format validation is perfomed in this function. - * @parm length length of the buffer val + * @parm length length of the buffer val */ -inline std::string removeTrailing0(char* val, uint32_t length) +inline std::string removeTrailing0(char* val, uint length) { char* ptr = val; - uint32_t i = 0; + uint i = 0; bool decimal_point = false; for (; i < length; i++, ptr++) { @@ -218,7 +218,7 @@ inline std::string removeTrailing0(char* val, uint32_t length) *ptr = 0; break; } - + if (decimal_point) { for (i = i-1; i >= 0; i--) @@ -247,12 +247,11 @@ inline std::string removeTrailing0(char* val, uint32_t length) */ struct Result { - Result():intVal(0), uintVal(0), origIntVal(0), dummy(0), + Result():intVal(0), origIntVal(0), dummy(0), doubleVal(0), floatVal(0), boolVal(false), strVal(""), decimalVal(IDB_Decimal(0,0,0)), valueConverted(false) {} int64_t intVal; - uint64_t uintVal; uint64_t origIntVal; // clear up the memory following origIntVal to make sure null terminated string // when converting origIntVal @@ -313,43 +312,11 @@ class TreeNode */ virtual bool operator!=(const TreeNode* t) const = 0; - // derivedTable mutator and accessor - virtual const std::string& derivedTable() const - { return fDerivedTable; } - - virtual void derivedTable(const std::string& derivedTable) - { fDerivedTable = derivedTable; } - - // must to be implented by treenode that could potentially belong to - // one single derived table - virtual void setDerivedTable() - { fDerivedTable = ""; } - - virtual TreeNode* derivedRefCol() const - { return fDerivedRefCol; } - - virtual void derivedRefCol(TreeNode* derivedRefCol) - { fDerivedRefCol = derivedRefCol; } - - virtual uint64_t refCount() const - { return fRefCount; } - - virtual void refCount (const uint64_t refCount) - { fRefCount = refCount; } - - // the inc and dec functions are used by connector single thread. - virtual void decRefCount() - { fRefCount--; } - - virtual void incRefCount() - { fRefCount++; } - /*********************************************************************** * F&E framework * ***********************************************************************/ - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) {return fResult.strVal;} + virtual std::string getStrVal(rowgroup::Row& row, bool& isNull) {return fResult.strVal;} virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) {return fResult.intVal;} - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) {return fResult.uintVal;} virtual float getFloatVal(rowgroup::Row& row, bool& isNull) {return fResult.floatVal;} virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) {return fResult.doubleVal;} virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) {return fResult.decimalVal;} @@ -359,9 +326,8 @@ class TreeNode virtual void evaluate(rowgroup::Row& row, bool& isNull) {} inline bool getBoolVal(); - inline const std::string& getStrVal(); + inline std::string getStrVal(); inline int64_t getIntVal(); - inline uint64_t getUintVal(); inline float getFloatVal(); inline double getDoubleVal(); inline IDB_Decimal getDecimalVal(); @@ -391,12 +357,6 @@ class TreeNode // double's range is +/-1.7E308 with at least 15 digits of precision char tmp[312]; // for conversion use - // @bug5635 If any item involved in this filter belongs to a derived table, - // the derived table alias is added to the reference vector. - std::string fDerivedTable; - uint64_t fRefCount; - TreeNode* fDerivedRefCol; - private: //default okay //TreeNode& operator=(const TreeNode& rhs); @@ -427,20 +387,11 @@ inline bool TreeNode::getBoolVal() case CalpontSystemCatalog::DATE: case CalpontSystemCatalog::DATETIME: return (fResult.intVal != 0); - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::UINT: - return (fResult.uintVal != 0); case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: return (fResult.floatVal != 0); case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: return (fResult.doubleVal != 0); case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: return (fResult.decimalVal.value != 0); default: throw logging::InvalidConversionExcept("TreeNode::getBoolVal: Invalid conversion."); @@ -448,23 +399,23 @@ inline bool TreeNode::getBoolVal() return fResult.boolVal; } -inline const std::string& TreeNode::getStrVal() +inline std::string TreeNode::getStrVal() { switch (fResultType.colDataType) { case CalpontSystemCatalog::CHAR: if (fResultType.colWidth <= 8) - fResult.strVal = (char*)(&fResult.origIntVal); - break; + return (char*)(&fResult.origIntVal); + return fResult.strVal; case CalpontSystemCatalog::VARCHAR: if (fResultType.colWidth <= 7) - fResult.strVal = (char*)(&fResult.origIntVal); - break; + return (char*)(&fResult.origIntVal); + return fResult.strVal; //FIXME: ??? case CalpontSystemCatalog::VARBINARY: if (fResultType.colWidth <= 7) - fResult.strVal = (char*)(&fResult.origIntVal); - break; + return (char*)(&fResult.origIntVal); + return fResult.strVal; case CalpontSystemCatalog::BIGINT: case CalpontSystemCatalog::SMALLINT: case CalpontSystemCatalog::MEDINT: @@ -476,73 +427,34 @@ inline const std::string& TreeNode::getStrVal() #else snprintf(tmp, 20, "%ld", fResult.intVal); #endif - fResult.strVal = std::string(tmp); - break; - } - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::UINT: - { -#ifndef __LP64__ - snprintf(tmp, 20, "%llu", fResult.uintVal); -#else - snprintf(tmp, 20, "%lu", fResult.uintVal); -#endif - fResult.strVal = std::string(tmp); - break; + return std::string(tmp); } case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { - if ((fabs(fResult.floatVal) > (1.0 / IDB_pow[4])) && - (fabs(fResult.floatVal) < (float) IDB_pow[6])) - { - snprintf(tmp, 312, "%f", fResult.floatVal); - fResult.strVal = removeTrailing0(tmp, 312); - } - else - { - snprintf(tmp, 312, "%e", fResult.floatVal); - fResult.strVal = tmp; - } - break; + snprintf(tmp, 312, "%f", fResult.floatVal); + //return std::string(tmp); + return removeTrailing0(tmp, 312); } case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { - if ((fabs(fResult.doubleVal) > (1.0 / IDB_pow[13])) && - (fabs(fResult.doubleVal) < (float) IDB_pow[15])) - { - snprintf(tmp, 312, "%f", fResult.doubleVal); - fResult.strVal = removeTrailing0(tmp, 312); - } - else - { - snprintf(tmp, 312, "%e", fResult.doubleVal); - fResult.strVal = tmp; - } - break; + snprintf(tmp, 312, "%f", fResult.doubleVal); + return removeTrailing0(tmp, 312); + //return std::string(tmp); } case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { - dataconvert::DataConvert::decimalToString(fResult.decimalVal.value, fResult.decimalVal.scale, tmp, 22, fResultType.colDataType); - fResult.strVal = std::string(tmp); - break; + dataconvert::DataConvert::decimalToString(fResult.decimalVal.value, fResult.decimalVal.scale, tmp, 22); + return std::string(tmp); } case CalpontSystemCatalog::DATE: { dataconvert::DataConvert::dateToString(fResult.intVal, tmp, 255); - fResult.strVal = std::string(tmp); - break; + return std::string(tmp); } case CalpontSystemCatalog::DATETIME: { dataconvert::DataConvert::datetimeToString(fResult.intVal, tmp, 255); - fResult.strVal = std::string(tmp); - break; + return std::string(tmp); } default: throw logging::InvalidConversionExcept("TreeNode::getStrVal: Invalid conversion."); @@ -573,20 +485,11 @@ inline int64_t TreeNode::getIntVal() case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: return fResult.intVal; - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - return fResult.uintVal; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: return (int64_t)fResult.floatVal; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: return (int64_t)fResult.doubleVal; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { return (int64_t)(fResult.decimalVal.value / pow((double)10, fResult.decimalVal.scale)); } @@ -598,41 +501,6 @@ inline int64_t TreeNode::getIntVal() } return fResult.intVal; } -inline uint64_t TreeNode::getUintVal() -{ - switch (fResultType.colDataType) - { - case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::TINYINT: - case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::MEDINT: - case CalpontSystemCatalog::INT: - return fResult.intVal; - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - return fResult.uintVal; - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - return (uint64_t)fResult.floatVal; - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - return (uint64_t)fResult.doubleVal; - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: - { - return (uint64_t)(fResult.decimalVal.value / pow((double)10, fResult.decimalVal.scale)); - } - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - return fResult.intVal; - default: - throw logging::InvalidConversionExcept("TreeNode::getIntVal: Invalid conversion."); - } - return fResult.intVal; -} inline float TreeNode::getFloatVal() { switch (fResultType.colDataType) @@ -656,17 +524,9 @@ inline float TreeNode::getFloatVal() case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: return (float)fResult.intVal; - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - return (float)fResult.uintVal; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: return fResult.floatVal; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: return (float)fResult.doubleVal; case CalpontSystemCatalog::DECIMAL: { @@ -703,20 +563,11 @@ inline double TreeNode::getDoubleVal() case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: return (double)fResult.intVal; - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - return (double)fResult.uintVal; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: return (double)fResult.floatVal; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: return fResult.doubleVal; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { // this may not be accurate. if this is problematic, change to pre-calculated power array. return (double)(fResult.decimalVal.value / pow((double)10, fResult.decimalVal.scale)); @@ -747,28 +598,14 @@ inline IDB_Decimal TreeNode::getDecimalVal() fResult.decimalVal.scale = fResultType.scale; fResult.decimalVal.precision = fResultType.precision; break; - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UTINYINT: - fResult.decimalVal.value =(int64_t)(fResult.uintVal * pow((double)10, fResultType.scale)); - fResult.decimalVal.scale = fResultType.scale; - fResult.decimalVal.precision = fResultType.precision; - break; case CalpontSystemCatalog::DATE: case CalpontSystemCatalog::DATETIME: throw logging::InvalidConversionExcept("TreeNode::getDecimalVal: Invalid conversion from datetime."); case CalpontSystemCatalog::FLOAT: throw logging::InvalidConversionExcept("TreeNode::getDecimalVal: non-support conversion from float"); - case CalpontSystemCatalog::UFLOAT: - throw logging::InvalidConversionExcept("TreeNode::getDecimalVal: non-support conversion from float unsigned"); case CalpontSystemCatalog::DOUBLE: throw logging::InvalidConversionExcept("TreeNode::getDecimalVal: non-support conversion from double"); - case CalpontSystemCatalog::UDOUBLE: - throw logging::InvalidConversionExcept("TreeNode::getDecimalVal: non-support conversion from double unsigned"); case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: return fResult.decimalVal; default: throw logging::InvalidConversionExcept("TreeNode::getDecimalVal: Invalid conversion."); @@ -790,9 +627,9 @@ inline int64_t TreeNode::getDatetimeIntVal() inline int32_t TreeNode::getDateIntVal() { if (fResultType.colDataType == execplan::CalpontSystemCatalog::DATETIME) - return (((int32_t)(fResult.intVal >> 32) & 0xFFFFFFC0) | 0x3E); + return (int32_t)(fResult.intVal >> 32) & 0xFFFFFFC0; else if (fResultType.colDataType == execplan::CalpontSystemCatalog::DATE) - return ((fResult.intVal & 0xFFFFFFC0) | 0x3E); + return fResult.intVal & 0xFFFFFFC0; else return getIntVal(); } diff --git a/dbcon/execplan/treenodeimpl.cpp b/dbcon/execplan/treenodeimpl.cpp index 6ffe2787..e4f97886 100644 --- a/dbcon/execplan/treenodeimpl.cpp +++ b/dbcon/execplan/treenodeimpl.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: treenodeimpl.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: treenodeimpl.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/treenodeimpl.h b/dbcon/execplan/treenodeimpl.h index 15bb1073..d75b5943 100644 --- a/dbcon/execplan/treenodeimpl.h +++ b/dbcon/execplan/treenodeimpl.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: treenodeimpl.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: treenodeimpl.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/vendorexecutionplan.cpp b/dbcon/execplan/vendorexecutionplan.cpp index 1f9edb3b..e5bc75ba 100644 --- a/dbcon/execplan/vendorexecutionplan.cpp +++ b/dbcon/execplan/vendorexecutionplan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: vendorexecutionplan.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: vendorexecutionplan.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/vendorexecutionplan.h b/dbcon/execplan/vendorexecutionplan.h index 5d2d23ce..3fa99745 100644 --- a/dbcon/execplan/vendorexecutionplan.h +++ b/dbcon/execplan/vendorexecutionplan.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: vendorexecutionplan.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: vendorexecutionplan.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/execplan/windowfunctioncolumn.cpp b/dbcon/execplan/windowfunctioncolumn.cpp deleted file mode 100644 index 25d28804..00000000 --- a/dbcon/execplan/windowfunctioncolumn.cpp +++ /dev/null @@ -1,572 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: windowfunctioncolumn.cpp 9679 2013-07-11 22:32:03Z zzhu $ -* -* -***********************************************************************/ - -#include -#include -#include -using namespace std; - -#include -#include -using namespace boost; - -#include "bytestream.h" -#include "windowfunctioncolumn.h" -#include "constantcolumn.h" -#include "arithmeticcolumn.h" -#include "simplecolumn.h" -#include "objectreader.h" -#include "calpontselectexecutionplan.h" -#include "simplefilter.h" -#include "aggregatecolumn.h" -#include "functioncolumn.h" - -#include "funcexp.h" -#include "functor_export.h" -using namespace funcexp; - -#include "rowgroup.h" -using namespace rowgroup; - -#include "joblisttypes.h" -using namespace joblist; - -#ifdef _MSC_VER -#define strcasecmp stricmp -#endif - -namespace execplan { - -void getWindowFunctionCols(execplan::ParseTree* n, void* obj) -{ - vector* list = reinterpret_cast< vector*>(obj); - TreeNode* tn = n->data(); - WindowFunctionColumn *afc = dynamic_cast(tn); - ArithmeticColumn *ac = dynamic_cast(tn); - FunctionColumn *fc = dynamic_cast(tn); - SimpleFilter *sf = dynamic_cast(tn); - - if (afc) - list->push_back(afc); - else if (ac) - list->insert(list->end(), ac->windowfunctionColumnList().begin(), ac->windowfunctionColumnList().end()); - else if (fc) - list->insert(list->end(), fc->windowfunctionColumnList().begin(), fc->windowfunctionColumnList().end()); - else if (sf) - list->insert(list->end(), sf->windowfunctionColumnList().begin(), sf->windowfunctionColumnList().end()); -} - -/** - * WF_Boundary class methods definition - */ -const std::string WF_Boundary::toString() const -{ - ostringstream output; - - if (fVal) - { - output << "val: "; - output << fVal->toString() << endl; - } - if (fBound) - { - output << "bound exp: "; - output << fBound->toString() << endl; - } - - switch (fFrame) - { - case WF_PRECEDING: - output << "PRECEDING"; - break; - case WF_FOLLOWING: - output << "FOLLOWING"; - break; - case WF_UNBOUNDED_PRECEDING: - output << "UNBOUNDED PRECEDING"; - break; - case WF_UNBOUNDED_FOLLOWING: - output << "UNBOUNDED FOLLOWING"; - break; - case WF_CURRENT_ROW: - output << "CURRENT ROW"; - break; - default: - output << "UNKNOWN"; - } - return output.str(); -} - -void WF_Boundary::serialize(messageqcpp::ByteStream& b) const -{ - b << (uint8_t)fFrame; - if (fVal) - fVal->serialize(b); - else - b << (uint8_t) ObjectReader::NULL_CLASS; - if (fBound) - fBound->serialize(b); - else - b << (uint8_t) ObjectReader::NULL_CLASS; -} - -void WF_Boundary::unserialize(messageqcpp::ByteStream& b) -{ - b >> (uint8_t&)fFrame; - fVal.reset(dynamic_cast(ObjectReader::createTreeNode(b))); - fBound.reset(dynamic_cast(ObjectReader::createTreeNode(b))); -} - -/** - * WF_Frame class methods definition - */ -const string WF_Frame::toString() const -{ - ostringstream output; - output << "WindowFrame:" << endl; - output << "Start:" << endl; - output << fStart.toString() << endl; - output << "End:" << endl; - output << fEnd.toString() << endl; - return output.str(); -} - -void WF_Frame::serialize(messageqcpp::ByteStream& b) const -{ - fStart.serialize(b); - fEnd.serialize(b); - b << (uint8_t)fIsRange; -} - -void WF_Frame::unserialize(messageqcpp::ByteStream& b) -{ - fStart.unserialize(b); - fEnd.unserialize(b); - b >> (uint8_t&)fIsRange; -} - -/** - * WF_OrderBy class methods definition - */ - -const string WF_OrderBy::toString() const -{ - ostringstream output; - output << "order by: " << endl; - for (uint32_t i = 0; i < fOrders.size(); i++) - output << fOrders[i]->toString() << endl; - output << fFrame.toString(); - return output.str(); -} - -void WF_OrderBy::serialize(messageqcpp::ByteStream& b) const -{ - b << (uint32_t)fOrders.size(); - for (uint32_t i = 0; i < fOrders.size(); i++) - fOrders[i]->serialize(b); - fFrame.serialize(b); -} - -void WF_OrderBy::unserialize(messageqcpp::ByteStream& b) -{ - uint32_t size; - b >> (uint32_t&)size; - SRCP srcp; - for (uint32_t i = 0; i < size; i++) - { - srcp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); - fOrders.push_back(srcp); - } - fFrame.unserialize(b); -} - - /** - * WindowFunctionColumn class definition - */ - -WindowFunctionColumn::WindowFunctionColumn() -{} - -WindowFunctionColumn::WindowFunctionColumn(const string& functionName, const uint32_t sessionID): - ReturnedColumn(sessionID), - fFunctionName(functionName) -{} - -WindowFunctionColumn::WindowFunctionColumn( const WindowFunctionColumn& rhs, const uint32_t sessionID): - ReturnedColumn(rhs, sessionID), - fFunctionName(rhs.functionName()), - fFunctionParms(rhs.functionParms()), - fPartitions (rhs.partitions()), - fOrderBy (rhs.orderBy()) -{} - -const string WindowFunctionColumn::toString() const -{ - ostringstream output; - output << "WindowFunctionColumn: " << fFunctionName; - if (distinct()) - output << " DISTINCT"; - output << endl; - output << "expressionId=" << fExpressionId << endl; - output << "resultType=" << colDataTypeToString(fResultType.colDataType) << "|" << fResultType.colWidth << endl; - output << "operationType=" << colDataTypeToString(fOperationType.colDataType) << endl; - output << "function parm: " << endl; - for (uint32_t i = 0; i < fFunctionParms.size(); i++) - output << fFunctionParms[i]->toString() << endl; - output << "partition by: " << endl; - for (uint32_t i = 0; i < fPartitions.size(); i++) - output << fPartitions[i]->toString() << endl; - output << fOrderBy.toString() << endl; - output << "getColumnList():" << endl; - vector colList = getColumnList(); - for (uint32_t i = 0; i < colList.size(); i++) - output << colList[i]->toString() << endl; - return output.str(); -} - -void WindowFunctionColumn::serialize(messageqcpp::ByteStream& b) const -{ - b << (ObjectReader::id_t) ObjectReader::WINDOWFUNCTIONCOLUMN; - ReturnedColumn::serialize(b); - b << fFunctionName; - - b << (uint32_t)fFunctionParms.size(); - for (uint32_t i = 0; i < fFunctionParms.size(); i++) - fFunctionParms[i]->serialize(b); - b << (uint32_t)fPartitions.size(); - for (uint32_t i = 0; i < fPartitions.size(); i++) - fPartitions[i]->serialize(b); - fOrderBy.serialize(b); -} - -void WindowFunctionColumn::unserialize(messageqcpp::ByteStream& b) -{ - ObjectReader::checkType(b, ObjectReader::WINDOWFUNCTIONCOLUMN); - ReturnedColumn::unserialize(b); - uint32_t size; - SRCP srcp; - - fFunctionParms.clear(); - fPartitions.clear(); - - b >> fFunctionName; - b >> (uint32_t&)size; - for (uint32_t i = 0; i < size; i++) - { - srcp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); - fFunctionParms.push_back(srcp); - } - b >> (uint32_t&)size; - for (uint32_t i = 0; i < size; i++) - { - srcp.reset(dynamic_cast(ObjectReader::createTreeNode(b))); - fPartitions.push_back(srcp); - } - fOrderBy.unserialize(b); -} - -void WindowFunctionColumn::addToPartition(vector& groupByList) -{ - fPartitions.insert(fPartitions.end(), groupByList.begin(), groupByList.end()); -} - -vector WindowFunctionColumn::getColumnList() const -{ - vector columnList; - columnList.insert(columnList.end(), fFunctionParms.begin(), fFunctionParms.end()); - columnList.insert(columnList.end(), fPartitions.begin(), fPartitions.end()); - columnList.insert(columnList.end(), fOrderBy.fOrders.begin(), fOrderBy.fOrders.end()); - if (fOrderBy.fFrame.fStart.fVal) - columnList.push_back(fOrderBy.fFrame.fStart.fVal); - if (fOrderBy.fFrame.fStart.fBound) - columnList.push_back(fOrderBy.fFrame.fStart.fBound); - if (fOrderBy.fFrame.fEnd.fVal) - columnList.push_back(fOrderBy.fFrame.fEnd.fVal); - if (fOrderBy.fFrame.fEnd.fBound) - columnList.push_back(fOrderBy.fFrame.fEnd.fBound); - return columnList; -} - -bool WindowFunctionColumn::hasWindowFunc() -{ - fWindowFunctionColumnList.push_back(this); - return true; -} - -void WindowFunctionColumn::adjustResultType() -{ - if (fResultType.colDataType == CalpontSystemCatalog::DECIMAL && - !boost::iequals(fFunctionName,"COUNT") && - !boost::iequals(fFunctionName,"COUNT(*)") && - !boost::iequals(fFunctionName,"ROW_NUMBER") && - !boost::iequals(fFunctionName,"RANK") && - !boost::iequals(fFunctionName,"PERCENT_RANK") && - !boost::iequals(fFunctionName,"DENSE_RANK") && - !boost::iequals(fFunctionName,"CUME_DIST") && - !boost::iequals(fFunctionName,"NTILE") && - !boost::iequals(fFunctionName,"PERCENTILE") && - !fFunctionParms.empty() && - fFunctionParms[0]->resultType().colDataType == CalpontSystemCatalog::DOUBLE) - fResultType = fFunctionParms[0]->resultType(); - - if ((boost::iequals(fFunctionName, "LEAD") || - boost::iequals(fFunctionName, "LAG") || - boost::iequals(fFunctionName, "MIN") || - boost::iequals(fFunctionName, "MAX") || - boost::iequals(fFunctionName, "FIRST_VALUE") || - boost::iequals(fFunctionName, "LAST_VALUE") || - boost::iequals(fFunctionName, "NTH_VALUE")) && - !fFunctionParms.empty()) - fResultType = fFunctionParms[0]->resultType(); -} - -void WindowFunctionColumn::evaluate(Row& row, bool& isNull) -{ - switch (fResultType.colDataType) - { - case CalpontSystemCatalog::DATE: - { - if (row.equals<4>(DATENULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getUintField<4>(fInputIndex); - break; - } - case CalpontSystemCatalog::DATETIME: - { - if (row.equals<8>(DATETIMENULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getUintField<8>(fInputIndex); - break; - } - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::STRINT: - { - switch (row.getColumnWidth(fInputIndex)) - { - case 1: - if (row.equals<1>(CHAR1NULL, fInputIndex)) - isNull = true; - else - fResult.origIntVal = row.getUintField<1>(fInputIndex); - break; - case 2: - if (row.equals<2>(CHAR2NULL, fInputIndex)) - isNull = true; - else - fResult.origIntVal = row.getUintField<2>(fInputIndex); - break; - case 3: - case 4: - if (row.equals<4>(CHAR4NULL, fInputIndex)) - isNull = true; - else - fResult.origIntVal = row.getUintField<4>(fInputIndex); - break; - case 5: - case 6: - case 7: - case 8: - if (row.equals<8>(CHAR8NULL, fInputIndex)) - isNull = true; - else - fResult.origIntVal = row.getUintField<8>(fInputIndex); - break; - default: - if (row.equals(CPNULLSTRMARK, fInputIndex)) - isNull = true; - else - fResult.strVal = row.getStringField(fInputIndex); - // stringColVal is padded with '\0' to colWidth so can't use str.length() - if (strlen(fResult.strVal.c_str()) == 0) - isNull = true; - break; - } - if (fResultType.colDataType == CalpontSystemCatalog::STRINT) - fResult.intVal = uint64ToStr(fResult.origIntVal); - else - fResult.intVal = atoll((char*)&fResult.origIntVal); - break; - } - case CalpontSystemCatalog::BIGINT: - { - if (row.equals<8>(BIGINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<8>(fInputIndex); - break; - } - case CalpontSystemCatalog::UBIGINT: - { - if (row.equals<8>(UBIGINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<8>(fInputIndex); - break; - } - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::MEDINT: - { - if (row.equals<4>(INTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<4>(fInputIndex); - break; - } - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UMEDINT: - { - if (row.equals<4>(UINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<4>(fInputIndex); - break; - } - case CalpontSystemCatalog::SMALLINT: - { - if (row.equals<2>(SMALLINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<2>(fInputIndex); - break; - } - case CalpontSystemCatalog::USMALLINT: - { - if (row.equals<2>(USMALLINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<2>(fInputIndex); - break; - } - case CalpontSystemCatalog::TINYINT: - { - if (row.equals<1>(TINYINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getIntField<1>(fInputIndex); - break; - } - case CalpontSystemCatalog::UTINYINT: - { - if (row.equals<1>(UTINYINTNULL, fInputIndex)) - isNull = true; - else - fResult.uintVal = row.getUintField<1>(fInputIndex); - break; - } - //In this case, we're trying to load a double output column with float data. This is the - // case when you do sum(floatcol), e.g. - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - { - if (row.equals<4>(FLOATNULL, fInputIndex)) - isNull = true; - else - fResult.floatVal = row.getFloatField(fInputIndex); - break; - } - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - { - if (row.equals<8>(DOUBLENULL, fInputIndex)) - isNull = true; - else - fResult.doubleVal = row.getDoubleField(fInputIndex); - break; - } - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: - { - switch (fResultType.colWidth) - { - case 1: - { - if (row.equals<1>(TINYINTNULL, fInputIndex)) - isNull = true; - else - { - fResult.decimalVal.value = row.getIntField<1>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } - break; - } - case 2: - { - if (row.equals<2>(SMALLINTNULL, fInputIndex)) - isNull = true; - else - { - fResult.decimalVal.value = row.getIntField<2>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } - break; - } - case 4: - { - if (row.equals<4>(INTNULL, fInputIndex)) - isNull = true; - else - { - fResult.decimalVal.value = row.getIntField<4>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } - break; - } - default: - { - if (row.equals<8>(BIGINTNULL, fInputIndex)) - isNull = true; - else - { - fResult.decimalVal.value = (int64_t)row.getUintField<8>(fInputIndex); - fResult.decimalVal.scale = (unsigned)fResultType.scale; - } - break; - } - } - break; - } - case CalpontSystemCatalog::VARBINARY: - isNull = true; - break; - default: // treat as int64 - { - if (row.equals<8>(BIGINTNULL, fInputIndex)) - isNull = true; - else - fResult.intVal = row.getUintField<8>(fInputIndex); - break; - } - } -} - - -ostream& operator<<(ostream& output, const WindowFunctionColumn& rhs) -{ - output << rhs.toString(); - return output; -} - -} //namespace diff --git a/dbcon/execplan/windowfunctioncolumn.h b/dbcon/execplan/windowfunctioncolumn.h deleted file mode 100644 index d8b9fec7..00000000 --- a/dbcon/execplan/windowfunctioncolumn.h +++ /dev/null @@ -1,265 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: windowfunctioncolumn.h 9679 2013-07-11 22:32:03Z zzhu $ -* -* -***********************************************************************/ - -/** @file */ - -#ifndef WINDOW_FUNCTION_COLUMN_H -#define WINDOW_FUNCTION_COLUMN_H -#include -#include -#include - -#include "returnedcolumn.h" -#include "functor.h" - -namespace messageqcpp { -class ByteStream; -} - -/** - * Namespace - */ -namespace execplan { - -// This enum is made consistant with mysql item_func_window -enum WF_FRAME -{ - WF_PRECEDING = 0, - WF_FOLLOWING, - WF_UNBOUNDED_PRECEDING, - WF_UNBOUNDED_FOLLOWING, - WF_CURRENT_ROW, - WF_UNKNOWN -}; - -struct WF_Boundary -{ - WF_Boundary() {} - WF_Boundary(WF_FRAME frame):fFrame(frame) {} - ~WF_Boundary() {} - const std::string toString() const; - void serialize(messageqcpp::ByteStream&) const; - void unserialize(messageqcpp::ByteStream&); - SRCP fVal; /// has to evaluate to unsigned value - SRCP fBound; /// order by col +, -, date_add or date_sub for RANGE window - enum WF_FRAME fFrame; -}; - -struct WF_Frame -{ - WF_Frame(): fIsRange(true) - { - fStart.fFrame = WF_UNBOUNDED_PRECEDING; - fEnd.fFrame = WF_UNBOUNDED_FOLLOWING; - } - ~WF_Frame() {} - const std::string toString() const; - void serialize(messageqcpp::ByteStream&) const; - void unserialize(messageqcpp::ByteStream&); - WF_Boundary fStart; - WF_Boundary fEnd; - bool fIsRange; /// RANGE or ROWS -}; - -/** - * @brief A class to represent the order by clause of window function - */ -struct WF_OrderBy -{ - WF_OrderBy() {} - WF_OrderBy(std::vector orders): fOrders(orders) {} - ~WF_OrderBy() {}; - const std::string toString() const; - void serialize(messageqcpp::ByteStream&) const; - void unserialize(messageqcpp::ByteStream&); - std::vector fOrders; - WF_Frame fFrame; -}; - -/** - * @brief A class to represent a functional column - * - * This class is a specialization of class ReturnedColumn that - * handles a window function. - */ -class WindowFunctionColumn : public ReturnedColumn { - -public: - WindowFunctionColumn(); - WindowFunctionColumn(const std::string& functionName, const uint32_t sessionID = 0); - WindowFunctionColumn(const WindowFunctionColumn& rhs, const uint32_t sessionID = 0); - virtual ~WindowFunctionColumn() {} - - /** get function name */ - inline const std::string& functionName() const - { - return fFunctionName; - } - - /** set function name */ - inline void functionName(const std::string functionName) - { - fFunctionName = functionName; - } - - /** get function parameters */ - inline const std::vector& functionParms() const - { - return fFunctionParms; - } - - /** set function parameters*/ - inline void functionParms(const std::vector& functionParms) - { - fFunctionParms = functionParms; - } - - /** get partition columns */ - inline const std::vector& partitions() const - { - return fPartitions; - } - - /** set partition columns */ - inline void partitions(const std::vector& partitions) - { - fPartitions = partitions; - } - - /** get order by clause */ - inline const WF_OrderBy& orderBy() const - { - return fOrderBy; - } - - /** set order by clause */ - inline void orderBy(const WF_OrderBy& orderBy) - { - fOrderBy = orderBy; - } - - /** make a clone of this window function */ - inline virtual WindowFunctionColumn* clone() const - { - return new WindowFunctionColumn (*this); - } - - std::vector getColumnList() const; - - /** output the function for debug purpose */ - const std::string toString() const; - - /** - * The serialization interface - */ - virtual void serialize(messageqcpp::ByteStream&) const; - virtual void unserialize(messageqcpp::ByteStream&); - - // util function for connector to use. - void addToPartition(std::vector& groupByList); - - virtual bool hasAggregate() {return false;} - virtual bool hasWindowFunc(); - void adjustResultType(); - -private: - /** - * Fields - */ - std::string fFunctionName; /// function name - std::vector fFunctionParms; /// function arguments - std::vector fPartitions; /// partition by clause - WF_OrderBy fOrderBy; /// order by clause - - // not support for window functions for now. - virtual bool operator==(const TreeNode* t) const { return false; } - bool operator==(const WindowFunctionColumn& t) const; - virtual bool operator!=(const TreeNode* t) const { return false; } - bool operator!=(const WindowFunctionColumn& t) const; - - /*********************************************************** - * F&E framework * - ***********************************************************/ -public: - virtual const std::string& getStrVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getStrVal(); - } - - virtual int64_t getIntVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getIntVal(); - } - - virtual uint64_t getUintVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getUintVal(); - } - - virtual float getFloatVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getFloatVal(); - } - - virtual double getDoubleVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getDoubleVal(); - } - - virtual IDB_Decimal getDecimalVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getDecimalVal(); - } - virtual int32_t getDateIntVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getDateIntVal(); - } - virtual int64_t getDatetimeIntVal(rowgroup::Row& row, bool& isNull) - { - evaluate(row, isNull); - return TreeNode::getDatetimeIntVal(); - } - -private: - void evaluate(rowgroup::Row& row, bool& isNull); -}; - -/** -* ostream operator -*/ -std::ostream& operator<<(std::ostream& output, const WindowFunctionColumn& rhs); - -/** - * utility function to extract all window function columns from a parse tree - */ -void getWindowFunctionCols(ParseTree* n, void* obj); - -} -#endif //WINDOW_FUNCTION_COLUMN_H diff --git a/dbcon/joblist/Makefile.am b/dbcon/joblist/Makefile.am index 80a0956f..f8f5ffbb 100644 --- a/dbcon/joblist/Makefile.am +++ b/dbcon/joblist/Makefile.am @@ -14,6 +14,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) @@ -28,7 +32,6 @@ libjoblist_la_SOURCES = \ command-jl.cpp \ crossenginestep.cpp \ dictstep-jl.cpp \ - diskjoinstep.cpp \ distributedenginecomm.cpp \ elementtype.cpp \ expressionstep.cpp \ @@ -54,7 +57,6 @@ libjoblist_la_SOURCES = \ pdictionary.cpp \ pdictionaryscan.cpp \ primitivemsg.cpp \ - pseudocc-jl.cpp \ resourcedistributor.cpp \ resourcemanager.cpp \ rowestimator.cpp \ @@ -71,8 +73,7 @@ libjoblist_la_SOURCES = \ tuplehavingstep.cpp \ tupleunion.cpp \ unique32generator.cpp \ - virtualtable.cpp \ - windowfunctionstep.cpp + virtualtable.cpp include_HEADERS = \ bpp-jl.h \ @@ -81,7 +82,6 @@ include_HEADERS = \ distributedenginecomm.h \ elementcompression.h \ elementtype.h \ - errorinfo.h \ fifo.h \ groupconcat.h \ jl_logger.h \ @@ -99,8 +99,7 @@ include_HEADERS = \ threadsafequeue.h \ timeset.h \ timestamp.h \ - unique32generator.h \ - windowfunctionstep.h + unique32generator.h test: diff --git a/dbcon/joblist/Makefile.in b/dbcon/joblist/Makefile.in index 5ef83a4c..ec41bdd4 100644 --- a/dbcon/joblist/Makefile.in +++ b/dbcon/joblist/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -41,9 +60,8 @@ subdir = dbcon/joblist DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -63,7 +81,6 @@ am_libjoblist_la_OBJECTS = libjoblist_la-anydatalist.lo \ libjoblist_la-batchprimitiveprocessor-jl.lo \ libjoblist_la-columncommand-jl.lo libjoblist_la-command-jl.lo \ libjoblist_la-crossenginestep.lo libjoblist_la-dictstep-jl.lo \ - libjoblist_la-diskjoinstep.lo \ libjoblist_la-distributedenginecomm.lo \ libjoblist_la-elementtype.lo libjoblist_la-expressionstep.lo \ libjoblist_la-filtercommand-jl.lo libjoblist_la-filterstep.lo \ @@ -80,7 +97,6 @@ am_libjoblist_la_OBJECTS = libjoblist_la-anydatalist.lo \ libjoblist_la-passthrustep.lo libjoblist_la-pcolscan.lo \ libjoblist_la-pcolstep.lo libjoblist_la-pdictionary.lo \ libjoblist_la-pdictionaryscan.lo libjoblist_la-primitivemsg.lo \ - libjoblist_la-pseudocc-jl.lo \ libjoblist_la-resourcedistributor.lo \ libjoblist_la-resourcemanager.lo libjoblist_la-rowestimator.lo \ libjoblist_la-rtscommand-jl.lo libjoblist_la-subquerystep.lo \ @@ -92,8 +108,7 @@ am_libjoblist_la_OBJECTS = libjoblist_la-anydatalist.lo \ libjoblist_la-tuplehashjoin.lo \ libjoblist_la-tuplehavingstep.lo libjoblist_la-tupleunion.lo \ libjoblist_la-unique32generator.lo \ - libjoblist_la-virtualtable.lo \ - libjoblist_la-windowfunctionstep.lo + libjoblist_la-virtualtable.lo libjoblist_la_OBJECTS = $(am_libjoblist_la_OBJECTS) DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp @@ -172,9 +187,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -216,7 +228,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -230,11 +241,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -245,23 +251,6 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) @@ -276,7 +265,6 @@ libjoblist_la_SOURCES = \ command-jl.cpp \ crossenginestep.cpp \ dictstep-jl.cpp \ - diskjoinstep.cpp \ distributedenginecomm.cpp \ elementtype.cpp \ expressionstep.cpp \ @@ -302,7 +290,6 @@ libjoblist_la_SOURCES = \ pdictionary.cpp \ pdictionaryscan.cpp \ primitivemsg.cpp \ - pseudocc-jl.cpp \ resourcedistributor.cpp \ resourcemanager.cpp \ rowestimator.cpp \ @@ -319,8 +306,7 @@ libjoblist_la_SOURCES = \ tuplehavingstep.cpp \ tupleunion.cpp \ unique32generator.cpp \ - virtualtable.cpp \ - windowfunctionstep.cpp + virtualtable.cpp include_HEADERS = \ bpp-jl.h \ @@ -329,7 +315,6 @@ include_HEADERS = \ distributedenginecomm.h \ elementcompression.h \ elementtype.h \ - errorinfo.h \ fifo.h \ groupconcat.h \ jl_logger.h \ @@ -347,8 +332,7 @@ include_HEADERS = \ threadsafequeue.h \ timeset.h \ timestamp.h \ - unique32generator.h \ - windowfunctionstep.h + unique32generator.h all: all-am @@ -425,7 +409,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-command-jl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-crossenginestep.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-dictstep-jl.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-diskjoinstep.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-distributedenginecomm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-elementtype.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-expressionstep.Plo@am__quote@ @@ -451,7 +434,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-pdictionary.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-pdictionaryscan.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-primitivemsg.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-pseudocc-jl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-resourcedistributor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-resourcemanager.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-rowestimator.Plo@am__quote@ @@ -469,7 +451,6 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-tupleunion.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-unique32generator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-virtualtable.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libjoblist_la-windowfunctionstep.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ @@ -534,13 +515,6 @@ libjoblist_la-dictstep-jl.lo: dictstep-jl.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -c -o libjoblist_la-dictstep-jl.lo `test -f 'dictstep-jl.cpp' || echo '$(srcdir)/'`dictstep-jl.cpp -libjoblist_la-diskjoinstep.lo: diskjoinstep.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -MT libjoblist_la-diskjoinstep.lo -MD -MP -MF "$(DEPDIR)/libjoblist_la-diskjoinstep.Tpo" -c -o libjoblist_la-diskjoinstep.lo `test -f 'diskjoinstep.cpp' || echo '$(srcdir)/'`diskjoinstep.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libjoblist_la-diskjoinstep.Tpo" "$(DEPDIR)/libjoblist_la-diskjoinstep.Plo"; else rm -f "$(DEPDIR)/libjoblist_la-diskjoinstep.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='diskjoinstep.cpp' object='libjoblist_la-diskjoinstep.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -c -o libjoblist_la-diskjoinstep.lo `test -f 'diskjoinstep.cpp' || echo '$(srcdir)/'`diskjoinstep.cpp - libjoblist_la-distributedenginecomm.lo: distributedenginecomm.cpp @am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -MT libjoblist_la-distributedenginecomm.lo -MD -MP -MF "$(DEPDIR)/libjoblist_la-distributedenginecomm.Tpo" -c -o libjoblist_la-distributedenginecomm.lo `test -f 'distributedenginecomm.cpp' || echo '$(srcdir)/'`distributedenginecomm.cpp; \ @am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libjoblist_la-distributedenginecomm.Tpo" "$(DEPDIR)/libjoblist_la-distributedenginecomm.Plo"; else rm -f "$(DEPDIR)/libjoblist_la-distributedenginecomm.Tpo"; exit 1; fi @@ -716,13 +690,6 @@ libjoblist_la-primitivemsg.lo: primitivemsg.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -c -o libjoblist_la-primitivemsg.lo `test -f 'primitivemsg.cpp' || echo '$(srcdir)/'`primitivemsg.cpp -libjoblist_la-pseudocc-jl.lo: pseudocc-jl.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -MT libjoblist_la-pseudocc-jl.lo -MD -MP -MF "$(DEPDIR)/libjoblist_la-pseudocc-jl.Tpo" -c -o libjoblist_la-pseudocc-jl.lo `test -f 'pseudocc-jl.cpp' || echo '$(srcdir)/'`pseudocc-jl.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libjoblist_la-pseudocc-jl.Tpo" "$(DEPDIR)/libjoblist_la-pseudocc-jl.Plo"; else rm -f "$(DEPDIR)/libjoblist_la-pseudocc-jl.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='pseudocc-jl.cpp' object='libjoblist_la-pseudocc-jl.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -c -o libjoblist_la-pseudocc-jl.lo `test -f 'pseudocc-jl.cpp' || echo '$(srcdir)/'`pseudocc-jl.cpp - libjoblist_la-resourcedistributor.lo: resourcedistributor.cpp @am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -MT libjoblist_la-resourcedistributor.lo -MD -MP -MF "$(DEPDIR)/libjoblist_la-resourcedistributor.Tpo" -c -o libjoblist_la-resourcedistributor.lo `test -f 'resourcedistributor.cpp' || echo '$(srcdir)/'`resourcedistributor.cpp; \ @am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libjoblist_la-resourcedistributor.Tpo" "$(DEPDIR)/libjoblist_la-resourcedistributor.Plo"; else rm -f "$(DEPDIR)/libjoblist_la-resourcedistributor.Tpo"; exit 1; fi @@ -842,13 +809,6 @@ libjoblist_la-virtualtable.lo: virtualtable.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -c -o libjoblist_la-virtualtable.lo `test -f 'virtualtable.cpp' || echo '$(srcdir)/'`virtualtable.cpp -libjoblist_la-windowfunctionstep.lo: windowfunctionstep.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -MT libjoblist_la-windowfunctionstep.lo -MD -MP -MF "$(DEPDIR)/libjoblist_la-windowfunctionstep.Tpo" -c -o libjoblist_la-windowfunctionstep.lo `test -f 'windowfunctionstep.cpp' || echo '$(srcdir)/'`windowfunctionstep.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libjoblist_la-windowfunctionstep.Tpo" "$(DEPDIR)/libjoblist_la-windowfunctionstep.Plo"; else rm -f "$(DEPDIR)/libjoblist_la-windowfunctionstep.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='windowfunctionstep.cpp' object='libjoblist_la-windowfunctionstep.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libjoblist_la_CPPFLAGS) $(CPPFLAGS) $(libjoblist_la_CXXFLAGS) $(CXXFLAGS) -c -o libjoblist_la-windowfunctionstep.lo `test -f 'windowfunctionstep.cpp' || echo '$(srcdir)/'`windowfunctionstep.cpp - mostlyclean-libtool: -rm -f *.lo diff --git a/dbcon/joblist/aggregatefilterstep.cpp b/dbcon/joblist/aggregatefilterstep.cpp new file mode 100644 index 00000000..4b10f3f0 --- /dev/null +++ b/dbcon/joblist/aggregatefilterstep.cpp @@ -0,0 +1,714 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/***************************************************************************** + * $Id: aggregatefilterstep.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + ****************************************************************************/ + +#include +#include +#include +#include +#include +using namespace std; + +#include "jobstep.h" +#include "datalist.h" +#include "calpontsystemcatalog.h" +#include "simplecolumn.h" +#include "aggregator.h" +using namespace execplan; + +#include + +/** Debug macro */ +#define AF_DEBUG 0 +#if AF_DEBUG +#define AFDEBUG std::cout +#else +#define AFDEBUG if (false) std::cout +#endif + +namespace joblist { +const unsigned DEFAULT_NUM_THREADS = 4; +const uint64_t INSERT_VEC_SIZE = 4096; + +struct AFRunner { + AggregateFilterStep *step; + + AFRunner(AggregateFilterStep *s) : step(s) + { } + + void operator()() { + try { + step->doAggFilter(); + } + catch (exception &e) { + cout << "AggregateFilterStep: doAggFilter caught: " << e.what() << endl; + catchHandler(e.what()); +// throw; + } + catch (...) { + string msg("AggregateFilterStep doAggFilter caught something not an exception!"); + cout << msg << endl; + catchHandler(msg); +// throw; + } + } +}; + +template +class ThreadedAggFilter +{ +public: + typedef vector > FilterVec; + + ThreadedAggFilter(AggregateFilterStep *ag, uint8_t threadID, FilterVec& f) : + fAggFilter(ag), fThreadID(threadID), fFilters(f) { } + + void operator()() + { + try { + fAggFilter->doThreadedAggFilter(fThreadID, fFilters); + } + catch (exception &e) { + cout << "AggregateFilterStep: doThreadedAggFilter caught: " << e.what() << endl; + catchHandler(e.what()); + } + catch (...) { + string msg("AggregateFilterStep doThreadedAggFilter caught something not an exception!"); + cout << msg << endl; + catchHandler(msg); + } + } + +private: + AggregateFilterStep *fAggFilter; + uint8_t fThreadID; + FilterVec fFilters; +}; + +AggregateFilterStep::AggregateFilterStep(const JobStepAssociation &in, + const JobStepAssociation &out, + const std::string& functionName, + const execplan::CalpontSelectExecutionPlan::ReturnedColumnList groupByCols, + execplan::CalpontSelectExecutionPlan::ReturnedColumnList aggCols, + execplan::SRCP aggParam, + execplan::CalpontSystemCatalog::OID tableOID, + uint32_t sessionID, + uint32_t txnId, + uint32_t verId, + uint16_t stepID, + uint32_t statementID, + ResourceManager& rm ) : JobStep(), + fInJSA(in), + fOutJSA(out), + fFunctionName(functionName), + fGroupByCols(groupByCols), + fAggCols(aggCols), + fAggParam(aggParam), + fTableOID(tableOID), + fSessionID(sessionID), + fTxnID(txnId), + fVerID(verId), + fStepID(stepID), + fStatementID(statementID), + fHashLen(0), + fDataLen(0), + fRm(rm), + fFifoRowCount(0) +{ + fCsc = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID); + idbassert(fInJSA.outSize() == 1); + idbassert(fOutJSA.outSize() == 1); + initialize(); +} + +AggregateFilterStep::~AggregateFilterStep() +{ + //pthread_mutex_destroy(&fFifoMutex); +} + +void AggregateFilterStep::join() +{ + runner->join(); +} + +const string AggregateFilterStep::toString() const +{ + DataList_t* dl = fOutJSA.outAt(0)->dataList(); + ostringstream oss; + oss << "AggregateFilterStep ses: " << fSessionID << " txn:" << fTxnID << " ver:" << fVerID; + oss << " st:" << stepId() << " tb:" << fTableOID; + oss << " (0x" << hex << (ptrdiff_t)dl << dec << "[" << AnyDataList::dlType(dl) << "])"; + oss << " in:"; + for (unsigned i = 0; i < fInJSA.outSize(); i++) + { + oss << fInJSA.outAt(i); + } + oss << "Function Name: " << fFunctionName << endl; + oss << "Group by Cols: " << *(fGroupByCols[0]) << endl; + oss << "Project cols: " << *(fAggCols[0]) << endl; + + return oss.str(); +} + +void AggregateFilterStep::outputCol(const execplan::CalpontSystemCatalog::OID& outputCol) +{ + fOutputCol = outputCol; + MetaDataVec::iterator it; + for (it = fGroupByMetas.begin(); it != fGroupByMetas.end(); it++) + { + if (it->colType.columnOID == fOutputCol) + fOutputMeta = (*it); + } + // only support output column is on group by list + assert (fOutputMeta.startPos < fHashLen); +} + +void AggregateFilterStep::run() +{ + if (traceOn()) + { + syslogStartStep(16, + string("AggregateFilterStep")); + } + runner.reset(new boost::thread(AFRunner(this))); +} + +void AggregateFilterStep::initialize() +{ + // set hashLen, dataLen and metadata for aggCols, outputCol and aggParam + CalpontSelectExecutionPlan::ReturnedColumnList::const_iterator gbIt; + CalpontSelectExecutionPlan::ReturnedColumnList::const_iterator aggIt; + + SRCP srcp; + MetaData md; + SimpleColumn* sc; + + for (gbIt = fGroupByCols.begin(); gbIt != fGroupByCols.end(); gbIt++) + { + sc = dynamic_cast(gbIt->get()); + if (sc == 0) + throw logic_error ("non-simple group by column is not supported."); + md.colType = fCsc->colType(sc->oid()); + roundColType(md.colType); + + md.startPos = fHashLen; + fGroupByMetas.push_back(md); + fHashLen += md.colType.colWidth; + } + + for (aggIt = fAggCols.begin(); aggIt != fAggCols.end(); aggIt++) + { + sc = dynamic_cast(aggIt->get()); + if (sc == 0) + throw logic_error ("aggregate projected columns should be simple columns"); + md.colType = fCsc->colType(sc->oid()); + roundColType(md.colType); + md.startPos = fHashLen + fDataLen; + fAggMetas.push_back(md); + fDataLen += md.colType.colWidth; + } + + // set fAggOp according to functionName + boost::algorithm::to_upper(fFunctionName); + if (fFunctionName == "SUM") + fOp = Aggregator::SUM; + else if (fFunctionName == "COUNT") + fOp = Aggregator::COUNT; + else if (fFunctionName == "AVG") + fOp = Aggregator::AVG; + else if (fFunctionName == "MIN") + fOp = Aggregator::MIN; + else if (fFunctionName == "MAX") + fOp = Aggregator::MAX; + + AFDEBUG << "hashLen=" << fHashLen << " dataLen=" << fDataLen << endl; + //pthread_mutex_init(&fFifoMutex, NULL); +} + +void AggregateFilterStep::doAggFilter() +{ + TupleBucketDataList *inDL = 0; + +try +{ + if (0 < fInJSA.status() ) + { + fOutJSA.status(fInJSA.status()); + } + else + { + inDL = dynamic_cast (fInJSA.outAt(0)->tupleBucketDL()); + if (!inDL) + throw logic_error("AggregateFilter::input is not TupleBucketDataList"); + + // @note only cover one column aggregate function (int and string type) + // @todo more complex logic to decide result type for expression. + idbassert(fAggMetas.size() == 1); + std::vector runners; + int type = -1; + switch (fOp) + { + case Aggregator::SUM: + case Aggregator::COUNT: + type = INT64; + break; + case Aggregator::MIN: + case Aggregator::MAX: + { + switch (fAggMetas[0].colType.colDataType) + { + case CalpontSystemCatalog::BIT: + case CalpontSystemCatalog::TINYINT: + case CalpontSystemCatalog::SMALLINT: + case CalpontSystemCatalog::MEDINT: + case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::BIGINT: + case CalpontSystemCatalog::DATE: + case CalpontSystemCatalog::DATETIME: + case CalpontSystemCatalog::DECIMAL: + type = INT64; + break; + case CalpontSystemCatalog::CHAR: + case CalpontSystemCatalog::VARCHAR: + case CalpontSystemCatalog::BLOB: + case CalpontSystemCatalog::CLOB: + if (fAggMetas[0].colType.colWidth > 8) + type = STRING; + else + type = INT64; + break; + case CalpontSystemCatalog::DOUBLE: + type = DOUBLE; + break; + case CalpontSystemCatalog::FLOAT: + type = FLOAT; + break; + default: + type = INT64; + break; + } + } + case Aggregator::AVG: + switch (fAggMetas[0].colType.colDataType) + { + case CalpontSystemCatalog::FLOAT: + type = FLOAT; + break; + default: + type = DOUBLE; + break; + } + break; + } + + vector::iterator filterIt = fFilters.begin(); + + switch (type) + { + case INT64: + { + vector > filters; + for (; filterIt != fFilters.end(); filterIt++) + filters.push_back(TFilter (filterIt->cop, filterIt->intVal)); + startThreads (filters); + break; + } + case STRING: + { + vector > filters; + for (; filterIt != fFilters.end(); filterIt++) + filters.push_back(TFilter (filterIt->cop, filterIt->strVal)); + startThreads (filters); + break; + } + case FLOAT: + { + vector > filters; + for (; filterIt != fFilters.end(); filterIt++) + filters.push_back(TFilter (filterIt->cop, (float)filterIt->intVal)); + startThreads (filters); + break; + } + case DOUBLE: + { + vector > filters; + for (; filterIt != fFilters.end(); filterIt++) + filters.push_back(TFilter (filterIt->cop, (double)filterIt->intVal)); + startThreads (filters); + break; + } + default: + throw logic_error("not supported result type"); + } + } // else fInJSA.status == 0 +} //try +catch(const exception& ex) +{ + catchHandler(ex.what()); + fOutJSA.status(logging::aggregateFilterStepErr); +} +catch(...) +{ + string msg("AggregateFilterStep: doAggFilter caught unknown exception"); + catchHandler(msg); + fOutJSA.status(logging::aggregateFilterStepErr); +} + + // result endofinput + DataList_t *outDL = fOutJSA.outAt(0)->dataList(); + StrDataList *outStrDL = fOutJSA.outAt(0)->strDataList(); + FifoDataList *fifo = fOutJSA.outAt(0)->fifoDL(); + StringFifoDataList *strFifo = fOutJSA.outAt(0)->stringDL(); + uint64_t totalSize; + + // @todo check double, float? + if (fifo) + { + fifo->endOfInput(); + totalSize = fFifoRowCount; + fifo->totalSize(totalSize); + } + else if (strFifo) + { + strFifo->endOfInput(); + totalSize = fFifoRowCount; + strFifo->totalSize(totalSize); + } + else if (outDL) + { + outDL->endOfInput(); + totalSize = outDL->totalSize(); + } + else // assume outStrDL + { + outStrDL->endOfInput(); + totalSize = outStrDL->totalSize(); + } + + dlTimes.setLastReadTime(); + dlTimes.setLastInsertTime(); + dlTimes.setEndOfInputTime(); + + if (fTableOID >= 3000 && traceOn()) + { + //...Print job step completion information + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + timeString[strlen(timeString)-1] = '\0'; + + ostringstream logStr; + logStr << "ses:" << fSessionID << " st: " << fStepID << + " finished at " << timeString << + "; output size-" << totalSize << endl << + "\t1st Insert " << dlTimes.FirstInsertTimeString() << " " << + "1st read " << dlTimes.FirstReadTimeString() << " " << + "last read " << dlTimes.LastReadTimeString() << " " << + "EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime())<< "s" << endl; + + logEnd(logStr.str().c_str()); + + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstInsertTime(), // first datalist write + dlTimes.EndOfInputTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + 0, // blocked datalist input + 0); // blocked datalist output + } +} + +template +void AggregateFilterStep::startThreads(vector >& fv) +{ + fNumThreads = fRm.getTwNumThreads(); + + std::vector > runners; + boost::shared_ptr runner; + uint8_t i; + for (i = 0; i < fNumThreads; i++) + { + runner.reset(new boost::thread(ThreadedAggFilter(this, i, fv))); + runners.push_back(runner); + } + for (i = 0; i < fNumThreads; i++) + runners[i]->join(); +} + +template +void AggregateFilterStep::doThreadedAggFilter(uint8_t threadID, vector >& filters) +{ + TupleBucketDataList *inDL = dynamic_cast (fInJSA.outAt(0)->tupleBucketDL()); + TupleHasher tupleHash(fHashLen); + TupleComparator tupleComp(fHashLen); + typename AggHashMap::SHMP shmp; + shmp.reset(new typename AggHashMap::TupleHashMap(1, tupleHash, tupleComp)); + vector vt; + + // avg needs to call non-template function to perform div in aggregator + typename AggHashMap::SHMP shmp_avg; + vector > fs; + + + if (fOp == Aggregator::AVG) + { + vector::iterator filterIt = fFilters.begin(); + shmp_avg.reset(new typename AggHashMap::TupleHashMap(1, tupleHash, tupleComp)); + for (; filterIt != fFilters.end(); filterIt++) + fs.push_back(TFilter (filterIt->cop, (double)filterIt->intVal)); + } + + typename AggHashMap::TupleHMIter iter; + typename AggHashMap::TupleHMIter iter_avg; + + // to profile accurate time + if (dlTimes.FirstReadTime().tv_sec==0) + { + uint64_t totalSize = inDL->totalSize(); + AFDEBUG << "TotalSize= " << totalSize << endl; + dlTimes.setFirstReadTime(); + } + + Aggregator *aggregator = new Aggregator (fOp, fAggMetas, fAggParam, fHashLen, 0); + for (uint64_t i = threadID; i < inDL->bucketCount(); i += fNumThreads) + { + aggregator->bucketID(i); + if (fOp == Aggregator::AVG) + { + aggregator->doAggregate_AVG (shmp_avg, inDL, vt); + doFilter(shmp_avg, fs, vt); + + // clean up hashmap memory + for (iter_avg = shmp_avg->begin(); iter_avg != shmp_avg->end(); iter++) + delete [] iter_avg->first; + shmp_avg->clear(); + vt.clear(); + } + else + { + aggregator->doAggregate (shmp, inDL, vt); + doFilter(shmp, filters, vt); + + // clean up memory + for (iter = shmp->begin(); iter != shmp->end(); ++iter) + delete [] iter->first; + shmp->clear(); + vt.clear(); + } + } + delete aggregator; +} + +template +void AggregateFilterStep::doFilter (typename AggHashMap::SHMP& shmp, + vector >& filters, vector &vt) +{ + // loop through hashtable and do filter + typename AggHashMap::TupleHMIter hashIt = shmp->begin(); + typename vector >::iterator it; + DataList_t *outDL = fOutJSA.outAt(0)->dataList(); + StrDataList *outStrDL = fOutJSA.outAt(0)->strDataList(); + FifoDataList *fifo = fOutJSA.outAt(0)->fifoDL(); + StringFifoDataList *strFifo = fOutJSA.outAt(0)->stringDL(); + + bool ret = false; + + // erase rids list of unqualified groups from the map + for (; hashIt != shmp->end(); ++hashIt) + { + for (it = filters.begin(); it != filters.end(); it++) + { + ret = compare(hashIt->second, it->val, it->cop); + if (!ret) + { + hashIt->first[fHashLen] = DROP; + break; + } + } + } + + if (fifo) + outputFifo(shmp, fifo, vt); + else if (strFifo) + outputFifo(shmp, strFifo, vt); + else if (outDL) + output(shmp, outDL, vt); + else // assume outStrDL + output(shmp, outStrDL, vt); +} + +template +void AggregateFilterStep::output(typename AggHashMap::SHMP& shmp, + DataList *outDL, vector &vt) +{ + // @todo may need to separate the function so don't check type every time + element_t e; + vector v; + vector::iterator it; + typename AggHashMap::TupleHMIter hashIt; + + if (dlTimes.FirstInsertTime().tv_sec==0) + dlTimes.setFirstInsertTime(); + + for (it = vt.begin(); it != vt.end(); ++it) + { + if (it->second[fHashLen] == KEEP) + { + switch (fOutputMeta.colType.colDataType) + { + case execplan::CalpontSystemCatalog::BIGINT: + case execplan::CalpontSystemCatalog::INT: { + ElementType *et = (ElementType *) &e; + memset(&et->second, 0, 8); + memcpy(&et->second, it->second+fOutputMeta.startPos, fOutputMeta.colType.colWidth); + break; + } + default: + throw logic_error("AggregateFilterStep::output unsupported output column type"); + } + e.first = it->first; + v.push_back(e); + AFDEBUG << "output " << e.first << "/" << e.second << std::endl; + if (v.size() >= INSERT_VEC_SIZE) + { + outDL->insert(v); + v.clear(); + } + } + } + + if (v.size() != 0) { + outDL->insert(v); + v.clear(); + } +} + +template +void AggregateFilterStep::outputFifo(typename AggHashMap::SHMP& shmp, + FIFO *outDL, vector &vt) +{ + // @todo may need to separate the function so don't check type every time + element_t rw; + vector::iterator it; + typename AggHashMap::TupleHMIter hashIt; + + if (dlTimes.FirstInsertTime().tv_sec==0) + dlTimes.setFirstInsertTime(); + + for (it = vt.begin(); it != vt.end(); ++it) + { + if (it->second[fHashLen] == KEEP) + { + switch (fOutputMeta.colType.colDataType) + { + case execplan::CalpontSystemCatalog::BIGINT: + case execplan::CalpontSystemCatalog::INT: + memset(&rw.et[rw.count].second, 0, 8); + memcpy(&rw.et[rw.count].second, it->second+fOutputMeta.startPos, fOutputMeta.colType.colWidth); + break; + default: + throw logic_error("AggregateFilterStep::output unsupported output column type"); + } + + rw.et[rw.count].first = it->first; + AFDEBUG << "output " << rw.et[rw.count].first << "/" << rw.et[rw.count].second << std::endl; + rw.count++; + if (rw.count == rw.ElementsPerGroup) + { + fFifoMutex.lock(); //pthread_mutex_lock(&fFifoMutex); + outDL->insert(rw); + fFifoRowCount += rw.count; + fFifoMutex.unlock(); //pthread_mutex_unlock(&fFifoMutex); + rw.count = 0; + } + } + } + + if (rw.count > 0) + { + fFifoMutex.lock(); //pthread_mutex_lock(&fFifoMutex); + outDL->insert(rw); + fFifoRowCount += rw.count; + fFifoMutex.unlock(); //pthread_mutex_unlock(&fFifoMutex); + } +} + +template +inline bool AggregateFilterStep::compare(result_t& val1, result_t& val2, int8_t COP) +{ + switch(COP) { + case COMPARE_NIL: + return false; + case COMPARE_LT: + return (val1 < val2 ? true : false); + case COMPARE_EQ: + return (val1 == val2 ? true : false); + case COMPARE_LE: + return (val1 <= val2 ? true : false); + case COMPARE_GT: + return (val1 > val2 ? true : false); + case COMPARE_NE: + return (val1 != val2 ? true : false); + case COMPARE_GE: + return (val1 >= val2 ? true : false); + default: + return false; + } +} + +void AggregateFilterStep::addFilter(int8_t COP, int64_t value, bool isNorm) +{ + FilterArg arg; + arg.cop = COP; + arg.intVal = value; + arg.isNorm = isNorm; + fFilters.push_back(arg); + AFDEBUG << "addFilter: COP=" << (uint)COP << " VAL=" << value << std::endl; +} + +void AggregateFilterStep::addFilter(int8_t COP, string value, bool isNorm) +{ + FilterArg arg; + arg.cop = COP; + arg.strVal = value; + arg.isNorm = isNorm; + fFilters.push_back(arg); + AFDEBUG << "addFilter: COP=" << (uint)COP << " VAL=" << value << std::endl; +} + +void AggregateFilterStep::roundColType(CalpontSystemCatalog::ColType& ct) +{ + if ( ct.colDataType == CalpontSystemCatalog::VARCHAR ) + ct.colWidth++; + //If this is a dictionary column, fudge the numbers... + if (ct.colWidth > 8 ) + ct.colWidth = 8; + + //Round colWidth up + if (ct.colWidth == 3) + ct.colWidth = 4; + else if (ct.colWidth == 5 || ct.colWidth == 6 || ct.colWidth == 7) + ct.colWidth = 8; +} + +}; //namespace diff --git a/dbcon/joblist/aggregator.cpp b/dbcon/joblist/aggregator.cpp new file mode 100644 index 00000000..952cf79e --- /dev/null +++ b/dbcon/joblist/aggregator.cpp @@ -0,0 +1,230 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/***************************************************************************** + * $Id: aggregator.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + ****************************************************************************/ +#include +#include +using namespace std; + +#include "aggregator.h" +#include "jobstep.h" +using namespace execplan; + +/** Debug macro */ +#define A_DEBUG 0 +#define A_DEBUG_VERBAL 0 +#if A_DEBUG +#define ADEBUG std::cout +#else +#define ADEBUG if (false) std::cout +#endif + +namespace joblist { + +Aggregator::Aggregator( + AggOp aggOp, + MetaDataVec& aggCols, + execplan::SRCP aggParam, + uint32_t hashLen, + uint64_t bucketID): + fAggOp (aggOp), + fAggCols (aggCols), + fAggParam (aggParam), + fHashLen (hashLen), + fBucketID (bucketID) +{ +} + +Aggregator::~Aggregator() +{ +} + +template +void Aggregator::doAggregate(typename AggHashMap::SHMP& shmp, TupleBucketDataList *inDL, vector &vt) +{ + bool ret; + uint64_t it = inDL->getIterator(fBucketID); + TupleType tt, ttv; + result_t r; + typename AggHashMap::TupleHMIter hashIt; + + vt.reserve(inDL->size(fBucketID)); + while ((ret=inDL->next(fBucketID, it, &tt))) + { + ttv.first = tt.first; + hashIt = shmp->find(tt.second); + + // if group not exist, insert the new group to the hashmap. allocate + // hashstr to be used by both the tuple inserted to the vector, and + // the map key. + if (hashIt == shmp->end()) + { + getAggResult(tt, r); + //cout << "VALUE: " << r << endl; + ttv.second = new char[fHashLen+1]; + memcpy(ttv.second, tt.second, fHashLen); + ttv.second[fHashLen] = KEEP; + vt.push_back(ttv); + shmp->insert(std::pair (ttv.second, r)); + } + + // if group exist, update the group result and insert tuple to vector. + // no memory allocation is taken place. + else + { + updateAggResult(tt, hashIt->second); + ttv.second = hashIt->first; + vt.push_back(ttv); + } + } + +#if A_DEBUG + uint64_t size = inDL->size(fBucketID); + vector::iterator ridit; + if (shmp->size() > 0) + { + ADEBUG << "bucket " << fBucketID << " size=" << size + << " hashtable size= " << shmp->size() + << " vector size = " << vt.size() << std::endl; + } +#if A_DEBUG_VERBAL + typename AggHashMap::TupleHMIter iter = shmp->begin(); + for (; iter != shmp->end(); iter++) + { + ADEBUG << "group result=" << (*iter).second << endl; + } +#endif +#endif +} + +void Aggregator::doAggregate_AVG( AggHashMap::SHMP& shmp, TupleBucketDataList *inDL, vector &vt) +{ + bool ret; + uint64_t it = inDL->getIterator(fBucketID); + TupleType tt, ttv; + double r; + AggHashMap::TupleHMIter hashIt; + uint64_t *counter = 0; + uint64_t ONE = 1; + + vt.reserve(inDL->size(fBucketID)); + while ((ret=inDL->next(fBucketID, it, &tt))) + { + ttv.first = tt.first; + hashIt = shmp->find(tt.second); + + if (hashIt == shmp->end()) + { + getAggResult(tt, r); + // the last 8 bytes are for counter. the counter is initialized to 1 here. + ttv.second = new char[fHashLen + 1 + 8]; + memcpy(ttv.second, tt.second, fHashLen); + ttv.second[fHashLen] = KEEP; + memcpy(ttv.second+fHashLen+1, &ONE, 8); + vt.push_back(ttv); + shmp->insert(std::pair (ttv.second, r)); + } + else + { + updateAggResult(tt, hashIt->second); + counter = reinterpret_cast(hashIt->first+fHashLen+1); + //RJD: This line used to be: '*counter++'. This doesn't do anything because the binding is + // *counter; counter++. Maybe it's supposed to be '(*counter)++'? But that will definitly change the + // answer to some queries. If it's supposed to be *counter; counter++ then this line and the + // previous line are superfluous. + (*counter)++; + ttv.second = hashIt->first; + vt.push_back(ttv); + } + } + + // calculate average + for (hashIt = shmp->begin(); hashIt != shmp->end(); hashIt++) + { + counter = reinterpret_cast(hashIt->first+fHashLen+1); + hashIt->second = hashIt->second / *counter; + } +} + +template +void Aggregator::getAggResult(TupleType& tt, result_t& result) +{ + if (fAggOp == COUNT) + { + result = 1; + return; + } + execplan::CalpontSystemCatalog::ColType& colType = fAggCols[0].colType; + memcpy(&result, tt.second+fAggCols[0].startPos, colType.colWidth); +} + +template +void Aggregator::updateAggResult(TupleType& tt, result_t& result) +{ + result_t val; + switch(fAggOp) + { + case SUM: + case AVG: + getAggResult(tt, val); + result += val; + return; + case COUNT: + result += 1; + return; + case MIN: + { + result_t r; + getAggResult(tt, r); + if (r < result) + result = r; + return; + } + case MAX: + { + result_t r; + getAggResult(tt, r); + if (r > result) + result = r; + return; + } + default: + throw logic_error("not handled aggregate function"); + } +} + +template +void Aggregator::doAggregate + (AggHashMap::SHMP& shmp, TupleBucketDataList *inDL, vector &vt); + +template +void Aggregator::doAggregate + (AggHashMap::SHMP& shmp, TupleBucketDataList *inDL, vector &vt); + +template +void Aggregator::doAggregate + (AggHashMap::SHMP& shmp, TupleBucketDataList *inDL, vector &vt); + +template +void Aggregator::doAggregate + (AggHashMap::SHMP& shmp, TupleBucketDataList *inDL, vector &vt); +} +// vim:ts=4 sw=4: + diff --git a/dbcon/joblist/aggregator.h b/dbcon/joblist/aggregator.h new file mode 100644 index 00000000..a3276a72 --- /dev/null +++ b/dbcon/joblist/aggregator.h @@ -0,0 +1,177 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/***************************************************************************** + * $Id: aggregator.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + ****************************************************************************/ + +#ifndef AGGREGATOR_H +#define AGGREGATOR_H + +/** @file */ + +#include +#include +#include +#ifdef _MSC_VER +#include +#else +#include +#endif +#include + +#include "elementtype.h" +#include "hasher.h" +#include "returnedcolumn.h" + +namespace joblist { + +/** @brief class TupleHasher + * + */ +class TupleHasher +{ +private: + utils::Hasher fHasher; + uint32_t fHashLen; + +public: + TupleHasher(uint32_t len) : fHashLen(len) {} + uint32_t operator()(const char* v) const + { + return fHasher(v, fHashLen); + } +}; + +/** @brief class TupleComparator + * + */ +class TupleComparator +{ +private: + uint32_t fCmpLen; + +public: + TupleComparator(uint32_t len) : fCmpLen(len) {} + bool operator()(const char* v1, const char *v2) const + { + return (memcmp(v1, v2, fCmpLen) == 0); + } +}; + +/** @brief struct MetaData + * + * Describe meta data of columns out of the raw data + */ +struct MetaData +{ + execplan::CalpontSystemCatalog::ColType colType; + uint32_t startPos; +}; +typedef std::vector MetaDataVec; + +/** @brief struct AggHashMap + * + * To hold template data structures + */ +template +struct AggHashMap +{ + typedef std::tr1::unordered_map TupleHashMap; + typedef typename std::tr1::unordered_map::iterator TupleHMIter; + typedef boost::shared_ptr SHMP; +}; + +/** @brief enum the bit flag to indicate a tuple qualified filter or not*/ +enum KEEP_FLAG +{ + KEEP = 0, + DROP +}; + +/** @brief class Aggregator + * + * Perform grouping and aggregate operations + */ +class Aggregator +{ +public: + + /** @brief aggregator operators */ + enum AggOp + { + COUNT = 0, + SUM, + AVG, + MIN, + MAX + }; + + /** @brief Constructor */ + Aggregator(AggOp aggOp, + MetaDataVec& aggCols, + execplan::SRCP aggParam, + uint32_t hashLen, + uint64_t bucketID); + + /** @brief Destructor */ + virtual ~Aggregator(); + + /** @brief aggregate main function + * + * @param map template hashmap reference. + * vt empty vector reference of tuple + * @output hash map with group results + * populated vector of tuple + */ + template + void doAggregate(typename AggHashMap::SHMP& map, TupleBucketDataList *inDL, std::vector &vt); + + /** @brief aggregate main function for AVG + * + * @param map double result hashmap reference + * @note because div operation is needed, this function is explicitly typed + */ + void doAggregate_AVG( AggHashMap::SHMP& map, TupleBucketDataList *inDL, std::vector &vt); + void bucketID (uint64_t bucketID) { fBucketID = bucketID;} + +private: + /** @brief constructor for completeness */ + Aggregator(); + Aggregator(const Aggregator& hj); + + /** @brief get agg function result + */ + template + void getAggResult(TupleType& tt, result_t& result); + + /** @brief update agg function result for this group + */ + template + void updateAggResult(TupleType& tt, result_t& result); + + uint8_t fAggOp; // aggregate operator + MetaDataVec fAggCols; // aggregate columns meta data + execplan::SRCP fAggParam; // aggregate parameter + uint64_t fHashLen; // hash length + uint64_t fBucketID; // bucket ID this aggregator handles +}; + +} //namespace + +#endif diff --git a/dbcon/joblist/anydatalist.cpp b/dbcon/joblist/anydatalist.cpp index a3cb2089..9694b862 100644 --- a/dbcon/joblist/anydatalist.cpp +++ b/dbcon/joblist/anydatalist.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: anydatalist.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: anydatalist.cpp 8476 2012-04-25 22:28:15Z xlou $ #include "elementtype.h" @@ -58,7 +58,7 @@ AnyDataList::DataListTypes AnyDataList::strDlType(const StrDataList* dl) //AnyDataList::DataListTypes AnyDataList::tupleDlType(const TupleDataList* dl) //{ -// if (dl == 0) return UNKNOWN_DATALIST; +// if (dl == 0) return UNKNOWN_DATALIST; // if (typeid(*dl) == typeid(TupleBucketDataList)) return TUPLEBUCKET_DATALIST; // return UNKNOWN_DATALIST; //} diff --git a/dbcon/joblist/bandeddl.h b/dbcon/joblist/bandeddl.h index a1703b8e..5f23cb96 100644 --- a/dbcon/joblist/bandeddl.h +++ b/dbcon/joblist/bandeddl.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: bandeddl.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: bandeddl.h 8476 2012-04-25 22:28:15Z xlou $ * *****************************************************************************/ -/** @file +/** @file * class XXX interface */ @@ -47,8 +47,8 @@ class BandedDL : public LargeDataList, element_t> typedef LargeDataList, element_t> base; public: - BandedDL(uint32_t numConsumers, const ResourceManager& rm); -// BandedDL(BucketDL &, uint32_t numConsumers, const ResourceManager& rm); + BandedDL(uint numConsumers, const ResourceManager& rm); +// BandedDL(BucketDL &, uint numConsumers, const ResourceManager& rm); virtual ~BandedDL(); int64_t saveBand(); @@ -73,22 +73,22 @@ class BandedDL : public LargeDataList, element_t> explicit BandedDL() { }; explicit BandedDL(const BandedDL &) { }; BandedDL & operator=(const BandedDL &) { }; - + // vars to support the WSDL-like next() fcn boost::condition nextSetLoaded; uint64_t waitingConsumers; }; template - BandedDL::BandedDL(uint32_t nc, const ResourceManager& rm) : base(nc, sizeof(uint64_t), sizeof(uint64_t), rm) + BandedDL::BandedDL(uint nc, const ResourceManager& rm) : base(nc, sizeof(uint64_t), sizeof(uint64_t), rm) { //pthread_cond_init(&nextSetLoaded, NULL); waitingConsumers = 0; } - + #if 0 template - BandedDL::BandedDL(BucketDL &b, uint32_t nc, const ResourceManager& rm) : base(nc, sizeof(uint64_t), sizeof(uint64_t), rm) + BandedDL::BandedDL(BucketDL &b, uint nc, const ResourceManager& rm) : base(nc, sizeof(uint64_t), sizeof(uint64_t), rm) { uint64_t i, it; element_t e; @@ -112,7 +112,7 @@ template template BandedDL::~BandedDL() -{ +{ //pthread_cond_destroy(&nextSetLoaded); } @@ -120,7 +120,7 @@ template int64_t BandedDL::saveBand() { int64_t ret; - + if (base::multipleProducers) base::lock(); sort(base::c->begin(), base::c->end()); @@ -132,14 +132,14 @@ int64_t BandedDL::saveBand() base::registerNewSet(); if (base::multipleProducers) base::unlock(); - + return ret; } template void BandedDL::loadBand(uint64_t band) { - + base::lock(); if (typeid(element_t) == typeid(ElementType) || typeid(element_t) == typeid(DoubleElementType)) @@ -159,7 +159,7 @@ int64_t BandedDL::bandCount() base::lock(); ret = base::setCount(); base::unlock(); - return ret; + return ret; } template @@ -216,7 +216,7 @@ the more I think they're the same thing. Not entirely sure yet though. */ guarantee the caller will be wakened when the next set is loaded. It could get skipped. It won't happen realistically, but it exists... */ - // signifies the caller is at the end of the loaded set, + // signifies the caller is at the end of the loaded set, // but there are more sets if (ret == false && (base::loadedSet < base::setCount - 1)) { @@ -245,7 +245,7 @@ the more I think they're the same thing. Not entirely sure yet though. */ if (locked) base::unlock(); - return ret; + return ret; } @@ -350,7 +350,7 @@ uint64_t BandedDL::totalSize() base::lock(); ret = base::totalSize(); base::unlock(); - + return ret; } diff --git a/dbcon/joblist/batchprimitiveprocessor-jl.cpp b/dbcon/joblist/batchprimitiveprocessor-jl.cpp index d9595025..805e403c 100644 --- a/dbcon/joblist/batchprimitiveprocessor-jl.cpp +++ b/dbcon/joblist/batchprimitiveprocessor-jl.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: batchprimitiveprocessor-jl.cpp 9705 2013-07-17 20:06:07Z pleblanc $ +// $Id: batchprimitiveprocessor-jl.cpp 8775 2012-08-01 16:12:11Z dhall $ // C++ Implementation: batchprimitiveprocessor // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -36,10 +36,6 @@ #include using namespace std; -#include -#include -namespace bu=boost::uuids; - #include "calpontsystemcatalog.h" using namespace execplan; @@ -74,46 +70,41 @@ BatchPrimitiveProcessorJL::BatchPrimitiveProcessorJL(const ResourceManager& rm) sendTupleJoinRowGroupData(false), bop(BOP_AND), forHJ(false), - threadCount(1), fJoinerChunkSize(rm.getJlJoinerChunkSize()), hasSmallOuterJoin(false), _priority(1) { PMJoinerCount = 0; - uuid = bu::nil_generator()(); } BatchPrimitiveProcessorJL::~BatchPrimitiveProcessorJL() { } -void BatchPrimitiveProcessorJL::addFilterStep(const pColScanStep &scan, vector lastScannedLBID) +void BatchPrimitiveProcessorJL::addFilterStep(const pColScanStep &scan) { SCommand cc; tableOID = scan.tableOid(); - cc.reset(new ColumnCommandJL(scan, lastScannedLBID)); + cc.reset(new ColumnCommandJL(scan)); cc->setBatchPrimitiveProcessor(this); - cc->setQueryUuid(scan.queryUuid()); - cc->setStepUuid(uuid); filterSteps.push_back(cc); filterCount++; _hasScan = true; idbassert(sessionID == scan.sessionId()); } -void BatchPrimitiveProcessorJL::addFilterStep(const PseudoColStep &pcs) +void BatchPrimitiveProcessorJL::addFilterStep(const pColScanStep &scan, vector lastScannedLBID) { - SCommand cc; + SCommand cc; - tableOID = pcs.tableOid(); - cc.reset(new PseudoCCJL(pcs)); + tableOID = scan.tableOid(); + cc.reset(new ColumnCommandJL(scan, lastScannedLBID)); cc->setBatchPrimitiveProcessor(this); - cc->setQueryUuid(pcs.queryUuid()); - cc->setStepUuid(uuid); filterSteps.push_back(cc); filterCount++; - idbassert(sessionID == pcs.sessionId()); + _hasScan = true; + idbassert(sessionID == scan.sessionId()); } void BatchPrimitiveProcessorJL::addFilterStep(const pColStep &step) @@ -123,8 +114,6 @@ void BatchPrimitiveProcessorJL::addFilterStep(const pColStep &step) tableOID = step.tableOid(); cc.reset(new ColumnCommandJL(step)); cc->setBatchPrimitiveProcessor(this); - cc->setQueryUuid(step.queryUuid()); - cc->setStepUuid(uuid); filterSteps.push_back(cc); filterCount++; idbassert(sessionID == step.sessionId()); @@ -142,8 +131,6 @@ void BatchPrimitiveProcessorJL::addFilterStep(const pDictionaryStep &step) } cc.reset(new DictStepJL(step)); cc->setBatchPrimitiveProcessor(this); - cc->setQueryUuid(step.queryUuid()); - cc->setStepUuid(uuid); filterSteps.push_back(cc); filterCount++; needStrValues = true; @@ -158,29 +145,11 @@ void BatchPrimitiveProcessorJL::addFilterStep(const FilterStep& step) tableOID = step.tableOid(); cc.reset(new FilterCommandJL(step)); cc->setBatchPrimitiveProcessor(this); - cc->setQueryUuid(step.queryUuid()); - cc->setStepUuid(uuid); filterSteps.push_back(cc); filterCount++; idbassert(sessionID == step.sessionId()); } -void BatchPrimitiveProcessorJL::addProjectStep(const PseudoColStep &step) -{ - SCommand cc; - - cc.reset(new PseudoCCJL(step)); - cc->setBatchPrimitiveProcessor(this); - cc->setTupleKey(step.tupleId()); - cc->setQueryUuid(step.queryUuid()); - cc->setStepUuid(uuid); - projectSteps.push_back(cc); - colWidths.push_back(cc->getWidth()); - tupleLength += cc->getWidth(); - projectCount++; - idbassert(sessionID == step.sessionId()); -} - void BatchPrimitiveProcessorJL::addProjectStep(const pColStep &step) { SCommand cc; @@ -188,8 +157,6 @@ void BatchPrimitiveProcessorJL::addProjectStep(const pColStep &step) cc.reset(new ColumnCommandJL(step)); cc->setBatchPrimitiveProcessor(this); cc->setTupleKey(step.tupleId()); - cc->setQueryUuid(step.queryUuid()); - cc->setStepUuid(uuid); projectSteps.push_back(cc); colWidths.push_back(cc->getWidth()); tupleLength += cc->getWidth(); @@ -204,8 +171,6 @@ void BatchPrimitiveProcessorJL::addProjectStep(const PassThruStep &step) cc.reset(new PassThruCommandJL(step)); cc->setBatchPrimitiveProcessor(this); cc->setTupleKey(step.tupleId()); - cc->setQueryUuid(step.queryUuid()); - cc->setStepUuid(uuid); projectSteps.push_back(cc); colWidths.push_back(cc->getWidth()); tupleLength += cc->getWidth(); @@ -223,8 +188,6 @@ void BatchPrimitiveProcessorJL::addProjectStep(const pColStep &col, cc.reset(new RTSCommandJL(col, dict)); cc->setBatchPrimitiveProcessor(this); cc->setTupleKey(dict.tupleId()); - cc->setQueryUuid(col.queryUuid()); - cc->setStepUuid(uuid); projectSteps.push_back(cc); colWidths.push_back(cc->getWidth()); tupleLength += cc->getWidth(); @@ -234,7 +197,7 @@ void BatchPrimitiveProcessorJL::addProjectStep(const pColStep &col, idbassert(sessionID == dict.sessionId()); } -void BatchPrimitiveProcessorJL::addProjectStep(const PassThruStep &p, +void BatchPrimitiveProcessorJL::addProjectStep(const PassThruStep &p, const pDictionaryStep &dict) { SCommand cc; @@ -242,8 +205,6 @@ void BatchPrimitiveProcessorJL::addProjectStep(const PassThruStep &p, cc.reset(new RTSCommandJL(p, dict)); cc->setBatchPrimitiveProcessor(this); cc->setTupleKey(dict.tupleId()); - cc->setQueryUuid(p.queryUuid()); - cc->setStepUuid(uuid); projectSteps.push_back(cc); colWidths.push_back(cc->getWidth()); tupleLength += cc->getWidth(); @@ -263,11 +224,11 @@ void BatchPrimitiveProcessorJL::addDeliveryStep(const DeliveryStep &ds) { idbassert(sessionID == ds.sessionId()); - uint32_t i; + uint i; templateTB = ds.fEmptyTableBand; tableOID = ds.fTableOID; - + tableColumnCount = templateTB.getColumnCount(); idbassert(tableColumnCount > 0); tablePositions.reset(new int[tableColumnCount]); @@ -276,7 +237,7 @@ void BatchPrimitiveProcessorJL::addDeliveryStep(const DeliveryStep &ds) idbassert(projectCount <= projectSteps.size()); - /* In theory, tablePositions maps a column's table position to a projection step + /* In theory, tablePositions maps a column's table position to a projection step -1 means it's a null column */ CalpontSystemCatalog::OID oid; int idx; @@ -305,9 +266,9 @@ void BatchPrimitiveProcessorJL::addDeliveryStep(const DeliveryStep &ds) } #endif -void BatchPrimitiveProcessorJL::addElementType(const ElementType &et, uint32_t dbroot) +void BatchPrimitiveProcessorJL::addElementType(const ElementType &et, uint dbroot) { - uint32_t i; + uint i; // rowCounter++; if (needToSetLBID) { @@ -335,10 +296,9 @@ void BatchPrimitiveProcessorJL::addElementType(const ElementType &et, uint32_t d idbassert(ridCount <= 8192); } -#if 0 void BatchPrimitiveProcessorJL::setRowGroupData(const rowgroup::RowGroup &rg) { - uint32_t i; + uint i; rowgroup::Row r; inputRG.setData(rg.getData()); @@ -357,9 +317,7 @@ void BatchPrimitiveProcessorJL::setRowGroupData(const rowgroup::RowGroup &rg) } } -#endif - -void BatchPrimitiveProcessorJL::addElementType(const StringElementType &et, uint32_t dbroot) +void BatchPrimitiveProcessorJL::addElementType(const StringElementType &et, uint dbroot) { if (filterCount == 0) throw logic_error("BPPJL::addElementType(StringElementType): doesn't work without filter steps yet"); @@ -393,7 +351,7 @@ void BatchPrimitiveProcessorJL::getElementTypes(ByteStream &in, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks, uint16_t *preJoinRidCount) const { - uint32_t i; + uint i; uint16_t l_count; uint64_t l_baseRid; uint16_t *rids; @@ -435,7 +393,7 @@ void BatchPrimitiveProcessorJL::getElementTypes(ByteStream &in, rids = (uint16_t *) buf; vals = (uint64_t *) (buf + (l_count << 1)); - idbassert(in.length() > (uint32_t) ((l_count << 1) + (l_count << 3)) ); + idbassert(in.length() > (uint) ((l_count << 1) + (l_count << 3)) ); in.advance((l_count << 1) + (l_count << 3)); for (i = 0; i < l_count; ++i) { @@ -460,7 +418,7 @@ void BatchPrimitiveProcessorJL::getElementTypes(ByteStream &in, in >> *cachedIO; in >> *physIO; in >> *touchedBlocks; -// cout << "ET: got physIO=" << (int) *physIO << " cachedIO=" << +// cout << "ET: got physIO=" << (int) *physIO << " cachedIO=" << // (int) *cachedIO << " touchedBlocks=" << (int) *touchedBlocks << endl; idbassert(in.length() == 0); } @@ -485,7 +443,7 @@ void BatchPrimitiveProcessorJL::getStringElementTypes(ByteStream &in, vector *out, bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks) const { - uint32_t i; + uint i; uint16_t l_count; uint64_t *l_absRids; uint64_t tmp64; @@ -521,7 +479,7 @@ void BatchPrimitiveProcessorJL::getStringElementTypes(ByteStream &in, in >> *cachedIO; in >> *physIO; in >> *touchedBlocks; -// cout << "SET: got physIO=" << (int) *physIO << " cachedIO=" << +// cout << "SET: got physIO=" << (int) *physIO << " cachedIO=" << // (int) *cachedIO << " touchedBlocks=" << (int) *touchedBlocks << endl; idbassert(in.length() == 0); } @@ -535,7 +493,7 @@ void BatchPrimitiveProcessorJL::getTuples(messageqcpp::ByteStream &in, std::vector *out, bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks) const { - uint32_t i, j, pos, len; + uint i, j, pos, len; uint16_t l_rowCount; uint64_t l_baseRid; uint16_t *l_relRids; @@ -578,7 +536,7 @@ void BatchPrimitiveProcessorJL::getTuples(messageqcpp::ByteStream &in, absRids[i] = l_relRids[i] + l_baseRid; in.advance(l_rowCount << 1); } - + /* Set up pointers to the column data */ pos = 0; buf = in.buf(); @@ -610,7 +568,7 @@ void BatchPrimitiveProcessorJL::getTuples(messageqcpp::ByteStream &in, } else { switch(colWidths[j]) { - case 8: + case 8: *((uint64_t *) &(*out)[i].second[pos]) = *((uint64_t *) columnData[j]); columnData[j] += 8; pos += 8; @@ -648,7 +606,7 @@ void BatchPrimitiveProcessorJL::getTuples(messageqcpp::ByteStream &in, bool BatchPrimitiveProcessorJL::countThisMsg(messageqcpp::ByteStream &in) const { const uint8_t *data = in.buf(); - uint32_t offset = sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader); // skip the headers + uint offset = sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader); // skip the headers if (_hasScan) { @@ -662,42 +620,29 @@ bool BatchPrimitiveProcessorJL::countThisMsg(messageqcpp::ByteStream &in) const return (data[offset] != 0); } -void BatchPrimitiveProcessorJL::deserializeAggregateResult(ByteStream *in, - vector *out) const -{ - RGData rgData; - uint32_t count, i; - - *in >> count; - for (i = 0; i < count; i++) { - rgData.deserialize(*in, true); - out->push_back(rgData); - } -} - -void BatchPrimitiveProcessorJL::getRowGroupData(ByteStream &in, vector *out, - bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, +boost::shared_array +BatchPrimitiveProcessorJL::getRowGroupData(messageqcpp::ByteStream &in, + bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks, bool *countThis, - uint32_t threadID) const + uint threadID) const { + messageqcpp::ByteStream::quadbyte len; uint64_t tmp64; uint8_t tmp8; - RGData rgData; + const uint8_t *buf; + boost::shared_array ret; uint32_t rowCount; - RowGroup &org = primprocRG[threadID]; - - out->clear(); + rowgroup::RowGroup org = projectionRG; // can we avoid this assignment? if (in.length() == 0) { - // done, return an empty RG - rgData = RGData(org, 0); - org.setData(&rgData); + /* make an empty tableband */ + ret.reset(new uint8_t[org.getEmptySize()]); + org.setData(ret.get()); org.resetRowGroup(0); - out->push_back(rgData); *cachedIO = 0; *physIO = 0; *touchedBlocks = 0; - return; + return ret; } /* skip the header */ @@ -719,50 +664,49 @@ void BatchPrimitiveProcessorJL::getRowGroupData(ByteStream &in, vector * in >> tmp8; *countThis = (tmp8 != 0); + in >> len; + /* XXXPAT! TODO: Make an allocator compatible with shared_ptr for each + rowgroup, tuned to issue chunks of rg.getMaxSize() bytes. + shared_ptr for boost 1.33.1 link: + http://www.boost.org/doc/libs/1_33_1/libs/smart_ptr/shared_ptr.htm + */ + ret.reset(new uint8_t[len]); + buf = in.buf(); + memcpy(ret.get(), buf, len); + in.advance(len); - /* Would be cleaner to make the PM BPP's send a msg count to unify the msg formats. - * For later... */ - if (aggregatorPM) { - deserializeAggregateResult(&in, out); - //for (uint32_t z = 0; z < out->size(); z++) { - // org.setData(&(*out)[z]); - // cout << "BPPJL: " << org.toString() << endl; - //} - } - else { - rgData.deserialize(in, true); - out->push_back(rgData); - org.setData(&rgData); - - rowCount = org.getRowCount(); - - bool pmSendsMatchesAnyway = (hasSmallOuterJoin && *countThis && PMJoinerCount > 0 && + org.setData(ret.get()); + rowCount = org.getRowCount(); +// cout << "rowCount = " << rowCount << endl; + bool pmSendsMatchesAnyway = (hasSmallOuterJoin && *countThis && PMJoinerCount > 0 && (fe2 || aggregatorPM)); - if (!pmSendsFinalResult() || pmSendsMatchesAnyway) { - boost::shared_array > joinResults; - uint32_t i, j; + if (!pmSendsFinalResult() || pmSendsMatchesAnyway) { + boost::shared_array > joinResults; + uint i, j; - if (pmSendsMatchesAnyway) { - uint16_t joinRowCount; - in >> joinRowCount; - rowCount = joinRowCount; - } + if (pmSendsMatchesAnyway) { + uint16_t joinRowCount; + in >> joinRowCount; + rowCount = joinRowCount; + } - for (j = 0; j < PMJoinerCount; j++) { - /* Reuse the result space if possible */ - joinResults = tJoiners[j]->getPMJoinArrays(threadID); - if (joinResults.get() == NULL) { - joinResults.reset(new vector[8192]); - tJoiners[j]->setPMJoinResults(joinResults, threadID); - } - for (i = 0; i < rowCount; i++) - deserializeInlineVector(in, joinResults[i]); - if (tJoiners[j]->smallOuterJoin()) - tJoiners[j]->markMatches(threadID, rowCount); + for (j = 0; j < PMJoinerCount; j++) { + /* Reuse the result space if possible */ + joinResults = tJoiners[j]->getPMJoinArrays(threadID); +// cout << "deserializing PM join result\n"; + if (joinResults.get() == NULL) { + joinResults.reset(new vector[8192]); + tJoiners[j]->setPMJoinResults(joinResults, threadID); } + for (i = 0; i < rowCount; i++) + deserializeInlineVector(in, joinResults[i]); + if (tJoiners[j]->smallOuterJoin()) + tJoiners[j]->markMatches(threadID, rowCount); } } +// else +// cout << "assuming no join or the PM sends joined rows\n"; if (*countThis) { // cout << "grabbing io stats\n"; @@ -776,23 +720,23 @@ void BatchPrimitiveProcessorJL::getRowGroupData(ByteStream &in, vector * *touchedBlocks = 0; } +// if (in.length() != 0) +// cout << "there are " << in.length() << " bytes left!\n"; idbassert(in.length() == 0); + return ret; } -//boost::shared_array -RGData +boost::shared_array BatchPrimitiveProcessorJL::getErrorRowGroupData(uint16_t error) const { - RGData ret; - rowgroup::RowGroup rg(projectionRG); + boost::shared_array ret; + rowgroup::RowGroup rg; - ret = RGData(rg, 0); - rg.setData(&ret); - //rg.convertToInlineDataInPlace(); + ret.reset(new uint8_t[rg.getEmptySize()]); + rg.setData(ret.get()); rg.resetRowGroup(0); rg.setStatus(error); return ret; - //return ret->rowData; } void BatchPrimitiveProcessorJL::reset() @@ -802,34 +746,32 @@ void BatchPrimitiveProcessorJL::reset() needToSetLBID = true; } -void BatchPrimitiveProcessorJL::setLBID(uint64_t l, const BRM::EMEntry &scannedExtent) +void BatchPrimitiveProcessorJL::setLBID(uint64_t l, uint dbroot) { - uint32_t i; - - dbRoot = scannedExtent.dbRoot; - baseRid = rowgroup::convertToRid(scannedExtent.partitionNum, - scannedExtent.segmentNum, - scannedExtent.blockOffset/(scannedExtent.range.size * 1024), // the extent # - (l - scannedExtent.range.start)/scannedExtent.range.size); // the logical block # - - /* - cout << "got baserid=" << baseRid << " from partnum=" << scannedExtent.partitionNum - << " segnum=" << scannedExtent.segmentNum << " extentnum=" << - scannedExtent.blockOffset/(scannedExtent.range.size * 1024) << - " blocknum=" << (l - scannedExtent.range.start)/scannedExtent.range.size << endl; - */ + dbRoot = dbroot; + filterSteps[0]->setLBID(l, dbroot); +} + +void BatchPrimitiveProcessorJL::setLBIDForScan(uint64_t rid, uint dbroot) +{ + uint i; - for (i = 0; i < filterCount; ++i) - filterSteps[i]->setLBID(baseRid, dbRoot); + baseRid = rid; +// cout << "scan set base RID to " << baseRid << endl; - for (i = 0; i < projectCount; ++i) - projectSteps[i]->setLBID(baseRid, dbRoot); + for (i = 1; i < filterCount; ++i) + filterSteps[i]->setLBID(rid, dbroot); + + for (i = 0; i < projectCount; ++i) { +// cout << "setting lbid for projection #" << i << endl; + projectSteps[i]->setLBID(rid, dbroot); + } } string BatchPrimitiveProcessorJL::toString() const { ostringstream ret; - uint32_t i; + uint i; ret << "BatchPrimitiveProcessorJL:" << endl; if (!_hasScan) { @@ -875,18 +817,18 @@ string BatchPrimitiveProcessorJL::toString() const void BatchPrimitiveProcessorJL::createBPP(ByteStream &bs) const { ISMPacketHeader ism; - uint32_t i; + uint i; uint8_t flags = 0; ism.Command = BATCH_PRIMITIVE_CREATE; bs.load((uint8_t *) &ism, sizeof(ism)); bs << (uint8_t) ot; + bs << (messageqcpp::ByteStream::quadbyte)versionNum; bs << (messageqcpp::ByteStream::quadbyte)txnID; bs << (messageqcpp::ByteStream::quadbyte)sessionID; bs << (messageqcpp::ByteStream::quadbyte)stepID; bs << uniqueID; - bs << versionInfo; if (needStrValues) flags |= NEED_STR_VALUES; @@ -941,7 +883,7 @@ void BatchPrimitiveProcessorJL::createBPP(ByteStream &bs) const if (ot == ROW_GROUP) { idbassert(tJoiners.size() > 0); bs << (messageqcpp::ByteStream::quadbyte)PMJoinerCount; - + bool atLeastOneFE = false; #ifdef JLF_DEBUG cout << "PMJoinerCount = " << PMJoinerCount << endl; @@ -949,9 +891,9 @@ void BatchPrimitiveProcessorJL::createBPP(ByteStream &bs) const for (i = 0; i < PMJoinerCount; i++) { bs << (uint32_t) tJoiners[i]->size(); bs << tJoiners[i]->getJoinType(); - + //bs << (uint64_t) tJoiners[i]->smallNullValue(); - + bs << (uint8_t) tJoiners[i]->isTypelessJoin(); if (tJoiners[i]->hasFEFilter()) { atLeastOneFE = true; @@ -963,10 +905,10 @@ void BatchPrimitiveProcessorJL::createBPP(ByteStream &bs) const if (!tJoiners[i]->isTypelessJoin()) { bs << (uint64_t) tJoiners[i]->smallNullValue(); bs << (messageqcpp::ByteStream::quadbyte)tJoiners[i]->getLargeKeyColumn(); - //cout << "large key column is " << (uint32_t) tJoiners[i]->getLargeKeyColumn() << endl; + //cout << "large key column is " << (uint) tJoiners[i]->getLargeKeyColumn() << endl; } else { - serializeVector(bs, tJoiners[i]->getLargeKeyColumns()); + serializeVector(bs, tJoiners[i]->getLargeKeyColumns()); bs << (uint32_t) tJoiners[i]->getKeyLength(); } } @@ -1011,23 +953,6 @@ void BatchPrimitiveProcessorJL::createBPP(ByteStream &bs) const bs << (uint8_t) 0; } } - // decide which rowgroup is received by PrimProc - if (ot == ROW_GROUP) { - primprocRG.reset(new RowGroup[threadCount]); - for (uint32_t i = 0; i < threadCount; i++) - if (aggregatorPM) - primprocRG[i] = aggregateRGPM; - else if (fe2) - primprocRG[i] = fe2Output; - //This shouldn't be necessary. As of 2-17-14, PrimProc - //will only send joined results if fe2 || aggregatorPM, - //so it will never send back data for joinedRG. - //else if ((flags & HAS_JOINER) && sendTupleJoinRowGroupData) - // primprocRG[i] = joinedRG; - else - primprocRG[i] = projectionRG; - } - } /** @@ -1058,7 +983,7 @@ void BatchPrimitiveProcessorJL::createBPP(ByteStream &bs) const void BatchPrimitiveProcessorJL::runBPP(ByteStream &bs, uint32_t pmNum) { ISMPacketHeader ism; - uint32_t i; + uint i; /* XXXPAT: BPPJL currently reuses the ism Size fields for other things to save bandwidth. They're completely unused otherwise. We need to throw out all unused @@ -1102,7 +1027,7 @@ fields of every defined header. */ } else { bs << ridCount; - if (sendAbsRids) + if (sendAbsRids) bs.append((uint8_t *) absRids.get(), ridCount << 3); else { bs << ridMap; @@ -1113,7 +1038,7 @@ fields of every defined header. */ bs.append((uint8_t *) values, ridCount << 3); } - for (i = 0; i < filterCount; i++) + for (i = 0; i < filterCount; i++) filterSteps[i]->runCommand(bs); for (i = 0; i < projectCount; i++) projectSteps[i]->runCommand(bs); @@ -1144,7 +1069,7 @@ void BatchPrimitiveProcessorJL::destroyBPP(ByteStream &bs) const ISMPacketHeader ism; // if (!(sessionID & 0x80000000)) -// cout << "step ID " << stepID << " added " << rowCounter << " rows, processed " +// cout << "step ID " << stepID << " added " << rowCounter << " rows, processed " // << rowsProcessed << " rows" << endl; memset((void*)&ism, 0, sizeof(ism)); @@ -1165,8 +1090,8 @@ void BatchPrimitiveProcessorJL::useJoiners(const vectorinPM()) { PMJoinerCount++; smallSideKeys.push_back(tJoiners[i]->getSmallKeyColumns()); @@ -1180,7 +1105,7 @@ void BatchPrimitiveProcessorJL::useJoiners(const vectorgetLargeRG(); - + if (aggregatorPM || fe2) { sendTupleJoinRowGroupData = true; #ifdef JLF_DEBUG @@ -1195,13 +1120,9 @@ bool BatchPrimitiveProcessorJL::nextTupleJoinerMsg(ByteStream &bs) uint32_t size = 0, toSend, i, j; ISMPacketHeader ism; Row r; - vector *tSmallSide; + std::vector *tSmallSide; joiner::TypelessData tlData; - uint32_t smallKeyCol; - uint32_t largeKeyCol; - uint64_t smallkey; bool isNull; - bool bSignedUnsigned; memset((void*)&ism, 0, sizeof(ism)); tSmallSide = tJoiners[joinerNum]->getSmallSide(); @@ -1237,34 +1158,15 @@ bool BatchPrimitiveProcessorJL::nextTupleJoinerMsg(ByteStream &bs) unsigned rowunits = fJoinerChunkSize / (r.getSize() + metasize); toSend = std::min(size - pos, rowunits); bs << toSend; - bs << pos; bs << joinerNum; if (tJoiners[joinerNum]->isTypelessJoin()) { utils::FixedAllocator fa(tlKeyLens[joinerNum], true); for (i = pos; i < pos + toSend; i++) { - r.setPointer((*tSmallSide)[i]); + r.setData((*tSmallSide)[i]); isNull = false; - bSignedUnsigned = tJoiners[joinerNum]->isSignedUnsignedJoin(); - for (j = 0; j < smallSideKeys[joinerNum].size(); j++){ + for (j = 0; j < smallSideKeys[joinerNum].size(); j++) isNull |= r.isNullValue(smallSideKeys[joinerNum][j]); - if (UNLIKELY(bSignedUnsigned)) { - // BUG 5628 If this is a signed/unsigned join column and the sign bit is set on either side, - // then it should not compare. Send null to PM to prevent compare - smallKeyCol = smallSideKeys[joinerNum][j]; - largeKeyCol = tJoiners[joinerNum]->getLargeKeyColumns()[j]; - if (r.isUnsigned(smallKeyCol) != largeSideRG.isUnsigned(largeKeyCol)) { - if (r.isUnsigned(smallKeyCol)) - smallkey = r.getUintField(smallKeyCol); - else - smallkey = r.getIntField(smallKeyCol); - if (smallkey & 0x8000000000000000ULL) { - isNull = true; - break; - } - } - } - } bs << (uint8_t) isNull; if (!isNull) { tlData = makeTypelessKey(r, smallSideKeys[joinerNum], @@ -1284,20 +1186,9 @@ bool BatchPrimitiveProcessorJL::nextTupleJoinerMsg(ByteStream &bs) bs.needAtLeast(toSend * sizeof(JoinerElements)); arr = (JoinerElements *) bs.getInputPtr(); - smallKeyCol = smallSideKeys[joinerNum][0]; - bSignedUnsigned = r.isUnsigned(smallKeyCol) != largeSideRG.isUnsigned(tJoiners[joinerNum]->getLargeKeyColumns()[0]); - j = 0; - for (i = pos, j = 0; i < pos + toSend; ++i, ++j) { - r.setPointer((*tSmallSide)[i]); - if (r.isUnsigned(smallKeyCol)) - smallkey = r.getUintField(smallKeyCol); - else - smallkey = r.getIntField(smallKeyCol); - // If this is a compare signed vs unsigned and the sign bit is on for this value, then all compares - // against the large side should fall. UBIGINTEMPTYROW is not a valid value, so nothing will match. - if (bSignedUnsigned && (smallkey & 0x8000000000000000ULL)) - smallkey = joblist::UBIGINTEMPTYROW; - arr[j].key = (int64_t)smallkey; + for (i = pos, j = 0; i < pos + toSend; i++, j++) { + r.setData((*tSmallSide)[i]); + arr[j].key = r.getIntField(smallSideKeys[joinerNum][0]); arr[j].value = i; // cout << "sending " << arr[j].key << ", " << arr[j].value << endl; } @@ -1306,37 +1197,34 @@ bool BatchPrimitiveProcessorJL::nextTupleJoinerMsg(ByteStream &bs) } if (sendTupleJoinRowGroupData) { - RowGroup &smallSide = smallSideRGs[joinerNum]; - RGData tmpData(smallSide, toSend); - Row tmpRow; - - smallSide.setData(&tmpData); - smallSide.initRow(&tmpRow); - smallSide.getRow(0, &tmpRow); - for (i = pos; i < pos + toSend; i++, tmpRow.nextRow()) { - r.setPointer((*tSmallSide)[i]); - copyRow(r, &tmpRow); - } - - smallSide.setRowCount(toSend); - tmpData.serialize(bs, smallSide.getDataSize()); - - /* uint32_t lpos; uint8_t *buf; bs.needAtLeast(r.getSize() * toSend); buf = (uint8_t *) bs.getInputPtr(); - //for (i = pos, lpos = 0; i < pos + toSend; i++, lpos += r.getSize()) - // memcpy(&buf[lpos], (*tSmallSide)[i], r.getSize()); + for (i = pos, lpos = 0; i < pos + toSend; i++, lpos += r.getSize()) + memcpy(&buf[lpos], (*tSmallSide)[i], r.getSize()); bs.advanceInputPtr(r.getSize() * toSend); - */ } pos += toSend; return true; } +#if 0 +void BatchPrimitiveProcessorJL::setTupleJoinRowGroups( + const rowgroup::RowGroup &smallRg, const rowgroup::RowGroup &largeRg) +{ + smallSideRG = smallRg; + largeSideRG = largeRg; +} + +void BatchPrimitiveProcessorJL::setSmallSideKeyColumn(uint col) +{ + smallSideKey = col; +} +#endif + void BatchPrimitiveProcessorJL::useJoiner(boost::shared_ptr j) { pos = 0; @@ -1347,7 +1235,7 @@ bool BatchPrimitiveProcessorJL::nextJoinerMsg(ByteStream &bs) { uint32_t size, toSend; ISMPacketHeader ism; - + memset((void*)&ism, 0, sizeof(ism)); if (smallSide.get() == NULL) smallSide = joiner->getSmallSide(); @@ -1372,7 +1260,6 @@ bool BatchPrimitiveProcessorJL::nextJoinerMsg(ByteStream &bs) toSend = (size - pos > 1000000 ? 1000000 : size - pos); bs << toSend; - bs << pos; bs.append((uint8_t *) (&(*smallSide)[pos]), sizeof(ElementType) * toSend); pos += toSend; @@ -1408,7 +1295,7 @@ void BatchPrimitiveProcessorJL::addAggregateStep(const rowgroup::SP_ROWAGG_PM_t& } /* OR hacks */ -void BatchPrimitiveProcessorJL::setBOP(uint32_t op) +void BatchPrimitiveProcessorJL::setBOP(uint op) { bop = op; @@ -1498,17 +1385,4 @@ void BatchPrimitiveProcessorJL::abortProcessing(ByteStream *bs) *bs << uniqueID; } -void BatchPrimitiveProcessorJL::deliverStringTableRowGroup(bool b) -{ - if (aggregatorPM) - aggregateRGPM.setUseStringTable(b); - else if (fe2) - fe2Output.setUseStringTable(b); -// else if ((joiner.get() != NULL || tJoiners.size() > 0) && sendTupleJoinRowGroupData) -// joinedRG.setUseStringTable(b); - else - projectionRG.setUseStringTable(b); -} - - -} +}; diff --git a/dbcon/joblist/batchprimitiveprocessor-jl.h b/dbcon/joblist/batchprimitiveprocessor-jl.h index 99d62874..8dd20c35 100644 --- a/dbcon/joblist/batchprimitiveprocessor-jl.h +++ b/dbcon/joblist/batchprimitiveprocessor-jl.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: batchprimitiveprocessor-jl.h 9705 2013-07-17 20:06:07Z pleblanc $ +// $Id: batchprimitiveprocessor-jl.h 8774 2012-07-31 21:00:09Z pleblanc $ // C++ Interface: batchprimitiveprocessor // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -35,7 +35,6 @@ #include #include #include -#include #include "primitivemsg.h" #include "serializeable.h" @@ -47,7 +46,7 @@ namespace joblist { -const uint32_t LOGICAL_BLOCKS_CONVERTER = 23; // 10 + 13. 13 to convert to logical blocks, +const uint LOGICAL_BLOCKS_CONVERTER = 23; // 10 + 13. 13 to convert to logical blocks, // 10 to convert to groups of 1024 logical blocks // forward reference @@ -61,31 +60,29 @@ class BatchPrimitiveProcessorJL ~BatchPrimitiveProcessorJL(); /* Interface used by the JobStep */ - + /* Some accessors */ inline bool hasScan() { return _hasScan; } /* For initializing the object */ - inline void setSessionID(uint32_t num) { sessionID = num; } - inline void setStepID(uint32_t num) { stepID = num; } + inline void setSessionID(uint num) { sessionID = num; } + inline void setStepID(uint num) { stepID = num; } inline void setUniqueID(uint32_t id) { uniqueID = id; } - inline void setQueryContext(const BRM::QueryContext &qc) { versionInfo = qc; } - inline void setTxnID(uint32_t num) { txnID = num; } + inline void setVersionNum(uint num) { versionNum = num; } + inline void setTxnID(uint num) { txnID = num; } inline void setOutputType(BPSOutputType o) { ot = o; if (ot == TUPLE || ot == ROW_GROUP) needRidsAtDelivery = true; } inline void setNeedRidsAtDelivery(bool b) { needRidsAtDelivery = b; } inline void setTraceFlags(uint32_t flags) { LBIDTrace = ((flags & execplan::CalpontSelectExecutionPlan::TRACE_LBIDS) != 0); } - inline uint32_t getRidCount() { return ridCount; } - inline void setThreadCount(uint32_t tc) { threadCount = tc; } + inline uint getRidCount() { return ridCount; } + void addFilterStep(const pColScanStep &); void addFilterStep(const pColScanStep &, std::vector lastScannedLBID); - void addFilterStep(const PseudoColStep &); void addFilterStep(const pColStep &); void addFilterStep(const pDictionaryStep &); void addFilterStep(const FilterStep &); - void addProjectStep(const PseudoColStep &); void addProjectStep(const pColStep &); void addProjectStep(const PassThruStep &); void addProjectStep(const pColStep &, const pDictionaryStep &); @@ -101,9 +98,9 @@ class BatchPrimitiveProcessorJL // void addDeliveryStep(const DeliveryStep &); /* At runtime, feed input here */ - void addElementType(const ElementType &, uint32_t dbroot); - void addElementType(const StringElementType &, uint32_t dbroot); - //void setRowGroupData(const rowgroup::RowGroup &); + void addElementType(const ElementType &, uint dbroot); + void addElementType(const StringElementType &, uint dbroot); + void setRowGroupData(const rowgroup::RowGroup &); void runBPP(messageqcpp::ByteStream &, uint32_t pmNum); void abortProcessing(messageqcpp::ByteStream *); @@ -112,46 +109,41 @@ class BatchPrimitiveProcessorJL void reset(); /* The JobStep calls these to initialize a BPP that starts with a column scan */ - void setLBID(uint64_t lbid, const BRM::EMEntry &scannedExtent); + void setLBID(uint64_t lbid, uint dbroot = 1); inline void setCount(uint16_t c) { idbassert(c > 0); count = c; } /* Turn a ByteStream into ElementTypes or StringElementTypes */ void getElementTypes(messageqcpp::ByteStream &in, std::vector *out, bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, - uint32_t *touchedBlocks, + uint32_t *touchedBlocks, uint16_t *preJoinRidCount) const; void getStringElementTypes(messageqcpp::ByteStream &in, - std::vector *out, bool *validCPData, uint64_t *lbid, - int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, + std::vector *out, bool *validCPData, uint64_t *lbid, + int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks) const; /* (returns the row count) */ -// uint32_t getTableBand(messageqcpp::ByteStream &in, messageqcpp::ByteStream *out, +// uint getTableBand(messageqcpp::ByteStream &in, messageqcpp::ByteStream *out, // bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, // uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks) const; void getTuples(messageqcpp::ByteStream &in, std::vector *out, bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks) const; - void deserializeAggregateResults(messageqcpp::ByteStream *in, - std::vector *out) const; - void getRowGroupData(messageqcpp::ByteStream &in, std::vector *out, + boost::shared_array getRowGroupData(messageqcpp::ByteStream &in, bool *validCPData, uint64_t *lbid, int64_t *min, int64_t *max, uint32_t *cachedIO, uint32_t *physIO, uint32_t *touchedBlocks, bool *countThis, - uint32_t threadID) const; - void deserializeAggregateResult(messageqcpp::ByteStream *in, - std::vector *out) const; + uint threadID) const; bool countThisMsg(messageqcpp::ByteStream &in) const; void setStatus(uint16_t s) { status = s; } uint16_t getStatus() const { return status; } void runErrorBPP(messageqcpp::ByteStream &); -// uint32_t getErrorTableBand(uint16_t error, messageqcpp::ByteStream *out); -// boost::shared_array getErrorRowGroupData(uint16_t error) const; - rowgroup::RGData getErrorRowGroupData(uint16_t error) const; +// uint getErrorTableBand(uint16_t error, messageqcpp::ByteStream *out); + boost::shared_array getErrorRowGroupData(uint16_t error) const; // @bug 1098 std::vector& getFilterSteps() { return filterSteps; } std::vector& getProjectSteps() { return projectSteps; } - + std::string toString() const; /* RowGroup additions */ @@ -165,10 +157,10 @@ class BatchPrimitiveProcessorJL /* Tuple hashjoin */ void useJoiners(const std::vector > &); bool nextTupleJoinerMsg(messageqcpp::ByteStream &); -// void setSmallSideKeyColumn(uint32_t col); +// void setSmallSideKeyColumn(uint col); /* OR hacks */ - void setBOP(uint32_t op); // BOP_AND or BOP_OR, default is BOP_AND + void setBOP(uint op); // BOP_AND or BOP_OR, default is BOP_AND void setForHJ(bool b); // default is false /* self-join */ @@ -190,24 +182,20 @@ class BatchPrimitiveProcessorJL } const std::string toMiniString() const; - void priority(uint32_t p) { _priority = p; }; - uint32_t priority() { return _priority; } - - void deliverStringTableRowGroup(bool b); - - void setUuid(const boost::uuids::uuid& u) { uuid = u; } + void priority(uint p) { _priority = p; }; + uint priority() { return _priority; } private: - //void setLBIDForScan(uint64_t rid, uint32_t dbroot); + void setLBIDForScan(uint64_t rid, uint dbroot); BPSOutputType ot; bool needToSetLBID; - BRM::QueryContext versionInfo; - uint32_t txnID; - uint32_t sessionID; - uint32_t stepID; + uint versionNum; + uint txnID; + uint sessionID; + uint stepID; uint32_t uniqueID; // # of times to loop over the command arrays @@ -238,7 +226,7 @@ class BatchPrimitiveProcessorJL // TableBand templateTB; uint32_t tableOID; boost::scoped_array tablePositions; - uint32_t tableColumnCount; + uint tableColumnCount; bool sendValues; bool sendAbsRids; bool _hasScan; @@ -246,9 +234,9 @@ class BatchPrimitiveProcessorJL /* for tuple return type */ std::vector colWidths; - uint32_t tupleLength; -// uint32_t rowCounter; // for debugging -// uint32_t rowsProcessed; + uint tupleLength; +// uint rowCounter; // for debugging +// uint rowsProcessed; uint16_t status; /* for Joiner serialization */ @@ -268,12 +256,13 @@ class BatchPrimitiveProcessorJL /* UM portion of the PM join alg */ std::vector > tJoiners; + std::vector *> tSmallSides; std::vector smallSideRGs; rowgroup::RowGroup largeSideRG; - std::vector > smallSideKeys; - boost::scoped_array tlKeyLens; + std::vector > smallSideKeys; + boost::scoped_array tlKeyLens; bool sendTupleJoinRowGroupData; - uint32_t PMJoinerCount; + uint PMJoinerCount; /* OR hack */ uint8_t bop; // BOP_AND or BOP_OR @@ -287,16 +276,11 @@ class BatchPrimitiveProcessorJL rowgroup::RowGroup fe1Input, fe2Output; rowgroup::RowGroup joinFERG; - mutable boost::scoped_array primprocRG; // the format of the data received from PrimProc - uint32_t threadCount; - unsigned fJoinerChunkSize; - uint32_t dbRoot; + uint dbRoot; bool hasSmallOuterJoin; - uint32_t _priority; - - boost::uuids::uuid uuid; + uint _priority; friend class CommandJL; friend class ColumnCommandJL; diff --git a/dbcon/joblist/batchprimitivestep.cpp b/dbcon/joblist/batchprimitivestep.cpp new file mode 100644 index 00000000..a04eb632 --- /dev/null +++ b/dbcon/joblist/batchprimitivestep.cpp @@ -0,0 +1,2715 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: batchprimitivestep.cpp 8476 2012-04-25 22:28:15Z xlou $ +* +* +***********************************************************************/ + +#include +#include +#include +#include +#include +using namespace std; + +#include +#include +using namespace boost; + +#include "bpp-jl.h" +#include "distributedenginecomm.h" +#include "elementtype.h" +#include "unique32generator.h" +using namespace joblist; + +#include "messagequeue.h" +using namespace messageqcpp; +#include "configcpp.h" +using namespace config; + +#include "messagelog.h" +#include "messageobj.h" +#include "loggingid.h" +#include "errorcodes.h" +#include "liboamcpp.h" +using namespace logging; + +#include "calpontsystemcatalog.h" +using namespace execplan; + +#include "brm.h" +using namespace BRM; + +#include "oamcache.h" +using namespace utils; + +// #define DEBUG 1 + + +// unname namespace for BatchPrimitiveStep profiling +namespace +{ +enum +{ + sendPrimMsg_c = 0, + sendWork_Scan, + tableBand_c, + getLBID_c, + write_c, + sendLock1_c, + sendLock2_c, + nextAddFilters1_c, + nextAddFilters2_c, + numOfSendCheckPoints, + + recvCheckpointOffset = numOfSendCheckPoints, + recvPrimMsg_c = 0, + recvWork_c, + recvLock_c, + recvWait_c, + read_c, + insert1_c, + insert2_c, + numOfRecvCheckPoints, + + TotalCheckPoints = numOfSendCheckPoints + numOfRecvCheckPoints +}; + +// !!these strings are for stats output. should be in the same order as the enum above. !! +static string CheckPoints[TotalCheckPoints] = { + "betweenFirstSendAndFirstRead", + "totalScanSend", + "getTableBandUsed", + "getLBID in send", + "fDec->write in send", + "mutex_lock_1 in send", + "mutex_lock_2 in send", + "1st ridList->next in addFilters", + "ridList->next in addFilters", + + "receivePrimitiveMessages", + "receive work", + "mutex_lock in receive", + "cond_wait in receive", + "fDec->read in receive", + "dlp->insert_1 in receive", + "dlp->insert_2 in receive" + }; +} +#endif + +extern boost::mutex fileLock_g; + +namespace +{ +const uint LOGICAL_EXTENT_CONVERTER = 10; // 10 + 13. 13 to convert to logical blocks, + // 10 to convert to groups of 1024 logical blocks +void logDiskIoInfo(uint64_t stepId, const AnyDataListSPtr& spdl) +{ + boost::mutex::scoped_lock lk(fileLock_g); + ofstream umDiskIoFile("/var/log/Calpont/trace/umdiskio.log", ios_base::app); + + CalpontSystemCatalog::OID oid; + uint64_t maxBuckets = 0; + list* infoList = NULL; + string bkt("tbd"); + //BucketDL* bdl = spdl->bucketDL(); + //BucketDL* sbdl = spdl->stringBucketDL(); + //ZDL* zdl = spdl->zonedDL(); + //ZDL* szdl = spdl->stringZonedDL(); + TupleBucketDataList* tbdl = spdl->tupleBucketDL(); + + if (tbdl) + { + maxBuckets = tbdl->bucketCount(); + oid = tbdl->OID(); + } + else + { + // not logged for now. + return; + } + + for (uint64_t i = 0; i < maxBuckets; i++) + { + infoList = &(tbdl->diskIoInfoList(i)); + + for (list::iterator j = infoList->begin(); j != infoList->end(); j++) + { + boost::posix_time::time_duration td = j->fEnd - j->fStart; + umDiskIoFile << setfill('0') + << "st" << setw(2) << stepId << "oid" << oid << bkt << setw(3) << i + << (j->fWrite ? " writes " : " reads ") << setw(7) << setfill(' ') + << j->fBytes << " bytes, at " << j->fStart << " duration " + << td.total_microseconds() << " mcs @ " + << (j->fBytes/td.total_microseconds()) << "MB/s" << endl; + } + } + + streampos curPos = umDiskIoFile.tellp( ); + umDiskIoFile.close(); + + // move the current file to bak when size above .5 G, so total log is 1 G + if (curPos > 0x20000000) + { + (void)system("/bin/mv /var/log/Calpont/trace/umdiskio.log /var/log/Calpont/trace/umdiskio.bak"); + } +} +} + +/** Debug macro */ +#define THROTTLE_DEBUG 0 +#if THROTTLE_DEBUG +#define THROTTLEDEBUG std::cout +#else +#define THROTTLEDEBUG if (false) std::cout +#endif +namespace joblist +{ + //const uint32_t defaultProjectBlockReqThreshold = 256; + //const uint32_t defaultScanBlockThreshold = 10000; +struct BatchPrimitiveStepPrimitive +{ + BatchPrimitiveStepPrimitive(BatchPrimitiveStep* batchPrimitiveStep) : fBatchPrimitiveStep(batchPrimitiveStep) + {} + BatchPrimitiveStep *fBatchPrimitiveStep; + void operator()() + { + try + { + fBatchPrimitiveStep->sendPrimitiveMessages(); + } + catch(std::exception& re) + { + cerr << "BatchPrimitiveStep: send thread threw an exception: " << re.what() << + "\t" << this << endl; + catchHandler(re.what()); + } + catch(...) + { + string msg("BatchPrimitiveStep: send thread threw an unknown exception "); + catchHandler(msg); + cerr << msg << this << endl; + } + } +}; + +struct BatchPrimitiveStepAggregator +{ + BatchPrimitiveStepAggregator(BatchPrimitiveStep* batchPrimitiveStep) : fBatchPrimitiveStepCol(batchPrimitiveStep) + {} + BatchPrimitiveStep *fBatchPrimitiveStepCol; + void operator()() + { + try + { + fBatchPrimitiveStepCol->receivePrimitiveMessages(); + } + catch(std::exception& re) + { + cerr << fBatchPrimitiveStepCol->toString() << ": recv thread threw an exception: " + << re.what() << endl; + catchHandler(re.what()); + } + catch(...) + { + string msg("BatchPrimitiveStep: recv thread threw an unknown exception "); + cerr << fBatchPrimitiveStepCol->toString() << msg << endl; + catchHandler(msg); + } + } +}; + +struct BatchPrimitiveStepAggregatores +{ + BatchPrimitiveStepAggregatores( BatchPrimitiveStep* batchPrimitiveStep, uint64_t index) : + fBatchPrimitiveStepCols(batchPrimitiveStep), fThreadId(index) + {} + BatchPrimitiveStep *fBatchPrimitiveStepCols; + uint64_t fThreadId; + + void operator()() + { + try + { + fBatchPrimitiveStepCols->receiveMultiPrimitiveMessages(fThreadId); + } + catch(std::exception& re) + { + cerr << fBatchPrimitiveStepCols->toString() << ": receive thread threw an exception: " + << re.what() << endl; + catchHandler(re.what()); + } + catch(...) + { + string msg("BatchPrimitiveStep: recv thread threw an unknown exception "); + cerr << fBatchPrimitiveStepCols->toString() << msg << endl; + catchHandler(msg); + } + } +}; + + +//------------------------------------------------------------------------------ +// Initialize configurable parameters +//------------------------------------------------------------------------------ +void BatchPrimitiveStep::initializeConfigParms() +{ + string strVal; + + //...Get the tuning parameters that throttle msgs sent to primproc + //...fFilterRowReqLimit puts a cap on how many rids we will request from + //... primproc, before pausing to let the consumer thread catch up. + //... Without this limit, there is a chance that PrimProc could flood + //... ExeMgr with thousands of messages that will consume massive + //... amounts of memory for a 100 gigabyte database. + //...fFilterRowReqThreshold is the level at which the number of outstanding + //... rids must fall below, before the producer can send more rids. + + //These could go in constructor + numDBRoots = fRm.getDBRootCount(); + fRequestSize = fRm.getJlRequestSize(); + fMaxOutstandingRequests = fRm.getJlMaxOutstandingRequests(); + fProcessorThreadsPerScan = fRm.getJlProcessorThreadsPerScan(); + if ( fRequestSize >= fMaxOutstandingRequests ) + fRequestSize = 1; + fNumThreads = fRm.getJlNumScanReceiveThreads(); + + fProducerThread.reset(new SPTHD[fNumThreads]); + //pthread_mutex_init(&mutex, NULL); + //pthread_mutex_init(&dlMutex, NULL); + //pthread_mutex_init(&cpMutex, NULL); + //pthread_cond_init(&condvar, NULL); + //pthread_cond_init(&condvarWakeupProducer, NULL); +} + +BatchPrimitiveStep::BatchPrimitiveStep(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, ResourceManager& rm): + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + msgsSent(0), + msgsRecvd(0), + finishedSending(false), + sendWaiting(false), + fRm(rm), fUpdatedEnd(false) +{ + throw logic_error("BPS's are initialized from other JobSteps"); + + fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); + initializeConfigParms ( ); + rowsReturned = 0; + fNumBlksSkipped = 0; + fMsgBytesIn = 0; + fMsgBytesOut = 0; + fBlockTouched = 0; + fMsgBppsToPm = 0; + fIsProjectionOnly = false; + fPhysicalIO = 0; + fCacheIO = 0; + recvWaiting = 0; + isFilterFeeder = false; + fSwallowRows = false; + die = false; +} + +BatchPrimitiveStep::BatchPrimitiveStep(const pColStep& rhs) : fRm (rhs.fRm), fUpdatedEnd(false) +{ + fInputJobStepAssociation = rhs.inputAssociation(); + fOutputJobStepAssociation = rhs.outputAssociation(); + fDec = rhs.dec(); + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); + fFilterCount = rhs.filterCount(); + fFilterString = rhs.filterString(); + isFilterFeeder = rhs.getFeederFlag(); + fOid = rhs.oid(); + fTableOid = rhs.tableOid(); + fBOP = rhs.BOP(); + extents = rhs.extents; + if (fOid>3000) + lbidList = rhs.lbidList; + rpbShift = rhs.rpbShift; + divShift = rhs.divShift; + modMask = rhs.modMask; + numExtents = rhs.numExtents; + ridsRequested = 0; + ridsReturned = 0; + rowsReturned = 0; + recvExited = 0; + msgsSent = 0; + msgsRecvd = 0; + fMsgBytesIn = 0; + fMsgBytesOut = 0; + fBlockTouched = 0; + fMsgBppsToPm = 0; + recvWaiting = 0; + fStepCount = 1; + fColType = rhs.colType(); + extentSize = (fRm.getExtentRows()*fColType.colWidth)/BLOCK_SIZE; + alias(rhs.alias()); + view(rhs.view()); + name(rhs.name()); + fColWidth = fColType.colWidth; + fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); + initializeConfigParms ( ); + fBPP->setSessionID( fSessionId ); + fBPP->setStepID(fStepId); + fBPP->setVersionNum( fVerId ); + fBPP->setTxnID( fTxnId ); + fTraceFlags = rhs.fTraceFlags; + fBPP->setTraceFlags( fTraceFlags ); +// if (fOid>=3000) +// cout << "BPS:initalized from pColStep. fSessionId=" << fSessionId << endl; + finishedSending = fIsProjectionOnly = sendWaiting = false; + fNumBlksSkipped = 0; + fPhysicalIO = 0; + fCacheIO = 0; + BPPIsAllocated = false; + uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + fBPP->setUniqueID(uniqueID); + fCardinality = rhs.cardinality(); + doJoin = false; + fRunExecuted = false; + fSwallowRows = false; + + // @1098 initialize scanFlags to be true + scanFlags.assign(numExtents, true); + die = false; +} + +BatchPrimitiveStep::BatchPrimitiveStep(const pColScanStep& rhs) : fRm (rhs.fRm), fUpdatedEnd(false) +{ + fInputJobStepAssociation = rhs.inputAssociation(); + fOutputJobStepAssociation = rhs.outputAssociation(); + fDec = rhs.dec(); + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); + fFilterCount = rhs.filterCount(); + fFilterString = rhs.filterString(); + isFilterFeeder = rhs.getFeederFlag(); + fOid = rhs.oid(); + fTableOid = rhs.tableOid(); + fBOP = rhs.BOP(); + lbidRanges = rhs.lbidRanges; + hwm = rhs.hwm; + extents = rhs.extents; + divShift = rhs.divShift; + numExtents = rhs.numExtents; + msgsSent = 0; + msgsRecvd = 0; + ridsReturned = 0; + ridsRequested = 0; + rowsReturned = 0; + fNumBlksSkipped = 0; + fMsgBytesIn = 0; + fMsgBytesOut = 0; + fBlockTouched = 0; + fMsgBppsToPm = 0; + recvWaiting = 0; + fSwallowRows = false; + fStepCount = 1; + fColType = rhs.colType(); + alias(rhs.alias()); + view(rhs.view()); + name(rhs.name()); + + extentSize = (fRm.getExtentRows()*fColType.colWidth)/BLOCK_SIZE; + fColWidth = fColType.colWidth; + lbidList=rhs.lbidList; + + fLogger = rhs.logger(); + finishedSending = fIsProjectionOnly = sendWaiting = false; + firstRead = true; + fSwallowRows = false; + recvExited = 0; + fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); + initializeConfigParms ( ); + fBPP->setSessionID( fSessionId ); + fBPP->setVersionNum( fVerId ); + fBPP->setTxnID( fTxnId ); + fTraceFlags = rhs.fTraceFlags; + fBPP->setTraceFlags( fTraceFlags ); +// if (fOid>=3000) +// cout << "BPS:initalized from pColScanStep. fSessionId=" << fSessionId << endl; + fBPP->setStepID( fStepId ); + fPhysicalIO = 0; + fCacheIO = 0; + BPPIsAllocated = false; + uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + fBPP->setUniqueID(uniqueID); + fCardinality = rhs.cardinality(); + doJoin = false; + fRunExecuted = false; + // @1098 initialize scanFlags to be true + scanFlags.assign(numExtents, true); + die = false; +} + +BatchPrimitiveStep::BatchPrimitiveStep(const PassThruStep& rhs) : fRm (rhs.fRm), fUpdatedEnd(false) +{ + fInputJobStepAssociation = rhs.inputAssociation(); + fOutputJobStepAssociation = rhs.outputAssociation(); + fDec = rhs.dec(); + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); + fFilterCount = 0; + fBOP = 0; + fOid = rhs.oid(); + fTableOid = rhs.tableOid(); + ridsReturned = 0; + rowsReturned = 0; + ridsRequested = 0; + fMsgBytesIn = 0; + fMsgBytesOut = 0; + fBlockTouched = 0; + fMsgBppsToPm = 0; + recvExited = 0; + msgsSent = 0; + msgsRecvd = 0; + recvWaiting = 0; + fStepCount = 1; + fColType = rhs.colType(); + alias(rhs.alias()); + view(rhs.view()); + name(rhs.name()); + fColWidth = fColType.colWidth; + fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); + initializeConfigParms ( ); + fBPP->setSessionID( fSessionId ); + fBPP->setStepID(fStepId); + fBPP->setVersionNum( fVerId ); + fBPP->setTxnID( fTxnId ); + fTraceFlags = rhs.fTraceFlags; + fBPP->setTraceFlags( fTraceFlags ); +// if (fOid>=3000) +// cout << "BPS:initalized from PassThruStep. fSessionId=" << fSessionId << endl; + + finishedSending = fIsProjectionOnly = sendWaiting = false; + fSwallowRows = false; + fNumBlksSkipped = 0; + fPhysicalIO = 0; + fCacheIO = 0; + BPPIsAllocated = false; + uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + fBPP->setUniqueID(uniqueID); + doJoin = false; + fRunExecuted = false; + isFilterFeeder = false; + die = false; +} + +BatchPrimitiveStep::BatchPrimitiveStep(const pDictionaryStep& rhs) : fRm (rhs.fRm), fUpdatedEnd(false) +{ + fInputJobStepAssociation = rhs.inputAssociation(); + fOutputJobStepAssociation = rhs.outputAssociation(); + fDec = rhs.dec(); + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); + fOid = rhs.oid(); + fTableOid = rhs.tableOid(); + msgsSent = 0; + msgsRecvd = 0; + ridsReturned = 0; + rowsReturned = 0; + ridsRequested = 0; + fNumBlksSkipped = 0; + fBlockTouched = 0; + fMsgBytesIn = 0; + fMsgBytesOut = 0; + fMsgBppsToPm = 0; + recvWaiting = 0; + fSwallowRows = false; + fStepCount = 1; + //fColType = rhs.colType(); + alias( rhs.alias()); + view(rhs.view()); + name(rhs.name()); + + fLogger = rhs.logger(); + finishedSending = fIsProjectionOnly = sendWaiting = false; + recvExited = 0; + fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); + initializeConfigParms ( ); + fBPP->setSessionID( fSessionId ); +// if (fOid>=3000) +// cout << "BPS:initalized from DictionaryStep. fSessionId=" << fSessionId << endl; + fBPP->setStepID( fStepId ); + fBPP->setVersionNum( fVerId ); + fBPP->setTxnID( fTxnId ); + fTraceFlags = rhs.fTraceFlags; + fBPP->setTraceFlags( fTraceFlags ); + fPhysicalIO = 0; + fCacheIO = 0; + BPPIsAllocated = false; + uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + fBPP->setUniqueID(uniqueID); + fCardinality = rhs.cardinality(); + doJoin = false; + fRunExecuted = false; + isFilterFeeder = false; + die = false; +} + +BatchPrimitiveStep::~BatchPrimitiveStep() +{ + //pthread_mutex_destroy(&mutex); + //pthread_mutex_destroy(&dlMutex); + //pthread_mutex_destroy(&cpMutex); + //pthread_cond_destroy(&condvar); + //pthread_cond_destroy(&condvarWakeupProducer); + if (fDec) { + fDec->removeDECEventListener(this); + if (BPPIsAllocated) { + ByteStream bs; + fBPP->destroyBPP(bs); + try { + fDec->write(bs); + } + catch(std::exception& re) + { + cerr << "~BatchPrimitiveStep: write(bs) exception: " << re.what() << endl; + catchHandler(re.what()); + } + catch(...) + { + string msg("~BatchPrimitiveStep: write(bs) threw an unknown exception "); + catchHandler(msg); + } + } + fDec->removeQueue(uniqueID); + } + + if (traceOn()) + { + for (uint64_t i = 0; i < fInputJobStepAssociation.outSize(); i++) + logDiskIoInfo(fStepId, fInputJobStepAssociation.outAt(i)); + for (uint64_t i = 0; i < fOutputJobStepAssociation.outSize(); i++) + logDiskIoInfo(fStepId, fOutputJobStepAssociation.outAt(i)); + } +} + +void BatchPrimitiveStep::setBPP( JobStep* jobStep ) +{ + fCardinality = jobStep->cardinality(); + + pColStep* pcsp = dynamic_cast(jobStep); + + int colWidth = 0; + if (pcsp != 0) + { + fBPP->addFilterStep( *pcsp ); + colWidth = (pcsp->colType()).colWidth; + isFilterFeeder = pcsp->getFeederFlag(); +// if (fOid>=3000) +// cout << "Adding pColStep BPS" << endl; + } + else + { + pColScanStep* pcss = dynamic_cast(jobStep); + if (pcss != 0) + { + fBPP->addFilterStep( *pcss ); + colWidth = (pcss->colType()).colWidth; + isFilterFeeder = pcss->getFeederFlag(); + } + else + { + pDictionaryStep* pdsp = dynamic_cast(jobStep); + if (pdsp != 0) + { + fBPP->addFilterStep( *pdsp ); + colWidth = (pdsp->colType()).colWidth; + } + else + { + FilterStep* pfsp = dynamic_cast(jobStep); + if ( pfsp ) + { + fBPP->addFilterStep( *pfsp ); + } + } + + } + } + + if ( colWidth > fColWidth ) + { + fColWidth = colWidth; + } +} + +void BatchPrimitiveStep::setProjectBPP( JobStep* jobStep1, JobStep* jobStep2 ) +{ + int colWidth = 0; + + if ( jobStep2 != NULL ) + { + pDictionaryStep* pdsp = 0; + pColStep* pcsp = dynamic_cast(jobStep1); + if (pcsp != 0) + { + pdsp = dynamic_cast(jobStep2); + fBPP->addProjectStep( *pcsp, *pdsp ); + //@Bug 961 + if ( !pcsp->isExeMgr()) + fBPP->setNeedRidsAtDelivery( true ); + colWidth = (pcsp->colType()).colWidth; + projectOids.push_back(jobStep1->oid()); +// if (fOid>=3000) +// cout << "Adding project step pColStep and pDictionaryStep to BPS" << endl; + } + else + { + PassThruStep* psth = dynamic_cast(jobStep1); + if (psth != 0) + { + pdsp = dynamic_cast(jobStep2); + fBPP->addProjectStep( *psth, *pdsp ); + //@Bug 961 + if ( !psth->isExeMgr()) + fBPP->setNeedRidsAtDelivery( true ); + projectOids.push_back(jobStep1->oid()); + colWidth = (psth->colType()).colWidth; +// if (fOid>=3000) +// cout << "Adding project step PassThruStep and pDictionaryStep to BPS" << endl; + } + } + } + else + { + pColStep* pcsp = dynamic_cast(jobStep1); + if (pcsp != 0) + { + fBPP->addProjectStep( *pcsp ); + //@Bug 961 + if ( !pcsp->isExeMgr()) + fBPP->setNeedRidsAtDelivery( true ); + colWidth = (pcsp->colType()).colWidth; + projectOids.push_back(jobStep1->oid()); +// if (fOid>=3000) +// cout << "Adding project step pColStep to BPS" << endl; + } + else + { + PassThruStep* passthru = dynamic_cast(jobStep1); + if (passthru!= 0) + { + fBPP->addProjectStep( *passthru ); + //@Bug 961 + if ( !passthru->isExeMgr()) + fBPP->setNeedRidsAtDelivery( true ); + colWidth = (passthru->colType()).colWidth; + projectOids.push_back(jobStep1->oid()); +// if (fOid>=3000) +// cout << "Adding project step PassThruStep to BPS" << endl; + } + else + { + DeliveryStep* ds = dynamic_cast(jobStep1); + if ( ds != 0 ) { +// if ( fOid>=3000) +// cout << "Adding DeliveryStep to BPS" << endl; + fBPP->addDeliveryStep( *ds ); + fTableName = ds->tableName(); + } + } + } + } + + if ( colWidth > fColWidth ) + { + //if ( fOid>=3000) + //cout << "colWidth resetted from " << fColWidth << " to " << colWidth << endl; + fColWidth = colWidth; + } +} + +void BatchPrimitiveStep::addFilter(int8_t COP, int64_t value, uint8_t roundFlag) +{ + int8_t tmp8; + int16_t tmp16; + int32_t tmp32; + + fFilterString << (uint8_t) COP; + fFilterString << roundFlag; + + // converts to a type of the appropriate width, then bitwise + // copies into the filter ByteStream + switch(fColType.colWidth) { + case 1: + tmp8 = value; + fFilterString << *((uint8_t *) &tmp8); + break; + case 2: + tmp16 = value; + fFilterString << *((uint16_t *) &tmp16); + break; + case 4: + tmp32 = value; + fFilterString << *((uint32_t *) &tmp32); + break; + case 8: + fFilterString << *((uint64_t *) &value); + break; + default: + ostringstream o; + + o << "BatchPrimitiveStep: CalpontSystemCatalog says OID " << fOid << + " has a width of " << fColType.colWidth; + throw runtime_error(o.str()); + } + + fFilterCount++; +} + +void BatchPrimitiveStep::storeCasualPartitionInfo() +{ + const vector& colCmdVec = fBPP->getFilterSteps(); + vector cpColVec; + vector numExtentsToCheck; + vector lbidListVec; + ColumnCommandJL* colCmd = 0; + uint firstColWidth = colCmdVec[0]->getWidth(); + + // ZZ debug -- please keep it for a couple of releases + // vector < vector > scanFs; + // cout << "storeCasualPartitionInfo" << endl; + + for (uint i = 0; i < colCmdVec.size(); i++) + { + colCmd = dynamic_cast(colCmdVec[i].get()); + if (!colCmd) + continue; + SP_LBIDList tmplbidList(new LBIDList(0)); + if (tmplbidList->CasualPartitionDataType(colCmd->getColType().colDataType, colCmd->getWidth())) + { + lbidListVec.push_back(tmplbidList); + cpColVec.push_back(colCmd); + int8_t num = 1; + if (firstColWidth > colCmd->getWidth()) + num = firstColWidth / colCmd->getWidth(); + else if (firstColWidth < colCmd->getWidth()) + { + num = (colCmd->getWidth() / firstColWidth); //both ars are unsigned, result is unsigned + num = -num; //make sure we get a signed result + } + numExtentsToCheck.push_back ( num ); + // debug + // cout << "col " << i << " num=" << (int)num << endl; + // vector scan; + // scan.assign(numExtents, true); + // scanFs.push_back(scan); + } + } + + //cout << "cp column number=" << cpColVec.size() << " 1st col extents size= " << scanFlags.size() + // << " fColWidth=" << firstColWidth << endl; + + if (cpColVec.size() == 0) + return; + + const bool ignoreCP = ((fTraceFlags & CalpontSelectExecutionPlan::IGNORE_CP) != 0); + + for (uint idx=0; idx getExtents()[idx].partition.cprange.isValid != BRM::CP_VALID || + lbidListVec[i]->CasualPartitionPredicate( + colCmd->getExtents()[idx].partition.cprange.lo_val, + colCmd->getExtents()[idx].partition.cprange.hi_val, + &(colCmd->getFilterString()), + colCmd->getFilterCount(), + colCmd->getColType(), + colCmd->getBOP()) || ignoreCP ) + { + scanFlags[idx] = true; + } + // if any colCmd gives a false, then this extent scanflag is false + if (!scanFlags[idx]) + { + //scanFs[i][idx] = false; // debug + break; + } + } + } + + // debug + /*for (uint i = 0; i < scanFs.size(); i++) + { + for (uint k = 0; k < scanFs[i].size(); k++) + cout << scanFs[i][k] << " "; + cout << endl; + } + for (uint i = 0; i < scanFlags.size(); i++) + cout << scanFlags[i] << " "; + cout << endl;*/ +} + +void BatchPrimitiveStep::startPrimitiveThread() +{ + pThread.reset(new boost::thread(BatchPrimitiveStepPrimitive(this))); +} + +void BatchPrimitiveStep::startAggregationThreads() +{ + for (uint i = 0; i < fNumThreads; i++) + fProducerThread[i].reset(new boost::thread(BatchPrimitiveStepAggregatores(this, i))); +} + +void BatchPrimitiveStep::startAggregationThread() +{ + cThread.reset(new boost::thread(BatchPrimitiveStepAggregator(this))); +} + +void BatchPrimitiveStep::serializeJoiner() +{ + ByteStream bs; + bool more = true; + + /* false from nextJoinerMsg means it's the last msg, + it's not exactly the exit condition*/ + while (more) { + more = fBPP->nextJoinerMsg(bs); + fDec->write(bs); + bs.restart(); + } +} + +void BatchPrimitiveStep::serializeJoiner(uint conn) +{ + ByteStream bs; + bool more = true; + + /* false from nextJoinerMsg means it's the last msg, + it's not exactly the exit condition*/ + while (more) { + more = fBPP->nextJoinerMsg(bs); + fDec->write(bs, conn); + bs.restart(); + } +} + +void BatchPrimitiveStep::run() +{ + fRunExecuted = true; + + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + std::string("BatchPrimitiveStep")); // step name + } + + //Set the input type + size_t sz = fInputJobStepAssociation.outSize(); + if ( sz > 0 ) + { + int ridListIdx = 0; + if (sz > 1) + ridListIdx = 1; + + const AnyDataListSPtr& dl = fInputJobStepAssociation.outAt(ridListIdx); + DataList_t* dlp = dl->dataList(); + DataList* strDlp = dl->stringDataList(); + if ( dlp ) + { + setRidList(dlp); + fifo = dl->fifoDL(); + if ( fifo ) + fInputType=FIFODATALIST; + else + fInputType=DATALIST; + } + else + { + setStrRidList( strDlp ); + strFifo = dl->stringDL(); + if ( strFifo ) + fInputType=STRINGFIFODATALIST; + else + fInputType=STRINGDATALIST; + } + } + + ByteStream bs; + + /* joiner needs to be set before the create msg is sent */ + if (doJoin && joiner->inPM()) + fBPP->useJoiner(joiner); + fDec->addDECEventListener(this); + fBPP->createBPP(bs); + try { + fDec->write(bs); + } + catch(std::exception& re) + { + cerr << "BatchPrimitiveStep::run() write(bs) in run: " << re.what() << endl; + catchHandler(re.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + + // bug 3141 + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + DataList_t* dlp = dl->dataList(); + StrDataList* strDlp = dl->stringDataList(); + FifoDataList *fifo = dl->fifoDL(); + StringFifoDataList *strFifo = dl->stringDL(); + TupleBucketDataList *tbdl = dl->tupleBucketDL(); + ZDL *zdl = dynamic_cast *>(dlp); + setEndOfInput(fifo, strFifo, strDlp, tbdl, zdl, dlp); + + return; + } + catch(...) + { + string msg("BatchPrimitiveStep::run() write(bs) in run threw an unknown exception "); + catchHandler(msg); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + + // bug 3141 + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + DataList_t* dlp = dl->dataList(); + StrDataList* strDlp = dl->stringDataList(); + FifoDataList *fifo = dl->fifoDL(); + StringFifoDataList *strFifo = dl->stringDL(); + TupleBucketDataList *tbdl = dl->tupleBucketDL(); + ZDL *zdl = dynamic_cast *>(dlp); + setEndOfInput(fifo, strFifo, strDlp, tbdl, zdl, dlp); + + return; + } + + BPPIsAllocated = true; + + try { + startPrimitiveThread(); + +/* + if (doJoin && joiner->inPM()) + cout << "BPS: inPM\n"; + else if (doJoin) + cout << "BPS: inUM\n"; +*/ + /* Do this in the send method maybe? */ + if (doJoin && joiner->inPM()) + serializeJoiner(); + } + catch(std::exception& re) + { + cerr << "BatchPrimitiveStep: startPrimitive threw an exception: " << re.what() << endl; + catchHandler(re.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + return; + } + catch(...) + { + string msg("BatchPrimitiveStep: startPrimitive threw an unknown exception "); + catchHandler(msg); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + return; + } + + // @bug 1293. setMultipleProducers() should be called only once. + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + DataList_t* dlp = dl->dataList(); + TupleBucketDataList *tbdl = dl->tupleBucketDL(); + BucketDL *bucket = dynamic_cast *>(dlp); + ZDL *zdl = dynamic_cast *>(dlp); + if (fNumThreads > 1 ) { + if ( bucket || zdl ) + { + dlp->setMultipleProducers(true); + } + if ( tbdl ) + { + tbdl->setMultipleProducers(true); + } + } + + if ( fOutputType != TABLE_BAND ) + { + try { + startAggregationThreads(); + } + catch(std::exception& re) + { + cerr << "BatchPrimitiveStep: startAggregation exception: " << re.what() << endl; + catchHandler(re.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + } + catch(...) + { + string msg("BatchPrimitiveStep: startAggregation threw an unknown exception "); + catchHandler(msg); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + } + } +} + +void BatchPrimitiveStep::join() +{ + if (fRunExecuted) + { + if (fOutputType == TABLE_BAND && msgsRecvd < msgsSent) { + // wake up the sending thread, it should drain the input dl and exit + mutex.lock(); //pthread_mutex_lock(&mutex); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); + mutex.unlock(); //pthread_mutex_unlock(&mutex); + // wait for the PM to return all results before destroying the BPPs + while (msgsRecvd + fDec->size(uniqueID) < msgsSent) + sleep(1); + } + + if (pThread.get()) + pThread->join(); + if ( fOutputType != TABLE_BAND && !fOutputJobStepAssociation.status() ) + { + for (uint i = 0; i < fNumThreads; i++) + fProducerThread[i]->join(); + } + + if (BPPIsAllocated) { + ByteStream bs; + fDec->removeDECEventListener(this); + fBPP->destroyBPP(bs); + try { + fDec->write(bs); + } + catch(std::exception& re) + { + cerr << "BatchPrimitiveStep: write(bs) in join: " << re.what() << endl; + catchHandler(re.what()); + } + catch(...) + { + string msg("BatchPrimitiveStep: write(bs) in join threw an unknown exception "); + catchHandler(msg); + } + BPPIsAllocated = false; + fDec->removeQueue(uniqueID); + joiner.reset(); + } + } +} + +void BatchPrimitiveStep::sendError(uint16_t status) +{ + ByteStream msgBpp; + fBPP->setCount ( 1 ); + fBPP->setStatus( status ); + fBPP->runErrorBPP(msgBpp); + fMsgBytesOut += msgBpp.lengthWithHdrOverhead(); + fDec->write(msgBpp); + fMsgBppsToPm++; + fBPP->reset(); + msgsSent++; + finishedSending = true; + condvar.notify_all(); //pthread_cond_broadcast(&condvar); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); +} + + +void BatchPrimitiveStep::setRidList(DataList *dl) +{ + ridList = dl; +} + +void BatchPrimitiveStep::setStrRidList(DataList *strDl) +{ + strRidList = strDl; +} + +void BatchPrimitiveStep::setBOP(int8_t b) +{ + fBOP = b; +} + +void BatchPrimitiveStep::setOutputType(BPSOutputType outputType) +{ + fOutputType = outputType; + fBPP->setOutputType(outputType ); +} + +void BatchPrimitiveStep::setBppStep() +{ + fBPP->setStepID( fStepId ); +// if ( fOid >= 3000) +// cout << "fBPP: set step to " << fStepId << endl; +} + +int BatchPrimitiveStep::getIterator() +{ + int it=-1; + switch ( fInputType ){ + case DATALIST: it = ridList->getIterator(); break; + case FIFODATALIST: it = fifo->getIterator(); break; + case STRINGDATALIST: it = strRidList->getIterator(); break; + case STRINGFIFODATALIST: it = strFifo->getIterator(); break; + default: + throw runtime_error("BatchPrimitiveStep: invalid input data type!"); + } + return it; +} + +inline bool BatchPrimitiveStep::getNextElement(const int it) +{ + bool more = false; + switch ( fInputType ){ + case DATALIST: + more = ridList->next(it, &e); + rw.count = 1; + break; + case FIFODATALIST: + more = fifo->next(it, &rw); + break; + case STRINGDATALIST: + more = strRidList->next(it, &strE); + strRw.count = 1; + break; + case STRINGFIFODATALIST: + more = strFifo->next(it, &strRw); + break; + default: + throw runtime_error("BatchPrimitiveStep: invalid input data type!"); + } + return more; +} + +inline uint64_t BatchPrimitiveStep::getAbsRid( uint64_t i ) +{ + uint64_t absRid; + switch ( fInputType ){ + case DATALIST: + absRid = e.first; + break; + case FIFODATALIST: + absRid = rw.et[i].first; + break; + case STRINGDATALIST: + absRid = strE.first; + break; + case STRINGFIFODATALIST: + absRid = strRw.et[i].first; + break; + default: + throw runtime_error("BatchPrimitiveStep: invalid input data type!"); + } + return absRid; +} + +inline uint64_t BatchPrimitiveStep::getRowCount() +{ + uint64_t rwCount; + if ( fInputType == DATALIST || fInputType == FIFODATALIST ) + rwCount = rw.count; + else + rwCount = strRw.count; + + return rwCount; +} + +inline void BatchPrimitiveStep::addElementToBPP(uint64_t i, uint dbroot) +{ + switch ( fInputType ){ + case DATALIST: + fBPP->addElementType(e, dbroot); + break; + case FIFODATALIST: + fBPP->addElementType(rw.et[i], dbroot); + break; + case STRINGDATALIST: + fBPP->addElementType(strE, dbroot); + break; + case STRINGFIFODATALIST: + fBPP->addElementType(strRw.et[i], dbroot); + break; + default: + throw runtime_error("BatchPrimitiveStep: invalid input data type!"); + } +} + +const TableBand BatchPrimitiveStep::nextBand() +{ + ByteStream bs; + TableBand tb; + + nextBand(bs); + tb.unserialize(bs); + return tb; +} + + uint BatchPrimitiveStep::nextBand ( messageqcpp::ByteStream &bs ) +{ + int64_t min; + int64_t max; + uint64_t lbid; + uint32_t cachedIO; + uint32_t physIO; + uint32_t touchedBlocks; + bool validCPData; + boost::shared_ptr bsIn; + uint rows = 0; + +again: +try +{ + while ( msgsRecvd == msgsSent && !finishedSending + && !fInputJobStepAssociation.status()) + usleep ( 1000 ); + + if ((msgsRecvd == msgsSent && finishedSending) || fInputJobStepAssociation.status()) + { + bsIn.reset(new ByteStream()); +// if ( fOid>=3000) +// cout << "BPS: sending last band for Table OID " << fTableOid << endl; + if ( fOid>=3000 ) dlTimes.setLastReadTime(); + if ( fOid>=3000 ) dlTimes.setEndOfInputTime(); + if ( fBPP->getStatus() || 0 < fOutputJobStepAssociation.status() ) + { + rows = fBPP->getErrorTableBand(fOutputJobStepAssociation.status(), &bs ); + if (!fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(fBPP->getStatus()); + } + else + { + rows = fBPP->getTableBand ( *bsIn, &bs, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks ); + } + ByteStream dbs; + fDec->removeDECEventListener(this); + fBPP->destroyBPP(dbs); + fDec->write(dbs); + BPPIsAllocated = false; + fDec->removeQueue(uniqueID); + joiner.reset(); + + if ( fOid>=3000 ) + { + time_t t = time ( 0 ); + char timeString[50]; + ctime_r ( &t, timeString ); + timeString[strlen ( timeString )-1 ] = '\0'; + FifoDataList* pFifo = 0; + uint64_t totalBlockedReadCount = 0; + uint64_t totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for ( size_t iDataList=0; iDataListfifoDL(); + if ( pFifo ) + { + totalBlockedReadCount += pFifo->blockedReadCount(); + } + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for ( size_t iDataList=0; iDataListfifoDL(); + if ( pFifo ) + { + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + } + + //...Roundoff msg byte counts to nearest KB for display + uint64_t msgBytesInKB = fMsgBytesIn >> 10; + uint64_t msgBytesOutKB = fMsgBytesOut >> 10; + if (fMsgBytesIn & 512) + msgBytesInKB++; + if (fMsgBytesOut & 512) + msgBytesOutKB++; + + if ( traceOn() ) + { + ostringstream logStr; + logStr << "ses:" << fSessionId << " st: " << fStepId << + " finished at "<< timeString << "; total rows returned-" << rowsReturned << + " physicalIO-" << fPhysicalIO << " cachedIO-" << fCacheIO << + "; MsgsSent-" << fMsgBppsToPm << "; MsgsRvcd-" << msgsRecvd << + "; BlocksTouched-"<< fBlockTouched << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << + "; output size-" << rowsReturned << endl << + "\tPartitionBlocksEliminated-" << fNumBlksSkipped << + "; MsgBytesIn-" << msgBytesInKB << "KB" << + "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + ";\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; + logEnd ( logStr.str().c_str() ); + syslogReadBlockCounts ( 16, // exemgr sybsystem + fPhysicalIO, // # blocks read from disk + fCacheIO, // # blocks read from cache + fNumBlksSkipped ); // # casual partition block hits + syslogProcessingTimes ( 16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstInsertTime(), // first datalist write + dlTimes.EndOfInputTime() ); // last (endOfInput) datalist write + syslogEndStep ( 16, // exemgr subsystem + totalBlockedReadCount, // blocked datalist input + totalBlockedWriteCount, // blocked datalist output + fMsgBytesIn, // incoming msg byte count + fMsgBytesOut ); // outgoing msg byte count + } + } + + if ( fOid>=3000 && ( ffirstStepType == SCAN ) ) { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateAllPartitionInfo(); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } + } + else + { + if ( fOid>=3000 && dlTimes.FirstReadTime().tv_sec ==0 ) + dlTimes.setFirstReadTime(); + fDec->read(uniqueID, bsIn ); + /* XXXPAT: Need to check for 0-length BS here */ + firstRead = false; + fMsgBytesIn += bsIn->lengthWithHdrOverhead(); + mutex.lock(); //pthread_mutex_lock(&mutex); + msgsRecvd++; + //@Bug 1424, 1298 + if ( (sendWaiting) && ( (msgsSent - msgsRecvd) <= (fMaxOutstandingRequests * (extentSize / fColWidth)) ) ) + { + condvarWakeupProducer.notify_one(); //pthread_cond_signal(&condvarWakeupProducer); + THROTTLEDEBUG << "nextBand wakes up sending side .. " << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; + } + mutex.unlock(); //pthread_mutex_unlock(&mutex); + + ISMPacketHeader *hdr = (ISMPacketHeader*)bsIn->buf(); + + // @bug 488. 0 length bs indicated PM connection lost + if (bsIn->length() == 0 || 0 < hdr->Status || 0 < fBPP->getStatus() || 0 < fOutputJobStepAssociation.status() ) + { + if (bsIn->length() == 0) + fOutputJobStepAssociation.status(primitiveServerErr); + if (!fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(0 < hdr->Status ? hdr->Status : fBPP->getStatus()); + mutex.lock(); //pthread_mutex_lock(&mutex); + if (!fSwallowRows) + { + msgsRecvd = msgsSent; + finishedSending = true; + rows = 0; //send empty message to indicate finished. + } + die = true; + condvar.notify_all(); //pthread_cond_broadcast(&condvar); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); + //cout << "BPS receive signal " << fStepId << endl; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + } + else + { + rows = fBPP->getTableBand ( *bsIn, &bs, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks ); + } + fPhysicalIO += physIO; + fCacheIO += cachedIO; + fBlockTouched += touchedBlocks; + + if ( fOid>=3000 && ( ffirstStepType == SCAN ) && validCPData ) + { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateMinMax ( min, max, lbid, fColType.colDataType ); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } + rowsReturned += rows; + if ( rows == 0 ) + { + bs.restart(); + goto again; + } + } +// return rows; +}//try +catch(const LargeDataListExcept& ex) +{ + catchHandler(ex.what(), fSessionId); + fOutputJobStepAssociation.status(batchPrimitiveStepLargeDataListFileErr); + return fBPP->getErrorTableBand(batchPrimitiveStepErr, &bs ); +} +catch(const std::exception& ex) +{ + catchHandler(ex.what(), fSessionId); + fOutputJobStepAssociation.status(batchPrimitiveStepErr); + return fBPP->getErrorTableBand(batchPrimitiveStepErr, &bs ); +} +catch(...) +{ + catchHandler("BatchPrimitiveStep next band caught an unknown exception", fSessionId); + fBPP->getErrorTableBand(batchPrimitiveStepErr, &bs ); + fOutputJobStepAssociation.status(batchPrimitiveStepErr); +} + return rows; +} + +void BatchPrimitiveStep::sendPrimitiveMessages() +{ + int it = -1; + bool more = false; + uint64_t absoluteRID = 0; + int64_t msgLargeBlock = -1; + int64_t nextLargeBlock = -1; + int64_t msgLogicalExtent = -1; + int64_t nextLogicalExtent = -1; + const uint logicBlockShift = 13; + ByteStream msgBpp; + int msgsSkip=0; + bool scan=true;; + bool scanThisBlock=true; + + int64_t Min=0; + int64_t Max=0; + int64_t SeqNum=0; + bool MinMaxValid=true; + + if (0 < fInputJobStepAssociation.status()) + { + finishedSending = true; + return; + } + +try +{ + // @bug 1098 + if (fOid >= 3000 && !fIsProjectionOnly ) + storeCasualPartitionInfo(); + + // Get the starting DBRoot for the column. We want to send use the starting DBRoot to send the right messages + // to the right PMs. If the first extent, is on DBRoot1, the message will go to the first connection. If it's + // DBRoot2, the first extent will get sent to the second connection, and so on. This is a change for the + // multiple files per OID enhancement as a precurser to shared nothing. + uint16_t startingDBRoot = 1; + uint32_t startingPartitionNumber = 0; + oam::OamCache *oamCache = oam::OamCache::makeOamCache(); + boost::shared_ptr > dbRootPMMap = oamCache->getDBRootToPMMap(); + + dbrm.getStartExtent(fOid, startingDBRoot, startingPartitionNumber); + + if ( ffirstStepType == SCAN ) + { + LBIDRange_v::iterator it; + uint32_t extentIndex; + uint64_t fbo; + bool cpPredicate = true; + bool firstSend = true; + //@Bug 913 + if (fOid>=3000 && dlTimes.FirstReadTime().tv_sec==0) { + dlTimes.setFirstReadTime(); + } + for (it = lbidRanges.begin(); it != lbidRanges.end() && !die; it++) + { + BRM::LBID_t lbid = (*it).start; + + fbo = getFBO(lbid); + if (hwm < fbo) + continue; + + extentIndex = fbo >> divShift; + if (fOid >= 3000) + { + // @bug 1297. getMinMax to prepare partition vector should consider + // cpPredicate. only scanned lbidrange will be pushed into the vector. + + cpPredicate = (scanFlags[extentIndex] != 0); + // @bug 1090. cal getMinMax to prepare the CP vector and update later + if (lbidList->CasualPartitionDataType(fColType.colDataType, fColType.colWidth) && cpPredicate) { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + MinMaxValid = lbidList->GetMinMax(Min, Max, SeqNum, + lbid, &extents); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } + } + + + if (cpPredicate==false){ //don't scan this extent + //...Track the number of LBIDs we skip due to Casual Partioning. + //...We use the same equation we use to initialize remainingLbids + //...in the code that follows down below this. + fNumBlksSkipped += ( (hwm > (fbo + it->size - 1)) ? + (it->size) : (hwm - fbo + 1) ); + continue; + } + + if (dbRootPMMap->find(extents[extentIndex].dbRoot) == dbRootPMMap->end()) + throw IDBExcept(ERR_DATA_OFFLINE); + + LBID_t msgLbidStart = it->start; + u_int32_t remainingLbids = 0; + u_int32_t lbidToBeSent = + ( (hwm > (fbo + it->size - 1)) ? (it->size) : (hwm - fbo + 1) ); + u_int32_t msgLbidCount = 0; + u_int32_t msgLbidCountBatch = 0; + u_int32_t totalLbid = 0; + u_int32_t requestLbids = 0; + u_int32_t sentLbids = 0; + u_int32_t maxOutstandingLbids = 0; + if ( lbidToBeSent % fColType.colWidth == 0 ) + totalLbid= lbidToBeSent/fColType.colWidth; + else + totalLbid= lbidToBeSent/fColType.colWidth + 1; + + remainingLbids = totalLbid; +// cout << "fColWidth=" << fColWidth<< endl; +// msgLbidCount = extentSize/fColWidth; + + // @bug 977 + // @bug 1264. Changed the number of logical blocks per BPS scan to be configurable based on the LogicalBlocksPerScan Calpont.xml + // entry. + // msgLbidCount = extentSize/8; + if ( fColWidth == 0 ) + fColWidth = fColType.colWidth; + requestLbids = fRequestSize * (extentSize / fColWidth); + msgLbidCount =(requestLbids /fProcessorThreadsPerScan)/ fRequestSize; + maxOutstandingLbids = fMaxOutstandingRequests * (extentSize / fColWidth); + while ( remainingLbids > 0 && 0 == fInputJobStepAssociation.status() && !die) + { + msgLbidCountBatch = msgLbidCount; + if ( remainingLbids < requestLbids) + requestLbids = remainingLbids; + + //@Bug 1424,1298Send one requestSize a batch + while ( sentLbids < requestLbids ) + { + if ( (requestLbids - sentLbids) < msgLbidCountBatch ) + msgLbidCountBatch = requestLbids - sentLbids; + + if ( fOid>=3000) { + THROTTLEDEBUG << "st:" << fStepId << " sending msgLbidStart=" << msgLbidStart << " msgLbidCount="<< msgLbidCountBatch<< + " colWidth=" << fColWidth <setLBID( msgLbidStart, extents[extentIndex].dbRoot); + idbassert(msgLbidCountBatch>0); + fBPP->setCount ( msgLbidCountBatch ); + fBPP->runBPP(msgBpp, (*dbRootPMMap)[extents[extentIndex].dbRoot]); + fMsgBytesOut += msgBpp.lengthWithHdrOverhead(); + //cout << "Requesting " << msgLbidCount << " logical blocks at LBID " << msgLbidStart; + //cout << " sending fOid " << fOid << endl; +#ifdef SHARED_NOTHING_DEMO + fDec->write(msgBpp, fOid); +#else + fDec->write(msgBpp); +#endif + fMsgBppsToPm++; + + msgBpp.restart(); + fBPP->reset(); + firstSend = false; + msgLbidStart += msgLbidCountBatch * fColType.colWidth; + sentLbids += msgLbidCountBatch; + } + mutex.lock(); //pthread_mutex_lock(&mutex); + msgsSent += sentLbids; + + if (recvWaiting) + condvar.notify_all(); //pthread_cond_broadcast(&condvar); //signal consumer to resume + + //Bug 939 + while (!fSwallowRows && + (( msgsSent - msgsRecvd) > maxOutstandingLbids) && !die) + { + sendWaiting = true; + THROTTLEDEBUG << "BPS send thread wait on step " << fStepId << " oid = " << fOid + << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; + condvarWakeupProducer.wait(mutex); //pthread_cond_wait ( &condvarWakeupProducer, &mutex ); + sendWaiting = false; + } + mutex.unlock(); //pthread_mutex_unlock(&mutex); + sentLbids = 0; + remainingLbids -= requestLbids; + } + } + } + else if ( ffirstStepType == COLSTEP ) + { + //The presence of more than 1 input DL means we (probably) have a pDictionaryScan step feeding this step + // a list of tokens to get the rids for. Convert the input tokens to a filter string. We also have a ridwhile (more) more = getNextElement(it); + // list as the second input dl + //cout << toString() << endl; + //if ( fOid >=3000 ) + // cout << "SES:" << fSessionId << " ST:" << fStepId << + // " total size = " << ridList->totalSize() << endl; + + if (fInputJobStepAssociation.outSize() > 1) + { + addFilters(); + if (fTableOid >= 3000) + cout << toString() << endl; + //If we got no input rids (as opposed to no input DL at all) then there were no matching rows from + // the previous step, so this step should not return any rows either. This would be the case, for + // instance, if P_NAME LIKE '%xxxx%' produced no signature matches. + if (fFilterCount == 0) + { + goto done; + } + } + if ( fColWidth == 0 ) + fColWidth = fColType.colWidth; + it = getIterator( ); + more = getNextElement( it ); + if (fOid>=3000 && dlTimes.FirstReadTime().tv_sec==0) + dlTimes.setFirstReadTime(); + absoluteRID = getAbsRid ( 0 ); + + if (more && !fIsProjectionOnly) + scan = scanit(absoluteRID); + + scanThisBlock = scan; + msgLargeBlock = absoluteRID >> logicBlockShift; + nextLargeBlock = msgLargeBlock; + msgLogicalExtent = msgLargeBlock >> LOGICAL_EXTENT_CONVERTER; + nextLogicalExtent = msgLogicalExtent; + uint numSentExtent = 0; + while (more && !die) { + if (0 < fInputJobStepAssociation.status()) + { + sendError(fInputJobStepAssociation.status()); + while (more) more = getNextElement(it ); + break; + } + uint64_t rwCount; + rwCount = getRowCount(); + + for (uint64_t i = 0; i < rwCount && !die; ++i) { + absoluteRID = getAbsRid(i); + nextLargeBlock = absoluteRID >> logicBlockShift; + if (!fIsProjectionOnly) + scan = scanit(absoluteRID); + if (msgLargeBlock == nextLargeBlock) { + if (scanThisBlock) { + addElementToBPP(i, startingDBRoot); + ridsRequested++; + } + // @bug 1301. msgsSkip should not increment for every skipped row +// else +// msgsSkip++; + } + else { + if (fBPP->getRidCount()) { + fBPP->runBPP(msgBpp, startingDBRoot); + fMsgBytesOut += msgBpp.lengthWithHdrOverhead(); + +#ifdef SHARED_NOTHING_DEMO + fDec->write(msgBpp, fOid); +#else + fDec->write(msgBpp); +#endif + mutex.lock(); //pthread_mutex_lock(&mutex); + fMsgBppsToPm = ++msgsSent; + + if (recvWaiting) + condvar.notify_all(); //pthread_cond_broadcast(&condvar); //signal consumer to resume + mutex.unlock(); //pthread_mutex_unlock(&mutex); + msgBpp.restart(); + fBPP->reset(); + } + scanThisBlock = scan; + msgLargeBlock = nextLargeBlock; + nextLogicalExtent = msgLargeBlock >> LOGICAL_EXTENT_CONVERTER; + if ( fOid >= 3000 ) + THROTTLEDEBUG << "msgLogicalExtent = " << msgLogicalExtent << " nextLogicalExtent = " << nextLogicalExtent << endl; + if (( nextLogicalExtent != msgLogicalExtent ) && ( ++numSentExtent == fRequestSize ) ) + { + mutex.lock(); //pthread_mutex_lock(&mutex); + //Bug 939,1424,1298 + while (!fSwallowRows && + (( msgsSent - msgsRecvd) > (fMaxOutstandingRequests * (extentSize / fColWidth ))) && !die) + { + sendWaiting = true; + THROTTLEDEBUG << "BPS send thread wait st:" << fStepId + << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; + condvarWakeupProducer.wait(mutex); //pthread_cond_wait ( &condvarWakeupProducer, &mutex ); + sendWaiting = false; + } + mutex.unlock(); //pthread_mutex_unlock(&mutex); + numSentExtent = 0; + msgLogicalExtent = nextLogicalExtent; + } + + if (scanThisBlock) { + addElementToBPP(i, startingDBRoot); + ridsRequested++; + } + else + msgsSkip++; + } + } + + more = getNextElement(it); + if (!more && !die && fBPP->getRidCount() > 0) { + //send last message + fBPP->runBPP(msgBpp, startingDBRoot); + fMsgBytesOut += msgBpp.lengthWithHdrOverhead(); +#ifdef SHARED_NOTHING_DEMO + fDec->write(msgBpp, fOid); +#else + fDec->write(msgBpp); +#endif + mutex.lock(); //pthread_mutex_lock(&mutex); + fMsgBppsToPm = ++msgsSent; + if (recvWaiting) + condvar.notify_all(); //pthread_cond_broadcast(&condvar); //signal consumer to resume + mutex.unlock(); //pthread_mutex_unlock(&mutex); + fBPP->reset(); + } + } + //cout << "st: "<< fStepId << " requested " << ridsRequested << endl; + } + + if (fOid>=3000) dlTimes.setLastReadTime(); +done: + /* If the query was aborted and there's an input datalist, drain it to make + sure the producer finishes too. */ + if (more && die && ffirstStepType != SCAN) { + while (more) + more = getNextElement(it); + } + + mutex.lock(); //pthread_mutex_lock(&mutex); + finishedSending = true; + if (recvWaiting) + condvar.notify_all(); //pthread_cond_broadcast(&condvar); //signal consumer to resume + mutex.unlock(); //pthread_mutex_unlock(&mutex); + msgBpp.reset(); + //if ( fOid >=3000 ) + // cout << "st: "<< fStepId << " requested " << ridsRequested << endl; + + //...Track the number of LBIDs we skip due to Casual Partioning. + fNumBlksSkipped += msgsSkip; +} // try +catch(const std::exception& ex) +{ + finishedSending = true; + msgBpp.reset(); + sendError(batchPrimitiveStepErr); + processError(ex.what(), batchPrimitiveStepErr, "BatchPrimitiveStep::SendPrimitiveMessages()"); +} +catch(...) +{ + finishedSending = true; + msgBpp.reset(); + sendError(batchPrimitiveStepErr); + processError("unknown", batchPrimitiveStepErr, "BatchPrimitiveStep::receivePrimitiveMessages()"); +} +} + +struct CPInfo { + CPInfo(int64_t MIN, + int64_t MAX, + uint64_t l) : + min(MIN), + max(MAX), + LBID(l) { }; + int64_t min; + int64_t max; + uint64_t LBID; +}; + +void BatchPrimitiveStep::receivePrimitiveMessages() +{ + int64_t ridResults = 0; + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + DataList_t* dlp = dl->dataList(); + StrDataList* strDlp = dl->stringDataList(); + FifoDataList *fifo = dl->fifoDL(); + StringFifoDataList *strFifo = dl->stringDL(); + TupleBucketDataList *tbdl = dl->tupleBucketDL(); + UintRowGroup rw; + uint i = 0, size, vecSize; + vector > bsv; + std::vector outBpp; + std::vector strOutBpp; + std::vector outTp; + int64_t min; + int64_t max; + uint64_t lbid; + uint32_t cachedIO; + uint32_t physIO; + uint32_t touchedBlocks; + bool validCPData; + + uint16_t error = fInputJobStepAssociation.status(); +try +{ + while (! error) { + // sync with the send side + while (!finishedSending && msgsSent == msgsRecvd) + usleep(2000); + + if (msgsSent == msgsRecvd && finishedSending) { + break; + } + // do the recv + fDec->read_all(uniqueID, bsv); + size = bsv.size(); + mutex.lock(); //pthread_mutex_lock(&mutex); + msgsRecvd+= size; + if ( (sendWaiting) && ( (msgsSent - msgsRecvd) <= ( fMaxOutstandingRequests * (extentSize / fColWidth) ) ) ) + { + condvarWakeupProducer.notify_one(); //pthread_cond_signal(&condvarWakeupProducer); + THROTTLEDEBUG << "receivePrimitiveMessages wakes up sending side .. " << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; + } + mutex.unlock(); //pthread_mutex_unlock(&mutex); + for (i = 0; i < size && !die; i++) { + //Order the message if needed + //const ByteStream::byte* bsp = bsv[i].buf(); + ByteStream* bs = bsv[i].get(); + ISMPacketHeader *ism = (ISMPacketHeader*)(bs->buf()); + if (0 < ism->Status) + { + fOutputJobStepAssociation.status(ism->Status); + error = ism->Status; + break; + } + fMsgBytesIn += bs->lengthWithHdrOverhead(); + + switch (fOutputType) { + case BPS_ELEMENT_TYPE: + uint16_t preJoinRidCount; + + outBpp.clear(); + fBPP->getElementTypes ( *bs, &outBpp, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks, &preJoinRidCount); + vecSize = outBpp.size(); + fPhysicalIO += physIO; + fCacheIO += cachedIO; + fBlockTouched += touchedBlocks; + ridResults += preJoinRidCount; + for ( uint j=0; jinPM()) { + if (!joiner->match(outBpp[j])) + continue; + } + else + if (outBpp[j].first & joiner::Joiner::MSB) { + // use joiner to mark the small side matches + joiner->mark(outBpp[j]); + continue; + } + } + + if (fifo) + { + rw.et[rw.count++] = outBpp[j]; + if (rw.count == rw.ElementsPerGroup) + { + fifo->insert(rw); + rw.count = 0; + } + } + else + { + dlp->insert(outBpp[j]); + } + } + break; + case STRING_ELEMENT_TYPE: + strOutBpp.clear(); + fBPP->getStringElementTypes( *bs, &strOutBpp, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks); + vecSize = strOutBpp.size(); + ridResults += vecSize; + fPhysicalIO += physIO; + fCacheIO += cachedIO; + fBlockTouched += touchedBlocks; + for ( uint j=0; jinsert(strRw); + strRw.count = 0; + } + } + else + { + strDlp->insert(strOutBpp[j]); + } + } + break; + + default: throw logic_error("BPS::receivePrimitiveMessages(): Unknown output type"); + } + + if (fOid >= 3000 && ( ffirstStepType == SCAN ) && validCPData ) { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateMinMax(min, max, lbid, fColType.colDataType); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } + } + } + // done reading +} // try +catch(const LargeDataListExcept& ex) +{ + processError(ex.what(), batchPrimitiveStepLargeDataListFileErr, "BatchPrimitiveStep::receivePrimitiveMessages()"); +} +catch(const std::exception& ex) +{ + processError(ex.what(), batchPrimitiveStepErr, "BatchPrimitiveStep::receivePrimitiveMessages()"); +} +catch(...) +{ + processError("unknown", batchPrimitiveStepErr, "BatchPrimitiveStep::receivePrimitiveMessages()"); +} + + if (fifo && rw.count > 0) + fifo->insert(rw); + + if (strFifo && strRw.count > 0) + strFifo->insert(strRw); + + if (fOid>=3000 && dlTimes.FirstReadTime().tv_sec==0) { + dlTimes.setFirstReadTime(); + dlTimes.setLastReadTime(); + dlTimes.setFirstInsertTime(); + } + if (fOid>=3000) dlTimes.setEndOfInputTime(); + + ByteStream bs; + fDec->removeDECEventListener(this); + fBPP->destroyBPP(bs); + fDec->write(bs); + BPPIsAllocated = false; + fDec->removeQueue(uniqueID); + joiner.reset(); + + if (fifo) + fifo->endOfInput(); + else if ( strFifo ) + strFifo->endOfInput(); + else if ( strDlp ) + strDlp->endOfInput(); + else if ( tbdl ) + tbdl->endOfInput(); + else + dlp->endOfInput(); + + //...Print job step completion information + if (fTableOid >= 3000) { + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + timeString[strlen(timeString)-1 ] = '\0'; + + FifoDataList* pFifo = 0; + uint64_t totalBlockedReadCount = 0; + uint64_t totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + { + totalBlockedReadCount += pFifo->blockedReadCount(); + } + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + { + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + } + + //...Roundoff msg byte counts to nearest KB for display + uint64_t msgBytesInKB = fMsgBytesIn >> 10; + uint64_t msgBytesOutKB = fMsgBytesOut >> 10; + if (fMsgBytesIn & 512) + msgBytesInKB++; + if (fMsgBytesOut & 512) + msgBytesOutKB++; + + // @bug 828 + if (fifo) + fifo->totalSize(ridResults); + + if (traceOn()) + { + ostringstream logStr; + logStr << "ses:" << fSessionId << " st: " << fStepId<<" finished at "<< + timeString << "; PhyI/O-" << fPhysicalIO << "; CacheI/O-" << + fCacheIO << "; MsgsSent-" << fMsgBppsToPm << "; MsgsRvcd-" << msgsRecvd << + "; BlocksTouched-"<< fBlockTouched << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << + "; output size-" << ridResults << endl << + "\tPartitionBlocksEliminated-" << fNumBlksSkipped << + "; MsgBytesIn-" << msgBytesInKB << "KB" << + "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime())<< "s" + << endl << "\tJob completion status " << fInputJobStepAssociation.status() << endl; + + logEnd(logStr.str().c_str()); + + syslogReadBlockCounts(16, // exemgr sybsystem + fPhysicalIO, // # blocks read from disk + fCacheIO, // # blocks read from cache + fNumBlksSkipped); // # casual partition block hits + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstInsertTime(), // first datalist write + dlTimes.EndOfInputTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + totalBlockedReadCount, // blocked datalist input + totalBlockedWriteCount, // blocked datalist output + fMsgBytesIn, // incoming msg byte count + fMsgBytesOut); // outgoing msg byte count + } + } + + if (fOid >=3000 && ( ffirstStepType == SCAN )) { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateAllPartitionInfo(); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } +} + +void BatchPrimitiveStep::receiveMultiPrimitiveMessages(uint threadID) +{ + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + DataList_t* dlp = dl->dataList(); + StrDataList* strDlp = dl->stringDataList(); + FifoDataList *fifo = dl->fifoDL(); + StringFifoDataList *strFifo = dl->stringDL(); + TupleBucketDataList *tbdl = dl->tupleBucketDL(); + BucketDL *bucket = dynamic_cast *>(dlp); + ZDL *zdl = dynamic_cast *>(dlp); + UintRowGroup rw; + uint i = 0, size = 0, vecSize = 0; + vector > bsv; + vector elementVec; + vector strElementVec; + std::vector outTp; + std::vector outBpp; + std::vector strOutBpp; + bool validCPData; + int64_t min; + int64_t max; + uint64_t lbid; + vector cpv; + uint32_t cachedIO; + uint32_t physIO; + uint32_t touchedBlocks; + uint64_t msgBytesIn_Thread = 0; + uint32_t cachedIO_Thread = 0; + uint32_t physIO_Thread = 0; + uint32_t touchedBlocks_Thread = 0; + int64_t ridsReturned_Thread = 0; + bool lastThread = false; + bool caughtError = false; + uint errorTimeout = 0; + bool didEOF = false; + +try +{ +// if (! fInputJobStepAssociation.status() ) + mutex.lock(); //pthread_mutex_lock(&mutex); +// while (! fInputJobStepAssociation.status() ) { + while (1) { + // sync with the send side + while (!finishedSending && msgsSent == msgsRecvd) { + recvWaiting++; + condvar.wait(mutex); //pthread_cond_wait(&condvar, &mutex); + recvWaiting--; + } + + if (msgsSent == msgsRecvd && finishedSending) { + break; + } + + // do the recv + + fDec->read_some(uniqueID, fNumThreads, bsv); + size = bsv.size(); + msgsRecvd+= size; + //@Bug 1424,1298 + if ( (sendWaiting) && ( (msgsSent - msgsRecvd) <= ( fMaxOutstandingRequests * (extentSize / fColWidth) ) ) ) + { + condvarWakeupProducer.notify_one(); //pthread_cond_signal(&condvarWakeupProducer); + THROTTLEDEBUG << "receiveMultiPrimitiveMessages wakes up sending side .. " << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; + } + + /* If there's an error and the joblist is being aborted, don't + sit around forever waiting for responses. Exit 30 secs after + the last msg from the PMs. */ + if (fInputJobStepAssociation.status() != 0 || die) { + mutex.unlock(); //pthread_mutex_unlock(&mutex); + // thread 0 stays, the rest finish & exit to allow a quicker EOF + if (threadID != 0) + break; + else if (!didEOF) { + didEOF = true; + while (recvExited < fNumThreads - 1) + sleep(1); + if (fifo) + fifo->endOfInput(); + else if ( strFifo ) + strFifo->endOfInput(); + else if ( strDlp ) + strDlp->endOfInput(); + else if ( tbdl ) + tbdl->endOfInput(); + else + dlp->endOfInput(); + } + if (size != 0) // got something, reset the timer + errorTimeout = 0; + sleep(1); + mutex.lock(); //pthread_mutex_lock(&mutex); + if (++errorTimeout == 30) + break; + continue; + } + + if (size == 0) { + mutex.unlock(); //pthread_mutex_unlock(&mutex); + usleep(1000); + mutex.lock(); //pthread_mutex_lock(&mutex); + continue; + } + mutex.unlock(); //pthread_mutex_unlock(&mutex); + for (i = 0; i < size; i++) { + ByteStream* bs = bsv[i].get(); + + // @bug 488. one PrimProc node is down. error out + //An error condition. We are not going to do anymore. + ISMPacketHeader *hdr = (ISMPacketHeader*)(bs->buf()); + if (bs->length() == 0) + { + mutex.lock(); //pthread_mutex_lock(&mutex); + fOutputJobStepAssociation.status(primitiveServerErr); + die = true; + condvar.notify_all(); //pthread_cond_broadcast(&condvar); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); + //cout << "BPS receive signal " << fStepId << endl; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + break; + } + if (0 < hdr->Status) + { + mutex.lock(); //pthread_mutex_lock(&mutex); + fOutputJobStepAssociation.status(hdr->Status); + die = true; + condvar.notify_all(); //pthread_cond_broadcast(&condvar); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); + //cout << "DEC receive signal" << endl; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + break; + } + + msgBytesIn_Thread += bs->lengthWithHdrOverhead(); + vecSize = 0; + switch (fOutputType) { + case BPS_ELEMENT_TYPE: + uint16_t preJoinRidCount; + + outBpp.clear(); + fBPP->getElementTypes ( *bs, &outBpp, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks, &preJoinRidCount); + ridsReturned_Thread += preJoinRidCount; + if (doJoin) + { + for (uint j=0, ssize = outBpp.size(); + jinPM()) + { + if (!joiner->match(outBpp[j])) + continue; + } + else + if (outBpp[j].first & joiner::Joiner::MSB) + { + // use joiner to mark the small side matches + joiner->mark(outBpp[j]); + continue; + } + + elementVec.push_back(outBpp[j]); + vecSize++; + } + } + else + { + vecSize = outBpp.size(); + //Push the elements into a tmp vector + elementVec.insert(elementVec.end(), outBpp.begin(), outBpp.end()); + } + break; + case STRING_ELEMENT_TYPE: + strOutBpp.clear(); + fBPP->getStringElementTypes( *bs, &strOutBpp, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks); + vecSize = strOutBpp.size(); + //Push the elements into a tmp vector + strElementVec.insert(strElementVec.end(), strOutBpp.begin(), strOutBpp.end()); + break; + case TUPLE: + fBPP->getTuples( *bs, &outTp, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks); + vecSize = outTp.size(); + tbdl->insert(outTp); + outTp.clear(); + break; + case TABLE_BAND: + break; + + default: throw logic_error("BPS::receivePrimitiveMessages(): Unknown output type"); + } + //@Bug 1099 + /* Hack to get different ridcount reporting when there's a join involved */ + if (fOutputType != BPS_ELEMENT_TYPE) + ridsReturned_Thread += vecSize; + cachedIO_Thread += cachedIO; + physIO_Thread += physIO; + touchedBlocks_Thread += touchedBlocks; + if ( ( fOid >= 3000 ) && ( ffirstStepType == SCAN ) && validCPData ) + cpv.push_back(CPInfo(min, max, lbid)); + } + + if (bucket) { + if (fOid>=3000 && dlTimes.FirstInsertTime().tv_sec==0) + dlTimes.setFirstInsertTime(); + + bucket->insert(elementVec); + } + else if (fifo) + { + size = elementVec.size(); + if ( size > 0 ) + if (fOid>=3000 && dlTimes.FirstInsertTime().tv_sec==0) + dlTimes.setFirstInsertTime(); + + dlMutex.lock(); //pthread_mutex_lock(&dlMutex); + + for (i = 0; i < size; ++i) { + rw.et[rw.count++] = elementVec[i]; + if (rw.count == rw.ElementsPerGroup) + { + fifo->insert(rw); + rw.count = 0; + } + } + + if (rw.count > 0) + { + fifo->insert(rw); + rw.count = 0; + } + dlMutex.unlock(); //pthread_mutex_unlock(&dlMutex); + } + else if (zdl) + { + if (fOid>=3000 && dlTimes.FirstInsertTime().tv_sec==0) + dlTimes.setFirstInsertTime(); + + dlp->insert(elementVec); + } + else if ( strFifo ) //@Bug 1308 + { + size = strElementVec.size(); + if ( size > 0 ) + if (fOid>=3000 && dlTimes.FirstInsertTime().tv_sec==0) + dlTimes.setFirstInsertTime(); + + dlMutex.lock(); //pthread_mutex_lock(&dlMutex); + + for (i = 0; i < size; ++i) { + strRw.et[strRw.count++] = strElementVec[i]; + if (strRw.count == strRw.ElementsPerGroup) + { + strFifo->insert(strRw); + strRw.count = 0; + } + } + + if (strRw.count > 0) + { + strFifo->insert(strRw); + strRw.count = 0; + } + dlMutex.unlock(); //pthread_mutex_unlock(&dlMutex); + } + else if ( strDlp ) + { + strDlp->insert(strElementVec); + + } + + elementVec.clear(); + strElementVec.clear(); + //update casual partition + size = cpv.size(); + if (size > 0) { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + for (i = 0; i < size; i++) { + CPInfo *cpi = &(cpv[i]); + lbidList->UpdateMinMax(cpi->min, cpi->max, cpi->LBID, fColType.colDataType); + } + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + cpv.clear(); + } + mutex.lock(); //pthread_mutex_lock(&mutex); + }// done reading + +}//try +catch(const LargeDataListExcept& ex) +{ + processError(ex.what(), batchPrimitiveStepLargeDataListFileErr, "BatchPrimitiveStep::receiveMultiPrimitiveMessages()"); + caughtError = true; +} +catch(const std::exception& ex) +{ + processError(ex.what(), batchPrimitiveStepErr, "BatchPrimitiveStep::receiveMultiPrimitiveMessages()"); + caughtError = true; +} +catch(...) +{ + processError("unknown", batchPrimitiveStepErr, "BatchPrimitiveStep::receiveMultiPrimitiveMessages()"); + caughtError = true; +} + if (caughtError && !fUpdatedEnd) + { + setEndOfInput(fifo, strFifo, strDlp, tbdl, zdl, dlp); + } + if (++recvExited == fNumThreads) { + //...Casual partitioning could cause us to do no processing. In that + //...case these time stamps did not get set. So we set them here. + + if (fOid>=3000 && dlTimes.FirstReadTime().tv_sec==0) { + dlTimes.setFirstReadTime(); + dlTimes.setLastReadTime(); + dlTimes.setFirstInsertTime(); + } + if (fOid>=3000) dlTimes.setEndOfInputTime(); + + ByteStream bs; + fDec->removeDECEventListener(this); + fBPP->destroyBPP(bs); + fDec->write(bs); + BPPIsAllocated = false; + fDec->removeQueue(uniqueID); + joiner.reset(); + + lastThread = true; + + if (! fUpdatedEnd && !didEOF) + { + setEndOfInput(fifo, strFifo, strDlp, tbdl, zdl, dlp); + } + } + //@Bug 1099 + ridsReturned += ridsReturned_Thread; + fPhysicalIO += physIO_Thread; + fCacheIO += cachedIO_Thread; + fBlockTouched += touchedBlocks_Thread; + fMsgBytesIn += msgBytesIn_Thread; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + + if (fTableOid >= 3000 && lastThread) + { + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + timeString[strlen(timeString)-1 ] = '\0'; + + FifoDataList* pFifo = 0; + uint64_t totalBlockedReadCount = 0; + uint64_t totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + { + totalBlockedReadCount += pFifo->blockedReadCount(); + } + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + { + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + } + + //...Roundoff msg byte counts to nearest KB for display + uint64_t msgBytesInKB = fMsgBytesIn >> 10; + uint64_t msgBytesOutKB = fMsgBytesOut >> 10; + if (fMsgBytesIn & 512) + msgBytesInKB++; + if (fMsgBytesOut & 512) + msgBytesOutKB++; + // @bug 828 + if (fifo) + fifo->totalSize(ridsReturned); + ostringstream logStr; + logStr << "ses:" << fSessionId << " st: " << fStepId<<" finished at "<< + timeString << "; PhyI/O-" << fPhysicalIO << "; CacheI/O-" << + fCacheIO << "; MsgsSent-" << fMsgBppsToPm << "; MsgsRvcd-" << msgsRecvd << + "; BlocksTouched-"<< fBlockTouched << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << + "; output size-" << ridsReturned<< endl << + "\tPartitionBlocksEliminated-" << fNumBlksSkipped << + "; MsgBytesIn-" << msgBytesInKB << "KB" << + "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime())<< "s" << endl + << "\tJob completion status " << fOutputJobStepAssociation.status() << endl; + + logEnd(logStr.str().c_str()); + + if (traceOn()) + { + syslogReadBlockCounts(16, // exemgr sybsystem + fPhysicalIO, // # blocks read from disk + fCacheIO, // # blocks read from cache + fNumBlksSkipped); // # casual partition block hits + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstInsertTime(), // first datalist write + dlTimes.EndOfInputTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + totalBlockedReadCount, // blocked datalist input + totalBlockedWriteCount, // blocked datalist output + fMsgBytesIn, // incoming msg byte count + fMsgBytesOut); // outgoing msg byte count + } + + if ( ffirstStepType == SCAN ) + lbidList->UpdateAllPartitionInfo(); + } +} + + +void BatchPrimitiveStep::processError(const string& ex, uint16_t err, const string& src) +{ + ostringstream oss; + oss << "st: " << fStepId << " " << src << " caught an exception: " << ex << endl; + catchHandler(oss.str(), fSessionId); + fOutputJobStepAssociation.status(err); + cerr << oss.str(); +} + +void BatchPrimitiveStep::setEndOfInput(FifoDataList *fifo, StringFifoDataList *strFifo, StrDataList* strDlp, TupleBucketDataList *tbdl, ZDL *zdl, DataList_t* dlp) +{ + if (fifo) + fifo->endOfInput(); + else if ( strFifo ) + strFifo->endOfInput(); + else if ( strDlp ) + strDlp->endOfInput(); + else if ( tbdl ) + tbdl->endOfInput(); + else if (zdl) + zdl->endOfInput(); + else + dlp->endOfInput(); + fUpdatedEnd = true; +} + +const string BatchPrimitiveStep::toString() const +{ + ostringstream oss; + oss << "BatchPrimitiveStep ses:" << fSessionId << " txn:" << fTxnId << " ver:" << fVerId << " st:" << fStepId << + " tb/col:" << fTableOid << "/" << fOid; + if (alias().length()) oss << " alias:" << alias(); + if (view().length()) oss << " view:" << view(); + + // @bug 1282, don't have output datalist for delivery + if (fOutputType != TABLE_BAND) + oss << " " << omitOidInDL << fOutputJobStepAssociation.outAt(0) << showOidInDL; + oss << " nf:" << fFilterCount; + oss << " in:"; + for (unsigned i = 0; i < fInputJobStepAssociation.outSize(); i++) + { + oss << fInputJobStepAssociation.outAt(i); + } + oss << " outputType=" << fOutputType; + oss << endl << " " << fBPP->toString() << endl; + return oss.str(); +} + +void BatchPrimitiveStep::addFilters() +{ + AnyDataListSPtr dl = fInputJobStepAssociation.outAt(0); + DataList_t* bdl = dl->dataList(); + FifoDataList* fifo = fInputJobStepAssociation.outAt(0)->fifoDL(); + + idbassert(bdl); + bool more; + ElementType e; + int64_t token; + int it = -1; + + if (fifo != NULL) + { + it = fifo->getIterator(); + + fBOP = BOP_OR; + UintRowGroup rw; + + more = fifo->next(it, &rw); + + while (more) + { + for (uint64_t i = 0; i < rw.count; ++i) + addFilter(COMPARE_EQ, (int64_t) rw.et[i].second, 0); + + more = fifo->next(it, &rw); + } + } + else + { + it = bdl->getIterator(); + + fBOP = BOP_OR; + + more = bdl->next(it, &e); + + while (more) + { + token = e.second; + addFilter(COMPARE_EQ, token, 0); + more = bdl->next(it, &e); + } + } + + return; +} + +/* This exists to avoid a DBRM lookup for every rid. */ +inline bool BatchPrimitiveStep::scanit(uint64_t rid) +{ + uint64_t fbo; + uint extentIndex; + + //if (fOid < 3000 || !lbidList->CasualPartitionDataType(fColType.colDataType)) + // return true; + if (fOid < 3000) + return true; + fbo = rid >> rpbShift; + extentIndex = fbo >> divShift; + return (scanFlags[extentIndex] != 0); +} + +uint64_t BatchPrimitiveStep::getFBO(uint64_t lbid) +{ + uint i; + uint64_t lastLBID; + + for (i = 0; i < numExtents; i++) { + lastLBID = extents[i].range.start + (extents[i].range.size << 10) - 1; + + if (lbid >= (uint64_t) extents[i].range.start && lbid <= lastLBID) + return (lbid - extents[i].range.start) + (i << divShift); + } + cerr << "BatchPrimitiveStep: didn't find the FBO?\n"; + throw logic_error("BatchPrimitiveStep: didn't find the FBO?"); +} + +void BatchPrimitiveStep::useJoiner(boost::shared_ptr j) +{ + joiner = j; + doJoin = (j.get() != NULL); +} + +void BatchPrimitiveStep::newPMOnline(uint connectionNumber) +{ + ByteStream bs; + + fBPP->createBPP(bs); + fDec->write(bs, connectionNumber); + if (doJoin && joiner->inPM()) + serializeJoiner(connectionNumber); + +} + +void BatchPrimitiveStep::setJobInfo(const JobInfo* jobInfo) +{ + fBPP->jobInfo(jobInfo); +} + +void BatchPrimitiveStep::stepId(uint16_t stepId) +{ + fStepId = stepId; + fBPP->setStepID(stepId); +} + +void BatchPrimitiveStep::dec(DistributedEngineComm* dec) +{ + if (fDec) + fDec->removeQueue(uniqueID); + fDec = dec; + if (fDec) + fDec->addQueue(uniqueID, true); +} + +} //namespace +// vim:ts=4 sw=4: + diff --git a/dbcon/joblist/bdlwrapper.h b/dbcon/joblist/bdlwrapper.h new file mode 100644 index 00000000..2f21bc0d --- /dev/null +++ b/dbcon/joblist/bdlwrapper.h @@ -0,0 +1,198 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// $Id: bdlwrapper.h 8436 2012-04-04 18:18:21Z rdempsey $ +#ifndef JOBLISTDLWRAPPER_H +#define JOBLISTDLWRAPPER_H + +// +// C++ Interface: dlwrapper +// +// Description: +// +// +// Author: Jason Rodriguez +// Calpont (C) 2007 +// +// Copyright: See COPYING file that comes with this distribution +// +// + +/** @file */ + +#include "bucketdl.h" + +namespace joblist { + +/** +Wrapper class for DataList abstract baseclass + + @author Jason Rodriguez +*/ + +// TEMP: types for construction. +// should be support each type to support for Hash Join +// +// TODO: is there an abstract class for column types +// or some other class to use here. + +/** @brief class BDLWrapper + * + */ +template +class BDLWrapper { + + typedef BucketDL BucketDL_t; + +public: + + BDLWrapper(); + BDLWrapper(BucketDL_t* bdlptr); + + ~BDLWrapper(); + + void init(); + uint getIterator(uint n) const {return fBDLintPtr->getIterator(n);} + + bool next(const uint b, const uint i, element_t* v) const; + + uint size() const; + uint size(uint n) const; + + uint bucketCount() const; + + void insert(element_t val) {fBDLintPtr->insert(val);} + + void dump() const ; + void dump(uint n) const ; + BucketDL_t* getBDL() const { return fBDLintPtr; } + +private: + + BucketDL_t* fBDLintPtr; + +}; // BDLWrapper + +template +bool BDLWrapper::next(const uint b, const uint i, element_t* v) const +{ + bool ret=false; + ret = fBDLintPtr->next(b, i, v); + return ret; +} + +template +BDLWrapper::BDLWrapper() +{ + fBDLintPtr = NULL; + return; +} + +template +BDLWrapper::BDLWrapper(BucketDL_t* bdlptr) +{ + fBDLintPtr = bdlptr; +} + +template +BDLWrapper::~BDLWrapper() { +} + +template +void BDLWrapper::init() { + return; +} + +template +uint BDLWrapper::size() const +{ + if (fBDLintPtr==NULL) + return 0; + + uint hSize=0; + uint bCount = fBDLintPtr->bucketCount(); + + for (int idx=0; idx < (int)bCount; idx++) + hSize += fBDLintPtr->size(idx); + + return hSize; +} + +template +uint BDLWrapper::bucketCount() const +{ + if (fBDLintPtr==NULL) + return 0; + + return fBDLintPtr->bucketCount(); + +} + +template +uint BDLWrapper::size(uint n) const +{ + if (fBDLintPtr==NULL) + return 0; + + return fBDLintPtr->size(n); + +} + +template +void BDLWrapper::dump(uint n) const +{ + + if (fBDLintPtr==NULL) + return; + + int bSize = fBDLintPtr->size(n); + element_t element; + uint bucketIter; + bool moreElems=true; + + bucketIter = fBDLintPtr->getIterator(n); + std::cout << "::dump(n) bucket# " << n << " " << fBDLintPtr->size(n) << std::endl; + + for (; fBDLintPtr->size(n) && moreElems; ) + { + moreElems = fBDLintPtr->next(n, bucketIter, &element); + if (moreElems) + std::cout << "Bkt " << n << " Idx " << bucketIter << " val " + << element.getValue() << std::endl; + } + + std::cout << "---" << std::endl; + bSize=0; +} + +template +void BDLWrapper::dump() const +{ + if (fBDLintPtr==NULL) + return; + + int bSize = fBDLintPtr->bucketCount(); + + std::cout << "dump() bucket count " << bSize << std::endl; + + for(int idx=0; idx, (C) 2008 @@ -42,5 +42,3 @@ #include "passthrucommand-jl.h" #include "rtscommand-jl.h" #include "filtercommand-jl.h" -#include "pseudocc-jl.h" - diff --git a/dbcon/joblist/bucketdl.h b/dbcon/joblist/bucketdl.h index 3a391f71..00f1496a 100644 --- a/dbcon/joblist/bucketdl.h +++ b/dbcon/joblist/bucketdl.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: bucketdl.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: bucketdl.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ -/** @file +/** @file * class XXX interface */ @@ -47,12 +47,12 @@ class BucketDL : public DataList typedef DataList base; typedef boost::shared_ptr< TupleWSDL > TWSSP; typedef std::vector TWSVec; - + enum ElementMode { RID_MODE, RID_VALUE }; - + public: /** Main constuctor. * @param numBuckets The number of buckets to create @@ -60,52 +60,52 @@ class BucketDL : public DataList * @param maxElementsPerBucket The maximum # of elements each bucket should keep in memory. * @param hash The function object that calculates which bucket an elements goes into on insertion. */ - - BucketDL(uint32_t numBuckets, uint32_t numConsumers, uint32_t maxElementsPerBucket, ResourceManager& rm, - boost::function hash = utils::Hasher()); - + + BucketDL(uint numBuckets, uint numConsumers, uint maxElementsPerBucket, ResourceManager& rm, + boost::function hash = utils::Hasher()); + virtual ~BucketDL(); - - // datalist interface. insert() and endOfInput() are the only + + // datalist interface. insert() and endOfInput() are the only // datalist function that makes sense. The consumer side functions // are stubs. Consumers know they're consuming a BucketDL. void insert(const element_t &e); void insert(const std::vector &e); void insert(const element_t* array, uint64_t arrayCount); - + void insert(TupleType &e); void insert(std::vector &e); - + void endOfInput(); uint64_t getIterator(); bool next(uint64_t it, element_t *e); void setMultipleProducers(bool); - + // BucketDL consumer fcns uint64_t getIterator(uint64_t bucket); bool next(uint64_t bucket, uint64_t it, element_t *e); - + /** Returns the size of the specified bucket */ uint64_t size(uint64_t bucket); - + /** Returns the total number of elements stored */ uint64_t totalSize(); - + /** Returns the number of buckets */ uint64_t bucketCount(); - + /** Sets the value to pass down to element_t::getHashString() */ void setHashMode(uint64_t mode); - + /** Sets the value to RID_only or rid_value mode */ void setElementMode(uint64_t mode); - + /** Total number of files and filespace used for temp files */ void totalFileCounts(uint64_t& numFiles, uint64_t& numBytes) const; - + const uint32_t hashLen() const {return fHashLen;} void hashLen (const uint32_t hashLen) {fHashLen = hashLen;} - + const uint32_t elementLen() const {return fElementLen;} void elementLen (const uint64_t ridSize, const uint64_t dataSize); @@ -114,17 +114,17 @@ class BucketDL : public DataList /** Sets the size of the element components that are saved to disk */ virtual void setDiskElemSize(uint32_t size1st,uint32_t size2nd); - + /** Accessor and mutator to the BucketReuseControlEntry */ void reuseControl(BucketReuseControlEntry* control, bool readonly); BucketReuseControlEntry* reuseControl() { return fReuseControl; } - + /** Restores the buckets' set number and start positions */ void restoreBucketInformation(); - + /** @brief return tuple rid size */ const uint64_t ridSize() const {return fRidSize;} - + /** @brief return tuple data size */ const uint64_t dataSize() const {return fDataSize;} @@ -138,8 +138,8 @@ class BucketDL : public DataList std::list& diskIoInfoList(uint64_t bucket); protected: - - + + private: // Declare default constructors but don't define to disable their use explicit BucketDL(); @@ -153,7 +153,7 @@ class BucketDL : public DataList uint64_t numBuckets; uint64_t numConsumers; uint64_t maxElements; - boost::function hashFcn; + boost::function hashFcn; uint64_t hashMode; uint64_t bucketMask; bool multiProducer; @@ -169,14 +169,14 @@ class BucketDL : public DataList }; template -BucketDL::BucketDL(uint32_t nb, uint32_t nc, uint32_t me, ResourceManager& rm, - boost::function hash) +BucketDL::BucketDL(uint nb, uint nc, uint me, ResourceManager& rm, + boost::function hash) : base(), fRm(rm), buckets(0), rbuckets(0), fTraceOn(false), fHashLen(0), fElementLen(0), bucketDoneCount(0), fReuseControl(NULL) { - uint32_t i; + uint i; uint64_t mask; - + numBuckets = nb; numConsumers = nc; maxElements = me; @@ -185,11 +185,11 @@ BucketDL::BucketDL(uint32_t nb, uint32_t nc, uint32_t me, ResourceMan elementMode = RID_MODE; multiProducer = false; - // initialize buckets + // initialize buckets if (typeid (element_t) == typeid(TupleType)) { - for (i = 0; i < numBuckets; i++) - fTBuckets.push_back(TWSSP(new TupleWSDL(numConsumers, maxElements, fRm))); + for (i = 0; i < numBuckets; i++) + fTBuckets.push_back(TWSSP(new TupleWSDL(numConsumers, maxElements, fRm))); } else { @@ -198,7 +198,7 @@ BucketDL::BucketDL(uint32_t nb, uint32_t nc, uint32_t me, ResourceMan rbuckets[i] = new WSDL (numConsumers, maxElements, rm); } - + for (i = 1, mask = 1, bucketMask = 0; i <= 64; i++) { mask <<= 1; bucketMask = (bucketMask << 1) | 1; @@ -208,8 +208,8 @@ BucketDL::BucketDL(uint32_t nb, uint32_t nc, uint32_t me, ResourceMan for (i++, mask <<= 1; i <= 64; i++, mask <<= 1) if (numBuckets & mask) - throw std::runtime_error("BucketDL: The number of buckets should be a power of 2."); -} + throw std::runtime_error("BucketDL: The number of buckets should be a power of 2."); +} template BucketDL::~BucketDL() @@ -230,7 +230,7 @@ BucketDL::~BucketDL() } template -void BucketDL::setMultipleProducers(bool b) +void BucketDL::setMultipleProducers(bool b) { multiProducer = b; uint64_t i; @@ -245,7 +245,7 @@ void BucketDL::setMultipleProducers(bool b) for (i = 0; i < numBuckets; i++) rbuckets[i]->setMultipleProducers(b); } - else { + else { for (i = 0; i < numBuckets; i++) buckets[i]->setMultipleProducers(b); } @@ -258,13 +258,13 @@ void BucketDL::insert(const element_t &e) /* Need the element type to provide what to hash, which conflicts with the standard meaning of "<<". For our currently-defined element types, this would be the rid field only, not the entire contents of the structure */ - + uint64_t bucket, len = fHashLen; const char *hashStr; - + hashStr = e.getHashString(hashMode, &len); bucket = hashFcn(hashStr, len) & bucketMask; - + if (elementMode == RID_MODE) { RIDElementType rid(e.first); @@ -280,12 +280,12 @@ void BucketDL::insert(TupleType &e) { uint64_t bucket, len = fHashLen; const char *hashStr; - + hashStr = e.getHashString(hashMode, &len); - + bucket = hashFcn(hashStr, len) & bucketMask; fTBuckets[bucket]->insert(e); -} +} template void BucketDL::insert(std::vector &v) @@ -297,7 +297,7 @@ void BucketDL::insert(std::vector &v) try { end = v.end(); - for (it = v.begin(); it != end; ++it) + for (it = v.begin(); it != end; ++it) fTBuckets[hashFcn(it->second, fHashLen) & bucketMask]->insert_nolock(*it); } catch( ... ) @@ -315,7 +315,7 @@ void BucketDL::insert(const std::vector &v) typename std::vector::const_iterator it, end; const char *hashStr; uint64_t len = fHashLen; - + if (multiProducer) base::lock(); try @@ -349,7 +349,7 @@ void BucketDL::insert(const element_t* array, uint64_t arrayCount) { const char *hashStr; uint64_t len = fHashLen; - + if (multiProducer) base::lock(); try @@ -382,7 +382,7 @@ void BucketDL::insert(const element_t* array, uint64_t arrayCount) template uint64_t BucketDL::getIterator() { - throw std::logic_error("don't call BucketDL::getIterator(), call getIterator(uint32_t)"); + throw std::logic_error("don't call BucketDL::getIterator(), call getIterator(uint)"); } template @@ -390,7 +390,7 @@ void BucketDL::endOfInput() { uint64_t i; uint64_t saveSize = 0; //debug - + if (typeid(element_t) == typeid(TupleType)) { for (i = 0; i < numBuckets; i++) { @@ -399,14 +399,14 @@ void BucketDL::endOfInput() } //std::cout << "bucketdl-" << this << " saveSize=" << saveSize << std::endl; } - else + else if (elementMode == RID_MODE) { for (i = 0; i < numBuckets; i++) - rbuckets[i]->endOfInput(); + rbuckets[i]->endOfInput(); } else { for (i = 0; i < numBuckets; i++) - buckets[i]->endOfInput(); + buckets[i]->endOfInput(); } if (fReuseControl != NULL && fReuseControl->userNotified() == false) @@ -417,7 +417,7 @@ void BucketDL::endOfInput() template bool BucketDL::next(uint64_t it, element_t *e) { - throw std::logic_error("don't call BucketDL::next(uint32_t, element_t), call next(uint32_t, uint32_t, element_t"); + throw std::logic_error("don't call BucketDL::next(uint, element_t), call next(uint, uint, element_t"); } template @@ -433,11 +433,11 @@ uint64_t BucketDL::getIterator(uint64_t bucket) template bool BucketDL::next(uint64_t bucket, uint64_t it, element_t *e) -{ +{ if (typeid(element_t) == typeid(TupleType)) return fTBuckets[bucket]->next(it, reinterpret_cast(e)); - - bool ret; + + bool ret; if (elementMode == RID_MODE) { RIDElementType rid; @@ -502,19 +502,19 @@ uint64_t BucketDL::totalSize() } template -void BucketDL::setHashMode(uint64_t mode) +void BucketDL::setHashMode(uint64_t mode) { hashMode = mode; - // Make elementMode the same as hashMode unless setElementMode + // Make elementMode the same as hashMode unless setElementMode // is explicitly called by the caller, like filterstep. setElementMode (mode); } template -void BucketDL::setElementMode(uint64_t mode) -{ +void BucketDL::setElementMode(uint64_t mode) +{ uint64_t i; - + if (typeid(element_t) == typeid(TupleType)) return; if (elementMode != mode) { @@ -553,7 +553,7 @@ void BucketDL::setElementMode(uint64_t mode) } } // std::cout << "bucketdl-" << this << " setElementMode " << hashMode << std::endl; - + } // @@ -567,7 +567,7 @@ void BucketDL::totalFileCounts( { numFiles = 0; numBytes = 0; - + if (typeid(element_t) == typeid(TupleType)) { for (uint64_t i = 0; i < numBuckets; i++) @@ -581,18 +581,18 @@ void BucketDL::totalFileCounts( } } } - else + else if (elementMode == RID_MODE) { for (uint64_t i = 0; i < numBuckets; i++) { uint64_t setCnt = rbuckets[i]->initialSetCount(); - + if (setCnt > 1) { //std::cout << "BDL: bucket " << i << " has " << setCnt << // " sets" << std::endl; - + numFiles += rbuckets[i]->numberOfTempFiles(); numBytes += rbuckets[i]->saveSize; } @@ -603,12 +603,12 @@ void BucketDL::totalFileCounts( for (uint64_t i = 0; i < numBuckets; i++) { uint64_t setCnt = buckets[i]->initialSetCount(); - + if (setCnt > 1) { //std::cout << "BDL: bucket " << i << " has " << setCnt << // " sets" << std::endl; - + numFiles += buckets[i]->numberOfTempFiles(); numBytes += buckets[i]->saveSize; } @@ -671,7 +671,7 @@ void BucketDL::reuseControl(BucketReuseControlEntry* control, bool re // @todo reuse for tuplewsdl if (typeid(element_t) == typeid(TupleType)) return; - + if (control == NULL) return; @@ -695,7 +695,7 @@ void BucketDL::restoreBucketInformation() { if (typeid(element_t) == typeid(TupleType)) return; - + std::vector& infoVec = fReuseControl->restoreInfoVec(); if (elementMode == RID_MODE) for (uint64_t i = 0; i < numBuckets; i++) diff --git a/dbcon/joblist/bucketreuse.cpp b/dbcon/joblist/bucketreuse.cpp new file mode 100644 index 00000000..d4f64f16 --- /dev/null +++ b/dbcon/joblist/bucketreuse.cpp @@ -0,0 +1,307 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: bucketreuse.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ + +#include +#include +#include +#include + +#include +#include + +#include +#include + +#define BUCKETREUSEMANAGER_DLLEXPORT +#include "bucketreuse.h" +#undef BUCKETREUSEMANAGER_DLLEXPORT +#include "configcpp.h" +#include "resourcemanager.h" + + +namespace joblist +{ +using namespace std; +using namespace boost; + +BucketReuseManager* BucketReuseManager::fInstance = NULL; + +BucketReuseManager* BucketReuseManager::instance() +{ + if (fInstance == NULL) fInstance = new BucketReuseManager; + return fInstance; +} + + +BucketReuseManager::~BucketReuseManager() +{ + // stop the Eraser + fEraserStop = true; + fNewVer.notify_one(); + fEraser->join(); + + for (BucketReuseMap::iterator it = fControlMap.begin(); it != fControlMap.end(); it++) + delete it->second; + + for (list::iterator it = fToRemoveEntries.begin(); + it != fToRemoveEntries.end(); it++) + delete *it; + + delete fEraser; + fEraser = NULL; + + // don't call delete, already in destructor + fInstance = NULL; +} + + +void BucketReuseManager::startup(ResourceManager& rm) +{ + fReuseDir = rm.getScTempDiskPath(); + fReuseDir += "/bucketreuse"; + + filesystem::path diskPath(fReuseDir); + if (filesystem::exists(diskPath)) + filesystem::remove_all(diskPath); // removes diskPath dir and all its contents + + filesystem::create_directory(diskPath); + if (!filesystem::exists(diskPath)) + throw runtime_error("Failed to create bucket reuse directory"); + + vector columns(rm.getHbrPredicate()); +// vector columns; +// cf->getConfig("HashBucketReuse", "Predicate", columns); + + // if no predicates defined, no need to make a calpont system catalog + if (columns.size() == 0) + return; + + // no need to check duplicate elements in columns vector, + // because map will ensure the values inserted is unique + for (vector::iterator it = columns.begin(); it != columns.end(); ++it) + { + string value = algorithm::erase_all_copy(*it," "); + algorithm::to_lower(value); + + // column namestring:filterstring, first search for the ":" + size_t separate = value.find_first_of(":"); + + // get the column name part + string name = value.substr(0, separate); + size_t schema = name.find_first_of("."); + size_t column = name.find_last_of("."); + + if (schema == string::npos || column == string::npos || schema == column) + { + cerr << "incorrect column name in HashBucketReuse: " << name << endl; + continue; + } + + execplan::CalpontSystemCatalog::TableColName columnName; + columnName.schema = value.substr(0, schema); + columnName.table = value.substr(schema+1, column-schema-1); + columnName.column = value.substr(column+1); + + // the filter string is not parsed in iter15 because only "allrows" is supported + // when arbitrary predicates are supported, may need to parse the filter part + string filter; + if (separate == string::npos || separate == value.length()) + filter = "allrows"; + else + filter = value.substr(separate+1); + + fConfigMap.insert(pair(name, BucketFileKey(columnName, filter))); + } + + initializeControlMap(); +} + +// caller of this method should alread get a lock to avoid race condition. +// no need to lock again in this method. +BucketReuseControlEntry* BucketReuseManager::userRegister( + const execplan::CalpontSystemCatalog::TableColName& tcn, + string filter, uint64_t version, uint64_t buckets, bool& scan) +{ + BucketReuseControlEntry* entry = NULL; + if (filter.length() == 0) filter = "allrows"; + + // do NOT lock here, locked in joblistfactory::checkBucketReuse() + // boost::mutex::scoped_lock lock(fMutex); + if (version != fVersion) + { + handleNewDbVersion(version); + } + + // default to true, unless entry found not in null state + scan = true; + + BucketReuseMap::iterator it = fControlMap.find(BucketFileKey(tcn, filter)); + if (it != fControlMap.end()) + { + entry = it->second; + if (entry->fileStatus() == BucketReuseControlEntry::null_c) + { + entry->fBucketCount = buckets; + entry->fUserCount = 1; + entry->fileStatus(BucketReuseControlEntry::progress_c); + } + else + { + if (entry->fBucketCount == buckets) + { + scan = false; + entry->fUserCount++; + if (entry->fStatus == BucketReuseControlEntry::ready_c) + entry->fStatus = BucketReuseControlEntry::using_c; + } + else + { + // how to handle bucket change?? + entry = NULL; + } + } + } + + return entry; +} + +void BucketReuseManager::userDeregister(BucketReuseControlEntry* entry) +{ + boost::mutex::scoped_lock lock(BucketReuseManager::instance()->getMutex()); + entry->fUserCount--; + if (entry->fUserCount == 0) + { + if (entry->fStatus == BucketReuseControlEntry::obsolete_c) + { + entry->fStatus = BucketReuseControlEntry::finished_c; + signalToCleanup(); + } + else + { + entry->fStatus = BucketReuseControlEntry::ready_c; + } + } +} + +void BucketReuseManager::initializeControlMap() +{ + for (ReuseConfigMap::iterator it = fConfigMap.begin(); it != fConfigMap.end(); ++it) + { + stringstream ss; + ss << fReuseDir << "/" << it->first << "." << it->second.second << ".ver" << fVersion; + fControlMap[it->second] = new BucketReuseControlEntry(ss.str().c_str()); + } +} + +void BucketReuseManager::handleNewDbVersion(uint64_t version) +{ + fVersion = version; + + // move all entries in the reuse map to remove list, let the cleanup thread to further process + for (BucketReuseMap::iterator mapIt = fControlMap.begin(); mapIt != fControlMap.end(); ++mapIt) + fToRemoveEntries.push_back(mapIt->second); + + if (fEraser != NULL) + signalToCleanup(); + else + fEraser = new boost::thread(Eraser(this)); + + initializeControlMap(); +} + +void BucketReuseManager::cleanupOldVersions() +{ + // let the query thread continue to make job list + boost::thread::yield(); + + while (fEraserStop != true) + { + boost::mutex::scoped_lock lock(BucketReuseManager::instance()->getMutex()); + list::iterator it; + for (it = fToRemoveEntries.begin(); it != fToRemoveEntries.end(); ) + { + BucketReuseControlEntry* entry = *it; + if (entry->fileStatus() == BucketReuseControlEntry::null_c) + { + it = fToRemoveEntries.erase(it); + delete entry; + } + else if (entry->fileStatus() == BucketReuseControlEntry::ready_c || + entry->fileStatus() == BucketReuseControlEntry::finished_c) + { + for (uint64_t i = 0; i < entry->bucketCount(); ++i) + { + stringstream ss; + ss << entry->baseName() << "." << i; + + boost::filesystem::remove(ss.str().c_str()); + } + + it = fToRemoveEntries.erase(it); + delete entry; + } + else + { + entry->fileStatus(BucketReuseControlEntry::obsolete_c); + ++it; + } + } + + if (fToRemoveEntries.size() == 0) + { + delete fEraser; + fEraser = NULL; + break; + } + + // give up the current time slice when waken up + // this thread should have lower priority + fNewVer.wait(lock); + boost::thread::yield(); + } +} + +void BucketReuseManager::signalToCleanup() +{ + fNewVer.notify_one(); +} + +ostream& operator<<(ostream& os, const BucketReuseControlEntry& entry) +{ + const char* statsName[] = {"null", "progress", "using", "ready", "obsolete", "finished"}; + os << "basename: " << entry.fFileBaseName << "buckets:" << entry.fBucketCount + << " status: " << statsName[entry.fStatus] << " users:" << entry.fUserCount << endl; + + return os; +} + +void BucketReuseControlEntry::notifyUsers() +{ + boost::mutex::scoped_lock lock(BucketReuseManager::instance()->getMutex()); + if (fStatus == progress_c) fStatus = using_c; // could be already obsolete + fNotified = true; + lock.unlock(); + fStateChange.notify_all(); +} + +} diff --git a/dbcon/joblist/bucketreuse.h b/dbcon/joblist/bucketreuse.h new file mode 100644 index 00000000..9ab01a6b --- /dev/null +++ b/dbcon/joblist/bucketreuse.h @@ -0,0 +1,231 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: bucketreuse.h 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ +/** @file + * class BucketReuseManager interface + */ + +#ifndef JOBLIST_BUCKETREUSE_H_ +#define JOBLIST_BUCKETREUSE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "calpontsystemcatalog.h" + +// forward reference +class BucketReUseDriver; + +#if defined(_MSC_VER) && defined(BUCKETREUSEMANAGER_DLLEXPORT) +#define EXPORT __declspec(dllexport) +#else +#define EXPORT +#endif + +namespace joblist +{ + +class ResourceManager; +/** @brief key to the bucket reuse map + * + * the bucket reuse map use the column oid and filter string as key, + * mapped value is a pointer to a bucket reuse control entry + */ +typedef std::pair BucketFileKey; + + +/** @brief offset to the file on disk + * + * vector keeps the offset of each set + */ +typedef std::vector OffsetVec; + + +/** @brief information for buckets restore + * + * information necessary to restore the bucket files from disk + * defined in largedatalist.h + */ +struct SetRestoreInfo +{ + uint64_t fSetCount; + uint64_t fTotalSize; + OffsetVec fSetStartPositions; + + SetRestoreInfo() : fSetCount(0), fTotalSize(0) {} +}; + + +/** @brief bucket reuse control entry + * + * this entry contains the file basename, status, and other control data + */ +class BucketReuseControlEntry +{ +public: + + enum BucketFileStatus + { + null_c, + progress_c, + using_c, + ready_c, + obsolete_c, + finished_c + }; + + BucketReuseControlEntry() : fStatus(null_c), fBucketCount(0), fUserCount(0), fNotified(false) {} + BucketReuseControlEntry(const std::string& name) : + fFileBaseName(name), fStatus(null_c), fBucketCount(0), fUserCount(0), fNotified(false) {} + + ~BucketReuseControlEntry() { } + + const std::string& baseName() { return fFileBaseName; } + void baseName(const std::string& name) { fFileBaseName = name; } + + BucketFileStatus fileStatus() { return fStatus; } + void fileStatus(BucketFileStatus s) { fStatus = s; } + + boost::condition& stateChange() { return fStateChange; } + + uint64_t bucketCount() { return fBucketCount; } + void bucketCount(uint64_t buckets) { fBucketCount = buckets; } + + std::vector& restoreInfoVec() { return fRestoreInfoVec; } + std::pair& dataSize() { return fDataSize; } + + void notifyUsers(); + bool userNotified() { return fNotified; } + + friend class BucketReuseManager; + friend std::ostream& operator<<(std::ostream&, const BucketReuseControlEntry&); + +private: + std::string fFileBaseName; + BucketFileStatus fStatus; + boost::condition fStateChange; + uint64_t fBucketCount; + uint64_t fUserCount; + bool fNotified; + + std::pair fDataSize; + std::vector fRestoreInfoVec; + + // disable copy constructor and assignment operator + BucketReuseControlEntry(const BucketReuseControlEntry&); + BucketReuseControlEntry& operator=(const BucketReuseControlEntry&); +}; + +typedef std::multimap ReuseConfigMap; +typedef std::map BucketReuseMap; + +/** @brief bucket reuse manager + * + * this singleton class maintains the reuse information and co-ordinates producer and consumers + */ +class BucketReuseManager +{ +public: + // constructors are disabled for singleton, only destructor is public. + EXPORT ~BucketReuseManager(); + + // instance access method + EXPORT static BucketReuseManager* instance(); + + // parse the configure data + EXPORT void startup(ResourceManager& rm); + + // take registration info from joblistfactory, + // update and return the entry to joblistfactory + // !! the caller shall have a lock on fMutex before call this method !! + // -- boost::mutex::scoped_lock lock(BucketReuseManager::instance()->getMutex()); + EXPORT BucketReuseControlEntry* userRegister(const execplan::CalpontSystemCatalog::TableColName& tcn, + std::string filter, uint64_t version, uint64_t buckets, bool& scan); + + // notified when the user is complete + EXPORT void userDeregister(BucketReuseControlEntry*); + + // get the reference to the mutex + EXPORT boost::mutex& getMutex() { return fMutex; } + + friend class ::BucketReUseDriver; + +private: + class Eraser + { + public: + Eraser(BucketReuseManager* eraser) : fEraser(eraser) {} + void operator()() { fEraser->cleanupOldVersions(); } + + private: + //Eraser(const Eraser&); + //Eraser& operator=(const Eraser&); + BucketReuseManager* fEraser; + }; + + // initialize the map using the configure records in Calpont.xml BucketReuse section, + void initializeControlMap(); + + // update the map version number, move currently re-using entries to remove list + void handleNewDbVersion(uint64_t version); + + // send signal to the cleanup thread + void signalToCleanup(); + + // cleanup old version files, which are not in use, from filesystem + void cleanupOldVersions(); + + // data members + uint64_t fVersion; + std::string fReuseDir; + boost::mutex fMutex; + boost::thread *fEraser; + boost::condition fNewVer; + ReuseConfigMap fConfigMap; + BucketReuseMap fControlMap; + std::list fToRemoveEntries; + bool fEraserStop; + + static BucketReuseManager* fInstance; + + // private constructor + BucketReuseManager() : fVersion(0), fEraser(NULL), fEraserStop(false) {} + + // disable copy constructor and assignment operator + // private without implementation + BucketReuseManager(const BucketReuseManager&); + BucketReuseManager& operator=(const BucketReuseManager&); +}; + +//extern const std::string defaultTempDiskPath; +extern std::ostream& operator<<(std::ostream&, const BucketReuseControlEntry&); + +} + +#undef EXPORT + +#endif // JOBLIST_BUCKETREUSE_H_ diff --git a/dbcon/joblist/bucketreusestep.cpp b/dbcon/joblist/bucketreusestep.cpp new file mode 100644 index 00000000..23583c18 --- /dev/null +++ b/dbcon/joblist/bucketreusestep.cpp @@ -0,0 +1,224 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: bucketreusestep.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ + +#include +#include +#include +#include + +#include "bucketreuse.h" +#include "jobstep.h" + +namespace joblist +{ +using namespace std; +using namespace boost; + +BucketReuseStep::BucketReuseStep(const pColScanStep& scan) : + fInputJobStepAssociation(scan.fInputJobStepAssociation), + fOutputJobStepAssociation(scan.fOutputJobStepAssociation), + fOid(scan.fOid), + fTableOid(scan.fTableOid), + fSessionId(scan.fSessionId), + fTxnId(scan.fTxnId), + fVerId(scan.fVerId), + fStatementId(scan.fStatementId), + fStepId(scan.fStepId), + fColWidth(scan.fColType.colWidth), + fDictColumn(false) +{ + fAlias = scan.fAlias; + fTraceFlags = scan.fTraceFlags; + fCardinality = scan.cardinality(); +} + +// Alternate constructor that can be used instead of +// BucketReuseStep(pColScanStep); warning, that output jobstep association +// is not set with this constructor. Application code must be sure to set +// via the outputAssociation() mutator. +BucketReuseStep::BucketReuseStep( + execplan::CalpontSystemCatalog::OID colOid, + execplan::CalpontSystemCatalog::OID tblOid, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId) : + fOid(colOid), + fTableOid(tblOid), + fSessionId(sessionId), + fTxnId(txnId), + fVerId(verId), + fStatementId(statementId), + fStepId(0), + fColWidth(0), + fDictColumn(false) +{ + fTraceFlags = 0; + fCardinality = 0; +} + +BucketReuseStep::BucketReuseStep(const pColScanStep& scan, pDictionaryStep& dict) : + fInputJobStepAssociation(scan.fInputJobStepAssociation), + fOutputJobStepAssociation(dict.fOutputJobStepAssociation), + fOid(dict.fOid), + fTableOid(dict.fTableOid), + fSessionId(scan.fSessionId), + fTxnId(dict.fTxnId), + fVerId(dict.fVerId), + fStatementId(dict.fStatementId), + fStepId(dict.fStepId), + fColWidth(scan.fColType.colWidth), + fDictColumn(true) +{ + fAlias = scan.fAlias; + fTraceFlags = scan.fTraceFlags; + fCardinality = scan.cardinality(); +} + +BucketReuseStep::~BucketReuseStep() +{ +} + +void BucketReuseStep::run() +{ + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + string("BucketReuseStep")); // step name + } + + runner.reset(new boost::thread(Runner(this))); +} + +void BucketReuseStep::join() +{ + runner->join(); +} + +void BucketReuseStep::reuseBuckets() +{ + if (0 < fInputJobStepAssociation.status()) + fOutputJobStepAssociation.status(fInputJobStepAssociation.status()); + else + if (fDictColumn) + reuseBuckets(fOutputJobStepAssociation.outAt(0)->stringBucketDL()); + else + reuseBuckets(fOutputJobStepAssociation.outAt(0)->bucketDL()); +} + +template +void BucketReuseStep::reuseBuckets(BucketDL* dl) +{ +try +{ + if (dl == NULL) + { + throw logic_error("output is not bucket datalist"); + } + + if (dl->reuseControl() == NULL) + { + throw logic_error("reuse control in bucket datalist is not set"); + } + + dlTimes.setFirstReadTime(); + dlTimes.setFirstInsertTime(); + if (dl->reuseControl()->fileStatus() == BucketReuseControlEntry::progress_c) + { + boost::mutex::scoped_lock lock(BucketReuseManager::instance()->getMutex()); + dl->reuseControl()->stateChange().wait(lock); + } +} +catch(const logging::LargeDataListExcept& ex) +{ + fOutputJobStepAssociation.status(logging::bucketReuseStepLargeDataListFileErr); + catchHandler(ex.what(), fSessionId); +} +catch(const std::exception& ex) +{ + fOutputJobStepAssociation.status(logging::bucketReuseStepErr); + catchHandler(ex.what(), fSessionId); +} +catch(...) +{ + string msg("BucketReuseStep: reuseBuckets caught unknown exception"); + fOutputJobStepAssociation.status(logging::bucketReuseStepErr); + catchHandler(msg, fSessionId); +} + + dlTimes.setLastReadTime(); + dlTimes.setLastInsertTime(); + dl->restoreBucketInformation(); + + dlTimes.setEndOfInputTime(); + dl->endOfInput(); + + if (fTableOid >= 3000) + { + //...Print job step completion information + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + timeString[strlen(timeString)-1] = '\0'; + + ostringstream logStr; + logStr << "ses:" << fSessionId << " st: " << fStepId << + " finished at " << timeString << + "; output size-" << dl->totalSize() << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime())<< "s" << endl; + + logEnd(logStr.str().c_str()); + + if (traceOn()) + { + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstInsertTime(), // first datalist write + dlTimes.EndOfInputTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + 0, // blocked datalist input + 0); // blocked datalist output + } + } +} + +const string BucketReuseStep::toString() const +{ + ostringstream oss; + oss << "BucketReuse ses:" << fSessionId << " txn:" << fTxnId << " ver:" << fVerId + << " st:" << fStepId << " tb/col:" << fTableOid << "/" << fOid; + if (alias().length()) oss << " alias:" << alias(); + + oss << " " << omitOidInDL << fOutputJobStepAssociation.outAt(0) << showOidInDL; + + oss << " in:"; + for (unsigned i = 0; i < fInputJobStepAssociation.outSize(); i++) + oss << fInputJobStepAssociation.outAt(i) << ","; + + return oss.str(); +} + +} diff --git a/dbcon/joblist/columncommand-jl.cpp b/dbcon/joblist/columncommand-jl.cpp index 1af4474f..bf5e03eb 100644 --- a/dbcon/joblist/columncommand-jl.cpp +++ b/dbcon/joblist/columncommand-jl.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: columncommand-jl.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: columncommand-jl.cpp 8829 2012-08-28 15:49:49Z pleblanc $ // C++ Implementation: columncommand // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -41,6 +41,48 @@ using namespace std; using namespace messageqcpp; +namespace +{ +uint8_t name2ord(const string& name) +{ + uint8_t ord = 0; +/* + if (ord == 255) return ::llabs; + if (ord == 254) return reinterpret_cast(::acos); + if (ord == 253) return reinterpret_cast(::asin); + if (ord == 252) return reinterpret_cast(::atan); + if (ord == 251) return reinterpret_cast(::cos); + if (ord == 250) return reinterpret_cast(cotangent); + if (ord == 249) return reinterpret_cast(::exp); + if (ord == 248) return reinterpret_cast(::log); + if (ord == 247) return reinterpret_cast(::log2); + if (ord == 246) return reinterpret_cast(::log10); + if (ord == 245) return reinterpret_cast(::sin); + if (ord == 244) return reinterpret_cast(::sqrt); + if (ord == 243) return reinterpret_cast(::tan); +*/ + if (name == "abs") return 255; + if (name == "acos") return 254; + if (name == "asin") return 253; + if (name == "atan") return 252; + if (name == "cos") return 251; + if (name == "cot") return 250; + if (name == "exp") return 249; + if (name == "log" || name == "ln") return 248; + if (name == "log2") return 247; + if (name == "log10") return 246; + if (name == "sin") return 245; + if (name == "sqrt") return 244; + if (name == "tan") return 243; + + string pfx(name, 0, 6); + if (pfx != "cpfunc") return 0; + string ordstr(name, 6); + ord = static_cast(atoi(ordstr.c_str())); + return ord; +} +} + namespace joblist { @@ -63,7 +105,7 @@ ColumnCommandJL::ColumnCommandJL(const pColScanStep &scan, vector l fLastLbid = lastLBID; //cout << "CCJL inherited lastlbids: "; - //for (uint32_t i = 0; i < lastLBID.size(); i++) + //for (uint i = 0; i < lastLBID.size(); i++) // cout << lastLBID[i] << " "; //cout << endl; @@ -71,8 +113,68 @@ ColumnCommandJL::ColumnCommandJL(const pColScanStep &scan, vector l /* I think modmask isn't necessary for scans */ divShift = scan.divShift; modMask = (1 << divShift) - 1; + fFcnOrd = name2ord(scan.udfName()); // @Bug 2889. Drop partition enhancement. Read FilesPerColumnPartition and ExtentsPerSegmentFile for use in RID calculation. + fExtentRows = dbrm.getExtentRows(); + fFilesPerColumnPartition = DEFAULT_FILES_PER_COLUMN_PARTITION; + fExtentsPerSegmentFile = DEFAULT_EXTENTS_PER_SEGMENT_FILE; + config::Config* cf = config::Config::makeConfig(); + string fpc = cf->getConfig("ExtentMap", "FilesPerColumnPartition"); + if ( fpc.length() != 0 ) + fFilesPerColumnPartition = cf->uFromText(fpc); + string epsf = cf->getConfig("ExtentMap", "ExtentsPerSegmentFile"); + if ( epsf.length() != 0 ) + fExtentsPerSegmentFile = cf->uFromText(epsf); +} + +ColumnCommandJL::ColumnCommandJL(const pColScanStep &scan) +{ + BRM::DBRM dbrm; + uint32_t partNum; + uint16_t segNum; + BRM::HWM_t lastHWM; + int err; + isScan = true; + + /* grab necessary vars from scan */ + traceFlags = scan.fTraceFlags; + filterString = scan.fFilterString; + filterCount = scan.fFilterCount; + colType = scan.fColType; + BOP = scan.fBOP; + extents = scan.extents; + OID = scan.fOid; + colName = scan.fName; + rpbShift = scan.rpbShift; + fIsDict = scan.fIsDict; + +// cout << "Init columncommand from scan with OID " << OID << endl; + /* I think modmask isn't necessary for scans */ + divShift = scan.divShift; + modMask = (1 << divShift) - 1; + fFcnOrd = name2ord(scan.udfName()); + + // PL - each dbroot will have a different HWM now; need to try to avoid needing this. + //get last lbid of this oid + ResourceManager rm; + numDBRoots = rm.getDBRootCount(); + + fLastLbid.resize(numDBRoots); + for (uint i = 0; i < numDBRoots; i++) { + err = dbrm.getLastHWM_DBroot((BRM::OID_t)OID, i+1, partNum, segNum, lastHWM); + if (err != 0) + dbrm.lookupLocal_DBroot((BRM::OID_t)OID, i+1, partNum, segNum, lastHWM, fLastLbid[i]); + else + fLastLbid[i] = 0; + } + //cout << "CCJL calculated lastlbids="; + //for (uint i = 0; i < fLastLbid.size(); i++) + // cout << fLastLbid[i] << " "; + //cout << endl; + + // @Bug 2889. Drop partition enhancement. Read FilesPerColumnPartition and ExtentsPerSegmentFile for use in RID calculation. + fExtentRows = dbrm.getExtentRows(); fFilesPerColumnPartition = DEFAULT_FILES_PER_COLUMN_PARTITION; fExtentsPerSegmentFile = DEFAULT_EXTENTS_PER_SEGMENT_FILE; config::Config* cf = config::Config::makeConfig(); @@ -102,16 +204,17 @@ ColumnCommandJL::ColumnCommandJL(const pColStep &step) rpbShift = step.rpbShift; OID = step.fOid; colName = step.fName; + fFcnOrd = name2ord(step.udfName()); fIsDict = step.fIsDict; ResourceManager rm; numDBRoots = rm.getDBRootCount(); - + // grab the last LBID for this column. It's a _minor_ optimization for the block loader. //dbrm.getLastLocalHWM((BRM::OID_t)OID, dbroot, partNum, segNum, lastHWM); //dbrm.lookupLocal((BRM::OID_t)OID, partNum, segNum, lastHWM, fLastLbid); /* fLastLbid.resize(numDBRoots); - for (uint32_t i = 0; i < numDBRoots; i++) { + for (uint i = 0; i < numDBRoots; i++) { dbrm.getLastLocalHWM2((BRM::OID_t)OID, i+1, partNum, segNum, lastHWM); dbrm.lookupLocal((BRM::OID_t)OID, partNum, segNum, lastHWM, fLastLbid[i]); } @@ -120,6 +223,7 @@ ColumnCommandJL::ColumnCommandJL(const pColStep &step) // cout << "Init columncommand from step with OID " << OID << " and width " << colType.colWidth << endl; // @Bug 2889. Drop partition enhancement. Read FilesPerColumnPartition and ExtentsPerSegmentFile for use in RID calculation. + fExtentRows = dbrm.getExtentRows(); fFilesPerColumnPartition = DEFAULT_FILES_PER_COLUMN_PARTITION; fExtentsPerSegmentFile = DEFAULT_EXTENTS_PER_SEGMENT_FILE; config::Config* cf = config::Config::makeConfig(); @@ -144,7 +248,7 @@ void ColumnCommandJL::createCommand(ByteStream &bs) const bs << filterString; #if 0 cout << "filter string: "; - for (uint32_t i = 0; i < filterString.length(); ++i) + for (uint i = 0; i < filterString.length(); ++i) cout << (int) filterString.buf()[i] << " "; cout << endl; #endif @@ -154,6 +258,7 @@ void ColumnCommandJL::createCommand(ByteStream &bs) const bs << (uint8_t) colType.compressionType; bs << BOP; bs << filterCount; + bs << fFcnOrd; serializeInlineVector(bs, fLastLbid); //bs << (uint64_t)fLastLbid; @@ -170,48 +275,71 @@ void ColumnCommandJL::runCommand(ByteStream &bs) const bs << lbid; } -void ColumnCommandJL::setLBID(uint64_t rid, uint32_t dbRoot) +void ColumnCommandJL::setLBID(uint64_t rid, uint dbRoot) { - uint32_t partNum; - uint16_t segNum; - uint8_t extentNum; - uint16_t blockNum; - uint32_t colWidth; - uint32_t i; - - idbassert(extents.size() > 0); - colWidth = extents[0].colWid; - rowgroup::getLocationFromRid(rid, &partNum, &segNum, &extentNum, &blockNum); + uint64_t l_rid, fbo; - for (i = 0; i < extents.size(); i++) { - if (extents[i].dbRoot == dbRoot && - extents[i].partitionNum == partNum && - extents[i].segmentNum == segNum && - extents[i].blockOffset == (extentNum * colWidth * 1024)) { - - lbid = extents[i].range.start + (blockNum * colWidth); - currentExtentIndex = i; - /* - ostringstream os; - os << "CCJL: rid=" << rid << "; dbroot=" << dbRoot << "; partitionNum=" << partNum - << "; segmentNum=" << segNum << "; extentNum = " << (int) extentNum << - "; blockNum = " << blockNum << "; OID=" << OID << " LBID=" << lbid; - cout << os.str() << endl; - */ - return; - } + if (isScan) { + lbid = rid; //it's not a rid here need to convert it to a rid + fbo = getFBO(lbid); + l_rid = fbo << rpbShift; + bpp->setLBIDForScan(l_rid, dbRoot); } - throw logic_error("ColumnCommandJL: setLBID didn't find the extent for the rid."); + else { + uint extentIndex = 0; + uint extentOffset = 0; + fbo = (rid >> 13); // a logical block FBO + fbo <<= (13-rpbShift); // convert to a real FBO rounding down to a logical block boundary + extentOffset = fbo & modMask; + + // @Bug 2889. Changed logic to find the extentIndex for the drop partition enhancement. The passed in RID is + // now relative to partition 0 and one or more partitions may have been dropped. Find the extent in the extents + // array rather than doing the math directly off of the fbo. + // extentIndex = fbo >> divShift; + + // partitionNum = "RID / rows per partition" + uint64_t partitionNum = rid / ( fFilesPerColumnPartition * fExtentsPerSegmentFile * fExtentRows ); + + // segmentNum = (RID % rows per partition) / rows per extent) % files per partition + // = (extent # within its partition) % files per partition + uint64_t segmentNum = + (((rid % (fFilesPerColumnPartition * fExtentsPerSegmentFile * fExtentRows)) / fExtentRows)) + % fFilesPerColumnPartition; + + // stripeWithinPartition = (RID - rows up to the partition before this one) / ?? + uint64_t stripeWithinPartition = + (rid - (partitionNum * fExtentsPerSegmentFile * fFilesPerColumnPartition * fExtentRows)) / + (fFilesPerColumnPartition * fExtentRows); + uint64_t blockOffset = stripeWithinPartition * colType.colWidth * 1024; + + bool found = false; + + for(uint i = 0; i < extents.size(); i++) + { + if(extents[i].dbRoot == dbRoot && (extents[i].partitionNum == partitionNum) && + (extents[i].segmentNum == segmentNum) && (extents[i].blockOffset == blockOffset)) + { + found = true; + extentIndex = i; + } + } + if(!found) + { + throw logic_error("ColumnCommandJL: setLBID didn't find the extent for the rid."); + } + // Calculate the lbid. + lbid = extents[extentIndex].range.start + extentOffset; // ostringstream os; // os << "CCJL: rid=" << rid << "; dbroot=" << dbRoot << "; partitionNum=" << partitionNum << "; segmentNum=" << segmentNum << "; stripeWithinPartition=" << // stripeWithinPartition << "; OID=" << OID << " LBID=" << lbid; // BRM::log(os.str()); + } } inline uint32_t ColumnCommandJL::getFBO(uint64_t lbid) { - uint32_t i; + uint i; uint64_t lastLBID; for (i = 0; i < extents.size(); i++) { @@ -219,19 +347,16 @@ inline uint32_t ColumnCommandJL::getFBO(uint64_t lbid) if (lbid >= (uint64_t) extents[i].range.start && lbid <= lastLBID) { - // @Bug 2889. Change for drop partition. Treat the FBO as if all of the partitions are - // still there as one or more partitions may have been dropped. Get the original index - // for this partition (i.e. what the index would be if all of the partitions were still - // there). The RIDs wind up being calculated off of this FBO for use in DML and DML - // needs calculates the partition number, segment number, etc. off of the RID and needs - // to remain the same when partitions are dropped. - // + // @Bug 2889. Change for drop partition. Treat the FBO as if all of the partitions are still there as one or more partitions + // may have been dropped. Get the original index for this partition (i.e. what the index would be if all of the partitions + // were still there). The RIDs wind up being calculated off of this FBO for use in DML and DML needs calculates the partition + // number, segment number, etc. off of the RID and needs to remain the same when partitions are dropped. + // originalIndex = extents in partitions above + // extents in this partition in stripes above + // file offset in this stripe - uint32_t originalIndex = - (extents[i].partitionNum * fExtentsPerSegmentFile * fFilesPerColumnPartition) + - ((extents[i].blockOffset / extents[i].colWid / 1024) * fFilesPerColumnPartition) + + uint originalIndex = (extents[i].partitionNum * fExtentsPerSegmentFile * fFilesPerColumnPartition) + + ((extents[i].blockOffset / extents[i].colWid / 1024) * fFilesPerColumnPartition) + extents[i].segmentNum; return (lbid - extents[i].range.start) + (originalIndex << divShift); @@ -256,13 +381,13 @@ string ColumnCommandJL::toString() { ostringstream ret; - ret << "ColumnCommandJL: " << filterCount << " filters colwidth=" << + ret << "ColumnCommandJL: " << filterCount << " filters colwidth=" << colType.colWidth << " oid=" << OID << " name=" << colName; if (isScan) ret << " (scan)"; if (isDict()) ret << " (tokens)"; - else if (execplan::isCharType(colType.colDataType)) + else if (isCharType()) ret << " (is char)"; return ret.str(); } @@ -272,6 +397,12 @@ uint16_t ColumnCommandJL::getWidth() return colType.colWidth; } +bool ColumnCommandJL::isCharType() const +{ + return (colType.colDataType == execplan::CalpontSystemCatalog::CHAR || + colType.colDataType == execplan::CalpontSystemCatalog::VARCHAR); +} + void ColumnCommandJL::reloadExtents() { int err; diff --git a/dbcon/joblist/columncommand-jl.h b/dbcon/joblist/columncommand-jl.h index 81c49bce..ffd7ff16 100644 --- a/dbcon/joblist/columncommand-jl.h +++ b/dbcon/joblist/columncommand-jl.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: columncommand-jl.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: columncommand-jl.h 8757 2012-07-27 19:00:31Z pleblanc $ // C++ Interface: columncommand // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -42,14 +42,15 @@ class ColumnCommandJL : public CommandJL { public: ColumnCommandJL(const pColScanStep &, std::vector lastLBID); + ColumnCommandJL(const pColScanStep &); ColumnCommandJL(const pColStep &); virtual ~ColumnCommandJL(); - virtual void createCommand(messageqcpp::ByteStream &bs) const; - virtual void runCommand(messageqcpp::ByteStream &bs) const; - void setLBID(uint64_t rid, uint32_t dbroot); + void createCommand(messageqcpp::ByteStream &bs) const; + void runCommand(messageqcpp::ByteStream &bs) const; + void setLBID(uint64_t rid, uint dbroot); uint8_t getTableColumnType(); - virtual std::string toString(); + std::string toString(); uint16_t getWidth(); CommandType getCommandType() { return COLUMN_COMMAND; } // @bug 1098 @@ -58,19 +59,15 @@ class ColumnCommandJL : public CommandJL const uint16_t getFilterCount() const { return filterCount; } const std::vector& getExtents() { return extents; } const execplan::CalpontSystemCatalog::ColType& getColType() const { return colType; } + bool isCharType() const; bool isDict() const { return fIsDict; } void scan(bool b) { isScan = b; } bool scan() { return isScan; } + uint8_t fcnOrd() { return fFcnOrd; } void reloadExtents(); -protected: - uint32_t currentExtentIndex; - messageqcpp::ByteStream filterString; - std::vector extents; - execplan::CalpontSystemCatalog::ColType colType; - private: ColumnCommandJL(); ColumnCommandJL(const ColumnCommandJL &); @@ -82,19 +79,23 @@ class ColumnCommandJL : public CommandJL uint32_t traceFlags; // probably move this to Command uint8_t BOP; uint32_t rpbShift, divShift, modMask; + std::vector extents; + messageqcpp::ByteStream filterString; uint16_t filterCount; + uint8_t fFcnOrd; std::vector fLastLbid; + // care about colDataType, colWidth and scale fields. On the PM the rest is uninitialized + execplan::CalpontSystemCatalog::ColType colType; bool fIsDict; // @Bug 2889. Added two members below for drop partition enhancement. // RJD: make sure that we keep enough significant digits around for partition math uint64_t fFilesPerColumnPartition; uint64_t fExtentsPerSegmentFile; + uint64_t fExtentRows; - uint32_t numDBRoots; - uint32_t dbroot; - + uint numDBRoots; static const unsigned DEFAULT_FILES_PER_COLUMN_PARTITION = 32; static const unsigned DEFAULT_EXTENTS_PER_SEGMENT_FILE = 4; }; diff --git a/dbcon/joblist/command-jl.cpp b/dbcon/joblist/command-jl.cpp index 62028c1d..102c8725 100644 --- a/dbcon/joblist/command-jl.cpp +++ b/dbcon/joblist/command-jl.cpp @@ -15,9 +15,18 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -#include -#include -namespace bu=boost::uuids; +// +// $Id: command-jl.cpp 8267 2012-01-18 17:58:09Z xlou $ +// C++ Implementation: command +// +// Description: +// +// +// Author: Patrick LeBlanc , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// #include "bpp-jl.h" @@ -26,24 +35,10 @@ using namespace messageqcpp; namespace joblist { -CommandJL::CommandJL() : - bpp(0), - OID(0), - tupleKey(0xFFFFFFFF) -{ - queryUuid = bu::nil_generator()(); - stepUuid = bu::nil_generator()(); -} +CommandJL::CommandJL() : bpp(NULL), OID(0), tupleKey(0xFFFFFFFF) { } CommandJL::CommandJL(const CommandJL &c) : - bpp(c.bpp), - OID(c.OID), - tupleKey(c.tupleKey), - colName(c.colName), - queryUuid(c.queryUuid), - stepUuid(c.stepUuid) -{ -} + bpp(c.bpp), OID(c.OID), tupleKey(c.tupleKey), colName(c.colName) { }; CommandJL::~CommandJL() { }; @@ -51,9 +46,35 @@ void CommandJL::createCommand(ByteStream &bs) const { bs << OID; bs << tupleKey; - bs << queryUuid; - bs << stepUuid; // no need to send column name to PM as of rel.2.2.5. } +void CommandJL::runCommand(ByteStream &bs) const +{ } + +void CommandJL::setBatchPrimitiveProcessor(BatchPrimitiveProcessorJL *b) +{ + bpp = b; +} + +uint32_t CommandJL::getOID() +{ + return OID; } + +const std::string& CommandJL::getColName() +{ + return colName; +} + +void CommandJL::setTupleKey(uint32_t tkey) +{ + tupleKey = tkey; +} + +uint32_t CommandJL::getTupleKey() +{ + return tupleKey; +} + +}; diff --git a/dbcon/joblist/command-jl.h b/dbcon/joblist/command-jl.h index e54c5497..f0a7ba30 100644 --- a/dbcon/joblist/command-jl.h +++ b/dbcon/joblist/command-jl.h @@ -15,14 +15,24 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +// +// $Id: command-jl.h 8476 2012-04-25 22:28:15Z xlou $ +// C++ Interface: command +// +// Description: +// +// +// Author: Patrick LeBlanc , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// /** @file */ #ifndef COMMANDJL_H #define COMMANDJL_H #include -#include - #include "serializeable.h" #include "bytestream.h" @@ -33,57 +43,49 @@ class BatchPrimitiveProcessorJL; class CommandJL { -public: - CommandJL(); - CommandJL(const CommandJL &); - virtual ~CommandJL(); - - // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, - // for a DictStep it's a token. - virtual void setLBID(uint64_t data, uint32_t dbroot) = 0; - virtual uint8_t getTableColumnType() = 0; - virtual std::string toString() = 0; - virtual void createCommand(messageqcpp::ByteStream &) const; - virtual void runCommand(messageqcpp::ByteStream &) const = 0; - uint32_t getOID() const { return OID; } - const std::string& getColName() const { return colName; } - void setTupleKey(uint32_t tkey) { tupleKey = tkey; } - uint32_t getTupleKey() const { return tupleKey; } - virtual uint16_t getWidth() = 0; - const boost::uuids::uuid& getQueryUuid() const { return queryUuid; } - void setQueryUuid(const boost::uuids::uuid& u) { queryUuid = u; } - const boost::uuids::uuid& getStepUuid() const { return stepUuid; } - void setStepUuid(const boost::uuids::uuid& u) { stepUuid = u; } - - void setBatchPrimitiveProcessor(BatchPrimitiveProcessorJL* b) { bpp = b; } - - enum CommandType { - NONE, - COLUMN_COMMAND, - DICT_STEP, - DICT_SCAN, - PASS_THRU, - RID_TO_STRING, - FILTER_COMMAND, - PSEUDO_COLUMN - }; - - virtual CommandType getCommandType() = 0; - -protected: - BatchPrimitiveProcessorJL *bpp; - uint32_t OID; - uint32_t tupleKey; - std::string colName; // for stats - boost::uuids::uuid queryUuid; - boost::uuids::uuid stepUuid; - -private: +// #warning got CommandJL definition + public: + CommandJL(); + CommandJL(const CommandJL &); + virtual ~CommandJL(); + + virtual void setLBID(uint64_t data, uint dbroot) = 0; // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. + virtual uint8_t getTableColumnType() = 0; + virtual std::string toString() = 0; + virtual void createCommand(messageqcpp::ByteStream &) const; + virtual void runCommand(messageqcpp::ByteStream &) const; + virtual uint32_t getOID(); + virtual const std::string& getColName(); + virtual void setTupleKey(uint32_t tkey); + virtual uint32_t getTupleKey(); + virtual uint16_t getWidth() = 0; + + void setBatchPrimitiveProcessor(BatchPrimitiveProcessorJL *); + + enum CommandType { + NONE, + COLUMN_COMMAND, + DICT_STEP, + DICT_SCAN, + PASS_THRU, + RID_TO_STRING, + FILTER_COMMAND + }; + + virtual CommandType getCommandType() = 0; + + protected: + BatchPrimitiveProcessorJL *bpp; + uint32_t OID; + uint32_t tupleKey; + std::string colName; // for stats + + private: }; typedef boost::shared_ptr SCommand; -} +}; #endif diff --git a/dbcon/joblist/constantdatalist.h b/dbcon/joblist/constantdatalist.h new file mode 100644 index 00000000..8db42bca --- /dev/null +++ b/dbcon/joblist/constantdatalist.h @@ -0,0 +1,120 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: constantdatalist.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + *****************************************************************************/ + +/** @file + * class XXX interface + */ + +#include "datalist.h" + +#ifndef _CONSTANTDATALIST_H_ +#define _CONSTANTDATALIST_H_ + +namespace joblist { + +/** @brief class ConstantDataList + * + */ +template +class ConstantDataList : public DataList +{ + typedef DataList base; + + public: + ConstantDataList(const element_t &); + virtual ~ConstantDataList(); + + ConstantDataList& operator= + (const ConstantDataList &dl); + + void insert(const element_t &e); + void insert(const std::vector &e); + uint64_t getIterator(); + bool next(uint64_t it, element_t *e); + void setMultipleProducers(bool b); + + protected: + + private: + explicit ConstantDataList(); + ConstantDataList(const ConstantDataList &); + + element_t value; +}; + +template +ConstantDataList::ConstantDataList() +{ } + +template +ConstantDataList::ConstantDataList(const element_t &e) +{ + value = e; +} + +template +ConstantDataList::~ConstantDataList() +{ } + +template +ConstantDataList & ConstantDataList::operator= + (const ConstantDataList &dl) +{ + value = dl.value; +} + +template +void ConstantDataList::insert(const element_t &e) +{ + value = e; +} + +template +void ConstantDataList::insert(const std::vector &e) +{ + throw std::logic_error("ConstantDataList::insert(vector) isn't implemented yet"); +} + +template +uint64_t ConstantDataList::getIterator() +{ + return 0; +} + +template +bool ConstantDataList::next(uint64_t id, element_t *e) +{ + if (base::noMoreInput) + return false; + + *e = value; + return true; +} + +template +void ConstantDataList::setMultipleProducers(bool b) +{ } + + +} // namespace + +#endif diff --git a/dbcon/joblist/crossenginestep.cpp b/dbcon/joblist/crossenginestep.cpp index 0da92ea6..448942f1 100644 --- a/dbcon/joblist/crossenginestep.cpp +++ b/dbcon/joblist/crossenginestep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: crossenginestep.cpp 9709 2013-07-20 06:08:46Z xlou $ +// $Id: crossenginestep.cpp 9242 2013-02-01 13:31:57Z rdempsey $ #include //#define NDEBUG @@ -26,7 +26,6 @@ using namespace std; #include #include -#include using namespace boost; #include "messagequeue.h" @@ -48,9 +47,6 @@ using namespace rowgroup; #include "dataconvert.h" using namespace dataconvert; -#include "querytele.h" -using namespace querytele; - #include "funcexp.h" #include "jobstep.h" @@ -60,132 +56,27 @@ using namespace querytele; #include "libdrizzle-2.0/drizzle.h" #include "libdrizzle-2.0/drizzle_client.h" -// wrapper for drizzle -namespace -{ - -class DrizzleMySQL -{ -public: - DrizzleMySQL(); - ~DrizzleMySQL(); - - // init: host port username passwd db - int init(const char*, unsigned int, const char*, const char*, const char*); - - // run the query - int run(const char* q); - - int getFieldCount() { return drizzle_result_column_count(fDrzrp); } - int getRowCount() { return drizzle_result_row_count(fDrzrp); } - char** nextRow() { return drizzle_row_next(fDrzrp); } - const string& getError() { return fErrStr; } - -private: - drizzle_st* fDrzp; - drizzle_con_st* fDrzcp; - drizzle_result_st* fDrzrp; - string fErrStr; -}; - -DrizzleMySQL::DrizzleMySQL() : fDrzp(NULL), fDrzcp(NULL), fDrzrp(NULL) -{ -} - - -DrizzleMySQL::~DrizzleMySQL() -{ - if (fDrzrp) - { - drizzle_result_free(fDrzrp); - } - fDrzrp = NULL; - - if (fDrzcp) - { - drizzle_con_close(fDrzcp); - drizzle_con_free(fDrzcp); - } - fDrzcp = NULL; - - if (fDrzp) - { - drizzle_free(fDrzp); - } - fDrzp = NULL; -} - - -int DrizzleMySQL::init(const char* h, unsigned int p, const char* u, const char* w, const char* d) -{ - int ret = -1; - - fDrzp = drizzle_create(); - if (fDrzp != NULL) - { - fDrzcp = drizzle_con_add_tcp(fDrzp, h, p, u, w, d, DRIZZLE_CON_MYSQL); - if (fDrzcp != NULL) - { - ret = drizzle_con_connect(fDrzcp); - if (ret != 0) - fErrStr = "fatal error in drizzle_con_connect()"; - } - else - { - fErrStr = "fatal error in drizzle_con_add_tcp()"; - } - } - else - { - fErrStr = "fatal error in drizzle_create()"; - } - - return ret; -} - - -int DrizzleMySQL::run(const char* query) -{ - int ret = 0; - drizzle_return_t drzret; - fDrzrp = drizzle_query_str(fDrzcp, fDrzrp, query, &drzret); - if (drzret == 0 && fDrzrp != NULL) - { - ret = drzret = drizzle_result_buffer(fDrzrp); - if (drzret != 0) - fErrStr = "fatal error reading result from crossengine client lib"; - } - else - { - fErrStr = "fatal error executing query in crossengine client lib"; - if (drzret != 0) - ret = drzret; - else - ret = -1; - } - - return ret; -} - - -} - - namespace joblist { CrossEngineStep::CrossEngineStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t statementId, const string& schema, const string& table, const string& alias, const JobInfo& jobInfo) : - BatchPrimitive(jobInfo), + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fStepId(0), fRowsRetrieved(0), fRowsReturned(0), fRowsPerGroup(256), fOutputDL(NULL), fOutputIterator(0), fEndOfResult(false), + fDelivery(false), fSchema(schema), fTable(table), fAlias(alias), @@ -194,7 +85,6 @@ CrossEngineStep::CrossEngineStep( { fExtendedInfo = "CES: "; getMysqldInfo(jobInfo); - fQtc.stepParms().stepType = StepTeleStats::T_CES; } @@ -209,25 +99,6 @@ void CrossEngineStep::setOutputRowGroup(const rowgroup::RowGroup& rg) } -void CrossEngineStep::deliverStringTableRowGroup(bool b) -{ - // results are either using setField, or mapping to delivered row group - fRowGroupDelivered.setUseStringTable(b); -} - - -bool CrossEngineStep::deliverStringTableRowGroup() const -{ - return fRowGroupDelivered.usesStringTable(); -} - - -void CrossEngineStep::addFcnJoinExp(const vector& fe) -{ - fFeFcnJoin = fe; -} - - void CrossEngineStep::addFcnExpGroup1(const boost::shared_ptr& fe) { fFeFilters = fe; @@ -240,7 +111,7 @@ void CrossEngineStep::setFE1Input(const rowgroup::RowGroup& rg) } -void CrossEngineStep::setFcnExpGroup3(const vector& fe) +void CrossEngineStep::setFcnExpGroup3(const vector >& fe) { fFeSelects = fe; } @@ -257,15 +128,17 @@ void CrossEngineStep::makeMappings() fFe1Column.reset(new int[fColumnCount]); for (uint64_t i = 0; i < fColumnCount; ++i) fFe1Column[i] = -1; - - if (fFeFilters != NULL || fFeFcnJoin.size() > 0) + + if (fFeFilters != NULL) { - const std::vector& colInFe1 = fRowGroupFe1.getKeys(); + const std::vector& colInFe1 = fRowGroupFe1.getKeys(); for (uint64_t i = 0; i < colInFe1.size(); i++) { - map::iterator it = fColumnMap.find(colInFe1[i]); + map::iterator it = fColumnMap.find(colInFe1[i]); if (it != fColumnMap.end()) fFe1Column[it->second] = i; + else + throw logic_error("Column not projected."); } fFeMapping1 = makeMapping(fRowGroupFe1, fRowGroupOut); @@ -300,7 +173,7 @@ void CrossEngineStep::setField(int i, const char* value, Row& row) } -inline void CrossEngineStep::addRow(RGData &data) +inline void CrossEngineStep::addRow(shared_array& data) { fRowDelivered.setRid(fRowsReturned%fRowsPerGroup); fRowDelivered.nextRow(); @@ -309,8 +182,8 @@ inline void CrossEngineStep::addRow(RGData &data) if (++fRowsReturned%fRowsPerGroup == 0) { fOutputDL->insert(data); - data.reinit(fRowGroupDelivered, fRowsPerGroup); - fRowGroupDelivered.setData(&data); + data.reset(new uint8_t[fRowGroupDelivered.getDataSize(fRowsPerGroup)]); + fRowGroupDelivered.setData(data.get()); fRowGroupDelivered.resetRowGroup(fRowsReturned); fRowGroupDelivered.getRow(0, &fRowDelivered); } @@ -349,15 +222,9 @@ int64_t CrossEngineStep::convertValueNum( case CalpontSystemCatalog::TINYINT: rv = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UTINYINT: - rv = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::SMALLINT: rv = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::USMALLINT: - rv = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: #ifdef _MSC_VER @@ -366,18 +233,10 @@ int64_t CrossEngineStep::convertValueNum( rv = boost::any_cast(anyVal); #endif break; - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - rv = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::BIGINT: rv = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UBIGINT: - rv = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { float f = boost::any_cast(anyVal); //N.B. There is a bug in boost::any or in gcc where, if you store a nan, @@ -395,7 +254,6 @@ int64_t CrossEngineStep::convertValueNum( } break; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { double d = boost::any_cast(anyVal); double* dp = &d; @@ -422,7 +280,6 @@ int64_t CrossEngineStep::convertValueNum( rv = boost::any_cast(anyVal); break; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: if (ct.colWidth == CalpontSystemCatalog::ONE_BYTE) rv = boost::any_cast(anyVal); else if (ct.colWidth == CalpontSystemCatalog::TWO_BYTE) @@ -433,7 +290,7 @@ int64_t CrossEngineStep::convertValueNum( #else rv = boost::any_cast(anyVal); #endif - else + else rv = boost::any_cast(anyVal); break; default: @@ -457,7 +314,7 @@ void CrossEngineStep::run() // idbassert(!fDelivery); if (fOutputJobStepAssociation.outSize() == 0) - throw logic_error("No output data list for cross engine step."); + throw logic_error("No output data list for non-delivery constant step."); fOutputDL = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); if (fOutputDL == NULL) @@ -481,40 +338,45 @@ void CrossEngineStep::join() void CrossEngineStep::execute() { - DrizzleMySQL drizzle; - int ret = 0; - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - + drizzle_st* drzp=0; + drzp = drizzle_create(); + if (drzp == 0) + handleMySqlError("fatal error initializing crossengine client lib", -1); try { - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - ret = drizzle.init(fHost.c_str(), fPort, fUser.c_str(), fPasswd.c_str(), fSchema.c_str()); - if (ret != 0) - handleMySqlError(drizzle.getError().c_str(), ret); + drizzle_con_st* drzcp=0; + drzcp = drizzle_con_add_tcp(drzp, fHost.c_str(), fPort, fUser.c_str(), fPasswd.c_str(), + fSchema.c_str(), DRIZZLE_CON_MYSQL); + if (drzcp == 0) + handleMySqlError("fatal error setting up parms in crossengine client lib", -1); + drizzle_return_t drzret; + drzret = drizzle_con_connect(drzcp); + if (drzret != 0) + handleMySqlError("fatal error connecting to InfiniDB in crossengine client lib", drzret); string query(makeQuery()); fLogger->logMessage(logging::LOG_TYPE_INFO, "QUERY to foreign engine: " + query); if (traceOn()) cout << "QUERY: " << query << endl; - ret = drizzle.run(query.c_str()); - if (ret != 0) - handleMySqlError(drizzle.getError().c_str(), ret); + drizzle_return_t* drzretp = &drzret; + drizzle_result_st* drzrp=0; + drzrp = drizzle_query_str(drzcp, drzrp, query.c_str(), drzretp); + if (drzret != 0 || drzrp == 0) + handleMySqlError("fatal error executing query in crossengine client lib", drzret); - int num_fields = drizzle.getFieldCount(); + drzret = drizzle_result_buffer(drzrp); + if (drzret != 0) + handleMySqlError("fatal error reading results from InfiniDB in crossengine client lib", drzret); + + int num_fields = drizzle_result_column_count(drzrp); - char** rowIn; // input - //shared_array rgDataDelivered; // output - RGData rgDataDelivered; + drizzle_row_t rowIn; // input + shared_array rgDataDelivered; // output fRowGroupDelivered.initRow(&fRowDelivered); - // use getDataSize() i/o getMaxDataSize() to make sure there are 8192 rows. - rgDataDelivered.reinit(fRowGroupDelivered, fRowsPerGroup); - fRowGroupDelivered.setData(&rgDataDelivered); + // use getDataSize() i/o getMaxDataSize() to make sure there are fRowsPerGroup rows. + rgDataDelivered.reset(new uint8_t[fRowGroupDelivered.getDataSize(fRowsPerGroup)]); + fRowGroupDelivered.setData(rgDataDelivered.get()); fRowGroupDelivered.resetRowGroup(0); fRowGroupDelivered.getRow(0, &fRowDelivered); @@ -523,11 +385,9 @@ void CrossEngineStep::execute() // Any functions to evaluate makeMappings(); - bool doFE1 = ((fFeFcnJoin.size() > 0) || (fFeFilters != NULL)); - bool doFE3 = (fFeSelects.size() > 0); - if (!doFE1 && !doFE3) + if (fFeSelects.empty() && fFeFilters == NULL) { - while ((rowIn = drizzle.nextRow()) && !cancelled()) + while ((rowIn = drizzle_row_next(drzrp)) && fInputJobStepAssociation.status() == 0) { for(int i = 0; i < num_fields; i++) setField(i, rowIn[i], fRowDelivered); @@ -536,15 +396,15 @@ void CrossEngineStep::execute() } } - else if (doFE1 && !doFE3) // FE in WHERE clause only + else if (fFeSelects.empty() && fFeFilters != NULL) // FE in WHERE clause only { shared_array rgDataFe1; // functions in where clause Row rowFe1; // row for fe evaluation - fRowGroupFe1.initRow(&rowFe1, true); + fRowGroupFe1.initRow(&rowFe1); rgDataFe1.reset(new uint8_t[rowFe1.getSize()]); rowFe1.setData(rgDataFe1.get()); - - while ((rowIn = drizzle.nextRow()) && !cancelled()) + + while ((rowIn = drizzle_row_next(drzrp)) && fInputJobStepAssociation.status() == 0) { // Parse the columns used in FE1 first, the other column may not need be parsed. for(int i = 0; i < num_fields; i++) @@ -553,12 +413,9 @@ void CrossEngineStep::execute() setField(fFe1Column[i], rowIn[i], rowFe1); } - if (fFeFilters && fFeInstance->evaluate(rowFe1, fFeFilters.get()) == false) + if (fFeInstance->evaluate(rowFe1, fFeFilters.get()) == false) continue; - // evaluate the FE join column - fFeInstance->evaluate(rowFe1, fFeFcnJoin); - // Pass throug the parsed columns, and parse the remaining columns. applyMapping(fFeMapping1, rowFe1, &fRowDelivered); for(int i = 0; i < num_fields; i++) @@ -571,43 +428,41 @@ void CrossEngineStep::execute() } } - else if (!doFE1 && doFE3) // FE in SELECT clause only + else if (!fFeSelects.empty() && fFeFilters == NULL) // FE in SELECT clause only { shared_array rgDataFe3; // functions in select clause Row rowFe3; // row for fe evaluation - fRowGroupOut.initRow(&rowFe3, true); + fRowGroupOut.initRow(&rowFe3); rgDataFe3.reset(new uint8_t[rowFe3.getSize()]); rowFe3.setData(rgDataFe3.get()); - - while ((rowIn = drizzle.nextRow()) && !cancelled()) + + while ((rowIn = drizzle_row_next(drzrp)) && fInputJobStepAssociation.status() == 0) { for(int i = 0; i < num_fields; i++) setField(i, rowIn[i], rowFe3); fFeInstance->evaluate(rowFe3, fFeSelects); - fFeInstance->evaluate(rowFe3, fFeSelects); - applyMapping(fFeMapping3, rowFe3, &fRowDelivered); addRow(rgDataDelivered); } } - else // FE in SELECT clause, FE join and WHERE clause + else // FE in SELECT clause and WHERE clause { shared_array rgDataFe1; // functions in where clause Row rowFe1; // row for fe1 evaluation - fRowGroupFe1.initRow(&rowFe1, true); + fRowGroupFe1.initRow(&rowFe1); rgDataFe1.reset(new uint8_t[rowFe1.getSize()]); rowFe1.setData(rgDataFe1.get()); shared_array rgDataFe3; // functions in select clause Row rowFe3; // row for fe3 evaluation - fRowGroupOut.initRow(&rowFe3, true); + fRowGroupOut.initRow(&rowFe3); rgDataFe3.reset(new uint8_t[rowFe3.getSize()]); rowFe3.setData(rgDataFe3.get()); - - while ((rowIn = drizzle.nextRow()) && !cancelled()) + + while ((rowIn = drizzle_row_next(drzrp)) && fInputJobStepAssociation.status() == 0) { // Parse the columns used in FE1 first, the other column may not need be parsed. for(int i = 0; i < num_fields; i++) @@ -616,12 +471,9 @@ void CrossEngineStep::execute() setField(fFe1Column[i], rowIn[i], rowFe1); } - if (fFeFilters && fFeInstance->evaluate(rowFe1, fFeFilters.get()) == false) + if (fFeInstance->evaluate(rowFe1, fFeFilters.get()) == false) continue; - // evaluate the FE join column - fFeInstance->evaluate(rowFe1, fFeFcnJoin); - // Pass throug the parsed columns, and parse the remaining columns. applyMapping(fFeMapping1, rowFe1, &rowFe3); for(int i = 0; i < num_fields; i++) @@ -637,29 +489,44 @@ void CrossEngineStep::execute() } } - //INSERT_ADAPTER(fOutputDL, rgDataDelivered); fOutputDL->insert(rgDataDelivered); - fRowsRetrieved = drizzle.getRowCount(); + fRowsRetrieved = drizzle_result_row_count(drzrp); + drizzle_result_free(drzrp); + drzrp = 0; + drizzle_con_close(drzcp); + drizzle_con_free(drzcp); + drzcp = 0; + drizzle_free(drzp); + drzp = 0; } catch (IDBExcept& iex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId); + catchHandler(iex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + { + fOutputJobStepAssociation.status(iex.errorCode()); + fOutputJobStepAssociation.errorMessage(iex.what()); + } } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_CROSS_ENGINE_CONNECT, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + { + fOutputJobStepAssociation.status(ERR_CROSS_ENGINE_CONNECT); + fOutputJobStepAssociation.errorMessage(ex.what()); + } } catch(...) { - catchHandler("CrossEngineStep execute caught an unknown exception", - ERR_CROSS_ENGINE_CONNECT, fErrorInfo, fSessionId); + catchHandler("CrossEngineStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + { + fOutputJobStepAssociation.status(ERR_CROSS_ENGINE_CONNECT); + fOutputJobStepAssociation.errorMessage("unknown exception"); + } } - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - fEndOfResult = true; fOutputDL->endOfInput(); @@ -683,32 +550,29 @@ void CrossEngineStep::setBPP(JobStep* jobStep) string bop = " AND "; if (pcs != 0) { - if (dynamic_cast(pcs) != NULL) - throw logic_error("No Psedo Column for foreign engine."); - if (pcs->BOP() == BOP_OR) bop = " OR "; addFilterStr(pcs->getFilters(), bop); } - else if ((pcss = dynamic_cast(jobStep)) != NULL) + else if ((pcss = dynamic_cast(jobStep)) != 0) { if (pcss->BOP() == BOP_OR) bop = " OR "; addFilterStr(pcss->getFilters(), bop); } - else if ((pds = dynamic_cast(jobStep)) != NULL) + else if ((pds = dynamic_cast(jobStep)) != 0) { if (pds->BOP() == BOP_OR) bop = " OR "; addFilterStr(pds->getFilters(), bop); } - else if ((pdss = dynamic_cast(jobStep)) != NULL) + else if ((pdss = dynamic_cast(jobStep)) != 0) { if (pds->BOP() == BOP_OR) bop = " OR "; addFilterStr(pdss->getFilters(), bop); } - else if ((fs = dynamic_cast(jobStep)) != NULL) + else if ((fs = dynamic_cast(jobStep)) != 0) { addFilterStr(fs->getFilters(), bop); } @@ -774,11 +638,6 @@ void CrossEngineStep::handleMySqlError(const char* errStr, unsigned int errCode) { ostringstream oss; oss << errStr << "(" << errCode << ")"; - if (errCode == (unsigned int) -1) - oss << "(null pointer)"; - else - oss << "(" << errCode << ")"; - throw IDBExcept(oss.str(), ERR_CROSS_ENGINE_CONNECT); return; @@ -797,12 +656,11 @@ const RowGroup& CrossEngineStep::getDeliveredRowGroup() const } -uint32_t CrossEngineStep::nextBand(messageqcpp::ByteStream &bs) +uint CrossEngineStep::nextBand(messageqcpp::ByteStream &bs) { - //shared_array rgDataOut; - RGData rgDataOut; + shared_array rgDataOut; bool more = false; - uint32_t rowCount = 0; + uint rowCount = 0; try { @@ -812,45 +670,43 @@ uint32_t CrossEngineStep::nextBand(messageqcpp::ByteStream &bs) if (traceOn() && dlTimes.FirstReadTime().tv_sec ==0) dlTimes.setFirstReadTime(); - if (more && !cancelled()) + if (more && (0 == fOutputJobStepAssociation.status()) && !die) { - fRowGroupDelivered.setData(&rgDataOut); - fRowGroupDelivered.serializeRGData(bs); + fRowGroupDelivered.setData(rgDataOut.get()); + bs.load(fRowGroupDelivered.getData(), fRowGroupDelivered.getDataSize()); rowCount = fRowGroupDelivered.getRowCount(); } else { - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + if (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_IN_DELIVERY, fErrorInfo, fSessionId); - - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_DELIVERY); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } catch(...) { - catchHandler("CrossEngineStep next band caught an unknown exception", - ERR_IN_DELIVERY, fErrorInfo, fSessionId); - - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + catchHandler("CrossEngineStep next band caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_DELIVERY); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } if (fEndOfResult) { // send an empty / error band - rgDataOut.reinit(fRowGroupDelivered, 0); - fRowGroupDelivered.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupDelivered.getEmptySize()]); + fRowGroupDelivered.setData(rgDataOut.get()); fRowGroupDelivered.resetRowGroup(0); - fRowGroupDelivered.setStatus(status()); - fRowGroupDelivered.serializeRGData(bs); + fRowGroupDelivered.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgDataOut.get(), fRowGroupDelivered.getDataSize()); if (traceOn()) { @@ -898,8 +754,7 @@ void CrossEngineStep::printCalTrace() << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); @@ -923,6 +778,12 @@ void CrossEngineStep::formatMiniStats() } +// static +void CrossEngineStep::init_mysqlcl_idb() +{ +} + + } //namespace // vim:ts=4 sw=4: diff --git a/dbcon/joblist/crossenginestep.h b/dbcon/joblist/crossenginestep.h index e7378137..54365088 100644 --- a/dbcon/joblist/crossenginestep.h +++ b/dbcon/joblist/crossenginestep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: crossenginestep.h 9620 2013-06-13 15:51:52Z pleblanc $ +// $Id: crossenginestep.h 8866 2012-09-07 15:58:05Z xlou $ #ifndef JOBLIST_CROSSENGINESTEP_H @@ -50,6 +50,9 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep /** @brief CrossEngineStep constructor */ CrossEngineStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t statementId, const string& schema, const string& table, const string& alias, @@ -62,23 +65,50 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep /** @brief virtual void Run method */ void run(); - - /** @brief virtual void join method - */ void join(); - /** @brief virtual string toString method + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * */ + const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + void stepId(uint16_t stepId) { fStepId = stepId; } + uint16_t stepId() const { return fStepId; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t verId() const { return fVerId; } + uint32_t statementId() const { return fStatementId; } + const std::string toString() const; - // from BatchPrimitive + // from BatchPrimitive bool getFeederFlag() const { return false; } - uint64_t getLastTupleId() const { return 0; } - uint32_t getStepCount () const { return 1; } + execplan::CalpontSystemCatalog::OID getLastOid() const { return 0; } + uint getStepCount () const { return 1; } void setBPP(JobStep* jobStep); void setFirstStepType(PrimitiveStepType firstStepType) {} void setIsProjectionOnly() {} - void setLastTupleId(uint64_t id) {} + void setLastOid(execplan::CalpontSystemCatalog::OID colOid) {} void setOutputType(BPSOutputType outputType) {} void setProjectBPP(JobStep* jobStep1, JobStep* jobStep2); void setStepCount() {} @@ -90,6 +120,7 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep bool wasStepRun() const { return fRunExecuted; } BPSOutputType getOutputType() const { return ROW_GROUP; } uint64_t getRows() const { return fRowsReturned; } +// const execplan::CalpontSystemCatalog::TableName& tableName() const { return fTableName; } const string& schemaName() const { return fSchema; } const string& tableName() const { return fTable; } const string& tableAlias() const { return fAlias; } @@ -99,22 +130,22 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep const rowgroup::RowGroup& getOutputRowGroup() const; // from DECEventListener - void newPMOnline(uint32_t) {} - + void newPMOnline(uint) {} + const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); + void logger(const SPJL& logger) { fLogger = logger; } + void setIsDelivery(bool b) { fDelivery = b; } - void addFcnJoinExp(const vector&); void addFcnExpGroup1(const boost::shared_ptr&); void setFE1Input(const rowgroup::RowGroup&); - void setFcnExpGroup3(const vector&); + void setFcnExpGroup3(const vector >&); void setFE23Output(const rowgroup::RowGroup&); void addFilter(JobStep* jobStep); void addProject(JobStep* jobStep); + static void init_mysqlcl_idb(); protected: virtual void execute(); @@ -123,16 +154,24 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep virtual void addFilterStr(const std::vector&, const std::string&); virtual std::string makeQuery(); virtual void setField(int, const char*, rowgroup::Row&); - inline void addRow(rowgroup::RGData &); - //inline void addRow(boost::shared_array&); + inline void addRow(boost::shared_array&); virtual int64_t convertValueNum( const char*, const execplan::CalpontSystemCatalog::ColType&, int64_t); virtual void formatMiniStats(); virtual void printCalTrace(); virtual void handleMySqlError(const char*, unsigned int); + // for base + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; uint64_t fRowsRetrieved; uint64_t fRowsReturned; + SPJL fLogger; uint64_t fRowsPerGroup; // output rowgroup and row @@ -156,6 +195,7 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep boost::scoped_ptr fRunner; OIDVector fOIDVector; bool fEndOfResult; + bool fDelivery; bool fRunExecuted; // MySQL server info @@ -174,8 +214,7 @@ class CrossEngineStep : public BatchPrimitive, public TupleDeliveryStep // Function & Expression columns boost::shared_ptr fFeFilters; std::vector > fFeSelects; - std::vector > fFeFcnJoin; - std::map fColumnMap; // projected key position (k->p) + std::map fColumnMap; // projected key position (k->p) uint64_t fColumnCount; boost::scoped_array fFe1Column; boost::shared_array fFeMapping1; diff --git a/dbcon/joblist/datalist.h b/dbcon/joblist/datalist.h index 296d25a5..4e7c15af 100644 --- a/dbcon/joblist/datalist.h +++ b/dbcon/joblist/datalist.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: datalist.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: datalist.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ -/** @file +/** @file * DataList interface definition */ @@ -34,7 +34,7 @@ namespace joblist { -/* +/* Need to implement the following members in element_t: copy constructor = operator @@ -45,20 +45,20 @@ namespace joblist * * DataList is an abstract interface that defines container-like methods. * A producer adds elements using insert(e). When it's done, it calls - * endOfInput(). - * + * endOfInput(). + * * To retrieve elements, a * consumer calls getIterator() once, then next(iterator, &e) for every * element in the DataList. next returns true when there was data to * consume, false when there was no data (e will not be changed in this case). * - * The exact semantics of these calls depends on the derived class's - * implementation. - * + * The exact semantics of these calls depends on the derived class's + * implementation. + * * - ConstantDataList is the simplest DataList. All it does is return * the same value over and over again. It simplifies things upstream * significantly for that behavior to be packaged as a DataList. - * + * * - FIFO is made for simultaneous access by readers * and writers and have a maximum size, so it's basically an implementation * of the producer-consumer problem right out of the algorithm textbooks, @@ -72,7 +72,7 @@ namespace joblist * very large amounts of data. Simultaneous access doesn't make sense here, * so next() blocks until the producer calls endOfInput(). * - * - BucketDL is used to cluster data according to some function provided + * - BucketDL is used to cluster data according to some function provided * by the caller. This DataList is used by the Hash join jobstep to reduce * the too-large-for-memory hash problem into a set of subhashes. It is * also used as the intermediate step between a large random dataset @@ -82,11 +82,11 @@ namespace joblist * difference between this and the WSDL class is that the underlying container * is an STL set, so it has some notion of order. It also exposes an interface * for loading and saving sets because band boundaries are only known at a higher - * level. To use this class, be sure you have the \< operator defined for + * level. To use this class, be sure you have the \< operator defined for * whatever element type you're storing. */ template -class DataList +class DataList { public: typedef element_t value_type; @@ -123,7 +123,7 @@ class DataList boost::mutex& getMutex() { return mutex; } // why in the world is this necessary in FIFO? - boost::mutex mutex; + boost::mutex mutex; bool noMoreInput; uint64_t consumersFinished; uint32_t fElemDiskFirstSize; //byte size of element.first saved to disk diff --git a/dbcon/joblist/datalistimpl.h b/dbcon/joblist/datalistimpl.h index d254efa2..90f52450 100644 --- a/dbcon/joblist/datalistimpl.h +++ b/dbcon/joblist/datalistimpl.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: datalistimpl.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: datalistimpl.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ -/** @file +/** @file * class XXX interface */ @@ -46,7 +46,7 @@ class DataListImpl : public DataList { public: - DataListImpl(uint32_t numConsumers); + DataListImpl(uint numConsumers); DataListImpl(const DataListImpl &dl); virtual ~DataListImpl(); @@ -58,9 +58,9 @@ class DataListImpl : public DataList virtual uint64_t getIterator(); virtual bool next(uint64_t it, element_t *e); - virtual void setNumConsumers(uint32_t); - virtual uint32_t getNumConsumers() const; - void resetNumConsumers(uint32_t numConsumers); + virtual void setNumConsumers(uint); + virtual uint getNumConsumers() const; + void resetNumConsumers(uint numConsumers); protected: bool endOfData(uint64_t id) const; @@ -84,25 +84,25 @@ DataListImpl::DataListImpl() : DataList(), c( { } template -void DataListImpl::setNumConsumers(uint32_t nc) +void DataListImpl::setNumConsumers(uint nc) { resetNumConsumers(nc); } template -uint32_t DataListImpl::getNumConsumers() const +uint DataListImpl::getNumConsumers() const { return numConsumers; } template -void DataListImpl::resetNumConsumers(uint32_t nc) +void DataListImpl::resetNumConsumers(uint nc) { if (itIndex != 0) throw std::logic_error("DataListImpl::resetNumConsumers(): attempt to change numConsumers " "after iterators have been issued"); - uint32_t i; + uint i; numConsumers = nc; delete [] cIterators; @@ -112,9 +112,9 @@ void DataListImpl::resetNumConsumers(uint32_t nc) } template -DataListImpl::DataListImpl(uint32_t nc) : DataList() +DataListImpl::DataListImpl(uint nc) : DataList() { - uint32_t i; + uint i; numConsumers = nc; itIndex = 0; @@ -126,15 +126,15 @@ DataListImpl::DataListImpl(uint32_t nc) : DataList DataListImpl::DataListImpl - (const DataListImpl &dl) + (const DataListImpl &dl) : DataList(dl) -{ +{ int i; c = dl.c; numConsumers = dl.numConsumers; itIndex = dl.itIndex; - + //delete [] cIterators; cIterators = new typename container_t::iterator[numConsumers]; for (i = 0; i < numConsumers; i++) @@ -143,7 +143,7 @@ DataListImpl::DataListImpl template DataListImpl::~DataListImpl() -{ +{ delete c; delete [] cIterators; }; @@ -155,7 +155,7 @@ DataListImpl & DataListImpl::ope { uint64_t i; - static_cast >(*this) = + static_cast >(*this) = static_cast >(dl); delete c; c = dl.c; @@ -185,8 +185,8 @@ uint64_t DataListImpl::getIterator() } template -inline void DataListImpl::insert(const element_t &e) -{ +inline void DataListImpl::insert(const element_t &e) +{ c->insert(c->end(), e); } @@ -199,11 +199,11 @@ inline void DataListImpl::insert(const std::vector -inline typename container_t::iterator DataListImpl::iInsert(const element_t &e) -{ +inline typename container_t::iterator DataListImpl::iInsert(const element_t &e) +{ return c->insert(c->end(), e); } diff --git a/dbcon/joblist/deliverystep.cpp b/dbcon/joblist/deliverystep.cpp new file mode 100644 index 00000000..49a8bccd --- /dev/null +++ b/dbcon/joblist/deliverystep.cpp @@ -0,0 +1,688 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/* + * $Id: deliverystep.cpp 8476 2012-04-25 22:28:15Z xlou $ + */ + +#include +#include +#include +#include +using namespace std; + +#include "calpontsystemcatalog.h" +using namespace execplan; + +#include "jobstep.h" +#include "tableband.h" +using namespace joblist; + +#include "bytestream.h" +using namespace messageqcpp; + +struct ObjNumColPos +{ + bool operator<(const ObjNumColPos& rhs) const + { + return colPosition < rhs.colPosition; + } + CalpontSystemCatalog::OID objnum; + int colPosition; +}; + +namespace +{ + +} +//std::fstream derr; +namespace joblist +{ + +DeliveryStep::~DeliveryStep() +{ + if (initialized) { + uint i; + +// cerr << "DeliveryStep::join()\n"; + + mutex.lock(); //pthread_mutex_lock(&mutex); + die = true; + nextBandReady.notify_all(); //pthread_cond_broadcast(&nextBandReady); + mutex.unlock(); //pthread_mutex_unlock(&mutex); + +// cerr << "joining " << columnCount << " threads" << endl; + for (i = 0; i < threads.size(); i++) { + threads[i]->join(); +// cerr << "joined " << i << endl; + delete threads[i]; + } + + //pthread_mutex_destroy(&mutex); + //pthread_cond_destroy(&nextBandReady); + //pthread_cond_destroy(&allDone); + } + +} + +/* Don't use this; it's only for the unit tester & benchmark */ +DeliveryStep::DeliveryStep(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint colWidth) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation) +{ + uint i; + FifoDataList *dlp; + StringFifoDataList *sdlp; + + initialized = true; + die = false; + bandCount = 0; + doneCounter = 0; + fRowsDelivered = 0; + + //pthread_mutex_init(&mutex, NULL); + //pthread_cond_init(&nextBandReady, NULL); + //pthread_cond_init(&allDone, NULL); + + columnCount = fInputJobStepAssociation.outSize(); + iterators.reset(new uint[columnCount]); + colWidths.reset(new uint[columnCount]); + fTableOID = 9000; + fTableBand.tableOID(fTableOID); + returnColumnCount = columnCount; + columnData.reset(new ByteStream[returnColumnCount]); + + for (i = 0; i < columnCount; i++) { + dlp = fInputJobStepAssociation.outAt(i)->fifoDL(); + if (dlp != NULL) + fTableBand.addNullColumn(dlp->OID()); + else { + sdlp = fInputJobStepAssociation.outAt(i)->stringDL(); + fTableBand.addNullColumn(sdlp->OID()); + } + } + fEmptyTableBand = fTableBand; + + for (i = 0; i < columnCount; i++) { + dlp = fInputJobStepAssociation.outAt(i)->fifoDL(); + if (dlp != NULL) { + iterators[i] = dlp->getIterator(); + colWidths[i] = colWidth; + threads.push_back(new boost::thread(Demuxer(this, i, 0, true))); + } + else { + sdlp = fInputJobStepAssociation.outAt(i)->stringDL(); + iterators[i] = sdlp->getIterator(); + colWidths[i] = 0; + threads.push_back(new boost::thread(Demuxer(this, i, 1, true))); + } + } + fExtendedInfo = "DS: Not yet..."; +} + +// This step delivers rows for a table a band at a time +DeliveryStep::DeliveryStep(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + CalpontSystemCatalog::TableName tableName, + CalpontSystemCatalog* cat, + uint32_t sessionId, + uint32_t txnId, + uint32_t statementId, + uint32_t flushInterval) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fSessionId(sessionId), + fTxnId(txnId), + fStepId(0), + fStatementId(statementId), + fFlushInterval(flushInterval), + fRowsDelivered(0) +{ + // We want to setup the table with all null columns in column position order + fTableName = tableName; + CalpontSystemCatalog::ROPair p = cat->tableRID(tableName); + fTableOID = p.objnum; + catalog = cat; + + CalpontSystemCatalog::RIDList ridList = cat->columnRIDs(tableName, true); + + // now put them into column position sorted order via a set + CalpontSystemCatalog::RIDList::iterator iter = ridList.begin(); + CalpontSystemCatalog::RIDList::iterator end = ridList.end(); + typedef set ObjNumColPosSet; + ObjNumColPosSet colPosMap; + while (iter != end) + { + ObjNumColPos cp; + cp.objnum = iter->objnum; + // get the col pos for this col + CalpontSystemCatalog::ColType ct = cat->colType(cp.objnum); + if ( ct.colDataType == CalpontSystemCatalog::VARCHAR ) + { + ct.colWidth++; + } + //If this is a dictionary column, fudge the numbers... + if (ct.colWidth > 8 || ct.colDataType == CalpontSystemCatalog::VARBINARY) + { + cp.objnum = ct.ddn.dictOID; + } + cp.colPosition = ct.colPosition; + colPosMap.insert(cp); + ++iter; + } + + fTableBand.tableOID(fTableOID); + ObjNumColPosSet::iterator iter2 = colPosMap.begin(); + ObjNumColPosSet::iterator end2 = colPosMap.end(); + returnColumnCount = 0; + while (iter2 != end2) + { + fTableBand.addNullColumn(iter2->objnum); + ++iter2; + ++returnColumnCount; + } + // keep a convenient "empty" band around + fEmptyTableBand = fTableBand; + columnData.reset(new ByteStream[returnColumnCount]); // != columnCount if there are duplicates + + fState = 0; + initialized = false; + fExtendedInfo = "DS: Not yet..."; +} + +void DeliveryStep::run() +{ + +} + +void DeliveryStep::join() +{ + +} + +void DeliveryStep::initialize(bool bs) +{ + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + std::string("DeliveryStep")); // step name + } + + uint i; + FifoDataList *dlp; + StringFifoDataList *sdlp; + initialized = true; + + if (fTableOID >= 3000 && traceOn()) + { + ostringstream logStr; + logStr << "first call of nextBand() for table OID " << fTableOID << endl; + logEnd(logStr.str().c_str()); + } + die = false; + bandCount = 0; + doneCounter = 0; + + //pthread_mutex_init(&mutex, NULL); + //pthread_cond_init(&nextBandReady, NULL); + //pthread_cond_init(&allDone, NULL); + + columnCount = fInputJobStepAssociation.outSize(); + iterators.reset(new uint[columnCount]); + colWidths.reset(new uint[columnCount]); + for (i = 0; i < columnCount; i++) { + dlp = fInputJobStepAssociation.outAt(i)->fifoDL(); + if (dlp != NULL) { + iterators[i] = dlp->getIterator(); + colWidths[i] = catalog->colType(dlp->OID()).colWidth; + if ( catalog->colType(dlp->OID()).colDataType == CalpontSystemCatalog::VARCHAR ) + ++colWidths[i]; + else if ( catalog->colType(dlp->OID()).colDataType == CalpontSystemCatalog::VARBINARY ) + colWidths[i] += 2; +// cout << "colWidths[" << i << "] = " << colWidths[i] << endl; + threads.push_back(new boost::thread(Demuxer(this, i, 0, bs))); + } + else { + sdlp = fInputJobStepAssociation.outAt(i)->stringDL(); + iterators[i] = sdlp->getIterator(); + colWidths[i] = 0; + threads.push_back(new boost::thread(Demuxer(this, i, 1, bs))); + } + } +} + +const string DeliveryStep::toString() const +{ + ostringstream oss; + size_t outSize = fInputJobStepAssociation.outSize(); + oss << "DeliverStep tb:" << fTableOID; + oss << " in:"; + for (unsigned i = 0; i < outSize; i++) + { + oss << fInputJobStepAssociation.outAt(i) << ", "; + } + return oss.str(); +} + +void DeliveryStep::fillByteStream(ByteStream &bs) +{ + ByteStream::octbyte ob; + uint i; + + ob = fTableOID; + bs << ob; + ob = returnColumnCount; + bs << ob; + ob = rowCount; + bs << ob; + bs << (uint64_t)0; //tableband fStatus + + bs << (uint8_t) false; // a new "got rids" var which DS doesn't use + + for (i = 0; i < returnColumnCount; ++i) { + if (columnData[i].length() > 0) { + bs += columnData[i]; + columnData[i].restart(); + } + else { + // Make the null columns serialize themselves. + fEmptyTableBand.getColumns()[i]->serialize(bs); + } + } +} + +uint DeliveryStep::nextBand(ByteStream &bs) +{ + if (!initialized) + initialize(true); + + if (traceOn() && (dlTimes.FirstReadTime().tv_sec == 0)) + dlTimes.setFirstReadTime(); + + mutex.lock(); //pthread_mutex_lock(&mutex); + bandCount++; + doneCounter = 0; + nextBandReady.notify_all(); //pthread_cond_broadcast(&nextBandReady); + while (doneCounter < columnCount) + allDone.wait(mutex); //pthread_cond_wait(&allDone, &mutex); + mutex.unlock(); //pthread_mutex_unlock(&mutex); + + fillByteStream(bs); + if (rowCount == 0) + columnData.reset(); + + if (fTableOID >= 3000) + { + if(fRowsDelivered == 0 && traceOn()) + { + ostringstream logStr; + logStr << "DeliveryStep::nextBand: delivering initial band for " << fTableName + << " (" << fTableOID << ") w/ " << rowCount << " rows" << endl; + logEnd(logStr.str().c_str()); + } + + fRowsDelivered += rowCount; + if(rowCount == 0) + { + //...Construct timestamp using ctime_r() instead of ctime() not + //...necessarily due to re-entrancy, but because we want to strip + //...the newline ('\n') off the end of the formatted string. + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + timeString[strlen(timeString)-1 ] = '\0'; + + FifoDataList* pFifo = 0; + uint totalBlockedReadCount = 0; + uint totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + totalBlockedReadCount += pFifo->blockedReadCount(); + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + + if (traceOn()) + { + //...Print job step completion information + ostringstream logStr; + logStr << "DeliveryStep::nextBand: delivered last band for " << fTableName << " (" + << fTableOID << ") - " << fRowsDelivered << " total rows delivered" << endl << + "DeliveryStep for " << fTableName << + " finished at " << timeString << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << endl; + logEnd(logStr.str().c_str()); + + dlTimes.setLastReadTime(); + + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstReadTime(), // first write n/a, use first read + dlTimes.LastReadTime()); // last write n/a, use last read + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist output to report + } + } + } + return rowCount; +} + +const TableBand DeliveryStep::nextBand() +{ + + if (!initialized) + initialize(false); + + fTableBand = fEmptyTableBand; + + if (traceOn() && (dlTimes.FirstReadTime().tv_sec == 0)) + dlTimes.setFirstReadTime(); + + mutex.lock(); //pthread_mutex_lock(&mutex); + bandCount++; + doneCounter = 0; + nextBandReady.notify_all(); //pthread_cond_broadcast(&nextBandReady); + while (doneCounter < columnCount) + allDone.wait(mutex); //pthread_cond_wait(&allDone, &mutex); + mutex.unlock(); //pthread_mutex_unlock(&mutex); + + if (fTableOID >= 3000) + { + if(fRowsDelivered == 0 && traceOn()) + { + ostringstream logStr; + logStr << "DeliveryStep::nextBand: delivering initial band for " << fTableName + << " (" << fTableOID << ") w/ " << fTableBand.getRowCount() << " rows" << endl; + logEnd(logStr.str().c_str()); + } + + fRowsDelivered += fTableBand.getRowCount(); + if(fTableBand.getRowCount() == 0) + { + //...Construct timestamp using ctime_r() instead of ctime() not + //...necessarily due to re-entrancy, but because we want to strip + //...the newline ('\n') off the end of the formatted string. + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + timeString[strlen(timeString)-1 ] = '\0'; + + FifoDataList* pFifo = 0; + uint totalBlockedReadCount = 0; + uint totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + totalBlockedReadCount += pFifo->blockedReadCount(); + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + + if (traceOn()) + { + //...Print job step completion information + ostringstream logStr; + logStr << "DeliveryStep::nextBand: delivered last band for " << fTableName << + " (" << fTableOID << ") - " << fRowsDelivered << + " total rows delivered" << endl << + "DeliveryStep for " << fTableName << + " finished at " << timeString << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << endl; + logEnd(logStr.str().c_str()); + + dlTimes.setLastReadTime(); + + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstReadTime(), // first write n/a, use first read + dlTimes.LastReadTime()); // last write n/a, use last read + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist output to report + } + } + } + + return fTableBand; +} + +void DeliveryStep::fillBSFromNumericalColumn(uint index) +{ + FifoDataList *fifo; +// uint it, i; + uint it; + int bsIndex; + uint64_t bandNumber; + UintRowGroup rg; + messageqcpp::ByteStream::octbyte bsRowCount; + messageqcpp::ByteStream::octbyte oid; + messageqcpp::ByteStream::byte nullFlag; + messageqcpp::ByteStream::byte columnType; + + bool firstColumn = (index == 0); + + fifo = fInputJobStepAssociation.outAt(index)->fifoDL(); + it = iterators[index]; + bsIndex = fEmptyTableBand.find(fifo->OID()); + if (bsIndex < 0) { + cout << "fill ByteStream throwing\n"; + throw logic_error("DeliveryStep: fEmptyTableBand is unaware of the given OID"); + } + bandNumber = 0; + + mutex.lock(); //pthread_mutex_lock(&mutex); + + while (1) { + while (bandNumber == bandCount && !die) + nextBandReady.wait(mutex); //pthread_cond_wait(&nextBandReady, &mutex); + bandNumber = bandCount; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + if (die) + return; + + // fill in column BS + oid = fifo->OID(); + columnData[bsIndex] << oid; + //Bug 836 + switch (colWidths[index]) { + case 5: + case 6: + case 7: {colWidths[index] = 8;} + case 8: columnType = TableColumn::UINT64; break; + case 3: { colWidths[index] = 4; } + case 4: columnType = TableColumn::UINT32; break; + case 2: columnType = TableColumn::UINT16; break; + case 1: columnType = TableColumn::UINT8; break; + default: + cout << "DS: throwing!\n" << endl; + throw logic_error("DeliveryStep: Bad column width!"); + } + columnData[bsIndex] << columnType; + + nullFlag = 0; + columnData[bsIndex] << nullFlag; + rg.count = 0; + fifo->next(it, &rg); + bsRowCount = rg.count; + columnData[bsIndex] << bsRowCount; +// cout << "DS: got an RG, oid = " << oid << " appending "<< +// rg.count * colWidths[index] << " count = " << rg.count << endl; + + /* When this is called, pColStep implicitly knows it's called and + puts packed data in the ElementType array. Here we just need to + copy it into the ByteStream for this column. + TableColumn::unserialize() will parse both formats */ + columnData[bsIndex].append((uint8_t *) &rg.et[0], rg.count * colWidths[index]); + mutex.lock(); //pthread_mutex_lock(&mutex); + if (firstColumn) + rowCount = rg.count; + if (++doneCounter == columnCount) + allDone.notify_one(); //pthread_cond_signal(&allDone); + } +} + +void DeliveryStep::fillBSFromStringColumn(uint index) +{ + StringFifoDataList *fifo; + uint it, i; + int bsIndex; + uint64_t bandNumber; + StringRowGroup rg; + messageqcpp::ByteStream::octbyte bsRowCount; + messageqcpp::ByteStream::octbyte oid; + messageqcpp::ByteStream::byte nullFlag; + messageqcpp::ByteStream::byte columnType; + + bool firstColumn = (index == 0); + + fifo = fInputJobStepAssociation.outAt(index)->stringDL(); + it = iterators[index]; + bsIndex = fEmptyTableBand.find(fifo->OID()); + if (bsIndex < 0) + throw logic_error("DeliveryStep: fEmptyTableBand is unaware of the given OID"); + bandNumber = 0; + + mutex.lock(); //pthread_mutex_lock(&mutex); + + while (1) { + while (bandNumber == bandCount && !die) + nextBandReady.wait(mutex); //pthread_cond_wait(&nextBandReady, &mutex); + bandNumber = bandCount; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + if (die) + return; + + // fill in column BS + oid = fifo->OID(); + columnData[bsIndex] << oid; + columnType = TableColumn::STRING; + columnData[bsIndex] << columnType; + nullFlag = 0; + columnData[bsIndex] << nullFlag; + + rg.count = 0; + fifo->next(it, &rg); + bsRowCount = rg.count; +// cout << "DS (S): got a group count = " << rg.count << endl; + columnData[bsIndex] << bsRowCount; + for (i = 0; i < rg.count; ++i) { + columnData[bsIndex] << rg.et[i].second; +// cout << "adding " << rg.et[i].second << " at " << i << endl; + } + + mutex.lock(); //pthread_mutex_lock(&mutex); + if (firstColumn) + rowCount = rg.count; + if (++doneCounter == columnCount) + allDone.notify_one(); //pthread_cond_signal(&allDone); + } +} + + +void DeliveryStep::readNumericalColumn(uint index) +{ + FifoDataList *fifo; + uint it; + uint64_t bandNumber; + + bool firstColumn = (index == 0); + + fifo = fInputJobStepAssociation.outAt(index)->fifoDL(); + it = iterators[index]; + bandNumber = 0; + + mutex.lock(); //pthread_mutex_lock(&mutex); + while (1) { + while (bandNumber == bandCount && !die) + nextBandReady.wait(mutex); //pthread_cond_wait(&nextBandReady, &mutex); + bandNumber = bandCount; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + if (die) + return; + + fTableBand.addColumn(fifo, it, fFlushInterval, firstColumn, false); + + mutex.lock(); //pthread_mutex_lock(&mutex); + if (++doneCounter == columnCount) + allDone.notify_one(); //pthread_cond_signal(&allDone); + } + +} + +void DeliveryStep::readStringColumn(uint index) +{ + StringElementType e; + StringFifoDataList *fifo; + uint it; + uint64_t bandNumber; + + + fifo = fInputJobStepAssociation.outAt(index)->stringDL(); + it = iterators[index]; + bandNumber = 0; + + bool firstColumn = (index == 0); + + mutex.lock(); //pthread_mutex_lock(&mutex); + while (1) { + while (bandNumber == bandCount && !die) + nextBandReady.wait(mutex); //pthread_cond_wait(&nextBandReady, &mutex); + bandNumber = bandCount; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + if (die) + return; + + fTableBand.addColumn(fifo, it, fFlushInterval, firstColumn, false); + + mutex.lock(); //pthread_mutex_lock(&mutex); + if (++doneCounter == columnCount) + allDone.notify_one(); //pthread_cond_signal(&allDone); + } + +} + +} diff --git a/dbcon/joblist/deliverywsdl.cpp b/dbcon/joblist/deliverywsdl.cpp new file mode 100644 index 00000000..3703e7de --- /dev/null +++ b/dbcon/joblist/deliverywsdl.cpp @@ -0,0 +1,148 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// +// $Id: deliverywsdl.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +// C++ Implementation: deliverywsdl +// +// Description: +// +// +// Author: Patrick LeBlanc , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// + +#include "deliverywsdl.h" + +namespace joblist +{ + +DeliveryWSDL::DeliveryWSDL(uint numConsumers, uint FIFOMaxElements, uint WSDLMaxElements, + uint32_t elementSaveSize1st, uint32_t elementSaveSize2nd, + ResourceManager& rm, execplan::CalpontSystemCatalog::OID tOID, + execplan::CalpontSystemCatalog::OID *projectingTable) +{ + fifo.reset(new FIFO(numConsumers, FIFOMaxElements)); + wsdl.reset(new WSDL(numConsumers, WSDLMaxElements, elementSaveSize1st, + elementSaveSize2nd, rm)); + + projectingTableOID = projectingTable; + doneInsertingIntoWSDL = false; + deliveringWSDL = true; + tableOID = tOID; + fElementMode = RID_VALUE; +} + +DeliveryWSDL::~DeliveryWSDL() { } + +uint64_t DeliveryWSDL::getIterator() +{ + uint64_t wIt, fIt; + + wIt = wsdl->getIterator(); + fIt = fifo->getIterator(); + idbassert(wIt == fIt); // there might be a small race between consumers here + return wIt; +} + +void DeliveryWSDL::endOfInput() +{ + if (!doneInsertingIntoWSDL) + wsdl->endOfInput(); + fifo->endOfInput(); +} + +void DeliveryWSDL::setMultipleProducers(bool b) +{ + wsdl->setMultipleProducers(b); + fifo->setMultipleProducers(b); +} + +// Note: ElementMode is not technically implemented in this class; at least not +// at this time. However, we provide a hook for it to store the element mode, +// because if a HashJoin decides to perform a join using a LHJ, this Delivery- +// WSDL may get changed to a ZDL. In that case the elementMode can be honored. +// So we want to store and track the "potential" elementMode so that HashJoin +// will be able to access this information if needed. +void DeliveryWSDL::setElementMode(uint elementMode) +{ + fElementMode = elementMode; +} +uint DeliveryWSDL::getElementMode() const +{ + return fElementMode; +} + +bool DeliveryWSDL::useDisk() +{ + return true; +} + +void DeliveryWSDL::setDiskElemSize(uint32_t size1st, uint32_t size2nd) +{ + wsdl->setDiskElemSize(size1st, size2nd); +} + +uint32_t DeliveryWSDL::getDiskElemSize1st() const +{ + return wsdl->getDiskElemSize1st(); +} + +uint32_t DeliveryWSDL::getDiskElemSize2nd() const +{ + return wsdl->getDiskElemSize2nd(); +} + +uint64_t DeliveryWSDL::numberOfTempFiles() const +{ + return wsdl->numberOfTempFiles(); +} + +void DeliveryWSDL::traceOn(bool b) +{ + wsdl->traceOn(b); +} + +std::list& DeliveryWSDL::diskIoList() +{ + return wsdl->diskIoList(); +} + +bool DeliveryWSDL::totalDiskIoTime(uint64_t &w, uint64_t &r) +{ + return wsdl->totalDiskIoTime(w, r); +} + +uint32_t DeliveryWSDL::getNumConsumers() +{ + return wsdl->getNumConsumers(); +} + +void DeliveryWSDL::totalFileCounts(uint64_t& numFiles, uint64_t& numBytes) const +{ + numFiles = wsdl->numberOfTempFiles(); + numBytes = wsdl->saveSize; +} + +uint64_t DeliveryWSDL::totalSize() +{ + return (wsdl->totalSize() + fifo->totalSize()); +} + +}; diff --git a/dbcon/joblist/deliverywsdl.h b/dbcon/joblist/deliverywsdl.h new file mode 100644 index 00000000..8e18d824 --- /dev/null +++ b/dbcon/joblist/deliverywsdl.h @@ -0,0 +1,146 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// +// $Id: deliverywsdl.h 8436 2012-04-04 18:18:21Z rdempsey $ +// C++ Interface: deliverywsdl +// +// Description: +// +// +// Author: Patrick LeBlanc , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// + +#include "elementtype.h" +#include "calpontsystemcatalog.h" +#include +#include + +#ifndef _DELIVERYWSDL_H_ +#define _DELIVERYWSDL_H_ + +namespace joblist +{ + +/* What should the element type be? Might be a benefit to using rowgroups */ + +class DeliveryWSDL : public DataList +{ + public: + enum ElementMode { + RID_ONLY, + RID_VALUE + }; + + DeliveryWSDL(uint numConsumers, uint FIFOMaxElements, uint WSDLMaxElements, + uint32_t elementSaveSize1st, uint32_t elementSaveSize2nd, + ResourceManager& rm, execplan::CalpontSystemCatalog::OID tOID, + execplan::CalpontSystemCatalog::OID *projectingTable); + virtual ~DeliveryWSDL(); + + inline void insert(const ElementType &); + inline void insert(const std::vector &v); + uint64_t getIterator(); + inline bool next(uint64_t it, ElementType *e); + void endOfInput(); + void setMultipleProducers(bool); + uint32_t getNumConsumers(); + + /* Element mode is not currently implemented by DeliveryWSDL. The */ + /* internal WSDL is always created using ElementType (rid/value). */ + /* But the mode should still be set in a DeliveryWSDL datalist, in */ + /* case the datalist is later converted to a ZDL. In that case the */ + /* element mode may be copied over and used by the ZDL. */ + void setElementMode(uint mode); + uint getElementMode() const; + + /* disk I/O accessors */ + bool useDisk(); + void setDiskElemSize(uint32_t size1st,uint32_t size2nd); + uint32_t getDiskElemSize1st() const; + uint32_t getDiskElemSize2nd() const; + uint64_t numberOfTempFiles() const; + void traceOn(bool b); + std::list& diskIoList(); + bool totalDiskIoTime(uint64_t& w, uint64_t& r); + void totalFileCounts(uint64_t& numFiles, uint64_t& numBytes) const; + uint64_t totalSize(); + + + private: + DeliveryWSDL(); + DeliveryWSDL(const DeliveryWSDL &); + DeliveryWSDL & operator=(const DeliveryWSDL &); + + boost::shared_ptr > wsdl; + boost::shared_ptr > fifo; + + bool doneInsertingIntoWSDL; + bool deliveringWSDL; + execplan::CalpontSystemCatalog::OID *projectingTableOID; + execplan::CalpontSystemCatalog::OID tableOID; + + uint fElementMode; +}; + +inline void DeliveryWSDL::insert(const ElementType &e) +{ + if (*projectingTableOID == tableOID) { + if (!doneInsertingIntoWSDL) { + wsdl->endOfInput(); + doneInsertingIntoWSDL = true; + } + fifo->insert(e); + } + else + wsdl->insert(e); +} + +inline void DeliveryWSDL::insert(const std::vector &v) +{ + if (*projectingTableOID == tableOID) { + if (!doneInsertingIntoWSDL) { + wsdl->endOfInput(); + doneInsertingIntoWSDL = true; + } + fifo->insert(v); + } + else + wsdl->insert(v); +} + +inline bool DeliveryWSDL::next(uint64_t it, ElementType *e) +{ + bool ret; + + if (deliveringWSDL) { + ret = wsdl->next(it, e); + if (!ret) + deliveringWSDL = false; + else + return true; + } + return fifo->next(it, e); +} + + +}; + +#endif diff --git a/dbcon/joblist/dictstep-jl.cpp b/dbcon/joblist/dictstep-jl.cpp index 60751373..18ebffa8 100644 --- a/dbcon/joblist/dictstep-jl.cpp +++ b/dbcon/joblist/dictstep-jl.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: dictstep-jl.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: dictstep-jl.cpp 8410 2012-03-22 12:57:23Z pleblanc $ // C++ Implementation: dictstep-js // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -61,7 +61,7 @@ DictStepJL::~DictStepJL() { } -void DictStepJL::setLBID(uint64_t token, uint32_t dbroot) +void DictStepJL::setLBID(uint64_t token, uint dbroot) { // lbid = token >> 10; // the lbid is calculated on the PM } @@ -77,7 +77,7 @@ void DictStepJL::createCommand(ByteStream &bs) const if (hasEqFilter) { idbassert(filterCount == eqFilter.size()); bs << eqOp; - for (uint32_t i = 0; i < filterCount; i++) + for (uint i = 0; i < filterCount; i++) bs << eqFilter[i]; } else diff --git a/dbcon/joblist/dictstep-jl.h b/dbcon/joblist/dictstep-jl.h index 2994d7c2..0bebdaa5 100644 --- a/dbcon/joblist/dictstep-jl.h +++ b/dbcon/joblist/dictstep-jl.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: dictstep-jl.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: dictstep-jl.h 8436 2012-04-04 18:18:21Z rdempsey $ // C++ Interface: dictstep-js // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -44,7 +44,7 @@ class DictStepJL : public CommandJL DictStepJL(const pDictionaryStep &); virtual ~DictStepJL(); - void setLBID(uint64_t data, uint32_t dbroot); // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. + void setLBID(uint64_t data, uint dbroot); // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. uint8_t getTableColumnType(); std::string toString(); diff --git a/dbcon/joblist/diskjoinstep.cpp b/dbcon/joblist/diskjoinstep.cpp deleted file mode 100644 index dab56b82..00000000 --- a/dbcon/joblist/diskjoinstep.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - - -#include "diskjoinstep.h" -#include "exceptclasses.h" -#include "resourcemanager.h" - -using namespace std; -using namespace rowgroup; -using namespace joiner; -using namespace logging; - -// a couple space-savers... - -#define LOG(x) {\ - logging::Logger logger(16); \ - LoggingID id(16, fSessionId); \ - logger.logMessage(LOG_TYPE_ERROR, x, id); \ -} - -#define CATCH_AND_LOG \ - catch(IDBExcept &e) { \ - if (!status()) { \ - errorMessage(e.what()); \ - status(e.errorCode()); \ - LOG(string(e.what())); \ - } \ - abort(); \ - } \ - catch(exception &e) { \ - if (!status()) { \ - ostringstream os; \ - os << "Disk join caught an error: " << e.what(); \ - errorMessage(os.str().c_str()); \ - LOG(os.str()); \ - status(ERR_DBJ_UNKNOWN_ERROR); \ - } \ - abort(); \ - } - -namespace joblist { - -DiskJoinStep::DiskJoinStep() { } - -DiskJoinStep::DiskJoinStep(TupleHashJoinStep *t, int djsIndex, int joinIndex, bool lastOne) : JobStep(*t), thjs(t), - joinerIndex(joinIndex), closedOutput(false) -{ - /* - grab all relevant vars from THJS - make largeRG and outputRG - make the RG mappings - init a JoinPartition - load the existing RGData into JoinPartition - */ - - largeRG = thjs->largeRG + thjs->outputRG; - if (lastOne) - outputRG = thjs->outputRG; - else - outputRG = largeRG; - smallRG = thjs->smallRGs[joinerIndex]; - largeKeyCols = thjs->largeSideKeys[joinerIndex]; - smallKeyCols = thjs->smallSideKeys[joinerIndex]; - - /* Should not be necessary if we can use THJS's logic to do the join */ - fe = thjs->getJoinFilter(joinerIndex); - if (fe) { - joinFERG = thjs->joinFilterRG; - SjoinFEMapping = makeMapping(smallRG, joinFERG); - LjoinFEMapping = makeMapping(largeRG, joinFERG); - } - joiner = thjs->djsJoiners[djsIndex]; - joinType = joiner->getJoinType(); - typeless = joiner->isTypelessJoin(); - joiner->clearData(); - joiner->setInUM(); - - LOMapping = makeMapping(largeRG, outputRG); - SOMapping = makeMapping(smallRG, outputRG); - - /* Link up */ - largeDL = thjs->fifos[djsIndex]; - outputDL = thjs->fifos[djsIndex+1]; - smallDL = thjs->smallDLs[joinerIndex]; - largeIt = largeDL->getIterator(); - - smallUsage = thjs->djsSmallUsage; - smallLimit = thjs->djsSmallLimit; - largeLimit = thjs->djsLargeLimit; - partitionSize = thjs->djsPartitionSize; - - if (smallLimit == 0) - smallLimit = numeric_limits::max(); - if (largeLimit == 0) - largeLimit = numeric_limits::max(); - - uint64_t totalUMMemory = thjs->resourceManager.getConfiguredUMMemLimit(); - jp.reset(new JoinPartition(largeRG, smallRG, smallKeyCols, largeKeyCols, typeless, - (joinType & ANTI) && (joinType & MATCHNULLS), (bool) fe, totalUMMemory, partitionSize)); - - if (cancelled()) { - // drain inputs, close output - smallReader(); // only small input is supplying input at this point - // largeReader(); - outputDL->endOfInput(); - closedOutput = true; - } - - largeIterationCount = 0; - lastLargeIteration = false; - fMiniInfo.clear(); - fExtendedInfo.clear(); -} - -DiskJoinStep::~DiskJoinStep() -{ - abort(); - if (mainThread) { - mainThread->join(); - mainThread.reset(); - } - if (jp) - atomicops::atomicSub(smallUsage.get(), jp->getSmallSideDiskUsage()); -} - -void DiskJoinStep::loadExistingData(vector &data) -{ - int64_t memUsage; - uint32_t i; - - for (i = 0; i < data.size() && !cancelled(); i++) { - memUsage = jp->insertSmallSideRGData(data[i]); - atomicops::atomicAdd(smallUsage.get(), memUsage); - } -} - -void DiskJoinStep::run() -{ - mainThread.reset(new boost::thread(Runner(this))); -} - -void DiskJoinStep::join() -{ - if (mainThread) - mainThread->join(); - if (jp) { - atomicops::atomicSub(smallUsage.get(), jp->getSmallSideDiskUsage()); - //int64_t memUsage; - //memUsage = atomicops::atomicSub(smallUsage.get(), jp->getSmallSideDiskUsage()); - //cout << "join(): small side usage was: " << jp->getSmallSideDiskUsage() << " final shared mem usage = " << memUsage << endl; - jp.reset(); - } -} - -void DiskJoinStep::smallReader() -{ - RGData rgData; - bool more = true; - int64_t memUsage = 0, combinedMemUsage = 0; - int rowCount = 0; - RowGroup l_smallRG = smallRG; - - try { - while (more && !cancelled()) { - more = smallDL->next(0, &rgData); - if (more) { - l_smallRG.setData(&rgData); - rowCount += l_smallRG.getRowCount(); - memUsage = jp->insertSmallSideRGData(rgData); - combinedMemUsage = atomicops::atomicAdd(smallUsage.get(), memUsage); - //cout << "memusage = " << memUsage << " total = " << combinedMemUsage << endl; - if (combinedMemUsage > smallLimit) { - errorMessage(IDBErrorInfo::instance()->errorMsg(ERR_DBJ_DISK_USAGE_LIMIT)); - status(ERR_DBJ_DISK_USAGE_LIMIT); - cout << "DJS small reader: exceeded disk space limit" << endl; - abort(); - } - } - } - - //cout << "(" << joinerIndex << ") read the small side data, combined mem usage= " << combinedMemUsage << " rowcount = " << rowCount << endl; - if (!cancelled()) { - memUsage = jp->doneInsertingSmallData(); - combinedMemUsage = atomicops::atomicAdd(smallUsage.get(), memUsage); - //cout << "2memusage = " << memUsage << " total = " << combinedMemUsage << endl; - if (combinedMemUsage > smallLimit) { - errorMessage(IDBErrorInfo::instance()->errorMsg(ERR_DBJ_DISK_USAGE_LIMIT)); - status(ERR_DBJ_DISK_USAGE_LIMIT); - cout << "DJS small reader: exceeded disk space limit" << endl; - abort(); - } - } - } - CATCH_AND_LOG; - - while (more) - more = smallDL->next(0, &rgData); -} - -void DiskJoinStep::largeReader() -{ - RGData rgData; - bool more = true; - int64_t largeSize = 0; - int rowCount = 0; - RowGroup l_largeRG = largeRG; - - largeIterationCount++; - //cout << "iteration " << largeIterationCount << " largeLimit=" << largeLimit << endl; - - try { - while (more && !cancelled() && largeSize < largeLimit) { - more = largeDL->next(largeIt, &rgData); - if (more) { - l_largeRG.setData(&rgData); - rowCount += l_largeRG.getRowCount(); - //cout << "large side raw data: " << largeRG.toString() << endl; - - largeSize += jp->insertLargeSideRGData(rgData); - } - } - - jp->doneInsertingLargeData(); - - //cout << "(" << joinerIndex << ") read the large side data rowcount = " << rowCount << endl; - if (!more) - lastLargeIteration = true; - } - CATCH_AND_LOG; - - if (cancelled()) - while (more) - more = largeDL->next(largeIt, &rgData); -} - - -void DiskJoinStep::loadFcn() -{ - boost::shared_ptr out; - bool ret; - - try { - do { - out.reset(new LoaderOutput()); - ret = jp->getNextPartition(&out->smallData, &out->partitionID, &out->jp); - if (ret) { - //cout << "loaded partition " << out->partitionID << " smallData = " << out->smallData.size() << endl; - loadFIFO->insert(out); - } - } while (ret && !cancelled()); - } - CATCH_AND_LOG; - - loadFIFO->endOfInput(); -} - -void DiskJoinStep::buildFcn() -{ - boost::shared_ptr in; - boost::shared_ptr out; - bool more = true; - int it = loadFIFO->getIterator(); - int i, j; - Row smallRow; - RowGroup l_smallRG = smallRG; - - l_smallRG.initRow(&smallRow); - - while (1) { - //cout << "getting a partition from the loader" << endl; - more = loadFIFO->next(it, &in); - if (!more || cancelled()) - goto out; - - out.reset(new BuilderOutput()); - out->smallData = in->smallData; - out->partitionID = in->partitionID; - out->jp = in->jp; - out->tupleJoiner = joiner->copyForDiskJoin(); - - //cout << "building a tuplejoiner" << endl; - for (i = 0; i < (int) in->smallData.size(); i++) { - l_smallRG.setData(&in->smallData[i]); - l_smallRG.getRow(0, &smallRow); - for (j = 0; j < (int) l_smallRG.getRowCount(); j++, smallRow.nextRow()) - out->tupleJoiner->insert(smallRow, (largeIterationCount == 1)); - } - out->tupleJoiner->doneInserting(); - buildFIFO->insert(out); - } - -out: - while (more) - more = loadFIFO->next(it, &in); - buildFIFO->endOfInput(); -} - -void DiskJoinStep::joinFcn() -{ - - /* This function mostly serves as an adapter between the - input data and the joinOneRG() fcn in THJS. */ - - boost::shared_ptr in; - bool more = true; - int it = buildFIFO->getIterator(); - int i, j; - vector joinResults; - RowGroup l_largeRG = largeRG, l_smallRG = smallRG; - RowGroup l_outputRG = outputRG; - Row l_largeRow; - Row l_joinFERow, l_outputRow, baseRow; - vector > joinMatches; - boost::shared_array smallRowTemplates(new Row[1]); - vector > joiners; - boost::shared_array > colMappings, fergMappings; - boost::scoped_array > smallNullMem; - boost::scoped_array joinFEMem; - Row smallNullRow; - - boost::scoped_array baseRowMem; - - if (joiner->hasFEFilter()) { - joinFERG.initRow(&l_joinFERow, true); - joinFEMem.reset(new uint8_t[l_joinFERow.getSize()]); - l_joinFERow.setData(joinFEMem.get()); - } - outputRG.initRow(&l_outputRow); - outputRG.initRow(&baseRow, true); - - largeRG.initRow(&l_largeRow); - - baseRowMem.reset(new uint8_t[baseRow.getSize()]); - baseRow.setData(baseRowMem.get()); - joinMatches.push_back(vector()); - smallRG.initRow(&smallRowTemplates[0]); - joiners.resize(1); - - colMappings.reset(new boost::shared_array[2]); - colMappings[0] = SOMapping; - colMappings[1] = LOMapping; - if (fe) { - fergMappings.reset(new boost::shared_array[2]); - fergMappings[0] = SjoinFEMapping; - fergMappings[1] = LjoinFEMapping; - } - - l_smallRG.initRow(&smallNullRow, true); - smallNullMem.reset(new boost::scoped_array[1]); - smallNullMem[0].reset(new uint8_t[smallNullRow.getSize()]); - smallNullRow.setData(smallNullMem[0].get()); - smallNullRow.initToNull(); - - try { - while (1) { - more = buildFIFO->next(it, &in); - if (!more || cancelled()) - goto out; - - joiners[0] = in->tupleJoiner; - boost::shared_ptr largeData; - largeData = in->jp->getNextLargeRGData(); - while (largeData) { - l_largeRG.setData(largeData.get()); - thjs->joinOneRG(0, &joinResults, l_largeRG, l_outputRG, l_largeRow, l_joinFERow, - l_outputRow, baseRow, joinMatches, smallRowTemplates, - &joiners, &colMappings, &fergMappings, &smallNullMem); - - for (j = 0; j < (int) joinResults.size(); j++) { - //l_outputRG.setData(&joinResults[j]); - //cout << "got joined output " << l_outputRG.toString() << endl; - outputDL->insert(joinResults[j]); - } - joinResults.clear(); - largeData = in->jp->getNextLargeRGData(); - } - - if (joinType & SMALLOUTER) { - if (!lastLargeIteration) { - - /* TODO: an optimization would be to detect whether any new rows were marked and if not - suppress the save operation */ - vector unmatched; - in->tupleJoiner->getUnmarkedRows(&unmatched); - //cout << "***** saving partition " << in->partitionID << " unmarked count=" << unmatched.size() << " total count=" - // << in->tupleJoiner->size() << " vector size=" << in->smallData.size() << endl; - in->jp->saveSmallSidePartition(in->smallData); - } - else { - - //cout << "finishing small-outer output" << endl; - vector unmatched; - RGData rgData(l_outputRG); - Row outputRow; - - l_outputRG.setData(&rgData); - l_outputRG.resetRowGroup(0); - l_outputRG.initRow(&outputRow); - l_outputRG.getRow(0, &outputRow); - - l_largeRG.initRow(&l_largeRow, true); - boost::scoped_array largeNullMem(new uint8_t[l_largeRow.getSize()]); - l_largeRow.setData(largeNullMem.get()); - l_largeRow.initToNull(); - - in->tupleJoiner->getUnmarkedRows(&unmatched); - //cout << " small-outer count=" << unmatched.size() << endl; - for (i = 0; i < (int) unmatched.size(); i++) { - smallRowTemplates[0].setData(unmatched[i]); - applyMapping(LOMapping, l_largeRow, &outputRow); - applyMapping(SOMapping, smallRowTemplates[0], &outputRow); - l_outputRG.incRowCount(); - if (l_outputRG.getRowCount() == 8192) { - outputDL->insert(rgData); - //cout << "inserting a full RG" << endl; - rgData.reinit(l_outputRG); - l_outputRG.setData(&rgData); - l_outputRG.resetRowGroup(0); - l_outputRG.getRow(0, &outputRow); - } - else - outputRow.nextRow(); - } - if (l_outputRG.getRowCount() > 0) { - //cout << "inserting an rg with " << l_outputRG.getRowCount() << endl; - outputDL->insert(rgData); - } - } - } - } - } // the try stmt above; need to reformat. - CATCH_AND_LOG; - -out: - while (more) - more = buildFIFO->next(it, &in); - if (lastLargeIteration || cancelled()) { - reportStats(); - outputDL->endOfInput(); - closedOutput = true; - } -} - -void DiskJoinStep::mainRunner() -{ - /* - Read from smallDL, insert into small side - Read from largeDL, insert into large side - Start the processing threads - */ - try { - smallReader(); - - while (!lastLargeIteration && !cancelled()) { - //cout << "large iteration " << largeIterationCount << endl; - jp->initForLargeSideFeed(); - largeReader(); - //cout << "done reading iteration " << largeIterationCount-1 << endl; - - jp->initForProcessing(); - if (cancelled()) - break; - - loadFIFO.reset(new FIFO >(1, 1)); // double buffering should be good enough - buildFIFO.reset(new FIFO >(1, 1)); - - loadThread.reset(new boost::thread(Loader(this))); - buildThread.reset(new boost::thread(Builder(this))); - joinThread.reset(new boost::thread(Joiner(this))); - loadThread->join(); - buildThread->join(); - joinThread->join(); - } - } - CATCH_AND_LOG; - - // make sure all inputs were drained & output closed - if (cancelled()) { - try { - jp->initForLargeSideFeed(); - } catch (...) { } // doesn't matter if this fails to open the large-file - - largeReader(); // large reader will only drain the fifo when cancelled() - if (!closedOutput) { - outputDL->endOfInput(); - closedOutput = true; - } - } -} - -const string DiskJoinStep::toString() const -{ - return "DiskJoinStep\n"; -} - -void DiskJoinStep::reportStats() -{ - ostringstream os1, os2; - - os1 << "DiskJoinStep: joined (large) " << alias() << " to (small) " << joiner->getTableName() <<". Processing stages: " << largeIterationCount << - ", disk usage small/large: " << jp->getMaxSmallSize() << "/" << jp->getMaxLargeSize() << - ", total bytes read/written: " << jp->getBytesRead() << "/" << jp->getBytesWritten() << endl; - fExtendedInfo = os1.str(); - - /* TODO: Can this report anything more useful in miniInfo? */ - int64_t bytesToReport = jp->getBytesRead() + jp->getBytesWritten(); - char units; - if (bytesToReport > (1 << 30)) { - bytesToReport >>= 30; - units = 'G'; - } - else if (bytesToReport > (1 << 20)) { - bytesToReport >>= 20; - units = 'M'; - } - else if (bytesToReport > (1 << 10)) { - bytesToReport >>= 10; - units = 'K'; - } - else units = ' '; - - os2 << "DJS UM " << alias() << "-" << joiner->getTableName() << " - - " << bytesToReport << - units << " - - -------- -\n"; - - fMiniInfo = os2.str(); - - if (traceOn()) - logEnd(os1.str().c_str()); -} - - -} diff --git a/dbcon/joblist/diskjoinstep.h b/dbcon/joblist/diskjoinstep.h deleted file mode 100644 index fc4f2bcf..00000000 --- a/dbcon/joblist/diskjoinstep.h +++ /dev/null @@ -1,132 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -#include "jobstep.h" -#include "tuplehashjoin.h" -#include "joinpartition.h" -#include "prioritythreadpool.h" - -#ifndef DISKJOINSTEP_H -#define DISKJOINSTEP_H - -namespace joblist { - -class DiskJoinStep : public JobStep -{ - public: - DiskJoinStep(); - DiskJoinStep(TupleHashJoinStep *, int djsIndex, int joinerIndex, bool lastOne); - virtual ~DiskJoinStep(); - - void run(); - void join(); - const std::string toString() const; - - void loadExistingData(std::vector &data); - uint32_t getIterationCount() { return largeIterationCount; } - - protected: - private: - boost::shared_ptr jp; - rowgroup::RowGroup largeRG, smallRG, outputRG, joinFERG; - std::vector largeKeyCols, smallKeyCols; - boost::shared_ptr largeDL, outputDL; - RowGroupDL *smallDL; - - boost::shared_array LOMapping, SOMapping, SjoinFEMapping, LjoinFEMapping; - TupleHashJoinStep *thjs; - boost::shared_ptr runner; - boost::shared_ptr fe; - bool typeless; - JoinType joinType; - boost::shared_ptr joiner; // the same instance THJS uses - - /* main thread, started by JobStep::run() */ - void mainRunner(); - struct Runner { - Runner(DiskJoinStep *d) : djs(d) { } - void operator()() { djs->mainRunner(); } - DiskJoinStep *djs; - }; - - void smallReader(); - void largeReader(); - int largeIt; - bool lastLargeIteration; - uint32_t largeIterationCount; - - boost::shared_ptr mainThread; - - /* Loader structs */ - struct LoaderOutput { - std::vector smallData; - uint64_t partitionID; - joiner::JoinPartition *jp; - }; - boost::shared_ptr > > loadFIFO; - - struct Loader { - Loader(DiskJoinStep *d) : djs(d) { } - void operator()() { djs->loadFcn(); } - DiskJoinStep *djs; - }; - void loadFcn(); - - boost::shared_ptr loadThread; - - /* Builder structs */ - struct BuilderOutput { - boost::shared_ptr tupleJoiner; - std::vector smallData; - uint64_t partitionID; - joiner::JoinPartition *jp; - }; - - boost::shared_ptr > > buildFIFO; - - struct Builder { - Builder(DiskJoinStep *d) : djs(d) { } - void operator()() { djs->buildFcn(); } - DiskJoinStep *djs; - }; - void buildFcn(); - boost::shared_ptr buildThread; - - /* Joining structs */ - struct Joiner { - Joiner(DiskJoinStep *d) : djs(d) { } - void operator()() { djs->joinFcn(); } - DiskJoinStep *djs; - }; - void joinFcn(); - boost::shared_ptr joinThread; - - // limits & usage - boost::shared_ptr smallUsage; - int64_t smallLimit; - int64_t largeLimit; - uint64_t partitionSize; - - void reportStats(); - - uint32_t joinerIndex; - bool closedOutput; -}; - -} - -#endif // DISKJOINSTEP_H diff --git a/dbcon/joblist/distributedenginecomm.cpp b/dbcon/joblist/distributedenginecomm.cpp index 8126a050..13016789 100644 --- a/dbcon/joblist/distributedenginecomm.cpp +++ b/dbcon/joblist/distributedenginecomm.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ // -// $Id: distributedenginecomm.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: distributedenginecomm.cpp 9469 2013-05-01 18:38:43Z pleblanc $ // // C++ Implementation: distributedenginecomm // @@ -35,13 +35,18 @@ #include #include #include +#ifdef _MSC_VER +#include +#endif using namespace std; #include #include using namespace boost; +#define DISTRIBUTEDENGINECOMM_DLLEXPORT #include "distributedenginecomm.h" +#undef DISTRIBUTEDENGINECOMM_DLLEXPORT #include "messagequeue.h" #include "bytestream.h" @@ -62,10 +67,21 @@ using namespace logging; using namespace snmpmanager; using namespace oam; +#ifdef SHARED_NOTHING_DEMO +#include "mastersegmenttable.h" +#include "extentmap.h" +#include "dbrm.h" +#endif + #include "jobstep.h" using namespace joblist; -#include "atomicops.h" +#if defined(_MSC_VER) && !defined(_WIN64) +# ifndef InterlockedAdd +# define InterlockedAdd64 InterlockedAdd +# define InterlockedAdd(x, y) ((x) + (y)) +# endif +#endif namespace { @@ -90,7 +106,7 @@ namespace case LOG_TYPE_CRITICAL: ml.logCriticalMessage(m); break; } } - + // @bug 1463. this function is added for PM failover. for dual/more nic PM, // this function is used to get the module name string getModuleNameByIPAddr(oam::ModuleTypeConfig moduletypeconfig, @@ -114,11 +130,11 @@ namespace struct EngineCommRunner { EngineCommRunner(joblist::DistributedEngineComm *jl, - boost::shared_ptr cl, uint32_t connectionIndex) : jbl(jl), client(cl), + boost::shared_ptr cl, uint connectionIndex) : jbl(jl), client(cl), connIndex(connectionIndex) {} joblist::DistributedEngineComm *jbl; boost::shared_ptr client; - uint32_t connIndex; + uint connIndex; void operator()() { //cout << "Listening on client at 0x" << hex << (ptrdiff_t)client << dec << endl; @@ -146,6 +162,94 @@ namespace } }; + uint64_t getInterleaveData(ISMPacketHeader *data) + { + ISMPacketHeader *MsgIn = data; + int Command = MsgIn->Command; + + switch (Command) { + case BATCH_PRIMITIVE_RUN: + case DICT_TOKEN_BY_SCAN_COMPARE: + return MsgIn->Interleave; + case COL_BY_SCAN: { + ColByScanRequestHeader * CRH; + CRH = (ColByScanRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case COL_BY_SCAN_RANGE: { + ColByScanRangeRequestHeader * CRH = (ColByScanRangeRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case COL_BY_RID: { + ColByRIDRequestHeader * CRH; + CRH = (ColByRIDRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case COL_AGG_BY_SCAN: { + ColAggByScanRequestHeader * CRH; + CRH = (ColAggByScanRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case COL_AGG_BY_RID: { + ColAggByRIDRequestHeader * CRH; + CRH = (ColAggByRIDRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case INDEX_BY_SCAN: { + IndexByScanRequestHeader * CRH; + CRH = (IndexByScanRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case INDEX_BY_COMPARE: { + IndexByCompareRequestHeader * CRH; + CRH = (IndexByCompareRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case DICT_TOKEN_BY_INDEX_COMPARE: { + DictTokenByIndexRequestHeader * CRH; + CRH = (DictTokenByIndexRequestHeader *) (MsgIn+1); + return CRH->LBID; + } +#if 0 + case DICT_TOKEN_BY_SCAN_COMPARE: { + DictTokenByScanRequestHeader * CRH; + CRH = (DictTokenByScanRequestHeader *) (MsgIn+1); + return CRH->LBID; + } +#endif + case DICT_SIGNATURE: { + DictSignatureRequestHeader * CRH; + CRH = (DictSignatureRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case DICT_SIGNATURE_RANGE: { + DictSignatureRangeRequestHeader * CRH; + CRH = (DictSignatureRangeRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case DICT_AGGREGATE: { + DictAggregateRequestHeader * CRH; + CRH = (DictAggregateRequestHeader *) (MsgIn+1); + return CRH->LBID; + } + case INDEX_WALK: { + IndexWalkHeader *iwh = (IndexWalkHeader *)MsgIn; + return iwh->LBID; + } + case INDEX_LIST: { + IndexListHeader *ilh = (IndexListHeader *)MsgIn; + return ilh->LBID; + } + case COL_LOOPBACK: { + return (uint64_t)NULL; + } + default: + cout << "DEC::getInterleaveData(): unknown primitive command " << Command + << endl; + throw logic_error("DEC::getInterleaveData(): unknown primitive command"); + } +} + template struct QueueShutdown : public unary_function { @@ -168,12 +272,12 @@ struct QueueShutdown : public unary_function namespace joblist { DistributedEngineComm* DistributedEngineComm::fInstance = 0; - + /*static*/ - DistributedEngineComm* DistributedEngineComm::instance(ResourceManager& rm, bool isExeMgr) + DistributedEngineComm* DistributedEngineComm::instance(ResourceManager& rm) { if (fInstance == 0) - fInstance = new DistributedEngineComm(rm, isExeMgr); + fInstance = new DistributedEngineComm(rm); return fInstance; } @@ -185,13 +289,13 @@ namespace joblist fInstance = 0; } - DistributedEngineComm::DistributedEngineComm(ResourceManager& rm, bool isExeMgr) : + DistributedEngineComm::DistributedEngineComm(ResourceManager& rm) : fRm(rm), fLBIDShift(fRm.getPsLBID_Shift()), pmCount(0), - fIsExeMgr(isExeMgr) + fMulticast(rm.getPsMulticast()), + fMulticastSender() { - Setup(); } @@ -203,24 +307,11 @@ namespace joblist void DistributedEngineComm::Setup() { - // This is here to ensure that this function does not get invoked multiple times simultaneously. - mutex::scoped_lock setupLock(fSetupMutex); - - makeBusy(true); - - // This needs to be here to ensure that whenever Setup function is called, the lists are - // empty. It's possible junk was left behind if exception. - ClientList::iterator iter; - for (iter = newClients.begin(); iter != newClients.end(); ++iter) - { - (*iter)->shutdown(); - } - newClients.clear(); - newLocks.clear(); + makeBusy(true); throttleThreshold = fRm.getDECThrottleThreshold(); - uint32_t newPmCount = fRm.getPsCount(); - int cpp = (fIsExeMgr ? fRm.getPsConnectionsPerPrimProc() : 1); + uint newPmCount = fRm.getPsCount(); + int cpp = fRm.getPsConnectionsPerPrimProc(); tbpsThreadCount = fRm.getJlNumScanReceiveThreads(); unsigned numConnections = newPmCount * cpp; oam::Oam oam; @@ -232,7 +323,7 @@ void DistributedEngineComm::Setup() throw runtime_error("Setup failed"); } - if (newPmCount == 0) + if (newPmCount == 0) writeToLog(__FILE__, __LINE__, "Got a config file with 0 PMs", LOG_TYPE_CRITICAL); @@ -272,14 +363,18 @@ void DistributedEngineComm::Setup() // first pmCount. If there is no match, it's a new node, // call the event listeners' newPMOnline() callbacks. mutex::scoped_lock lock(eventListenerLock); - for (uint32_t i = 0; i < newPmCount; i++) { - uint32_t j; + for (uint i = 0; i < newPmCount; i++) { +#ifdef _MSC_VER + LONG j; +#else + uint j; +#endif for (j = 0; j < pmCount; j++) { if (newClients[i]->isSameAddr(*fPmConnections[j])) break; } if (j == pmCount) - for (uint32_t k = 0; k < eventListeners.size(); k++) + for (uint k = 0; k < eventListeners.size(); k++) eventListeners[k]->newPMOnline(i); } lock.unlock(); @@ -287,7 +382,11 @@ void DistributedEngineComm::Setup() fWlock.swap(newLocks); fPmConnections.swap(newClients); // memory barrier to prevent the pmCount assignment migrating upward - atomicops::atomicMb(); +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) + __sync_synchronize(); +#elif defined(_MSC_VER) + MemoryBarrier(); +#endif pmCount = newPmCount; newLocks.clear(); @@ -305,19 +404,17 @@ int DistributedEngineComm::Close() return 0; } -void DistributedEngineComm::Listen(boost::shared_ptr client, uint32_t connIndex) +void DistributedEngineComm::Listen ( boost::shared_ptr client, uint connIndex) { SBS sbs; try { - while (Busy()) + while ( Busy() ) { - Stats stats; //TODO: This call blocks so setting Busy() in another thread doesn't work here... - sbs = client->read(0, NULL, &stats); - if (sbs->length() != 0) { - addDataToOutput(sbs, connIndex, &stats); - } + sbs = client->read(); + if ( sbs->length() != 0 ) + addDataToOutput(sbs, connIndex); else // got zero bytes on read, nothing more will come goto Error; } @@ -344,7 +441,11 @@ void DistributedEngineComm::Listen(boost::shared_ptr client, for (map_tok = fSessionMessages.begin(); map_tok != fSessionMessages.end(); ++map_tok) { map_tok->second->queue.clear(); - (void)atomicops::atomicInc(&map_tok->second->unackedWork[0]); +#ifdef _MSC_VER + InterlockedIncrement(&map_tok->second->unackedWork[0]); +#else + __sync_add_and_fetch(&map_tok->second->unackedWork[0], 1); // prevent an error msg +#endif map_tok->second->queue.push(sbs); } lk.unlock(); @@ -356,7 +457,7 @@ void DistributedEngineComm::Listen(boost::shared_ptr client, mutex::scoped_lock onErrLock(fOnErrMutex); string moduleName = client->moduleName(); //cout << "moduleName=" << moduleName << endl; - for ( uint32_t i = 0; i < fPmConnections.size(); i++) + for ( uint i = 0; i < fPmConnections.size(); i++) { if (moduleName != fPmConnections[i]->moduleName()) tempConns.push_back(fPmConnections[i]); @@ -375,7 +476,7 @@ void DistributedEngineComm::Listen(boost::shared_ptr client, string alarmItem = client->addr2String(); alarmItem.append(" PrimProc"); alarmMgr.sendAlarmReport(alarmItem.c_str(), oam::CONN_FAILURE, SET); - + ostringstream os; os << "DEC: lost connection to " << client->addr2String(); writeToLog(__FILE__, __LINE__, os.str(), LOG_TYPE_CRITICAL); @@ -410,7 +511,6 @@ void DistributedEngineComm::addQueue(uint32_t key, bool sendACKs) MessageQueueMap::iterator map_tok = fSessionMessages.find(key); if (map_tok == fSessionMessages.end()) return; - map_tok->second->queue.shutdown(); map_tok->second->queue.clear(); fSessionMessages.erase(map_tok); @@ -517,8 +617,7 @@ void DistributedEngineComm::read(uint32_t key, SBS &bs) } } - void DistributedEngineComm::read_some(uint32_t key, uint32_t divisor, vector &v, - bool *flowControlOn) + void DistributedEngineComm::read_some(uint32_t key, uint divisor, vector &v) { boost::shared_ptr mqe; @@ -537,16 +636,11 @@ void DistributedEngineComm::read(uint32_t key, SBS &bs) TSQSize_t queueSize = mqe->queue.pop_some(divisor, v, 1); // need to play with the min # - if (flowControlOn) - *flowControlOn = false; - if (mqe->sendACKs) { mutex::scoped_lock lk(ackLock); if (mqe->throttled && !mqe->hasBigMsgs && queueSize.size <= disableThreshold) setFlowControl(false, key, mqe); sendAcks(key, v, mqe, queueSize.size); - if (flowControlOn) - *flowControlOn = mqe->throttled; } } @@ -561,35 +655,35 @@ void DistributedEngineComm::sendAcks(uint32_t uniqueID, const vector &msgs, */ if (!mqe->throttled || queueSize >= mqe->targetQueueSize) { /* no acks will be sent, but update unackedwork to keep the #s accurate */ - uint16_t numack=0; - uint32_t sockidx=0; + uint16_t dummy16; + uint32_t dummy32; while (l_msgCount > 0) { - nextPMToACK(mqe, l_msgCount, &sockidx, &numack); - idbassert(numack <= l_msgCount); - l_msgCount -= numack; + nextPMToACK(mqe, l_msgCount, &dummy32, &dummy16); + idbassert(dummy16 <= l_msgCount); + l_msgCount -= dummy16; } return; } size_t totalMsgSize = 0; - for (uint32_t i = 0; i < msgs.size(); i++) + for (uint i = 0; i < msgs.size(); i++) totalMsgSize += msgs[i]->lengthWithHdrOverhead(); if (queueSize + totalMsgSize > mqe->targetQueueSize) { /* update unackedwork for the overage that will never be acked */ int64_t overage = queueSize + totalMsgSize - mqe->targetQueueSize; - uint16_t numack=0; - uint32_t sockidx=0; - uint32_t msgsToIgnore; + uint16_t dummy16; + uint32_t dummy32; + uint msgsToIgnore; for (msgsToIgnore = 0; overage >= 0; msgsToIgnore++) overage -= msgs[msgsToIgnore]->lengthWithHdrOverhead(); if (overage < 0) msgsToIgnore--; l_msgCount = msgs.size() - msgsToIgnore; // this num gets acked while (msgsToIgnore > 0) { - nextPMToACK(mqe, msgsToIgnore, &sockidx, &numack); - idbassert(numack <= msgsToIgnore); - msgsToIgnore -= numack; + nextPMToACK(mqe, msgsToIgnore, &dummy32, &dummy16); + idbassert(dummy16 <= msgsToIgnore); + msgsToIgnore -= dummy16; } } @@ -611,7 +705,7 @@ void DistributedEngineComm::sendAcks(uint32_t uniqueID, const vector &msgs, while (l_msgCount > 0) { /* could have to send up to pmCount ACKs */ - uint32_t sockIndex=0; + uint32_t sockIndex; /* This will reset the ACK field in the Bytestream directly, and nothing * else needs to change if multiple msgs are sent. */ @@ -628,12 +722,20 @@ void DistributedEngineComm::sendAcks(uint32_t uniqueID, const vector &msgs, if (mqe->hasBigMsgs) { uint64_t totalUnackedWork = 0; - for (uint32_t i = 0; i < pmCount; i++) +#ifdef _MSC_VER + for (LONG i = 0; i < pmCount; i++) +#else + for (uint i = 0; i < pmCount; i++) +#endif totalUnackedWork += mqe->unackedWork[i]; if (totalUnackedWork == 0) { *toAck = 1; - for (uint32_t i = 0; i < pmCount; i++) { +#ifdef _MSC_VER + for (LONG i = 0; i < pmCount; i++) { +#else + for (uint i = 0; i < pmCount; i++) { +#endif if (!pmAcked[i]) writeToClient(i, msg); } @@ -642,20 +744,28 @@ void DistributedEngineComm::sendAcks(uint32_t uniqueID, const vector &msgs, } } -void DistributedEngineComm::nextPMToACK(boost::shared_ptr mqe, uint32_t maxAck, +void DistributedEngineComm::nextPMToACK(boost::shared_ptr mqe, uint16_t maxAck, uint32_t *sockIndex, uint16_t *numToAck) { - uint32_t i; +#ifdef _MSC_VER + LONG i; + uint &nextIndex = mqe->ackSocketIndex; +#else + uint i; uint32_t &nextIndex = mqe->ackSocketIndex; +#endif /* Other threads can be touching mqe->unackedWork at the same time, but because of * the locking env, mqe->unackedWork can only grow; whatever gets latched in this fcn * is a safe minimum at the point of use. */ if (mqe->unackedWork[nextIndex] >= maxAck) { - (void)atomicops::atomicSub(&mqe->unackedWork[nextIndex], maxAck); +#ifdef _MSC_VER + InterlockedAdd(&mqe->unackedWork[nextIndex], -maxAck); +#else + __sync_sub_and_fetch(&mqe->unackedWork[nextIndex], maxAck); +#endif *sockIndex = nextIndex; - //FIXME: we're going to truncate here from 32 to 16 bits. Hopefully this will always fit... *numToAck = maxAck; if (pmCount > 0) nextIndex = (nextIndex + 1) % pmCount; @@ -666,7 +776,12 @@ void DistributedEngineComm::nextPMToACK(boost::shared_ptr mqe, uint32_t max uint32_t curVal = mqe->unackedWork[nextIndex]; uint32_t unackedWork = (curVal > maxAck ? maxAck : curVal); if (unackedWork > 0) { - (void)atomicops::atomicSub(&mqe->unackedWork[nextIndex], unackedWork); +#ifdef _MSC_VER + int32_t tmp = static_cast(unackedWork); + InterlockedAdd(&mqe->unackedWork[nextIndex], -tmp); +#else + __sync_sub_and_fetch(&mqe->unackedWork[nextIndex], unackedWork); +#endif *sockIndex = nextIndex; *numToAck = unackedWork; if (pmCount > 0) @@ -710,15 +825,19 @@ void DistributedEngineComm::setFlowControl(bool enabled, uint32_t uniqueID, boos msg.advanceInputPtr(sizeof(ISMPacketHeader)); - for (uint32_t i = 0; i < mqe->pmCount; i++) + for (uint i = 0; i < mqe->pmCount; i++) writeToClient(i, msg); } +#ifdef SHARED_NOTHING_DEMO + void DistributedEngineComm::write(ByteStream& msg, BRM::OID_t oid) +#else void DistributedEngineComm::write(uint32_t senderID, ByteStream& msg) +#endif { ISMPacketHeader *ism = (ISMPacketHeader *) msg.buf(); - uint32_t dest; - uint32_t numConn = fPmConnections.size(); + uint dest; + uint numConn = fPmConnections.size(); if (numConn > 0) { switch (ism->Command) { @@ -731,20 +850,45 @@ void DistributedEngineComm::setFlowControl(bool enabled, uint32_t uniqueID, boos case BATCH_PRIMITIVE_ABORT: case DICT_CREATE_EQUALITY_FILTER: case DICT_DESTROY_EQUALITY_FILTER: - /* XXXPAT: This relies on the assumption that the first pmCount "PMS*" - entries in the config file point to unique PMs */ - uint32_t i; - for (i = 0; i < pmCount; i++) - writeToClient(i, msg, senderID); - return; + if (fMulticast) + try + { + mutex::scoped_lock lk(fMulticastLock); + fMulticastSender.send(msg); + } + catch (const MulticastException&) + { + writeToLog(__FILE__, __LINE__, " Error in setting up Multicast. Turning Multicast send off.", LOG_TYPE_WARNING); + fMulticast = false; +#ifdef _MSC_VER + LONG i; +#else + uint i; +#endif + for (i = 0; i < pmCount; i++) + writeToClient(i, msg, senderID); + return; + } + else { + /* XXXPAT: This relies on the assumption that the first pmCount "PMS*" + entries in the config file point to unique PMs */ +#ifdef _MSC_VER + LONG i; +#else + uint i; +#endif + for (i = 0; i < pmCount; i++) + writeToClient(i, msg, senderID); + return; + } case BATCH_PRIMITIVE_RUN: case DICT_TOKEN_BY_SCAN_COMPARE: // for efficiency, writeToClient() grabs the interleaving factor for the caller, - // and decides the final connection index because it already grabs the + // and decides the final connection index because it already grabs the // caller's queue information dest = ism->Interleave; writeToClient(dest, msg, senderID, true); - break; + return; default: idbassert_s(0, "Unknown message type"); } @@ -756,32 +900,25 @@ void DistributedEngineComm::setFlowControl(bool enabled, uint32_t uniqueID, boos } } -void DistributedEngineComm::write(messageqcpp::ByteStream &msg, uint32_t connection) +void DistributedEngineComm::write(messageqcpp::ByteStream &msg, uint connection) { ISMPacketHeader *ism = (ISMPacketHeader *) msg.buf(); - PrimitiveHeader *pm = (PrimitiveHeader *) (ism + 1); - uint32_t senderID = pm->UniqueID; - - mutex::scoped_lock lk(fMlock, defer_lock_t()); - MessageQueueMap::iterator it; - Stats *senderStats = NULL; - - lk.lock(); - it = fSessionMessages.find(senderID); - if (it != fSessionMessages.end()) - senderStats = &(it->second->stats); - lk.unlock(); - newClients[connection]->write(msg, NULL, senderStats); + if (ism->Command == BATCH_PRIMITIVE_CREATE) + { + /* Disable flow control initially */ + msg << (uint32_t) -1; + } + newClients[connection]->write(msg); } - void DistributedEngineComm::StartClientListener(boost::shared_ptr cl, uint32_t connIndex) + void DistributedEngineComm::StartClientListener(boost::shared_ptr cl, uint connIndex) { boost::thread *thrd = new boost::thread(EngineCommRunner(this, cl, connIndex)); fPmReader.push_back(thrd); } - void DistributedEngineComm::addDataToOutput(SBS sbs, uint32_t connIndex, Stats *stats) + void DistributedEngineComm::addDataToOutput(SBS sbs, uint connIndex) { ISMPacketHeader *hdr = (ISMPacketHeader*)(sbs->buf()); PrimitiveHeader *p = (PrimitiveHeader *)(hdr+1); @@ -800,7 +937,11 @@ void DistributedEngineComm::write(messageqcpp::ByteStream &msg, uint32_t connect lk.unlock(); if (pmCount > 0) { - (void)atomicops::atomicInc(&mqe->unackedWork[connIndex % pmCount]); +#ifdef _MSC_VER + InterlockedIncrement(&mqe->unackedWork[connIndex % pmCount]); +#else + __sync_add_and_fetch(&mqe->unackedWork[connIndex % pmCount], 1); +#endif } TSQSize_t queueSize = mqe->queue.push(sbs); @@ -813,8 +954,6 @@ void DistributedEngineComm::write(messageqcpp::ByteStream &msg, uint32_t connect if (!mqe->throttled && queueSize.size >= mqe->targetQueueSize) setFlowControl(true, uniqueId, mqe); } - if (stats) - mqe->stats.dataRecvd(stats->dataRecvd()); } void DistributedEngineComm::doHasBigMsgs(boost::shared_ptr mqe, uint64_t targetSize) @@ -828,32 +967,28 @@ int DistributedEngineComm::writeToClient(size_t index, const ByteStream& bs, uin { mutex::scoped_lock lk(fMlock, defer_lock_t()); MessageQueueMap::iterator it; - Stats *senderStats = NULL; - uint32_t interleaver = 0; + uint interleaver = 0; if (fPmConnections.size() == 0) return 0; - - if (sender != numeric_limits::max()) { + + if (doInterleaving && sender != numeric_limits::max()) { lk.lock(); it = fSessionMessages.find(sender); - if (it != fSessionMessages.end()) { - senderStats = &(it->second->stats); - if (doInterleaving) - interleaver = it->second->interleaver[index % it->second->pmCount]++; - } + if (it != fSessionMessages.end()) + interleaver = it->second->interleaver[index % it->second->pmCount]++; lk.unlock(); } try { - if (doInterleaving) + if (doInterleaving) index = (index + (interleaver * pmCount)) % fPmConnections.size(); ClientList::value_type client = fPmConnections[index]; if (!client->isAvailable()) return 0; mutex::scoped_lock lk(*(fWlock[index])); - client->write(bs, NULL, senderStats); + client->write(bs); return 0; } catch(...) @@ -861,7 +996,7 @@ int DistributedEngineComm::writeToClient(size_t index, const ByteStream& bs, uin // @bug 488. error out under such condition instead of re-trying other connection, // by pushing 0 size bytestream to messagequeue and throw excpetion SBS sbs; - lk.lock(); + mutex::scoped_lock lk(fMlock); //cout << "WARNING: DEC WRITE BROKEN PIPE. PMS index = " << index << endl; MessageQueueMap::iterator map_tok; sbs.reset(new ByteStream(0)); @@ -869,7 +1004,11 @@ int DistributedEngineComm::writeToClient(size_t index, const ByteStream& bs, uin for (map_tok = fSessionMessages.begin(); map_tok != fSessionMessages.end(); ++map_tok) { map_tok->second->queue.clear(); - (void)atomicops::atomicInc(&map_tok->second->unackedWork[0]); +#ifdef _MSC_VER + InterlockedIncrement(&map_tok->second->unackedWork[0]); +#else + __sync_add_and_fetch(&map_tok->second->unackedWork[0], 1); // prevent an error msg +#endif map_tok->second->queue.push(sbs); } @@ -884,7 +1023,7 @@ int DistributedEngineComm::writeToClient(size_t index, const ByteStream& bs, uin //cout << "module name = " << moduleName << endl; if (index >= fPmConnections.size()) return 0; - for (uint32_t i = 0; i < fPmConnections.size(); i++) + for (uint i = 0; i < fPmConnections.size(); i++) { if (moduleName != fPmConnections[i]->moduleName()) tempConns.push_back(fPmConnections[i]); @@ -907,7 +1046,7 @@ int DistributedEngineComm::writeToClient(size_t index, const ByteStream& bs, uin } } -uint32_t DistributedEngineComm::size(uint32_t key) +uint DistributedEngineComm::size(uint32_t key) { mutex::scoped_lock lk(fMlock); MessageQueueMap::iterator map_tok = fSessionMessages.find(key); @@ -929,33 +1068,28 @@ void DistributedEngineComm::removeDECEventListener(DECEventListener *l) { mutex::scoped_lock lk(eventListenerLock); std::vector newListeners; - uint32_t s = eventListeners.size(); + uint s = eventListeners.size(); - for (uint32_t i = 0; i < s; i++) + for (uint i = 0; i < s; i++) if (eventListeners[i] != l) newListeners.push_back(eventListeners[i]); eventListeners.swap(newListeners); } -Stats DistributedEngineComm::getNetworkStats(uint32_t uniqueID) -{ - mutex::scoped_lock lk(fMlock); - MessageQueueMap::iterator it; - Stats empty; - - it = fSessionMessages.find(uniqueID); - if (it != fSessionMessages.end()) - return it->second->stats; - return empty; -} - -DistributedEngineComm::MQE::MQE(uint32_t pCount) : ackSocketIndex(0), pmCount(pCount), hasBigMsgs(false), +DistributedEngineComm::MQE::MQE(uint pCount) : ackSocketIndex(0), pmCount(pCount), hasBigMsgs(false), targetQueueSize(targetRecvQueueSize) { +#ifdef _MSC_VER + unackedWork.reset(new volatile long[pmCount]); + interleaver.reset(new long[pmCount]); + memset((void *) unackedWork.get(), 0, pmCount * sizeof(long)); + memset((void *) interleaver.get(), 0, pmCount + sizeof(long)); +#else unackedWork.reset(new volatile uint32_t[pmCount]); - interleaver.reset(new uint32_t[pmCount]); + interleaver.reset(new uint[pmCount]); memset((void *) unackedWork.get(), 0, pmCount * sizeof(uint32_t)); - memset((void *) interleaver.get(), 0, pmCount * sizeof(uint32_t)); + memset((void *) interleaver.get(), 0, pmCount * sizeof(uint)); +#endif } } diff --git a/dbcon/joblist/distributedenginecomm.h b/dbcon/joblist/distributedenginecomm.h index 0c29cd1a..3f10b4e2 100644 --- a/dbcon/joblist/distributedenginecomm.h +++ b/dbcon/joblist/distributedenginecomm.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ // -// $Id: distributedenginecomm.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: distributedenginecomm.h 9469 2013-05-01 18:38:43Z pleblanc $ // // C++ Interface: distributedenginecomm // -// Description: +// Description: // // // Author: , (C) 2006 @@ -47,11 +47,17 @@ #include "threadsafequeue.h" #include "rwlock_local.h" #include "resourcemanager.h" -#include "messagequeue.h" + +//#define SHARED_NOTHING_DEMO +#ifdef SHARED_NOTHING_DEMO +#include "brmtypes.h" +#endif + +#include "multicast.h" class TestDistributedEngineComm; -#if defined(_MSC_VER) && defined(JOBLIST_DLLEXPORT) +#if defined(_MSC_VER) && defined(DISTRIBUTEDENGINECOMM_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -75,7 +81,7 @@ class DECEventListener virtual ~DECEventListener() { }; /* Do whatever needs to be done to init the new PM */ - virtual void newPMOnline(uint32_t newConnectionNumber) = 0; + virtual void newPMOnline(uint newConnectionNumber) = 0; }; /** @@ -88,8 +94,8 @@ class DistributedEngineComm * Constructors */ EXPORT virtual ~DistributedEngineComm(); - - EXPORT static DistributedEngineComm* instance(ResourceManager& rm, bool isExeMgr=false); + + EXPORT static DistributedEngineComm* instance(ResourceManager& rm); /** @brief delete the static instance * This has the effect of causing the connection to be rebuilt @@ -116,7 +122,7 @@ class DistributedEngineComm * * Returns the next message in the inbound queue for session sessionId and step stepId. * @param bs A pointer to the ByteStream to fill in. - * @note: saves a copy vs read(uint32_t, uint32_t). + * @note: saves a copy vs read(uint, uint). */ EXPORT void read(uint32_t key, messageqcpp::SBS &); @@ -127,21 +133,24 @@ class DistributedEngineComm EXPORT void read_all(uint32_t key, std::vector &v); /** reads queuesize/divisor msgs */ - EXPORT void read_some(uint32_t key, uint32_t divisor, std::vector &v, - bool *flowControlOn = NULL); + EXPORT void read_some(uint32_t key, uint divisor, std::vector &v); /** @brief Write a primitive message * * Writes a primitive message to a primitive server. Msg needs to conatin an ISMPacketHeader. The * LBID is extracted from the ISMPacketHeader and used to determine the actual P/M to send to. */ +#ifdef SHARED_NOTHING_DEMO + EXPORT void write(messageqcpp::ByteStream& msg, BRM::OID_t oid=0); +#else EXPORT void write(uint32_t key, messageqcpp::ByteStream& msg); +#endif //EXPORT void throttledWrite(const messageqcpp::ByteStream& msg); /** @brief Special write function for use only by newPMOnline event handlers */ - EXPORT void write(messageqcpp::ByteStream &msg, uint32_t connection); + EXPORT void write(messageqcpp::ByteStream &msg, uint connection); /** @brief Shutdown this object * @@ -154,7 +163,7 @@ class DistributedEngineComm * Starts the current thread listening on the client socket for primitive response messages. Will not return * until busy() returns false or a zero-length response is received. */ - EXPORT void Listen(boost::shared_ptr client, uint32_t connIndex); + EXPORT void Listen(boost::shared_ptr client, uint connIndex); /** @brief set/unset busy flag * @@ -169,17 +178,18 @@ class DistributedEngineComm /** @brief Returns the size of the queue for the specified jobstep */ - EXPORT uint32_t size(uint32_t key); + EXPORT uint size(uint32_t key); EXPORT void Setup(); EXPORT void addDECEventListener(DECEventListener *); EXPORT void removeDECEventListener(DECEventListener *); - uint64_t connectedPmServers() const { return fPmConnections.size(); } - uint32_t getPmCount() const { return pmCount; } + EXPORT void setMulticast(bool mc) { fMulticast = mc; } + EXPORT void destroyMulticastSender() { fMulticastSender.destroy(); } - messageqcpp::Stats getNetworkStats(uint32_t uniqueID); + uint64_t connectedPmServers() const { return fPmConnections.size(); } + uint getPmCount() const { return pmCount; } friend class ::TestDistributedEngineComm; @@ -189,21 +199,25 @@ class DistributedEngineComm //A queue of ByteStreams coming in from PrimProc heading for a JobStep typedef ThreadSafeQueue StepMsgQueue; - - /* To keep some state associated with the connection. These aren't copyable. */ - struct MQE : public boost::noncopyable { - MQE(uint32_t pmCount); - messageqcpp::Stats stats; + + /* To keep some state associated with the connection */ + struct MQE { + MQE(uint pmCount); StepMsgQueue queue; - uint32_t ackSocketIndex; + uint ackSocketIndex; +#ifdef _MSC_VER + boost::scoped_array unackedWork; + boost::scoped_array interleaver; +#else boost::scoped_array unackedWork; - boost::scoped_array interleaver; - uint32_t pmCount; + boost::scoped_array interleaver; +#endif + uint pmCount; // non-BPP primitives don't do ACKs bool sendACKs; - + // This var will allow us to toggle flow control for BPP instances when - // the UM is keeping up. Send -1 as the ACK value to disable flow control + // the UM is keeping up. Send -1 as the ACK value to disable flow control // on the PM side, positive value to reenable it. Not yet impl'd on the UM side. bool throttled; @@ -213,18 +227,18 @@ class DistributedEngineComm uint64_t targetQueueSize; }; - + //The mapping of session ids to StepMsgQueueLists typedef std::map > MessageQueueMap; - explicit DistributedEngineComm(ResourceManager& rm, bool isExeMgr); + explicit DistributedEngineComm(ResourceManager& rm); - void StartClientListener(boost::shared_ptr cl, uint32_t connIndex); + void StartClientListener(boost::shared_ptr cl, uint connIndex); /** @brief Add a message to the queue * */ - void addDataToOutput(messageqcpp::SBS, uint32_t connIndex, messageqcpp::Stats *statsToAdd); + void addDataToOutput(messageqcpp::SBS, uint connIndex); /** @brief Writes data to the client at the index * @@ -235,7 +249,7 @@ class DistributedEngineComm static DistributedEngineComm* fInstance; ResourceManager& fRm; - + ClientList fPmConnections; // all the pm servers ReaderList fPmReader; // all the reader threads for the pm servers MessageQueueMap fSessionMessages; // place to put messages from the pm server to be returned by the Read method @@ -243,33 +257,36 @@ class DistributedEngineComm std::vector > fWlock; //PrimProc socket write mutexes bool fBusy; unsigned fLBIDShift; - volatile uint32_t pmCount; +#ifdef _MSC_VER + volatile LONG pmCount; +#else + uint pmCount; +#endif boost::mutex fOnErrMutex; // to lock function scope to reset pmconnections under error condition - boost::mutex fSetupMutex; // event listener data std::vector eventListeners; boost::mutex eventListenerLock; - + ClientList newClients; std::vector > newLocks; - - bool fIsExeMgr; - + bool fMulticast; + boost::mutex fMulticastLock; + multicast::MulticastSender fMulticastSender; + // send-side throttling vars uint64_t throttleThreshold; - static const uint32_t targetRecvQueueSize = 50000000; - static const uint32_t disableThreshold = 10000000; - uint32_t tbpsThreadCount; - + static const uint targetRecvQueueSize = 50000000; + static const uint disableThreshold = 10000000; + uint tbpsThreadCount; + void sendAcks(uint32_t uniqueID, const std::vector &msgs, boost::shared_ptr mqe, size_t qSize); - void nextPMToACK(boost::shared_ptr mqe, uint32_t maxAck, uint32_t *sockIndex, + void nextPMToACK(boost::shared_ptr mqe, uint16_t maxAck, uint32_t *sockIndex, uint16_t *numToAck); void setFlowControl(bool enable, uint32_t uniqueID, boost::shared_ptr mqe); void doHasBigMsgs(boost::shared_ptr mqe, uint64_t targetSize); boost::mutex ackLock; - }; } diff --git a/dbcon/joblist/elementcompression.h b/dbcon/joblist/elementcompression.h index 64b42813..26eebfc9 100644 --- a/dbcon/joblist/elementcompression.h +++ b/dbcon/joblist/elementcompression.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: elementcompression.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: elementcompression.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ @@ -61,7 +61,7 @@ struct CompElement32Rid64Val struct CompElement32Rid32Val { - uint32_t first; + uint32_t first; uint32_t second; }; @@ -153,7 +153,7 @@ class ElementCompression static void compress( std::vector& vIn, std::vector& vOut); - + static void compress( std::vector& vIn, std::vector& vOut) @@ -248,7 +248,7 @@ class ElementCompression static void expand( std::vector& vIn, RIDElementType* vOut); - + static void expand( std::vector& vIn, TupleType* vOut) @@ -289,7 +289,7 @@ class ElementCompression std::fstream& fFile); static void writeWith32Rid( const TupleType& e, - std::fstream& fFile) + std::fstream& fFile) {throw std::logic_error( "Compress/Write of 32 RID TupleType not supported");} @@ -312,7 +312,7 @@ class ElementCompression std::fstream& fFile); static void readWith32Rid( TupleType& e, - std::fstream& fFile) + std::fstream& fFile) {throw std::logic_error( "Read/Expand of 32 RID TupleType not supported");} }; diff --git a/dbcon/joblist/elementtype.cpp b/dbcon/joblist/elementtype.cpp index fdf58cb3..6cb3d3cb 100644 --- a/dbcon/joblist/elementtype.cpp +++ b/dbcon/joblist/elementtype.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: elementtype.cpp 9655 2013-06-25 23:08:13Z xlou $ + * $Id: elementtype.cpp 8436 2012-04-04 18:18:21Z rdempsey $ */ #include @@ -38,10 +38,10 @@ StringElementType::StringElementType(uint64_t f, const std::string &s) : first(f DoubleElementType::DoubleElementType() { }; DoubleElementType::DoubleElementType(uint64_t f, double s) : first(f), second(s) { }; - + RIDElementType::RIDElementType() {first = static_cast(-1); }; -RIDElementType::RIDElementType(uint64_t f) : first(f) { }; +RIDElementType::RIDElementType(uint64_t f) : first(f) { }; const string ElementType::toString() const { @@ -57,7 +57,7 @@ istream& operator>>(istream& in, ElementType& rhs) } ostream& operator<<(ostream& out, const ElementType& rhs) -{ +{ out.write((char *) &rhs, sizeof(ElementType)); return out; } @@ -65,11 +65,11 @@ ostream& operator<<(ostream& out, const ElementType& rhs) ostream& operator<<(std::ostream& out, const StringElementType& rhs) { uint64_t r = rhs.first; - int16_t dlen = rhs.second.length(); + int16_t dlen = rhs.second.length(); - out.write((char*)&r, sizeof(r)); - out.write( (char*)&dlen, sizeof(dlen)); - out.write( rhs.second.c_str(), dlen); + out.write((char*)&r, sizeof(r)); + out.write( (char*)&dlen, sizeof(dlen)); + out.write( rhs.second.c_str(), dlen); return out; } @@ -80,9 +80,9 @@ istream& operator>>(std::istream& out, StringElementType& rhs) int16_t dlen; char d[32768]; // atm 32k is the largest possible val for the length of strings stored - out.read((char*)&r, sizeof(r)); - out.read( (char*)&dlen, sizeof(dlen)); - out.read( (char*)&d, dlen); + out.read((char*)&r, sizeof(r)); + out.read( (char*)&dlen, sizeof(dlen)); + out.read( (char*)&d, dlen); rhs.first = r; rhs.second = string(d, dlen); @@ -102,26 +102,26 @@ ostream& operator<<(ostream& out, const DoubleElementType& rhs) return out; } -istream& operator>>(istream &is, RIDElementType &dl) -{ - is.read((char *)&dl, sizeof(RIDElementType)); - return is; +istream& operator>>(istream &is, RIDElementType &dl) +{ + is.read((char *)&dl, sizeof(RIDElementType)); + return is; } -ostream& operator<<(ostream &os, const RIDElementType &dl) -{ - os.write((char *)&dl, sizeof(RIDElementType)); - return os; +ostream& operator<<(ostream &os, const RIDElementType &dl) +{ + os.write((char *)&dl, sizeof(RIDElementType)); + return os; } -istream& operator>>(istream &is, TupleType &dl) -{ - throw std::logic_error("TupleType >> not implemented"); +istream& operator>>(istream &is, TupleType &dl) +{ + throw std::logic_error("TupleType >> not implemented"); } -ostream& operator<<(ostream &os, const TupleType &dl) -{ - throw std::logic_error("TupleType << not implemented"); +ostream& operator<<(ostream &os, const TupleType &dl) +{ + throw std::logic_error("TupleType << not implemented"); } } // namespace joblist diff --git a/dbcon/joblist/elementtype.h b/dbcon/joblist/elementtype.h index 0eca411a..3b99565c 100644 --- a/dbcon/joblist/elementtype.h +++ b/dbcon/joblist/elementtype.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: elementtype.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: elementtype.h 8476 2012-04-25 22:28:15Z xlou $ */ /** @file */ @@ -29,7 +29,6 @@ #include #include #include -#include #ifndef __GNUC__ # ifndef __attribute__ @@ -43,7 +42,7 @@ namespace joblist /** @brief struct ElementType * */ - + struct ElementType { typedef uint64_t first_type; @@ -56,7 +55,7 @@ struct ElementType { }; ElementType(uint64_t f, uint64_t s) : first(f), second(s) { }; - const char * getHashString(uint64_t mode, uint64_t *len) const { + const char * getHashString(uint64_t mode, uint64_t *len) const { switch (mode) { case 0: *len = 8; @@ -86,12 +85,12 @@ struct StringElementType StringElementType(); StringElementType(uint64_t f, const std::string &s); - const char * getHashString(uint64_t mode, uint64_t *len) const { + const char * getHashString(uint64_t mode, uint64_t *len) const { switch (mode) { case 0: *len = sizeof(first); return (char *) &first; - case 1: + case 1: *len = second.size(); return (char *) second.data(); default: @@ -115,9 +114,9 @@ struct DoubleElementType DoubleElementType(uint64_t f, double s); typedef double second_type; - const char * getHashString(uint64_t mode, uint64_t *len) const { + const char * getHashString(uint64_t mode, uint64_t *len) const { switch (mode) { - case 0: + case 0: *len = sizeof(first); return (char *) &first; case 1: @@ -126,7 +125,7 @@ struct DoubleElementType default: throw std::logic_error("StringElementType: invalid mode in getHashString()."); } - } + } inline bool operator<(const DoubleElementType &e) const { return (first < e.first); } }; @@ -143,7 +142,7 @@ struct RowWrapper inline RowWrapper(const RowWrapper &rg) : count(rg.count) { - for (uint32_t i = 0; i < count; ++i) + for (uint i = 0; i < count; ++i) et[i] = rg.et[i]; } @@ -154,7 +153,7 @@ struct RowWrapper inline RowWrapper & operator=(const RowWrapper &rg) { count = rg.count; - for (uint32_t i = 0; i < count; ++i) + for (uint i = 0; i < count; ++i) et[i] = rg.et[i]; return *this; } @@ -169,8 +168,8 @@ struct RIDElementType RIDElementType(); RIDElementType(uint64_t f); - - const char * getHashString(uint64_t mode, uint64_t *len) const { + + const char * getHashString(uint64_t mode, uint64_t *len) const { *len = 8; return (char *) &first; } @@ -183,33 +182,33 @@ struct RIDElementType * first: rid * second: data value in unstructured format */ - + struct TupleType { - uint64_t first; + uint64_t first; char* second; TupleType() {} TupleType (uint64_t f, char* s):first(f), second(s){} - + /** @brief delete a tuple * - * this function should be called by the tuple user outside + * this function should be called by the tuple user outside * the datalist if necessary */ void deleter() { delete [] second; } - - /** @brief get hash string + + /** @brief get hash string * @note params mode and len are ignored here. they are carried * just to keep a consistent interface with the other element type */ - const char * getHashString(uint64_t mode, uint64_t *len) const - { - return (char*)second; + const char * getHashString(uint64_t mode, uint64_t *len) const + { + return (char*)second; } - + bool operator<(const TupleType &e) const { return (first < e.first); } }; @@ -318,7 +317,7 @@ typedef DataList StrDataList; // */ //typedef BucketDL TupleBucketDataList; -typedef FIFO RowGroupDL; +typedef FIFO > RowGroupDL; } @@ -333,8 +332,8 @@ namespace joblist class AnyDataList { public: - AnyDataList() : fDl3(0), fDl6(0), fDl9(0), fDisown(false) { } - ~AnyDataList() { if (!fDisown) { delete fDl3; delete fDl6; delete fDl9; } } + AnyDataList() : fDl3(0), fDl6(0), fDl9(0), fDl20(0), fDisown(false) { } + ~AnyDataList() { if (!fDisown) { delete fDl3; delete fDl6; delete fDl9; delete fDl20; } } // AnyDataList() : fDl1(0), fDl2(0), fDl3(0), fDl4(0), fDl5(0), fDl6(0), fDl7(0), fDl8(0), fDl9(0), // fDl10(0), fDl11(0), fDl12(0), fDl13(0), fDl14(0), fDl15(0), fDl16(0), fDl17(0), fDl18(0), @@ -344,10 +343,10 @@ class AnyDataList // delete fDl12; delete fDl13; delete fDl14; delete fDl15; delete fDl16; delete fDl17; // delete fDl18; delete fDl19; delete fDl20; } } - // disown() fixes the problem of multiple ownership of a single DL, + // disown() fixes the problem of multiple ownership of a single DL, // or one on the stack - //In the world of bad ideas these are at the top. The whole point of this class is to manage + //In the world of bad ideas these are at the top. The whole point of this class is to manage // dynamically allocated data in an automatic way. These 2 methods circumvent this, and they // are not necessary in any event, because you can safely share AnyDataList's via a AnyDataListSPtr. inline void disown() __attribute__ ((deprecated)) { fDisown = true; } @@ -376,7 +375,7 @@ class AnyDataList // inline void sortedWSDL(SortedWSDL* dl) { fDl13 = dl; } // inline SortedWSDL* sortedWSDL() { return fDl13; } // inline const SortedWSDL* sortedWSDL() const { return fDl13; } -// +// // inline void zonedDL(ZonedDL* dl) { fDl15 = dl; } // inline ZonedDL* zonedDL() { return fDl15; } // inline const ZonedDL* zonedDL() const { return fDl15; } @@ -400,28 +399,27 @@ class AnyDataList // inline void stringSortedWSDL(StringSortedWSDL* dl) { fDl14 = dl; } // inline StringSortedWSDL* stringSortedWSDL() { return fDl14; } // inline const StringSortedWSDL* stringSortedWSDL() const { return fDl14; } -// +// // inline void stringZonedDL(StringZonedDL* dl) { fDl16 = dl; } // inline StringZonedDL* stringZonedDL() { return fDl16; } // inline const StringZonedDL* stringZonedDL() const { return fDl16; } -// +// // inline void tupleBucketDL(TupleBucketDataList* dl) { fDl18 = dl; } // inline TupleBucketDataList* tupleBucketDL() { return fDl18; } // inline const TupleBucketDataList* tupleBucketDL() const { return fDl18; } -// +// // inline void deliveryWSDL(DeliveryWSDL *dl) { fDl19 = dl; } // inline DeliveryWSDL * deliveryWSDL() { return fDl19; } // inline const DeliveryWSDL * deliveryWSDL() const { return fDl19; } - inline void rowGroupDL(boost::shared_ptr dl) { fDl20 = dl; } - inline void rowGroupDL(RowGroupDL *dl) { fDl20.reset(dl); } - inline RowGroupDL * rowGroupDL() { return fDl20.get(); } - inline const RowGroupDL * rowGroupDL() const { return fDl20.get(); } + inline void rowGroupDL(RowGroupDL *dl) { fDl20 = dl; } + inline RowGroupDL * rowGroupDL() { return fDl20; } + inline const RowGroupDL * rowGroupDL() const { return fDl20; } DataList_t* dataList() { if (fDl3 != NULL) return reinterpret_cast(fDl3); else if (fDl9 != NULL) return fDl9; - return reinterpret_cast(fDl20.get()); + return reinterpret_cast(fDl20); // if (fDl1 != NULL) return fDl1; // else if (fDl2 != NULL) return fDl2; // else if (fDl3 != NULL) return reinterpret_cast(fDl3); @@ -444,7 +442,7 @@ class AnyDataList // return fDl8; return reinterpret_cast(fDl6); } -// +// // TupleDataList* tupleDataList() { // if (fDl18 != NULL) return fDl18; // return fDl17; @@ -452,7 +450,7 @@ class AnyDataList // // /* fDl{7,8} store base class pointers. For consistency, maybe strDataList // should consider fDl6 also. */ -// inline StrDataList * strDataList() +// inline StrDataList * strDataList() // { return fDl8; } // // inline void strDataList(StrDataList *d) @@ -463,35 +461,35 @@ class AnyDataList // // inline void doubleDL(DoubleDataList *d) // { fDl7 = d; } - + enum DataListTypes { - UNKNOWN_DATALIST, /*!< 0 Unknown DataList */ - BANDED_DATALIST, /*!< 1 Banded DataList */ - WORKING_SET_DATALIST, /*!< 2 WSDL */ - FIFO_DATALIST, /*!< 3 FIFO */ - BUCKET_DATALIST, /*!< 4 Bucket */ - CONSTANT_DATALIST, /*!< 5 Constant */ - STRING_DATALIST, /*!< 6 String */ - DOUBLE_DATALIST, /*!< 7 Double */ - STRINGFIFO_DATALIST, /*!< 8 String FIFO */ - STRINGBANDED_DATALIST, /*!< 9 String Banded */ - STRINGBUCKET_DATALIST, /*!< 10 String Bucket */ - STRINGCONSTANT_DATALIST, /*!< 11 String Constant */ - SORTED_WORKING_SET_DATALIST, /*!< 12 Sorted WSDL */ - STRINGSORTED_WORKING_SET_DATALIST, /*!< 13 String Sorted WSDL */ - ZONED_DATALIST, /*!< 14 Zoned Datalist */ - STRINGZONED_DATALIST, /*!< 15 String Zoned Datalist */ - TUPLEBUCKET_DATALIST, /*!< 16 Tuple Bucket Datalist */ - TUPLE_DATALIST, /*!< 17 Tuple Datalist */ - DELIVERYWSDL, /*!< 18 Delivery WSDL */ - ROWGROUP_DATALIST + UNKNOWN_DATALIST, /*!< 0 Unknown DataList */ + BANDED_DATALIST, /*!< 1 Banded DataList */ + WORKING_SET_DATALIST, /*!< 2 WSDL */ + FIFO_DATALIST, /*!< 3 FIFO */ + BUCKET_DATALIST, /*!< 4 Bucket */ + CONSTANT_DATALIST, /*!< 5 Constant */ + STRING_DATALIST, /*!< 6 String */ + DOUBLE_DATALIST, /*!< 7 Double */ + STRINGFIFO_DATALIST, /*!< 8 String FIFO */ + STRINGBANDED_DATALIST, /*!< 9 String Banded */ + STRINGBUCKET_DATALIST, /*!< 10 String Bucket */ + STRINGCONSTANT_DATALIST, /*!< 11 String Constant */ + SORTED_WORKING_SET_DATALIST, /*!< 12 Sorted WSDL */ + STRINGSORTED_WORKING_SET_DATALIST, /*!< 13 String Sorted WSDL */ + ZONED_DATALIST, /*!< 14 Zoned Datalist */ + STRINGZONED_DATALIST, /*!< 15 String Zoned Datalist */ + TUPLEBUCKET_DATALIST, /*!< 16 Tuple Bucket Datalist */ + TUPLE_DATALIST, /*!< 17 Tuple Datalist */ + DELIVERYWSDL, /*!< 18 Delivery WSDL */ + ROWGROUP_DATALIST }; static DataListTypes dlType(const DataList_t* dl); static DataListTypes strDlType(const StrDataList* dl); // static DataListTypes tupleDlType(const TupleDataList* dl); - uint32_t getNumConsumers() + uint getNumConsumers() { // if (fDl1 != NULL) return fDl1->getNumConsumers(); // else if (fDl2 != NULL) return fDl2->getNumConsumers(); @@ -509,7 +507,7 @@ class AnyDataList // else if (fDl20 != NULL) return 1; // else return 0; - if (fDl20) return 1; + if (fDl20 != NULL) return 1; else if (fDl3 != NULL) return fDl3->getNumConsumers(); else if (fDl6 != NULL) return fDl6->getNumConsumers(); return 0; @@ -544,7 +542,7 @@ class AnyDataList // TupleDataList* fDl17; // TupleBucketDataList *fDl18; // DeliveryWSDL *fDl19; - boost::shared_ptr fDl20; + RowGroupDL *fDl20; bool fDisown; }; diff --git a/dbcon/joblist/errorinfo.h b/dbcon/joblist/errorinfo.h deleted file mode 100644 index af83bc3d..00000000 --- a/dbcon/joblist/errorinfo.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: jobstep.h 9636 2013-06-20 14:23:36Z rdempsey $ - - -/** @file */ - -#ifndef JOBLIST_ERROR_INFO_H_ -#define JOBLIST_ERROR_INFO_H_ - -#include -#include - -namespace joblist -{ - -/** @brief struct ErrorInfo - * - * struct ErrorInfo stores the error code and message - */ -struct ErrorInfo { - ErrorInfo() : errCode(0) { } - uint32_t errCode; - std::string errMsg; - // for backward compat - ErrorInfo(uint16_t v) : errCode(v) { } - ErrorInfo & operator=(uint16_t v) { errCode = v; errMsg.clear(); return *this; } -}; -typedef boost::shared_ptr SErrorInfo; - - -} - -#endif // JOBLIST_ERROR_INFO_H_ -// vim:ts=4 sw=4: - - - diff --git a/dbcon/joblist/expressionstep.cpp b/dbcon/joblist/expressionstep.cpp index 96616ee0..5f69fbdc 100644 --- a/dbcon/joblist/expressionstep.cpp +++ b/dbcon/joblist/expressionstep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: expressionstep.cpp 9681 2013-07-11 22:58:05Z xlou $ +// $Id: expressionstep.cpp 8526 2012-05-17 02:28:10Z xlou $ //#define NDEBUG @@ -40,15 +40,12 @@ using namespace logging; #include "arithmeticcolumn.h" #include "constantcolumn.h" #include "functioncolumn.h" -#include "pseudocolumn.h" #include "simplecolumn.h" -#include "windowfunctioncolumn.h" #include "constantfilter.h" #include "simplefilter.h" using namespace execplan; #include "jlf_common.h" -#include "jlf_tuplejoblist.h" #include "rowgroup.h" using namespace rowgroup; @@ -56,24 +53,37 @@ using namespace rowgroup; namespace joblist { -ExpressionStep::ExpressionStep(const JobInfo& jobInfo) : - JobStep(jobInfo), - fExpressionFilter(NULL), - fExpressionId(-1), - fVarBinOK(false), - fSelectFilter(false), - fAssociatedJoinId(0), - fDoJoin(false), - fVirtual(false) +ExpressionStep::ExpressionStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId) : + fSessionId(sessionId), + fTxnId(txnId), + fVerId(verId), + fStatementId(statementId), + fExpressionFilter(NULL), + fExpressionId(-1), + fVarBinOK(false), + fSelectFilter(false), + fAssociatedJoinId(0) { } ExpressionStep::ExpressionStep(const ExpressionStep& rhs) : - JobStep(rhs), + fInputJobStepAssociation(rhs.inputAssociation()), + fOutputJobStepAssociation(rhs.outputAssociation()), + fSessionId(rhs.sessionId()), + fTxnId(rhs.txnId()), + fVerId(rhs.verId()), + fStepId(rhs.stepId()), + fStatementId(rhs.statementId()), fExpression(rhs.expression()), fExpressionFilter(NULL), fExpressionId(rhs.expressionId()), + fTableOids(tableOids()), + fOids(rhs.oids()), fAliases(rhs.aliases()), fViews(rhs.views()), fSchemas(rhs.schemas()), @@ -81,9 +91,7 @@ ExpressionStep::ExpressionStep(const ExpressionStep& rhs) : fColumnKeys(rhs.columnKeys()), fVarBinOK(rhs.fVarBinOK), fSelectFilter(rhs.fSelectFilter), - fAssociatedJoinId(rhs.fAssociatedJoinId), - fDoJoin(rhs.fDoJoin), - fVirtual(rhs.fVirtual) + fAssociatedJoinId(rhs.fAssociatedJoinId) { if (rhs.expressionFilter() != NULL) fExpressionFilter = new ParseTree(*(rhs.expressionFilter())); @@ -113,18 +121,22 @@ void ExpressionStep::expression(const SRCP exp, JobInfo& jobInfo) // set expression Id ArithmeticColumn* ac = dynamic_cast(fExpression.get()); - FunctionColumn* fc = dynamic_cast(fExpression.get()); - fExpressionId = exp.get()->expressionId(); + FunctionColumn* fc = NULL; + if (ac != NULL) + fExpressionId = ac->expressionId(); + else if ((fc = dynamic_cast(fExpression.get())) != NULL) + fExpressionId = fc->expressionId(); + else + throw runtime_error("Unsupported Expression"); - if (ac != NULL || fc != NULL) - addColumn(exp.get(), jobInfo); + addColumn(exp.get(), jobInfo); } void ExpressionStep::expressionFilter(const Filter* filter, JobInfo& jobInfo) { Filter *f = filter->clone(); - fExpressionFilter = new ParseTree(f); + fExpressionFilter = new ParseTree(f); idbassert(fExpressionFilter != NULL); if (fExpressionFilter == NULL) { @@ -134,18 +146,26 @@ void ExpressionStep::expressionFilter(const Filter* filter, JobInfo& jobInfo) throw runtime_error(errmsg.str()); } - addFilter(fExpressionFilter, jobInfo); - // populate the oid vectors - SimpleFilter* sf = dynamic_cast(f); - if (sf != NULL && sf->op()->data() == "=") - functionJoinCheck(sf, jobInfo); + SimpleFilter* sf = NULL; + ConstantFilter* cf = NULL; + if ((sf = dynamic_cast(f)) != NULL) + { + addColumn(sf->lhs(), jobInfo); + addColumn(sf->rhs(), jobInfo); + } + else if ((cf = dynamic_cast(f)) != NULL) + { + //addColumn(cf->col().get(), jobInfo); + for (uint i = 0; i < cf->simpleColumnList().size(); i++) + addColumn(cf->simpleColumnList()[i], jobInfo); + } } void ExpressionStep::expressionFilter(const ParseTree* filter, JobInfo& jobInfo) { - fExpressionFilter = new ParseTree(); + fExpressionFilter = new ParseTree(); idbassert(fExpressionFilter != NULL); if (fExpressionFilter == NULL) { @@ -156,160 +176,55 @@ void ExpressionStep::expressionFilter(const ParseTree* filter, JobInfo& jobInfo) } fExpressionFilter->copyTree(*filter); - addFilter(fExpressionFilter, jobInfo); -} - - -void ExpressionStep::addSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) -{ - addColumn(sf->lhs(), jobInfo); - addColumn(sf->rhs(), jobInfo); -} - - -void ExpressionStep::addFilter(ParseTree* filter, JobInfo& jobInfo) -{ - stack filterStack; - while (filter || !filterStack.empty()) - { - if(filter != NULL) - { - filterStack.push(filter); - filter = filter->left(); - } - else if (!filterStack.empty()) - { - filter = filterStack.top(); - filterStack.pop(); - - TreeNode* tn = filter->data(); - filter = filter->right(); - - ReturnedColumn* rc = dynamic_cast(tn); - SimpleFilter *sf = dynamic_cast(tn); - ConstantFilter *cf = dynamic_cast(tn); - Operator* op = dynamic_cast(tn); - if (rc != NULL) - { - addColumn(rc, jobInfo); - } - else if (sf != NULL) - { - addSimpleFilter(sf, jobInfo); - } - else if (cf != NULL) - { - const ConstantFilter::FilterList& fs = cf->filterList(); - for (ConstantFilter::FilterList::const_iterator i = fs.begin(); i != fs.end(); i++) - { - SimpleFilter* f = dynamic_cast(i->get()); - if (f != NULL) - addSimpleFilter(f, jobInfo); - else - throw logic_error("unknow filter type in constant filter."); - } - } - else if (op == NULL) - { - throw logic_error("tree node not handled in Expression step."); - } - } - } - -#if 0 // have to workaround correlation on exp, the following approach does not work // extract simple columns from parse tree vector scv; - filter->walk(getSimpleCols, &scv); + fExpressionFilter->walk(getSimpleCols, &scv); // populate the oid vectors for (vector::iterator it = scv.begin(); it != scv.end(); it++) addColumn(*it, jobInfo); - - // aggregate columns - vector acv; - filter->walk(getAggCols, &acv); - for (vector::iterator it = acv.begin(); it != acv.end(); it++) - addColumn(*it, jobInfo); - - // window function columns - vector wcv; - filter->walk(getWindowFunctionCols, &wcv); - for (vector::iterator it = wcv.begin(); it != wcv.end(); it++) - addColumn(*it, jobInfo); -#endif - - return; } void ExpressionStep::addColumn(ReturnedColumn* rc, JobInfo& jobInfo) { - const vector* scs = NULL; - const vector* wcs = NULL; - ArithmeticColumn* ac = NULL; - FunctionColumn* fc = NULL; - SimpleColumn* sc = NULL; - WindowFunctionColumn* wc = NULL; - - // workaround for exp(sc) in (sub) where correlation is set on exp, but not sc. - // populate it to sc for correct scope resolution - uint64_t correlated = rc->joinInfo(); - if (NULL != (ac = dynamic_cast(rc))) + const vector* cols = NULL; + const ArithmeticColumn* ac = NULL; + const FunctionColumn* fc = NULL; + SimpleColumn* sc = NULL; + + if (NULL != (ac = dynamic_cast(rc))) { - scs = &(ac->simpleColumnList()); - wcs = &(ac->windowfunctionColumnList()); + cols = &(ac->simpleColumnList()); } - else if (NULL != (fc = dynamic_cast(rc))) + else if (NULL != (fc = dynamic_cast(rc))) { - scs = &(fc->simpleColumnList()); - wcs = &(fc->windowfunctionColumnList()); + cols = &(fc->simpleColumnList()); fVarBinOK = ((strcmp(fc->functionName().c_str(), "hex") == 0) || (strcmp(fc->functionName().c_str(), "length") == 0)); } - if (scs != NULL || wcs != NULL) + + if (cols != NULL) { - if (scs != NULL) - { - vector::const_iterator cit = scs->begin(); - vector::const_iterator end = scs->end(); - while (cit != end) - { - SimpleColumn* sc = *cit; - sc->joinInfo(sc->joinInfo() | correlated); - populateColumnInfo(*cit, jobInfo); - ++cit; - } - } - if (wcs != NULL) + vector::const_iterator cit = cols->begin(); + vector::const_iterator end = cols->end(); + while (cit != end) { - vector::const_iterator cit = wcs->begin(); - vector::const_iterator end = wcs->end(); - while (cit != end) - { - populateColumnInfo(*cit, jobInfo); - ++cit; - } + populateColumnInfo(*cit, jobInfo); + ++cit; } } else if (NULL != (sc = dynamic_cast(rc))) { populateColumnInfo(sc, jobInfo); } - else if (NULL != (wc = dynamic_cast(rc))) - { - populateColumnInfo(rc, jobInfo); - } - else if (NULL != (dynamic_cast(rc))) - { - populateColumnInfo(rc, jobInfo); - } else { - ConstantColumn* cc = dynamic_cast(rc); + const ConstantColumn* cc = dynamic_cast(rc); -// idbassert(cc != NULL) + idbassert(cc != NULL); if (cc == NULL) { std::ostringstream errmsg; @@ -321,30 +236,10 @@ void ExpressionStep::addColumn(ReturnedColumn* rc, JobInfo& jobInfo) } -void ExpressionStep::populateColumnInfo(ReturnedColumn* rc, JobInfo& jobInfo) -{ - // As of bug3695, make sure varbinary is not used in function expression. - if (rc->resultType().colDataType == CalpontSystemCatalog::VARBINARY && !fVarBinOK) - throw runtime_error("VARBINARY in filter or function is not supported."); - - SimpleColumn* sc = dynamic_cast(rc); - WindowFunctionColumn* wc = NULL; - AggregateColumn* ac = NULL; - if (NULL != sc) - return populateColumnInfo(sc, jobInfo); - else if (NULL != (wc = dynamic_cast(rc))) - return populateColumnInfo(wc, jobInfo); - else if (NULL != (ac = dynamic_cast(rc))) - return populateColumnInfo(ac, jobInfo); - else // for now only allow simple and windowfunction column, more work to do. - throw runtime_error("Error in parsing expression."); -} - - void ExpressionStep::populateColumnInfo(SimpleColumn* sc, JobInfo& jobInfo) { // As of bug3695, make sure varbinary is not used in function expression. - if (sc->resultType().colDataType == CalpontSystemCatalog::VARBINARY && !fVarBinOK) + if (sc->resultType().colDataType == CalpontSystemCatalog::VARBINARY && !fVarBinOK) throw runtime_error ("VARBINARY in filter or function is not supported."); CalpontSystemCatalog::OID tblOid = joblist::tableOid(sc, jobInfo.csc); @@ -366,13 +261,12 @@ void ExpressionStep::populateColumnInfo(SimpleColumn* sc, JobInfo& jobInfo) { ct = sc->colType(); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (dynamic_cast(sc) == NULL) - ct = jobInfo.csc->colType(sc->oid()); + ct = jobInfo.csc->colType(sc->oid()); //X if (ct.scale == 0) // keep passed original ct for decimal type sc->resultType(ct); // update from mysql type to calpont type } + fOids.push_back(sc->oid()); fAliases.push_back(alias); fViews.push_back(view); fSchemas.push_back(schema); @@ -397,68 +291,18 @@ void ExpressionStep::populateColumnInfo(SimpleColumn* sc, JobInfo& jobInfo) CalpontSystemCatalog::OID dictOid = joblist::isDictCol(ct); if (dictOid > 0) { - uint32_t tupleKey = ti.key; + uint tupleKey = ti.key; jobInfo.tokenOnly[tupleKey] = false; jobInfo.keyInfo->dictOidToColOid[dictOid] = sc->oid(); ti = setTupleInfo(ct, dictOid, jobInfo, tblOid, sc, alias); jobInfo.keyInfo->dictKeyMap[tupleKey] = ti.key; } -} - - -void ExpressionStep::populateColumnInfo(WindowFunctionColumn* wc, JobInfo& jobInfo) -{ - // As of bug3695, make sure varbinary is not used in function expression. - if (wc->resultType().colDataType == CalpontSystemCatalog::VARBINARY && !fVarBinOK) - throw runtime_error("VARBINARY in filter or function is not supported."); - - // This is for window function in IN/EXISTS sub-query. - // In 4.0 implementation, the window function is cloned to where clause in a simple filter. - // This can be identified because SQL syntax does NOT allow window function in where clause. - // Workaround here until a better way found. - TupleInfo ti(setExpTupleInfo(wc->resultType(), wc->expressionId(), wc->alias(), jobInfo)); - uint64_t wcKey = ti.key; - string alias(""); - string view(""); - string schema(""); - fTableOids.push_back(jobInfo.keyInfo->tupleKeyToTableOid[wcKey]); - fAliases.push_back(alias); - fViews.push_back(view); - fSchemas.push_back(schema); - fTableKeys.push_back(jobInfo.keyInfo->colKeyToTblKey[wcKey]); - fColumnKeys.push_back(wcKey); - fColumns.push_back(wc); -} - -void ExpressionStep::populateColumnInfo(AggregateColumn* ac, JobInfo& jobInfo) -{ - // As of bug3695, make sure varbinary is not used in function expression. - if (ac->resultType().colDataType == CalpontSystemCatalog::VARBINARY && !fVarBinOK) - throw runtime_error("VARBINARY in filter or function is not supported."); - - // This is for aggregate function in IN/EXISTS sub-query. - TupleInfo ti(setExpTupleInfo(ac->resultType(), ac->expressionId(), ac->alias(), jobInfo)); - uint64_t acKey = ti.key; - string alias(""); - string view(""); - string schema(""); - fTableOids.push_back(jobInfo.keyInfo->tupleKeyToTableOid[acKey]); - fAliases.push_back(alias); - fViews.push_back(view); - fSchemas.push_back(schema); - fTableKeys.push_back(jobInfo.keyInfo->colKeyToTblKey[acKey]); - fColumnKeys.push_back(acKey); - fColumns.push_back(ac); } -void ExpressionStep::updateInputIndex(map& indexMap, const JobInfo& jobInfo) +void ExpressionStep::updateInputIndex(map& indexMap, const JobInfo& jobInfo) { - // expression is handled as function join already - if (fDoJoin) - return; - if (jobInfo.trace) cout << "Input indices of Expression:" << (int64_t) fExpressionId << endl; @@ -471,7 +315,7 @@ void ExpressionStep::updateInputIndex(map& indexMap, const J CalpontSystemCatalog::OID oid = sc->oid(); CalpontSystemCatalog::OID dictOid = 0; CalpontSystemCatalog::ColType ct; - uint32_t key = fColumnKeys[distance(fColumns.begin(), it)]; + uint key = fColumnKeys[distance(fColumns.begin(), it)]; if (sc->schemaName().empty()) { ct = sc->resultType(); @@ -482,12 +326,7 @@ void ExpressionStep::updateInputIndex(map& indexMap, const J } else { - ct = sc->colType(); -//XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (dynamic_cast(sc) == NULL) - ct = jobInfo.csc->colType(oid); -//X + ct = jobInfo.csc->colType(oid); dictOid = joblist::isDictCol(ct); if (dictOid > 0) key = jobInfo.keyInfo->dictKeyMap[key]; @@ -495,11 +334,26 @@ void ExpressionStep::updateInputIndex(map& indexMap, const J sc->inputIndex(indexMap[key]); if (jobInfo.trace) - cout <<"OID/key:"<<(dictOid?dictOid:oid)<<"/"<tableAlias()<<"):"; + cout << "OID:" << (dictOid ? dictOid : oid) << "(" << sc->tableAlias() << "):"; } else { - (*it)->inputIndex(indexMap[getExpTupleKey(jobInfo, (*it)->expressionId())]); + ArithmeticColumn* ac = dynamic_cast(*it); + AggregateColumn* ag = NULL; + FunctionColumn* fc = NULL; + + if (ac != NULL) + { + ac->inputIndex(indexMap[getExpTupleKey(jobInfo, ac->expressionId())]); + } + else if ((ag = dynamic_cast(*it)) != NULL) + { + ag->inputIndex(indexMap[getExpTupleKey(jobInfo, ag->expressionId())]); + } + else if ((fc = dynamic_cast(*it)) != NULL) + { + fc->inputIndex(indexMap[getExpTupleKey(jobInfo, fc->expressionId())]); + } if (jobInfo.trace) cout << "EID:" << (*it)->expressionId(); @@ -508,14 +362,10 @@ void ExpressionStep::updateInputIndex(map& indexMap, const J if (jobInfo.trace) cout << (*it)->inputIndex() << endl; } - - // if substutes exist, update the original column - for (map::iterator k = fSubMap.begin(); k != fSubMap.end(); k++) - k->second->inputIndex(k->first->inputIndex()); } -void ExpressionStep::updateOutputIndex(map& indexMap, const JobInfo& jobInfo) +void ExpressionStep::updateOutputIndex(map& indexMap, const JobInfo& jobInfo) { fExpression->outputIndex(indexMap[getExpTupleKey(jobInfo, fExpressionId)]); @@ -535,195 +385,13 @@ void ExpressionStep::updateColumnOidAlias(JobInfo& jobInfo) if (sc != NULL && sc->schemaName().empty()) { fTableOids[i] = joblist::tableOid(sc, jobInfo.csc); + fOids[i] = sc->oid(); fAliases[i] = extractTableAlias(sc); } } } -void ExpressionStep::substitute(uint64_t i, const SSC& ssc) -{ - fVsc.insert(ssc); // save a local copy in case the virtual table in subquery be out of scope. - fSubMap[ssc.get()] = fColumns[i]; - fColumns[i] = ssc.get(); -} - - -void ExpressionStep::functionJoinCheck(SimpleFilter* sf, JobInfo& jobInfo) -{ - // only handle one & only one table at each side, and not the same table - fFunctionJoinInfo.reset(new FunctionJoinInfo); - if ((parseFuncJoinColumn(sf->lhs(), jobInfo) == false) || - (parseFuncJoinColumn(sf->rhs(), jobInfo) == false) || - (fFunctionJoinInfo->fTableKey[0] == fFunctionJoinInfo->fTableKey[1]) || - (!compatibleColumnTypes(sf->lhs()->resultType(), sf->rhs()->resultType(), true))) - { - // for better error message - if (fFunctionJoinInfo->fTableKey.size() == 2) - { - uint32_t t1 = fFunctionJoinInfo->fTableKey[0]; - uint32_t t2 = fFunctionJoinInfo->fTableKey[1]; - jobInfo.incompatibleJoinMap[t1] = t2; - jobInfo.incompatibleJoinMap[t2] = t1; - } - - // not convertible - fFunctionJoinInfo.reset(); - return; - } - - SJSTEP sjstep; - ReturnedColumn* sfLhs = sf->lhs(); - ReturnedColumn* sfRhs = sf->rhs(); - if (dynamic_cast(sfLhs) == NULL) - { - SRCP lhs(sfLhs->clone()); - ExpressionStep* esLhs = new ExpressionStep(jobInfo); - esLhs->expression(lhs, jobInfo); - sjstep.reset(esLhs); - } - fFunctionJoinInfo->fStep.push_back(sjstep); - sjstep.reset(); - - if (dynamic_cast(sfRhs) == NULL) - { - SRCP rhs(sfRhs->clone()); - ExpressionStep* esRhs = new ExpressionStep(jobInfo); - esRhs->expression(rhs, jobInfo); - sjstep.reset(esRhs); - } - fFunctionJoinInfo->fStep.push_back(sjstep); - - JoinType jt = INNER; - if (sfLhs->returnAll()) - jt = LEFTOUTER; - else if (sfRhs->returnAll()) - jt = RIGHTOUTER; - - uint64_t joinInfo = sfLhs->joinInfo() | sfRhs->joinInfo(); - int64_t correlatedSide = 0; - ExpressionStep* ve = NULL; - if (joinInfo != 0) - { - if (joinInfo & JOIN_SEMI) - jt |= SEMI; - - if (joinInfo & JOIN_ANTI) - jt |= ANTI; - - if (joinInfo & JOIN_SCALAR) - jt |= SCALAR; - - if (joinInfo & JOIN_NULL_MATCH) - jt |= MATCHNULLS; - - if (joinInfo & JOIN_CORRELATED) - jt |= CORRELATED; - - if (joinInfo & JOIN_OUTER_SELECT) - jt |= LARGEOUTER; - - if (sfLhs->joinInfo() & JOIN_CORRELATED) - { - correlatedSide = 1; - ve = dynamic_cast(fFunctionJoinInfo->fStep[1].get()); - } - else if (sfRhs->joinInfo() & JOIN_CORRELATED) - { - correlatedSide = 2; - ve = dynamic_cast(fFunctionJoinInfo->fStep[0].get()); - } - } - - if (ve != NULL) - ve->virtualStep(); - - fFunctionJoinInfo->fJoinType = jt; - fFunctionJoinInfo->fCorrelatedSide = correlatedSide; - fFunctionJoinInfo->fJoinId = ++jobInfo.joinNum; - - jobInfo.functionJoins.push_back(this); -} - - -bool ExpressionStep::parseFuncJoinColumn(ReturnedColumn* rc, JobInfo& jobInfo) -{ - set tids; // tables used in the expression - set cids; // columns used in the expression - uint32_t key = -1; // join key - uint32_t tid = -1; // table Id of the simple column - bool isSc = false; // rc is a simple column - - ArithmeticColumn* ac = dynamic_cast(rc); - FunctionColumn* fc = dynamic_cast(rc); - SimpleColumn* sc = dynamic_cast(rc); - if (sc != NULL) - { - isSc = true; - key = getTupleKey(jobInfo, sc); - tid = getTableKey(jobInfo, key); - if (jobInfo.keyInfo->dictKeyMap.find(key) != jobInfo.keyInfo->dictKeyMap.end()) - key = jobInfo.keyInfo->dictKeyMap[key]; - tids.insert(tid); - cids.insert(key); - } - else if (ac != NULL || fc != NULL) - { - TupleInfo ti(setExpTupleInfo(rc, jobInfo)); - key = ti.key; - for (uint32_t i = 0; i < rc->simpleColumnList().size(); i++) - { - sc = rc->simpleColumnList()[i]; - uint32_t cid = getTupleKey(jobInfo, sc); - tid = getTableKey(jobInfo, cid); - tids.insert(tid); - cids.insert(cid); - } - } - - int32_t tableOid = -1; - int32_t oid = -1; - string alias; - string view; - string schema; - if (sc && tids.size() == 1) - { - tableOid = joblist::tableOid(sc, jobInfo.csc); - oid = sc->oid(); - alias = extractTableAlias(sc); - view = sc->viewName(); - schema = sc->schemaName(); - } - else if (dynamic_cast(rc) || dynamic_cast(rc) || - dynamic_cast(rc) || dynamic_cast(rc)) - { - tableOid = execplan::CNX_VTABLE_ID; - oid = rc->expressionId(); - alias = jobInfo.subAlias; - } - else - { - return false; - } - - if (isSc == false) - jobInfo.keyInfo->functionJoinKeys.insert(key); - - fFunctionJoinInfo->fExpression.push_back(rc); - fFunctionJoinInfo->fJoinKey.push_back(key); - fFunctionJoinInfo->fTableKey.push_back(tid); - fFunctionJoinInfo->fColumnKeys.push_back(cids); - fFunctionJoinInfo->fTableOid.push_back(tableOid); - fFunctionJoinInfo->fOid.push_back(oid); - fFunctionJoinInfo->fSequence.push_back(rc->sequence()); - fFunctionJoinInfo->fAlias.push_back(alias); - fFunctionJoinInfo->fView.push_back(view); - fFunctionJoinInfo->fSchema.push_back(schema); - - return true; -} - - const string ExpressionStep::toString() const { ostringstream oss; diff --git a/dbcon/joblist/expressionstep.h b/dbcon/joblist/expressionstep.h index 0b909b78..2107695f 100644 --- a/dbcon/joblist/expressionstep.h +++ b/dbcon/joblist/expressionstep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: expressionstep.h 9632 2013-06-18 22:18:20Z xlou $ +// $Id: expressionstep.h 8526 2012-05-17 02:28:10Z xlou $ /** @file @@ -29,44 +29,51 @@ #include "jobstep.h" #include "filter.h" - -namespace execplan -{ -// forward reference -class ReturnedColumn; -class SimpleColumn; -class SimpleFilter; -class WindowFunctionColumn; -}; - - namespace joblist { struct JobInfo; -struct FunctionJoinInfo; class ExpressionStep : public JobStep { public: // constructors - ExpressionStep(const JobInfo&); + ExpressionStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId); + // destructor constructors virtual ~ExpressionStep(); // inherited methods void run(); void join(); - const std::string toString() const; + const JobStepAssociation& inputAssociation() const { return fInputJobStepAssociation; } + void inputAssociation(const JobStepAssociation& in) { fInputJobStepAssociation = in; } + const JobStepAssociation& outputAssociation() const { return fOutputJobStepAssociation; } + void outputAssociation(const JobStepAssociation& out) { fOutputJobStepAssociation = out; } + JobStepAssociation& outputAssociation() { return fOutputJobStepAssociation; } - execplan::CalpontSystemCatalog::OID oid() const { return 0; } + const std::string toString() const; + void stepId(uint16_t sId) { fStepId = sId; } + uint16_t stepId() const { return fStepId; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t verId() const { return fVerId; } + uint32_t statementId() const { return fStatementId; } + void logger(const SPJL& logger) { fLogger = logger; } + + execplan::CalpontSystemCatalog::OID oid() const + { return fOids.empty() ? 0 : fOids.front(); } execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOids.empty() ? 0 : fTableOids.front(); } std::string alias() const { return fAliases.empty() ? "" : fAliases.front(); } std::string view() const { return fViews.empty() ? "" : fViews.front(); } std::string schema() const { return fSchemas.empty() ? "" : fSchemas.front(); } - uint32_t tableKey() const { return fTableKeys.empty() ? -1 : fTableKeys.front(); } - uint32_t columnKey() const { return fColumnKeys.empty() ? -1 : fColumnKeys.front(); } + uint tableKey() const { return fTableKeys.empty() ? -1 : fTableKeys.front(); } + uint columnKey() const { return fColumnKeys.empty() ? -1 : fColumnKeys.front(); } void expression(const execplan::SRCP exp, JobInfo& jobInfo); execplan::SRCP expression() const { return fExpression; } @@ -79,25 +86,26 @@ class ExpressionStep : public JobStep uint64_t expressionId() const { return fExpressionId; } const std::vector& tableOids() const { return fTableOids; } + const std::vector& oids() const { return fOids; } const std::vector& aliases() const { return fAliases; } const std::vector& views() const { return fViews; } const std::vector& schemas() const { return fSchemas; } - const std::vector& tableKeys() const { return fTableKeys; } - const std::vector& columnKeys() const { return fColumnKeys; } + const std::vector& tableKeys() const { return fTableKeys; } + const std::vector& columnKeys() const { return fColumnKeys; } std::vector& tableOids() { return fTableOids; } + std::vector& oids() { return fOids; } std::vector& aliases() { return fAliases; } std::vector& views() { return fViews; } std::vector& schemas() { return fSchemas; } - std::vector& tableKeys() { return fTableKeys; } - std::vector& columnKeys() { return fColumnKeys; } + std::vector& tableKeys() { return fTableKeys; } + std::vector& columnKeys() { return fColumnKeys; } - virtual void updateInputIndex(std::map& indexMap, const JobInfo& jobInfo); - virtual void updateOutputIndex(std::map& indexMap, const JobInfo& jobInfo); + virtual void updateInputIndex(std::map& indexMap, const JobInfo& jobInfo); + virtual void updateOutputIndex(std::map& indexMap, const JobInfo& jobInfo); virtual void updateColumnOidAlias(JobInfo& jobInfo); std::vector& columns() { return fColumns; } - void substitute(uint64_t, const SSC&); void selectFilter(bool b) { fSelectFilter = b; } bool selectFilter() const { return fSelectFilter; } @@ -105,26 +113,18 @@ class ExpressionStep : public JobStep void associatedJoinId(uint64_t i) { fAssociatedJoinId = i; } uint64_t associatedJoinId() const { return fAssociatedJoinId; } - void functionJoin(bool b) { fDoJoin = b; } - bool functionJoin() const { return fDoJoin; } - - void virtualStep(bool b) { fVirtual = b; } - bool virtualStep() const { return fVirtual; } - - boost::shared_ptr& functionJoinInfo() { return fFunctionJoinInfo; } - void resetJoinInfo() { fFunctionJoinInfo.reset(); } - protected: virtual void addColumn(execplan::ReturnedColumn* rc, JobInfo& jobInfo); - virtual void addFilter(execplan::ParseTree* filter, JobInfo& jobInfo); - virtual void addSimpleFilter(execplan::SimpleFilter* sf, JobInfo& jobInfo); - virtual void populateColumnInfo(execplan::ReturnedColumn* rc, JobInfo& jobInfo); virtual void populateColumnInfo(execplan::SimpleColumn* sc, JobInfo& jobInfo); - virtual void populateColumnInfo(execplan::WindowFunctionColumn* wc, JobInfo& jobInfo); - virtual void populateColumnInfo(execplan::AggregateColumn* ac, JobInfo& jobInfo); - virtual void functionJoinCheck(execplan::SimpleFilter* sf, JobInfo& jobInfo); - virtual bool parseFuncJoinColumn(ReturnedColumn* rc, JobInfo& jobInfo); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; + SPJL fLogger; // expression execplan::SRCP fExpression; @@ -133,11 +133,12 @@ class ExpressionStep : public JobStep // columns accessed std::vector fTableOids; + std::vector fOids; std::vector fAliases; std::vector fViews; std::vector fSchemas; - std::vector fTableKeys; - std::vector fColumnKeys; + std::vector fTableKeys; + std::vector fColumnKeys; std::vector fColumns; private: @@ -148,20 +149,11 @@ class ExpressionStep : public JobStep // for VARBINARY, only support limited number of functions: like hex(), length(), etc. bool fVarBinOK; - // @bug 3780, for select filter + // @bug3780, for select filter bool fSelectFilter; // @bug 3037, outer join with additional comparison uint64_t fAssociatedJoinId; - - // @bug 4531, for window function in IN/EXISTS sub-query. - std::map fSubMap; - std::set fVsc; // for substitute wc with vsc - - // @bug 3683, function join - boost::shared_ptr fFunctionJoinInfo; - bool fDoJoin; - bool fVirtual; }; } diff --git a/dbcon/joblist/fifo-bench.cpp b/dbcon/joblist/fifo-bench.cpp new file mode 100644 index 00000000..3e521e79 --- /dev/null +++ b/dbcon/joblist/fifo-bench.cpp @@ -0,0 +1,592 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// $Id: fifo-bench.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +#include +#include +#include + +#include +// #include +#include +#include +#include "bytestream.h" + +#include "fifo.h" +#include "elementtype.h" + +using namespace std; +using namespace joblist; +using namespace messageqcpp; + +int64_t count = 100 * 1000 * 1000; +int maxElements = 50 * 1000; //max elements in memory at once for the benchmarks + +int fifoSize = 128; +int rowContainerSize = 8 * 1024; + +int cCount = 0; + +struct RowContainer +{ + int count; + ElementType *et; + + RowContainer(uint64_t rowsPerRowContainer):count(rowsPerRowContainer) + { + et = new ElementType[rowsPerRowContainer]; + } + + RowContainer(const RowContainer &rhs) + { + et = new ElementType[rhs.count]; + count = rhs.count; + memcpy(et, rhs.et, rhs.count * sizeof(ElementType)); + } + + RowContainer():count(::rowContainerSize) + { + et = new ElementType[::rowContainerSize]; + } + + RowContainer& operator = (const RowContainer &rhs) + { + if(this == &rhs) + return *this; + if(et != NULL) + { + delete [] et; + } + et = new ElementType[rhs.count]; + count = rhs.count; + memcpy(et, rhs.et, rhs.count * sizeof(ElementType)); + return *this; + } + + ~RowContainer() + { + delete [] et; + } +}; + +struct RowContainer2 +{ + int count; + ByteStream bs; + + RowContainer2(uint64_t rowsPerRowContainer):count(0) + { + } + + RowContainer2():count(0) + { + } + + ~RowContainer2() + { + } +}; + +class NearFIFO { + private: + int size; + ElementType *et; + int pindex, cindex; + + public: + NearFIFO() : size(::maxElements), pindex(0), cindex(0) + { + et = new ElementType[size]; + }; + + inline bool next(uint64_t it, ElementType *e) + { + // uint64_t it2 = it++; + + *e = et[cindex]; + + if ((++cindex) << 1 >= size) { + cindex = 0; + return false; + } + else + return true; + } + + inline void insert(const ElementType &e) + { + et[pindex] = e; + if (++pindex == size) + pindex = 0; + } + +}; + + +void timespec_sub(const struct timespec &tv1, const struct timespec &tv2, + struct timespec &diff) +{ + if (tv2.tv_nsec < tv1.tv_nsec) { + diff.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; + diff.tv_nsec = tv1.tv_nsec - tv2.tv_nsec; + } + else { + diff.tv_sec = tv2.tv_sec - tv1.tv_sec; + diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; + } +} + +void *FIFO_stress_consumer(void *arg) +{ + FIFO *f = reinterpret_cast *>(arg); + uint64_t it; + ElementType val; + bool ret; + int id = ++::cCount; + + cout << "consumer " << id << " started" << endl; + it = f->getIterator(); + // WWW+ + int blockCount = 0; + ByteStream bs; + // WWW- + while (1) { + ret = f->next(it, &val); + // WWW+ + bs << val.first; + blockCount++; + if(blockCount%1000 == 0) + { + bs.restart(); + } + // WWW- + + if (!ret) { + cout << "consumer " << id << " exiting" << endl; + return NULL; + } + } + return NULL; +} + + + void FIFO_stress(int threads) + { + int64_t i; + FIFO f(threads, ::maxElements); + pthread_t consumer[threads]; + ElementType val; + int err = 0; + + ::cCount = 0; + for (i = 0; i < threads; i++) + err = pthread_create(&consumer[i], NULL, FIFO_stress_consumer, &f); + if (err) + cout << "ERROR starting threads" << endl; +// for (i = 0; i < MAXINT64; i++) { + for (i = 0; i < ::count; i++) { +// if ((i % 1000000) == 0) +// cout << i << endl; + val.first = i; + val.second = i; + f.insert(val); + } + f.endOfInput(); + for (i = 0; i < threads; i++) + pthread_join(consumer[i], NULL); + } + +void *FIFO_stress_consumer_with_rowcontainers(void *arg) +{ + FIFO *f = reinterpret_cast *>(arg); + uint64_t it; + ElementType val; + RowContainer rc(::rowContainerSize); + bool ret; + int id = ++::cCount; + + it = f->getIterator(); + uint64_t rid = 0; + while (1) { + ret = f->next(it, &rc); + if (!ret) { + return NULL; + } + else + { + ByteStream bs; + + for(int i = 0; i < rc.count; i++) + { + if(i%1000 == 0) + bs.restart(); + bs << rc.et[i].first; + if(id == 1 && rc.et[i].first != rid) { + } + rid++; + } + } + } + return NULL; +} + + + void FIFO_stress_with_rowcontainers(int threads, int64_t fifoSize, int64_t rowsPerRowContainer) + { + int64_t i; + FIFO f(threads, fifoSize); + pthread_t consumer[threads]; + ElementType val; + int err = 0; + + ::cCount = 0; + for (i = 0; i < threads; i++) + err = pthread_create(&consumer[i], NULL, FIFO_stress_consumer_with_rowcontainers, &f); + if (err) + cout << "ERROR starting threads" << endl; + + RowContainer rw(rowsPerRowContainer); + int wrapperCount = 0; + int rwCount = 0; + for (i = 0; i < ::count; i++) { + val.first = i; + val.second = i; + rw.et[rwCount] = val; + rwCount++; + if(rwCount == rowsPerRowContainer) + { + rw.count = rwCount; + wrapperCount++; + rwCount = 0; + f.insert(rw); + } + } + f.endOfInput(); + for (i = 0; i < threads; i++) + pthread_join(consumer[i], NULL); + } + + +void *FIFO_stress_consumer_with_rowcontainers2(void *arg) +{ + FIFO *f = reinterpret_cast *>(arg); + uint64_t it; + ElementType val; + RowContainer2 rw; + bool ret; + ByteStream bs; + + it = f->getIterator(); + while (1) { + ret = f->next(it, &rw); + if (!ret) { + // cout << "consumer " << id << " exiting" << endl; + return NULL; + } + else + { + uint64_t i = 1; + bs << i; + bs += rw.bs; + bs.restart(); + } + } + return NULL; +} + + + void FIFO_stress_with_rowcontainers2(int threads, int64_t fifoSize, int64_t rowsPerRowContainer) + { + int64_t i; + // FIFO f(threads, ::maxElements); + FIFO f(threads, fifoSize); + pthread_t consumer[threads]; + ElementType val; + int err = 0; + + ::cCount = 0; + for (i = 0; i < threads; i++) + err = pthread_create(&consumer[i], NULL, FIFO_stress_consumer_with_rowcontainers2, &f); + if (err) + cout << "ERROR starting threads" << endl; +// for (i = 0; i < MAXINT64; i++) { + + RowContainer2 rw(rowsPerRowContainer); + int wrapperCount = 0; + int rwCount = 0; + ByteStream bs; + uint64_t j = 0; + for (i = 0; i < ::count; i++) { +// if ((i % 1000000) == 0) +// cout << i << endl; + val.first = i; + val.second = i; + rw.bs << j; + rwCount++; + if(rwCount == rowsPerRowContainer) + { + rw.count = wrapperCount; + wrapperCount++; + rwCount = 0; + f.insert(rw); + rw.bs.restart(); + } + } + f.endOfInput(); + for (i = 0; i < threads; i++) + pthread_join(consumer[i], NULL); + } + +void *bandwidth_consumer(void *arg) +{ + ElementType *f = reinterpret_cast(arg); + int64_t i; + int j; + ElementType val; + int id = ++::cCount; + + cout << "consumer " << id << " started" << endl; + for (i = 0, j = 0; i < ::count; i++) { + val = f[j++]; + if (j == ::maxElements) + j = 0; + } + cout << "consumer " << id << " exiting" << endl; + return NULL; + +} + +void bandwidth(int threads) +{ + int64_t i; + int j; + ElementType *f = new ElementType[::maxElements]; + pthread_t consumer[threads]; + ElementType val; + + ::cCount = 0; + + for (i = 0; i < threads; i++) + pthread_create(&consumer[i], NULL, bandwidth_consumer, f); + for (j = 0, i = 0; i < ::count; i++) { +// if ((i % 1000000) == 0) +// cout << i << endl; + val.first = i; + val.second = i; + f[j++] = val; + if (j == ::maxElements) + j = 0; + } + for (i = 0; i < threads; i++) + pthread_join(consumer[i], NULL); +} + + +void *bandwidth_nearfifo_consumer(void *arg) +{ + NearFIFO *nf = reinterpret_cast(arg); + int64_t i; + int j; + ElementType val; + int id = ++::cCount; + bool ret; + + cout << "consumer " << id << " started" << endl; + for (i = 0, j = 0; i < ::count; i++) { + ret = nf->next(i, &val); + if (ret) + continue; + } + cout << "consumer " << id << " exiting" << endl; + return NULL; + +} + +void bandwidth_nearfifo(int threads) +{ + int64_t i; + int j; + NearFIFO nf; + pthread_t consumer[threads]; + ElementType val; + + ::cCount = 0; + + for (i = 0; i < threads; i++) + pthread_create(&consumer[i], NULL, bandwidth_nearfifo_consumer, &nf); + for (j = 0, i = 0; i < ::count; i++) { +// if ((i % 1000000) == 0) +// cout << i << endl; + val.first = i; + val.second = i; + nf.insert(val); + } + for (i = 0; i < threads; i++) + pthread_join(consumer[i], NULL); +} + +ElementType *et; +int cindex = 0, pindex = 0, size = 50000; + +inline bool next(uint64_t it, ElementType *e) +{ + // uint64_t it2 = it++; + + *e = et[cindex]; + + if ((++cindex) << 1 >= size) { + cindex = 0; + return false; + } + else + return true; +} + +inline void insert(const ElementType &e) +{ + et[pindex] = e; + if (++pindex == size) + pindex = 0; +} + + +void *bandwidth_fcn_consumer(void *arg) +{ + int64_t i; + int j; + ElementType val; + int id = ++::cCount; + bool ret; + + cout << "consumer " << id << " started" << endl; + for (i = 0, j = 0; i < ::count; i++) { + ret = next(i, &val); + if (ret) + continue; + } + cout << "consumer " << id << " exiting" << endl; + return NULL; + +} + +void bandwidth_fcn(int threads) +{ + int64_t i; + int j; + NearFIFO nf; + pthread_t consumer[threads]; + ElementType val; + + ::cCount = 0; + + et = new ElementType[size]; + + for (i = 0; i < threads; i++) + pthread_create(&consumer[i], NULL, bandwidth_fcn_consumer, NULL); + for (j = 0, i = 0; i < ::count; i++) { +// if ((i % 1000000) == 0) +// cout << i << endl; + val.first = i; + val.second = i; + insert(val); + } + for (i = 0; i < threads; i++) + pthread_join(consumer[i], NULL); +} + +int main( int argc, char **argv) +{ + struct timespec ts1, ts2, diff; + + if (argc == 1) { + cout << "running with 1 consumer" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + FIFO_stress(1); + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count << " elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + cout << "running bandwidth check" << endl; + + clock_gettime(CLOCK_REALTIME, &ts1); + bandwidth(1); + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count << " elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + } + else { + cout << "running with " << argv[1] << " consumers" << endl; + cout << ::count/(1000*1000) << " million rows." << endl << endl; + cout << "running FIFO benchmark" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + FIFO_stress(atoi(argv[1])); + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count/1000/1000 << " million elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + + cout << "running FIFO benchmark with RowContainers" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + FIFO_stress_with_rowcontainers(atoi(argv[1]), ::fifoSize, ::rowContainerSize); // Consume up to 128 MB + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count/1000/1000 << " million elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + + cout << "running FIFO benchmark with RowContainers and bytestream" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + FIFO_stress_with_rowcontainers2(atoi(argv[1]), ::fifoSize, ::rowContainerSize); // Consume up to 128 MB + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count/1000/1000 << " million elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + +/* + cout << "running NearFIFO benchmark" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + bandwidth_nearfifo(atoi(argv[1])); + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count << " elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + + cout << "running shared array via fcns benchmark" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + bandwidth_fcn(atoi(argv[1])); + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count << " elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + +*/ + + cout << "running shared array benchmark" << endl; + clock_gettime(CLOCK_REALTIME, &ts1); + bandwidth(atoi(argv[1])); + clock_gettime(CLOCK_REALTIME, &ts2); + timespec_sub(ts1, ts2, diff); + cout << "passed " << ::count << " elements in " << + diff.tv_sec << "s " << diff.tv_nsec << "ns" << endl; + + } + + + return 0; +} + + diff --git a/dbcon/joblist/fifo.h b/dbcon/joblist/fifo.h index a6bd286d..6a1bea27 100644 --- a/dbcon/joblist/fifo.h +++ b/dbcon/joblist/fifo.h @@ -16,12 +16,12 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: fifo.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: fifo.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ -/** @file +/** @file * class XXX interface */ @@ -44,7 +44,7 @@ namespace joblist { /* This derives from DataListImpl > but it manages its own data */ template -class FIFO : public DataListImpl, element_t> +class FIFO : public DataListImpl, element_t> { private: typedef DataListImpl, element_t> base; @@ -55,7 +55,7 @@ class FIFO : public DataListImpl, element_t> RID_VALUE }; - FIFO(uint32_t numConsumers, uint32_t maxElements); + FIFO(uint numConsumers, uint maxElements); virtual ~FIFO(); /* DataList interface */ @@ -78,14 +78,14 @@ class FIFO : public DataListImpl, element_t> execplan::CalpontSystemCatalog::OID OID() const { return base::OID(); } inline void dropToken() { }; - inline void dropToken(uint32_t) { }; + inline void dropToken(uint) { }; // Counters that reflect how many many times this FIFO blocked on reads/writes uint64_t blockedWriteCount() const; uint64_t blockedReadCount() const; - + // @bug 653 set number of consumers when it is empty. - void setNumConsumers( uint32_t nc ); + void setNumConsumers( uint nc ); void inOrder(bool order) { fInOrder = order; } bool inOrder() const { return fInOrder; } @@ -106,17 +106,13 @@ class FIFO : public DataListImpl, element_t> // a FIFO is converted to another datalist, this enum should be copied // over to the datalist, as a ZDL for example can use the element mode // for other reasons. - void setElementMode(uint32_t mode) { fElementMode = mode; } - uint32_t getElementMode() const { return fElementMode; } + void setElementMode(uint mode) { fElementMode = mode; } + uint getElementMode() const { return fElementMode; } // Total number of files and filespace used for temp files void setTotalFileCounts(uint64_t numFiles, uint64_t numBytes); void totalFileCounts(uint64_t& numFiles, uint64_t& numBytes) const; - // returns true if there might be more data to read, - // false if there is no more data. Similar to next(), but - // does not return data. - bool more(uint64_t id); protected: private: @@ -133,10 +129,10 @@ class FIFO : public DataListImpl, element_t> bool fInOrder; uint64_t fConsumerFinishedCount; volatile bool fConsumptionStarted; - uint32_t fElementMode; + uint fElementMode; uint64_t fNumFiles; uint64_t fNumBytes; - + // Counters that reflect how many many times this FIFO blocked // on reads and writes due to the FIFO being empty or full. uint64_t blockedInsertWriteCount; @@ -149,17 +145,16 @@ class FIFO : public DataListImpl, element_t> void signalPs(); bool swapBuffers(bool waitIfBlocked=true); bool waitForSwap(uint64_t id); - }; // #define FIFO_DEBUG // toggles consumer behavior st it only has one critical section. -// Need to bench both ways before changing it. +// Need to bench both ways before changing it. // #define ONE_CS template -FIFO::FIFO(uint32_t con, uint32_t max) : DataListImpl, element_t>(con) +FIFO::FIFO(uint con, uint max) : DataListImpl, element_t>(con) { fMaxElements = max; pBuffer = 0; @@ -190,7 +185,7 @@ FIFO::FIFO() } template -FIFO::FIFO(const FIFO &f) +FIFO::FIFO(const FIFO &f) { throw std::logic_error("don't use FIFO(FIFO &)"); } @@ -305,7 +300,7 @@ bool FIFO::waitForSwap(uint64_t id) #ifdef ONE_CS if (cpos[id] == fMaxElements) - if (++cDone == base::numConsumers) + if (++cDone == base::numConsumers) finishedConsuming.notify_all() #endif while (cpos[id] == fMaxElements && !base::noMoreInput) { @@ -327,18 +322,11 @@ bool FIFO::waitForSwap(uint64_t id) return true; } -template -bool FIFO::more(uint64_t id) -{ - boost::mutex::scoped_lock scoped(base::mutex); - return !(cpos[id] == fMaxElements && base::noMoreInput); -} - template void FIFO::signalPs() { boost::mutex::scoped_lock scoped(base::mutex); - if (++cDone == base::numConsumers) + if (++cDone == base::numConsumers) finishedConsuming.notify_all(); } @@ -376,7 +364,7 @@ void FIFO::endOfInput() memset(cpos, 0, sizeof(*cpos) * base::numConsumers); } base::endOfInput(); - if (cWaiting) + if (cWaiting) moreData.notify_all(); } @@ -411,7 +399,7 @@ void FIFO::setMultipleProducers(bool b) //@bug 653 template -void FIFO::setNumConsumers( uint32_t nc ) +void FIFO::setNumConsumers( uint nc ) { delete [] cpos; base::setNumConsumers(nc); diff --git a/dbcon/joblist/filtercommand-jl.cpp b/dbcon/joblist/filtercommand-jl.cpp index 59a5b879..483d51b8 100644 --- a/dbcon/joblist/filtercommand-jl.cpp +++ b/dbcon/joblist/filtercommand-jl.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: filtercommand-jl.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: filtercommand-jl.cpp 8410 2012-03-22 12:57:23Z pleblanc $ * * ***********************************************************************/ @@ -42,7 +42,7 @@ FilterCommandJL::~FilterCommandJL() } -void FilterCommandJL::setLBID(uint64_t rid, uint32_t dbroot) +void FilterCommandJL::setLBID(uint64_t rid, uint dbroot) { } diff --git a/dbcon/joblist/filtercommand-jl.h b/dbcon/joblist/filtercommand-jl.h index 1e7bea82..0c2b078f 100644 --- a/dbcon/joblist/filtercommand-jl.h +++ b/dbcon/joblist/filtercommand-jl.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: filtercommand-jl.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: filtercommand-jl.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -39,7 +39,7 @@ class FilterCommandJL : public CommandJL FilterCommandJL(const FilterStep&); virtual ~FilterCommandJL(); - void setLBID(uint64_t rid, uint32_t dbroot); + void setLBID(uint64_t rid, uint dbroot); uint8_t getTableColumnType(); CommandType getCommandType(); std::string toString(); diff --git a/dbcon/joblist/filteroperation.cpp b/dbcon/joblist/filteroperation.cpp new file mode 100644 index 00000000..2175238b --- /dev/null +++ b/dbcon/joblist/filteroperation.cpp @@ -0,0 +1,304 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: filteroperation.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + *****************************************************************************/ + +#include "filteroperation.h" +#include "constantdatalist.h" +#include "iostream" +#include "timeset.h" + +using namespace std; +namespace joblist +{ + +template +void FilterOperation::filter(int8_t COP, FIFO >& dl1, + FIFO >& dl2, FIFO >& dlOut, uint64_t & resultCount, TimeSet& ts) +{ + + bool constantDL = false; + // Validate that if a ConstantDataList is being used that it's the second one passed in. + if(typeid(ConstantDataList) == typeid(dl1)) { + throw(std::runtime_error("FilterOperation::filter(): first DataList argument cannot be a ConstantDataList.")); + } + if(typeid(ConstantDataList) == typeid(dl2)) { + RowWrapper rw; + int id = dl2.getIterator(); + if(!dl2.next(id, &rw)) { + throw(std::runtime_error("FilterOperation::filter(): ConstantDataList passed does not contain any values.")); + } + constantDL = true; + + } + + // Iterate over the data lists, perform the comparison, and load the output datalist with the qualifying + // RIDs and values. + RowWrapper rw1, rw2, rw3; + int id1, id2; + id1 = dl1.getIterator(); + id2 = dl2.getIterator(); + ts.setTimer(filterCompare); + if(constantDL) { + dl2.next(id2, &rw2); + typename element_t::second_type c = rw2.et[0].second; + while(dl1.next(id1, &rw1)) { + for (uint64_t i = 0; i < rw1.count; ++i) { + if(compare(COP, rw1.et[i].second, c)) { + resultCount++; + rw3.et[rw3.count++] = rw1.et[i]; + if (rw3.count == rw3.ElementsPerGroup) { + ts.setTimer(filterInsert); + dlOut.insert(rw3); + rw3.count = 0; + ts.holdTimer(filterInsert); + } + } + } + } + dlOut.endOfInput(); + dlOut.totalSize(resultCount); + ts.setTimer(filterCompare, false); + } + else { + bool more1 = dl1.next(id1, &rw1); + bool more2 = dl2.next(id2, &rw2); + uint64_t i=0, j=0; + + while(more1 && more2) { + while (i < rw1.count && j < rw2.count) { + + //cout << "IN1: " << rw1.et[i].first << " : " << rw1.et[i].second << " IN2: " << rw2.et[i].first << " : " < rw2.et[j].first) { + ++j; + } + else if (rw1.et[i].first < rw2.et[j].first) { + ++i; + } + else { + if(compare(COP, rw1.et[i].second, rw2.et[j].second)) { + resultCount++; + rw3.et[rw3.count++] = rw1.et[i]; + if (rw3.count == rw3.ElementsPerGroup) { + ts.setTimer(filterInsert); + dlOut.insert(rw3); + rw3.count = 0; + ts.holdTimer(filterInsert); + } + } + ++i; + ++j; + } + } + + if(i == rw1.count) { + more1 = dl1.next(id1, &rw1); + i = 0; + } + if(j == rw2.count) { + more2 = dl2.next(id2, &rw2); + j = 0; + } + } + + if (rw3.count > 0) + { + dlOut.insert(rw3); + } + ts.setTimer(filterCompare, false); + + dlOut.endOfInput(); + dlOut.totalSize(resultCount); + + ts.setTimer(filterFinish); + while ( more1 ) + { + more1 = dl1.next(id1, &rw1); + } + while ( more2 ) + { + more2 = dl2.next(id2, &rw2); + } + ts.setTimer(filterFinish, false); + } + +} + + +template +void FilterOperation::filter(int8_t COP, FIFO >& dl1, + FIFO >& dl2, DataList& dlOut, uint64_t & resultCount, TimeSet& ts) +{ + + bool constantDL = false; + int ridcount = 0; + // Validate that if a ConstantDataList is being used that it's the second one passed in. + if(typeid(ConstantDataList) == typeid(dl1)) { + throw(std::runtime_error("FilterOperation::filter(): first DataList argument cannot be a ConstantDataList.")); + } + if(typeid(ConstantDataList) == typeid(dl2)) { + RowWrapper rw; + int id = dl2.getIterator(); + if(!dl2.next(id, &rw)) { + throw(std::runtime_error("FilterOperation::filter(): ConstantDataList passed does not contain any values.")); + } + constantDL = true; + + } + + // Iterate over the data lists, perform the comparison, and load the output datalist with the qualifying + // RIDs and values. + RowWrapper rw1, rw2; + int id1, id2; + id1 = dl1.getIterator(); + id2 = dl2.getIterator(); + + ts.setTimer(filterCompare); + if(constantDL) { + dl2.next(id2, &rw2); + typename element_t::second_type c = rw2.et[0].second; + while(dl1.next(id1, &rw1)) { + for (uint64_t i = 0; i < rw1.count; ++i) { + if(compare(COP, rw1.et[i].second, c)) { + resultCount++; + dlOut.insert(rw1.et[i]); + } + } + } + dlOut.endOfInput(); + ts.setTimer(filterCompare, false); + } + else { + bool more1 = dl1.next(id1, &rw1); + bool more2 = dl2.next(id2, &rw2); + uint64_t i=0, j=0; + + while(more1 && more2) { + while (i < rw1.count && j < rw2.count) { + if(rw1.et[i].first > rw2.et[j].first) { + ++j; + } + else if (rw1.et[i].first < rw2.et[j].first) { + ++i; + } + else { + if(compare(COP, rw1.et[i].second, rw2.et[j].second)) { + resultCount++; + dlOut.insert(rw1.et[i]); + ridcount++; + } + ++i; + ++j; + } + } + + if(i == rw1.count) { + more1 = dl1.next(id1, &rw1); + i = 0; + } + if(j == rw2.count) { + more2 = dl2.next(id2, &rw2); + j = 0; + } + } + dlOut.endOfInput(); + ts.setTimer(filterCompare, false); + + ts.setTimer(filterFinish); + while ( more1 ) + { + more1 = dl1.next(id1, &rw1); + } + while ( more2 ) + { + more2 = dl2.next(id2, &rw2); + } + ts.setTimer(filterFinish, false); + } +} + + + +template +bool FilterOperation::compare(const int8_t COP, const datavalue_t& v1, const datavalue_t& v2) { + switch(COP) { + case COMPARE_GT: + return v1 > v2; + break; + case COMPARE_LT: + return v1 < v2; + break; + case COMPARE_EQ: + return v1 == v2; + break; + case COMPARE_GE: + return v1 >= v2; + break; + case COMPARE_LE: + return v1 <= v2; + break; + case COMPARE_NE: + return v1 != v2; + break; + default: + return false; + break; + } +} + + +template void FilterOperation::filter(int8_t COP, + FIFO >& dl1, + FIFO >& dl2, + FIFO >& dlOut, + uint64_t & resultCount, TimeSet& ts ); + +template void FilterOperation::filter(int8_t COP, + FIFO >& dl1, + FIFO >& dl2, + DataList& dlOut, + uint64_t & resultCount, TimeSet& ts); + +template void FilterOperation::filter(int8_t COP, + FIFO >& dl1, + FIFO >& dl2, + FIFO >& dlOut, + uint64_t & resultCount, TimeSet& ts); + +template void FilterOperation::filter(int8_t COP, + FIFO >& dl1, + FIFO >& dl2, + DataList& dlOut, + uint64_t & resultCount, TimeSet& ts); + +template void FilterOperation::filter(int8_t COP, + FIFO >& dl1, + FIFO >& dl2, + FIFO >& dlOut, + uint64_t & resultCount, TimeSet& ts); + +template void FilterOperation::filter(int8_t COP, + FIFO >& dl1, + FIFO >& dl2, + DataList& dlOut, + uint64_t & resultCount, TimeSet& ts); + +} // namespace + diff --git a/dbcon/joblist/filteroperation.h b/dbcon/joblist/filteroperation.h new file mode 100644 index 00000000..c124b559 --- /dev/null +++ b/dbcon/joblist/filteroperation.h @@ -0,0 +1,93 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: filteroperation.h 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ +/** @file */ + +#ifndef _FILTEROPERATION_H_ +#define _FILTEROPERATION_H_ + +#include +#include "datalist.h" +#include "elementtype.h" +#include "primitivemsg.h" +#include + +namespace joblist +{ + +/** @brief filters a data list based on a comparison with a constant or another data list. + * + * Class FilterOperation is used to compare values from a DataList to values in another DataList and produce + * a new DataList with the qualifying RIDS. + * + * Notes: + * The data lists must contain values with common RIDs unless the second data list passed in is a ConstantDataList. + * + * The RIDs must be from the same table and must be in the same order. The input data lists do not have to have the + * same number of rows, but they must be in RID order. + * + * The original input data lists are not changed. + * + * The new data list produced will be a subset of the first data list passed in containing the rows that qualified. + * + * If comparing with a constant, the second data list passed in should be a ConstantDataList containing one row + * with the constant value. An exception will be thrown if a ConstantDataList is passed as the first datalist. + */ + +class TimeSet; + const std::string filterCompare("Filter Op compare time: "); + const std::string filterInsert("Filter insert time: "); + const std::string filterFinish("Filter finish time: "); + +class FilterOperation +{ +public: + + // Defaults okay for constructor and destructor. + + + /** @brief compares the first data list to the second datalist based on the operator and produces third datalist. + * + * @param fe the comparison operator. + * @param dl1 the data list containing values used for the left hand side. + * @param dl2 the data list containing values used for the right hand side of the comparison. + * @param dlOut the data list will be returned with a subset of dl1 containing the qualifying rows. + */ + template + void filter(int8_t COP, FIFO >& dl1, FIFO >& dl2, + FIFO >& dlOut, uint64_t & resultCount, TimeSet& ts); + + template + void filter(int8_t COP, FIFO >& dl1, FIFO >& dl2, + DataList& dlOut, uint64_t & resultCount, TimeSet& ts); + +private: + template + bool compare(const int8_t COP, const datavalue_t& v1, const datavalue_t& v2); + + // defaults okay + //FilterOperation(const FilterOperation& rhs); + //FilterOperation& operator=(const FilterOperation& rhs); +}; + +} // namespace +#endif diff --git a/dbcon/joblist/filterstep.cpp b/dbcon/joblist/filterstep.cpp index 8e236ec1..e8743748 100644 --- a/dbcon/joblist/filterstep.cpp +++ b/dbcon/joblist/filterstep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: filterstep.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: filterstep.cpp 8526 2012-05-17 02:28:10Z xlou $ #include #include @@ -60,13 +60,17 @@ namespace joblist // } // } //}; - -FilterStep::FilterStep( - const execplan::CalpontSystemCatalog::ColType& colType, - const JobInfo& jobInfo) : - JobStep(jobInfo), - fTableOID(0), - fColType(colType) + +FilterStep::FilterStep(uint32_t sessionId, + uint32_t txnId, + uint32_t statementId, + execplan::CalpontSystemCatalog::ColType colType) : + fSessionId(sessionId), + fTxnId(txnId), + fStepId(0), + fStatementId(statementId), + fTableOID(0), + fColType(colType) { } @@ -104,12 +108,12 @@ void FilterStep::doFilter() // StringFifoDataList* fStrFBp = 0; // StringFifoDataList* strFifo = 0; // StrDataList* strResult = 0; -// +// // FifoDataList* fFBP = 0; // FifoDataList* fFAP = 0; // FifoDataList* fifo = 0; // DataList_t* result = 0; -// +// // TimeSet timer; //try //{ @@ -119,20 +123,20 @@ void FilterStep::doFilter() // { // fStrFAp = fInputJobStepAssociation.outAt(0)->stringDL(); // idbassert(fStrFAp); -// +// // fStrFBp = fInputJobStepAssociation.outAt(1)->stringDL(); // idbassert(fStrFBp); -// +// // strFifo = fOutputJobStepAssociation.outAt(0)->stringDL(); -// +// // strResult = fOutputJobStepAssociation.outAt(0)->stringDataList(); // } // else -// { +// { // fFBP = fInputJobStepAssociation.outAt(1)->fifoDL(); // idbassert(fFBP); // fifo = fOutputJobStepAssociation.outAt(0)->fifoDL(); -// +// // result = fOutputJobStepAssociation.outAt(0)->dataList(); // } // ostringstream ss; //tester @@ -143,9 +147,13 @@ void FilterStep::doFilter() // { // dlTimes.setFirstReadTime(); // } -// uint32_t cop = BOP(); -// -// if (0 == status()) +// uint cop = BOP(); +// +// if (0 < fInputJobStepAssociation.status()) +// { +// fOutputJobStepAssociation.status(fInputJobStepAssociation.status()); +// } +// else // { // FilterOperation filterOP; // if ( !fFAP ) @@ -170,25 +178,25 @@ void FilterStep::doFilter() // filterOP.filter( cop, *fFAP, *fFBP, *result,resultCount, timer ); // } // } -// } // status() == 0 +// } //else fInputJobStepAssociation.status() == 0 //}//try -//catch (std::exception &e) +//catch (std::exception &e) //{ // std::cout << "FilterStep caught: " << e.what() << std::endl; // unblockDataLists(fifo, strFifo, strResult, result); // catchHandler(e.what()); -// status(logging::filterStepErr); +// fOutputJobStepAssociation.status(logging::filterStepErr); //} -//catch (...) +//catch (...) //{ // string msg("FSRunner caught something not an exception!"); // std::cout << msg << std::endl; // unblockDataLists(fifo, strFifo, strResult, result); // catchHandler(msg); -// status(logging::filterStepErr); +// fOutputJobStepAssociation.status(logging::filterStepErr); //} // -// +// // if (fTableOID >= 3000) // dlTimes.setEndOfInputTime(); // //...Print job step completion information @@ -198,7 +206,7 @@ void FilterStep::doFilter() // char finTimeString[50]; // ctime_r(&finTime, finTimeString); // finTimeString[strlen(finTimeString)-1 ] = '\0'; -// +// // ostringstream logStr; // logStr << "ses:" << fSessionId << " st: " << fStepId << // " finished at " << finTimeString << @@ -206,18 +214,18 @@ void FilterStep::doFilter() // "; EOI " << dlTimes.EndOfInputTimeString() // <<"; Output:"< @@ -48,10 +48,9 @@ using namespace rowgroup; #include "dataconvert.h" using namespace dataconvert; +#define GROUPCONCAT_DLLEXPORT #include "groupconcat.h" - -#include "idborderby.h" -using namespace ordering; +#undef GROUPCONCAT_DLLEXPORT #include "jobstep.h" #include "jlf_common.h" @@ -85,7 +84,6 @@ void GroupConcatInfo::prepGroupConcat(JobInfo& jobInfo) groupConcat->fDistinct = gcc->distinct(); groupConcat->fSize = gcc->resultType().colWidth; groupConcat->fRm = &(jobInfo.rm); - groupConcat->fSessionMemLimit = jobInfo.umMemLimit; int key = -1; const vector& cols = rcp->columnVec(); @@ -146,7 +144,7 @@ void GroupConcatInfo::prepGroupConcat(JobInfo& jobInfo) } -uint32_t GroupConcatInfo::getColumnKey(const SRCP& srcp, JobInfo& jobInfo) +uint GroupConcatInfo::getColumnKey(const SRCP& srcp, JobInfo& jobInfo) { int colKey = -1; const SimpleColumn* sc = dynamic_cast(srcp.get()); @@ -189,25 +187,25 @@ uint32_t GroupConcatInfo::getColumnKey(const SRCP& srcp, JobInfo& jobInfo) void GroupConcatInfo::mapColumns(const RowGroup& projRG) { - map projColumnMap; - const vector& keysProj = projRG.getKeys(); + map projColumnMap; + const vector& keysProj = projRG.getKeys(); for (uint64_t i = 0; i < projRG.getColumnCount(); i++) projColumnMap[keysProj[i]] = i; for (vector::iterator k = fGroupConcat.begin(); k!= fGroupConcat.end(); k++) { - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); - vector >::iterator i1 = (*k)->fGroupCols.begin(); + vector >::iterator i1 = (*k)->fGroupCols.begin(); while (i1 != (*k)->fGroupCols.end()) { - map::iterator j = projColumnMap.find(i1->first); + map::iterator j = projColumnMap.find(i1->first); if(j == projColumnMap.end()) { cerr << "Concat Key:" << i1->first << " is not projected." << endl; @@ -224,17 +222,17 @@ void GroupConcatInfo::mapColumns(const RowGroup& projRG) i1++; } - vector >::iterator i2 = (*k)->fOrderCols.begin(); + vector >::iterator i2 = (*k)->fOrderCols.begin(); while (i2 != (*k)->fOrderCols.end()) { - map::iterator j = projColumnMap.find(i2->first); + map::iterator j = projColumnMap.find(i2->first); if(j == projColumnMap.end()) { cerr << "Order Key:" << i2->first << " is not projected." << endl; throw runtime_error("Project error."); } - vector::iterator i3 = find(keys.begin(), keys.end(), j->first); + vector::iterator i3 = find(keys.begin(), keys.end(), j->first); int idx = 0; if (i3 == keys.end()) { @@ -257,7 +255,7 @@ void GroupConcatInfo::mapColumns(const RowGroup& projRG) i2++; } - (*k)->fRowGroup = RowGroup(oids.size(), pos, oids, keys, types, scale, precision, projRG.getStringTableThreshold(), false); + (*k)->fRowGroup = RowGroup(oids.size(), pos, oids, keys, types, scale, precision); (*k)->fMapping = makeMapping(projRG, (*k)->fRowGroup); } } @@ -265,7 +263,6 @@ void GroupConcatInfo::mapColumns(const RowGroup& projRG) shared_array GroupConcatInfo::makeMapping(const RowGroup& in, const RowGroup& out) { - // For some reason using the rowgroup mapping fcns don't work completely right in this class shared_array mapping(new int[out.getColumnCount()]); for (uint64_t i = 0; i < out.getColumnCount(); i++) @@ -313,7 +310,7 @@ void GroupConcatAgUM::initialize() fConcator->initialize(fGroupConcat); - fGroupConcat->fRowGroup.initRow(&fRow, true); + fGroupConcat->fRowGroup.initRow(&fRow); fData.reset(new uint8_t[fRow.getSize()]); fRow.setData(fData.get()); } @@ -342,22 +339,16 @@ void GroupConcatAgUM::getResult(uint8_t* buff) fConcator->getResult(buff, fGroupConcat->fSeparator); } -uint8_t * GroupConcatAgUM::getResult() -{ - return fConcator->getResult(fGroupConcat->fSeparator); -} - void GroupConcatAgUM::applyMapping(const boost::shared_array& mapping, const Row& row) { - // For some reason the rowgroup mapping fcns don't work right in this class. for (uint64_t i = 0; i < fRow.getColumnCount(); i++) { - if (fRow.getColumnWidth(i) > 8 && + if (fRow.getColumnWidth(i) > 7 && (fRow.getColTypes()[i] == execplan::CalpontSystemCatalog::CHAR || fRow.getColTypes()[i] == execplan::CalpontSystemCatalog::VARCHAR)) { - fRow.setStringField(row.getStringPointer(mapping[i]), row.getStringLength(mapping[i]), i); + fRow.setStringField(row.getStringField(mapping[i]), i); } else { @@ -382,10 +373,6 @@ void GroupConcator::initialize(const rowgroup::SP_GroupConcat& gcc) { fGroupConcatLen = gcc->fSize; fCurrentLength -= strlen(gcc->fSeparator.c_str()); - - fOutputString.reset(new uint8_t[fGroupConcatLen+2]); - memset(fOutputString.get(), 0, fGroupConcatLen+2); - fConstCols = gcc->fConstCols; fConstantLen = strlen(gcc->fSeparator.c_str()); for (uint64_t i = 0; i < fConstCols.size(); i++) @@ -397,7 +384,7 @@ void GroupConcator::outputRow(std::ostringstream& oss, const rowgroup::Row& row) { const CalpontSystemCatalog::ColDataType* types = row.getColTypes(); vector::iterator i = fConcatColumns.begin(); - vector >::iterator j = fConstCols.begin(); + vector >::iterator j = fConstCols.begin(); uint64_t groupColCount = fConcatColumns.size() + fConstCols.size(); @@ -418,7 +405,6 @@ void GroupConcator::outputRow(std::ostringstream& oss, const rowgroup::Row& row) case CalpontSystemCatalog::INT: case CalpontSystemCatalog::BIGINT: case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { int64_t intVal = row.getIntField(*i); int scale = (int) row.getScale(*i); @@ -433,40 +419,18 @@ void GroupConcator::outputRow(std::ostringstream& oss, const rowgroup::Row& row) } break; } - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - { - uint64_t uintVal = row.getUintField(*i); - int scale = (int) row.getScale(*i); - if (scale == 0) - { - oss << uintVal; - } - else - { - long double dblVal = uintVal / pow(10.0, (double)scale); - oss << fixed << setprecision(scale) << dblVal; - } - break; - } - case CalpontSystemCatalog::CHAR: + case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: { oss << row.getStringField(*i).c_str(); - //oss << row.getStringField(*i); break; } case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { oss << setprecision(15) << row.getDoubleField(*i); break; } case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { oss << row.getFloatField(*i); break; @@ -535,19 +499,7 @@ int64_t GroupConcator::lengthEstimate(const rowgroup::Row& row) fieldLen += 1; break; } - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - { - uint64_t v = row.getUintField(*i); - while ((v /=10) != 0) fieldLen++; - fieldLen += 1; - break; - } case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { int64_t v = row.getIntField(*i); double scale = row.getScale(*i); @@ -569,19 +521,13 @@ int64_t GroupConcator::lengthEstimate(const rowgroup::Row& row) case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: { - int64_t colWidth = row.getStringLength(*i); - fieldLen += colWidth; // getStringLength() does the same thing as below - //assert(!row.usesStringTable()); - //int64_t colWidth = row.getColumnWidth(*i); - //uint8_t* pStr = row.getData() + row.getOffset(*i); - //while ((*pStr++ > 0) && (fieldLen < colWidth)) - // fieldLen++; + int64_t colWidth = row.getColumnWidth(*i); + uint8_t* pStr = row.getData() + row.getOffset(*i); + fieldLen = strnlen((char *) pStr, colWidth); break; } case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: + case CalpontSystemCatalog::FLOAT: { fieldLen = 1; // minimum length break; @@ -615,7 +561,7 @@ const string GroupConcator::toString() const oss << "GroupConcat size-" << fGroupConcatLen; oss << "Concat cols: "; vector::const_iterator i = fConcatColumns.begin(); - vector >::const_iterator j = fConstCols.begin(); + vector >::const_iterator j = fConstCols.begin(); uint64_t groupColCount = fConcatColumns.size() + fConstCols.size(); for (uint64_t k = 0; k < groupColCount; k++) { @@ -639,7 +585,7 @@ const string GroupConcator::toString() const // GroupConcatOrderBy class implementation GroupConcatOrderBy::GroupConcatOrderBy() { - fRule.fIdbCompare = this; + fRule.fOrderBy = this; } @@ -652,17 +598,13 @@ void GroupConcatOrderBy::initialize(const rowgroup::SP_GroupConcat& gcc) { GroupConcator::initialize(gcc); - fOrderByCond.resize(0); - for (uint64_t i = 0; i < gcc->fOrderCond.size(); i++) - fOrderByCond.push_back(IdbSortSpec(gcc->fOrderCond[i].first, gcc->fOrderCond[i].second)); - + fOrderByCond = gcc->fOrderCond; fDistinct = gcc->fDistinct; fRowsPerRG = 128; fErrorCode = ERR_AGGREGATION_TOO_BIG; fRm = gcc->fRm; - fSessionMemLimit = gcc->fSessionMemLimit; - vector >::iterator i = gcc->fGroupCols.begin(); + vector >::iterator i = gcc->fGroupCols.begin(); while (i != gcc->fGroupCols.end()) fConcatColumns.push_back((*(i++)).second); @@ -673,15 +615,14 @@ void GroupConcatOrderBy::initialize(const rowgroup::SP_GroupConcat& gcc) uint64_t GroupConcatOrderBy::getKeyLength() const { // only distinct the concatenated columns - //return (fRow0.getOffset(fConcatColumns.size()) - 2); - return fConcatColumns.size()-1; // cols 0 to fConcatColumns will be conpared + return (fRow0.getOffset(fConcatColumns.size()) - 2); } void GroupConcatOrderBy::processRow(const rowgroup::Row& row) { // check if this is a distinct row - if (fDistinct && fDistinctMap->find(row.getPointer()) != fDistinctMap->end()) + if (fDistinct && fDistinctMap->find(row.getData() + 2) != fDistinctMap->end()) return; // this row is skipped if any concatenated column is null. @@ -691,19 +632,17 @@ void GroupConcatOrderBy::processRow(const rowgroup::Row& row) // if the row count is less than the limit if (fCurrentLength < fGroupConcatLen) { - copyRow(row, &fRow0); - //cout << "length < GB limit: " << fRow0.toString() << endl; - //memcpy(fRow0.getData(), row.getData(), row.getSize()); + memcpy(fRow0.getData(), row.getData(), row.getSize()); // the RID is no meaning here, use it to store the estimated length. int16_t estLen = lengthEstimate(fRow0); - fRow0.setRid(estLen); + *((int16_t*)(fRow0.getData())) = estLen; OrderByRow newRow(fRow0, fRule); fOrderByQueue.push(newRow); fCurrentLength += estLen; // add to the distinct map if (fDistinct) - fDistinctMap->insert(fRow0.getPointer()); + fDistinctMap->insert(make_pair((fRow0.getData()+2), fRow0.getData())); fRowGroup.incRowCount(); fRow0.nextRow(); @@ -713,7 +652,7 @@ void GroupConcatOrderBy::processRow(const rowgroup::Row& row) fDataQueue.push(fData); uint64_t newSize = fRowsPerRG * fRowGroup.getRowSize(); - if (!fRm->getMemory(newSize, fSessionMemLimit)) + if (!fRm->getMemory(newSize)) { cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) << " @" << __FILE__ << ":" << __LINE__; @@ -721,34 +660,33 @@ void GroupConcatOrderBy::processRow(const rowgroup::Row& row) } fMemSize += newSize; - fData.reinit(fRowGroup, fRowsPerRG); - fRowGroup.setData(&fData); + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); fRowGroup.resetRowGroup(0); fRowGroup.getRow(0, &fRow0); } } - else if (fOrderByCond.size() > 0 && fRule.less(row.getPointer(), fOrderByQueue.top().fData)) + else if (fOrderByCond.size() > 0 && fRule.less(row.getData(), fOrderByQueue.top().fData)) { OrderByRow swapRow = fOrderByQueue.top(); fRow1.setData(swapRow.fData); - fCurrentLength -= fRow1.getRelRid(); - fRow2.setData(swapRow.fData); + fCurrentLength -= *((int16_t*)(fRow1.getData())); if (!fDistinct) { - copyRow(row, &fRow1); + memcpy(swapRow.fData, row.getData(), row.getSize()); } else { - // only the copyRow does useful work here - fDistinctMap->erase(swapRow.fData); - copyRow(row, &fRow2); - fDistinctMap->insert(swapRow.fData); + fDistinctMap->erase(fDistinctMap->find(swapRow.fData + 2)); + memcpy(swapRow.fData, row.getData(), row.getSize()); + fDistinctMap->insert(make_pair((swapRow.fData+2), swapRow.fData)); } + fRow2.setData(swapRow.fData); int16_t estLen = lengthEstimate(fRow2); - fRow2.setRid(estLen); + *((int16_t*)(fRow2.getData())) = estLen; fCurrentLength += estLen; fOrderByQueue.pop(); @@ -763,9 +701,9 @@ void GroupConcatOrderBy::merge(GroupConcator* gc) while (go->fOrderByQueue.empty() == false) { const OrderByRow& row = go->fOrderByQueue.top(); - + // check if the distinct row already exists - if (fDistinct && fDistinctMap->find(row.fData) != fDistinctMap->end()) + if (fDistinct && fDistinctMap->find(row.fData + 2) != fDistinctMap->end()) { ; // no op; } @@ -774,31 +712,25 @@ void GroupConcatOrderBy::merge(GroupConcator* gc) else if (fCurrentLength < fGroupConcatLen) { fOrderByQueue.push(row); - row1.setData(row.fData); - fCurrentLength += row1.getRelRid(); + fCurrentLength += *((int16_t*)row.fData); // add to the distinct map if (fDistinct) - fDistinctMap->insert(row.fData); - //fDistinctMap->insert(make_pair((row.fData+2), row.fData)); + fDistinctMap->insert(make_pair((row.fData+2), row.fData)); } else if (fOrderByCond.size() > 0 && fRule.less(row.fData, fOrderByQueue.top().fData)) { OrderByRow swapRow = fOrderByQueue.top(); - row1.setData(swapRow.fData); - fCurrentLength -= row1.getRelRid(); + fCurrentLength -= *((int16_t*)(swapRow.fData)); if (fDistinct) { - fDistinctMap->erase(swapRow.fData); - fDistinctMap->insert(row.fData); - //fDistinctMap->erase(fDistinctMap->find(swapRow.fData + 2)); - //fDistinctMap->insert(make_pair((row.fData+2), row.fData)); + fDistinctMap->erase(fDistinctMap->find(swapRow.fData + 2)); + fDistinctMap->insert(make_pair((row.fData+2), row.fData)); } - row1.setData(row.fData); - fCurrentLength += row1.getRelRid(); + fCurrentLength += *((int16_t*)row.fData); fOrderByQueue.pop(); fOrderByQueue.push(row); @@ -809,9 +741,8 @@ void GroupConcatOrderBy::merge(GroupConcator* gc) } -void GroupConcatOrderBy::getResult(uint8_t* buff, const string &sep) +void GroupConcatOrderBy::getResult(uint8_t* buff, string sep) { -#if 1 ostringstream oss; bool addSep = false; @@ -837,32 +768,8 @@ void GroupConcatOrderBy::getResult(uint8_t* buff, const string &sep) } strncpy((char*) buff, oss.str().c_str(), fGroupConcatLen); -#else - ostringstream oss; - bool addSep = false; - priority_queue::reverse_iterator rit; - - for (rit = fOrderByQueue.rbegin(); rit != fOrderByQueue.rend(); ++rit) { - if (addSep) - oss << sep; - else - addSep = true; - - const OrderByRow &topRow = *rit; - fRow0.setData(topRow.fData); - outputRow(oss, fRow0); - } - fOrderByQueue.clear(); - - strncpy((char *) buff, oss.str().c_str(), fGroupConcatLen); -#endif } -uint8_t * GroupConcator::getResult(const string &sep) -{ - getResult(fOutputString.get(), sep); - return fOutputString.get(); -} const string GroupConcatOrderBy::toString() const { @@ -870,11 +777,9 @@ const string GroupConcatOrderBy::toString() const ostringstream oss; oss << "OrderBy cols: "; - vector::const_iterator i = fOrderByCond.begin(); + vector >::const_iterator i = fOrderByCond.begin(); for (; i != fOrderByCond.end(); i++) - oss << "(" << i->fIndex << "," - << ((i->fAsc)?"Asc":"Desc") << "," - << ((i->fNf)?"null first":"null last") << ") "; + oss << "(" << i->first << "," << ((i->second)?1:-1) << ") "; if (fDistinct) oss << endl << " distinct"; oss << endl; @@ -893,7 +798,7 @@ GroupConcatNoOrder::GroupConcatNoOrder() : GroupConcatNoOrder::~GroupConcatNoOrder() { if (fRm) - fRm->returnMemory(fMemSize, fSessionMemLimit); + fRm->returnMemory(fMemSize); } @@ -905,14 +810,13 @@ void GroupConcatNoOrder::initialize(const rowgroup::SP_GroupConcat& gcc) fRowsPerRG = 128; fErrorCode = ERR_AGGREGATION_TOO_BIG; fRm = gcc->fRm; - fSessionMemLimit = gcc->fSessionMemLimit; - vector >::iterator i = gcc->fGroupCols.begin(); + vector >::iterator i = gcc->fGroupCols.begin(); while (i != gcc->fGroupCols.end()) fConcatColumns.push_back((*(i++)).second); uint64_t newSize = fRowsPerRG * fRowGroup.getRowSize(); - if (!fRm->getMemory(newSize, fSessionMemLimit)) + if (!fRm->getMemory(newSize)) { cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) << " @" << __FILE__ << ":" << __LINE__; @@ -920,9 +824,8 @@ void GroupConcatNoOrder::initialize(const rowgroup::SP_GroupConcat& gcc) } fMemSize += newSize; - //fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); - fData.reinit(fRowGroup, fRowsPerRG); - fRowGroup.setData(&fData); + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); fRowGroup.resetRowGroup(0); fRowGroup.initRow(&fRow); fRowGroup.getRow(0, &fRow); @@ -934,12 +837,11 @@ void GroupConcatNoOrder::processRow(const rowgroup::Row& row) // if the row count is less than the limit if (fCurrentLength < fGroupConcatLen && concatColIsNull(row) == false) { - copyRow(row, &fRow); - //memcpy(fRow.getData(), row.getData(), row.getSize()); + memcpy(fRow.getData(), row.getData(), row.getSize()); // the RID is no meaning here, use it to store the estimated length. int16_t estLen = lengthEstimate(fRow); - fRow.setRid(estLen); + *((int16_t*)(fRow.getData())) = estLen; fCurrentLength += estLen; fRowGroup.incRowCount(); fRow.nextRow(); @@ -948,7 +850,7 @@ void GroupConcatNoOrder::processRow(const rowgroup::Row& row) { uint64_t newSize = fRowsPerRG * fRowGroup.getRowSize(); - if (!fRm->getMemory(newSize, fSessionMemLimit)) + if (!fRm->getMemory(newSize)) { cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) << " @" << __FILE__ << ":" << __LINE__; @@ -957,9 +859,8 @@ void GroupConcatNoOrder::processRow(const rowgroup::Row& row) fMemSize += newSize; fDataQueue.push(fData); - fData.reinit(fRowGroup, fRowsPerRG); - //fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); - fRowGroup.setData(&fData); + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); fRowGroup.resetRowGroup(0); fRowGroup.getRow(0, &fRow); } @@ -982,7 +883,7 @@ void GroupConcatNoOrder::merge(GroupConcator* gc) } -void GroupConcatNoOrder::getResult(uint8_t* buff, const string &sep) +void GroupConcatNoOrder::getResult(uint8_t* buff, string sep) { ostringstream oss; bool addSep = false; @@ -990,7 +891,7 @@ void GroupConcatNoOrder::getResult(uint8_t* buff, const string &sep) fDataQueue.push(fData); while (fDataQueue.size() > 0) { - fRowGroup.setData(&fDataQueue.front()); + fRowGroup.setData(fDataQueue.front().get()); fRowGroup.getRow(0, &fRow); for (uint64_t i = 0; i < fRowGroup.getRowCount(); i++) { diff --git a/dbcon/joblist/groupconcat.h b/dbcon/joblist/groupconcat.h index eb33cf0d..c9140969 100644 --- a/dbcon/joblist/groupconcat.h +++ b/dbcon/joblist/groupconcat.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: groupconcat.h 9705 2013-07-17 20:06:07Z pleblanc $ +// $Id: groupconcat.h 8436 2012-04-04 18:18:21Z rdempsey $ /** @file */ @@ -34,7 +34,7 @@ #include "rowaggregation.h" // SP_GroupConcat #include "limitedorderby.h" // IdbOrderBy -#if defined(_MSC_VER) && defined(JOBLIST_DLLEXPORT) +#if defined(_MSC_VER) && defined(GROUPCONCAT_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -58,16 +58,16 @@ class GroupConcatInfo void prepGroupConcat(JobInfo&); void mapColumns(const rowgroup::RowGroup&); - std::set& columns() { return fColumns; } + std::set& columns() { return fColumns; } std::vector& groupConcat() { return fGroupConcat; } const std::string toString() const; protected: - uint32_t getColumnKey(const execplan::SRCP& srcp, JobInfo& jobInfo); + uint getColumnKey(const execplan::SRCP& srcp, JobInfo& jobInfo); boost::shared_array makeMapping(const rowgroup::RowGroup&, const rowgroup::RowGroup&); - std::set fColumns; + std::set fColumns; std::vector fGroupConcat; }; @@ -84,13 +84,12 @@ class GroupConcatAgUM : public rowgroup::GroupConcatAg boost::scoped_ptr& concator() { return fConcator; } EXPORT void getResult(uint8_t*); - EXPORT uint8_t * getResult(); protected: void applyMapping(const boost::shared_array&, const rowgroup::Row&); boost::scoped_ptr fConcator; - boost::scoped_array fData; + boost::shared_array fData; rowgroup::Row fRow; bool fNoOrder; }; @@ -107,8 +106,7 @@ class GroupConcator virtual void processRow(const rowgroup::Row&) = 0; virtual void merge(GroupConcator*) = 0; - virtual void getResult(uint8_t* buff, const std::string &sep) = 0; - virtual uint8_t * getResult(const std::string &sep); + virtual void getResult(uint8_t* buff, std::string sep) = 0; virtual const std::string toString() const; @@ -118,11 +116,10 @@ class GroupConcator virtual int64_t lengthEstimate(const rowgroup::Row&); std::vector fConcatColumns; - std::vector > fConstCols; + std::vector > fConstCols; int64_t fCurrentLength; int64_t fGroupConcatLen; int64_t fConstantLen; - boost::scoped_array fOutputString; }; @@ -137,26 +134,25 @@ class GroupConcatNoOrder : public GroupConcator void processRow(const rowgroup::Row&); void merge(GroupConcator*); - void getResult(uint8_t* buff, const std::string &sep); + void getResult(uint8_t* buff, std::string sep); const std::string toString() const; protected: rowgroup::RowGroup fRowGroup; rowgroup::Row fRow; - rowgroup::RGData fData; - std::queue fDataQueue; + boost::shared_array fData; + std::queue > fDataQueue; uint64_t fRowsPerRG; uint64_t fErrorCode; uint64_t fMemSize; ResourceManager* fRm; - boost::shared_ptr fSessionMemLimit; }; // ORDER BY used in GROUP_CONCAT class // This version is for GROUP_CONCAT, the size is limited by the group_concat_max_len. -class GroupConcatOrderBy : public GroupConcator, public ordering::IdbOrderBy +class GroupConcatOrderBy : public GroupConcator, public IdbOrderBy { public: GroupConcatOrderBy(); @@ -167,7 +163,7 @@ class GroupConcatOrderBy : public GroupConcator, public ordering::IdbOrderBy uint64_t getKeyLength() const; void merge(GroupConcator*); - void getResult(uint8_t* buff, const std::string &sep); + void getResult(uint8_t* buff, std::string sep); const std::string toString() const; diff --git a/dbcon/joblist/hashjoin.cpp b/dbcon/joblist/hashjoin.cpp new file mode 100644 index 00000000..4f49018a --- /dev/null +++ b/dbcon/joblist/hashjoin.cpp @@ -0,0 +1,1895 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// +// $Id: hashjoin.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +// C++ Implementation: hashjoin +// +// Description: +// +// +// Author: Patrick , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// +#include "hashjoin.h" +#include "calpontsystemcatalog.h" +#include "elementcompression.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef O_BINARY +# define O_BINARY 0 +#endif +#ifndef O_DIRECT +# define O_DIRECT 0 +#endif +#ifndef O_LARGEFILE +# define O_LARGEFILE 0 +#endif +#ifndef O_NOATIME +# define O_NOATIME 0 +#endif + +using namespace execplan; +using namespace std; +using namespace joiner; +using namespace joblist; + +namespace +{ + const uint64_t LHJ_STEP_OFFSET = 1000;//added to HJ stepId to get LHJ stepId + const uint64_t BR_STEP_OFFSET = 2000;//added to BPS to get BucketReuse step + const uint64_t BDL_VEC_MAXSIZE = 4096; +} + +namespace joblist +{ + +HashJoinStep::HashJoinStep(JoinType jt, uint32_t ses, uint32_t stmt, uint32_t txn, + ResourceManager *rm) : + joinType(jt), sessionID(ses), statementID(stmt), txnID(txn), resourceManager(rm), + sizeFlag(true), fAllowLargeSideFifoToDisk(true), + om(BOTH), leftCount(0), rightCount(0), bps(0), fSmallCardinalityEstimate(0), + fSmallSideStepsOut(0), fLargeSideStepsOut(0), fLhjStep(0), + fHashJoinMode(UM_MEMORY), fTempFilePath(rm->getScTempDiskPath()), + fFilenameCounter(1), fCompMode(COMPRESS_NONE), fumMemory( rm->getHjUmMaxMemorySmallSide(sessionID)),fpmMemory( rm->getHjPmMaxMemorySmallSide(sessionID)),fhjMemory(0) +{ +// cout << "HashJoinStep(): sessionid" << ses << endl; + + /* The node based STL structures seem to use ~3x the space as an array + when the elements are only 16 bytes */ + fUMThreshold = fumMemory/(sizeof(ElementType) * 3); + fPMThreshold = fpmMemory/(sizeof(ElementType) * 3); + for (unsigned int i=0; ireturnHJUmMaxMemorySmallSide(fhjMemory); + if (fLhjStep) + delete fLhjStep; + if (fBucketReuseParms[0].fStep) + delete fBucketReuseParms[0].fStep; + if (fBucketReuseParms[1].fStep) + delete fBucketReuseParms[1].fStep; + + // Any temp file we created should have been deleted as soon as we were + // through with it, but we will put a check here just in case some error + // condition caused us to bypass the normal file cleanup. + if (fFile.is_open()) + fFile.close(); + if (!fFilename.empty()) + unlink(fFilename.c_str()); +} + +void HashJoinStep::setOutputMode(OutputMode o) +{ + om = o; +} + +const JobStepAssociation & HashJoinStep::inputAssociation() const +{ + return inJSA; +} + +void HashJoinStep::inputAssociation(const JobStepAssociation &in) +{ + inJSA = in; +} + +const JobStepAssociation & HashJoinStep::outputAssociation() const +{ + return outJSA; +} + +void HashJoinStep::outputAssociation(const JobStepAssociation &out) +{ + outJSA = out; +} + +void HashJoinStep::logger(const SPJL &logger) +{ + fLogger = logger; +} + +void HashJoinStep::stepId(uint16_t id) +{ + stepID = id; +} + +uint16_t HashJoinStep::stepId() const +{ + return stepID; +} + +uint32_t HashJoinStep::sessionId() const +{ + return sessionID; +} + +uint32_t HashJoinStep::statementId() const +{ + return statementID; +} + +uint32_t HashJoinStep::txnId() const +{ + return txnID; +} + +void HashJoinStep::run() +{ + // any init to do? + // sanity checks? + + idbassert(inJSA.outSize() == 2); + idbassert(outJSA.outSize() == 2); + + mainRunner.reset(new boost::thread(HJRunner(this))); +} + +void HashJoinStep::abort() +{ + die = true; + if (fBucketReuseParms[0].fStepUsing) + fBucketReuseParms[0].fStep->abort(); + if (fBucketReuseParms[1].fStepUsing) + fBucketReuseParms[1].fStep->abort(); + if (fLhjStep != NULL) + fLhjStep->abort(); +} + +void HashJoinStep::join() +{ + // Note that we already joined the threads that perform LHJ and + // small-side writer, so those threads are not "joined" here. + if (fBucketReuseParms[0].fStepUsing) + fBucketReuseParms[0].fStep->join(); + if (fBucketReuseParms[1].fStepUsing) + fBucketReuseParms[1].fStep->join(); + + mainRunner->join(); +} + +void HashJoinStep::setSizeFlag(bool b) +{ + sizeFlag = b; +} + +//------------------------------------------------------------------------------ +// Set flag controlling how HJ should handle the case where the large-side +// output Fifo "appears" to have become blocked. +// if true - the HJ should start dumping the elements to disk +// if false - the HJ will wait indefinitely for the fifo to become unblocked +//------------------------------------------------------------------------------ +void HashJoinStep::setAllowLargeSideFifoToDisk(bool b) +{ + fAllowLargeSideFifoToDisk = b; +} + +//------------------------------------------------------------------------------ +// Returns true/false indicating whether temp disk was used to cache the output +// large-side (Fifo or DeliveryWSDL) for the specified output association index. +//------------------------------------------------------------------------------ +bool HashJoinStep::didOutputAssocUseDisk( unsigned int index ) const +{ + // Eliminate check for small-side, since we never cache small-side to disk + if (sizeFlag) { + if (index == 0) + return false; + } + else { + if (index == 1) + return false; + } + + // Get disk usage total from applicable large-side datalist + uint64_t nFiles = 0; + uint64_t nBytes = 0; + FifoDataList* pFdsl = 0; + DeliveryWSDL* pDWSDL = 0; + const AnyDataListSPtr& pDl = outJSA.outAt(index); + + if ((pFdsl = pDl->fifoDL()) != 0) { + pFdsl->totalFileCounts (nFiles, nBytes); + } + else if ((pDWSDL = pDl->deliveryWSDL()) != 0) { + pDWSDL->totalFileCounts(nFiles, nBytes); + } + + if (nBytes > 0) + return true; + + return false; +} + +//------------------------------------------------------------------------------ +// This method is called by JLF prior to knowing anything about small-side vs +// large-side, and whether we will employ LHJ or BucketReuse, etc. JLF is +// providing us with the information we will need to use BucketReuse, should +// we decide to use it at query execution time. +// pFifoDL - The input JSA fifo that this BucketReuse info applies to +// filterString - filter string used in column scan +// tblOid - OID of table containing colOid +// colOid - column OID to be scanned from database +// verId - database version +//------------------------------------------------------------------------------ +void +HashJoinStep::addBucketReuse(FifoDataList* pFifoDL, + const std::string& filterString, + execplan::CalpontSystemCatalog::OID tblOid, + execplan::CalpontSystemCatalog::OID colOid, + uint32_t verId, + execplan::CalpontSystemCatalog::TableColName& colName) +{ + // Find the input JSA that matches the specified FIFO + for (unsigned int i=0; ififoDL()) { + fBucketReuseParms[i].fTblOid = tblOid; + fBucketReuseParms[i].fColOid = colOid; + fBucketReuseParms[i].fVerId = verId; + fBucketReuseParms[i].fColName = colName; + fBucketReuseParms[i].fFilterString = filterString; + break; + } + } +} + +//------------------------------------------------------------------------------ +// Initiate creation or reuse of Buckets (BDL) in BucketReuseStep for the +// specified input association. +// idx - jobstep datalist for which bucket reuse is to be initialized +//------------------------------------------------------------------------------ +void +HashJoinStep::initiateBucketReuse(unsigned int idx) +{ + // prevent syscat calls get into the reuse manager due to bad xml config + // which may invalid the db version being reused + if (fBucketReuseParms[idx].fTblOid < 3000) + return; + + bool scan = true; + + // lock this check, so the version in reuse manager will not be changed + // in a race condition + boost::mutex::scoped_lock lock(BucketReuseManager::instance()->getMutex()); + + uint64_t buckets = resourceManager->getHjMaxBuckets(); + BucketReuseControlEntry* entry = + BucketReuseManager::instance()->userRegister( + fBucketReuseParms[idx].fColName, + fBucketReuseParms[idx].fFilterString, + fBucketReuseParms[idx].fVerId, + buckets, + scan); + + if (entry) + { + fBucketReuseParms[idx].fBucketReuseEntry = entry; + fBucketReuseParms[idx].fReadOnly = !scan; + if (scan == false) + { + fBucketReuseParms[idx].fStep = new BucketReuseStep( + fBucketReuseParms[idx].fColOid, + fBucketReuseParms[idx].fTblOid, + sessionID, + txnID, + fBucketReuseParms[idx].fVerId, + statementID); + } + } +} + +/* Is it possible to get rid of the DataList switching? */ +void HashJoinStep::hjRunner() +{ +// cout << "hjrunner()\n"; + uint64_t nFiles = 0; + uint64_t nBytes = 0; + bool bFifoDiskUsed = false; + FifoDataList* largeOut = 0; + + if (0 < inJSA.status()) + { + outJSA.status(inJSA.status()); + outJSA.outAt(0)->dataList()->endOfInput(); + outJSA.outAt(1)->dataList()->endOfInput(); + startAdjoiningSteps(); + } + else + { + + FifoDataList *leftDL, *rightDL, *smallDL, *largeDL, *leftOut, *rightOut, + *smallOut; + DataList_t *smallOutDL = NULL, *largeOutDL = NULL, *leftOutDL = NULL, + *rightOutDL = NULL; + uint leftIt, rightIt, smallIt, largeIt, i, smallSize; + UintRowGroup inputRG; + bool more, sendSmall, sendLarge, sendAllSmallSide; + uint64_t *smallCount, *largeCount; + + leftDL = inJSA.outAt(0)->fifoDL(); + rightDL = inJSA.outAt(1)->fifoDL(); + leftOut = outJSA.outAt(0)->fifoDL(); + if (leftOut == NULL) + leftOutDL = outJSA.outAt(0)->dataList(); + rightOut = outJSA.outAt(1)->fifoDL(); + if (rightOut == NULL) + rightOutDL = outJSA.outAt(1)->dataList(); + idbassert(leftDL); + idbassert(rightDL); + idbassert(leftOut || leftOutDL); + idbassert(rightOut || rightOutDL); + + leftIt = leftDL->getIterator(); + rightIt = rightDL->getIterator(); + + if (sizeFlag) { + smallDL = leftDL; + largeDL = rightDL; + smallOut = leftOut; + largeOut = rightOut; + smallOutDL = leftOutDL; + largeOutDL = rightOutDL; + smallIt = leftIt; + largeIt = rightIt; + sendSmall = (om == BOTH || om == LEFTONLY); + sendLarge = (om == BOTH || om == RIGHTONLY); + smallCount = &leftCount; + largeCount = &rightCount; + } + else { + smallDL = rightDL; + largeDL = leftDL; + smallOut = rightOut; + largeOut = leftOut; + smallOutDL = rightOutDL; + largeOutDL = leftOutDL; + smallIt = rightIt; + largeIt = leftIt; + sendSmall = (om == BOTH || om == RIGHTONLY); + sendLarge = (om == BOTH || om == LEFTONLY); + smallCount = &rightCount; + largeCount = &leftCount; + } + + /* include all of the large side when: + - jointype is left outer and left is large + - jointype is right outer and right is large + include all of the small side when: + - jointype is left outer and left is small + - jointype is right outer and right is small + */ + + joiner.reset(new Joiner + ((joinType == LEFTOUTER && !sizeFlag) || + (joinType == RIGHTOUTER && sizeFlag))); + sendAllSmallSide = ((joinType == LEFTOUTER && sizeFlag) || + (joinType == RIGHTOUTER && !sizeFlag)); + + /* + read the small side and instantiate a Joiner + send the Joiner to BPS + start the BPS + + read from the large side. + For the In-UM alg, an optimization would be to connect the BPS + directly to the large-side output. No real need for a passthrough, + except to be notified that it's done. + */ + smallSize = 0; + + /* Automatically perform LHJ if estimated cardinality exceeds UM limit. */ + /* After LHJ completes, update dlTimes for result graphs. */ + if (fSmallCardinalityEstimate > fUMThreshold) + { + fHashJoinMode = LARGE_HASHJOIN_CARD; + performLargeHashJoin( smallDL, smallIt ); + fLhjStep->join(); + dlTimes.setFirstReadTime ( fLhjStep->dlTimes.FirstReadTime() ); + dlTimes.setEndOfInputTime( fLhjStep->dlTimes.EndOfInputTime() ); + return; + } + + string currentAction("reading small-side"); + bool startedAdjSteps = false; + + try { + more = smallDL->next(smallIt, &inputRG); + + startElapsedTime(WAIT_FOR_UMMEMORY); + //This can block. + if (fUMThreshold > inputRG.count) + fhjMemory = resourceManager->requestHJMaxMemorySmallSide(sessionID, fpmMemory); + else + fhjMemory = resourceManager->requestHJUmMaxMemorySmallSide(sessionID); + stopElapsedTime(WAIT_FOR_UMMEMORY); + + startElapsedTime(READ_SMALL_SIDE); + if (fTableOID2 >= 3000) dlTimes.setFirstReadTime(); + while (more && !die) { + smallSize += inputRG.count; + if (fhjMemory < fumMemory && smallSize > fPMThreshold) + { + startElapsedTime(WAIT_FOR_UMMEMORY); + fhjMemory += resourceManager->requestHJMaxMemorySmallSide(sessionID, fumMemory - fpmMemory); + stopElapsedTime(WAIT_FOR_UMMEMORY); + } + for (i = 0; i < inputRG.count; ++i) { + joiner->insert(inputRG.et[i]); + } + /* largehashjoin */ + /* After LHJ completes, update dlTimes for result graphs. */ + if (smallSize > fUMThreshold) + { + fHashJoinMode = LARGE_HASHJOIN_RUNTIME; + stopElapsedTime(READ_SMALL_SIDE); + performLargeHashJoin( smallDL, smallIt ); + + resourceManager->returnHJUmMaxMemorySmallSide(fhjMemory); + + fLhjStep->join(); + dlTimes.setFirstReadTime ( fLhjStep->dlTimes.FirstReadTime() ); + dlTimes.setEndOfInputTime( fLhjStep->dlTimes.EndOfInputTime() ); + return; + } + more = smallDL->next(smallIt, &inputRG); + } + stopElapsedTime(READ_SMALL_SIDE); + + startElapsedTime(RETURN_UNUSED_MEMORY); + uint64_t usedMemory = joiner->getMemUsage(); + //Joiner returns a minimum of chunksize, which may be less than fpmMemory + if (usedMemory < fhjMemory) + { + resourceManager->returnHJUmMaxMemorySmallSide(fhjMemory - usedMemory); + fhjMemory = usedMemory; + } + stopElapsedTime(RETURN_UNUSED_MEMORY); + + + currentAction = "setting up joiner"; + + /* If vec is small enough, do In-PM or In-UM else use largehashjoin */ + /* We should also restrict based on the expected size of the large side. + We'd lose time on all these extra msgs if there are < 1M elements to check + for example. Might also want to do it only if there are multiple PMs */ + + if (smallSize < fPMThreshold && fTableOID2 >= 3000) { + fHashJoinMode = PM_MEMORY; + joiner->inPM(true); + } + + /* In-UM algorithm */ + bps->useJoiner(joiner); + startElapsedTime(START_OTHER_STEPS); + startAdjoiningSteps(); + stopElapsedTime(START_OTHER_STEPS); + + startedAdjSteps = true; + currentAction = "writing large-side"; + + bFifoDiskUsed = outputLargeSide( + largeDL,largeIt,sendLarge,sendSmall,largeOut,largeOutDL,largeCount); + + smallSideWriter.reset(new boost::thread(HJSmallSideWriter(this, + sendSmall, sendAllSmallSide, smallOut, smallOutDL, smallCount))); + + /* If large-side (FIFO) was cached to temp disk, then go back and */ + /* copy the contents of the file to the large-side output datalist */ + if (bFifoDiskUsed) + outputLargeSideFifoFromDisk(largeOut); + if (largeOut) + largeOut->totalSize(*largeCount); + + } // try + + //...If enter a "catch" block, we keep going and try starting adjoining + //...steps else ExeMgr could block waiting for a jobstep to be "joined". + //...Similarly, we need to call endOfInput() on any output datalists. + catch (const logging::LargeDataListExcept& ex) + { + ostringstream errMsg; + errMsg << "HashJoinStep::hjRunner LDL error " << currentAction << "; "<< + ex.what(); + errorLogging(errMsg.str()); + outJSA.status(logging::hashJoinStepLargeDataListFileErr); + if (!startedAdjSteps) + startAdjoiningSteps(); + } + catch (const exception& ex) + { + stringstream errMsg; + errMsg << "HashJoinStep::hjRunner exception " << currentAction << "; "<< + ex.what(); + errorLogging(errMsg.str()); + outJSA.status(logging::hashJoinStepErr); + if (!startedAdjSteps) + startAdjoiningSteps(); + } + catch (...) + { + stringstream errMsg; + errMsg << "HashJoinStep::hjRunner unknown error " << currentAction; + errorLogging(errMsg.str()); + outJSA.status(logging::hashJoinStepErr); + if (!startedAdjSteps) + startAdjoiningSteps(); + } + + if (largeOut) + largeOut->endOfInput(); + else + largeOutDL->endOfInput(); + + if (bFifoDiskUsed) + stopElapsedTime(LARGE_SIDE_FIFO_FROM_DISK); + else + stopElapsedTime(RW_LARGE_SIDE_DL); + + if (smallSideWriter.get()) { + smallSideWriter->join(); + } + else { // send endOfInput if exception kept us from starting writer thread + if (smallOut) + smallOut->endOfInput(); + else + smallOutDL->endOfInput(); + } + + startElapsedTime(RETURN_USED_MEMORY); + resourceManager->returnHJUmMaxMemorySmallSide(fhjMemory); + stopElapsedTime(RETURN_USED_MEMORY); + fhjMemory = 0; + + } // else (inJSA.status() == 0) + + if (fTableOID2 >= 3000) + { + dlTimes.setEndOfInputTime(); + char leftSideLabel = 'S'; + char rightSideLabel = 'L'; + if (!sizeFlag) { + leftSideLabel = 'L'; + rightSideLabel = 'S'; + } + + if (largeOut) { + largeOut->totalFileCounts(nFiles, nBytes); + } + else { + DeliveryWSDL* pDWSDL = 0; + if (sizeFlag) + pDWSDL = outJSA.outAt(1)->deliveryWSDL(); + else + pDWSDL = outJSA.outAt(0)->deliveryWSDL(); + if (pDWSDL) + pDWSDL->totalFileCounts(nFiles, nBytes); + } + + ostringstream oss; + oss << "ses:" << sessionID << " st: " << stepID << + " Hashjoin finished:" + " output sizes left-side(" << leftSideLabel << ") " << leftCount << + ", right-side(" << rightSideLabel << ") " << rightCount << "; " << + ((fHashJoinMode==PM_MEMORY) ? "PM-MemoryJoin" : "UM-MemoryJoin"); + if (nBytes > 0) { + uint64_t kBytes = nBytes >> 10; + if (nBytes & 512) + kBytes++; + oss << " (tempDisk-" << kBytes << "KB)"; + } + oss << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + "; EOI " << dlTimes.EndOfInputTimeString() << " run time: " << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << "s" << + endl << + "\tElapsed times: " << fixed << setprecision(2) << + "startSteps-" << fElapsedTimes[START_OTHER_STEPS].second << + "s; rdSmall-" << fElapsedTimes[READ_SMALL_SIDE].second << + "s; wrSmall-" << fElapsedTimes[WRITE_SMALL_SIDE].second << + "s; waitLarge-" << fElapsedTimes[WAIT_FOR_LARGE_SIDE].second << + "s; r/wLargeDL-" << fElapsedTimes[RW_LARGE_SIDE_DL].second <<"s"; + if (bFifoDiskUsed) { + oss << + "; LFifoToDisk-" << + fElapsedTimes[LARGE_SIDE_FIFO_TO_DISK].second << + "s; LFifoFromDisk-" << + fElapsedTimes[LARGE_SIDE_FIFO_FROM_DISK].second << "s"; + } + + oss << "\n\tResourceManager: wait for UmMemory-" << setprecision(6) << fElapsedTimes[WAIT_FOR_UMMEMORY].second + << " return unused-" << fElapsedTimes[RETURN_UNUSED_MEMORY].second + << " return used-" << fElapsedTimes[RETURN_USED_MEMORY].second; + + oss << endl << + "\tJob completion status " << inJSA.status() << endl << endl; + cout << oss.str(); + } +} + +void HashJoinStep::setLargeSideBPS(BatchPrimitive* b) +{ + bps = b; +} + +// Set estimated small side cardinality used to determine if LHJ is to be used +void HashJoinStep::setSmallSideCardEst( uint64_t card ) +{ + fSmallCardinalityEstimate = card; +} + +//------------------------------------------------------------------------------ +// Outputs elements to large-side output datalist +// largeDL - input large-side datalist elements are to be read from +// largeIt - iterator used to read from largeDL +// sendLarge - boolean indicating whether jointype requires largeside output +// sendSmall - boolean indicating whether smallside is to be output +// largeOut - fifo output large-side datalist +// largeOutDL - alternate (zdl) large-side output datalist +// largeCount - number of elements read from largeDL +// return value of true indicates elements had to be cached to temp disk. +//------------------------------------------------------------------------------ +bool HashJoinStep::outputLargeSide( + FifoDataList *largeDL, + uint largeIt, + bool sendLarge, + bool sendSmall, + FifoDataList *largeOut, + DataList_t *largeOutDL, + uint64_t *largeCount) +{ + UintRowGroup inputRG; + + startElapsedTime(WAIT_FOR_LARGE_SIDE); + bool more = largeDL->next(largeIt, &inputRG); + stopElapsedTime(WAIT_FOR_LARGE_SIDE); + startElapsedTime(RW_LARGE_SIDE_DL); + bool consumeStarted = false; + while (more && !die) { + if (sendLarge) { + bool bufferFull = false; + + /* if large output is a FIFO, need to pack row groups... */ + *largeCount += inputRG.count; + if (largeOut) { +// cout << "large side:\n"; +// for (i = 0; i < rg.count; ++i) +// cout << " <" << rg.et[i].first << ", " << rg.et[i].second << ">" << endl; +// cout << endl; + + // If we are sending both small and large-sides then we have to + // handle case where large-side becomes blocked, by sending + // large-side FIFO to disk. If not sending small-side we can + // always output large-side to FIFO w/o using disk. + // If fAllowLargeSideFifoToDisk is false, then JLF has de- + // tected a pattern whereby permanent blocking will not occur, + // so we do not need to worry about caching the fifo to disk. + if (sendSmall && fAllowLargeSideFifoToDisk) { + largeOut->insert(inputRG, bufferFull, consumeStarted); + + // if large-side FIFO is blocked awaiting consumer, + // first retry, and if necessary, cache to temp disk + if(bufferFull) { + if (checkIfFifoBlocked(largeOut)) { + stopElapsedTime(RW_LARGE_SIDE_DL); + outputLargeSideFifoToDisk(largeDL,largeIt, + largeCount,largeOut); + return true; + } + } + } + else { + largeOut->insert(inputRG); + } + } + else { + for (uint i = 0; i < inputRG.count; ++i) + largeOutDL->insert(inputRG.et[i]); + } + } + more = largeDL->next(largeIt, &inputRG); + } + return false; +} + +//------------------------------------------------------------------------------ +// Go into loop MAX_SLEEP_RETRIES times, waiting to see if a blocked FIFO +// output datalist will eventually accept insertions. +// largeOut - fifo output large-side datalist +// return value of true means largeOut is still blocked. +//------------------------------------------------------------------------------ +bool HashJoinStep::checkIfFifoBlocked(FifoDataList *largeOut) +{ + const uint MAX_SLEEP_RETRIES = 100; + const uint USLEEP_INTERVAL = 5000; // half a second + + bool blocked = true; + for (uint k=0; kisOutputBlocked(); + if (!blocked) + break; + } + + return blocked; +} + +//------------------------------------------------------------------------------ +// When large-side output FIFO datalist is blocked, this method is called to +// save the elements out to disk, so that we can go ahead and complete the join, +// and send the small-side result set to the subsequent small-side output +// jobstep. The saved FIFO datalist, must then be read back in and routed to +// the large-side output jobstep by outputLargeSideFifoFromDisk(). +// largeDL - input large-side datalist elements are to be read from +// largeIt - iterator used to read from largeDL +// largeCount - number of elements read from largeDL +// largeOut - fifo output large-side datalist +//------------------------------------------------------------------------------ +void HashJoinStep::outputLargeSideFifoToDisk( + FifoDataList *largeDL, + uint largeIt, + uint64_t *largeCount, + FifoDataList *largeOut) +{ + startElapsedTime(LARGE_SIDE_FIFO_TO_DISK); + uint32_t ridSize = largeOut->getDiskElemSize1st(); + uint32_t valSize = largeOut->getDiskElemSize2nd(); + UintRowGroup inputRG; + + // Set enum and generic buffer ptr relative to how we intend to compress + // the data saved to disk; We use a char* buffer so that we can share a + // common buffer across all compression modes. + uint32_t elemCnt = inputRG.ElementsPerGroup; + if (largeOut->getElementMode() == FifoDataList::RID_ONLY) { + if (ridSize == 4) { + fCompMode = COMPRESS_32; + fCompBuffer.reset(new char[sizeof(uint32_t)*elemCnt]); + } + else { + fCompMode = COMPRESS_64; + fCompBuffer.reset(new char[sizeof(uint64_t)*elemCnt]); + } + } + else { + if ((ridSize == 8) && (valSize == 4)) { + fCompMode = COMPRESS_64_32; + fCompBuffer.reset(new char[sizeof(CompElement64Rid32Val)*elemCnt]); + } + else if ((ridSize == 4) && (valSize == 8)) { + fCompMode = COMPRESS_32_64; + fCompBuffer.reset(new char[sizeof(CompElement32Rid64Val)*elemCnt]); + } + else if ((ridSize == 4) && (valSize == 4)) { + fCompMode = COMPRESS_32_32; + fCompBuffer.reset(new char[sizeof(CompElement32Rid32Val)*elemCnt]); + } + else { + fCompMode = COMPRESS_NONE; + } + } + + try { + // open temporary file for our output fifo datalist + createTempFile(); + //ostringstream oss; + //oss << "ses:" << sessionID << " HashJoinStep " << stepID << + // " caching large-side FIFO to file " << fFilename << endl; + //cout << oss.str(); + + // write elements coming from largeDL (input datalist) to disk + + + bool more = largeDL->next(largeIt, &inputRG); + while (more && !die) { + /* if large output is a FIFO, need to pack row groups... */ + *largeCount += inputRG.count; + writeRowGroupToDisk(inputRG); + more = largeDL->next(largeIt, &inputRG); + } + + // save the file usage stats in the FIFO datalist + largeOut->setTotalFileCounts(1, fFile.tellg()); + } + catch (...) { + if (fFile.is_open()) + fFile.close(); + if (!fFilename.empty()) { + unlink(fFilename.c_str()); + fFilename.clear(); + } + + ostringstream errMsg; + errMsg << "Error occurred saving HashJoin FIFO into file " << fFilename; + errorLogging(errMsg.str()); + throw; // rethrow to main try/catch block in hjRunner() + } + stopElapsedTime(LARGE_SIDE_FIFO_TO_DISK); +} + +//------------------------------------------------------------------------------ +// Writes the current contents of the "rg" RowGroup to a temp disk file. We +// compress the elements using a common char* buffer if compression is needed. +//------------------------------------------------------------------------------ +void HashJoinStep::writeRowGroupToDisk(const UintRowGroup &rg) +{ + fFile.write((char*)&(rg.count), sizeof(rg.count)); + + switch (fCompMode) + { + case COMPRESS_64: + { + uint64_t* ridArray = reinterpret_cast(fCompBuffer.get()); + for (unsigned int i=0; i(fCompBuffer.get()); + for (unsigned int i=0; i(fCompBuffer.get()); + for (unsigned int i=0; i(fCompBuffer.get()); + for (unsigned int i=0; i(fCompBuffer.get()); + for (unsigned int i=0; iwaitTillReadyForInserts(); + + // Loop through reading row groups from the temp file and inserting + // them into the large-side output datalist. + while (!die) { + if (readRowGroupFromDisk(&rg)) + break; + + largeOut->insert(rg); + } + } // try + catch (...) { + ostringstream errMsg; + errMsg << "Error occurred copying HashJoin FIFO from file " <count), sizeof(rg->count)); + if (fFile.eof()) + return true; + + switch (fCompMode) + { + case COMPRESS_64: + { + fFile.read(fCompBuffer.get(), (sizeof(uint64_t)*rg->count)); + if (!fFile.good()) + break; + + uint64_t* ridArray = reinterpret_cast(fCompBuffer.get()); + for (unsigned int i=0; icount; ++i) { + rg->et[i].first = ridArray[i]; + rg->et[i].second = 0; + } + break; + } + case COMPRESS_32: + { + fFile.read(fCompBuffer.get(), (sizeof(uint32_t)*rg->count)); + if (!fFile.good()) + break; + + uint32_t* ridArray = reinterpret_cast(fCompBuffer.get()); + for (unsigned int i=0; icount; ++i) { + rg->et[i].first = ridArray[i]; + rg->et[i].second = 0; + } + break; + } + case COMPRESS_64_32: + { + fFile.read(fCompBuffer.get(), + (sizeof(CompElement64Rid32Val)*rg->count)); + if (!fFile.good()) + break; + + CompElement64Rid32Val* elemArray = + reinterpret_cast(fCompBuffer.get()); + for (unsigned int i=0; icount; ++i) { + rg->et[i].first = elemArray[i].first; + rg->et[i].second = elemArray[i].second; + } + break; + } + case COMPRESS_32_64: + { + fFile.read(fCompBuffer.get(), + (sizeof(CompElement32Rid64Val)*rg->count)); + if (!fFile.good()) + break; + + CompElement32Rid64Val* elemArray = + reinterpret_cast(fCompBuffer.get()); + for (unsigned int i=0; icount; ++i) { + rg->et[i].first = elemArray[i].first; + rg->et[i].second = elemArray[i].second; + } + break; + } + case COMPRESS_32_32: + { + fFile.read(fCompBuffer.get(), + (sizeof(CompElement32Rid32Val)*rg->count)); + if (!fFile.good()) + break; + + CompElement32Rid32Val* elemArray = + reinterpret_cast(fCompBuffer.get()); + for (unsigned int i=0; icount; ++i) { + rg->et[i].first = elemArray[i].first; + rg->et[i].second = elemArray[i].second; + } + break; + } + case COMPRESS_NONE: + default: + { + fFile.read((char*)rg->et, (sizeof(ElementType)*rg->count)); + if (!fFile.good()) + break; + + break; + } + } + + if (!fFile.good()) { + ostringstream errMsg; + errMsg << "Error occurred reading HashJoin FIFO file " << + fFilename << "; errno-" << errno << "; errmsg-" << + strerror(errno) << endl; + throw runtime_error(errMsg.str()); + } + + return false; +} + +//------------------------------------------------------------------------------ +// Outputs elements to small-side output datalist. Input comes from joiner. +// sendSmall - boolean indicating whether jointype requires smallside output +// sendAllSmallSide - boolean requesting all of small-side (due to outerjoin) +// smallOut - fifo output small-side datalist +// smallOutDL - alternate (zdl) small-side output datalist +// smallCount - number of elements copied to output datalist +//------------------------------------------------------------------------------ +void HashJoinStep::outputSmallSide( + bool sendSmall, + bool sendAllSmallSide, + FifoDataList *smallOut, + DataList_t *smallOutDL, + uint64_t *smallCount) +{ + startElapsedTime(WRITE_SMALL_SIDE); + try { + UintRowGroup smallRg; + + smallRg.count = 0; + if (sendSmall) { + boost::shared_ptr > sortedSmallSide; + + if (sendAllSmallSide) { + sortedSmallSide = joiner->getSmallSide(); + sort::iterator>(sortedSmallSide->begin(), + sortedSmallSide->end()); + } + else + sortedSmallSide = joiner->getSortedMatches(); + + joiner.reset(); + + uint vSize = sortedSmallSide->size(); + *smallCount = vSize; +// cout << "small side:\n"; + for (uint i = 0; i < vSize && !die; ++i) { + /* if small output is a FIFO, need to pack row groups... */ + if (smallOut) { + smallRg.et[smallRg.count++] = (*sortedSmallSide)[i]; + if (smallRg.count == smallRg.ElementsPerGroup) { + smallOut->insert(smallRg); + smallRg.count = 0; + } + } + else + smallOutDL->insert((*sortedSmallSide)[i]); + } + } + else { + joiner.reset(); + } + + if (smallOut) { + if (smallRg.count > 0) + smallOut->insert(smallRg); + smallOut->totalSize(*smallCount); + } + } // try + catch (const logging::LargeDataListExcept& ex) + { + ostringstream errMsg; + errMsg<<"HashJoinStep::outputSmallSide LDL error writing small-side; "<< + ex.what(); + errorLogging(errMsg.str()); + outJSA.status( logging::hashJoinStepLargeDataListFileErr ); + } + catch (const exception& ex) + { + stringstream errMsg; + errMsg<<"HashJoinStep::outputSmallSide exception writing small-side; "<< + ex.what(); + errorLogging(errMsg.str()); + outJSA.status( logging::hashJoinStepErr ); + } + catch (...) + { + string errMsg ( + "HashJoinStep::outputSmallSide unknown error writing small-side"); + errorLogging(errMsg); + outJSA.status( logging::hashJoinStepErr ); + } + + if (smallOut) + smallOut->endOfInput(); + else + smallOutDL->endOfInput(); + stopElapsedTime(WRITE_SMALL_SIDE); +} + +//------------------------------------------------------------------------------ +// Public method called by JLF to provide list of jobsteps connected to this +// hashjoin's large-side output. +//------------------------------------------------------------------------------ +void HashJoinStep::setLargeSideStepsOut(const vector& largeSideSteps) +{ + if (largeSideSteps.size() > 0) + { + ostringstream oss; + for (unsigned i=0; istepId(); + // else + // oss << ", " << largeSideSteps[i]->stepId(); + //} + } + //if (traceOn()) + //{ + // oss << endl; + // cout << oss.str(); + //} + } +} + +//------------------------------------------------------------------------------ +// Public method called by JLF to provide list of jobsteps connected to this +// hashjoin's small-side output. +//------------------------------------------------------------------------------ +void HashJoinStep::setSmallSideStepsOut(const vector& smallSideSteps) +{ + if (smallSideSteps.size() > 0) + { + ostringstream oss; + for (unsigned i=0; istepId(); + // else + // oss << ", " << smallSideSteps[i]->stepId(); + //} + } + //if (traceOn()) + //{ + // oss << endl; + // cout << oss.str(); + //} + } +} + +//------------------------------------------------------------------------------ +// Start jobsteps that have been delayed, if they can be started now, else +// we just decrement the count, and another hashjoin will start them later, +// when the wait step count is decremented to 1. +// Also note the extra BucketReuse logic involving the start of the large- +// side input step. For a LHJ, if we can replace the input step with a +// BucketReuseStep, then we do so. +//------------------------------------------------------------------------------ +void HashJoinStep::startAdjoiningSteps() +{ + if (bps->decWaitToRunStepCnt() == 1) + { + bool startedBucketReuseStep = false; + + if ((fHashJoinMode == LARGE_HASHJOIN_CARD) || + (fHashJoinMode == LARGE_HASHJOIN_RUNTIME)) + { + unsigned int largeSide = 0; + if (sizeFlag) + largeSide = 1; + + // If possible, substitute a BucketReuseStep for large-side in BPS + if (fBucketReuseParms[largeSide].fBucketReuseEntry && + fBucketReuseParms[largeSide].fReadOnly) + { + JobStepAssociation bucketReuseJSA(inJSA.statusPtr()); + bucketReuseJSA.outAdd( inJSA.outAt(largeSide) ); + fBucketReuseParms[largeSide].fStep->outputAssociation( + bucketReuseJSA ); + fBucketReuseParms[largeSide].fStep->stepId(bps->stepId() + + BR_STEP_OFFSET); + fBucketReuseParms[largeSide].fStepUsing = true; + + if (traceOn()) + { + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + + ostringstream oss; + oss << "ses:" << sessionID << " HashJoinStep " << stepID << + " starting large-side BucketReuse InputStep " << + fBucketReuseParms[largeSide].fStep->stepId() << + " at: " << timeString; + //oss<toString()<run(); + startedBucketReuseStep = true; + + // We won't be running the BPS, but we still update the output + // JSA so that the result graph can connect the steps correctly. + bps->outputAssociation( bucketReuseJSA ); + } + } + + if (!startedBucketReuseStep) + { + if (traceOn()) + { + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + + ostringstream oss; + oss << "ses:" << sessionID << " HashJoinStep " << stepID << + " starting large-side InputStep " << bps->stepId() << + " at: " << timeString; + //oss << bps->toString() << endl; + cout << oss.str(); + } + bps->run(); + } + } + + for (unsigned int i=0; idecWaitToRunStepCnt() == 1) + { + if (traceOn()) + { + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + + ostringstream oss; + oss << "ses:" << sessionID << " HashJoinStep " << stepID << + " starting small-side OutputStep " << + fSmallSideStepsOut[i]->stepId() << " at: " << timeString; + //oss << fSmallSideStepsOut[i]->toString() << endl; + cout << oss.str(); + } + fSmallSideStepsOut[i]->run(); + } + } + + for (unsigned int i=0; idecWaitToRunStepCnt() == 1) + { + if (traceOn()) + { + time_t t = time(0); + char timeString[50]; + ctime_r(&t, timeString); + + ostringstream oss; + oss << "ses:" << sessionID << " HashJoinStep " << stepID << + " starting large-side OutputStep " << + fLargeSideStepsOut[i]->stepId() << " at: " << timeString; + //oss << fLargeSideStepsOut[i]->toString() << endl; + cout << oss.str(); + } + fLargeSideStepsOut[i]->run(); + } + } +} + +//------------------------------------------------------------------------------ +// Perform LargeHashJoin employing disk cache with BDL input and ZDL output +// smallDL - fifo datalist we are using to read in the small-side input +// smallIt - iterator we are using to read elements in from smallDL +//------------------------------------------------------------------------------ +void +HashJoinStep::performLargeHashJoin( + FifoDataList* smallDL, + uint smallIt ) +{ + startElapsedTime(START_OTHER_STEPS); + //...Create jobstep to perform "large" hashjoin + fLhjStep = new LargeHashJoin( joinType, + sessionID, + txnID, + statementID, + *resourceManager); + + //..."Might" consider adding a LargeHashJoin constructor that takes a + //...HashJoinStep arg, so we would not have to call all these setters. + fLhjStep->logger ( fLogger ); + fLhjStep->stepId ( stepId() + LHJ_STEP_OFFSET ); + fLhjStep->setTraceFlags(fTraceFlags ); + fLhjStep->alias1 ( fAlias1 ); + fLhjStep->alias2 ( fAlias2 ); + fLhjStep->view1 ( fView1 ); + fLhjStep->view2 ( fView2 ); + fLhjStep->tableOid1 ( fTableOID1 ); + fLhjStep->tableOid2 ( fTableOID2 ); + fLhjStep->cardinality( fCardinality ); + + JobStepAssociation lhjJsaIn (inJSA.statusPtr()); // JSA Input to LHJ + JobStepAssociation lhjJsaOut(inJSA.statusPtr()); // JSA Output from LHJ + BucketDataList* lhjSmallBdlIn = 0; // BDL small-side input to LHJ + + //...Construct BDL jobstep association going into LargeHashJoin. + //...(For the sake of the jobstep graph, we also modify the jobstep assoc + //... for the original hj step, so that they reflect the new associations + //... used by the LargeHashJoin step.) + JobStepAssociation myNewInputJSA(inJSA.statusPtr()); + + bool bBucketReuseError = false; + try { + if (sizeFlag) // input 1 is large-side + { + buildLhjInJsa( inJSA.outAt(0), 0 , lhjJsaIn ); + buildLhjInJsa( inJSA.outAt(1), bps, lhjJsaIn ); + lhjSmallBdlIn = lhjJsaIn.outAt(0)->bucketDL(); + myNewInputJSA.outAdd( inJSA.outAt(0) ); // original small-side input + myNewInputJSA.outAdd( lhjJsaIn.outAt(1) );// new large-side input + + //...Provide bucket-reuse info to large-side BDL + initiateBucketReuse(1); + if (fBucketReuseParms[1].fBucketReuseEntry) + lhjJsaIn.outAt(1)->bucketDL()->reuseControl( + fBucketReuseParms[1].fBucketReuseEntry, + fBucketReuseParms[1].fReadOnly ); + } + else // input 0 is large-side + { + buildLhjInJsa( inJSA.outAt(0), bps, lhjJsaIn ); + buildLhjInJsa( inJSA.outAt(1), 0 , lhjJsaIn ); + lhjSmallBdlIn = lhjJsaIn.outAt(1)->bucketDL(); + myNewInputJSA.outAdd( lhjJsaIn.outAt(0) );// new large-side input + myNewInputJSA.outAdd( inJSA.outAt(1) ); // original small-side input + + //...Provide bucket-reuse info to large-side BDL + initiateBucketReuse(0); + if (fBucketReuseParms[0].fBucketReuseEntry) + lhjJsaIn.outAt(0)->bucketDL()->reuseControl( + fBucketReuseParms[0].fBucketReuseEntry, + fBucketReuseParms[0].fReadOnly ); + } + } // try + + //...If enter a "catch" block, we keep going and try starting adjoining + //...steps else ExeMgr could block waiting for a jobstep to be "joined". + //...Similarly, we need to call endOfInput() on any output datalists. + catch (const logging::LargeDataListExcept& ex) + { + ostringstream errMsg; + errMsg << "HashJoinStep::performLHJ LDL error with BucketReuse; " << + ex.what(); + errorLogging(errMsg.str()); + outJSA.status( logging::hashJoinStepLargeDataListFileErr ); + bBucketReuseError = true; + } + catch (const exception& ex) + { + stringstream errMsg; + errMsg << "HashJoinStep::performLHJ exception with BucketReuse; " << + ex.what(); + errorLogging(errMsg.str()); + outJSA.status( logging::hashJoinStepErr ); + bBucketReuseError = true; + } + catch (...) + { + string errMsg ( + "HashJoinStep::performLHJ unknown error with BucketReuse"); + errorLogging(errMsg); + outJSA.status( logging::hashJoinStepErr ); + bBucketReuseError = true; + } + + fLhjStep->inputAssociation( lhjJsaIn ); + inputAssociation( myNewInputJSA );// update my input assoc for jobstep graph + + //...Construct ZDL jobstep asssociation coming out of LargeHashJoin + if (sizeFlag) + { + buildLhjOutJsa( outJSA.outAt(0), fSmallSideStepsOut, lhjJsaOut, + (om == RIGHTONLY) ); + buildLhjOutJsa( outJSA.outAt(1), fLargeSideStepsOut, lhjJsaOut, + (om == LEFTONLY) ); + } + else + { + buildLhjOutJsa( outJSA.outAt(0), fLargeSideStepsOut, lhjJsaOut, + (om == RIGHTONLY) ); + buildLhjOutJsa( outJSA.outAt(1), fSmallSideStepsOut, lhjJsaOut, + (om == LEFTONLY) ); + } + fLhjStep->outputAssociation( lhjJsaOut ); + outputAssociation( lhjJsaOut ); // update my output assoc for jobstep graph + + startAdjoiningSteps(); + + //...Start the LargeHashJoin step itself + if (traceOn()) + { + ostringstream oss; + oss << "ses:" << sessionID << " st: " << stepID << + " creating the following LargeHashJoin step: " << endl << + fLhjStep->toString() << endl; + cout << oss.str(); + } + fLhjStep->run(); + stopElapsedTime(START_OTHER_STEPS); + + //...If we have problems with BucketReuse, then we can skip sending + //...any elements to our small-side output datalist, else we start + //...sending the small-side elements to LHJ. + uint64_t smallSideCount = joiner->size(); + if (!bBucketReuseError) + { + //...Forward small-side data read in so far, to LargeHashJoin. + //...If we have already started reading from small side, then resume + //...the READ_SMALL_SIDE timer, else we wait till after our first read. + if (smallSideCount > 0) + startElapsedTime(READ_SMALL_SIDE); + + try { + vector bdlVec; + for (Joiner::iterator it=joiner->begin(); it!=joiner->end(); ++it) + { + bdlVec.push_back(ElementType(it->second & ~Joiner::MSB, it->first)); + if (bdlVec.size() > BDL_VEC_MAXSIZE) + { + lhjSmallBdlIn->insert(bdlVec); + bdlVec.clear(); + } + } + joiner.reset(); + if (bdlVec.size() > 0) + { + lhjSmallBdlIn->insert(bdlVec); + bdlVec.clear(); + } + vector().swap(bdlVec); // immediately release memory + + //...Enter loop to forward remaining small-side elements to LHJ + bool more; + UintRowGroup rg; + + more = smallDL->next(smallIt, &rg); + if (smallSideCount == 0) + { + startElapsedTime(READ_SMALL_SIDE); // start timer if first read + if (fTableOID2 >= 3000) dlTimes.setFirstReadTime(); + } + while (more) + { + smallSideCount += rg.count; + lhjSmallBdlIn->insert(rg.et, rg.count); + more = smallDL->next(smallIt, &rg); + } + } // try + catch (const logging::LargeDataListExcept& ex) + { + ostringstream errMsg; + errMsg << "HashJoinStep::performLHJ LDL error writing BDL; " << + ex.what(); + errorLogging(errMsg.str()); + outJSA.status( logging::hashJoinStepLargeDataListFileErr ); + } + catch (const exception& ex) + { + stringstream errMsg; + errMsg << "HashJoinStep::performLHJ exception writing BDL; " << + ex.what(); + errorLogging(errMsg.str()); + outJSA.status( logging::hashJoinStepErr ); + } + catch (...) + { + string errMsg ( + "HashJoinStep::performLHJ unknown error writing BDL"); + errorLogging(errMsg); + outJSA.status( logging::hashJoinStepErr ); + } + } + else + { + startElapsedTime(READ_SMALL_SIDE); + joiner.reset(); + } + + lhjSmallBdlIn->endOfInput(); + stopElapsedTime(READ_SMALL_SIDE); + + if (fTableOID2 >= 3000) + { + dlTimes.setEndOfInputTime(); + + ostringstream oss; + oss << "ses:" << sessionID << " st: " << stepID << + "; Initial HashJoin step finished: Using LHJ step: " << + fLhjStep->stepId() << " (" << + ((fHashJoinMode==LARGE_HASHJOIN_CARD) ? + "card-select" : "run-select") << "); input " << + ((sizeFlag) ? " left" : " right") << "-side (small-side) count: " << + smallSideCount << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + "; EOI-to-LHJ " << dlTimes.EndOfInputTimeString() << " run time: "<< + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << "s" << + endl << + "\tJob completion status " << inJSA.status() << endl << endl; + cout << oss.str(); + } +} + +//------------------------------------------------------------------------------ +// Build BDL jobstep associations connecting jobStep2 output to LHJ input +// anyDL1 - if jobStep2 is nonzero, then anyDL1 is the datalist we are +// replacing in jobStep2's output association. +// jobStep2 - (optional) jobstep that is connected to LHJ input +// newJsa1 - jobstep input association to be stored in LHJ jobstep +//------------------------------------------------------------------------------ +void +HashJoinStep::buildLhjInJsa( + const AnyDataListSPtr& anyDl1, + JobStep* jobStep2, + JobStepAssociation& newJsa1) +{ + FifoDataList* fdl = anyDl1->fifoDL(); + if (fdl) + { + BucketDataList* pBdl = new BucketDataList( + resourceManager->getHjMaxBuckets(), fdl->getNumConsumers(), + resourceManager->getHjMaxElems(), *resourceManager); + pBdl->setHashMode(1); + pBdl->setDiskElemSize( fdl->getDiskElemSize1st(), + fdl->getDiskElemSize2nd()); + pBdl->OID( fdl->OID() ); + if (fTraceFlags & CalpontSelectExecutionPlan::TRACE_DISKIO_UM) + pBdl->enableDiskIoTrace(); + AnyDataListSPtr spdlBdl(new AnyDataList()); + spdlBdl->bucketDL(pBdl); + + // Place new BDL into output JSA of jobStep2 + if (jobStep2) + { + DataList_t* dl1in = anyDl1->dataList(); + JobStepAssociation newJsa2(inJSA.statusPtr()); + + for (unsigned int i = 0; + i < jobStep2->outputAssociation().outSize(); + ++i) + { + AnyDataListSPtr dl2In=jobStep2->outputAssociation().outAt(i); + if ((ptrdiff_t)(dl2In->dataList()) == (ptrdiff_t)dl1in) + newJsa2.outAdd( spdlBdl ); // found match; replace with BDL + else + newJsa2.outAdd( dl2In ); // no match; reuse old datalist + } + + if (traceOn()) + { + ostringstream oss; + oss << " updated output JSA in step " << + jobStep2->stepId() << " for LHJ: "; + printJSA( oss.str().c_str(), newJsa2 ); + } + jobStep2->outputAssociation( newJsa2 ); + } + + newJsa1.outAdd( spdlBdl ); + } + else + { + newJsa1.outAdd( anyDl1 ); // assume already a BDL, so just copy as-is + } +} + +//------------------------------------------------------------------------------ +// Build ZDL jobstep associations connecting LHJ output to jobSteps2 input +// anyDL1 - output datalist from LHJ that we are searching for in adjoining +// jobSteps2 vector +// jobSteps2 - jobstep vector of jobsteps that are connected to LHJ output +// newJsa1 - jobstep output association to be stored in LHJ jobstep +// dropInserts-flag indicating if we should drop inserts to this output ZDL +//------------------------------------------------------------------------------ +void +HashJoinStep::buildLhjOutJsa( + const AnyDataListSPtr& anyDl1, + vector& jobSteps2, + JobStepAssociation& newJsa1, + bool dropInserts ) +{ + // If hashjoin output is not ZDL, we switch to ZDL + if (!anyDl1->zonedDL()) + { + // Create new ZDL to connect hashjoin to subsequent jobstep. + uint numConsumers; + uint32_t diskElemSize1st, diskElemSize2nd; + execplan::CalpontSystemCatalog::OID dlOID; + uint elementMode; + + FifoDataList* fdl = anyDl1->fifoDL(); + if (fdl) { + numConsumers = fdl->getNumConsumers(); + diskElemSize1st = fdl->getDiskElemSize1st(); + diskElemSize2nd = fdl->getDiskElemSize2nd(); + dlOID = fdl->OID(); + if (fdl->getElementMode() == FifoDataList::RID_ONLY) + elementMode = ZonedDL::RID_ONLY; + else + elementMode = ZonedDL::RID_VALUE; + } + else { + DeliveryWSDL* dwdl = anyDl1->deliveryWSDL(); + numConsumers = dwdl->getNumConsumers(); + diskElemSize1st = dwdl->getDiskElemSize1st(); + diskElemSize2nd = dwdl->getDiskElemSize2nd(); + dlOID = dwdl->OID(); + if (dwdl->getElementMode() == DeliveryWSDL::RID_ONLY) + elementMode = ZonedDL::RID_ONLY; + else + elementMode = ZonedDL::RID_VALUE; + } + + ZonedDL* pZdl = new ZonedDL( numConsumers, *resourceManager); + pZdl->setMultipleProducers(true); + pZdl->setDiskElemSize( diskElemSize1st, diskElemSize2nd ); + pZdl->OID( dlOID ); + pZdl->setElementMode( elementMode ); + if (dropInserts) + pZdl->dropAllInserts(); + if (fTraceFlags & CalpontSelectExecutionPlan::TRACE_DISKIO_UM) + pZdl->enableDiskIoTrace(); + AnyDataListSPtr spdlZdl(new AnyDataList()); + spdlZdl->zonedDL(pZdl); + + DataList_t* dl1in = anyDl1->dataList(); + + // Place new ZDL into "input" JSA of steps in jobStep2 vector + for (unsigned int m=0; minputAssociation().outSize(); + ++i) + { + AnyDataListSPtr dl2In=jobSteps2[m]->inputAssociation().outAt(i); + if ((ptrdiff_t)(dl2In->dataList()) == (ptrdiff_t)dl1in) + newJsa2.outAdd( spdlZdl ); // found match; replace with ZDL + else + newJsa2.outAdd( dl2In ); // no match; reuse old datalist + } + + if (traceOn()) + { + ostringstream oss; + oss << " updated input JSA in step " << + jobSteps2[m]->stepId() << " for LHJ: "; + printJSA( oss.str().c_str(), newJsa2 ); + } + jobSteps2[m]->inputAssociation( newJsa2 ); + } + + // Place new ZDL into "output" JSA of hashjoin step. + newJsa1.outAdd( spdlZdl ); + } + else + { + newJsa1.outAdd( anyDl1 ); // assume already a ZDL, so just copy as-is + } +} + +//------------------------------------------------------------------------------ +// Debug function used to dump a JobStepAssociation +//------------------------------------------------------------------------------ +void +HashJoinStep::printJSA(const char* label, const JobStepAssociation& jsa) +{ + ostringstream oss; + oss << "ses:" << sessionID << " st:" << stepID << "; " << label; + for (unsigned int i=0; i 0) + oss << ", "; + oss << jsa.outAt(i); + } + oss << endl; + cout << oss.str(); +} + +const string HashJoinStep::toString() const +{ + ostringstream oss; + CalpontSystemCatalog::OID oid1 = 0; + CalpontSystemCatalog::OID oid2 = 0; + DataList_t* dl1; + DataList_t* dl2; + size_t idlsz; + + idlsz = inJSA.outSize(); + idbassert(idlsz == 2); + dl1 = inJSA.outAt(0)->dataList(); + if (dl1) oid1 = dl1->OID(); + dl2 = inJSA.outAt(1)->dataList(); + if (dl2) oid2 = dl2->OID(); + oss << "HashJoinStep ses:" << sessionID << " st:" << stepID; + oss << omitOidInDL; + oss << " in tb/col1:" << fTableOID1 << "/" << oid1; + oss << " " << inJSA.outAt(0); + oss << " in tb/col2:" << fTableOID2 << "/" << oid2; + oss << " " << inJSA.outAt(1); + + idlsz = outJSA.outSize(); + if (idlsz > 0) + { + oss << endl << " "; + dl1 = outJSA.outAt(0)->dataList(); + if (dl1) oid1 = dl1->OID(); + oss << " out tb/col1:" << fTableOID1 << "/" << oid1; + oss << " " << outJSA.outAt(0); + } + if (idlsz > 1) + { + dl2 = outJSA.outAt(1)->dataList(); + if (dl2) oid2 = dl2->OID(); + oss << " out tb/col2:" << fTableOID2 << "/" << oid2; + oss << " " << outJSA.outAt(1); + } + + return oss.str(); +} + +//------------------------------------------------------------------------------ +// Log specified error to stderr and the critical log +//------------------------------------------------------------------------------ +void HashJoinStep::errorLogging(const string& msg) const +{ + ostringstream errMsg; + errMsg << "Step " << stepId() << "; " << msg; + cerr << errMsg.str() << endl; + catchHandler( errMsg.str(), sessionId() ); +} + +//------------------------------------------------------------------------------ +// Start a timer used to track elapsed time for the specified HjElapsedTime enum +// fElapsedTimes[i].first is the start of current elapsed time we are tracking. +// fElapsedTimers[i].second is the sum of elapsed times. +//------------------------------------------------------------------------------ +void HashJoinStep::startElapsedTime(HjElapsedTime whichTime) +{ + struct timeval currentTime; + gettimeofday(¤tTime, 0); + + fElapsedTimes[whichTime].first = + (double)currentTime.tv_sec+(double)currentTime.tv_usec/1000000.0; +} + +//------------------------------------------------------------------------------ +// Stop a timer for the specified HjElapsedTime enum, and update elapsed time +//------------------------------------------------------------------------------ +void HashJoinStep::stopElapsedTime(HjElapsedTime whichTime) +{ + struct timeval currentTime; + gettimeofday(¤tTime, 0); + + double endTime = + (double)currentTime.tv_sec+(double)currentTime.tv_usec/1000000.0; + fElapsedTimes[whichTime].second += (endTime-fElapsedTimes[whichTime].first); +} + +} diff --git a/dbcon/joblist/hashjoin.h b/dbcon/joblist/hashjoin.h new file mode 100644 index 00000000..92452c2b --- /dev/null +++ b/dbcon/joblist/hashjoin.h @@ -0,0 +1,308 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// +// $Id: hashjoin.h 8436 2012-04-04 18:18:21Z rdempsey $ +// C++ Interface: hashjoin +// +// Description: +// +// +// Author: Patrick , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// + +#ifndef HASHJOIN_H_ +#define HASHJOIN_H_ + +#include "jobstep.h" +#include "calpontsystemcatalog.h" +#include +#include +#include +#include +#include +#include +#include + +namespace joblist +{ + +class HashJoinStep : public JobStep +{ + public: + HashJoinStep(JoinType, uint32_t sessionId, uint32_t statementId, + uint32_t txnId, ResourceManager *); + virtual ~HashJoinStep(); + + void hjRunner(); + + void setLargeSideBPS(BatchPrimitive*); + void setSmallSideCardEst(uint64_t card); + void setLargeSideStepsOut(const std::vector& largeSideSteps); + void setSmallSideStepsOut(const std::vector& smallSideSteps); + void setSizeFlag(bool); // true -> left is smaller, false ->right is smaller + void setAllowLargeSideFifoToDisk(bool);// how handle blocked fifo + + /* mandatory JobStep interface */ + void run(); + void abort(); + void join(); + const JobStepAssociation& inputAssociation() const; + void inputAssociation(const JobStepAssociation& inputAssociation); + const JobStepAssociation& outputAssociation() const; + void outputAssociation(const JobStepAssociation& outputAssociation); + const std::string toString() const; + void stepId(uint16_t stepId); + uint16_t stepId() const; + uint32_t sessionId() const; + uint32_t txnId() const; + uint32_t statementId() const; + void logger(const SPJL& logger); + + execplan::CalpontSystemCatalog::OID tableOid() const{return fTableOID2;} + execplan::CalpontSystemCatalog::OID tableOid1()const{return fTableOID1;} + execplan::CalpontSystemCatalog::OID tableOid2()const{return fTableOID2;} + void tableOid1(execplan::CalpontSystemCatalog::OID tableOid1) + { fTableOID1 = tableOid1; } + void tableOid2(execplan::CalpontSystemCatalog::OID tableOid2) + { fTableOID2 = tableOid2; } + + std::string alias1() const { return fAlias1; } + void alias1(const std::string& alias) { fAlias1 = alias; } + std::string alias2() const { return fAlias2; } + void alias2(const std::string& alias) { fAlias = fAlias2 = alias; } + + std::string view1() const { return fView1; } + void view1(const std::string& vw) { fView1 = vw; } + std::string view2() const { return fView2; } + void view2(const std::string& vw) { fView = fView2 = vw; } + + std::map& tbCardMap() + { return fTbCardMap; } + + enum OutputMode { + BOTH, + LEFTONLY, + RIGHTONLY + }; + void setOutputMode(OutputMode); + + enum HashJoinMode { + PM_MEMORY, + UM_MEMORY, + LARGE_HASHJOIN_CARD, + LARGE_HASHJOIN_RUNTIME + }; + HashJoinMode hashJoinMode() const { return fHashJoinMode; } + bool didOutputAssocUseDisk(unsigned int index) const; + + /* Store BucketReuse info in case it can be used during LHJ */ + void addBucketReuse(FifoDataList* pFifoDL, + const std::string& filterString, + execplan::CalpontSystemCatalog::OID tblOid, + execplan::CalpontSystemCatalog::OID colOid, + uint32_t verId, + execplan::CalpontSystemCatalog::TableColName& colName); + double getUmMemoryTime() { return fElapsedTimes[WAIT_FOR_UMMEMORY].second + fElapsedTimes[RETURN_UNUSED_MEMORY].second + fElapsedTimes[RETURN_USED_MEMORY].second; } + + private: + HashJoinStep(); + HashJoinStep(const HashJoinStep &); + HashJoinStep & operator=(const HashJoinStep &); + + void errorLogging(const std::string& msg) const; + void startAdjoiningSteps(); + bool outputLargeSide(FifoDataList *largeDL, + uint largeIt, + bool sendLarge, + bool sendSmall, + FifoDataList *largeOut, + DataList_t *largeOutDL, + uint64_t *largeCount); + void outputSmallSide(bool sendSmall, + bool sendAllSmallSide, + FifoDataList *smallOut, + DataList_t *smallOutDL, + uint64_t *smallCount); + + /* large hash join fcns */ + void performLargeHashJoin( + FifoDataList* smallDL, + uint smallIt); + void buildLhjInJsa( + const AnyDataListSPtr& anyDl1, + JobStep* jobStep2, + JobStepAssociation& newJsa1); + void buildLhjOutJsa( + const AnyDataListSPtr& anyDl1, + std::vector& jobSteps2, + JobStepAssociation& newJsa1, + bool dropInserts); + void printJSA( + const char* label, + const JobStepAssociation& jsa); + void initiateBucketReuse( unsigned int idx ); + + /* functions used when we have to cache large-side FIFO to disk */ + bool checkIfFifoBlocked(FifoDataList *largeOut); + void outputLargeSideFifoToDisk( + FifoDataList *largeDL, + uint largeIt, + uint64_t *largeCount, + FifoDataList *largeOut); + void writeRowGroupToDisk(const UintRowGroup &rg); + void createTempFile(); + std::string getFilename(); + void outputLargeSideFifoFromDisk(FifoDataList *largeOut); + bool readRowGroupFromDisk(UintRowGroup *rg); + + /* enum and functions to track elapsed times */ + enum HjElapsedTime { + READ_SMALL_SIDE = 0, // time to read small-side + WRITE_SMALL_SIDE = 1, // time to write small-side + WAIT_FOR_LARGE_SIDE = 2, // time waiting for 1st L-side read + RW_LARGE_SIDE_DL = 3, // time to read/write L-side datalist + LARGE_SIDE_FIFO_TO_DISK = 4, // time to save L-side fifo to disk + LARGE_SIDE_FIFO_FROM_DISK = 5, // time to get L-side fifo from disk + START_OTHER_STEPS = 6, // time to startup adjacent jobsteps + WAIT_FOR_UMMEMORY = 7, // time waiting for ummemory from Resource Manager + RETURN_UNUSED_MEMORY = 8, // time to return unused memory to Resource Manager + RETURN_USED_MEMORY = 9, // time to return used memory to Resource Manager + NUM_ELAPSED_TIMES // last enumeration value + 1 + }; + void startElapsedTime(HjElapsedTime whichTimeToStart); + void stopElapsedTime (HjElapsedTime whichTimeToStop); + + /* data members... */ + JobStepAssociation inJSA; + JobStepAssociation outJSA; + + JoinType joinType; + uint32_t sessionID; + uint32_t stepID; + uint32_t statementID; + uint32_t txnID; + ResourceManager *resourceManager; + bool sizeFlag; + bool fAllowLargeSideFifoToDisk; + OutputMode om; + uint64_t leftCount, rightCount; + SPJL fLogger; + + boost::shared_ptr joiner; + BatchPrimitive* bps; + uint64_t fSmallCardinalityEstimate; + std::vector fSmallSideStepsOut; + std::vector fLargeSideStepsOut; + uint64_t fUMThreshold, fPMThreshold; + LargeHashJoin* fLhjStep; + HashJoinMode fHashJoinMode; + + struct HJRunner { + HJRunner(HashJoinStep *hj) : HJ(hj) { } + void operator()() { HJ->hjRunner(); } + HashJoinStep *HJ; + }; + boost::shared_ptr mainRunner; + + struct HJSmallSideWriter { + HJSmallSideWriter(HashJoinStep* hj, bool sendSmall, + bool sendAllSmallSide, + FifoDataList *smallOut, + DataList_t *smallOutDL, + uint64_t *smallCount) : HJ(hj), + fSendSmall(sendSmall), + fSendAllSmallSide(sendAllSmallSide), + fSmallOut(smallOut), + fSmallOutDL(smallOutDL), + fSmallCount(smallCount) { } + void operator()() { HJ->outputSmallSide( fSendSmall, fSendAllSmallSide, + fSmallOut, fSmallOutDL, fSmallCount ); } + HashJoinStep *HJ; + bool fSendSmall; + bool fSendAllSmallSide; + FifoDataList *fSmallOut; + DataList_t *fSmallOutDL; + uint64_t *fSmallCount; + }; + boost::shared_ptr smallSideWriter; + + execplan::CalpontSystemCatalog::OID fTableOID1; + execplan::CalpontSystemCatalog::OID fTableOID2; + + std::string fAlias1; + std::string fAlias2; + + std::string fView1; + std::string fView2; + + std::map fTbCardMap; + + /* tracks elapsed times. */ + /* ".first" is current timer start, ".second" is elapsed time */ + std::pair fElapsedTimes[NUM_ELAPSED_TIMES]; + + /* data members relating to FIFO caching to temp disk */ + enum CompressionMode // denotes how data is stored in FIFO temp disk + { + COMPRESS_NONE = 1, // no compression, leave as 64bitRID , 64bitVal + COMPRESS_64_32 = 2, // compress to 64bit RID, 32 bit value + COMPRESS_32_64 = 3, // compress to 32bit RID, 64 bit value + COMPRESS_32_32 = 4, // compress to 32bit RID, 32 bit value + COMPRESS_64 = 5, // compress to 64bit RID only + COMPRESS_32 = 6 // compress to 32bit RID only + }; + std::string fTempFilePath; // dir path of temp file + std::string fFilename; // filename of temp file + std::fstream fFile; // fstream used to write temp file + uint64_t fFilenameCounter; // counter used in temp file name + CompressionMode fCompMode; // how data is stored on temp disk + boost::shared_ptr fCompBuffer;// temp buffer used for compression + + /* data members relating to BucketReuse; only applicable to LHJ */ + struct BucketReuseParms + { + BucketReuseParms() : fBucketReuseEntry(0), + fReadOnly(false), + fStep(0), + fStepUsing(false), + fColOid(0), + fTblOid(0), + fVerId(0) { } + BucketReuseControlEntry* fBucketReuseEntry; + bool fReadOnly; + BucketReuseStep* fStep; + bool fStepUsing; + execplan::CalpontSystemCatalog::OID fColOid; + execplan::CalpontSystemCatalog::OID fTblOid; + uint32_t fVerId; + execplan::CalpontSystemCatalog::TableColName fColName; + std::string fFilterString; + }; + BucketReuseParms fBucketReuseParms[2]; + uint64_t fumMemory; + uint64_t fpmMemory; + uint64_t fhjMemory; + +}; + +} + +#endif diff --git a/dbcon/joblist/jl_logger.cpp b/dbcon/joblist/jl_logger.cpp index 85c68898..358a78ca 100644 --- a/dbcon/joblist/jl_logger.cpp +++ b/dbcon/joblist/jl_logger.cpp @@ -16,14 +16,12 @@ MA 02110-1301, USA. */ /* - * $Id: jl_logger.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: jl_logger.cpp 8436 2012-04-04 18:18:21Z rdempsey $ */ #include using namespace std; -#include - #include "messageobj.h" #include "messageids.h" #include "loggingid.h" @@ -31,12 +29,6 @@ using namespace logging; #include "jl_logger.h" -namespace -{ -boost::mutex logMutex; -}; - - namespace joblist { @@ -58,15 +50,8 @@ Logger::Logger() : fLogId(5), fImpl->msgMap(msgMap); } -void catchHandler(const string& ex, int c, SErrorInfo& ei, unsigned sid, logging::LOG_TYPE level) +void catchHandler(const string& ex, unsigned sid, logging::LOG_TYPE level) { - boost::mutex::scoped_lock lk(logMutex); - if (ei->errCode == 0) - { - ei->errMsg = ex; - ei->errCode = c; - } - Logger log; log.setLoggingSession(sid); log.logMessage(level, ex); diff --git a/dbcon/joblist/jl_logger.h b/dbcon/joblist/jl_logger.h index 7b85893a..0638d848 100644 --- a/dbcon/joblist/jl_logger.h +++ b/dbcon/joblist/jl_logger.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: jl_logger.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: jl_logger.h 8436 2012-04-04 18:18:21Z rdempsey $ */ /** @file */ @@ -32,7 +32,6 @@ #include "errorids.h" #include "logger.h" #include "errorcodes.h" -#include "errorinfo.h" #include "exceptclasses.h" namespace joblist @@ -82,7 +81,7 @@ class Logger }; typedef boost::shared_ptr SPJL; -void catchHandler(const std::string& s, int c, SErrorInfo& errorInfo, unsigned sid = 0, +void catchHandler(const std::string& s, unsigned sid = 0, logging::LOG_TYPE = logging::LOG_TYPE_CRITICAL); } diff --git a/dbcon/joblist/jlf_common.cpp b/dbcon/joblist/jlf_common.cpp index ec4b8346..245fdb25 100644 --- a/dbcon/joblist/jlf_common.cpp +++ b/dbcon/joblist/jlf_common.cpp @@ -15,12 +15,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_common.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: jlf_common.cpp 8862 2012-09-07 14:38:08Z xlou $ #include "calpontsystemcatalog.h" #include "aggregatecolumn.h" -#include "pseudocolumn.h" #include "simplecolumn.h" using namespace std; using namespace execplan; @@ -42,36 +41,35 @@ namespace { // @brief Returns unique key for a column, table, or expresssion. -uint32_t uniqTupleKey(JobInfo& jobInfo, - CalpontSystemCatalog::OID& o, - CalpontSystemCatalog::OID& t, - const string& cn, - const string& ca, - const string& tn, - const string& ta, - const string& sn, - const string& vw, - uint32_t pi, - uint64_t en, - bool correlated=false) +uint uniqTupleKey(JobInfo& jobInfo, + CalpontSystemCatalog::OID& o, + CalpontSystemCatalog::OID& t, + const string& cn, + const string& ca, + const string& tn, + const string& ta, + const string& sn, + const string& vw, + uint64_t en, + bool correlated=false) { uint64_t subId = jobInfo.subId; if (correlated) - subId = jobInfo.pJobInfo->subId; - + subId = jobInfo.pSubId; + string alias(ta); // if (!ca.empty()) // alias += "." + ca; string nm(ta); if (!cn.empty()) nm += "." + cn; - UniqId id(o, ta, sn, vw, pi, subId); + UniqId id(o, ta, sn, vw, subId); TupleKeyMap::iterator iter = jobInfo.keyInfo->tupleKeyMap.find(id); if (iter != jobInfo.keyInfo->tupleKeyMap.end()) return iter->second; - uint32_t newId = jobInfo.keyInfo->nextKey++; -//cout << "new id: " << newId << " -- " << o << ", " << pi << ", " << nm << ", " << vw << ", " << sn << ", " << subId << endl; + uint newId = jobInfo.keyInfo->nextKey++; +//cout << "new id: " << newId << " -- " << o << ", " << nm << ", " << vw << ", " << sn << ", " << subId << endl; jobInfo.keyInfo->tupleKeyMap[id] = newId; jobInfo.keyInfo->tupleKeyVec.push_back(id); jobInfo.keyInfo->tupleKeyToTableOid.insert(make_pair(newId, t)); @@ -128,7 +126,7 @@ uint32_t uniqTupleKey(JobInfo& jobInfo, // @brief Returns a suitably fudged column width -uint32_t fudgeWidth(const CalpontSystemCatalog::ColType& ict, CalpontSystemCatalog::OID oid) +uint fudgeWidth(const CalpontSystemCatalog::ColType& ict, CalpontSystemCatalog::OID oid) { CalpontSystemCatalog::OID dictOid = isDictCol(ict); CalpontSystemCatalog::ColType ct = ict; @@ -156,64 +154,80 @@ uint32_t fudgeWidth(const CalpontSystemCatalog::ColType& ict, CalpontSystemCatal // @brief Set some tuple info TupleInfo setTupleInfo_(const CalpontSystemCatalog::ColType& ct, - CalpontSystemCatalog::OID col_oid, - JobInfo& jobInfo, - CalpontSystemCatalog::OID tbl_oid, - const string& col_name, - const string& col_alias, - const string& sch_name, - const string& tbl_name, - const string& tbl_alias, - const string& vw_name, - bool correlated = false, - uint32_t pc_id = 0, - uint64_t engine = 0) + CalpontSystemCatalog::OID col_oid, + JobInfo& jobInfo, + CalpontSystemCatalog::OID tbl_oid, + const string& col_name, + const string& col_alias, + const string& sch_name, + const string& tbl_name, + const string& tbl_alias, + const string& vw_name, + uint64_t engine = 0, + bool correlated = false) { // get the unique tupleOids for this column - uint32_t tbl_key = uniqTupleKey(jobInfo, tbl_oid, tbl_oid, "", "", tbl_name, tbl_alias, - sch_name, vw_name, 0, engine, correlated); - uint32_t col_key = uniqTupleKey(jobInfo, col_oid, tbl_oid, col_name, col_alias, tbl_name, - tbl_alias, sch_name, vw_name, pc_id, engine, correlated); + uint tbl_key = uniqTupleKey(jobInfo, tbl_oid, tbl_oid, "", "", tbl_name, tbl_alias, + sch_name, vw_name, engine, correlated); + uint col_key = uniqTupleKey(jobInfo, col_oid, tbl_oid, col_name, col_alias, tbl_name, tbl_alias, + sch_name, vw_name, engine, correlated); + TupleInfo ti = TupleInfo(fudgeWidth(ct, col_oid), col_oid, col_key, tbl_key, + ct.scale, ct.precision, ct.colDataType); //If this is the first time we've seen this col, add it to the tim - TupleInfoMap::iterator it = jobInfo.keyInfo->tupleInfoMap.find(col_key); - TupleInfo ti; - if (it != jobInfo.keyInfo->tupleInfoMap.end()) + TupleInfoMap::iterator i1; + TupleInfoMap::mapped_type v; + i1 = jobInfo.keyInfo->tupleInfoMap.find(tbl_key); + if (i1 != jobInfo.keyInfo->tupleInfoMap.end()) { - //We've seen the key - ti = it->second; + //We've seen the table, now look for the col + v = i1->second; + TupleInfoMap::mapped_type::iterator it2 = v.begin(); + TupleInfoMap::mapped_type::iterator end2 = v.end();; + bool found = false; + while (it2 != end2) + { + if (it2->key == ti.key) + { + found = true; + ti = *it2; + break; + } + ++it2; + } + + if (!found) + { + v.push_back(ti); + i1->second = v; + jobInfo.keyInfo->colKeyToTblKey[col_key] = tbl_key; + jobInfo.keyInfo->colType[col_key] = ct; + } } else { //Haven't even seen the table yet, much less this col - ti = TupleInfo(fudgeWidth(ct, col_oid), col_oid, col_key, tbl_key, - ct.scale, ct.precision, ct.colDataType); - jobInfo.keyInfo->tupleInfoMap[col_key] = ti; + v.push_back(ti); + jobInfo.keyInfo->tupleInfoMap[tbl_key] = v; jobInfo.keyInfo->colKeyToTblKey[col_key] = tbl_key; - jobInfo.keyInfo->colKeyToTblKey[tbl_key] = tbl_key; jobInfo.keyInfo->colType[col_key] = ct; - jobInfo.keyInfo->pseudoType[col_key] = pc_id; } - if (pc_id > 0 && jobInfo.pseudoColTable.find(tbl_key) == jobInfo.pseudoColTable.end()) - jobInfo.pseudoColTable.insert(tbl_key); - return ti; } -uint32_t getTupleKey_(const JobInfo& jobInfo, +uint getTupleKey_(const JobInfo& jobInfo, CalpontSystemCatalog::OID oid, const string& colName, const string& tblAlias, const string& schema, const string& view, - bool correlated = false, - uint32_t pseudo = 0, - uint64_t engine = 0) + uint64_t engine = 0, + bool correlated = false) { uint64_t subId = jobInfo.subId; if (correlated) - subId = jobInfo.pJobInfo->subId; + subId = jobInfo.pSubId; string alias(tblAlias); string name(tblAlias); @@ -221,7 +235,7 @@ uint32_t getTupleKey_(const JobInfo& jobInfo, name += "." + colName; // if (!colAlias.empty()) // alias += "." + colAlias; - UniqId id(oid, tblAlias, schema, view, pseudo, subId); + UniqId id(oid, tblAlias, schema, view, subId); TupleKeyMap::const_iterator iter = jobInfo.keyInfo->tupleKeyMap.find(id); if (iter != jobInfo.keyInfo->tupleKeyMap.end()) return iter->second; @@ -247,7 +261,7 @@ uint32_t getTupleKey_(const JobInfo& jobInfo, throw logic_error("column is not found in info map."); } - return static_cast(-1); + return static_cast(-1); } } @@ -261,12 +275,8 @@ UniqId::UniqId(const execplan::SimpleColumn* sc) : fTable(extractTableAlias(sc)), fSchema(sc->schemaName()), fView(sc->viewName()), - fPseudo(0), fSubId(-1) { - const PseudoColumn* pc = dynamic_cast(sc); - uint32_t pseudoType = (pc) ? pc->pseudoType() : execplan::PSEUDO_UNKNOWN; - fPseudo = pseudoType; } @@ -276,21 +286,11 @@ UniqId::UniqId(int o, const execplan::SimpleColumn* sc) : fTable(extractTableAlias(sc)), fSchema(sc->schemaName()), fView(sc->viewName()), - fPseudo(0), fSubId(-1) { } -string UniqId::toString() const -{ - ostringstream strstm; - strstm << fId << ":" << fTable << ":" << fSchema << ":" << fView << ":" - << fPseudo << ":" << (int64_t)fSubId; - return strstm.str(); -} - - //------------------------------------------------------------------------------ // Returns the table alias for the specified column //------------------------------------------------------------------------------ @@ -299,7 +299,6 @@ string extractTableAlias(const SimpleColumn* sc) return ba::to_lower_copy(sc->tableAlias()); } - //------------------------------------------------------------------------------ // Returns the table alias for the specified column //------------------------------------------------------------------------------ @@ -308,7 +307,6 @@ string extractTableAlias(const SSC& sc) return ba::to_lower_copy(sc->tableAlias()); } - //------------------------------------------------------------------------------ // Returns OID associated with colType if it is a dictionary column, else // the value returned for the OID is 0. @@ -324,7 +322,6 @@ CalpontSystemCatalog::OID isDictCol(const CalpontSystemCatalog::ColType& colType return 0; } - //------------------------------------------------------------------------------ // Determines if colType is a character column //------------------------------------------------------------------------------ @@ -345,7 +342,6 @@ bool isCharCol(const CalpontSystemCatalog::ColType& colType) return false; } - //------------------------------------------------------------------------------ // Returns OID associated with a table //------------------------------------------------------------------------------ @@ -362,126 +358,46 @@ CalpontSystemCatalog::OID tableOid(const SimpleColumn* sc, boost::shared_ptr(sc); - uint32_t pseudoType = (pc) ? pc->pseudoType() : execplan::PSEUDO_UNKNOWN; return getTupleKey_(jobInfo, sc->oid(), sc->columnName(), extractTableAlias(sc), - sc->schemaName(), sc->viewName(), - ((sc->joinInfo() & execplan::JOIN_CORRELATED) != 0), - pseudoType, (sc->isInfiniDB() ? 0 : 1)); -} - - -uint32_t getTupleKey(JobInfo& jobInfo, const SRCP& srcp, bool add) -{ - int key = -1; - - if (add) - { - // setTupleInfo first if add is ture, ok if already set. - const SimpleColumn* sc = dynamic_cast(srcp.get()); - if (sc != NULL) - { - if (sc->schemaName().empty()) - { - SimpleColumn tmp(*sc, jobInfo.sessionId); - tmp.oid(tableOid(sc, jobInfo.csc) + 1 + sc->colPosition()); - key = getTupleKey(jobInfo, &tmp); // sub-query should be there - } - else - { - CalpontSystemCatalog::ColType ct = sc->colType(); - string alias(extractTableAlias(sc)); - CalpontSystemCatalog::OID tblOid = tableOid(sc, jobInfo.csc); - TupleInfo ti(setTupleInfo(ct, sc->oid(), jobInfo, tblOid, sc, alias)); - key = ti.key; - - CalpontSystemCatalog::OID dictOid = isDictCol(ct); - if (dictOid > 0) - { - ti = setTupleInfo(ct, dictOid, jobInfo, tblOid, sc, alias); - jobInfo.keyInfo->dictKeyMap[key] = ti.key; - key = ti.key; - } - } - } - else - { - CalpontSystemCatalog::ColType ct = srcp->resultType(); - TupleInfo ti(setExpTupleInfo(ct, srcp->expressionId(), srcp->alias(), jobInfo)); - key = ti.key; - } - } - else - { - // TupleInfo is expected to be set already - const SimpleColumn* sc = dynamic_cast(srcp.get()); - if (sc != NULL) - { - if (sc->schemaName().empty()) - { - SimpleColumn tmp(*sc, jobInfo.sessionId); - tmp.oid(tableOid(sc, jobInfo.csc) + 1 + sc->colPosition()); - key = getTupleKey(jobInfo, &tmp); - } - else - { - key = getTupleKey(jobInfo, sc); - } - - // check if this is a dictionary column - if (jobInfo.keyInfo->dictKeyMap.find(key) != jobInfo.keyInfo->dictKeyMap.end()) - key = jobInfo.keyInfo->dictKeyMap[key]; - } - else - { - key = getExpTupleKey(jobInfo, srcp->expressionId()); - } - } - - return key; + sc->schemaName(), sc->viewName(), (sc->isInfiniDB() ? 0 : 1), + ((sc->joinInfo() & execplan::JOIN_CORRELATED) != 0)); } +//uint getTupleKey(const JobInfo& jobInfo, CalpontSystemCatalog::OID oid, const string& colName, +// const string& tblAlias, const string& schema, const string& view) +//{ +// return getTupleKey_(jobInfo, oid, colName, tblAlias, schema, view); +//} -uint32_t getTableKey(const JobInfo& jobInfo, execplan::CalpontSystemCatalog::OID tableOid, - const string& alias, const string& schema, const string& view) +uint getTableKey(const JobInfo& jobInfo, execplan::CalpontSystemCatalog::OID tableOid, + const string& alias, const string& schema, const string& view) { return getTupleKey_(jobInfo, tableOid, "", alias, schema, view); } - -uint32_t getTableKey(const JobInfo& jobInfo, uint32_t cid) +uint getTableKey(const JobInfo& jobInfo, uint cid) { return jobInfo.keyInfo->colKeyToTblKey[cid]; } - -void updateTableKey(uint32_t cid, uint32_t tid, JobInfo& jobInfo) -{ - jobInfo.keyInfo->colKeyToTblKey[cid] = tid; -} - - -uint32_t getTableKey(JobInfo& jobInfo, JobStep* js) +uint getTableKey(JobInfo& jobInfo, JobStep* js) { CalpontSystemCatalog::OID tableOid = js->tableOid(); return getTupleKey_(jobInfo, tableOid, "", js->alias(), js->schema(), js->view()); } - -uint32_t makeTableKey(JobInfo& jobInfo, const execplan::SimpleColumn* sc) +uint makeTableKey(JobInfo& jobInfo, const execplan::SimpleColumn* sc) { CalpontSystemCatalog::OID o = tableOid(sc, jobInfo.csc); - return uniqTupleKey(jobInfo, o, o, "", "", sc->tableName(), extractTableAlias(sc), - sc->schemaName(), sc->viewName(), 0, (sc->isInfiniDB() ? 0 : 1), - ((sc->joinInfo() & execplan::JOIN_CORRELATED) != 0)); + return uniqTupleKey(jobInfo, o, o, "", "", "", extractTableAlias(sc), + sc->schemaName(), sc->viewName(), (sc->isInfiniDB() ? 0 : 1), + ((sc->joinInfo() & execplan::JOIN_CORRELATED) != 0)); } - -uint32_t makeTableKey(JobInfo& jobInfo, +uint makeTableKey(JobInfo& jobInfo, CalpontSystemCatalog::OID o, const string& tn, const string& ta, @@ -489,15 +405,23 @@ uint32_t makeTableKey(JobInfo& jobInfo, const string& vn, uint64_t en) { - return uniqTupleKey(jobInfo, o, o, "", "", tn, ta, sn, vn, 0, en); + return uniqTupleKey(jobInfo, o, o, "", "", tn, ta, sn, vn, en); } - -TupleInfo getTupleInfo(uint32_t columnKey, const JobInfo& jobInfo) +TupleInfo getTupleInfo(uint tableKey, uint columnKey, const JobInfo& jobInfo) { - TupleInfoMap::const_iterator cit = jobInfo.keyInfo->tupleInfoMap.find(columnKey); - if ((cit == jobInfo.keyInfo->tupleInfoMap.end()) || - (cit->second.dtype == CalpontSystemCatalog::BIT)) + TupleInfoMap::const_iterator cit = jobInfo.keyInfo->tupleInfoMap.find(tableKey); + assert (cit != jobInfo.keyInfo->tupleInfoMap.end()); + TupleInfoMap::mapped_type mt = cit->second; + TupleInfoMap::mapped_type::iterator mtit = mt.begin(); + while (mtit != mt.end()) + { + if (mtit->key == columnKey) + break; + ++mtit; + } + + if (mtit == mt.end()) { ostringstream strstm; strstm << "TupleInfo for (" << jobInfo.keyInfo->tupleKeyVec[columnKey].fId << "," @@ -515,10 +439,9 @@ TupleInfo getTupleInfo(uint32_t columnKey, const JobInfo& jobInfo) throw runtime_error("column's tuple info could not be found"); } - return cit->second; + return *mtit; } - TupleInfo setTupleInfo(const execplan::CalpontSystemCatalog::ColType& ct, execplan::CalpontSystemCatalog::OID col_oid, JobInfo& jobInfo, @@ -526,57 +449,43 @@ TupleInfo setTupleInfo(const execplan::CalpontSystemCatalog::ColType& ct, const execplan::SimpleColumn* sc, const string& alias) { - const PseudoColumn* pc = dynamic_cast(sc); - uint32_t pseudoType = (pc) ? pc->pseudoType() : execplan::PSEUDO_UNKNOWN; return setTupleInfo_(ct, col_oid, jobInfo, tbl_oid, sc->columnName(), sc->alias(), - sc->schemaName(), sc->tableName(), alias, sc->viewName(), - ((sc->joinInfo() & execplan::JOIN_CORRELATED) != 0), - pseudoType, (sc->isInfiniDB() ? 0 : 1)); + sc->schemaName(), sc->tableName(), alias, sc->viewName(), + (sc->isInfiniDB() ? 0 : 1), + ((sc->joinInfo() & execplan::JOIN_CORRELATED) != 0)); } - TupleInfo setExpTupleInfo(const execplan::CalpontSystemCatalog::ColType& ct, uint64_t expressionId, - const string& alias, JobInfo& jobInfo, bool cr) + const string& alias, JobInfo& jobInfo) { - // pretend all expressions belong to "virtual" table EXPRESSION, (CNX_EXP_TABLE_ID, expression) - // CNX_EXP_TABLE_ID(999) is not for user table or column, there will be no confilict in queries. - JobInfo* ji = &jobInfo; - if (cr) - ji = jobInfo.pJobInfo; - - string expAlias("$exp"); - if (!(ji->subAlias.empty())) - expAlias = ji->subAlias; - - return setTupleInfo_( - ct, expressionId, jobInfo, CNX_EXP_TABLE_ID, "", alias, "", "$exp", expAlias, "", cr); + // pretend all expressions belong to "virtual" table EXPRESSION, (3000, expression) + // OID 3000 is not for user table or column, there will be no confilict in queries. + stringstream ss; + ss << "$exp"; + if (jobInfo.subLevel > 0) + ss << "_" << jobInfo.subId << "_" << jobInfo.subLevel << "_" << jobInfo.subNum; + return setTupleInfo_(ct, expressionId, jobInfo, 3000, "", alias, "", "$exp", ss.str(), ""); } - -TupleInfo setExpTupleInfo(const execplan::ReturnedColumn* rc, JobInfo& jobInfo) +uint getExpTupleKey(const JobInfo& jobInfo, uint64_t eid) { - return setExpTupleInfo(rc->resultType(), rc->expressionId(), rc->alias(), jobInfo, - ((rc->joinInfo() & execplan::JOIN_CORRELATED) != 0)); + stringstream ss; + ss << "$exp"; + if (jobInfo.subLevel > 0) + ss << "_" << jobInfo.subId << "_" << jobInfo.subLevel << "_" << jobInfo.subNum; + return getTupleKey_(jobInfo, eid, "", ss.str(), "", ""); } - -uint32_t getExpTupleKey(const JobInfo& jobInfo, uint64_t eid, bool cr) +TupleInfo getExpTupleInfo(uint expKey, const JobInfo& jobInfo) { - const JobInfo* ji = &jobInfo; - if (cr) - ji = jobInfo.pJobInfo; - - string expAlias("$exp"); - if (!(ji->subAlias.empty())) - expAlias = ji->subAlias; - - return getTupleKey_(jobInfo, eid, "", expAlias, "", "", cr); + // first retrieve the expression virtual table key + uint evtKey = getExpTupleKey(jobInfo, 3000); + return getTupleInfo(evtKey, expKey, jobInfo); } - void addAggregateColumn(AggregateColumn* agc, int idx, RetColsVector& vec, JobInfo& jobInfo) { - uint32_t eid = agc->expressionId(); + uint eid = agc->expressionId(); setExpTupleInfo(agc->resultType(), eid, agc->alias(), jobInfo); vector >::iterator i; @@ -620,21 +529,17 @@ bool operator < (const struct UniqId& x, const struct UniqId& y) (x.fId == y.fId && x.fTable == y.fTable && x.fSchema < y.fSchema) || (x.fId == y.fId && x.fTable == y.fTable && x.fSchema == y.fSchema && x.fView < y.fView) || (x.fId == y.fId && x.fTable == y.fTable && x.fSchema == y.fSchema && x.fView == y.fView && - x.fPseudo < y.fPseudo) || - (x.fId == y.fId && x.fTable == y.fTable && x.fSchema == y.fSchema && x.fView == y.fView && - x.fPseudo == y.fPseudo && x.fSubId < y.fSubId)); + x.fSubId < y.fSubId)); } bool operator == (const struct UniqId& x, const struct UniqId& y) { - return ( - x.fId == y.fId && - x.fTable == y.fTable && - x.fSchema == y.fSchema && - x.fView == y.fView && - x.fPseudo == y.fPseudo && - x.fSubId == y.fSubId); + return (x.fId == y.fId && + x.fTable == y.fTable && + x.fSchema == y.fSchema && + x.fView == y.fView && + x.fSubId == y.fSubId); } @@ -682,105 +587,6 @@ bool filterWithDictionary(execplan::CalpontSystemCatalog::OID dictOid, uint64_t } -// @Bug 1230 & 1955 -// Don't allow join/compare on "incompatible" cols -// Compatible columns: -// any 1,2,4,8-byte int to any 1,2,4,8-byte int -// decimal w/scale x to decimal w/scale x -// date to date -// datetime to datetime -// string to string -bool compatibleColumnTypes(const CalpontSystemCatalog::ColType& ct1, - const CalpontSystemCatalog::ColType& ct2, - bool forJoin) -{ - return compatibleColumnTypes(ct1.colDataType, ct1.scale, ct2.colDataType, ct2.scale, forJoin); -} - - -bool compatibleColumnTypes(const CalpontSystemCatalog::ColDataType& dt1, uint32_t scale1, - const CalpontSystemCatalog::ColDataType& dt2, uint32_t scale2, - bool forJoin) -{ - // disable VARBINARY used in join - if (dt1 == CalpontSystemCatalog::VARBINARY || - dt2 == CalpontSystemCatalog::VARBINARY) - throw runtime_error("Comparsion between VARBINARY columns is not supported."); - - switch (dt1) - { - case CalpontSystemCatalog::BIT: - if (dt2 != CalpontSystemCatalog::BIT) return false; - break; - case CalpontSystemCatalog::TINYINT: - case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::MEDINT: - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::UDECIMAL: - if (dt2 != CalpontSystemCatalog::TINYINT && - dt2 != CalpontSystemCatalog::SMALLINT && - dt2 != CalpontSystemCatalog::MEDINT && - dt2 != CalpontSystemCatalog::INT && - dt2 != CalpontSystemCatalog::BIGINT && - dt2 != CalpontSystemCatalog::DECIMAL && - dt2 != CalpontSystemCatalog::UTINYINT && - dt2 != CalpontSystemCatalog::USMALLINT && - dt2 != CalpontSystemCatalog::UMEDINT && - dt2 != CalpontSystemCatalog::UINT && - dt2 != CalpontSystemCatalog::UBIGINT && - dt2 != CalpontSystemCatalog::UDECIMAL) return false; - if (scale2 != scale1) return false; - break; - case CalpontSystemCatalog::DATE: - if (dt2 != CalpontSystemCatalog::DATE) return false; - break; - case CalpontSystemCatalog::DATETIME: - if (dt2 != CalpontSystemCatalog::DATETIME) return false; - break; - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - // @bug 1495 compound/string join - if (dt2 != CalpontSystemCatalog::VARCHAR && - dt2 != CalpontSystemCatalog::CHAR) - return false; - break; - case CalpontSystemCatalog::VARBINARY: - if (dt2 != CalpontSystemCatalog::VARBINARY) return false; - break; - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - if (forJoin && (dt2 != CalpontSystemCatalog::FLOAT && - dt2 != CalpontSystemCatalog::FLOAT)) return false; - else if (dt2 != CalpontSystemCatalog::FLOAT && - dt2 != CalpontSystemCatalog::DOUBLE && - dt2 != CalpontSystemCatalog::UFLOAT && - dt2 != CalpontSystemCatalog::UDOUBLE) return false; - break; - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - if (forJoin && (dt2 != CalpontSystemCatalog::DOUBLE && - dt2 != CalpontSystemCatalog::UDOUBLE)) return false; - else if (dt2 != CalpontSystemCatalog::FLOAT && - dt2 != CalpontSystemCatalog::DOUBLE && - dt2 != CalpontSystemCatalog::UFLOAT && - dt2 != CalpontSystemCatalog::UDOUBLE) return false; - break; - default: - return false; - break; - } - - return true; -} - - } // vim:ts=4 sw=4: diff --git a/dbcon/joblist/jlf_common.h b/dbcon/joblist/jlf_common.h index ce0f3d15..d9b8cff1 100644 --- a/dbcon/joblist/jlf_common.h +++ b/dbcon/joblist/jlf_common.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_common.h 9702 2013-07-17 19:08:07Z xlou $ +// $Id: jlf_common.h 9704 2013-07-17 19:18:23Z xlou $ /** @file jlf_common.h @@ -31,7 +31,6 @@ #include #include -#include #include "calpontexecutionplan.h" #include "calpontselectexecutionplan.h" @@ -48,11 +47,9 @@ #include "resourcemanager.h" #include "rowgroup.h" -// forward reference namespace execplan { class AggregateColumn; -class SimpleColumn; } @@ -66,23 +63,19 @@ const int8_t CONST_COL_NONE = 0; const int8_t CONST_COL_EXIST = 1; const int8_t CONST_COL_ONLY = 2; -// pretend all expressions belong to "virtual" table EXPRESSION, (CNX_EXP_TABLE_ID, expression) -// CNX_EXP_TABLE_ID(999) is not for user table or column, there will be no confilict in queries. -const int32_t CNX_EXP_TABLE_ID = 999; - struct TupleInfo { - TupleInfo(uint32_t w=0, uint32_t o=0, uint32_t k=-1, uint32_t t=-1, uint32_t s=0, uint32_t p=0, - execplan::CalpontSystemCatalog::ColDataType dt=execplan::CalpontSystemCatalog::BIT) : + TupleInfo(uint w=0, uint o=0, uint k=-1, uint t=-1, uint s=0, uint p=0, + execplan::CalpontSystemCatalog::ColDataType dt=execplan::CalpontSystemCatalog::BIGINT) : width(w), oid(o), key(k), tkey(t), scale(s), precision(p), dtype(dt) { } ~TupleInfo() { } - uint32_t width; - uint32_t oid; - uint32_t key; - uint32_t tkey; - uint32_t scale; - uint32_t precision; + uint width; + uint oid; + uint key; + uint tkey; + uint scale; + uint precision; execplan::CalpontSystemCatalog::ColDataType dtype; }; @@ -90,8 +83,8 @@ struct TupleInfo struct JoinData { int64_t fJoinId; - std::vector fLeftKeys; - std::vector fRightKeys; + std::vector fLeftKeys; + std::vector fRightKeys; std::vector fTypes; // joblisttypes.h: INNER, LEFTOUTER, RIGHTOUTER bool fTypeless; @@ -99,9 +92,13 @@ struct JoinData }; typedef std::stack JobStepVectorStack; +typedef std::set DeliveredTablesSet; typedef std::map DictOidToColOidMap; typedef std::vector TupleInfoVector; -typedef std::map TupleInfoMap; +typedef std::map TupleInfoMap; + +//@bug 598 & 1632 self-join +//typedef std::pair OIDAliasPair; //self-join //for subquery support struct UniqId @@ -111,47 +108,44 @@ struct UniqId std::string fTable; // table name (table alias) std::string fSchema; // schema name std::string fView; // view name - uint32_t fPseudo; // pseudo type // uint64_t fEngine; // InfiniDB == 0 uint64_t fSubId; // subquery ID UniqId() : fId(-1), fSubId(-1) {} - UniqId(int i, const std::string& t, const std::string& s, const std::string& v, - uint32_t pi = 0, uint64_t l=-1) : - fId(i), fTable(t), fSchema(s), fView(v), fPseudo(pi), fSubId(l) {} + UniqId(int i, const std::string& t, const std::string& s, const std::string& v, uint64_t l=-1) : + fId(i), fTable(t), fSchema(s), fView(v), fSubId(l) {} UniqId(const execplan::SimpleColumn* sc); UniqId(int o, const execplan::SimpleColumn* sc); - - std::string toString() const; }; bool operator < (const struct UniqId& x, const struct UniqId& y); bool operator == (const struct UniqId& x, const struct UniqId& y); -typedef std::map TupleKeyMap; +typedef std::map TupleKeyMap; //typedef vector RetColsVector; typedef execplan::CalpontSelectExecutionPlan::ReturnedColumnList RetColsVector; //join data between table pairs -typedef std::map, JoinData> TableJoinMap; +typedef std::map, JoinData> TableJoinMap; +// map, pair > +//typedef std::map, std::pair > TableJoinKeyMap; +//typedef std::map, JoinType> JoinTypeMap; struct TupleKeyInfo { - uint32_t nextKey; + uint32_t nextKey; TupleKeyMap tupleKeyMap; std::vector tupleKeyVec; - std::vector tupleKeyToName; - std::vector crossEngine; - - // TODO: better organize these structs - std::map tupleKeyToTableOid; - std::map colType; - std::map token2DictTypeMap; - std::map keyName; - std::map colKeyToTblKey; - std::map dictKeyMap; // map token key to dictionary key - DictOidToColOidMap dictOidToColOid; // map dictionary OID to column OID - std::map pseudoType; // key to pseudo column type - std::set functionJoinKeys; // key used in function join + std::vector tupleKeyToName; + std::vector crossEngine; + + // TODO: better orgineze this structs + std::map tupleKeyToTableOid; + std::map colType; + std::map token2DictTypeMap; // i/c token only + std::map keyName; + std::map colKeyToTblKey; + std::map dictKeyMap; // map token key to dictionary key + DictOidToColOidMap dictOidToColOid; // map dictionary OID to column OID TupleInfoMap tupleInfoMap; TupleKeyInfo() : nextKey(0) {} @@ -169,6 +163,7 @@ struct JobInfo rm(r), sessionId(0), txnId(0), + verId(0), statementId(0), maxBuckets(rm.getHjMaxBuckets()), maxElems(rm.getHjMaxElems()), @@ -182,6 +177,7 @@ struct JobInfo traceFlags(0), tupleDLMaxSize(rm.getTwMaxSize()), tupleMaxBuckets(rm.getTwMaxBuckets()), +// status(new uint16_t(0)), projectingTableOID(0), isExeMgr(false), trace(false), @@ -189,28 +185,27 @@ struct JobInfo constantCol(CONST_COL_NONE), hasDistinct(false), hasAggregation(false), + hasImplicitGroupBy(false), limitStart(0), limitCount(-1), joinNum(0), subLevel(0), subNum(0), subId(0), - pJobInfo(NULL), + pSubId(-1), constantFalse(false), cntStarPos(-1), - stringScanThreshold(1), - wfqLimitStart(0), - wfqLimitCount(-1) + stringScanThreshold(1) { } ResourceManager& rm; uint32_t sessionId; uint32_t txnId; - BRM::QueryContext verId; + uint32_t verId; uint32_t statementId; - std::string queryType; boost::shared_ptr csc; + DeliveredTablesSet tables; int maxBuckets; - uint64_t maxElems; + uint64_t maxElems; JobStepVectorStack stack; uint32_t flushInterval; uint32_t fifoSize; @@ -226,7 +221,7 @@ struct JobInfo uint32_t traceFlags; uint64_t tupleDLMaxSize; uint32_t tupleMaxBuckets; - SErrorInfo errorInfo; + SErrorInfo status; execplan::CalpontSystemCatalog::OID* projectingTableOID; // DeliveryWSDLs get a reference to this bool isExeMgr; bool trace; @@ -237,6 +232,7 @@ struct JobInfo // aggregation bool hasDistinct; bool hasAggregation; + bool hasImplicitGroupBy; std::vector groupByColVec; std::vector distinctColVec; std::vector expressionVec; @@ -254,7 +250,7 @@ struct JobInfo // In most case, the string is used for return or comparison, so default is false. // when setting to false, no need to check: false overwrites true; // When setting to true, need check: true cannot overwrite false. - std::map tokenOnly; + std::map tokenOnly; // unique ID list of the tables in from clause std::vector tableList; @@ -266,31 +262,28 @@ struct JobInfo JobStepVector crossTableExpressions; JobStepVector returnedExpressions; - // @bug3683, function join - std::vector functionJoins; // store expressions can be converted to joins - // for function on aggregation - RetColsVector deliveredCols; // columns to be sent to connector - RetColsVector nonConstCols; // none constant columns - RetColsVector nonConstDelCols; // delivered none constant columns - RetColsVector projectionCols; // columns for projection + RetColsVector deliveredCols; // columns to be sent to connector + RetColsVector nonConstCols; // none constant columns + RetColsVector nonConstDelCols; // delivered none constant columns + RetColsVector projectionCols; // columns for projection std::multimap cloneAggregateColMap; std::vector > aggEidIndexList; // for AVG to support CNX_USE_DECIMAL_SCALE // map - std::map scaleOfAvg; + std::map scaleOfAvg; // table pairs with incompatible join which is treated as expression - std::map incompatibleJoinMap; + std::map incompatibleJoinMap; // bug 1573 & 3391, having SJSTEP havingStep; JobStepVector havingStepVec; // bug 2634, 5311 and 5374, outjoin and predicates - std::set outerOnTable; - std::set tableHasIsNull; + std::set outerOnTable; + std::set tableHasIsNull; JobStepVector outerJoinExpressions; // bug 3759, join in order @@ -303,9 +296,8 @@ struct JobInfo int subLevel; // subquery level int subNum; // # of subqueries @ level n int subId; // id of current subquery - JobInfo* pJobInfo; // jobinfo of outer query + int pSubId; // id of outer query bool constantFalse; // has constant false filter - std::string subAlias; // unique alias to identify the subquery JobStepVector correlateSteps; JobStepVector selectAndFromSubs; std::set returnColSet; @@ -314,6 +306,9 @@ struct JobInfo // step to process orderby, limit and fill in constants SJSTEP annexStep; + // view ?? workaround + std::string subView; + // @bug3475, aggregate constant column std::map constAggregate; int64_t cntStarPos; // position of count(*) @@ -326,43 +321,13 @@ struct JobInfo GroupConcatInfo groupConcatInfo; // @bug3736, column map - std::map > columnMap; + std::map > columnMap; // @bug3438, joblist for trace/stats JobList* jobListPtr; // just reference, NOT delete by JobInfo // WORKAROUND for join FE limitation (join Id to expression tables map) - std::map > joinFeTableMap; - - uint32_t stringTableThreshold; - - // @bug4531, Window Function support - RetColsVector windowCols; - RetColsVector windowExps; - RetColsVector windowDels; - std::set windowSet; - RetColsVector wfqOrderby; - uint64_t wfqLimitStart; - uint64_t wfqLimitCount; - // workaround for expression of windowfunction in IN/EXISTS sub-query - //std::map exprWinfuncListMap; - - // Flag to tell us we are in local PM only query mode - uint32_t localQuery; - - boost::uuids::uuid uuid; - - // @bug4021, column map for all pseudo column queries - std::map tableColMap; - std::set pseudoColTable; - - /* Disk-based join vars */ - boost::shared_ptr smallSideUsage; - boost::shared_ptr umMemLimit; - int64_t smallSideLimit; // need to get these from a session var in execplan - int64_t largeSideLimit; - uint64_t partitionSize; - bool isDML; + std::map > joinFeTableMap; private: //defaults okay @@ -404,32 +369,31 @@ execplan::CalpontSystemCatalog::OID tableOid(const execplan::SimpleColumn* sc, /** @brief Returns the unique ID to be used in tupleInfo * */ -uint32_t getTupleKey(const JobInfo& jobInfo, +uint getTupleKey(const JobInfo& jobInfo, const execplan::SimpleColumn* sc); -uint32_t getTableKey(const JobInfo& jobInfo, +//uint getTupleKey(const JobInfo& jobInfo, +// execplan::CalpontSystemCatalog::OID oid, +// const std::string& colName, +// const std::string& tblAlias, +// const std::string& schema, +// const std::string& view); + +uint getTableKey(const JobInfo& jobInfo, execplan::CalpontSystemCatalog::OID tableOid, const std::string& alias, const std::string& schema, const std::string& view); -uint32_t getTupleKey(JobInfo& jobInfo, - const execplan::SRCP& srcp, - bool add = false); -uint32_t getTableKey(const JobInfo& jobInfo, - uint32_t cid); -uint32_t getTableKey(JobInfo& jobInfo, +uint getTableKey(const JobInfo& jobInfo, + uint cid); +uint getTableKey(JobInfo& jobInfo, JobStep* js); -void updateTableKey(uint32_t cid, - uint32_t tid, - JobInfo& jobInfo); - -uint32_t getExpTupleKey(const JobInfo& jobInfo, - uint64_t eid, - bool cr = false); +uint getExpTupleKey(const JobInfo& jobInfo, + uint64_t eid); -uint32_t makeTableKey(JobInfo& jobInfo, +uint makeTableKey(JobInfo& jobInfo, const execplan::SimpleColumn* sc); -uint32_t makeTableKey(JobInfo& jobInfo, +uint makeTableKey(JobInfo& jobInfo, execplan::CalpontSystemCatalog::OID tableOid, const std::string& tbl_name, const std::string& tbl_alias, @@ -437,11 +401,15 @@ uint32_t makeTableKey(JobInfo& jobInfo, const std::string& vw_name, uint64_t engine = 0); - /** @brief Returns the tupleInfo associate with the (table, column) key pair * */ -TupleInfo getTupleInfo(uint32_t columnKey, const JobInfo& jobInfo); +TupleInfo getTupleInfo(uint tableKey, uint columnKey, const JobInfo& jobInfo); + +/** @brief Returns the tupleInfo associate with the expression + * + */ +TupleInfo getExpTupleInfo(uint expKey, const JobInfo& jobInfo); /** @brief set tuple info for simple column * @@ -459,10 +427,7 @@ TupleInfo setTupleInfo(const execplan::CalpontSystemCatalog::ColType& ct, TupleInfo setExpTupleInfo(const execplan::CalpontSystemCatalog::ColType& ct, uint64_t expressionId, const std::string& alias, - JobInfo& jobInfo, - bool rc = false); - -TupleInfo setExpTupleInfo(const execplan::ReturnedColumn* rc, JobInfo& jobInfo); + JobInfo& jobInfo); /** @brief add an aggregate column info * @@ -470,25 +435,15 @@ TupleInfo setExpTupleInfo(const execplan::ReturnedColumn* rc, JobInfo& jobInfo); void addAggregateColumn(execplan::AggregateColumn*, int, RetColsVector&, JobInfo&); void makeJobSteps(execplan::CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, - JobStepVector& querySteps, JobStepVector& projectSteps, - DeliveredTableMap& deliverySteps); + JobStepVector& querySteps, JobStepVector& projectSteps, DeliveredTableMap& deliverySteps); void makeUnionJobSteps(execplan::CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, - JobStepVector& querySteps, JobStepVector&, DeliveredTableMap& deliverySteps); + JobStepVector& querySteps, JobStepVector&, DeliveredTableMap& deliverySteps); -void updateDerivedColumn(JobInfo&, execplan::SimpleColumn*, - execplan::CalpontSystemCatalog::ColType&); +void updateDerivedColumn(JobInfo&, SimpleColumn*, execplan::CalpontSystemCatalog::ColType&); bool filterWithDictionary(execplan::CalpontSystemCatalog::OID dictOid, uint64_t n); -bool compatibleColumnTypes(const execplan::CalpontSystemCatalog::ColType& ct1, - const execplan::CalpontSystemCatalog::ColType& ct2, - bool forJoin = true); -bool compatibleColumnTypes(const execplan::CalpontSystemCatalog::ColDataType& dt1, uint32_t scale1, - const execplan::CalpontSystemCatalog::ColDataType& dt2, uint32_t scale2, - bool forJoin = true); - - } // end of jlf_common namespace #endif diff --git a/dbcon/joblist/jlf_execplantojoblist.cpp b/dbcon/joblist/jlf_execplantojoblist.cpp index d9e9da1c..ecfc93e2 100644 --- a/dbcon/joblist/jlf_execplantojoblist.cpp +++ b/dbcon/joblist/jlf_execplantojoblist.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_execplantojoblist.cpp 9702 2013-07-17 19:08:07Z xlou $ +// $Id: jlf_execplantojoblist.cpp 9704 2013-07-17 19:18:23Z xlou $ #include "jlf_execplantojoblist.h" @@ -33,9 +33,7 @@ using namespace std; #include -#include #include -#include namespace ba=boost::algorithm; #include "calpontexecutionplan.h" @@ -47,15 +45,12 @@ namespace ba=boost::algorithm; #include "constantfilter.h" #include "existsfilter.h" #include "selectfilter.h" -#include "windowfunctioncolumn.h" #include "aggregatecolumn.h" #include "arithmeticcolumn.h" #include "constantcolumn.h" #include "functioncolumn.h" -#include "pseudocolumn.h" #include "simplecolumn.h" #include "simplecolumn_int.h" -#include "simplecolumn_uint.h" #include "simplecolumn_decimal.h" #include "returnedcolumn.h" #include "treenodeimpl.h" @@ -87,7 +82,6 @@ using namespace logging; #include "jlf_common.h" #include "jlf_subquery.h" -#include "jlf_tuplejoblist.h" namespace @@ -124,12 +118,6 @@ const Operator opNOTLIKE("NOT LIKE"); const Operator opisnotnull("isnotnull"); const Operator opisnull("isnull"); - -const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo); - - -/* This looks like an inefficient way to get NULL values. Much easier ways - to do it. */ int64_t valueNullNum(const CalpontSystemCatalog::ColType& ct) { int64_t n = 0; @@ -144,31 +132,17 @@ int64_t valueNullNum(const CalpontSystemCatalog::ColType& ct) case CalpontSystemCatalog::TINYINT: n = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UTINYINT: - n = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::SMALLINT: n = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::USMALLINT: - n = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: n = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - n = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::BIGINT: n = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UBIGINT: - n = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { float f = boost::any_cast(anyVal); //N.B. There is a bug in boost::any or in gcc where, if you store a nan, you will get back a nan, @@ -186,7 +160,6 @@ int64_t valueNullNum(const CalpontSystemCatalog::ColType& ct) } break; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { double d = boost::any_cast(anyVal); double* dp = &d; @@ -206,6 +179,7 @@ int64_t valueNullNum(const CalpontSystemCatalog::ColType& ct) (ct.colDataType == CalpontSystemCatalog::VARBINARY && ct.colWidth <= 7) || (ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) ) { + const string &i = boost::any_cast(anyVal); //n = *((uint64_t *) i.c_str()); /* this matches what dataconvert is returning; not valid to copy @@ -226,7 +200,7 @@ int64_t valueNullNum(const CalpontSystemCatalog::ColType& ct) default: n = *((uint64_t *) i.data()); break; } } - + } else { @@ -242,7 +216,6 @@ int64_t valueNullNum(const CalpontSystemCatalog::ColType& ct) n = boost::any_cast(anyVal); break; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: if (ct.colWidth == execplan::CalpontSystemCatalog::ONE_BYTE) n = boost::any_cast(anyVal); else if (ct.colWidth == execplan::CalpontSystemCatalog::TWO_BYTE) @@ -276,21 +249,11 @@ int64_t convertValueNum(const string& str, const CalpontSystemCatalog::ColType& v = boost::any_cast(anyVal); break; case CalpontSystemCatalog::TINYINT: -#if BOOST_VERSION >= 105200 v = boost::any_cast(anyVal); -#else - v = boost::any_cast(anyVal); -#endif break; - case CalpontSystemCatalog::UTINYINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::SMALLINT: v = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::USMALLINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: #ifdef _MSC_VER @@ -299,22 +262,10 @@ int64_t convertValueNum(const string& str, const CalpontSystemCatalog::ColType& v = boost::any_cast(anyVal); #endif break; - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: -#ifdef _MSC_VER - v = boost::any_cast(anyVal); -#else - v = boost::any_cast(anyVal); -#endif - break; case CalpontSystemCatalog::BIGINT: v = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UBIGINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { float f = boost::any_cast(anyVal); //N.B. There is a bug in boost::any or in gcc where, if you store a nan, @@ -332,7 +283,6 @@ int64_t convertValueNum(const string& str, const CalpontSystemCatalog::ColType& } break; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { double d = boost::any_cast(anyVal); double* dp = &d; @@ -361,7 +311,6 @@ int64_t convertValueNum(const string& str, const CalpontSystemCatalog::ColType& v = boost::any_cast(anyVal); break; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: if (ct.colWidth == execplan::CalpontSystemCatalog::ONE_BYTE) v = boost::any_cast(anyVal); else if (ct.colWidth == execplan::CalpontSystemCatalog::TWO_BYTE) @@ -384,13 +333,7 @@ int64_t convertValueNum(const string& str, const CalpontSystemCatalog::ColType& ct.colDataType == CalpontSystemCatalog::MEDINT || ct.colDataType == CalpontSystemCatalog::INT || ct.colDataType == CalpontSystemCatalog::BIGINT || - ct.colDataType == CalpontSystemCatalog::DECIMAL || - ct.colDataType == CalpontSystemCatalog::UTINYINT || - ct.colDataType == CalpontSystemCatalog::USMALLINT || - ct.colDataType == CalpontSystemCatalog::UMEDINT || - ct.colDataType == CalpontSystemCatalog::UINT || - ct.colDataType == CalpontSystemCatalog::UBIGINT || - ct.colDataType == CalpontSystemCatalog::UDECIMAL) && + ct.colDataType == CalpontSystemCatalog::DECIMAL) && pushWarning) { // get rid of leading white spaces and parentheses @@ -462,7 +405,6 @@ enum TreeNodeType OPERATOR, RETURNEDCOLUMN, AGGREGATECOLUMN, - WINDOWFUNCTIONCOLUMN, ARITHMETICCOLUMN, CONSTANTCOLUMN, FUNCTIONCOLUMN, @@ -497,8 +439,6 @@ TreeNodeType TreeNode2Type(const TreeNode* tn) return RETURNEDCOLUMN; if (typeid(*tn) == typeid(AggregateColumn)) return AGGREGATECOLUMN; - if (typeid(*tn) == typeid(WindowFunctionColumn)) - return WINDOWFUNCTIONCOLUMN; if (typeid(*tn) == typeid(ArithmeticColumn)) return ARITHMETICCOLUMN; if (typeid(*tn) == typeid(ConstantColumn)) @@ -510,19 +450,13 @@ TreeNodeType TreeNode2Type(const TreeNode* tn) if (typeid(*tn) == typeid(SimpleColumn_INT<1>) || typeid(*tn) == typeid(SimpleColumn_INT<2>) || typeid(*tn) == typeid(SimpleColumn_INT<4>) || - typeid(*tn) == typeid(SimpleColumn_INT<8>) || - typeid(*tn) == typeid(SimpleColumn_UINT<1>) || - typeid(*tn) == typeid(SimpleColumn_UINT<2>) || - typeid(*tn) == typeid(SimpleColumn_UINT<4>) || - typeid(*tn) == typeid(SimpleColumn_UINT<8>)) + typeid(*tn) == typeid(SimpleColumn_INT<8>)) return SIMPLECOLUMN; if (typeid(*tn) == typeid(SimpleColumn_Decimal<1>) || typeid(*tn) == typeid(SimpleColumn_Decimal<2>) || typeid(*tn) == typeid(SimpleColumn_Decimal<4>) || typeid(*tn) == typeid(SimpleColumn_Decimal<8>)) return SIMPLECOLUMN; - if (typeid(*tn) == typeid(PseudoColumn)) - return SIMPLECOLUMN; if (typeid(*tn) == typeid(TreeNodeImpl)) return TREENODEIMPL; if (typeid(*tn) == typeid(SimpleScalarFilter)) @@ -597,6 +531,60 @@ boost::shared_ptr doWhereFcn(const SimpleColumn* sc, const SOP& sop, c return ret; } +// @Bug 1955 +// Don't allow filter on "incompatible" cols +// Compatible columns: +// any 1,2,4,8-byte int/decimal to any 1,2,4,8-byte int/decimal +// date to date +// datetime to datetime +// string to string +bool compatibleFilterColumns(const SimpleColumn* sc1, const CalpontSystemCatalog::ColType& ct1, + const SimpleColumn* sc2, const CalpontSystemCatalog::ColType& ct2) +{ + switch (ct1.colDataType) + { + case CalpontSystemCatalog::BIT: + if (ct2.colDataType != CalpontSystemCatalog::BIT) return false; + break; + case CalpontSystemCatalog::TINYINT: + case CalpontSystemCatalog::SMALLINT: + case CalpontSystemCatalog::MEDINT: + case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::BIGINT: + case CalpontSystemCatalog::DECIMAL: + if (ct2.colDataType != CalpontSystemCatalog::TINYINT && + ct2.colDataType != CalpontSystemCatalog::SMALLINT && + ct2.colDataType != CalpontSystemCatalog::MEDINT && + ct2.colDataType != CalpontSystemCatalog::INT && + ct2.colDataType != CalpontSystemCatalog::BIGINT && + ct2.colDataType != CalpontSystemCatalog::DECIMAL) return false; + break; + case CalpontSystemCatalog::DATE: + if (ct2.colDataType != CalpontSystemCatalog::DATE) return false; + break; + case CalpontSystemCatalog::DATETIME: + if (ct2.colDataType != CalpontSystemCatalog::DATETIME) return false; + break; + case CalpontSystemCatalog::VARCHAR: + case CalpontSystemCatalog::CHAR: + if (ct2.colDataType != CalpontSystemCatalog::VARCHAR && + ct2.colDataType != CalpontSystemCatalog::CHAR) return false; + break; + case CalpontSystemCatalog::VARBINARY: + if (ct2.colDataType != CalpontSystemCatalog::VARBINARY) return false; + break; + case CalpontSystemCatalog::FLOAT: + case CalpontSystemCatalog::DOUBLE: + if (ct2.colDataType != CalpontSystemCatalog::FLOAT && + ct2.colDataType != CalpontSystemCatalog::DOUBLE) return false; + break; + default: + return false; + break; + } + + return true; +} const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2, JobInfo& jobInfo, const SOP& sop, SimpleFilter* sf) @@ -609,50 +597,45 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 string alias2(extractTableAlias(sc2)); CalpontSystemCatalog::ColType ct1 = sc1->colType(); CalpontSystemCatalog::ColType ct2 = sc2->colType(); - const PseudoColumn* pc1 = dynamic_cast(sc1); - const PseudoColumn* pc2 = dynamic_cast(sc2); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (!sc1->schemaName().empty() && sc1->isInfiniDB() && !pc1) + if (!sc1->schemaName().empty() && sc1->isInfiniDB()) ct1 = jobInfo.csc->colType(sc1->oid()); - if (!sc2->schemaName().empty() && sc2->isInfiniDB() && !pc2) + if (!sc2->schemaName().empty() && sc2->isInfiniDB()) ct2 = jobInfo.csc->colType(sc2->oid()); //X int8_t op = op2num(sop); - pColStep* pcs1 = NULL; - if (pc1 == NULL) - pcs1 = new pColStep(sc1->oid(), tableOid1, ct1, jobInfo); - else - pcs1 = new PseudoColStep(sc1->oid(), tableOid1, pc1->pseudoType(), ct1, jobInfo); + pColStep* pcss1 = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, sc1->oid(), tableOid1, ct1, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); CalpontSystemCatalog::OID dictOid1 = isDictCol(ct1); - pcs1->alias(alias1); - pcs1->view(sc1->viewName()); - pcs1->name(sc1->columnName()); - pcs1->schema(sc1->schemaName()); - pcs1->cardinality(sc1->cardinality()); - pcs1->setFeederFlag(true); - - pColStep* pcs2 = NULL; - if (pc2 == NULL) - pcs2 = new pColStep(sc2->oid(), tableOid2, ct2, jobInfo); - else - pcs2 = new PseudoColStep(sc2->oid(), tableOid2, pc2->pseudoType(), ct2, jobInfo); + pcss1->logger(jobInfo.logger); + pcss1->alias(alias1); + pcss1->view(sc1->viewName()); + pcss1->name(sc1->columnName()); + pcss1->schema(sc1->schemaName()); + pcss1->cardinality(sc1->cardinality()); + pcss1->setFeederFlag(true); + + pColStep* pcss2 = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, sc2->oid(), tableOid2, ct2, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); CalpontSystemCatalog::OID dictOid2 = isDictCol(ct2); - pcs2->alias(alias2); - pcs2->view(sc2->viewName()); - pcs2->name(sc2->columnName()); - pcs2->schema(sc2->schemaName()); - pcs2->cardinality(sc2->cardinality()); - pcs2->setFeederFlag(true); + pcss2->logger(jobInfo.logger); + pcss2->alias(alias2); + pcss2->view(sc2->viewName()); + pcss2->name(sc2->columnName()); + pcss2->schema(sc2->schemaName()); + pcss2->cardinality(sc2->cardinality()); + pcss2->setFeederFlag(true); //Associate the steps JobStepVector jsv; TupleInfo ti1(setTupleInfo(ct1, sc1->oid(), jobInfo, tableOid1, sc1, alias1)); - pcs1->tupleId(ti1.key); + pcss1->tupleId(ti1.key); TupleInfo ti2(setTupleInfo(ct2, sc2->oid(), jobInfo, tableOid2, sc2, alias2)); - pcs2->tupleId(ti2.key); + pcss2->tupleId(ti2.key); // check if they are string columns greater than 8 bytes. if ((!isDictCol(ct1)) && (!isDictCol(ct2))) @@ -663,40 +646,41 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl1->fifoDL(dl1); dl1->OID(sc1->oid()); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); - pcs1->outputAssociation(outJs1); + pcss1->outputAssociation(outJs1); AnyDataListSPtr spdl2(new AnyDataList()); FifoDataList* dl2 = new FifoDataList(1, jobInfo.fifoSize); spdl2->fifoDL(dl2); dl2->OID(sc2->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); - pcs2->outputAssociation(outJs2); - pcs2->inputAssociation(outJs1); + pcss2->outputAssociation(outJs2); + pcss2->inputAssociation(outJs1); - FilterStep* filt=new FilterStep(ct1, jobInfo); + FilterStep* filt=new FilterStep(jobInfo.sessionId, jobInfo.txnId, jobInfo.statementId, ct1); + filt->logger(jobInfo.logger); filt->alias(extractTableAlias(sc1)); filt->tableOid(tableOid1); - filt->name(pcs1->name()+","+pcs2->name()); - filt->view(pcs1->view()); - filt->schema(pcs1->schema()); + filt->name(pcss1->name()+","+pcss2->name()); + filt->view(pcss1->view()); + filt->schema(pcss1->schema()); filt->addFilter(sf); if (op) filt->setBOP(op); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl1); outJs3.outAdd(spdl2); filt->inputAssociation(outJs3); SJSTEP step; - step.reset(pcs1); + step.reset(pcss1); jsv.push_back(step); - step.reset(pcs2); + step.reset(pcss2); jsv.push_back(step); step.reset(filt); jsv.push_back(step); @@ -707,7 +691,11 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 if ((isDictCol(ct1) != 0 ) && (isDictCol(ct2) !=0 )) { // extra steps for string column greater than eight bytes -- from token to string - pDictionaryStep* pdss1 = new pDictionaryStep(dictOid1, tableOid1, ct1, jobInfo); + pDictionaryStep* pdss1 = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, + jobInfo.csc, dictOid1, ct1.ddn.compressionType, tableOid1, jobInfo.sessionId, + jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pdss1->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid1] = sc1->oid(); pdss1->alias(extractTableAlias(sc1)); pdss1->view(sc1->viewName()); @@ -721,9 +709,9 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl11->fifoDL(dl11); dl11->OID(sc1->oid()); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl11); - pcs1->outputAssociation(outJs1); + pcss1->outputAssociation(outJs1); // data list for column 1 step 2 (pdictionarystep) output AnyDataListSPtr spdl12(new AnyDataList()); @@ -731,17 +719,21 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl12->stringDL(dl12); dl12->OID(sc1->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl12); pdss1->outputAssociation(outJs2); - //Associate pcs1 with pdss1 - JobStepAssociation outJs11; + //Associate pcss1 with pdss1 + JobStepAssociation outJs11(jobInfo.status); outJs11.outAdd(spdl11); pdss1->inputAssociation(outJs11); - pDictionaryStep* pdss2 = new pDictionaryStep(dictOid2, tableOid2, ct2, jobInfo); + pDictionaryStep* pdss2 = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, + jobInfo.csc, dictOid2, ct2.ddn.compressionType, tableOid2, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pdss2->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid2] = sc2->oid(); pdss2->alias(extractTableAlias(sc2)); pdss2->view(sc2->viewName()); @@ -756,12 +748,12 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl21->fifoDL(dl21); dl21->OID(sc2->oid()); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl21); - pcs2->outputAssociation(outJs3); - pcs2->inputAssociation(outJs2); - //Associate pcs2 with pdss2 - JobStepAssociation outJs22; + pcss2->outputAssociation(outJs3); + pcss2->inputAssociation(outJs2); + //Associate pcss2 with pdss2 + JobStepAssociation outJs22(jobInfo.status); outJs22.outAdd(spdl21); pdss2->inputAssociation(outJs22); @@ -771,31 +763,33 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl22->stringDL(dl22); dl22->OID(sc2->oid()); - JobStepAssociation outJs4; + JobStepAssociation outJs4(jobInfo.status); outJs4.outAdd(spdl22); pdss2->outputAssociation(outJs4); - FilterStep* filt = new FilterStep(ct1, jobInfo); + FilterStep* filt = new FilterStep(jobInfo.sessionId, jobInfo.txnId, + jobInfo.statementId, ct1); + filt->logger(jobInfo.logger); filt->alias(extractTableAlias(sc1)); filt->tableOid(tableOid1); - filt->name(pcs1->name()+","+pcs2->name()); - filt->view(pcs1->view()); - filt->schema(pcs1->schema()); + filt->name(pcss1->name()+","+pcss2->name()); + filt->view(pcss1->view()); + filt->schema(pcss1->schema()); filt->addFilter(sf); if (op) filt->setBOP((op)); - JobStepAssociation outJs5; + JobStepAssociation outJs5(jobInfo.status); outJs5.outAdd(spdl12); outJs5.outAdd(spdl22); filt->inputAssociation(outJs5); SJSTEP step; - step.reset(pcs1); + step.reset(pcss1); jsv.push_back(step); step.reset(pdss1); jsv.push_back(step); - step.reset(pcs2); + step.reset(pcss2); jsv.push_back(step); step.reset(pdss2); jsv.push_back(step); @@ -804,18 +798,21 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 TupleInfo ti1(setTupleInfo(ct1, dictOid1, jobInfo, tableOid1, sc1, alias1)); pdss1->tupleId(ti1.key); - jobInfo.keyInfo->dictKeyMap[pcs1->tupleId()] = ti1.key; - jobInfo.tokenOnly[pcs1->tupleId()] = false; + jobInfo.keyInfo->dictKeyMap[pcss1->tupleId()] = ti1.key; + jobInfo.tokenOnly[pcss1->tupleId()] = false; TupleInfo ti2(setTupleInfo(ct2, dictOid2, jobInfo, tableOid2, sc2, alias2)); pdss2->tupleId(ti2.key); - jobInfo.keyInfo->dictKeyMap[pcs2->tupleId()] = ti2.key; - jobInfo.tokenOnly[pcs2->tupleId()] = false; + jobInfo.keyInfo->dictKeyMap[pcss2->tupleId()] = ti2.key; + jobInfo.tokenOnly[pcss2->tupleId()] = false; } else if ((isDictCol(ct1) != 0 ) && (isDictCol(ct2) ==0 )) //col1 is dictionary column { // extra steps for string column greater than eight bytes -- from token to string - pDictionaryStep* pdss1 = new pDictionaryStep(dictOid1, tableOid1, ct1, jobInfo); + pDictionaryStep* pdss1 = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, dictOid1, ct1.ddn.compressionType, tableOid1, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pdss1->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid1] = sc1->oid(); pdss1->alias(extractTableAlias(sc1)); pdss1->view(sc1->viewName()); @@ -829,9 +826,9 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl11->fifoDL(dl11); dl11->OID(sc1->oid()); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl11); - pcs1->outputAssociation(outJs1); + pcss1->outputAssociation(outJs1); // data list for column 1 step 2 (pdictionarystep) output AnyDataListSPtr spdl12(new AnyDataList()); @@ -839,12 +836,12 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl12->stringDL(dl12); dl12->OID(sc1->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl12); pdss1->outputAssociation(outJs2); - //Associate pcs1 with pdss1 - JobStepAssociation outJs11; + //Associate pcss1 with pdss1 + JobStepAssociation outJs11(jobInfo.status); outJs11.outAdd(spdl11); pdss1->inputAssociation(outJs11); @@ -854,39 +851,41 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl21->fifoDL(dl21); dl21->OID(sc2->oid()); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl21); - pcs2->outputAssociation(outJs3); - pcs2->inputAssociation(outJs2); + pcss2->outputAssociation(outJs3); + pcss2->inputAssociation(outJs2); - FilterStep* filt = new FilterStep(ct1, jobInfo); + FilterStep* filt = new FilterStep(jobInfo.sessionId, jobInfo.txnId, + jobInfo.statementId, ct1); + filt->logger(jobInfo.logger); filt->alias(extractTableAlias(sc1)); filt->tableOid(tableOid1); - filt->view(pcs1->view()); - filt->schema(pcs1->schema()); + filt->view(pcss1->view()); + filt->schema(pcss1->schema()); filt->addFilter(sf); if (op) filt->setBOP((op)); - JobStepAssociation outJs5; + JobStepAssociation outJs5(jobInfo.status); outJs5.outAdd(spdl12); outJs5.outAdd(spdl21); filt->inputAssociation(outJs5); SJSTEP step; - step.reset(pcs1); + step.reset(pcss1); jsv.push_back(step); step.reset(pdss1); jsv.push_back(step); - step.reset(pcs2); + step.reset(pcss2); jsv.push_back(step); step.reset(filt); jsv.push_back(step); TupleInfo ti1(setTupleInfo(ct1, dictOid1, jobInfo, tableOid1, sc1, alias1)); pdss1->tupleId(ti1.key); - jobInfo.keyInfo->dictKeyMap[pcs1->tupleId()] = ti1.key; - jobInfo.tokenOnly[pcs1->tupleId()] = false; + jobInfo.keyInfo->dictKeyMap[pcss1->tupleId()] = ti1.key; + jobInfo.tokenOnly[pcss1->tupleId()] = false; } else // if ((isDictCol(ct1) == 0 ) && (isDictCol(ct2) !=0 )) //col2 is dictionary column { @@ -897,9 +896,9 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl11->fifoDL(dl11); dl11->OID(sc1->oid()); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl11); - pcs1->outputAssociation(outJs1); + pcss1->outputAssociation(outJs1); // data list for column 1 step 2 (pdictionarystep) output AnyDataListSPtr spdl12(new AnyDataList()); @@ -908,7 +907,10 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 dl12->OID(sc1->oid()); - pDictionaryStep* pdss2 = new pDictionaryStep(dictOid2, tableOid2, ct2, jobInfo); + pDictionaryStep* pdss2 = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, dictOid2, ct2.ddn.compressionType, tableOid2, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pdss2->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid2] = sc2->oid(); pdss2->alias(extractTableAlias(sc2)); pdss2->view(sc2->viewName()); @@ -923,12 +925,12 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl21->fifoDL(dl21); dl21->OID(sc2->oid()); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl21); - pcs2->outputAssociation(outJs3); - pcs2->inputAssociation(outJs1); - //Associate pcs2 with pdss2 - JobStepAssociation outJs22; + pcss2->outputAssociation(outJs3); + pcss2->inputAssociation(outJs1); + //Associate pcss2 with pdss2 + JobStepAssociation outJs22(jobInfo.status); outJs22.outAdd(spdl21); pdss2->inputAssociation(outJs22); @@ -938,28 +940,32 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 spdl22->stringDL(dl22); dl22->OID(sc2->oid()); - JobStepAssociation outJs4; + JobStepAssociation outJs4(jobInfo.status); outJs4.outAdd(spdl22); pdss2->outputAssociation(outJs4); - FilterStep* filt = new FilterStep(ct1, jobInfo); + FilterStep* filt = new FilterStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, ct1); + filt->logger(jobInfo.logger); filt->alias(extractTableAlias(sc1)); filt->tableOid(tableOid1); - filt->view(pcs1->view()); - filt->schema(pcs1->schema()); + filt->view(pcss1->view()); + filt->schema(pcss1->schema()); filt->addFilter(sf); if (op) filt->setBOP((op)); - JobStepAssociation outJs5; + JobStepAssociation outJs5(jobInfo.status); outJs5.outAdd(spdl11); outJs5.outAdd(spdl22); filt->inputAssociation(outJs5); SJSTEP step; - step.reset(pcs1); + step.reset(pcss1); jsv.push_back(step); - step.reset(pcs2); + step.reset(pcss2); jsv.push_back(step); step.reset(pdss2); jsv.push_back(step); @@ -968,8 +974,8 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 TupleInfo ti2(setTupleInfo(ct2, dictOid2, jobInfo, tableOid2, sc2, alias2)); pdss2->tupleId(ti2.key); - jobInfo.keyInfo->dictKeyMap[pcs2->tupleId()] = ti2.key; - jobInfo.tokenOnly[pcs2->tupleId()] = false; + jobInfo.keyInfo->dictKeyMap[pcss2->tupleId()] = ti2.key; + jobInfo.tokenOnly[pcss2->tupleId()] = false; } } else @@ -981,15 +987,108 @@ const JobStepVector doColFilter(const SimpleColumn* sc1, const SimpleColumn* sc2 return jsv; } +bool sameTable(const SimpleColumn* sc1, const SimpleColumn* sc2) +{ + if (sc1->schemaName() != sc2->schemaName()) return false; + if (sc1->tableName() != sc2->tableName()) return false; + return true; +} + +// @Bug 1230 +// Don't allow join on "incompatible" cols +// Compatible columns: +// any 1,2,4,8-byte int to any 1,2,4,8-byte int +// decimal w/scale x to decimal w/scale x +// date to date +// datetime to datetime +// string to string +bool compatibleJoinColumns(const SimpleColumn* sc1, const CalpontSystemCatalog::ColType& ct1, + const SimpleColumn* sc2, const CalpontSystemCatalog::ColType& ct2) +{ + // disable VARBINARY used in join + if (ct1.colDataType == CalpontSystemCatalog::VARBINARY || + ct2.colDataType == CalpontSystemCatalog::VARBINARY) + throw runtime_error("VARBINARY in join is not supported."); + + switch (ct1.colDataType) + { + case CalpontSystemCatalog::BIT: + if (ct2.colDataType != CalpontSystemCatalog::BIT) return false; + break; + case CalpontSystemCatalog::TINYINT: + case CalpontSystemCatalog::SMALLINT: + case CalpontSystemCatalog::MEDINT: + case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::BIGINT: + case CalpontSystemCatalog::DECIMAL: + if (ct2.colDataType != CalpontSystemCatalog::TINYINT && + ct2.colDataType != CalpontSystemCatalog::SMALLINT && + ct2.colDataType != CalpontSystemCatalog::MEDINT && + ct2.colDataType != CalpontSystemCatalog::INT && + ct2.colDataType != CalpontSystemCatalog::BIGINT && + ct2.colDataType != CalpontSystemCatalog::DECIMAL) return false; + if (ct2.scale != ct1.scale) return false; + break; + case CalpontSystemCatalog::DATE: + if (ct2.colDataType != CalpontSystemCatalog::DATE) return false; + break; + case CalpontSystemCatalog::DATETIME: + if (ct2.colDataType != CalpontSystemCatalog::DATETIME) return false; + break; + case CalpontSystemCatalog::VARCHAR: + // @bug 1495 compound/string join + if (ct2.colDataType == CalpontSystemCatalog::VARCHAR || + ct2.colDataType == CalpontSystemCatalog::CHAR) + break; + // @bug 1920. disable joins on dictionary column + if (ct1.colWidth > 7 ) return false; + if (ct2.colDataType != CalpontSystemCatalog::VARCHAR && ct2.colDataType != CalpontSystemCatalog::CHAR) return false; + if (ct2.colDataType == CalpontSystemCatalog::VARCHAR && ct2.colWidth > 7) return false; + if (ct2.colDataType == CalpontSystemCatalog::CHAR && ct2.colWidth > 8) return false; + break; + case CalpontSystemCatalog::CHAR: + // @bug 1495 compound/string join + if (ct2.colDataType == CalpontSystemCatalog::VARCHAR || + ct2.colDataType == CalpontSystemCatalog::CHAR) + break; + // @bug 1920. disable joins on dictionary column + if (ct1.colWidth > 8 ) return false; + if (ct2.colDataType != CalpontSystemCatalog::VARCHAR && ct2.colDataType != CalpontSystemCatalog::CHAR) return false; + if (ct2.colDataType == CalpontSystemCatalog::VARCHAR && ct2.colWidth > 7) return false; + if (ct2.colDataType == CalpontSystemCatalog::CHAR && ct2.colWidth > 8) return false; + break; + case CalpontSystemCatalog::VARBINARY: + if (ct2.colDataType != CalpontSystemCatalog::VARBINARY) return false; + break; + + case CalpontSystemCatalog::FLOAT: + if (ct2.colDataType != CalpontSystemCatalog::FLOAT) return false; + break; + case CalpontSystemCatalog::DOUBLE: + if (ct2.colDataType != CalpontSystemCatalog::DOUBLE) return false; + break; + default: + return false; + break; + } + + return true; +} const JobStepVector doFilterExpression(const SimpleColumn* sc1, const SimpleColumn* sc2, JobInfo& jobInfo, const SOP& sop) { JobStepVector jsv; SJSTEP sjstep; - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + if (es == NULL) throw runtime_error("Failed to create ExpressionStep 2"); + es->logger(jobInfo.logger); + SimpleFilter sf; sf.op(sop); sf.lhs(sc1->clone()); @@ -1018,13 +1117,10 @@ const JobStepVector doJoin( CalpontSystemCatalog::ColType ct1 = sc1->colType(); CalpontSystemCatalog::ColType ct2 = sc2->colType(); - PseudoColumn* pc1 = dynamic_cast(sc1); - PseudoColumn* pc2 = dynamic_cast(sc2); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (!sc1->schemaName().empty() && sc1->isInfiniDB() && !pc1) + if (!sc1->schemaName().empty() && sc1->isInfiniDB()) ct1 = jobInfo.csc->colType(sc1->oid()); - if (!sc2->schemaName().empty() && sc2->isInfiniDB() && !pc2) + if (!sc2->schemaName().empty() && sc2->isInfiniDB()) ct2 = jobInfo.csc->colType(sc2->oid()); //X uint64_t joinInfo = sc1->joinInfo() | sc2->joinInfo(); @@ -1045,7 +1141,7 @@ const JobStepVector doJoin( //Bug 590 if (tableOid1 == tableOid2 && alias1 == alias2 && view1 == view2 && joinInfo == 0) { - if (sc1->schemaName().empty() || !compatibleColumnTypes(ct1, ct2, false)) + if (sc1->schemaName().empty() || !compatibleFilterColumns(sc1, ct1, sc2, ct2)) { return doFilterExpression(sc1, sc2, jobInfo, sop); } @@ -1056,12 +1152,12 @@ const JobStepVector doJoin( } // different tables - if (!compatibleColumnTypes(ct1, ct2, true)) + if (!compatibleJoinColumns(sc1, ct1, sc2, ct2)) { JobStepVector jsv; jsv = doFilterExpression(sc1, sc2, jobInfo, sop); - uint32_t t1 = makeTableKey(jobInfo, sc1); - uint32_t t2 = makeTableKey(jobInfo, sc2); + uint t1 = makeTableKey(jobInfo, sc1); + uint t2 = makeTableKey(jobInfo, sc2); jobInfo.incompatibleJoinMap[t1] = t2; jobInfo.incompatibleJoinMap[t2] = t1; @@ -1073,10 +1169,10 @@ const JobStepVector doJoin( CalpontSystemCatalog::OID dictOid1 = isDictCol(ct1); if (sc1->schemaName().empty() == false) { - if (pc1 == NULL) - pcs1 = new pColStep(oid1, tableOid1, ct1, jobInfo); - else - pcs1 = new PseudoColStep(oid1, tableOid1, pc1->pseudoType(), ct1, jobInfo); + pcs1 = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, oid1, tableOid1, ct1, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pcs1->logger(jobInfo.logger); pcs1->alias(alias1); pcs1->view(view1); pcs1->name(sc1->columnName()); @@ -1089,10 +1185,10 @@ const JobStepVector doJoin( CalpontSystemCatalog::OID dictOid2 = isDictCol(ct2); if (sc2->schemaName().empty() == false) { - if (pc2 == NULL) - pcs2 = new pColStep(oid2, tableOid2, ct2, jobInfo); - else - pcs2 = new PseudoColStep(oid2, tableOid2, pc2->pseudoType(), ct2, jobInfo); + pcs2 = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, oid2, tableOid2, ct2, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pcs2->logger(jobInfo.logger); pcs2->alias(alias2); pcs2->view(view2); pcs2->name(sc2->columnName()); @@ -1128,7 +1224,7 @@ const JobStepVector doJoin( if (pcs1) { - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); pcs1->outputAssociation(outJs1); @@ -1143,7 +1239,7 @@ const JobStepVector doJoin( if (pcs2) { - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); pcs2->outputAssociation(outJs2); @@ -1151,7 +1247,12 @@ const JobStepVector doJoin( jsv.push_back(step); } - TupleHashJoinStep* thj = new TupleHashJoinStep(jobInfo); + TupleHashJoinStep* thj = new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm); + thj->logger(jobInfo.logger); thj->tableOid1(tableOid1); thj->tableOid2(tableOid2); thj->alias1(alias1); @@ -1168,6 +1269,7 @@ const JobStepVector doJoin( thj->sequence2(sc2->sequence()); thj->column1(sc1); thj->column2(sc2); +// thj->joinId(jobInfo.joinNum++); thj->joinId((joinInfo == 0) ? (++jobInfo.joinNum) : 0); // Check if SEMI/ANTI join. @@ -1202,7 +1304,7 @@ const JobStepVector doJoin( } thj->setJoinType(jt); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl1); outJs3.outAdd(spdl2); thj->inputAssociation(outJs3); @@ -1257,13 +1359,11 @@ const JobStepVector doSemiJoin(const SimpleColumn* sc, const ReturnedColumn* rc, CalpontSystemCatalog::OID tableOid1 = tableOid(sc, jobInfo.csc); CalpontSystemCatalog::OID tableOid2 = execplan::CNX_VTABLE_ID; string alias1(extractTableAlias(sc)); - string alias2(jobInfo.subAlias); CalpontSystemCatalog::ColType ct1 = sc->colType(); CalpontSystemCatalog::ColType ct2 = rc->resultType(); - const PseudoColumn* pc1 = dynamic_cast(sc); + //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (!sc->schemaName().empty() && sc->isInfiniDB() && !pc1) + if (!sc->schemaName().empty() && sc->isInfiniDB()) ct1 = jobInfo.csc->colType(sc->oid()); //X JobStepVector jsv; @@ -1274,12 +1374,11 @@ const JobStepVector doSemiJoin(const SimpleColumn* sc, const ReturnedColumn* rc, uint64_t tupleId2 = -1; if (sc->schemaName().empty() == false) { - pColStep* pcs1 = NULL; - if (pc1 == NULL) - pcs1 = new pColStep(sc->oid(), tableOid1, ct1, jobInfo); - else - pcs1 = new PseudoColStep(sc->oid(), tableOid1, pc1->pseudoType(), ct1, jobInfo); + pColStep* pcs1 = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, sc->oid(), tableOid1, ct1, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); dictOid1 = isDictCol(ct1); + pcs1->logger(jobInfo.logger); pcs1->alias(alias1); pcs1->view(sc->viewName()); pcs1->name(sc->columnName()); @@ -1301,7 +1400,12 @@ const JobStepVector doSemiJoin(const SimpleColumn* sc, const ReturnedColumn* rc, } } - TupleHashJoinStep* thj = new TupleHashJoinStep(jobInfo); + TupleHashJoinStep* thj = new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm); + thj->logger(jobInfo.logger); thj->tableOid1(tableOid1); thj->tableOid2(tableOid2); thj->alias1(alias1); @@ -1309,13 +1413,13 @@ const JobStepVector doSemiJoin(const SimpleColumn* sc, const ReturnedColumn* rc, thj->schema1(sc->schemaName()); thj->oid1(sc->oid()); thj->oid2(tableOid2 + 1 + rc->sequence()); - thj->alias2(alias2); thj->dictOid1(dictOid1); thj->dictOid2(0); thj->sequence1(sc->sequence()); thj->sequence2(rc->sequence()); thj->column1(sc); thj->column2(rc); +// thj->joinId(jobInfo.joinNum++); thj->joinId(0); thj->tupleId1(tupleId1); thj->tupleId2(tupleId2); @@ -1352,47 +1456,54 @@ const JobStepVector doSemiJoin(const SimpleColumn* sc, const ReturnedColumn* rc, } -SJSTEP expressionToFuncJoin(ExpressionStep* es, JobInfo& jobInfo) +const JobStepVector doFunctionColumn(const FunctionColumn* fc, JobInfo& jobInfo) +{ + throw logic_error("jlf_execplantojoblist.cpp:doFunctionColumn(): Not implemented"); +} + +// This function returns a JobStepVector with the steps necessary to evaluate the passed Arithmetic column. +// It recurses directly and indirectly through calls to doFunctionColumn. +const JobStepVector doArithmeticColumn(const ArithmeticColumn* ac, JobInfo& jobInfo) { - idbassert(es); - boost::shared_ptr fji = es->functionJoinInfo(); - es->functionJoin(true); - TupleHashJoinStep* thjs= new TupleHashJoinStep(jobInfo); - thjs->tableOid1(fji->fTableOid[0]); - thjs->tableOid2(fji->fTableOid[1]); - thjs->oid1(fji->fOid[0]); - thjs->oid2(fji->fOid[1]); - thjs->alias1(fji->fAlias[0]); - thjs->alias2(fji->fAlias[1]); - thjs->view1(fji->fView[0]); - thjs->view2(fji->fView[1]); - thjs->schema1(fji->fSchema[0]); - thjs->schema2(fji->fSchema[1]); - thjs->column1(fji->fExpression[0]); - thjs->column2(fji->fExpression[1]); - thjs->sequence1(fji->fSequence[0]); - thjs->sequence2(fji->fSequence[1]); - thjs->joinId(fji->fJoinId); - thjs->setJoinType(fji->fJoinType); - thjs->correlatedSide(fji->fCorrelatedSide); - thjs->funcJoinInfo(fji); - thjs->tupleId1(fji->fJoinKey[0]); - thjs->tupleId2(fji->fJoinKey[1]); - - updateTableKey(fji->fJoinKey[0], fji->fTableKey[0], jobInfo); - updateTableKey(fji->fJoinKey[1], fji->fTableKey[1], jobInfo); - - return SJSTEP(thjs); + JobStepVector jsv; + + + TreeNodeStack stack; + ac->expression()->walk(walkTreeNode, &stack); + + const TreeNode* tnop; + + tnop = stack.top(); + stack.pop(); + + // Only handling ArithmeticColumns that contain FunctionColumn for now. + if(TreeNode2Type(tnop) == FUNCTIONCOLUMN) + { + const FunctionColumn* fc = static_cast(tnop); + jsv = doFunctionColumn(fc, jobInfo); + } + else + { + cerr << boldStart << "doArithmeticColumn: Unhandled Type." << boldStop << endl; + } + + return jsv; + } const JobStepVector doExpressionFilter(const ParseTree* n, JobInfo& jobInfo) { JobStepVector jsv; - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + if (es == NULL) throw runtime_error("Failed to create ExpressionStep 1"); + es->logger(jobInfo.logger); es->expressionFilter(n, jobInfo); SJSTEP sjstep(es); jsv.push_back(sjstep); @@ -1404,38 +1515,19 @@ const JobStepVector doExpressionFilter(const ParseTree* n, JobInfo& jobInfo) const JobStepVector doExpressionFilter(const Filter* f, JobInfo& jobInfo) { JobStepVector jsv; - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + if (es == NULL) throw runtime_error("Failed to create ExpressionStep 2"); + es->logger(jobInfo.logger); es->expressionFilter(f, jobInfo); SJSTEP sjstep(es); jsv.push_back(sjstep); - // @bug3683, support in/exists suquery function join - const SimpleFilter* sf = dynamic_cast(f); - if (sf != NULL) - { - const ReturnedColumn* lrc = static_cast(sf->lhs()); - const ReturnedColumn* rrc = static_cast(sf->rhs()); - if (lrc->joinInfo()) - { - const ReturnedColumn* lac = dynamic_cast(lrc); - const ReturnedColumn* lfc = dynamic_cast(lrc); - const ReturnedColumn* lsc = dynamic_cast(lrc); - if ((lac || lfc || lsc) && es->functionJoinInfo()) - jsv.push_back(expressionToFuncJoin(es, jobInfo)); - } - else if (rrc->joinInfo()) - { - const ReturnedColumn* rac = dynamic_cast(lrc); - const ReturnedColumn* rfc = dynamic_cast(lrc); - const ReturnedColumn* rsc = dynamic_cast(lrc); - if ((rac || rfc || rsc) && es->functionJoinInfo()) - jsv.push_back(expressionToFuncJoin(es, jobInfo)); - } - } - return jsv; } @@ -1444,7 +1536,13 @@ const JobStepVector doConstantBooleanFilter(const ParseTree* n, JobInfo& jobInfo { JobStepVector jsv; TupleConstantBooleanStep* tcbs = new - TupleConstantBooleanStep(jobInfo, n->data()->getBoolVal()); + TupleConstantBooleanStep(JobStepAssociation(), + JobStepAssociation(), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId, + n->data()->getBoolVal()); if (tcbs == NULL) throw runtime_error("Failed to create Constant Boolean Step"); @@ -1456,50 +1554,6 @@ const JobStepVector doConstantBooleanFilter(const ParseTree* n, JobInfo& jobInfo } -bool optimizeIdbPatitionSimpleFilter(SimpleFilter* sf, JobStepVector& jsv, JobInfo& jobInfo) -{ - //@bug5848, not equal filter is not optimized. - if (sf->op()->op() != opeq.op()) - return false; - - const FunctionColumn* fc = static_cast(sf->lhs()); - const ConstantColumn* cc = static_cast(sf->rhs()); - if (fc == NULL) - { - cc = static_cast(sf->lhs()); - fc = static_cast(sf->rhs()); - } - - // not a function or not idbparttition - if (fc == NULL || cc == NULL || fc->functionName().compare("idbpartition") != 0) - return false; - - // make sure the cc has 3 tokens - vector cv; - boost::split(cv, cc->constval(), boost::is_any_of(".")); - if (cv.size() != 3) - return false; - - // construct separate filters, then make job steps - JobStepVector v; - SOP sop = sf->op(); - const funcexp::FunctionParm& parms = fc->functionParms(); - - for (uint64_t i = 0; i < 3; i++) - { - // very weird parms order is: db root, physical partition, segment - // logical partition string : physical partition, segment, db root - ReturnedColumn* lhs = dynamic_cast(parms[(i+1)%3]->data()); - ConstantColumn* rhs = new ConstantColumn(cv[i]); - SimpleFilter* f = new SimpleFilter(sop, lhs->clone(), rhs); - v = doSimpleFilter(f, jobInfo); - jsv.insert(jsv.end(), v.begin(), v.end()); - } - - return true; -} - - const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) { JobStepVector jsv; @@ -1533,7 +1587,7 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) string schema(sc->schemaName()); tbl_oid = tableOid(sc, jobInfo.csc); - if (sc->joinInfo() != 0 && cc->sequence() != -1) + if (sc->joinInfo() != 0 && (int32_t)cc->sequence() != -1) { // correlated, like in 'c1 in select 1' type sub queries. return doSemiJoin(sc, cc, jobInfo); @@ -1552,12 +1606,12 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) size_t spos = constval.find_last_not_of(" "); if (spos != string::npos) constval = constval.substr(0, spos+1); + if (!sc->schemaName().empty()) + jobInfo.tables.insert(make_table(sc->schemaName(), sc->tableName())); CalpontSystemCatalog::OID dictOid = 0; CalpontSystemCatalog::ColType ct = sc->colType(); - const PseudoColumn* pc = dynamic_cast(sc); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (!sc->schemaName().empty() && sc->isInfiniDB() && !pc) + if (!sc->schemaName().empty() && sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X //@bug 339 nulls are not stored in dictionary @@ -1566,8 +1620,11 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) if (jobInfo.trace) cout << "Emit pTokenByScan/pCol for SimpleColumn op ConstantColumn" << endl; - // dictionary, cannot be pseudo column - pColStep* pcs = new pColStep(sc->oid(), tbl_oid, ct, jobInfo); + pColStep* pcs = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, sc->oid(), + tbl_oid, ct, jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, + jobInfo.statementId, jobInfo.rm); + pcs->logger(jobInfo.logger); pcs->alias(alias); pcs->view(view); pcs->name(sc->columnName()); @@ -1576,7 +1633,11 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) if (filterWithDictionary(dictOid, jobInfo.stringScanThreshold)) { - pDictionaryStep* pds = new pDictionaryStep(dictOid, tbl_oid, ct, jobInfo); + pDictionaryStep* pds = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, dictOid, + ct.ddn.compressionType, tbl_oid, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pds->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid] = sc->oid(); pds->alias(alias); pds->view(view); @@ -1593,7 +1654,7 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) spdl1->fifoDL(dl1); dl1->OID(sc->oid()); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); pcs->outputAssociation(outJs1); @@ -1603,12 +1664,12 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) spdl2->stringDL(dl2); dl2->OID(sc->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); pds->outputAssociation(outJs2); //Associate pcs with pds - JobStepAssociation outJs; + JobStepAssociation outJs(jobInfo.status); outJs.outAdd(spdl1); pds->inputAssociation(outJs); @@ -1639,7 +1700,11 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) } else { - pDictionaryScan* pds = new pDictionaryScan(dictOid, tbl_oid, ct, jobInfo); + pDictionaryScan* pds = new pDictionaryScan(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, dictOid, + ct.ddn.compressionType, tbl_oid, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pds->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid] = sc->oid(); pds->alias(alias); pds->view(view); @@ -1653,7 +1718,12 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) // save for expression transformation pds->addFilter(sf); - TupleHashJoinStep* thj = new TupleHashJoinStep(jobInfo); + TupleHashJoinStep* thj = new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm); + thj->logger(jobInfo.logger); thj->tableOid1(0); thj->tableOid2(tbl_oid); thj->alias1(alias); @@ -1664,6 +1734,7 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) thj->schema2(schema); thj->oid1(sc->oid()); thj->oid2(sc->oid()); +// thj->joinId(jobInfo.joinNum++); thj->joinId(0); thj->setJoinType(INNER); @@ -1691,7 +1762,7 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) spdl1->rowGroupDL(dl1); dl1->OID(dictOid); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); pds->outputAssociation(outJs1); @@ -1701,11 +1772,11 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) spdl2->rowGroupDL(dl2); dl2->OID(sc->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); pcs->outputAssociation(outJs2); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl1); outJs3.outAdd(spdl2); sjstep.reset(pds); @@ -1763,11 +1834,6 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: value = 0; rf = 0; break; @@ -1805,27 +1871,27 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) " (" << cc->constval() << ')' << endl; if (sf->indexFlag() == 0) { - pColStep* pcs = NULL; - if (pc == NULL) - pcs = new pColStep(sc->oid(), tbl_oid, ct, jobInfo); - else - pcs = new PseudoColStep(sc->oid(), tbl_oid, pc->pseudoType(), ct, jobInfo); + pColStep* pcss = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, + sc->oid(), tbl_oid, ct, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pcss->logger(jobInfo.logger); if (sc->isInfiniDB()) - pcs->addFilter(cop, value, rf); - pcs->alias(alias); - pcs->view(view); - pcs->name(sc->columnName()); - pcs->schema(sc->schemaName()); - pcs->cardinality(sf->cardinality()); - - sjstep.reset(pcs); + pcss->addFilter(cop, value, rf); + pcss->alias(alias); + pcss->view(view); + pcss->name(sc->columnName()); + pcss->schema(sc->schemaName()); + pcss->cardinality(sf->cardinality()); + + sjstep.reset(pcss); jsv.push_back(sjstep); // save for expression transformation - pcs->addFilter(sf); + pcss->addFilter(sf); TupleInfo ti(setTupleInfo(ct, sc->oid(), jobInfo, tbl_oid, sc, alias)); - pcs->tupleId(ti.key); + pcss->tupleId(ti.key); if (dictOid > 0) // cc->type() == ConstantColumn::NULLDATA { @@ -1847,18 +1913,19 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) indexName.table = sc->tableName(); indexName.index = sc->indexName(); CalpontSystemCatalog::IndexOID indexOID = jobInfo.csc->lookupIndexNbr(indexName); - pIdxWalk* pidxw = new pIdxWalk(JobStepAssociation(), JobStepAssociation(), 0, + pIdxWalk* pidxw = new pIdxWalk(JobStepAssociation(jobInfo.status), JobStepAssociation(jobInfo.status), 0, jobInfo.csc, indexOID.objnum, sc->oid(), tbl_oid, jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId); + pidxw->logger(jobInfo.logger); pidxw->addSearchStr(cop, value); pidxw->cardinality(sf->cardinality()); sjstep.reset(pidxw); jsv.push_back(sjstep); - pIdxList* pidxL = new pIdxList(JobStepAssociation(), - JobStepAssociation(), 0, jobInfo.csc, + pIdxList* pidxL = new pIdxList(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, indexOID.listOID, tbl_oid, jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId); @@ -1867,7 +1934,7 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) ZonedDL* dl1 = new ZonedDL(1, jobInfo.rm); dl1->OID(indexOID.objnum); spdl1->zonedDL(dl1); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); pidxw->outputAssociation(outJs1); @@ -1879,10 +1946,11 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) ZonedDL* dl2 = new ZonedDL(1, jobInfo.rm); dl2->OID(indexOID.listOID); spdl2->zonedDL(dl2); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); pidxL->outputAssociation(outJs2); + pidxL->logger(jobInfo.logger); sjstep.reset(pidxL); jsv.push_back(sjstep); #endif @@ -1895,6 +1963,13 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) SimpleColumn* sc1 = static_cast(lhs); SimpleColumn* sc2 = static_cast(rhs); + // @bug 1349. no-op rules: + // 1. If two columns of a simple filter are of the two different tables, and the + // filter operator is not "=", no-op this simple filter, + // 2. If a join filter has "ANTI" option, no op this filter before ANTI hashjoin + // is supported in ExeMgr. + // @bug 1933. Throw exception instead of no-op for MySQL virtual table + // (no connector re-filter). // @bug 1496. handle non equal operator as expression in v-table mode if ((sc1->tableName() != sc2->tableName() || sc1->tableAlias() != sc2->tableAlias() || @@ -1904,20 +1979,16 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) return doExpressionFilter(sf, jobInfo); } - // @bug 1349. no-op rules: - // 1. If two columns of a simple filter are of the two different tables, and the - // filter operator is not "=", no-op this simple filter, - // 2. If a join filter has "ANTI" option, no op this filter before ANTI hashjoin - // is supported in ExeMgr. - // @bug 1933. Throw exception instead of no-op for MySQL virtual table - // (no connector re-filter). if (sf->joinFlag() == SimpleFilter::ANTI) throw runtime_error("Anti join is not currently supported"); - // Do a simple column join + if (!sc1->schemaName().empty()) + jobInfo.tables.insert(make_table(sc1->schemaName(), sc1->tableName())); + if (!sc2->schemaName().empty()) + jobInfo.tables.insert(make_table(sc2->schemaName(), sc2->tableName())); JobStepVector join = doJoin(sc1, sc2, jobInfo, sop, sf); // set cardinality for the hashjoin step. hj result card <= larger input card - uint32_t card = 0; + uint card = 0; if (sf->cardinality() > sc1->cardinality() && sf->cardinality() > sc2->cardinality()) card = (sc1->cardinality() > sc2->cardinality() ? sc1->cardinality() : sc2->cardinality()); else @@ -1940,16 +2011,7 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) else if (lhsType == ARITHMETICCOLUMN || rhsType == ARITHMETICCOLUMN || lhsType == FUNCTIONCOLUMN || rhsType == FUNCTIONCOLUMN) { - const ReturnedColumn* rc = static_cast(lhs); - if (rc && (!rc->joinInfo()) && rhsType == AGGREGATECOLUMN) - throw IDBExcept(ERR_AGG_IN_WHERE); - - // @bug5848, CP elimination for idbPartition(col) - JobStepVector sv; - if (optimizeIdbPatitionSimpleFilter(sf, sv, jobInfo)) - jsv.swap(sv); - else - jsv = doExpressionFilter(sf, jobInfo); + jsv = doExpressionFilter(sf, jobInfo); } else if (lhsType == SIMPLECOLUMN && (rhsType == AGGREGATECOLUMN || rhsType == ARITHMETICCOLUMN || rhsType == FUNCTIONCOLUMN)) @@ -1977,16 +2039,6 @@ const JobStepVector doSimpleFilter(SimpleFilter* sf, JobInfo& jobInfo) else throw logic_error("doSimpleFilter: Unhandled SimpleFilter."); } - else if (rhsType == WINDOWFUNCTIONCOLUMN) - { - // workaroud for IN subquery with window function - // window function as arguments of a function is not covered !! - jsv = doExpressionFilter(sf, jobInfo); - } - else if (lhsType == CONSTANTCOLUMN && rhsType == CONSTANTCOLUMN) - { - jsv = doExpressionFilter(sf, jobInfo); - } else { cerr << boldStart << "doSimpleFilter: Unhandled SimpleFilter: left = " << lhsType << @@ -2009,7 +2061,7 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) // Parse the join on filter to join steps and an expression step, if any. stack nodeStack; // stack used for pre-order traverse - set doneNodes; // solved joins and simple filters + vector doneNodes; // vector of joins and simple filters solved map cpMap; // link for node removal JobStepVector join; // join step with its projection steps set nodesToRemove; // nodes to be removed after converted to steps @@ -2025,9 +2077,6 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) // @bug5311, optimization for outer join on clause set tablesInJoin; - // @bug3683, function join - vector > fjCandidates; - // while stack is not empty while(!nodeStack.empty()) { @@ -2056,6 +2105,11 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) sc1->tableAlias() != sc2->tableAlias() || sc1->viewName() != sc2->viewName())) { + if (!sc1->schemaName().empty()) + jobInfo.tables.insert(make_table(sc1->schemaName(), sc1->tableName())); + if (!sc2->schemaName().empty()) + jobInfo.tables.insert(make_table(sc2->schemaName(), sc2->tableName())); + // @bug3037, workaround on join order, wish this can be corrected soon, // cascade outer table attribute. CalpontSystemCatalog::OID tableOid1 = tableOid(sc1, jobInfo.csc); @@ -2080,7 +2134,7 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) join = doJoin(sc1, sc2, jobInfo, sop, sf); // set cardinality for the hashjoin step. - uint32_t card = sf->cardinality(); + uint card = sf->cardinality(); if (sf->cardinality() > sc1->cardinality() && sf->cardinality() > sc2->cardinality()) card = ((sc1->cardinality() > sc2->cardinality()) ? @@ -2088,19 +2142,7 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) join[join.size()-1].get()->cardinality(card); jsv.insert(jsv.end(), join.begin(), join.end()); - doneNodes.insert(cn); - } - else - { - ExpressionStep* es = new ExpressionStep(jobInfo); - if (es == NULL) - throw runtime_error("Failed to create ExpressionStep 2"); - - SJSTEP sjstep; - es->expressionFilter(sf, jobInfo); - sjstep.reset(es); - if (es->functionJoinInfo()) - fjCandidates.push_back(make_pair(cn, sjstep)); + doneNodes.push_back(cn); } } @@ -2129,31 +2171,6 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) thjs = dynamic_cast(i->get()); } - // no simple column join found, try function join - if (thjs == NULL) - { - // check any expressions can be converted to function joins. - vector >::iterator i = fjCandidates.begin(); - while (i != fjCandidates.end()) - { - ExpressionStep* es = dynamic_cast((i->second).get()); - SJSTEP sjstep = expressionToFuncJoin(es, jobInfo); - idbassert(sjstep.get()); - jsv.push_back(sjstep); - - doneNodes.insert(i->first); - - i++; - } - } - - // check again if we got a join step. - for (JobStepVector::iterator i = jsv.begin(); i != jsv.end(); i++) - { - if (dynamic_cast(i->get()) != thjs) - thjs = dynamic_cast(i->get()); - } - if (thjs != NULL) { // @bug5311, optimization for outer join on clause, move out small side simple filters. @@ -2172,7 +2189,7 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) continue; SimpleFilter* sf = dynamic_cast(tn); - if ((sf != NULL) && (doneNodes.find(cn) == doneNodes.end())) + if (sf != NULL) { // joins are done, this is not a join. ReturnedColumn* lhs = sf->lhs(); @@ -2201,6 +2218,9 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) if (sc != NULL) { + if (!sc->schemaName().empty()) + jobInfo.tables.insert(make_table(sc->schemaName(), sc->tableName())); + CalpontSystemCatalog::OID tblOid = tableOid(sc, jobInfo.csc); uint64_t tid = getTableKey( jobInfo, tblOid, sc->tableAlias(), sc->schemaName(), sc->viewName()); @@ -2221,7 +2241,7 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) jsv.insert(jsv.end(), sfv.begin(), sfv.end()); - doneNodes.insert(cn); + doneNodes.push_back(cn); } } @@ -2243,7 +2263,7 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) // remove joins from the original filters ParseTree* nullTree = NULL; - for (set::iterator i = doneNodes.begin(); i != doneNodes.end() && isOk; i++) + for (vector::iterator i = doneNodes.begin(); i != doneNodes.end() && isOk; i++) { ParseTree* c = *i; map::iterator j = cpMap.find(c); @@ -2307,10 +2327,15 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) // construct an expression step, if additional comparison exists. if (isOk && filters != NULL && filters->data() != NULL) { - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + if (es == NULL) throw runtime_error("Failed to create ExpressionStep 1"); + es->logger(jobInfo.logger); es->expressionFilter(filters, jobInfo); es->associatedJoinId(thjs->joinId()); SJSTEP sjstep(es); @@ -2320,10 +2345,15 @@ const JobStepVector doOuterJoinOnFilter(OuterJoinOnFilter* oj, JobInfo& jobInfo) else { // Due to Calpont view handling, some joins may treated as expressions. - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + if (es == NULL) throw runtime_error("Failed to create ExpressionStep 1"); + es->logger(jobInfo.logger); es->expressionFilter(filters, jobInfo); SJSTEP sjstep(es); jsv.push_back(sjstep); @@ -2371,10 +2401,12 @@ bool tryCombineDictionary(JobStepVector& jsv1, JobStepVector& jsv2, int8_t bop) pDictionaryStep* pdsp = dynamic_cast(iter->get()); if (pdsp != NULL && pdsp->onClauseFilter() == onClauseFilter) { + pDictionaryStep* pdsp = dynamic_cast((*iter).get()); + // If the OID's match and the BOP's match and the previous step is pcolstep, // then append the filters. if ((ipdsp->tupleId() == pdsp->tupleId()) && - (dynamic_cast((iter-1)->get()) != NULL)) + (typeid(*((iter-1)->get())) == typeid(pColStep))) { if (pdsp->BOP() == BOP_NONE) { @@ -2484,6 +2516,7 @@ bool tryCombineFilters(JobStepVector& jsv1, JobStepVector& jsv2, int8_t bop) // non-dictionary filters if (jsv2.size() != 1) return false; + if (typeid(*jsv2.back().get()) != typeid(pColStep)) return false; pColStep* ipcsp = dynamic_cast(jsv2.back().get()); if (ipcsp == NULL) @@ -2505,6 +2538,7 @@ bool tryCombineFilters(JobStepVector& jsv1, JobStepVector& jsv2, int8_t bop) pColStep* pcsp = dynamic_cast(iter->get()); if (pcsp != NULL && pcsp->onClauseFilter() == onClauseFilter) { + pColStep* pcsp = dynamic_cast((*iter).get()); idbassert(pcsp); // If the OID's match and the BOP's match then append the filters if (ipcsp->tupleId() == pcsp->tupleId()) @@ -2536,7 +2570,6 @@ bool tryCombineFilters(JobStepVector& jsv1, JobStepVector& jsv2, int8_t bop) return false; } - const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) { JobStepVector jsv; @@ -2551,20 +2584,19 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) { SOP sop; - const SSC sc = boost::dynamic_pointer_cast(cf->col()); + const SSC sc = cf->col(); // if column from subquery - if (!sc || sc->schemaName().empty()) + if (sc->schemaName().empty()) { return doExpressionFilter(cf, jobInfo); } + jobInfo.tables.insert(make_table(sc->schemaName(), sc->tableName())); ConstantFilter::FilterList fl = cf->filterList(); CalpontSystemCatalog::OID dictOid = 0; CalpontSystemCatalog::ColType ct = sc.get()->colType(); - PseudoColumn* pc = dynamic_cast(sc.get()); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (!sc->schemaName().empty() && sc->isInfiniDB() && !pc) + if (!sc->schemaName().empty() && sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X CalpontSystemCatalog::OID tbOID = tableOid(sc.get(), jobInfo.csc); @@ -2577,7 +2609,11 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) cout << "Emit pTokenByScan/pCol for SimpleColumn op ConstantColumn " "[op ConstantColumn]" << endl; - pColStep* pcs = new pColStep(sc->oid(), tbOID, ct, jobInfo); + pColStep* pcs = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, + jobInfo.csc, sc->oid(), tbOID, ct, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pcs->logger(jobInfo.logger); pcs->alias(alias); pcs->view(view); pcs->name(sc->columnName()); @@ -2586,7 +2622,11 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) if (filterWithDictionary(dictOid, jobInfo.stringScanThreshold)) { - pDictionaryStep* pds = new pDictionaryStep(dictOid, tbOID, ct, jobInfo); + pDictionaryStep* pds = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, dictOid, + ct.ddn.compressionType, tbOID, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pds->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid] = sc->oid(); pds->alias(alias); pds->view(view); @@ -2597,6 +2637,7 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) pds->setBOP(bop2num(op)); //Add the filter(s) + uint64_t card = 0; for (unsigned i = 0; i < fl.size(); i++) { const SSFP sf = fl[i]; @@ -2616,6 +2657,7 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) size_t spos = value.find_last_not_of(" "); if (spos != string::npos) value = value.substr(0, spos+1); pds->addFilter(cop, value); + card = sf->cardinality(); } // data list for pcolstep output @@ -2624,7 +2666,7 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) spdl1->fifoDL(dl1); dl1->OID(sc->oid()); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); pcs->outputAssociation(outJs1); @@ -2634,12 +2676,12 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) spdl2->stringDL(dl2); dl2->OID(sc->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); pds->outputAssociation(outJs2); //Associate pcs with pds - JobStepAssociation outJs; + JobStepAssociation outJs(jobInfo.status); outJs.outAdd(spdl1); pds->inputAssociation(outJs); @@ -2670,7 +2712,11 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) } else { - pDictionaryScan* pds = new pDictionaryScan(dictOid, tbOID, ct, jobInfo); + pDictionaryScan* pds = new pDictionaryScan(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, dictOid, + ct.ddn.compressionType, tbOID, jobInfo.sessionId, jobInfo.txnId, + jobInfo.verId, 0, jobInfo.statementId, jobInfo.rm); + pds->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid] = sc.get()->oid(); pds->alias(alias); pds->view(view); @@ -2680,6 +2726,7 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) pds->setBOP(bop2num(op)); //Add the filter(s) + uint64_t card = 0; for (unsigned i = 0; i < fl.size(); i++) { const SSFP sf = fl[i]; @@ -2699,12 +2746,18 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) size_t spos = value.find_last_not_of(" "); if (spos != string::npos) value = value.substr(0, spos+1); pds->addFilter(cop, value); + card = sf->cardinality(); } // save for expression transformation pds->addFilter(cf); - TupleHashJoinStep* thj = new TupleHashJoinStep(jobInfo); + TupleHashJoinStep* thj = new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm); + thj->logger(jobInfo.logger); thj->tableOid1(0); thj->tableOid2(tbOID); thj->alias1(alias); @@ -2715,6 +2768,7 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) thj->schema2(schema); thj->oid1(sc->oid()); thj->oid2(sc->oid()); +// thj->joinId(jobInfo.joinNum++); thj->joinId(0); thj->setJoinType(INNER); @@ -2724,7 +2778,7 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) spdl1->rowGroupDL(dl1); dl1->OID(dictOid); - JobStepAssociation outJs1; + JobStepAssociation outJs1(jobInfo.status); outJs1.outAdd(spdl1); pds->outputAssociation(outJs1); @@ -2733,11 +2787,11 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) spdl2->rowGroupDL(dl2); dl2->OID(sc->oid()); - JobStepAssociation outJs2; + JobStepAssociation outJs2(jobInfo.status); outJs2.outAdd(spdl2); pcs->outputAssociation(outJs2); - JobStepAssociation outJs3; + JobStepAssociation outJs3(jobInfo.status); outJs3.outAdd(spdl1); outJs3.outAdd(spdl2); thj->inputAssociation(outJs3); @@ -2774,21 +2828,20 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) CalpontSystemCatalog::OID tblOid = tableOid(sc.get(), jobInfo.csc); string alias(extractTableAlias(sc)); - pColStep* pcs = NULL; - if (pc == NULL) - pcs = new pColStep(sc->oid(), tblOid, ct, jobInfo); - else - pcs = new PseudoColStep(sc->oid(), tblOid, pc->pseudoType(), ct, jobInfo); - - pcs->alias(extractTableAlias(sc)); - pcs->view(sc->viewName()); - pcs->name(sc->columnName()); - pcs->schema(sc->schemaName()); + pColStep* pcss = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), 0, jobInfo.csc, sc->oid(), tblOid, ct, + jobInfo.sessionId, jobInfo.txnId, jobInfo.verId, 0, jobInfo.statementId, + jobInfo.rm); + pcss->logger(jobInfo.logger); + pcss->alias(extractTableAlias(sc)); + pcss->view(sc->viewName()); + pcss->name(sc->columnName()); + pcss->schema(sc->schemaName()); if (sc->isInfiniDB()) { if (op) - pcs->setBOP(bop2num(op)); + pcss->setBOP(bop2num(op)); for (unsigned i = 0; i < fl.size(); i++) { @@ -2824,23 +2877,42 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) if (ConstantColumn::NULLDATA == cc->type() && (opeq == *sop || opne == *sop)) cop = COMPARE_NIL; - pcs->addFilter(cop, value, rf); + pcss->addFilter(cop, value, rf); + } + if (!cf->functionName().empty()) + { + //This is one of the CNX UDF functions. We want to make this look like + //SimpleColumn op ConstantColumn, but mark the SimpleColumn as using a distributed UDF + string fPfx(cf->functionName(), 0, 6); + if (fPfx != "cpfunc") + { + string fn = cf->functionName(); + if (fn == "abs" || fn == "acos" || fn == "asin" || fn == "atan" || fn == "cos" || fn == "cot" || + fn == "exp" || fn == "ln" || fn == "log" || fn == "log2" || fn == "log10" || fn == "sin" || + fn == "sqrt" || fn == "tan") + ; + else + throw runtime_error("Unhandled distributed UDF"); + } + //set the func on pColStep here... + pcss->udfName(cf->functionName()); } } + // save for expression transformation - pcs->addFilter(cf); + pcss->addFilter(cf); - sjstep.reset(pcs); + sjstep.reset(pcss); jsv.push_back(sjstep); //XXX use this before connector sets colType in sc correctly. CalpontSystemCatalog::ColType ct = sc->colType(); - if (!sc->schemaName().empty() && sc->isInfiniDB() && !pc) + if (!sc->schemaName().empty() && sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); TupleInfo ti(setTupleInfo(ct, sc->oid(), jobInfo, tblOid, sc.get(), alias)); //X TupleInfo ti(setTupleInfo(sc->colType(), sc->oid(), jobInfo, tblOid, sc.get(), alias)); - pcs->tupleId(ti.key); + pcss->tupleId(ti.key); } } else @@ -2854,112 +2926,6 @@ const JobStepVector doConstantFilter(const ConstantFilter* cf, JobInfo& jobInfo) } -const JobStepVector doFunctionFilter(const ParseTree* n, JobInfo& jobInfo) -{ - FunctionColumn* fc = dynamic_cast(n->data()); - idbassert(fc); - - JobStepVector jsv; - string functionName = ba::to_lower_copy(fc->functionName()); - if (functionName.compare("in") == 0 || functionName.compare(" in ") == 0) - { - const funcexp::FunctionParm& parms = fc->functionParms(); - FunctionColumn* parm0Fc = dynamic_cast(parms[0]->data()); - PseudoColumn* parm0Pc = dynamic_cast(parms[0]->data()); - vector > constParms(3); - uint64_t constParmsCount = 0; - if (parm0Fc && parm0Fc->functionName().compare("idbpartition") == 0) - { - for (uint64_t i = 1; i < parms.size(); i++) - { - ConstantColumn* cc = dynamic_cast(parms[i]->data()); - if (cc) - { - vector cv; - boost::split(cv, cc->constval(), boost::is_any_of(".")); - if (cv.size() == 3) - { - constParms[1].push_back(cv[0]); - constParms[2].push_back(cv[1]); - constParms[0].push_back(cv[2]); - constParmsCount++; - } - } - } - - if (constParmsCount == (parms.size() - 1)) - { - const funcexp::FunctionParm& pcs = parm0Fc->functionParms(); - for (uint64_t i = 0; i < 3; i++) - { - ConstantFilter* cf = new ConstantFilter(); - SOP sop(new LogicOperator("or")); - PseudoColumn* pc = dynamic_cast(pcs[i]->data()); - idbassert(pc); - SSC col(pc->clone()); - cf->op(sop); - cf->col(col); - sop.reset(new PredicateOperator("=")); - for (uint64_t j = 0; j < constParmsCount; j++) - { - SimpleFilter* f = new SimpleFilter(sop, col->clone(), - new ConstantColumn(constParms[i][j])); - cf->pushFilter(f); - } - - JobStepVector sv = doConstantFilter(cf, jobInfo); - delete cf; - - jsv.insert(jsv.end(), sv.begin(), sv.end()); - } - } - - // put the separate filtered resulted together - JobStepVector sv = doExpressionFilter(n, jobInfo); - jsv.insert(jsv.end(), sv.begin(), sv.end()); - } - else if (parm0Pc != NULL) - { - for (uint64_t i = 1; i < parms.size(); i++) - { - ConstantColumn* cc = dynamic_cast(parms[i]->data()); - if (cc) - { - constParms[0].push_back(cc->constval()); - constParmsCount++; - } - } - - if (constParmsCount == (parms.size() - 1)) - { - ConstantFilter* cf = new ConstantFilter(); - SOP sop(new LogicOperator("or")); - SSC col(parm0Pc->clone()); - cf->op(sop); - cf->col(col); - sop.reset(new PredicateOperator("=")); - for (uint64_t j = 0; j < constParmsCount; j++) - { - SimpleFilter* f = new SimpleFilter(sop, col->clone(), - new ConstantColumn(constParms[0][j])); - cf->pushFilter(f); - } - - JobStepVector sv = doConstantFilter(cf, jobInfo); - delete cf; - - jsv.insert(jsv.end(), sv.begin(), sv.end()); - } - } - } - - if (jsv.empty()) - jsv = doExpressionFilter(n, jobInfo); - - return jsv; -} - - void doAND(JobStepVector& jsv, JobInfo& jobInfo) { // idbassert(jobInfo.stack.size() >= 2); @@ -3009,9 +2975,9 @@ void doOR(const ParseTree* n, JobStepVector& jsv, JobInfo& jobInfo, bool tryComb jobInfo.stack.pop(); // @bug3570, attempt to combine only if there is one column involved. - if (tryCombine && ((jsv.size() == 1 && dynamic_cast(jsv.begin()->get()) != NULL) || - (jsv.size() == 2 && dynamic_cast((jsv.end()-1)->get()) != NULL) || - (jsv.size() == 3 && dynamic_cast(jsv.begin()->get()) != NULL)) && + if (tryCombine && ((jsv.size() == 1 && (typeid(*(jsv.begin()->get())) == typeid(pColStep))) || + (jsv.size() == 2 && (typeid(*((jsv.end()-1)->get())) == typeid(pDictionaryStep))) || + (jsv.size() == 3 && (typeid(*(jsv.begin()->get())) == typeid(pDictionaryScan)))) && tryCombineFilters(jsv, rhv, BOP_OR)) { jobInfo.stack.push(jsv); @@ -3076,9 +3042,6 @@ JLF_ExecPlanToJobList::walkTree(ParseTree* n, void* obj) jobInfo->stack.push(jsv); break; case FUNCTIONCOLUMN: - jsv = doFunctionFilter(n, *jobInfo); - jobInfo->stack.push(jsv); - break; case ARITHMETICCOLUMN: jsv = doExpressionFilter(n, *jobInfo); jobInfo->stack.push(jsv); diff --git a/dbcon/joblist/jlf_execplantojoblist.h b/dbcon/joblist/jlf_execplantojoblist.h index 3b6b1938..d63f45ca 100644 --- a/dbcon/joblist/jlf_execplantojoblist.h +++ b/dbcon/joblist/jlf_execplantojoblist.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: jlf_execplantojoblist.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: jlf_execplantojoblist.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/joblist/jlf_graphics.cpp b/dbcon/joblist/jlf_graphics.cpp index c81898ee..6f301488 100644 --- a/dbcon/joblist/jlf_graphics.cpp +++ b/dbcon/joblist/jlf_graphics.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_graphics.cpp 9550 2013-05-17 23:58:07Z xlou $ +// $Id: jlf_graphics.cpp 8526 2012-05-17 02:28:10Z xlou $ #include using namespace std; @@ -24,9 +24,6 @@ using namespace std; #include "primitivestep.h" #include "crossenginestep.h" #include "subquerystep.h" -#include "windowfunctionstep.h" -#include "tupleaggregatestep.h" -#include "tupleannexstep.h" #include "tuplehashjoin.h" #include "tupleunion.h" using namespace joblist; @@ -148,22 +145,6 @@ ostream& writeDotCmds(ostream& dotFile, const JobStepVector& query, const JobSte dotFile << " shape=box style=bold"; dotFile << " peripheries=2"; } - else if (typeid(*(qsi->get())) == typeid(TupleAggregateStep)) - { - dotFile << "\""; - dotFile << " shape=triangle orientation=180"; - } - else if (typeid(*(qsi->get())) == typeid(TupleAnnexStep)) - { - dotFile << "\""; - dotFile << " shape=star"; - } - else if (typeid(*(qsi->get())) == typeid(WindowFunctionStep)) - { - dotFile << "\""; - dotFile << " shape=triangle orientation=180"; - dotFile << " peripheries=2"; - } // else if (typeid(*(qsi->get())) == typeid(AggregateFilterStep)) // { // dotFile << "\""; @@ -181,7 +162,7 @@ ostream& writeDotCmds(ostream& dotFile, const JobStepVector& query, const JobSte { ptrdiff_t dloutptr; DataList_t* dlout = qsi->get()->outputAssociation().outAt(i)->dataList(); - uint32_t numConsumers = qsi->get()->outputAssociation().outAt(i)->getNumConsumers(); + uint numConsumers = qsi->get()->outputAssociation().outAt(i)->getNumConsumers(); if (dlout) { @@ -321,7 +302,7 @@ ostream& writeDotCmds(ostream& dotFile, const JobStepVector& query, const JobSte { ptrdiff_t dloutptr; DataList_t* dlout = psi->get()->outputAssociation().outAt(i)->dataList(); - uint32_t numConsumers = psi->get()->outputAssociation().outAt(i)->getNumConsumers(); + uint numConsumers = psi->get()->outputAssociation().outAt(i)->getNumConsumers(); if (dlout) { diff --git a/dbcon/joblist/jlf_graphics.h b/dbcon/joblist/jlf_graphics.h index 9a28d95d..ae3fde11 100644 --- a/dbcon/joblist/jlf_graphics.h +++ b/dbcon/joblist/jlf_graphics.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_graphics.h 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: jlf_graphics.h 8436 2012-04-04 18:18:21Z rdempsey $ /** @file */ diff --git a/dbcon/joblist/jlf_subquery.cpp b/dbcon/joblist/jlf_subquery.cpp index 01ea078d..848d9931 100644 --- a/dbcon/joblist/jlf_subquery.cpp +++ b/dbcon/joblist/jlf_subquery.cpp @@ -34,11 +34,9 @@ using namespace boost; #include "constantcolumn.h" #include "existsfilter.h" #include "predicateoperator.h" -#include "pseudocolumn.h" #include "selectfilter.h" #include "simplefilter.h" #include "simplescalarfilter.h" -#include "windowfunctioncolumn.h" using namespace execplan; #include "rowgroup.h" @@ -86,7 +84,6 @@ void getColumnValue(ConstantColumn** cc, uint64_t i, const Row& row) // else > 0; fall through case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: data = row.getIntField(i); oss << (data / IDB_pow[row.getScale(i)]); if (row.getScale(i) > 0) @@ -100,17 +97,7 @@ void getColumnValue(ConstantColumn** cc, uint64_t i, const Row& row) IDB_Decimal(data, row.getScale(i), row.getPrecision(i))); break; - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - oss << row.getUintField(i); - *cc = new ConstantColumn(oss.str(), row.getUintField(i)); - break; - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: oss << fixed << row.getFloatField(i); *cc = new ConstantColumn(oss.str(), (double) row.getFloatField(i)); break; @@ -157,24 +144,25 @@ bool simpleScalarFilterToParseTree(SimpleScalarFilter* sf, ParseTree*& pt, JobIn lop = "or"; // Transformer sub to a scalar result. - SErrorInfo errorInfo(jobInfo.errorInfo); - SimpleScalarTransformer transformer(&jobInfo, errorInfo, false); + SErrorInfo status(jobInfo.status); + SimpleScalarTransformer transformer(&jobInfo, status, false); transformer.makeSubQueryStep(csep); // Do not catch exceptions here, let caller handle them. transformer.run(); // if subquery errored out - if (errorInfo->errCode) + if (status->errCode) { ostringstream oss; oss << "Sub-query failed: "; - if (errorInfo->errMsg.empty()) - { - oss << "error code " << errorInfo->errCode; - errorInfo->errMsg = oss.str(); - } - throw runtime_error(errorInfo->errMsg); + if (status->errMsg.empty()) + oss << "error code " << status->errCode; + else + oss << status->errMsg; + + status->errMsg = oss.str(); + throw runtime_error(status->errMsg); } // Construct simple filters based on the scalar result. @@ -256,35 +244,35 @@ void ssfInHaving(ParseTree* pt, void* obj) } -void getCorrelatedFilters(ParseTree* pt, void* obj) +void getSemiJoins(ParseTree* pt, void* obj) { SimpleFilter* sf = dynamic_cast(pt->data()); if (sf != NULL) { - ReturnedColumn* rc1 = dynamic_cast(sf->lhs()); - ReturnedColumn* rc2 = dynamic_cast(sf->rhs()); + SimpleColumn* sc1 = dynamic_cast(sf->lhs()); + SimpleColumn* sc2 = dynamic_cast(sf->rhs()); - bool correlated = false; - if (rc1 != NULL && rc1->joinInfo() != 0) - correlated = true; + bool semijoin = false; + if (sc1 != NULL && sc1->joinInfo() != 0) + semijoin = true; - if (rc2 != NULL && rc2->joinInfo() != 0) - correlated = true; + if (sc2 != NULL && sc2->joinInfo() != 0) + semijoin = true; - if (correlated) + if (semijoin) { - ParseTree** correlatedFilters = reinterpret_cast(obj); - if (*correlatedFilters == NULL) + ParseTree** semiJoins = reinterpret_cast(obj); + if (*semiJoins == NULL) { - *correlatedFilters = new ParseTree(sf); + *semiJoins = new ParseTree(sf); } else { - ParseTree* left = *correlatedFilters; - *correlatedFilters = new ParseTree(new LogicOperator("and")); - (*correlatedFilters)->left(left); - (*correlatedFilters)->right(new ParseTree(sf)); + ParseTree* left = *semiJoins; + *semiJoins = new ParseTree(new LogicOperator("and")); + (*semiJoins)->left(left); + (*semiJoins)->right(new ParseTree(sf)); } pt->data(NULL); @@ -347,12 +335,16 @@ void handleNotIn(JobStepVector& jsv, JobInfo* jobInfo) sop->resultType(sop->operationType()); SimpleFilter* sf = new SimpleFilter(sop, lhs, rhs); - ExpressionStep* es = new ExpressionStep(*jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo->sessionId, + jobInfo->txnId, + jobInfo->verId, + jobInfo->statementId); + if (es == NULL) throw runtime_error("Failed to create ExpressionStep 2"); + es->logger(jobInfo->logger); es->expressionFilter(sf, *jobInfo); - es->resetJoinInfo(); // Not to be done as join i->reset(es); delete sf; @@ -382,40 +374,12 @@ bool isNotInSubquery(JobStepVector& jsv) } -void alterCsepInExistsFilter(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) -{ - // This is for window function in IN/EXISTS sub-query. - // Replace an expression of window functions with indivisual window functions. - RetColsVector& retCols = csep->returnedCols(); - RetColsVector wcs; - for (RetColsVector::iterator i = retCols.begin(); i < retCols.end(); i++) - { - const vector& wcList = (*i)->windowfunctionColumnList(); - if (!wcList.empty()) - { - vector::const_iterator j = wcList.begin(); - while (j != wcList.end()) - wcs.push_back(SRCP((*j++)->clone())); - - // a little optimization, eliminate the expression in select clause - // replace the window function expression with the 1st windowfunction - (*i) = wcs[0]; - } - } - - if (wcs.size() > 1) - retCols.insert(retCols.end(), wcs.begin()+1, wcs.end()); -} - - void doCorrelatedExists(const ExistsFilter* ef, JobInfo& jobInfo) { // Transformer sub to a subquery step. - SErrorInfo errorInfo(jobInfo.errorInfo); - SubQueryTransformer transformer(&jobInfo, errorInfo); - CalpontSelectExecutionPlan* csep = ef->sub().get(); - //alterCsepInExistsFilter(csep, jobInfo); - SJSTEP subQueryStep = transformer.makeSubQueryStep(csep); + SErrorInfo status(jobInfo.status); + SubQueryTransformer transformer(&jobInfo, status); + SJSTEP subQueryStep = transformer.makeSubQueryStep(ef->sub().get()); // @bug3524, special handling of not in. JobStepVector& jsv = transformer.correlatedSteps(); @@ -438,8 +402,8 @@ void doNonCorrelatedExists(const ExistsFilter* ef, JobInfo& jobInfo) if (!noFrom) { // Transformer sub to a scalar result set. - SErrorInfo errorInfo(new ErrorInfo()); - SimpleScalarTransformer transformer(&jobInfo, errorInfo, true); + SErrorInfo status(new ErrorInfo()); + SimpleScalarTransformer transformer(&jobInfo, status, true); transformer.makeSubQueryStep(ef->sub().get()); // @bug 2839. error out in-relelvant correlated column case @@ -489,7 +453,13 @@ void doNonCorrelatedExists(const ExistsFilter* ef, JobInfo& jobInfo) } JobStepVector jsv; - SJSTEP tcs(new TupleConstantBooleanStep(jobInfo, exists)); + SJSTEP tcs(new TupleConstantBooleanStep(JobStepAssociation(), + JobStepAssociation(), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId, + exists)); jsv.push_back(tcs); jobInfo.stack.push(jsv); } @@ -499,9 +469,9 @@ const SRCP doSelectSubquery(CalpontExecutionPlan* ep, SRCP& sc, JobInfo& jobInfo { CalpontSelectExecutionPlan* csep = dynamic_cast(ep); SRCP rc; - SErrorInfo errorInfo(jobInfo.errorInfo); - string subView = dynamic_cast(sc.get())->viewName(); - SubQueryTransformer transformer(&jobInfo, errorInfo, subView); + SErrorInfo status(jobInfo.status); + jobInfo.subView = dynamic_cast(sc.get())->viewName(); + SubQueryTransformer transformer(&jobInfo, status); transformer.setVarbinaryOK(); SJSTEP subQueryStep = transformer.makeSubQueryStep(csep); if (transformer.correlatedSteps().size() > 0) @@ -584,7 +554,13 @@ void doSimpleScalarFilter(ParseTree* p, JobInfo& jobInfo) // not a scalar result delete parseTree; JobStepVector jsv; - SJSTEP tcs(new TupleConstantBooleanStep(jobInfo, false)); + SJSTEP tcs(new TupleConstantBooleanStep(JobStepAssociation(), + JobStepAssociation(), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId, + false)); jsv.push_back(tcs); jobInfo.stack.push(jsv); } @@ -607,8 +583,8 @@ void doSelectFilter(const ParseTree* p, JobInfo& jobInfo) const SelectFilter* sf = dynamic_cast(p->data()); idbassert(sf != NULL); - SErrorInfo errorInfo(jobInfo.errorInfo); - SubQueryTransformer transformer(&jobInfo, errorInfo); + SErrorInfo status(jobInfo.status); + SubQueryTransformer transformer(&jobInfo, status); SJSTEP subQueryStep = transformer.makeSubQueryStep(sf->sub().get()); transformer.updateCorrelateInfo(); JobStepVector jsv = transformer.correlatedSteps(); @@ -650,7 +626,11 @@ void doSelectFilter(const ParseTree* p, JobInfo& jobInfo) if (pt != NULL) { - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + es->logger(jobInfo.logger); es->expressionFilter(pt, jobInfo); es->selectFilter(true); delete pt; @@ -659,6 +639,7 @@ void doSelectFilter(const ParseTree* p, JobInfo& jobInfo) } jobInfo.stack.push(jsv); + } @@ -674,15 +655,15 @@ void preprocessHavingClause(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) havings->walk(ssfInHaving, &jobInfo); // check correlated columns in having - ParseTree* correlatedFilters = NULL; - havings->walk(getCorrelatedFilters, &correlatedFilters); + ParseTree* semiJoins = NULL; + havings->walk(getSemiJoins, &semiJoins); trim(havings); - if (correlatedFilters != NULL) + if (semiJoins != NULL) { ParseTree* newFilters = new ParseTree(new LogicOperator("and")); newFilters->left(csep->filters()); - newFilters->right(correlatedFilters); + newFilters->right(semiJoins); csep->filters(newFilters); csep->having(havings); @@ -693,12 +674,16 @@ void preprocessHavingClause(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) int doFromSubquery(CalpontExecutionPlan* ep, const string& alias, const string& view, JobInfo& jobInfo) { CalpontSelectExecutionPlan* csep = dynamic_cast(ep); - SErrorInfo errorInfo(jobInfo.errorInfo); - SubQueryTransformer transformer(&jobInfo, errorInfo, alias, view); + SErrorInfo status(jobInfo.status); + jobInfo.subView = view; + SubQueryTransformer transformer(&jobInfo, status, alias); transformer.setVarbinaryOK(); SJSTEP subQueryStep = transformer.makeSubQueryStep(csep, true); subQueryStep->view(view); - SJSTEP subAd(new SubAdapterStep(subQueryStep, jobInfo)); + SJSTEP subAd(new SubAdapterStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + subQueryStep)); jobInfo.selectAndFromSubs.push_back(subAd); return CNX_VTABLE_ID; @@ -721,7 +706,7 @@ void addOrderByAndLimit(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) if (dynamic_cast(orderByCols[i].get()) != NULL) continue; - uint32_t tupleKey = -1; + uint tupleKey = -1; SimpleColumn* sc = dynamic_cast(orderByCols[i].get()); if (sc != NULL) { @@ -737,15 +722,14 @@ void addOrderByAndLimit(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) { ct = sc->colType(); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (sc->isInfiniDB() && !(dynamic_cast(sc))) + if (sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X dictOid = isDictCol(ct); } else { - if (sc->colPosition() == -1) + if (sc->colPosition() == (uint64_t) -1) { sc = dynamic_cast(jobInfo.deliveredCols[sc->orderPos()].get()); } @@ -754,7 +738,7 @@ void addOrderByAndLimit(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) sc->oid((tblOid+1) + sc->colPosition()); } oid = sc->oid(); - ct = jobInfo.vtableColTypes[UniqId(oid, alias, "", "")]; + ct = jobInfo.vtableColTypes[UniqId(oid, alias, schema, view)]; } tupleKey = getTupleKey(jobInfo, sc); @@ -796,15 +780,17 @@ void preprocessSelectSubquery(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo SJSTEP doUnionSub(CalpontExecutionPlan* ep, JobInfo& jobInfo) { CalpontSelectExecutionPlan* csep = dynamic_cast(ep); - SErrorInfo errorInfo(jobInfo.errorInfo); - SubQueryTransformer transformer(&jobInfo, errorInfo); + SErrorInfo status(jobInfo.status); + SubQueryTransformer transformer(&jobInfo, status); transformer.setVarbinaryOK(); SJSTEP subQueryStep = transformer.makeSubQueryStep(csep, false); - SJSTEP subAd(new SubAdapterStep(subQueryStep, jobInfo)); + SJSTEP subAd(new SubAdapterStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + subQueryStep)); return subAd; } - } // vim:ts=4 sw=4: diff --git a/dbcon/joblist/jlf_tuplejoblist.cpp b/dbcon/joblist/jlf_tuplejoblist.cpp index eb4d973a..21f25076 100644 --- a/dbcon/joblist/jlf_tuplejoblist.cpp +++ b/dbcon/joblist/jlf_tuplejoblist.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_tuplejoblist.cpp 9728 2013-07-26 22:08:20Z xlou $ +// $Id: jlf_tuplejoblist.cpp 9704 2013-07-17 19:18:23Z xlou $ #include @@ -51,20 +51,19 @@ using namespace logging; using namespace dataconvert; #include "elementtype.h" -#include "jlf_common.h" -#include "limitedorderby.h" #include "jobstep.h" #include "primitivestep.h" +#include "jlf_common.h" #include "crossenginestep.h" +#include "tuplehashjoin.h" +#include "tupleunion.h" #include "expressionstep.h" #include "subquerystep.h" #include "tupleaggregatestep.h" #include "tupleannexstep.h" #include "tupleconstantstep.h" -#include "tuplehashjoin.h" #include "tuplehavingstep.h" -#include "tupleunion.h" -#include "windowfunctionstep.h" +#include "limitedorderby.h" #include "configcpp.h" #include "jlf_tuplejoblist.h" using namespace joblist; @@ -75,7 +74,7 @@ namespace // construct a pcolstep from column key -void tupleKeyToProjectStep(uint32_t key, JobStepVector& jsv, JobInfo& jobInfo) +void tupleKeyToProjectStep(uint key, JobStepVector& jsv, JobInfo& jobInfo) { // this JSA is for pcolstep construct, is not taking input/output // because the pcolstep is to be added into TBPS @@ -86,7 +85,7 @@ void tupleKeyToProjectStep(uint32_t key, JobStepVector& jsv, JobInfo& jobInfo) if (mit != jobInfo.keyInfo->dictOidToColOid.end()) { oid = mit->second; - for (map::iterator i = jobInfo.keyInfo->dictKeyMap.begin(); + for (map::iterator i = jobInfo.keyInfo->dictKeyMap.begin(); i != jobInfo.keyInfo->dictKeyMap.end(); i++) { @@ -100,24 +99,34 @@ void tupleKeyToProjectStep(uint32_t key, JobStepVector& jsv, JobInfo& jobInfo) jobInfo.tokenOnly[key] = false; } - CalpontSystemCatalog::OID tableOid = jobInfo.keyInfo->tupleKeyToTableOid[key]; -// JobStepAssociation dummyJsa; -// AnyDataListSPtr adl(new AnyDataList()); -// RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); -// dl->OID(oid); -// adl->rowGroupDL(dl); -// dummyJsa.outAdd(adl); + CalpontSystemCatalog::OID tableOid = jobInfo.keyInfo->tupleKeyToTableOid.find(key)->second; + JobStepAssociation dummyJsa(jobInfo.status); + AnyDataListSPtr adl(new AnyDataList()); + RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); + dl->OID(oid); + adl->rowGroupDL(dl); + dummyJsa.outAdd(adl); CalpontSystemCatalog::ColType ct = jobInfo.keyInfo->colType[key]; if (jobInfo.keyInfo->token2DictTypeMap.find(key) != jobInfo.keyInfo->token2DictTypeMap.end()) ct = jobInfo.keyInfo->token2DictTypeMap[key]; - uint32_t pt = jobInfo.keyInfo->pseudoType[key]; - SJSTEP sjs; - if (pt == 0) - sjs.reset(new pColStep(oid, tableOid, ct, jobInfo)); - else - sjs.reset(new PseudoColStep(oid, tableOid, pt, ct, jobInfo)); + SJSTEP sjs(new pColStep(dummyJsa, + dummyJsa, + 0, + jobInfo.csc, + oid, + tableOid, + ct, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm, + jobInfo.flushInterval, + jobInfo.isExeMgr)); + sjs->logger(jobInfo.logger); sjs->alias(jobInfo.keyInfo->tupleKeyVec[key].fTable); sjs->view(jobInfo.keyInfo->tupleKeyVec[key].fView); sjs->schema(jobInfo.keyInfo->tupleKeyVec[key].fSchema); @@ -127,16 +136,30 @@ void tupleKeyToProjectStep(uint32_t key, JobStepVector& jsv, JobInfo& jobInfo) jsv.push_back(sjs); bool tokenOnly = false; - map::iterator toIt = jobInfo.tokenOnly.find(key); + map::iterator toIt = jobInfo.tokenOnly.find(key); if (toIt != jobInfo.tokenOnly.end()) tokenOnly = toIt->second; if (sjs.get()->isDictCol() && !tokenOnly) { // Need a dictionary step - uint32_t dictKey = jobInfo.keyInfo->dictKeyMap[key]; + uint dictKey = jobInfo.keyInfo->dictKeyMap[key]; CalpontSystemCatalog::OID dictOid = jobInfo.keyInfo->tupleKeyVec[dictKey].fId; - sjs.reset(new pDictionaryStep(dictOid, tableOid, ct, jobInfo)); + sjs.reset(new pDictionaryStep(dummyJsa, + dummyJsa, + 0, + jobInfo.csc, + dictOid, + ct.ddn.compressionType, + tableOid, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm, + jobInfo.flushInterval)); + sjs->logger(jobInfo.logger); sjs->alias(jobInfo.keyInfo->tupleKeyVec[dictKey].fTable); sjs->view(jobInfo.keyInfo->tupleKeyVec[dictKey].fView); sjs->schema(jobInfo.keyInfo->tupleKeyVec[dictKey].fSchema); @@ -150,11 +173,11 @@ void tupleKeyToProjectStep(uint32_t key, JobStepVector& jsv, JobInfo& jobInfo) } -inline void addColumnToRG(uint32_t cid, vector& pos, vector& oids, - vector& keys, vector& scale, vector& precision, +inline void addColumnToRG(uint tid, uint cid, vector& pos, vector& oids, + vector& keys, vector& scale, vector& precision, vector& types, JobInfo& jobInfo) { - TupleInfo ti(getTupleInfo(cid, jobInfo)); + TupleInfo ti(getTupleInfo(tid, cid, jobInfo)); pos.push_back(pos.back() + ti.width); oids.push_back(ti.oid); keys.push_back(ti.key); @@ -164,62 +187,62 @@ inline void addColumnToRG(uint32_t cid, vector& pos, vector& } -inline void addColumnInExpToRG(uint32_t cid, vector& pos, vector& oids, - vector& keys, vector& scale, vector& precision, +inline void addColumnInExpToRG(uint tid, uint cid, vector& pos, vector& oids, + vector& keys, vector& scale, vector& precision, vector& types, JobInfo& jobInfo) { if (jobInfo.keyInfo->dictKeyMap.find(cid) != jobInfo.keyInfo->dictKeyMap.end()) cid = jobInfo.keyInfo->dictKeyMap[cid]; if (find(keys.begin(), keys.end(), cid) == keys.end()) - addColumnToRG(cid, pos, oids, keys, scale, precision, types, jobInfo); + addColumnToRG(tid, cid, pos, oids, keys, scale, precision, types, jobInfo); } -inline void addColumnsToRG(uint32_t tid, vector& pos, vector& oids, - vector& keys, vector& scale, vector& precision, +inline void addColumnsToRG(uint tid, vector& pos, vector& oids, + vector& keys, vector& scale, vector& precision, vector& types, TableInfoMap& tableInfoMap, JobInfo& jobInfo) { // -- the selected columns - vector& pjCol = tableInfoMap[tid].fProjectCols; + vector& pjCol = tableInfoMap[tid].fProjectCols; for (unsigned i = 0; i < pjCol.size(); i++) { - addColumnToRG(pjCol[i], pos, oids, keys, scale, precision, types, jobInfo); + addColumnToRG(tid, pjCol[i], pos, oids, keys, scale, precision, types, jobInfo); } // -- any columns will be used in cross-table exps - vector& exp2 = tableInfoMap[tid].fColsInExp2; + vector& exp2 = tableInfoMap[tid].fColsInExp2; for (unsigned i = 0; i < exp2.size(); i++) { - addColumnInExpToRG(exp2[i], pos, oids, keys, scale, precision, types, jobInfo); + addColumnInExpToRG(tid, exp2[i], pos, oids, keys, scale, precision, types, jobInfo); } // -- any columns will be used in returned exps - vector& expr = tableInfoMap[tid].fColsInRetExp; + vector& expr = tableInfoMap[tid].fColsInRetExp; for (unsigned i = 0; i < expr.size(); i++) { - addColumnInExpToRG(expr[i], pos, oids, keys, scale, precision, types, jobInfo); + addColumnInExpToRG(tid, expr[i], pos, oids, keys, scale, precision, types, jobInfo); } // -- any columns will be used in final outer join expression - vector& expo = tableInfoMap[tid].fColsInOuter; + vector& expo = tableInfoMap[tid].fColsInOuter; for (unsigned i = 0; i < expo.size(); i++) { - addColumnInExpToRG(expo[i], pos, oids, keys, scale, precision, types, jobInfo); + addColumnInExpToRG(tid, expo[i], pos, oids, keys, scale, precision, types, jobInfo); } } -void constructJoinedRowGroup(RowGroup& rg, uint32_t large, uint32_t prev, bool root, - set& tableSet, TableInfoMap& tableInfoMap, JobInfo& jobInfo) +void constructJoinedRowGroup(RowGroup& rg, uint large, uint prev, bool root, + set& tableSet, TableInfoMap& tableInfoMap, JobInfo& jobInfo) { // Construct the output rowgroup for the join. - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); @@ -228,55 +251,55 @@ void constructJoinedRowGroup(RowGroup& rg, uint32_t large, uint32_t prev, bool r // [loop throuh the key list to support compound join] if (root == false) // not root { - vector& joinKeys = jobInfo.tableJoinMap[make_pair(large, prev)].fLeftKeys; - for (vector::iterator i = joinKeys.begin(); i != joinKeys.end(); i++) - addColumnToRG(*i, pos, oids, keys, scale, precision, types, jobInfo); + vector& joinKeys = jobInfo.tableJoinMap[make_pair(large, prev)].fLeftKeys; + for (vector::iterator i = joinKeys.begin(); i != joinKeys.end(); i++) + addColumnToRG(large, *i, pos, oids, keys, scale, precision, types, jobInfo); } // -- followed by the columns in select or expression - for (set::iterator i = tableSet.begin(); i != tableSet.end(); i++) + for (set::iterator i = tableSet.begin(); i != tableSet.end(); i++) addColumnsToRG(*i, pos, oids, keys, scale, precision, types, tableInfoMap, jobInfo); - RowGroup tmpRg(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup tmpRg(oids.size(), pos, oids, keys, types, scale, precision); rg = tmpRg; } -void constructJoinedRowGroup(RowGroup& rg, set& tableSet, TableInfoMap& tableInfoMap, +void constructJoinedRowGroup(RowGroup& rg, set& tableSet, TableInfoMap& tableInfoMap, JobInfo& jobInfo) { // Construct the output rowgroup for the join. - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); - for (set::iterator i = tableSet.begin(); i != tableSet.end(); i++) + for (set::iterator i = tableSet.begin(); i != tableSet.end(); i++) { // columns in select or expression addColumnsToRG(*i, pos, oids, keys, scale, precision, types, tableInfoMap, jobInfo); // keys to be joined if not already in the rowgroup - vector& adjList = tableInfoMap[*i].fAdjacentList; - for (vector::iterator j = adjList.begin(); j != adjList.end(); j++) + vector& adjList = tableInfoMap[*i].fAdjacentList; + for (vector::iterator j = adjList.begin(); j != adjList.end(); j++) { if (find(tableSet.begin(), tableSet.end(), *j) == tableSet.end()) { // not joined - vector& joinKeys = jobInfo.tableJoinMap[make_pair(*i, *j)].fLeftKeys; - for (vector::iterator k = joinKeys.begin(); k != joinKeys.end(); k++) + vector& joinKeys = jobInfo.tableJoinMap[make_pair(*i, *j)].fLeftKeys; + for (vector::iterator k = joinKeys.begin(); k != joinKeys.end(); k++) { if (find(keys.begin(), keys.end(), *k) == keys.end()) - addColumnToRG(*k, pos, oids, keys, scale, precision, types, jobInfo); + addColumnToRG(*i, *k, pos, oids, keys, scale, precision, types, jobInfo); } } } } - RowGroup tmpRg(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup tmpRg(oids.size(), pos, oids, keys, types, scale, precision); rg = tmpRg; } @@ -286,12 +309,12 @@ void updateExp2Cols(JobStepVector& expSteps, TableInfoMap& tableInfoMap, JobInfo for (JobStepVector::iterator it = expSteps.begin(); it != expSteps.end(); it++) { ExpressionStep* exps = dynamic_cast(it->get()); - const vector& tables = exps->tableKeys(); - const vector& columns = exps->columnKeys(); + const vector& tables = exps->tableKeys(); + const vector& columns = exps->columnKeys(); for (uint64_t i = 0; i < tables.size(); ++i) { - vector& exp2 = tableInfoMap[tables[i]].fColsInExp2; - vector::iterator cit = find(exp2.begin(), exp2.end(), columns[i]); + vector& exp2 = tableInfoMap[tables[i]].fColsInExp2; + vector::iterator cit = find(exp2.begin(), exp2.end(), columns[i]); if (cit != exp2.end()) exp2.erase(cit); } @@ -315,11 +338,11 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, // Construct a rowgroup that matches the select columns TupleInfoVector v = jobInfo.pjColList; - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); @@ -332,7 +355,7 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, scale.push_back(v[i].scale); precision.push_back(v[i].precision); } - RowGroup rg1(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup rg1(oids.size(), pos, oids, keys, types, scale, precision); // evaluate the returned/groupby expressions if any JobStepVector& expSteps = jobInfo.returnedExpressions; @@ -347,7 +370,7 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, types.clear(); pos.push_back(2); - const vector& keys0 = rg0->getKeys(); + const vector& keys0 = rg0->getKeys(); for (unsigned i = 0; i < v.size(); i++) { if (find(keys0.begin(), keys0.end(), v[i].key) == keys0.end()) @@ -363,10 +386,10 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, // for v0.9.3.0, the output and input to the expression are in the same row // add the returned column into the rg0 as rg01 - RowGroup rg01 = *rg0 + RowGroup(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup rg01 = *rg0 + RowGroup(oids.size(), pos, oids, keys, types, scale, precision); if (jobInfo.trace) cout << "Output RowGroup 01: " << rg01.toString() << endl; - map keyToIndexMap0; // maps key to the index in the input RG + map keyToIndexMap0; // maps key to the index in the input RG for (uint64_t i = 0; i < rg01.getKeys().size(); ++i) keyToIndexMap0.insert(make_pair(rg01.getKeys()[i], i)); @@ -406,14 +429,12 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, if (jobInfo.hasAggregation == false) { if (thjs != NULL) //setup a few things for the final thjs step... - thjs->outputAssociation(JobStepAssociation()); + thjs->outputAssociation(JobStepAssociation(jobInfo.status)); deliverySteps[CNX_VTABLE_ID] = spjs; } else { - TupleDeliveryStep* tds = dynamic_cast(spjs.get()); - idbassert(tds != NULL); SJSTEP ads = TupleAggregateStep::prepAggregate(spjs, jobInfo); querySteps.push_back(ads); if (ads.get() != NULL) @@ -431,7 +452,7 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, RowGroupDL* dlIn = new RowGroupDL(1, jobInfo.fifoSize); dlIn->OID(CNX_VTABLE_ID); spdlIn->rowGroupDL(dlIn); - JobStepAssociation jsaIn; + JobStepAssociation jsaIn(jobInfo.status); jsaIn.outAdd(spdlIn); dynamic_cast(ds)->outputAssociation(jsaIn); jobInfo.havingStep->inputAssociation(jsaIn); @@ -440,7 +461,7 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, RowGroupDL* dlOut = new RowGroupDL(1, jobInfo.fifoSize); dlOut->OID(CNX_VTABLE_ID); spdlOut->rowGroupDL(dlOut); - JobStepAssociation jsaOut; + JobStepAssociation jsaOut(jobInfo.status); jsaOut.outAdd(spdlOut); jobInfo.havingStep->outputAssociation(jsaOut); @@ -450,24 +471,19 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, deliverySteps[CNX_VTABLE_ID] = jobInfo.havingStep; } - if (jobInfo.windowCols.size() > 0) - { - spjs = querySteps.back(); - SJSTEP ws = WindowFunctionStep::makeWindowFunctionStep(spjs, jobInfo); - idbassert(ws.get()); - querySteps.push_back(ws); - deliverySteps[CNX_VTABLE_ID] = ws; - } - if ((jobInfo.limitCount != (uint64_t) -1) || (jobInfo.constantCol == CONST_COL_EXIST) || - (jobInfo.hasDistinct)) + (jobInfo.hasDistinct && jobInfo.hasImplicitGroupBy)) { if (jobInfo.annexStep.get() == NULL) - jobInfo.annexStep.reset(new TupleAnnexStep(jobInfo)); + jobInfo.annexStep.reset(new TupleAnnexStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId, + jobInfo)); TupleAnnexStep* tas = dynamic_cast(jobInfo.annexStep.get()); - tas->setLimit(jobInfo.limitStart, jobInfo.limitCount); + tas->setLimit(jobInfo.limitCount); if (jobInfo.limitCount != (uint64_t) -1) { @@ -476,10 +492,17 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, } if (jobInfo.constantCol == CONST_COL_EXIST) - tas->addConstant(new TupleConstantStep(jobInfo)); - - if (jobInfo.hasDistinct) + tas->addConstant(new TupleConstantStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId)); + + if (jobInfo.hasDistinct && jobInfo.hasImplicitGroupBy) tas->setDistinct(); + + tas->logger(jobInfo.logger); } if (jobInfo.annexStep) @@ -487,13 +510,12 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, TupleDeliveryStep* ds = dynamic_cast(deliverySteps[CNX_VTABLE_ID].get()); RowGroup rg2 = ds->getDeliveredRowGroup(); - if (jobInfo.trace) cout << "Output RowGroup 2: " << rg2.toString() << endl; AnyDataListSPtr spdlIn(new AnyDataList()); RowGroupDL* dlIn = new RowGroupDL(1, jobInfo.fifoSize); dlIn->OID(CNX_VTABLE_ID); spdlIn->rowGroupDL(dlIn); - JobStepAssociation jsaIn; + JobStepAssociation jsaIn(jobInfo.status); jsaIn.outAdd(spdlIn); dynamic_cast(ds)->outputAssociation(jsaIn); jobInfo.annexStep->inputAssociation(jsaIn); @@ -502,7 +524,7 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, RowGroupDL* dlOut = new RowGroupDL(1, jobInfo.fifoSize); dlOut->OID(CNX_VTABLE_ID); spdlOut->rowGroupDL(dlOut); - JobStepAssociation jsaOut; + JobStepAssociation jsaOut(jobInfo.status); jsaOut.outAdd(spdlOut); jobInfo.annexStep->outputAssociation(jsaOut); @@ -514,8 +536,14 @@ void adjustLastStep(JobStepVector& querySteps, DeliveredTableMap& deliverySteps, // Check if constant false if (jobInfo.constantFalse) { - TupleConstantBooleanStep* tcs = new TupleConstantBooleanStep(jobInfo, false); - tcs->outputAssociation(querySteps.back().get()->outputAssociation()); + TupleConstantBooleanStep* tcs = new + TupleConstantBooleanStep(JobStepAssociation(), + querySteps.back().get()->outputAssociation(), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId, + false); TupleDeliveryStep* tds = dynamic_cast(deliverySteps[CNX_VTABLE_ID].get()); tcs->initialize(tds->getDeliveredRowGroup(), jobInfo); @@ -557,41 +585,32 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI throw runtime_error("BPS is null"); // construct a pcolstep for each joinkey to be projected - vector& joinKeys = mit->second.fJoinKeys; + vector& joinKeys = mit->second.fJoinKeys; JobStepVector keySteps; - vector fjKeys; - for (vector::iterator kit = joinKeys.begin(); kit != joinKeys.end(); kit++) - { - if (jobInfo.keyInfo.get()->tupleKeyToTableOid[*kit] != CNX_EXP_TABLE_ID) - tupleKeyToProjectStep(*kit, keySteps, jobInfo); - else - fjKeys.push_back(*kit); - } + for (vector::iterator kit = joinKeys.begin(); kit != joinKeys.end(); kit++) + tupleKeyToProjectStep(*kit, keySteps, jobInfo); // construct pcolstep for columns in expresssions JobStepVector expSteps; - vector& exp1 = mit->second.fColsInExp1; - for (vector::iterator kit = exp1.begin(); kit != exp1.end(); kit++) + vector& exp1 = mit->second.fColsInExp1; + for (vector::iterator kit = exp1.begin(); kit != exp1.end(); kit++) tupleKeyToProjectStep(*kit, expSteps, jobInfo); - vector& exp2 = mit->second.fColsInExp2; - for (vector::iterator kit = exp2.begin(); kit != exp2.end(); kit++) + vector& exp2 = mit->second.fColsInExp2; + for (vector::iterator kit = exp2.begin(); kit != exp2.end(); kit++) tupleKeyToProjectStep(*kit, expSteps, jobInfo); - vector& expRet = mit->second.fColsInRetExp; - for (vector::iterator kit = expRet.begin(); kit != expRet.end(); kit++) + vector& expRet = mit->second.fColsInRetExp; + for (vector::iterator kit = expRet.begin(); kit != expRet.end(); kit++) tupleKeyToProjectStep(*kit, expSteps, jobInfo); - vector& expOut = mit->second.fColsInOuter; - for (vector::iterator kit = expOut.begin(); kit != expOut.end(); kit++) - tupleKeyToProjectStep(*kit, expSteps, jobInfo); - vector& expFj = mit->second.fColsInFuncJoin; - for (vector::iterator kit = expFj.begin(); kit != expFj.end(); kit++) + vector& expOut = mit->second.fColsInOuter; + for (vector::iterator kit = expOut.begin(); kit != expOut.end(); kit++) tupleKeyToProjectStep(*kit, expSteps, jobInfo); // for output rowgroup - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); @@ -599,19 +618,19 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI JobStepVector psv = mit->second.fProjectSteps; // columns being selected psv.insert(psv.begin(), keySteps.begin(), keySteps.end()); // add joinkeys to project psv.insert(psv.end(), expSteps.begin(), expSteps.end()); // add expressions to project - set seenCols; // columns already processed + set seenCols; // columns already processed // for passthru conversion - // passthru is disabled (default lastTupleId to -1) unless the TupleBPS::bop is BOP_AND. - uint64_t lastTupleId = -1; + // passthru is disabled (default lastOid to -1) unless the TupleBPS::bop is BOP_AND. + CalpontSystemCatalog::OID lastOid = -1; TupleBPS* tbps = dynamic_cast(bps); if (tbps != NULL && tbps->getBOP() == BOP_AND && exp1.size() == 0) - lastTupleId = tbps->getLastTupleId(); + lastOid = tbps->getLastOid(); for (JobStepVector::iterator it = psv.begin(); it != psv.end(); it++) { JobStep* js = it->get(); - uint32_t tupleKey = js->tupleId(); + uint tupleKey = js->tupleId(); if (seenCols.find(tupleKey) != seenCols.end()) continue; @@ -620,11 +639,9 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI // if the projected column is the last accessed predicate pColStep* pcol = dynamic_cast(js); - if (pcol != NULL && js->tupleId() == lastTupleId) + if (pcol != NULL && js->oid() == lastOid) { - PassThruStep* pts = new PassThruStep(*pcol); - if (dynamic_cast(pcol)) - pts->pseudoType(dynamic_cast(pcol)->pseudoColumnId()); + PassThruStep* pts = new PassThruStep(*pcol, jobInfo.isExeMgr); pts->alias(pcol->alias()); pts->view(pcol->view()); pts->name(pcol->name()); @@ -634,7 +651,7 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI // add projected column to TBPS bool tokenOnly = false; - map::iterator toIt = jobInfo.tokenOnly.find(js->tupleId()); + map::iterator toIt = jobInfo.tokenOnly.find(js->tupleId()); if (toIt != jobInfo.tokenOnly.end()) tokenOnly = toIt->second; if (it->get()->isDictCol() && !tokenOnly) @@ -645,9 +662,9 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI bps->setProjectBPP(it->get(),(it+1)->get()); // this is a two-step project step, remove the token step from id vector - vector& pjv = mit->second.fProjectCols; - uint32_t tokenKey = js->tupleId(); - for (vector::iterator i = pjv.begin(); i != pjv.end(); ++i) + vector& pjv = mit->second.fProjectCols; + uint tokenKey = js->tupleId(); + for (vector::iterator i = pjv.begin(); i != pjv.end(); ++i) { if (*i == tokenKey) { @@ -670,19 +687,7 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI } // add the tuple info of the column into the RowGroup - TupleInfo ti(getTupleInfo(tupleKey, jobInfo)); - pos.push_back(pos.back() + ti.width); - oids.push_back(ti.oid); - keys.push_back(ti.key); - types.push_back(ti.dtype); - scale.push_back(ti.scale); - precision.push_back(ti.precision); - } - - // add function join columns - for (vector::iterator i = fjKeys.begin(); i != fjKeys.end(); i++) - { - TupleInfo ti(getTupleInfo(*i, jobInfo)); + TupleInfo ti(getTupleInfo(mit->first, tupleKey, jobInfo)); pos.push_back(pos.back() + ti.width); oids.push_back(ti.oid); keys.push_back(ti.key); @@ -692,14 +697,14 @@ void addProjectStepsToBps(TableInfoMap::iterator& mit, BatchPrimitive* bps, JobI } // construct RowGroup - RowGroup rg(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup rg(oids.size(), pos, oids, keys, types, scale, precision); // fix the output association AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); spdl->rowGroupDL(dl); dl->OID(mit->first); - JobStepAssociation jsa; + JobStepAssociation jsa(jobInfo.status); jsa.outAdd(spdl); bps->outputAssociation(jsa); bps->setOutputRowGroup(rg); @@ -712,28 +717,35 @@ void addExpresssionStepsToBps(TableInfoMap::iterator& mit, SJSTEP& sjsp, JobInfo BatchPrimitive* bps = dynamic_cast(sjsp.get()); CalpontSystemCatalog::OID tableOid = mit->second.fTableOid; JobStepVector& exps = mit->second.fOneTableExpSteps; - JobStepVector& fjs = mit->second.fFuncJoinExps; - ExpressionStep* exp0 = NULL; - if (exps.size() > 0) - exp0 = dynamic_cast(exps[0].get()); - else - exp0 = dynamic_cast(fjs[0].get()); + ExpressionStep* exp0 = dynamic_cast(exps[0].get()); if (bps == NULL) { if (tableOid > 0) { - uint32_t key0 = exp0->columnKey(); + uint key0 = exp0->columnKey(); CalpontSystemCatalog::ColType ct = jobInfo.keyInfo->colType[key0]; - map::iterator dkMit; + map::iterator dkMit; if (jobInfo.keyInfo->token2DictTypeMap.find(key0) != jobInfo.keyInfo->token2DictTypeMap.end()) ct = jobInfo.keyInfo->token2DictTypeMap[key0]; scoped_ptr pcss( - new pColScanStep(exp0->oid(), tableOid, ct, jobInfo)); - - sjsp.reset(new TupleBPS(*pcss, jobInfo)); + new pColScanStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + 0, + jobInfo.csc, + exp0->oid(), + tableOid, + ct, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm)); + + sjsp.reset(new TupleBPS(*pcss)); TupleBPS* tbps = dynamic_cast(sjsp.get()); tbps->setJobInfo(&jobInfo); tbps->setFirstStepType(SCAN); @@ -745,38 +757,35 @@ void addExpresssionStepsToBps(TableInfoMap::iterator& mit, SJSTEP& sjsp, JobInfo } else { - sjsp.reset(new CrossEngineStep(mit->second.fSchema, + sjsp.reset(new CrossEngineStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + jobInfo.statementId, + mit->second.fSchema, mit->second.fName, mit->second.fAlias, jobInfo)); bps = dynamic_cast(sjsp.get()); } + + bps->logger(jobInfo.logger); } - // rowgroup for evaluating the one table expression - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + // rowgroup for evaluating the expression + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); - vector cols; - JobStepVector& fjExp = mit->second.fFuncJoinExps; - for (JobStepVector::iterator it = fjExp.begin(); it != fjExp.end(); it++) - { - ExpressionStep* e = dynamic_cast(it->get()); - cols.push_back(getExpTupleKey(jobInfo, e->expressionId())); - } - cols.insert(cols.end(), mit->second.fColsInExp1.begin(), mit->second.fColsInExp1.end()); - cols.insert(cols.end(), mit->second.fColsInFuncJoin.begin(), mit->second.fColsInFuncJoin.end()); - uint32_t index = 0; // index in the rowgroup - map keyToIndexMap; // maps key to the index in the RG - for (vector::iterator kit = cols.begin(); kit != cols.end(); kit++) + vector& cols = mit->second.fColsInExp1; + uint index = 0; // index in the rowgroup + map keyToIndexMap; // maps key to the index in the RG + for (vector::iterator kit = cols.begin(); kit != cols.end(); kit++) { - uint32_t key = *kit; + uint key = *kit; if (jobInfo.keyInfo->dictKeyMap.find(key) != jobInfo.keyInfo->dictKeyMap.end()) key = jobInfo.keyInfo->dictKeyMap[key]; @@ -788,7 +797,7 @@ void addExpresssionStepsToBps(TableInfoMap::iterator& mit, SJSTEP& sjsp, JobInfo keyToIndexMap.insert(make_pair(key, index++)); // add the tuple info of the column into the RowGroup - TupleInfo ti(getTupleInfo(key, jobInfo)); + TupleInfo ti(getTupleInfo(mit->first, key, jobInfo)); pos.push_back(pos.back() + ti.width); oids.push_back(ti.oid); keys.push_back(ti.key); @@ -798,41 +807,20 @@ void addExpresssionStepsToBps(TableInfoMap::iterator& mit, SJSTEP& sjsp, JobInfo } // construct RowGroup and add to TBPS - RowGroup rg(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup rg(oids.size(), pos, oids, keys, types, scale, precision); bps->setFE1Input(rg); if (jobInfo.trace) cout << "FE1 input RowGroup: " << rg.toString() << endl << endl; - + // add the expression steps into TBPS, the input-indices are set in SCs. for (JobStepVector::iterator it = exps.begin(); it != exps.end(); it++) { ExpressionStep* e = dynamic_cast(it->get()); - if (e->functionJoin()) - continue; - e->updateInputIndex(keyToIndexMap, jobInfo); - boost::shared_ptr sppt(new ParseTree); + shared_ptr sppt(new ParseTree); sppt->copyTree(*(e->expressionFilter())); bps->addFcnExpGroup1(sppt); } - - // add the function join expression steps into TBPS, too - if (fjs.size() > 0) - { - vector fjCols; - for (JobStepVector::iterator it = fjs.begin(); it != fjs.end(); it++) - { - ExpressionStep* e = dynamic_cast(it->get()); - if (e->virtualStep()) - continue; - - e->updateInputIndex(keyToIndexMap, jobInfo); - e->updateOutputIndex(keyToIndexMap, jobInfo); - fjCols.push_back(e->expression()); - } - - bps->addFcnJoinExp(fjCols); - } } @@ -850,7 +838,7 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) if (qsv.size() == 0) { // find a column in FE1, FE2, or FE3 - uint32_t key = -1; + uint key = -1; if (tableInfo.fColsInExp1.size() > 0) key = tableInfo.fColsInExp1[0]; else if (tableInfo.fColsInExp2.size() > 0) @@ -866,13 +854,32 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) // construct a pcolscanstep to initialize the tbps CalpontSystemCatalog::OID oid = jobInfo.keyInfo->tupleKeyVec[key].fId; + JobStepAssociation dummyJsa(jobInfo.status); + AnyDataListSPtr adl(new AnyDataList()); + RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); + dl->OID(oid); + adl->rowGroupDL(dl); + dummyJsa.outAdd(adl); CalpontSystemCatalog::ColType ct = jobInfo.keyInfo->colType[key]; - map::iterator dkMit; + map::iterator dkMit; if (jobInfo.keyInfo->token2DictTypeMap.find(key) != jobInfo.keyInfo->token2DictTypeMap.end()) ct = jobInfo.keyInfo->token2DictTypeMap[key]; - SJSTEP sjs(new pColScanStep(oid, tableOid, ct, jobInfo)); + SJSTEP sjs(new pColScanStep(dummyJsa, + dummyJsa, + 0, + jobInfo.csc, + oid, + tableOid, + ct, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm)); + sjs->logger(jobInfo.logger); sjs->alias(jobInfo.keyInfo->tupleKeyVec[key].fTable); sjs->view(jobInfo.keyInfo->tupleKeyVec[key].fView); sjs->schema(jobInfo.keyInfo->tupleKeyVec[key].fSchema); @@ -915,7 +922,7 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) { if (tableOid > 0) { - sjsp.reset(new TupleBPS(*(dynamic_cast(it->get())),jobInfo)); + sjsp.reset(new TupleBPS(*(dynamic_cast(it->get())))); TupleBPS* tbps = dynamic_cast(sjsp.get()); tbps->setJobInfo(&jobInfo); tbps->setFirstStepType(SCAN); @@ -923,12 +930,17 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) } else { - sjsp.reset(new CrossEngineStep(mit->second.fSchema, + sjsp.reset(new CrossEngineStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + jobInfo.statementId, + mit->second.fSchema, mit->second.fName, mit->second.fAlias, jobInfo)); bps = dynamic_cast(sjsp.get()); } + + bps->logger(jobInfo.logger); } else { @@ -940,35 +952,35 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) unsigned itInc = 1; // iterator increase number unsigned numOfStepsAddToBps = 0; // # steps to be added into TBPS if ((distance(it, end) > 2 && - dynamic_cast(it->get()) != NULL && - (dynamic_cast((it + 1)->get()) != NULL || - dynamic_cast((it + 1)->get()) != NULL) && - dynamic_cast((it + 2)->get()) != NULL) || + typeid(*(it->get())) == typeid(pDictionaryScan) && + (typeid(*((it + 1)->get())) == typeid(pColScanStep) || + typeid(*((it + 1)->get())) == typeid(pColStep)) && + typeid(*((it + 2)->get())) == typeid(TupleHashJoinStep)) || (distance(it, end) > 1 && - dynamic_cast(it->get()) != NULL && - dynamic_cast((it + 1)->get()) != NULL)) + typeid(*(it->get())) == typeid(pDictionaryScan) && + typeid(*((it + 1)->get())) == typeid(TupleHashJoinStep))) { // string access predicate // setup pDictionaryScan pDictionaryScan* pds = dynamic_cast(it->get()); - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); pos.push_back(2 + 8); CalpontSystemCatalog::OID coid = jobInfo.keyInfo->dictOidToColOid[pds->oid()]; oids.push_back(coid); - uint32_t keyId = pds->tupleId(); + uint keyId = pds->tupleId(); keys.push_back(keyId); types.push_back(CalpontSystemCatalog::BIGINT); scale.push_back(0); precision.push_back(0); - RowGroup rg(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + RowGroup rg(oids.size(), pos, oids, keys, types, scale, precision); if (jobInfo.trace) cout << "RowGroup pds(and): " << rg.toString() << endl; pds->setOutputRowGroup(rg); newSteps.push_back(*it); @@ -984,55 +996,55 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) numOfStepsAddToBps = 0; } else if (distance(begin, it) > 1 && - (dynamic_cast((it-1)->get()) != NULL || - dynamic_cast((it-2)->get()) != NULL) && - dynamic_cast(it->get()) != NULL) + (typeid(*((it-1)->get())) == typeid(pDictionaryScan) || + typeid(*((it-2)->get())) == typeid(pDictionaryScan)) && + typeid(*(it->get())) == typeid(TupleHashJoinStep)) { // save the token join to the last, by pdsInfo itInc = 1; numOfStepsAddToBps = 0; } else if (distance(it, end) > 2 && - dynamic_cast((it + 1)->get()) != NULL && - dynamic_cast((it + 2)->get()) != NULL) + typeid(*((it + 1)->get())) == typeid(pColStep) && + typeid(*((it + 2)->get())) == typeid(FilterStep)) { itInc = 3; numOfStepsAddToBps = 3; } else if (distance(it, end) > 3 && - dynamic_cast((it + 1)->get()) != NULL && - dynamic_cast((it + 2)->get()) != NULL && - dynamic_cast((it + 3)->get()) != NULL) + typeid(*((it + 1)->get())) == typeid(pColStep) && + typeid(*((it + 2)->get())) == typeid(pDictionaryStep) && + typeid(*((it + 3)->get())) == typeid(FilterStep)) { itInc = 4; numOfStepsAddToBps = 4; } else if (distance(it, end) > 3 && - dynamic_cast((it + 1)->get()) != NULL && - dynamic_cast((it + 2)->get()) != NULL && - dynamic_cast((it + 3)->get()) != NULL) + typeid(*((it + 1)->get())) == typeid(pDictionaryStep) && + typeid(*((it + 2)->get())) == typeid(pColStep) && + typeid(*((it + 3)->get())) == typeid(FilterStep)) { itInc = 4; numOfStepsAddToBps = 4; } else if (distance(it, end) > 4 && - dynamic_cast((it + 1)->get()) != NULL && - dynamic_cast((it + 2)->get()) != NULL && - dynamic_cast((it + 3)->get()) != NULL && - dynamic_cast((it + 4)->get()) != NULL) + typeid(*((it + 1)->get())) == typeid(pDictionaryStep) && + typeid(*((it + 2)->get())) == typeid(pColStep) && + typeid(*((it + 3)->get())) == typeid(pDictionaryStep) && + typeid(*((it + 4)->get())) == typeid(FilterStep)) { itInc = 5; numOfStepsAddToBps = 5; } else if (distance(it, end) > 1 && - (dynamic_cast(it->get()) != NULL || - dynamic_cast(it->get()) != NULL) && - dynamic_cast((it + 1)->get()) != NULL) + (typeid(*(it->get())) == typeid(pColStep) || + typeid(*(it->get())) == typeid(pColScanStep)) && + typeid(*((it + 1)->get())) == typeid(pDictionaryStep)) { itInc = 2; numOfStepsAddToBps = 2; } - else if (dynamic_cast(it->get()) != NULL) + else if (typeid(*(it->get())) == typeid(pColStep)) { pColStep* pcol = dynamic_cast(it->get()); if (pcol->getFilters().size() == 0) @@ -1047,14 +1059,14 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) itInc = 1; } - else if (dynamic_cast(it->get()) != NULL) + else if (typeid(*(it->get())) == typeid(pColScanStep)) { numOfStepsAddToBps = 1; itInc = 1; } else { - // Not a combinable step, or step pattern not recognized. + // Not a combinable step, or step pattern not recognized. cerr << boldStart << "Try to combine " << typeid(*(it->get())).name() << ": " << it->get()->oid() << " into TBPS" << boldStop << endl; return false; @@ -1068,14 +1080,14 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) { bps->setBPP((it+i)->get()); bps->setStepCount(); - bps->setLastTupleId((it+i)->get()->tupleId()); + bps->setLastOid((it+i)->get()->oid()); } it += itInc; } // add one-table expression steps to TBPS - if (tableInfo.fOneTableExpSteps.size() > 0 || tableInfo.fFuncJoinExps.size() > 0) + if (tableInfo.fOneTableExpSteps.size() > 0) addExpresssionStepsToBps(mit, sjsp, jobInfo); // add TBPS to the step vector @@ -1095,7 +1107,12 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) // ---- token joins ---- // construct a TupleHashJoinStep TupleBPS* tbps = dynamic_cast(bps); - TupleHashJoinStep* thjs= new TupleHashJoinStep(jobInfo); + TupleHashJoinStep* thjs= new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm); + thjs->logger(jobInfo.logger); thjs->tableOid1(0); thjs->tableOid2(tableInfo.fTableOid); thjs->alias1(tableInfo.fAlias); @@ -1107,7 +1124,6 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) thjs->setLargeSideBPS(tbps); thjs->joinId(-1); // token join is a filter force it done before other joins thjs->setJoinType(INNER); - thjs->tokenJoin(mit->first); tbps->incWaitToRunStepCnt(); SJSTEP spthjs(thjs); @@ -1118,32 +1134,44 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) // input jobstepassociation // 1. small sides -- pdictionaryscan steps vector rgPdsVec; - map addedCol; + map addedCol; vector jointypes; vector typeless; - vector > smallKeyIndices; - vector > largeKeyIndices; + vector > smallKeyIndices; + vector > largeKeyIndices; vector tableNames; - JobStepAssociation inJsa; + JobStepAssociation inJsa(jobInfo.status); for (vector::iterator i = pdsVec.begin(); i != pdsVec.end(); i++) { // add the token steps to the TBPS - uint32_t tupleKey = i->fTokenId; - map::iterator k = addedCol.find(tupleKey); + uint tupleKey = i->fTokenId; + map::iterator k = addedCol.find(tupleKey); unsigned largeSideIndex = rgTbps.getColumnCount(); if (k == addedCol.end()) { - SJSTEP sjs(new pColStep(jobInfo.keyInfo->tupleKeyVec[tupleKey].fId, + SJSTEP sjs(new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + 0, + jobInfo.csc, + jobInfo.keyInfo->tupleKeyVec[tupleKey].fId, tableInfo.fTableOid, jobInfo.keyInfo->token2DictTypeMap[tupleKey], - jobInfo)); + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm, + jobInfo.flushInterval, + jobInfo.isExeMgr)); + sjs->logger(jobInfo.logger); sjs->alias(tableInfo.fAlias); sjs->view(tableInfo.fView); sjs->schema(tableInfo.fSchema); sjs->name(jobInfo.keyInfo->keyName[tupleKey]); sjs->tupleId(tupleKey); bps->setProjectBPP(sjs.get(), NULL); - + // Update info, which will be used to config the hashjoin later. rgTbps += i->fRowGroup; addedCol[tupleKey] = largeSideIndex; @@ -1158,8 +1186,8 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) rgPdsVec.push_back(i->fRowGroup); jointypes.push_back(INNER); typeless.push_back(false); - smallKeyIndices.push_back(vector(1, 0)); - largeKeyIndices.push_back(vector(1, largeSideIndex)); + smallKeyIndices.push_back(vector(1, 0)); + largeKeyIndices.push_back(vector(1, largeSideIndex)); } // 2. large side @@ -1176,7 +1204,7 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); spdl->rowGroupDL(dl); dl->OID(mit->first); - JobStepAssociation jsaOut; + JobStepAssociation jsaOut(jobInfo.status); jsaOut.outAdd(spdl); thjs->outputAssociation(jsaOut); @@ -1213,80 +1241,6 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) if (tableInfo.fOneTableExpSteps.size() > 0) adaStep->addExpression(tableInfo.fOneTableExpSteps, jobInfo); - // add function join steps - if (tableInfo.fFuncJoinExps.size() > 0) - { - // fe rowgroup info - RowGroup feRg = adaStep->getFeRowGroup(); - if (feRg.getColumnCount() == 0) - feRg = adaStep->getOutputRowGroup(); - const vector& feKeys = feRg.getKeys(); - map keyToIndexMapFe; - for (uint64_t i = 0; i < feKeys.size(); ++i) - keyToIndexMapFe.insert(make_pair(feKeys[i], i)); - - // output rowgroup info - const RowGroup& outRg = adaStep->getOutputRowGroup(); - const vector& outKeys = outRg.getKeys(); - map keyToIndexMapOut; - for (uint64_t i = 0; i < outKeys.size(); ++i) - keyToIndexMapOut.insert(make_pair(outKeys[i], i)); - - // make sure the function join columns are present in the rgs - vector fjKeys; - vector fjCols; - TupleInfoVector tis; - uint64_t lastFeIdx = feKeys.size(); - JobStepVector& fjs = tableInfo.fFuncJoinExps; - for (JobStepVector::iterator it = fjs.begin(); it != fjs.end(); it++) - { - ExpressionStep* e = dynamic_cast(it->get()); - TupleInfo ti = setExpTupleInfo(e->expression().get(), jobInfo); - if (find(feKeys.begin(), feKeys.end(), ti.key) == feKeys.end()) - { - tis.push_back(ti); - keyToIndexMapFe.insert(make_pair(ti.key, lastFeIdx++)); - } - e->updateInputIndex(keyToIndexMapFe, jobInfo); - e->updateOutputIndex(keyToIndexMapFe, jobInfo); - fjCols.push_back(e->expression()); - } - - // additional fields in the rowgroup - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; - vector types; - pos.push_back(2); - - for (unsigned i = 0; i < tis.size(); i++) - { - pos.push_back(pos.back() + tis[i].width); - oids.push_back(tis[i].oid); - keys.push_back(tis[i].key); - types.push_back(tis[i].dtype); - scale.push_back(tis[i].scale); - precision.push_back(tis[i].precision); - } - - RowGroup addRg(oids.size(), pos, oids, keys, types, scale, precision, - jobInfo.stringTableThreshold); - - RowGroup feRg1 = feRg; - RowGroup outRg1 = outRg; - if (addRg.getColumnCount() > 0) - { - feRg1 += addRg; - outRg1 += addRg; - } - - adaStep->addFcnJoinExp(fjCols); - adaStep->setFeRowGroup(feRg1); - adaStep->setOutputRowGroup(outRg1); - } - rgOut = adaStep->getOutputRowGroup(); } } @@ -1303,200 +1257,7 @@ bool combineJobStepsByTable(TableInfoMap::iterator& mit, JobInfo& jobInfo) } -bool addFunctionJoin(vector& joinedTables, JobStepVector& joinSteps, - set& nodeSet, set >& pathSet, - TableInfoMap& tableInfoMap, JobInfo& jobInfo) -{ - // @bug3683, adding function joins for not joined tables, one pair at a time. - // design review comment: - // all convertable expressions between a pair of tables should be done all, or none. - vector::iterator i = jobInfo.functionJoins.begin(); // candidates - set > functionJoinPairs; // pairs - bool added = false; // new node added - - // for function join tables' scope checking, not to try semi join inside subquery. - set tables; // tables to join - tables.insert(jobInfo.tableList.begin(), jobInfo.tableList.end()); - - // table pairs to be joined by function joins - TableJoinMap::iterator m1 = jobInfo.tableJoinMap.end(); - TableJoinMap::iterator m2 = jobInfo.tableJoinMap.end(); - for (; (i != jobInfo.functionJoins.end()); i++) - { - ExpressionStep* es = dynamic_cast((*i)); - idbassert(es); - if (es->functionJoin()) - continue; // already converted to a join - - boost::shared_ptr fji = es->functionJoinInfo(); - uint32_t key1 = fji->fJoinKey[0]; - uint32_t key2 = fji->fJoinKey[1]; - uint32_t tid1 = fji->fTableKey[0]; - uint32_t tid2 = fji->fTableKey[1]; - - if (nodeSet.find(tid1) != nodeSet.end() && nodeSet.find(tid2) != nodeSet.end()) - continue; // both connected, will be a cycle if added. - - if (nodeSet.find(tid1) == nodeSet.end() && nodeSet.find(tid2) == nodeSet.end()) - continue; // both isolated, wait until one is connected. - - if (tables.find(tid1) == tables.end() || tables.find(tid2) == tables.end()) - continue; // sub-query case - - // one & only one is already connected - pair p(tid1, tid2); - if (functionJoinPairs.empty()) - { - functionJoinPairs.insert(make_pair(tid1, tid2)); - functionJoinPairs.insert(make_pair(tid2, tid1)); - tableInfoMap[tid1].fAdjacentList.push_back(tid2); - tableInfoMap[tid2].fAdjacentList.push_back(tid1); - - if (find(joinedTables.begin(), joinedTables.end(), tid1) == joinedTables.end()) - { - joinedTables.push_back(tid1); - nodeSet.insert(tid1); - pathSet.insert(make_pair(tid2, tid1)); - } - else - { - joinedTables.push_back(tid2); - nodeSet.insert(tid2); - pathSet.insert(make_pair(tid1, tid2)); - } - - added = true; - - m1 = jobInfo.tableJoinMap.insert(m1, make_pair(make_pair(tid1,tid2), JoinData())); - m2 = jobInfo.tableJoinMap.insert(m1, make_pair(make_pair(tid2,tid1), JoinData())); - - if (m1 == jobInfo.tableJoinMap.end() || m2 == jobInfo.tableJoinMap.end()) - throw runtime_error("Bad table map."); - - TupleInfo ti1 = getTupleInfo(key1, jobInfo); - TupleInfo ti2 = getTupleInfo(key2, jobInfo); - if (ti1.dtype==CalpontSystemCatalog::CHAR || ti1.dtype==CalpontSystemCatalog::VARCHAR) - m1->second.fTypeless = m2->second.fTypeless = true; // ti2 is compatible - else - m1->second.fTypeless = m2->second.fTypeless = false; - } - else if (functionJoinPairs.find(p) == functionJoinPairs.end()) - { - continue; // different path - } - else - { - // path already added, do compound join - m1->second.fTypeless = m2->second.fTypeless = true; - } - - // simple or compound function join - es->functionJoin(true); - updateTableKey(key1, tid1, jobInfo); - updateTableKey(key2, tid2, jobInfo); - - tableInfoMap[tid1].fJoinKeys.push_back(key1); - tableInfoMap[tid2].fJoinKeys.push_back(key2); - if (fji->fStep[0]) - tableInfoMap[tid1].fFuncJoinExps.push_back(fji->fStep[0]); - if (fji->fStep[1]) - tableInfoMap[tid2].fFuncJoinExps.push_back(fji->fStep[1]); - vector& cols1 = tableInfoMap[tid1].fColsInFuncJoin; - cols1.insert(cols1.end(), fji->fColumnKeys[0].begin(), fji->fColumnKeys[0].end()); - vector& cols2 = tableInfoMap[tid2].fColsInFuncJoin; - cols2.insert(cols2.end(), fji->fColumnKeys[1].begin(), fji->fColumnKeys[1].end()); - - // construct a join step - TupleHashJoinStep* thjs= new TupleHashJoinStep(jobInfo); - thjs->tableOid1(fji->fTableOid[0]); - thjs->tableOid2(fji->fTableOid[1]); - thjs->oid1(fji->fOid[0]); - thjs->oid2(fji->fOid[1]); - thjs->alias1(fji->fAlias[0]); - thjs->alias2(fji->fAlias[1]); - thjs->view1(fji->fView[0]); - thjs->view2(fji->fView[1]); - thjs->schema1(fji->fSchema[0]); - thjs->schema2(fji->fSchema[1]); - thjs->column1(fji->fExpression[0]); - thjs->column2(fji->fExpression[1]); - thjs->sequence1(fji->fSequence[0]); - thjs->sequence2(fji->fSequence[1]); - thjs->joinId(fji->fJoinId); - thjs->setJoinType(fji->fJoinType); - thjs->funcJoinInfo(fji); - thjs->tupleId1(key1); - thjs->tupleId2(key2); - SJSTEP spjs(thjs); - - // check correlated info - JoinType joinType = fji->fJoinType; - if (!(joinType & CORRELATED)) - { - joinSteps.push_back(spjs); - - // Keep a map of the join (table, key) pairs - m1->second.fLeftKeys.push_back(key1); - m1->second.fRightKeys.push_back(key2); - - m2->second.fLeftKeys.push_back(key2); - m2->second.fRightKeys.push_back(key1); - - // Keep a map of the join type between the keys. - // OUTER join and SEMI/ANTI join are mutually exclusive. - if (joinType == LEFTOUTER) - { - m1->second.fTypes.push_back(SMALLOUTER); - m2->second.fTypes.push_back(LARGEOUTER); - jobInfo.outerOnTable.insert(tid2); - } - else if (joinType == RIGHTOUTER) - { - m1->second.fTypes.push_back(LARGEOUTER); - m2->second.fTypes.push_back(SMALLOUTER); - jobInfo.outerOnTable.insert(tid1); - } - else if ((joinType & SEMI) && - ((joinType & LEFTOUTER) == LEFTOUTER || (joinType & RIGHTOUTER) == RIGHTOUTER)) - { - // @bug3998, DML UPDATE borrows "SEMI" flag, - // allowing SEMI and LARGEOUTER combination to support update with outer join. - if ((joinType & LEFTOUTER) == LEFTOUTER) - { - joinType ^= LEFTOUTER; - m1->second.fTypes.push_back(joinType); - m2->second.fTypes.push_back(joinType | LARGEOUTER); - jobInfo.outerOnTable.insert(tid2); - } - else - { - joinType ^= RIGHTOUTER; - m1->second.fTypes.push_back(joinType | LARGEOUTER); - m2->second.fTypes.push_back(joinType); - jobInfo.outerOnTable.insert(tid1); - } - } - else - { - m1->second.fTypes.push_back(joinType); - m2->second.fTypes.push_back(joinType); - } - - // need id to keep the join order - m1->second.fJoinId = m2->second.fJoinId = thjs->joinId(); - } - else - { - // one of the tables is in outer query - jobInfo.correlateSteps.push_back(spjs); - } - } - - return added; -} - - -void spanningTreeCheck(TableInfoMap& tableInfoMap, JobStepVector joinSteps, JobInfo& jobInfo) +void spanningTreeCheck(TableInfoMap& tableInfoMap, JobInfo& jobInfo) { bool spanningTree = true; unsigned errcode = 0; @@ -1508,7 +1269,7 @@ void spanningTreeCheck(TableInfoMap& tableInfoMap, JobStepVector joinSteps, JobI for (TableInfoMap::iterator i = tableInfoMap.begin(); i != tableInfoMap.end(); i++) { cout << i->first << " :"; - vector::iterator j = i->second.fAdjacentList.begin(); + vector::iterator j = i->second.fAdjacentList.begin(); while (j != i->second.fAdjacentList.end()) cout << " " << *j++; cout << endl; @@ -1524,71 +1285,33 @@ void spanningTreeCheck(TableInfoMap& tableInfoMap, JobStepVector joinSteps, JobI } else if (tableInfoMap.size() > 1) { - // 1a. make sure all tables are joined if not a single table query. - set nodeSet; - set > pathSet; - vector joinedTables; + // make sure all tables are joined if not a single table query + set > joinPaths; + vector joinedTables; joinedTables.push_back((tableInfoMap.begin())->first); for (size_t i = 0; i < joinedTables.size(); i++) { - vector& v = tableInfoMap[joinedTables[i]].fAdjacentList; - nodeSet.insert(joinedTables[i]); - for (vector::iterator j = v.begin(); j != v.end(); j++) + vector& v = tableInfoMap[joinedTables[i]].fAdjacentList; + for (vector::iterator j = v.begin(); j != v.end(); j++) { - if (nodeSet.find(*j) == nodeSet.end()) + if (find(joinedTables.begin(), joinedTables.end(), *j) == joinedTables.end()) joinedTables.push_back(*j); - nodeSet.insert(*j); - pathSet.insert(make_pair(joinedTables[i], *j)); + joinPaths.insert(make_pair(joinedTables[i], *j)); } } - // 1b. convert expressions to function joins if not connected with simple column joins. - bool fjAdded = false; - while (joinedTables.size() < tableInfoMap.size() && - addFunctionJoin(joinedTables, joinSteps, nodeSet, pathSet, tableInfoMap, jobInfo)) - { - fjAdded = true; - for (size_t i = joinedTables.size()-1; i < joinedTables.size(); i++) - { - vector& v = tableInfoMap[joinedTables[i]].fAdjacentList; - for (vector::iterator j = v.begin(); j != v.end(); j++) - { - if (find(joinedTables.begin(), joinedTables.end(), *j) == joinedTables.end()) - joinedTables.push_back(*j); - - nodeSet.insert(*j); - pathSet.insert(make_pair(joinedTables[i], *j)); - } - } - } - - - if (jobInfo.trace && fjAdded) - { - cout << "Table Connection after adding function join:" << endl; - for (TableInfoMap::iterator i = tableInfoMap.begin(); i != tableInfoMap.end(); i++) - { - cout << i->first << " :"; - vector::iterator j = i->second.fAdjacentList.begin(); - while (j != i->second.fAdjacentList.end()) - cout << " " << *j++; - cout << endl; - } - cout << endl; - } - - // 1c. check again if all tables are joined after pulling in function joins. + // 1. connected if (joinedTables.size() < tableInfoMap.size()) { - vector notJoinedTables; + vector notJoinedTables; for (TableInfoMap::iterator i = tableInfoMap.begin(); i != tableInfoMap.end(); i++) { if (find(joinedTables.begin(), joinedTables.end(), i->first) == joinedTables.end()) notJoinedTables.push_back(i->first); } - vector::iterator k = joinedTables.begin(); + vector::iterator k = joinedTables.begin(); set views1; set tables1; for (; k != joinedTables.end(); k++) @@ -1614,7 +1337,7 @@ void spanningTreeCheck(TableInfoMap& tableInfoMap, JobStepVector joinSteps, JobI { errcode = ERR_INCOMPATIBLE_JOIN; - uint32_t key2 = jobInfo.incompatibleJoinMap[*k]; + uint key2 = jobInfo.incompatibleJoinMap[*k]; if (jobInfo.keyInfo->tupleKeyVec[*k].fView.length() > 0) { string view2 = jobInfo.keyInfo->tupleKeyVec[key2].fView; @@ -1725,7 +1448,7 @@ void spanningTreeCheck(TableInfoMap& tableInfoMap, JobStepVector joinSteps, JobI } // 2. no cycles - if (spanningTree && (nodeSet.size() - pathSet.size()/2 != 1)) + if (spanningTree && (joinedTables.size() - joinPaths.size()/2 != 1)) { errcode = ERR_CIRCULAR_JOIN; spanningTree = false; @@ -1742,7 +1465,7 @@ void spanningTreeCheck(TableInfoMap& tableInfoMap, JobStepVector joinSteps, JobI void outjoinPredicateAdjust(TableInfoMap& tableInfoMap, JobInfo& jobInfo) { - set::iterator i = jobInfo.outerOnTable.begin(); + set::iterator i = jobInfo.outerOnTable.begin(); for (; i != jobInfo.outerOnTable.end(); i++) { // resetTableFilters(tableInfoMap[*i], jobInfo) @@ -1759,7 +1482,7 @@ void outjoinPredicateAdjust(TableInfoMap& tableInfoMap, JobInfo& jobInfo) continue; } - uint32_t colKey = -1; + uint colKey = -1; pColStep* pcs = dynamic_cast(k->get()); pColScanStep* pcss = dynamic_cast(k->get()); pDictionaryScan* pdss = dynamic_cast(k->get()); @@ -1808,10 +1531,15 @@ void outjoinPredicateAdjust(TableInfoMap& tableInfoMap, JobInfo& jobInfo) pt = op; } - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + if (es == NULL) throw runtime_error ("Failed to new ExpressionStep 2"); + es->logger(jobInfo.logger); es->expressionFilter(pt, jobInfo); SJSTEP sjstep(es); jobInfo.outerJoinExpressions.push_back(sjstep); @@ -1836,7 +1564,7 @@ void outjoinPredicateAdjust(TableInfoMap& tableInfoMap, JobInfo& jobInfo) } -uint32_t getLargestTable(JobInfo& jobInfo, TableInfoMap& tableInfoMap, bool overrideLargeSideEstimate) +uint getLargestTable(JobInfo& jobInfo, TableInfoMap& tableInfoMap, bool overrideLargeSideEstimate) { // Subquery in FROM clause assumptions: // hint will be ignored, if the 1st table in FROM clause is a derived table. @@ -1850,7 +1578,7 @@ uint32_t getLargestTable(JobInfo& jobInfo, TableInfoMap& tableInfoMap, bool over // Default to the first table in the from clause if: // the user set the hint; or // there is only one table in the query. - uint32_t ret = jobInfo.tableList.front(); + uint ret = jobInfo.tableList.front(); if(jobInfo.tableList.size() <= 1) { @@ -1862,7 +1590,7 @@ uint32_t getLargestTable(JobInfo& jobInfo, TableInfoMap& tableInfoMap, bool over uint64_t estimatedRowCount = 0; // Loop through the tables and find the one with the largest estimated cardinality. - for (uint32_t i = 0; i < jobInfo.tableList.size(); i++) + for (uint i = 0; i < jobInfo.tableList.size(); i++) { jobInfo.tableSize[jobInfo.tableList[i]] = 0; TableInfoMap::iterator it = tableInfoMap.find(jobInfo.tableList[i]); @@ -1884,7 +1612,7 @@ uint32_t getLargestTable(JobInfo& jobInfo, TableInfoMap& tableInfoMap, bool over ret = jobInfo.tableList[i]; largestCardinality = estimatedRowCount; } - break; + break; } } } @@ -1901,13 +1629,13 @@ uint32_t getLargestTable(JobInfo& jobInfo, TableInfoMap& tableInfoMap, bool over } -uint32_t getPrevLarge(uint32_t n, TableInfoMap& tableInfoMap) +uint getPrevLarge(uint n, TableInfoMap& tableInfoMap) { // root node : no previous node; // other node: only one immediate previous node; int prev = -1; - vector& adjList = tableInfoMap[n].fAdjacentList; - for (vector::iterator i = adjList.begin(); i != adjList.end() && prev < 0; i++) + vector& adjList = tableInfoMap[n].fAdjacentList; + for (vector::iterator i = adjList.begin(); i != adjList.end() && prev < 0; i++) { if (tableInfoMap[*i].fVisited == true) prev = *i; @@ -1917,9 +1645,9 @@ uint32_t getPrevLarge(uint32_t n, TableInfoMap& tableInfoMap) } -uint32_t getKeyIndex(uint32_t key, const RowGroup& rg) +uint getKeyIndex(uint key, const RowGroup& rg) { - vector::const_iterator i = rg.getKeys().begin(); + vector::const_iterator i = rg.getKeys().begin(); for (; i != rg.getKeys().end(); ++i) if (key == *i) break; @@ -1940,7 +1668,7 @@ bool joinInfoCompare(const SP_JoinInfo& a, const SP_JoinInfo& b) string joinTypeToString(const JoinType& joinType) { string ret; - if (joinType & INNER) + if (joinType & INNER) ret = "inner"; else if (joinType & LARGEOUTER) ret = "largeOuter"; @@ -1964,8 +1692,8 @@ string joinTypeToString(const JoinType& joinType) } -SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, - JobInfo& jobInfo, vector& joinOrder) +SP_JoinInfo joinToLargeTable(uint large, TableInfoMap& tableInfoMap, + JobInfo& jobInfo, vector& joinOrder) { vector smallSides; tableInfoMap[large].fVisited = true; @@ -1974,12 +1702,15 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, vector& adjList = tableInfoMap[large].fAdjacentList; uint32_t prevLarge = (uint32_t) getPrevLarge(large, tableInfoMap); bool root = (prevLarge == (uint32_t) -1) ? true : false; + uint32_t link = large; + uint32_t cId = -1; // Get small sides ready. - for (vector::iterator i = adjList.begin(); i != adjList.end(); i++) + for (vector::iterator i = adjList.begin(); i != adjList.end(); i++) { if (tableInfoMap[*i].fVisited == false) { + cId = *i; smallSides.push_back(joinToLargeTable(*i, tableInfoMap, jobInfo, joinOrder)); tableSet.insert(tableInfoMap[*i].fJoinedTables.begin(), @@ -1995,6 +1726,41 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, BatchPrimitive* bps = dynamic_cast(spjs.get()); SubAdapterStep* tsas = dynamic_cast(spjs.get()); TupleHashJoinStep* thjs = dynamic_cast(spjs.get()); + + // @bug6158, try to put BPS on large side if possible + if (tsas && smallSides.size() == 1) + { + SJSTEP sspjs = tableInfoMap[cId].fQuerySteps.back(),get(); + BatchPrimitive* sbps = dynamic_cast(sspjs.get()); + TupleHashJoinStep* sthjs = dynamic_cast(sspjs.get()); + if (sbps || (sthjs && sthjs->tokenJoin() == cId)) + { + SP_JoinInfo largeJoinInfo(new JoinInfo); + largeJoinInfo->fTableOid = tableInfoMap[large].fTableOid; + largeJoinInfo->fAlias = tableInfoMap[large].fAlias; + largeJoinInfo->fView = tableInfoMap[large].fView; + largeJoinInfo->fSchema = tableInfoMap[large].fSchema; + + largeJoinInfo->fDl = tableInfoMap[large].fDl; + largeJoinInfo->fRowGroup = tableInfoMap[large].fRowGroup; + + TableJoinMap::iterator mit = jobInfo.tableJoinMap.find(make_pair(large, cId)); + if (mit == jobInfo.tableJoinMap.end()) + throw runtime_error("Join step not found."); + largeJoinInfo->fJoinData = mit->second; + + // switch large and small sides + joinOrder.back() = large; + large = cId; + smallSides[0] = largeJoinInfo; + tableInfoMap[large].fJoinedTables = tableSet; + + bps = sbps; + thjs = sthjs; + tsas = NULL; + } + } + if (!bps && !thjs && !tsas) { if (dynamic_cast(spjs.get())) @@ -2003,12 +1769,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, } size_t dcf = 0; // for dictionary column filters, 0 if thjs is null. - RowGroup largeSideRG = tableInfoMap[large].fRowGroup; - if (thjs && thjs->tokenJoin() == large) - { - dcf = thjs->getLargeKeys().size(); - largeSideRG = thjs->getLargeRowGroup(); - } + if (thjs) dcf = thjs->getLargeKeys().size(); // info for debug trace vector tableNames; @@ -2023,8 +1784,8 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, vector smallSideRGs; vector jointypes; vector typeless; - vector > smallKeyIndices; - vector > largeKeyIndices; + vector > smallKeyIndices; + vector > largeKeyIndices; for (vector::iterator i = smallSides.begin(); i != smallSides.end(); i++) { JoinInfo* info = i->get(); @@ -2033,18 +1794,17 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, jointypes.push_back(info->fJoinData.fTypes[0]); typeless.push_back(info->fJoinData.fTypeless); - vector smallIndices; - vector largeIndices; - const vector& keys1 = info->fJoinData.fLeftKeys; - const vector& keys2 = info->fJoinData.fRightKeys; - vector::const_iterator k1 = keys1.begin(); - vector::const_iterator k2 = keys2.begin(); - uint32_t stid = getTableKey(jobInfo, *k1); - tableNames.push_back(jobInfo.keyInfo->tupleKeyVec[stid].fTable); + vector smallIndices; + vector largeIndices; + const vector& keys1 = info->fJoinData.fLeftKeys; + const vector& keys2 = info->fJoinData.fRightKeys; + vector::const_iterator k1 = keys1.begin(); + vector::const_iterator k2 = keys2.begin(); + tableNames.push_back(jobInfo.keyInfo->tupleKeyVec[*k1].fTable); for (; k1 != keys1.end(); ++k1, ++k2) { smallIndices.push_back(getKeyIndex(*k1, info->fRowGroup)); - largeIndices.push_back(getKeyIndex(*k2, largeSideRG)); + largeIndices.push_back(getKeyIndex(*k2, tableInfoMap[large].fRowGroup)); } smallKeyIndices.push_back(smallIndices); @@ -2054,7 +1814,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, { // small side column ostringstream smallKey, smallIndex; - string alias1 = jobInfo.keyInfo->keyName[getTableKey(jobInfo, keys1.front())]; + string alias1 = jobInfo.keyInfo->tupleKeyVec[keys1.front()].fTable; smallKey << alias1 << "-"; for (k1 = keys1.begin(); k1 != keys1.end(); ++k1) { @@ -2065,14 +1825,14 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, } // large side column ostringstream largeKey, largeIndex; - string alias2 = jobInfo.keyInfo->keyName[getTableKey(jobInfo, keys2.front())]; + string alias2 = jobInfo.keyInfo->tupleKeyVec[keys2.front()].fTable; largeKey << alias2 << "-"; for (k2 = keys2.begin(); k2 != keys2.end(); ++k2) { CalpontSystemCatalog::OID oid2 = jobInfo.keyInfo->tupleKeyVec[*k2].fId; CalpontSystemCatalog::TableColName tcn2 = jobInfo.csc->colName(oid2); largeKey << "(" << tcn2.column << ":" << oid2 << ":" << *k2 << ")"; - largeIndex << " " << getKeyIndex(*k2, largeSideRG); + largeIndex << " " << getKeyIndex(*k2, tableInfoMap[large].fRowGroup); } ostringstream oss; @@ -2090,13 +1850,18 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, if (jobInfo.trace) { ostringstream oss; - oss << "large side RG" << endl << largeSideRG.toString() << endl; + oss << "large side RG" << endl << tableInfoMap[large].fRowGroup.toString() << endl; traces.push_back(oss.str()); } if (bps || tsas) { - thjs= new TupleHashJoinStep(jobInfo); + thjs= new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm,jobInfo.isExeMgr); + thjs->logger(jobInfo.logger); thjs->tableOid1(smallSides[0]->fTableOid); thjs->tableOid2(tableInfoMap[large].fTableOid); thjs->alias1(smallSides[0]->fAlias); @@ -2113,13 +1878,13 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, SJSTEP spjs(thjs); - JobStepAssociation inJsa; + JobStepAssociation inJsa(jobInfo.status); inJsa.outAdd(smallSideDLs, 0); inJsa.outAdd(tableInfoMap[large].fDl); thjs->inputAssociation(inJsa); thjs->setLargeSideDLIndex(inJsa.outSize() - 1); - JobStepAssociation outJsa; + JobStepAssociation outJsa(jobInfo.status); AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); spdl->rowGroupDL(dl); @@ -2149,7 +1914,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, } RowGroup rg; - constructJoinedRowGroup(rg, large, prevLarge, root, tableSet, tableInfoMap, jobInfo); + constructJoinedRowGroup(rg, link, prevLarge, root, tableSet, tableInfoMap, jobInfo); thjs->setOutputRowGroup(rg); tableInfoMap[large].fRowGroup = rg; if (jobInfo.trace) @@ -2169,19 +1934,11 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, ExpressionStep* exp = dynamic_cast(eit->get()); if (exp == NULL) throw runtime_error("Not an expression."); - - if (exp->functionJoin()) - { - eit++; - continue; // done as join - } - - const vector& tables = exp->tableKeys(); + const vector& tables = exp->tableKeys(); uint64_t i = 0; for (; i < tables.size(); i++) { - if (tableInfoMap[large].fJoinedTables.find(tables[i]) == - tableInfoMap[large].fJoinedTables.end()) + if (tableSet.find(tables[i]) == tableSet.end()) break; } @@ -2206,7 +1963,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, // check additional compares for semi-join if (readyExpSteps.size() > 0) { - map keyToIndexMap; // map keys to the indices in the RG + map keyToIndexMap; // map keys to the indices in the RG for (uint64_t i = 0; i < rg.getKeys().size(); ++i) keyToIndexMap.insert(make_pair(rg.getKeys()[i], i)); @@ -2241,7 +1998,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, continue; } - const vector& tables = e->tableKeys(); + const vector& tables = e->tableKeys(); map::iterator j = correlateTables.end(); for (size_t i = 0; i < tables.size(); i++) @@ -2287,7 +2044,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, ParseTree* pt = correlateCompare[k->first]; if (pt != NULL) { - boost::shared_ptr sppt(pt); + shared_ptr sppt(pt); thjs->addJoinFilter(sppt, dcf + k->second); } @@ -2327,13 +2084,13 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, } } - boost::shared_ptr sppt(pt); + shared_ptr sppt(pt); thjs->addFcnExpGroup2(sppt); } // update the fColsInExp2 and construct the output RG updateExp2Cols(readyExpSteps, tableInfoMap, jobInfo); - constructJoinedRowGroup(rg, large, prevLarge, root, tableSet, tableInfoMap, jobInfo); + constructJoinedRowGroup(rg, link, prevLarge, root, tableSet, tableInfoMap, jobInfo); if (thjs->hasFcnExpGroup2()) thjs->setFE23Output(rg); else @@ -2349,7 +2106,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, // Prepare the current table info to join with its large side. - SP_JoinInfo joinInfo(new JoinInfo); + SP_JoinInfo joinInfo(new JoinInfo); joinInfo->fTableOid = tableInfoMap[large].fTableOid; joinInfo->fAlias = tableInfoMap[large].fAlias; joinInfo->fView = tableInfoMap[large].fView; @@ -2360,7 +2117,7 @@ SP_JoinInfo joinToLargeTable(uint32_t large, TableInfoMap& tableInfoMap, if (root == false) // not root { - TableJoinMap::iterator mit = jobInfo.tableJoinMap.find(make_pair(large, prevLarge)); + TableJoinMap::iterator mit = jobInfo.tableJoinMap.find(make_pair(link, prevLarge)); if (mit == jobInfo.tableJoinMap.end()) throw runtime_error("Join step not found."); @@ -2382,9 +2139,9 @@ bool joinStepCompare(const SJSTEP& a, const SJSTEP& b) struct JoinOrderData { - uint32_t fTid1; - uint32_t fTid2; - uint32_t fJoinId; + uint fTid1; + uint fTid2; + uint fJoinId; }; @@ -2417,7 +2174,7 @@ void getJoinOrder(vector& joins, JobStepVector& joinSteps, JobInf } } -inline void updateJoinSides(uint32_t small, uint32_t large, map& joinInfoMap, +inline void updateJoinSides(uint small, uint large, map& joinInfoMap, vector& smallSides, TableInfoMap& tableInfoMap, JobInfo& jobInfo) { TableJoinMap::iterator mit = jobInfo.tableJoinMap.find(make_pair(small, large)); @@ -2435,11 +2192,11 @@ inline void updateJoinSides(uint32_t small, uint32_t large, map& joinOrder) +void joinTablesInOrder(uint largest, JobStepVector& joinSteps, TableInfoMap& tableInfoMap, + JobInfo& jobInfo, vector& joinOrder) { // populate the tableInfo for join - map joinInfoMap; // + map joinInfoMap; // // > // large priority: @@ -2447,7 +2204,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& // 0 - prefer to be on small side, like FROM subquery; // 1 - can be on either large or small side; // 2 - must be on large side. - map > joinStepMap; + map > joinStepMap; BatchPrimitive* bps = NULL; SubAdapterStep* tsas = NULL; @@ -2486,24 +2243,27 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& // join the steps int64_t lastJoinId = -1; - uint32_t large = (uint32_t) -1; - uint32_t small = (uint32_t) -1; - uint32_t prevLarge = (uint32_t) -1; + uint large = (uint) -1; + uint small = (uint) -1; + uint prevLarge = (uint) -1; bool umstream = false; - vector joinedTable; - uint32_t lastJoin = joins.size() - 1; + vector joinedTable; + uint lastJoin = joins.size() - 1; bool isSemijoin = true; for (uint64_t js = 0; js < joins.size(); js++) { - set smallSideTid; + map joinIdIndexMap; + set smallSideTid; + size_t index = 0; + joinIdIndexMap[joins[js].fJoinId] = index++; if (joins[js].fJoinId != 0) isSemijoin = false; vector smallSides; - uint32_t tid1 = joins[js].fTid1; - uint32_t tid2 = joins[js].fTid2; + uint tid1 = joins[js].fTid1; + uint tid2 = joins[js].fTid2; lastJoinId = joins[js].fJoinId; // largest has already joined, and this join cannot be merged. @@ -2534,11 +2294,11 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& smallSideTid.insert(small); // merge in the next step if the large side is the same - for (uint64_t ns = js + 1; ns < joins.size(); js++, ns++) + for (uint64_t ns = js + 1; ns < joins.size(); ns++) { - uint32_t tid1 = joins[ns].fTid1; - uint32_t tid2 = joins[ns].fTid2; - uint32_t small = (uint32_t) -1; + uint tid1 = joins[ns].fTid1; + uint tid2 = joins[ns].fTid2; + uint small = (uint) -1; if ((tid1 == large) && ((joinStepMap[tid1].second > joinStepMap[tid2].second) || @@ -2562,8 +2322,8 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& // check if FE needs table in previous smallsides if (jobInfo.joinFeTableMap[joins[ns].fJoinId].size() > 0) { - set& tids = jobInfo.joinFeTableMap[joins[ns].fJoinId]; - for (set::iterator si = smallSideTid.begin(); si != smallSideTid.end(); si++) + set& tids = jobInfo.joinFeTableMap[joins[ns].fJoinId]; + for (set::iterator si = smallSideTid.begin(); si != smallSideTid.end(); si++) { if (tids.find(*si) != tids.end()) throw runtime_error("On clause filter involving a table not directly involved in the outer join is currently not supported."); @@ -2575,6 +2335,9 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& if (find(joinedTable.begin(), joinedTable.end(), small) == joinedTable.end()) joinedTable.push_back(small); smallSideTid.insert(small); + + joinIdIndexMap[joins[ns].fJoinId] = index++; + js++; } joinedTable.push_back(large); @@ -2591,9 +2354,6 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& } size_t startPos = 0; // start point to add new smallsides - RowGroup largeSideRG = joinInfoMap[large]->fRowGroup; - if (thjs && thjs->tokenJoin() == large) - largeSideRG = thjs->getLargeRowGroup(); // get info to config the TupleHashjoin vector traces; @@ -2602,54 +2362,57 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& vector smallSideRGs; vector jointypes; vector typeless; - vector > smallKeyIndices; - vector > largeKeyIndices; - - // bug5764, make sure semi joins acting as filter is after outer join. - { - // the inner table filters have to be performed after outer join - vector semijoins; - vector smallouts; - for (size_t i = 0; i < smallSides.size(); i++) - { - // find the the small-outer and semi-join joins - JoinType jt = smallSides[i]->fJoinData.fTypes[0]; - if (jt & SMALLOUTER) - smallouts.push_back(i); - else if (jt & (SEMI | ANTI | SCALAR | CORRELATED)) - semijoins.push_back(i); - } - - // check the join order, re-arrange if necessary - if (smallouts.size() > 0 && semijoins.size() > 0) - { - uint64_t lastSmallOut = smallouts.back(); - uint64_t lastSemijoin = semijoins.back(); - if (lastSmallOut > lastSemijoin) - { - vector temp1; - vector temp2; - size_t j = 0; - for (size_t i = 0; i < smallSides.size(); i++) - { - if (j < semijoins.size() && i == semijoins[j]) - { - temp1.push_back(smallSides[i]); - j++; - } - else - { - temp2.push_back(smallSides[i]); - } - - if (i == lastSmallOut) - temp2.insert(temp2.end(), temp1.begin(), temp1.end()); - } - - smallSides = temp2; - } - } - } + vector > smallKeyIndices; + vector > largeKeyIndices; + + // bug5764, make sure semi joins acting as filter is after outer join. + { + // the inner table filters have to be performed after outer join + vector semijoins; + vector smallouts; + for (size_t i = 0; i < smallSides.size(); i++) + { + // find the the small-outer and semi-join joins + JoinType jt = smallSides[i]->fJoinData.fTypes[0]; + if (jt & SMALLOUTER) + smallouts.push_back(i); + else if (jt & (SEMI | ANTI | SCALAR | CORRELATED)) + semijoins.push_back(i); + } + + // check the join order, re-arrange if necessary + if (smallouts.size() > 0 && semijoins.size() > 0) + { + uint64_t lastSmallOut = smallouts.back(); + uint64_t lastSemijoin = semijoins.back(); + if (lastSmallOut > lastSemijoin) + { + vector temp1; + vector temp2; + size_t j = 0; + for (size_t i = 0; i < smallSides.size(); i++) + { + if (j < semijoins.size() && i == semijoins[j]) + { + temp1.push_back(smallSides[i]); + j++; + } + else + { + temp2.push_back(smallSides[i]); + } + + if (i == lastSmallOut) + temp2.insert(temp2.end(), temp1.begin(), temp1.end()); + } + + smallSides = temp2; + + for (size_t i = 0; i < smallSides.size(); i++) + joinIdIndexMap[smallSides[i]->fJoinData.fJoinId] = i; + } + } + } for (vector::iterator i = smallSides.begin(); i != smallSides.end(); i++) { @@ -2659,18 +2422,17 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& jointypes.push_back(info->fJoinData.fTypes[0]); typeless.push_back(info->fJoinData.fTypeless); - vector smallIndices; - vector largeIndices; - const vector& keys1 = info->fJoinData.fLeftKeys; - const vector& keys2 = info->fJoinData.fRightKeys; - vector::const_iterator k1 = keys1.begin(); - vector::const_iterator k2 = keys2.begin(); - uint32_t stid = getTableKey(jobInfo, *k1); - tableNames.push_back(jobInfo.keyInfo->tupleKeyVec[stid].fTable); + vector smallIndices; + vector largeIndices; + const vector& keys1 = info->fJoinData.fLeftKeys; + const vector& keys2 = info->fJoinData.fRightKeys; + vector::const_iterator k1 = keys1.begin(); + vector::const_iterator k2 = keys2.begin(); + tableNames.push_back(jobInfo.keyInfo->tupleKeyVec[*k1].fTable); for (; k1 != keys1.end(); ++k1, ++k2) { smallIndices.push_back(getKeyIndex(*k1, info->fRowGroup)); - largeIndices.push_back(getKeyIndex(*k2, largeSideRG)); + largeIndices.push_back(getKeyIndex(*k2, joinInfoMap[large]->fRowGroup)); } smallKeyIndices.push_back(smallIndices); @@ -2680,7 +2442,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& { // small side column ostringstream smallKey, smallIndex; - string alias1 = jobInfo.keyInfo->keyName[getTableKey(jobInfo, keys1.front())]; + string alias1 = jobInfo.keyInfo->tupleKeyVec[keys1.front()].fTable; smallKey << alias1 << "-"; for (k1 = keys1.begin(); k1 != keys1.end(); ++k1) { @@ -2691,14 +2453,14 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& } // large side column ostringstream largeKey, largeIndex; - string alias2 = jobInfo.keyInfo->keyName[getTableKey(jobInfo, keys2.front())]; + string alias2 = jobInfo.keyInfo->tupleKeyVec[keys2.front()].fTable; largeKey << alias2 << "-"; for (k2 = keys2.begin(); k2 != keys2.end(); ++k2) { CalpontSystemCatalog::OID oid2 = jobInfo.keyInfo->tupleKeyVec[*k2].fId; CalpontSystemCatalog::TableColName tcn2 = jobInfo.csc->colName(oid2); largeKey << "(" << tcn2.column << ":" << oid2 << ":" << *k2 << ")"; - largeIndex << " " << getKeyIndex(*k2, largeSideRG); + largeIndex << " " << getKeyIndex(*k2, joinInfoMap[large]->fRowGroup); } ostringstream oss; @@ -2716,13 +2478,18 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& if (jobInfo.trace) { ostringstream oss; - oss << "large side RG" << endl << largeSideRG.toString() << endl; + oss << "large side RG" << endl << joinInfoMap[large]->fRowGroup.toString() << endl; traces.push_back(oss.str()); } if (bps || tsas || umstream || (thjs && joinStepMap[large].second < 1)) { - thjs= new TupleHashJoinStep(jobInfo); + thjs= new TupleHashJoinStep( + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.statementId, + &jobInfo.rm,jobInfo.isExeMgr); + thjs->logger(jobInfo.logger); thjs->tableOid1(smallSides[0]->fTableOid); thjs->tableOid2(tableInfoMap[large].fTableOid); thjs->alias1(smallSides[0]->fAlias); @@ -2739,13 +2506,13 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& spjs.reset(thjs); - JobStepAssociation inJsa; + JobStepAssociation inJsa(jobInfo.status); inJsa.outAdd(smallSideDLs, 0); inJsa.outAdd(joinInfoMap[large]->fDl); thjs->inputAssociation(inJsa); thjs->setLargeSideDLIndex(inJsa.outSize() - 1); - JobStepAssociation outJsa; + JobStepAssociation outJsa(jobInfo.status); AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); spdl->rowGroupDL(dl); @@ -2775,7 +2542,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& } RowGroup rg; - set& tableSet = tableInfoMap[large].fJoinedTables; + set& tableSet = tableInfoMap[large].fJoinedTables; constructJoinedRowGroup(rg, tableSet, tableInfoMap, jobInfo); thjs->setOutputRowGroup(rg); tableInfoMap[large].fRowGroup = rg; @@ -2788,14 +2555,6 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& cout << "RowGroup join result: " << endl << rg.toString() << endl << endl; } - // on clause filter association - map joinIdIndexMap; - for (size_t i = 0; i < smallSides.size(); i++) - { - if (smallSides[i]->fJoinData.fJoinId > 0) - joinIdIndexMap[smallSides[i]->fJoinData.fJoinId] = i; - } - // check if any cross-table expressions can be evaluated after the join JobStepVector readyExpSteps; JobStepVector& expSteps = jobInfo.crossTableExpressions; @@ -2805,14 +2564,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& ExpressionStep* exp = dynamic_cast(eit->get()); if (exp == NULL) throw runtime_error("Not an expression."); - - if (exp->functionJoin()) - { - eit++; - continue; // done as join - } - - const vector& tables = exp->tableKeys(); + const vector& tables = exp->tableKeys(); uint64_t i = 0; for (; i < tables.size(); i++) { @@ -2851,7 +2603,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& // check additional compares for semi-join if (readyExpSteps.size() > 0) { - map keyToIndexMap; // map keys to the indices in the RG + map keyToIndexMap; // map keys to the indices in the RG for (uint64_t i = 0; i < rg.getKeys().size(); ++i) keyToIndexMap.insert(make_pair(rg.getKeys()[i], i)); @@ -2886,7 +2638,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& continue; } - const vector& tables = e->tableKeys(); + const vector& tables = e->tableKeys(); map::iterator j = correlateTables.end(); for (size_t i = 0; i < tables.size(); i++) @@ -2932,7 +2684,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& ParseTree* pt = correlateCompare[k->first]; if (pt != NULL) { - boost::shared_ptr sppt(pt); + shared_ptr sppt(pt); thjs->addJoinFilter(sppt, startPos + k->second); } @@ -2956,11 +2708,11 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& // short circuit on clause expressions map::iterator x = joinIdIndexMap.find(e->associatedJoinId()); - if (x != joinIdIndexMap.end()) + if (e->associatedJoinId() > 0 && x != joinIdIndexMap.end()) { ParseTree* joinFilter = new ParseTree; joinFilter->copyTree(*(e->expressionFilter())); - boost::shared_ptr sppt(joinFilter); + shared_ptr sppt(joinFilter); thjs->addJoinFilter(sppt, startPos + x->second); thjs->setJoinFilterInputRG(rg); continue; @@ -2986,7 +2738,7 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& if (pt != NULL) { - boost::shared_ptr sppt(pt); + shared_ptr sppt(pt); thjs->addFcnExpGroup2(sppt); } } @@ -3013,19 +2765,13 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& else joinStepMap[large] = make_pair(spjs, l); - for (set::iterator i = tableSet.begin(); i != tableSet.end(); i++) + for (set::iterator i = tableSet.begin(); i != tableSet.end(); i++) { joinInfoMap[*i]->fDl = tableInfoMap[large].fDl; joinInfoMap[*i]->fRowGroup = tableInfoMap[large].fRowGroup; if (*i != large) { - //@bug6117, token should be done for small side tables. - SJSTEP smallJs = joinStepMap[*i].first; - TupleHashJoinStep* smallThjs = dynamic_cast(smallJs.get()); - if (smallThjs && smallThjs->tokenJoin()) - smallThjs->tokenJoin(-1); - // Set join priority for smallsides. joinStepMap[*i] = make_pair(spjs, l); @@ -3039,25 +2785,24 @@ void joinTablesInOrder(uint32_t largest, JobStepVector& joinSteps, TableInfoMap& // Keep join order by the table last used for picking the right delivery step. { - for (vector::reverse_iterator i = joinedTable.rbegin(); i < joinedTable.rend(); i++) + for (vector::reverse_iterator i = joinedTable.rbegin(); i < joinedTable.rend(); i++) { if (find(joinOrder.begin(), joinOrder.end(), *i) == joinOrder.end()) joinOrder.push_back(*i); } - const uint64_t n = joinOrder.size(); - const uint64_t h = n / 2; - const uint64_t e = n - 1; + uint64_t n = joinOrder.size(); + uint64_t h = n/2, e = n - 1; for (uint64_t i = 0; i < h; i++) - std::swap(joinOrder[i], joinOrder[e - i]); + swap(joinOrder[i], joinOrder[e - i]); } } inline void joinTables(JobStepVector& joinSteps, TableInfoMap& tableInfoMap, JobInfo& jobInfo, - vector& joinOrder, const bool overrideLargeSideEstimate) + vector& joinOrder, const bool overrideLargeSideEstimate) { - uint32_t largestTable = getLargestTable(jobInfo, tableInfoMap, overrideLargeSideEstimate); + uint largestTable = getLargestTable(jobInfo, tableInfoMap, overrideLargeSideEstimate); if (jobInfo.outerOnTable.size() == 0) joinToLargeTable(largestTable, tableInfoMap, jobInfo, joinOrder); else @@ -3079,7 +2824,6 @@ void makeNoTableJobStep(JobStepVector& querySteps, JobStepVector& projectSteps, } - namespace joblist { void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSteps, @@ -3088,7 +2832,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte { if (jobInfo.trace) { - const boost::shared_ptr& keyInfo = jobInfo.keyInfo; + const shared_ptr& keyInfo = jobInfo.keyInfo; cout << "query steps:" << endl; for (JobStepVector::iterator i = querySteps.begin(); i != querySteps.end(); ++i) { @@ -3109,42 +2853,34 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte << (int)((id2 != -1) ? getTableKey(jobInfo, id2) : -1) << endl; } } - cout << "project steps:" << endl; for (JobStepVector::iterator i = projectSteps.begin(); i != projectSteps.end(); ++i) { cout << typeid(*(i->get())).name() << ": " << (*i)->oid() << " " << (*i)->tupleId() << " " << getTableKey(jobInfo, (*i)->tupleId()) << endl; } - cout << "delivery steps:" << endl; for (DeliveredTableMap::iterator i = deliverySteps.begin(); i != deliverySteps.end(); ++i) cout << typeid(*(i->second.get())).name() << endl; - cout << "\nTable Info: (key oid name alias view sub)" << endl; - for (uint32_t i = 0; i < keyInfo->tupleKeyVec.size(); ++i) + TupleInfoMap::iterator iter = keyInfo->tupleInfoMap.begin(); + cout << "\nTupleInfoMap: (tupleKey oid tableName view sub)" << endl; + while (iter != keyInfo->tupleInfoMap.end()) { - int64_t tid = jobInfo.keyInfo->colKeyToTblKey[i]; - if (tid == i) - { - CalpontSystemCatalog::OID oid = keyInfo->tupleKeyVec[i].fId; - string alias = keyInfo->tupleKeyVec[i].fTable; - if (alias.length() < 1) alias = "N/A"; - string name = keyInfo->keyName[i]; - if (name.empty()) name = "unknown"; - string view = keyInfo->tupleKeyVec[i].fView; - if (view.length() < 1) view = "N/A"; - int sid = keyInfo->tupleKeyVec[i].fSubId; - cout << i << "\t" << oid << "\t" << name << "\t" << alias - << "\t" << view << "\t" << hex << sid << dec << endl; - } + string alias = keyInfo->tupleKeyVec[iter->first].fTable; + if (alias.length() < 1) alias = "N/A"; + string view = keyInfo->tupleKeyVec[iter->first].fView; + if (view.length() < 1) view = "N/A"; + int sid = keyInfo->tupleKeyVec[iter->first].fSubId; + cout << iter->first << "\t" << keyInfo->tupleKeyVec[iter->first].fId + << "\t" << alias << "\t" << view << "\t" << hex << sid << dec << endl; + ++iter; } - cout << "\nTupleKey vector: (tupleKey oid tableKey name alias view sub)" << endl; - for (uint32_t i = 0; i < keyInfo->tupleKeyVec.size(); ++i) + cout << "\nTupleKey vector: (tupleKey oid name alias view sub)" << endl; + for (uint i = 0; i < keyInfo->tupleKeyVec.size(); ++i) { CalpontSystemCatalog::OID oid = keyInfo->tupleKeyVec[i].fId; - int64_t tid = jobInfo.keyInfo->colKeyToTblKey[i]; string alias = keyInfo->tupleKeyVec[i].fTable; if (alias.length() < 1) alias = "N/A"; // Expression IDs are borrowed from systemcatalog IDs, which are not used in tuple. @@ -3153,10 +2889,6 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte { name += "[d]"; // indicate this is a dictionary column } - if (jobInfo.keyInfo->pseudoType[i] > 0) - { - name += "[p]"; // indicate this is a pseudo column - } if (name.empty()) { name = "unknown"; @@ -3164,8 +2896,8 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte string view = keyInfo->tupleKeyVec[i].fView; if (view.length() < 1) view = "N/A"; int sid = keyInfo->tupleKeyVec[i].fSubId; - cout << i << "\t" << oid << "\t" << tid << "\t" << name << "\t" << alias - << "\t" << view << "\t" << hex << sid << dec << endl; + cout << i << "\t" << oid << "\t" << name << "\t" << alias << "\t" << view + << "\t" << hex << sid << dec << endl; } cout << endl; } @@ -3182,7 +2914,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte TableInfoMap tableInfoMap; for (uint64_t i = 0; i < jobInfo.tableList.size(); i++) { - uint32_t tableUid = jobInfo.tableList[i]; + uint tableUid = jobInfo.tableList[i]; tableInfoMap[tableUid] = TableInfo(); tableInfoMap[tableUid].fTableOid = jobInfo.keyInfo->tupleKeyVec[tableUid].fId; tableInfoMap[tableUid].fName = jobInfo.keyInfo->keyName[tableUid]; @@ -3201,54 +2933,25 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte for (uint64_t i = 0; i < querySteps.size(); ) { TupleConstantBooleanStep* bs = dynamic_cast(querySteps[i].get()); - ExpressionStep* es = dynamic_cast(querySteps[i].get()); if (bs != NULL) { - // cosntant step if (bs->boolValue() == false) jobInfo.constantFalse = true; querySteps.erase(querySteps.begin()+i); } - else if (es != NULL && es->tableKeys().size() == 0) - { - // constant expression - ParseTree* p = es->expressionFilter(); // filter - if (p != NULL) - { - Row r; // dummy row - if (funcexp::FuncExp::instance()->evaluate(r, p) == false) - jobInfo.constantFalse = true; - - querySteps.erase(querySteps.begin()+i); - } - } else { i++; } } - // double check if the function join canditates are still there. - JobStepVector steps = querySteps; - for (int64_t i = jobInfo.functionJoins.size()-1; i >= 0; i--) - { - bool exist = false; - for (JobStepVector::iterator j = steps.begin(); j != steps.end() && !exist; ++j) - { - if (jobInfo.functionJoins[i] == j->get()) - exist = true; - } - - if (!exist) - jobInfo.functionJoins.erase(jobInfo.functionJoins.begin() + i); - } - // Concatenate query and project steps + JobStepVector steps = querySteps; steps.insert(steps.end(), projectSteps.begin(), projectSteps.end()); // Make sure each query step has an output DL - // This is necessary for toString() method on most steps + // This is necessary for toString() method on most steps for (JobStepVector::iterator it = steps.begin(); it != steps.end(); ++it) { //if (dynamic_cast(it->get())) @@ -3256,7 +2959,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte if (it->get()->outputAssociation().outSize() == 0) { - JobStepAssociation jsa; + JobStepAssociation jsa(jobInfo.status); AnyDataListSPtr adl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); dl->OID(it->get()->oid()); @@ -3310,26 +3013,8 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte tableInfoMap[tid1].fJoinKeys.push_back(key1); tableInfoMap[tid2].fJoinKeys.push_back(key2); - // save the function join expressions - boost::shared_ptr fji = thjs->funcJoinInfo(); - if (fji) - { - if (fji->fStep[0]) - { - tableInfoMap[tid1].fFuncJoinExps.push_back(fji->fStep[0]); - vector& cols = tableInfoMap[tid1].fColsInFuncJoin; - cols.insert(cols.end(), fji->fColumnKeys[0].begin(), fji->fColumnKeys[0].end()); - } - if (fji->fStep[1]) - { - tableInfoMap[tid2].fFuncJoinExps.push_back(fji->fStep[1]); - vector& cols = tableInfoMap[tid2].fColsInFuncJoin; - cols.insert(cols.end(), fji->fColumnKeys[1].begin(), fji->fColumnKeys[1].end()); - } - } - // keep a join map - pair tablePair(tid1, tid2); + pair tablePair(tid1, tid2); TableJoinMap::iterator m1 = jobInfo.tableJoinMap.find(tablePair); TableJoinMap::iterator m2 = jobInfo.tableJoinMap.end(); if (m1 == jobInfo.tableJoinMap.end()) @@ -3340,8 +3025,8 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte m1 = jobInfo.tableJoinMap.insert(m1, make_pair(make_pair(tid1,tid2), JoinData())); m2 = jobInfo.tableJoinMap.insert(m1, make_pair(make_pair(tid2,tid1), JoinData())); - TupleInfo ti1(getTupleInfo(key1, jobInfo)); - TupleInfo ti2(getTupleInfo(key2, jobInfo)); + TupleInfo ti1(getTupleInfo(tid1, key1, jobInfo)); + TupleInfo ti2(getTupleInfo(tid2, key2, jobInfo)); if (ti1.width > 8 || ti2.width > 8) m1->second.fTypeless = m2->second.fTypeless = true; else @@ -3380,7 +3065,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte else if ((joinType & SEMI) && ((joinType & LEFTOUTER) == LEFTOUTER || (joinType & RIGHTOUTER) == RIGHTOUTER)) { - // @bug3998, DML UPDATE borrows "SEMI" flag, + // @bug3998, DML UPDATE borrows "SEMI" flag, // allowing SEMI and LARGEOUTER combination to support update with outer join. if ((joinType & LEFTOUTER) == LEFTOUTER) { @@ -3409,8 +3094,9 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte // Separate the expressions else if (exps != NULL && subs == NULL) { - const vector& tables = exps->tableKeys(); - const vector& columns = exps->columnKeys(); + const vector& oids = exps->oids(); + const vector& tables = exps->tableKeys(); + const vector& columns = exps->columnKeys(); bool tableInOuterQuery = false; set tableSet; // involved unique tables for (uint64_t i = 0; i < tables.size(); ++i) @@ -3436,7 +3122,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte if (jobInfo.returnColSet.find(c) == jobInfo.returnColSet.end()) { tableInfoMap[tables[i]].fProjectCols.push_back(c); - jobInfo.pjColList.push_back(getTupleInfo(c, jobInfo)); + jobInfo.pjColList.push_back(getTupleInfo(tables[i], c, jobInfo)); jobInfo.returnColSet.insert(c); const SimpleColumn* sc = dynamic_cast(exps->columns()[i]); @@ -3454,7 +3140,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte { // single table and not in join on clause uint32_t tid = tables[0]; - for (uint64_t i = 0; i < columns.size(); ++i) + for (uint64_t i = 0; i < oids.size(); ++i) tableInfoMap[tid].fColsInExp1.push_back(columns[i]); tableInfoMap[tid].fOneTableExpSteps.push_back(*it); @@ -3464,14 +3150,14 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte // WORKAROUND for limitation on join with filter if (exps->associatedJoinId() != 0) { - for (uint64_t i = 0; i < exps->columns().size(); ++i) + for (uint64_t i = 0; i < exps->oids().size(); ++i) { jobInfo.joinFeTableMap[exps->associatedJoinId()].insert(tables[i]); } } // resolve after join: cross table or on clause conditions - for (uint64_t i = 0; i < columns.size(); ++i) + for (uint64_t i = 0; i < oids.size(); ++i) { uint32_t cid = columns[i]; uint32_t tid = getTableKey(jobInfo, cid); @@ -3507,63 +3193,6 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte // @bug5374, delay predicates for outerjoin outjoinPredicateAdjust(tableInfoMap, jobInfo); - // @bug4021, make sure there is real column to scan - for (TableInfoMap::iterator it = tableInfoMap.begin(); it != tableInfoMap.end(); it++) - { - uint32_t tableUid = it->first; - if (jobInfo.pseudoColTable.find(tableUid) == jobInfo.pseudoColTable.end()) - continue; - - JobStepVector& steps = tableInfoMap[tableUid].fQuerySteps; - JobStepVector::iterator s = steps.begin(); - JobStepVector::iterator p = steps.end(); - for (; s != steps.end(); s++) - { - if (typeid(*(s->get())) == typeid(pColScanStep) || - typeid(*(s->get())) == typeid(pColStep)) - break; - - // @bug5893, iterator to the first pseudocolumn - if (typeid(*(s->get())) == typeid(PseudoColStep) && p == steps.end()) - p = s; - } - - if (s == steps.end()) - { - map::iterator t = jobInfo.tableColMap.find(tableUid); - if (t == jobInfo.tableColMap.end()) - { - string msg = jobInfo.keyInfo->tupleKeyToName[tableUid]; - msg += " has no column in column map."; - throw runtime_error(msg); - } - - SimpleColumn* sc = dynamic_cast(t->second.get()); - CalpontSystemCatalog::OID oid = sc->oid(); - CalpontSystemCatalog::OID tblOid = tableOid(sc, jobInfo.csc); - CalpontSystemCatalog::ColType ct = sc->colType(); - string alias(extractTableAlias(sc)); - SJSTEP sjs(new pColScanStep(oid, tblOid, ct, jobInfo)); - sjs->alias(alias); - sjs->view(sc->viewName()); - sjs->schema(sc->schemaName()); - sjs->name(sc->columnName()); - TupleInfo ti(setTupleInfo(ct, oid, jobInfo, tblOid, sc, alias)); - sjs->tupleId(ti.key); - steps.insert(steps.begin(), sjs); - - if (isDictCol(ct) && jobInfo.tokenOnly.find(ti.key) == jobInfo.tokenOnly.end()) - jobInfo.tokenOnly[ti.key] = true; - } - else if (s > p) - { - // @bug5893, make sure a pcol is in front of any pseudo step. - SJSTEP t = *s; - *s = *p; - *p = t; - } - } - // @bug3767, error out scalar subquery with aggregation and correlated additional comparison. if (jobInfo.hasAggregation && (jobInfo.correlateSteps.size() > 0)) { @@ -3571,10 +3200,8 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte ExpressionStep* exp = NULL; for (it = jobInfo.correlateSteps.begin(); it != jobInfo.correlateSteps.end(); it++) { - if (((exp = dynamic_cast(it->get())) != NULL) && (!exp->functionJoin())) + if ((exp = dynamic_cast(it->get())) != NULL) break; - - exp = NULL; } // correlated join step @@ -3596,7 +3223,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte end = projectSteps.end(); while (it != end) { - uint32_t tid = getTableKey(jobInfo, (*it)->tupleId()); + uint tid = getTableKey(jobInfo, (*it)->tupleId()); tableInfoMap[tid].fProjectSteps.push_back(*it); tableInfoMap[tid].fProjectCols.push_back((*it)->tupleId()); it++; @@ -3604,10 +3231,10 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte for (TupleInfoVector::iterator j = jobInfo.pjColList.begin(); j != jobInfo.pjColList.end(); j++) { - if (jobInfo.keyInfo->tupleKeyVec[j->tkey].fId == CNX_EXP_TABLE_ID) + if (jobInfo.keyInfo->tupleKeyVec[j->tkey].fId == 3000) continue; - vector& projectCols = tableInfoMap[j->tkey].fProjectCols; + vector& projectCols = tableInfoMap[j->tkey].fProjectCols; if (find(projectCols.begin(), projectCols.end(), j->key) == projectCols.end()) projectCols.push_back(j->key); } @@ -3630,7 +3257,7 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte deliverySteps.clear(); // Check if the tables and joins can be used to construct a spanning tree. - spanningTreeCheck(tableInfoMap, joinSteps, jobInfo); + spanningTreeCheck(tableInfoMap, jobInfo); // 1. combine job steps for each table TableInfoMap::iterator mit; @@ -3639,11 +3266,11 @@ void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSte throw runtime_error("combineJobStepsByTable failed."); // 2. join the combined steps together to form the spanning tree - vector joinOrder; + vector joinOrder; joinTables(joinSteps, tableInfoMap, jobInfo, joinOrder, overrideLargeSideEstimate); // 3. put the steps together - for (vector::iterator i = joinOrder.begin(); i != joinOrder.end(); ++i) + for (vector::iterator i = joinOrder.begin(); i != joinOrder.end(); ++i) querySteps.insert(querySteps.end(), tableInfoMap[*i].fQuerySteps.begin(), tableInfoMap[*i].fQuerySteps.end()); @@ -3658,19 +3285,19 @@ SJSTEP unionQueries(JobStepVector& queries, uint64_t distinctUnionNum, JobInfo& vector distinct; uint64_t colCount = jobInfo.deliveredCols.size(); - vector oids; - vector keys; - vector scale; - vector precision; - vector width; + vector oids; + vector keys; + vector scale; + vector precision; + vector width; vector types; - JobStepAssociation jsaToUnion; + JobStepAssociation jsaToUnion(jobInfo.status); // bug4388, share code with connector for column type coversion vector > queryColTypes; for (uint64_t j = 0; j < colCount; ++j) queryColTypes.push_back(vector(queries.size())); - + for (uint64_t i = 0; i < queries.size(); i++) { SJSTEP& spjs = queries[i]; @@ -3683,8 +3310,8 @@ SJSTEP unionQueries(JobStepVector& queries, uint64_t distinctUnionNum, JobInfo& const RowGroup& rg = tds->getDeliveredRowGroup(); inputRGs.push_back(rg); - const vector& scaleIn = rg.getScale(); - const vector& precisionIn = rg.getPrecision(); + const vector& scaleIn = rg.getScale(); + const vector& precisionIn = rg.getPrecision(); const vector& typesIn = rg.getColTypes(); for (uint64_t j = 0; j < colCount; ++j) @@ -3697,8 +3324,8 @@ SJSTEP unionQueries(JobStepVector& queries, uint64_t distinctUnionNum, JobInfo& if (i == 0) { - const vector& oidsIn = rg.getOIDs(); - const vector& keysIn = rg.getKeys(); + const vector& oidsIn = rg.getOIDs(); + const vector& keysIn = rg.getKeys(); oids.insert(oids.end(), oidsIn.begin(), oidsIn.begin() + colCount); keys.insert(keys.end(), keysIn.begin(), keysIn.begin() + colCount); } @@ -3710,7 +3337,7 @@ SJSTEP unionQueries(JobStepVector& queries, uint64_t distinctUnionNum, JobInfo& RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); spdl->rowGroupDL(dl); dl->OID(CNX_VTABLE_ID); - JobStepAssociation jsa; + JobStepAssociation jsa(jobInfo.status); jsa.outAdd(spdl); spjs->outputAssociation(jsa); jsaToUnion.outAdd(spdl); @@ -3720,11 +3347,18 @@ SJSTEP unionQueries(JobStepVector& queries, uint64_t distinctUnionNum, JobInfo& RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); spdl->rowGroupDL(dl); dl->OID(CNX_VTABLE_ID); - JobStepAssociation jsa; + JobStepAssociation jsa(jobInfo.status); jsa.outAdd(spdl); - TupleUnion *unionStep = new TupleUnion(CNX_VTABLE_ID, jobInfo); - unionStep->inputAssociation(jsaToUnion); - unionStep->outputAssociation(jsa); + TupleUnion *unionStep = new TupleUnion(jsaToUnion, + jsa, + CNX_VTABLE_ID, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, // stepId + jobInfo.statementId, + jobInfo.rm); + unionStep->logger(jobInfo.logger); // get unioned column types for (uint64_t j = 0; j < colCount; ++j) @@ -3736,13 +3370,13 @@ SJSTEP unionQueries(JobStepVector& queries, uint64_t distinctUnionNum, JobInfo& width.push_back(colType.colWidth); } - vector pos; + vector pos; pos.push_back(2); for (uint64_t i = 0; i < oids.size(); ++i) pos.push_back(pos[i] + width[i]); unionStep->setInputRowGroups(inputRGs); unionStep->setDistinctFlags(distinct); - unionStep->setOutputRowGroup(RowGroup(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold)); + unionStep->setOutputRowGroup(RowGroup(oids.size(), pos, oids, keys, types, scale, precision)); // Fix for bug 4388 adjusts the result type at connector side, this workaround is obsolete. // bug 3067, update the returned column types. diff --git a/dbcon/joblist/jlf_tuplejoblist.h b/dbcon/joblist/jlf_tuplejoblist.h index e875a54d..13ff6d5b 100644 --- a/dbcon/joblist/jlf_tuplejoblist.h +++ b/dbcon/joblist/jlf_tuplejoblist.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jlf_tuplejoblist.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: jlf_tuplejoblist.h 8526 2012-05-17 02:28:10Z xlou $ /** @file */ @@ -52,7 +52,7 @@ typedef boost::shared_ptr SP_JoinInfo; // data to construct and config a token hashjoin for string access predicates struct DictionaryScanInfo { - uint32_t fTokenId; // token unique id + uint fTokenId; // token unique id AnyDataListSPtr fDl; // data list rowgroup::RowGroup fRowGroup; // rowgroup meta data for the data list @@ -71,57 +71,31 @@ struct TableInfo uint64_t fSubId; JobStepVector fQuerySteps; JobStepVector fProjectSteps; - JobStepVector fFuncJoinExps; JobStepVector fOneTableExpSteps; - std::vector fProjectCols; - std::vector fColsInExp1; // 1 table expression - std::vector fColsInExp2; // 2 or more tables in expression - std::vector fColsInRetExp; // expression in selection/group by clause - std::vector fColsInOuter; // delayed outer join filter - std::vector fColsInFuncJoin; // expression for function join - std::vector fColsInColMap; // columns in column map - std::vector fJoinKeys; - std::vector fAdjacentList; // tables joined with + std::vector fProjectCols; + std::vector fColsInExp1; // 1 table expression + std::vector fColsInExp2; // 2 or more tables in expression + std::vector fColsInRetExp; // expression in selection/group by clause + std::vector fColsInOuter; // delayed outer join filter + std::vector fColsInColMap; // columns in column map + std::vector fJoinKeys; + std::vector fAdjacentList; // tables joined with bool fVisited; - AnyDataListSPtr fDl; // output data list - rowgroup::RowGroup fRowGroup; // output rowgroup meta data - std::set fJoinedTables; // tables directly/indirectly joined to this table + AnyDataListSPtr fDl; // output data list + rowgroup::RowGroup fRowGroup; // output rowgroup meta data + std::set fJoinedTables; // tables directly/indirectly joined to this table TableInfo() : fTableOid(-1), fVisited(false) {} }; typedef std::map TableInfoMap; - -struct FunctionJoinInfo -{ - std::vector fTableKey; - std::vector fJoinKey; - std::vector fTableOid; - std::vector fOid; - std::vector fSequence; - std::vector fAlias; - std::vector fView; - std::vector fSchema; - JobStepVector fStep; - JoinType fJoinType; - int64_t fJoinId; - int64_t fCorrelatedSide; - std::vector > fColumnKeys; - std::vector fExpression; - - FunctionJoinInfo() : fJoinType(0), fJoinId(0), fCorrelatedSide(0) {} -}; -typedef boost::shared_ptr SP_FuncJoinInfo; -typedef std::pair KeyPair; - - // combine and associate tuple job steps void associateTupleJobSteps(JobStepVector& querySteps, JobStepVector& projectSteps, DeliveredTableMap& deliverySteps, - JobInfo& jobInfo, - const bool overrideLargeSideEstimate); + JobInfo& jobInfo, + const bool overrideLargeSideEstimate); // make BOP_OR an expression step diff --git a/dbcon/joblist/joblist.cpp b/dbcon/joblist/joblist.cpp index 5edba438..37f581be 100644 --- a/dbcon/joblist/joblist.cpp +++ b/dbcon/joblist/joblist.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: joblist.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: joblist.cpp 9227 2013-01-28 22:58:06Z xlou $ #include "errorcodes.h" @@ -25,7 +25,9 @@ #include using namespace std; +#define JOBLIST_DLLEXPORT #include "joblist.h" +#undef JOBLIST_DLLEXPORT #include "calpontsystemcatalog.h" using namespace execplan; @@ -35,14 +37,10 @@ using namespace execplan; #include "primitivestep.h" #include "crossenginestep.h" #include "subquerystep.h" -#include "tupleaggregatestep.h" -#include "tupleannexstep.h" #include "tuplehashjoin.h" #include "tupleunion.h" #include "tupleaggregatestep.h" -#include "windowfunctionstep.h" -#include "atomicops.h" namespace joblist { @@ -62,8 +60,12 @@ JobList::JobList(bool isEM) : fIsExeMgr(isEM), fPmConnected(false), projectingTableOID(0), +#ifdef _MSC_VER fAborted(0), - fPriority(50) +#else + fAborted(false), +#endif + _priority(50) { } @@ -100,7 +102,7 @@ JobList::~JobList() ++iter; } - for (uint32_t i = 0; i < joiners.size(); i++) { + for (uint i = 0; i < joiners.size(); i++) { joiners[i]->join(); delete joiners[i]; } @@ -125,10 +127,10 @@ int JobList::doQuery() JobStep *js; // Set the priority on the jobsteps - for (uint32_t i = 0; i < fQuery.size(); i++) - fQuery[i]->priority(fPriority); - for (uint32_t i = 0; i < fProject.size(); i++) - fProject[i]->priority(fPriority); + for (uint i = 0; i < fQuery.size(); i++) + fQuery[i]->priority(_priority); + for (uint i = 0; i < fProject.size(); i++) + fProject[i]->priority(_priority); // I put this logging in a separate loop rather than including it in the // other loop that calls run(), to insure that these logging msgs would @@ -174,30 +176,43 @@ int JobList::doQuery() JobStepVector::iterator iter = fQuery.begin(); JobStepVector::iterator end = fQuery.end(); - // Start the query running - while (iter != end) - { - js = iter->get(); - if (!js->delayedRun()) + //try + //{ + // Start the query running + while (iter != end) { - js->run(); + js = iter->get(); + if (!js->delayedRun()) + { + js->run(); + } + ++iter; } - ++iter; - } - iter = fProject.begin(); - end = fProject.end(); + iter = fProject.begin(); + end = fProject.end(); - // Fire up the projection steps - while (iter != end) - { - if (!iter->get()->delayedRun()) + // Fire up the projection steps + while (iter != end) { - iter->get()->run(); + if (!iter->get()->delayedRun()) + { + iter->get()->run(); + } + ++iter; } - ++iter; + //} + /* + catch (exception& ex) + { + cerr << "JobList::doQuery: exception caught: " << ex.what() << endl; + return -1; } - + catch (...) + { + cerr << "JobList::doQuery: exception caught!" << endl; + return -1; + } */ fIsRunning = true; rc = 0; return rc; @@ -230,11 +245,37 @@ int JobList::putEngineComm(DistributedEngineComm* dec) { SJSTEP sjstep = *iter; JobStep* jsp = sjstep.get(); +// if (typeid(*jsp) == typeid(pColScanStep)) +// { +// pColScanStep* step = dynamic_cast(jsp); +// step->dec(dec); +// } +// else if (typeid(*jsp) == typeid(pColStep)) +// { +// pColStep* step = dynamic_cast(jsp); +// step->dec(dec); +// } +// else if (typeid(*jsp) == typeid(pDictionaryScan)) if (typeid(*jsp) == typeid(pDictionaryScan)) { pDictionaryScan* step = dynamic_cast(jsp); step->dec(dec); } +// else if (typeid(*jsp) == typeid(pDictionaryStep)) +// { +// pDictionaryStep* step = dynamic_cast(jsp); +// step->dec(dec); +// } +// else if (typeid(*jsp) == typeid(pIdxWalk)) +// { +// pIdxWalk* step = dynamic_cast(jsp); +// step->dec(dec); +// } +// else if (typeid(*jsp) == typeid(pIdxList)) +// { +// pIdxList* step = dynamic_cast(jsp); +// step->dec(dec); +// } else if (typeid(*jsp) == typeid(TupleBPS)) { BatchPrimitive* step = dynamic_cast(jsp); @@ -251,6 +292,17 @@ int JobList::putEngineComm(DistributedEngineComm* dec) { SJSTEP sjstep = *iter; JobStep* jsp = sjstep.get(); +// if (typeid(*jsp) == typeid(pColStep)) +// { +// pColStep* step = dynamic_cast(jsp); +// step->dec(dec); +// } +// else if (typeid(*jsp) == typeid(pDictionaryStep)) +// { +// pDictionaryStep* step = dynamic_cast(jsp); +// step->dec(dec); +// } +// else if (typeid(*jsp) == typeid(TupleBPS)) if (typeid(*jsp) == typeid(TupleBPS)) { BatchPrimitive* step = dynamic_cast(jsp); @@ -265,9 +317,9 @@ int JobList::putEngineComm(DistributedEngineComm* dec) // -- TupleJobList /* returns row count */ -uint32_t TupleJobList::projectTable(CalpontSystemCatalog::OID, messageqcpp::ByteStream& bs) +uint TupleJobList::projectTable(CalpontSystemCatalog::OID, messageqcpp::ByteStream& bs) { - uint32_t ret = ds->nextBand(bs); + uint ret = ds->nextBand(bs); moreData = (ret != 0); return ret; } @@ -292,7 +344,7 @@ void TupleJobList::setDeliveryFlag(bool f) SJSTEP dstep = iter->second; ds = dynamic_cast(dstep.get()); if (ds) // if not dummy step - dstep->delivery(f); + ds->setIsDelivery(f); } //------------------------------------------------------------------------------ @@ -355,6 +407,86 @@ void JobList::querySummary(bool extendedStats) else if (typeid(*js) == typeid(TupleBPS)) skipCnt = (dynamic_cast(js))->blksSkipped (); fStats.fCPBlocksSkipped += skipCnt; +#if 0 + cout << "qstep-" << js->stepId() << + "; adding phy, cache, msg, blkSkip, msgBytesIn, msgBytesOut: "<< + js->phyIOCount() << ", " << + js->cacheIOCount() << ", " << + js->msgsRcvdCount() << ", " << + skipCnt << ", " << + js->msgBytesIn() << ", " << + js->msgBytesOut() << endl; +#endif +// // +// //...Iterate through the output job step associations; adding up the +// //...temp file counts and sizes for the ZDL and Bucket datalists. +// // +// for (unsigned int i = 0; +// i < js->outputAssociation().outSize(); +// i++) +// { +// uint64_t nFiles = 0; +// uint64_t nBytes = 0; +// +// ZonedDL* pZdl = 0; +// StringZonedDL* pStrZdl = 0; +// BucketDataList* pBdl = 0; +// StringBucketDataList* pStrBdl = 0; +// FifoDataList* pFdl = 0; +// DeliveryWSDL* pDWSDL = 0; +// bool updateTotals = false; +// //string dlType; +// +// const AnyDataListSPtr& pDl = +// js->outputAssociation().outAt(i); +// if ((pZdl = pDl->zonedDL()) != 0) +// { +// pZdl->totalFileCounts(nFiles, nBytes); +// updateTotals = true; +// //dlType = "zdl"; +// } +// else if ((pStrZdl = pDl->stringZonedDL()) != 0) +// { +// pStrZdl->totalFileCounts(nFiles, nBytes); +// updateTotals = true; +// //dlType = "strZdl"; +// } +// else if ((pBdl = pDl->bucketDL()) != 0) +// { +// pBdl->totalFileCounts(nFiles, nBytes); +// updateTotals = true; +// //dlType = "bucketdl"; +// } +// else if ((pStrBdl = pDl->stringBucketDL()) != 0) +// { +// pStrBdl->totalFileCounts(nFiles, nBytes); +// updateTotals = true; +// //dlType = "strBucketdl"; +// } +// else if ((pFdl = pDl->fifoDL()) != 0) +// { +// pFdl->totalFileCounts(nFiles, nBytes); +// updateTotals = true; +// //dlType = "fifo"; +// } +// else if ((pDWSDL = pDl->deliveryWSDL()) != 0) +// { +// pDWSDL->totalFileCounts(nFiles, nBytes); +// updateTotals = true; +// //dlType = "deliveryWSDL"; +// } +// +// if ( updateTotals ) +// { +//#if 0 +// cout << "jobstep : " << js->stepId() << " qstep outlist " << i << " is type " << dlType << +// ": files-" << nFiles << +// "; bytes-" << nBytes << endl; +//#endif +// fStats.fNumFiles += nFiles; +// fStats.fFileBytes+= nBytes; +// } +// } if (extendedStats) { @@ -405,6 +537,16 @@ void JobList::querySummary(bool extendedStats) else if (typeid(*js) == typeid(TupleBPS)) skipCnt = (dynamic_cast(js))->blksSkipped (); fStats.fCPBlocksSkipped += skipCnt; +#if 0 + cout << "pstep-" << js->stepId() << + "; adding phy, cache, msg, blkSkip, msgBytesIn, msgBytesOut: "<< + js->phyIOCount() << ", " << + js->cacheIOCount() << ", " << + js->msgsRcvdCount() << ", " << + skipCnt << ", " << + js->msgBytesIn() << ", " << + js->msgBytesOut() << endl; +#endif ++pIter; } @@ -475,6 +617,7 @@ void JobList::graph(uint32_t sessionID) uint64_t outSize = 0; uint64_t msgs = 0; uint64_t pio = 0; + uint64_t cio = 0; int ctn = 0; bool diskIo = false; uint64_t saveTime = 0; @@ -514,8 +657,7 @@ void JobList::graph(uint32_t sessionID) uint16_t stepidIn = qsi->get()->stepId(); dotFile << stepidIn << " [label=\"st_" << stepidIn << " "; - // @Bug 1033. colName was being called for dictionary steps that don't have column names. - // Added if condition below. + // @Bug 1033. colName was being called for dictionary steps that don't have column names. Added if condition below. if ( typeid(*(qsi->get())) == typeid(pColScanStep) || typeid(*(qsi->get())) == typeid(pColStep)) tcn = csc->colName(qsi->get()->oid()); @@ -555,8 +697,7 @@ void JobList::graph(uint32_t sessionID) tcn.table = qsi->get()->alias(); } - dotFile << JSTimeStamp::tsdiffstr(qsi->get()->dlTimes.EndOfInputTime(), - qsi->get()->dlTimes.FirstReadTime()) << "s"; + dotFile << JSTimeStamp::tsdiffstr(qsi->get()->dlTimes.EndOfInputTime(), qsi->get()->dlTimes.FirstReadTime()) << "s"; dotFile << ")"; @@ -590,18 +731,35 @@ void JobList::graph(uint32_t sessionID) { dotFile << "\"" << " shape=box style=dashed"; } - else if (typeid(*(qsi->get())) == typeid(TupleAggregateStep)) - { - dotFile << "\"" << " shape=triangle orientation=180"; - } - else if (typeid(*(qsi->get())) == typeid(TupleAnnexStep)) - { - dotFile << "\"" << " shape=star"; - } - else if (typeid(*(qsi->get())) == typeid(WindowFunctionStep)) - { - dotFile << "\"" << " shape=triangle orientation=180 peripheries=2"; - } +// else if (typeid(*(qsi->get())) == typeid(HashJoinStep) || +// typeid(*(qsi->get())) == typeid(StringHashJoinStep)) +// { +// if (typeid(*(qsi->get())) == typeid(HashJoinStep)) +// { +// hjs = static_cast(qsi->get()); +// dotFile << "\\; rm: " << hjs->getUmMemoryTime() ; +// switch (hjs->hashJoinMode()) +// { +// case HashJoinStep::PM_MEMORY: +// dotFile << "\"" << " shape=diamond style=dashed"; +// break; +// case HashJoinStep::LARGE_HASHJOIN_CARD: +// dotFile << "\"" << " shape=diamond style=solid peripheries=2"; +// break; +// case HashJoinStep::LARGE_HASHJOIN_RUNTIME: +// dotFile << "\"" << " shape=diamond style=solid peripheries=3"; +// break; +// case HashJoinStep::UM_MEMORY: +// default: +// dotFile << "\"" << " shape=diamond style=solid"; +// break; +// } +// } +// else +// { +// dotFile << "\"" << " shape=diamond"; +// } +// } else if (typeid(*(qsi->get())) == typeid(TupleHashJoinStep)) { dotFile << "\""; @@ -615,6 +773,10 @@ void JobList::graph(uint32_t sessionID) { dotFile << "\"" << " shape=trapezium"; } +// else if (typeid(*(qsi->get())) == typeid(ReduceStep)) +// { +// dotFile << "\"" << " shape=triangle orientation=180"; +// } else if (typeid(*(qsi->get())) == typeid(FilterStep)) { dotFile << "\"" << " shape=house orientation=180"; @@ -629,6 +791,15 @@ void JobList::graph(uint32_t sessionID) dotFile << "\"" << " shape=box style=bold"; dotFile << " peripheries=2"; } +// else if (typeid(*(qsi->get())) == typeid(AggregateFilterStep)) +// { +// dotFile << "\"" << " shape=hexagon peripheries=2 style=bold"; +// } +// else if (typeid(*(qsi->get())) == typeid(BucketReuseStep)) +// { +// dotFile << "\"" << " shape=box style=dashed"; +// +// } else dotFile << "\""; dotFile << "]" << endl; @@ -636,6 +807,7 @@ void JobList::graph(uint32_t sessionID) // msgsRecived, physicalIO, cacheIO msgs = qsi->get()->msgsRcvdCount(); pio = qsi->get()->phyIOCount(); + cio = qsi->get()->cacheIOCount(); for (unsigned int i = 0; i < qsi->get()->outputAssociation().outSize(); i++) { @@ -656,9 +828,20 @@ void JobList::graph(uint32_t sessionID) outSize = sdl->totalSize(); diskIo = sdl->totalDiskIoTime(saveTime, loadTime); } +// else if ((tdl = qsi->get()->outputAssociation().outAt(i)->tupleDataList())) +// { +// dloutptr = (ptrdiff_t)tdl; +// outSize = tdl->totalSize(); +// diskIo = tdl->totalDiskIoTime(saveTime, loadTime); +// } // if HashJoinStep, determine if output fifo was cached to disk bool hjTempDiskFlag = false; +// if (hjs) +// { +// hjTempDiskFlag = hjs->didOutputAssocUseDisk(i); +// } + for (unsigned int k = 0; k < querySteps.size(); k++) { uint16_t stepidOut = querySteps[k].get()->stepId(); @@ -668,6 +851,7 @@ void JobList::graph(uint32_t sessionID) ptrdiff_t dlinptr = 0; DataList_t *dlin = queryInputSA.outAt(j)->dataList(); StrDataList* sdl = 0; +// TupleDataList* tdl = 0; if (dlin) dlinptr = (ptrdiff_t)dlin; @@ -675,6 +859,8 @@ void JobList::graph(uint32_t sessionID) { dlinptr = (ptrdiff_t)sdl; } +// else if ((tdl = queryInputSA.outAt(j)->tupleDataList())) +// dlinptr = (ptrdiff_t)tdl; if (dloutptr == dlinptr) { @@ -854,6 +1040,14 @@ void JobList::graph(uint32_t sessionID) if (typeid(*(psi->get())) == typeid(TupleBPS)) dotFile << " peripheries=2"; } +// else if (typeid(*(psi->get())) == typeid(HashJoinStep)) +// { +// dotFile << "\"" << " shape=diamond"; +// } +// else if (typeid(*(psi->get())) == typeid(UnionStep)) +// { +// dotFile << "\"" << " shape=triangle"; +// } else if (typeid(*(psi->get())) == typeid(pDictionaryStep)) { dotFile << "\"" << " shape=trapezium"; @@ -862,6 +1056,10 @@ void JobList::graph(uint32_t sessionID) { dotFile << "\"" << " shape=octagon"; } +// else if (typeid(*(psi->get())) == typeid(ReduceStep)) +// { +// dotFile << "\"" << " shape=triangle orientation=180"; +// } else if (typeid(*(psi->get())) == typeid(FilterStep)) { dotFile << "\"" << " shape=house orientation=180"; @@ -873,6 +1071,7 @@ void JobList::graph(uint32_t sessionID) // msgsRecived, physicalIO, cacheIO msgs = psi->get()->msgsRcvdCount(); pio = psi->get()->phyIOCount(); + cio = psi->get()->cacheIOCount(); CalpontSystemCatalog::OID tableOIDProject = 0; if (bps) @@ -908,7 +1107,7 @@ void JobList::graph(uint32_t sessionID) void JobList::validate() const { -// uint32_t i; +// uint i; // DeliveredTableMap::const_iterator it; /* Make sure there's at least one query step and that they're the right type */ @@ -931,19 +1130,22 @@ void JobList::validate() const // // /* Check that all JobSteps use the right status pointer */ // for (i = 0; i < fQuery.size(); i++) { -// idbassert(fQuery[i]->errorInfo().get() == errorInfo().get()); +// idbassert(fQuery[i]->inputAssociation().statusPtr().get() == statusPtr().get()); +// idbassert(fQuery[i]->outputAssociation().statusPtr().get() == statusPtr().get()); // } // for (i = 0; i < fProject.size(); i++) { -// idbassert(fProject[i]->errorInfo().get() == errorInfo().get()); +// idbassert(fProject[i]->inputAssociation().statusPtr().get() == statusPtr().get()); +// idbassert(fProject[i]->outputAssociation().statusPtr().get() == statusPtr().get()); // } // for (it = fDeliveredTables.begin(); it != fDeliveredTables.end(); ++it) { -// idbassert(it->second->errorInfo().get() == errorInfo().get()); +// idbassert(it->second->inputAssociation().statusPtr().get() == statusPtr().get()); +// idbassert(it->second->outputAssociation().statusPtr().get() == statusPtr().get()); // } } void TupleJobList::validate() const { - uint32_t i, j; + uint i, j; DeliveredTableMap::const_iterator it; idbassert(fQuery.size() > 0); @@ -970,21 +1172,32 @@ void TupleJobList::validate() const idbassert(dynamic_cast(fDeliveredTables.begin()->second.get())); /* Check that all JobSteps use the right status pointer */ - for (i = 0; i < fQuery.size(); i++) - idbassert(fQuery[i]->errorInfo().get() == errorInfo().get()); - - for (i = 0; i < fProject.size(); i++) - idbassert(fProject[i]->errorInfo().get() == errorInfo().get()); - - for (it = fDeliveredTables.begin(); it != fDeliveredTables.end(); ++it) - idbassert(it->second->errorInfo().get() == errorInfo().get()); + for (i = 0; i < fQuery.size(); i++) { + idbassert(fQuery[i]->inputAssociation().statusPtr().get() == statusPtr().get()); + idbassert(fQuery[i]->outputAssociation().statusPtr().get() == statusPtr().get()); + } + for (i = 0; i < fProject.size(); i++) { + idbassert(fProject[i]->inputAssociation().statusPtr().get() == statusPtr().get()); + idbassert(fProject[i]->outputAssociation().statusPtr().get() == statusPtr().get()); + } + for (it = fDeliveredTables.begin(); it != fDeliveredTables.end(); ++it) { + idbassert(it->second->inputAssociation().statusPtr().get() == statusPtr().get()); + idbassert(it->second->outputAssociation().statusPtr().get() == statusPtr().get()); + } } void JobList::abort() { - uint32_t i; - //If we're not currently aborting, then start aborting... - if (atomicops::atomicCAS(&fAborted, 0, 1)) { + uint i; +#ifdef _MSC_VER + //If the current value of fAborted is 0 then set it to 1 and return the initial value + // of fAborted (which will be 0), else do nothing and return fAborted (which will be 1) + if (InterlockedCompareExchange(&fAborted, 1, 0) == 0) { +#else + //If the current value of fAborted is false then set it to true and return true, else + // do not change fAborted and return false + if (__sync_bool_compare_and_swap(&fAborted, false, true)) { +#endif for (i = 0; i < fQuery.size(); i++) fQuery[i]->abort(); for (i = 0; i < fProject.size(); i++) @@ -994,10 +1207,16 @@ void JobList::abort() void JobList::abortOnLimit(JobStep* js) { - //If we're not currently aborting, then start aborting... - if (atomicops::atomicCAS(&fAborted, 0, 1)) { - // @bug4848, enhance and unify limit handling. - for (uint32_t i = 0; i < fQuery.size(); i++) { +#ifdef _MSC_VER + //If the current value of fAborted is 0 then set it to 1 and return the initial value + // of fAborted (which will be 0), else do nothing and return fAborted (which will be 1) + if (InterlockedCompareExchange(&fAborted, 1, 0) == 0) { +#else + //If the current value of fAborted is false then set it to true and return true, else + // do not change fAborted and return false + if (__sync_bool_compare_and_swap(&fAborted, false, true)) { +#endif + for (uint i = 0; i < fQuery.size(); i++) { if (fQuery[i].get() == js) break; @@ -1008,7 +1227,7 @@ void JobList::abortOnLimit(JobStep* js) string JobList::toString() const { - uint32_t i; + uint i; string ret; ret = "Filter Steps:\n"; @@ -1025,14 +1244,18 @@ TupleJobList::TupleJobList(bool isEM) : JobList(isEM), ds(NULL), moreData(true) { } -TupleJobList::~TupleJobList() -{ +TupleJobList::~TupleJobList() +{ abort(); } void TupleJobList::abort() { +#ifdef _MSC_VER if (fAborted == 0 && fIsRunning) { +#else + if (!fAborted && fIsRunning) { +#endif JobList::abort(); messageqcpp::ByteStream bs; if (ds && moreData) @@ -1040,6 +1263,10 @@ void TupleJobList::abort() } } +void init_mysqlcl_idb() +{ + CrossEngineStep::init_mysqlcl_idb(); +} } diff --git a/dbcon/joblist/joblist.h b/dbcon/joblist/joblist.h index 73cfa0c4..a1747501 100644 --- a/dbcon/joblist/joblist.h +++ b/dbcon/joblist/joblist.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: joblist.h 9623 2013-06-13 19:56:23Z rdempsey $ +// $Id: joblist.h 9227 2013-01-28 22:58:06Z xlou $ /** @file */ @@ -68,7 +68,7 @@ class JobList virtual int doQuery(); /* returns row count */ - virtual uint32_t projectTable(execplan::CalpontSystemCatalog::OID, messageqcpp::ByteStream&) = 0; + virtual uint projectTable(execplan::CalpontSystemCatalog::OID, messageqcpp::ByteStream&) = 0; virtual int putEngineComm(DistributedEngineComm*); virtual void addQuery(const JobStepVector& query) { fQuery = query; } @@ -79,8 +79,8 @@ class JobList virtual void querySummary(bool extendedStats); virtual void graph(uint32_t sessionID); - virtual const SErrorInfo& errorInfo() const { return errInfo; } - virtual void errorInfo(SErrorInfo sp) { errInfo = sp; } + virtual const SErrorInfo& statusPtr() const { return errInfo; } + virtual void statusPtr(SErrorInfo sp) { errInfo = sp; } virtual const uint32_t status() const { return errInfo->errCode; } virtual void status(uint32_t ec) { errInfo->errCode = ec; } @@ -113,12 +113,16 @@ class JobList */ EXPORT virtual void abort(); EXPORT virtual bool aborted() - { return (fAborted != 0); } +#ifdef _MSC_VER + { return (fAborted != 0); } +#else + { return fAborted; } +#endif std::string toString() const; - void priority(uint32_t p) { fPriority = p; } - uint32_t priority() { return fPriority; } + void priority(uint p) { _priority = p; } + uint priority() { return _priority; } // @bug4848, enhance and unify limit handling. EXPORT virtual void abortOnLimit(JobStep* js); @@ -143,9 +147,13 @@ class JobList std::string fMiniInfo; std::vector subqueryJoblists; - volatile uint32_t fAborted; +#ifdef _MSC_VER + volatile LONG fAborted; +#else + volatile bool fAborted; +#endif - uint32_t fPriority; //higher #s = higher priority + uint _priority; //higher #s = higher priority }; class TupleJobList : public JobList @@ -154,7 +162,7 @@ class TupleJobList : public JobList TupleJobList(bool isEM=false); virtual ~TupleJobList(); - EXPORT uint32_t projectTable(execplan::CalpontSystemCatalog::OID, messageqcpp::ByteStream&); + EXPORT uint projectTable(execplan::CalpontSystemCatalog::OID, messageqcpp::ByteStream&); EXPORT const rowgroup::RowGroup& getOutputRowGroup() const; TupleDeliveryStep* getDeliveryStep() { return ds; } const JobStepVector& querySteps() const { return fQuery; } @@ -180,6 +188,8 @@ class TupleJobList : public JobList typedef boost::shared_ptr STJLP; +EXPORT void init_mysqlcl_idb(); + } #undef EXPORT diff --git a/dbcon/joblist/joblistfactory.cpp b/dbcon/joblist/joblistfactory.cpp index 125aec6a..7bc36fa8 100644 --- a/dbcon/joblist/joblistfactory.cpp +++ b/dbcon/joblist/joblistfactory.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: joblistfactory.cpp 9632 2013-06-18 22:18:20Z xlou $ +// $Id: joblistfactory.cpp 9324 2013-03-21 21:30:23Z zzhu $ #include @@ -32,14 +32,14 @@ using namespace std; #include #include -#include using namespace boost; +#define JOBLISTFACTORY_DLLEXPORT #include "joblistfactory.h" +#undef JOBLISTFACTORY_DLLEXPORT #include "calpontexecutionplan.h" #include "calpontselectexecutionplan.h" -#include "calpontsystemcatalog.h" #include "dbrm.h" #include "filter.h" #include "simplefilter.h" @@ -48,15 +48,14 @@ using namespace boost; #include "selectfilter.h" #include "returnedcolumn.h" #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" +#include "groupconcatcolumn.h" #include "arithmeticcolumn.h" #include "constantcolumn.h" #include "functioncolumn.h" -#include "groupconcatcolumn.h" -#include "pseudocolumn.h" #include "simplecolumn.h" #include "rowcolumn.h" #include "treenodeimpl.h" +#include "calpontsystemcatalog.h" using namespace execplan; #include "configcpp.h" @@ -77,7 +76,6 @@ using namespace logging; #include "expressionstep.h" #include "tupleconstantstep.h" #include "tuplehavingstep.h" -#include "windowfunctionstep.h" #include "jlf_common.h" #include "jlf_graphics.h" @@ -128,10 +126,6 @@ bool checkCombinable(JobStep* jobStepPtr) { return true; } - else if (typeid(*(jobStepPtr)) == typeid(PseudoColStep)) - { - return true; - } else if (typeid(*(jobStepPtr)) == typeid(pColStep)) { return true; @@ -152,6 +146,44 @@ bool checkCombinable(JobStep* jobStepPtr) return false; } +//------------------------------------------------------------------------------ +// Get the necessary RID size for a column OID based on the current HWM +// for that column. Possible return values are 8 bytes or 4 bytes. +//------------------------------------------------------------------------------ +uint32_t getRidSizeBasedOnHwm( + BRM::DBRM& dbrm, + const execplan::CalpontSystemCatalog::OID& colOid, + int colWidth) +{ + uint32_t sizeOfRid = 8; // default to 8 bytes + + //...Get HWM for the specified column OID + BRM::HWM_t hwm; + int err = dbrm.getHWM(colOid, hwm); + if (err != 0) + { + std::ostringstream errmsg; + errmsg << "Error getting HWM for column OID " << colOid << "; " << err; + throw std::runtime_error(errmsg.str()); + } + + //...Calculate highest RID, to see if it can be held within a 4 byte + // unsigned integer. For example... + // For an 8 byte column, hwm<=4194302 yields RID that fits in uint32_t. + // hwm>=4194303 yields RID that requires uint64_t. + double d_hwm = hwm; + double d_blksize = BLOCK_SIZE; + double d_colwid = colWidth; + double d_highestRID = ((d_hwm + 1.0) * d_blksize) / d_colwid; + uint64_t highestRID = (uint64_t)d_highestRID; + + if (highestRID <= numeric_limits::max()) + sizeOfRid = 4; + + return sizeOfRid; +} + + void projectSimpleColumn(const SimpleColumn* sc, JobStepVector& jsv, JobInfo& jobInfo) { if (sc == NULL) @@ -179,17 +211,27 @@ void projectSimpleColumn(const SimpleColumn* sc, JobStepVector& jsv, JobInfo& jo // if (jobInfo.trace) // cout << "doProject Emit pCol for SimpleColumn " << oid << endl; - const PseudoColumn* pc = dynamic_cast(sc); ct = sc->colType(); //XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (sc->isInfiniDB() && !pc) + if (sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X - if (pc == NULL) - pcs = new pColStep(oid, tbl_oid, ct, jobInfo); - else - pcs = new PseudoColStep(oid, tbl_oid, pc->pseudoType(), ct, jobInfo); + pcs = new pColStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + 0, + jobInfo.csc, + oid, + tbl_oid, + ct, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm, + jobInfo.flushInterval, + jobInfo.isExeMgr); + pcs->logger(jobInfo.logger); pcs->alias(alias); pcs->view(view); pcs->name(sc->columnName()); @@ -205,7 +247,7 @@ void projectSimpleColumn(const SimpleColumn* sc, JobStepVector& jsv, JobInfo& jo if (dictOid > 0 && jobInfo.hasAggregation) { - map::iterator it = + map::iterator it = jobInfo.tokenOnly.find(getTupleKey(jobInfo, sc)); if (it != jobInfo.tokenOnly.end()) tokenOnly = it->second; @@ -217,7 +259,21 @@ void projectSimpleColumn(const SimpleColumn* sc, JobStepVector& jsv, JobInfo& jo // if (jobInfo.trace) // cout << "doProject Emit pGetSignature for SimpleColumn " << dictOid << endl; - pds = new pDictionaryStep(dictOid, tbl_oid, ct, jobInfo); + pds = new pDictionaryStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + 0, + jobInfo.csc, + dictOid, + ct.ddn.compressionType, + tbl_oid, + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + 0, + jobInfo.statementId, + jobInfo.rm, + jobInfo.flushInterval); + pds->logger(jobInfo.logger); jobInfo.keyInfo->dictOidToColOid[dictOid] = oid; pds->alias(alias); pds->view(view); @@ -226,7 +282,7 @@ void projectSimpleColumn(const SimpleColumn* sc, JobStepVector& jsv, JobInfo& jo //pds->setOrderRids(true); //Associate these two linked steps - JobStepAssociation outJs; + JobStepAssociation outJs(jobInfo.status); AnyDataListSPtr spdl1(new AnyDataList()); RowGroupDL* dl1 = new RowGroupDL(1, jobInfo.fifoSize); spdl1->rowGroupDL(dl1); @@ -252,7 +308,7 @@ void projectSimpleColumn(const SimpleColumn* sc, JobStepVector& jsv, JobInfo& jo else // must be vtable mode { oid = (tbl_oid+1) + sc->colPosition(); - ct = jobInfo.vtableColTypes[UniqId(oid, alias, "", "")]; + ct = jobInfo.vtableColTypes[UniqId(oid, sc)]; ti = setTupleInfo(ct, oid, jobInfo, tbl_oid, sc, alias); } @@ -274,26 +330,21 @@ const JobStepVector doProject(const RetColsVector& retCols, JobInfo& jobInfo) for (unsigned i = 0; i < retCols.size(); i++) { const SimpleColumn* sc = dynamic_cast(retCols[i].get()); - const WindowFunctionColumn* wc = NULL; if (sc != NULL) { projectSimpleColumn(sc, jsv, jobInfo); } - else if ((wc = dynamic_cast(retCols[i].get())) != NULL) - { - //put place hold column in projection list - uint64_t eid = wc->expressionId(); - CalpontSystemCatalog::ColType ct = wc->resultType(); - TupleInfo ti(setExpTupleInfo(ct, eid, retCols[i].get()->alias(), jobInfo)); - jobInfo.pjColList.push_back(ti); - } else { const ArithmeticColumn* ac = NULL; const FunctionColumn* fc = NULL; uint64_t eid = -1; CalpontSystemCatalog::ColType ct; - ExpressionStep* es = new ExpressionStep(jobInfo); + ExpressionStep* es = new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + es->logger(jobInfo.logger); es->expression(retCols[i], jobInfo); sjstep.reset(es); @@ -317,11 +368,9 @@ const JobStepVector doProject(const RetColsVector& retCols, JobInfo& jobInfo) // set expression tuple Info TupleInfo ti(setExpTupleInfo(ct, eid, retCols[i].get()->alias(), jobInfo)); - uint32_t key = ti.key; + uint key = ti.key; - if (retCols[i]->windowfunctionColumnList().size() > 0) - jobInfo.expressionVec.push_back(key); - else if (find(jobInfo.expressionVec.begin(), jobInfo.expressionVec.end(), key) == + if (find(jobInfo.expressionVec.begin(), jobInfo.expressionVec.end(), key) == jobInfo.expressionVec.end()) jobInfo.returnedExpressions.push_back(sjstep); @@ -335,7 +384,11 @@ const JobStepVector doProject(const RetColsVector& retCols, JobInfo& jobInfo) void checkHavingClause(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) { - TupleHavingStep* ths = new TupleHavingStep(jobInfo); + TupleHavingStep* ths = new TupleHavingStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); + ths->logger(jobInfo.logger); ths->expressionFilter(csep->having(), jobInfo); jobInfo.havingStep.reset(ths); @@ -366,7 +419,7 @@ void checkHavingClause(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) { if (sc->schemaName().empty() && sc->oid() == 0) { - if (sc->colPosition() == -1) + if (sc->colPosition() == (uint64_t) -1) { // from select subquery SRCP ss = csep->returnedCols()[sc->orderPos()]; @@ -543,11 +596,6 @@ void checkGroupByCols(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) { if (orderByCols[i]->orderPos() == (uint64_t)(-1)) { - // @bug 4531, skip window functions, should be already added. - if (dynamic_cast(orderByCols[i].get()) != NULL || - orderByCols[i]->windowfunctionColumnList().size() > 0) - continue; - jobInfo.deliveredCols.push_back(orderByCols[i]); // @bug 3025 @@ -575,13 +623,16 @@ void checkGroupByCols(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) if (dynamic_cast(i->get()) != NULL) continue; + if ((*i)->orderPos() == (uint64_t) -1) + jobInfo.hasImplicitGroupBy = true; + ReturnedColumn *rc = i->get(); SimpleColumn* sc = dynamic_cast(rc); bool selectSubquery = false; if (sc && sc->schemaName().empty() && sc->oid() == 0) { - if (sc->colPosition() == -1) + if (sc->colPosition() == (uint64_t) -1) { // from select subquery // sc->orderPos() should NOT be -1 because it is a SELECT sub-query. @@ -647,17 +698,17 @@ void checkAggregation(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) } } -void updateAggregateColType(AggregateColumn* ac, const SRCP& srcp, int op, JobInfo& jobInfo) +void updateAggregateColType(AggregateColumn* ac, const SRCP* srcp, int op, JobInfo& jobInfo) { CalpontSystemCatalog::ColType ct; - const SimpleColumn* sc = dynamic_cast(srcp.get()); + const SimpleColumn* sc = dynamic_cast(srcp->get()); const ArithmeticColumn* ar = NULL; const FunctionColumn* fc = NULL; if (sc != NULL) ct = sc->resultType(); - else if ((ar = dynamic_cast(srcp.get())) != NULL) + else if ((ar = dynamic_cast(srcp->get())) != NULL) ct = ar->resultType(); - else if ((fc = dynamic_cast(srcp.get())) != NULL) + else if ((fc = dynamic_cast(srcp->get())) != NULL) ct = fc->resultType(); if (op == AggregateColumn::SUM || op == AggregateColumn::DISTINCT_SUM) @@ -667,8 +718,7 @@ void updateAggregateColType(AggregateColumn* ac, const SRCP& srcp, int op, JobIn ct.colDataType == CalpontSystemCatalog::MEDINT || ct.colDataType == CalpontSystemCatalog::INT || ct.colDataType == CalpontSystemCatalog::BIGINT || - ct.colDataType == CalpontSystemCatalog::DECIMAL || - ct.colDataType == CalpontSystemCatalog::UDECIMAL) + ct.colDataType == CalpontSystemCatalog::DECIMAL) { ct.colWidth = sizeof(int64_t); if (ct.scale != 0) @@ -677,16 +727,6 @@ void updateAggregateColType(AggregateColumn* ac, const SRCP& srcp, int op, JobIn ct.colDataType = CalpontSystemCatalog::BIGINT; ct.precision = 19; } - if (ct.colDataType == CalpontSystemCatalog::UTINYINT || - ct.colDataType == CalpontSystemCatalog::USMALLINT || - ct.colDataType == CalpontSystemCatalog::UMEDINT || - ct.colDataType == CalpontSystemCatalog::UINT || - ct.colDataType == CalpontSystemCatalog::UBIGINT) - { - ct.colWidth = sizeof(uint64_t); - ct.colDataType = CalpontSystemCatalog::UBIGINT; - ct.precision = 20; - } } else if (op == AggregateColumn::STDDEV_POP || op == AggregateColumn::STDDEV_SAMP || op == AggregateColumn::VAR_POP || op == AggregateColumn::VAR_SAMP) @@ -714,7 +754,7 @@ void updateAggregateColType(AggregateColumn* ac, const SRCP& srcp, int op, JobIn const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) { - vector projectKeys; // projected column keys -- unique + map projectColMap; // projected column map -- unique RetColsVector pcv; // projected column vector -- may have duplicates // add the groupby cols in the front part of the project column vector (pcv) @@ -734,13 +774,11 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo CalpontSystemCatalog::OID tblOid = tableOid(sc, jobInfo.csc); CalpontSystemCatalog::OID dictOid = 0; CalpontSystemCatalog::ColType ct; - string alias(extractTableAlias(sc)); - string view(sc->viewName()); if (!sc->schemaName().empty()) { ct = sc->colType(); //XXX use this before connector sets colType in sc correctly. - if (sc->isInfiniDB() && dynamic_cast(sc) == NULL) + if (sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X dictOid = isDictCol(ct); @@ -748,17 +786,19 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo else { gbOid = (tblOid+1) + sc->colPosition(); - ct = jobInfo.vtableColTypes[UniqId(gbOid, alias, "", "")]; + ct = jobInfo.vtableColTypes[UniqId(gbOid, sc)]; } // As of bug3695, make sure varbinary is not used in group by. if (ct.colDataType == CalpontSystemCatalog::VARBINARY) throw runtime_error ("VARBINARY in group by is not supported."); + string alias(extractTableAlias(sc)); + string view(sc->viewName()); TupleInfo ti(setTupleInfo(ct, gbOid, jobInfo, tblOid, sc, alias)); - uint32_t tupleKey = ti.key; - if (find(projectKeys.begin(), projectKeys.end(), tupleKey) == projectKeys.end()) - projectKeys.push_back(tupleKey); + uint tupleKey = ti.key; + if (projectColMap.find(tupleKey) == projectColMap.end()) + projectColMap[tupleKey] = i; // for dictionary columns, replace the token oid with string oid if (dictOid > 0) @@ -775,41 +815,40 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo uint64_t eid = ac->expressionId(); CalpontSystemCatalog::ColType ct = ac->resultType(); TupleInfo ti(setExpTupleInfo(ct, eid, ac->alias(), jobInfo)); - uint32_t tupleKey = ti.key; + uint tupleKey = ti.key; jobInfo.groupByColVec.push_back(tupleKey); - if (find(projectKeys.begin(), projectKeys.end(), tupleKey) == projectKeys.end()) - projectKeys.push_back(tupleKey); + if (projectColMap.find(tupleKey) == projectColMap.end()) + projectColMap[tupleKey] = i; } else if ((fc = dynamic_cast(groupByCols[i].get())) != NULL) { uint64_t eid = fc->expressionId(); CalpontSystemCatalog::ColType ct = fc->resultType(); TupleInfo ti(setExpTupleInfo(ct, eid, fc->alias(), jobInfo)); - uint32_t tupleKey = ti.key; + uint tupleKey = ti.key; jobInfo.groupByColVec.push_back(tupleKey); - if (find(projectKeys.begin(), projectKeys.end(), tupleKey) == projectKeys.end()) - projectKeys.push_back(tupleKey); + if (projectColMap.find(tupleKey) == projectColMap.end()) + projectColMap[tupleKey] = i; } else { std::ostringstream errmsg; - errmsg << "doAggProject: unsupported group by column: " - << typeid(*groupByCols[i]).name(); - cerr << boldStart << errmsg.str() << boldStop << endl; + errmsg << "doAggProject: unsupported group by column: " + << typeid(*groupByCols[i]).name(); + cerr << boldStart << errmsg.str() << boldStop << endl; throw logic_error(errmsg.str()); } } // process the returned columns RetColsVector& retCols = jobInfo.projectionCols; - SRCP srcp; for (uint64_t i = 0; i < retCols.size(); i++) { GroupConcatColumn* gcc = dynamic_cast(retCols[i].get()); if (gcc != NULL) { - srcp = gcc->functionParms(); - const RowColumn* rcp = dynamic_cast(srcp.get()); + const SRCP* srcp = &(gcc->functionParms()); + const RowColumn* rcp = dynamic_cast(srcp->get()); const vector& cols = rcp->columnVec(); for (vector::const_iterator j = cols.begin(); j != cols.end(); j++) @@ -828,28 +867,32 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo continue; } - srcp = retCols[i]; + const SRCP* srcp = &(retCols[i]); const AggregateColumn* ag = dynamic_cast(retCols[i].get()); if (ag != NULL) - srcp = ag->functionParms(); + srcp = &(ag->functionParms()); - const ArithmeticColumn* ac = dynamic_cast(srcp.get()); - const FunctionColumn* fc = dynamic_cast(srcp.get()); + const ArithmeticColumn* ac = dynamic_cast(srcp->get()); + const FunctionColumn* fc = dynamic_cast(srcp->get()); if (ac != NULL || fc != NULL) { // bug 3728, make a dummy expression step for each expression. - scoped_ptr es(new ExpressionStep(jobInfo)); - es->expression(srcp, jobInfo); + scoped_ptr es(new ExpressionStep(jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId)); + es->logger(jobInfo.logger); + es->expression(*srcp, jobInfo); } } - map dictMap; // bug 1853, the tupleKey - dictoid map + map dictMap; // bug 1853, the tupleKey - dictoid map for (uint64_t i = 0; i < retCols.size(); i++) { - srcp = retCols[i]; - const SimpleColumn* sc = dynamic_cast(srcp.get()); + const SRCP* srcp = &(retCols[i]); + const SimpleColumn* sc = dynamic_cast(srcp->get()); bool doDistinct = (csep->distinct() && csep->groupByCols().empty()); - uint32_t tupleKey = -1; + uint tupleKey = -1; string alias; string view; @@ -877,8 +920,8 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo AggregateColumn* ac = dynamic_cast(retCols[i].get()); if (ac != NULL) { - srcp = ac->functionParms(); - sc = dynamic_cast(srcp.get()); + srcp = &(ac->functionParms()); + sc = dynamic_cast(srcp->get()); if (ac->constCol().get() != NULL) { // replace the aggregate on constant with a count(*) @@ -910,7 +953,7 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo { ct = sc->colType(); //XXX use this before connector sets colType in sc correctly. - if (sc->isInfiniDB() && dynamic_cast(sc) == NULL) + if (sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X dictOid = isDictCol(ct); @@ -918,7 +961,7 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo else { retOid = (tblOid+1) + sc->colPosition(); - ct = jobInfo.vtableColTypes[UniqId(retOid, alias, "", "")]; + ct = jobInfo.vtableColTypes[UniqId(retOid, sc)]; } TupleInfo ti(setTupleInfo(ct, retOid, jobInfo, tblOid, sc, alias)); @@ -927,7 +970,7 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo // this is a string column if (dictOid > 0) { - map::iterator findit = jobInfo.tokenOnly.find(tupleKey); + map::iterator findit = jobInfo.tokenOnly.find(tupleKey); // if the column has never seen, and the op is count: possible need count only. if (AggregateColumn::COUNT == op || AggregateColumn::COUNT_ASTERISK == op) { @@ -954,62 +997,59 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo { const ArithmeticColumn* ac = NULL; const FunctionColumn* fc = NULL; - const WindowFunctionColumn* wc = NULL; bool hasAggCols = false; - if ((ac = dynamic_cast(srcp.get())) != NULL) + if ((ac = dynamic_cast(srcp->get())) != NULL) { if (ac->aggColumnList().size() > 0) hasAggCols = true; } - else if ((fc = dynamic_cast(srcp.get())) != NULL) + else if ((fc = dynamic_cast(srcp->get())) != NULL) { if (fc->aggColumnList().size() > 0) hasAggCols = true; } - else if (dynamic_cast(srcp.get()) != NULL) - { - std::ostringstream errmsg; - errmsg << "Invalid aggregate function nesting."; - cerr << boldStart << errmsg.str() << boldStop << endl; - throw logic_error(errmsg.str()); - } - else if ((wc = dynamic_cast(srcp.get())) == NULL) + else { std::ostringstream errmsg; - errmsg << "doAggProject: unsupported column: " << typeid(*(srcp.get())).name(); + errmsg << "doAggProject: unsupported column: " << typeid(*(srcp->get())).name(); cerr << boldStart << errmsg.str() << boldStop << endl; throw logic_error(errmsg.str()); } - uint64_t eid = srcp.get()->expressionId(); - ct = srcp.get()->resultType(); - TupleInfo ti(setExpTupleInfo(ct, eid, srcp.get()->alias(), jobInfo)); + uint64_t eid = srcp->get()->expressionId(); + ct = srcp->get()->resultType(); + TupleInfo ti(setExpTupleInfo(ct, eid, srcp->get()->alias(), jobInfo)); tupleKey = ti.key; if (hasAggCols) jobInfo.expressionVec.push_back(tupleKey); } // add to project list - vector::iterator keyIt = find(projectKeys.begin(), projectKeys.end(), tupleKey); - if (keyIt == projectKeys.end()) + if (projectColMap.find(tupleKey) == projectColMap.end()) { RetColsVector::iterator it = pcv.end(); if (doDistinct) - it = pcv.insert(pcv.begin()+lastGroupByPos++, srcp); + it = pcv.insert(pcv.begin()+lastGroupByPos++, *srcp); else - it = pcv.insert(pcv.end(), srcp); + it = pcv.insert(pcv.end(), *srcp); - projectKeys.insert(projectKeys.begin() + distance(pcv.begin(), it), tupleKey); + projectColMap[tupleKey] = distance(pcv.begin(), it); } else if (doDistinct) // @bug4250, move forward distinct column if necessary. { - uint32_t pos = distance(projectKeys.begin(), keyIt); + uint pos = projectColMap[tupleKey]; if (pos >= lastGroupByPos) { pcv[pos] = pcv[lastGroupByPos]; - pcv[lastGroupByPos] = srcp; - projectKeys[pos] = projectKeys[lastGroupByPos]; - projectKeys[lastGroupByPos] = tupleKey; + pcv[lastGroupByPos] = *srcp; + + // @bug4935, update the projectColMap after swapping + map::iterator j = projectColMap.begin(); + for (; j != projectColMap.end(); j++) + if (j->second == lastGroupByPos) + j->second = pos; + + projectColMap[tupleKey] = lastGroupByPos; lastGroupByPos++; } } @@ -1038,13 +1078,13 @@ const JobStepVector doAggProject(const CalpontSelectExecutionPlan* csep, JobInfo { // if the column is a dictionary column and not count only bool tokenOnly = false; - map::iterator i = jobInfo.tokenOnly.find(it->first); + map::iterator i = jobInfo.tokenOnly.find(it->first); if (i != jobInfo.tokenOnly.end()) tokenOnly = i->second; if (dictMap.find(it->first) != dictMap.end() && !tokenOnly) { - uint32_t tupleKey = jobInfo.keyInfo->dictKeyMap[it->first]; + uint tupleKey = jobInfo.keyInfo->dictKeyMap[it->first]; int op = it->second; *it = make_pair(tupleKey, op); } @@ -1109,9 +1149,6 @@ uint16_t numberSteps(JobStepVector& steps, uint16_t stepNo, uint32_t flags) void changePcolStepToPcolScan(JobStepVector::iterator& it, JobStepVector::iterator& end) { - // make sure no pseudo column is a scan column - idbassert(dynamic_cast(it->get()) == NULL); - pColStep* colStep = dynamic_cast(it->get()); pColScanStep* scanStep = 0; //Might be a pDictionaryScan step @@ -1138,7 +1175,7 @@ void changePcolStepToPcolScan(JobStepVector::iterator& it, JobStepVector::iterat } } -uint32_t shouldSort(const JobStep* inJobStep, int colWidth) +uint shouldSort(const JobStep* inJobStep, int colWidth) { //only pColStep and pColScan have colType const pColStep *inStep = dynamic_cast(inJobStep); @@ -1158,18 +1195,18 @@ void convertPColStepInProjectToPassThru(JobStepVector& psv, JobInfo& jobInfo) { for (JobStepVector::iterator iter = psv.begin(); iter != psv.end(); ++iter) { - pColStep* colStep = dynamic_cast(iter->get()); - if (colStep != NULL) + if (typeid(*(iter->get())) == typeid(pColStep)) { JobStepAssociation ia = iter->get()->inputAssociation(); DataList_t* fifoDlp = ia.outAt(0).get()->dataList(); + pColStep* colStep = dynamic_cast(iter->get()); if (fifoDlp) { if (iter->get()->oid() >= 3000 && iter->get()->oid() == fifoDlp->OID()) { PassThruStep* pts = 0; - pts = new PassThruStep(*colStep); + pts = new PassThruStep(*colStep, jobInfo.isExeMgr); pts->alias(colStep->alias()); pts->view(colStep->view()); pts->name(colStep->name()); @@ -1297,9 +1334,6 @@ void parseExecutionPlan(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, jobInfo.selectAndFromSubs.begin(), jobInfo.selectAndFromSubs.end()); } - // bug4531, window function support - WindowFunctionStep::checkWindowFunction(csep, jobInfo); - // bug3391, move forward the aggregation check for no aggregte having clause. checkAggregation(csep, jobInfo); @@ -1310,10 +1344,10 @@ void parseExecutionPlan(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, //Need to change the leading pColStep to a pColScanStep //Keep a list of the (table OIDs,alias) that we've already processed for @bug 598 self-join - set seenTableIds; + set seenTableIds; //Stack of seenTables to make sure the left-hand side and right-hand have the same content - stack > seenTableStack; + stack > seenTableStack; if (!querySteps.empty()) { @@ -1364,13 +1398,13 @@ void parseExecutionPlan(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, // continue; // } - if (typeid(*(iter->get())) == typeid(pColStep)) + pColStep* colStep = dynamic_cast(iter->get()); + if (colStep != NULL) { - pColStep* colStep = dynamic_cast(iter->get()); string alias(colStep->alias()); string view(colStep->view()); //If this is the first time we've seen this table or alias - uint32_t tableId = 0; + uint tableId = 0; tableId = getTableKey(jobInfo, colStep->tupleId()); if (seenTableIds.find(tableId) == seenTableIds.end()) @@ -1409,17 +1443,16 @@ void parseExecutionPlan(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, CalpontSystemCatalog::OID tblOid = tableOid(sc, jobInfo.csc); CalpontSystemCatalog::ColType ct = sc->colType(); //XXX use this before connector sets colType in sc correctly. - if (sc->isInfiniDB() && dynamic_cast(sc) == NULL) + if (sc->isInfiniDB()) ct = jobInfo.csc->colType(sc->oid()); //X + string alias(extractTableAlias(sc)); TupleInfo ti(setTupleInfo(ct, sc->oid(), jobInfo, tblOid, sc, alias)); - uint32_t colKey = ti.key; - uint32_t tblKey = getTableKey(jobInfo, colKey); + uint colKey = ti.key; + uint tblKey = getTableKey(jobInfo, colKey); jobInfo.columnMap[tblKey].push_back(colKey); - if (jobInfo.tableColMap.find(tblKey) == jobInfo.tableColMap.end()) - jobInfo.tableColMap[tblKey] = i->second; } } @@ -1431,11 +1464,11 @@ void parseExecutionPlan(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, //TODO: more work here... // @bug 497 fix. populate a map of tableoid for querysteps. tablescan // cols whose table does not belong to the map - typedef set tableIDMap_t; + typedef set tableIDMap_t; tableIDMap_t tableIDMap; JobStepVector::iterator qsiter = querySteps.begin(); JobStepVector::iterator qsend = querySteps.end(); - uint32_t tableId = 0; + uint tableId = 0; while (qsiter != qsend) { JobStep* js = qsiter->get(); @@ -1462,7 +1495,7 @@ void parseExecutionPlan(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, pColStep* colStep = dynamic_cast(step0.get()); pColScanStep* scanStep = new pColScanStep(*colStep); //clear out any output association so we get a nice, new one during association - scanStep->outputAssociation(JobStepAssociation()); + scanStep->outputAssociation(JobStepAssociation(jobInfo.status)); step0.reset(scanStep); querySteps.push_back(step0); js = step0.get(); @@ -1479,27 +1512,20 @@ void makeVtableModeSteps(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, JobStepVector& querySteps, JobStepVector& projectSteps, DeliveredTableMap& deliverySteps) { // @bug4848, enhance and unify limit handling. - if (csep->limitNum() != (uint64_t) -1) + // @bug5176. Do limit only for select. + if (csep->queryType() == "SELECT" && csep->limitNum() != (uint64_t) -1) { // special case for outer query order by limit -- return all if (jobInfo.subId == 0 && csep->hasOrderBy()) - { jobInfo.limitCount = (uint64_t) -1; - } // support order by and limit in sub-query/union else if (csep->orderByCols().size() > 0) - { addOrderByAndLimit(csep, jobInfo); - } // limit without order by in any query else - { - jobInfo.limitStart = csep->limitStart(); - jobInfo.limitCount = csep->limitNum(); - } - + jobInfo.limitCount = csep->limitStart() + csep->limitNum(); } // Bug 2123. Added overrideLargeSideEstimate parm below. True if the query was written @@ -1539,7 +1565,7 @@ void makeJobSteps(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, else oid = 0; - uint32_t tableUid = makeTableKey(jobInfo, oid, it->table, it->alias, it->schema, it->view); + uint tableUid = makeTableKey(jobInfo, oid, it->table, it->alias, it->schema, it->view); jobInfo.tableList.push_back(tableUid); } @@ -1562,11 +1588,19 @@ void makeUnionJobSteps(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo, uint8_t distinctUnionNum = csep->distinctUnionNum(); RetColsVector unionRetCols = csep->returnedCols(); JobStepVector unionFeeders; +// CalpontSelectExecutionPlan* ep = NULL; for (CalpontSelectExecutionPlan::SelectList::iterator cit = selectVec.begin(); cit != selectVec.end(); cit++) { - // @bug4848, enhance and unify limit handling. +// JobStepVector qSteps; +// JobStepVector pSteps; +// DeliveredTableMap dSteps; +// JobInfo queryJobInfo = jobInfo; +// ep = dynamic_cast((*cit).get()); +// makeJobSteps(ep, queryJobInfo, qSteps, pSteps, dSteps); +// querySteps.insert(querySteps.end(), qSteps.begin(), qSteps.end()); +// unionFeeders.push_back(dSteps[execplan::CNX_VTABLE_ID]); SJSTEP sub = doUnionSub(cit->get(), jobInfo); querySteps.push_back(sub); unionFeeders.push_back(sub); @@ -1597,13 +1631,13 @@ SJLP makeJobList_( // We have to go ahead and create JobList now so we can store the joblist's // projectTableOID pointer in JobInfo for use during jobstep creation. - SErrorInfo errorInfo(new ErrorInfo()); - boost::shared_ptr keyInfo(new TupleKeyInfo); - boost::shared_ptr subCount(new int); + SErrorInfo status(new ErrorInfo()); + shared_ptr keyInfo(new TupleKeyInfo); + shared_ptr subCount(new int); *subCount = 0; JobList* jl = new TupleJobList(isExeMgr); jl->priority(csep->priority()); - jl->errorInfo(errorInfo); + jl->statusPtr(status); rm.setTraceFlags(csep->traceFlags()); //Stuff a util struct with some stuff we always need @@ -1612,7 +1646,6 @@ SJLP makeJobList_( jobInfo.txnId = csep->txnID(); jobInfo.verId = csep->verID(); jobInfo.statementId = csep->statementID(); - jobInfo.queryType = csep->queryType(); jobInfo.csc = csc; //TODO: clean up the vestiges of the bool trace jobInfo.trace = csep->traceOn(); @@ -1620,25 +1653,11 @@ SJLP makeJobList_( jobInfo.isExeMgr = isExeMgr; // jobInfo.tryTuples = tryTuples; // always tuples after release 3.0 jobInfo.stringScanThreshold = csep->stringScanThreshold(); - jobInfo.errorInfo = errorInfo; + jobInfo.status = status; jobInfo.keyInfo = keyInfo; jobInfo.subCount = subCount; jobInfo.projectingTableOID = jl->projectingTableOIDPtr(); jobInfo.jobListPtr = jl; - jobInfo.stringTableThreshold = csep->stringTableThreshold(); - jobInfo.localQuery = csep->localQuery(); - jobInfo.uuid = csep->uuid(); - - /* disk-based join vars */ - jobInfo.smallSideLimit = csep->djsSmallSideLimit(); - jobInfo.largeSideLimit = csep->djsLargeSideLimit(); - jobInfo.partitionSize = csep->djsPartitionSize(); - jobInfo.umMemLimit.reset(new int64_t); - *(jobInfo.umMemLimit) = csep->umMemLimit(); - jobInfo.isDML = csep->isDML(); - - jobInfo.smallSideUsage.reset(new int64_t); - *jobInfo.smallSideUsage = 0; // set fifoSize to 1 for CalpontSystemCatalog query if (csep->sessionID() & 0x80000000) @@ -1671,7 +1690,6 @@ SJLP makeJobList_( ", fifoSize = " << jobInfo.fifoSize << ", ScanLimit/Threshold = " << jobInfo.scanLbidReqLimit << "/" << jobInfo.scanLbidReqThreshold << endl; - oss << "UUID: " << jobInfo.uuid << endl; oss << endl << "job filter steps: " << endl; ostream_iterator oIter(oss, "\n"); copy(querySteps.begin(), querySteps.end(), oIter); @@ -1743,15 +1761,23 @@ SJLP makeJobList_( } catch (IDBExcept& iex) { - jobInfo.errorInfo->errCode = iex.errorCode(); + jobInfo.status->errCode = iex.errorCode(); errCode = iex.errorCode(); exceptionHandler(jl, jobInfo, iex.what(), LOG_TYPE_DEBUG); emsg = iex.what(); goto bailout; } + catch (QueryDataExcept& uee) + { + jobInfo.status->errCode = uee.errorCode(); + errCode = uee.errorCode(); + exceptionHandler(jl, jobInfo, uee.what(), LOG_TYPE_DEBUG); + emsg = uee.what(); + goto bailout; + } catch (const std::exception& ex) { - jobInfo.errorInfo->errCode = makeJobListErr; + jobInfo.status->errCode = makeJobListErr; errCode = makeJobListErr; exceptionHandler(jl, jobInfo, ex.what()); emsg = ex.what(); @@ -1759,7 +1785,7 @@ SJLP makeJobList_( } catch (...) { - jobInfo.errorInfo->errCode = makeJobListErr; + jobInfo.status->errCode = makeJobListErr; errCode = makeJobListErr; exceptionHandler(jl, jobInfo, "an exception"); emsg = "An unknown internal joblist error"; @@ -1799,10 +1825,10 @@ SJLP JobListFactory::makeJobList( if (!ret) { ret.reset(new TupleJobList(isExeMgr)); - SErrorInfo errorInfo(new ErrorInfo); - errorInfo->errCode = errCode; - errorInfo->errMsg = emsg; - ret->errorInfo(errorInfo); + SErrorInfo status(new ErrorInfo); + status->errCode = errCode; + status->errMsg = emsg; + ret->statusPtr(status); } return ret; diff --git a/dbcon/joblist/joblistfactory.h b/dbcon/joblist/joblistfactory.h index 537a6b03..55f6a6e4 100644 --- a/dbcon/joblist/joblistfactory.h +++ b/dbcon/joblist/joblistfactory.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: joblistfactory.h 9655 2013-06-25 23:08:13Z xlou $ +* $Id: joblistfactory.h 8268 2012-01-18 20:57:55Z xlou $ * * ***********************************************************************/ @@ -29,7 +29,7 @@ #include "joblist.h" -#if defined(_MSC_VER) && defined(JOBLIST_DLLEXPORT) +#if defined(_MSC_VER) && defined(JOBLISTFACTORY_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -40,8 +40,8 @@ namespace execplan class CalpontExecutionPlan; } -namespace joblist -{ +namespace joblist +{ class ResourceManager; /** @brief create a JobList object from a CalpontExecutionPlan object @@ -55,12 +55,12 @@ class ResourceManager; * can't inherit from this class). This class can be easily enough converted into * a singleton if necessary later. */ -class JobListFactory +class JobListFactory { public: /** @brief static JobList constructor method - * + * * @param cplan the CalpontExecutionPlan from which the JobList is constructed */ EXPORT static SJLP makeJobList( @@ -73,7 +73,7 @@ class JobListFactory }; -} +} #undef EXPORT diff --git a/dbcon/joblist/joblisttypes.h b/dbcon/joblist/joblisttypes.h index 1a8eb2b6..d0577f8d 100644 --- a/dbcon/joblist/joblisttypes.h +++ b/dbcon/joblist/joblisttypes.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /** -* $Id: joblisttypes.h 9251 2013-02-01 21:21:35Z dhall $ +* $Id: joblisttypes.h 8436 2012-04-04 18:18:21Z rdempsey $ */ /** @file */ @@ -34,17 +34,8 @@ const uint32_t INTNULL = 0x80000000; const uint32_t INTEMPTYROW = 0x80000001; const uint16_t SMALLINTNULL = 0x8000; const uint16_t SMALLINTEMPTYROW = 0x8001; -const uint8_t TINYINTNULL = 0x80; -const uint8_t TINYINTEMPTYROW = 0x81; - -const uint64_t UBIGINTNULL = 0xFFFFFFFFFFFFFFFEULL; -const uint64_t UBIGINTEMPTYROW = 0xFFFFFFFFFFFFFFFFULL; -const uint32_t UINTNULL = 0xFFFFFFFE; -const uint32_t UINTEMPTYROW = 0xFFFFFFFF; -const uint16_t USMALLINTNULL = 0xFFFE; -const uint16_t USMALLINTEMPTYROW = 0xFFFF; -const uint8_t UTINYINTNULL = 0xFE; -const uint8_t UTINYINTEMPTYROW = 0xFF; +const uint8_t TINYINTNULL = 0x80; +const uint8_t TINYINTEMPTYROW = 0x81; const uint32_t FLOATNULL = 0xFFAAAAAA; const uint32_t FLOATEMPTYROW = 0xFFAAAAAB; @@ -56,8 +47,8 @@ const uint32_t DATEEMPTYROW = 0xFFFFFFFF; const uint64_t DATETIMENULL = 0xFFFFFFFFFFFFFFFEULL; const uint64_t DATETIMEEMPTYROW = 0xFFFFFFFFFFFFFFFFULL; -const uint8_t CHAR1NULL = 0xFE; -const uint8_t CHAR1EMPTYROW = 0xFF; +const uint8_t CHAR1NULL = 0xFE; +const uint8_t CHAR1EMPTYROW = 0xFF; const uint16_t CHAR2NULL = 0xFEFF; const uint16_t CHAR2EMPTYROW = 0xFFFF; const uint32_t CHAR4NULL = 0xFEFFFFFF; @@ -65,16 +56,11 @@ const uint32_t CHAR4EMPTYROW = 0xFFFFFFFF; const uint64_t CHAR8NULL = 0xFEFFFFFFFFFFFFFFULL; const uint64_t CHAR8EMPTYROW = 0xFFFFFFFFFFFFFFFFULL; -const int8_t NULL_INT8 = TINYINTNULL; +const int8_t NULL_INT8 = TINYINTNULL; const int16_t NULL_INT16 = SMALLINTNULL; const int32_t NULL_INT32 = INTNULL; const int64_t NULL_INT64 = BIGINTNULL; -const uint8_t NULL_UINT8 = UTINYINTNULL; -const uint16_t NULL_UINT16 = USMALLINTNULL; -const uint32_t NULL_UINT32 = UINTNULL; -const uint64_t NULL_UINT64 = UBIGINTNULL; - const std::string CPNULLSTRMARK("_CpNuLl_"); const std::string CPSTRNOTFOUND("_CpNoTf_"); diff --git a/dbcon/joblist/jobstep.cpp b/dbcon/joblist/jobstep.cpp index 891db9c1..1917d063 100644 --- a/dbcon/joblist/jobstep.cpp +++ b/dbcon/joblist/jobstep.cpp @@ -15,18 +15,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jobstep.cpp 9414 2013-04-22 22:18:30Z xlou $ +// $Id: jobstep.cpp 8476 2012-04-25 22:28:15Z xlou $ #include #include -using namespace std; - #include -#include -#include -namespace bu=boost::uuids; - -#include "configcpp.h" -using namespace config; +using namespace std; #include "calpontsystemcatalog.h" #include "calpontselectexecutionplan.h" @@ -35,139 +28,125 @@ using namespace config; #include "timestamp.h" #include "oamcache.h" #include "jobstep.h" -#include "jlf_common.h" using namespace logging; -#include "querytele.h" -using namespace querytele; - -namespace -{ - -int toInt(const string& val) -{ - if (val.length() == 0) return -1; - return static_cast(config::Config::fromText(val)); -} -} - namespace joblist { -boost::mutex JobStep::fLogMutex; //=PTHREAD_MUTEX_INITIALIZER; - +boost::mutex JobStep::mutex; //=PTHREAD_MUTEX_INITIALIZER; + +//void JobStep::intToStr( DataList_t& inList, StringBucketDataList& outList ) +//{ +// int it = -1; +// bool more; +// ElementType e; +// int64_t token; +// char buffer[21]; // 19 digits in a 64-bit number + sign + nul +// int n = 0; +// try{ +// it = inList.getIterator(); +// }catch(exception& ex) { +// cerr << "JobStep::intToStr: caught exception: " +// << ex.what() << endl; +// throw; +// }catch(...) { +// cerr << "JobStep::intToStr: caught exception" << endl; +// throw; +// } +// +// more = inList.next(it, &e); +// while (more) +// { +// token = e.second; +// n = snprintf(buffer, 21, +//#if __LP64__ +// "%ld", +//#else +// "%lld", +//#endif +// token); +// outList.insert(StringElementType(e.first, buffer)); +// more = inList.next(it, &e); +// } +// +// return; +//} + ostream& operator<<(ostream& os, const JobStep* rhs) { - os << rhs->toString(); - return os; + os << rhs->toString(); + return os; } -//------------------------------------------------------------------------------ -// constructor -//------------------------------------------------------------------------------ -JobStep::JobStep(const JobInfo& j) : - fSessionId(j.sessionId), - fTxnId(j.txnId), - fVerId(j.verId), - fStatementId(j.statementId), - fStepId(0), - fTupleId(-1), - fTraceFlags(0), - fCardinality(0), - fDelayedRunFlag(false), - fDelivery(false), - fOnClauseFilter(false), - fDie(false), - fWaitToRunStepCnt(0), - fPriority(1), - fErrorInfo(j.errorInfo), - fLogger(j.logger), - fLocalQuery(j.localQuery), - fQueryUuid(j.uuid), - fProgress(0), - fStartTime(-1) -{ - QueryTeleServerParms tsp; - string teleServerHost(Config::makeConfig()->getConfig("QueryTele", "Host")); - if (!teleServerHost.empty()) - { - int teleServerPort = toInt(Config::makeConfig()->getConfig("QueryTele", "Port")); - if (teleServerPort > 0) - { - tsp.host = teleServerHost; - tsp.port = teleServerPort; - } - } - fQtc.serverParms(tsp); - //fStepUuid = bu::random_generator()(); - fStepUuid = QueryTeleClient::genUUID(); } +using namespace joblist; + //------------------------------------------------------------------------------ // Log a syslog msg for the start of this specified job step //------------------------------------------------------------------------------ void JobStep::syslogStartStep ( - uint32_t subSystem, + uint32_t subSystem, const string& stepName) const { - LoggingID logId ( subSystem, sessionId(), txnId() ); - MessageLog msgLog ( logId ); - - Message msgStartStep ( M0030 ); - Message::Args args; - args.add ( (uint64_t)statementId() ); // statement id for this job step - args.add ( (int)stepId() ); // step id for this job step - args.add ( stepName ); // step name for this job step - msgStartStep.format ( args ); - msgLog.logDebugMessage ( msgStartStep ); + LoggingID logId ( subSystem, sessionId(), txnId() ); + MessageLog msgLog ( logId ); + + Message msgStartStep ( M0030 ); + Message::Args args; + args.add ( (uint64_t)statementId() ); // statement id for this job step + args.add ( (int)stepId() ); // step id for this job step + args.add ( stepName ); // step name for this job step + msgStartStep.format ( args ); + msgLog.logDebugMessage ( msgStartStep ); } //------------------------------------------------------------------------------ // Log a syslog message for the end of this specified job step //------------------------------------------------------------------------------ void JobStep::syslogEndStep ( - uint32_t subSystem, - uint64_t blockedDLInput, - uint64_t blockedDLOutput, - uint64_t msgBytesInput, - uint64_t msgBytesOutput) const + uint32_t subSystem, + uint64_t blockedDLInput, + uint64_t blockedDLOutput, + uint64_t msgBytesInput, + uint64_t msgBytesOutput) const { - LoggingID logId ( subSystem, sessionId(), txnId() ); - MessageLog msgLog ( logId ); - - Message msgEndStep ( M0031 ); - Message::Args args; - args.add ( (uint64_t)statementId() ); // statement id for this job step - args.add ( (int)stepId() ); // step id for this job step - args.add ( blockedDLInput ); // blocked datalist input (ex: fifo) - args.add ( blockedDLOutput ); // blocked datalist output(ex: fifo) - args.add ( msgBytesInput ); // incoming msg byte count - args.add ( msgBytesOutput ); // outgoing msg byte count - msgEndStep.format ( args ); - msgLog.logDebugMessage ( msgEndStep ); + LoggingID logId ( subSystem, sessionId(), txnId() ); + MessageLog msgLog ( logId ); + + Message msgEndStep ( M0031 ); + Message::Args args; + args.add ( (uint64_t)statementId() ); // statement id for this job step + args.add ( (int)stepId() ); // step id for this job step + args.add ( blockedDLInput ); // blocked datalist input (ex: fifo) + args.add ( blockedDLOutput ); // blocked datalist output(ex: fifo) + args.add ( msgBytesInput ); // incoming msg byte count + args.add ( msgBytesOutput ); // outgoing msg byte count + msgEndStep.format ( args ); + msgLog.logDebugMessage ( msgEndStep ); } //------------------------------------------------------------------------------ // Log a syslog message for the physical vs cache block I/O counts //------------------------------------------------------------------------------ void JobStep::syslogReadBlockCounts ( - uint32_t subSystem, - uint64_t physicalReadCount, - uint64_t cacheReadCount, - uint64_t casualPartBlocks) const + uint32_t subSystem, + uint64_t physicalReadCount, + uint64_t cacheReadCount, + uint64_t casualPartBlocks) const { - LoggingID logId ( subSystem, sessionId(), txnId() ); - MessageLog msgLog ( logId ); - - Message msgEndStep ( M0032 ); - Message::Args args; - args.add ( (uint64_t)statementId() ); // statement id for this job step - args.add ( (int)stepId() ); // step id for this job step - args.add ( (int)oid() ); // step id for this job step - args.add ( physicalReadCount ); // blocked datalist input (ex: fifo) - args.add ( cacheReadCount ); // blocked datalist output(ex: fifo) - args.add ( casualPartBlocks ); // casual partition block hits - msgEndStep.format ( args ); - msgLog.logDebugMessage ( msgEndStep ); + LoggingID logId ( subSystem, sessionId(), txnId() ); + MessageLog msgLog ( logId ); + + Message msgEndStep ( M0032 ); + Message::Args args; + args.add ( (uint64_t)statementId() ); // statement id for this job step + args.add ( (int)stepId() ); // step id for this job step + args.add ( (int)oid() ); // step id for this job step + args.add ( physicalReadCount ); // blocked datalist input (ex: fifo) + args.add ( cacheReadCount ); // blocked datalist output(ex: fifo) + args.add ( casualPartBlocks ); // casual partition block hits + msgEndStep.format ( args ); + msgLog.logDebugMessage ( msgEndStep ); } //------------------------------------------------------------------------------ @@ -175,32 +154,34 @@ void JobStep::syslogReadBlockCounts ( // (lastWriteTime denotes when the EndOfInput marker was written out). //------------------------------------------------------------------------------ void JobStep::syslogProcessingTimes ( - uint32_t subSystem, - const struct timeval& firstReadTime, - const struct timeval& lastReadTime, - const struct timeval& firstWriteTime, - const struct timeval& lastWriteTime) const + uint32_t subSystem, + const struct timeval& firstReadTime, + const struct timeval& lastReadTime, + const struct timeval& firstWriteTime, + const struct timeval& lastWriteTime) const { - LoggingID logId ( subSystem, sessionId(), txnId() ); - MessageLog msgLog ( logId ); - Message msgStartStep ( M0046 ); - Message::Args args; - - args.add ( (uint64_t)statementId() ); // statement id for this job step - args.add ( (int)stepId() ); // step id for this job step - args.add ( JSTimeStamp::format(firstReadTime) ); // when first DL input element read - args.add ( JSTimeStamp::format(lastReadTime) ); // when last DL input element read - args.add ( JSTimeStamp::format(firstWriteTime));// when first DL output elem written - args.add ( JSTimeStamp::format(lastWriteTime)); // when EndOfInput written to DL out - msgStartStep.format ( args ); - msgLog.logDebugMessage ( msgStartStep ); + LoggingID logId ( subSystem, sessionId(), txnId() ); + MessageLog msgLog ( logId ); + Message msgStartStep ( M0046 ); + Message::Args args; + + args.add ( (uint64_t)statementId() ); // statement id for this job step + args.add ( (int)stepId() ); // step id for this job step + args.add ( JSTimeStamp::format(firstReadTime) ); // when first DL input element read + args.add ( JSTimeStamp::format(lastReadTime) ); // when last DL input element read + args.add ( JSTimeStamp::format(firstWriteTime));// when first DL output elem written + args.add ( JSTimeStamp::format(lastWriteTime)); // when EndOfInput written to DL out + msgStartStep.format ( args ); + msgLog.logDebugMessage ( msgStartStep ); } -bool JobStep::traceOn() const +void JobStep::abort() { - return fTraceFlags & execplan::CalpontSelectExecutionPlan::TRACE_LOG; + die = true; } -} //namespace joblist -// vim:ts=4 sw=4: +bool JobStep::traceOn() const +{ + return fTraceFlags & execplan::CalpontSelectExecutionPlan::TRACE_LOG; +} diff --git a/dbcon/joblist/jobstep.h b/dbcon/joblist/jobstep.h index 7dccd30d..9d10ece7 100644 --- a/dbcon/joblist/jobstep.h +++ b/dbcon/joblist/jobstep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: jobstep.h 9636 2013-06-20 14:23:36Z rdempsey $ +// $Id: jobstep.h 8774 2012-07-31 21:00:09Z pleblanc $ /** @file */ @@ -32,20 +32,26 @@ #include #include -#include #include "calpontsystemcatalog.h" #include "calpontselectexecutionplan.h" #include "elementtype.h" -#include "errorinfo.h" #include "jl_logger.h" #include "timestamp.h" #include "rowgroup.h" -#include "querytele.h" -#include "atomicops.h" -#include "branchpred.h" +/* branch prediction macros for gcc. Is there a better place for them? */ +#if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96) +#ifndef __builtin_expect +#define __builtin_expect(x, expected_value) (x) +#endif +#endif + +#ifndef LIKELY +#define LIKELY(x) __builtin_expect((x),1) +#define UNLIKELY(x) __builtin_expect((x),0) +#endif #ifndef __GNUC__ # ifndef __attribute__ @@ -58,286 +64,247 @@ namespace joblist { /** @brief class JobStepAssociation mediator class to connect/control JobSteps and DataLists - * - * Class JobStepAssociation connects/controls JobSteps and DalaLists + * + * Class JobStepAssociation controls JobSteps and DataLists */ +struct ErrorInfo { + ErrorInfo() : errCode(0) { } + uint32_t errCode; + std::string errMsg; + // for backward compat + ErrorInfo(uint16_t v) : errCode(v) { } + ErrorInfo & operator=(uint16_t v) { errCode = v; errMsg.clear(); return *this; } +}; +typedef boost::shared_ptr SErrorInfo; + + class JobStepAssociation { public: - JobStepAssociation() { } + JobStepAssociation(): fToSort(0) { } + JobStepAssociation(SErrorInfo s): fToSort(0), errInfo(s) { } virtual ~JobStepAssociation() {} - void inAdd(const AnyDataListSPtr& spdl) __attribute__((deprecated)) { fInDataList.push_back(spdl); } + void inAdd(const AnyDataListSPtr& spdl) __attribute__((deprecated)) { fInDataList.push_back(spdl); } void outAdd(const AnyDataListSPtr& spdl) { fOutDataList.push_back(spdl); } void outAdd(const AnyDataListSPtr& spdl, size_t pos) { - if (pos > fOutDataList.size()) throw std::logic_error("Insert position is beyond end."); - fOutDataList.insert(fOutDataList.begin()+pos, spdl); } + if (pos > fOutDataList.size()) throw std::logic_error("Insert position is beyond end."); + fOutDataList.insert(fOutDataList.begin()+pos, spdl); } void outAdd(const DataListVec& spdlVec, size_t pos) { - if (pos > fOutDataList.size()) throw std::logic_error("Insert position is beyond end."); - fOutDataList.insert(fOutDataList.begin()+pos, spdlVec.begin(), spdlVec.end()); } + if (pos > fOutDataList.size()) throw std::logic_error("Insert position is beyond end."); + fOutDataList.insert(fOutDataList.begin()+pos, spdlVec.begin(), spdlVec.end()); } size_t inSize() const __attribute__((deprecated)) { return fInDataList.size(); } size_t outSize() const { return fOutDataList.size(); } const AnyDataListSPtr& inAt(size_t i) const __attribute__((deprecated)) { return fInDataList.at(i); } const AnyDataListSPtr& outAt(size_t i) const { return fOutDataList.at(i); } AnyDataListSPtr& outAt(size_t i) { return fOutDataList.at(i); } + uint8_t toSort() const { return fToSort; } + void toSort(uint8_t toSort) { fToSort = toSort; } + uint32_t status() const { return errInfo->errCode; } + void status(uint32_t s) { errInfo->errCode = s; } + std::string errorMessage() { return errInfo->errMsg; } + void errorMessage(const std::string &s) { errInfo->errMsg = s; } + const SErrorInfo& statusPtr() const { return errInfo; } + void statusPtr(SErrorInfo sp) { errInfo = sp; } private: DataListVec fInDataList; DataListVec fOutDataList; -}; + uint8_t fToSort; + SErrorInfo errInfo; -// forward reference -struct JobInfo; +}; /** @brief class JobStep abstract class describing a query execution step - * + * * Class JobStep is an abstract class that describes a query execution step */ -class JobStep +struct JobStep { -public: - /** constructor */ - JobStep() { } - JobStep(const JobInfo&); + JobStep() : fToSort(0), fTraceFlags(0), fCardinality(0), fError(0), + fDelayedRunFlag(false), fOnClauseFilter(false), fWaitToRunStepCnt(0), + die(false), fTupleId(-1), _priority(1) { } /** destructor */ virtual ~JobStep() { /*pthread_mutex_destroy(&mutex);*/ } /** @brief virtual void Run method */ virtual void run() = 0; - virtual void abort() { fDie = true; } + virtual void abort(); /** @brief virtual void join method */ virtual void join() = 0; - /** @brief virtual string toString method - */ - virtual const std::string toString() const = 0; - /** @brief virtual JobStepAssociation * inputAssociation method */ - virtual void inputAssociation(const JobStepAssociation& inputAssociation) - { fInputJobStepAssociation = inputAssociation; } - virtual const JobStepAssociation& inputAssociation() const - { return fInputJobStepAssociation; } + virtual const JobStepAssociation& inputAssociation() const = 0; + virtual void inputAssociation(const JobStepAssociation& inputAssociation) = 0; /** @brief virtual JobStepAssociation * outputAssociation method */ - virtual void outputAssociation(const JobStepAssociation& outputAssociation) - { fOutputJobStepAssociation = outputAssociation; } - virtual const JobStepAssociation& outputAssociation() const - { return fOutputJobStepAssociation; } - - virtual void stepId(uint16_t stepId) { fStepId = stepId; } - virtual uint16_t stepId() const { return fStepId; } - virtual uint32_t sessionId() const { return fSessionId; } - virtual uint32_t txnId() const { return fTxnId; } - virtual uint32_t statementId() const { return fStatementId; } - virtual void logger(const SPJL& logger) { fLogger = logger; } + virtual const JobStepAssociation& outputAssociation() const = 0; + virtual void outputAssociation(const JobStepAssociation& outputAssociation) = 0; + virtual const std::string toString() const = 0; + virtual void stepId(uint16_t stepId) = 0; + virtual uint16_t stepId() const = 0; + virtual uint32_t sessionId() const = 0; + virtual uint32_t txnId() const = 0; + virtual uint32_t statementId() const = 0; virtual bool isDictCol() const { return 0; } virtual execplan::CalpontSystemCatalog::OID oid() const { return 0; } virtual execplan::CalpontSystemCatalog::OID tableOid() const { return 0; } - // @bug 598 Added alias for self-join + virtual void logger(const SPJL& logger) = 0; + // @bug 598 Added alias for self-join virtual std::string alias() const { return fAlias; } virtual void alias(const std::string& alias) { fAlias = alias; } - // @bug 3401 & 3402, view support + // @bug 3401 & 3402, view support virtual std::string view() const { return fView; } virtual void view(const std::string& vw) { fView= vw; } - // @bug 3438, stats with column name + // @bug 3438, stats with column name virtual std::string name() const { return fName; } virtual void name(const std::string& nm) { fName= nm; } virtual std::string schema() const { return fSchema; } virtual void schema(const std::string& s) { fSchema = s; } - // @bug 3398, add columns' unique tuple ID to job step - virtual uint64_t tupleId() const { return fTupleId; } - virtual void tupleId(uint64_t id) { fTupleId = id; } - - //...Final I/O blk count, msg rcv count, etc for this job step. These - //...methods do not use a mutex lock to acquire values, because it is - //...assumed they are called after all processing is complete. - virtual uint64_t phyIOCount ( ) const { return 0; } - virtual uint64_t cacheIOCount ( ) const { return 0; } - virtual uint64_t msgsRcvdCount ( ) const { return 0; } - virtual uint64_t msgBytesIn ( ) const { return 0; } - virtual uint64_t msgBytesOut ( ) const { return 0; } - virtual uint64_t blockTouched ( ) const { return 0;} - virtual uint64_t cardinality ( ) const { return fCardinality; } - virtual void cardinality ( const uint64_t cardinality ) { fCardinality = cardinality; } - - // functions to delay/control jobstep execution; decWaitToRunStepCnt() per- - // forms atomic decrement op because it is accessed by multiple threads. - bool delayedRun() const { return fDelayedRunFlag; } - int waitToRunStepCnt() { return fWaitToRunStepCnt; } - void incWaitToRunStepCnt() { - fDelayedRunFlag = true; - ++fWaitToRunStepCnt; } - int decWaitToRunStepCnt() { - return atomicops::atomicDec(&fWaitToRunStepCnt); - } - void resetDelayedRun() { fDelayedRunFlag = false; fWaitToRunStepCnt = 0; } - - void logEnd(const char* s) - { - fLogMutex.lock(); //pthread_mutex_lock(&mutex); - std::cout << s <errCode; } - void status(uint32_t s) { fErrorInfo->errCode = s; } - std::string errorMessage() { return fErrorInfo->errMsg; } - void errorMessage(const std::string &s) { fErrorInfo->errMsg = s; } - const SErrorInfo& errorInfo() const { return fErrorInfo; } - SErrorInfo& errorInfo() { return fErrorInfo; } - void errorInfo(SErrorInfo& sp) { fErrorInfo = sp; } + void setTrace(bool trace) __attribute__((deprecated)); + bool traceOn() const; + void setTraceFlags(uint32_t flags) { fTraceFlags = flags; } + JSTimeStamp dlTimes; - bool cancelled() { return (fErrorInfo->errCode > 0 || fDie); } + const std::string& extendedInfo() const { return fExtendedInfo; } + const std::string& miniInfo() const { return fMiniInfo; } - virtual bool stringTableFriendly() { return false; } - - bool delivery() const { return fDelivery; } - void delivery(bool b) { fDelivery = b; } - - const boost::uuids::uuid& queryUuid() const { return fQueryUuid; } + uint priority() const { return _priority; } + void priority(uint p) { _priority = p; } //@bug5887, distinguish on clause filter and where clause filter bool onClauseFilter() const { return fOnClauseFilter; } void onClauseFilter(bool b) { fOnClauseFilter = b; } protected: - - //@bug6088, for telemetry posting - static const int64_t STEP_TELE_INTERVAL = 5000; // now, this is the browser refresh rate - void postStepStartTele(querytele::StepTeleStats& sts) - { - fStartTime = fLastStepTeleTime = sts.start_time = querytele::QueryTeleClient::timeNowms(); - fQtc.postStepTele(sts); - } - void postStepProgressTele(querytele::StepTeleStats& sts) - { - int64_t crntTime = querytele::QueryTeleClient::timeNowms(); - if ((crntTime - fLastStepTeleTime) >= STEP_TELE_INTERVAL) - { - // interval between step telemetry - sts.start_time = fStartTime; - fQtc.postStepTele(sts); - fLastStepTeleTime = crntTime; - } - } - void postStepSummaryTele(querytele::StepTeleStats& sts) - { - sts.start_time = fStartTime; - sts.end_time = fLastStepTeleTime = querytele::QueryTeleClient::timeNowms(); - fQtc.postStepTele(sts); - } - - JobStepAssociation fInputJobStepAssociation; - JobStepAssociation fOutputJobStepAssociation; - - uint32_t fSessionId; - uint32_t fTxnId; - BRM::QueryContext fVerId; - uint32_t fStatementId; - - uint32_t fStepId; - uint64_t fTupleId; - std::string fAlias; std::string fView; - std::string fName; - std::string fSchema; - uint32_t fTraceFlags; - uint64_t fCardinality; - bool fDelayedRunFlag; - bool fDelivery; + std::string fName; + std::string fSchema; + uint8_t fToSort; + uint32_t fTraceFlags; + uint64_t fCardinality; + bool fError; + bool fDelayedRunFlag; bool fOnClauseFilter; - volatile bool fDie; - volatile uint32_t fWaitToRunStepCnt; - std::string fExtendedInfo; - std::string fMiniInfo; - - uint32_t fPriority; - - SErrorInfo fErrorInfo; - SPJL fLogger; - - uint32_t fLocalQuery; - - boost::uuids::uuid fQueryUuid; - boost::uuids::uuid fStepUuid; - querytele::QueryTeleClient fQtc; - uint64_t fProgress; - int64_t fStartTime; - int64_t fLastStepTeleTime; +#ifdef _MSC_VER + volatile long fWaitToRunStepCnt; +#else + _Atomic_word fWaitToRunStepCnt; +#endif + volatile bool die; + boost::mutex* fStatsMutexPtr; + std::string fExtendedInfo; + std::string fMiniInfo; + uint64_t fTupleId; + uint _priority; private: - static boost::mutex fLogMutex; - - friend class CommandJL; + static boost::mutex mutex; + friend class CommandJL; }; class TupleJobStep { public: - TupleJobStep() { } - virtual ~TupleJobStep() { } - virtual void setOutputRowGroup(const rowgroup::RowGroup&) = 0; - virtual void setFcnExpGroup3(const std::vector&) {} - virtual void setFE23Output(const rowgroup::RowGroup&) {} - virtual const rowgroup::RowGroup& getOutputRowGroup() const = 0; + TupleJobStep() {} + virtual ~TupleJobStep() {} + virtual void setOutputRowGroup(const rowgroup::RowGroup&) = 0; + virtual void setFcnExpGroup3(const std::vector&) {} + virtual void setFE23Output(const rowgroup::RowGroup&) {} + virtual const rowgroup::RowGroup& getOutputRowGroup() const = 0; }; class TupleDeliveryStep : public TupleJobStep { public: - virtual ~TupleDeliveryStep() { } - virtual uint32_t nextBand(messageqcpp::ByteStream &bs) = 0; - virtual const rowgroup::RowGroup& getDeliveredRowGroup() const = 0; - virtual void deliverStringTableRowGroup(bool b) = 0; - virtual bool deliverStringTableRowGroup() const = 0; + virtual ~TupleDeliveryStep() { } + virtual uint nextBand(messageqcpp::ByteStream &bs) = 0; + virtual const rowgroup::RowGroup& getDeliveredRowGroup() const = 0; + virtual void setIsDelivery(bool b) = 0; }; // calls rhs->toString() std::ostream& operator<<(std::ostream& os, const JobStep* rhs); + typedef boost::shared_ptr SJSA; -typedef boost::shared_ptr JobStepAssociationSPtr; +typedef boost::shared_ptr JobStepAssociationSPtr; typedef boost::shared_ptr SJSTEP; + } #endif // JOBLIST_JOBSTEP_H_ // vim:ts=4 sw=4: + + diff --git a/dbcon/joblist/jobstepassociation.cpp b/dbcon/joblist/jobstepassociation.cpp index e00cddab..3eecc8b0 100644 --- a/dbcon/joblist/jobstepassociation.cpp +++ b/dbcon/joblist/jobstepassociation.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: jobstepassociation.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: jobstepassociation.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/joblist/largedatalist.h b/dbcon/joblist/largedatalist.h index cfb793ad..d98cc84f 100644 --- a/dbcon/joblist/largedatalist.h +++ b/dbcon/joblist/largedatalist.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: largedatalist.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: largedatalist.h 8476 2012-04-25 22:28:15Z xlou $ * *****************************************************************************/ -/** @file +/** @file * class XXX interface */ @@ -49,7 +49,7 @@ #include "resourcemanager.h" #include "exceptclasses.h" - + #ifndef O_BINARY # define O_BINARY 0 #endif @@ -105,7 +105,7 @@ class LargeDataList : public DataListImpl typedef DataListImpl base; public: - LargeDataList(uint32_t numConsumers, + LargeDataList(uint numConsumers, uint32_t elementSaveSize1, uint32_t elementSaveSize2, const ResourceManager& rm); @@ -113,7 +113,7 @@ class LargeDataList : public DataListImpl virtual void endOfInput(); virtual void insert(const element_t& e); - virtual uint64_t totalSize(); + virtual uint64_t totalSize(); virtual void setMultipleProducers(bool); virtual uint64_t numberOfTempFiles() const; virtual void setDiskElemSize(uint32_t size1st,uint32_t size2nd); @@ -121,7 +121,7 @@ class LargeDataList : public DataListImpl virtual void restoreSetForReuse(const struct SetRestoreInfo& info); virtual void traceOn(bool b) { fTraceOn = b; } std::list& diskIoList() { return fDiskIoList; } - + protected: // @bug 721. add append option virtual void load(uint64_t setNumber, bool append = false); @@ -137,7 +137,7 @@ class LargeDataList : public DataListImpl virtual uint64_t save(container_t *c); virtual uint64_t save_contiguous(); virtual uint64_t save_contiguous(container_t *c); - + virtual void registerNewSet(); virtual std::string getFilename(); @@ -191,7 +191,7 @@ class LargeDataList : public DataListImpl }; template -LargeDataList::LargeDataList(uint32_t nc, uint32_t elementSaveSize1st, uint32_t elementSaveSize2nd, const ResourceManager& rm): +LargeDataList::LargeDataList(uint nc, uint32_t elementSaveSize1st, uint32_t elementSaveSize2nd, const ResourceManager& rm): base(nc), path(rm.getScTempDiskPath()), fTraceOn(false), fReUse(false), fSaveForReuse(false), fRestoreInfo(NULL) { // config::Config *config = config::Config::makeConfig(); @@ -314,7 +314,7 @@ uint64_t LargeDataList::numberOfTempFiles() const // uint64_t nFiles = 0; // if ( !fFilename.empty() ) // nFiles = 1; -// +// // return nFiles; return ((!fSetStartPositions.empty() && !fReUse) ? 1 : 0); } @@ -359,7 +359,7 @@ void LargeDataList::createTempFile() // Need to grab the mutex at a higher level -/* +/* File format: int: # of elements element_t[# of elements] stored according to ostream& element_t::operator<< @@ -373,7 +373,7 @@ uint64_t LargeDataList::save() // Need to grab the mutex at a higher level -/* +/* File format: int: # of elements element_t[# of elements] stored according to ostream& element_t::operator<< @@ -411,7 +411,7 @@ uint64_t LargeDataList::save(container_t *c ) std::copy(c->begin(), c->end(), std::ostream_iterator(fFile)); - } + } else { save_noncontiguousCompressed ( c ); } @@ -426,16 +426,16 @@ uint64_t LargeDataList::save(container_t *c ) catch(const std::runtime_error& e) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred saving non-contiguous container into file " + fFilename + " "); + std::string msg("Error occurred saving non-contiguous container into file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg + e.what()); } catch(...) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred saving non-contiguous container into file " + fFilename + " "); + std::string msg("Error occurred saving non-contiguous container into file " + fFilename + " "); std::cerr << msg << std::endl; - throw logging::LargeDataListExcept(msg); + throw logging::LargeDataListExcept(msg); } #ifdef PROFILE @@ -447,14 +447,14 @@ uint64_t LargeDataList::save(container_t *c ) } template -uint64_t LargeDataList::save_contiguous() +uint64_t LargeDataList::save_contiguous() { std::vector *c = reinterpret_cast *>(base::c); return save_contiguous(c); } template -uint64_t LargeDataList::save_contiguous(container_t *c) +uint64_t LargeDataList::save_contiguous(container_t *c) { uint64_t count, nBytesWritten=0; typename container_t::iterator it; @@ -501,14 +501,14 @@ uint64_t LargeDataList::save_contiguous(container_t *c) catch(const std::runtime_error& e) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred saving contiguous container into file " + fFilename + " "); + std::string msg("Error occurred saving contiguous container into file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg + e.what()); } catch(...) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred saving contiguous container into file " + fFilename + " "); + std::string msg("Error occurred saving contiguous container into file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg); } @@ -527,7 +527,7 @@ uint64_t LargeDataList::save_contiguous(container_t *c) //------------------------------------------------------------------------------ template void LargeDataList::save_contiguousCompressed( - container_t *c) + container_t *c) { //...Compress and write out the elements based on the compression mode switch (fCompressMode) @@ -593,7 +593,7 @@ void LargeDataList::writeContiguousCompressed( //------------------------------------------------------------------------------ template void LargeDataList::save_noncontiguousCompressed( - container_t *c) + container_t *c) { //...Compress and write out the elements based on the compression mode. //...The only compression currently supported here is compression of the @@ -641,7 +641,7 @@ void LargeDataList::load(uint64_t setNumber, bool append } /* XXXPAT: How to handle errors here? Specifically, unless the entire load - is successful, things will be left in a relatively undefined state. Do we + is successful, things will be left in a relatively undefined state. Do we have to care about things like that here? Initial guess: no. */ try { DiskIoInfo info; @@ -650,7 +650,7 @@ void LargeDataList::load(uint64_t setNumber, bool append // Position the file to the correct file offset for this set. fFile.seekg( fSetStartPositions.at(setNumber) ); //std::cout << "Loading filename-" << fFilename << - // "; set-" << setNumber << "; fPos-" << + // "; set-" << setNumber << "; fPos-" << // fSetStartPositions.at(setNumber) << std::endl; std::streampos startPos = fFile.tellg(); @@ -663,7 +663,7 @@ void LargeDataList::load(uint64_t setNumber, bool append // @bug 721. merge all saving sets to current loaded set 0 and sort if (!append) v->resize(0); - if (count > v->size()) + if (count > v->size()) v->reserve( count ); switch (fCompressMode) @@ -737,7 +737,7 @@ void LargeDataList::load(uint64_t setNumber, bool append delete base::c; base::c = new container_t(); } - + switch (fCompressMode) { case COMPRESS_TO_32_64: @@ -783,14 +783,14 @@ void LargeDataList::load(uint64_t setNumber, bool append catch(const std::runtime_error& e) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred loading non-contiguous container from file " + fFilename + " "); + std::string msg("Error occurred loading non-contiguous container from file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg + e.what()); } catch(...) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred loading non-contiguous container from file " + fFilename + " "); + std::string msg("Error occurred loading non-contiguous container from file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg); } @@ -831,18 +831,18 @@ void LargeDataList::load_contiguous(uint64_t setNumber, } /* XXXPAT: How to handle errors here? Specifically, unless the entire load - is successful, things will be left in a relatively undefined state. Do we + is successful, things will be left in a relatively undefined state. Do we have to care about things like that here? Initial guess: no. */ try { DiskIoInfo info; if (fTraceOn) info.fStart = boost::posix_time::microsec_clock::local_time(); - v = reinterpret_cast *>(base::c); + v = reinterpret_cast *>(base::c); // Position the file to the correct file offset for this set. fFile.seekg( fSetStartPositions.at(setNumber) ); //std::cout << "LoadingC filename-" << fFilename << - // "; set-" << setNumber << "; fPos-" << + // "; set-" << setNumber << "; fPos-" << // fSetStartPositions.at(setNumber) << std::endl; std::streampos startPos = fFile.tellg(); @@ -877,14 +877,14 @@ void LargeDataList::load_contiguous(uint64_t setNumber, catch(const std::runtime_error& e) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred loading contiguous container from file " + fFilename + " "); + std::string msg("Error occurred loading contiguous container from file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg + e.what()); } catch(...) { if (fFile.is_open()) fFile.close(); - std::string msg("Error occurred loading contiguous container from file " + fFilename + " "); + std::string msg("Error occurred loading contiguous container from file " + fFilename + " "); std::cerr << msg << std::endl; throw logging::LargeDataListExcept(msg); } @@ -917,7 +917,7 @@ template void LargeDataList::load_contiguousCompressed(bool append, uint64_t count) { std::vector* v = - reinterpret_cast *>(base::c); + reinterpret_cast *>(base::c); element_t* pElementData = 0; if (append){ @@ -1004,7 +1004,7 @@ inline bool LargeDataList::next(uint64_t it, element_t * template inline bool LargeDataList::next_nowait(uint64_t it, element_t *e) -{ +{ bool ret; ret = base::next(it, e); return ret; @@ -1028,9 +1028,9 @@ void LargeDataList::registerNewSet() template uint64_t LargeDataList::totalSize() -{ +{ waitForConsumePhase(); - return totSize; + return totSize; } template @@ -1041,7 +1041,7 @@ inline void LargeDataList::insert(const element_t& e) } template -void LargeDataList::resetIterators() +void LargeDataList::resetIterators() { waitForConsumePhase(); for (int i = 0; i < (int) base::numConsumers; ++i) @@ -1049,7 +1049,7 @@ void LargeDataList::resetIterators() } template -void LargeDataList::resetIterators_nowait() +void LargeDataList::resetIterators_nowait() { for (uint64_t i = 0; i < base::numConsumers; ++i) { diff --git a/dbcon/joblist/largehashjoin.cpp b/dbcon/joblist/largehashjoin.cpp index b9a6a959..ba4f07ae 100644 --- a/dbcon/joblist/largehashjoin.cpp +++ b/dbcon/joblist/largehashjoin.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: largehashjoin.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: largehashjoin.cpp 8476 2012-04-25 22:28:15Z xlou $ #include #include #include @@ -92,7 +92,7 @@ void logDiskIoInfo(uint64_t stepId, const AnyDataListSPtr& spdl) { boost::posix_time::time_duration td = j->fEnd - j->fStart; umDiskIoFile << setfill('0') - << "st" << setw(2) << stepId << "oid" << oid << bkt << setw(3) << i + << "st" << setw(2) << stepId << "oid" << oid << bkt << setw(3) << i << (j->fWrite ? " writes " : " reads ") << setw(7) << setfill(' ') << j->fBytes << " bytes, at " << j->fStart << " duration " << td.total_microseconds() << " mcs @ " @@ -180,7 +180,7 @@ void* HashJoinByBucket_thr(void* arg) bool sendAllSearchSet = false; try { - for (uint32_t idx=0, bucketIdx=params->startBucket; + for (uint idx=0, bucketIdx=params->startBucket; idxnumBuckets; idx++, bucketIdx++) { @@ -210,7 +210,7 @@ try sendAllHashSet = (joinType == RIGHTOUTER); sendAllSearchSet = (joinType == LEFTOUTER); } - else + else { hjPtr->setHashSet(hjPtr->Set1()->getBDL(), thrIdx); hjPtr->setSearchSet(hjPtr->Set2()->getBDL(), thrIdx); @@ -222,10 +222,10 @@ try } // if set1Size <=0 . . . params->timeset.setTimer(createHashStr); - hjPtr->createHash(hjPtr->HashSet(thrIdx), - hjPtr->HashTable(thrIdx), - bucketIdx, - sendAllHashSet, + hjPtr->createHash(hjPtr->HashSet(thrIdx), + hjPtr->HashTable(thrIdx), + bucketIdx, + sendAllHashSet, hjPtr->HashResult(thrIdx), params->dlTimes, params->die); params->timeset.holdTimer(createHashStr); @@ -233,10 +233,10 @@ try #ifdef DEBUG long hashSetTotal = 0; long searchSetTotal = 0; - for (uint32_t j=0;jHashSet(thrIdx)->bucketCount();j++) + for (uint j=0;jHashSet(thrIdx)->bucketCount();j++) hashSetTotal+=hjPtr->HashSet(thrIdx)->bucketCount(); // are bucketDL - for (uint32_t j=0;jHashSet(thrIdx)->bucketCount();j++) + for (uint j=0;jHashSet(thrIdx)->bucketCount();j++) searchSetTotal+=hjPtr->SearchSet(thrIdx)->size(j); // can be any datalist cout << "\t\tJoinByBucket() thr " << dec << thrIdx @@ -247,15 +247,15 @@ try bool more; e_t e; - e_t e2; + e_t e2; const uint64_t InvalidRID = static_cast(-1); int iter = hjPtr->SearchSet(thrIdx)->getIterator(bucketIdx); - - ZonedDL* zdl1 = dynamic_cast(hjPtr->SearchResult(thrIdx)); - ZonedDL* zdl2 = dynamic_cast(hjPtr->HashResult(thrIdx)); - vector vec1; - vector vec2; - + + ZonedDL* zdl1 = dynamic_cast(hjPtr->SearchResult(thrIdx)); + ZonedDL* zdl2 = dynamic_cast(hjPtr->HashResult(thrIdx)); + vector vec1; + vector vec2; + std::pair::hashIter_t, typename HashJoin::hashIter_t> hashItPair; typename HashJoin::hashIter_t hashIt; typename HashJoin::hash_t* ht = hjPtr->HashTable(thrIdx); @@ -266,7 +266,7 @@ try { // If sendAllSearchSet=true, keep all of the search set. If this is - // a right outer, we are dealing with a join such as + // a right outer, we are dealing with a join such as // col1 = col2 (+) // where col1 is the SearchSet and col2 is the HashSet. We want to include // all of col1 in this case regardless of whether there is a matching col2. @@ -294,10 +294,10 @@ try if(hjPtr->SearchResult(thrIdx)->OID() >= 3000) cout << "JoinByBucket() SearchResult add " << bucketIdx << " [" << e.first << "][" << e.second << "]" << endl; - uint32_t a=0; + uint a=0; e_t b=e_t(); #endif - + // If sendAllSearchSet=false, we already added the search result // before the if condition above. if (!sendAllSearchSet) @@ -327,7 +327,7 @@ try // so no reason to add it to the output datalist or keep searching for more matching values. if(hashIt->second != InvalidRID) { - + // If the matching pair has it's RID set to invalid, it's already been encountered, hashItPair = ht->equal_range(e.second); for(hashIt = hashItPair.first; hashIt != hashItPair.second; hashIt++) @@ -348,19 +348,19 @@ try } else hjPtr->HashResult(thrIdx)->insert(e2); - + #ifdef DEBUG a++; b=v.second; #endif - + // Set the RID to invalid rid now that it's been matched and added to the output datalist. - // This will keep us from duplicating it if it is matched again. - hashIt->second = InvalidRID; - - } + // This will keep us from duplicating it if it is matched again. + hashIt->second = InvalidRID; -#ifdef DEBUG + } + +#ifdef DEBUG cout << "\t\tadded " << b << " " << a << " times" << endl << endl; #endif } @@ -372,14 +372,14 @@ try } // for ( hjPtr... params->timeset.holdTimer(hashJoinStr); - params->timeset.setTimer(insertLastResultsStr); + params->timeset.setTimer(insertLastResultsStr); if (vec1.size() != 0) { hjPtr->SearchResult(thrIdx)->insert(vec1); vec1.clear(); } if (vec2.size() != 0) { hjPtr->HashResult(thrIdx)->insert(vec2); - vec2.clear(); + vec2.clear(); } params->timeset.holdTimer(insertLastResultsStr); @@ -432,7 +432,7 @@ catch (...) } cerr << errMsg.str() << endl; catchHandler(errMsg.str(),hjPtr->sessionId()); -} +} return NULL; } // HashJoinByBucket_thr @@ -577,7 +577,7 @@ void LargeHashJoin::doHashJoin() BDLWrapper< ElementType > setB(Bp); hj = new HashJoin(setA, setB, resultA, resultB, fJoinType, &dlTimes, fOutputJobStepAssociation.statusPtr(), sessionId(), &die); - if (fTableOID2 >= 3000) + if (fTableOID2 >= 3000) { ostringstream logStr2; logStr2 << "LargeHashJoin::run: ses:" << fSessionId << @@ -886,12 +886,12 @@ void StringHashJoinStep::doStringHashJoin() StringElementType se; ElementType e; int id = dlA->getIterator(); - + bdl1 = dynamic_cast(resultA); bdl2 = dynamic_cast(resultB); vector v; v.reserve(ZDL_VEC_SIZE); - if (bdl1) + if (bdl1) { while (dlA->next(id, &se)) { @@ -908,12 +908,12 @@ void StringHashJoinStep::doStringHashJoin() } if (v.size() > 0) resultA->insert(v); - + resultA->endOfInput(); } - - else - { + + else + { while (dlA->next(id, &se)) { if (se.second != CPNULLSTRMARK) @@ -926,8 +926,8 @@ void StringHashJoinStep::doStringHashJoin() } id = dlB->getIterator(); - - if (bdl2) + + if (bdl2) { v.clear(); while (dlB->next(id, &se)) @@ -945,7 +945,7 @@ void StringHashJoinStep::doStringHashJoin() } if (v.size() > 0) resultB->insert(v); - + resultB->endOfInput(); } else diff --git a/dbcon/joblist/largehashjoin.h b/dbcon/joblist/largehashjoin.h index cab7ff7f..a90a0d82 100644 --- a/dbcon/joblist/largehashjoin.h +++ b/dbcon/joblist/largehashjoin.h @@ -17,13 +17,13 @@ #ifndef LARGEHASHJOIN_H #define LARGEHASHJOIN_H -// $Id: largehashjoin.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: largehashjoin.h 8436 2012-04-04 18:18:21Z rdempsey $ // // C++ Implementation: hashjoin // // Author: Jason Rodriguez // -// Description: +// Description: // // // @@ -118,7 +118,7 @@ class HjHasher public: uint32_t operator()(const std::string& v) const { - return hasher(v.c_str(), (uint32_t) v.length()); + return hasher(v.c_str(), (uint) v.length()); } }; @@ -155,7 +155,7 @@ class HashJoin uint32_t startBucket; uint32_t numBuckets; uint32_t thrIdx; - TimeSet timeset; + TimeSet timeset; JSTimeStamp dlTimes; volatile bool *die; } thrParams_t; @@ -169,14 +169,14 @@ class HashJoin const SErrorInfo& status, uint32_t sessionId, volatile bool *die); - + HashJoin(); HashJoin(const HashJoin& hj); JoinType getJoinType() { return fJoinType; } virtual ~HashJoin(); - virtual int performJoin(const uint32_t thrCount=1); + virtual int performJoin(const uint thrCount=1); virtual int performThreadedJoin(const uint32_t numThreads); - + joblist::BDLWrapper* Set1() { return & fSet1;} joblist::BDLWrapper* Set2() { return & fSet2;} joblist::DataList* Result1() { return fResult1;} @@ -217,7 +217,7 @@ class HashJoin joblist::DataList* fResult1; joblist::DataList* fResult2; - // convenience pointers + // convenience pointers BucketDL *fSearchSet; BucketDL *fHashSet; joblist::DataList* fSearchResult; @@ -242,7 +242,7 @@ HashJoin::HashJoin(joblist::BDLWrapper& set1, joblist::DataList* result1, joblist::DataList* result2, JoinType joinType, - JSTimeStamp *dlt, + JSTimeStamp *dlt, const SErrorInfo& status, uint32_t sessionId, volatile bool *d) : fTimeSet(),fStatus(status), fSessionId(sessionId) @@ -287,8 +287,8 @@ int HashJoin::performThreadedJoin(const uint32_t numThreads) boost::scoped_array::thrParams_t> params(new typename HashJoin::thrParams_t[numThreads]); uint32_t maxThreads=numThreads; int realCnt=0; - uint32_t bucketsPerThr=0; - uint32_t totalBuckets=0; + uint bucketsPerThr=0; + uint totalBuckets=0; // TODO: maybe this should throw an exception if (maxThreads<=0 || maxThreads >32) { @@ -302,10 +302,10 @@ int HashJoin::performThreadedJoin(const uint32_t numThreads) maxThreads=Set1()->bucketCount(); } - bucketsPerThr=(uint32_t)(Set1()->bucketCount()/maxThreads); - uint32_t idx=0; + bucketsPerThr=(uint)(Set1()->bucketCount()/maxThreads); + uint idx=0; for(idx=0; idxbucketCount(); idx++) - { + { params[idx].hjptr = this; params[idx].startBucket=totalBuckets; params[idx].numBuckets=bucketsPerThr; @@ -405,7 +405,7 @@ int HashJoin::performThreadedJoin(const uint32_t numThreads) // Select earliest read time as overall firstReadTime if ( params[i].dlTimes.FirstReadTime().tv_sec < dlTimes->FirstReadTime().tv_sec ) dlTimes->setFirstReadTime( params[i].dlTimes.FirstReadTime() ); - } + } controls.reset(); return realCnt; @@ -413,7 +413,7 @@ int HashJoin::performThreadedJoin(const uint32_t numThreads) // defaults to 1 thread template -int HashJoin::performJoin(const uint32_t thrCount) +int HashJoin::performJoin(const uint thrCount) { return performThreadedJoin(thrCount); } @@ -438,7 +438,7 @@ void HashJoin::createHash(BucketDL *srcBucketDL, timespec ts1, ts2, diff; clock_gettime(CLOCK_REALTIME, &ts1); #endif - uint32_t bucketIter = srcBucketDL->getIterator((int)bucketNum); + uint bucketIter = srcBucketDL->getIterator((int)bucketNum); // @bug 828. catch hashjoin starting time more = srcBucketDL->next(bucketNum, bucketIter, &e); if (thrDlTimes.FirstReadTime().tv_sec == 0) { @@ -456,7 +456,7 @@ void HashJoin::createHash(BucketDL *srcBucketDL, // and the passed bucket datalist contains colb, we will go ahead and populate the output datalist here // because all of colB should be returned regardless of whether there is a matching colA. if(populateResult) - { + { result->insert(e); } @@ -490,7 +490,7 @@ void HashJoin::createHash(BucketDL *srcBucketDL, << bucketNum << ": " << diff.tv_sec << "s " << diff.tv_nsec << "ns" - << std::endl; + << std::endl; #endif } // createHash diff --git a/dbcon/joblist/lbidlist.cpp b/dbcon/joblist/lbidlist.cpp index 885f0fa6..314a9b92 100644 --- a/dbcon/joblist/lbidlist.cpp +++ b/dbcon/joblist/lbidlist.cpp @@ -17,7 +17,7 @@ /****************************************************************************** -* $Id: lbidlist.cpp 9655 2013-06-25 23:08:13Z xlou $ +* $Id: lbidlist.cpp 8727 2012-07-22 19:04:25Z dcathey $ * ******************************************************************************/ #include @@ -57,18 +57,19 @@ LBIDList::LBIDList() } /** @LBIDList(oid, debug) - * + * * Create a new LBIDList structure. * Used to apply CP logic but cannot perform updates of CP data */ LBIDList::LBIDList(const int debug) + { fDebug=debug; } - + /** @LBIDList(oid, debug) - * + * * Create a new LBIDList structure. * ctor that prepares the object for updates * of the CP data. @@ -79,9 +80,9 @@ LBIDList::LBIDList(const CalpontSystemCatalog::OID oid, { init(oid, debug); } - + /** @LBIDList::Init() Initializes a LBIDList structure - * + * * Create a new LBIDList structure and initialize it */ @@ -145,8 +146,8 @@ LBIDList::~LBIDList() } -void LBIDList::Dump(long Index, int Count) const -{ + void LBIDList::Dump(long Index, int Count) const + { LBIDRange LBIDR; const int RangeCount = LBIDRanges.size(); @@ -159,16 +160,15 @@ void LBIDList::Dump(long Index, int Count) const } cout << endl; -} + } // Store max/min structure for update later. lbidPartitionVector serves a list of lbid,max,min to update // when the primitive returns with valid max/min values and the brm returns an invalid flag for the // requested lbid // -bool LBIDList::GetMinMax(int64_t& min, int64_t& max, int64_t& seq, int64_t lbid, - const std::vector* pEMEntries, - execplan::CalpontSystemCatalog::ColDataType colDataType) -{ + bool LBIDList::GetMinMax(int64_t& min, int64_t& max, int64_t& seq, + int64_t lbid, const std::vector* pEMEntries) + { bool bRet = true; MinMaxPartition *mmp=NULL; LBIDRange LBIDR; @@ -194,11 +194,11 @@ bool LBIDList::GetMinMax(int64_t& min, int64_t& max, int64_t& seq, int64_t lbid, seq = seq32; #ifdef DEBUG if (IS_VERBOSE) - cout << i + cout << i << " GetMinMax() ret " << retVal << " Min " << min << " Max " << max - << " lbid " << lbid + << " lbid " << lbid << " seq32 " << seq32 << endl; #endif @@ -211,16 +211,8 @@ bool LBIDList::GetMinMax(int64_t& min, int64_t& max, int64_t& seq, int64_t lbid, mmp->lbid = (int64_t)LBIDR.start; mmp->lbidmax = (int64_t)(LBIDR.start+LBIDR.size); mmp->seq = seq32; - if (isUnsigned(colDataType)) - { - mmp->max = 0; - mmp->min = static_cast(numeric_limits::max()); - } - else - { - mmp->max = numeric_limits::min(); - mmp->min = numeric_limits::max(); - } + mmp->max = numeric_limits::min(); + mmp->min = numeric_limits::max(); mmp->isValid = retVal; mmp->blksScanned = 0; lbidPartitionVector.push_back(mmp); @@ -231,11 +223,10 @@ bool LBIDList::GetMinMax(int64_t& min, int64_t& max, int64_t& seq, int64_t lbid, } return false; -} + } bool LBIDList::GetMinMax(int64_t *min, int64_t *max, int64_t *seq, - int64_t lbid, const tr1::unordered_map &entries, - execplan::CalpontSystemCatalog::ColDataType colDataType) + int64_t lbid, const tr1::unordered_map &entries) { tr1::unordered_map::const_iterator it = entries.find(lbid); @@ -250,16 +241,8 @@ bool LBIDList::GetMinMax(int64_t *min, int64_t *max, int64_t *seq, mmp->lbid = lbid; mmp->lbidmax = lbid + (entry.range.size * 1024); mmp->seq = entry.partition.cprange.sequenceNum; - if (isUnsigned(colDataType)) - { - mmp->max = 0; - mmp->min = static_cast(numeric_limits::max()); - } - else - { - mmp->max = numeric_limits::min(); - mmp->min = numeric_limits::max(); - } + mmp->max = numeric_limits::min(); + mmp->min = numeric_limits::max(); mmp->isValid = entry.partition.cprange.isValid; mmp->blksScanned = 0; lbidPartitionVector.push_back(mmp); @@ -304,7 +287,7 @@ int LBIDList::getMinMaxFromEntries(int64_t& min, int64_t& max, int32_t& seq, << " sz " << lbidPartitionVector.size() << endl; #endif - for(uint32_t i = 0; imin << "/" << mmp->max - << " lbid " << lbid - << " seq " << mmp->seq + << " lbid " << lbid + << " seq " << mmp->seq << " valid " << mmp->isValid << endl; #endif if (!validData) { @@ -326,10 +309,8 @@ int LBIDList::getMinMaxFromEntries(int64_t& min, int64_t& max, int32_t& seq, return; } - if (mmp->isValid == BRM::CP_INVALID) - { - if (execplan::isCharType(type)) - { + if (mmp->isValid == BRM::CP_INVALID) { + if (isChar(type)) { if (order_swap(min) < order_swap(mmp->min) || mmp->min == numeric_limits::max()) mmp->min = min; @@ -337,29 +318,18 @@ int LBIDList::getMinMaxFromEntries(int64_t& min, int64_t& max, int32_t& seq, mmp->max == numeric_limits::min()) mmp->max = max; } - else if (execplan::isUnsigned(type)) - { - if (static_cast(min) < static_cast(mmp->min)) - mmp->min = min; - if (static_cast(max) > static_cast(mmp->max)) - mmp->max = max; + else { + if (min < mmp->min) mmp->min = min; + if (max > mmp->max) mmp->max = max; } - else - { - if (min < mmp->min) - mmp->min = min; - if (max > mmp->max) - mmp->max = max; - } - } #ifdef DEBUG if (IS_VERBOSE) cout << "UpdateMinMax() new Mn/Mx " - << mmp->min << "/" << mmp->max << " " - << " lbid " << lbid - << " seq " << mmp->seq + << mmp->min << "/" << mmp->max << " " + << " lbid " << lbid + << " seq " << mmp->seq << " valid " << mmp->isValid << endl; #endif return; @@ -372,57 +342,57 @@ void LBIDList::UpdateAllPartitionInfo() MinMaxPartition *mmp=NULL; #ifdef DEBUG if (IS_VERBOSE) - cout << "LBIDList::UpdateAllPartitionInfo() size " << lbidPartitionVector.size() << endl; + cout << "LBIDList::UpdateAllPartitionInfo() size " << lbidPartitionVector.size() << endl; #endif - // @bug 1970 - Added new dbrm interface that takes a vector of CPInfo objects to set the min and max for multiple - // extents at a time. This cuts the number of calls way down and improves performance. - CPInfo cpInfo; - vector vCpInfo; + // @bug 1970 - Added new dbrm interface that takes a vector of CPInfo objects to set the min and max for multiple + // extents at a time. This cuts the number of calls way down and improves performance. + CPInfo cpInfo; + vector vCpInfo; - uint32_t cpUpdateInterval = 25000; - for (uint32_t i=0;iisValid == BRM::CP_INVALID) && (mmp->blksScanned > 0)) - { - cpInfo.firstLbid = mmp->lbid; - cpInfo.max = mmp->max; - cpInfo.min = mmp->min; - cpInfo.seqNum = (int32_t)mmp->seq; - vCpInfo.push_back(cpInfo); - - // Limit the number of extents to update at a time. A map is created within the call and this will prevent unbounded - // memory. Probably will never approach this limit but just in case. - if ((i+1)%cpUpdateInterval == 0 || (i+1) == lbidPartitionVector.size()) - { - em->setExtentsMaxMin(vCpInfo); - vCpInfo.clear(); - } + //@bug4543: only update extentmap CP if blks were scanned for this extent + if ((mmp->isValid == BRM::CP_INVALID) && (mmp->blksScanned > 0)) + { + cpInfo.firstLbid = mmp->lbid; + cpInfo.max = mmp->max; + cpInfo.min = mmp->min; + cpInfo.seqNum = (int32_t)mmp->seq; + vCpInfo.push_back(cpInfo); + + // Limit the number of extents to update at a time. A map is created within the call and this will prevent unbounded + // memory. Probably will never approach this limit but just in case. + if((i+1)%cpUpdateInterval == 0 || (i+1) == lbidPartitionVector.size()) + { + em->setExtentsMaxMin(vCpInfo); + vCpInfo.clear(); + } #ifdef DEBUG - if (IS_VERBOSE) - cout << "LBIDList::UpdateAllPartitionInfo() updated mmp.lbid " << mmp->lbid - << " mmp->max " << mmp->max - << " mmp->min " << mmp->min - << " seq " << mmp->seq - << " blksScanned " << mmp->blksScanned - << endl; + if (IS_VERBOSE) + cout << "LBIDList::UpdateAllPartitionInfo() updated mmp.lbid " << mmp->lbid + << " mmp->max " << mmp->max + << " mmp->min " << mmp->min + << " seq " << mmp->seq + << " blksScanned " << mmp->blksScanned + << endl; #endif - mmp->isValid = BRM::CP_VALID; - } - - //delete mmp; + mmp->isValid = BRM::CP_VALID; + } + + //delete mmp; } - // Send the last batch of CP info to BRM. - if (!vCpInfo.empty()) - { - em->setExtentsMaxMin(vCpInfo); - } + // Send the last batch of CP info to BRM. + if (!vCpInfo.empty()) + { + em->setExtentsMaxMin(vCpInfo); + } } bool LBIDList::IsRangeBoundary(uint64_t lbid) @@ -444,27 +414,21 @@ bool LBIDList::IsRangeBoundary(uint64_t lbid) * returns false if casual partitioning predicate optimization is not possible for datatype. */ -bool LBIDList::CasualPartitionDataType(const CalpontSystemCatalog::ColDataType type, const uint8_t size) const +bool LBIDList::CasualPartitionDataType(const uint8_t type, const uint8_t size) const { switch(type) { - case CalpontSystemCatalog::CHAR: + case WriteEngine::CHAR: return size <9; - case CalpontSystemCatalog::VARCHAR: + case WriteEngine::VARCHAR: return size <8; - case CalpontSystemCatalog::TINYINT: - case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::MEDINT: - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UDECIMAL: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: + case WriteEngine::TINYINT: + case WriteEngine::SMALLINT: + case WriteEngine::MEDINT: + case WriteEngine::INT: + case WriteEngine::BIGINT: + case WriteEngine::DECIMAL: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return true; default: return false; @@ -473,7 +437,7 @@ bool LBIDList::CasualPartitionDataType(const CalpontSystemCatalog::ColDataType t /* Check for casual partitioning predicate optimization. This function applies the predicate using * column Min/Max values to determine if the scan is required. - * + * * returns true if scan should be executed. * returns false if casual partitioning predicate optimization has eliminated the scan. */ @@ -521,54 +485,65 @@ inline bool LBIDList::compareVal(const T& Min, const T& Max, const T& value, cha return true; } -bool LBIDList::checkSingleValue(int64_t min, int64_t max, int64_t value, - execplan::CalpontSystemCatalog::ColDataType type) + +template +inline bool LBIDList::checkNull(execplan::CalpontSystemCatalog::ColDataType type, T val, T nullVal, T nullCharVal) { - if (isCharType(type)) - { - uint64_t mmin = order_swap(min); - uint64_t mmax = order_swap(max); - uint64_t vvalue = order_swap(value); + if (isChar(type)) return nullCharVal == val; + else return (nullVal == val); +} + +inline bool LBIDList::checkNull32(execplan::CalpontSystemCatalog::ColDataType type, int32_t val) +{ + uint32_t uval = static_cast(val); + + if (isChar(type)) + return (CHAR4NULL == uval); + else if (execplan::CalpontSystemCatalog::DATE == type) + return (DATENULL == uval); + else + return (NULL_INT32 == val); +} + +inline bool LBIDList::checkNull64(execplan::CalpontSystemCatalog::ColDataType type, int64_t val) +{ + uint64_t uval = static_cast(val); + + if (isChar(type)) + return (CHAR8NULL == uval); + else if (execplan::CalpontSystemCatalog::DATETIME == type) + return (DATETIMENULL == uval); + else + return (NULL_INT64 == val); +} + +bool LBIDList::checkSingleValue(int64_t min, int64_t max, int64_t value, bool isChar) +{ + if (isChar) { + uint64_t mmin = order_swap(min), mmax = order_swap(max), vvalue = order_swap(value); return (vvalue >= mmin && vvalue <= mmax); } - else if (isUnsigned(type)) - { - return (static_cast(value) >= static_cast(min) && - static_cast(value) <= static_cast(max)); - } else - { return (value >= min && value <= max); - } } bool LBIDList::checkRangeOverlap(int64_t min, int64_t max, int64_t tmin, int64_t tmax, - execplan::CalpontSystemCatalog::ColDataType type) + bool isChar) { - if (isCharType(type)) - { - uint64_t min2 = order_swap(min); - uint64_t max2 = order_swap(max); - uint64_t tmin2 = order_swap(tmin); - uint64_t tmax2 = order_swap(tmax); + if (isChar) { + uint64_t min2 = order_swap(min), max2 = order_swap(max), tmin2 = order_swap(tmin), + tmax2 = order_swap(tmax); return (tmin2 <= max2 && tmax2 >= min2); } - else if (isUnsigned(type)) - { - return (static_cast(tmin) <= static_cast(max) && - static_cast(tmax) >= static_cast(min)); - } else - { return (tmin <= max && tmax >= min); - } } -bool LBIDList::CasualPartitionPredicate(const int64_t Min, - const int64_t Max, +bool LBIDList::CasualPartitionPredicate(const int64_t Min, + const int64_t Max, const messageqcpp::ByteStream* bs, - const uint16_t NOPS, - const execplan::CalpontSystemCatalog::ColType& ct, + const uint16_t NOPS, + const execplan::CalpontSystemCatalog::ColType& ct, const uint8_t BOP) { @@ -576,8 +551,6 @@ bool LBIDList::CasualPartitionPredicate(const int64_t Min, const char *MsgDataPtr = (const char *) bs->buf(); bool scan = true; int64_t value=0; - bool bIsUnsigned = execplan::isUnsigned(ct.colDataType); - bool bIsChar = execplan::isCharType(ct.colDataType); for (int i=0; i(val); - } - } - } - else - { - switch (ct.colWidth) - { - case 1: { - int8_t val = *(int8_t*)MsgDataPtr; - value = val; - break; - } - case 2: { - int16_t val = *(int16_t*)MsgDataPtr; - value = val; - break; - } - case 4: { - int32_t val = *(int32_t*)MsgDataPtr; - value = val; - break; - } - case 8: { - int64_t val = *(int64_t*)MsgDataPtr; - value = val; - } - } - } - // Should we also check for empty here? - if (isNull(value, ct)) // This will work even if the data column is unsigned. + switch (ct.colWidth) { - continue; + case 1: { + int8_t val = *(int8_t*)MsgDataPtr; + if (checkNull(ct.colDataType, val, NULL_INT8, CHAR1NULL)) + continue; + value = val; + break; + } + case 2: { + int16_t val = *(int16_t*)MsgDataPtr; + if (checkNull(ct.colDataType, val, NULL_INT16, CHAR2NULL)) + continue; + value = val; + break; + } + case 4: { + int32_t val = *(int32_t*)MsgDataPtr; + if (checkNull32(ct.colDataType, val)) + continue; + value = val; + break; + } + case 8: { + int64_t val = *(int64_t*)MsgDataPtr; + if (checkNull64(ct.colDataType, val)) + continue; + value = val; + } } MsgDataPtr += ct.colWidth; + if (pos > length) { +#ifdef DEBUG + cout << "CasualPartitionPredicate: Filter parsing went beyond the end of the filter string!" << endl; +#endif + return true; + } - if (bIsChar && 1 < ct.colWidth) - { + if (isChar(ct.colDataType) && 1 < ct.colWidth) { scan = compareVal(order_swap(Min), order_swap(Max), order_swap(value), op, lcf); -// cout << "scan=" << (uint32_t) scan << endl; - } - else if (bIsUnsigned) - { - scan = compareVal(static_cast(Min), static_cast(Max), static_cast(value), op, lcf); +// cout << "scan=" << (uint) scan << endl; } else - { scan = compareVal(Min, Max, value, op, lcf); - } if (BOP == BOP_AND && !scan) { break; diff --git a/dbcon/joblist/lbidlist.h b/dbcon/joblist/lbidlist.h index 187dde9a..40c22f38 100644 --- a/dbcon/joblist/lbidlist.h +++ b/dbcon/joblist/lbidlist.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: lbidlist.h 9655 2013-06-25 23:08:13Z xlou $ +* $Id: lbidlist.h 8729 2012-07-22 19:29:01Z dcathey $ * * ***********************************************************************/ @@ -38,8 +38,8 @@ #include #endif -namespace joblist -{ +namespace joblist +{ typedef BRM::LBIDRange_v LBIDRangeVector; @@ -75,19 +75,16 @@ class LBIDList virtual ~LBIDList(); void Dump(long Index, int Count) const; - uint32_t GetRangeSize() const { return LBIDRanges.size() ? LBIDRanges.at(0).size : 0; } + u_int32_t GetRangeSize() const { return LBIDRanges.size() ? LBIDRanges.at(0).size : 0; } - // Functions to handle min/max values per lbid for casual partitioning; + // New functions to handle min/max values per lbid for casual partitioning; // If pEMEntries is provided, then min/max will be extracted from that - // vector, else extents in BRM will be searched. If type is unsigned, caller - // should static cast returned min and max to uint64_t + // vector, else extents in BRM will be searched. bool GetMinMax(int64_t& min, int64_t& max, int64_t& seq, int64_t lbid, - const std::vector* pEMEntries, - execplan::CalpontSystemCatalog::ColDataType type); + const std::vector* pEMEntries); bool GetMinMax(int64_t *min, int64_t *max, int64_t *seq, int64_t lbid, - const std::tr1::unordered_map &entries, - execplan::CalpontSystemCatalog::ColDataType type); + const std::tr1::unordered_map &entries); void UpdateMinMax(int64_t min, int64_t max, int64_t lbid, execplan::CalpontSystemCatalog::ColDataType type, bool validData = true); @@ -96,22 +93,20 @@ class LBIDList bool IsRangeBoundary(uint64_t lbid); - bool CasualPartitionPredicate(const int64_t Min, - const int64_t Max, + bool CasualPartitionPredicate(const int64_t Min, + const int64_t Max, const messageqcpp::ByteStream* MsgDataPtr, - const uint16_t NOPS, - const execplan::CalpontSystemCatalog::ColType& ct, + const uint16_t NOPS, + const execplan::CalpontSystemCatalog::ColType& ct, const uint8_t BOP); - bool checkSingleValue(int64_t min, int64_t max, int64_t value, - execplan::CalpontSystemCatalog::ColDataType type); - - bool checkRangeOverlap(int64_t min, int64_t max, int64_t tmin, int64_t tmax, - execplan::CalpontSystemCatalog::ColDataType type); + bool checkSingleValue(int64_t min, int64_t max, int64_t value, bool isCharColumn); + + bool checkRangeOverlap(int64_t min, int64_t max, int64_t tmin, int64_t tmax, bool isCharColumn); // check the column data type and the column size to determine if it // is a data type to apply casual paritioning. - bool CasualPartitionDataType(const execplan::CalpontSystemCatalog::ColDataType type, const uint8_t size) const; + bool CasualPartitionDataType(const uint8_t type, const uint8_t size) const; LBIDList(const LBIDList& rhs) { copyLbidList(rhs); } @@ -125,6 +120,17 @@ class LBIDList template inline bool compareVal(const T& Min, const T& Max, const T& value, char op, uint8_t lcf); + inline bool isChar(execplan::CalpontSystemCatalog::ColDataType type) + { + return (execplan::CalpontSystemCatalog::VARCHAR == type || execplan::CalpontSystemCatalog::CHAR == type); + } + + template + inline bool checkNull(execplan::CalpontSystemCatalog::ColDataType type, T val, T nullVal, T nullCharVal); + + inline bool checkNull32(execplan::CalpontSystemCatalog::ColDataType type, int32_t val); + inline bool checkNull64(execplan::CalpontSystemCatalog::ColDataType type, int64_t val); + int getMinMaxFromEntries(int64_t& min, int64_t& max, int32_t& seq, int64_t lbid, const std::vector& EMEntries); diff --git a/dbcon/joblist/libjoblist.rc b/dbcon/joblist/libjoblist.rc deleted file mode 100644 index 7b0e36a4..00000000 --- a/dbcon/joblist/libjoblist.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB Job List API" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "libjoblist.dll" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "libjoblist.dll" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/dbcon/joblist/libjoblist.vcxproj b/dbcon/joblist/libjoblist.vcxproj deleted file mode 100644 index 0749dc03..00000000 --- a/dbcon/joblist/libjoblist.vcxproj +++ /dev/null @@ -1,474 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {CBA13EF7-ECA1-42F4-8CE2-9E18E24DCDE2} - libjoblist - - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - true - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - true - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - true - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\mysqlcl_idb;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - JOBLIST_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;$(SolutionDir)..\..\x64\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\mysqlcl_idb;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - JOBLIST_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - false - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\mysqlcl_idb;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - JOBLIST_DLLEXPORT;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - false - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\mysqlcl_idb;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - JOBLIST_DLLEXPORT;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - false - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - false - - - $(SolutionDir)..\..\signit "InfiniDB Job List API" $(SolutionDir)..\..x64\Release\libjoblist.dll - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\mysqlcl_idb;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - JOBLIST_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;$(SolutionDir)..\build\x64\EnterpriseRelease;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\mysqlcl_idb;$(SolutionDir)..\utils\windowfunction;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - JOBLIST_DLLEXPORT;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - false - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - false - - - $(SolutionDir)..\..\signit "InfiniDB Job List API" $(SolutionDir)..\..\x64\EnterpriseRelease\libjoblist.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {fc0ba86e-2cc2-4ce8-ac62-16b662fe5b29} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {0bbaeacb-3336-4406-acfb-255669a3b9cf} - - - {3238cd73-8ffd-44a7-aa5f-815beef8f402} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {0dd34627-b046-4415-80cf-d0fba4e069cb} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - - - - \ No newline at end of file diff --git a/dbcon/joblist/libjoblist.vcxproj.filters b/dbcon/joblist/libjoblist.vcxproj.filters deleted file mode 100644 index c82123ef..00000000 --- a/dbcon/joblist/libjoblist.vcxproj.filters +++ /dev/null @@ -1,374 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/dbcon/joblist/limitedorderby.cpp b/dbcon/joblist/limitedorderby.cpp index 2069536b..a095465d 100644 --- a/dbcon/joblist/limitedorderby.cpp +++ b/dbcon/joblist/limitedorderby.cpp @@ -15,13 +15,14 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: limitedorderby.cpp 9581 2013-05-31 13:46:14Z pleblanc $ +// $Id: limitedorderby.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include //#define NDEBUG #include #include +#include using namespace std; #include @@ -31,12 +32,16 @@ using namespace boost; #include "exceptclasses.h" using namespace logging; +#include "calpontsystemcatalog.h" +using namespace execplan; + #include "rowgroup.h" using namespace rowgroup; -#include "idborderby.h" -using namespace ordering; +#include "dataconvert.h" +using namespace dataconvert; +#include "jobstep.h" #include "jlf_common.h" #include "limitedorderby.h" @@ -44,11 +49,301 @@ using namespace ordering; namespace joblist { +int IntCompare::operator()(IdbOrderBy* l, uint8_t* r1, uint8_t* r2) +{ + l->row1().setData(r1); + l->row2().setData(r2); + + bool b1 = l->row1().isNullValue(fIndex); + bool b2 = l->row2().isNullValue(fIndex); + + int ret = 0; + + if (b1 == true || b2 == true) + { + if (b1 == false && b2 == true) + ret = 1; + else if (b1 == true && b2 == false) + ret = -1; + } + else + { + int64_t v1 = l->row1().getIntField(fIndex); + int64_t v2 = l->row2().getIntField(fIndex); + + if (v1 > v2) + ret = 1; + else if (v1 < v2) + ret = -1; + } + + return ret * fAsc; +} + + +int UintCompare::operator()(IdbOrderBy* l, uint8_t* r1, uint8_t* r2) +{ + l->row1().setData(r1); + l->row2().setData(r2); + + bool b1 = l->row1().isNullValue(fIndex); + bool b2 = l->row2().isNullValue(fIndex); + + int ret = 0; + + if (b1 == true || b2 == true) + { + if (b1 == false && b2 == true) + ret = 1; + else if (b1 == true && b2 == false) + ret = -1; + } + else + { + uint64_t v1 = l->row1().getUintField(fIndex); + uint64_t v2 = l->row2().getUintField(fIndex); + + if (v1 > v2) + ret = 1; + else if (v1 < v2) + ret = -1; + } + + return ret * fAsc; +} + + +int StringCompare::operator()(IdbOrderBy* l, uint8_t* r1, uint8_t* r2) +{ + l->row1().setData(r1); + l->row2().setData(r2); + + bool b1 = l->row1().isNullValue(fIndex); + bool b2 = l->row2().isNullValue(fIndex); + + int ret = 0; + + if (b1 == true || b2 == true) + { + if (b1 == false && b2 == true) + ret = 1; + else if (b1 == true && b2 == false) + ret = -1; + } + else + { + string v1 = l->row1().getStringField(fIndex); + string v2 = l->row2().getStringField(fIndex); + + if (v1 > v2) + ret = 1; + else if (v1 < v2) + ret = -1; + } + + return ret * fAsc; +} + + +int DoubleCompare::operator()(IdbOrderBy* l, uint8_t* r1, uint8_t* r2) +{ + l->row1().setData(r1); + l->row2().setData(r2); + + bool b1 = l->row1().isNullValue(fIndex); + bool b2 = l->row2().isNullValue(fIndex); + + int ret = 0; + + if (b1 == true || b2 == true) + { + if (b1 == false && b2 == true) + ret = 1; + else if (b1 == true && b2 == false) + ret = -1; + } + else + { + double v1 = l->row1().getDoubleField(fIndex); + double v2 = l->row2().getDoubleField(fIndex); + + if (v1 > v2) + ret = 1; + else if (v1 < v2) + ret = -1; + } + + return ret * fAsc; +} + + +int FloatCompare::operator()(IdbOrderBy* l, uint8_t* r1, uint8_t* r2) +{ + l->row1().setData(r1); + l->row2().setData(r2); + + bool b1 = l->row1().isNullValue(fIndex); + bool b2 = l->row2().isNullValue(fIndex); + + int ret = 0; + + if (b1 == true || b2 == true) + { + if (b1 == false && b2 == true) + ret = 1; + else if (b1 == true && b2 == false) + ret = -1; + } + else + { + float v1 = l->row1().getFloatField(fIndex); + float v2 = l->row2().getFloatField(fIndex); + + if (v1 > v2) + ret = 1; + else if (v1 < v2) + ret = -1; + } + + return ret * fAsc; +} + + +// IdbOrderBy class implementation +IdbOrderBy::IdbOrderBy() : + fDistinct(false), fMemSize(0), fRowsPerRG(8192), fErrorCode(0), fRm(NULL) +{ +} + + +IdbOrderBy::~IdbOrderBy() +{ + if (fRm) + fRm->returnMemory(fMemSize); + + // delete compare objects + vector::iterator i = fRule.fCompares.begin(); + while (i != fRule.fCompares.end()) + delete *i++; +} + + +void IdbOrderBy::initialize(const RowGroup& rg) +{ + // initialize rows + fRowGroup = rg; + + uint64_t newSize = fRowsPerRG * rg.getRowSize(); + if (!fRm->getMemory(newSize)) + { + cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) + << " @" << __FILE__ << ":" << __LINE__; + throw IDBExcept(fErrorCode); + } + fMemSize += newSize; + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); + fRowGroup.resetRowGroup(0); + fRowGroup.initRow(&fRow0); + fRowGroup.initRow(&fRow1); + fRowGroup.initRow(&fRow2); + fRowGroup.getRow(0, &fRow0); + + // set compare functors + const vector& types = fRowGroup.getColTypes(); + for (vector >::iterator i = fOrderByCond.begin(); i != fOrderByCond.end(); i++) + { + switch (types[i->first]) + { + case CalpontSystemCatalog::TINYINT: + case CalpontSystemCatalog::SMALLINT: + case CalpontSystemCatalog::MEDINT: + case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::BIGINT: + case CalpontSystemCatalog::DECIMAL: + { + Compare* c = new IntCompare(i->first, i->second); + fRule.fCompares.push_back(c); + break; + } + case CalpontSystemCatalog::CHAR: + case CalpontSystemCatalog::VARCHAR: + { + Compare* c = new StringCompare(i->first, i->second); + fRule.fCompares.push_back(c); + break; + } + case CalpontSystemCatalog::DOUBLE: + { + Compare* c = new DoubleCompare(i->first, i->second); + fRule.fCompares.push_back(c); + break; + } + case CalpontSystemCatalog::FLOAT: + { + Compare* c = new FloatCompare(i->first, i->second); + fRule.fCompares.push_back(c); + break; + } + case CalpontSystemCatalog::DATE: + case CalpontSystemCatalog::DATETIME: + { + Compare* c = new UintCompare(i->first, i->second); + fRule.fCompares.push_back(c); + break; + } + default: + { + break; + } + } + } + + if (fDistinct) + { + uint64_t keyLength = getKeyLength(); + utils::TupleHasher hasher(keyLength); + utils::TupleComparator comp(keyLength); + fPool.reset(new utils::SimplePool); + utils::SimpleAllocator > alloc(fPool); + fDistinctMap.reset(new DistinctMap_t(10, hasher, comp, alloc)); + } +} + + +bool IdbOrderBy::getData(boost::shared_array& data) +{ + if (fDataQueue.empty()) + return false; + + data = fDataQueue.front(); + fDataQueue.pop(); + + return true; +} + + +//bool IdbOrderBy::CompareRule::less(const uint8_t* r1, const uint8_t* r2) +bool IdbOrderBy::CompareRule::less(uint8_t* r1, uint8_t* r2) +{ + for (vector::iterator i = fCompares.begin(); i != fCompares.end(); i++) + { + int c = ((*(*i))(fOrderBy, r1, r2)); + + if (c < 0) + return true; + else if (c > 0) + return false; + } + + return false; +} + // LimitedOrderBy class implementation LimitedOrderBy::LimitedOrderBy() : fStart(0), fCount(-1) { - fRule.fIdbCompare = this; + fRule.fOrderBy = this; } @@ -60,11 +355,10 @@ LimitedOrderBy::~LimitedOrderBy() void LimitedOrderBy::initialize(const RowGroup& rg, const JobInfo& jobInfo) { fRm = &jobInfo.rm; - fSessionMemLimit = jobInfo.umMemLimit; fErrorCode = ERR_LIMIT_TOO_BIG; // locate column position in the rowgroup - map keyToIndexMap; + map keyToIndexMap; for (uint64_t i = 0; i < rg.getKeys().size(); ++i) { if (keyToIndexMap.find(rg.getKeys()[i]) == keyToIndexMap.end()) @@ -74,9 +368,9 @@ void LimitedOrderBy::initialize(const RowGroup& rg, const JobInfo& jobInfo) vector >::const_iterator i = jobInfo.orderByColVec.begin(); for ( ; i != jobInfo.orderByColVec.end(); i++) { - map::iterator j = keyToIndexMap.find(i->first); + map::iterator j = keyToIndexMap.find(i->first); idbassert(j != keyToIndexMap.end()); - fOrderByCond.push_back(IdbSortSpec(j->second, i->second)); + fOrderByCond.push_back(make_pair(j->second, i->second)); } // limit row count info @@ -91,33 +385,26 @@ void LimitedOrderBy::initialize(const RowGroup& rg, const JobInfo& jobInfo) uint64_t LimitedOrderBy::getKeyLength() const { - //return (fRow0.getSize() - 2); - return fRow0.getColumnCount(); + return (fRow0.getSize() - 2); } void LimitedOrderBy::processRow(const rowgroup::Row& row) { // check if this is a distinct row - if (fDistinct && fDistinctMap->find(row.getPointer()) != fDistinctMap->end()) - return; - - // @bug5312, limit count is 0, do nothing. - if (fCount == 0) + if (fDistinct && fDistinctMap->find(row.getData() + 2) != fDistinctMap->end()) return; // if the row count is less than the limit if (fOrderByQueue.size() < fStart+fCount) { - copyRow(row, &fRow0); - //memcpy(fRow0.getData(), row.getData(), row.getSize()); + memcpy(fRow0.getData(), row.getData(), row.getSize()); OrderByRow newRow(fRow0, fRule); fOrderByQueue.push(newRow); // add to the distinct map if (fDistinct) - fDistinctMap->insert(fRow0.getPointer()); - //fDistinctMap->insert(make_pair((fRow0.getData()+2), fRow0.getData())); + fDistinctMap->insert(make_pair((fRow0.getData()+2), fRow0.getData())); fRowGroup.incRowCount(); fRow0.nextRow(); @@ -126,37 +413,32 @@ void LimitedOrderBy::processRow(const rowgroup::Row& row) { fDataQueue.push(fData); uint64_t newSize = fRowsPerRG * fRowGroup.getRowSize(); - if (!fRm->getMemory(newSize, fSessionMemLimit)) + if (!fRm->getMemory(newSize)) { cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) << " @" << __FILE__ << ":" << __LINE__; throw IDBExcept(fErrorCode); } fMemSize += newSize; - fData.reinit(fRowGroup, fRowsPerRG); - fRowGroup.setData(&fData); + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); fRowGroup.resetRowGroup(0); fRowGroup.getRow(0, &fRow0); } } - else if (fOrderByCond.size() > 0 && fRule.less(row.getPointer(), fOrderByQueue.top().fData)) + else if (fOrderByCond.size() > 0 && fRule.less(row.getData(), fOrderByQueue.top().fData)) { OrderByRow swapRow = fOrderByQueue.top(); - row1.setData(swapRow.fData); if (!fDistinct) { - copyRow(row, &row1); - //memcpy(swapRow.fData, row.getData(), row.getSize()); + memcpy(swapRow.fData, row.getData(), row.getSize()); } else { - fDistinctMap->erase(row.getPointer()); - copyRow(row, &row1); - fDistinctMap->insert(row1.getPointer()); - //fDistinctMap->erase(fDistinctMap->find(row.getData() + 2)); - //memcpy(swapRow.fData, row.getData(), row.getSize()); - //fDistinctMap->insert(make_pair((swapRow.fData+2), swapRow.fData)); + fDistinctMap->erase(fDistinctMap->find(row.getData() + 2)); + memcpy(swapRow.fData, row.getData(), row.getSize()); + fDistinctMap->insert(make_pair((swapRow.fData+2), swapRow.fData)); } fOrderByQueue.pop(); fOrderByQueue.push(swapRow); @@ -172,25 +454,23 @@ void LimitedOrderBy::finalize() if (fStart != 0) { uint64_t newSize = fRowsPerRG * fRowGroup.getRowSize(); - if (!fRm->getMemory(newSize, fSessionMemLimit)) + if (!fRm->getMemory(newSize)) { cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) << " @" << __FILE__ << ":" << __LINE__; throw IDBExcept(fErrorCode); } fMemSize += newSize; - fData.reinit(fRowGroup, fRowsPerRG); - fRowGroup.setData(&fData); + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); fRowGroup.resetRowGroup(0); fRowGroup.getRow(0, &fRow0); - queue tempQueue; + queue > tempQueue; uint64_t i = 0; while ((fOrderByQueue.size() > fStart) && (i++ < fCount)) { const OrderByRow& topRow = fOrderByQueue.top(); - row1.setData(topRow.fData); - copyRow(row1, &fRow0); - //memcpy(fRow0.getData(), topRow.fData, fRow0.getSize()); + memcpy(fRow0.getData(), topRow.fData, fRow0.getSize()); fRowGroup.incRowCount(); fRow0.nextRow(); fOrderByQueue.pop(); @@ -198,16 +478,15 @@ void LimitedOrderBy::finalize() if (fRowGroup.getRowCount() >= fRowsPerRG) { tempQueue.push(fData); - if (!fRm->getMemory(newSize, fSessionMemLimit)) + if (!fRm->getMemory(newSize)) { cerr << IDBErrorInfo::instance()->errorMsg(fErrorCode) << " @" << __FILE__ << ":" << __LINE__; throw IDBExcept(fErrorCode); } fMemSize += newSize; - fData.reinit(fRowGroup, fRowsPerRG); - //fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); - fRowGroup.setData(&fData); + fData.reset(new uint8_t[fRowGroup.getDataSize(fRowsPerRG)]); + fRowGroup.setData(fData.get()); fRowGroup.resetRowGroup(0); fRowGroup.getRow(0, &fRow0); } @@ -224,12 +503,9 @@ const string LimitedOrderBy::toString() const { ostringstream oss; oss << "OrderBy cols: "; - vector::const_iterator i = fOrderByCond.begin(); + vector >::const_iterator i = fOrderByCond.begin(); for (; i != fOrderByCond.end(); i++) - oss << "(" << i->fIndex << "," - << ((i->fAsc)?"Asc":"Desc") << "," - << ((i->fNf)?"null first":"null last") << ") "; - + oss << "(" << i->first << "," << ((i->second)?1:-1) << ") "; oss << " start-" << fStart << " count-" << fCount; if (fDistinct) oss << " distinct"; diff --git a/dbcon/joblist/limitedorderby.h b/dbcon/joblist/limitedorderby.h index 3ab4eab7..2db41883 100644 --- a/dbcon/joblist/limitedorderby.h +++ b/dbcon/joblist/limitedorderby.h @@ -15,17 +15,22 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: limitedorderby.h 9414 2013-04-22 22:18:30Z xlou $ +// $Id: limitedorderby.h 8436 2012-04-04 18:18:21Z rdempsey $ /** @file */ -#ifndef LIMITED_ORDER_BY_H -#define LIMITED_ORDER_BY_H +#ifndef IDB_ORDER_BY_H +#define IDB_ORDER_BY_H -#include +#include +#include +#include +#include +#include #include "rowgroup.h" -#include "idborderby.h" +#include "hasher.h" +#include "simpleallocator.h" namespace joblist @@ -34,13 +39,143 @@ namespace joblist // forward reference struct JobInfo; +class ResourceManager; +class IdbOrderBy; + +// compare functor for different datatypes +// cannot use template because Row's getXxxField method. +class Compare +{ +public: + Compare(int i, bool b) : fIndex(i), fAsc(b ? 1 : -1) {} + virtual ~Compare() {} + + virtual int operator()(IdbOrderBy*, uint8_t*, uint8_t*) = 0; + +protected: + int fIndex; + int fAsc; +}; + + +class IntCompare : public Compare +{ +public: + IntCompare(int i, bool b) : Compare(i, b) {} + + int operator()(IdbOrderBy*, uint8_t*, uint8_t*); +}; + + +class UintCompare : public Compare +{ +public: + UintCompare(int i, bool b) : Compare(i, b) {} + + int operator()(IdbOrderBy*, uint8_t*, uint8_t*); +}; + + +class StringCompare : public Compare +{ +public: + StringCompare(int i, bool b) : Compare(i, b) {} + + int operator()(IdbOrderBy*, uint8_t*, uint8_t*); +}; + + +class DoubleCompare : public Compare +{ +public: + DoubleCompare(int i, bool b) : Compare(i, b) {} + + int operator()(IdbOrderBy*, uint8_t*, uint8_t*); +}; + + +class FloatCompare : public Compare +{ +public: + FloatCompare(int i, bool b) : Compare(i, b) {} + + int operator()(IdbOrderBy*, uint8_t*, uint8_t*); +}; + + +// base classs for order by clause used in IDB +class IdbOrderBy +{ +public: + IdbOrderBy(); + virtual ~IdbOrderBy(); + + virtual void initialize(const rowgroup::RowGroup&); + virtual void processRow(const rowgroup::Row&) = 0; + virtual uint64_t getKeyLength() const = 0; + virtual const std::string toString() const = 0; + + bool getData(boost::shared_array& data); + + rowgroup::Row& row1() { return fRow1; } + rowgroup::Row& row2() { return fRow2; } + + void distinct(bool b) { fDistinct = b; } + bool distinct() const { return fDistinct; } + +protected: + class CompareRule + { + public: + CompareRule() : fOrderBy(NULL) {} + +// bool less(const uint8_t* r1, const uint8_t* r2); + bool less(uint8_t* r1, uint8_t* r2); + + std::vector fCompares; + IdbOrderBy* fOrderBy; + }; + + class OrderByRow + { + public: + OrderByRow(const rowgroup::Row& r, CompareRule& c) : fData(r.getData()), fRule(&c) {} + + bool operator < (const OrderByRow& rhs) const { return fRule->less(fData, rhs.fData); } + + uint8_t* fData; + CompareRule* fRule; + }; + + std::vector > fOrderByCond; + std::priority_queue fOrderByQueue; + rowgroup::RowGroup fRowGroup; + rowgroup::Row fRow0; + rowgroup::Row fRow1; + rowgroup::Row fRow2; + CompareRule fRule; + + boost::shared_array fData; + std::queue > fDataQueue; + + typedef std::tr1::unordered_map > > DistinctMap_t; + boost::shared_ptr fPool; + boost::scoped_ptr fDistinctMap; + + bool fDistinct; + uint64_t fMemSize; + uint64_t fRowsPerRG; + uint64_t fErrorCode; + ResourceManager* fRm; +}; -// ORDER BY with LIMIT class +// LIMIT class // This version is for subqueries, limit the result set to fit in memory, // use ORDER BY to make the results consistent. // The actual output are the first or last # of rows, which are NOT ordered. -class LimitedOrderBy : public ordering::IdbOrderBy +class LimitedOrderBy : public IdbOrderBy { public: LimitedOrderBy(); @@ -61,5 +196,5 @@ class LimitedOrderBy : public ordering::IdbOrderBy } -#endif // LIMITED_ORDER_BY_H +#endif // IDB_ORDER_BY_H diff --git a/dbcon/joblist/passthrucommand-jl.cpp b/dbcon/joblist/passthrucommand-jl.cpp index 976f7e56..8ba2a04b 100644 --- a/dbcon/joblist/passthrucommand-jl.cpp +++ b/dbcon/joblist/passthrucommand-jl.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: passthrucommand-jl.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: passthrucommand-jl.cpp 8476 2012-04-25 22:28:15Z xlou $ // C++ Implementation: passthrucommand-jl // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -40,7 +40,7 @@ using namespace messageqcpp; #include "command-jl.h" #include "passthrucommand-jl.h" -namespace joblist +namespace joblist { /* I think this class literally does nothing */ @@ -54,7 +54,7 @@ PassThruCommandJL::PassThruCommandJL(const PassThruStep &p) /* Is this ever a dictionary column? */ if (p.isDictColumn) tableColumnType = TableColumn::STRING; - else + else switch (colWidth) { case 1: tableColumnType = TableColumn::UINT8; break; case 2: tableColumnType = TableColumn::UINT16; break; @@ -69,7 +69,7 @@ PassThruCommandJL::~PassThruCommandJL() { } -void PassThruCommandJL::setLBID(uint64_t l, uint32_t dbroot) +void PassThruCommandJL::setLBID(uint64_t l, uint dbroot) { } @@ -92,7 +92,7 @@ uint8_t PassThruCommandJL::getTableColumnType() string PassThruCommandJL::toString() { ostringstream oss; - oss << "PassThruCommandJL: colwidth=" << static_cast(colWidth) << " oid=" << OID + oss << "PassThruCommandJL: colwidth=" << static_cast(colWidth) << " oid=" << OID << " colName=" << colName; return oss.str(); } diff --git a/dbcon/joblist/passthrucommand-jl.h b/dbcon/joblist/passthrucommand-jl.h index 7e482655..bf352b25 100644 --- a/dbcon/joblist/passthrucommand-jl.h +++ b/dbcon/joblist/passthrucommand-jl.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: passthrucommand-jl.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: passthrucommand-jl.h 8436 2012-04-04 18:18:21Z rdempsey $ // C++ Interface: passthrucommand-jl // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -43,7 +43,7 @@ class PassThruCommandJL : public CommandJL PassThruCommandJL(const PassThruStep &); virtual ~PassThruCommandJL(); - void setLBID(uint64_t data, uint32_t dbroot); // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. + void setLBID(uint64_t data, uint dbroot); // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. uint8_t getTableColumnType(); std::string toString(); @@ -55,7 +55,7 @@ class PassThruCommandJL : public CommandJL private: PassThruCommandJL(); PassThruCommandJL(const PassThruCommandJL &); - + uint8_t colWidth; uint8_t tableColumnType; }; diff --git a/dbcon/joblist/passthrustep.cpp b/dbcon/joblist/passthrustep.cpp index 7508aaca..3fc4cbd4 100644 --- a/dbcon/joblist/passthrustep.cpp +++ b/dbcon/joblist/passthrustep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: passthrustep.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: passthrustep.cpp 8476 2012-04-25 22:28:15Z xlou $ // // This is a simple optimization to take DV's out of an IDL and insert them into an ODL // without having to get them from PrimProc @@ -29,9 +29,8 @@ using namespace std; #include using namespace boost; -#include "jlf_common.h" -#include "datalist.h" #include "primitivestep.h" +#include "datalist.h" using namespace execplan; //namespace { @@ -39,7 +38,7 @@ using namespace execplan; //class ptt //{ //public: -// ptt(DataList_t* i, DataList_t* o, bool swallowRows, PassThruStep* pStep) : +// ptt(DataList_t* i, DataList_t* o, bool swallowRows, PassThruStep* pStep) : // idl(i), odl(o), fSwallowRows(swallowRows), fpStep(pStep) { } // // void operator()() @@ -92,7 +91,7 @@ using namespace execplan; // else { // pos = ((uint8_t *) &rwOut.et[0]); // for (uint64_t i = 0; i < rwIn.count; ++i) -// { +// { // switch (colWidth) { // case 1: pos[rwOut.count++] = rwIn.et[i].second; break; // case 2: ((uint16_t *) pos)[rwOut.count++] = rwIn.et[i].second; @@ -106,7 +105,7 @@ using namespace execplan; // case 8: ((uint64_t *) pos)[rwOut.count++] = rwIn.et[i].second; // break; // default: -// cout << "PassThruStep: bad column width of " << +// cout << "PassThruStep: bad column width of " << // fpStep->getColWidth() << endl; // throw logic_error("PassThruStep: bad column width"); // } @@ -153,7 +152,7 @@ using namespace execplan; // case 8: ((uint64_t *) pos)[rwOut.count++] = e.second; // break; // default: -// cout << "PassThruStep: bad column width of " << +// cout << "PassThruStep: bad column width of " << // fpStep->getColWidth() << endl; // throw logic_error("PassThruStep: bad column width"); // } @@ -174,7 +173,7 @@ using namespace execplan; // odlrw->insert(rwOut); // outSize += rwOut.count; // } -// +// // odlrw->totalSize(outSize); // odlrw->endOfInput(); // @@ -207,47 +206,42 @@ using namespace execplan; namespace joblist { -PassThruStep::PassThruStep( +PassThruStep::PassThruStep(const JobStepAssociation& in, + const JobStepAssociation& out, + DistributedEngineComm* dec, + execplan::CalpontSystemCatalog::ColType colType, execplan::CalpontSystemCatalog::OID oid, execplan::CalpontSystemCatalog::OID tableOid, - const execplan::CalpontSystemCatalog::ColType& colType, - const JobInfo& jobInfo) : - JobStep(jobInfo), + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId, + bool EM, + ResourceManager& rm) : + fInputJobStepAssociation(in), + fOutputJobStepAssociation(out), + fDec( dec), fOid(oid), fTableOid(tableOid), - isEM(jobInfo.isExeMgr), + fSessionId(sessionId), + fTxnId(txnId), + fVerId(verId), + fStepId(stepId), + fStatementId(statementId), + isEM(EM), fSwallowRows(false), - fRm(jobInfo.rm) + fRm(rm) { colWidth = colType.colWidth; realWidth = colType.colWidth; - isDictColumn = ((colType.colDataType == CalpontSystemCatalog::VARCHAR && colType.colWidth > 7) + isDictColumn = ((colType.colDataType == CalpontSystemCatalog::VARCHAR && colType.colWidth > 7) || (colType.colDataType == CalpontSystemCatalog::CHAR && colType.colWidth > 8)); fColType = colType; - fPseudoType = 0; - -} - -PassThruStep::PassThruStep(const pColStep& rhs) : JobStep(rhs), fRm(rhs.fRm) -{ - fInputJobStepAssociation = rhs.inputAssociation(); - fOutputJobStepAssociation = rhs.outputAssociation(); - colWidth = rhs.fColType.colWidth; - realWidth = rhs.realWidth; - fOid = rhs.oid(); - fTableOid = rhs.tableOid(); - fSwallowRows = rhs.getSwallowRows(); - isDictColumn = rhs.isDictCol(); - fColType = rhs.colType(); - isEM = rhs.isExeMgr(); - - const PseudoColStep* pcs = dynamic_cast(&rhs); - if (pcs) - fPseudoType = pcs->pseudoColumnId(); - + } -PassThruStep::PassThruStep(const PseudoColStep& rhs) : JobStep(rhs), fRm(rhs.fRm) + PassThruStep::PassThruStep(const pColStep& rhs, bool EM): fRm(rhs.fRm) { fInputJobStepAssociation = rhs.inputAssociation(); fOutputJobStepAssociation = rhs.outputAssociation(); @@ -255,11 +249,17 @@ PassThruStep::PassThruStep(const PseudoColStep& rhs) : JobStep(rhs), fRm(rhs.fRm realWidth = rhs.realWidth; fOid = rhs.oid(); fTableOid = rhs.tableOid(); + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); + fLogger = rhs.logger(); fSwallowRows = rhs.getSwallowRows(); isDictColumn = rhs.isDictCol(); + isEM = EM; +// fDec = rhs.dec(); fColType = rhs.colType(); - fPseudoType = rhs.pseudoColumnId(); - isEM = rhs.isExeMgr(); } PassThruStep::~PassThruStep() diff --git a/dbcon/joblist/pcolscan.cpp b/dbcon/joblist/pcolscan.cpp index c28e40a6..b872aa57 100644 --- a/dbcon/joblist/pcolscan.cpp +++ b/dbcon/joblist/pcolscan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: pcolscan.cpp 9655 2013-06-25 23:08:13Z xlou $ +* $Id: pcolscan.cpp 8526 2012-05-17 02:28:10Z xlou $ * * ***********************************************************************/ @@ -40,16 +40,17 @@ using namespace config; #include "messageobj.h" using namespace logging; -#include "logicoperator.h" -using namespace execplan; - - #include "distributedenginecomm.h" #include "primitivemsg.h" #include "timestamp.h" #include "unique32generator.h" -#include "jlf_common.h" #include "primitivestep.h" +using namespace joblist; + +#include "logicoperator.h" +using namespace execplan; + +using namespace BRM; //#define DEBUG 1 //#define DEBUG2 1 @@ -116,13 +117,28 @@ namespace namespace joblist { -pColScanStep::pColScanStep( +pColScanStep::pColScanStep(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + boost::shared_ptr syscat, CalpontSystemCatalog::OID o, CalpontSystemCatalog::OID t, const CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo) : - JobStep(jobInfo), - fRm(jobInfo.rm), + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId, + ResourceManager& rm) : + fRm(rm), + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + fSessionId(sessionId), + fTxnId(txnId), + fVerId(verId), + fStepId(stepId), + fStatementId(statementId), fNumThreads(fRm.getJlNumScanReceiveThreads()), fFilterCount(0), fOid(o), @@ -146,7 +162,7 @@ pColScanStep::pColScanStep( return; int err, i, mask; - BRM::LBIDRange_v::iterator it; + LBIDRange_v::iterator it; //pthread_mutex_init(&mutex, NULL); //pthread_mutex_init(&dlMutex, NULL); @@ -156,6 +172,8 @@ pColScanStep::pColScanStep( finishedSending=false; recvWaiting=0; recvExited = 0; + ridsReturned = 0; + sendWaiting=false; rDoNothing = false; fIsDict = false; @@ -164,10 +182,8 @@ pColScanStep::pColScanStep( //If this is a dictionary column, fudge the numbers... if ( fColType.colDataType == CalpontSystemCatalog::VARCHAR ) { - if (8 > fColType.colWidth && 4 <= fColType.colWidth ) - fColType.colDataType = CalpontSystemCatalog::CHAR; - - fColType.colWidth++; + if (8 > fColType.colWidth && 4 <= fColType.colWidth ) fColType.colDataType = CalpontSystemCatalog::CHAR; + fColType.colWidth++; } //If this is a dictionary column, fudge the numbers... @@ -193,10 +209,13 @@ pColScanStep::pColScanStep( err = dbrm.lookup(fOid, lbidRanges); if (err) throw runtime_error("pColScan: BRM LBID range lookup failure (1)"); + err = dbrm.getHWM(fOid, hwm); + if (err) + throw runtime_error("pColScan: BRM HWM lookup failure (3)"); err = dbrm.getExtents(fOid, extents); if (err) throw runtime_error("pColScan: BRM HWM lookup failure (4)"); - sort(extents.begin(), extents.end(), BRM::ExtentSorter()); + sort(extents.begin(), extents.end(), ExtentSorter()); numExtents = extents.size(); extentSize = (fRm.getExtentRows()*fColType.colWidth)/BLOCK_SIZE; @@ -215,7 +234,7 @@ pColScanStep::pColScanStep( for (i++, mask <<= 1; i <= 32; i++, mask <<= 1) if (extentSize & mask) throw runtime_error("pColScan: Extent size must be a power of 2 in blocks"); - + ridsPerBlock = BLOCK_SIZE/fColType.colWidth; for (i = 1, mask = 1; i <= 32; i++) { mask <<= 1; @@ -227,6 +246,15 @@ pColScanStep::pColScanStep( for (i++, mask <<= 1; i <= 32; i++, mask <<= 1) if (ridsPerBlock & mask) throw runtime_error("pColScan: Block size and column width must be a power of 2"); + + // XXXPAT: how to handle BRM failures here? + +// uniqueID = UniqueNumberGenerator::instance()->getUnique32(); +// if (fDec) +// fDec->addQueue(uniqueID); + +// initializeConfigParms ( ); +// fProducerThread = new SPTHD[fNumThreads]; } pColScanStep::~pColScanStep() @@ -266,11 +294,11 @@ void pColScanStep::initializeConfigParms() // strVal = cf->getConfig(section, sendLimitName); // if (strVal.size() > 0) // fScanLbidReqLimit = static_cast(Config::uFromText(strVal)); -// +// // strVal = cf->getConfig(section, sendThresholdName); // if (strVal.size() > 0) // fScanLbidReqThreshold = static_cast(Config::uFromText(strVal)); -// +// // fNumThreads = 8; // strVal = cf->getConfig(section, numReadThreadsName); // if (strVal.size() > 0) @@ -286,7 +314,7 @@ void pColScanStep::startPrimitiveThread() void pColScanStep::startAggregationThread() { -// for (uint32_t i = 0; i < fNumThreads; i++) +// for (uint i = 0; i < fNumThreads; i++) // fProducerThread[i].reset(new boost::thread(pColScanStepAggregater(this, i))); } @@ -309,7 +337,7 @@ void pColScanStep::join() { // fConsumerThread->join(); // if ( !fSingleThread ) { -// for (uint32_t i = 0; i < fNumThreads; i++) +// for (uint i = 0; i < fNumThreads; i++) // fProducerThread[i]->join(); // } } @@ -327,14 +355,14 @@ void pColScanStep::sendPrimitiveMessages() // // the previous step, so this step should not return any rows either. This would be the case, for // // instance, if P_NAME LIKE '%xxxx%' produced no signature matches. // if (fFilterCount == 0) { -// rDoNothing=true; -// startAggregationThread(); +// rDoNothing=true; +// startAggregationThread(); // return; // } // } -// +// // startAggregationThread(); -// +// // /* for all the blocks that need to be sent // * build out a message for each block with the primitive message header filled // * out and all the NOPS and BOP structures as well. @@ -345,19 +373,19 @@ void pColScanStep::sendPrimitiveMessages() // uint64_t fbo; // // ISMPacketHeader ism; -// ism.Flags = planFlagsToPrimFlags(fTraceFlags); +// ism.Flags = planFlagsToPrimFlags(fTraceFlags); // ism.Command=COL_BY_SCAN_RANGE; // ism.Size = sizeof(ISMPacketHeader) + sizeof(ColByScanRangeRequestHeader) + fFilterString.length(); // ism.Type=2; // //bool firstWrite = true; -// +// // //...Counter used to track the number of LBIDs we are requesting from // //...primproc in the current set of msgs, till we reach fScanLbidReqLimit -// uint32_t runningLbidCount = 0; +// u_int32_t runningLbidCount = 0; // bool exitLoop = false; // const bool ignoreCP = ((fTraceFlags & CalpontSelectExecutionPlan::IGNORE_CP) != 0); // -// for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) +// for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) // { // BRM::LBID_t lbid = (*it).start; // @@ -365,7 +393,7 @@ void pColScanStep::sendPrimitiveMessages() // if (hwm < fbo) // continue; // -// if (fOid >= 3000 && lbidList->CasualPartitionDataType(fColType.colDataType, fColType.colWidth) ) +// if (fOid >= 3000 && lbidList->CasualPartitionDataType(fColType.colDataType, fColType.colWidth) ) // { // int64_t Min=0; // int64_t Max=0; @@ -380,14 +408,14 @@ void pColScanStep::sendPrimitiveMessages() // if (MinMaxValid) // { // cpPredicate=lbidList->CasualPartitionPredicate(Min, -// Max, +// Max, // &fFilterString, -// fFilterCount, -// fColType, +// fFilterCount, +// fColType, // fBOP) || ignoreCP; // } // cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); -// +// // if (cpPredicate==false){ //don't scan this extent //#ifdef DEBUG // cout << "Scan Skip " << lbid << endl; @@ -403,14 +431,14 @@ void pColScanStep::sendPrimitiveMessages() // else // cout << "Scan " << lbid << endl; //#endif -// +// // } // // LBID_t msgLbidStart = it->start; -// uint32_t remainingLbids = -// ( (hwm > (fbo + it->size - 1)) ? (it->size) : (hwm - fbo + 1) ); -// uint32_t msgLbidCount = 0; -// +// u_int32_t remainingLbids = +// ( (hwm > (fbo + it->size - 1)) ? (it->size) : (hwm - fbo + 1) ); +// u_int32_t msgLbidCount = 0; +// // while ( remainingLbids > 0 ) // { // //...Break up this range of LBIDs when we reach the msg size @@ -418,8 +446,8 @@ void pColScanStep::sendPrimitiveMessages() // if ( (runningLbidCount + remainingLbids) >= fScanLbidReqLimit ) // { // msgLbidCount = fScanLbidReqLimit - runningLbidCount; -// sendAPrimitiveMessage(ism, msgLbidStart, msgLbidCount ); -// //...Wait for the consuming thread to catch up if our +// sendAPrimitiveMessage(ism, msgLbidStart, msgLbidCount ); +// //...Wait for the consuming thread to catch up if our // //...backlog of work is >= the allowable threshold limit // // mutex.lock(); //pthread_mutex_lock(&mutex); @@ -433,7 +461,7 @@ void pColScanStep::sendPrimitiveMessages() // sendWaiting = true; //#ifdef DEBUG2 // if (fOid >= 3000) -// cout << "pColScanStep producer WAITING: " << +// cout << "pColScanStep producer WAITING: " << // "st:" << fStepId << // "; sentCount-" << sentCount << // "; recvCount-" << recvCount << @@ -460,7 +488,7 @@ void pColScanStep::sendPrimitiveMessages() // { // msgLbidCount = remainingLbids; // -// sendAPrimitiveMessage(ism, msgLbidStart, msgLbidCount ); +// sendAPrimitiveMessage(ism, msgLbidStart, msgLbidCount ); // mutex.lock(); //pthread_mutex_lock(&mutex); // sentCount += msgLbidCount; // if (recvWaiting) @@ -516,7 +544,7 @@ void pColScanStep::sendPrimitiveMessages() void pColScanStep::sendAPrimitiveMessage( ISMPacketHeader& ism, BRM::LBID_t msgLbidStart, - uint32_t msgLbidCount + u_int32_t msgLbidCount ) { // ByteStream bs; @@ -552,7 +580,7 @@ void pColScanStep::sendAPrimitiveMessage( // ": sending req for lbid start " << msgLbidStart << // "; lbid count " << msgLbidCount << endl; //#endif -// +// // fMsgBytesOut += bs.lengthWithHdrOverhead(); // fDec->write(bs); // fMsgsToPm++; @@ -579,10 +607,10 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // vector v; // UintRowGroup rw; // vector > bsv; -// uint32_t i, k, size, bsLength; +// uint i, k, size, bsLength; // bool lastThread = false; // vector cpv; -// +// // if (bucket || zdl) // dlp->setMultipleProducers(true); // @@ -606,10 +634,10 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // for (unsigned int jj=0; jjlengthWithHdrOverhead(); // } -// +// // // size = bsv.size(); -// +// // if (size == 0) { // /* XXXPAT: Need to give other threads a chance to update recvCount. // As of 2/25/08, each BS contains multiple responses. With the current @@ -632,14 +660,14 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // // mutex.unlock(); //pthread_mutex_unlock(&mutex); // -// uint32_t msgCount = 0; +// uint msgCount = 0; // for (i = 0; i < size; i++) { // const ByteStream::byte* bsp = bsv[i]->buf(); -// +// // bsLength = bsv[i]->length(); // k = 0; // while (k < bsLength) { -// ++msgCount; +// ++msgCount; //// cout << "got msg " << msgCount << " k = " << k << endl; // k += sizeof(ISMPacketHeader); // const ColResultHeader* crh = reinterpret_cast(&bsp[k]); @@ -648,7 +676,7 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // // l_cachedIO += crh->CacheIO; // l_physicalIO += crh->PhysicalIO; -// fbo = getFBO(crh->LBID); +// fbo = getFBO(crh->LBID); // ridBase = fbo << rpbShift; // // for(int j = 0; j < crh->NVALS; j++) @@ -676,7 +704,7 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // default: // throw runtime_error("pColStep: invalid column width!"); // } -// +// // v.push_back(ElementType(rid, dv)); // ++l_ridsReturned; //#ifdef DEBUG @@ -690,7 +718,7 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // //#ifdef DEBUG // cout << "recvPrimMsgs Oid " << fOid -// << " valid " << crh->ValidMinMax +// << " valid " << crh->ValidMinMax // << " LBID " << crh->LBID // << " Mn/Mx " << crh->Min << "/" << crh->Max // << " nvals " << crh->NVALS @@ -806,7 +834,7 @@ void pColScanStep::receivePrimitiveMessages(uint64_t tid) // FifoDataList* pFifo = 0; // uint64_t totalBlockedReadCount = 0; // uint64_t totalBlockedWriteCount = 0; -// +// // //...Sum up the blocked FIFO reads for all input associations // size_t inDlCnt = fInputJobStepAssociation.outSize(); // for (size_t iDataList=0; iDataList(val8); + return (*val32 == joblist::FLOATEMPTYROW); + } + case WriteEngine::DOUBLE: + { + const u_int64_t *val64 = reinterpret_cast(val8); + return (*val64 == joblist::DOUBLEEMPTYROW); + } + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: + if (width == 1) + { + return (*val8 == joblist::CHAR1EMPTYROW); + } + else if (width == 2) + { + const u_int16_t *val16 = reinterpret_cast(val8); + return (*val16 == joblist::CHAR2EMPTYROW); + } + else if (width <= 4) + { + const u_int32_t *val32 = reinterpret_cast(val8); + return (*val32 == joblist::CHAR4EMPTYROW); + } + else if (width <= 8) + { + const u_int64_t *val64 = reinterpret_cast(val8); + return (*val64 == joblist::CHAR8EMPTYROW); + } + default: + break; + } - switch (fColType.colDataType) - { - case CalpontSystemCatalog::UTINYINT: - { - return(*val8 == joblist::UTINYINTEMPTYROW); - } - case CalpontSystemCatalog::USMALLINT: - { - const uint16_t *val16 = reinterpret_cast(val8); - return(*val16 == joblist::USMALLINTEMPTYROW); - } - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - { - const uint32_t *val32 = reinterpret_cast(val8); - return(*val32 == joblist::UINTEMPTYROW); - } - case CalpontSystemCatalog::UBIGINT: - { - const uint64_t *val64 = reinterpret_cast(val8); - return(*val64 == joblist::BIGINTEMPTYROW); - } - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - { - const uint32_t *val32 = reinterpret_cast(val8); - return(*val32 == joblist::FLOATEMPTYROW); - } - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - { - const uint64_t *val64 = reinterpret_cast(val8); - return(*val64 == joblist::DOUBLEEMPTYROW); - } - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - if (width == 1) - { - return(*val8 == joblist::CHAR1EMPTYROW); - } - else if (width == 2) - { - const uint16_t *val16 = reinterpret_cast(val8); - return(*val16 == joblist::CHAR2EMPTYROW); - } - else if (width <= 4) - { - const uint32_t *val32 = reinterpret_cast(val8); - return(*val32 == joblist::CHAR4EMPTYROW); - } - else if (width <= 8) - { - const uint64_t *val64 = reinterpret_cast(val8); - return(*val64 == joblist::CHAR8EMPTYROW); - } - default: - break; - } - - switch (width) - { - case 1: - { - return(*val8 == joblist::TINYINTEMPTYROW); - } - case 2: - { - const uint16_t *val16 = reinterpret_cast(val8); - return(*val16 == joblist::SMALLINTEMPTYROW); - } - case 4: - { - const uint32_t *val32 = reinterpret_cast(val8); - return(*val32 == joblist::INTEMPTYROW); - } - case 8: - { - const uint64_t *val64 = reinterpret_cast(val8); - return(*val64 == joblist::BIGINTEMPTYROW); - } - default: - MessageLog logger(LoggingID(28)); - logging::Message::Args colWidth; - Message msg(33); - - colWidth.add(width); - msg.format(colWidth); - logger.logErrorMessage(msg); - return false; - } - - return false; + switch(width) { + case 1: + { + return (*val8 == joblist::TINYINTEMPTYROW); + } + case 2: + { + const u_int16_t *val16 = reinterpret_cast(val8); + return (*val16 == joblist::SMALLINTEMPTYROW); + } + case 4: + { + const u_int32_t *val32 = reinterpret_cast(val8); + return (*val32 == joblist::INTEMPTYROW); + } + case 8: + { + const u_int64_t *val64 = reinterpret_cast(val8); + return (*val64 == joblist::BIGINTEMPTYROW); + } + default: + MessageLog logger(LoggingID(28)); + logging::Message::Args colWidth; + Message msg(33); + + colWidth.add(width); + msg.format(colWidth); + logger.logErrorMessage(msg); + return false; + } + + return false; } diff --git a/dbcon/joblist/pcolstep.cpp b/dbcon/joblist/pcolstep.cpp index 31cae38b..d665c5fe 100644 --- a/dbcon/joblist/pcolstep.cpp +++ b/dbcon/joblist/pcolstep.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: pcolstep.cpp 9655 2013-06-25 23:08:13Z xlou $ +* $Id: pcolstep.cpp 8531 2012-05-18 22:18:04Z xlou $ * * ***********************************************************************/ @@ -32,6 +32,7 @@ using namespace std; #include "distributedenginecomm.h" #include "elementtype.h" #include "unique32generator.h" +#include "primitivestep.h" #include "messagequeue.h" using namespace messageqcpp; @@ -51,8 +52,6 @@ using namespace execplan; using namespace BRM; #include "idbcompress.h" -#include "jlf_common.h" -#include "primitivestep.h" // #define DEBUG 1 @@ -74,7 +73,7 @@ struct pColStepPrimitive } catch(exception& re) { - cerr << "pColStep: send thread threw an exception: " << re.what() << + cerr << "pColStep: send thread threw an exception: " << re.what() << "\t" << this << endl; } } @@ -99,17 +98,34 @@ struct pColStepAggregator }; #endif -pColStep::pColStep( +pColStep::pColStep(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + boost::shared_ptr cat, CalpontSystemCatalog::OID o, CalpontSystemCatalog::OID t, const CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo) : - JobStep(jobInfo), - fRm(jobInfo.rm), - sysCat(jobInfo.csc), + uint32_t session, + uint32_t txn, + uint32_t verID, + uint16_t step, + uint32_t statementId, + ResourceManager& rm, + uint32_t fInterval, + bool isEMgr) : + fRm(rm), + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + sysCat(cat), fOid(o), fTableOid(t), fColType(ct), + fSessionId(session), + fTxnId(txn), + fVerId(verID), + fStepId(step), + fStatementId(statementId), fFilterCount(0), fBOP(BOP_NONE), ridList(0), @@ -118,12 +134,12 @@ pColStep::pColStep( finishedSending(false), recvWaiting(false), fIsDict(false), - isEM(jobInfo.isExeMgr), + isEM(isEMgr), ridCount(0), - fFlushInterval(jobInfo.flushInterval), + fFlushInterval(fInterval), fSwallowRows(false), - fProjectBlockReqLimit(fRm.getJlProjectBlockReqLimit()), - fProjectBlockReqThreshold(fRm.getJlProjectBlockReqThreshold()), + fProjectBlockReqLimit(rm.getJlProjectBlockReqLimit()), + fProjectBlockReqThreshold(rm.getJlProjectBlockReqThreshold()), fStopSending(false), isFilterFeeder(false), fPhysicalIO(0), @@ -136,9 +152,9 @@ pColStep::pColStep( return; int err, i; - uint32_t mask; - - if (fFlushInterval == 0 || !isEM) + uint mask; + + if (fInterval == 0 || !isEM) fOutputType = OT_BOTH; else fOutputType = OT_TOKEN; @@ -162,10 +178,8 @@ pColStep::pColStep( if ( fColType.colDataType == CalpontSystemCatalog::VARCHAR ) { - if (8 > fColType.colWidth && 4 <= fColType.colWidth ) - fColType.colDataType = CalpontSystemCatalog::CHAR; - - fColType.colWidth++; + if (8 > fColType.colWidth && 4 <= fColType.colWidth ) fColType.colDataType = CalpontSystemCatalog::CHAR; + fColType.colWidth++; } //If this is a dictionary column, fudge the numbers... @@ -181,7 +195,7 @@ pColStep::pColStep( //TODO: is this right? fColType.colDataType = CalpontSystemCatalog::VARCHAR; } - + //Round colWidth up if (fColType.colWidth == 3) fColType.colWidth = 4; @@ -247,11 +261,18 @@ pColStep::pColStep( } pColStep::pColStep(const pColScanStep& rhs) : - JobStep(rhs), fRm(rhs.resourceManager()), + fInputJobStepAssociation(rhs.inputAssociation()), + fOutputJobStepAssociation(rhs.outputAssociation()), + fDec(0), fOid(rhs.oid()), fTableOid(rhs.tableOid()), fColType(rhs.colType()), + fSessionId(rhs.sessionId()), + fTxnId(rhs.txnId()), + fVerId(rhs.verId()), + fStepId(rhs.stepId()), + fStatementId(rhs.statementId()), fFilterCount(rhs.filterCount()), fBOP(rhs.BOP()), ridList(0), @@ -273,10 +294,18 @@ pColStep::pColStep(const pColScanStep& rhs) : fNumBlksSkipped(0), fMsgBytesIn(0), fMsgBytesOut(0), + fLogger(rhs.logger()), + fUdfName(rhs.udfName()), fFilters(rhs.getFilters()) { + fCardinality = rhs.cardinality(); + fAlias = rhs.alias(); + fView = rhs.view(); + fName = rhs.name(); + fTupleId = rhs.tupleId(); + int err, i; - uint32_t mask; + uint mask; if (fTableOid == 0) // cross engine support return; @@ -328,7 +357,7 @@ pColStep::pColStep(const pColScanStep& rhs) : os << "pColStep: BRM lookup error. Could not get extents for OID " << fOid; throw runtime_error(os.str()); } - + lbidList=rhs.getlbidList(); sort(extents.begin(), extents.end(), ExtentSorter()); @@ -343,11 +372,18 @@ pColStep::pColStep(const pColScanStep& rhs) : } pColStep::pColStep(const PassThruStep& rhs) : - JobStep(rhs), fRm(rhs.resourceManager()), + fInputJobStepAssociation(rhs.inputAssociation()), + fOutputJobStepAssociation(rhs.outputAssociation()), + fDec(0), fOid(rhs.oid()), fTableOid(rhs.tableOid()), fColType(rhs.colType()), + fSessionId(rhs.sessionId()), + fTxnId(rhs.txnId()), + fVerId(rhs.verId()), + fStepId(rhs.stepId()), + fStatementId(rhs.statementId()), fFilterCount(0), fBOP(BOP_NONE), ridList(0), @@ -367,10 +403,16 @@ pColStep::pColStep(const PassThruStep& rhs) : fCacheIO(0), fNumBlksSkipped(0), fMsgBytesIn(0), - fMsgBytesOut(0) + fMsgBytesOut(0), + fLogger(rhs.logger()) { + fCardinality = rhs.cardinality(); + fAlias = rhs.alias(); + fView = rhs.view(); + fName = rhs.name(); + fTupleId = rhs.tupleId(); int err, i; - uint32_t mask; + uint mask; if (fTableOid == 0) // cross engine support return; @@ -450,7 +492,7 @@ void pColStep::initializeConfigParms() // const string sendLimitName ( "ProjectBlockReqLimit" ); // const string sendThresholdName ( "ProjectBlockReqThreshold" ); // Config* cf = Config::makeConfig(); -// +// // string strVal; // uint64_t numVal; @@ -469,16 +511,16 @@ void pColStep::initializeConfigParms() // errno = 0; // numVal = Config::uFromText(strVal); // if ( errno == 0 ) -// fProjectBlockReqLimit = (uint32_t)numVal; +// fProjectBlockReqLimit = (u_int32_t)numVal; // } -// +// // strVal = cf->getConfig(section, sendThresholdName); // if (strVal.size() > 0) // { // errno = 0; // numVal = Config::uFromText(strVal); // if ( errno == 0 ) -// fProjectBlockReqThreshold = (uint32_t)numVal; +// fProjectBlockReqThreshold = (u_int32_t)numVal; // } } @@ -536,7 +578,7 @@ void pColStep::addFilter(int8_t COP, float value) fFilterString << (uint8_t) 0; fFilterString << *((uint32_t *) &value); fFilterCount++; -} +} void pColStep::addFilter(int8_t COP, int64_t value, uint8_t roundFlag) { @@ -550,25 +592,25 @@ void pColStep::addFilter(int8_t COP, int64_t value, uint8_t roundFlag) // converts to a type of the appropriate width, then bitwise // copies into the filter ByteStream switch(fColType.colWidth) { - case 1: - tmp8 = value; - fFilterString << *((uint8_t *) &tmp8); + case 1: + tmp8 = value; + fFilterString << *((uint8_t *) &tmp8); break; - case 2: + case 2: tmp16 = value; - fFilterString << *((uint16_t *) &tmp16); + fFilterString << *((uint16_t *) &tmp16); break; - case 4: + case 4: tmp32 = value; - fFilterString << *((uint32_t *) &tmp32); + fFilterString << *((uint32_t *) &tmp32); break; - case 8: - fFilterString << *((uint64_t *) &value); + case 8: + fFilterString << *((uint64_t *) &value); break; default: ostringstream o; - o << "pColStep: CalpontSystemCatalog says OID " << fOid << + o << "pColStep: CalpontSystemCatalog says OID " << fOid << " has a width of " << fColType.colWidth; throw runtime_error(o.str()); } @@ -613,8 +655,8 @@ void pColStep::sendPrimitiveMessages() // int64_t msgLargeBlock = -1; // int64_t nextLargeBlock = -1; // uint16_t blockRelativeRID; -// uint32_t msgCount = 0; -// uint32_t sentBlockCount = 0; +// uint msgCount = 0; +// uint sentBlockCount = 0; // int msgsSkip=0; // bool scan=false; // bool scanThisBlock=false; @@ -622,7 +664,7 @@ void pColStep::sendPrimitiveMessages() // UintRowGroup rw; // StringElementType strE; // StringRowGroup strRw; -// +// // ByteStream msgRidList; // ByteStream primMsg(MAX_BUFFER_SIZE); //the MAX_BUFFER_SIZE as of 8/20 // @@ -660,7 +702,7 @@ void pColStep::sendPrimitiveMessages() // // scanFlags.resize(numExtents); // -// for (uint32_t idx=0; idx =3000) //// cout << " " << scanFlags[idx]; // } -//// if (scanFlags.size()>0) +//// if (scanFlags.size()>0) //// cout << endl; // // // If there was more than 1 input DL, the first is a list of filters and the second is a list of rids, @@ -700,7 +742,7 @@ void pColStep::sendPrimitiveMessages() // // dl = fInputJobStepAssociation.outAt(ridListIdx); // ridList = dl->dataList(); -// if ( ridList ) +// if ( ridList ) // { // fifo = dl->fifoDL(); // @@ -717,7 +759,7 @@ void pColStep::sendPrimitiveMessages() // if (strFifo) // it = strFifo->getIterator(); // else -// it = strRidList->getIterator(); +// it = strRidList->getIterator(); // } // // if (ridList) @@ -765,14 +807,14 @@ void pColStep::sendPrimitiveMessages() // msgLBID = getLBID(absoluteRID, scan); // scanThisBlock = scan; // msgLargeBlock = absoluteRID >> blockSizeShift; -// +// // while (more || msgRidCount > 0) { // uint64_t rwCount; // if ( ridList) // rwCount = rw.count; // else // rwCount = strRw.count; -// +// // for (uint64_t i = 0; ((i < rwCount) || (!more && msgRidCount > 0)); ) // { // if ( ridList) @@ -789,7 +831,7 @@ void pColStep::sendPrimitiveMessages() // else // absoluteRID = strE.first; // } -// +// // if (more) { // nextLBID = getLBID(absoluteRID, scan); // nextLargeBlock = absoluteRID >> blockSizeShift; @@ -831,13 +873,13 @@ void pColStep::sendPrimitiveMessages() // hdr.NOPS = fFilterCount; // hdr.NVALS = msgRidCount; // hdr.sort = fToSort; -// +// // primMsg.append((const uint8_t *) &hdr, sizeof(NewColRequestHeader)); // primMsg += fFilterString; // primMsg += msgRidList; // ridCount += msgRidCount; // ++sentBlockCount; -// +// //#ifdef DEBUG // if (flushInterval == 0 && fOid >= 3000) // cout << "sending a prim msg for LBID " << msgLBID << endl; @@ -852,24 +894,24 @@ void pColStep::sendPrimitiveMessages() // msgCount = 0; // primMsg.restart(); // msgLargeBlock = nextLargeBlock; -// -// // @bug 769 - Added "&& !fSwallowRows" condition below to fix problem with -// // caltraceon(16) not working for tpch01 and some other queries. If a query -// // ever held off requesting more blocks, it would lock and never finish. +// +// // @bug 769 - Added "&& !fSwallowRows" condition below to fix problem with +// // caltraceon(16) not working for tpch01 and some other queries. If a query ever held +// // off requesting more blocks, it would lock and never finish. // //Bug 815 -// if (( sentBlockCount >= fProjectBlockReqLimit) && !fSwallowRows && +// if (( sentBlockCount >= fProjectBlockReqLimit) && !fSwallowRows && // (( msgsSent - msgsRecvd) > fProjectBlockReqThreshold)) // { // mutex.lock(); //pthread_mutex_lock(&mutex); -// fStopSending = true; -// +// fStopSending = true; +// // // @bug 836. Wake up the receiver if he's sleeping. // if (recvWaiting) // condvar.notify_one(); //pthread_cond_signal(&condvar); // flushed.wait(mutex); //pthread_cond_wait(&flushed, &mutex); // fStopSending = false; // mutex.unlock(); //pthread_mutex_unlock(&mutex); -// sentBlockCount = 0; +// sentBlockCount = 0; // } // } // } @@ -891,7 +933,7 @@ void pColStep::sendPrimitiveMessages() // #endif // } // scanThisBlock = scan; -// mutex.unlock(); //pthread_mutex_unlock(&mutex); +// mutex.unlock(); //pthread_mutex_unlock(&mutex); // // // break the for loop // if (!more) @@ -960,8 +1002,8 @@ void pColStep::receivePrimitiveMessages() // UintRowGroup rw; // uint64_t ridBase; // boost::shared_ptr bs; -// uint32_t i = 0, length; -// +// uint i = 0, length; +// // while (1) { // // sync with the send side // mutex.lock(); //pthread_mutex_lock(&mutex); @@ -984,7 +1026,7 @@ void pColStep::receivePrimitiveMessages() // break; // } // mutex.unlock(); //pthread_mutex_unlock(&mutex); -// +// // // do the recv // fDec->read(uniqueID, bs); // fMsgBytesIn += bs->lengthWithHdrOverhead(); @@ -998,7 +1040,7 @@ void pColStep::receivePrimitiveMessages() // #endif // // const ByteStream::byte* bsp = bs->buf(); -// +// // // get the ISMPacketHeader out of the bytestream // //const ISMPacketHeader* ism = reinterpret_cast(bsp); // @@ -1008,9 +1050,9 @@ void pColStep::receivePrimitiveMessages() // // bool firstRead = true; // length = bs->length(); -// +// // i = 0; -// uint32_t msgCount = 0; +// uint msgCount = 0; // while (i < length) { // ++msgCount; // @@ -1024,7 +1066,7 @@ void pColStep::receivePrimitiveMessages() // // // From this point on the rest of the bytestream is the data that comes back from the primitive server // // This needs to be fed to a datalist that is retrieved from the outputassociation object. -// +// // fbo = getFBO(crh->LBID); // ridBase = fbo << rpbShift; // @@ -1038,9 +1080,10 @@ void pColStep::receivePrimitiveMessages() // ridResults += crh->NVALS; // } // -// /* XXXPAT: This clause is executed when ExeMgr calls the new nextBand(BS) fcn. +// /* XXXPAT: This clause is executed when ExeMgr calls the +// new nextBand(BS) fcn. // -// TODO: both classes have to agree +// TODO: both classes have to agree // on which nextBand() variant will be called. pColStep // currently has to infer that from flushInterval and the // Table OID. It would be better to have a more explicit form @@ -1052,7 +1095,7 @@ void pColStep::receivePrimitiveMessages() // the memory used for the ElementType array. DeliveryStep // will also treat the ElementType array as raw memory and // serialize that. TableColumn now parses the packed data -// instead of whole ElementTypes. +// instead of whole ElementTypes. // */ // else if (fOutputType == OT_TOKEN && fFlushInterval > 0 && !fIsDict) { // @@ -1061,7 +1104,7 @@ void pColStep::receivePrimitiveMessages() // ridResults += crh->NVALS; // // /* memcpy the bytestream into the output set */ -// uint32_t toCopy, bsPos = 0; +// uint toCopy, bsPos = 0; // uint8_t *pos; // while (bsPos < crh->NVALS) { // toCopy = (crh->NVALS - bsPos > rw.ElementsPerGroup - rw.count ? @@ -1099,7 +1142,7 @@ void pColStep::receivePrimitiveMessages() // case 1: dv = *((const uint8_t *) &bsp[i]); ++i; break; // default: // throw runtime_error("pColStep: invalid column width!"); -// } +// } // // // @bug 663 - Don't output any rows if fSwallowRows (caltraceon(16)) is on. // // This options swallows rows in the project steps. @@ -1119,7 +1162,7 @@ void pColStep::receivePrimitiveMessages() // { // dlp->insert(ElementType(rid, dv)); // } -// #ifdef DEBUG +// #ifdef DEBUG // //cout << " -- inserting <" << rid << ", " << dv << "> " << *prid << endl; // #endif // } @@ -1171,16 +1214,16 @@ void pColStep::receivePrimitiveMessages() // } // } // } // unpacking the BS -// +// // //Bug 815: Check whether we have enough to process // //++lockCount; // mutex.lock(); //pthread_mutex_lock(&mutex); // if ( fStopSending && ((msgsSent - msgsRecvd ) <= fProjectBlockReqThreshold) ) -// { +// { // flushed.notify_one(); //pthread_cond_signal(&flushed); -// } +// } // mutex.unlock(); //pthread_mutex_unlock(&mutex); -// +// // firstRead = false; // msgsRecvd += msgCount; // } // read loop @@ -1249,10 +1292,10 @@ void pColStep::receivePrimitiveMessages() // msgBytesInKB++; // if (fMsgBytesOut & 512) // msgBytesOutKB++; -// +// // // @bug 828 // if (fifo) -// fifo->totalSize(ridResults); +// fifo->totalSize(ridResults); // // if (traceOn()) // { @@ -1268,13 +1311,13 @@ void pColStep::receivePrimitiveMessages() // "\tPartitionBlocksEliminated-" << fNumBlksSkipped << // "; MsgBytesIn-" << msgBytesInKB << "KB" << // "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << -// "\t1st read " << dlTimes.FirstReadTimeString() << +// "\t1st read " << dlTimes.FirstReadTimeString() << // "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << // JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime()) << // "s" << endl; -// +// // logEnd(logStr.str().c_str()); -// +// // syslogReadBlockCounts(16, // exemgr sybsystem // fPhysicalIO, // # blocks read from disk // fCacheIO, // # blocks read from cache @@ -1380,7 +1423,7 @@ void pColStep::addFilters() /* This exists to avoid a DBRM lookup for every rid. */ inline uint64_t pColStep::getLBID(uint64_t rid, bool& scan) { - uint32_t extentIndex, extentOffset; + uint extentIndex, extentOffset; uint64_t fbo; fbo = rid >> rpbShift; extentIndex = fbo >> divShift; @@ -1391,7 +1434,7 @@ inline uint64_t pColStep::getLBID(uint64_t rid, bool& scan) inline uint64_t pColStep::getFBO(uint64_t lbid) { - uint32_t i; + uint i; uint64_t lastLBID; for (i = 0; i < numExtents; i++) { @@ -1402,7 +1445,7 @@ inline uint64_t pColStep::getFBO(uint64_t lbid) cerr << "pColStep: didn't find the FBO?\n"; throw logic_error("pColStep: didn't find the FBO?"); } - + void pColStep::appendFilter(const messageqcpp::ByteStream& filter, unsigned count) { diff --git a/dbcon/joblist/pdictionary.cpp b/dbcon/joblist/pdictionary.cpp index 5397974c..ae15e60e 100644 --- a/dbcon/joblist/pdictionary.cpp +++ b/dbcon/joblist/pdictionary.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: pdictionary.cpp 9655 2013-06-25 23:08:13Z xlou $ +* $Id: pdictionary.cpp 8526 2012-05-17 02:28:10Z xlou $ * * ***********************************************************************/ @@ -27,6 +27,11 @@ #include using namespace std; +#include "distributedenginecomm.h" +#include "elementtype.h" +#include "unique32generator.h" +#include "primitivestep.h" + #include "messagequeue.h" using namespace messageqcpp; #include "configcpp.h" @@ -43,11 +48,6 @@ using namespace execplan; #include "brm.h" using namespace BRM; -#include "distributedenginecomm.h" -#include "elementtype.h" -#include "unique32generator.h" -#include "jlf_common.h" -#include "primitivestep.h" namespace joblist { @@ -91,33 +91,50 @@ namespace joblist pDictionaryStep::pDictionaryStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + boost::shared_ptr cat, CalpontSystemCatalog::OID o, + int ct, CalpontSystemCatalog::OID t, - const CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo) : - JobStep(jobInfo), + uint32_t session, + uint32_t txn, + uint32_t verID, + uint16_t step, + uint32_t statementId, + ResourceManager& rm, + uint32_t interval) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + sysCat(cat), fOid(o), fTableOid(t), + fSessionId(session), + fTxnId(txn), + fVerId(verID), + fStepId(step), + fStatementId(statementId), fBOP(BOP_NONE), msgsSent(0), msgsRecvd(0), finishedSending(false), recvWaiting(false), ridCount(0), - fColType(ct), fFilterCount(0), requestList(0), - fInterval(jobInfo.flushInterval), + fInterval(interval), fPhysicalIO(0), fCacheIO(0), fMsgBytesIn(0), fMsgBytesOut(0), - fRm(jobInfo.rm), + fRm(rm), hasEqualityFilter(false) { // uniqueID = UniqueNumberGenerator::instance()->getUnique32(); -// fColType.compressionType = fColType.ddn.compressionType = ct; + fColType.compressionType = fColType.ddn.compressionType = ct; } pDictionaryStep::~pDictionaryStep() @@ -208,7 +225,7 @@ void pDictionaryStep::sendPrimitiveMessages() // // if (fifo == 0) // throw logic_error("Use p_colscanrange instead here"); -// +// // try{ // it = fifo->getIterator(); // }catch(exception& ex) { @@ -218,7 +235,7 @@ void pDictionaryStep::sendPrimitiveMessages() // } // // more = fifo->next(it, &rw); -// +// // sigToken = rw.et[0].second; // msgLBID = sigToken >> 10; // while (more || msgRidCount > 0) { @@ -265,11 +282,11 @@ void pDictionaryStep::sendPrimitiveMessages() // hdr.Hdr.StepID = fStepId; // hdr.Hdr.UniqueID = uniqueID; // -// hdr.LBID = msgLBID; +// hdr.LBID = msgLBID; // idbassert(msgRidCount <= 8000); // hdr.NVALS = msgRidCount; // hdr.CompType = fColType.ddn.compressionType; -// +// // primMsg.load((const uint8_t *) &ism, sizeof(ism)); // primMsg.append((const uint8_t *) &hdr, sizeof(DictSignatureRequestHeader)); // primMsg += msgRidList; @@ -316,7 +333,7 @@ void pDictionaryStep::receivePrimitiveMessages() // StrDataList* dlp = dl->stringDataList(); // StringFifoDataList *fifo = fOutputJobStepAssociation.outAt(0)->stringDL(); // StringRowGroup rw; -// +// // while (1) { // // // sync with the send side @@ -336,7 +353,7 @@ void pDictionaryStep::receivePrimitiveMessages() // goto junk; // } // mutex.unlock(); -// +// // // do the recv // // ByteStream bs = fDec->read(uniqueID); @@ -344,16 +361,16 @@ void pDictionaryStep::receivePrimitiveMessages() // if (fOid>=3000 && dlTimes.FirstReadTime().tv_sec==0) // dlTimes.setFirstReadTime(); // if (fOid>=3000) dlTimes.setLastReadTime(); -// +// // msgsRecvd++; -// if (bs.length() == 0) +// if (bs.length() == 0) // break; // // const ByteStream::byte* bsp = bs.buf(); // // // get the ResultHeader out of the bytestream // const DictOutput* drh = reinterpret_cast(bsp); -// +// // bsp += sizeof(DictOutput); // // fCacheIO += drh->CacheIO; @@ -462,10 +479,10 @@ void pDictionaryStep::receivePrimitiveMessages() // msgBytesInKB++; // if (fMsgBytesOut & 512) // msgBytesOutKB++; -// +// // // @bug 807 // if (fifo) -// fifo->totalSize(ridResults); +// fifo->totalSize(ridResults); // // if (traceOn()) // { @@ -477,7 +494,7 @@ void pDictionaryStep::receivePrimitiveMessages() // fCacheIO << "; MsgsRcvd-" << msgsRecvd << // "; BlockedFifoIn/Out-" << totalBlockedReadCount << // "/" << totalBlockedWriteCount << -// "; output size-" << ridResults << endl << +// "; output size-" << ridResults << endl << // "\tMsgBytesIn-" << msgBytesInKB << "KB" << // "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << // "\t1st read " << dlTimes.FirstReadTimeString() << @@ -486,7 +503,7 @@ void pDictionaryStep::receivePrimitiveMessages() // "s" << endl; // // logEnd(logStr.str().c_str()); -// +// // syslogReadBlockCounts(16, // exemgr subsystem // fPhysicalIO, // # blocks read from disk // fCacheIO, // # blocks read from cache diff --git a/dbcon/joblist/pdictionaryscan.cpp b/dbcon/joblist/pdictionaryscan.cpp index 17316ac9..2e4377e8 100644 --- a/dbcon/joblist/pdictionaryscan.cpp +++ b/dbcon/joblist/pdictionaryscan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: pdictionaryscan.cpp 9655 2013-06-25 23:08:13Z xlou $ +* $Id: pdictionaryscan.cpp 9469 2013-05-01 18:38:43Z pleblanc $ * * ***********************************************************************/ @@ -26,17 +26,14 @@ #include //#define NDEBUG #include -#include -using namespace std; - #include #include +using namespace std; #include "distributedenginecomm.h" #include "elementtype.h" #include "unique32generator.h" #include "oamcache.h" -#include "jlf_common.h" #include "primitivestep.h" #include "messagequeue.h" @@ -60,8 +57,9 @@ using namespace BRM; #include "rowgroup.h" using namespace rowgroup; -#include "querytele.h" -using namespace querytele; +//#define DEBUG 1 +//#define DEBUG2 1 + namespace joblist { @@ -79,12 +77,11 @@ struct pDictionaryScanPrimitive } catch(runtime_error& re) { - catchHandler(re.what(), ERR_DICTIONARY_SCAN, fPDictScan->errorInfo(), fPDictScan->sessionId()); + catchHandler(re.what()); } catch(...) { - catchHandler("pDictionaryScan send caught an unknown exception", - ERR_DICTIONARY_SCAN, fPDictScan->errorInfo(), fPDictScan->sessionId()); + catchHandler("pDictionaryScan send caught an unknown exception"); } } @@ -103,12 +100,11 @@ struct pDictionaryScanAggregator } catch(runtime_error& re) { - catchHandler(re.what(), ERR_DICTIONARY_SCAN, fPDictScan->errorInfo(), fPDictScan->sessionId()); + catchHandler(re.what()); } catch(...) { - catchHandler("pDictionaryScan receive caught an unknown exception", - ERR_DICTIONARY_SCAN, fPDictScan->errorInfo(), fPDictScan->sessionId()); + catchHandler("pDictionaryScan receive caught an unknown exception"); } } @@ -116,15 +112,30 @@ struct pDictionaryScanAggregator pDictionaryScan::pDictionaryScan( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + boost::shared_ptr cat, CalpontSystemCatalog::OID o, + int ct, CalpontSystemCatalog::OID t, - const CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo) : - JobStep(jobInfo), - fDec(NULL), - sysCat(jobInfo.csc), + uint32_t session, + uint32_t txn, + uint32_t verID, + uint16_t step, + uint32_t statement, + ResourceManager& rm) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + sysCat(cat), fOid(o), fTableOid(t), + fSessionId(session), + fTxnId(txn), + fVerId(verID), + fStepId(step), + fStatementId(statement), fFilterCount(0), fBOP(BOP_NONE), msgsSent(0), @@ -134,9 +145,8 @@ pDictionaryScan::pDictionaryScan( sendWaiting(false), ridCount(0), ridList(0), - colType(ct), - fScanLbidReqLimit(jobInfo.rm.getJlScanLbidReqLimit()), - fScanLbidReqThreshold(jobInfo.rm.getJlScanLbidReqThreshold()), + fScanLbidReqLimit(rm.getJlScanLbidReqLimit()), + fScanLbidReqThreshold(rm.getJlScanLbidReqThreshold()), fStopSending(false), fSingleThread(false), fPhysicalIO(0), @@ -144,14 +154,24 @@ pDictionaryScan::pDictionaryScan( fMsgBytesIn(0), fMsgBytesOut(0), fMsgsToPm(0), - fMsgsExpect(0), - fRm(jobInfo.rm), + fRm(rm), isEquality(false) { int err; DBRM dbrm; - // Get list of non outOfService extents for the OID of interest + fDictBlkCount=0; + err = dbrm.getHWM(fOid, fDictBlkCount); + if (err) + { + ostringstream oss; + oss << "pDictionaryScan: getHWM error! For OID-" << fOid; + throw runtime_error(oss.str()); + } + + if (fDictBlkCount <=0) + fDictBlkCount=1; + err = dbrm.lookup(fOid, fDictlbids); if (err) { @@ -190,9 +210,11 @@ pDictionaryScan::pDictionaryScan( fCOP2 = COMPARE_NIL; uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + if (fDec) + fDec->addQueue(uniqueID); initializeConfigParms(); fExtendedInfo = "DSS: "; - fQtc.stepParms().stepType = StepTeleStats::T_DSS; + colType.compressionType = colType.ddn.compressionType = ct; } pDictionaryScan::~pDictionaryScan() @@ -314,67 +336,49 @@ void pDictionaryScan::sendPrimitiveMessages() uint32_t partNum; uint16_t segNum; BRM::OID_t oid; - boost::shared_ptr > dbRootConnectionMap; boost::shared_ptr > dbRootPMMap; oam::OamCache *oamCache = oam::OamCache::makeOamCache(); - int localPMId = oamCache->getLocalPMId(); try { - dbRootConnectionMap = oamCache->getDBRootToConnectionMap(); - dbRootPMMap = oamCache->getDBRootToPMMap(); + dbRootPMMap = oamCache->getDBRootToConnectionMap(); it = fDictlbids.begin(); - for (; it != fDictlbids.end() && !cancelled(); it++) + for (; it != fDictlbids.end() && !die; it++) { LBID_t msgLbidStart = it->start; dbrm.lookupLocal(msgLbidStart, - (BRM::VER_t)fVerId.currentScn, - false, + (BRM::VER_t)fVerId, + false, oid, - dbroot, - partNum, + dbroot, + partNum, segNum, fbo); - // Bug5741 If we are local only and this doesn't belongs to us, skip it - if (fLocalQuery == execplan::CalpontSelectExecutionPlan::LOCAL_QUERY) - { - if (localPMId == 0) - throw IDBExcept(ERR_LOCAL_QUERY_UM); - if (dbRootPMMap->find(dbroot)->second != localPMId) - continue; - } - - // Retrieve the HWM blk for the segment file specified by the oid, - // partition, and segment number. The extState arg indicates - // whether the hwm block is outOfService or not, but we already - // filtered out the outOfService extents when we constructed the - // fDictlbids list, so extState is extraneous info at this point. - int extState; - dbrm.getLocalHWM(oid, partNum, segNum, hwm, extState); - - uint32_t remainingLbids = fMsgsExpect = - ( (hwm > (fbo + it->size - 1)) ? (it->size) : (hwm - fbo + 1) ); + dbrm.getLastHWM_DBroot(oid, dbroot, partNum, segNum, hwm); - uint32_t msgLbidCount = fLogicalBlocksPerScan; + u_int32_t remainingLbids = + ( (hwm > (fbo + it->size - 1)) ? (it->size) : (hwm - fbo + 1) ); - while ( remainingLbids && !cancelled()) - { - if ( remainingLbids < msgLbidCount) + u_int32_t msgLbidCount = fLogicalBlocksPerScan; + + while ( remainingLbids && 0 == fInputJobStepAssociation.status() && !die) + { + if ( remainingLbids < msgLbidCount) msgLbidCount = remainingLbids; - if (dbRootConnectionMap->find(dbroot) == dbRootConnectionMap->end()) + if (dbRootPMMap->find(dbroot) == dbRootPMMap->end()) throw IDBExcept(ERR_DATA_OFFLINE); - sendAPrimitiveMessage(primMsg, msgLbidStart, msgLbidCount, (*dbRootConnectionMap)[dbroot]); + sendAPrimitiveMessage(primMsg, msgLbidStart, msgLbidCount, (*dbRootPMMap)[dbroot]); primMsg.restart(); mutex.lock(); msgsSent += msgLbidCount; if (recvWaiting) condvar.notify_all(); - - while (( msgsSent - msgsRecvd) > fScanLbidReqThreshold) + + while (( msgsSent - msgsRecvd) > fScanLbidReqThreshold) { sendWaiting = true; condvarWakeupProducer.wait(mutex); @@ -389,13 +393,12 @@ void pDictionaryScan::sendPrimitiveMessages() }//try catch(const exception& e) { - catchHandler(e.what(), ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler(e.what(), fSessionId); sendError(ERR_DICTIONARY_SCAN); } catch(...) { - catchHandler("pDictionaryScan caught an unknown exception.", - ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler("pDictionaryScan caught an unknown exception.", fSessionId); sendError(ERR_DICTIONARY_SCAN); } @@ -422,9 +425,9 @@ void pDictionaryScan::sendPrimitiveMessages() } -void pDictionaryScan::sendError(uint16_t s) +void pDictionaryScan::sendError(uint16_t status) { - status(s); + fOutputJobStepAssociation.status(status); } //------------------------------------------------------------------------------ @@ -449,7 +452,7 @@ void pDictionaryScan::sendAPrimitiveMessage( hdr.Hdr.SessionID = fSessionId; hdr.Hdr.TransactionID = fTxnId; - hdr.Hdr.VerID = fVerId.currentScn; + hdr.Hdr.VerID = fVerId; hdr.Hdr.StepID = fStepId; hdr.Hdr.UniqueID = uniqueID; hdr.Hdr.Priority = priority(); @@ -470,24 +473,11 @@ void pDictionaryScan::sendAPrimitiveMessage( if (fSessionId & 0x80000000) hdr.flags |= IS_SYSCAT; - - /* TODO: Need to figure out how to get the full fVerID into this msg. - * XXXPAT: The way I did it is IMO the least kludgy, while requiring only a couple - * changes. - * The old msg was: TokenByScanRequestHeader + fFilterString - * The new msg is: TokenByScanRequestHeader + fVerId + old message - * Prepending verid wastes a few bytes that go over the network, but that is better - * than putting it in the middle or at the end in terms of simplicity & memory usage, - * given the current code. - */ - - primMsg.load((const uint8_t *) &hdr, sizeof(DictTokenByScanRequestHeader)); - primMsg << fVerId; - primMsg.append((const uint8_t*) &hdr, sizeof(DictTokenByScanRequestHeader)); + primMsg.load((const uint8_t*) &hdr, sizeof(DictTokenByScanRequestHeader)); primMsg += fFilterString; //cout << "Sending rqst LBIDS " << msgLbidStart - // << " hdr.Count " << hdr.Count + // << " blkCount " << fDictBlkCount << " hdr.Count " << hdr.Count // << " filterCount " << fFilterCount << endl; #ifdef DEBUG2 if (fOid >= 3000) @@ -495,64 +485,66 @@ void pDictionaryScan::sendAPrimitiveMessage( ": sending req for lbid start " << msgLbidStart << "; lbid count " << msgLbidCount << endl; #endif - + + fMsgBytesOut += primMsg.lengthWithHdrOverhead(); try { fDec->write(uniqueID, primMsg); } - catch (const IDBExcept& e) { + catch (const IDBExcept &e) { abort(); - cerr << "pDictionaryScan::send() caught: " << e.what() << endl; - catchHandler(e.what(), e.errorCode(), fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(e.errorCode()); } catch (const std::exception& e) { abort(); cerr << "pDictionaryScan::send() caught: " << e.what() << endl; - catchHandler(e.what(), ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); } catch (...) { abort(); cerr << "pDictionaryScan::send() caught unknown exception" << endl; - catchHandler("pDictionaryScan::send() caught unknown exception", - ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler("pDictionaryScan::send() caught unknown exception"); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); } fMsgsToPm++; } void pDictionaryScan::receivePrimitiveMessages() { + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + DataList_t* dlp = dl->dataList(); + FifoDataList *fifo = fOutputJobStepAssociation.outAt(0)->fifoDL(); RowGroupDL* rgFifo = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); + UintRowGroup rw; boost::shared_ptr bs; - RGData rgData; + boost::shared_array rgData; Row r; fRidResults = 0; - idbassert(fOutputRowGroup.getColumnCount() > 0); - fOutputRowGroup.initRow(&r); - rgData = RGData(fOutputRowGroup); - fOutputRowGroup.setData(&rgData); - fOutputRowGroup.resetRowGroup(0); - - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - if (fOid >= 3000) + if (rgFifo) { - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = fMsgsExpect; - postStepStartTele(sts); + idbassert(fOutputRowGroup.getColumnCount() > 0); + fOutputRowGroup.initRow(&r); + rgData.reset(new uint8_t[fOutputRowGroup.getMaxDataSize()]); + fOutputRowGroup.setData(rgData.get()); + fOutputRowGroup.resetRowGroup(0); } - uint16_t error = status(); + uint16_t error = fOutputJobStepAssociation.status(); //...Be careful here. Mutex is locked prior to entering the loop, so //...any continue statement in the loop must be sure the mutex is locked. //error condition will not go through loop if (!error) mutex.lock(); try - { + { while (!error) { // sync with the send side @@ -570,9 +562,10 @@ void pDictionaryScan::receivePrimitiveMessages() mutex.unlock(); fDec->read(uniqueID, bs); + fMsgBytesIn += bs->lengthWithHdrOverhead(); if (fOid>=3000 && traceOn() && dlTimes.FirstReadTime().tv_sec==0) dlTimes.setFirstReadTime(); - if (fOid>=3000 && traceOn()) dlTimes.setLastReadTime(); + if (fOid>=3000 && traceOn()) dlTimes.setLastReadTime(); if (bs->length() == 0) { @@ -585,9 +578,9 @@ void pDictionaryScan::receivePrimitiveMessages() ISMPacketHeader *hdr = (ISMPacketHeader*)(bs->buf()); error = hdr->Status; if (! error) - { + { const ByteStream::byte* bsp = bs->buf(); - + // get the ResultHeader out of the bytestream const TokenByScanResultHeader* crh = reinterpret_cast(bsp); bsp += sizeof(TokenByScanResultHeader); @@ -597,7 +590,7 @@ void pDictionaryScan::receivePrimitiveMessages() // From this point on the rest of the bytestream is the data that comes back from the primitive server // This needs to be fed to a datalist that is retrieved from the outputassociation object. - + PrimToken pt; uint64_t token; #ifdef DEBUG @@ -606,44 +599,49 @@ void pDictionaryScan::receivePrimitiveMessages() if (fOid>=3000 && traceOn() && dlTimes.FirstInsertTime().tv_sec==0) dlTimes.setFirstInsertTime(); - for(int j = 0; j < crh->NVALS && !cancelled(); j++) + for(int j = 0; j < crh->NVALS && !die; j++) { memcpy(&pt, bsp, sizeof(pt)); bsp += sizeof(pt); uint64_t rid = fRidResults++; token = (pt.LBID << 10) | pt.offset; - fOutputRowGroup.getRow(fOutputRowGroup.getRowCount(), &r); - // load r up w/ values - r.setRid(rid); - r.setUintField<8>(token, 0); - fOutputRowGroup.incRowCount(); - if (fOutputRowGroup.getRowCount() == 8192) { - //INSERT_ADAPTER(rgFifo, rgData); - //fOutputRowGroup.convertToInlineDataInPlace(); - rgFifo->insert(rgData); - rgData = RGData(fOutputRowGroup); - fOutputRowGroup.setData(&rgData); - fOutputRowGroup.resetRowGroup(0); + if (fifo) + { + rw.et[rw.count++] = ElementType(rid, token); + if (rw.count == rw.ElementsPerGroup) + { + fifo->insert(rw); + rw.count = 0; + } } + else if (rgFifo) + { + fOutputRowGroup.getRow(fOutputRowGroup.getRowCount(), &r); + // load r up w/ values + r.setRid(rid); +// r.setUintField<8>(token, 1); + r.setUintField<8>(token, 0); + fOutputRowGroup.incRowCount(); + if (fOutputRowGroup.getRowCount() == 8192) { + rgFifo->insert(rgData); + rgData.reset(new uint8_t[fOutputRowGroup.getMaxDataSize()]); + fOutputRowGroup.setData(rgData.get()); + fOutputRowGroup.resetRowGroup(0); + } + } + else + { + dlp->insert(ElementType(rid, token)); + } +#ifdef DEBUG2 + cout << " -- inserting <" << rid << ", " << token << ">" << endl; +#endif } mutex.lock(); msgsRecvd++; - if (fOid >= 3000) - { - uint64_t progress = msgsRecvd * 100 / fMsgsExpect; - if (progress > fProgress) - { - fProgress = progress; - sts.msg_type = StepTeleStats::ST_PROGRESS; - sts.total_units_of_work = fMsgsExpect; - sts.units_of_work_completed = msgsRecvd; - postStepProgressTele(sts); - } - } - //...If producer is waiting, and we have gone below our threshold value, //...then we signal the producer to request more data from primproc if ( (sendWaiting) && @@ -667,52 +665,39 @@ void pDictionaryScan::receivePrimitiveMessages() fStopSending = true; condvarWakeupProducer.notify_one(); mutex.unlock(); - string errMsg; - //bs->advance(sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); - //*bs >> errMsg; - if (error < 1000) - { - logging::ErrorCodes errorcodes; - errMsg = errorcodes.errorString(error); - } - else - { - errMsg = IDBErrorInfo::instance()->errorMsg(error); - } - errorMessage(errMsg); - status(error); + fOutputJobStepAssociation.status(error); } } // end of loop to read LBID responses from primproc } catch(const LargeDataListExcept& ex) { - catchHandler(ex.what(), ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); mutex.unlock(); } catch(const exception& e) { - catchHandler(e.what(), ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler(e.what(), fSessionId); + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); mutex.unlock(); } catch(...) { - catchHandler("pDictionaryScan caught an unknown exception.", - ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler("pDictionaryScan caught an unknown exception.", fSessionId); + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); mutex.unlock(); } - if (fOutputRowGroup.getRowCount() > 0) { - //fOutputRowGroup.convertToInlineDataInPlace(); - //INSERT_ADAPTER(rgFifo, rgData); + if (rgFifo && fOutputRowGroup.getRowCount() > 0) { rgFifo->insert(rgData); - rgData = RGData(fOutputRowGroup); - fOutputRowGroup.setData(&rgData); + rgData.reset(new uint8_t[fOutputRowGroup.getMaxDataSize()]); + fOutputRowGroup.setData(rgData.get()); fOutputRowGroup.resetRowGroup(0); } - Stats stats = fDec->getNetworkStats(uniqueID); - fMsgBytesIn = stats.dataRecvd(); - fMsgBytesOut = stats.dataSent(); + // send the last remaining tokens + if (fifo && rw.count > 0) + fifo->insert(rw); //@bug 699: Reset StepMsgQueue fDec->removeQueue(uniqueID); @@ -723,16 +708,46 @@ void pDictionaryScan::receivePrimitiveMessages() //...necessarily due to re-entrancy, but because we want to strip //...the newline ('\n') off the end of the formatted string. time_t t = time(0); - char timeString[50]; + char timeString[50]; ctime_r(&t, timeString); timeString[strlen(timeString)-1 ] = '\0'; + FifoDataList* pFifo = 0; + uint64_t totalBlockedReadCount = 0; + uint64_t totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + { + totalBlockedReadCount += pFifo->blockedReadCount(); + } + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataListfifoDL(); + if (pFifo) + { + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + } + //...Roundoff inbound msg byte count to nearest KB for display; //...no need to do so for outbound, because it should be small. uint64_t msgBytesInKB = fMsgBytesIn >> 10; if (fMsgBytesIn & 512) msgBytesInKB++; - + + // @bug 828 + if (fifo) + fifo->totalSize(fRidResults); + if (traceOn()) { dlTimes.setEndOfInputTime(); @@ -742,14 +757,16 @@ void pDictionaryScan::receivePrimitiveMessages() logStr << "ses:" << fSessionId << " st: " << fStepId <<" finished at "<< timeString << "; PhyI/O-" << fPhysicalIO << "; CacheI/O-" << fCacheIO << "; MsgsSent-" << fMsgsToPm << "; MsgsRcvd-" << msgsRecvd << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << "; output size-" << fRidResults << endl << "\tMsgBytesIn-" << msgBytesInKB << "KB" "; MsgBytesOut-" << fMsgBytesOut << "B" << endl << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime())<< "s" << endl - << "\tJob completion status " << status() << endl; - + << "\tJob completion status " << fInputJobStepAssociation.status() << endl; + logEnd(logStr.str().c_str()); syslogReadBlockCounts(16, // exemgr subsystem @@ -762,23 +779,17 @@ void pDictionaryScan::receivePrimitiveMessages() dlTimes.FirstInsertTime(), // first datlist write dlTimes.EndOfInputTime()); // last (endOfInput) datalist write syslogEndStep(16, // exemgr subsystem + totalBlockedReadCount, // blocked datalist input + totalBlockedWriteCount, // blocked datalist output fMsgBytesIn, // incoming msg byte count fMsgBytesOut); // outgoing msg byte count fExtendedInfo += toString() + logStr.str(); formatMiniStats(); } - - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.phy_io = fPhysicalIO; - sts.cache_io = fCacheIO; - sts.msg_rcv_cnt = sts.total_units_of_work = sts.units_of_work_completed = msgsRecvd; - sts.msg_bytes_in = fMsgBytesIn; - sts.msg_bytes_out = fMsgBytesOut; - sts.rows = fRidResults; - postStepSummaryTele(sts); } - rgFifo->endOfInput(); + // Bug 3136, let mini stats to be formatted if traceOn. + dlp->endOfInput(); } const string pDictionaryScan::toString() const @@ -838,7 +849,7 @@ void pDictionaryScan::serializeEqualityFilter() { ByteStream msg; ISMPacketHeader ism; - uint32_t i; + uint i; vector empty; memset(&ism, 0, sizeof(ISMPacketHeader)); @@ -853,21 +864,25 @@ void pDictionaryScan::serializeEqualityFilter() } catch (const IDBExcept &e) { abort(); - cerr << "pDictionaryScan::serializeEqualityFilter() caught: " << e.what() << endl; - catchHandler(e.what(), e.errorCode(), fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(e.errorCode()); } catch (const std::exception& e) { abort(); cerr << "pDictionaryScan::serializeEqualityFilter() caught: " << e.what() << endl; - catchHandler(e.what(), ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); } catch (...) { abort(); cerr << "pDictionaryScan::serializeEqualityFilter() caught unknown exception" << endl; - catchHandler("pDictionaryScan::serializeEqualityFilter() caught unknown exception", - ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler("pDictionaryScan::serializeEqualityFilter() caught unknown exception"); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); } empty.swap(equalityFilter); } @@ -886,20 +901,25 @@ void pDictionaryScan::destroyEqualityFilter() } catch (const IDBExcept &e) { abort(); - catchHandler(e.what(), e.errorCode(), fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(e.errorCode()); } catch (const std::exception& e) { abort(); cerr << "pDictionaryScan::destroyEqualityFilter() caught: " << e.what() << endl; - catchHandler(e.what(), ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); } catch (...) { abort(); cerr << "pDictionaryScan::destroyEqualityFilter() caught unknown exception" << endl; - catchHandler("pDictionaryScan::destroyEqualityFilter() caught unknown exception", - ERR_DICTIONARY_SCAN, fErrorInfo, fSessionId); + catchHandler("pDictionaryScan::destroyEqualityFilter() caught unknown exception"); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_DICTIONARY_SCAN); } } diff --git a/dbcon/joblist/pidxlist.cpp b/dbcon/joblist/pidxlist.cpp new file mode 100644 index 00000000..2ed37a23 --- /dev/null +++ b/dbcon/joblist/pidxlist.cpp @@ -0,0 +1,487 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** + * $Id: pidxlist.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + * + ***********************************************************************/ +using namespace std; +#include "pidxlist.h" +#include "distributedenginecomm.h" +#include "elementtype.h" +#include "unique32generator.h" + +#include "messagequeue.h" +using namespace messageqcpp; +#include "configcpp.h" +using namespace config; + +using namespace logging; + +using namespace execplan; + +#include "brm.h" +using namespace BRM; + +#ifdef PROFILE +void ltimespec_sub(const struct timespec &tv1, const struct timespec &tv2, + struct timespec &diff) +{ + if (tv2.tv_nsec < tv1.tv_nsec) { + diff.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; + diff.tv_nsec = tv1.tv_nsec - tv2.tv_nsec; + } + else + { + diff.tv_sec = tv2.tv_sec - tv1.tv_sec; + diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; + } +} +#endif + +namespace joblist +{ + + const size_t ELEMENTS_PER_MESSAGE = (MAX_BUFFER_SIZE - sizeof(IndexListHeader))/sizeof(uint64_t); + + struct IndexElementComparer + { + bool operator() (const IndexListParam& lhs, const IndexListParam& rhs) const + { + return (lhs.fbo < rhs.fbo); + } + }; + + struct pIdxListPrimitive + { + pIdxListPrimitive(pIdxList* ptr) : fpIdxList(ptr) {} + pIdxList* fpIdxList; + void operator()() + { + try + { + fpIdxList->sendPrimitiveMessages(); + } + catch(runtime_error& re) + { + catchHandler(re.what()); + } + catch(...) + { + catchHandler("pIdxList send caught an unknown exception"); + } + + } + }; + + struct pIdxListAggregator + { + pIdxListAggregator(pIdxList* ptr) : fpIdxList(ptr) + {} + pIdxList* fpIdxList; + void operator()() + { + try + { + fpIdxList->receivePrimitiveMessages(); + } + catch(runtime_error& re) + { + catchHandler(re.what()); + } + catch(...) + { + catchHandler("pIdxList receive caught an unknown exception"); + } + } + }; + + + pIdxList::pIdxList(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + CalpontSystemCatalog* cat, + execplan::CalpontSystemCatalog::OID oid, + execplan::CalpontSystemCatalog::OID tableOid, + uint32_t session, + uint32_t txn, + uint32_t verID, + uint16_t step, + uint32_t statement) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + fSysCat(cat), + fOid(oid), + fTableOid(tableOid), + fSessionId(session), + fTxnId(txn), + fVerId(verID), + fStepId(step), + fStatementId(statement), + fMsgsSent(0), + fMsgsRecvd(0), + fFinishedSending(false), + fRecvWaiting(false), + fConsumerThread(), + fProducerThread(), + fMutex(), + fCondvar() +{ + uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + if (fDec) + fDec->addQueue(uniqueID); +} + +pIdxList::~pIdxList() +{ + if (fDec) + fDec->removeQueue(uniqueID); +} + + void pIdxList::startPrimitiveThread() + { + fProducerThread.reset(new boost::thread(pIdxListPrimitive(this))); + } + + void pIdxList::startAggregationThread() + { + fConsumerThread.reset(new boost::thread(pIdxListAggregator(this))); + } + + void pIdxList::run() + { +#ifdef PROFILE + clock_gettime(CLOCK_REALTIME, &fTs1); +#endif + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + std::string("pIdxList")); // step name + } + + pthread_mutex_init(&fMutex, NULL); + pthread_cond_init(&fCondvar, NULL); + startPrimitiveThread(); + startAggregationThread(); + } + + void pIdxList::join() + { + fProducerThread->join(); + fConsumerThread->join(); + pthread_mutex_destroy(&fMutex); + pthread_cond_destroy(&fCondvar); + } + + + void pIdxList::makeIndexHeader(IndexListHeader& indexHdr) + { + indexHdr.ism.Interleave=0; + indexHdr.ism.Flags=planFlagsToPrimFlags(fTraceFlags); + indexHdr.ism.Command=INDEX_LIST; + indexHdr.ism.Type=2; + indexHdr.ism.Status=0; + + // Init the Index List Structure + indexHdr.Hdr.SessionID = fSessionId; + indexHdr.Hdr.TransactionID = fTxnId; + indexHdr.Hdr.VerID = fVerId; + indexHdr.Hdr.StepID = fStepId; + indexHdr.Hdr.UniqueID = uniqueID; + + indexHdr.NVALS = 0; + indexHdr.Pad1 = 0; + indexHdr.Pad1 = 0; + } + + void pIdxList::sendError(uint16_t status) + { + fOutputJobStepAssociation.status(status); + + uint16_t size = sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader); + ISMPacketHeader ism; + ism.Command = INDEX_LIST; + ism.Size = size; + ism.Type = 2; + ism.Status = status; + PrimitiveHeader ph = {fSessionId, 0, fTxnId, fVerId, fStepId, uniqueID }; + ByteStream primMsg(size); + primMsg.load((const uint8_t *) &ism, sizeof(ism)); + primMsg.append((const uint8_t *) &ph, sizeof(ph)); + fDec->write(primMsg); + updateMsgSent(); + } + + void pIdxList::updateMsgSent(bool notify) + { + pthread_mutex_lock(&fMutex); + fMsgsSent++; + if (notify && fRecvWaiting ) + pthread_cond_signal(&fCondvar); +#ifdef DEBUG + cout << "IndexList msgsSent++ = " << fMsgsSent << endl; +#endif + pthread_mutex_unlock(&fMutex); + } + + + void pIdxList::sendPrimitiveMessages() + { + try + { + if (0 < fInputJobStepAssociation.status() ) + { + sendError(fInputJobStepAssociation.status()); + } + else + { + IndexListHeader indexHdr; + makeIndexHeader(indexHdr); + + if ( ! fInputJobStepAssociation.outSize() ) + throw logic_error("No input datalist to fIdxList"); + + ZonedDL* indexParams = fInputJobStepAssociation.outAt(0)->zonedDL(); + + if ( ! indexParams ) + throw logic_error("IdxList requires IndexParam list"); + + ByteStream msgParams; + ByteStream primMsg(MAX_BUFFER_SIZE); + + //Repackage the IndexListParams into send messages according to block (fbo) + ElementType e; + int it = indexParams->getIterator(); + bool more = indexParams->next(it, &e); + while (more) + { + IndexListParam* param = reinterpret_cast(&e.second); + uint64_t block = param->fbo; + while (ELEMENTS_PER_MESSAGE > indexHdr.NVALS && more && block == param->fbo ) + { + msgParams << *((uint64_t* ) &(*param)); + indexHdr.NVALS++; + more = indexParams->next(it, &e); + } + +#ifdef DEBUG + cout << "IndexList sending a prim msg" << endl; +#endif + if (indexHdr.NVALS) + { + indexHdr.ism.Size =+ indexHdr.NVALS * 8; + indexHdr.LBID = block; + primMsg.load((const uint8_t *) &indexHdr, sizeof(IndexListHeader)); + primMsg += msgParams; + fDec->write(primMsg); + updateMsgSent(); + + makeIndexHeader(indexHdr); + primMsg.reset(); + msgParams.reset(); + } + } + } // else no error + } // try +catch(const exception& e) +{ + catchHandler(e.what()); + sendError(pIdxListErr); +} +catch(...) +{ + catchHandler("pIdxList send caught an unknown exception."); + sendError(pIdxListErr); +} + + pthread_mutex_lock(&fMutex); + fFinishedSending = true; + if (fRecvWaiting) + pthread_cond_signal(&fCondvar); + pthread_mutex_unlock(&fMutex); + } + + bool pIdxList::syncWithSend() + { + pthread_mutex_lock(&fMutex); + while (!fFinishedSending && fMsgsSent == fMsgsRecvd) + { + fRecvWaiting = true; + + pthread_cond_wait(&fCondvar, &fMutex); + + fRecvWaiting = false; + } + if (fMsgsSent == fMsgsRecvd) + { + pthread_mutex_unlock(&fMutex); + return true; + } + fMsgsRecvd++; +#ifdef DEBUG + cout << "IndexList msgsRecvd++ = " << fMsgsRecvd << endl; +#endif + pthread_mutex_unlock(&fMutex); + return false; + } + + + +void pIdxList::receivePrimitiveMessages() +{ + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + ZonedDL* dlp = dl->zonedDL(); + int64_t results = 0; + try + { + uint16_t error = fOutputJobStepAssociation.status(); + while (! error) + { + if (syncWithSend()) + break; + // read the results + ByteStream bs = fDec->read(uniqueID); + if (bs.length() == 0) break; + +#ifdef DEBUG + cout << "Got an IndexListHeader!: " << bs.length() << " bytes" << endl; +#endif + + const ByteStream::byte* bsp = bs.buf(); + + // get the IdxListHeader out of the bytestream and ready one for resend + const IndexListHeader* idxHdr = reinterpret_cast(bsp); + if (0 == (error = idxHdr->ism.Status)) + { + uint16_t nvals = idxHdr->NVALS; + + IndexListHeader msgHdr(*idxHdr); + msgHdr.NVALS = 1; + + msgHdr.ism.Command = INDEX_LIST; + bsp += sizeof(IndexListHeader); + + // The remainder of the bytestream is the returned data from the primitive server. + // If the data is RID type, then it is a result and put in the output datalist. + // Otherwise it gets sent back to the primitive processor with the fbo as the lbid. + +#ifdef DEBUG + + cout << " IndexList returned values = " << nvals << endl; +#endif + for(uint16_t j = 0; j < nvals; j++) + { + const IndexListEntry *walk = reinterpret_cast(bsp); + switch (walk->type) + { + case RID: + { + dlp->insert(ElementType(walk->value, 0)); + pthread_mutex_lock(&fMutex); + ++results; + pthread_mutex_unlock(&fMutex); +#ifdef DEBUG + cout << " IndexList -- inserting <" << walk->value << ">\n"; +#endif + break; + } + case LLP_SUBBLK: + case LLP_BLK: + { + const IndexListParam* param = reinterpret_cast(bsp); //same size as IndexListEntry + msgHdr.LBID = param->fbo; //update header with LBID from param. + ByteStream primMsg; + primMsg.load((const uint8_t*) &msgHdr, sizeof(IndexListHeader) ); + primMsg.append((const uint8_t*) param, sizeof(IndexListEntry) ); + fDec->write(primMsg); + + updateMsgSent(false); + +#ifdef DEBUG + cout << " IndexList -- resending < " << idxHdr->LBID << " >" << endl; +#endif + primMsg.reset(); + break; + } + default: + break; + + }//switch + bsp += sizeof(IndexListEntry); + } //for + } // if error == 0 + + } //while == 0 + } + catch(const exception& e) + { + catchHandler(e.what()); + fOutputJobStepAssociation.status(pIdxListErr); + } + catch(...) + { + catchHandler("pIdxList receive caught an unknown exception."); + fOutputJobStepAssociation.status(pIdxListErr); + } + + + fDec->removeQueue(uniqueID); + + dlp->endOfInput(); + + //@bug 699: Reset StepMsgQueue + + if (traceOn()) + { + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist output to report + } + +#ifdef PROFILE + timespec diff; + clock_gettime(CLOCK_REALTIME, &fTs2); + ltimespec_sub(fTs1, fTs2, diff); + cout << "pIdxList execution stats:" << endl; + cout << " Primitive msgs sent & recvd: " << fMsgsSent << endl; + cout << " # of data results returned: " << results << endl; + cout << " total runtime: " << diff.tv_sec << "s " << diff.tv_nsec << + "ns" << endl; +#endif +} + + const string pIdxList::toString() const + { + ostringstream oss; + oss << "pIdxList ses:" << fSessionId << " txn:" << fTxnId << " ver:" << fVerId << " st:" << fStepId << + " tb/idxList:" << fTableOid << "/" << fOid; + oss << " " << omitOidInDL + << fOutputJobStepAssociation.outAt(0) << showOidInDL; + oss << " nf:0"; + oss << " in:"; + for (unsigned i = 0; i < fInputJobStepAssociation.outSize(); i++) + { + oss << fInputJobStepAssociation.outAt(i) << ", "; + } + return oss.str(); + } + + } //namespace + + diff --git a/dbcon/joblist/pidxlist.h b/dbcon/joblist/pidxlist.h new file mode 100644 index 00000000..6d7e665b --- /dev/null +++ b/dbcon/joblist/pidxlist.h @@ -0,0 +1,176 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** + * $Id: pidxlist.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + * + ***********************************************************************/ +/** @file */ + +#ifndef JOBLIST_PIDXLIST_H_ +#define JOBLIST_PIDXLIST_H_ + +#include +#include + +#include "jobstep.h" + +namespace joblist +{ + /** @brief pIdxList definition + * Takes the output (rids) from the index walk function and + * looks up the rids pointed to by the index walk pointers + */ + class pIdxList : public JobStep, public PrimitiveMsg + { + public: + /** @brief pIdxList constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer + */ + pIdxList(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + execplan::CalpontSystemCatalog* syscat, + execplan::CalpontSystemCatalog::OID oid, + execplan::CalpontSystemCatalog::OID tableOid, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId); + + virtual ~pIdxList(); + + /** @brief Starts processing. + * + * Starts processing. + */ + virtual void run(); + + /** @brief Sync's the caller with the end of execution. + * + * Does nothing. Returns when this instance is finished. + */ + virtual void join(); + + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + /** @brief The main loop for the send-side thread + * + * The main loop for the primitive-issuing thread. Don't call it directly. + */ + void sendPrimitiveMessages(); + + /** @brief The main loop for the recv-side thread + * + * The main loop for the receive-side thread. Don't call it directly. + */ + void receivePrimitiveMessages(); + + /** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ + void dec(DistributedEngineComm* dec) { fDec = dec; if (fDec) fDec->addQueue(uniqueID); } + + /** @brief Set the step ID of this JobStep + * + * Set the step ID of this JobStep. + */ + virtual void stepId(uint16_t stepId) { fStepId = stepId; } + virtual uint16_t stepId() const { return fStepId; } + + virtual uint32_t sessionId() const { return fSessionId; } + virtual uint32_t txnId() const { return fTxnId; } + virtual uint32_t statementId() const { return fStatementId; } + + virtual const std::string toString() const; + void logger(const SPJL& logger) { fLogger = logger; } + execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } + private: + pIdxList(const pIdxList& rhs); + pIdxList& operator=(const pIdxList& rhs); + + typedef boost::shared_ptr SPTHD; + + void startPrimitiveThread(); + void startAggregationThread(); + void makeIndexHeader(IndexListHeader& indexHdr); + void updateMsgSent(bool notify = true); + bool syncWithSend(); + void sendError(uint16_t status); + + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + DistributedEngineComm* fDec; + execplan::CalpontSystemCatalog* fSysCat; + execplan::CalpontSystemCatalog::OID fOid; + execplan::CalpontSystemCatalog::OID fTableOid; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; + + int fMsgsSent; + int fMsgsRecvd; + bool fFinishedSending; + bool fRecvWaiting; + + SPTHD fConsumerThread; + SPTHD fProducerThread; + boost::mutex fMutex; + boost::condition fCondvar; + SPJL fLogger; + uint32_t uniqueID; + +#ifdef PROFILE + timespec fTs1, fTs2; +#endif + }; + +} + +#endif + diff --git a/dbcon/joblist/pidxwalk.cpp b/dbcon/joblist/pidxwalk.cpp new file mode 100644 index 00000000..808246e1 --- /dev/null +++ b/dbcon/joblist/pidxwalk.cpp @@ -0,0 +1,578 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** + * $Id: pidxwalk.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + * + ***********************************************************************/ +using namespace std; +#include "pidxwalk.h" +#include "distributedenginecomm.h" +#include "elementtype.h" +#include "unique32generator.h" + +#include "messagequeue.h" +using namespace messageqcpp; +#include "configcpp.h" +using namespace config; + +using namespace logging; + +using namespace execplan; + +#include "brm.h" +using namespace BRM; + +#ifdef PROFILE +void itimespec_sub(const struct timespec &tv1, const struct timespec &tv2, + struct timespec &diff) +{ + if (tv2.tv_nsec < tv1.tv_nsec) + { + diff.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; + diff.tv_nsec = tv1.tv_nsec - tv2.tv_nsec; + } + else + { + diff.tv_sec = tv2.tv_sec - tv1.tv_sec; + diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; + } +} +#endif + +namespace joblist +{ + const size_t SEARCH_STRING_SIZE = 2; + const size_t ELEMENTS_PER_MESSAGE = (MAX_BUFFER_SIZE - sizeof(IndexWalkHeader))/sizeof(uint64_t); + + struct pIdxWalkPrimitive + { + pIdxWalkPrimitive(pIdxWalk* ptr) : fpIdxWalk(ptr) {} + pIdxWalk* fpIdxWalk; + void operator()() + { + try + { + fpIdxWalk->sendPrimitiveMessages(); + } + catch(runtime_error& re) + { + catchHandler(re.what()); + } + catch(...) + { + catchHandler("pIdxWalk send caught an unknown exception"); + } + } + }; + + struct pIdxWalkAggregator + { + pIdxWalkAggregator(pIdxWalk* ptr) : fpIdxWalk(ptr) + {} + pIdxWalk* fpIdxWalk; + void operator()() + { + try + { + fpIdxWalk->receivePrimitiveMessages(); + } + catch(runtime_error& re) + { + catchHandler(re.what()); + } + catch(...) + { + catchHandler("pIdxWalk receive caught an unknown exception"); + } + } + }; + + + pIdxWalk::pIdxWalk(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + CalpontSystemCatalog* cat, + CalpontSystemCatalog::OID idxTreeOid, + execplan::CalpontSystemCatalog::OID columnOid, + execplan::CalpontSystemCatalog::OID tableOid, + uint32_t session, + uint32_t txn, + uint32_t verID, + uint16_t step, + uint32_t statement) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fDec(dec), + fSysCat(cat), + fOid(idxTreeOid), + fColumnOid(columnOid), + fTableOid(tableOid), + fSessionId(session), + fTxnId(txn), + fVerId(verID), + fStepId(step), + fStatementId(statement), + fBop(BOP_NONE), + fColType(), + fLBID(0), + fMsgsSent(0), + fMsgsRecvd(0), + fFinishedSending(false), + fRecvWaiting(false), + fSearchStrings(), + fCop1(COMPARE_EQ), + fCop2(COMPARE_NIL), + fConsumerThread(), + fProducerThread(), + fMutex(), + fCondvar(), + fFilterCount(0) + { + DBRM dbrm; + fColType = fSysCat->colType(fColumnOid); + + bool err = dbrm.lookup(fOid, 0, fLBID); + if (err) + throw runtime_error("pIdxWalk: BRM error!"); + + uniqueID = UniqueNumberGenerator::instance()->getUnique32(); + if (fDec) + fDec->addQueue(uniqueID); + } + +pIdxWalk::~pIdxWalk() +{ + if (fDec) + fDec->removeQueue(uniqueID); +} + + void pIdxWalk::startPrimitiveThread() + { + fProducerThread.reset(new boost::thread(pIdxWalkPrimitive(this))); + } + + void pIdxWalk::startAggregationThread() + { + fConsumerThread.reset(new boost::thread(pIdxWalkAggregator(this))); + } + + void pIdxWalk::run() + { +#ifdef PROFILE + clock_gettime(CLOCK_REALTIME, &fTs1); +#endif + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + std::string("pIdxWalk")); // step name + } + + pthread_mutex_init(&fMutex, NULL); + pthread_cond_init(&fCondvar, NULL); + startPrimitiveThread(); + startAggregationThread(); + } + + void pIdxWalk::join() + { + fProducerThread->join(); + fConsumerThread->join(); + pthread_mutex_destroy(&fMutex); + pthread_cond_destroy(&fCondvar); + } + + + void pIdxWalk::addSearchStr(int8_t cop, int64_t value) + { + if (SEARCH_STRING_SIZE > fSearchStrings.size()) + { + if (fSearchStrings.empty()) + fCop1 = cop; + else fCop2 = cop; + + fSearchStrings.push_back(value); + } + else + { +#ifdef DEBUG + cout << "IdxWalk only allows " << SEARCH_STRING_SIZE << " search strings\n"; +#endif + ; + } + } + + + void pIdxWalk::makeIndexHeader(IndexWalkHeader& indexHdr) + { + indexHdr.ism.Interleave=0; + indexHdr.ism.Flags=planFlagsToPrimFlags(fTraceFlags); + indexHdr.ism.Command=INDEX_WALK; + indexHdr.ism.Size=sizeof(IndexWalkHeader); + indexHdr.ism.Type=CMD; + + // Init the Index List Structure + indexHdr.Hdr.SessionID = fSessionId; + indexHdr.Hdr.StatementID = 0; + indexHdr.Hdr.TransactionID = fTxnId; + indexHdr.Hdr.VerID = fVerId; + indexHdr.Hdr.StepID = fStepId; + + indexHdr.LBID = fLBID; + idbassert(indexHdr.LBID >= 0); + + indexHdr.SSlen = fColType.colWidth * 8; + indexHdr.Shift = 0; + indexHdr.BOP = fBop; + indexHdr.COP1 = fCop1; + indexHdr.COP2 = fCop2; + indexHdr.State = 0; + indexHdr.NVALS = (uint16_t)(fSearchStrings.size() > SEARCH_STRING_SIZE ? SEARCH_STRING_SIZE : fSearchStrings.size()); + + indexHdr.SubBlock = 1; + indexHdr.SBEntry = 0; + + for (size_t i = 0; i < indexHdr.NVALS; ++i) + indexHdr.SearchString[i] = fSearchStrings[i]; + fSearchStrings.clear(); + fCop1 = COMPARE_EQ; + fCop2 = COMPARE_NIL; + + } + + void pIdxWalk::sendError(uint16_t status) + { + fOutputJobStepAssociation.status(status); + + uint16_t size = sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader); + ISMPacketHeader ism; + ism.Command = INDEX_WALK; + ism.Size = size; + ism.Type = 2; + ism.Status = status; + PrimitiveHeader ph = {fSessionId, 0, fTxnId, fVerId, fStepId, uniqueID }; + ByteStream primMsg(size); + primMsg.load((const uint8_t *) &ism, sizeof(ism)); + primMsg.append((const uint8_t *) &ph, sizeof(ph)); + fDec->write(primMsg); + updateMsgSent(); + } + + + void pIdxWalk::updateMsgSent() + { + pthread_mutex_lock(&fMutex); + fMsgsSent++; + if (fRecvWaiting) + pthread_cond_signal(&fCondvar); +#ifdef DEBUG + cout << "IndexWalk msgsSent++ = " << fMsgsSent << endl; +#endif + pthread_mutex_unlock(&fMutex); + } + + void pIdxWalk::sendPrimitiveMessages() + { + +try +{ + if (0 < fInputJobStepAssociation.status() ) + { + sendError(fInputJobStepAssociation.status()); + } + else + { + + IndexWalkHeader indexHdr; + makeIndexHeader(indexHdr); + + ByteStream primMsg(MAX_BUFFER_SIZE); + ByteStream msgElements; + + if (fInputJobStepAssociation.outSize() ) + { + ZonedDL* tokenList = fInputJobStepAssociation.outAt(0)->zonedDL(); + int it = tokenList->getIterator(); + ElementType e; + bool more = tokenList->next(it, &e); + //if there are 2 or less tokens use the SearchString, otherwise add after header. + if (SEARCH_STRING_SIZE >= tokenList->totalSize() ) + { + while (more ) + { + indexHdr.SearchString[indexHdr.NVALS++] = e.second; + more = tokenList->next(it, &e); + } + indexHdr.COP2 = COMPARE_EQ; + } + else + while ( more ) + { + if (ELEMENTS_PER_MESSAGE > indexHdr.NVALS) + { + msgElements << e.second; + indexHdr.NVALS++; + more = tokenList->next(it, &e); + } + else + { + indexHdr.ism.Size =+ indexHdr.NVALS * 8; + + primMsg.load((const uint8_t *) &indexHdr, sizeof(IndexWalkHeader)); + primMsg += msgElements; + fDec->write(primMsg); + updateMsgSent(); + + makeIndexHeader(indexHdr); + primMsg.reset(); + msgElements.reset(); + } + } + } + + primMsg.load((const uint8_t *) &indexHdr, sizeof(IndexWalkHeader)); + if (SEARCH_STRING_SIZE < indexHdr.NVALS) + { + indexHdr.ism.Size =+ indexHdr.NVALS * 8; + primMsg += msgElements; + } + fDec->write(primMsg); + updateMsgSent(); + } //else fInputJobStepAssociation.status() == 0 + } //try +catch(const exception& e) +{ + catchHandler(e.what()); + sendError(pIdxWalkErr); +} +catch(...) +{ + catchHandler("pIdxWalk send caught an unknown exception."); + sendError(pIdxWalkErr); +} + + pthread_mutex_lock(&fMutex); + fFinishedSending = true; + if (fRecvWaiting) + pthread_cond_signal(&fCondvar); + pthread_mutex_unlock(&fMutex); + } + + + bool pIdxWalk::syncWithSend() + { + pthread_mutex_lock(&fMutex); + while (!fFinishedSending && fMsgsSent == fMsgsRecvd) + { + fRecvWaiting = true; + + pthread_cond_wait(&fCondvar, &fMutex); + + fRecvWaiting = false; + } + if (fMsgsSent == fMsgsRecvd) + { + pthread_mutex_unlock(&fMutex); + return true; + } + fMsgsRecvd++; +#ifdef DEBUG + cout << "IndexWalk msgsRecvd++ = " << fMsgsRecvd << endl; +#endif + pthread_mutex_unlock(&fMutex); + return false; + } + + void pIdxWalk::receivePrimitiveMessages() + { + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); + ZonedDL* dlp = dl->zonedDL(); + int64_t results = 0; + try + { + uint16_t error = fOutputJobStepAssociation.status(); + while (! error) + { + if (syncWithSend()) + break; + + // read the results + ByteStream bs = fDec->read(uniqueID); + if (bs.length() == 0) break; + +#ifdef DEBUG + cout << "IdxWalk: Got an IndexResultHeader!: " << bs.length() << " bytes" << endl; +#endif + + const ByteStream::byte* bsp = bs.buf(); + const ISMPacketHeader* ism = reinterpret_cast(bsp); + if (0 == (error = ism->Status)) + { + bsp += sizeof(ISMPacketHeader); + const IndexResultHeader* resultHdr = reinterpret_cast(bsp); + uint16_t nvals = resultHdr->NVALS; + bsp += sizeof(IndexResultHeader); + // The rest of the bytestream is returned data from the primitive server. + // If it has been shifted all the way it is complete and the results are + // put into the output as an IndexListParam, otherwise it is + // sent back to the primitives with an INDEX_WALK command. + ByteStream primMsg; + ByteStream primMsgParam; +#ifdef DEBUG + + cout << " IdxWalk: returned values = " << nvals << endl; +#endif + IndexListParam listParam; + listParam.type = 0; + listParam.spare = 0; + + for(uint16_t j = 0; j < nvals; j++) + { + const IndexWalkHeader* walk = reinterpret_cast(bsp); + + //This one is finished + if (walk->Shift >= walk->SSlen) + { + listParam.fbo = walk->LBID; + listParam.sbid = walk->SubBlock; + listParam.entry = walk->SBEntry; + //what about an rid? + dlp->insert(ElementType(0, *reinterpret_cast(&listParam))); + bsp += sizeof(IndexWalkHeader); + if (SEARCH_STRING_SIZE < walk->NVALS) + bsp += walk->NVALS * 8; + pthread_mutex_lock(&fMutex); + ++results; + pthread_mutex_unlock(&fMutex); + } + else + //This one is sent back to the primitives with its data and an INDEX_WALK command + { + int len = sizeof(IndexWalkHeader); + if (2 < walk->NVALS) + len += (walk->NVALS * 8); + //We need the header and the data behind it. + char* buffer = new char[len]; + memcpy(buffer, (char*)walk, len); + reinterpret_cast(buffer)->ism.Command = INDEX_WALK; + primMsg.load((const uint8_t*)buffer, len ); + fDec->write(primMsg); + bsp += len; + delete [] buffer; + updateMsgSent(); + } + } //for + } // if error == 0 + } //while +} //try + + catch(const exception& e) + { + catchHandler(e.what()); + fOutputJobStepAssociation.status(pIdxWalkErr); + } + catch(...) + { + catchHandler("pIdxWalk receive caught an unknown exception."); + fOutputJobStepAssociation.status(pIdxWalkErr); + } + + dlp->endOfInput(); + + fDec->removeQueue(uniqueID); + + if (traceOn()) + { + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist output to report + } + +#ifdef PROFILE + timespec diff; + clock_gettime(CLOCK_REALTIME, &fTs2); + itimespec_sub(fTs1, fTs2, diff); + cout << "pIdxWalk execution stats:" << endl; + cout << " Primitive msgs sent & recvd: " << fMsgsSent << endl; + cout << " # of data results returned: " << results << endl; + cout << " total runtime: " << diff.tv_sec << "s " << diff.tv_nsec << + "ns" << endl; +#endif + } + + const string pIdxWalk::toString() const + { + ostringstream oss; + oss << "pIdxWalk ses:" << fSessionId << " txn:" << fTxnId << " ver:" << fVerId << " st:" << fStepId << + " tb/col/idxTree:" << fTableOid << "/" << fColumnOid << "/" << fOid; + oss << " " << omitOidInDL + << fOutputJobStepAssociation.outAt(0) << showOidInDL; + oss << " nf:" << fFilterCount; + oss << " in:"; + for (unsigned i = 0; i < fInputJobStepAssociation.outSize(); i++) + { + oss << fInputJobStepAssociation.outAt(i) << ", "; + } + return oss.str(); + } + + void pIdxWalk::addFilter(int8_t COP, float value) + { + fFilterString << (uint8_t) COP; + fFilterString << *((uint32_t *) &value); + fFilterCount++; + } + + void pIdxWalk::addFilter(int8_t COP, int64_t value) + { + int8_t tmp8; + int16_t tmp16; + int32_t tmp32; + + fFilterString << (uint8_t) COP; + + // converts to a type of the appropriate width, then bitwise + // copies into the filter ByteStream + switch(fColType.colWidth) { + case 1: + tmp8 = value; + fFilterString << *((uint8_t *) &tmp8); + break; + case 2: + tmp16 = value; + fFilterString << *((uint16_t *) &tmp16); + break; + case 4: + tmp32 = value; + fFilterString << *((uint32_t *) &tmp32); + break; + case 8: + fFilterString << *((uint64_t *) &value); + break; + default: + ostringstream o; + + o << "pColScanStep: CalpontSystemCatalog says OID " << fOid << + " has a width of " << fColType.colWidth; + throw runtime_error(o.str()); + } + fFilterCount++; +} + } //namespace + + diff --git a/dbcon/joblist/pidxwalk.h b/dbcon/joblist/pidxwalk.h new file mode 100644 index 00000000..6e3140f1 --- /dev/null +++ b/dbcon/joblist/pidxwalk.h @@ -0,0 +1,215 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** + * $Id: pidxwalk.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + * + ***********************************************************************/ +/** @file */ + +#ifndef JOBLIST_PIDXWALK_H_ +#define JOBLIST_PIDXWALK_H_ + +#include +#include +#include + +#include "jobstep.h" + +namespace joblist +{ + /** @brief pIdxWalk definition + * Does a full index scan using using up to two search filters and with + * filters from tokens from input data list. + */ + class pIdxWalk : public JobStep, public PrimitiveMsg + { + public: + /** @brief pIdxWalk constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer + */ + pIdxWalk(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + execplan::CalpontSystemCatalog* syscat, + execplan::CalpontSystemCatalog::OID oid, + execplan::CalpontSystemCatalog::OID columnOid, + execplan::CalpontSystemCatalog::OID tableOid, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId); + + virtual ~pIdxWalk(); + + /** @brief Starts processing. + * + * Starts processing. + */ + virtual void run(); + + /** @brief Sync's the caller with the end of execution. + * + * Does nothing. Returns when this instance is finished. + */ + virtual void join(); + + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + /** @brief The main loop for the send-side thread + * + * The main loop for the primitive-issuing thread. Don't call it directly. + */ + void sendPrimitiveMessages(); + + /** @brief The main loop for the recv-side thread + * + * The main loop for the receive-side thread. Don't call it directly. + */ + void receivePrimitiveMessages(); + + /** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ + void dec(DistributedEngineComm* dec) { fDec = dec; if (fDec) fDec->addQueue(uniqueID); } + + /** @brief Set the step ID of this JobStep + * + * Set the step ID of this JobStep. + */ + virtual void stepId(uint16_t stepId) { fStepId = stepId; } + virtual uint16_t stepId() const { return fStepId; } + + virtual uint32_t sessionId() const { return fSessionId; } + virtual uint32_t txnId() const { return fTxnId; } + virtual uint32_t statementId() const { return fStatementId; } + + /** @brief Add a search string + * + * Adds a search string with an operator. (Only 2 are implemented.) + */ + void addSearchStr(int8_t cop, int64_t value); + + /** @brief set Bop + * + * Sets the binary operator, valid only if there a 2 search strings. + */ + void setBOP(int8_t bop) { fBop = bop; } + + virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } + execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } + + virtual const std::string toString() const; + + void logger(const SPJL& logger) { fLogger = logger; } + /** @brief Add a filter when the column is a 4-byte float type + * + * Add a filter when the column is a 4-byte float type + */ + void addFilter(int8_t COP, float value); + + /** @brief Add a filter when the column is anything but a 4-byte float type. + * + * Add a filter when the column is anything but a 4-byte float type, including + * 8-byte doubles. + */ + void addFilter(int8_t COP, int64_t value); + + private: + pIdxWalk(const pIdxWalk& rhs); + pIdxWalk& operator=(const pIdxWalk& rhs); + void makeIndexHeader(IndexWalkHeader& hdr); + void updateMsgSent(); + bool syncWithSend(); + void sendError(uint16_t status); + + typedef boost::shared_ptr SPTHD; + + void startPrimitiveThread(); + void startAggregationThread(); + + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + DistributedEngineComm* fDec; + execplan::CalpontSystemCatalog* fSysCat; + execplan::CalpontSystemCatalog::OID fOid; + execplan::CalpontSystemCatalog::OID fColumnOid; + execplan::CalpontSystemCatalog::OID fTableOid; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; + uint8_t fBop; + execplan::CalpontSystemCatalog::ColType fColType; + int64_t fLBID; + int fNOPS; + uint64_t* fVals; + int fMsgsSent; + int fMsgsRecvd; + bool fFinishedSending; + bool fRecvWaiting; + std::vector fSearchStrings; + uint8_t fCop1:5; + uint8_t fCop2:5; + + SPTHD fConsumerThread; + SPTHD fProducerThread; + boost::mutex fMutex; + boost::condition fCondvar; + SPJL fLogger; + messageqcpp::ByteStream fFilterString; + uint fFilterCount; +#ifdef PROFILE + timespec fTs1, fTs2; +#endif + uint32_t uniqueID; + }; + +} + +#endif + diff --git a/dbcon/joblist/pnljoin.cpp b/dbcon/joblist/pnljoin.cpp new file mode 100644 index 00000000..b9092255 --- /dev/null +++ b/dbcon/joblist/pnljoin.cpp @@ -0,0 +1,405 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/***************************************************************************** + * $Id: pnljoin.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + ****************************************************************************/ + +#include "elementtype.h" +#include "jobstep.h" + +using namespace std; + +namespace joblist { + +#ifdef PROFILE +extern void timespec_sub(const struct timespec &tv1, const struct timespec &tv2, + struct timespec &diff); +#endif + + +struct PNLJRunner +{ + PNLJRunner(PNLJoin* p) : joiner(p) + {} + PNLJoin *joiner; + void operator()() + { + try + { + if (joiner->out.outSize() > 1) + joiner->doPNLJoin_reduce(); + else + joiner->doPNLJoin(); + } + catch(runtime_error& re) + { + catchHandler(re.what()); + } + catch(...) + { + catchHandler("PNLJoin caught an unknown exception"); + } + } +}; + +/* Override operator < so sets sort on value not rid */ +class VElementType : public ElementType +{ + public: + VElementType() : ElementType() { } + VElementType(uint64_t f, uint64_t s) : ElementType(f, s) { } + VElementType(const VElementType &d) : ElementType(d) { } + VElementType(const ElementType &d) : ElementType(d) { } + ~VElementType() { }; + void operator=(const ElementType &d) { ElementType::operator=(d); } + bool operator<(const VElementType &d) { return (second < d.second); } +}; + + +PNLJoin::PNLJoin(const JobStepAssociation &i, const JobStepAssociation &o, + DistributedEngineComm* de, execplan::CalpontSystemCatalog* cat, + uint32_t session, uint32_t txn, uint16_t step, uint32_t statement, ResourceManager& rm) + : + in(i), + out(o), + sessionID(session), + txnID(txn), + stepID(step), + statementID(statement), + dec(de), + syscat(cat), + fRm(rm) +{ +} + +PNLJoin::~PNLJoin() +{ } + +const JobStepAssociation& PNLJoin::inputAssociation() const +{ + return in; +} + +void PNLJoin::inputAssociation(const JobStepAssociation& inputAssociation) +{ + in = inputAssociation; +} + +const JobStepAssociation& PNLJoin::outputAssociation() const +{ + return out; +} + +void PNLJoin::outputAssociation(const JobStepAssociation& outputAssociation) +{ + out = outputAssociation; +} + +const std::string PNLJoin::toString() const +{ + // XXXPAT: TBD. + return string("PNLJoin"); +} + +void PNLJoin::stepId(uint16_t s) +{ + stepID = s; +} + +uint16_t PNLJoin::stepId() const +{ + return stepID; +} + +uint32_t PNLJoin::sessionId() const +{ + return sessionID; +} + +uint32_t PNLJoin::txnId() const +{ + return txnID; +} + +uint32_t PNLJoin::statementId() const +{ + return statementID; +} + +void PNLJoin::run() +{ + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + std::string("PNLJoin")); // step name + } + + runner.reset(new boost::thread(PNLJRunner(this))); +} + +void PNLJoin::join() +{ + runner->join(); +} + +void PNLJoin::doPNLJoin() +{ + boost::shared_ptr step; + boost::shared_ptr scan; + JobStepAssociation inJSA, outJSA; + AnyDataList adl; + DataList *filterList; + ElementType e; + int it; + bool more; + try + { + if (0 < in.status()) + out.status(in.status()); + else + { + + filterList = in.outAt(0)->dataList(); + + // if no RID list, do pcolscan + if (in.outSize() == 1) { + + /* + make pColScanStep + get in[0].oid + set the output list to out[0] + read in[0], step.addFilters() + run step + */ + + /* XXXPAT: Will there be confusion here using the same stepID? */ + scan.reset(new pColScanStep(inJSA, out, dec, syscat, filterList->OID(), + 0 /* fudge the tableoid */, sessionID, txnID, txnID /* fudge the verID */, + stepID, statementID, fRm)); + + it = filterList->getIterator(); + for (more = filterList->next(it, &e); + more; + more = filterList->next(it, &e)) + scan->addFilter(COMPARE_EQ, *((int64_t *) &e.second)); + + scan->run(); + scan->join(); + } + + // if RID list, do pcolstep + else { + + /* + make pColStep + get in[0].oid + set the output list to out[0] + read in[0], step.addFilters() + set ridlist to in[1] + run step + */ + + inJSA.outAdd(in.outAt(1)); + step.reset(new pColStep(inJSA, out, dec, syscat, filterList->OID(), + 0 /* fudge the tableoid */, sessionID, txnID, txnID /* fudge the verID */, + stepID, statementID, fRm)); + + it = filterList->getIterator(); + for (more = filterList->next(it, &e); + more; + more = filterList->next(it, &e)) + step->addFilter(COMPARE_EQ, *((int64_t *) &e.second)); + + step->run(); + step->join(); + + } + }// in.status() == 0 + } //try + catch(const exception& e) + { + catchHandler(e.what()); + out.status(logging::pnlJoinErr); + } + catch(...) + { + catchHandler("PNLJoin caught an unknown exception."); + out.status(logging::pnlJoinErr); + } + + + if (traceOn()) + { + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist output to report + } +} + + +void PNLJoin::doPNLJoin_reduce() +{ + // These BucketDLs are tuned to use ~500MB of memory apiece + BucketDL bucketValueList(BUCKETS, 1, PERBUCKET, fRm); + BucketDL stepResult(BUCKETS, 1, PERBUCKET, fRm); + boost::shared_ptr step; + boost::shared_ptr scan; + JobStepAssociation inJSA, outJSA; + DataList *filterList; + DataList *out0, *out1; + AnyDataListSPtr adl1(new AnyDataList()); + set searchSet; + ElementType e; + int it, i; + bool more; + + + filterList = in.outAt(0)->dataList(); + out0 = out.outAt(0)->dataList(); + out1 = out.outAt(1)->dataList(); + adl1->disown(); + adl1->bucketDL(&stepResult); + outJSA.outAdd(adl1); + bucketValueList.setHashMode(1); // use only the values for hash data + stepResult.setHashMode(1); + + try + { + if (0 < in.status()) + out.status(in.status()); + else + { + + if (in.outSize() == 1) { + + /* + make pColScanStep + get in[0].oid + set the output list to stepResult + read in[0] -> step.addFilters(), build in0tmp + run step + */ + scan.reset(new pColScanStep(in, outJSA, dec, syscat, filterList->OID(), + 0 /* fudge the tableoid */, sessionID, txnID, txnID /* fudge the verID */, + stepID, statementID, fRm)); + + it = filterList->getIterator(); + for (more = filterList->next(it, &e); + more; + more = filterList->next(it, &e)) { + scan->addFilter(COMPARE_EQ, *((int64_t *) &e.second)); + bucketValueList.insert(e); + } + bucketValueList.endOfInput(); + + scan->run(); + scan->join(); + + + } + + // if RID list, do pcolstep + else { + + /* + make pColStep + get in[0].oid + set the output list to stepResult + read in[0] -> step.addFilters(), build in0tmp + set ridlist to in[1] + run step + */ + + inJSA.outAdd(in.outAt(1)); + step.reset(new pColStep(inJSA, outJSA, dec, syscat, filterList->OID(), + 0 /* fudge the tableoid */, sessionID, txnID, txnID /* fudge the verID */, + stepID, statementID, fRm)); + + it = filterList->getIterator(); + for (more = filterList->next(it, &e); + more; + more = filterList->next(it, &e)) { + step->addFilter(COMPARE_EQ, *((int64_t *) &e.second)); + bucketValueList.insert(e); + } + bucketValueList.endOfInput(); + + step->run(); + step->join(); + + } + + /* At this point, stepResult contains the result of the column operation, + and bucketValueList contains the filter list in a bucketDL */ + + /* + reduce bucketValueList with stepResult into out[0] and out[1] + + Iterate over buckets, + read stepResult, + fill the set, + copy into out[0]. + read bucketValueList + set.find(), if match, put result in out[1] + */ + for (i = 0; i < BUCKETS; i++) { + it = stepResult.getIterator(i); + more = stepResult.next(i, it, &e); + while (more) { + searchSet.insert(VElementType(e)); + out0->insert(e); + more = stepResult.next(i, it, &e); + } + + it = bucketValueList.getIterator(i); + more = bucketValueList.next(i, it, &e); + while (more) { + if (searchSet.find(VElementType(e)) != searchSet.end()) + out1->insert(e); + more = bucketValueList.next(i, it, &e); + } + searchSet.clear(); + } + + } // if in.status == 0 + }// try + catch(const exception& e) + { + catchHandler(e.what()); + out.status(logging::pnlJoinErr); + } + catch(...) + { + catchHandler("PNLJoin reduce caught an unknown exception."); + out.status(logging::pnlJoinErr); + } + + out0->endOfInput(); + out1->endOfInput(); + + if (traceOn()) + { + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist output to report + } +} + + +} //namespace diff --git a/dbcon/joblist/primitivemsg.cpp b/dbcon/joblist/primitivemsg.cpp index ca12f29c..a0394322 100644 --- a/dbcon/joblist/primitivemsg.cpp +++ b/dbcon/joblist/primitivemsg.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: primitivemsg.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: primitivemsg.cpp 8476 2012-04-25 22:28:15Z xlou $ */ #include diff --git a/dbcon/joblist/primitivemsg.h b/dbcon/joblist/primitivemsg.h index c78f71a5..efc042f6 100644 --- a/dbcon/joblist/primitivemsg.h +++ b/dbcon/joblist/primitivemsg.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: primitivemsg.h 9655 2013-06-25 23:08:13Z xlou $ +* $Id: primitivemsg.h 8774 2012-07-31 21:00:09Z pleblanc $ */ /** @file */ @@ -164,7 +164,6 @@ enum ISMPACKETCOMMAND FLUSH_ALL_VERSION = PRIM_CACHEBASE+4, // Drop all versions of specified LBIDs CACHE_FLUSH_BY_OID = PRIM_CACHEBASE+5, // Drop all versions of all LBIDs for the given OIDs CACHE_FLUSH_PARTITION = PRIM_CACHEBASE+6, // Drop a partition - CACHE_PURGE_FDS = PRIM_CACHEBASE+7, // Purge the file descriptor cache for the modified files //max of 250-200=50 commands DICT_RESULTS = PRIM_DICTBASE+0, @@ -249,12 +248,12 @@ struct ISMPacketHeader //@Bug 2744 changed all variables to 32 bit, and took out StatementID struct PrimitiveHeader { - uint32_t SessionID; // Front end Session Identifier - uint32_t TransactionID; // Front end Transaction Identifier - uint32_t VerID; // DB Version ID used for this Session/Statement - uint32_t StepID; // Internal Primitive Sequence number - uint32_t UniqueID; // Unique ID for DEC and BPP - uint32_t Priority; // Priority level of the user + uint32_t SessionID; // Front end Session Identifier + uint32_t TransactionID; // Front end Transaction Identifier + uint32_t VerID; // DB Version ID used for this Session/Statement + uint32_t StepID; // Internal Primitive Sequence number + uint32_t UniqueID; // Unique ID for DEC and BPP + uint32_t Priority; // Priority level of the user }; #if 0 @@ -278,7 +277,7 @@ struct DiskResultsHeader struct ColLoopback { - PrimitiveHeader Hdr; // 64 bit header + PrimitiveHeader Hdr; // 64 bit header }; // COL_BY_SCAN @@ -286,13 +285,13 @@ struct ColLoopback struct ColByScanRequestHeader { - PrimitiveHeader Hdr; // 64 bit header + PrimitiveHeader Hdr; // 64 bit header uint64_t LBID; int32_t CompType; uint16_t DataSize; - uint8_t DataType; // enum ColDataType defined in calpont system catalog header file - uint8_t OutputType; // 1 = RID, 2 = Token, 3 = Both - uint8_t BOP; // 0 = N/A, 1 = AND, 2 = OR + uint8_t DataType; // enum ColDataType defined in calpont system catalog header file + uint8_t OutputType; // 1 = RID, 2 = Token, 3 = Both + uint8_t BOP; // 0 = N/A, 1 = AND, 2 = OR uint8_t RidFlags; // a bitmap indicating the rid ranges in the resultM SB => row 7168-8191 uint16_t NOPS; uint16_t NVALS; @@ -304,13 +303,13 @@ struct ColByScanRequestHeader struct ColByScanRangeRequestHeader { - PrimitiveHeader Hdr; // 64 bit header - uint64_t LBID; // starting LBID + PrimitiveHeader Hdr; // 64 bit header + uint64_t LBID; //starting LBID int32_t CompType; uint16_t DataSize; - uint8_t DataType; // enum ColDataType defined in calpont system catalog header file - uint8_t OutputType; // 1 = RID, 2 = Token, 3 = Both - uint8_t BOP; // 0 = N/A, 1 = AND, 2 = OR + uint8_t DataType; // enum ColDataType defined in calpont system catalog header file + uint8_t OutputType; // 1 = RID, 2 = Token, 3 = Both + uint8_t BOP; // 0 = N/A, 1 = AND, 2 = OR uint8_t RidFlags; // a bitmap indicating the rid ranges in the result MSB => row 7168-8191 uint16_t NOPS; uint16_t NVALS; @@ -702,8 +701,8 @@ struct NewColResultHeader uint16_t NVALS; uint16_t ValidMinMax; // 1 if Min/Max are valid, otherwise 0 uint32_t OutputType; - int64_t Min; // Minimum value in this block for signed data types - int64_t Max; // Maximum value in this block for signed data types + int64_t Min; // Minimum value in this block (signed) + int64_t Max; // Maximum value in this block (signed) uint32_t CacheIO; // I/O count from buffer cache uint32_t PhysicalIO; // Physical I/O count from disk // if OutputType was OT_DATAVALUE, what follows is DataType[NVALS] @@ -711,7 +710,22 @@ struct NewColResultHeader // if OutputType was OT_BOTH, what follows is NVALS pairs }; +struct NewColAggResultHeader +{ + ISMPacketHeader ism; + PrimitiveHeader hdr; + uint64_t LBID; + int64_t Sum; + uint16_t SumOverflow; // SUM = (SumSign) Sum + (SumOverflow * 2^63) + uint8_t SumSign; // 0 = +, 1 = - + int64_t Min; + int64_t Max; + uint16_t NVALS; //number of values in the block +}; + + /* additional types to support p_dictionary */ + struct DictFilterElement { uint8_t COP; @@ -725,7 +739,7 @@ struct DictInput PrimitiveHeader hdr; uint64_t LBID; uint8_t BOP; - uint8_t InputFlags; // 1 -> 64-bit RID, 64-bit token pairs (old p_GetSignature behavior), + uint8_t InputFlags; // 1 -> 64-bit RID, 64-bit token pairs (old p_GetSignature behavior), // 0-> new behavior uint8_t OutputType; uint16_t NOPS; @@ -762,8 +776,8 @@ struct DictOutput }; //same as TokenByScanResultHeader at the moment struct OldGetSigParams { - uint64_t rid; - uint16_t offsetIndex; + u_int64_t rid; + u_int16_t offsetIndex; }; struct LbidAtVer diff --git a/dbcon/joblist/primitivestep.h b/dbcon/joblist/primitivestep.h index 9c24548e..9b328e38 100644 --- a/dbcon/joblist/primitivestep.h +++ b/dbcon/joblist/primitivestep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: primitivestep.h 9688 2013-07-15 19:27:22Z pleblanc $ +// $Id: primitivestep.h 9144 2012-12-11 22:42:40Z pleblanc $ /** @file */ @@ -55,6 +55,7 @@ #include "primitivemsg.h" #include "elementtype.h" #include "distributedenginecomm.h" +#include "jl_logger.h" #include "lbidlist.h" #include "joblisttypes.h" #include "timestamp.h" @@ -78,7 +79,6 @@ class BatchPrimitiveProcessorJL; class pColStep; class pColScanStep; class PassThruStep; -class PseudoColStep; typedef boost::shared_ptr SP_LBIDList; @@ -128,19 +128,32 @@ class pColScanStep; class pColStep : public JobStep, public PrimitiveMsg { - typedef std::pair element_t; + typedef std::pair element_t; public: /** @brief pColStep constructor - * @param flushInterval The interval in msgs at which the sending side should + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer + * @param flushInterval The interval in msgs at which the sending side should * wait for the receiveing side to catch up. 0 (default) means never. */ - pColStep( + pColStep(const JobStepAssociation& in, + const JobStepAssociation& out, + DistributedEngineComm* ec, + boost::shared_ptr sysCat, execplan::CalpontSystemCatalog::OID oid, execplan::CalpontSystemCatalog::OID tableOid, const execplan::CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo); - + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId, + ResourceManager& rm, + uint32_t flushInterval = 0, + bool isEM = false); + pColStep(const pColScanStep& rhs); pColStep(const PassThruStep& rhs); @@ -148,7 +161,7 @@ class pColStep : public JobStep, public PrimitiveMsg virtual ~pColStep(); /** @brief Starts processing. Set at least the RID list before calling. - * + * * Starts processing. Set at least the RID list before calling this. */ virtual void run(); @@ -158,8 +171,42 @@ class pColStep : public JobStep, public PrimitiveMsg */ virtual void join(); - virtual const std::string toString() const; + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + virtual const std::string toString() const; + + /** @brief Set the step ID for this JobStep. + * + * Set the step ID for this JobStep. + */ + virtual void stepId(uint16_t stepId) { fStepId = stepId; } + virtual bool isDictCol() const { return fIsDict; }; bool isExeMgr() const { return isEM; } @@ -168,9 +215,9 @@ class pColStep : public JobStep, public PrimitiveMsg * Set the config parameters this JobStep. */ void initializeConfigParms(); - - /** @brief The main loop for the send-side thread - * + + /** @brief The main loop for the send-side thread + * * The main loop for the primitive-issuing thread. Don't call it directly. */ void sendPrimitiveMessages(); @@ -182,22 +229,22 @@ class pColStep : public JobStep, public PrimitiveMsg void receivePrimitiveMessages(); /** @brief Add a filter. Use this interface when the column stores anything but 4-byte floats. - * + * * Add a filter. Use this interface when the column stores anything but 4-byte floats. */ void addFilter(int8_t COP, int64_t value, uint8_t roundFlag = 0); void addFilter(int8_t COP, float value); /** @brief Sets the DataList to get RID values from. - * + * * Sets the DataList to get RID values from. Filtering by RID distinguishes * this class from pColScan. Use pColScan if the every RID should be considered; it's * faster at that. */ void setRidList(DataList *rids); - + /** @brief Sets the String DataList to get RID values from. - * + * * Sets the string DataList to get RID values from. Filtering by RID distinguishes * this class from pColScan. Use pColScan if the every RID should be considered; it's * faster at that. @@ -205,27 +252,27 @@ class pColStep : public JobStep, public PrimitiveMsg void setStrRidList(DataList *strDl); /** @brief Set the binary operator for the filter predicate (BOP_AND or BOP_OR). - * + * * Set the binary operator for the filter predicate (BOP_AND or BOP_OR). */ void setBOP(int8_t BOP); /** @brief Set the output type. - * + * * Set the output type (1 = RID, 2 = Token, 3 = Both). */ void setOutputType(int8_t OutputType); /** @brief Set the swallowRows flag. - * - * + * + * * If true, no rows will be inserted to the output datalists. */ void setSwallowRows(const bool swallowRows); /** @brief Get the swallowRows flag. - * - * + * + * * If true, no rows will be inserted to the output datalists. */ bool getSwallowRows() const { return fSwallowRows; } @@ -233,15 +280,33 @@ class pColStep : public JobStep, public PrimitiveMsg virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } virtual execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } - + +/** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ +// void dec(DistributedEngineComm* dec) { +// if (fDec) fDec->removeQueue(uniqueID); +// fDec = dec; +// if (fDec) fDec->addQueue(uniqueID); +// } + +// DistributedEngineComm* dec() const { return fDec; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t verId() const { return fVerId; } + uint16_t stepId() const { return fStepId; } + uint32_t statementId() const { return fStatementId; } uint32_t filterCount() const { return fFilterCount; } - const messageqcpp::ByteStream &filterString() const { return fFilterString; } + messageqcpp::ByteStream filterString() const { return fFilterString; } int8_t BOP() const { return fBOP; } const execplan::CalpontSystemCatalog::ColType& colType() const { return fColType; } + void logger(const SPJL& logger) { fLogger = logger; } + const SPJL& logger() const { return fLogger; } void appendFilter(const messageqcpp::ByteStream& filter, unsigned count); - uint32_t flushInterval() const { return fFlushInterval; } + uint flushInterval() const { return fFlushInterval; } bool getFeederFlag() const { return isFilterFeeder; } - + void setFeederFlag (bool filterFeeder) { isFilterFeeder = filterFeeder; } virtual uint64_t phyIOCount () const { return fPhysicalIO; } virtual uint64_t cacheIOCount () const { return fCacheIO; } @@ -255,6 +320,8 @@ class pColStep : public JobStep, public PrimitiveMsg uint64_t blksSkipped () const { return fNumBlksSkipped; } ResourceManager& resourceManager() const { return fRm; } + std::string udfName() const { return fUdfName; }; + void udfName(const std::string& name) { fUdfName = name; } SP_LBIDList getlbidList() const { return lbidList;} void addFilter(const execplan::Filter* f); @@ -282,10 +349,18 @@ class pColStep : public JobStep, public PrimitiveMsg uint64_t getFBO(uint64_t lbid); ResourceManager& fRm; + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + DistributedEngineComm* fDec; boost::shared_ptr sysCat; execplan::CalpontSystemCatalog::OID fOid; execplan::CalpontSystemCatalog::OID fTableOid; execplan::CalpontSystemCatalog::ColType fColType; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; uint32_t fFilterCount; int8_t fBOP; int8_t fOutputType; @@ -294,20 +369,20 @@ class pColStep : public JobStep, public PrimitiveMsg StrDataList* strRidList; messageqcpp::ByteStream fFilterString; std::vector extents; - uint32_t extentSize, divShift, modMask, ridsPerBlock, rpbShift, blockSizeShift, numExtents; - uint64_t rpbMask; + uint extentSize, divShift, modMask, ridsPerBlock, rpbShift, blockSizeShift, numExtents; + uint64_t rpbMask; uint64_t msgsSent, msgsRecvd; bool finishedSending, recvWaiting, fIsDict; bool isEM; int64_t ridCount; - uint32_t fFlushInterval; + uint fFlushInterval; - // @bug 663 - Added fSwallowRows for calpont.caltrace(16) which is TRACE_FLAGS::TRACE_NO_ROWS4. + // @bug 663 - Added fSwallowRows for calpont.caltrace(16) which is TRACE_FLAGS::TRACE_NO_ROWS4. // Running with this one will swallow rows at projection. - bool fSwallowRows; - uint32_t fProjectBlockReqLimit; // max number of rids to send in a scan + bool fSwallowRows; + u_int32_t fProjectBlockReqLimit; // max number of rids to send in a scan // request to primproc - uint32_t fProjectBlockReqThreshold; // min level of rids backlog before + u_int32_t fProjectBlockReqThreshold; // min level of rids backlog before // consumer will tell producer to send // more rids scan requests to primproc @@ -318,7 +393,7 @@ class pColStep : public JobStep, public PrimitiveMsg uint64_t fNumBlksSkipped;//total number of block scans skipped due to CP uint64_t fMsgBytesIn; // total byte count for incoming messages uint64_t fMsgBytesOut; // total byte count for outcoming messages - + BRM::DBRM dbrm; boost::shared_ptr cThread; //consumer thread @@ -326,9 +401,11 @@ class pColStep : public JobStep, public PrimitiveMsg boost::mutex mutex; boost::condition condvar; boost::condition flushed; + SPJL fLogger; SP_LBIDList lbidList; std::vector scanFlags; // use to keep track of which extents to eliminate from this step - uint32_t uniqueID; + uint32_t uniqueID; + std::string fUdfName; //@bug 2634 //@bug 3128 change ParseTree* to vector @@ -343,11 +420,11 @@ class pColStep : public JobStep, public PrimitiveMsg }; /** @brief the pColScan Step - * + * * The most common step which requires no input RID list, but may have value filters applied - * + * * The input association will always be null here so that we can go as soon as the Run function is called - * + * * The StartPrimitiveThread will spawn a new worker thread that will * a) take any input filters and apply them to a primitive message to be sent * b) walk the block resolution manager via an LBID list for the oid @@ -358,18 +435,29 @@ class pColScanStep : public JobStep, public PrimitiveMsg { public: /** @brief pColScanStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer */ - pColScanStep( + pColScanStep(const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + DistributedEngineComm* dec, + boost::shared_ptr syscat, execplan::CalpontSystemCatalog::OID oid, execplan::CalpontSystemCatalog::OID tableOid, const execplan::CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo); + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId, + ResourceManager& rm); pColScanStep(const pColStep& rhs); ~pColScanStep(); /** @brief Starts processing. - * + * * Starts processing. */ virtual void run(); @@ -380,10 +468,35 @@ class pColScanStep : public JobStep, public PrimitiveMsg */ virtual void join(); + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + virtual bool isDictCol() const { return fIsDict; }; - /** @brief The main loop for the send-side thread - * + /** @brief The main loop for the send-side thread + * * The main loop for the primitive-issuing thread. Don't call it directly. */ void sendPrimitiveMessages(); @@ -394,8 +507,8 @@ class pColScanStep : public JobStep, public PrimitiveMsg */ void receivePrimitiveMessages(uint64_t i = 0); - /** @brief Add a filter when the column is a 4-byte float type - * + /** @brief Add a filter when the column is a 4-byte float type + * * Add a filter when the column is a 4-byte float type */ void addFilter(int8_t COP, float value); @@ -416,7 +529,7 @@ class pColScanStep : public JobStep, public PrimitiveMsg int8_t BOP() const { return fBOP; } bool getFeederFlag() const { return isFilterFeeder; } - + void setFeederFlag (bool filterFeeder) { isFilterFeeder = filterFeeder; } /** @brief Get the string of the filter predicates * @@ -426,19 +539,44 @@ class pColScanStep : public JobStep, public PrimitiveMsg void setSingleThread(bool b); bool getSingleThread() { return fSingleThread; } - + /** @brief Set the output type. - * + * * Set the output type (1 = RID, 2 = Token, 3 = Both).pColScan */ void setOutputType(int8_t OutputType); +// DistributedEngineComm* dec() const { return fDec; } + uint32_t verId() const { return fVerId; } uint32_t filterCount() const { return fFilterCount; } + /** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ +// void dec(DistributedEngineComm* dec) { +// if (fDec) fDec->removeQueue(uniqueID); +// fDec = dec; +// if (fDec) fDec->addQueue(uniqueID); +// } + + /** @brief Set the step ID of this JobStep + * + * Set the step ID of this JobStep. XXXPAT: todo: Need to update the DEC as well + * I assume. + */ + virtual void stepId(uint16_t stepId) { fStepId = stepId; } + virtual uint16_t stepId() const { return fStepId; } + + virtual uint32_t sessionId() const { return fSessionId; } + virtual uint32_t txnId() const { return fTxnId; } + virtual uint32_t statementId() const { return fStatementId; } virtual const std::string toString() const; virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } virtual execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } + void logger(const SPJL& logger) { fLogger = logger; } + const SPJL& logger() const { return fLogger; } const execplan::CalpontSystemCatalog::ColType& colType() const { return fColType; } ResourceManager& resourceManager() const { return fRm; } @@ -447,7 +585,7 @@ class pColScanStep : public JobStep, public PrimitiveMsg virtual uint64_t msgsRcvdCount () const { return recvCount; } virtual uint64_t msgBytesIn () const { return fMsgBytesIn; } virtual uint64_t msgBytesOut () const { return fMsgBytesOut;} - uint32_t getRidsPerBlock() const {return ridsPerBlock;} + uint getRidsPerBlock() const {return ridsPerBlock;} //...Currently only supported by pColStep and pColScanStep, so didn't bother //...to define abstract method in base class, but if start adding to other @@ -479,27 +617,36 @@ class pColScanStep : public JobStep, public PrimitiveMsg void sendAPrimitiveMessage ( ISMPacketHeader& ism, BRM::LBID_t msgLbidStart, - uint32_t msgLbidCount); + u_int32_t msgLbidCount); uint64_t getFBO(uint64_t lbid); - bool isEmptyVal(const uint8_t *val8) const; + bool isEmptyVal(const u_int8_t *val8) const; ResourceManager& fRm; + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + DistributedEngineComm* fDec; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; ColByScanRangeRequestHeader fMsgHeader; SPTHD fConsumerThread; /// number of threads on the receive side - uint32_t fNumThreads; - + uint fNumThreads; + SPTHD * fProducerThread; messageqcpp::ByteStream fFilterString; - uint32_t fFilterCount; + uint fFilterCount; execplan::CalpontSystemCatalog::OID fOid; execplan::CalpontSystemCatalog::OID fTableOid; execplan::CalpontSystemCatalog::ColType fColType; int8_t fBOP; int8_t fOutputType; uint32_t sentCount; - uint32_t recvCount; + uint32_t recvCount; BRM::LBIDRange_v lbidRanges; + uint32_t hwm; BRM::DBRM dbrm; SP_LBIDList lbidList; @@ -509,15 +656,17 @@ class pColScanStep : public JobStep, public PrimitiveMsg boost::condition condvar; boost::condition condvarWakeupProducer; bool finishedSending, sendWaiting, rDoNothing, fIsDict; - uint32_t recvWaiting, recvExited; + uint recvWaiting, recvExited; + uint64_t ridsReturned; std::vector extents; - uint32_t extentSize, divShift, ridsPerBlock, rpbShift, numExtents; + uint extentSize, divShift, ridsPerBlock, rpbShift, numExtents; + SPJL fLogger; // config::Config *fConfig; - uint32_t fScanLbidReqLimit; // max number of LBIDs to send in a scan + u_int32_t fScanLbidReqLimit; // max number of LBIDs to send in a scan // request to primproc - uint32_t fScanLbidReqThreshold; // min level of scan LBID backlog before + u_int32_t fScanLbidReqThreshold; // min level of scan LBID backlog before // consumer will tell producer to send // more LBID scan requests to primproc @@ -578,13 +727,25 @@ class pDictionaryStep : public JobStep, public PrimitiveMsg public: /** @brief pDictionaryStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer */ - - pDictionaryStep( + + pDictionaryStep(const JobStepAssociation& in, + const JobStepAssociation& out, + DistributedEngineComm* ec, + boost::shared_ptr sysCat, execplan::CalpontSystemCatalog::OID oid, + int ct, execplan::CalpontSystemCatalog::OID tabelOid, - const execplan::CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo); + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId, + ResourceManager& rm, + uint32_t interval=0); virtual ~pDictionaryStep(); @@ -598,13 +759,58 @@ class pDictionaryStep : public JobStep, public PrimitiveMsg void sendPrimitiveMessages(); void receivePrimitiveMessages(); + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + virtual const std::string toString() const; + void stepId(uint16_t stepId) { fStepId = stepId; } + uint16_t stepId() const { return fStepId; } + + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t statementId() const { return fStatementId; } +// DistributedEngineComm* dec() const { return fDec; } + uint32_t verId() const { return fVerId; } execplan::CalpontSystemCatalog::ColType& colType() { return fColType; } execplan::CalpontSystemCatalog::ColType colType() const { return fColType; } +/** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ +// void dec(DistributedEngineComm* dec) { +// if (fDec) fDec->removeQueue(uniqueID); +// fDec = dec; +// if (fDec) fDec->addQueue(uniqueID); +// } + virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } + virtual execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } + void logger(const SPJL& logger) { fLogger = logger; } + const SPJL& logger() const { return fLogger; } virtual uint64_t phyIOCount () const { return fPhysicalIO; } virtual uint64_t cacheIOCount () const { return fCacheIO; } virtual uint64_t msgsRcvdCount () const { return msgsRecvd; } @@ -626,9 +832,17 @@ class pDictionaryStep : public JobStep, public PrimitiveMsg void startPrimitiveThread(); void startAggregationThread(); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + DistributedEngineComm* fDec; boost::shared_ptr sysCat; execplan::CalpontSystemCatalog::OID fOid; execplan::CalpontSystemCatalog::OID fTableOid; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint32_t fStepId; + uint32_t fStatementId; uint32_t fBOP; uint32_t msgsSent; uint32_t msgsRecvd; @@ -640,13 +854,14 @@ class pDictionaryStep : public JobStep, public PrimitiveMsg boost::shared_ptr cThread; //producer thread messageqcpp::ByteStream fFilterString; - uint32_t fFilterCount; + uint fFilterCount; DataList_t* requestList; //StringDataList* stringList; boost::mutex mutex; boost::condition condvar; uint32_t fInterval; + SPJL fLogger; uint64_t fPhysicalIO; // total physical I/O count uint64_t fCacheIO; // total cache I/O count uint64_t fMsgBytesIn; // total byte count for incoming messages @@ -656,7 +871,7 @@ class pDictionaryStep : public JobStep, public PrimitiveMsg //@bug 3128 change ParseTree* to vector std::vector fFilters; - + bool hasEqualityFilter; int8_t tmpCOP; std::vector eqFilter; @@ -673,16 +888,31 @@ class pDictionaryStep : public JobStep, public PrimitiveMsg */ class pDictionaryScan : public JobStep, public PrimitiveMsg { + +//typedef StringElementType DictionaryStepElement_t; +//typedef StringDataList DictionaryDataList; + public: /** @brief pDictionaryScan constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer */ - - pDictionaryScan( + + pDictionaryScan(const JobStepAssociation& in, + const JobStepAssociation& out, + DistributedEngineComm* ec, + boost::shared_ptr syscat, execplan::CalpontSystemCatalog::OID oid, + int ct, execplan::CalpontSystemCatalog::OID tableOid, - const execplan::CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo); + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t step, + uint32_t statementId, + ResourceManager& rm); ~pDictionaryScan(); @@ -690,33 +920,68 @@ class pDictionaryScan : public JobStep, public PrimitiveMsg */ virtual void run(); virtual void join(); + //void setOutList(StringDataList* rids); void setInputList(DataList_t* rids); void setBOP(int8_t b); void sendPrimitiveMessages(); void receivePrimitiveMessages(); void setSingleThread(); + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + virtual const std::string toString() const; + virtual void stepId(uint16_t step) { fStepId = step; } + + virtual uint16_t stepId() const { return fStepId; } + + virtual uint32_t sessionId() const { return fSessionId; } + virtual uint32_t txnId() const { return fTxnId; } + virtual uint32_t statementId() const { return fStatementId; } + void setRidList(DataList *rids); /** @brief Add a filter. Use this interface when the column stores anything but 4-byte floats. - * + * * Add a filter. Use this interface when the column stores anything but 4-byte floats. */ void addFilter(int8_t COP, const std::string& value); // all but FLOATS can use this interface - /** @brief Set the DistributedEngineComm object this instance should use - * - * Set the DistributedEngineComm object this instance should use - */ +/** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ void dec(DistributedEngineComm* dec) { if (fDec) fDec->removeQueue(uniqueID); - fDec = dec; - if (fDec) fDec->addQueue(uniqueID); + fDec = dec; + if (fDec) fDec->addQueue(uniqueID); } virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } + virtual execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } + void logger(const SPJL& logger) { fLogger = logger; } uint64_t phyIOCount () const { return fPhysicalIO; } uint64_t cacheIOCount () const { return fCacheIO; } @@ -754,10 +1019,18 @@ class pDictionaryScan : public JobStep, public PrimitiveMsg uint32_t msgLbidCount, uint16_t dbroot); void formatMiniStats(); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; DistributedEngineComm* fDec; boost::shared_ptr sysCat; execplan::CalpontSystemCatalog::OID fOid; execplan::CalpontSystemCatalog::OID fTableOid; + BRM::HWM_t fDictBlkCount; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint32_t fStepId; + uint32_t fStatementId; uint32_t fFilterCount; uint32_t fBOP; uint32_t fCOP1; @@ -768,7 +1041,7 @@ class pDictionaryScan : public JobStep, public PrimitiveMsg uint32_t recvWaiting; uint32_t sendWaiting; int64_t ridCount; - uint32_t fLogicalBlocksPerScan; + u_int32_t fLogicalBlocksPerScan; DataList *ridList; messageqcpp::ByteStream fFilterString; execplan::CalpontSystemCatalog::ColType colType; @@ -784,9 +1057,10 @@ class pDictionaryScan : public JobStep, public PrimitiveMsg uint64_t extentSize; uint64_t divShift; uint64_t numExtents; - uint32_t fScanLbidReqLimit; // max number of LBIDs to send in a scan + SPJL fLogger; + u_int32_t fScanLbidReqLimit; // max number of LBIDs to send in a scan // request to primproc - uint32_t fScanLbidReqThreshold; // min level of scan LBID backlog before + u_int32_t fScanLbidReqThreshold; // min level of scan LBID backlog before // consumer will tell producer to send bool fStopSending; bool fSingleThread; @@ -795,7 +1069,6 @@ class pDictionaryScan : public JobStep, public PrimitiveMsg uint64_t fMsgBytesIn; // total byte count for incoming messages uint64_t fMsgBytesOut; // total byte count for outcoming messages uint32_t fMsgsToPm; // total number of messages sent to PMs - uint32_t fMsgsExpect; // total blocks to scan uint32_t uniqueID; ResourceManager& fRm; BPSOutputType fOutType; @@ -812,19 +1085,17 @@ class pDictionaryScan : public JobStep, public PrimitiveMsg void destroyEqualityFilter(); }; - class BatchPrimitive : public JobStep, public PrimitiveMsg, public DECEventListener { public: - BatchPrimitive(const JobInfo& jobInfo) : JobStep(jobInfo) {} virtual bool getFeederFlag() const = 0; - virtual uint64_t getLastTupleId() const = 0; - virtual uint32_t getStepCount () const = 0; + virtual execplan::CalpontSystemCatalog::OID getLastOid() const = 0; + virtual uint getStepCount () const = 0; virtual void setBPP(JobStep* jobStep) = 0; virtual void setFirstStepType(PrimitiveStepType firstStepType) = 0; virtual void setIsProjectionOnly() = 0; - virtual void setLastTupleId(uint64_t) = 0; + virtual void setLastOid(execplan::CalpontSystemCatalog::OID colOid) = 0; virtual void setOutputType(BPSOutputType outputType) = 0; virtual void setProjectBPP(JobStep* jobStep1, JobStep* jobStep2) = 0; virtual void setStepCount() = 0; @@ -840,11 +1111,12 @@ class BatchPrimitive : public JobStep, public PrimitiveMsg, public DECEventListe virtual void setJobInfo(const JobInfo* jobInfo) = 0; virtual void setOutputRowGroup(const rowgroup::RowGroup& rg) = 0; virtual const rowgroup::RowGroup& getOutputRowGroup() const = 0; - virtual void addFcnJoinExp(const std::vector& fe) = 0; virtual void addFcnExpGroup1(const boost::shared_ptr& fe) = 0; virtual void setFE1Input(const rowgroup::RowGroup& feInput) = 0; virtual void setFcnExpGroup3(const std::vector& fe) = 0; virtual void setFE23Output(const rowgroup::RowGroup& rg) = 0; + + }; @@ -854,15 +1126,15 @@ class BatchPrimitive : public JobStep, public PrimitiveMsg, public DECEventListe class TupleBPS : public BatchPrimitive, public TupleDeliveryStep { public: - TupleBPS(const pColStep& rhs, const JobInfo& jobInfo); - TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo); - TupleBPS(const pDictionaryStep& rhs, const JobInfo& jobInfo); - TupleBPS(const pDictionaryScan& rhs, const JobInfo& jobInfo); - TupleBPS(const PassThruStep& rhs, const JobInfo& jobInfo); + TupleBPS(const pColStep& rhs); + TupleBPS(const pColScanStep& rhs); + TupleBPS(const pDictionaryStep& rhs); + TupleBPS(const pDictionaryScan& rhs); + TupleBPS(const PassThruStep& rhs); virtual ~TupleBPS(); /** @brief Starts processing. - * + * * Starts processing. */ virtual void run(); @@ -872,11 +1144,36 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep */ virtual void join(); - void abort(); + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + virtual void abort(); void abort_nolock(); - /** @brief The main loop for the send-side thread - * + /** @brief The main loop for the send-side thread + * * The main loop for the primitive-issuing thread. Don't call it directly. */ void sendPrimitiveMessages(); @@ -885,7 +1182,7 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep * * The main loop for the receive-side thread. Don't call it directly. */ - void receiveMultiPrimitiveMessages(uint32_t threadID); + void receiveMultiPrimitiveMessages(uint threadID); /** @brief Add a filter when the column is anything but a 4-byte float type. * @@ -900,6 +1197,7 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep void setFeederFlag (bool filterFeeder) { isFilterFeeder = filterFeeder; } void setSwallowRows(const bool swallowRows) {fSwallowRows = swallowRows; } bool getSwallowRows() const { return fSwallowRows; } + void setIsDelivery(bool b) { isDelivery = b; } /* Base class interface fcn that can go away */ void setOutputType(BPSOutputType) { } //Can't change the ot of a TupleBPS @@ -907,26 +1205,39 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep void setBppStep() { } void setIsProjectionOnly() { } - uint64_t getRows() const { return ridsReturned; } + uint64_t getRows() const { return rowsReturned; } void setFirstStepType(PrimitiveStepType firstStepType) { ffirstStepType = firstStepType;} PrimitiveStepType getPrimitiveStepType () { return ffirstStepType; } void setStepCount() { fStepCount++; } - uint32_t getStepCount () const { return fStepCount; } - void setLastTupleId(uint64_t id) { fLastTupleId = id; } - uint64_t getLastTupleId() const { return fLastTupleId; } + uint getStepCount () const { return fStepCount; } + void setLastOid(execplan::CalpontSystemCatalog::OID colOid) { fLastOid = colOid; } + execplan::CalpontSystemCatalog::OID getLastOid() const { return fLastOid; } - /** @brief Set the DistributedEngineComm object this instance should use - * - * Set the DistributedEngineComm object this instance should use - */ +/** @brief Set the DistributedEngineComm object this instance should use + * + * Set the DistributedEngineComm object this instance should use + */ void dec(DistributedEngineComm* dec); +/** @brief Set the step ID of this JobStep + * + * Set the step ID of this JobStep. XXXPAT: todo: Need to update the DEC as well + * I assume. + */ virtual void stepId(uint16_t stepId); virtual uint16_t stepId() const { return fStepId; } + + virtual uint32_t sessionId() const { return fSessionId; } + virtual uint32_t txnId() const { return fTxnId; } + virtual uint32_t statementId() const { return fStatementId; } + virtual const std::string toString() const; virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } + virtual execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } + void logger(const SPJL& logger) { fLogger = logger; } + const SPJL& logger() const { return fLogger; } const execplan::CalpontSystemCatalog::ColType& colType() const { return fColType; } const OIDVector& getProjectOids() const { return projectOids; } virtual uint64_t phyIOCount () const { return fPhysicalIO; } @@ -935,7 +1246,7 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep virtual uint64_t msgBytesIn () const { return fMsgBytesIn; } virtual uint64_t msgBytesOut () const { return fMsgBytesOut;} virtual uint64_t blockTouched () const { return fBlockTouched;} - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); //...Currently only supported by pColStep and pColScanStep, so didn't bother //...to define abstract method in base class, but if start adding to other @@ -949,7 +1260,7 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep bool wasStepRun() const { return fRunExecuted; } // DEC event listener interface - void newPMOnline(uint32_t connectionNumber); + void newPMOnline(uint connectionNumber); void setInputRowGroup(const rowgroup::RowGroup &rg); void setOutputRowGroup(const rowgroup::RowGroup &rg); @@ -966,8 +1277,8 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep void setJobInfo(const JobInfo* jobInfo); - // @bug 2123. Added getEstimatedRowCount function. - /* @brief estimates the number of rows that will be returned for use in determining the + // @bug 2123. Added getEstimatedRowCount function. + /* @brief estimates the number of rows that will be returned for use in determining the * large side table for hashjoins. */ uint64_t getEstimatedRowCount(); @@ -987,7 +1298,6 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep JLF should register that object with the TBPS for that table. If it's cross-table, then JLF should register it with the join step. */ - void addFcnJoinExp(const std::vector& fe); void addFcnExpGroup1(const boost::shared_ptr& fe); void setFE1Input(const rowgroup::RowGroup& feInput); @@ -1004,20 +1314,18 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep // rowgroup to connector const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; /* Interface for adding add'l predicates for casual partitioning. * This fcn checks for any intersection between the values in vals * and the range of a given extent. If there is no intersection, that extent * won't be processed. For every extent in OID, it effectively calculates - * ((vals[0] >= min && vals[0] <= max) || (vals[1] >= min && vals[1] <= max)) ... + * ((vals[0] >= min && vals[0] <= max) || (vals[1] >= min && vals[1] <= max)) ... * && (previous calculation for that extent). * Note that it is an adder not a setter. For an extent to be scanned, all calls * must have a non-empty intersection. */ void addCPPredicates(uint32_t OID, const std::vector &vals, bool isRange); - + /* semijoin adds */ void setJoinFERG(const rowgroup::RowGroup &rg); @@ -1027,8 +1335,6 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep void reloadExtentLists(); void initExtentMarkers(); // need a better name for this - virtual bool stringTableFriendly() { return true; } - protected: void sendError(uint16_t status); void processError(const std::string& ex, uint16_t err, const std::string& src); @@ -1039,72 +1345,81 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep typedef boost::shared_ptr SPTHD; typedef boost::shared_array SATHD; void startPrimitiveThread(); - void startAggregationThread(); + void startAggregationThreads(); void initializeConfigParms(); uint64_t getFBO(uint64_t lbid); void checkDupOutputColumns(const rowgroup::RowGroup &rg); void dupOutputColumns(rowgroup::RowGroup&); - void dupOutputColumns(rowgroup::RGData&, rowgroup::RowGroup&); - void rgDataToDl(rowgroup::RGData &, rowgroup::RowGroup&, RowGroupDL*); - void rgDataVecToDl(std::vector&,rowgroup::RowGroup&,RowGroupDL*); + void dupOutputColumns(boost::shared_array&, rowgroup::RowGroup&); + void rgDataToDl(boost::shared_array&, rowgroup::RowGroup&, RowGroupDL*); + void rgDataVecToDl(std::vector >&, rowgroup::RowGroup&, RowGroupDL*); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; DistributedEngineComm* fDec; boost::shared_ptr fBPP; + uint rowCount; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; uint16_t fNumSteps; int fColWidth; - uint32_t fStepCount; + uint fStepCount; bool fCPEvaluated; // @bug 2123 uint64_t fEstimatedRows; // @bug 2123 /// number of threads on the receive side - uint32_t fMaxNumThreads; - uint32_t fNumThreads; + uint fNumThreads; PrimitiveStepType ffirstStepType; bool isFilterFeeder; SATHD fProducerThread; messageqcpp::ByteStream fFilterString; - uint32_t fFilterCount; + uint fFilterCount; execplan::CalpontSystemCatalog::ColType fColType; execplan::CalpontSystemCatalog::OID fOid; execplan::CalpontSystemCatalog::OID fTableOid; - uint64_t fLastTupleId; + execplan::CalpontSystemCatalog::OID fLastOid; BRM::LBIDRange_v lbidRanges; + boost::scoped_array hwm; std::vector lastExtent; std::vector lastScannedLBID; BRM::DBRM dbrm; SP_LBIDList lbidList; uint64_t ridsRequested; - uint64_t totalMsgs; - volatile uint64_t msgsSent; - volatile uint64_t msgsRecvd; + volatile uint64_t msgsSent, msgsRecvd; volatile bool finishedSending; - bool firstRead; - bool sendWaiting; + bool firstRead, sendWaiting; uint32_t recvWaiting; - uint32_t recvExited; + uint recvExited; uint64_t ridsReturned; + uint64_t rowsReturned; std::map > extentsMap; std::vector scannedExtents; OIDVector projectOids; - uint32_t extentSize, divShift, rpbShift, numExtents, modMask; - uint32_t fRequestSize; // the number of logical extents per batch of requests sent to PrimProc. - uint32_t fProcessorThreadsPerScan; // The number of messages sent per logical extent. - bool fSwallowRows; - uint32_t fMaxOutstandingRequests; // The number of logical extents have not processed by PrimProc + uint extentSize, divShift, rpbShift, numExtents, modMask; + SPJL fLogger; +// config::Config *fConfig; + u_int32_t fRequestSize; // the number of logical extents per batch of requests sent to PrimProc. + u_int32_t fProcessorThreadsPerScan; // The number of messages sent per logical extent. + bool fSwallowRows; + u_int32_t fMaxOutstandingRequests; // The number of logical extents have not processed by PrimProc uint64_t fPhysicalIO; // total physical I/O count uint64_t fCacheIO; // total cache I/O count uint64_t fNumBlksSkipped;//total number of block scans skipped due to CP uint64_t fMsgBytesIn; // total byte count for incoming messages uint64_t fMsgBytesOut; // total byte count for outcoming messages uint64_t fBlockTouched; // total blocks touched - uint32_t fExtentsPerSegFile;//config num of Extents Per Segment File + uint32_t fMsgBppsToPm; // total number of BPP messages sent to PMs + uint32_t fExtentRows; // config value of ExtentMap/ExtentRows boost::shared_ptr cThread; //consumer thread boost::shared_ptr pThread; //producer thread boost::mutex mutex; boost::mutex dlMutex; boost::mutex cpMutex; - boost::mutex serializeJoinerMutex; boost::condition condvarWakeupProducer, condvar; - + bool isDelivery; + std::vector scanFlags; // use to keep track of which extents to eliminate from this step bool BPPIsAllocated; uint32_t uniqueID; @@ -1113,19 +1428,19 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep /* HashJoin support */ void serializeJoiner(); - void serializeJoiner(uint32_t connectionNumber); + void serializeJoiner(uint connectionNumber); - void generateJoinResultSet(const std::vector > &joinerOutput, + void generateJoinResultSet(const std::vector > &joinerOutput, rowgroup::Row &baseRow, const std::vector > &mappings, - const uint32_t depth, rowgroup::RowGroup &outputRG, rowgroup::RGData &rgData, - std::vector *outputData, + const uint depth, rowgroup::RowGroup &outputRG, boost::shared_array &rgData, + std::vector > *outputData, const boost::scoped_array &smallRows, rowgroup::Row &joinedRow); std::vector > tjoiners; bool doJoin, hasPMJoin, hasUMJoin; std::vector joinerMatchesRGs; // parses the small-side matches from joiner - uint32_t smallSideCount; + uint smallSideCount; int smallOuterJoiner; bool fRunExecuted; // was the run method executed for this step @@ -1142,11 +1457,10 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep // temporary hack to make sure JobList only calls run and join once boost::mutex jlLock; - bool runRan; - bool joinRan; + bool runRan, joinRan; // bug 1965, trace duplicat columns in delivery list - std::vector > dupColumns; + std::vector > dupColumns; /* Functions & Expressions vars */ boost::shared_ptr fe1, fe2; @@ -1155,37 +1469,34 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep bool runFEonPM; /* for UM F & E 2 processing */ - rowgroup::RGData fe2Data; + boost::scoped_array fe2Data; rowgroup::Row fe2InRow, fe2OutRow; - + void processFE2(rowgroup::RowGroup &input, rowgroup::RowGroup &output, rowgroup::Row &inRow, rowgroup::Row &outRow, - std::vector *rgData, + std::vector > *rgData, funcexp::FuncExpWrapper* localFE2); void processFE2_oneRG(rowgroup::RowGroup &input, rowgroup::RowGroup &output, rowgroup::Row &inRow, rowgroup::Row &outRow, funcexp::FuncExpWrapper* localFE2); - + /* Runtime Casual Partitioning adjustments. The CP code is needlessly complicated; * to avoid making it worse, decided to designate 'scanFlags' as the static * component and this new array as the runtime component. The final CP decision * is scanFlags & runtimeCP. */ std::vector runtimeCPFlags; - + /* semijoin vars */ rowgroup::RowGroup joinFERG; - boost::shared_ptr deliveryDL; - uint32_t deliveryIt; - /* shared nothing support */ struct Job { - Job(uint32_t d, uint32_t n, uint32_t b, boost::shared_ptr &bs) : + Job(uint d, uint n, uint b, boost::shared_ptr &bs) : dbroot(d), connectionNum(n), expectedResponses(b), msg(bs) { } - uint32_t dbroot; - uint32_t connectionNum; - uint32_t expectedResponses; + uint dbroot; + uint connectionNum; + uint expectedResponses; boost::shared_ptr msg; }; @@ -1193,20 +1504,7 @@ class TupleBPS : public BatchPrimitive, public TupleDeliveryStep void makeJobs(std::vector *jobs); void interleaveJobs(std::vector *jobs) const; void sendJobs(const std::vector &jobs); - uint32_t numDBRoots; - - /* Pseudo column filter processing. Think about refactoring into a separate class. */ - bool processPseudoColFilters(uint32_t extentIndex, boost::shared_ptr > dbRootPMMap) const; - bool processOneFilterType(int8_t colWidth, int64_t value, uint32_t type) const; - bool processSingleFilterString(int8_t BOP, int8_t colWidth, int64_t val, const uint8_t *filterString, - uint32_t filterCount) const; - bool processSingleFilterString_ranged(int8_t BOP, int8_t colWidth, int64_t min, int64_t max, - const uint8_t *filterString, uint32_t filterCount) const; - bool processLBIDFilter(const BRM::EMEntry &emEntry) const; - bool compareSingleValue(uint8_t COP, int64_t val1, int64_t val2) const; - bool compareRange(uint8_t COP, int64_t min, int64_t max, int64_t val) const; - bool hasPCFilter, hasPMFilter, hasRIDFilter, hasSegmentFilter, hasDBRootFilter, hasSegmentDirFilter, - hasPartitionFilter, hasMaxFilter, hasMinFilter, hasLBIDFilter, hasExtentIDFilter; + uint numDBRoots; }; @@ -1217,7 +1515,10 @@ class FilterStep : public JobStep { public: - FilterStep(const execplan::CalpontSystemCatalog::ColType& colType, const JobInfo& jobInfo); + FilterStep(uint32_t sessionId, + uint32_t txnId, + uint32_t statementId, + execplan::CalpontSystemCatalog::ColType colType); ~FilterStep(); /** @brief virtual void Run method @@ -1225,14 +1526,47 @@ class FilterStep : public JobStep void run(); void join(); + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + void stepId(uint16_t stepId) { fStepId = stepId; } + virtual uint16_t stepId() const { return fStepId; } + + virtual uint32_t sessionId() const { return fSessionId; } + virtual uint32_t txnId() const { return fTxnId; } + virtual uint32_t statementId() const { return fStatementId; } + const std::string toString() const; execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOID; } void tableOid(execplan::CalpontSystemCatalog::OID tableOid) { fTableOID = tableOid; } const execplan::CalpontSystemCatalog::ColType& colType() const { return fColType; } + void logger(const SPJL& logger) { fLogger = logger; } void setBOP(int8_t b); int8_t BOP() const { return fBOP; } - friend struct FSRunner; + friend struct FSRunner; void addFilter(const execplan::Filter* f); std::vector& getFilters() { return fFilters; } @@ -1248,8 +1582,15 @@ class FilterStep : public JobStep // config::Config *fConfig; + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint16_t fStepId; + uint32_t fStatementId; execplan::CalpontSystemCatalog::OID fTableOID; execplan::CalpontSystemCatalog::ColType fColType; + SPJL fLogger; int8_t fBOP; boost::shared_ptr runner; // @bug 686 @@ -1269,24 +1610,35 @@ class FilterStep : public JobStep class PassThruStep : public JobStep, public PrimitiveMsg { - typedef std::pair element_t; + typedef std::pair element_t; public: /** @brief PassThruStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer + * @param ec the DistributedEngineComm pointer + * wait for the receiveing side to catch up. 0 (default) means never. */ - PassThruStep( + PassThruStep(const JobStepAssociation& in, + const JobStepAssociation& out, + DistributedEngineComm* dec, + execplan::CalpontSystemCatalog::ColType colType, execplan::CalpontSystemCatalog::OID oid, execplan::CalpontSystemCatalog::OID tableOid, - const execplan::CalpontSystemCatalog::ColType& colType, - const JobInfo& jobInfo); + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint16_t stepId, + uint32_t statementId, + bool isEM, + ResourceManager& rm); - PassThruStep(const pColStep& rhs); - PassThruStep(const PseudoColStep& rhs); + PassThruStep(const pColStep& rhs, bool isEM); virtual ~PassThruStep(); /** @brief Starts processing. Set at least the RID list before calling. - * + * * Starts processing. Set at least the RID list before calling this. */ virtual void run(); @@ -1297,21 +1649,61 @@ class PassThruStep : public JobStep, public PrimitiveMsg */ virtual void join(); - virtual const std::string toString() const; + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + virtual const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + + virtual void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + virtual const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + virtual void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + virtual const std::string toString() const; + + /** @brief Set the step ID for this JobStep. + * + * Set the step ID for this JobStep. + */ + virtual void stepId(uint16_t stepId) { fStepId = stepId; } + virtual execplan::CalpontSystemCatalog::OID oid() const { return fOid; } virtual execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOid; } - + + DistributedEngineComm* dec() const { return fDec; } + void dec(DistributedEngineComm* dec) { fDec = dec; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t verId() const { return fVerId; } + uint16_t stepId() const { return fStepId; } + uint32_t statementId() const { return fStatementId; } + void logger(const SPJL& logger) { fLogger = logger; } + const SPJL& logger() const { return fLogger; } uint8_t getColWidth() const { return colWidth; } bool isDictCol() const { return isDictColumn; } bool isExeMgr() const { return isEM; } const execplan::CalpontSystemCatalog::ColType& colType() const { return fColType; } ResourceManager& resourceManager() const { return fRm; } - void pseudoType(uint32_t p) { fPseudoType = p; } - uint32_t pseudoType() const { return fPseudoType; } - protected: private: @@ -1323,21 +1715,29 @@ class PassThruStep : public JobStep, public PrimitiveMsg uint64_t getLBID(uint64_t rid, bool& scan); uint64_t getFBO(uint64_t lbid); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; boost::shared_ptr catalog; + DistributedEngineComm *fDec; execplan::CalpontSystemCatalog::OID fOid; execplan::CalpontSystemCatalog::OID fTableOid; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; uint8_t colWidth; uint16_t realWidth; - uint32_t fPseudoType; - execplan::CalpontSystemCatalog::ColType fColType; + execplan::CalpontSystemCatalog::ColType fColType; bool isDictColumn; bool isEM; boost::thread* fPTThd; - // @bug 663 - Added fSwallowRows for calpont.caltrace(16) which is TRACE_FLAGS::TRACE_NO_ROWS4. + // @bug 663 - Added fSwallowRows for calpont.caltrace(16) which is TRACE_FLAGS::TRACE_NO_ROWS4. // Running with this one will swallow rows at projection. bool fSwallowRows; + SPJL fLogger; ResourceManager& fRm; friend class PassThruCommandJL; friend class RTSCommandJL; @@ -1345,41 +1745,6 @@ class PassThruStep : public JobStep, public PrimitiveMsg friend class TupleBPS; }; -class PseudoColStep : public pColStep -{ -public: - /** @brief PseudoColStep constructor - */ - PseudoColStep( - execplan::CalpontSystemCatalog::OID oid, - execplan::CalpontSystemCatalog::OID tableOid, - uint32_t pId, - const execplan::CalpontSystemCatalog::ColType& ct, - const JobInfo& jobInfo) : - pColStep(oid, tableOid, ct, jobInfo), - fPseudoColumnId(pId) - {} - - PseudoColStep(const PassThruStep& rhs) : - pColStep(rhs), - fPseudoColumnId(rhs.pseudoType()) - {} - - virtual ~PseudoColStep() {} - - uint32_t pseudoColumnId() const { return fPseudoColumnId; } - void pseudoColumnId(uint32_t pId) { fPseudoColumnId = pId; } - -protected: - uint32_t fPseudoColumnId; - -private: - /** @brief disabled constuctor - */ - PseudoColStep(const pColScanStep&); - PseudoColStep(const pColStep&); -}; - } diff --git a/dbcon/joblist/profiling.cpp b/dbcon/joblist/profiling.cpp new file mode 100644 index 00000000..2f64c395 --- /dev/null +++ b/dbcon/joblist/profiling.cpp @@ -0,0 +1,233 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: profiling.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ + +#include +#include +#include +using namespace std; + +#include "profiling.h" + +namespace joblist +{ +const timespec timespec_ini() +{ + timespec t; + t.tv_sec = t.tv_nsec = 0L; + return t; +} +const timespec TimespecIni_c = timespec_ini(); + +const timespec timespec_max() +{ + timespec t; + t.tv_sec = t.tv_nsec = numeric_limits::max(); + return t; +} +const timespec TimespecMax_c = timespec_max(); + +const timespec timespec_min() +{ + timespec t; + t.tv_sec = t.tv_nsec = numeric_limits::min(); + return t; +} +const timespec TimespecMin_c = timespec_min(); + +int64_t timespec_compare(const timespec &tv1, const timespec &tv2) +{ + if (tv1.tv_sec > tv2.tv_sec) + return 1; + if (tv1.tv_sec < tv2.tv_sec) + return -1; + + return (tv1.tv_nsec - tv2.tv_nsec); +} + +timespec timespec_add(const timespec &tv1, const timespec &tv2) +{ + timespec ts; + ts.tv_sec = tv1.tv_sec + tv2.tv_sec; + ts.tv_nsec = tv1.tv_nsec + tv2.tv_nsec; + if (ts.tv_nsec >= 1000000000) + { + ts.tv_sec += 1; + ts.tv_nsec -= 1000000000; + } + return ts; +} + +timespec timespec_sub(const struct timespec &tv1, const struct timespec &tv2) +{ + timespec ts; + if (tv2.tv_nsec < tv1.tv_nsec) + { + ts.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; + ts.tv_nsec = tv2.tv_nsec + 1000000000 - tv1.tv_nsec; + } + else + { + ts.tv_sec = tv2.tv_sec - tv1.tv_sec; + ts.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; + } + return ts; +} + +static string ind_s[] = {" "}; + +ProfilePoint::ProfilePoint(const string& pp) : + fIntBegin(TimespecIni_c), + fTtl(TimespecIni_c), + fMax(TimespecMin_c), + fMin(TimespecMax_c), + fCount(0), + fPercent(0), + fCheckpoint(pp) +{} + +void ProfilePoint::stop() +{ + timespec t; +#ifdef _MSC_VER + t.tv_nsec = t.tv_sec = 0; +#else + clock_gettime(CLOCK_REALTIME, &t); +#endif + timespec interval = timespec_sub(fIntBegin, t); + if (timespec_compare(interval, fMax) > 0) fMax = interval; + if (timespec_compare(interval, fMin) < 0) fMin = interval; + fTtl = timespec_add(fTtl, interval); + ++fCount; +} + +timespec ProfilePoint::average() const +{ + timespec t; + double avg = (((double) fTtl.tv_sec) * 1000000000 + fTtl.tv_nsec) / (double) fCount; + t.tv_sec = (long) (avg / 1000000000); + t.tv_nsec = (long) (avg - (double) t.tv_sec * 1000000000); + + return t; +} + +ostream& operator<<(ostream& os, const timespec& t) +{ + os << t.tv_sec << "." << setw(9) << setfill('0') << t.tv_nsec << "s"; + return os; +} + +ostream& operator<<(ostream& os, const ProfilePoint& p) +{ + if (p.fCount > 0) + os << " " << setw(6) << setfill(' ') << fixed << setprecision(2) + << p.fPercent << "% time spent at " + << p.fCheckpoint << ":\n total=" << p.fTtl << ", max=" << p.fMax + << ", avg=" << p.average() << ", min=" << p.fMin << ", #=" << p.fCount << endl; + return os; +} + +ProfileGroup::ProfileGroup() +{} + +void ProfileGroup::initialize(uint64_t pointCount, const string* pointName) +{ + for (uint64_t i = 0; i < pointCount; i++) + { + ProfilePoint pp(pointName[i]); + fPoints.push_back(pp); + } +} + +ostream& operator<<(ostream& os, ProfileGroup& group) +{ + vector::iterator i = group.fPoints.begin(), end = group.fPoints.end(); + timespec ts = (i++)->ttl(); + + // fPoints[0] has the overall timing of this group, use that to calculate percentage + double totalNsec = (double) ts.tv_sec*1000000000 + (double) ts.tv_nsec; + os << " ==> thread " << group.fPoints[0].fCheckpoint << " uses " << ts << endl; + + if (ts.tv_sec == 0 && ts.tv_nsec == 0) + return os; + + while (i != end) + { + i->fPercent = ((double) i->fTtl.tv_sec*1000000000 + (double) i->fTtl.tv_nsec) / totalNsec; + i->fPercent *= 100; + + os << *i++; + } + + return os; +} + +ProfileData::ProfileData() : fName(), fTs1(TimespecIni_c), fTs2(TimespecIni_c) +{} + +void ProfileData::initialize(const string& dataName) +{ + fName = dataName; +#ifdef _MSC_VER + fTs1.tv_nsec = fTs1.tv_sec = 0; +#else + clock_gettime(CLOCK_REALTIME, &fTs1); +#endif +} + +void ProfileData::restart() +{ +#ifdef _MSC_VER + fTs1.tv_nsec = fTs1.tv_sec = 0; +#else + clock_gettime(CLOCK_REALTIME, &fTs1); +#endif +} + +void ProfileData::start(uint64_t group, uint64_t point) +{ + fPrfGroup[group].fPoints[point].start(); +} + +void ProfileData::stop(uint64_t group, uint64_t point) +{ + fPrfGroup[group].fPoints[point].stop(); +} + + +ostream& operator<<(ostream& os, ProfileData& data) +{ +#ifdef _MSC_VER + data.fTs2.tv_nsec = data.fTs2.tv_sec = 0; +#else + clock_gettime(CLOCK_REALTIME, &(data.fTs2)); +#endif + if (data.fName.length() > 0) os << data.fName << " spent: "; + os << timespec_sub(data.fTs1, data.fTs2) << endl; + vector::iterator i = data.fPrfGroup.begin(), end = data.fPrfGroup.end(); + while (i != end) + os << *i++; + + return os; +} + +} diff --git a/dbcon/joblist/profiling.h b/dbcon/joblist/profiling.h new file mode 100644 index 00000000..4543c8de --- /dev/null +++ b/dbcon/joblist/profiling.h @@ -0,0 +1,134 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: profiling.h 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ +/** @file */ + +#ifndef JOBLIST_PROFILING_H_ +#define JOBLIST_PROFILING_H_ + +#include +#include +#include +#include +#include +#include + +namespace joblist +{ +// forward reference for ostream& operator<<(std::ostream&, ProfileGroup&); +class ProfileGroup; + +class ProfilePoint +{ +public: + // constructor, default copy constructor will be enough. + ProfilePoint(const std::string&); + +#if defined(CLOCK_REALTIME) + void start() { clock_gettime(CLOCK_REALTIME, &fIntBegin); } +#elif defined(_my_pthread_h) + //FIXME: This looks suspect! + void start() { fIntBegin.tv.i64 = fIntBegin.max_timeout_msec = 0; } +#else + void start() { fIntBegin.tv_sec = fIntBegin.tv_nsec = 0; } +#endif + void stop(); + timespec ttl() { return fTtl; } + timespec average() const; + + friend std::ostream& operator<<(std::ostream&, const ProfilePoint&); + friend std::ostream& operator<<(std::ostream&, ProfileGroup&); + +private: + timespec fIntBegin; // interval timing start + timespec fTtl; // total time + timespec fMax; // max interval + timespec fMin; // min interval + uint64_t fCount; // checkpoint access count + double fPercent; // percentage in whole process + std::string fCheckpoint; // name of the point +}; + + +class ProfileGroup +{ +public: + // constructor, default copy constructor will be enough. + ProfileGroup(); + + // initialize the ProfilePoint vector + void initialize(uint64_t pointCount, const std::string* pointName); + + friend class ProfileData; + + // output to a stream + friend std::ostream& operator<<(std::ostream&, ProfileGroup&); + +protected: + std::vector fPoints; +}; + + +class ProfileData +{ +public: + // constructor, default copy constructor will be enough. + ProfileData(); + + // initialize the ProfilePoint vector + void initialize(const std::string& name); + + // reset start time to current time + void restart(); + + // start/stop timing at group[g] point[p] + void start(uint64_t g, uint64_t p); + void stop(uint64_t g, uint64_t p); + + // add a group + void addGroup(ProfileGroup& g) { fPrfGroup.push_back(g); } + + // output to a stream + friend std::ostream& operator<<(std::ostream&, ProfileData&); + +private: + std::string fName; + timespec fTs1, fTs2; + + std::vector fPrfGroup; +}; + +extern const timespec timespec_ini(); +extern const timespec timespec_max(); +extern const timespec timespec_min(); +extern int64_t timespec_compare(const timespec &tv1, const timespec &tv2); +extern timespec timespec_add(const timespec &tv1, const timespec &tv2); +extern timespec timespec_sub(const timespec &tv1, const timespec &tv2); + +extern std::ostream& operator<<(std::ostream&, const timespec&); +extern std::ostream& operator<<(std::ostream&, const ProfilePoint&); +extern std::ostream& operator<<(std::ostream&, ProfileGroup&); +extern std::ostream& operator<<(std::ostream&, ProfileData&); + +} + +#endif // JOBLIST_PROFILING_H_ diff --git a/dbcon/joblist/pseudocc-jl.cpp b/dbcon/joblist/pseudocc-jl.cpp deleted file mode 100644 index b6932fc7..00000000 --- a/dbcon/joblist/pseudocc-jl.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - - -#include "pseudocc-jl.h" -#include "pseudocolumn.h" -#include "nullvaluemanip.h" - -using namespace std; -using namespace messageqcpp; -using namespace execplan; - -namespace joblist { - -PseudoCCJL::PseudoCCJL(const PseudoColStep &pcs) : ColumnCommandJL(pcs), function(pcs.pseudoColumnId()) -{ -} - -PseudoCCJL::~PseudoCCJL() -{ -} - -void PseudoCCJL::createCommand(ByteStream &bs) const -{ - bs << (uint8_t) PSEUDO_COLUMN; - bs << function; - ColumnCommandJL::createCommand(bs); -} - -void PseudoCCJL::runCommand(ByteStream &bs) const -{ - if (function == PSEUDO_EXTENTMAX) { - int64_t max = extents[currentExtentIndex].partition.cprange.hi_val; - int64_t min = extents[currentExtentIndex].partition.cprange.lo_val; - if (extents[currentExtentIndex].partition.cprange.isValid == BRM::CP_VALID && max >= min) - bs << max; - else - bs << utils::getNullValue(colType.colDataType, colType.colWidth); - } - else if (function == PSEUDO_EXTENTMIN) { - int64_t max = extents[currentExtentIndex].partition.cprange.hi_val; - int64_t min = extents[currentExtentIndex].partition.cprange.lo_val; - if (extents[currentExtentIndex].partition.cprange.isValid == BRM::CP_VALID && max >= min) - bs << min; - else - bs << utils::getNullValue(colType.colDataType, colType.colWidth); - } - else if (function == PSEUDO_EXTENTID) - bs << extents[currentExtentIndex].range.start; - ColumnCommandJL::runCommand(bs); -} - -string PseudoCCJL::toString() -{ - ostringstream oss; - oss << "PseudoColumnJL fcn: " << function << " on: " << ColumnCommandJL::toString(); - return oss.str(); -} - - - - - -} diff --git a/dbcon/joblist/pseudocc-jl.h b/dbcon/joblist/pseudocc-jl.h deleted file mode 100644 index c1c2c0bb..00000000 --- a/dbcon/joblist/pseudocc-jl.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - - -#ifndef PSEUDOCCJL_H -#define PSEUDOCCJL_H - -#include "columncommand-jl.h" - -namespace joblist { - -class PseudoCCJL : public ColumnCommandJL -{ - public: - PseudoCCJL(const PseudoColStep &); - virtual ~PseudoCCJL(); - - virtual void createCommand(messageqcpp::ByteStream &) const; - virtual void runCommand(messageqcpp::ByteStream &) const; - virtual std::string toString(); - uint32_t getFunction() const { return function; } - protected: - private: - uint32_t function; -}; - - -} -#endif // PSEUDOCCJL_H diff --git a/dbcon/joblist/reducestep.cpp b/dbcon/joblist/reducestep.cpp new file mode 100644 index 00000000..f855e416 --- /dev/null +++ b/dbcon/joblist/reducestep.cpp @@ -0,0 +1,783 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/***************************************************************************** + * $Id: reducestep.cpp 8436 2012-04-04 18:18:21Z rdempsey $ + * + ****************************************************************************/ + +#include "jobstep.h" +#include "datalist.h" +#include "exceptclasses.h" +#include + +#include +#include + +using namespace std; + +namespace { +using namespace joblist; + +const string finish(" finish: "); +struct Reducer { + ReduceStep *step; + + Reducer(ReduceStep *s) : step(s) + { } + + void operator()() { + try { + step->doReduction(); + } + catch (exception &e) { + cout << "reducestep: caught: " << e.what() << endl; + catchHandler(e.what()); //throw; //@bug 632 + } + catch (...) { + string msg("Reducer caught something not an exception!"); + cout << msg << endl; + catchHandler(msg); //throw; //@bug 632 + } + } +}; +}; + +namespace joblist { + +ReduceStep::ReduceStep(const JobStepAssociation& in, const JobStepAssociation& out, + execplan::CalpontSystemCatalog::OID tableOID, + uint32_t session, + uint32_t txn, + uint32_t ver, + uint16_t step, + uint32_t statement) : JobStep(), + inJSA(in), + outJSA(out), + fTableOID(tableOID), + sessionID(session), + txnID(txn), + verID(ver), + stepID(step), + statementID(statement), + inputSize(0), + outputSize(0), + fAlias1(), + fAlias2(), + fTimeSet() +{ +} + +ReduceStep::~ReduceStep() { } + +const JobStepAssociation & ReduceStep::inputAssociation() const +{ + return inJSA; +} + +void ReduceStep::inputAssociation(const JobStepAssociation &in) +{ + inJSA = in; +} + +const JobStepAssociation & ReduceStep::outputAssociation() const +{ + return outJSA; +} + +void ReduceStep::outputAssociation(const JobStepAssociation &out) +{ + outJSA = out; +} + +void ReduceStep::join() +{ + runner->join(); +} + +const std::string ReduceStep::toString() const +{ + DataList_t* dl = outJSA.outAt(0)->dataList(); + ostringstream oss; + oss << "ReduceStep ses:" << sessionID << " txn:" << txnID << " ver:" << verID; + oss << " st:" << stepId() << " tb/col:" << fTableOID << "/" << dl->OID(); + oss << " tb/col:" << fTableOID << "/" << dl->OID(); + oss << " " << omitOidInDL + << outJSA.outAt(0) << showOidInDL; + oss << " alias1: " << ((fAlias1.length()) ? fAlias1 : "none"); + oss << " alias2: " << ((fAlias2.length()) ? fAlias2 : "none"); + oss << " in:"; + for (unsigned i = 0; i < inJSA.outSize(); i++) + { + oss << inJSA.outAt(i) << ", "; + } + + return oss.str(); +} + +void ReduceStep::stepId(uint16_t id) +{ + stepID = id; +} + +uint16_t ReduceStep::stepId() const +{ + return stepID; +} + +uint32_t ReduceStep::sessionId() const +{ + return sessionID; +} + +uint32_t ReduceStep::txnId() const +{ + return txnID; +} + +uint32_t ReduceStep::statementId() const +{ + return statementID; +} + +void ReduceStep::run() +{ + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + string("ReduceStep")); // step name + } + runner.reset(new boost::thread(Reducer(this))); +} + +void ReduceStep::unblockDatalists(uint16_t status) +{ + outJSA.status(status); + + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + StrDataList *strdlout = outJSA.outAt(0)->stringDataList(); + + if (fifo) fifo->endOfInput(); + else if (dlout) dlout->endOfInput(); + else if (strdlout) strdlout->endOfInput(); +} + + +void ReduceStep::doReduction() +{ + DataList *dlIn1=inJSA.outAt(0)->dataList(); + DataList *dlIn2=inJSA.outAt(1)->dataList(); + ZDL *zdlIn1=inJSA.outAt(0)->zonedDL(); + ZDL *zdlIn2=inJSA.outAt(1)->zonedDL(); + FIFO > *fifoIn1=inJSA.outAt(0)->fifoDL(); + FIFO > *fifoIn2=inJSA.outAt(1)->fifoDL(); + + DataList *sdlIn1=inJSA.outAt(0)->strDataList(); + DataList *sdlIn2=inJSA.outAt(1)->strDataList(); + ZDL *szdlIn1=inJSA.outAt(0)->stringZonedDL(); + ZDL *szdlIn2=inJSA.outAt(1)->stringZonedDL(); + FIFO > *sfifoIn1=inJSA.outAt(0)->stringDL(); + FIFO > *sfifoIn2=inJSA.outAt(1)->stringDL(); + + try + { + if (0 < inJSA.status()) + { + unblockDatalists(inJSA.status()); + } + else + { + // make sure the input datalists are either ordered fifo or zdl + // if not, throw an exception + bool dlTypeOK = true; + if (dlIn1 != NULL) + dlTypeOK = dlTypeOK && ((zdlIn1 != NULL) || ((fifoIn1 != NULL) && fifoIn1->inOrder())); + else if (sdlIn1 != NULL) + dlTypeOK = dlTypeOK && ((szdlIn1 != NULL) || ((sfifoIn1 != NULL) && sfifoIn1->inOrder())); + + if (dlIn2 != NULL) + dlTypeOK = dlTypeOK && ((zdlIn2 != NULL) || ((fifoIn2 != NULL) && fifoIn2->inOrder())); + else if (sdlIn2 != NULL) + dlTypeOK = dlTypeOK && ((szdlIn2 != NULL) || ((sfifoIn2 != NULL) && sfifoIn2->inOrder())); + + if (dlTypeOK == false) + throw logic_error("ReduceStep: input datalist is not ZDL or ordered FIFO."); + + // input lists are fifo + if (fifoIn1 != NULL && fifoIn2 != NULL) + reduceByOrderedFifo(fifoIn1, fifoIn2); + else if (sfifoIn1 != NULL && sfifoIn2 != NULL) + reduceByOrderedFifo(sfifoIn1, sfifoIn2); + else if (fifoIn1 != NULL && sfifoIn2 != NULL) + reduceByOrderedFifo(fifoIn1, sfifoIn2); + else if (sfifoIn1 != NULL && fifoIn2 != NULL) + reduceByOrderedFifo(sfifoIn1, fifoIn2); + + // input lists are zdl + else if (zdlIn1 != NULL && zdlIn2 != NULL) + reduceByZdl(zdlIn1, zdlIn2); + else if (szdlIn1 != NULL && szdlIn2 != NULL) + reduceByZdl(szdlIn1, szdlIn2); + else if (sdlIn1 != NULL && sdlIn2 != NULL) + reduceByZdl(szdlIn1, szdlIn2); + else if (dlIn1 != NULL && szdlIn2 != NULL) + reduceByZdl(zdlIn1, szdlIn2); + else if (sdlIn1 != NULL && zdlIn2 != NULL) + reduceByZdl(szdlIn1, zdlIn2); + + // one is fifo, the other is zdl + else if (fifoIn1 != NULL && zdlIn2 != NULL) + reduceByMixedDl(fifoIn1, zdlIn2); + else if (fifoIn1 != NULL && szdlIn2 != NULL) + reduceByMixedDl(fifoIn1, szdlIn2); + else if (sfifoIn1 != NULL && zdlIn2 != NULL) + reduceByMixedDl(sfifoIn1, zdlIn2); + else if (sfifoIn1 != NULL && szdlIn2 != NULL) + reduceByMixedDl(sfifoIn1, szdlIn2); + else if (fifoIn2 != NULL && zdlIn1 != NULL) + reduceByMixedDl(fifoIn2, zdlIn1); + else if (fifoIn2 != NULL && szdlIn1 != NULL) + reduceByMixedDl(fifoIn2, szdlIn1); + else if (sfifoIn2 != NULL && zdlIn1 != NULL) + reduceByMixedDl(sfifoIn2, zdlIn1); + else // (sfifoIn2 != NULL && szdlIn1 != NULL) + reduceByMixedDl(sfifoIn2, szdlIn1); + } + + }// try + catch(const logging::LargeDataListExcept& ex) + { + catchHandler(ex.what(), sessionID); + unblockDatalists(logging::reduceStepLargeDataListFileErr); + } + catch(const exception& ex) + { + catchHandler(ex.what(), sessionID); + unblockDatalists(logging::reduceStepErr); + } + catch(...) + { + catchHandler("ReduceStep caught an unknown exception", sessionID); + unblockDatalists(logging::reduceStepErr); + } + + if (traceOn()) + { + std::ostringstream oss; + oss << "ses:" << sessionID << " st: " << stepID + << " finished at " << dlTimes.EndOfInputTimeString() + << "; input size-" << inputSize << "; output size-" << outputSize << endl + << "\t1st read " << dlTimes.FirstReadTimeString() + << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" + << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) + << "s" << endl << "\tWork Times: " << mergeTime << fTimeSet.totalTime(mergeTime) << " " + << insertTime << fTimeSet.totalTime(insertTime) << finish << fTimeSet.totalTime(finish) + << "\n\tJob completion status " << outJSA.status() << endl; + + logEnd(oss.str().c_str()); + + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstReadTime(), // first datalist write(use 1st read) + dlTimes.LastInsertTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist input to report + } +} + +template +void ReduceStep::reduceByOrderedFifo(FIFO *dl1, FIFO *dl2) +{ + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + + if (fifo) + { + element1_t rw1; + element2_t rw2; + RowWrapper rw3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &rw2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0, j=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (rw1.et[i].first < rw2.et[j].first) + { + ++i; + } + else if (rw1.et[i].first > rw2.et[j].first) + { + ++j; + } + else + { + rw3.et[rw3.count++].first = rw1.et[i].first; + ++i; + ++j; + ++inputSize; + } + + ++inputSize; + + if (rw3.count == rw3.ElementsPerGroup) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + fTimeSet.holdTimer(insertTime); + } + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + if (j == rw2.count) + { + more2 = dl2->next(id2, &rw2); + j = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + fTimeSet.setTimer(insertTime); + if (rw3.count > 0) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + fTimeSet.holdTimer(insertTime); + dlTimes.setLastReadTime(); + + fifo->totalSize(outputSize); + + fifo->endOfInput(); + dlTimes.setEndOfInputTime(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &rw1); + while (more2) + more2 = dl2->next(id2, &rw2); + fTimeSet.setTimer(finish,false); + } + + else + { + element1_t rw1; + element2_t rw2; + ElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &rw2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0, j=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (rw1.et[i].first < rw2.et[j].first) + { + ++i; + } + else if (rw1.et[i].first > rw2.et[j].first) + { + ++j; + } + else + { + e3.first = rw1.et[i].first; + dlout->insert(e3); + ++i; + ++j; + ++inputSize; + } + + ++inputSize; + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + if (j == rw2.count) + { + more2 = dl2->next(id2, &rw2); + j = 0; + } + } + fTimeSet.setTimer(mergeTime,false); + dlTimes.setLastReadTime(); + + dlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = dlout->totalSize(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &rw1); + while (more2) + more2 = dl2->next(id2, &rw2); + fTimeSet.setTimer(finish,false); + } +} + + +template +void ReduceStep::reduceByZdl(ZDL *dl1, ZDL *dl2) +{ + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + + StrDataList *strdlout = outJSA.outAt(0)->stringDataList(); + + + if (fifo) + { + element1_t e1; + element2_t e2; + RowWrapper rw3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &e1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (e1.first < e2.first) + { + more1 = dl1->next(id1, &e1); + } + else if (e1.first > e2.first) + { + more2 = dl2->next(id2, &e2); + } + else + { + rw3.et[rw3.count++].first = e1.first; + ++inputSize; + more1 = dl1->next(id1, &e1); + more2 = dl2->next(id2, &e2); + } + + ++inputSize; + + if (rw3.count == rw3.ElementsPerGroup) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + fTimeSet.holdTimer(insertTime); + } + } + fTimeSet.setTimer(mergeTime, false); + // no more input + if (rw3.count > 0) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + fTimeSet.holdTimer(insertTime); + } + + dlTimes.setLastReadTime(); + + fifo->totalSize(outputSize); + + fifo->endOfInput(); + dlTimes.setEndOfInputTime(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &e1); + while (more2) + more2 = dl2->next(id2, &e2); + fTimeSet.setTimer(finish,false); + } + + else if (dlout) + { + element1_t e1; + element2_t e2; + ElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &e1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (e1.first < e2.first) + { + more1 = dl1->next(id1, &e1); + } + else if (e1.first > e2.first) + { + more2 = dl2->next(id2, &e2); + } + else + { + e3.first = e1.first; + dlout->insert(e3); + ++inputSize; + more1 = dl1->next(id1, &e1); + more2 = dl2->next(id2, &e2); + } + + ++inputSize; + } + fTimeSet.setTimer(mergeTime,false); + dlTimes.setLastReadTime(); + + dlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = dlout->totalSize(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &e1); + while (more2) + more2 = dl2->next(id2, &e2); + fTimeSet.setTimer(finish,false); + } + else if (strdlout) + { + element1_t e1; + element2_t e2; + StringElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &e1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (e1.first < e2.first) + { + more1 = dl1->next(id1, &e1); + } + else if (e1.first > e2.first) + { + more2 = dl2->next(id2, &e2); + } + else + { + e3.first = e1.first; + strdlout->insert(e3); + ++inputSize; + more1 = dl1->next(id1, &e1); + more2 = dl2->next(id2, &e2); + } + + ++inputSize; + } + fTimeSet.setTimer(mergeTime,false); + dlTimes.setLastReadTime(); + + strdlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = strdlout->totalSize(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &e1); + while (more2) + more2 = dl2->next(id2, &e2); + fTimeSet.setTimer(finish,false); + } + else + throw logic_error("ReduceStep: output datalist is unknown type."); + + +} + + +template +void ReduceStep::reduceByMixedDl(FIFO *dl1, ZDL *dl2) +{ + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + + if (fifo) + { + element1_t rw1; + element2_t e2; + RowWrapper rw3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (rw1.et[i].first < e2.first) + { + ++i; + } + else if (rw1.et[i].first > e2.first) + { + more2 = dl2->next(id2, &e2); + } + else + { + rw3.et[rw3.count++].first = rw1.et[i++].first; + more2 = dl2->next(id2, &e2); + ++inputSize; + } + + ++inputSize; + + if (rw3.count == rw3.ElementsPerGroup) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + fTimeSet.holdTimer(insertTime); + outputSize += rw3.count; + rw3.count = 0; + } + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + if (rw3.count > 0) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + fTimeSet.holdTimer(insertTime); + outputSize += rw3.count; + rw3.count = 0; + } + + dlTimes.setLastReadTime(); + + fifo->totalSize(outputSize); + + fifo->endOfInput(); + dlTimes.setEndOfInputTime(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &rw1); + while (more2) + more2 = dl2->next(id2, &e2); + fTimeSet.setTimer(finish,false); + } + + else + { + element1_t rw1; + element2_t e2; + ElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2) + { + if (rw1.et[i].first < e2.first) + { + ++i; + } + else if (rw1.et[i].first > e2.first) + { + more2 = dl2->next(id2, &e2); + } + else + { + e3.first = e2.first; + dlout->insert(e3); + more2 = dl2->next(id2, &e2); + ++i; + ++inputSize; + } + + ++inputSize; + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + dlTimes.setLastReadTime(); + + dlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = dlout->totalSize(); + + fTimeSet.setTimer(finish); + while (more1) + more1 = dl1->next(id1, &rw1); + while (more2) + more2 = dl2->next(id2, &e2); + fTimeSet.setTimer(finish,false); + } +} + +}; //namespace diff --git a/dbcon/joblist/resource.h b/dbcon/joblist/resource.h deleted file mode 100644 index 74ca7f73..00000000 --- a/dbcon/joblist/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by libjoblist.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/dbcon/joblist/resourcedistributor.cpp b/dbcon/joblist/resourcedistributor.cpp index 739fbd9a..2f4dd8f6 100644 --- a/dbcon/joblist/resourcedistributor.cpp +++ b/dbcon/joblist/resourcedistributor.cpp @@ -26,7 +26,6 @@ #include using namespace std; -#include "jl_logger.h" #include "resourcedistributor.h" namespace joblist { @@ -36,7 +35,7 @@ const unsigned maxSessionsDefault = 100; uint64_t ResourceDistributor::requestResource(uint32_t sessionID) { uint64_t resource = getSessionResource(sessionID); - + return requestResource(sessionID, resource); } @@ -50,7 +49,7 @@ uint64_t ResourceDistributor::requestResource(uint32_t sessionID, uint64_t resou { if (fTraceOn) logMessage(logging::LOG_TYPE_DEBUG, LogRDRequestWait, resource, sessionID); - + fResourceAvailable.wait(lk); if (fTraceOn) @@ -86,8 +85,8 @@ void ResourceDistributor::logMessage(logging::LOG_TYPE logLevel, logging::Messag log.logMessage(logLevel, mid, args, logging::LoggingID(5, sessionID)); } -void LockedSessionMap::updateAging(uint32_t sessionID) -{ +void LockedSessionMap::updateAging(uint32_t sessionID) +{ boost::mutex::scoped_lock lock(fSessionLock); SessionList::iterator pos = find(fSessionAgingList.begin(), fSessionAgingList.end(), sessionID); if (fSessionAgingList.end() != pos) @@ -96,15 +95,15 @@ void LockedSessionMap::updateAging(uint32_t sessionID) fSessionAgingList.push_back(sessionID); } -uint64_t LockedSessionMap::getSessionResource(uint32_t sessionID) -{ +uint64_t LockedSessionMap::getSessionResource(uint32_t sessionID) +{ SessionMap::const_iterator it = fSessionMap.find(sessionID); if (fSessionMap.end() != it) { updateAging(sessionID); - return it->second; + return it->second; } - return fResourceBlock; + return fResourceBlock; } bool LockedSessionMap::addSession(uint32_t sessionID, uint64_t resource, uint64_t limit) @@ -117,7 +116,7 @@ bool LockedSessionMap::addSession(uint32_t sessionID, uint64_t resource, uint64_ } boost::mutex::scoped_lock maplock(fMapLock); - fSessionMap[sessionID] = resource; + fSessionMap[sessionID] = resource; updateAging(sessionID); if (fMaxSessions < fSessionMap.size()) { @@ -130,10 +129,10 @@ bool LockedSessionMap::addSession(uint32_t sessionID, uint64_t resource, uint64_ } -void LockedSessionMap::removeSession(uint32_t sessionID) +void LockedSessionMap::removeSession(u_int32_t sessionID) { boost::mutex::scoped_lock maplock(fMapLock); - fSessionMap.erase(sessionID); + fSessionMap.erase(sessionID); boost::mutex::scoped_lock listlock(fSessionLock); fSessionAgingList.erase(find(fSessionAgingList.begin(), fSessionAgingList.end(), sessionID)); } @@ -150,5 +149,5 @@ ostream& operator<<(ostream& os, const LockedSessionMap& lsm) os << endl; return os; } -} //namespace +} //namespace diff --git a/dbcon/joblist/resourcedistributor.h b/dbcon/joblist/resourcedistributor.h index 126f3103..70fb9666 100644 --- a/dbcon/joblist/resourcedistributor.h +++ b/dbcon/joblist/resourcedistributor.h @@ -26,16 +26,15 @@ #define JOBLIST_RESOURCEMANAGER_H #include +#include "jl_logger.h" #include #include #include -#include "logger.h" - #undef min #undef max -namespace joblist +namespace joblist { /** @brief ResourceDistributor @@ -49,10 +48,10 @@ namespace joblist * The aging logic is needed because exemgr gets a close message after every query, not * for a session, so it does not know when a session is ended. Therefore LockedSessionMap * must keep all its sessions. To prevent the map from becoming too large, after it reaches - * fMaxSessions, it removes the oldest used session. fMaxSessions is defined in + * fMaxSessions, it removes the oldest used session. fMaxSessions is defined in * resourcedistributor.cpp. UpdateAging keeps the last accessed session at the end of the * aging list. The oldest is at the front. - * + * */ extern const unsigned maxSessionsDefault; @@ -72,7 +71,7 @@ class LockedSessionMap void updateAging(uint32_t sessionID); boost::mutex fMapLock; SessionMap fSessionMap; - uint64_t fResourceBlock; + uint64_t fResourceBlock; boost::mutex fSessionLock; SessionList fSessionAgingList; const unsigned fMaxSessions; @@ -85,44 +84,44 @@ class ResourceDistributor { public: - ResourceDistributor(const std::string& job, const std::string& identity, uint64_t totalResource, uint64_t resourceBlock, bool trace) : + ResourceDistributor(const std::string& job, const std::string& identity, uint64_t totalResource, uint64_t resourceBlock, bool trace) : fJob(job), fIdentity(identity), fTotalResource(totalResource), fSessionMap(resourceBlock), fTraceOn(trace) {} - + virtual ~ResourceDistributor(){} - + typedef std::map SessionMap; - + uint64_t requestResource(uint32_t sessionID); uint64_t requestResource(uint32_t sessionID, uint64_t resource); void returnResource(uint64_t resource); - - uint64_t getSessionResource(uint32_t sessionID) - { + + uint64_t getSessionResource(uint32_t sessionID) + { return fSessionMap.getSessionResource(sessionID); } uint64_t getTotalResource() const { return fTotalResource; } - + void setTrace(bool trace) { fTraceOn = trace; } - + bool addSession(uint32_t sessionID, uint64_t resource) {return fSessionMap.addSession(sessionID, resource, fTotalResource);} void removeSession(uint32_t sessionID) {fSessionMap.removeSession(sessionID); } private: void logMessage(logging::LOG_TYPE logLevel, logging::Message::MessageID mid, uint64_t value = 0, uint32_t sessionId = 0); - + std::string fJob; std::string fIdentity; uint64_t fTotalResource; uint64_t fResourceBlock; boost::mutex fResourceLock; boost::condition fResourceAvailable; - - LockedSessionMap fSessionMap; + + LockedSessionMap fSessionMap; uint32_t fTraceOn; }; diff --git a/dbcon/joblist/resourcemanager.cpp b/dbcon/joblist/resourcemanager.cpp index 9babbb06..25a4642c 100644 --- a/dbcon/joblist/resourcemanager.cpp +++ b/dbcon/joblist/resourcemanager.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** - * $Id: resourcemanager.cpp 9655 2013-06-25 23:08:13Z xlou $ + * $Id: resourcemanager.cpp 9491 2013-05-06 20:57:41Z pleblanc $ * ******************************************************************************************/ @@ -32,14 +32,52 @@ using namespace std; #include using namespace boost; +#define RESOURCEMANAGER_DLLEXPORT #include "resourcemanager.h" - -#include "jl_logger.h" -#include "cgroupconfigurator.h" -#include "liboamcpp.h" +#undef RESOURCEMANAGER_DLLEXPORT using namespace config; +namespace +{ + +unsigned getNumCores() +{ +#ifdef _MSC_VER + SYSTEM_INFO siSysInfo; + GetSystemInfo(&siSysInfo); + return siSysInfo.dwNumberOfProcessors; +#else + ifstream cpuinfo("/proc/cpuinfo"); + + if (!cpuinfo.good()) + return 0; + + unsigned nc = 0; + + regex re("Processor\\s*:\\s*[0-9]+", regex::normal|regex::icase); + + string line; + + getline(cpuinfo, line); + + unsigned i = 0; + while (i < 10000 && cpuinfo.good() && !cpuinfo.eof()) + { + if (regex_match(line, re)) + nc++; + + getline(cpuinfo, line); + + ++i; + } + + return nc; +#endif +} + +} + namespace joblist { //const string ResourceManager::fExeMgrStr("ExeMgr1"); @@ -65,12 +103,12 @@ namespace joblist { fHjNumThreads(defaultNumThreads), fJlProcessorThreadsPerScan(defaultProcessorThreadsPerScan), fJlNumScanReceiveThreads(defaultScanReceiveThreads), - fTwNumThreads(defaultNumThreads), + fTwNumThreads(defaultNumThreads), fHJUmMaxMemorySmallSideDistributor(fHashJoinStr, "UmMaxMemorySmallSide", getUintVal(fHashJoinStr, "TotalUmMaxMemorySmallSide", defaultTotalUmMemory), getUintVal(fHashJoinStr, "UmMaxMemorySmallSide", defaultHJUmMaxMemorySmallSide), - 0), + 0), fHJPmMaxMemorySmallSideSessionMap( getUintVal(fHashJoinStr, "PmMaxMemorySmallSide", defaultHJPmMaxMemorySmallSide)), isExeMgr(runningInExeMgr) @@ -87,8 +125,7 @@ namespace joblist { if (configNumCores <= 0) { //count the actual #cores - utils::CGroupConfigurator cg; - fNumCores = cg.getNumCores(); + fNumCores = getNumCores(); if (fNumCores <= 0) fNumCores = 8; } @@ -116,50 +153,15 @@ namespace joblist { temp = getIntVal(fTupleWSDLStr, "NumThreads", -1); if (temp > 0) fTwNumThreads = temp; - + pmJoinMemLimit = getIntVal(fHashJoinStr, "PmMaxMemorySmallSide", defaultHJPmMaxMemorySmallSide); - // Need to use different limits if this instance isn't running on the UM, - // or if it's an ExeMgr running on a PM node + // Need to use different limits if this instance isn't running on the UM if (!isExeMgr) totalUmMemLimit = pmJoinMemLimit; - else { - string whichLimit = "TotalUmMemory"; - string pmWithUM = fConfig->getConfig("Installation", "PMwithUM"); - if (pmWithUM == "y" || pmWithUM == "Y") { - oam::Oam OAM; - oam::oamModuleInfo_t moduleInfo = OAM.getModuleInfo(); - string &moduleType = boost::get<1>(moduleInfo); - - if (moduleType == "pm" || moduleType == "PM") { - string doesItExist = fConfig->getConfig(fHashJoinStr, "TotalPmUmMemory"); - if (!doesItExist.empty()) - whichLimit = "TotalPmUmMemory"; - } - } - - string umtxt = fConfig->getConfig(fHashJoinStr, whichLimit); - if (umtxt.empty()) - totalUmMemLimit = defaultTotalUmMemory; - else { - // is it an absolute or a percentage? - if (umtxt.find('%') != string::npos) { - utils::CGroupConfigurator cg; - uint64_t totalMem = cg.getTotalMemory(); - totalUmMemLimit = atoll(umtxt.c_str())/100.0 * (double) totalMem; - - if (totalUmMemLimit == 0 || totalUmMemLimit == LLONG_MIN || - totalUmMemLimit == LLONG_MAX) // some garbage in the xml entry - totalUmMemLimit = defaultTotalUmMemory; - } - else { // an absolute; use the existing converter - totalUmMemLimit = getIntVal(fHashJoinStr, whichLimit, - defaultTotalUmMemory); - } - } - } - configuredUmMemLimit = totalUmMemLimit; - //cout << "RM: total UM memory = " << totalUmMemLimit << endl; + else + totalUmMemLimit = getIntVal(fHashJoinStr, "TotalUmMemory", + defaultTotalUmMemory); // multi-thread aggregate string nt, nb, nr; @@ -167,34 +169,19 @@ namespace joblist { if (nt.empty()) fAggNumThreads = numCores(); else - fAggNumThreads = fConfig->uFromText(nt); - + fAggNumThreads = fConfig->uFromText(nt); + nb = fConfig->getConfig("RowAggregation","RowAggrBuckets"); if (nb.empty()) fAggNumBuckets = fAggNumThreads * 4; else fAggNumBuckets = fConfig->uFromText(nb); - + nr = fConfig->getConfig("RowAggregation", "RowAggrRowGroupsPerThread"); if (nr.empty()) fAggNumRowGroups = 20; else fAggNumRowGroups = fConfig->uFromText(nr); - - // window function - string wt = fConfig->getConfig("WindowFunction", "WorkThreads"); - if (wt.empty()) - fWindowFunctionThreads = numCores(); - else - fWindowFunctionThreads = fConfig->uFromText(wt); - - // hdfs info - string hdfs = fConfig->getConfig("SystemConfig", "DataFilePlugin"); - - if ( hdfs.find("hdfs") != string::npos) - fUseHdfs = true; - else - fUseHdfs = false; } int ResourceManager::getEmPriority() const @@ -214,8 +201,9 @@ namespace joblist { return val; } - void ResourceManager::addHJPmMaxSmallSideMap(uint32_t sessionID, uint64_t mem) - { + + void ResourceManager::addHJPmMaxSmallSideMap(uint32_t sessionID, uint64_t mem) + { if (fHJPmMaxMemorySmallSideSessionMap.addSession(sessionID, mem, fHJUmMaxMemorySmallSideDistributor.getTotalResource())) logResourceChangeMessage(logging::LOG_TYPE_INFO, sessionID, mem, defaultHJPmMaxMemorySmallSide, @@ -231,9 +219,9 @@ namespace joblist { LogRMResourceChangeError); } } - - void ResourceManager::addHJUmMaxSmallSideMap(uint32_t sessionID, uint64_t mem) - { + + void ResourceManager::addHJUmMaxSmallSideMap(uint32_t sessionID, uint64_t mem) + { if (fHJUmMaxMemorySmallSideDistributor.addSession(sessionID, mem)) logResourceChangeMessage(logging::LOG_TYPE_INFO, sessionID, mem, defaultHJUmMaxMemorySmallSide, "UmMaxMemorySmallSide", LogRMResourceChange); @@ -263,7 +251,7 @@ namespace joblist { } void ResourceManager::emServerThreads() { } - void ResourceManager::emServerQueueSize() { } + void ResourceManager::emServerQueueSize() { } void ResourceManager::emSecondsBetweenMemChecks() { } void ResourceManager::emMaxPct() { } void ResourceManager::emPriority() { } @@ -272,11 +260,11 @@ namespace joblist { void ResourceManager::hjNumThreads() { } void ResourceManager::hjMaxBuckets() { } void ResourceManager::hjMaxElems() { } - void ResourceManager::hjFifoSizeLargeSide() { } + void ResourceManager::hjFifoSizeLargeSide() { } void ResourceManager::hjPmMaxMemorySmallSide() { } void ResourceManager::jlFlushInterval() { } - void ResourceManager::jlFifoSize() { } + void ResourceManager::jlFifoSize() { } void ResourceManager::jlScanLbidReqLimit() { } void ResourceManager::jlScanLbidReqThreshold(){ } void ResourceManager::jlProjectBlockReqLimit(){ } @@ -318,37 +306,21 @@ namespace joblist { return rc; } - + bool ResourceManager::queryStatsEnabled() const { - std::string val(getStringVal("QueryStats", "Enabled", "N" )); - boost::to_upper(val); - return "Y" == val; + std::string val(getStringVal("QueryStats", "Enabled", "N" )); + boost::to_upper(val); + return "Y" == val; } bool ResourceManager::userPriorityEnabled() const { - std::string val(getStringVal("UserPriority", "Enabled", "N" )); - boost::to_upper(val); - return "Y" == val; -} - -bool ResourceManager::getMemory(int64_t amount, boost::shared_ptr sessionLimit, bool patience) -{ - bool ret1 = (atomicops::atomicSub(&totalUmMemLimit, amount) >= 0); - bool ret2 = (atomicops::atomicSub(sessionLimit.get(), amount) >= 0); - - uint32_t retryCounter = 0, maxRetries = 20; // 10s delay - while (patience && !(ret1 && ret2) && retryCounter++ < maxRetries) { - atomicops::atomicAdd(&totalUmMemLimit, amount); - atomicops::atomicAdd(sessionLimit.get(), amount); - usleep(500000); - ret1 = (atomicops::atomicSub(&totalUmMemLimit, amount) >= 0); - ret2 = (atomicops::atomicSub(sessionLimit.get(), amount) >= 0); - } - return (ret1 && ret2); + std::string val(getStringVal("UserPriority", "Enabled", "N" )); + boost::to_upper(val); + return "Y" == val; } -} //namespace +} //namespace diff --git a/dbcon/joblist/resourcemanager.h b/dbcon/joblist/resourcemanager.h index d65eef87..5507e7e9 100644 --- a/dbcon/joblist/resourcemanager.h +++ b/dbcon/joblist/resourcemanager.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** - * $Id: resourcemanager.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: resourcemanager.h 9491 2013-05-06 20:57:41Z pleblanc $ * ******************************************************************************************/ /** @@ -33,17 +33,23 @@ #include "configcpp.h" #include "calpontselectexecutionplan.h" +#include "jl_logger.h" #include "resourcedistributor.h" -#include "atomicops.h" +#if defined(_MSC_VER) && !defined(_WIN64) +# ifndef InterlockedAdd +# define InterlockedAdd64 InterlockedAdd +# define InterlockedAdd(x, y) ((x) + (y)) +# endif +#endif -#if defined(_MSC_VER) && defined(JOBLIST_DLLEXPORT) +#if defined(_MSC_VER) && defined(RESOURCEMANAGER_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT #endif -namespace joblist +namespace joblist { //aggfilterstep const uint32_t defaultNumThreads = 8; @@ -58,7 +64,7 @@ namespace joblist const uint32_t defaultTempSaveSize = defaultHJMaxElems; const uint64_t defaultTotalUmMemory = 8 * 1024 * 1024 * 1024ULL; const uint64_t defaultHUATotalMem = 8 * 1024 * 1024 * 1024ULL; - + const uint32_t defaultTupleDLMaxSize = 64 * 1024; const uint32_t defaultTupleMaxBuckets = 256; @@ -73,7 +79,7 @@ namespace joblist //pcolstep.cpp const uint32_t defaultProjectBlockReqLimit = 32 * 1024; const uint32_t defaultProjectBlockReqThreshold = 16 * 1024; //256 in jobstep.h - + //BatchPrimitiveStep const uint32_t defaultRequestSize = 1; const uint32_t defaultMaxOutstandingRequests = 20; @@ -100,40 +106,40 @@ namespace joblist const int defaultEMExecQueueSize = 20; - const uint64_t defaultInitialCapacity = 1024 * 1024; + const uint64_t defaultInitialCapacity = 1024 * 1024; const int defaultTWMaxBuckets = 256; const int defaultPSCount = 0; const int defaultConnectionsPerPrimProc = 1; - const uint32_t defaultLBID_Shift = 13; + const uint defaultLBID_Shift = 13; const uint64_t defaultExtentRows = 8 * 1024 * 1024; // DMLProc // @bug 1886. Knocked a 0 off the default below dropping it from 4M down to 256K. Delete was consuming too much memory. - const uint64_t defaultDMLMaxDeleteRows = 256 * 1024; + const uint64_t defaultDMLMaxDeleteRows = 256 * 1024; // Connector // @bug 2048. To control batch insert memory usage. - const uint64_t defaultRowsPerBatch = 10000; - + const uint64_t defaultRowsPerBatch = 10000; + /* HJ CP feedback, see bug #1465 */ - const uint32_t defaultHjCPUniqueLimit = 100; + const uint defaultHjCPUniqueLimit = 100; // Order By and Limit const uint64_t defaultOrderByLimitMaxMemory = 1 * 1024 * 1024 * 1024ULL; const uint64_t defaultDECThrottleThreshold = 200000000; // ~200 MB + - const uint8_t defaultUseCpimport = 1; /** @brief ResourceManager - * Returns requested values from Config - * + * Returns requested values from Config + * */ class ResourceManager { public: /** @brief ctor - * + * */ EXPORT ResourceManager(bool runningInExeMgr=false); // ResourceManager(const config::Config *cf); @@ -159,7 +165,7 @@ namespace joblist unsigned getHjNumThreads() const { return fHjNumThreads; } //getUintVal(fHashJoinStr, "NumThreads", defaultNumThreads); } uint64_t getHjMaxElems() const { return getUintVal(fHashJoinStr, "MaxElems", defaultHJMaxElems); } uint32_t getHjFifoSizeLargeSide() const { return getUintVal(fHashJoinStr, "FifoSizeLargeSide", defaultHJFifoSizeLargeSide); } - uint32_t getHjCPUniqueLimit() const { return getUintVal(fHashJoinStr, "CPUniqueLimit", defaultHjCPUniqueLimit); } + uint getHjCPUniqueLimit() const { return getUintVal(fHashJoinStr, "CPUniqueLimit", defaultHjCPUniqueLimit); } uint64_t getPMJoinMemLimit() const { return pmJoinMemLimit; } uint32_t getJLFlushInterval() const { return getUintVal(fJobListStr, "FlushInterval", defaultFlushInterval); } @@ -168,27 +174,39 @@ namespace joblist uint32_t getJlScanLbidReqThreshold() const { return getUintVal(fJobListStr,"ScanLbidReqThreshold", defaultScanLbidReqThreshold); } // @bug 1264 - Added LogicalBlocksPerScan configurable which determines the number of blocks contained in each BPS scan request. - uint32_t getJlLogicalBlocksPerScan() const { return getUintVal(fJobListStr,"LogicalBlocksPerScan", defaultLogicalBlocksPerScan); } + uint32_t getJlLogicalBlocksPerScan() const { return getUintVal(fJobListStr,"LogicalBlocksPerScan", defaultLogicalBlocksPerScan); } uint32_t getJlProjectBlockReqLimit() const { return getUintVal(fJobListStr, "ProjectBlockReqLimit", defaultProjectBlockReqLimit ); } uint32_t getJlProjectBlockReqThreshold() const { return getUintVal(fJobListStr,"ProjectBlockReqThreshold", defaultProjectBlockReqThreshold);} uint32_t getJlNumScanReceiveThreads() const { return fJlNumScanReceiveThreads; } //getUintVal(fJobListStr, "NumScanReceiveThreads", defaultScanReceiveThreads); } - + // @bug 1424,1298 - uint32_t getJlProcessorThreadsPerScan() const { return fJlProcessorThreadsPerScan; } //getUintVal(fJobListStr,"ProcessorThreadsPerScan", defaultProcessorThreadsPerScan); } + uint32_t getJlProcessorThreadsPerScan() const { return fJlProcessorThreadsPerScan; } //getUintVal(fJobListStr,"ProcessorThreadsPerScan", defaultProcessorThreadsPerScan); } uint32_t getJlRequestSize() const { return getUintVal(fJobListStr, "RequestSize", defaultRequestSize ); } uint32_t getJlMaxOutstandingRequests() const { return getUintVal(fJobListStr,"MaxOutstandingRequests", defaultMaxOutstandingRequests);} uint32_t getJlJoinerChunkSize() const { return getUintVal(fJobListStr,"JoinerChunkSize", defaultJoinerChunkSize);} int getPsCount() const { return getUintVal(fPrimitiveServersStr, "Count", defaultPSCount ); } - int getPsConnectionsPerPrimProc() const { return getUintVal(fPrimitiveServersStr, "ConnectionsPerPrimProc", defaultConnectionsPerPrimProc); } - uint32_t getPsLBID_Shift() const { return getUintVal(fPrimitiveServersStr, "LBID_Shift", defaultLBID_Shift ); } + int getPsConnectionsPerPrimProc() const { return getUintVal(fPrimitiveServersStr, "ConnectionsPerPrimProc", defaultConnectionsPerPrimProc); } + uint getPsLBID_Shift() const { return getUintVal(fPrimitiveServersStr, "LBID_Shift", defaultLBID_Shift ); } + bool getPsMulticast() const + { + std::string val(getStringVal(fPrimitiveServersStr, "Multicast", "N" )); + boost::to_upper(val); + return "Y" == val; + } + bool getPsMulticastLoop() const + { + std::string val(getStringVal(fPrimitiveServersStr, "MulticastLoop", "N" )); + boost::to_upper(val); + return "Y" == val; + } std::string getScTempDiskPath() const { return getStringVal(fSystemConfigStr, "TempDiskPath", defaultTempDiskPath ); } uint64_t getScTempSaveSize() const { return getUintVal(fSystemConfigStr, "TempSaveSize", defaultTempSaveSize); } std::string getScWorkingDir() const { return getStringVal(fSystemConfigStr, "WorkingDir", defaultWorkingDir ); } uint32_t getTwMaxSize() const { return getUintVal(fTupleWSDLStr, "MaxSize",defaultTupleDLMaxSize ); } - uint64_t getTwInitialCapacity() const { return getUintVal(fTupleWSDLStr, "InitialCapacity", defaultInitialCapacity ); } + uint64_t getTwInitialCapacity() const { return getUintVal(fTupleWSDLStr, "InitialCapacity", defaultInitialCapacity ); } int getTwMaxBuckets () const { return getUintVal(fTupleWSDLStr, "MaxBuckets", defaultTWMaxBuckets ); } uint8_t getTwNumThreads() const { return fTwNumThreads; } //getUintVal(fTupleWSDLStr, "NumThreads", defaultNumThreads ); } uint64_t getZdl_MaxElementsInMem() const { return getUintVal(fZDLStr,"ZDL_MaxElementsInMem", defaultMaxElementsInMem ); } @@ -212,11 +230,6 @@ namespace joblist uint64_t getRowsPerBatch() const { return getUintVal(fBatchInsertStr, "RowsPerBatch", defaultRowsPerBatch); } - uint8_t getUseCpimport() const - { - int val = getIntVal(fBatchInsertStr, "UseCpimport", defaultUseCpimport); - return val; } - uint64_t getOrderByLimitMaxMemory() const { return getUintVal(fOrderByLimitStr, "MaxMemory", defaultOrderByLimitMaxMemory); } @@ -237,13 +250,19 @@ namespace joblist EXPORT void hjPmMaxMemorySmallSide(); /* new HJ/Union/Aggregation mem interface, used by TupleBPS */ - /* sessionLimit is a pointer to the var holding the session-scope limit, should be JobInfo.umMemLimit - for the query. */ - /* Temporary parameter 'patience', will wait for up to 10s to get the memory. */ - EXPORT bool getMemory(int64_t amount, boost::shared_ptr sessionLimit, bool patience = true); - inline void returnMemory(int64_t amount, boost::shared_ptr sessionLimit) { - atomicops::atomicAdd(&totalUmMemLimit, amount); - atomicops::atomicAdd(sessionLimit.get(), amount); + inline bool getMemory(int64_t amount) { +#ifdef _MSC_VER + return InterlockedAdd64(&totalUmMemLimit, -amount) >= 0; +#else + return __sync_sub_and_fetch(&totalUmMemLimit, amount) >= 0; +#endif + } + inline void returnMemory(int64_t amount) { +#ifdef _MSC_VER + InterlockedAdd64(&totalUmMemLimit, amount); +#else + __sync_add_and_fetch(&totalUmMemLimit, amount); +#endif } inline int64_t availableMemory() { return totalUmMemLimit; } @@ -267,7 +286,7 @@ namespace joblist fHJPmMaxMemorySmallSideSessionMap.removeSession(sessionID); fHJUmMaxMemorySmallSideDistributor.removeSession(sessionID); } - + uint64_t requestHJMaxMemorySmallSide(uint32_t sessionID, uint64_t amount) { return fHJUmMaxMemorySmallSideDistributor.requestResource(sessionID, amount); } @@ -275,7 +294,6 @@ namespace joblist void returnHJUmMaxMemorySmallSide(uint64_t mem) { fHJUmMaxMemorySmallSideDistributor.returnResource(mem); } - EXPORT void jlFlushInterval(); EXPORT void jlFifoSize(); EXPORT void jlScanLbidReqLimit(); @@ -286,7 +304,7 @@ namespace joblist EXPORT void psCount(); EXPORT void psConnectionsPerPrimProc() ; - EXPORT void psLBID_Shift(); + EXPORT void psLBID_Shift(); EXPORT void scTempDiskPath(); EXPORT void scTempSaveSize() ; @@ -302,35 +320,29 @@ namespace joblist EXPORT void hbrPredicate(); - void setTraceFlags(uint32_t flags) - { - fTraceFlags = flags; + void setTraceFlags(uint32_t flags) + { + fTraceFlags = flags; fHJUmMaxMemorySmallSideDistributor.setTrace(((fTraceFlags & execplan::CalpontSelectExecutionPlan::TRACE_RESRCMGR) != 0)); } bool rmtraceOn() const { return ((fTraceFlags & execplan::CalpontSelectExecutionPlan::TRACE_RESRCMGR) != 0); } void numCores(unsigned numCores) { fNumCores = numCores; } unsigned numCores() const { return fNumCores; } - - void aggNumThreads(uint32_t numThreads) { fAggNumThreads = numThreads; } - uint32_t aggNumThreads() const { return fAggNumThreads; } - - void aggNumBuckets(uint32_t numBuckets) { fAggNumBuckets = numBuckets; } - uint32_t aggNumBuckets() const { return fAggNumBuckets; } - - void aggNumRowGroups(uint32_t numRowGroups) { fAggNumRowGroups = numRowGroups; } - uint32_t aggNumRowGroups() const { return fAggNumRowGroups; } - - void windowFunctionThreads(uint32_t n) { fWindowFunctionThreads = n; } - uint32_t windowFunctionThreads() const { return fWindowFunctionThreads; } - - bool useHdfs() const { return fUseHdfs; } + + void aggNumThreads(uint numThreads) { fAggNumThreads = numThreads; } + uint aggNumThreads() const { return fAggNumThreads; } + + void aggNumBuckets(uint numBuckets) { fAggNumBuckets = numBuckets; } + uint aggNumBuckets() const { return fAggNumBuckets; } + + void aggNumRowGroups(uint numRowGroups) { fAggNumRowGroups = numRowGroups; } + uint aggNumRowGroups() const { return fAggNumRowGroups; } EXPORT bool getMysqldInfo(std::string& h, std::string& u, std::string& w, unsigned int& p) const; EXPORT bool queryStatsEnabled() const; EXPORT bool userPriorityEnabled() const; - uint64_t getConfiguredUMMemLimit() const { return configuredUmMemLimit; } private: void logResourceChangeMessage(logging::LOG_TYPE logType, uint32_t sessionID, uint64_t newvalue, uint64_t value, const std::string& source, logging::Message::MessageID mid); @@ -365,7 +377,7 @@ namespace joblist static const std::string fOrderByLimitStr; config::Config* fConfig; - uint32_t fTraceFlags; + uint32_t fTraceFlags; unsigned fNumCores; unsigned fHjNumThreads; @@ -378,21 +390,19 @@ namespace joblist LockedSessionMap fHJPmMaxMemorySmallSideSessionMap; /* new HJ/Union/Aggregation support */ - volatile int64_t totalUmMemLimit; // mem limit for join, union, and aggregation on the UM - uint64_t configuredUmMemLimit; +#ifdef _MSC_VER + volatile LONGLONG totalUmMemLimit; +#else + int64_t totalUmMemLimit; // mem limit for join, union, and aggregation on the UM +#endif uint64_t pmJoinMemLimit; // mem limit on individual PM joins /* multi-thread aggregate */ - uint32_t fAggNumThreads; - uint32_t fAggNumBuckets; - uint32_t fAggNumRowGroups; - - // window function - uint32_t fWindowFunctionThreads; - + uint fAggNumThreads; + uint fAggNumBuckets; + uint fAggNumRowGroups; bool isExeMgr; - bool fUseHdfs; }; @@ -405,7 +415,7 @@ namespace joblist return (0 == val.length() ? defval : val); } - template + template inline IntType ResourceManager::getUintVal(const std::string& section, const std::string& name, IntType defval) const { IntType val = fConfig->uFromText(fConfig->getConfig(section, name)); @@ -416,7 +426,7 @@ namespace joblist } - template + template inline IntType ResourceManager::getIntVal(const std::string& section, const std::string& name, IntType defval) const { std::string retStr = fConfig->getConfig(section, name); diff --git a/dbcon/joblist/rowestimator.cpp b/dbcon/joblist/rowestimator.cpp index 3fbffa72..675102eb 100644 --- a/dbcon/joblist/rowestimator.cpp +++ b/dbcon/joblist/rowestimator.cpp @@ -49,7 +49,7 @@ namespace joblist // This is used for converting a Calpont date to an integer representing the day number since the year 0 for use in // calculating the number of distinct days in a range. It doesn't account for leap years as these are rough estimates // and only need to be accurate within an order of magnitude. -uint32_t RowEstimator::daysThroughMonth(uint32_t mth) +uint RowEstimator::daysThroughMonth(uint mth) { switch(mth) { @@ -91,36 +91,36 @@ uint64_t RowEstimator::adjustValue(const execplan::CalpontSystemCatalog::ColType { // Use day precision for dates. We'll use day relative to the year 0 without worrying about leap // years. This is for row count estimation and we are close enough for hand grenades. - case CalpontSystemCatalog::DATE: + case WriteEngine::DATE: { dataconvert::Date dt(value); return dt.year * 365 + daysThroughMonth(dt.month - 1) + dt.day; - } + } // Use second precision for datetime estimates. We'll use number of seconds since the year 0 // without worrying about leap years. - case CalpontSystemCatalog::DATETIME: + case WriteEngine::DATETIME: { dataconvert::DateTime dtm(value); // 86,400 seconds in a day. - return (dtm.year * 365 + daysThroughMonth(dtm.month - 1) + dtm.day - 1) * 86400 + + return (dtm.year * 365 + daysThroughMonth(dtm.month - 1) + dtm.day - 1) * 86400 + dtm.hour * 3600 + dtm.minute * 60 + dtm.second; } // Use the first character only for estimating chars and varchar ranges. // TODO: Use dictionary column HWM for dictionary columns. - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: // Last byte is the first character in the string. - return (0xFF & value); + return (0xFF & value); default: return value; } } -// Estimates the number of distinct values given a min/max range. When the range has not been set, -// rules from the requirements are used based on the column type. -uint32_t RowEstimator::estimateDistinctValues(const execplan::CalpontSystemCatalog::ColType& ct, +// Estimates the number of distinct values given a min / max range. When the range has not been set, rules from +// the requirements are used based on the column type. +uint32_t RowEstimator::estimateDistinctValues(const execplan::CalpontSystemCatalog::ColType& ct, const uint64_t& min, const uint64_t& max, const char cpStatus) @@ -133,35 +133,26 @@ uint32_t RowEstimator::estimateDistinctValues(const execplan::CalpontSystemCatal switch(ct.colDataType) { - case CalpontSystemCatalog::BIT: + case WriteEngine::BIT: return 2; // Return limit/2 for integers where limit is number of possible values. - case CalpontSystemCatalog::TINYINT: - return (2^8)/2; - case CalpontSystemCatalog::UTINYINT: - return (2^8); - case CalpontSystemCatalog::SMALLINT: - return (2^16)/2; - case CalpontSystemCatalog::USMALLINT: - return (2^16); + case WriteEngine::TINYINT: + return (2^8)/2; + case WriteEngine::SMALLINT: + return (2^16)/2; // Next group all have range greater than 8M (# of rows in an extent), use 8M/2 as the estimate. - case CalpontSystemCatalog::MEDINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: + case WriteEngine::MEDINT: + case WriteEngine::INT: + case WriteEngine::BIGINT: + case WriteEngine::FLOAT: + case WriteEngine::DOUBLE: return fRowsPerExtent / 2; // Use 1000 for dates. - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return 1000; // Use 10 for CHARs and VARCHARs. We'll use 10 for whatever else. @@ -172,22 +163,21 @@ uint32_t RowEstimator::estimateDistinctValues(const execplan::CalpontSystemCatal } else { - ret = max - min + 1; + ret = max - min + 1; } if(ret > fRowsPerExtent) { - ret = fRowsPerExtent; + ret = fRowsPerExtent; } return ret; } // Returns a floating point number between 0 and 1 representing the percentage of matching rows for the given predicate against // the given range. This function is used for estimating an individual operation such as col1 = 2. -template -float RowEstimator::estimateOpFactor(const T& min, const T& max, const T& value, char op, uint8_t lcf, uint32_t distinctValues, char cpStatus) +float RowEstimator::estimateOpFactor(const int64_t& min, const int64_t& max, const int64_t& value, char op, uint8_t lcf, uint32_t distinctValues, char cpStatus) { float factor = 1.0; - switch(op) + switch(op) { case COMPARE_LT: case COMPARE_NGE: @@ -201,7 +191,7 @@ float RowEstimator::estimateOpFactor(const T& min, const T& max, const T& value, if(cpStatus == BRM::CP_VALID) { factor = (1.0 * value - min + 1) / (max - min + 1); - } + } break; case COMPARE_GT: case COMPARE_NLE: @@ -225,7 +215,7 @@ float RowEstimator::estimateOpFactor(const T& min, const T& max, const T& value, factor = 1.0 - (1.0 / distinctValues); break; } - if(factor < 0.0) + if(factor < 0.0) { factor = 0.0; } @@ -245,15 +235,13 @@ float RowEstimator::estimateRowReturnFactor(const BRM::EMEntry& emEntry, const uint8_t BOP, const uint32_t& rowsInExtent) { - bool bIsUnsigned = execplan::isUnsigned(ct.colDataType); float factor = 1.0; float tempFactor = 1.0; - // Adjust values based on column type and estimate the + // Adjust values based on column type and estimate the uint64_t adjustedMin = adjustValue(ct, emEntry.partition.cprange.lo_val); uint64_t adjustedMax = adjustValue(ct, emEntry.partition.cprange.hi_val); - uint32_t distinctValuesEstimate = estimateDistinctValues( - ct, adjustedMin, adjustedMax, emEntry.partition.cprange.isValid); + uint32_t distinctValuesEstimate = estimateDistinctValues(ct, adjustedMin, adjustedMax, emEntry.partition.cprange.isValid); // Loop through the operations and estimate the percentage of rows that will qualify. // For example, there are two operations for "col1 > 5 and col1 < 10": @@ -267,8 +255,7 @@ float RowEstimator::estimateRowReturnFactor(const BRM::EMEntry& emEntry, for (int i = 0; i < comparisonLimit; i++) { pos += ct.colWidth + 2; // predicate + op + lcf - // TODO: Stole this condition from lbidlist. - // Investigate whether this can happen / should throw an error. + // TODO: Stole this condition from lbidlist. Investigate whether this can happen / should throw an error. if (pos > length) { return factor; } @@ -276,68 +263,34 @@ float RowEstimator::estimateRowReturnFactor(const BRM::EMEntry& emEntry, // Get the comparison value for the condition. char op = *msgDataPtr++; uint8_t lcf = *(uint8_t*)msgDataPtr++; - if (bIsUnsigned) - { - switch (ct.colWidth) - { - case 1: - { - uint8_t val = *(uint8_t*)msgDataPtr; - value = val; - break; - } - case 2: - { - uint16_t val = *(uint16_t*)msgDataPtr; - value = val; - break; - } - case 4: - { - uint32_t val = *(uint32_t*)msgDataPtr; - value = val; - break; - } - case 8: - default: - { - uint64_t val = *(uint64_t*)msgDataPtr; - value = static_cast(val); - break; - } - } - } - else - { - switch (ct.colWidth) - { - case 1: - { - int8_t val = *(int8_t*)msgDataPtr; - value = val; - break; - } - case 2: - { - int16_t val = *(int16_t*)msgDataPtr; - value = val; - break; - } - case 4: - { - int32_t val = *(int32_t*)msgDataPtr; - value = val; - break; - } - case 8: - default: - { - int64_t val = *(int64_t*)msgDataPtr; - value = val; - break; - } - } - } + switch (ct.colWidth) + { + case 1: + { + int8_t val = *(int8_t*)msgDataPtr; + value = val; + break; + } + case 2: + { + int16_t val = *(int16_t*)msgDataPtr; + value = val; + break; + } + case 4: + { + int32_t val = *(int32_t*)msgDataPtr; + value = val; + break; + } + case 8: + default: + { + int64_t val = *(int64_t*)msgDataPtr; + value = val; + break; + } + } // TODO: Investigate whether condition below should throw an error. msgDataPtr += ct.colWidth; @@ -352,18 +305,8 @@ float RowEstimator::estimateRowReturnFactor(const BRM::EMEntry& emEntry, #endif // Get the factor for the individual operation. - if (bIsUnsigned) - { - tempFactor = estimateOpFactor( - adjustedMin, adjustedMax, adjustValue(ct, value), op, lcf, - distinctValuesEstimate, emEntry.partition.cprange.isValid); - } - else - { - tempFactor = estimateOpFactor( - adjustedMin, adjustedMax, adjustValue(ct, value), op, lcf, - distinctValuesEstimate, emEntry.partition.cprange.isValid); - } + tempFactor = estimateOpFactor(adjustedMin, adjustedMax, adjustValue(ct, value), op, lcf, + distinctValuesEstimate, emEntry.partition.cprange.isValid); #if ROW_EST_DEBUG cout << ", OperatorFactor-" << tempFactor << ", DistinctValsEst-" << distinctValuesEstimate << endl; @@ -373,7 +316,7 @@ float RowEstimator::estimateRowReturnFactor(const BRM::EMEntry& emEntry, if (BOP == BOP_AND) { // TODO: Handle betweens correctly (same as a >= 5 and a <= 10) factor *= tempFactor; - } + } else if (BOP == BOP_OR) { if (firstQualifyingOrCondition) { factor = tempFactor; @@ -403,7 +346,7 @@ float RowEstimator::estimateRowReturnFactor(const BRM::EMEntry& emEntry, // This function returns the estimated row count for the entire TupleBPS. It samples the last 20 (configurable) extents to // calculate the estimate. -uint64_t RowEstimator::estimateRows(const vector& cpColVec, +uint64_t RowEstimator::estimateRows(const vector& cpColVec, const std::vector& scanFlags, BRM::DBRM& dbrm, const execplan::CalpontSystemCatalog::OID oid) @@ -455,7 +398,7 @@ uint64_t RowEstimator::estimateRows(const vector& cpColVec, cout << "Ext-" << idx << ", rowsToScan-" << extentRows << endl; #endif factor = 1.0; - for (uint32_t j = 0; j < cpColVec.size(); j++) + for (uint j = 0; j < cpColVec.size(); j++) { colCmd = cpColVec[j]; //RowEstimator rowEstimator; @@ -496,8 +439,8 @@ uint64_t RowEstimator::estimateRows(const vector& cpColVec, } } - // If there are more extents than we sampled, add the row counts for the qualifying extents - // that we didn't sample to the count of rows that will be scanned. + // If there are more extents than we sampled, add the row counts for the qualifying extents that we didn't sample + // to the count of rows that will be scanned. if((extentsSampled >= fExtentsToSample) && (idx > 0)) { factor = (1.0 * estimatedRowCount) / (1.0 * totalRowsToBeScanned); @@ -508,10 +451,10 @@ uint64_t RowEstimator::estimateRows(const vector& cpColVec, { if(scanFlags[i]) { - // Don't take the expense of checking to see if the last extent was one that wasn't - // sampled. It will more than likely have been the first extent sampled since we - // are doing them in reverse order. If not, the amount of rows not populated isn't - // that significant since there are many qualifying extents. + // Don't take the expense of checking to see if the last extent was one that wasn't sampled. + // It will more than likely have been the first extent sampled since we are doing them in + // reverse order. If not, the amount of rows not populated isn't that significant since there + // are many qualifying extents. totalRowsToBeScanned += fRowsPerExtent; } } @@ -526,9 +469,8 @@ uint64_t RowEstimator::estimateRows(const vector& cpColVec, return estimatedRowCount; } -// @Bug 3503. Fix to use the number of extents to estimate the number of rows in queries that do -// joins on dictionaries or other column types that do not use casual partitioning. -// We use an estimate of 100% of the rows regardless of any dictionary filters. +// @Bug 3503. Fix to use the number of extents to estimate the number of rows in queries that do joins on dictionaries or other column types +// that do not use casual partitioning. We use an estimate of 100% of the rows regardless of any dictionary filters. uint64_t RowEstimator::estimateRowsForNonCPColumn(ColumnCommandJL& colCmd) { uint64_t estimatedRows = 0; @@ -536,8 +478,7 @@ uint64_t RowEstimator::estimateRowsForNonCPColumn(ColumnCommandJL& colCmd) if (numExtents > 0) { HWM_t hwm = colCmd.getExtents()[numExtents - 1].HWM; - uint32_t rowsInLastExtent = - ((hwm+1) * fBlockSize/ colCmd.getColType().colWidth)%fRowsPerExtent; + uint32_t rowsInLastExtent = ((hwm+1) * fBlockSize/ colCmd.getColType().colWidth)%fRowsPerExtent; estimatedRows = fRowsPerExtent * (numExtents - 1) + rowsInLastExtent; } return estimatedRows; diff --git a/dbcon/joblist/rowestimator.h b/dbcon/joblist/rowestimator.h index b6d03524..b4da8eb5 100644 --- a/dbcon/joblist/rowestimator.h +++ b/dbcon/joblist/rowestimator.h @@ -35,8 +35,8 @@ #include #include "brm.h" -namespace joblist -{ +namespace joblist +{ /** @brief estimates row counts for a TupleBPS. * @@ -54,40 +54,39 @@ class RowEstimator /** @brief estimate the number of rows that will be returned for a particular tuple batch primitive step. * * @param cpColVec vector of ColumnCommandJL pointers associated to the step. - * @param scanFlags vector of flags with one entry per extent populated by the casual - * partitioning evaluation, each that will be scanned are true, the ones that - * were eliminated by casual partitioining are false. + * @param scanFlags vector of flags with one entry per extent populated by the casual partitioning evaluation, each + * that will be scanned are true, the ones that were eliminated by casual partitioining are false. * @param dbrm DBRM object used to get the HWM. * @parm oid The objectid for the first column in the step. - * + * */ - uint64_t estimateRows(const std::vector& cpColVec, + uint64_t estimateRows(const std::vector& cpColVec, const std::vector & scanFlags, BRM::DBRM& dbrm, const execplan::CalpontSystemCatalog::OID oid); - /** @brief Estimate the number of rows that will be returned for a particular table given - * a ColumnCommandJL for non casual partitioning column. Added for bug 3503. + /** @brief Estimate the number of rows that will be returned for a particular table given a ColumnCommandJL for non + * casual partitioning column. Added for bug 3503. * * @param colCmd The ColumnCommandJL. - * + * */ uint64_t estimateRowsForNonCPColumn(ColumnCommandJL& colCmd); private: - /** @brief adjusts column values so that they can be compared via ranges. + /** @brief adjusts column values so that they can be compared via ranges. * * This function provides a value for dates, datetimes, and strings that can be used for distinct value estimation and * comparisons. * * @param ct The column type. * @param value The column value. - * + * */ uint64_t adjustValue(const execplan::CalpontSystemCatalog::ColType& ct, const uint64_t& value); - uint32_t daysThroughMonth(uint32_t mth); + uint daysThroughMonth(uint mth); uint32_t estimateDistinctValues(const execplan::CalpontSystemCatalog::ColType& ct, const uint64_t& min, @@ -104,15 +103,13 @@ class RowEstimator * @parm cpStatus The status of the CP data (whether it's valid). * */ - template - float estimateOpFactor(const T& min, const T& max, const T& value, char op, uint8_t lcf, - uint32_t distinctValues, char cpStatus); + float estimateOpFactor(const int64_t& min, const int64_t& max, const int64_t& value, char op, uint8_t lcf, + uint32_t distinctValues, char cpStatus); - /** @brief returns a factor between 0 and 1 for the estimate of rows that will qualify - * the given operation(s). + /** @brief returns a factor between 0 and 1 for the estimate of rows that will qualify the given operation(s). * - * This function works for multiple operations against the same column such as - * "col1 = 5 or col1 = 10". It calls estimateOpFactor for each individual operation. + * This function works for multiple operations against the same column such as "col1 = 5 or col1 = 10". It + * calls estimateOpFactor for each individual operation. * * @param emEntry The extent map entry for the extent being evaluated. * @param msgDataPtr The filter string. @@ -129,21 +126,21 @@ class RowEstimator const uint32_t& rowsInExtent); // Configurables read from Calpont.xml - future. - uint32_t fExtentsToSample; - uint32_t fIntDistinctAdjust; - uint32_t fDecDistinctAdjust; - uint32_t fChar1DistinctAdjust; - uint32_t fChar2Thru7DistinctAdjust; - uint32_t fDictDistinctAdjust; - uint32_t fDateDistinctAdjust; - - static const uint32_t fRowsPerExtent = 8192 * 1024; + uint fExtentsToSample; + uint fIntDistinctAdjust; + uint fDecDistinctAdjust; + uint fChar1DistinctAdjust; + uint fChar2Thru7DistinctAdjust; + uint fDictDistinctAdjust; + uint fDateDistinctAdjust; + + static const uint32_t fRowsPerExtent = 8192 * 1024; static const uint32_t fBlockSize = 8192; // Block size in bytes. // Limits the number of comparisons for each extent. Example, in clause w/ 1000 values will limit the checks to // the number below. static const uint32_t fMaxComparisons = 10; - + }; // RowEstimator diff --git a/dbcon/joblist/rtscommand-jl.cpp b/dbcon/joblist/rtscommand-jl.cpp index c09f6a0c..8aa5a52b 100644 --- a/dbcon/joblist/rtscommand-jl.cpp +++ b/dbcon/joblist/rtscommand-jl.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: rtscommand-jl.cpp 9655 2013-06-25 23:08:13Z xlou $ +// $Id: rtscommand-jl.cpp 8476 2012-04-25 22:28:15Z xlou $ // C++ Implementation: rtscommand-jl // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -66,7 +66,7 @@ RTSCommandJL::~RTSCommandJL() { } -void RTSCommandJL::setLBID(uint64_t data, uint32_t dbroot) +void RTSCommandJL::setLBID(uint64_t data, uint dbroot) { if (!passThru) col->setLBID(data, dbroot); @@ -87,7 +87,7 @@ void RTSCommandJL::runCommand(ByteStream &bs) const { if (!passThru) col->runCommand(bs); - dict->runCommand(bs); + dict->runCommand(bs); } uint8_t RTSCommandJL::getTableColumnType() diff --git a/dbcon/joblist/rtscommand-jl.h b/dbcon/joblist/rtscommand-jl.h index 30704057..b9ff55e0 100644 --- a/dbcon/joblist/rtscommand-jl.h +++ b/dbcon/joblist/rtscommand-jl.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: rtscommand-jl.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: rtscommand-jl.h 8436 2012-04-04 18:18:21Z rdempsey $ // C++ Interface: ridtostringcommand-jl // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -46,7 +46,7 @@ class RTSCommandJL : public CommandJL RTSCommandJL(const PassThruStep &, const pDictionaryStep &); virtual ~RTSCommandJL(); - void setLBID(uint64_t data, uint32_t dbroot); // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. + void setLBID(uint64_t data, uint dbroot); // converts a rid or dictionary token to an LBID. For ColumnCommandJL it's a RID, for a DictStep it's a token. uint8_t getTableColumnType(); std::string toString(); bool isPassThru() { return (passThru != 0); } diff --git a/dbcon/joblist/stopwatch.cpp b/dbcon/joblist/stopwatch.cpp new file mode 100644 index 00000000..5ac6c309 --- /dev/null +++ b/dbcon/joblist/stopwatch.cpp @@ -0,0 +1,211 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// +// $Id: stopwatch.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +// +// Timer class used to spit out times and percentages. Temporarily lives in joblist. +// This is strictly a debugging utility class that accumulates times between .start() and +// .stop() calls for a particular string. It can be useful in tdrivers. +// +// It outputs a report when finish() is called with +// the total times by string and their percentage of the total. The total is tracked from +// the first time start() is called until finish() is called. You should always match your +// start and stop calls up. +// +// This works fine as long as you don't use it with huge numbers of calls. If you call start +// and stop too many times the overhead of the Stopwatch class will start factoring in to your +// results. +// +// How to use: +// +// Stopwatch timer; +// timer.start("Loop only"); +// for(int i = 0; i < 6999075; i++) +// { +// } +// timer.stop("Loop only"); +// +// timer.start("Loop Plus"); +// for(int i = 0; i < 100000; i++) +// { +// timer.start("Inside loop"); +// timer.stop("Inside loop"); +// } +// timer.stop("Loop Plus"); +// timer.finish(); +// +// Produces this: +// +// Seconds Percentage Calls Description +// 0.02865 9.377% 1 Loop only +// 0.27680 90.59% 1 Loop Plus +// 0.12138 39.72% 100000 Inside loop +// +// 0.30553 100 % 1 Total +// +// Note that you can have overlapping timers which will make your percentages add up to more than 100%. + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +class Stopwatch { + public: + void start(const string& message); + void stop(const string& message); + void finish() { + + // Calculate the total seconds elapsed. + struct timeval tvStop; + gettimeofday(&tvStop, 0); + double totalSeconds = + (tvStop.tv_sec + (tvStop.tv_usec / 1000000.0)) - + (fTvStart.tv_sec + (fTvStart.tv_usec / 1000000.0)); + + profLog << endl; + profLog << "Seconds Percentage Calls Description" << endl; + + // Add a last entry into the vector for total. + ProcessStats total; + total.fTotalSeconds = totalSeconds; + total.fProcess = "Total"; + total.fStartCount = 1; + fProcessStats.push_back(total); + + for(uint i = 0; i < fProcessStats.size(); i++) { + + if(i == (fProcessStats.size() - 1)) { + profLog << endl; + } + + // Seconds. + string seconds; + ostringstream oss; + oss << fProcessStats[i].fTotalSeconds; + seconds = oss.str(); + seconds.resize(11, ' '); + profLog << seconds << " "; + + // Percentage. + string percentage; + ostringstream oss2; + oss2 << (fProcessStats[i].fTotalSeconds / totalSeconds) * 100.0; + percentage = oss2.str(); + percentage.resize(5, ' '); + profLog << percentage << "% "; + + // Times Initiated. + ostringstream oss3; + oss3 << fProcessStats[i].fStartCount; + string timesInitiated = oss3.str(); + timesInitiated.resize(10, ' '); + profLog << timesInitiated << " "; + + // Description. + profLog << fProcessStats[i].fProcess << endl; + } + + // Clear everything out. + fStarted = false; + fProcessStats.clear(); + + } + Stopwatch() : fStarted(false) {profLog.open("prof.log", std::ios::app);}; + + private: + class ProcessStats + { + public: + + string fProcess; + struct timeval fTvProcessStarted; + double fTotalSeconds; + long fStartCount; + long fStopCount; + + ProcessStats() : fProcess(""), fTotalSeconds(0.0), fStartCount(0), fStopCount(0) {}; + + void processStart() + { + gettimeofday(&fTvProcessStarted, 0); + fStartCount++; + } + + void processStop() + { + struct timeval tvStop; + gettimeofday(&tvStop, 0); + fStopCount++; + fTotalSeconds += + (tvStop.tv_sec + (tvStop.tv_usec / 1000000.0)) - + (fTvProcessStarted.tv_sec + (fTvProcessStarted.tv_usec / 1000000.0)); + + } + }; + + struct timeval fTvStart; + vector fProcessStats; + bool fStarted; + ofstream profLog; +}; + +void Stopwatch::stop(const string& message) { + bool found = false; + uint idx = 0; + for(uint i = 0; i < fProcessStats.size(); i++) { + if(fProcessStats[i].fProcess == message) { + idx = i; + found = true; + break; + } + } + if(!found) { + throw std::runtime_error("Stopwatch::stop " + message + " called without calling start first."); + } + fProcessStats[idx].processStop(); +} + +void Stopwatch::start(const string& message) { + bool found = false; + uint idx = 0; + ProcessStats processStats; + if(!fStarted) { + fStarted = true; + gettimeofday(&fTvStart, 0); + } + for(uint i = 0; i < fProcessStats.size(); i++) { + if(fProcessStats[i].fProcess == message) { + idx = i; + found = true; + break; + } + } + if(!found) { + fProcessStats.push_back(processStats); + idx = fProcessStats.size() - 1; + } + fProcessStats[idx].fProcess = message; + fProcessStats[idx].processStart(); +} diff --git a/dbcon/joblist/subquerystep.cpp b/dbcon/joblist/subquerystep.cpp index fa3c6bfc..5a1d633d 100644 --- a/dbcon/joblist/subquerystep.cpp +++ b/dbcon/joblist/subquerystep.cpp @@ -28,7 +28,6 @@ using namespace std; #include #include #include -#include using namespace boost; #include "parsetree.h" @@ -42,9 +41,6 @@ using namespace rowgroup; #include "exceptclasses.h" using namespace logging; -#include "querytele.h" -using namespace querytele; - #include "funcexp.h" #include "jobstep.h" @@ -58,12 +54,17 @@ using namespace joblist; namespace joblist { -SubQueryStep::SubQueryStep(const JobInfo& jobInfo) - : JobStep(jobInfo) - , fRowsReturned(0) +SubQueryStep::SubQueryStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t statementId) : + fSessionId(sessionId), + fTxnId(txnId), + fStepId(0), + fStatementId(statementId), + fRowsReturned(0) { fExtendedInfo = "SQS: "; - fQtc.stepParms().stepType = StepTeleStats::T_SQS; } SubQueryStep::~SubQueryStep() @@ -116,7 +117,7 @@ void SubQueryStep::printCalTrace() << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); @@ -141,13 +142,16 @@ void SubQueryStep::formatMiniStats() */ -SubAdapterStep::SubAdapterStep(SJSTEP& s, const JobInfo& jobInfo) - : JobStep(jobInfo) +SubAdapterStep::SubAdapterStep(uint32_t sessionId, uint32_t txnId, uint32_t statementId, SJSTEP& s) + : fSessionId(sessionId) + , fTxnId(txnId) + , fStepId(0) + , fStatementId(statementId) , fTableOid(s->tableOid()) , fSubStep(s) - , fRowsInput(0) , fRowsReturned(0) , fEndOfResult(false) + , fDelivery(false) , fInputIterator(0) , fOutputIterator(0) { @@ -173,7 +177,7 @@ void SubAdapterStep::abort() void SubAdapterStep::run() { if (fInputJobStepAssociation.outSize() == 0) - throw logic_error("No input data list for subquery adapter step."); + throw logic_error("No input data list for constant step."); fInputDL = fInputJobStepAssociation.outAt(0)->rowGroupDL(); if (fInputDL == NULL) @@ -202,56 +206,56 @@ void SubAdapterStep::join() } -uint32_t SubAdapterStep::nextBand(messageqcpp::ByteStream &bs) +uint SubAdapterStep::nextBand(messageqcpp::ByteStream &bs) { - RGData rgDataOut; + shared_array rgDataOut; bool more = false; - uint32_t rowCount = 0; + uint rowCount = 0; try { bs.restart(); more = fOutputDL->next(fOutputIterator, &rgDataOut); - if (!more || cancelled()) + if (!more || (0 < fOutputJobStepAssociation.status() || die)) { //@bug4459. - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } if (more && !fEndOfResult) { - fRowGroupDeliver.setData(&rgDataOut); - fRowGroupDeliver.serializeRGData(bs); + fRowGroupDeliver.setData(rgDataOut.get()); + bs.load(rgDataOut.get(), fRowGroupDeliver.getDataSize()); rowCount = fRowGroupDeliver.getRowCount(); } } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_IN_DELIVERY, fErrorInfo, fSessionId); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } catch(...) { - catchHandler("SubAdapterStep next band caught an unknown exception", - ERR_IN_DELIVERY, fErrorInfo, fSessionId); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + catchHandler("TupleConstantStep next band caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } if (fEndOfResult) { // send an empty / error band - RGData rgData(fRowGroupDeliver, 0); - fRowGroupDeliver.setData(&rgData); + shared_array rgData(new uint8_t[fRowGroupDeliver.getEmptySize()]); + fRowGroupDeliver.setData(rgData.get()); fRowGroupDeliver.resetRowGroup(0); - fRowGroupDeliver.setStatus(status()); - fRowGroupDeliver.serializeRGData(bs); + fRowGroupDeliver.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgData.get(), fRowGroupDeliver.getDataSize()); } return rowCount; @@ -267,7 +271,7 @@ void SubAdapterStep::setFeRowGroup(const rowgroup::RowGroup& rg) void SubAdapterStep::setOutputRowGroup(const rowgroup::RowGroup& rg) { fRowGroupOut = fRowGroupDeliver = rg; - if (fRowGroupFe.getColumnCount() == 0) + if (fRowGroupFe.getColumnCount() == (uint) -1) fIndexMap = makeMapping(fRowGroupIn, fRowGroupOut); else fIndexMap = makeMapping(fRowGroupFe, fRowGroupOut); @@ -278,12 +282,12 @@ void SubAdapterStep::setOutputRowGroup(const rowgroup::RowGroup& rg) void SubAdapterStep::checkDupOutputColumns() { - map keymap; // map + map keymap; // map fDupColumns.clear(); - const vector& keys = fRowGroupDeliver.getKeys(); - for (uint32_t i = 0; i < keys.size(); i++) + const vector& keys = fRowGroupDeliver.getKeys(); + for (uint i = 0; i < keys.size(); i++) { - map::iterator j = keymap.find(keys[i]); + map::iterator j = keymap.find(keys[i]); if (j == keymap.end()) keymap.insert(make_pair(keys[i], i)); // map key to col index else @@ -311,20 +315,6 @@ void SubAdapterStep::outputRow(Row& rowIn, Row& rowOut) } -void SubAdapterStep::deliverStringTableRowGroup(bool b) -{ - fRowGroupOut.setUseStringTable(b); - fRowGroupDeliver.setUseStringTable(b); -} - - -bool SubAdapterStep::deliverStringTableRowGroup() const -{ - idbassert(fRowGroupOut.usesStringTable() == fRowGroupDeliver.usesStringTable()); - return fRowGroupDeliver.usesStringTable(); -} - - const string SubAdapterStep::toString() const { ostringstream oss; @@ -342,51 +332,44 @@ const string SubAdapterStep::toString() const void SubAdapterStep::execute() { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; Row rowIn; Row rowFe; Row rowOut; fRowGroupIn.initRow(&rowIn); fRowGroupOut.initRow(&rowOut); - RGData rowFeData; - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - bool usesFE = false; - if (fRowGroupFe.getColumnCount() > 0) + scoped_array rowFeData; + if (fRowGroupFe.getColumnCount() != (uint) -1) { - usesFE = true; - fRowGroupFe.initRow(&rowFe, true); - rowFeData = RGData(fRowGroupFe, 1); - fRowGroupFe.setData(&rowFeData); - fRowGroupFe.getRow(0, &rowFe); + fRowGroupFe.initRow(&rowFe); + rowFeData.reset(new uint8_t[rowFe.getSize()]); + rowFe.setData(rowFeData.get()); } bool more = false; try { - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - fSubStep->run(); more = fInputDL->next(fInputIterator, &rgDataIn); if (traceOn()) dlTimes.setFirstReadTime(); - while (more && !cancelled()) + while (more && 0 == fInputJobStepAssociation.status() && !die) { - fRowGroupIn.setData(&rgDataIn); - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); - fRowGroupOut.resetRowGroup(fRowGroupIn.getBaseRid()); + fRowGroupIn.setData(rgDataIn.get()); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); +#ifdef VALGRIND + /* As of 1/21/14, some columns are left uninitialized. Valgrind doesn't like that. + Nothing seems broken, this would be a minor optimization opportunity. */ + memset(rgDataOut.get(), 0, fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())); +#endif + fRowGroupOut.setData(rgDataOut.get()); fRowGroupIn.getRow(0, &rowIn); fRowGroupOut.getRow(0, &rowOut); - - fRowsInput += fRowGroupIn.getRowCount(); + fRowGroupOut.resetRowGroup(fRowGroupIn.getBaseRid()); for (uint64_t i = 0; i < fRowGroupIn.getRowCount(); ++i) { @@ -394,7 +377,7 @@ void SubAdapterStep::execute() { outputRow(rowIn, rowOut); } - else if (!usesFE) + else if (rowFeData.get() == NULL) { if(fExpression->evaluate(&rowIn)) { @@ -403,8 +386,7 @@ void SubAdapterStep::execute() } else { - copyRow(rowIn, &rowFe, rowIn.getColumnCount()); - //memcpy(rowFe.getData(), rowIn.getData(), rowIn.getSize()); + memcpy(rowFe.getData(), rowIn.getData(), rowIn.getSize()); if(fExpression->evaluate(&rowFe)) { outputRow(rowFe, rowOut); @@ -421,21 +403,24 @@ void SubAdapterStep::execute() } more = fInputDL->next(fInputIterator, &rgDataIn); + } } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_EXEMGR_MALFUNCTION, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_EXEMGR_MALFUNCTION); } catch(...) { - catchHandler("SubAdapterStep execute caught an unknown exception", - ERR_EXEMGR_MALFUNCTION, fErrorInfo, fSessionId); + catchHandler("SubAdapterStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_EXEMGR_MALFUNCTION); } - if (cancelled()) - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + if (fOutputJobStepAssociation.status() > 0 || die) + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); if (traceOn()) { @@ -444,11 +429,6 @@ void SubAdapterStep::execute() printCalTrace(); } - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - // Bug 3136, let mini stats to be formatted if traceOn. fOutputDL->endOfInput(); } @@ -457,8 +437,8 @@ void SubAdapterStep::execute() void SubAdapterStep::addExpression(const JobStepVector& exps, JobInfo& jobInfo) { // maps key to the index in the RG - map keyToIndexMap; - const vector& keys = fRowGroupIn.getKeys(); + map keyToIndexMap; + const vector& keys = fRowGroupIn.getKeys(); for (size_t i = 0; i < keys.size(); i++) keyToIndexMap[keys[i]] = i; @@ -489,7 +469,7 @@ void SubAdapterStep::addExpression(const JobStepVector& exps, JobInfo& jobInfo) // add to the expression wrapper if (fExpression.get() == NULL) fExpression.reset(new funcexp::FuncExpWrapper()); - fExpression->addFilter(boost::shared_ptr(filter)); + fExpression->addFilter(shared_ptr(filter)); } @@ -504,12 +484,6 @@ void SubAdapterStep::addExpression(const vector& exps) } -void SubAdapterStep::addFcnJoinExp(const vector& exps) -{ - addExpression(exps); -} - - void SubAdapterStep::printCalTrace() { time_t t = time (0); @@ -518,13 +492,11 @@ void SubAdapterStep::printCalTrace() timeString[strlen (timeString )-1] = '\0'; ostringstream logStr; logStr << "ses:" << fSessionId << " st: " << fStepId << " finished at "<< timeString - << "; total rows input-" << fRowsInput << "; total rows returned-" << fRowsReturned << endl << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); diff --git a/dbcon/joblist/subquerystep.h b/dbcon/joblist/subquerystep.h index 4455e591..f939d22e 100644 --- a/dbcon/joblist/subquerystep.h +++ b/dbcon/joblist/subquerystep.h @@ -41,8 +41,14 @@ class SubQueryStep : public JobStep public: /** @brief SubQueryStep constructor + * @param sessionId the session Id + * @param txnId the transaction Id + * @param statementId the statement Id */ - SubQueryStep(const JobInfo&); + SubQueryStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t statementId); /** @brief SubQueryStep destructor */ @@ -55,10 +61,62 @@ class SubQueryStep : public JobStep /** @brief virtual void join method */ void join(); + + void abort(); - /** @brief virtual void abort method + /** @brief virtual const JobStepAssociation& inputAssociation + * @returns const JobStepAssociation& */ - void abort(); + const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + + /** @brief virtual JobStepAssociation& inputAssociation + */ + void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual const JobStepAssociation& outputAssociation + * @returns const JobStepAssocation& + */ + const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + + /** @brief virtual JobStepAssociation& outputAssociation + */ + void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + /** @brief virtual set step Id + */ + void stepId(uint16_t stepId) { fStepId = stepId; } + + /** @brief virtual get step Id + * @returns uint16 + */ + uint16_t stepId() const { return fStepId; } + + /** @brief virtual get session Id + * @returns uint32 + */ + uint32_t sessionId() const { return fSessionId; } + + /** @brief virtual get transaction Id + * @returns uint32 + */ + uint32_t txnId() const { return fTxnId; } + + /** @brief virtual get statement Id + * @returns uint32 + */ + uint32_t statementId() const { return fStatementId; } /** @brief virtual get table OID * @returns OID @@ -74,6 +132,10 @@ class SubQueryStep : public JobStep */ const std::string toString() const; + /** @brief virtual set default logger + */ + void logger(const SPJL& logger) { fLogger = logger; } + /** @brief virtual set the output rowgroup */ virtual void setOutputRowGroup(const rowgroup::RowGroup& rg) { fOutputRowGroup = rg; } @@ -94,7 +156,14 @@ class SubQueryStep : public JobStep protected: + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint16_t fStepId; + uint32_t fStatementId; uint64_t fRowsReturned; + SPJL fLogger; execplan::CalpontSystemCatalog::OID fTableOid; std::vector fColumnOids; @@ -110,8 +179,15 @@ class SubAdapterStep : public JobStep, public TupleDeliveryStep public: /** @brief SubAdapterStep constructor + * @param sessionId the session Id + * @param txnId the transaction Id + * @param statementId the statement Id */ - SubAdapterStep(SJSTEP& s, const JobInfo&); + SubAdapterStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t statementId, + SJSTEP& s); /** @brief SubAdapterStep destructor */ @@ -124,10 +200,62 @@ class SubAdapterStep : public JobStep, public TupleDeliveryStep /** @brief virtual void join method */ void join(); + + void abort(); - /** @brief virtual void abort method + /** @brief virtual const JobStepAssociation& inputAssociation + * @returns const JobStepAssociation& */ - void abort(); + const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + + /** @brief virtual JobStepAssociation& inputAssociation + */ + void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + + /** @brief virtual const JobStepAssociation& outputAssociation + * @returns const JobStepAssocation& + */ + const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + + /** @brief virtual JobStepAssociation& outputAssociation + */ + void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + /** @brief virtual set step Id + */ + void stepId(uint16_t stepId) { fStepId = stepId; } + + /** @brief virtual get step Id + * @returns uint16 + */ + uint16_t stepId() const { return fStepId; } + + /** @brief virtual get session Id + * @returns uint32 + */ + uint32_t sessionId() const { return fSessionId; } + + /** @brief virtual get transaction Id + * @returns uint32 + */ + uint32_t txnId() const { return fTxnId; } + + /** @brief virtual get statement Id + * @returns uint32 + */ + uint32_t statementId() const { return fStatementId; } /** @brief virtual get table OID * @returns OID @@ -143,6 +271,14 @@ class SubAdapterStep : public JobStep, public TupleDeliveryStep */ const std::string toString() const; + /** @brief virtual set default logger + */ + void logger(const SPJL& logger) { fLogger = logger; } + + /** @brief virtual set the rowgroup for FE to work on + */ + void setFeRowGroup(const rowgroup::RowGroup& rg); + /** @brief virtual set the output rowgroup */ void setOutputRowGroup(const rowgroup::RowGroup& rg); @@ -155,30 +291,16 @@ class SubAdapterStep : public JobStep, public TupleDeliveryStep /** @brief TupleDeliveryStep's pure virtual methods nextBand * @returns row count */ - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); /** @brief Delivered Row Group * @returns RowGroup */ const rowgroup::RowGroup& getDeliveredRowGroup() const { return fRowGroupDeliver; } - /** @brief Turn on/off string table delivery - */ - void deliverStringTableRowGroup(bool b); - - /** @brief Check useStringTable flag on delivered RowGroup - * @returns boolean + /** @brief set delivery falg */ - bool deliverStringTableRowGroup() const; - - /** @brief set the rowgroup for FE to work on - */ - void setFeRowGroup(const rowgroup::RowGroup& rg); - - /** @brief get the rowgroup for FE - * @returns RowGroup - */ - const rowgroup::RowGroup& getFeRowGroup() const { return fRowGroupFe; } + void setIsDelivery(bool b) { fDelivery = b; } /** @brief get subquery step */ @@ -192,10 +314,6 @@ class SubAdapterStep : public JobStep, public TupleDeliveryStep */ void addExpression(const vector&); - /** @brief add function join expresssion - */ - void addFcnJoinExp(const vector&); - protected: void execute(); @@ -205,17 +323,25 @@ class SubAdapterStep : public JobStep, public TupleDeliveryStep void printCalTrace(); void formatMiniStats(); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint16_t fStepId; + uint32_t fStatementId; + SPJL fLogger; + execplan::CalpontSystemCatalog::OID fTableOid; rowgroup::RowGroup fRowGroupIn; rowgroup::RowGroup fRowGroupOut; rowgroup::RowGroup fRowGroupFe; rowgroup::RowGroup fRowGroupDeliver; SJSTEP fSubStep; - uint64_t fRowsInput; uint64_t fRowsReturned; bool fEndOfResult; + bool fDelivery; boost::shared_array fIndexMap; - std::vector > fDupColumns; + std::vector > fDupColumns; RowGroupDL* fInputDL; RowGroupDL* fOutputDL; diff --git a/dbcon/joblist/subquerytransformer.cpp b/dbcon/joblist/subquerytransformer.cpp index bb12d20a..b36616d1 100644 --- a/dbcon/joblist/subquerytransformer.cpp +++ b/dbcon/joblist/subquerytransformer.cpp @@ -29,7 +29,6 @@ using namespace std; using namespace boost; #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" using namespace execplan; #include "rowgroup.h" @@ -41,7 +40,6 @@ using namespace logging; #include "jobstep.h" #include "jlf_common.h" -#include "jlf_tuplejoblist.h" #include "distributedenginecomm.h" #include "expressionstep.h" #include "tuplehashjoin.h" @@ -52,27 +50,16 @@ using namespace logging; namespace joblist { -SubQueryTransformer::SubQueryTransformer(JobInfo* jobInfo, SErrorInfo& err) : - fOutJobInfo(jobInfo), fSubJobInfo(NULL), fErrorInfo(err) +SubQueryTransformer::SubQueryTransformer(JobInfo* jobInfo, SErrorInfo& status) : + fOutJobInfo(jobInfo), fSubJobInfo(NULL), fStatus(status) { } -SubQueryTransformer::SubQueryTransformer(JobInfo* jobInfo, SErrorInfo& err, - const string& view) : - fOutJobInfo(jobInfo), fSubJobInfo(NULL), fErrorInfo(err) +SubQueryTransformer::SubQueryTransformer(JobInfo* jobInfo, SErrorInfo& err, const string& alias) : + fOutJobInfo(jobInfo), fSubJobInfo(NULL), fStatus(err) { - fVtable.view(algorithm::to_lower_copy(view)); -} - - -SubQueryTransformer::SubQueryTransformer(JobInfo* jobInfo, SErrorInfo& err, - const string& alias, - const string& view) : - fOutJobInfo(jobInfo), fSubJobInfo(NULL), fErrorInfo(err) -{ - fVtable.alias(algorithm::to_lower_copy(alias)); - fVtable.view(algorithm::to_lower_copy(view)); + fVtable.alias(algorithm::to_lower_copy(alias)); } @@ -87,16 +74,12 @@ SubQueryTransformer::~SubQueryTransformer() SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPlan* csep, bool subInFromClause) { - if (fOutJobInfo->trace) - cout << (*csep) << endl; - // Setup job info, job list and error status relation. fSubJobInfo = new JobInfo(fOutJobInfo->rm); fSubJobInfo->sessionId = fOutJobInfo->sessionId; fSubJobInfo->txnId = fOutJobInfo->txnId; fSubJobInfo->verId = fOutJobInfo->verId; fSubJobInfo->statementId = fOutJobInfo->statementId; - fSubJobInfo->queryType = fOutJobInfo->queryType; fSubJobInfo->csc = fOutJobInfo->csc; fSubJobInfo->trace = fOutJobInfo->trace; fSubJobInfo->traceFlags = fOutJobInfo->traceFlags; @@ -105,27 +88,17 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl fSubJobInfo->keyInfo = fOutJobInfo->keyInfo; fSubJobInfo->stringScanThreshold = fOutJobInfo->stringScanThreshold; fSubJobInfo->tryTuples = true; - fSubJobInfo->errorInfo = fErrorInfo; + fSubJobInfo->status = fStatus; fOutJobInfo->subNum++; fSubJobInfo->subCount = fOutJobInfo->subCount; fSubJobInfo->subId = ++(*(fSubJobInfo->subCount)); - fSubJobInfo->pJobInfo = fOutJobInfo; + fSubJobInfo->pSubId = fOutJobInfo->subId; fSubJobList.reset(new TupleJobList(true)); fSubJobList->priority(csep->priority()); fSubJobInfo->projectingTableOID = fSubJobList->projectingTableOIDPtr(); fSubJobInfo->jobListPtr = fSubJobList.get(); - fSubJobInfo->stringTableThreshold = fOutJobInfo->stringTableThreshold; - fSubJobInfo->localQuery = fOutJobInfo->localQuery; - fSubJobInfo->uuid = fOutJobInfo->uuid; fOutJobInfo->jobListPtr->addSubqueryJobList(fSubJobList); - fSubJobInfo->smallSideLimit = fOutJobInfo->smallSideLimit; - fSubJobInfo->largeSideLimit = fOutJobInfo->largeSideLimit; - fSubJobInfo->smallSideUsage = fOutJobInfo->smallSideUsage; - fSubJobInfo->partitionSize = fOutJobInfo->partitionSize; - fSubJobInfo->umMemLimit = fOutJobInfo->umMemLimit; - fSubJobInfo->isDML = fOutJobInfo->isDML; - // Update v-table's alias. fVtable.name("$sub"); if (fVtable.alias().empty()) @@ -135,9 +108,8 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl << fSubJobInfo->subId << "_" << fSubJobInfo->subLevel << "_" << fOutJobInfo->subNum; - fVtable.alias(oss.str()); + fVtable.alias(oss.str()); } - fSubJobInfo->subAlias = fVtable.alias(); //@bug5844, unique alias for sub // Make the jobsteps out of the execution plan. JobStepVector querySteps; @@ -150,7 +122,7 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl else throw IDBExcept(ERR_UNION_IN_SUBQUERY); - if (fSubJobInfo->trace) + if (fSubJobInfo->trace) { ostringstream oss; oss << boldStart @@ -172,7 +144,7 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl // Convert subquery to step. SubQueryStep* sqs = - new SubQueryStep(*fSubJobInfo); + new SubQueryStep(fSubJobInfo->sessionId, fSubJobInfo->txnId, fSubJobInfo->statementId); sqs->tableOid(fVtable.tableOid()); sqs->alias(fVtable.alias()); sqs->subJoblist(fSubJobList); @@ -181,18 +153,18 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl RowGroupDL* dl = new RowGroupDL(1, fSubJobInfo->fifoSize); spdl->rowGroupDL(dl); dl->OID(fVtable.tableOid()); - JobStepAssociation jsa; + JobStepAssociation jsa(fSubJobInfo->status); jsa.outAdd(spdl); (querySteps.back())->outputAssociation(jsa); sqs->outputAssociation(jsa); fSubQueryStep.reset(sqs); // Update the v-table columns and rowgroup - vector pos; - vector oids; - vector keys; - vector scale; - vector precision; + vector pos; + vector oids; + vector keys; + vector scale; + vector precision; vector types; pos.push_back(2); @@ -202,17 +174,14 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl const RowGroup& rg = fSubJobList->getOutputRowGroup(); Row row; rg.initRow(&row); - uint64_t outputCols = rg.getColumnCount() < fSubReturnedCols.size() ? - rg.getColumnCount() : fSubReturnedCols.size() ; - for (uint64_t i = 0; i < outputCols; i++) + for (uint64_t i = 0; i < fSubReturnedCols.size(); i++) { - fVtable.addColumn(fSubReturnedCols[i]); + fVtable.addColumn(fSubReturnedCols[i], fOutJobInfo->subView); // make sure the column type is the same as rowgroup CalpontSystemCatalog::ColType ct = fVtable.columnType(i); CalpontSystemCatalog::ColDataType colDataTypeInRg = row.getColTypes()[i]; - if (dynamic_cast(fSubReturnedCols[i].get()) != NULL || - dynamic_cast(fSubReturnedCols[i].get()) != NULL) + if (dynamic_cast(fSubReturnedCols[i].get()) != NULL) { // skip char/varchar/varbinary column because the colWidth in row is fudged. if (colDataTypeInRg != CalpontSystemCatalog::VARCHAR && @@ -222,7 +191,7 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl ct.colWidth = row.getColumnWidth(i); ct.colDataType = row.getColTypes()[i]; ct.scale = row.getScale(i); - if (ct.scale != 0 && ct.precision != -1) + if (ct.scale != 0) ct.colDataType = CalpontSystemCatalog::DECIMAL; ct.precision = row.getPrecision(i); fVtable.columnType(ct, i); @@ -242,24 +211,17 @@ SJSTEP& SubQueryTransformer::makeSubQueryStep(execplan::CalpontSelectExecutionPl // build tuple info to export to outer query TupleInfo ti(setTupleInfo(fVtable.columnType(i), fVtable.columnOid(i), *fOutJobInfo, tblOid, fVtable.columns()[i].get(), alias)); - - if (i < rg.getColumnCount()) - { - pos.push_back(pos.back() + ti.width); - oids.push_back(ti.oid); - keys.push_back(ti.key); - types.push_back(ti.dtype); - scale.push_back(ti.scale); - precision.push_back(ti.precision); - } + pos.push_back(pos.back() + ti.width); + oids.push_back(ti.oid); + keys.push_back(ti.key); + types.push_back(ti.dtype); + scale.push_back(ti.scale); + precision.push_back(ti.precision); fOutJobInfo->vtableColTypes[UniqId(fVtable.columnOid(i), fVtable.alias(), "", "")] = fVtable.columnType(i); } - - RowGroup rg1(oids.size(),pos,oids,keys,types,scale,precision,csep->stringTableThreshold()); - rg1.setUseStringTable(rg.usesStringTable()); - + RowGroup rg1(oids.size(), pos, oids, keys, types, scale, precision); dynamic_cast(fSubQueryStep.get())->setOutputRowGroup(rg1); return fSubQueryStep; @@ -272,12 +234,13 @@ void SubQueryTransformer::checkCorrelateInfo(TupleHashJoinStep* thjs, const JobI if (pos == -1 || (size_t) pos >= fVtable.columns().size()) { + uint64_t id = (thjs->correlatedSide() == 1) ? thjs->tupleId2() : thjs->tupleId1(); string alias = jobInfo.keyInfo->tupleKeyVec[id].fTable; string name = jobInfo.keyInfo->keyName[id]; if (!name.empty() && alias.length() > 0) name = alias + "." + name; - + Message::Args args; args.add(name); string errMsg(IDBErrorInfo::instance()->errorMsg(ERR_CORRELATE_COL_MISSING, args)); @@ -289,11 +252,11 @@ void SubQueryTransformer::checkCorrelateInfo(TupleHashJoinStep* thjs, const JobI void SubQueryTransformer::updateCorrelateInfo() { - // put vtable into the table list to resolve correlated filters + // put vtable into the table list to resolve correlated filters // Temp fix for @bug3932 until outer join has no dependency on table order. // Insert at [1], not to mess with OUTER join and hint(INFINIDB_ORDERED -- bug2317). fOutJobInfo->tableList.insert(fOutJobInfo->tableList.begin()+1, makeTableKey( - *fOutJobInfo, fVtable.tableOid(), fVtable.name(), fVtable.alias(), "", fVtable.view())); + *fOutJobInfo, fVtable.tableOid(), fVtable.name(), fVtable.alias(), "", "")); // tables in outer level set outTables; @@ -305,12 +268,8 @@ void SubQueryTransformer::updateCorrelateInfo() for (uint64_t i = 0; i < fSubJobInfo->tableList.size(); i++) subTables.insert(fSubJobInfo->tableList[i]); - // any function joins - fOutJobInfo->functionJoins.insert(fOutJobInfo->functionJoins.end(), - fSubJobInfo->functionJoins.begin(), fSubJobInfo->functionJoins.end()); - // Update correlated steps - const map& subMap = fVtable.columnMap(); + const map& subMap = fVtable.columnMap(); for (JobStepVector::iterator i = fCorrelatedSteps.begin(); i != fCorrelatedSteps.end(); i++) { TupleHashJoinStep* thjs = dynamic_cast(i->get()); @@ -337,6 +296,7 @@ void SubQueryTransformer::updateCorrelateInfo() TupleInfo ti(setTupleInfo(ct2, thjs->oid2(), *fOutJobInfo, thjs->tableOid2(), fVtable.columns()[pos].get(), thjs->alias2())); thjs->tupleId2(ti.key); + } else { @@ -369,19 +329,14 @@ void SubQueryTransformer::updateCorrelateInfo() } else if (es) { - // already handled by function join - if (es->functionJoin()) - continue; - vector& scList = es->columns(); vector& tableOids = es->tableOids(); + vector& oids = es->oids(); vector& aliases = es->aliases(); vector& views = es->views(); vector& schemas = es->schemas(); - vector& tableKeys = es->tableKeys(); - vector& columnKeys = es->columnKeys(); - - // update simple columns + vector& tableKeys = es->tableKeys(); + vector& columnKeys = es->columnKeys(); for (uint64_t j = 0; j < scList.size(); j++) { SimpleColumn* sc = dynamic_cast(scList[j]); @@ -389,9 +344,10 @@ void SubQueryTransformer::updateCorrelateInfo() { if (subTables.find(tableKeys[j]) != subTables.end()) { - const map::const_iterator k = - subMap.find(UniqId(sc->oid(), aliases[j], schemas[j], views[j])); + const map::const_iterator k = + subMap.find(UniqId(oids[j], aliases[j], schemas[j], views[j])); if (k == subMap.end()) + //throw CorrelateFailExcept(); throw IDBExcept(logging::ERR_NON_SUPPORT_SUB_QUERY_TYPE); sc->schemaName(""); @@ -404,6 +360,7 @@ void SubQueryTransformer::updateCorrelateInfo() ct, sc->oid(), *fOutJobInfo, fVtable.tableOid(), sc, fVtable.alias()); tableOids[j] = execplan::CNX_VTABLE_ID; + oids[j] = sc->oid(); aliases[j] = sc->tableAlias(); views[j] = sc->viewName(); schemas[j] = sc->schemaName(); @@ -412,7 +369,12 @@ void SubQueryTransformer::updateCorrelateInfo() } else { - const CalpontSystemCatalog::ColType& + if ((sc->joinInfo() & JOIN_CORRELATED) != 0) + { + sc->joinInfo(0); + } + + const CalpontSystemCatalog::ColType& ct = fOutJobInfo->keyInfo->colType[columnKeys[j]]; sc->joinInfo(0); TupleInfo ti = setTupleInfo( @@ -422,77 +384,19 @@ void SubQueryTransformer::updateCorrelateInfo() tableKeys[j] = getTableKey(*fOutJobInfo, ti.key); } } - else if (dynamic_cast(scList[j]) != NULL) - { - // workaround for window function IN/EXISTS subquery - const map::const_iterator k = - subMap.find(UniqId(scList[j]->expressionId(), "", "", "")); - if (k == subMap.end()) - throw IDBExcept(logging::ERR_NON_SUPPORT_SUB_QUERY_TYPE); - - sc = fVtable.columns()[k->second].get(); - es->substitute(j, fVtable.columns()[k->second]); - CalpontSystemCatalog::ColType ct = sc->colType(); - string alias(extractTableAlias(sc)); - CalpontSystemCatalog::OID tblOid = fVtable.tableOid(); - TupleInfo ti(setTupleInfo(ct, sc->oid(), *fOutJobInfo, tblOid, sc, alias)); - - tableOids[j] = execplan::CNX_VTABLE_ID; - columnKeys[j] = ti.key; - tableKeys[j] = getTableKey(*fOutJobInfo, ti.key); - } } es->updateColumnOidAlias(*fOutJobInfo); - - // update function join info - boost::shared_ptr& fji = es->functionJoinInfo(); - if (fji && fji->fCorrelatedSide) - { - // replace sub side with a virtual column - int64_t subSide = (fji->fCorrelatedSide == 1) ? 1 : 0; - ReturnedColumn* rc = fji->fExpression[subSide]; - SimpleColumn* sc = dynamic_cast(rc); - if (sc == NULL) - { - UniqId colId = UniqId(rc->expressionId(), "", "", ""); - const map::const_iterator k = subMap.find(colId); - if (k == subMap.end()) - throw IDBExcept(logging::ERR_NON_SUPPORT_SUB_QUERY_TYPE); - - SSC vc = fVtable.columns()[k->second]; - sc = vc.get(); - } - - // virtual table info in outer query - TupleInfo ti(setTupleInfo(sc->colType(), sc->oid(), *fOutJobInfo, - fVtable.tableOid(), sc, fVtable.alias())); - - set cids; - cids.insert(ti.key); - fji->fJoinKey[subSide] = ti.key; - fji->fTableKey[subSide] = ti.tkey; - fji->fColumnKeys[subSide] = cids; - fji->fTableOid[subSide] = fVtable.tableOid(); - fji->fAlias[subSide] = fVtable.alias(); - fji->fView[subSide] = fVtable.view(); - fji->fSchema[subSide] = ""; - - // turn off correlated flag - fji->fExpression[fji->fCorrelatedSide-1]->joinInfo(0); - fji->fJoinType ^= CORRELATED; - fji->fJoinId = 0; - } } else { JobStep* j = i->get(); - uint32_t tid = -1; - uint64_t cid = j->tupleId(); - if (cid != (uint64_t) -1) - tid = getTableKey(*fOutJobInfo, cid); - else - tid = getTableKey(*fOutJobInfo, j); + uint32_t tid = -1; + uint64_t cid = j->tupleId(); + if (cid != (uint64_t) -1) + tid = getTableKey(*fOutJobInfo, cid); + else + tid = getTableKey(*fOutJobInfo, j); if (outTables.find(tid) == outTables.end()) { @@ -524,7 +428,7 @@ SimpleScalarTransformer::SimpleScalarTransformer(JobInfo* jobInfo, SErrorInfo& s SimpleScalarTransformer::SimpleScalarTransformer(const SubQueryTransformer& rhs) : - SubQueryTransformer(rhs.outJobInfo(), rhs.errorInfo()), + SubQueryTransformer(rhs.outJobInfo(), rhs.status()), fInputDl(NULL), fDlIterator(-1), fEmptyResultSet(true), @@ -544,7 +448,7 @@ void SimpleScalarTransformer::run() { // set up receiver fRowGroup = dynamic_cast(fSubQueryStep.get())->getOutputRowGroup(); - fRowGroup.initRow(&fRow, true); + fRowGroup.initRow(&fRow); fInputDl = fSubQueryStep->outputAssociation().outAt(0)->rowGroupDL(); fDlIterator = fInputDl->getIterator(); @@ -555,53 +459,46 @@ void SimpleScalarTransformer::run() getScalarResult(); // check result count - if (fErrorInfo->errCode == ERR_MORE_THAN_1_ROW) + if (fStatus->errCode == ERR_MORE_THAN_1_ROW) throw MoreThan1RowExcept(); } void SimpleScalarTransformer::getScalarResult() { - RGData rgData; - bool more; + shared_array rgData; + bool more = fInputDl->next(fDlIterator, &rgData); - more = fInputDl->next(fDlIterator, &rgData); while (more) { - fRowGroup.setData(&rgData); + fRowGroup.setData(rgData.get()); // Only need one row for scalar filter if (fEmptyResultSet && fRowGroup.getRowCount() == 1) { fEmptyResultSet = false; - Row row; - fRowGroup.initRow(&row); - fRowGroup.getRow(0, &row); fRowData.reset(new uint8_t[fRow.getSize()]); + fRowGroup.getRow(0, &fRow); + memcpy(fRowData.get(), fRow.getData(), fRow.getSize()); fRow.setData(fRowData.get()); - copyRow(row, &fRow); // For exist filter, stop the query after one or more rows retrieved. if (fExistFilter) - { - fErrorInfo->errMsg = IDBErrorInfo::instance()->errorMsg(ERR_MORE_THAN_1_ROW); - fErrorInfo->errCode = ERR_MORE_THAN_1_ROW; - } + fStatus->errCode = ERR_MORE_THAN_1_ROW; } // more than 1 row case: // not empty set, and get new rows - // empty set, but get more than 1 rows + // empty set, but get more than 1 rows else if (fRowGroup.getRowCount() > 0) { // Stop the query after some rows retrieved. fEmptyResultSet = false; - fErrorInfo->errMsg = IDBErrorInfo::instance()->errorMsg(ERR_MORE_THAN_1_ROW); - fErrorInfo->errCode = ERR_MORE_THAN_1_ROW; + fStatus->errCode = ERR_MORE_THAN_1_ROW; } // For scalar filter, have to check all blocks to ensure only one row. - if (fErrorInfo->errCode != 0) + if (fStatus->errCode != 0) while (more) more = fInputDl->next(fDlIterator, &rgData); else more = fInputDl->next(fDlIterator, &rgData); diff --git a/dbcon/joblist/subquerytransformer.h b/dbcon/joblist/subquerytransformer.h index 20b19683..5fccd820 100644 --- a/dbcon/joblist/subquerytransformer.h +++ b/dbcon/joblist/subquerytransformer.h @@ -50,25 +50,16 @@ class SubQueryTransformer public: /** @brief SubQueryTransformer constructor * @param jobInfo - * @param errorInfo + * @param status */ SubQueryTransformer(JobInfo*, SErrorInfo&); /** @brief SubQueryTransformer constructor * @param jobInfo - * @param errorInfo - * @param view - */ - SubQueryTransformer(JobInfo*, SErrorInfo&, const std::string&); - - /** @brief SubQueryTransformer constructor - * @param jobInfo - * @param errorInfo + * @param status * @param alias - * @param view */ - SubQueryTransformer( - JobInfo*, SErrorInfo&, const std::string&, const std::string&); + SubQueryTransformer(JobInfo*, SErrorInfo&, const std::string&); /** @brief SubQueryTransformer destructor */ @@ -104,7 +95,7 @@ class SubQueryTransformer /** @brief virtual error info pointer * @returns SErrorInfo& */ - virtual SErrorInfo& errorInfo() const { return fErrorInfo; } + virtual SErrorInfo& status() const { return fStatus; } /** @brief virtual joblist * @returns STJLP& @@ -137,7 +128,7 @@ class SubQueryTransformer JobInfo* fOutJobInfo; JobInfo* fSubJobInfo; - SErrorInfo& fErrorInfo; + SErrorInfo& fStatus; JobStepVector fCorrelatedSteps; RetColsVector fSubReturnedCols; STJLP fSubJobList; @@ -157,10 +148,10 @@ class SimpleScalarTransformer : public SubQueryTransformer public: /** @brief SimpleScalarTransformer constructor * @param jobInfo - * @param errorInfo for error info + * @param status for error status * @param existFilter indicate if exist filter */ - SimpleScalarTransformer(JobInfo* jobInfo, SErrorInfo& errInfo, bool existFilter); + SimpleScalarTransformer(JobInfo* jobInfo, SErrorInfo& status, bool existFilter); /** @brief SimpleScalarTransformer constructor * @param SubQueryTransformer diff --git a/dbcon/joblist/swsdl.h b/dbcon/joblist/swsdl.h new file mode 100644 index 00000000..ecc6bc01 --- /dev/null +++ b/dbcon/joblist/swsdl.h @@ -0,0 +1,386 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: swsdl.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + *****************************************************************************/ + +/** @file + * class XXX interface + */ + +#include +#include + +#include "largedatalist.h" +#include "elementtype.h" +//#include "configcpp.h" +#include "resourcemanager.h" + +#ifndef _SWSDL_HPP +#define _SWSDL_HPP + +/** Debug macro */ +#define SWSDL_DEBUG 1 +#if SWSDL_DEBUG +#define SDEBUG std::cout +#else +#define SDEBUG if (false) std::cout +#endif + +namespace joblist { +/** @brief class StagedDL + * + */ +template +class SWSDL : public LargeDataList, element_t> +{ + typedef LargeDataList, element_t> base; + typedef std::vector container_t; + + public: + SWSDL(uint numConsumers, ResourceManager& rm); + SWSDL(uint numConsumers, uint maxElements, ResourceManager& rm); + virtual ~SWSDL(); + + void insert(const element_t &e); + void insert(const container_t &e); + void insert_nolock(const element_t &e); + bool next(uint64_t it, element_t *e); + void endOfInput(); + uint64_t getIterator(); + uint64_t totalSize(); + + protected: + + private: + // Default constructors and assignment operator are declared but + // never defined to disable their use + SWSDL(); + SWSDL(const SWSDL &); + SWSDL & operator=(const SWSDL &); + + void load(uint64_t setNum); + uint64_t save(); + uint64_t save(container_t *c); + bool inputDone(); + + ResourceManager& fRm; + uint64_t maxElements; + uint64_t waitingConsumers; + boost::condition nextSetLoaded; + boost::condition nextSetReady; + bool endInput; + container_t *tempC; // temp buffer for the producer to write to + boost::mutex writeLock; // lock to protect the temp buffer +}; + +template +SWSDL::SWSDL(uint nc, ResourceManager& rm) : + base(nc,sizeof(uint64_t),sizeof(uint64_t), rm), fRm(rm), maxElements(rm.getScTempSaveSize()), + waitingConsumers(0), endInput(false), tempC(new container_t()) + +{ + +// config::Config *config = config::Config::makeConfig(); +// std::string strVal; +// strVal = config->getConfig("SystemConfig", "TempSaveSize"); +// if (strVal.size() > 0) +// maxElements = config::Config::uFromText(strVal); +// else +// maxElements = defaultMaxElements; +// waitingConsumers = 0; +// endInput = false; +// tempC = new container_t(); + // need to modify base assignment from 1 to 0 to enssure concurrency correctness + base::setCount = 0; + //pthread_cond_init(&nextSetLoaded, NULL); + //pthread_cond_init(&nextSetReady, NULL); + //pthread_mutex_init(&writeLock, NULL); + SDEBUG << "SWSDL-" << this << " maxElements=" << maxElements << std::endl; +} + +template +SWSDL::SWSDL(uint nc, uint me, ResourceManager& rm) : + base(nc,sizeof(uint64_t),sizeof(uint64_t), rm), fRm(rm), maxElements(me), + waitingConsumers(0), endInput(false), tempC(new container_t()) +{ +// maxElements = me; +// waitingConsumers = 0; +// endInput = false; +// tempC = new container_t(); + // need to modify base assignment from 1 to 0 to enssure concurrency correctness + base::setCount = 0; + //pthread_cond_init(&nextSetLoaded, NULL); + //pthread_cond_init(&nextSetReady, NULL); + //pthread_mutex_init(&writeLock, NULL); + SDEBUG << "SWSDL-" << this << " maxElements=" << me << std::endl; +} + +template +SWSDL::~SWSDL() +{ + //pthread_cond_destroy(&nextSetLoaded); + //pthread_cond_destroy(&nextSetReady); + //pthread_mutex_destroy(&writeLock); + SDEBUG << "swsdl-" << this << " destructed" << std::endl; +} + +template +void SWSDL::load(uint64_t setNum) +{ + if (typeid(element_t) == typeid(ElementType) || + typeid(element_t) == typeid(DoubleElementType)) + base::load_contiguous(setNum); + else + base::load(setNum); +} + +template +uint64_t SWSDL::save() +{ + sort(base::c->begin(), base::c->end()); + if (typeid(element_t) == typeid(ElementType) || + typeid(element_t) == typeid(DoubleElementType)) + return base::save_contiguous(); + else + return base::save(); +} + +template +uint64_t SWSDL::save(container_t *c) +{ + sort(c->begin(), c->end()); + if (typeid(element_t) == typeid(ElementType) || + typeid(element_t) == typeid(DoubleElementType)) + return base::save_contiguous(c); + else + return base::save(c); +} + +template +void SWSDL::insert(const element_t &e) +{ + if (base::multipleProducers) + writeLock.lock(); //pthread_mutex_lock(&writeLock); + + insert_nolock(e); + if (base::multipleProducers) + writeLock.unlock(); //pthread_mutex_unlock(&writeLock); +} + +template +void SWSDL::insert_nolock(const element_t &e) +{ + /* 1. insert into tempC + 2. if maxElement, save tempC to disk. increment setCount, and renew tempC + 3. if initial state (phase==0), load(0), flip phase and signal consumer load ready + 4. else, signal consumer next set ready + */ + if (tempC->size() == maxElements) + { + save(tempC); + delete tempC; + tempC = new container_t(); + + base::lock(); + base::setCount++; + + // when 1st set ready, save and load it, and flip phase. so phase=0 represents + // the initial state; phase=1 represent in-process state (at least one set has + // been loaded and consumers have stared consuming). + if (base::phase == 0) + { + load(0); + base::phase = 1; + SDEBUG << this << " first set ready. " << std::endl; + nextSetLoaded.notify_all(); //pthread_cond_broadcast(&nextSetLoaded); + } + else + { + SDEBUG << this << " next set ready" << std::endl; + nextSetReady.notify_all(); //pthread_cond_broadcast(&nextSetReady); + } + base::unlock(); + + } + base::totSize++; + tempC->insert(tempC->end(), e); +} + +template +void SWSDL::insert(const container_t &e) +{ + throw std::logic_error("StagedDL::insert(vector) isn't implemented yet"); +} + +template +void SWSDL::endOfInput() +{ + /* + 1. if current is not the only set, save tempC to disk and increment setCount; + 2. else, sort tempC, assign to base::C and signal consumer load ready + 3. set endInput flag true + */ + base::lock(); + SDEBUG << "end of input " << this << std::endl; + base::endOfInput(); + if (base::setCount > 0) { + save(tempC); + base::setCount++; + nextSetReady.notify_all(); //pthread_cond_broadcast(&nextSetReady); + } + else + { + sort(tempC->begin(), tempC->end()); + base::c = tempC; + SDEBUG << this << " One only set ready" << std::endl; + base::setCount++; + nextSetLoaded.notify_all(); //pthread_cond_broadcast(&nextSetLoaded); + base::resetIterators(); + } + endInput = true; // setCount is the final count now + base::unlock(); +} + +template +uint64_t SWSDL::getIterator() +{ + uint64_t ret; + + base::lock(); + ret = base::getIterator(); + base::unlock(); + return ret; +} + +template +bool SWSDL::inputDone() +{ + return ( base::loadedSet >= base::setCount-1 && endInput); +} + +template +bool SWSDL::next(uint64_t id, element_t *e) +{ + /* + 1. if initial state (phase==0), wait for load ready. + 2. read without wait + 3. if end of current set, and more set is ready, and no more consumer is still reading this set, load new set. + 4. if end of current set, and more set is ready, and other consumers are still working, wait for next load signal. + 5. if end of current set, and end of set, shrink(). + */ + bool ret, locked = false; + uint64_t nextSet; +/* + if (base::numConsumers > 1 || !inputDone()) + { + locked = true; + base::lock(); + } +*/ + if (base::phase == 0) { + locked = true; + base::lock(); + } + + while (base::phase == 0) + { + SDEBUG << id << " waiting on nextSetLoaded: 215 for " << this << std::endl; + nextSetLoaded.wait(this->mutex); //pthread_cond_wait(&nextSetLoaded, &(this->mutex)); + SDEBUG << "consumer " << id << " wake up for " << this << std::endl; + } + + ret = base::next_nowait(id, e); + + if (ret == false){ + SDEBUG << id << " One set read done for " << this << " loadedSet="<< base::loadedSet + << " setCount=" << base::setCount << std::endl; + if (locked) base::unlock(); + } + + // signal the caller is at the end of the loaded set, + // but there are more sets + if (ret == false && !inputDone()) { + if (!locked && (base::numConsumers > 1 || !inputDone())) { + locked = true; + base::lock(); + } + + nextSet = base::loadedSet + 1; + waitingConsumers++; + // other consumers not done on this set yet + if (waitingConsumers < base::numConsumers) + while (nextSet != base::loadedSet) { + SDEBUG << id << " waiting on nextSetLoaded: 217 for " << this + << " nextSet=" << nextSet << " loadedSet=" << base::loadedSet << std::endl; + nextSetLoaded.wait(this->mutex); //pthread_cond_wait(&nextSetLoaded, &(this->mutex)); + SDEBUG << id << " wake up nextSetLoaded: 217 for " << this << std::endl; + } + // current consumer is the last one who done reading this set + else { + // set ready, not loaded yet + if (base::loadedSet < base::setCount-1) + { + load(nextSet); + SDEBUG << id << " Loaded next set for " << this << std::endl; + nextSetLoaded.notify_all(); //pthread_cond_broadcast(&nextSetLoaded); + waitingConsumers = 0; + } + // next set not saved yet + else if (!inputDone()) + { + SDEBUG << id << " wait on nextSetReady for " << this << std::endl; + nextSetReady.wait(this->mutex); //pthread_cond_wait(&nextSetReady, &(this->mutex)); + SDEBUG << id << " wake up ready for " << this << std::endl; + load(nextSet); + nextSetLoaded.notify_all(); //pthread_cond_broadcast(&nextSetLoaded); + waitingConsumers = 0; + } + } + ret = base::next(id, e); + } + + // end of input + if (ret == false && inputDone() && ++base::consumersFinished == base::numConsumers) + { + SDEBUG << "finished consumer # = " << base::consumersFinished << " # consumers = " << base::numConsumers << std::endl; + SDEBUG << "shrink " << this << std::endl; + base::shrink(); + } + + if (locked) + base::unlock(); + return ret; +} + +template +uint64_t SWSDL::totalSize() +{ + uint64_t ret; + + base::lock(); + ret = base::totalSize(); + base::unlock(); + + return ret; +} + +} //namespace + +#endif diff --git a/dbcon/joblist/tableband.cpp b/dbcon/joblist/tableband.cpp new file mode 100644 index 00000000..953ef01f --- /dev/null +++ b/dbcon/joblist/tableband.cpp @@ -0,0 +1,616 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: tableband.cpp 8582 2012-06-01 20:09:05Z xlou $ + * + *****************************************************************************/ +#include +#include +#include +#include +#if BOOST_VERSION <= 103200 +#error your boost version is too old +#endif +using namespace std; + +#define TABLEBAND_DLLEXPORT +#include "tableband.h" +#undef TABLEBAND_DLLEXPORT + +#include "bytestream.h" +using namespace messageqcpp; + +#include "calpontsystemcatalog.h" +using namespace execplan; + +#include "dataconvert.h" +using namespace dataconvert; + +#include "joblisttypes.h" + +#include "tablecolumn.h" +#include "datalist.h" +#include "elementtype.h" + +namespace +{ +const string boldStart = "\033[0;1m"; +const string boldStop = "\033[0;39m"; +} + +namespace joblist +{ + +TableBand::TableBand(CalpontSystemCatalog::OID tableOID) : + fTableOID(tableOID), fRowCount(0), numColumns(0), fStatus(0) +{ + +} + +void TableBand::serialize(ByteStream& b) const { + ByteStream::octbyte ob; + + ob = fTableOID; + b << ob; + ob = numColumns; + b << ob; + ob = fRowCount; + b << ob; + ob = fStatus; + b << ob; + b << (uint8_t) false; // the "got rows" var. when serialized this way, there are never rids + + VBA::size_type i; + for(i = 0; i < numColumns; i++) + fColumns[i]->serialize(b); +} + +void TableBand::unserialize(ByteStream& b) { + ByteStream::octbyte colSize; + ByteStream::octbyte status; + ByteStream::octbyte ob; + uint8_t tmp8; + bool gotRids; + + b >> ob; + fTableOID = ob; + b >> colSize; + b >> ob; + fRowCount = ob; + b >> status; + fStatus = status; + + if (fStatus) + return; + + b >> tmp8; + gotRids = (tmp8 != 0); + if (gotRids) { + fRids.resize(fRowCount); + memcpy(&fRids[0], b.buf(), fRowCount << 3); + b.advance(fRowCount << 3); + } + + fColumns.clear(); + fColumns.reserve(colSize); + for(ByteStream::octbyte i = 0; i < colSize; i++) { + boost::shared_ptr colSPtr(new TableColumn); + colSPtr->unserialize(b); + fColumns.push_back(colSPtr); + } + numColumns = colSize; +} + +int TableBand::find(execplan::CalpontSystemCatalog::OID columnOID) const +{ + VBA::const_iterator iter = fColumns.begin(); + VBA::const_iterator end = fColumns.end(); + + int idx = 0; + while (iter != end) + { + if ((*iter)->getColumnOID() == columnOID) + return idx; + idx++; + ++iter; + } + return -1; +} + +void TableBand::addColumn(FifoDataList *fifo, uint it, uint32_t flushInterval, bool firstColumn, bool isExeMgr) +{ + boost::shared_ptr > sv; + vector *values; + boost::shared_ptr stc; + TableColumn *tc; + int index; + + // Create a new TableColumn through a shared pointer. + stc.reset(new TableColumn(fifo->OID(), TableColumn::UINT64)); + tc = stc.get(); + + // Find the column in the band. + index = find(tc->getColumnOID()); + if (index < 0) { + std::cerr << "find failed?" << std::endl; + throw std::exception(); + } + + // Create a vector of values for the TableColumn through a shared pointer. + sv.reset(new vector()); + values = sv.get(); + if (fRowCount > 0) values->reserve(fRowCount); + + UintRowGroup rw; + uint64_t ridCount = 0; + bool more = fifo->next(it, &rw); + + if (firstColumn) + { + fRowCount = 0; + while (more) { + for (uint64_t i = 0; i < rw.count; ++i) + { + values->push_back(rw.et[i].second); + fRids.push_back(rw.et[i].first); + } + ridCount += rw.count; + + if (ridCount >= flushInterval) + more = false; + else + more = fifo->next(it, &rw); + } + fRowCount = ridCount; + } + else + { + while (more) { + for (uint64_t i = 0; i < rw.count; ++i) + values->push_back(rw.et[i].second); + ridCount += rw.count; + + if (ridCount >= flushInterval) + more = false; + else + more = fifo->next(it, &rw); + } + + if ((fRowCount > 0) && (ridCount != fRowCount)) + { + ostringstream oss; + oss << "TableBand::addColumn(uint64 pairs): attempt to add column " << fifo->OID() << " w/ " << + ridCount << " to a table w/ " << fRowCount << " rows!"; + cerr << boldStart << oss.str() << boldStop << endl; + throw runtime_error(oss.str()); + } + } + tc->setIntValues(sv); + if (isExeMgr) + tc->serialize(); + fColumns[index] = stc; +} + +void TableBand::addColumn(StringFifoDataList *fifo, uint it, uint32_t flushInterval, bool firstColumn, bool isExeMgr) +{ + + boost::shared_ptr > sv; + vector *values; + boost::shared_ptr stc; + TableColumn *tc; + int index; + + // Create a new TableColumn through a shared pointer. + stc.reset(new TableColumn(fifo->OID(), TableColumn::STRING)); + tc = stc.get(); + + // Find the column in the band. + index = find(tc->getColumnOID()); + if (index < 0) { + std::cerr << "find failed?" << std::endl; + throw std::exception(); + } + + // Create a vector of values for the TableColumn through a shared pointer. + sv.reset(new vector()); + values = sv.get(); + + // Add the values to the vector. + if (fRowCount > 0) values->reserve(fRowCount); + + StringRowGroup rw; + bool more = fifo->next(it, &rw); + uint64_t ridCount = 0; + + if (firstColumn) + { + fRowCount = 0; + while (more) { + for (uint64_t i = 0; i < rw.count; ++i) + { + values->push_back(rw.et[i].second); + fRids.push_back(rw.et[i].first); + } + ridCount += rw.count; + + if (ridCount >= flushInterval) + more = false; + else + more = fifo->next(it, &rw); + } + fRowCount = ridCount; + } + else + { + while (more) { + for (uint64_t i = 0; i < rw.count; ++i) + values->push_back(rw.et[i].second); + ridCount += rw.count; + + if (ridCount >= flushInterval) + more = false; + else + more = fifo->next(it, &rw); + } + + if ((fRowCount > 0) && (ridCount != fRowCount)) + { + ostringstream oss; + oss << "TableBand::addColumn(string pairs): attempt to add column " << fifo->OID() << " w/ " << + ridCount << " to a table w/ " << fRowCount << " rows!"; + cerr << boldStart << oss.str() << boldStop << endl; + throw runtime_error(oss.str()); + } + } + tc->setStrValues(sv); + if (isExeMgr) + tc->serialize(); + fColumns[index] = stc; +} + +void TableBand::addNullColumn(execplan::CalpontSystemCatalog::OID columnOID) +{ + boost::shared_ptr stc; + stc.reset(new TableColumn(columnOID, TableColumn::UNDEFINED)); + + int idx = find(columnOID); + if (idx != -1) cout << "TableBand::addNullColumn: adding a null column on top of a non-null column! " << columnOID << endl; + if (idx >= 0) + fColumns[idx] = stc; + else { + fColumns.push_back(stc); + ++numColumns; + } +} + +void TableBand::convertToSysDataList(CalpontSystemCatalog::NJLSysDataList& sysDataList, CalpontSystemCatalog *csc) +{ + uint i; + for(i = 0; i < numColumns; i++) + if(!fColumns[i]->isNullColumn()) + fColumns[i]->addToSysDataList(sysDataList, fRids); +} +#if 0 +void TableBand::convertToSysDataRids(CalpontSystemCatalog::NJLSysDataList& sysDataList) +{ + uint i; + for(i = 0; i < numColumns; i++) + if(!fColumns[i]->isNullColumn()) + fColumns[i]->addToSysDataRids(sysDataList, fRids); +} +#endif + +void TableBand::clearRows() +{ + for(uint i = 0; i < numColumns; i++) { + fColumns[i]->getStrValues()->clear(); + fColumns[i]->getIntValues()->clear(); + } + fRowCount = 0; +} + +void TableBand::toString() const +{ + cout << endl; + cout << "---------------------------------------------------------------------"; + cout << "TableBand Table OID: " << fTableOID << endl; + cout << "# of Columns = " << numColumns << endl; + cout << "Rows = " << fRowCount << endl; + cout << endl; + cout << "Columns:" << endl; + uint i; + for(i = 0; i < numColumns; i++) { + cout << "Column OID: " << fColumns[i]->getColumnOID(); + if(fColumns[i]->isNullColumn()) + cout << " (null column)"; + cout << endl; + } + cout << "---------------------------------------------------------------------" << endl << endl; +} +} //namespace joblist + +namespace +{ +boost::mutex sysCatMutex; + +CalpontSystemCatalog::ColType getColType(execplan::CalpontSystemCatalog::OID oid) +{ + boost::mutex::scoped_lock lk(sysCatMutex); + return CalpontSystemCatalog::makeCalpontSystemCatalog()->colType(oid); +} +} + +namespace joblist +{ +ostream& TableBand::formatToCSV(ostream& os, char sep) const +{ + vector colTypes(numColumns); + ostringstream oss; + unsigned numRealCols = numColumns; + for (unsigned col = (numColumns - 1); true; --col) + { + if (!fColumns[col]->isNullColumn()) + break; + numRealCols--; + if (col == 0) + break; + } + for (unsigned row = 0; row < fRowCount; row++) + { + for (unsigned col = 0; col < numRealCols; col++) + { + if (fColumns[col]->isNullColumn()) + { + oss << sep; + continue; + } + if (colTypes[col].columnOID == 0) + colTypes[col] = getColType(fColumns[col]->getColumnOID()); + //lifted more or less from dbcon/sm/dhcs_ti.cpp:dhcs_tpl_scan_fetch_fillrow() + if (fColumns[col]->getColumnType() == TableColumn::UINT64) + { + uint64_t rowVal; + rowVal = (*fColumns[col]->getIntValues())[row]; + if (colTypes[col].colDataType == CalpontSystemCatalog::DATE) + { + if (rowVal != 0xfffffffeLL) + { + //oss << DataConvert::dateToString(rowVal); + char ds[11]; + unsigned t = 0; + rowVal >>= 6; + t = rowVal & 0x3f; + ds[10] = 0; + ds[9] = (t % 10) + '0'; + ds[8] = (t / 10) + '0'; + ds[7] = '-'; + rowVal >>= 6; + t = rowVal & 0xf; + ds[6] = (t % 10) + '0'; + ds[5] = (t / 10) + '0'; + ds[4] = '-'; + rowVal >>= 4; + t = rowVal & 0xffff; + //TODO: do we need to handle this case better? + //t %= 10000; + ds[3] = (t % 10) + '0'; + ds[2] = ((t / 10) % 10) + '0'; + ds[1] = ((t / 100) % 10) + '0'; + ds[0] = (t / 1000) + '0'; + oss << ds; + } + } + else if (colTypes[col].colDataType == CalpontSystemCatalog::DATETIME) + { + if (rowVal != 0xfffffffffffffffeLL) + { + //oss << DataConvert::dateToString(rowVal); + char ds[20]; + unsigned t = 0; + rowVal >>= 20; + t = rowVal & 0x3f; + ds[19] = 0; + ds[18] = (t % 10) + '0'; + ds[17] = (t / 10) + '0'; + ds[16] = ':'; + rowVal >>= 6; + t = rowVal & 0x3f; + ds[15] = (t % 10) + '0'; + ds[14] = (t / 10) + '0'; + ds[13] = ':'; + rowVal >>= 6; + t = rowVal & 0x3f; + ds[12] = (t % 10) + '0'; + ds[11] = (t / 10) + '0'; + ds[10] = ' '; + rowVal >>= 6; + t = rowVal & 0x3f; + ds[9] = (t % 10) + '0'; + ds[8] = (t / 10) + '0'; + ds[7] = '-'; + rowVal >>= 6; + t = rowVal & 0xf; + ds[6] = (t % 10) + '0'; + ds[5] = (t / 10) + '0'; + ds[4] = '-'; + rowVal >>= 4; + t = rowVal & 0xffff; + //TODO: do we need to handle this case better? + //t %= 10000; + ds[3] = (t % 10) + '0'; + ds[2] = ((t / 10) % 10) + '0'; + ds[1] = ((t / 100) % 10) + '0'; + ds[0] = (t / 1000) + '0'; + oss << ds; + } + } + else if (colTypes[col].colDataType == CalpontSystemCatalog::CHAR || + colTypes[col].colDataType == CalpontSystemCatalog::VARCHAR) + { + int cw = colTypes[col].colWidth; + bool isVC = (colTypes[col].colDataType == CalpontSystemCatalog::VARCHAR); + if (cw == 1) + { + if ( (!isVC && rowVal != 0xfeLL) || + (isVC && rowVal != 0xfeffLL) ) + oss << static_cast(rowVal); + } + else if (cw == 2) + { + if ( (!isVC && rowVal != 0xfeffLL) || + (isVC && rowVal != 0xfeffffffLL) ) + oss << static_cast(rowVal) + << static_cast(rowVal>>8); + } + else if (cw == 3) + { + if (rowVal != 0xfeffffffLL) + oss << static_cast(rowVal) + << static_cast(rowVal>>8) + << static_cast(rowVal>>16); + } + else if (cw == 4) + { + if ( (!isVC && rowVal != 0xfeffffffLL) || + (isVC && rowVal != 0xfeffffffffffffffLL) ) + oss << static_cast(rowVal) + << static_cast(rowVal>>8) + << static_cast(rowVal>>16) + << static_cast(rowVal>>24); + } + else if (cw == 5) + { + if (rowVal != 0xfeffffffffffffffLL) + oss << static_cast(rowVal) + << static_cast(rowVal>>8) + << static_cast(rowVal>>16) + << static_cast(rowVal>>24) + << static_cast(rowVal>>32); + } + else if (cw == 6) + { + if (rowVal != 0xfeffffffffffffffLL) + oss << static_cast(rowVal) + << static_cast(rowVal>>8) + << static_cast(rowVal>>16) + << static_cast(rowVal>>24) + << static_cast(rowVal>>32) + << static_cast(rowVal>>40); + } + else if (cw == 7) + { + if (rowVal != 0xfeffffffffffffffLL) + oss << static_cast(rowVal) + << static_cast(rowVal>>8) + << static_cast(rowVal>>16) + << static_cast(rowVal>>24) + << static_cast(rowVal>>32) + << static_cast(rowVal>>40) + << static_cast(rowVal>>48); + } + else if (cw == 8) + { + if (rowVal != 0xfeffffffffffffffLL) + oss << static_cast(rowVal) + << static_cast(rowVal>>8) + << static_cast(rowVal>>16) + << static_cast(rowVal>>24) + << static_cast(rowVal>>32) + << static_cast(rowVal>>40) + << static_cast(rowVal>>48) + << static_cast(rowVal>>56); + } + else + { + //TODO: handle more cases + oss << static_cast(rowVal); + } + } + else + { + if ( (colTypes[col].colWidth == 8 && rowVal != 0x8000000000000000LL) || + (colTypes[col].colWidth == 4 && rowVal != 0x80000000LL) || + (colTypes[col].colWidth == 2 && rowVal != 0x8000LL) || + (colTypes[col].colWidth == 1 && rowVal != 0x80LL) ) + { + int64_t* sRowValp = reinterpret_cast(&rowVal); +#ifndef __LP64__ + //Something is amiss in the 32-bit versions...rowVal always + // seems to have the upper 32-bits cleared. This will sign-extend + // the negative values so the dumped values are correct. + if (*sRowValp & 0x0000000080000000ULL) + *sRowValp |= 0xffffffff80000000ULL; +#endif + int negAdj = (*sRowValp < 0 ? 2 : 1); + if (colTypes[col].scale > 0) + { + //biggest 64-bit number is 19 digits, + 1 for sign, + // + 1 for dp, + 1 for NULL + char tmp[22]; + snprintf(&tmp[1], + 21, +#ifndef __LP64__ + "%lld", +#else + "%ld", +#endif + *sRowValp); + size_t l = strlen(&tmp[negAdj]); + ssize_t n = l - colTypes[col].scale; + //we need to put some leading zeros + // ("2" needs to look like "02", etc.) + if (n < 0) + { + n = -n; + memmove(&tmp[negAdj + n], &tmp[negAdj], (l + 1)); + do + { + tmp[negAdj + --n] = '0'; + } while (n > 0); + } + n += (negAdj - 1); + memmove(&tmp[0], &tmp[1], n); + tmp[n] = '.'; + oss << tmp; + } + else + { + oss << *sRowValp; + } + } + } + } + else if (fColumns[col]->getColumnType() == TableColumn::STRING) + { + string rowVal; + rowVal = (*fColumns[col]->getStrValues())[row]; + if (rowVal != CPNULLSTRMARK) + oss << rowVal; + } + oss << sep; + } + oss << endl; + } + const string& s = oss.str(); + os.write(s.c_str(), s.length()); + + return os; +} + +} // namespace + diff --git a/dbcon/joblist/tableband.h b/dbcon/joblist/tableband.h new file mode 100644 index 00000000..967fabeb --- /dev/null +++ b/dbcon/joblist/tableband.h @@ -0,0 +1,163 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: tableband.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + *****************************************************************************/ + +/** @file */ + +#ifndef JOBLIST_TABLEBAND_H_ +#define JOBLIST_TABLEBAND_H_ + +#include +#include +#include +#include +#include + +#include "calpontsystemcatalog.h" +#include "bytestream.h" +#include "datalist.h" +#include "elementtype.h" +#include "tablecolumn.h" + +//#define TB_CHECK_RIDS 1 +//#define TB_CHECK_STR_RIDS 1 + +#if defined(_MSC_VER) && defined(TABLEBAND_DLLEXPORT) +#define EXPORT __declspec(dllexport) +#else +#define EXPORT +#endif + +namespace joblist +{ + +/** @brief used during the delivery step to project a band of rows to the front end. + * + * Class TableBand is used during the delivery step to project a band of rows to the front end. + */ +class TableBand { +public: + + typedef std::vector > VBA; + + /** @brief Constructor - used on the ExeMgr side to create a new band of rows. + * + * @param shemaOwner the schema owner of the table + * @param tableName the table name. + */ + EXPORT explicit TableBand(execplan::CalpontSystemCatalog::OID tableOID=0); + + // @bug 710 - fifo read is moved here because sorting is not needed in deliverystep + /** @brief addColumn + */ + EXPORT void addColumn(FifoDataList *fifo, uint it, uint32_t flushInterval, bool firstColumn, bool isExeMgr); + + /** @brief addColumn + */ + EXPORT void addColumn(StringFifoDataList *fifo, uint it, uint32_t flushInterval, bool firstColumn, bool isExeMgr); + + /** @brief addNullColumn + */ + EXPORT void addNullColumn(execplan::CalpontSystemCatalog::OID columnOID); + + /** @brief Getter for the Table OID + */ + EXPORT execplan::CalpontSystemCatalog::OID tableOID() const { return fTableOID; } + + /** @brief Getter for the Table OID + */ + EXPORT void tableOID(execplan::CalpontSystemCatalog::OID tableOID) { fTableOID = tableOID; } + + /** @brief Getter for the vector of TableColumn objects. + * + * The any is actually a TableColumn. Since the data types (kind) can be different for each + * column, they had to be typed as any. + */ + EXPORT const VBA& getColumns() const { return fColumns; } + + /** @brief Getter for the number of columns. + */ + EXPORT VBA::size_type getColumnCount() const { return fColumns.size(); } + + /** @brief Getter for the number of rows. + */ + EXPORT VBA::size_type getRowCount() const { return fRowCount; } + + /** @brief Getter for status. + */ + EXPORT uint16_t getStatus() const { return fStatus; } + + /** @brief Serializes the object into the passed bytestream. + */ + EXPORT void serialize(messageqcpp::ByteStream& b) const; + + /** @brief Inflates the object from the passed bytestream. + */ + EXPORT void unserialize(messageqcpp::ByteStream& b); + + /** @brief Converts the tableband to the passed SysDataList. + */ + EXPORT void convertToSysDataList(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList, + execplan::CalpontSystemCatalog *csc); +#if 0 + EXPORT void convertToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList); +#endif + /** @brief Clears out the rows. + */ + EXPORT void clearRows(); + + /** @brief print the band metadata to cout + */ + EXPORT void toString() const; + + /** @brief find a column OID in this band + * + * Returns the index of OID in this band. Returns -1 if the OID was not found. + */ + EXPORT int find(execplan::CalpontSystemCatalog::OID OID) const; + + /** @brief format a band into a string + * + * Formats a band of data out to a stream in ASCII using sep as the column separator. This is generally + * suitable for import back into the system via cpimport (perhaps with some final post-processing). + */ + EXPORT std::ostream& formatToCSV(std::ostream& os, char sep) const; + + EXPORT std::vector* getRidList() { return &fRids; } + +private: + // defaults okay + //TableBand(const TableBand& rhs); // no copies + //TableBand& operator=(const TableBand& rhs); // no assignments + + execplan::CalpontSystemCatalog::OID fTableOID; + VBA fColumns; + uint fRowCount; + std::vector fRids; + uint numColumns; + uint16_t fStatus; +}; + +#undef EXPORT + +} // namespace + +#endif diff --git a/dbcon/joblist/tablecolumn.cpp b/dbcon/joblist/tablecolumn.cpp index 1f008f1a..8c7e4331 100644 --- a/dbcon/joblist/tablecolumn.cpp +++ b/dbcon/joblist/tablecolumn.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: tablecolumn.cpp 9655 2013-06-25 23:08:13Z xlou $ + * $Id: tablecolumn.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ @@ -29,25 +29,27 @@ using namespace messageqcpp; #include "columnresult.h" +#define TABLECOLUMN_DLLEXPORT #include "tablecolumn.h" +#undef TABLECOLUMN_DLLEXPORT namespace joblist { -/** @brief constructor +/** @brief constructor */ TableColumn::TableColumn(const execplan::CalpontSystemCatalog::OID columnOID, const supportedType columnType) : - fColumnOID(columnOID), fIsNullColumn(true), fColumnType(columnType) + fColumnOID(columnOID), fIsNullColumn(true), fColumnType(columnType) { preserialized.reset(new ByteStream()); } -TableColumn::TableColumn() : fColumnOID(0), fIsNullColumn(true), fColumnType(UNDEFINED) +TableColumn::TableColumn() : fColumnOID(0), fIsNullColumn(true), fColumnType(UNDEFINED) { preserialized.reset(new ByteStream()); }; -void TableColumn::serialize() +void TableColumn::serialize() { // cerr << "pre-serializing" << endl; messageqcpp::ByteStream::octbyte rowCount; @@ -76,7 +78,7 @@ void TableColumn::serialize() else if(fColumnType == STRING) { rowCount = fStrValues->size(); *preserialized << rowCount; - for(uint32_t i = 0; i < rowCount; i++) + for(uint i = 0; i < rowCount; i++) *preserialized << (*fStrValues)[i]; } } @@ -84,7 +86,7 @@ void TableColumn::serialize() /** @brief serializes the object into the passed byte stream. */ -void TableColumn::serialize(messageqcpp::ByteStream& b) +void TableColumn::serialize(messageqcpp::ByteStream& b) { if (preserialized->length() != 0) { b += *preserialized; @@ -119,7 +121,7 @@ void TableColumn::serialize(messageqcpp::ByteStream& b) else if(fColumnType == STRING) { rowCount = fStrValues->size(); b << rowCount; - for(uint32_t i = 0; i < rowCount; i++) + for(uint i = 0; i < rowCount; i++) b << (*fStrValues)[i]; } } @@ -160,13 +162,13 @@ void TableColumn::unserialize(messageqcpp::ByteStream& b) { if (columnType != STRING) fIntValues.reset(new std::vector()); - /* XXXPAT: A switch on fColumnType is more concise, but I suspect this is + /* XXXPAT: A switch on fColumnType is more concise, but I suspect this is a little faster b/c of fewer jumps in the loop. Since it's a row-by-row operation, it has to scream. */ if (columnType == UINT8) { // cout << "UN (" << oid << "): is an 8\n"; fIntValues->reserve(rowCount); - for (uint32_t i = 0; i < rowCount; ++i) { + for (uint i = 0; i < rowCount; ++i) { b >> val8; // cout << "UN (" << oid << "): " << (int) val8 << " at " << i << endl; fIntValues->push_back(val8); @@ -175,7 +177,7 @@ void TableColumn::unserialize(messageqcpp::ByteStream& b) { else if (columnType == UINT16) { // cout << "UN (" << oid << "): is a 16\n"; fIntValues->reserve(rowCount); - for (uint32_t i = 0; i < rowCount; ++i) { + for (uint i = 0; i < rowCount; ++i) { b >> val16; // cout << "UN (" << oid << "): " << val16 << " at " << i << endl; fIntValues->push_back(val16); @@ -184,7 +186,7 @@ void TableColumn::unserialize(messageqcpp::ByteStream& b) { else if (columnType == UINT32) { // cout << "UN (" << oid << "): is a 32\n"; fIntValues->reserve(rowCount); - for (uint32_t i = 0; i < rowCount; ++i) { + for (uint i = 0; i < rowCount; ++i) { b >> val32; // cout << "UN (" << oid << "): " << val32 << " at " << i << endl; fIntValues->push_back(val32); @@ -199,7 +201,7 @@ void TableColumn::unserialize(messageqcpp::ByteStream& b) { fStrValues.reset(new std::vector()); fStrValues->reserve(rowCount); std::string value; - for(uint32_t i = 0; i < rowCount; i++) { + for(uint i = 0; i < rowCount; i++) { b >> value; // cout << "UN: " << value << endl; fStrValues->push_back(value); @@ -223,9 +225,9 @@ void TableColumn::addToSysDataList(execplan::CalpontSystemCatalog::NJLSysDataLis sysDataList.push_back(cr); } if(fColumnType == UINT64) { - uint32_t vsize = fIntValues->size(); + uint vsize = fIntValues->size(); bool putRids = (rids.size() == vsize); - for(uint32_t i = 0; i < vsize; i++) { + for(uint i = 0; i < vsize; i++) { cr->PutData((*fIntValues)[i]); if(putRids) { cr->PutRid(rids[i]); @@ -236,9 +238,9 @@ void TableColumn::addToSysDataList(execplan::CalpontSystemCatalog::NJLSysDataLis } } else { - uint32_t vsize = fStrValues->size(); + uint vsize = fStrValues->size(); bool putRids = (rids.size() == vsize); - for(uint32_t i = 0; i < vsize; i++) { + for(uint i = 0; i < vsize; i++) { cr->PutStringData((*fStrValues)[i]); if(putRids) { cr->PutRid(rids[i]); @@ -250,7 +252,7 @@ void TableColumn::addToSysDataList(execplan::CalpontSystemCatalog::NJLSysDataLis } } #if 0 -void TableColumn::addToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList, const std::vector& rids) +void TableColumn::addToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList, const std::vector& rids) { execplan::ColumnResult *cr; @@ -264,10 +266,10 @@ void TableColumn::addToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataLis sysDataList.push_back(cr); } - uint32_t vsize = (fIntValues) ? fIntValues->size() : fStrValues->size(); + uint vsize = (fIntValues) ? fIntValues->size() : fStrValues->size(); bool putRids = (rids.size() == vsize); - for(uint32_t i = 0; i < vsize; i++) { + for(uint i = 0; i < vsize; i++) { if(putRids) { cr->PutRidOnly(rids[i]); } @@ -275,7 +277,7 @@ void TableColumn::addToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataLis cr->PutRidOnly(0); } } - + } #endif diff --git a/dbcon/joblist/tablecolumn.h b/dbcon/joblist/tablecolumn.h index 218f3a68..1c73453a 100644 --- a/dbcon/joblist/tablecolumn.h +++ b/dbcon/joblist/tablecolumn.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: tablecolumn.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: tablecolumn.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ @@ -35,7 +35,7 @@ //#define TC_CHECK_RIDS 1 -#if defined(_MSC_VER) && defined(JOBLIST_DLLEXPORT) +#if defined(_MSC_VER) && defined(TABLECOLUMN_DLLEXPORT) #define EXPORT __declspec(dllexport) #else #define EXPORT @@ -64,10 +64,10 @@ class TableColumn { UNDEFINED }; - /** @brief constructor + /** @brief constructor */ EXPORT TableColumn(const execplan::CalpontSystemCatalog::OID columnOID, const supportedType columnType); - + EXPORT TableColumn(); /** @brief getter for the column's OID. @@ -77,7 +77,7 @@ class TableColumn { /** @brief getter for the column's values. */ inline const boost::shared_ptr > getIntValues() { return fIntValues; } - + inline const boost::shared_ptr > getStrValues() { return fStrValues; } inline bool isNullColumn() const { return fIsNullColumn; } @@ -88,24 +88,24 @@ class TableColumn { /** @brief serializes the object into the passed byte stream. */ EXPORT void serialize(messageqcpp::ByteStream& b); - + /** @brief inflates the object from the passed byte stream. */ EXPORT void unserialize(messageqcpp::ByteStream& b); - + /** @brief adds the column and it's values to the passed NJLSysDataList or appends the values if the column is already included in the NJLSysDataList. */ EXPORT void addToSysDataList(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList, const std::vector& rids); #if 0 - EXPORT void addToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList, const std::vector& rids); + EXPORT void addToSysDataRids(execplan::CalpontSystemCatalog::NJLSysDataList& sysDataList, const std::vector& rids); #endif inline void setIntValues(boost::shared_ptr > sv) { fIntValues = sv; fIsNullColumn = fIntValues->empty(); } - + inline void setStrValues(boost::shared_ptr > sv) { fStrValues = sv; diff --git a/dbcon/joblist/tdriver-agg.cpp b/dbcon/joblist/tdriver-agg.cpp index f25fd501..4ae34a78 100644 --- a/dbcon/joblist/tdriver-agg.cpp +++ b/dbcon/joblist/tdriver-agg.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: tdriver-agg.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: tdriver-agg.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -101,7 +101,7 @@ void timespec_sub(const struct timespec &tv1, const struct timespec &tv2, int threadNumber = parms->threadNumber; int64_t i; ElementType val; - uint32_t it; + uint it; int bucketIndex; int cnt = 0; @@ -126,7 +126,7 @@ void timespec_sub(const struct timespec &tv1, const struct timespec &tv2, int i; //ElementType val; TupleType val; - uint32_t it; + uint it; int bucketIndex; int cnt = 0; @@ -187,13 +187,13 @@ class TupleComparator1 void *aggregator(void *arg) { - uint32_t fHashLen = 4; + uint fHashLen = 4; TupleType tt; tt.second = new char[fHashLen]; ThreadParms *parms = reinterpret_cast(arg); int threadNumber = parms->threadNumber; struct timespec ts1, ts2, diff; - uint32_t size = 585938; + uint size = 585938; #if 0 //typedef std::vector RIDVec; typedef std::pair Results; @@ -214,13 +214,13 @@ class TupleComparator1 Hasher hasher; bool flag = true; - for (uint32_t k = 0; k < NUM_BUCKETS/4; k++) + for (uint k = 0; k < NUM_BUCKETS/4; k++) { clock_gettime(CLOCK_REALTIME, &ts1); - for (uint32_t j = 0; j < 4; j++) + for (uint j = 0; j < 4; j++) { - for (uint32_t i = 0; i < size/10; i++) + for (uint i = 0; i < size/10; i++) { flag = true; memcpy(tt.second, &i, 4); @@ -282,12 +282,12 @@ class TupleComparator1 Results rr; uint32_t val = 0; - for (uint32_t k = 0; k < NUM_BUCKETS/4; k++) + for (uint k = 0; k < NUM_BUCKETS/4; k++) { clock_gettime(CLOCK_REALTIME, &ts1); - for (uint32_t j = 0; j < 4; j++) + for (uint j = 0; j < 4; j++) { - for (uint32_t i = 0; i < size/10; i++) + for (uint i = 0; i < size/10; i++) { memcpy(tt.second, &i, 4); iter = shmp->find(tt.second); @@ -339,12 +339,12 @@ class TupleComparator1 int64_t rr; uint32_t val = 0; - for (uint32_t k = 0; k < NUM_BUCKETS/4; k++) + for (uint k = 0; k < NUM_BUCKETS/4; k++) { clock_gettime(CLOCK_REALTIME, &ts1); - for (uint32_t j = 0; j < 4; j++) + for (uint j = 0; j < 4; j++) { - for (uint32_t i = 0; i < size/10; i++) + for (uint i = 0; i < size/10; i++) { memcpy(tt.second, &i, 4); vt.push_back(tt); @@ -400,7 +400,7 @@ class TupleComparator1 TupleBucketDataList *tbdl = parms->tbdl; TupleType t; vector vt; - for (uint32_t i = 0; i < 150000000; i++) + for (uint i = 0; i < 150000000; i++) { t.first = i; t.second = new char[4]; @@ -423,7 +423,7 @@ class TupleComparator1 TupleType t; ElementType e; vector vt; - for (uint32_t i = 0; i < 150000000; i++) + for (uint i = 0; i < 150000000; i++) { e.first = i; e.second = i; @@ -534,7 +534,7 @@ typedef boost::shared_ptr SSFP; if (v.size() > 0) { tbdl->insert(v); - //for (uint32_t i = 0; i < v.size(); i++) + //for (uint i = 0; i < v.size(); i++) // delete [] (v[i].second); v.clear(); } @@ -621,7 +621,7 @@ typedef boost::shared_ptr SSFP; ThreadParms producerThreadParms[4]; timer1.start("insert-tbdl"); - for (uint32_t i = 0; i < 4; i++) + for (uint i = 0; i < 4; i++) { producerThreadParms[i].tbdl = tbdl; producerThreadParms[i].threadNumber = i; @@ -629,7 +629,7 @@ typedef boost::shared_ptr SSFP; pthread_create(&producer[i], NULL, TBDL_producer, &producerThreadParms[i]); } - for (uint32_t i = 0; i < 4; i++) + for (uint i = 0; i < 4; i++) pthread_join(producer[i], NULL); tbdl->endOfInput(); timer1.stop("insert-tbdl"); @@ -647,7 +647,7 @@ typedef boost::shared_ptr SSFP; ThreadParms producerThreadParms[4]; timer1.start("insert-bdl"); - for (uint32_t i = 0; i < 4; i++) + for (uint i = 0; i < 4; i++) { producerThreadParms[i].bdl = bdl; producerThreadParms[i].threadNumber = i; @@ -655,7 +655,7 @@ typedef boost::shared_ptr SSFP; pthread_create(&producer[i], NULL, BDL_producer, &producerThreadParms[i]); } - for (uint32_t i = 0; i < 4; i++) + for (uint i = 0; i < 4; i++) pthread_join(producer[i], NULL); bdl->endOfInput(); timer1.stop("insert-bdl"); @@ -708,7 +708,7 @@ typedef boost::shared_ptr SSFP; if (v.size() == 2048) { tbdl->insert(v); - for (uint32_t i = 0; i < v.size(); i++) + for (uint i = 0; i < v.size(); i++) v[i].deleter(); v.clear(); } @@ -721,7 +721,7 @@ typedef boost::shared_ptr SSFP; if (v.size() > 0) { tbdl->insert(v); - for (uint32_t i = 0; i < v.size(); i++) + for (uint i = 0; i < v.size(); i++) delete [] (v[i].second); v.clear(); } @@ -1043,7 +1043,7 @@ typedef boost::shared_ptr SSFP; memset(a,0,5*1024*1024); memcpy(&tm, a, 4); } - uint32_t fHashLen = 4; + uint fHashLen = 4; TupleType tt; tt.second = new char[fHashLen]; uint64_t size = 585937; @@ -1193,7 +1193,7 @@ typedef boost::shared_ptr SSFP; #if 0 void hashmap_tuple_multi() { - uint32_t fHashLen = 4; + uint fHashLen = 4; TupleHasher tupleHash(fHashLen); TupleComparator tupleComp(fHashLen); TupleType tt; @@ -1212,7 +1212,7 @@ typedef boost::shared_ptr SSFP; Hasher fHasher; timer1.start("multi_insert"); - uint32_t i = 0, j = 0; + uint i = 0, j = 0; uint32_t val = 0; for ( j = 0; j < 4; j++) @@ -1234,7 +1234,7 @@ typedef boost::shared_ptr SSFP; char* key; if (iter != shmp->end()) key = iter->first; - uint32_t ct = 0; + uint ct = 0; for (iter = ++iter; iter != shmp->end(); iter++) { if (memcmp(iter->first, key, 4) == 0) diff --git a/dbcon/joblist/tdriver-bdl.cpp b/dbcon/joblist/tdriver-bdl.cpp index c0048354..1a264076 100644 --- a/dbcon/joblist/tdriver-bdl.cpp +++ b/dbcon/joblist/tdriver-bdl.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: tdriver-bdl.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: tdriver-bdl.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -225,11 +225,11 @@ CPPUNIT_TEST_SUITE_END(); eofInputTag += testDesc; consumeTag += testDesc; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; - uint32_t numBuckets = NUM_BUCKETS; - uint32_t maxElements = MAX_ELEMENTS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; + uint numBuckets = NUM_BUCKETS; + uint maxElements = MAX_ELEMENTS; BucketDL bdl(numBuckets, 1, maxElements); bdl.setMultipleProducers(true); bdl.setElementMode(1); // RID_VALUE @@ -323,11 +323,11 @@ CPPUNIT_TEST_SUITE_END(); eofInputTag += testDesc; consumeTag += testDesc; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; - uint32_t numBuckets = NUM_BUCKETS; - uint32_t maxElements = MAX_ELEMENTS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; + uint numBuckets = NUM_BUCKETS; + uint maxElements = MAX_ELEMENTS; BucketDL bdl(numBuckets, 1, maxElements); bdl.setMultipleProducers(true); if ( compress ) @@ -405,7 +405,7 @@ CPPUNIT_TEST_SUITE_END(); typedef ElementType Element; vector v; - for (uint32_t i = 0; i < ::count; i++) + for (uint i = 0; i < ::count; i++) v.push_back(Element(i,i)); vector v1; diff --git a/dbcon/joblist/tdriver-bru.cpp b/dbcon/joblist/tdriver-bru.cpp index 98f33f30..ab65c663 100644 --- a/dbcon/joblist/tdriver-bru.cpp +++ b/dbcon/joblist/tdriver-bru.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: tdriver-bru.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: tdriver-bru.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/joblist/tdriver-datalist.cpp b/dbcon/joblist/tdriver-datalist.cpp index 2327f25b..ea9acc79 100644 --- a/dbcon/joblist/tdriver-datalist.cpp +++ b/dbcon/joblist/tdriver-datalist.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver-datalist.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver-datalist.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include #include #include @@ -67,7 +67,7 @@ int buckets = 16; // # of buckets to use in bucketDL tests. class BandGrouper { public: - uint32_t operator()(const char *data, uint32_t len) const + uint32_t operator()(const char *data, uint len) const { stringstream ss(string(data, len)); ElementType dle; @@ -101,7 +101,7 @@ void *MP_FIFO_stress_producer(void *arg) uint64_t id = ::pCount++; // cout << "producer " << id << " started" << endl; - for (i = 0; i < (uint32_t) ::count/10; i++) { + for (i = 0; i < (uint) ::count/10; i++) { val.first = (id << 60) | i; val.second = val.first; f->insert(val); @@ -202,7 +202,7 @@ void *FIFO_2_helper(void *arg) void *WSDL_2_helper(void *arg) { WSDL *w = reinterpret_cast *>(arg); - uint32_t i, id; + uint i, id; bool nextRet; ElementType dle; @@ -220,7 +220,7 @@ void *WSDL_2_helper(void *arg) void *BandedDL_1_helper(void *arg) { BandedDL *w = reinterpret_cast *>(arg); - uint32_t i, id; + uint i, id; bool nextRet; ElementType dle; @@ -238,7 +238,7 @@ void *BandedDL_1_helper(void *arg) void *BandedDL_2_helper(void *arg) { BandedDL *w = reinterpret_cast *>(arg); - uint32_t i, id; + uint i, id; bool nextRet; StringElementType dle; @@ -558,7 +558,7 @@ CPPUNIT_TEST_SUITE_END(); { WSDL w(1, ::count/100); ElementType dle; - uint32_t i, id; + uint i, id; bool nextRet; for (i = 0; i < ::count; i++) { @@ -581,7 +581,7 @@ CPPUNIT_TEST_SUITE_END(); { WSDL w(2, ::count/10); ElementType dle; - uint32_t i, id, size; + uint i, id, size; bool nextRet; pthread_t consumer1; @@ -616,7 +616,7 @@ CPPUNIT_TEST_SUITE_END(); { WSDL w(1, ::count/10); StringElementType dle; - uint32_t i, id; + uint i, id; bool nextRet; for (i = 0; i < ::count; i++) { @@ -731,7 +731,7 @@ CPPUNIT_TEST_SUITE_END(); int i, id; ElementType e; bool nextRet; - uint32_t numOfThreads = 8; + uint numOfThreads = 8; pthread_t producer[numOfThreads]; struct timespec ts1, ts2, diff; @@ -767,10 +767,10 @@ CPPUNIT_TEST_SUITE_END(); SWSDL sw(4); sw.setMultipleProducers(true); ElementType dle; - uint32_t i, id; + uint i, id; bool nextRet; - uint32_t numOfProducers = 8; - uint32_t numOfConsumers = 4; + uint numOfProducers = 8; + uint numOfConsumers = 4; pthread_t producer[numOfProducers]; pthread_t consumer[numOfConsumers]; struct timespec ts1, ts2, diff; @@ -802,9 +802,9 @@ CPPUNIT_TEST_SUITE_END(); BandedDL w(2); w.setMultipleProducers(true); ElementType dle; - uint32_t i, id; + uint i, id; bool nextRet; - uint32_t numOfThreads = 8; + uint numOfThreads = 8; pthread_t producer[numOfThreads]; struct timespec ts1, ts2, diff; @@ -861,9 +861,9 @@ CPPUNIT_TEST_SUITE_END(); BandedDL w(2); w.setMultipleProducers(true); ElementType dle; - uint32_t i, id; + uint i, id; bool nextRet; - uint32_t numOfThreads = 8; + uint numOfThreads = 8; pthread_t producer[numOfThreads]; pthread_t consumer; struct timespec ts1, ts2, diff; @@ -981,7 +981,7 @@ CPPUNIT_TEST_SUITE_END(); { BucketDL bdl(16, 1, ::count/100); ElementType dle; - uint32_t i, it, eCount = 0, buckets; + uint i, it, eCount = 0, buckets; bool nextRet; for (i = 0; i < ::count; i++) { @@ -1010,7 +1010,7 @@ CPPUNIT_TEST_SUITE_END(); { BandedDL w(2); ElementType dle; - uint32_t i, id, size; + uint i, id, size; bool nextRet; pthread_t consumer1; @@ -1049,7 +1049,7 @@ CPPUNIT_TEST_SUITE_END(); { BandedDL w(2); StringElementType dle; - uint32_t i, id, size; + uint i, id, size; bool nextRet; pthread_t consumer1; @@ -1098,7 +1098,7 @@ CPPUNIT_TEST_SUITE_END(); { BandedDL bdl(1); ElementType e; - uint32_t i, it; + uint i, it; bool more; for (i = 1; i <= ::count; i++) { @@ -1135,7 +1135,7 @@ CPPUNIT_TEST_SUITE_END(); void BandedDL_as_WSDL_2() { BucketDL bucketDL(::buckets, 1, 1000, BandGrouper()); - uint32_t last, i, it; + uint last, i, it; ElementType dle; bool more; @@ -1176,10 +1176,10 @@ CPPUNIT_TEST_SUITE_END(); ZDL zdl(4); zdl.setMultipleProducers(true); ElementType dle; - uint32_t i, id; + uint i, id; bool nextRet; - uint32_t numOfProducers = 8; - uint32_t numOfConsumers = 4; + uint numOfProducers = 8; + uint numOfConsumers = 4; pthread_t producer[numOfProducers]; pthread_t consumer[numOfConsumers]; struct timespec ts1, ts2, diff; diff --git a/dbcon/joblist/tdriver-dec.cpp b/dbcon/joblist/tdriver-dec.cpp index 91a0e1ba..5adbf6af 100644 --- a/dbcon/joblist/tdriver-dec.cpp +++ b/dbcon/joblist/tdriver-dec.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver-dec.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver-dec.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include #include #include diff --git a/dbcon/joblist/tdriver-deliver.cpp b/dbcon/joblist/tdriver-deliver.cpp index 89985560..2457bf06 100644 --- a/dbcon/joblist/tdriver-deliver.cpp +++ b/dbcon/joblist/tdriver-deliver.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: tdriver-deliver.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: tdriver-deliver.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ @@ -56,7 +56,7 @@ int fifoSize = 128; int startingOid = 3416; // Oid for lineitem.l_orderkey on your database. // uint32_t flushInterval = 16384; // interval used in flushing table bands uint32_t flushInterval = 16384; // interval used in flushing table bands -uint32_t columns; +uint columns; Stopwatch timer; @@ -101,7 +101,7 @@ class BSQueueMgr * * @return Next projected table band. Row count of 0 marks end of data */ - messageqcpp::ByteStream* getNextByteStream(uint32_t &rowCount); + messageqcpp::ByteStream* getNextByteStream(uint &rowCount); private: //Disable these by declaring but not defining @@ -110,7 +110,7 @@ class BSQueueMgr struct QueueElement { messageqcpp::ByteStream *bs; - uint32_t rowCount; + uint rowCount; }; DeliveryStep *ds; @@ -164,7 +164,7 @@ void BSQueueMgr::project ( ) while ( moreData ) { - uint32_t rowCount; + uint rowCount; QueueElement qe; qe.bs = new ByteStream; @@ -196,7 +196,7 @@ void BSQueueMgr::project ( ) // Returns next projected table band. A row count of 0, marks the table // band as being the last. //------------------------------------------------------------------------------ -ByteStream * BSQueueMgr::getNextByteStream(uint32_t &rowCount) +ByteStream * BSQueueMgr::getNextByteStream(uint &rowCount) { QueueElement qe; @@ -717,7 +717,7 @@ void *nextBandBenchProducer(void *arg) FIFO* dl1 = (FIFO*) arg; UintRowGroup rg; uint64_t *arr; - uint32_t i; + uint i; arr = (uint64_t*) rg.et; for (i = 0; i < 8192; ++i) @@ -737,7 +737,7 @@ void nextBandBenchmark() { ByteStream bs; pthread_t threads[columns]; - uint32_t i, rowCount = 1; + uint i, rowCount = 1; JobStepAssociation inJs; for (i = 0; i < columns; ++i) { @@ -774,7 +774,7 @@ void queuedBSBenchmark(int queueLength) { ByteStream *bs; pthread_t threads[columns]; - uint32_t i, rowCount = 1; + uint i, rowCount = 1; JobStepAssociation inJs; for (i = 0; i < columns; ++i) { diff --git a/dbcon/joblist/tdriver-filter.cpp b/dbcon/joblist/tdriver-filter.cpp index 6fb71344..1c3f84c3 100644 --- a/dbcon/joblist/tdriver-filter.cpp +++ b/dbcon/joblist/tdriver-filter.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver-filter.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver-filter.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include #include diff --git a/dbcon/joblist/tdriver-function.cpp b/dbcon/joblist/tdriver-function.cpp index f86734c4..b41e896a 100644 --- a/dbcon/joblist/tdriver-function.cpp +++ b/dbcon/joblist/tdriver-function.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver-function.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver-function.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include #include #include @@ -140,7 +140,7 @@ class MultiTimer { total.fStartCount = 1; fProcessStats.push_back(total); - for(uint32_t i = 0; i < fProcessStats.size(); i++) { + for(uint i = 0; i < fProcessStats.size(); i++) { if(i == (fProcessStats.size() - 1)) { cout << endl; @@ -216,8 +216,8 @@ class MultiTimer { void MultiTimer::stop(const string& message) { bool found = false; - uint32_t idx = 0; - for(uint32_t i = 0; i < fProcessStats.size(); i++) { + uint idx = 0; + for(uint i = 0; i < fProcessStats.size(); i++) { if(fProcessStats[i].fProcess == message) { idx = i; found = true; @@ -232,13 +232,13 @@ void MultiTimer::stop(const string& message) { void MultiTimer::start(const string& message) { bool found = false; - uint32_t idx = 0; + uint idx = 0; ProcessStats processStats; if(!fStarted) { fStarted = true; gettimeofday(&fTvStart, 0); } - for(uint32_t i = 0; i < fProcessStats.size(); i++) { + for(uint i = 0; i < fProcessStats.size(); i++) { if(fProcessStats[i].fProcess == message) { idx = i; found = true; @@ -541,7 +541,7 @@ CPPUNIT_TEST_SUITE_END(); // double list WSDL* wsdlInD1 = new WSDL(20, numRows, fRm); WSDL* wsdlInD2 = new WSDL(20, numRows, fRm); - // uint32_t list + // uint list WSDL* wsdlInU1 = new WSDL(20, numRows, fRm); WSDL* wsdlInU2 = new WSDL(20, numRows, fRm); // string list @@ -602,7 +602,7 @@ CPPUNIT_TEST_SUITE_END(); } } - // double add(double, uint32_t) + // double add(double, uint) { DoubleElementType el0, el1; ElementType el2; @@ -666,7 +666,7 @@ CPPUNIT_TEST_SUITE_END(); } } - // double add(uint32_t, double) + // double add(uint, double) { DoubleElementType el0, el2; ElementType el1; @@ -698,7 +698,7 @@ CPPUNIT_TEST_SUITE_END(); } } - // double add(uint32_t, uint32_t) + // double add(uint, uint) { DoubleElementType el0; ElementType el1, el2; @@ -730,7 +730,7 @@ CPPUNIT_TEST_SUITE_END(); } } - // double add(uint32_t, string) + // double add(uint, string) { DoubleElementType el0; ElementType el1; @@ -795,7 +795,7 @@ CPPUNIT_TEST_SUITE_END(); } } - // double add(string, uint32_t) + // double add(string, uint) { DoubleElementType el0; StringElementType el1; diff --git a/dbcon/joblist/tdriver-hashjoin.cpp b/dbcon/joblist/tdriver-hashjoin.cpp index 3b7b9dca..e6a197fa 100644 --- a/dbcon/joblist/tdriver-hashjoin.cpp +++ b/dbcon/joblist/tdriver-hashjoin.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver-hashjoin.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver-hashjoin.cpp 8436 2012-04-04 18:18:21Z rdempsey $ // // C++ Implementation: testhasjoin // diff --git a/dbcon/joblist/tdriver-index.cpp b/dbcon/joblist/tdriver-index.cpp index f5ed60d1..d6060a1e 100644 --- a/dbcon/joblist/tdriver-index.cpp +++ b/dbcon/joblist/tdriver-index.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: tdriver-index.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: tdriver-index.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ /* diff --git a/dbcon/joblist/tdriver-jobstep.cpp b/dbcon/joblist/tdriver-jobstep.cpp index 5ca87716..536fb380 100644 --- a/dbcon/joblist/tdriver-jobstep.cpp +++ b/dbcon/joblist/tdriver-jobstep.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: tdriver-jobstep.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: tdriver-jobstep.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ diff --git a/dbcon/joblist/tdriver-pdict.cpp b/dbcon/joblist/tdriver-pdict.cpp index 8d33cdff..99fcdc91 100644 --- a/dbcon/joblist/tdriver-pdict.cpp +++ b/dbcon/joblist/tdriver-pdict.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: tdriver-pdict.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: tdriver-pdict.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * ****************************************************************************/ @@ -53,7 +53,7 @@ CPPUNIT_TEST_SUITE_END(); DistributedEngineComm* dec; boost::shared_ptr cat; ElementType e; - uint32_t i, it; + uint i, it; bool more; BRM::DBRM dbrm; const uint32_t dictOID=2064; @@ -82,7 +82,7 @@ CPPUNIT_TEST_SUITE_END(); // populate the element pair UintRowGroup rw; - const uint32_t tcount=10; + const uint tcount=10; for (i = 1; i <= tcount; i++) { WriteEngine::Token token; // rid token.op=i; // index of sig in block diff --git a/dbcon/joblist/tdriver-tableband.cpp b/dbcon/joblist/tdriver-tableband.cpp new file mode 100644 index 00000000..3d69b78a --- /dev/null +++ b/dbcon/joblist/tdriver-tableband.cpp @@ -0,0 +1,559 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// $Id: tdriver-tableband.cpp 8436 2012-04-04 18:18:21Z rdempsey $ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fifo.h" + +#include "calpontsystemcatalog.h" +using namespace execplan; + +#include "tablecolumn.h" +#include "tableband.h" +#include +#include +#include "bytestream.h" +#include +#include +#include + +#define DEBUG + +using namespace std; +using namespace joblist; +using namespace messageqcpp; + +// Timer class used by this tdriver to output elapsed times, etc. +class Timer { + public: + void logMessage(const string& message) { + time_t now; + time(&now); + string secondsElapsed; + getTimeElapsed(secondsElapsed); + if(fLogCount == 0) { + if(!fSuppressLogMessages) { + cout << endl; + cout << " Total" << endl; + cout << "Time Seconds Message" << endl; + } + fStarted = now; + fLastLogged = now; + } + if(!fSuppressLogMessages) { + cout << timestr() << " " << secondsElapsed << " " << message << endl; + } + fLogCount++; + } + + void logNewTest(const string& message) { + fLogCount = 0; + + } + + void startTimer() { + gettimeofday(&fTvStart, 0); + } + + double getTimeElapsed(string& seconds) { + struct timeval tvStop; + gettimeofday(&tvStop, 0); + double secondsElapsed = + (tvStop.tv_sec + (tvStop.tv_usec / 1000000.0)) - + (fTvStart.tv_sec + (fTvStart.tv_usec / 1000000.0)); + ostringstream oss; + oss << secondsElapsed; + seconds = oss.str(); + return secondsElapsed; + } + + void setSuppressLogMessages(const bool& suppressLogMessages) { + fSuppressLogMessages = suppressLogMessages; + } + + private: + + time_t fStarted; + time_t fLastLogged; + int fLogCount; + struct timeval fTvStart; + bool fSuppressLogMessages; + + string timestr() + { + struct tm tm; + struct timeval tv; + + gettimeofday(&tv, 0); + localtime_r(&tv.tv_sec, &tm); + + ostringstream oss; + oss << setfill('0') + << setw(2) << tm.tm_hour << ':' + << setw(2) << tm.tm_min << ':' + << setw(2) << tm.tm_sec << '.' + << setw(6) << tv.tv_usec + ; + return oss.str(); + } +}; +Timer timer; + +// Timer class used by this tdriver to output elapsed times, etc. +class MultiTimer { + + + public: + void start(const string& message); + void stop(const string& message); + void finish() { + + // Calculate the total seconds elapsed. + struct timeval tvStop; + gettimeofday(&tvStop, 0); + double totalSeconds = + (tvStop.tv_sec + (tvStop.tv_usec / 1000000.0)) - + (fTvStart.tv_sec + (fTvStart.tv_usec / 1000000.0)); + + cout << endl; + cout << "Seconds Percentage Calls Description" << endl; + + // Add a last entry into the vector for total. + ProcessStats total; + total.fTotalSeconds = totalSeconds; + total.fProcess = "Total"; + total.fStartCount = 1; + fProcessStats.push_back(total); + + for(uint i = 0; i < fProcessStats.size(); i++) { + + if(i == (fProcessStats.size() - 1)) { + cout << endl; + } + + // Seconds. + string seconds; + ostringstream oss; + oss << fProcessStats[i].fTotalSeconds; + seconds = oss.str(); + seconds.resize(7, '0'); + cout << seconds << " "; + + // Percentage. + string percentage; + ostringstream oss2; + oss2 << (fProcessStats[i].fTotalSeconds / totalSeconds) * 100.0; + percentage = oss2.str(); + percentage.resize(5, ' '); + cout << percentage << "% "; + + // Times Initiated. + ostringstream oss3; + oss3 << fProcessStats[i].fStartCount; + string timesInitiated = oss3.str(); + timesInitiated.resize(10, ' '); + cout << timesInitiated << " "; + + // Description. + cout << fProcessStats[i].fProcess << endl; + } + + + + } + MultiTimer() : fStarted(false) {}; + + private: + class ProcessStats + { + public: + + string fProcess; + struct timeval fTvProcessStarted; + double fTotalSeconds; + long fStartCount; + long fStopCount; + + ProcessStats() : fProcess(""), fTotalSeconds(0.0), fStartCount(0), fStopCount(0) {}; + + void processStart() + { + gettimeofday(&fTvProcessStarted, 0); + fStartCount++; + } + + void processStop() + { + struct timeval tvStop; + gettimeofday(&tvStop, 0); + fStopCount++; + fTotalSeconds += + (tvStop.tv_sec + (tvStop.tv_usec / 1000000.0)) - + (fTvProcessStarted.tv_sec + (fTvProcessStarted.tv_usec / 1000000.0)); + + } + }; + + struct timeval fTvStart; + vector fProcessStats; + bool fStarted; +}; + +void MultiTimer::stop(const string& message) { + bool found = false; + uint idx = 0; + for(uint i = 0; i < fProcessStats.size(); i++) { + if(fProcessStats[i].fProcess == message) { + idx = i; + found = true; + break; + } + } + if(!found) { + throw std::runtime_error("MultiTimer::stop " + message + " called without calling start first."); + } + fProcessStats[idx].processStop(); +} + +void MultiTimer::start(const string& message) { + bool found = false; + uint idx = 0; + ProcessStats processStats; + if(!fStarted) { + fStarted = true; + gettimeofday(&fTvStart, 0); + } + for(uint i = 0; i < fProcessStats.size(); i++) { + if(fProcessStats[i].fProcess == message) { + idx = i; + found = true; + break; + } + } + if(!found) { + fProcessStats.push_back(processStats); + idx = fProcessStats.size() - 1; + } + fProcessStats[idx].fProcess = message; + fProcessStats[idx].processStart(); +} + +// Creates a FIFO datalist containing a uint64_t column and adds it to the passed TableBand object. +// Args: +// colOID - The column OID. +// size - The number of rows. +// band - The TableBand to which the column will be added. +void addInt64FifoToBand(CalpontSystemCatalog::OID colOID, const int& size, TableBand& band) { + + timer.logMessage("Creating and populating FIFO."); + FIFO fifo(1, size); + int i; + ElementType element; + for(i = 0; i < size; i++) { + element.first = i; + element.second = i; + fifo.insert(element); + } + fifo.endOfInput(); + + timer.logMessage("Adding column to band."); + band.addColumn(colOID, &fifo); +} + +// Creates a FIFO datalist containing a string column and adds it to the passed TableBand object. +// Args: +// colOID - The column OID. +// size - The number of rows. +// band - The TableBand to which the column will be added. + + +// Compares two instances of TableColumn to verify that they containt the same column and values. +template +void validateColumnsMatch(TableColumn& col1, TableColumn& col2) { + CPPUNIT_ASSERT(col1.getColumnOID() == col2.getColumnOID()); + for(uint i = 0; i < col1.getValues().size(); i++) { + CPPUNIT_ASSERT(col1.getValues()[i] == col2.getValues()[i]); + // cout << "Row " << i << " has a value of " << col1.getValues()[i] << endl; + } +} + +// Function bandTest +// +// Purpose: +// Performs a bandTest by doing the following: +// 1) Creates a band of four columns (40 bytes per row) with the number of rows passed in the size argument. +// 2) Serializes the band to a byte stream +// 3) Creates another instance of the band from the bytesteam +// 4) Verifies that the two bands are the same. +// +// Arguments: +// size - the number of rows to place in the band. +void bandTest(const int& size) { + // cout << endl; + // cout << "-------------------------------------------------------------" << endl; + TableBand band; + // int size = 30000; // (30000 rows * 40 bytes / row = about 1200000 bytes in a band) + + // 8 + 12 + 12 + 8 = 40 bytes per row. + addInt64FifoToBand(1, size, band); +// addStringFifoToBand(2, size, band); +// addStringFifoToBand(3, size, band); + addInt64FifoToBand(2, size, band); + + timer.logMessage("Serializing band."); + messageqcpp::ByteStream b; + band.serialize(b); + + TableBand band2; + timer.logMessage("Unserializing band."); + band2.unserialize(b); + + timer.logMessage("Validating results."); + CPPUNIT_ASSERT(band.tableOID() == band2.tableOID()); + CPPUNIT_ASSERT(band.getColumnCount() == band2.getColumnCount()); + CPPUNIT_ASSERT(band.getRowCount() == band2.getRowCount()); + + for(uint i = 0; i < band.getColumns().size(); i++) { + if(typeid(TableColumn) == band.getColumns()[i].type()) { + TableColumn col1 = + boost::any_cast > (band.getColumns()[i]); + TableColumn col2 = + boost::any_cast > (band2.getColumns()[i]); + validateColumnsMatch(col1, col2); + } + else if(typeid(TableColumn) == band.getColumns()[i].type()) { + TableColumn col1 = + boost::any_cast > (band.getColumns()[i]); + TableColumn col2 = + boost::any_cast > (band2.getColumns()[i]); + validateColumnsMatch(col1, col2); + } + } + timer.logMessage("All done."); +} + +class DataListDriver : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE(DataListDriver); + + CPPUNIT_TEST(BAND_TEST2); +// CPPUNIT_TEST(MULTI_BAND_TEST); +// CPPUNIT_TEST(BAD_BAND_TEST); +// CPPUNIT_TEST(CONVERT_TO_SYSDATA_TEST); + +CPPUNIT_TEST_SUITE_END(); + +private: +public: + + // Tests a band by and outputs elapsed times for each step of the test. + void BAND_TEST() + { + + int rowsPerBand = 27000; // 40 * 27000 = 1,080,000 bytes (a little over 1MB) + cout << endl; + cout << "Testing Load of " << rowsPerBand << " rows." << endl; + cout << "-------------------------------------------------------------" << endl; + + timer.startTimer(); + bandTest(rowsPerBand); + } + + void BAND_TEST2() + { + int rowcount = 2500000; + int bandSize = 8192; + int columnCount = 9; + int rowsRemaining = rowcount; + MultiTimer timer; + + while(rowsRemaining > 0) + { + + // Create banded Ds + string message = "Creating BandedDLs."; + timer.start(message); + + BandedDataList* bandedDLs[columnCount]; + + for(int i = 0; i < columnCount; i++) + { + bandedDLs[i] = new BandedDataList(1); + bandedDLs[i]->OID(i); + } + ElementType element; + int bandSize2 = bandSize; + if(bandSize2 > rowsRemaining) + bandSize2 = rowsRemaining; + for(int i = 0; i < bandSize2; i++) + { + element.first = i; + element.second = i; + for(int j = 0; j < columnCount; j++) + { + bandedDLs[j]->insert(element); + } + } + for(int i = 0; i < columnCount; i++) + { + bandedDLs[i]->endOfInput(); + } + timer.stop(message); + + // Create the TableBand. + message = "Creating TableBands"; + timer.start(message); + TableBand band; + for(int i = 0; i < columnCount; i++) + { + band.addColumn(bandedDLs[i]->OID(), bandedDLs[i]); + } + timer.stop(message); + + // Delete the DLs. + message = "Deleting BandedDLs"; + timer.start(message); + for(int i = 0; i < columnCount; i++) + { + delete bandedDLs[i]; + } + timer.stop(message); + + rowsRemaining -= bandSize; + } + + + timer.finish(); + +// int i; +// ElementType element; +// for(i = 0; i < size; i++) { +// element.first = i; +// element.second = i; +// fifo.insert(element); +// fifo2.insert(element); +// fifo3.insert(element); +// fifo4.insert(element); +// } +// fifo.endOfInput(); +// fifo2.endOfInput(); +// fifo3.endOfInput(); +// fifo4.endOfInput(); + } + + // Repeats a band test for totalRows using various band sizes. Outputs total time for each test. + // Used to verify that we get similar performance with various band sizes. + void MULTI_BAND_TEST() { + timer.setSuppressLogMessages(true); + const int totalRows = 200000; + const int startBandRows = 2000; + const int stopBandRows = 40000; + const int increment = 2000; + cout << endl; + cout << "Testing " << totalRows << " total rows" << endl; + cout << endl; + cout << "Seconds # Rows / Band # Bands Bytes per Band" << endl; + cout << "---------------------------------------------" << endl; + int rowsToGo; + string timeStr; + int numBands; + for(int i = startBandRows; i <= stopBandRows; i = i + increment) { + timer.startTimer(); + rowsToGo = totalRows; + numBands = 0; + while(rowsToGo > 0) { + numBands++; + if(rowsToGo >= i) { + bandTest(i); + } + else { + bandTest(rowsToGo); + } + rowsToGo -= i; + } + double seconds; + seconds = timer.getTimeElapsed(timeStr); + cout << timeStr << " " << i << " " << numBands << " " << (i * 40) << endl; + } + } + + // Adds a column to a band. Attempts to add a second column with a different number of rows which shoul + // produce an error. + void BAD_BAND_TEST() { + TableBand band(3000); + addInt64FifoToBand(1, 100, band); + addInt64FifoToBand(1, 101, band); // Should fail. Trying to add a column with wrong number of rows. + } + + // Adds two bands to an NJLSysDataList and asserts that they were added correctly. + void CONVERT_TO_SYSDATA_TEST() { + TableBand band; + CalpontSystemCatalog *csc = CalpontSystemCatalog::makeCalpontSystemCatalog(); + + CalpontSystemCatalog::NJLSysDataList sysDataList; + int size = 10; + addInt64FifoToBand(1, size, band); +// addStringFifoToBand(2, size, band); +// addStringFifoToBand(3, size, band); + addInt64FifoToBand(2, size, band); + band.convertToSysDataList(sysDataList, csc); + + TableBand band2; + addInt64FifoToBand(1, size, band2); +// addStringFifoToBand(2, size, band2); +// addStringFifoToBand(3, size, band2); + addInt64FifoToBand(2, size, band2); + band2.convertToSysDataList(sysDataList, csc); + + vector::const_iterator it; + for (it = sysDataList.begin(); it != sysDataList.end(); it++) + { + CPPUNIT_ASSERT((*it)->dataCount() == 20); + cout << "OID=" << (*it)->ColumnOID() << endl; +// if((*it)->ColumnOID() == 2) +// for(int i = 0; i < (*it)->dataCount(); i++) { +// cout << "col[" << i << "]=" << (*it)->GetStringData(i) << endl; +// } + for(int i = 0; i < (*it)->dataCount(); i++) { + cout << "col[" << i << "]=" << (*it)->GetData(i) << endl; + cout << "rid[" << i << "]=" << (*it)->GetRid(i) << endl; + } + } + } + }; + +CPPUNIT_TEST_SUITE_REGISTRATION(DataListDriver); + + +int main( int argc, char **argv) +{ + CppUnit::TextUi::TestRunner runner; + CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); + runner.addTest( registry.makeTest() ); + bool wasSuccessful = runner.run( "", false ); + return (wasSuccessful ? 0 : 1); +} + + diff --git a/dbcon/joblist/tdriver-zdl.cpp b/dbcon/joblist/tdriver-zdl.cpp index e9c6acc0..0ce5eba4 100644 --- a/dbcon/joblist/tdriver-zdl.cpp +++ b/dbcon/joblist/tdriver-zdl.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: tdriver-zdl.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: tdriver-zdl.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ @@ -358,9 +358,9 @@ ResourceManager fRm; typedef ElementType Element; id_sw = 0; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; SWSDL sw(numOfConsumers, fRm); sw.setMultipleProducers(true); @@ -399,9 +399,9 @@ ResourceManager fRm; typedef ElementType Element; id_sw = 0; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; SWSDL sw(numOfConsumers, fRm); sw.setMultipleProducers(true); @@ -447,9 +447,9 @@ ResourceManager fRm; typedef ElementType Element; id_sw = 0; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; SWSDL sw(numOfConsumers, ::maxElements, fRm); sw.setMultipleProducers(true); @@ -488,9 +488,9 @@ ResourceManager fRm; typedef ElementType Element; id_sw = 0; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; SWSDL sw(numOfConsumers, ::maxElements, fRm); sw.setMultipleProducers(true); @@ -531,9 +531,9 @@ ResourceManager fRm; { typedef ElementType Element; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; ZDL zdl(numOfConsumers, fRm); zdl.setMultipleProducers(true); zdl.setElementMode(1); // RID_VALUE @@ -596,9 +596,9 @@ ResourceManager fRm; eofInputTag += testDesc; consumeTag += testDesc; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; ZDL zdl(numOfConsumers, fRm); zdl.setMultipleProducers(true); zdl.setElementMode(1); // RID_VALUE @@ -682,9 +682,9 @@ ResourceManager fRm; { typedef ElementType Element; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; ZDL zdl(numOfConsumers, fRm); zdl.setMultipleProducers(true); zdl.setElementMode(1); // RID_VALUE @@ -736,9 +736,9 @@ ResourceManager fRm; { typedef ElementType Element; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; ZDL zdl(numOfConsumers, fRm); zdl.setMultipleProducers(true); zdl.setElementMode(1); // RID_VALUE @@ -799,9 +799,9 @@ ResourceManager fRm; eofInputTag += testDesc; consumeTag += testDesc; - uint32_t i; - uint32_t numOfProducers = NUM_PRODUCERS; - uint32_t numOfConsumers = NUM_CONSUMERS; + uint i; + uint numOfProducers = NUM_PRODUCERS; + uint numOfConsumers = NUM_CONSUMERS; ZDL zdl(numOfConsumers, fRm); zdl.setMultipleProducers(true); if ( compress ) @@ -878,7 +878,7 @@ ResourceManager fRm; typedef ElementType Element; vector v; - for (uint32_t i = 0; i < ::count1Set*8; i++) + for (uint i = 0; i < ::count1Set*8; i++) v.push_back(Element(i,i)); vector v1; diff --git a/dbcon/joblist/tdriver1.cpp b/dbcon/joblist/tdriver1.cpp index f2853731..8dfa97e0 100644 --- a/dbcon/joblist/tdriver1.cpp +++ b/dbcon/joblist/tdriver1.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver1.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver1.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include using namespace std; diff --git a/dbcon/joblist/tdriver2.cpp b/dbcon/joblist/tdriver2.cpp index e8207550..b64b814d 100644 --- a/dbcon/joblist/tdriver2.cpp +++ b/dbcon/joblist/tdriver2.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tdriver2.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: tdriver2.cpp 8436 2012-04-04 18:18:21Z rdempsey $ #include #include #include diff --git a/dbcon/joblist/threadsafequeue.h b/dbcon/joblist/threadsafequeue.h index 26000a1f..98d78b84 100644 --- a/dbcon/joblist/threadsafequeue.h +++ b/dbcon/joblist/threadsafequeue.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: threadsafequeue.h 9655 2013-06-25 23:08:13Z xlou $ +* $Id: threadsafequeue.h 8436 2012-04-04 18:18:21Z rdempsey $ */ /** @file */ @@ -42,7 +42,7 @@ namespace joblist struct TSQSize_t { size_t size; - uint32_t count; + uint count; }; /** @brief A thread-safe queue class @@ -144,7 +144,7 @@ class ThreadSafeQueue bytes += v->lengthWithHdrOverhead(); fPimplCond->notify_one(); ret.size = bytes; - ret.count = static_cast(fImpl.size()); + ret.count = static_cast(fImpl.size()); return ret; } /** @brief remove the front item in the queue @@ -182,17 +182,17 @@ class ThreadSafeQueue } fImpl.pop(); ret.size = bytes; - ret.count = static_cast(fImpl.size()); + ret.count = static_cast(fImpl.size()); return ret; } /* If there are less than min elements in the queue, this fcn will return nothing - * for up to 10 consecutive calls (poor man's timer). On the 11th, it will return + * for up to 10 consecutive calls (poor man's timer). On the 11th, it will return * the entire queue. Note, the zeroCount var is non-critical. Not a big deal if * it gets fudged now and then. */ - TSQSize_t pop_some(uint32_t divisor, std::vector &t, uint32_t min = 1) + TSQSize_t pop_some(uint divisor, std::vector &t, uint min = 1) { - uint32_t curSize, workSize; + uint curSize, workSize; TSQSize_t ret = {0, 0}; if (fPimplLock == 0) @@ -218,7 +218,7 @@ class ThreadSafeQueue workSize = curSize; zeroCount = 0; } - for (uint32_t i = 0; i < workSize; ++i) { + for (uint i = 0; i < workSize; ++i) { t.push_back(fImpl.front()); bytes -= fImpl.front()->lengthWithHdrOverhead(); fImpl.pop(); @@ -253,7 +253,7 @@ class ThreadSafeQueue ret.count = fImpl.size(); return ret; } - + /** @brief shutdown the queue * * cause all readers blocked in front() to return a default-constructed T @@ -265,8 +265,8 @@ class ThreadSafeQueue fPimplCond->notify_all(); return; } - - void clear() + + void clear() { if (fPimplLock == 0) throw std::runtime_error("TSQ: clear(): no sync!"); @@ -296,7 +296,7 @@ class ThreadSafeQueue #else size_t bytes; #endif - uint32_t zeroCount; // counts the # of times read_some returned 0 + uint zeroCount; // counts the # of times read_some returned 0 }; } diff --git a/dbcon/joblist/timeset.h b/dbcon/joblist/timeset.h index d9535447..3566133d 100644 --- a/dbcon/joblist/timeset.h +++ b/dbcon/joblist/timeset.h @@ -16,11 +16,11 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: timeset.h 9655 2013-06-25 23:08:13Z xlou $ + * $Id: timeset.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ -/** @file timeset.h +/** @file timeset.h * Used to maintain collection of timers tracking elapsed times for set of tasks */ @@ -80,7 +80,7 @@ class TimeSet inline void TimeSet::displayAll() const { - ElapsedMap::const_iterator itend = fElapsed.end(); + ElapsedMap::const_iterator itend = fElapsed.end(); for (ElapsedMap::const_iterator it = fElapsed.begin(); it != itend; ++it) { double t; @@ -106,7 +106,7 @@ void TimeSet::displayAll() const inline void TimeSet::display(const std::string& key) const { - ElapsedMap::const_iterator em = fElapsed.find(key); + ElapsedMap::const_iterator em = fElapsed.find(key); if (fElapsed.end() != em) { double t; @@ -143,7 +143,7 @@ inline double TimeSet::totalTime() const { struct timespec tSum = {0,0}; - ElapsedMap::const_iterator itend = fElapsed.end(); + ElapsedMap::const_iterator itend = fElapsed.end(); for (ElapsedMap::const_iterator it = fElapsed.begin(); it != itend; ++it) { #if defined(_MSC_VER) && !defined(_my_pthread_h) @@ -169,7 +169,7 @@ inline double TimeSet::totalTime(const std::string& key) const { ElapsedMap::const_iterator el = fElapsed.find(key); - if (fElapsed.end() != el) + if (fElapsed.end() != el) { double totSeconds; #if defined(_MSC_VER) && defined(_my_pthread_h) @@ -181,7 +181,7 @@ double TimeSet::totalTime(const std::string& key) const #endif return totSeconds; } - else + else { return 0; } @@ -267,7 +267,7 @@ void TimeSet::stopTimer(const std::string& key) // start (in) - boolean indicating whether to start or stop the timer. //------------------------------------------------------------------------------ inline -void TimeSet::setTimer(const std::string& key, bool start /*= true*/) +void TimeSet::setTimer(const std::string& key, bool start /*= true*/) { if (start) startTimer(key); diff --git a/dbcon/joblist/timestamp.cpp b/dbcon/joblist/timestamp.cpp index f6348379..db04013b 100644 --- a/dbcon/joblist/timestamp.cpp +++ b/dbcon/joblist/timestamp.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ // -// $Id: timestamp.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: timestamp.cpp 8698 2012-07-10 14:47:53Z rdempsey $ // #include @@ -34,9 +34,6 @@ namespace const struct timeval zerotime = {0, 0}; } -namespace joblist -{ - JSTimeStamp::JSTimeStamp() : fFirstInsertTime(zerotime), fLastInsertTime(zerotime), @@ -95,13 +92,3 @@ const string JSTimeStamp::tsdiffstr(const struct timeval& t2, const struct timev return res; } -/* static */ -const string JSTimeStamp::timeNow() -{ - struct timeval tv; - gettimeofday(&tv, 0); - return JSTimeStamp::format(tv); -} - -} //namespace joblist - diff --git a/dbcon/joblist/timestamp.h b/dbcon/joblist/timestamp.h index 4572ba5e..bbd5785f 100644 --- a/dbcon/joblist/timestamp.h +++ b/dbcon/joblist/timestamp.h @@ -18,7 +18,7 @@ #ifndef TIMESTAMP_H_ #define TIMESTAMP_H_ // -// $Id: timestamp.h 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: timestamp.h 8436 2012-04-04 18:18:21Z rdempsey $ // /** @file */ @@ -28,9 +28,6 @@ #include #include -namespace joblist -{ - class JSTimeStamp { public: @@ -67,8 +64,6 @@ class JSTimeStamp { //returns str rep of tvbuf static const std::string format(const struct timeval& tvbuf); - static const std::string timeNow(); - protected: private: @@ -79,7 +74,4 @@ class JSTimeStamp { struct timeval fLastReadTime; }; -} //namespace joblist - #endif - diff --git a/dbcon/joblist/tuple-bps.cpp b/dbcon/joblist/tuple-bps.cpp index 023a0b72..68a5bcf2 100644 --- a/dbcon/joblist/tuple-bps.cpp +++ b/dbcon/joblist/tuple-bps.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tuple-bps.cpp 9705 2013-07-17 20:06:07Z pleblanc $ +// $Id: tuple-bps.cpp 9469 2013-05-01 18:38:43Z pleblanc $ #include @@ -31,34 +31,29 @@ using namespace std; #include #include -#include using namespace boost; #include "bpp-jl.h" #include "distributedenginecomm.h" #include "elementtype.h" -#include "jlf_common.h" #include "primitivestep.h" #include "unique32generator.h" -#include "rowestimator.h" using namespace joblist; #include "messagequeue.h" using namespace messageqcpp; - -#include "configcpp.h" using namespace config; #include "messagelog.h" #include "messageobj.h" #include "loggingid.h" #include "errorcodes.h" +#include "rowestimator.h" #include "errorids.h" +#include "liboamcpp.h" #include "exceptclasses.h" using namespace logging; -#include "liboamcpp.h" - #include "calpontsystemcatalog.h" using namespace execplan; @@ -67,25 +62,30 @@ using namespace BRM; #include "oamcache.h" -#include "rowgroup.h" using namespace rowgroup; -#include "querytele.h" -using namespace querytele; +// #define DEBUG 1 + + +//uint TBPSCount = 0; -#include "pseudocolumn.h" -//#define DEBUG 1 extern boost::mutex fileLock_g; namespace { -const uint32_t LOGICAL_EXTENT_CONVERTER = 10; // 10 + 13. 13 to convert to logical blocks, +const uint LOGICAL_EXTENT_CONVERTER = 10; // 10 + 13. 13 to convert to logical blocks, // 10 to convert to groups of 1024 logical blocks -const uint32_t DEFAULT_EXTENTS_PER_SEG_FILE = 2; +} +void timespec_diff(const struct timespec &tv1, + const struct timespec &tv2, + double &tm) +{ + tm = (double)(tv2.tv_sec - tv1.tv_sec) + 1.e-9*(tv2.tv_nsec - tv1.tv_nsec); } + /** Debug macro */ #define THROTTLE_DEBUG 0 #if THROTTLE_DEBUG @@ -108,13 +108,13 @@ struct TupleBPSPrimitive fBatchPrimitiveStep->sendPrimitiveMessages(); } catch(std::exception& re) { - cerr << "TupleBPS: send thread threw an exception: " << re.what() << + cerr << "TupleBPS: send thread threw an exception: " << re.what() << "\t" << this << endl; - catchHandler(re.what(), ERR_TUPLE_BPS, fBatchPrimitiveStep->errorInfo()); + catchHandler(re.what()); } catch(...) { string msg("TupleBPS: send thread threw an unknown exception "); - catchHandler(msg, ERR_TUPLE_BPS, fBatchPrimitiveStep->errorInfo()); + catchHandler(msg); cerr << msg << this << endl; } } @@ -135,12 +135,12 @@ struct TupleBPSAggregators } catch(std::exception& re) { cerr << fBatchPrimitiveStepCols->toString() << ": receive thread threw an exception: " << re.what() << endl; - catchHandler(re.what(), ERR_TUPLE_BPS, fBatchPrimitiveStepCols->errorInfo()); + catchHandler(re.what()); } catch(...) { string msg("TupleBPS: recv thread threw an unknown exception "); cerr << fBatchPrimitiveStepCols->toString() << msg << endl; - catchHandler(msg, ERR_TUPLE_BPS, fBatchPrimitiveStepCols->errorInfo()); + catchHandler(msg); } } }; @@ -152,7 +152,6 @@ void TupleBPS::initializeConfigParms() { string strVal; - //...Get the tuning parameters that throttle msgs sent to primproc //...fFilterRowReqLimit puts a cap on how many rids we will request from //... primproc, before pausing to let the consumer thread catch up. @@ -166,33 +165,25 @@ void TupleBPS::initializeConfigParms() fRequestSize = fRm.getJlRequestSize(); fMaxOutstandingRequests = fRm.getJlMaxOutstandingRequests(); fProcessorThreadsPerScan = fRm.getJlProcessorThreadsPerScan(); - fNumThreads = 0; - - config::Config* cf = config::Config::makeConfig(); - string epsf = cf->getConfig("ExtentMap", "ExtentsPerSegmentFile"); - if ( epsf.length() != 0 ) - fExtentsPerSegFile = cf->uFromText(epsf); + fExtentRows = fRm.getExtentRows()/BLOCK_SIZE; // convert to Blocks; if (fRequestSize >= fMaxOutstandingRequests) fRequestSize = 1; - if ((fSessionId & 0x80000000) == 0) - fMaxNumThreads = fRm.getJlNumScanReceiveThreads(); - else - fMaxNumThreads = 1; + fNumThreads = fRm.getJlNumScanReceiveThreads(); - fProducerThread.reset(new SPTHD[fMaxNumThreads]); - // Make maxnum thread objects even if they don't get used to make join() safe. - for (uint32_t i = 0; i < fMaxNumThreads; i++) - fProducerThread[i].reset(new thread()); + fProducerThread.reset(new SPTHD[fNumThreads]); } -TupleBPS::TupleBPS(const pColStep& rhs, const JobInfo& jobInfo) : - BatchPrimitive(jobInfo), fRm(jobInfo.rm) +TupleBPS::TupleBPS(const pColStep& rhs) : fRm(rhs.fRm) { fInputJobStepAssociation = rhs.inputAssociation(); fOutputJobStepAssociation = rhs.outputAssociation(); fDec = 0; fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); fFilterCount = rhs.filterCount(); fFilterString = rhs.filterString(); isFilterFeeder = rhs.getFeederFlag(); @@ -203,7 +194,7 @@ TupleBPS::TupleBPS(const pColStep& rhs, const JobInfo& jobInfo) : scannedExtents = rhs.extents; extentsMap[fOid] = tr1::unordered_map(); tr1::unordered_map &ref = extentsMap[fOid]; - for (uint32_t z = 0; z < rhs.extents.size(); z++) + for (uint z = 0; z < rhs.extents.size(); z++) ref[rhs.extents[z].range.start] = rhs.extents[z]; lbidList = rhs.lbidList; @@ -213,18 +204,18 @@ TupleBPS::TupleBPS(const pColStep& rhs, const JobInfo& jobInfo) : numExtents = rhs.numExtents; ridsRequested = 0; ridsReturned = 0; + rowsReturned = 0; recvExited = 0; - totalMsgs = 0; msgsSent = 0; msgsRecvd = 0; fMsgBytesIn = 0; fMsgBytesOut = 0; fBlockTouched = 0; - fExtentsPerSegFile = DEFAULT_EXTENTS_PER_SEG_FILE; + fMsgBppsToPm = 0; recvWaiting = 0; fStepCount = 1; - fCPEvaluated = false; - fEstimatedRows = 0; + fCPEvaluated = false; + fEstimatedRows = 0; fColType = rhs.colType(); alias(rhs.alias()); view(rhs.view()); @@ -234,11 +225,13 @@ TupleBPS::TupleBPS(const pColStep& rhs, const JobInfo& jobInfo) : initializeConfigParms(); fBPP->setSessionID(fSessionId); fBPP->setStepID(fStepId); - fBPP->setQueryContext(fVerId); + fBPP->setVersionNum(fVerId); fBPP->setTxnID(fTxnId); fTraceFlags = rhs.fTraceFlags; fBPP->setTraceFlags(fTraceFlags); fBPP->setOutputType(ROW_GROUP); +// if (fOid>=3000) +// cout << "BPS:initalized from pColStep. fSessionId=" << fSessionId << endl; finishedSending = sendWaiting = false; fNumBlksSkipped = 0; fPhysicalIO = 0; @@ -246,7 +239,6 @@ TupleBPS::TupleBPS(const pColStep& rhs, const JobInfo& jobInfo) : BPPIsAllocated = false; uniqueID = UniqueNumberGenerator::instance()->getUnique32(); fBPP->setUniqueID(uniqueID); - fBPP->setUuid(fStepUuid); fCardinality = rhs.cardinality(); doJoin = false; hasPMJoin = false; @@ -258,25 +250,25 @@ TupleBPS::TupleBPS(const pColStep& rhs, const JobInfo& jobInfo) : // @1098 initialize scanFlags to be true scanFlags.assign(numExtents, true); runtimeCPFlags.assign(numExtents, true); + die = false; bop = BOP_AND; runRan = joinRan = false; - fDelivery = false; + isDelivery = false; fExtendedInfo = "TBPS: "; - fQtc.stepParms().stepType = StepTeleStats::T_BPS; - - - hasPCFilter = hasPMFilter = hasRIDFilter = hasSegmentFilter = hasDBRootFilter = hasSegmentDirFilter = - hasPartitionFilter = hasMaxFilter = hasMinFilter = hasLBIDFilter = hasExtentIDFilter = false; // cout << "TBPSCount = " << ++TBPSCount << endl; } -TupleBPS::TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo) : - BatchPrimitive(jobInfo), fRm(jobInfo.rm) +TupleBPS::TupleBPS(const pColScanStep& rhs) : fRm(rhs.fRm) { fInputJobStepAssociation = rhs.inputAssociation(); fOutputJobStepAssociation = rhs.outputAssociation(); fDec = 0; + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); fFilterCount = rhs.filterCount(); fFilterString = rhs.filterString(); isFilterFeeder = rhs.getFeederFlag(); @@ -289,25 +281,25 @@ TupleBPS::TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo) : scannedExtents = rhs.extents; extentsMap[fOid] = tr1::unordered_map(); tr1::unordered_map &ref = extentsMap[fOid]; - for (uint32_t z = 0; z < rhs.extents.size(); z++) + for (uint z = 0; z < rhs.extents.size(); z++) ref[rhs.extents[z].range.start] = rhs.extents[z]; divShift = rhs.divShift; - totalMsgs = 0; msgsSent = 0; msgsRecvd = 0; ridsReturned = 0; ridsRequested = 0; + rowsReturned = 0; fNumBlksSkipped = 0; fMsgBytesIn = 0; fMsgBytesOut = 0; fBlockTouched = 0; - fExtentsPerSegFile = DEFAULT_EXTENTS_PER_SEG_FILE; + fMsgBppsToPm = 0; recvWaiting = 0; fSwallowRows = false; fStepCount = 1; fCPEvaluated = false; - fEstimatedRows = 0; + fEstimatedRows = 0; fColType = rhs.colType(); alias(rhs.alias()); view(rhs.view()); @@ -316,6 +308,7 @@ TupleBPS::TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo) : fColWidth = fColType.colWidth; lbidList = rhs.lbidList; + fLogger = rhs.logger(); finishedSending = sendWaiting = false; firstRead = true; fSwallowRows = false; @@ -323,7 +316,7 @@ TupleBPS::TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo) : fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); initializeConfigParms(); fBPP->setSessionID(fSessionId); - fBPP->setQueryContext(fVerId); + fBPP->setVersionNum(fVerId); fBPP->setTxnID(fTxnId); fTraceFlags = rhs.fTraceFlags; fBPP->setTraceFlags(fTraceFlags); @@ -336,7 +329,6 @@ TupleBPS::TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo) : BPPIsAllocated = false; uniqueID = UniqueNumberGenerator::instance()->getUnique32(); fBPP->setUniqueID(uniqueID); - fBPP->setUuid(fStepUuid); fCardinality = rhs.cardinality(); doJoin = false; hasPMJoin = false; @@ -346,42 +338,43 @@ TupleBPS::TupleBPS(const pColScanStep& rhs, const JobInfo& jobInfo) : // @1098 initialize scanFlags to be true //scanFlags.assign(numExtents, true); //runtimeCPFlags.assign(numExtents, true); + die = false; bop = BOP_AND; runRan = joinRan = false; - fDelivery = false; + isDelivery = false; fExtendedInfo = "TBPS: "; initExtentMarkers(); - fQtc.stepParms().stepType = StepTeleStats::T_BPS; - - hasPCFilter = hasPMFilter = hasRIDFilter = hasSegmentFilter = hasDBRootFilter = hasSegmentDirFilter = - hasPartitionFilter = hasMaxFilter = hasMinFilter = hasLBIDFilter = hasExtentIDFilter = false; } -TupleBPS::TupleBPS(const PassThruStep& rhs, const JobInfo& jobInfo) : - BatchPrimitive(jobInfo), fRm(jobInfo.rm) +TupleBPS::TupleBPS(const PassThruStep& rhs) : fRm(rhs.fRm) { fInputJobStepAssociation = rhs.inputAssociation(); fOutputJobStepAssociation = rhs.outputAssociation(); fDec = 0; + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); fFilterCount = 0; fOid = rhs.oid(); fTableOid = rhs.tableOid(); ridsReturned = 0; + rowsReturned = 0; ridsRequested = 0; fMsgBytesIn = 0; fMsgBytesOut = 0; fBlockTouched = 0; - fExtentsPerSegFile = DEFAULT_EXTENTS_PER_SEG_FILE; + fMsgBppsToPm = 0; recvExited = 0; - totalMsgs = 0; msgsSent = 0; msgsRecvd = 0; recvWaiting = 0; fStepCount = 1; fCPEvaluated = false; - fEstimatedRows = 0; + fEstimatedRows = 0; fColType = rhs.colType(); alias(rhs.alias()); view(rhs.view()); @@ -391,7 +384,7 @@ TupleBPS::TupleBPS(const PassThruStep& rhs, const JobInfo& jobInfo) : initializeConfigParms(); fBPP->setSessionID(fSessionId); fBPP->setStepID(fStepId); - fBPP->setQueryContext(fVerId); + fBPP->setVersionNum(fVerId); fBPP->setTxnID(fTxnId); fTraceFlags = rhs.fTraceFlags; fBPP->setTraceFlags(fTraceFlags); @@ -407,7 +400,6 @@ TupleBPS::TupleBPS(const PassThruStep& rhs, const JobInfo& jobInfo) : BPPIsAllocated = false; uniqueID = UniqueNumberGenerator::instance()->getUnique32(); fBPP->setUniqueID(uniqueID); - fBPP->setUuid(fStepUuid); doJoin = false; hasPMJoin = false; hasUMJoin = false; @@ -418,46 +410,48 @@ TupleBPS::TupleBPS(const PassThruStep& rhs, const JobInfo& jobInfo) : // @1098 initialize scanFlags to be true scanFlags.assign(numExtents, true); runtimeCPFlags.assign(numExtents, true); + die = false; bop = BOP_AND; runRan = joinRan = false; - fDelivery = false; + isDelivery = false; fExtendedInfo = "TBPS: "; - fQtc.stepParms().stepType = StepTeleStats::T_BPS; - - hasPCFilter = hasPMFilter = hasRIDFilter = hasSegmentFilter = hasDBRootFilter = hasSegmentDirFilter = - hasPartitionFilter = hasMaxFilter = hasMinFilter = hasLBIDFilter = hasExtentIDFilter = false; - // cout << "TBPSCount = " << ++TBPSCount << endl; } -TupleBPS::TupleBPS(const pDictionaryStep& rhs, const JobInfo& jobInfo) : - BatchPrimitive(jobInfo), fRm(jobInfo.rm) +TupleBPS::TupleBPS(const pDictionaryStep& rhs) : fRm(rhs.fRm) { fInputJobStepAssociation = rhs.inputAssociation(); fOutputJobStepAssociation = rhs.outputAssociation(); fDec = 0; + fSessionId = rhs.sessionId(); + fTxnId = rhs.txnId(); + fVerId = rhs.verId(); + fStepId = rhs.stepId(); + fStatementId = rhs.statementId(); fOid = rhs.oid(); fTableOid = rhs.tableOid(); - totalMsgs = 0; msgsSent = 0; msgsRecvd = 0; ridsReturned = 0; + rowsReturned = 0; ridsRequested = 0; fNumBlksSkipped = 0; fBlockTouched = 0; fMsgBytesIn = 0; fMsgBytesOut = 0; - fExtentsPerSegFile = DEFAULT_EXTENTS_PER_SEG_FILE; + fMsgBppsToPm = 0; recvWaiting = 0; fSwallowRows = false; fStepCount = 1; fCPEvaluated = false; - fEstimatedRows = 0; + fEstimatedRows = 0; //fColType = rhs.colType(); alias(rhs.alias()); view(rhs.view()); name(rhs.name()); + + fLogger = rhs.logger(); finishedSending = sendWaiting = false; recvExited = 0; fBPP.reset(new BatchPrimitiveProcessorJL(fRm)); @@ -466,7 +460,7 @@ TupleBPS::TupleBPS(const pDictionaryStep& rhs, const JobInfo& jobInfo) : // if (fOid>=3000) // cout << "BPS:initalized from DictionaryStep. fSessionId=" << fSessionId << endl; fBPP->setStepID(fStepId); - fBPP->setQueryContext(fVerId); + fBPP->setVersionNum(fVerId); fBPP->setTxnID(fTxnId); fTraceFlags = rhs.fTraceFlags; fBPP->setTraceFlags(fTraceFlags); @@ -476,7 +470,6 @@ TupleBPS::TupleBPS(const pDictionaryStep& rhs, const JobInfo& jobInfo) : BPPIsAllocated = false; uniqueID = UniqueNumberGenerator::instance()->getUnique32(); fBPP->setUniqueID(uniqueID); - fBPP->setUuid(fStepUuid); fCardinality = rhs.cardinality(); doJoin = false; hasPMJoin = false; @@ -487,16 +480,12 @@ TupleBPS::TupleBPS(const pDictionaryStep& rhs, const JobInfo& jobInfo) : // @1098 initialize scanFlags to be true scanFlags.assign(numExtents, true); runtimeCPFlags.assign(numExtents, true); + die = false; bop = BOP_AND; runRan = joinRan = false; - fDelivery = false; + isDelivery = false; fExtendedInfo = "TBPS: "; - fQtc.stepParms().stepType = StepTeleStats::T_BPS; - - hasPCFilter = hasPMFilter = hasRIDFilter = hasSegmentFilter = hasDBRootFilter = hasSegmentDirFilter = - hasPartitionFilter = hasMaxFilter = hasMinFilter = hasLBIDFilter = hasExtentIDFilter = false; - // cout << "TBPSCount = " << ++TBPSCount << endl; } @@ -508,19 +497,19 @@ TupleBPS::~TupleBPS() ByteStream bs; fBPP->destroyBPP(bs); try { + fMsgBytesOut += bs.length() * fDec->getPmCount(); fDec->write(uniqueID, bs); } catch (const std::exception& e) { // log the exception cerr << "~TupleBPS caught: " << e.what() << endl; - catchHandler(e.what(), ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler(e.what()); } catch (...) { cerr << "~TupleBPS caught unknown exception" << endl; - catchHandler("~TupleBPS caught unknown exception", - ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler("~TupleBPS caught unknown exception"); } } fDec->removeQueue(uniqueID); @@ -529,7 +518,7 @@ TupleBPS::~TupleBPS() } void TupleBPS::setBPP(JobStep* jobStep) -{ +{ fCardinality = jobStep->cardinality(); pColStep* pcsp = dynamic_cast(jobStep); @@ -537,32 +526,11 @@ void TupleBPS::setBPP(JobStep* jobStep) int colWidth = 0; if (pcsp != 0) { - PseudoColStep *pseudo = dynamic_cast(jobStep); - if (pseudo) { - //cout << "adding a pseudo col filter" << endl; - fBPP->addFilterStep(*pseudo); - if (pseudo->filterCount() > 0) { - hasPCFilter = true; - switch(pseudo->pseudoColumnId()) { - case PSEUDO_EXTENTRELATIVERID: hasRIDFilter = true; break; - case PSEUDO_DBROOT: hasDBRootFilter = true; break; - case PSEUDO_PM: hasPMFilter = true; break; - case PSEUDO_SEGMENT: hasSegmentFilter = true; break; - case PSEUDO_SEGMENTDIR: hasSegmentDirFilter = true; break; - case PSEUDO_EXTENTMIN: hasMinFilter = true; break; - case PSEUDO_EXTENTMAX: hasMaxFilter = true; break; - case PSEUDO_BLOCKID: hasLBIDFilter = true; break; - case PSEUDO_EXTENTID: hasExtentIDFilter = true; break; - case PSEUDO_PARTITION: hasPartitionFilter = true; break; - } - } - } - else - fBPP->addFilterStep(*pcsp); + fBPP->addFilterStep(*pcsp); extentsMap[pcsp->fOid] = tr1::unordered_map(); tr1::unordered_map &ref = extentsMap[pcsp->fOid]; - for (uint32_t z = 0; z < pcsp->extents.size(); z++) + for (uint z = 0; z < pcsp->extents.size(); z++) ref[pcsp->extents[z].range.start] = pcsp->extents[z]; colWidth = (pcsp->colType()).colWidth; @@ -572,7 +540,7 @@ void TupleBPS::setBPP(JobStep* jobStep) if (bop == BOP_OR && isFilterFeeder == false) fBPP->setForHJ(true); } - else + else { pColScanStep* pcss = dynamic_cast(jobStep); if (pcss != 0) @@ -581,13 +549,13 @@ void TupleBPS::setBPP(JobStep* jobStep) extentsMap[pcss->fOid] = tr1::unordered_map(); tr1::unordered_map &ref = extentsMap[pcss->fOid]; - for (uint32_t z = 0; z < pcss->extents.size(); z++) + for (uint z = 0; z < pcss->extents.size(); z++) ref[pcss->extents[z].range.start] = pcss->extents[z]; colWidth = (pcss->colType()).colWidth; isFilterFeeder = pcss->getFeederFlag(); } - else + else { pDictionaryStep* pdsp = dynamic_cast(jobStep); if (pdsp != 0) @@ -655,17 +623,11 @@ void TupleBPS::setProjectBPP(JobStep* jobStep1, JobStep* jobStep2) pColStep* pcsp = dynamic_cast(jobStep1); if (pcsp != 0) { - PseudoColStep *pseudo = dynamic_cast(jobStep1); - if (pseudo) { - //cout << "adding a pseudo col projection" << endl; - fBPP->addProjectStep(*pseudo); - } - else - fBPP->addProjectStep(*pcsp); + fBPP->addProjectStep(*pcsp); extentsMap[pcsp->fOid] = tr1::unordered_map(); tr1::unordered_map &ref = extentsMap[pcsp->fOid]; - for (uint32_t z = 0; z < pcsp->extents.size(); z++) + for (uint z = 0; z < pcsp->extents.size(); z++) ref[pcsp->extents[z].range.start] = pcsp->extents[z]; //@Bug 961 @@ -674,7 +636,7 @@ void TupleBPS::setProjectBPP(JobStep* jobStep1, JobStep* jobStep2) colWidth = (pcsp->colType()).colWidth; projectOids.push_back(jobStep1->oid()); } - else + else { PassThruStep* passthru = dynamic_cast(jobStep1); if (passthru!= 0) @@ -683,17 +645,8 @@ void TupleBPS::setProjectBPP(JobStep* jobStep1, JobStep* jobStep2) if (static_cast(fBPP->getFilterSteps().back()->getOID()) != passthru->oid()) { SJSTEP pts; - if (passthru->pseudoType() == 0) - { - pts.reset(new pColStep(*passthru)); - pcsp = dynamic_cast(pts.get()); - } - else - { - pts.reset(new PseudoColStep(*passthru)); - pcsp = dynamic_cast(pts.get()); - } - + pts.reset(new pColStep(*passthru)); + pcsp = dynamic_cast(pts.get()); fBPP->addProjectStep(*pcsp); if (!passthru->isExeMgr()) fBPP->setNeedRidsAtDelivery(true); @@ -736,10 +689,11 @@ void TupleBPS::storeCasualPartitionInfo(const bool estimateRowCounts) if (colCmdVec.size() == 0) return; - for (uint32_t i = 0; i < colCmdVec.size(); i++) + for (uint i = 0; i < colCmdVec.size(); i++) { colCmd = dynamic_cast(colCmdVec[i].get()); - if (!colCmd || dynamic_cast(colCmdVec[i].get())) + // bug 2116. skip CP check for function column + if (!colCmd || colCmd->fcnOrd() !=0) continue; SP_LBIDList tmplbidList(new LBIDList(0)); @@ -752,8 +706,8 @@ void TupleBPS::storeCasualPartitionInfo(const bool estimateRowCounts) // @Bug 3503. Use the total table size as the estimate for non CP columns. else if (fEstimatedRows == 0 && estimateRowCounts) { - RowEstimator rowEstimator; - fEstimatedRows = rowEstimator.estimateRowsForNonCPColumn(*colCmd); + RowEstimator rowEstimator; + fEstimatedRows = rowEstimator.estimateRowsForNonCPColumn(*colCmd); } } @@ -764,10 +718,10 @@ void TupleBPS::storeCasualPartitionInfo(const bool estimateRowCounts) const bool ignoreCP = ((fTraceFlags & CalpontSelectExecutionPlan::IGNORE_CP) != 0); - for (uint32_t idx=0; idx getExtents()[idx]; @@ -803,52 +757,33 @@ void TupleBPS::startPrimitiveThread() pThread.reset(new boost::thread(TupleBPSPrimitive(this))); } -void TupleBPS::startAggregationThread() +void TupleBPS::startAggregationThreads() { -// This block of code starts all threads up front -// fMaxNumThreads = 1; -// fNumThreads = fMaxNumThreads; -// for (uint32_t i = 0; i < fMaxNumThreads; i++) -// fProducerThread[i].reset(new boost::thread(TupleBPSAggregators(this, i))); - -// This block of code starts one thread at a time - if (fNumThreads >= fMaxNumThreads) - return; - fNumThreads++; - fProducerThread[fNumThreads-1].reset(new boost::thread(TupleBPSAggregators(this, fNumThreads-1))); + //fNumThreads = 1; + for (uint i = 0; i < fNumThreads; i++) + fProducerThread[i].reset(new boost::thread(TupleBPSAggregators(this, i))); } -//#include "boost/date_time/posix_time/posix_time.hpp" - void TupleBPS::serializeJoiner() { -// boost::posix_time::ptime start, stop; -// start = boost::posix_time::microsec_clock::local_time(); ByteStream bs; bool more = true; /* false from nextJoinerMsg means it's the last msg, it's not exactly the exit condition*/ while (more) { - { // code block to release the lock immediatly - boost::mutex::scoped_lock lk(serializeJoinerMutex); - more = fBPP->nextTupleJoinerMsg(bs); - } + more = fBPP->nextTupleJoinerMsg(bs); #ifdef JLF_DEBUG cout << "serializing joiner into " << bs.length() << " bytes" << endl; #endif + fMsgBytesOut += bs.length() * fDec->getPmCount(); fDec->write(uniqueID, bs); bs.restart(); } -// stop = boost::posix_time::microsec_clock::local_time(); -// cout << "serializing took " << stop-start << endl; } -void TupleBPS::serializeJoiner(uint32_t conn) +void TupleBPS::serializeJoiner(uint conn) { - // We need this lock for TupleBPS::serializeJoiner() - boost::mutex::scoped_lock lk(serializeJoinerMutex); - ByteStream bs; bool more = true; @@ -856,6 +791,7 @@ void TupleBPS::serializeJoiner(uint32_t conn) it's not exactly the exit condition*/ while (more) { more = fBPP->nextTupleJoinerMsg(bs); + fMsgBytesOut += bs.length(); fDec->write(bs, conn); bs.restart(); } @@ -863,7 +799,7 @@ void TupleBPS::serializeJoiner(uint32_t conn) void TupleBPS::prepCasualPartitioning() { - uint32_t i; + uint i; int64_t min, max, seq; mutex::scoped_lock lk(cpMutex); @@ -874,8 +810,7 @@ void TupleBPS::prepCasualPartitioning() scanFlags[i] = scanFlags[i] && runtimeCPFlags[i]; if (scanFlags[i] && lbidList->CasualPartitionDataType(fColType.colDataType, fColType.colWidth)) - lbidList->GetMinMax(min, max, seq, (int64_t) scannedExtents[i].range.start, - &scannedExtents, fColType.colDataType); + lbidList->GetMinMax(min, max, seq, (int64_t) scannedExtents[i].range.start, &scannedExtents); } else scanFlags[i] = true; @@ -884,7 +819,7 @@ void TupleBPS::prepCasualPartitioning() bool TupleBPS::goodExtentCount() { - uint32_t eCount = extentsMap.begin()->second.size(); + uint eCount = extentsMap.begin()->second.size(); map > ::iterator it; @@ -896,6 +831,7 @@ bool TupleBPS::goodExtentCount() void TupleBPS::initExtentMarkers() { + numDBRoots = fRm.getDBRootCount(); lastExtent.resize(numDBRoots); lastScannedLBID.resize(numDBRoots); @@ -903,25 +839,10 @@ void TupleBPS::initExtentMarkers() tr1::unordered_map &ref = extentsMap[fOid]; tr1::unordered_map::iterator it; - // Map part# and seg# to an extent count per segment file. - // Part# is 32 hi order bits of key, seg# is 32 lo order bits - std::tr1::unordered_map extentCountPerDbFile; - scannedExtents.clear(); for (it = ref.begin(); it != ref.end(); ++it) - { scannedExtents.push_back(it->second); - //@bug 5322: 0 HWM may not mean full extent if 1 extent in file. - // Track how many extents are in each segment file - if (fExtentsPerSegFile > 1) - { - EMEntry& e = it->second; - uint64_t key = ((uint64_t)e.partitionNum << 32) + e.segmentNum; - ++extentCountPerDbFile[key]; - } - } - sort(scannedExtents.begin(), scannedExtents.end(), ExtentSorter()); numExtents = scannedExtents.size(); @@ -929,38 +850,27 @@ void TupleBPS::initExtentMarkers() scanFlags.assign(numExtents, true); runtimeCPFlags.assign(numExtents, true); - for (uint32_t i = 0; i < numDBRoots; i++) + for (uint i = 0; i < numDBRoots; i++) lastExtent[i] = -1; - for (uint32_t i = 0; i < scannedExtents.size(); i++) { - uint32_t dbRoot = scannedExtents[i].dbRoot - 1; + for (uint i = 0; i < scannedExtents.size(); i++) { + uint dbRoot = scannedExtents[i].dbRoot - 1; /* Kludge to account for gaps in the dbroot mapping. */ if (scannedExtents[i].dbRoot > numDBRoots) { lastExtent.resize(scannedExtents[i].dbRoot); lastScannedLBID.resize(scannedExtents[i].dbRoot); - for (uint32_t z = numDBRoots; z < scannedExtents[i].dbRoot; z++) + for (uint z = numDBRoots; z < scannedExtents[i].dbRoot; z++) lastExtent[z] = -1; numDBRoots = scannedExtents[i].dbRoot; } if ((scannedExtents[i].status == EXTENTAVAILABLE) && (lastExtent[dbRoot] < (int) i)) lastExtent[dbRoot] = i; - - //@bug 5322: 0 HWM may not mean full extent if 1 extent in file. - // Use special status (EXTENTSTATUSMAX+1) to denote a single extent - // file with HWM 0; retrieve 1 block and not full extent. - if ((fExtentsPerSegFile > 1) && (scannedExtents[i].HWM == 0)) - { - uint64_t key = ((uint64_t)scannedExtents[i].partitionNum << 32) + - scannedExtents[i].segmentNum; - if (extentCountPerDbFile[key] == 1) - scannedExtents[i].status = EXTENTSTATUSMAX + 1; - } } // if only 1 block is written in the last extent, HWM is 0 and didn't get counted. - for (uint32_t i = 0; i < numDBRoots; i++) { + for (uint i = 0; i < numDBRoots; i++) { if (lastExtent[i] != -1) lastScannedLBID[i] = scannedExtents[lastExtent[i]].range.start + (scannedExtents[lastExtent[i]].HWM - scannedExtents[lastExtent[i]].blockOffset); @@ -979,7 +889,7 @@ void TupleBPS::reloadExtentLists() * 3) update vars dependent on the extent layout (lastExtent, scanFlags, etc) */ - uint32_t i, j; + uint i, j; ColumnCommandJL *cc; vector &filters = fBPP->getFilterSteps(); vector &projections = fBPP->getProjectSteps(); @@ -1030,17 +940,17 @@ void TupleBPS::reloadExtentLists() for (j = 0; j < extents.size(); j++) mref[extents[j].range.start] = extents[j]; } - + initExtentMarkers(); } void TupleBPS::run() { - uint32_t i; + uint i; boost::mutex::scoped_lock lk(jlLock); - uint32_t retryCounter = 0; - const uint32_t retryMax = 1000; // 50s max; we've seen a 15s window so 50s should be 'safe' - const uint32_t waitInterval = 50000; // in us + uint retryCounter = 0; + const uint retryMax = 1000; // 50s max; we've seen a 15s window so 50s should be 'safe' + const uint waitInterval = 50000; // in us if (fRunExecuted) return; @@ -1057,14 +967,18 @@ void TupleBPS::run() ostringstream os; os << "TupleBPS: Could not get a consistent extent count for each column. Got '" << e.what() << "'\n"; - catchHandler(os.str(), ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler(os.str()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_TUPLE_BPS); fOutputJobStepAssociation.outAt(0)->rowGroupDL()->endOfInput(); return; + } if (retryCounter == retryMax) { - catchHandler("TupleBPS: Could not get a consistent extent count for each column.", - ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler("TupleBPS: Could not get a consistent extent count for each column."); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_TUPLE_BPS); fOutputJobStepAssociation.outAt(0)->rowGroupDL()->endOfInput(); return; } @@ -1077,33 +991,31 @@ void TupleBPS::run() ByteStream bs; - if (fDelivery) { - deliveryDL.reset(new RowGroupDL(1, 5)); - deliveryIt = deliveryDL->getIterator(); - } - - fBPP->setThreadCount(fMaxNumThreads); - if (doJoin) + if (doJoin) { for (i = 0; i < smallSideCount; i++) - tjoiners[i]->setThreadCount(fMaxNumThreads); + if (isDelivery) + tjoiners[i]->setThreadCount(1); + else + tjoiners[i]->setThreadCount(fNumThreads); + } if (fe1) fBPP->setFEGroup1(fe1, fe1Input); if (fe2 && runFEonPM) fBPP->setFEGroup2(fe2, fe2Output); if (fe2) { - //if (fDelivery) { - // fe2Data.reinit(fe2Output); - // fe2Output.setData(&fe2Data); - //} + if (isDelivery) { + fe2Data.reset(new uint8_t[fe2Output.getMaxDataSize()]); + fe2Output.setData(fe2Data.get()); + } primRowGroup.initRow(&fe2InRow); fe2Output.initRow(&fe2OutRow); } /* if (doJoin) { - for (uint32_t z = 0; z < smallSideCount; z++) + for (uint z = 0; z < smallSideCount; z++) cout << "join #" << z << " " << "0x" << hex << tjoiners[z]->getJoinType() - << std::dec << " typeless: " << (uint32_t) tjoiners[z]->isTypelessJoin() << endl; + << std::dec << " typeless: " << (uint) tjoiners[z]->isTypelessJoin() << endl; } */ @@ -1111,26 +1023,32 @@ void TupleBPS::run() fDec->addDECEventListener(this); fBPP->priority(priority()); fBPP->createBPP(bs); + fMsgBytesOut += bs.length() * fDec->getPmCount(); fDec->write(uniqueID, bs); BPPIsAllocated = true; if (doJoin && tjoiners[0]->inPM()) serializeJoiner(); prepCasualPartitioning(); + startPrimitiveThread(); - startAggregationThread(); + if (!isDelivery) + startAggregationThreads(); } catch (const std::exception& e) { // log the exception cerr << "tuple-bps::run() caught: " << e.what() << endl; - catchHandler(e.what(), ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_TUPLE_BPS); fOutputJobStepAssociation.outAt(0)->rowGroupDL()->endOfInput(); } catch (...) { cerr << "tuple-bps::run() caught unknown exception" << endl; - catchHandler("tuple-bps::run() caught unknown exception", - ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler("tuple-bps::run() caught unknown exception"); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_TUPLE_BPS); fOutputJobStepAssociation.outAt(0)->rowGroupDL()->endOfInput(); } } @@ -1145,37 +1063,41 @@ void TupleBPS::join() if (fRunExecuted) { - if (msgsRecvd < msgsSent) { + if (isDelivery && msgsRecvd < msgsSent) { // wake up the sending thread, it should drain the input dl and exit - mutex.lock(); - condvarWakeupProducer.notify_all(); - mutex.unlock(); + mutex.lock(); //pthread_mutex_lock(&mutex); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); + mutex.unlock(); //pthread_mutex_unlock(&mutex); + // wait for the PM to return all results before destroying the BPPs + while (msgsRecvd + fDec->size(uniqueID) < msgsSent) + sleep(1); } if (pThread) pThread->join(); - for (uint32_t i = 0; i < fMaxNumThreads; i++) - fProducerThread[i]->join(); + if (!isDelivery) + for (uint i = 0; i < fNumThreads; i++) + fProducerThread[i]->join(); if (BPPIsAllocated) { ByteStream bs; fDec->removeDECEventListener(this); fBPP->destroyBPP(bs); try { + fMsgBytesOut += bs.length() * fDec->getPmCount(); fDec->write(uniqueID, bs); } catch (const std::exception& e) { // log the exception cerr << "tuple-bps::join() write(bs) caught: " << e.what() << endl; - catchHandler(e.what(), ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler(e.what()); } catch (...) { cerr << "tuple-bps::join() write(bs) caught unknown exception" << endl; - catchHandler("tuple-bps::join() write(bs) caught unknown exception", - ERR_TUPLE_BPS, fErrorInfo, fSessionId); + catchHandler("tuple-bps::join() write(bs) caught unknown exception"); } BPPIsAllocated = false; @@ -1191,40 +1113,313 @@ void TupleBPS::sendError(uint16_t status) fBPP->setCount(1); fBPP->setStatus(status); fBPP->runErrorBPP(msgBpp); + fMsgBytesOut += msgBpp.lengthWithHdrOverhead(); try { fDec->write(uniqueID, msgBpp); } catch(...) { // this fcn is only called in exception handlers - // let the first error take precedence + // let the first error take precidence } + fMsgBppsToPm++; fBPP->reset(); // msgsSent++; // not expecting a response from this msg finishedSending = true; - condvar.notify_all(); - condvarWakeupProducer.notify_all(); + condvar.notify_all(); //pthread_cond_broadcast(&condvar); + condvarWakeupProducer.notify_all(); //pthread_cond_broadcast(&condvarWakeupProducer); } -uint32_t TupleBPS::nextBand(ByteStream &bs) +/* XXXPAT: This function is ridiculous. Need to replace it with code that uses + * the multithreaded recv fcn & a FIFO once we get tighter control over memory usage. + */ +uint TupleBPS::nextBand(messageqcpp::ByteStream &bs) { - bool more = true; + int64_t min; + int64_t max; + uint64_t lbid; + uint32_t cachedIO=0; + uint32_t physIO=0; + uint32_t touchedBlocks=0; + bool validCPData = false; + boost::shared_ptr bsIn; + boost::shared_array rgData; + uint rows = 0; RowGroup &realOutputRG = (fe2 ? fe2Output : primRowGroup); - RGData rgData; - uint32_t rowCount = 0; bs.restart(); - while (rowCount == 0 && more) { - more = deliveryDL->next(deliveryIt, &rgData); - if (!more) - rgData = fBPP->getErrorRowGroupData(status()); - realOutputRG.setData(&rgData); - rowCount = realOutputRG.getRowCount(); - if ((more && rowCount > 0) || !more) - realOutputRG.serializeRGData(bs); + +again: +try +{ + while (msgsRecvd == msgsSent && !finishedSending && + !fInputJobStepAssociation.status()) + usleep(1000); + + /* "If there are no more messages expected, or if there was an error somewhere else in the joblist..." */ + if ((msgsRecvd == msgsSent && finishedSending) || fInputJobStepAssociation.status()) + { + bsIn.reset(new ByteStream()); + if (fOid>=3000 && traceOn()) dlTimes.setLastReadTime(); + if (fOid>=3000 && traceOn()) dlTimes.setEndOfInputTime(); + /* "If there was an error, make a response with the error code... */ + if (die || fBPP->getStatus() || 0 < fInputJobStepAssociation.status()) + { + /* Note, doesn't matter which rowgroup is used here */ + rgData = fBPP->getErrorRowGroupData(fInputJobStepAssociation.status()); + //cout << "TBPS: returning error status " << fInputJobStepAssociation.status() << endl; + rows = 0; + if (!fInputJobStepAssociation.status()) + fInputJobStepAssociation.status(fBPP->getStatus()); + bs.load(rgData.get(), primRowGroup.getEmptySize()); + } + else + { + /* else, send the special, 0-row last message. */ + bool unused; + rgData = fBPP->getRowGroupData(*bsIn, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks, &unused, 0); + + primRowGroup.setData(rgData.get()); + if (fe2) + { + if (!runFEonPM) + processFE2_oneRG(primRowGroup, fe2Output, fe2InRow, fe2OutRow, fe2.get()); + else + fe2Output.setData(rgData.get()); + } + + rows = realOutputRG.getRowCount(); + bs.load(realOutputRG.getData(), realOutputRG.getDataSize()); + + /* send the cleanup commands to the PM & DEC */ + ByteStream dbs; + fDec->removeDECEventListener(this); + fBPP->destroyBPP(dbs); + fMsgBytesOut += bs.length() * fDec->getPmCount(); + try { + fDec->write(uniqueID, dbs); + } + catch (...) { + // return the result since it's + // completed instead of returning an error. + } + BPPIsAllocated = false; + fDec->removeQueue(uniqueID); + tjoiners.clear(); + + /* A pile of stats gathering */ + if (fOid>=3000) + { + struct timeval tvbuf; + gettimeofday(&tvbuf, 0); + FIFO > *pFifo = 0; + uint64_t totalBlockedReadCount = 0; + uint64_t totalBlockedWriteCount = 0; + + //...Sum up the blocked FIFO reads for all input associations + size_t inDlCnt = fInputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataList > *>( + fInputJobStepAssociation.outAt(iDataList)->rowGroupDL()); + if (pFifo) + { + totalBlockedReadCount += pFifo->blockedReadCount(); + } + } + + //...Sum up the blocked FIFO writes for all output associations + size_t outDlCnt = fOutputJobStepAssociation.outSize(); + for (size_t iDataList=0; iDataList > *>( + fOutputJobStepAssociation.outAt(iDataList)->rowGroupDL()); + if (pFifo) + { + totalBlockedWriteCount += pFifo->blockedWriteCount(); + } + } + + if (traceOn()) + { + //...Roundoff msg byte counts to nearest KB for display + uint64_t msgBytesInKB = fMsgBytesIn >> 10; + uint64_t msgBytesOutKB = fMsgBytesOut >> 10; + if (fMsgBytesIn & 512) + msgBytesInKB++; + if (fMsgBytesOut & 512) + msgBytesOutKB++; + + ostringstream logStr; + logStr << "ses:" << fSessionId << " st: " << fStepId<<" finished at "<< + JSTimeStamp::format(tvbuf) << "; PhyI/O-" << fPhysicalIO << "; CacheI/O-" << + fCacheIO << "; MsgsSent-" << fMsgBppsToPm << "; MsgsRvcd-" << msgsRecvd << + "; BlocksTouched-"<< fBlockTouched << + "; BlockedFifoIn/Out-" << totalBlockedReadCount << + "/" << totalBlockedWriteCount << + "; output size-" << rowsReturned << endl << + "\tPartitionBlocksEliminated-" << fNumBlksSkipped << + "; MsgBytesIn-" << msgBytesInKB << "KB" << + "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << + "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime()) + << "s\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; + logEnd(logStr.str().c_str()); + syslogReadBlockCounts(16, // exemgr sybsystem + fPhysicalIO, // # blocks read from disk + fCacheIO, // # blocks read from cache + fNumBlksSkipped); // # casual partition block hits + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstInsertTime(), // first datalist write + dlTimes.EndOfInputTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + totalBlockedReadCount, // blocked datalist input + totalBlockedWriteCount, // blocked datalist output + fMsgBytesIn, // incoming msg byte count + fMsgBytesOut); // outgoing msg byte count + fExtendedInfo += toString() + logStr.str(); + formatMiniStats(); + } + } + + if (fOid>=3000 && (ffirstStepType == SCAN) && bop == BOP_AND) { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateAllPartitionInfo(); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } + } } - return rowCount; + + /* .. else, this is the next msg to process from the PM... */ + else + { + if (fOid>=3000 && traceOn() && dlTimes.FirstReadTime().tv_sec ==0) + dlTimes.setFirstReadTime(); + fDec->read(uniqueID, bsIn); + firstRead = false; + fMsgBytesIn += bsIn->lengthWithHdrOverhead(); + if (bsIn->length() != 0 && fBPP->countThisMsg(*bsIn)) { + mutex.lock(); //pthread_mutex_lock(&mutex); + msgsRecvd++; + //@Bug 1424, 1298 + if ((sendWaiting) && ((msgsSent - msgsRecvd) <= + (fMaxOutstandingRequests << LOGICAL_EXTENT_CONVERTER))) + { + condvarWakeupProducer.notify_one(); //pthread_cond_signal(&condvarWakeupProducer); + THROTTLEDEBUG << "nextBand wakes up sending side .. " << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; + } + mutex.unlock(); //pthread_mutex_unlock(&mutex); + } + + ISMPacketHeader *hdr = (ISMPacketHeader*)bsIn->buf(); + + // Check for errors and abort + if (bsIn->length() == 0 || 0 < hdr->Status || 0 < fBPP->getStatus() || 0 < fOutputJobStepAssociation.status()) + { + if (bsIn->length() == 0) + fOutputJobStepAssociation.status(ERR_PRIMPROC_DOWN); + else if (hdr->Status) { + string errmsg; + bsIn->advance(sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); + *bsIn >> errmsg; + fOutputJobStepAssociation.status(hdr->Status); + fOutputJobStepAssociation.errorMessage(errmsg); + } + mutex.lock(); //pthread_mutex_lock(&mutex); + + /* What is this supposed to do? */ + if (!fSwallowRows) + { + msgsRecvd = msgsSent; + finishedSending = true; + rows = 0; //send empty message to indicate finished. + } + abort_nolock(); + //cout << "BPS receive signal " << fStepId << endl; + mutex.unlock(); //pthread_mutex_unlock(&mutex); + } + /* " ... no error, process the message */ + else + { + bool unused; + rgData = fBPP->getRowGroupData(*bsIn, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks, &unused, 0); + + primRowGroup.setData(rgData.get()); + if (fe2) { + if (!runFEonPM) + processFE2_oneRG(primRowGroup, fe2Output, fe2InRow, fe2OutRow, fe2.get()); + else + fe2Output.setData(rgData.get()); + } + + if (dupColumns.size() > 0) + dupOutputColumns(realOutputRG); + + if (fOid>=3000 && (ffirstStepType == SCAN) && bop == BOP_AND) + { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateMinMax(min, max, lbid, fColType.colDataType, validCPData); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } + + rows = realOutputRG.getRowCount(); +// cout << "realOutputRG toString()\n"; +// cout << realOutputRG.toString() << endl; +// cout << " -- realout.. rowcount=" << realOutputRG.getRowCount() << "\n"; + bs.load(realOutputRG.getData(), realOutputRG.getDataSize()); +// cout << "loaded\n"; + + } + + fPhysicalIO += physIO; + fCacheIO += cachedIO; + fBlockTouched += touchedBlocks; + +#if 0 + if (fOid>=3000 && (ffirstStepType == SCAN) && bop == BOP_AND) + { + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); + lbidList->UpdateMinMax(min, max, lbid, fColType.colDataType, validCPData); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); + } +#endif + + rowsReturned += rows; + if (rows == 0) + { + bs.restart(); + goto again; + } + } +}//try +catch(const std::exception& ex) +{ + std::string errstr("TupleBPS next band caught exception: "); + errstr.append(ex.what()); + catchHandler(errstr, fSessionId); + fOutputJobStepAssociation.status(ERR_TUPLE_BPS); + bs.restart(); + rgData = fBPP->getErrorRowGroupData(ERR_TUPLE_BPS); + primRowGroup.setData(rgData.get()); + bs.load(rgData.get(), primRowGroup.getDataSize()); + return 0; +} +catch(...) +{ + catchHandler("TupleBPS next band caught an unknown exception", fSessionId); + fOutputJobStepAssociation.status(ERR_TUPLE_BPS); + bs.restart(); + rgData = fBPP->getErrorRowGroupData(ERR_TUPLE_BPS); + primRowGroup.setData(rgData.get()); + bs.load(rgData.get(), primRowGroup.getDataSize()); + return 0; +} + return rows; } + /* The current interleaving rotates over PMs, clustering jobs for a single PM * by dbroot to keep block accesses adjacent & make best use of prefetching & * cache. @@ -1232,8 +1427,8 @@ uint32_t TupleBPS::nextBand(ByteStream &bs) void TupleBPS::interleaveJobs(vector *jobs) const { vector newJobs; - uint32_t i; - uint32_t pmCount = 0; + uint i; + uint pmCount = 0; scoped_array > bins; // the input is grouped by dbroot @@ -1272,10 +1467,10 @@ void TupleBPS::interleaveJobs(vector *jobs) const // the last step is to round-robin on the connections of each PM. // ex: on a 3 PM system where connections per PM is 2, // connections 0 and 3 are for PM 1, 1 and 4 are PM2, 2 and 5 are PM3. - uint32_t *jobCounters = (uint32_t *) alloca(pmCount * sizeof(uint32_t)); - memset(jobCounters, 0, pmCount * sizeof(uint32_t)); + uint *jobCounters = (uint *) alloca(pmCount * sizeof(uint)); + memset(jobCounters, 0, pmCount * sizeof(uint)); for (i = 0; i < newJobs.size(); i++) { - uint32_t &conn = newJobs[i].connectionNum; // for readability's sake + uint &conn = newJobs[i].connectionNum; // for readability's sake conn = conn + (pmCount * jobCounters[conn]); jobCounters[conn]++; } @@ -1290,17 +1485,18 @@ void TupleBPS::interleaveJobs(vector *jobs) const void TupleBPS::sendJobs(const vector &jobs) { - uint32_t i; + uint i; - for (i = 0; i < jobs.size() && !cancelled(); i++) { + for (i = 0; i < jobs.size() && !die && !fInputJobStepAssociation.status(); i++) { //cout << "sending a job for dbroot " << jobs[i].dbroot << ", PM " << jobs[i].connectionNum << endl; fDec->write(uniqueID, *(jobs[i].msg)); mutex.lock(); + fMsgBytesOut += (jobs[i].msg)->length() * fDec->getPmCount(); msgsSent += jobs[i].expectedResponses; if (recvWaiting) condvar.notify_all(); while ((msgsSent - msgsRecvd > fMaxOutstandingRequests << LOGICAL_EXTENT_CONVERTER) - && !fDie) { + && !die) { sendWaiting = true; condvarWakeupProducer.wait(mutex); sendWaiting = false; @@ -1309,297 +1505,37 @@ void TupleBPS::sendJobs(const vector &jobs) } } -bool TupleBPS::compareSingleValue(uint8_t COP, int64_t val1, int64_t val2) const -{ - switch(COP) { - case COMPARE_LT: - case COMPARE_NGE: - return (val1 < val2); - case COMPARE_LE: - case COMPARE_NGT: - return (val1 <= val2); - case COMPARE_GT: - case COMPARE_NLE: - return (val1 > val2); - case COMPARE_GE: - case COMPARE_NLT: - return (val1 >= val2); - case COMPARE_EQ: - return (val1 == val2); - case COMPARE_NE: - return (val1 != val2); - } - return false; -} - -/* (range COP val) comparisons */ -bool TupleBPS::compareRange(uint8_t COP, int64_t min, int64_t max, int64_t val) const -{ - switch(COP) { - case COMPARE_LT: - case COMPARE_NGE: - return (min < val); - case COMPARE_LE: - case COMPARE_NGT: - return (min <= val); - case COMPARE_GT: - case COMPARE_NLE: - return (max > val); - case COMPARE_GE: - case COMPARE_NLT: - return (max >= val); - case COMPARE_EQ: // an 'in' comparison - return (val >= min && val <= max); - case COMPARE_NE: // 'not in' - return (val < min || val > max); - } - return false; -} - -bool TupleBPS::processSingleFilterString_ranged(int8_t BOP, int8_t colWidth, int64_t min, int64_t max, const uint8_t *filterString, - uint32_t filterCount) const -{ - uint j; - bool ret = true; - - for (j = 0; j < filterCount; j++) { - int8_t COP; - int64_t val2; - bool thisPredicate; - COP = *filterString++; - filterString++; // skip the round var, don't think that applies here - switch (colWidth) { - case 1: - val2 = *((int8_t *) filterString); - filterString++; - break; - case 2: - val2 = *((int16_t *) filterString); - filterString += 2; - break; - case 4: - val2 = *((int32_t *) filterString); - filterString += 4; - break; - case 8: - val2 = *((int64_t *) filterString); - filterString += 8; - break; - default: - throw logic_error("invalid column width"); - } - thisPredicate = compareRange(COP, min, max, val2); - if (j == 0) - ret = thisPredicate; - if (BOP == BOP_OR && thisPredicate) - return true; - else if (BOP == BOP_AND && !thisPredicate) - return false; - } - return ret; -} - -bool TupleBPS::processSingleFilterString(int8_t BOP, int8_t colWidth, int64_t val, const uint8_t *filterString, - uint32_t filterCount) const -{ - uint j; - bool ret = true; - - for (j = 0; j < filterCount; j++) { - int8_t COP; - int64_t val2; - bool thisPredicate; - COP = *filterString++; - filterString++; // skip the round var, don't think that applies here - switch (colWidth) { - case 1: - val2 = *((int8_t *) filterString); - filterString++; - break; - case 2: - val2 = *((int16_t *) filterString); - filterString += 2; - break; - case 4: - val2 = *((int32_t *) filterString); - filterString += 4; - break; - case 8: - val2 = *((int64_t *) filterString); - filterString += 8; - break; - default: - throw logic_error("invalid column width"); - } - thisPredicate = compareSingleValue(COP, val, val2); - if (j == 0) - ret = thisPredicate; - if (BOP == BOP_OR && thisPredicate) - return true; - else if (BOP == BOP_AND && !thisPredicate) - return false; - } - return ret; -} - -bool TupleBPS::processOneFilterType(int8_t colWidth, int64_t value, uint32_t type) const -{ - const vector& filters = fBPP->getFilterSteps(); - uint i; - bool ret = true; - bool firstPseudo = true; - - for (i = 0; i < filters.size(); i++) { - PseudoCCJL *pseudo = dynamic_cast(filters[i].get()); - if (!pseudo || pseudo->getFunction() != type) - continue; - - int8_t BOP = pseudo->getBOP(); // I think this is the same as TupleBPS's bop var...? - - /* 1-byte COP, 1-byte 'round', colWidth-bytes value */ - const uint8_t *filterString = pseudo->getFilterString().buf(); - uint32_t filterCount = pseudo->getFilterCount(); - bool thisPredicate = processSingleFilterString(BOP, colWidth, value, filterString, filterCount); - - if (firstPseudo) { - firstPseudo = false; - ret = thisPredicate; - } - if (bop == BOP_OR && thisPredicate) - return true; - else if (bop == BOP_AND && !thisPredicate) - return false; - } - return ret; -} - -bool TupleBPS::processLBIDFilter(const EMEntry &emEntry) const -{ - const vector& filters = fBPP->getFilterSteps(); - uint i; - bool ret = true; - bool firstPseudo = true; - LBID_t firstLBID = emEntry.range.start; - LBID_t lastLBID = firstLBID + (emEntry.range.size * 1024) - 1; - - for (i = 0; i < filters.size(); i++) { - PseudoCCJL *pseudo = dynamic_cast(filters[i].get()); - if (!pseudo || pseudo->getFunction() != PSEUDO_BLOCKID) - continue; - - int8_t BOP = pseudo->getBOP(); // I think this is the same as TupleBPS's bop var...? - - /* 1-byte COP, 1-byte 'round', colWidth-bytes value */ - const uint8_t *filterString = pseudo->getFilterString().buf(); - uint32_t filterCount = pseudo->getFilterCount(); - bool thisPredicate = processSingleFilterString_ranged(BOP, 8, - firstLBID, lastLBID, filterString, filterCount); - - if (firstPseudo) { - firstPseudo = false; - ret = thisPredicate; - } - if (bop == BOP_OR && thisPredicate) - return true; - else if (bop == BOP_AND && !thisPredicate) - return false; - } - return ret; -} - -bool TupleBPS::processPseudoColFilters(uint32_t extentIndex, boost::shared_ptr > dbRootPMMap) const -{ - if (!hasPCFilter) - return true; - - const EMEntry &emEntry = scannedExtents[extentIndex]; - - if (bop == BOP_AND) { - /* All Pseudocolumns have been promoted to 8-bytes except the casual partitioning filters */ - return (!hasPMFilter || processOneFilterType(8, (*dbRootPMMap)[emEntry.dbRoot], PSEUDO_PM)) - && (!hasSegmentFilter || processOneFilterType(8, emEntry.segmentNum, PSEUDO_SEGMENT)) - && (!hasDBRootFilter || processOneFilterType(8, emEntry.dbRoot, PSEUDO_DBROOT)) - && (!hasSegmentDirFilter || processOneFilterType(8, emEntry.partitionNum, PSEUDO_SEGMENTDIR)) - && (!hasExtentIDFilter || processOneFilterType(8, emEntry.range.start, PSEUDO_EXTENTID)) - && (!hasMaxFilter || (emEntry.partition.cprange.isValid == BRM::CP_VALID ? - processOneFilterType(emEntry.range.size, emEntry.partition.cprange.hi_val, PSEUDO_EXTENTMAX) : true)) - && (!hasMinFilter || (emEntry.partition.cprange.isValid == BRM::CP_VALID ? - processOneFilterType(emEntry.range.size, emEntry.partition.cprange.lo_val, PSEUDO_EXTENTMIN) : true)) - && (!hasLBIDFilter || processLBIDFilter(emEntry)) - ; - } - else { - return (hasPMFilter && processOneFilterType(8, (*dbRootPMMap)[emEntry.dbRoot], PSEUDO_PM)) - || (hasSegmentFilter && processOneFilterType(8, emEntry.segmentNum, PSEUDO_SEGMENT)) - || (hasDBRootFilter && processOneFilterType(8, emEntry.dbRoot, PSEUDO_DBROOT)) - || (hasSegmentDirFilter && processOneFilterType(8, emEntry.partitionNum, PSEUDO_SEGMENTDIR)) - || (hasExtentIDFilter && processOneFilterType(8, emEntry.range.start, PSEUDO_EXTENTID)) - || (hasMaxFilter && (emEntry.partition.cprange.isValid == BRM::CP_VALID ? - processOneFilterType(emEntry.range.size, emEntry.partition.cprange.hi_val, PSEUDO_EXTENTMAX) : false)) - || (hasMinFilter && (emEntry.partition.cprange.isValid == BRM::CP_VALID ? - processOneFilterType(emEntry.range.size, emEntry.partition.cprange.lo_val, PSEUDO_EXTENTMIN) : false)) - || (hasLBIDFilter && processLBIDFilter(emEntry)) - ; - } -} - - void TupleBPS::makeJobs(vector *jobs) { - boost::shared_ptr bs; - uint32_t i; - uint32_t lbidsToScan; - uint32_t blocksToScan; - uint32_t blocksPerJob; + shared_ptr bs; + uint i; + uint lbidsToScan; + uint blocksToScan; + uint blocksPerJob; LBID_t startingLBID; oam::OamCache *oamCache = oam::OamCache::makeOamCache(); - boost::shared_ptr > dbRootConnectionMap = oamCache->getDBRootToConnectionMap(); - boost::shared_ptr > dbRootPMMap = oamCache->getDBRootToPMMap(); - int localPMId = oamCache->getLocalPMId(); + shared_ptr > dbRootConnectionMap = oamCache->getDBRootToConnectionMap(); idbassert(ffirstStepType == SCAN); if (fOid >= 3000 && bop == BOP_AND) storeCasualPartitionInfo(false); - totalMsgs = 0; for (i = 0; i < scannedExtents.size(); i++) { - // the # of LBIDs to scan in this extent, if it will be scanned. - //@bug 5322: status EXTENTSTATUSMAX+1 means single block extent. - if ((scannedExtents[i].HWM == 0) && - ((int) i < lastExtent[scannedExtents[i].dbRoot-1]) && - (scannedExtents[i].status <= EXTENTSTATUSMAX)) + // the # of LBIDs to scan in this extent, if it will be scanned + if (scannedExtents[i].HWM == 0 && (int) i < lastExtent[scannedExtents[i].dbRoot-1]) lbidsToScan = scannedExtents[i].range.size * 1024; - else - lbidsToScan = scannedExtents[i].HWM - scannedExtents[i].blockOffset + 1; + else + lbidsToScan = scannedExtents[i].HWM - scannedExtents[i].blockOffset + 1; // skip this extent if CP data rules it out or the scan has already passed // the last extent for that DBRoot (import may be adding extents that shouldn't - // be read yet). Also skip if there's a pseudocolumn with a filter that would - // eliminate this extent - - bool inBounds = ((int)i <= lastExtent[scannedExtents[i].dbRoot-1]); - - if (!inBounds) { - //cout << "out of bounds" << endl; - continue; - } - - if (!scanFlags[i]) { - //cout << "CP elimination" << endl; - fNumBlksSkipped += lbidsToScan; - continue; - } - - if (!processPseudoColFilters(i, dbRootPMMap)) { - //cout << "Skipping an extent due to pseudo-column filter elimination" << endl; + // be read yet). + if (!scanFlags[i] && (int)i <= lastExtent[scannedExtents[i].dbRoot-1]) fNumBlksSkipped += lbidsToScan; + if (!scanFlags[i] || (int)i > lastExtent[scannedExtents[i].dbRoot-1]) continue; - } - - //if (!scanFlags[i] || !inBounds) - // continue; /* Figure out many blocks have data in this extent * Calc how many jobs to issue, @@ -1607,17 +1543,6 @@ void TupleBPS::makeJobs(vector *jobs) * construct the job msgs */ - // Bug5741 If we are local only and this doesn't belongs to us, skip it - if (fLocalQuery == execplan::CalpontSelectExecutionPlan::LOCAL_QUERY) - { - if (localPMId == 0) - { - throw IDBExcept(ERR_LOCAL_QUERY_UM); - } - if (dbRootPMMap->find(scannedExtents[i].dbRoot)->second != localPMId) - continue; - } - // a necessary DB root is offline if (dbRootConnectionMap->find(scannedExtents[i].dbRoot) == dbRootConnectionMap->end()) throw IDBExcept(ERR_DATA_OFFLINE); @@ -1631,10 +1556,8 @@ void TupleBPS::makeJobs(vector *jobs) else blocksToScan = lbidsToScan/fColType.colWidth; - totalMsgs += blocksToScan; - // how many logical blocks to process with a single job (& single thread on the PM) -#if defined(_MSC_VER) && BOOST_VERSION < 105200 +#ifdef _MSC_VER blocksPerJob = max(blocksToScan/fProcessorThreadsPerScan, 16UL); #else blocksPerJob = max(blocksToScan/fProcessorThreadsPerScan, 16U); @@ -1644,17 +1567,17 @@ void TupleBPS::makeJobs(vector *jobs) startingLBID = scannedExtents[i].range.start; while (blocksToScan > 0) { - uint32_t blocksThisJob = min(blocksToScan, blocksPerJob); + uint blocksThisJob = min(blocksToScan, blocksPerJob); //cout << "starting LBID = " << startingLBID << " count = " << blocksThisJob << // " dbroot = " << scannedExtents[i].dbRoot << endl; - fBPP->setLBID(startingLBID, scannedExtents[i]); + fBPP->setLBID(startingLBID, scannedExtents[i].dbRoot); fBPP->setCount(blocksThisJob); bs.reset(new ByteStream()); fBPP->runBPP(*bs, (*dbRootConnectionMap)[scannedExtents[i].dbRoot]); //cout << "making job for connection # " << (*dbRootConnectionMap)[scannedExtents[i].dbRoot] << endl; jobs->push_back(Job(scannedExtents[i].dbRoot, (*dbRootConnectionMap)[scannedExtents[i].dbRoot], - blocksThisJob, bs)); + blocksThisJob, bs)); blocksToScan -= blocksThisJob; startingLBID += fColType.colWidth * blocksThisJob; fBPP->reset(); @@ -1670,7 +1593,7 @@ void TupleBPS::sendPrimitiveMessages() idbassert(ffirstStepType == SCAN); - if (cancelled()) + if (fInputJobStepAssociation.status() != 0) goto abort; try { @@ -1679,17 +1602,14 @@ void TupleBPS::sendPrimitiveMessages() sendJobs(jobs); } catch(const IDBExcept &e) { - //cout << "Caught IDBExcept" << e.what() << e.errorCode() << endl; sendError(e.errorCode()); processError(e.what(), e.errorCode(), "TupleBPS::sendPrimitiveMessages()"); } catch(const std::exception& ex) { - //cout << "Caught exception" << endl; sendError(ERR_TUPLE_BPS); processError(ex.what(), ERR_TUPLE_BPS, "TupleBPS::sendPrimitiveMessages()"); } catch(...) { - //cout << "Caught ..." << endl; sendError(ERR_TUPLE_BPS); processError("unknown", ERR_TUPLE_BPS, "TupleBPS::sendPrimitiveMessages()"); } @@ -1709,17 +1629,16 @@ struct _CPInfo { bool valid; }; -void TupleBPS::receiveMultiPrimitiveMessages(uint32_t threadID) +void TupleBPS::receiveMultiPrimitiveMessages(uint threadID) { AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); - RowGroupDL* dlp = (fDelivery ? deliveryDL.get() : dl->rowGroupDL()); + RowGroupDL* dlp = dl->rowGroupDL(); - uint32_t size = 0; + uint size = 0; vector > bsv; - RGData rgData; - vector rgDatav; - vector fromPrimProc; + boost::shared_array rgData; + vector > rgDatav; bool validCPData; int64_t min; @@ -1729,19 +1648,20 @@ void TupleBPS::receiveMultiPrimitiveMessages(uint32_t threadID) uint32_t cachedIO; uint32_t physIO; uint32_t touchedBlocks; + uint64_t msgBytesIn_Thread = 0; uint32_t cachedIO_Thread = 0; uint32_t physIO_Thread = 0; uint32_t touchedBlocks_Thread = 0; int64_t ridsReturned_Thread = 0; bool lastThread = false; - uint32_t i, j, k; + uint i, j, k; RowGroup local_primRG = primRowGroup; RowGroup local_outputRG = outputRowGroup; bool didEOF = false; bool unused; /* Join vars */ - vector > joinerOutput; // clean usage + vector > joinerOutput; // clean usage Row largeSideRow, joinedBaseRow, largeNull, joinFERow; // LSR clean scoped_array smallSideRows, smallNulls; scoped_array joinedBaseRowData; @@ -1749,20 +1669,17 @@ void TupleBPS::receiveMultiPrimitiveMessages(uint32_t threadID) shared_array largeMapping; vector > smallMappings; vector > fergMappings; - RGData joinedData; + shared_array joinedData; scoped_array largeNullMemory; scoped_array > smallNullMemory; - uint32_t matchCount; + uint matchCount; /* Thread-scoped F&E 2 var */ Row postJoinRow; // postJoinRow is also used for joins RowGroup local_fe2Output; - RGData local_fe2Data; + scoped_array local_fe2Data; Row local_fe2OutRow; funcexp::FuncExpWrapper local_fe2; - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; try { @@ -1772,8 +1689,8 @@ try if (fe2) { local_fe2Output = fe2Output; local_fe2Output.initRow(&local_fe2OutRow); - local_fe2Data.reinit(fe2Output); - local_fe2Output.setData(&local_fe2Data); + local_fe2Data.reset(new uint8_t[fe2Output.getMaxDataSize()]); + local_fe2Output.setData(local_fe2Data.get()); // local_fe2OutRow = fe2OutRow; local_fe2 = *fe2; } @@ -1785,10 +1702,9 @@ try fergMappings.resize(smallSideCount + 1); smallNullMemory.reset(new shared_array[smallSideCount]); local_primRG.initRow(&largeSideRow); - local_outputRG.initRow(&joinedBaseRow, true); + local_outputRG.initRow(&joinedBaseRow); joinedBaseRowData.reset(new uint8_t[joinedBaseRow.getSize()]); joinedBaseRow.setData(joinedBaseRowData.get()); - joinedBaseRow.initToNull(); largeMapping = makeMapping(local_primRG, local_outputRG); bool hasJoinFE = false; @@ -1803,7 +1719,7 @@ try // } } if (hasJoinFE) { - joinFERG.initRow(&joinFERow, true); + joinFERG.initRow(&joinFERow); joinFERowData.reset(new uint8_t[joinFERow.getSize()]); memset(joinFERowData.get(), 0, joinFERow.getSize()); joinFERow.setData(joinFERowData.get()); @@ -1811,12 +1727,12 @@ try } for (i = 0; i < smallSideCount; i++) { - joinerMatchesRGs[i].initRow(&smallNulls[i], true); + joinerMatchesRGs[i].initRow(&smallNulls[i]); smallNullMemory[i].reset(new uint8_t[smallNulls[i].getSize()]); smallNulls[i].setData(smallNullMemory[i].get()); smallNulls[i].initToNull(); } - local_primRG.initRow(&largeNull, true); + local_primRG.initRow(&largeNull); largeNullMemory.reset(new uint8_t[largeNull.getSize()]); largeNull.setData(largeNullMemory.get()); largeNull.initToNull(); @@ -1843,7 +1759,7 @@ try for (i = 0; i < local_primRG.getColumnCount(); i++) cout << largeMapping[i] << " "; cout << endl; - for (uint32_t z = 0; z < smallSideCount; z++) { + for (uint z = 0; z < smallSideCount; z++) { cout << "small mapping[" << z << "] :\n"; for (i = 0; i < joinerMatchesRGs[z].getColumnCount(); i++) cout << smallMappings[z][i] << " "; @@ -1856,7 +1772,7 @@ try mutex.lock(); while (1) { - // sync with the send side + // sync with the send side while (!finishedSending && msgsSent == msgsRecvd) { recvWaiting++; condvar.wait(mutex); @@ -1866,41 +1782,9 @@ try if (msgsSent == msgsRecvd && finishedSending) break; - bool flowControlOn; - fDec->read_some(uniqueID, fNumThreads, bsv, &flowControlOn); + fDec->read_some(uniqueID, fNumThreads, bsv); size = bsv.size(); - - // @bug 4562 - if (traceOn() && fOid>=3000 && dlTimes.FirstReadTime().tv_sec==0) - dlTimes.setFirstReadTime(); - - if (fOid>=3000 && threadID == 0 && sts.msg_type == StepTeleStats::ST_INVALID && size > 0) - { - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = totalMsgs; - postStepStartTele(sts); - } - - /* This is a simple ramp-up of the TBPS msg processing threads. - One thread is created by run(), and add'l threads are created - as needed. Right now, "as needed" means that flow control - is on, which means that the UM is not keeping up by definition, - or size > 5. We found that using flow control alone was not aggressive - enough when the messages were small. The 'size' parameter checks - the number of msgs waiting in the DEC buffers. Since each - message can be processed independently of the others, they can all - be processed in different threads. In benchmarking we found that - there was no end-to-end performance difference between using 1 - and 20 msgs as the threshold. Erring on the side of aggressiveness, - we chose '5'. - '5' still preserves the original goal of not starting MAX threads - for small queries or when the UM can keep up with the PMs with - fewer threads. Tweak as necessary. */ - - if ((size > 5 || flowControlOn) && fNumThreads < fMaxNumThreads) - startAggregationThread(); - - for (uint32_t z = 0; z < size; z++) { + for (uint z = 0; z < size; z++) { if (bsv[z]->length() > 0 && fBPP->countThisMsg(*(bsv[z]))) ++msgsRecvd; } @@ -1908,20 +1792,45 @@ try if (sendWaiting && ((msgsSent - msgsRecvd) <= (fMaxOutstandingRequests << LOGICAL_EXTENT_CONVERTER))) { - condvarWakeupProducer.notify_one(); + condvarWakeupProducer.notify_one(); //pthread_cond_signal(&condvarWakeupProducer); THROTTLEDEBUG << "receiveMultiPrimitiveMessages wakes up sending side .. " << " msgsSent: " << msgsSent << " msgsRecvd = " << msgsRecvd << endl; } + // @bug 4562 + if (fOid>=3000 && traceOn() && dlTimes.FirstReadTime().tv_sec==0) + dlTimes.setFirstReadTime(); + /* If there's an error and the joblist is being aborted, don't sit around forever waiting for responses. */ - if (cancelled()) { + if (fInputJobStepAssociation.status() != 0 || die) { if (sendWaiting) condvarWakeupProducer.notify_one(); break; + +#if 0 + // thread 0 stays, the rest finish & exit to allow a quicker EOF + if (threadID != 0 || fNumThreads == 1) + break; + else if (!didEOF) { + didEOF = true; + // need a time limit here too? Better to leak something than to hang? + while (recvExited < fNumThreads - 1) + usleep(100000); + dlp->endOfInput(); + } + if (size != 0) // got something, reset the timer and go again + errorTimeout = 0; + + usleep(5000); + mutex.lock(); //pthread_mutex_lock(&mutex); + if (++errorTimeout == 1000) // 5 sec delay + break; + continue; +#endif } if (size == 0) { mutex.unlock(); - usleep(2000 * fNumThreads); + usleep(1000); mutex.lock(); continue; } @@ -1929,7 +1838,7 @@ try mutex.unlock(); // cout << "thread " << threadID << " has " << size << " Bytestreams\n"; - for (i = 0; i < size && !cancelled(); i++) { + for (i = 0; i < size && !die; i++) { ByteStream* bs = bsv[i].get(); // @bug 488. when PrimProc node is down. error out @@ -1941,8 +1850,7 @@ try mutex.lock(); if (bs->length() == 0) { - errorMessage(IDBErrorInfo::instance()->errorMsg(ERR_PRIMPROC_DOWN)); - status(ERR_PRIMPROC_DOWN); + fOutputJobStepAssociation.status(ERR_PRIMPROC_DOWN); } else { @@ -1950,176 +1858,173 @@ try bs->advance(sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); *bs >> errMsg; - status(hdr->Status); - errorMessage(errMsg); + fOutputJobStepAssociation.status(hdr->Status); + fOutputJobStepAssociation.errorMessage(errMsg); } abort_nolock(); + if (hdr && multicastErr == hdr->Status) + { + fDec->setMulticast(false); + } goto out; } - fromPrimProc.clear(); - fBPP->getRowGroupData(*bs, &fromPrimProc, &validCPData, &lbid, &min, &max, + msgBytesIn_Thread += bs->lengthWithHdrOverhead(); + + rgData = fBPP->getRowGroupData(*bs, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks, &unused, threadID); - /* Another layer of messiness. Need to refactor this fcn. */ - while (!fromPrimProc.empty() && !cancelled()) { - rgData = fromPrimProc.back(); - fromPrimProc.pop_back(); - - local_primRG.setData(&rgData); - ridsReturned_Thread += local_primRG.getRowCount(); // TODO need the pre-join count even on PM joins... later - - /* TupleHashJoinStep::joinOneRG() is a port of the main join loop here. Any - * changes made here should also be made there and vice versa. */ - if (hasUMJoin || !fBPP->pmSendsFinalResult()) { - joinedData = RGData(local_outputRG); - local_outputRG.setData(&joinedData); - local_outputRG.resetRowGroup(local_primRG.getBaseRid()); - local_outputRG.setDBRoot(local_primRG.getDBRoot()); - local_primRG.getRow(0, &largeSideRow); - //cout << "large-side raw data: " << local_primRG.toString() << endl; - - //cout << "jointype = " << tjoiners[0]->getJoinType() << endl; - for (k = 0; k < local_primRG.getRowCount() && !cancelled(); k++, largeSideRow.nextRow()) { - //cout << "TBPS: Large side row: " << largeSideRow.toString() << endl; - matchCount = 0; - for (j = 0; j < smallSideCount; j++) { - tjoiners[j]->match(largeSideRow, k, threadID, &joinerOutput[j]); - /* Debugging code to print the matches - Row r; - joinerMatchesRGs[j].initRow(&r); - cout << joinerOutput[j].size() << " matches: \n"; - for (uint32_t z = 0; z < joinerOutput[j].size(); z++) { - r.setPointer(joinerOutput[j][z]); - cout << " " << r.toString() << endl; - } - */ - matchCount = joinerOutput[j].size(); - if (tjoiners[j]->inUM()) { - /* Count the # of rows that pass the join filter */ - if (tjoiners[j]->hasFEFilter() && matchCount > 0) { - //cout << "doing FE filter" << endl; - vector newJoinerOutput; - applyMapping(fergMappings[smallSideCount], largeSideRow, &joinFERow); - for (uint32_t z = 0; z < joinerOutput[j].size(); z++) { - smallSideRows[j].setPointer(joinerOutput[j][z]); - applyMapping(fergMappings[j], smallSideRows[j], &joinFERow); - if (!tjoiners[j]->evaluateFilter(joinFERow, threadID)) - matchCount--; - else { - /* The first match includes it in a SEMI join result and excludes it from an ANTI join - * result. If it's SEMI & SCALAR however, it needs to continue. - */ - newJoinerOutput.push_back(joinerOutput[j][z]); - if (tjoiners[j]->antiJoin() || (tjoiners[j]->semiJoin() && !tjoiners[j]->scalar())) - break; - } - } - // the filter eliminated all matches, need to join with the NULL row - if (matchCount == 0 && tjoiners[j]->largeOuterJoin()) { - newJoinerOutput.push_back(Row::Pointer(smallNullMemory[j].get())); - matchCount = 1; + local_primRG.setData(rgData.get()); +// cout << "rowcount is " << local_primRG.getRowCount() << endl; + ridsReturned_Thread += local_primRG.getRowCount(); // TODO need the pre-join count even on PM joins... later + + /* TupleHashJoinStep::joinOneRG() is a port of the main join loop here. Any + * changes made here should also be made there and vice versa. */ + if (hasUMJoin || !fBPP->pmSendsFinalResult()) { + joinedData.reset(new uint8_t[local_outputRG.getMaxDataSize()]); + local_outputRG.setData(joinedData.get()); + local_outputRG.resetRowGroup(local_primRG.getBaseRid()); + local_outputRG.setDBRoot(local_primRG.getDBRoot()); +// local_outputRG.getRow(0, &joinedRow); + local_primRG.getRow(0, &largeSideRow); + for (k = 0; k < local_primRG.getRowCount() && !die; k++, largeSideRow.nextRow()) { + //cout << "TBPS: Large side row: " << largeSideRow.toString() << endl; + matchCount = 0; + for (j = 0; j < smallSideCount; j++) { + tjoiners[j]->match(largeSideRow, k, threadID, &joinerOutput[j]); + + /* Debugging code to print the matches + Row r; + joinerMatchesRGs[j].initRow(&r); + cout << "matches: \n"; + for (uint z = 0; z < joinerOutput[j].size(); z++) { + r.setData(joinerOutput[j][z]); + cout << " " << r.toString() << endl; + } + */ + matchCount = joinerOutput[j].size(); + if (tjoiners[j]->inUM()) { + /* Count the # of rows that pass the join filter */ + if (tjoiners[j]->hasFEFilter() && matchCount > 0) { + vector newJoinerOutput; + applyMapping(fergMappings[smallSideCount], largeSideRow, &joinFERow); + for (uint z = 0; z < joinerOutput[j].size(); z++) { + smallSideRows[j].setData(joinerOutput[j][z]); + applyMapping(fergMappings[j], smallSideRows[j], &joinFERow); + if (!tjoiners[j]->evaluateFilter(joinFERow, threadID)) + matchCount--; + else { + /* The first match includes it in a SEMI join result and excludes it from an ANTI join + * result. If it's SEMI & SCALAR however, it needs to continue. + */ + newJoinerOutput.push_back(joinerOutput[j][z]); + if (tjoiners[j]->antiJoin() || (tjoiners[j]->semiJoin() && !tjoiners[j]->scalar())) + break; } - - joinerOutput[j].swap(newJoinerOutput); } - // XXXPAT: This has gone through enough revisions it would benefit - // from refactoring - - /* If anti-join, reverse the result */ - if (tjoiners[j]->antiJoin()) { - matchCount = (matchCount ? 0 : 1); - // if (matchCount) - // cout << "in the result\n"; - // else - // cout << "not in the result\n"; + // the filter eliminated all matches, need to join with the NULL row + if (matchCount == 0 && tjoiners[j]->largeOuterJoin()) { + newJoinerOutput.push_back(smallNullMemory[j].get()); + matchCount = 1; } - if (matchCount == 0) { - joinerOutput[j].clear(); - break; - } - else if (!tjoiners[j]->scalar() && + joinerOutput[j].swap(newJoinerOutput); + } + // XXXPAT: This has gone through enough revisions it would benefit + // from refactoring + + /* If anti-join, reverse the result */ + if (tjoiners[j]->antiJoin()) { + matchCount = (matchCount ? 0 : 1); + // if (matchCount) + // cout << "in the result\n"; + // else + // cout << "not in the result\n"; + } + + if (matchCount == 0) { + joinerOutput[j].clear(); + break; + } + else if (!tjoiners[j]->scalar() && (tjoiners[j]->antiJoin() || tjoiners[j]->semiJoin())) { joinerOutput[j].clear(); - joinerOutput[j].push_back(Row::Pointer(smallNullMemory[j].get())); + joinerOutput[j].push_back(smallNullMemory[j].get()); matchCount = 1; - } } + } - if (matchCount == 0 && tjoiners[j]->innerJoin()) - break; - - /* Scalar check */ - if (tjoiners[j]->scalar() && matchCount > 1) { - errorMessage(IDBErrorInfo::instance()->errorMsg(ERR_MORE_THAN_1_ROW)); - status(ERR_MORE_THAN_1_ROW); - abort(); - } - if (tjoiners[j]->smallOuterJoin()) - tjoiners[j]->markMatches(threadID, joinerOutput[j]); + if (matchCount == 0 && tjoiners[j]->innerJoin()) + break; + /* Scalar check */ + if (tjoiners[j]->scalar() && matchCount > 1) { + fOutputJobStepAssociation.status(ERR_MORE_THAN_1_ROW); + abort(); } - if (matchCount > 0) { - applyMapping(largeMapping, largeSideRow, &joinedBaseRow); - joinedBaseRow.setRid(largeSideRow.getRelRid()); - generateJoinResultSet(joinerOutput, joinedBaseRow, smallMappings, - 0, local_outputRG, joinedData, &rgDatav, smallSideRows, postJoinRow); - /* Bug 3510: Don't let the join results buffer get out of control. Need - to refactor this. All post-join processing needs to go here AND below - for now. */ - if (rgDatav.size() * local_outputRG.getMaxDataSize() > 50000000) { - RowGroup out(local_outputRG); - if (fe2 && !runFEonPM) { - processFE2(out, local_fe2Output, postJoinRow, - local_fe2OutRow, &rgDatav, &local_fe2); - rgDataVecToDl(rgDatav, local_fe2Output, dlp); - } - else - rgDataVecToDl(rgDatav, out, dlp); - } - } - } // end of the for-loop in the join code + if (tjoiners[j]->smallOuterJoin()) + tjoiners[j]->markMatches(threadID, joinerOutput[j]); - if (local_outputRG.getRowCount() > 0) { - rgDatav.push_back(joinedData); } - } - else { -// cout << "TBPS: sending unjoined data\n"; - rgDatav.push_back(rgData); - } + if (matchCount > 0) { + applyMapping(largeMapping, largeSideRow, &joinedBaseRow); + joinedBaseRow.setRid(largeSideRow.getRid()); + generateJoinResultSet(joinerOutput, joinedBaseRow, smallMappings, + 0, local_outputRG, joinedData, &rgDatav, smallSideRows, postJoinRow); + /* Bug 3510: Don't let the join results buffer get out of control. Need + to refactor this. All post-join processing needs to go here AND below + for now. */ + if (rgDatav.size() * local_outputRG.getMaxDataSize() > 50000000) { + RowGroup out(local_outputRG); + if (fe2 && !runFEonPM) { + processFE2(out, local_fe2Output, postJoinRow, + local_fe2OutRow, &rgDatav, &local_fe2); + rgDataVecToDl(rgDatav, local_fe2Output, dlp); + } + else + rgDataVecToDl(rgDatav, out, dlp); + } + } + } // end of the for-loop - /* Execute UM F & E group 2 on rgDatav */ - if (fe2 && !runFEonPM && rgDatav.size() > 0 && !cancelled()) { - processFE2(local_outputRG, local_fe2Output, postJoinRow, local_fe2OutRow, &rgDatav, &local_fe2); - rgDataVecToDl(rgDatav, local_fe2Output, dlp); + if (local_outputRG.getRowCount() > 0) { + rgDatav.push_back(joinedData); } + } + else { +// cout << "TBPS: sending unjoined data\n"; + rgDatav.push_back(rgData); + } - cachedIO_Thread += cachedIO; - physIO_Thread += physIO; - touchedBlocks_Thread += touchedBlocks; - if (fOid >= 3000 && ffirstStepType == SCAN && bop == BOP_AND) - cpv.push_back(_CPInfo(min, max, lbid, validCPData)); - } // end of the per-rowgroup processing loop - - // insert the resulting rowgroup data from a single bytestream into dlp - if (rgDatav.size() > 0) { - if (fe2 && runFEonPM) - rgDataVecToDl(rgDatav, local_fe2Output, dlp); - else - rgDataVecToDl(rgDatav, local_outputRG, dlp); + /* Execute UM F & E group 2 on rgDatav */ + if (fe2 && !runFEonPM && rgDatav.size() > 0 && !die) { + processFE2(local_outputRG, local_fe2Output, postJoinRow, local_fe2OutRow, &rgDatav, &local_fe2); + rgDataVecToDl(rgDatav, local_fe2Output, dlp); } - } // end of the per-bytestream loop + + cachedIO_Thread += cachedIO; + physIO_Thread += physIO; + touchedBlocks_Thread += touchedBlocks; + if (fOid >= 3000 && ffirstStepType == SCAN && bop == BOP_AND) + cpv.push_back(_CPInfo(min, max, lbid, validCPData)); + } + + // insert the rowgroup data into dlp + if (rgDatav.size() > 0) { + if (fe2 && runFEonPM) + rgDataVecToDl(rgDatav, local_fe2Output, dlp); + else + rgDataVecToDl(rgDatav, local_outputRG, dlp); + } // @bug 4562 - if (traceOn() && fOid>=3000) + if (fOid>=3000 && traceOn() && dlTimes.FirstInsertTime().tv_sec==0) dlTimes.setFirstInsertTime(); //update casual partition size = cpv.size(); - if (size > 0 && !cancelled()) { + if (size > 0 && fInputJobStepAssociation.status() == 0) { cpMutex.lock(); for (i = 0; i < size; i++) { lbidList->UpdateMinMax(cpv[i].min, cpv[i].max, cpv[i].LBID, fColType.colDataType, @@ -2128,24 +2033,7 @@ try cpMutex.unlock(); } cpv.clear(); - mutex.lock(); - - if (fOid >= 3000) - { - uint64_t progress = msgsRecvd * 100 / totalMsgs; - bool postProgress = (progress > fProgress); - if (postProgress) - { - fProgress = progress; - - sts.msg_type = StepTeleStats::ST_PROGRESS; - sts.total_units_of_work = totalMsgs; - sts.units_of_work_completed = msgsRecvd; - postStepProgressTele(sts); - } - } - } // done reading }//try @@ -2161,25 +2049,25 @@ catch(...) out: if (++recvExited == fNumThreads) { - if (doJoin && smallOuterJoiner != -1 && !cancelled()) { - mutex.unlock(); + if (doJoin && smallOuterJoiner != -1 && + fInputJobStepAssociation.status() == 0 && !die) { + mutex.unlock(); //Bug 5499 /* If this was a left outer join, this needs to put the unmatched - rows from the joiner into the output + rows from the joiner into the output XXXPAT: This might be a problem if later steps depend on sensible rids and/or sensible ordering */ - vector unmatched; + vector unmatched; #ifdef JLF_DEBUG cout << "finishing small-outer join output\n"; #endif i = smallOuterJoiner; tjoiners[i]->getUnmarkedRows(&unmatched); - joinedData = RGData(local_outputRG); - local_outputRG.setData(&joinedData); + joinedData.reset(new uint8_t[local_outputRG.getMaxDataSize()]); + local_outputRG.setData(joinedData.get()); local_outputRG.resetRowGroup(-1); local_outputRG.getRow(0, &joinedBaseRow); for (j = 0; j < unmatched.size(); j++) { - smallSideRows[i].setPointer(unmatched[j]); -// cout << "small side Row: " << smallSideRows[i].toString() << endl; + smallSideRows[i].setData(unmatched[j]); for (k = 0; k < smallSideCount; k++) { if (i == k) applyMapping(smallMappings[i], smallSideRows[i], &joinedBaseRow); @@ -2189,7 +2077,7 @@ catch(...) applyMapping(largeMapping, largeNull, &joinedBaseRow); joinedBaseRow.setRid(0); // cout << "outer row is " << joinedBaseRow.toString() << endl; -// joinedBaseRow.setRid(largeSideRow.getRelRid()); +// joinedBaseRow.setRid(largeSideRow.getRid()); joinedBaseRow.nextRow(); local_outputRG.incRowCount(); if (local_outputRG.getRowCount() == 8192) { @@ -2203,8 +2091,8 @@ catch(...) else rgDataToDl(joinedData, local_outputRG, dlp); - joinedData = RGData(local_outputRG); - local_outputRG.setData(&joinedData); + joinedData.reset(new uint8_t[local_outputRG.getMaxDataSize()]); + local_outputRG.setData(joinedData.get()); local_outputRG.resetRowGroup(-1); local_outputRG.getRow(0, &joinedBaseRow); } @@ -2212,6 +2100,7 @@ catch(...) if (local_outputRG.getRowCount() > 0) { if (fe2) { rgDatav.push_back(joinedData); + idbassert(joinedData); processFE2(local_outputRG, local_fe2Output, postJoinRow, local_fe2OutRow, &rgDatav, &local_fe2); if (rgDatav.size() > 0) rgDataToDl(rgDatav[0], local_fe2Output, dlp); @@ -2220,10 +2109,10 @@ catch(...) else rgDataToDl(joinedData, local_outputRG, dlp); } - mutex.unlock(); + mutex.lock(); //Bug 5499 } - if (traceOn() && fOid>=3000) { + if (fOid>=3000 && traceOn()) { //...Casual partitioning could cause us to do no processing. In that //...case these time stamps did not get set. So we set them here. if (dlTimes.FirstReadTime().tv_sec==0) { @@ -2236,14 +2125,14 @@ catch(...) } ByteStream bs; - try { - if (BPPIsAllocated) { - fDec->removeDECEventListener(this); - fBPP->destroyBPP(bs); - fDec->write(uniqueID, bs); - BPPIsAllocated = false; - } + fDec->removeDECEventListener(this); + fBPP->destroyBPP(bs); + fMsgBytesOut += bs.length() * fDec->getPmCount(); + fDec->write(uniqueID, bs); + BPPIsAllocated = false; + fDec->removeQueue(uniqueID); + tjoiners.clear(); } // catch and do nothing. Let it continues with the clean up and profiling catch (const std::exception& e) @@ -2255,12 +2144,6 @@ catch(...) cerr << "tuple-bps caught unknown exception" << endl; } - Stats stats = fDec->getNetworkStats(uniqueID); - fMsgBytesIn = stats.dataRecvd(); - fMsgBytesOut = stats.dataSent(); - fDec->removeQueue(uniqueID); - tjoiners.clear(); - lastThread = true; } //@Bug 1099 @@ -2268,6 +2151,7 @@ catch(...) fPhysicalIO += physIO_Thread; fCacheIO += cachedIO_Thread; fBlockTouched += touchedBlocks_Thread; + fMsgBytesIn += msgBytesIn_Thread; mutex.unlock(); if (fTableOid >= 3000 && lastThread) @@ -2316,21 +2200,18 @@ catch(...) ostringstream logStr; logStr << "ses:" << fSessionId << " st: " << fStepId<<" finished at "<< JSTimeStamp::format(tvbuf) << "; PhyI/O-" << fPhysicalIO << "; CacheI/O-" << - fCacheIO << "; MsgsSent-" << msgsSent << "; MsgsRvcd-" << msgsRecvd << + fCacheIO << "; MsgsSent-" << fMsgBppsToPm << "; MsgsRvcd-" << msgsRecvd << "; BlocksTouched-"<< fBlockTouched << "; BlockedFifoIn/Out-" << totalBlockedReadCount << "/" << totalBlockedWriteCount << "; output size-" << ridsReturned << endl << "\tPartitionBlocksEliminated-" << fNumBlksSkipped << "; MsgBytesIn-" << msgBytesInKB << "KB" << - "; MsgBytesOut-" << msgBytesOutKB << "KB" << - "; TotalMsgs-" << totalMsgs << endl << - "\t1st read " << dlTimes.FirstReadTimeString() << + "; MsgBytesOut-" << msgBytesOutKB << "KB" << endl << + "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << - JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime()) << - "s\n\tUUID " << uuids::to_string(fStepUuid) << - "\n\tQuery UUID " << uuids::to_string(queryUuid()) << - "\n\tJob completion status " << status() << endl; + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime()) + << "s\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); syslogReadBlockCounts(16, // exemgr sybsystem @@ -2351,24 +2232,11 @@ catch(...) formatMiniStats(); } - if (lastThread && fOid >= 3000) - { - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.phy_io = fPhysicalIO; - sts.cache_io = fCacheIO; - sts.msg_rcv_cnt = sts.total_units_of_work = sts.units_of_work_completed = msgsRecvd; - sts.cp_blocks_skipped = fNumBlksSkipped; - sts.msg_bytes_in = fMsgBytesIn; - sts.msg_bytes_out = fMsgBytesOut; - sts.rows = ridsReturned; - postStepSummaryTele(sts); - } - - if (ffirstStepType == SCAN && bop == BOP_AND && !cancelled()) + if (ffirstStepType == SCAN && bop == BOP_AND && !(fInputJobStepAssociation.status() != 0 || die)) { - cpMutex.lock(); + cpMutex.lock(); //pthread_mutex_lock(&cpMutex); lbidList->UpdateAllPartitionInfo(); - cpMutex.unlock(); + cpMutex.unlock(); //pthread_mutex_unlock(&cpMutex); } } @@ -2381,7 +2249,8 @@ void TupleBPS::processError(const string& ex, uint16_t err, const string& src) { ostringstream oss; oss << "st: " << fStepId << " " << src << " caught an exception: " << ex << endl; - catchHandler(oss.str(), err, fErrorInfo, fSessionId); + catchHandler(oss.str(), fSessionId); + fOutputJobStepAssociation.status(err); abort_nolock(); cerr << oss.str(); } @@ -2396,16 +2265,16 @@ const string TupleBPS::toString() const #if 0 // @bug 1282, don't have output datalist for delivery - if (!fDelivery) + if (!isDelivery) oss << " " << omitOidInDL << fOutputJobStepAssociation.outAt(0) << showOidInDL; #else -if (fDelivery) +if (isDelivery) oss << " is del "; else oss << " not del "; if (bop == BOP_OR) oss << " BOP_OR "; -if (fDie) +if (die) oss << " aborting " << msgsSent << "/" << msgsRecvd << " " << uniqueID << " "; if (fOutputJobStepAssociation.outSize() > 0) { @@ -2424,9 +2293,7 @@ else { oss << fInputJobStepAssociation.outAt(i); } - oss << endl << " UUID: " << uuids::to_string(fStepUuid) << endl; - oss << " Query UUID: " << uuids::to_string(queryUuid()) << endl; - oss << " " << fBPP->toString() << endl; + oss << endl << " " << fBPP->toString() << endl; return oss.str(); } @@ -2434,7 +2301,7 @@ else inline bool TupleBPS::scanit(uint64_t rid) { uint64_t fbo; - uint32_t extentIndex; + uint extentIndex; if (fOid < 3000) return true; @@ -2447,7 +2314,7 @@ inline bool TupleBPS::scanit(uint64_t rid) uint64_t TupleBPS::getFBO(uint64_t lbid) { - uint32_t i; + uint i; uint64_t lastLBID; for (i = 0; i < numExtents; i++) { @@ -2459,16 +2326,16 @@ uint64_t TupleBPS::getFBO(uint64_t lbid) throw logic_error("TupleBPS: didn't find the FBO?"); } -void TupleBPS::useJoiner(boost::shared_ptr tj) +void TupleBPS::useJoiner(shared_ptr tj) { - vector > v; + vector > v; v.push_back(tj); useJoiners(v); } void TupleBPS::useJoiners(const vector > &joiners) { - uint32_t i; + uint i; tjoiners = joiners; doJoin = (joiners.size() != 0); @@ -2495,11 +2362,12 @@ void TupleBPS::useJoiner(boost::shared_ptr j) { } -void TupleBPS::newPMOnline(uint32_t connectionNumber) +void TupleBPS::newPMOnline(uint connectionNumber) { ByteStream bs; fBPP->createBPP(bs); + fMsgBytesOut += bs.length() * fDec->getPmCount(); try { fDec->write(bs, connectionNumber); if (hasPMJoin) @@ -2507,7 +2375,9 @@ void TupleBPS::newPMOnline(uint32_t connectionNumber) } catch (IDBExcept &e) { abort(); - catchHandler(e.what(), e.errorCode(), fErrorInfo, fSessionId); + catchHandler(e.what()); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(e.errorCode()); } } @@ -2537,17 +2407,18 @@ void TupleBPS::setJoinedResultRG(const rowgroup::RowGroup &rg) } /* probably worthwhile to make some of these class vars */ -void TupleBPS::generateJoinResultSet(const vector > &joinerOutput, - Row &baseRow, const vector > &mappings, const uint32_t depth, - RowGroup &outputRG, RGData &rgData, vector *outputData, const scoped_array &smallRows, +void TupleBPS::generateJoinResultSet(const vector > &joinerOutput, + Row &baseRow, const vector > &mappings, const uint depth, + RowGroup &outputRG, shared_array &rgData, + vector > *outputData, const scoped_array &smallRows, Row &joinedRow) { - uint32_t i; + uint i; Row &smallRow = smallRows[depth]; if (depth < smallSideCount - 1) { for (i = 0; i < joinerOutput[depth].size(); i++) { - smallRow.setPointer(joinerOutput[depth][i]); + smallRow.setData(joinerOutput[depth][i]); applyMapping(mappings[depth], smallRow, &baseRow); // cout << "depth " << depth << ", size " << joinerOutput[depth].size() << ", row " << i << ": " << smallRow.toString() << endl; generateJoinResultSet(joinerOutput, baseRow, mappings, depth + 1, @@ -2558,23 +2429,21 @@ void TupleBPS::generateJoinResultSet(const vector > &joiner outputRG.getRow(outputRG.getRowCount(), &joinedRow); for (i = 0; i < joinerOutput[depth].size(); i++, joinedRow.nextRow(), outputRG.incRowCount()) { - smallRow.setPointer(joinerOutput[depth][i]); + smallRow.setData(joinerOutput[depth][i]); if (UNLIKELY(outputRG.getRowCount() == 8192)) { - uint32_t dbRoot = outputRG.getDBRoot(); - uint64_t baseRid = outputRG.getBaseRid(); + uint dbRoot = outputRG.getDBRoot(); // cout << "GJRS adding data\n"; outputData->push_back(rgData); - rgData = RGData(outputRG); - outputRG.setData(&rgData); - outputRG.resetRowGroup(baseRid); + rgData.reset(new uint8_t[outputRG.getMaxDataSize()]); + outputRG.setData(rgData.get()); + outputRG.resetRowGroup(baseRow.getRid()); outputRG.setDBRoot(dbRoot); outputRG.getRow(0, &joinedRow); } // cout << "depth " << depth << ", size " << joinerOutput[depth].size() << ", row " << i << ": " << smallRow.toString() << endl; applyMapping(mappings[depth], smallRow, &baseRow); - copyRow(baseRow, &joinedRow); - //memcpy(joinedRow.getData(), baseRow.getData(), joinedRow.getSize()); - //cout << "(step " << fStepId << ") fully joined row is: " << joinedRow.toString() << endl; + memcpy(joinedRow.getData(), baseRow.getData(), joinedRow.getSize()); +// cout << "(step " << fStepId << ") fully joined row is: " << joinedRow.toString() << endl; } } } @@ -2621,12 +2490,12 @@ uint64_t TupleBPS::getEstimatedRowCount() void TupleBPS::checkDupOutputColumns(const rowgroup::RowGroup &rg) { // bug 1965, find if any duplicate columns selected - map keymap; // map + map keymap; // map dupColumns.clear(); - const vector& keys = rg.getKeys(); - for (uint32_t i = 0; i < keys.size(); i++) + const vector& keys = rg.getKeys(); + for (uint i = 0; i < keys.size(); i++) { - map::iterator j = keymap.find(keys[i]); + map::iterator j = keymap.find(keys[i]); if (j == keymap.end()) keymap.insert(make_pair(keys[i], i)); // map key to col index else @@ -2634,9 +2503,9 @@ void TupleBPS::checkDupOutputColumns(const rowgroup::RowGroup &rg) } } -void TupleBPS::dupOutputColumns(RGData& data, RowGroup& rg) +void TupleBPS::dupOutputColumns(boost::shared_array& data, RowGroup& rg) { - rg.setData(&data); + rg.setData(data.get()); dupOutputColumns(rg); } @@ -2660,15 +2529,6 @@ void TupleBPS::stepId(uint16_t stepId) fBPP->setStepID(stepId); } -void TupleBPS::addFcnJoinExp(const vector& fe) -{ - if (!fe1) - fe1.reset(new funcexp::FuncExpWrapper()); - - for (uint32_t i = 0; i < fe.size(); i++) - fe1->addReturnedColumn(fe[i]); -} - void TupleBPS::addFcnExpGroup1(const boost::shared_ptr& fe) { if (!fe1) @@ -2693,12 +2553,12 @@ void TupleBPS::setFcnExpGroup2(const boost::shared_ptr& fBPP->setFEGroup2(fe2, fe2Output); } -void TupleBPS::setFcnExpGroup3(const vector& fe) +void TupleBPS::setFcnExpGroup3(const vector >& fe) { if (!fe2) fe2.reset(new funcexp::FuncExpWrapper()); - for (uint32_t i = 0; i < fe.size(); i++) + for (uint i = 0; i < fe.size(); i++) fe2->addReturnedColumn(fe[i]); // if this is called, there's no join, so it can always run on the PM @@ -2719,7 +2579,7 @@ void TupleBPS::processFE2_oneRG(RowGroup &input, RowGroup &output, Row &inRow, Row &outRow, funcexp::FuncExpWrapper* local_fe) { bool ret; - uint32_t i; + uint i; output.resetRowGroup(input.getBaseRid()); output.setDBRoot(input.getDBRoot()); @@ -2730,7 +2590,7 @@ void TupleBPS::processFE2_oneRG(RowGroup &input, RowGroup &output, Row &inRow, if (ret) { applyMapping(fe2Mapping, inRow, &outRow); //cout << "fe2 passed row: " << outRow.toString() << endl; - outRow.setRid(inRow.getRelRid()); + outRow.setRid(inRow.getRid()); output.incRowCount(); outRow.nextRow(); } @@ -2738,20 +2598,20 @@ void TupleBPS::processFE2_oneRG(RowGroup &input, RowGroup &output, Row &inRow, } void TupleBPS::processFE2(RowGroup &input, RowGroup &output, Row &inRow, Row &outRow, - vector *rgData, funcexp::FuncExpWrapper* local_fe) + vector > *rgData, funcexp::FuncExpWrapper* local_fe) { - vector results; - RGData result; - uint32_t i, j; + vector > results; + shared_array result; + uint i, j; bool ret; - result = RGData(output); - output.setData(&result); + result.reset(new uint8_t[output.getMaxDataSize()]); + output.setData(result.get()); output.resetRowGroup(-1); output.getRow(0, &outRow); for (i = 0; i < rgData->size(); i++) { - input.setData(&(*rgData)[i]); + input.setData((*rgData)[i].get()); if (output.getRowCount() == 0) { output.resetRowGroup(input.getBaseRid()); output.setDBRoot(input.getDBRoot()); @@ -2761,7 +2621,7 @@ void TupleBPS::processFE2(RowGroup &input, RowGroup &output, Row &inRow, Row &ou ret = local_fe->evaluate(&inRow); if (ret) { applyMapping(fe2Mapping, inRow, &outRow); - outRow.setRid(inRow.getRelRid()); + outRow.setRid(inRow.getRid()); output.incRowCount(); outRow.nextRow(); if (output.getRowCount() == 8192 || @@ -2770,8 +2630,8 @@ void TupleBPS::processFE2(RowGroup &input, RowGroup &output, Row &inRow, Row &ou ) { // cout << "FE2 produced a full RG\n"; results.push_back(result); - result = RGData(output); - output.setData(&result); + result.reset(new uint8_t[output.getMaxDataSize()]); + output.setData(result.get()); output.resetRowGroup(input.getBaseRid()); output.setDBRoot(input.getDBRoot()); output.getRow(0, &outRow); @@ -2796,27 +2656,6 @@ const rowgroup::RowGroup& TupleBPS::getDeliveredRowGroup() const return outputRowGroup; } -void TupleBPS::deliverStringTableRowGroup(bool b) -{ - if (fe2) - fe2Output.setUseStringTable(b); - else if (doJoin) - outputRowGroup.setUseStringTable(b); - else { - outputRowGroup.setUseStringTable(b); - primRowGroup.setUseStringTable(b); - } - - fBPP->deliverStringTableRowGroup(b); -} - -bool TupleBPS::deliverStringTableRowGroup() const -{ - if (fe2) - return fe2Output.usesStringTable(); - return outputRowGroup.usesStringTable(); -} - void TupleBPS::formatMiniStats() { @@ -2829,37 +2668,35 @@ void TupleBPS::formatMiniStats() << fPhysicalIO << " " << fCacheIO << " " << fNumBlksSkipped << " " - << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << " " - << ridsReturned << " "; + << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << " "; + + if (ridsReturned == 0) + oss << rowsReturned << " "; + else + oss << ridsReturned << " "; fMiniInfo += oss.str(); } -void TupleBPS::rgDataToDl(RGData &rgData, RowGroup& rg, RowGroupDL* dlp) +void TupleBPS::rgDataToDl(shared_array& rgData, RowGroup& rg, RowGroupDL* dlp) { // bug 1965, populate duplicate columns if any. if (dupColumns.size() > 0) dupOutputColumns(rgData, rg); -/* - if (!(fSessionId & 0x80000000)) { - rg.setData(&rgData); - cerr << "TBPS rowcount: " << rg.getRowCount() << endl; - } -*/ dlp->insert(rgData); } -void TupleBPS::rgDataVecToDl(vector& rgDatav, RowGroup& rg, RowGroupDL* dlp) +void TupleBPS::rgDataVecToDl(vector >& rgDatav, RowGroup& rg, RowGroupDL* dlp) { uint64_t size = rgDatav.size(); - if (size > 0 && !cancelled()) { - dlMutex.lock(); + if (size > 0 && fInputJobStepAssociation.status() == 0) { + dlMutex.lock(); //pthread_mutex_lock(&dlMutex); for (uint64_t i = 0; i < size; i++) { rgDataToDl(rgDatav[i], rg, dlp); } - dlMutex.unlock(); + dlMutex.unlock(); //pthread_mutex_unlock(&dlMutex); } rgDatav.clear(); } @@ -2876,7 +2713,7 @@ void TupleBPS::addCPPredicates(uint32_t OID, const vector &vals, bool i if (fTraceFlags & CalpontSelectExecutionPlan::IGNORE_CP || fOid < 3000) return; - uint32_t i, j, k; + uint i, j, k; int64_t min, max, seq; bool isValid, intersection; vector colCmdVec = fBPP->getFilterSteps(); @@ -2899,15 +2736,20 @@ void TupleBPS::addCPPredicates(uint32_t OID, const vector &vals, bool i cmd = dynamic_cast(colCmdVec[i].get()); if (cmd != NULL && cmd->getOID() == OID) { if (!ll.CasualPartitionDataType(cmd->getColType().colDataType, cmd->getColType().colWidth) - || cmd->isDict()) + || cmd->fcnOrd() || cmd->isDict()) return; // @bug 2989, use correct extents tr1::unordered_map *extentsPtr = NULL; vector extents; // in case the extents of OID is not in Map - // TODO: store the sorted vectors from the pcolscans/steps as a minor optimization - dbrm.getExtents(OID, extents); + // TODO: store the sorted vectors from the pcolscans/steps as a minor optimization + dbrm.getExtents(OID, extents); + if (extents.empty()) { + ostringstream os; + os << "TupleBPS::addCPPredicates(): OID " << OID << " is empty."; + throw runtime_error(os.str()); + } sort(extents.begin(), extents.end(), ExtentSorter()); if (extentsMap.find(OID) != extentsMap.end()) { @@ -2916,23 +2758,22 @@ void TupleBPS::addCPPredicates(uint32_t OID, const vector &vals, bool i else if (dbrm.getExtents(OID, extents) == 0) { extentsMap[OID] = tr1::unordered_map(); tr1::unordered_map &mref = extentsMap[OID]; - for (uint32_t z = 0; z < extents.size(); z++) + for (uint z = 0; z < extents.size(); z++) mref[extents[z].range.start] = extents[z]; extentsPtr = &mref; } for (j = 0; j < extents.size(); j++) { - isValid = ll.GetMinMax(&min, &max, &seq, extents[j].range.start, *extentsPtr, - cmd->getColType().colDataType); + isValid = ll.GetMinMax(&min, &max, &seq, extents[j].range.start, *extentsPtr); if (isValid) { if (isRange) runtimeCPFlags[j] = ll.checkRangeOverlap(min, max, vals[0], vals[1], - cmd->getColType().colDataType) && runtimeCPFlags[j]; + cmd->isCharType()) && runtimeCPFlags[j]; else { intersection = false; for (k = 0; k < vals.size(); k++) intersection = intersection || - ll.checkSingleValue(min, max, vals[k], cmd->getColType().colDataType); + ll.checkSingleValue(min, max, vals[k], cmd->isCharType()); runtimeCPFlags[j] = intersection && runtimeCPFlags[j]; } } @@ -2948,17 +2789,18 @@ void TupleBPS::dec(DistributedEngineComm* dec) fDec->removeQueue(uniqueID); fDec = dec; if (fDec) - fDec->addQueue(uniqueID, true); + fDec->addQueue(uniqueID, true); } void TupleBPS::abort_nolock() { - if (fDie) + if (die) return; JobStep::abort(); - if (fDec && BPPIsAllocated) { + if (fDec) { ByteStream bs; fBPP->abortProcessing(&bs); + fMsgBytesOut += bs.length() * fDec->getPmCount(); try { fDec->write(uniqueID, bs); } @@ -2967,7 +2809,6 @@ void TupleBPS::abort_nolock() // that is the cause of the abort and that will be reported to the // front-end already. Nothing to do here. } - BPPIsAllocated = false; fDec->shutdownQueue(uniqueID); } condvarWakeupProducer.notify_all(); @@ -2976,8 +2817,28 @@ void TupleBPS::abort_nolock() void TupleBPS::abort() { - boost::mutex::scoped_lock scoped(mutex); - abort_nolock(); + boost::mutex::scoped_lock scoped(mutex, boost::defer_lock); + if (die) + return; + JobStep::abort(); + if (fDec) { + ByteStream bs; + fBPP->abortProcessing(&bs); + fMsgBytesOut += bs.length() * fDec->getPmCount(); + try { + fDec->write(uniqueID, bs); + } + catch(...) { + // this throws only if there are no PMs left. If there are none, + // that is the cause of the abort and that will be reported to the + // front-end already. Nothing to do here. + } + fDec->shutdownQueue(uniqueID); + } + scoped.lock(); + condvarWakeupProducer.notify_all(); + condvar.notify_all(); + scoped.unlock(); } } //namespace diff --git a/dbcon/joblist/tupleaggregatestep.cpp b/dbcon/joblist/tupleaggregatestep.cpp index 69587871..dc18ae3c 100644 --- a/dbcon/joblist/tupleaggregatestep.cpp +++ b/dbcon/joblist/tupleaggregatestep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tupleaggregatestep.cpp 9732 2013-08-02 15:56:15Z pleblanc $ +// $Id: tupleaggregatestep.cpp 9389 2013-04-09 15:53:35Z xlou $ //#define NDEBUG @@ -28,7 +28,6 @@ using namespace std; #include #include #include -#include using namespace boost; #include "messagequeue.h" @@ -53,9 +52,6 @@ using namespace execplan; #include "rowaggregation.h" using namespace rowgroup; -#include "querytele.h" -using namespace querytele; - #include "jlf_common.h" #include "jobstep.h" #include "primitivestep.h" @@ -72,7 +68,7 @@ namespace { -typedef vector RowBucket; +typedef vector RowBucket; typedef vector RowBucketVec; @@ -135,20 +131,12 @@ inline string colTypeIdString(CalpontSystemCatalog::ColDataType type) case CalpontSystemCatalog::VARCHAR: return string("VARCHAR"); case CalpontSystemCatalog::CLOB: return string("CLOB"); case CalpontSystemCatalog::BLOB: return string("BLOB"); - case CalpontSystemCatalog::UTINYINT: return string("UTINYINT"); - case CalpontSystemCatalog::USMALLINT: return string("USMALLINT"); - case CalpontSystemCatalog::UDECIMAL: return string("UDECIMAL"); - case CalpontSystemCatalog::UMEDINT: return string("UMEDINT"); - case CalpontSystemCatalog::UINT: return string("UINT"); - case CalpontSystemCatalog::UFLOAT: return string("UFLOAT"); - case CalpontSystemCatalog::UBIGINT: return string("UBIGINT"); - case CalpontSystemCatalog::UDOUBLE: return string("UDOUBLE"); default: return string("UNKNOWN"); } } -string keyName(uint64_t i, uint32_t key, const joblist::JobInfo& jobInfo) +string keyName(uint64_t i, uint key, const joblist::JobInfo& jobInfo) { string name = jobInfo.projectionCols[i]->alias(); if (name.empty()) @@ -170,58 +158,66 @@ namespace joblist TupleAggregateStep::TupleAggregateStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + boost::shared_ptr syscat, + uint32_t sessionId, + uint32_t txnId, + uint32_t statementId, const SP_ROWAGG_UM_t& agg, const RowGroup& rgOut, const RowGroup& rgIn, - const JobInfo& jobInfo) : - JobStep(jobInfo), - fCatalog(jobInfo.csc), + ResourceManager *r) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fCatalog(syscat), + fSessionId(sessionId), + fTxnId(txnId), + fStepId(0), + fStatementId(statementId), fRowsReturned(0), fDoneAggregate(false), fEndOfResult(false), fAggregator(agg), fRowGroupOut(rgOut), fRowGroupIn(rgIn), + fDelivery(false), fUmOnly(false), - fRm(jobInfo.rm), - fBucketNum(0), - fInputIter(-1), - fSessionMemLimit(jobInfo.umMemLimit) + rm(r), + fBucketMask(0), + fInputIter(-1) { - fRowGroupData.reinit(fRowGroupOut); - fRowGroupOut.setData(&fRowGroupData); + fRowGroupData.reset(new uint8_t[fRowGroupOut.getMaxDataSize()]); + fRowGroupOut.setData(fRowGroupData.get()); fAggregator->setInputOutput(fRowGroupIn, &fRowGroupOut); - + // decide if this needs to be multi-threaded RowAggregationDistinct* multiAgg = dynamic_cast(fAggregator.get()); - fIsMultiThread = (multiAgg || fAggregator->aggMapKeyLength() > 0); + fIsMultiThread = (multiAgg || fAggregator->aggMapKeyLength() > 0); // initialize multi-thread variables - fNumOfThreads = fRm.aggNumThreads(); - fNumOfBuckets = fRm.aggNumBuckets(); - fNumOfRowGroups = fRm.aggNumRowGroups(); - fMemUsage.reset(new uint64_t[fNumOfThreads]); - memset(fMemUsage.get(), 0, fNumOfThreads * sizeof(uint64_t)); + fNumOfThreads = rm->aggNumThreads(); + fNumOfBuckets = rm->aggNumBuckets(); + fNumOfRowGroups = rm->aggNumRowGroups(); + memUsage.reset(new uint64_t[fNumOfThreads]); + memset(memUsage.get(), 0, fNumOfThreads * sizeof(uint64_t)); fExtendedInfo = "TAS: "; - fQtc.stepParms().stepType = StepTeleStats::T_TAS; } TupleAggregateStep::~TupleAggregateStep() { - for (uint32_t i = 0; i < fNumOfThreads; i++) - fRm.returnMemory(fMemUsage[i], fSessionMemLimit); - for (uint32_t i = 0; i < fAgg_mutex.size(); i++) - delete fAgg_mutex[i]; + for (uint i = 0; i < fNumOfThreads; i++) + rm->returnMemory(memUsage[i]); + for (uint i = 0; i < agg_mutex.size(); i++) + delete agg_mutex[i]; } void TupleAggregateStep::initializeMultiThread() { RowGroupDL *dlIn = fInputJobStepAssociation.outAt(0)->rowGroupDL(); - uint32_t i; - if (dlIn == NULL) throw logic_error("Input is not RowGroup data list in delivery step."); @@ -229,21 +225,39 @@ void TupleAggregateStep::initializeMultiThread() fInputIter = dlIn->getIterator(); fRowGroupIns.resize(fNumOfThreads); + fBucketMask = 0; + + uint64_t mask = 1; + uint i; + for (i = 1; i <= 64; i++) + { + mask <<= 1; + fBucketMask = (fBucketMask << 1) | 1; + if (fNumOfBuckets & mask) + break; + } + + // Check if the bucket number is a power of 2. If not, force it to be 16. + for (i++, mask <<= 1; i <= 64; i++, mask <<= 1) + if (fNumOfBuckets & mask) + { + fNumOfBuckets = 16; + fBucketMask = 15; + } + fRowGroupOuts.resize(fNumOfBuckets); - fRowGroupDatas.resize(fNumOfBuckets); rowgroup::SP_ROWAGG_UM_t agg; - RGData rgData; + boost::shared_array rgData; for (i = 0; i < fNumOfBuckets; i++) { - mutex *lock = new mutex(); - fAgg_mutex.push_back(lock); + boost::mutex *lock = new boost::mutex(); + agg_mutex.push_back(lock); fRowGroupOuts[i] = fRowGroupOut; - rgData.reinit(fRowGroupOut); - fRowGroupDatas[i] = rgData; - fRowGroupOuts[i].setData(&fRowGroupDatas[i]); - fRowGroupOuts[i].resetRowGroup(0); + rgData.reset(new uint8_t[fRowGroupOut.getMaxDataSize()]); + fRowGroupDatas.push_back(rgData); + fRowGroupOuts[i].setData(fRowGroupDatas[i].get()); } } @@ -252,7 +266,7 @@ void TupleAggregateStep::run() { if (fDelivery == false) { - fRunner.reset(new thread(Aggregator(this))); + fRunner.reset(new boost::thread(Aggregator(this))); } } @@ -264,15 +278,14 @@ void TupleAggregateStep::join() } -void TupleAggregateStep::doThreadedSecondPhaseAggregate(uint32_t threadID) +void TupleAggregateStep::doThreadedSecondPhaseAggregate(uint8_t threadID) { - if (threadID >= fNumOfBuckets) - return; - + //RowBucketVec rowBucketVecs[fNumOfBuckets]; scoped_array rowBucketVecs(new RowBucketVec[fNumOfBuckets]); scoped_array bucketDone(new bool[fNumOfBuckets]); + uint32_t hashlen = fAggregator->aggMapKeyLength(); - bool caughtException = false; + utils::TupleHasher hash(hashlen); try { @@ -281,23 +294,25 @@ void TupleAggregateStep::doThreadedSecondPhaseAggregate(uint32_t threadID) Row rowIn; RowGroup* rowGroupIn = 0; rowGroupIn = (aggDist->aggregator()->getOutputRowGroup()); - uint32_t bucketID; + + uint bucketID; + //bool bucketDone[fNumOfBuckets]; if (multiDist) { - for (uint32_t i = 0; i < fNumOfBuckets; i++) + for (uint i = 0; i < fNumOfBuckets; i++) rowBucketVecs[i].resize(multiDist->subAggregators().size()); } else { - for (uint32_t i = 0; i < fNumOfBuckets; i++) + for (uint i = 0; i < fNumOfBuckets; i++) rowBucketVecs[i].resize(1); } // dispatch rows to bucket if (multiDist) { - for (uint32_t j = 0; j < multiDist->subAggregators().size(); j++) + for (uint j = 0; j < multiDist->subAggregators().size(); j++) { rowGroupIn = (multiDist->subAggregators()[j]->getOutputRowGroup()); rowGroupIn->initRow(&rowIn); @@ -308,10 +323,9 @@ void TupleAggregateStep::doThreadedSecondPhaseAggregate(uint32_t threadID) for (uint64_t i = 0; i < rowGroupIn->getRowCount(); ++i) { // The key is the groupby columns, which are the leading columns. - //uint8_t* hashMapKey = rowIn.getData() + 2; - //bucketID = hash.operator()(hashMapKey) & fBucketMask; - bucketID = rowIn.hash(hashlen-1) % fNumOfBuckets; - rowBucketVecs[bucketID][j].push_back(rowIn.getPointer()); + uint8_t* hashMapKey = rowIn.getData() + 2; + bucketID = hash.operator()(hashMapKey) & fBucketMask; + rowBucketVecs[bucketID][j].push_back(rowIn.getData()); rowIn.nextRow(); } } @@ -322,37 +336,38 @@ void TupleAggregateStep::doThreadedSecondPhaseAggregate(uint32_t threadID) rowGroupIn->initRow(&rowIn); while (dynamic_cast(aggDist->aggregator().get())->nextRowGroup()) { - rowGroupIn->setData(aggDist->aggregator()->getOutputRowGroup()->getRGData()); + rowGroupIn->setData(aggDist->aggregator()->getOutputRowGroup()->getData()); rowGroupIn->getRow(0, &rowIn); for (uint64_t i = 0; i < rowGroupIn->getRowCount(); ++i) { // The key is the groupby columns, which are the leading columns. - //uint8_t* hashMapKey = rowIn.getData() + 2; - //bucketID = hash.operator()(hashMapKey) & fBucketMask; - bucketID = rowIn.hash(hashlen-1) % fNumOfBuckets; - rowBucketVecs[bucketID][0].push_back(rowIn.getPointer()); + uint8_t* hashMapKey = rowIn.getData() + 2; + bucketID = hash.operator()(hashMapKey) & fBucketMask; + rowBucketVecs[bucketID][0].push_back(rowIn.getData()); rowIn.nextRow(); } } } bool done = false; + //uint64_t rgcount = 0; //debug // reset bucketDone[] to be false //memset(bucketDone, 0, sizeof(bucketDone)); fill(&bucketDone[0], &bucketDone[fNumOfBuckets], false); - while (!done && !cancelled()) + while (!done && !(die || fInputJobStepAssociation.status())) { done = true; - for (uint32_t c = 0; c < fNumOfBuckets && !cancelled(); c++) + for (uint c = 0; c < fNumOfBuckets && !(die || fInputJobStepAssociation.status()); c++) { - if (!bucketDone[c] && fAgg_mutex[c]->try_lock()) + if (!bucketDone[c] && agg_mutex[c]->try_lock()) { + //rgcount += rowBucketVecs[c][0].size(); if (multiDist) dynamic_cast(fAggregators[c].get())->doDistinctAggregation_rowVec(rowBucketVecs[c]); else dynamic_cast(fAggregators[c].get())->doDistinctAggregation_rowVec(rowBucketVecs[c][0]); - fAgg_mutex[c]->unlock(); + agg_mutex[c]->unlock(); bucketDone[c] = true; rowBucketVecs[c][0].clear(); } @@ -363,46 +378,78 @@ void TupleAggregateStep::doThreadedSecondPhaseAggregate(uint32_t threadID) } } - if (cancelled()) + if (0 < fInputJobStepAssociation.status()) { + fOutputJobStepAssociation.status(fInputJobStepAssociation.status()); fEndOfResult = true; } + //cout << "2nd phase thread " << (int)threadID << " rcount: " << rgcount << endl; } // try catch (IDBExcept& iex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId, - (iex.errorCode() == ERR_AGGREGATION_TOO_BIG ? LOG_TYPE_INFO : LOG_TYPE_CRITICAL)); - caughtException = true; + catchHandler(iex.what(), fSessionId, (iex.errorCode() == logging::ERR_AGGREGATION_TOO_BIG ? logging::LOG_TYPE_INFO : + logging::LOG_TYPE_CRITICAL)); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(iex.errorCode()); + + fEndOfResult = true; + fDoneAggregate = true; + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + return; + } + catch (QueryDataExcept& qex) + { + catchHandler(qex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(qex.errorCode()); + + fEndOfResult = true; + fDoneAggregate = true; + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + return; } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleAggregateStepErr, fErrorInfo, fSessionId); - caughtException = true; + catchHandler(ex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); + + fEndOfResult = true; + fDoneAggregate = true; + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + return; } catch(...) { - catchHandler("doThreadedSecondPhaseAggregate() caught an unknown exception", - tupleAggregateStepErr, fErrorInfo, fSessionId); - caughtException = true; - } + catchHandler("TupleAggregateStep::aggregateRowGroups() caught an unknown exception", fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); - if (caughtException) fEndOfResult = true; + fDoneAggregate = true; - fDoneAggregate = true; - - if (traceOn()) - { dlTimes.setLastReadTime(); dlTimes.setEndOfInputTime(); + return; } + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + + fDoneAggregate = true; } -uint32_t TupleAggregateStep::nextBand_singleThread(messageqcpp::ByteStream &bs) +uint TupleAggregateStep::nextBand_singleThread(messageqcpp::ByteStream &bs) { - uint32_t rowCount = 0; + uint rowCount = 0; try { @@ -424,10 +471,10 @@ uint32_t TupleAggregateStep::nextBand_singleThread(messageqcpp::ByteStream &bs) fAggregator->finalize(); rowCount = fRowGroupOut.getRowCount(); fRowsReturned += rowCount; - fRowGroupDelivered.setData(fRowGroupOut.getRGData()); + fRowGroupDelivered.setData(fRowGroupOut.getData()); if (fRowGroupOut.getColumnCount() != fRowGroupDelivered.getColumnCount()) pruneAuxColumns(); - fRowGroupDelivered.serializeRGData(bs); + bs.load(fRowGroupDelivered.getData(), fRowGroupDelivered.getDataSize()); } else { @@ -437,41 +484,42 @@ uint32_t TupleAggregateStep::nextBand_singleThread(messageqcpp::ByteStream &bs) } // try catch (IDBExcept& iex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId, - (iex.errorCode() == ERR_AGGREGATION_TOO_BIG ? LOG_TYPE_INFO : LOG_TYPE_CRITICAL)); - + catchHandler(iex.what(), fSessionId, (iex.errorCode() == logging::ERR_AGGREGATION_TOO_BIG ? logging::LOG_TYPE_INFO : + logging::LOG_TYPE_CRITICAL)); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(iex.errorCode()); + fEndOfResult = true; + } + catch (QueryDataExcept& qex) + { + catchHandler(qex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(qex.errorCode()); fEndOfResult = true; } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleAggregateStepErr, fErrorInfo, fSessionId); - + catchHandler(ex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); fEndOfResult = true; } catch(...) { - catchHandler("TupleAggregateStep next band caught an unknown exception", - tupleAggregateStepErr, fErrorInfo, fSessionId); - + catchHandler("TupleAggregateStep next band caught an unknown exception", fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); fEndOfResult = true; } if (fEndOfResult) { - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - // send an empty / error band - RGData rgData(fRowGroupOut, 0); - fRowGroupOut.setData(&rgData); + shared_array rgData(new uint8_t[fRowGroupOut.getEmptySize()]); + fRowGroupOut.setData(rgData.get()); fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setStatus(status()); - fRowGroupOut.serializeRGData(bs); + fRowGroupOut.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgData.get(), fRowGroupOut.getDataSize()); rowCount = 0; if (traceOn()) @@ -484,26 +532,28 @@ uint32_t TupleAggregateStep::nextBand_singleThread(messageqcpp::ByteStream &bs) bool TupleAggregateStep::nextDeliveredRowGroup() { - for (; fBucketNum < fNumOfBuckets; fBucketNum++) + static uint bucketNum = 0; + + for (; bucketNum < fNumOfBuckets; bucketNum++) { - while (fAggregators[fBucketNum]->nextRowGroup()) + while (fAggregators[bucketNum]->nextRowGroup()) { - fAggregators[fBucketNum]->finalize(); - fRowGroupDelivered.setData(fAggregators[fBucketNum]->getOutputRowGroup()->getRGData()); - fRowGroupOut.setData(fAggregators[fBucketNum]->getOutputRowGroup()->getRGData()); + fAggregators[bucketNum]->finalize(); + fRowGroupDelivered.setData(fAggregators[bucketNum]->getOutputRowGroup()->getData()); + fRowGroupOut.setData(fAggregators[bucketNum]->getOutputRowGroup()->getData()); return true; } } - fBucketNum = 0; + bucketNum = 0; return false; } -uint32_t TupleAggregateStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleAggregateStep::nextBand(messageqcpp::ByteStream &bs) { // use the orignal single thread model when no group by and distnct. // @bug4314. DO NOT access fAggregtor before the first read of input, - // because hashjoin may not have finalized fAggregator. + // because hashjoin may not have finalized fAggregator. if (!fIsMultiThread) return nextBand_singleThread(bs); @@ -531,54 +581,49 @@ bool TupleAggregateStep::setPmHJAggregation(JobStep* step) void TupleAggregateStep::configDeliveredRowGroup(const JobInfo& jobInfo) { // configure the oids and keys - vector oids = fRowGroupOut.getOIDs(); - vector keys = fRowGroupOut.getKeys(); - vector >::const_iterator begin = jobInfo.aggEidIndexList.begin(); - vector >::const_iterator end = jobInfo.aggEidIndexList.end(); - for (vector >::const_iterator i = begin; i != end; i++) + vector oids = fRowGroupOut.getOIDs(); + vector keys = fRowGroupOut.getKeys(); + for (vector >::const_iterator i = jobInfo.aggEidIndexList.begin(); + i != jobInfo.aggEidIndexList.end(); + i++) { oids[i->second] = i->first; keys[i->second] = getExpTupleKey(jobInfo, i->first); } // correct the scale - vector scale = fRowGroupOut.getScale(); + vector scale = fRowGroupOut.getScale(); for (uint64_t i = 0; i < scale.size(); i++) { // to support CNX_DECIMAL_SCALE the avg column's scale is coded with two scales: // fe's avg column scale << 8 + original column scale - //if ((scale[i] & 0x0000FF00) > 0) - scale[i] = scale[i] & 0x000000FF; + if ((scale[i] & 0x0000FF00) > 0) + scale[i] = scale[i] & 0x000000FF; } size_t retColCount = jobInfo.nonConstDelCols.size(); if (jobInfo.havingStep) retColCount = jobInfo.returnedColVec.size(); - vector::const_iterator offsets0 = fRowGroupOut.getOffsets().begin(); + vector::const_iterator offsets0 = fRowGroupOut.getOffsets().begin(); vector::const_iterator types0 = fRowGroupOut.getColTypes().begin(); - vector::const_iterator precision0 = fRowGroupOut.getPrecision().begin(); + vector::const_iterator precision0 = fRowGroupOut.getPrecision().begin(); fRowGroupDelivered = RowGroup(retColCount, - vector(offsets0, offsets0+retColCount+1), - vector(oids.begin(), oids.begin()+retColCount), - vector(keys.begin(), keys.begin()+retColCount), + vector(offsets0, offsets0+retColCount+1), + vector(oids.begin(), oids.begin()+retColCount), + vector(keys.begin(), keys.begin()+retColCount), vector(types0, types0+retColCount), - vector(scale.begin(), scale.begin()+retColCount), - vector(precision0, precision0+retColCount), - jobInfo.stringTableThreshold); - - if (jobInfo.trace) - cout << "delivered RG: " << fRowGroupDelivered.toString() << endl << endl; - + vector(scale.begin(), scale.begin()+retColCount), + vector(precision0, precision0+retColCount)); } void TupleAggregateStep::setOutputRowGroup(const RowGroup& rg) { fRowGroupOut = rg; - fRowGroupData.reinit(fRowGroupOut); - fRowGroupOut.setData(&fRowGroupData); + fRowGroupData.reset(new uint8_t[fRowGroupOut.getMaxDataSize()]); + fRowGroupOut.setData(fRowGroupData.get()); fAggregator->setInputOutput(fRowGroupIn, &fRowGroupOut); } @@ -603,18 +648,6 @@ void TupleAggregateStep::savePmHJData(SP_ROWAGG_t& um, SP_ROWAGG_t& pm, RowGroup } -void TupleAggregateStep::deliverStringTableRowGroup(bool b) -{ - fRowGroupDelivered.setUseStringTable(b); -} - - -bool TupleAggregateStep::deliverStringTableRowGroup() const -{ - return fRowGroupDelivered.usesStringTable(); -} - - const string TupleAggregateStep::toString() const { ostringstream oss; @@ -650,7 +683,7 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) vector constAggDataVec; vector > returnedColVecOrig = jobInfo.returnedColVec; - for(uint32_t idx = 0; idx < jobInfo.returnedColVec.size(); idx++) + for(uint idx = 0; idx < jobInfo.returnedColVec.size(); idx++) { if (jobInfo.returnedColVec[idx].second == AggregateColumn::DISTINCT_COUNT || jobInfo.returnedColVec[idx].second == AggregateColumn::DISTINCT_AVG || @@ -696,7 +729,7 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) jobInfo.returnedColVec.push_back(make_pair(constKey, AggregateColumn::COUNT_ASTERISK)); } - // preprocess the columns used by group_concat + // preprocess the columns used by group_concat jobInfo.groupConcatInfo.prepGroupConcat(jobInfo); bool doGroupConcat = false; @@ -724,7 +757,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) } // make sure connected by a RowGroupDL - JobStepAssociation tbpsJsa; + JobStepAssociation dummyJsa(jobInfo.status); + JobStepAssociation tbpsJsa(jobInfo.status); AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); dl->OID(execplan::CNX_VTABLE_ID); @@ -733,8 +767,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) // create delivery step aggUM = dynamic_pointer_cast(aggs[0]); - spjs.reset(new TupleAggregateStep(aggUM, rgs[1], rgs[2], jobInfo)); - spjs->inputAssociation(tbpsJsa); + spjs.reset(new TupleAggregateStep(tbpsJsa, dummyJsa, jobInfo.csc, + step->sessionId(), step->txnId(), step->statementId(), aggUM, rgs[1], rgs[2], &jobInfo.rm)); // step id?? spjs->stepId(step->stepId()+1); @@ -773,7 +807,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) } // make sure connected by a RowGroupDL - JobStepAssociation thjsJsa; + JobStepAssociation dummyJsa(jobInfo.status); + JobStepAssociation thjsJsa(jobInfo.status); AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); dl->OID(execplan::CNX_VTABLE_ID); @@ -782,9 +817,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) // create delivery step aggUM = dynamic_pointer_cast(aggs[0]); - spjs.reset(new TupleAggregateStep(aggUM, rgs[1], rgs[0], jobInfo)); - spjs->inputAssociation(thjsJsa); - + spjs.reset(new TupleAggregateStep(thjsJsa, dummyJsa, jobInfo.csc, + step->sessionId(), step->txnId(), step->statementId(), aggUM, rgs[1], rgs[0], &jobInfo.rm)); if (doGroupConcat) dynamic_cast(spjs.get())->umOnly(true); else @@ -810,7 +844,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) prep1PhaseAggregate(jobInfo, rgs, aggs); // make sure connected by a RowGroupDL - JobStepAssociation sasJsa; + JobStepAssociation dummyJsa(jobInfo.status); + JobStepAssociation sasJsa(jobInfo.status); AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); dl->OID(execplan::CNX_VTABLE_ID); @@ -819,8 +854,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) // create delivery step aggUM = dynamic_pointer_cast(aggs[0]); - spjs.reset(new TupleAggregateStep(aggUM, rgs[1], rgs[0], jobInfo)); - spjs->inputAssociation(sasJsa); + spjs.reset(new TupleAggregateStep(sasJsa, dummyJsa, jobInfo.csc, + step->sessionId(), step->txnId(), step->statementId(), aggUM, rgs[1], rgs[0], &jobInfo.rm)); // step id?? spjs->stepId(step->stepId()+1); @@ -840,7 +875,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) prep1PhaseAggregate(jobInfo, rgs, aggs); // make sure connected by a RowGroupDL - JobStepAssociation cesJsa; + JobStepAssociation dummyJsa(jobInfo.status); + JobStepAssociation cesJsa(jobInfo.status); AnyDataListSPtr spdl(new AnyDataList()); RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); dl->OID(execplan::CNX_VTABLE_ID); @@ -849,8 +885,8 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) // create delivery step aggUM = dynamic_pointer_cast(aggs[0]); - spjs.reset(new TupleAggregateStep(aggUM, rgs[1], rgs[0], jobInfo)); - spjs->inputAssociation(cesJsa); + spjs.reset(new TupleAggregateStep(cesJsa, dummyJsa, jobInfo.csc, + step->sessionId(), step->txnId(), step->statementId(), aggUM, rgs[1], rgs[0], &jobInfo.rm)); // step id?? spjs->stepId(step->stepId()+1); @@ -868,9 +904,17 @@ SJSTEP TupleAggregateStep::prepAggregate(SJSTEP& step, JobInfo& jobInfo) // fix the delivered rowgroup data dynamic_cast(spjs.get())->configDeliveredRowGroup(jobInfo); + if (jobInfo.trace) + { + cout << "delivered RG: " + << dynamic_cast(spjs.get())->getDeliveredRowGroup().toString() + << endl << endl; + } if (jobInfo.expressionVec.size() > 0) + { dynamic_cast(spjs.get())->prepExpressionOnAggregate(aggUM, jobInfo); + } return spjs; } @@ -894,29 +938,28 @@ void TupleAggregateStep::prep1PhaseAggregate( // 1. get projected rowgroup (done by doAggProject) -- passed in // 2. construct aggregate rowgroup -- output of UM const RowGroup projRG = rowgroups[0]; - const vector& oidsProj = projRG.getOIDs(); - const vector& keysProj = projRG.getKeys(); - const vector& scaleProj = projRG.getScale(); - const vector& precisionProj = projRG.getPrecision(); + const vector& oidsProj = projRG.getOIDs(); + const vector& keysProj = projRG.getKeys(); + const vector& scaleProj = projRG.getScale(); + const vector& precisionProj = projRG.getPrecision(); const vector& typeProj = projRG.getColTypes(); - vector posAgg; - vector oidsAgg; - vector keysAgg; - vector scaleAgg; - vector precisionAgg; + vector posAgg; + vector oidsAgg; + vector keysAgg; + vector scaleAgg; + vector precisionAgg; vector typeAgg; - vector widthAgg; + vector widthAgg; vector groupBy; vector functionVec; - uint32_t bigIntWidth = sizeof(int64_t); - uint32_t bigUintWidth = sizeof(uint64_t); + uint bigIntWidth = sizeof(int64_t); // for count column of average function map avgFuncMap; // collect the projected column info, prepare for aggregation - vector width; + vector width; map projColPosMap; for (uint64_t i = 0; i < keysProj.size(); i++) { @@ -937,10 +980,6 @@ void TupleAggregateStep::prep1PhaseAggregate( // for distinct column for (uint64_t i = 0; i < jobInfo.distinctColVec.size(); i++) { - //@bug6126, continue if already in group by - if (groupbyMap.find(jobInfo.distinctColVec[i]) != groupbyMap.end()) - continue; - int64_t colProj = projColPosMap[jobInfo.distinctColVec[i]]; SP_ROWAGG_GRPBY_t groupby(new RowAggGroupByCol(colProj, -1)); groupBy.push_back(groupby); @@ -953,11 +992,11 @@ void TupleAggregateStep::prep1PhaseAggregate( { RowAggFunctionType aggOp = functionIdMap(returnedColVec[i].second); RowAggFunctionType stats = statsFuncIdMap(returnedColVec[i].second); - uint32_t key = returnedColVec[i].first; + uint key = returnedColVec[i].first; if (aggOp == ROWAGG_CONSTANT) { - TupleInfo ti = getTupleInfo(key, jobInfo); + TupleInfo ti = getExpTupleInfo(key, jobInfo); oidsAgg.push_back(ti.oid); keysAgg.push_back(key); scaleAgg.push_back(ti.scale); @@ -972,9 +1011,9 @@ void TupleAggregateStep::prep1PhaseAggregate( if (aggOp == ROWAGG_GROUP_CONCAT) { - TupleInfo ti = getTupleInfo(key, jobInfo); - uint32_t ptrSize = sizeof(GroupConcatAg*); - uint32_t width = (ti.width >= ptrSize) ? ti.width : ptrSize; + TupleInfo ti = getExpTupleInfo(key, jobInfo); + uint ptrSize = sizeof(GroupConcatAg*); + uint width = (ti.width >= ptrSize) ? ti.width : ptrSize; oidsAgg.push_back(ti.oid); keysAgg.push_back(key); scaleAgg.push_back(ti.scale); @@ -1039,7 +1078,7 @@ void TupleAggregateStep::prep1PhaseAggregate( else if (find(jobInfo.expressionVec.begin(), jobInfo.expressionVec.end(), key) != jobInfo.expressionVec.end()) { - TupleInfo ti = getTupleInfo(key, jobInfo); + TupleInfo ti = getExpTupleInfo(key, jobInfo); oidsAgg.push_back(ti.oid); keysAgg.push_back(key); scaleAgg.push_back(ti.scale); @@ -1060,17 +1099,6 @@ void TupleAggregateStep::prep1PhaseAggregate( widthAgg.push_back(width[colProj]); continue; } - else if (jobInfo.windowSet.find(key) != jobInfo.windowSet.end()) - { - // skip window columns/expression, which are computed later - oidsAgg.push_back(oidsProj[colProj]); - keysAgg.push_back(key); - scaleAgg.push_back(scaleProj[colProj]); - precisionAgg.push_back(precisionProj[colProj]); - typeAgg.push_back(typeProj[colProj]); - widthAgg.push_back(width[colProj]); - continue; - } else { Message::Args args; @@ -1122,31 +1150,11 @@ void TupleAggregateStep::prep1PhaseAggregate( oidsAgg.push_back(oidsProj[colProj]); keysAgg.push_back(key); - if (typeProj[colProj] == CalpontSystemCatalog::DOUBLE || - typeProj[colProj] == CalpontSystemCatalog::UDOUBLE || - typeProj[colProj] == CalpontSystemCatalog::FLOAT || - typeProj[colProj] == CalpontSystemCatalog::UFLOAT) - { - typeAgg.push_back(typeProj[colProj]); - scaleAgg.push_back(scaleProj[colProj]); - precisionAgg.push_back(precisionProj[colProj]); - widthAgg.push_back(width[colProj]); - } - else if (isUnsigned(typeProj[colProj])) - { - typeAgg.push_back(CalpontSystemCatalog::UBIGINT); - uint32_t scale = scaleProj[colProj]; - // for int average, FE expects a decimal - if (aggOp == ROWAGG_AVG) - scale = jobInfo.scaleOfAvg[key]; // scale += 4; - scaleAgg.push_back(scale); - precisionAgg.push_back(20); - widthAgg.push_back(bigUintWidth); - } - else + if (typeProj[colProj] != CalpontSystemCatalog::DOUBLE && + typeProj[colProj] != CalpontSystemCatalog::FLOAT) { typeAgg.push_back(CalpontSystemCatalog::BIGINT); - uint32_t scale = scaleProj[colProj]; + uint scale = scaleProj[colProj]; // for int average, FE expects a decimal if (aggOp == ROWAGG_AVG) scale = jobInfo.scaleOfAvg[key]; // scale += 4; @@ -1154,6 +1162,13 @@ void TupleAggregateStep::prep1PhaseAggregate( precisionAgg.push_back(19); widthAgg.push_back(bigIntWidth); } + else + { + typeAgg.push_back(typeProj[colProj]); + scaleAgg.push_back(scaleProj[colProj]); + precisionAgg.push_back(precisionProj[colProj]); + widthAgg.push_back(width[colProj]); + } } break; @@ -1213,7 +1228,7 @@ void TupleAggregateStep::prep1PhaseAggregate( ostringstream emsg; emsg << "aggregate function (" << (uint64_t) aggOp << ") isn't supported"; cerr << "prep1PhaseAggregate: " << emsg.str() << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } @@ -1301,9 +1316,8 @@ void TupleAggregateStep::prep1PhaseAggregate( posAgg.push_back(2); for (uint64_t i = 0; i < oidsAgg.size(); i++) posAgg.push_back(posAgg[i] + widthAgg[i]); - RowGroup aggRG(oidsAgg.size(), posAgg, oidsAgg, keysAgg, typeAgg, scaleAgg, precisionAgg, - jobInfo.stringTableThreshold); - SP_ROWAGG_UM_t rowAgg(new RowAggregationUM(groupBy, functionVec, &jobInfo.rm, jobInfo.umMemLimit)); + RowGroup aggRG(oidsAgg.size(), posAgg, oidsAgg, keysAgg, typeAgg, scaleAgg, precisionAgg); + SP_ROWAGG_UM_t rowAgg(new RowAggregationUM(groupBy, functionVec, &jobInfo.rm)); rowgroups.push_back(aggRG); aggregators.push_back(rowAgg); @@ -1341,22 +1355,22 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( // 1. get projected rowgroup (done by doAggProject) -- passed in // 2. construct aggregate rowgroup -- output of UM const RowGroup projRG = rowgroups[0]; - const vector& oidsProj = projRG.getOIDs(); - const vector& keysProj = projRG.getKeys(); - const vector& scaleProj = projRG.getScale(); - const vector& precisionProj = projRG.getPrecision(); + const vector& oidsProj = projRG.getOIDs(); + const vector& keysProj = projRG.getKeys(); + const vector& scaleProj = projRG.getScale(); + const vector& precisionProj = projRG.getPrecision(); const vector& typeProj = projRG.getColTypes(); - vector posAgg, posAggDist; - vector oidsAgg, oidsAggDist; - vector keysAgg, keysAggDist; - vector scaleAgg, scaleAggDist; - vector precisionAgg, precisionAggDist; + vector posAgg, posAggDist; + vector oidsAgg, oidsAggDist; + vector keysAgg, keysAggDist; + vector scaleAgg, scaleAggDist; + vector precisionAgg, precisionAggDist; vector typeAgg, typeAggDist; - vector widthProj, widthAgg, widthAggDist; + vector widthProj, widthAgg, widthAggDist; vector groupBy, groupByNoDist; vector functionVec1, functionVec2, functionNoDistVec; - uint32_t bigIntWidth = sizeof(int64_t); + uint bigIntWidth = sizeof(int64_t); map, uint64_t> aggFuncMap; set avgSet; @@ -1431,10 +1445,6 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( throw logic_error(emsg.str()); } - // check for dup distinct column -- @bug6126 - if (find(keysAgg.begin(), keysAgg.end(), key) != keysAgg.end()) - continue; - uint64_t colProj = projColPosMap[key]; SP_ROWAGG_GRPBY_t groupby(new RowAggGroupByCol(colProj, colAgg)); @@ -1466,8 +1476,8 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( // skip if this is a group_concat if (aggOp == ROWAGG_GROUP_CONCAT) { - TupleInfo ti = getTupleInfo(aggKey, jobInfo); - uint32_t width = sizeof(GroupConcatAg*); + TupleInfo ti = getExpTupleInfo(aggKey, jobInfo); + uint width = sizeof(GroupConcatAg*); oidsAgg.push_back(ti.oid); keysAgg.push_back(aggKey); scaleAgg.push_back(ti.scale); @@ -1554,7 +1564,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( typeProj[colProj] != CalpontSystemCatalog::FLOAT) { typeAgg.push_back(CalpontSystemCatalog::BIGINT); - uint32_t scale = scaleProj[colProj]; + uint scale = scaleProj[colProj]; // for int average, FE expects a decimal if (aggOp == ROWAGG_AVG) scale = jobInfo.scaleOfAvg[aggKey]; // scale += 4; @@ -1656,7 +1666,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( ostringstream emsg; emsg << "aggregate function (" << (uint64_t) aggOp << ") isn't supported"; cerr << "prep1PhaseDistinctAggregate: " << emsg.str() << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } } @@ -1664,7 +1674,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( // populated the functionNoDistVec { -// for (uint32_t idx = 0; idx < functionVec1.size(); idx++) +// for (uint idx = 0; idx < functionVec1.size(); idx++) // { // SP_ROWAGG_FUNC_t func1 = functionVec1[idx]; // SP_ROWAGG_FUNC_t funct( @@ -1722,7 +1732,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( if (jobInfo.keyInfo->tupleKeyVec[retKey].fView.length() > 0) cerr << ", view=" << jobInfo.keyInfo->tupleKeyVec[retKey].fView; cerr << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } @@ -1751,7 +1761,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( typeAgg[colAgg] != CalpontSystemCatalog::FLOAT) { typeAggDist.push_back(CalpontSystemCatalog::BIGINT); - uint32_t scale = scaleProj[colAgg]; + uint scale = scaleProj[colAgg]; // for int average, FE expects a decimal if (aggOp == ROWAGG_DISTINCT_AVG) scale = jobInfo.scaleOfAvg[retKey]; // scale += 4; @@ -1803,10 +1813,10 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( scaleAggDist.push_back(scaleAgg[colAgg]); precisionAggDist.push_back(precisionAgg[colAgg]); typeAggDist.push_back(typeAgg[colAgg]); - uint32_t width = widthAgg[colAgg]; + uint width = widthAgg[colAgg]; if (aggOp == ROWAGG_GROUP_CONCAT) { - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); if (ti.width > width) width = ti.width; } @@ -1855,7 +1865,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( retKey) != jobInfo.expressionVec.end()) { // a function on aggregation - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggDist.push_back(ti.oid); keysAggDist.push_back(retKey); scaleAggDist.push_back(ti.scale); @@ -1867,7 +1877,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( } else if (aggOp == ROWAGG_CONSTANT) { - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggDist.push_back(ti.oid); keysAggDist.push_back(retKey); scaleAggDist.push_back(ti.scale); @@ -1880,7 +1890,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( #if 0 else if (aggOp == ROWAGG_GROUP_CONCAT) { - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggDist.push_back(ti.oid); keysAggDist.push_back(retKey); scaleAggDist.push_back(ti.scale); @@ -1912,26 +1922,6 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( } } - else if (jobInfo.windowSet.find(retKey) != jobInfo.windowSet.end()) - { - // skip window columns/expression, which are computed later - for (uint64_t k = 0; k < keysProj.size(); k++) - { - if (retKey == keysProj[k]) - { - oidsAggDist.push_back(oidsProj[k]); - keysAggDist.push_back(retKey); - scaleAggDist.push_back(scaleProj[k] >> 8); - precisionAggDist.push_back(precisionProj[k]); - typeAggDist.push_back(typeProj[k]); - widthAggDist.push_back(widthProj[k]); - - returnColMissing = false; - break; - } - } - } - if (returnColMissing) { Message::Args args; @@ -2101,16 +2091,14 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( posAgg.push_back(2); for (uint64_t i = 0; i < oidsAgg.size(); i++) posAgg.push_back(posAgg[i] + widthAgg[i]); - RowGroup aggRG(oidsAgg.size(), posAgg, oidsAgg, keysAgg, typeAgg, scaleAgg, precisionAgg, - jobInfo.stringTableThreshold); - SP_ROWAGG_UM_t rowAgg(new RowAggregationUM(groupBy, functionVec1, &jobInfo.rm, jobInfo.umMemLimit)); + RowGroup aggRG(oidsAgg.size(), posAgg, oidsAgg, keysAgg, typeAgg, scaleAgg, precisionAgg); + SP_ROWAGG_UM_t rowAgg(new RowAggregationUM(groupBy, functionVec1, &jobInfo.rm)); posAggDist.push_back(2); // rid for (uint64_t i = 0; i < oidsAggDist.size(); i++) posAggDist.push_back(posAggDist[i] + widthAggDist[i]); - RowGroup aggRgDist(oidsAggDist.size(), posAggDist, oidsAggDist, keysAggDist, typeAggDist, - scaleAggDist, precisionAggDist, jobInfo.stringTableThreshold); - SP_ROWAGG_DIST rowAggDist(new RowAggregationDistinct(groupByNoDist, functionVec2, &jobInfo.rm, jobInfo.umMemLimit)); + RowGroup aggRgDist(oidsAggDist.size(), posAggDist, oidsAggDist, keysAggDist, typeAggDist, scaleAggDist, precisionAggDist); + SP_ROWAGG_DIST rowAggDist(new RowAggregationDistinct(groupByNoDist, functionVec2, &jobInfo.rm)); // mapping the group_concat columns, if any. if (jobInfo.groupConcatInfo.groupConcat().size() > 0) @@ -2125,18 +2113,18 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( if (jobInfo.distinctColVec.size() > 1) { RowAggregationMultiDistinct* multiDistinctAggregator = - new RowAggregationMultiDistinct(groupByNoDist, functionVec2, &jobInfo.rm, jobInfo.umMemLimit); + new RowAggregationMultiDistinct(groupByNoDist, functionVec2, &jobInfo.rm); rowAggDist.reset(multiDistinctAggregator); rowAggDist->groupConcat(jobInfo.groupConcatInfo.groupConcat()); // construct and add sub-aggregators to rowAggDist - vector posAggGb, posAggSub; - vector oidsAggGb, oidsAggSub; - vector keysAggGb, keysAggSub; - vector scaleAggGb, scaleAggSub; - vector precisionAggGb, precisionAggSub; + vector posAggGb, posAggSub; + vector oidsAggGb, oidsAggSub; + vector keysAggGb, keysAggSub; + vector scaleAggGb, scaleAggSub; + vector precisionAggGb, precisionAggSub; vector typeAggGb, typeAggSub; - vector widthAggGb, widthAggSub; + vector widthAggGb, widthAggSub; // populate groupby column info for (uint64_t i = 0; i < jobInfo.groupByColVec.size(); i++) @@ -2153,7 +2141,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( vector rowAggSubDistVec; for (uint64_t i = 0; i < jobInfo.distinctColVec.size(); i++) { - uint32_t distinctColKey = jobInfo.distinctColVec[i]; + uint distinctColKey = jobInfo.distinctColVec[i]; uint64_t j = -1; // locate the distinct key in the row group @@ -2186,8 +2174,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( posAggSub.push_back(2); // rid for (uint64_t k = 0; k < oidsAggSub.size(); k++) posAggSub.push_back(posAggSub[k] + widthAggSub[k]); - RowGroup subRg(oidsAggSub.size(), posAggSub, oidsAggSub, keysAggSub, typeAggSub, - scaleAggSub, precisionAggSub, jobInfo.stringTableThreshold); + RowGroup subRg(oidsAggSub.size(), posAggSub, oidsAggSub, keysAggSub, typeAggSub, scaleAggSub, precisionAggSub); subRgVec.push_back(subRg); // construct groupby vector @@ -2236,7 +2223,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( // construct sub-aggregator SP_ROWAGG_UM_t subAgg( - new RowAggregationSubDistinct(groupBySub, functionSub1, &jobInfo.rm, jobInfo.umMemLimit)); + new RowAggregationSubDistinct(groupBySub, functionSub1, &jobInfo.rm)); subAgg->groupConcat(jobInfo.groupConcatInfo.groupConcat()); // add to rowAggDist @@ -2290,7 +2277,7 @@ void TupleAggregateStep::prep1PhaseDistinctAggregate( // construct sub-aggregator SP_ROWAGG_UM_t subAgg( - new RowAggregationUM(groupBySubNoDist, functionSub1, &jobInfo.rm, jobInfo.umMemLimit)); + new RowAggregationUM(groupBySubNoDist, functionSub1, &jobInfo.rm)); subAgg->groupConcat(jobInfo.groupConcatInfo.groupConcat()); // add to rowAggDist @@ -2348,23 +2335,22 @@ void TupleAggregateStep::prep2PhasesAggregate( // 2. construct aggregate rowgroup -- output of PM, input of UM // 3. construct aggregate rowgroup -- output of UM const RowGroup projRG = rowgroups[0]; - const vector& oidsProj = projRG.getOIDs(); - const vector& keysProj = projRG.getKeys(); - const vector& scaleProj = projRG.getScale(); - const vector& precisionProj = projRG.getPrecision(); + const vector& oidsProj = projRG.getOIDs(); + const vector& keysProj = projRG.getKeys(); + const vector& scaleProj = projRG.getScale(); + const vector& precisionProj = projRG.getPrecision(); const vector& typeProj = projRG.getColTypes(); - vector posAggPm, posAggUm; - vector oidsAggPm, oidsAggUm; - vector keysAggPm, keysAggUm; - vector scaleAggPm, scaleAggUm; - vector precisionAggPm, precisionAggUm; + vector posAggPm, posAggUm; + vector oidsAggPm, oidsAggUm; + vector keysAggPm, keysAggUm; + vector scaleAggPm, scaleAggUm; + vector precisionAggPm, precisionAggUm; vector typeAggPm, typeAggUm; - vector widthAggPm, widthAggUm; + vector widthAggPm, widthAggUm; vector groupByPm, groupByUm; vector functionVecPm, functionVecUm; - uint32_t bigIntWidth = sizeof(int64_t); - uint32_t bigUintWidth = sizeof(uint64_t); + uint bigIntWidth = sizeof(int64_t); map, uint64_t> aggFuncMap; // associate the columns between projected RG and aggregate RG on PM @@ -2374,7 +2360,7 @@ void TupleAggregateStep::prep2PhasesAggregate( { // project only uniq oids, but they may be repeated in aggregation // collect the projected column info, prepare for aggregation - vector width; + vector width; map projColPosMap; for (uint64_t i = 0; i < keysProj.size(); i++) { @@ -2438,10 +2424,6 @@ void TupleAggregateStep::prep2PhasesAggregate( uint64_t colProj = projColPosMap[key]; - // check for dup distinct column -- @bug6126 - if (find(keysAggPm.begin(), keysAggPm.end(), key) != keysAggPm.end()) - continue; - SP_ROWAGG_GRPBY_t groupby(new RowAggGroupByCol(colProj, colAggPm)); groupByPm.push_back(groupby); @@ -2530,31 +2512,11 @@ void TupleAggregateStep::prep2PhasesAggregate( oidsAggPm.push_back(oidsProj[colProj]); keysAggPm.push_back(aggKey); - if (typeProj[colProj] == CalpontSystemCatalog::DOUBLE || - typeProj[colProj] == CalpontSystemCatalog::UDOUBLE || - typeProj[colProj] == CalpontSystemCatalog::FLOAT || - typeProj[colProj] == CalpontSystemCatalog::UFLOAT) - { - typeAggPm.push_back(typeProj[colProj]); - scaleAggPm.push_back(scaleProj[colProj]); - precisionAggPm.push_back(precisionProj[colProj]); - widthAggPm.push_back(width[colProj]); - } - else if (isUnsigned(typeProj[colProj])) - { - typeAggPm.push_back(CalpontSystemCatalog::UBIGINT); - uint32_t scale = scaleProj[colProj]; - // for int average, FE expects a decimal - if (aggOp == ROWAGG_AVG) - scale = jobInfo.scaleOfAvg[aggKey]; // scale += 4; - scaleAggPm.push_back(scale); - precisionAggPm.push_back(20); - widthAggPm.push_back(bigUintWidth); - } - else + if (typeProj[colProj] != CalpontSystemCatalog::DOUBLE && + typeProj[colProj] != CalpontSystemCatalog::FLOAT) { typeAggPm.push_back(CalpontSystemCatalog::BIGINT); - uint32_t scale = scaleProj[colProj]; + uint scale = scaleProj[colProj]; // for int average, FE expects a decimal if (aggOp == ROWAGG_AVG) scale = jobInfo.scaleOfAvg[aggKey]; // scale += 4; @@ -2562,6 +2524,13 @@ void TupleAggregateStep::prep2PhasesAggregate( precisionAggPm.push_back(19); widthAggPm.push_back(bigIntWidth); } + else + { + typeAggPm.push_back(typeProj[colProj]); + scaleAggPm.push_back(scaleProj[colProj]); + precisionAggPm.push_back(precisionProj[colProj]); + widthAggPm.push_back(width[colProj]); + } colAggPm++; } // PM: put the count column for avg next to the sum @@ -2647,7 +2616,7 @@ void TupleAggregateStep::prep2PhasesAggregate( ostringstream emsg; emsg << "aggregate function (" << (uint64_t) aggOp << ") isn't supported"; cerr << "prep2PhasesAggregate: " << emsg.str() << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } } @@ -2736,20 +2705,7 @@ void TupleAggregateStep::prep2PhasesAggregate( retKey) != jobInfo.expressionVec.end()) { // a function on aggregation - TupleInfo ti = getTupleInfo(retKey, jobInfo); - oidsAggUm.push_back(ti.oid); - keysAggUm.push_back(retKey); - scaleAggUm.push_back(ti.scale); - precisionAggUm.push_back(ti.precision); - typeAggUm.push_back(ti.dtype); - widthAggUm.push_back(ti.width); - - returnColMissing = false; - } - else if (jobInfo.windowSet.find(retKey) != jobInfo.windowSet.end()) - { - // an window function - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggUm.push_back(ti.oid); keysAggUm.push_back(retKey); scaleAggUm.push_back(ti.scale); @@ -2761,7 +2717,7 @@ void TupleAggregateStep::prep2PhasesAggregate( } else if (aggOp == ROWAGG_CONSTANT) { - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggUm.push_back(ti.oid); keysAggUm.push_back(retKey); scaleAggUm.push_back(ti.scale); @@ -2772,7 +2728,6 @@ void TupleAggregateStep::prep2PhasesAggregate( returnColMissing = false; } - if (returnColMissing) { Message::Args args; @@ -2916,17 +2871,15 @@ void TupleAggregateStep::prep2PhasesAggregate( posAggUm.push_back(2); // rid for (uint64_t i = 0; i < oidsAggUm.size(); i++) posAggUm.push_back(posAggUm[i] + widthAggUm[i]); - RowGroup aggRgUm(oidsAggUm.size(), posAggUm, oidsAggUm, keysAggUm, typeAggUm, scaleAggUm, - precisionAggUm, jobInfo.stringTableThreshold); - SP_ROWAGG_UM_t rowAggUm(new RowAggregationUMP2(groupByUm, functionVecUm, &jobInfo.rm, jobInfo.umMemLimit)); + RowGroup aggRgUm(oidsAggUm.size(), posAggUm, oidsAggUm, keysAggUm, typeAggUm, scaleAggUm, precisionAggUm); + SP_ROWAGG_UM_t rowAggUm(new RowAggregationUMP2(groupByUm, functionVecUm, &jobInfo.rm)); rowgroups.push_back(aggRgUm); aggregators.push_back(rowAggUm); posAggPm.push_back(2); // rid for (uint64_t i = 0; i < oidsAggPm.size(); i++) posAggPm.push_back(posAggPm[i] + widthAggPm[i]); - RowGroup aggRgPm(oidsAggPm.size(), posAggPm, oidsAggPm, keysAggPm, typeAggPm, scaleAggPm, - precisionAggPm, jobInfo.stringTableThreshold); + RowGroup aggRgPm(oidsAggPm.size(), posAggPm, oidsAggPm, keysAggPm, typeAggPm, scaleAggPm, precisionAggPm); SP_ROWAGG_PM_t rowAggPm(new RowAggregation(groupByPm, functionVecPm)); rowgroups.push_back(aggRgPm); aggregators.push_back(rowAggPm); @@ -2951,15 +2904,14 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( vector >& returnedColVec = jobInfo.returnedColVec; for (uint64_t i = 0; i < returnedColVec.size(); i++) { - // col should be an aggregate or groupBy or window function + // col should be an aggregate or groupBy uint32_t rtcKey = returnedColVec[i].first; uint32_t rtcOp = returnedColVec[i].second; if (rtcOp == 0 && find(jobInfo.distinctColVec.begin(),jobInfo.distinctColVec.end(), rtcKey) != jobInfo.distinctColVec.end() && find(jobInfo.groupByColVec.begin(),jobInfo.groupByColVec.end(), rtcKey ) == - jobInfo.groupByColVec.end() && - jobInfo.windowSet.find(rtcKey) != jobInfo.windowSet.end()) + jobInfo.groupByColVec.end()) { Message::Args args; args.add(keyName(i, rtcKey, jobInfo)); @@ -2996,24 +2948,24 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( // 4. construct aggregate rowgroup -- output of distinct aggregates const RowGroup projRG = rowgroups[0]; - const vector& oidsProj = projRG.getOIDs(); - const vector& keysProj = projRG.getKeys(); - const vector& scaleProj = projRG.getScale(); - const vector& precisionProj = projRG.getPrecision(); + const vector& oidsProj = projRG.getOIDs(); + const vector& keysProj = projRG.getKeys(); + const vector& scaleProj = projRG.getScale(); + const vector& precisionProj = projRG.getPrecision(); const vector& typeProj = projRG.getColTypes(); - vector posAggPm, posAggUm, posAggDist; - vector oidsAggPm, oidsAggUm, oidsAggDist; - vector keysAggPm, keysAggUm, keysAggDist; - vector scaleAggPm, scaleAggUm, scaleAggDist; - vector precisionAggPm, precisionAggUm, precisionAggDist; + vector posAggPm, posAggUm, posAggDist; + vector oidsAggPm, oidsAggUm, oidsAggDist; + vector keysAggPm, keysAggUm, keysAggDist; + vector scaleAggPm, scaleAggUm, scaleAggDist; + vector precisionAggPm, precisionAggUm, precisionAggDist; vector typeAggPm, typeAggUm, typeAggDist; - vector widthAggPm, widthAggUm, widthAggDist; + vector widthAggPm, widthAggUm, widthAggDist; vector groupByPm, groupByUm, groupByNoDist; vector functionVecPm, functionNoDistVec, functionVecUm; - uint32_t bigIntWidth = sizeof(int64_t); + uint bigIntWidth = sizeof(int64_t); map, uint64_t> aggFuncMap, avgFuncDistMap; // associate the columns between projected RG and aggregate RG on PM @@ -3023,7 +2975,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( { // project only uniq oids, but they may be repeated in aggregation // collect the projected column info, prepare for aggregation - vector width; + vector width; map projColPosMap; for (uint64_t i = 0; i < keysProj.size(); i++) { @@ -3085,7 +3037,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( throw logic_error(emsg.str()); } - // check for dup distinct column -- @bug6126 + // check for dup distinct column if (find(keysAggPm.begin(), keysAggPm.end(), key) != keysAggPm.end()) continue; @@ -3187,7 +3139,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( typeProj[colProj] != CalpontSystemCatalog::FLOAT) { typeAggPm.push_back(CalpontSystemCatalog::BIGINT); - uint32_t scale = scaleProj[colProj]; + uint scale = scaleProj[colProj]; // for int average, FE expects a decimal if (aggOp == ROWAGG_AVG) scale = jobInfo.scaleOfAvg[aggKey]; // scale += 4; @@ -3289,7 +3241,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( ostringstream emsg; emsg << "aggregate function (" << (uint64_t) aggOp << ") isn't supported"; cerr << "prep2PhasesDistinctAggregate: " << emsg.str() << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } } @@ -3299,13 +3251,13 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( // associate the columns between the aggregate RGs on PM and UM without distinct aggregator // populated the returned columns { - for (uint32_t idx = 0; idx < groupByPm.size(); idx++) + for (uint idx = 0; idx < groupByPm.size(); idx++) { SP_ROWAGG_GRPBY_t groupby(new RowAggGroupByCol(idx, idx)); groupByUm.push_back(groupby); } - for (uint32_t idx = 0; idx < functionVecPm.size(); idx++) + for (uint idx = 0; idx < functionVecPm.size(); idx++) { SP_ROWAGG_FUNC_t funcPm = functionVecPm[idx]; SP_ROWAGG_FUNC_t funct(new RowAggFunctionCol( @@ -3371,7 +3323,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( if (jobInfo.keyInfo->tupleKeyVec[retKey].fView.length() > 0) cerr << ", view=" << jobInfo.keyInfo->tupleKeyVec[retKey].fView; cerr << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } @@ -3401,7 +3353,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( typeAggUm[colUm] != CalpontSystemCatalog::FLOAT) { typeAggDist.push_back(CalpontSystemCatalog::BIGINT); - uint32_t scale = scaleAggUm[colUm]; + uint scale = scaleAggUm[colUm]; // for int average, FE expects a decimal if (aggOp == ROWAGG_DISTINCT_AVG) scale = jobInfo.scaleOfAvg[retKey]; // scale += 4; @@ -3502,20 +3454,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( retKey) != jobInfo.expressionVec.end()) { // a function on aggregation - TupleInfo ti = getTupleInfo(retKey, jobInfo); - oidsAggDist.push_back(ti.oid); - keysAggDist.push_back(retKey); - scaleAggDist.push_back(ti.scale); - precisionAggDist.push_back(ti.precision); - typeAggDist.push_back(ti.dtype); - widthAggDist.push_back(ti.width); - - returnColMissing = false; - } - else if (jobInfo.windowSet.find(retKey) != jobInfo.windowSet.end()) - { - // a window function - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggDist.push_back(ti.oid); keysAggDist.push_back(retKey); scaleAggDist.push_back(ti.scale); @@ -3527,7 +3466,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( } else if (aggOp == ROWAGG_CONSTANT) { - TupleInfo ti = getTupleInfo(retKey, jobInfo); + TupleInfo ti = getExpTupleInfo(retKey, jobInfo); oidsAggDist.push_back(ti.oid); keysAggDist.push_back(retKey); scaleAggDist.push_back(ti.scale); @@ -3706,33 +3645,31 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( posAggUm.push_back(2); // rid for (uint64_t i = 0; i < oidsAggUm.size(); i++) posAggUm.push_back(posAggUm[i] + widthAggUm[i]); - RowGroup aggRgUm(oidsAggUm.size(), posAggUm, oidsAggUm, keysAggUm, typeAggUm, scaleAggUm, - precisionAggUm, jobInfo.stringTableThreshold); - SP_ROWAGG_UM_t rowAggUm(new RowAggregationUMP2(groupByUm, functionNoDistVec, &jobInfo.rm, jobInfo.umMemLimit)); + RowGroup aggRgUm(oidsAggUm.size(), posAggUm, oidsAggUm, keysAggUm, typeAggUm, scaleAggUm, precisionAggUm); + SP_ROWAGG_UM_t rowAggUm(new RowAggregationUMP2(groupByUm, functionNoDistVec, &jobInfo.rm)); posAggDist.push_back(2); // rid for (uint64_t i = 0; i < oidsAggDist.size(); i++) posAggDist.push_back(posAggDist[i] + widthAggDist[i]); - RowGroup aggRgDist(oidsAggDist.size(), posAggDist, oidsAggDist, keysAggDist, typeAggDist, - scaleAggDist, precisionAggDist, jobInfo.stringTableThreshold); - SP_ROWAGG_DIST rowAggDist(new RowAggregationDistinct(groupByNoDist, functionVecUm, &jobInfo.rm, jobInfo.umMemLimit)); + RowGroup aggRgDist(oidsAggDist.size(), posAggDist, oidsAggDist, keysAggDist, typeAggDist, scaleAggDist, precisionAggDist); + SP_ROWAGG_DIST rowAggDist(new RowAggregationDistinct(groupByNoDist, functionVecUm, &jobInfo.rm)); // if distinct key word applied to more than one aggregate column, reset rowAggDist vector subRgVec; if (jobInfo.distinctColVec.size() > 1) { RowAggregationMultiDistinct* multiDistinctAggregator = - new RowAggregationMultiDistinct(groupByNoDist, functionVecUm, &jobInfo.rm, jobInfo.umMemLimit); + new RowAggregationMultiDistinct(groupByNoDist, functionVecUm, &jobInfo.rm); rowAggDist.reset(multiDistinctAggregator); // construct and add sub-aggregators to rowAggDist - vector posAggGb, posAggSub; - vector oidsAggGb, oidsAggSub; - vector keysAggGb, keysAggSub; - vector scaleAggGb, scaleAggSub; - vector precisionAggGb, precisionAggSub; + vector posAggGb, posAggSub; + vector oidsAggGb, oidsAggSub; + vector keysAggGb, keysAggSub; + vector scaleAggGb, scaleAggSub; + vector precisionAggGb, precisionAggSub; vector typeAggGb, typeAggSub; - vector widthAggGb, widthAggSub; + vector widthAggGb, widthAggSub; // populate groupby column info for (uint64_t i = 0; i < jobInfo.groupByColVec.size(); i++) @@ -3749,7 +3686,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( vector rowAggSubDistVec; for (uint64_t i = 0; i < jobInfo.distinctColVec.size(); i++) { - uint32_t distinctColKey = jobInfo.distinctColVec[i]; + uint distinctColKey = jobInfo.distinctColVec[i]; uint64_t j = -1; // locate the distinct key in the row group @@ -3782,8 +3719,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( posAggSub.push_back(2); // rid for (uint64_t k = 0; k < oidsAggSub.size(); k++) posAggSub.push_back(posAggSub[k] + widthAggSub[k]); - RowGroup subRg(oidsAggSub.size(), posAggSub, oidsAggSub, keysAggSub, typeAggSub, - scaleAggSub, precisionAggSub, jobInfo.stringTableThreshold); + RowGroup subRg(oidsAggSub.size(), posAggSub, oidsAggSub, keysAggSub, typeAggSub, scaleAggSub, precisionAggSub); subRgVec.push_back(subRg); // construct groupby vector @@ -3795,7 +3731,6 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( groupBySub.push_back(groupby); k++; } - // add the distinct column as groupby SP_ROWAGG_GRPBY_t groupby(new RowAggGroupByCol(j, k)); groupBySub.push_back(groupby); @@ -3832,7 +3767,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( } // construct sub-aggregator - SP_ROWAGG_UM_t subAgg(new RowAggregationSubDistinct(groupBySub, functionSub1, &jobInfo.rm, jobInfo.umMemLimit)); + SP_ROWAGG_UM_t subAgg(new RowAggregationSubDistinct(groupBySub, functionSub1, &jobInfo.rm)); // add to rowAggDist multiDistinctAggregator->addSubAggregator(subAgg, subRg, functionSub2); @@ -3884,7 +3819,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( // construct sub-aggregator SP_ROWAGG_UM_t subAgg( - new RowAggregationUMP2(groupBySubNoDist, functionSub1, &jobInfo.rm, jobInfo.umMemLimit)); + new RowAggregationUMP2(groupBySubNoDist, functionSub1, &jobInfo.rm)); // add to rowAggDist multiDistinctAggregator->addSubAggregator(subAgg, aggRgUm, functionSub2); @@ -3900,8 +3835,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( posAggPm.push_back(2); // rid for (uint64_t i = 0; i < oidsAggPm.size(); i++) posAggPm.push_back(posAggPm[i] + widthAggPm[i]); - RowGroup aggRgPm(oidsAggPm.size(), posAggPm, oidsAggPm, keysAggPm, typeAggPm, scaleAggPm, - precisionAggPm, jobInfo.stringTableThreshold); + RowGroup aggRgPm(oidsAggPm.size(), posAggPm, oidsAggPm, keysAggPm, typeAggPm, scaleAggPm, precisionAggPm); SP_ROWAGG_PM_t rowAggPm(new RowAggregation(groupByPm, functionVecPm)); rowgroups.push_back(aggRgPm); aggregators.push_back(rowAggPm); @@ -3921,7 +3855,7 @@ void TupleAggregateStep::prep2PhasesDistinctAggregate( void TupleAggregateStep::prepExpressionOnAggregate(SP_ROWAGG_UM_t& aggUM, JobInfo& jobInfo) { - map keyToIndexMap; + map keyToIndexMap; for (uint64_t i = 0; i < fRowGroupOut.getKeys().size(); ++i) { if (keyToIndexMap.find(fRowGroupOut.getKeys()[i]) == keyToIndexMap.end()) @@ -3958,7 +3892,7 @@ void TupleAggregateStep::prepExpressionOnAggregate(SP_ROWAGG_UM_t& aggUM, JobInf // update the output index if (eid != (uint64_t) -1) { - map::iterator mit = keyToIndexMap.find(getExpTupleKey(jobInfo, eid)); + map::iterator mit = keyToIndexMap.find(getExpTupleKey(jobInfo, eid)); if (mit != keyToIndexMap.end()) { @@ -3969,7 +3903,7 @@ void TupleAggregateStep::prepExpressionOnAggregate(SP_ROWAGG_UM_t& aggUM, JobInf ostringstream emsg; emsg << "expression " << eid << " cannot be found in tuple."; cerr << "prepExpressionOnAggregate: " << emsg.str() << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } } @@ -3978,7 +3912,7 @@ void TupleAggregateStep::prepExpressionOnAggregate(SP_ROWAGG_UM_t& aggUM, JobInf for (vector::iterator i = simpleColumns.begin(); i != simpleColumns.end(); i++) { CalpontSystemCatalog::OID oid = (*i)->oid(); - uint32_t key = getTupleKey(jobInfo, *i); + uint key = getTupleKey(jobInfo, *i); CalpontSystemCatalog::OID dictOid = joblist::isDictCol((*i)->colType()); if (dictOid > 0) { @@ -3986,7 +3920,7 @@ void TupleAggregateStep::prepExpressionOnAggregate(SP_ROWAGG_UM_t& aggUM, JobInf key = jobInfo.keyInfo->dictKeyMap[key]; } - map::iterator mit = keyToIndexMap.find(key); + map::iterator mit = keyToIndexMap.find(key); if (mit != keyToIndexMap.end()) { @@ -3998,7 +3932,7 @@ void TupleAggregateStep::prepExpressionOnAggregate(SP_ROWAGG_UM_t& aggUM, JobInf emsg << "'" << jobInfo.keyInfo->tupleKeyToName[key] << "' cannot be found in tuple."; cerr << "prepExpressionOnAggregate: " << emsg.str() << " simple column: oid(" << oid << "), alias(" << extractTableAlias(*i) << ")." << endl; - throw QueryDataExcept(emsg.str(), aggregateFuncErr); + throw logging::QueryDataExcept(emsg.str(), logging::aggregateFuncErr); } } @@ -4015,18 +3949,18 @@ void TupleAggregateStep::addConstangAggregate(vector& constAggD void TupleAggregateStep::aggregateRowGroups() { - RGData rgData; + shared_array rgData; bool more = true; RowGroupDL *dlIn = NULL; if (!fDoneAggregate) { if (fInputJobStepAssociation.outSize() == 0) - throw logic_error("No input data list for TupleAggregate step."); + throw logic_error("No input data list for delivery."); dlIn = fInputJobStepAssociation.outAt(0)->rowGroupDL(); if (dlIn == NULL) - throw logic_error("Input is not RowGroup data list in TupleAggregate step."); + throw logic_error("Input is not RowGroup data list in delivery step."); if (fInputIter < 0) fInputIter = dlIn->getIterator(); @@ -4034,17 +3968,10 @@ void TupleAggregateStep::aggregateRowGroups() more = dlIn->next(fInputIter, &rgData); if (traceOn()) dlTimes.setFirstReadTime(); - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - try { // this check covers the no row case - if (!more && cancelled()) + if (!more && (0 < fInputJobStepAssociation.status() || die)) { fDoneAggregate = true; fEndOfResult = true; @@ -4052,65 +3979,133 @@ void TupleAggregateStep::aggregateRowGroups() while (more && !fEndOfResult) { - fRowGroupIn.setData(&rgData); + fRowGroupIn.setData(rgData.get()); + //timer.start("insert"); fAggregator->addRowGroup(&fRowGroupIn); + //timer.stop("insert"); more = dlIn->next(fInputIter, &rgData); - - // error checking - if (cancelled()) + /* error checking */ + if (0 < fInputJobStepAssociation.status() || die) { + fOutputJobStepAssociation.status(fInputJobStepAssociation.status()); fEndOfResult = true; - while (more) - more = dlIn->next(fInputIter, &rgData); + while (more) more = dlIn->next(fInputIter, &rgData); } } } // try catch (IDBExcept& iex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId, - (iex.errorCode() == ERR_AGGREGATION_TOO_BIG ? LOG_TYPE_INFO : LOG_TYPE_CRITICAL)); + catchHandler(iex.what(), fSessionId, (iex.errorCode() == logging::ERR_AGGREGATION_TOO_BIG ? logging::LOG_TYPE_INFO : + logging::LOG_TYPE_CRITICAL)); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(iex.errorCode()); + fEndOfResult = true; + fDoneAggregate = true; + while (more) more = dlIn->next(fInputIter, &rgData); + + if (traceOn()) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + } + + throw; + } + catch (QueryDataExcept& qex) + { + catchHandler(qex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(qex.errorCode()); + + fEndOfResult = true; + fDoneAggregate = true; + while (more) more = dlIn->next(fInputIter, &rgData); + + if (traceOn()) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + } + + throw; } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleAggregateStepErr, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); + fEndOfResult = true; + fDoneAggregate = true; + while (more) more = dlIn->next(fInputIter, &rgData); + + if (traceOn()) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + } + + throw; } catch(...) { - catchHandler("TupleAggregateStep::aggregateRowGroups() caught an unknown exception", - tupleAggregateStepErr, fErrorInfo, fSessionId); + catchHandler("TupleAggregateStep::aggregateRowGroups() caught an unknown exception", fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); + fEndOfResult = true; - } - } + fDoneAggregate = true; + while (more) more = dlIn->next(fInputIter, &rgData); - fDoneAggregate = true; + if (traceOn()) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + } - while (more) - more = dlIn->next(fInputIter, &rgData); + throw; + } - if (traceOn()) - { - dlTimes.setLastReadTime(); - dlTimes.setEndOfInputTime(); + if (traceOn()) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + } + + fDoneAggregate = true; } + /* Bug 5698. A catch-all. It seems that control can get here w/o having + drained the input. Prevents the feeding JobStep from exiting & hangs the session. + */ + while (more) + more = dlIn->next(fInputIter, &rgData); } -void TupleAggregateStep::threadedAggregateRowGroups(uint32_t threadID) +void TupleAggregateStep::threadedAggregateRowGroups(uint8_t threadID) { - RGData rgData; + shared_array rgData; + uint32_t hashlen; + //RowBucketVec rowBucketVecs[fNumOfBuckets]; scoped_array rowBucketVecs(new RowBucketVec[fNumOfBuckets]); - scoped_array distRow; - scoped_array > distRowData; - uint32_t bucketID; + boost::scoped_array distRow; + boost::shared_array* distRowData; + uint bucketID; + //bool bucketDone[fNumOfBuckets]; scoped_array bucketDone(new bool[fNumOfBuckets]); - vector hashLens; + vector hashs; bool locked = false; + + // profiling + //ostringstream readInput, buildBucket, buildMap; + //readInput << "readInput" << (int)threadID; + //buildBucket << "buildBucket" << (int)threadID; + //buildMap << "buildMap" << (int)threadID; + bool more = true; RowGroupDL *dlIn = NULL; - bool caughtException = false; - + RowAggregationMultiDistinct *multiDist = NULL; if (!fDoneAggregate) @@ -4122,105 +4117,78 @@ void TupleAggregateStep::threadedAggregateRowGroups(uint32_t threadID) if (dlIn == NULL) throw logic_error("Input is not RowGroup data list in delivery step."); - vector rgDatas; + vector > rgDatas; try { // this check covers the no row case - if (!more && cancelled()) + if (!more && (0 < fInputJobStepAssociation.status())) { fDoneAggregate = true; fEndOfResult = true; } + //uint64_t rgcount = 0; //debug bool firstRead = true; Row rowIn; while (more && !fEndOfResult) { - fMutex.lock(); + mutex.lock(); locked = true; - for (uint32_t c = 0; c < fNumOfRowGroups && !cancelled(); c++) + //timer.start(readInput.str()); + for (uint c = 0; c < fNumOfRowGroups && !die; c++) { more = dlIn->next(fInputIter, &rgData); if (firstRead) { - if (threadID == 0) - { - if (traceOn()) - dlTimes.setFirstReadTime(); - - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - } + if (traceOn() && threadID == 0) dlTimes.setFirstReadTime(); multiDist = dynamic_cast(fAggregator.get()); if (multiDist) { - for (uint32_t i = 0; i < fNumOfBuckets; i++) + for (uint i = 0; i < fNumOfBuckets; i++) rowBucketVecs[i].resize(multiDist->subAggregators().size()); distRow.reset(new Row[multiDist->subAggregators().size()]); - distRowData.reset(new shared_array[ - multiDist->subAggregators().size()]); - for (uint32_t j = 0; j < multiDist->subAggregators().size(); j++) + distRowData = new boost::shared_array[multiDist->subAggregators().size()]; + for (uint j = 0; j < multiDist->subAggregators().size(); j++) { multiDist->subAggregators()[j]->getOutputRowGroup()->initRow( - &distRow[j], true); + &distRow[j]); distRowData[j].reset(new uint8_t[distRow[j].getSize()]); distRow[j].setData(distRowData[j].get()); - hashLens.push_back(multiDist->subAggregators()[j]->aggMapKeyLength()); + hashlen = multiDist->subAggregators()[j]->aggMapKeyLength(); + hashs.push_back(new utils::TupleHasher(hashlen)); } } else { - for (uint32_t i = 0; i < fNumOfBuckets; i++) + for (uint i = 0; i < fNumOfBuckets; i++) rowBucketVecs[i].resize(1); if (dynamic_cast(fAggregator.get())) - hashLens.push_back(dynamic_cast(fAggregator.get())->aggregator()->aggMapKeyLength()); + hashlen = dynamic_cast(fAggregator.get())->aggregator()->aggMapKeyLength(); else - hashLens.push_back(fAggregator->aggMapKeyLength()); + hashlen = fAggregator->aggMapKeyLength(); + hashs.push_back(new utils::TupleHasher(hashlen)); } fRowGroupIns[threadID] = fRowGroupIn; fRowGroupIns[threadID].initRow(&rowIn); firstRead = false; } - if (more) { - // Trying out a ramp-up strategy for starting the - // first phase threads to cut overhead on big systems - // processing small result - // sets. On every non-zero read from the input FIFO, - // and if there is more data to read, the - // first thread will start another thread until the - // maximum number is reached. - if (threadID == 0 && fFirstPhaseThreadCount < fNumOfThreads && - dlIn->more(fInputIter)) { - fFirstPhaseRunners[fFirstPhaseThreadCount].reset - (new boost::thread(ThreadedAggregator(this, fFirstPhaseThreadCount))); - fFirstPhaseThreadCount++; - } - - fRowGroupIns[threadID].setData(&rgData); - fMemUsage[threadID] += fRowGroupIns[threadID].getSizeWithStrings(); - if (!fRm.getMemory(fRowGroupIns[threadID].getSizeWithStrings(), fSessionMemLimit)) + fRowGroupIns[threadID].setData(rgData.get()); + memUsage[threadID] += fRowGroupIns[threadID].getDataSize(); + if (!rm->getMemory(fRowGroupIns[threadID].getDataSize())) { rgDatas.clear(); // to short-cut the rest of processing abort(); more = false; fEndOfResult = true; - if (status() == 0) - { - errorMessage(IDBErrorInfo::instance()->errorMsg( - ERR_AGGREGATION_TOO_BIG)); - status(ERR_AGGREGATION_TOO_BIG); - } + if (fInputJobStepAssociation.status() == 0) + fInputJobStepAssociation.status(logging::ERR_AGGREGATION_TOO_BIG); break; } else @@ -4234,41 +4202,44 @@ void TupleAggregateStep::threadedAggregateRowGroups(uint32_t threadID) } } - // input rowgroup and aggregator is finalized only right before hashjoin starts - // if there is. + // input rowgroup and aggregator is finalized only right before hashjoin starts if there is. if (fAggregators.empty()) { fAggregators.resize(fNumOfBuckets); - for (uint32_t i = 0; i < fNumOfBuckets; i++) + for (uint i = 0; i < fNumOfBuckets; i++) { fAggregators[i].reset(fAggregator->clone()); fAggregators[i]->setInputOutput(fRowGroupIn, &fRowGroupOuts[i]); } } - fMutex.unlock(); + mutex.unlock(); locked = false; + //timer.stop(readInput.str()); + //timer.start(buildBucket.str()); multiDist = dynamic_cast(fAggregator.get()); // dispatch rows to row buckets if (multiDist) { - for (uint32_t c = 0; c < rgDatas.size(); c++) + for (uint c = 0; c < rgDatas.size(); c++) { - fRowGroupIns[threadID].setData(&rgDatas[c]); - for (uint32_t j = 0; j < multiDist->subAggregators().size(); j++) + fRowGroupIns[threadID].setData(rgDatas[c].get()); + + for (uint j = 0; j < multiDist->subAggregators().size(); j++) { fRowGroupIns[threadID].getRow(0, &rowIn); for (uint64_t i = 0; i < fRowGroupIns[threadID].getRowCount(); ++i) { - for (uint64_t k = 0; - k < multiDist->subAggregators()[j]->getGroupByCols().size(); - ++k) + for (uint64_t k = 0; k < multiDist->subAggregators()[j]->getGroupByCols().size(); ++k) { - rowIn.copyField(distRow[j], k, multiDist->subAggregators()[j]->getGroupByCols()[k].get()->fInputColumnIndex); + rowIn.copyField( + distRow[j].getData() + multiDist->subAggregators()[j]->getOutputRowGroup()->getOffsets()[k], + multiDist->subAggregators()[j]->getGroupByCols()[k].get()->fInputColumnIndex); } - bucketID = distRow[j].hash(hashLens[j] - 1) % fNumOfBuckets; - rowBucketVecs[bucketID][j].push_back(rowIn.getPointer()); + uint8_t* hashMapKey = distRow[j].getData() + 2; + bucketID = hashs[j]->operator()(hashMapKey) & fBucketMask; + rowBucketVecs[bucketID][j].push_back(rowIn.getData()); rowIn.nextRow(); } } @@ -4276,39 +4247,45 @@ void TupleAggregateStep::threadedAggregateRowGroups(uint32_t threadID) } else { - for (uint32_t c = 0; c < rgDatas.size(); c++) + for (uint c = 0; c < rgDatas.size(); c++) { - fRowGroupIns[threadID].setData(&rgDatas[c]); + fRowGroupIns[threadID].setData(rgDatas[c].get()); fRowGroupIns[threadID].getRow(0, &rowIn); for (uint64_t i = 0; i < fRowGroupIns[threadID].getRowCount(); ++i) { // The key is the groupby columns, which are the leading columns. - int bucketID = rowIn.hash(hashLens[0] - 1) % fNumOfBuckets; - rowBucketVecs[bucketID][0].push_back(rowIn.getPointer()); + uint8_t* hashMapKey = rowIn.getData() + 2; + int bucketID = hashs[0]->operator()(hashMapKey) & fBucketMask; + rowBucketVecs[bucketID][0].push_back(rowIn.getData()); rowIn.nextRow(); } } } + //timer.stop(buildBucket.str()); // insert to the hashmaps owned by each aggregator bool done = false; + //memset(bucketDone, 0, sizeof(bucketDone)); fill(&bucketDone[0], &bucketDone[fNumOfBuckets], false); - while (!fEndOfResult && !done && !cancelled()) + while (!fEndOfResult && !done && !die && !fInputJobStepAssociation.status()) { bool didWork = false; done = true; - for (uint32_t c = 0; c < fNumOfBuckets && !cancelled(); c++) + for (uint c = 0; c < fNumOfBuckets && !(die || fInputJobStepAssociation.status()); c++) { - if (!fEndOfResult && !bucketDone[c] && fAgg_mutex[c]->try_lock()) + if (!fEndOfResult && !bucketDone[c] && agg_mutex[c]->try_lock()) { didWork = true; + //timer.start(buildMap.str()); + //rgcount += rowBucketVecs[c][0].size(); //debug if (multiDist) dynamic_cast(fAggregators[c].get())->addRowGroup(&fRowGroupIns[threadID], rowBucketVecs[c]); else fAggregators[c]->addRowGroup(&fRowGroupIns[threadID], rowBucketVecs[c][0]); - fAgg_mutex[c]->unlock(); + agg_mutex[c]->unlock(); rowBucketVecs[c][0].clear(); bucketDone[c] = true; + //timer.stop(buildMap.str()); } else if (!bucketDone[c]) { @@ -4319,56 +4296,111 @@ void TupleAggregateStep::threadedAggregateRowGroups(uint32_t threadID) usleep(1000); // avoid using all CPU during busy wait } rgDatas.clear(); - fRm.returnMemory(fMemUsage[threadID], fSessionMemLimit); - fMemUsage[threadID] = 0; + rm->returnMemory(memUsage[threadID]); + memUsage[threadID] = 0; - if (cancelled()) + if (0 < fInputJobStepAssociation.status() || die) { + fOutputJobStepAssociation.status(fInputJobStepAssociation.status()); fEndOfResult = true; - fMutex.lock(); - - while (more) - more = dlIn->next(fInputIter, &rgData); - - fMutex.unlock(); + mutex.lock(); + while (more) more = dlIn->next(fInputIter, &rgData); + mutex.unlock(); } } + //cout << "thread " << (int)threadID << " rcount: " << rgcount << endl; + } // try catch (IDBExcept& iex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId, - (iex.errorCode() == ERR_AGGREGATION_TOO_BIG ? LOG_TYPE_INFO : LOG_TYPE_CRITICAL)); - caughtException = true; + catchHandler(iex.what(), fSessionId, + (iex.errorCode() == logging::ERR_AGGREGATION_TOO_BIG ? logging::LOG_TYPE_INFO : + logging::LOG_TYPE_CRITICAL)); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(iex.errorCode()); + + fEndOfResult = true; + fDoneAggregate = true; + if (!locked) + mutex.lock(); + while (more) more = dlIn->next(fInputIter, &rgData); + mutex.unlock(); + locked = false; + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + + return; + } + catch (QueryDataExcept& qex) + { + catchHandler(qex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(qex.errorCode()); + + fEndOfResult = true; + fDoneAggregate = true; + if (!locked) + mutex.lock(); + while (more) more = dlIn->next(fInputIter, &rgData); + mutex.unlock(); + locked = false; + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + + return; } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleAggregateStepErr, fErrorInfo, fSessionId); - caughtException = true; + catchHandler(ex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); + + fEndOfResult = true; + fDoneAggregate = true; + if (!locked) + mutex.lock(); + while (more) more = dlIn->next(fInputIter, &rgData); + mutex.unlock(); + locked = false; + + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + + return; } catch(...) { - catchHandler("threadedAggregateRowGroups() caught an unknown exception", - tupleAggregateStepErr, fErrorInfo, fSessionId); - caughtException = true; - } - } + catchHandler("TupleAggregateStep::aggregateRowGroups() caught an unknown exception", fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); - if (caughtException) - { - fEndOfResult = true; - fDoneAggregate = true; - } + fEndOfResult = true; + fDoneAggregate = true; + if (!locked) + mutex.lock(); + while (more) more = dlIn->next(fInputIter, &rgData); + mutex.unlock(); + locked = false; - if (!locked) fMutex.lock(); - while (more) more = dlIn->next(fInputIter, &rgData); - fMutex.unlock(); - locked = false; + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + + return; + } - if (traceOn()) - { dlTimes.setLastReadTime(); dlTimes.setEndOfInputTime(); } + + /* Bug 5698. A catch-all. It seems that control can get here w/o + having drained the input. Prevents the feeding JobStep from exiting & hangs the session. + */ + mutex.lock(); + while (more) + more = dlIn->next(fInputIter, &rgData); + mutex.unlock(); } @@ -4376,7 +4408,7 @@ void TupleAggregateStep::doAggregate_singleThread() { AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); RowGroupDL* dlp = dl->rowGroupDL(); - RGData rgData; + shared_array rgData; try { @@ -4396,40 +4428,37 @@ void TupleAggregateStep::doAggregate_singleThread() { fAggregator->finalize(); fRowsReturned += fRowGroupOut.getRowCount(); - rgData = fRowGroupOut.duplicate(); - fRowGroupDelivered.setData(&rgData); + rgData.reset(new uint8_t[fRowGroupOut.getDataSize()]); + memcpy(rgData.get(), fRowGroupOut.getData(), fRowGroupOut.getDataSize()); + fRowGroupDelivered.setData(rgData.get()); if (fRowGroupOut.getColumnCount() > fRowGroupDelivered.getColumnCount()) pruneAuxColumns(); dlp->insert(rgData); } } } // try - catch (IDBExcept& iex) + catch (QueryDataExcept& qex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId, - (iex.errorCode() == ERR_AGGREGATION_TOO_BIG ? LOG_TYPE_INFO : LOG_TYPE_CRITICAL)); + catchHandler(qex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(qex.errorCode()); } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleAggregateStepErr, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); } catch(...) { - catchHandler("TupleAggregateStep next band caught an unknown exception", - tupleAggregateStepErr, fErrorInfo, fSessionId); + catchHandler("TupleAggregateStep next band caught an unknown exception", fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); } if (traceOn()) printCalTrace(); - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - // Bug 3136, let mini stats to be formatted if traceOn. fEndOfResult = true; dlp->endOfInput(); @@ -4442,7 +4471,7 @@ void TupleAggregateStep::doAggregate() // because hashjoin may not have finalized fAggregator. if (!fIsMultiThread) return doAggregate_singleThread(); - + AnyDataListSPtr dl = fOutputJobStepAssociation.outAt(0); RowGroupDL* dlp = dl->rowGroupDL(); ByteStream bs; @@ -4454,37 +4483,23 @@ void TupleAggregateStep::doAggregate() uint64_t TupleAggregateStep::doThreadedAggregate(ByteStream& bs, RowGroupDL* dlp) { uint32_t i; - RGData rgData; + shared_array rgData; uint64_t rowCount = 0; try { if (!fDoneAggregate) { + vector > runners; + boost::shared_ptr runner; initializeMultiThread(); -/* -// This block of code starts all threads at the start - fFirstPhaseThreadCount = fNumOfThreads; - boost::shared_ptr runner; - for (i = 0; i < fNumOfThreads; i++) - { - runner.reset(new boost::thread(ThreadedAggregator(this, i))); - fFirstPhaseRunners.push_back(runner); - } -*/ - -// This block of code starts one thread, relies on doThreadedAggregation() -// to start more as needed - fFirstPhaseRunners.resize(fNumOfThreads); // to prevent a resize during use - fFirstPhaseThreadCount = 1; - for (i = 1; i < fNumOfThreads; i++) - // fill with valid thread objects to make joining work - fFirstPhaseRunners[i].reset(new boost::thread()); - fFirstPhaseRunners[0].reset(new boost::thread(ThreadedAggregator(this, 0))); - - for (i = 0; i < fNumOfThreads; i++) - fFirstPhaseRunners[i]->join(); - fFirstPhaseRunners.clear(); - } + for (i = 0; i < fNumOfThreads; i++) + { + runner.reset(new boost::thread(ThreadedAggregator(this, i))); + runners.push_back(runner); + } + for (i = 0; i < fNumOfThreads; i++) + runners[i]->join(); + } if (dynamic_cast(fAggregator.get()) && fAggregator->aggMapKeyLength() > 0) { @@ -4493,24 +4508,24 @@ uint64_t TupleAggregateStep::doThreadedAggregate(ByteStream& bs, RowGroupDL* dlp { if (!fDoneAggregate) { - vector > runners; - boost::shared_ptr runner; + vector > runners; + boost::shared_ptr runner; fRowGroupsDeliveredData.resize(fNumOfBuckets); - uint32_t bucketsPerThread = fNumOfBuckets/fNumOfThreads; - uint32_t numThreads = ((fNumOfBuckets % fNumOfThreads) == 0 ? - fNumOfThreads : fNumOfThreads + 1); - //uint32_t bucketsPerThread = 1; - //uint32_t numThreads = fNumOfBuckets; - - for (i = 0; i < numThreads; i++) - { - runner.reset(new boost::thread(ThreadedSecondPhaseAggregator(this, i*bucketsPerThread, bucketsPerThread))); - runners.push_back(runner); - } - for (i = 0; i < numThreads; i++) - runners[i]->join(); - } + for (i = 0; i < fNumOfBuckets; i++) + { + runner.reset(new boost::thread(ThreadedSecondPhaseAggregator(this, i))); + runners.push_back(runner); + } + for (i = 0; i < fNumOfBuckets; i++) + runners[i]->join(); + } + + // profiling debug + //for (uint c = 0; c < fNumOfBuckets; c++) + //{ + // cout << "map[" << c << "] = " << fAggregators[c]->mapPtr()->size() << endl; + //} fDoneAggregate = true; bool done = true; @@ -4525,13 +4540,14 @@ uint64_t TupleAggregateStep::doThreadedAggregate(ByteStream& bs, RowGroupDL* dlp if (dlp) { - rgData = fRowGroupDelivered.duplicate(); + rgData.reset(new uint8_t[fRowGroupDelivered.getDataSize()]); + memcpy(rgData.get(), fRowGroupDelivered.getData(), fRowGroupDelivered.getDataSize()); dlp->insert(rgData); } else { bs.restart(); - fRowGroupDelivered.serializeRGData(bs); + bs.load(fRowGroupDelivered.getData(), fRowGroupDelivered.getDataSize()); break; } } @@ -4547,6 +4563,7 @@ uint64_t TupleAggregateStep::doThreadedAggregate(ByteStream& bs, RowGroupDL* dlp RowAggregationDistinct* agg = dynamic_cast(fAggregator.get()); if (!fEndOfResult) { + ////bs.restart(); if (!fDoneAggregate) { for (i = 0; i < fNumOfBuckets; i++) @@ -4559,39 +4576,35 @@ uint64_t TupleAggregateStep::doThreadedAggregate(ByteStream& bs, RowGroupDL* dlp if (agg != NULL) { RowAggregationMultiDistinct *aggMultiDist = - dynamic_cast(fAggregators[i].get()); - RowAggregationDistinct *aggDist = - dynamic_cast(fAggregators[i].get()); + dynamic_cast(fAggregators[i].get()); + RowAggregationDistinct *aggDist = dynamic_cast(fAggregators[i].get()); agg->aggregator(aggDist->aggregator()); if (aggMultiDist) - (dynamic_cast(agg)) - ->subAggregators(aggMultiDist->subAggregators()); + (dynamic_cast(agg))->subAggregators(aggMultiDist->subAggregators()); agg->doDistinctAggregation(); } // for "group by without distinct" case else { - fAggregator->resultDataVec().insert( - fAggregator->resultDataVec().end(), - fAggregators[i]->resultDataVec().begin(), - fAggregators[i]->resultDataVec().end()); + fAggregator->resultDataVec().insert(fAggregator->resultDataVec().end(), + fAggregators[i]->resultDataVec().begin(), + fAggregators[i]->resultDataVec().end()); } } } } - fDoneAggregate = true; } bool done = true; //@bug4459 - while (fAggregator->nextRowGroup() && !cancelled()) + while (fAggregator->nextRowGroup() && !die) { done = false; fAggregator->finalize(); rowCount = fRowGroupOut.getRowCount(); fRowsReturned += rowCount; - fRowGroupDelivered.setData(fRowGroupOut.getRGData()); + fRowGroupDelivered.setData(fRowGroupOut.getData()); if (rowCount != 0) { @@ -4600,66 +4613,72 @@ uint64_t TupleAggregateStep::doThreadedAggregate(ByteStream& bs, RowGroupDL* dlp if (dlp) { - rgData = fRowGroupDelivered.duplicate(); + rgData.reset(new uint8_t[fRowGroupOut.getDataSize()]); + memcpy(rgData.get(), fRowGroupOut.getData(), fRowGroupOut.getDataSize()); dlp->insert(rgData); } else { bs.restart(); - fRowGroupDelivered.serializeRGData(bs); + bs.load(fRowGroupDelivered.getData(), fRowGroupDelivered.getDataSize()); break; } } done = true; } - if (done) { fEndOfResult = true; } } + //timer.finish(); + } catch (IDBExcept& iex) + { + catchHandler(iex.what(), fSessionId, (iex.errorCode() == logging::ERR_AGGREGATION_TOO_BIG ? logging::LOG_TYPE_INFO : + logging::LOG_TYPE_CRITICAL)); + if (0 == fOutputJobStepAssociation.status()) + { + fOutputJobStepAssociation.status(iex.errorCode()); + fOutputJobStepAssociation.errorMessage(iex.what()); + } + fEndOfResult = true; } - catch (IDBExcept& iex) + catch (QueryDataExcept& qex) { - catchHandler(iex.what(), iex.errorCode(), fErrorInfo, fSessionId, - (iex.errorCode() == ERR_AGGREGATION_TOO_BIG ? LOG_TYPE_INFO : LOG_TYPE_CRITICAL)); + catchHandler(qex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(qex.errorCode()); fEndOfResult = true; } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleAggregateStepErr, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (0 == fOutputJobStepAssociation.status()) + fOutputJobStepAssociation.status(tupleAggregateStepErr); fEndOfResult = true; } - if (fEndOfResult) + if (dlp) { - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - - if (dlp) - { + if (fEndOfResult) dlp->endOfInput(); - } - else + } + else + { + if (fEndOfResult) { // send an empty / error band - RGData rgData(fRowGroupOut, 0); - fRowGroupOut.setData(&rgData); + shared_array rgData(new uint8_t[fRowGroupOut.getEmptySize()]); + fRowGroupOut.setData(rgData.get()); fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setStatus(status()); - fRowGroupOut.serializeRGData(bs); + fRowGroupOut.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgData.get(), fRowGroupOut.getDataSize()); rowCount = 0; - } - if (traceOn()) - printCalTrace(); + if (traceOn()) + printCalTrace(); + } } - return rowCount; } @@ -4696,8 +4715,7 @@ void TupleAggregateStep::printCalTrace() << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); diff --git a/dbcon/joblist/tupleaggregatestep.h b/dbcon/joblist/tupleaggregatestep.h index 79ae2a5a..62c987d7 100644 --- a/dbcon/joblist/tupleaggregatestep.h +++ b/dbcon/joblist/tupleaggregatestep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tupleaggregatestep.h 9732 2013-08-02 15:56:15Z pleblanc $ +// $Id: tupleaggregatestep.h 8810 2012-08-13 17:01:37Z zzhu $ #ifndef JOBLIST_TUPLEAGGREGATESTEP_H @@ -40,12 +40,20 @@ class TupleAggregateStep : public JobStep, public TupleDeliveryStep { public: /** @brief TupleAggregateStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer */ TupleAggregateStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + boost::shared_ptr syscat, + uint32_t sessionId, + uint32_t txnId, + uint32_t statementId, const rowgroup::SP_ROWAGG_UM_t&, const rowgroup::RowGroup&, const rowgroup::RowGroup&, - const JobInfo&); + ResourceManager *); /** @brief TupleAggregateStep destructor */ @@ -56,23 +64,54 @@ class TupleAggregateStep : public JobStep, public TupleDeliveryStep void run(); void join(); + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * + */ + const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + void stepId(uint16_t stepId) { fStepId = stepId; } + uint16_t stepId() const { return fStepId; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t statementId() const { return fStatementId; } + const std::string toString() const; void setOutputRowGroup(const rowgroup::RowGroup&); const rowgroup::RowGroup& getOutputRowGroup() const; const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; - uint32_t nextBand(messageqcpp::ByteStream &bs); - uint32_t nextBand_singleThread(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); + uint nextBand_singleThread(messageqcpp::ByteStream &bs); bool setPmHJAggregation(JobStep* step); void savePmHJData(rowgroup::SP_ROWAGG_t&, rowgroup::SP_ROWAGG_t&, rowgroup::RowGroup&); + void logger(const SPJL& logger) { fLogger = logger; } bool umOnly() const { return fUmOnly; } void umOnly(bool b) { fUmOnly = b; } void configDeliveredRowGroup(const JobInfo&); - //void setEidMap(std::map& m) { fIndexEidMap = m; } + void setIsDelivery(bool b) { fDelivery = b; } + void setEidMap(std::map& m) { fIndexEidMap = m; } static SJSTEP prepAggregate(SJSTEP&, JobInfo&); @@ -96,25 +135,32 @@ class TupleAggregateStep : public JobStep, public TupleDeliveryStep void doAggregate_singleThread(); uint64_t doThreadedAggregate(messageqcpp::ByteStream &bs, RowGroupDL* dlp); void aggregateRowGroups(); - void threadedAggregateRowGroups(uint32_t threadID); - void doThreadedSecondPhaseAggregate(uint32_t threadID); + void threadedAggregateRowGroups(uint8_t threadID); + void doThreadedSecondPhaseAggregate(uint8_t threadID); bool nextDeliveredRowGroup(); void pruneAuxColumns(); void formatMiniStats(); void printCalTrace(); + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; boost::shared_ptrfCatalog; + uint32_t fSessionId; + uint32_t fTxnId; + uint16_t fStepId; + uint32_t fStatementId; uint64_t fRowsReturned; bool fDoneAggregate; bool fEndOfResult; + SPJL fLogger; rowgroup::SP_ROWAGG_UM_t fAggregator; rowgroup::RowGroup fRowGroupOut; rowgroup::RowGroup fRowGroupDelivered; - rowgroup::RGData fRowGroupData; + boost::shared_array fRowGroupData; // for setting aggregate column eid in delivered rowgroup - //std::map fIndexEidMap; + std::map fIndexEidMap; // data from RowGroupDL rowgroup::RowGroup fRowGroupIn; @@ -125,7 +171,7 @@ class TupleAggregateStep : public JobStep, public TupleDeliveryStep rowgroup::SP_ROWAGG_PM_t fAggregatorPM; rowgroup::RowGroup fRowGroupPMHJ; - // for run thread (first added for union) + // for Union class Aggregator { public: @@ -138,58 +184,50 @@ class TupleAggregateStep : public JobStep, public TupleDeliveryStep class ThreadedAggregator { public: - ThreadedAggregator(TupleAggregateStep* step, uint32_t threadID) : + ThreadedAggregator(TupleAggregateStep* step, uint8_t threadID) : fStep(step), fThreadID(threadID) {} void operator()() { fStep->threadedAggregateRowGroups(fThreadID); } TupleAggregateStep* fStep; - uint32_t fThreadID; + uint8_t fThreadID; }; class ThreadedSecondPhaseAggregator { public: - ThreadedSecondPhaseAggregator(TupleAggregateStep* step, uint32_t threadID, uint32_t bucketsPerThread) : + ThreadedSecondPhaseAggregator(TupleAggregateStep* step, uint8_t threadID) : fStep(step), - fThreadID(threadID), - bucketCount(bucketsPerThread) + fThreadID(threadID) { } - void operator()() { - for (uint32_t i = 0; i < bucketCount; i++) - fStep->doThreadedSecondPhaseAggregate(fThreadID+i); - } + void operator()() {fStep->doThreadedSecondPhaseAggregate(fThreadID);} TupleAggregateStep* fStep; - uint32_t fThreadID; - uint32_t bucketCount; + uint8_t fThreadID; }; boost::scoped_ptr fRunner; + bool fDelivery; bool fUmOnly; - ResourceManager& fRm; + ResourceManager *rm; // multi-threaded - uint32_t fNumOfThreads; - uint32_t fNumOfBuckets; - uint32_t fNumOfRowGroups; - uint32_t fBucketNum; - - boost::mutex fMutex; - std::vector fAgg_mutex; - std::vector fRowGroupDatas; + uint fNumOfThreads; + uint fNumOfBuckets; + uint fNumOfRowGroups; + uint64_t fBucketMask; + + boost::mutex mutex; + std::vector agg_mutex; + std::vector > fRowGroupDatas; std::vector fAggregators; std::vector fRowGroupIns; vector fRowGroupOuts; - std::vector > fRowGroupsDeliveredData; + std::vector > > fRowGroupsDeliveredData; bool fIsMultiThread; int fInputIter; // iterator - boost::scoped_array fMemUsage; - vector > fFirstPhaseRunners; - uint32_t fFirstPhaseThreadCount; - - boost::shared_ptr fSessionMemLimit; + boost::scoped_array memUsage; }; diff --git a/dbcon/joblist/tupleannexstep.cpp b/dbcon/joblist/tupleannexstep.cpp index ea889a14..3ca6d220 100644 --- a/dbcon/joblist/tupleannexstep.cpp +++ b/dbcon/joblist/tupleannexstep.cpp @@ -15,23 +15,17 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tupleannexstep.cpp 9661 2013-07-01 20:33:05Z pleblanc $ +// $Id: tupleannexstep.cpp 9662 2013-07-01 20:34:26Z pleblanc $ //#define NDEBUG #include #include #include -#ifdef _MSC_VER -#include -#else -#include -#endif using namespace std; #include #include -#include using namespace boost; #include "messagequeue.h" @@ -42,6 +36,7 @@ using namespace messageqcpp; using namespace logging; #include "calpontsystemcatalog.h" +#include "aggregatecolumn.h" #include "constantcolumn.h" #include "simplecolumn.h" using namespace execplan; @@ -50,12 +45,9 @@ using namespace execplan; using namespace rowgroup; #include "hasher.h" -#include "stlpoolallocator.h" +#include "simpleallocator.h" using namespace utils; -#include "querytele.h" -using namespace querytele; - #include "funcexp.h" #include "jobstep.h" #include "jlf_common.h" @@ -66,60 +58,38 @@ using namespace querytele; namespace { -struct TAHasher { - joblist::TupleAnnexStep *ts; - utils::Hasher_r h; - TAHasher(joblist::TupleAnnexStep *t) : ts(t) { } - uint64_t operator()(const rowgroup::Row::Pointer &) const; -}; -struct TAEq { - joblist::TupleAnnexStep *ts; - TAEq(joblist::TupleAnnexStep *t) : ts(t) { } - bool operator()(const rowgroup::Row::Pointer &, const rowgroup::Row::Pointer &) const; -}; -//TODO: Generalize these and put them back in utils/common/hasher.h -typedef tr1::unordered_set > DistinctMap_t; +typedef tr1::unordered_map > > DistinctMap_t; }; -inline uint64_t TAHasher::operator()(const Row::Pointer &p) const -{ - Row &row = ts->row1; - row.setPointer(p); - return row.hash(); -} - -inline bool TAEq::operator()(const Row::Pointer &d1, const Row::Pointer &d2) const -{ - Row &r1 = ts->row1, &r2 = ts->row2; - r1.setPointer(d1); - r2.setPointer(d2); - return r1.equals(r2); -} namespace joblist { -TupleAnnexStep::TupleAnnexStep(const JobInfo& jobInfo) : - JobStep(jobInfo), +TupleAnnexStep::TupleAnnexStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId, + const JobInfo& jobInfo) : + fSessionId(sessionId), + fTxnId(txnId), + fVerId(verId), + fStatementId(statementId), fInputDL(NULL), fOutputDL(NULL), fInputIterator(0), fOutputIterator(0), - fRowsProcessed(0), fRowsReturned(0), - fLimitStart(0), - fLimitCount(-1), - fLimitHit(false), fEndOfResult(false), + fDelivery(false), fDistinct(false), fOrderBy(NULL), fConstant(NULL), fFeInstance(funcexp::FuncExp::instance()), fJobList(jobInfo.jobListPtr) { - fExtendedInfo = "TNS: "; - fQtc.stepParms().stepType = StepTeleStats::T_TNS; + fExtendedInfo = "TXS: "; } @@ -154,12 +124,12 @@ void TupleAnnexStep::initialize(const RowGroup& rgIn, const JobInfo& jobInfo) if (fConstant == NULL) { - vector oids, oidsIn = fRowGroupIn.getOIDs(); - vector keys, keysIn = fRowGroupIn.getKeys(); - vector scale, scaleIn = fRowGroupIn.getScale(); - vector precision, precisionIn = fRowGroupIn.getPrecision(); + vector oids, oidsIn = fRowGroupIn.getOIDs(); + vector keys, keysIn = fRowGroupIn.getKeys(); + vector scale, scaleIn = fRowGroupIn.getScale(); + vector precision, precisionIn = fRowGroupIn.getPrecision(); vector types, typesIn = fRowGroupIn.getColTypes(); - vector pos, posIn = fRowGroupIn.getOffsets(); + vector pos, posIn = fRowGroupIn.getOffsets(); size_t n = jobInfo.nonConstDelCols.size(); oids.insert(oids.end(), oidsIn.begin(), oidsIn.begin() + n); @@ -169,7 +139,7 @@ void TupleAnnexStep::initialize(const RowGroup& rgIn, const JobInfo& jobInfo) types.insert(types.end(), typesIn.begin(), typesIn.begin() + n); pos.insert(pos.end(), posIn.begin(), posIn.begin() + n + 1); - fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision); } else { @@ -194,7 +164,7 @@ void TupleAnnexStep::run() fInputIterator = fInputDL->getIterator(); if (fOutputJobStepAssociation.outSize() == 0) - throw logic_error("No output data list for annex step."); + throw logic_error("No output data list for non-delivery annex step."); fOutputDL = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); if (fOutputDL == NULL) @@ -216,21 +186,24 @@ void TupleAnnexStep::join() } -uint32_t TupleAnnexStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleAnnexStep::nextBand(messageqcpp::ByteStream &bs) { - RGData rgDataOut; + shared_array rgDataOut; bool more = false; - uint32_t rowCount = 0; + uint rowCount = 0; try { bs.restart(); more = fOutputDL->next(fOutputIterator, &rgDataOut); - if (more && !cancelled()) + if (traceOn() && dlTimes.FirstReadTime().tv_sec ==0) + dlTimes.setFirstReadTime(); + + if (more && (0 == fOutputJobStepAssociation.status()) && !die) { - fRowGroupDeliver.setData(&rgDataOut); - fRowGroupDeliver.serializeRGData(bs); + fRowGroupDeliver.setData(rgDataOut.get()); + bs.load(fRowGroupDeliver.getData(), fRowGroupDeliver.getDataSize()); rowCount = fRowGroupDeliver.getRowCount(); } else @@ -242,28 +215,38 @@ uint32_t TupleAnnexStep::nextBand(messageqcpp::ByteStream &bs) } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_IN_DELIVERY, fErrorInfo, fSessionId); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_DELIVERY); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } catch(...) { - catchHandler("TupleAnnexStep next band caught an unknown exception", - ERR_IN_DELIVERY, fErrorInfo, fSessionId); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); + catchHandler("TupleAnnexStep next band caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_DELIVERY); + while (more) more = fOutputDL->next(fOutputIterator, &rgDataOut); fEndOfResult = true; } if (fEndOfResult) { // send an empty / error band - rgDataOut.reinit(fRowGroupDeliver, 0); - fRowGroupDeliver.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupDeliver.getEmptySize()]); + fRowGroupDeliver.setData(rgDataOut.get()); fRowGroupDeliver.resetRowGroup(0); - fRowGroupDeliver.setStatus(status()); - fRowGroupDeliver.serializeRGData(bs); + fRowGroupDeliver.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgDataOut.get(), fRowGroupDeliver.getDataSize()); + + if (traceOn()) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + } + + if (traceOn()) + printCalTrace(); } return rowCount; @@ -278,80 +261,50 @@ void TupleAnnexStep::execute() executeNoOrderByWithDistinct(); else executeNoOrderBy(); - - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - - if (traceOn()) - { - if (dlTimes.FirstReadTime().tv_sec ==0) - dlTimes.setFirstReadTime(); - - dlTimes.setLastReadTime(); - dlTimes.setEndOfInputTime(); - printCalTrace(); - } } void TupleAnnexStep::executeNoOrderBy() { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; + bool hitLimit = false; try { more = fInputDL->next(fInputIterator, &rgDataIn); if (traceOn()) dlTimes.setFirstReadTime(); - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - while (more && !cancelled() && !fLimitHit) + while (more && (0 == fInputJobStepAssociation.status()) && !die && !hitLimit) { - fRowGroupIn.setData(&rgDataIn); + fRowGroupIn.setData(rgDataIn.get()); fRowGroupIn.getRow(0, &fRowIn); // Get a new output rowgroup for each input rowgroup to preserve the rids - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); + fRowGroupOut.setData(rgDataOut.get()); fRowGroupOut.resetRowGroup(fRowGroupIn.getBaseRid()); fRowGroupOut.setDBRoot(fRowGroupIn.getDBRoot()); fRowGroupOut.getRow(0, &fRowOut); - for (uint64_t i = 0; i < fRowGroupIn.getRowCount() && !cancelled() && !fLimitHit; ++i) + for (uint64_t i = 0; i < fRowGroupIn.getRowCount() && + (0 == fInputJobStepAssociation.status()) && !die && !hitLimit; ++i) { - // skip first limit-start rows - if (fRowsProcessed++ < fLimitStart) - { - fRowIn.nextRow(); - continue; - } - if (fConstant) fConstant->fillInConstants(fRowIn, fRowOut); else - copyRow(fRowIn, &fRowOut); + memcpy(fRowOut.getData(), fRowIn.getData(), fRowOut.getSize()); fRowGroupOut.incRowCount(); - if (++fRowsReturned < fLimitCount) + if (++fRowsReturned < fLimit) { fRowOut.nextRow(); fRowIn.nextRow(); } else { - fLimitHit = true; + hitLimit = true; fJobList->abortOnLimit((JobStep*) this); } } @@ -366,16 +319,26 @@ void TupleAnnexStep::executeNoOrderBy() } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_IN_PROCESS, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_PROCESS); } catch(...) { - catchHandler("TupleAnnexStep execute caught an unknown exception", - ERR_IN_PROCESS, fErrorInfo, fSessionId); + catchHandler("TupleAnnexStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_PROCESS); } - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); + + + if (traceOn() && !fDelivery) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + printCalTrace(); + } // Bug 3136, let mini stats to be formatted if traceOn. fOutputDL->endOfInput(); @@ -384,63 +347,63 @@ void TupleAnnexStep::executeNoOrderBy() void TupleAnnexStep::executeNoOrderByWithDistinct() { - scoped_ptr distinctMap(new DistinctMap_t(10, TAHasher(this), TAEq(this))); - vector dataVec; - RGData rgDataIn; - RGData rgDataOut; + uint64_t keyLength = fRowOut.getSize() - 2; + utils::TupleHasher hasher(keyLength); + utils::TupleComparator comp(keyLength); + shared_ptr pool(new utils::SimplePool); + utils::SimpleAllocator > alloc(pool); + scoped_ptr distinctMap(new DistinctMap_t(10, hasher, comp, alloc)); + vector > dataVec; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; + bool hitLimit = false; - rgDataOut.reinit(fRowGroupOut); - fRowGroupOut.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(8192)]); + fRowGroupOut.setData(rgDataOut.get()); fRowGroupOut.resetRowGroup(0); fRowGroupOut.getRow(0, &fRowOut); - fRowGroupOut.initRow(&row1); - fRowGroupOut.initRow(&row2); - try { more = fInputDL->next(fInputIterator, &rgDataIn); if (traceOn()) dlTimes.setFirstReadTime(); - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - while (more && !cancelled() && !fLimitHit) + while (more && (0 == fInputJobStepAssociation.status()) && !die && !hitLimit) { - fRowGroupIn.setData(&rgDataIn); + fRowGroupIn.setData(rgDataIn.get()); fRowGroupIn.getRow(0, &fRowIn); - for (uint64_t i = 0; i < fRowGroupIn.getRowCount() && !cancelled() && !fLimitHit; ++i) + for (uint64_t i = 0; i < fRowGroupIn.getRowCount() && + (0 == fInputJobStepAssociation.status()) && !die && !hitLimit; ++i) { - pair inserted; if (fConstant) fConstant->fillInConstants(fRowIn, fRowOut); else - copyRow(fRowIn, &fRowOut); + memcpy(fRowOut.getData(), fRowIn.getData(), fRowOut.getSize()); - ++fRowsProcessed; fRowIn.nextRow(); - inserted = distinctMap->insert(fRowOut.getPointer()); - if (inserted.second) { + if (distinctMap->find(fRowOut.getData()+2) == distinctMap->end()) + { + distinctMap->insert(make_pair(fRowOut.getData()+2, fRowOut.getData())); + fRowGroupOut.incRowCount(); - fRowOut.nextRow(); - if (UNLIKELY(++fRowsReturned >= fLimitCount)) + if (++fRowsReturned < fLimit) { - fLimitHit = true; + fRowOut.nextRow(); + } + else + { + hitLimit = true; fJobList->abortOnLimit((JobStep*) this); } - if (UNLIKELY(fRowGroupOut.getRowCount() >= 8192)) + if (fRowGroupOut.getRowCount() >= 8192) { dataVec.push_back(rgDataOut); - rgDataOut.reinit(fRowGroupOut); - fRowGroupOut.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(8192)]); + fRowGroupOut.setData(rgDataOut.get()); fRowGroupOut.resetRowGroup(0); fRowGroupOut.getRow(0, &fRowOut); } @@ -453,25 +416,34 @@ void TupleAnnexStep::executeNoOrderByWithDistinct() if (fRowGroupOut.getRowCount() > 0) dataVec.push_back(rgDataOut); - for (vector::iterator i = dataVec.begin(); i != dataVec.end(); i++) + for (vector >::iterator i = dataVec.begin(); i != dataVec.end(); i++) { rgDataOut = *i; - fRowGroupOut.setData(&rgDataOut); + fRowGroupOut.setData(rgDataOut.get()); fOutputDL->insert(rgDataOut); } } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_IN_PROCESS, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_PROCESS); } catch(...) { - catchHandler("TupleAnnexStep execute caught an unknown exception", - ERR_IN_PROCESS, fErrorInfo, fSessionId); + catchHandler("TupleAnnexStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_PROCESS); } - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); + + if (traceOn() && !fDelivery) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + printCalTrace(); + } // Bug 3136, let mini stats to be formatted if traceOn. fOutputDL->endOfInput(); @@ -480,8 +452,8 @@ void TupleAnnexStep::executeNoOrderByWithDistinct() void TupleAnnexStep::executeWithOrderBy() { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; try @@ -489,19 +461,14 @@ void TupleAnnexStep::executeWithOrderBy() more = fInputDL->next(fInputIterator, &rgDataIn); if (traceOn()) dlTimes.setFirstReadTime(); - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - while (more && !cancelled()) + while (more && (0 == fInputJobStepAssociation.status()) && !die) { - fRowGroupIn.setData(&rgDataIn); + fRowGroupIn.setData(rgDataIn.get()); fRowGroupIn.getRow(0, &fRowIn); - for (uint64_t i = 0; i < fRowGroupIn.getRowCount() && !cancelled(); ++i) + for (uint64_t i = 0; + i < fRowGroupIn.getRowCount() && (0 == fInputJobStepAssociation.status()) && !die; + ++i) { fOrderBy->processRow(fRowIn); fRowIn.nextRow(); @@ -512,7 +479,7 @@ void TupleAnnexStep::executeWithOrderBy() fOrderBy->finalize(); - if (!cancelled()) + if (fOutputJobStepAssociation.status() == 0 && !die) { while (fOrderBy->getData(rgDataIn)) { @@ -520,15 +487,15 @@ void TupleAnnexStep::executeWithOrderBy() fRowGroupOut.getColumnCount() == fRowGroupIn.getColumnCount()) { rgDataOut = rgDataIn; - fRowGroupOut.setData(&rgDataOut); + fRowGroupOut.setData(rgDataOut.get()); } else { - fRowGroupIn.setData(&rgDataIn); + fRowGroupIn.setData(rgDataIn.get()); fRowGroupIn.getRow(0, &fRowIn); - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); + fRowGroupOut.setData(rgDataOut.get()); fRowGroupOut.resetRowGroup(fRowGroupIn.getBaseRid()); fRowGroupOut.setDBRoot(fRowGroupIn.getDBRoot()); fRowGroupOut.getRow(0, &fRowOut); @@ -538,7 +505,7 @@ void TupleAnnexStep::executeWithOrderBy() if (fConstant) fConstant->fillInConstants(fRowIn, fRowOut); else - copyRow(fRowIn, &fRowOut); + memcpy(fRowOut.getData(), fRowIn.getData(), fRowOut.getSize()); fRowGroupOut.incRowCount(); fRowOut.nextRow(); @@ -556,16 +523,25 @@ void TupleAnnexStep::executeWithOrderBy() } catch(const std::exception& ex) { - catchHandler(ex.what(), ERR_IN_PROCESS, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_PROCESS); } catch(...) { - catchHandler("TupleAnnexStep execute caught an unknown exception", - ERR_IN_PROCESS, fErrorInfo, fSessionId); + catchHandler("TupleAnnexStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(ERR_IN_PROCESS); } - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); + + if (traceOn() && !fDelivery) + { + dlTimes.setLastReadTime(); + dlTimes.setEndOfInputTime(); + printCalTrace(); + } // Bug 3136, let mini stats to be formatted if traceOn. fOutputDL->endOfInput(); @@ -584,20 +560,6 @@ const RowGroup& TupleAnnexStep::getDeliveredRowGroup() const } -void TupleAnnexStep::deliverStringTableRowGroup(bool b) -{ - fRowGroupOut.setUseStringTable(b); - fRowGroupDeliver.setUseStringTable(b); -} - - -bool TupleAnnexStep::deliverStringTableRowGroup() const -{ - idbassert(fRowGroupOut.usesStringTable() == fRowGroupDeliver.usesStringTable()); - return fRowGroupDeliver.usesStringTable(); -} - - const string TupleAnnexStep::toString() const { ostringstream oss; @@ -633,8 +595,7 @@ void TupleAnnexStep::printCalTrace() << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); diff --git a/dbcon/joblist/tupleannexstep.h b/dbcon/joblist/tupleannexstep.h index 69a16734..4c9f3b36 100644 --- a/dbcon/joblist/tupleannexstep.h +++ b/dbcon/joblist/tupleannexstep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tupleannexstep.h 9596 2013-06-04 19:59:04Z xlou $ +// $Id: tupleannexstep.h 9219 2013-01-25 18:48:19Z xlou $ #ifndef JOBLIST_TUPLEANNEXSTEP_H @@ -47,8 +47,14 @@ class TupleAnnexStep : public JobStep, public TupleDeliveryStep { public: /** @brief TupleAnnexStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer */ - TupleAnnexStep(const JobInfo& jobInfo); + TupleAnnexStep( uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId, + const JobInfo& jobInfo); /** @brief TupleAnnexStep destructor */ @@ -57,7 +63,20 @@ class TupleAnnexStep : public JobStep, public TupleDeliveryStep // inherited methods void run(); void join(); + const JobStepAssociation& inputAssociation() const { return fInputJobStepAssociation; } + void inputAssociation(const JobStepAssociation& in) { fInputJobStepAssociation = in; } + const JobStepAssociation& outputAssociation() const { return fOutputJobStepAssociation; } + void outputAssociation(const JobStepAssociation& out) { fOutputJobStepAssociation = out; } + JobStepAssociation& outputAssociation() { return fOutputJobStepAssociation; } + const std::string toString() const; + void stepId(uint16_t sId) { fStepId = sId; } + uint16_t stepId() const { return fStepId; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t verId() const { return fVerId; } + uint32_t statementId() const { return fStatementId; } + void logger(const SPJL& logger) { fLogger = logger; } /** @brief TupleJobStep's pure virtual methods */ @@ -66,21 +85,16 @@ class TupleAnnexStep : public JobStep, public TupleDeliveryStep /** @brief TupleDeliveryStep's pure virtual methods */ - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; + void setIsDelivery(bool b) { fDelivery = b; } void initialize(const rowgroup::RowGroup& rgIn, const JobInfo& jobInfo); void addOrderBy(LimitedOrderBy* lob) { fOrderBy = lob; } void addConstant(TupleConstantStep* tcs) { fConstant = tcs; } void setDistinct() { fDistinct = true; } - void setLimit(uint64_t s, uint64_t c) { fLimitStart = s; fLimitCount = c; } - - virtual bool stringTableFriendly() { return true; } - - rowgroup::Row row1, row2; // scratch space for distinct comparisons todo: make them private + void setLimit(uint64_t l) { fLimit = l; } protected: void execute(); @@ -90,6 +104,16 @@ class TupleAnnexStep : public JobStep, public TupleDeliveryStep void formatMiniStats(); void printCalTrace(); + // for virtual function + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; + SPJL fLogger; + // input/output rowgroup and row rowgroup::RowGroup fRowGroupIn; rowgroup::RowGroup fRowGroupOut; @@ -113,12 +137,10 @@ class TupleAnnexStep : public JobStep, public TupleDeliveryStep }; boost::scoped_ptr fRunner; - uint64_t fRowsProcessed; uint64_t fRowsReturned; - uint64_t fLimitStart; - uint64_t fLimitCount; - bool fLimitHit; + uint64_t fLimit; bool fEndOfResult; + bool fDelivery; bool fDistinct; LimitedOrderBy* fOrderBy; @@ -126,7 +148,6 @@ class TupleAnnexStep : public JobStep, public TupleDeliveryStep funcexp::FuncExp* fFeInstance; JobList* fJobList; - }; diff --git a/dbcon/joblist/tupleconstantstep.cpp b/dbcon/joblist/tupleconstantstep.cpp index 4e79bd62..ad6fc59f 100644 --- a/dbcon/joblist/tupleconstantstep.cpp +++ b/dbcon/joblist/tupleconstantstep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tupleconstantstep.cpp 9649 2013-06-25 16:08:05Z xlou $ +// $Id: tupleconstantstep.cpp 8526 2012-05-17 02:28:10Z xlou $ //#define NDEBUG @@ -26,7 +26,6 @@ using namespace std; #include #include -#include using namespace boost; #include "messagequeue.h" @@ -46,9 +45,6 @@ using namespace execplan; #include "rowgroup.h" using namespace rowgroup; -#include "querytele.h" -using namespace querytele; - #include "jlf_common.h" #include "tupleconstantstep.h" @@ -62,11 +58,22 @@ SJSTEP TupleConstantStep::addConstantStep(const JobInfo& jobInfo, const rowgroup if (jobInfo.constantCol != CONST_COL_ONLY) { - tcs = new TupleConstantStep(jobInfo); + + tcs = new TupleConstantStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); } else { - tcs = new TupleConstantOnlyStep(jobInfo); + tcs = new TupleConstantOnlyStep(JobStepAssociation(jobInfo.status), + JobStepAssociation(jobInfo.status), + jobInfo.sessionId, + jobInfo.txnId, + jobInfo.verId, + jobInfo.statementId); } tcs->initialize(jobInfo, rg); @@ -75,16 +82,28 @@ SJSTEP TupleConstantStep::addConstantStep(const JobInfo& jobInfo, const rowgroup } -TupleConstantStep::TupleConstantStep(const JobInfo& jobInfo) : - JobStep(jobInfo), +TupleConstantStep::TupleConstantStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId) : + fInputJobStepAssociation(inputJobStepAssociation), + fOutputJobStepAssociation(outputJobStepAssociation), + fSessionId(sessionId), + fTxnId(txnId), + fVerId(verId), + fStepId(0), + fStatementId(statementId), fRowsReturned(0), fInputDL(NULL), fOutputDL(NULL), fInputIterator(0), - fEndOfResult(false) + fEndOfResult(false), + fDelivery(false) { fExtendedInfo = "TCS: "; - fQtc.stepParms().stepType = StepTeleStats::T_TCS; } @@ -101,12 +120,12 @@ void TupleConstantStep::setOutputRowGroup(const rowgroup::RowGroup& rg) void TupleConstantStep::initialize(const JobInfo& jobInfo, const RowGroup* rgIn) { - vector oids, oidsIn = fRowGroupIn.getOIDs(); - vector keys, keysIn = fRowGroupIn.getKeys(); - vector scale, scaleIn = fRowGroupIn.getScale(); - vector precision, precisionIn = fRowGroupIn.getPrecision(); + vector oids, oidsIn = fRowGroupIn.getOIDs(); + vector keys, keysIn = fRowGroupIn.getKeys(); + vector scale, scaleIn = fRowGroupIn.getScale(); + vector precision, precisionIn = fRowGroupIn.getPrecision(); vector types, typesIn = fRowGroupIn.getColTypes(); - vector pos; + vector pos; pos.push_back(2); if (rgIn) @@ -166,10 +185,9 @@ void TupleConstantStep::initialize(const JobInfo& jobInfo, const RowGroup* rgIn) } } - fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision, - jobInfo.stringTableThreshold); + fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision); fRowGroupOut.initRow(&fRowOut); - fRowGroupOut.initRow(&fRowConst, true); + fRowGroupOut.initRow(&fRowConst); constructContanstRow(jobInfo); } @@ -180,7 +198,6 @@ void TupleConstantStep::constructContanstRow(const JobInfo& jobInfo) // construct a row with only the constant values fConstRowData.reset(new uint8_t[fRowConst.getSize()]); fRowConst.setData(fConstRowData.get()); - fRowConst.initToNull(); // make sure every col is init'd to something, because later we copy the whole row const vector& types = fRowGroupOut.getColTypes(); for (vector::iterator i = fIndexConst.begin(); i != fIndexConst.end(); i++) { @@ -192,17 +209,9 @@ void TupleConstantStep::constructContanstRow(const JobInfo& jobInfo) { if (types[*i] == CalpontSystemCatalog::CHAR || types[*i] == CalpontSystemCatalog::VARCHAR) - { fRowConst.setStringField("", *i); - } - else if (isUnsigned(types[*i])) - { - fRowConst.setUintField(fRowConst.getNullValue(*i), *i); - } else - { fRowConst.setIntField(fRowConst.getSignedNullValue(*i), *i); - } continue; } @@ -223,21 +232,18 @@ void TupleConstantStep::constructContanstRow(const JobInfo& jobInfo) } case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { fRowConst.setIntField(c.decimalVal.value, *i); break; } case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { fRowConst.setFloatField(c.floatVal, *i); break; } case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { fRowConst.setDoubleField(c.doubleVal, *i); break; @@ -250,16 +256,6 @@ void TupleConstantStep::constructContanstRow(const JobInfo& jobInfo) break; } - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - { - fRowConst.setUintField(c.uintVal, *i); - break; - } - default: { throw runtime_error("un-supported constant column type."); @@ -302,12 +298,12 @@ void TupleConstantStep::join() } -uint32_t TupleConstantStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleConstantStep::nextBand(messageqcpp::ByteStream &bs) { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; - uint32_t rowCount = 0; + uint rowCount = 0; try { @@ -317,19 +313,19 @@ uint32_t TupleConstantStep::nextBand(messageqcpp::ByteStream &bs) if (traceOn() && dlTimes.FirstReadTime().tv_sec == 0) dlTimes.setFirstReadTime(); - if (!more && cancelled()) + if (!more && (0 < fInputJobStepAssociation.status() || die)) { fEndOfResult = true; } if (more && !fEndOfResult) { - fRowGroupIn.setData(&rgDataIn); - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); + fRowGroupIn.setData(rgDataIn.get()); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); + fRowGroupOut.setData(rgDataOut.get()); fillInConstants(); - fRowGroupOut.serializeRGData(bs); + bs.load(fRowGroupOut.getData(), fRowGroupOut.getDataSize()); rowCount = fRowGroupOut.getRowCount(); } else @@ -339,28 +335,29 @@ uint32_t TupleConstantStep::nextBand(messageqcpp::ByteStream &bs) } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleConstantStepErr, fErrorInfo, fSessionId); - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); fEndOfResult = true; } catch(...) { - catchHandler("TupleConstantStep next band caught an unknown exception", - tupleConstantStepErr, fErrorInfo, fSessionId); - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + catchHandler("TupleConstantStep next band caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); fEndOfResult = true; } if (fEndOfResult) { // send an empty / error band - RGData rgData(fRowGroupOut, 0); - fRowGroupOut.setData(&rgData); + shared_array rgData(new uint8_t[fRowGroupOut.getEmptySize()]); + fRowGroupOut.setData(rgData.get()); fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setStatus(status()); - fRowGroupOut.serializeRGData(bs); + fRowGroupOut.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgData.get(), fRowGroupOut.getDataSize()); if (traceOn()) { @@ -376,37 +373,30 @@ uint32_t TupleConstantStep::nextBand(messageqcpp::ByteStream &bs) void TupleConstantStep::execute() { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; try { more = fInputDL->next(fInputIterator, &rgDataIn); if (traceOn()) dlTimes.setFirstReadTime(); - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - if (!more && cancelled()) + if (!more && (0 < fInputJobStepAssociation.status() || die)) { fEndOfResult = true; } while (more && !fEndOfResult) { - fRowGroupIn.setData(&rgDataIn); - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); + fRowGroupIn.setData(rgDataIn.get()); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); + fRowGroupOut.setData(rgDataOut.get()); fillInConstants(); more = fInputDL->next(fInputIterator, &rgDataIn); - if (cancelled()) + if (0 < fInputJobStepAssociation.status() || die) { fEndOfResult = true; } @@ -418,23 +408,21 @@ void TupleConstantStep::execute() } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleConstantStepErr, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); } catch(...) { - catchHandler("TupleConstantStep execute caught an unknown exception", - tupleConstantStepErr, fErrorInfo, fSessionId); + catchHandler("TupleConstantStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); } // if (!fEndOfResult) while (more) more = fInputDL->next(fInputIterator, &rgDataIn); - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - // Bug 3136, let mini stats to be formatted if traceOn. if (traceOn()) { @@ -457,11 +445,11 @@ void TupleConstantStep::fillInConstants() { for (uint64_t i = 0; i < fRowGroupIn.getRowCount(); ++i) { - copyRow(fRowConst, &fRowOut); + memcpy(fRowOut.getData(), fRowConst.getData(), fRowConst.getSize()); - fRowOut.setRid(fRowIn.getRelRid()); + fRowOut.setRid(fRowIn.getRid()); for (uint64_t j = 0; j < fIndexMapping.size(); ++j) - fRowIn.copyField(fRowOut, fIndexMapping[j], j); + fRowIn.copyField(fRowOut.getData() + fRowOut.getOffset(fIndexMapping[j]), j); fRowIn.nextRow(); fRowOut.nextRow(); @@ -469,13 +457,12 @@ void TupleConstantStep::fillInConstants() } else // only first column is constant { - //size_t n = fRowOut.getOffset(fRowOut.getColumnCount()) - fRowOut.getOffset(1); + size_t n = fRowOut.getOffset(fRowOut.getColumnCount()) - fRowOut.getOffset(1); for (uint64_t i = 0; i < fRowGroupIn.getRowCount(); ++i) { - fRowOut.setRid(fRowIn.getRelRid()); - fRowConst.copyField(fRowOut, 0, 0); - for (uint32_t i = 1; i < fRowOut.getColumnCount(); i++) - fRowIn.copyField(fRowOut, i, i-1); + fRowOut.setRid(fRowIn.getRid()); + fRowConst.copyField(fRowOut.getData()+2, 0); // hardcoded 2 for rid length + memcpy(fRowOut.getData()+fRowOut.getOffset(1), fRowIn.getData()+2, n); fRowIn.nextRow(); fRowOut.nextRow(); @@ -492,22 +479,17 @@ void TupleConstantStep::fillInConstants(const rowgroup::Row& rowIn, rowgroup::Ro { if (fIndexConst.size() > 1 || fIndexConst[0] != 0) { - copyRow(fRowConst, &rowOut); - //memcpy(rowOut.getData(), fRowConst.getData(), fRowConst.getSize()); - rowOut.setRid(rowIn.getRelRid()); + memcpy(rowOut.getData(), fRowConst.getData(), fRowConst.getSize()); + rowOut.setRid(rowIn.getRid()); for (uint64_t j = 0; j < fIndexMapping.size(); ++j) - rowIn.copyField(rowOut, fIndexMapping[j], j); - //rowIn.copyField(rowOut.getData() + rowOut.getOffset(fIndexMapping[j]), j); + rowIn.copyField(rowOut.getData() + rowOut.getOffset(fIndexMapping[j]), j); } else // only first column is constant { - //size_t n = rowOut.getOffset(rowOut.getColumnCount()) - rowOut.getOffset(1); - rowOut.setRid(rowIn.getRelRid()); - fRowConst.copyField(rowOut, 0, 0); - //fRowConst.copyField(rowOut.getData()+2, 0); // hardcoded 2 for rid length - for (uint32_t i = 1; i < rowOut.getColumnCount(); i++) - rowIn.copyField(rowOut, i, i-1); - //memcpy(rowOut.getData()+rowOut.getOffset(1), rowIn.getData()+2, n); + size_t n = rowOut.getOffset(rowOut.getColumnCount()) - rowOut.getOffset(1); + rowOut.setRid(rowIn.getRid()); + fRowConst.copyField(rowOut.getData()+2, 0); // hardcoded 2 for rid length + memcpy(rowOut.getData()+rowOut.getOffset(1), rowIn.getData()+2, n); } } @@ -524,18 +506,6 @@ const RowGroup& TupleConstantStep::getDeliveredRowGroup() const } -void TupleConstantStep::deliverStringTableRowGroup(bool b) -{ - fRowGroupOut.setUseStringTable(b); -} - - -bool TupleConstantStep::deliverStringTableRowGroup() const -{ - return fRowGroupOut.usesStringTable(); -} - - const string TupleConstantStep::toString() const { ostringstream oss; @@ -567,8 +537,7 @@ void TupleConstantStep::printCalTrace() << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); @@ -593,7 +562,18 @@ void TupleConstantStep::formatMiniStats() // class TupleConstantOnlyStep -TupleConstantOnlyStep::TupleConstantOnlyStep(const JobInfo& jobInfo) : TupleConstantStep(jobInfo) +TupleConstantOnlyStep::TupleConstantOnlyStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId) : TupleConstantStep(inputJobStepAssociation, + outputJobStepAssociation, + sessionId, + txnId, + verId, + statementId) { // fExtendedInfo = "TCOS: "; } @@ -606,12 +586,12 @@ TupleConstantOnlyStep::~TupleConstantOnlyStep() void TupleConstantOnlyStep::initialize(const RowGroup& rgIn, const JobInfo& jobInfo) { - vector oids; - vector keys; - vector scale; - vector precision; + vector oids; + vector keys; + vector scale; + vector precision; vector types; - vector pos; + vector pos; pos.push_back(2); for (uint64_t i = 0; i < jobInfo.deliveredCols.size(); i++) @@ -620,7 +600,7 @@ void TupleConstantOnlyStep::initialize(const RowGroup& rgIn, const JobInfo& jobI dynamic_cast(jobInfo.deliveredCols[i].get()); if (cc == NULL) throw runtime_error("none constant column found."); - + CalpontSystemCatalog::ColType ct = cc->resultType(); if (ct.colDataType == CalpontSystemCatalog::VARCHAR) ct.colWidth++; @@ -641,9 +621,9 @@ void TupleConstantOnlyStep::initialize(const RowGroup& rgIn, const JobInfo& jobI fIndexConst.push_back(i); } - fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision); fRowGroupOut.initRow(&fRowOut); - fRowGroupOut.initRow(&fRowConst, true); + fRowGroupOut.initRow(&fRowConst); constructContanstRow(jobInfo); } @@ -662,8 +642,9 @@ void TupleConstantOnlyStep::run() try { - RGData rgDataOut(fRowGroupOut, 1); - fRowGroupOut.setData(&rgDataOut); + shared_array rgDataOut; + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(1)]); + fRowGroupOut.setData(rgDataOut.get()); if (traceOn()) dlTimes.setFirstReadTime(); fillInConstants(); @@ -672,8 +653,9 @@ void TupleConstantOnlyStep::run() } catch(...) { - catchHandler("TupleConstantOnlyStep run caught an unknown exception", - tupleConstantStepErr, fErrorInfo, fSessionId); + catchHandler("TupleConstantOnlyStep run caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); } if (traceOn()) @@ -690,10 +672,10 @@ void TupleConstantOnlyStep::run() } -uint32_t TupleConstantOnlyStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleConstantOnlyStep::nextBand(messageqcpp::ByteStream &bs) { - RGData rgDataOut; - uint32_t rowCount = 0; + shared_array rgDataOut; + uint rowCount = 0; if (!fEndOfResult) { @@ -704,21 +686,24 @@ uint32_t TupleConstantOnlyStep::nextBand(messageqcpp::ByteStream &bs) if (traceOn() && dlTimes.FirstReadTime().tv_sec == 0) dlTimes.setFirstReadTime(); - rgDataOut.reinit(fRowGroupOut, 1); - fRowGroupOut.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(1)]); + fRowGroupOut.setData(rgDataOut.get()); fillInConstants(); - fRowGroupOut.serializeRGData(bs); + bs.load(fRowGroupOut.getData(), fRowGroupOut.getDataSize()); rowCount = fRowGroupOut.getRowCount(); } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleConstantStepErr, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); } catch(...) { - catchHandler("TupleConstantStep next band caught an unknown exception", - tupleConstantStepErr, fErrorInfo, fSessionId); + catchHandler("TupleConstantStep next band caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleConstantStepErr); } fEndOfResult = true; @@ -726,11 +711,11 @@ uint32_t TupleConstantOnlyStep::nextBand(messageqcpp::ByteStream &bs) else { // send an empty / error band - RGData rgData(fRowGroupOut, 0); - fRowGroupOut.setData(&rgData); + shared_array rgData(new uint8_t[fRowGroupOut.getEmptySize()]); + fRowGroupOut.setData(rgData.get()); fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setStatus(status()); - fRowGroupOut.serializeRGData(bs); + fRowGroupOut.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgData.get(), fRowGroupOut.getDataSize()); if (traceOn()) { @@ -747,8 +732,7 @@ uint32_t TupleConstantOnlyStep::nextBand(messageqcpp::ByteStream &bs) void TupleConstantOnlyStep::fillInConstants() { fRowGroupOut.getRow(0, &fRowOut); - idbassert(fRowConst.getColumnCount() == fRowOut.getColumnCount()); - copyRow(fRowConst, &fRowOut); + memcpy(fRowOut.getData(), fRowConst.getData(), fRowConst.getSize()); fRowGroupOut.resetRowGroup(0); fRowGroupOut.setRowCount(1); fRowsReturned = 1; @@ -771,9 +755,20 @@ const string TupleConstantOnlyStep::toString() const // class TupleConstantBooleanStep -TupleConstantBooleanStep::TupleConstantBooleanStep(const JobInfo& jobInfo, bool value) : - TupleConstantStep(jobInfo), - fValue(value) +TupleConstantBooleanStep::TupleConstantBooleanStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId, + bool value) : TupleConstantStep(inputJobStepAssociation, + outputJobStepAssociation, + sessionId, + txnId, + verId, + statementId), + fValue(value) { // fExtendedInfo = "TCBS: "; } @@ -788,7 +783,7 @@ void TupleConstantBooleanStep::initialize(const RowGroup& rgIn, const JobInfo&) { fRowGroupOut = rgIn; fRowGroupOut.initRow(&fRowOut); - fRowGroupOut.initRow(&fRowConst, true); + fRowGroupOut.initRow(&fRowConst); } @@ -817,14 +812,14 @@ void TupleConstantBooleanStep::run() } -uint32_t TupleConstantBooleanStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleConstantBooleanStep::nextBand(messageqcpp::ByteStream &bs) { // send an empty band - RGData rgData(fRowGroupOut, 0); - fRowGroupOut.setData(&rgData); + shared_array rgData(new uint8_t[fRowGroupOut.getEmptySize()]); + fRowGroupOut.setData(rgData.get()); fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setStatus(status()); - fRowGroupOut.serializeRGData(bs); + fRowGroupOut.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgData.get(), fRowGroupOut.getDataSize()); if (traceOn()) { diff --git a/dbcon/joblist/tupleconstantstep.h b/dbcon/joblist/tupleconstantstep.h index 34875228..9b4b29c6 100644 --- a/dbcon/joblist/tupleconstantstep.h +++ b/dbcon/joblist/tupleconstantstep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tupleconstantstep.h 9596 2013-06-04 19:59:04Z xlou $ +// $Id: tupleconstantstep.h 8436 2012-04-04 18:18:21Z rdempsey $ #ifndef JOBLIST_TUPLECONSTANTSTEP_H @@ -33,8 +33,16 @@ class TupleConstantStep : public JobStep, public TupleDeliveryStep { public: /** @brief TupleConstantStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer */ - TupleConstantStep(const JobInfo& jobInfo); + TupleConstantStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId); /** @brief TupleConstantStep destructor */ @@ -43,21 +51,48 @@ class TupleConstantStep : public JobStep, public TupleDeliveryStep /** @brief virtual void Run method */ void run(); - - /** @brief virtual void join method - */ void join(); - /** @brief virtual string toString method + /** @brief virtual JobStepAssociation * inputAssociation + * + * @returns JobStepAssociation * */ + const JobStepAssociation& inputAssociation() const + { + return fInputJobStepAssociation; + } + void inputAssociation(const JobStepAssociation& inputAssociation) + { + fInputJobStepAssociation = inputAssociation; + } + /** @brief virtual JobStepAssociation * outputAssociation + * + * @returns JobStepAssocation * + */ + const JobStepAssociation& outputAssociation() const + { + return fOutputJobStepAssociation; + } + void outputAssociation(const JobStepAssociation& outputAssociation) + { + fOutputJobStepAssociation = outputAssociation; + } + + void stepId(uint16_t stepId) { fStepId = stepId; } + uint16_t stepId() const { return fStepId; } + uint32_t sessionId() const { return fSessionId; } + uint32_t txnId() const { return fTxnId; } + uint32_t verId() const { return fVerId; } + uint32_t statementId() const { return fStatementId; } + const std::string toString() const; void setOutputRowGroup(const rowgroup::RowGroup&); const rowgroup::RowGroup& getOutputRowGroup() const; const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); + void logger(const SPJL& logger) { fLogger = logger; } + void setIsDelivery(bool b) { fDelivery = b; } virtual void initialize(const JobInfo& jobInfo, const rowgroup::RowGroup* rgIn); virtual void fillInConstants(const rowgroup::Row& rowIn, rowgroup::Row& rowOut); @@ -71,7 +106,15 @@ class TupleConstantStep : public JobStep, public TupleDeliveryStep virtual void constructContanstRow(const JobInfo& jobInfo); // for base + JobStepAssociation fInputJobStepAssociation; + JobStepAssociation fOutputJobStepAssociation; + uint32_t fSessionId; + uint32_t fTxnId; + uint32_t fVerId; + uint16_t fStepId; + uint32_t fStatementId; uint64_t fRowsReturned; + SPJL fLogger; // input/output rowgroup and row rowgroup::RowGroup fRowGroupIn; @@ -103,6 +146,7 @@ class TupleConstantStep : public JobStep, public TupleDeliveryStep boost::scoped_ptr fRunner; bool fEndOfResult; + bool fDelivery; }; @@ -110,8 +154,16 @@ class TupleConstantOnlyStep : public TupleConstantStep { public: /** @brief TupleConstantOnlyStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer */ - TupleConstantOnlyStep(const JobInfo& jobInfo); + TupleConstantOnlyStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId); /** @brief TupleConstantOnlyStep destructor */ @@ -126,7 +178,7 @@ class TupleConstantOnlyStep : public TupleConstantStep void initialize(const rowgroup::RowGroup& rgIn, const JobInfo& jobInfo); const std::string toString() const; - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); protected: void fillInConstants(); @@ -138,8 +190,17 @@ class TupleConstantBooleanStep : public TupleConstantStep { public: /** @brief TupleConstantBooleanStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer */ - TupleConstantBooleanStep(const JobInfo& jobInfo, bool value); + TupleConstantBooleanStep( + const JobStepAssociation& inputJobStepAssociation, + const JobStepAssociation& outputJobStepAssociation, + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId, + bool value); /** @brief TupleConstantBooleanStep destructor */ @@ -154,7 +215,7 @@ class TupleConstantBooleanStep : public TupleConstantStep void initialize(const rowgroup::RowGroup& rgIn, const JobInfo& jobInfo); const std::string toString() const; - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); virtual void boolValue(bool b) { fValue = b; } virtual bool boolValue() const { return fValue; } diff --git a/dbcon/joblist/tuplehashjoin.cpp b/dbcon/joblist/tuplehashjoin.cpp index 38aab2eb..3ac0c762 100644 --- a/dbcon/joblist/tuplehashjoin.cpp +++ b/dbcon/joblist/tuplehashjoin.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tuplehashjoin.cpp 9709 2013-07-20 06:08:46Z xlou $ +// $Id: tuplehashjoin.cpp 9171 2012-12-20 18:28:58Z xlou $ #include @@ -34,7 +34,6 @@ #include using namespace std; -#include "jlf_common.h" #include "primitivestep.h" #include "tuplehashjoin.h" #include "calpontsystemcatalog.h" @@ -42,7 +41,6 @@ using namespace std; #include "resourcemanager.h" #include "tupleaggregatestep.h" #include "errorids.h" -#include "diskjoinstep.h" using namespace execplan; using namespace joiner; @@ -50,117 +48,130 @@ using namespace rowgroup; using namespace boost; using namespace funcexp; -#include "querytele.h" -using namespace querytele; - -#include "atomicops.h" +#if defined(_MSC_VER) && !defined(_WIN64) +# ifndef InterlockedAdd +# define InterlockedAdd64 InterlockedAdd +# define InterlockedAdd(x, y) ((x) + (y)) +# endif +#endif namespace joblist { - -TupleHashJoinStep::TupleHashJoinStep(const JobInfo& jobInfo) : - JobStep(jobInfo), - joinType(INIT), - fTableOID1(0), - fTableOID2(0), - fOid1(0), - fOid2(0), - fDictOid1(0), - fDictOid2(0), - fSequence1(-1), - fSequence2(-1), - fTupleId1(-1), - fTupleId2(-1), - fCorrelatedSide(0), - resourceManager(jobInfo.rm), - totalUMMemoryUsage(0), - rgDataSize(0), - runRan(false), - joinRan(false), - largeSideIndex(1), - joinIsTooBig(false), - isExeMgr(jobInfo.isExeMgr), - lastSmallOuterJoiner(-1), - fTokenJoin(-1), - fStatsMutexPtr(new boost::mutex()), - fFunctionJoinKeys(jobInfo.keyInfo->functionJoinKeys), - sessionMemLimit(jobInfo.umMemLimit) + +TupleHashJoinStep::TupleHashJoinStep(uint32_t ses, uint32_t stmt, uint32_t txn, ResourceManager *rm, + bool exemgr) + : joinType(INIT), sessionID(ses), statementID(stmt), txnID(txn), fTableOID1(0), fTableOID2(0), + fOid1(0), fOid2(0), fDictOid1(0), fDictOid2(0), fSequence1(-1), fSequence2(-1), + fTupleId1(-1), fTupleId2(-1), fCorrelatedSide(0), resourceManager(rm), totalUMMemoryUsage(0), + isDelivery(false), runRan(false), joinRan(false), largeSideIndex(1), joinIsTooBig(false), + isExeMgr(exemgr), lastSmallOuterJoiner(-1) { /* Need to figure out how much memory these use... Overhead storing 16 byte elements is about 32 bytes. That should stay the same for other element sizes. */ - pmMemLimit = resourceManager.getHjPmMaxMemorySmallSide(fSessionId); - uniqueLimit = resourceManager.getHjCPUniqueLimit(); + // PM stores uint32's unless there's PM aggregation or F & E cross-table processing + // @bug 3088 + //uint64_t PMSmallSide = resourceManager->getPMJoinMemLimit(); + uint64_t PMSmallSide = resourceManager->getHjPmMaxMemorySmallSide(sessionID); + PMRowLimit = PMSmallSide/44; // 32 + 8 (key) + 4 (value) + totalUMMemoryUsage = 0; + uniqueLimit = resourceManager->getHjCPUniqueLimit(); + fStatsMutexPtr = new boost::mutex(); fExtendedInfo = "THJS: "; joinType = INIT; - joinThreadCount = resourceManager.getJlNumScanReceiveThreads(); + stepID = 0; + joinThreadCount = resourceManager->getJlNumScanReceiveThreads(); largeBPS = NULL; moreInput = true; - fQtc.stepParms().stepType = StepTeleStats::T_HJS; - outputDL = NULL; - ownsOutputDL = false; - djsSmallUsage = jobInfo.smallSideUsage; - djsSmallLimit = jobInfo.smallSideLimit; - djsLargeLimit = jobInfo.largeSideLimit; - djsPartitionSize = jobInfo.partitionSize; - isDML = jobInfo.isDML; - - config::Config *config = config::Config::makeConfig(); - string str = config->getConfig("HashJoin", "AllowDiskBasedJoin"); - if (str.empty() || str == "y" || str == "Y") - allowDJS = true; - else - allowDJS = false; - - /* Debugging, rand() is used to simulate failures - time_t t = time(NULL); - srand(t); - */ - } TupleHashJoinStep::~TupleHashJoinStep() { delete fStatsMutexPtr; - if (ownsOutputDL) + if (!largeBPS && isDelivery) delete outputDL; if (totalUMMemoryUsage != 0) - resourceManager.returnMemory(totalUMMemoryUsage, sessionMemLimit); - //cout << "deallocated THJS, UM memory available: " << resourceManager.availableMemory() << endl; + resourceManager->returnMemory(totalUMMemoryUsage); + //cout << "deallocated THJS, UM memory available: " << resourceManager->availableMemory() << endl; +} + +const JobStepAssociation & TupleHashJoinStep::inputAssociation() const +{ + return inJSA; +} + +void TupleHashJoinStep::inputAssociation(const JobStepAssociation &in) +{ + inJSA = in; +} + +const JobStepAssociation & TupleHashJoinStep::outputAssociation() const +{ + return outJSA; +} + +void TupleHashJoinStep::outputAssociation(const JobStepAssociation &out) +{ + outJSA = out; +} + +void TupleHashJoinStep::logger(const SPJL &logger) +{ + fLogger = logger; +} + +void TupleHashJoinStep::stepId(uint16_t id) +{ + stepID = id; +} + +uint16_t TupleHashJoinStep::stepId() const +{ + return stepID; +} + +uint32_t TupleHashJoinStep::sessionId() const +{ + return sessionID; +} + +uint32_t TupleHashJoinStep::statementId() const +{ + return statementID; +} + +uint32_t TupleHashJoinStep::txnId() const +{ + return txnID; } void TupleHashJoinStep::run() { - uint32_t i; + uint i; mutex::scoped_lock lk(jlLock); if (runRan) return; runRan = true; - deliverMutex.lock(); - -// cout << "TupleHashJoinStep::run(): fOutputJobStepAssociation.outSize = " << fOutputJobStepAssociation.outSize() << ", fDelivery = " << boolalpha << fDelivery << endl; - idbassert((fOutputJobStepAssociation.outSize() == 1 && !fDelivery) || - (fOutputJobStepAssociation.outSize() == 0 && fDelivery)); - idbassert(fInputJobStepAssociation.outSize() >= 2); - - largeDL = fInputJobStepAssociation.outAt(largeSideIndex)->rowGroupDL(); +// cout << "TupleHashJoinStep::run(): outJSA.outSize = " << outJSA.outSize() << ", isDelivery = " << boolalpha << isDelivery << endl; + idbassert((outJSA.outSize() == 1 && !isDelivery) || (outJSA.outSize() == 0 && isDelivery)); + idbassert(inJSA.outSize() >= 2); + + largeDL = inJSA.outAt(largeSideIndex)->rowGroupDL(); largeIt = largeDL->getIterator(); - for (i = 0; i < fInputJobStepAssociation.outSize(); i++) { + for (i = 0; i < inJSA.outSize(); i++) { if (i != largeSideIndex) { - smallDLs.push_back(fInputJobStepAssociation.outAt(i)->rowGroupDL()); + smallDLs.push_back(inJSA.outAt(i)->rowGroupDL()); smallIts.push_back(smallDLs.back()->getIterator()); } } - - if (!fDelivery) - outputDL = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); + if (!isDelivery) + outputDL = outJSA.outAt(0)->rowGroupDL(); else if (!largeBPS) { - ownsOutputDL = true; outputDL = new RowGroupDL(1, 5); outputIt = outputDL->getIterator(); } @@ -176,37 +187,33 @@ void TupleHashJoinStep::join() return; joinRan = true; mainRunner->join(); - if (djs) { - for (int i = 0; i < (int) djsJoiners.size(); i++) - djs[i].join(); - djsReader.join(); - djsRelay.join(); - //cout << "THJS: joined all DJS threads, shared usage = " << *djsSmallUsage << endl; - } + for (uint i = 0; i < smallRunners.size(); i++) + smallRunners[i]->join(); + smallRunners.clear(); } /* Index is which small input to read. */ -void TupleHashJoinStep::smallRunnerFcn(uint32_t index) +void TupleHashJoinStep::smallRunnerFcn(uint index) { - uint64_t i; + uint64_t i, smallSize, rowSize; bool more, flippedUMSwitch = false, gotMem; - RGData oneRG; - //shared_array oneRG; + shared_array oneRG; Row r; JoinType jt; + RowGroupDL *smallDL; - uint32_t smallIt; + uint smallIt; RowGroup smallRG; - boost::shared_ptr joiner; + shared_ptr joiner; string extendedInfo; - extendedInfo += toString(); // is each small side supposed to have the whole THJS info? - + extendedInfo += toString(); + smallDL = smallDLs[index]; smallIt = smallIts[index]; smallRG = smallRGs[index]; jt = joinTypes[index]; - + //cout << " smallRunner " << index << " sees jointype " << jt << " joinTypes has " << joinTypes.size() // << " elements" << endl; if (typelessJoin[index]) { @@ -221,6 +228,8 @@ void TupleHashJoinStep::smallRunnerFcn(uint32_t index) joiner->setTableName(smallTableNames[index]); joiners[index] = joiner; + rowSize = smallRG.getRowSize(); + /* read the small side into a TupleJoiner send the TupleJoiner to the large side TBPS @@ -228,104 +237,80 @@ void TupleHashJoinStep::smallRunnerFcn(uint32_t index) read the large side, write to the output */ + smallSize = 0; smallRG.initRow(&r); // cout << "reading smallDL" << endl; more = smallDL->next(smallIt, &oneRG); ostringstream oss; - try - { - /* check for join types unsupported on the PM. */ - if (!largeBPS || !isExeMgr) { - flippedUMSwitch = true; - oss << "UM join (" << index << ")"; + + /* check for join types unsupported on the PM. */ + if (!largeBPS || !isExeMgr) { + flippedUMSwitch = true; + oss << "UM join (" << index << ")"; #ifdef JLF_DEBUG - cout << oss.str() << endl; + cout << oss.str() << endl; #endif - extendedInfo += oss.str(); - joiner->setInUM(); - } - - resourceManager.getMemory(joiner->getMemUsage(), sessionMemLimit, false); - (void)atomicops::atomicAdd(&totalUMMemoryUsage, joiner->getMemUsage()); - memUsedByEachJoin[index] += joiner->getMemUsage(); - - while (more && !cancelled()) { - uint64_t memUseBefore, memUseAfter; - - smallRG.setData(&oneRG); - if (smallRG.getRowCount() == 0) - goto next; + extendedInfo += oss.str(); + joiner->setInUM(); + } + + resourceManager->getMemory(joiner->getMemUsage()); +#ifdef _MSC_VER + InterlockedAdd64(&totalUMMemoryUsage, joiner->getMemUsage()); +#else + __sync_add_and_fetch(&totalUMMemoryUsage, joiner->getMemUsage()); +#endif + while (more && !die && inJSA.status() == 0) { + int64_t memUseBefore, memUseAfter; - smallRG.getRow(0, &r); + smallRG.setData(oneRG.get()); + // TupleHJ owns the row memory + if (smallRG.getRowCount() > 0) + rgData[index].push_back(oneRG); - memUseBefore = joiner->getMemUsage() + rgDataSize; + smallRG.getRow(0, &r); + smallSize += smallRG.getRowCount(); - // TupleHJ owns the row memory - rgData[index].push_back(oneRG); - rgDataSize += smallRG.getSizeWithStrings(); - for (i = 0; i < smallRG.getRowCount(); i++, r.nextRow()) { - //cout << "inserting " << r.toString() << endl; - joiner->insert(r); - } - memUseAfter = joiner->getMemUsage() + rgDataSize; + memUseBefore = joiner->getMemUsage(); + for (i = 0; i < smallRG.getRowCount(); i++, r.nextRow()) + joiner->insert(r); - if (UNLIKELY(!flippedUMSwitch && (memUseAfter >= pmMemLimit))) { - flippedUMSwitch = true; - oss << "UM join (" << index << ") "; + if (UNLIKELY(!flippedUMSwitch && (smallSize >= PMRowLimit))) { + flippedUMSwitch = true; + oss << "UM join (" << index << ") "; #ifdef JLF_DEBUG - cout << oss.str() << endl; + cout << oss.str() << endl; #endif - extendedInfo += oss.str(); - joiner->setInUM(); - memUseAfter = joiner->getMemUsage() + rgDataSize; - } - - gotMem = resourceManager.getMemory(memUseAfter - memUseBefore, sessionMemLimit, false); - atomicops::atomicAdd(&totalUMMemoryUsage, memUseAfter - memUseBefore); - memUsedByEachJoin[index] += memUseAfter - memUseBefore; - /* This is kind of kludgy and overlaps with segreateJoiners() atm. - If this join won't be converted to disk-based, this fcn needs to abort the same as - it did before. If it will be converted, it should just return. */ - if (UNLIKELY(!gotMem)) { - if (isDML || !allowDJS || (fSessionId & 0x80000000) || - (tableOid() < 3000 && tableOid() >= 1000)) { - joinIsTooBig = true; - fLogger->logMessage(logging::LOG_TYPE_INFO, logging::ERR_JOIN_TOO_BIG); - errorMessage(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_JOIN_TOO_BIG)); - status(logging::ERR_JOIN_TOO_BIG); - cout << "Join is too big, raise the UM join limit for now" << endl; - abort(); - break; - } - else - return; - } -next: -// cout << "inserted one rg into the joiner, rowcount = " << -// smallRG.getRowCount() << endl; - more = smallDL->next(smallIt, &oneRG); + extendedInfo += oss.str(); + joiner->setInUM(); } + memUseAfter = joiner->getMemUsage(); + + gotMem = resourceManager->getMemory(memUseAfter - memUseBefore); +#ifdef _MSC_VER + InterlockedAdd64(&totalUMMemoryUsage, memUseAfter - memUseBefore); +#else + __sync_add_and_fetch(&totalUMMemoryUsage, memUseAfter - memUseBefore); +#endif + if (UNLIKELY(!gotMem)) { + /* bail out until we get an LHJ impl */ + fLogger->logMessage(logging::LOG_TYPE_INFO, logging::ERR_JOIN_TOO_BIG); + inJSA.status(logging::ERR_JOIN_TOO_BIG); + inJSA.errorMessage(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_JOIN_TOO_BIG)); + die = true; + joinIsTooBig = true; + oss << "join too big "; + cout << oss.str() << endl; + extendedInfo += oss.str(); + break; + } + +// cout << "inserted one rg into the joiner, rowcount = " << +// smallRG.getRowCount() << endl; + more = smallDL->next(smallIt, &oneRG); } - catch (boost::exception& e) - { - ostringstream oss; - oss << "TupleHashJoinStep::smallRunnerFcn failed due to " << boost::diagnostic_information(e); - fLogger->logMessage(logging::LOG_TYPE_ERROR, oss.str()); - status(logging::ERR_EXEMGR_MALFUNCTION); - } - catch (std::exception& e) - { - ostringstream oss; - oss << "TupleHashJoinStep::smallRunnerFcn failed due to " << e.what(); - fLogger->logMessage(logging::LOG_TYPE_ERROR, oss.str()); - status(logging::ERR_EXEMGR_MALFUNCTION); - } - catch (...) - { - fLogger->logMessage(logging::LOG_TYPE_ERROR, "TupleHashJoinStep::smallRunnerFcn failed due to an unknown reason (...)"); - status(logging::ERR_EXEMGR_MALFUNCTION); - } - if (!flippedUMSwitch && !cancelled()) { + + if (!flippedUMSwitch && !die) { oss << "PM join (" << index << ")"; #ifdef JLF_DEBUG cout << oss.str() << endl; @@ -336,15 +321,18 @@ void TupleHashJoinStep::smallRunnerFcn(uint32_t index) /* If there was an error or an abort drain the input DL, do endOfInput on the output */ - if (cancelled()) { - cout << "HJ stopping... status is " << status() << endl; + if (die || inJSA.status() > 0) { + cout << "HJ stopping... status is " << inJSA.status() << endl; if (largeBPS) largeBPS->abort(); while (more) more = smallDL->next(smallIt, &oneRG); } - + joiner->doneInserting(); +#ifdef JLF_DEBUG + cout << "(step " << stepID << ") finished reading small side, inserted " << smallSize << " elements\n"; +#endif extendedInfo += "\n"; boost::mutex::scoped_lock lk(*fStatsMutexPtr); @@ -354,7 +342,7 @@ void TupleHashJoinStep::smallRunnerFcn(uint32_t index) void TupleHashJoinStep::forwardCPData() { - uint32_t i, col; + uint i, col; if (largeBPS == NULL) return; @@ -362,167 +350,31 @@ void TupleHashJoinStep::forwardCPData() for (i = 0; i < joiners.size(); i++) { if (joiners[i]->antiJoin() || joiners[i]->largeOuterJoin()) continue; - + for (col = 0; col < joiners[i]->getSmallKeyColumns().size(); col++) { if (smallRGs[i].isLongString(joiners[i]->getSmallKeyColumns()[col])) continue; - - // @bug3683, not to add CP predicates if large side is not simple column - if (fFunctionJoinKeys.find(largeRG.getKeys()[joiners[i]->getLargeKeyColumns()[col]]) != - fFunctionJoinKeys.end()) - continue; - largeBPS->addCPPredicates(largeRG.getOIDs()[joiners[i]->getLargeKeyColumns()[col]], joiners[i]->getCPData()[col], !joiners[i]->discreteCPValues()[col]); } } } -void TupleHashJoinStep::djsRelayFcn() -{ - /* - read from largeDL - map to largeRG + outputRG format - insert into fifos[0] - */ - - RowGroup djsInputRG = largeRG + outputRG; - RowGroup l_largeRG = (tbpsJoiners.empty() ? largeRG : largeRG + outputRG); - boost::shared_array relayMapping = makeMapping(l_largeRG, djsInputRG); - bool more; - RGData inData, outData; - Row l_largeRow, djsInputRow; - int i; - - l_largeRG.initRow(&l_largeRow); - djsInputRG.initRow(&djsInputRow); - - //cout << "Relay started" << endl; - - more = largeDL->next(largeIt, &inData); - while (more && !cancelled()) { - l_largeRG.setData(&inData); - //if (fSessionId < 0x80000000) - // cout << "got largeside data = " << l_largeRG.toString() << endl; - if (l_largeRG.getRowCount() == 0) - goto next; - outData.reinit(djsInputRG, l_largeRG.getRowCount()); - djsInputRG.setData(&outData); - djsInputRG.resetRowGroup(0); - l_largeRG.getRow(0, &l_largeRow); - djsInputRG.getRow(0, &djsInputRow); - for (i = 0; i < (int) l_largeRG.getRowCount(); i++, l_largeRow.nextRow(), djsInputRow.nextRow()) { - applyMapping(relayMapping, l_largeRow, &djsInputRow); - djsInputRG.incRowCount(); - } - fifos[0]->insert(outData); -next: - more = largeDL->next(largeIt, &inData); - } - - while (more) - more = largeDL->next(largeIt, &inData); - fifos[0]->endOfInput(); -} - -void TupleHashJoinStep::djsReaderFcn(int index) -{ - /* - read from fifos[index] - - incoming rgdata's have outputRG format - do FE2 processing - put into outputDL, to be picked up by the next JS or nextBand() - */ - - int it = fifos[index]->getIterator(); - bool more = true; - RowGroup l_outputRG = outputRG; - RGData rgData; - vector v_rgData; - - RowGroup l_fe2RG; - Row fe2InRow, fe2OutRow; - FuncExpWrapper l_fe; - - if (fe2) { - l_fe2RG = fe2Output; - l_outputRG.initRow(&fe2InRow); - l_fe2RG.initRow(&fe2OutRow); - l_fe = *fe2; - } - - makeDupList(fe2 ? l_fe2RG : l_outputRG); - - while (!cancelled()) { - more = fifos[index]->next(it, &rgData); - if (!more) - break; - l_outputRG.setData(&rgData); - if (l_outputRG.getRowCount() == 0) - continue; - - v_rgData.clear(); - v_rgData.push_back(rgData); - if (fe2) - processFE2(l_outputRG, l_fe2RG, fe2InRow, fe2OutRow, &v_rgData, &l_fe); - processDupList(0, (fe2 ? l_fe2RG : l_outputRG), &v_rgData); -#if 0 - if (!v_rgData.empty() && fSessionId < 0x80000000) { - if (fe2) { - l_fe2RG.setData(&v_rgData[0]); - cout << "fully processed rowgroup: " << l_fe2RG.toString() << endl; - } - else { - l_outputRG.setData(&v_rgData[0]); - cout << "fully processed rowgroup: " << l_outputRG.toString() << endl; - } - } - cout << "ownsOutputDL = " << (int) ownsOutputDL << " fDelivery = " << (int) fDelivery << endl; -#endif - sendResult(v_rgData); - } - while (more) - more = fifos[index]->next(it, &rgData); - - for (int i = 0; i < (int) djsJoiners.size(); i++) { - fExtendedInfo += djs[i].extendedInfo(); - fMiniInfo += djs[i].miniInfo(); - } - outputDL->endOfInput(); -} - void TupleHashJoinStep::hjRunner() { - uint32_t i; + uint i; - if (cancelled()) { - if (fOutputJobStepAssociation.outSize() > 0) - fOutputJobStepAssociation.outAt(0)->rowGroupDL()->endOfInput(); + if (inJSA.status() > 0) { + if (outJSA.outSize() > 0) + outJSA.outAt(0)->rowGroupDL()->endOfInput(); startAdjoiningSteps(); - deliverMutex.unlock(); return; } - StepTeleStats sts; - if (fTableOID1 >= 3000) - { - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.start_time = QueryTeleClient::timeNowms(); - sts.total_units_of_work = 1; - postStepStartTele(sts); - } - idbassert(joinTypes.size() == smallDLs.size()); - idbassert(joinTypes.size() == joiners.size()); - + /* Start the small-side runners */ - rgData.reset(new vector[smallDLs.size()]); - memUsedByEachJoin.reset(new uint64_t[smallDLs.size()]); - for (i = 0; i < smallDLs.size(); i++) - memUsedByEachJoin[i] = 0; - + rgData.reset(new vector >[smallDLs.size()]); try { /* Note: the only join that can have a useful small outer table is the last small outer, * the others get clobbered by the join after it. Turn off small outer for 'the others'. @@ -545,156 +397,38 @@ void TupleHashJoinStep::hjRunner() } for (i = 0; i < smallDLs.size(); i++) - smallRunners.push_back(boost::shared_ptr + smallRunners.push_back(shared_ptr (new boost::thread(SmallRunner(this, i)))); } catch (thread_resource_error&) { string emsg = "TupleHashJoin caught a thread resource error, aborting...\n"; - errorMessage("too many threads"); - status(logging::threadResourceErr); - errorLogging(emsg, logging::threadResourceErr); - fDie = true; - deliverMutex.unlock(); + inJSA.status(logging::threadResourceErr); + inJSA.errorMessage(emsg); + errorLogging(emsg); + die = true; } for (i = 0; i < smallRunners.size(); i++) smallRunners[i]->join(); smallRunners.clear(); - - for (i = 0; i < feIndexes.size() && joiners.size() > 0; i++) - joiners[feIndexes[i]]->setFcnExpFilter(fe[i]); - - /* segregate the Joiners into ones for TBPS and ones for DJS */ - segregateJoiners(); - - /* Need to clean this stuff up. If the query was cancelled before this, and this would have had - a disk join, it's still necessary to construct the DJS objects to finish the abort. */ - if (!djsJoiners.empty()) { - joinIsTooBig = false; - if (!cancelled()) - fLogger->logMessage(logging::LOG_TYPE_INFO, logging::INFO_SWITCHING_TO_DJS); - - uint32_t smallSideCount = djsJoiners.size(); - - if (!outputDL) { - ownsOutputDL = true; - outputDL = new RowGroupDL(1, 5); - outputIt = outputDL->getIterator(); - } - - djs.reset(new DiskJoinStep[smallSideCount]); - fifos.reset(new boost::shared_ptr[smallSideCount+1]); - - for (i = 0; i <= smallSideCount; i++) - fifos[i].reset(new RowGroupDL(1, 5)); - - boost::mutex::scoped_lock sl(djsLock); - for (i = 0; i < smallSideCount; i++) { - // these link themselves fifos[0]->DSJ[0]->fifos[1]->DSJ[1] ... ->fifos[smallSideCount], - // THJS puts data into fifos[0], reads it from fifos[smallSideCount] - djs[i] = DiskJoinStep(this, i, djsJoinerMap[i], (i == smallSideCount - 1)); - } - sl.unlock(); - - try { - for (i = 0; !cancelled() && i < smallSideCount; i++) { - vector empty; - resourceManager.returnMemory(memUsedByEachJoin[djsJoinerMap[i]], sessionMemLimit); - atomicops::atomicSub(&totalUMMemoryUsage, memUsedByEachJoin[djsJoinerMap[i]]); - djs[i].loadExistingData(rgData[djsJoinerMap[i]]); - rgData[djsJoinerMap[i]].swap(empty); - } - } - catch (logging::IDBExcept &e) { - cout << e.what() << endl; - if (!status()) { - errorMessage(logging::IDBErrorInfo::instance()->errorMsg(e.errorCode())); - status(e.errorCode()); - } - abort(); - } - catch (std::exception &e) { - cout << e.what() << endl; - if (!status()) { - errorMessage(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_DBJ_UNKNOWN_ERROR)); - status(logging::ERR_DBJ_UNKNOWN_ERROR); - } - abort(); - } - - if (fe2) - fe2Mapping = makeMapping(outputRG, fe2Output); - - bool relay = false, reader = false; - /* If an error happened loading the existing data, these threads are necessary - to finish the abort */ - try { - djsRelay = boost::thread(DJSRelay(this)); - relay = true; - djsReader = boost::thread(DJSReader(this, smallSideCount)); - reader = true; - for (i = 0; i < smallSideCount; i++) - djs[i].run(); - } - catch (thread_resource_error&) { - /* This means there is a gap somewhere in the chain, need to identify - where the gap is, drain the input, and close the output. */ - - string emsg = "TupleHashJoin caught a thread resource error, aborting...\n"; - errorMessage("too many threads"); - status(logging::threadResourceErr); - errorLogging(emsg, logging::threadResourceErr); - abort(); - if (reader && relay) { // must have been thrown from the djs::run() loop - // fill the gap in the chain: drain input of the failed DJS (i), close the last fifo - if (largeBPS) - largeDL->endOfInput(); - int it = fifos[i]->getIterator(); - RGData rg; - while (fifos[i]->next(it, &rg)); - fifos[smallSideCount]->endOfInput(); - } - else { // no DJS's have been started - if (relay) { - // drain Relay's output - if (largeBPS) - largeDL->endOfInput(); - int it = fifos[0]->getIterator(); - RGData rg; - while (fifos[0]->next(it, &rg)); - } - if (reader) - // close Reader's input - fifos[smallSideCount]->endOfInput(); - else // close the next JobStep's input - outputDL->endOfInput(); - } - } - } - - /* Final THJS configuration is settled here at the moment */ - deliverMutex.unlock(); - - if (cancelled()) { - if (joinIsTooBig && !status()) { - fLogger->logMessage(logging::LOG_TYPE_INFO, logging::ERR_JOIN_TOO_BIG); - errorMessage(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_JOIN_TOO_BIG)); - status(logging::ERR_JOIN_TOO_BIG); - cout << "Join is too big, raise the UM join limit for now" << endl; - /* Drop memory */ - if (!fDelivery) { - joiners.clear(); - tbpsJoiners.clear(); - rgData.reset(); - resourceManager.returnMemory(totalUMMemoryUsage, sessionMemLimit); - totalUMMemoryUsage = 0; - } - } + +// cout << "joined the small runners\n"; + + forwardCPData(); // this fcn has its own exclusion list + + if (die || inJSA.status() != 0) { + vector > empty_joiners; + if (joinIsTooBig) + cout << "Join is too big, raise the UM join limit for now\n"; + //minor optimization: clear out mem as soon as it's not necessary + rgData.reset(); + joiners.swap(empty_joiners); + resourceManager->returnMemory(totalUMMemoryUsage); + totalUMMemoryUsage = 0; } - // todo: forwardCPData needs to grab data from djs - if (!djs) - forwardCPData(); // this fcn has its own exclusion list + for (uint i = 0; i < feIndexes.size() && joiners.size() > 0; i++) + joiners[feIndexes[i]]->setFcnExpFilter(fe[i]); // decide if perform aggregation on PM if (dynamic_cast(fDeliveryStep.get()) != NULL && largeBPS) @@ -709,35 +443,30 @@ void TupleHashJoinStep::hjRunner() // can we sort the joiners? Currently they all have to be inner joins. // Note, any vars that used to parallel the joiners list will be invalidated // (ie. smallTableNames) - - for (i = 0; i < tbpsJoiners.size(); i++) - if (!tbpsJoiners[i]->innerJoin()) + for (i = 0; i < joiners.size(); i++) + if (!joiners[i]->innerJoin()) break; - if (i == tbpsJoiners.size()) - sort(tbpsJoiners.begin(), tbpsJoiners.end(), JoinerSorter()); - + if (i == joiners.size()) + sort(joiners.begin(), joiners.end(), JoinerSorter()); + /* Each thread independently decides whether a given join can execute on the PM. * A PM join can't follow a UM join, so we fix that here. */ bool doUM; - for (i = 0, doUM = false; i < tbpsJoiners.size(); i++) { - if (tbpsJoiners[i]->inUM()) + for (i = 0, doUM = false; i < joiners.size(); i++) { + if (joiners[i]->inUM()) doUM = true; - if (tbpsJoiners[i]->inPM() && doUM) { + if (joiners[i]->inPM() && doUM) { #ifdef JLF_DEBUG cout << "moving join " << i << " to UM (PM join can't follow a UM join)\n"; #endif - tbpsJoiners[i]->setInUM(); + joiners[i]->setInUM(); } } - // there is an in-mem UM or PM join - if (largeBPS && !tbpsJoiners.empty()) { - largeBPS->useJoiners(tbpsJoiners); - if (djs) - largeBPS->setJoinedResultRG(largeRG + outputRG); - else - largeBPS->setJoinedResultRG(outputRG); + if (largeBPS) { + largeBPS->useJoiners(joiners); + largeBPS->setJoinedResultRG(outputRG); if (!feIndexes.empty()) largeBPS->setJoinFERG(joinFilterRG); // cout << "join UM memory available is " << totalUMMemoryUsage << endl; @@ -747,12 +476,12 @@ void TupleHashJoinStep::hjRunner() For now, the alg is "assume if any joins are done on the UM, fe2 has to go on the UM." The structs and logic aren't in place yet to track all of the tables through a joblist. */ - if (fe2 && !djs) { + if (fe2) { /* Can't do a small outer join when the PM sends back joined rows */ runFE2onPM = true; if (joinTypes[joiners.size()-1] == SMALLOUTER) runFE2onPM = false; - + for (i = 0; i < joiners.size(); i++) if (joiners[i]->inUM()) { runFE2onPM = false; @@ -766,48 +495,30 @@ void TupleHashJoinStep::hjRunner() #endif largeBPS->setFcnExpGroup2(fe2, fe2Output, runFE2onPM); } - else if (fe2) - runFE2onPM = false; - if (!fDelivery && !djs) { + if (!isDelivery) { /* connect the largeBPS directly to the next step */ - JobStepAssociation newJsa; - newJsa.outAdd(fOutputJobStepAssociation.outAt(0)); + JobStepAssociation newJsa(inJSA.statusPtr()); + newJsa.outAdd(outJSA.outAt(0)); for (unsigned i = 1; i < largeBPS->outputAssociation().outSize(); i++) newJsa.outAdd(largeBPS->outputAssociation().outAt(i)); largeBPS->outputAssociation(newJsa); } startAdjoiningSteps(); } - else if (largeBPS) { - // there are no in-mem UM or PM joins, only disk-joins - startAdjoiningSteps(); - } - else if (!djs) - // if there's no largeBPS, all joins are either done by DJS or join threads, - // this clause starts the THJS join threads. + else startJoinThreads(); - - if (fTableOID1 >= 3000) - { - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.end_time = QueryTeleClient::timeNowms(); - sts.total_units_of_work = sts.units_of_work_completed = 1; - postStepSummaryTele(sts); - } } -uint32_t TupleHashJoinStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleHashJoinStep::nextBand(messageqcpp::ByteStream &bs) { - RGData oneRG; + shared_array oneRG; bool more; - uint32_t ret = 0; + uint ret = 0; RowGroupDL *dl; uint64_t it; - idbassert(fDelivery); - - boost::mutex::scoped_lock lk(deliverMutex); + idbassert(isDelivery); RowGroup* deliveredRG; if (fe2) @@ -815,7 +526,7 @@ uint32_t TupleHashJoinStep::nextBand(messageqcpp::ByteStream &bs) else deliveredRG = &outputRG; - if (largeBPS && !djs) { + if (largeBPS) { dl = largeDL; it = largeIt; } @@ -825,41 +536,42 @@ uint32_t TupleHashJoinStep::nextBand(messageqcpp::ByteStream &bs) } while (ret == 0) { - if (cancelled()) { - oneRG.reinit(*deliveredRG, 0); - deliveredRG->setData(&oneRG); + if (inJSA.status() > 0 || die) { + oneRG.reset(new uint8_t[deliveredRG->getEmptySize()]); + deliveredRG->setData(oneRG.get()); deliveredRG->resetRowGroup(0); - deliveredRG->setStatus(status()); - deliveredRG->serializeRGData(bs); + deliveredRG->setStatus(inJSA.status()); + bs.load(oneRG.get(), deliveredRG->getEmptySize()); + //cout << "got die. returning last band, error status " << inJSA.status() + // << endl; more = true; while (more) more = dl->next(it, &oneRG); joiners.clear(); rgData.reset(); - resourceManager.returnMemory(totalUMMemoryUsage, sessionMemLimit); + resourceManager->returnMemory(totalUMMemoryUsage); totalUMMemoryUsage = 0; return 0; } more = dl->next(it, &oneRG); if (!more) { joiners.clear(); - tbpsJoiners.clear(); rgData.reset(); - oneRG.reinit(*deliveredRG, 0); - deliveredRG->setData(&oneRG); + oneRG.reset(new uint8_t[deliveredRG->getEmptySize()]); + deliveredRG->setData(oneRG.get()); deliveredRG->resetRowGroup(0); - deliveredRG->setStatus(status()); - if (status() != 0) + deliveredRG->setStatus(inJSA.status()); + if (inJSA.status() != 0) cout << " -- returning error status " << deliveredRG->getStatus() << endl; - deliveredRG->serializeRGData(bs); - resourceManager.returnMemory(totalUMMemoryUsage, sessionMemLimit); + bs.load(oneRG.get(), deliveredRG->getEmptySize()); + resourceManager->returnMemory(totalUMMemoryUsage); totalUMMemoryUsage = 0; return 0; } - deliveredRG->setData(&oneRG); + deliveredRG->setData(oneRG.get()); ret = deliveredRG->getRowCount(); } - deliveredRG->serializeRGData(bs); + bs.load(deliveredRG->getData(), deliveredRG->getDataSize()); return ret; } @@ -878,30 +590,30 @@ void TupleHashJoinStep::startAdjoiningSteps() const string TupleHashJoinStep::toString() const { ostringstream oss; - size_t idlsz = fInputJobStepAssociation.outSize(); + size_t idlsz = inJSA.outSize(); idbassert(idlsz > 1); - oss << "TupleHashJoinStep ses:" << fSessionId << " st:" << fStepId; + oss << "TupleHashJoinStep ses:" << sessionID << " st:" << stepID; oss << omitOidInDL; for (size_t i = 0; i < idlsz; ++i) { - RowGroupDL *idl = fInputJobStepAssociation.outAt(i)->rowGroupDL(); + RowGroupDL *idl = inJSA.outAt(i)->rowGroupDL(); CalpontSystemCatalog::OID oidi = 0; if (idl) oidi = idl->OID(); oss << " in "; if (largeSideIndex == i) oss << "*"; oss << "tb/col:" << fTableOID1 << "/" << oidi; - oss << " " << fInputJobStepAssociation.outAt(i); + oss << " " << inJSA.outAt(i); } - idlsz = fOutputJobStepAssociation.outSize(); + idlsz = outJSA.outSize(); if (idlsz > 0) { oss << endl << " "; - RowGroupDL *dlo = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); + RowGroupDL *dlo = outJSA.outAt(0)->rowGroupDL(); CalpontSystemCatalog::OID oido = 0; if (dlo) oido = dlo->OID(); oss << " out tb/col:" << fTableOID1 << "/" << oido; - oss << " " << fOutputJobStepAssociation.outAt(0); + oss << " " << outJSA.outAt(0); } oss << endl; @@ -911,13 +623,12 @@ const string TupleHashJoinStep::toString() const //------------------------------------------------------------------------------ // Log specified error to stderr and the critical log //------------------------------------------------------------------------------ -void TupleHashJoinStep::errorLogging(const string& msg, int err) const +void TupleHashJoinStep::errorLogging(const string& msg) const { ostringstream errMsg; errMsg << "Step " << stepId() << "; " << msg; cerr << errMsg.str() << endl; - SErrorInfo errorInfo(new ErrorInfo); // dummy, error info already set by caller. - catchHandler(msg, err, errorInfo, fSessionId); + catchHandler( errMsg.str(), sessionId() ); } void TupleHashJoinStep::addSmallSideRG(const vector& rgs, @@ -929,15 +640,15 @@ void TupleHashJoinStep::addSmallSideRG(const vector& rgs, void TupleHashJoinStep::addJoinKeyIndex(const vector& jt, const vector& typeless, - const vector >& smallkey, - const vector >& largekey) + const vector >& smallkey, + const vector >& largekey) { joinTypes.insert(joinTypes.end(), jt.begin(), jt.end()); typelessJoin.insert(typelessJoin.end(), typeless.begin(), typeless.end()); smallSideKeys.insert(smallSideKeys.end(), smallkey.begin(), smallkey.end()); largeSideKeys.insert(largeSideKeys.end(), largekey.begin(), largekey.end()); #ifdef JLF_DEBUG - for (uint32_t i = 0; i < joinTypes.size(); i++) + for (uint i = 0; i < joinTypes.size(); i++) cout << "jointype[" << i << "] = 0x" << hex << joinTypes[i] << dec << endl; #endif } @@ -955,15 +666,15 @@ void TupleHashJoinStep::configLargeSideRG(const RowGroup &rg) void TupleHashJoinStep::configJoinKeyIndex(const vector& jt, const vector& typeless, - const vector >& smallkey, - const vector >& largekey) + const vector >& smallkey, + const vector >& largekey) { joinTypes.insert(joinTypes.begin(), jt.begin(), jt.end()); typelessJoin.insert(typelessJoin.begin(), typeless.begin(), typeless.end()); smallSideKeys.insert(smallSideKeys.begin(), smallkey.begin(), smallkey.end()); largeSideKeys.insert(largeSideKeys.begin(), largekey.begin(), largekey.end()); #ifdef JLF_DEBUG - for (uint32_t i = 0; i < joinTypes.size(); i++) + for (uint i = 0; i < joinTypes.size(); i++) cout << "jointype[" << i << "] = 0x" << hex << joinTypes[i] << dec << endl; #endif } @@ -973,29 +684,29 @@ void TupleHashJoinStep::setOutputRowGroup(const RowGroup &rg) outputRG = rg; } -execplan::CalpontSystemCatalog::OID TupleHashJoinStep::smallSideKeyOID(uint32_t s, uint32_t k) const +execplan::CalpontSystemCatalog::OID TupleHashJoinStep::smallSideKeyOID(uint s, uint k) const { return smallRGs[s].getOIDs()[smallSideKeys[s][k]]; } -execplan::CalpontSystemCatalog::OID TupleHashJoinStep::largeSideKeyOID(uint32_t s, uint32_t k) const +execplan::CalpontSystemCatalog::OID TupleHashJoinStep::largeSideKeyOID(uint s, uint k) const { return largeRG.getOIDs()[largeSideKeys[s][k]]; } -void TupleHashJoinStep::addFcnExpGroup2(const boost::shared_ptr& fe) +void TupleHashJoinStep::addFcnExpGroup2(const shared_ptr& fe) { if (!fe2) fe2.reset(new funcexp::FuncExpWrapper()); fe2->addFilter(fe); } -void TupleHashJoinStep::setFcnExpGroup3(const vector >& v) +void TupleHashJoinStep::setFcnExpGroup3(const vector >& v) { if (!fe2) fe2.reset(new funcexp::FuncExpWrapper()); - for (uint32_t i = 0; i < v.size(); i++) + for (uint i = 0; i < v.size(); i++) fe2->addReturnedColumn(v[i]); } @@ -1012,24 +723,8 @@ const rowgroup::RowGroup& TupleHashJoinStep::getDeliveredRowGroup() const return outputRG; } -void TupleHashJoinStep::deliverStringTableRowGroup(bool b) -{ - if (fe2) - fe2Output.setUseStringTable(b); - - outputRG.setUseStringTable(b); -} - -bool TupleHashJoinStep::deliverStringTableRowGroup() const -{ - if (fe2) - return fe2Output.usesStringTable(); - - return outputRG.usesStringTable(); -} - //Must hold the stats lock when calling this! -void TupleHashJoinStep::formatMiniStats(uint32_t index) +void TupleHashJoinStep::formatMiniStats(uint index) { ostringstream oss; oss << "HJS "; @@ -1054,31 +749,24 @@ void TupleHashJoinStep::formatMiniStats(uint32_t index) fMiniInfo += oss.str(); } -void TupleHashJoinStep::addJoinFilter(boost::shared_ptr pt, uint32_t index) +void TupleHashJoinStep::addJoinFilter(boost::shared_ptr pt, uint index) { - boost::shared_ptr newfe(new funcexp::FuncExpWrapper()); - + shared_ptr newfe(new funcexp::FuncExpWrapper()); + newfe->addFilter(pt); fe.push_back(newfe); feIndexes.push_back(index); } -bool TupleHashJoinStep::hasJoinFilter(uint32_t index) const +bool TupleHashJoinStep::hasJoinFilter(uint index) const { - for (uint32_t i = 0; i < feIndexes.size(); i++) + //FIXME: this assumes that index fits into signed space... + for (uint i = 0; i < feIndexes.size(); i++) if (feIndexes[i] == static_cast(index)) return true; return false; } -boost::shared_ptr TupleHashJoinStep::getJoinFilter(uint32_t index) const -{ - for (uint32_t i = 0; i < feIndexes.size(); i++) - if (feIndexes[i] == static_cast(index)) - return fe[i]; - return boost::shared_ptr(); -} - void TupleHashJoinStep::setJoinFilterInputRG(const rowgroup::RowGroup &rg) { joinFilterRG = rg; @@ -1086,16 +774,13 @@ void TupleHashJoinStep::setJoinFilterInputRG(const rowgroup::RowGroup &rg) void TupleHashJoinStep::startJoinThreads() { - uint32_t i; - uint32_t smallSideCount = smallDLs.size(); - bool more = true; - RGData oneRG; - - if (joinRunners) - return; + uint i; + uint smallSideCount = smallDLs.size(); + bool more = true; + shared_array oneRG; //@bug4836, in error case, stop process, and unblock the next step. - if (cancelled()) { + if (die || inJSA.status() != 0) { outputDL->endOfInput(); //@bug5785, memory leak on canceling complex queries while (more) @@ -1107,11 +792,11 @@ void TupleHashJoinStep::startJoinThreads() * * Get a list of small RGs consistent with the joiners. * Generate small & large mappings for joinFERG and outputRG. - * If fDelivery, create outputDL. + * If isDelivery, create outputDL. */ for (i = 0; i < smallSideCount; i++) smallRGs[i] = joiners[i]->getSmallRG(); - + columnMappings.reset(new shared_array[smallSideCount + 1]); for (i = 0; i < smallSideCount; i++) columnMappings[i] = makeMapping(smallRGs[i], outputRG); @@ -1123,26 +808,26 @@ void TupleHashJoinStep::startJoinThreads() fergMappings[i] = makeMapping(smallRGs[i], joinFilterRG); fergMappings[smallSideCount] = makeMapping(largeRG, joinFilterRG); } - + if (fe2) fe2Mapping = makeMapping(outputRG, fe2Output); smallNullMemory.reset(new scoped_array[smallSideCount]); for (i = 0; i < smallSideCount; i++) { Row smallRow; - smallRGs[i].initRow(&smallRow, true); - smallNullMemory[i].reset(new uint8_t[smallRow.getSize()]); + smallNullMemory[i].reset(new uint8_t[smallRGs[i].getRowSize()]); + smallRGs[i].initRow(&smallRow); smallRow.setData(smallNullMemory[i].get()); smallRow.initToNull(); } for (i = 0; i < smallSideCount; i++) joiners[i]->setThreadCount(joinThreadCount); - + makeDupList(fe2 ? fe2Output : outputRG); /* Start join runners */ - joinRunners.reset(new boost::shared_ptr[joinThreadCount]); + joinRunners.reset(new shared_ptr[joinThreadCount]); for (i = 0; i < joinThreadCount; i++) joinRunners[i].reset(new boost::thread(JoinRunner(this, i))); @@ -1150,7 +835,7 @@ void TupleHashJoinStep::startJoinThreads() for (i = 0; i < joinThreadCount; i++) joinRunners[i]->join(); - if (lastSmallOuterJoiner != (uint32_t) -1) + if (lastSmallOuterJoiner != (uint) -1) finishSmallOuterJoin(); outputDL->endOfInput(); @@ -1158,17 +843,15 @@ void TupleHashJoinStep::startJoinThreads() void TupleHashJoinStep::finishSmallOuterJoin() { - vector unmatched; - uint32_t smallSideCount = smallDLs.size(); - uint32_t i, j, k; - shared_array largeNullMemory; - RGData joinedData; + vector unmatched; + uint smallSideCount = smallDLs.size(); + uint i, j, k; + shared_array joinedData, largeNullMemory; Row joinedBaseRow, fe2InRow, fe2OutRow; shared_array smallRowTemplates; shared_array smallNullRows; Row largeNullRow; RowGroup l_outputRG = outputRG; - RowGroup l_fe2Output = fe2Output; joiners[lastSmallOuterJoiner]->getUnmarkedRows(&unmatched); if (unmatched.empty()) @@ -1178,16 +861,16 @@ void TupleHashJoinStep::finishSmallOuterJoin() smallNullRows.reset(new Row[smallSideCount]); for (i = 0; i < smallSideCount; i++) { smallRGs[i].initRow(&smallRowTemplates[i]); - smallRGs[i].initRow(&smallNullRows[i], true); + smallRGs[i].initRow(&smallNullRows[i]); smallNullRows[i].setData(smallNullMemory[i].get()); } - largeRG.initRow(&largeNullRow, true); + largeRG.initRow(&largeNullRow); largeNullMemory.reset(new uint8_t[largeNullRow.getSize()]); largeNullRow.setData(largeNullMemory.get()); largeNullRow.initToNull(); - - joinedData.reinit(l_outputRG); - l_outputRG.setData(&joinedData); + + joinedData.reset(new uint8_t[l_outputRG.getMaxDataSize()]); + l_outputRG.setData(joinedData.get()); l_outputRG.resetRowGroup(0); l_outputRG.initRow(&joinedBaseRow); l_outputRG.getRow(0, &joinedBaseRow); @@ -1196,7 +879,7 @@ void TupleHashJoinStep::finishSmallOuterJoin() fe2Output.initRow(&fe2OutRow); } for (j = 0; j < unmatched.size(); j++) { - smallRowTemplates[lastSmallOuterJoiner].setPointer(unmatched[j]); + smallRowTemplates[lastSmallOuterJoiner].setData(unmatched[j]); for (k = 0; k < smallSideCount; k++) { if (k == lastSmallOuterJoiner) applyMapping(columnMappings[lastSmallOuterJoiner], smallRowTemplates[lastSmallOuterJoiner], &joinedBaseRow); @@ -1209,48 +892,46 @@ void TupleHashJoinStep::finishSmallOuterJoin() l_outputRG.incRowCount(); if (l_outputRG.getRowCount() == 8192) { if (fe2) { - vector rgDatav; + vector > rgDatav; rgDatav.push_back(joinedData); - processFE2(l_outputRG, l_fe2Output, fe2InRow, fe2OutRow, &rgDatav, fe2.get()); + processFE2(l_outputRG, fe2Output, fe2InRow, fe2OutRow, &rgDatav, fe2.get()); outputDL->insert(rgDatav[0]); } - else { + else outputDL->insert(joinedData); - } - joinedData.reinit(l_outputRG); - l_outputRG.setData(&joinedData); + joinedData.reset(new uint8_t[l_outputRG.getMaxDataSize()]); + l_outputRG.setData(joinedData.get()); l_outputRG.resetRowGroup(0); l_outputRG.getRow(0, &joinedBaseRow); } } if (l_outputRG.getRowCount() > 0) { if (fe2) { - vector rgDatav; + vector > rgDatav; rgDatav.push_back(joinedData); - processFE2(l_outputRG, l_fe2Output, fe2InRow, fe2OutRow, &rgDatav, fe2.get()); + processFE2(l_outputRG, fe2Output, fe2InRow, fe2OutRow, &rgDatav, fe2.get()); outputDL->insert(rgDatav[0]); } - else { + else outputDL->insert(joinedData); - } } } -void TupleHashJoinStep::joinRunnerFcn(uint32_t threadID) +void TupleHashJoinStep::joinRunnerFcn(uint threadID) { RowGroup local_inputRG, local_outputRG, local_joinFERG; - uint32_t smallSideCount = smallDLs.size(); - vector inputData, joinedRowData; + uint smallSideCount = smallDLs.size(); + vector > inputData, joinedRowData; bool hasJoinFE = !fe.empty(); - uint32_t i; - + uint i; + /* thread-local scratch space for join processing */ shared_array joinFERowData; Row largeRow, joinFERow, joinedRow, baseRow; shared_array baseRowData; - vector > joinMatches; + vector > joinMatches; shared_array smallRowTemplates; - + /* F & E vars */ FuncExpWrapper local_fe; RowGroup local_fe2RG; @@ -1261,17 +942,17 @@ void TupleHashJoinStep::joinRunnerFcn(uint32_t threadID) local_outputRG = outputRG; local_inputRG.initRow(&largeRow); local_outputRG.initRow(&joinedRow); - local_outputRG.initRow(&baseRow, true); + local_outputRG.initRow(&baseRow); baseRowData.reset(new uint8_t[baseRow.getSize()]); baseRow.setData(baseRowData.get()); if (hasJoinFE) { local_joinFERG = joinFilterRG; - local_joinFERG.initRow(&joinFERow, true); + local_joinFERG.initRow(&joinFERow); joinFERowData.reset(new uint8_t[joinFERow.getSize()]); joinFERow.setData(joinFERowData.get()); } - + if (fe2) { local_fe2RG = fe2Output; local_outputRG.initRow(&fe2InRow); @@ -1284,9 +965,9 @@ void TupleHashJoinStep::joinRunnerFcn(uint32_t threadID) smallRGs[i].initRow(&smallRowTemplates[i]); grabSomeWork(&inputData); - while (!inputData.empty() && !cancelled()) { - for (i = 0; i < inputData.size() && !cancelled(); i++) { - local_inputRG.setData(&inputData[i]); + while (!inputData.empty() && !die) { + for (i = 0; i < inputData.size() && !die; i++) { + local_inputRG.setData(inputData[i].get()); if (local_inputRG.getRowCount() == 0) continue; @@ -1300,35 +981,34 @@ void TupleHashJoinStep::joinRunnerFcn(uint32_t threadID) joinedRowData.clear(); grabSomeWork(&inputData); } - while (!inputData.empty()) grabSomeWork(&inputData); } void TupleHashJoinStep::makeDupList(const RowGroup &rg) { - uint32_t i, j, cols = rg.getColumnCount(); - + uint i, j, cols = rg.getColumnCount(); + for (i = 0; i < cols; i++) for (j = i + 1; j < cols; j++) if (rg.getKeys()[i] == rg.getKeys()[j]) dupList.push_back(make_pair(j, i)); - + dupRows.reset(new Row[joinThreadCount]); for (i = 0; i < joinThreadCount; i++) rg.initRow(&dupRows[i]); } -void TupleHashJoinStep::processDupList(uint32_t threadID, RowGroup &rg, - vector *rowData) +void TupleHashJoinStep::processDupList(uint threadID, RowGroup &rg, + vector > *rowData) { - uint32_t i, j, k; - + uint i, j, k; + if (dupList.empty()) return; - + for (i = 0; i < rowData->size(); i++) { - rg.setData(&(*rowData)[i]); + rg.setData((*rowData)[i].get()); rg.getRow(0, &dupRows[threadID]); for (j = 0; j < rg.getRowCount(); j++, dupRows[threadID].nextRow()) for (k = 0; k < dupList.size(); k++) @@ -1337,20 +1017,34 @@ void TupleHashJoinStep::processDupList(uint32_t threadID, RowGroup &rg, } void TupleHashJoinStep::processFE2(RowGroup &input, RowGroup &output, Row &inRow, Row &outRow, - vector *rgData, funcexp::FuncExpWrapper* local_fe) + vector > *rgData, funcexp::FuncExpWrapper* local_fe) { - vector results; - RGData result; - uint32_t i, j; + vector > results; + shared_array result; + uint i, j; bool ret; - result.reinit(output); - output.setData(&result); + result.reset(new uint8_t[output.getMaxDataSize()]); + +/* Another case where it seems there is an unused column in the RowGroup; + valgrind complains that it doesn't get initialized before it's sent + over the network for this query against tpch 1G + +select sub1.c1 s1c1, sub2.c1 s2c1, sub3.c1 s3c1 from sub1 left join sub2 + on sub1.c1 = sub2.c1 left join sub3 on sub2.c1 = sub3.c1 where sub3.c1 + is null order by 1, 2, 3; + + Minor optimization opportunity. */ +#ifdef VALGRIND + memset(result.get(), 0, output.getMaxDataSize()); +#endif + + output.setData(result.get()); output.resetRowGroup(0); output.getRow(0, &outRow); for (i = 0; i < rgData->size(); i++) { - input.setData(&(*rgData)[i]); + input.setData((*rgData)[i].get()); if (output.getRowCount() == 0) { output.resetRowGroup(input.getBaseRid()); output.setDBRoot(input.getDBRoot()); @@ -1364,8 +1058,8 @@ void TupleHashJoinStep::processFE2(RowGroup &input, RowGroup &output, Row &inRow outRow.nextRow(); if (output.getRowCount() == 8192) { results.push_back(result); - result.reinit(output); - output.setData(&result); + result.reset(new uint8_t[output.getMaxDataSize()]); + output.setData(result.get()); output.resetRowGroup(input.getBaseRid()); output.setDBRoot(input.getDBRoot()); output.getRow(0, &outRow); @@ -1379,25 +1073,24 @@ void TupleHashJoinStep::processFE2(RowGroup &input, RowGroup &output, Row &inRow rgData->swap(results); } -void TupleHashJoinStep::sendResult(const vector &res) +void TupleHashJoinStep::sendResult(const vector > &res) { boost::mutex::scoped_lock lock(outputDLLock); - for (uint32_t i = 0; i < res.size(); i++) - //INSERT_ADAPTER(outputDL, res[i]); + for (uint i = 0; i < res.size(); i++) outputDL->insert(res[i]); } -void TupleHashJoinStep::grabSomeWork(vector *work) +void TupleHashJoinStep::grabSomeWork(vector > *work) { boost::mutex::scoped_lock lock(inputDLLock); work->clear(); if (!moreInput) return; - RGData e; + shared_array e; moreInput = largeDL->next(largeIt, &e); /* Tunable number here, but it probably won't change things much */ - for (uint32_t i = 0; i < 10 && moreInput; i++) { + for (uint i = 0; i < 10 && moreInput; i++) { work->push_back(e); moreInput = largeDL->next(largeIt, &e); } @@ -1407,80 +1100,56 @@ void TupleHashJoinStep::grabSomeWork(vector *work) /* This function is a port of the main join loop in TupleBPS::receiveMultiPrimitiveMessages(). Any * changes made here should also be made there and vice versa. */ -void TupleHashJoinStep::joinOneRG(uint32_t threadID, vector *out, +void TupleHashJoinStep::joinOneRG(uint threadID, vector > *out, RowGroup &inputRG, RowGroup &joinOutput, Row &largeSideRow, Row &joinFERow, - Row &joinedRow, Row &baseRow, vector > &joinMatches, - shared_array &smallRowTemplates, - // disk-join support vars. This param list is insane; refactor attempt would be nice at some point. - vector > *tjoiners, - boost::shared_array > *rgMappings, - boost::shared_array > *feMappings, - boost::scoped_array > *smallNullMem - ) + Row &joinedRow, Row &baseRow, vector > &joinMatches, + shared_array &smallRowTemplates) { + shared_array joinedData; + uint matchCount, smallSideCount = smallDLs.size(); + uint j, k; - /* Disk-join support. - These dissociate the fcn from THJS's members & allow this fcn to be called from DiskJoinStep - */ - if (!tjoiners) - tjoiners = &joiners; - - if (!rgMappings) - rgMappings = &columnMappings; - - if (!feMappings) - feMappings = &fergMappings; - - if (!smallNullMem) - smallNullMem = &smallNullMemory; - - RGData joinedData; - uint32_t matchCount, smallSideCount = tjoiners->size(); - uint32_t j, k; - - joinedData.reinit(joinOutput); - joinOutput.setData(&joinedData); + joinedData.reset(new uint8_t[joinOutput.getMaxDataSize()]); + joinOutput.setData(joinedData.get()); joinOutput.resetRowGroup(inputRG.getBaseRid()); joinOutput.setDBRoot(inputRG.getDBRoot()); inputRG.getRow(0, &largeSideRow); - //cout << "jointype = " << (*tjoiners)[0]->getJoinType() << endl; - for (k = 0; k < inputRG.getRowCount() && !cancelled(); k++, largeSideRow.nextRow()) { + for (k = 0; k < inputRG.getRowCount() && !die; k++, largeSideRow.nextRow()) { //cout << "THJS: Large side row: " << largeSideRow.toString() << endl; matchCount = 0; for (j = 0; j < smallSideCount; j++) { - (*tjoiners)[j]->match(largeSideRow, k, threadID, &joinMatches[j]); + joiners[j]->match(largeSideRow, k, threadID, &joinMatches[j]); /* Debugging code to print the matches Row r; smallRGs[j].initRow(&r); cout << joinMatches[j].size() << " matches: \n"; - for (uint32_t z = 0; z < joinMatches[j].size(); z++) { + for (uint z = 0; z < joinMatches[j].size(); z++) { r.setData(joinMatches[j][z]); cout << " " << r.toString() << endl; } */ matchCount = joinMatches[j].size(); - if ((*tjoiners)[j]->hasFEFilter() && matchCount > 0) { - //cout << "doing FE filter" << endl; - vector newJoinMatches; - applyMapping((*feMappings)[smallSideCount], largeSideRow, &joinFERow); - for (uint32_t z = 0; z < joinMatches[j].size(); z++) { - smallRowTemplates[j].setPointer(joinMatches[j][z]); - applyMapping((*feMappings)[j], smallRowTemplates[j], &joinFERow); - if (!(*tjoiners)[j]->evaluateFilter(joinFERow, threadID)) + if (joiners[j]->hasFEFilter() && matchCount > 0) { + vector newJoinMatches; + applyMapping(fergMappings[smallSideCount], largeSideRow, &joinFERow); + for (uint z = 0; z < joinMatches[j].size(); z++) { + smallRowTemplates[j].setData(joinMatches[j][z]); + applyMapping(fergMappings[j], smallRowTemplates[j], &joinFERow); + if (!joiners[j]->evaluateFilter(joinFERow, threadID)) matchCount--; else { /* The first match includes it in a SEMI join result and excludes it from an ANTI join * result. If it's SEMI & SCALAR however, it needs to continue. */ newJoinMatches.push_back(joinMatches[j][z]); - if ((*tjoiners)[j]->antiJoin() || ((*tjoiners)[j]->semiJoin() && !(*tjoiners)[j]->scalar())) + if (joiners[j]->antiJoin() || (joiners[j]->semiJoin() && !joiners[j]->scalar())) break; } } // the filter eliminated all matches, need to join with the NULL row - if (matchCount == 0 && (*tjoiners)[j]->largeOuterJoin()) { + if (matchCount == 0 && joiners[j]->largeOuterJoin()) { newJoinMatches.clear(); - newJoinMatches.push_back(Row::Pointer((*smallNullMem)[j].get())); + newJoinMatches.push_back(smallNullMemory[j].get()); matchCount = 1; } @@ -1488,37 +1157,36 @@ void TupleHashJoinStep::joinOneRG(uint32_t threadID, vector *out, } /* If anti-join, reverse the result */ - if ((*tjoiners)[j]->antiJoin()) { + if (joiners[j]->antiJoin()) matchCount = (matchCount ? 0 : 1); - } if (matchCount == 0) { joinMatches[j].clear(); break; } - else if (!(*tjoiners)[j]->scalar() && ((*tjoiners)[j]->semiJoin() || (*tjoiners)[j]->antiJoin())) { + else if (!joiners[j]->scalar() && (joiners[j]->semiJoin() || joiners[j]->antiJoin())) { joinMatches[j].clear(); - joinMatches[j].push_back(Row::Pointer((*smallNullMem)[j].get())); + joinMatches[j].push_back(smallNullMemory[j].get()); matchCount = 1; } - - if (matchCount == 0 && (*tjoiners)[j]->innerJoin()) + + if (matchCount == 0 && joiners[j]->innerJoin()) break; - - if ((*tjoiners)[j]->scalar() && matchCount > 1) { - errorMessage(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_MORE_THAN_1_ROW)); - status(logging::ERR_MORE_THAN_1_ROW); + + if (joiners[j]->scalar() && matchCount > 1) { + outJSA.status(logging::ERR_MORE_THAN_1_ROW); + outJSA.errorMessage(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_MORE_THAN_1_ROW)); abort(); } - if ((*tjoiners)[j]->smallOuterJoin()) - (*tjoiners)[j]->markMatches(threadID, joinMatches[j]); + if (joiners[j]->smallOuterJoin()) + joiners[j]->markMatches(threadID, joinMatches[j]); } if (matchCount > 0) { /* TODO!!! See TupleBPS for the fix for bug 3510! */ - applyMapping((*rgMappings)[smallSideCount], largeSideRow, &baseRow); - baseRow.setRid(largeSideRow.getRelRid()); - generateJoinResultSet(joinMatches, baseRow, *rgMappings, + applyMapping(columnMappings[smallSideCount], largeSideRow, &baseRow); + baseRow.setRid(largeSideRow.getRid()); + generateJoinResultSet(joinMatches, baseRow, columnMappings, 0, joinOutput, joinedData, out, smallRowTemplates, joinedRow); } } @@ -1526,19 +1194,19 @@ void TupleHashJoinStep::joinOneRG(uint32_t threadID, vector *out, out->push_back(joinedData); } -void TupleHashJoinStep::generateJoinResultSet(const vector > &joinerOutput, +void TupleHashJoinStep::generateJoinResultSet(const vector > &joinerOutput, Row &baseRow, const shared_array > &mappings, - const uint32_t depth, RowGroup &l_outputRG, RGData &rgData, - vector *outputData, const shared_array &smallRows, + const uint depth, RowGroup &l_outputRG, shared_array &rgData, + vector > *outputData, const shared_array &smallRows, Row &joinedRow) { - uint32_t i; + uint i; Row &smallRow = smallRows[depth]; - uint32_t smallSideCount = joinerOutput.size(); + uint smallSideCount = smallDLs.size(); if (depth < smallSideCount - 1) { for (i = 0; i < joinerOutput[depth].size(); i++) { - smallRow.setPointer(joinerOutput[depth][i]); + smallRow.setData(joinerOutput[depth][i]); applyMapping(mappings[depth], smallRow, &baseRow); // cout << "depth " << depth << ", size " << joinerOutput[depth].size() << ", row " << i << ": " << smallRow.toString() << endl; generateJoinResultSet(joinerOutput, baseRow, mappings, depth + 1, @@ -1549,125 +1217,24 @@ void TupleHashJoinStep::generateJoinResultSet(const vector l_outputRG.getRow(l_outputRG.getRowCount(), &joinedRow); for (i = 0; i < joinerOutput[depth].size(); i++, joinedRow.nextRow(), l_outputRG.incRowCount()) { - smallRow.setPointer(joinerOutput[depth][i]); + smallRow.setData(joinerOutput[depth][i]); if (UNLIKELY(l_outputRG.getRowCount() == 8192)) { - uint32_t dbRoot = l_outputRG.getDBRoot(); - uint64_t baseRid = l_outputRG.getBaseRid(); + uint dbRoot = l_outputRG.getDBRoot(); outputData->push_back(rgData); - rgData.reinit(l_outputRG); - l_outputRG.setData(&rgData); - l_outputRG.resetRowGroup(baseRid); + rgData.reset(new uint8_t[l_outputRG.getMaxDataSize()]); + l_outputRG.setData(rgData.get()); + l_outputRG.resetRowGroup(baseRow.getRid()); l_outputRG.setDBRoot(dbRoot); l_outputRG.getRow(0, &joinedRow); } // cout << "depth " << depth << ", size " << joinerOutput[depth].size() << ", row " << i << ": " << smallRow.toString() << endl; applyMapping(mappings[depth], smallRow, &baseRow); - copyRow(baseRow, &joinedRow); - //memcpy(joinedRow.getData(), baseRow.getData(), joinedRow.getSize()); + memcpy(joinedRow.getData(), baseRow.getData(), joinedRow.getSize()); //cout << "(step " << stepID << ") fully joined row is: " << joinedRow.toString() << endl; } } } -void TupleHashJoinStep::segregateJoiners() -{ - uint32_t i; - bool allInnerJoins = true; - bool anyTooLarge = false; - uint32_t smallSideCount = smallDLs.size(); - - boost::mutex::scoped_lock sl(djsLock); - - for (i = 0; i < smallSideCount; i++) { - allInnerJoins &= (joinTypes[i] == INNER); - anyTooLarge |= !joiners[i]->isFinished(); - } - - /* When DDL updates syscat, the syscat checks here are necessary */ - if (isDML || !allowDJS || (fSessionId & 0x80000000) || - (tableOid() < 3000 && tableOid() >= 1000)) { - if (anyTooLarge) { - joinIsTooBig = true; - abort(); - } - tbpsJoiners = joiners; - return; - } - /* Debugging code, this makes all eligible joins disk-based. - else { - cout << "making all joins disk-based" << endl; - for (i = 0; i < smallSideCount; i++) { - joinIsTooBig = true; - djsJoiners.push_back(joiners[i]); - djsJoinerMap.push_back(i); - } - return; - } - */ - - /* For now if there is no largeBPS all joins need to either be DJS or not, not mixed */ - if (!largeBPS) { - if (anyTooLarge) { - joinIsTooBig = true; - for (i = 0; i < smallSideCount; i++) { - djsJoiners.push_back(joiners[i]); - djsJoinerMap.push_back(i); - } - } - else - tbpsJoiners = joiners; - return; - } - - /* If they are all inner joins they can be segregated w/o respect to - ordering; if they're not, the ordering has to stay consistent therefore - the first joiner that isn't finished and everything after has to be - done by DJS. */ - - if (allInnerJoins) { - for (i = 0; i < smallSideCount; i++) { - //if (joiners[i]->isFinished() && (rand() % 2)) { // for debugging - if (joiners[i]->isFinished()) { - //cout << "1joiner " << i << " " << hex << (uint64_t) joiners[i].get() << dec << " -> TBPS" << endl; - tbpsJoiners.push_back(joiners[i]); - } - else { - joinIsTooBig = true; - //cout << "1joiner " << i << " " << hex << (uint64_t) joiners[i].get() << dec << " -> DJS" << endl; - djsJoiners.push_back(joiners[i]); - djsJoinerMap.push_back(i); - } - } - } - else { - //uint limit = rand() % smallSideCount; - for (i = 0; i < smallSideCount; i++) { - //if (joiners[i]->isFinished() && i < limit) { // debugging - if (joiners[i]->isFinished()) { - //cout << "2joiner " << i << " " << hex << (uint64_t) joiners[i].get() << dec << " -> TBPS" << endl; - tbpsJoiners.push_back(joiners[i]); - } - else - break; - } - for (; i < smallSideCount; i++) { - joinIsTooBig = true; - //cout << "2joiner " << i << " " << hex << (uint64_t) joiners[i].get() << dec << " -> DJS" << endl; - djsJoiners.push_back(joiners[i]); - djsJoinerMap.push_back(i); - } - } -} - -void TupleHashJoinStep::abort() -{ - JobStep::abort(); - boost::mutex::scoped_lock sl(djsLock); - if (djs) { - for (uint32_t i = 0; i < djsJoiners.size(); i++) - djs[i].abort(); - } -} } // vim:ts=4 sw=4: diff --git a/dbcon/joblist/tuplehashjoin.h b/dbcon/joblist/tuplehashjoin.h index f340d58e..743dfba2 100644 --- a/dbcon/joblist/tuplehashjoin.h +++ b/dbcon/joblist/tuplehashjoin.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tuplehashjoin.h 9655 2013-06-25 23:08:13Z xlou $ +// $Id: tuplehashjoin.h 8526 2012-05-17 02:28:10Z xlou $ #ifndef TUPLEHASHJOIN_H_ @@ -36,16 +36,19 @@ namespace joblist class BatchPrimitive; class ResourceManager; class TupleBPS; -struct FunctionJoinInfo; -class DiskJoinStep; class TupleHashJoinStep : public JobStep, public TupleDeliveryStep { public: /** - * @param + * @param + * @param sessionId + * @param statementId + * @param txnId + * @param resourceManager */ - TupleHashJoinStep(const JobInfo& jobInfo); + TupleHashJoinStep(uint32_t sessionId, uint32_t statementId, uint32_t txnId, ResourceManager *, + bool isExeMgr = true); virtual ~TupleHashJoinStep(); void setLargeSideBPS(BatchPrimitive*); @@ -55,7 +58,17 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep /* mandatory JobStep interface */ void run(); void join(); + const JobStepAssociation& inputAssociation() const; + void inputAssociation(const JobStepAssociation& inputAssociation); + const JobStepAssociation& outputAssociation() const; + void outputAssociation(const JobStepAssociation& outputAssociation); const std::string toString() const; + void stepId(uint16_t stepId); + uint16_t stepId() const; + uint32_t sessionId() const; + uint32_t txnId() const; + uint32_t statementId() const; + void logger(const SPJL& logger); /* These tableOID accessors can go away soon */ execplan::CalpontSystemCatalog::OID tableOid() const { return fTableOID2; } @@ -104,8 +117,8 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep const std::vector &tableNames); void addJoinKeyIndex(const std::vector& jt, const std::vector& typeless, - const std::vector >& smallkeys, - const std::vector >& largekeys); + const std::vector >& smallkeys, + const std::vector >& largekeys); void configSmallSideRG(const std::vector& rgs, const std::vector &tableNames); @@ -113,20 +126,22 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep void configJoinKeyIndex(const std::vector& jt, const std::vector& typeless, - const std::vector >& smallkeys, - const std::vector >& largekeys); + const std::vector >& smallkeys, + const std::vector >& largekeys); void setOutputRowGroup(const rowgroup::RowGroup &rg); - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); + + void setIsDelivery(bool b) { isDelivery = b; } const rowgroup::RowGroup& getOutputRowGroup() const { return outputRG; } const rowgroup::RowGroup &getSmallRowGroup() const { return smallRGs[0]; } const std::vector &getSmallRowGroups() const { return smallRGs; } const rowgroup::RowGroup& getLargeRowGroup() const { return largeRG; } - const uint32_t getSmallKey() const { return smallSideKeys[0][0]; } - const std::vector >& getSmallKeys() const { return smallSideKeys; } - const std::vector >& getLargeKeys() const { return largeSideKeys; } + const uint getSmallKey() const { return smallSideKeys[0][0]; } + const std::vector >& getSmallKeys() const { return smallSideKeys; } + const std::vector >& getLargeKeys() const { return largeSideKeys; } /* Some compat fcns to get rid of later */ void oid1(execplan::CalpontSystemCatalog::OID oid) { fOid1 = oid; } @@ -141,13 +156,13 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep /* The replacements. I don't think there's a need for setters or vars. OIDs are already in the rowgroups. */ // s - sth table pair; k - kth key in compound join, 0 for non-compand join - execplan::CalpontSystemCatalog::OID smallSideKeyOID(uint32_t s, uint32_t k) const; - execplan::CalpontSystemCatalog::OID largeSideKeyOID(uint32_t s, uint32_t k) const; + execplan::CalpontSystemCatalog::OID smallSideKeyOID(uint s, uint k) const; + execplan::CalpontSystemCatalog::OID largeSideKeyOID(uint s, uint k) const; void deliveryStep(const SJSTEP& ds) { fDeliveryStep = ds; } /* Iteration 18 mods */ - void setLargeSideDLIndex(uint32_t i) { largeSideIndex = i; } + void setLargeSideDLIndex(uint i) { largeSideIndex = i; } /* obsolete, need to update JLF */ void setJoinType(JoinType jt) { joinType = jt; } @@ -165,47 +180,43 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep /* result rowgroup */ const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; // joinId void joinId(int64_t id) { fJoinId = id; } int64_t joinId() const { return fJoinId; } /* semi-join support */ - void addJoinFilter(boost::shared_ptr, uint32_t index); + void addJoinFilter(boost::shared_ptr, uint index); bool hasJoinFilter() const { return (fe.size() > 0); } - bool hasJoinFilter(uint32_t index) const; - boost::shared_ptr getJoinFilter(uint32_t index) const; + bool hasJoinFilter(uint index) const; void setJoinFilterInputRG(const rowgroup::RowGroup &rg); - virtual bool stringTableFriendly() { return true; } - - uint32_t tokenJoin() const { return fTokenJoin; } - void tokenJoin(uint32_t k) { fTokenJoin = k; } + /* UM Join logic */ + boost::shared_array joinOneRG(boost::shared_array input); - //@bug3683 function join - boost::shared_ptr& funcJoinInfo() { return fFunctionJoinInfo; } - void funcJoinInfo(const boost::shared_ptr& fji) { fFunctionJoinInfo = fji; } - - void abort(); private: TupleHashJoinStep(); TupleHashJoinStep(const TupleHashJoinStep &); TupleHashJoinStep & operator=(const TupleHashJoinStep &); - void errorLogging(const std::string& msg, int err) const; + void errorLogging(const std::string& msg) const; void startAdjoiningSteps(); - void formatMiniStats(uint32_t index); + void formatMiniStats(uint index); + JobStepAssociation inJSA; + JobStepAssociation outJSA; RowGroupDL *largeDL, *outputDL; std::vector smallDLs; - std::vector smallIts; - uint32_t largeIt; + std::vector smallIts; + uint largeIt; JoinType joinType; // deprecated std::vector joinTypes; + uint32_t sessionID; + uint32_t stepID; + uint32_t statementID; + uint32_t txnID; execplan::CalpontSystemCatalog::OID fTableOID1; execplan::CalpontSystemCatalog::OID fTableOID2; execplan::CalpontSystemCatalog::OID fOid1; @@ -241,11 +252,16 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep int fCorrelatedSide; std::vector typelessJoin; // the size of the vector is # of small side - std::vector > largeSideKeys; - std::vector > smallSideKeys; - - ResourceManager& resourceManager; - volatile uint64_t totalUMMemoryUsage; + std::vector > largeSideKeys; + std::vector > smallSideKeys; + + ResourceManager *resourceManager; +#ifdef _MSC_VER + volatile LONGLONG totalUMMemoryUsage; +#else + uint64_t totalUMMemoryUsage; +#endif + SPJL fLogger; struct JoinerSorter { inline bool operator()(const boost::shared_ptr &j1, @@ -254,15 +270,17 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep }; std::vector > joiners; - boost::scoped_array > rgData; + boost::scoped_array > > rgData; + std::vector rows; // for PM join. Points into rgData. TupleBPS* largeBPS; rowgroup::RowGroup largeRG, outputRG; std::vector smallRGs; - uint64_t pmMemLimit; - uint64_t rgDataSize; + uint PMRowLimit; + + bool isDelivery; void hjRunner(); - void smallRunnerFcn(uint32_t index); + void smallRunnerFcn(uint index); struct HJRunner { HJRunner(TupleHashJoinStep *hj) : HJ(hj) { } @@ -270,10 +288,10 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep TupleHashJoinStep *HJ; }; struct SmallRunner { - SmallRunner(TupleHashJoinStep *hj, uint32_t i) :HJ(hj), index(i) { } + SmallRunner(TupleHashJoinStep *hj, uint i) :HJ(hj), index(i) { } void operator()() { HJ->smallRunnerFcn(index); } TupleHashJoinStep *HJ; - uint32_t index; + uint index; }; boost::shared_ptr mainRunner; @@ -291,129 +309,70 @@ class TupleHashJoinStep : public JobStep, public TupleDeliveryStep bool runRan, joinRan; /* Iteration 18 mods */ - uint32_t largeSideIndex; + uint largeSideIndex; bool joinIsTooBig; /* Functions & Expressions support */ boost::shared_ptr fe2; - std::vector fe2TableDeps; + std::vector fe2TableDeps; rowgroup::RowGroup fe2Output; bool runFE2onPM; // Support Mixed Join Type int64_t fJoinId; - + /* Semi-join support */ std::vector feIndexes; std::vector > fe; rowgroup::RowGroup joinFilterRG; - + /* Casual Partitioning forwarding */ void forwardCPData(); - uint32_t uniqueLimit; + uint uniqueLimit; /* UM Join support. Most of this code is ported from the UM join code in tuple-bps.cpp. * They should be kept in sync as much as possible. */ struct JoinRunner { - JoinRunner(TupleHashJoinStep *hj, uint32_t i) : HJ(hj), index(i) { } + JoinRunner(TupleHashJoinStep *hj, uint i) : HJ(hj), index(i) { } void operator()() { HJ->joinRunnerFcn(index); } TupleHashJoinStep *HJ; - uint32_t index; + uint index; }; - void joinRunnerFcn(uint32_t index); + void joinRunnerFcn(uint index); void startJoinThreads(); - void generateJoinResultSet(const std::vector > &joinerOutput, + void generateJoinResultSet(const std::vector > &joinerOutput, rowgroup::Row &baseRow, const boost::shared_array > &mappings, - const uint32_t depth, rowgroup::RowGroup &outputRG, rowgroup::RGData &rgData, - std::vector *outputData, + const uint depth, rowgroup::RowGroup &outputRG, boost::shared_array &rgData, + std::vector > *outputData, const boost::shared_array &smallRows, rowgroup::Row &joinedRow); - void grabSomeWork(std::vector *work); - void sendResult(const std::vector &res); + void grabSomeWork(std::vector > *work); + void sendResult(const std::vector > &res); void processFE2(rowgroup::RowGroup &input, rowgroup::RowGroup &output, rowgroup::Row &inRow, - rowgroup::Row &outRow, std::vector *rgData, + rowgroup::Row &outRow, std::vector > *rgData, funcexp::FuncExpWrapper* local_fe); - void joinOneRG(uint32_t threadID, std::vector *out, + void joinOneRG(uint threadID, std::vector > *out, rowgroup::RowGroup &inputRG, rowgroup::RowGroup &joinOutput, rowgroup::Row &largeSideRow, rowgroup::Row &joinFERow, rowgroup::Row &joinedRow, rowgroup::Row &baseRow, - std::vector > &joinMatches, - boost::shared_array &smallRowTemplates, - std::vector > *joiners = NULL, - boost::shared_array > *rgMappings = NULL, - boost::shared_array > *feMappings = NULL, - boost::scoped_array > *smallNullMem = NULL - ); + std::vector > &joinMatches, + boost::shared_array &smallRowTemplates); void finishSmallOuterJoin(); void makeDupList(const rowgroup::RowGroup &rg); - void processDupList(uint32_t threadID, rowgroup::RowGroup &ingrp, - std::vector *rowData); + void processDupList(uint threadID, rowgroup::RowGroup &ingrp, + std::vector > *rowData); boost::scoped_array > joinRunners; boost::mutex inputDLLock, outputDLLock; boost::shared_array > columnMappings, fergMappings; boost::shared_array fe2Mapping; - uint32_t joinThreadCount; + uint joinThreadCount; boost::scoped_array > smallNullMemory; uint64_t outputIt; bool moreInput; - std::vector > dupList; + std::vector > dupList; boost::scoped_array dupRows; std::vector smallTableNames; bool isExeMgr; - uint32_t lastSmallOuterJoiner; - - //@bug5958 & 6117, stores the table key for identify token join - uint32_t fTokenJoin; - - // moved from base class JobStep - boost::mutex* fStatsMutexPtr; - - //@bug3683 function join - boost::shared_ptr fFunctionJoinInfo; - std::set fFunctionJoinKeys; // for skipping CP forward - - /* Disk-based join support */ - boost::scoped_array djs; - boost::scoped_array > fifos; - void djsReaderFcn(int index); - boost::thread djsReader; - struct DJSReader { - DJSReader(TupleHashJoinStep *hj, uint32_t i) : HJ(hj), index(i) { } - void operator()() { HJ->djsReaderFcn(index); } - TupleHashJoinStep *HJ; - uint32_t index; - }; - - boost::thread djsRelay; - void djsRelayFcn(); - struct DJSRelay { - DJSRelay(TupleHashJoinStep *hj) : HJ(hj) { } - void operator()() { HJ->djsRelayFcn(); } - TupleHashJoinStep *HJ; - }; - - boost::shared_ptr djsSmallUsage; - int64_t djsSmallLimit; - int64_t djsLargeLimit; - uint64_t djsPartitionSize; - bool isDML; - bool allowDJS; - - // hacky mechanism to prevent nextBand from starting before the final - // THJS configuration is settled. Debatable whether to use a bool and poll instead; - // once the config is settled it stays settled, technically no need to - // keep grabbing locks after that. - boost::mutex deliverMutex; - bool ownsOutputDL; - - void segregateJoiners(); - std::vector > tbpsJoiners; - std::vector > djsJoiners; - std::vector djsJoinerMap; - boost::scoped_array memUsedByEachJoin; - boost::mutex djsLock; - boost::shared_ptr sessionMemLimit; - - friend class DiskJoinStep; + uint lastSmallOuterJoiner; }; } diff --git a/dbcon/joblist/tuplehavingstep.cpp b/dbcon/joblist/tuplehavingstep.cpp index d7196ef8..6ebf5545 100644 --- a/dbcon/joblist/tuplehavingstep.cpp +++ b/dbcon/joblist/tuplehavingstep.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tuplehavingstep.cpp 9709 2013-07-20 06:08:46Z xlou $ +// $Id: tuplehavingstep.cpp 8476 2012-04-25 22:28:15Z xlou $ //#define NDEBUG @@ -26,7 +26,6 @@ using namespace std; #include #include -#include using namespace boost; #include "messagequeue.h" @@ -46,9 +45,6 @@ using namespace execplan; #include "rowgroup.h" using namespace rowgroup; -#include "querytele.h" -using namespace querytele; - #include "funcexp.h" #include "jlf_common.h" @@ -58,17 +54,21 @@ using namespace querytele; namespace joblist { -TupleHavingStep::TupleHavingStep(const JobInfo& jobInfo) : - ExpressionStep(jobInfo), +TupleHavingStep::TupleHavingStep( + uint32_t sessionId, + uint32_t txnId, + uint32_t verId, + uint32_t statementId) : + ExpressionStep(sessionId, txnId, verId, statementId), fInputDL(NULL), fOutputDL(NULL), fInputIterator(0), fRowsReturned(0), fEndOfResult(false), + fDelivery(false), fFeInstance(funcexp::FuncExp::instance()) { - fExtendedInfo = "HVS: "; - fQtc.stepParms().stepType = StepTeleStats::T_HVS; + fExtendedInfo = "THS: "; } @@ -88,21 +88,21 @@ void TupleHavingStep::initialize(const RowGroup& rgIn, const JobInfo& jobInfo) fRowGroupIn = rgIn; fRowGroupIn.initRow(&fRowIn); - map keyToIndexMap; + map keyToIndexMap; for (uint64_t i = 0; i < fRowGroupIn.getKeys().size(); ++i) if (keyToIndexMap.find(fRowGroupIn.getKeys()[i]) == keyToIndexMap.end()) keyToIndexMap.insert(make_pair(fRowGroupIn.getKeys()[i], i)); updateInputIndex(keyToIndexMap, jobInfo); - vector oids, oidsIn = fRowGroupIn.getOIDs(); - vector keys, keysIn = fRowGroupIn.getKeys(); - vector scale, scaleIn = fRowGroupIn.getScale(); - vector precision, precisionIn = fRowGroupIn.getPrecision(); + vector oids, oidsIn = fRowGroupIn.getOIDs(); + vector keys, keysIn = fRowGroupIn.getKeys(); + vector scale, scaleIn = fRowGroupIn.getScale(); + vector precision, precisionIn = fRowGroupIn.getPrecision(); vector types, typesIn = fRowGroupIn.getColTypes(); - vector pos, posIn = fRowGroupIn.getOffsets(); + vector pos, posIn = fRowGroupIn.getOffsets(); size_t n = 0; - RetColsVector::const_iterator i = jobInfo.deliveredCols.begin(); + RetColsVector::const_iterator i = jobInfo.deliveredCols.begin(); while (i != jobInfo.deliveredCols.end()) if (NULL == dynamic_cast(i++->get())) n++; @@ -114,7 +114,7 @@ void TupleHavingStep::initialize(const RowGroup& rgIn, const JobInfo& jobInfo) types.insert(types.end(), typesIn.begin(), typesIn.begin() + n); pos.insert(pos.end(), posIn.begin(), posIn.begin() + n + 1); - fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision, jobInfo.stringTableThreshold); + fRowGroupOut = RowGroup(oids.size(), pos, oids, keys, types, scale, precision); fRowGroupOut.initRow(&fRowOut); } @@ -163,12 +163,12 @@ void TupleHavingStep::join() } -uint32_t TupleHavingStep::nextBand(messageqcpp::ByteStream &bs) +uint TupleHavingStep::nextBand(messageqcpp::ByteStream &bs) { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; - uint32_t rowCount = 0; + uint rowCount = 0; try { @@ -178,7 +178,7 @@ uint32_t TupleHavingStep::nextBand(messageqcpp::ByteStream &bs) if (dlTimes.FirstReadTime().tv_sec ==0) dlTimes.setFirstReadTime(); - if (!more || cancelled()) + if (!more || (0 < fInputJobStepAssociation.status())) { fEndOfResult = true; } @@ -186,23 +186,22 @@ uint32_t TupleHavingStep::nextBand(messageqcpp::ByteStream &bs) bool emptyRowGroup = true; while (more && !fEndOfResult && emptyRowGroup) { - if (cancelled()) + if (0 < fInputJobStepAssociation.status()) { - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); break; } - fRowGroupIn.setData(&rgDataIn); - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); + fRowGroupIn.setData(rgDataIn.get()); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); + fRowGroupOut.setData(rgDataOut.get()); doHavingFilters(); if (fRowGroupOut.getRowCount() > 0) { emptyRowGroup = false; - fRowGroupOut.serializeRGData(bs); + bs.load(fRowGroupOut.getData(), fRowGroupOut.getDataSize()); rowCount = fRowGroupOut.getRowCount(); } else @@ -218,28 +217,29 @@ uint32_t TupleHavingStep::nextBand(messageqcpp::ByteStream &bs) } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleHavingStepErr, fErrorInfo, fSessionId); - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleHavingStepErr); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); fEndOfResult = true; } catch(...) { - catchHandler("TupleHavingStep next band caught an unknown exception", - tupleHavingStepErr, fErrorInfo, fSessionId); - while (more) - more = fInputDL->next(fInputIterator, &rgDataIn); + catchHandler("TupleHavingStep next band caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleHavingStepErr); + while (more) more = fInputDL->next(fInputIterator, &rgDataIn); fEndOfResult = true; } if (fEndOfResult) { // send an empty / error band - rgDataOut.reinit(fRowGroupOut, 0); - fRowGroupOut.setData(&rgDataOut); + rgDataOut.reset(new uint8_t[fRowGroupOut.getEmptySize()]); + fRowGroupOut.setData(rgDataOut.get()); fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setStatus(status()); - fRowGroupOut.serializeRGData(bs); + fRowGroupOut.setStatus(fOutputJobStepAssociation.status()); + bs.load(rgDataOut.get(), fRowGroupOut.getDataSize()); dlTimes.setLastReadTime(); dlTimes.setEndOfInputTime(); @@ -254,37 +254,30 @@ uint32_t TupleHavingStep::nextBand(messageqcpp::ByteStream &bs) void TupleHavingStep::execute() { - RGData rgDataIn; - RGData rgDataOut; + shared_array rgDataIn; + shared_array rgDataOut; bool more = false; - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; try { more = fInputDL->next(fInputIterator, &rgDataIn); dlTimes.setFirstReadTime(); - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - if (!more && cancelled()) + if (!more && (0 < fInputJobStepAssociation.status())) { fEndOfResult = true; } while (more && !fEndOfResult) { - fRowGroupIn.setData(&rgDataIn); - rgDataOut.reinit(fRowGroupOut, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgDataOut); + fRowGroupIn.setData(rgDataIn.get()); + rgDataOut.reset(new uint8_t[fRowGroupOut.getDataSize(fRowGroupIn.getRowCount())]); + fRowGroupOut.setData(rgDataOut.get()); doHavingFilters(); more = fInputDL->next(fInputIterator, &rgDataIn); - if (cancelled()) + if (0 < fInputJobStepAssociation.status()) { fEndOfResult = true; } @@ -296,12 +289,15 @@ void TupleHavingStep::execute() } catch(const std::exception& ex) { - catchHandler(ex.what(), tupleHavingStepErr, fErrorInfo, fSessionId); + catchHandler(ex.what(), fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleHavingStepErr); } catch(...) { - catchHandler("TupleHavingStep execute caught an unknown exception", - tupleHavingStepErr, fErrorInfo, fSessionId); + catchHandler("TupleHavingStep execute caught an unknown exception", fSessionId); + if (fOutputJobStepAssociation.status() == 0) + fOutputJobStepAssociation.status(tupleHavingStepErr); } while (more) @@ -310,11 +306,6 @@ void TupleHavingStep::execute() fEndOfResult = true; fOutputDL->endOfInput(); - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - dlTimes.setLastReadTime(); dlTimes.setEndOfInputTime(); @@ -333,7 +324,7 @@ void TupleHavingStep::doHavingFilters() { if(fFeInstance->evaluate(fRowIn, fExpressionFilter)) { - copyRow(fRowIn, &fRowOut); + memcpy(fRowOut.getData(), fRowIn.getData(), fRowOut.getSize()); fRowGroupOut.incRowCount(); fRowOut.nextRow(); } @@ -357,18 +348,6 @@ const RowGroup& TupleHavingStep::getDeliveredRowGroup() const } -void TupleHavingStep::deliverStringTableRowGroup(bool b) -{ - fRowGroupOut.setUseStringTable(b); -} - - -bool TupleHavingStep::deliverStringTableRowGroup() const -{ - return fRowGroupOut.usesStringTable(); -} - - const string TupleHavingStep::toString() const { ostringstream oss; @@ -400,8 +379,7 @@ void TupleHavingStep::printCalTrace() << "\t1st read " << dlTimes.FirstReadTimeString() << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; + << "s;\n\tJob completion status " << fOutputJobStepAssociation.status() << endl; logEnd(logStr.str().c_str()); fExtendedInfo += logStr.str(); formatMiniStats(); diff --git a/dbcon/joblist/tuplehavingstep.h b/dbcon/joblist/tuplehavingstep.h index 1e3467b6..ee1fb8e3 100644 --- a/dbcon/joblist/tuplehavingstep.h +++ b/dbcon/joblist/tuplehavingstep.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: tuplehavingstep.h 9596 2013-06-04 19:59:04Z xlou $ +// $Id: tuplehavingstep.h 8526 2012-05-17 02:28:10Z xlou $ #ifndef JOBLIST_TUPLEHAVINGSTEP_H @@ -40,8 +40,10 @@ class TupleHavingStep : public ExpressionStep, public TupleDeliveryStep { public: /** @brief TupleHavingStep constructor + * @param in the inputAssociation pointer + * @param out the outputAssociation pointer */ - TupleHavingStep(const JobInfo& jobInfo); + TupleHavingStep( uint32_t sessionId, uint32_t txnId, uint32_t verId, uint32_t statementId); /** @brief TupleHavingStep destructor */ @@ -61,15 +63,12 @@ class TupleHavingStep : public ExpressionStep, public TupleDeliveryStep /** @brief TupleDeliveryStep's pure virtual methods */ - uint32_t nextBand(messageqcpp::ByteStream &bs); + uint nextBand(messageqcpp::ByteStream &bs); const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; + void setIsDelivery(bool b) { fDelivery = b; } void initialize(const rowgroup::RowGroup& rgIn, const JobInfo& jobInfo); void expressionFilter(const execplan::ParseTree* filter, JobInfo& jobInfo); - - virtual bool stringTableFriendly() { return true; } protected: void execute(); @@ -101,6 +100,7 @@ class TupleHavingStep : public ExpressionStep, public TupleDeliveryStep uint64_t fRowsReturned; bool fEndOfResult; + bool fDelivery; funcexp::FuncExp* fFeInstance; }; diff --git a/dbcon/joblist/tupleunion.cpp b/dbcon/joblist/tupleunion.cpp index 2647e2b1..349cf88a 100644 --- a/dbcon/joblist/tupleunion.cpp +++ b/dbcon/joblist/tupleunion.cpp @@ -16,21 +16,16 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: tupleunion.cpp 9665 2013-07-02 21:47:39Z pleblanc $ + * $Id: tupleunion.cpp 8476 2012-04-25 22:28:15Z xlou $ * ****************************************************************************/ #include #include #include -#include - -#include "querytele.h" -using namespace querytele; #include "dataconvert.h" #include "hasher.h" -#include "jlf_common.h" #include "resourcemanager.h" #include "tupleunion.h" @@ -56,58 +51,99 @@ inline double pow10(double x) namespace joblist { -inline uint64_t TupleUnion::Hasher::operator()(const RowPosition &p) const +uint64_t TupleUnion::Hasher::operator()(const uint8_t *d) const { - Row &row = ts->row; - if (p.group & RowPosition::normalizedFlag) - ts->normalizedData[p.group & ~RowPosition::normalizedFlag].getRow(p.row, &row); - else - ts->rowMemory[p.group].getRow(p.row, &row); - return row.hash(); + return h((const char *) d, ts->rowLength); } -inline bool TupleUnion::Eq::operator()(const RowPosition &d1, const RowPosition &d2) const +bool TupleUnion::Eq::operator()(const uint8_t *d1, const uint8_t *d2) const { - Row &r1 = ts->row, &r2 = ts->row2; - if (d1.group & RowPosition::normalizedFlag) - ts->normalizedData[d1.group & ~RowPosition::normalizedFlag].getRow(d1.row, &r1); - else - ts->rowMemory[d1.group].getRow(d1.row, &r1); - if (d2.group & RowPosition::normalizedFlag) - ts->normalizedData[d2.group & ~RowPosition::normalizedFlag].getRow(d2.row, &r2); - else - ts->rowMemory[d2.group].getRow(d2.row, &r2); - return r1.equals(r2); + return (memcmp(d1, d2, ts->rowLength) == 0); } -TupleUnion::TupleUnion(CalpontSystemCatalog::OID tableOID, const JobInfo& jobInfo) : - JobStep(jobInfo), +TupleUnion::TupleUnion(const JobStepAssociation& in, + const JobStepAssociation& out, + CalpontSystemCatalog::OID tableOID, + uint32_t session, + uint32_t txn, + uint32_t ver, + uint16_t step, + uint32_t statement, + ResourceManager& r) : + JobStep(), + inJSA(in), + outJSA(out), fTableOID(tableOID), + sessionID(session), + txnID(txn), + verID(ver), + stepID(step), + statementID(statement), + isDelivery(false), output(NULL), outputIt(-1), memUsage(0), - rm(jobInfo.rm), + rm(r), allocator(64*1024*1024 + 1), runnersDone(0), - distinctCount(0), - distinctDone(0), - fRowsReturned(0), runRan(false), - joinRan(false), - sessionMemLimit(jobInfo.umMemLimit) + joinRan(false) { uniquer.reset(new Uniquer_t(10, Hasher(this), Eq(this), allocator)); - fExtendedInfo = "TUN: "; - fQtc.stepParms().stepType = StepTeleStats::T_TUN; } TupleUnion::~TupleUnion() { - rm.returnMemory(memUsage, sessionMemLimit); + rm.returnMemory(memUsage); if (!runRan && output) output->endOfInput(); } +const JobStepAssociation & TupleUnion::inputAssociation() const +{ + return inJSA; +} + +void TupleUnion::inputAssociation(const JobStepAssociation &in) +{ + inJSA = in; +} + +const JobStepAssociation & TupleUnion::outputAssociation() const +{ + return outJSA; +} + +void TupleUnion::outputAssociation(const JobStepAssociation &out) +{ + outJSA = out; +} + +void TupleUnion::stepId(uint16_t id) +{ + stepID = id; +} + +uint16_t TupleUnion::stepId() const +{ + return stepID; +} + +uint32_t TupleUnion::sessionId() const +{ + return sessionID; +} + +uint32_t TupleUnion::txnId() const +{ + return txnID; +} + +uint32_t TupleUnion::statementId() const +{ + return statementID; +} + CalpontSystemCatalog::OID TupleUnion::tableOid() const { return fTableOID; @@ -121,7 +157,7 @@ void TupleUnion::setInputRowGroups(const vector &in) void TupleUnion::setOutputRowGroup(const rowgroup::RowGroup &out) { outputRG = out; - rowLength = outputRG.getRowSizeWithStrings(); + rowLength = outputRG.getRowSize(); } void TupleUnion::setDistinctFlags(const vector &v) @@ -129,119 +165,91 @@ void TupleUnion::setDistinctFlags(const vector &v) distinctFlags = v; } -void TupleUnion::readInput(uint32_t which) +void TupleUnion::setIsDelivery(bool b) { - /* The handling of the output got a little kludgey with the string table enhancement. - * When there is no distinct check, the outputs are all generated independently of - * each other locally in this fcn. When there is a distinct check, threads - * share the output, which is built in the 'rowMemory' vector rather than in - * thread-local memory. Building the result in a common space allows us to - * store 8-byte offsets in rowMemory rather than 16-bytes for absolute pointers. - */ + isDelivery = b; +} +void TupleUnion::readInput(uint which) +{ RowGroupDL *dl = NULL; bool more = true; - RGData inRGData, outRGData, *tmpRGData; - uint32_t it = numeric_limits::max(); + shared_array inRGData, outRGData, tmpRGData; + uint it = numeric_limits::max(); RowGroup l_inputRG, l_outputRG, l_tmpRG; Row inRow, outRow, tmpRow; - bool distinct; + bool distinct, inserted; uint64_t memUsageBefore, memUsageAfter, memDiff; - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - - l_outputRG = outputRG; - dl = inputs[which]; - l_inputRG = inputRGs[which]; - l_inputRG.initRow(&inRow); - l_outputRG.initRow(&outRow); - distinct = distinctFlags[which]; - - if (distinct) { - l_tmpRG = outputRG; - tmpRGData = &normalizedData[which]; - l_tmpRG.initRow(&tmpRow); - l_tmpRG.setData(tmpRGData); - l_tmpRG.resetRowGroup(0); - l_tmpRG.getRow(0, &tmpRow); - } - else { - outRGData = RGData(l_outputRG); - l_outputRG.setData(&outRGData); +// uint rCount = 0; + + try { + l_outputRG = outputRG; + outRGData.reset(new uint8_t[l_outputRG.getMaxDataSize()]); + dl = inputs[which]; + l_inputRG = inputRGs[which]; + l_inputRG.initRow(&inRow); + l_outputRG.initRow(&outRow); + l_outputRG.setData(outRGData.get()); l_outputRG.resetRowGroup(0); l_outputRG.getRow(0, &outRow); - } + distinct = distinctFlags[which]; - try { + if (distinct) { + l_tmpRG = outputRG; + tmpRGData.reset(new uint8_t[l_tmpRG.getMaxDataSize()]); + l_tmpRG.initRow(&tmpRow); + l_tmpRG.setData(tmpRGData.get()); + l_tmpRG.resetRowGroup(0); + l_tmpRG.getRow(0, &tmpRow); + } it = dl->getIterator(); more = dl->next(it, &inRGData); - if (dlTimes.FirstReadTime().tv_sec==0) - dlTimes.setFirstReadTime(); - - if (fStartTime == -1) - { - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - } - - while (more && !cancelled()) { + while (more && !die && inJSA.status() == 0) { /* normalize each row - if distinct flag is set - copy the row into the output and test for uniqueness - if unique, increment the row count - else - copy the row into the output & inc row count + if distinct flag is set insert into uniquer + if row was inserted, put it in the output RG + else put it in the output RG */ - l_inputRG.setData(&inRGData); + l_inputRG.setData(inRGData.get()); l_inputRG.getRow(0, &inRow); if (distinct) { memDiff = 0; l_tmpRG.resetRowGroup(0); l_tmpRG.getRow(0, &tmpRow); l_tmpRG.setRowCount(l_inputRG.getRowCount()); - for (uint32_t i = 0; i < l_inputRG.getRowCount(); i++, inRow.nextRow(), + for (uint i = 0; i < l_inputRG.getRowCount(); i++, inRow.nextRow(), tmpRow.nextRow()) normalize(inRow, &tmpRow); l_tmpRG.getRow(0, &tmpRow); { mutex::scoped_lock lk(uniquerMutex); - getOutput(&l_outputRG, &outRow, &outRGData); memUsageBefore = allocator.getMemUsage(); - for (uint32_t i = 0; i < l_tmpRG.getRowCount(); i++, tmpRow.nextRow()) { - pair inserted; - inserted = uniquer->insert(RowPosition(which | RowPosition::normalizedFlag, i)); - if (inserted.second) { - copyRow(tmpRow, &outRow); - const_cast(*(inserted.first)) = RowPosition(rowMemory.size()-1, l_outputRG.getRowCount()); - memDiff += outRow.getRealSize(); - addToOutput(&outRow, &l_outputRG, true, outRGData); + for (uint i = 0; i < l_tmpRG.getRowCount(); i++, tmpRow.nextRow()) { + memcpy(outRow.getData(), tmpRow.getData(), tmpRow.getSize()); + inserted = uniquer->insert(outRow.getData()).second; + if (inserted) { + addToOutput(&outRow, &l_outputRG, true, &outRGData); + memDiff += outRow.getSize(); } } memUsageAfter = allocator.getMemUsage(); memDiff += (memUsageAfter - memUsageBefore); memUsage += memDiff; } - if (!rm.getMemory(memDiff, sessionMemLimit)) { + if (!rm.getMemory(memDiff)) { fLogger->logMessage(logging::LOG_TYPE_INFO, logging::ERR_UNION_TOO_BIG); - if (status() == 0) // preserve existing error code - { - errorMessage(logging::IDBErrorInfo::instance()->errorMsg( - logging::ERR_UNION_TOO_BIG)); - status(logging::ERR_UNION_TOO_BIG); - } + inJSA.status(logging::ERR_UNION_TOO_BIG); abort(); } } else { - for (uint32_t i = 0; i < l_inputRG.getRowCount(); i++, inRow.nextRow()) { + for (uint i = 0; i < l_inputRG.getRowCount(); i++, inRow.nextRow()) { normalize(inRow, &outRow); - addToOutput(&outRow, &l_outputRG, false, outRGData); + addToOutput(&outRow, &l_outputRG, false, &outRGData); } } more = dl->next(it, &inRGData); @@ -249,10 +257,9 @@ void TupleUnion::readInput(uint32_t which) } catch(...) { - if (status() == 0) + if (outJSA.status() == 0) { - errorMessage("Union step caught an unknown exception."); - status(logging::unionStepErr); + outJSA.status(logging::unionStepErr); fLogger->logMessage(logging::LOG_TYPE_CRITICAL, "Union step caught an unknown exception."); } abort(); @@ -260,114 +267,67 @@ void TupleUnion::readInput(uint32_t which) /* make sure that the input was drained before exiting. This can happen if the query was aborted */ - if (dl && it != numeric_limits::max()) + if (dl && it != numeric_limits::max()) while (more) more = dl->next(it, &inRGData); { - mutex::scoped_lock lock1(uniquerMutex); - mutex::scoped_lock lock2(sMutex); - if (!distinct && l_outputRG.getRowCount() > 0) + mutex::scoped_lock lock(sMutex); + if (l_outputRG.getRowCount() > 0) { output->insert(outRGData); - if (distinct) { - getOutput(&l_outputRG, &outRow, &outRGData); - if (++distinctDone == distinctCount && l_outputRG.getRowCount() > 0) - output->insert(outRGData); + if (distinctFlags[which]) + rowMemory.push_back(outRGData); } - if (++runnersDone == fInputJobStepAssociation.outSize()) - { + runnersDone++; + if (runnersDone == inJSA.outSize()) output->endOfInput(); - - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - - if (traceOn()) - { - dlTimes.setLastReadTime(); - dlTimes.setEndOfInputTime(); - - time_t t = time (0); - char timeString[50]; - ctime_r (&t, timeString); - timeString[strlen (timeString )-1] = '\0'; - ostringstream logStr; - logStr << "ses:" << fSessionId << " st: " << fStepId << " finished at " - << timeString << "; total rows returned-" << fRowsReturned << endl - << "\t1st read " << dlTimes.FirstReadTimeString() - << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" - << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(),dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; - logEnd(logStr.str().c_str()); - fExtendedInfo += logStr.str(); - formatMiniStats(); - } - } } } -uint32_t TupleUnion::nextBand(messageqcpp::ByteStream &bs) +uint TupleUnion::nextBand(messageqcpp::ByteStream &bs) { - RGData mem; + shared_array mem; bool more; - uint32_t ret = 0; + uint ret = 0; bs.restart(); more = output->next(outputIt, &mem); if (more) - outputRG.setData(&mem); + outputRG.setData(mem.get()); else { - mem = RGData(outputRG, 0); - outputRG.setData(&mem); + mem.reset(new uint8_t[outputRG.getEmptySize()]); + outputRG.setData(mem.get()); outputRG.resetRowGroup(0); - outputRG.setStatus(status()); + outputRG.setStatus(inJSA.status()); } - outputRG.serializeRGData(bs); - ret = outputRG.getRowCount(); + bs.load(mem.get(), outputRG.getDataSize()); + ret = outputRG.getRowCount(); return ret; } -void TupleUnion::getOutput(RowGroup *rg, Row *row, RGData *data) -{ - if (UNLIKELY(rowMemory.empty())) { - *data = RGData(*rg); - rg->setData(data); - rg->resetRowGroup(0); - rowMemory.push_back(*data); - } - else { - *data = rowMemory.back(); - rg->setData(data); - } - rg->getRow(rg->getRowCount(), row); -} - void TupleUnion::addToOutput(Row *r, RowGroup *rg, bool keepit, - RGData &data) + shared_array *data) { r->nextRow(); rg->incRowCount(); - fRowsReturned++; if (rg->getRowCount() == 8192) { { mutex::scoped_lock lock(sMutex); - output->insert(data); + output->insert(*data); + if (keepit) + rowMemory.push_back(*data); } - data = RGData(*rg); - rg->setData(&data); + data->reset(new uint8_t[rg->getMaxDataSize()]); + rg->setData(data->get()); rg->resetRowGroup(0); rg->getRow(0, r); - if (keepit) - rowMemory.push_back(data); } } void TupleUnion::normalize(const Row &in, Row *out) { - uint32_t i; + uint i; out->setRid(0); for (i = 0; i < out->getColumnCount(); i++) { @@ -391,15 +351,6 @@ void TupleUnion::normalize(const Row &in, Row *out) goto dec1; out->setIntField(in.getIntField(i), i); break; - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - if (in.getScale(i)) - goto dec1; - out->setUintField(in.getUintField(i), i); - break; case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: { ostringstream os; @@ -417,8 +368,7 @@ void TupleUnion::normalize(const Row &in, Row *out) case CalpontSystemCatalog::DATE: case CalpontSystemCatalog::DATETIME: throw logic_error("TupleUnion::normalize(): tried to normalize an int to a date or datetime"); - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { + case CalpontSystemCatalog::FLOAT: { int scale = in.getScale(i); if (scale != 0) { float f = in.getIntField(i); @@ -429,8 +379,7 @@ void TupleUnion::normalize(const Row &in, Row *out) out->setFloatField(in.getIntField(i), i); break; } - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { + case CalpontSystemCatalog::DOUBLE: { int scale = in.getScale(i); if (scale != 0) { double d = in.getIntField(i); @@ -441,8 +390,7 @@ void TupleUnion::normalize(const Row &in, Row *out) out->setDoubleField(in.getIntField(i), i); break; } - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { + case CalpontSystemCatalog::DECIMAL: { dec1: uint64_t val = in.getIntField(i); int diff = out->getScale(i) - in.getScale(i); if (diff < 0) @@ -459,87 +407,6 @@ dec1: uint64_t val = in.getIntField(i); throw logic_error(os.str()); } break; - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - switch (out->getColTypes()[i]) { - case CalpontSystemCatalog::TINYINT: - case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::MEDINT: - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::BIGINT: - if (out->getScale(i)) - goto dec2; - out->setIntField(in.getUintField(i), i); - break; - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - out->setUintField(in.getUintField(i), i); - break; - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: { - ostringstream os; - if (in.getScale(i)) { - double d = in.getUintField(i); - d /= pow10(in.getScale(i)); - os.precision(15); - os << d; - } - else - os << in.getUintField(i); - out->setStringField(os.str(), i); - break; - } - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - throw logic_error("TupleUnion::normalize(): tried to normalize an int to a date or datetime"); - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { - int scale = in.getScale(i); - if (scale != 0) { - float f = in.getUintField(i); - f /= (uint64_t) pow(10.0, scale); - out->setFloatField(f, i); - } - else - out->setFloatField(in.getUintField(i), i); - break; - } - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { - int scale = in.getScale(i); - if (scale != 0) { - double d = in.getUintField(i); - d /= (uint64_t) pow(10.0, scale); - out->setDoubleField(d, i); - } - else - out->setDoubleField(in.getUintField(i), i); - break; - } - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { -dec2: uint64_t val = in.getIntField(i); - int diff = out->getScale(i) - in.getScale(i); - if (diff < 0) - val /= (uint64_t) pow((double) 10, (double) -diff); - else - val *= (uint64_t) pow((double) 10, (double) diff); - out->setIntField(val, i); - break; - } - default: - ostringstream os; - os << "TupleUnion::normalize(): tried an illegal conversion: integer to " - << out->getColTypes()[i]; - throw logic_error(os.str()); - } - break; case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: switch (out->getColTypes()[i]) { @@ -607,9 +474,7 @@ dec2: uint64_t val = in.getIntField(i); } break; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { + case CalpontSystemCatalog::DOUBLE: { double val = (in.getColTypes()[i] == CalpontSystemCatalog::FLOAT ? in.getFloatField(i) : in.getDoubleField(i)); @@ -620,22 +485,13 @@ dec2: uint64_t val = in.getIntField(i); case CalpontSystemCatalog::INT: case CalpontSystemCatalog::BIGINT: if (out->getScale(i)) - goto dec3; + goto dec2; out->setIntField((int64_t) val, i); break; - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - out->setUintField((uint64_t) val, i); - break; case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: out->setFloatField(val, i); break; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: out->setDoubleField(val, i); break; case CalpontSystemCatalog::CHAR: @@ -646,10 +502,9 @@ dec2: uint64_t val = in.getIntField(i); out->setStringField(os.str(), i); break; } - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { -dec3: /* have to pick a scale to use for the double. using 5... */ - uint32_t scale = 5; + case CalpontSystemCatalog::DECIMAL: { +dec2: /* have to pick a scale to use for the double. using 5... */ + uint scale = 5; uint64_t ival = (uint64_t) (double) (val * pow((double) 10, (double) scale)); int diff = out->getScale(i) - scale; if (diff < 0) @@ -667,10 +522,9 @@ dec2: uint64_t val = in.getIntField(i); } break; } - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { + case CalpontSystemCatalog::DECIMAL: { int64_t val = in.getIntField(i); - uint32_t scale = in.getScale(i); + uint scale = in.getScale(i); switch (out->getColTypes()[i]) { case CalpontSystemCatalog::TINYINT: @@ -678,13 +532,7 @@ dec2: uint64_t val = in.getIntField(i); case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { + case CalpontSystemCatalog::DECIMAL: { if (out->getScale(i) == scale) out->setIntField(val, i); else if (out->getScale(i) > scale) @@ -694,8 +542,7 @@ dec2: uint64_t val = in.getIntField(i); break; } - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { + case CalpontSystemCatalog::FLOAT: { float fval = ((float) val) / IDB_pow[scale]; out->setFloatField(fval, i); break; @@ -709,7 +556,7 @@ dec2: uint64_t val = in.getIntField(i); case CalpontSystemCatalog::VARCHAR: default: { char buf[50]; - dataconvert::DataConvert::decimalToString(val, scale, buf, 50, out->getColTypes()[i]); + dataconvert::DataConvert::decimalToString( val, scale, buf, 50 ); /* ostringstream oss; if (scale == 0) oss << val; @@ -740,32 +587,21 @@ dec2: uint64_t val = in.getIntField(i); void TupleUnion::run() { - uint32_t i; + uint i; mutex::scoped_lock lk(jlLock); if (runRan) return; runRan = true; lk.unlock(); + + for (i = 0; i < inJSA.outSize(); i++) + inputs.push_back(inJSA.outAt(i)->rowGroupDL()); - for (i = 0; i < fInputJobStepAssociation.outSize(); i++) - inputs.push_back(fInputJobStepAssociation.outAt(i)->rowGroupDL()); - - output = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); - if (fDelivery) { + output = outJSA.outAt(0)->rowGroupDL(); + if (isDelivery) { outputIt = output->getIterator(); } - outputRG.initRow(&row); - outputRG.initRow(&row2); - - distinctCount = 0; - normalizedData.reset(new RGData[inputs.size()]); - for (i = 0; i < inputs.size(); i++) { - if (distinctFlags[i]) { - distinctCount++; - normalizedData[i].reinit(outputRG); - } - } for (i = 0; i < inputs.size(); i++) { boost::shared_ptr th(new boost::thread(Runner(this, i))); @@ -775,7 +611,7 @@ void TupleUnion::run() void TupleUnion::join() { - uint32_t i; + uint i; mutex::scoped_lock lk(jlLock); Uniquer_t::iterator it; @@ -789,78 +625,67 @@ void TupleUnion::join() runners.clear(); uniquer->clear(); rowMemory.clear(); - rm.returnMemory(memUsage, sessionMemLimit); + rm.returnMemory(memUsage); memUsage = 0; } const string TupleUnion::toString() const { ostringstream oss; - oss << "TupleUnion ses:" << fSessionId << " txn:" << fTxnId << " ver:" << fVerId; - oss << " st:" << fStepId; + oss << "TupleUnion ses:" << sessionID << " txn:" << txnID << " ver:" << verID; + oss << " st:" << stepId(); oss << " in:"; - for (unsigned i = 0; i < fInputJobStepAssociation.outSize(); i++) - oss << ((i==0) ? " " : ", ") << fInputJobStepAssociation.outAt(i); + for (unsigned i = 0; i < inJSA.outSize(); i++) + oss << ((i==0) ? " " : ", ") << inJSA.outAt(i); oss << " out:"; - for (unsigned i = 0; i < fOutputJobStepAssociation.outSize(); i++) - oss << ((i==0) ? " " : ", ") << fOutputJobStepAssociation.outAt(i); + for (unsigned i = 0; i < outJSA.outSize(); i++) + oss << ((i==0) ? " " : ", ") << outJSA.outAt(i); oss << endl; return oss.str(); } -void TupleUnion::writeNull(Row *out, uint32_t col) +void TupleUnion::writeNull(Row *out, uint col) { switch (out->getColTypes()[col]) { case CalpontSystemCatalog::TINYINT: out->setUintField<1>(joblist::TINYINTNULL, col); break; case CalpontSystemCatalog::SMALLINT: out->setUintField<1>(joblist::SMALLINTNULL, col); break; - case CalpontSystemCatalog::UTINYINT: - out->setUintField<1>(joblist::UTINYINTNULL, col); break; - case CalpontSystemCatalog::USMALLINT: - out->setUintField<1>(joblist::USMALLINTNULL, col); break; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { - uint32_t len = out->getColumnWidth(col); + uint len = out->getColumnWidth(col); switch (len) { - case 1: + case 1: out->setUintField<1>(joblist::TINYINTNULL, col); break; - case 2: + case 2: out->setUintField<1>(joblist::SMALLINTNULL, col); break; case 4: out->setUintField<4>(joblist::INTNULL, col); break; case 8: out->setUintField<8>(joblist::BIGINTNULL, col); break; - default: {} + default: {} } - break; + break; } case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: out->setUintField<4>(joblist::INTNULL, col); break; - case CalpontSystemCatalog::UINT: - out->setUintField<4>(joblist::UINTNULL, col); break; - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: + case CalpontSystemCatalog::FLOAT: out->setUintField<4>(joblist::FLOATNULL, col); break; case CalpontSystemCatalog::DATE: out->setUintField<4>(joblist::DATENULL, col); break; case CalpontSystemCatalog::BIGINT: out->setUintField<8>(joblist::BIGINTNULL, col); break; - case CalpontSystemCatalog::UBIGINT: - out->setUintField<8>(joblist::UBIGINTNULL, col); break; case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: out->setUintField<8>(joblist::DOUBLENULL, col); break; case CalpontSystemCatalog::DATETIME: out->setUintField<8>(joblist::DATETIMENULL, col); break; case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: { - uint32_t len = out->getColumnWidth(col); + uint len = out->getColumnWidth(col); switch (len) { case 1: out->setUintField<1>(joblist::CHAR1NULL, col); break; case 2: out->setUintField<2>(joblist::CHAR2NULL, col); break; @@ -883,20 +708,4 @@ void TupleUnion::writeNull(Row *out, uint32_t col) } } -void TupleUnion::formatMiniStats() -{ - ostringstream oss; - oss << "TUS " - << "UM " - << "- " - << "- " - << "- " - << "- " - << "- " - << "- " - << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << " " - << fRowsReturned << " "; - fMiniInfo += oss.str(); -} - } diff --git a/dbcon/joblist/tupleunion.h b/dbcon/joblist/tupleunion.h index 60859e3a..a6df17d4 100644 --- a/dbcon/joblist/tupleunion.h +++ b/dbcon/joblist/tupleunion.h @@ -18,7 +18,7 @@ // // C++ Interface: TupleUnion // -// Description: +// Description: // // // Author: Patrick , (C) 2009 @@ -42,19 +42,35 @@ namespace joblist { - - class TupleUnion : public JobStep, public TupleDeliveryStep { public: - TupleUnion(execplan::CalpontSystemCatalog::OID tableOID, const JobInfo& jobInfo); + TupleUnion(const JobStepAssociation &in, + const JobStepAssociation &out, + execplan::CalpontSystemCatalog::OID tableOID, + uint32_t sessionID, + uint32_t txnId, + uint32_t verId, + uint16_t stepID, + uint32_t statementID, + ResourceManager& r); ~TupleUnion(); void run(); void join(); const std::string toString() const; + void stepId(uint16_t); + uint16_t stepId() const; + uint32_t sessionId() const; + uint32_t txnId() const; + uint32_t statementId() const; execplan::CalpontSystemCatalog::OID tableOid() const; + void logger(const SPJL& logger) { fLogger = logger; } + const JobStepAssociation & inputAssociation() const; + void inputAssociation(const JobStepAssociation &in); + const JobStepAssociation & outputAssociation() const; + void outputAssociation(const JobStepAssociation &out); void setInputRowGroups(const std::vector &); void setOutputRowGroup(const rowgroup::RowGroup &); @@ -62,8 +78,6 @@ class TupleUnion : public JobStep, public TupleDeliveryStep const rowgroup::RowGroup& getOutputRowGroup() const { return outputRG; } const rowgroup::RowGroup& getDeliveredRowGroup() const { return outputRG; } - void deliverStringTableRowGroup(bool b) { outputRG.setUseStringTable(b); } - bool deliverStringTableRowGroup() const { return outputRG.usesStringTable(); } // @bug 598 for self-join std::string alias1() const { return fAlias1; } @@ -76,29 +90,26 @@ class TupleUnion : public JobStep, public TupleDeliveryStep std::string view2() const { return fView2; } void view2(const std::string& vw) { fView2 = vw; } - uint32_t nextBand(messageqcpp::ByteStream &bs); - + uint nextBand(messageqcpp::ByteStream &bs); + void setIsDelivery(bool); private: - struct RowPosition - { - uint64_t group : 48; - uint64_t row : 16; - - inline RowPosition(uint64_t i = 0, uint64_t j = 0) : group(i), row(j) {}; - static const uint64_t normalizedFlag = 0x800000000000ULL; // 48th bit is set - }; - - void getOutput(rowgroup::RowGroup *rg, rowgroup::Row *row, rowgroup::RGData *data); void addToOutput(rowgroup::Row *r, rowgroup::RowGroup *rg, bool keepit, - rowgroup::RGData &data); + boost::shared_array *data); void normalize(const rowgroup::Row &in, rowgroup::Row *out); - void writeNull(rowgroup::Row *out, uint32_t col); - void readInput(uint32_t); - void formatMiniStats(); + void writeNull(rowgroup::Row *out, uint col); + void readInput(uint); + JobStepAssociation inJSA; + JobStepAssociation outJSA; execplan::CalpontSystemCatalog::OID fTableOID; + uint32_t sessionID; + uint32_t txnID; + uint32_t verID; + uint16_t stepID; + uint32_t statementID; + SPJL fLogger; // @bug 598 for self-join std::string fAlias1; std::string fAlias2; @@ -106,57 +117,50 @@ class TupleUnion : public JobStep, public TupleDeliveryStep std::string fView1; std::string fView2; + bool isDelivery; + rowgroup::RowGroup outputRG; std::vector inputRGs; std::vector inputs; RowGroupDL *output; - uint32_t outputIt; + uint outputIt; struct Runner { TupleUnion *tu; - uint32_t index; - Runner(TupleUnion *t, uint32_t in) : tu(t), index(in) { } + uint index; + Runner(TupleUnion *t, uint in) : tu(t), index(in) { } void operator()() { tu->readInput(index); } }; std::vector > runners; struct Hasher { TupleUnion *ts; - utils::Hasher_r h; + utils::Hasher h; Hasher(TupleUnion *t) : ts(t) { } - uint64_t operator()(const RowPosition &) const; + uint64_t operator()(const uint8_t *) const; }; struct Eq { TupleUnion *ts; Eq(TupleUnion *t) : ts(t) { } - bool operator()(const RowPosition &, const RowPosition &) const; + bool operator()(const uint8_t *, const uint8_t *) const; }; - - typedef std::tr1::unordered_set > Uniquer_t; + typedef std::tr1::unordered_set > Uniquer_t; boost::scoped_ptr uniquer; - std::vector rowMemory; + std::vector > rowMemory; boost::mutex sMutex, uniquerMutex; uint64_t memUsage; - uint32_t rowLength; - rowgroup::Row row, row2; + uint rowLength; std::vector distinctFlags; ResourceManager& rm; - utils::STLPoolAllocator allocator; - boost::scoped_array normalizedData; + utils::STLPoolAllocator allocator; - uint32_t runnersDone; - uint32_t distinctCount; - uint32_t distinctDone; - - uint64_t fRowsReturned; + uint runnersDone; // temporary hack to make sure JobList only calls run, join once boost::mutex jlLock; bool runRan, joinRan; - - boost::shared_ptr sessionMemLimit; }; } diff --git a/dbcon/joblist/tuplewsdl.cpp b/dbcon/joblist/tuplewsdl.cpp new file mode 100644 index 00000000..7c1be6b2 --- /dev/null +++ b/dbcon/joblist/tuplewsdl.cpp @@ -0,0 +1,413 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: tuplewsdl.cpp 8476 2012-04-25 22:28:15Z xlou $ + * + *****************************************************************************/ + +#include +#include + +#include "tuplewsdl.h" +#include "configcpp.h" + +#ifndef O_BINARY +# define O_BINARY 0 +#endif +#ifndef O_DIRECT +# define O_DIRECT 0 +#endif +#ifndef O_LARGEFILE +# define O_LARGEFILE 0 +#endif +#ifndef O_NOATIME +# define O_NOATIME 0 +#endif + +using namespace std; +using namespace config; + +namespace joblist { +extern const string defaultTempDiskPath; // defined in resourcemanager.cpp + //const uint64_t defaultInitialCapacity = 1 * 1024*1024; // 1M + +TupleWSDL::TupleWSDL(uint64_t nm, uint64_t maxSize, ResourceManager& rm) : + DataList(), + fRm(rm), + fData(0), + fNumConsumers(nm), + fMaxSize(maxSize), + fItIndex(0), + fCapacity(rm.getTwInitialCapacity()), + fCurPos(0), + fRidSize(0), + fDataSize(0), + fTupleSize(0), + fTotSize(0), + fMultipleProducers(false), + fLoadedSet(0), + fSetCount(1), + fInitialSetCnt(0), + fLoadedSetCount(0), + fFilenameCounter(1), + fSaveSize(0), + fPath(rm.getScTempDiskPath()), + fPhase(PRODUCTION), + fWaitingConsumers(0), + fTraceOn(false) +{ +// config::Config *config = config::Config::makeConfig(); +// fPath = config->getConfig("SystemConfig", "TempDiskPath"); +// if (fPath.length() == 0) +// fPath = defaultTempDiskPath; +// +// string capacity; +// capacity = config->getConfig("TupleWSDL", "InitialCapacity"); +// if (capacity.length() == 0) +// fCapacity = defaultInitialCapacity; +// else +// fCapacity = Config::uFromText(capacity); + + //pthread_cond_init(&fConsumePhase, NULL); + //pthread_cond_init(&fNextSetLoaded, NULL); + + fIters = new uint64_t [fNumConsumers]; + TDEBUG << "TupleWSDL: " << "capacity=" << fCapacity << " maxsize=" << fMaxSize << endl; +} + +TupleWSDL::~TupleWSDL() +{ + delete [] fData; + delete [] fIters; + //pthread_cond_destroy(&fConsumePhase); + //pthread_cond_destroy(&fNextSetLoaded); + removeFile(); +} + +void TupleWSDL::setNumConsumers(uint nc) +{ + resetNumConsumers(nc); +} + +void TupleWSDL::resetNumConsumers(uint nc) +{ + if (fItIndex != 0) + throw logic_error("TupleWSDL::resetNumConsumers(): attempt to change numConsumers " + "after iterators have been issued"); + fNumConsumers = nc; + delete [] fIters; + fIters = new uint64_t [fNumConsumers]; +} + +uint64_t TupleWSDL::getIterator() +{ + if (fItIndex >= fNumConsumers) + { + ostringstream oss; + oss << "getIterator::getIterator(): caller attempted to grab too many iterators: " << + "have " << fNumConsumers << " asked for " << (fItIndex + 1); + throw logic_error(oss.str().c_str()); + } + fIters[fItIndex] = 0; + return fItIndex++; +} + +void TupleWSDL::insert(const vector &v) +{ + throw logic_error("TupleWSDL insert vector is not implemented"); +} + +//----------------------------------------------------------------------- +// This is different from wsdl logic. This will not save the in-memory +// set at end of input, no matter this is the only set or not. +//----------------------------------------------------------------------- +void TupleWSDL::endOfInput() +{ + base::lock(); + fInitialSetCnt = fSetCount; + if (fLoadedSet > 0) + { + fLoadedSet = 0; + } + + resetIterators(); + + base::endOfInput(); + fPhase = CONSUMPTION; + fConsumePhase.notify_all(); //pthread_cond_broadcast(&fConsumePhase); + base::unlock(); +} + +void TupleWSDL::tupleSize (const uint64_t ridSize, const uint64_t dataSize) +{ + fRidSize = ridSize; + fDataSize = dataSize; + fTupleSize = ridSize + dataSize; + TDEBUG << "<<getFilename(); + fd = open(fFilename.c_str(), O_CREAT | O_RDWR | O_EXCL | O_BINARY, 0666); + } while (fd < 0 && errno == EEXIST); + + if (fd < 0) + { + ostringstream errmsg; + errmsg << "TupleWSDL::createTempFile(): could not save to disk (" + << errno << ") - " << strerror(errno); + cerr << errmsg.str() << endl; + throw runtime_error(errmsg.str()); + } + + close(fd); + + //cout << "Creating/opening file: " << fFilename << endl; + fFile.open(fFilename.c_str(), ios_base::in | ios_base::out | ios_base::binary ); + if (!(fFile.is_open())) + { + perror("open"); + throw runtime_error("LDL: open() failed"); + } +} + + +uint64_t TupleWSDL::save() +{ + uint64_t nBytesWritten=0; + + try { + //...Create the temporary LDL file (if necessary) + if ( fFilename.empty() ) + createTempFile(); + + // Save our file offset for this set, to be used when we load the set. + fstream::pos_type firstByte = fFile.tellp(); + fSetStartPositions.push_back( firstByte ); + TDEBUG << "Saving " << fFilename << "; count-" << fCurPos << + "; tellp-" << fFile.tellp() << endl; + + DiskIoInfo info(true); + if (fTraceOn) info.fStart = boost::posix_time::microsec_clock::local_time(); + + // write size + fFile.write((char*) &fCurPos, sizeof(fCurPos)); + + // write data + fFile.write(fData, fCurPos); + nBytesWritten = fFile.tellp() - firstByte; + fCurPos = 0; + + if (fTraceOn) + { + info.fEnd= boost::posix_time::microsec_clock::local_time(); + info.fBytes = nBytesWritten; + fDiskIoList.push_back(info); + } + } + catch(...) + { + delete [] fData; + if (fFile.is_open()) + fFile.close(); + cerr << "Error occurred saving contiguous Tuple array " + "into file " << fFilename << endl; + throw; + } + + return nBytesWritten; +} + +void TupleWSDL::load(uint64_t setNumber, bool append) +{ + uint64_t prevPos = fCurPos; + + if (fLoadedSetCount != 0 && fLoadedSet == setNumber && fPhase != PRODUCTION) + { + resetIterators(); + return; + } + + try + { + // Position the file to the correct file offset for this set. +// fFile.seekg( fSetStartPositions.at(setNumber) ); + if (setNumber == 0) + fFile.seekg(0); + + TDEBUG << "Loading filename-" << fFilename << + "; set-" << setNumber << "; fPos-" << + fSetStartPositions.at(setNumber) << endl; + + DiskIoInfo info; + if (fTraceOn) info.fStart = boost::posix_time::microsec_clock::local_time(); + streampos startPos = fFile.tellg(); + + fFile.read((char *) &fCurPos, sizeof(fCurPos)); + + if (append) + { + if (fCapacity - prevPos < fCurPos) + { + char* tmp = new char[fCapacity*2]; + memcpy(tmp, fData, fCapacity); + fData = tmp; + fCapacity *= 2; + } + fFile.read(fData, fCurPos); + fCurPos += prevPos; + } + else + { + // array should always hold saved sets becuase they're in there before + fFile.read(fData, fCurPos); + } + + if (fTraceOn) + { + info.fEnd= boost::posix_time::microsec_clock::local_time(); + info.fBytes = fFile.tellg() - startPos; + fDiskIoList.push_back(info); + } + } + catch (...) + { + delete [] fData; + fFile.close(); + cerr << "Error occurred loading contiguous container " + "from file " << fFilename << " vector size=" << fSetStartPositions.size() << endl; + throw; + } + resetIterators(); + fLoadedSet = setNumber; + fLoadedSetCount++; + + //...Close the file once all the sets have been loaded. + if ( fLoadedSetCount == fSetStartPositions.size() ) + { + fFile.close(); + } +} + +inline void TupleWSDL::waitForConsumePhase() +{ + base::lock(); + + while (fPhase == PRODUCTION) + { + fConsumePhase.wait(this->mutex); //pthread_cond_wait(&fConsumePhase, &(this->mutex)); + } + base::unlock(); +} + +void TupleWSDL::registerNewSet() +{ + fLoadedSet++; + fSetCount++; +} + +uint64_t TupleWSDL::totalSize() +{ + waitForConsumePhase(); + return fTotSize; +} + +uint64_t TupleWSDL::saveSize() +{ + waitForConsumePhase(); + return fSaveSize; +} + +bool TupleWSDL::totalDiskIoTime(uint64_t& w, uint64_t& r) +{ + boost::posix_time::time_duration wTime(0,0,0,0); + boost::posix_time::time_duration rTime(0,0,0,0); + bool diskIo = false; + + list::iterator k = fDiskIoList.begin(); + while (k != fDiskIoList.end()) + { + if (k->fWrite == true) + wTime += k->fEnd - k->fStart; + else + rTime += k->fEnd - k->fStart; + k++; + } + + w = wTime.total_seconds(); + r = rTime.total_seconds(); + + return diskIo; +} + +list& TupleWSDL::diskIoInfoList() +{ + return fDiskIoList; +} + +} //namespace + diff --git a/dbcon/joblist/tuplewsdl.h b/dbcon/joblist/tuplewsdl.h new file mode 100644 index 00000000..0ecba77d --- /dev/null +++ b/dbcon/joblist/tuplewsdl.h @@ -0,0 +1,370 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: tuplewsdl.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + *****************************************************************************/ + +/** @file */ + +#include +#include +#include +#include + +#include "datalist.h" +#include "elementtype.h" +#include "resourcemanager.h" + +#ifndef _TUPLEWSDL_HPP_ +#define _TUPLEWSDL_HPP_ + +/** Debug macro */ +#define TW_DEBUG 0 +#if TW_DEBUG +#define TDEBUG std::cout +#else +#define TDEBUG if (false) std::cout +#endif + +namespace joblist { + +#ifndef _DISKIOINFO__ +#define _DISKIOINFO__ +struct DiskIoInfo +{ + boost::posix_time::ptime fStart; + boost::posix_time::ptime fEnd; + uint64_t fBytes; + bool fWrite; + + // c: byte count; b: is write operation? + DiskIoInfo(bool b = false) : fBytes(0), fWrite(b) {} +}; +#endif //_DISKIOINFO__ + +/** @brief class TupleWSDL + * + * Working set datalist for TupleType + */ +class TupleWSDL : public DataList +{ + typedef DataList base; + + public: + enum Phase + { + PRODUCTION = 0, + CONSUMPTION + }; + + /** @brief Constructor */ + TupleWSDL(uint64_t numConsumers, uint64_t maxSize, ResourceManager& rm); + + /** @brief Destructor */ + virtual ~TupleWSDL(); + + /** @brief insert to datalist + * + * @param e reference of insert tuple element + */ + inline virtual void insert( const TupleType &e); + + /** @brief insert to datalist without locking + * + * @param e reference of insert tuple element + */ + //void insert_nolock(const TupleType &e) + inline void insert_nolock(TupleType &e); + + /** @brief insert a vector of e to datalist + * + * @param v reference of insert tuple vector + */ + inline virtual void insert(const std::vector &v); + + /** @brief get iterator for consumer + * + * @return consumer id + */ + virtual uint64_t getIterator(); + + /** @brief get next element from datalist + * + * @param it consumer id + * @param e pointer of read back tuple + */ + inline virtual bool next(uint64_t id, TupleType *e); + + /** @brief end of input to datalist */ + virtual void endOfInput(); + + /** @brief set number of consumers */ + void setNumConsumers(uint); + + /** @brief get number of consumers */ + uint getNumConsumers() const { return fNumConsumers; } + + /** @brief reset number of consumers */ + void resetNumConsumers(uint numConsumers); + + /** @brief return datalist total size */ + virtual uint64_t totalSize(); + + /** @brief set multiple producers flag */ + virtual void setMultipleProducers(bool m) {fMultipleProducers = m;} + + /** @brief return the number of temp files generated */ + uint64_t numberOfTempFiles() const; + + /** @brief return tuple size (rid+data) */ + const uint64_t tupleSize() const {return fTupleSize;} + + /** @set tuple size */ + void tupleSize(const uint64_t ridSize, const uint64_t dataSize); + + /** @brief return initial set count before merges */ + uint64_t initialSetCount() const { return fInitialSetCnt; } + + /** @brief return the save size of datalist. */ + uint64_t saveSize(); + + /** @brief returns the disk I/O time in seconds */ + bool totalDiskIoTime(uint64_t& w, uint64_t& r); + + /** @brief returns the reference of the disk I/O info list */ + std::list& diskIoInfoList(); + + /** @brief set trace flag */ + void traceOn(bool b) { fTraceOn = b; } + + /** @brief get diskiolist */ + std::list& diskIoList() { return fDiskIoList; } + protected: + /** @brief reset read offset for all consumers */ + void resetIterators(); + + /** @brief delete datalist data structure */ + void shrink(); + + /** @brief load set from disk to memory + * @param setNumber the set number being loaded + * @param append append to in memory set or not (ZDL set append true) + */ + void load(uint64_t setNumber, bool append = false); + + /** @brief save the in memory set to disk */ + uint64_t save(); + + /** @brief register a new saved set by bookkeeping */ + void registerNewSet(); + + /** @brief get save file name */ + std::string getFilename(); + + /** @brief wait until consumption phase starts */ + void waitForConsumePhase(); + + /** @brief read next tuple from the byte array + * @param it iterator id + * @param e pointer of read back tuple + */ + inline bool read(uint64_t id, TupleType *e); + + /** @brief create a temp file to save */ + void createTempFile(); + + /** @brief remove all temp filess of this datalist */ + void removeFile(); + + private: + /** @brief constructor/assignment op for completeness */ + explicit TupleWSDL(); + TupleWSDL(const TupleWSDL &dl); + TupleWSDL& operator=(const TupleWSDL &dl); + + ResourceManager& fRm; + char* fData; + uint64_t* fIters; + uint64_t fNumConsumers; + uint64_t fMaxSize; // max size in array before saving + uint64_t fItIndex; + uint64_t fCapacity; // array pre-allocated size + uint64_t fCurPos; // in memory array current write offset + uint64_t fRidSize; + uint64_t fDataSize; + uint64_t fTupleSize; + uint64_t fTotSize; + bool fMultipleProducers; + + uint64_t fLoadedSet; + uint64_t fSetCount; + uint64_t fInitialSetCnt; + uint64_t fLoadedSetCount; + uint64_t fFilenameCounter; + uint64_t fSaveSize; + std::string fPath; + std::string fFilename; + std::fstream fFile; + std::vector fSetStartPositions; + + int64_t fPhase; + uint64_t fWaitingConsumers; + boost::condition fNextSetLoaded; + boost::condition fConsumePhase; + + std::list fDiskIoList; + bool fTraceOn; + +}; + +void TupleWSDL::insert( const TupleType &e) +{ + if (fMultipleProducers) + base::lock(); + insert_nolock(const_cast(e)); + if (fMultipleProducers) + base::unlock(); +} + +void TupleWSDL::insert_nolock(TupleType &e) +{ + // lazy allocation + if (!fData) + fData = new char [fCapacity]; + + // check if need to save + if (fMaxSize - fCurPos < fTupleSize) + { + TDEBUG << "TupleWSDL-" << this << " full and save: " << fCurPos << std::endl; + fSaveSize += save(); + registerNewSet(); + TDEBUG << "setcount=" << fSetCount << std::endl; + fCurPos = 0; + } + + // check if need expand memory + else if (fCapacity - fCurPos < fTupleSize) + { + fCapacity *= 2; + TDEBUG << "TupleWSDL-" << this << " expand array to " << fCapacity << std::endl; + char *tmp = new char[fCapacity]; + memcpy(tmp, fData, fCurPos); + fData = tmp; + } + + // insert + fTotSize++; + switch(fRidSize) + { + case 4: + memcpy(fData + fCurPos, &e.first, 4); + break; + case 8: + memcpy(fData + fCurPos, &e.first, 8); + break; + default: + memcpy(fData + fCurPos, &e.first, fRidSize); + } + memcpy(fData + fCurPos + fRidSize, e.second, fDataSize); + fCurPos += fTupleSize; + e.deleter(); +} + +bool TupleWSDL::next(uint64_t id, TupleType *e) +{ + bool ret, locked = false; + uint64_t nextSet; + + if (fPhase == PRODUCTION) { + locked = true; + base::lock(); + waitForConsumePhase(); + } + + ret = read(id, e); + + if (ret == false && (fLoadedSet < fSetCount - 1)) + { + if (!locked && (fNumConsumers > 1 || fPhase == PRODUCTION)) + { + locked = true; + base::lock(); + } + if (fLoadedSetCount == 0) + { + nextSet = 0; + fSetCount--; + } + else + nextSet = fLoadedSet + 1; + + fWaitingConsumers++; + if (fWaitingConsumers < fNumConsumers) + { + while (nextSet != fLoadedSet || fLoadedSetCount == 0) + { + fNextSetLoaded.wait(this->mutex); //pthread_cond_wait(&fNextSetLoaded, &(this->mutex)); + } + } + else + { + load(nextSet); + fNextSetLoaded.notify_all(); //pthread_cond_broadcast(&fNextSetLoaded); + } + fWaitingConsumers--; + ret = read(id, e); + } + + if (ret == false && ++base::consumersFinished == fNumConsumers) + { + shrink(); + removeFile(); + } + if (locked) + base::unlock(); + + return ret; +} + +bool TupleWSDL::read(uint64_t id, TupleType *e) +{ + if ( !fData || fIters[id] == fCurPos ) + return false; + + e->first = 0; + switch (fRidSize) + { + case 4: + memcpy(&e->first, fData+fIters[id], 4); + break; + case 8: + memcpy(&e->first, fData+fIters[id], 8); + break; + default: + memcpy(&e->first, fData+fIters[id], fRidSize); + } + + e->second = fData + fIters[id] + fRidSize; + fIters[id] += fTupleSize; + return true; +} + +} //namespace + +#endif diff --git a/dbcon/joblist/unionstep.cpp b/dbcon/joblist/unionstep.cpp new file mode 100644 index 00000000..57ba8902 --- /dev/null +++ b/dbcon/joblist/unionstep.cpp @@ -0,0 +1,853 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/***************************************************************************** + * $Id: unionstep.cpp 8321 2012-02-15 04:11:55Z xlou $ + * + ****************************************************************************/ +#include "jobstep.h" +#include "datalist.h" +#include "calpontsystemcatalog.h" +#include "exceptclasses.h" + +#include +#include +#include + +using namespace std; +using namespace execplan; + + +namespace { +using namespace joblist; + +struct Unionizer { + UnionStep *step; + + Unionizer(UnionStep *s) : step(s) + { } + + void operator()() + { + try + { + step->doUnion(); + } + catch(const logging::LargeDataListExcept& ex) + { + cout << "unionstep: caught: " << ex.what() << endl; + step->unblockDatalists(logging::unionStepLargeDataListFileErr); + catchHandler(ex.what(), step->sessionId()); + } + catch (const exception &e) + { + cout << "unionstep: caught: " << e.what() << endl; + step->unblockDatalists(logging::unionStepErr); + catchHandler(e.what(), step->sessionId()); //throw; //@bug 632 + } + catch (...) + { + string msg("Unionstep caught something not an exception!"); + cout << msg << endl; + step->unblockDatalists(logging::unionStepErr); + catchHandler(msg); //throw; //@bug 632 + } + } +}; +}; + +namespace joblist { + +UnionStep::UnionStep(const JobStepAssociation& in, const JobStepAssociation& out, + CalpontSystemCatalog::OID tableOID, + uint32_t session, + uint32_t txn, + uint32_t ver, + uint16_t step, + uint32_t statement) : JobStep(), + inJSA(in), + outJSA(out), + fTableOID(tableOID), + sessionID(session), + txnID(txn), + verID(ver), + stepID(step), + statementID(statement), + inputSize(0), + outputSize(0), + fAlias1(), + fAlias2(), + fTimeSet() +{ +} + +UnionStep::~UnionStep() +{ + +} + +const JobStepAssociation & UnionStep::inputAssociation() const +{ + return inJSA; +} + +void UnionStep::inputAssociation(const JobStepAssociation &in) +{ + inJSA = in; +} + +const JobStepAssociation & UnionStep::outputAssociation() const +{ + return outJSA; +} + +void UnionStep::outputAssociation(const JobStepAssociation &out) +{ + outJSA = out; +} + +void UnionStep::join() +{ + runner->join(); +} + +const string UnionStep::toString() const +{ + DataList_t* dl = outJSA.outAt(0)->dataList(); + ostringstream oss; + oss << "UnionStep ses:" << sessionID << " txn:" << txnID << " ver:" << verID; + oss << " st:" << stepId() << " tb/col:" << fTableOID << "/" << dl->OID(); + oss << " " << omitOidInDL + << outJSA.outAt(0) << showOidInDL; + oss << " alias1: " << ((fAlias1.length()) ? fAlias1 : "none"); + oss << " alias2: " << ((fAlias2.length()) ? fAlias2 : "none"); + oss << " in:"; + for (unsigned i = 0; i < inJSA.outSize(); i++) + { + oss << inJSA.outAt(i) << ", "; + } + + return oss.str(); +} + +void UnionStep::stepId(uint16_t id) +{ + stepID = id; +} + +uint16_t UnionStep::stepId() const +{ + return stepID; +} + +uint32_t UnionStep::sessionId() const +{ + return sessionID; +} + +uint32_t UnionStep::txnId() const +{ + return txnID; +} + +uint32_t UnionStep::statementId() const +{ + return statementID; +} + +CalpontSystemCatalog::OID UnionStep::tableOid() const +{ + return fTableOID; +} + + +void UnionStep::run() +{ + if (traceOn()) + { + syslogStartStep(16, // exemgr subsystem + string("UnionStep")); // step name + } + runner.reset(new boost::thread(Unionizer(this))); +} + + +void UnionStep::unblockDatalists(uint16_t status) +{ + outJSA.status(status); + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + StrDataList *strdlout = outJSA.outAt(0)->stringDataList(); + + if (fifo) fifo->endOfInput(); + else if (dlout) dlout->endOfInput(); + else if (strdlout) strdlout->endOfInput(); +} + + +void UnionStep::doUnion() +{ + DataList *dlIn1=inJSA.outAt(0)->dataList(); + DataList *dlIn2=inJSA.outAt(1)->dataList(); + ZDL *zdlIn1=inJSA.outAt(0)->zonedDL(); + ZDL *zdlIn2=inJSA.outAt(1)->zonedDL(); + FIFO > *fifoIn1=inJSA.outAt(0)->fifoDL(); + FIFO > *fifoIn2=inJSA.outAt(1)->fifoDL(); + + DataList *sdlIn1=inJSA.outAt(0)->strDataList(); + DataList *sdlIn2=inJSA.outAt(1)->strDataList(); + ZDL *szdlIn1=inJSA.outAt(0)->stringZonedDL(); + ZDL *szdlIn2=inJSA.outAt(1)->stringZonedDL(); + FIFO > *sfifoIn1=inJSA.outAt(0)->stringDL(); + FIFO > *sfifoIn2=inJSA.outAt(1)->stringDL(); + + if (0 < inJSA.status()) + { + unblockDatalists(inJSA.status()); + } + else + { + // make sure the input datalists are either ordered fifo or zdl + // if not, throw an exception + bool dlTypeOK = true; + if (dlIn1 != NULL) + dlTypeOK = dlTypeOK && (zdlIn1 != NULL || (fifoIn1 != NULL && fifoIn1->inOrder())); + else if (sdlIn1 != NULL) + dlTypeOK = dlTypeOK && (szdlIn1 != NULL || (sfifoIn1 != NULL && sfifoIn1->inOrder())); + + if (dlIn2 != NULL) + dlTypeOK = dlTypeOK && (zdlIn2 != NULL || (fifoIn2 != NULL && fifoIn2->inOrder())); + else if (sdlIn2 != NULL) + dlTypeOK = dlTypeOK && (szdlIn2 != NULL || (sfifoIn2 != NULL && sfifoIn2->inOrder())); + + if (dlTypeOK == false) + throw logic_error("UnionStep: input datalist is not ZDL or ordered FIFO."); + + // input lists are fifo + if (fifoIn1 != NULL && fifoIn2 != NULL) + unionByOrderedFifo(fifoIn1, fifoIn2); + else if (sfifoIn1 != NULL && sfifoIn2 != NULL) + unionByOrderedFifo(sfifoIn1, sfifoIn2); + else if (fifoIn1 != NULL && sfifoIn2 != NULL) + unionByOrderedFifo(fifoIn1, sfifoIn2); + else if (sfifoIn1 != NULL && fifoIn2 != NULL) + unionByOrderedFifo(sfifoIn1, fifoIn2); + + // input lists are zdl + else if (zdlIn1 != NULL && zdlIn2 != NULL) + unionByZdl(zdlIn1, zdlIn2); + else if (sdlIn1 != NULL && sdlIn2 != NULL) + unionByZdl(szdlIn1, szdlIn2); + else if (dlIn1 != NULL && szdlIn2 != NULL) + unionByZdl(zdlIn1, szdlIn2); + else if (sdlIn1 != NULL && zdlIn2 != NULL) + unionByZdl(szdlIn1, zdlIn2); + + // one is fifo, the other is zdl + else if (fifoIn1 != NULL && zdlIn2 != NULL) + unionByMixedDl(fifoIn1, zdlIn2); + else if (fifoIn1 != NULL && szdlIn2 != NULL) + unionByMixedDl(fifoIn1, szdlIn2); + else if (sfifoIn1 != NULL && zdlIn2 != NULL) + unionByMixedDl(sfifoIn1, zdlIn2); + else if (sfifoIn1 != NULL && szdlIn2 != NULL) + unionByMixedDl(sfifoIn1, szdlIn2); + else if (fifoIn2 != NULL && zdlIn1 != NULL) + unionByMixedDl(fifoIn2, zdlIn1); + else if (fifoIn2 != NULL && szdlIn1 != NULL) + unionByMixedDl(fifoIn2, szdlIn1); + else if (sfifoIn2 != NULL && zdlIn1 != NULL) + unionByMixedDl(sfifoIn2, zdlIn1); + else // (sfifoIn2 != NULL && szdlIn1 != NULL) + unionByMixedDl(sfifoIn2, szdlIn1); + }// else inJSA.status == 0 + + if (traceOn()) + { + ostringstream oss; + oss << "ses:" << sessionID << " st: " << stepID + << " finished at " << dlTimes.EndOfInputTimeString() + << "; input size-" << inputSize << "; output size-" << outputSize << endl + << "\t1st read " << dlTimes.FirstReadTimeString() + << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" << + JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << "s" + << endl << "\tWork times: " << mergeTime << fTimeSet.totalTime(mergeTime) << " " + << insertTime << fTimeSet.totalTime(insertTime) + << ",s\n\tJob completion status " << outJSA.status() << endl; + + logEnd(oss.str().c_str()); + + syslogProcessingTimes(16, // exemgr subsystem + dlTimes.FirstReadTime(), // first datalist read + dlTimes.LastReadTime(), // last datalist read + dlTimes.FirstReadTime(), // first datalist write(use 1st read) + dlTimes.LastInsertTime()); // last (endOfInput) datalist write + syslogEndStep(16, // exemgr subsystem + 0, // no blocked datalist input to report + 0); // no blocked datalist input to report + } +} + +template +void UnionStep::unionByOrderedFifo(FIFO *dl1, FIFO *dl2) +{ + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + + if (fifo) + { + element1_t rw1; + element2_t rw2; + RowWrapper rw3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &rw2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0, j=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2 && !die) + { + if (rw1.et[i].first < rw2.et[j].first) + { + rw3.et[rw3.count++].first = rw1.et[i++].first; + } + else if (rw1.et[i].first > rw2.et[j].first) + { + rw3.et[rw3.count++].first = rw2.et[j++].first; + } + else + { + rw3.et[rw3.count++].first = rw1.et[i].first; + ++i; + ++j; + ++inputSize; + } + + ++inputSize; + + if (rw3.count == rw3.ElementsPerGroup) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + fTimeSet.holdTimer(insertTime); + } + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + if (j == rw2.count) + { + more2 = dl2->next(id2, &rw2); + j = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + + fTimeSet.setTimer(insertTime); + while (more1 && !die) + { + ++inputSize; + rw3.et[rw3.count++].first = rw1.et[i++].first; + if (rw3.count == rw3.ElementsPerGroup) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + + while (more2 && !die) + { + ++inputSize; + rw3.et[rw3.count++].first = rw2.et[j++].first; + if (rw3.count == rw3.ElementsPerGroup) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + + if (j == rw2.count) + { + more2 = dl2->next(id2, &rw2); + j = 0; + } + } + + if (rw3.count > 0) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + fTimeSet.holdTimer(insertTime); + + dlTimes.setLastReadTime(); + + fifo->totalSize(outputSize); + + fifo->endOfInput(); + dlTimes.setEndOfInputTime(); + } + + else + { + element1_t rw1; + element2_t rw2; + ElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &rw2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0, j=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2 && !die) + { + if (rw1.et[i].first < rw2.et[j].first) + { + e3.first = rw1.et[i++].first; + } + else if (rw1.et[i].first > rw2.et[j].first) + { + e3.first = rw2.et[j++].first; + } + else + { + e3.first = rw1.et[i].first; + ++i; + ++j; + ++inputSize; + } + + dlout->insert(e3); + ++inputSize; + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + if (j == rw2.count) + { + more2 = dl2->next(id2, &rw2); + j = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + fTimeSet.setTimer(insertTime); + while (more1 && !die) + { + while (i < rw1.count) + { + ++inputSize; + e3.first = rw1.et[i++].first; + dlout->insert(e3); + } + more1 = dl1->next(id1, &rw1); + i = 0; + } + + while (more2 && !die) + { + while (j < rw2.count) + { + ++inputSize; + e3.first = rw2.et[j++].first; + dlout->insert(e3); + } + more2 = dl2->next(id2, &rw2); + j = 0; + } + fTimeSet.setTimer(insertTime, false); + + dlTimes.setLastReadTime(); + + dlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = dlout->totalSize(); + } +} + + +template +void UnionStep::unionByZdl(ZDL *dl1, ZDL *dl2) +{ + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + + if (fifo) + { + element1_t e1; + element2_t e2; + RowWrapper rw3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &e1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + fTimeSet.setTimer(mergeTime); + while (more1 && more2 && !die) + { + if (e1.first < e2.first) + { + rw3.et[rw3.count++].first = e1.first; + more1 = dl1->next(id1, &e1); + } + else if (e1.first > e2.first) + { + rw3.et[rw3.count++].first = e2.first; + more2 = dl2->next(id2, &e2); + } + else + { + rw3.et[rw3.count++].first = e1.first; + ++inputSize; + more1 = dl1->next(id1, &e1); + more2 = dl2->next(id2, &e2); + } + + ++inputSize; + + if (rw3.count == rw3.ElementsPerGroup) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + fTimeSet.holdTimer(insertTime); + } + } + fTimeSet.setTimer(mergeTime,false); + fTimeSet.setTimer(insertTime); + while (more1 && !die) + { + ++inputSize; + rw3.et[rw3.count++].first = e1.first; + if (rw3.count == rw3.ElementsPerGroup) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + + more1 = dl1->next(id1, &e1); + } + + while (more2 && !die) + { + ++inputSize; + rw3.et[rw3.count++].first = e2.first; + if (rw3.count == rw3.ElementsPerGroup) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + + more2 = dl2->next(id2, &e2); + } + + // no more input + if (rw3.count > 0 && !die) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + fTimeSet.holdTimer(insertTime); + dlTimes.setLastReadTime(); + + fifo->totalSize(outputSize); + + fifo->endOfInput(); + dlTimes.setEndOfInputTime(); + } + + else + { + element1_t e1; + element2_t e2; + ElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &e1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + fTimeSet.setTimer(mergeTime); + while (more1 && more2 && !die) + { + if (e1.first < e2.first) + { + e3.first = e1.first; + more1 = dl1->next(id1, &e1); + } + else if (e1.first > e2.first) + { + e3.first = e2.first; + more2 = dl2->next(id2, &e2); + } + else + { + e3.first = e1.first; + ++inputSize; + more1 = dl1->next(id1, &e1); + more2 = dl2->next(id2, &e2); + } + + dlout->insert(e3); + ++inputSize; + } + fTimeSet.setTimer(mergeTime, false); + fTimeSet.setTimer(insertTime); + while (more1 && !die) + { + ++inputSize; + e3.first = e1.first; + dlout->insert(e3); + more1 = dl1->next(id1, &e1); + } + + while (more2 && !die) + { + ++inputSize; + e3.first = e2.first; + dlout->insert(e3); + more2 = dl2->next(id2, &e2); + } + fTimeSet.setTimer(insertTime,false); + + dlTimes.setLastReadTime(); + + dlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = dlout->totalSize(); + } +} + + +template +void UnionStep::unionByMixedDl(FIFO *dl1, ZDL *dl2) +{ + DataList *dlout = outJSA.outAt(0)->dataList(); + FIFO > *fifo = outJSA.outAt(0)->fifoDL(); + + if (fifo) + { + element1_t rw1; + element2_t e2; + RowWrapper rw3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2 && !die) + { + if (rw1.et[i].first < e2.first) + { + rw3.et[rw3.count++].first = rw1.et[i++].first; + } + else if (rw1.et[i].first > e2.first) + { + rw3.et[rw3.count++].first = e2.first; + more2 = dl2->next(id2, &e2); + } + else + { + rw3.et[rw3.count++].first = rw1.et[i++].first; + more2 = dl2->next(id2, &e2); + ++inputSize; + } + + ++inputSize; + + if (rw3.count == rw3.ElementsPerGroup) + { + fTimeSet.setTimer(insertTime); + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + fTimeSet.holdTimer(insertTime); + } + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + fTimeSet.setTimer(insertTime); + while (more1 && !die) + { + ++inputSize; + rw3.et[rw3.count++].first = rw1.et[i++].first; + if (rw3.count == rw3.ElementsPerGroup) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + + while (more2 && !die) + { + ++inputSize; + rw3.et[rw3.count++].first = e2.first; + if (rw3.count == rw3.ElementsPerGroup) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + + more2 = dl2->next(id2, &e2); + } + + if (rw3.count > 0) + { + fifo->insert(rw3); + outputSize += rw3.count; + rw3.count = 0; + } + fTimeSet.holdTimer(insertTime); + + dlTimes.setLastReadTime(); + + fifo->totalSize(outputSize); + + fifo->endOfInput(); + dlTimes.setEndOfInputTime(); + } + + else + { + element1_t rw1; + element2_t e2; + ElementType e3; + + int id1 = dl1->getIterator(); + int id2 = dl2->getIterator(); + + bool more1 = dl1->next(id1, &rw1); + bool more2 = dl2->next(id2, &e2); + + dlTimes.setFirstReadTime(); + + uint64_t i=0; + fTimeSet.setTimer(mergeTime); + while (more1 && more2 && !die) + { + if (rw1.et[i].first < e2.first) + { + e3.first = rw1.et[i++].first; + } + else if (rw1.et[i].first > e2.first) + { + e3.first = e2.first; + more2 = dl2->next(id2, &e2); + } + else + { + e3.first = e2.first; + more2 = dl2->next(id2, &e2); + ++i; + ++inputSize; + } + + dlout->insert(e3); + ++inputSize; + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + fTimeSet.setTimer(mergeTime, false); + fTimeSet.setTimer(insertTime); + while (more1 && !die) + { + ++inputSize; + e3.first = rw1.et[i++].first; + dlout->insert(e3); + + if (i == rw1.count) + { + more1 = dl1->next(id1, &rw1); + i = 0; + } + } + + while (more2 && !die) + { + ++inputSize; + e3.first = e2.first; + dlout->insert(e3); + more2 = dl2->next(id2, &e2); + } + fTimeSet.setTimer(insertTime,false); + dlTimes.setLastReadTime(); + + dlout->endOfInput(); + dlTimes.setEndOfInputTime(); + + outputSize = dlout->totalSize(); + } +} + +}; //namespace diff --git a/dbcon/joblist/unique32generator.cpp b/dbcon/joblist/unique32generator.cpp index 681f0d8e..00f2bce0 100644 --- a/dbcon/joblist/unique32generator.cpp +++ b/dbcon/joblist/unique32generator.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: unique32generator.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: unique32generator.cpp 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ diff --git a/dbcon/joblist/unique32generator.h b/dbcon/joblist/unique32generator.h index 88f61af4..c4cee7da 100644 --- a/dbcon/joblist/unique32generator.h +++ b/dbcon/joblist/unique32generator.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: unique32generator.h 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: unique32generator.h 8436 2012-04-04 18:18:21Z rdempsey $ * *****************************************************************************/ diff --git a/dbcon/joblist/virtualtable.cpp b/dbcon/joblist/virtualtable.cpp index e0ce9590..b063c814 100644 --- a/dbcon/joblist/virtualtable.cpp +++ b/dbcon/joblist/virtualtable.cpp @@ -33,7 +33,6 @@ using namespace logging; #include "returnedcolumn.h" #include "aggregatecolumn.h" -#include "windowfunctioncolumn.h" #include "arithmeticcolumn.h" #include "constantcolumn.h" #include "functioncolumn.h" @@ -58,26 +57,25 @@ void VirtualTable::initialize() } -void VirtualTable::addColumn(const SRCP& column) +void VirtualTable::addColumn(const SRCP& column, const string& view) { // As of bug3695, make sure varbinary is not used in subquery. if (column->resultType().colDataType == CalpontSystemCatalog::VARBINARY && !fVarBinOK) throw runtime_error ("VARBINARY in subquery is not supported."); - AggregateColumn* agc = NULL; - ArithmeticColumn* arc = NULL; - ConstantColumn* cc = NULL; - FunctionColumn* fc = NULL; - SimpleColumn* sc = NULL; - WindowFunctionColumn* wc = NULL; + AggregateColumn* agc = NULL; + ArithmeticColumn* arc = NULL; + ConstantColumn* cc = NULL; + FunctionColumn* fc = NULL; + SimpleColumn* sc = NULL; + SRCP nc; string columnName; + string viewName(view); ostringstream oss; UniqId colId; if ((sc = dynamic_cast(column.get())) != NULL) { - if (sc->schemaName().empty()) - sc->oid(fTableOid+sc->colPosition()+1); columnName = sc->columnName(); colId = UniqId(sc); } @@ -86,32 +84,25 @@ void VirtualTable::addColumn(const SRCP& column) // oss << agc->functionName() << "_" << agc->expressionId(); // oss << "Aggregate_" << agc->expressionId(); columnName = agc->data(); - colId = UniqId(agc->expressionId(), "", "", ""); - } - else if ((wc = dynamic_cast(column.get())) != NULL) - { -// oss << wc->functionName() << "_" << wc->expressionId(); -// oss << "Window_" << wc->expressionId(); - columnName = wc->data(); - colId = UniqId(wc->expressionId(), "", "", ""); + colId = UniqId(agc->expressionId(), agc->alias(), "", viewName); } else if ((arc = dynamic_cast(column.get())) != NULL) { // oss << "Arithmetic_" << arc->expressionId(); columnName = arc->data(); - colId = UniqId(arc->expressionId(), "", "", ""); + colId = UniqId(arc->expressionId(), arc->alias(), "", viewName); } else if ((fc = dynamic_cast(column.get())) != NULL) { // oss << fc->functionName() << "_" << fc->expressionId(); columnName = fc->data(); - colId = UniqId(fc->expressionId(), "", "", ""); + colId = UniqId(fc->expressionId(), fc->alias(), "", viewName); } else if ((cc = dynamic_cast(column.get())) != NULL) { // oss << "Constant_" << cc->expressionId(); columnName = cc->data(); - colId = UniqId(cc->expressionId(), cc->alias(), "", fView); + colId = UniqId(cc->expressionId(), cc->alias(), "", viewName); } else // new column type has added, but this code is not updated. { @@ -127,9 +118,9 @@ void VirtualTable::addColumn(const SRCP& column) vc->tableAlias(fAlias); vc->columnName(columnName); vc->alias(column->alias()); - vc->viewName(fView); + vc->viewName(viewName); - uint32_t index = fColumns.size(); + uint index = fColumns.size(); vc->colPosition(index); vc->oid(fTableOid+index+1); vc->resultType(column->resultType()); @@ -141,13 +132,13 @@ void VirtualTable::addColumn(const SRCP& column) } -const CalpontSystemCatalog::OID& VirtualTable::columnOid(uint32_t i) const +const CalpontSystemCatalog::OID& VirtualTable::columnOid(uint i) const { idbassert(i < fColumns.size()); return fColumns[i]->oid(); } -void VirtualTable::columnType(CalpontSystemCatalog::ColType& type, uint32_t i) +void VirtualTable::columnType(CalpontSystemCatalog::ColType& type, uint i) { idbassert(i < fColumnTypes.size()); fColumnTypes[i] = type; @@ -155,7 +146,7 @@ void VirtualTable::columnType(CalpontSystemCatalog::ColType& type, uint32_t i) } -const CalpontSystemCatalog::ColType& VirtualTable::columnType(uint32_t i) const +const CalpontSystemCatalog::ColType& VirtualTable::columnType(uint i) const { idbassert(i < fColumnTypes.size()); return fColumnTypes[i]; diff --git a/dbcon/joblist/virtualtable.h b/dbcon/joblist/virtualtable.h index 1b1e971f..83e26a43 100644 --- a/dbcon/joblist/virtualtable.h +++ b/dbcon/joblist/virtualtable.h @@ -37,7 +37,7 @@ class VirtualTable virtual ~VirtualTable() {} virtual void initialize(); - void addColumn(const execplan::SRCP& column); + void addColumn(const execplan::SRCP& column, const std::string& view); void tableOid(const execplan::CalpontSystemCatalog::OID& oid) { fTableOid = oid; } const execplan::CalpontSystemCatalog::OID& tableOid() const { return fTableOid; } @@ -48,18 +48,15 @@ class VirtualTable void alias(const std::string& s) { fAlias = s; } const std::string& alias() const { return fAlias; } - void view(const std::string& v) { fView = v; } - const std::string& view() const { return fView; } - const std::vector& columns() const { return fColumns; } - const execplan::CalpontSystemCatalog::OID& columnOid(uint32_t i) const; + const execplan::CalpontSystemCatalog::OID& columnOid(uint i) const; const std::vector& columnTypes() const { return fColumnTypes; } - void columnType(execplan::CalpontSystemCatalog::ColType& type, uint32_t i); - const execplan::CalpontSystemCatalog::ColType& columnType(uint32_t i) const; + void columnType(execplan::CalpontSystemCatalog::ColType& type, uint i); + const execplan::CalpontSystemCatalog::ColType& columnType(uint i) const; - const std::map& columnMap() const { return fColumnMap; } + const std::map& columnMap() const { return fColumnMap; } void varbinaryOK(bool b) { fVarBinOK = b; } bool varbinaryOK() const { return fVarBinOK; } @@ -67,12 +64,11 @@ class VirtualTable protected: execplan::CalpontSystemCatalog::OID fTableOid; std::string fName; - std::string fAlias; - std::string fView; + std::string fAlias; std::vector fColumns; std::vector fColumnTypes; - std::map fColumnMap; + std::map fColumnMap; bool fVarBinOK; }; diff --git a/dbcon/joblist/windowfunctionstep.cpp b/dbcon/joblist/windowfunctionstep.cpp deleted file mode 100644 index c6b0309d..00000000 --- a/dbcon/joblist/windowfunctionstep.cpp +++ /dev/null @@ -1,1515 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: windowfunctionstep.cpp 9681 2013-07-11 22:58:05Z xlou $ - - -//#define NDEBUG -#include -#include -#include -using namespace std; - -#include // to_upper_copy -#include -#include -#include -#include -using namespace boost; - -#include "atomicops.h" -using namespace atomicops; - -#include "loggingid.h" -#include "errorcodes.h" -#include "idberrorinfo.h" -using namespace logging; - -#include "configcpp.h" -using namespace config; - -#include "calpontselectexecutionplan.h" -#include "calpontsystemcatalog.h" -#include "aggregatecolumn.h" -#include "arithmeticcolumn.h" -#include "constantcolumn.h" -#include "functioncolumn.h" -#include "pseudocolumn.h" -#include "simplefilter.h" -#include "windowfunctioncolumn.h" -using namespace execplan; - -#include "windowfunction.h" -#include "windowfunctiontype.h" -#include "framebound.h" -#include "frameboundrange.h" -#include "frameboundrow.h" -#include "windowframe.h" -using namespace windowfunction; - -#include "rowgroup.h" -using namespace rowgroup; - -#include "idborderby.h" -using namespace ordering; - -#include "funcexp.h" -using namespace funcexp; - -#include "querytele.h" -using namespace querytele; - -#include "jlf_common.h" -#include "jobstep.h" -#include "windowfunctionstep.h" -using namespace joblist; - - -namespace -{ - -string keyName(uint64_t i, uint32_t key, const joblist::JobInfo& jobInfo) -{ - string name = jobInfo.projectionCols[i]->alias(); - if (name.empty()) - { - name = jobInfo.keyInfo->tupleKeyToName[key]; - if (jobInfo.keyInfo->tupleKeyVec[key].fId < 100) - name = "Expression/Function"; - } - - return name = "'" + name + "'"; -} - - -uint64_t getColumnIndex(const SRCP& c, const map& m, JobInfo& jobInfo) -{ - uint64_t key = getTupleKey(jobInfo, c, true); - const SimpleColumn* sc = dynamic_cast(c.get()); - if (sc != NULL && !sc->schemaName().empty()) - { - // special handling for dictionary - CalpontSystemCatalog::ColType ct = sc->colType(); -//XXX use this before connector sets colType in sc correctly. -// type of pseudo column is set by connector - if (!(dynamic_cast(sc))) - ct = jobInfo.csc->colType(sc->oid()); -//X - CalpontSystemCatalog::OID dictOid = isDictCol(ct); - string alias(extractTableAlias(sc)); - if (dictOid > 0) - { - TupleInfo ti = - setTupleInfo(ct, dictOid, jobInfo, tableOid(sc, jobInfo.csc), sc, alias); - key = ti.key; - } - } - - map::const_iterator j = m.find(key); - if (j == m.end()) - { - string name = jobInfo.keyInfo->tupleKeyToName[key]; - cerr << name << " is not in tuple, key=" << key << endl; - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_COLUMN_MISSING, name), - ERR_WF_COLUMN_MISSING); - } - - return j->second; -} - - -} - - -namespace joblist -{ - - -WindowFunctionStep::WindowFunctionStep(const JobInfo& jobInfo) : - JobStep(jobInfo), - fCatalog(jobInfo.csc), - fRowsReturned(0), - fEndOfResult(false), - fIsSelect(true), - fUseSSMutex(false), - fInputDL(NULL), - fOutputDL(NULL), - fInputIterator(-1), - fOutputIterator(-1), - fFunctionCount(0), - fTotalThreads(1), - fNextIndex(0), - fMemUsage(0), - fRm(jobInfo.rm), - fSessionMemLimit(jobInfo.umMemLimit) -{ - fTotalThreads = fRm.windowFunctionThreads(); - fExtendedInfo = "WFS: "; - fQtc.stepParms().stepType = StepTeleStats::T_WFS; -} - - -WindowFunctionStep::~WindowFunctionStep() -{ - if (fMemUsage > 0) - fRm.returnMemory(fMemUsage, fSessionMemLimit); -} - - -void WindowFunctionStep::run() -{ - if (fInputJobStepAssociation.outSize() == 0) - throw logic_error("No input data list for window function step."); - - fInputDL = fInputJobStepAssociation.outAt(0)->rowGroupDL(); - if (fInputDL == NULL) - throw logic_error("Input is not a RowGroup data list in window function step."); - - fInputIterator = fInputDL->getIterator(); - - if (fOutputJobStepAssociation.outSize() == 0) - throw logic_error("No output data list for window function step."); - - fOutputDL = fOutputJobStepAssociation.outAt(0)->rowGroupDL(); - if (fOutputDL == NULL) - throw logic_error("Output of window function step is not a RowGroup data list."); - - if (fDelivery == true) - { - fOutputIterator = fOutputDL->getIterator(); - } - - fRunner.reset(new boost::thread(Runner(this))); -} - - -void WindowFunctionStep::join() -{ - if (fRunner) - fRunner->join(); -} - - -uint32_t WindowFunctionStep::nextBand(messageqcpp::ByteStream &bs) -{ - RGData rgDataOut; - bool more = false; - uint32_t rowCount = 0; - - try - { - bs.restart(); - - more = fOutputDL->next(fOutputIterator, &rgDataOut); - - if (more && !cancelled()) - { - fRowGroupDelivered.setData(&rgDataOut); - fRowGroupDelivered.serializeRGData(bs); - rowCount = fRowGroupDelivered.getRowCount(); - } - else - { - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); - fEndOfResult = true; - } - } - catch (IDBExcept& iex) - { - handleException(iex.what(), iex.errorCode()); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); - fEndOfResult = true; - } - catch(const std::exception& ex) - { - handleException(ex.what(), ERR_IN_DELIVERY); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); - fEndOfResult = true; - } - catch(...) - { - handleException("WindowFunctionStep caught an unknown exception", ERR_IN_DELIVERY); - while (more) - more = fOutputDL->next(fOutputIterator, &rgDataOut); - fEndOfResult = true; - } - - if (fEndOfResult) - { - // send an empty / error band - rgDataOut.reinit(fRowGroupDelivered, 0); - fRowGroupDelivered.setData(&rgDataOut); - fRowGroupDelivered.resetRowGroup(0); - fRowGroupDelivered.setStatus(status()); - fRowGroupDelivered.serializeRGData(bs); - } - - return rowCount; -} - - -void WindowFunctionStep::setOutputRowGroup(const RowGroup& rg) -{ - idbassert(0); -} - - -const RowGroup& WindowFunctionStep::getOutputRowGroup() const -{ - return fRowGroupOut; -} - - -const RowGroup& WindowFunctionStep::getDeliveredRowGroup() const -{ - return fRowGroupDelivered; -} - - -void WindowFunctionStep::deliverStringTableRowGroup(bool b) -{ - fRowGroupOut.setUseStringTable(b); - fRowGroupDelivered.setUseStringTable(b); -} - - -bool WindowFunctionStep::deliverStringTableRowGroup() const -{ - idbassert(fRowGroupOut.usesStringTable() == fRowGroupDelivered.usesStringTable()); - return fRowGroupDelivered.usesStringTable(); -} - - -const string WindowFunctionStep::toString() const -{ - ostringstream oss; - oss << "WindowFunctionStep ses:" << fSessionId << " txn:" << fTxnId << " st:" << fStepId; - - oss << " in:"; - for (unsigned i = 0; i < fInputJobStepAssociation.outSize(); i++) - oss << fInputJobStepAssociation.outAt(i); - - if (fOutputJobStepAssociation.outSize() > 0) - { - oss << " out:"; - for (unsigned i = 0; i < fOutputJobStepAssociation.outSize(); i++) - oss << fOutputJobStepAssociation.outAt(i); - } - - return oss.str(); -} - -void WindowFunctionStep::checkWindowFunction(CalpontSelectExecutionPlan* csep, JobInfo& jobInfo) -{ - // window functions in select clause, selected or in expression - jobInfo.windowDels = jobInfo.deliveredCols; - for (RetColsVector::iterator i=jobInfo.windowDels.begin(); i& wcl = (*i)->windowfunctionColumnList(); - RetColsVector wcList; - for (vector::const_iterator j = wcl.begin(); j != wcl.end(); j++) - wcList.push_back(SRCP((*j)->clone())); - - if (!wcList.empty()) - { - jobInfo.windowExps.push_back(*i); - jobInfo.windowSet.insert(getTupleKey(jobInfo, *i, true)); - } - - if (dynamic_cast(i->get()) != NULL) - { - jobInfo.windowCols.push_back(*i); - jobInfo.windowSet.insert(getTupleKey(jobInfo, *i, true)); - } - else if (!wcList.empty()) - { - jobInfo.windowCols.insert(jobInfo.windowCols.end(), wcList.begin(), wcList.end()); - for (RetColsVector::const_iterator k = wcList.begin(); k < wcList.end(); k++) - { - jobInfo.windowSet.insert(getTupleKey(jobInfo, *k, true)); - } - } - } - - // window functions in order by clause - const CalpontSelectExecutionPlan::OrderByColumnList& orderByCols = csep->orderByCols(); - RetColsVector wcInOrderby; - for (uint64_t i = 0; i < orderByCols.size(); i++) - { - if (orderByCols[i]->orderPos() == (uint64_t)(-1)) - { - WindowFunctionColumn* wc = dynamic_cast(orderByCols[i].get()); - const vector& wcl = orderByCols[i]->windowfunctionColumnList(); - RetColsVector wcList; - for (vector::const_iterator j = wcl.begin(); j != wcl.end(); j++) - wcList.push_back(SRCP((*j)->clone())); - - if (wc == NULL && wcList.empty()) - continue; - - // an window function or expression of window functions - wcInOrderby.push_back(orderByCols[i]); - - if (!wcList.empty()) - { - jobInfo.windowExps.push_back(orderByCols[i]); - jobInfo.windowSet.insert(getTupleKey(jobInfo, orderByCols[i], true)); - } - - if (dynamic_cast(orderByCols[i].get()) != NULL) - { - jobInfo.windowCols.push_back(orderByCols[i]); - jobInfo.windowSet.insert(getTupleKey(jobInfo, orderByCols[i], true)); - } - else if (!wcList.empty()) - { - jobInfo.windowCols.insert( - jobInfo.windowCols.end(), wcList.begin(), wcList.end()); - for (RetColsVector::const_iterator k = wcList.begin(); k < wcList.end(); k++) - { - jobInfo.windowSet.insert(getTupleKey(jobInfo, *k, true)); - } - } - } - } - - // no window function involved in the query - if (jobInfo.windowCols.empty()) - return; - - // reconstruct the delivered column list with auxiliary columns - set colSet; - jobInfo.deliveredCols.resize(0); - for (RetColsVector::iterator i=jobInfo.windowDels.begin(); i(i->get())->getColumnList(); - for (RetColsVector::iterator j = columns.begin(); j < columns.end(); j++) - { - if (dynamic_cast(j->get()) != NULL) - continue; - - key = getTupleKey(jobInfo, *j, true); - if (colSet.find(key) == colSet.end()) - jobInfo.deliveredCols.push_back(*j); - - colSet.insert(key); - } - } - - // for handling order by and limit in outer query - jobInfo.wfqLimitStart = csep->limitStart(); - jobInfo.wfqLimitCount = csep->limitNum(); - csep->limitStart(0); - csep->limitNum(-1); - if (csep->orderByCols().size() > 0) - { - jobInfo.wfqOrderby = csep->orderByCols(); - csep->orderByCols().clear(); - - // add order by columns - for (RetColsVector::iterator i=jobInfo.wfqOrderby.begin(); i(i->get()) != NULL) - continue; - - uint64_t key = getTupleKey(jobInfo, *i, true); - if (colSet.find(key) == colSet.end()) - jobInfo.deliveredCols.push_back(*i); - - colSet.insert(key); - } - } -} - - -SJSTEP WindowFunctionStep::makeWindowFunctionStep(SJSTEP& step, JobInfo& jobInfo) -{ - // create a window function step - WindowFunctionStep* ws = new WindowFunctionStep(jobInfo); - - // connect to the feeding step - JobStepAssociation jsa; - AnyDataListSPtr spdl(new AnyDataList()); - RowGroupDL* dl = new RowGroupDL(1, jobInfo.fifoSize); - dl->OID(execplan::CNX_VTABLE_ID); - spdl->rowGroupDL(dl); - jsa.outAdd(spdl); - ws->inputAssociation(jsa); - ws->stepId(step->stepId()+1); - step->outputAssociation(jsa); - - AnyDataListSPtr spdlOut(new AnyDataList()); - RowGroupDL* dlOut = new RowGroupDL(1, jobInfo.fifoSize); - dlOut->OID(CNX_VTABLE_ID); - spdlOut->rowGroupDL(dlOut); - JobStepAssociation jsaOut; - jsaOut.outAdd(spdlOut); - ws->outputAssociation(jsaOut); - - // configure the rowgroups and index mapping - TupleDeliveryStep* ds = dynamic_cast(step.get()); - idbassert(ds != NULL); - ws->initialize(ds->getDeliveredRowGroup(), jobInfo); - - // restore the original delivery coloumns - jobInfo.deliveredCols = jobInfo.windowDels; - jobInfo.nonConstDelCols.clear(); - for (RetColsVector::iterator i=jobInfo.windowDels.begin(); i(i->get())) - jobInfo.nonConstDelCols.push_back(*i); - } - - return SJSTEP(ws); -} - - -void WindowFunctionStep::initialize(const RowGroup& rg, JobInfo& jobInfo) -{ - if (jobInfo.trace) cout << "Input to WindowFunctionStep: " << rg.toString() << endl; - - // query type decides the output by dbroot or partition - // @bug 5631. Insert select should be treated as select - fIsSelect = (jobInfo.queryType == "SELECT" || - jobInfo.queryType == "INSERT_SELECT"); - - // input row meta data - fRowGroupIn = rg; - fRowGroupIn.initRow(&fRowIn); - - // make an input map(id, index) - map colIndexMap; - uint64_t colCntIn = rg.getColumnCount(); - const vector& pos = rg.getOffsets(); - const vector& oids = rg.getOIDs(); - const vector& keys = rg.getKeys(); - const vector& types = rg.getColTypes(); - const vector& scales = rg.getScale(); - const vector& precisions = rg.getPrecision(); - for (uint64_t i = 0; i < colCntIn; i++) - colIndexMap.insert(make_pair(keys[i], i)); - - // @bug6065, window functions that will update string table - int64_t wfsUpdateStringTable = 0; - for (RetColsVector::iterator i=jobInfo.windowCols.begin(); i(i->get()); - uint64_t ridx = getColumnIndex(*i, colIndexMap, jobInfo); // result index - // @bug6065, window functions that will update string table - { - CalpontSystemCatalog::ColType rt = wc->resultType(); - if ((types[ridx] == CalpontSystemCatalog::CHAR || - types[ridx] == CalpontSystemCatalog::VARCHAR) && - rg.getColumnWidth(ridx) >= jobInfo.stringTableThreshold) - { - wfsUpdateStringTable++; - } - } - - vector fields; - fields.push_back(ridx); // result - const RetColsVector& parms = wc->functionParms(); - for (uint64_t i = 0; i < parms.size(); i++) // arguments - { - // skip constant column - if (dynamic_cast(parms[i].get()) == NULL) - fields.push_back(getColumnIndex(parms[i], colIndexMap, jobInfo)); - else - fields.push_back(-1); - } - - // partition & order by - const RetColsVector& partitions = wc->partitions(); - vector eqIdx; - vector peerIdx; - vector sorts; - for (uint64_t i = 0; i < partitions.size(); i++) - { - // skip constant column - if (dynamic_cast(partitions[i].get()) != NULL) - continue; - - // get column index - uint64_t idx = getColumnIndex(partitions[i], colIndexMap, jobInfo); - eqIdx.push_back(idx); - sorts.push_back(IdbSortSpec(idx, partitions[i]->asc(), partitions[i]->nullsFirst())); - } - - const RetColsVector& orders = wc->orderBy().fOrders; - for (uint64_t i = 0; i < orders.size(); i++) - { - // skip constant column - if (dynamic_cast(orders[i].get()) != NULL) - continue; - - // get column index - uint64_t idx = getColumnIndex(orders[i], colIndexMap, jobInfo); - peerIdx.push_back(idx); - sorts.push_back(IdbSortSpec(idx, orders[i]->asc(), orders[i]->nullsFirst())); - } - - // functors for sorting - boost::shared_ptr parts(new EqualCompData(eqIdx, rg)); - boost::shared_ptr orderbys(new OrderByData(sorts, rg)); - boost::shared_ptr peers(new EqualCompData(peerIdx, rg)); - - // column type for functor templates - int ct = 0; - // make sure index is in range - if (fields.size() > 1 && fields[1] >= 0 && static_cast(fields[1]) < types.size()) - ct = types[fields[1]]; - - // workaround for functions using "within group (order by)" syntax - string fn = boost::to_upper_copy(wc->functionName()); - if ( (fn == "MEDIAN" || fn == "PERCENTILE_CONT" || fn == "PERCENTILE_DISC") && - peerIdx[0] >= 0 && peerIdx[0] < types.size() ) - ct = types[peerIdx[0]]; - - // create the functor based on function name - boost::shared_ptr func = - WindowFunctionType::makeWindowFunction(fn, ct); - - // parse parms after peer and fields are set - // functions may need to set order column index - func->peer(peers); - func->fieldIndex(fields); - func->parseParms(parms); - - // window frame - const WF_Frame& frame = wc->orderBy().fFrame; - int frameUnit = (frame.fIsRange) ? WF__FRAME_RANGE : WF__FRAME_ROWS; - if (frame.fStart.fFrame == WF_UNBOUNDED_PRECEDING && - frame.fEnd.fFrame == WF_UNBOUNDED_FOLLOWING) - frameUnit = WF__FRAME_ROWS; - boost::shared_ptr upper = parseFrameBound( - frame.fStart, colIndexMap, orders, peers, jobInfo, !frame.fIsRange, true); - boost::shared_ptr lower = parseFrameBound( - frame.fEnd, colIndexMap, orders, peers, jobInfo, !frame.fIsRange, false); - boost::shared_ptr windows(new WindowFrame(frameUnit, upper, lower)); - func->frameUnit(frameUnit); - - // add to the function list - fFunctions.push_back(boost::shared_ptr( - new WindowFunction(func, parts, orderbys, windows, rg, fRowIn))); - fFunctionCount++; - } - - // initialize window function expresssions - fExpression = jobInfo.windowExps; - for (RetColsVector::iterator i = fExpression.begin(); i < fExpression.end(); i++) - { - // output index - (*i)->outputIndex(getColumnIndex(*i, colIndexMap, jobInfo)); - - // map the input indices - const vector& scols = (*i)->simpleColumnList(); - for (vector::const_iterator j = scols.begin(); j != scols.end(); j++) - { - uint64_t key = getTupleKey(jobInfo, *j); - CalpontSystemCatalog::OID dictOid = joblist::isDictCol((*j)->colType()); - if (dictOid > 0) - { - key = jobInfo.keyInfo->dictKeyMap[key]; - } - - map::iterator k = colIndexMap.find(key); - - if (k != colIndexMap.end()) - { - (*j)->inputIndex(k->second); - } - else - { - string name = jobInfo.keyInfo->tupleKeyToName[key]; - cerr << name << " is not in tuple, key=" << key << endl; - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_COLUMN_MISSING, name), - ERR_WF_COLUMN_MISSING); - } - } - - ArithmeticColumn* ac = dynamic_cast((*i).get()); - FunctionColumn* fc = dynamic_cast((*i).get()); - if (ac != NULL) - { - updateWindowCols(ac->expression(), colIndexMap, jobInfo); - } - else if (fc != NULL) - { -// RetColsVector wcList = fc->windowfunctionColumnList(); -// for (RetColsVector::iterator j = wcList.begin(); j != wcList.end(); j++) -// (*j)->inputIndex(getColumnIndex(*j, colIndexMap, jobInfo)); - funcexp::FunctionParm parms = fc->functionParms(); - for (vector::iterator j = parms.begin(); j < parms.end(); j++) - updateWindowCols(j->get(), colIndexMap, jobInfo); - } - } - - // order by part - if (jobInfo.wfqOrderby.size() > 0) - { - // query order by - vector eqIdx; - vector sorts; - const RetColsVector& orderby = jobInfo.wfqOrderby; - for (uint64_t i = 0; i < orderby.size(); i++) - { - // skip constant column - if (dynamic_cast(orderby[i].get()) != NULL) - continue; - - // get column index - uint64_t idx = getColumnIndex(orderby[i], colIndexMap, jobInfo); - sorts.push_back(IdbSortSpec(idx, orderby[i]->asc(), orderby[i]->nullsFirst())); - } - - fQueryOrderBy.reset(new OrderByData(sorts, rg)); - } - - // limit part - fQueryLimitStart = jobInfo.wfqLimitStart; - fQueryLimitCount = jobInfo.wfqLimitCount; - - // fix the delivered rowgroup data - vector delColIdx; - for (RetColsVector::iterator i=jobInfo.windowDels.begin(); i((*i).get()) != NULL) - continue; - - delColIdx.push_back(getColumnIndex(*i, colIndexMap, jobInfo)); - } - - size_t retColCount = delColIdx.size(); - vector pos1; - vector oids1; - vector keys1; - vector scales1; - vector precisions1; - vector types1; - pos1.push_back(2); - - for (size_t i = 0; i < retColCount; i++) - { - size_t j = delColIdx[i]; - pos1.push_back(pos1[i] + (pos[j+1] - pos[j])); - oids1.push_back(oids[j]); - keys1.push_back(keys[j]); - scales1.push_back(scales[j]); - precisions1.push_back(precisions[j]); - types1.push_back(types[j]); - } - - fRowGroupDelivered = RowGroup( - retColCount,pos1,oids1,keys1,types1,scales1,precisions1,jobInfo.stringTableThreshold); - - if (jobInfo.trace) - cout << "delivered RG: " << fRowGroupDelivered.toString() << endl << endl; - - if (wfsUpdateStringTable > 1) - fUseSSMutex = true; - - fRowGroupOut = fRowGroupDelivered; -} - - -void WindowFunctionStep::execute() -{ - RGData rgData; - Row row; - fRowGroupIn.initRow(&row); - bool more = fInputDL->next(fInputIterator, &rgData); - uint64_t i = 0; // for RowGroup index in the fInRowGroupData - - if (traceOn()) dlTimes.setFirstReadTime(); - - StepTeleStats sts; - sts.query_uuid = fQueryUuid; - sts.step_uuid = fStepUuid; - sts.msg_type = StepTeleStats::ST_START; - sts.total_units_of_work = 1; - postStepStartTele(sts); - - try - { - while (more && !cancelled()) - { - fRowGroupIn.setData(&rgData); - fRowGroupIn.getRow(0, &row); - uint64_t rowCnt = fRowGroupIn.getRowCount(); - if (rowCnt > 0) - { - fInRowGroupData.push_back(rgData); - uint64_t memAdd = fRowGroupIn.getSizeWithStrings() + rowCnt * sizeof(RowPosition); - if (fRm.getMemory(memAdd, fSessionMemLimit) == false) - throw IDBExcept(ERR_WF_DATA_SET_TOO_BIG); - fMemUsage += memAdd; - - for (uint64_t j = 0; j < rowCnt; ++j) - { - if (i > 0x0000FFFFFFFFFFFFULL || j > 0x000000000000FFFFULL) - throw IDBExcept(ERR_WF_DATA_SET_TOO_BIG); - - fRows.push_back(RowPosition(i, j)); - row.nextRow(); - } - - //@bug6065, make StringStore::storeString() thread safe, default to false. - rgData.useStoreStringMutex(fUseSSMutex); - - // window function does not change row count - fRowsReturned += rowCnt; - - i++; - } - more = fInputDL->next(fInputIterator, &rgData); - } - } // try - catch(const IDBExcept &idb) { - handleException(idb.what(), idb.errorCode()); - } - catch(const std::exception& ex) - { - handleException(ex.what(), ERR_READ_INPUT_DATALIST); - } - catch(...) - { - handleException("WindowFunctionStep caught an unknown exception", ERR_READ_INPUT_DATALIST); - } - - if (traceOn()) - dlTimes.setLastReadTime(); - - // no need for the window function if aborted or result set is empty. - if (cancelled() || fRows.size() == 0) - { - while (more) - more = fInputDL->next(fInputIterator, &rgData); - - fOutputDL->endOfInput(); - - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - - if (traceOn()) - { - dlTimes.setEndOfInputTime(); - printCalTrace(); - } - - return; - } - - // got something to work on - try - { - if (fFunctionCount == 1) - { - doFunction(); - } - else - { - if (fTotalThreads > fFunctionCount) - fTotalThreads = fFunctionCount; - - for (uint64_t i = 0; i < fTotalThreads && !cancelled(); i++) - fFunctionThreads.push_back( - boost::shared_ptr(new boost::thread(WFunction(this)))); - - // If cancelled, not all thread is started. - for (uint64_t i = 0; i < fFunctionThreads.size(); i++) - fFunctionThreads[i]->join(); - } - - if (!(cancelled())) - { - if (fIsSelect) - doPostProcessForSelect(); - else - doPostProcessForDml(); - } - - } - catch(const std::exception& ex) - { - handleException(ex.what(), ERR_EXECUTE_WINDOW_FUNCTION); - } - catch(...) - { - handleException("WindowFunctionStep caught an unknown exception", - ERR_EXECUTE_WINDOW_FUNCTION); - } - - fOutputDL->endOfInput(); - - sts.msg_type = StepTeleStats::ST_SUMMARY; - sts.total_units_of_work = sts.units_of_work_completed = 1; - sts.rows = fRowsReturned; - postStepSummaryTele(sts); - - if (traceOn()) - { - dlTimes.setEndOfInputTime(); - printCalTrace(); - } - - return; -} - - -uint64_t WindowFunctionStep::nextFunctionIndex() -{ - uint64_t idx = atomicInc(&fNextIndex); - - // return index in the function array - return --idx; -} - - -void WindowFunctionStep::doFunction() -{ - uint64_t i = 0; - try - { - while (((i = nextFunctionIndex()) < fFunctionCount) && !cancelled()) - { - uint64_t memAdd = fRows.size() * sizeof(RowPosition); - if (fRm.getMemory(memAdd, fSessionMemLimit) == false) - throw IDBExcept(ERR_WF_DATA_SET_TOO_BIG); - fMemUsage += memAdd; - fFunctions[i]->setCallback(this, i); - (*fFunctions[i].get())(); - } - } - catch (IDBExcept& iex) - { - handleException(iex.what(), iex.errorCode()); - } - catch(const std::exception& ex) - { - handleException(ex.what(), ERR_EXECUTE_WINDOW_FUNCTION); - } - catch(...) - { - handleException("doFunction caught an unknown exception", ERR_EXECUTE_WINDOW_FUNCTION); - } -} - - -void WindowFunctionStep::doPostProcessForSelect() -{ - FuncExp* fe = funcexp::FuncExp::instance(); - boost::shared_array mapping = makeMapping(fRowGroupIn, fRowGroupOut); - Row rowIn, rowOut; - fRowGroupIn.initRow(&rowIn); - fRowGroupOut.initRow(&rowOut); - RGData rgData; - vector& rowData = *(fFunctions.back()->fRowData.get()); - int64_t rowsLeft = rowData.size(); - int64_t rowsInRg = 0; - int64_t rgCapacity = 0; - - int64_t begin = fQueryLimitStart; - int64_t count = (fQueryLimitCount == (uint64_t) -1) ? rowsLeft : fQueryLimitCount; - int64_t end = begin + count; - end = (end < rowsLeft) ? end : rowsLeft; - rowsLeft = (end > begin) ? (end - begin) : 0; - - if (fQueryOrderBy.get() != NULL) - sort(rowData.begin(), rowData.size()); - - for (int64_t i = begin; i < end; i++) - { - if (rgData.rowData.get() == NULL) - { - rgCapacity = ((rowsLeft > 8192) ? 8192 : rowsLeft); - rowsLeft -= rgCapacity; - rgData.reinit(fRowGroupOut, rgCapacity); - - fRowGroupOut.setData(&rgData); - fRowGroupOut.resetRowGroup(0); - fRowGroupOut.setDBRoot(0); // not valid dbroot - fRowGroupOut.getRow(0, &rowOut); - rowsInRg = 0; - } - - rowIn.setData(getPointer(rowData[i], fRowGroupIn, rowIn)); - - // evaluate the window function expressions before apply mapping - if (fExpression.size() > 0) - fe->evaluate(rowIn, fExpression); - - applyMapping(mapping, rowIn, &rowOut); - rowOut.nextRow(); - rowsInRg++; - - if (rowsInRg == rgCapacity) - { - fRowGroupOut.setRowCount(rowsInRg); - fOutputDL->insert(rgData); - rgData.clear(); - } - } -} - - -void WindowFunctionStep::doPostProcessForDml() -{ - FuncExp* fe = funcexp::FuncExp::instance(); - boost::shared_array mapping = makeMapping(fRowGroupIn, fRowGroupOut); - Row rowIn, rowOut; - fRowGroupIn.initRow(&rowIn); - fRowGroupOut.initRow(&rowOut); - - for (vector::iterator i = fInRowGroupData.begin(); - i < fInRowGroupData.end(); i++) - { - fRowGroupIn.setData(&(*i)); - RGData rgData = RGData(fRowGroupIn, fRowGroupIn.getRowCount()); - fRowGroupOut.setData(&rgData); - // @bug 5631. reset rowgroup before the data is populated. - fRowGroupOut.resetRowGroup(fRowGroupIn.getBaseRid()); - fRowGroupOut.setDBRoot(fRowGroupIn.getDBRoot()); - fRowGroupOut.setRowCount(fRowGroupIn.getRowCount()); - - fRowGroupIn.getRow(0, &rowIn); - fRowGroupOut.getRow(0, &rowOut); - - for (uint64_t i = 0; i < fRowGroupIn.getRowCount(); ++i) - { - // evaluate the window function expressions before apply mapping - if (fExpression.size() > 0) - fe->evaluate(rowIn, fExpression); - - applyMapping(mapping, rowIn, &rowOut); - rowIn.nextRow(); - rowOut.nextRow(); - } - - //fRowGroupOut.resetRowGroup(fRowGroupIn.getBaseRid()); - //fRowGroupOut.setRowCount(fRowGroupIn.getRowCount()); - - fOutputDL->insert(rgData); - } -} - - -void WindowFunctionStep::handleException(string errStr, int errCode) -{ - cerr << "Exception: " << errStr << endl; - catchHandler(errStr, errCode, fErrorInfo, fSessionId); -} - - -boost::shared_ptr WindowFunctionStep::parseFrameBoundRows( - const execplan::WF_Boundary& b, - const map& m, - JobInfo& jobInfo) -{ - boost::shared_ptr fb; - if (b.fFrame == WF_CURRENT_ROW) - { - fb.reset(new FrameBoundRow(WF__CURRENT_ROW)); - return fb; - } - - ConstantColumn* cc = dynamic_cast(b.fVal.get()); - if (cc != NULL) - { - Row dummy; - bool isNull = false; - int val = cc->getIntVal(dummy, isNull); - if (val >= 0 && isNull == false) - { - int type = (b.fFrame==WF_PRECEDING)?WF__CONSTANT_PRECEDING:WF__CONSTANT_FOLLOWING; - fb.reset(new FrameBoundConstantRow(type, val)); - } - else - { - string str("NULL"); - if (!isNull) - { - ostringstream oss; - oss << val; - str = oss.str(); - } - - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_BOUND_OUT_OF_RANGE, str), - ERR_WF_BOUND_OUT_OF_RANGE); - } - } - else - { - int type = (b.fFrame==WF_PRECEDING)?WF__EXPRESSION_PRECEDING:WF__EXPRESSION_FOLLOWING; - uint64_t id = getTupleKey(jobInfo, b.fVal); - uint64_t idx = getColumnIndex(b.fVal, m, jobInfo); - TupleInfo ti = getTupleInfo(id, jobInfo); - switch(ti.dtype) - { - case execplan::CalpontSystemCatalog::TINYINT: - case execplan::CalpontSystemCatalog::SMALLINT: - case execplan::CalpontSystemCatalog::MEDINT: - case execplan::CalpontSystemCatalog::INT: - case execplan::CalpontSystemCatalog::BIGINT: - case execplan::CalpontSystemCatalog::DECIMAL: - { - fb.reset(new FrameBoundExpressionRow(type, id, idx)); - break; - } - - case execplan::CalpontSystemCatalog::DOUBLE: - case execplan::CalpontSystemCatalog::UDOUBLE: - { - fb.reset(new FrameBoundExpressionRow(type, id, idx)); - break; - } - - case execplan::CalpontSystemCatalog::FLOAT: - case execplan::CalpontSystemCatalog::UFLOAT: - { - fb.reset(new FrameBoundExpressionRow(type, id, idx)); - break; - } - - case execplan::CalpontSystemCatalog::UTINYINT: - case execplan::CalpontSystemCatalog::USMALLINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UBIGINT: - case execplan::CalpontSystemCatalog::UDECIMAL: - case execplan::CalpontSystemCatalog::DATE: - case execplan::CalpontSystemCatalog::DATETIME: - { - fb.reset(new FrameBoundExpressionRow(type, id, idx)); - break; - } - - default: - { - string str = windowfunction::colType2String[ti.dtype]; - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_INVALID_BOUND_TYPE, str), - ERR_WF_INVALID_BOUND_TYPE); - break; - } - } - } - - return fb; -} - - -boost::shared_ptr WindowFunctionStep::parseFrameBoundRange(const execplan::WF_Boundary& b, - const map& m, - const vector& o, - JobInfo& jobInfo) -{ - boost::shared_ptr fb; - if (b.fFrame == WF_CURRENT_ROW) - { - fb.reset(new FrameBoundRange(WF__CURRENT_ROW)); - return fb; - } - - bool isConstant = false; - bool isNull = false; - Row dummy; - ConstantColumn* cc = dynamic_cast(b.fVal.get()); - if (cc != NULL) - { - isConstant = true; - double val = cc->getDoubleVal(dummy, isNull); - if (val < 0 || isNull) - { - string str("NULL"); - if (!isNull) - { - ostringstream oss; - oss << val; - str = oss.str(); - } - - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_BOUND_OUT_OF_RANGE, str), - ERR_WF_BOUND_OUT_OF_RANGE); - } - } - - int type = 0; - vector ids; - vector index; - ids.push_back(getTupleKey(jobInfo, o[0])); - index.push_back(getColumnIndex(o[0], m, jobInfo)); - if (isConstant) - { - type = (b.fFrame==WF_PRECEDING)?WF__CONSTANT_PRECEDING:WF__CONSTANT_FOLLOWING; - ids.push_back(-1); // dummy, n/a for constant - index.push_back(-1); // dummy, n/a for constant - } - else - { - type = (b.fFrame==WF_PRECEDING)?WF__EXPRESSION_PRECEDING:WF__EXPRESSION_FOLLOWING; - ids.push_back(getTupleKey(jobInfo, b.fVal)); - index.push_back(getColumnIndex(b.fVal, m, jobInfo)); - } - ids.push_back(getTupleKey(jobInfo, b.fBound)); - index.push_back(getColumnIndex(b.fBound, m, jobInfo)); - - FrameBoundRange* fbr = NULL; - TupleInfo ti = getTupleInfo(ids[0], jobInfo); - bool asc = o[0]->asc(); - bool nlf = o[0]->nullsFirst(); - switch(ti.dtype) - { - case execplan::CalpontSystemCatalog::TINYINT: - case execplan::CalpontSystemCatalog::SMALLINT: - case execplan::CalpontSystemCatalog::MEDINT: - case execplan::CalpontSystemCatalog::INT: - case execplan::CalpontSystemCatalog::BIGINT: - case execplan::CalpontSystemCatalog::DECIMAL: - { - if (isConstant) - { - int64_t v = cc->getIntVal(dummy, isNull); - fbr = new FrameBoundConstantRange(type, asc, nlf, &v); - fbr->isZero((v == 0)); - } - else - { - fbr = new FrameBoundExpressionRange(type, asc, nlf); - } - break; - } - - case execplan::CalpontSystemCatalog::DOUBLE: - case execplan::CalpontSystemCatalog::UDOUBLE: - { - if (isConstant) - { - double v = cc->getDoubleVal(dummy, isNull); - fbr = new FrameBoundConstantRange(type, asc, nlf, &v); - fbr->isZero((v == 0.0)); - } - else - { - fbr = new FrameBoundExpressionRange(type, asc, nlf); - } - break; - } - - case execplan::CalpontSystemCatalog::FLOAT: - case execplan::CalpontSystemCatalog::UFLOAT: - { - if (isConstant) - { - float v = cc->getFloatVal(dummy, isNull); - fbr = new FrameBoundConstantRange(type, asc, nlf, &v); - fbr->isZero((v == 0.0)); - } - else - { - fbr = new FrameBoundExpressionRange(type, asc, nlf); - } - break; - } - - case execplan::CalpontSystemCatalog::UTINYINT: - case execplan::CalpontSystemCatalog::USMALLINT: - case execplan::CalpontSystemCatalog::UMEDINT: - case execplan::CalpontSystemCatalog::UINT: - case execplan::CalpontSystemCatalog::UBIGINT: - case execplan::CalpontSystemCatalog::UDECIMAL: - case execplan::CalpontSystemCatalog::DATE: - case execplan::CalpontSystemCatalog::DATETIME: - { - if (isConstant) - { - uint64_t v = cc->getUintVal(dummy, isNull); - fbr = new FrameBoundConstantRange(type, asc, nlf, &v); - fbr->isZero((v == 0)); - } - else - { - fbr = new FrameBoundExpressionRange(type, asc, nlf); - } - break; - } - - default: - { - string str = windowfunction::colType2String[ti.dtype]; - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_INVALID_BOUND_TYPE, str), - ERR_WF_INVALID_BOUND_TYPE); - break; - } - } - - fbr->setTupleId(ids); - fbr->setIndex(index); - fb.reset(fbr); - - return fb; -} - - -boost::shared_ptr WindowFunctionStep::parseFrameBound(const execplan::WF_Boundary& b, - const map& m, - const vector& o, - const boost::shared_ptr& p, - JobInfo& j, - bool rows, - bool s) -{ - boost::shared_ptr fb; - - switch(b.fFrame) - { - case WF_UNBOUNDED_PRECEDING: - { - fb.reset(new FrameBound(WF__UNBOUNDED_PRECEDING)); - break; - } - - case WF_UNBOUNDED_FOLLOWING: - { - fb.reset(new FrameBound(WF__UNBOUNDED_FOLLOWING)); - break; - } - - case WF_CURRENT_ROW: - case WF_PRECEDING: - case WF_FOLLOWING: - { - if (rows) - { - fb = parseFrameBoundRows(b, m, j); - } - else - { - fb = parseFrameBoundRange(b, m, o, j); - } - break; - } - - default: // unknown - { - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_UNKNOWN_BOUND, b.fFrame), - ERR_WF_UNKNOWN_BOUND); - break; - } - } - - fb->peer(p); - fb->start(s); - - return fb; -} - - -void WindowFunctionStep::updateWindowCols(ReturnedColumn* rc, - const map& m, - JobInfo& jobInfo) -{ - if (rc == NULL) - return; - - ArithmeticColumn* ac = dynamic_cast(rc); - FunctionColumn* fc = dynamic_cast(rc); - SimpleFilter* sf = dynamic_cast(rc); - WindowFunctionColumn* wc = dynamic_cast(rc); - - if (wc) - { - uint64_t key = getExpTupleKey(jobInfo, wc->expressionId()); - map::const_iterator j = m.find(key); - if (j == m.end()) - { - string name = jobInfo.keyInfo->tupleKeyToName[key]; - cerr << name << " is not in tuple, key=" << key << endl; - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_COLUMN_MISSING, name), - ERR_WF_COLUMN_MISSING); - } - - wc->inputIndex(j->second); - } - else if (ac) - { - updateWindowCols(ac->expression(), m, jobInfo); - } - else if (fc) - { - funcexp::FunctionParm parms = fc->functionParms(); - for (vector::iterator i = parms.begin(); i < parms.end(); i++) - updateWindowCols(i->get(), m, jobInfo); - } - else if (sf) - { - updateWindowCols(sf->lhs(), m, jobInfo); - updateWindowCols(sf->rhs(), m, jobInfo); - } -} - - -void WindowFunctionStep::updateWindowCols(ParseTree* pt, - const map& m, - JobInfo& jobInfo) -{ - if (pt == NULL) - return; - - updateWindowCols(pt->left(), m, jobInfo); - updateWindowCols(pt->right(), m, jobInfo); - - TreeNode* tn = pt->data(); - ArithmeticColumn* ac = dynamic_cast(tn); - FunctionColumn* fc = dynamic_cast(tn); - SimpleFilter* sf = dynamic_cast(tn); - WindowFunctionColumn* wc = dynamic_cast(tn); - - if (wc) - { - uint64_t key = getExpTupleKey(jobInfo, wc->expressionId()); - map::const_iterator j = m.find(key); - if (j == m.end()) - { - string name = jobInfo.keyInfo->tupleKeyToName[key]; - cerr << name << " is not in tuple, key=" << key << endl; - throw IDBExcept(IDBErrorInfo::instance()->errorMsg(ERR_WF_COLUMN_MISSING, name), - ERR_WF_COLUMN_MISSING); - } - - wc->inputIndex(j->second); - } - else if (ac) - { - updateWindowCols(ac->expression(), m, jobInfo); - } - else if (fc) - { - funcexp::FunctionParm parms = fc->functionParms(); - for (vector::iterator i = parms.begin(); i < parms.end(); i++) - updateWindowCols(i->get(), m, jobInfo); - } - else if (sf) - { - updateWindowCols(sf->lhs(), m, jobInfo); - updateWindowCols(sf->rhs(), m, jobInfo); - } -} - - -void WindowFunctionStep::sort(std::vector::iterator v, uint64_t n) -{ - // recursive function termination condition. - if (n < 2 || cancelled()) - return; - - RowPosition p = *(v + n/2); // pivot value - vector::iterator l = v; // low address - vector::iterator h = v + (n - 1); // high address - while (l <= h && !cancelled()) - { - // Can use while here, but need check boundary and cancel status. - if (fQueryOrderBy->operator()(getPointer(*l), getPointer(p))) - { - l++; - } - else if (fQueryOrderBy->operator()(getPointer(p), getPointer(*h))) - { - h--; - } - else - { - RowPosition t = *l; // temp value for swap - *l++ = *h; - *h-- = t; - } - } - - sort(v, distance(v, h) + 1); - sort(l, distance(l, v) + n); -} - - -void WindowFunctionStep::printCalTrace() -{ - time_t t = time (0); - char timeString[50]; - ctime_r (&t, timeString); - timeString[strlen (timeString )-1] = '\0'; - ostringstream logStr; - logStr << "ses:" << fSessionId << " st: " << fStepId << " finished at "<< timeString - << "; total rows returned-" << fRowsReturned << endl - << "\t1st read " << dlTimes.FirstReadTimeString() - << "; EOI " << dlTimes.EndOfInputTimeString() << "; runtime-" - << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) - << "s;\n\tUUID " << uuids::to_string(fStepUuid) << endl - << "\tJob completion status " << status() << endl; - logEnd(logStr.str().c_str()); - fExtendedInfo += logStr.str(); - formatMiniStats(); -} - - -void WindowFunctionStep::formatMiniStats() -{ - ostringstream oss; - oss << "WFS " - << "UM " - << "- " - << "- " - << "- " - << "- " - << "- " - << "- " - << JSTimeStamp::tsdiffstr(dlTimes.EndOfInputTime(), dlTimes.FirstReadTime()) << " " - << fRowsReturned << " "; - fMiniInfo += oss.str(); -} - - -} //namespace -// vim:ts=4 sw=4: - diff --git a/dbcon/joblist/windowfunctionstep.h b/dbcon/joblist/windowfunctionstep.h deleted file mode 100644 index a1cfaf9c..00000000 --- a/dbcon/joblist/windowfunctionstep.h +++ /dev/null @@ -1,222 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: windowfunctionstep.h 9722 2013-07-25 21:29:10Z pleblanc $ - - -#ifndef JOBLIST_WINDOWFUNCTIONSTEP_H -#define JOBLIST_WINDOWFUNCTIONSTEP_H - -#include "idborderby.h" -#include "jobstep.h" -#include "rowgroup.h" -#include "windowfunctioncolumn.h" - -namespace execplan -{ -// forward reference -class CalpontSelectExecutionPlan; -class ParseTree; -class ReturnedColumn; -}; - - -namespace windowfunction -{ -// forward reference -class WindowFunction; -class FrameBound; -}; - - -namespace ordering -{ -// forward reference -class EqualCompData; -}; - - -namespace joblist -{ - -// forward reference -struct JobInfo; -class ResourceManager; - - -struct RowPosition -{ - uint64_t fGroupId : 48; - uint64_t fRowId : 16; - - inline RowPosition(uint64_t i = 0, uint64_t j = 0) : fGroupId(i), fRowId(j) {}; -}; - - -/** @brief class WindowFunctionStep - * - */ -class WindowFunctionStep : public JobStep, public TupleDeliveryStep -{ -public: - /** @brief WindowFunctionStep constructor - * @param - * @param - */ - WindowFunctionStep(const JobInfo&); - - /** @brief WindowFunctionStep destructor - */ - virtual ~WindowFunctionStep(); - - /** @brief virtual methods - */ - void run(); - void join(); - const std::string toString() const; - void setOutputRowGroup(const rowgroup::RowGroup&); - const rowgroup::RowGroup& getOutputRowGroup() const; - const rowgroup::RowGroup& getDeliveredRowGroup() const; - void deliverStringTableRowGroup(bool b); - bool deliverStringTableRowGroup() const; - uint32_t nextBand(messageqcpp::ByteStream &bs); - - /** @brief initialize methods - */ - void initialize(const rowgroup::RowGroup& rg, JobInfo& jobInfo); - - static void checkWindowFunction(execplan::CalpontSelectExecutionPlan*, JobInfo&); - static SJSTEP makeWindowFunctionStep(SJSTEP&, JobInfo&); - - // for WindowFunction and WindowFunctionWrapper callback - const std::vector& getRowData() const { return fRows; } - void handleException(std::string, int); - - // for string table - rowgroup::Row::Pointer getPointer(RowPosition& pos) - { - fRowGroupIn.setData(&(fInRowGroupData[pos.fGroupId])); - fRowGroupIn.getRow(pos.fRowId, &fRowIn); - return fRowIn.getPointer(); - } - - rowgroup::Row::Pointer getPointer(RowPosition& pos, rowgroup::RowGroup& rg, rowgroup::Row& row) - { - rg.setData(&(fInRowGroupData[pos.fGroupId])); - rg.getRow(pos.fRowId, &row); - return row.getPointer(); - } - -private: - void execute(); - void doFunction(); - void doPostProcessForSelect(); - void doPostProcessForDml(); - - uint64_t nextFunctionIndex(); - - boost::shared_ptr parseFrameBound(const execplan::WF_Boundary&, - const map&, const vector&, - const boost::shared_ptr&, JobInfo&, bool, bool); - boost::shared_ptr parseFrameBoundRows( - const execplan::WF_Boundary&, const map&, JobInfo&); - boost::shared_ptr parseFrameBoundRange( - const execplan::WF_Boundary&, const map&, const vector&, - JobInfo&); - void updateWindowCols(execplan::ParseTree*, const map&, JobInfo&); - void updateWindowCols(execplan::ReturnedColumn*, const map&, JobInfo&); - void sort(std::vector::iterator, uint64_t); - - void formatMiniStats(); - void printCalTrace(); - - class Runner - { - public: - Runner(WindowFunctionStep* step) : fStep(step) { } - void operator()() { fStep->execute(); } - - WindowFunctionStep* fStep; - }; - - boost::scoped_ptr fRunner; - - boost::shared_ptr fCatalog; - uint64_t fRowsReturned; - bool fEndOfResult; - bool fIsSelect; - bool fUseSSMutex; //@bug6065, mutex for setStringField - - // for input/output datalist - RowGroupDL* fInputDL; - RowGroupDL* fOutputDL; - int fInputIterator; - int fOutputIterator; - - // rowgroups - rowgroup::RowGroup fRowGroupIn; - rowgroup::RowGroup fRowGroupOut; - rowgroup::RowGroup fRowGroupDelivered; - rowgroup::Row fRowIn; - - // data storage - std::vector fInRowGroupData; - - // for funciton/expression taking window function as parameter - std::vector fExpression; - - // for threads computing window functions and partitions - class WFunction - { - public: - WFunction(WindowFunctionStep* step) : fStep(step) { } - void operator()() { fStep->doFunction(); } - - WindowFunctionStep* fStep; - }; - std::vector > fFunctionThreads; - - std::vector fRows; - std::vector > fFunctions; - uint64_t fFunctionCount; - uint64_t fTotalThreads; -#ifdef _MSC_VER - volatile LONG fNextIndex; -#else - int fNextIndex; -#endif - - - // query order by - boost::shared_ptr fQueryOrderBy; - uint64_t fQueryLimitStart; - uint64_t fQueryLimitCount; - - // for resource management - uint64_t fMemUsage; - ResourceManager& fRm; - boost::shared_ptr fSessionMemLimit; - - friend class windowfunction::WindowFunction; -}; - - -} // namespace - -#endif // JOBLIST_WINDOWFUNCTIONSTEP_H - -// vim:ts=4 sw=4: diff --git a/dbcon/joblist/wsdl.h b/dbcon/joblist/wsdl.h new file mode 100644 index 00000000..f3e4837f --- /dev/null +++ b/dbcon/joblist/wsdl.h @@ -0,0 +1,353 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: wsdl.h 8436 2012-04-04 18:18:21Z rdempsey $ + * + *****************************************************************************/ + +/** @file + * class XXX interface + */ + +#include +#include +#include +#include "elementtype.h" +#include "largedatalist.h" + +#ifndef _WSDL_HPP +#define _WSDL_HPP + +namespace joblist { + +/** @brief class WSDL + * + */ +template +class WSDL : public LargeDataList, element_t> +{ + typedef LargeDataList, element_t> base; + typedef std::vector container_t; + + public: + // elementeSaveSize1st - size (in bytes) to be used in saving + // element_t.first to disk. + // elementSaveSize2 - size (in bytes) to be used in saving + // element_t.second to disk. + WSDL(uint numConsumers, uint maxElements, ResourceManager& rm); + WSDL(uint numConsumers, uint maxElements, + uint32_t elementSaveSize1st, + uint32_t elementSaveSize2nd, + ResourceManager& rm); + virtual ~WSDL(); + + void insert(const element_t &e); + void insert(const std::vector &e); + void insert_nolock(const element_t &e); + bool next(uint64_t it, element_t *e); + void endOfInput(); + void endOfInput_nosave(); + uint64_t getIterator(); + uint64_t totalSize(); + uint64_t maxElem() { return maxElements; } + uint64_t initialSetCount() const { return initialSetCnt; } + void mergeSets(); + void flush (const uint64_t &threshold, bool lockFlag = true); + uint64_t curSize; + uint64_t saveSize; // total save to disk size. debug usage + + protected: + + private: + // this doesn't make sense during the consume phase. + // if necessary we have to put a little thought into what to do + // with waiting threads. Same with =. + // Declare but don't define default and copy constuctor, and + // assignment operator to disable their use. + WSDL(); + WSDL(const WSDL &); + WSDL & operator=(const WSDL &); + + // @bug 721. add append option + void load(uint64_t setNum, bool append=false); + uint64_t save(); + uint64_t save(container_t *c); + uint64_t maxElements; + uint64_t waitingConsumers; + boost::condition nextSetLoaded; + uint64_t initialSetCnt; // total number of sets prior to any merges +}; + +template +WSDL::WSDL(uint nc, uint me, ResourceManager& rm) : + base(nc,sizeof(uint64_t),sizeof(uint64_t), rm), curSize(0), + saveSize(0), maxElements(me), waitingConsumers(0), initialSetCnt(0) +{ + //pthread_cond_init(&nextSetLoaded, NULL); +} + +template +WSDL::WSDL(uint nc, uint me, + uint32_t elementSaveSize1st, uint32_t elementSaveSize2nd, ResourceManager& rm) : + base(nc,elementSaveSize1st,elementSaveSize2nd, rm), curSize(0), + saveSize(0), maxElements(me), waitingConsumers(0), initialSetCnt(0) +{ + //pthread_cond_init(&nextSetLoaded, NULL); +} + +template +WSDL::~WSDL() +{ + //pthread_cond_destroy(&nextSetLoaded); +} + +template +void WSDL::load(uint64_t setNum, bool append) +{ + if (typeid(element_t) == typeid(ElementType) || + typeid(element_t) == typeid(DoubleElementType) || + typeid(element_t) == typeid(RIDElementType)) + base::load_contiguous(setNum, append); + else + base::load(setNum, append); +} + +// returns the number of bytes written by this save operation +template +uint64_t WSDL::save() +{ + if (typeid(element_t) == typeid(ElementType) || + typeid(element_t) == typeid(DoubleElementType) || + typeid(element_t) == typeid(RIDElementType)) + return base::save_contiguous(); + else + return base::save(); +} + +// returns the number of bytes written by this save operation +template +uint64_t WSDL::save(container_t *c) +{ + sort(c->begin(), c->end()); + if (typeid(element_t) == typeid(ElementType) || + typeid(element_t) == typeid(DoubleElementType) || + typeid(element_t) == typeid(RIDElementType)) + return base::save_contiguous(c); + else + return base::save(c); +} + +template +void WSDL::insert(const element_t &e) +{ + if (base::multipleProducers) + base::lock(); + try + { + insert_nolock(e); + } + catch ( ... ) + { + if (base::multipleProducers) + base::unlock(); + throw; + } + if (base::multipleProducers) + base::unlock(); +} + +template +void WSDL::insert_nolock(const element_t &e) +{ + if (base::c->size() == maxElements) { +// std::cout << "WSDL-" << this << " full and save" << std::endl; + curSize = 0; + saveSize += save(); + base::registerNewSet(); + } + + base::insert(e); + curSize++; + +} + +template +void WSDL::insert(const std::vector &e) +{ + throw std::logic_error("WSDL::insert(vector) isn't implemented yet"); +} + +template +void WSDL::endOfInput() +{ + base::lock(); + initialSetCnt = base::setCount; + if (base::loadedSet > 0) + { + saveSize += save(); + load(0); + } + else + { + // save the in memory set for reuse + if (base::saveForReuse() == true) + saveSize += save(); + + base::resetIterators_nowait(); + } + + base::endOfInput(); + base::unlock(); +} + +template +void WSDL::endOfInput_nosave() +{ + base::lock(); + initialSetCnt = base::setCount; + base::endOfInput(); + base::unlock(); + +} + +template +uint64_t WSDL::getIterator() +{ + uint64_t ret; + + base::lock(); + ret = base::getIterator(); + base::unlock(); + return ret; +} + +template +bool WSDL::next(uint64_t id, element_t *e) +{ + bool ret, locked = false; + uint64_t nextSet; + + if (base::phase == 0) { + locked = true; + base::lock(); + base::waitForConsumePhase(); + } + + ret = base::next_nowait(id, e); + + /* XXXPAT: insignificant race condition here. Technically, there's no + guarantee the caller will be wakened when the next set is loaded. It could + get skipped. It won't happen realistically, but it exists... */ + + // signifies the caller is at the end of the loaded set, + // but there are more sets + if (ret == false && (base::loadedSet < base::setCount - 1)) { + + if (!locked && (base::numConsumers > 1 || base::phase == 0)) { + locked = true; + base::lock(); + } + + nextSet = base::loadedSet + 1; + waitingConsumers++; + if (waitingConsumers < base::numConsumers) + while (nextSet != base::loadedSet) { + nextSetLoaded.wait(this->mutex); //pthread_cond_wait(&nextSetLoaded, &(this->mutex)); + } + else { + load(nextSet); + nextSetLoaded.notify_all(); //pthread_cond_broadcast(&nextSetLoaded); + } + waitingConsumers--; + ret = base::next(id, e); + } + + if (ret == false && ++base::consumersFinished == base::numConsumers) { + base::shrink(); + base::removeFile(); + } + if (locked) + base::unlock(); + + return ret; +} + +template +uint64_t WSDL::totalSize() +{ + uint64_t ret; + + base::lock(); + ret = base::totalSize(); + base::unlock(); + + return ret; +} + +/** @bug 721. merge all the saved sets to one set and sort */ +template +void WSDL::mergeSets() +{ + uint64_t i, size; + container_t *temp = reinterpret_cast *>(base::c); + size = totalSize(); + temp->reserve(size); + + for (i = 0; i < base::setCount-1; i++) { + // append set to the end of current set + load(i, true); + } + + sort(base::c->begin(), base::c->end()); + //std::cout << "WSDL-" << this << " mergeSets " << "setCount=" << base::setCount + // << " totalSize=" << size << std::endl; + base::setCount = 1; + base::resetIterators_nowait(); + +} + +/** @bug 721. flush the largest bucket to disk when over threshold */ +template +void WSDL::flush(const uint64_t &threshold, bool lockFlag) +{ + + if (lockFlag) base::lock(); + try + { + if (curSize > threshold){ + // force flush +// std::cout << "WSDL-" << this << " flushed " << "curSize=" << curSize +// << " max= " << maxElements << std::endl; + curSize = 0; + saveSize += save(); + base::registerNewSet(); + } + } + catch(...) + { + if (lockFlag) base::unlock(); + std::cerr << __FILE__ << "@" << __LINE__ << " ZDL insert vector caught an exception\n"; + throw; + } + if (lockFlag) base::unlock(); +} + + +} //namespace + +#endif diff --git a/dbcon/joblist/zdl.h b/dbcon/joblist/zdl.h new file mode 100644 index 00000000..dce163be --- /dev/null +++ b/dbcon/joblist/zdl.h @@ -0,0 +1,1109 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** +* $Id: zdl.h 8436 2012-04-04 18:18:21Z rdempsey $ +* +* +***********************************************************************/ + +/** @file + * class ZDL interface + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "wsdl.h" +#include "calpontsystemcatalog.h" +#include "configcpp.h" +#include "blocksize.h" + +#ifndef _ZDL_HPP_ +#define _ZDL_HPP_ + +/** Debug macro */ +#define ZDL_DEBUG 0 +#if ZDL_DEBUG +#define ZDEBUG std::cout +#else +#define ZDEBUG if (false) std::cout +#endif + +namespace joblist { +//const uint64_t defaultMaxElementsInMem = 32 * 1024 * 1024; // 32M +//const uint64_t defaultNumBuckets = 128; +//const uint64_t defaultMaxElementsPerBuckert = 16 * 1024 * 1024; // 16M + +/** @brief class BucketDL + * + */ +template +class ZDL : public DataList +{ + typedef DataList base; + typedef boost::shared_ptr< WSDL > SWSP; + typedef boost::shared_ptr< WSDL > RIDSWSP; + typedef std::vector WSVec; + typedef std::vector RIDWSVec; + + public: + enum ElementMode { + RID_ONLY, + RID_VALUE + }; + + /** Main constuctor. + * @param numConsumers The number of consumers that will eventually read this DL. + */ + ZDL(uint64_t numConsumers, ResourceManager& rm); + virtual ~ZDL(); + + // datalist interface. + virtual void insert(const element_t &e); + virtual void insert(const std::vector &e); + virtual void endOfInput(); + virtual uint64_t getIterator(); + virtual bool next(uint64_t it, element_t *e); + // multithreaded read interface + //bool next (uint64_t bucketID, uint64_t it, element_t *e); + virtual void setMultipleProducers(bool); + + /** Returns the size of the specified bucket */ + uint64_t size(uint64_t bucket); + + /** Returns the total number of elements stored */ + uint64_t totalSize(); + + /** Returns the number of buckets */ + uint64_t bucketCount(); + + /** Get the number of consumers */ + virtual uint getNumConsumers() const {return numConsumers; } + + /** Reset the number of consumers for the datalist */ + void resetNumConsumers(uint numConsumers); + + /** consumers block here until endOfInput */ + void waitForConsumePhase(); + + /** set element type for buckets */ + void setElementMode (const uint mode); + + /** Total number of files and filespace used for temp files */ + void totalFileCounts(uint64_t& numFiles, uint64_t& numBytes) const; + + /** This class does employ temp disk */ + virtual bool useDisk() const { return true; } + + /** Sets the size of the element components that are saved to disk */ + virtual void setDiskElemSize(uint32_t size1st,uint32_t size2nd); + + /** Configure this ZDL to behave as a stub; all inserts are dropped */ + void dropAllInserts() { fDropInserts = true; } + + /** Enables disk I/O time logging */ + void enableDiskIoTrace(); + + /** Returns the disk I/O time in seconds */ + bool totalDiskIoTime(uint64_t& w, uint64_t& r); + + /** Returns the reference of the disk I/O info list */ + std::list& diskIoInfoList(uint64_t bucket); + + protected: + + + private: + // Declare default constructors but don't define to disable their use + explicit ZDL(); + explicit ZDL(const ZDL &); + ZDL& operator=(const ZDL &); + + uint64_t nextBucket(uint64_t bucketID); + + + void insert_r(const RIDElementType &e); + void insert_rv(const element_t &e); + void endOfInput_r(); + void endOfInput_rv(); + uint64_t getIterator_r(); + uint64_t getIterator_rv(); + bool next_r(uint64_t it, RIDElementType *e); + bool next_rv(uint64_t it, element_t *e); + void setMultipleProducers_r(bool); + void setMultipleProducers_rv(bool); + uint64_t nextBucket_r(uint64_t bucketID); + uint64_t nextBucket_rv(uint64_t bucketID); + void checkBucket_r(uint64_t bucketID, bool lockFlag=true); + void checkBucket_rv(uint64_t bucketID, bool lockFlag=true); + void totalFileCounts_r(uint64_t& numFiles, uint64_t& numBytes) const; + void totalFileCounts_rv(uint64_t& numFiles, uint64_t& numBytes)const; + + ResourceManager& fRm; + uint64_t numBuckets; + uint64_t numConsumers; +// uint64_t maxElements; + uint64_t bitShifter; + int64_t phase; // 0 = produce phase, 1 = consume phase + WSVec rvbuckets; + RIDWSVec rbuckets; + bool multiProducer; + uint64_t lowestBucketID; + uint64_t largestBucketID; + boost::condition nextBucketReady; + boost::condition consumePhase; + uint64_t maxElementsInMem; + uint64_t insertCheckingThresh; + uint64_t maxElemPerBucket; + uint64_t nextBucketID; + uint elementMode; // 0 = RIDElementType, 1 = element_t (rid/value) + bool fDropInserts; + bool fTraceOn; +}; + +template +ZDL::ZDL(uint64_t nc, ResourceManager& rm) : + base(), fRm(rm), numBuckets(defaultNumBuckets), numConsumers(nc), phase(0), + multiProducer(false), lowestBucketID(defaultNumBuckets), largestBucketID(0), + maxElementsInMem(rm.getZdl_MaxElementsInMem()), + maxElemPerBucket(rm.getZdl_MaxElementsPerBucket()), + nextBucketID(0), elementMode(RID_ONLY), fDropInserts(false), fTraceOn(false) +{ + /* 1. start with 1 bucket + 2. calculate maxElements, bitShifter + 3. initialize condition and buckets + */ + uint64_t i; +// numConsumers = nc; +// nextBucketID = 0; +// multiProducer = false; + + + if ((maxElemPerBucket - 1) & maxElemPerBucket) + throw std::runtime_error("ZDL: ZDL_MaxElementsPerBucket should be a power of 2."); + +// config::Config *config = config::Config::makeConfig(); +// std::string strVal; +// strVal = config->getConfig("ZDL", "ZDL_MaxElementsPerBucket"); +// if (strVal.size() > 0){ +// maxElemPerBucket = config::Config::uFromText(strVal); +// if ((maxElemPerBucket - 1) & maxElemPerBucket) +// throw std::runtime_error("ZDL: ZDL_MaxElementsPerBucket should be a power of 2."); +// } +// else +// maxElemPerBucket = defaultMaxElementsPerBuckert; +// +// strVal = config->getConfig("ZDL", "ZDL_MaxElementsInMem"); +// if (strVal.size() > 0){ +// maxElementsInMem = config::Config::uFromText(strVal); +// } +// else +// maxElementsInMem = defaultMaxElementsInMem; + + // calculate shifter + for (i = 1; i <= 32; i++) { + if ((maxElemPerBucket >> i) & 1 ){ + bitShifter = i; + break; + } + } + + // initialize buckets + for (i = 0; i < defaultNumBuckets; i++) { + rbuckets.push_back(RIDSWSP(new WSDL + (numConsumers, maxElemPerBucket, fRm) )); + } + + insertCheckingThresh = maxElementsInMem / defaultNumBuckets; + //pthread_cond_init(&nextBucketReady, NULL); + //pthread_cond_init(&consumePhase, NULL); + ZDEBUG << "ZDL-" << this << " maxMem=" << maxElemPerBucket + << " shifter=" << bitShifter + << " #consumer= " << numConsumers << std::endl; +} + +template +ZDL::~ZDL() +{ + //pthread_cond_destroy(&nextBucketReady); + //pthread_cond_destroy(&consumePhase); +} + +template +void ZDL::setMultipleProducers(bool b) +{ + uint64_t i; + multiProducer = b; + if (elementMode == RID_ONLY) + for (i = 0; i < rbuckets.size(); i++) + rbuckets[i].get()->setMultipleProducers(b); + else + for (i = 0; i < rvbuckets.size(); i++) + rvbuckets[i].get()->setMultipleProducers(b); +} + +template +void ZDL::setMultipleProducers_r(bool b) +{ + uint64_t i; + multiProducer = b; + + for (i = 0; i < rbuckets.size(); i++) + rbuckets[i].get()->setMultipleProducers(b); +} + +template +void ZDL::setMultipleProducers_rv(bool b) +{ + uint64_t i; + multiProducer = b; + + for (i = 0; i < rvbuckets.size(); i++) + rvbuckets[i].get()->setMultipleProducers(b); +} + +template +void ZDL::insert(const element_t &e) +{ + if (fDropInserts) + return; + if (elementMode == RID_ONLY){ + RIDElementType rid(e.first); + insert_r(rid); + } + else + insert_rv(e); +} + +template +void ZDL::insert_r(const RIDElementType &e) +{ + /* 1. calculate bucketID + 2. if new bucketID, create new bucket, insert to vector at right pos + 3. update lowestBucketID and largestBucketID + 4. insert to bucket[bucketID] + */ + uint64_t bucketID = e.first >> bitShifter; + + checkBucket_r(bucketID); + + rbuckets[bucketID]->insert(e); + if (rbuckets[bucketID]->curSize % insertCheckingThresh == 0){ + uint64_t totalSize = 0; + uint64_t maxSize = 0; + uint64_t bigBucket = defaultNumBuckets; + for (uint64_t i = 0; i < rbuckets.size(); i++){ + uint64_t size = rbuckets[i]->curSize; + totalSize += size; + if (size > maxSize){ + bigBucket = i; + maxSize = size; + } + } + if (totalSize > maxElementsInMem) { + rbuckets[bigBucket]->flush(insertCheckingThresh); + } + } +} + +template +void ZDL::insert_rv(const element_t &e) +{ + /* 1. calculate bucketID + 2. if new bucketID, create new bucket, insert to vector at right pos + 3. update lowestBucketID and largestBucketID + 4. insert to bucket[bucketID] + */ + uint64_t bucketID = e.first >> bitShifter; + + checkBucket_rv(bucketID); + + rvbuckets[bucketID]->insert(e); + if (rvbuckets[bucketID]->curSize % insertCheckingThresh == 0){ + uint64_t totalSize = 0; + uint64_t maxSize = 0; + uint64_t bigBucket = defaultNumBuckets; + for (uint64_t i = 0; i < rvbuckets.size(); i++){ + uint64_t size = rvbuckets[i]->curSize; + totalSize += size; + if (size > maxSize){ + bigBucket = i; + maxSize = size; + } + } + if (totalSize > maxElementsInMem) { + rvbuckets[bigBucket]->flush(insertCheckingThresh); + } + } +} + +template +void ZDL::insert(const std::vector &v) +{ + if (fDropInserts) + return; + + typename std::vector::const_iterator it, end; + + end = v.end(); + uint64_t bucketID = 0; + bool checkFlush = false; + + if (multiProducer) base::lock(); + +try +{ + if (elementMode == RID_ONLY) + { + RIDElementType rid; + for (it = v.begin(); it != end; ++it) + { + bucketID = (*it).first >> bitShifter; + checkBucket_r(bucketID, false); + rid.first = (*it).first; + rbuckets[bucketID]->insert_nolock(rid); + // check threshold + if (!checkFlush && rbuckets[bucketID]->curSize % insertCheckingThresh == 0) + checkFlush = true; + } + + if (checkFlush) + { + uint64_t totalSize = 0; + uint64_t maxSize = 0; + uint64_t bigBucket = defaultNumBuckets; + for (uint64_t i = 0; i < rbuckets.size(); i++) + { + uint64_t size = rbuckets[i]->curSize; + totalSize += size; + if (size > maxSize){ + bigBucket = i; + maxSize = size; + } + } + if (totalSize > maxElementsInMem) + { + rbuckets[bigBucket]->flush(insertCheckingThresh, false); + } + } + } + else + { + for (it = v.begin(); it != end; ++it) + { + bucketID = (*it).first >> bitShifter; + checkBucket_rv(bucketID, false); + rvbuckets[bucketID]->insert_nolock(*it); + if (!checkFlush && rvbuckets[bucketID]->curSize % insertCheckingThresh == 0) + checkFlush = true; + } + + if (checkFlush) + { + uint64_t totalSize = 0; + uint64_t maxSize = 0; + uint64_t bigBucket = defaultNumBuckets; + for (uint64_t i = 0; i < rvbuckets.size(); i++) + { + uint64_t size = rvbuckets[i]->curSize; + totalSize += size; + if (size > maxSize) + { + bigBucket = i; + maxSize = size; + } + } + if (totalSize > maxElementsInMem) + { + rvbuckets[bigBucket]->flush(insertCheckingThresh, false); + } + } + } +} +catch(...) +{ + if (multiProducer) base::unlock(); + std::cerr << __FILE__ << "@" << __LINE__ << " ZDL insert vector caught an exception\n"; + throw; +} + if (multiProducer) base::unlock(); +} + +template +uint64_t ZDL::getIterator() +{ + if (elementMode == RID_ONLY) + return getIterator_r(); + else + return getIterator_rv(); +} + +template +uint64_t ZDL::getIterator_r() +{ + uint64_t id; + + base::lock(); + waitForConsumePhase(); + base::unlock(); + + if (lowestBucketID >= rbuckets.size()) { + return 0; + } + else + id = rbuckets[lowestBucketID]->getIterator(); + ZDEBUG << "ZDL-" << this << " consumer get iterator " << id << std::endl; + + return id; +} + +template +uint64_t ZDL::getIterator_rv() +{ + uint64_t id; + + base::lock(); + waitForConsumePhase(); + base::unlock(); + + if (lowestBucketID >= rvbuckets.size()) { + return 0; + } + else + id = rvbuckets[lowestBucketID]->getIterator(); + ZDEBUG << "ZDL-" << this << " consumer get iterator " << id << std::endl; + + return id; +} + +template +void ZDL::endOfInput() +{ + if (elementMode == RID_ONLY) + endOfInput_r(); + else + endOfInput_rv(); +} + +template +void ZDL::endOfInput_r() +{ + /* 1. call endOfInput on all buckets + 2. merge lowestBucketID bucket and sort + */ + uint64_t i; + if (multiProducer) + base::lock(); + + for (i = 0; i < rbuckets.size(); i++) { + rbuckets[i]->endOfInput_nosave(); + if ( rbuckets[i]->totalSize() != 0 ){ + largestBucketID = i; + if (i < lowestBucketID) lowestBucketID = i; + } + } + nextBucketID = lowestBucketID; + + // debug / profile + if (ZDL_DEBUG) { + uint64_t saveSize = 0; + for (i = 0; i < rbuckets.size(); i++) + saveSize += rbuckets[i]->saveSize; + + ZDEBUG << "ZDL-" << this << " end of input" + << " lowestID=" << lowestBucketID + << " largestID=" << largestBucketID << " saveSize=" << saveSize << std::endl; + } + + if (lowestBucketID < rbuckets.size()){ + ZDEBUG << "ZDL-" << this << " load bucket " << lowestBucketID << std::endl; + rbuckets[lowestBucketID]->mergeSets(); + } + phase = 1; + consumePhase.notify_all(); //pthread_cond_broadcast(&consumePhase); + ZDEBUG << "ZDL-" << this << " signal consumer" << std::endl; + if (multiProducer) + base::unlock(); +} + +template +void ZDL::endOfInput_rv() +{ + /* 1. call endOfInput on all buckets + 2. merge lowestBucketID bucket and sort + */ + uint64_t i; + if (multiProducer) + base::lock(); + + for (i = 0; i < rvbuckets.size(); i++) { + rvbuckets[i]->endOfInput_nosave(); + if ( rvbuckets[i]->totalSize() != 0 ){ + largestBucketID = i; + if (i < lowestBucketID) lowestBucketID = i; + } + } + nextBucketID = lowestBucketID; + + // debug / profile + if (ZDL_DEBUG) { + uint64_t saveSize = 0; + for (i = 0; i < rvbuckets.size(); i++) + saveSize += rvbuckets[i]->saveSize; + + ZDEBUG << "ZDL-" << this << " end of input" + << " lowestID=" << lowestBucketID + << " largestID=" << largestBucketID << " saveSize=" << saveSize << std::endl; + } + + // merge the first bucket here + if (lowestBucketID < rvbuckets.size()){ + ZDEBUG << "zdl-" << this << " load bucket " << lowestBucketID << std::endl; + rvbuckets[lowestBucketID]->mergeSets(); + } + phase = 1; + consumePhase.notify_all(); //pthread_cond_broadcast(&consumePhase); + ZDEBUG << "ZDL-" << this << " signal consumer" << std::endl; + if (multiProducer) + base::unlock(); +} + +template +bool ZDL::next(uint64_t it, element_t *e) +{ + if (elementMode == RID_ONLY) + { + RIDElementType rid; + bool ret = next_r(it, &rid); + e->first = rid.first; + return ret; + } + else + return next_rv(it, e); +} + +template +bool ZDL::next_r(uint64_t it, RIDElementType *e) +{ + /* 1. read from lowestBucketID bucket + 2. if read false, check if more buckets are available and update lowestBucketID + 3. if yes and this is the last consumer, merge lowestBucketID bucket and signal + 4. if not the last consumer, wait + 5. read from new lowestBucketID bucket + 6. if no more, all done and return false + */ + int ret; + bool locked = false; + if (phase == 0) + { + locked = true; + base::lock(); + waitForConsumePhase(); + } + + if (lowestBucketID >= rbuckets.size()){ + ZDEBUG << "ZDL-" << this << " consumer " << it << " return false on empty ZDL" << std::endl; + if (locked) + base::unlock(); + return false; + } + + ret = rbuckets[lowestBucketID]->next(it, e); + if (!ret) { + + if (lowestBucketID == largestBucketID){ + if (locked) + base::unlock(); + ZDEBUG << "ZDL-" << this << " Consumer " << it << " finished" << std::endl; + return (ret != 0); + } + + if (numConsumers > 1 || phase == 0){ + locked = true; + base::lock(); + } + + // more buckets. last consumer load new bucket + if (++base::consumersFinished == numConsumers) { + if (lowestBucketID != nextBucketID) { + lowestBucketID = nextBucketID; + ZDEBUG << "ZDL-" << this << " Consumer " << it << " call next bucket " << lowestBucketID << std::endl; + nextBucketReady.notify_all(); //pthread_cond_broadcast(&nextBucketReady); + } + else { + // being the only consumer + nextBucketID = nextBucket(lowestBucketID); + lowestBucketID = nextBucketID; + ZDEBUG << "ZDL-" << this << " consumer " << it << " merge next bucket " << nextBucketID << std::endl; + rbuckets[lowestBucketID]->mergeSets(); + } + base::consumersFinished = 0; + } + else { + // 1st finished consumer merge next set + if (base::consumersFinished == 1) { + nextBucketID = nextBucket(lowestBucketID); + ZDEBUG << "ZDL-" << this << " consumer " << it << " merge next bucket " << nextBucketID << std::endl; + rbuckets[nextBucketID]->mergeSets(); + } + nextBucketReady.wait(this->mutex); //pthread_cond_wait(&nextBucketReady, &(this->mutex)); + } + if (locked) + base::unlock(); + + ret = rbuckets[lowestBucketID]->next(it, e); + } + + return (ret != 0); + +} + +template +bool ZDL::next_rv(uint64_t it, element_t *e) +{ + /* 1. read from lowestBucketID bucket + 2. if read false, check if more buckets are available and update lowestBucketID + 3. if yes and this is the last consumer, merge lowestBucketID bucket and signal + 4. if not the last consumer, wait + 5. read from new lowestBucketID bucket + 6. if no more, all done and return false + */ + int ret; + bool locked = false; + if (phase == 0) + { + locked = true; + base::lock(); + waitForConsumePhase(); + } + + if (lowestBucketID >= rvbuckets.size()){ + ZDEBUG << "ZDL-" << this << " consumer " << it << " return false on empty ZDL" << std::endl; + if (locked) + base::unlock(); + return false; + } + + ret = rvbuckets[lowestBucketID]->next(it, e); + if (!ret) { + + if (lowestBucketID == largestBucketID){ + if (locked) + base::unlock(); + ZDEBUG << "ZDL-" << this << " Consumer " << it << " finished" << std::endl; + return (ret != 0); + } + + if (numConsumers > 1 || phase == 0){ + locked = true; + base::lock(); + } + + // more buckets. last consumer load new bucket + if (++base::consumersFinished == numConsumers) { + if (lowestBucketID != nextBucketID) { + lowestBucketID = nextBucketID; + ZDEBUG << "ZDL-" << this << " Consumer " << it << " call next bucket " << lowestBucketID << std::endl; + nextBucketReady.notify_all(); //pthread_cond_broadcast(&nextBucketReady); + } + else { + // being the only consumer + nextBucketID = nextBucket(lowestBucketID); + lowestBucketID = nextBucketID; + ZDEBUG << "ZDL-" << this << " consumer " << it << " merge next bucket " << nextBucketID << std::endl; + rvbuckets[lowestBucketID]->mergeSets(); + } + base::consumersFinished = 0; + } + else { + // 1st finished consumer merge next set + if (base::consumersFinished == 1) { + nextBucketID = nextBucket(lowestBucketID); + ZDEBUG << "ZDL-" << this << " consumer " << it << " merge next bucket " << nextBucketID << std::endl; + rvbuckets[nextBucketID]->mergeSets(); + } + nextBucketReady.wait(this->mutex); //pthread_cond_wait(&nextBucketReady, &(this->mutex)); + } + if (locked) + base::unlock(); + + ret = rvbuckets[lowestBucketID]->next(it, e); + } + + return (ret != 0); + +} + +template +uint64_t ZDL::size(uint64_t bucket) +{ + if (elementMode == RID_ONLY) + return rbuckets[bucket].get()->totalSize(); + else + return rvbuckets[bucket].get()->totalSize(); +} + +template +uint64_t ZDL::bucketCount() +{ + waitForConsumePhase(); + return numBuckets; +} + +template +uint64_t ZDL::totalSize() +{ + uint64_t ret = 0; + uint i; + + if (elementMode == RID_ONLY) + for (i = 0; i < rbuckets.size(); i++) + ret += rbuckets[i].get()->totalSize(); + else + for (i = 0; i < rvbuckets.size(); i++) + ret += rvbuckets[i].get()->totalSize(); + return ret; +} + +template +uint64_t ZDL::nextBucket(uint64_t bucketID) +{ + if (elementMode == RID_ONLY) + return nextBucket_r (bucketID); + else + return nextBucket_rv (bucketID); +} + +template +uint64_t ZDL::nextBucket_r(uint64_t bucketID) +{ + // should already be consumption phase by now + uint64_t i; + if ( bucketID >= rbuckets.size()) + return bucketID; + + for (i = bucketID+1; i <= largestBucketID; i++) { + if (rbuckets[i]->totalSize() != 0){ + return i; + } + } + return bucketID; +} + +template +uint64_t ZDL::nextBucket_rv(uint64_t bucketID) +{ + // should already be consumption phase by now + uint64_t i; + if ( bucketID >= rvbuckets.size()) + return bucketID; + + for (i = bucketID+1; i <= largestBucketID; i++) { + if (rvbuckets[i]->totalSize() != 0){ + return i; + } + } + return bucketID; +} + +template +void ZDL::resetNumConsumers(uint nc) +{ + uint64_t i; + numConsumers = nc; + if (elementMode == RID_ONLY) + for (i = 0; i < rbuckets.size(); i++) + rbuckets[i].get()->resetNumConsumers(numConsumers); + else + for (i = 0; i < rvbuckets.size(); i++) + rvbuckets[i].get()->resetNumConsumers(numConsumers); +} + +template +inline void ZDL::waitForConsumePhase() +{ + while (phase == 0) + consumePhase.wait(this->mutex); //pthread_cond_wait(&consumePhase, &(this->mutex)); +} + +template +void ZDL::setElementMode(const uint mode) +{ + ZDEBUG << "ZDL-" << this << " set elementmode " << mode << std::endl; + if (elementMode != mode) + { + if (elementMode == RID_ONLY) + rbuckets.clear(); + else + rvbuckets.clear(); + elementMode = mode; + if (elementMode == RID_ONLY){ + RIDSWSP ridswsp; + for (uint64_t i = 0; i < defaultNumBuckets; i++) { + ridswsp.reset(new WSDL + (numConsumers, maxElemPerBucket, + base::getDiskElemSize1st(), + base::getDiskElemSize2nd(), fRm) ); + ridswsp->setMultipleProducers(multiProducer); + ridswsp->traceOn(fTraceOn); + rbuckets.push_back(ridswsp); + } + } + else { + SWSP swsp; + for (uint64_t i = 0; i < defaultNumBuckets; i++) { + swsp.reset(new WSDL + (numConsumers, maxElemPerBucket, + base::getDiskElemSize1st(), + base::getDiskElemSize2nd(), fRm) ); + swsp->setMultipleProducers(multiProducer); + swsp->traceOn(fTraceOn); + rvbuckets.push_back(swsp); + } + } + } +} + +template +inline void ZDL::checkBucket_r(uint64_t bucketID, bool lockFlag) +{ + if (bucketID >= rbuckets.size()) + { + if (lockFlag) base::lock(); + RIDSWSP ridswsp; + // increase buckets when necessary + while (bucketID >= rbuckets.size()) { + for (uint64_t i = 0; i < defaultNumBuckets; i++) { + ridswsp.reset(new WSDL + (numConsumers, maxElemPerBucket, + base::getDiskElemSize1st(), + base::getDiskElemSize2nd(), fRm ) ); + ridswsp->setMultipleProducers(multiProducer); + rbuckets.push_back(ridswsp); + } + } + numBuckets = rbuckets.size(); + if (lockFlag) base::unlock(); + } +} + +template +// @bug 831. check lockFlag to lock or not +inline void ZDL::checkBucket_rv(uint64_t bucketID, bool lockFlag) +{ + if (bucketID >= rvbuckets.size()) + { + if (lockFlag) base::lock(); + SWSP swsp; + // increase buckets when necessary + while (bucketID >= rvbuckets.size()) { + for (uint64_t i = 0; i < defaultNumBuckets; i++) { + swsp.reset(new WSDL + (numConsumers, maxElemPerBucket, + base::getDiskElemSize1st(), + base::getDiskElemSize2nd(), fRm )); + swsp->setMultipleProducers(multiProducer); + rvbuckets.push_back(swsp); + } + } + numBuckets = rvbuckets.size(); + if (lockFlag) base::unlock(); + } +} + +// +// Returns the number of temp files and the space taken up by those files +// (in bytes) by this ZDL collection. +// +template +void ZDL::totalFileCounts(uint64_t& numFiles, uint64_t& numBytes) + const +{ + numFiles = 0; + numBytes = 0; + + if (elementMode == RID_ONLY) + totalFileCounts_r (numFiles, numBytes); + else + totalFileCounts_rv(numFiles, numBytes); +} + +template +void ZDL::totalFileCounts_r(uint64_t& numFiles, uint64_t& numBytes) + const +{ + for (uint64_t i = 0; i < rbuckets.size(); i++) + { + uint64_t setCnt = rbuckets[i].get()->initialSetCount(); + + if (setCnt > 1) + { + //std::cout << "ZDL: bucket " << i << " has " << setCnt << + // " sets" << std::endl; + + numFiles += rbuckets[i].get()->numberOfTempFiles(); + numBytes += rbuckets[i].get()->saveSize; + } + } +} + +template +void ZDL::totalFileCounts_rv(uint64_t& numFiles, uint64_t& numBytes) + const +{ + for (uint64_t i = 0; i < rvbuckets.size(); i++) + { + uint64_t setCnt = rvbuckets[i].get()->initialSetCount(); + + if (setCnt > 1) + { + //std::cout << "ZDL: bucket " << i << " has " << setCnt << + // " sets" << std::endl; + + numFiles += rvbuckets[i].get()->numberOfTempFiles(); + numBytes += rvbuckets[i].get()->saveSize; + } + } +} + +#if 0 +template +bool ZDL::next(uint64_t bucket, uint64_t it, element_t *e) +{ + if (elementMode == RID_ONLY) + { + RIDElementType rid; + bool ret; + if (!rbuckets[bucket]->mergeFlag) + { + if (numConsumers >1) + base::lock(); + rbuckets[bucket]->mergeSets(); + if (numConsumers >1) + base::unlock(); + } + ret = rbuckets[bucket]->next(it, &rid); + e->first = rid.first; + return ret; + } + else + { + if (!rvbuckets[bucket]->mergeFlag) + { + if (numConsumers >1) + base::lock(); + rvbuckets[bucket]->mergeSets(); + if (numConsumers >1) + base::unlock(); + } + return rvbuckets[bucket]->next(it, e); + } +} +#endif + +// +// Sets the sizes to be employed in saving the elements to disk. +// size1st is the size in bytes of element_t.first. +// size2nd is the size in bytes of element_t.second. +// +template +void ZDL::setDiskElemSize(uint32_t size1st,uint32_t size2nd) +{ + base::fElemDiskFirstSize = size1st; + base::fElemDiskSecondSize = size2nd; + + //...Forward this size information to our internal WSDL containers. + + if (elementMode == RID_ONLY) + { + for (uint64_t i = 0; i < rbuckets.size(); i++) + { + rbuckets[i]->setDiskElemSize ( size1st, size2nd ); + } + } + else + { + for (uint64_t i = 0; i < rvbuckets.size(); i++) + { + rvbuckets[i]->setDiskElemSize ( size1st, size2nd ); + } + } +} + +template +void ZDL::enableDiskIoTrace() +{ + fTraceOn = true; + if (elementMode == RID_ONLY) + for (uint64_t bucket = 0; bucket < numBuckets; bucket++) + rbuckets[bucket]->traceOn(fTraceOn); + else + for (uint64_t bucket = 0; bucket < numBuckets; bucket++) + rvbuckets[bucket]->traceOn(fTraceOn); +} + +template +bool ZDL::totalDiskIoTime(uint64_t& w, uint64_t& r) +{ + boost::posix_time::time_duration wTime(0,0,0,0); + boost::posix_time::time_duration rTime(0,0,0,0); + bool diskIo = false; + + for (uint64_t bucket = 0; bucket < numBuckets; bucket++) + { + std::list& infoList = diskIoInfoList(bucket); + std::list::iterator k = infoList.begin(); + while (k != infoList.end()) + { + if (k->fWrite == true) + wTime += k->fEnd - k->fStart; + else + rTime += k->fEnd - k->fStart; + k++; + } + + if (infoList.size() > 0) + diskIo = true; + } + + w = wTime.total_seconds(); + r = rTime.total_seconds(); + + return diskIo; +} + +template +std::list& ZDL::diskIoInfoList(uint64_t bucket) +{ + if (elementMode == RID_ONLY) + return (rbuckets[bucket]->diskIoList()); + else + return (rvbuckets[bucket]->diskIoList()); +} + + +} //namespace + +#endif diff --git a/dbcon/mysql/CMakeLists.txt b/dbcon/mysql/CMakeLists.txt deleted file mode 100644 index b28fab8b..00000000 --- a/dbcon/mysql/CMakeLists.txt +++ /dev/null @@ -1,155 +0,0 @@ -# Copyright (C) 2006 MySQL AB -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; version 2 of the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -INCLUDE("${PROJECT_SOURCE_DIR}/win/mysql_manifest.cmake") - -SET(CMAKE_CXX_FLAGS_DEBUG - "${CMAKE_CXX_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX -DUSE_SYMDIR /Zi") -SET(CMAKE_C_FLAGS_DEBUG - "${CMAKE_C_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX -DUSE_SYMDIR /Zi") -SET(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /MAP /MAPINFO:EXPORTS") - -INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include - ${CMAKE_SOURCE_DIR}/extra/yassl/include - ${CMAKE_SOURCE_DIR}/sql - ${CMAKE_SOURCE_DIR}/regex - ${CMAKE_SOURCE_DIR}/zlib -) - -SET_SOURCE_FILES_PROPERTIES(${CMAKE_SOURCE_DIR}/sql/sql_yacc.h - ${CMAKE_SOURCE_DIR}/sql/sql_yacc.cc - ${CMAKE_SOURCE_DIR}/include/mysql_version.h - ${CMAKE_SOURCE_DIR}/sql/sql_builtin.cc - ${CMAKE_SOURCE_DIR}/sql/lex_hash.h - ${PROJECT_SOURCE_DIR}/include/mysqld_error.h - ${PROJECT_SOURCE_DIR}/include/mysqld_ername.h - ${PROJECT_SOURCE_DIR}/include/sql_state.h - PROPERTIES GENERATED 1) - -ADD_DEFINITIONS(-DMYSQL_SERVER -D_CONSOLE -DHAVE_DLOPEN -DHAVE_EVENT_SCHEDULER) - - -SET (SQL_SOURCE - ../sql-common/client.c derror.cc des_key_file.cc - discover.cc ../libmysql/errmsg.c field.cc field_conv.cc - filesort.cc gstream.cc - ha_partition.cc - handler.cc hash_filo.cc hash_filo.h - hostname.cc init.cc item.cc item_buff.cc item_cmpfunc.cc - item_create.cc item_func.cc item_geofunc.cc item_row.cc - item_strfunc.cc item_subselect.cc item_sum.cc item_timefunc.cc - item_window_function.cc item_create_window_function.cc - key.cc log.cc lock.cc message.rc - log_event.cc rpl_record.cc rpl_reporting.cc - log_event_old.cc rpl_record_old.cc - message.h mf_iocache.cc my_decimal.cc ../sql-common/my_time.c - mysqld.cc net_serv.cc - nt_servc.cc nt_servc.h opt_range.cc opt_range.h opt_sum.cc - ../sql-common/pack.c parse_file.cc password.c procedure.cc - protocol.cc records.cc repl_failsafe.cc rpl_filter.cc set_var.cc - slave.cc sp.cc sp_cache.cc sp_head.cc sp_pcontext.cc - sp_rcontext.cc spatial.cc sql_acl.cc sql_analyse.cc sql_base.cc - sql_cache.cc sql_class.cc sql_client.cc sql_crypt.cc sql_crypt.h - sql_cursor.cc sql_db.cc sql_delete.cc sql_derived.cc sql_do.cc - sql_error.cc sql_handler.cc sql_help.cc sql_insert.cc sql_lex.cc - sql_list.cc sql_load.cc sql_manager.cc sql_map.cc sql_parse.cc - sql_partition.cc sql_plugin.cc sql_prepare.cc sql_rename.cc - sql_repl.cc sql_select.cc sql_show.cc sql_state.c sql_string.cc - sql_table.cc sql_test.cc sql_trigger.cc sql_udf.cc sql_union.cc - sql_update.cc sql_view.cc strfunc.cc table.cc thr_malloc.cc - time.cc tztime.cc uniques.cc unireg.cc item_xmlfunc.cc - rpl_tblmap.cc sql_binlog.cc event_scheduler.cc event_data_objects.cc - event_queue.cc event_db_repository.cc - sql_tablespace.cc events.cc ../sql-common/my_user.c - partition_info.cc rpl_utility.cc rpl_injector.cc sql_locale.cc - rpl_rli.cc rpl_mi.cc sql_servers.cc - sql_connect.cc scheduler.cc - sql_profile.cc event_parse_data.cc - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.cc - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.h - ${PROJECT_SOURCE_DIR}/include/mysqld_error.h - ${PROJECT_SOURCE_DIR}/include/mysqld_ername.h - ${PROJECT_SOURCE_DIR}/include/sql_state.h - ${PROJECT_SOURCE_DIR}/include/mysql_version.h - ${PROJECT_SOURCE_DIR}/sql/sql_builtin.cc - ${PROJECT_SOURCE_DIR}/sql/lex_hash.h) -ADD_LIBRARY(sql ${SQL_SOURCE}) - -IF (NOT EXISTS cmake_dummy.cc) - FILE (WRITE cmake_dummy.cc "") -ENDIF (NOT EXISTS cmake_dummy.cc) -ADD_EXECUTABLE(mysqld cmake_dummy.cc) - -SET_TARGET_PROPERTIES(mysqld PROPERTIES OUTPUT_NAME mysqld${MYSQLD_EXE_SUFFIX}) -SET_TARGET_PROPERTIES(mysqld PROPERTIES ENABLE_EXPORTS TRUE) - -SET (MYSQLD_CORE_LIBS mysys zlib dbug strings yassl taocrypt vio regex sql) -TARGET_LINK_LIBRARIES(mysqld ${MYSQLD_CORE_LIBS} ${MYSQLD_STATIC_ENGINE_LIBS}) -TARGET_LINK_LIBRARIES(mysqld ws2_32.lib) - - -IF(MSVC AND NOT WITHOUT_DYNAMIC_PLUGINS) - # Set module definition file. Also use non-incremental linker, - # incremental appears to crash from time to time,if used with /DEF option - SET_TARGET_PROPERTIES(mysqld PROPERTIES LINK_FLAGS "/DEF:mysqld.def /INCREMENTAL:NO") - - FOREACH (CORELIB ${MYSQLD_CORE_LIBS}) - GET_TARGET_PROPERTY(LOC ${CORELIB} LOCATION) - FILE(TO_NATIVE_PATH ${LOC} LOC) - SET (LIB_LOCATIONS ${LIB_LOCATIONS} ${LOC}) - ENDFOREACH (CORELIB ${MYSQLD_CORE_LIBS}) - - ADD_CUSTOM_COMMAND(TARGET mysqld PRE_LINK - COMMAND cscript ARGS //nologo ${PROJECT_SOURCE_DIR}/win/create_def_file.js - ${PLATFORM} ${LIB_LOCATIONS} > mysqld.def - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/sql) -ENDIF(MSVC AND NOT WITHOUT_DYNAMIC_PLUGINS) - -ADD_DEPENDENCIES(sql GenError) - -# Sql Parser custom command -ADD_CUSTOM_COMMAND( - OUTPUT ${PROJECT_SOURCE_DIR}/sql/sql_yacc.h - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.cc - COMMAND bison ARGS -y -p MYSQL --defines=sql_yacc.h - --output=sql_yacc.cc sql_yacc.yy - DEPENDS ${PROJECT_SOURCE_DIR}/sql/sql_yacc.yy) - - -# Gen_lex_hash -ADD_EXECUTABLE(gen_lex_hash gen_lex_hash.cc) -TARGET_LINK_LIBRARIES(gen_lex_hash debug dbug mysqlclient wsock32) -GET_TARGET_PROPERTY(GEN_LEX_HASH_EXE gen_lex_hash LOCATION) -ADD_CUSTOM_COMMAND( - OUTPUT ${PROJECT_SOURCE_DIR}/sql/lex_hash.h - COMMAND ${GEN_LEX_HASH_EXE} ARGS > lex_hash.h - DEPENDS ${GEN_LEX_HASH_EXE}) - -ADD_CUSTOM_TARGET( - GenServerSource ALL - DEPENDS ${PROJECT_SOURCE_DIR}/sql/sql_yacc.h - ${PROJECT_SOURCE_DIR}/sql/sql_yacc.cc - ${PROJECT_SOURCE_DIR}/sql/message.h - ${PROJECT_SOURCE_DIR}/sql/message.rc - ${PROJECT_SOURCE_DIR}/sql/lex_hash.h) - -ADD_DEPENDENCIES(mysqld GenServerSource) - -# Remove the auto-generated files as part of 'Clean Solution' -SET_DIRECTORY_PROPERTIES(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES - "lex_hash.h;sql_yacc.h;sql_yacc.cc;mysqld.def") - -ADD_LIBRARY(udf_example MODULE udf_example.c udf_example.def) -ADD_DEPENDENCIES(udf_example strings GenError) -TARGET_LINK_LIBRARIES(udf_example strings wsock32) diff --git a/dbcon/mysql/Makefile.am b/dbcon/mysql/Makefile.am index eaccd8f2..03ea9ecd 100644 --- a/dbcon/mysql/Makefile.am +++ b/dbcon/mysql/Makefile.am @@ -14,17 +14,21 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) lib_LTLIBRARIES = libcalmysql.la -libcalmysql_la_SOURCES = ha_calpont.cpp ha_calpont_impl.cpp ha_calpont_dml.cpp ha_calpont_ddl.cpp ha_calpont_execplan.cpp ha_scalar_sub.cpp ha_in_sub.cpp ha_exists_sub.cpp ha_from_sub.cpp ha_select_sub.cpp ha_view.cpp sm.cpp ha_window_function.cpp ha_calpont_partition.cpp ha_pseudocolumn.cpp -libcalmysql_la_LDFLAGS = -version-info 1:0:0 $(idb_common_ldflags) $(idb_common_libs) $(idb_write_libs) $(AM_LDFLAGS) -libcalmysql_la_CPPFLAGS = -I/usr/include/libxml2 -I../../../mysql/include -I../../../mysql/sql -I../../../mysql/regex -DMYSQL_DYNAMIC_PLUGIN $(AM_CPPFLAGS) -include_HEADERS = idb_mysql.h +libcalmysql_la_SOURCES = ha_calpont.cpp ha_calpont_impl.cpp ha_calpont_dml.cpp ha_calpont_ddl.cpp ha_calpont_udf.cpp ha_calpont_execplan.cpp ha_scalar_sub.cpp ha_in_sub.cpp ha_exists_sub.cpp ha_from_sub.cpp ha_select_sub.cpp +libcalmysql_la_LDFLAGS = -version-info 1:0:0 $(idb_common_ldflags) $(idb_common_libs) $(idb_write_libs) -lsm $(AM_LDFLAGS) +libcalmysql_la_CPPFLAGS = -I/usr/include/libxml2 -I../../mysql/include -I../../mysql/sql -I../../mysql/regex -DMYSQL_DYNAMIC_PLUGIN $(AM_CPPFLAGS) +include_HEADERS = -dist_mysql_DATA = syscatalog_mysql.sql dumpcat_mysql.sql calsetuserpriority.sql calremoveuserpriority.sql calshowprocesslist.sql my.cnf +dist_mysql_DATA = syscatalog_mysql.sql dumpcat_mysql.sql calsetuserpriority.sql calremoveuserpriority.sql calshowprocesslist.sql dist_mysql_SCRIPTS = install_calpont_mysql.sh mysql-Calpont dumpcat.pl test: diff --git a/dbcon/mysql/Makefile.am.mysql b/dbcon/mysql/Makefile.am.mysql deleted file mode 100644 index b14a4d63..00000000 --- a/dbcon/mysql/Makefile.am.mysql +++ /dev/null @@ -1,194 +0,0 @@ -# Copyright (C) 2000-2006 MySQL AB -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; version 2 of the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -#called from the top level Makefile - -MYSQLDATAdir = $(localstatedir) -MYSQLSHAREdir = $(pkgdatadir) -MYSQLBASEdir= $(prefix) -MYSQLLIBdir= $(pkglibdir) -pkgplugindir = $(pkglibdir)/plugin -INCLUDES = @ZLIB_INCLUDES@ \ - -I$(top_builddir)/include -I$(top_srcdir)/include \ - -I$(top_srcdir)/regex -I$(srcdir) $(openssl_includes) -WRAPLIBS= @WRAPLIBS@ -SUBDIRS = share -libexec_PROGRAMS = mysqld -EXTRA_PROGRAMS = gen_lex_hash -bin_PROGRAMS = mysql_tzinfo_to_sql - -noinst_LTLIBRARIES= libndb.la \ - udf_example.la - -SUPPORTING_LIBS = $(top_builddir)/vio/libvio.a \ - $(top_builddir)/mysys/libmysys.a \ - $(top_builddir)/dbug/libdbug.a \ - $(top_builddir)/regex/libregex.a \ - $(top_builddir)/strings/libmystrings.a -mysqld_DEPENDENCIES= @mysql_plugin_libs@ $(SUPPORTING_LIBS) libndb.la -LDADD = $(SUPPORTING_LIBS) @ZLIB_LIBS@ @NDB_SCI_LIBS@ -mysqld_LDADD = libndb.la \ - @MYSQLD_EXTRA_LDFLAGS@ \ - @pstack_libs@ \ - @mysql_plugin_libs@ \ - $(LDADD) $(CXXLDFLAGS) $(WRAPLIBS) @LIBDL@ \ - $(yassl_libs) $(openssl_libs) @MYSQLD_EXTRA_LIBS@ - -noinst_HEADERS = item.h item_func.h item_sum.h item_cmpfunc.h \ - item_strfunc.h item_timefunc.h \ - item_xmlfunc.h item_window_function.h \ - item_create.h item_subselect.h item_row.h \ - mysql_priv.h item_geofunc.h sql_bitmap.h \ - procedure.h sql_class.h sql_lex.h sql_list.h \ - sql_map.h sql_string.h unireg.h \ - sql_error.h field.h handler.h mysqld_suffix.h \ - sql_profile.h \ - ha_ndbcluster.h ha_ndbcluster_cond.h \ - ha_ndbcluster_binlog.h ha_ndbcluster_tables.h \ - ha_partition.h rpl_constants.h \ - opt_range.h protocol.h rpl_tblmap.h rpl_utility.h \ - rpl_reporting.h \ - log.h sql_show.h rpl_rli.h rpl_mi.h \ - sql_select.h structs.h table.h sql_udf.h hash_filo.h \ - lex.h lex_symbol.h sql_acl.h sql_crypt.h \ - sql_repl.h slave.h rpl_filter.h rpl_injector.h \ - log_event.h rpl_record.h \ - log_event_old.h rpl_record_old.h \ - sql_sort.h sql_cache.h set_var.h \ - spatial.h gstream.h client_settings.h tzfile.h \ - tztime.h my_decimal.h\ - sp_head.h sp_pcontext.h sp_rcontext.h sp.h sp_cache.h \ - parse_file.h sql_view.h sql_trigger.h \ - sql_array.h sql_cursor.h events.h scheduler.h \ - event_db_repository.h event_queue.h \ - sql_plugin.h authors.h event_parse_data.h \ - event_data_objects.h event_scheduler.h \ - sql_partition.h partition_info.h partition_element.h \ - contributors.h sql_servers.h \ - item_create_window_function.h \ - errorids.h - -mysqld_SOURCES = sql_lex.cc sql_handler.cc sql_partition.cc \ - item.cc item_sum.cc item_buff.cc item_func.cc item_window_function.cc\ - item_cmpfunc.cc item_strfunc.cc item_timefunc.cc\ - thr_malloc.cc item_create.cc item_create_window_function.cc item_subselect.cc \ - item_row.cc item_geofunc.cc item_xmlfunc.cc \ - field.cc strfunc.cc key.cc sql_class.cc sql_list.cc \ - net_serv.cc protocol.cc sql_state.c \ - lock.cc my_lock.c \ - sql_string.cc sql_manager.cc sql_map.cc \ - mysqld.cc password.c hash_filo.cc hostname.cc \ - sql_connect.cc scheduler.cc sql_parse.cc \ - set_var.cc sql_yacc.yy \ - sql_base.cc table.cc sql_select.cc sql_insert.cc \ - sql_profile.cc \ - sql_prepare.cc sql_error.cc sql_locale.cc \ - sql_update.cc sql_delete.cc uniques.cc sql_do.cc \ - procedure.cc sql_test.cc \ - log.cc init.cc derror.cc sql_acl.cc \ - unireg.cc des_key_file.cc \ - log_event.cc rpl_record.cc \ - log_event_old.cc rpl_record_old.cc \ - discover.cc time.cc opt_range.cc opt_sum.cc \ - records.cc filesort.cc handler.cc \ - ha_partition.cc \ - sql_db.cc sql_table.cc sql_rename.cc sql_crypt.cc \ - sql_load.cc mf_iocache.cc field_conv.cc sql_show.cc \ - sql_udf.cc sql_analyse.cc sql_analyse.h sql_cache.cc \ - slave.cc sql_repl.cc rpl_filter.cc rpl_tblmap.cc \ - rpl_utility.cc rpl_injector.cc rpl_rli.cc rpl_mi.cc \ - rpl_reporting.cc \ - sql_union.cc sql_derived.cc \ - sql_client.cc \ - repl_failsafe.h repl_failsafe.cc \ - sql_olap.cc sql_view.cc \ - gstream.cc spatial.cc sql_help.cc sql_cursor.cc \ - tztime.cc my_decimal.cc\ - sp_head.cc sp_pcontext.cc sp_rcontext.cc sp.cc \ - sp_cache.cc parse_file.cc sql_trigger.cc \ - event_scheduler.cc event_data_objects.cc \ - event_queue.cc event_db_repository.cc events.cc \ - sql_plugin.cc sql_binlog.cc \ - sql_builtin.cc sql_tablespace.cc partition_info.cc \ - sql_servers.cc event_parse_data.cc - -nodist_mysqld_SOURCES = mini_client_errors.c pack.c client.c my_time.c my_user.c - -libndb_la_CPPFLAGS= @ndbcluster_includes@ -libndb_la_SOURCES= ha_ndbcluster.cc \ - ha_ndbcluster_binlog.cc \ - ha_ndbcluster_cond.cc - -gen_lex_hash_SOURCES = gen_lex_hash.cc -gen_lex_hash_LDFLAGS = @NOINST_LDFLAGS@ - -mysql_tzinfo_to_sql_SOURCES = tztime.cc -mysql_tzinfo_to_sql_CXXFLAGS= -DTZINFO2SQL - -DEFS = -DMYSQL_SERVER \ - -DDEFAULT_MYSQL_HOME="\"$(MYSQLBASEdir)\"" \ - -DMYSQL_DATADIR="\"$(MYSQLDATAdir)\"" \ - -DSHAREDIR="\"$(MYSQLSHAREdir)\"" \ - -DPLUGINDIR="\"$(pkgplugindir)\"" \ - -DHAVE_EVENT_SCHEDULER \ - @DEFS@ - -BUILT_MAINT_SRC = sql_yacc.cc sql_yacc.h -BUILT_SOURCES = $(BUILT_MAINT_SRC) lex_hash.h link_sources -EXTRA_DIST = udf_example.c udf_example.def $(BUILT_MAINT_SRC) \ - nt_servc.cc nt_servc.h \ - message.mc message.h message.rc MSG00001.bin \ - CMakeLists.txt - -CLEANFILES = lex_hash.h sql_yacc.output link_sources -DISTCLEANFILES = $(EXTRA_PROGRAMS) -MAINTAINERCLEANFILES = $(BUILT_MAINT_SRC) -AM_YFLAGS = -d --verbose - -# These are listed in 'nodist_mysqld_SOURCES' -link_sources: - rm -f mini_client_errors.c - @LN_CP_F@ $(top_srcdir)/libmysql/errmsg.c mini_client_errors.c - rm -f pack.c - @LN_CP_F@ $(top_srcdir)/sql-common/pack.c pack.c - rm -f client.c - @LN_CP_F@ $(top_srcdir)/sql-common/client.c client.c - rm -f my_time.c - @LN_CP_F@ $(top_srcdir)/sql-common/my_time.c my_time.c - rm -f my_user.c - @LN_CP_F@ $(top_srcdir)/sql-common/my_user.c my_user.c - echo timestamp > link_sources - -# This generates lex_hash.h -# NOTE Built sources should depend on their sources not the tool -# this avoid the rebuild of the built files in a source dist -lex_hash.h: gen_lex_hash.cc lex.h - $(MAKE) $(AM_MAKEFLAGS) gen_lex_hash$(EXEEXT) - ./gen_lex_hash$(EXEEXT) > $@-t - $(MV) $@-t $@ - -# For testing of udf_example.so -udf_example_la_SOURCES= udf_example.c -udf_example_la_LDFLAGS= -module -rpath $(pkglibdir) - -# We might have some stuff not built in this build, but that we want to install -install-exec-hook: - $(mkinstalldirs) $(DESTDIR)$(libexecdir) $(DESTDIR)$(pkglibdir) - test ! -x mysqld-debug$(EXEEXT) || $(INSTALL_PROGRAM) mysqld-debug$(EXEEXT) $(DESTDIR)$(libexecdir) - test ! -f mysqld-debug.sym.gz || $(INSTALL_DATA) mysqld-debug.sym.gz $(DESTDIR)$(pkglibdir) - test ! -f mysqld.sym.gz || $(INSTALL_DATA) mysqld.sym.gz $(DESTDIR)$(pkglibdir) - -# Don't update the files from bitkeeper -%::SCCS/s.% diff --git a/dbcon/mysql/Makefile.in b/dbcon/mysql/Makefile.in index b7509130..bbe4d3e7 100644 --- a/dbcon/mysql/Makefile.in +++ b/dbcon/mysql/Makefile.in @@ -14,6 +14,25 @@ @SET_MAKE@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + @@ -43,9 +62,8 @@ subdir = dbcon/mysql DIST_COMMON = $(dist_mysql_DATA) $(dist_mysql_SCRIPTS) \ $(include_HEADERS) $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -66,13 +84,11 @@ am_libcalmysql_la_OBJECTS = libcalmysql_la-ha_calpont.lo \ libcalmysql_la-ha_calpont_impl.lo \ libcalmysql_la-ha_calpont_dml.lo \ libcalmysql_la-ha_calpont_ddl.lo \ + libcalmysql_la-ha_calpont_udf.lo \ libcalmysql_la-ha_calpont_execplan.lo \ libcalmysql_la-ha_scalar_sub.lo libcalmysql_la-ha_in_sub.lo \ libcalmysql_la-ha_exists_sub.lo libcalmysql_la-ha_from_sub.lo \ - libcalmysql_la-ha_select_sub.lo libcalmysql_la-ha_view.lo \ - libcalmysql_la-sm.lo libcalmysql_la-ha_window_function.lo \ - libcalmysql_la-ha_calpont_partition.lo \ - libcalmysql_la-ha_pseudocolumn.lo + libcalmysql_la-ha_select_sub.lo libcalmysql_la_OBJECTS = $(am_libcalmysql_la_OBJECTS) dist_mysqlSCRIPT_INSTALL = $(INSTALL_SCRIPT) SCRIPTS = $(dist_mysql_SCRIPTS) @@ -155,9 +171,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -199,7 +212,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -213,11 +225,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -228,33 +235,16 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) lib_LTLIBRARIES = libcalmysql.la -libcalmysql_la_SOURCES = ha_calpont.cpp ha_calpont_impl.cpp ha_calpont_dml.cpp ha_calpont_ddl.cpp ha_calpont_execplan.cpp ha_scalar_sub.cpp ha_in_sub.cpp ha_exists_sub.cpp ha_from_sub.cpp ha_select_sub.cpp ha_view.cpp sm.cpp ha_window_function.cpp ha_calpont_partition.cpp ha_pseudocolumn.cpp -libcalmysql_la_LDFLAGS = -version-info 1:0:0 $(idb_common_ldflags) $(idb_common_libs) $(idb_write_libs) $(AM_LDFLAGS) -libcalmysql_la_CPPFLAGS = -I/usr/include/libxml2 -I../../../mysql/include -I../../../mysql/sql -I../../../mysql/regex -DMYSQL_DYNAMIC_PLUGIN $(AM_CPPFLAGS) -include_HEADERS = idb_mysql.h -dist_mysql_DATA = syscatalog_mysql.sql dumpcat_mysql.sql calsetuserpriority.sql calremoveuserpriority.sql calshowprocesslist.sql my.cnf +libcalmysql_la_SOURCES = ha_calpont.cpp ha_calpont_impl.cpp ha_calpont_dml.cpp ha_calpont_ddl.cpp ha_calpont_udf.cpp ha_calpont_execplan.cpp ha_scalar_sub.cpp ha_in_sub.cpp ha_exists_sub.cpp ha_from_sub.cpp ha_select_sub.cpp +libcalmysql_la_LDFLAGS = -version-info 1:0:0 $(idb_common_ldflags) $(idb_common_libs) $(idb_write_libs) -lsm $(AM_LDFLAGS) +libcalmysql_la_CPPFLAGS = -I/usr/include/libxml2 -I../../mysql/include -I../../mysql/sql -I../../mysql/regex -DMYSQL_DYNAMIC_PLUGIN $(AM_CPPFLAGS) +include_HEADERS = +dist_mysql_DATA = syscatalog_mysql.sql dumpcat_mysql.sql calsetuserpriority.sql calremoveuserpriority.sql calshowprocesslist.sql dist_mysql_SCRIPTS = install_calpont_mysql.sh mysql-Calpont dumpcat.pl all: all-am @@ -349,16 +339,12 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_calpont_dml.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_calpont_execplan.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_calpont_impl.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_calpont_partition.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_calpont_udf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_exists_sub.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_from_sub.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_in_sub.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_pseudocolumn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_scalar_sub.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_select_sub.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_view.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-ha_window_function.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libcalmysql_la-sm.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ @@ -402,6 +388,13 @@ libcalmysql_la-ha_calpont_ddl.lo: ha_calpont_ddl.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_calpont_ddl.lo `test -f 'ha_calpont_ddl.cpp' || echo '$(srcdir)/'`ha_calpont_ddl.cpp +libcalmysql_la-ha_calpont_udf.lo: ha_calpont_udf.cpp +@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-ha_calpont_udf.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-ha_calpont_udf.Tpo" -c -o libcalmysql_la-ha_calpont_udf.lo `test -f 'ha_calpont_udf.cpp' || echo '$(srcdir)/'`ha_calpont_udf.cpp; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-ha_calpont_udf.Tpo" "$(DEPDIR)/libcalmysql_la-ha_calpont_udf.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-ha_calpont_udf.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='ha_calpont_udf.cpp' object='libcalmysql_la-ha_calpont_udf.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_calpont_udf.lo `test -f 'ha_calpont_udf.cpp' || echo '$(srcdir)/'`ha_calpont_udf.cpp + libcalmysql_la-ha_calpont_execplan.lo: ha_calpont_execplan.cpp @am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-ha_calpont_execplan.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-ha_calpont_execplan.Tpo" -c -o libcalmysql_la-ha_calpont_execplan.lo `test -f 'ha_calpont_execplan.cpp' || echo '$(srcdir)/'`ha_calpont_execplan.cpp; \ @am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-ha_calpont_execplan.Tpo" "$(DEPDIR)/libcalmysql_la-ha_calpont_execplan.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-ha_calpont_execplan.Tpo"; exit 1; fi @@ -444,41 +437,6 @@ libcalmysql_la-ha_select_sub.lo: ha_select_sub.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_select_sub.lo `test -f 'ha_select_sub.cpp' || echo '$(srcdir)/'`ha_select_sub.cpp -libcalmysql_la-ha_view.lo: ha_view.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-ha_view.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-ha_view.Tpo" -c -o libcalmysql_la-ha_view.lo `test -f 'ha_view.cpp' || echo '$(srcdir)/'`ha_view.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-ha_view.Tpo" "$(DEPDIR)/libcalmysql_la-ha_view.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-ha_view.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='ha_view.cpp' object='libcalmysql_la-ha_view.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_view.lo `test -f 'ha_view.cpp' || echo '$(srcdir)/'`ha_view.cpp - -libcalmysql_la-sm.lo: sm.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-sm.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-sm.Tpo" -c -o libcalmysql_la-sm.lo `test -f 'sm.cpp' || echo '$(srcdir)/'`sm.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-sm.Tpo" "$(DEPDIR)/libcalmysql_la-sm.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-sm.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='sm.cpp' object='libcalmysql_la-sm.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-sm.lo `test -f 'sm.cpp' || echo '$(srcdir)/'`sm.cpp - -libcalmysql_la-ha_window_function.lo: ha_window_function.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-ha_window_function.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-ha_window_function.Tpo" -c -o libcalmysql_la-ha_window_function.lo `test -f 'ha_window_function.cpp' || echo '$(srcdir)/'`ha_window_function.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-ha_window_function.Tpo" "$(DEPDIR)/libcalmysql_la-ha_window_function.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-ha_window_function.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='ha_window_function.cpp' object='libcalmysql_la-ha_window_function.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_window_function.lo `test -f 'ha_window_function.cpp' || echo '$(srcdir)/'`ha_window_function.cpp - -libcalmysql_la-ha_calpont_partition.lo: ha_calpont_partition.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-ha_calpont_partition.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-ha_calpont_partition.Tpo" -c -o libcalmysql_la-ha_calpont_partition.lo `test -f 'ha_calpont_partition.cpp' || echo '$(srcdir)/'`ha_calpont_partition.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-ha_calpont_partition.Tpo" "$(DEPDIR)/libcalmysql_la-ha_calpont_partition.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-ha_calpont_partition.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='ha_calpont_partition.cpp' object='libcalmysql_la-ha_calpont_partition.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_calpont_partition.lo `test -f 'ha_calpont_partition.cpp' || echo '$(srcdir)/'`ha_calpont_partition.cpp - -libcalmysql_la-ha_pseudocolumn.lo: ha_pseudocolumn.cpp -@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libcalmysql_la-ha_pseudocolumn.lo -MD -MP -MF "$(DEPDIR)/libcalmysql_la-ha_pseudocolumn.Tpo" -c -o libcalmysql_la-ha_pseudocolumn.lo `test -f 'ha_pseudocolumn.cpp' || echo '$(srcdir)/'`ha_pseudocolumn.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libcalmysql_la-ha_pseudocolumn.Tpo" "$(DEPDIR)/libcalmysql_la-ha_pseudocolumn.Plo"; else rm -f "$(DEPDIR)/libcalmysql_la-ha_pseudocolumn.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='ha_pseudocolumn.cpp' object='libcalmysql_la-ha_pseudocolumn.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcalmysql_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libcalmysql_la-ha_pseudocolumn.lo `test -f 'ha_pseudocolumn.cpp' || echo '$(srcdir)/'`ha_pseudocolumn.cpp - mostlyclean-libtool: -rm -f *.lo diff --git a/dbcon/mysql/calsetuserpriority.sql b/dbcon/mysql/calsetuserpriority.sql index 4aa319b8..4077dbeb 100644 --- a/dbcon/mysql/calsetuserpriority.sql +++ b/dbcon/mysql/calsetuserpriority.sql @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: calsetuserpriority.sql 9440 2013-04-24 21:07:42Z chao $ + * $Id: calsetuserpriority.sql 9442 2013-04-24 21:09:27Z chao $ */ DELIMITER $$ diff --git a/dbcon/mysql/calshowprocesslist.sql b/dbcon/mysql/calshowprocesslist.sql index 01e8ac66..42b0767b 100644 --- a/dbcon/mysql/calshowprocesslist.sql +++ b/dbcon/mysql/calshowprocesslist.sql @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: calshowprocesslist.sql 9736 2013-08-02 18:49:52Z zzhu $ + * $Id: calshowprocesslist.sql 9734 2013-08-02 16:46:23Z zzhu $ */ DELIMITER $$ diff --git a/dbcon/mysql/configure.in b/dbcon/mysql/configure.in new file mode 100644 index 00000000..079f3db0 --- /dev/null +++ b/dbcon/mysql/configure.in @@ -0,0 +1,2892 @@ +# +# $Id: configure.in 5893 2009-10-06 15:53:25Z rdempsey $ +# +dnl -*- ksh -*- +dnl Process this file with autoconf to produce a configure script. + +AC_PREREQ(2.52)dnl Minimum Autoconf version required. + +AC_INIT(sql/mysqld.cc) +AC_CANONICAL_SYSTEM +# The Docs Makefile.am parses this line! +# remember to also update version.c in ndb +# +# When changing major version number please also check switch statement +# in mysqlbinlog::check_master_version(). +AM_INIT_AUTOMAKE(mysql, 5.1.39) +AM_CONFIG_HEADER([include/config.h:config.h.in]) + +PROTOCOL_VERSION=10 +DOT_FRM_VERSION=6 +# See the libtool docs for information on how to do shared lib versions. +SHARED_LIB_MAJOR_VERSION=16 +SHARED_LIB_VERSION=$SHARED_LIB_MAJOR_VERSION:0:0 +NDB_SHARED_LIB_MAJOR_VERSION=3 +NDB_SHARED_LIB_VERSION=$NDB_SHARED_LIB_MAJOR_VERSION:0:0 + +# Set all version vars based on $VERSION. How do we do this more elegant ? +# Remember that regexps needs to quote [ and ] since this is run through m4 +# We take some made up examples +# +# VERSION 5.1.40sp1-alpha 5.0.34a +# MYSQL_NO_DASH_VERSION 5.1.40sp1 5.0.34a +# MYSQL_NUMERIC_VERSION 5.1.40 5.0.34 +# MYSQL_BASE_VERSION 5.1 5.0 +# MYSQL_VERSION_ID 50140 50034 +# +MYSQL_NO_DASH_VERSION=`echo $VERSION | sed -e "s|-.*$||"` +MYSQL_NUMERIC_VERSION=`echo $MYSQL_NO_DASH_VERSION | sed -e "s|[[a-z]][[a-z0-9]]*$||"` +MYSQL_BASE_VERSION=`echo $MYSQL_NUMERIC_VERSION | sed -e "s|\.[[^.]]*$||"` +MYSQL_VERSION_ID=`echo $MYSQL_NUMERIC_VERSION | \ + awk -F. '{printf "%d%0.2d%0.2d", $1, $2, $3}'` +MYSQL_COPYRIGHT_YEAR=`date '+%Y'` + +# Add previous major version for debian package upgrade path +MYSQL_PREVIOUS_BASE_VERSION=5.0 + +# The port should be constant for a LONG time +MYSQL_TCP_PORT_DEFAULT=3306 +MYSQL_UNIX_ADDR_DEFAULT="/tmp/mysql.sock" + +dnl Include m4 +sinclude(config/ac-macros/alloca.m4) +sinclude(config/ac-macros/check_cpu.m4) +sinclude(config/ac-macros/character_sets.m4) +sinclude(config/ac-macros/compiler_flag.m4) +sinclude(config/ac-macros/plugins.m4) +sinclude(config/ac-macros/ha_ndbcluster.m4) +sinclude(config/ac-macros/large_file.m4) +sinclude(config/ac-macros/misc.m4) +sinclude(config/ac-macros/readline.m4) +sinclude(config/ac-macros/ssl.m4) +sinclude(config/ac-macros/zlib.m4) + +# Remember to add a directory sql/share/LANGUAGE +AVAILABLE_LANGUAGES="\ +czech danish dutch english estonian french german greek hungarian \ +italian japanese korean norwegian norwegian-ny polish portuguese \ +romanian russian serbian slovak spanish swedish ukrainian" + +##### +##### + +AC_SUBST(MYSQL_NO_DASH_VERSION) +AC_SUBST(MYSQL_BASE_VERSION) +AC_SUBST(MYSQL_VERSION_ID) +AC_SUBST(MYSQL_PREVIOUS_BASE_VERSION) +AC_SUBST(MYSQL_COPYRIGHT_YEAR) +AC_SUBST(PROTOCOL_VERSION) +AC_DEFINE_UNQUOTED([PROTOCOL_VERSION], [$PROTOCOL_VERSION], + [mysql client protocol version]) +AC_SUBST(DOT_FRM_VERSION) +AC_DEFINE_UNQUOTED([DOT_FRM_VERSION], [$DOT_FRM_VERSION], + [Version of .frm files]) +AC_SUBST(SHARED_LIB_MAJOR_VERSION) +AC_SUBST(SHARED_LIB_VERSION) +AC_SUBST(AVAILABLE_LANGUAGES) + + +# Canonicalize the configuration name. + +# Check whether --with-system-type or --without-system-type was given. +AC_ARG_WITH(system-type, + [ --with-system-type Set the system type, like "sun-solaris10"], + [SYSTEM_TYPE="$withval"], + [SYSTEM_TYPE="$host_vendor-$host_os"]) +AC_ARG_WITH(machine-type, + [ --with-machine-type Set the machine type, like "powerpc"], + [MACHINE_TYPE="$withval"], + [MACHINE_TYPE="$host_cpu"]) +AC_SUBST(SYSTEM_TYPE) +AC_DEFINE_UNQUOTED([SYSTEM_TYPE], ["$SYSTEM_TYPE"], + [Name of system, eg sun-solaris]) +AC_SUBST(MACHINE_TYPE) +AC_DEFINE_UNQUOTED([MACHINE_TYPE], ["$MACHINE_TYPE"], + [Machine type name, eg sparc]) + +# Detect intel x86 like processor +BASE_MACHINE_TYPE=$MACHINE_TYPE +case $MACHINE_TYPE in + i?86) BASE_MACHINE_TYPE=i386 ;; +esac + +# Save some variables and the command line options for mysqlbug +SAVE_CC="$CC" +SAVE_CXX="$CXX" +SAVE_ASFLAGS="$ASFLAGS" +SAVE_CFLAGS="$CFLAGS" +SAVE_CXXFLAGS="$CXXFLAGS" +SAVE_LDFLAGS="$LDFLAGS" +SAVE_CXXLDFLAGS="$CXXLDFLAGS" +CONF_COMMAND="$0 $ac_configure_args" +AC_SUBST(CONF_COMMAND) +AC_SUBST(SAVE_CC) +AC_SUBST(SAVE_CXX) +AC_SUBST(SAVE_ASFLAGS) +AC_SUBST(SAVE_CFLAGS) +AC_SUBST(SAVE_CXXFLAGS) +AC_SUBST(SAVE_LDFLAGS) +AC_SUBST(SAVE_CXXLDFLAGS) +AC_SUBST(CXXLDFLAGS) + +#AC_ARG_PROGRAM # Automaticly invoked by AM_INIT_AUTOMAKE + +AM_SANITY_CHECK +# This is needed is SUBDIRS is set +AC_PROG_MAKE_SET + +############################################################################## +# The below section needs to be done before AC_PROG_CC +############################################################################## + +# Hack for OS X/Darwin and Metrowerks CodeWarrior +AC_ARG_WITH(darwin-mwcc, +[ --with-darwin-mwcc Use Metrowerks CodeWarrior wrappers on OS X/Darwin],[ + if [ "with_darwin_mwcc" = yes ] ; then + builddir=`pwd` + ccwrapper="$builddir/support-files/MacOSX/mwcc-wrapper" + arwrapper="$builddir/support-files/MacOSX/mwar-wrapper" + CC="$ccwrapper" + CXX="$ccwrapper" + LD="$ccwrapper" + AR="$arwrapper" + RANLIB=: + export CC CXX LD AR RANLIB + AC_SUBST(AR) + AC_SUBST(RANLIB) + fi +]) + +AM_CONDITIONAL(DARWIN_MWCC, test x$with_darwin_mwcc = xyes) + +if test "x${CFLAGS-}" = x ; then + cflags_is_set=no +else + cflags_is_set=yes +fi + +if test "x${CPPFLAGS-}" = x ; then + cppflags_is_set=no +else + cppflags_is_set=yes +fi + +if test "x${LDFLAGS-}" = x ; then + ldflags_is_set=no +else + ldflags_is_set=yes +fi + +################ End of section to be done before AC_PROG_CC ################# + +# The following hack should ensure that configure doesn't add optimizing +# or debugging flags to CFLAGS or CXXFLAGS +# C_EXTRA_FLAGS are flags that are automaticly added to both +# CFLAGS and CXXFLAGS +CFLAGS="$CFLAGS $C_EXTRA_FLAGS " +CXXFLAGS="$CXXFLAGS $C_EXTRA_FLAGS " + +dnl Checks for programs. +AC_PROG_AWK +AC_PROG_CC +AC_PROG_CXX +AC_PROG_CPP + +# Print version of CC and CXX compiler (if they support --version) +case $SYSTEM_TYPE in + *netware*) +CC_VERSION=`$CC -version | grep -i version` + ;; + *) +CC_VERSION=`$CC --version | sed 1q` + ;; +esac +if test $? -eq "0" +then + AC_MSG_CHECKING("C Compiler version") + AC_MSG_RESULT("$CC $CC_VERSION") +else +CC_VERSION="" +fi +AC_SUBST(CC_VERSION) +MYSQL_CHECK_CXX_VERSION + +# Fix for sgi gcc / sgiCC which tries to emulate gcc +if test "$CC" = "sgicc" +then + ac_cv_prog_gcc="no" +fi +if test "$CXX" = "sgi++" +then + GXX="no" +fi + +if test "$ac_cv_prog_gcc" = "yes" +then + AS="$CC -c" + AC_SUBST(AS) +else + AC_PATH_PROG(AS, as, as) +fi + +# Still need ranlib for readline; local static use only so no libtool. +AC_PROG_RANLIB +# We use libtool +#AC_LIBTOOL_WIN32_DLL +AC_PROG_LIBTOOL + +# Ensure that we have --preserve-dup-deps defines, otherwise we get link +# problems of 'mysql' with CXX=g++ +LIBTOOL="$LIBTOOL --preserve-dup-deps" +AC_SUBST(LIBTOOL)dnl + +AC_SUBST(NM)dnl + +# NM= "$NM -X64" +#archive_expsym_cmds= `echo "$archive_expsym_cmds" | sed -e '/"$(CC)"//'` +#archive_expsym_cmds= "$CC -q64 $archive_expsym_cmds" +# CXXFLAGS=`echo "$CXXFLAGS -Werror" | sed -e 's/-fbranch-probabilities//; s/-Wall//; s/-ansi//; s/-pedantic//; s/-Wcheck//'` + +#AC_LIBTOOL_DLOPEN AC_LIBTOOL_WIN32_DLL AC_DISABLE_FAST_INSTALL AC_DISABLE_SHARED AC_DISABLE_STATIC + +# AC_PROG_INSTALL +AC_PROG_INSTALL +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL_PROGRAM}' + +# Not critical since the generated file is distributed +AC_CHECK_PROGS(YACC, ['bison -y -p MYSQL']) +AC_CHECK_PROG(PDFMANUAL, pdftex, manual.pdf) +AC_CHECK_PROG(DVIS, tex, manual.dvi) + +#check the return type of sprintf +AC_MSG_CHECKING("return type of sprintf") +AC_TRY_RUN([ + int main() + { + char* s = "hello"; + char buf[6]; + if((int)sprintf(buf, s) == strlen(s)) + return 0; + + return -1; + } + ], + [AC_DEFINE(SPRINTF_RETURNS_INT, [1], [POSIX sprintf]) + AC_MSG_RESULT("int")], + [AC_TRY_RUN([ + int main() + { + char* s = "hello"; + char buf[6]; + if((char*)sprintf(buf,s) == buf + strlen(s)) + return 0; + return -1; + } ], + [AC_DEFINE(SPRINTF_RETURNS_PTR, [1], [Broken sprintf]) + AC_MSG_RESULT("ptr")], + [AC_DEFINE(SPRINTF_RETURNS_GARBAGE, [1], [Broken sprintf]) + AC_MSG_RESULT("garbage")] + )], + # Cross compile, assume POSIX + [AC_DEFINE(SPRINTF_RETURNS_INT, [1], [POSIX sprintf]) + AC_MSG_RESULT("int (we assume)")] +) + +AC_PATH_PROG(uname_prog, uname, no) + +# We should go through this and put all the explictly system dependent +# stuff in one place +AC_MSG_CHECKING(operating system) +AC_CACHE_VAL(mysql_cv_sys_os, +[ +if test "$uname_prog" != "no"; then + mysql_cv_sys_os="`uname`" +else + mysql_cv_sys_os="Not Solaris" +fi +]) +AC_MSG_RESULT($mysql_cv_sys_os) + +# This should be rewritten to use $target_os +case "$target_os" in + sco3.2v5*) + CFLAGS="$CFLAGS -DSCO" + CXXFLAGS="$CXXFLAGS -DSCO" + LD='$(CC) $(CFLAGS)' + case "$CFLAGS" in + *-belf*) + AC_SYS_COMPILER_FLAG(-belf,sco_belf_option,CFLAGS,[],[ + case "$LDFLAGS" in + *-belf*) ;; + *) AC_MSG_WARN([Adding -belf option to ldflags.]) + LDFLAGS="$LDFLAGS -belf" + ;; + esac + ]) + ;; + *) + AC_SYS_COMPILER_FLAG(-belf,sco_belf_option,CFLAGS,[],[ + case "$LDFLAGS" in + *-belf*) ;; + *) + AC_MSG_WARN([Adding -belf option to ldflags.]) + LDFLAGS="$LDFLAGS -belf" + ;; + esac + ]) + ;; + esac + ;; + sysv5UnixWare* | sysv5OpenUNIX8*) + if test "$GCC" != "yes"; then + # Use the built-in alloca() + CFLAGS="$CFLAGS -Kalloca" + fi + CXXFLAGS="$CXXFLAGS -DNO_CPLUSPLUS_ALLOCA" + ;; + sysv5SCO_SV6.0.0*) + if test "$GCC" != "yes"; then + # Use the built-in alloca() + CFLAGS="$CFLAGS -Kalloca" + CXXFLAGS="$CFLAGS -Kalloca" + # Use no_implicit for templates + CXXFLAGS="$CXXFLAGS -Tno_implicit" + AC_DEFINE([HAVE_EXPLICIT_TEMPLATE_INSTANTIATION], + [1], [Defined by configure. Use explicit template instantiation.]) + fi + ;; +esac +AC_SUBST(CC) +AC_SUBST(CFLAGS) +AC_SUBST(CXX) +AC_SUBST(CXXFLAGS) +AC_SUBST(ASFLAGS) +AC_SUBST(LD) +AC_SUBST(INSTALL_SCRIPT) + +export CC CXX CFLAGS LD LDFLAGS AR ARFLAGS + +if test "$GCC" = "yes" +then + # mysqld requires -fno-implicit-templates. + # Disable exceptions as they seams to create problems with gcc and threads. + # mysqld doesn't use run-time-type-checking, so we disable it. + # We should use -Wno-invalid-offsetof flag to disable some warnings from gcc + # regarding offset() usage in C++ which are done in a safe manner in the + # server + CXXFLAGS="$CXXFLAGS -fno-implicit-templates -fno-exceptions -fno-rtti" + AC_DEFINE([HAVE_EXPLICIT_TEMPLATE_INSTANTIATION], + [1], [Defined by configure. Use explicit template instantiation.]) +fi + +MYSQL_PROG_AR + +# libmysqlclient versioning when linked with GNU ld. +if $LD --version 2>/dev/null| grep GNU >/dev/null 2>&1; then + LD_VERSION_SCRIPT="-Wl,--version-script=\$(top_builddir)/libmysql/libmysql.ver" + AC_CONFIG_FILES(libmysql/libmysql.ver) +fi +AC_SUBST(LD_VERSION_SCRIPT) + + +# Avoid bug in fcntl on some versions of linux +AC_MSG_CHECKING([if we should use 'skip-external-locking' as default for $target_os]) +# Any variation of Linux +if expr "$target_os" : "[[Ll]]inux.*" > /dev/null +then + MYSQLD_DEFAULT_SWITCHES="--skip-external-locking" + TARGET_LINUX="true" + AC_MSG_RESULT([yes]) + AC_DEFINE([TARGET_OS_LINUX], [1], [Whether we build for Linux]) +else + MYSQLD_DEFAULT_SWITCHES="" + TARGET_LINUX="false" + AC_MSG_RESULT([no]) +fi +AC_SUBST(MYSQLD_DEFAULT_SWITCHES) +AC_SUBST(TARGET_LINUX) + +dnl Find paths to some shell programs +AC_PATH_PROG(LN, ln, ln) +# This must be able to take a -f flag like normal unix ln. +AC_PATH_PROG(LN_CP_F, ln, ln) +case $SYSTEM_TYPE in + *netware*) ;; + *) + # If ln -f does not exists use -s (AFS systems) + if test -n "$LN_CP_F"; then + LN_CP_F="$LN_CP_F -s" + fi + ;; +esac + +AC_PATH_PROG(MV, mv, mv) +AC_PATH_PROG(RM, rm, rm) +AC_PATH_PROG(CP, cp, cp) +AC_PATH_PROG(SED, sed, sed) +AC_PATH_PROG(CMP, cmp, cmp) +AC_PATH_PROG(CHMOD, chmod, chmod) +AC_PATH_PROG(HOSTNAME, hostname, hostname) +AC_PATH_PROG(DIFF, diff, diff) +# Check for a GNU tar named 'gtar', or 'gnutar' (MacOS X) and +# fall back to 'tar' otherwise and hope that it's a GNU tar as well +AC_CHECK_PROGS(TAR, gnutar gtar tar) + +dnl We use a path for perl so the script startup works +dnl We make sure to use perl, not perl5, in hopes that the RPMs will +dnl not depend on the perl5 binary being installed (probably a bug in RPM) +AC_PATH_PROG(PERL, perl, no) +if test "$PERL" != "no" && $PERL -e 'require 5' > /dev/null 2>&1 +then + PERL5=$PERL +else + AC_PATH_PROG(PERL5, perl5, no) + if test "$PERL5" != no + then + PERL=$PERL5 + ac_cv_path_PERL=$ac_cv_path_PERL5 + fi +fi + +AC_SUBST(HOSTNAME) +AC_SUBST(PERL) +AC_SUBST(PERL5) + +# Enable the abi_check rule only if gcc is available + +if test "$GCC" != "yes" || expr "$CC" : ".*icc.*" +then + ABI_CHECK="" +else + ABI_CHECK="abi_check" +fi + +AC_SUBST(ABI_CHECK) + +# Look for PS usage. We use double dollar-signs in FIND_PROC because this +# value is written to a makefile, which interprets away one level of +# dollar-signs. So, interpretation stages are m4 and then shell in autoconf, +# then Make, then shell. The autoconf substitution uses single quotes, so +# no unprotected single quotes should appear in the expression. +AC_PATH_PROG(PS, ps, ps) +AC_MSG_CHECKING("how to check if pid exists") +PS=$ac_cv_path_PS +# Linux style +if $PS wwwp $$ 2> /dev/null | grep -- "$0" > /dev/null +then + FIND_PROC="$PS wwwp \$\$PID | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" > /dev/null" +# Solaris +elif $PS -fp $$ 2> /dev/null | grep -- $0 > /dev/null +then + FIND_PROC="$PS -p \$\$PID | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" > /dev/null" +# BSD style +elif $PS -uaxww 2> /dev/null | grep -- $0 > /dev/null +then + FIND_PROC="$PS -uaxww | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" | grep \" \$\$PID \" > /dev/null" +# SysV style +elif $PS -ef 2> /dev/null | grep -- $0 > /dev/null +then + FIND_PROC="$PS -ef | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" | grep \" \$\$PID \" > /dev/null" +# Do anybody use this? +elif $PS $$ 2> /dev/null | grep -- $0 > /dev/null +then + FIND_PROC="$PS \$\$PID | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" > /dev/null" +else + case $SYSTEM_TYPE in + *freebsd*|*dragonfly*) + FIND_PROC="$PS p \$\$PID | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" > /dev/null" + ;; + *darwin*) + FIND_PROC="$PS -uaxww | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" | grep \" \$\$PID \" > /dev/null" + ;; + *cygwin*) + FIND_PROC="$PS -e | grep -v \" grep\" | grep -v mysqld_safe | grep -- \"\$\$MYSQLD\" | grep \" \$\$PID \" > /dev/null" + ;; + *netware*) + FIND_PROC= + ;; + *) + AC_MSG_ERROR([Could not find the right ps and/or grep switches. Which OS is this? See the Installation chapter in the Reference Manual.]) + esac +fi +AC_SUBST(FIND_PROC) +AC_MSG_RESULT("$FIND_PROC") + +# Check if a pid is valid +AC_PATH_PROG(KILL, kill, kill) +AC_MSG_CHECKING("for kill switches") +if $ac_cv_path_KILL -0 $$ +then + CHECK_PID="$ac_cv_path_KILL -0 \$\$PID > /dev/null 2> /dev/null" +elif kill -s 0 $$ +then + CHECK_PID="$ac_cv_path_KILL -s 0 \$\$PID > /dev/null 2> /dev/null" +else + AC_MSG_WARN([kill -0 to check for pid seems to fail]) + CHECK_PID="$ac_cv_path_KILL -s SIGCONT \$\$PID > /dev/null 2> /dev/null" +fi +AC_SUBST(CHECK_PID) +AC_MSG_RESULT("$CHECK_PID") + +# We need an ANSI C compiler +AM_PROG_CC_STDC + +# We need an assembler, too +AM_PROG_AS +CCASFLAGS="$CCASFLAGS $ASFLAGS" + +# Check if we need noexec stack for assembler +AC_CHECK_NOEXECSTACK + +if test "$am_cv_prog_cc_stdc" = "no" +then + AC_MSG_ERROR([MySQL requires an ANSI C compiler (and a C++ compiler). Try gcc. See the Installation chapter in the Reference Manual.]) +fi + +NOINST_LDFLAGS="-static" + +static_nss="" +STATIC_NSS_FLAGS="" +OTHER_LIBC_LIB="" +AC_ARG_WITH(other-libc, + [ --with-other-libc=DIR Link against libc and other standard libraries + installed in the specified non-standard location + overriding default. Originally added to be able to + link against glibc 2.2 without making the user + upgrade the standard libc installation.], + [ + other_libc_include="$withval/include" + other_libc_lib="$withval/lib" + with_other_libc="yes" + enable_shared="no" + all_is_static="yes" + CFLAGS="$CFLAGS -I$other_libc_include" + # There seems to be a feature in gcc that treats system and libc headers + # silently when they violatate ANSI C++ standard, but it is strict otherwise + # since gcc cannot now recognize that our headers are libc, we work around + # by telling it to be permissive. Note that this option only works with + # new versions of gcc (2.95.x and above) + CXXFLAGS="$CXXFLAGS -fpermissive -I$other_libc_include" + if test -f "$other_libc_lib/libnss_files.a" + then + # libc has been compiled with --enable-static-nss + # we need special flags, but we will have to add those later + STATIC_NSS_FLAGS="-lc -lnss_files -lnss_dns -lresolv" + STATIC_NSS_FLAGS="$STATIC_NSS_FLAGS $STATIC_NSS_FLAGS" + OTHER_LIBC_LIB="-static -L$other_libc_lib" + static_nss=1 + else + # this is a dirty hack. We if we detect static nss glibc in the special + # location, we do not re-direct the linker to get libraries from there + # during check. The reason is that if we did, we would have to find a + # way to append the special static nss flags to LIBS every time we do + # any check - this is definitely feasible, but not worthwhile the risk + # of breaking other things. So for our purposes it would be sufficient + # to assume that whoever is using static NSS knows what he is doing and + # has sensible libraries in the regular location + LDFLAGS="$LDFLAGS -static -L$other_libc_lib " + fi + + # When linking against custom libc installed separately, we want to force + # all binary builds to be static, including the build done by configure + # itself to test for system features. + with_mysqld_ldflags="-all-static" + with_client_ldflags="-all-static" + NOINST_LDFLAGS="-all-static" + ], + [ + other_libc_include= + other_libc_lib= + with_other_libc="no" + ] +) +AC_SUBST(NOINST_LDFLAGS) + +# +# Check if we are using Linux and a glibc compiled with static nss +# (this is true on the MySQL build machines to avoid NSS problems) +# +AC_CHECK_TOOL([NM], [nm]) + +if test "$TARGET_LINUX" = "true" -a "$static_nss" = "" +then + tmp=`$NM ${other_libc_lib:-/usr/lib*}/libc.a | grep _nss_files_getaliasent_r1` + if test -n "$tmp" + then + STATIC_NSS_FLAGS="-lc -lnss_files -lnss_dns -lresolv" + STATIC_NSS_FLAGS="$STATIC_NSS_FLAGS $STATIC_NSS_FLAGS" + static_nss=1 + fi +fi + +AC_MSG_CHECKING(whether features provided by the user community should be included.) +AC_ARG_ENABLE(community-features, + AC_HELP_STRING( + [--disable-community-features], + [Disable additional features provided by the user community.]), + [ ENABLE_COMMUNITY_FEATURES=$enableval ], + [ ENABLE_COMMUNITY_FEATURES=yes ] + ) + +if test "$ENABLE_COMMUNITY_FEATURES" = "yes" +then + AC_DEFINE([COMMUNITY_SERVER], [1], + [Whether features provided by the user community should be included]) + AC_MSG_RESULT([yes]) +else + AC_MSG_RESULT([no]) +fi + +AC_ARG_WITH(server-suffix, + [ --with-server-suffix Append value to the version string.], + [ MYSQL_SERVER_SUFFIX=`echo "$withval" | sed -e 's/^\(...................................\)..*$/\1/'` ], + [ MYSQL_SERVER_SUFFIX= ] + ) +AC_SUBST(MYSQL_SERVER_SUFFIX) + +# Set flags if we want to force to use pthreads +AC_ARG_WITH(pthread, + [ --with-pthread Force use of pthread library.], + [ with_pthread=$withval ], + [ with_pthread=no ] + ) + +# Force use of thread libs LIBS +AC_ARG_WITH(named-thread-libs, + [ --with-named-thread-libs=ARG + Use specified thread libraries instead of + those automatically found by configure.], + [ with_named_thread=$withval ], + [ with_named_thread=no ] + ) + +# Force use of a curses libs +AC_ARG_WITH(named-curses-libs, + [ --with-named-curses-libs=ARG + Use specified curses libraries instead of + those automatically found by configure.], + [ with_named_curses=$withval ], + [ with_named_curses=no ] + ) + +# Make thread safe client +AC_ARG_ENABLE(thread-safe-client, + [ --disable-thread-safe-client + Compile the client without threads.], + [ THREAD_SAFE_CLIENT=$enableval ], + [ THREAD_SAFE_CLIENT=yes ] + ) + +# compile with strings functions in assembler +AC_ARG_ENABLE(assembler, + [ --enable-assembler Use assembler versions of some string + functions if available.], + [ ENABLE_ASSEMBLER=$enableval ], + [ ENABLE_ASSEMBLER=no ] + ) + +AC_MSG_CHECKING(if we should use assembler functions) +# For now we only support assembler on i386 and sparc systems +AM_CONDITIONAL(ASSEMBLER_x86, test "$ENABLE_ASSEMBLER" = "yes" -a "$BASE_MACHINE_TYPE" = "i386" && $AS strings/strings-x86.s -o checkassembler >/dev/null 2>&1 && test -f checkassembler && (rm -f checkassembler; exit 0;)) +AM_CONDITIONAL(ASSEMBLER_sparc32, test "$ENABLE_ASSEMBLER" = "yes" -a "$BASE_MACHINE_TYPE" = "sparc") +AM_CONDITIONAL(ASSEMBLER_sparc64, test "$ENABLE_ASSEMBLER" = "yes" -a "$BASE_MACHINE_TYPE" = "sparcv9") +AM_CONDITIONAL(ASSEMBLER, test "$ASSEMBLER_x86_TRUE" = "" -o "$ASSEMBLER_sparc32_TRUE" = "") + +if test "$ASSEMBLER_TRUE" = "" +then + AC_MSG_RESULT([yes]) +else + AC_MSG_RESULT([no]) +fi + +# Add query profiler +AC_MSG_CHECKING(if SHOW PROFILE should be enabled.) +AC_ARG_ENABLE(profiling, + AS_HELP_STRING([--enable-profiling], [Build a version with query profiling code (req. community-features)]), + [ ENABLED_PROFILING=$enableval ], + [ ENABLED_PROFILING=$ENABLE_COMMUNITY_FEATURES ]) + +if test "$ENABLED_PROFILING" = "yes" +then + if test "$ENABLE_COMMUNITY_FEATURES" = "yes"; + then + AC_DEFINE([ENABLED_PROFILING], [1], + [If SHOW PROFILE should be enabled]) + AC_MSG_RESULT([yes]) + else + ENABLED_PROFILING="no" + AC_MSG_RESULT([no, overridden by community-features disabled]) + fi +else + AC_MSG_RESULT([no]) +fi + +# Use this to set the place used for unix socket used to local communication. +AC_ARG_WITH(unix-socket-path, + [ --with-unix-socket-path=SOCKET + Where to put the unix-domain socket. SOCKET must be + an absolute file name.], + [ MYSQL_UNIX_ADDR=$withval ], + [ MYSQL_UNIX_ADDR=$MYSQL_UNIX_ADDR_DEFAULT ] + ) +AC_SUBST(MYSQL_UNIX_ADDR) + +AC_ARG_WITH(tcp-port, + [ --with-tcp-port=port-number + Which port to use for MySQL services (default 3306)], + [ MYSQL_TCP_PORT=$withval ], + [ MYSQL_TCP_PORT=$MYSQL_TCP_PORT_DEFAULT + # if we actually defaulted (as opposed to the pathological case of + # --with-tcp-port= which might in theory + # happen if whole batch of servers was built from a script), set + # the default to zero to indicate that; we don't lose information + # that way, because 0 obviously indicates that we can get the + # default value from MYSQL_TCP_PORT. this seems really evil, but + # testing for MYSQL_TCP_PORT==MYSQL_TCP_PORT_DEFAULT would make a + # a port of MYSQL_TCP_PORT_DEFAULT magic even if the builder did not + # intend it to mean "use the default, in fact, look up a good default + # from /etc/services if you can", but really, really meant 3306 when + # they passed in 3306. When they pass in a specific value, let them + # have it; don't second guess user and think we know better, this will + # just make people cross. this makes the the logic work like this + # (which is complicated enough): + # + # - if a port was set during build, use that as a default. + # + # - otherwise, try to look up a port in /etc/services; if that fails, + # use MYSQL_TCP_PORT_DEFAULT (at the time of this writing 3306) + # + # - allow the MYSQL_TCP_PORT environment variable to override that. + # + # - allow command-line parameters to override all of the above. + # + # the top-most MYSQL_TCP_PORT_DEFAULT is read from win/configure.js, + # so don't mess with that. + MYSQL_TCP_PORT_DEFAULT=0 ] + ) +AC_SUBST(MYSQL_TCP_PORT) +# We might want to document the assigned port in the manual. +AC_SUBST(MYSQL_TCP_PORT_DEFAULT) + +# Use this to set the place used for unix socket used to local communication. +AC_ARG_WITH(mysqld-user, + [ --with-mysqld-user=username + What user the mysqld daemon shall be run as.], + [ MYSQLD_USER=$withval ], + [ MYSQLD_USER=mysql ] + ) +AC_SUBST(MYSQLD_USER) + +# If we should allow LOAD DATA LOCAL +AC_MSG_CHECKING(If we should should enable LOAD DATA LOCAL by default) +AC_ARG_ENABLE(local-infile, + [ --enable-local-infile Enable LOAD DATA LOCAL INFILE (default: disabled)], + [ ENABLED_LOCAL_INFILE=$enableval ], + [ ENABLED_LOCAL_INFILE=no ] + ) +if test "$ENABLED_LOCAL_INFILE" = "yes" +then + AC_MSG_RESULT([yes]) + AC_DEFINE([ENABLED_LOCAL_INFILE], [1], + [If LOAD DATA LOCAL INFILE should be enabled by default]) +else + AC_MSG_RESULT([no]) +fi + +# If we should allow init-file, skip-grant-table and bootstrap options +AC_MSG_CHECKING(If we should should enable init-file, skip-grant-table options and bootstrap) +AC_ARG_ENABLE(grant-options, + [ --disable-grant-options Disables the use of --init-file, --skip-grant-tables and --bootstrap options], + [ mysql_grant_options_enabled=$enableval ], + [ mysql_grant_options_enabled=yes ] + ) +if test "$mysql_grant_options_enabled" = "yes" +then + AC_MSG_RESULT([yes]) +else + AC_DEFINE([DISABLE_GRANT_OPTIONS], [1], + [Disables the use of --init-file, --skip-grant-tables and --bootstrap options]) + AC_MSG_RESULT([no]) +fi + +MYSQL_SYS_LARGEFILE + +# Types that must be checked AFTER large file support is checked +AC_TYPE_SIZE_T + +#-------------------------------------------------------------------- +# Check for system header files +#-------------------------------------------------------------------- + +AC_HEADER_DIRENT +AC_HEADER_STDC +AC_HEADER_SYS_WAIT +AC_CHECK_HEADERS(fcntl.h fenv.h float.h floatingpoint.h ieeefp.h limits.h \ + memory.h pwd.h select.h \ + stdlib.h stddef.h \ + strings.h string.h synch.h sys/mman.h sys/socket.h netinet/in.h arpa/inet.h \ + sys/timeb.h sys/types.h sys/un.h sys/vadvise.h sys/wait.h term.h \ + unistd.h utime.h sys/utime.h termio.h termios.h sched.h crypt.h alloca.h \ + sys/ioctl.h malloc.h sys/malloc.h sys/ipc.h sys/shm.h linux/config.h \ + sys/prctl.h sys/resource.h sys/param.h port.h ieeefp.h \ + execinfo.h) + +AC_CHECK_HEADERS([xfs/xfs.h]) + +#-------------------------------------------------------------------- +# Check for system libraries. Adds the library to $LIBS +# and defines HAVE_LIBM etc +#-------------------------------------------------------------------- + +AC_CHECK_LIB(m, floor, [], AC_CHECK_LIB(m, __infinity)) + +AC_CHECK_LIB(nsl_r, gethostbyname_r, [], + AC_CHECK_LIB(nsl, gethostbyname_r)) +AC_CHECK_FUNC(gethostbyname_r) + +AC_SEARCH_LIBS(setsockopt, socket) +# This may get things to compile even if bind-8 is installed +AC_SEARCH_LIBS(bind, bind) +# Check if crypt() exists in libc or libcrypt, sets LIBS if needed +AC_SEARCH_LIBS(crypt, crypt, AC_DEFINE(HAVE_CRYPT, 1, [crypt])) +# See if we need a library for address lookup. +AC_SEARCH_LIBS(inet_aton, [socket nsl resolv]) + +# For the sched_yield() function on Solaris +AC_SEARCH_LIBS(sched_yield, posix4, + AC_DEFINE(HAVE_SCHED_YIELD, 1, [sched_yield])) + +MYSQL_CHECK_ZLIB_WITH_COMPRESS + +# For large pages support +if test "$TARGET_LINUX" = "true" +then + # For SHM_HUGETLB on Linux + AC_CHECK_DECLS(SHM_HUGETLB, + AC_DEFINE([HAVE_LARGE_PAGES], [1], + [Define if you have large pages support]) + AC_DEFINE([HUGETLB_USE_PROC_MEMINFO], [1], + [Define if /proc/meminfo shows the huge page size (Linux only)]) + , , + [ +#include + ] + ) +fi + +#-------------------------------------------------------------------- +# Check for TCP wrapper support +#-------------------------------------------------------------------- + +AC_ARG_WITH(libwrap, +[ --with-libwrap[=DIR] Compile in libwrap (tcp_wrappers) support],[ + case "$with_libwrap" in + no) : ;; + yes|*) + _cppflags=${CPPFLAGS} + _ldflags=${LDFLAGS} + + if test "$with_libwrap" != "yes"; then + CPPFLAGS="${CPPFLAGS} -I$with_libwrap/include" + LDFLAGS="${LDFLAGS} -L$with_libwrap/lib" + fi + + _libs=${LIBS} + AC_CHECK_HEADER(tcpd.h, + LIBS="-lwrap $LIBS" + AC_MSG_CHECKING(for TCP wrappers library -lwrap) + AC_TRY_LINK([#include +int allow_severity = 0; +int deny_severity = 0; + +struct request_info *req; +],[hosts_access (req)], + AC_MSG_RESULT(yes) + AC_DEFINE([LIBWRAP], [1], [Define if you have -lwrap]) + AC_DEFINE([HAVE_LIBWRAP], [1], [Define if have -lwrap]) + if test "$with_libwrap" != "yes"; then + WRAPLIBS="-L${with_libwrap}/lib" + fi + WRAPLIBS="${WRAPLIBS} -lwrap", + AC_MSG_RESULT(no) + CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}), + CPPFLAGS=${_cppflags} LDFLAGS=${_ldflags}) + LDFLAGS=${_ldflags} LIBS=${_libs} + ;; + esac +]) +AC_SUBST(WRAPLIBS) + +if test "$TARGET_LINUX" = "true"; then + AC_ARG_WITH(pstack, + [ --with-pstack Use the pstack backtrace library], + [ USE_PSTACK=$withval ], + [ USE_PSTACK=no ]) + pstack_libs= + pstack_dir= + if test "$USE_PSTACK" = yes -a "$TARGET_LINUX" = "true" -a "$BASE_MACHINE_TYPE" = "i386" + then + have_libiberty= have_libbfd= + my_save_LIBS="$LIBS" +dnl I have no idea if this is a good test - can not find docs for libiberty + AC_CHECK_LIB([iberty], [fdmatch], + [have_libiberty=yes + AC_CHECK_LIB([bfd], [bfd_openr], [have_libbfd=yes], , [-liberty])]) + LIBS="$my_save_LIBS" + + if test x"$have_libiberty" = xyes -a x"$have_libbfd" = xyes + then + pstack_dir="pstack" + pstack_libs="../pstack/libpstack.a -lbfd -liberty" + # We must link staticly when using pstack + with_mysqld_ldflags="-all-static" + AC_SUBST([pstack_dir]) + AC_SUBST([pstack_libs]) + AC_DEFINE([USE_PSTACK], [1], [the pstack backtrace library]) +dnl This check isn't needed, but might be nice to give some feedback.... +dnl AC_CHECK_HEADER(libiberty.h, +dnl have_libiberty_h=yes, +dnl have_libiberty_h=no) + else + USE_PSTACK="no" + fi + else + USE_PSTACK="no" + fi +fi +AC_MSG_CHECKING([if we should use pstack]) +AC_MSG_RESULT([$USE_PSTACK]) + +# Check for gtty if termio.h doesn't exists +if test "$ac_cv_header_termio_h" = "no" -a "$ac_cv_header_termios_h" = "no" +then + AC_SEARCH_LIBS(gtty, compat) +fi + +# We make a special variable for non-threaded version of LIBS to avoid +# including thread libs into non-threaded version of MySQL client library. +# Later in this script LIBS will be augmented with a threads library. +NON_THREADED_LIBS="$LIBS" + +AC_CHECK_TYPES([int8, uint8, int16, uint16, int32, uint32, int64, uint64, + uchar, uint, ulong],[],[], [ +#include +]) +AC_CHECK_TYPES([in_addr_t], [], [], [ +#include +#include +#include +#include +]) +AC_CHECK_TYPES([fp_except], [], [], [ +#include +#include +]) + +# +# Some system specific hacks +# + +MAX_C_OPTIMIZE="-O3" +MAX_CXX_OPTIMIZE="-O3" + +case $SYSTEM_TYPE in + *solaris2.7*) + # Solaris 2.7 has a broken /usr/include/widec.h + # Make a fixed copy in ./include + AC_MSG_WARN([Fixing broken include files for $SYSTEM_TYPE]) + echo " - Creating local copy of widec.h" + if test ! -d include + then + mkdir ./include + fi + builddir=`pwd` + sed -e "s|^#if[ ]*!defined(lint) && !defined(__lint)|#if !defined\(lint\) \&\& !defined\(__lint\) \&\& !defined\(getwc\)|" < /usr/include/widec.h > include/widec.h + CFLAGS="$CFLAGS -DHAVE_CURSES_H -I$builddir/include -DHAVE_RWLOCK_T" + CXXFLAGS="$CXXFLAGS -DHAVE_CURSES_H -I$builddir/include -DHAVE_RWLOCK_T" + ;; + *solaris2.8*) + # Solaris 2.8 has a broken /usr/include/widec.h + # Make a fixed copy in ./include + AC_MSG_WARN([Fixing broken include files for $SYSTEM_TYPE]) + echo " - Creating local copy of widec.h" + if test ! -d include + then + mkdir ./include + fi + builddir=`pwd` + sed -e "s|^#if[ ]*!defined(__lint)|#if !defined\(__lint\) \&\& !defined\(getwc\)|" < /usr/include/widec.h > include/widec.h + CFLAGS="$CFLAGS -DHAVE_CURSES_H -I$builddir/include -DHAVE_RWLOCK_T" + CXXFLAGS="$CXXFLAGS -DHAVE_CURSES_H -I$builddir/include -DHAVE_RWLOCK_T" + ;; + *solaris2.5.1*) + AC_MSG_WARN([Enabling getpass() workaround for Solaris 2.5.1]) + CFLAGS="$CFLAGS -DHAVE_BROKEN_GETPASS -DSOLARIS -DHAVE_RWLOCK_T"; + CXXFLAGS="$CXXFLAGS -DHAVE_RWLOCK_T -DSOLARIS" + ;; + *solaris*) + CFLAGS="$CFLAGS -DHAVE_RWLOCK_T" + CXXFLAGS="$CXXFLAGS -DHAVE_RWLOCK_T" + ;; + *SunOS*) + AC_MSG_WARN([Enabling getpass() workaround for SunOS]) + CFLAGS="$CFLAGS -DHAVE_BROKEN_GETPASS -DSOLARIS"; + ;; + *hpux10.20*) + AC_MSG_WARN([Enabling workarounds for hpux 10.20]) + CFLAGS="$CFLAGS -DHAVE_BROKEN_SNPRINTF -DSIGNALS_DONT_BREAK_READ -DDO_NOT_REMOVE_THREAD_WRAPPERS -DHPUX10 -DSIGNAL_WITH_VIO_CLOSE -DHAVE_BROKEN_PTHREAD_COND_TIMEDWAIT -DHAVE_POSIX1003_4a_MUTEX" + CXXFLAGS="$CXXFLAGS -DHAVE_BROKEN_SNPRINTF -D_INCLUDE_LONGLONG -DSIGNALS_DONT_BREAK_READ -DDO_NOT_REMOVE_THREAD_WRAPPERS -DHPUX10 -DSIGNAL_WITH_VIO_CLOSE -DHAVE_BROKEN_PTHREAD_COND_TIMEDWAIT -DHAVE_POSIX1003_4a_MUTEX" + if test "$with_named_thread" = "no" + then + AC_MSG_WARN([Using --with-named-thread=-lpthread]) + with_named_thread="-lcma" + fi + ;; + *hpux11.*) + AC_MSG_WARN([Enabling workarounds for hpux 11]) + CFLAGS="$CFLAGS -DHPUX11 -DSNPRINTF_RETURN_TRUNC -DHAVE_BROKEN_PREAD -DHAVE_BROKEN_GETPASS -DNO_FCNTL_NONBLOCK -DDO_NOT_REMOVE_THREAD_WRAPPERS -DHAVE_BROKEN_PTHREAD_COND_TIMEDWAIT" + CXXFLAGS="$CXXFLAGS -DHPUX11 -DSNPRINTF_RETURN_TRUNC -DHAVE_BROKEN_PREAD -D_INCLUDE_LONGLONG -DNO_FCNTL_NONBLOCK -DDO_NOT_REMOVE_THREAD_WRAPPERS -DHAVE_BROKEN_PTHREAD_COND_TIMEDWAIT" + if test "$with_named_thread" = "no" + then + AC_MSG_WARN([Using --with-named-thread=-lpthread]) + with_named_thread="-lpthread" + fi + # Fixes for HPUX 11.0 compiler + if test "$ac_cv_prog_gcc" = "no" + then + CFLAGS="$CFLAGS -DHAVE_BROKEN_INLINE" +# set working flags first in line, letting override it (i. e. for debug): + CXXFLAGS="+O2 $CXXFLAGS" + MAX_C_OPTIMIZE="" + MAX_CXX_OPTIMIZE="" + ndb_cxxflags_fix="$ndb_cxxflags_fix -Aa" + fi + ;; + *rhapsody*) + if test "$ac_cv_prog_gcc" = "yes" + then + CPPFLAGS="$CPPFLAGS -traditional-cpp " + CFLAGS="-DHAVE_CTHREADS_WRAPPER -DDO_NOT_REMOVE_THREAD_WRAPPERS" + CXXFLAGS="-DHAVE_CTHREADS_WRAPPER" + if test $with_named_curses = "no" + then + with_named_curses="" + fi + fi + ;; + *darwin5*) + if test "$ac_cv_prog_gcc" = "yes" + then + FLAGS="-traditional-cpp -DHAVE_DARWIN5_THREADS -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DHAVE_BROKEN_REALPATH" + CFLAGS="$CFLAGS $FLAGS" + CXXFLAGS="$CXXFLAGS $FLAGS" + MAX_C_OPTIMIZE="-O" + with_named_curses="" + fi + ;; + *darwin6*) + if test "$ac_cv_prog_gcc" = "yes" + then + FLAGS="-D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DHAVE_BROKEN_REALPATH -DDONT_DECLARE_CXA_PURE_VIRTUAL " + CFLAGS="$CFLAGS $FLAGS" + CXXFLAGS="$CXXFLAGS $FLAGS" + MAX_C_OPTIMIZE="-O" + fi + ;; + *darwin*) + if test "$ac_cv_prog_gcc" = "yes" + then + FLAGS="-D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL" + CFLAGS="$CFLAGS $FLAGS" + CXXFLAGS="$CXXFLAGS $FLAGS" + MAX_C_OPTIMIZE="-O" + fi + ;; + *freebsd*|*dragonfly*) + AC_MSG_WARN([Adding fix for interrupted reads]) + OSVERSION=`sysctl -a | grep osreldate | awk '{ print $2 }'` + if test "$OSVERSION" -gt "480100" && \ + test "$OSVERSION" -lt "500000" || \ + test "$OSVERSION" -gt "500109" + then + CXXFLAGS="$CXXFLAGS -DMYSQLD_NET_RETRY_COUNT=1000000" + else + CFLAGS="$CFLAGS -DHAVE_BROKEN_REALPATH" + CXXFLAGS="$CXXFLAGS -DMYSQLD_NET_RETRY_COUNT=1000000 -DHAVE_BROKEN_REALPATH" + fi + ;; + *netbsd*) + AC_MSG_WARN([Adding flag -Dunix]) + CFLAGS="$CFLAGS -Dunix" + CXXFLAGS="$CXXFLAGS -Dunix" + OVERRIDE_MT_LD_ADD="\$(top_srcdir)/mit-pthreads/obj/libpthread.a" + ;; + *bsdi*) + AC_MSG_WARN([Adding fix for BSDI]) + CFLAGS="$CFLAGS -D__BSD__ -DHAVE_BROKEN_REALPATH" + AC_DEFINE_UNQUOTED([SOCKOPT_OPTLEN_TYPE], [size_t], + [Last argument to get/setsockopt]) + ;; + *sgi-irix6*) + if test "$with_named_thread" = "no" + then + AC_MSG_WARN([Using --with-named-thread=-lpthread]) + with_named_thread="-lpthread" + fi + CXXFLAGS="$CXXFLAGS -D_BOOL" + ;; + *aix4.3*) + AC_MSG_WARN([Adding defines for AIX]) + CFLAGS="$CFLAGS -Wa,-many -DUNDEF_HAVE_INITGROUPS -DSIGNALS_DONT_BREAK_READ" + CXXFLAGS="$CXXFLAGS -Wa,-many -DUNDEF_HAVE_INITGROUPS -DSIGNALS_DONT_BREAK_READ" + ;; +dnl Is this the right match for DEC OSF on alpha? + *dec-osf*) + if test "$ac_cv_prog_gcc" = "yes" && test "$host_cpu" = "alpha" + then + AC_MSG_WARN([Adding defines for DEC OSF on alpha]) + CFLAGS="$CFLAGS -mieee" + CXXFLAGS="$CXXFLAGS -mieee" + fi + AC_MSG_WARN([Adding defines for OSF1]) + # gethostbyname_r is deprecated and doesn't work ok on OSF1 + CFLAGS="$CFLAGS -DUNDEF_HAVE_GETHOSTBYNAME_R -DSNPRINTF_RETURN_TRUNC" + CXXFLAGS="$CXXFLAGS -DUNDEF_HAVE_GETHOSTBYNAME_R -DSNPRINTF_RETURN_TRUNC" + # fix to handle include of correctly on OSF1 with cxx compiler + CXXFLAGS="$CXXFLAGS -I/usr/include/cxx -I/usr/include/cxx_cname -I/usr/include -I/usr/include.dtk" + ;; + *netware*) + # No need for curses library so set it to null + with_named_curses="" + + # No thread library - in LibC + with_named_thread="" + + # + # Edit Makefile.in files. + # + echo -n "configuring Makefile.in files for NetWare... " + for file in sql/Makefile.in extra/Makefile.in client/Makefile.in + do + # echo "#### $file ####" + filedir="`dirname $file`" + filebase="`basename $file`" + filesed=$filedir/$filebase.sed + # + # Backup and always use original file + # + if test -f $file.bk + then + cp -fp $file.bk $file + else + cp -fp $file $file.bk + fi + case $file in + sql/Makefile.in) + # Use gen_lex_hash.linux instead of gen_lex_hash + # Add library dependencies to mysqld_DEPENDENCIES + lib_DEPENDENCIES="\$(pstack_libs) \$(openssl_libs) \$(yassl_libs)" + cat > $filesed << EOF +s,\(\./gen_lex_hash\)\$(EXEEXT),\1.linux, +s%\(mysqld_DEPENDENCIES = \)%\1$lib_DEPENDENCIES % +EOF + ;; + extra/Makefile.in) + cat > $filesed << EOF +s,\(extra/comp_err\)\$(EXEEXT),\1.linux, +EOF + ;; + libmysql/Makefile.in) + cat > $filesed << EOF +s,libyassl.la,.libs/libyassl.a, +s,libtaocrypt.la,.libs/libtaocrypt.a, +EOF + ;; + libmysql_r/Makefile.in) + cat > $filesed << EOF +s,libyassl.la,.libs/libyassl.a, +s,libtaocrypt.la,.libs/libtaocrypt.a, +EOF + ;; + client/Makefile.in) + # + cat > $filesed << EOF +s,libmysqlclient.la,.libs/libmysqlclient.a, +EOF + ;; + esac + if `sed -f $filesed $file > $file.nw`;\ + then + mv -f $file.nw $file + rm -f $filesed + else + exit 1 + fi + # wait for file system changes to complete + sleep 1 + done + echo "done" + + # + # Make sure the following files are writable. + # + # When the files are retrieved from some source code control systems they are read-only. + # + echo -n "making sure specific build files are writable... " + for file in \ + Docs/manual.chm \ + Docs/mysql.info \ + Docs/INSTALL-BINARY \ + INSTALL-SOURCE \ + COPYING + do + if test -e $file; then + chmod +w $file + fi + done + echo "done" + + ;; +esac + + +#---START: Used in for client configure +# Check if we threads are in libc or if we should use +# -lpthread, -lpthreads or mit-pthreads +# We have to check libc last because else it fails on Solaris 2.6 + +with_posix_threads="no" +# Search thread lib on Linux +if test "$with_named_thread" = "no" +then + AC_MSG_CHECKING("Linux threads") + if test "$TARGET_LINUX" = "true" + then + AC_MSG_RESULT("starting") + # use getconf to check glibc contents + AC_MSG_CHECKING("getconf GNU_LIBPTHREAD_VERSION") + case `getconf GNU_LIBPTHREAD_VERSION | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ` in + NPTL* ) + AC_MSG_RESULT("NPTL") + AC_DEFINE([HAVE_NPTL], [1], [NPTL threads implementation]) + with_named_thread="-lpthread" + ;; + LINUXTHREADS* ) + AC_MSG_RESULT("Linuxthreads") + AC_DEFINE([HAVE_LINUXTHREADS], [1], + [Whether we are using Xavier Leroy's LinuxThreads]) + with_named_thread="-lpthread" + ;; + * ) + AC_MSG_RESULT("unknown") + ;; + esac + if test "$with_named_thread" = "no" + then + # old method, check headers + # Look for LinuxThreads. + AC_MSG_CHECKING("LinuxThreads in header file comment") + res=`grep Linuxthreads /usr/include/pthread.h 2>/dev/null | wc -l` + if test "$res" -gt 0 + then + AC_MSG_RESULT("Found") + AC_DEFINE([HAVE_LINUXTHREADS], [1], + [Whether we are using Xavier Leroy's LinuxThreads]) + # Linux 2.0 sanity check + AC_TRY_COMPILE([#include ], [int a = sched_get_priority_min(1);], , + AC_MSG_ERROR([Syntax error in sched.h. Change _P to __P in the /usr/include/sched.h file. See the Installation chapter in the Reference Manual])) + # RedHat 5.0 does not work with dynamic linking of this. -static also + # gives a speed increase in linux so it does not hurt on other systems. + with_named_thread="-lpthread" + else + AC_MSG_RESULT("Not found") + # If this is a linux machine we should barf + AC_MSG_ERROR([This is a Linux system without a working getconf, +and Linuxthreads was not found. Please install it (or a new glibc) and try again. +See the Installation chapter in the Reference Manual for more information.]) + fi + else + AC_MSG_RESULT("no need to check headers") + fi + + AC_MSG_CHECKING("for pthread_create in -lpthread") + ac_save_LIBS="$LIBS" + LIBS="$LIBS -lpthread" + AC_TRY_LINK( [#include ], + [ (void) pthread_create((pthread_t*) 0,(pthread_attr_t*) 0, 0, 0); ], + AC_MSG_RESULT("yes"), + [ AC_MSG_RESULT("no") + AC_MSG_ERROR([ +This is a Linux system claiming to support threads, either Linuxthreads or NPTL, but linking a test program failed. +Please install one of these (or a new glibc) and try again. +See the Installation chapter in the Reference Manual for more information.]) ] + ) + LIBS="$ac_save_LIBS" + else + AC_MSG_RESULT("no") + fi # "$TARGET_LINUX" +fi # "$with_named_thread" = "no" -a "$with_mit_threads" = "no" + + +# Hack for DEC-UNIX (OSF1 -> Tru64) +if test "$with_named_thread" = "no" -a "$with_mit_threads" = "no" +then + AC_MSG_CHECKING("DEC threads post OSF/1 3.2") + if test -f /usr/shlib/libpthread.so -a -f /usr/lib/libmach.a -a -f /usr/ccs/lib/cmplrs/cc/libexc.a + then + with_named_thread="-lpthread -lmach -lexc" + CFLAGS="$CFLAGS -D_REENTRANT" + CXXFLAGS="$CXXFLAGS -D_REENTRANT" + AC_DEFINE(HAVE_DEC_THREADS, [1], [Whether we are using DEC threads]) + AC_MSG_RESULT("yes") + else + AC_MSG_RESULT("no") + fi # DEC threads +fi # "$with_named_thread" = "no" -a "$with_mit_threads" = "no" + + +dnl This is needed because -lsocket has to come after the thread +dnl library on SCO. +AC_DEFUN([MYSQL_REMOVE_SOCKET_FROM_LIBS_HACK], [ + LIBS=`echo " $LIBS " | sed -e 's/ -lsocket / /g'` +]) +# Hack for SCO UNIX +if test "$with_named_thread" = "no" +then + AC_MSG_CHECKING("SCO threads") + if expr "$SYSTEM_TYPE" : ".*sco.*" > /dev/null + then + if test -f /usr/lib/libgthreads.a -o -f /usr/lib/libgthreads.so + then + MYSQL_REMOVE_SOCKET_FROM_LIBS_HACK + with_named_thread="-lgthreads -lsocket -lgthreads" + # sched.h conflicts with fsu-threads + touch ./include/sched.h + touch ./include/semaphore.h + + # We must have gcc + if expr "$CC" : ".*gcc.*" + then + AC_MSG_RESULT("yes") + else + AC_MSG_ERROR([On SCO UNIX MySQL must be compiled with gcc. See the Installation chapter in the Reference Manual.]) + fi + AC_MSG_RESULT("yes") + elif test -f /usr/local/lib/libpthread.a -o -f /usr/local/lib/libpthread.so + then + MYSQL_REMOVE_SOCKET_FROM_LIBS_HACK + with_named_thread="-lpthread -lsocket" + # sched.h conflicts with fsu-threads + # touch ./include/sched.h + + AC_MSG_CHECKING("for gcc") + # We must have gcc + if expr "$CC" : ".*gcc.*" + then + AC_MSG_RESULT("yes") + else + AC_MSG_ERROR([On SCO UNIX MySQL must be compiled with gcc. See the Installation chapter in the Reference Manual.]) + fi + AC_MSG_RESULT("yes") + # Hack for SCO UnixWare 7.1.x + # + elif test "$with_named_thread" = "no" + then + AC_MSG_RESULT("no") + AC_MSG_CHECKING("SCO UnixWare 7.1.x native threads") + if expr "$SYSTEM_TYPE" : ".*sco.*" > /dev/null + then + if test -f /usr/lib/libthread.so -o -f /usr/lib/libthreadT.so + then + MYSQL_REMOVE_SOCKET_FROM_LIBS_HACK + if expr "$CC" : ".*gcc.*" + then + with_named_thread="-pthread -lsocket -lnsl" + else + with_named_thread="-Kthread -lsocket -lnsl" + fi + if expr "$SYSTEM_TYPE" : ".*unixware7.0.0" > /dev/null + then + AC_DEFINE(HAVE_UNIXWARE7_THREADS, [1]) + fi + AC_MSG_RESULT("yes") + # We must have cc + AC_MSG_CHECKING("for gcc") + if expr "$CC" : ".*gcc.*" + then + CC="$CC -pthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK" + CXX="$CXX -pthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK" + else + CC="$CC -Kthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK" + CXX="$CXX -Kthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK" + fi + else + AC_MSG_ERROR([configure: error: Can't find thread libs on SCO UnixWare7. See the Installation chapter in the Reference Manual.]) + fi + else + AC_MSG_RESULT("no") + fi + else + AC_MSG_ERROR([On SCO UNIX MySQL requires that the FSUThreads package is installed. See the Installation chapter in the Reference Manual.]) + fi + else + AC_MSG_RESULT("no") + fi +fi + +# +# Check for SCO threading libraries +# +if test "$with_named_thread" = "no" +then + AC_MSG_CHECKING([SCO OpenServer 6, UnixWare 7 or OpenUNIX 8 native threads]) + if expr "$SYSTEM_TYPE" : ".*UnixWare.*" > /dev/null || \ + expr "$SYSTEM_TYPE" : ".*SCO_SV6.*" > /dev/null || \ + expr "$SYSTEM_TYPE" : ".*OpenUNIX.*" > /dev/null + then + if test -f /usr/lib/libthread.so -o -f /usr/lib/libthreadT.so + then + MYSQL_REMOVE_SOCKET_FROM_LIBS_HACK + if expr "$CC" : ".*gcc.*" > /dev/null + then + with_named_thread="-pthread -lsocket -lnsl" + CC="$CC -pthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK"; + CXX="$CXX -pthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK"; + else + with_named_thread="-Kthread -lsocket -lnsl" + CC="$CC -Kthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK"; + CXX="$CXX -Kthread -DUNIXWARE_7 -DHAVE_BROKEN_RWLOCK"; + fi + if expr "$SYSTEM_TYPE" : ".*unixware7.0.0" > /dev/null + then + AC_DEFINE(HAVE_UNIXWARE7_THREADS, [1], [Have UnixWare 7 (or similar) almost-POSIX threading library]) + fi + AC_MSG_RESULT(yes) + else + AC_MSG_ERROR([configure: error: Can't find thread library on SCO/Caldera system. See the Installation chapter in the Reference Manual.]) + fi + else + AC_MSG_RESULT(no) + fi +fi + +# Hack for Siemens UNIX +if test "$with_named_thread" = "no" +then + AC_MSG_CHECKING("Siemens threads") + if test -f /usr/lib/libxnet.so -a "$SYSTEM_TYPE" = "sni-sysv4" + then + LIBS="-lxnet $LIBS" + NON_THREADED_LIBS="-lxnet $NON_THREADED_LIBS" + with_named_thread="-Kthread $LDFLAGS -lxnet" + LD_FLAGS="" + CFLAGS="-Kthread $CFLAGS" + CXXFLAGS="-Kthread $CXXFLAGS" + AC_MSG_RESULT("yes") + else + AC_MSG_RESULT("no") + fi +fi + +# Use library named -lpthread +if test "$with_named_thread" = "no" -a "$with_pthread" = "yes" +then + with_named_thread="-lpthread" +fi + +#---END: + +# Hack for Solaris >= 2.5 +# We want both the new and the old interface + +if test "$with_named_thread" = "no" +then + AC_MSG_CHECKING("Solaris threads") + if test -f /usr/lib/libpthread.so -a -f /usr/lib/libthread.so + then + with_named_thread="-lpthread -lthread" + AC_MSG_RESULT("yes") + else + AC_MSG_RESULT("no") + fi +fi + +# Should we use named pthread library ? +AC_MSG_CHECKING("named thread libs:") +if test "$with_named_thread" != "no" +then + LIBS="$with_named_thread $LIBS $with_named_thread" + CLIENT_THREAD_LIBS="$with_named_thread" + with_posix_threads="yes" + AC_MSG_RESULT("$with_named_thread") +else + AC_MSG_RESULT("no") + # pthread_create is in standard libraries (As in BSDI 3.0) + AC_MSG_CHECKING("for pthread_create in -libc"); + AC_TRY_LINK( + [#include ], + [ (void) pthread_create((pthread_t*) 0,(pthread_attr_t*) 0, 0, 0); ], + with_posix_threads=yes, with_posix_threads=no) + AC_MSG_RESULT("$with_posix_threads") + if test "$with_posix_threads" = "no" + then + AC_MSG_CHECKING("for pthread_create in -lpthread") + ac_save_LIBS="$LIBS" + LIBS="$LIBS -lpthread" + CLIENT_THREAD_LIBS="-lpthread" + AC_TRY_LINK( + [#include ], + [ (void) pthread_create((pthread_t*) 0,(pthread_attr_t*) 0, 0, 0); ], + with_posix_threads=yes, with_posix_threads=no) + AC_MSG_RESULT("$with_posix_threads") + if test "$with_posix_threads" = "no" + then + LIBS=" $ac_save_LIBS -lpthreads" + CLIENT_THREAD_LIBS="-lpthreads" + AC_MSG_CHECKING("for pthread_create in -lpthreads") + AC_TRY_LINK( + [#include ], + [ pthread_create((pthread_t*) 0,(pthread_attr_t*) 0, 0, 0); ], + with_posix_threads=yes, with_posix_threads=no) + AC_MSG_RESULT("$with_posix_threads") + if test "$with_posix_threads" = "no" + then + # This is for FreeBSD + LIBS="$ac_save_LIBS -pthread" + CLIENT_THREAD_LIBS="-pthread" + AC_MSG_CHECKING("for pthread_create in -pthread") + AC_TRY_LINK( + [#include ], + [ pthread_create((pthread_t*) 0,(pthread_attr_t*) 0, 0, 0); ], + with_posix_threads=yes, with_posix_threads=no) + AC_MSG_RESULT("$with_posix_threads") + fi + fi + fi +fi + +#---START: Used in for client configure +# Must be checked after, because strtok_r may be in -lpthread +# On AIX strtok_r is in libc_r + +my_save_LIBS="$LIBS" +AC_CHECK_LIB(pthread,strtok_r) +LIBS="$my_save_LIBS" +if test "$ac_cv_lib_pthread_strtok_r" = "no" +then + AC_CHECK_LIB(c_r,strtok_r) + case "$with_osf32_threads---$target_os" in + # Don't keep -lc_r in LIBS; -pthread handles it magically + yes---* | *---freebsd* | *---hpux*) LIBS="$my_save_LIBS" ;; + + esac + AC_CHECK_FUNCS(strtok_r pthread_init) +else + AC_CHECK_FUNCS(strtok_r) +fi +#---END: + +# dlopen, dlerror +case "$with_mysqld_ldflags " in + + *"-all-static "*) + # No need to check for dlopen when mysqld is linked with + # -all-static as it won't be able to load any functions. + # NOTE! It would be better if it was possible to test if dlopen + # can be used, but a good way to test it couldn't be found + + ;; + + *) + # Check for dlopen, needed for user definable functions + # This must be checked after threads on AIX + # We only need this for mysqld, not for the clients. + + my_save_LIBS="$LIBS" + LIBS="" + AC_CHECK_LIB(dl,dlopen) + LIBDL=$LIBS + LIBS="$my_save_LIBS" + AC_SUBST(LIBDL) + + my_save_LIBS="$LIBS" + LIBS="$LIBS $LIBDL" + AC_CHECK_FUNCS(dlopen dlerror) + LIBS="$my_save_LIBS" + + ;; +esac + + +# System characteristics +case $SYSTEM_TYPE in + *netware*) ;; + *) +AC_SYS_RESTARTABLE_SYSCALLS + ;; +esac + +# Build optimized or debug version ? +# First check for gcc and g++ +if test "$GCC" = "yes" +then + DEBUG_CFLAGS="-g" + DEBUG_OPTIMIZE_CC="-O" + OPTIMIZE_CFLAGS="$MAX_C_OPTIMIZE" +else + DEBUG_CFLAGS="-g" + DEBUG_OPTIMIZE_CC="" + case $SYSTEM_TYPE in + *solaris*) + OPTIMIZE_CFLAGS="-O1" + ;; + *) + OPTIMIZE_CFLAGS="-O" + ;; + esac +fi +if test "$GXX" = "yes" +then + DEBUG_CXXFLAGS="-g" + DEBUG_OPTIMIZE_CXX="-O" + OPTIMIZE_CXXFLAGS="$MAX_CXX_OPTIMIZE" +else + DEBUG_CXXFLAGS="-g" + DEBUG_OPTIMIZE_CXX="" + case $SYSTEM_TYPE in + *solaris*) + OPTIMIZE_CXXFLAGS="-O1" + ;; + *) + OPTIMIZE_CXXFLAGS="-O" + ;; + esac +fi + +case $SYSTEM_TYPE in + *netware*) + DEBUG_CFLAGS="-g -DDEBUG -sym internal,codeview4" + DEBUG_CXXFLAGS="-g -DDEBUG -sym internal,codeview4" + DEBUG_OPTIMIZE_CC="-DDEBUG" + DEBUG_OPTIMIZE_CXX="-DDEBUG" + OPTIMIZE_CFLAGS="-O3 -DNDEBUG" + OPTIMIZE_CXXFLAGS="-O3 -DNDEBUG" + ;; +esac + +# If the user specified CFLAGS, we won't add any optimizations +if test -n "$SAVE_CFLAGS" +then + OPTIMIZE_CFLAGS="" + DEBUG_OPTIMIZE_CC="" +fi +# Ditto for CXXFLAGS +if test -n "$SAVE_CXXFLAGS" +then + OPTIMIZE_CXXFLAGS="" + DEBUG_OPTIMIZE_CXX="" +fi + +AC_ARG_WITH(debug, + [ --with-debug Add debug code + --with-debug=full Add debug code (adds memory checker, very slow)], + [with_debug=$withval], + [with_debug=no]) +if test "$with_debug" = "yes" +then + # Medium debug. + AC_DEFINE([DBUG_ON], [1], [Use libdbug]) + CFLAGS="$DEBUG_CFLAGS $DEBUG_OPTIMIZE_CC -DSAFE_MUTEX $CFLAGS" + CXXFLAGS="$DEBUG_CXXFLAGS $DEBUG_OPTIMIZE_CXX -DSAFE_MUTEX $CXXFLAGS" +elif test "$with_debug" = "full" +then + # Full debug. Very slow in some cases + AC_DEFINE([DBUG_ON], [1], [Use libdbug]) + CFLAGS="$DEBUG_CFLAGS -DSAFE_MUTEX -DSAFEMALLOC $CFLAGS" + CXXFLAGS="$DEBUG_CXXFLAGS -DSAFE_MUTEX -DSAFEMALLOC $CXXFLAGS" +else + # Optimized version. No debug + AC_DEFINE([DBUG_OFF], [1], [Don't use libdbug]) + CFLAGS="$OPTIMIZE_CFLAGS $CFLAGS" + CXXFLAGS="$OPTIMIZE_CXXFLAGS $CXXFLAGS" +fi + +# If we should allow error injection tests +AC_ARG_WITH(error-inject, + AC_HELP_STRING([--with-error-inject],[Enable error injection in MySQL Server]), + [ with_error_inject=$withval ], + [ with_error_inject=no ]) + +if test $with_debug != "no" +then + if test "$with_error_inject" = "yes" + then + AC_DEFINE([ERROR_INJECT_SUPPORT], [1], + [Enable error injection in MySQL Server]) + fi +fi + +AC_ARG_WITH([fast-mutexes], + AC_HELP_STRING([--with-fast-mutexes], + [Compile with fast mutexes (default is disabled)]), + [with_fast_mutexes=$withval], [with_fast_mutexes=no]) + +if test "$with_fast_mutexes" != "no" +then + if test "$with_debug" != "no" + then + AC_MSG_WARN(['--with-fast-mutexes' ignored when '--with-debug' is given]) + else + AC_DEFINE([MY_PTHREAD_FASTMUTEX], [1], + [Define to 1 if you want to use fast mutexes]) + fi +fi + +AC_ARG_WITH([atomic-ops], + AC_HELP_STRING([--with-atomic-ops=rwlocks|smp|up], + [Implement atomic operations using pthread rwlocks or atomic CPU + instructions for multi-processor (default) or uniprocessor + configuration]), , [with_atomic_ops=smp]) +case "$with_atomic_ops" in + "up") AC_DEFINE([MY_ATOMIC_MODE_DUMMY], [1], + [Assume single-CPU mode, no concurrency]) ;; + "rwlocks") AC_DEFINE([MY_ATOMIC_MODE_RWLOCKS], [1], + [Use pthread rwlocks for atomic ops]) ;; + "smp") ;; + *) AC_MSG_ERROR(["$with_atomic_ops" is not a valid value for --with-atomic-ops]) ;; +esac + +AC_CACHE_CHECK([whether the compiler provides atomic builtins], + [mysql_cv_gcc_atomic_builtins], [AC_TRY_RUN([ + int main() + { + int foo= -10; int bar= 10; + if (!__sync_fetch_and_add(&foo, bar) || foo) + return -1; + bar= __sync_lock_test_and_set(&foo, bar); + if (bar || foo != 10) + return -1; + bar= __sync_val_compare_and_swap(&bar, foo, 15); + if (bar) + return -1; + return 0; + } +], [mysql_cv_gcc_atomic_builtins=yes], + [mysql_cv_gcc_atomic_builtins=no], + [mysql_cv_gcc_atomic_builtins=no])]) + +if test "x$mysql_cv_gcc_atomic_builtins" = xyes; then + AC_DEFINE(HAVE_GCC_ATOMIC_BUILTINS, 1, + [Define to 1 if compiler provides atomic builtins.]) +fi + +# Force static compilation to avoid linking problems/get more speed +AC_ARG_WITH(mysqld-ldflags, + [ --with-mysqld-ldflags Extra linking arguments for mysqld], + [MYSQLD_EXTRA_LDFLAGS=$withval], + [MYSQLD_EXTRA_LDFLAGS=]) +AC_SUBST(MYSQLD_EXTRA_LDFLAGS) + +AC_ARG_WITH(client-ldflags, + [ --with-client-ldflags Extra linking arguments for clients], + [CLIENT_EXTRA_LDFLAGS=$withval], + [CLIENT_EXTRA_LDFLAGS=]) +AC_SUBST(CLIENT_EXTRA_LDFLAGS) + +AC_ARG_WITH(mysqld-libs, + [ --with-mysqld-libs Extra libraries to link with for mysqld], + [MYSQLD_EXTRA_LIBS=$withval], + [MYSQLD_EXTRA_LIBS=]) +AC_SUBST(MYSQLD_EXTRA_LIBS) + +AC_ARG_WITH(lib-ccflags, + [ --with-lib-ccflags Extra CC options for libraries], + [LIB_EXTRA_CCFLAGS=$withval], + [LIB_EXTRA_CCFLAGS=]) +AC_SUBST(LIB_EXTRA_CCFLAGS) + +# Avoid stupid bug on some OS +AC_ARG_WITH(low-memory, + [ --with-low-memory Try to use less memory to compile to avoid + memory limitations.], + [with_lowmem=$withval], + [with_lowmem=no]) +if test "$with_lowmem" = "yes" +then + if test "$ac_cv_prog_gcc" = "yes" + then + LM_CFLAGS="-fno-inline" + else + LM_CFLAGS="-O0" + fi +else + LM_CFLAGS="" +fi +AC_SUBST(LM_CFLAGS) + +AC_ARG_WITH(comment, + [ --with-comment Comment about compilation environment.], + [with_comment=$withval], + [with_comment=no]) +if test "$with_comment" != "no" +then + COMPILATION_COMMENT=$with_comment +else + COMPILATION_COMMENT="Calpont InfiniDB Community 3.5.6 Beta (COSS LA)" +fi +AC_SUBST(COMPILATION_COMMENT) + +AC_MSG_CHECKING("need of special linking flags") +if test "$TARGET_LINUX" = "true" -a "$ac_cv_prog_gcc" = "yes" -a "$all_is_static" != "yes" +then + LDFLAGS="$LDFLAGS -rdynamic" + AC_MSG_RESULT("-rdynamic") +else + case "$SYSTEM_TYPE$with_mysqld_ldflags " in + *freebsd*"-all-static "*|*dragonfly*"-all-static "*) + AC_MSG_RESULT("none") + ;; + *freebsd*|*dragonfly*) + MYSQLD_EXTRA_LDFLAGS="$MYSQLD_EXTRA_LDFLAGS -export-dynamic" + AC_MSG_RESULT("-export-dynamic") + ;; + *) + AC_MSG_RESULT("none") + ;; + esac +fi + +dnl Checks for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_C_INLINE +AC_TYPE_OFF_T +AC_STRUCT_ST_RDEV +AC_HEADER_TIME +AC_STRUCT_TM +MYSQL_NEEDS_MYSYS_NEW +# AC_CHECK_SIZEOF return 0 when it does not find the size of a +# type. We want a error instead. +AC_CHECK_SIZEOF(char, 1) +if test "$ac_cv_sizeof_char" -eq 0 +then + AC_MSG_ERROR([No size for char type. +A likely cause for this could be that there isn't any +static libraries installed. You can verify this by checking if you have libm.a +in /lib, /usr/lib or some other standard place. If this is the problem, +install the static libraries and try again. If this isn't the problem, +examine config.log for possible errors. If you want to report this, use +'scripts/mysqlbug' and include at least the last 20 rows from config.log!]) +fi +AC_CHECK_SIZEOF(char*, 4) +AC_CHECK_SIZEOF(short, 2) +AC_CHECK_SIZEOF(int, 4) +if test "$ac_cv_sizeof_int" -eq 0 +then + AC_MSG_ERROR("No size for int type.") +fi +AC_CHECK_SIZEOF(long, 4) +if test "$ac_cv_sizeof_long" -eq 0 +then + AC_MSG_ERROR("No size for long type.") +fi +AC_CHECK_SIZEOF(long long, 8) +if test "$ac_cv_sizeof_long_long" -eq 0 +then + AC_MSG_ERROR("MySQL needs a long long type.") +fi +# off_t is not a builtin type +AC_CHECK_SIZEOF(off_t, 4) +if test "$ac_cv_sizeof_off_t" -eq 0 +then + AC_MSG_ERROR("MySQL needs a off_t type.") +fi + +dnl +dnl check if time_t is unsigned +dnl + +MYSQL_CHECK_TIME_T + + +# do we need #pragma interface/#pragma implementation ? +# yes if it's gcc 2.x, and not icc pretending to be gcc, and not cygwin +AC_MSG_CHECKING(the need for @%:@pragma interface/implementation) +# instead of trying to match SYSTEM_TYPE and CC_VERSION (that doesn't +# follow any standard), we'll use well-defined preprocessor macros: +AC_TRY_CPP([ +#if !defined(__CYGWIN__) && !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ < 3) +#error USE_PRAGMA_IMPLEMENTATION +#endif +],AC_MSG_RESULT(no) ,AC_MSG_RESULT(yes) ; CXXFLAGS="$CXXFLAGS -DUSE_PRAGMA_IMPLEMENTATION") + +# This always gives a warning. Ignore it unless you are cross compiling +AC_C_BIGENDIAN +#---START: Used in for client configure +# Check base type of last arg to accept +MYSQL_TYPE_ACCEPT +#---END: +# Figure out what type of struct rlimit to use with setrlimit +MYSQL_TYPE_STRUCT_RLIMIT +# Find where the stack goes +MYSQL_STACK_DIRECTION +# We want to skip alloca on irix unconditionally. It may work on some version.. +MYSQL_FUNC_ALLOCA +# Do struct timespec have members tv_sec or ts_sec +MYSQL_TIMESPEC_TS +# Do we have the tzname variable +MYSQL_TZNAME +# Do the c++ compiler have a bool type +MYSQL_CXX_BOOL +# Check some common bugs with gcc 2.8.# on sparc +case $SYSTEM_TYPE in + *netware*) ;; + *) + MYSQL_CHECK_LONGLONG_TO_FLOAT + if test "$ac_cv_conv_longlong_to_float" != "yes" + then + AC_MSG_ERROR([Your compiler cannot convert a longlong value to a float! + If you are using gcc 2.8.# you should upgrade to egcs 1.0.3 or newer and try + again]) + fi + ;; +esac +AC_CHECK_TYPES([sigset_t, off_t], [], [], [#include ]) +AC_CHECK_TYPES([size_t], [], [], [#include ]) +AC_CHECK_TYPES([u_int32_t]) + +MYSQL_PTHREAD_YIELD + +###################################################################### +# For readline/libedit (We simply move the mimimum amount of stuff from +# the readline/libedit configure.in here) + +dnl Checks for header files. +AC_CHECK_HEADERS(malloc.h sys/cdefs.h) + +dnl Checks for library functions. +AC_FUNC_ALLOCA +AC_PROG_GCC_TRADITIONAL +AC_TYPE_SIGNAL +AC_CHECK_FUNCS(re_comp regcomp strdup) + +dnl Sun compilers have their own vis.h that is about something +dnl totally different. So, not to change the libedit source, we +dnl do some additional checks before we define HAVE_VIS_H. +AC_CHECK_HEADER(vis.h, + [AC_CHECK_FUNC(strvis, + [AC_DEFINE([HAVE_VIS_H], [1],[Found vis.h and the strvis() function])])]) + +AC_CHECK_FUNCS(strlcat strlcpy) +AC_CHECK_FUNCS(issetugid) +AC_CHECK_FUNCS(fgetln) +AC_CHECK_FUNCS(getline flockfile) + +# from old readline settting: + +MAKE_SHELL=/bin/sh +AC_SUBST(MAKE_SHELL) + +# Already-done: stdlib.h string.h unistd.h termios.h +AC_CHECK_HEADERS(varargs.h stdarg.h dirent.h locale.h ndir.h sys/dir.h \ + sys/file.h sys/ndir.h sys/ptem.h sys/pte.h sys/select.h sys/stream.h \ + sys/mman.h curses.h termcap.h termio.h termbits.h asm/termbits.h grp.h \ +paths.h semaphore.h) + +# Already-done: strcasecmp +AC_CHECK_FUNCS(lstat putenv select setenv setlocale strcoll tcgetattr) + +AC_STAT_MACROS_BROKEN +MYSQL_SIGNAL_CHECK +MYSQL_CHECK_GETPW_FUNCS +MYSQL_HAVE_TIOCGWINSZ +MYSQL_HAVE_FIONREAD +MYSQL_HAVE_TIOCSTAT +MYSQL_STRUCT_DIRENT_D_INO +MYSQL_STRUCT_DIRENT_D_NAMLEN +MYSQL_TYPE_SIGHANDLER +MYSQL_CHECK_MULTIBYTE +if test "$with_named_curses" = "no" +then + MYSQL_CHECK_LIB_TERMCAP +else + TERMCAP_LIB="$with_named_curses" +fi +AC_SUBST(TERMCAP_LIB) + +# Check if the termcap function 'tgoto' is already declared in +# system header files or if it need to be declared locally +AC_CHECK_DECLS(tgoto,,,[ +#ifdef HAVE_CURSES_H +# include +#elif HAVE_NCURSES_H +# include +#endif +#ifdef HAVE_TERM_H +# include +#endif +]) + +LIBEDIT_LOBJECTS="" +AC_CHECK_FUNC(strunvis, ,[LIBEDIT_LOBJECTS="$LIBEDIT_LOBJECTS unvis.o"]) +AC_CHECK_FUNC(strvis, ,[LIBEDIT_LOBJECTS="$LIBEDIT_LOBJECTS vis.o"]) +AC_CHECK_FUNC(strlcpy, ,[LIBEDIT_LOBJECTS="$LIBEDIT_LOBJECTS strlcpy.o"]) +AC_CHECK_FUNC(strlcat, ,[LIBEDIT_LOBJECTS="$LIBEDIT_LOBJECTS strlcat.o"]) +AC_CHECK_FUNC(fgetln, ,[LIBEDIT_LOBJECTS="$LIBEDIT_LOBJECTS fgetln.o"]) +AC_SUBST(LIBEDIT_LOBJECTS) +enable_readline="yes" + +# End of readline/libedit stuff +######################################################################### + +dnl Checks for library functions. + +# +# The following code disables intrinsic function support while we test for +# library functions. This is to avoid configure problems with Intel ecc +# compiler + +ORG_CFLAGS="$CFLAGS" +if test "$GCC" != "yes"; then + AC_SYS_COMPILER_FLAG(-nolib_inline,nolib_inline,CFLAGS,[],[]) +fi + +#AC_FUNC_MMAP +AC_TYPE_SIGNAL +MYSQL_TYPE_QSORT +AC_FUNC_UTIME_NULL +AC_FUNC_VPRINTF + +AC_CHECK_FUNCS(alarm bcmp bfill bmove bsearch bzero \ + chsize cuserid fchmod fcntl \ + fconvert fdatasync fesetround finite fpresetsticky fpsetmask fsync ftruncate \ + getcwd gethostbyaddr_r gethostbyname_r getpass getpassphrase getpwnam \ + getpwuid getrlimit getrusage getwd index initgroups isnan \ + localtime_r gethrtime gmtime_r \ + locking longjmp lrand48 madvise mallinfo memcpy memmove \ + mkstemp mlockall perror poll pread pthread_attr_create mmap mmap64 getpagesize \ + pthread_attr_getstacksize pthread_attr_setprio pthread_attr_setschedparam \ + pthread_attr_setstacksize pthread_condattr_create pthread_getsequence_np \ + pthread_key_delete pthread_rwlock_rdlock pthread_setprio \ + pthread_setprio_np pthread_setschedparam pthread_sigmask readlink \ + realpath rename rint rwlock_init setupterm \ + shmget shmat shmdt shmctl sigaction sigemptyset sigaddset \ + sighold sigset sigthreadmask port_create sleep \ + snprintf socket stpcpy strcasecmp strerror strsignal strnlen strpbrk strstr \ + strtol strtoll strtoul strtoull tell tempnam thr_setconcurrency vidattr \ + posix_fallocate backtrace backtrace_symbols backtrace_symbols_fd) + +# +# +# +case "$target" in + *-*-aix4* | *-*-sco*) + # (grr) aix 4.3 has a stub for clock_gettime, (returning ENOSYS) + # and using AC_TRY_RUN is hard when cross-compiling + # We also disable for SCO for the time being, the headers for the + # thread library we use conflicts with other headers. + ;; + *) AC_CHECK_FUNCS(clock_gettime) + ;; +esac + +case "$mysql_cv_sys_os" in + OS400) # i5/OS (OS/400) emits a SIGILL (Function not implemented) when + # unsupported priority values are passed to pthread_setschedprio. + # Since the only supported value is 1, treat it as inexistent. + ;; + SunOS) # Bug#42599 error: `pthread_setschedprio' was not declared in this scope + # In some installations, the pthread.h header used by GCC does not + # declare the pthread_setscheprio prototype, but the function is + # implemented. Since the function is used in C++ code, ensure that + # the function prototype is present. + AC_MSG_CHECKING([whether pthread_setschedprio is declared]) + AC_LANG_PUSH([C++]) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([#include ], + [(void)(pthread_setschedprio);])], + [ac_cv_func_pthread_setschedprio=yes], + [ac_cv_func_pthread_setschedprio=no]) + AC_LANG_POP([C++]) + AC_MSG_RESULT([$ac_cv_func_pthread_setschedprio]) + if test "$ac_cv_func_pthread_setschedprio" = yes; then + AC_DEFINE(HAVE_PTHREAD_SETSCHEDPRIO, 1, + [Define to 1 if you have the `pthread_setschedprio' function.]) + fi + ;; + *) AC_CHECK_FUNCS(pthread_setschedprio) + ;; +esac + +# Check that isinf() is available in math.h and can be used in both C and C++ +# code +AC_MSG_CHECKING(for isinf in ) +AC_TRY_LINK([#include ], [float f = 0.0; int r = isinf(f); return r], + AC_MSG_RESULT(yes) + AC_MSG_CHECKING(whether isinf() is safe to use in C code) + AC_TRY_RUN([ +#include +int main() +{ + double a= 10.0; + double b= 1e308; + + return !isinf(a * b); +} +], + [AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) + AC_DEFINE([HAVE_BROKEN_ISINF], [1], + [Define to 1 if isinf() uses 80-bit register for intermediate values]) + ], + [ +# Let's be optimistic when cross-compiling, since the only compiler known +# to be affected by this isinf() bug is GCC 4.3 on 32-bit x86. + AC_MSG_RESULT([[cross-compiling, assuming 'yes']]) + ]) + AC_MSG_CHECKING(whether isinf() can be used in C++ code) + AC_LANG_SAVE + AC_LANG_CPLUSPLUS + AC_TRY_LINK([#include ], [float f = 0.0; int r = isinf(f); return r], + AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_ISINF, [1], [isinf() macro or function]), + AC_MSG_RESULT(no)) + AC_LANG_RESTORE, + AC_MSG_RESULT(no)) + +CFLAGS="$ORG_CFLAGS" + +# Sanity check: We chould not have any fseeko symbol unless +# large_file_support=yes +AC_CHECK_FUNC(fseeko, +[if test "$large_file_support" = no -a "$TARGET_LINUX" = "true"; +then + AC_MSG_ERROR("Found fseeko symbol but large_file_support is not enabled!") +fi] +) + +# Check definition of gethostbyaddr_r (glibc2 defines this with 8 arguments) +ac_save_CXXFLAGS="$CXXFLAGS" +AC_CACHE_CHECK([style of gethost* routines], mysql_cv_gethost_style, +AC_LANG_SAVE +AC_LANG_CPLUSPLUS + +# Test whether madvise() is declared in C++ code -- it is not on some +# systems, such as Solaris +AC_CHECK_DECLS(madvise, [], [], [#if HAVE_SYS_MMAN_H +#include +#include +#endif]) + +# Do not treat warnings as errors if we are linking against other libc +# this is to work around gcc not being permissive on non-system includes +# with respect to ANSI C++ +# We also remove the -fbranch-probabilities option as this will give warnings +# about not profiled code, which confuses configure +# We also must remove -W and -Wcheck which on icc produces warnings that +# we don't want to catch with -Werror + +if test "$ac_cv_prog_gxx" = "yes" -a "$with_other_libc" = "no" +then + CXXFLAGS=`echo "$CXXFLAGS -Werror" | sed -e 's/-fbranch-probabilities//; s/-Wall//; s/-ansi//; s/-pedantic//; s/-Wcheck//'` +fi + +AC_TRY_COMPILE( +[#undef inline +#if !defined(SCO) && !defined(__osf__) && !defined(_REENTRANT) +#define _REENTRANT +#endif +#include +#include +#include +#include +#include +#include ], +[int skr; + struct hostent *foo = gethostbyaddr_r((const char *) 0, + 0, 0, (struct hostent *) 0, (char *) NULL, 0, &skr); return (foo == 0);], +mysql_cv_gethost_style=solaris, mysql_cv_gethost_style=other)) +AC_LANG_RESTORE +CXXFLAGS="$ac_save_CXXFLAGS" +if test "$mysql_cv_gethost_style" = "solaris" +then + AC_DEFINE([HAVE_SOLARIS_STYLE_GETHOST], [1], + [Solaris define gethostbyaddr_r with 7 arguments. glibc2 defines this with 8 arguments]) +fi + +#---START: Used in for client configure + +# Check definition of gethostbyname_r (glibc2.0.100 is different from Solaris) +ac_save_CXXFLAGS="$CXXFLAGS" +AC_CACHE_CHECK([style of gethostbyname_r routines], mysql_cv_gethostbyname_style, +AC_LANG_SAVE +AC_LANG_CPLUSPLUS +if test "$ac_cv_prog_gxx" = "yes" -a "$with_other_libc" = "no" +then + CXXFLAGS=`echo "$CXXFLAGS -Werror" | sed -e 's/-fbranch-probabilities//; s/-Wall//; s/-ansi//; s/-pedantic//; s/-Wcheck//'` +fi +AC_TRY_COMPILE( +[#undef inline +#if !defined(SCO) && !defined(__osf__) && !defined(_REENTRANT) +#define _REENTRANT +#endif +#include +#include +#include +#include +#include +#include ], +[int skr; + + skr = gethostbyname_r((const char *) 0, + (struct hostent*) 0, (char*) 0, 0, (struct hostent **) 0, &skr);], +mysql_cv_gethostbyname_style=glibc2, mysql_cv_gethostbyname_style=other)) +AC_LANG_RESTORE +CXXFLAGS="$ac_save_CXXFLAGS" +if test "$mysql_cv_gethostbyname_style" = "glibc2" +then + AC_DEFINE([HAVE_GETHOSTBYNAME_R_GLIBC2_STYLE], [1], + [Solaris define gethostbyname_r with 5 arguments. glibc2 defines this with 6 arguments]) +fi + +# Check 3rd argument of getthostbyname_r +ac_save_CXXFLAGS="$CXXFLAGS" +AC_CACHE_CHECK([3 argument to gethostbyname_r routines], mysql_cv_gethostbyname_arg, +AC_LANG_SAVE +AC_LANG_CPLUSPLUS +if test "$ac_cv_prog_gxx" = "yes" -a "$with_other_libc" = "no" +then + CXXFLAGS=`echo "$CXXFLAGS -Werror" | sed -e 's/-fbranch-probabilities//; s/-Wall//; s/-ansi//; s/-pedantic//; s/-Wcheck//'` +fi +AC_TRY_COMPILE( +[#undef inline +#if !defined(SCO) && !defined(__osf__) && !defined(_REENTRANT) +#define _REENTRANT +#endif +#include +#include +#include +#include +#include +#include ], +[int skr; + + skr = gethostbyname_r((const char *) 0, (struct hostent*) 0, (struct hostent_data*) 0);], +mysql_cv_gethostbyname_arg=hostent_data, mysql_cv_gethostbyname_arg=char)) +AC_LANG_RESTORE +CXXFLAGS="$ac_save_CXXFLAGS" +if test "$mysql_cv_gethostbyname_arg" = "hostent_data" +then + AC_DEFINE([HAVE_GETHOSTBYNAME_R_RETURN_INT], [1], + [In OSF 4.0f the 3'd argument to gethostbyname_r is hostent_data *]) +fi + + +# Check definition of pthread_getspecific +AC_CACHE_CHECK("args to pthread_getspecific", mysql_cv_getspecific_args, +AC_TRY_COMPILE( +[#if !defined(SCO) && !defined(__osf__) && !defined(_REENTRANT) +#define _REENTRANT +#endif +#define _POSIX_PTHREAD_SEMANTICS +#include ], +[ void *pthread_getspecific(pthread_key_t key); +pthread_getspecific((pthread_key_t) NULL); ], +mysql_cv_getspecific_args=POSIX, mysql_cv_getspecific_args=other)) + if test "$mysql_cv_getspecific_args" = "other" + then + AC_DEFINE([HAVE_NONPOSIX_PTHREAD_GETSPECIFIC], [1], + [For some non posix threads]) + fi + + # Check definition of pthread_mutex_init + AC_CACHE_CHECK("args to pthread_mutex_init", mysql_cv_mutex_init_args, + AC_TRY_COMPILE( +[#if !defined(SCO) && !defined(__osf__) +#define _REENTRANT +#endif +#define _POSIX_PTHREAD_SEMANTICS +#include ], +[ + pthread_mutexattr_t attr; + pthread_mutex_t mp; + pthread_mutex_init(&mp,&attr); ], +mysql_cv_mutex_init_args=POSIX, mysql_cv_mutex_init_args=other)) + if test "$mysql_cv_mutex_init_args" = "other" + then + AC_DEFINE([HAVE_NONPOSIX_PTHREAD_MUTEX_INIT], [1], + [For some non posix threads]) + fi +#---END: + +#---START: Used in for client configure +# Check definition of readdir_r +AC_CACHE_CHECK("args to readdir_r", mysql_cv_readdir_r, +AC_TRY_LINK( +[#if !defined(SCO) && !defined(__osf__) +#define _REENTRANT +#endif +#define _POSIX_PTHREAD_SEMANTICS +#include +#include ], +[ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result); +readdir_r((DIR *) NULL, (struct dirent *) NULL, (struct dirent **) NULL); ], +mysql_cv_readdir_r=POSIX, mysql_cv_readdir_r=other)) +if test "$mysql_cv_readdir_r" = "POSIX" +then + AC_DEFINE([HAVE_READDIR_R], [1], [POSIX readdir_r]) +fi + +# Check definition of posix sigwait() +AC_CACHE_CHECK("style of sigwait", mysql_cv_sigwait, +AC_TRY_LINK( +[#if !defined(SCO) && !defined(__osf__) +#define _REENTRANT +#endif +#define _POSIX_PTHREAD_SEMANTICS +#include +#include ], +[#ifndef _AIX +sigset_t set; +int sig; +sigwait(&set,&sig); +#endif], +mysql_cv_sigwait=POSIX, mysql_cv_sigwait=other)) +if test "$mysql_cv_sigwait" = "POSIX" +then + AC_DEFINE([HAVE_SIGWAIT], [1], [POSIX sigwait]) +fi + +if test "$mysql_cv_sigwait" != "POSIX" +then +unset mysql_cv_sigwait +# Check definition of posix sigwait() +AC_CACHE_CHECK("style of sigwait", mysql_cv_sigwait, +AC_TRY_LINK( +[#if !defined(SCO) && !defined(__osf__) +#define _REENTRANT +#endif +#define _POSIX_PTHREAD_SEMANTICS +#include +#include ], +[sigset_t set; +int sig; +sigwait(&set);], +mysql_cv_sigwait=NONPOSIX, mysql_cv_sigwait=other)) +if test "$mysql_cv_sigwait" = "NONPOSIX" +then + AC_DEFINE([HAVE_NONPOSIX_SIGWAIT], [1], [sigwait with one argument]) +fi +fi +#---END: + +# Check if pthread_attr_setscope() exists +AC_CACHE_CHECK("for pthread_attr_setscope", mysql_cv_pthread_attr_setscope, +AC_TRY_LINK( +[#if !defined(SCO) && !defined(__osf__) +#define _REENTRANT +#endif +#define _POSIX_PTHREAD_SEMANTICS +#include ], +[pthread_attr_t thr_attr; +pthread_attr_setscope(&thr_attr,0);], +mysql_cv_pthread_attr_setscope=yes, mysql_cv_pthread_attr_setscope=no)) +if test "$mysql_cv_pthread_attr_setscope" = "yes" +then + AC_DEFINE([HAVE_PTHREAD_ATTR_SETSCOPE], [1], [pthread_attr_setscope]) +fi + +# Check for bad includes +AC_MSG_CHECKING("can netinet files be included") +AC_TRY_COMPILE( +[#include +#include +#include +#include +#include +#include ], +[ printf("1\n"); ], +netinet_inc=yes, netinet_inc=no) +if test "$netinet_inc" = "no" +then + AC_DEFINE([HAVE_BROKEN_NETINET_INCLUDES], [1], [Can netinet be included]) +fi +AC_MSG_RESULT("$netinet_inc") + +AC_CACHE_CHECK([support for weak symbols], mysql_cv_weak_symbol, +[AC_TRY_LINK([],[ + extern void __attribute__((weak)) foo(void); +], [mysql_cv_weak_symbol=yes], [mysql_cv_weak_symbol=no])]) + +if test "x$mysql_cv_weak_symbol" = xyes; then + AC_DEFINE(HAVE_WEAK_SYMBOL, 1, + [Define to 1 if compiler supports weak symbol attribute.]) +fi + +AC_CACHE_CHECK([whether __bss_start is defined], mysql_cv_bss_start, +[AC_TRY_LINK([],[ + extern char *__bss_start; + return __bss_start ? 1 : 0; +], [mysql_cv_bss_start=yes], [mysql_cv_bss_start=no])]) + +if test "x$mysql_cv_bss_start" = xyes; then + AC_DEFINE(HAVE_BSS_START, 1, + [Define to 1 if compiler defines __bss_start.]) +fi + +AC_LANG_SAVE +AC_LANG_CPLUSPLUS +AC_CHECK_HEADERS(cxxabi.h) +AC_CACHE_CHECK([for abi::__cxa_demangle], mysql_cv_cxa_demangle, +[AC_TRY_LINK([#include ], [ + char *foo= 0; int bar= 0; + foo= abi::__cxa_demangle(foo, foo, 0, &bar); +], [mysql_cv_cxa_demangle=yes], [mysql_cv_cxa_demangle=no])]) +AC_LANG_RESTORE + +if test "x$mysql_cv_cxa_demangle" = xyes; then + AC_DEFINE(HAVE_ABI_CXA_DEMANGLE, 1, + [Define to 1 if you have the `abi::__cxa_demangle' function.]) +fi + +#-------------------------------------------------------------------- +# Check for requested features +#-------------------------------------------------------------------- + +MYSQL_CHECK_BIG_TABLES +MYSQL_CHECK_MAX_INDEXES +MYSQL_CHECK_VIO +MYSQL_CHECK_SSL + +#-------------------------------------------------------------------- +# Declare our plugin modules +# Has to be done late, as the plugin may need to check for existence of +# functions tested above +#-------------------------------------------------------------------- + +MYSQL_STORAGE_ENGINE(partition, partition, [Partition Support], + [MySQL Partitioning Support], [max,max-no-ndb]) + +dnl -- ndbcluster requires partition to be enabled + +MYSQL_CONFIGURE_PLUGINS([none]) + +# Only build client code? +AC_ARG_WITH(server, + [ --without-server Only build the client.], + [with_server=$withval], + [with_server=yes] +) + +AC_ARG_WITH(embedded-server, + [ --with-embedded-server Build the embedded server (libmysqld).], + [with_embedded_server=$withval], + [with_embedded_server=no] +) + +AC_ARG_WITH(query_cache, + [ --without-query-cache Do not build query cache.], + [with_query_cache=$withval], + [with_query_cache=yes] +) + +if test "$with_query_cache" = "yes" +then + AC_DEFINE([HAVE_QUERY_CACHE], [1], [If we want to have query cache]) +fi + +AC_ARG_WITH(geometry, + [ --without-geometry Do not build geometry-related parts.], + [with_geometry=$withval], + [with_geometry=yes] +) + +if test "$with_geometry" = "yes" +then + AC_DEFINE([HAVE_SPATIAL], [1], [Spatial extentions]) + AC_DEFINE([HAVE_RTREE_KEYS], [1], [RTree keys]) +fi + +AC_ARG_WITH(embedded_privilege_control, + [ --with-embedded-privilege-control + Build parts to check user's privileges. + Only affects embedded library.], + [with_embedded_privilege_control=$withval], + [with_embedded_privilege_control=no] +) + +if test "$with_embedded_privilege_control" = "yes" +then + AC_DEFINE([HAVE_EMBEDDED_PRIVILEGE_CONTROL], [1], + [Access checks in embedded library]) +fi + +tools_dirs="" + +AC_ARG_WITH([mysqlmanager], + AC_HELP_STRING([--with-mysqlmanager], [Build the mysqlmanager binary: yes/no (default: build if server is built.)]),,) + +if test "$with_mysqlmanager" = "yes" -o \ + '(' "$with_mysqlmanager:$with_server" = ":yes" -a \ + -d "$srcdir/server-tools" ')' ; then + tools_dirs="server-tools" +fi + +AC_SUBST(tools_dirs) + +#MYSQL_CHECK_CPU + +libmysqld_dirs= +if test "$with_embedded_server" = "yes" +then + libmysqld_dirs=libmysqld + + # We can't build embedded library without building the server, because + # we depend on libmysys, libmystrings, libmyisam, etc. + with_server=yes +fi +# XXX: We need to add @libmysqld_extra_libs@ (or whatever) so that +# mysql_config --libmysqld-libs will print out something like +# -L/path/to/lib/mysql -lmysqld -lmyisam -lmysys -lmystrings -ldbug ... +AC_SUBST([libmysqld_dirs]) + +# Shall we build the docs? +AC_ARG_WITH(docs, + [ --without-docs Skip building of the documentation.], + [with_docs=$withval], + [with_docs=yes] +) + +if test "$with_docs" = "yes" +then + docs_dirs="Docs" + if test -f "$srcdir/Docs/manual.chm" ; then + extra_docs="manual.chm" + fi +else + docs_dirs="" + extra_docs="" +fi +AC_SUBST(docs_dirs) +AC_SUBST(extra_docs) + +# Shall we build the man pages? +AC_ARG_WITH(man, + [ --without-man Skip building of the man pages.], + [with_man=$withval], + [with_man=yes] +) + +# Don't build readline, i have it already +AC_ARG_WITH(readline, + [ --without-readline Use system readline instead of bundled copy.], + [ with_readline=$withval ], + [ with_readline=undefined ] + ) + +AC_ARG_WITH(libedit, + [ --without-libedit Use system libedit instead of bundled copy.], + [ with_libedit=$withval ], + [ with_libedit=undefined ] + ) + +if test "$with_readline/$with_libedit" = "undefined/undefined" -a ! -e "$srcdir/cmd-line-utils" +then + with_readline=no + with_libedit=no +fi + +# +# We support next variants of compilation: +# --with-readline +# | yes | no | undefined +# --with-libedit | | | +# ---------------+----------------+------+---------------------------------- +# yes | ERROR! | use libedit from mysql sources +# ---------------+----------------+------+---------------------------------- +# no | use readline | use system readline or external libedit +# | from mysql | according to results of m4 tests +# ---------------+ sources (if it + +---------------------------------- +# undefined | is presented) | | use libedit from mysql sources + + +compile_readline="no" +compile_libedit="no" + +if [test "$with_libedit" = "yes"] && [test "$with_readline" = "yes"] +then + AC_MSG_ERROR([You can not use --with-readline and --with-libedit at the same time, please choose one of it]) +fi + +readline_topdir="" +readline_basedir="" +readline_dir="" +readline_h_ln_cmd="" +readline_link="" +want_to_use_readline="no" + +case $SYSTEM_TYPE in + *netware*) + # For NetWare, do not need readline + echo "Skipping readline" + ;; + *) + if [test "$with_libedit" = "yes"] || [test "$with_libedit" = "undefined"] && [test "$with_readline" = "undefined"] + then + readline_topdir="cmd-line-utils" + readline_basedir="libedit" + readline_dir="$readline_topdir/$readline_basedir" + readline_link="\$(top_builddir)/cmd-line-utils/libedit/libedit.a" + readline_h_ln_cmd="\$(LN) -s \$(top_srcdir)/cmd-line-utils/libedit/readline readline" + compile_libedit=yes + AC_DEFINE_UNQUOTED(HAVE_HIST_ENTRY, 1) + AC_DEFINE_UNQUOTED(USE_LIBEDIT_INTERFACE, 1) + elif test "$with_readline" = "yes" + then + readline_topdir="cmd-line-utils" + readline_basedir="readline" + readline_dir="$readline_topdir/$readline_basedir" + readline_link="\$(top_builddir)/cmd-line-utils/readline/libreadline.a" + readline_h_ln_cmd="\$(LN) -s \$(top_srcdir)/cmd-line-utils/readline readline" + compile_readline=yes + want_to_use_readline="yes" + AC_DEFINE_UNQUOTED(USE_NEW_READLINE_INTERFACE, 1) + else + # Use system readline library + AC_LANG_SAVE + AC_LANG_CPLUSPLUS + MYSQL_CHECK_LIBEDIT_INTERFACE + MYSQL_CHECK_NEW_RL_INTERFACE + MYSQL_CHECK_READLINE_DECLARES_HIST_ENTRY + AC_LANG_RESTORE + if [test "$mysql_cv_new_rl_interface" = "yes"] && [test -d "$srcdir/cmd-line-utils/readline"] + then + # Use the new readline interface, but only if the package includes a bundled libreadline + # this way we avoid linking commercial source with GPL readline + readline_link="-lreadline" + want_to_use_readline="yes" + elif [test "$mysql_cv_libedit_interface" = "yes"] + then + # Use libedit + readline_link="-ledit" + else + AC_MSG_ERROR([Could not find system readline or libedit libraries + Use --with-readline or --with-libedit to use the bundled + versions of libedit or readline]) + fi + fi + + # if there is no readline, but we want to build with readline, we fail + if [test "$want_to_use_readline" = "yes"] && [test ! -d "./cmd-line-utils/readline"] + then + AC_MSG_ERROR([This commercially licensed MySQL source package can't + be built with libreadline. Please use --with-libedit to use + the bundled version of libedit instead.]) + fi + ;; +esac + +AC_SUBST(readline_dir) +AC_SUBST(readline_topdir) +AC_SUBST(readline_basedir) +AC_SUBST(readline_link) +AC_SUBST(readline_h_ln_cmd) + + + +# Include man pages, if desired, adapted to the configured parts. +if test X"$with_man" = Xyes +then + # First, create the list of all man pages present. + MANLISTFIL=manlist.$$ + TMPLISTFIL=`echo $MANLISTFIL | sed -e 's/manlist/tmplist/'` + if test -f $MANLISTFIL -o -f $TMPLISTFIL + then + echo "Temp file '$MANLISTFIL' or '$TMPLISTFIL' already exists in '`pwd`' - aborting" + exit 1 + fi + touch $MANLISTFIL $TMPLISTFIL + + ls $srcdir/man/*.[[18]] > $MANLISTFIL + + # Then, remove all those pages from the list which are specific to parts + # (table handlers, features, ...) which are not configured in this run. + AC_MSG_CHECKING("for man pages to remove") + MAN_DROP="dropping" + if test X"$with_plugin_ndbcluster" != Xyes + then + MAN_DROP="$MAN_DROP ndbcluster" + grep -v '/ndb' $MANLISTFIL > $TMPLISTFIL ; mv -f $TMPLISTFIL $MANLISTFIL + fi + if test X"$with_embedded_server" != Xyes + then + MAN_DROP="$MAN_DROP embedded" + grep -v 'embedded' $MANLISTFIL > $TMPLISTFIL ; mv -f $TMPLISTFIL $MANLISTFIL + fi + if test X"$with_plugin_innobase" != Xyes + then + MAN_DROP="$MAN_DROP innodb" + grep -v 'inno' $MANLISTFIL > $TMPLISTFIL ; mv -f $TMPLISTFIL $MANLISTFIL + fi + AC_MSG_RESULT([$MAN_DROP]) + + # Finally, split the man pages into sections 1 and 8. + # Get rid of line breaks. + man1_files=`sed -n -e '/\.1$/s/^.*man\///p' <$MANLISTFIL` + man8_files=`sed -n -e '/\.8$/s/^.*man\///p' <$MANLISTFIL` + + man_dirs="man" + man1_files=`echo $man1_files` + man8_files=`echo $man8_files` + rm -f $MANLISTFIL $TMPLISTFIL +else + man_dirs="" + man1_files="" + man8_files="" +fi +AC_SUBST(man_dirs) +AC_SUBST(man1_files) +AC_SUBST(man8_files) + +# If we have threads generate some library functions and test programs +sql_server_dirs= +sql_server= +server_scripts= + +dnl This probably should be cleaned up more - for now the threaded +dnl client is just using plain-old libs. +sql_client_dirs="strings regex mysys libmysql" + +AM_CONDITIONAL(THREAD_SAFE_CLIENT, test "$THREAD_SAFE_CLIENT" != "no") + +if test "$THREAD_SAFE_CLIENT" != "no" +then + sql_client_dirs="$sql_client_dirs libmysql_r" + AC_DEFINE([THREAD_SAFE_CLIENT], [1], [Should the client be thread safe]) +fi +sql_client_dirs="$sql_client_dirs client" + +CLIENT_LIBS="$NON_THREADED_LIBS $openssl_libs $ZLIB_LIBS $STATIC_NSS_FLAGS" + +AC_SUBST(CLIENT_LIBS) +AC_SUBST(CLIENT_THREAD_LIBS) +AC_SUBST(NON_THREADED_LIBS) +AC_SUBST(STATIC_NSS_FLAGS) +AC_SUBST(sql_client_dirs) + +# If configuring for NetWare, build the netware directory +netware_dir= +if expr "$SYSTEM_TYPE" : ".*netware.*" > /dev/null +then + netware_dir="netware" +fi +AC_SUBST(netware_dir) +AM_CONDITIONAL(HAVE_NETWARE, test "$netware_dir" = "netware") + +if test "$with_server" = "yes" -o "$THREAD_SAFE_CLIENT" != "no" +then + AC_DEFINE([THREAD], [1], + [Define if you want to have threaded code. This may be undef on client code]) + # Avoid _PROGRAMS names + THREAD_LOBJECTS="thr_alarm.o thr_lock.o thr_mutex.o thr_rwlock.o my_pthread.o my_thr_init.o mf_keycache.o" + AC_SUBST(THREAD_LOBJECTS) + server_scripts="mysqld_safe mysql_install_db" + sql_server_dirs="strings mysys dbug extra regex" + + sql_server="vio sql" +fi + +# "innochecksum" is not in the "innobase/" subdirectory, but should be switched +AM_CONDITIONAL([BUILD_INNODB_TOOLS], [test X"$with_plugin_innobase" = Xyes]) + +# IMPORTANT - do not modify LIBS past this line - this hack is the only way +# I know to add the static NSS magic if we have static NSS libraries with +# glibc - Sasha + +LDFLAGS="$LDFLAGS $OTHER_LIBC_LIB" +LIBS="$LIBS $STATIC_NSS_FLAGS" + +AC_SUBST(sql_server_dirs) +AC_SUBST(sql_server) +AC_SUBST(server_scripts) + +AC_SUBST(mysql_plugin_dirs) +AC_SUBST(mysql_plugin_libs) +AC_SUBST(mysql_plugin_defs) + + +# Now that sql_client_dirs and sql_server_dirs are stable, determine the union. +# Start with the (longer) server list, add each client item not yet present. +sql_union_dirs=" $sql_server_dirs " +for DIR in $sql_client_dirs +do + if echo " $sql_union_dirs " | grep " $DIR " >/dev/null + then + : # already present, skip + else + sql_union_dirs="$sql_union_dirs $DIR " + fi +done +AC_SUBST(sql_union_dirs) + +# Some usefull subst +AC_SUBST(CC) +AC_SUBST(GXX) + +# Set configuration options for make_binary_distribution +case $SYSTEM_TYPE in + *netware*) + MAKE_BINARY_DISTRIBUTION_OPTIONS="$MAKE_BINARY_DISTRIBUTION_OPTIONS --no-strip" + ;; + *) + : # no change for other platforms yet + ;; +esac +AC_SUBST(MAKE_BINARY_DISTRIBUTION_OPTIONS) + +# Output results +if test -d "$srcdir/pstack" ; then + AC_CONFIG_FILES(pstack/Makefile pstack/aout/Makefile) +fi +if test -d "$srcdir/cmd-line-utils/readline" ; then + AC_CONFIG_FILES(cmd-line-utils/readline/Makefile) +fi + +AC_CONFIG_FILES(Makefile extra/Makefile mysys/Makefile dnl + unittest/Makefile unittest/mytap/Makefile unittest/mytap/t/Makefile dnl + unittest/mysys/Makefile unittest/examples/Makefile dnl + strings/Makefile regex/Makefile storage/Makefile dnl + man/Makefile BUILD/Makefile vio/Makefile dnl + libmysql/Makefile libmysql_r/Makefile client/Makefile dnl + sql/Makefile sql/share/Makefile dnl + sql/sql_builtin.cc sql-common/Makefile dnl + dbug/Makefile scripts/Makefile include/Makefile dnl + tests/Makefile Docs/Makefile support-files/Makefile dnl + support-files/MacOSX/Makefile support-files/RHEL4-SElinux/Makefile dnl + server-tools/Makefile server-tools/instance-manager/Makefile dnl + cmd-line-utils/Makefile cmd-line-utils/libedit/Makefile dnl + libmysqld/Makefile libmysqld/examples/Makefile dnl + mysql-test/Makefile mysql-test/lib/My/SafeProcess/Makefile dnl + netware/Makefile sql-bench/Makefile dnl + include/mysql_version.h plugin/Makefile win/Makefile) + +AC_CONFIG_COMMANDS([default], , test -z "$CONFIG_HEADERS" || echo timestamp > stamp-h) + +# Ensure that table handlers gets all modifications to CFLAGS/CXXFLAGS +AC_CONFIG_COMMANDS_POST(ac_configure_args="$ac_configure_args CFLAGS='$CFLAGS' CXXFLAGS='$CXXFLAGS'") + +AC_OUTPUT + +echo +echo "MySQL has a Web site at http://www.mysql.com/ which carries details on the" +echo "latest release, upcoming features, and other information to make your" +echo "work or play with MySQL more productive. There you can also find" +echo "information about mailing lists for MySQL discussion." +echo +echo "Remember to check the platform specific part of the reference manual for" +echo "hints about installing MySQL on your platform. Also have a look at the" +echo "files in the Docs directory." +echo +# The following text is checked in ./Do-compile to verify that configure +# ended sucessfully - don't remove it. +echo "Thank you for choosing MySQL!" +echo diff --git a/dbcon/mysql/field.h b/dbcon/mysql/field.h new file mode 100644 index 00000000..02e50b29 --- /dev/null +++ b/dbcon/mysql/field.h @@ -0,0 +1,2182 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Because of the function new_field() all field classes that have static + variables must declare the size_of() member function. +*/ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +#define NOT_FIXED_DEC 31 +#define DATETIME_DEC 6 +const uint32 max_field_size= (uint32) 4294967295U; + +class Send_field; +class Protocol; +class Create_field; +class Relay_log_info; + +struct st_cache_field; +int field_conv(Field *to,Field *from); + +inline uint get_enum_pack_length(int elements) +{ + return elements < 256 ? 1 : 2; +} + +inline uint get_set_pack_length(int elements) +{ + uint len= (elements + 7) / 8; + return len > 4 ? 8 : len; +} + +class Field +{ + Field(const Item &); /* Prevent use of these */ + void operator=(Field &); +public: + static void *operator new(size_t size) throw () + { return sql_alloc(size); } + static void operator delete(void *ptr_arg, size_t size) { TRASH(ptr_arg, size); } + + uchar *ptr; // Position to field in record + uchar *null_ptr; // Byte where null_bit is + /* + Note that you can use table->in_use as replacement for current_thd member + only inside of val_*() and store() members (e.g. you can't use it in cons) + */ + struct st_table *table; // Pointer for table + struct st_table *orig_table; // Pointer to original table + const char **table_name, *field_name; + LEX_STRING comment; + /* Field is part of the following keys */ + key_map key_start, part_of_key, part_of_key_not_clustered; + key_map part_of_sortkey; + /* + We use three additional unireg types for TIMESTAMP to overcome limitation + of current binary format of .frm file. We'd like to be able to support + NOW() as default and on update value for such fields but unable to hold + this info anywhere except unireg_check field. This issue will be resolved + in more clean way with transition to new text based .frm format. + See also comment for Field_timestamp::Field_timestamp(). + */ + enum utype { NONE,DATE,SHIELD,NOEMPTY,CASEUP,PNR,BGNR,PGNR,YES,NO,REL, + CHECK,EMPTY,UNKNOWN_FIELD,CASEDN,NEXT_NUMBER,INTERVAL_FIELD, + BIT_FIELD, TIMESTAMP_OLD_FIELD, CAPITALIZE, BLOB_FIELD, + TIMESTAMP_DN_FIELD, TIMESTAMP_UN_FIELD, TIMESTAMP_DNUN_FIELD}; + enum geometry_type + { + GEOM_GEOMETRY = 0, GEOM_POINT = 1, GEOM_LINESTRING = 2, GEOM_POLYGON = 3, + GEOM_MULTIPOINT = 4, GEOM_MULTILINESTRING = 5, GEOM_MULTIPOLYGON = 6, + GEOM_GEOMETRYCOLLECTION = 7 + }; + enum imagetype { itRAW, itMBR}; + + utype unireg_check; + uint32 field_length; // Length of field + uint32 flags; + uint16 field_index; // field number in fields array + uchar null_bit; // Bit used to test null bit + /** + If true, this field was created in create_tmp_field_from_item from a NULL + value. This means that the type of the field is just a guess, and the type + may be freely coerced to another type. + + @see create_tmp_field_from_item + @see Item_type_holder::get_real_type + + */ + bool is_created_from_null_item; + + Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg, + uchar null_bit_arg, utype unireg_check_arg, + const char *field_name_arg); + virtual ~Field() {} + /* Store functions returns 1 on overflow and -1 on fatal error */ + virtual int store(const char *to, uint length,CHARSET_INFO *cs)=0; + virtual int store(double nr)=0; + virtual int store(longlong nr, bool unsigned_val)=0; + virtual int store_decimal(const my_decimal *d)=0; + virtual int store_time(MYSQL_TIME *ltime, timestamp_type t_type); + int store(const char *to, uint length, CHARSET_INFO *cs, + enum_check_fields check_level); + virtual double val_real(void)=0; + virtual longlong val_int(void)=0; + virtual my_decimal *val_decimal(my_decimal *); + inline String *val_str(String *str) { return val_str(str, str); } + /* + val_str(buf1, buf2) gets two buffers and should use them as follows: + if it needs a temp buffer to convert result to string - use buf1 + example Field_tiny::val_str() + if the value exists as a string already - use buf2 + example Field_string::val_str() + consequently, buf2 may be created as 'String buf;' - no memory + will be allocated for it. buf1 will be allocated to hold a + value if it's too small. Using allocated buffer for buf2 may result in + an unnecessary free (and later, may be an alloc). + This trickery is used to decrease a number of malloc calls. + */ + virtual String *val_str(String*,String *)=0; + String *val_int_as_str(String *val_buffer, my_bool unsigned_flag); + /* + str_needs_quotes() returns TRUE if the value returned by val_str() needs + to be quoted when used in constructing an SQL query. + */ + virtual bool str_needs_quotes() { return FALSE; } + virtual Item_result result_type () const=0; + virtual Item_result cmp_type () const { return result_type(); } + virtual Item_result cast_to_int_type () const { return result_type(); } + static bool type_can_have_key_part(enum_field_types); + static enum_field_types field_type_merge(enum_field_types, enum_field_types); + static Item_result result_merge_type(enum_field_types); + virtual bool eq(Field *field) + { + return (ptr == field->ptr && null_ptr == field->null_ptr && + null_bit == field->null_bit && field->type() == type()); + } + virtual bool eq_def(Field *field); + + /* + pack_length() returns size (in bytes) used to store field data in memory + (i.e. it returns the maximum size of the field in a row of the table, + which is located in RAM). + */ + virtual uint32 pack_length() const { return (uint32) field_length; } + + /* + pack_length_in_rec() returns size (in bytes) used to store field data on + storage (i.e. it returns the maximal size of the field in a row of the + table, which is located on disk). + */ + virtual uint32 pack_length_in_rec() const { return pack_length(); } + virtual int compatible_field_size(uint field_metadata, + const Relay_log_info *); + virtual uint pack_length_from_metadata(uint field_metadata) + { return field_metadata; } + /* + This method is used to return the size of the data in a row-based + replication row record. The default implementation of returning 0 is + designed to allow fields that do not use metadata to return TRUE (1) + from compatible_field_size() which uses this function in the comparison. + The default value for field metadata for fields that do not have + metadata is 0. Thus, 0 == 0 means the fields are compatible in size. + + Note: While most classes that override this method return pack_length(), + the classes Field_string, Field_varstring, and Field_blob return + field_length + 1, field_length, and pack_length_no_ptr() respectfully. + */ + virtual uint row_pack_length() { return 0; } + virtual int save_field_metadata(uchar *first_byte) + { return do_save_field_metadata(first_byte); } + + /* + data_length() return the "real size" of the data in memory. + */ + virtual uint32 data_length() { return pack_length(); } + virtual uint32 sort_length() const { return pack_length(); } + + /** + Get the maximum size of the data in packed format. + + @return Maximum data length of the field when packed using the + Field::pack() function. + */ + virtual uint32 max_data_length() const { + return pack_length(); + }; + + virtual int reset(void) { bzero(ptr,pack_length()); return 0; } + virtual void reset_fields() {} + virtual void set_default() + { + my_ptrdiff_t l_offset= (my_ptrdiff_t) (table->s->default_values - + table->record[0]); + memcpy(ptr, ptr + l_offset, pack_length()); + if (null_ptr) + *null_ptr= ((*null_ptr & (uchar) ~null_bit) | + (null_ptr[l_offset] & null_bit)); + } + virtual bool binary() const { return 1; } + virtual bool zero_pack() const { return 1; } + virtual enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; } + virtual uint32 key_length() const { return pack_length(); } + virtual enum_field_types type() const =0; + virtual enum_field_types real_type() const { return type(); } + inline int cmp(const uchar *str) { return cmp(ptr,str); } + virtual int cmp_max(const uchar *a, const uchar *b, uint max_len) + { return cmp(a, b); } + virtual int cmp(const uchar *,const uchar *)=0; + virtual int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0L) + { return memcmp(a,b,pack_length()); } + virtual int cmp_offset(uint row_offset) + { return cmp(ptr,ptr+row_offset); } + virtual int cmp_binary_offset(uint row_offset) + { return cmp_binary(ptr, ptr+row_offset); }; + virtual int key_cmp(const uchar *a,const uchar *b) + { return cmp(a, b); } + virtual int key_cmp(const uchar *str, uint length) + { return cmp(ptr,str); } + virtual uint decimals() const { return 0; } + /* + Caller beware: sql_type can change str.Ptr, so check + ptr() to see if it changed if you are using your own buffer + in str and restore it with set() if needed + */ + virtual void sql_type(String &str) const =0; + virtual uint size_of() const =0; // For new field + inline bool is_null(my_ptrdiff_t row_offset= 0) + { return null_ptr ? (null_ptr[row_offset] & null_bit ? 1 : 0) : table->null_row; } + inline bool is_real_null(my_ptrdiff_t row_offset= 0) + { return null_ptr ? (null_ptr[row_offset] & null_bit ? 1 : 0) : 0; } + inline bool is_null_in_record(const uchar *record) + { + if (!null_ptr) + return 0; + return test(record[(uint) (null_ptr -table->record[0])] & + null_bit); + } + inline bool is_null_in_record_with_offset(my_ptrdiff_t offset) + { + if (!null_ptr) + return 0; + return test(null_ptr[offset] & null_bit); + } + inline void set_null(my_ptrdiff_t row_offset= 0) + { if (null_ptr) null_ptr[row_offset]|= null_bit; } + inline void set_notnull(my_ptrdiff_t row_offset= 0) + { if (null_ptr) null_ptr[row_offset]&= (uchar) ~null_bit; } + inline bool maybe_null(void) { return null_ptr != 0 || table->maybe_null; } + inline bool real_maybe_null(void) { return null_ptr != 0; } + + enum { + LAST_NULL_BYTE_UNDEF= 0 + }; + + /* + Find the position of the last null byte for the field. + + SYNOPSIS + last_null_byte() + + DESCRIPTION + Return a pointer to the last byte of the null bytes where the + field conceptually is placed. + + RETURN VALUE + The position of the last null byte relative to the beginning of + the record. If the field does not use any bits of the null + bytes, the value 0 (LAST_NULL_BYTE_UNDEF) is returned. + */ + size_t last_null_byte() const { + size_t bytes= do_last_null_byte(); + DBUG_PRINT("debug", ("last_null_byte() ==> %ld", (long) bytes)); + DBUG_ASSERT(bytes <= table->s->null_bytes); + return bytes; + } + + virtual void make_field(Send_field *); + virtual void sort_string(uchar *buff,uint length)=0; + virtual bool optimize_range(uint idx, uint part); + /* + This should be true for fields which, when compared with constant + items, can be casted to longlong. In this case we will at 'fix_fields' + stage cast the constant items to longlongs and at the execution stage + use field->val_int() for comparison. Used to optimize clauses like + 'a_column BETWEEN date_const, date_const'. + */ + virtual bool can_be_compared_as_longlong() const { return FALSE; } + virtual void free() {} + virtual Field *new_field(MEM_ROOT *root, struct st_table *new_table, + bool keep_type); + virtual Field *new_key_field(MEM_ROOT *root, struct st_table *new_table, + uchar *new_ptr, uchar *new_null_ptr, + uint new_null_bit); + Field *clone(MEM_ROOT *mem_root, struct st_table *new_table); + inline void move_field(uchar *ptr_arg,uchar *null_ptr_arg,uchar null_bit_arg) + { + ptr=ptr_arg; null_ptr=null_ptr_arg; null_bit=null_bit_arg; + } + inline void move_field(uchar *ptr_arg) { ptr=ptr_arg; } + virtual void move_field_offset(my_ptrdiff_t ptr_diff) + { + ptr=ADD_TO_PTR(ptr,ptr_diff, uchar*); + if (null_ptr) + null_ptr=ADD_TO_PTR(null_ptr,ptr_diff,uchar*); + } + virtual void get_image(uchar *buff, uint length, CHARSET_INFO *cs) + { memcpy(buff,ptr,length); } + virtual void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) + { memcpy(ptr,buff,length); } + + + /* + Copy a field part into an output buffer. + + SYNOPSIS + Field::get_key_image() + buff [out] output buffer + length output buffer size + type itMBR for geometry blobs, otherwise itRAW + + DESCRIPTION + This function makes a copy of field part of size equal to or + less than "length" parameter value. + For fields of string types (CHAR, VARCHAR, TEXT) the rest of buffer + is padded by zero byte. + + NOTES + For variable length character fields (i.e. UTF-8) the "length" + parameter means a number of output buffer bytes as if all field + characters have maximal possible size (mbmaxlen). In the other words, + "length" parameter is a number of characters multiplied by + field_charset->mbmaxlen. + + RETURN + Number of copied bytes (excluding padded zero bytes -- see above). + */ + + virtual uint get_key_image(uchar *buff, uint length, imagetype type) + { + get_image(buff, length, &my_charset_bin); + return length; + } + virtual void set_key_image(const uchar *buff,uint length) + { set_image(buff,length, &my_charset_bin); } + inline longlong val_int_offset(uint row_offset) + { + ptr+=row_offset; + longlong tmp=val_int(); + ptr-=row_offset; + return tmp; + } + inline longlong val_int(const uchar *new_ptr) + { + uchar *old_ptr= ptr; + longlong return_value; + ptr= (uchar*) new_ptr; + return_value= val_int(); + ptr= old_ptr; + return return_value; + } + inline String *val_str(String *str, const uchar *new_ptr) + { + uchar *old_ptr= ptr; + ptr= (uchar*) new_ptr; + val_str(str); + ptr= old_ptr; + return str; + } + virtual bool send_binary(Protocol *protocol); + + virtual uchar *pack(uchar *to, const uchar *from, + uint max_length, bool low_byte_first); + /** + @overload Field::pack(uchar*, const uchar*, uint, bool) + */ + uchar *pack(uchar *to, const uchar *from) + { + DBUG_ENTER("Field::pack"); + uchar *result= this->pack(to, from, UINT_MAX, table->s->db_low_byte_first); + DBUG_RETURN(result); + } + + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first); + /** + @overload Field::unpack(uchar*, const uchar*, uint, bool) + */ + const uchar *unpack(uchar* to, const uchar *from) + { + DBUG_ENTER("Field::unpack"); + const uchar *result= unpack(to, from, 0U, table->s->db_low_byte_first); + DBUG_RETURN(result); + } + + virtual uchar *pack_key(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + return pack(to, from, max_length, low_byte_first); + } + virtual uchar *pack_key_from_key_image(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + return pack(to, from, max_length, low_byte_first); + } + virtual const uchar *unpack_key(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + return unpack(to, from, max_length, low_byte_first); + } + virtual uint packed_col_length(const uchar *to, uint length) + { return length;} + virtual uint max_packed_col_length(uint max_length) + { return max_length;} + + virtual int pack_cmp(const uchar *a,const uchar *b, uint key_length_arg, + my_bool insert_or_update) + { return cmp(a,b); } + virtual int pack_cmp(const uchar *b, uint key_length_arg, + my_bool insert_or_update) + { return cmp(ptr,b); } + uint offset(uchar *record) + { + return (uint) (ptr - record); + } + void copy_from_tmp(int offset); + uint fill_cache_field(struct st_cache_field *copy); + virtual bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + virtual bool get_time(MYSQL_TIME *ltime); + virtual CHARSET_INFO *charset(void) const { return &my_charset_bin; } + virtual CHARSET_INFO *sort_charset(void) const { return charset(); } + virtual bool has_charset(void) const { return FALSE; } + virtual void set_charset(CHARSET_INFO *charset_arg) { } + virtual enum Derivation derivation(void) const + { return DERIVATION_IMPLICIT; } + virtual void set_derivation(enum Derivation derivation_arg) { } + bool set_warning(MYSQL_ERROR::enum_warning_level, unsigned int code, + int cuted_increment); + void set_datetime_warning(MYSQL_ERROR::enum_warning_level, uint code, + const char *str, uint str_len, + timestamp_type ts_type, int cuted_increment); + void set_datetime_warning(MYSQL_ERROR::enum_warning_level, uint code, + longlong nr, timestamp_type ts_type, + int cuted_increment); + void set_datetime_warning(MYSQL_ERROR::enum_warning_level, const uint code, + double nr, timestamp_type ts_type); + inline bool check_overflow(int op_result) + { + return (op_result == E_DEC_OVERFLOW); + } + int warn_if_overflow(int op_result); + void init(TABLE *table_arg) + { + orig_table= table= table_arg; + table_name= &table_arg->alias; + } + + /* maximum possible display length */ + virtual uint32 max_display_length()= 0; + + virtual uint is_equal(Create_field *new_field); + /* convert decimal to longlong with overflow check */ + longlong convert_decimal2longlong(const my_decimal *val, bool unsigned_flag, + int *err); + /* The max. number of characters */ + inline uint32 char_length() const + { + return field_length / charset()->mbmaxlen; + } + + virtual geometry_type get_geometry_type() + { + /* shouldn't get here. */ + DBUG_ASSERT(0); + return GEOM_GEOMETRY; + } + /* Hash value */ + virtual void hash(ulong *nr, ulong *nr2); + friend bool reopen_table(THD *,struct st_table *,bool); + friend int cre_myisam(char * name, register TABLE *form, uint options, + ulonglong auto_increment_value); + friend class Copy_field; + friend class Item_avg_field; + friend class Item_std_field; + friend class Item_sum_num; + friend class Item_sum_sum; + friend class Item_sum_str; + friend class Item_sum_count; + friend class Item_sum_avg; + friend class Item_sum_std; + friend class Item_sum_min; + friend class Item_sum_max; + friend class Item_func_group_concat; + +private: + /* + Primitive for implementing last_null_byte(). + + SYNOPSIS + do_last_null_byte() + + DESCRIPTION + Primitive for the implementation of the last_null_byte() + function. This represents the inheritance interface and can be + overridden by subclasses. + */ + virtual size_t do_last_null_byte() const; + +/** + Retrieve the field metadata for fields. + + This default implementation returns 0 and saves 0 in the metadata_ptr + value. + + @param metadata_ptr First byte of field metadata + + @returns 0 no bytes written. +*/ + virtual int do_save_field_metadata(uchar *metadata_ptr) + { return 0; } + +protected: + /* + Helper function to pack()/unpack() int32 values + */ + static void handle_int32(uchar *to, const uchar *from, + bool low_byte_first_from, bool low_byte_first_to) + { + int32 val; +#ifdef WORDS_BIGENDIAN + if (low_byte_first_from) + val = sint4korr(from); + else +#endif + longget(val, from); + +#ifdef WORDS_BIGENDIAN + if (low_byte_first_to) + int4store(to, val); + else +#endif + longstore(to, val); + } + + /* + Helper function to pack()/unpack() int64 values + */ + static void handle_int64(uchar* to, const uchar *from, + bool low_byte_first_from, bool low_byte_first_to) + { + int64 val; +#ifdef WORDS_BIGENDIAN + if (low_byte_first_from) + val = sint8korr(from); + else +#endif + longlongget(val, from); + +#ifdef WORDS_BIGENDIAN + if (low_byte_first_to) + int8store(to, val); + else +#endif + longlongstore(to, val); + } + + uchar *pack_int32(uchar *to, const uchar *from, bool low_byte_first_to) + { + handle_int32(to, from, table->s->db_low_byte_first, low_byte_first_to); + return to + sizeof(int32); + } + + const uchar *unpack_int32(uchar* to, const uchar *from, + bool low_byte_first_from) + { + handle_int32(to, from, low_byte_first_from, table->s->db_low_byte_first); + return from + sizeof(int32); + } + + uchar *pack_int64(uchar* to, const uchar *from, bool low_byte_first_to) + { + handle_int64(to, from, table->s->db_low_byte_first, low_byte_first_to); + return to + sizeof(int64); + } + + const uchar *unpack_int64(uchar* to, const uchar *from, + bool low_byte_first_from) + { + handle_int64(to, from, low_byte_first_from, table->s->db_low_byte_first); + return from + sizeof(int64); + } +}; + + +class Field_num :public Field { +public: + /** + The scale of the Field's value, i.e. the number of digits to the right + of the decimal point. + */ + /*const*/ uint8 dec; //@InfiniDB need to adjust this field due to vtable restriction + bool zerofill,unsigned_flag; // Purify cannot handle bit fields + Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, utype unireg_check_arg, + const char *field_name_arg, + uint8 dec_arg, bool zero_arg, bool unsigned_arg); + Item_result result_type () const { return REAL_RESULT; } + void prepend_zeros(String *value); + void add_zerofill_and_unsigned(String &res) const; + friend class Create_field; + void make_field(Send_field *); + uint decimals() const { return (uint) dec; } + uint size_of() const { return sizeof(*this); } + bool eq_def(Field *field); + int store_decimal(const my_decimal *); + my_decimal *val_decimal(my_decimal *); + uint is_equal(Create_field *new_field); + int check_int(CHARSET_INFO *cs, const char *str, int length, + const char *int_end, int error); + bool get_int(CHARSET_INFO *cs, const char *from, uint len, + longlong *rnd, ulonglong unsigned_max, + longlong signed_min, longlong signed_max); +}; + + +class Field_str :public Field { +protected: + CHARSET_INFO *field_charset; + enum Derivation field_derivation; +public: + Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, utype unireg_check_arg, + const char *field_name_arg, CHARSET_INFO *charset); + Item_result result_type () const { return STRING_RESULT; } + uint decimals() const { return NOT_FIXED_DEC; } + int store(double nr); + int store(longlong nr, bool unsigned_val)=0; + int store_decimal(const my_decimal *); + int store(const char *to,uint length,CHARSET_INFO *cs)=0; + uint size_of() const { return sizeof(*this); } + CHARSET_INFO *charset(void) const { return field_charset; } + void set_charset(CHARSET_INFO *charset_arg) { field_charset= charset_arg; } + enum Derivation derivation(void) const { return field_derivation; } + virtual void set_derivation(enum Derivation derivation_arg) + { field_derivation= derivation_arg; } + bool binary() const { return field_charset == &my_charset_bin; } + uint32 max_display_length() { return field_length; } + friend class Create_field; + my_decimal *val_decimal(my_decimal *); + virtual bool str_needs_quotes() { return TRUE; } + bool compare_str_field_flags(Create_field *new_field, uint32 flags); + uint is_equal(Create_field *new_field); +}; + + +/* base class for Field_string, Field_varstring and Field_blob */ + +class Field_longstr :public Field_str +{ +protected: + int report_if_important_data(const char *ptr, const char *end, + bool count_spaces); +public: + Field_longstr(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, utype unireg_check_arg, + const char *field_name_arg, CHARSET_INFO *charset_arg) + :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, + field_name_arg, charset_arg) + {} + + int store_decimal(const my_decimal *d); + uint32 max_data_length() const; +}; + +/* base class for float and double and decimal (old one) */ +class Field_real :public Field_num { +public: + my_bool not_fixed; + + Field_real(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, utype unireg_check_arg, + const char *field_name_arg, + uint8 dec_arg, bool zero_arg, bool unsigned_arg) + :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, + field_name_arg, dec_arg, zero_arg, unsigned_arg), + not_fixed(dec_arg >= NOT_FIXED_DEC) + {} + int store_decimal(const my_decimal *); + my_decimal *val_decimal(my_decimal *); + int truncate(double *nr, double max_length); + uint32 max_display_length() { return field_length; } + uint size_of() const { return sizeof(*this); } + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first); + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length, bool low_byte_first); +}; + + +class Field_decimal :public Field_real { +public: + Field_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + uint8 dec_arg,bool zero_arg,bool unsigned_arg) + :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + dec_arg, zero_arg, unsigned_arg) + {} + enum_field_types type() const { return MYSQL_TYPE_DECIMAL;} + enum ha_base_keytype key_type() const + { return zerofill ? HA_KEYTYPE_BINARY : HA_KEYTYPE_NUM; } + int reset(void); + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + void overflow(bool negative); + bool zero_pack() const { return 0; } + void sql_type(String &str) const; + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first) + { + return Field::unpack(to, from, param_data, low_byte_first); + } + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + return Field::pack(to, from, max_length, low_byte_first); + } +}; + + +/* New decimal/numeric field which use fixed point arithmetic */ +class Field_new_decimal :public Field_num { +private: + int do_save_field_metadata(uchar *first_byte); +public: + /* The maximum number of decimal digits can be stored */ + uint precision; + uint bin_size; + /* + Constructors take max_length of the field as a parameter - not the + precision as the number of decimal digits allowed. + So for example we need to count length from precision handling + CREATE TABLE ( DECIMAL(x,y)) + */ + Field_new_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + uint8 dec_arg, bool zero_arg, bool unsigned_arg); + Field_new_decimal(uint32 len_arg, bool maybe_null_arg, + const char *field_name_arg, uint8 dec_arg, + bool unsigned_arg); + /* + Create a field to hold a decimal value from an item. + Truncates the precision and/or scale if necessary. + */ + static Field_new_decimal *new_decimal_field(const Item *item); + enum_field_types type() const { return MYSQL_TYPE_NEWDECIMAL;} + enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; } + Item_result result_type () const { return DECIMAL_RESULT; } + int reset(void); + bool store_value(const my_decimal *decimal_value); + void set_value_on_overflow(my_decimal *decimal_value, bool sign); + int store(const char *to, uint length, CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int store_time(MYSQL_TIME *ltime, timestamp_type t_type); + int store_decimal(const my_decimal *); + double val_real(void); + longlong val_int(void); + my_decimal *val_decimal(my_decimal *); + String *val_str(String*, String *); + int cmp(const uchar *, const uchar *); + void sort_string(uchar *buff, uint length); + bool zero_pack() const { return 0; } + void sql_type(String &str) const; + uint32 max_display_length() { return field_length; } + uint size_of() const { return sizeof(*this); } + uint32 pack_length() const { return (uint32) bin_size; } + uint pack_length_from_metadata(uint field_metadata); + uint row_pack_length() { return pack_length(); } + int compatible_field_size(uint field_metadata, + const Relay_log_info *rli); + uint is_equal(Create_field *new_field); + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first); +}; + + +class Field_tiny :public Field_num { +public: + Field_tiny(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + bool zero_arg, bool unsigned_arg) + :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + 0, zero_arg,unsigned_arg) + {} + enum Item_result result_type () const { return INT_RESULT; } + enum_field_types type() const { return MYSQL_TYPE_TINY;} + enum ha_base_keytype key_type() const + { return unsigned_flag ? HA_KEYTYPE_BINARY : HA_KEYTYPE_INT8; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 1; } + void sql_type(String &str) const; + uint32 max_display_length() { return 4; } + + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + *to= *from; + return to + 1; + } + + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first) + { + *to= *from; + return from + 1; + } +}; + + +class Field_short :public Field_num { +public: + Field_short(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + bool zero_arg, bool unsigned_arg) + :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + 0, zero_arg,unsigned_arg) + {} + Field_short(uint32 len_arg,bool maybe_null_arg, const char *field_name_arg, + bool unsigned_arg) + :Field_num((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg, 0, 0, unsigned_arg) + {} + enum Item_result result_type () const { return INT_RESULT; } + enum_field_types type() const { return MYSQL_TYPE_SHORT;} + enum ha_base_keytype key_type() const + { return unsigned_flag ? HA_KEYTYPE_USHORT_INT : HA_KEYTYPE_SHORT_INT;} + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=ptr[1]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 2; } + void sql_type(String &str) const; + uint32 max_display_length() { return 6; } + + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + int16 val; +#ifdef WORDS_BIGENDIAN + if (table->s->db_low_byte_first) + val = sint2korr(from); + else +#endif + shortget(val, from); + +#ifdef WORDS_BIGENDIAN + if (low_byte_first) + int2store(to, val); + else +#endif + shortstore(to, val); + return to + sizeof(val); + } + + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first) + { + int16 val; +#ifdef WORDS_BIGENDIAN + if (low_byte_first) + val = sint2korr(from); + else +#endif + shortget(val, from); + +#ifdef WORDS_BIGENDIAN + if (table->s->db_low_byte_first) + int2store(to, val); + else +#endif + shortstore(to, val); + return from + sizeof(val); + } +}; + +class Field_medium :public Field_num { +public: + Field_medium(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + bool zero_arg, bool unsigned_arg) + :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + 0, zero_arg,unsigned_arg) + {} + enum Item_result result_type () const { return INT_RESULT; } + enum_field_types type() const { return MYSQL_TYPE_INT24;} + enum ha_base_keytype key_type() const + { return unsigned_flag ? HA_KEYTYPE_UINT24 : HA_KEYTYPE_INT24; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=ptr[1]=ptr[2]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 3; } + void sql_type(String &str) const; + uint32 max_display_length() { return 8; } + + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length, bool low_byte_first) + { + return Field::pack(to, from, max_length, low_byte_first); + } + + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first) + { + return Field::unpack(to, from, param_data, low_byte_first); + } +}; + + +class Field_long :public Field_num { +public: + Field_long(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + bool zero_arg, bool unsigned_arg) + :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + 0, zero_arg,unsigned_arg) + {} + Field_long(uint32 len_arg,bool maybe_null_arg, const char *field_name_arg, + bool unsigned_arg) + :Field_num((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg,0,0,unsigned_arg) + {} + enum Item_result result_type () const { return INT_RESULT; } + enum_field_types type() const { return MYSQL_TYPE_LONG;} + enum ha_base_keytype key_type() const + { return unsigned_flag ? HA_KEYTYPE_ULONG_INT : HA_KEYTYPE_LONG_INT; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } + double val_real(void); + longlong val_int(void); + bool send_binary(Protocol *protocol); + String *val_str(String*,String *); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 4; } + void sql_type(String &str) const; + uint32 max_display_length() { return MY_INT32_NUM_DECIMAL_DIGITS; } + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length __attribute__((unused)), + bool low_byte_first) + { + return pack_int32(to, from, low_byte_first); + } + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data __attribute__((unused)), + bool low_byte_first) + { + return unpack_int32(to, from, low_byte_first); + } +}; + + +#ifdef HAVE_LONG_LONG +class Field_longlong :public Field_num { +public: + Field_longlong(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + bool zero_arg, bool unsigned_arg) + :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + 0, zero_arg,unsigned_arg) + {} + Field_longlong(uint32 len_arg,bool maybe_null_arg, + const char *field_name_arg, + bool unsigned_arg) + :Field_num((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg,0,0,unsigned_arg) + {} + enum Item_result result_type () const { return INT_RESULT; } + enum_field_types type() const { return MYSQL_TYPE_LONGLONG;} + enum ha_base_keytype key_type() const + { return unsigned_flag ? HA_KEYTYPE_ULONGLONG : HA_KEYTYPE_LONGLONG; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) + { + ptr[0]=ptr[1]=ptr[2]=ptr[3]=ptr[4]=ptr[5]=ptr[6]=ptr[7]=0; + return 0; + } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 8; } + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } + uint32 max_display_length() { return 20; } + virtual uchar *pack(uchar* to, const uchar *from, + uint max_length __attribute__((unused)), + bool low_byte_first) + { + return pack_int64(to, from, low_byte_first); + } + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data __attribute__((unused)), + bool low_byte_first) + { + return unpack_int64(to, from, low_byte_first); + } +}; +#endif + + +class Field_float :public Field_real { +public: + Field_float(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + uint8 dec_arg,bool zero_arg,bool unsigned_arg) + :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + dec_arg, zero_arg, unsigned_arg) + {} + Field_float(uint32 len_arg, bool maybe_null_arg, const char *field_name_arg, + uint8 dec_arg) + :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, (uint) 0, + NONE, field_name_arg, dec_arg, 0, 0) + {} + enum_field_types type() const { return MYSQL_TYPE_FLOAT;} + enum ha_base_keytype key_type() const { return HA_KEYTYPE_FLOAT; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { bzero(ptr,sizeof(float)); return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return sizeof(float); } + uint row_pack_length() { return pack_length(); } + void sql_type(String &str) const; +private: + int do_save_field_metadata(uchar *first_byte); +}; + + +class Field_double :public Field_real { +public: + Field_double(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + uint8 dec_arg,bool zero_arg,bool unsigned_arg) + :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + dec_arg, zero_arg, unsigned_arg) + {} + Field_double(uint32 len_arg, bool maybe_null_arg, const char *field_name_arg, + uint8 dec_arg) + :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0, + NONE, field_name_arg, dec_arg, 0, 0) + {} + Field_double(uint32 len_arg, bool maybe_null_arg, const char *field_name_arg, + uint8 dec_arg, my_bool not_fixed_arg) + :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0, + NONE, field_name_arg, dec_arg, 0, 0) + {not_fixed= not_fixed_arg; } + enum_field_types type() const { return MYSQL_TYPE_DOUBLE;} + enum ha_base_keytype key_type() const { return HA_KEYTYPE_DOUBLE; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { bzero(ptr,sizeof(double)); return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return sizeof(double); } + uint row_pack_length() { return pack_length(); } + void sql_type(String &str) const; +private: + int do_save_field_metadata(uchar *first_byte); +}; + + +/* Everything saved in this will disappear. It will always return NULL */ + +class Field_null :public Field_str { + static uchar null[1]; +public: + Field_null(uchar *ptr_arg, uint32 len_arg, + enum utype unireg_check_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str(ptr_arg, len_arg, null, 1, + unireg_check_arg, field_name_arg, cs) + {} + enum_field_types type() const { return MYSQL_TYPE_NULL;} + int store(const char *to, uint length, CHARSET_INFO *cs) + { null[0]=1; return 0; } + int store(double nr) { null[0]=1; return 0; } + int store(longlong nr, bool unsigned_val) { null[0]=1; return 0; } + int store_decimal(const my_decimal *d) { null[0]=1; return 0; } + int reset(void) { return 0; } + double val_real(void) { return 0.0;} + longlong val_int(void) { return 0;} + my_decimal *val_decimal(my_decimal *) { return 0; } + String *val_str(String *value,String *value2) + { value2->length(0); return value2;} + int cmp(const uchar *a, const uchar *b) { return 0;} + void sort_string(uchar *buff, uint length) {} + uint32 pack_length() const { return 0; } + void sql_type(String &str) const; + uint size_of() const { return sizeof(*this); } + uint32 max_display_length() { return 4; } +}; + + +class Field_timestamp :public Field_str { +public: + Field_timestamp(uchar *ptr_arg, uint32 len_arg, + uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + TABLE_SHARE *share, CHARSET_INFO *cs); + Field_timestamp(bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs); + enum_field_types type() const { return MYSQL_TYPE_TIMESTAMP;} + enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONG_INT; } + enum Item_result cmp_type () const { return INT_RESULT; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 4; } + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } + bool zero_pack() const { return 0; } + void set_time(); + virtual void set_default() + { + if (table->timestamp_field == this && + unireg_check != TIMESTAMP_UN_FIELD) + set_time(); + else + Field::set_default(); + } + /* Get TIMESTAMP field value as seconds since begging of Unix Epoch */ + inline long get_timestamp(my_bool *null_value) + { + if ((*null_value= is_null())) + return 0; +#ifdef WORDS_BIGENDIAN + if (table && table->s->db_low_byte_first) + return sint4korr(ptr); +#endif + long tmp; + longget(tmp,ptr); + return tmp; + } + inline void store_timestamp(my_time_t timestamp) + { +#ifdef WORDS_BIGENDIAN + if (table && table->s->db_low_byte_first) + { + int4store(ptr,timestamp); + } + else +#endif + longstore(ptr,(uint32) timestamp); + } + bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + bool get_time(MYSQL_TIME *ltime); + timestamp_auto_set_type get_auto_set_type() const; + uchar *pack(uchar *to, const uchar *from, + uint max_length __attribute__((unused)), bool low_byte_first) + { + return pack_int32(to, from, low_byte_first); + } + const uchar *unpack(uchar* to, const uchar *from, + uint param_data __attribute__((unused)), + bool low_byte_first) + { + return unpack_int32(to, from, low_byte_first); + } +}; + + +class Field_year :public Field_tiny { +public: + Field_year(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg) + :Field_tiny(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, 1, 1) + {} + enum_field_types type() const { return MYSQL_TYPE_YEAR;} + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } +}; + + +class Field_date :public Field_str { +public: + Field_date(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str(ptr_arg, 10, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, cs) + {} + Field_date(bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str((uchar*) 0,10, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg, cs) {} + enum_field_types type() const { return MYSQL_TYPE_DATE;} + enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONG_INT; } + enum Item_result cmp_type () const { return INT_RESULT; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool get_time(MYSQL_TIME *ltime); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 4; } + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } + bool zero_pack() const { return 1; } + uchar *pack(uchar* to, const uchar *from, + uint max_length __attribute__((unused)), bool low_byte_first) + { + return pack_int32(to, from, low_byte_first); + } + const uchar *unpack(uchar* to, const uchar *from, + uint param_data __attribute__((unused)), + bool low_byte_first) + { + return unpack_int32(to, from, low_byte_first); + } +}; + + +class Field_newdate :public Field_str { +public: + Field_newdate(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str(ptr_arg, 10, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, cs) + {} + Field_newdate(bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str((uchar*) 0,10, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg, cs) {} + enum_field_types type() const { return MYSQL_TYPE_DATE;} + enum_field_types real_type() const { return MYSQL_TYPE_NEWDATE; } + enum ha_base_keytype key_type() const { return HA_KEYTYPE_UINT24; } + enum Item_result cmp_type () const { return INT_RESULT; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int store_time(MYSQL_TIME *ltime, timestamp_type type); + int reset(void) { ptr[0]=ptr[1]=ptr[2]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 3; } + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } + bool zero_pack() const { return 1; } + bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + bool get_time(MYSQL_TIME *ltime); +}; + + +class Field_time :public Field_str { +public: + Field_time(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str(ptr_arg, 8, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, cs) + {} + Field_time(bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str((uchar*) 0,8, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg, cs) {} + enum_field_types type() const { return MYSQL_TYPE_TIME;} + enum ha_base_keytype key_type() const { return HA_KEYTYPE_INT24; } + enum Item_result cmp_type () const { return INT_RESULT; } + int store_time(MYSQL_TIME *ltime, timestamp_type type); + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int reset(void) { ptr[0]=ptr[1]=ptr[2]=0; return 0; } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool get_date(MYSQL_TIME *ltime, uint fuzzydate); + bool send_binary(Protocol *protocol); + bool get_time(MYSQL_TIME *ltime); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 3; } + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } + bool zero_pack() const { return 1; } +}; + + +class Field_datetime :public Field_str { +public: + Field_datetime(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str(ptr_arg, 19, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, cs) + {} + Field_datetime(bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_str((uchar*) 0,19, maybe_null_arg ? (uchar*) "": 0,0, + NONE, field_name_arg, cs) {} + enum_field_types type() const { return MYSQL_TYPE_DATETIME;} +#ifdef HAVE_LONG_LONG + enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONGLONG; } +#endif + enum Item_result cmp_type () const { return INT_RESULT; } + uint decimals() const { return DATETIME_DEC; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int store_time(MYSQL_TIME *ltime, timestamp_type type); + int reset(void) + { + ptr[0]=ptr[1]=ptr[2]=ptr[3]=ptr[4]=ptr[5]=ptr[6]=ptr[7]=0; + return 0; + } + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + bool send_binary(Protocol *protocol); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return 8; } + void sql_type(String &str) const; + bool can_be_compared_as_longlong() const { return TRUE; } + bool zero_pack() const { return 1; } + bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + bool get_time(MYSQL_TIME *ltime); + uchar *pack(uchar* to, const uchar *from, + uint max_length __attribute__((unused)), bool low_byte_first) + { + return pack_int64(to, from, low_byte_first); + } + const uchar *unpack(uchar* to, const uchar *from, + uint param_data __attribute__((unused)), + bool low_byte_first) + { + return unpack_int64(to, from, low_byte_first); + } +}; + + +class Field_string :public Field_longstr { +public: + bool can_alter_field_type; + Field_string(uchar *ptr_arg, uint32 len_arg,uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, cs), + can_alter_field_type(1) {}; + Field_string(uint32 len_arg,bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0, + NONE, field_name_arg, cs), + can_alter_field_type(1) {}; + + enum_field_types type() const + { + return ((can_alter_field_type && orig_table && + orig_table->s->db_create_options & HA_OPTION_PACK_RECORD && + field_length >= 4) && + orig_table->s->frm_version < FRM_VER_TRUE_VARCHAR ? + MYSQL_TYPE_VAR_STRING : MYSQL_TYPE_STRING); + } + enum ha_base_keytype key_type() const + { return binary() ? HA_KEYTYPE_BINARY : HA_KEYTYPE_TEXT; } + bool zero_pack() const { return 0; } + int reset(void) + { + charset()->cset->fill(charset(),(char*) ptr, field_length, + (has_charset() ? ' ' : 0)); + return 0; + } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(longlong nr, bool unsigned_val); + int store(double nr) { return Field_str::store(nr); } /* QQ: To be deleted */ + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + my_decimal *val_decimal(my_decimal *); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + void sql_type(String &str) const; + virtual uchar *pack(uchar *to, const uchar *from, + uint max_length, bool low_byte_first); + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first); + uint pack_length_from_metadata(uint field_metadata) + { + DBUG_PRINT("debug", ("field_metadata: 0x%04x", field_metadata)); + if (field_metadata == 0) + return row_pack_length(); + return (((field_metadata >> 4) & 0x300) ^ 0x300) + (field_metadata & 0x00ff); + } + int compatible_field_size(uint field_metadata, + const Relay_log_info *rli); + uint row_pack_length() { return (field_length + 1); } + int pack_cmp(const uchar *a,const uchar *b,uint key_length, + my_bool insert_or_update); + int pack_cmp(const uchar *b,uint key_length,my_bool insert_or_update); + uint packed_col_length(const uchar *to, uint length); + uint max_packed_col_length(uint max_length); + uint size_of() const { return sizeof(*this); } + enum_field_types real_type() const { return MYSQL_TYPE_STRING; } + bool has_charset(void) const + { return charset() == &my_charset_bin ? FALSE : TRUE; } + Field *new_field(MEM_ROOT *root, struct st_table *new_table, bool keep_type); + virtual uint get_key_image(uchar *buff,uint length, imagetype type); +private: + int do_save_field_metadata(uchar *first_byte); +}; + + +class Field_varstring :public Field_longstr { +public: + /* + The maximum space available in a Field_varstring, in bytes. See + length_bytes. + */ + static const uint MAX_SIZE; + /* Store number of bytes used to store length (1 or 2) */ + uint32 length_bytes; + Field_varstring(uchar *ptr_arg, + uint32 len_arg, uint length_bytes_arg, + uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + TABLE_SHARE *share, CHARSET_INFO *cs) + :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, cs), + length_bytes(length_bytes_arg) + { + share->varchar_fields++; + } + Field_varstring(uint32 len_arg,bool maybe_null_arg, + const char *field_name_arg, + TABLE_SHARE *share, CHARSET_INFO *cs) + :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0, + NONE, field_name_arg, cs), + length_bytes(len_arg < 256 ? 1 :2) + { + share->varchar_fields++; + } + + enum_field_types type() const { return MYSQL_TYPE_VARCHAR; } + enum ha_base_keytype key_type() const; + uint row_pack_length() { return field_length; } + bool zero_pack() const { return 0; } + int reset(void) { bzero(ptr,field_length+length_bytes); return 0; } + uint32 pack_length() const { return (uint32) field_length+length_bytes; } + uint32 key_length() const { return (uint32) field_length; } + uint32 sort_length() const + { + return (uint32) field_length + (field_charset == &my_charset_bin ? + length_bytes : 0); + } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(longlong nr, bool unsigned_val); + int store(double nr) { return Field_str::store(nr); } /* QQ: To be deleted */ + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + my_decimal *val_decimal(my_decimal *); + int cmp_max(const uchar *, const uchar *, uint max_length); + int cmp(const uchar *a,const uchar *b) + { + return cmp_max(a, b, ~0L); + } + void sort_string(uchar *buff,uint length); + uint get_key_image(uchar *buff,uint length, imagetype type); + void set_key_image(const uchar *buff,uint length); + void sql_type(String &str) const; + virtual uchar *pack(uchar *to, const uchar *from, + uint max_length, bool low_byte_first); + uchar *pack_key(uchar *to, const uchar *from, uint max_length, bool low_byte_first); + uchar *pack_key_from_key_image(uchar* to, const uchar *from, + uint max_length, bool low_byte_first); + virtual const uchar *unpack(uchar* to, const uchar *from, + uint param_data, bool low_byte_first); + const uchar *unpack_key(uchar* to, const uchar *from, + uint max_length, bool low_byte_first); + int pack_cmp(const uchar *a, const uchar *b, uint key_length, + my_bool insert_or_update); + int pack_cmp(const uchar *b, uint key_length,my_bool insert_or_update); + int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0L); + int key_cmp(const uchar *,const uchar*); + int key_cmp(const uchar *str, uint length); + uint packed_col_length(const uchar *to, uint length); + uint max_packed_col_length(uint max_length); + uint32 data_length(); + uint size_of() const { return sizeof(*this); } + enum_field_types real_type() const { return MYSQL_TYPE_VARCHAR; } + bool has_charset(void) const + { return charset() == &my_charset_bin ? FALSE : TRUE; } + Field *new_field(MEM_ROOT *root, struct st_table *new_table, bool keep_type); + Field *new_key_field(MEM_ROOT *root, struct st_table *new_table, + uchar *new_ptr, uchar *new_null_ptr, + uint new_null_bit); + uint is_equal(Create_field *new_field); + void hash(ulong *nr, ulong *nr2); +private: + int do_save_field_metadata(uchar *first_byte); +}; + + +class Field_blob :public Field_longstr { +protected: + /** + The number of bytes used to represent the length of the blob. + */ + uint packlength; + + /** + The 'value'-object is a cache fronting the storage engine. + */ + String value; + +public: + Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + TABLE_SHARE *share, uint blob_pack_length, CHARSET_INFO *cs); + Field_blob(uint32 len_arg,bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs) + :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0, + NONE, field_name_arg, cs), + packlength(4) + { + flags|= BLOB_FLAG; + } + Field_blob(uint32 len_arg,bool maybe_null_arg, const char *field_name_arg, + CHARSET_INFO *cs, bool set_packlength) + :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0, + NONE, field_name_arg, cs) + { + flags|= BLOB_FLAG; + packlength= 4; + if (set_packlength) + { + uint32 l_char_length= len_arg/cs->mbmaxlen; + packlength= l_char_length <= 255 ? 1 : + l_char_length <= 65535 ? 2 : + l_char_length <= 16777215 ? 3 : 4; + } + } + Field_blob(uint32 packlength_arg) + :Field_longstr((uchar*) 0, 0, (uchar*) "", 0, NONE, "temp", system_charset_info), + packlength(packlength_arg) {} + enum_field_types type() const { return MYSQL_TYPE_BLOB;} + enum ha_base_keytype key_type() const + { return binary() ? HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2; } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + my_decimal *val_decimal(my_decimal *); + int cmp_max(const uchar *, const uchar *, uint max_length); + int cmp(const uchar *a,const uchar *b) + { return cmp_max(a, b, ~0L); } + int cmp(const uchar *a, uint32 a_length, const uchar *b, uint32 b_length); + int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0L); + int key_cmp(const uchar *,const uchar*); + int key_cmp(const uchar *str, uint length); + uint32 key_length() const { return 0; } + void sort_string(uchar *buff,uint length); + uint32 pack_length() const + { return (uint32) (packlength+table->s->blob_ptr_size); } + + /** + Return the packed length without the pointer size added. + + This is used to determine the size of the actual data in the row + buffer. + + @returns The length of the raw data itself without the pointer. + */ + uint32 pack_length_no_ptr() const + { return (uint32) (packlength); } + uint row_pack_length() { return pack_length_no_ptr(); } + uint32 sort_length() const; + virtual uint32 max_data_length() const + { + return (uint32) (((ulonglong) 1 << (packlength*8)) -1); + } + int reset(void) { bzero(ptr, packlength+sizeof(uchar*)); return 0; } + void reset_fields() { bzero((uchar*) &value,sizeof(value)); } + uint32 get_field_buffer_size(void) { return value.alloced_length(); } +#ifndef WORDS_BIGENDIAN + static +#endif + void store_length(uchar *i_ptr, uint i_packlength, uint32 i_number, bool low_byte_first); + void store_length(uchar *i_ptr, uint i_packlength, uint32 i_number) + { + store_length(i_ptr, i_packlength, i_number, table->s->db_low_byte_first); + } + inline void store_length(uint32 number) + { + store_length(ptr, packlength, number); + } + + /** + Return the packed length plus the length of the data. + + This is used to determine the size of the data plus the + packed length portion in the row data. + + @returns The length in the row plus the size of the data. + */ + uint32 get_packed_size(const uchar *ptr_arg, bool low_byte_first) + {return packlength + get_length(ptr_arg, packlength, low_byte_first);} + + inline uint32 get_length(uint row_offset= 0) + { return get_length(ptr+row_offset, this->packlength, table->s->db_low_byte_first); } + uint32 get_length(const uchar *ptr, uint packlength, bool low_byte_first); + uint32 get_length(const uchar *ptr_arg) + { return get_length(ptr_arg, this->packlength, table->s->db_low_byte_first); } + void put_length(uchar *pos, uint32 length); + inline void get_ptr(uchar **str) + { + memcpy_fixed((uchar*) str,ptr+packlength,sizeof(uchar*)); + } + inline void get_ptr(uchar **str, uint row_offset) + { + memcpy_fixed((uchar*) str,ptr+packlength+row_offset,sizeof(char*)); + } + inline void set_ptr(uchar *length, uchar *data) + { + memcpy(ptr,length,packlength); + memcpy_fixed(ptr+packlength,&data,sizeof(char*)); + } + void set_ptr_offset(my_ptrdiff_t ptr_diff, uint32 length, uchar *data) + { + uchar *ptr_ofs= ADD_TO_PTR(ptr,ptr_diff,uchar*); + store_length(ptr_ofs, packlength, length); + memcpy_fixed(ptr_ofs+packlength,&data,sizeof(char*)); + } + inline void set_ptr(uint32 length, uchar *data) + { + set_ptr_offset(0, length, data); + } + uint get_key_image(uchar *buff,uint length, imagetype type); + void set_key_image(const uchar *buff,uint length); + void sql_type(String &str) const; + inline bool copy() + { + uchar *tmp; + get_ptr(&tmp); + if (value.copy((char*) tmp, get_length(), charset())) + { + Field_blob::reset(); + return 1; + } + tmp=(uchar*) value.ptr(); + memcpy_fixed(ptr+packlength,&tmp,sizeof(char*)); + return 0; + } + virtual uchar *pack(uchar *to, const uchar *from, + uint max_length, bool low_byte_first); + uchar *pack_key(uchar *to, const uchar *from, + uint max_length, bool low_byte_first); + uchar *pack_key_from_key_image(uchar* to, const uchar *from, + uint max_length, bool low_byte_first); + virtual const uchar *unpack(uchar *to, const uchar *from, + uint param_data, bool low_byte_first); + const uchar *unpack_key(uchar* to, const uchar *from, + uint max_length, bool low_byte_first); + int pack_cmp(const uchar *a, const uchar *b, uint key_length, + my_bool insert_or_update); + int pack_cmp(const uchar *b, uint key_length,my_bool insert_or_update); + uint packed_col_length(const uchar *col_ptr, uint length); + uint max_packed_col_length(uint max_length); + void free() { value.free(); } + inline void clear_temporary() { bzero((uchar*) &value,sizeof(value)); } + friend int field_conv(Field *to,Field *from); + uint size_of() const { return sizeof(*this); } + bool has_charset(void) const + { return charset() == &my_charset_bin ? FALSE : TRUE; } + uint32 max_display_length(); + uint is_equal(Create_field *new_field); + inline bool in_read_set() { return bitmap_is_set(table->read_set, field_index); } + inline bool in_write_set() { return bitmap_is_set(table->write_set, field_index); } +private: + int do_save_field_metadata(uchar *first_byte); +}; + + +#ifdef HAVE_SPATIAL +class Field_geom :public Field_blob { +public: + enum geometry_type geom_type; + + Field_geom(uchar *ptr_arg, uchar *null_ptr_arg, uint null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + TABLE_SHARE *share, uint blob_pack_length, + enum geometry_type geom_type_arg) + :Field_blob(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, + field_name_arg, share, blob_pack_length, &my_charset_bin) + { geom_type= geom_type_arg; } + Field_geom(uint32 len_arg,bool maybe_null_arg, const char *field_name_arg, + TABLE_SHARE *share, enum geometry_type geom_type_arg) + :Field_blob(len_arg, maybe_null_arg, field_name_arg, &my_charset_bin) + { geom_type= geom_type_arg; } + enum ha_base_keytype key_type() const { return HA_KEYTYPE_VARBINARY2; } + enum_field_types type() const { return MYSQL_TYPE_GEOMETRY; } + void sql_type(String &str) const; + int store(const char *to, uint length, CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int store_decimal(const my_decimal *); + uint size_of() const { return sizeof(*this); } + int reset(void) { return !maybe_null() || Field_blob::reset(); } + geometry_type get_geometry_type() { return geom_type; }; +}; +#endif /*HAVE_SPATIAL*/ + + +class Field_enum :public Field_str { +protected: + uint packlength; +public: + TYPELIB *typelib; + Field_enum(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + uint packlength_arg, + TYPELIB *typelib_arg, + CHARSET_INFO *charset_arg) + :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, charset_arg), + packlength(packlength_arg),typelib(typelib_arg) + { + flags|=ENUM_FLAG; + } + Field *new_field(MEM_ROOT *root, struct st_table *new_table, bool keep_type); + enum_field_types type() const { return MYSQL_TYPE_STRING; } + enum Item_result cmp_type () const { return INT_RESULT; } + enum Item_result cast_to_int_type () const { return INT_RESULT; } + enum ha_base_keytype key_type() const; + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + double val_real(void); + longlong val_int(void); + String *val_str(String*,String *); + int cmp(const uchar *,const uchar *); + void sort_string(uchar *buff,uint length); + uint32 pack_length() const { return (uint32) packlength; } + void store_type(ulonglong value); + void sql_type(String &str) const; + uint size_of() const { return sizeof(*this); } + enum_field_types real_type() const { return MYSQL_TYPE_ENUM; } + uint pack_length_from_metadata(uint field_metadata) + { return (field_metadata & 0x00ff); } + uint row_pack_length() { return pack_length(); } + virtual bool zero_pack() const { return 0; } + bool optimize_range(uint idx, uint part) { return 0; } + bool eq_def(Field *field); + bool has_charset(void) const { return TRUE; } + /* enum and set are sorted as integers */ + CHARSET_INFO *sort_charset(void) const { return &my_charset_bin; } +private: + int do_save_field_metadata(uchar *first_byte); + bool compare_enum_values(TYPELIB *values); + uint is_equal(Create_field *new_field); +}; + + +class Field_set :public Field_enum { +public: + Field_set(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg, + uint32 packlength_arg, + TYPELIB *typelib_arg, CHARSET_INFO *charset_arg) + :Field_enum(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, + unireg_check_arg, field_name_arg, + packlength_arg, + typelib_arg,charset_arg) + { + flags=(flags & ~ENUM_FLAG) | SET_FLAG; + } + int store(const char *to,uint length,CHARSET_INFO *charset); + int store(double nr) { return Field_set::store((longlong) nr, FALSE); } + int store(longlong nr, bool unsigned_val); + + virtual bool zero_pack() const { return 1; } + String *val_str(String*,String *); + void sql_type(String &str) const; + enum_field_types real_type() const { return MYSQL_TYPE_SET; } + bool has_charset(void) const { return TRUE; } +}; + + +/* + Note: + To use Field_bit::cmp_binary() you need to copy the bits stored in + the beginning of the record (the NULL bytes) to each memory you + want to compare (where the arguments point). + + This is the reason: + - Field_bit::cmp_binary() is only implemented in the base class + (Field::cmp_binary()). + - Field::cmp_binary() currenly use pack_length() to calculate how + long the data is. + - pack_length() includes size of the bits stored in the NULL bytes + of the record. +*/ +class Field_bit :public Field { +public: + uchar *bit_ptr; // position in record where 'uneven' bits store + uchar bit_ofs; // offset to 'uneven' high bits + uint bit_len; // number of 'uneven' high bits + uint bytes_in_rec; + Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg, + enum utype unireg_check_arg, const char *field_name_arg); + enum_field_types type() const { return MYSQL_TYPE_BIT; } + enum ha_base_keytype key_type() const { return HA_KEYTYPE_BIT; } + uint32 key_length() const { return (uint32) (field_length + 7) / 8; } + uint32 max_data_length() const { return (field_length + 7) / 8; } + uint32 max_display_length() { return field_length; } + uint size_of() const { return sizeof(*this); } + Item_result result_type () const { return INT_RESULT; } + int reset(void) { bzero(ptr, bytes_in_rec); return 0; } + int store(const char *to, uint length, CHARSET_INFO *charset); + int store(double nr); + int store(longlong nr, bool unsigned_val); + int store_decimal(const my_decimal *); + double val_real(void); + longlong val_int(void); + String *val_str(String*, String *); + virtual bool str_needs_quotes() { return TRUE; } + my_decimal *val_decimal(my_decimal *); + int cmp(const uchar *a, const uchar *b) + { + DBUG_ASSERT(ptr == a); + return Field_bit::key_cmp(b, bytes_in_rec+test(bit_len)); + } + int cmp_binary_offset(uint row_offset) + { return cmp_offset(row_offset); } + int cmp_max(const uchar *a, const uchar *b, uint max_length); + int key_cmp(const uchar *a, const uchar *b) + { return cmp_binary((uchar *) a, (uchar *) b); } + int key_cmp(const uchar *str, uint length); + int cmp_offset(uint row_offset); + void get_image(uchar *buff, uint length, CHARSET_INFO *cs) + { get_key_image(buff, length, itRAW); } + void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) + { Field_bit::store((char *) buff, length, cs); } + uint get_key_image(uchar *buff, uint length, imagetype type); + void set_key_image(const uchar *buff, uint length) + { Field_bit::store((char*) buff, length, &my_charset_bin); } + void sort_string(uchar *buff, uint length) + { get_key_image(buff, length, itRAW); } + uint32 pack_length() const { return (uint32) (field_length + 7) / 8; } + uint32 pack_length_in_rec() const { return bytes_in_rec; } + uint pack_length_from_metadata(uint field_metadata); + uint row_pack_length() + { return (bytes_in_rec + ((bit_len > 0) ? 1 : 0)); } + int compatible_field_size(uint field_metadata, + const Relay_log_info *rli); + void sql_type(String &str) const; + virtual uchar *pack(uchar *to, const uchar *from, + uint max_length, bool low_byte_first); + virtual const uchar *unpack(uchar *to, const uchar *from, + uint param_data, bool low_byte_first); + virtual void set_default(); + + Field *new_key_field(MEM_ROOT *root, struct st_table *new_table, + uchar *new_ptr, uchar *new_null_ptr, + uint new_null_bit); + void set_bit_ptr(uchar *bit_ptr_arg, uchar bit_ofs_arg) + { + bit_ptr= bit_ptr_arg; + bit_ofs= bit_ofs_arg; + } + bool eq(Field *field) + { + return (Field::eq(field) && + bit_ptr == ((Field_bit *)field)->bit_ptr && + bit_ofs == ((Field_bit *)field)->bit_ofs); + } + uint is_equal(Create_field *new_field); + void move_field_offset(my_ptrdiff_t ptr_diff) + { + Field::move_field_offset(ptr_diff); + bit_ptr= ADD_TO_PTR(bit_ptr, ptr_diff, uchar*); + } + void hash(ulong *nr, ulong *nr2); + +private: + virtual size_t do_last_null_byte() const; + int do_save_field_metadata(uchar *first_byte); +}; + + +/** + BIT field represented as chars for non-MyISAM tables. + + @todo The inheritance relationship is backwards since Field_bit is + an extended version of Field_bit_as_char and not the other way + around. Hence, we should refactor it to fix the hierarchy order. + */ +class Field_bit_as_char: public Field_bit { +public: + Field_bit_as_char(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, + uchar null_bit_arg, + enum utype unireg_check_arg, const char *field_name_arg); + enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; } + uint size_of() const { return sizeof(*this); } + int store(const char *to, uint length, CHARSET_INFO *charset); + int store(double nr) { return Field_bit::store(nr); } + int store(longlong nr, bool unsigned_val) + { return Field_bit::store(nr, unsigned_val); } + void sql_type(String &str) const; +}; + + +/* + Create field class for CREATE TABLE +*/ + +class Create_field :public Sql_alloc +{ +public: + const char *field_name; + const char *change; // If done with alter table + const char *after; // Put column after this one + LEX_STRING comment; // Comment for field + Item *def; // Default value + enum enum_field_types sql_type; + /* + At various stages in execution this can be length of field in bytes or + max number of characters. + */ + ulong length; + /* + The value of `length' as set by parser: is the number of characters + for most of the types, or of bytes for BLOBs or numeric types. + */ + uint32 char_length; + uint decimals, flags, pack_length, key_length; + Field::utype unireg_check; + TYPELIB *interval; // Which interval to use + TYPELIB *save_interval; // Temporary copy for the above + // Used only for UCS2 intervals + List interval_list; + CHARSET_INFO *charset; + Field::geometry_type geom_type; + Field *field; // For alter table + + uint8 row,col,sc_length,interval_id; // For rea_create_table + uint offset,pack_flag; + Create_field() :after(0) {} + Create_field(Field *field, Field *orig_field); + /* Used to make a clone of this object for ALTER/CREATE TABLE */ + Create_field *clone(MEM_ROOT *mem_root) const + { return new (mem_root) Create_field(*this); } + void create_length_to_internal_length(void); + + /* Init for a tmp table field. To be extended if need be. */ + void init_for_tmp_table(enum_field_types sql_type_arg, + uint32 max_length, uint32 decimals, + bool maybe_null, bool is_unsigned); + + bool init(THD *thd, char *field_name, enum_field_types type, char *length, + char *decimals, uint type_modifier, Item *default_value, + Item *on_update_value, LEX_STRING *comment, char *change, + List *interval_list, CHARSET_INFO *cs, + uint uint_geom_type); +}; + + +/* + A class for sending info to the client +*/ + +class Send_field { + public: + const char *db_name; + const char *table_name,*org_table_name; + const char *col_name,*org_col_name; + ulong length; + uint charsetnr, flags, decimals; + enum_field_types type; + Send_field() {} +}; + + +/* + A class for quick copying data to fields +*/ + +class Copy_field :public Sql_alloc { + /** + Convenience definition of a copy function returned by + get_copy_func. + */ + typedef void Copy_func(Copy_field*); + Copy_func *get_copy_func(Field *to, Field *from); +public: + uchar *from_ptr,*to_ptr; + uchar *from_null_ptr,*to_null_ptr; + my_bool *null_row; + uint from_bit,to_bit; + uint from_length,to_length; + Field *from_field,*to_field; + String tmp; // For items + + Copy_field() {} + ~Copy_field() {} + void set(Field *to,Field *from,bool save); // Field to field + void set(uchar *to,Field *from); // Field to string + void (*do_copy)(Copy_field *); + void (*do_copy2)(Copy_field *); // Used to handle null values +}; + + +Field *make_field(TABLE_SHARE *share, uchar *ptr, uint32 field_length, + uchar *null_pos, uchar null_bit, + uint pack_flag, enum_field_types field_type, + CHARSET_INFO *cs, + Field::geometry_type geom_type, + Field::utype unireg_check, + TYPELIB *interval, const char *field_name); +uint pack_length_to_packflag(uint type); +enum_field_types get_blob_type_from_length(ulong length); +uint32 calc_pack_length(enum_field_types type,uint32 length); +int set_field_to_null(Field *field); +int set_field_to_null_with_conversions(Field *field, bool no_conversions); + +/* + The following are for the interface with the .frm file +*/ + +#define FIELDFLAG_DECIMAL 1 +#define FIELDFLAG_BINARY 1 // Shares same flag +#define FIELDFLAG_NUMBER 2 +#define FIELDFLAG_ZEROFILL 4 +#define FIELDFLAG_PACK 120 // Bits used for packing +#define FIELDFLAG_INTERVAL 256 // mangled with decimals! +#define FIELDFLAG_BITFIELD 512 // mangled with decimals! +#define FIELDFLAG_BLOB 1024 // mangled with decimals! +#define FIELDFLAG_GEOM 2048 // mangled with decimals! + +#define FIELDFLAG_TREAT_BIT_AS_CHAR 4096 /* use Field_bit_as_char */ + +#define FIELDFLAG_LEFT_FULLSCREEN 8192 +#define FIELDFLAG_RIGHT_FULLSCREEN 16384 +#define FIELDFLAG_FORMAT_NUMBER 16384 // predit: ###,,## in output +#define FIELDFLAG_NO_DEFAULT 16384 /* sql */ +#define FIELDFLAG_SUM ((uint) 32768)// predit: +#fieldflag +#define FIELDFLAG_MAYBE_NULL ((uint) 32768)// sql +#define FIELDFLAG_HEX_ESCAPE ((uint) 0x10000) +#define FIELDFLAG_PACK_SHIFT 3 +#define FIELDFLAG_DEC_SHIFT 8 +#define FIELDFLAG_MAX_DEC 31 +#define FIELDFLAG_NUM_SCREEN_TYPE 0x7F01 +#define FIELDFLAG_ALFA_SCREEN_TYPE 0x7800 + +#define MTYP_TYPENR(type) (type & 127) /* Remove bits from type */ + +#define f_is_dec(x) ((x) & FIELDFLAG_DECIMAL) +#define f_is_num(x) ((x) & FIELDFLAG_NUMBER) +#define f_is_zerofill(x) ((x) & FIELDFLAG_ZEROFILL) +#define f_is_packed(x) ((x) & FIELDFLAG_PACK) +#define f_packtype(x) (((x) >> FIELDFLAG_PACK_SHIFT) & 15) +#define f_decimals(x) ((uint8) (((x) >> FIELDFLAG_DEC_SHIFT) & FIELDFLAG_MAX_DEC)) +#define f_is_alpha(x) (!f_is_num(x)) +#define f_is_binary(x) ((x) & FIELDFLAG_BINARY) // 4.0- compatibility +#define f_is_enum(x) (((x) & (FIELDFLAG_INTERVAL | FIELDFLAG_NUMBER)) == FIELDFLAG_INTERVAL) +#define f_is_bitfield(x) (((x) & (FIELDFLAG_BITFIELD | FIELDFLAG_NUMBER)) == FIELDFLAG_BITFIELD) +#define f_is_blob(x) (((x) & (FIELDFLAG_BLOB | FIELDFLAG_NUMBER)) == FIELDFLAG_BLOB) +#define f_is_geom(x) (((x) & (FIELDFLAG_GEOM | FIELDFLAG_NUMBER)) == FIELDFLAG_GEOM) +#define f_is_equ(x) ((x) & (1+2+FIELDFLAG_PACK+31*256)) +#define f_settype(x) (((int) x) << FIELDFLAG_PACK_SHIFT) +#define f_maybe_null(x) (x & FIELDFLAG_MAYBE_NULL) +#define f_no_default(x) (x & FIELDFLAG_NO_DEFAULT) +#define f_bit_as_char(x) ((x) & FIELDFLAG_TREAT_BIT_AS_CHAR) +#define f_is_hex_escape(x) ((x) & FIELDFLAG_HEX_ESCAPE) diff --git a/dbcon/mysql/ha_autoi.cpp b/dbcon/mysql/ha_autoi.cpp index 67f42552..e9168acf 100644 --- a/dbcon/mysql/ha_autoi.cpp +++ b/dbcon/mysql/ha_autoi.cpp @@ -19,7 +19,7 @@ * $Id$ */ -bool parseAutoincrementTableComment ( std::string comment, uint64_t& startValue, std::string& columnName ) +bool parseAutoincrementTableComment ( std::string comment, int64_t& startValue, std::string& columnName ) { algorithm::to_upper(comment); regex compat("[[:space:]]*AUTOINCREMENT[[:space:]]*=[[:space:]]*", regex_constants::extended); @@ -70,7 +70,7 @@ bool parseAutoincrementTableComment ( std::string comment, uint64_t& startValue, errno = 0; char *ep = NULL; const char *str = startVal.c_str(); - startValue = strtoull(str, &ep, 10); + startValue = strtoll(str, &ep, 10); // (no digits) || (more chars) || (other errors & value = 0) if ((ep == str) || (*ep != '\0') || (errno != 0)) { @@ -98,7 +98,7 @@ bool parseAutoincrementTableComment ( std::string comment, uint64_t& startValue, return autoincrement; } -bool parseAutoincrementColumnComment ( std::string comment, uint64_t& startValue ) +bool parseAutoincrementColumnComment ( std::string comment, int64_t& startValue ) { algorithm::to_upper(comment); regex compat("[[:space:]]*AUTOINCREMENT[[:space:]]*", regex_constants::extended); diff --git a/dbcon/mysql/ha_calpont.cpp b/dbcon/mysql/ha_calpont.cpp index 3458248c..09e45a9a 100644 --- a/dbcon/mysql/ha_calpont.cpp +++ b/dbcon/mysql/ha_calpont.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: ha_calpont.cpp 9642 2013-06-24 14:57:42Z rdempsey $ +// $Id: ha_calpont.cpp 8436 2012-04-04 18:18:21Z rdempsey $ /* Copyright (C) 2003 MySQL AB @@ -121,7 +121,6 @@ static int calpont_commit(handlerton *hton, THD* thd, bool all); static int calpont_rollback(handlerton *hton, THD* thd, bool all); static int calpont_close_connection ( handlerton *hton, THD* thd ); -static void calpont_set_error( THD*, uint64_t, LEX_STRING*, uint32_t); handlerton *calpont_hton; /* Variables for example share methods */ @@ -189,15 +188,17 @@ static int calpont_init_func(void *p) calpont_hton->commit= calpont_commit; calpont_hton->rollback= calpont_rollback; calpont_hton->close_connection = calpont_close_connection; - calpont_hton->set_error= calpont_set_error; DBUG_RETURN(0); } static int calpont_done_func(void *p) { + int error= 0; DBUG_ENTER("calpont_done_func"); + if (calpont_open_tables.records) + error= 1; hash_free(&calpont_open_tables); #ifndef _MSC_VER pthread_mutex_destroy(&calpont_mutex); @@ -218,12 +219,12 @@ static int calpont_done_func(void *p) static CALPONT_SHARE *get_share(const char *table_name, TABLE *table) { CALPONT_SHARE *share; - uint32_t length; + uint length; char *tmp_name; #ifndef _MSC_VER pthread_mutex_lock(&calpont_mutex); #endif - length=(uint32_t) strlen(table_name); + length=(uint) strlen(table_name); if (!(share=(CALPONT_SHARE*) hash_search(&calpont_open_tables, (uchar*) table_name, @@ -306,12 +307,6 @@ static int calpont_close_connection ( handlerton *hton, THD* thd ) int rc = ha_calpont_impl_close_connection( hton, thd); return rc; } - -static void calpont_set_error(THD* thd, uint64_t errCode, LEX_STRING* args, uint32_t argCount) -{ - return ha_calpont_impl_set_error(thd, errCode, args, argCount); -} - ha_calpont::ha_calpont(handlerton *hton, TABLE_SHARE *table_arg) :handler(hton, table_arg) {} @@ -361,7 +356,7 @@ const char **ha_calpont::bas_ext() const handler::ha_open() in handler.cc */ -int ha_calpont::open(const char *name, int mode, uint32_t test_if_locked) +int ha_calpont::open(const char *name, int mode, uint test_if_locked) { DBUG_ENTER("ha_calpont::open"); @@ -738,7 +733,7 @@ int ha_calpont::rnd_pos(uchar *buf, uchar *pos) sql_select.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_table.cc, sql_union.cc and sql_update.cc */ -int ha_calpont::info(uint32_t flag) +int ha_calpont::info(uint flag) { DBUG_ENTER("ha_calpont::info"); // @bug 1635. Raise this number magically fix the filesort crash issue. May need to twist @@ -763,7 +758,6 @@ puts("info"); int ha_calpont::extra(enum ha_extra_function operation) { DBUG_ENTER("ha_calpont::extra"); -#ifdef INFINIDB_DEBUG { const char* hefs; switch (operation) @@ -787,9 +781,10 @@ int ha_calpont::extra(enum ha_extra_function operation) hefs = "UNKNOWN ENUM!"; break; } +#ifdef INFINIDB_DEBUG fprintf(stderr, "ha_calpont::extra(\"%s\", %d: %s)\n", table->s->table_name.str, operation, hefs); - } #endif + } DBUG_RETURN(0); } @@ -965,7 +960,7 @@ int ha_calpont::rename_table(const char * from, const char * to) @see check_quick_keys() in opt_range.cc */ -ha_rows ha_calpont::records_in_range(uint32_t inx, key_range *min_key, +ha_rows ha_calpont::records_in_range(uint inx, key_range *min_key, key_range *max_key) { DBUG_ENTER("ha_calpont::records_in_range"); @@ -1065,9 +1060,9 @@ mysql_declare_plugin(calpont) MYSQL_STORAGE_ENGINE_PLUGIN, &infinidb_storage_engine, "InfiniDB", - "InfiniDB, Inc.", - "InfiniDB storage engine", - PLUGIN_LICENSE_GPL, + "Calpont Corp.", + "Calpont InfiniDB storage engine", + PLUGIN_LICENSE_PROPRIETARY, calpont_init_func, /* Plugin Init */ calpont_done_func, /* Plugin Deinit */ 0x0001 /* 0.1 */, diff --git a/dbcon/mysql/ha_calpont.h b/dbcon/mysql/ha_calpont.h index 651bef72..ba2b2a75 100644 --- a/dbcon/mysql/ha_calpont.h +++ b/dbcon/mysql/ha_calpont.h @@ -32,7 +32,7 @@ /sql/handler.h and /storage/example/ha_example.cc */ -// $Id: ha_calpont.h 9210 2013-01-21 14:10:42Z rdempsey $ +// $Id: ha_calpont.h 8436 2012-04-04 18:18:21Z rdempsey $ #ifndef HA_CALPONT_H__ #define HA_CALPONT_H__ @@ -44,7 +44,7 @@ */ typedef struct st_calpont_share { char *table_name; - uint32_t table_name_length,use_count; + uint table_name_length,use_count; pthread_mutex_t mutex; THR_LOCK lock; } INFINIDB_SHARE; @@ -72,7 +72,7 @@ class ha_calpont: public handler The name of the index type that will be used for display. Don't implement this method unless you really have indexes. */ - //const char *index_type(uint32_t inx) { return "HASH"; } + //const char *index_type(uint inx) { return "HASH"; } /** @brief The file extensions. @@ -103,19 +103,19 @@ class ha_calpont: public handler If all_parts is set, MySQL wants to know the flags for the combined index, up to and including 'part'. */ - ulong index_flags(uint32_t inx, uint32_t part, bool all_parts) const + ulong index_flags(uint inx, uint part, bool all_parts) const { return 0; } /** @brief unireg.cc will call max_supported_record_length(), max_supported_keys(), - max_supported_key_parts(), uint32_t max_supported_key_length() + max_supported_key_parts(), uint max_supported_key_length() to make sure that the storage engine can handle the data it is about to send. Return *real* limits of your storage engine here; MySQL will do min(your_limits, MySQL_limits) automatically. */ - uint32_t max_supported_record_length() const { return HA_MAX_REC_LENGTH; } + uint max_supported_record_length() const { return HA_MAX_REC_LENGTH; } /** @brief unireg.cc will call this to make sure that the storage engine can handle @@ -126,7 +126,7 @@ class ha_calpont: public handler There is no need to implement ..._key_... methods if your engine doesn't support indexes. */ - uint32_t max_supported_keys() const { return 1; } + uint max_supported_keys() const { return 1; } /** @brief unireg.cc will call this to make sure that the storage engine can handle @@ -137,7 +137,7 @@ class ha_calpont: public handler There is no need to implement ..._key_... methods if your engine doesn't support indexes. */ - uint32_t max_supported_key_parts() const { return 1; } + uint max_supported_key_parts() const { return 1; } /** @brief unireg.cc will call this to make sure that the storage engine can handle @@ -148,7 +148,7 @@ class ha_calpont: public handler There is no need to implement ..._key_... methods if your engine doesn't support indexes. */ - uint32_t max_supported_key_length() const { return 8; } + uint max_supported_key_length() const { return 8; } /** @brief Called in test_quick_select to determine if indexes should be used. @@ -169,7 +169,7 @@ class ha_calpont: public handler /** @brief We implement this in ha_example.cc; it's a required method. */ - int open(const char *name, int mode, uint32_t test_if_locked); // required + int open(const char *name, int mode, uint test_if_locked); // required /** @brief We implement this in ha_example.cc; it's a required method. @@ -253,11 +253,11 @@ class ha_calpont: public handler int rnd_next(uchar *buf); ///< required int rnd_pos(uchar *buf, uchar *pos); ///< required void position(const uchar *record); ///< required - int info(uint32_t); ///< required + int info(uint); ///< required int extra(enum ha_extra_function operation); int external_lock(THD *thd, int lock_type); ///< required int delete_all_rows(void); - ha_rows records_in_range(uint32_t inx, key_range *min_key, + ha_rows records_in_range(uint inx, key_range *min_key, key_range *max_key); int delete_table(const char *from); int rename_table(const char * from, const char * to); diff --git a/dbcon/mysql/ha_calpont_ddl.cpp b/dbcon/mysql/ha_calpont_ddl.cpp index 5149729c..99e06194 100644 --- a/dbcon/mysql/ha_calpont_ddl.cpp +++ b/dbcon/mysql/ha_calpont_ddl.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: ha_calpont_ddl.cpp 9675 2013-07-11 15:38:12Z chao $ + * $Id: ha_calpont_ddl.cpp 9079 2012-11-14 22:14:23Z rdempsey $ */ #include @@ -87,15 +87,14 @@ using namespace BRM; #include "constantcolumn.h" using namespace execplan; -#include "resourcemanager.h" -using namespace joblist; - namespace { +const int MAX_INT = numeric_limits::max(); +const short MAX_TINYINT = numeric_limits::max(); //127; +const short MAX_SMALLINT = numeric_limits::max(); //32767; +const long long MAX_BIGINT = numeric_limits::max();//9223372036854775807LL typedef CalpontSelectExecutionPlan::ColumnMap::value_type CMVT_; -ResourceManager rm; -bool useHdfs = rm.useHdfs(); #ifndef SKIP_AUTOI #include "ha_autoi.cpp" @@ -108,9 +107,9 @@ inline uint32_t tid2sid(const uint32_t tid) } -uint32_t convertDataType(int dataType) +uint convertDataType(int dataType) { - uint32_t calpontDataType; + uint calpontDataType; switch (dataType) { @@ -182,34 +181,6 @@ uint32_t convertDataType(int dataType) calpontDataType = CalpontSystemCatalog::BLOB; break; - case ddlpackage::DDL_UNSIGNED_TINYINT: - calpontDataType = CalpontSystemCatalog::UTINYINT; - break; - - case ddlpackage::DDL_UNSIGNED_SMALLINT: - calpontDataType = CalpontSystemCatalog::USMALLINT; - break; - - case ddlpackage::DDL_UNSIGNED_INT: - calpontDataType = CalpontSystemCatalog::UINT; - break; - - case ddlpackage::DDL_UNSIGNED_BIGINT: - calpontDataType = CalpontSystemCatalog::UBIGINT; - break; - - case ddlpackage::DDL_UNSIGNED_DECIMAL: - case ddlpackage::DDL_UNSIGNED_NUMERIC: - calpontDataType = CalpontSystemCatalog::UDECIMAL; - break; - - case ddlpackage::DDL_UNSIGNED_FLOAT: - calpontDataType = CalpontSystemCatalog::UFLOAT; - break; - - case ddlpackage::DDL_UNSIGNED_DOUBLE: - calpontDataType = CalpontSystemCatalog::UDOUBLE; - break; default: throw runtime_error("Unsupported datatype!"); @@ -218,7 +189,6 @@ uint32_t convertDataType(int dataType) return calpontDataType; } - int parseCompressionComment ( std::string comment ) { algorithm::to_upper(comment); @@ -227,9 +197,9 @@ int parseCompressionComment ( std::string comment ) boost::match_results what; std::string::const_iterator start, end; start = comment.begin(); - end = comment.end(); + end = comment.end(); boost::match_flag_type flags = boost::match_default; - if (boost::regex_search(start, end, what, compat, flags)) + if (boost::regex_search(start, end, what, compat, flags)) { //Find the pattern, now get the compression type string compType (&(*(what[0].second))); @@ -254,7 +224,7 @@ int parseCompressionComment ( std::string comment ) { compressiontype = -1; } - + } else compressiontype = MAX_INT; @@ -273,11 +243,6 @@ bool validateAutoincrementDatatype ( int type ) case ddlpackage::DDL_MEDINT: case ddlpackage::DDL_SMALLINT: case ddlpackage::DDL_TINYINT: - case ddlpackage::DDL_UNSIGNED_INT: - case ddlpackage::DDL_UNSIGNED_BIGINT: - case ddlpackage::DDL_UNSIGNED_MEDINT: - case ddlpackage::DDL_UNSIGNED_SMALLINT: - case ddlpackage::DDL_UNSIGNED_TINYINT: validAutoType = true; break; } @@ -295,12 +260,6 @@ bool validateNextValue( int type, int64_t value ) validValue = false; } break; - case ddlpackage::DDL_UNSIGNED_BIGINT: - { - if (static_cast(value) > MAX_UBIGINT) - validValue = false; - } - break; case ddlpackage::DDL_INT: case ddlpackage::DDL_INTEGER: case ddlpackage::DDL_MEDINT: @@ -309,37 +268,18 @@ bool validateNextValue( int type, int64_t value ) validValue = false; } break; - case ddlpackage::DDL_UNSIGNED_INT: - case ddlpackage::DDL_UNSIGNED_MEDINT: - { - if (static_cast(value) > MAX_UINT) - validValue = false; - } - break; case ddlpackage::DDL_SMALLINT: { if (value > MAX_SMALLINT) validValue = false; } break; - case ddlpackage::DDL_UNSIGNED_SMALLINT: - { - if (static_cast(value) > MAX_USMALLINT) - validValue = false; - } - break; case ddlpackage::DDL_TINYINT: { if (value > MAX_TINYINT) validValue = false; } break; - case ddlpackage::DDL_UNSIGNED_TINYINT: - { - if (static_cast(value) > MAX_UTINYINT) - validValue = false; - } - break; } return validValue; } @@ -356,11 +296,11 @@ bool anyRowInTable(string& schema, string& tableName, int sessionID) aTableName.table = tableName; CalpontSystemCatalog::RIDList ridList = csc->columnRIDs(aTableName, true); CalpontSystemCatalog::TableColName tableColName = csc->colName(ridList[0].objnum); - - CalpontSelectExecutionPlan csep; - CalpontSelectExecutionPlan::ReturnedColumnList returnedColumnList; - CalpontSelectExecutionPlan::ColumnMap colMap; - + + CalpontSelectExecutionPlan csep; + CalpontSelectExecutionPlan::ReturnedColumnList returnedColumnList; + CalpontSelectExecutionPlan::ColumnMap colMap; + SessionManager sm; BRM::TxnID txnID; txnID = sm.getTxnID(sessionID); @@ -369,43 +309,42 @@ bool anyRowInTable(string& schema, string& tableName, int sessionID) txnID.id = 0; txnID.valid = true; } - QueryContext verID; + CalpontSystemCatalog::SCN verID; verID = sm.verID(); csep.txnID(txnID.id); csep.verID(verID); csep.sessionID(sessionID); - + string firstCol = tableColName.schema+"."+tableColName.table+"."+tableColName.column; SimpleColumn* col[1]; - col[0] = new SimpleColumn(firstCol, sessionID); + col[0] = new SimpleColumn(firstCol, sessionID); SRCP srcp; - srcp.reset(col[0]); - colMap.insert(CMVT_(firstCol, srcp)); + srcp.reset(col[0]); + colMap.insert(CMVT_(firstCol, srcp)); csep.columnMapNonStatic(colMap); returnedColumnList.push_back(srcp); - csep.returnedCols(returnedColumnList); - + csep.returnedCols(returnedColumnList); + CalpontSelectExecutionPlan::TableList tablelist; tablelist.push_back(make_aliastable(schema, tableName, "")); csep.tableList(tablelist); - + boost::shared_ptr exemgrClient (new messageqcpp::MessageQueueClient("ExeMgr1")); ByteStream msg, emsgBs; - rowgroup::RGData rgData; ByteStream::quadbyte qb = 4; msg << qb; rowgroup::RowGroup *rowGroup = 0; bool anyRow = false; - + exemgrClient->write(msg); ByteStream msgPlan; csep.serialize(msgPlan); - exemgrClient->write(msgPlan); + exemgrClient->write(msgPlan); msg.restart(); msg = exemgrClient->read(); //error handling - emsgBs = exemgrClient->read(); + emsgBs = exemgrClient->read(); ByteStream::quadbyte qb1; - + if (emsgBs.length() == 0) { //exemgrClient->shutdown(); @@ -414,11 +353,11 @@ bool anyRowInTable(string& schema, string& tableName, int sessionID) throw runtime_error("Lost conection to ExeMgr."); } string emsgStr; - emsgBs >> emsgStr; + emsgBs >> emsgStr; if (msg.length() == 4) { msg >> qb1; - if (qb1 != 0) + if (qb1 != 0) { //exemgrClient->shutdown(); //delete exemgrClient; @@ -426,7 +365,7 @@ bool anyRowInTable(string& schema, string& tableName, int sessionID) throw runtime_error(emsgStr); } } - + while (true) { msg.restart(); @@ -451,12 +390,11 @@ bool anyRowInTable(string& schema, string& tableName, int sessionID) exemgrClient->write(msg); continue; } - rgData.deserialize(msg); - rowGroup->setData(&rgData); - + rowGroup->setData(const_cast(msg.buf())); + if (rowGroup->getStatus() != 0) { - //msg.advance(rowGroup->getDataSize()); + msg.advance(rowGroup->getDataSize()); msg >> emsgStr; //exemgrClient->shutdown(); //delete exemgrClient; @@ -471,19 +409,19 @@ bool anyRowInTable(string& schema, string& tableName, int sessionID) //exemgrClient = 0; return anyRow; } - } + } } bool anyNullInTheColumn (string& schema, string& table, string& columnName, int sessionID) { - CalpontSelectExecutionPlan csep; - CalpontSelectExecutionPlan::ReturnedColumnList returnedColumnList; - CalpontSelectExecutionPlan::FilterTokenList filterTokenList; - CalpontSelectExecutionPlan::ColumnMap colMap; + CalpontSelectExecutionPlan csep; + CalpontSelectExecutionPlan::ReturnedColumnList returnedColumnList; + CalpontSelectExecutionPlan::FilterTokenList filterTokenList; + CalpontSelectExecutionPlan::ColumnMap colMap; algorithm::to_lower(schema); algorithm::to_lower(table); algorithm::to_lower(columnName); - + SessionManager sm; BRM::TxnID txnID; txnID = sm.getTxnID(sessionID); @@ -492,53 +430,52 @@ bool anyNullInTheColumn (string& schema, string& table, string& columnName, int txnID.id = 0; txnID.valid = true; } - QueryContext verID; + CalpontSystemCatalog::SCN verID; verID = sm.verID(); csep.txnID(txnID.id); csep.verID(verID); csep.sessionID(sessionID); - + string firstCol = schema+"."+table+"."+columnName; SimpleColumn* col[1]; - col[0] = new SimpleColumn(firstCol, sessionID); + col[0] = new SimpleColumn(firstCol, sessionID); SRCP srcp; - srcp.reset(col[0]); - colMap.insert(CMVT_(firstCol, srcp)); + srcp.reset(col[0]); + colMap.insert(CMVT_(firstCol, srcp)); csep.columnMapNonStatic(colMap); returnedColumnList.push_back(srcp); - csep.returnedCols(returnedColumnList); - + csep.returnedCols(returnedColumnList); + SimpleFilter *sf = new SimpleFilter(); - boost::shared_ptr sop(new PredicateOperator("isnull")); + shared_ptr sop(new PredicateOperator("isnull")); sf->op(sop); ConstantColumn *rhs = new ConstantColumn("", ConstantColumn::NULLDATA); sf->lhs(col[0]->clone()); sf->rhs(rhs); - + filterTokenList.push_back(sf); - csep.filterTokenList(filterTokenList); - + csep.filterTokenList(filterTokenList); + CalpontSelectExecutionPlan::TableList tablelist; tablelist.push_back(make_aliastable(schema, table, "")); csep.tableList(tablelist); - + boost::shared_ptr exemgrClient (new messageqcpp::MessageQueueClient("ExeMgr1")); ByteStream msg, emsgBs; - rowgroup::RGData rgData; ByteStream::quadbyte qb = 4; msg << qb; rowgroup::RowGroup *rowGroup = 0; bool anyRow = false; - + exemgrClient->write(msg); ByteStream msgPlan; csep.serialize(msgPlan); - exemgrClient->write(msgPlan); + exemgrClient->write(msgPlan); msg.restart(); msg = exemgrClient->read(); //error handling - emsgBs = exemgrClient->read(); + emsgBs = exemgrClient->read(); ByteStream::quadbyte qb1; - + if (emsgBs.length() == 0) { //exemgrClient->shutdown(); @@ -547,11 +484,11 @@ bool anyNullInTheColumn (string& schema, string& table, string& columnName, int throw runtime_error("Lost conection to ExeMgr."); } string emsgStr; - emsgBs >> emsgStr; + emsgBs >> emsgStr; if (msg.length() == 4) { msg >> qb1; - if (qb1 != 0) + if (qb1 != 0) { //exemgrClient->shutdown(); //delete exemgrClient; @@ -559,7 +496,7 @@ bool anyNullInTheColumn (string& schema, string& table, string& columnName, int throw runtime_error(emsgStr); } } - + while (true) { msg.restart(); @@ -584,12 +521,11 @@ bool anyNullInTheColumn (string& schema, string& table, string& columnName, int exemgrClient->write(msg); continue; } - rgData.deserialize(msg); - rowGroup->setData(&rgData); - + rowGroup->setData(const_cast(msg.buf())); + if (rowGroup->getStatus() != 0) { - //msg.advance(amount); + msg.advance(rowGroup->getDataSize()); msg >> emsgStr; //exemgrClient->shutdown(); //delete exemgrClient; @@ -604,18 +540,15 @@ bool anyNullInTheColumn (string& schema, string& table, string& columnName, int //exemgrClient = 0; return anyRow; } - } + } } int ProcessDDLStatement(string& ddlStatement, string& schema, const string& table, int sessionID, - string& emsg, int compressionTypeIn = 2, bool isAnyAutoincreCol = false, int64_t nextvalue = 1, std::string autoiColName = "") + string& emsg, int compressionTypeIn = 0, bool isAnyAutoincreCol = false, int64_t nextvalue = 1, std::string autoiColName = "") { SqlParser parser; THD *thd = current_thd; -#ifdef INFINIDB_DEBUG - cout << "ProcessDDLStatement: " << schema << "." << table << ":" << ddlStatement << endl; -#endif - + parser.setDefaultSchema(schema); int rc = 0; IDBCompressInterface idbCompress; @@ -625,10 +558,8 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); if(parser.Good()) { - boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); - csc->identity(execplan::CalpontSystemCatalog::FE); - const ddlpackage::ParseTree &ptree = parser.GetParseTree(); - SqlStatement &stmt = *ptree.fList[0]; + const ddlpackage::ParseTree &ptree = parser.GetParseTree(); + SqlStatement &stmt = *ptree.fList[0]; bool isVarbinaryAllowed = false; std::string valConfig = config::Config::makeConfig()->getConfig( "WriteEngine", "AllowVarbinary" ); @@ -636,33 +567,21 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl if (valConfig.compare("YES") == 0) isVarbinaryAllowed = true; - //@Bug 1771. error out for not supported feature. - if ( typeid ( stmt ) == typeid ( CreateTableStatement ) ) - { - CreateTableStatement * createTable = dynamic_cast ( &stmt ); - //@Bug 5767. To handle key words inside `` for a tablename. - if (!(boost::iequals(schema, createTable->fTableDef->fQualifiedName->fSchema)) || !(boost::iequals(table,createTable->fTableDef->fQualifiedName->fName))) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CREATE_DATATYPE_NOT_SUPPORT)).c_str()); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - - bool matchedCol = false; - for ( unsigned i=0; i < createTable->fTableDef->fColumns.size(); i++ ) - { + //@Bug 1771. error out for not supported feature. + if ( typeid ( stmt ) == typeid ( CreateTableStatement ) ) + { + CreateTableStatement * createTable = dynamic_cast ( &stmt ); + bool matchedCol = false; + for ( unsigned i=0; i < createTable->fTableDef->fColumns.size(); i++ ) + { // if there are any constraints other than 'DEFAULT NULL' (which is the default in IDB), kill // the statement bool autoIncre = false; - uint64_t startValue = 1; - if (createTable->fTableDef->fColumns[i]->fConstraints.size() > 0 ) - { - //support default value and NOT NULL constraint - for (uint32_t j=0; j < createTable->fTableDef->fColumns[i]->fConstraints.size(); j++) + int64_t startValue = 1; + if (createTable->fTableDef->fColumns[i]->fConstraints.size() > 0 ) + { + //support default value and NOT NULL constraint + for (uint j=0; j < createTable->fTableDef->fColumns[i]->fConstraints.size(); j++) { if (createTable->fTableDef->fColumns[i]->fConstraints[j]->fConstraintType != DDL_NOT_NULL) { @@ -672,11 +591,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - } - } - + } + } + //check varbinary data type if ((createTable->fTableDef->fColumns[i]->fType->fType == ddlpackage::DDL_VARBINARY) && !isVarbinaryAllowed) { @@ -686,10 +605,10 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary is currently not supported by InfiniDB."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - - if ((createTable->fTableDef->fColumns[i]->fType->fType == ddlpackage::DDL_VARBINARY) && + + if ((createTable->fTableDef->fColumns[i]->fType->fType == ddlpackage::DDL_VARBINARY) && ((createTable->fTableDef->fColumns[i]->fType->fLength > 8000) || (createTable->fTableDef->fColumns[i]->fType->fLength < 8))) { rc = 1; @@ -698,9 +617,9 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary length has to be between 8 and 8000."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - + if (createTable->fTableDef->fColumns[i]->fDefaultValue) { if ((!createTable->fTableDef->fColumns[i]->fDefaultValue->fNull) && (createTable->fTableDef->fColumns[i]->fType->fType == ddlpackage::DDL_VARBINARY)) @@ -711,13 +630,13 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary column cannot have default value."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - + if (!createTable->fTableDef->fColumns[i]->fDefaultValue->fNull) { //validate the default value, if out of range, just error out - uint32_t dataType; + uint dataType; dataType = convertDataType(createTable->fTableDef->fColumns[i]->fType->fType); CalpontSystemCatalog::ColType colType; colType.colDataType = (CalpontSystemCatalog::ColDataType) dataType; @@ -736,8 +655,8 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; - } + return rc; + } if (pushWarning) { rc = 1; @@ -745,9 +664,9 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - if (((colType.colDataType == execplan::CalpontSystemCatalog::DATE) && (createTable->fTableDef->fColumns[i]->fDefaultValue->fValue =="0000-00-00")) || + if (((colType.colDataType == execplan::CalpontSystemCatalog::DATE) && (createTable->fTableDef->fColumns[i]->fDefaultValue->fValue =="0000-00-00")) || ((colType.colDataType == execplan::CalpontSystemCatalog::DATETIME) && (createTable->fTableDef->fColumns[i]->fDefaultValue->fValue =="0000-00-00 00:00:00"))) { rc = 1; @@ -755,11 +674,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } } - + //Parse the column comment string comment = createTable->fTableDef->fColumns[i]->fComment; int compressionType = compressionTypeIn; @@ -794,7 +713,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl #endif return rc; } - + try { #ifndef SKIP_AUTOI autoIncre = parseAutoincrementColumnComment(comment, startValue); @@ -810,7 +729,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl return rc; } #endif - + if (autoIncre) { //Check whether there is a column with autoincrement already @@ -829,7 +748,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl autoiColName = createTable->fTableDef->fColumns[i]->fName; matchedCol = true; } - + //Check whether the column has default value. If there is, error out if (createTable->fTableDef->fColumns[i]->fDefaultValue) { @@ -854,7 +773,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + } if (!autoIncre && isAnyAutoincreCol && (boost::iequals(autoiColName, createTable->fTableDef->fColumns[i]->fName))) { @@ -862,7 +781,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl matchedCol = true; startValue = nextvalue; } - + if (startValue <= 0) { rc = 1; @@ -872,20 +791,20 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if(autoIncre) - { - if (!validateAutoincrementDatatype(createTable->fTableDef->fColumns[i]->fType->fType)) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_INVALID_AUTOINCREMENT_TYPE)).c_str()); + { + if (!validateAutoincrementDatatype(createTable->fTableDef->fColumns[i]->fType->fType)) + { + rc = 1; + thd->main_da.can_overwrite_status = true; + thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_INVALID_AUTOINCREMENT_TYPE)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; - } - } - + return rc; + } + } + if (!validateNextValue(createTable->fTableDef->fColumns[i]->fType->fType, startValue)) { rc = 1; @@ -895,23 +814,14 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - - //hdfs - if ((compressionType ==0) && (useHdfs)) - { - compressionType = 2; - string errmsg ("The table is created with infinidb compression type 2 under HDFS." ); - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); - } - (createTable->fTableDef->fColumns[i]->fType)->fCompressiontype = compressionType; if (autoIncre) (createTable->fTableDef->fColumns[i]->fType)->fAutoincrement = "y"; else (createTable->fTableDef->fColumns[i]->fType)->fAutoincrement = "n"; - + (createTable->fTableDef->fColumns[i]->fType)->fNextvalue = startValue; - } + } if (isAnyAutoincreCol && !matchedCol) //@Bug 3555 error out on invalid column { @@ -924,10 +834,10 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - } - else if ( typeid ( stmt ) == typeid ( AlterTableStatement ) ) - { - AlterTableStatement * alterTable = dynamic_cast ( &stmt ); + } + else if ( typeid ( stmt ) == typeid ( AlterTableStatement ) ) + { + AlterTableStatement * alterTable = dynamic_cast ( &stmt ); if ( schema.length() == 0 ) { schema = alterTable->fTableName->fSchema; @@ -939,27 +849,27 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "No database selected."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } - ddlpackage::AlterTableActionList actionList = alterTable->fActions; + ddlpackage::AlterTableActionList actionList = alterTable->fActions; if (actionList.size() > 1) //@bug 3753 we don't support multiple actions in alter table statement { rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Multiple actions in alter table statement is currently not supported by InfiniDB."); - + ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - for ( unsigned i=0; i < actionList.size(); i++ ) - { - if ( ddlpackage::AtaAddColumn *addColumnPtr = dynamic_cast (actionList[i]) ) - { + for ( unsigned i=0; i < actionList.size(); i++ ) + { + if ( ddlpackage::AtaAddColumn *addColumnPtr = dynamic_cast (actionList[i]) ) + { //check varbinary data type if ((addColumnPtr->fColumnDef->fType->fType == ddlpackage::DDL_VARBINARY) && !isVarbinaryAllowed) { @@ -968,25 +878,25 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary is currently not supported by InfiniDB."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - - if ((addColumnPtr->fColumnDef->fType->fType == ddlpackage::DDL_VARBINARY) && + + if ((addColumnPtr->fColumnDef->fType->fType == ddlpackage::DDL_VARBINARY) && ((addColumnPtr->fColumnDef->fType->fLength > 8000) || (addColumnPtr->fColumnDef->fType->fLength < 8))) { rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary length has to be between 8 and 8000."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; + ci->alterTableState = cal_connection_info::NOT_ALTER; + ci->isAlter = false; + return rc; } - uint64_t startValue = 1; + int64_t startValue = 1; bool autoIncre = false; if ( (addColumnPtr->fColumnDef->fConstraints.size() > 0 ) || addColumnPtr->fColumnDef->fDefaultValue ) { - //support default value and NOT NULL constraint - for (uint32_t j=0; j < addColumnPtr->fColumnDef->fConstraints.size(); j++) + //support default value and NOT NULL constraint + for (uint j=0; j < addColumnPtr->fColumnDef->fConstraints.size(); j++) { if (addColumnPtr->fColumnDef->fConstraints[j]->fConstraintType != DDL_NOT_NULL) { @@ -995,12 +905,12 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } //if not null constraint, user has to provide a default value if ((addColumnPtr->fColumnDef->fConstraints[j]->fConstraintType == DDL_NOT_NULL) && (!addColumnPtr->fColumnDef->fDefaultValue)) { - + //do select count(*) from the table to check whether there are existing rows. if there is, error out. bool anyRow = false; try { @@ -1013,7 +923,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, ex.what()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } catch (...) { @@ -1022,7 +932,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Unknown exception caught when checking any rows in the table."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } if (anyRow) { @@ -1031,7 +941,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Table is not empty. New column has to have a default value if NOT NULL required."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } else if ((addColumnPtr->fColumnDef->fConstraints[j]->fConstraintType == DDL_NOT_NULL) &&(addColumnPtr->fColumnDef->fDefaultValue)) @@ -1043,11 +953,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "New column has to have a default value if NOT NULL required."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } } - + if (addColumnPtr->fColumnDef->fDefaultValue) { if ((!addColumnPtr->fColumnDef->fDefaultValue->fNull) && (addColumnPtr->fColumnDef->fType->fType == ddlpackage::DDL_VARBINARY)) @@ -1057,11 +967,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary column cannot have default value."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - + //validate the default value, if out of range, just error out - uint32_t dataType; + uint dataType; dataType = convertDataType(addColumnPtr->fColumnDef->fType->fType); CalpontSystemCatalog::ColType colType; colType.colDataType = (CalpontSystemCatalog::ColDataType) dataType; @@ -1080,8 +990,8 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; - } + return rc; + } if (pushWarning) { rc = 1; @@ -1089,9 +999,9 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - if (((colType.colDataType == execplan::CalpontSystemCatalog::DATE) && (addColumnPtr->fColumnDef->fDefaultValue->fValue =="0000-00-00")) || + if (((colType.colDataType == execplan::CalpontSystemCatalog::DATE) && (addColumnPtr->fColumnDef->fDefaultValue->fValue =="0000-00-00")) || ((colType.colDataType == execplan::CalpontSystemCatalog::DATETIME) && (addColumnPtr->fColumnDef->fDefaultValue->fValue =="0000-00-00 00:00:00"))) { rc = 1; @@ -1099,7 +1009,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } } @@ -1108,7 +1018,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl int compressionType = compressionTypeIn; if ( comment.length() > 0 ) { - //@Bug 3782 This is for synchronization after calonlinealter to use + //@Bug 3782 This is for synchronization after calonlinealter to use algorithm::to_upper(comment); regex pat("[[:space:]]*SCHEMA[[:space:]]+SYNC[[:space:]]+ONLY", regex_constants::extended); if (regex_search(comment, pat)) @@ -1128,7 +1038,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (( compressionType > 0 ) && !(idbCompress.isCompressionAvail( compressionType ))) { rc = 1; @@ -1144,14 +1054,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - - if ((compressionType ==0) && (useHdfs)) - { - compressionType = 2; - string errmsg ("The column is created with infinidb compression type 2 under HDFS." ); - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); - } - + try { #ifndef SKIP_AUTOI autoIncre = parseAutoincrementColumnComment(comment, startValue); @@ -1188,7 +1091,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl tableName.table = alterTable->fTableName->fName; CalpontSystemCatalog::TableInfo tblInfo; try { - tblInfo = csc->tableInfo(tableName); + tblInfo = csc->tableInfo(tableName); } catch (runtime_error& ex) { @@ -1199,7 +1102,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (tblInfo.tablewithautoincr == 1) { rc = 1; @@ -1209,7 +1112,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (!validateAutoincrementDatatype(addColumnPtr->fColumnDef->fType->fType)) { rc = 1; @@ -1228,7 +1131,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (startValue <= 0) { rc = 1; @@ -1237,7 +1140,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; return rc; - } + } } } addColumnPtr->fColumnDef->fType->fCompressiontype = compressionType; @@ -1245,38 +1148,38 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl addColumnPtr->fColumnDef->fType->fAutoincrement = "y"; else addColumnPtr->fColumnDef->fType->fAutoincrement = "n"; - + addColumnPtr->fColumnDef->fType->fNextvalue = startValue; - - } - else if ( dynamic_cast (actionList[i])) - { - rc = 1; + + } + else if ( dynamic_cast (actionList[i])) + { + rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; return rc; - } -/* else if ( dynamic_cast (actionList[i]) ) - { - rc = 1; + } +/* else if ( dynamic_cast (actionList[i]) ) + { + rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; return rc; - } + } else if ( dynamic_cast (actionList[i]) ) - { - rc = 1; + { + rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; return rc; - } + } */ else if ( ddlpackage::AtaAddColumns *addColumnsPtr = dynamic_cast(actionList[i])) { @@ -1289,7 +1192,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + //check varbinary data type if ((addColumnsPtr->fColumns[0]->fType->fType == ddlpackage::DDL_VARBINARY) && !isVarbinaryAllowed) { @@ -1298,11 +1201,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary is currently not supported by InfiniDB."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - - - if ((addColumnsPtr->fColumns[0]->fType->fType == ddlpackage::DDL_VARBINARY) && + + + if ((addColumnsPtr->fColumns[0]->fType->fType == ddlpackage::DDL_VARBINARY) && ((addColumnsPtr->fColumns[0]->fType->fLength > 8000) || (addColumnsPtr->fColumns[0]->fType->fLength < 8))) { rc = 1; @@ -1310,130 +1213,19 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary length has to be between 8 and 8000."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - uint64_t startValue = 1; + int64_t startValue = 1; bool autoIncre = false; - if ( (addColumnsPtr->fColumns[0]->fConstraints.size() > 0 ) || addColumnsPtr->fColumns[0]->fDefaultValue ) - { - //@Bug 5274. support default value and NOT NULL constraint - for (uint32_t j=0; j < addColumnsPtr->fColumns[0]->fConstraints.size(); j++) - { - if (addColumnsPtr->fColumns[0]->fConstraints[j]->fConstraintType != DDL_NOT_NULL) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - //if not null constraint, user has to provide a default value - if ((addColumnsPtr->fColumns[0]->fConstraints[j]->fConstraintType == DDL_NOT_NULL) && (!addColumnsPtr->fColumns[0]->fDefaultValue)) - { - - //do select count(*) from the table to check whether there are existing rows. if there is, error out. - bool anyRow = false; - try { - anyRow = anyRowInTable(alterTable->fTableName->fSchema, alterTable->fTableName->fName, sessionID); - } - catch (runtime_error& ex) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, ex.what()); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - catch (...) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Unknown exception caught when checking any rows in the table."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - if (anyRow) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Table is not empty. New column has to have a default value if NOT NULL required."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - } - else if ((addColumnsPtr->fColumns[0]->fConstraints[j]->fConstraintType == DDL_NOT_NULL) &&(addColumnsPtr->fColumns[0]->fDefaultValue)) - { - if (addColumnsPtr->fColumns[0]->fDefaultValue->fValue.length() == 0) //empty string is NULL in infinidb - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "New column has to have a default value if NOT NULL required."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - } - } - - if (addColumnsPtr->fColumns[0]->fDefaultValue) - { - if ((!addColumnsPtr->fColumns[0]->fDefaultValue->fNull) && (addColumnsPtr->fColumns[0]->fType->fType == ddlpackage::DDL_VARBINARY)) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Varbinary column cannot have default value."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - - //validate the default value, if out of range, just error out - uint32_t dataType; - dataType = convertDataType(addColumnsPtr->fColumns[0]->fType->fType); - CalpontSystemCatalog::ColType colType; - colType.colDataType = (CalpontSystemCatalog::ColDataType) dataType; - colType.colWidth = addColumnsPtr->fColumns[0]->fType->fLength; - colType.precision = addColumnsPtr->fColumns[0]->fType->fPrecision; - colType.scale = addColumnsPtr->fColumns[0]->fType->fScale; - boost::any convertedVal; - bool pushWarning = false; - try { - convertedVal = DataConvert::convertColumnData(colType, addColumnsPtr->fColumns[0]->fDefaultValue->fValue, pushWarning, false, false ); - } - catch(std::exception&) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - if (pushWarning) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - if (((colType.colDataType == execplan::CalpontSystemCatalog::DATE) && (addColumnsPtr->fColumns[0]->fDefaultValue->fValue =="0000-00-00")) || - ((colType.colDataType == execplan::CalpontSystemCatalog::DATETIME) && (addColumnsPtr->fColumns[0]->fDefaultValue->fValue =="0000-00-00 00:00:00"))) - { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The default value is out of range for the specified data type."); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; - } - } - } + if ( (addColumnsPtr->fColumns[0]->fConstraints.size() > 0 ) || addColumnsPtr->fColumns[0]->fDefaultValue ) + { + rc = 1; + thd->main_da.can_overwrite_status = true; + thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); + ci->alterTableState = cal_connection_info::NOT_ALTER; + ci->isAlter = false; + return rc; + } //Handle compression type string comment = addColumnsPtr->fColumns[0]->fComment; int compressionType = compressionTypeIn; @@ -1452,7 +1244,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (( compressionType > 0 ) && !(idbCompress.isCompressionAvail( compressionType ))) { rc = 1; @@ -1468,15 +1260,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - - if ((compressionType ==0) && (useHdfs)) - { - compressionType = 2; - string errmsg ("The column is created with infinidb compression type 2 under HDFS." ); - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); - } - - + try { #ifndef SKIP_AUTOI autoIncre = parseAutoincrementColumnComment(comment, startValue); @@ -1513,7 +1297,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl tableName.table = alterTable->fTableName->fName; CalpontSystemCatalog::TableInfo tblInfo; try { - tblInfo = csc->tableInfo(tableName); + tblInfo = csc->tableInfo(tableName); } catch (runtime_error& ex) { @@ -1524,7 +1308,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (tblInfo.tablewithautoincr == 1) { rc = 1; @@ -1534,7 +1318,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (!validateAutoincrementDatatype(addColumnsPtr->fColumns[0]->fType->fType)) { rc = 1; @@ -1559,7 +1343,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_NEGATIVE_STARTVALUE)).c_str()); return rc; - } + } } } addColumnsPtr->fColumns[0]->fType->fCompressiontype = compressionType; @@ -1567,15 +1351,15 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl addColumnsPtr->fColumns[0]->fType->fAutoincrement = "y"; else addColumnsPtr->fColumns[0]->fType->fAutoincrement = "n"; - + addColumnsPtr->fColumns[0]->fType->fNextvalue = startValue; } else if (ddlpackage::AtaRenameColumn* renameColumnsPtr = dynamic_cast(actionList[i])) { //cout << "Rename a column" << endl; - uint64_t startValue = 1; + int64_t startValue = 1; bool autoIncre = false; - //@Bug 3746 Handle compression type + //@Bug 3746 Handle compression type string comment = renameColumnsPtr->fComment; int compressionType = compressionTypeIn; if ( comment.length() > 0 ) @@ -1593,7 +1377,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + if (( compressionType > 0 ) && !(idbCompress.isCompressionAvail( compressionType ))) { rc = 1; @@ -1609,19 +1393,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - - if ((compressionType ==0) && (useHdfs)) - { - compressionType = 2; - string errmsg ("The column is created with infinidb compression type 2 under HDFS." ); - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); - } - } - + //Handle autoincrement if ( comment.length() > 0 ) - { + { try { #ifndef SKIP_AUTOI autoIncre = parseAutoincrementColumnComment(comment, startValue); @@ -1637,7 +1413,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl return rc; } #endif - + } catch (runtime_error& ex) { @@ -1651,22 +1427,22 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl if (autoIncre) { //Check if the table already has autoincrement column + boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + csc->identity(execplan::CalpontSystemCatalog::FE); CalpontSystemCatalog::TableName tableName; tableName.schema = alterTable->fTableName->fSchema; tableName.table = alterTable->fTableName->fName; - //CalpontSystemCatalog::TableInfo tblInfo = csc->tableInfo(tableName); - - //@Bug 5444. rename column doen't need to check this. - /* if (tblInfo.tablewithautoincr == 1) + CalpontSystemCatalog::TableInfo tblInfo = csc->tableInfo(tableName); + + if (tblInfo.tablewithautoincr == 1) { rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_INVALID_NUMBER_AUTOINCREMENT)).c_str()); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; + ci->alterTableState = cal_connection_info::NOT_ALTER;ci->isAlter = false; return rc; - } */ - + } + if (!validateAutoincrementDatatype(renameColumnsPtr->fNewType->fType)) { rc = 1; @@ -1685,21 +1461,21 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl ci->isAlter = false; return rc; } - + } } - + if (autoIncre) renameColumnsPtr->fNewType->fAutoincrement = "y"; else renameColumnsPtr->fNewType->fAutoincrement = "n"; - + renameColumnsPtr->fNewType->fNextvalue = startValue; renameColumnsPtr->fNewType->fCompressiontype = compressionType; - + if (renameColumnsPtr->fConstraints.size() > 0) { - for (uint32_t j=0; j < renameColumnsPtr->fConstraints.size(); j++) + for (uint j=0; j < renameColumnsPtr->fConstraints.size(); j++) { if (renameColumnsPtr->fConstraints[j]->fConstraintType == DDL_NOT_NULL) { @@ -1715,7 +1491,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, ex.what()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } catch (...) { @@ -1724,7 +1500,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Unknown exception caught when checking any existing null values in the column."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } if (anyNullVal) { @@ -1733,7 +1509,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The existing rows in this column has null value already."); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } else @@ -1743,7 +1519,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CONSTRAINTS)).c_str()); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } } } @@ -1751,21 +1527,11 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl else { } - } - } - //@Bug 5923 error out on unsupported statements. - else if (( typeid ( stmt ) != typeid ( DropTableStatement )) && ( typeid ( stmt ) != typeid ( TruncTableStatement )) - && ( typeid ( stmt ) != typeid ( MarkPartitionStatement )) && ( typeid ( stmt ) != typeid ( RestorePartitionStatement )) - && ( typeid ( stmt ) != typeid ( DropPartitionStatement ))) + } + } + else { - rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_SYNTAX)).c_str()); - ci->alterTableState = cal_connection_info::NOT_ALTER; - ci->isAlter = false; - return rc; } - //@Bug 4387 scoped_ptr dbrmp(new DBRM()); int rc = dbrmp->isReadWrite(); @@ -1776,64 +1542,64 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Cannot execute the statement. DBRM is read only!"); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - return rc; + return rc; } - stmt.fSessionID = sessionID; - stmt.fSql = ddlStatement; + stmt.fSessionID = sessionID; + stmt.fSql = ddlStatement; stmt.fOwner = schema; stmt.fTableWithAutoi = isAnyAutoincreCol; //cout << "Sending to DDLProc" << endl; - ByteStream bytestream; - bytestream << stmt.fSessionID; - stmt.serialize(bytestream); - MessageQueueClient mq("DDLProc"); - ByteStream::byte b=0; - try - { - mq.write(bytestream); - bytestream = mq.read(); + ByteStream bytestream; + bytestream << stmt.fSessionID; + stmt.serialize(bytestream); + MessageQueueClient mq("DDLProc"); + ByteStream::byte b=0; + try + { + mq.write(bytestream); + bytestream = mq.read(); if ( bytestream.length() == 0 ) { rc = 1; - thd->main_da.can_overwrite_status = true; + thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DDLProc"); + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DDLProc"); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; } else { - bytestream >> b; - bytestream >> emsg; - rc = b; + bytestream >> b; + bytestream >> emsg; + rc = b; } - } - catch (runtime_error&) - { - rc =1; - thd->main_da.can_overwrite_status = true; + } + catch (runtime_error&) + { + rc =1; + thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DDLProc"); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - } - catch (...) - { - rc = 1; - thd->main_da.can_overwrite_status = true; + } + catch (...) + { + rc = 1; + thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Unknown error caught"); ci->alterTableState = cal_connection_info::NOT_ALTER; ci->isAlter = false; - } + } - if ((b != 0) && (b!=ddlpackageprocessor::DDLPackageProcessor::WARNING)) - { - thd->main_da.can_overwrite_status = true; + if ((b != 0) && (b!=ddlpackageprocessor::DDLPackageProcessor::WARNING)) + { + thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, emsg.c_str()); - } + } if (b ==ddlpackageprocessor::DDLPackageProcessor::WARNING) { @@ -1841,7 +1607,7 @@ int ProcessDDLStatement(string& ddlStatement, string& schema, const string& tabl string errmsg ("Error occured during file deletion. Restart DMLProc or use command tool ddlcleanup to clean up. " ); push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); } - return rc; + return rc; } else @@ -1895,36 +1661,37 @@ pair parseTableName(const string& tn) int ha_calpont_impl_create_(const char *name, TABLE *table_arg, HA_CREATE_INFO *create_info, cal_connection_info& ci) { #ifdef INFINIDB_DEBUG - cout << "ha_calpont_impl_create_: " << name << endl; + cout << "ha_calpont_impl_create_: " << name << endl; #endif - THD *thd = current_thd; + THD *thd = current_thd; - string stmt = idb_mysql_query_str(thd); - stmt += ";"; - algorithm::to_upper(stmt); + string stmt = thd->query; + stmt += ";"; + algorithm::to_upper(stmt); - string db = table_arg->s->db.str; - string tbl = table_arg->s->table_name.str; + string db = table_arg->s->db.str; + string tbl = table_arg->s->table_name.str; string tablecomment; bool isAnyAutoincreCol = false; std::string columnName(""); - uint64_t startValue = 1; + int64_t startValue = 1; if (table_arg->s->comment.length > 0 ) { tablecomment = table_arg->s->comment.str; try { #ifndef SKIP_AUTOI - isAnyAutoincreCol = parseAutoincrementTableComment(tablecomment, startValue, columnName); + isAnyAutoincreCol = parseAutoincrementTableComment(tablecomment, startValue, columnName); #else - algorithm::to_upper(tablecomment); - if ( tablecomment.find("AUTOINCREMENT") != string::npos ) - { - int rc = 1; - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CREATE_AUTOINCREMENT_NOT_SUPPORT)).c_str()); - return rc; - } + algorithm::to_upper(tablecomment); + if ( tablecomment.find("AUTOINCREMENT") != string::npos ) + { + int rc = 1; + thd->main_da.can_overwrite_status = true; + thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_CREATE_AUTOINCREMENT_NOT_SUPPORT)).c_str()); + return rc; + } #endif + } catch (runtime_error& ex) { @@ -1940,86 +1707,74 @@ int ha_calpont_impl_create_(const char *name, TABLE *table_arg, HA_CREATE_INFO * bool schemaSyncOnly = false; bool isCreate = true; - // relate to bug 1793. Make sure this is not for a select statement because - if (db == "calpontsys" && thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT - && tbl != "systable" - && tbl != "syscolumn" && tbl != "sysindex" - && tbl != "sysconstraint" && tbl != "sysindexcol" - && tbl != "sysconstraintcol" ) - { - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Can not create non-system Calpont tables in calpontsys database"); - return 1; - } + // relate to bug 1793. Make sure this is not for a select statement because + if (db == "calpontsys" && thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT + && tbl != "systable" + && tbl != "syscolumn" && tbl != "sysindex" + && tbl != "sysconstraint" && tbl != "sysindexcol" + && tbl != "sysconstraintcol" ) + { + thd->main_da.can_overwrite_status = true; + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Can not create non-system Calpont tables in calpontsys database"); + return 1; + } - regex pat("[[:space:]]*SCHEMA[[:space:]]+SYNC[[:space:]]+ONLY", regex_constants::extended); - if (regex_search(tablecomment, pat)) - { + regex pat("[[:space:]]*SCHEMA[[:space:]]+SYNC[[:space:]]+ONLY", regex_constants::extended); + if (regex_search(tablecomment, pat)) + { schemaSyncOnly = true; pat = createpatstr; if (!regex_search(stmt, pat)) { isCreate = false; - } - - if (isCreate) - { + } + + if (isCreate) + { #ifdef INFINIDB_DEBUG - cout << "ha_calpont_impl_create_: SCHEMA SYNC ONLY found, returning" << endl; + cout << "ha_calpont_impl_create_: SCHEMA SYNC ONLY found, returning" << endl; #endif - return 0; + return 0; } else if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ALTER_VTABLE) //check if it is select { return 0; } - } - else - { - if (db == "calpontsys") - { + } + else + { + if (db == "calpontsys") + { thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Calpont system tables can only be created with 'SCHEMA SYNC ONLY'"); return 1; - } + } else if ( db == "infinidb_vtable") //@bug 3540. table created in infinidb_vtable schema could be dropped when select statement happen to have same tablename. { thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Table creation is not allowed in infinidb_vtable schema."); return 1; } - } - - pat = alterpatstr; - if (regex_search(stmt, pat)) { + } + + pat = alterpatstr; + if (regex_search(stmt, pat)) { ci.isAlter = true; - ci.alterTableState = cal_connection_info::ALTER_FIRST_RENAME; + ci.alterTableState = cal_connection_info::ALTER_FIRST_RENAME; #ifdef INFINIDB_DEBUG cout << "ha_calpont_impl_create_: now in state ALTER_FIRST_RENAME" << endl; #endif } - string emsg; - stmt = idb_mysql_query_str(thd); - stmt += ";"; - int rc = 0; + + string emsg; + stmt = thd->query; + stmt += ";"; + int rc = 0; // Don't do the DDL (only for create table if this is SSO. Should only get here on ATAC w/SSO. if ( schemaSyncOnly && isCreate) return rc; - - //this is replcated DDL, treat it just like SSO - if (thd->slave_thread) - return rc; - - //@bug 5660. Error out REAL DDL/DML on slave node. - // When the statement gets here, it's NOT SSO or RESTRICT - if (ci.isSlaveNode) - { - string emsg = logging::IDBErrorInfo::instance()->errorMsg(ERR_DML_DDL_SLAVE); - setError(current_thd, HA_ERR_UNSUPPORTED, emsg); - return 1; - } - + // @bug 3908. error out primary key for now. if (table_arg->key_info && table_arg->key_info->name && string(table_arg->key_info->name) == "PRIMARY") { @@ -2033,7 +1788,6 @@ int ha_calpont_impl_create_(const char *name, TABLE *table_arg, HA_CREATE_INFO * } int compressiontype = thd->variables.infinidb_compression_type; - if (compressiontype == 1) compressiontype = 2; //string tablecomment; if (table_arg->s->comment.length > 0 ) @@ -2050,18 +1804,9 @@ int ha_calpont_impl_create_(const char *name, TABLE *table_arg, HA_CREATE_INFO * ci.alterTableState = cal_connection_info::NOT_ALTER; ci.isAlter = false; return rc; - } - - //hdfs - if ((compressiontype ==0) && (useHdfs)) - { - compressiontype = 2; - string errmsg ("The table is created with infinidb compression type 2 under HDFS." ); - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); - } - + } if (compressiontype == 1) compressiontype = 2; - + IDBCompressInterface idbCompress; if ( ( compressiontype > 0 ) && !(idbCompress.isCompressionAvail( compressiontype )) ) { @@ -2077,66 +1822,53 @@ int ha_calpont_impl_create_(const char *name, TABLE *table_arg, HA_CREATE_INFO * ci.alterTableState = cal_connection_info::NOT_ALTER; ci.isAlter = false; return rc; - } - + } + rc = ProcessDDLStatement(stmt, db, tbl, tid2sid(thd->thread_id), emsg, compressiontype, isAnyAutoincreCol, startValue, columnName); - - if (rc != 0) { - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, 9999, emsg.c_str()); - //Bug 1705 reset the flag if error occurs - ci.alterTableState = cal_connection_info::NOT_ALTER; + + if (rc != 0) { + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, 9999, emsg.c_str()); + //Bug 1705 reset the flag if error occurs + ci.alterTableState = cal_connection_info::NOT_ALTER; ci.isAlter = false; #ifdef INFINIDB_DEBUG cout << "ha_calpont_impl_create_: ProcessDDL error, now in state NOT_ALTER" << endl; #endif - } - return rc; + } + return rc; } int ha_calpont_impl_delete_table_(const char *name, cal_connection_info& ci) { #ifdef INFINIDB_DEBUG - cout << "ha_calpont_impl_delete_table: " << name << endl; + cout << "ha_calpont_impl_delete_table: " << name << endl; #endif - THD *thd = current_thd; - std::string tbl(name); - std::string stmt(idb_mysql_query_str(thd)); - algorithm::to_upper(stmt); + THD *thd = current_thd; + std::string tbl(name); + std::string stmt(thd->query); + algorithm::to_upper(stmt); // @bug 4158 allow table name with 'restrict' in it (but not by itself) std::string::size_type fpos; fpos = stmt.rfind(" RESTRICT"); if ((fpos != std::string::npos) && ((stmt.size() - fpos) == 9)) //last 9 chars of stmt are " RESTRICT" - { - return 0; - } - - //this is replcated DDL, treat it just like SSO - if (thd->slave_thread) - return 0; + { + return 0; + } - //@bug 5660. Error out REAL DDL/DML on slave node. - // When the statement gets here, it's NOT SSO or RESTRICT - if (ci.isSlaveNode) - { - string emsg = logging::IDBErrorInfo::instance()->errorMsg(ERR_DML_DDL_SLAVE); - setError(current_thd, HA_ERR_UNSUPPORTED, emsg); - return 1; - } - - TABLE_LIST *first_table= (TABLE_LIST*) thd->lex->select_lex.table_list.first; + TABLE_LIST *first_table= (TABLE_LIST*) thd->lex->select_lex.table_list.first; string db = first_table->table->s->db.str; - string emsg; - stmt = idb_mysql_query_str(thd); - stmt += ";"; - int rc = ProcessDDLStatement(stmt, db, tbl, tid2sid(thd->thread_id), emsg); - if (rc != 0) - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, 9999, emsg.c_str()); - return rc; + string emsg; + stmt = thd->query; + stmt += ";"; + int rc = ProcessDDLStatement(stmt, db, tbl, tid2sid(thd->thread_id), emsg); + if (rc != 0) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, 9999, emsg.c_str()); + return rc; } int ha_calpont_impl_rename_table_(const char* from, const char* to, cal_connection_info& ci) { - THD *thd = current_thd; + THD *thd = current_thd; string emsg; ostringstream stmt1; @@ -2144,26 +1876,14 @@ int ha_calpont_impl_rename_table_(const char* from, const char* to, cal_connecti pair toPair; string stmt; - //this is replcated DDL, treat it just like SSO - if (thd->slave_thread) - return 0; - - //@bug 5660. Error out REAL DDL/DML on slave node. - // When the statement gets here, it's NOT SSO or RESTRICT - if (ci.isSlaveNode) - { - string emsg = logging::IDBErrorInfo::instance()->errorMsg(ERR_DML_DDL_SLAVE); - setError(current_thd, HA_ERR_UNSUPPORTED, emsg); - return 1; - } - fromPair = parseTableName(from); toPair = parseTableName(to); if (fromPair.first != toPair.first) { thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Both tables must be in the same database to use RENAME TABLE"); + + thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Both tables must be in the same database to use RENAME TABLE"); return -1; } @@ -2176,8 +1896,8 @@ int ha_calpont_impl_rename_table_(const char* from, const char* to, cal_connecti else if ( fromPair.first.length() !=0 ) db = fromPair.first; else - db = toPair.first; - + db = toPair.first; + int rc = ProcessDDLStatement(stmt, db, "", tid2sid(thd->thread_id), emsg); if (rc != 0) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, 9999, emsg.c_str()); @@ -2198,27 +1918,12 @@ long long calonlinealter(UDF_INIT* initid, UDF_ARGS* args, string stmt(args->args[0], args->lengths[0]); string emsg; - THD *thd = current_thd; + THD *thd = current_thd; string db(""); if ( thd->db ) db = thd->db; - - int compressiontype = thd->variables.infinidb_compression_type; - - if (compressiontype == 1) compressiontype = 2; - - if ( compressiontype == MAX_INT ) - compressiontype = thd->variables.infinidb_compression_type; - - //hdfs - if ((compressiontype ==0) && (useHdfs)) - { - compressiontype = 2; - } - - if (compressiontype == 1) compressiontype = 2; - - int rc = ProcessDDLStatement(stmt, db, "", tid2sid(thd->thread_id), emsg, compressiontype); + + int rc = ProcessDDLStatement(stmt, db, "", tid2sid(thd->thread_id), emsg); if (rc != 0) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, 9999, emsg.c_str()); diff --git a/dbcon/mysql/ha_calpont_dml.cpp b/dbcon/mysql/ha_calpont_dml.cpp index 2e6806d4..e000527e 100644 --- a/dbcon/mysql/ha_calpont_dml.cpp +++ b/dbcon/mysql/ha_calpont_dml.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: ha_calpont_dml.cpp 9711 2013-07-23 21:01:27Z chao $ + * $Id: ha_calpont_dml.cpp 8792 2012-08-07 18:34:27Z chao $ */ #include @@ -64,7 +64,6 @@ using namespace messageqcpp; using namespace config; #include "calpontsystemcatalog.h" -using namespace execplan; #include "resourcemanager.h" using namespace joblist; @@ -77,7 +76,6 @@ namespace { ResourceManager rm; uint64_t fBatchInsertGroupRows = rm.getRowsPerBatch(); -bool useHdfs = rm.useHdfs(); //convenience fcn inline uint32_t tid2sid(const uint32_t tid) @@ -182,11 +180,15 @@ uint32_t buildValueList (TABLE* table, cal_connection_info& ci ) &my_charset_bin); uint32_t size=0; int columnPos = 0; - double dbval; for (Field** field = table->field; *field; field++) { + const char* ptr; + const char* end_ptr; + double dbval; + if((*field)->is_null()) { + ptr = end_ptr =0; ci.tableValuesMap[columnPos].push_back (""); //currently, empty string is treated as null. } else @@ -207,13 +209,19 @@ uint32_t buildValueList (TABLE* table, cal_connection_info& ci ) { //fetch different data type (*field)->val_str(&attribute, &attribute); - if (attribute.length() == 0) + ptr = attribute.ptr(); + end_ptr = attribute.length() + ptr; + if (ptr == end_ptr) { ci.tableValuesMap[columnPos].push_back (""); //currently, empty string is treated as null. } else { - string val(attribute.ptr(),attribute.length()); + string val; + while (ptr < end_ptr) + { + val += *ptr++; + } ci.tableValuesMap[columnPos].push_back(val); } } @@ -227,18 +235,22 @@ uint32_t buildValueList (TABLE* table, cal_connection_info& ci ) return size; } - int ProcessCommandStatement(THD *thd, string& dmlStatement, cal_connection_info& ci, std::string schema="") { int rc = 0; - ulong sessionID = tid2sid(thd->thread_id); + bool isRollback = false; + + //MySQL server pukes if rollback ever fails. If DMLProc isn't running, rollback will fail. + if (dmlStatement == "ROLLBACK") isRollback = true; + if (dmlStatement == "COMMIT") isRollback = false; + ulong sessionID = tid2sid(thd->thread_id); CalpontDMLPackage* pDMLPackage; //@Bug 2721 and 2722. Log the statement before issuing commit/rollback if ( dmlStatement == "LOGGING" ) { - VendorDMLStatement cmdStmt(idb_mysql_query_str(thd), DML_COMMAND, sessionID); + VendorDMLStatement cmdStmt(thd->query, DML_COMMAND, sessionID); cmdStmt.set_Logging( false ); pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(cmdStmt); pDMLPackage->set_Logging( false ); @@ -258,16 +270,15 @@ int ProcessCommandStatement(THD *thd, string& dmlStatement, cal_connection_info& if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) pDMLPackage->set_isAutocommitOn(true); - - if (useHdfs) - pDMLPackage->set_isAutocommitOn(true); ByteStream bytestream; - bytestream << static_cast(sessionID); + bytestream << static_cast(sessionID); pDMLPackage->write(bytestream); delete pDMLPackage; + idbassert( ci.dmlProc ); + ByteStream::byte b = 0; string errormsg; ByteStream::octbyte rows; @@ -281,7 +292,7 @@ int ProcessCommandStatement(THD *thd, string& dmlStatement, cal_connection_info& thd->killed = THD::KILL_QUERY; thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc [1]"); + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc"); } else { @@ -296,7 +307,7 @@ int ProcessCommandStatement(THD *thd, string& dmlStatement, cal_connection_info& thd->killed = THD::KILL_QUERY; thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc [2]"); + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc"); } catch (...) { @@ -313,8 +324,7 @@ int ProcessCommandStatement(THD *thd, string& dmlStatement, cal_connection_info& thd->killed = THD::KILL_QUERY; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, errormsg.c_str()); } - delete ci.dmlProc; - ci.dmlProc = NULL; + return rc; } @@ -325,7 +335,7 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci int rc = 0; - VendorDMLStatement dmlStmts(idb_mysql_query_str(thd), DML_INSERT, table->s->table_name.str, + VendorDMLStatement dmlStmts(thd->query, DML_INSERT, table->s->table_name.str, table->s->db.str, size, ci.colNameList.size(), ci.colNameList, ci.tableValuesMap, sessionID); @@ -389,15 +399,16 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci //cout << "autocommit is on" << endl; pDMLPackage->set_isAutocommitOn(true); } - else if (useHdfs) + else { - pDMLPackage->set_isAutocommitOn(true); + //cout << "autocommit is off" << endl; } ByteStream bytestream, bytestreamRcv; bytestream << sessionID; pDMLPackage->write(bytestream); delete pDMLPackage; + idbassert( ci.dmlProc ); ByteStream::byte b = 0; string errormsg; @@ -413,7 +424,6 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci { delete ci.dmlProc; ci.dmlProc = new MessageQueueClient("DMLProc"); - //cout << "doProcessInsertValues starts a client " << ci.dmlProc << " for session " << thd->thread_id << endl; try { ci.dmlProc->write(bytestream); @@ -422,7 +432,7 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci { rc = -1; b=1; - errormsg = "Lost connection to DMLProc [3]"; + errormsg = "Lost connection to DMLProc"; } else { @@ -436,7 +446,7 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci { rc = -1; thd->main_da.can_overwrite_status = true; - errormsg = "Lost connection to DMLProc [4]"; + errormsg = "Lost connection to DMLProc"; b = 1; } } @@ -449,14 +459,13 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci rc = b; } } - catch (std::exception& rex) + catch (runtime_error&) { //check if it is first batch and DMLProc restarted. Only this case, get a new client and resend if (ci.rowsHaveInserted == 0) { delete ci.dmlProc; ci.dmlProc = new MessageQueueClient("DMLProc"); - //cout << "doProcessInsertValues exception starts a client " << ci.dmlProc << " for session " << thd->thread_id << endl; try { ci.dmlProc->write(bytestream); @@ -465,7 +474,7 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci { rc = -1; b=1; - errormsg = string("Lost connection to DMLProc after getting a new client [1:") + rex.what() + "]"; + errormsg = "Lost connection to DMLProc"; } else { @@ -475,11 +484,11 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci rc = b; } } - catch (std::exception& rrex) + catch (runtime_error&) { rc = -1; thd->main_da.can_overwrite_status = true; - errormsg = string("Lost connection to DMLProc after getting a new client [2:") + rex.what() + " then " + rrex.what() + "]"; + errormsg = "Lost connection to DMLProc"; b = 1; } } @@ -487,7 +496,7 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci { rc = -1; thd->main_da.can_overwrite_status = true; - errormsg = string("Lost connection to DMLProc really [1:") + rex.what() + "]"; + errormsg = "Lost connection to DMLProc"; b = 1; } } @@ -511,7 +520,8 @@ int doProcessInsertValues ( TABLE* table, uint32_t size, cal_connection_info& ci if ( b == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING ) { rc = 0; - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errormsg.c_str()); + string errmsg ("Out of range value detected. Please check Calpont Syntax Guide for supported data range." ); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errmsg.c_str()); } if ( rc != 0 ) @@ -535,15 +545,11 @@ int ha_calpont_impl_write_last_batch(TABLE* table, cal_connection_info& ci, bool command = "COMMIT"; std::string schema; schema = table->s->db.str; - //@Bug 6112. if no row to be insert and no rows have been inserted, no need to send to DMLProc - if ((size == 0) && (ci.rowsHaveInserted == 0)) - return rc; //@Bug 2715 Check the saved error code. //@Bug 4516 always send the last package to allow DMLProc receive all messages from WES if (( ci.rc != 0 ) || abort ) { - if (abort) //@Bug 5285. abort is different from error, dmlproc only clean up when erroring out - rc = doProcessInsertValues( table, size , ci, true); + rc = doProcessInsertValues( table, size , ci, true); //@Bug 2722 Log the statement into datamod log //@Bug 4605 if error, rollback and no need to check whether the session is autocommit off @@ -582,12 +588,6 @@ int ha_calpont_impl_write_last_batch(TABLE* table, cal_connection_info& ci, bool command = "COMMIT"; ProcessCommandStatement ( thd, command, ci, schema ); } - else if (useHdfs) - { - ci.rowsHaveInserted += size; - command = "COMMIT"; - ProcessCommandStatement ( thd, command, ci, schema ); - } else if (( rc != 0) || abort ) { command = "ROLLBACK"; @@ -668,12 +668,7 @@ int ha_calpont_impl_write_row_(uchar *buf, TABLE* table, cal_connection_info& ci { command = "COMMIT"; ProcessCommandStatement ( thd, command, ci, schema ); - } - else if (useHdfs) - { - command = "COMMIT"; - ProcessCommandStatement ( thd, command, ci, schema ); - } + } } } //timer.stop( "DMLProc takes"); @@ -687,853 +682,6 @@ int ha_calpont_impl_write_row_(uchar *buf, TABLE* table, cal_connection_info& ci } } -int ha_calpont_impl_write_batch_row_(uchar *buf, TABLE* table, cal_impl_if::cal_connection_info& ci) -{ - ByteStream rowData; - int rc = 0; - //std::ostringstream data; - bool nullVal = false; - uchar *bufHdr = buf; - uint16_t colpos = 0; - buf = buf + ci.headerLength; - //char delimiter = '|'; - //char delimiter = '\7'; - //@Bug 6122 if all columns have not null constraint, there is no information in the header - while (colpos < ci.columnTypes.size()) //test bitmap for null values - { - char tmp = *bufHdr++; - uint8_t numLoop = 7; - if ((ci.useXbit) || (colpos > 6)) - numLoop++; - - for (uint8_t i = 0; i < numLoop; i++) - { - if (colpos == ci.columnTypes.size()) - break; - - //if a column has not null constraint, it will not be in the bit map - if (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT) - { - if (!ci.useXbit && (colpos == 0)) - { - tmp = tmp>>1; - } - nullVal = tmp & 0x01; - tmp = tmp>>1; - } - else - nullVal = false; - - switch (ci.columnTypes[colpos].colDataType) - { - case CalpontSystemCatalog::DATE: //date fetch - { - - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - { - fprintf(ci.filePtr, "%c", ci.delimiter); - } - else - { - uchar *tmp1 = buf; - uint32_t tmp = (tmp1[2] << 16) + (tmp1[1] << 8) + tmp1[0]; - - int day = tmp & 0x0000001fl; - int month = (tmp >> 5) & 0x0000000fl; - int year = tmp >> 9; - fprintf(ci.filePtr, "%04d-%02d-%02d%c", year,month,day,ci.delimiter); - } - buf += 3; - break; - } - case CalpontSystemCatalog::DATETIME: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - { - fprintf(ci.filePtr, "%c", ci.delimiter); - } - else - { - long long value = *((long long*) buf); - long datePart = (long) (value/1000000ll); - int day = datePart % 100; - int month = (datePart/100) % 100; - int year = datePart/10000; - fprintf(ci.filePtr, "%04d-%02d-%02d ", year,month,day); - - long timePart = (long) (value - (long long) datePart*1000000ll); - int second = timePart % 100; - int min = (timePart/100) % 100; - int hour = timePart/10000; - fprintf(ci.filePtr, "%02d:%02d:%02d%c", hour,min,second, ci.delimiter); - } - buf += 8; - break; - } - case CalpontSystemCatalog::CHAR: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - { - fprintf(ci.filePtr, "%c", ci.delimiter); - } - else - fprintf(ci.filePtr, "%.*s%c", ci.columnTypes[colpos].colWidth, buf, ci.delimiter); - - if (ci.utf8) - buf += (ci.columnTypes[colpos].colWidth * 3); - else - buf += ci.columnTypes[colpos].colWidth; - break; - } - case CalpontSystemCatalog::VARCHAR: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - { - fprintf(ci.filePtr, "%c", ci.delimiter); - if (!ci.utf8) - { - if (ci.columnTypes[colpos].colWidth < 256) - { - buf++; - } - else - { - buf = buf + 2 ; - } - } - else //utf8 - { - if (ci.columnTypes[colpos].colWidth < 86) - { - buf++; - } - else - { - buf = buf + 2 ; - } - } - } - else - { - int dataLength = 0; - if (!ci.utf8) - { - if (ci.columnTypes[colpos].colWidth < 256) - { - dataLength = *(int8_t*) buf; - buf++; - } - else - { - dataLength = *(int16_t*) buf; - buf = buf + 2 ; - } - fprintf(ci.filePtr, "%.*s%c", dataLength, buf, ci.delimiter); - } - else //utf8 - { - if (ci.columnTypes[colpos].colWidth < 86) - { - dataLength = *(int8_t*) buf; - buf++; - } - else - { - dataLength = *(uint16_t*) buf; - buf = buf + 2 ; - } - if ( dataLength > ci.columnTypes[colpos].colWidth) - dataLength = ci.columnTypes[colpos].colWidth; - - fprintf(ci.filePtr, "%.*s%c", dataLength, buf, ci.delimiter); - } - } - //buf += ci.columnTypes[colpos].colWidth; - if (ci.utf8) - buf += (ci.columnTypes[colpos].colWidth * 3); - else - buf += ci.columnTypes[colpos].colWidth; - - break; - } - case CalpontSystemCatalog::BIGINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%lld%c", *((long long*)buf), ci.delimiter); - - buf += 8; - break; - } - case CalpontSystemCatalog::UBIGINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%llu%c", *((long long unsigned*)buf), ci.delimiter); - buf += 8; - break; - } - case CalpontSystemCatalog::INT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%d%c", *((int32_t*)buf), ci.delimiter); - buf += 4; - break; - } - case CalpontSystemCatalog::UINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - { - fprintf(ci.filePtr, "%u%c", *((uint32_t*)buf), ci.delimiter); - //printf("%u|", *((uint32_t*)buf)); - //cout << *((uint32_t*)buf) << endl; - } - buf += 4; - break; - } - case CalpontSystemCatalog::SMALLINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%d%c", *((int16_t*)buf), ci.delimiter); - buf += 2; - break; - } - case CalpontSystemCatalog::USMALLINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%u%c", *((uint16_t*)buf), ci.delimiter); - buf += 2; - break; - } - case CalpontSystemCatalog::TINYINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%d%c", *((int8_t*)buf), ci.delimiter); - buf += 1; - break; - } - case CalpontSystemCatalog::UTINYINT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - fprintf(ci.filePtr, "%u%c", *((uint8_t*)buf), ci.delimiter); - buf += 1; - break; - } - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - { - float val = *((float*)buf); - if ((fabs(val) > (1.0 / IDB_pow[4])) && (fabs(val) < (float) IDB_pow[6])) - { - fprintf(ci.filePtr, "%.7f%c", val, ci.delimiter); - } - else - { - fprintf(ci.filePtr, "%e%c", val, ci.delimiter); - } - - - //fprintf(ci.filePtr, "%.7g|", *((float*)buf)); - //printf("%.7f|", *((float*)buf)); - } - buf += 4; - break; - } - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - fprintf(ci.filePtr, "%c", ci.delimiter); - else - { - fprintf(ci.filePtr, "%.15g%c", *((double*)buf), ci.delimiter); - //printf("%.15g|", *((double*)buf)); - } - buf += 8; - break; - } - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: - { - uint bytesBefore = 1; - uint totalBytes = 9; - - switch (ci.columnTypes[colpos].precision) - { - case 18: - case 17: - case 16: - { - totalBytes = 8; - break; - } - case 15: - case 14: - { - totalBytes = 7; - break; - } - case 13: - case 12: - { - totalBytes = 6; - break; - } - case 11: - { - totalBytes = 5; - break; - } - case 10: - { - totalBytes = 5; - break; - } - case 9: - case 8: - case 7: - { - totalBytes = 4; - break; - } - case 6: - case 5: - { - totalBytes = 3; - break; - } - case 4: - case 3: - { - totalBytes = 2; - break; - } - case 2: - case 1: - { - totalBytes = 1; - break; - } - default: - break; - } - - switch (ci.columnTypes[colpos].scale) - { - case 0: - { - bytesBefore = totalBytes; - break; - } - case 1: //1 byte for digits after decimal point - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 14) - && (ci.columnTypes[colpos].precision != 12) && (ci.columnTypes[colpos].precision != 10) - && (ci.columnTypes[colpos].precision != 7) && (ci.columnTypes[colpos].precision != 5) - && (ci.columnTypes[colpos].precision != 3) && (ci.columnTypes[colpos].precision != 1)) - totalBytes++; - bytesBefore = totalBytes-1; - break; - } - case 2: //1 byte for digits after decimal point - { - if ((ci.columnTypes[colpos].precision == 18) || (ci.columnTypes[colpos].precision == 9)) - totalBytes++; - bytesBefore = totalBytes-1; - break; - } - case 3: //2 bytes for digits after decimal point - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 14) - && (ci.columnTypes[colpos].precision != 12) && (ci.columnTypes[colpos].precision != 7) - && (ci.columnTypes[colpos].precision != 5) && (ci.columnTypes[colpos].precision != 3)) - totalBytes++; - - bytesBefore = totalBytes-2; - break; - } - case 4: - { - if ((ci.columnTypes[colpos].precision == 18) || (ci.columnTypes[colpos].precision == 11) - || (ci.columnTypes[colpos].precision == 9)) - totalBytes++; - bytesBefore = totalBytes-2; - break; - - } - case 5: - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 14) - && (ci.columnTypes[colpos].precision != 7) && (ci.columnTypes[colpos].precision != 5)) - totalBytes++; - bytesBefore = totalBytes-3; - break; - } - case 6: - { - if ((ci.columnTypes[colpos].precision == 18) || (ci.columnTypes[colpos].precision == 13) - || (ci.columnTypes[colpos].precision == 11) || (ci.columnTypes[colpos].precision == 9)) - totalBytes++; - bytesBefore = totalBytes-3; - break; - } - case 7: - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 7)) - totalBytes++; - bytesBefore = totalBytes-4; - break; - } - case 8: - { - if ((ci.columnTypes[colpos].precision == 18) || (ci.columnTypes[colpos].precision == 15) - || (ci.columnTypes[colpos].precision == 13) || (ci.columnTypes[colpos].precision == 11) - || (ci.columnTypes[colpos].precision == 9)) - totalBytes++; - bytesBefore = totalBytes-4;; - break; - } - case 9: - { - bytesBefore = totalBytes-4;; - break; - } - case 10: - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 14) - && (ci.columnTypes[colpos].precision != 12) && (ci.columnTypes[colpos].precision != 10)) - totalBytes++; - bytesBefore = totalBytes-5;; - break; - } - case 11: - { - if (ci.columnTypes[colpos].precision == 18) - totalBytes++; - bytesBefore = totalBytes-5; - break; - } - case 12: - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 14) - && (ci.columnTypes[colpos].precision != 12)) - totalBytes++; - bytesBefore = totalBytes-6; - break; - } - case 13: - { - if (ci.columnTypes[colpos].precision == 18) - totalBytes++; - bytesBefore = totalBytes-6; - break; - } - case 14: - { - if ((ci.columnTypes[colpos].precision != 16) && (ci.columnTypes[colpos].precision != 14)) - totalBytes++; - bytesBefore = totalBytes-7; - break; - } - case 15: - { - if (ci.columnTypes[colpos].precision == 18) - totalBytes++; - bytesBefore = totalBytes-7; - break; - } - case 16: - { - if (ci.columnTypes[colpos].precision != 16) - totalBytes++; - bytesBefore = totalBytes-8; - break; - } - case 17: - { - if (ci.columnTypes[colpos].precision == 18) - totalBytes++; - bytesBefore = totalBytes-8; - break; - } - case 18: - { - bytesBefore = totalBytes-8; - break; - } - default: - break; - } - - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - { - fprintf(ci.filePtr, "%c", ci.delimiter); - //printf("|"); - } - else - { - uint32_t mask [5] = {0, 0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF}; - char neg = '-'; - - if (ci.columnTypes[colpos].scale == 0) - { - uchar* tmpBuf = buf; - //test flag bit for sign - bool posNum = tmpBuf[0] & (0x80); - tmpBuf[0] ^= 0x80; //flip the bit - int32_t tmp1 = tmpBuf[0]; - - if (totalBytes > 4) - { - for (uint i=1; i<(totalBytes-4); i++) - { - tmp1 = (tmp1 << 8) + tmpBuf[i]; - } - if (( tmp1 != 0 ) && (tmp1 != -1)) - { - if (!posNum) - { - tmp1 = mask[totalBytes-4] - tmp1; - if(tmp1 != 0) - { - fprintf(ci.filePtr, "%c", neg); - //printf("%c", neg); - } - } - if(tmp1 != 0) - { - fprintf(ci.filePtr, "%d", tmp1); - ////printf("%d", tmp1); - } - } - - int32_t tmp2 = tmpBuf[totalBytes-4]; - for (uint i=(totalBytes-3); i 4) - { - for (uint i=1; i<(bytesBefore-4); i++) - { - tmp1 = (tmp1 << 8) + tmpBuf[i]; - } - if (!posNum) - { - tmp1 = mask[bytesBefore-4] - tmp1; - } - if (( tmp1 != 0 ) && (tmp1 != -1)) - { - if (!posNum) - { - fprintf(ci.filePtr, "%c", neg); - //printf("%c", neg); - } - - fprintf(ci.filePtr, "%d", tmp1); - //printf("%d", tmp1); - } - tmpBuf += (bytesBefore-4); - int32_t tmp2 = *((int32_t*)tmpBuf); - tmp2 = ntohl(tmp2); - - if ( tmp1 != 0 ) - { - if (!posNum) - { - tmp2 = mask[4] - tmp2; - } - if (tmp1 == -1) - { - fprintf(ci.filePtr, "%c", neg); - fprintf(ci.filePtr, "%d.", tmp2); - //printf("%c", neg); - //printf("%d.", tmp2); - } - else - { - fprintf(ci.filePtr, "%09u.", tmp2); - //printf("%09u.", tmp2); - } - } - else - { - if (!posNum) - { - tmp2 = mask[4] - tmp2; - fprintf(ci.filePtr, "%c", neg); - //printf("%c", neg); - } - fprintf(ci.filePtr, "%d.", tmp2); - //printf("%d.", tmp2); - } - } - else - { - for (uint i=1; i 4) - tmpBuf += 4; - else - tmpBuf += bytesBefore; - - tmp2 = tmpBuf[0]; - if ((totalBytes-bytesBefore) < 5) - { - for (uint j=1; j < (totalBytes-bytesBefore); j++) - { - tmp2 = (tmp2<<8) + tmpBuf[j]; - } - int8_t digits = ci.columnTypes[colpos].scale - 9; //9 digits is a 4 bytes chunk - if ( digits <= 0 ) - digits = ci.columnTypes[colpos].scale; - - if (!posNum) - { - tmp2 = mask[totalBytes-bytesBefore] - tmp2; - } - fprintf(ci.filePtr, "%0*u%c", digits, tmp2, ci.delimiter); - //printf("%0*u|", digits, tmp2); - } - else - { - for (uint j=1; j < 4; j++) - { - tmp2 = (tmp2 << 8) + tmpBuf[j]; - } - if (!posNum) - { - tmp2 = mask[4] - tmp2; - } - fprintf(ci.filePtr, "%09u", tmp2); - //printf("%09u", tmp2); - - tmpBuf += 4; - int32_t tmp3 = tmpBuf[0]; - for (uint j=1; j < (totalBytes-bytesBefore-4); j++) - { - tmp3 = (tmp3 << 8) + tmpBuf[j]; - } - int8_t digits = ci.columnTypes[colpos].scale - 9; //9 digits is a 4 bytes chunk - if ( digits < 0 ) - digits = ci.columnTypes[colpos].scale; - - if (!posNum) - { - tmp3 = mask[totalBytes-bytesBefore-4] - tmp3; - } - fprintf(ci.filePtr, "%0*u%c", digits, tmp3, ci.delimiter); - //printf("%0*u|", digits, tmp3); - } - } - } - buf += totalBytes; - break; - } - case CalpontSystemCatalog::VARBINARY: - { - if (nullVal && (ci.columnTypes[colpos].constraintType != CalpontSystemCatalog::NOTNULL_CONSTRAINT)) - { - fprintf(ci.filePtr, "%c", ci.delimiter); - - if (!ci.utf8) - { - if (ci.columnTypes[colpos].colWidth < 256) - { - buf++; - } - else - { - buf = buf + 2 ; - } - } - else //utf8 - { - if (ci.columnTypes[colpos].colWidth < 86) - { - buf++; - } - else - { - buf = buf + 2 ; - } - } - } - else - { - int dataLength = 0; - - if (!ci.utf8) - { - if (ci.columnTypes[colpos].colWidth < 256) - { - dataLength = *(int8_t*) buf; - buf++; - } - else - { - dataLength = *(int16_t*) buf; - buf = buf + 2 ; - } - - uchar* tmpBuf = buf; - for (int32_t i=0; i ci.columnTypes[colpos].colWidth) - dataLength = ci.columnTypes[colpos].colWidth; - - uchar* tmpBuf = buf; - for (int32_t i=0; iset_TableName (tablename.table); ByteStream bytestream; - bytestream << static_cast(sessionID); + bytestream << static_cast(sessionID); pDMLPackage->write(bytestream); delete pDMLPackage; + idbassert( ci.dmlProc ); + int rc = 0; ByteStream::byte b = 0; ByteStream::octbyte rows; std::string errorMsg; @@ -1562,9 +712,10 @@ int ha_calpont_impl_write_batch_row_(uchar *buf, TABLE* table, cal_impl_if::cal_ bytestream = ci.dmlProc->read(); if ( bytestream.length() == 0 ) { + rc = 1; thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc [5]"); + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc"); } else @@ -1578,12 +729,14 @@ int ha_calpont_impl_write_batch_row_(uchar *buf, TABLE* table, cal_impl_if::cal_ } catch (runtime_error&) { + rc =1 ; thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc [6]"); + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DMLProc"); } catch (...) { + rc = 1; thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Caught unknown error"); @@ -1667,10 +820,12 @@ int ha_calpont_impl_write_batch_row_(uchar *buf, TABLE* table, cal_impl_if::cal_ pDMLPackage->set_SQLStatement( lockIDString.str() ); ByteStream bytestream; - bytestream << static_cast(sessionID); + bytestream << static_cast(sessionID); pDMLPackage->write(bytestream); delete pDMLPackage; + idbassert( ci.dmlProc ); + ByteStream::byte b = 0; ByteStream::octbyte rows; std::string errorMsg; @@ -1684,7 +839,7 @@ int ha_calpont_impl_write_batch_row_(uchar *buf, TABLE* table, cal_impl_if::cal_ thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, - "Lost connection to DMLProc [7]"); + "Lost connection to DMLProc"); } else { @@ -1700,7 +855,7 @@ int ha_calpont_impl_write_batch_row_(uchar *buf, TABLE* table, cal_impl_if::cal_ thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, - "Lost connection to DMLProc [8]"); + "Lost connection to DMLProc"); } catch (...) { @@ -1722,7 +877,6 @@ int ha_calpont_impl_commit_ (handlerton *hton, THD *thd, bool all, cal_connectio if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ALTER_VTABLE || thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE ) return rc; - if (thd->slave_thread) return 0; std::string command("COMMIT"); #ifdef INFINIDB_DEBUG cout << "COMMIT" << endl; @@ -1737,14 +891,6 @@ int ha_calpont_impl_rollback_ (handlerton *hton, THD *thd, bool all, cal_connect #ifdef INFINIDB_DEBUG cout << "ROLLBACK" << endl; #endif - if (useHdfs) - { - string msg = string("Some non-transactional changed tables couldn't be rolled back"); - // cout << "Some non-transactional changed tables couldn't be rolled back" << endl; - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1196, msg.c_str()); - return rc; - } - std::string command("ROLLBACK"); rc = ProcessCommandStatement(thd, command, ci); return rc; diff --git a/dbcon/mysql/ha_calpont_execplan.cpp b/dbcon/mysql/ha_calpont_execplan.cpp index 920a8a72..e2e628a8 100644 --- a/dbcon/mysql/ha_calpont_execplan.cpp +++ b/dbcon/mysql/ha_calpont_execplan.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: ha_calpont_execplan.cpp 9749 2013-08-15 04:00:39Z zzhu $ + * $Id: ha_calpont_execplan.cpp 9748 2013-08-15 03:57:46Z zzhu $ */ /** @file */ @@ -62,7 +62,6 @@ using namespace cal_impl_if; #include "calpontselectexecutionplan.h" #include "calpontsystemcatalog.h" #include "simplecolumn_int.h" -#include "simplecolumn_uint.h" #include "simplecolumn_decimal.h" #include "aggregatecolumn.h" #include "constantcolumn.h" @@ -78,7 +77,6 @@ using namespace cal_impl_if; #include "existsfilter.h" #include "groupconcatcolumn.h" #include "outerjoinonfilter.h" -#include "intervalcolumn.h" using namespace execplan; #include "funcexp.h" @@ -87,8 +85,6 @@ using namespace funcexp; const uint64_t AGG_BIT = 0x01; const uint64_t SUB_BIT = 0x02; -const uint64_t AF_BIT = 0x04; -const uint64_t CORRELATED = 0x08; //#define OUTER_JOIN_DEBUG namespace @@ -108,13 +104,39 @@ namespace namespace cal_impl_if { +// function prototypes +ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupport); +ReturnedColumn* buildFunctionColumn(Item_func* item, gp_walk_info& gwi, bool& nonSupport); +ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info &gwi, bool& nonSupport); +ConstantColumn* buildDecimalColumn(Item *item, gp_walk_info &gwi); +SimpleColumn* buildSimpleColumn(Item_field* item, gp_walk_info& gwi); +FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonSupport); +ParseTree* buildParseTree(Item_func* item, gp_walk_info& gwi, bool& nonSupport); +AggregateColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi); +void addIntervalArgs(Item_func* ifp, FunctionParm& functionParms); +void castCharArgs(Item_func* ifp, FunctionParm& functionParms); +void castDecimalArgs(Item_func* ifp, FunctionParm& functionParms); +void castTypeArgs(Item_func* ifp, FunctionParm& functionParms); +void parse_item (Item *item, vector& field_vec, bool& hasNonSupportItem, uint16& parseInfo); +bool isPredicateFunction(Item* item, gp_walk_info* gwip); +ParseTree* buildRowPredicate(RowColumn* lhs, RowColumn* rhs, string predicateOp); +void buildRowColumnFilter(gp_walk_info* gwip, RowColumn* rhs, RowColumn* lhs, Item_func* ifp); +void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip); +void collectAllCols(gp_walk_info& gwi, Item_field* ifp); +void buildSubselectFunc(Item_func* ifp, gp_walk_info* gwip); +uint buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex); +string getViewName(TABLE_LIST* table_ptr); +void buildConstPredicate(Item_func* ifp, ReturnedColumn* rhs, gp_walk_info* gwip); +CalpontSystemCatalog::ColType fieldType_MysqlToIDB (const Field* field); +CalpontSystemCatalog::ColType colType_MysqlToIDB (const Item* item); + //@bug5228. need to escape backtick ` string escapeBackTick(const char* str) { if (!str) return ""; string ret; - for (uint32_t i = 0; str[i] != 0; i++) + for (uint i = 0; str[i] != 0; i++) { if (str[i] == '`') ret.append("``"); @@ -134,11 +156,9 @@ void clearStacks(gp_walk_info& gwi) bool nonConstFunc(Item_func* ifp) { - if (strcasecmp(ifp->func_name(), "rand") == 0 || - strcasecmp(ifp->func_name(), "sysdate") == 0 || - strcasecmp(ifp->func_name(), "idblocalpm") == 0) + if (strcasecmp(ifp->func_name(), "rand") == 0 || strcasecmp(ifp->func_name(), "sysdate") == 0) return true; - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { if (ifp->arguments()[i]->type() == Item::FUNC_ITEM && nonConstFunc(((Item_func*)ifp->arguments()[i]))) @@ -149,9 +169,7 @@ bool nonConstFunc(Item_func* ifp) string getViewName(TABLE_LIST* table_ptr) { - string viewName = ""; - if (!table_ptr) - return viewName; + string viewName; TABLE_LIST *view = table_ptr->referencing_view; if (view) { @@ -166,238 +184,7 @@ string getViewName(TABLE_LIST* table_ptr) return viewName; } -#ifdef DEBUG_WALK_COND -void debug_walk(const Item *item, void *arg) -{ - switch (item->type()) - { - case Item::FIELD_ITEM: - { - Item_field* ifp = (Item_field*)item; - cout << "FIELD_ITEM: " << (ifp->db_name ? ifp->db_name : "") << '.' << bestTableName(ifp) << - '.' << ifp->field_name << endl; - break; - } - case Item::INT_ITEM: - { - Item_int* iip = (Item_int*)item; - cout << "INT_ITEM: "; - if (iip->name) cout << iip->name << " (from name string)" << endl; - else cout << iip->val_int() << endl; - break; - } - case Item::STRING_ITEM: - { - Item_string* isp = (Item_string*)item; - String val, *str = isp->val_str(&val); - cout << "STRING_ITEM: >" << str->c_ptr() << '<' << endl; - break; - } - case Item::REAL_ITEM: - { - cout << "REAL_ITEM" << endl; - break; - } - case Item::DECIMAL_ITEM: - { - cout << "DECIMAL_ITEM" << endl; - break; - } - case Item::FUNC_ITEM: - { - Item_func* ifp = (Item_func*)item; - Item_func_opt_neg* inp; - cout << "FUNC_ITEM: "; - switch (ifp->functype()) - { - case Item_func::UNKNOWN_FUNC: // 0 - cout << ifp->func_name() << endl; - break; - case Item_func::GT_FUNC: // 7 - cout << '>' << endl; - break; - case Item_func::EQ_FUNC: // 1 - cout << '=' << endl; - break; - case Item_func::GE_FUNC: - cout << ">=" << endl; - break; - case Item_func::LE_FUNC: - cout << "<=" << endl; - break; - case Item_func::LT_FUNC: - cout << '<' << endl; - break; - case Item_func::NE_FUNC: - cout << "<>" << endl; - break; - case Item_func::NEG_FUNC: // 45 - cout << "unary minus" << endl; - break; - case Item_func::IN_FUNC: // 16 - inp = (Item_func_opt_neg*)ifp; - if (inp->negated) cout << "not "; - cout << "in" << endl; - break; - case Item_func::BETWEEN: - inp = (Item_func_opt_neg*)ifp; - if (inp->negated) cout << "not "; - cout << "between" << endl; - break; - case Item_func::ISNULL_FUNC: // 10 - cout << "is null" << endl; - break; - case Item_func::ISNOTNULL_FUNC: // 11 - cout << "is not null" << endl; - break; - case Item_func::NOT_ALL_FUNC: - cout << "not_all" << endl; - break; - case Item_func::NOT_FUNC: - cout << "not_func" << endl; - break; - case Item_func::TRIG_COND_FUNC: - cout << "trig_cond_func" << endl; - break; - case Item_func::ISNOTNULLTEST_FUNC: - cout << "isnotnulltest_func" << endl; - break; - default: - cout << "type=" << ifp->functype() << endl; - break; - } - break; - } - case Item::COND_ITEM: - { - Item_cond* icp = (Item_cond*)item; - cout << "COND_ITEM: " << icp->func_name() << endl; - break; - } - case Item::SUM_FUNC_ITEM: - { - Item_sum* isp = (Item_sum*)item; - Item_sum_int* isip = 0; - Item_sum_distinct* isdp = 0; - Item_sum_avg* isap = 0; - Item_sum_count* iscp = 0; - Item_sum_count_distinct* iscdp = 0; - Item_sum_min* isnp = 0; - Item_sum_max* isxp = 0; - - switch (isp->sum_func()) - { - case Item_sum::SUM_FUNC: - isip = (Item_sum_int*)isp; - cout << "SUM_FUNC: " << isip->name << endl; - break; - case Item_sum::SUM_DISTINCT_FUNC: - isdp = (Item_sum_distinct*)isp; - cout << "SUM_DISTINCT_FUNC: " << isdp->name << endl; - break; - case Item_sum::AVG_FUNC: - isap = (Item_sum_avg*)isp; - cout << "AVG_FUNC: " << isap->name << endl; - break; - case Item_sum::COUNT_FUNC: - iscp = (Item_sum_count*)isp; - cout << "COUNT_FUNC: " << iscp->name << endl; - break; - case Item_sum::COUNT_DISTINCT_FUNC: - iscdp = (Item_sum_count_distinct*)isp; - cout << "COUNT_DISTINCT_FUNC: " << iscdp->name << endl; - break; - case Item_sum::MIN_FUNC: - isnp = (Item_sum_min*)isp; - cout << "MIN_FUNC: " << isnp->name << endl; - break; - case Item_sum::MAX_FUNC: - isxp = (Item_sum_max*)isp; - cout << "MAX_FUNC: " << isxp->name << endl; - break; - default: - cout << "SUM_FUNC_ITEM type=" << isp->sum_func() << endl; - break; - } - break; - } - case Item::SUBSELECT_ITEM: - { - Item_subselect* sub = (Item_subselect*)item; - cout << "SUBSELECT Item: "; - switch (sub->substype()) - { - case Item_subselect::EXISTS_SUBS: - cout << "EXISTS"; - break; - case Item_subselect::IN_SUBS: - cout << "IN"; - break; - default: - cout << sub->substype(); - break; - } - cout << endl; - JOIN* join = sub->get_select_lex()->join; - if (join) - { - Item_cond* cond = reinterpret_cast(join->conds); - if (cond) - cond->traverse_cond(debug_walk, arg, Item::POSTFIX); - } - cout << "Finish subselect item traversing" << endl; - break; - } - case Item::REF_ITEM: - { - Item_ref* ref = (Item_ref*)item; - if (ref->real_item()->type() == Item::CACHE_ITEM) - { - Item* field = ((Item_cache*)ref->real_item())->get_example(); - if (field->type() == Item::FIELD_ITEM) - { - Item_field* ifp = (Item_field*)field; - //ifp->cached_table->select_lex->select_number gives the select level. - // could be used on alias. - // could also be used to tell correlated join (equal level). - cout << "CACHED FIELD_ITEM: " << ifp->db_name << '.' << bestTableName(ifp) << - '.' << ifp->field_name << endl; - break; - } - } - else if (ref->real_item()->type() == Item::FIELD_ITEM) - { - Item_field* ifp = (Item_field*)ref->real_item(); - cout << "REF FIELD_ITEM: " << ifp->db_name << '.' << bestTableName(ifp) << '.' << - ifp->field_name << endl; - break; - } - cout << "UNKNOWN REF ITEM" << endl; - break; - } - case Item::ROW_ITEM: - { - Item_row* row = (Item_row*)item; - cout << "ROW_ITEM: " << endl; - for (uint32_t i = 0; i < row->cols(); i++) - debug_walk(row->element_index(i), 0); - break; - } - case Item::WINDOW_FUNC_ITEM: - { - cout << "Window Function Item" << endl; - break; - } - default: - { - cout << "UNKNOWN_ITEM type " << item->type() << endl; - break; - } - } -} -#endif - -uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex) +uint buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex) { // check non-collapsed outer join // this set contains all processed embedded joins. duplicate joins are ignored @@ -405,7 +192,6 @@ uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex) TABLE_LIST* table_ptr = select_lex.get_table_list(); gp_walk_info gwi_outer = gwi; gwi_outer.subQuery = NULL; - gwi_outer.hasSubSelect = false; vector tmpVec; for (; table_ptr; table_ptr= table_ptr->next_local) @@ -413,7 +199,6 @@ uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex) gwi_outer.innerTables.clear(); clearStacks(gwi_outer); gwi_outer.subQuery = NULL; - gwi_outer.hasSubSelect = false; // View is already processed in view::transform // @bug5319. view is sometimes treated as derived table and @@ -514,7 +299,7 @@ uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex) } // Error out subquery in outer join on filter for now - if (gwi_outer.hasSubSelect) + if (gwi_outer.subQuery) { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_OUTER_JOIN_SUBSELECT); @@ -556,7 +341,7 @@ uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex) ParseTree* buildRowPredicate(RowColumn* lhs, RowColumn* rhs, string predicateOp) { PredicateOperator *po = new PredicateOperator(predicateOp); - boost::shared_ptr sop(po); + shared_ptr sop(po); LogicOperator *lo = NULL; if (predicateOp == "=") lo = new LogicOperator("and"); @@ -567,7 +352,7 @@ ParseTree* buildRowPredicate(RowColumn* lhs, RowColumn* rhs, string predicateOp) sop->setOpType(lhs->columnVec()[0]->resultType(), rhs->columnVec()[0]->resultType()); SimpleFilter *sf = new SimpleFilter(sop, lhs->columnVec()[0].get(), rhs->columnVec()[0].get()); pt->left(new ParseTree(sf)); - for (uint32_t i = 1; i < lhs->columnVec().size(); i++) + for (uint i = 1; i < lhs->columnVec().size(); i++) { sop.reset(po->clone()); sop->setOpType(lhs->columnVec()[i]->resultType(), rhs->columnVec()[i]->resultType()); @@ -617,7 +402,7 @@ void buildRowColumnFilter(gp_walk_info* gwip, RowColumn* rhs, RowColumn* lhs, It tmpStack.push(rhs); tmpStack.push(lhs); assert (gwip->rcWorkStack.size() >= ifp->arg_count - 2); - for (uint32_t i = 2; i < ifp->arg_count; i++) + for (uint i = 2; i < ifp->arg_count; i++) { tmpStack.push(gwip->rcWorkStack.top()); if (!gwip->rcWorkStack.empty()) @@ -646,10 +431,10 @@ void buildRowColumnFilter(gp_walk_info* gwip, RowColumn* rhs, RowColumn* lhs, It return; // 2nd round. add the filter to favor casual partition for IN clause - boost::shared_ptr sop; - boost::shared_ptr ssc; + shared_ptr sop; + shared_ptr ssc; stack tmpPtStack; - for (uint32_t i = 0; i < columns->columnVec().size(); i++) + for (uint i = 0; i < columns->columnVec().size(); i++) { ConstantFilter* cf = new ConstantFilter(); @@ -664,7 +449,7 @@ void buildRowColumnFilter(gp_walk_info* gwip, RowColumn* rhs, RowColumn* lhs, It ssc.reset(sc->clone()); cf->col(ssc); - uint32_t j = 0; + uint j = 0; for (; j < valVec.size(); j++) { sop.reset(new PredicateOperator(predicateOp)); @@ -726,11 +511,7 @@ void buildRowColumnFilter(gp_walk_info* gwip, RowColumn* rhs, RowColumn* lhs, It void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) { - boost::shared_ptr sop(new PredicateOperator(ifp->func_name())); - if (!(gwip->thd->infinidb_vtable.cal_conn_info)) - gwip->thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwip->thd->infinidb_vtable.cal_conn_info); - + shared_ptr sop(new PredicateOperator(ifp->func_name())); if (ifp->functype() == Item_func::BETWEEN) { @@ -765,8 +546,7 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) cf->pushFilter(new SimpleFilter(sop, gwip->scsp->clone(), lhs)); cf->functionName(gwip->funcName); String str; - // @bug5811. This filter string is for cross engine to use. - // Use real table name. + // @bug5811 ifp->print(&str, QT_INFINIDB_DERIVED); IDEBUG(cout << str.c_ptr() << endl); if (str.c_ptr()) @@ -844,8 +624,7 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) } cf->functionName(gwip->funcName); String str; - // @bug5811. This filter string is for cross engine to use. - // Use real table name. + // @bug5811 ifp->print(&str, QT_INFINIDB_DERIVED); IDEBUG(cout << str.c_ptr() << endl); if (str.c_ptr()) @@ -883,14 +662,7 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) String buf; if (udf->result_type() == INT_RESULT) { - if (udf->unsigned_flag) - { - gwip->rcWorkStack.push(new ConstantColumn((uint64_t)udf->val_uint())); - } - else - { - gwip->rcWorkStack.push(new ConstantColumn((int64_t)udf->val_int())); - } + gwip->rcWorkStack.push(new ConstantColumn(udf->val_int())); } else { @@ -908,9 +680,7 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) if (udf->result_type() == STRING_RESULT) gwip->rcWorkStack.push(new ConstantColumn(buf.c_ptr())); else - { gwip->rcWorkStack.push(new ConstantColumn(buf.c_ptr(), ConstantColumn::NUM)); - } } } else if (ifp->functype() == Item_func::NEG_FUNC) @@ -937,9 +707,10 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) { if (gwip->condPush && ifp->next->type() == Item::SUBSELECT_ITEM) return; - if (ifp->next && ifp->next->type() == Item::SUBSELECT_ITEM && gwip->lastSub) + if (ifp->next && ifp->next->type() == Item::SUBSELECT_ITEM && gwip->subQuery) { - gwip->lastSub->handleNot(); + gwip->subQuery->handleNot(); +// gwip->subQuery = NULL; // finish processing this subquery return; } @@ -1036,13 +807,10 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) !(localCol->joinInfo() & JOIN_CORRELATED)) { localCol->sequence(gwip->returnedCols.size()); - localCol->expressionId(ci->expressionId++); + localCol->expressionId(gwip->expressionId++); ReturnedColumn *rc = localCol->clone(); rc->colSource(rc->colSource() | CORRELATED_JOIN); - gwip->additionalRetCols.push_back(SRCP(rc)); - gwip->localCols.push_back(localCol); - if (rc->hasWindowFunc()) - gwip->windowFuncList.push_back(rc); + gwip->returnedCols.push_back(SRCP(rc)); } // push the correlated join partner to the group by list only when there's aggregate @@ -1052,7 +820,9 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) // to add the group by or not. if (gwip->subQuery) { - if (!localCol->hasAggregate() && !localCol->hasWindowFunc()) + AggregateColumn* ac = dynamic_cast(localCol); + if (!ac) + // @todo push local column to potential group by list in case there is agg on SELECT gwip->subGroupByCols.push_back(SRCP(localCol->clone())); } @@ -1068,14 +838,13 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) } SimpleFilter *sf = new SimpleFilter(); + SimpleColumn *slhs = NULL; + SimpleColumn *srhs = NULL; - //@bug 2101 for when there are only constants in a delete or update where clause (eg "where 5 < 6"). - //There will be no field column and it will get here only if the comparison is true. + + //@bug 2101 for when there are only constants in a delete or update where clause (eg "where 5 < 6"). There will be no field column and it will get here only if the comparison is true. if (gwip->columnMap.empty() && - ((current_thd->lex->sql_command == SQLCOM_UPDATE) || - (current_thd->lex->sql_command == SQLCOM_UPDATE_MULTI) || - (current_thd->lex->sql_command == SQLCOM_DELETE) || - (current_thd->lex->sql_command == SQLCOM_DELETE_MULTI))) + ((current_thd->lex->sql_command == SQLCOM_UPDATE) || (current_thd->lex->sql_command == SQLCOM_UPDATE_MULTI) || (current_thd->lex->sql_command == SQLCOM_DELETE) || (current_thd->lex->sql_command == SQLCOM_DELETE_MULTI))) { IDEBUG( cout << "deleted func with 2 const columns" << endl ); delete rhs; @@ -1090,7 +859,7 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) } else { - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { if (isPredicateFunction(ifp->arguments()[i], gwip)) { @@ -1105,16 +874,18 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) sf->rhs(rhs); sop->setOpType(lhs->resultType(), rhs->resultType()); sop->resultType(sop->operationType()); + slhs = dynamic_cast(lhs); + srhs = dynamic_cast(rhs); - if (sop->op() == OP_EQ) + if (srhs && slhs && sop->op() == OP_EQ) { - CalpontSystemCatalog::TableAliasName tan_lhs; - CalpontSystemCatalog::TableAliasName tan_rhs; + CalpontSystemCatalog::TableAliasName tan_lhs = make_aliasview(slhs->schemaName(), slhs->tableName(), slhs->tableAlias(), slhs->viewName()); + CalpontSystemCatalog::TableAliasName tan_rhs = make_aliasview(srhs->schemaName(), srhs->tableName(), srhs->tableAlias(), srhs->viewName()); + set::const_iterator it; - bool outerjoin = (rhs->singleTable(tan_rhs) && lhs->singleTable(tan_lhs)); // @bug 1632. Alias should be taken account to the identity of tables for selfjoin to work - if (outerjoin && tan_lhs != tan_rhs) // join + if (tan_lhs != tan_rhs) // join { if (!gwip->condPush) // vtable { @@ -1124,13 +895,13 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) for (it = gwip->innerTables.begin(); it != gwip->innerTables.end(); ++it) { - if (tan_lhs.alias == it->alias && tan_lhs.view == it->view) + if (slhs->tableAlias() == it->alias && slhs->viewName() == it->view) notInner = false; } if (notInner) - lhs->returnAll(true); - IDEBUG( cout << "setting returnAll on " << tan_lhs << endl); + slhs->returnAll(true); + IDEBUG( cout << "setting returnAll on " << slhs->oid() << endl); } if (!gwip->innerTables.empty()) { @@ -1138,13 +909,13 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) for (it = gwip->innerTables.begin(); it != gwip->innerTables.end(); ++it) { - if (tan_rhs.alias == it->alias && tan_rhs.view == it->view) + if (srhs->tableAlias() == it->alias && srhs->viewName() == it->view) notInner = false; } if (notInner) - rhs->returnAll(true); - IDEBUG( cout << "setting returnAll on " << tan_rhs << endl ); + srhs->returnAll(true); + IDEBUG( cout << "setting returnAll on " << srhs->oid() << endl ); } ParseTree* ptp = new ParseTree(sf); @@ -1168,7 +939,7 @@ void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip) void buildConstPredicate(Item_func* ifp, ReturnedColumn* rhs, gp_walk_info* gwip) { SimpleFilter *sf = new SimpleFilter(); - boost::shared_ptr sop(new PredicateOperator(ifp->func_name())); + shared_ptr sop(new PredicateOperator(ifp->func_name())); ConstantColumn *lhs = 0; if (ifp->functype() == Item_func::ISNULL_FUNC) @@ -1183,7 +954,7 @@ void buildConstPredicate(Item_func* ifp, ReturnedColumn* rhs, gp_walk_info* gwip } else //if (ifp->functype() == Item_func::NOT_FUNC) { - lhs = new ConstantColumn((int64_t)0, ConstantColumn::NUM); + lhs = new ConstantColumn(0, ConstantColumn::NUM); sop.reset(new PredicateOperator("=")); } @@ -1211,14 +982,15 @@ SimpleColumn* buildSimpleColFromDerivedTable(gp_walk_info& gwi, Item_field* ifp) SimpleColumn* sc = NULL; // view name - string viewName = getViewName(ifp->cached_table); + string viewName = ""; + if (ifp->cached_table) + viewName = getViewName(ifp->cached_table); - // Check from the end because local scope resolve is preferred - for (int32_t i = gwi.tbList.size() - 1; i >=0; i--) + for (uint i = 0; i < gwi.tbList.size(); i++) { if (sc) break; if (!gwi.tbList[i].schema.empty() && !gwi.tbList[i].table.empty() && - (!ifp->table_name || strcasecmp(ifp->table_name, gwi.tbList[i].alias.c_str()) == 0)) + (!ifp->table_name || strcasecmp(ifp->table_name, gwi.tbList[i].alias.c_str()) == 0)) { CalpontSystemCatalog::TableName tn(gwi.tbList[i].schema, gwi.tbList[i].table); CalpontSystemCatalog::RIDList oidlist = gwi.csc->columnRIDs(tn, true); @@ -1246,10 +1018,11 @@ SimpleColumn* buildSimpleColFromDerivedTable(gp_walk_info& gwi, Item_field* ifp) sc->tableName(tcn.table); sc->schemaName(tcn.schema); sc->oid(oidlist[j].objnum); - // @bug 3003. Keep column alias if it has. - sc->alias(ifp->is_autogenerated_name ? tcn.column: ifp->name); - + if (!ifp->is_autogenerated_name) + sc->alias(ifp->name); + else + sc->alias(tcn.column); sc->tableAlias(lower(gwi.tbList[i].alias)); sc->viewName(lower(viewName)); sc->resultType(ct); @@ -1262,26 +1035,21 @@ SimpleColumn* buildSimpleColFromDerivedTable(gp_walk_info& gwi, Item_field* ifp) if (sc) return sc; - // Check from the end because local scope resolve is preferred - for (int32_t i = gwi.derivedTbList.size()-1; i>=0; i--) + for (uint i = 0; i < gwi.derivedTbList.size(); i++) { if (sc) break; CalpontSelectExecutionPlan* csep = dynamic_cast(gwi.derivedTbList[i].get()); - string derivedName = csep->derivedTbAlias(); - - if (!ifp->table_name || strcasecmp(ifp->table_name, derivedName.c_str()) == 0) + if (!ifp->table_name || strcasecmp(ifp->table_name, csep->derivedTbAlias().c_str()) == 0) { CalpontSelectExecutionPlan::ReturnedColumnList cols = csep->returnedCols(); - for (uint32_t j = 0; j < cols.size(); j++) + for (uint j = 0; j < cols.size(); j++) { // @bug 3167 duplicate column alias is full name SimpleColumn *col = dynamic_cast(cols[j].get()); - string alias = cols[j]->alias(); - if (strcasecmp(ifp->field_name, alias.c_str()) == 0 || - (col && alias.find(".") != string::npos && - (strcasecmp(ifp->field_name, col->columnName().c_str()) == 0 || - strcasecmp(ifp->field_name, (alias.substr(alias.find_last_of(".")+1)).c_str()) == 0))) //@bug6066 + if (strcasecmp(ifp->field_name, cols[j]->alias().c_str()) == 0 || + (col && cols[j]->alias().find(".") != string::npos && + strcasecmp(ifp->field_name, col->columnName().c_str()) == 0)) { // @bug4827. Remove the checking because outside tables could be the same // name as inner tables. This function is to identify column from a table, @@ -1300,27 +1068,19 @@ SimpleColumn* buildSimpleColFromDerivedTable(gp_walk_info& gwi, Item_field* ifp) sc->columnName(cols[j]->alias()); else sc->columnName(col->columnName()); - // @bug 3003. Keep column alias if it has. - sc->alias(ifp->is_autogenerated_name ? cols[j]->alias(): ifp->name); + if (!ifp->is_autogenerated_name) + sc->alias(ifp->name); + else + sc->alias(cols[j]->alias()); sc->tableName(csep->derivedTbAlias()); sc->colPosition(j); string tableAlias(csep->derivedTbAlias()); sc->tableAlias(lower(tableAlias)); sc->viewName(lower(viewName)); sc->resultType(cols[j]->resultType()); - sc->hasAggregate(cols[j]->hasAggregate()); if (col) sc->isInfiniDB(col->isInfiniDB()); - - // @bug5634, @bug5635. mark used derived col on derived table. - // outer join inner table filter can not be moved in - if (!(ifp->cached_table && ifp->cached_table->outer_join)) - { - sc->derivedTable(derivedName); - sc->derivedRefCol(cols[j].get()); - } - cols[j]->incRefCount(); break; } } @@ -1339,22 +1099,6 @@ SimpleColumn* buildSimpleColFromDerivedTable(gp_walk_info& gwi, Item_field* ifp) args.add(name); gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_UNKNOWN_COL, args); } - - if (ifp->depended_from) - { - sc->joinInfo(sc->joinInfo() | JOIN_CORRELATED); - if (gwi.subQuery) - gwi.subQuery->correlated(true); - - // for error out non-support select filter case (comparison outside semi join tables) - gwi.correlatedTbNameVec.push_back(make_aliastable(sc->schemaName(), sc->tableName(), sc->tableAlias())); - - // imply semi for scalar for now. - if (gwi.subSelectType == CalpontSelectExecutionPlan::SINGLEROW_SUBS) - sc->joinInfo(sc->joinInfo() | JOIN_SCALAR | JOIN_SEMI); - if (gwi.subSelectType == CalpontSelectExecutionPlan::SELECT_SUBS) - sc->joinInfo(sc->joinInfo() | JOIN_SCALAR | JOIN_OUTER_SELECT); - } return sc; } @@ -1362,7 +1106,9 @@ SimpleColumn* buildSimpleColFromDerivedTable(gp_walk_info& gwi, Item_field* ifp) void collectAllCols(gp_walk_info& gwi, Item_field* ifp) { // view name - string viewName = getViewName(ifp->cached_table); + string viewName = ""; + if (ifp->cached_table) + viewName = getViewName(ifp->cached_table); if (gwi.derivedTbList.empty()) { @@ -1374,7 +1120,7 @@ void collectAllCols(gp_walk_info& gwi, Item_field* ifp) } string tableName = (ifp->table_name? string(ifp->table_name) : ""); CalpontSelectExecutionPlan::SelectList::const_iterator it = gwi.derivedTbList.begin(); - for (uint32_t i = 0; i < gwi.tbList.size(); i++) + for (uint i = 0; i < gwi.tbList.size(); i++) { SRCP srcp; // derived table @@ -1385,7 +1131,7 @@ void collectAllCols(gp_walk_info& gwi, Item_field* ifp) if (!tableName.empty() && strcasecmp(tableName.c_str(), csep->derivedTbAlias().c_str()) != 0) continue; CalpontSelectExecutionPlan::ReturnedColumnList cols = csep->returnedCols(); - for (uint32_t j = 0; j < cols.size(); j++) + for (uint j = 0; j < cols.size(); j++) { SimpleColumn* sc = new SimpleColumn(); sc->columnName(cols[j]->alias()); @@ -1394,11 +1140,6 @@ void collectAllCols(gp_walk_info& gwi, Item_field* ifp) sc->tableAlias(lower(tableAlias)); sc->viewName(lower(gwi.tbList[i].view)); sc->resultType(cols[j]->resultType()); - - // @bug5634 derived table optimization - cols[j]->incRefCount(); - sc->derivedTable(tableAlias); - sc->derivedRefCol(cols[j].get()); srcp.reset(sc); gwi.returnedCols.push_back(srcp); gwi.columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(sc->columnName(), srcp)); @@ -1444,20 +1185,8 @@ void buildSubselectFunc(Item_func* ifp, gp_walk_info* gwip) } WhereSubQuery* subquery = NULL; - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { -#if MYSQL_VERSION_ID >= 50172 - // changes comply with mysql 5.1.72 - if (ifp->arguments()[i]->type() == Item::FUNC_ITEM && - string(((Item_func*)ifp->arguments()[i])->func_name()) == "") - { - if (ifp->functype() == Item_func::NOT_FUNC) - { - if (gwip->lastSub) - gwip->lastSub->handleNot(); - } - } -#endif if (ifp->arguments()[i]->type() == Item::SUBSELECT_ITEM) { Item_subselect* sub = (Item_subselect*)ifp->arguments()[i]; @@ -1473,14 +1202,12 @@ void buildSubselectFunc(Item_func* ifp, gp_walk_info* gwip) case Item_subselect::EXISTS_SUBS: // exists sub has been handled earlier. here is for not function if (ifp->functype() == Item_func::NOT_FUNC) - { - if (gwip->lastSub) - gwip->lastSub->handleNot(); - } + gwip->subQuery->handleNot(); break; default: Message::Args args; gwip->fatalParseError = true; + //gwip->parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_ALL_SOME_IN_SUBQUERY); gwip->parseErrorText = "non supported subquery"; return; } @@ -1488,14 +1215,9 @@ void buildSubselectFunc(Item_func* ifp, gp_walk_info* gwip) } if (subquery) { - gwip->hasSubSelect = true; - SubQuery* orig = gwip->subQuery; gwip->subQuery = subquery; // no need to check NULL for now. error will be handled in gp_walk gwip->ptWorkStack.push(subquery->transform()); - // recover original sub. Save current sub for Not handling. - gwip->lastSub = subquery; - gwip->subQuery = orig; } return; } @@ -1525,26 +1247,12 @@ bool isPredicateFunction(Item* item, gp_walk_info* gwip) string(ifp->func_name()) == "xor"); } -void setError(THD* thd, uint32_t errcode, string errmsg) +void setError(THD* thd, uint errcode, const string errmsg) { thd->main_da.can_overwrite_status = true; - if (errmsg.empty()) - errmsg = "Unknown error"; thd->main_da.set_error_status(thd, errcode, errmsg.c_str()); thd->infinidb_vtable.mysql_optimizer_off = false; thd->infinidb_vtable.override_largeside_estimate = false; - // reset expressionID - if (!(thd->infinidb_vtable.cal_conn_info)) - thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - ci->expressionId = 0; - -} - -void setError(THD* thd, uint32_t errcode, string errmsg, gp_walk_info& gwi) -{ - setError(thd, errcode, errmsg); - clearStacks(gwi); } const string bestTableName(const Item_field* ifp) @@ -1569,10 +1277,10 @@ const string bestTableName(const Item_field* ifp) return tn; } -uint32_t setAggOp(AggregateColumn* ac, Item_sum* isp) +uint setAggOp(AggregateColumn* ac, Item_sum* isp) { Item_sum::Sumfunctype agg_type = isp->sum_func(); - uint32_t rc = 0; + uint rc = 0; switch (agg_type) { case Item_sum::COUNT_FUNC: ac->aggOp(AggregateColumn::COUNT); @@ -1644,6 +1352,230 @@ uint32_t setAggOp(AggregateColumn* ac, Item_sum* isp) } } +#ifdef DEBUG_WALK_COND +void debug_walk(const Item *item, void *arg) +{ + switch (item->type()) + { + case Item::FIELD_ITEM: + { + Item_field* ifp = (Item_field*)item; + cout << "FIELD_ITEM: " << (ifp->db_name ? ifp->db_name : "") << '.' << bestTableName(ifp) << '.' << ifp->field_name << endl; + break; + } + case Item::INT_ITEM: + { + Item_int* iip = (Item_int*)item; + cout << "INT_ITEM: "; + if (iip->name) cout << iip->name << " (from name string)" << endl; + else cout << iip->val_int() << endl; + break; + } + case Item::STRING_ITEM: + { + Item_string* isp = (Item_string*)item; + String val, *str = isp->val_str(&val); + cout << "STRING_ITEM: >" << str->c_ptr() << '<' << endl; + break; + } + case Item::REAL_ITEM: + { + cout << "REAL_ITEM" << endl; + break; + } + case Item::DECIMAL_ITEM: + { + cout << "DECIMAL_ITEM" << endl; + break; + } + case Item::FUNC_ITEM: + { + Item_func* ifp = (Item_func*)item; + Item_func_opt_neg* inp; + cout << "FUNC_ITEM: "; + switch (ifp->functype()) + { + case Item_func::UNKNOWN_FUNC: // 0 + cout << ifp->func_name() << endl; + break; + case Item_func::GT_FUNC: // 7 + cout << '>' << endl; + break; + case Item_func::EQ_FUNC: // 1 + cout << '=' << endl; + break; + case Item_func::GE_FUNC: + cout << ">=" << endl; + break; + case Item_func::LE_FUNC: + cout << "<=" << endl; + break; + case Item_func::LT_FUNC: + cout << '<' << endl; + break; + case Item_func::NE_FUNC: + cout << "<>" << endl; + break; + case Item_func::NEG_FUNC: // 45 + cout << "unary minus" << endl; + break; + case Item_func::IN_FUNC: // 16 + inp = (Item_func_opt_neg*)ifp; + if (inp->negated) cout << "not "; + cout << "in" << endl; + break; + case Item_func::BETWEEN: + inp = (Item_func_opt_neg*)ifp; + if (inp->negated) cout << "not "; + cout << "between" << endl; + break; + case Item_func::ISNULL_FUNC: // 10 + cout << "is null" << endl; + break; + case Item_func::ISNOTNULL_FUNC: // 11 + cout << "is not null" << endl; + break; + case Item_func::NOT_ALL_FUNC: + cout << "not_all" << endl; + break; + default: + cout << "type=" << ifp->functype() << endl; + break; + } + //for (uint i = 0; i < ifp->arg_count; i++) + // debug_walk(ifp->arguments()[i], 0); + break; + } + case Item::COND_ITEM: + { + Item_cond* icp = (Item_cond*)item; + cout << "COND_ITEM: " << icp->func_name() << endl; + break; + } + case Item::SUM_FUNC_ITEM: + { + Item_sum* isp = (Item_sum*)item; + Item_sum_int* isip = 0; + Item_sum_distinct* isdp = 0; + Item_sum_avg* isap = 0; + Item_sum_count* iscp = 0; + Item_sum_count_distinct* iscdp = 0; + Item_sum_min* isnp = 0; + Item_sum_max* isxp = 0; + //Item* ip = 0; + //uint arg_count = 0; + + switch (isp->sum_func()) + { + case Item_sum::SUM_FUNC: + isip = (Item_sum_int*)isp; + //ip = *isip->args; + //arg_count = isip->arg_count; + cout << "SUM_FUNC: " << isip->name << endl; + break; + case Item_sum::SUM_DISTINCT_FUNC: + isdp = (Item_sum_distinct*)isp; + //ip = *isdp->args; + //arg_count = isdp->arg_count; + cout << "SUM_DISTINCT_FUNC: " << isdp->name << endl; + break; + case Item_sum::AVG_FUNC: + isap = (Item_sum_avg*)isp; + //ip = *isap->args; + //arg_count = isap->arg_count; + cout << "AVG_FUNC: " << isap->name << endl; + break; + case Item_sum::COUNT_FUNC: + iscp = (Item_sum_count*)isp; + //ip = *iscp->args; + //arg_count = iscp->arg_count; + cout << "COUNT_FUNC: " << iscp->name << endl; + break; + case Item_sum::COUNT_DISTINCT_FUNC: + iscdp = (Item_sum_count_distinct*)isp; + //ip = *iscdp->args; + //arg_count = iscdp->arg_count; + cout << "COUNT_DISTINCT_FUNC: " << iscdp->name << endl; + break; + case Item_sum::MIN_FUNC: + isnp = (Item_sum_min*)isp; + //ip = *isnp->args; + //arg_count = isnp->arg_count; + cout << "MIN_FUNC: " << isnp->name << endl; + break; + case Item_sum::MAX_FUNC: + isxp = (Item_sum_max*)isp; + //ip = *isxp->args; + //arg_count = isxp->arg_count; + cout << "MAX_FUNC: " << isxp->name << endl; + break; + default: + cout << "SUM_FUNC_ITEM type=" << isp->sum_func() << endl; + break; + } +// while (ip) +// { +// debug_walk(ip, 0); +// ip = ip->next; +// } + break; + } +#if 1 // subquery debug + case Item::SUBSELECT_ITEM: + { + Item_subselect* sub = (Item_subselect*)item; + cout << "SUBSELECT Item: " << sub->substype() << endl; + JOIN* join = sub->get_select_lex()->join; + if (join) + { + Item_cond* cond = reinterpret_cast(join->conds); + if (cond) + cond->traverse_cond(debug_walk, arg, Item::POSTFIX); + } + cout << "Finish subselect item traversing" << endl; + break; + } + case Item::REF_ITEM: + { + Item_ref* ref = (Item_ref*)item; + if (ref->real_item()->type() == Item::CACHE_ITEM) + { + Item* field = ((Item_cache*)ref->real_item())->get_example(); + if (field->type() == Item::FIELD_ITEM) + { + Item_field* ifp = (Item_field*)field; + //ifp->cached_table->select_lex->select_number gives the select level. could be used on alias. + // could also be used to tell correlated join (equal level). + cout << "CACHED FIELD_ITEM: " << ifp->db_name << '.' << bestTableName(ifp) << '.' << ifp->field_name << endl; + break; + } + } + else if (ref->real_item()->type() == Item::FIELD_ITEM) + { + Item_field* ifp = (Item_field*)ref->real_item(); + cout << "REF FIELD_ITEM: " << ifp->db_name << '.' << bestTableName(ifp) << '.' << ifp->field_name << endl; + break; + } + cout << "UNKNOWN REF ITEM" << endl; + break; + } + case Item::ROW_ITEM: + { + Item_row* row = (Item_row*)item; + cout << "ROW_ITEM: " << endl; + for (uint i = 0; i < row->cols(); i++) + debug_walk(row->element_index(i), 0); + } +#endif + default: + { + cout << "UNKNOWN_ITEM type " << item->type() << endl; + break; + } + } +} +#endif + /* get the smallest column of a table. Used for filling columnmap */ SimpleColumn* getSmallestColumn(boost::shared_ptr csc, CalpontSystemCatalog::TableName& tn, @@ -1654,7 +1586,7 @@ SimpleColumn* getSmallestColumn(boost::shared_ptr csc, // derived table if (tan.schema.empty()) { - for (uint32_t i = 0; i < gwi.derivedTbList.size(); i++) + for (uint i = 0; i < gwi.derivedTbList.size(); i++) { CalpontSelectExecutionPlan *csep = dynamic_cast(gwi.derivedTbList[i].get()); if (tan.alias == csep->derivedTbAlias()) @@ -1665,10 +1597,8 @@ SimpleColumn* getSmallestColumn(boost::shared_ptr csc, sc->columnName(rc->alias()); sc->sequence(0); sc->tableAlias(lower(tan.alias)); - // @bug5634 derived table optimization. - rc->incRefCount(); - sc->derivedTable(csep->derivedTbAlias()); - sc->derivedRefCol(rc); + //if (!gwi.viewAlias.empty()) + // sc->tableAlias(lower(gwi.viewAlias) + string(".") + sc->tableAlias()); return sc; } } @@ -1760,14 +1690,7 @@ CalpontSystemCatalog::ColType colType_MysqlToIDB (const Item* item) switch (item->result_type()) { case INT_RESULT: - if (item->unsigned_flag) - { - ct.colDataType = CalpontSystemCatalog::UBIGINT; - } - else - { - ct.colDataType = CalpontSystemCatalog::BIGINT; - } + ct.colDataType = CalpontSystemCatalog::BIGINT; ct.colWidth = 8; break; case STRING_RESULT: @@ -1858,38 +1781,25 @@ ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupp case Item::VARBIN_ITEM: { String val, *str = item->val_str(&val); - if (item->unsigned_flag) - { - //cc = new ConstantColumn(str->c_ptr(), (uint64_t)item->val_uint(), ConstantColumn::NUM); - // It seems that str at this point is crap if val_uint() is > MAX_BIGINT. By using - // this constructor, ConstantColumn is built with the proper string. For whatever reason, - // ExeMgr converts the fConstval member to numeric, rather than using the existing numeric - // values available, so it's important to have fConstval correct. - rc = new ConstantColumn((uint64_t)item->val_uint(), ConstantColumn::NUM); - } - else - { - rc = new ConstantColumn(str->c_ptr(), (int64_t)item->val_int(), ConstantColumn::NUM); - } - //return cc; - break; + ConstantColumn *cc = new ConstantColumn(str->c_ptr(), (int64_t)item->val_int(), ConstantColumn::NUM); + return cc; } case Item::STRING_ITEM: { String val, *str = item->val_str(&val); - rc = new ConstantColumn(str->c_ptr()); - break; + ConstantColumn *cc = new ConstantColumn(str->c_ptr()); + return cc; } case Item::REAL_ITEM: { String val, *str = item->val_str(&val); - rc = new ConstantColumn(str->c_ptr(), item->val_real()); - break; + ConstantColumn *cc = new ConstantColumn(str->c_ptr(), (int64_t)item->val_int(), ConstantColumn::NUM); + return cc; } case Item::DECIMAL_ITEM: { - rc = buildDecimalColumn(item, gwi); - break; + ConstantColumn *cc = buildDecimalColumn(item, gwi); + return cc; } case Item::FUNC_ITEM: { @@ -1902,37 +1812,27 @@ ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupp uint16_t parseInfo = 0; parse_item(ifp, tmpVec, gwi.fatalParseError, parseInfo); - if (parseInfo & SUB_BIT) - { - gwi.fatalParseError = true; - gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_SELECT_SUB); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); - break; - } - - if (!gwi.fatalParseError && - !nonConstFunc(ifp) && - !(parseInfo & AF_BIT) && - (tmpVec.size() == 0)) + if (!gwi.fatalParseError && !nonConstFunc(ifp) && (tmpVec.size() == 0)) { String val, *str = ifp->val_str(&val); + ConstantColumn *cc = NULL; if (!str) { - rc = new ConstantColumn("", ConstantColumn::NULLDATA); + cc = new ConstantColumn("", ConstantColumn::NULLDATA); } else if (ifp->result_type() == STRING_RESULT) { - rc = new ConstantColumn(str->c_ptr(), ConstantColumn::LITERAL); - rc->resultType(colType_MysqlToIDB(item)); + cc = new ConstantColumn(str->c_ptr(), ConstantColumn::LITERAL); + cc->resultType(colType_MysqlToIDB(item)); } else if (ifp->result_type() == DECIMAL_RESULT) - rc = buildDecimalColumn(ifp, gwi); + cc = buildDecimalColumn(ifp, gwi); else { - rc = new ConstantColumn(str->c_ptr(), ConstantColumn::NUM); - rc->resultType(colType_MysqlToIDB(item)); + cc = new ConstantColumn(str->c_ptr(), ConstantColumn::NUM); + cc->resultType(colType_MysqlToIDB(item)); } - break; + return cc; } if (func_name == "+" || func_name == "-" || func_name == "*" || func_name == "/" ) @@ -1948,9 +1848,7 @@ ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupp { Item_ref* ref = (Item_ref*)item; if ((*(ref->ref))->type() == Item::SUM_FUNC_ITEM) - { return buildAggregateColumn(*(ref->ref), gwi); - } else if ((*(ref->ref))->type() == Item::FIELD_ITEM) return buildReturnedColumn(*(ref->ref), gwi, nonSupport); else if ((*(ref->ref))->type() == Item::REF_ITEM) @@ -1973,7 +1871,7 @@ ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupp case Item::CACHE_ITEM: { Item* col = ((Item_cache*)item)->get_example(); - rc = buildReturnedColumn(col, gwi, nonSupport); + ReturnedColumn *rc = buildReturnedColumn(col, gwi, nonSupport); if (rc) { ConstantColumn *cc = dynamic_cast(rc); @@ -1984,28 +1882,7 @@ ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupp gwi.subQuery->correlated(true); } } - break; - } - case Item::WINDOW_FUNC_ITEM: - { - return buildWindowFunctionColumn(item, gwi, nonSupport); - } - case Item::INTERVAL_ITEM: - { - Item_interval* interval = (Item_interval*)item; - SRCP srcp; - srcp.reset(buildReturnedColumn(interval->item, gwi, nonSupport)); - if (!srcp) - return NULL; - - rc = new IntervalColumn(srcp, (int)interval->interval); - rc->resultType(srcp->resultType()); - break; - } - case Item::SUBSELECT_ITEM: - { - gwi.hasSubSelect = true; - break; + return rc; } default: @@ -2015,17 +1892,11 @@ ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupp break; } } - if (rc && item->name) - rc->alias(item->name); return rc; } ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info& gwi, bool& nonSupport) { - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - ArithmeticColumn* ac = new ArithmeticColumn(); Item** sfitempp = item->arguments(); ArithmeticOperator* aop = new ArithmeticOperator(item->func_name()); @@ -2044,6 +1915,17 @@ ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info& gwi, bool { lhs = new ParseTree(buildReturnedColumn(sfitempp[0], gwi, nonSupport)); rhs = new ParseTree(buildReturnedColumn(sfitempp[1], gwi, nonSupport)); + if (!lhs->data() || !rhs->data()) + { + gwi.fatalParseError = true; + if (gwi.parseErrorText.empty()) + gwi.parseErrorText = "Un-recognized Arithmetic Operand"; + return NULL; + } + else if (nonSupport) + { + return NULL; + } } else // where clause { @@ -2097,16 +1979,6 @@ ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info& gwi, bool } } - if (!lhs->data() || !rhs->data() || nonSupport) - { - gwi.fatalParseError = true; - if (gwi.parseErrorText.empty()) - gwi.parseErrorText = "Un-recognized Arithmetic Operand"; - delete lhs; - delete rhs; - return NULL; - } - //aop->operationType(lhs->resultType(), rhs->resultType()); pt->left(lhs); pt->right(rhs); @@ -2130,28 +2002,11 @@ ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info& gwi, bool gwi.rcWorkStack.pop(); } } - if (!rhs->data() || nonSupport) - { - gwi.fatalParseError = true; - if (gwi.parseErrorText.empty()) - gwi.parseErrorText = "Un-recognized Arithmetic Operand"; - delete rhs; - return NULL; - } pt->left(cc); pt->right(rhs); } - //aop->resultType(colType_MysqlToIDB(item)); - // @bug5715. Use InfiniDB adjusted coltype for result type. - // decimal arithmetic operation gives double result when the session variable is set. - //idbassert(pt->left() && pt->right() && pt->left()->data() && pt->right()->data()); - CalpontSystemCatalog::ColType mysql_type = colType_MysqlToIDB(item); - if (gwi.thd->variables.infinidb_double_for_decimal_math == 1) - aop->adjustResultType(mysql_type); - else - aop->resultType(mysql_type); - + aop->resultType(colType_MysqlToIDB(item)); // adjust decimal result type according to internalDecimalScale if (gwi.internalDecimalScale >= 0 && aop->resultType().colDataType == CalpontSystemCatalog::DECIMAL) { @@ -2164,11 +2019,11 @@ ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info& gwi, bool ac->expression(pt); ac->resultType(aop->resultType()); ac->operationType(aop->operationType()); - ac->expressionId(ci->expressionId++); + ac->expressionId(gwi.expressionId++); // @3391. optimization. try to associate expression ID to the expression on the select list if (gwi.clauseType != SELECT) { - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { if ((!ac->alias().empty()) && strcasecmp(ac->alias().c_str(), gwi.returnedCols[i]->alias().c_str()) == 0) { @@ -2177,50 +2032,16 @@ ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info& gwi, bool } } } - - // For function join. If any argument has non-zero joininfo, set it to the function. - ac->setSimpleColumnList(); - std::vector simpleColList = ac->simpleColumnList(); - for (uint i = 0; i < simpleColList.size(); i++) - { - if (simpleColList[i]->joinInfo() != 0) - { - ac->joinInfo(simpleColList[i]->joinInfo()); - break; - } - } return ac; } ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& nonSupport) { - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - string funcName = ifp->func_name(); FuncExp* funcExp = FuncExp::instance(); Func* functor; FunctionColumn *fc = NULL; - // Pseudocolumn - uint32_t pseudoType = PSEUDO_UNKNOWN; - if (ifp->functype() == Item_func::UDF_FUNC) - pseudoType = PseudoColumn::pseudoNameToType(funcName); - - if (pseudoType != PSEUDO_UNKNOWN) - { - ReturnedColumn* rc = buildPseudoColumn(ifp, gwi, gwi.fatalParseError, pseudoType); - if (!rc || gwi.fatalParseError) - { - if (gwi.parseErrorText.empty()) - gwi.parseErrorText = "Unsupported function."; - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); - return NULL; - } - return rc; - } - // Arithmetic exp if (funcName == "+" || funcName == "-" || funcName == "*" || funcName == "/" ) { @@ -2254,7 +2075,7 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non (*(((Item_ref*)ifp->arguments()[0])->ref))->type() == Item::FIELD_ITEM)) { bool fe = false; - for (uint32_t i = 1; i < ifp->arg_count; i++) + for (uint i = 1; i < ifp->arg_count; i++) { if (!(ifp->arguments()[i]->type() == Item::INT_ITEM || ifp->arguments()[i]->type() == Item::STRING_ITEM || @@ -2269,7 +2090,7 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non uint16_t parseInfo = 0; parse_item(ifp->arguments()[i], tmpVec, gwi.fatalParseError, parseInfo); - if (!gwi.fatalParseError && !(parseInfo & AF_BIT) && tmpVec.size() == 0) + if (!gwi.fatalParseError && tmpVec.size() == 0) continue; } fe = true; @@ -2290,12 +2111,12 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non ClauseType clauseType = gwi.clauseType; if (gwi.clauseType == SELECT || /*gwi.clauseType == HAVING || */gwi.clauseType == GROUP_BY) // select clause { - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { // group by clause try to see if the arguments are alias if (gwi.clauseType == GROUP_BY && ifp->arguments()[i]->name) { - uint32_t j = 0; + uint j = 0; for (; j < gwi.returnedCols.size(); j++) { if (string (ifp->arguments()[i]->name) == gwi.returnedCols[j]->alias()) @@ -2348,7 +2169,7 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non else // where clause { stack tmpPtStack;; - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { if (funcName == "if" ) { @@ -2393,13 +2214,6 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non { if (gwi.rcWorkStack.empty()) { - ReturnedColumn *rc = buildReturnedColumn(ifp->arguments()[i], gwi, nonSupport); - if (!rc || nonSupport) - { - nonSupport = true; - gwi.fatalParseError = true; - return NULL; - } sptp.reset(new ParseTree(buildReturnedColumn(ifp->arguments()[i], gwi, nonSupport))); } else @@ -2423,14 +2237,13 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non if (funcName == "week" && funcParms.size() == 1) { THD* thd = current_thd; - sptp.reset(new ParseTree(new ConstantColumn(static_cast(thd->variables.default_week_format)))); + sptp.reset(new ParseTree(new ConstantColumn(thd->variables.default_week_format))); funcParms.push_back(sptp); } // add the keyword unit argument for interval function if (funcName == "date_add_interval" || funcName == "extract" || funcName == "timestampdiff") { - addIntervalArgs(ifp, funcParms); } @@ -2499,10 +2312,10 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non time_t tmp_t= 1; struct tm tmp; localtime_r(&tmp_t, &tmp); - sptp.reset(new ParseTree(new ConstantColumn(static_cast(tmp.tm_gmtoff), ConstantColumn::NUM))); + sptp.reset(new ParseTree(new ConstantColumn(tmp.tm_gmtoff, ConstantColumn::NUM))); #else //FIXME: Get GMT offset (in seconds east of GMT) in Windows... - sptp.reset(new ParseTree(new ConstantColumn(static_cast(0), ConstantColumn::NUM))); + sptp.reset(new ParseTree(new ConstantColumn(0, ConstantColumn::NUM))); #endif funcParms.push_back(sptp); } @@ -2534,12 +2347,12 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non if (funcName == "add_time") { Item_func_add_time* addtime = (Item_func_add_time*)ifp; - sptp.reset(new ParseTree(new ConstantColumn((int64_t)addtime->get_sign()))); + sptp.reset(new ParseTree(new ConstantColumn(addtime->get_sign()))); funcParms.push_back(sptp); } fc->functionName(funcName); - fc->functionParms(funcParms); + fc->funcParms(funcParms); fc->resultType(colType_MysqlToIDB(ifp)); // MySQL give string result type for date function, but has the flag set. @@ -2560,7 +2373,7 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non } fc->operationType(functor->operationType(funcParms, fc->resultType())); - fc->expressionId(ci->expressionId++); + fc->expressionId(gwi.expressionId++); } else if (ifp->type() == Item::COND_ITEM || ifp->functype() == Item_func::EQ_FUNC || @@ -2575,9 +2388,7 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non ifp->functype() == Item_func::ISNULL_FUNC || ifp->functype() == Item_func::ISNOTNULL_FUNC || ifp->functype() == Item_func::NOT_FUNC) - { return NULL; - } else { nonSupport = true; @@ -2603,33 +2414,17 @@ ReturnedColumn* buildFunctionColumn(Item_func* ifp, gp_walk_info& gwi, bool& non // @3391. optimization. try to associate expression ID to the expression on the select list if (gwi.clauseType != SELECT) { - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { if ((!fc->alias().empty()) && strcasecmp(fc->alias().c_str(), gwi.returnedCols[i]->alias().c_str()) == 0) fc->expressionId(gwi.returnedCols[i]->expressionId()); } } - - // For function join. If any argument has non-zero joininfo, set it to the function. - fc->setSimpleColumnList(); - std::vector simpleColList = fc->simpleColumnList(); - for (uint i = 0; i < simpleColList.size(); i++) - { - if (simpleColList[i]->joinInfo() != 0) - { - fc->joinInfo(simpleColList[i]->joinInfo()); - break; - } - } return fc; } FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonSupport) { - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - FunctionColumn* fc = new FunctionColumn(); FunctionParm funcParms; SPTP sptp; @@ -2645,7 +2440,7 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS // the first argument if (funcName == "case_searched") { - for (uint32_t i = 0; i < item->arg_count; i++) + for (uint i = 0; i < item->arg_count; i++) { if (i % 2 == 0 && i != 1 && i != item->arg_count-1) { @@ -2669,7 +2464,7 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS } else { - for (uint32_t i = 0; i < item->arg_count; i++) + for (uint i = 0; i < item->arg_count; i++) { ReturnedColumn* parm = buildReturnedColumn(item->arguments()[i], gwi, nonSupport); if (parm) @@ -2690,7 +2485,7 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS gwi.clauseType = SELECT; if (funcName == "case_searched") { - for (uint32_t i = 0; i < item->arg_count; i++) + for (uint i = 0; i < item->arg_count; i++) { if (i % 2 == 0 && i != item->arg_count-1) { @@ -2705,7 +2500,7 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS ReturnedColumn* parm = buildReturnedColumn(item->arguments()[i], gwi, nonSupport); if (parm) { - sptp.reset(new ParseTree(parm)); + sptp.reset(new ParseTree(buildReturnedColumn(item->arguments()[i], gwi, nonSupport))); if (!gwi.rcWorkStack.empty()) gwi.rcWorkStack.pop(); } @@ -2721,7 +2516,7 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS } else // simple_case { - for (uint32_t i = 0; i < item->arg_count; i++) + for (uint i = 0; i < item->arg_count; i++) { ReturnedColumn* parm = buildReturnedColumn(item->arguments()[i], gwi, nonSupport); if (parm) @@ -2745,7 +2540,7 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS if (gwi.fatalParseError) { - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return NULL; } @@ -2753,20 +2548,8 @@ FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonS fc->resultType(colType_MysqlToIDB(item)); fc->operationType(functor->operationType(funcParms, fc->resultType())); fc->functionName(funcName); - fc->functionParms(funcParms); - fc->expressionId(ci->expressionId++); - - // For function join. If any argument has non-zero joininfo, set it to the function. - fc->setSimpleColumnList(); - std::vector simpleColList = fc->simpleColumnList(); - for (uint i = 0; i < simpleColList.size(); i++) - { - if (simpleColList[i]->joinInfo() != 0) - { - fc->joinInfo(simpleColList[i]->joinInfo()); - break; - } - } + fc->funcParms(funcParms); + fc->expressionId(gwi.expressionId++); return fc; } @@ -2776,7 +2559,7 @@ ConstantColumn* buildDecimalColumn(Item *item, gp_walk_info &gwi) IDB_Decimal infinidb_decimal; String val, *str = item->val_str(&val); ostringstream infinidb_decimal_val; - uint32_t i = 0; + uint i = 0; if (str->c_ptr()[0] == '+' || str->c_ptr()[0] == '-') { infinidb_decimal_val << str->c_ptr()[0]; @@ -2788,12 +2571,12 @@ ConstantColumn* buildDecimalColumn(Item *item, gp_walk_info &gwi) continue; infinidb_decimal_val << str->c_ptr()[i]; } - infinidb_decimal.value = strtoll(infinidb_decimal_val.str().c_str(), 0, 10); + infinidb_decimal.value = atol(infinidb_decimal_val.str().c_str()); if (gwi.internalDecimalScale >= 0 && idp->decimals > gwi.internalDecimalScale) - { - infinidb_decimal.scale = gwi.internalDecimalScale; - double val = (double)(infinidb_decimal.value / pow((double)10, idp->decimals - gwi.internalDecimalScale)); + { + infinidb_decimal.scale = gwi.internalDecimalScale; + double val = (double)(infinidb_decimal.value / pow((double)10, idp->decimals - gwi.internalDecimalScale)); infinidb_decimal.value = (int64_t)(val > 0 ? val + 0.5 : val - 0.5); } else @@ -2810,16 +2593,9 @@ SimpleColumn* buildSimpleColumn(Item_field* ifp, gp_walk_info& gwi) gwi.csc->identity(CalpontSystemCatalog::FE); } - bool isInformationSchema = false; - - // @bug5523 - if (ifp->cached_table && strcmp(ifp->cached_table->db, "information_schema") == 0) - isInformationSchema = true; - // support FRPM subquery. columns from the derived table has no definition - if ((!ifp->field || !ifp->db_name || strlen(ifp->db_name) == 0) && !isInformationSchema) + if (!ifp->field || !ifp->db_name || strlen(ifp->db_name) == 0) return buildSimpleColFromDerivedTable(gwi, ifp); - CalpontSystemCatalog::ColType ct; bool infiniDB = true; @@ -2889,56 +2665,25 @@ SimpleColumn* buildSimpleColumn(Item_field* ifp, gp_walk_info& gwi) ct.colDataType = CalpontSystemCatalog::DECIMAL; } break; - case CalpontSystemCatalog::UTINYINT: - sc = new SimpleColumn_UINT<1>(ifp->db_name, bestTableName(ifp), ifp->field_name, infiniDB, gwi.sessionid); - break; - case CalpontSystemCatalog::USMALLINT: - sc = new SimpleColumn_UINT<2>(ifp->db_name, bestTableName(ifp), ifp->field_name, infiniDB, gwi.sessionid); - break; - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UMEDINT: - sc = new SimpleColumn_UINT<4>(ifp->db_name, bestTableName(ifp), ifp->field_name, infiniDB, gwi.sessionid); - break; - case CalpontSystemCatalog::UBIGINT: - sc = new SimpleColumn_UINT<8>(ifp->db_name, bestTableName(ifp), ifp->field_name, infiniDB, gwi.sessionid); - break; default: sc = new SimpleColumn(ifp->db_name, bestTableName(ifp), ifp->field_name, infiniDB, gwi.sessionid); } sc->resultType(ct); string tbname(ifp->table_name); - if (isInformationSchema) - { - sc->schemaName("information_schema"); - sc->tableName(tbname); - } - sc->tableAlias(lower(tbname)); // view name - sc->viewName(lower(getViewName(ifp->cached_table))); - + if (ifp->cached_table) + sc->viewName(lower(getViewName(ifp->cached_table))); + sc->alias(ifp->name); sc->isInfiniDB(infiniDB); - + //SRCP srcp(sc); + //gwi.columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(string(ifp->field_name), srcp)); +// TABLE_LIST* tmp = (ifp->cached_table ? ifp->cached_table : 0); + //gwi.tableMap[make_aliastable(sc->schemaName(), sc->tableName(), sc->tableAlias(), sc->isInfiniDB())] = make_pair(1, tmp); if (!infiniDB && ifp->field) sc->oid(ifp->field->field_index + 1); // ExeMgr requires offset started from 1 - - if (ifp->depended_from) - { - sc->joinInfo(sc->joinInfo() | JOIN_CORRELATED); - if (gwi.subQuery) - gwi.subQuery->correlated(true); - - // for error out non-support select filter case (comparison outside semi join tables) - gwi.correlatedTbNameVec.push_back(make_aliastable(sc->schemaName(), sc->tableName(), sc->tableAlias())); - - // imply semi for scalar for now. - if (gwi.subSelectType == CalpontSelectExecutionPlan::SINGLEROW_SUBS) - sc->joinInfo(sc->joinInfo() | JOIN_SCALAR | JOIN_SEMI); - if (gwi.subSelectType == CalpontSelectExecutionPlan::SELECT_SUBS) - sc->joinInfo(sc->joinInfo() | JOIN_SCALAR | JOIN_OUTER_SELECT); - } return sc; } @@ -2973,12 +2718,8 @@ ParseTree* buildParseTree(Item_func* item, gp_walk_info& gwi, bool& nonSupport) return pt; } -ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) +AggregateColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) { - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - Item_sum* isp = reinterpret_cast(item); Item** sfitempp = isp->args; SRCP parm; @@ -2987,7 +2728,7 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) gwi.aggOnSelect = true; // N.B. arg_count is the # of formal parms to the agg fcn. InifniDB only supports 1 argument - if (isp->arg_count != 1 && isp->sum_func() != Item_sum::GROUP_CONCAT_FUNC) + if (isp->arg_count > 1 && isp->sum_func() != Item_sum::GROUP_CONCAT_FUNC) { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_MUL_ARG_AGG); @@ -3017,10 +2758,9 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) vector orderCols; RowColumn *rowCol = new RowColumn(); vector selCols; - uint32_t select_ctn = gc->count_field(); ReturnedColumn *rc = NULL; - for (uint32_t i = 0; i < select_ctn; i++) + for (uint i = 0; i < select_ctn; i++) { rc = buildReturnedColumn(sfitempp[i], gwi, gwi.fatalParseError); if (!rc || gwi.fatalParseError) @@ -3029,9 +2769,8 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) } ORDER **order_item, **end; - for (order_item= gc->order, - end=order_item + gc->order_field();order_item < end; - order_item++) + for (order_item= gc->order, end=order_item + gc->order_field();order_item < end; + order_item++) { Item *ord_col= *(*order_item)->item; if (ord_col->type() == Item::INT_ITEM) @@ -3061,10 +2800,11 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) } else { - for (uint32_t i = 0; i < isp->arg_count; i++) + for (uint i = 0; i < isp->arg_count; i++) { Item* sfitemp = sfitempp[i]; Item::Type sfitype = sfitemp->type(); + switch (sfitype) { case Item::FIELD_ITEM: @@ -3076,7 +2816,7 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) gwi.fatalParseError = true; break; } - + parm.reset(sc); gwi.columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(string(ifp->field_name), parm)); TABLE_LIST* tmp = (ifp->cached_table ? ifp->cached_table : 0); @@ -3092,6 +2832,7 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) if (ac->aggOp() == AggregateColumn::COUNT) ac->aggOp(AggregateColumn::COUNT_ASTERISK); + gwi.count_asterisk_list.push_back(ac); ac->constCol(SRCP(buildReturnedColumn(sfitemp, gwi, gwi.fatalParseError))); break; } @@ -3100,6 +2841,7 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) //ac->aggOp(AggregateColumn::COUNT); parm.reset(new ConstantColumn("", ConstantColumn::NULLDATA)); //ac->functionParms(parm); + gwi.count_asterisk_list.push_back(ac); ac->constCol(SRCP(buildReturnedColumn(sfitemp, gwi, gwi.fatalParseError))); break; } @@ -3117,33 +2859,31 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) gwi.fatalParseError = true; break; } - else if (!gwi.fatalParseError && - !(parseInfo & AGG_BIT) && - !(parseInfo & AF_BIT) && - tmpVec.size() == 0) + + else if (!gwi.fatalParseError && !(parseInfo & AGG_BIT) && tmpVec.size() == 0) { rc = buildFunctionColumn(ifp, gwi, gwi.fatalParseError); FunctionColumn* fc = dynamic_cast(rc); if ((fc && fc->functionParms().empty()) || !fc) { - //ac->aggOp(AggregateColumn::COUNT_ASTERISK); ReturnedColumn* rc = buildReturnedColumn(sfitemp, gwi, gwi.fatalParseError); if (dynamic_cast(rc)) { //@bug5229. handle constant function on aggregate argument + gwi.count_asterisk_list.push_back(ac); ac->constCol(SRCP(rc)); break; - } + } } } - + // MySQL carelessly allows correlated aggregate function on the WHERE clause. // Here is the work around to deal with that inconsistence. // e.g., SELECT (SELECT t.c FROM t1 AS t WHERE t.b=MAX(t1.b + 0)) FROM t1; ClauseType clauseType = gwi.clauseType; if (gwi.clauseType == WHERE) gwi.clauseType = HAVING; - // @bug 3603. for cases like max(rand()). try to build function first. + // @bug 3606. for cases like max(rand()). try to build function first. if (!rc) rc = buildFunctionColumn(ifp, gwi, gwi.fatalParseError); @@ -3198,16 +2938,10 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) { case CalpontSystemCatalog::TINYINT: case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::BIGINT: case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: ct.colDataType = CalpontSystemCatalog::DECIMAL; ct.colWidth = 8; ct.scale += 4; @@ -3215,9 +2949,7 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) #if PROMOTE_FLOAT_TO_DOUBLE_ON_SUM case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: ct.colDataType = CalpontSystemCatalog::DOUBLE; ct.colWidth = 8; break; @@ -3245,31 +2977,19 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) { case CalpontSystemCatalog::TINYINT: case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: + case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::BIGINT: ct.colDataType = CalpontSystemCatalog::BIGINT; // no break, let fall through case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: - ct.colWidth = 8; - break; - - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - ct.colDataType = CalpontSystemCatalog::UBIGINT; ct.colWidth = 8; break; #if PROMOTE_FLOAT_TO_DOUBLE_ON_SUM case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: ct.colDataType = CalpontSystemCatalog::DOUBLE; ct.colWidth = 8; break; @@ -3326,29 +3046,15 @@ ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi) } // check for same aggregate on the select list - ac->expressionId(ci->expressionId++); + ac->expressionId(gwi.expressionId++); if (gwi.clauseType != SELECT) { - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { if (*ac == gwi.returnedCols[i].get()) ac->expressionId(gwi.returnedCols[i]->expressionId()); } } - - // @bug5977 @note Temporary fix to avoid mysqld crash. The permanent fix will - // be applied in ExeMgr. When the ExeMgr fix is available, this checking - // will be taken out. - if (ac->constCol() && gwi.tbList.empty() && gwi.derivedTbList.empty()) - { - gwi.fatalParseError = true; - gwi.parseErrorText = "No project column found for aggregate function"; - return NULL; - } - else if (ac->constCol()) - { - gwi.count_asterisk_list.push_back(ac); - } return ac; } @@ -3363,36 +3069,93 @@ void addIntervalArgs(Item_func* ifp, FunctionParm& functionParms) else if (funcName == "extract") interval_type = ((Item_extract*)ifp)->int_type; - functionParms.push_back(getIntervalType(interval_type)); SPTP sptp; + switch (interval_type) { + case INTERVAL_YEAR: + sptp.reset(new ParseTree(new ConstantColumn("YEAR"))); + break; + case INTERVAL_QUARTER: + sptp.reset(new ParseTree(new ConstantColumn("QUARTER"))); + break; + case INTERVAL_MONTH: + sptp.reset(new ParseTree(new ConstantColumn("MONTH"))); + break; + case INTERVAL_WEEK: + sptp.reset(new ParseTree(new ConstantColumn("WEEK"))); + break; + case INTERVAL_DAY: + sptp.reset(new ParseTree(new ConstantColumn("DAY"))); + break; + case INTERVAL_HOUR: + sptp.reset(new ParseTree(new ConstantColumn("HOUR"))); + break; + case INTERVAL_MICROSECOND: + sptp.reset(new ParseTree(new ConstantColumn("MICROSECOND"))); + break; + case INTERVAL_MINUTE: + sptp.reset(new ParseTree(new ConstantColumn("MINUTE"))); + break; + case INTERVAL_SECOND: + sptp.reset(new ParseTree(new ConstantColumn("SECOND"))); + break; + case INTERVAL_YEAR_MONTH: + sptp.reset(new ParseTree(new ConstantColumn("YEAR_MONTH"))); + break; + case INTERVAL_DAY_HOUR: + sptp.reset(new ParseTree(new ConstantColumn("DAY_HOUR"))); + break; + case INTERVAL_DAY_MICROSECOND: + sptp.reset(new ParseTree(new ConstantColumn("DAY_MICROSECOND"))); + break; + case INTERVAL_DAY_MINUTE: + sptp.reset(new ParseTree(new ConstantColumn("DAY_MINUTE"))); + break; + case INTERVAL_DAY_SECOND: + sptp.reset(new ParseTree(new ConstantColumn("DAY_SECOND"))); + break; + case INTERVAL_HOUR_MICROSECOND: + sptp.reset(new ParseTree(new ConstantColumn("HOUR_MICROSECOND"))); + break; + case INTERVAL_HOUR_MINUTE: + sptp.reset(new ParseTree(new ConstantColumn("HOUR_MINUTE"))); + break; + case INTERVAL_HOUR_SECOND: + sptp.reset(new ParseTree(new ConstantColumn("HOUR_SECOND"))); + break; + case INTERVAL_MINUTE_MICROSECOND: + sptp.reset(new ParseTree(new ConstantColumn("MINUTE_MICROSECOND"))); + break; + case INTERVAL_MINUTE_SECOND: + sptp.reset(new ParseTree(new ConstantColumn("MINUTE_SECOND"))); + break; + case INTERVAL_SECOND_MICROSECOND: + sptp.reset(new ParseTree(new ConstantColumn("SECOND_MICROSECOND"))); + break; + default: + sptp.reset(new ParseTree(new ConstantColumn("UNKNOWN"))); + } + functionParms.push_back(sptp); if (funcName == "date_add_interval") { if (((Item_date_add_interval*)ifp)->date_sub_interval) { - sptp.reset(new ParseTree(new ConstantColumn((int64_t)OP_SUB))); + sptp.reset(new ParseTree(new ConstantColumn("SUB"))); functionParms.push_back(sptp); } else { - sptp.reset(new ParseTree(new ConstantColumn((int64_t)OP_ADD))); + sptp.reset(new ParseTree(new ConstantColumn("ADD"))); functionParms.push_back(sptp); } } } -SPTP getIntervalType(int interval_type) -{ - SPTP sptp; - sptp.reset(new ParseTree(new ConstantColumn((int64_t)interval_type))); - return sptp; -} - void castCharArgs(Item_func* ifp, FunctionParm& functionParms) { Item_char_typecast * idai = (Item_char_typecast *)ifp; SPTP sptp; - sptp.reset(new ParseTree(new ConstantColumn((int64_t)idai->castLength()))); + sptp.reset(new ParseTree(new ConstantColumn(idai->castLength()))); functionParms.push_back(sptp); } @@ -3400,13 +3163,13 @@ void castDecimalArgs(Item_func* ifp, FunctionParm& functionParms) { Item_decimal_typecast * idai = (Item_decimal_typecast *)ifp; SPTP sptp; - sptp.reset(new ParseTree(new ConstantColumn((int64_t)idai->decimals))); + sptp.reset(new ParseTree(new ConstantColumn(idai->decimals))); functionParms.push_back(sptp); // max length including sign and/or decimal points if (idai->decimals == 0) - sptp.reset(new ParseTree(new ConstantColumn((int64_t)idai->max_length-1))); + sptp.reset(new ParseTree(new ConstantColumn( idai->max_length-1))); else - sptp.reset(new ParseTree(new ConstantColumn((int64_t)idai->max_length-2))); + sptp.reset(new ParseTree(new ConstantColumn( idai->max_length-2))); functionParms.push_back(sptp); } @@ -3444,13 +3207,25 @@ void gp_walk(const Item *item, void *arg) if (!scp) break; string aliasTableName(scp->tableAlias()); + + if (ifp->depended_from) + { + scp->joinInfo(scp->joinInfo() | JOIN_CORRELATED); + if (gwip->subQuery) + gwip->subQuery->correlated(true); + // for error out non-support select filter case (comparison outside semi join tables) + gwip->correlatedTbNameVec.push_back(make_aliastable(scp->schemaName(), scp->tableName(), scp->tableAlias())); + + // imply semi for scalar for now. + if (gwip->subSelectType == CalpontSelectExecutionPlan::SINGLEROW_SUBS) + scp->joinInfo(scp->joinInfo() | JOIN_SCALAR | JOIN_SEMI); + if (gwip->subSelectType == CalpontSelectExecutionPlan::SELECT_SUBS) + scp->joinInfo(scp->joinInfo() | JOIN_SCALAR | JOIN_OUTER_SELECT); + } scp->tableAlias(lower(aliasTableName)); gwip->rcWorkStack.push(scp->clone()); - //gwip->rcWorkStack.push(scp); - boost::shared_ptr scsp(scp); - //boost::shared_ptr scsp(scp->clone()); + shared_ptr scsp(scp); gwip->scsp = scsp; - gwip->funcName.clear(); gwip->columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(string(ifp->field_name), scsp)); @@ -3536,7 +3311,7 @@ void gp_walk(const Item *item, void *arg) } if (ifp->arguments() && ifp->arg_count > 0) { - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { if (ifp->arguments()[i]->type() == Item::SUBSELECT_ITEM) { @@ -3575,7 +3350,7 @@ void gp_walk(const Item *item, void *arg) if (gwip->condPush) { set tableSet; - for (uint32_t i = 0; i < tmpVec.size(); i++) + for (uint i = 0; i < tmpVec.size(); i++) { if (tmpVec[i]->table_name) tableSet.insert(tmpVec[i]->table_name); @@ -3584,11 +3359,9 @@ void gp_walk(const Item *item, void *arg) break; } - if (!gwip->fatalParseError && !(parseInfo & AGG_BIT) && - !(parseInfo & SUB_BIT) && - !nonConstFunc(ifp) && - !(parseInfo & AF_BIT) && - tmpVec.size() == 0) + if (!gwip->fatalParseError && !(parseInfo & AGG_BIT) && + !(parseInfo & SUB_BIT) && + !nonConstFunc(ifp) && tmpVec.size() == 0) { String val, *str = ifp->val_str(&val); @@ -3611,7 +3384,7 @@ void gp_walk(const Item *item, void *arg) cc->resultType(colType_MysqlToIDB(item)); } - for (uint32_t i = 0; i < ifp->arg_count && !gwip->rcWorkStack.empty(); i++) + for (uint i = 0; i < ifp->arg_count && !gwip->rcWorkStack.empty(); i++) { gwip->rcWorkStack.pop(); } @@ -3648,7 +3421,7 @@ void gp_walk(const Item *item, void *arg) // predicate operators fall in the old path if (rc) { - // @bug 2383. For some reason func_name() for "in" gives " IN " always + // @bug 2383. Fow some reason func_name() for "in" gives " IN " allways if (funcName == "between" || funcName == "in" || funcName == " IN ") gwip->ptWorkStack.push(new ParseTree(rc)); else @@ -3681,39 +3454,26 @@ void gp_walk(const Item *item, void *arg) //if (gwip->ptWorkStack.size() < icp->argument_list()->elements) { List_iterator_fast li(*(icp->argument_list())); - while (Item *it= li++) - { - //@bug3495, @bug5865 error out non-supported OR with correlated subquery - if (icp->functype() == Item_func::COND_OR_FUNC) - { - vector fieldVec; - uint16_t parseInfo = 0; - parse_item(it, fieldVec, gwip->fatalParseError, parseInfo); - if (parseInfo & CORRELATED) - { - gwip->fatalParseError = true; - gwip->parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_CORRELATED_SUB_OR); - return; - } - } - if ((it->type() == Item::FIELD_ITEM - || it->type() == Item::INT_ITEM - || it->type() == Item::DECIMAL_ITEM - || it->type() == Item::STRING_ITEM - || it->type() == Item::REAL_ITEM - || it->type() == Item::NULL_ITEM - || (it->type() == Item::FUNC_ITEM - && !isPredicateFunction(it, gwip))) && !gwip->rcWorkStack.empty() - ) - { - gwip->ptWorkStack.push(new ParseTree(gwip->rcWorkStack.top())); - gwip->rcWorkStack.pop(); - } - } - } + while (Item *it= li++) + { + if ((it->type() == Item::FIELD_ITEM + || it->type() == Item::INT_ITEM + || it->type() == Item::DECIMAL_ITEM + || it->type() == Item::STRING_ITEM + || it->type() == Item::REAL_ITEM + || it->type() == Item::NULL_ITEM + || (it->type() == Item::FUNC_ITEM + && !isPredicateFunction(it, gwip))) && !gwip->rcWorkStack.empty() + ) + { + gwip->ptWorkStack.push(new ParseTree(gwip->rcWorkStack.top())); + gwip->rcWorkStack.pop(); + } + } + } // @bug1603. MySQL's filter tree is a multi-tree grouped by operator. So more than // two filters saved on the stack so far might belong to this operator. - uint32_t leftInStack = gwip->ptWorkStack.size() - icp->argument_list()->elements + 1; + uint leftInStack = gwip->ptWorkStack.size() - icp->argument_list()->elements + 1; while (true) { if (gwip->ptWorkStack.size() < 2) @@ -3754,6 +3514,23 @@ void gp_walk(const Item *item, void *arg) Operator* op = new LogicOperator(icp->func_name()); ParseTree* ptp = new ParseTree(op); + // bug 3459. error out non-supported OR with correlated subquery + if (icp->functype() == Item_func::COND_OR_FUNC) + { + SelectFilter *lsel = dynamic_cast(lhs->data()); + SelectFilter *rsel = dynamic_cast(rhs->data()); + ExistsFilter *lexists = dynamic_cast(lhs->data()); + ExistsFilter *rexists = dynamic_cast(rhs->data()); + + if ((lsel && lsel->correlated()) || (rsel && rsel->correlated()) || + (lexists && lexists->correlated()) || (rexists && rexists->correlated())) + { + gwip->fatalParseError = true; + gwip->parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_CORRELATED_SUB_OR); + break; + } + } + ptp->left(lhs); ptp->right(rhs); gwip->ptWorkStack.push(ptp); @@ -3781,7 +3558,7 @@ void gp_walk(const Item *item, void *arg) SimpleColumn *sc = dynamic_cast(rc); if (sc) { - boost::shared_ptr scsp(sc->clone()); + shared_ptr scsp(sc->clone()); gwip->scsp = scsp; } @@ -3794,7 +3571,6 @@ void gp_walk(const Item *item, void *arg) rc->joinInfo(rc->joinInfo() | JOIN_CORRELATED); if (gwip->subQuery) gwip->subQuery->correlated(true); - SimpleColumn *scp = dynamic_cast(rc); if (scp) gwip->correlatedTbNameVec.push_back(make_aliastable(scp->schemaName(), scp->tableName(), scp->tableAlias())); @@ -3811,7 +3587,7 @@ void gp_walk(const Item *item, void *arg) // which are always predicate operator, the function (gp_key>3) comes in as // one item. Item_func* ifp = (Item_func*)col; - for (uint32_t i = 0; i < ifp->arg_count; i++) + for (uint i = 0; i < ifp->arg_count; i++) { ReturnedColumn *operand = NULL; if (ifp->arguments()[i]->type() == Item::REF_ITEM) @@ -3857,30 +3633,12 @@ void gp_walk(const Item *item, void *arg) if (sub->substype() == Item_subselect::EXISTS_SUBS) { - SubQuery *orig = gwip->subQuery; ExistsSub* existsSub = new ExistsSub(*gwip, sub); - gwip->hasSubSelect = true; gwip->subQuery = existsSub; gwip->ptWorkStack.push(existsSub->transform()); current_thd->infinidb_vtable.isUnion = true; // only temp. bypass the 2nd phase. - // recover original - gwip->subQuery = orig; - gwip->lastSub = existsSub; } -#if MYSQL_VERSION_ID >= 50172 - else if (sub->substype() == Item_subselect::IN_SUBS) - { - if (!((Item_in_subselect*)sub)->getOptimizer() && gwip->thd->derived_tables_processing) - { - ostringstream oss; - oss << "Invalid In_optimizer: " << item->type(); - gwip->parseErrorText = oss.str(); - gwip->fatalParseError = true; - break; - } - } -#endif // store a dummy subselect object. the transform is handled in item_func. SubSelect *subselect = new SubSelect(); gwip->rcWorkStack.push(subselect); @@ -3893,22 +3651,13 @@ void gp_walk(const Item *item, void *arg) vector cols; // temp change clause type because the elements of row column are not walked yet gwip->clauseType = SELECT; - for (uint32_t i = 0; i < row->cols(); i++) + for (uint i = 0; i < row->cols(); i++) cols.push_back(SRCP(buildReturnedColumn(row->element_index(i), *gwip, gwip->fatalParseError))); gwip->clauseType = WHERE; rowCol->columnVec(cols); gwip->rcWorkStack.push(rowCol); break; } - case Item::WINDOW_FUNC_ITEM: - { - gwip->hasWindowFunc = true; - Item_func_window* ifa = (Item_func_window*)item; - ReturnedColumn* af = buildWindowFunctionColumn(ifa, *gwip, gwip->fatalParseError); - if (af) - gwip->rcWorkStack.push(af); - break; - } default: { if (gwip->condPush) @@ -3949,21 +3698,15 @@ void parse_item (Item *item, vector& field_vec, bool& hasNonSupport parseInfo |= AGG_BIT; Item_sum* isp = reinterpret_cast(item); Item** sfitempp = isp->args; - for (uint32_t i = 0; i < isp->arg_count; i++) + for (uint i = 0; i < isp->arg_count; i++) parse_item(sfitempp[i], field_vec, hasNonSupportItem, parseInfo); break; } case Item::FUNC_ITEM: { Item_func* isp = reinterpret_cast(item); - if (string(isp->func_name()) == "") - { - parseInfo |= SUB_BIT; - parseInfo |= CORRELATED; - break; - } Item** sfitempp = isp->arguments(); - for (uint32_t i = 0; i < isp->arg_count; i++) + for (uint i = 0; i < isp->arg_count; i++) parse_item(sfitempp[i], field_vec, hasNonSupportItem, parseInfo); break; } @@ -3993,7 +3736,7 @@ void parse_item (Item *item, vector& field_vec, bool& hasNonSupport sfitempp[0]->type() == Item::REAL_ITEM || sfitempp[0]->type() == Item::DECIMAL_ITEM)) field_vec.push_back((Item_field*)item); //dummy - for (uint32_t i = 0; i < isp->arg_count; i++) + for (uint i = 0; i < isp->arg_count; i++) parse_item(sfitempp[i], field_vec, hasNonSupportItem, parseInfo); break; } @@ -4007,7 +3750,7 @@ void parse_item (Item *item, vector& field_vec, bool& hasNonSupport { Item_func* isp = reinterpret_cast(*(ref->ref)); Item** sfitempp = isp->arguments(); - for (uint32_t i = 0; i < isp->arg_count; i++) + for (uint i = 0; i < isp->arg_count; i++) parse_item(sfitempp[i], field_vec, hasNonSupportItem, parseInfo); break; } @@ -4031,22 +3774,15 @@ void parse_item (Item *item, vector& field_vec, bool& hasNonSupport break; } case Item::SUBSELECT_ITEM: - { parseInfo |= SUB_BIT; - Item_subselect* sub = (Item_subselect*)item; - if (sub->is_correlated) - parseInfo |= CORRELATED; break; - } case Item::ROW_ITEM: { Item_row *row = (Item_row*)item; - for (uint32_t i = 0; i < row->cols(); i++) + for (uint i = 0; i < row->cols(); i++) parse_item(row->element_index(i), field_vec, hasNonSupportItem, parseInfo); break; } - case Item::WINDOW_FUNC_ITEM: - parseInfo |= AF_BIT; default: return; } @@ -4076,10 +3812,7 @@ bool isInfiniDB(TABLE* table_ptr) int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool isUnion) { // by pass the derived table resolve phase of mysql - if (!(((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || - ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || - ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || - ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI ) ) && gwi.thd->derived_tables_processing) + if (!(((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI ) ) && gwi.thd->derived_tables_processing) { gwi.thd->infinidb_vtable.isUnion = false; return -1; @@ -4090,7 +3823,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_ROLLUP_NOT_SUPPORT); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } @@ -4110,10 +3843,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i else if (select_lex.where) icp = (Item_cond*)(select_lex.where); } - else if (!join && ( ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || - ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || - ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || - ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI ))) + else if (!join && ( ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI ))) { icp = reinterpret_cast(select_lex.where); } @@ -4128,22 +3858,9 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (gwi.thd->infinidb_vtable.override_largeside_estimate || gwi.thd->variables.infinidb_ordered_only) csep->overrideLargeSideEstimate(true); - // @bug 5741. Set a flag when in Local PM only query mode - csep->localQuery(gwi.thd->variables.infinidb_local_query); - // @bug 3321. Set max number of blocks in a dictionary file to be scanned for filtering csep->stringScanThreshold(gwi.thd->variables.infinidb_string_scan_threshold); - csep->stringTableThreshold(gwi.thd->variables.infinidb_stringtable_threshold); - - csep->djsSmallSideLimit(gwi.thd->variables.infinidb_diskjoin_smallsidelimit * 1024ULL * 1024); - csep->djsLargeSideLimit(gwi.thd->variables.infinidb_diskjoin_largesidelimit * 1024ULL * 1024); - csep->djsPartitionSize(gwi.thd->variables.infinidb_diskjoin_bucketsize * 1024ULL * 1024); - if (gwi.thd->variables.infinidb_um_mem_limit == 0) - csep->umMemLimit(numeric_limits::max()); - else - csep->umMemLimit(gwi.thd->variables.infinidb_um_mem_limit * 1024ULL * 1024); - // populate table map and trigger syscolumn cache for all the tables (@bug 1637). // all tables on FROM list must have at least one col in colmap TABLE_LIST* table_ptr = select_lex.get_table_list(); @@ -4166,7 +3883,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { Message::Args args; args.add("View"); - setError(gwi.thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_ENTERPRISE_ONLY, args)), gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, (IDBErrorInfo::instance()->errorMsg(ERR_ENTERPRISE_ONLY, args))); return HA_ERR_UNSUPPORTED; } #endif @@ -4184,15 +3901,14 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i SCSEP plan = fromSub.transform(); if (!plan) { - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, fromSub.gwip().parseErrorText, gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, fromSub.gwip().parseErrorText); CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); return HA_ERR_INTERNAL_ERROR; } gwi.derivedTbList.push_back(plan); gwi.tbList.push_back(tn); - CalpontSystemCatalog::TableAliasName tan = make_aliastable("", alias, alias); - gwi.tableMap[tan] = make_pair(0, table_ptr); + gwi.tableMap[tn] = make_pair(0, table_ptr); gwi.thd->infinidb_vtable.isUnion = true; //by-pass the 2nd pass of rnd_init } #ifndef SKIP_VIEW @@ -4214,27 +3930,20 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (infiniDB) csc->columnRIDs(make_table(table_ptr->db, table_ptr->table_name), true); - string table_name = table_ptr->table_name; - - // @bug5523 - if (table_ptr->db && strcmp(table_ptr->db, "information_schema") == 0) - table_name = (table_ptr->schema_table_name ? table_ptr->schema_table_name : table_ptr->alias); - - CalpontSystemCatalog::TableAliasName tn = make_aliasview(table_ptr->db, table_name, table_ptr->alias, viewName, infiniDB); + CalpontSystemCatalog::TableAliasName tn = make_aliasview(table_ptr->db, table_ptr->table_name, table_ptr->alias, viewName, infiniDB); gwi.tbList.push_back(tn); - CalpontSystemCatalog::TableAliasName tan = make_aliastable(table_ptr->db, table_name, table_ptr->alias, infiniDB); - gwi.tableMap[tan] = make_pair(0,table_ptr); + gwi.tableMap[tn] = make_pair(0,table_ptr); } } if (gwi.fatalParseError) { - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } } catch (IDBExcept& ie) { - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, ie.what(), gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, ie.what()); CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); // @bug 3852. set error status for gwi. gwi.fatalParseError = true; @@ -4247,7 +3956,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // @bug3852 set error status for gwi. gwi.fatalParseError = true; gwi.parseErrorText = emsg; - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, emsg, gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, emsg); CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); return HA_ERR_INTERNAL_ERROR; } @@ -4288,7 +3997,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // gwi for the union unit gp_walk_info union_gwi; union_gwi.thd = gwi.thd; - uint32_t err = 0; + uint err = 0; if ((err = getSelectPlan(union_gwi, *sl, plan, unionSel)) != 0) return err; @@ -4298,7 +4007,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (sl == select_lex.master_unit()->union_distinct) distUnionNum = unionVec.size(); -/*#ifdef DEBUG_WALK_COND +#ifdef DEBUG_WALK_COND IDEBUG( cout << ">>>> UNION DEBUG" << endl ); JOIN* join = sl->join; Item_cond* icp = 0; @@ -4308,8 +4017,8 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i icp->traverse_cond(debug_walk, &gwi, Item::POSTFIX); IDEBUG ( cout << *plan << endl ); IDEBUG ( cout << "<<<unionVec(unionVec); csep->distinctUnionNum(distUnionNum); if (unionVec.empty()) @@ -4317,16 +4026,11 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } gwi.clauseType = WHERE; - if (icp) { -#if MYSQL_VERSION_ID < 50172 //@bug 3039. fix fields for constants if (!icp->fixed) - { icp->fix_fields(gwi.thd, (Item**)&icp); - } -#endif gwi.fatalParseError = false; #ifdef DEBUG_WALK_COND cout << "------------------ WHERE -----------------------" << endl; @@ -4344,10 +4048,9 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (gwi.thd->derived_tables_processing) { gwi.thd->infinidb_vtable.isUnion = false; - gwi.thd->infinidb_vtable.isUpdateWithDerive = true; return -1; } - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } } @@ -4482,7 +4185,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { ScalarSub* scalar = dynamic_cast(gwi.subQuery); if (scalar) - scalar->returnedColPos(gwi.additionalRetCols.size()); + scalar->returnedColPos(gwi.returnedCols.size()); } CalpontSelectExecutionPlan::SelectList selectSubList; @@ -4490,7 +4193,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i while ((item= it++)) { string itemAlias = (item->name? item->name : ""); - // @bug 5916. Need to keep checking until getting concret item in case + // @bug 5916. Need to keep checking until getting concrete item in case // of nested view. while (item->type() == Item::REF_ITEM) { @@ -4506,16 +4209,31 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i Item_field* ifp = (Item_field*)item; SimpleColumn *sc = NULL; - if (ifp->field_name && string(ifp->field_name) == "*") + // FROM clause subquery handling + if (!ifp->field || !ifp->db_name || strlen(ifp->db_name) == 0) { - collectAllCols(gwi, ifp); - break; + // select * from (select ...); + if (string(ifp->field_name) == "*") + { + // collect all the columns from table list + collectAllCols(gwi, ifp); + // @todo selectCols need to be handled for post process? + break; + } + // no table alias prefixed on the selected column + else + { + // @todo find out the which derived table this column is from by matching field name + sc = buildSimpleColFromDerivedTable(gwi, ifp); + } + } + else + { + sc = buildSimpleColumn(ifp, gwi); } - - sc = buildSimpleColumn(ifp, gwi); if (sc) { - boost::shared_ptr spsc(sc); + shared_ptr spsc(sc); if (sel_cols_in_create.length() != 0) sel_cols_in_create += ", "; string fullname; @@ -4551,7 +4269,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } else { - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); delete sc; return HA_ERR_UNSUPPORTED; } @@ -4560,20 +4278,20 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i //aggregate column case Item::SUM_FUNC_ITEM: { - ReturnedColumn *ac = buildAggregateColumn(item, gwi); + AggregateColumn *ac = buildAggregateColumn(item, gwi); if (gwi.fatalParseError) { // e.g., non-support ref column - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); delete ac; return HA_ERR_UNSUPPORTED; } // add this agg col to returnedColumnList - boost::shared_ptr spac(ac); + shared_ptr spac(ac); gwi.returnedCols.push_back(spac); gwi.selectCols.push_back('`' + escapeBackTick(spac->alias().c_str()) + '`'); - String str(256); + String str; item->print(&str, QT_INFINIDB_NO_QUOTE); if (sel_cols_in_create.length() != 0) sel_cols_in_create += ", "; @@ -4589,7 +4307,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_SP_FUNCTION_NOT_SUPPORT); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } @@ -4597,7 +4315,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_FILTER_COND_EXP); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } @@ -4612,30 +4330,27 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_SELECT_SUB); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } ReturnedColumn* rc = buildFunctionColumn(ifp, gwi, hasNonSupportItem); - SRCP srcp(rc); + if (rc) { - if (!hasNonSupportItem && !nonConstFunc(ifp) && !(parseInfo & AF_BIT) && tmpVec.size() == 0) + if (!hasNonSupportItem && !nonConstFunc(ifp) && tmpVec.size() == 0) { if (isUnion || unionSel || gwi.subSelectType != CalpontSelectExecutionPlan::MAIN_SELECT || parseInfo & SUB_BIT || select_lex.group_list.elements != 0) { - srcp.reset(buildReturnedColumn(item, gwi, gwi.fatalParseError)); + SRCP srcp(buildReturnedColumn(item, gwi, gwi.fatalParseError)); gwi.returnedCols.push_back(srcp); if (ifp->name) srcp->alias(ifp->name); continue; } - if ( ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || - ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || - ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || - ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI ) ) + if ( ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI ) ) { } else { @@ -4647,13 +4362,13 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i break; } - //SRCP srcp(rc); + SRCP srcp(rc); gwi.returnedCols.push_back(srcp); if ( ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE ) || ((gwi.thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) || ((gwi.thd->lex)->sql_command == SQLCOM_DELETE_MULTI )) { } else { - String str(256); + String str; ifp->print(&str, QT_INFINIDB_NO_QUOTE); if (sel_cols_in_create.length() != 0) sel_cols_in_create += ", "; @@ -4661,17 +4376,15 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i gwi.selectCols.push_back("`" + escapeBackTick(ifp->name) + "`"); } } - else // InfiniDB Non support functions still go through post process for now + else // InfiniDB Non support functions stil go through post process for now { hasNonSupportItem = false; - uint32_t before_size = funcFieldVec.size(); + uint before_size = funcFieldVec.size(); parse_item(ifp, funcFieldVec, hasNonSupportItem, parseInfo); - uint32_t after_size = funcFieldVec.size(); + uint after_size = funcFieldVec.size(); // group by func and func in subquery can not be post processed // @bug3881. set_user_var can not be treated as constant function - // @bug5716. Try to avoid post process function for union query. - if ((gwi.subQuery || select_lex.group_list.elements != 0 || - !csep->unionVec().empty() || isUnion) && + if ((gwi.subQuery || select_lex.group_list.elements != 0 )&& !hasNonSupportItem && (after_size-before_size) == 0 && !(parseInfo & AGG_BIT) && !(parseInfo & SUB_BIT) && string(ifp->func_name()) != "set_user_var") @@ -4714,14 +4427,14 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i args.add(ifp->func_name()); gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORTED_FUNCTION, args); } - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } else if ( gwi.subQuery && (isPredicateFunction(ifp, &gwi) || ifp->type() == Item::COND_ITEM )) { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_FILTER_COND_EXP); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } @@ -4762,8 +4475,8 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // do not push the dummy column (mysql added) to returnedCol if (item->name && string(item->name) == "Not_used") continue; - - // @bug3509. Constant column is sent to ExeMgr now. + + // @bug3509. Constanct column is sent to ExeMgr now. SRCP srcp(buildReturnedColumn(item, gwi, gwi.fatalParseError)); if (item->name) srcp->alias(item->name); @@ -4794,7 +4507,6 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i String val; String* str = isp->val_str(&val); string name = "'" + string(str->c_ptr()) + "'" + " " + "`" + escapeBackTick(srcp->alias().c_str()) + "`"; - if (sel_cols_in_create.length() != 0) sel_cols_in_create += ", "; sel_cols_in_create += name; @@ -4849,7 +4561,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_SELECT_SUB); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } #ifdef DEBUG_WALK_COND @@ -4870,7 +4582,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { if (gwi.parseErrorText.empty()) gwi.parseErrorText = "Unsupported Item in SELECT subquery."; - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } selectSubList.push_back(ssub); @@ -4902,22 +4614,9 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_FILTER_COND_EXP); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } - case Item::WINDOW_FUNC_ITEM: - { - SRCP srcp(buildWindowFunctionColumn(item, gwi, gwi.fatalParseError)); - if (!srcp || gwi.fatalParseError) - { - if (gwi.parseErrorText.empty()) - gwi.parseErrorText = "Unsupported Item in SELECT subquery."; - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); - return HA_ERR_UNSUPPORTED; - } - gwi.returnedCols.push_back(srcp); - break; - } default: { break; @@ -4928,18 +4627,13 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // @bug4388 normalize the project coltypes for union main select list if (!csep->unionVec().empty()) { - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { vector coltypes; - for (uint32_t j = 0; j < csep->unionVec().size(); j++) + for (uint j = 0; j < csep->unionVec().size(); j++) { coltypes.push_back( dynamic_cast(csep->unionVec()[j].get())->returnedCols()[i]->resultType()); - - // @bug5976. set hasAggregate true for the main column if - // one corresponding union column has aggregate - if (dynamic_cast(csep->unionVec()[j].get())->returnedCols()[i]->hasAggregate()) - gwi.returnedCols[i]->hasAggregate(true); } gwi.returnedCols[i]->resultType(dataconvert::DataConvert::convertUnionColType(coltypes)); } @@ -4964,7 +4658,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i having->traverse_cond(gp_walk, &gwi, Item::POSTFIX); if (gwi.fatalParseError) { - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } @@ -5005,7 +4699,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } } - for (uint32_t i = 0; i < funcFieldVec.size(); i++) + for (uint i = 0; i < funcFieldVec.size(); i++) { //SimpleColumn *sc = new SimpleColumn(funcFieldVec[i]->db_name, bestTableName(funcFieldVec[i])/*funcFieldVec[i]->table_name*/, funcFieldVec[i]->field_name, sessionID); SimpleColumn *sc = buildSimpleColumn(funcFieldVec[i], gwi); @@ -5022,7 +4716,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { emsg = gwi.parseErrorText; } - setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } String str; @@ -5031,7 +4725,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i //sc->tableAlias(funcFieldVec[i]->table_name); sc->tableAlias(sc->tableAlias()); SRCP srcp(sc); - uint32_t j = 0; + uint j = 0; for (; j < gwi.returnedCols.size(); j++) { if (sc->sameColumn(gwi.returnedCols[j].get())) @@ -5067,40 +4761,15 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i gwi.clauseType = GROUP_BY; Item* nonSupportItem = NULL; ORDER* groupcol = reinterpret_cast(select_lex.group_list.first); - - // check if window functions are in order by. InfiniDB process order by list if - // window functions are involved, either in order by or projection. - bool hasWindowFunc = gwi.hasWindowFunc; - gwi.hasWindowFunc = false; - for (; groupcol; groupcol= groupcol->next) - { - if ((*(groupcol->item))->type() == Item::WINDOW_FUNC_ITEM) - gwi.hasWindowFunc = true; - } - if (gwi.hasWindowFunc) - { - gwi.fatalParseError = true; - gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_WF_NOT_ALLOWED, "GROUP BY clause"); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); - return HA_ERR_UNSUPPORTED; - } - gwi.hasWindowFunc = hasWindowFunc; - - groupcol = reinterpret_cast(select_lex.group_list.first); - for (; groupcol; groupcol= groupcol->next) { Item* groupItem = *(groupcol->item); - // @bug5993. Could be nested ref. - while (groupItem->type() == Item::REF_ITEM) + if (groupItem->type() == Item::REF_ITEM) groupItem = (*((Item_ref*)groupItem)->ref); if (groupItem->type() == Item::FUNC_ITEM) { Item_func* ifp = (Item_func*)groupItem; - - // call buildFunctionColumn here mostly for finding out - // non-support column on GB list. Should be simplified. ReturnedColumn *fc = buildFunctionColumn(ifp, gwi, gwi.fatalParseError); if (!fc || gwi.fatalParseError) { @@ -5109,11 +4778,10 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } if (groupcol->in_field_list && groupcol->counter_used) { - delete fc; fc = gwi.returnedCols[groupcol->counter-1].get(); - SRCP srcp(fc->clone()); + SRCP srcp(gwi.returnedCols[groupcol->counter-1]->clone()); // check if no column parm - for (uint32_t i = 0; i < gwi.no_parm_func_list.size(); i++) + for (uint i = 0; i < gwi.no_parm_func_list.size(); i++) { if (gwi.no_parm_func_list[i]->expressionId() == fc->expressionId()) { @@ -5128,7 +4796,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } else if (!groupItem->is_autogenerated_name) // alias { - uint32_t i = 0; + uint i = 0; for (; i < gwi.returnedCols.size(); i++) { if (string(groupItem->name) == gwi.returnedCols[i]->alias()) @@ -5136,7 +4804,6 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i ReturnedColumn *rc = gwi.returnedCols[i]->clone(); rc->orderPos(i); gwi.groupByCols.push_back(SRCP(rc)); - delete fc; break; } } @@ -5148,7 +4815,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } else { - uint32_t i = 0; + uint i = 0; for (; i < gwi.returnedCols.size(); i++) { if (fc->operator==(gwi.returnedCols[i].get())) @@ -5156,7 +4823,6 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i ReturnedColumn *rc = gwi.returnedCols[i]->clone(); rc->orderPos(i); gwi.groupByCols.push_back(SRCP(rc)); - delete fc; break; } } @@ -5174,7 +4840,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i ReturnedColumn *rc = buildSimpleColumn(ifp, gwi); SimpleColumn* sc = dynamic_cast(rc); - for (uint32_t j = 0; j < gwi.returnedCols.size(); j++) + for (uint j = 0; j < gwi.returnedCols.size(); j++) { if (sc) { @@ -5217,7 +4883,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i gwi.groupByCols.push_back(srcp); gwi.columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(string(ifp->field_name), srcp)); } - // @bug5638. The group by column is constant but not counter, alias has to match a column + // @bug5638. The group by column is constant but not couter, alias has to match a column // on the select list else if (!groupcol->counter_used && (groupItem->type() == Item::INT_ITEM || @@ -5226,7 +4892,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i groupItem->type() == Item::DECIMAL_ITEM)) { ReturnedColumn* rc = 0; - for (uint32_t j = 0; j < gwi.returnedCols.size(); j++) + for (uint j = 0; j < gwi.returnedCols.size(); j++) { if (groupItem->name && string(groupItem->name) == gwi.returnedCols[j].get()->alias()) { @@ -5250,7 +4916,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } else { - uint32_t i = 0; + uint i = 0; for (; i < gwi.returnedCols.size(); i++) { if (string(groupItem->name) == gwi.returnedCols[i]->alias()) @@ -5270,7 +4936,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // @bug 3761. else if (groupcol->counter_used) { - if (gwi.returnedCols.size() <= (uint32_t)(groupcol->counter-1)) + if (gwi.returnedCols.size() <= (uint)(groupcol->counter-1)) { nonSupportItem = groupItem; } @@ -5289,21 +4955,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // @bug 4756. Add internal groupby column for correlated join to the groupby list if (gwi.aggOnSelect && !gwi.subGroupByCols.empty()) gwi.groupByCols.insert(gwi.groupByCols.end(), gwi.subGroupByCols.begin(), gwi.subGroupByCols.end()); - - // this is window func on SELECT becuase ORDER BY has not been processed - if (!gwi.windowFuncList.empty() && !gwi.subGroupByCols.empty()) - { - for (uint32_t i = 0; i < gwi.windowFuncList.size(); i++) - { - if (gwi.windowFuncList[i]->hasWindowFunc()) - { - vector windowFunctions = gwi.windowFuncList[i]->windowfunctionColumnList(); - for (uint32_t j = 0; j < windowFunctions.size(); j++) - windowFunctions[j]->addToPartition(gwi.subGroupByCols); - } - } - } - + if (nonSupportItem) { Message::Args args; @@ -5312,7 +4964,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i else args.add(""); gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_GROUP_BY, args); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } } @@ -5328,21 +4980,9 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i algorithm::to_lower(lower_create_query); algorithm::to_lower(lower_select_query); - - // check if window functions are in order by. InfiniDB process order by list if - // window functions are involved, either in order by or projection. - for (; ordercol; ordercol= ordercol->next) - { - if ((*(ordercol->item))->type() == Item::WINDOW_FUNC_ITEM) - gwi.hasWindowFunc = true; - } - - // re-visit the first of ordercol list - ordercol = reinterpret_cast(order_list.first); - // for subquery, order+limit by will be supported in infinidb. build order by columns // @todo union order by and limit support - if (gwi.hasWindowFunc || gwi.subSelectType != CalpontSelectExecutionPlan::MAIN_SELECT) + if (/*isUnion ||*/ gwi.subSelectType != CalpontSelectExecutionPlan::MAIN_SELECT) { for (; ordercol; ordercol= ordercol->next) { @@ -5351,39 +4991,21 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { rc = gwi.returnedCols[ordercol->counter-1]->clone(); rc->orderPos(ordercol->counter-1); - // can not be optimized off if used in order by with counter. - // set with self derived table alias if it's derived table - gwi.returnedCols[ordercol->counter-1]->incRefCount(); } else { Item* ord_item = *(ordercol->item); - // ignore not_used column on order by. - if (ord_item->type() == Item::INT_ITEM && ord_item->name && string(ord_item->name) == "Not_used") - continue; - else if (ord_item->type() == Item::INT_ITEM) + if (ord_item->type() == Item::INT_ITEM) rc = gwi.returnedCols[((Item_int*)ord_item)->val_int()-1]->clone(); else if (ord_item->type() == Item::SUBSELECT_ITEM) gwi.fatalParseError = true; else rc = buildReturnedColumn(ord_item, gwi, gwi.fatalParseError); - - // @bug5501 try item_ptr if item can not be fixed. For some - // weird dml statement state, item can not be fixed but the - // infomation is available in item_ptr. if (!rc || gwi.fatalParseError) - { - Item* item_ptr = ordercol->item_ptr; - while (item_ptr->type() == Item::REF_ITEM) - item_ptr = *(((Item_ref*)item_ptr)->ref); - rc = buildReturnedColumn(item_ptr, gwi, gwi.fatalParseError); - } - - if (!rc) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY); gwi.parseErrorText = emsg; - setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } } @@ -5405,8 +5027,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i for (; ordercol; ordercol= ordercol->next) { Item* ord_item = *(ordercol->item); - // @bug5993. Could be nested ref. - while (ord_item->type() == Item::REF_ITEM) + if (ord_item->type() == Item::REF_ITEM) ord_item = (*((Item_ref*)ord_item)->ref); // @bug 1706. re-construct the order by item one by one //Item* ord_item = *(ordercol->item); @@ -5441,7 +5062,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i rc = buildFunctionColumn(ifp, gwi, gwi.fatalParseError); if (rc) { - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { if (rc && rc->operator==(gwi.returnedCols[i].get())) { @@ -5461,11 +5082,11 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i addToSel = false; redo = true; string ord_func = string(ifp->func_name()) + "("; - for (uint32_t i = 0; i < fc->functionParms().size(); i++) + for (uint i = 0; i < fc->functionParms().size(); i++) { if (i != 0) ord_func += ","; - for (uint32_t j = 0; j < gwi.returnedCols.size(); j++) + for (uint j = 0; j < gwi.returnedCols.size(); j++) { if (fc->functionParms()[i]->data()->operator==(gwi.returnedCols[j].get())) { @@ -5477,7 +5098,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (ac) { gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } addToSel = true; @@ -5494,7 +5115,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i else if (ord_item->type() == Item::SUBSELECT_ITEM) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY); - setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } @@ -5508,11 +5129,11 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (!ac) { setError(gwi.thd, HA_ERR_UNSUPPORTED, - IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY), gwi); + IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY)); return HA_ERR_UNSUPPORTED; } // check if this order by column is on the select list - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { AggregateColumn *ret = dynamic_cast(gwi.returnedCols[i].get()); if (!ret) @@ -5561,7 +5182,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (field->field_name) fullname += string(field->field_name); - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { SimpleColumn* sc = dynamic_cast(gwi.returnedCols[i].get()); if (sc && ((Item_field*)ord_item)->cached_table && @@ -5590,7 +5211,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (select_lex.options & SELECT_DISTINCT) { gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_ORDERBY_NOT_IN_DISTINCT); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } bool hasNonSupportItem = false; @@ -5599,7 +5220,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (hasNonSupportItem) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY); - setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } String str; @@ -5613,20 +5234,20 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // populate string to be added to the select list for order by redo = (redo || fieldVec.size() != 0); - for (uint32_t i = 0; i < fieldVec.size(); i++) + for (uint i = 0; i < fieldVec.size(); i++) { SimpleColumn* sc = buildSimpleColumn(fieldVec[i], gwi); if (!sc) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY); - setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } String str; fieldVec[i]->print(&str, QT_INFINIDB_NO_QUOTE); sc->alias(string(str.c_ptr())); SRCP srcp(sc); - uint32_t j = 0; + uint j = 0; for (; j < gwi.returnedCols.size(); j++) { if (sc->sameColumn(gwi.returnedCols[j].get())) @@ -5670,20 +5291,19 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } catch (runtime_error& e) { - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, e.what(), gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, e.what()); CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); return HA_ERR_INTERNAL_ERROR; } catch (...) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_LOST_CONN_EXEMGR); - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, emsg, gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, emsg); CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); return HA_ERR_INTERNAL_ERROR; } - if (!gwi.count_asterisk_list.empty() || !gwi.no_parm_func_list.empty() || - gwi.returnedCols.empty()) + if (!gwi.count_asterisk_list.empty() || !gwi.no_parm_func_list.empty() || gwi.returnedCols.empty()) { // get the smallest column from colmap CalpontSelectExecutionPlan::ColumnMap::const_iterator iter; @@ -5713,16 +5333,16 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } catch (...) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_LOST_CONN_EXEMGR); - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, emsg, gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, emsg); CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); return HA_ERR_INTERNAL_ERROR; } - if (gwi.returnedCols.empty() && gwi.additionalRetCols.empty()) + if (gwi.returnedCols.empty()) gwi.returnedCols.push_back(minSc); } - if (!isUnion && !gwi.hasWindowFunc && gwi.subSelectType == CalpontSelectExecutionPlan::MAIN_SELECT) + if (!isUnion && gwi.subSelectType == CalpontSelectExecutionPlan::MAIN_SELECT) { std::ostringstream vtb; vtb << "infinidb_vtable.$vtable_" << gwi.thd->thread_id; @@ -5760,7 +5380,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (aliasSet.find(table_ptr->alias) != aliasSet.end()) continue; String str; - (table_ptr->derived->first_select())->print(gwi.thd, &str, QT_INFINIDB_DERIVED); + (table_ptr->derived->first_select())->print(gwi.thd, &str, QT_INFINIDB_NO_QUOTE); if (!firstTb) create_query += ", "; create_query += "(" + string(str.c_ptr()) +") " + string(table_ptr->alias); @@ -5813,7 +5433,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i gwi.thd->infinidb_vtable.create_vtable_query.free(); gwi.thd->infinidb_vtable.create_vtable_query.append(create_query.c_str(), create_query.length()); - gwi.thd->infinidb_vtable.vtable_state = THD::INFINIDB_REDO_PHASE1; // redo phase 1 + gwi.thd->infinidb_vtable.vtable_state = THD::INFINIDB_REDO_PHASE1; // redo phase 1 // turn off select distinct from post process unless there're post process functions // on the select list. @@ -5826,7 +5446,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // select * from derived table... if (gwi.selectCols.size() == 0) sel_query += " * "; - for (uint32_t i = 0; i < gwi.selectCols.size(); i++) + for (uint i = 0; i < gwi.selectCols.size(); i++) { sel_query += gwi.selectCols[i]; if ( i+1 != gwi.selectCols.size()) @@ -5863,7 +5483,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { Item_sum* ifp = (Item_sum*)(*(ordercol->item)); ReturnedColumn *fc = buildAggregateColumn(ifp, gwi); - for (uint32_t i = 0; i < gwi.returnedCols.size(); i++) + for (uint i = 0; i < gwi.returnedCols.size(); i++) { if (fc->operator==(gwi.returnedCols[i].get())) { @@ -5917,7 +5537,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i else if (ord_item->type() == Item::SUBSELECT_ITEM) { string emsg = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_ORDER_BY); - setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg, gwi); + setError(gwi.thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } else @@ -5962,7 +5582,11 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // check limit clause if (gwi.thd->variables.select_limit != (uint64_t)-1) + { gwi.thd->infinidb_vtable.has_limit = true; + csep->limitStart(0); + csep->limitNum(gwi.thd->variables.select_limit); + } if (unionSel || gwi.subSelectType != CalpontSelectExecutionPlan::MAIN_SELECT) { @@ -6001,33 +5625,11 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i } else if (select_lex.explicit_limit) { - uint32_t limitOffset = 0; - uint32_t limitNum = std::numeric_limits::max(); + uint limitOffset = 0, limitNum = -1; if (join) { -#if MYSQL_VERSION_ID >= 50172 - // @bug5729. After upgrade, join->unit sometimes is uninitialized pointer - // (not null though) and will cause seg fault. Prefer checking - // select_lex->offset_limit if not null. - if (join->select_lex && - join->select_lex->offset_limit && - join->select_lex->offset_limit->fixed && - join->select_lex->select_limit && - join->select_lex->select_limit->fixed) - { - limitOffset = join->select_lex->offset_limit->val_int(); - limitNum = join->select_lex->select_limit->val_int(); - } - - else if (join->unit) - { - limitOffset = join->unit->offset_limit_cnt; - limitNum = join->unit->select_limit_cnt - limitOffset; - } -#else limitOffset = (join->unit)->offset_limit_cnt; limitNum = (join->unit)->select_limit_cnt - (join->unit)->offset_limit_cnt; -#endif } else { @@ -6042,24 +5644,12 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i limitNum = select->val_int(); } } - - // relate to bug4848. let mysql drive limit when limit session variable set. - // do not set in csep. @bug5096. ignore session limit setting for dml - if ((gwi.thd->variables.select_limit == (uint64_t)-1 || - (gwi.thd->variables.select_limit != (uint64_t)-1 && - gwi.thd->infinidb_vtable.vtable_state != THD::INFINIDB_CREATE_VTABLE))&& - !csep->hasOrderBy()) - { - csep->limitStart(limitOffset); - csep->limitNum(limitNum); - } - else - { - ostringstream limit; - limit << " limit " << limitOffset << ", " << limitNum; - select_query += limit.str(); - gwi.thd->infinidb_vtable.has_limit = true; - } + csep->limitStart(limitOffset); + csep->limitNum(limitNum); + ostringstream limit; + limit << " limit " << limitOffset << ", " << limitNum; + select_query += limit.str(); + gwi.thd->infinidb_vtable.has_limit = true; } gwi.thd->infinidb_vtable.select_vtable_query.free(); @@ -6071,7 +5661,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { gwi.fatalParseError = true; gwi.parseErrorText = IDBErrorInfo::instance()->errorMsg(ERR_NON_SUPPORT_LIMIT_SUB); - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, gwi.parseErrorText, gwi); + setError(gwi.thd, HA_ERR_INTERNAL_ERROR, gwi.parseErrorText); return HA_ERR_UNSUPPORTED; } } @@ -6083,12 +5673,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i // select constant in subquery case std::vector::iterator coliter; if (!minSc) - { - if (!gwi.returnedCols.empty()) - minSc = gwi.returnedCols[0]; - else if (!gwi.additionalRetCols.empty()) - minSc = gwi.additionalRetCols[0]; - } + minSc = gwi.returnedCols[0]; // @bug3523, count(*) on subquery always pick column[0]. SimpleColumn* sc = dynamic_cast(minSc.get()); @@ -6097,7 +5682,7 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i if (gwi.derivedTbList.size() >= 1) { SimpleColumn* sc1 = new SimpleColumn(); - sc1->columnName(sc->columnName()); + sc1->tableName(sc->tableName()); sc1->tableAlias(sc->tableAlias()); sc1->viewName(lower(sc->viewName())); @@ -6108,15 +5693,6 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i for (coliter = gwi.count_asterisk_list.begin(); coliter != gwi.count_asterisk_list.end(); ++coliter) { - // @bug5977 @note should never throw this, but checking just in case. - // When ExeMgr fix is ready, this should not error out... - if (dynamic_cast(minSc.get())) - { - gwi.fatalParseError = true; - gwi.parseErrorText = "No project column found for aggregate function"; - setError(gwi.thd, HA_ERR_INTERNAL_ERROR, gwi.parseErrorText, gwi); - return HA_ERR_UNSUPPORTED; - } (*coliter)->functionParms(minSc); } @@ -6127,17 +5703,9 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i { FunctionParm funcParms = (*funciter)->functionParms(); funcParms.push_back(sptp); - (*funciter)->functionParms(funcParms); + (*funciter)->funcParms(funcParms); } - // set sequence# for subquery localCols - for (uint32_t i = 0; i < gwi.localCols.size(); i++) - gwi.localCols[i]->sequence(i); - - // append additionalRetCols to returnedCols - gwi.returnedCols.insert(gwi.returnedCols.begin(), gwi.additionalRetCols.begin(), - gwi.additionalRetCols.end()); - csep->groupByCols(gwi.groupByCols); csep->orderByCols(gwi.orderByCols); csep->returnedCols(gwi.returnedCols); @@ -6145,9 +5713,8 @@ int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, SCSEP& csep, bool i csep->having(havingFilter); csep->derivedTableList(gwi.derivedTbList); csep->selectSubList(selectSubList); - csep->subSelectList(gwi.subselectList); + gwi.thd->infinidb_vtable.duplicate_field_name = false; - clearStacks(gwi); return 0; } @@ -6160,13 +5727,13 @@ int cp_get_plan(THD* thd, SCSEP& csep) gp_walk_info gwi; gwi.thd = thd; int status = getSelectPlan(gwi, select_lex, csep); + //if (getSelectPlan(gwi, select_lex, csep) > 0) if (status > 0) return HA_ERR_INTERNAL_ERROR; else if (status < 0) return status; - - // Derived table projection and filter optimization. - derivedTableOptimization(csep); + //cout << thd->infinidb_vtable.create_vtable_query.c_ptr() << endl; + //cout << thd->infinidb_vtable.select_vtable_query.c_ptr() << endl; return 0; } @@ -6197,7 +5764,7 @@ int cp_get_table_plan(THD* thd, SCSEP& csep, cal_table_info& ti) string alias(table->alias); sc->tableAlias(lower(alias)); assert (sc); - boost::shared_ptr spsc(sc); + shared_ptr spsc(sc); gwi->returnedCols.push_back(spsc); gwi->columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(string(field->field_name), spsc)); } diff --git a/dbcon/mysql/ha_calpont_impl.cpp b/dbcon/mysql/ha_calpont_impl.cpp index e4f9217c..ab3b0c4c 100644 --- a/dbcon/mysql/ha_calpont_impl.cpp +++ b/dbcon/mysql/ha_calpont_impl.cpp @@ -16,19 +16,15 @@ MA 02110-1301, USA. */ /* - * $Id: ha_calpont_impl.cpp 9642 2013-06-24 14:57:42Z rdempsey $ + * $Id: ha_calpont_impl.cpp 9355 2013-04-01 21:34:40Z zzhu $ */ -#ifndef _MSC_VER -#include -#endif #include #include #include #ifdef _MSC_VER #include #include -#include #else #include #include @@ -43,15 +39,6 @@ #include #include #include -#if defined(__linux__) -#include //wait() -#elif defined(__FreeBSD__) -#include -#include // For stat(). -#include -#include -#include -#endif using namespace std; #include @@ -137,7 +124,6 @@ using namespace logging; #include "functor.h" using namespace funcexp; -#include "installdir.h" #include "versionnumber.h" namespace cal_impl_if @@ -147,15 +133,15 @@ namespace cal_impl_if namespace { -// Calpont vtable non-support error message +// Calpont vtable non-support error message const string infinidb_autoswitch_warning = "The query includes syntax that is not supported by InfiniDB distributed mode. The execution was switched to standard mode with downgraded performance."; // copied from item_timefunc.cc static const string interval_names[]= { - "year", "quarter", "month", "week", "day", + "year", "quarter", "month", "week", "day", "hour", "minute", "second", "microsecond", - "year_month", "day_hour", "day_minute", + "year_month", "day_hour", "day_minute", "day_second", "hour_minute", "hour_second", "minute_second", "day_microsecond", "hour_microsecond", "minute_microsecond", @@ -166,8 +152,7 @@ const unsigned NONSUPPORTED_ERR_THRESH = 2000; //TODO: make this session-safe (put in connMap?) vector rmParms; -ResourceManager rm; -bool useHdfs = rm.useHdfs(); + //convenience fcn inline uint32_t tid2sid(const uint32_t tid) { @@ -178,10 +163,7 @@ void storeNumericField(Field** f, int64_t value, CalpontSystemCatalog::ColType& { // unset null bit first if ((*f)->null_ptr) - *(*f)->null_ptr &= ~(*f)->null_bit; - // For unsigned, use the ColType returned in the row rather than the - // unsigned_flag set by mysql. This is because mysql gets it wrong for SUM() - // Hopefully, in all other cases we get it right. + *(*f)->null_ptr &= ~(*f)->null_bit; switch ((*f)->type()) { case MYSQL_TYPE_NEWDECIMAL: @@ -192,7 +174,7 @@ void storeNumericField(Field** f, int64_t value, CalpontSystemCatalog::ColType& if (f2->dec < ct.scale) f2->dec = ct.scale; char buf[256]; - dataconvert::DataConvert::decimalToString(value, (unsigned)ct.scale, buf, 256, ct.colDataType); + dataconvert::DataConvert::decimalToString( value, (unsigned)ct.scale, buf, 256 ); f2->store(buf, strlen(buf), f2->charset()); break; } @@ -238,25 +220,14 @@ void storeNumericField(Field** f, int64_t value, CalpontSystemCatalog::ColType& f2->store(double_val); break; } - case MYSQL_TYPE_VARCHAR: - { - Field_varstring* f2 = (Field_varstring*)*f; - char tmp[25]; - if (ct.colDataType == CalpontSystemCatalog::DECIMAL) - dataconvert::DataConvert::decimalToString(value, (unsigned)ct.scale, tmp, 25, ct.colDataType); - else - snprintf(tmp, 25, "%ld", value); - f2->store(tmp, strlen(tmp), f2->charset()); - break; - } default: { Field_longlong* f2 = (Field_longlong*)*f; longlong int_val = (longlong)value; - f2->store(int_val, f2->unsigned_flag); + f2->store(int_val, f2->unsigned_flag); break; } - } + } } // @@ -270,14 +241,14 @@ void tpl_scan_fetch_LogException( cal_table_info& ti, cal_connection_info* ci, s ctime_r(&t, datestr); datestr[ strlen(datestr)-1 ] = '\0'; // strip off trailing newline - uint32_t sesID = 0; + u_int32_t sesID = 0; string connHndl("No connection handle to use"); - + if (ti.conn_hndl) { connHndl = "ti connection used"; sesID = ti.conn_hndl->sessionID; } - + else if (ci->cal_conn_hndl) { connHndl = "ci connection used"; sesID = ci->cal_conn_hndl->sessionID; @@ -312,29 +283,32 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) { int rc = HA_ERR_END_OF_FILE; int num_attr = ti.msTablePtr->s->fields; + boost::shared_ptr csc; sm::status_t sm_stat; try { if (ti.conn_hndl) { - sm_stat = sm::tpl_scan_fetch(ti.tpl_scan_ctx, ti.conn_hndl); + sm_stat = sm::tpl_scan_fetch(ti.tpl_scan_ctx, NULL, 0, ti.conn_hndl); + csc = ti.conn_hndl->csc; } else if (ci->cal_conn_hndl) { - sm_stat = sm::tpl_scan_fetch(ti.tpl_scan_ctx, ci->cal_conn_hndl, (int*)(¤t_thd->killed)); + sm_stat = sm::tpl_scan_fetch(ti.tpl_scan_ctx, NULL, 0, ci->cal_conn_hndl, (int*)(¤t_thd->killed)); + csc = ci->cal_conn_hndl->csc; } else throw runtime_error("internal error"); } catch (std::exception& ex) { // @bug 2244. Always log this msg for now, as we try to track down when/why we are -// losing socket connection with ExeMgr +// losing socket connection with ExeMgr //#ifdef INFINIDB_DEBUG tpl_scan_fetch_LogException( ti, ci, &ex); //#endif sm_stat = sm::CALPONT_INTERNAL_ERROR; } catch (...) { // @bug 2244. Always log this msg for now, as we try to track down when/why we are -// losing socket connection with ExeMgr +// losing socket connection with ExeMgr //#ifdef INFINIDB_DEBUG tpl_scan_fetch_LogException( ti, ci, 0 ); //#endif @@ -349,18 +323,17 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) memset(buf, -1, ti.msTablePtr->s->null_bytes); std::vector &colTypes = ti.tpl_scan_ctx->ctp; int64_t intColVal = 0; - uint64_t uintColVal = 0; - string stringColVal; + string stringColVal; char tmp[256]; - + RowGroup *rowGroup = ti.tpl_scan_ctx->rowGroup; // table mode mysql expects all columns of the table. mapping between columnoid and position in rowgroup // set coltype.position to be the position in rowgroup. only set once. - if (ti.tpl_scan_ctx->rowsreturned == 0 && + if (ti.tpl_scan_ctx->rowsreturned == 0 && (ti.tpl_scan_ctx->traceFlags & execplan::CalpontSelectExecutionPlan::TRACE_TUPLE_OFF)) { - for (uint32_t i = 0; i < rowGroup->getColumnCount(); i++) + for (uint i = 0; i < rowGroup->getColumnCount(); i++) { int oid = rowGroup->getOIDs()[i]; int j = 0; @@ -384,7 +357,7 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) { //This col is going to be written bitmap_set_bit(ti.msTablePtr->write_set, (*f)->field_index); - + // get coltype if not there yet if (colTypes[0].colWidth == 0) { @@ -399,7 +372,7 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) } } CalpontSystemCatalog::ColType colType(colTypes[p]); - + // table mode handling if (ti.tpl_scan_ctx->traceFlags & execplan::CalpontSelectExecutionPlan::TRACE_TUPLE_OFF) { @@ -416,7 +389,7 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) // precision == -16 is borrowed as skip null check indicator for bit ops. if (row.isNullValue(s) && colType.precision != -16) { - // @2835. Handle empty string and null confusion. store empty string for string column + // @2835. Handle empty string and null confusion. store empty string for string column if (colType.colDataType == CalpontSystemCatalog::CHAR || colType.colDataType == CalpontSystemCatalog::VARCHAR || colType.colDataType == CalpontSystemCatalog::VARBINARY) @@ -426,7 +399,7 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) } continue; } - + // fetch and store data switch (colType.colDataType) { @@ -458,22 +431,22 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) { case 1: intColVal = row.getUintField<1>(s); - f2->store((char*)(&intColVal), strlen((char*)(&intColVal)), f2->charset()); + f2->store((char*)(&intColVal), strlen((char*)(&intColVal)), f2->charset()); break; case 2: intColVal = row.getUintField<2>(s); - f2->store((char*)(&intColVal), strlen((char*)(&intColVal)), f2->charset()); + f2->store((char*)(&intColVal), strlen((char*)(&intColVal)), f2->charset()); break; case 4: intColVal = row.getUintField<4>(s); - f2->store((char*)(&intColVal), strlen((char*)(&intColVal)), f2->charset()); + f2->store((char*)(&intColVal), strlen((char*)(&intColVal)), f2->charset()); break; case 8: //make sure we don't send strlen off into the weeds... intColVal = row.getUintField<8>(s); memcpy(tmp, &intColVal, 8); tmp[8] = 0; - f2->store(tmp, strlen(tmp), f2->charset()); + f2->store(tmp, strlen(tmp), f2->charset()); break; default: stringColVal = row.getStringField(s); @@ -489,9 +462,9 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) if (current_thd->variables.infinidb_varbin_always_hex) { - uint32_t l; + uint l; const uint8_t* p = row.getVarBinaryField(l, s); - uint32_t ll = l * 2; + uint ll = l * 2; boost::scoped_array sca(new char[ll]); vbin2hex(p, l, sca.get()); f2->store(sca.get(), ll, f2->charset()); @@ -509,57 +482,32 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) storeNumericField(f, intColVal, colType); break; } - case CalpontSystemCatalog::UBIGINT: - { - uintColVal = row.getUintField<8>(s); - storeNumericField(f, uintColVal, colType); - break; - } case CalpontSystemCatalog::INT: { intColVal = row.getIntField<4>(s); storeNumericField(f, intColVal, colType); break; } - case CalpontSystemCatalog::UINT: - { - uintColVal = row.getUintField<4>(s); - storeNumericField(f, uintColVal, colType); - break; - } case CalpontSystemCatalog::SMALLINT: { intColVal = row.getIntField<2>(s); storeNumericField(f, intColVal, colType); break; } - case CalpontSystemCatalog::USMALLINT: - { - uintColVal = row.getUintField<2>(s); - storeNumericField(f, uintColVal, colType); - break; - } case CalpontSystemCatalog::TINYINT: { intColVal = row.getIntField<1>(s); storeNumericField(f, intColVal, colType); break; } - case CalpontSystemCatalog::UTINYINT: - { - uintColVal = row.getUintField<1>(s); - storeNumericField(f, uintColVal, colType); - break; - } //In this case, we're trying to load a double output column with float data. This is the // case when you do sum(floatcol), e.g. case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: { float dl = row.getFloatField(s); if (dl == std::numeric_limits::infinity()) continue; - + //int64_t* icvp = (int64_t*)&dl; //intColVal = *icvp; Field_float* f2 = (Field_float*)*f; @@ -571,14 +519,13 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) //f2->store(float_val); f2->store(dl); if ((*f)->null_ptr) - *(*f)->null_ptr &= ~(*f)->null_bit; + *(*f)->null_ptr &= ~(*f)->null_bit; break; - + //storeNumericField(f, intColVal, colType); //break; } case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: { double dl = row.getDoubleField(s); if (dl == std::numeric_limits::infinity()) @@ -586,15 +533,15 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) Field_double* f2 = (Field_double*)*f; // bug 3483, reserve enough space for the longest double value // -1.7976931348623157E+308 to -2.2250738585072014E-308, 0, and - // 2.2250738585072014E-308 to 1.7976931348623157E+308. + // 2.2250738585072014E-308 to 1.7976931348623157E+308. (*f)->field_length = 310; //double double_val = *(double*)(&value); //f2->store(double_val); f2->store(dl); if ((*f)->null_ptr) - *(*f)->null_ptr &= ~(*f)->null_bit; + *(*f)->null_ptr &= ~(*f)->null_bit; break; - + //int64_t* icvp = (int64_t*)&dl; //intColVal = *icvp; @@ -602,7 +549,6 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) //break; } case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { intColVal = row.getIntField(s); storeNumericField(f, intColVal, colType); @@ -616,7 +562,9 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) } } } + + ti.tpl_scan_ctx->rowsreturned++; ti.c++; #ifdef INFINIDB_DEBUG @@ -624,8 +572,8 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) cerr << "fetchNextRow so far table " << ti.msTablePtr->s->table_name.str << " rows = " << ti.c << endl; #endif ti.moreRows = true; - rc = 0; - } + rc = 0; + } else if (sm_stat == sm::SQL_NOT_FOUND) { IDEBUG( cerr << "fetchNextRow done for table " << ti.msTablePtr->s->table_name.str << " rows = " << ti.c << endl ); @@ -639,12 +587,14 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) rc = HA_ERR_INTERNAL_ERROR; ci->rc = rc; } - else if ((uint32_t)sm_stat == logging::ERR_LOST_CONN_EXEMGR) + else if ((uint)sm_stat == logging::ERR_LOST_CONN_EXEMGR) { ti.moreRows = false; rc = logging::ERR_LOST_CONN_EXEMGR; - sm::sm_init(tid2sid(current_thd->thread_id), &ci->cal_conn_hndl, - current_thd->variables.infinidb_local_query); + char sessionIDstr[80]; + snprintf(sessionIDstr, 80, "%u", tid2sid(current_thd->thread_id)); + sessionIDstr[79] = 0; + sm::sm_init(0, 0, 0, sessionIDstr, (void**)&ci->cal_conn_hndl); idbassert(ci->cal_conn_hndl != 0); ci->rc = rc; } @@ -658,14 +608,14 @@ int fetchNextRow(uchar *buf, cal_table_info& ti, cal_connection_info* ci) current_thd->infinidb_vtable.has_limit = true; ci->rc = rc; } - else + else { ti.moreRows = false; rc = sm_stat; ci->rc = rc; } - return rc; + return rc; } void makeUpdateScalarJoin(const ParseTree* n, void* obj) @@ -674,13 +624,13 @@ void makeUpdateScalarJoin(const ParseTree* n, void* obj) SimpleFilter *sf = dynamic_cast(tn); if (!sf) return; - + SimpleColumn *scLeft = dynamic_cast(sf->lhs()); SimpleColumn *scRight = dynamic_cast(sf->rhs()); CalpontSystemCatalog::TableAliasName* updatedTables = reinterpret_cast(obj); if ( scLeft && scRight ) { - if ( (strcasecmp(scLeft->tableName().c_str(), updatedTables->table.c_str()) == 0 ) && (strcasecmp(scLeft->schemaName().c_str(), updatedTables->schema.c_str()) == 0) + if ( (strcasecmp(scLeft->tableName().c_str(), updatedTables->table.c_str()) == 0 ) && (strcasecmp(scLeft->schemaName().c_str(), updatedTables->schema.c_str()) == 0) && (strcasecmp(scLeft->tableAlias().c_str(),updatedTables->alias.c_str()) == 0)) { uint64_t lJoinInfo = sf->lhs()->joinInfo(); @@ -701,7 +651,7 @@ void makeUpdateScalarJoin(const ParseTree* n, void* obj) else return; } - else + else return; } @@ -711,14 +661,14 @@ void makeUpdateSemiJoin(const ParseTree* n, void* obj) SimpleFilter *sf = dynamic_cast(tn); if (!sf) return; - + SimpleColumn *scLeft = dynamic_cast(sf->lhs()); SimpleColumn *scRight = dynamic_cast(sf->rhs()); CalpontSystemCatalog::TableAliasName* updatedTables = reinterpret_cast(obj); - //@Bug 3279. Added a check for column filters. + //@Bug 3279. Added a check for column filters. if ( scLeft && scRight && (strcasecmp(scRight->tableAlias().c_str(),scLeft->tableAlias().c_str()) != 0)) { - if ( (strcasecmp(scLeft->tableName().c_str(), updatedTables->table.c_str()) == 0 ) && (strcasecmp(scLeft->schemaName().c_str(), updatedTables->schema.c_str()) == 0) + if ( (strcasecmp(scLeft->tableName().c_str(), updatedTables->table.c_str()) == 0 ) && (strcasecmp(scLeft->schemaName().c_str(), updatedTables->schema.c_str()) == 0) && (strcasecmp(scLeft->tableAlias().c_str(),updatedTables->alias.c_str()) == 0)) { uint64_t lJoinInfo = sf->lhs()->joinInfo(); @@ -739,35 +689,24 @@ void makeUpdateSemiJoin(const ParseTree* n, void* obj) else return; } - else + else return; } -uint32_t doUpdateDelete(THD *thd) -{ - if (!thd->infinidb_vtable.cal_conn_info) - thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - - //@bug 5660. Error out DDL/DML on slave node, or on local query node - if (ci->isSlaveNode && !thd->slave_thread) - { - string emsg = logging::IDBErrorInfo::instance()->errorMsg(ERR_DML_DDL_SLAVE); - setError(current_thd, HA_ERR_UNSUPPORTED, emsg); - return HA_ERR_UNSUPPORTED; - } - +uint doUpdateDelete(THD *thd) +{ //@Bug 4387. Check BRM status before start statement. scoped_ptr dbrmp(new DBRM()); int rc = dbrmp->isReadWrite(); - thd->infinidb_vtable.isInfiniDBDML = true; - if (rc != 0 ) { setError(current_thd, HA_ERR_GENERIC, "Cannot execute the statement. DBRM is read only!"); return HA_ERR_UNSUPPORTED; } + if (!thd->infinidb_vtable.cal_conn_info) + thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); // stats start ci->stats.reset(); ci->stats.setStartTime(); @@ -786,12 +725,12 @@ uint32_t doUpdateDelete(THD *thd) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, msg.c_str()); } ci->stats.fSessionID = tid2sid(thd->thread_id); - + LEX* lex = thd->lex; idbassert(lex != 0); - + // Error out DELETE on VIEW. It's currently not supported. - // @note DELETE on VIEW works natually (for simple cases at least), but we choose to turn it off + // @note DELETE on VIEW works natually (for simple cases at least), but we choose to turn it off // for now - ZZ. TABLE_LIST* tables = thd->lex->query_tables; for (; tables; tables= tables->next_local) @@ -808,13 +747,13 @@ uint32_t doUpdateDelete(THD *thd) return HA_ERR_UNSUPPORTED; } -/* +/* // @bug5050. turn on cross engine support for delete/update #if (defined(_MSC_VER) && defined(_DEBUG)) || defined(SAFE_MUTEX) if ((strcmp((*tables->table->s->db_plugin)->name.str, "InfiniDB") != 0) && (strcmp((*tables->table->s->db_plugin)->name.str, "MEMORY") != 0) && - (tables->table->s->table_category != TABLE_CATEGORY_TEMPORARY) ) + (tables->table->s->table_category != TABLE_CATEGORY_TEMPORARY) ) #else if ((strcmp(tables->table->s->db_plugin->name.str, "InfiniDB") != 0) && (strcmp(tables->table->s->db_plugin->name.str, "MEMORY") != 0) && - (tables->table->s->table_category != TABLE_CATEGORY_TEMPORARY) ) + (tables->table->s->table_category != TABLE_CATEGORY_TEMPORARY) ) #endif { Message::Args args; @@ -825,7 +764,7 @@ uint32_t doUpdateDelete(THD *thd) } */ } - + // @bug 1127. Re-construct update stmt using lex instead of using the original query. string dmlStmt=""; string schemaName; @@ -833,11 +772,11 @@ uint32_t doUpdateDelete(THD *thd) string aliasName(""); UpdateSqlStatement updateSqlStmt; ColumnAssignmentList* colAssignmentListPtr = new ColumnAssignmentList(); + bool anyFromCol = false; bool isFromCol = false; bool isFromSameTable = true; execplan::SCSEP updateCP(new execplan::CalpontSelectExecutionPlan()); - updateCP->isDML(true); //@Bug 2753. the memory already freed by destructor of UpdateSqlStatement if (((thd->lex)->sql_command == SQLCOM_UPDATE) || ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI)) { @@ -849,30 +788,24 @@ uint32_t doUpdateDelete(THD *thd) dmlStmt += "update "; updateCP->queryType(CalpontSelectExecutionPlan::UPDATE); ci->stats.fQueryType = updateCP->queryType(); - uint32_t cnt = 0; - + uint cnt = 0; + for (; table_ptr; table_ptr= table_ptr->next_leaf) { dmlStmt += string(table_ptr->table_name); if (table_ptr->next_leaf) dmlStmt += ", "; } - - dmlStmt += " set "; - + + dmlStmt += " set "; + while ((item= (Item_field *) field_it++)) { cnt++; dmlStmt += string(item->name) + "="; - + string tmpTableName = bestTableName(item); - - //@Bug 5312 populate aliasname with tablename if it is empty - if (!item->table_name) - aliasName = tmpTableName; - else - aliasName = item->table_name; - + aliasName = item->table_name; if (strcasecmp(tableName.c_str(), "") == 0) { tableName = tmpTableName; @@ -883,44 +816,29 @@ uint32_t doUpdateDelete(THD *thd) string emsg(IDBErrorInfo::instance()->errorMsg(ERR_UPDATE_NOT_SUPPORT_FEATURE)); thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, emsg.c_str()); ci->rc = -1; - thd->row_count_func = 0; + thd->row_count_func = 0; return -1; } - if (!item->db_name) - { - //@Bug 5312. if subselect, wait until the schema info is available. - if (thd->derived_tables_processing) - return 0; - else - { - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "The statement cannot be processed without schema."); - ci->rc = -1; - thd->row_count_func = 0; - return -1; - } - } - else - schemaName = string(item->db_name); - + schemaName = string(item->db_name); columnAssignmentPtr = new ColumnAssignment(); columnAssignmentPtr->fColumn = string(item->name); columnAssignmentPtr->fOperator = "="; columnAssignmentPtr->fFuncScale = 0; - Item *value= value_it++; + Item *value= value_it++; if (value->type() == Item::STRING_ITEM) { //@Bug 2587 use val_str to replace value->name to get rid of 255 limit - String val, *str; - str = value->val_str(&val); - dmlStmt += "'" + string(str->c_ptr()) + "'"; + String val, *str; + str = value->val_str(&val); + dmlStmt += "'" + string(str->c_ptr()) + "'"; columnAssignmentPtr->fScalarExpression = string(str->c_ptr()) ; columnAssignmentPtr->fFromCol = false; - } + } else if ( value->type() == Item::VARBIN_ITEM ) - { + { String val, *str; - str = value->val_str(&val); - dmlStmt += "'" + string(str->c_ptr()) + "'"; + str = value->val_str(&val); + dmlStmt += "'" + string(str->c_ptr()) + "'"; columnAssignmentPtr->fScalarExpression = string(str->c_ptr()) ; columnAssignmentPtr->fFromCol = false; } @@ -934,7 +852,7 @@ uint32_t doUpdateDelete(THD *thd) vector tmpVec; bool hasNonSupportItem = false; uint16_t parseInfo = 0; - parse_item(ifp, tmpVec, hasNonSupportItem, parseInfo); + parse_item(ifp, tmpVec, hasNonSupportItem, parseInfo); // const f&e evaluate here. @bug3513. Rule out special functions that takes // no argument but needs to be sent to the back end to process. Like rand(), // sysdate() etc. @@ -944,7 +862,7 @@ uint32_t doUpdateDelete(THD *thd) gwi.thd = thd; SRCP srcp(buildReturnedColumn(value, gwi, gwi.fatalParseError)); ConstantColumn *constCol = dynamic_cast(srcp.get()); - if (constCol ) + if (constCol ) { columnAssignmentPtr->fScalarExpression = constCol->constval(); isFromCol = false; @@ -953,16 +871,18 @@ uint32_t doUpdateDelete(THD *thd) else { isFromCol = true; + anyFromCol = true; columnAssignmentPtr->fFromCol = true; - + } } else { isFromCol = true; + anyFromCol = true; columnAssignmentPtr->fFromCol = true; } - + if ( isFromCol ) { string sectableName(""); @@ -983,24 +903,18 @@ uint32_t doUpdateDelete(THD *thd) } } } - else if ( value->type() == Item::INT_ITEM ) + else if ( value->type() == Item::INT_ITEM ) { std::ostringstream oss; - if (value->unsigned_flag) - { - oss << value->val_uint(); - } - else - { - oss << value->val_int(); - } + oss << value->val_int(); dmlStmt += oss.str(); columnAssignmentPtr->fScalarExpression = oss.str(); columnAssignmentPtr->fFromCol = false; } - else if ( value->type() == Item::FIELD_ITEM) + else if ( value->type() == Item::FIELD_ITEM) { isFromCol = true; + anyFromCol = true; columnAssignmentPtr->fFromCol = true; Item_field* setIt = reinterpret_cast (value); string sectableName = string(setIt->table_name); @@ -1015,17 +929,18 @@ uint32_t doUpdateDelete(THD *thd) else { isFromSameTable = false; - } + } } else if ( value->type() == Item::NULL_ITEM ) { - dmlStmt += "NULL"; + dmlStmt += "NULL"; columnAssignmentPtr->fScalarExpression = "NULL"; columnAssignmentPtr->fFromCol = false; } else if ( value->type() == Item::SUBSELECT_ITEM ) { isFromCol = true; + anyFromCol = true; columnAssignmentPtr->fFromCol = true; Item_field* setIt = reinterpret_cast (value); string sectableName = string(setIt->table_name); @@ -1036,58 +951,42 @@ uint32_t doUpdateDelete(THD *thd) } } //@Bug 4449 handle default value - else if (value->type() == Item::DEFAULT_VALUE_ITEM) - { - Item_field* tmp = (Item_field*)value; - - if (!tmp->field_name) //null + else if (value->type() == Item::DEFAULT_VALUE_ITEM) + { + Item_field* tmp = (Item_field*)value; + + if (!tmp->field_name) //null { - dmlStmt += "NULL"; - columnAssignmentPtr->fScalarExpression = "NULL"; - columnAssignmentPtr->fFromCol = false; + dmlStmt += "NULL"; + columnAssignmentPtr->fScalarExpression = "NULL"; + columnAssignmentPtr->fFromCol = false; } else { - String val, *str; - str = value->val_str(&val); - dmlStmt += string(str->c_ptr()); - columnAssignmentPtr->fScalarExpression = string(str->c_ptr()); - columnAssignmentPtr->fFromCol = false; + String val, *str; + str = value->val_str(&val); + dmlStmt += string(str->c_ptr()); + columnAssignmentPtr->fScalarExpression = string(str->c_ptr()); + columnAssignmentPtr->fFromCol = false; } - } - else if (value->type() == Item::WINDOW_FUNC_ITEM) - { - setError(thd, HA_ERR_INTERNAL_ERROR, - logging::IDBErrorInfo::instance()->errorMsg(ERR_WF_UPDATE)); - return HA_ERR_UNSUPPORTED; - //return 0; - } - else + } + else { String val, *str; - str = value->val_str(&val); - if (str) - { - dmlStmt += string(str->c_ptr()); - columnAssignmentPtr->fScalarExpression = string(str->c_ptr()); - columnAssignmentPtr->fFromCol = false; - } - else - { - dmlStmt += "NULL"; - columnAssignmentPtr->fScalarExpression = "NULL"; - columnAssignmentPtr->fFromCol = false; - } - } - + str = value->val_str(&val); + dmlStmt += string(str->c_ptr()); + columnAssignmentPtr->fScalarExpression = string(str->c_ptr()); + columnAssignmentPtr->fFromCol = false; + } + colAssignmentListPtr->push_back ( columnAssignmentPtr ); - if (cnt < thd->lex->select_lex.item_list.elements) - dmlStmt += ", "; - } + if (cnt < thd->lex->select_lex.item_list.elements) + dmlStmt += ", "; + } } else { - dmlStmt = string(idb_mysql_query_str(thd)); + dmlStmt = string( thd->query ); updateCP->queryType(CalpontSelectExecutionPlan::DELETE); ci->stats.fQueryType = updateCP->queryType(); } @@ -1100,21 +999,21 @@ uint32_t doUpdateDelete(THD *thd) if (( (thd->lex)->sql_command == SQLCOM_UPDATE ) || ( (thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) ) { aTableName.schema = schemaName; - aTableName.table = tableName; + aTableName.table = tableName; } else { first_table= (TABLE_LIST*) thd->lex->select_lex.table_list.first; aTableName.schema = first_table->table->s->db.str; - aTableName.table = first_table->table->s->table_name.str; + aTableName.table = first_table->table->s->table_name.str; } - CalpontSystemCatalog::ROPair roPair; + CalpontSystemCatalog::ROPair roPair; try { roPair = csc->tableRID( aTableName ); } catch (IDBExcept &ie) { setError(thd, HA_ERR_NO_SUCH_TABLE, - ie.what()); + ie.what()); return HA_ERR_UNSUPPORTED; } catch (std::exception&ex) { @@ -1122,20 +1021,20 @@ uint32_t doUpdateDelete(THD *thd) logging::IDBErrorInfo::instance()->errorMsg(ERR_SYSTEM_CATALOG) + ex.what()); return HA_ERR_UNSUPPORTED; } - + ci->tableOid = roPair.objnum; CalpontDMLPackage* pDMLPackage = 0; - dmlStmt += ";"; - IDEBUG( cout << "STMT: " << dmlStmt << " and sessionID " << thd->thread_id << endl ); + dmlStmt += ";"; + IDEBUG( cout << "STMT: " << dmlStmt << " and sessionID " << thd->thread_id << endl ); VendorDMLStatement dmlStatement(dmlStmt, sessionID); if (( (thd->lex)->sql_command == SQLCOM_UPDATE ) || ( (thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) ) dmlStatement.set_DMLStatementType( DML_UPDATE ); else dmlStatement.set_DMLStatementType( DML_DELETE ); - + TableName* qualifiedTablName = new TableName(); - + UpdateSqlStatement updateStmt; //@Bug 2753. To make sure the momory is freed. updateStmt.fColAssignmentListPtr = colAssignmentListPtr; @@ -1146,47 +1045,11 @@ uint32_t doUpdateDelete(THD *thd) updateStmt.fNamePtr = qualifiedTablName; pDMLPackage = CalpontDMLFactory::makeCalpontUpdatePackageFromMysqlBuffer( dmlStatement, updateStmt ); } - else if ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI) //@Bug 6121 error out on multi tables delete. - { - if ( (thd->lex->select_lex.join) != 0) - { - multi_delete* deleteTable = (multi_delete*)((thd->lex->select_lex.join)->result); - first_table= (TABLE_LIST*) deleteTable->get_tables(); - if (deleteTable->num_of_tables == 1) - { - schemaName = first_table->db; - tableName = first_table->table_name; - aliasName = first_table->alias; - qualifiedTablName->fName = tableName; - qualifiedTablName->fSchema = schemaName; - pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(dmlStatement); - } - else - { - string emsg("Deleting rows from multiple tables in a single statement is currently not supported."); - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, emsg.c_str()); - ci->rc = 1; - thd->row_count_func = 0; - return 0; - } - } - else - { - first_table= (TABLE_LIST*) thd->lex->select_lex.table_list.first; - schemaName = first_table->table->s->db.str; - tableName = first_table->table->s->table_name.str; - aliasName = first_table->alias; - qualifiedTablName->fName = tableName; - qualifiedTablName->fSchema = schemaName; - pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(dmlStatement); - } - } else { first_table= (TABLE_LIST*) thd->lex->select_lex.table_list.first; schemaName = first_table->table->s->db.str; tableName = first_table->table->s->table_name.str; - aliasName = first_table->alias; qualifiedTablName->fName = tableName; qualifiedTablName->fSchema = schemaName; pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(dmlStatement); @@ -1198,38 +1061,32 @@ uint32_t doUpdateDelete(THD *thd) return HA_ERR_UNSUPPORTED; } pDMLPackage->set_TableName(tableName); - + pDMLPackage->set_SchemaName(schemaName); - + + //pDMLPackage->set_IsFromCol( anyFromCol ); pDMLPackage->set_IsFromCol( true ); //cout << " setting isFromCol to " << isFromCol << endl; - string origStmt(idb_mysql_query_str(thd)); - origStmt += ";"; + string origStmt( thd->query ); + origStmt += ";"; pDMLPackage->set_SQLStatement( origStmt ); - + //Save the item list - List items; - SELECT_LEX select_lex; - if (( (thd->lex)->sql_command == SQLCOM_UPDATE ) || ( (thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) ) - { - items = (thd->lex->select_lex.item_list); - thd->lex->select_lex.item_list = thd->lex->value_list; - } - select_lex = lex->select_lex; + List items = (thd->lex->select_lex.item_list); + thd->lex->select_lex.item_list = thd->lex->value_list; + + SELECT_LEX select_lex = lex->select_lex; - //@Bug 2808 Error out on order by or limit clause - //@bug5096. support dml limit. - if (/*( select_lex.explicit_limit ) || */( select_lex.order_list.elements != 0 ) ) + if (( select_lex.explicit_limit ) || ( select_lex.order_list.elements != 0 ) ) { - string emsg("DML Statement with order by clause is not currently supported."); + string emsg("DML Statement with a limit or order by clause is not currently supported."); thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, emsg.c_str()); ci->rc = 1; - thd->row_count_func = 0; + thd->row_count_func = 0; return 0; } - - //thd->infinidb_vtable.isInfiniDBDML = true; + thd->infinidb_vtable.isInfiniDBDML = true; THD::infinidb_state origState = thd->infinidb_vtable.vtable_state; //if (( (thd->lex)->sql_command == SQLCOM_UPDATE ) || ( (thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) ) { @@ -1247,13 +1104,13 @@ uint32_t doUpdateDelete(THD *thd) txnID.id = 0; txnID.valid = true; } - QueryContext verID; + CalpontSystemCatalog::SCN verID; verID = sm.verID(); - + updateCP->txnID(txnID.id); updateCP->verID(verID); updateCP->sessionID(sessionID); - updateCP->data(idb_mysql_query_str(thd)); + updateCP->data(thd->query); try { updateCP->priority( ci->stats.userPriority(ci->stats.fHost, ci->stats.fUser)); }catch(std::exception& e) @@ -1269,36 +1126,27 @@ uint32_t doUpdateDelete(THD *thd) if (thd->infinidb_vtable.isUpdateWithDerive) { // @bug 4457. MySQL inconsistence! for some queries, some structures are only available - // in the derived_tables_processing phase. So by pass the phase for DML only when the + // in the derived_tables_processing phase. So by pass the phase for DML only when the // execution plan can not be successfully generated. recover lex before returning; thd->lex->select_lex.item_list = items; thd->infinidb_vtable.vtable_state = origState; return 0; } - + //check different error code - // avoid double set IDB error - string emsg; - if (gwi.parseErrorText.find("IDB-") == string::npos) - { - Message::Args args; - args.add(gwi.parseErrorText); - emsg = IDBErrorInfo::instance()->errorMsg(ERR_DML_NOT_SUPPORT_FEATURE, args); - } - else - { - emsg = gwi.parseErrorText; - } + Message::Args args; + args.add(gwi.parseErrorText); + string emsg(IDBErrorInfo::instance()->errorMsg(ERR_DML_NOT_SUPPORT_FEATURE, args)); thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, emsg.c_str()); ci->rc = -1; - thd->row_count_func = 0; + thd->row_count_func = 0; return -1; - + } -//cout<< "Plan before is " << endl << *updateCP << endl; + //set the large side by putting the updated table at the first CalpontSelectExecutionPlan::TableList tbList = updateCP->tableList(); - + CalpontSelectExecutionPlan::TableList::iterator iter = tbList.begin(); bool notFirst = false; while ( iter != tbList.end() ) @@ -1318,12 +1166,12 @@ uint32_t doUpdateDelete(THD *thd) string emsg(IDBErrorInfo::instance()->errorMsg(ERR_COLUMN_EQ_DIFFTABLE_COLUMN, args)); thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, emsg.c_str()); ci->rc = 1; - thd->row_count_func = 0; + thd->row_count_func = 0; return 0; */ CalpontSystemCatalog::TableAliasName tn = make_aliastable(schemaName, tableName, aliasName); iter = tbList.begin(); - tbList.insert( iter, 1, tn ); + tbList.insert( iter, 1, tn ); } updateCP->tableList( tbList ); updateCP->overrideLargeSideEstimate( true ); @@ -1333,9 +1181,9 @@ uint32_t doUpdateDelete(THD *thd) while ( coliter != returnedCols.end() ) { ConstantColumn *returnCol = dynamic_cast((*coliter).get()); - if (returnCol ) + if (returnCol ) { - returnedCols.erase(coliter); + returnedCols.erase(coliter); coliter = returnedCols.begin(); //cout << "constant column " << endl; } @@ -1346,47 +1194,6 @@ uint32_t doUpdateDelete(THD *thd) throw runtime_error ("column map is empty!"); if (returnedCols.empty()) returnedCols.push_back((updateCP->columnMap()).begin()->second); - //@Bug 6123. get the correct returned columnlist - if (( (thd->lex)->sql_command == SQLCOM_DELETE ) || ( (thd->lex)->sql_command == SQLCOM_DELETE_MULTI ) ) - { - returnedCols.clear(); - //choose the smallest column to project - CalpontSystemCatalog::TableName deleteTableName; - deleteTableName.schema = schemaName; - deleteTableName.table = tableName; - CalpontSystemCatalog::RIDList colrids; - try { - colrids = csc->columnRIDs(deleteTableName); - } - catch (IDBExcept &ie) { - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, ie.what()); - ci->rc = -1; - thd->row_count_func = 0; - return 0; - } - int minColWidth = -1; - int minWidthColOffset = 0; - for (unsigned int j = 0; j < colrids.size(); j++) - { - CalpontSystemCatalog::ColType ct = csc->colType(colrids[j].objnum); - if (ct.colDataType == CalpontSystemCatalog::VARBINARY) - continue; - - if (minColWidth == -1 || ct.colWidth < minColWidth) - { - minColWidth = ct.colWidth; - minWidthColOffset= j; - } - } - CalpontSystemCatalog::TableColName tcn = csc->colName(colrids[minWidthColOffset].objnum); - SimpleColumn *sc = new SimpleColumn(tcn.schema, tcn.table, tcn.column, csc->sessionID()); - sc->tableAlias(aliasName); - sc->resultType(csc->colType(colrids[minWidthColOffset].objnum)); - SRCP srcp; - srcp.reset(sc); - returnedCols.push_back(srcp); - //cout << "tablename:alias = " << tcn.table<<":"<returnedCols( returnedCols ); if (( (thd->lex)->sql_command == SQLCOM_UPDATE ) || ( (thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) ) { @@ -1405,17 +1212,15 @@ uint32_t doUpdateDelete(THD *thd) ptsub->walk(makeUpdateSemiJoin, &tbList[0] ); } //cout<< "Plan is " << endl << *updateCP << endl; - if (( (thd->lex)->sql_command == SQLCOM_UPDATE ) || ( (thd->lex)->sql_command == SQLCOM_UPDATE_MULTI ) ) - thd->lex->select_lex.item_list = items; + thd->lex->select_lex.item_list = items; } //cout<< "Plan is " << endl << *updateCP << endl; } - + //updateCP->traceFlags(1); //cout<< "Plan is " << endl << *updateCP << endl; pDMLPackage->HasFilter(true); - pDMLPackage->uuid(updateCP->uuid()); - + ByteStream bytestream, bytestream1; bytestream << sessionID; boost::shared_ptr plan = pDMLPackage->get_ExecutionPlan(); @@ -1438,7 +1243,7 @@ uint32_t doUpdateDelete(THD *thd) } //querystats::QueryStats stats; string tableLockInfo; - + // Send the request to DMLProc and wait for a response. try { @@ -1474,15 +1279,8 @@ uint32_t doUpdateDelete(THD *thd) if (!ci->dmlProc) { ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "doUpdateDelete start new DMLProc client " << ci->dmlProc << " for session " << sessionID << endl; - } - else - { - delete ci->dmlProc; - ci->dmlProc = NULL; - ci->dmlProc = new MessageQueueClient("DMLProc"); + //cout << "test007: doUpdateDelete use new DMLProc client " << ci->dmlProc << " for session " << sessionID << endl; } - // Send the request to DMLProc ci->dmlProc->write(bytestream); // Get an answer from DMLProc @@ -1497,7 +1295,6 @@ uint32_t doUpdateDelete(THD *thd) // DMLProc to stop processing and return an error on the // original connection which will cause a rollback. messageqcpp::MessageQueueClient ctrlCProc("DMLProc"); - //cout << "doUpdateDelete start new DMLProc client for ctrl-c " << " for session " << sessionID << endl; VendorDMLStatement cmdStmt( "CTRL+C", DML_COMMAND, sessionID); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(cmdStmt); ByteStream bytestream; @@ -1531,7 +1328,6 @@ uint32_t doUpdateDelete(THD *thd) } if (bytestream1.length() == 0 && thd->killed <= 0) { - //cout << "line 1442. received 0 byte from DMLProc and retry = "<< retry << endl; // Seems dmlProc isn't playing. Reset it and try again. delete ci->dmlProc; ci->dmlProc = NULL; @@ -1566,13 +1362,12 @@ uint32_t doUpdateDelete(THD *thd) ci->stats.unserialize(bytestream1); } } - + dmlRowCount = rows; if (thd->killed && b == 0) { b = dmlpackageprocessor::DMLPackageProcessor::JOB_CANCELED; - errorMsg = "Command canceled by user"; } } catch (runtime_error& ex) @@ -1585,31 +1380,27 @@ uint32_t doUpdateDelete(THD *thd) } catch ( ... ) { - //cout << "... exception while writing to DMLProc" << endl; + cout << "... exception while writing to DMLProc" << endl; b = 1; delete ci->dmlProc; ci->dmlProc = NULL; errorMsg = "Unknown error caught"; } - + // If autocommit is on then go ahead and tell the engine to commit the transaction //@Bug 1960 If error occurs, the commit is just to release the active transaction. //@Bug 2241. Rollback transaction when it failed //@Bug 4605. If error, always rollback. if (b != dmlpackageprocessor::DMLPackageProcessor::ACTIVE_TRANSACTION_ERROR) - { + { std::string command; - if ((useHdfs) && (b == 0)) - command = "COMMIT"; - else if ((useHdfs) && (b != 0)) - command = "ROLLBACK"; - else if ((!(current_thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) && (( b == 0 ) || (b == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING)) ) + if ((!(current_thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) && (( b == 0 ) || (b == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING)) ) command = "COMMIT"; - else if (( b != 0 ) && (b != dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) ) + else if (( b != 0 ) && (b != dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) ) command = "ROLLBACK"; - else + else command = ""; - + if ( command != "") { VendorDMLStatement cmdStmt(command, DML_COMMAND, sessionID); @@ -1619,7 +1410,7 @@ uint32_t doUpdateDelete(THD *thd) bytestream << static_cast(sessionID); pDMLPackage->write(bytestream); delete pDMLPackage; - + ByteStream::byte bc; std::string errMsg; try @@ -1627,17 +1418,18 @@ uint32_t doUpdateDelete(THD *thd) if (!ci->dmlProc) { ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << " doupdateDelete command use a new dml client " << ci->dmlProc << endl; + errorMsg = "Command canceled by user"; +// cout << "test007:command use dml client " << ci->dmlProc << endl; } ci->dmlProc->write(bytestream); bytestream1 = ci->dmlProc->read(); bytestream1 >> bc; bytestream1 >> rows; bytestream1 >> errMsg; - if ( b == 0 ) + if ( b == 0 ) { b = bc; - errorMsg = errMsg; + errorMsg = errMsg; } } catch (runtime_error&) @@ -1654,15 +1446,15 @@ uint32_t doUpdateDelete(THD *thd) } } } - + //@Bug 2241 Display an error message to user - + if ( ( b != 0 ) && (b != dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING)) - { - //@Bug 2540. Set error status instead of warning + { + //@Bug 2540. Set error status instead of warning thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, errorMsg.c_str()); ci->rc = b; - thd->row_count_func = 0; + thd->row_count_func = 0; thd->main_da.can_overwrite_status = true; //cout << " error status " << ci->rc << endl; } @@ -1670,8 +1462,6 @@ uint32_t doUpdateDelete(THD *thd) { if (dmlRowCount != 0) //Bug 5117. Handling self join. thd->row_count_func = dmlRowCount; - - //cout << " error status " << ci->rc << " and rowcount = " << dmlRowCount << endl; } if ( b == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING ) @@ -1679,27 +1469,25 @@ uint32_t doUpdateDelete(THD *thd) //string errmsg ("Out of range value detected. Please check Calpont Syntax Guide for supported data range." ); push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, errorMsg.c_str()); } - + // @bug 4027. comment out the following because this will cause mysql // kernel assertion failure. not sure why this is here in the first place. // if (thd->derived_tables) // { // thd->main_da.can_overwrite_status= TRUE; // thd->main_da.set_ok_status( thd, dmlRowCount, 0, ""); -// } +// } // insert query stats ci->stats.setEndTime(); - try + try { ci->stats.insert(); - } + } catch (std::exception& e) { string msg = string("InfiniDB Query Stats - ") + e.what(); push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, msg.c_str()); } - delete ci->dmlProc; - ci->dmlProc = NULL; return 0; } @@ -1764,7 +1552,7 @@ long long calsettrace(UDF_INIT* initid, UDF_ARGS* args, if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); long long oldTrace = ci->traceFlags; ci->traceFlags = (uint32_t)(*((long long*)args->args[0])); @@ -1808,12 +1596,10 @@ const size_t Elen = strlen(SetParmsError); const char* invalidParmSizeMessage(uint64_t size, size_t& len) { - static char str[sizeof(InvalidParmSize) + 12] = {0}; ostringstream os; os << InvalidParmSize << size; len = os.str().length(); - strcpy(str, os.str().c_str()); - return str; + return os.str().c_str(); } #ifdef _MSC_VER @@ -1871,7 +1657,7 @@ const char* calsetparms(UDF_INIT* initid, UDF_ARGS* args, memcpy(result + mlen, valuestr, vlen); *length = mlen + vlen; } - else + else *length = mlen; return result; } @@ -1887,7 +1673,7 @@ my_bool calsetparms_init(UDF_INIT* initid, UDF_ARGS* args, char* message) return 1; } initid->max_length=MAXSTRINGLENGTH; - + char valuestr[MAXSTRINGLENGTH]; size_t vlen = args->lengths[1]; @@ -1992,11 +1778,10 @@ const char* calviewtablelock(UDF_INIT* initid, UDF_ARGS* args, if ( !ci->dmlProc ) { ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "viewtablelock starts a new client " << ci->dmlProc << " for session " << thd->thread_id << endl; } string lockinfo = ha_calpont_impl_viewtablelock(*ci, tableName); - + memcpy(result,lockinfo.c_str(), lockinfo.length()); *length = lockinfo.length(); return result; @@ -2036,20 +1821,17 @@ const char* calcleartablelock(UDF_INIT* initid, UDF_ARGS* args, THD* thd = current_thd; if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - + cal_connection_info* ci = reinterpret_cast( - thd->infinidb_vtable.cal_conn_info); + thd->infinidb_vtable.cal_conn_info); long long lockID = *reinterpret_cast(args->args[0]); - + if ( !ci->dmlProc ) - { ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "cleartablelock starts a new client " << ci->dmlProc << " for session " << thd->thread_id << endl; - } unsigned long long uLockID = lockID; string lockinfo = ha_calpont_impl_cleartablelock(*ci, uLockID); - + memcpy(result,lockinfo.c_str(), lockinfo.length()); *length = lockinfo.length(); return result; @@ -2101,9 +1883,9 @@ long long callastinsertid(UDF_INIT* initid, UDF_ARGS* args, char* is_null, char* error) { THD* thd = current_thd; - + CalpontSystemCatalog::TableName tableName; - uint64_t nextVal = 0; + long long nextVal = 0; if ( args->arg_count == 2 ) { tableName.schema = args->args[0]; @@ -2122,19 +1904,16 @@ long long callastinsertid(UDF_INIT* initid, UDF_ARGS* args, boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(tid2sid(thd->thread_id)); csc->identity(execplan::CalpontSystemCatalog::FE); - - try - { - nextVal = csc->nextAutoIncrValue(tableName); - } - catch (std::exception&) + nextVal = csc->nextAutoIncrValue(tableName); + + if (nextVal == -2) { string msg("No such table found"); setError(thd, HA_ERR_UNSUPPORTED, msg); return nextVal; } - - if (nextVal == AUTOINCR_SATURATED) + + if (nextVal < 0) { setError(thd, HA_ERR_UNSUPPORTED, IDBErrorInfo::instance()->errorMsg(ERR_EXCEED_LIMIT)); return nextVal; @@ -2143,10 +1922,10 @@ long long callastinsertid(UDF_INIT* initid, UDF_ARGS* args, if (nextVal == 0) { string msg("Autoincrement does not exist for this table."); - setError(thd, HA_ERR_UNSUPPORTED, msg); + setError(thd, HA_ERR_UNSUPPORTED, msg); return nextVal; } - + return (nextVal-1); } @@ -2211,8 +1990,8 @@ const char* calgettrace(UDF_INIT* initid, UDF_ARGS* args, if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + if (flags > 0) //msgp = &connMap[sessionID].extendedStats; msgp = &ci->extendedStats; @@ -2291,7 +2070,7 @@ void calgetversion_deinit(UDF_INIT* initid) } //extern "C" -int ha_calpont_impl_open(const char *name, int mode, uint32_t test_if_locked) +int ha_calpont_impl_open(const char *name, int mode, uint test_if_locked) { IDEBUG ( cout << "ha_calpont_impl_open: " << name << ", " << mode << ", " << test_if_locked << endl ); Config::makeConfig(); @@ -2307,58 +2086,44 @@ int ha_calpont_impl_close(void) int ha_calpont_impl_rnd_init(TABLE* table) { #ifdef DEBUG_SETENV - string home(getenv("HOME")); - if (!getenv("CALPONT_HOME")) - { - string calpontHome(home + "/Calpont/etc/"); - setenv("CALPONT_HOME", calpontHome.c_str(), 1); - } - - if (!getenv("CALPONT_CONFIG_FILE")) - { - string calpontConfigFile(home + "/Calpont/etc/Calpont.xml"); - setenv("CALPONT_CONFIG_FILE", calpontConfigFile.c_str(), 1); - } - - if (!getenv("CALPONT_CSC_IDENT")) - setenv("CALPONT_CSC_IDENT", "dm", 1); + string home(getenv("HOME")); + if (!getenv("CALPONT_HOME")) + { + string calpontHome(home + "/Calpont/etc/"); + setenv("CALPONT_HOME", calpontHome.c_str(), 1); + } + + if (!getenv("CALPONT_CONFIG_FILE")) + { + string calpontConfigFile(home + "/Calpont/etc/Calpont.xml"); + setenv("CALPONT_CONFIG_FILE", calpontConfigFile.c_str(), 1); + } + + if (!getenv("CALPONT_CSC_IDENT")) + setenv("CALPONT_CSC_IDENT", "dm", 1); #endif IDEBUG( cout << "rnd_init for table " << table->s->table_name.str << endl ); THD* thd = current_thd; - - // prevent "create table as select" from running on slave - thd->infinidb_vtable.hasInfiniDBTable = true; - - /* If this node is the slave, ignore DML to IDB tables */ - if (thd->slave_thread && ( - thd->lex->sql_command == SQLCOM_INSERT || - thd->lex->sql_command == SQLCOM_INSERT_SELECT || - thd->lex->sql_command == SQLCOM_UPDATE || - thd->lex->sql_command == SQLCOM_UPDATE_MULTI || - thd->lex->sql_command == SQLCOM_DELETE || - thd->lex->sql_command == SQLCOM_DELETE_MULTI || - thd->lex->sql_command == SQLCOM_TRUNCATE || - thd->lex->sql_command == SQLCOM_LOAD)) - return 0; - - // @bug 3005. if the table is not $vtable, then this could be a UDF defined on the connector. - // watch this for other complications - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE && - string(table->s->table_name.str).find("$vtable") != 0) - return 0; + + // @bug 3005. if the table is not $vtable, then this could be a UDF defined on the connector. + // watch this for other complications + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE && + string(table->s->table_name.str).find("$vtable") != 0) + return 0; // return error is error status is already set if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ERROR) return HA_ERR_INTERNAL_ERROR; - + // by pass the extra union trips. return 0 if (thd->infinidb_vtable.isUnion && thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE) return 0; - + // @bug 2232. Basic SP support. Error out non support sp cases. // @bug 3939. Only error out for sp with select. Let pass for alter table in sp. - if (thd->infinidb_vtable.call_sp && (thd->lex)->sql_command != SQLCOM_ALTER_TABLE) + if (thd->infinidb_vtable.call_sp && (thd->lex)->sql_command != SQLCOM_ALTER_TABLE + /*thd->infinidb_vtable.vtable_state != THD::INFINIDB_INIT && thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE*/) { setError(thd, HA_ERR_UNSUPPORTED, "This stored procedure syntax is not supported by InfiniDB in this version"); thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; @@ -2377,26 +2142,25 @@ int ha_calpont_impl_rnd_init(TABLE* table) // mysql reads table twice for order by if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_PHASE1 || - thd->infinidb_vtable.vtable_state == THD::INFINIDB_ORDER_BY) + thd->infinidb_vtable.vtable_state == THD::INFINIDB_ORDER_BY) return 0; - + if ( (thd->lex)->sql_command == SQLCOM_ALTER_TABLE ) return 0; - + //Update and delete code if ( ((thd->lex)->sql_command == SQLCOM_UPDATE) || ((thd->lex)->sql_command == SQLCOM_DELETE) || ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI) || ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI)) return doUpdateDelete(thd); - + uint32_t sessionID = tid2sid(thd->thread_id); - boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); + boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); csc->identity(CalpontSystemCatalog::FE); - if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); idbassert(ci != 0); - + if(thd->killed == THD::KILL_QUERY) { if (ci->cal_conn_hndl) @@ -2423,25 +2187,16 @@ int ha_calpont_impl_rnd_init(TABLE* table) sm::cpsm_conhdl_t* hndl; SCSEP csep; - // update traceFlags according to the autoswitch state. replication query - // on slave are in table mode (create table as...) - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE || - (thd->slave_thread && thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT)) - { + // update traceFlags according to the autoswitch state + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) ci->traceFlags |= CalpontSelectExecutionPlan::TRACE_TUPLE_OFF; - thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; - } else - { ci->traceFlags = (ci->traceFlags | CalpontSelectExecutionPlan::TRACE_TUPLE_OFF)^ - CalpontSelectExecutionPlan::TRACE_TUPLE_OFF; - } - - bool localQuery = (thd->variables.infinidb_local_query>0 ? true : false); + CalpontSelectExecutionPlan::TRACE_TUPLE_OFF; // table mode if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) - { + { ti = ci->tableMap[table]; // get connection handle for this table handler @@ -2451,11 +2206,17 @@ int ha_calpont_impl_rnd_init(TABLE* table) sm::sm_cleanup(ti.conn_hndl); ti.conn_hndl = 0; } - - sm::sm_init(sessionID, &ti.conn_hndl, localQuery); - ti.conn_hndl->csc = csc; + if (ti.conn_hndl == 0) + { + + char sessionIDstr[80]; + snprintf(sessionIDstr, 80, "%u", sessionID); + sessionIDstr[79] = 0; + sm::sm_init(0, 0, 0, sessionIDstr, (void**)&ti.conn_hndl); + ti.conn_hndl->csc = csc; + } hndl = ti.conn_hndl; - + try { ti.conn_hndl->connect(); } catch (...) { @@ -2463,8 +2224,8 @@ int ha_calpont_impl_rnd_init(TABLE* table) CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); goto error; } - - // get filter plan for table + + // get filter plan for table if (ti.csep.get() == 0) { ti.csep.reset(new CalpontSelectExecutionPlan()); @@ -2477,31 +2238,30 @@ int ha_calpont_impl_rnd_init(TABLE* table) txnID.id = 0; txnID.valid = true; } - QueryContext verID; + CalpontSystemCatalog::SCN verID; verID = sm.verID(); - + ti.csep->txnID(txnID.id); ti.csep->verID(verID); ti.csep->sessionID(sessionID); - if (thd->db) - ti.csep->schemaName(thd->db); + ti.csep->traceFlags(ci->traceFlags); ti.msTablePtr = table; - + // send plan whenever rnd_init is called cp_get_table_plan(thd, ti.csep, ti); } - + IDEBUG( cerr << table->s->table_name.str << " send plan:" << endl ); IDEBUG( cerr << *ti.csep << endl ); csep = ti.csep; - + // for ExeMgr logging sqltext. only log once for the query although multi plans may be sent if (ci->tableMap.size() == 1) - ti.csep->data(idb_mysql_query_str(thd)); + ti.csep->data(thd->query); } // vtable mode - else + else { //if (!ci->cal_conn_hndl || thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE) if ( thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE) @@ -2531,12 +2291,20 @@ int ha_calpont_impl_rnd_init(TABLE* table) ci->cal_conn_hndl = 0; } } + + if (!ci->cal_conn_hndl) + { + char sessionIDstr[80]; + snprintf(sessionIDstr, 80, "%u", sessionID); + sessionIDstr[79] = 0; + sm::sm_init(0, 0, 0, sessionIDstr, (void**)&ci->cal_conn_hndl); + idbassert(ci->cal_conn_hndl != 0); + ci->cal_conn_hndl->csc = csc; + } - sm::sm_init(sessionID, &ci->cal_conn_hndl, localQuery); idbassert(ci->cal_conn_hndl != 0); - ci->cal_conn_hndl->csc = csc; idbassert(ci->cal_conn_hndl->exeMgr != 0); - + try { ci->cal_conn_hndl->connect(); } catch (...) { @@ -2545,7 +2313,7 @@ int ha_calpont_impl_rnd_init(TABLE* table) goto error; } hndl = ci->cal_conn_hndl; - + if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_SELECT_VTABLE) { //CalpontSelectExecutionPlan csep; @@ -2560,19 +2328,17 @@ int ha_calpont_impl_rnd_init(TABLE* table) txnID.id = 0; txnID.valid = true; } - QueryContext verID; + CalpontSystemCatalog::SCN verID; verID = sm.verID(); - + csep->txnID(txnID.id); csep->verID(verID); csep->sessionID(sessionID); - if (thd->db) - csep->schemaName(thd->db); - + csep->traceFlags(ci->traceFlags); if (thd->infinidb_vtable.isInsertSelect) csep->queryType(CalpontSelectExecutionPlan::INSERT_SELECT); - + //get plan int status = cp_get_plan(thd, csep); //if (cp_get_plan(thd, csep) != 0) @@ -2580,11 +2346,11 @@ int ha_calpont_impl_rnd_init(TABLE* table) return HA_ERR_INTERNAL_ERROR; else if (status < 0) return 0; - + // @bug 2547. don't need to send the plan if it's impossible where for all unions. - if (thd->infinidb_vtable.impossibleWhereOnUnion) + if (thd->infinidb_vtable.impossibleWhereOnUnion) return 0; - + csep->data(thd->infinidb_vtable.original_query.c_ptr()); try { csep->priority( ci->stats.userPriority(ci->stats.fHost, ci->stats.fUser)); @@ -2603,137 +2369,133 @@ int ha_calpont_impl_rnd_init(TABLE* table) csep->unserialize(bs1); #endif - if (ci->traceFlags & 1) - { - cerr << "---------------- EXECUTION PLAN ----------------" << endl; - cerr << *csep << endl ; - cerr << "-------------- EXECUTION PLAN END --------------\n" << endl; - } - else - { - IDEBUG( cout << "---------------- EXECUTION PLAN ----------------" << endl ); - IDEBUG( cerr << *csep << endl ); - IDEBUG( cout << "-------------- EXECUTION PLAN END --------------\n" << endl ); - } - } + IDEBUG( cout << "---------------- EXECUTION PLAN ----------------" << endl ); + IDEBUG( cerr << *csep << endl ); + IDEBUG( cout << "-------------- EXECUTION PLAN END --------------\n" << endl ); + } }// end of execution plan generation - - if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_SELECT_VTABLE) - { - ByteStream msg; - ByteStream emsgBs; - - while (true) + + if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_SELECT_VTABLE) { - try { - ByteStream::quadbyte qb = 4; - msg << qb; - hndl->exeMgr->write(msg); - msg.restart(); - csep->rmParms(rmParms); - - //send plan - csep->serialize(msg); - hndl->exeMgr->write(msg); - - //get ExeMgr status back to indicate a vtable joblist success or not - msg.restart(); - emsgBs.restart(); - msg = hndl->exeMgr->read(); - emsgBs = hndl->exeMgr->read(); - string emsg; - - if (msg.length() == 0 || emsgBs.length() == 0) - { - emsg = "Lost connection to ExeMgr. Please contact your administrator"; - setError(thd, HA_ERR_UNSUPPORTED, emsg); - return HA_ERR_UNSUPPORTED; - } - string emsgStr; - emsgBs >> emsgStr; - bool err = false; - - if (msg.length() == 4) - { - msg >> qb; - if (qb != 0) + ByteStream msg; + ByteStream emsgBs; + + while (true) + { + try { + ByteStream::quadbyte qb = 4; + msg << qb; + hndl->exeMgr->write(msg); + msg.restart(); + csep->rmParms(rmParms); + + //send plan + csep->serialize(msg); + hndl->exeMgr->write(msg); + + //get ExeMgr status back to indicate a vtable joblist success or not + msg.restart(); + emsgBs.restart(); + msg = hndl->exeMgr->read(); + emsgBs = hndl->exeMgr->read(); + string emsg; + //ByteStream::quadbyte qb; + + if (msg.length() == 0 || emsgBs.length() == 0) { - err = true; - // for makejoblist error, stats contains only error code and insert from here - // because table fetch is not started - ci->stats.setEndTime(); - ci->stats.fQuery = csep->data(); - ci->stats.fQueryType = csep->queryType(); - ci->stats.fErrorNo = qb; - try { - ci->stats.insert(); - } catch (std::exception& e) + emsg = "Lost connection to ExeMgr. Please contact your administrator"; + setError(thd, HA_ERR_UNSUPPORTED, emsg); + return HA_ERR_UNSUPPORTED; + } + string emsgStr; + emsgBs >> emsgStr; + bool err = false; + + if (msg.length() == 4) + { + msg >> qb; + if (qb != 0) { - string msg = string("InfiniDB Query Stats - ") + e.what(); - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, msg.c_str()); + err = true; + // for makejoblist error, stats contains only error code and insert from here + // because table fetch is not started + ci->stats.setEndTime(); + ci->stats.fQuery = csep->data(); + ci->stats.fQueryType = csep->queryType(); + ci->stats.fErrorNo = qb; + try { + ci->stats.insert(); + } catch (std::exception& e) + { + string msg = string("InfiniDB Query Stats - ") + e.what(); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, msg.c_str()); + } } } - } - else - { - err = true; - } - if (err) - { - setError(thd, HA_ERR_UNSUPPORTED, emsgStr); - return HA_ERR_UNSUPPORTED; - } - - rmParms.clear(); - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) - { - ci->tableMap[table] = ti; - } - else + else + { + err = true; + } + if (err) + { + setError(thd, HA_ERR_UNSUPPORTED, emsgStr); + return HA_ERR_UNSUPPORTED; + } + + rmParms.clear(); + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) + { + ci->tableMap[table] = ti; + } + else + { + ci->queryState = 1; + } + break; + } catch (...) { - ci->queryState = 1; - } - break; - } catch (...) { - sm::sm_cleanup(hndl); - hndl = 0; - - sm::sm_init(sessionID, &hndl, localQuery); - idbassert(hndl != 0); - hndl->csc = csc; - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) - ti.conn_hndl = hndl; - else - ci->cal_conn_hndl = hndl; - try { - hndl->connect(); - } catch (...) { - setError(thd, HA_ERR_INTERNAL_ERROR, IDBErrorInfo::instance()->errorMsg(ERR_LOST_CONN_EXEMGR)); - CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); - goto error; + sm::sm_cleanup(hndl); + + char sessionIDstr[80]; + snprintf(sessionIDstr, 80, "%u", sessionID); + sessionIDstr[79] = 0; + sm::sm_init(0, 0, 0, sessionIDstr, (void**)&hndl); + idbassert(hndl != 0); + hndl->csc = csc; + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) + ti.conn_hndl = hndl; + else + ci->cal_conn_hndl = hndl; + try { + hndl->connect(); + } catch (...) + { + setError(thd, HA_ERR_INTERNAL_ERROR, IDBErrorInfo::instance()->errorMsg(ERR_LOST_CONN_EXEMGR)); + CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); + goto error; + } + msg.restart(); } - msg.restart(); } - } - } +} // common path for both vtable select phase and table mode -- open scan handle ti = ci->tableMap[table]; ti.msTablePtr = table; if ((thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE)|| - (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) || - (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_QUERY)) + (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) || + (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_QUERY)) { if (ti.tpl_ctx == 0) - { + { ti.tpl_ctx = new sm::cpsm_tplh_t(); ti.tpl_scan_ctx = sm::sp_cpsm_tplsch_t(new sm::cpsm_tplsch_t()); } - + // make sure rowgroup is null so the new meta data can be taken. This is for some case mysql // call rnd_init for a table more than once. ti.tpl_scan_ctx->rowGroup = NULL; - + try { tableid = execplan::IDB_VTABLE_ID; } catch (...) { @@ -2742,10 +2504,10 @@ int ha_calpont_impl_rnd_init(TABLE* table) CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); goto internal_error; } - + try { - sm::tpl_open(tableid, ti.tpl_ctx, hndl); - sm::tpl_scan_open(tableid, ti.tpl_scan_ctx, hndl); + sm::tpl_open(tableid, (void**)&ti.tpl_ctx, hndl); + sm::tpl_scan_open(tableid, sm::TPL_FH_READ, ti.tpl_scan_ctx, hndl); } catch (std::exception& e) { string emsg = "table can not be opened: " + string(e.what()); @@ -2760,23 +2522,27 @@ int ha_calpont_impl_rnd_init(TABLE* table) CalpontSystemCatalog::removeCalpontSystemCatalog(sessionID); goto internal_error; } - + ti.tpl_scan_ctx->traceFlags = ci->traceFlags; if ((ti.tpl_scan_ctx->ctp).size() == 0) { - uint32_t num_attr = table->s->fields; - for (uint32_t i=0; i < num_attr; i++) + //CalpontSystemCatalog::ColType* ct; + uint num_attr = table->s->fields; + for (uint i=0; i < num_attr; i++) { CalpontSystemCatalog::ColType ctype; ti.tpl_scan_ctx->ctp.push_back(ctype); } + //ct = (CalpontSystemCatalog::ColType*)calloc(num_attr, sizeof(CalpontSystemCatalog::ColType)); + + //idbassert(ct != 0); // populate coltypes here for table mode because tableband gives treeoid for dictionary column if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) { CalpontSystemCatalog::RIDList oidlist = csc->columnRIDs(make_table(table->s->db.str, table->s->table_name.str), true); for (unsigned int j = 0; j < oidlist.size(); j++) - { + { CalpontSystemCatalog::ColType ctype = csc->colType(oidlist[j].objnum); ti.tpl_scan_ctx->ctp[ctype.colPosition] = ctype; ti.tpl_scan_ctx->ctp[ctype.colPosition].colPosition = -1; @@ -2784,7 +2550,7 @@ int ha_calpont_impl_rnd_init(TABLE* table) } } } - + ci->tableMap[table] = ti; return 0; @@ -2796,7 +2562,7 @@ int ha_calpont_impl_rnd_init(TABLE* table) } // do we need to close all connection handle of the table map? return HA_ERR_INTERNAL_ERROR; - + internal_error: if (ci->cal_conn_hndl) { @@ -2810,46 +2576,32 @@ int ha_calpont_impl_rnd_next(uchar *buf, TABLE* table) { THD* thd = current_thd; - /* If this node is the slave, ignore DML to IDB tables */ - if (thd->slave_thread && ( - thd->lex->sql_command == SQLCOM_INSERT || - thd->lex->sql_command == SQLCOM_INSERT_SELECT || - thd->lex->sql_command == SQLCOM_UPDATE || - thd->lex->sql_command == SQLCOM_UPDATE_MULTI || - thd->lex->sql_command == SQLCOM_DELETE || - thd->lex->sql_command == SQLCOM_DELETE_MULTI || - thd->lex->sql_command == SQLCOM_TRUNCATE || - thd->lex->sql_command == SQLCOM_LOAD)) - return 0; - - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ERROR) return HA_ERR_INTERNAL_ERROR; // @bug 3005 - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE && - string(table->s->table_name.str).find("$vtable") != 0) + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE && + string(table->s->table_name.str).find("$vtable") != 0) + return HA_ERR_END_OF_FILE; + if ( ((thd->lex)->sql_command == SQLCOM_UPDATE) || ((thd->lex)->sql_command == SQLCOM_DELETE) || ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI) || ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI)) return HA_ERR_END_OF_FILE; - if (((thd->lex)->sql_command == SQLCOM_UPDATE) || ((thd->lex)->sql_command == SQLCOM_DELETE) || - ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI) || ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI)) - return HA_ERR_END_OF_FILE; - + // @bug 2547 if (thd->infinidb_vtable.impossibleWhereOnUnion) return HA_ERR_END_OF_FILE; - - // @bug 2232. Basic SP support + + // @bug 2232. Basic SP support // @bug 3939. Only error out for sp with select. Let pass for alter table in sp. if (thd->infinidb_vtable.call_sp && (thd->lex)->sql_command != SQLCOM_ALTER_TABLE) - { - setError(thd, HA_ERR_UNSUPPORTED, "This stored procedure syntax is not supported by InfiniDB in this version"); - thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; - return HA_ERR_INTERNAL_ERROR; - } - + { + setError(thd, HA_ERR_UNSUPPORTED, "This stored procedure syntax is not supported by InfiniDB in this version"); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; + return HA_ERR_INTERNAL_ERROR; + } + if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + // @bug 3078 if(thd->killed == THD::KILL_QUERY) { @@ -2871,39 +2623,35 @@ int ha_calpont_impl_rnd_next(uchar *buf, TABLE* table) thd->infinidb_vtable.has_limit = false; return 0; } - + if (ci->alterTableState > 0) return HA_ERR_END_OF_FILE; - + cal_table_info ti; ti = ci->tableMap[table]; int rc = HA_ERR_END_OF_FILE; - + if (!ti.tpl_ctx || !ti.tpl_scan_ctx) { - // @bug 2135. Changed wording of error message below. If error already - // set, do not reset. - if (!thd->main_da.is_error()) - { - string emsg = "Cannot open table handle for " + string(table->s->table_name.str) + "."; - setError(thd, HA_ERR_INTERNAL_ERROR, emsg); - } + // @bug 2135. Changed wording of error message below. + string emsg = "Cannot open table handle for " + string(table->s->table_name.str) + "."; + setError(thd, HA_ERR_INTERNAL_ERROR, emsg); CalpontSystemCatalog::removeCalpontSystemCatalog(tid2sid(thd->thread_id)); - return HA_ERR_INTERNAL_ERROR; + return HA_ERR_INTERNAL_ERROR; } - + idbassert(ti.msTablePtr == table); - + try { rc = fetchNextRow(buf, ti, ci); - } catch (std::exception& e) + } catch (...) { - string emsg = string("Lost connection to ExeMgr while fetching: ") + e.what(); + string emsg = "Lost connection to ExeMgr while fetching."; setError(thd, HA_ERR_INTERNAL_ERROR, emsg); CalpontSystemCatalog::removeCalpontSystemCatalog(tid2sid(thd->thread_id)); - return HA_ERR_INTERNAL_ERROR; + return HA_ERR_INTERNAL_ERROR; } ci->tableMap[table] = ti; - + if (rc != 0 && rc != HA_ERR_END_OF_FILE) { string emsg; @@ -2916,10 +2664,9 @@ int ha_calpont_impl_rnd_next(uchar *buf, TABLE* table) emsg = errorcodes.errorString(rc); } setError(thd, HA_ERR_INTERNAL_ERROR, emsg); - //setError(thd, HA_ERR_INTERNAL_ERROR, "testing"); ci->stats.fErrorNo = rc; CalpontSystemCatalog::removeCalpontSystemCatalog(tid2sid(thd->thread_id)); - rc = HA_ERR_INTERNAL_ERROR; + rc = HA_ERR_INTERNAL_ERROR; } return rc; @@ -2930,22 +2677,10 @@ int ha_calpont_impl_rnd_end(TABLE* table) int rc = 0; THD* thd = current_thd; cal_connection_info* ci = NULL; - - if (thd->slave_thread && ( - thd->lex->sql_command == SQLCOM_INSERT || - thd->lex->sql_command == SQLCOM_INSERT_SELECT || - thd->lex->sql_command == SQLCOM_UPDATE || - thd->lex->sql_command == SQLCOM_UPDATE_MULTI || - thd->lex->sql_command == SQLCOM_DELETE || - thd->lex->sql_command == SQLCOM_DELETE_MULTI || - thd->lex->sql_command == SQLCOM_TRUNCATE || - thd->lex->sql_command == SQLCOM_LOAD)) - return 0; - - + if (thd->infinidb_vtable.cal_conn_info) - ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ORDER_BY ) { thd->infinidb_vtable.vtable_state = THD::INFINIDB_SELECT_VTABLE; // flip back to normal state @@ -2953,18 +2688,18 @@ int ha_calpont_impl_rnd_end(TABLE* table) } if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_PHASE1 && thd->infinidb_vtable.mysql_optimizer_off) return rc; - + if ( (thd->lex)->sql_command == SQLCOM_ALTER_TABLE ) return rc; + + if ( ((thd->lex)->sql_command == SQLCOM_UPDATE) || + ((thd->lex)->sql_command == SQLCOM_DELETE) || + ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI) || + ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI)) + return rc; - if (((thd->lex)->sql_command == SQLCOM_UPDATE) || - ((thd->lex)->sql_command == SQLCOM_DELETE) || - ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI) || - ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI)) - return rc; - - if (((thd->lex)->sql_command == SQLCOM_INSERT) || - ((thd->lex)->sql_command == SQLCOM_INSERT_SELECT) ) + if ( ((thd->lex)->sql_command == SQLCOM_INSERT) || + ((thd->lex)->sql_command == SQLCOM_INSERT_SELECT) ) { // @bug 4022. error handling for select part of dml if (ci->cal_conn_hndl && ci->rc) @@ -2985,18 +2720,15 @@ int ha_calpont_impl_rnd_end(TABLE* table) return rc; } } - + if (!ci) { thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); } - - // @bug 3078. Also session limit variable works the same as ctrl+c - if (thd->killed == THD::KILL_QUERY || - ((thd->lex)->sql_command != SQLCOM_INSERT && - (thd->lex)->sql_command != SQLCOM_INSERT_SELECT && - thd->variables.select_limit != (uint64_t)-1)) + + // @bug 3078 + if(thd->killed == THD::KILL_QUERY) { if (ci->cal_conn_hndl) { @@ -3008,34 +2740,32 @@ int ha_calpont_impl_rnd_end(TABLE* table) ci->cal_conn_hndl->exeMgr->write(msg); } catch (...) { - // this is the end of query. Ignore the exception if exemgr connection failed + // this is the end of query. Ignore the exception if exemgr connection failed // for whatever reason. } sm::sm_cleanup(ci->cal_conn_hndl); ci->cal_conn_hndl = 0; - // clear querystats because no query stats available for cancelled query - ci->queryStats = ""; } thd->infinidb_vtable.has_limit = false; return 0; } - + IDEBUG( cerr << "rnd_end for table " << table->s->table_name.str << endl ); cal_table_info ti = ci->tableMap[table]; sm::cpsm_conhdl_t* hndl; - + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) hndl = ti.conn_hndl; else - hndl = ci->cal_conn_hndl; - + hndl = ci->cal_conn_hndl; + if (ti.tpl_ctx) { if (ti.tpl_scan_ctx.get()) { try { - sm::tpl_scan_close(ti.tpl_scan_ctx); + sm::tpl_scan_close(ti.tpl_scan_ctx, hndl); } catch (...) { rc = HA_ERR_INTERNAL_ERROR; } @@ -3043,7 +2773,7 @@ int ha_calpont_impl_rnd_end(TABLE* table) ti.tpl_scan_ctx.reset(); try { sm::tpl_close(ti.tpl_ctx, &hndl, ci->stats); - // set conn hndl back. could be changed in tpl_close + // @bug5054. set conn hndl back. could be changed in tpl_close if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) ti.conn_hndl = hndl; else @@ -3057,49 +2787,38 @@ int ha_calpont_impl_rnd_end(TABLE* table) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, msg.c_str()); } else - { + { setError(thd, HA_ERR_INTERNAL_ERROR, e.what()); rc = HA_ERR_INTERNAL_ERROR; } } - catch (std::exception& e) { - setError(thd, HA_ERR_INTERNAL_ERROR, e.what()); - rc = HA_ERR_INTERNAL_ERROR; - } - catch (...) - { - setError(thd, HA_ERR_INTERNAL_ERROR, "Internal error throwed in rnd_end"); + catch (...) { rc = HA_ERR_INTERNAL_ERROR; } } ti.tpl_ctx = 0; - - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE && + + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE && thd->infinidb_vtable.has_order_by) thd->infinidb_vtable.vtable_state = THD::INFINIDB_ORDER_BY; - + ci->tableMap[table] = ti; - + // push warnings from CREATE phase if (!ci->warningMsg.empty()) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, ci->warningMsg.c_str()); ci->warningMsg.clear(); - // reset expressionId just in case - ci->expressionId = 0; + return rc; } int ha_calpont_impl_create(const char *name, TABLE *table_arg, HA_CREATE_INFO *create_info) { THD *thd = current_thd; + if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - - // @bug1940 Do nothing for select query. Support of set default engine to IDB. - if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE || - string(name).find("@0024vtable") != string::npos) - return 0; + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); //@Bug 1948. Mysql calls create table to create a new table with new signature. if (ci->alterTableState > 0) return 0; @@ -3110,34 +2829,26 @@ int ha_calpont_impl_create(const char *name, TABLE *table_arg, HA_CREATE_INFO *c } int ha_calpont_impl_delete_table(const char *name) -{ +{ //if this is an InfiniDB tmp table ('#sql*.frm') just leave... - if (!memcmp((uchar*)name, tmp_file_prefix, tmp_file_prefix_length)) return 0; + if (!bcmp((uchar*)name, tmp_file_prefix, tmp_file_prefix_length)) return 0; THD *thd = current_thd; - // @bug1940 Do nothing for select query. Support of set default engine to IDB. - if (string(name).find("@0024vtable") != string::npos) - return 0; - - if (!thd->infinidb_vtable.cal_conn_info) - thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - if (!thd) return 0; if (!thd->lex) return 0; - if (!idb_mysql_query_str(thd)) return 0; + if (!thd->query) return 0; - // @bug 1700. + // @bug 1700. if (thd->lex->sql_command == SQLCOM_DROP_DB) { - thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Non-empty database can not be dropped. "); - return 1; + thd->main_da.can_overwrite_status = true; + thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Non-empty database can not be dropped. "); + return 1; } - + TABLE_LIST *first_table= (TABLE_LIST*) thd->lex->select_lex.table_list.first; - + // should never get in here if (!first_table) { @@ -3146,9 +2857,13 @@ int ha_calpont_impl_delete_table(const char *name) } if (!(first_table->table && first_table->table->s && first_table->table->s->db.str)) return 0; - + string db = first_table->table->s->db.str; + if (!thd->infinidb_vtable.cal_conn_info) + thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + if (!ci) return 0; //@Bug 1948,2306. if alter table want to drop the old table, InfiniDB does not need to drop. @@ -3157,9 +2872,9 @@ int ha_calpont_impl_delete_table(const char *name) return 0; } // @bug 1793. make vtable droppable in calpontsys. "$vtable" ==> "@0024vtable" passed in as name. - if (db == "calpontsys" && string(name).find("@0024vtable") == string::npos) + if (db == "calpontsys" && string(name).find("@0024vtable") == string::npos) { - std::string stmt(idb_mysql_query_str(thd)); + std::string stmt(thd->query); algorithm::to_upper(stmt); //@Bug 2432. systables can be dropped with restrict if (stmt.find(" RESTRICT") != string::npos) @@ -3176,9 +2891,9 @@ int ha_calpont_impl_delete_table(const char *name) int ha_calpont_impl_write_row(uchar *buf, TABLE* table) { THD *thd = current_thd; - //sleep(100); + // Error out INSERT on VIEW. It's currently not supported. - // @note INSERT on VIEW works natually (for simple cases at least), but we choose to turn it off + // @note INSERT on VIEW works natually (for simple cases at least), but we choose to turn it off // for now - ZZ. TABLE_LIST* tables = thd->lex->query_tables; for (; tables; tables= tables->next_local) @@ -3192,41 +2907,27 @@ int ha_calpont_impl_write_row(uchar *buf, TABLE* table) return HA_ERR_UNSUPPORTED; } } - + if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - - if (thd->slave_thread) return 0; - - - - if (ci->alterTableState > 0) return 0; - ha_rows rowsInserted = 0; - int rc = 0; - - if ( (ci->useCpimport > 0) && (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) && (!ci->singleInsert) && ((ci->isLoaddataInfile) || - ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || - ((thd->lex)->sql_command == SQLCOM_INSERT_SELECT)) ) - { - rc = ha_calpont_impl_write_batch_row_(buf, table, *ci); - } - else + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + + if ( !ci->dmlProc ) { - if ( !ci->dmlProc ) - { - ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "write_row starts a client " << ci->dmlProc << " for session " << thd->thread_id << endl; - } - - rc = ha_calpont_impl_write_row_(buf, table, *ci, rowsInserted); - + ci->dmlProc = new MessageQueueClient("DMLProc"); + //cout << "test007: ha_calpont_impl_write_row use new DMLProc client " <dmlProc << " for session " << current_thd->thread_id << endl; } - + + if (ci->alterTableState > 0) return 0; + ha_rows rowsInserted = 0; + int rc = ha_calpont_impl_write_row_(buf, table, *ci, rowsInserted); + //@Bug 2438 Added a variable rowsHaveInserted to keep track of how many rows have been inserted already. if ( !ci->singleInsert && ( rc == 0 ) && ( rowsInserted > 0 )) { ci->rowsHaveInserted += rowsInserted; +// if ( ( ci->bulkInsertRows > 0 ) && ( ci->rowsHaveInserted >= ci->bulkInsertRows ) ) +// ci->rowsHaveInserted = 0; //reset this variable } return rc; } @@ -3235,7 +2936,7 @@ int ha_calpont_impl_update_row() { //@Bug 2540. Return the correct error code. THD *thd = current_thd; - + if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); @@ -3249,14 +2950,14 @@ int ha_calpont_impl_delete_row() { //@Bug 2540. Return the correct error code. THD *thd = current_thd; - + if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); int rc = ci->rc; if ( rc !=0 ) ci->rc = 0; - + return ( rc ); } @@ -3268,42 +2969,28 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); // clear rows variable - ci->rowsHaveInserted = 0; - - if (ci->alterTableState > 0) return; - - if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_ALTER_VTABLE) - thd->infinidb_vtable.isInfiniDBDML = true; + ci->rowsHaveInserted = 0; //reset this variable - if (thd->slave_thread) return; - - //@bug 5660. Error out DDL/DML on slave node, or on local query node - if (ci->isSlaveNode && thd->infinidb_vtable.vtable_state != THD::INFINIDB_ALTER_VTABLE) - { - string emsg = logging::IDBErrorInfo::instance()->errorMsg(ERR_DML_DDL_SLAVE); - setError(current_thd, HA_ERR_UNSUPPORTED, emsg); - return; - } - //@bug 4771. reject REPLACE key word + if (ci->alterTableState > 0) return; + + //@bug 4771. reject REPLACE key wordd if ((thd->lex)->sql_command == SQLCOM_REPLACE_SELECT) { setError(current_thd, HA_ERR_GENERIC, "REPLACE statement is not supported in infinidb."); } - - boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(tid2sid(thd->thread_id)); - csc->identity(execplan::CalpontSystemCatalog::FE); - //@Bug 2515. + + //@Bug 2515. //Check command instead of vtable state - if ((thd->lex)->sql_command == SQLCOM_INSERT) + if ((thd->lex)->sql_command == SQLCOM_INSERT) { - string insertStmt = idb_mysql_query_str(thd); + string insertStmt = thd->query; algorithm::to_lower(insertStmt); string intoStr("into"); size_t found = insertStmt.find(intoStr); if (found != string::npos) insertStmt.erase(found); - + found = insertStmt.find("ignore"); if (found!=string::npos) { @@ -3317,378 +3004,22 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) } else if ( (thd->lex)->sql_command == SQLCOM_LOAD || (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) { - ci->singleInsert = false; + ci->singleInsert = false; ci->isLoaddataInfile = true; } ci->bulkInsertRows = rows; - if ((((thd->lex)->sql_command == SQLCOM_INSERT) || - ((thd->lex)->sql_command == SQLCOM_LOAD) || - (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) && !ci->singleInsert ) - { - ci->useCpimport = thd->variables.infinidb_use_import_for_batchinsert; - - if (((thd->lex)->sql_command == SQLCOM_INSERT) && (rows > 0)) - ci->useCpimport = 0; - - if ((ci->useCpimport > 0) && (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))) //If autocommit on batch insert will use cpimport to load data - { - //store table info to connection info - CalpontSystemCatalog::TableName tableName; - tableName.schema = table->s->db.str; - tableName.table = table->s->table_name.str; - ci->useXbit = false; - ci->utf8 = false; - CalpontSystemCatalog::RIDList colrids; - try { - colrids = csc->columnRIDs(tableName); - } - catch (IDBExcept &ie) { - setError(thd, HA_ERR_NO_SUCH_TABLE, ie.what()); - ci->rc = 5; - ci->singleInsert = true; - return; - } - //@bug 6122 Check how many columns have not null constraint. columnn with not null constraint will not show up in header. - unsigned int numberNotNull = 0; - for (unsigned int j = 0; j < colrids.size(); j++) - { - CalpontSystemCatalog::ColType ctype = csc->colType(colrids[j].objnum); - ci->columnTypes.push_back(ctype); - if ((( ctype.colDataType == CalpontSystemCatalog::VARCHAR ) || ( ctype.colDataType == CalpontSystemCatalog::VARBINARY )) && !ci->useXbit ) - ci->useXbit = true; - if (ctype.constraintType == CalpontSystemCatalog::NOTNULL_CONSTRAINT) - numberNotNull++; - } - - // The length of the record header is:(1 + number of columns + 7) / 8 bytes - if (ci->useXbit) - ci->headerLength = (1 + colrids.size() + 7 - 1-numberNotNull) /8; //xbit is used - else - ci->headerLength = (1 + colrids.size() + 7 - numberNotNull) /8; - - if ((strncmp(table->s->table_charset->comment, "UTF-8", 5) == 0) || (strncmp(table->s->table_charset->comment, "utf-8", 5) == 0)) - { - ci->utf8 = true; - } - //Log the statement to debug.log - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("Start SQL statement: "); - ostringstream oss; - oss << idb_mysql_query_str(thd) << "; |" << table->s->db.str<<"|"; - args1.add(oss.str()); - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - - //start process cpimport mode 1 - ci->mysqld_pid = getpid(); - - //get delimiter - if (char(thd->variables.infinidb_import_for_batchinsert_delimiter) != '\7') - ci->delimiter = char(thd->variables.infinidb_import_for_batchinsert_delimiter); - else - ci->delimiter = '\7'; - - //cout << "current set up is usecpimport:delimiter = " << (int)ci->useCpimport<<":"<< ci->delimiter < Cmds; - std::string aCmdLine(startup::StartUp::installDir()); - //If local module type is not PM and Local PM query is set, error out - if (thd->variables.infinidb_local_query > 0 ) - { - OamCache * oamcache = OamCache::makeOamCache(); - int localModuleId = oamcache->getLocalPMId(); - if (localModuleId == 0) - { - setError(current_thd, HA_ERR_UNSUPPORTED, logging::IDBErrorInfo::instance()->errorMsg(ERR_LOCAL_QUERY_UM)); - ci->singleInsert = true; - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("End SQL statement"); - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - return; - } - else - { -#ifdef _MSC_VER - aCmdLine = aCmdLine + "/bin/cpimport.exe -N -P " + to_string(localModuleId)+ " -s " + ci->delimiter + " -e 0 "; -#else - aCmdLine = aCmdLine + "/bin/cpimport -m 1 -N -P " + to_string(localModuleId)+ " -s " + ci->delimiter + " -e 0 "; -#endif - } - } - else - { -#ifdef _MSC_VER - aCmdLine = aCmdLine + "/bin/cpimport.exe -N -s " + ci->delimiter + " -e 0 "; -#else - aCmdLine = aCmdLine + "/bin/cpimport -m 1 -N -s " + ci->delimiter + " -e 0 "; -#endif - } - aCmdLine = aCmdLine + table->s->db.str + " " + table->s->table_name.str ; - - //cout << "aCmdLine = " << aCmdLine << endl; - std::istringstream ss(aCmdLine); - std::string arg; - std::vector v2; - while (ss >> arg) - { - v2.push_back(arg); - Cmds.push_back(const_cast(v2.back().c_str())); - } - - Cmds.push_back(0); //null terminate - -#ifdef _MSC_VER - BOOL bSuccess = false; - BOOL bInitialized = false; - SECURITY_ATTRIBUTES saAttr; - saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = NULL; - HANDLE handleList[2]; - const char* pSectionMsg; - // Create a pipe for the child process's STDOUT. -#if 0 // We don't need stdout to come back right now. - pSectionMsg = "Create Stdout"; - bSuccess = CreatePipe(&ci->cpimport_stdout_Rd, &ci->cpimport_stdout_Wr, &saAttr, 0); - // Ensure the read handle to the pipe for STDIN is not inherited. - if (bSuccess) - { - pSectionMsg = "SetHandleInformation(stdout)"; - bSuccess = SetHandleInformation(ci->cpimport_stdout_Rd, HANDLE_FLAG_INHERIT, 0); - } -#endif - bSuccess = true; - // Create a pipe for the child process's STDIN. - if (bSuccess) - { - pSectionMsg = "Create Stdin"; - bSuccess = CreatePipe(&ci->cpimport_stdin_Rd, &ci->cpimport_stdin_Wr, &saAttr, 65536); - // Ensure the write handle to the pipe for STDIN is not inherited. - if (bSuccess) - { - pSectionMsg = "SetHandleInformation(stdin)"; - bSuccess = SetHandleInformation(ci->cpimport_stdin_Wr, HANDLE_FLAG_INHERIT, 0); - } - } - // Launch cpimport - LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList = NULL; - SIZE_T attrSize = 0; - STARTUPINFOEX siStartInfo; - // To ensure the child only inherits the STDIN and STDOUT Handles, we add a list of - // Handles that can be inherited to the call to CreateProcess - if (bSuccess) - { - pSectionMsg = "InitializeProcThreadAttributeList(NULL)"; - bSuccess = InitializeProcThreadAttributeList(NULL, 1, 0, &attrSize) || - GetLastError() == ERROR_INSUFFICIENT_BUFFER; // Asks how much buffer to alloc - } - if (bSuccess) - { - pSectionMsg = "HeapAlloc for AttrList"; - lpAttributeList = reinterpret_cast - (HeapAlloc(GetProcessHeap(), 0, attrSize)); - bSuccess = lpAttributeList != NULL; - } - if (bSuccess) - { - pSectionMsg = "InitializeProcThreadAttributeList"; - bSuccess = InitializeProcThreadAttributeList(lpAttributeList, 1, 0, &attrSize); - } - if (bSuccess) - { - pSectionMsg = "UpdateProcThreadAttribute"; - bInitialized = true; - handleList[0] = ci->cpimport_stdin_Rd; -// handleList[1] = ci->cpimport_stdout_Wr; - bSuccess = UpdateProcThreadAttribute(lpAttributeList, - 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, -// handleList, 2*sizeof(HANDLE), NULL, NULL); - handleList, sizeof(HANDLE), NULL, NULL); - } - if (bSuccess) - { - pSectionMsg = "CreateProcess"; - // In order for GenerateConsoleCtrlEvent (used when job is canceled) to work, - // this process must have a Console, which Services don't have. We create this - // when we create the child process. Once created, we leave it around for next time. - // AllocConsole will silently fail if it already exists, so no pain. - AllocConsole(); - // Set up members of the PROCESS_INFORMATION structure. - memset(&ci->cpimportProcInfo, 0, sizeof(PROCESS_INFORMATION)); - - // Set up members of the STARTUPINFOEX structure. - // This structure specifies the STDIN and STDOUT handles for redirection. - memset(&siStartInfo, 0, sizeof(STARTUPINFOEX)); - siStartInfo.StartupInfo.cb = sizeof(STARTUPINFOEX); - siStartInfo.lpAttributeList = lpAttributeList; - siStartInfo.StartupInfo.hStdError = NULL; - siStartInfo.StartupInfo.hStdOutput = NULL; -// siStartInfo.StartupInfo.hStdError = ci->cpimport_stdout_Wr; -// siStartInfo.StartupInfo.hStdOutput = ci->cpimport_stdout_Wr; - siStartInfo.StartupInfo.hStdInput = ci->cpimport_stdin_Rd; - siStartInfo.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; - // Create the child process. - bSuccess = CreateProcess(NULL, // program. NULL means use command line - const_cast(aCmdLine.c_str()), // command line - NULL, // process security attributes - NULL, // primary thread security attributes - TRUE, // handles are inherited - EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_PROCESS_GROUP, // creation flags - NULL, // use parent's environment - NULL, // use parent's current directory - &siStartInfo.StartupInfo, // STARTUPINFO pointer - &ci->cpimportProcInfo); // receives PROCESS_INFORMATION - - } - // We need to clean up the memory created by InitializeProcThreadAttributeList - // and HeapAlloc - if (bInitialized) - DeleteProcThreadAttributeList(lpAttributeList); - if (lpAttributeList) - HeapFree(GetProcessHeap(), 0, lpAttributeList); - - if (!bSuccess) - { - // If an error occurs, Log and return. - int errnum = GetLastError(); - char errmsg[512]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errnum, 0, errmsg, 512, NULL); - ostringstream oss; - oss <<" : Error in " << pSectionMsg << " (errno-" << - errnum << "); " << errmsg; - setError(current_thd, HA_ERR_GENERIC, oss.str()); - ci->singleInsert = true; - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1, args2; - logging::Message emsg(1), msg(1); - args1.add(oss.str()); - emsg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_ERROR, emsg, logid); - args2.add("End SQL statement"); - msg.format( args2 ); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - return; - } - // Close the read handle that the child is using. We won't be needing this. - CloseHandle(ci->cpimport_stdin_Rd); - // The write functions all want a FILE* - ci->fdt[1] = _open_osfhandle((intptr_t)ci->cpimport_stdin_Wr, _O_APPEND); - ci->filePtr = _fdopen(ci->fdt[1], "w"); -#else - long maxFD = -1; - maxFD = sysconf(_SC_OPEN_MAX); - if(pipe(ci->fdt)== -1) - { - int errnum = errno; - ostringstream oss; - oss <<" : Error in creating pipe (errno-" << - errnum << "); " << strerror(errnum); - setError(current_thd, HA_ERR_GENERIC, oss.str()); - ci->singleInsert = true; - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("End SQL statement"); - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - return; - } - //cout << "maxFD = " << maxFD <singleInsert = true; - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("End SQL statement"); - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - return; - } - else if(aChPid == 0)// we are in child - { - for(int i=0;i< maxFD;i++) - { - if (i != ci->fdt[0]) - close(i); - } - errno = 0; - if (dup2(ci->fdt[0], 0) < 0) //make stdin be the reading end of the pipe - { - setError(current_thd, HA_ERR_GENERIC, "dup2 failed"); - ci->singleInsert = true; - exit (1); - } - close(ci->fdt[0]); // will trigger an EOF on stdin - ci->fdt[0] = -1; - open("/dev/null", O_WRONLY); - open("/dev/null", O_WRONLY); - errno = 0; - execv(Cmds[0], &Cmds[0]); //NOTE - works with full Path - - int execvErrno = errno; - - ostringstream oss; - oss << " : execv error: cpimport.bin invocation failed; " - << "(errno-" << errno << "); " << strerror(execvErrno) << - "; Check file and try invoking locally."; - cout << oss.str(); - - setError(current_thd, HA_ERR_GENERIC, "Forking process cpimport failed."); - ci->singleInsert = true; - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("End SQL statement"); - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - exit(1); - } - else // parent - { - ci->filePtr = fdopen(ci->fdt[1], "w"); - ci->cpimport_pid = aChPid; // This is the child PID - //cout << "Child PID is " << aChPid << endl; - close(ci->fdt[0]); //close the READER of PARENT - ci->fdt[0] = -1; - // now we can send all the data thru FIFO[1], writer of PARENT - } - - //if(aChPid == 0) - //cout << "******** Child finished its work ********" << endl; -#endif - } - else + if ( ( ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) && !ci->singleInsert ) + { + if ( !ci->dmlProc ) { - if(!ci->dmlProc) - { - ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "start_bulk_insert starts a client " << ci->dmlProc << " for session " << thd->thread_id << endl; - } - } - } - + ci->dmlProc = new MessageQueueClient("DMLProc"); + //cout << "test007: ha_calpont_impl_start_bulk_insert use new DMLProc client " <dmlProc << " for session " << current_thd->thread_id << endl; + } + } + //Save table oid for commit to use - if ( ( ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) ) + if ( ( ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) ) { // query stats. only collect execution time and rows inserted for insert/load_data_infile ci->stats.reset(); @@ -3701,7 +3032,7 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) else ci->stats.fHost = "unknown"; ci->stats.fSessionID = thd->thread_id; - ci->stats.fQuery = idb_mysql_query_str(thd); + ci->stats.fQuery = thd->query; try { ci->stats.userPriority(ci->stats.fHost, ci->stats.fUser); } catch (std::exception& e) @@ -3714,7 +3045,7 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) ci->stats.fQueryType = CalpontSelectExecutionPlan::queryTypeToString(CalpontSelectExecutionPlan::INSERT); else if ((thd->lex)->sql_command == SQLCOM_LOAD) ci->stats.fQueryType = CalpontSelectExecutionPlan::queryTypeToString(CalpontSelectExecutionPlan::LOAD_DATA_INFILE); - + //@Bug 4387. Check BRM status before start statement. scoped_ptr dbrmp(new DBRM()); int rc = dbrmp->isReadWrite(); @@ -3722,10 +3053,11 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) { setError(current_thd, HA_ERR_GENERIC, "Cannot execute the statement. DBRM is read only!"); ci->rc = rc; - ci->singleInsert = true; return; } - + + boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(tid2sid(thd->thread_id)); + csc->identity(execplan::CalpontSystemCatalog::FE); CalpontSystemCatalog::TableName tableName; tableName.schema = table->s->db.str; tableName.table = table->s->table_name.str; @@ -3735,7 +3067,7 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) } catch (IDBExcept &ie) { setError(thd, HA_ERR_NO_SUCH_TABLE, - ie.what()); + ie.what()); } catch (std::exception& ex) { setError(thd, HA_ERR_GENERIC, @@ -3749,204 +3081,45 @@ void ha_calpont_impl_start_bulk_insert(ha_rows rows, TABLE* table) int ha_calpont_impl_end_bulk_insert(bool abort, TABLE* table) -{ +{ THD *thd = current_thd; if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - - if (thd->slave_thread) return 0; - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + int rc = 0; if (ci->rc == 5) //read only dbrm return rc; - - // @bug 2378. do not enter for select, reset singleInsert flag after multiple insert. - // @bug 2515. Check command intead of vtable state - if ( ( ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) && !ci->singleInsert ) + // @bug 2378. do not enter for select, reset singleInsert flag after multiple insert. + //@bug 2515. Check command intead of vtable state + if ( ( ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || (thd->lex)->sql_command == SQLCOM_INSERT_SELECT) && !ci->singleInsert ) { + if ( !ci->dmlProc ) + { + ci->dmlProc = new MessageQueueClient("DMLProc"); + //cout << "test007: ha_calpont_impl_end_bulk_insert use new DMLProc client " <dmlProc << " for session " << current_thd->thread_id << endl; + } //@Bug 2438. Only load dta infile calls last batch process -/* if ( ci->isLoaddataInfile && ((thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) || (ci->useCpimport == 0))) { + if ( ci->isLoaddataInfile ) { + //cout << "calling ha_calpont_impl_write_last_batch" << endl; //@Bug 2829 Handle ctrl-C if ( thd->killed > 0 ) abort = true; - if ( !ci->dmlProc ) - { - ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "end_bulk_insert starts a client " << ci->dmlProc << " for session " << thd->thread_id << endl; - } rc = ha_calpont_impl_write_last_batch(table, *ci, abort); + //ci->rowsHaveInserted = 0; } - else if ((ci->useCpimport > 0) && (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) && (!ci->singleInsert) && ((ci->isLoaddataInfile) || - } */ - if ((ci->useCpimport > 0) && (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) && (!ci->singleInsert) && ((ci->isLoaddataInfile) || - ((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD) || - ((thd->lex)->sql_command == SQLCOM_INSERT_SELECT)) ) - { -#ifdef _MSC_VER - if (thd->killed > 0) - { - errno = 0; - // GenerateConsoleCtrlEvent sends a signal to cpimport - BOOL brtn = GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, ci->cpimportProcInfo.dwProcessId); - if (!brtn) - { - int errnum = GetLastError(); - char errmsg[512]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errnum, 0, errmsg, 512, NULL); - ostringstream oss; - oss <<"GenerateConsoleCtrlEvent: (errno-" << errnum << "); " << errmsg; - LoggingID logid( 24, 0, 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add(oss.str()); - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - } - // Close handles to the cpimport process and its primary thread. - fclose (ci->filePtr); - ci->filePtr = 0; - ci->fdt[1] = -1; - CloseHandle(ci->cpimportProcInfo.hProcess); - CloseHandle(ci->cpimportProcInfo.hThread); - WaitForSingleObject(ci->cpimportProcInfo.hProcess, INFINITE); - } -#else - if ( (thd->killed > 0) && (ci->cpimport_pid > 0) ) //handle CTRL-C - { - //cout << "sending ctrl-c to cpimport" << endl; - errno = 0; - kill( ci->cpimport_pid, SIGUSR1 ); - fclose (ci->filePtr); - ci->filePtr = 0; - ci->fdt[1] = -1; - int aStatus; - waitpid(ci->cpimport_pid, &aStatus, 0); // wait until cpimport finishs - } -#endif - else - { - //tear down cpimport -#ifdef _MSC_VER - fclose (ci->filePtr); - ci->filePtr = 0; - ci->fdt[1] = -1; - DWORD exitCode; - WaitForSingleObject(ci->cpimportProcInfo.hProcess, INFINITE); - GetExitCodeProcess(ci->cpimportProcInfo.hProcess, &exitCode); - if (exitCode != 0) - { - rc = 1; - setError(thd, HA_ERR_INTERNAL_ERROR, "load failed. The detailed error information is listed in InfiniDBLog.txt."); - } - // Close handles to the cpimport process and its primary thread. - CloseHandle(ci->cpimportProcInfo.hProcess); - CloseHandle(ci->cpimportProcInfo.hThread); -#else - fclose (ci->filePtr); - ci->filePtr = 0; - ci->fdt[1] = -1; - int aStatus; - pid_t aPid = waitpid(ci->cpimport_pid, &aStatus, 0); // wait until cpimport finishs - if ((aPid == ci->cpimport_pid)|| (aPid == -1)) - { - ci->cpimport_pid = 0; - - if ((WIFEXITED(aStatus)) && (WEXITSTATUS(aStatus) == 0)) - { - //cout << "\tCpimport exit on success" << endl; - } - else - { - if (WEXITSTATUS(aStatus) == 2) - { - rc = 1; - ifstream dmlFile; - ostringstream oss; - oss << "/tmp/" <tableOid << ".txt"; - dmlFile.open(oss.str().c_str()); - if (dmlFile.is_open()) - { - string line; - getline(dmlFile, line); - setError(thd, HA_ERR_INTERNAL_ERROR, line); - dmlFile.close(); - remove (oss.str().c_str()); - } - } - else - { - rc = 1; - ifstream dmlFile; - ostringstream oss; - oss << "/tmp/" <tableOid << ".txt"; - dmlFile.open(oss.str().c_str()); - if (dmlFile.is_open()) - { - string line; - getline(dmlFile, line); - setError(thd, HA_ERR_INTERNAL_ERROR, line); - dmlFile.close(); - remove (oss.str().c_str()); - } - else - setError(thd, HA_ERR_INTERNAL_ERROR, "load failed. The detailed error information is listed in err.log."); - } - } - } -#endif - LoggingID logid( 24, tid2sid(thd->thread_id), 0); - logging::Message::Args args1; - logging::Message msg(1); - if ( rc == 0) - args1.add("End SQL statement"); - else - args1.add("End SQL statement with error"); - - msg.format( args1 ); - Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - ci->columnTypes.clear(); - //get extra warning count if any - ifstream dmlFile; - ostringstream oss; - oss << "/tmp/" <tableOid << ".txt"; - dmlFile.open(oss.str().c_str()); - int totalWarnCount = 0; - int colWarns = 0; - string line; - if (dmlFile.is_open()) - { - while (getline(dmlFile, line)) - { - colWarns = atoi(line.c_str()); - totalWarnCount += colWarns; - } - dmlFile.close(); - remove (oss.str().c_str()); - for (int i=0; i < totalWarnCount; i++) - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, "Values saturated"); - } - } - } - else + + if ( (ci->rc != 0) && ((thd->lex)->sql_command == SQLCOM_INSERT) && !ci->singleInsert && ( ci->rowsHaveInserted < ci->bulkInsertRows ) ) { if ( thd->killed > 0 ) abort = true; - if ( !ci->dmlProc ) - { - ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "end_bulk_insert starts a client " << ci->dmlProc << " for session " << thd->thread_id << endl; - } - if (((thd->lex)->sql_command == SQLCOM_INSERT_SELECT) || ((thd->lex)->sql_command == SQLCOM_LOAD)) - rc = ha_calpont_impl_write_last_batch(table, *ci, abort); - } + rc = ha_calpont_impl_write_last_batch(table, *ci, abort); + } } - - // populate query stats for insert and load data infile. insert select has + + // populate query stast for insert and load data infile. insert select has // stats entered in sm already if (((thd->lex)->sql_command == SQLCOM_INSERT) || ((thd->lex)->sql_command == SQLCOM_LOAD)) { @@ -3964,36 +3137,35 @@ int ha_calpont_impl_end_bulk_insert(bool abort, TABLE* table) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, msg.c_str()); } } - - if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))){ + + if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))){ ci->singleInsert = true; // reset the flag ci->isLoaddataInfile = false; ci->tableOid = 0; ci->rowsHaveInserted = 0; - ci->useCpimport = 1; } - return rc; + return rc; } int ha_calpont_impl_commit (handlerton *hton, THD *thd, bool all) { if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + if (ci->isAlter) return 0; - + //@Bug 5823 check if any active transaction for this session - scoped_ptr dbrmp(new DBRM()); - BRM::TxnID txnId = dbrmp->getTxnID(tid2sid(thd->thread_id)); - if (!txnId.valid) - return 0; + scoped_ptr dbrmp(new DBRM()); + BRM::TxnID txnId = dbrmp->getTxnID(tid2sid(thd->thread_id)); + if (!txnId.valid) + return 0; if ( !ci->dmlProc ) { ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "commit starts a client " << ci->dmlProc << " for session " << thd->thread_id << endl; + //cout << "test007: ha_calpont_impl_commit use new DMLProc client " <dmlProc << " for session " << current_thd->thread_id << endl; } int rc = ha_calpont_impl_commit_(hton, thd, all, *ci); @@ -4009,7 +3181,7 @@ int ha_calpont_impl_rollback (handlerton *hton, THD *thd, bool all) { // @bug 1738. no need to rollback for select. This is to avoid concurrent session // conflict because DML is not thread safe. - //comment out for bug 3874. Select should never come to rollback. If there is no active transaction, + //comment out for bug 3874. Select should never come to rollback. If there is no active transaction, //rollback in DMLProc is not doing anything anyway //if (!(current_thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) //{ @@ -4018,14 +3190,14 @@ int ha_calpont_impl_rollback (handlerton *hton, THD *thd, bool all) if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + if ( !ci->dmlProc ) { - + ci->dmlProc = new MessageQueueClient("DMLProc"); - //cout << "rollback starts a client " << ci->dmlProc << " for session " << thd->thread_id << endl; + //cout << "test007: ha_calpont_impl_rollback use new DMLProc client " <dmlProc << " for session " << current_thd->thread_id << endl; } - + int rc = ha_calpont_impl_rollback_(hton, thd, all, *ci); ci->singleInsert = true; // reset the flag ci->isLoaddataInfile = false; @@ -4046,7 +3218,7 @@ int ha_calpont_impl_close_connection (handlerton *hton, THD *thd) if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); if (!ci) return 0; int rc = 0; @@ -4056,9 +3228,9 @@ int ha_calpont_impl_close_connection (handlerton *hton, THD *thd) delete ci->dmlProc; ci->dmlProc = NULL; } - + if (ci->cal_conn_hndl) - { + { sm::sm_cleanup(ci->cal_conn_hndl); ci->cal_conn_hndl = 0; } @@ -4068,13 +3240,16 @@ int ha_calpont_impl_close_connection (handlerton *hton, THD *thd) int ha_calpont_impl_rename_table(const char* from, const char* to) { +//#ifdef INFINIDB_DEBUG +// cout << "ha_calpont_impl_rename_table: " << from << " => " << to << endl; +//#endif IDEBUG( cout << "ha_calpont_impl_rename_table: " << from << " => " << to << endl ); THD *thd = current_thd; if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + //@Bug 1948. Alter table call rename table twice if ( ci->alterTableState == cal_connection_info::ALTER_FIRST_RENAME ) { @@ -4093,12 +3268,12 @@ int ha_calpont_impl_rename_table(const char* from, const char* to) else { #if 0 - thd->main_da.can_overwrite_status = true; + thd->main_da.can_overwrite_status = true; thd->main_da.set_error_status(thd, HA_ERR_UNSUPPORTED, "Syntax is not supported in InfiniDB."); return 1; #endif } - + int rc = ha_calpont_impl_rename_table_(from, to, *ci); return rc; } @@ -4112,39 +3287,31 @@ int ha_calpont_impl_delete_row(const uchar *buf) COND* ha_calpont_impl_cond_push(COND *cond, TABLE* table) { THD *thd = current_thd; - - if (thd->slave_thread && thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT) - thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; - if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE) return cond; - - if (((thd->lex)->sql_command == SQLCOM_UPDATE) || - ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI) || - ((thd->lex)->sql_command == SQLCOM_DELETE) || - ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI)) + + if (((thd->lex)->sql_command == SQLCOM_UPDATE) || ((thd->lex)->sql_command == SQLCOM_UPDATE_MULTI) || ((thd->lex)->sql_command == SQLCOM_DELETE) || ((thd->lex)->sql_command == SQLCOM_DELETE_MULTI)) return cond; IDEBUG( cout << "ha_calpont_impl_cond_push: " << table->alias << endl ); - + if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - - cal_table_info ti = ci->tableMap[table]; - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + + cal_table_info ti = ci->tableMap[table]; + if (!ti.csep) { if (!ti.condInfo) - ti.condInfo = new gp_walk_info(); + ti.condInfo = new gp_walk_info(); gp_walk_info* gwi = ti.condInfo; gwi->dropCond = false; gwi->fatalParseError = false; gwi->condPush = true; - gwi->thd = thd; gwi->sessionid = tid2sid(thd->thread_id); - cond->traverse_cond(gp_walk, gwi, Item::POSTFIX); + cond->traverse_cond(gp_walk, gwi, Item::POSTFIX); ci->tableMap[table] = ti; - + if (gwi->fatalParseError) { IDEBUG( cout << gwi->parseErrorText << endl ); @@ -4160,8 +3327,8 @@ COND* ha_calpont_impl_cond_push(COND *cond, TABLE* table) return cond; else return NULL; - } - + } + return cond; } @@ -4171,19 +3338,18 @@ int ha_calpont_impl_external_lock(THD *thd, TABLE* table, int lock_type) if (thd->lex->sql_command == SQLCOM_LOCK_TABLES) { setError(current_thd, HA_ERR_UNSUPPORTED, - logging::IDBErrorInfo::instance()->errorMsg(ERR_LOCK_TABLE)); + logging::IDBErrorInfo::instance()->errorMsg(ERR_LOCK_TABLE)); return HA_ERR_UNSUPPORTED; } // @info called for every table at the beginning and at the end of a query. // used for cleaning up the tableinfo. IDEBUG( cout << "external_lock for " << table->alias << endl ); - idbassert((thd->infinidb_vtable.vtable_state >= THD::INFINIDB_INIT_CONNECT && - thd->infinidb_vtable.vtable_state <= THD::INFINIDB_REDO_QUERY) || - thd->infinidb_vtable.vtable_state == THD::INFINIDB_ERROR); - if ( thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT ) + idbassert((thd->infinidb_vtable.vtable_state >= THD::INFINIDB_INIT_CONNECT && thd->infinidb_vtable.vtable_state <= THD::INFINIDB_REDO_QUERY) || + thd->infinidb_vtable.vtable_state == THD::INFINIDB_ERROR); + if ( thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT ) //return if not select return 0; - + #ifdef SKIP_INSERT_SELECT if (thd->infinidb_vtable.isInsertSelect) { @@ -4196,8 +3362,8 @@ int ha_calpont_impl_external_lock(THD *thd, TABLE* table, int lock_type) if (!thd->infinidb_vtable.cal_conn_info) thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - + cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); + if(thd->killed == THD::KILL_QUERY) { if (ci->cal_conn_hndl) @@ -4218,10 +3384,10 @@ int ha_calpont_impl_external_lock(THD *thd, TABLE* table, int lock_type) thd->infinidb_vtable.has_limit = false; return 0; } - + CalTableMap::iterator mapiter = ci->tableMap.find(table); #ifdef _MSC_VER - //FIXME: fix this! (must be related to F_UNLCK define in winport) + //FIMEX: fix this! (must be related to F_UNLCK define in winport) if (mapiter != ci->tableMap.end() && lock_type == 0) // make sure it's the release lock (2nd) call #else if (mapiter != ci->tableMap.end() && lock_type == 2) // make sure it's the release lock (2nd) call @@ -4237,29 +3403,26 @@ int ha_calpont_impl_external_lock(THD *thd, TABLE* table, int lock_type) ci->queryStats = mapiter->second.conn_hndl->queryStats; ci->extendedStats = mapiter->second.conn_hndl->extendedStats; ci->miniStats = mapiter->second.conn_hndl->miniStats; - sm::sm_cleanup(mapiter->second.conn_hndl); - mapiter->second.conn_hndl = 0; - } - if (mapiter->second.condInfo) - { - delete mapiter->second.condInfo; - mapiter->second.condInfo = 0; + sm::sm_cleanup((*mapiter).second.conn_hndl); } + (*mapiter).second.conn_hndl = 0; + if ((*mapiter).second.condInfo) + delete (*mapiter).second.condInfo; // only push this warning for once - if (ci->tableMap.size() == 1 && + if (ci->tableMap.size() == 1 && thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE && thd->infinidb_vtable.autoswitch) { push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, infinidb_autoswitch_warning.c_str()); } } else // vtable mode - { + { if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_SELECT_VTABLE) { if (ci->traceFlags & 1) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, 9999, ci->cal_conn_hndl->queryStats.c_str()); - + if (!ci->cal_conn_hndl) return 0; ci->queryStats = ci->cal_conn_hndl->queryStats; @@ -4272,7 +3435,7 @@ int ha_calpont_impl_external_lock(THD *thd, TABLE* table, int lock_type) } ci->tableMap.erase(table); } - + return 0; } @@ -4284,16 +3447,5 @@ int ha_calpont_impl_rnd_pos(uchar *buf, uchar *pos) setError(current_thd, HA_ERR_UNSUPPORTED, emsg); return HA_ERR_UNSUPPORTED; } - -// Called from mysql parser to set IDB error for window functions -void ha_calpont_impl_set_error(THD* thd, uint64_t errCode, LEX_STRING* args, uint32_t argCount) -{ - IDEBUG( cout << "ha_calpont_impl_ser_error" << endl); - Message::Args arguments; - for (uint32_t i = 0; i < argCount; i++) - arguments.add(args[i].str); - string emsg = logging::IDBErrorInfo::instance()->errorMsg(errCode, arguments); - setError(thd, HA_ERR_INTERNAL_ERROR, emsg); -} // vim:sw=4 ts=4: diff --git a/dbcon/mysql/ha_calpont_impl.h b/dbcon/mysql/ha_calpont_impl.h index 469bceb7..dd1fb75e 100644 --- a/dbcon/mysql/ha_calpont_impl.h +++ b/dbcon/mysql/ha_calpont_impl.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: ha_calpont_impl.h 9413 2013-04-22 22:03:42Z zzhu $ + * $Id: ha_calpont_impl.h 8436 2012-04-04 18:18:21Z rdempsey $ */ /** @file */ @@ -29,7 +29,7 @@ #ifdef NEED_CALPONT_EXTERNS extern int ha_calpont_impl_create(const char *name, TABLE *table_arg, HA_CREATE_INFO *create_info); extern int ha_calpont_impl_delete_table(const char *name); -extern int ha_calpont_impl_open(const char *name, int mode, uint32_t test_if_locked); +extern int ha_calpont_impl_open(const char *name, int mode, uint test_if_locked); extern int ha_calpont_impl_close(void); extern int ha_calpont_impl_rnd_init(TABLE* table); extern int ha_calpont_impl_rnd_next(uchar *buf, TABLE* table); @@ -46,7 +46,6 @@ extern int ha_calpont_impl_external_lock(THD *thd, TABLE* table, int lock_type); extern int ha_calpont_impl_update_row(); extern int ha_calpont_impl_delete_row(); extern int ha_calpont_impl_rnd_pos(uchar *buf, uchar *pos); -extern void ha_calpont_impl_set_error(THD* thd, uint64_t errCode, LEX_STRING* args, uint32_t argCount); #endif #ifdef NEED_CALPONT_INTERFACE @@ -54,7 +53,6 @@ extern void ha_calpont_impl_set_error(THD* thd, uint64_t errCode, LEX_STRING* ar #include "calpontsystemcatalog.h" extern int ha_calpont_impl_rename_table_(const char* from, const char* to, cal_impl_if::cal_connection_info& ci); extern int ha_calpont_impl_write_row_(uchar *buf, TABLE* table, cal_impl_if::cal_connection_info& ci, ha_rows& rowsInserted); -extern int ha_calpont_impl_write_batch_row_(uchar *buf,TABLE* table, cal_impl_if::cal_connection_info& ci); extern int ha_calpont_impl_write_last_batch(TABLE* table, cal_impl_if::cal_connection_info& ci, bool abort); extern int ha_calpont_impl_commit_ (handlerton *hton, THD *thd, bool all, cal_impl_if::cal_connection_info& ci); extern int ha_calpont_impl_rollback_ (handlerton *hton, THD *thd, bool all, cal_impl_if::cal_connection_info& ci); diff --git a/dbcon/mysql/ha_calpont_impl_if.h b/dbcon/mysql/ha_calpont_impl_if.h index 995d9f5b..72fad6c2 100644 --- a/dbcon/mysql/ha_calpont_impl_if.h +++ b/dbcon/mysql/ha_calpont_impl_if.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: ha_calpont_impl_if.h 9701 2013-07-17 18:51:55Z zzhu $ +// $Id: ha_calpont_impl_if.h 8984 2012-10-12 21:16:32Z zzhu $ /** @file */ #ifndef HA_CALPONT_IMPL_IF_H__ #define HA_CALPONT_IMPL_IF_H__ @@ -36,14 +36,10 @@ struct st_table; struct st_ha_create_information; -#include "configcpp.h" #include "idberrorinfo.h" #include "calpontselectexecutionplan.h" -#include "windowfunctioncolumn.h" -#include "pseudocolumn.h" #include "querystats.h" #include "sm.h" -#include "functor.h" /** Debug macro */ #if INFINIDB_DEBUG @@ -59,10 +55,6 @@ namespace execplan class SimpleFilter; class AggregateColumn; class FunctionColumn; - class ArithmeticColumn; - class ParseTree; - class ConstantColumn; - class RowColumn; } namespace cal_impl_if @@ -99,13 +91,6 @@ struct gp_walk_info execplan::CalpontSelectExecutionPlan::ReturnedColumnList subGroupByCols; execplan::CalpontSelectExecutionPlan::ReturnedColumnList orderByCols; execplan::CalpontSelectExecutionPlan::ColumnMap columnMap; - // This vector temporarily hold the projection columns to be added - // to the returnedCols vector for subquery processing. It will be appended - // to the end of returnedCols when the processing is finished. - execplan::CalpontSelectExecutionPlan::ReturnedColumnList additionalRetCols; - // the sequence # of the subselect local columns need to be set after - // the additionRetCols are merged to the returnedCols. - std::vector localCols; std::stack rcWorkStack; std::stack ptWorkStack; boost::shared_ptr scsp; @@ -118,9 +103,9 @@ struct gp_walk_info bool condPush; bool dropCond; std::string funcName; + uint expressionId; // for F&E std::vector count_asterisk_list; std::vector no_parm_func_list; - std::vector windowFuncList; TableMap tableMap; boost::shared_ptr csc; int8_t internalDecimalScale; @@ -133,30 +118,21 @@ struct gp_walk_info ClauseType clauseType; execplan::CalpontSystemCatalog::TableAliasName viewName; bool aggOnSelect; - bool hasWindowFunc; - bool hasSubSelect; - SubQuery* lastSub; std::vector viewList; - std::map derivedTbFilterMap; - uint32_t derivedTbCnt; - std::vector subselectList; - - gp_walk_info() : sessionid(0), - fatalParseError(false), - condPush(false), - dropCond(false), - internalDecimalScale(4), - thd(0), - subSelectType(uint64_t(-1)), - subQuery(0), - clauseType(INIT), - aggOnSelect(false), - hasWindowFunc(false), - hasSubSelect(false), - lastSub(0), - derivedTbCnt(0) - {} + gp_walk_info() : sessionid(0), + fatalParseError(false), + condPush(false), + dropCond(false), + expressionId(0), + internalDecimalScale(4), + thd(0), + subSelectType(uint64_t(-1)), + subQuery(0), + clauseType(INIT), + aggOnSelect(false) + { } + ~gp_walk_info() {} }; @@ -165,12 +141,12 @@ struct cal_table_info enum RowSources { FROM_ENGINE, FROM_FILE }; cal_table_info() : tpl_ctx(0), - //tpl_scan_ctx(0), - c(0), - msTablePtr(0), - conn_hndl(0), - condInfo(0), - moreRows(false) + //tpl_scan_ctx(0), + c(0), + msTablePtr(0), + conn_hndl(0), + condInfo(0), + moreRows(false) { } ~cal_table_info() {} sm::cpsm_tplh_t* tpl_ctx; @@ -190,47 +166,9 @@ typedef std::map TableValuesMap; struct cal_connection_info { enum AlterTableState { NOT_ALTER, ALTER_SECOND_RENAME, ALTER_FIRST_RENAME }; - cal_connection_info() : cal_conn_hndl(0), - queryState(0), - currentTable(0), - traceFlags(0), - alterTableState(NOT_ALTER), - isAlter(false), - bulkInsertRows(0), - singleInsert(true), - isLoaddataInfile( false ), - dmlProc(0), - rowsHaveInserted(0), - rc(0), - tableOid(0), - localPm(-1), - isSlaveNode(false), - expressionId(0), - mysqld_pid(getpid()), - cpimport_pid(0), - filePtr(0), - headerLength(0), - useXbit(false), - utf8(false), - useCpimport(1), - delimiter('\7') - { - // check if this is a slave mysql daemon - isSlaveNode = checkSlave(); - } - - static bool checkSlave() - { - config::Config* cf = config::Config::makeConfig(); - std::string configVal = cf->getConfig("Installation", "MySQLRep"); - bool isMysqlRep = (configVal == "y" || configVal == "Y"); - if (!isMysqlRep) return false; - configVal = cf->getConfig("SystemConfig", "PrimaryUMModuleName"); - std::string module = execplan::ClientRotator::getModule(); - if (boost::iequals(configVal, module)) - return false; - return true; - } + cal_connection_info() : cal_conn_hndl(0), queryState(0), currentTable(0), traceFlags(0), alterTableState(NOT_ALTER), isAlter(false), + bulkInsertRows(0), singleInsert(true), isLoaddataInfile( false ), dmlProc(0), rowsHaveInserted(0), rc(0), tableOid(0) + { } sm::cpsm_conhdl_t* cal_conn_hndl; int queryState; @@ -253,27 +191,6 @@ struct cal_connection_info uint32_t tableOid; querystats::QueryStats stats; std::string warningMsg; - int64_t localPm; - bool isSlaveNode; - uint32_t expressionId; // for F&E - pid_t mysqld_pid; - pid_t cpimport_pid; - int fdt[2]; -#ifdef _MSC_VER - // Used for launching cpimport for Load Data Infile - HANDLE cpimport_stdin_Rd; - HANDLE cpimport_stdin_Wr; - HANDLE cpimport_stdout_Rd; - HANDLE cpimport_stdout_Wr; - PROCESS_INFORMATION cpimportProcInfo; -#endif - FILE * filePtr; - uint8_t headerLength; - bool useXbit; - bool utf8; - uint8_t useCpimport; - char delimiter; - std::vector columnTypes; }; typedef std::tr1::unordered_map CalConnMap; @@ -283,49 +200,13 @@ const std::string infinidb_err_msg = "\nThe query includes syntax that is not su int cp_get_plan(THD* thd, execplan::SCSEP& csep); int cp_get_table_plan(THD* thd, execplan::SCSEP& csep, cal_impl_if::cal_table_info& ti); int getSelectPlan(gp_walk_info& gwi, SELECT_LEX& select_lex, execplan::SCSEP& csep, bool isUnion=false); -void setError(THD* thd, uint32_t errcode, const std::string errmsg, gp_walk_info* gwi); -void setError(THD* thd, uint32_t errcode, const std::string errmsg); +void setError(THD* thd, uint errcode, const std::string errmsg); void gp_walk(const Item *item, void *arg); void parse_item (Item *item, std::vector& field_vec, bool& hasNonSupportItem, uint16& parseInfo); execplan::ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupport); const std::string bestTableName(const Item_field* ifp); bool isInfiniDB(TABLE* table_ptr); -// execution plan util functions prototypes -execplan::ReturnedColumn* buildReturnedColumn(Item* item, gp_walk_info& gwi, bool& nonSupport); -execplan::ReturnedColumn* buildFunctionColumn(Item_func* item, gp_walk_info& gwi, bool& nonSupport); -execplan::ArithmeticColumn* buildArithmeticColumn(Item_func* item, gp_walk_info &gwi, bool& nonSupport); -execplan::ConstantColumn* buildDecimalColumn(Item *item, gp_walk_info &gwi); -execplan::SimpleColumn* buildSimpleColumn(Item_field* item, gp_walk_info& gwi); -execplan::FunctionColumn* buildCaseFunction(Item_func* item, gp_walk_info& gwi, bool& nonSupport); -execplan::ParseTree* buildParseTree(Item_func* item, gp_walk_info& gwi, bool& nonSupport); -execplan::ReturnedColumn* buildAggregateColumn(Item* item, gp_walk_info& gwi); -execplan::ReturnedColumn* buildWindowFunctionColumn(Item* item, gp_walk_info& gwi, bool& nonSupport); -execplan::ReturnedColumn* buildPseudoColumn(Item* item, gp_walk_info& gwi, bool& nonSupport, uint32_t pseudoType); -void addIntervalArgs(Item_func* ifp, funcexp::FunctionParm& functionParms); -void castCharArgs(Item_func* ifp, funcexp::FunctionParm& functionParms); -void castDecimalArgs(Item_func* ifp, funcexp::FunctionParm& functionParms); -void castTypeArgs(Item_func* ifp, funcexp::FunctionParm& functionParms); -void parse_item (Item *item, std::vector& field_vec, bool& hasNonSupportItem, uint16& parseInfo); -bool isPredicateFunction(Item* item, gp_walk_info* gwip); -execplan::ParseTree* buildRowPredicate(execplan::RowColumn* lhs, execplan::RowColumn* rhs, std::string predicateOp); -void buildRowColumnFilter(gp_walk_info* gwip, execplan::RowColumn* rhs, execplan::RowColumn* lhs, Item_func* ifp); -void buildPredicateItem(Item_func* ifp, gp_walk_info* gwip); -void collectAllCols(gp_walk_info& gwi, Item_field* ifp); -void buildSubselectFunc(Item_func* ifp, gp_walk_info* gwip); -uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex); -std::string getViewName(TABLE_LIST* table_ptr); -void buildConstPredicate(Item_func* ifp, execplan::ReturnedColumn* rhs, gp_walk_info* gwip); -execplan::CalpontSystemCatalog::ColType fieldType_MysqlToIDB (const Field* field); -execplan::CalpontSystemCatalog::ColType colType_MysqlToIDB (const Item* item); -execplan::SPTP getIntervalType(int interval_type); -uint32_t isPseudoColumn(std::string funcName); -void setDerivedTable(execplan::ParseTree* n); -execplan::ParseTree* setDerivedFilter(execplan::ParseTree*& n, - std::map& obj, - execplan::CalpontSelectExecutionPlan::SelectList& derivedTbList); -void derivedTableOptimization(execplan::SCSEP& csep); - #ifdef DEBUG_WALK_COND void debug_walk(const Item *item, void *arg); #endif diff --git a/dbcon/mysql/ha_calpont_partition.cpp b/dbcon/mysql/ha_calpont_partition.cpp index bff9c806..baec0ba3 100644 --- a/dbcon/mysql/ha_calpont_partition.cpp +++ b/dbcon/mysql/ha_calpont_partition.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: ha_calpont_partition.cpp 9642 2013-06-24 14:57:42Z rdempsey $ +* $Id: ha_calpont_partition.cpp 9038 2012-10-29 22:13:24Z zzhu $ */ #include @@ -75,12 +75,12 @@ inline uint32_t tid2sid(const uint32_t tid) } void CHECK( int rc) -{ - if (rc != 0) +{ + if (rc != 0) { ostringstream oss; oss << "Error in DBRM call " << rc << endl; - throw runtime_error(oss.str()); + throw runtime_error(oss.str()); } } @@ -93,7 +93,7 @@ void push_warnings(THD* thd, string& warnings) for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { - push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, (*tok_iter).c_str()); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, (*tok_iter).c_str()); } } @@ -141,22 +141,6 @@ string name(CalpontSystemCatalog::ColType& ct) return "BLOB"; case CalpontSystemCatalog::CLOB: return "CLOB"; - case CalpontSystemCatalog::UINT: - return "UINT"; - case CalpontSystemCatalog::UTINYINT: - return "UTINYINT"; - case CalpontSystemCatalog::UMEDINT: - return "UMEDINT"; - case CalpontSystemCatalog::USMALLINT: - return "USMALLINT"; - case CalpontSystemCatalog::UBIGINT: - return "UBIGINT"; - case CalpontSystemCatalog::UDECIMAL: - return "UDECIMAL"; - case CalpontSystemCatalog::UFLOAT: - return "UFLOAT"; - case CalpontSystemCatalog::UDOUBLE: - return "UDOUBLE"; default: return "Unknown Type"; } @@ -165,21 +149,15 @@ string name(CalpontSystemCatalog::ColType& ct) bool CP_type(CalpontSystemCatalog::ColType& ct) { if (ct.colDataType == CalpontSystemCatalog::INT || - ct.colDataType == CalpontSystemCatalog::TINYINT || - ct.colDataType == CalpontSystemCatalog::MEDINT || - ct.colDataType == CalpontSystemCatalog::SMALLINT || - ct.colDataType == CalpontSystemCatalog::BIGINT || - ct.colDataType == CalpontSystemCatalog::DATE || - ct.colDataType == CalpontSystemCatalog::DATETIME || - ct.colDataType == CalpontSystemCatalog::DECIMAL || - ct.colDataType == CalpontSystemCatalog::UTINYINT || - ct.colDataType == CalpontSystemCatalog::USMALLINT || - ct.colDataType == CalpontSystemCatalog::UMEDINT || - ct.colDataType == CalpontSystemCatalog::UINT || - ct.colDataType == CalpontSystemCatalog::UBIGINT || - ct.colDataType == CalpontSystemCatalog::UDECIMAL || - (ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || - (ct.colDataType == CalpontSystemCatalog::VARCHAR && ct.colWidth <= 7)) + ct.colDataType == CalpontSystemCatalog::TINYINT || + ct.colDataType == CalpontSystemCatalog::MEDINT || + ct.colDataType == CalpontSystemCatalog::SMALLINT || + ct.colDataType == CalpontSystemCatalog::BIGINT || + ct.colDataType == CalpontSystemCatalog::DATE || + ct.colDataType == CalpontSystemCatalog::DATETIME || + ct.colDataType == CalpontSystemCatalog::DECIMAL || + (ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || + (ct.colDataType == CalpontSystemCatalog::VARCHAR && ct.colWidth <= 7)) { return true; } @@ -194,9 +172,9 @@ struct PartitionInfo int64_t min; int64_t max; uint64_t status; - PartitionInfo():min((uint64_t)0x8000000000000001ULL), - max((uint64_t)-0x8000000000000001LL), - status(0) {}; + PartitionInfo():min((uint64_t)0x8000000000000001ULL), + max((uint64_t)-0x8000000000000001LL), + status(0) {}; }; typedef map PartitionMap; @@ -217,7 +195,7 @@ const string charcolToString(int64_t v) const string format(int64_t v, CalpontSystemCatalog::ColType& ct) { ostringstream oss; - + switch (ct.colDataType) { case CalpontSystemCatalog::DATE: @@ -232,6 +210,7 @@ const string format(int64_t v, CalpontSystemCatalog::ColType& ct) // swap again to retain the string byte order uint64_t tmp = uint64ToStr(v); oss << (char*)(&tmp); + break; } case CalpontSystemCatalog::TINYINT: @@ -240,11 +219,10 @@ const string format(int64_t v, CalpontSystemCatalog::ColType& ct) case CalpontSystemCatalog::INT: case CalpontSystemCatalog::BIGINT: case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: { if (ct.scale > 0) { - double d = ((double)(v) / (double)pow((double)10, ct.scale)); + double d = ((double)(v) / (double)pow((double)10, ct.scale)); oss << setprecision(ct.scale) << fixed << d; } else @@ -253,13 +231,6 @@ const string format(int64_t v, CalpontSystemCatalog::ColType& ct) } break; } - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: - oss << static_cast(v); - break; case CalpontSystemCatalog::VARBINARY: oss << "N/A"; break; @@ -285,15 +256,9 @@ const int64_t IDB_format(char* str, CalpontSystemCatalog::ColType& ct, uint8_t& case CalpontSystemCatalog::TINYINT: v = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UTINYINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::SMALLINT: v = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::USMALLINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::MEDINT: case CalpontSystemCatalog::INT: #ifdef _MSC_VER @@ -302,16 +267,9 @@ const int64_t IDB_format(char* str, CalpontSystemCatalog::ColType& ct, uint8_t& v = boost::any_cast(anyVal); #endif break; - case CalpontSystemCatalog::UMEDINT: - case CalpontSystemCatalog::UINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::BIGINT: v = boost::any_cast(anyVal); break; - case CalpontSystemCatalog::UBIGINT: - v = boost::any_cast(anyVal); - break; case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: case CalpontSystemCatalog::VARBINARY: @@ -333,7 +291,6 @@ const int64_t IDB_format(char* str, CalpontSystemCatalog::ColType& ct, uint8_t& v = boost::any_cast(anyVal); break; case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: if (ct.colWidth == execplan::CalpontSystemCatalog::ONE_BYTE) v = boost::any_cast(anyVal); else if (ct.colWidth == execplan::CalpontSystemCatalog::TWO_BYTE) @@ -344,7 +301,7 @@ const int64_t IDB_format(char* str, CalpontSystemCatalog::ColType& ct, uint8_t& #else v = boost::any_cast(anyVal); #endif - else + else v = boost::any_cast(anyVal); break; default: @@ -356,8 +313,7 @@ const int64_t IDB_format(char* str, CalpontSystemCatalog::ColType& ct, uint8_t& ct.colDataType == CalpontSystemCatalog::MEDINT || ct.colDataType == CalpontSystemCatalog::INT || ct.colDataType == CalpontSystemCatalog::BIGINT || - ct.colDataType == CalpontSystemCatalog::DECIMAL || - ct.colDataType == CalpontSystemCatalog::UDECIMAL) && + ct.colDataType == CalpontSystemCatalog::DECIMAL) && pushWarning) { // get rid of leading white spaces and parentheses @@ -375,11 +331,11 @@ const int64_t IDB_format(char* str, CalpontSystemCatalog::ColType& ct, uint8_t& } -void parsePartitionString(UDF_ARGS* args, - int offset, - set& partitionNums, - string& errMsg, - execplan::CalpontSystemCatalog::TableName tableName) +void parsePartitionString(UDF_ARGS* args, + int offset, + set& partitionNums, + string& errMsg, + execplan::CalpontSystemCatalog::TableName tableName) { //@Bug 4695 algorithm::to_lower(tableName.schema); @@ -396,7 +352,7 @@ void parsePartitionString(UDF_ARGS* args, char* tmp = partStrNoSpace; // trim off space - for (uint32_t i = 0; i < partStr.length(); i++) + for (uint i = 0; i < partStr.length(); i++) { if (partStr[i] == ' ' || partStr[i] == '\t') continue; @@ -418,7 +374,7 @@ void parsePartitionString(UDF_ARGS* args, LogicalPartition lp; tokenizer tokens1((*tok_iter), sep1); - uint32_t ctn = 0; + uint ctn = 0; for (tokenizer::iterator tok_iter1 = tokens1.begin(); tok_iter1 != tokens1.end(); ++tok_iter1, ctn++) { ss << *tok_iter1; @@ -454,7 +410,7 @@ void parsePartitionString(UDF_ARGS* args, error: errMsg = "Invalid partition identifier(s)"; return; - + // debug set::const_iterator it; cout << "Partition: "; @@ -481,7 +437,7 @@ int processPartition ( SqlStatement* stmt) { rc = 1; thd->main_da.can_overwrite_status = true; - thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DDLProc"); + thd->main_da.set_error_status(thd, HA_ERR_INTERNAL_ERROR, "Lost connection to DDLProc"); } else { @@ -506,7 +462,7 @@ int processPartition ( SqlStatement* stmt) if (b == ddlpackageprocessor::DDLPackageProcessor::WARN_NO_PARTITION) { rc = b; - push_warnings(thd, emsg); + push_warnings(thd, emsg); } else if (b == ddlpackageprocessor::DDLPackageProcessor::PARTITION_WARNING) { @@ -527,11 +483,11 @@ int processPartition ( SqlStatement* stmt) return rc; } -void partitionByValue_common(UDF_ARGS* args, // input - string& errMsg, // output - CalpontSystemCatalog::TableName& tableName, // output - set& partSet, // output - string functionName) // input +void partitionByValue_common(UDF_ARGS* args, // input + string& errMsg, // output + CalpontSystemCatalog::TableName& tableName, // output + set& partSet, // output + string functionName) // input { // identify partitions by the range DBRM em; @@ -540,11 +496,12 @@ void partitionByValue_common(UDF_ARGS* args, // input PartitionMap partMap; PartitionMap::iterator mapit; int32_t seqNum; + bool header; string schema, table, column; CalpontSystemCatalog::ColType ct; int64_t startVal, endVal; uint8_t rfMin = 0, rfMax = 0; - + if (args->arg_count == 5) { schema = (char*)(args->args[0]); @@ -555,7 +512,7 @@ void partitionByValue_common(UDF_ARGS* args, // input { if (current_thd->db) { - schema = current_thd->db; + schema = current_thd->db; } else { @@ -565,10 +522,10 @@ void partitionByValue_common(UDF_ARGS* args, // input table = (char*)(args->args[0]); column = (char*)(args->args[1]); } - + tableName.schema = schema; tableName.table = table; - + //@Bug 4695 algorithm::to_lower(tableName.schema); if (tableName.schema == "calpontsys") @@ -580,7 +537,6 @@ void partitionByValue_common(UDF_ARGS* args, // input try { boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(tid2sid(current_thd->thread_id)); - csc->identity(execplan::CalpontSystemCatalog::FE); CalpontSystemCatalog::TableColName tcn = make_tcn(schema, table, column); csc->identity(CalpontSystemCatalog::FE); OID_t oid = csc->lookupOID(tcn); @@ -592,7 +548,7 @@ void partitionByValue_common(UDF_ARGS* args, // input errMsg = IDBErrorInfo::instance()->errorMsg(ERR_TABLE_NOT_IN_CATALOG, args); return; } - + // check casual partition data type if (!CP_type(ct)) { @@ -606,75 +562,32 @@ void partitionByValue_common(UDF_ARGS* args, // input if (args->arg_count == 4) { if (!args->args[2]) - { - if (isUnsigned(ct.colDataType)) - { - startVal = 0; - } - else - { - startVal = numeric_limits::min(); - } - } + startVal = numeric_limits::min(); else - { startVal = IDB_format((char*) args->args[2], ct, rfMin); - } if (!args->args[3]) - { - if (isUnsigned(ct.colDataType)) - { - endVal = static_cast(numeric_limits::max()); - } - else - { - endVal = numeric_limits::max(); - } - } + endVal = numeric_limits::max(); else - { endVal = IDB_format((char*) args->args[3], ct, rfMax); - } } else { if (!args->args[3]) - { - if (isUnsigned(ct.colDataType)) - { - startVal = 0; - } - else - { - startVal = numeric_limits::min(); - } - } + startVal = numeric_limits::min(); else - { startVal = IDB_format((char*) args->args[3], ct, rfMin); - } if (!args->args[4]) - { - if (isUnsigned(ct.colDataType)) - { - endVal = static_cast(numeric_limits::max()); - } - else - { - endVal = numeric_limits::max(); - } - } + endVal = numeric_limits::max(); else - { endVal = IDB_format((char*) args->args[4], ct, rfMax); - } } - + CHECK(em.getExtents(oid, entries, false, false, true)); if (entries.size() > 0) { + header = false; LogicalPartition logicalPartNum; - + for (iter = entries.begin(); iter != entries.end(); ++iter) { PartitionInfo partInfo; @@ -683,18 +596,18 @@ void partitionByValue_common(UDF_ARGS* args, // input logicalPartNum.seg = (*iter).segmentNum; if (iter->status == EXTENTOUTOFSERVICE) partInfo.status |= ET_DISABLED; - + mapit = partMap.find(logicalPartNum); int state = em.getExtentMaxMin(iter->range.start, partInfo.max, partInfo.min, seqNum); - + // char column order swap - if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || + if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || (ct.colDataType == CalpontSystemCatalog::VARCHAR && ct.colWidth <= 7)) { partInfo.max = uint64ToStr(partInfo.max); partInfo.min = uint64ToStr(partInfo.min); } - + if (mapit == partMap.end()) { if (state != CP_VALID) @@ -705,54 +618,31 @@ void partitionByValue_common(UDF_ARGS* args, // input { if (mapit->second.status & CPINVALID) continue; - if (isUnsigned(ct.colDataType)) - { - mapit->second.min = - (static_cast(partInfo.min) < static_cast(mapit->second.min) ? partInfo.min : mapit->second.min); - mapit->second.max = - (static_cast(partInfo.max) > static_cast(mapit->second.max) ? partInfo.max : mapit->second.max); - } - else - { - mapit->second.min = (partInfo.min < mapit->second.min ? partInfo.min : mapit->second.min); - mapit->second.max = (partInfo.max > mapit->second.max ? partInfo.max : mapit->second.max); - } + mapit->second.min = (partInfo.min < mapit->second.min ? partInfo.min : mapit->second.min); + mapit->second.max = (partInfo.max > mapit->second.max ? partInfo.max : mapit->second.max); } } - + // check col value range for (mapit = partMap.begin(); mapit != partMap.end(); ++mapit) { // @bug 4595. check empty/null case - if (isUnsigned(ct.colDataType)) - { - if (!(mapit->second.status & CPINVALID) && - static_cast(mapit->second.min) >= static_cast(startVal) && - static_cast(mapit->second.max) <= static_cast(endVal) && - !(static_cast(mapit->second.min) == numeric_limits::max() && - static_cast(mapit->second.max == 0))) - { - if (rfMin == ROUND_POS && mapit->second.min == startVal) - continue; - if (rfMax == ROUND_NEG && mapit->second.max == endVal) - continue; - partSet.insert(mapit->first); - } - } - else + if (!(mapit->second.status & CPINVALID) && mapit->second.min >= startVal && mapit->second.max <= endVal && + !(mapit->second.min == numeric_limits::max() && mapit->second.max == numeric_limits::min())) { - if (!(mapit->second.status & CPINVALID) && mapit->second.min >= startVal && mapit->second.max <= endVal && - !(mapit->second.min == numeric_limits::max() && mapit->second.max == numeric_limits::min())) - { - if (rfMin == ROUND_POS && mapit->second.min == startVal) - continue; - if (rfMax == ROUND_NEG && mapit->second.max == endVal) - continue; - partSet.insert(mapit->first); - } + if (rfMin == ROUND_POS && mapit->second.min == startVal) + continue; + if (rfMax == ROUND_NEG && mapit->second.max == endVal) + continue; + partSet.insert(mapit->first); } } - } + + } + } catch (IDBExcept& ex) + { + errMsg = ex.what(); + return; } catch (QueryDataExcept& ex) { @@ -761,17 +651,12 @@ void partitionByValue_common(UDF_ARGS* args, // input errMsg = IDBErrorInfo::instance()->errorMsg(ERR_INVALID_FUNC_ARGUMENT, args); return; } - catch (IDBExcept& ex) - { - errMsg = ex.what(); - return; - } catch (...) { errMsg = string("Error occured when calling ") + functionName; return; } - + if (partSet.empty()) { errMsg = IDBErrorInfo::instance()->errorMsg(WARN_NO_PARTITION_FOUND); @@ -779,8 +664,7 @@ void partitionByValue_common(UDF_ARGS* args, // input } } -std::string ha_calpont_impl_markpartitions_( - execplan::CalpontSystemCatalog::TableName tableName, set& partitionNums) +std::string ha_calpont_impl_markpartitions_ (execplan::CalpontSystemCatalog::TableName tableName, set& partitionNums) { ddlpackage::QualifiedName *qualifiedName = new QualifiedName(); qualifiedName->fSchema = tableName.schema; @@ -799,8 +683,7 @@ std::string ha_calpont_impl_markpartitions_( return msg; } -std::string ha_calpont_impl_restorepartitions_( - execplan::CalpontSystemCatalog::TableName tableName, set& partitionNums) +std::string ha_calpont_impl_restorepartitions_ (execplan::CalpontSystemCatalog::TableName tableName, set& partitionNums) { ddlpackage::QualifiedName *qualifiedName = new QualifiedName(); qualifiedName->fSchema = tableName.schema; @@ -815,13 +698,12 @@ std::string ha_calpont_impl_restorepartitions_( if ( rc != 0 ) return msg; msg = "Partitions are enabled successfully." ; - + delete stmt; return msg; } -std::string ha_calpont_impl_droppartitions_( - execplan::CalpontSystemCatalog::TableName tableName, set& partitionNums) +std::string ha_calpont_impl_droppartitions_ (execplan::CalpontSystemCatalog::TableName tableName, set& partitionNums) { ddlpackage::QualifiedName *qualifiedName = new QualifiedName(); qualifiedName->fSchema = tableName.schema; @@ -836,7 +718,7 @@ std::string ha_calpont_impl_droppartitions_( int rc = processPartition( stmt); if (rc == ddlpackageprocessor::DDLPackageProcessor::WARN_NO_PARTITION) msg = "No partitions are dropped"; - + delete stmt; return msg; } @@ -844,16 +726,16 @@ std::string ha_calpont_impl_droppartitions_( extern "C" { -/** +/** * CalShowPartitions */ - + #ifdef _MSC_VER __declspec(dllexport) #endif my_bool calshowpartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message) { - if (args->arg_count < 2 || + if (args->arg_count < 2 || args->arg_count > 3 || args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || @@ -862,8 +744,8 @@ my_bool calshowpartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message) strcpy(message,"usage: CALSHOWPARTITIONS ([schema], table, column)"); return 1; } - - for (uint32_t i = 0; i < args->arg_count; i++) + + for (uint i = 0; i < args->arg_count; i++) { if (!args->args[i]) { @@ -897,10 +779,11 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, PartitionMap partMap; PartitionMap::iterator mapit; int32_t seqNum; + bool header; string schema, table, column; CalpontSystemCatalog::ColType ct; string errMsg; - + try { if (args->arg_count == 3) @@ -913,7 +796,7 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, { if (current_thd->db) { - schema = current_thd->db; + schema = current_thd->db; } else { @@ -922,7 +805,9 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, table = (char*)(args->args[0]); column = (char*)(args->args[1]); } - + + //try + //{ boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(tid2sid(current_thd->thread_id)); csc->identity(CalpontSystemCatalog::FE); CalpontSystemCatalog::TableColName tcn = make_tcn(schema, table, column); @@ -934,10 +819,11 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, args.add("'" + schema + string(".") + table + string(".") + column + "'"); throw IDBExcept(ERR_TABLE_NOT_IN_CATALOG, args); } - + CHECK(em.getExtents(oid, entries, false, false, true)); if (entries.size() > 0) { + header = false; iter = entries.begin(); end = entries.end(); LogicalPartition logicalPartNum; @@ -947,21 +833,21 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, logicalPartNum.dbroot = (*iter).dbRoot; logicalPartNum.pp = (*iter).partitionNum; logicalPartNum.seg = (*iter).segmentNum; - + if (iter->status == EXTENTOUTOFSERVICE) partInfo.status |= ET_DISABLED; - + mapit = partMap.find(logicalPartNum); int state = em.getExtentMaxMin(iter->range.start, partInfo.max, partInfo.min, seqNum); - + // char column order swap for compare - if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || + if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || (ct.colDataType == CalpontSystemCatalog::VARCHAR && ct.colWidth <= 7)) { partInfo.max = uint64ToStr(partInfo.max); partInfo.min = uint64ToStr(partInfo.min); } - + if (mapit == partMap.end()) { if (state != CP_VALID) @@ -980,32 +866,22 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, } catch (IDBExcept& ex) { current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, ex.what()); + current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, ex.what()); return result; } catch (...) { current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, "Error occured when calling CALSHOWPARTITIONS"); + current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, "Error occured when calling CALSHOWPARTITIONS"); return result; } - + ostringstream output; output.setf(ios::left, ios::adjustfield); - output << setw(10) << "Part#" - << setw(30) << "Min" + output << setw(10) << "Part#" + << setw(30) << "Min" << setw(30) << "Max" << "Status"; - - int64_t maxLimit = numeric_limits::max(); - int64_t minLimit = numeric_limits::min(); - // char column order swap for compare in subsequent loop - if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || - (ct.colDataType == CalpontSystemCatalog::VARCHAR && ct.colWidth <= 7)) - { - maxLimit = uint64ToStr(maxLimit); - minLimit = uint64ToStr(minLimit); - } - + PartitionMap::const_iterator partIt; for (partIt = partMap.begin(); partIt != partMap.end(); ++partIt) { @@ -1013,34 +889,17 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, oss << partIt->first; output << "\n " << setw(10) << oss.str(); if (partIt->second.status & CPINVALID) - { output << setw(30) << "N/A" << setw(30) << "N/A"; - } + else if (partIt->second.min == numeric_limits::max() && partIt->second.max == numeric_limits::min()) + output << setw(30) << "Empty/Null" << setw(30) << "Empty/Null"; else - { - if ((isUnsigned(ct.colDataType))) - { - if (static_cast(partIt->second.min) == numeric_limits::max() - && static_cast(partIt->second.max) == numeric_limits::min()) - output << setw(30) << "Empty/Null" << setw(30) << "Empty/Null"; - else - output << setw(30) << format(mapit->second.min, ct) << setw(30) << format(mapit->second.max, ct); - } - else - { - if (partIt->second.min == maxLimit && partIt->second.max == minLimit) - output << setw(30) << "Empty/Null" << setw(30) << "Empty/Null"; - else - output << setw(30) << format(partIt->second.min, ct) << setw(30) << format(partIt->second.max, ct); - } - } - + output << setw(30) << format(partIt->second.min, ct) << setw(30) << format(partIt->second.max, ct); if (partIt->second.status & ET_DISABLED) output << "Disabled"; else output << "Enabled"; } - + // use our own buffer to make sure it fits. initid->ptr = new char[output.str().length()+1]; memcpy(initid->ptr,output.str().c_str(),output.str().length()); @@ -1049,27 +908,27 @@ const char* calshowpartitions(UDF_INIT* initid, UDF_ARGS* args, } -/** +/** * CalDisablePartitions */ - + #ifdef _MSC_VER __declspec(dllexport) #endif my_bool caldisablepartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message) { bool err = false; - + if (args->arg_count < 2 || args->arg_count > 3) err = true; - else if (args->arg_count == 3 && ((args->arg_type[0] != STRING_RESULT || - args->arg_type[1] != STRING_RESULT || - args->arg_type[2] != STRING_RESULT))) + else if (args->arg_count == 3 && ((args->arg_type[0] != STRING_RESULT || + args->arg_type[1] != STRING_RESULT || + args->arg_type[2] != STRING_RESULT))) err = true; else if (args->arg_count == 2 && ((args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT))) err = true; - - for (uint32_t i = 0; i < args->arg_count; i++) + + for (uint i = 0; i < args->arg_count; i++) { if (!args->args[i]) { @@ -1077,7 +936,7 @@ my_bool caldisablepartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* messag break; } } - + if (err) { strcpy(message,"\nusage: CALDISABLEPARTITIONS (['schemaName'], 'tableName', 'partitionList')"); @@ -1094,7 +953,7 @@ __declspec(dllexport) const char* caldisablepartitions(UDF_INIT* initid, UDF_ARGS* args, char* result, unsigned long* length, char* is_null, char* error) -{ +{ CalpontSystemCatalog::TableName tableName; set partitionNums; string errMsg; @@ -1117,10 +976,10 @@ const char* caldisablepartitions(UDF_INIT* initid, UDF_ARGS* args, tableName.schema = current_thd->db; parsePartitionString(args, 1, partitionNums, errMsg, tableName); } - + if (errMsg.empty()) errMsg = ha_calpont_impl_markpartitions_(tableName,partitionNums ); - + memcpy(result,errMsg.c_str(), errMsg.length()); *length = errMsg.length(); return result; @@ -1133,10 +992,10 @@ void caldisablepartitions_deinit(UDF_INIT* initid) { } -/** +/** * CalEnablePartitions */ - + #ifdef _MSC_VER __declspec(dllexport) #endif @@ -1145,14 +1004,14 @@ my_bool calenablepartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message bool err = false; if (args->arg_count < 2 || args->arg_count > 3) err = true; - else if (args->arg_count == 3 && ((args->arg_type[0] != STRING_RESULT || - args->arg_type[1] != STRING_RESULT || - args->arg_type[2] != STRING_RESULT))) + else if (args->arg_count == 3 && ((args->arg_type[0] != STRING_RESULT || + args->arg_type[1] != STRING_RESULT || + args->arg_type[2] != STRING_RESULT))) err = true; else if (args->arg_count == 2 && ((args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT))) err = true; - - for (uint32_t i = 0; i < args->arg_count; i++) + + for (uint i = 0; i < args->arg_count; i++) { if (!args->args[i]) { @@ -1160,7 +1019,7 @@ my_bool calenablepartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message break; } } - + if (err) { strcpy(message,"\nusage: CALENABLEPARTITIONS (['schemaName'], 'tableName', 'partitionList')"); @@ -1178,7 +1037,7 @@ __declspec(dllexport) const char* calenablepartitions(UDF_INIT* initid, UDF_ARGS* args, char* result, unsigned long* length, char* is_null, char* error) -{ +{ CalpontSystemCatalog::TableName tableName; string errMsg; set partitionNums; @@ -1194,21 +1053,18 @@ const char* calenablepartitions(UDF_INIT* initid, UDF_ARGS* args, if (!current_thd->db) { current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status - ( - current_thd, - HA_ERR_INTERNAL_ERROR, - IDBErrorInfo::instance()->errorMsg(ERR_PARTITION_NO_SCHEMA).c_str() - ); + current_thd->main_da.set_error_status(current_thd, + HA_ERR_INTERNAL_ERROR, + IDBErrorInfo::instance()->errorMsg(ERR_PARTITION_NO_SCHEMA).c_str()); return result; } tableName.schema = current_thd->db; parsePartitionString(args, 1, partitionNums, errMsg, tableName); } - + if (errMsg.empty()) errMsg = ha_calpont_impl_restorepartitions_(tableName,partitionNums ); - + memcpy(result, errMsg.c_str(), errMsg.length()); *length = errMsg.length(); return result; @@ -1221,10 +1077,10 @@ void calenablepartitions_deinit(UDF_INIT* initid) { } -/** +/** * CalDropPartitions */ - + #ifdef _MSC_VER __declspec(dllexport) #endif @@ -1233,14 +1089,14 @@ my_bool caldroppartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message) bool err = false; if (args->arg_count < 2 || args->arg_count > 3) err = true; - else if (args->arg_count == 3 && ((args->arg_type[0] != STRING_RESULT || - args->arg_type[1] != STRING_RESULT || - args->arg_type[2] != STRING_RESULT))) - err = true; + else if (args->arg_count == 3 && ((args->arg_type[0] != STRING_RESULT || + args->arg_type[1] != STRING_RESULT || + args->arg_type[2] != STRING_RESULT))) + err = true; else if (args->arg_count == 2 && ((args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT))) - err = true; - - for (uint32_t i = 0; i < args->arg_count; i++) + err = true; + + for (uint i = 0; i < args->arg_count; i++) { if (!args->args[i]) { @@ -1248,7 +1104,7 @@ my_bool caldroppartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message) break; } } - + if (err) { strcpy(message,"\nusage: CALDROPPARTITIONS (['schemaName'], 'tableName', 'partitionList')"); @@ -1264,13 +1120,13 @@ my_bool caldroppartitions_init(UDF_INIT* initid, UDF_ARGS* args, char* message) __declspec(dllexport) #endif const char* caldroppartitions(UDF_INIT* initid, UDF_ARGS* args, - char* result, unsigned long* length, - char* is_null, char* error) -{ + char* result, unsigned long* length, + char* is_null, char* error) +{ CalpontSystemCatalog::TableName tableName; string errMsg; set partSet; - + if ( args->arg_count == 3 ) { tableName.schema = args->args[0]; @@ -1283,8 +1139,9 @@ const char* caldroppartitions(UDF_INIT* initid, UDF_ARGS* args, if (!current_thd->db) { current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status( current_thd, HA_ERR_INTERNAL_ERROR, - IDBErrorInfo::instance()->errorMsg(ERR_PARTITION_NO_SCHEMA).c_str()); + current_thd->main_da.set_error_status(current_thd, + HA_ERR_INTERNAL_ERROR, + IDBErrorInfo::instance()->errorMsg(ERR_PARTITION_NO_SCHEMA).c_str()); return result; } tableName.schema = current_thd->db; @@ -1293,7 +1150,7 @@ const char* caldroppartitions(UDF_INIT* initid, UDF_ARGS* args, if (errMsg.empty()) errMsg = ha_calpont_impl_droppartitions_(tableName,partSet); - + memcpy(result, errMsg.c_str(), errMsg.length()); *length = errMsg.length(); return result; @@ -1306,10 +1163,10 @@ void caldroppartitions_deinit(UDF_INIT* initid) { } -/** +/** * CalDropPartitionsByValue */ - + #ifdef _MSC_VER __declspec(dllexport) #endif @@ -1335,7 +1192,7 @@ my_bool caldroppartitionsbyvalue_init(UDF_INIT* initid, UDF_ARGS* args, char* me } else if (args->arg_count == 5) { - if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || + if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || args->arg_type[2] != STRING_RESULT || args->arg_type[3] != STRING_RESULT || args->arg_type[4] != STRING_RESULT) err = true; } @@ -1366,22 +1223,22 @@ const char* caldroppartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, CalpontSystemCatalog::TableName tableName; set partSet; partitionByValue_common(args, msg, tableName, partSet, "calDropPartitionsByValue"); - + if (!msg.empty()) { current_thd->main_da.can_overwrite_status = true; current_thd->main_da.set_error_status(current_thd, HA_ERR_INTERNAL_ERROR, msg.c_str()); return result; } - + msg = ha_calpont_impl_droppartitions_(tableName,partSet); - + memcpy(result, msg.c_str(), msg.length()); *length = msg.length(); return result; } -/** +/** * CalDisablePartitionsByValue */ @@ -1410,7 +1267,7 @@ my_bool caldisablepartitionsbyvalue_init(UDF_INIT* initid, UDF_ARGS* args, char* } else if (args->arg_count == 5) { - if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || + if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || args->arg_type[2] != STRING_RESULT || args->arg_type[3] != STRING_RESULT || args->arg_type[4] != STRING_RESULT) err = true; } @@ -1437,7 +1294,7 @@ const char* caldisablepartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, set partSet; CalpontSystemCatalog::TableName tableName; partitionByValue_common(args, msg, tableName, partSet, "calDisablePartitionsByValue"); - + if (!msg.empty()) { current_thd->main_da.can_overwrite_status = true; @@ -1446,14 +1303,14 @@ const char* caldisablepartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, } msg = ha_calpont_impl_markpartitions_(tableName, partSet); - + memcpy(result, msg.c_str(), msg.length()); *length = msg.length(); return result; } -/** +/** * CalEnablePartitionsByValue */ #ifdef _MSC_VER @@ -1481,11 +1338,11 @@ my_bool calenablepartitionsbyvalue_init(UDF_INIT* initid, UDF_ARGS* args, char* } else if (args->arg_count == 5) { - if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || + if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || args->arg_type[2] != STRING_RESULT || args->arg_type[3] != STRING_RESULT || args->arg_type[4] != STRING_RESULT) err = true; } - + if (err) { strcpy(message,"\nusage: CALENABLEPARTITIONSBYVALUE (['schema'], 'table', 'column', 'min', 'max')"); @@ -1508,7 +1365,7 @@ const char* calenablepartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, set partSet; CalpontSystemCatalog::TableName tableName; partitionByValue_common(args, msg, tableName, partSet, "calEnablePartitionsByValue"); - + if (!msg.empty()) { current_thd->main_da.can_overwrite_status = true; @@ -1517,13 +1374,13 @@ const char* calenablepartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, } msg = ha_calpont_impl_restorepartitions_(tableName, partSet); - + memcpy(result, msg.c_str(), msg.length()); *length = msg.length(); return result; } -/** +/** * CalShowPartitionsByValue */ #ifdef _MSC_VER @@ -1543,11 +1400,11 @@ my_bool calshowpartitionsbyvalue_init(UDF_INIT* initid, UDF_ARGS* args, char* me } else if (args->arg_count == 5) { - if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || + if (args->arg_type[0] != STRING_RESULT || args->arg_type[1] != STRING_RESULT || args->arg_type[2] != STRING_RESULT || args->arg_type[3] != STRING_RESULT || args->arg_type[4] != STRING_RESULT) err = true; } - + if (err) { strcpy(message,"\nusage: CALSHOWPARTITIONSBYVALUE (['schema'], 'table', 'column', 'min', 'max')"); @@ -1581,12 +1438,13 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, PartitionMap partMap; PartitionMap::iterator mapit; int32_t seqNum; + bool header; string schema, table, column; CalpontSystemCatalog::ColType ct; string errMsg; int64_t startVal, endVal; uint8_t rfMin = 0, rfMax = 0; - + try { if (args->arg_count == 5) @@ -1599,7 +1457,7 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, { if (current_thd->db) { - schema = current_thd->db; + schema = current_thd->db; } else { @@ -1608,7 +1466,7 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, table = (char*)(args->args[0]); column = (char*)(args->args[1]); } - + boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(tid2sid(current_thd->thread_id)); csc->identity(CalpontSystemCatalog::FE); CalpontSystemCatalog::TableColName tcn = make_tcn(schema, table, column); @@ -1620,7 +1478,7 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, args.add("'" + schema + string(".") + table + string(".") + column + "'"); throw IDBExcept(ERR_TABLE_NOT_IN_CATALOG, args); } - + // check casual partition data type if (!CP_type(ct)) { @@ -1629,77 +1487,34 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, args.add("calShowPartitionsByValue"); throw IDBExcept(ERR_PARTITION_BY_RANGE, args); } - + if (args->arg_count == 4) { if (!args->args[2]) - { - if (isUnsigned(ct.colDataType)) - { - startVal = 0; - } - else - { - startVal = numeric_limits::min(); - } - } + startVal = numeric_limits::min(); else - { startVal = IDB_format((char*) args->args[2], ct, rfMin); - } if (!args->args[3]) - { - if (isUnsigned(ct.colDataType)) - { - endVal = static_cast(numeric_limits::max()); - } - else - { - endVal = numeric_limits::max(); - } - } + endVal = numeric_limits::max(); else - { endVal = IDB_format((char*) args->args[3], ct, rfMax); - } } else { if (!args->args[3]) - { - if (isUnsigned(ct.colDataType)) - { - startVal = 0; - } - else - { - startVal = numeric_limits::min(); - } - } + startVal = numeric_limits::min(); else - { startVal = IDB_format((char*) args->args[3], ct, rfMin); - } if (!args->args[4]) - { - if (isUnsigned(ct.colDataType)) - { - endVal = static_cast(numeric_limits::max()); - } - else - { - endVal = numeric_limits::max(); - } - } + endVal = numeric_limits::max(); else - { endVal = IDB_format((char*) args->args[4], ct, rfMax); - } } - + CHECK(em.getExtents(oid, entries, false, false, true)); if (entries.size() > 0) { + header = false; iter = entries.begin(); end = entries.end(); LogicalPartition logicalPartNum; @@ -1711,12 +1526,12 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, logicalPartNum.seg = (*iter).segmentNum; if (iter->status == EXTENTOUTOFSERVICE) partInfo.status |= ET_DISABLED; - + mapit = partMap.find(logicalPartNum); int state = em.getExtentMaxMin(iter->range.start, partInfo.max, partInfo.min, seqNum); - + // char column order swap - if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || + if ((ct.colDataType == CalpontSystemCatalog::CHAR && ct.colWidth <= 8) || (ct.colDataType == CalpontSystemCatalog::VARCHAR && ct.colWidth <= 7)) { partInfo.max = uint64ToStr(partInfo.max); @@ -1732,44 +1547,33 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, { if (mapit->second.status & CPINVALID) continue; - if (isUnsigned(ct.colDataType)) - { - mapit->second.min = - (static_cast(partInfo.min) < static_cast(mapit->second.min) ? partInfo.min : mapit->second.min); - mapit->second.max = - (static_cast(partInfo.max) > static_cast(mapit->second.max) ? partInfo.max : mapit->second.max); - } - else - { - mapit->second.min = (partInfo.min < mapit->second.min ? partInfo.min : mapit->second.min); - mapit->second.max = (partInfo.max > mapit->second.max ? partInfo.max : mapit->second.max); - } + mapit->second.min = (partInfo.min < mapit->second.min ? partInfo.min : mapit->second.min); + mapit->second.max = (partInfo.max > mapit->second.max ? partInfo.max : mapit->second.max); } } } - } - catch (logging::QueryDataExcept& ex) + } catch (IDBExcept& ex) { - Message::Args args; - args.add(ex.what()); - errMsg = IDBErrorInfo::instance()->errorMsg(ERR_INVALID_FUNC_ARGUMENT, args); current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, (char*)errMsg.c_str()); + current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, ex.what()); return result; } - catch (IDBExcept& ex) + catch (logging::QueryDataExcept& ex) { + Message::Args args; + args.add(ex.what()); + errMsg = IDBErrorInfo::instance()->errorMsg(ERR_INVALID_FUNC_ARGUMENT, args); current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, ex.what()); + current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, (char*)errMsg.c_str()); return result; } catch (...) { current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, "Error occured when calling CALSHOWPARTITIONS"); + current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, "Error occured when calling CALSHOWPARTITIONS"); return result; } - + // create a set of partInfo for sorting. bool noPartFound = true; ostringstream output; @@ -1788,50 +1592,34 @@ const char* calshowpartitionsbyvalue(UDF_INIT* initid, UDF_ARGS* args, if (noPartFound) { output.setf(ios::left, ios::adjustfield); - output << setw(10) << "Part#" - << setw(30) << "Min" - << setw(30) << "Max" << "Status"; + output << setw(10) << "Part#" + << setw(30) << "Min" + << setw(30) << "Max" << "Status"; } noPartFound = false; - + // print part info ostringstream oss; oss << mapit->first; output << "\n " << setw(10) << oss.str(); if (mapit->second.status & CPINVALID) - { output << setw(30) << "N/A" << setw(30) << "N/A"; - } + else if (mapit->second.min > mapit->second.max) + output << setw(30) << "Empty/Null" << setw(30) << "Empty/Null"; else - { - if ((isUnsigned(ct.colDataType))) - { - if (static_cast(mapit->second.min) > static_cast(mapit->second.max)) - output << setw(30) << "Empty/Null" << setw(30) << "Empty/Null"; - else - output << setw(30) << format(mapit->second.min, ct) << setw(30) << format(mapit->second.max, ct); - } - else - { - if (mapit->second.min > mapit->second.max) - output << setw(30) << "Empty/Null" << setw(30) << "Empty/Null"; - else - output << setw(30) << format(mapit->second.min, ct) << setw(30) << format(mapit->second.max, ct); - } - } - + output << setw(30) << format(mapit->second.min, ct) << setw(30) << format(mapit->second.max, ct); if (mapit->second.status & ET_DISABLED) output << "Disabled"; else output << "Enabled"; } } - + if (noPartFound) { errMsg = IDBErrorInfo::instance()->errorMsg(WARN_NO_PARTITION_FOUND); current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, errMsg.c_str()); + current_thd->main_da.set_error_status(current_thd, HA_ERR_UNSUPPORTED, errMsg.c_str()); return result; } diff --git a/dbcon/mysql/ha_calpont_udf.cpp b/dbcon/mysql/ha_calpont_udf.cpp index 14d56755..817ab3e9 100644 --- a/dbcon/mysql/ha_calpont_udf.cpp +++ b/dbcon/mysql/ha_calpont_udf.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: ha_calpont_udf.cpp 9210 2013-01-21 14:10:42Z rdempsey $ + * $Id: ha_calpont_udf.cpp 8436 2012-04-04 18:18:21Z rdempsey $ */ #ifdef _MSC_VER diff --git a/dbcon/mysql/ha_exists_sub.cpp b/dbcon/mysql/ha_exists_sub.cpp index 0ec8e792..76f7b5f6 100644 --- a/dbcon/mysql/ha_exists_sub.cpp +++ b/dbcon/mysql/ha_exists_sub.cpp @@ -51,7 +51,7 @@ void checkCorrelation(const ParseTree* n, void* obj) return; uint64_t lJoinInfo = sf->lhs()->joinInfo(); uint64_t rJoinInfo = sf->rhs()->joinInfo(); - + if (lJoinInfo & JOIN_CORRELATED) { ConstantColumn *cc = dynamic_cast(sf->rhs()); @@ -66,7 +66,7 @@ void checkCorrelation(const ParseTree* n, void* obj) } } -ExistsSub::ExistsSub(gp_walk_info& gwip) : WhereSubQuery(gwip) +ExistsSub::ExistsSub(gp_walk_info& gwip) : WhereSubQuery(gwip) {} ExistsSub::ExistsSub(gp_walk_info& gwip, Item_subselect* sub) : @@ -79,21 +79,21 @@ ExistsSub::~ExistsSub() execplan::ParseTree* ExistsSub::transform() { idbassert(fSub); - + SCSEP csep(new CalpontSelectExecutionPlan()); - csep->sessionID(fGwip.sessionid); + csep->sessionID(fGwip.sessionid); csep->location(CalpontSelectExecutionPlan::WHERE); csep->subType (CalpontSelectExecutionPlan::EXISTS_SUBS); - + // gwi for the sub query gp_walk_info gwi; gwi.thd = fGwip.thd; gwi.subQuery = this; - + // @4827 merge table list to gwi in case there is FROM sub to be referenced // in the FROM sub - gwi.derivedTbCnt = fGwip.derivedTbList.size(); - uint32_t tbCnt = fGwip.tbList.size(); + uint derivedTbCnt = fGwip.derivedTbList.size(); + uint tbCnt = fGwip.tbList.size(); gwi.tbList.insert(gwi.tbList.begin(), fGwip.tbList.begin(), fGwip.tbList.end()); gwi.derivedTbList.insert(gwi.derivedTbList.begin(), fGwip.derivedTbList.begin(), fGwip.derivedTbList.end()); @@ -104,7 +104,7 @@ execplan::ParseTree* ExistsSub::transform() fGwip.parseErrorText = logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_AGG_EXISTS); return NULL; } - + if (getSelectPlan(gwi, *(fSub->get_select_lex()), csep) != 0) { fGwip.fatalParseError = true; @@ -114,15 +114,15 @@ execplan::ParseTree* ExistsSub::transform() fGwip.parseErrorText = "Error occured in ExistsSub::transform()"; return NULL; } - + // remove outer query tables CalpontSelectExecutionPlan::TableList tblist; if (csep->tableList().size() >= tbCnt) tblist.insert(tblist.begin(),csep->tableList().begin()+tbCnt, csep->tableList().end()); CalpontSelectExecutionPlan::SelectList derivedTbList; - if (csep->derivedTableList().size() >= gwi.derivedTbCnt) - derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+gwi.derivedTbCnt, csep->derivedTableList().end()); - + if (csep->derivedTableList().size() >= derivedTbCnt) + derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+derivedTbCnt, csep->derivedTableList().end()); + csep->tableList(tblist); csep->derivedTableList(derivedTbList); @@ -132,9 +132,7 @@ execplan::ParseTree* ExistsSub::transform() const ParseTree* pt = csep->filters(); if (pt) pt->walk(checkCorrelation, subFilter); - - fGwip.subselectList.push_back(csep); - return new ParseTree(subFilter); + return new ParseTree(subFilter); } /** diff --git a/dbcon/mysql/ha_from_sub.cpp b/dbcon/mysql/ha_from_sub.cpp index d6a242e5..bd4c9160 100644 --- a/dbcon/mysql/ha_from_sub.cpp +++ b/dbcon/mysql/ha_from_sub.cpp @@ -25,258 +25,18 @@ //#define NDEBUG #include -#include -using namespace std; #include "idb_mysql.h" #include "parsetree.h" #include "simplefilter.h" -#include "logicoperator.h" -#include "constantcolumn.h" -#include "simplecolumn.h" using namespace execplan; #include "ha_subquery.h" namespace cal_impl_if { - -void derivedTableOptimization(SCSEP& csep) -{ - // @bug5634. replace the unused column with ConstantColumn from derived table column list, - // ExeMgr will not project ConstantColumn. Only count for local derived column. - // subquery may carry main query derived table list for column reference, those - // derived tables are not checked for optimization in this scope. - CalpontSelectExecutionPlan::SelectList derivedTbList = csep->derivedTableList(); - for (uint i = 0; i < derivedTbList.size(); i++) - { - CalpontSelectExecutionPlan *plan = dynamic_cast(derivedTbList[i].get()); - CalpontSelectExecutionPlan::ReturnedColumnList cols = plan->returnedCols(); - vector unionColVec; - - // only do vertical optimization for union all - // @bug6134. Also skip the vertical optimization for select distinct - // because all columns need to be projected to check the distinctness. - bool verticalOptimization = false; - if (plan->distinctUnionNum() == 0 && !plan->distinct()) - { - verticalOptimization = true; - for (uint j = 0; j < plan->unionVec().size(); j++) - { - unionColVec.push_back( - dynamic_cast(plan->unionVec()[j].get())->returnedCols()); - } - } - - if (verticalOptimization) - { - int64_t val = 1; - for (uint i = 0; i < cols.size(); i++) - { - //if (cols[i]->derivedTable().empty()) - if (cols[i]->refCount() == 0) - { - if (cols[i]->derivedRefCol()) - cols[i]->derivedRefCol()->decRefCount(); - cols[i].reset(new ConstantColumn(val)); - for (uint j = 0; j < unionColVec.size(); j++) - unionColVec[j][i].reset(new ConstantColumn(val)); - } - } - - // set back - plan->returnedCols(cols); - for (uint j = 0; j < unionColVec.size(); j++) - dynamic_cast(plan->unionVec()[j].get())->returnedCols(unionColVec[j]); - } - } - - /* - * @bug5635. Move filters that only belongs to a derived table to inside the derived table. - * 1. parse tree walk to populate derivedTableFilterMap and set null candidate on the tree. - * 2. remove the null filters - * 3. and the filters of derivedTableFilterMap and append to the WHERE filter of the derived table - * - * Note: - * 1. Subquery filters is ignored because derived table can not be in subquery - * 2. While walking tree, whenever a single derive simplefilter is encountered, - * this filter is pushed to the corresponding stack - * 2. Whenever an OR operator is encountered, all the filter stack of - * that OR involving derived table are emptied and null candidate of each - * stacked filter needs to be reset (not null) - */ - ParseTree* pt = csep->filters(); - map derivedTbFilterMap; - if (pt) - { - pt->walk(setDerivedTable); - setDerivedFilter(pt, derivedTbFilterMap, derivedTbList); - csep->filters(pt); - } - - // AND the filters of individual stack to the derived table filter tree - // @todo union filters. - // @todo outer join complication - map::iterator mapIt; - for (uint i = 0; i < derivedTbList.size(); i++) - { - CalpontSelectExecutionPlan *plan = dynamic_cast(derivedTbList[i].get()); - CalpontSelectExecutionPlan::ReturnedColumnList derivedColList = plan->returnedCols(); - mapIt = derivedTbFilterMap.find(plan->derivedTbAlias()); - - if (mapIt != derivedTbFilterMap.end()) - { - // replace all derived column of this filter with real column from - // derived table projection list. - ParseTree *mainFilter = new ParseTree(); - mainFilter->copyTree(*(mapIt->second)); - replaceRefCol(mainFilter, derivedColList); - ParseTree* derivedFilter = plan->filters(); - if (derivedFilter) - { - LogicOperator *op = new LogicOperator("and"); - ParseTree *filter = new ParseTree(op); - filter->left(derivedFilter); - filter->right(mainFilter); - plan->filters(filter); - } - else - { - plan->filters(mainFilter); - } - - // union filter handling - for (uint j = 0; j < plan->unionVec().size(); j++) - { - CalpontSelectExecutionPlan *unionPlan = - dynamic_cast(plan->unionVec()[j].get()); - CalpontSelectExecutionPlan::ReturnedColumnList unionColList = unionPlan->returnedCols(); - ParseTree* mainFilterForUnion = new ParseTree(); - mainFilterForUnion->copyTree(*(mapIt->second)); - replaceRefCol(mainFilterForUnion, unionColList); - ParseTree *unionFilter = unionPlan->filters(); - if (unionFilter) - { - LogicOperator *op = new LogicOperator("and"); - ParseTree *filter = new ParseTree(op); - filter->left(unionFilter); - filter->right(mainFilterForUnion); - unionPlan->filters(filter); - } - else - { - unionPlan->filters(mainFilterForUnion); - } - } - } - } - - // clean derivedTbFilterMap because all the filters are copied - for( mapIt = derivedTbFilterMap.begin(); mapIt != derivedTbFilterMap.end(); ++mapIt ) - delete (*mapIt).second; - - // recursively process the nested derived table - for (uint i = 0; i < csep->subSelectList().size(); i++) - { - SCSEP subselect(boost::dynamic_pointer_cast(csep->subSelectList()[i])); - derivedTableOptimization(subselect); - } -} - -void setDerivedTable(execplan::ParseTree* n) -{ - ParseTree *lhs = n->left(); - ParseTree *rhs = n->right(); - - Operator *op = dynamic_cast(n->data()); - - // if logic operator then lhs and rhs can't be both null - if (op) - { - if (!lhs || lhs->derivedTable() == "*") - { - n->derivedTable(rhs ? rhs->derivedTable() : "*"); - } - else if (!rhs || rhs->derivedTable() == "*") - { - n->derivedTable(lhs->derivedTable()); - } - else if (lhs->derivedTable() == rhs->derivedTable()) - { - n->derivedTable(lhs->derivedTable()); - } - else - { - n->derivedTable(""); - } - } - else - { - n->data()->setDerivedTable(); - n->derivedTable(n->data()->derivedTable()); - } -} - -ParseTree* setDerivedFilter(ParseTree*& n, map& filterMap, - CalpontSelectExecutionPlan::SelectList& derivedTbList) -{ - if (!(n->derivedTable().empty())) - { - // @todo replace virtual column of n to real column - // all simple columns should belong to the same derived table - CalpontSelectExecutionPlan *csep = NULL; - for (uint i = 0; i < derivedTbList.size(); i++) - { - CalpontSelectExecutionPlan *plan = dynamic_cast(derivedTbList[i].get()); - if (plan->derivedTbAlias() == n->derivedTable()) - { - csep = plan; - break; - } - } - // should never be null; if null then give up optimization. - if (!csep) - return n; - - // 2. push the filter to the derived table filter stack, or 'and' with - // the filters in the stack - map::iterator mapIter = filterMap.find(n->derivedTable()); - if ( mapIter == filterMap.end()) - { - filterMap.insert(pair(n->derivedTable(), n)); - } - else - { - ParseTree* pt = new ParseTree(new LogicOperator("and")); - pt->left(mapIter->second); - pt->right(n); - mapIter->second = pt; - } - int64_t val = 1; - n = new ParseTree(new ConstantColumn(val)); - } - else - { - Operator *op = dynamic_cast(n->data()); - if (op && (op->op() == OP_OR || op->op() == OP_XOR)) - { - return n; - } - else - { - ParseTree *lhs = n->left(); - ParseTree *rhs = n->right(); - if (lhs) - n->left(setDerivedFilter(lhs, filterMap, derivedTbList)); - if (rhs) - n->right(setDerivedFilter(rhs, filterMap, derivedTbList)); - } - } - return n; -} - -FromSubQuery::FromSubQuery(gp_walk_info& gwip) : SubQuery(gwip) +FromSubQuery::FromSubQuery(gp_walk_info& gwip) : SubQuery(gwip) {} FromSubQuery::FromSubQuery(gp_walk_info& gwip, SELECT_LEX* sub) : @@ -291,20 +51,19 @@ SCSEP FromSubQuery::transform() { assert (fFromSub); SCSEP csep(new CalpontSelectExecutionPlan()); - csep->sessionID(fGwip.sessionid); + csep->sessionID(fGwip.sessionid); csep->location(CalpontSelectExecutionPlan::FROM); csep->subType (CalpontSelectExecutionPlan::FROM_SUBS); - + // gwi for the sub query gp_walk_info gwi; gwi.thd = fGwip.thd; gwi.subQuery = this; gwi.viewName = fGwip.viewName; - csep->derivedTbAlias(fAlias); // always lower case if (getSelectPlan(gwi, *fFromSub, csep) != 0) { - fGwip.fatalParseError = true; + fGwip.fatalParseError = true; if (!gwi.parseErrorText.empty()) fGwip.parseErrorText = gwi.parseErrorText; else @@ -312,8 +71,8 @@ SCSEP FromSubQuery::transform() csep.reset(); return csep; } - fGwip.subselectList.push_back(csep); - return csep; + csep->derivedTbAlias(fAlias); // always lower case + return csep; } } diff --git a/dbcon/mysql/ha_in_sub.cpp b/dbcon/mysql/ha_in_sub.cpp index c443eb43..d18ebf5f 100644 --- a/dbcon/mysql/ha_in_sub.cpp +++ b/dbcon/mysql/ha_in_sub.cpp @@ -57,7 +57,7 @@ void makeAntiJoin(const ParseTree* n) if (!sf) return; uint64_t lJoinInfo = sf->lhs()->joinInfo(); - + if (lJoinInfo & JOIN_SEMI) { lJoinInfo &= ~JOIN_SEMI; @@ -77,7 +77,7 @@ void makeAntiJoin(const ParseTree* n) } } -InSub::InSub(gp_walk_info& gwip) : WhereSubQuery(gwip) +InSub::InSub(gp_walk_info& gwip) : WhereSubQuery(gwip) {} InSub::InSub(gp_walk_info& gwip, Item_func* func) : @@ -109,31 +109,31 @@ execplan::ParseTree* InSub::transform() fGwip.parseErrorText = "Unsupported item in IN subquery"; return NULL; } - + ReturnedColumn* rhs = fGwip.rcWorkStack.top(); fGwip.rcWorkStack.pop(); delete rhs; ReturnedColumn* lhs = fGwip.rcWorkStack.top(); - fGwip.rcWorkStack.pop(); - delete lhs; - + fGwip.rcWorkStack.pop(); + delete lhs; + fSub = (Item_subselect*)(fFunc->arguments()[1]); idbassert(fSub && fFunc); - + SCSEP csep (new CalpontSelectExecutionPlan()); - csep->sessionID(fGwip.sessionid); + csep->sessionID(fGwip.sessionid); csep->location(CalpontSelectExecutionPlan::WHERE); csep->subType (CalpontSelectExecutionPlan::IN_SUBS); - + // gwi for the sub query gp_walk_info gwi; gwi.thd = fGwip.thd; gwi.subQuery = this; - + // @4827 merge table list to gwi in case there is FROM sub to be referenced // in the FROM sub - gwi.derivedTbCnt = fGwip.derivedTbList.size(); - uint32_t tbCnt = fGwip.tbList.size(); + uint derivedTbCnt = fGwip.derivedTbList.size(); + uint tbCnt = fGwip.tbList.size(); gwi.tbList.insert(gwi.tbList.begin(), fGwip.tbList.begin(), fGwip.tbList.end()); gwi.derivedTbList.insert(gwi.derivedTbList.begin(), fGwip.derivedTbList.begin(), fGwip.derivedTbList.end()); @@ -147,23 +147,21 @@ execplan::ParseTree* InSub::transform() fGwip.parseErrorText = "Error occured in InSub::transform()"; return NULL; } - + // remove outer query tables CalpontSelectExecutionPlan::TableList tblist; if (csep->tableList().size() >= tbCnt) tblist.insert(tblist.begin(),csep->tableList().begin()+tbCnt, csep->tableList().end()); CalpontSelectExecutionPlan::SelectList derivedTbList; - if (csep->derivedTableList().size() >= gwi.derivedTbCnt) - derivedTbList.insert(derivedTbList.begin(), - csep->derivedTableList().begin()+gwi.derivedTbCnt, - csep->derivedTableList().end()); - + if (csep->derivedTableList().size() >= derivedTbCnt) + derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+derivedTbCnt, csep->derivedTableList().end()); + csep->tableList(tblist); csep->derivedTableList(derivedTbList); - + ExistsFilter *subFilter = new ExistsFilter(); subFilter->sub(csep); - + if (gwi.subQuery->correlated()) subFilter->correlated(true); else @@ -173,9 +171,8 @@ execplan::ParseTree* InSub::transform() fGwip.fatalParseError = true; fGwip.parseErrorText = logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_NON_SUPPORT_HAVING); } - - fGwip.subselectList.push_back(csep); - return new ParseTree(subFilter); + + return new ParseTree(subFilter); } /** @@ -196,7 +193,7 @@ void InSub::handleFunc(gp_walk_info* gwip, Item_func* func) return; } Item_cond* cond; - + if (func->functype() == Item_func::TRIG_COND_FUNC) { Item* item; @@ -233,9 +230,9 @@ void InSub::handleFunc(gp_walk_info* gwip, Item_func* func) //idbassert(sf && sf->op()->op() == execplan::OP_EQ); if (!sf || sf->op()->op() != execplan::OP_EQ) return; - + // set NULLMATCH for both operand. It's really a setting for the join. - // should only set NULLMATCH when the subtype is NOT_IN. for some IN subquery + // should only set NULLMATCH when the subtype is NOT_IN. for some IN subquery // with aggregation column, MySQL inefficiently convert to: // (cache=item or item is null) and item is not null, which is equivalent to // cache = item. Do not set NULLMATCH for this case. @@ -259,7 +256,7 @@ void InSub::handleFunc(gp_walk_info* gwip, Item_func* func) SimpleFilter *sf = dynamic_cast(pt->data()); if (!sf || sf->op()->op() != execplan::OP_EQ) return; - + if (sf->lhs()->joinInfo() & JOIN_CORRELATED) sf->lhs()->joinInfo(sf->lhs()->joinInfo() | JOIN_NULLMATCH_CANDIDATE); if (sf->rhs()->joinInfo() & JOIN_CORRELATED) diff --git a/dbcon/mysql/ha_pseudocolumn.cpp b/dbcon/mysql/ha_pseudocolumn.cpp deleted file mode 100644 index b29b3061..00000000 --- a/dbcon/mysql/ha_pseudocolumn.cpp +++ /dev/null @@ -1,574 +0,0 @@ -#include -#include -#include -using namespace std; - -#include "idb_mysql.h" - -#include "errorids.h" -#include "idberrorinfo.h" -#include "exceptclasses.h" -using namespace logging; - -#include "pseudocolumn.h" -#include "functioncolumn.h" -#include "constantcolumn.h" -using namespace execplan; - -#include "functor.h" -#include "functor_str.h" - -#include "ha_calpont_impl_if.h" -using namespace cal_impl_if; - -namespace { - -/******************************************************************************* - * Pseudo column connector interface - * - * idbdbroot - * idbpm - * idbextentrelativerid - * idbsegmentdir - * idbsegment - * idbpartition - * idbextentmin - * idbextentmax - * idbextentid - * idbblockid - * - * All the pseudo column functions are only executed in InfiniDB. - */ - -void bailout(char* error, const string& funcName) -{ - string errMsg = IDBErrorInfo::instance()->errorMsg(ERR_PSEUDOCOL_IDB_ONLY, funcName); - current_thd->main_da.can_overwrite_status = true; - current_thd->main_da.set_error_status(current_thd, HA_ERR_INTERNAL_ERROR, errMsg.c_str()); - *error = 1; -} - -int64_t idblocalpm() -{ - THD* thd = current_thd; - if (!thd->infinidb_vtable.cal_conn_info) - thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(thd->infinidb_vtable.cal_conn_info); - - if (ci->localPm == -1) - { - string module = ClientRotator::getModule(); - if (module.size() >= 3 && (module[0] == 'p' || module[0] == 'P')) - ci->localPm = atol(module.c_str()+2); - else - ci->localPm = 0; - } - return ci->localPm; -} - -extern "C" -{ -/** - * IDBDBROOT - */ -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbdbroot_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbdbroot() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbdbroot_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbdbroot(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbdbroot"); - return 0; -} - -/** - * IDBPM - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbpm_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbpm() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbpm_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbpm(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbpm"); - return 0; -} - -/** - * IDBEXTENTRELATIVERID - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbextentrelativerid_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbextentrelativerid() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbextentrelativerid_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbextentrelativerid(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbextentrelativerid"); - return 0; -} - -/** - * IDBBLOCKID - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbblockid_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbblockid() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbblockid_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbblockid(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbblockid"); - return 0; -} - -/** - * IDBEXTENTID - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbextentid_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbextentid() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbextentid_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbextentid(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbextentid"); - return 0; -} - -/** - * IDBSEGMENT - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbsegment_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbsegment() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbsegment_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbsegment(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbsegment"); - return 0; -} - -/** - * IDBSEGMENTDIR - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbsegmentdir_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbsegmentdir() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbsegmentdir_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idbsegmentdir(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - bailout(error, "idbsegmentdir"); - return 0; -} - -/** - * IDBPARTITION - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbpartition_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbpartition() requires one argument"); - return 1; - } - - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbpartition_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -const char* idbpartition(UDF_INIT* initid, UDF_ARGS* args, - char* result, unsigned long* length, - char* is_null, char* error) -{ - bailout(error, "idbpartition"); - return result; -} - -/** - * IDBEXTENTMIN - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbextentmin_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbpm() requires one argument"); - return 1; - } - initid->maybe_null = 1; - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbextentmin_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -const char* idbextentmin(UDF_INIT* initid, UDF_ARGS* args, - char* result, unsigned long* length, - char* is_null, char* error) -{ - bailout(error, "idbextentmin"); - return result; -} - -/** - * IDBEXTENTMAX - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idbextentmax_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 1) - { - strcpy(message,"idbextentmax() requires one argument"); - return 1; - } - initid->maybe_null = 1; - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idbextentmax_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -const char* idbextentmax(UDF_INIT* initid, UDF_ARGS* args, - char* result, unsigned long* length, - char* is_null, char* error) -{ - bailout(error, "idbextentmax"); - return result; -} - -/** - * IDBLOCALPM - */ - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -my_bool idblocalpm_init(UDF_INIT* initid, UDF_ARGS* args, char* message) -{ - if (args->arg_count != 0) - { - strcpy(message,"idblocalpm() should take no argument"); - return 1; - } - initid->maybe_null = 1; - return 0; -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -void idblocalpm_deinit(UDF_INIT* initid) -{ -} - -#ifdef _MSC_VER -__declspec(dllexport) -#endif -long long idblocalpm(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) -{ - longlong localpm = idblocalpm(); - if (localpm == 0) - *is_null = 1; - return localpm; -} - -} - -} - -namespace cal_impl_if { - -ReturnedColumn* nullOnError(gp_walk_info& gwi, string& funcName) -{ - gwi.fatalParseError = true; - gwi.parseErrorText = - logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_PSEUDOCOL_WRONG_ARG, funcName); - return NULL; -} - -uint32_t isPseudoColumn(string funcName) -{ - return execplan::PseudoColumn::pseudoNameToType(funcName); -} - -execplan::ReturnedColumn* buildPseudoColumn(Item* item, - gp_walk_info& gwi, - bool& nonSupport, - uint32_t pseudoType) -{ - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - - Item_func* ifp = (Item_func*)item; - - // idblocalpm is replaced by constant - if (pseudoType == PSEUDO_LOCALPM) - { - int64_t localPm = idblocalpm(); - ConstantColumn* cc; - if (localPm) - cc = new ConstantColumn(localPm); - else - cc = new ConstantColumn("", ConstantColumn::NULLDATA); - cc->alias(ifp->name? ifp->name : ""); - return cc; - } - - // convert udf item to pseudocolumn item. - // adjust result type - // put arg col to column map - string funcName = ifp->func_name(); - if (ifp->arg_count != 1 || - !(ifp->arguments()) || - !(ifp->arguments()[0]) || - ifp->arguments()[0]->type() != Item::FIELD_ITEM) - return nullOnError(gwi, funcName); - - Item_field* field = (Item_field*)(ifp->arguments()[0]); - - // @todo rule out derive table - if (!field->field || !field->db_name || strlen(field->db_name) == 0) - return nullOnError(gwi, funcName); - - SimpleColumn *sc = buildSimpleColumn(field, gwi); - if (!sc) - return nullOnError(gwi, funcName); - - if ((pseudoType == PSEUDO_EXTENTMIN || pseudoType == PSEUDO_EXTENTMAX) && - (sc->colType().colDataType == CalpontSystemCatalog::VARBINARY || - (sc->colType().colDataType == CalpontSystemCatalog::VARCHAR && sc->colType().colWidth > 7) || - (sc->colType().colDataType == CalpontSystemCatalog::CHAR && sc->colType().colWidth > 8))) - return nullOnError(gwi, funcName); - - // put arg col to column map - if (gwi.clauseType == SELECT || gwi.clauseType == GROUP_BY) // select clause - { - SRCP srcp(sc); - gwi.columnMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(sc->columnName(), srcp)); - gwi.tableMap[make_aliastable(sc->schemaName(), sc->tableName(), sc->tableAlias(), sc->isInfiniDB())] = - make_pair(1, field->cached_table); - } - else if (!gwi.rcWorkStack.empty()) - { - gwi.rcWorkStack.pop(); - } - - if (pseudoType == PSEUDO_PARTITION) - { - // parms: psueducolumn dbroot, segmentdir, segment - SPTP sptp; - FunctionColumn *fc = new FunctionColumn(funcName); - funcexp::FunctionParm parms; - PseudoColumn *dbroot = new PseudoColumn(*sc, PSEUDO_DBROOT); - sptp.reset(new ParseTree(dbroot)); - parms.push_back(sptp); - PseudoColumn *pp = new PseudoColumn(*sc, PSEUDO_SEGMENTDIR); - sptp.reset(new ParseTree(pp)); - parms.push_back(sptp); - PseudoColumn* seg = new PseudoColumn(*sc, PSEUDO_SEGMENT); - sptp.reset(new ParseTree(seg)); - parms.push_back(sptp); - fc->functionParms(parms); - fc->expressionId(ci->expressionId++); - - // string result type - CalpontSystemCatalog::ColType ct; - ct.colDataType = CalpontSystemCatalog::VARCHAR; - ct.colWidth = 256; - fc->resultType(ct); - - // operation type integer - funcexp::Func_idbpartition* idbpartition = new funcexp::Func_idbpartition(); - fc->operationType(idbpartition->operationType(parms, fc->resultType())); - fc->alias(ifp->name? ifp->name : ""); - return fc; - } - - PseudoColumn *pc = new PseudoColumn(*sc, pseudoType); - - // @bug5892. set alias for derived table column matching. - pc->alias(ifp->name? ifp->name : ""); - return pc; -} - -} -// vim:ts=4 sw=4: - diff --git a/dbcon/mysql/ha_scalar_sub.cpp b/dbcon/mysql/ha_scalar_sub.cpp index bb49a917..258ea6dc 100644 --- a/dbcon/mysql/ha_scalar_sub.cpp +++ b/dbcon/mysql/ha_scalar_sub.cpp @@ -80,7 +80,7 @@ execplan::ParseTree* ScalarSub::transform() return transform_between(); if (fFunc->functype() == Item_func::IN_FUNC) return transform_in(); - + ReturnedColumn* rhs = NULL; ReturnedColumn* lhs = NULL; if (!fGwip.rcWorkStack.empty()) @@ -94,8 +94,8 @@ execplan::ParseTree* ScalarSub::transform() fGwip.rcWorkStack.pop(); } - PredicateOperator *op = new PredicateOperator(fFunc->func_name()); - if (!lhs && (fFunc->functype() == Item_func::ISNULL_FUNC || + PredicateOperator *op = new PredicateOperator(fFunc->func_name()); + if (!lhs && (fFunc->functype() == Item_func::ISNULL_FUNC || fFunc->functype() == Item_func::ISNOTNULL_FUNC)) { fSub = (Item_subselect*)(fFunc->arguments()[0]); @@ -103,22 +103,22 @@ execplan::ParseTree* ScalarSub::transform() delete rhs; return buildParseTree(op); } - + bool reverseOp = false; SubSelect* sub = dynamic_cast(rhs); if (!sub) { reverseOp = true; delete lhs; - lhs = rhs; - fSub = (Item_subselect*)(fFunc->arguments()[0]); + lhs = rhs; + fSub = (Item_subselect*)(fFunc->arguments()[0]); } else { delete rhs; fSub = (Item_subselect*)(fFunc->arguments()[1]); } - fColumn.reset(lhs); // column should be in the stack already. in, between may be different + fColumn.reset(lhs); // column should be in the stack already. in, between may be different //PredicateOperator *op = new PredicateOperator(fFunc->func_name()); if (reverseOp) op->reverseOp(); @@ -142,12 +142,12 @@ execplan::ParseTree* ScalarSub::transform_between() ReturnedColumn* op1 = fGwip.rcWorkStack.top(); fGwip.rcWorkStack.pop(); fColumn.reset(op1); - + ParseTree* lhs = NULL; ParseTree* rhs = NULL; PredicateOperator* op_LE = new PredicateOperator("<="); PredicateOperator* op_GE = new PredicateOperator(">="); - + SubSelect* sub2 = dynamic_cast(op3); fSub = (Item_subselect*)(fFunc->arguments()[2]); if (sub2) @@ -161,7 +161,7 @@ execplan::ParseTree* ScalarSub::transform_between() sop.reset(op_LE); rhs = new ParseTree(new SimpleFilter(sop, fColumn.get(), op3)); } - + SubSelect* sub1 = dynamic_cast(op2); fSub = (Item_subselect*)(fFunc->arguments()[1]); if (sub1) @@ -175,7 +175,7 @@ execplan::ParseTree* ScalarSub::transform_between() sop.reset(op_GE); lhs = new ParseTree(new SimpleFilter(sop, fColumn.get(), op2)); } - + if (!rhs || !lhs) { fGwip.fatalParseError = true; @@ -199,7 +199,7 @@ execplan::ParseTree* ScalarSub::transform_in() execplan::ParseTree* ScalarSub::buildParseTree(PredicateOperator* op) { idbassert(fColumn.get() && fSub && fFunc); - + vector cols; Filter *filter; RowColumn* rcol = dynamic_cast(fColumn.get()); @@ -216,25 +216,25 @@ execplan::ParseTree* ScalarSub::buildParseTree(PredicateOperator* op) } else cols.push_back(fColumn); - + SCSEP csep(new CalpontSelectExecutionPlan()); csep->sessionID(fGwip.sessionid); csep->location(CalpontSelectExecutionPlan::WHERE); csep->subType (CalpontSelectExecutionPlan::SINGLEROW_SUBS); - + // gwi for the sub query gp_walk_info gwi; gwi.thd = fGwip.thd; gwi.subQuery = this; - + // @4827 merge table list to gwi in case there is FROM sub to be referenced // in the FROM sub - gwi.derivedTbCnt = fGwip.derivedTbList.size(); - uint32_t tbCnt = fGwip.tbList.size(); + uint derivedTbCnt = fGwip.derivedTbList.size(); + uint tbCnt = fGwip.tbList.size(); gwi.tbList.insert(gwi.tbList.begin(), fGwip.tbList.begin(), fGwip.tbList.end()); gwi.derivedTbList.insert(gwi.derivedTbList.begin(), fGwip.derivedTbList.begin(), fGwip.derivedTbList.end()); - + if (getSelectPlan(gwi, *(fSub->get_select_lex()), csep) != 0) { //@todo more in error handling @@ -250,19 +250,18 @@ execplan::ParseTree* ScalarSub::buildParseTree(PredicateOperator* op) } return NULL; } - fGwip.subselectList.push_back(csep); - + // error out non-support case for now: comparison out of semi join tables. // only check for simplecolumn if (!gwi.correlatedTbNameVec.empty()) { - for (uint32_t i = 0; i < cols.size(); i++) + for (uint i = 0; i < cols.size(); i++) { SimpleColumn* sc = dynamic_cast(cols[i].get()); if (sc) { CalpontSystemCatalog::TableAliasName tan = make_aliastable(sc->schemaName(), sc->tableName(), sc->tableAlias()); - uint32_t j = 0; + uint j = 0; for (; j < gwi.correlatedTbNameVec.size(); j++) if (tan == gwi.correlatedTbNameVec[j]) break; @@ -275,18 +274,18 @@ execplan::ParseTree* ScalarSub::buildParseTree(PredicateOperator* op) } } } - + // remove outer query tables CalpontSelectExecutionPlan::TableList tblist; if (csep->tableList().size() >= tbCnt) tblist.insert(tblist.begin(),csep->tableList().begin()+tbCnt, csep->tableList().end()); CalpontSelectExecutionPlan::SelectList derivedTbList; - if (csep->derivedTableList().size() >= gwi.derivedTbCnt) - derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+gwi.derivedTbCnt, csep->derivedTableList().end()); - + if (csep->derivedTableList().size() >= derivedTbCnt) + derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+derivedTbCnt, csep->derivedTableList().end()); + csep->tableList(tblist); csep->derivedTableList(derivedTbList); - + if (fSub->is_correlated) { SelectFilter *subFilter = new SelectFilter(); @@ -305,8 +304,8 @@ execplan::ParseTree* ScalarSub::buildParseTree(PredicateOperator* op) subFilter->op(SOP(op)); filter = subFilter; } - return new ParseTree(filter); - + return new ParseTree(filter); + } } diff --git a/dbcon/mysql/ha_select_sub.cpp b/dbcon/mysql/ha_select_sub.cpp index 8f40b563..1f25daca 100644 --- a/dbcon/mysql/ha_select_sub.cpp +++ b/dbcon/mysql/ha_select_sub.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ha_select_sub.cpp 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: ha_select_sub.cpp 9010 2012-10-19 18:40:12Z zzhu $ * * ***********************************************************************/ @@ -59,9 +59,9 @@ SCSEP SelectSubQuery::transform() { idbassert(fSelSub); SCSEP csep(new CalpontSelectExecutionPlan()); - csep->sessionID(fGwip.sessionid); + csep->sessionID(fGwip.sessionid); csep->subType (CalpontSelectExecutionPlan::SELECT_SUBS); - + // gwi for the sub query gp_walk_info gwi; gwi.thd = fGwip.thd; @@ -69,9 +69,9 @@ SCSEP SelectSubQuery::transform() // @4632 merge table list to gwi in case there is FROM sub to be referenced // in the SELECT sub - gwi.derivedTbCnt = fGwip.derivedTbList.size(); - uint32_t tbCnt = fGwip.tbList.size(); - + uint derivedTbCnt = fGwip.derivedTbList.size(); + uint tbCnt = fGwip.tbList.size(); + gwi.tbList.insert(gwi.tbList.begin(), fGwip.tbList.begin(), fGwip.tbList.end()); gwi.derivedTbList.insert(gwi.derivedTbList.begin(), fGwip.derivedTbList.begin(), fGwip.derivedTbList.end()); @@ -90,20 +90,16 @@ SCSEP SelectSubQuery::transform() csep.reset(); return csep; } - - fGwip.subselectList.push_back(csep); - // remove outer query tables CalpontSelectExecutionPlan::TableList tblist; if (csep->tableList().size() >= tbCnt) tblist.insert(tblist.begin(),csep->tableList().begin()+tbCnt, csep->tableList().end()); CalpontSelectExecutionPlan::SelectList derivedTbList; - - if (csep->derivedTableList().size() >= gwi.derivedTbCnt) - derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+gwi.derivedTbCnt, csep->derivedTableList().end()); + if (csep->derivedTableList().size() >= derivedTbCnt) + derivedTbList.insert(derivedTbList.begin(), csep->derivedTableList().begin()+derivedTbCnt, csep->derivedTableList().end()); csep->tableList(tblist); csep->derivedTableList(derivedTbList); - return csep; + return csep; } } diff --git a/dbcon/mysql/ha_view.cpp b/dbcon/mysql/ha_view.cpp index 33e0d61f..b8446e15 100644 --- a/dbcon/mysql/ha_view.cpp +++ b/dbcon/mysql/ha_view.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ha_view.cpp 9642 2013-06-24 14:57:42Z rdempsey $ +* $Id: ha_view.cpp 9010 2012-10-19 18:40:12Z zzhu $ * * ***********************************************************************/ @@ -42,7 +42,7 @@ using namespace execplan; namespace cal_impl_if { -extern uint32_t buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex); +extern uint buildOuterJoin(gp_walk_info& gwi, SELECT_LEX& select_lex); extern string getViewName(TABLE_LIST* table_ptr); CalpontSystemCatalog::TableAliasName& View::viewName() @@ -62,7 +62,12 @@ void View::transform() // gwi for the sub query gp_walk_info gwi; - gwi.thd = fParentGwip->thd; + gwi.thd = fParentGwip->thd; + + JOIN* join = fSelect.join; + Item_cond* icp = 0; + if (join != 0) + icp = reinterpret_cast(join->conds); uint32_t sessionID = csep->sessionID(); gwi.sessionid = sessionID; diff --git a/dbcon/mysql/ha_view.h b/dbcon/mysql/ha_view.h index ef18d3a9..376a6712 100644 --- a/dbcon/mysql/ha_view.h +++ b/dbcon/mysql/ha_view.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: ha_view.h 9210 2013-01-21 14:10:42Z rdempsey $ +* $Id: ha_view.h 8436 2012-04-04 18:18:21Z rdempsey $ * * ***********************************************************************/ diff --git a/dbcon/mysql/ha_window_function.cpp b/dbcon/mysql/ha_window_function.cpp deleted file mode 100644 index 4d5076b0..00000000 --- a/dbcon/mysql/ha_window_function.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** -* $Id: ha_window_function.cpp 9586 2013-05-31 22:02:06Z zzhu $ -* -* -***********************************************************************/ -#include -#include -using namespace std; - -#include "idb_mysql.h" -#include "ha_calpont_impl_if.h" - -#include "arithmeticcolumn.h" -#include "arithmeticoperator.h" -#include "constantcolumn.h" -#include "functioncolumn.h" -#include "intervalcolumn.h" -#include "windowfunctioncolumn.h" -using namespace execplan; - -#include "idberrorinfo.h" -#include "errorids.h" -using namespace logging; - -#include "functor.h" -#include "funcexp.h" -using namespace funcexp; - -namespace cal_impl_if { - -ReturnedColumn* nullOnError(gp_walk_info& gwi) -{ - if (gwi.hasSubSelect) - { - gwi.parseErrorText = logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_NON_SUPPORT_SELECT_SUB); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); - } - - if (gwi.parseErrorText.empty()) - { - gwi.parseErrorText = logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_WF_NON_SUPPORT); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); - } - return NULL; -} - -WF_FRAME frame(BOUND& bound) -{ - switch (bound) - { - case PRECEDING: - return WF_PRECEDING; - case FOLLOWING: - return WF_FOLLOWING; - case UNBOUNDED_PRECEDING: - return WF_UNBOUNDED_PRECEDING; - case UNBOUNDED_FOLLOWING: - return WF_UNBOUNDED_FOLLOWING; - case CURRENT_ROW: - return WF_CURRENT_ROW; - default: - return WF_UNKNOWN; - } -} - -ReturnedColumn* buildBoundExp(WF_Boundary& bound, SRCP& order, gp_walk_info& gwi) -{ - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - - bool addOp = true; - ReturnedColumn* rc = NULL; - if (bound.fFrame == execplan::WF_PRECEDING) - { - if (order->asc()) - addOp = false; - } - else if (!order->asc()) // must be WF_FOLLOWING - addOp = false; - - funcexp::FunctionParm funcParms; - SPTP sptp; - IntervalColumn* intervalCol = dynamic_cast(bound.fVal.get()); - // @todo error out non constant. only support literal interval for now. - if (!intervalCol && order->resultType().colDataType == CalpontSystemCatalog::DATE) - { - intervalCol = new IntervalColumn(bound.fVal, (int)IntervalColumn::INTERVAL_DAY); - bound.fVal.reset(intervalCol); - } - - if (intervalCol) - { - // date_add - rc = new FunctionColumn(); - string funcName = "date_add_interval"; - - // @bug6061 . YEAR, QUARTER, MONTH, WEEK, DAY type - CalpontSystemCatalog::ColType ct; - if (order->resultType().colDataType == CalpontSystemCatalog::DATE && - intervalCol->intervalType() <= IntervalColumn::INTERVAL_DAY) - { - ct.colDataType = CalpontSystemCatalog::DATE; - ct.colWidth = 4; - } - else - { - ct.colDataType = CalpontSystemCatalog::DATETIME; - ct.colWidth = 8; - } - // put interval val column to bound - (dynamic_cast(rc))->functionName(funcName); - sptp.reset(new ParseTree(order->clone())); - funcParms.push_back(sptp); - sptp.reset(new ParseTree(intervalCol->val()->clone())); - funcParms.push_back(sptp); - funcParms.push_back(getIntervalType(intervalCol->intervalType())); - SRCP srcp(intervalCol->val()); - bound.fVal = srcp; - if (addOp) - { - sptp.reset(new ParseTree(new ConstantColumn("ADD"))); - funcParms.push_back(sptp); - } - else - { - sptp.reset(new ParseTree(new ConstantColumn("SUB"))); - funcParms.push_back(sptp); - } - (dynamic_cast(rc))->functionParms(funcParms); - - rc->resultType(ct); - // @bug6061. Use result type as operation type for WF bound expression - rc->operationType(ct); - rc->expressionId(ci->expressionId++); - return rc; - } - - // arithmetic - rc = new ArithmeticColumn(); - ArithmeticOperator* aop; - if (addOp) - aop = new ArithmeticOperator("+"); - else - aop = new ArithmeticOperator("-"); - ParseTree *pt = new ParseTree(aop); - ParseTree *lhs = 0, *rhs = 0; - lhs = new ParseTree(order->clone()); - rhs = new ParseTree(bound.fVal->clone()); - pt->left(lhs); - pt->right(rhs); - aop->resultType(order->resultType()); - aop->operationType(aop->resultType()); - (dynamic_cast(rc))->expression(pt); - rc->resultType(aop->resultType()); - rc->operationType(aop->operationType()); - rc->expressionId(ci->expressionId++); - return rc; -} - -ReturnedColumn* buildWindowFunctionColumn(Item* item, gp_walk_info& gwi, bool& nonSupport) -{ - //@todo fix print for create view - //String str; - //item->print(&str, QT_INFINIDB_NO_QUOTE); - //cout << str.c_ptr() << endl; - if (!(gwi.thd->infinidb_vtable.cal_conn_info)) - gwi.thd->infinidb_vtable.cal_conn_info = (void*)(new cal_connection_info()); - cal_connection_info* ci = reinterpret_cast(gwi.thd->infinidb_vtable.cal_conn_info); - - gwi.hasWindowFunc = true; - Item_func_window* wf = (Item_func_window*)item; - string funcName = wf->func_name(); - WindowFunctionColumn* ac = new WindowFunctionColumn(funcName); - ac->distinct(wf->isDistinct()); - Window_context *wf_ctx = wf->window_ctx(); - SRCP srcp; - - // arguments - vector funcParms; - for (uint32_t i = 0; i < wf->arg_count; i++) - { - srcp.reset(buildReturnedColumn(wf->arguments()[i], gwi, nonSupport)); - if (!srcp) - return nullOnError(gwi); - funcParms.push_back(srcp); - if (gwi.clauseType == WHERE && !gwi.rcWorkStack.empty()) - gwi.rcWorkStack.pop(); - } - ac->functionParms(funcParms); - - // Partition by - if (wf_ctx) - { - vector partitions; - for (uint32_t i = 0; i < wf_ctx->partition_count; i++) - { - srcp.reset(buildReturnedColumn(wf_ctx->partitions[i], gwi, nonSupport)); - if (!srcp) - return nullOnError(gwi); - partitions.push_back(srcp); - } - ac->partitions(partitions); - - // Order by - if (wf_ctx->ordering) - { - WF_OrderBy orderBy; - // order columns - if (wf_ctx->ordering->orders) - { - vector orders; - ORDER* orderCol = reinterpret_cast(wf_ctx->ordering->orders->first); - for (; orderCol; orderCol= orderCol->next) - { - Item* orderItem = *(orderCol->item); - srcp.reset(buildReturnedColumn(orderItem, gwi, nonSupport)); - if (!srcp) - return nullOnError(gwi); - srcp->asc(orderCol->asc); - srcp->nullsFirst(orderCol->nulls); // nulls 1-nulls first 0-nulls last - orders.push_back(srcp); - } - orderBy.fOrders = orders; - } - - // window frame - WF_Frame frm; - if (wf_ctx->ordering->frame) - { - frm.fIsRange = wf_ctx->ordering->frame->isRange; - // start - if (wf_ctx->ordering->frame->start) - { - frm.fStart.fFrame = frame(wf_ctx->ordering->frame->start->bound); - - if (wf_ctx->ordering->frame->start->item) - { - frm.fStart.fVal.reset(buildReturnedColumn(wf_ctx->ordering->frame->start->item, gwi, nonSupport)); - if (!frm.fStart.fVal) - return nullOnError(gwi); - - // 1. check expr is numeric type (rows) or interval (range) - bool boundTypeErr = false; - switch (frm.fStart.fVal->resultType().colDataType) - { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::VARBINARY: - case CalpontSystemCatalog::BLOB: - case CalpontSystemCatalog::CLOB: - boundTypeErr = true; - break; - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - if (!frm.fIsRange) - boundTypeErr = true; - else if (dynamic_cast(frm.fStart.fVal.get()) == NULL) - boundTypeErr = true; - break; - default: //okay - break; - } - if (boundTypeErr) - { - gwi.fatalParseError = true; - gwi.parseErrorText = - logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_WF_INVALID_BOUND_TYPE, - colDataTypeToString(frm.fStart.fVal->resultType().colDataType)); - return nullOnError(gwi); - } - } - } - - // end - if (wf_ctx->ordering->frame->end) - { - frm.fEnd.fFrame = frame(wf_ctx->ordering->frame->end->bound); - if (wf_ctx->ordering->frame->end->item) - { - frm.fEnd.fVal.reset(buildReturnedColumn(wf_ctx->ordering->frame->end->item, gwi, nonSupport)); - if (!frm.fEnd.fVal) - return nullOnError(gwi); - - // check expr is numeric type (rows) or interval (range) - bool boundTypeErr = false; - switch (frm.fEnd.fVal->resultType().colDataType) - { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::VARBINARY: - case CalpontSystemCatalog::BLOB: - case CalpontSystemCatalog::CLOB: - boundTypeErr = true; - break; - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - if (!frm.fIsRange) - boundTypeErr = true; - else if (dynamic_cast(frm.fEnd.fVal.get()) == NULL) - boundTypeErr = true; - break; - default: //okay - break; - } - if (boundTypeErr) - { - gwi.fatalParseError = true; - gwi.parseErrorText = - logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_WF_INVALID_BOUND_TYPE, - colDataTypeToString(frm.fStart.fVal->resultType().colDataType)); - return nullOnError(gwi); - } - } - } - else // no end specified. default end to current row - { - frm.fEnd.fFrame = WF_CURRENT_ROW; - } - - if (frm.fStart.fVal || frm.fEnd.fVal) - { - // check order by key only 1 (should be error-ed out in parser. double check here) - if (frm.fIsRange && orderBy.fOrders.size() > 1) - { - gwi.fatalParseError = true; - gwi.parseErrorText = - logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_WF_INVALID_ORDER_KEY); - return nullOnError(gwi); - } - - // check order by key type is numeric or date/datetime - bool orderTypeErr = false; - if (frm.fIsRange && orderBy.fOrders.size() == 1) - { - switch (orderBy.fOrders[0]->resultType().colDataType) - { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::VARBINARY: - case CalpontSystemCatalog::BLOB: - case CalpontSystemCatalog::CLOB: - orderTypeErr = true; - break; - default: //okay - // interval bound has to have date/datetime order key - if ((dynamic_cast(frm.fStart.fVal.get()) != NULL || - dynamic_cast(frm.fEnd.fVal.get()) != NULL)) - { - if (orderBy.fOrders[0]->resultType().colDataType != CalpontSystemCatalog::DATE && - orderBy.fOrders[0]->resultType().colDataType != CalpontSystemCatalog::DATETIME) - orderTypeErr = true; - } - else - { - if (orderBy.fOrders[0]->resultType().colDataType == CalpontSystemCatalog::DATETIME) - orderTypeErr = true; - } - break; - } - if (orderTypeErr) - { - gwi.fatalParseError = true; - gwi.parseErrorText = - logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_WF_INVALID_ORDER_TYPE, - colDataTypeToString(orderBy.fOrders[0]->resultType().colDataType)); - return nullOnError(gwi); - } - } - } - - // construct +,- or interval function for boundary - if (frm.fIsRange && frm.fStart.fVal) - { - frm.fStart.fBound.reset(buildBoundExp(frm.fStart, orderBy.fOrders[0], gwi)); - if (!frm.fStart.fBound) - return nullOnError(gwi); - } - if (frm.fIsRange && frm.fEnd.fVal) - { - frm.fEnd.fBound.reset(buildBoundExp(frm.fEnd, orderBy.fOrders[0], gwi)); - if (!frm.fEnd.fVal) - return nullOnError(gwi); - } - } - else - { - frm.fStart.fFrame = WF_UNBOUNDED_PRECEDING; - frm.fEnd.fFrame = WF_CURRENT_ROW; - } - - orderBy.fFrame = frm; - ac->orderBy(orderBy); - } - } - - if (gwi.fatalParseError || nonSupport) - { - if (gwi.parseErrorText.empty()) - gwi.parseErrorText = logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_WF_NON_SUPPORT); - setError(gwi.thd, HA_ERR_UNSUPPORTED, gwi.parseErrorText); - return NULL; - } - - ac->resultType(colType_MysqlToIDB(wf)); - - // bug5736. Make the result type double for some window functions when - // infinidb_double_for_decimal_math is set. - ac->adjustResultType(); - - ac->expressionId(ci->expressionId++); - if (item->name) - ac->alias(item->name); - - // put ac on windowFuncList - gwi.windowFuncList.push_back(ac); - return ac; - -} - -} diff --git a/dbcon/mysql/handler.cc b/dbcon/mysql/handler.cc new file mode 100644 index 00000000..14df21a9 --- /dev/null +++ b/dbcon/mysql/handler.cc @@ -0,0 +1,4883 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** @file handler.cc + + @brief + Handler-calling-functions +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include "rpl_filter.h" +#include +#include + +#ifdef WITH_PARTITION_STORAGE_ENGINE +#include "ha_partition.h" +#endif + +/* + While we have legacy_db_type, we have this array to + check for dups and to find handlerton from legacy_db_type. + Remove when legacy_db_type is finally gone +*/ +st_plugin_int *hton2plugin[MAX_HA]; + +static handlerton *installed_htons[128]; + +#define BITMAP_STACKBUF_SIZE (128/8) + +KEY_CREATE_INFO default_key_create_info= { HA_KEY_ALG_UNDEF, 0, {NullS,0} }; + +/* number of entries in handlertons[] */ +ulong total_ha= 0; +/* number of storage engines (from handlertons[]) that support 2pc */ +ulong total_ha_2pc= 0; +/* size of savepoint storage area (see ha_init) */ +ulong savepoint_alloc_size= 0; + +static const LEX_STRING sys_table_aliases[]= +{ + { C_STRING_WITH_LEN("INNOBASE") }, { C_STRING_WITH_LEN("INNODB") }, + { C_STRING_WITH_LEN("NDB") }, { C_STRING_WITH_LEN("NDBCLUSTER") }, + { C_STRING_WITH_LEN("HEAP") }, { C_STRING_WITH_LEN("MEMORY") }, + { C_STRING_WITH_LEN("MERGE") }, { C_STRING_WITH_LEN("MRG_MYISAM") }, + {NullS, 0} +}; + +const char *ha_row_type[] = { + "", "FIXED", "DYNAMIC", "COMPRESSED", "REDUNDANT", "COMPACT", + /* Reserved to be "PAGE" in future versions */ "?", + "?","?","?" +}; + +const char *tx_isolation_names[] = +{ "READ-UNCOMMITTED", "READ-COMMITTED", "REPEATABLE-READ", "SERIALIZABLE", + NullS}; +TYPELIB tx_isolation_typelib= {array_elements(tx_isolation_names)-1,"", + tx_isolation_names, NULL}; + +static TYPELIB known_extensions= {0,"known_exts", NULL, NULL}; +uint known_extensions_id= 0; + + + +static plugin_ref ha_default_plugin(THD *thd) +{ + if (thd->variables.table_plugin) + return thd->variables.table_plugin; + return my_plugin_lock(thd, &global_system_variables.table_plugin); +} + + +/** @brief + Return the default storage engine handlerton for thread + + SYNOPSIS + ha_default_handlerton(thd) + thd current thread + + RETURN + pointer to handlerton +*/ +handlerton *ha_default_handlerton(THD *thd) +{ + plugin_ref plugin= ha_default_plugin(thd); + DBUG_ASSERT(plugin); + handlerton *hton= plugin_data(plugin, handlerton*); + DBUG_ASSERT(hton); + return hton; +} + + +/** @brief + Return the storage engine handlerton for the supplied name + + SYNOPSIS + ha_resolve_by_name(thd, name) + thd current thread + name name of storage engine + + RETURN + pointer to storage engine plugin handle +*/ +plugin_ref ha_resolve_by_name(THD *thd, const LEX_STRING *name) +{ + const LEX_STRING *table_alias; + plugin_ref plugin; + +redo: + /* my_strnncoll is a macro and gcc doesn't do early expansion of macro */ + if (thd && !my_charset_latin1.coll->strnncoll(&my_charset_latin1, + (const uchar *)name->str, name->length, + (const uchar *)STRING_WITH_LEN("DEFAULT"), 0)) + return ha_default_plugin(thd); + + if ((plugin= my_plugin_lock_by_name(thd, name, MYSQL_STORAGE_ENGINE_PLUGIN))) + { + handlerton *hton= plugin_data(plugin, handlerton *); + if (!(hton->flags & HTON_NOT_USER_SELECTABLE)) + return plugin; + + /* + unlocking plugin immediately after locking is relatively low cost. + */ + plugin_unlock(thd, plugin); + } + + /* + We check for the historical aliases. + */ + for (table_alias= sys_table_aliases; table_alias->str; table_alias+= 2) + { + if (!my_strnncoll(&my_charset_latin1, + (const uchar *)name->str, name->length, + (const uchar *)table_alias->str, table_alias->length)) + { + name= table_alias + 1; + goto redo; + } + } + + return NULL; +} + + +plugin_ref ha_lock_engine(THD *thd, handlerton *hton) +{ + if (hton) + { + st_plugin_int **plugin= hton2plugin + hton->slot; + +#ifdef DBUG_OFF + return my_plugin_lock(thd, plugin); +#else + return my_plugin_lock(thd, &plugin); +#endif + } + return NULL; +} + + +#ifdef NOT_USED +static handler *create_default(TABLE_SHARE *table, MEM_ROOT *mem_root) +{ + handlerton *hton= ha_default_handlerton(current_thd); + return (hton && hton->create) ? hton->create(hton, table, mem_root) : NULL; +} +#endif + + +handlerton *ha_resolve_by_legacy_type(THD *thd, enum legacy_db_type db_type) +{ + plugin_ref plugin; + switch (db_type) { + case DB_TYPE_DEFAULT: + return ha_default_handlerton(thd); + default: + if (db_type > DB_TYPE_UNKNOWN && db_type < DB_TYPE_DEFAULT && + (plugin= ha_lock_engine(thd, installed_htons[db_type]))) + return plugin_data(plugin, handlerton*); + /* fall through */ + case DB_TYPE_UNKNOWN: + return NULL; + } +} + + +/** + Use other database handler if databasehandler is not compiled in. +*/ +handlerton *ha_checktype(THD *thd, enum legacy_db_type database_type, + bool no_substitute, bool report_error) +{ + handlerton *hton= ha_resolve_by_legacy_type(thd, database_type); + if (ha_storage_engine_is_enabled(hton)) + return hton; + + if (no_substitute) + { + if (report_error) + { + const char *engine_name= ha_resolve_storage_engine_name(hton); + my_error(ER_FEATURE_DISABLED,MYF(0),engine_name,engine_name); + } + return NULL; + } + + switch (database_type) { +#ifndef NO_HASH + case DB_TYPE_HASH: + return ha_resolve_by_legacy_type(thd, DB_TYPE_HASH); +#endif + case DB_TYPE_MRG_ISAM: + return ha_resolve_by_legacy_type(thd, DB_TYPE_MRG_MYISAM); + default: + break; + } + + return ha_default_handlerton(thd); +} /* ha_checktype */ + + +handler *get_new_handler(TABLE_SHARE *share, MEM_ROOT *alloc, + handlerton *db_type) +{ + handler *file; + DBUG_ENTER("get_new_handler"); + DBUG_PRINT("enter", ("alloc: 0x%lx", (long) alloc)); + + if (db_type && db_type->state == SHOW_OPTION_YES && db_type->create) + { + if ((file= db_type->create(db_type, share, alloc))) + file->init(); + DBUG_RETURN(file); + } + /* + Try the default table type + Here the call to current_thd() is ok as we call this function a lot of + times but we enter this branch very seldom. + */ + DBUG_RETURN(get_new_handler(share, alloc, ha_default_handlerton(current_thd))); +} + + +#ifdef WITH_PARTITION_STORAGE_ENGINE +handler *get_ha_partition(partition_info *part_info) +{ + ha_partition *partition; + DBUG_ENTER("get_ha_partition"); + if ((partition= new ha_partition(partition_hton, part_info))) + { + if (partition->initialize_partition(current_thd->mem_root)) + { + delete partition; + partition= 0; + } + else + partition->init(); + } + else + { + my_error(ER_OUTOFMEMORY, MYF(0), sizeof(ha_partition)); + } + DBUG_RETURN(((handler*) partition)); +} +#endif + + +/** + Register handler error messages for use with my_error(). + + @retval + 0 OK + @retval + !=0 Error +*/ + +int ha_init_errors(void) +{ +#define SETMSG(nr, msg) errmsgs[(nr) - HA_ERR_FIRST]= (msg) + const char **errmsgs; + + /* Allocate a pointer array for the error message strings. */ + /* Zerofill it to avoid uninitialized gaps. */ + if (! (errmsgs= (const char**) my_malloc(HA_ERR_ERRORS * sizeof(char*), + MYF(MY_WME | MY_ZEROFILL)))) + return 1; + + /* Set the dedicated error messages. */ + SETMSG(HA_ERR_KEY_NOT_FOUND, ER(ER_KEY_NOT_FOUND)); + SETMSG(HA_ERR_FOUND_DUPP_KEY, ER(ER_DUP_KEY)); + SETMSG(HA_ERR_RECORD_CHANGED, "Update wich is recoverable"); + SETMSG(HA_ERR_WRONG_INDEX, "Wrong index given to function"); + SETMSG(HA_ERR_CRASHED, ER(ER_NOT_KEYFILE)); + SETMSG(HA_ERR_WRONG_IN_RECORD, ER(ER_CRASHED_ON_USAGE)); + SETMSG(HA_ERR_OUT_OF_MEM, "Table handler out of memory"); + SETMSG(HA_ERR_NOT_A_TABLE, "Incorrect file format '%.64s'"); + SETMSG(HA_ERR_WRONG_COMMAND, "Command not supported"); + SETMSG(HA_ERR_OLD_FILE, ER(ER_OLD_KEYFILE)); + SETMSG(HA_ERR_NO_ACTIVE_RECORD, "No record read in update"); + SETMSG(HA_ERR_RECORD_DELETED, "Intern record deleted"); + SETMSG(HA_ERR_RECORD_FILE_FULL, ER(ER_RECORD_FILE_FULL)); + SETMSG(HA_ERR_INDEX_FILE_FULL, "No more room in index file '%.64s'"); + SETMSG(HA_ERR_END_OF_FILE, "End in next/prev/first/last"); + SETMSG(HA_ERR_UNSUPPORTED, ER(ER_ILLEGAL_HA)); + SETMSG(HA_ERR_TO_BIG_ROW, "Too big row"); + SETMSG(HA_WRONG_CREATE_OPTION, "Wrong create option"); + SETMSG(HA_ERR_FOUND_DUPP_UNIQUE, ER(ER_DUP_UNIQUE)); + SETMSG(HA_ERR_UNKNOWN_CHARSET, "Can't open charset"); + SETMSG(HA_ERR_WRONG_MRG_TABLE_DEF, ER(ER_WRONG_MRG_TABLE)); + SETMSG(HA_ERR_CRASHED_ON_REPAIR, ER(ER_CRASHED_ON_REPAIR)); + SETMSG(HA_ERR_CRASHED_ON_USAGE, ER(ER_CRASHED_ON_USAGE)); + SETMSG(HA_ERR_LOCK_WAIT_TIMEOUT, ER(ER_LOCK_WAIT_TIMEOUT)); + SETMSG(HA_ERR_LOCK_TABLE_FULL, ER(ER_LOCK_TABLE_FULL)); + SETMSG(HA_ERR_READ_ONLY_TRANSACTION, ER(ER_READ_ONLY_TRANSACTION)); + SETMSG(HA_ERR_LOCK_DEADLOCK, ER(ER_LOCK_DEADLOCK)); + SETMSG(HA_ERR_CANNOT_ADD_FOREIGN, ER(ER_CANNOT_ADD_FOREIGN)); + SETMSG(HA_ERR_NO_REFERENCED_ROW, ER(ER_NO_REFERENCED_ROW_2)); + SETMSG(HA_ERR_ROW_IS_REFERENCED, ER(ER_ROW_IS_REFERENCED_2)); + SETMSG(HA_ERR_NO_SAVEPOINT, "No savepoint with that name"); + SETMSG(HA_ERR_NON_UNIQUE_BLOCK_SIZE, "Non unique key block size"); + SETMSG(HA_ERR_NO_SUCH_TABLE, "No such table: '%.64s'"); + SETMSG(HA_ERR_TABLE_EXIST, ER(ER_TABLE_EXISTS_ERROR)); + SETMSG(HA_ERR_NO_CONNECTION, "Could not connect to storage engine"); + SETMSG(HA_ERR_TABLE_DEF_CHANGED, ER(ER_TABLE_DEF_CHANGED)); + SETMSG(HA_ERR_FOREIGN_DUPLICATE_KEY, "FK constraint would lead to duplicate key"); + SETMSG(HA_ERR_TABLE_NEEDS_UPGRADE, ER(ER_TABLE_NEEDS_UPGRADE)); + SETMSG(HA_ERR_TABLE_READONLY, ER(ER_OPEN_AS_READONLY)); + SETMSG(HA_ERR_AUTOINC_READ_FAILED, ER(ER_AUTOINC_READ_FAILED)); + SETMSG(HA_ERR_AUTOINC_ERANGE, ER(ER_WARN_DATA_OUT_OF_RANGE)); + SETMSG(HA_ERR_TOO_MANY_CONCURRENT_TRXS, ER(ER_TOO_MANY_CONCURRENT_TRXS)); + + /* Register the error messages for use with my_error(). */ + return my_error_register(errmsgs, HA_ERR_FIRST, HA_ERR_LAST); +} + + +/** + Unregister handler error messages. + + @retval + 0 OK + @retval + !=0 Error +*/ +static int ha_finish_errors(void) +{ + const char **errmsgs; + + /* Allocate a pointer array for the error message strings. */ + if (! (errmsgs= my_error_unregister(HA_ERR_FIRST, HA_ERR_LAST))) + return 1; + my_free((uchar*) errmsgs, MYF(0)); + return 0; +} + + +int ha_finalize_handlerton(st_plugin_int *plugin) +{ + handlerton *hton= (handlerton *)plugin->data; + DBUG_ENTER("ha_finalize_handlerton"); + + /* hton can be NULL here, if ha_initialize_handlerton() failed. */ + if (!hton) + goto end; + + switch (hton->state) + { + case SHOW_OPTION_NO: + case SHOW_OPTION_DISABLED: + break; + case SHOW_OPTION_YES: + if (installed_htons[hton->db_type] == hton) + installed_htons[hton->db_type]= NULL; + break; + }; + + if (hton->panic) + hton->panic(hton, HA_PANIC_CLOSE); + + if (plugin->plugin->deinit) + { + /* + Today we have no defined/special behavior for uninstalling + engine plugins. + */ + DBUG_PRINT("info", ("Deinitializing plugin: '%s'", plugin->name.str)); + if (plugin->plugin->deinit(NULL)) + { + DBUG_PRINT("warning", ("Plugin '%s' deinit function returned error.", + plugin->name.str)); + } + } + + /* + In case a plugin is uninstalled and re-installed later, it should + reuse an array slot. Otherwise the number of uninstall/install + cycles would be limited. + */ + hton2plugin[hton->slot]= NULL; + + my_free((uchar*)hton, MYF(0)); + + end: + DBUG_RETURN(0); +} + + +int ha_initialize_handlerton(st_plugin_int *plugin) +{ + handlerton *hton; + DBUG_ENTER("ha_initialize_handlerton"); + DBUG_PRINT("plugin", ("initialize plugin: '%s'", plugin->name.str)); + + hton= (handlerton *)my_malloc(sizeof(handlerton), + MYF(MY_WME | MY_ZEROFILL)); + /* Historical Requirement */ + plugin->data= hton; // shortcut for the future + if (plugin->plugin->init && plugin->plugin->init(hton)) + { + sql_print_error("Plugin '%s' init function returned error.", + plugin->name.str); + goto err; + } + + /* + the switch below and hton->state should be removed when + command-line options for plugins will be implemented + */ + switch (hton->state) { + case SHOW_OPTION_NO: + break; + case SHOW_OPTION_YES: + { + uint tmp; + ulong fslot; + /* now check the db_type for conflict */ + if (hton->db_type <= DB_TYPE_UNKNOWN || + hton->db_type >= DB_TYPE_DEFAULT || + installed_htons[hton->db_type]) + { + int idx= (int) DB_TYPE_FIRST_DYNAMIC; + + while (idx < (int) DB_TYPE_DEFAULT && installed_htons[idx]) + idx++; + + if (idx == (int) DB_TYPE_DEFAULT) + { + sql_print_warning("Too many storage engines!"); + goto err_deinit; + } + if (hton->db_type != DB_TYPE_UNKNOWN) + sql_print_warning("Storage engine '%s' has conflicting typecode. " + "Assigning value %d.", plugin->plugin->name, idx); + hton->db_type= (enum legacy_db_type) idx; + } + + /* + In case a plugin is uninstalled and re-installed later, it should + reuse an array slot. Otherwise the number of uninstall/install + cycles would be limited. So look for a free slot. + */ + DBUG_PRINT("plugin", ("total_ha: %lu", total_ha)); + for (fslot= 0; fslot < total_ha; fslot++) + { + if (!hton2plugin[fslot]) + break; + } + if (fslot < total_ha) + hton->slot= fslot; + else + { + if (total_ha >= MAX_HA) + { + sql_print_error("Too many plugins loaded. Limit is %lu. " + "Failed on '%s'", (ulong) MAX_HA, plugin->name.str); + goto err_deinit; + } + hton->slot= total_ha++; + } + installed_htons[hton->db_type]= hton; + tmp= hton->savepoint_offset; + hton->savepoint_offset= savepoint_alloc_size; + savepoint_alloc_size+= tmp; + hton2plugin[hton->slot]=plugin; + if (hton->prepare) + total_ha_2pc++; + break; + } + /* fall through */ + default: + hton->state= SHOW_OPTION_DISABLED; + break; + } + + /* + This is entirely for legacy. We will create a new "disk based" hton and a + "memory" hton which will be configurable longterm. We should be able to + remove partition and myisammrg. + */ + switch (hton->db_type) { + case DB_TYPE_HEAP: + heap_hton= hton; + break; + case DB_TYPE_MYISAM: + myisam_hton= hton; + break; + case DB_TYPE_PARTITION_DB: + partition_hton= hton; + break; + default: + break; + }; + + DBUG_RETURN(0); + +err_deinit: + /* + Let plugin do its inner deinitialization as plugin->init() + was successfully called before. + */ + if (plugin->plugin->deinit) + (void) plugin->plugin->deinit(NULL); + +err: + my_free((uchar*) hton, MYF(0)); + plugin->data= NULL; + DBUG_RETURN(1); +} + +int ha_init() +{ + int error= 0; + DBUG_ENTER("ha_init"); + + DBUG_ASSERT(total_ha < MAX_HA); + /* + Check if there is a transaction-capable storage engine besides the + binary log (which is considered a transaction-capable storage engine in + counting total_ha) + */ + opt_using_transactions= total_ha>(ulong)opt_bin_log; + savepoint_alloc_size+= sizeof(SAVEPOINT); + DBUG_RETURN(error); +} + +int ha_end() +{ + int error= 0; + DBUG_ENTER("ha_end"); + + + /* + This should be eventualy based on the graceful shutdown flag. + So if flag is equal to HA_PANIC_CLOSE, the deallocate + the errors. + */ + if (ha_finish_errors()) + error= 1; + + DBUG_RETURN(error); +} + +static my_bool dropdb_handlerton(THD *unused1, plugin_ref plugin, + void *path) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->drop_database) + hton->drop_database(hton, (char *)path); + return FALSE; +} + + +void ha_drop_database(char* path) +{ + plugin_foreach(NULL, dropdb_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, path); +} + + +static my_bool closecon_handlerton(THD *thd, plugin_ref plugin, + void *unused) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + /* + there's no need to rollback here as all transactions must + be rolled back already + */ + //Not all storage engines can handle a close_connection() on startup, so... + //There's got to be a better way to do this. ha_resolve_by_name() doesn't seem to work. + // @InfiniDB +#if (defined(_MSC_VER) && defined(_DEBUG)) || defined(SAFE_MUTEX) + if ((*plugin)->name.length == 8 && strncmp((*plugin)->name.str, "InfiniDB", 8) == 0) +#else + if (plugin->name.length == 8 && strncmp(plugin->name.str, "InfiniDB", 8) == 0) +#endif + { + if (hton->state == SHOW_OPTION_YES && hton->close_connection) + { + hton->close_connection(hton, thd); + } + } + else + { + if (hton->state == SHOW_OPTION_YES && hton->close_connection && + thd_get_ha_data(thd, hton)) + { + hton->close_connection(hton, thd); + } + } + + return FALSE; +} + + +/** + @note + don't bother to rollback here, it's done already +*/ +void ha_close_connection(THD* thd) +{ + plugin_foreach(thd, closecon_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, 0); +} + +/* ======================================================================== + ======================= TRANSACTIONS ===================================*/ + +/** + Transaction handling in the server + ================================== + + In each client connection, MySQL maintains two transactional + states: + - a statement transaction, + - a standard, also called normal transaction. + + Historical note + --------------- + "Statement transaction" is a non-standard term that comes + from the times when MySQL supported BerkeleyDB storage engine. + + First of all, it should be said that in BerkeleyDB auto-commit + mode auto-commits operations that are atomic to the storage + engine itself, such as a write of a record, and are too + high-granular to be atomic from the application perspective + (MySQL). One SQL statement could involve many BerkeleyDB + auto-committed operations and thus BerkeleyDB auto-commit was of + little use to MySQL. + + Secondly, instead of SQL standard savepoints, BerkeleyDB + provided the concept of "nested transactions". In a nutshell, + transactions could be arbitrarily nested, but when the parent + transaction was committed or aborted, all its child (nested) + transactions were handled committed or aborted as well. + Commit of a nested transaction, in turn, made its changes + visible, but not durable: it destroyed the nested transaction, + all its changes would become available to the parent and + currently active nested transactions of this parent. + + So the mechanism of nested transactions was employed to + provide "all or nothing" guarantee of SQL statements + required by the standard. + A nested transaction would be created at start of each SQL + statement, and destroyed (committed or aborted) at statement + end. Such nested transaction was internally referred to as + a "statement transaction" and gave birth to the term. + + + + Since then a statement transaction is started for each statement + that accesses transactional tables or uses the binary log. If + the statement succeeds, the statement transaction is committed. + If the statement fails, the transaction is rolled back. Commits + of statement transactions are not durable -- each such + transaction is nested in the normal transaction, and if the + normal transaction is rolled back, the effects of all enclosed + statement transactions are undone as well. Technically, + a statement transaction can be viewed as a savepoint which is + maintained automatically in order to make effects of one + statement atomic. + + The normal transaction is started by the user and is ended + usually upon a user request as well. The normal transaction + encloses transactions of all statements issued between + its beginning and its end. + In autocommit mode, the normal transaction is equivalent + to the statement transaction. + + Since MySQL supports PSEA (pluggable storage engine + architecture), more than one transactional engine can be + active at a time. Hence transactions, from the server + point of view, are always distributed. In particular, + transactional state is maintained independently for each + engine. In order to commit a transaction the two phase + commit protocol is employed. + + Not all statements are executed in context of a transaction. + Administrative and status information statements do not modify + engine data, and thus do not start a statement transaction and + also have no effect on the normal transaction. Examples of such + statements are SHOW STATUS and RESET SLAVE. + + Similarly DDL statements are not transactional, + and therefore a transaction is [almost] never started for a DDL + statement. The difference between a DDL statement and a purely + administrative statement though is that a DDL statement always + commits the current transaction before proceeding, if there is + any. + + At last, SQL statements that work with non-transactional + engines also have no effect on the transaction state of the + connection. Even though they are written to the binary log, + and the binary log is, overall, transactional, the writes + are done in "write-through" mode, directly to the binlog + file, followed with a OS cache sync, in other words, + bypassing the binlog undo log (translog). + They do not commit the current normal transaction. + A failure of a statement that uses non-transactional tables + would cause a rollback of the statement transaction, but + in case there no non-transactional tables are used, + no statement transaction is started. + + Data layout + ----------- + + The server stores its transaction-related data in + thd->transaction. This structure has two members of type + THD_TRANS. These members correspond to the statement and + normal transactions respectively: + + - thd->transaction.stmt contains a list of engines + that are participating in the given statement + - thd->transaction.all contains a list of engines that + have participated in any of the statement transactions started + within the context of the normal transaction. + Each element of the list contains a pointer to the storage + engine, engine-specific transactional data, and engine-specific + transaction flags. + + In autocommit mode thd->transaction.all is empty. + Instead, data of thd->transaction.stmt is + used to commit/rollback the normal transaction. + + The list of registered engines has a few important properties: + - no engine is registered in the list twice + - engines are present in the list a reverse temporal order -- + new participants are always added to the beginning of the list. + + Transaction life cycle + ---------------------- + + When a new connection is established, thd->transaction + members are initialized to an empty state. + If a statement uses any tables, all affected engines + are registered in the statement engine list. In + non-autocommit mode, the same engines are registered in + the normal transaction list. + At the end of the statement, the server issues a commit + or a roll back for all engines in the statement list. + At this point transaction flags of an engine, if any, are + propagated from the statement list to the list of the normal + transaction. + When commit/rollback is finished, the statement list is + cleared. It will be filled in again by the next statement, + and emptied again at the next statement's end. + + The normal transaction is committed in a similar way + (by going over all engines in thd->transaction.all list) + but at different times: + - upon COMMIT SQL statement is issued by the user + - implicitly, by the server, at the beginning of a DDL statement + or SET AUTOCOMMIT={0|1} statement. + + The normal transaction can be rolled back as well: + - if the user has requested so, by issuing ROLLBACK SQL + statement + - if one of the storage engines requested a rollback + by setting thd->transaction_rollback_request. This may + happen in case, e.g., when the transaction in the engine was + chosen a victim of the internal deadlock resolution algorithm + and rolled back internally. When such a situation happens, there + is little the server can do and the only option is to rollback + transactions in all other participating engines. In this case + the rollback is accompanied by an error sent to the user. + + As follows from the use cases above, the normal transaction + is never committed when there is an outstanding statement + transaction. In most cases there is no conflict, since + commits of the normal transaction are issued by a stand-alone + administrative or DDL statement, thus no outstanding statement + transaction of the previous statement exists. Besides, + all statements that manipulate with the normal transaction + are prohibited in stored functions and triggers, therefore + no conflicting situation can occur in a sub-statement either. + The remaining rare cases when the server explicitly has + to commit the statement transaction prior to committing the normal + one cover error-handling scenarios (see for example + SQLCOM_LOCK_TABLES). + + When committing a statement or a normal transaction, the server + either uses the two-phase commit protocol, or issues a commit + in each engine independently. The two-phase commit protocol + is used only if: + - all participating engines support two-phase commit (provide + handlerton::prepare PSEA API call) and + - transactions in at least two engines modify data (i.e. are + not read-only). + + Note that the two phase commit is used for + statement transactions, even though they are not durable anyway. + This is done to ensure logical consistency of data in a multiple- + engine transaction. + For example, imagine that some day MySQL supports unique + constraint checks deferred till the end of statement. In such + case a commit in one of the engines may yield ER_DUP_KEY, + and MySQL should be able to gracefully abort statement + transactions of other participants. + + After the normal transaction has been committed, + thd->transaction.all list is cleared. + + When a connection is closed, the current normal transaction, if + any, is rolled back. + + Roles and responsibilities + -------------------------- + + The server has no way to know that an engine participates in + the statement and a transaction has been started + in it unless the engine says so. Thus, in order to be + a part of a transaction, the engine must "register" itself. + This is done by invoking trans_register_ha() server call. + Normally the engine registers itself whenever handler::external_lock() + is called. trans_register_ha() can be invoked many times: if + an engine is already registered, the call does nothing. + In case autocommit is not set, the engine must register itself + twice -- both in the statement list and in the normal transaction + list. + In which list to register is a parameter of trans_register_ha(). + + Note, that although the registration interface in itself is + fairly clear, the current usage practice often leads to undesired + effects. E.g. since a call to trans_register_ha() in most engines + is embedded into implementation of handler::external_lock(), some + DDL statements start a transaction (at least from the server + point of view) even though they are not expected to. E.g. + CREATE TABLE does not start a transaction, since + handler::external_lock() is never called during CREATE TABLE. But + CREATE TABLE ... SELECT does, since handler::external_lock() is + called for the table that is being selected from. This has no + practical effects currently, but must be kept in mind + nevertheless. + + Once an engine is registered, the server will do the rest + of the work. + + During statement execution, whenever any of data-modifying + PSEA API methods is used, e.g. handler::write_row() or + handler::update_row(), the read-write flag is raised in the + statement transaction for the involved engine. + Currently All PSEA calls are "traced", and the data can not be + changed in a way other than issuing a PSEA call. Important: + unless this invariant is preserved the server will not know that + a transaction in a given engine is read-write and will not + involve the two-phase commit protocol! + + At the end of a statement, server call + ha_autocommit_or_rollback() is invoked. This call in turn + invokes handlerton::prepare() for every involved engine. + Prepare is followed by a call to handlerton::commit_one_phase() + If a one-phase commit will suffice, handlerton::prepare() is not + invoked and the server only calls handlerton::commit_one_phase(). + At statement commit, the statement-related read-write engine + flag is propagated to the corresponding flag in the normal + transaction. When the commit is complete, the list of registered + engines is cleared. + + Rollback is handled in a similar fashion. + + Additional notes on DDL and the normal transaction. + --------------------------------------------------- + + DDLs and operations with non-transactional engines + do not "register" in thd->transaction lists, and thus do not + modify the transaction state. Besides, each DDL in + MySQL is prefixed with an implicit normal transaction commit + (a call to end_active_trans()), and thus leaves nothing + to modify. + However, as it has been pointed out with CREATE TABLE .. SELECT, + some DDL statements can start a *new* transaction. + + Behaviour of the server in this case is currently badly + defined. + DDL statements use a form of "semantic" logging + to maintain atomicity: if CREATE TABLE .. SELECT failed, + the newly created table is deleted. + In addition, some DDL statements issue interim transaction + commits: e.g. ALTER TABLE issues a commit after data is copied + from the original table to the internal temporary table. Other + statements, e.g. CREATE TABLE ... SELECT do not always commit + after itself. + And finally there is a group of DDL statements such as + RENAME/DROP TABLE that doesn't start a new transaction + and doesn't commit. + + This diversity makes it hard to say what will happen if + by chance a stored function is invoked during a DDL -- + whether any modifications it makes will be committed or not + is not clear. Fortunately, SQL grammar of few DDLs allows + invocation of a stored function. + + A consistent behaviour is perhaps to always commit the normal + transaction after all DDLs, just like the statement transaction + is always committed at the end of all statements. +*/ + +/** + Register a storage engine for a transaction. + + Every storage engine MUST call this function when it starts + a transaction or a statement (that is it must be called both for the + "beginning of transaction" and "beginning of statement"). + Only storage engines registered for the transaction/statement + will know when to commit/rollback it. + + @note + trans_register_ha is idempotent - storage engine may register many + times per transaction. + +*/ +void trans_register_ha(THD *thd, bool all, handlerton *ht_arg) +{ + THD_TRANS *trans; + Ha_trx_info *ha_info; + DBUG_ENTER("trans_register_ha"); + DBUG_PRINT("enter",("%s", all ? "all" : "stmt")); + + if (all) + { + trans= &thd->transaction.all; + thd->server_status|= SERVER_STATUS_IN_TRANS; + } + else + trans= &thd->transaction.stmt; + + ha_info= thd->ha_data[ht_arg->slot].ha_info + static_cast(all); + + if (ha_info->is_started()) + DBUG_VOID_RETURN; /* already registered, return */ + + ha_info->register_ha(trans, ht_arg); + + trans->no_2pc|=(ht_arg->prepare==0); + if (thd->transaction.xid_state.xid.is_null()) + thd->transaction.xid_state.xid.set(thd->query_id); + DBUG_VOID_RETURN; +} + +/** + @retval + 0 ok + @retval + 1 error, transaction was rolled back +*/ +int ha_prepare(THD *thd) +{ + int error=0, all=1; + THD_TRANS *trans=all ? &thd->transaction.all : &thd->transaction.stmt; + Ha_trx_info *ha_info= trans->ha_list; + DBUG_ENTER("ha_prepare"); +#ifdef USING_TRANSACTIONS + if (ha_info) + { + for (; ha_info; ha_info= ha_info->next()) + { + int err; + handlerton *ht= ha_info->ht(); + status_var_increment(thd->status_var.ha_prepare_count); + if (ht->prepare) + { + if ((err= ht->prepare(ht, thd, all))) + { + my_error(ER_ERROR_DURING_COMMIT, MYF(0), err); + ha_rollback_trans(thd, all); + error=1; + break; + } + } + else + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA), + ha_resolve_storage_engine_name(ht)); + } + } + } +#endif /* USING_TRANSACTIONS */ + DBUG_RETURN(error); +} + +/** + Check if we can skip the two-phase commit. + + A helper function to evaluate if two-phase commit is mandatory. + As a side effect, propagates the read-only/read-write flags + of the statement transaction to its enclosing normal transaction. + + If we have at least two engines with read-write changes we must + run a two-phase commit. Otherwise we can run several independent + commits as the only transactional engine has read-write changes + and others are read-only. + + @retval 0 All engines are read-only. + @retval 1 We have the only engine with read-write changes. + @retval >1 More than one engine have read-write changes. + Note: return value might NOT be the exact number of + engines with read-write changes. +*/ + +static +uint +ha_check_and_coalesce_trx_read_only(THD *thd, Ha_trx_info *ha_list, + bool all) +{ + /* The number of storage engines that have actual changes. */ + unsigned rw_ha_count= 0; + Ha_trx_info *ha_info; + + for (ha_info= ha_list; ha_info; ha_info= ha_info->next()) + { + if (ha_info->is_trx_read_write()) + ++rw_ha_count; + + if (! all) + { + Ha_trx_info *ha_info_all= &thd->ha_data[ha_info->ht()->slot].ha_info[1]; + DBUG_ASSERT(ha_info != ha_info_all); + /* + Merge read-only/read-write information about statement + transaction to its enclosing normal transaction. Do this + only if in a real transaction -- that is, if we know + that ha_info_all is registered in thd->transaction.all. + Since otherwise we only clutter the normal transaction flags. + */ + if (ha_info_all->is_started()) /* FALSE if autocommit. */ + ha_info_all->coalesce_trx_with(ha_info); + } + else if (rw_ha_count > 1) + { + /* + It is a normal transaction, so we don't need to merge read/write + information up, and the need for two-phase commit has been + already established. Break the loop prematurely. + */ + break; + } + } + return rw_ha_count; +} + + +/** + @retval + 0 ok + @retval + 1 transaction was rolled back + @retval + 2 error during commit, data may be inconsistent + + @todo + Since we don't support nested statement transactions in 5.0, + we can't commit or rollback stmt transactions while we are inside + stored functions or triggers. So we simply do nothing now. + TODO: This should be fixed in later ( >= 5.1) releases. +*/ +int ha_commit_trans(THD *thd, bool all) +{ + int error= 0, cookie= 0; + /* + 'all' means that this is either an explicit commit issued by + user, or an implicit commit issued by a DDL. + */ + THD_TRANS *trans= all ? &thd->transaction.all : &thd->transaction.stmt; + /* + "real" is a nick name for a transaction for which a commit will + make persistent changes. E.g. a 'stmt' transaction inside a 'all' + transation is not 'real': even though it's possible to commit it, + the changes are not durable as they might be rolled back if the + enclosing 'all' transaction is rolled back. + */ + bool is_real_trans= all || thd->transaction.all.ha_list == 0; + Ha_trx_info *ha_info= trans->ha_list; + my_xid xid= thd->transaction.xid_state.xid.get_my_xid(); + DBUG_ENTER("ha_commit_trans"); + + /* + We must not commit the normal transaction if a statement + transaction is pending. Otherwise statement transaction + flags will not get propagated to its normal transaction's + counterpart. + */ + // @InfiniDB + if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_ALTER_VTABLE && thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE) + DBUG_ASSERT(thd->transaction.stmt.ha_list == NULL || + trans == &thd->transaction.stmt); + + if (thd->in_sub_stmt) + { + /* + Since we don't support nested statement transactions in 5.0, + we can't commit or rollback stmt transactions while we are inside + stored functions or triggers. So we simply do nothing now. + TODO: This should be fixed in later ( >= 5.1) releases. + */ + if (!all) + DBUG_RETURN(0); + /* + We assume that all statements which commit or rollback main transaction + are prohibited inside of stored functions or triggers. So they should + bail out with error even before ha_commit_trans() call. To be 100% safe + let us throw error in non-debug builds. + */ + DBUG_ASSERT(0); + my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); + DBUG_RETURN(2); + } +#ifdef USING_TRANSACTIONS + + // @bug 1809. Skip commit/rollback with vtable transaction + // @bug 2106. Follow the normal transaction path for table mode + if (ha_info && (thd->infinidb_vtable.vtable_state == THD::INFINIDB_INIT || + thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE)) + { + uint rw_ha_count; + bool rw_trans; + + DBUG_EXECUTE_IF("crash_commit_before", abort();); + + /* Close all cursors that can not survive COMMIT */ + if (is_real_trans) /* not a statement commit */ + thd->stmt_map.close_transient_cursors(); + + rw_ha_count= ha_check_and_coalesce_trx_read_only(thd, ha_info, all); + /* rw_trans is TRUE when we in a transaction changing data */ + rw_trans= is_real_trans && (rw_ha_count > 0); + + if (rw_trans && + wait_if_global_read_lock(thd, 0, 0)) + { + ha_rollback_trans(thd, all); + DBUG_RETURN(1); + } + + if (rw_trans && + opt_readonly && + !(thd->security_ctx->master_access & SUPER_ACL) && + !thd->slave_thread) + { + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only"); + ha_rollback_trans(thd, all); + error= 1; + goto end; + } + + if (!trans->no_2pc && (rw_ha_count > 1)) + { + for (; ha_info && !error; ha_info= ha_info->next()) + { + int err; + handlerton *ht= ha_info->ht(); + /* + Do not call two-phase commit if this particular + transaction is read-only. This allows for simpler + implementation in engines that are always read-only. + */ + if (! ha_info->is_trx_read_write()) + continue; + /* + Sic: we know that prepare() is not NULL since otherwise + trans->no_2pc would have been set. + */ + if ((err= ht->prepare(ht, thd, all))) + { + my_error(ER_ERROR_DURING_COMMIT, MYF(0), err); + error= 1; + } + status_var_increment(thd->status_var.ha_prepare_count); + } + DBUG_EXECUTE_IF("crash_commit_after_prepare", abort();); + if (error || (is_real_trans && xid && + (error= !(cookie= tc_log->log_xid(thd, xid))))) + { + ha_rollback_trans(thd, all); + error= 1; + goto end; + } + DBUG_EXECUTE_IF("crash_commit_after_log", abort();); + } + error=ha_commit_one_phase(thd, all) ? (cookie ? 2 : 1) : 0; + DBUG_EXECUTE_IF("crash_commit_before_unlog", abort();); + if (cookie) + tc_log->unlog(cookie, xid); + DBUG_EXECUTE_IF("crash_commit_after", abort();); +end: + if (rw_trans) + start_waiting_global_read_lock(thd); + } + /* Free resources and perform other cleanup even for 'empty' transactions. */ + else if (is_real_trans) + thd->transaction.cleanup(); +#endif /* USING_TRANSACTIONS */ + DBUG_RETURN(error); +} + +/** + @note + This function does not care about global read lock. A caller should. +*/ +int ha_commit_one_phase(THD *thd, bool all) +{ + int error=0; + THD_TRANS *trans=all ? &thd->transaction.all : &thd->transaction.stmt; + /* + "real" is a nick name for a transaction for which a commit will + make persistent changes. E.g. a 'stmt' transaction inside a 'all' + transation is not 'real': even though it's possible to commit it, + the changes are not durable as they might be rolled back if the + enclosing 'all' transaction is rolled back. + */ + bool is_real_trans=all || thd->transaction.all.ha_list == 0; + Ha_trx_info *ha_info= trans->ha_list, *ha_info_next; + DBUG_ENTER("ha_commit_one_phase"); +#ifdef USING_TRANSACTIONS + if (ha_info) + { + for (; ha_info; ha_info= ha_info_next) + { + int err; + handlerton *ht= ha_info->ht(); + if ((err= ht->commit(ht, thd, all))) + { + my_error(ER_ERROR_DURING_COMMIT, MYF(0), err); + error=1; + } + status_var_increment(thd->status_var.ha_commit_count); + ha_info_next= ha_info->next(); + ha_info->reset(); /* keep it conveniently zero-filled */ + } + trans->ha_list= 0; + trans->no_2pc=0; + if (all) + { +#ifdef HAVE_QUERY_CACHE + if (thd->transaction.changed_tables) + query_cache.invalidate(thd->transaction.changed_tables); +#endif + thd->variables.tx_isolation=thd->session_tx_isolation; + } + } + /* Free resources and perform other cleanup even for 'empty' transactions. */ + if (is_real_trans) + thd->transaction.cleanup(); +#endif /* USING_TRANSACTIONS */ + DBUG_RETURN(error); +} + + +int ha_rollback_trans(THD *thd, bool all) +{ + int error=0; + THD_TRANS *trans=all ? &thd->transaction.all : &thd->transaction.stmt; + Ha_trx_info *ha_info= trans->ha_list, *ha_info_next; + /* + "real" is a nick name for a transaction for which a commit will + make persistent changes. E.g. a 'stmt' transaction inside a 'all' + transation is not 'real': even though it's possible to commit it, + the changes are not durable as they might be rolled back if the + enclosing 'all' transaction is rolled back. + */ + bool is_real_trans=all || thd->transaction.all.ha_list == 0; + DBUG_ENTER("ha_rollback_trans"); + + /* + We must not rollback the normal transaction if a statement + transaction is pending. + */ + DBUG_ASSERT(thd->transaction.stmt.ha_list == NULL || + trans == &thd->transaction.stmt); + + if (thd->in_sub_stmt) + { + /* + If we are inside stored function or trigger we should not commit or + rollback current statement transaction. See comment in ha_commit_trans() + call for more information. + */ + if (!all) + DBUG_RETURN(0); + DBUG_ASSERT(0); + my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); + DBUG_RETURN(1); + } +#ifdef USING_TRANSACTIONS + if (ha_info) + { + /* Close all cursors that can not survive ROLLBACK */ + if (is_real_trans) /* not a statement commit */ + thd->stmt_map.close_transient_cursors(); + + for (; ha_info; ha_info= ha_info_next) + { + int err; + handlerton *ht= ha_info->ht(); + if ((err= ht->rollback(ht, thd, all))) + { // cannot happen + my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err); + error=1; + } + status_var_increment(thd->status_var.ha_rollback_count); + ha_info_next= ha_info->next(); + ha_info->reset(); /* keep it conveniently zero-filled */ + } + trans->ha_list= 0; + trans->no_2pc=0; + if (is_real_trans && thd->transaction_rollback_request) + thd->transaction.xid_state.rm_error= thd->main_da.sql_errno(); + if (all) + thd->variables.tx_isolation=thd->session_tx_isolation; + } + /* Always cleanup. Even if there nht==0. There may be savepoints. */ + if (is_real_trans) + thd->transaction.cleanup(); +#endif /* USING_TRANSACTIONS */ + if (all) + thd->transaction_rollback_request= FALSE; + + /* + If a non-transactional table was updated, warn; don't warn if this is a + slave thread (because when a slave thread executes a ROLLBACK, it has + been read from the binary log, so it's 100% sure and normal to produce + error ER_WARNING_NOT_COMPLETE_ROLLBACK. If we sent the warning to the + slave SQL thread, it would not stop the thread but just be printed in + the error log; but we don't want users to wonder why they have this + message in the error log, so we don't send it. + */ + if (is_real_trans && thd->transaction.all.modified_non_trans_table && + !thd->slave_thread && thd->killed != THD::KILL_CONNECTION) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARNING_NOT_COMPLETE_ROLLBACK, + ER(ER_WARNING_NOT_COMPLETE_ROLLBACK)); + DBUG_RETURN(error); +} + +/** + This is used to commit or rollback a single statement depending on + the value of error. + + @note + Note that if the autocommit is on, then the following call inside + InnoDB will commit or rollback the whole transaction (= the statement). The + autocommit mechanism built into InnoDB is based on counting locks, but if + the user has used LOCK TABLES then that mechanism does not know to do the + commit. +*/ +int ha_autocommit_or_rollback(THD *thd, int error) +{ + DBUG_ENTER("ha_autocommit_or_rollback"); +#ifdef USING_TRANSACTIONS + if (thd->transaction.stmt.ha_list) + { + if (!error) + { + if (ha_commit_trans(thd, 0)) + error=1; + } + else + { + (void) ha_rollback_trans(thd, 0); + if (thd->transaction_rollback_request && !thd->in_sub_stmt) + (void) ha_rollback(thd); + } + + thd->variables.tx_isolation=thd->session_tx_isolation; + } +#endif + DBUG_RETURN(error); +} + + +struct xahton_st { + XID *xid; + int result; +}; + +static my_bool xacommit_handlerton(THD *unused1, plugin_ref plugin, + void *arg) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->recover) + { + hton->commit_by_xid(hton, ((struct xahton_st *)arg)->xid); + ((struct xahton_st *)arg)->result= 0; + } + return FALSE; +} + +static my_bool xarollback_handlerton(THD *unused1, plugin_ref plugin, + void *arg) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->recover) + { + hton->rollback_by_xid(hton, ((struct xahton_st *)arg)->xid); + ((struct xahton_st *)arg)->result= 0; + } + return FALSE; +} + + +int ha_commit_or_rollback_by_xid(XID *xid, bool commit) +{ + struct xahton_st xaop; + xaop.xid= xid; + xaop.result= 1; + + plugin_foreach(NULL, commit ? xacommit_handlerton : xarollback_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &xaop); + + return xaop.result; +} + + +#ifndef DBUG_OFF +/** + @note + This does not need to be multi-byte safe or anything +*/ +static char* xid_to_str(char *buf, XID *xid) +{ + int i; + char *s=buf; + *s++='\''; + for (i=0; i < xid->gtrid_length+xid->bqual_length; i++) + { + uchar c=(uchar)xid->data[i]; + /* is_next_dig is set if next character is a number */ + bool is_next_dig= FALSE; + if (i < XIDDATASIZE) + { + char ch= xid->data[i+1]; + is_next_dig= (ch >= '0' && ch <='9'); + } + if (i == xid->gtrid_length) + { + *s++='\''; + if (xid->bqual_length) + { + *s++='.'; + *s++='\''; + } + } + if (c < 32 || c > 126) + { + *s++='\\'; + /* + If next character is a number, write current character with + 3 octal numbers to ensure that the next number is not seen + as part of the octal number + */ + if (c > 077 || is_next_dig) + *s++=_dig_vec_lower[c >> 6]; + if (c > 007 || is_next_dig) + *s++=_dig_vec_lower[(c >> 3) & 7]; + *s++=_dig_vec_lower[c & 7]; + } + else + { + if (c == '\'' || c == '\\') + *s++='\\'; + *s++=c; + } + } + *s++='\''; + *s=0; + return buf; +} +#endif + +/** + recover() step of xa. + + @note + there are three modes of operation: + - automatic recover after a crash + in this case commit_list != 0, tc_heuristic_recover==0 + all xids from commit_list are committed, others are rolled back + - manual (heuristic) recover + in this case commit_list==0, tc_heuristic_recover != 0 + DBA has explicitly specified that all prepared transactions should + be committed (or rolled back). + - no recovery (MySQL did not detect a crash) + in this case commit_list==0, tc_heuristic_recover == 0 + there should be no prepared transactions in this case. +*/ +struct xarecover_st +{ + int len, found_foreign_xids, found_my_xids; + XID *list; + HASH *commit_list; + bool dry_run; +}; + +static my_bool xarecover_handlerton(THD *unused, plugin_ref plugin, + void *arg) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + struct xarecover_st *info= (struct xarecover_st *) arg; + int got; + + if (hton->state == SHOW_OPTION_YES && hton->recover) + { + while ((got= hton->recover(hton, info->list, info->len)) > 0 ) + { + sql_print_information("Found %d prepared transaction(s) in %s", + got, ha_resolve_storage_engine_name(hton)); + for (int i=0; i < got; i ++) + { + my_xid x=info->list[i].get_my_xid(); + if (!x) // not "mine" - that is generated by external TM + { +#ifndef DBUG_OFF + char buf[XIDDATASIZE*4+6]; // see xid_to_str + sql_print_information("ignore xid %s", xid_to_str(buf, info->list+i)); +#endif + xid_cache_insert(info->list+i, XA_PREPARED); + info->found_foreign_xids++; + continue; + } + if (info->dry_run) + { + info->found_my_xids++; + continue; + } + // recovery mode + if (info->commit_list ? + hash_search(info->commit_list, (uchar *)&x, sizeof(x)) != 0 : + tc_heuristic_recover == TC_HEURISTIC_RECOVER_COMMIT) + { +#ifndef DBUG_OFF + char buf[XIDDATASIZE*4+6]; // see xid_to_str + sql_print_information("commit xid %s", xid_to_str(buf, info->list+i)); +#endif + hton->commit_by_xid(hton, info->list+i); + } + else + { +#ifndef DBUG_OFF + char buf[XIDDATASIZE*4+6]; // see xid_to_str + sql_print_information("rollback xid %s", + xid_to_str(buf, info->list+i)); +#endif + hton->rollback_by_xid(hton, info->list+i); + } + } + if (got < info->len) + break; + } + } + return FALSE; +} + +int ha_recover(HASH *commit_list) +{ + struct xarecover_st info; + DBUG_ENTER("ha_recover"); + info.found_foreign_xids= info.found_my_xids= 0; + info.commit_list= commit_list; + info.dry_run= (info.commit_list==0 && tc_heuristic_recover==0); + info.list= NULL; + + /* commit_list and tc_heuristic_recover cannot be set both */ + DBUG_ASSERT(info.commit_list==0 || tc_heuristic_recover==0); + /* if either is set, total_ha_2pc must be set too */ + DBUG_ASSERT(info.dry_run || total_ha_2pc>(ulong)opt_bin_log); + + if (total_ha_2pc <= (ulong)opt_bin_log) + DBUG_RETURN(0); + + if (info.commit_list) + sql_print_information("Starting crash recovery..."); + +#ifndef WILL_BE_DELETED_LATER + /* + for now, only InnoDB supports 2pc. It means we can always safely + rollback all pending transactions, without risking inconsistent data + */ + DBUG_ASSERT(total_ha_2pc == (ulong) opt_bin_log+1); // only InnoDB and binlog + tc_heuristic_recover= TC_HEURISTIC_RECOVER_ROLLBACK; // forcing ROLLBACK + info.dry_run=FALSE; +#endif + + for (info.len= MAX_XID_LIST_SIZE ; + info.list==0 && info.len > MIN_XID_LIST_SIZE; info.len/=2) + { + info.list=(XID *)my_malloc(info.len*sizeof(XID), MYF(0)); + } + if (!info.list) + { + sql_print_error(ER(ER_OUTOFMEMORY), info.len*sizeof(XID)); + DBUG_RETURN(1); + } + + plugin_foreach(NULL, xarecover_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &info); + + my_free((uchar*)info.list, MYF(0)); + if (info.found_foreign_xids) + sql_print_warning("Found %d prepared XA transactions", + info.found_foreign_xids); + if (info.dry_run && info.found_my_xids) + { + sql_print_error("Found %d prepared transactions! It means that mysqld was " + "not shut down properly last time and critical recovery " + "information (last binlog or %s file) was manually deleted " + "after a crash. You have to start mysqld with " + "--tc-heuristic-recover switch to commit or rollback " + "pending transactions.", + info.found_my_xids, opt_tc_log_file); + DBUG_RETURN(1); + } + if (info.commit_list) + sql_print_information("Crash recovery finished."); + DBUG_RETURN(0); +} + +/** + return the list of XID's to a client, the same way SHOW commands do. + + @note + I didn't find in XA specs that an RM cannot return the same XID twice, + so mysql_xa_recover does not filter XID's to ensure uniqueness. + It can be easily fixed later, if necessary. +*/ +bool mysql_xa_recover(THD *thd) +{ + List field_list; + Protocol *protocol= thd->protocol; + int i=0; + XID_STATE *xs; + DBUG_ENTER("mysql_xa_recover"); + + field_list.push_back(new Item_int("formatID", 0, MY_INT32_NUM_DECIMAL_DIGITS)); + field_list.push_back(new Item_int("gtrid_length", 0, MY_INT32_NUM_DECIMAL_DIGITS)); + field_list.push_back(new Item_int("bqual_length", 0, MY_INT32_NUM_DECIMAL_DIGITS)); + field_list.push_back(new Item_empty_string("data",XIDDATASIZE)); + + if (protocol->send_fields(&field_list, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) + DBUG_RETURN(1); + + pthread_mutex_lock(&LOCK_xid_cache); + while ((xs= (XID_STATE*)hash_element(&xid_cache, i++))) + { + if (xs->xa_state==XA_PREPARED) + { + protocol->prepare_for_resend(); + protocol->store_longlong((longlong)xs->xid.formatID, FALSE); + protocol->store_longlong((longlong)xs->xid.gtrid_length, FALSE); + protocol->store_longlong((longlong)xs->xid.bqual_length, FALSE); + protocol->store(xs->xid.data, xs->xid.gtrid_length+xs->xid.bqual_length, + &my_charset_bin); + if (protocol->write()) + { + pthread_mutex_unlock(&LOCK_xid_cache); + DBUG_RETURN(1); + } + } + } + + pthread_mutex_unlock(&LOCK_xid_cache); + my_eof(thd); + DBUG_RETURN(0); +} + +/** + @details + This function should be called when MySQL sends rows of a SELECT result set + or the EOF mark to the client. It releases a possible adaptive hash index + S-latch held by thd in InnoDB and also releases a possible InnoDB query + FIFO ticket to enter InnoDB. To save CPU time, InnoDB allows a thd to + keep them over several calls of the InnoDB handler interface when a join + is executed. But when we let the control to pass to the client they have + to be released because if the application program uses mysql_use_result(), + it may deadlock on the S-latch if the application on another connection + performs another SQL query. In MySQL-4.1 this is even more important because + there a connection can have several SELECT queries open at the same time. + + @param thd the thread handle of the current connection + + @return + always 0 +*/ + +int ha_release_temporary_latches(THD *thd) +{ + Ha_trx_info *info; + + /* + Note that below we assume that only transactional storage engines + may need release_temporary_latches(). If this will ever become false, + we could iterate on thd->open_tables instead (and remove duplicates + as if (!seen[hton->slot]) { seen[hton->slot]=1; ... }). + */ + for (info= thd->transaction.stmt.ha_list; info; info= info->next()) + { + handlerton *hton= info->ht(); + if (hton && hton->release_temporary_latches) + hton->release_temporary_latches(hton, thd); + } + return 0; +} + +int ha_rollback_to_savepoint(THD *thd, SAVEPOINT *sv) +{ + int error=0; + THD_TRANS *trans= (thd->in_sub_stmt ? &thd->transaction.stmt : + &thd->transaction.all); + Ha_trx_info *ha_info, *ha_info_next; + + DBUG_ENTER("ha_rollback_to_savepoint"); + + trans->no_2pc=0; + /* + rolling back to savepoint in all storage engines that were part of the + transaction when the savepoint was set + */ + for (ha_info= sv->ha_list; ha_info; ha_info= ha_info->next()) + { + int err; + handlerton *ht= ha_info->ht(); + DBUG_ASSERT(ht); + DBUG_ASSERT(ht->savepoint_set != 0); + if ((err= ht->savepoint_rollback(ht, thd, + (uchar *)(sv+1)+ht->savepoint_offset))) + { // cannot happen + my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err); + error=1; + } + status_var_increment(thd->status_var.ha_savepoint_rollback_count); + trans->no_2pc|= ht->prepare == 0; + } + /* + rolling back the transaction in all storage engines that were not part of + the transaction when the savepoint was set + */ + for (ha_info= trans->ha_list; ha_info != sv->ha_list; + ha_info= ha_info_next) + { + int err; + handlerton *ht= ha_info->ht(); + if ((err= ht->rollback(ht, thd, !thd->in_sub_stmt))) + { // cannot happen + my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err); + error=1; + } + status_var_increment(thd->status_var.ha_rollback_count); + ha_info_next= ha_info->next(); + ha_info->reset(); /* keep it conveniently zero-filled */ + } + trans->ha_list= sv->ha_list; + DBUG_RETURN(error); +} + +/** + @note + according to the sql standard (ISO/IEC 9075-2:2003) + section "4.33.4 SQL-statements and transaction states", + SAVEPOINT is *not* transaction-initiating SQL-statement +*/ +int ha_savepoint(THD *thd, SAVEPOINT *sv) +{ + int error=0; + THD_TRANS *trans= (thd->in_sub_stmt ? &thd->transaction.stmt : + &thd->transaction.all); + Ha_trx_info *ha_info= trans->ha_list; + DBUG_ENTER("ha_savepoint"); +#ifdef USING_TRANSACTIONS + for (; ha_info; ha_info= ha_info->next()) + { + int err; + handlerton *ht= ha_info->ht(); + DBUG_ASSERT(ht); + if (! ht->savepoint_set) + { + my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "SAVEPOINT"); + error=1; + break; + } + if ((err= ht->savepoint_set(ht, thd, (uchar *)(sv+1)+ht->savepoint_offset))) + { // cannot happen + my_error(ER_GET_ERRNO, MYF(0), err); + error=1; + } + status_var_increment(thd->status_var.ha_savepoint_count); + } + /* + Remember the list of registered storage engines. All new + engines are prepended to the beginning of the list. + */ + sv->ha_list= trans->ha_list; +#endif /* USING_TRANSACTIONS */ + DBUG_RETURN(error); +} + +int ha_release_savepoint(THD *thd, SAVEPOINT *sv) +{ + int error=0; + Ha_trx_info *ha_info= sv->ha_list; + DBUG_ENTER("ha_release_savepoint"); + + for (; ha_info; ha_info= ha_info->next()) + { + int err; + handlerton *ht= ha_info->ht(); + /* Savepoint life time is enclosed into transaction life time. */ + DBUG_ASSERT(ht); + if (!ht->savepoint_release) + continue; + if ((err= ht->savepoint_release(ht, thd, + (uchar *)(sv+1) + ht->savepoint_offset))) + { // cannot happen + my_error(ER_GET_ERRNO, MYF(0), err); + error=1; + } + } + DBUG_RETURN(error); +} + + +static my_bool snapshot_handlerton(THD *thd, plugin_ref plugin, + void *arg) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && + hton->start_consistent_snapshot) + { + hton->start_consistent_snapshot(hton, thd); + *((bool *)arg)= false; + } + return FALSE; +} + +int ha_start_consistent_snapshot(THD *thd) +{ + bool warn= true; + + plugin_foreach(thd, snapshot_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, &warn); + + /* + Same idea as when one wants to CREATE TABLE in one engine which does not + exist: + */ + if (warn) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, + "This MySQL server does not support any " + "consistent-read capable storage engine"); + return 0; +} + + +static my_bool flush_handlerton(THD *thd, plugin_ref plugin, + void *arg) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->flush_logs && + hton->flush_logs(hton)) + return TRUE; + return FALSE; +} + + +bool ha_flush_logs(handlerton *db_type) +{ + if (db_type == NULL) + { + if (plugin_foreach(NULL, flush_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, 0)) + return TRUE; + } + else + { + if (db_type->state != SHOW_OPTION_YES || + (db_type->flush_logs && db_type->flush_logs(db_type))) + return TRUE; + } + return FALSE; +} + +const char *get_canonical_filename(handler *file, const char *path, + char *tmp_path) +{ + if (lower_case_table_names != 2 || (file->ha_table_flags() & HA_FILE_BASED)) + return path; + + /* Ensure that table handler get path in lower case */ + if (tmp_path != path) + strmov(tmp_path, path); + + /* + we only should turn into lowercase database/table part + so start the process after homedirectory + */ + my_casedn_str(files_charset_info, tmp_path + mysql_data_home_len); + return tmp_path; +} + + +/** + An interceptor to hijack the text of the error message without + setting an error in the thread. We need the text to present it + in the form of a warning to the user. +*/ + +struct Ha_delete_table_error_handler: public Internal_error_handler +{ +public: + virtual bool handle_error(uint sql_errno, + const char *message, + MYSQL_ERROR::enum_warning_level level, + THD *thd); + char buff[MYSQL_ERRMSG_SIZE]; +}; + + +bool +Ha_delete_table_error_handler:: +handle_error(uint sql_errno, + const char *message, + MYSQL_ERROR::enum_warning_level level, + THD *thd) +{ + /* Grab the error message */ + strmake(buff, message, sizeof(buff)-1); + return TRUE; +} + + +/** @brief + This should return ENOENT if the file doesn't exists. + The .frm file will be deleted only if we return 0 or ENOENT +*/ +int ha_delete_table(THD *thd, handlerton *table_type, const char *path, + const char *db, const char *alias, bool generate_warning) +{ + handler *file; + char tmp_path[FN_REFLEN]; + int error; + TABLE dummy_table; + TABLE_SHARE dummy_share; + DBUG_ENTER("ha_delete_table"); + + bzero((char*) &dummy_table, sizeof(dummy_table)); + bzero((char*) &dummy_share, sizeof(dummy_share)); + dummy_table.s= &dummy_share; + + /* DB_TYPE_UNKNOWN is used in ALTER TABLE when renaming only .frm files */ + if (table_type == NULL || + ! (file=get_new_handler((TABLE_SHARE*)0, thd->mem_root, table_type))) + DBUG_RETURN(ENOENT); + + path= get_canonical_filename(file, path, tmp_path); + if ((error= file->ha_delete_table(path)) && generate_warning) + { + /* + Because file->print_error() use my_error() to generate the error message + we use an internal error handler to intercept it and store the text + in a temporary buffer. Later the message will be presented to user + as a warning. + */ + Ha_delete_table_error_handler ha_delete_table_error_handler; + + /* Fill up strucutures that print_error may need */ + dummy_share.path.str= (char*) path; + dummy_share.path.length= strlen(path); + dummy_share.db.str= (char*) db; + dummy_share.db.length= strlen(db); + dummy_share.table_name.str= (char*) alias; + dummy_share.table_name.length= strlen(alias); + dummy_table.alias= alias; + + file->change_table_ptr(&dummy_table, &dummy_share); + + thd->push_internal_handler(&ha_delete_table_error_handler); + file->print_error(error, 0); + + thd->pop_internal_handler(); + + /* + XXX: should we convert *all* errors to warnings here? + What if the error is fatal? + */ + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, error, + ha_delete_table_error_handler.buff); + } + delete file; + DBUG_RETURN(error); +} + +/**************************************************************************** +** General handler functions +****************************************************************************/ +handler *handler::clone(MEM_ROOT *mem_root) +{ + handler *new_handler= get_new_handler(table->s, mem_root, table->s->db_type()); + /* + Allocate handler->ref here because otherwise ha_open will allocate it + on this->table->mem_root and we will not be able to reclaim that memory + when the clone handler object is destroyed. + */ + if (!(new_handler->ref= (uchar*) alloc_root(mem_root, ALIGN_SIZE(ref_length)*2))) + return NULL; + if (new_handler && !new_handler->ha_open(table, + table->s->normalized_path.str, + table->db_stat, + HA_OPEN_IGNORE_IF_LOCKED)) + return new_handler; + return NULL; +} + + + +void handler::ha_statistic_increment(ulong SSV::*offset) const +{ + status_var_increment(table->in_use->status_var.*offset); +} + +void **handler::ha_data(THD *thd) const +{ + return thd_ha_data(thd, ht); +} + +THD *handler::ha_thd(void) const +{ + DBUG_ASSERT(!table || !table->in_use || table->in_use == current_thd); + return (table && table->in_use) ? table->in_use : current_thd; +} + + +/** @brief + Open database-handler. + + IMPLEMENTATION + Try O_RDONLY if cannot open as O_RDWR + Don't wait for locks if not HA_OPEN_WAIT_IF_LOCKED is set +*/ +int handler::ha_open(TABLE *table_arg, const char *name, int mode, + int test_if_locked) +{ + int error; + DBUG_ENTER("handler::ha_open"); + DBUG_PRINT("enter", + ("name: %s db_type: %d db_stat: %d mode: %d lock_test: %d", + name, ht->db_type, table_arg->db_stat, mode, + test_if_locked)); + + table= table_arg; + DBUG_ASSERT(table->s == table_share); + DBUG_ASSERT(alloc_root_inited(&table->mem_root)); + + if ((error=open(name,mode,test_if_locked))) + { + if ((error == EACCES || error == EROFS) && mode == O_RDWR && + (table->db_stat & HA_TRY_READ_ONLY)) + { + table->db_stat|=HA_READ_ONLY; + error=open(name,O_RDONLY,test_if_locked); + } + } + if (error) + { + my_errno= error; /* Safeguard */ + DBUG_PRINT("error",("error: %d errno: %d",error,errno)); + } + else + { + if (table->s->db_options_in_use & HA_OPTION_READ_ONLY_DATA) + table->db_stat|=HA_READ_ONLY; + (void) extra(HA_EXTRA_NO_READCHECK); // Not needed in SQL + + /* ref is already allocated for us if we're called from handler::clone() */ + if (!ref && !(ref= (uchar*) alloc_root(&table->mem_root, + ALIGN_SIZE(ref_length)*2))) + { + close(); + error=HA_ERR_OUT_OF_MEM; + } + else + dup_ref=ref+ALIGN_SIZE(ref_length); + cached_table_flags= table_flags(); + } + DBUG_RETURN(error); +} + + +/** + Read first row (only) from a table. + + This is never called for InnoDB tables, as these table types + has the HA_STATS_RECORDS_IS_EXACT set. +*/ +int handler::read_first_row(uchar * buf, uint primary_key) +{ + register int error; + DBUG_ENTER("handler::read_first_row"); + + ha_statistic_increment(&SSV::ha_read_first_count); + + /* + If there is very few deleted rows in the table, find the first row by + scanning the table. + TODO remove the test for HA_READ_ORDER + */ + if (stats.deleted < 10 || primary_key >= MAX_KEY || + !(index_flags(primary_key, 0, 0) & HA_READ_ORDER)) + { + (void) ha_rnd_init(1); + while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) ; + (void) ha_rnd_end(); + } + else + { + /* Find the first row through the primary key */ + (void) ha_index_init(primary_key, 0); + error=index_first(buf); + (void) ha_index_end(); + } + DBUG_RETURN(error); +} + +/** + Generate the next auto-increment number based on increment and offset. + computes the lowest number + - strictly greater than "nr" + - of the form: auto_increment_offset + N * auto_increment_increment + + In most cases increment= offset= 1, in which case we get: + @verbatim 1,2,3,4,5,... @endverbatim + If increment=10 and offset=5 and previous number is 1, we get: + @verbatim 1,5,15,25,35,... @endverbatim +*/ +inline ulonglong +compute_next_insert_id(ulonglong nr,struct system_variables *variables) +{ + if (variables->auto_increment_increment == 1) + return (nr+1); // optimization of the formula below + nr= (((nr+ variables->auto_increment_increment - + variables->auto_increment_offset)) / + (ulonglong) variables->auto_increment_increment); + return (nr* (ulonglong) variables->auto_increment_increment + + variables->auto_increment_offset); +} + + +void handler::adjust_next_insert_id_after_explicit_value(ulonglong nr) +{ + /* + If we have set THD::next_insert_id previously and plan to insert an + explicitely-specified value larger than this, we need to increase + THD::next_insert_id to be greater than the explicit value. + */ + if ((next_insert_id > 0) && (nr >= next_insert_id)) + set_next_insert_id(compute_next_insert_id(nr, &table->in_use->variables)); +} + + +/** @brief + Computes the largest number X: + - smaller than or equal to "nr" + - of the form: auto_increment_offset + N * auto_increment_increment + where N>=0. + + SYNOPSIS + prev_insert_id + nr Number to "round down" + variables variables struct containing auto_increment_increment and + auto_increment_offset + + RETURN + The number X if it exists, "nr" otherwise. +*/ +inline ulonglong +prev_insert_id(ulonglong nr, struct system_variables *variables) +{ + if (unlikely(nr < variables->auto_increment_offset)) + { + /* + There's nothing good we can do here. That is a pathological case, where + the offset is larger than the column's max possible value, i.e. not even + the first sequence value may be inserted. User will receive warning. + */ + DBUG_PRINT("info",("auto_increment: nr: %lu cannot honour " + "auto_increment_offset: %lu", + (ulong) nr, variables->auto_increment_offset)); + return nr; + } + if (variables->auto_increment_increment == 1) + return nr; // optimization of the formula below + nr= (((nr - variables->auto_increment_offset)) / + (ulonglong) variables->auto_increment_increment); + return (nr * (ulonglong) variables->auto_increment_increment + + variables->auto_increment_offset); +} + + +/** + Update the auto_increment field if necessary. + + Updates columns with type NEXT_NUMBER if: + + - If column value is set to NULL (in which case + auto_increment_field_not_null is 0) + - If column is set to 0 and (sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO) is not + set. In the future we will only set NEXT_NUMBER fields if one sets them + to NULL (or they are not included in the insert list). + + In those cases, we check if the currently reserved interval still has + values we have not used. If yes, we pick the smallest one and use it. + Otherwise: + + - If a list of intervals has been provided to the statement via SET + INSERT_ID or via an Intvar_log_event (in a replication slave), we pick the + first unused interval from this list, consider it as reserved. + + - Otherwise we set the column for the first row to the value + next_insert_id(get_auto_increment(column))) which is usually + max-used-column-value+1. + We call get_auto_increment() for the first row in a multi-row + statement. get_auto_increment() will tell us the interval of values it + reserved for us. + + - In both cases, for the following rows we use those reserved values without + calling the handler again (we just progress in the interval, computing + each new value from the previous one). Until we have exhausted them, then + we either take the next provided interval or call get_auto_increment() + again to reserve a new interval. + + - In both cases, the reserved intervals are remembered in + thd->auto_inc_intervals_in_cur_stmt_for_binlog if statement-based + binlogging; the last reserved interval is remembered in + auto_inc_interval_for_cur_row. The number of reserved intervals is + remembered in auto_inc_intervals_count. It differs from the number of + elements in thd->auto_inc_intervals_in_cur_stmt_for_binlog() because the + latter list is cumulative over all statements forming one binlog event + (when stored functions and triggers are used), and collapses two + contiguous intervals in one (see its append() method). + + The idea is that generated auto_increment values are predictable and + independent of the column values in the table. This is needed to be + able to replicate into a table that already has rows with a higher + auto-increment value than the one that is inserted. + + After we have already generated an auto-increment number and the user + inserts a column with a higher value than the last used one, we will + start counting from the inserted value. + + This function's "outputs" are: the table's auto_increment field is filled + with a value, thd->next_insert_id is filled with the value to use for the + next row, if a value was autogenerated for the current row it is stored in + thd->insert_id_for_cur_row, if get_auto_increment() was called + thd->auto_inc_interval_for_cur_row is modified, if that interval is not + present in thd->auto_inc_intervals_in_cur_stmt_for_binlog it is added to + this list. + + @todo + Replace all references to "next number" or NEXT_NUMBER to + "auto_increment", everywhere (see below: there is + table->auto_increment_field_not_null, and there also exists + table->next_number_field, it's not consistent). + + @retval + 0 ok + @retval + HA_ERR_AUTOINC_READ_FAILED get_auto_increment() was called and + returned ~(ulonglong) 0 + @retval + HA_ERR_AUTOINC_ERANGE storing value in field caused strict mode + failure. +*/ + +#define AUTO_INC_DEFAULT_NB_ROWS 1 // Some prefer 1024 here +#define AUTO_INC_DEFAULT_NB_MAX_BITS 16 +#define AUTO_INC_DEFAULT_NB_MAX ((1 << AUTO_INC_DEFAULT_NB_MAX_BITS) - 1) + +int handler::update_auto_increment() +{ + ulonglong nr, nb_reserved_values; + bool append= FALSE; + THD *thd= table->in_use; + struct system_variables *variables= &thd->variables; + DBUG_ENTER("handler::update_auto_increment"); + + /* + next_insert_id is a "cursor" into the reserved interval, it may go greater + than the interval, but not smaller. + */ + DBUG_ASSERT(next_insert_id >= auto_inc_interval_for_cur_row.minimum()); + + if ((nr= table->next_number_field->val_int()) != 0 || + (table->auto_increment_field_not_null && + thd->variables.sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO)) + { + /* + Update next_insert_id if we had already generated a value in this + statement (case of INSERT VALUES(null),(3763),(null): + the last NULL needs to insert 3764, not the value of the first NULL plus + 1). + */ + adjust_next_insert_id_after_explicit_value(nr); + insert_id_for_cur_row= 0; // didn't generate anything + DBUG_RETURN(0); + } + + if ((nr= next_insert_id) >= auto_inc_interval_for_cur_row.maximum()) + { + /* next_insert_id is beyond what is reserved, so we reserve more. */ + const Discrete_interval *forced= + thd->auto_inc_intervals_forced.get_next(); + if (forced != NULL) + { + nr= forced->minimum(); + nb_reserved_values= forced->values(); + } + else + { + /* + handler::estimation_rows_to_insert was set by + handler::ha_start_bulk_insert(); if 0 it means "unknown". + */ + ulonglong nb_desired_values; + /* + If an estimation was given to the engine: + - use it. + - if we already reserved numbers, it means the estimation was + not accurate, then we'll reserve 2*AUTO_INC_DEFAULT_NB_ROWS the 2nd + time, twice that the 3rd time etc. + If no estimation was given, use those increasing defaults from the + start, starting from AUTO_INC_DEFAULT_NB_ROWS. + Don't go beyond a max to not reserve "way too much" (because + reservation means potentially losing unused values). + Note that in prelocked mode no estimation is given. + */ + if ((auto_inc_intervals_count == 0) && (estimation_rows_to_insert > 0)) + nb_desired_values= estimation_rows_to_insert; + else /* go with the increasing defaults */ + { + /* avoid overflow in formula, with this if() */ + if (auto_inc_intervals_count <= AUTO_INC_DEFAULT_NB_MAX_BITS) + { + nb_desired_values= AUTO_INC_DEFAULT_NB_ROWS * + (1 << auto_inc_intervals_count); + set_if_smaller(nb_desired_values, AUTO_INC_DEFAULT_NB_MAX); + } + else + nb_desired_values= AUTO_INC_DEFAULT_NB_MAX; + } + /* This call ignores all its parameters but nr, currently */ + get_auto_increment(variables->auto_increment_offset, + variables->auto_increment_increment, + nb_desired_values, &nr, + &nb_reserved_values); + if (nr == ~(ulonglong) 0) + DBUG_RETURN(HA_ERR_AUTOINC_READ_FAILED); // Mark failure + + /* + That rounding below should not be needed when all engines actually + respect offset and increment in get_auto_increment(). But they don't + so we still do it. Wonder if for the not-first-in-index we should do + it. Hope that this rounding didn't push us out of the interval; even + if it did we cannot do anything about it (calling the engine again + will not help as we inserted no row). + */ + nr= compute_next_insert_id(nr-1, variables); + } + + if (table->s->next_number_keypart == 0) + { + /* We must defer the appending until "nr" has been possibly truncated */ + append= TRUE; + } + else + { + /* + For such auto_increment there is no notion of interval, just a + singleton. The interval is not even stored in + thd->auto_inc_interval_for_cur_row, so we are sure to call the engine + for next row. + */ + DBUG_PRINT("info",("auto_increment: special not-first-in-index")); + } + } + + DBUG_PRINT("info",("auto_increment: %lu", (ulong) nr)); + + if (unlikely(table->next_number_field->store((longlong) nr, TRUE))) + { + /* + first test if the query was aborted due to strict mode constraints + */ + if (thd->killed == THD::KILL_BAD_DATA) + DBUG_RETURN(HA_ERR_AUTOINC_ERANGE); + + /* + field refused this value (overflow) and truncated it, use the result of + the truncation (which is going to be inserted); however we try to + decrease it to honour auto_increment_* variables. + That will shift the left bound of the reserved interval, we don't + bother shifting the right bound (anyway any other value from this + interval will cause a duplicate key). + */ + nr= prev_insert_id(table->next_number_field->val_int(), variables); + if (unlikely(table->next_number_field->store((longlong) nr, TRUE))) + nr= table->next_number_field->val_int(); + } + if (append) + { + auto_inc_interval_for_cur_row.replace(nr, nb_reserved_values, + variables->auto_increment_increment); + auto_inc_intervals_count++; + /* Row-based replication does not need to store intervals in binlog */ + if (mysql_bin_log.is_open() && !thd->current_stmt_binlog_row_based) + thd->auto_inc_intervals_in_cur_stmt_for_binlog.append(auto_inc_interval_for_cur_row.minimum(), + auto_inc_interval_for_cur_row.values(), + variables->auto_increment_increment); + } + + /* + Record this autogenerated value. If the caller then + succeeds to insert this value, it will call + record_first_successful_insert_id_in_cur_stmt() + which will set first_successful_insert_id_in_cur_stmt if it's not + already set. + */ + insert_id_for_cur_row= nr; + /* + Set next insert id to point to next auto-increment value to be able to + handle multi-row statements. + */ + set_next_insert_id(compute_next_insert_id(nr, variables)); + + DBUG_RETURN(0); +} + + +/** @brief + MySQL signal that it changed the column bitmap + + USAGE + This is for handlers that needs to setup their own column bitmaps. + Normally the handler should set up their own column bitmaps in + index_init() or rnd_init() and in any column_bitmaps_signal() call after + this. + + The handler is allowd to do changes to the bitmap after a index_init or + rnd_init() call is made as after this, MySQL will not use the bitmap + for any program logic checking. +*/ +void handler::column_bitmaps_signal() +{ + DBUG_ENTER("column_bitmaps_signal"); + DBUG_PRINT("info", ("read_set: 0x%lx write_set: 0x%lx", (long) table->read_set, + (long) table->write_set)); + DBUG_VOID_RETURN; +} + + +/** @brief + Reserves an interval of auto_increment values from the handler. + + SYNOPSIS + get_auto_increment() + offset + increment + nb_desired_values how many values we want + first_value (OUT) the first value reserved by the handler + nb_reserved_values (OUT) how many values the handler reserved + + offset and increment means that we want values to be of the form + offset + N * increment, where N>=0 is integer. + If the function sets *first_value to ~(ulonglong)0 it means an error. + If the function sets *nb_reserved_values to ULONGLONG_MAX it means it has + reserved to "positive infinite". +*/ +void handler::get_auto_increment(ulonglong offset, ulonglong increment, + ulonglong nb_desired_values, + ulonglong *first_value, + ulonglong *nb_reserved_values) +{ + ulonglong nr; + int error; + + (void) extra(HA_EXTRA_KEYREAD); + table->mark_columns_used_by_index_no_reset(table->s->next_number_index, + table->read_set); + column_bitmaps_signal(); + index_init(table->s->next_number_index, 1); + if (table->s->next_number_keypart == 0) + { // Autoincrement at key-start + error=index_last(table->record[1]); + /* + MySQL implicitely assumes such method does locking (as MySQL decides to + use nr+increment without checking again with the handler, in + handler::update_auto_increment()), so reserves to infinite. + */ + *nb_reserved_values= ULONGLONG_MAX; + } + else + { + uchar key[MAX_KEY_LENGTH]; + key_copy(key, table->record[0], + table->key_info + table->s->next_number_index, + table->s->next_number_key_offset); + error= index_read_map(table->record[1], key, + make_prev_keypart_map(table->s->next_number_keypart), + HA_READ_PREFIX_LAST); + /* + MySQL needs to call us for next row: assume we are inserting ("a",null) + here, we return 3, and next this statement will want to insert + ("b",null): there is no reason why ("b",3+1) would be the good row to + insert: maybe it already exists, maybe 3+1 is too large... + */ + *nb_reserved_values= 1; + } + + if (error) + nr=1; + else + nr= ((ulonglong) table->next_number_field-> + val_int_offset(table->s->rec_buff_length)+1); + index_end(); + (void) extra(HA_EXTRA_NO_KEYREAD); + *first_value= nr; +} + + +void handler::ha_release_auto_increment() +{ + release_auto_increment(); + insert_id_for_cur_row= 0; + auto_inc_interval_for_cur_row.replace(0, 0, 0); + auto_inc_intervals_count= 0; + if (next_insert_id > 0) + { + next_insert_id= 0; + /* + this statement used forced auto_increment values if there were some, + wipe them away for other statements. + */ + table->in_use->auto_inc_intervals_forced.empty(); + } +} + + +void handler::print_keydup_error(uint key_nr, const char *msg) +{ + /* Write the duplicated key in the error message */ + char key[MAX_KEY_LENGTH]; + String str(key,sizeof(key),system_charset_info); + + if (key_nr == MAX_KEY) + { + /* Key is unknown */ + str.copy("", 0, system_charset_info); + my_printf_error(ER_DUP_ENTRY, msg, MYF(0), str.c_ptr(), "*UNKNOWN*"); + } + else + { + /* Table is opened and defined at this point */ + key_unpack(&str,table,(uint) key_nr); + uint max_length=MYSQL_ERRMSG_SIZE-(uint) strlen(msg); + if (str.length() >= max_length) + { + str.length(max_length-4); + str.append(STRING_WITH_LEN("...")); + } + my_printf_error(ER_DUP_ENTRY, msg, + MYF(0), str.c_ptr_safe(), table->key_info[key_nr].name); + } +} + + +/** + Print error that we got from handler function. + + @note + In case of delete table it's only safe to use the following parts of + the 'table' structure: + - table->s->path + - table->alias +*/ +void handler::print_error(int error, myf errflag) +{ + DBUG_ENTER("handler::print_error"); + DBUG_PRINT("enter",("error: %d",error)); + + int textno=ER_GET_ERRNO; + switch (error) { + case EACCES: + textno=ER_OPEN_AS_READONLY; + break; + case EAGAIN: + textno=ER_FILE_USED; + break; + case ENOENT: + textno=ER_FILE_NOT_FOUND; + break; + case HA_ERR_KEY_NOT_FOUND: + case HA_ERR_NO_ACTIVE_RECORD: + case HA_ERR_END_OF_FILE: + textno=ER_KEY_NOT_FOUND; + break; + case HA_ERR_WRONG_MRG_TABLE_DEF: + textno=ER_WRONG_MRG_TABLE; + break; + case HA_ERR_FOUND_DUPP_KEY: + { + uint key_nr=get_dup_key(error); + if ((int) key_nr >= 0) + { + print_keydup_error(key_nr, ER(ER_DUP_ENTRY_WITH_KEY_NAME)); + DBUG_VOID_RETURN; + } + textno=ER_DUP_KEY; + break; + } + case HA_ERR_FOREIGN_DUPLICATE_KEY: + { + uint key_nr= get_dup_key(error); + if ((int) key_nr >= 0) + { + uint max_length; + /* Write the key in the error message */ + char key[MAX_KEY_LENGTH]; + String str(key,sizeof(key),system_charset_info); + /* Table is opened and defined at this point */ + key_unpack(&str,table,(uint) key_nr); + max_length= (MYSQL_ERRMSG_SIZE- + (uint) strlen(ER(ER_FOREIGN_DUPLICATE_KEY))); + if (str.length() >= max_length) + { + str.length(max_length-4); + str.append(STRING_WITH_LEN("...")); + } + my_error(ER_FOREIGN_DUPLICATE_KEY, MYF(0), table_share->table_name.str, + str.c_ptr_safe(), key_nr+1); + DBUG_VOID_RETURN; + } + textno= ER_DUP_KEY; + break; + } + case HA_ERR_NULL_IN_SPATIAL: + my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, MYF(0)); + DBUG_VOID_RETURN; + case HA_ERR_FOUND_DUPP_UNIQUE: + textno=ER_DUP_UNIQUE; + break; + case HA_ERR_RECORD_CHANGED: + textno=ER_CHECKREAD; + break; + case HA_ERR_CRASHED: + textno=ER_NOT_KEYFILE; + break; + case HA_ERR_WRONG_IN_RECORD: + textno= ER_CRASHED_ON_USAGE; + break; + case HA_ERR_CRASHED_ON_USAGE: + textno=ER_CRASHED_ON_USAGE; + break; + case HA_ERR_NOT_A_TABLE: + textno= error; + break; + case HA_ERR_CRASHED_ON_REPAIR: + textno=ER_CRASHED_ON_REPAIR; + break; + case HA_ERR_OUT_OF_MEM: + textno=ER_OUT_OF_RESOURCES; + break; + case HA_ERR_WRONG_COMMAND: + textno=ER_ILLEGAL_HA; + break; + case HA_ERR_OLD_FILE: + textno=ER_OLD_KEYFILE; + break; + case HA_ERR_UNSUPPORTED: + textno=ER_UNSUPPORTED_EXTENSION; + break; + case HA_ERR_RECORD_FILE_FULL: + case HA_ERR_INDEX_FILE_FULL: + { + textno=ER_RECORD_FILE_FULL; + /* Write the error message to error log */ + errflag|= ME_NOREFRESH; + break; + } + case HA_ERR_LOCK_WAIT_TIMEOUT: + textno=ER_LOCK_WAIT_TIMEOUT; + break; + case HA_ERR_LOCK_TABLE_FULL: + textno=ER_LOCK_TABLE_FULL; + break; + case HA_ERR_LOCK_DEADLOCK: + textno=ER_LOCK_DEADLOCK; + break; + case HA_ERR_READ_ONLY_TRANSACTION: + textno=ER_READ_ONLY_TRANSACTION; + break; + case HA_ERR_CANNOT_ADD_FOREIGN: + textno=ER_CANNOT_ADD_FOREIGN; + break; + case HA_ERR_ROW_IS_REFERENCED: + { + String str; + get_error_message(error, &str); + my_error(ER_ROW_IS_REFERENCED_2, MYF(0), str.c_ptr_safe()); + DBUG_VOID_RETURN; + } + case HA_ERR_NO_REFERENCED_ROW: + { + String str; + get_error_message(error, &str); + my_error(ER_NO_REFERENCED_ROW_2, MYF(0), str.c_ptr_safe()); + DBUG_VOID_RETURN; + } + case HA_ERR_TABLE_DEF_CHANGED: + textno=ER_TABLE_DEF_CHANGED; + break; + case HA_ERR_NO_SUCH_TABLE: + my_error(ER_NO_SUCH_TABLE, MYF(0), table_share->db.str, + table_share->table_name.str); + DBUG_VOID_RETURN; + case HA_ERR_RBR_LOGGING_FAILED: + textno= ER_BINLOG_ROW_LOGGING_FAILED; + break; + case HA_ERR_DROP_INDEX_FK: + { + const char *ptr= "???"; + uint key_nr= get_dup_key(error); + if ((int) key_nr >= 0) + ptr= table->key_info[key_nr].name; + my_error(ER_DROP_INDEX_FK, MYF(0), ptr); + DBUG_VOID_RETURN; + } + case HA_ERR_TABLE_NEEDS_UPGRADE: + textno=ER_TABLE_NEEDS_UPGRADE; + break; + case HA_ERR_TABLE_READONLY: + textno= ER_OPEN_AS_READONLY; + break; + case HA_ERR_AUTOINC_READ_FAILED: + textno= ER_AUTOINC_READ_FAILED; + break; + case HA_ERR_AUTOINC_ERANGE: + textno= ER_WARN_DATA_OUT_OF_RANGE; + break; + case HA_ERR_TOO_MANY_CONCURRENT_TRXS: + textno= ER_TOO_MANY_CONCURRENT_TRXS; + break; + default: + { + /* The error was "unknown" to this function. + Ask handler if it has got a message for this error */ + bool temporary= FALSE; + String str; + temporary= get_error_message(error, &str); + if (!str.is_empty()) + { + const char* engine= table_type(); + if (temporary) + my_error(ER_GET_TEMPORARY_ERRMSG, MYF(0), error, str.ptr(), engine); + else + my_error(ER_GET_ERRMSG, MYF(0), error, str.ptr(), engine); + } + else + my_error(ER_GET_ERRNO,errflag,error); + DBUG_VOID_RETURN; + } + } + my_error(textno, errflag, table_share->table_name.str, error); + DBUG_VOID_RETURN; +} + + +/** + Return an error message specific to this handler. + + @param error error code previously returned by handler + @param buf pointer to String where to add error message + + @return + Returns true if this is a temporary error +*/ +bool handler::get_error_message(int error, String* buf) +{ + return FALSE; +} + + +/** + Check for incompatible collation changes. + + @retval + HA_ADMIN_NEEDS_UPGRADE Table may have data requiring upgrade. + @retval + 0 No upgrade required. +*/ + +int handler::check_collation_compatibility() +{ + ulong mysql_version= table->s->mysql_version; + + if (mysql_version < 50124) + { + KEY *key= table->key_info; + KEY *key_end= key + table->s->keys; + for (; key < key_end; key++) + { + KEY_PART_INFO *key_part= key->key_part; + KEY_PART_INFO *key_part_end= key_part + key->key_parts; + for (; key_part < key_part_end; key_part++) + { + if (!key_part->fieldnr) + continue; + Field *field= table->field[key_part->fieldnr - 1]; + uint cs_number= field->charset()->number; + if ((mysql_version < 50048 && + (cs_number == 11 || /* ascii_general_ci - bug #29499, bug #27562 */ + cs_number == 41 || /* latin7_general_ci - bug #29461 */ + cs_number == 42 || /* latin7_general_cs - bug #29461 */ + cs_number == 20 || /* latin7_estonian_cs - bug #29461 */ + cs_number == 21 || /* latin2_hungarian_ci - bug #29461 */ + cs_number == 22 || /* koi8u_general_ci - bug #29461 */ + cs_number == 23 || /* cp1251_ukrainian_ci - bug #29461 */ + cs_number == 26)) || /* cp1250_general_ci - bug #29461 */ + (mysql_version < 50124 && + (cs_number == 33 || /* utf8_general_ci - bug #27877 */ + cs_number == 35))) /* ucs2_general_ci - bug #27877 */ + return HA_ADMIN_NEEDS_UPGRADE; + } + } + } + return 0; +} + + +int handler::ha_check_for_upgrade(HA_CHECK_OPT *check_opt) +{ + int error; + KEY *keyinfo, *keyend; + KEY_PART_INFO *keypart, *keypartend; + + if (!table->s->mysql_version) + { + /* check for blob-in-key error */ + keyinfo= table->key_info; + keyend= table->key_info + table->s->keys; + for (; keyinfo < keyend; keyinfo++) + { + keypart= keyinfo->key_part; + keypartend= keypart + keyinfo->key_parts; + for (; keypart < keypartend; keypart++) + { + if (!keypart->fieldnr) + continue; + Field *field= table->field[keypart->fieldnr-1]; + if (field->type() == MYSQL_TYPE_BLOB) + { + if (check_opt->sql_flags & TT_FOR_UPGRADE) + check_opt->flags= T_MEDIUM; + return HA_ADMIN_NEEDS_CHECK; + } + } + } + } + if (table->s->frm_version != FRM_VER_TRUE_VARCHAR) + return HA_ADMIN_NEEDS_ALTER; + + if ((error= check_collation_compatibility())) + return error; + + return check_for_upgrade(check_opt); +} + + +int handler::check_old_types() +{ + Field** field; + + if (!table->s->mysql_version) + { + /* check for bad DECIMAL field */ + for (field= table->field; (*field); field++) + { + if ((*field)->type() == MYSQL_TYPE_NEWDECIMAL) + { + return HA_ADMIN_NEEDS_ALTER; + } + if ((*field)->type() == MYSQL_TYPE_VAR_STRING) + { + return HA_ADMIN_NEEDS_ALTER; + } + } + } + return 0; +} + + +static bool update_frm_version(TABLE *table) +{ + char path[FN_REFLEN]; + File file; + int result= 1; + DBUG_ENTER("update_frm_version"); + + /* + No need to update frm version in case table was created or checked + by server with the same version. This also ensures that we do not + update frm version for temporary tables as this code doesn't support + temporary tables. + */ + if (table->s->mysql_version == MYSQL_VERSION_ID) + DBUG_RETURN(0); + + strxmov(path, table->s->normalized_path.str, reg_ext, NullS); + + if ((file= my_open(path, O_RDWR|O_BINARY, MYF(MY_WME))) >= 0) + { + uchar version[4]; + char *key= table->s->table_cache_key.str; + uint key_length= table->s->table_cache_key.length; + TABLE *entry; + HASH_SEARCH_STATE state; + + int4store(version, MYSQL_VERSION_ID); + + if ((result= my_pwrite(file,(uchar*) version,4,51L,MYF_RW))) + goto err; + + for (entry=(TABLE*) hash_first(&open_cache,(uchar*) key,key_length, &state); + entry; + entry= (TABLE*) hash_next(&open_cache,(uchar*) key,key_length, &state)) + entry->s->mysql_version= MYSQL_VERSION_ID; + } +err: + if (file >= 0) + VOID(my_close(file,MYF(MY_WME))); + DBUG_RETURN(result); +} + + + +/** + @return + key if error because of duplicated keys +*/ +uint handler::get_dup_key(int error) +{ + DBUG_ENTER("handler::get_dup_key"); + table->file->errkey = (uint) -1; + if (error == HA_ERR_FOUND_DUPP_KEY || error == HA_ERR_FOREIGN_DUPLICATE_KEY || + error == HA_ERR_FOUND_DUPP_UNIQUE || error == HA_ERR_NULL_IN_SPATIAL || + error == HA_ERR_DROP_INDEX_FK) + table->file->info(HA_STATUS_ERRKEY | HA_STATUS_NO_LOCK); + DBUG_RETURN(table->file->errkey); +} + + +/** + Delete all files with extension from bas_ext(). + + @param name Base name of table + + @note + We assume that the handler may return more extensions than + was actually used for the file. + + @retval + 0 If we successfully deleted at least one file from base_ext and + didn't get any other errors than ENOENT + @retval + !0 Error +*/ +int handler::delete_table(const char *name) +{ + int saved_error= 0; + int error= 0; + int enoent_or_zero= ENOENT; // Error if no file was deleted + char buff[FN_REFLEN]; + + for (const char **ext=bas_ext(); *ext ; ext++) + { + fn_format(buff, name, "", *ext, MY_UNPACK_FILENAME|MY_APPEND_EXT); + if (my_delete_with_symlink(buff, MYF(0))) + { + if (my_errno != ENOENT) + { + /* + If error on the first existing file, return the error. + Otherwise delete as much as possible. + */ + if (enoent_or_zero) + return my_errno; + saved_error= my_errno; + } + } + else + enoent_or_zero= 0; // No error for ENOENT + error= enoent_or_zero; + } + return saved_error ? saved_error : error; +} + + +int handler::rename_table(const char * from, const char * to) +{ + int error= 0; + const char **ext, **start_ext; + start_ext= bas_ext(); + for (ext= start_ext; *ext ; ext++) + { + if (rename_file_ext(from, to, *ext)) + { + if ((error=my_errno) != ENOENT) + break; + error= 0; + } + } + if (error) + { + /* Try to revert the rename. Ignore errors. */ + for (; ext >= start_ext; ext--) + rename_file_ext(to, from, *ext); + } + return error; +} + + +void handler::drop_table(const char *name) +{ + close(); + delete_table(name); +} + + +/** + Performs checks upon the table. + + @param thd thread doing CHECK TABLE operation + @param check_opt options from the parser + + @retval + HA_ADMIN_OK Successful upgrade + @retval + HA_ADMIN_NEEDS_UPGRADE Table has structures requiring upgrade + @retval + HA_ADMIN_NEEDS_ALTER Table has structures requiring ALTER TABLE + @retval + HA_ADMIN_NOT_IMPLEMENTED +*/ +int handler::ha_check(THD *thd, HA_CHECK_OPT *check_opt) +{ + int error; + + if ((table->s->mysql_version >= MYSQL_VERSION_ID) && + (check_opt->sql_flags & TT_FOR_UPGRADE)) + return 0; + + if (table->s->mysql_version < MYSQL_VERSION_ID) + { + if ((error= check_old_types())) + return error; + error= ha_check_for_upgrade(check_opt); + if (error && (error != HA_ADMIN_NEEDS_CHECK)) + return error; + if (!error && (check_opt->sql_flags & TT_FOR_UPGRADE)) + return 0; + } + if ((error= check(thd, check_opt))) + return error; + return update_frm_version(table); +} + +/** + A helper function to mark a transaction read-write, + if it is started. +*/ + +inline +void +handler::mark_trx_read_write() +{ + Ha_trx_info *ha_info= &ha_thd()->ha_data[ht->slot].ha_info[0]; + /* + When a storage engine method is called, the transaction must + have been started, unless it's a DDL call, for which the + storage engine starts the transaction internally, and commits + it internally, without registering in the ha_list. + Unfortunately here we can't know know for sure if the engine + has registered the transaction or not, so we must check. + */ + if (ha_info->is_started()) + { + DBUG_ASSERT(has_transactions()); + /* + table_share can be NULL in ha_delete_table(). See implementation + of standalone function ha_delete_table() in sql_base.cc. + */ + if (table_share == NULL || table_share->tmp_table == NO_TMP_TABLE) + ha_info->set_trx_read_write(); + } +} + + +/** + Repair table: public interface. + + @sa handler::repair() +*/ + +int handler::ha_repair(THD* thd, HA_CHECK_OPT* check_opt) +{ + int result; + + mark_trx_read_write(); + + if ((result= repair(thd, check_opt))) + return result; + return update_frm_version(table); +} + + +/** + Bulk update row: public interface. + + @sa handler::bulk_update_row() +*/ + +int +handler::ha_bulk_update_row(const uchar *old_data, uchar *new_data, + uint *dup_key_found) +{ + mark_trx_read_write(); + + return bulk_update_row(old_data, new_data, dup_key_found); +} + + +/** + Delete all rows: public interface. + + @sa handler::delete_all_rows() +*/ + +int +handler::ha_delete_all_rows() +{ + mark_trx_read_write(); + + return delete_all_rows(); +} + + +/** + Reset auto increment: public interface. + + @sa handler::reset_auto_increment() +*/ + +int +handler::ha_reset_auto_increment(ulonglong value) +{ + mark_trx_read_write(); + + return reset_auto_increment(value); +} + + +/** + Backup table: public interface. + + @sa handler::backup() +*/ + +int +handler::ha_backup(THD* thd, HA_CHECK_OPT* check_opt) +{ + mark_trx_read_write(); + + return backup(thd, check_opt); +} + + +/** + Restore table: public interface. + + @sa handler::restore() +*/ + +int +handler::ha_restore(THD* thd, HA_CHECK_OPT* check_opt) +{ + mark_trx_read_write(); + + return restore(thd, check_opt); +} + + +/** + Optimize table: public interface. + + @sa handler::optimize() +*/ + +int +handler::ha_optimize(THD* thd, HA_CHECK_OPT* check_opt) +{ + mark_trx_read_write(); + + return optimize(thd, check_opt); +} + + +/** + Analyze table: public interface. + + @sa handler::analyze() +*/ + +int +handler::ha_analyze(THD* thd, HA_CHECK_OPT* check_opt) +{ + mark_trx_read_write(); + + return analyze(thd, check_opt); +} + + +/** + Check and repair table: public interface. + + @sa handler::check_and_repair() +*/ + +bool +handler::ha_check_and_repair(THD *thd) +{ + mark_trx_read_write(); + + return check_and_repair(thd); +} + + +/** + Disable indexes: public interface. + + @sa handler::disable_indexes() +*/ + +int +handler::ha_disable_indexes(uint mode) +{ + mark_trx_read_write(); + + return disable_indexes(mode); +} + + +/** + Enable indexes: public interface. + + @sa handler::enable_indexes() +*/ + +int +handler::ha_enable_indexes(uint mode) +{ + mark_trx_read_write(); + + return enable_indexes(mode); +} + + +/** + Discard or import tablespace: public interface. + + @sa handler::discard_or_import_tablespace() +*/ + +int +handler::ha_discard_or_import_tablespace(my_bool discard) +{ + mark_trx_read_write(); + + return discard_or_import_tablespace(discard); +} + + +/** + Prepare for alter: public interface. + + Called to prepare an *online* ALTER. + + @sa handler::prepare_for_alter() +*/ + +void +handler::ha_prepare_for_alter() +{ + mark_trx_read_write(); + + prepare_for_alter(); +} + + +/** + Rename table: public interface. + + @sa handler::rename_table() +*/ + +int +handler::ha_rename_table(const char *from, const char *to) +{ + mark_trx_read_write(); + + return rename_table(from, to); +} + + +/** + Delete table: public interface. + + @sa handler::delete_table() +*/ + +int +handler::ha_delete_table(const char *name) +{ + mark_trx_read_write(); + + return delete_table(name); +} + + +/** + Drop table in the engine: public interface. + + @sa handler::drop_table() +*/ + +void +handler::ha_drop_table(const char *name) +{ + mark_trx_read_write(); + + return drop_table(name); +} + + +/** + Create a table in the engine: public interface. + + @sa handler::create() +*/ + +int +handler::ha_create(const char *name, TABLE *form, HA_CREATE_INFO *info) +{ + mark_trx_read_write(); + + return create(name, form, info); +} + + +/** + Create handler files for CREATE TABLE: public interface. + + @sa handler::create_handler_files() +*/ + +int +handler::ha_create_handler_files(const char *name, const char *old_name, + int action_flag, HA_CREATE_INFO *info) +{ + mark_trx_read_write(); + + return create_handler_files(name, old_name, action_flag, info); +} + + +/** + Change partitions: public interface. + + @sa handler::change_partitions() +*/ + +int +handler::ha_change_partitions(HA_CREATE_INFO *create_info, + const char *path, + ulonglong * const copied, + ulonglong * const deleted, + const uchar *pack_frm_data, + size_t pack_frm_len) +{ + mark_trx_read_write(); + + return change_partitions(create_info, path, copied, deleted, + pack_frm_data, pack_frm_len); +} + + +/** + Drop partitions: public interface. + + @sa handler::drop_partitions() +*/ + +int +handler::ha_drop_partitions(const char *path) +{ + mark_trx_read_write(); + + return drop_partitions(path); +} + + +/** + Rename partitions: public interface. + + @sa handler::rename_partitions() +*/ + +int +handler::ha_rename_partitions(const char *path) +{ + mark_trx_read_write(); + + return rename_partitions(path); +} + + +/** + Tell the storage engine that it is allowed to "disable transaction" in the + handler. It is a hint that ACID is not required - it is used in NDB for + ALTER TABLE, for example, when data are copied to temporary table. + A storage engine may treat this hint any way it likes. NDB for example + starts to commit every now and then automatically. + This hint can be safely ignored. +*/ +int ha_enable_transaction(THD *thd, bool on) +{ + int error=0; + DBUG_ENTER("ha_enable_transaction"); + DBUG_PRINT("enter", ("on: %d", (int) on)); + + if ((thd->transaction.on= on)) + { + /* + Now all storage engines should have transaction handling enabled. + But some may have it enabled all the time - "disabling" transactions + is an optimization hint that storage engine is free to ignore. + So, let's commit an open transaction (if any) now. + */ + if (!(error= ha_commit_trans(thd, 0))) + error= end_trans(thd, COMMIT); + } + DBUG_RETURN(error); +} + +int handler::index_next_same(uchar *buf, const uchar *key, uint keylen) +{ + int error; + DBUG_ENTER("index_next_same"); + if (!(error=index_next(buf))) + { + my_ptrdiff_t ptrdiff= buf - table->record[0]; + uchar *save_record_0; + KEY *key_info; + KEY_PART_INFO *key_part; + KEY_PART_INFO *key_part_end; + LINT_INIT(save_record_0); + LINT_INIT(key_info); + LINT_INIT(key_part); + LINT_INIT(key_part_end); + + /* + key_cmp_if_same() compares table->record[0] against 'key'. + In parts it uses table->record[0] directly, in parts it uses + field objects with their local pointers into table->record[0]. + If 'buf' is distinct from table->record[0], we need to move + all record references. This is table->record[0] itself and + the field pointers of the fields used in this key. + */ + if (ptrdiff) + { + save_record_0= table->record[0]; + table->record[0]= buf; + key_info= table->key_info + active_index; + key_part= key_info->key_part; + key_part_end= key_part + key_info->key_parts; + for (; key_part < key_part_end; key_part++) + { + DBUG_ASSERT(key_part->field); + key_part->field->move_field_offset(ptrdiff); + } + } + + if (key_cmp_if_same(table, key, active_index, keylen)) + { + table->status=STATUS_NOT_FOUND; + error=HA_ERR_END_OF_FILE; + } + + /* Move back if necessary. */ + if (ptrdiff) + { + table->record[0]= save_record_0; + for (key_part= key_info->key_part; key_part < key_part_end; key_part++) + key_part->field->move_field_offset(-ptrdiff); + } + } + DBUG_RETURN(error); +} + + +void handler::get_dynamic_partition_info(PARTITION_INFO *stat_info, + uint part_id) +{ + info(HA_STATUS_CONST | HA_STATUS_TIME | HA_STATUS_VARIABLE | + HA_STATUS_NO_LOCK); + stat_info->records= stats.records; + stat_info->mean_rec_length= stats.mean_rec_length; + stat_info->data_file_length= stats.data_file_length; + stat_info->max_data_file_length= stats.max_data_file_length; + stat_info->index_file_length= stats.index_file_length; + stat_info->delete_length= stats.delete_length; + stat_info->create_time= stats.create_time; + stat_info->update_time= stats.update_time; + stat_info->check_time= stats.check_time; + stat_info->check_sum= 0; + if (table_flags() & (ulong) HA_HAS_CHECKSUM) + stat_info->check_sum= checksum(); + return; +} + + +/**************************************************************************** +** Some general functions that isn't in the handler class +****************************************************************************/ + +/** + Initiates table-file and calls appropriate database-creator. + + @retval + 0 ok + @retval + 1 error +*/ +int ha_create_table(THD *thd, const char *path, + const char *db, const char *table_name, + HA_CREATE_INFO *create_info, + bool update_create_info) +{ + int error= 1; + TABLE table; + char name_buff[FN_REFLEN]; + const char *name; + TABLE_SHARE share; + DBUG_ENTER("ha_create_table"); + + init_tmp_table_share(thd, &share, db, 0, table_name, path); + if (open_table_def(thd, &share, 0) || + open_table_from_share(thd, &share, "", 0, (uint) READ_ALL, 0, &table, + TRUE)) + goto err; + + if (update_create_info) + update_create_info_from_table(create_info, &table); + + name= get_canonical_filename(table.file, share.path.str, name_buff); + + error= table.file->ha_create(name, &table, create_info); + VOID(closefrm(&table, 0)); + if (error) + { + strxmov(name_buff, db, ".", table_name, NullS); + my_error(ER_CANT_CREATE_TABLE, MYF(ME_BELL+ME_WAITTANG), name_buff, error); + } +err: + free_table_share(&share); + DBUG_RETURN(error != 0); +} + +/** + Try to discover table from engine. + + @note + If found, write the frm file to disk. + + @retval + -1 Table did not exists + @retval + 0 Table created ok + @retval + > 0 Error, table existed but could not be created +*/ +int ha_create_table_from_engine(THD* thd, const char *db, const char *name) +{ + int error; + uchar *frmblob; + size_t frmlen; + char path[FN_REFLEN + 1]; + HA_CREATE_INFO create_info; + TABLE table; + TABLE_SHARE share; + DBUG_ENTER("ha_create_table_from_engine"); + DBUG_PRINT("enter", ("name '%s'.'%s'", db, name)); + + bzero((uchar*) &create_info,sizeof(create_info)); + if ((error= ha_discover(thd, db, name, &frmblob, &frmlen))) + { + /* Table could not be discovered and thus not created */ + DBUG_RETURN(error); + } + + /* + Table exists in handler and could be discovered + frmblob and frmlen are set, write the frm to disk + */ + + build_table_filename(path, sizeof(path) - 1, db, name, "", 0); + // Save the frm file + error= writefrm(path, frmblob, frmlen); + my_free(frmblob, MYF(0)); + if (error) + DBUG_RETURN(2); + + init_tmp_table_share(thd, &share, db, 0, name, path); + if (open_table_def(thd, &share, 0)) + { + DBUG_RETURN(3); + } + if (open_table_from_share(thd, &share, "" ,0, 0, 0, &table, FALSE)) + { + free_table_share(&share); + DBUG_RETURN(3); + } + + update_create_info_from_table(&create_info, &table); + create_info.table_options|= HA_OPTION_CREATE_FROM_ENGINE; + + get_canonical_filename(table.file, path, path); + error=table.file->ha_create(path, &table, &create_info); + VOID(closefrm(&table, 1)); + + DBUG_RETURN(error != 0); +} + +void st_ha_check_opt::init() +{ + flags= sql_flags= 0; + sort_buffer_size = current_thd->variables.myisam_sort_buff_size; +} + + +/***************************************************************************** + Key cache handling. + + This code is only relevant for ISAM/MyISAM tables + + key_cache->cache may be 0 only in the case where a key cache is not + initialized or when we where not able to init the key cache in a previous + call to ha_init_key_cache() (probably out of memory) +*****************************************************************************/ + +/** + Init a key cache if it has not been initied before. +*/ +int ha_init_key_cache(const char *name, KEY_CACHE *key_cache) +{ + DBUG_ENTER("ha_init_key_cache"); + + if (!key_cache->key_cache_inited) + { + pthread_mutex_lock(&LOCK_global_system_variables); + size_t tmp_buff_size= (size_t) key_cache->param_buff_size; + uint tmp_block_size= (uint) key_cache->param_block_size; + uint division_limit= key_cache->param_division_limit; + uint age_threshold= key_cache->param_age_threshold; + pthread_mutex_unlock(&LOCK_global_system_variables); + DBUG_RETURN(!init_key_cache(key_cache, + tmp_block_size, + tmp_buff_size, + division_limit, age_threshold)); + } + DBUG_RETURN(0); +} + + +/** + Resize key cache. +*/ +int ha_resize_key_cache(KEY_CACHE *key_cache) +{ + DBUG_ENTER("ha_resize_key_cache"); + + if (key_cache->key_cache_inited) + { + pthread_mutex_lock(&LOCK_global_system_variables); + size_t tmp_buff_size= (size_t) key_cache->param_buff_size; + long tmp_block_size= (long) key_cache->param_block_size; + uint division_limit= key_cache->param_division_limit; + uint age_threshold= key_cache->param_age_threshold; + pthread_mutex_unlock(&LOCK_global_system_variables); + DBUG_RETURN(!resize_key_cache(key_cache, tmp_block_size, + tmp_buff_size, + division_limit, age_threshold)); + } + DBUG_RETURN(0); +} + + +/** + Change parameters for key cache (like size) +*/ +int ha_change_key_cache_param(KEY_CACHE *key_cache) +{ + if (key_cache->key_cache_inited) + { + pthread_mutex_lock(&LOCK_global_system_variables); + uint division_limit= key_cache->param_division_limit; + uint age_threshold= key_cache->param_age_threshold; + pthread_mutex_unlock(&LOCK_global_system_variables); + change_key_cache_param(key_cache, division_limit, age_threshold); + } + return 0; +} + +/** + Free memory allocated by a key cache. +*/ +int ha_end_key_cache(KEY_CACHE *key_cache) +{ + end_key_cache(key_cache, 1); // Can never fail + return 0; +} + +/** + Move all tables from one key cache to another one. +*/ +int ha_change_key_cache(KEY_CACHE *old_key_cache, + KEY_CACHE *new_key_cache) +{ + mi_change_key_cache(old_key_cache, new_key_cache); + return 0; +} + + +/** + Try to discover one table from handler(s). + + @retval + -1 Table did not exists + @retval + 0 OK. In this case *frmblob and *frmlen are set + @retval + >0 error. frmblob and frmlen may not be set +*/ +struct st_discover_args +{ + const char *db; + const char *name; + uchar **frmblob; + size_t *frmlen; +}; + +static my_bool discover_handlerton(THD *thd, plugin_ref plugin, + void *arg) +{ + st_discover_args *vargs= (st_discover_args *)arg; + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->discover && + (!(hton->discover(hton, thd, vargs->db, vargs->name, + vargs->frmblob, + vargs->frmlen)))) + return TRUE; + + return FALSE; +} + +int ha_discover(THD *thd, const char *db, const char *name, + uchar **frmblob, size_t *frmlen) +{ + int error= -1; // Table does not exist in any handler + DBUG_ENTER("ha_discover"); + DBUG_PRINT("enter", ("db: %s, name: %s", db, name)); + st_discover_args args= {db, name, frmblob, frmlen}; + + if (is_prefix(name,tmp_file_prefix)) /* skip temporary tables */ + DBUG_RETURN(error); + + if (plugin_foreach(thd, discover_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &args)) + error= 0; + + if (!error) + status_var_increment(thd->status_var.ha_discover_count); + DBUG_RETURN(error); +} + + +/** + Call this function in order to give the handler the possiblity + to ask engine if there are any new tables that should be written to disk + or any dropped tables that need to be removed from disk +*/ +struct st_find_files_args +{ + const char *db; + const char *path; + const char *wild; + bool dir; + List *files; +}; + +static my_bool find_files_handlerton(THD *thd, plugin_ref plugin, + void *arg) +{ + st_find_files_args *vargs= (st_find_files_args *)arg; + handlerton *hton= plugin_data(plugin, handlerton *); + + + if (hton->state == SHOW_OPTION_YES && hton->find_files) + if (hton->find_files(hton, thd, vargs->db, vargs->path, vargs->wild, + vargs->dir, vargs->files)) + return TRUE; + + return FALSE; +} + +int +ha_find_files(THD *thd,const char *db,const char *path, + const char *wild, bool dir, List *files) +{ + int error= 0; + DBUG_ENTER("ha_find_files"); + DBUG_PRINT("enter", ("db: '%s' path: '%s' wild: '%s' dir: %d", + db, path, wild ? wild : "NULL", dir)); + st_find_files_args args= {db, path, wild, dir, files}; + + plugin_foreach(thd, find_files_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &args); + /* The return value is not currently used */ + DBUG_RETURN(error); +} + +/** + Ask handler if the table exists in engine. + @retval + HA_ERR_NO_SUCH_TABLE Table does not exist + @retval + HA_ERR_TABLE_EXIST Table exists + @retval + \# Error code +*/ +struct st_table_exists_in_engine_args +{ + const char *db; + const char *name; + int err; +}; + +static my_bool table_exists_in_engine_handlerton(THD *thd, plugin_ref plugin, + void *arg) +{ + st_table_exists_in_engine_args *vargs= (st_table_exists_in_engine_args *)arg; + handlerton *hton= plugin_data(plugin, handlerton *); + + int err= HA_ERR_NO_SUCH_TABLE; + + if (hton->state == SHOW_OPTION_YES && hton->table_exists_in_engine) + err = hton->table_exists_in_engine(hton, thd, vargs->db, vargs->name); + + vargs->err = err; + if (vargs->err == HA_ERR_TABLE_EXIST) + return TRUE; + + return FALSE; +} + +int ha_table_exists_in_engine(THD* thd, const char* db, const char* name) +{ + DBUG_ENTER("ha_table_exists_in_engine"); + DBUG_PRINT("enter", ("db: %s, name: %s", db, name)); + st_table_exists_in_engine_args args= {db, name, HA_ERR_NO_SUCH_TABLE}; + plugin_foreach(thd, table_exists_in_engine_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &args); + DBUG_PRINT("exit", ("error: %d", args.err)); + DBUG_RETURN(args.err); +} + +#ifdef HAVE_NDB_BINLOG +/* + TODO: change this into a dynamic struct + List does not work as + 1. binlog_end is called when MEM_ROOT is gone + 2. cannot work with thd MEM_ROOT as memory should be freed +*/ +#define MAX_HTON_LIST_ST 63 +struct hton_list_st +{ + handlerton *hton[MAX_HTON_LIST_ST]; + uint sz; +}; + +struct binlog_func_st +{ + enum_binlog_func fn; + void *arg; +}; + +/** @brief + Listing handlertons first to avoid recursive calls and deadlock +*/ +static my_bool binlog_func_list(THD *thd, plugin_ref plugin, void *arg) +{ + hton_list_st *hton_list= (hton_list_st *)arg; + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->binlog_func) + { + uint sz= hton_list->sz; + if (sz == MAX_HTON_LIST_ST-1) + { + /* list full */ + return FALSE; + } + hton_list->hton[sz]= hton; + hton_list->sz= sz+1; + } + return FALSE; +} + +static my_bool binlog_func_foreach(THD *thd, binlog_func_st *bfn) +{ + hton_list_st hton_list; + uint i, sz; + + hton_list.sz= 0; + plugin_foreach(thd, binlog_func_list, + MYSQL_STORAGE_ENGINE_PLUGIN, &hton_list); + + for (i= 0, sz= hton_list.sz; i < sz ; i++) + hton_list.hton[i]->binlog_func(hton_list.hton[i], thd, bfn->fn, bfn->arg); + return FALSE; +} + +int ha_reset_logs(THD *thd) +{ + binlog_func_st bfn= {BFN_RESET_LOGS, 0}; + binlog_func_foreach(thd, &bfn); + return 0; +} + +void ha_reset_slave(THD* thd) +{ + binlog_func_st bfn= {BFN_RESET_SLAVE, 0}; + binlog_func_foreach(thd, &bfn); +} + +void ha_binlog_wait(THD* thd) +{ + binlog_func_st bfn= {BFN_BINLOG_WAIT, 0}; + binlog_func_foreach(thd, &bfn); +} + +int ha_binlog_end(THD* thd) +{ + binlog_func_st bfn= {BFN_BINLOG_END, 0}; + binlog_func_foreach(thd, &bfn); + return 0; +} + +int ha_binlog_index_purge_file(THD *thd, const char *file) +{ + binlog_func_st bfn= {BFN_BINLOG_PURGE_FILE, (void *)file}; + binlog_func_foreach(thd, &bfn); + return 0; +} + +struct binlog_log_query_st +{ + enum_binlog_command binlog_command; + const char *query; + uint query_length; + const char *db; + const char *table_name; +}; + +static my_bool binlog_log_query_handlerton2(THD *thd, + handlerton *hton, + void *args) +{ + struct binlog_log_query_st *b= (struct binlog_log_query_st*)args; + if (hton->state == SHOW_OPTION_YES && hton->binlog_log_query) + hton->binlog_log_query(hton, thd, + b->binlog_command, + b->query, + b->query_length, + b->db, + b->table_name); + return FALSE; +} + +static my_bool binlog_log_query_handlerton(THD *thd, + plugin_ref plugin, + void *args) +{ + return binlog_log_query_handlerton2(thd, plugin_data(plugin, handlerton *), args); +} + +void ha_binlog_log_query(THD *thd, handlerton *hton, + enum_binlog_command binlog_command, + const char *query, uint query_length, + const char *db, const char *table_name) +{ + struct binlog_log_query_st b; + b.binlog_command= binlog_command; + b.query= query; + b.query_length= query_length; + b.db= db; + b.table_name= table_name; + if (hton == 0) + plugin_foreach(thd, binlog_log_query_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &b); + else + binlog_log_query_handlerton2(thd, hton, &b); +} +#endif + +/** + Read the first row of a multi-range set. + + @param found_range_p Returns a pointer to the element in 'ranges' that + corresponds to the returned row. + @param ranges An array of KEY_MULTI_RANGE range descriptions. + @param range_count Number of ranges in 'ranges'. + @param sorted If result should be sorted per key. + @param buffer A HANDLER_BUFFER for internal handler usage. + + @note + - Record is read into table->record[0]. + - *found_range_p returns a valid value only if read_multi_range_first() + returns 0. + - Sorting is done within each range. If you want an overall sort, enter + 'ranges' with sorted ranges. + + @retval + 0 OK, found a row + @retval + HA_ERR_END_OF_FILE No rows in range + @retval + \# Error code +*/ +int handler::read_multi_range_first(KEY_MULTI_RANGE **found_range_p, + KEY_MULTI_RANGE *ranges, uint range_count, + bool sorted, HANDLER_BUFFER *buffer) +{ + int result= HA_ERR_END_OF_FILE; + DBUG_ENTER("handler::read_multi_range_first"); + multi_range_sorted= sorted; + multi_range_buffer= buffer; + + table->mark_columns_used_by_index_no_reset(active_index, table->read_set); + table->column_bitmaps_set(table->read_set, table->write_set); + + for (multi_range_curr= ranges, multi_range_end= ranges + range_count; + multi_range_curr < multi_range_end; + multi_range_curr++) + { + result= read_range_first(multi_range_curr->start_key.keypart_map ? + &multi_range_curr->start_key : 0, + multi_range_curr->end_key.keypart_map ? + &multi_range_curr->end_key : 0, + test(multi_range_curr->range_flag & EQ_RANGE), + multi_range_sorted); + if (result != HA_ERR_END_OF_FILE) + break; + } + + *found_range_p= multi_range_curr; + DBUG_PRINT("exit",("result %d", result)); + DBUG_RETURN(result); +} + + +/** + Read the next row of a multi-range set. + + @param found_range_p Returns a pointer to the element in 'ranges' that + corresponds to the returned row. + + @note + - Record is read into table->record[0]. + - *found_range_p returns a valid value only if read_multi_range_next() + returns 0. + + @retval + 0 OK, found a row + @retval + HA_ERR_END_OF_FILE No (more) rows in range + @retval + \# Error code +*/ +int handler::read_multi_range_next(KEY_MULTI_RANGE **found_range_p) +{ + int result; + DBUG_ENTER("handler::read_multi_range_next"); + + /* We should not be called after the last call returned EOF. */ + DBUG_ASSERT(multi_range_curr < multi_range_end); + + do + { + /* Save a call if there can be only one row in range. */ + if (multi_range_curr->range_flag != (UNIQUE_RANGE | EQ_RANGE)) + { + result= read_range_next(); + + /* On success or non-EOF errors jump to the end. */ + if (result != HA_ERR_END_OF_FILE) + break; + } + else + { + if (was_semi_consistent_read()) + goto scan_it_again; + /* + We need to set this for the last range only, but checking this + condition is more expensive than just setting the result code. + */ + result= HA_ERR_END_OF_FILE; + } + + multi_range_curr++; +scan_it_again: + /* Try the next range(s) until one matches a record. */ + for (; multi_range_curr < multi_range_end; multi_range_curr++) + { + result= read_range_first(multi_range_curr->start_key.keypart_map ? + &multi_range_curr->start_key : 0, + multi_range_curr->end_key.keypart_map ? + &multi_range_curr->end_key : 0, + test(multi_range_curr->range_flag & EQ_RANGE), + multi_range_sorted); + if (result != HA_ERR_END_OF_FILE) + break; + } + } + while ((result == HA_ERR_END_OF_FILE) && + (multi_range_curr < multi_range_end)); + + *found_range_p= multi_range_curr; + DBUG_PRINT("exit",("handler::read_multi_range_next: result %d", result)); + DBUG_RETURN(result); +} + + +/** + Read first row between two ranges. + Store ranges for future calls to read_range_next. + + @param start_key Start key. Is 0 if no min range + @param end_key End key. Is 0 if no max range + @param eq_range_arg Set to 1 if start_key == end_key + @param sorted Set to 1 if result should be sorted per key + + @note + Record is read into table->record[0] + + @retval + 0 Found row + @retval + HA_ERR_END_OF_FILE No rows in range + @retval + \# Error code +*/ +int handler::read_range_first(const key_range *start_key, + const key_range *end_key, + bool eq_range_arg, bool sorted) +{ + int result; + DBUG_ENTER("handler::read_range_first"); + + eq_range= eq_range_arg; + end_range= 0; + if (end_key) + { + end_range= &save_end_range; + save_end_range= *end_key; + key_compare_result_on_equal= ((end_key->flag == HA_READ_BEFORE_KEY) ? 1 : + (end_key->flag == HA_READ_AFTER_KEY) ? -1 : 0); + } + range_key_part= table->key_info[active_index].key_part; + + if (!start_key) // Read first record + result= index_first(table->record[0]); + else + result= index_read_map(table->record[0], + start_key->key, + start_key->keypart_map, + start_key->flag); + if (result) + DBUG_RETURN((result == HA_ERR_KEY_NOT_FOUND) + ? HA_ERR_END_OF_FILE + : result); + + DBUG_RETURN (compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE); +} + + +/** + Read next row between two ranges. + + @note + Record is read into table->record[0] + + @retval + 0 Found row + @retval + HA_ERR_END_OF_FILE No rows in range + @retval + \# Error code +*/ +int handler::read_range_next() +{ + int result; + DBUG_ENTER("handler::read_range_next"); + + if (eq_range) + { + /* We trust that index_next_same always gives a row in range */ + DBUG_RETURN(index_next_same(table->record[0], + end_range->key, + end_range->length)); + } + result= index_next(table->record[0]); + if (result) + DBUG_RETURN(result); + DBUG_RETURN(compare_key(end_range) <= 0 ? 0 : HA_ERR_END_OF_FILE); +} + + +/** + Compare if found key (in row) is over max-value. + + @param range range to compare to row. May be 0 for no range + + @seealso + key.cc::key_cmp() + + @return + The return value is SIGN(key_in_row - range_key): + + - 0 : Key is equal to range or 'range' == 0 (no range) + - -1 : Key is less than range + - 1 : Key is larger than range +*/ +int handler::compare_key(key_range *range) +{ + int cmp; + if (!range) + return 0; // No max range + cmp= key_cmp(range_key_part, range->key, range->length); + if (!cmp) + cmp= key_compare_result_on_equal; + return cmp; +} + + +int handler::index_read_idx_map(uchar * buf, uint index, const uchar * key, + key_part_map keypart_map, + enum ha_rkey_function find_flag) +{ + int error, error1; + error= index_init(index, 0); + if (!error) + { + error= index_read_map(buf, key, keypart_map, find_flag); + error1= index_end(); + } + return error ? error : error1; +} + + +/** + Returns a list of all known extensions. + + No mutexes, worst case race is a minor surplus memory allocation + We have to recreate the extension map if mysqld is restarted (for example + within libmysqld) + + @retval + pointer pointer to TYPELIB structure +*/ +static my_bool exts_handlerton(THD *unused, plugin_ref plugin, + void *arg) +{ + List *found_exts= (List *) arg; + handlerton *hton= plugin_data(plugin, handlerton *); + handler *file; + if (hton->state == SHOW_OPTION_YES && hton->create && + (file= hton->create(hton, (TABLE_SHARE*) 0, current_thd->mem_root))) + { + List_iterator_fast it(*found_exts); + const char **ext, *old_ext; + + for (ext= file->bas_ext(); *ext; ext++) + { + while ((old_ext= it++)) + { + if (!strcmp(old_ext, *ext)) + break; + } + if (!old_ext) + found_exts->push_back((char *) *ext); + + it.rewind(); + } + delete file; + } + return FALSE; +} + +TYPELIB *ha_known_exts(void) +{ + if (!known_extensions.type_names || mysys_usage_id != known_extensions_id) + { + List found_exts; + const char **ext, *old_ext; + + known_extensions_id= mysys_usage_id; + found_exts.push_back((char*) TRG_EXT); + found_exts.push_back((char*) TRN_EXT); + + plugin_foreach(NULL, exts_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &found_exts); + + ext= (const char **) my_once_alloc(sizeof(char *)* + (found_exts.elements+1), + MYF(MY_WME | MY_FAE)); + + DBUG_ASSERT(ext != 0); + known_extensions.count= found_exts.elements; + known_extensions.type_names= ext; + + List_iterator_fast it(found_exts); + while ((old_ext= it++)) + *ext++= old_ext; + *ext= 0; + } + return &known_extensions; +} + + +static bool stat_print(THD *thd, const char *type, uint type_len, + const char *file, uint file_len, + const char *status, uint status_len) +{ + Protocol *protocol= thd->protocol; + protocol->prepare_for_resend(); + protocol->store(type, type_len, system_charset_info); + protocol->store(file, file_len, system_charset_info); + protocol->store(status, status_len, system_charset_info); + if (protocol->write()) + return TRUE; + return FALSE; +} + + +static my_bool showstat_handlerton(THD *thd, plugin_ref plugin, + void *arg) +{ + enum ha_stat_type stat= *(enum ha_stat_type *) arg; + handlerton *hton= plugin_data(plugin, handlerton *); + if (hton->state == SHOW_OPTION_YES && hton->show_status && + hton->show_status(hton, thd, stat_print, stat)) + return TRUE; + return FALSE; +} + +bool ha_show_status(THD *thd, handlerton *db_type, enum ha_stat_type stat) +{ + List field_list; + Protocol *protocol= thd->protocol; + bool result; + + field_list.push_back(new Item_empty_string("Type",10)); + field_list.push_back(new Item_empty_string("Name",FN_REFLEN)); + field_list.push_back(new Item_empty_string("Status",10)); + + if (protocol->send_fields(&field_list, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) + return TRUE; + + if (db_type == NULL) + { + result= plugin_foreach(thd, showstat_handlerton, + MYSQL_STORAGE_ENGINE_PLUGIN, &stat); + } + else + { + if (db_type->state != SHOW_OPTION_YES) + { + const LEX_STRING *name=&hton2plugin[db_type->slot]->name; + result= stat_print(thd, name->str, name->length, + "", 0, "DISABLED", 8) ? 1 : 0; + } + else + result= db_type->show_status && + db_type->show_status(db_type, thd, stat_print, stat) ? 1 : 0; + } + + if (!result) + my_eof(thd); + return result; +} + +/* + Function to check if the conditions for row-based binlogging is + correct for the table. + + A row in the given table should be replicated if: + - Row-based replication is enabled in the current thread + - The binlog is enabled + - It is not a temporary table + - The binary log is open + - The database the table resides in shall be binlogged (binlog_*_db rules) + - table is not mysql.event +*/ + +static bool check_table_binlog_row_based(THD *thd, TABLE *table) +{ + if (table->s->cached_row_logging_check == -1) + { + int const check(table->s->tmp_table == NO_TMP_TABLE && + binlog_filter->db_ok(table->s->db.str)); + table->s->cached_row_logging_check= check; + } + + DBUG_ASSERT(table->s->cached_row_logging_check == 0 || + table->s->cached_row_logging_check == 1); + + return (thd->current_stmt_binlog_row_based && + table->s->cached_row_logging_check && + (thd->options & OPTION_BIN_LOG) && + mysql_bin_log.is_open()); +} + + +/** @brief + Write table maps for all (manually or automatically) locked tables + to the binary log. + + SYNOPSIS + write_locked_table_maps() + thd Pointer to THD structure + + DESCRIPTION + This function will generate and write table maps for all tables + that are locked by the thread 'thd'. Either manually locked + (stored in THD::locked_tables) and automatically locked (stored + in THD::lock) are considered. + + RETURN VALUE + 0 All OK + 1 Failed to write all table maps + + SEE ALSO + THD::lock + THD::locked_tables +*/ + +static int write_locked_table_maps(THD *thd) +{ + DBUG_ENTER("write_locked_table_maps"); + DBUG_PRINT("enter", ("thd: 0x%lx thd->lock: 0x%lx thd->locked_tables: 0x%lx " + "thd->extra_lock: 0x%lx", + (long) thd, (long) thd->lock, + (long) thd->locked_tables, (long) thd->extra_lock)); + + DBUG_PRINT("debug", ("get_binlog_table_maps(): %d", thd->get_binlog_table_maps())); + + if (thd->get_binlog_table_maps() == 0) + { + MYSQL_LOCK *locks[3]; + locks[0]= thd->extra_lock; + locks[1]= thd->lock; + locks[2]= thd->locked_tables; + for (uint i= 0 ; i < sizeof(locks)/sizeof(*locks) ; ++i ) + { + MYSQL_LOCK const *const lock= locks[i]; + if (lock == NULL) + continue; + + TABLE **const end_ptr= lock->table + lock->table_count; + for (TABLE **table_ptr= lock->table ; + table_ptr != end_ptr ; + ++table_ptr) + { + TABLE *const table= *table_ptr; + DBUG_PRINT("info", ("Checking table %s", table->s->table_name.str)); + if (table->current_lock == F_WRLCK && + check_table_binlog_row_based(thd, table)) + { + int const has_trans= table->file->has_transactions(); + int const error= thd->binlog_write_table_map(table, has_trans); + /* + If an error occurs, it is the responsibility of the caller to + roll back the transaction. + */ + if (unlikely(error)) + DBUG_RETURN(1); + } + } + } + } + DBUG_RETURN(0); +} + + +typedef bool Log_func(THD*, TABLE*, bool, MY_BITMAP*, + uint, const uchar*, const uchar*); + +static int binlog_log_row(TABLE* table, + const uchar *before_record, + const uchar *after_record, + Log_func *log_func) +{ + if (table->no_replicate) + return 0; + bool error= 0; + THD *const thd= table->in_use; + + if (check_table_binlog_row_based(thd, table)) + { + MY_BITMAP cols; + /* Potential buffer on the stack for the bitmap */ + uint32 bitbuf[BITMAP_STACKBUF_SIZE/sizeof(uint32)]; + uint n_fields= table->s->fields; + my_bool use_bitbuf= n_fields <= sizeof(bitbuf)*8; + + /* + If there are no table maps written to the binary log, this is + the first row handled in this statement. In that case, we need + to write table maps for all locked tables to the binary log. + */ + if (likely(!(error= bitmap_init(&cols, + use_bitbuf ? bitbuf : NULL, + (n_fields + 7) & ~7UL, + FALSE)))) + { + bitmap_set_all(&cols); + if (likely(!(error= write_locked_table_maps(thd)))) + error= (*log_func)(thd, table, table->file->has_transactions(), + &cols, table->s->fields, + before_record, after_record); + + if (!use_bitbuf) + bitmap_free(&cols); + } + } + return error ? HA_ERR_RBR_LOGGING_FAILED : 0; +} + +int handler::ha_external_lock(THD *thd, int lock_type) +{ + DBUG_ENTER("handler::ha_external_lock"); + /* + Whether this is lock or unlock, this should be true, and is to verify that + if get_auto_increment() was called (thus may have reserved intervals or + taken a table lock), ha_release_auto_increment() was too. + */ + DBUG_ASSERT(next_insert_id == 0); + + /* + We cache the table flags if the locking succeeded. Otherwise, we + keep them as they were when they were fetched in ha_open(). + */ + int error= external_lock(thd, lock_type); + if (error == 0) + cached_table_flags= table_flags(); + DBUG_RETURN(error); +} + + +/** @brief + Check handler usage and reset state of file to after 'open' +*/ +int handler::ha_reset() +{ + DBUG_ENTER("ha_reset"); + /* Check that we have called all proper deallocation functions */ + DBUG_ASSERT((uchar*) table->def_read_set.bitmap + + table->s->column_bitmap_size == + (uchar*) table->def_write_set.bitmap); + DBUG_ASSERT(bitmap_is_set_all(&table->s->all_set)); + DBUG_ASSERT(table->key_read == 0); + /* ensure that ha_index_end / ha_rnd_end has been called */ + DBUG_ASSERT(inited == NONE); + /* Free cache used by filesort */ + free_io_cache(table); + /* reset the bitmaps to point to defaults */ + table->default_column_bitmaps(); + DBUG_RETURN(reset()); +} + + +int handler::ha_write_row(uchar *buf) +{ + int error; + Log_func *log_func= Write_rows_log_event::binlog_row_logging_function; + DBUG_ENTER("handler::ha_write_row"); + + mark_trx_read_write(); + + if (unlikely(error= write_row(buf))) + DBUG_RETURN(error); + if (unlikely(error= binlog_log_row(table, 0, buf, log_func))) + DBUG_RETURN(error); /* purecov: inspected */ + DBUG_RETURN(0); +} + + +int handler::ha_update_row(const uchar *old_data, uchar *new_data) +{ + int error; + Log_func *log_func= Update_rows_log_event::binlog_row_logging_function; + + /* + Some storage engines require that the new record is in record[0] + (and the old record is in record[1]). + */ + DBUG_ASSERT(new_data == table->record[0]); + + mark_trx_read_write(); + + if (unlikely(error= update_row(old_data, new_data))) + return error; + if (unlikely(error= binlog_log_row(table, old_data, new_data, log_func))) + return error; + return 0; +} + +int handler::ha_delete_row(const uchar *buf) +{ + int error; + Log_func *log_func= Delete_rows_log_event::binlog_row_logging_function; + + mark_trx_read_write(); + + if (unlikely(error= delete_row(buf))) + return error; + if (unlikely(error= binlog_log_row(table, buf, 0, log_func))) + return error; + return 0; +} + + + +/** @brief + use_hidden_primary_key() is called in case of an update/delete when + (table_flags() and HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) is defined + but we don't have a primary key +*/ +void handler::use_hidden_primary_key() +{ + /* fallback to use all columns in the table to identify row */ + table->use_all_columns(); +} + + +/** @brief + Dummy function which accept information about log files which is not need + by handlers +*/ +void signal_log_not_needed(struct handlerton, char *log_file) +{ + DBUG_ENTER("signal_log_not_needed"); + DBUG_PRINT("enter", ("logfile '%s'", log_file)); + DBUG_VOID_RETURN; +} + + +#ifdef TRANS_LOG_MGM_EXAMPLE_CODE +/* + Example of transaction log management functions based on assumption that logs + placed into a directory +*/ +#include +#include +int example_of_iterator_using_for_logs_cleanup(handlerton *hton) +{ + void *buffer; + int res= 1; + struct handler_iterator iterator; + struct handler_log_file_data data; + + if (!hton->create_iterator) + return 1; /* iterator creator is not supported */ + + if ((*hton->create_iterator)(hton, HA_TRANSACTLOG_ITERATOR, &iterator) != + HA_ITERATOR_OK) + { + /* error during creation of log iterator or iterator is not supported */ + return 1; + } + while((*iterator.next)(&iterator, (void*)&data) == 0) + { + printf("%s\n", data.filename.str); + if (data.status == HA_LOG_STATUS_FREE && + my_delete(data.filename.str, MYF(MY_WME))) + goto err; + } + res= 0; +err: + (*iterator.destroy)(&iterator); + return res; +} + + +/* + Here we should get info from handler where it save logs but here is + just example, so we use constant. + IMHO FN_ROOTDIR ("/") is safe enough for example, because nobody has + rights on it except root and it consist of directories only at lest for + *nix (sorry, can't find windows-safe solution here, but it is only example). +*/ +#define fl_dir FN_ROOTDIR + + +/** @brief + Dummy function to return log status should be replaced by function which + really detect the log status and check that the file is a log of this + handler. +*/ +enum log_status fl_get_log_status(char *log) +{ + MY_STAT stat_buff; + if (my_stat(log, &stat_buff, MYF(0))) + return HA_LOG_STATUS_INUSE; + return HA_LOG_STATUS_NOSUCHLOG; +} + + +struct fl_buff +{ + LEX_STRING *names; + enum log_status *statuses; + uint32 entries; + uint32 current; +}; + + +int fl_log_iterator_next(struct handler_iterator *iterator, + void *iterator_object) +{ + struct fl_buff *buff= (struct fl_buff *)iterator->buffer; + struct handler_log_file_data *data= + (struct handler_log_file_data *) iterator_object; + if (buff->current >= buff->entries) + return 1; + data->filename= buff->names[buff->current]; + data->status= buff->statuses[buff->current]; + buff->current++; + return 0; +} + + +void fl_log_iterator_destroy(struct handler_iterator *iterator) +{ + my_free((uchar*)iterator->buffer, MYF(MY_ALLOW_ZERO_PTR)); +} + + +/** @brief + returns buffer, to be assigned in handler_iterator struct +*/ +enum handler_create_iterator_result +fl_log_iterator_buffer_init(struct handler_iterator *iterator) +{ + MY_DIR *dirp; + struct fl_buff *buff; + char *name_ptr; + uchar *ptr; + FILEINFO *file; + uint32 i; + + /* to be able to make my_free without crash in case of error */ + iterator->buffer= 0; + + if (!(dirp = my_dir(fl_dir, MYF(0)))) + { + return HA_ITERATOR_ERROR; + } + if ((ptr= (uchar*)my_malloc(ALIGN_SIZE(sizeof(fl_buff)) + + ((ALIGN_SIZE(sizeof(LEX_STRING)) + + sizeof(enum log_status) + + + FN_REFLEN + 1) * + (uint) dirp->number_off_files), + MYF(0))) == 0) + { + return HA_ITERATOR_ERROR; + } + buff= (struct fl_buff *)ptr; + buff->entries= buff->current= 0; + ptr= ptr + (ALIGN_SIZE(sizeof(fl_buff))); + buff->names= (LEX_STRING*) (ptr); + ptr= ptr + ((ALIGN_SIZE(sizeof(LEX_STRING)) * + (uint) dirp->number_off_files)); + buff->statuses= (enum log_status *)(ptr); + name_ptr= (char *)(ptr + (sizeof(enum log_status) * + (uint) dirp->number_off_files)); + for (i=0 ; i < (uint) dirp->number_off_files ; i++) + { + enum log_status st; + file= dirp->dir_entry + i; + if ((file->name[0] == '.' && + ((file->name[1] == '.' && file->name[2] == '\0') || + file->name[1] == '\0'))) + continue; + if ((st= fl_get_log_status(file->name)) == HA_LOG_STATUS_NOSUCHLOG) + continue; + name_ptr= strxnmov(buff->names[buff->entries].str= name_ptr, + FN_REFLEN, fl_dir, file->name, NullS); + buff->names[buff->entries].length= (name_ptr - + buff->names[buff->entries].str); + buff->statuses[buff->entries]= st; + buff->entries++; + } + + iterator->buffer= buff; + iterator->next= &fl_log_iterator_next; + iterator->destroy= &fl_log_iterator_destroy; + return HA_ITERATOR_OK; +} + + +/* An example of a iterator creator */ +enum handler_create_iterator_result +fl_create_iterator(enum handler_iterator_type type, + struct handler_iterator *iterator) +{ + switch(type) { + case HA_TRANSACTLOG_ITERATOR: + return fl_log_iterator_buffer_init(iterator); + default: + return HA_ITERATOR_UNSUPPORTED; + } +} +#endif /*TRANS_LOG_MGM_EXAMPLE_CODE*/ diff --git a/dbcon/mysql/idb_mysql.h b/dbcon/mysql/idb_mysql.h index cf12f7b0..35d87eea 100644 --- a/dbcon/mysql/idb_mysql.h +++ b/dbcon/mysql/idb_mysql.h @@ -21,10 +21,6 @@ #ifndef IDB_MYSQL_H__ #define IDB_MYSQL_H__ -#ifdef _MSC_VER -#include -#endif - #define MYSQL_SERVER 1 //needed for definition of struct THD in mysql_priv.h #define USE_CALPONT_REGEX @@ -39,9 +35,6 @@ #endif #define MYSQL_DYNAMIC_PLUGIN #define DONT_DEFINE_VOID -#ifdef ETIMEDOUT -#undef ETIMEDOUT -#endif #endif #include "mysql_priv.h" @@ -71,18 +64,6 @@ #undef PACKAGE_NAME #undef PACKAGE_BUGREPORT #undef DEBUG -#undef set_bits - -namespace { -inline char* idb_mysql_query_str(THD* thd) -{ -#if MYSQL_VERSION_ID >= 50172 - return thd->query(); -#else - return thd->query; -#endif -} -} #endif // vim:ts=4 sw=4: diff --git a/dbcon/mysql/include/my_base.h b/dbcon/mysql/include/my_base.h new file mode 100644 index 00000000..0f65c057 --- /dev/null +++ b/dbcon/mysql/include/my_base.h @@ -0,0 +1,571 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* This file includes constants used with all databases */ + +#ifndef _my_base_h +#define _my_base_h + +#ifndef stdin /* Included first in handler */ +#define CHSIZE_USED +#include +#include /* This includes types */ +#include +#include +#include + +#ifndef EOVERFLOW +#define EOVERFLOW 84 +#endif + +#if !defined(USE_MY_FUNC) && !defined(THREAD) +#include /* For faster code, after test */ +#endif /* USE_MY_FUNC */ +#endif /* stdin */ +#include + +/* The following is bits in the flag parameter to ha_open() */ + +#define HA_OPEN_ABORT_IF_LOCKED 0 /* default */ +#define HA_OPEN_WAIT_IF_LOCKED 1 +#define HA_OPEN_IGNORE_IF_LOCKED 2 +#define HA_OPEN_TMP_TABLE 4 /* Table is a temp table */ +#define HA_OPEN_DELAY_KEY_WRITE 8 /* Don't update index */ +#define HA_OPEN_ABORT_IF_CRASHED 16 +#define HA_OPEN_FOR_REPAIR 32 /* open even if crashed */ +#define HA_OPEN_FROM_SQL_LAYER 64 +#define HA_OPEN_MMAP 128 /* open memory mapped */ +#define HA_OPEN_COPY 256 /* Open copy (for repair) */ +/* Internal temp table, used for temporary results */ +#define HA_OPEN_INTERNAL_TABLE 512 + +/* The following is parameter to ha_rkey() how to use key */ + +/* + We define a complete-field prefix of a key value as a prefix where + the last included field in the prefix contains the full field, not + just some bytes from the start of the field. A partial-field prefix + is allowed to contain only a few first bytes from the last included + field. + + Below HA_READ_KEY_EXACT, ..., HA_READ_BEFORE_KEY can take a + complete-field prefix of a key value as the search + key. HA_READ_PREFIX and HA_READ_PREFIX_LAST could also take a + partial-field prefix, but currently (4.0.10) they are only used with + complete-field prefixes. MySQL uses a padding trick to implement + LIKE 'abc%' queries. + + NOTE that in InnoDB HA_READ_PREFIX_LAST will NOT work with a + partial-field prefix because InnoDB currently strips spaces from the + end of varchar fields! +*/ + +enum ha_rkey_function { + HA_READ_KEY_EXACT, /* Find first record else error */ + HA_READ_KEY_OR_NEXT, /* Record or next record */ + HA_READ_KEY_OR_PREV, /* Record or previous */ + HA_READ_AFTER_KEY, /* Find next rec. after key-record */ + HA_READ_BEFORE_KEY, /* Find next rec. before key-record */ + HA_READ_PREFIX, /* Key which as same prefix */ + HA_READ_PREFIX_LAST, /* Last key with the same prefix */ + HA_READ_PREFIX_LAST_OR_PREV, /* Last or prev key with the same prefix */ + HA_READ_MBR_CONTAIN, + HA_READ_MBR_INTERSECT, + HA_READ_MBR_WITHIN, + HA_READ_MBR_DISJOINT, + HA_READ_MBR_EQUAL +}; + + /* Key algorithm types */ + +enum ha_key_alg { + HA_KEY_ALG_UNDEF= 0, /* Not specified (old file) */ + HA_KEY_ALG_BTREE= 1, /* B-tree, default one */ + HA_KEY_ALG_RTREE= 2, /* R-tree, for spatial searches */ + HA_KEY_ALG_HASH= 3, /* HASH keys (HEAP tables) */ + HA_KEY_ALG_FULLTEXT= 4 /* FULLTEXT (MyISAM tables) */ +}; + + /* Storage media types */ + +enum ha_storage_media { + HA_SM_DEFAULT= 0, /* Not specified (engine default) */ + HA_SM_DISK= 1, /* DISK storage */ + HA_SM_MEMORY= 2 /* MAIN MEMORY storage */ +}; + + /* The following is parameter to ha_extra() */ + +enum ha_extra_function { + HA_EXTRA_NORMAL=0, /* Optimize for space (def) */ + HA_EXTRA_QUICK=1, /* Optimize for speed */ + HA_EXTRA_NOT_USED=2, + HA_EXTRA_CACHE=3, /* Cache record in HA_rrnd() */ + HA_EXTRA_NO_CACHE=4, /* End caching of records (def) */ + HA_EXTRA_NO_READCHECK=5, /* No readcheck on update */ + HA_EXTRA_READCHECK=6, /* Use readcheck (def) */ + HA_EXTRA_KEYREAD=7, /* Read only key to database */ + HA_EXTRA_NO_KEYREAD=8, /* Normal read of records (def) */ + HA_EXTRA_NO_USER_CHANGE=9, /* No user is allowed to write */ + HA_EXTRA_KEY_CACHE=10, + HA_EXTRA_NO_KEY_CACHE=11, + HA_EXTRA_WAIT_LOCK=12, /* Wait until file is avalably (def) */ + HA_EXTRA_NO_WAIT_LOCK=13, /* If file is locked, return quickly */ + HA_EXTRA_WRITE_CACHE=14, /* Use write cache in ha_write() */ + HA_EXTRA_FLUSH_CACHE=15, /* flush write_record_cache */ + HA_EXTRA_NO_KEYS=16, /* Remove all update of keys */ + HA_EXTRA_KEYREAD_CHANGE_POS=17, /* Keyread, but change pos */ + /* xxxxchk -r must be used */ + HA_EXTRA_REMEMBER_POS=18, /* Remember pos for next/prev */ + HA_EXTRA_RESTORE_POS=19, + HA_EXTRA_REINIT_CACHE=20, /* init cache from current record */ + HA_EXTRA_FORCE_REOPEN=21, /* Datafile have changed on disk */ + HA_EXTRA_FLUSH, /* Flush tables to disk */ + HA_EXTRA_NO_ROWS, /* Don't write rows */ + HA_EXTRA_RESET_STATE, /* Reset positions */ + HA_EXTRA_IGNORE_DUP_KEY, /* Dup keys don't rollback everything*/ + HA_EXTRA_NO_IGNORE_DUP_KEY, + HA_EXTRA_PREPARE_FOR_DROP, + HA_EXTRA_PREPARE_FOR_UPDATE, /* Remove read cache if problems */ + HA_EXTRA_PRELOAD_BUFFER_SIZE, /* Set buffer size for preloading */ + /* + On-the-fly switching between unique and non-unique key inserting. + */ + HA_EXTRA_CHANGE_KEY_TO_UNIQUE, + HA_EXTRA_CHANGE_KEY_TO_DUP, + /* + When using HA_EXTRA_KEYREAD, overwrite only key member fields and keep + other fields intact. When this is off (by default) InnoDB will use memcpy + to overwrite entire row. + */ + HA_EXTRA_KEYREAD_PRESERVE_FIELDS, + HA_EXTRA_MMAP, + /* + Ignore if the a tuple is not found, continue processing the + transaction and ignore that 'row'. Needed for idempotency + handling on the slave + + Currently only used by NDB storage engine. Partition handler ignores flag. + */ + HA_EXTRA_IGNORE_NO_KEY, + HA_EXTRA_NO_IGNORE_NO_KEY, + /* + Mark the table as a log table. For some handlers (e.g. CSV) this results + in a special locking for the table. + */ + HA_EXTRA_MARK_AS_LOG_TABLE, + /* + Informs handler that write_row() which tries to insert new row into the + table and encounters some already existing row with same primary/unique + key can replace old row with new row instead of reporting error (basically + it informs handler that we do REPLACE instead of simple INSERT). + Off by default. + */ + HA_EXTRA_WRITE_CAN_REPLACE, + HA_EXTRA_WRITE_CANNOT_REPLACE, + /* + Inform handler that delete_row()/update_row() cannot batch deletes/updates + and should perform them immediately. This may be needed when table has + AFTER DELETE/UPDATE triggers which access to subject table. + These flags are reset by the handler::extra(HA_EXTRA_RESET) call. + */ + HA_EXTRA_DELETE_CANNOT_BATCH, + HA_EXTRA_UPDATE_CANNOT_BATCH, + /* + Inform handler that an "INSERT...ON DUPLICATE KEY UPDATE" will be + executed. This condition is unset by HA_EXTRA_NO_IGNORE_DUP_KEY. + */ + HA_EXTRA_INSERT_WITH_UPDATE, + /* Inform handler that we will do a rename */ + HA_EXTRA_PREPARE_FOR_RENAME, + /* + Orders MERGE handler to attach or detach its child tables. Used at + begin and end of a statement. + */ + HA_EXTRA_ATTACH_CHILDREN, + HA_EXTRA_DETACH_CHILDREN +}; + +/* Compatible option, to be deleted in 6.0 */ +#define HA_EXTRA_PREPARE_FOR_DELETE HA_EXTRA_PREPARE_FOR_DROP + + /* The following is parameter to ha_panic() */ + +enum ha_panic_function { + HA_PANIC_CLOSE, /* Close all databases */ + HA_PANIC_WRITE, /* Unlock and write status */ + HA_PANIC_READ /* Lock and read keyinfo */ +}; + + /* The following is parameter to ha_create(); keytypes */ + +enum ha_base_keytype { + HA_KEYTYPE_END=0, + HA_KEYTYPE_TEXT=1, /* Key is sorted as letters */ + HA_KEYTYPE_BINARY=2, /* Key is sorted as unsigned chars */ + HA_KEYTYPE_SHORT_INT=3, + HA_KEYTYPE_LONG_INT=4, + HA_KEYTYPE_FLOAT=5, + HA_KEYTYPE_DOUBLE=6, + HA_KEYTYPE_NUM=7, /* Not packed num with pre-space */ + HA_KEYTYPE_USHORT_INT=8, + HA_KEYTYPE_ULONG_INT=9, + HA_KEYTYPE_LONGLONG=10, + HA_KEYTYPE_ULONGLONG=11, + HA_KEYTYPE_INT24=12, + HA_KEYTYPE_UINT24=13, + HA_KEYTYPE_INT8=14, + /* Varchar (0-255 bytes) with length packed with 1 byte */ + HA_KEYTYPE_VARTEXT1=15, /* Key is sorted as letters */ + HA_KEYTYPE_VARBINARY1=16, /* Key is sorted as unsigned chars */ + /* Varchar (0-65535 bytes) with length packed with 2 bytes */ + HA_KEYTYPE_VARTEXT2=17, /* Key is sorted as letters */ + HA_KEYTYPE_VARBINARY2=18, /* Key is sorted as unsigned chars */ + HA_KEYTYPE_BIT=19 +}; + +#define HA_MAX_KEYTYPE 31 /* Must be log2-1 */ + + /* These flags kan be OR:ed to key-flag */ + +#define HA_NOSAME 1 /* Set if not dupplicated records */ +#define HA_PACK_KEY 2 /* Pack string key to previous key */ +#define HA_AUTO_KEY 16 +#define HA_BINARY_PACK_KEY 32 /* Packing of all keys to prev key */ +#define HA_FULLTEXT 128 /* For full-text search */ +#define HA_UNIQUE_CHECK 256 /* Check the key for uniqueness */ +#define HA_SPATIAL 1024 /* For spatial search */ +#define HA_NULL_ARE_EQUAL 2048 /* NULL in key are cmp as equal */ +#define HA_GENERATED_KEY 8192 /* Automaticly generated key */ + + /* The combination of the above can be used for key type comparison. */ +#define HA_KEYFLAG_MASK (HA_NOSAME | HA_PACK_KEY | HA_AUTO_KEY | \ + HA_BINARY_PACK_KEY | HA_FULLTEXT | HA_UNIQUE_CHECK | \ + HA_SPATIAL | HA_NULL_ARE_EQUAL | HA_GENERATED_KEY) + +#define HA_KEY_HAS_PART_KEY_SEG 65536 /* Key contains partial segments */ + + /* Automatic bits in key-flag */ + +#define HA_SPACE_PACK_USED 4 /* Test for if SPACE_PACK used */ +#define HA_VAR_LENGTH_KEY 8 +#define HA_NULL_PART_KEY 64 +#define HA_USES_PARSER 16384 /* Fulltext index uses [pre]parser */ +#define HA_USES_BLOCK_SIZE ((uint) 32768) +#define HA_SORT_ALLOWS_SAME 512 /* Intern bit when sorting records */ +#if MYSQL_VERSION_ID < 0x50200 +/* + Key has a part that can have end space. If this is an unique key + we have to handle it differently from other unique keys as we can find + many matching rows for one key (because end space are not compared) +*/ +#define HA_END_SPACE_KEY 0 /* was: 4096 */ +#else +#error HA_END_SPACE_KEY is obsolete, please remove it +#endif + + + /* These flags can be added to key-seg-flag */ + +#define HA_SPACE_PACK 1 /* Pack space in key-seg */ +#define HA_PART_KEY_SEG 4 /* Used by MySQL for part-key-cols */ +#define HA_VAR_LENGTH_PART 8 +#define HA_NULL_PART 16 +#define HA_BLOB_PART 32 +#define HA_SWAP_KEY 64 +#define HA_REVERSE_SORT 128 /* Sort key in reverse order */ +#define HA_NO_SORT 256 /* do not bother sorting on this keyseg */ +/* + End space in unique/varchar are considered equal. (Like 'a' and 'a ') + Only needed for internal temporary tables. +*/ +#define HA_END_SPACE_ARE_EQUAL 512 +#define HA_BIT_PART 1024 + + /* optionbits for database */ +#define HA_OPTION_PACK_RECORD 1 +#define HA_OPTION_PACK_KEYS 2 +#define HA_OPTION_COMPRESS_RECORD 4 +#define HA_OPTION_LONG_BLOB_PTR 8 /* new ISAM format */ +#define HA_OPTION_TMP_TABLE 16 +#define HA_OPTION_CHECKSUM 32 +#define HA_OPTION_DELAY_KEY_WRITE 64 +#define HA_OPTION_NO_PACK_KEYS 128 /* Reserved for MySQL */ +#define HA_OPTION_CREATE_FROM_ENGINE 256 +#define HA_OPTION_RELIES_ON_SQL_LAYER 512 +#define HA_OPTION_NULL_FIELDS 1024 +#define HA_OPTION_PAGE_CHECKSUM 2048 +#define HA_OPTION_TEMP_COMPRESS_RECORD ((uint) 16384) /* set by isamchk */ +#define HA_OPTION_READ_ONLY_DATA ((uint) 32768) /* Set by isamchk */ + + /* Bits in flag to create() */ + +#define HA_DONT_TOUCH_DATA 1 /* Don't empty datafile (isamchk) */ +#define HA_PACK_RECORD 2 /* Request packed record format */ +#define HA_CREATE_TMP_TABLE 4 +#define HA_CREATE_CHECKSUM 8 +#define HA_CREATE_KEEP_FILES 16 /* don't overwrite .MYD and MYI */ +#define HA_CREATE_PAGE_CHECKSUM 32 +#define HA_CREATE_DELAY_KEY_WRITE 64 +#define HA_CREATE_RELIES_ON_SQL_LAYER 128 + +/* + The following flags (OR-ed) are passed to handler::info() method. + The method copies misc handler information out of the storage engine + to data structures accessible from MySQL + + Same flags are also passed down to mi_status, myrg_status, etc. +*/ + +/* this one is not used */ +#define HA_STATUS_POS 1 +/* + assuming the table keeps shared actual copy of the 'info' and + local, possibly outdated copy, the following flag means that + it should not try to get the actual data (locking the shared structure) + slightly outdated version will suffice +*/ +#define HA_STATUS_NO_LOCK 2 +/* update the time of the last modification (in handler::update_time) */ +#define HA_STATUS_TIME 4 +/* + update the 'constant' part of the info: + handler::max_data_file_length, max_index_file_length, create_time + sortkey, ref_length, block_size, data_file_name, index_file_name. + handler::table->s->keys_in_use, keys_for_keyread, rec_per_key +*/ +#define HA_STATUS_CONST 8 +/* + update the 'variable' part of the info: + handler::records, deleted, data_file_length, index_file_length, + delete_length, check_time, mean_rec_length +*/ +#define HA_STATUS_VARIABLE 16 +/* + get the information about the key that caused last duplicate value error + update handler::errkey and handler::dupp_ref + see handler::get_dup_key() +*/ +#define HA_STATUS_ERRKEY 32 +/* + update handler::auto_increment_value +*/ +#define HA_STATUS_AUTO 64 + +/* + Errorcodes given by handler functions + + opt_sum_query() assumes these codes are > 1 + Do not add error numbers before HA_ERR_FIRST. + If necessary to add lower numbers, change HA_ERR_FIRST accordingly. +*/ +#define HA_ERR_FIRST 120 /* Copy of first error nr.*/ + +#define HA_ERR_KEY_NOT_FOUND 120 /* Didn't find key on read or update */ +#define HA_ERR_FOUND_DUPP_KEY 121 /* Dupplicate key on write */ +#define HA_ERR_INTERNAL_ERROR 122 /* Internal error */ +#define HA_ERR_RECORD_CHANGED 123 /* Uppdate with is recoverable */ +#define HA_ERR_WRONG_INDEX 124 /* Wrong index given to function */ +#define HA_ERR_CRASHED 126 /* Indexfile is crashed */ +#define HA_ERR_WRONG_IN_RECORD 127 /* Record-file is crashed */ +#define HA_ERR_OUT_OF_MEM 128 /* Record-file is crashed */ +#define HA_ERR_NOT_A_TABLE 130 /* not a MYI file - no signature */ +#define HA_ERR_WRONG_COMMAND 131 /* Command not supported */ +#define HA_ERR_OLD_FILE 132 /* old databasfile */ +#define HA_ERR_NO_ACTIVE_RECORD 133 /* No record read in update() */ +#define HA_ERR_RECORD_DELETED 134 /* A record is not there */ +#define HA_ERR_RECORD_FILE_FULL 135 /* No more room in file */ +#define HA_ERR_INDEX_FILE_FULL 136 /* No more room in file */ +#define HA_ERR_END_OF_FILE 137 /* end in next/prev/first/last */ +#define HA_ERR_UNSUPPORTED 138 /* unsupported extension used */ +#define HA_ERR_TO_BIG_ROW 139 /* Too big row */ +#define HA_WRONG_CREATE_OPTION 140 /* Wrong create option */ +#define HA_ERR_FOUND_DUPP_UNIQUE 141 /* Dupplicate unique on write */ +#define HA_ERR_UNKNOWN_CHARSET 142 /* Can't open charset */ +#define HA_ERR_WRONG_MRG_TABLE_DEF 143 /* conflicting tables in MERGE */ +#define HA_ERR_CRASHED_ON_REPAIR 144 /* Last (automatic?) repair failed */ +#define HA_ERR_CRASHED_ON_USAGE 145 /* Table must be repaired */ +#define HA_ERR_LOCK_WAIT_TIMEOUT 146 +#define HA_ERR_LOCK_TABLE_FULL 147 +#define HA_ERR_READ_ONLY_TRANSACTION 148 /* Updates not allowed */ +#define HA_ERR_LOCK_DEADLOCK 149 +#define HA_ERR_CANNOT_ADD_FOREIGN 150 /* Cannot add a foreign key constr. */ +#define HA_ERR_NO_REFERENCED_ROW 151 /* Cannot add a child row */ +#define HA_ERR_ROW_IS_REFERENCED 152 /* Cannot delete a parent row */ +#define HA_ERR_NO_SAVEPOINT 153 /* No savepoint with that name */ +#define HA_ERR_NON_UNIQUE_BLOCK_SIZE 154 /* Non unique key block size */ +#define HA_ERR_NO_SUCH_TABLE 155 /* The table does not exist in engine */ +#define HA_ERR_TABLE_EXIST 156 /* The table existed in storage engine */ +#define HA_ERR_NO_CONNECTION 157 /* Could not connect to storage engine */ +/* NULLs are not supported in spatial index */ +#define HA_ERR_NULL_IN_SPATIAL 158 +#define HA_ERR_TABLE_DEF_CHANGED 159 /* The table changed in storage engine */ +/* There's no partition in table for given value */ +#define HA_ERR_NO_PARTITION_FOUND 160 +#define HA_ERR_RBR_LOGGING_FAILED 161 /* Row-based binlogging of row failed */ +#define HA_ERR_DROP_INDEX_FK 162 /* Index needed in foreign key constr */ +/* + Upholding foreign key constraints would lead to a duplicate key error + in some other table. +*/ +#define HA_ERR_FOREIGN_DUPLICATE_KEY 163 +/* The table changed in storage engine */ +#define HA_ERR_TABLE_NEEDS_UPGRADE 164 +#define HA_ERR_TABLE_READONLY 165 /* The table is not writable */ + +#define HA_ERR_AUTOINC_READ_FAILED 166 /* Failed to get next autoinc value */ +#define HA_ERR_AUTOINC_ERANGE 167 /* Failed to set row autoinc value */ +#define HA_ERR_GENERIC 168 /* Generic error */ +/* row not actually updated: new values same as the old values */ +#define HA_ERR_RECORD_IS_THE_SAME 169 +/* It is not possible to log this statement */ +#define HA_ERR_LOGGING_IMPOSSIBLE 170 /* It is not possible to log this + statement */ +#define HA_ERR_CORRUPT_EVENT 171 /* The event was corrupt, leading to + illegal data being read */ +#define HA_ERR_NEW_FILE 172 /* New file format */ +#define HA_ERR_ROWS_EVENT_APPLY 173 /* The event could not be processed + no other hanlder error happened */ +#define HA_ERR_INITIALIZATION 174 /* Error during initialization */ +#define HA_ERR_FILE_TOO_SHORT 175 /* File too short */ +#define HA_ERR_WRONG_CRC 176 /* Wrong CRC on page */ +#define HA_ERR_TOO_MANY_CONCURRENT_TRXS 177 /*Too many active concurrent transactions */ +/* The error codes from 178 to 180 is not used, because we need to +maintain forward compatibility with higher versions. */ +//@InfiniDB @bug4585 for InnoDB upgrade +#define HA_ERR_TABLE_IN_FK_CHECK 181 /* Table being used in foreign key check */ + +#define HA_ERR_LAST 181 /* Copy of last error nr */ + +/* Number of different errors */ +#define HA_ERR_ERRORS (HA_ERR_LAST - HA_ERR_FIRST + 1) + + /* Other constants */ + +#define HA_NAMELEN 64 /* Max length of saved filename */ +#define NO_SUCH_KEY (~(uint)0) /* used as a key no. */ + +typedef ulong key_part_map; +#define HA_WHOLE_KEY (~(key_part_map)0) + + /* Intern constants in databases */ + + /* bits in _search */ +#define SEARCH_FIND 1 +#define SEARCH_NO_FIND 2 +#define SEARCH_SAME 4 +#define SEARCH_BIGGER 8 +#define SEARCH_SMALLER 16 +#define SEARCH_SAVE_BUFF 32 +#define SEARCH_UPDATE 64 +#define SEARCH_PREFIX 128 +#define SEARCH_LAST 256 +#define MBR_CONTAIN 512 +#define MBR_INTERSECT 1024 +#define MBR_WITHIN 2048 +#define MBR_DISJOINT 4096 +#define MBR_EQUAL 8192 +#define MBR_DATA 16384 +#define SEARCH_NULL_ARE_EQUAL 32768 /* NULL in keys are equal */ +#define SEARCH_NULL_ARE_NOT_EQUAL 65536 /* NULL in keys are not equal */ + + /* bits in opt_flag */ +#define QUICK_USED 1 +#define READ_CACHE_USED 2 +#define READ_CHECK_USED 4 +#define KEY_READ_USED 8 +#define WRITE_CACHE_USED 16 +#define OPT_NO_ROWS 32 + + /* bits in update */ +#define HA_STATE_CHANGED 1 /* Database has changed */ +#define HA_STATE_AKTIV 2 /* Has a current record */ +#define HA_STATE_WRITTEN 4 /* Record is written */ +#define HA_STATE_DELETED 8 +#define HA_STATE_NEXT_FOUND 16 /* Next found record (record before) */ +#define HA_STATE_PREV_FOUND 32 /* Prev found record (record after) */ +#define HA_STATE_NO_KEY 64 /* Last read didn't find record */ +#define HA_STATE_KEY_CHANGED 128 +#define HA_STATE_WRITE_AT_END 256 /* set in _ps_find_writepos */ +#define HA_STATE_BUFF_SAVED 512 /* If current keybuff is info->buff */ +#define HA_STATE_ROW_CHANGED 1024 /* To invalide ROW cache */ +#define HA_STATE_EXTEND_BLOCK 2048 +#define HA_STATE_RNEXT_SAME 4096 /* rnext_same occupied lastkey2 */ + +/* myisampack expects no more than 32 field types. */ +enum en_fieldtype { + FIELD_LAST=-1,FIELD_NORMAL,FIELD_SKIP_ENDSPACE,FIELD_SKIP_PRESPACE, + FIELD_SKIP_ZERO,FIELD_BLOB,FIELD_CONSTANT,FIELD_INTERVALL,FIELD_ZERO, + FIELD_VARCHAR,FIELD_CHECK, + FIELD_enum_val_count +}; + +enum data_file_type { + STATIC_RECORD, DYNAMIC_RECORD, COMPRESSED_RECORD, BLOCK_RECORD +}; + +/* For key ranges */ + +#define NO_MIN_RANGE 1 +#define NO_MAX_RANGE 2 +#define NEAR_MIN 4 +#define NEAR_MAX 8 +#define UNIQUE_RANGE 16 +#define EQ_RANGE 32 +#define NULL_RANGE 64 +#define GEOM_FLAG 128 +#define SKIP_RANGE 256 + +typedef struct st_key_range +{ + const uchar *key; + uint length; + key_part_map keypart_map; + enum ha_rkey_function flag; +} key_range; + +typedef struct st_key_multi_range +{ + key_range start_key; + key_range end_key; + char *ptr; /* Free to use by caller (ptr to row etc) */ + uint range_flag; /* key range flags see above */ +} KEY_MULTI_RANGE; + + +/* For number of records */ +#ifdef BIG_TABLES +#define rows2double(A) ulonglong2double(A) +typedef my_off_t ha_rows; +#else +#define rows2double(A) (double) (A) +typedef ulong ha_rows; +#endif + +#define HA_POS_ERROR (~ (ha_rows) 0) +#define HA_OFFSET_ERROR (~ (my_off_t) 0) + +#if SYSTEM_SIZEOF_OFF_T == 4 +#define MAX_FILE_SIZE INT_MAX32 +#else +#define MAX_FILE_SIZE LONGLONG_MAX +#endif + +#define HA_VARCHAR_PACKLENGTH(field_length) ((field_length) < 256 ? 1 :2) + +/* invalidator function reference for Query Cache */ +typedef void (* invalidator_by_filename)(const char * filename); + +#endif /* _my_base_h */ diff --git a/dbcon/mysql/include/my_sys.h b/dbcon/mysql/include/my_sys.h new file mode 100644 index 00000000..ee223f32 --- /dev/null +++ b/dbcon/mysql/include/my_sys.h @@ -0,0 +1,997 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _my_sys_h +#define _my_sys_h +C_MODE_START + +#ifdef HAVE_AIOWAIT +#include /* Used by record-cache */ +typedef struct my_aio_result { + aio_result_t result; + int pending; +} my_aio_result; +#endif + +#ifndef THREAD +extern int NEAR my_errno; /* Last error in mysys */ +#else +#include +#endif + +#include /* for CHARSET_INFO */ +#include +#include + +#define MYSYS_PROGRAM_USES_CURSES() { error_handler_hook = my_message_curses; mysys_uses_curses=1; } +#define MYSYS_PROGRAM_DONT_USE_CURSES() { error_handler_hook = my_message_no_curses; mysys_uses_curses=0;} +#define MY_INIT(name); { my_progname= name; my_init(); } + +#define MY_FILE_ERROR ((size_t) -1) + + /* General bitmaps for my_func's */ +#define MY_FFNF 1 /* Fatal if file not found */ +#define MY_FNABP 2 /* Fatal if not all bytes read/writen */ +#define MY_NABP 4 /* Error if not all bytes read/writen */ +#define MY_FAE 8 /* Fatal if any error */ +#define MY_WME 16 /* Write message on error */ +#define MY_WAIT_IF_FULL 32 /* Wait and try again if disk full error */ +#define MY_IGNORE_BADFD 32 /* my_sync: ignore 'bad descriptor' errors */ +#define MY_SYNC_DIR 1024 /* my_create/delete/rename: sync directory */ +#define MY_RAID 64 /* Support for RAID */ +#define MY_FULL_IO 512 /* For my_read - loop intil I/O is complete */ +#define MY_DONT_CHECK_FILESIZE 128 /* Option to init_io_cache() */ +#define MY_LINK_WARNING 32 /* my_redel() gives warning if links */ +#define MY_COPYTIME 64 /* my_redel() copys time */ +#define MY_DELETE_OLD 256 /* my_create_with_symlink() */ +#define MY_RESOLVE_LINK 128 /* my_realpath(); Only resolve links */ +#define MY_HOLD_ORIGINAL_MODES 128 /* my_copy() holds to file modes */ +#define MY_REDEL_MAKE_BACKUP 256 +#define MY_SEEK_NOT_DONE 32 /* my_lock may have to do a seek */ +#define MY_DONT_WAIT 64 /* my_lock() don't wait if can't lock */ +#define MY_ZEROFILL 32 /* my_malloc(), fill array with zero */ +#define MY_ALLOW_ZERO_PTR 64 /* my_realloc() ; zero ptr -> malloc */ +#define MY_FREE_ON_ERROR 128 /* my_realloc() ; Free old ptr on error */ +#define MY_HOLD_ON_ERROR 256 /* my_realloc() ; Return old ptr on error */ +#define MY_DONT_OVERWRITE_FILE 1024 /* my_copy: Don't overwrite file */ +#define MY_THREADSAFE 2048 /* my_seek(): lock fd mutex */ + +#define MY_CHECK_ERROR 1 /* Params to my_end; Check open-close */ +#define MY_GIVE_INFO 2 /* Give time info about process*/ +#define MY_DONT_FREE_DBUG 4 /* Do not call DBUG_END() in my_end() */ + +#define MY_REMOVE_NONE 0 /* Params for modify_defaults_file */ +#define MY_REMOVE_OPTION 1 +#define MY_REMOVE_SECTION 2 + +#define ME_HIGHBYTE 8 /* Shift for colours */ +#define ME_NOCUR 1 /* Don't use curses message */ +#define ME_OLDWIN 2 /* Use old window */ +#define ME_BELL 4 /* Ring bell then printing message */ +#define ME_HOLDTANG 8 /* Don't delete last keys */ +#define ME_WAITTOT 16 /* Wait for errtime secs of for a action */ +#define ME_WAITTANG 32 /* Wait for a user action */ +#define ME_NOREFRESH 64 /* Dont refresh screen */ +#define ME_NOINPUT 128 /* Dont use the input libary */ +#define ME_COLOUR1 ((1 << ME_HIGHBYTE)) /* Possibly error-colours */ +#define ME_COLOUR2 ((2 << ME_HIGHBYTE)) +#define ME_COLOUR3 ((3 << ME_HIGHBYTE)) +#define ME_FATALERROR 1024 /* Fatal statement error */ +#define ME_NO_WARNING_FOR_ERROR 2048 /* Don't push a warning for error */ +#define ME_NO_SP_HANDLER 4096 /* Don't call stored routine error handlers */ + + /* Bits in last argument to fn_format */ +#define MY_REPLACE_DIR 1 /* replace dir in name with 'dir' */ +#define MY_REPLACE_EXT 2 /* replace extension with 'ext' */ +#define MY_UNPACK_FILENAME 4 /* Unpack name (~ -> home) */ +#define MY_PACK_FILENAME 8 /* Pack name (home -> ~) */ +#define MY_RESOLVE_SYMLINKS 16 /* Resolve all symbolic links */ +#define MY_RETURN_REAL_PATH 32 /* return full path for file */ +#define MY_SAFE_PATH 64 /* Return NULL if too long path */ +#define MY_RELATIVE_PATH 128 /* name is relative to 'dir' */ +#define MY_APPEND_EXT 256 /* add 'ext' as additional extension*/ + + + /* My seek flags */ +#define MY_SEEK_SET 0 +#define MY_SEEK_CUR 1 +#define MY_SEEK_END 2 + + /* Some constants */ +#define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */ +#define MY_WAIT_GIVE_USER_A_MESSAGE 10 /* Every 10 times of prev */ +#define MIN_COMPRESS_LENGTH 50 /* Don't compress small bl. */ +#define DFLT_INIT_HITS 3 + + /* root_alloc flags */ +#define MY_KEEP_PREALLOC 1 +#define MY_MARK_BLOCKS_FREE 2 /* move used to free list and reuse them */ + + /* Internal error numbers (for assembler functions) */ +#define MY_ERRNO_EDOM 33 +#define MY_ERRNO_ERANGE 34 + + /* Bits for get_date timeflag */ +#define GETDATE_DATE_TIME 1 +#define GETDATE_SHORT_DATE 2 +#define GETDATE_HHMMSSTIME 4 +#define GETDATE_GMT 8 +#define GETDATE_FIXEDLENGTH 16 + + /* defines when allocating data */ +#ifdef SAFEMALLOC +#define my_malloc(SZ,FLAG) _mymalloc((SZ), __FILE__, __LINE__, FLAG ) +#define my_malloc_ci(SZ,FLAG) _mymalloc((SZ), sFile, uLine, FLAG ) +#define my_realloc(PTR,SZ,FLAG) _myrealloc((PTR), (SZ), __FILE__, __LINE__, FLAG ) +#define my_checkmalloc() _sanity( __FILE__, __LINE__ ) +#define my_free(PTR,FLAG) _myfree((PTR), __FILE__, __LINE__,FLAG) +#define my_memdup(A,B,C) _my_memdup((A),(B), __FILE__,__LINE__,C) +#define my_strdup(A,C) _my_strdup((A), __FILE__,__LINE__,C) +#define my_strndup(A,B,C) _my_strndup((A),(B),__FILE__,__LINE__,C) +#define TRASH(A,B) bfill(A, B, 0x8F) +#define QUICK_SAFEMALLOC sf_malloc_quick=1 +#define NORMAL_SAFEMALLOC sf_malloc_quick=0 +extern uint sf_malloc_prehunc,sf_malloc_endhunc,sf_malloc_quick; +extern ulonglong sf_malloc_mem_limit; + +#define CALLER_INFO_PROTO , const char *sFile, uint uLine +#define CALLER_INFO , __FILE__, __LINE__ +#define ORIG_CALLER_INFO , sFile, uLine +#else +#define my_checkmalloc() +#undef TERMINATE +#define TERMINATE(A,B) {} +#define QUICK_SAFEMALLOC +#define NORMAL_SAFEMALLOC +extern void *my_malloc(size_t Size,myf MyFlags); +#define my_malloc_ci(SZ,FLAG) my_malloc( SZ, FLAG ) +extern void *my_realloc(void *oldpoint, size_t Size, myf MyFlags); +extern void my_no_flags_free(void *ptr); +extern void *my_memdup(const void *from,size_t length,myf MyFlags); +extern char *my_strdup(const char *from,myf MyFlags); +extern char *my_strndup(const char *from, size_t length, + myf MyFlags); +/* we do use FG (as a no-op) in below so that a typo on FG is caught */ +#define my_free(PTR,FG) ((void)FG,my_no_flags_free(PTR)) +#define CALLER_INFO_PROTO /* nothing */ +#define CALLER_INFO /* nothing */ +#define ORIG_CALLER_INFO /* nothing */ +#define TRASH(A,B) /* nothing */ +#endif + +//@InfiniDB. @bug4585 For InnoDB upgrade. +#if defined(ENABLED_DEBUG_SYNC) +extern void (*debug_sync_C_callback_ptr)(const char *, size_t); +#define DEBUG_SYNC_C(_sync_point_name_) do { \ + if (debug_sync_C_callback_ptr != NULL) \ + (*debug_sync_C_callback_ptr)(STRING_WITH_LEN(_sync_point_name_)); } \ + while(0) +#else +#define DEBUG_SYNC_C(_sync_point_name_) +#endif /* defined(ENABLED_DEBUG_SYNC) */ + + +#ifdef HAVE_LARGE_PAGES +extern uint my_get_large_page_size(void); +extern uchar * my_large_malloc(size_t size, myf my_flags); +extern void my_large_free(uchar * ptr, myf my_flags); +#else +#define my_get_large_page_size() (0) +#define my_large_malloc(A,B) my_malloc_lock((A),(B)) +#define my_large_free(A,B) my_free_lock((A),(B)) +#endif /* HAVE_LARGE_PAGES */ + +#ifdef HAVE_ALLOCA +#if defined(_AIX) && !defined(__GNUC__) && !defined(_AIX43) +#pragma alloca +#endif /* _AIX */ +#if defined(__MWERKS__) +#undef alloca +#define alloca _alloca +#endif /* __MWERKS__ */ +#if defined(__GNUC__) && !defined(HAVE_ALLOCA_H) && ! defined(alloca) +#define alloca __builtin_alloca +#endif /* GNUC */ +#define my_alloca(SZ) alloca((size_t) (SZ)) +#define my_afree(PTR) {} +#else +#define my_alloca(SZ) my_malloc(SZ,MYF(0)) +#define my_afree(PTR) my_free(PTR,MYF(MY_WME)) +#endif /* HAVE_ALLOCA */ + +#ifndef errno /* did we already get it? */ +#ifdef HAVE_ERRNO_AS_DEFINE +#include /* errno is a define */ +#else +extern int errno; /* declare errno */ +#endif +#endif /* #ifndef errno */ +extern char *home_dir; /* Home directory for user */ +extern const char *my_progname; /* program-name (printed in errors) */ +extern char NEAR curr_dir[]; /* Current directory for user */ +extern int (*error_handler_hook)(uint my_err, const char *str,myf MyFlags); +extern int (*fatal_error_handler_hook)(uint my_err, const char *str, + myf MyFlags); +extern uint my_file_limit; +extern ulong my_thread_stack_size; + +#ifdef HAVE_LARGE_PAGES +extern my_bool my_use_large_pages; +extern uint my_large_page_size; +#endif + +/* charsets */ +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *default_charset_info; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *all_charsets[256]; +extern CHARSET_INFO compiled_charsets[]; + +/* statistics */ +extern ulong my_file_opened,my_stream_opened, my_tmp_file_created; +extern ulong my_file_total_opened; +extern uint mysys_usage_id; +extern my_bool my_init_done; + + /* Point to current my_message() */ +extern void (*my_sigtstp_cleanup)(void), + /* Executed before jump to shell */ + (*my_sigtstp_restart)(void), + (*my_abort_hook)(int); + /* Executed when comming from shell */ +extern MYSQL_PLUGIN_IMPORT int NEAR my_umask; /* Default creation mask */ +extern int NEAR my_umask_dir, + NEAR my_recived_signals, /* Signals we have got */ + NEAR my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */ + NEAR my_dont_interrupt; /* call remember_intr when set */ +extern my_bool NEAR mysys_uses_curses, my_use_symdir; +extern size_t sf_malloc_cur_memory, sf_malloc_max_memory; + +extern ulong my_default_record_cache_size; +extern my_bool NEAR my_disable_locking,NEAR my_disable_async_io, + NEAR my_disable_flush_key_blocks, NEAR my_disable_symlinks; +extern char wild_many,wild_one,wild_prefix; +extern const char *charsets_dir; +/* from default.c */ +extern char *my_defaults_extra_file; +extern const char *my_defaults_group_suffix; +extern const char *my_defaults_file; + +extern my_bool timed_mutexes; + +typedef struct wild_file_pack /* Struct to hold info when selecting files */ +{ + uint wilds; /* How many wildcards */ + uint not_pos; /* Start of not-theese-files */ + char * *wild; /* Pointer to wildcards */ +} WF_PACK; + +enum loglevel { + ERROR_LEVEL, + WARNING_LEVEL, + INFORMATION_LEVEL +}; + +enum cache_type +{ + TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE, + SEQ_READ_APPEND /* sequential read or append */, + READ_FIFO, READ_NET,WRITE_NET}; + +enum flush_type +{ + FLUSH_KEEP, /* flush block and keep it in the cache */ + FLUSH_RELEASE, /* flush block and remove it from the cache */ + FLUSH_IGNORE_CHANGED, /* remove block from the cache */ + /* + As my_disable_flush_pagecache_blocks is always 0, the following option + is strictly equivalent to FLUSH_KEEP + */ + FLUSH_FORCE_WRITE +}; + +typedef struct st_record_cache /* Used when cacheing records */ +{ + File file; + int rc_seek,error,inited; + uint rc_length,read_length,reclength; + my_off_t rc_record_pos,end_of_file; + uchar *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos; +#ifdef HAVE_AIOWAIT + int use_async_io; + my_aio_result aio_result; +#endif + enum cache_type type; +} RECORD_CACHE; + +enum file_type +{ + UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN, + FILE_BY_MKSTEMP, FILE_BY_DUP +}; + +struct st_my_file_info +{ + char * name; + enum file_type type; +#if defined(THREAD) && !defined(HAVE_PREAD) + pthread_mutex_t mutex; +#endif +}; + +extern struct st_my_file_info *my_file_info; + +typedef struct st_dynamic_array +{ + uchar *buffer; + uint elements,max_element; + uint alloc_increment; + uint size_of_element; +} DYNAMIC_ARRAY; + +typedef struct st_my_tmpdir +{ + DYNAMIC_ARRAY full_list; + char **list; + uint cur, max; +#ifdef THREAD + pthread_mutex_t mutex; +#endif +} MY_TMPDIR; + +typedef struct st_dynamic_string +{ + char *str; + size_t length,max_length,alloc_increment; +} DYNAMIC_STRING; + +struct st_io_cache; +typedef int (*IO_CACHE_CALLBACK)(struct st_io_cache*); + +#ifdef THREAD +typedef struct st_io_cache_share +{ + pthread_mutex_t mutex; /* To sync on reads into buffer. */ + pthread_cond_t cond; /* To wait for signals. */ + pthread_cond_t cond_writer; /* For a synchronized writer. */ + /* Offset in file corresponding to the first byte of buffer. */ + my_off_t pos_in_file; + /* If a synchronized write cache is the source of the data. */ + struct st_io_cache *source_cache; + uchar *buffer; /* The read buffer. */ + uchar *read_end; /* Behind last valid byte of buffer. */ + int running_threads; /* threads not in lock. */ + int total_threads; /* threads sharing the cache. */ + int error; /* Last error. */ +#ifdef NOT_YET_IMPLEMENTED + /* whether the structure should be free'd */ + my_bool alloced; +#endif +} IO_CACHE_SHARE; +#endif + +typedef struct st_io_cache /* Used when cacheing files */ +{ + /* Offset in file corresponding to the first byte of uchar* buffer. */ + my_off_t pos_in_file; + /* + The offset of end of file for READ_CACHE and WRITE_CACHE. + For SEQ_READ_APPEND it the maximum of the actual end of file and + the position represented by read_end. + */ + my_off_t end_of_file; + /* Points to current read position in the buffer */ + uchar *read_pos; + /* the non-inclusive boundary in the buffer for the currently valid read */ + uchar *read_end; + uchar *buffer; /* The read buffer */ + /* Used in ASYNC_IO */ + uchar *request_pos; + + /* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */ + uchar *write_buffer; + /* + Only used in SEQ_READ_APPEND, and points to the current read position + in the write buffer. Note that reads in SEQ_READ_APPEND caches can + happen from both read buffer (uchar* buffer) and write buffer + (uchar* write_buffer). + */ + uchar *append_read_pos; + /* Points to current write position in the write buffer */ + uchar *write_pos; + /* The non-inclusive boundary of the valid write area */ + uchar *write_end; + + /* + Current_pos and current_end are convenience variables used by + my_b_tell() and other routines that need to know the current offset + current_pos points to &write_pos, and current_end to &write_end in a + WRITE_CACHE, and &read_pos and &read_end respectively otherwise + */ + uchar **current_pos, **current_end; +#ifdef THREAD + /* + The lock is for append buffer used in SEQ_READ_APPEND cache + need mutex copying from append buffer to read buffer. + */ + pthread_mutex_t append_buffer_lock; + /* + The following is used when several threads are reading the + same file in parallel. They are synchronized on disk + accesses reading the cached part of the file asynchronously. + It should be set to NULL to disable the feature. Only + READ_CACHE mode is supported. + */ + IO_CACHE_SHARE *share; +#endif + /* + A caller will use my_b_read() macro to read from the cache + if the data is already in cache, it will be simply copied with + memcpy() and internal variables will be accordinging updated with + no functions invoked. However, if the data is not fully in the cache, + my_b_read() will call read_function to fetch the data. read_function + must never be invoked directly. + */ + int (*read_function)(struct st_io_cache *,uchar *,size_t); + /* + Same idea as in the case of read_function, except my_b_write() needs to + be replaced with my_b_append() for a SEQ_READ_APPEND cache + */ + int (*write_function)(struct st_io_cache *,const uchar *,size_t); + /* + Specifies the type of the cache. Depending on the type of the cache + certain operations might not be available and yield unpredicatable + results. Details to be documented later + */ + enum cache_type type; + /* + Callbacks when the actual read I/O happens. These were added and + are currently used for binary logging of LOAD DATA INFILE - when a + block is read from the file, we create a block create/append event, and + when IO_CACHE is closed, we create an end event. These functions could, + of course be used for other things + */ + IO_CACHE_CALLBACK pre_read; + IO_CACHE_CALLBACK post_read; + IO_CACHE_CALLBACK pre_close; + /* + Counts the number of times, when we were forced to use disk. We use it to + increase the binlog_cache_disk_use status variable. + */ + ulong disk_writes; + void* arg; /* for use by pre/post_read */ + char *file_name; /* if used with 'open_cached_file' */ + char *dir,*prefix; + File file; /* file descriptor */ + /* + seek_not_done is set by my_b_seek() to inform the upcoming read/write + operation that a seek needs to be preformed prior to the actual I/O + error is 0 if the cache operation was successful, -1 if there was a + "hard" error, and the actual number of I/O-ed bytes if the read/write was + partial. + */ + int seek_not_done,error; + /* buffer_length is memory size allocated for buffer or write_buffer */ + size_t buffer_length; + /* read_length is the same as buffer_length except when we use async io */ + size_t read_length; + myf myflags; /* Flags used to my_read/my_write */ + /* + alloced_buffer is 1 if the buffer was allocated by init_io_cache() and + 0 if it was supplied by the user. + Currently READ_NET is the only one that will use a buffer allocated + somewhere else + */ + my_bool alloced_buffer; +#ifdef HAVE_AIOWAIT + /* + As inidicated by ifdef, this is for async I/O, which is not currently + used (because it's not reliable on all systems) + */ + uint inited; + my_off_t aio_read_pos; + my_aio_result aio_result; +#endif +} IO_CACHE; + +typedef int (*qsort2_cmp)(const void *, const void *, const void *); + + /* defines for mf_iocache */ + + /* Test if buffer is inited */ +#define my_b_clear(info) (info)->buffer=0 +#define my_b_inited(info) (info)->buffer +#define my_b_EOF INT_MIN + +#define my_b_read(info,Buffer,Count) \ + ((info)->read_pos + (Count) <= (info)->read_end ?\ + (memcpy(Buffer,(info)->read_pos,(size_t) (Count)), \ + ((info)->read_pos+=(Count)),0) :\ + (*(info)->read_function)((info),Buffer,Count)) + +#define my_b_write(info,Buffer,Count) \ + ((info)->write_pos + (Count) <=(info)->write_end ?\ + (memcpy((info)->write_pos, (Buffer), (size_t)(Count)),\ + ((info)->write_pos+=(Count)),0) : \ + (*(info)->write_function)((info),(uchar *)(Buffer),(Count))) + +#define my_b_get(info) \ + ((info)->read_pos != (info)->read_end ?\ + ((info)->read_pos++, (int) (uchar) (info)->read_pos[-1]) :\ + _my_b_get(info)) + + /* my_b_write_byte dosn't have any err-check */ +#define my_b_write_byte(info,chr) \ + (((info)->write_pos < (info)->write_end) ?\ + ((*(info)->write_pos++)=(chr)) :\ + (_my_b_write(info,0,0) , ((*(info)->write_pos++)=(chr)))) + +#define my_b_fill_cache(info) \ + (((info)->read_end=(info)->read_pos),(*(info)->read_function)(info,0,0)) + +#define my_b_tell(info) ((info)->pos_in_file + \ + (size_t) (*(info)->current_pos - (info)->request_pos)) + +#define my_b_get_buffer_start(info) (info)->request_pos +#define my_b_get_bytes_in_buffer(info) (char*) (info)->read_end - \ + (char*) my_b_get_buffer_start(info) +#define my_b_get_pos_in_file(info) (info)->pos_in_file + +/* tell write offset in the SEQ_APPEND cache */ +int my_b_copy_to_file(IO_CACHE *cache, FILE *file); +my_off_t my_b_append_tell(IO_CACHE* info); +my_off_t my_b_safe_tell(IO_CACHE* info); /* picks the correct tell() */ + +#define my_b_bytes_in_cache(info) (size_t) (*(info)->current_end - \ + *(info)->current_pos) + +typedef uint32 ha_checksum; + +/* Define the type of function to be passed to process_default_option_files */ +typedef int (*Process_option_func)(void *ctx, const char *group_name, + const char *option); + +#include + + + /* Prototypes for mysys and my_func functions */ + +extern int my_copy(const char *from,const char *to,myf MyFlags); +extern int my_append(const char *from,const char *to,myf MyFlags); +extern int my_delete(const char *name,myf MyFlags); +extern int my_getwd(char * buf,size_t size,myf MyFlags); +extern int my_setwd(const char *dir,myf MyFlags); +extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags); +extern void *my_once_alloc(size_t Size,myf MyFlags); +extern void my_once_free(void); +extern char *my_once_strdup(const char *src,myf myflags); +extern void *my_once_memdup(const void *src, size_t len, myf myflags); +extern File my_open(const char *FileName,int Flags,myf MyFlags); +extern File my_register_filename(File fd, const char *FileName, + enum file_type type_of_file, + uint error_message_number, myf MyFlags); +extern File my_create(const char *FileName,int CreateFlags, + int AccessFlags, myf MyFlags); +extern int my_close(File Filedes,myf MyFlags); +extern File my_dup(File file, myf MyFlags); +extern int my_mkdir(const char *dir, int Flags, myf MyFlags); +extern int my_readlink(char *to, const char *filename, myf MyFlags); +extern int my_is_symlink(const char *filename); +extern int my_realpath(char *to, const char *filename, myf MyFlags); +extern File my_create_with_symlink(const char *linkname, const char *filename, + int createflags, int access_flags, + myf MyFlags); +extern int my_delete_with_symlink(const char *name, myf MyFlags); +extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags); +extern int my_symlink(const char *content, const char *linkname, myf MyFlags); +extern size_t my_read(File Filedes,uchar *Buffer,size_t Count,myf MyFlags); +extern size_t my_pread(File Filedes,uchar *Buffer,size_t Count,my_off_t offset, + myf MyFlags); +extern int my_rename(const char *from,const char *to,myf MyFlags); +extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags); +extern my_off_t my_tell(File fd,myf MyFlags); +extern size_t my_write(File Filedes,const uchar *Buffer,size_t Count, + myf MyFlags); +extern size_t my_pwrite(File Filedes,const uchar *Buffer,size_t Count, + my_off_t offset,myf MyFlags); +extern size_t my_fread(FILE *stream,uchar *Buffer,size_t Count,myf MyFlags); +extern size_t my_fwrite(FILE *stream,const uchar *Buffer,size_t Count, + myf MyFlags); +extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags); +extern my_off_t my_ftell(FILE *stream,myf MyFlags); +extern void *_mymalloc(size_t uSize,const char *sFile, + uint uLine, myf MyFlag); +extern void *_myrealloc(void *pPtr,size_t uSize,const char *sFile, + uint uLine, myf MyFlag); +extern void * my_multi_malloc _VARARGS((myf MyFlags, ...)); +extern void _myfree(void *pPtr,const char *sFile,uint uLine, myf MyFlag); +extern int _sanity(const char *sFile, uint uLine); +extern void *_my_memdup(const void *from, size_t length, + const char *sFile, uint uLine,myf MyFlag); +extern char * _my_strdup(const char *from, const char *sFile, uint uLine, + myf MyFlag); +extern char *_my_strndup(const char *from, size_t length, + const char *sFile, uint uLine, + myf MyFlag); + +/* implemented in my_memmem.c */ +extern void *my_memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen); + + +#ifdef __WIN__ +extern int my_access(const char *path, int amode); +extern File my_sopen(const char *path, int oflag, int shflag, int pmode); +#else +#define my_access access +#endif +extern int check_if_legal_filename(const char *path); +extern int check_if_legal_tablename(const char *path); + +#if defined(__WIN__) && defined(__NT__) +extern int nt_share_delete(const char *name,myf MyFlags); +#define my_delete_allow_opened(fname,flags) nt_share_delete((fname),(flags)) +#else +#define my_delete_allow_opened(fname,flags) my_delete((fname),(flags)) +#endif + +#ifndef TERMINATE +extern void TERMINATE(FILE *file, uint flag); +#endif +extern void init_glob_errs(void); +extern void wait_for_free_space(const char *filename, int errors); +extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags); +extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags); +extern int my_fclose(FILE *fd,myf MyFlags); +extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags); +extern int my_sync(File fd, myf my_flags); +extern int my_sync_dir(const char *dir_name, myf my_flags); +extern int my_sync_dir_by_file(const char *file_name, myf my_flags); +extern int my_error _VARARGS((int nr,myf MyFlags, ...)); +extern int my_printf_error _VARARGS((uint my_err, const char *format, + myf MyFlags, ...)) + ATTRIBUTE_FORMAT(printf, 2, 4); +extern int my_error_register(const char **errmsgs, int first, int last); +extern const char **my_error_unregister(int first, int last); +extern int my_message(uint my_err, const char *str,myf MyFlags); +extern int my_message_no_curses(uint my_err, const char *str,myf MyFlags); +extern int my_message_curses(uint my_err, const char *str,myf MyFlags); +extern my_bool my_init(void); +extern void my_end(int infoflag); +extern int my_redel(const char *from, const char *to, int MyFlags); +extern int my_copystat(const char *from, const char *to, int MyFlags); +extern char * my_filename(File fd); + +#ifndef THREAD +extern void dont_break(void); +extern void allow_break(void); +#else +#define dont_break() +#define allow_break() +#endif + +#ifdef EXTRA_DEBUG +void my_print_open_files(void); +#else +#define my_print_open_files() +#endif + +extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist); +extern char *my_tmpdir(MY_TMPDIR *tmpdir); +extern void free_tmpdir(MY_TMPDIR *tmpdir); + +extern void my_remember_signal(int signal_number,sig_handler (*func)(int)); +extern size_t dirname_part(char * to,const char *name, size_t *to_res_length); +extern size_t dirname_length(const char *name); +#define base_name(A) (A+dirname_length(A)) +extern int test_if_hard_path(const char *dir_name); +extern my_bool has_path(const char *name); +extern char *convert_dirname(char *to, const char *from, const char *from_end); +extern void to_unix_path(char * name); +extern char * fn_ext(const char *name); +extern char * fn_same(char * toname,const char *name,int flag); +extern char * fn_format(char * to,const char *name,const char *dir, + const char *form, uint flag); +extern size_t strlength(const char *str); +extern void pack_dirname(char * to,const char *from); +extern size_t normalize_dirname(char * to, const char *from); +extern size_t unpack_dirname(char * to,const char *from); +extern size_t cleanup_dirname(char * to,const char *from); +extern size_t system_filename(char * to,const char *from); +extern size_t unpack_filename(char * to,const char *from); +extern char * intern_filename(char * to,const char *from); +extern char * directory_file_name(char * dst, const char *src); +extern int pack_filename(char * to, const char *name, size_t max_length); +extern char * my_path(char * to,const char *progname, + const char *own_pathname_part); +extern char * my_load_path(char * to, const char *path, + const char *own_path_prefix); +extern int wild_compare(const char *str,const char *wildstr, + pbool str_is_pattern); +extern WF_PACK *wf_comp(char * str); +extern int wf_test(struct wild_file_pack *wf_pack,const char *name); +extern void wf_end(struct wild_file_pack *buffer); +extern size_t strip_sp(char * str); +extern my_bool array_append_string_unique(const char *str, + const char **array, size_t size); +extern void get_date(char * to,int timeflag,time_t use_time); +extern void soundex(CHARSET_INFO *, char * out_pntr, char * in_pntr, + pbool remove_garbage); +extern int init_record_cache(RECORD_CACHE *info,size_t cachesize,File file, + size_t reclength,enum cache_type type, + pbool use_async_io); +extern int read_cache_record(RECORD_CACHE *info,uchar *to); +extern int end_record_cache(RECORD_CACHE *info); +extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos, + const uchar *record,size_t length); +extern int flush_write_cache(RECORD_CACHE *info); +extern long my_clock(void); +extern sig_handler sigtstp_handler(int signal_number); +extern void handle_recived_signals(void); + +extern sig_handler my_set_alarm_variable(int signo); +extern void my_string_ptr_sort(uchar *base,uint items,size_t size); +extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements, + size_t size_of_element,uchar *buffer[]); +extern qsort_t my_qsort(void *base_ptr, size_t total_elems, size_t size, + qsort_cmp cmp); +extern qsort_t my_qsort2(void *base_ptr, size_t total_elems, size_t size, + qsort2_cmp cmp, void *cmp_argument); +extern qsort2_cmp get_ptr_compare(size_t); +void my_store_ptr(uchar *buff, size_t pack_length, my_off_t pos); +my_off_t my_get_ptr(uchar *ptr, size_t pack_length); +extern int init_io_cache(IO_CACHE *info,File file,size_t cachesize, + enum cache_type type,my_off_t seek_offset, + pbool use_async_io, myf cache_myflags); +extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type, + my_off_t seek_offset,pbool use_async_io, + pbool clear_cache); +extern void setup_io_cache(IO_CACHE* info); +extern int _my_b_read(IO_CACHE *info,uchar *Buffer,size_t Count); +#ifdef THREAD +extern int _my_b_read_r(IO_CACHE *info,uchar *Buffer,size_t Count); +extern void init_io_cache_share(IO_CACHE *read_cache, IO_CACHE_SHARE *cshare, + IO_CACHE *write_cache, uint num_threads); +extern void remove_io_thread(IO_CACHE *info); +#endif +extern int _my_b_seq_read(IO_CACHE *info,uchar *Buffer,size_t Count); +extern int _my_b_net_read(IO_CACHE *info,uchar *Buffer,size_t Count); +extern int _my_b_get(IO_CACHE *info); +extern int _my_b_async_read(IO_CACHE *info,uchar *Buffer,size_t Count); +extern int _my_b_write(IO_CACHE *info,const uchar *Buffer,size_t Count); +extern int my_b_append(IO_CACHE *info,const uchar *Buffer,size_t Count); +extern int my_b_safe_write(IO_CACHE *info,const uchar *Buffer,size_t Count); + +extern int my_block_write(IO_CACHE *info, const uchar *Buffer, + size_t Count, my_off_t pos); +extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock); + +#define flush_io_cache(info) my_b_flush_io_cache((info),1) + +extern int end_io_cache(IO_CACHE *info); +extern size_t my_b_fill(IO_CACHE *info); +extern void my_b_seek(IO_CACHE *info,my_off_t pos); +extern size_t my_b_gets(IO_CACHE *info, char *to, size_t max_length); +extern my_off_t my_b_filelength(IO_CACHE *info); +extern size_t my_b_printf(IO_CACHE *info, const char* fmt, ...); +extern size_t my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap); +extern my_bool open_cached_file(IO_CACHE *cache,const char *dir, + const char *prefix, size_t cache_size, + myf cache_myflags); +extern my_bool real_open_cached_file(IO_CACHE *cache); +extern void close_cached_file(IO_CACHE *cache); +File create_temp_file(char *to, const char *dir, const char *pfx, + int mode, myf MyFlags); +#define my_init_dynamic_array(A,B,C,D) init_dynamic_array2(A,B,NULL,C,D CALLER_INFO) +#define my_init_dynamic_array_ci(A,B,C,D) init_dynamic_array2(A,B,NULL,C,D ORIG_CALLER_INFO) +#define my_init_dynamic_array2(A,B,C,D,E) init_dynamic_array2(A,B,C,D,E CALLER_INFO) +#define my_init_dynamic_array2_ci(A,B,C,D,E) init_dynamic_array2(A,B,C,D,E ORIG_CALLER_INFO) +extern my_bool init_dynamic_array2(DYNAMIC_ARRAY *array,uint element_size, + void *init_buffer, uint init_alloc, + uint alloc_increment + CALLER_INFO_PROTO); +/* init_dynamic_array() function is deprecated */ +extern my_bool init_dynamic_array(DYNAMIC_ARRAY *array,uint element_size, + uint init_alloc,uint alloc_increment + CALLER_INFO_PROTO); +extern my_bool insert_dynamic(DYNAMIC_ARRAY *array,uchar * element); +extern uchar *alloc_dynamic(DYNAMIC_ARRAY *array); +extern uchar *pop_dynamic(DYNAMIC_ARRAY*); +extern my_bool set_dynamic(DYNAMIC_ARRAY *array,uchar * element,uint array_index); +extern my_bool allocate_dynamic(DYNAMIC_ARRAY *array, uint max_elements); +extern void get_dynamic(DYNAMIC_ARRAY *array,uchar * element,uint array_index); +extern void delete_dynamic(DYNAMIC_ARRAY *array); +extern void delete_dynamic_element(DYNAMIC_ARRAY *array, uint array_index); +extern void freeze_size(DYNAMIC_ARRAY *array); +extern int get_index_dynamic(DYNAMIC_ARRAY *array, uchar * element); +#define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element) +#define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index)) +#define push_dynamic(A,B) insert_dynamic((A),(B)) +#define reset_dynamic(array) ((array)->elements= 0) +#define sort_dynamic(A,cmp) my_qsort((A)->buffer, (A)->elements, (A)->size_of_element, (cmp)) + +extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str, + size_t init_alloc,size_t alloc_increment); +extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append); +my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append, + size_t length); +extern my_bool dynstr_append_os_quoted(DYNAMIC_STRING *str, const char *append, + ...); +extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str); +extern my_bool dynstr_realloc(DYNAMIC_STRING *str, size_t additional_size); +extern my_bool dynstr_trunc(DYNAMIC_STRING *str, size_t n); +extern void dynstr_free(DYNAMIC_STRING *str); +#ifdef HAVE_MLOCK +extern void *my_malloc_lock(size_t length,myf flags); +extern void my_free_lock(void *ptr,myf flags); +#else +#define my_malloc_lock(A,B) my_malloc((A),(B)) +#define my_free_lock(A,B) my_free((A),(B)) +#endif +#define alloc_root_inited(A) ((A)->min_malloc != 0) +#define ALLOC_ROOT_MIN_BLOCK_SIZE (MALLOC_OVERHEAD + sizeof(USED_MEM) + 8) +#define clear_alloc_root(A) do { (A)->free= (A)->used= (A)->pre_alloc= 0; (A)->min_malloc=0;} while(0) +extern void init_alloc_root(MEM_ROOT *mem_root, size_t block_size, + size_t pre_alloc_size); +extern void *alloc_root(MEM_ROOT *mem_root, size_t Size); +extern void *multi_alloc_root(MEM_ROOT *mem_root, ...); +extern void free_root(MEM_ROOT *root, myf MyFLAGS); +extern void set_prealloc_root(MEM_ROOT *root, char *ptr); +extern void reset_root_defaults(MEM_ROOT *mem_root, size_t block_size, + size_t prealloc_size); +extern char *strdup_root(MEM_ROOT *root,const char *str); +extern char *strmake_root(MEM_ROOT *root,const char *str,size_t len); +extern void *memdup_root(MEM_ROOT *root,const void *str, size_t len); +extern int get_defaults_options(int argc, char **argv, + char **defaults, char **extra_defaults, + char **group_suffix); +extern int my_load_defaults(const char *conf_file, const char **groups, + int *argc, char ***argv, const char ***); +extern int load_defaults(const char *conf_file, const char **groups, + int *argc, char ***argv); +extern int modify_defaults_file(const char *file_location, const char *option, + const char *option_value, + const char *section_name, int remove_option); +extern int my_search_option_files(const char *conf_file, int *argc, + char ***argv, uint *args_used, + Process_option_func func, void *func_ctx, + const char **default_directories); +extern void free_defaults(char **argv); +extern void my_print_default_files(const char *conf_file); +extern void print_defaults(const char *conf_file, const char **groups); +extern my_bool my_compress(uchar *, size_t *, size_t *); +extern my_bool my_uncompress(uchar *, size_t , size_t *); +extern uchar *my_compress_alloc(const uchar *packet, size_t *len, + size_t *complen); +extern int packfrm(uchar *, size_t, uchar **, size_t *); +extern int unpackfrm(uchar **, size_t *, const uchar *); + +extern ha_checksum my_checksum(ha_checksum crc, const uchar *mem, + size_t count); +extern void my_sleep(ulong m_seconds); +extern ulong crc32(ulong crc, const uchar *buf, uint len); +extern uint my_set_max_open_files(uint files); +void my_free_open_file_info(void); + +extern time_t my_time(myf flags); +extern ulonglong my_getsystime(void); +extern ulonglong my_micro_time(); +extern ulonglong my_micro_time_and_time(time_t *time_arg); +time_t my_time_possible_from_micro(ulonglong microtime); +extern my_bool my_gethwaddr(uchar *to); +extern int my_getncpus(); + +#ifdef HAVE_SYS_MMAN_H +#include + +#ifndef MAP_NOSYNC +#define MAP_NOSYNC 0 +#endif +#ifndef MAP_NORESERVE +#define MAP_NORESERVE 0 /* For irix and AIX */ +#endif + +#ifdef HAVE_MMAP64 +#define my_mmap(a,b,c,d,e,f) mmap64(a,b,c,d,e,f) +#else +#define my_mmap(a,b,c,d,e,f) mmap(a,b,c,d,e,f) +#endif +#define my_munmap(a,b) munmap((a),(b)) + +#else +/* not a complete set of mmap() flags, but only those that nesessary */ +#define PROT_READ 1 +#define PROT_WRITE 2 +#define MAP_NORESERVE 0 +#define MAP_SHARED 0x0001 +#define MAP_PRIVATE 0x0002 +#define MAP_NOSYNC 0x0800 +#define MAP_FAILED ((void *)-1) +#define MS_SYNC 0x0000 + +#ifndef __NETWARE__ +#define HAVE_MMAP +#endif + +void *my_mmap(void *, size_t, int, int, int, my_off_t); +int my_munmap(void *, size_t); +#endif + +/* my_getpagesize */ +#ifdef HAVE_GETPAGESIZE +#define my_getpagesize() getpagesize() +#else +int my_getpagesize(void); +#endif + +int my_msync(int, void *, size_t, int); + +/* character sets */ +extern uint get_charset_number(const char *cs_name, uint cs_flags); +extern uint get_collation_number(const char *name); +extern const char *get_charset_name(uint cs_number); + +extern CHARSET_INFO *get_charset(uint cs_number, myf flags); +extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags); +extern CHARSET_INFO *get_charset_by_csname(const char *cs_name, + uint cs_flags, myf my_flags); + +extern my_bool resolve_charset(const char *cs_name, + CHARSET_INFO *default_cs, + CHARSET_INFO **cs); +extern my_bool resolve_collation(const char *cl_name, + CHARSET_INFO *default_cl, + CHARSET_INFO **cl); + +extern void free_charsets(void); +extern char *get_charsets_dir(char *buf); +extern my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2); +extern my_bool init_compiled_charsets(myf flags); +extern void add_compiled_collation(CHARSET_INFO *cs); +extern size_t escape_string_for_mysql(CHARSET_INFO *charset_info, + char *to, size_t to_length, + const char *from, size_t length); +#ifdef __WIN__ +#define BACKSLASH_MBTAIL +/* File system character set */ +extern CHARSET_INFO *fs_character_set(void); +#endif +extern size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info, + char *to, size_t to_length, + const char *from, size_t length); + +extern void thd_increment_bytes_sent(ulong length); +extern void thd_increment_bytes_received(ulong length); +extern void thd_increment_net_big_packet_count(ulong length); + +#ifdef __WIN__ +extern my_bool have_tcpip; /* Is set if tcpip is used */ + +/* implemented in my_windac.c */ + +int my_security_attr_create(SECURITY_ATTRIBUTES **psa, const char **perror, + DWORD owner_rights, DWORD everybody_rights); + +void my_security_attr_free(SECURITY_ATTRIBUTES *sa); + +/* implemented in my_conio.c */ +char* my_cgets(char *string, size_t clen, size_t* plen); + +#endif +#ifdef __NETWARE__ +void netware_reg_user(const char *ip, const char *user, + const char *application); +#endif + +C_MODE_END +#endif /* _my_sys_h */ diff --git a/dbcon/mysql/include/mysql_com.h b/dbcon/mysql/include/mysql_com.h new file mode 100644 index 00000000..2a39cbe5 --- /dev/null +++ b/dbcon/mysql/include/mysql_com.h @@ -0,0 +1,522 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* +** Common definition between mysql server & client +*/ + +#ifndef _mysql_com_h +#define _mysql_com_h + +#define HOSTNAME_LENGTH 60 +#define SYSTEM_CHARSET_MBMAXLEN 3 +#define NAME_CHAR_LEN 128 /* Field/table name length */ +#define USERNAME_CHAR_LENGTH 16 +#define NAME_LEN (NAME_CHAR_LEN*SYSTEM_CHARSET_MBMAXLEN) +#define USERNAME_LENGTH (USERNAME_CHAR_LENGTH*SYSTEM_CHARSET_MBMAXLEN) + +#define SERVER_VERSION_LENGTH 60 +#define SQLSTATE_LENGTH 5 + +/* + USER_HOST_BUFF_SIZE -- length of string buffer, that is enough to contain + username and hostname parts of the user identifier with trailing zero in + MySQL standard format: + user_name_part@host_name_part\0 +*/ +#define USER_HOST_BUFF_SIZE HOSTNAME_LENGTH + USERNAME_LENGTH + 2 + +#define LOCAL_HOST "localhost" +#define LOCAL_HOST_NAMEDPIPE "." + + +#if defined(__WIN__) && !defined( _CUSTOMCONFIG_) +#define MYSQL_NAMEDPIPE "MySQL" +#define MYSQL_SERVICENAME "MySQL" +#endif /* __WIN__ */ + +/* + You should add new commands to the end of this list, otherwise old + servers won't be able to handle them as 'unsupported'. +*/ + +enum enum_server_command +{ + COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, + COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, + COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, + COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, + COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE, + COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, + COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_DAEMON, + /* don't forget to update const char *command_name[] in sql_parse.cc */ + + /* Must be last */ + COM_END +}; + + +/* + Length of random string sent by server on handshake; this is also length of + obfuscated password, recieved from client +*/ +#define SCRAMBLE_LENGTH 20 +#define SCRAMBLE_LENGTH_323 8 +/* length of password stored in the db: new passwords are preceeded with '*' */ +#define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1) +#define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2) + + +#define NOT_NULL_FLAG 1 /* Field can't be NULL */ +#define PRI_KEY_FLAG 2 /* Field is part of a primary key */ +#define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */ +#define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */ +#define BLOB_FLAG 16 /* Field is a blob */ +#define UNSIGNED_FLAG 32 /* Field is unsigned */ +#define ZEROFILL_FLAG 64 /* Field is zerofill */ +#define BINARY_FLAG 128 /* Field is binary */ + +/* The following are only sent to new clients */ +#define ENUM_FLAG 256 /* field is an enum */ +#define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */ +#define TIMESTAMP_FLAG 1024 /* Field is a timestamp */ +#define SET_FLAG 2048 /* field is a set */ +#define NO_DEFAULT_VALUE_FLAG 4096 /* Field doesn't have default value */ +#define ON_UPDATE_NOW_FLAG 8192 /* Field is set to NOW on UPDATE */ +#define NUM_FLAG 32768 /* Field is num (for clients) */ +#define PART_KEY_FLAG 16384 /* Intern; Part of some key */ +#define GROUP_FLAG 32768 /* Intern: Group field */ +#define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */ +#define BINCMP_FLAG 131072 /* Intern: Used by sql_yacc */ +#define GET_FIXED_FIELDS_FLAG (1 << 18) /* Used to get fields in item tree */ +#define FIELD_IN_PART_FUNC_FLAG (1 << 19)/* Field part of partition func */ +#define FIELD_IN_ADD_INDEX (1<< 20) /* Intern: Field used in ADD INDEX */ +#define FIELD_IS_RENAMED (1<< 21) /* Intern: Field is being renamed */ + +#define REFRESH_GRANT 1 /* Refresh grant tables */ +#define REFRESH_LOG 2 /* Start on new log file */ +#define REFRESH_TABLES 4 /* close all tables */ +#define REFRESH_HOSTS 8 /* Flush host cache */ +#define REFRESH_STATUS 16 /* Flush status variables */ +#define REFRESH_THREADS 32 /* Flush thread cache */ +#define REFRESH_SLAVE 64 /* Reset master info and restart slave + thread */ +#define REFRESH_MASTER 128 /* Remove all bin logs in the index + and truncate the index */ + +/* The following can't be set with mysql_refresh() */ +#define REFRESH_READ_LOCK 16384 /* Lock tables for read */ +#define REFRESH_FAST 32768 /* Intern flag */ + +/* RESET (remove all queries) from query cache */ +#define REFRESH_QUERY_CACHE 65536 +#define REFRESH_QUERY_CACHE_FREE 0x20000L /* pack query cache */ +#define REFRESH_DES_KEY_FILE 0x40000L +#define REFRESH_USER_RESOURCES 0x80000L + +#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */ +#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */ +#define CLIENT_LONG_FLAG 4 /* Get all column flags */ +#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */ +#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */ +#define CLIENT_COMPRESS 32 /* Can use compression protocol */ +#define CLIENT_ODBC 64 /* Odbc client */ +#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */ +#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */ +#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */ +#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */ +#define CLIENT_SSL 2048 /* Switch to SSL after handshake */ +#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */ +#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */ +#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */ +#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */ +#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */ +#define CLIENT_MULTI_RESULTS (1UL << 17) /* Enable/disable multi-results */ + +#define CLIENT_SSL_VERIFY_SERVER_CERT (1UL << 30) +#define CLIENT_REMEMBER_OPTIONS (1UL << 31) + +/* Gather all possible capabilites (flags) supported by the server */ +#define CLIENT_ALL_FLAGS (CLIENT_LONG_PASSWORD | \ + CLIENT_FOUND_ROWS | \ + CLIENT_LONG_FLAG | \ + CLIENT_CONNECT_WITH_DB | \ + CLIENT_NO_SCHEMA | \ + CLIENT_COMPRESS | \ + CLIENT_ODBC | \ + CLIENT_LOCAL_FILES | \ + CLIENT_IGNORE_SPACE | \ + CLIENT_PROTOCOL_41 | \ + CLIENT_INTERACTIVE | \ + CLIENT_SSL | \ + CLIENT_IGNORE_SIGPIPE | \ + CLIENT_TRANSACTIONS | \ + CLIENT_RESERVED | \ + CLIENT_SECURE_CONNECTION | \ + CLIENT_MULTI_STATEMENTS | \ + CLIENT_MULTI_RESULTS | \ + CLIENT_SSL_VERIFY_SERVER_CERT | \ + CLIENT_REMEMBER_OPTIONS) + +/* + Switch off the flags that are optional and depending on build flags + If any of the optional flags is supported by the build it will be switched + on before sending to the client during the connection handshake. +*/ +#define CLIENT_BASIC_FLAGS (((CLIENT_ALL_FLAGS & ~CLIENT_SSL) \ + & ~CLIENT_COMPRESS) \ + & ~CLIENT_SSL_VERIFY_SERVER_CERT) + +#define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */ +#define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */ +#define SERVER_MORE_RESULTS_EXISTS 8 /* Multi query - next query exists */ +#define SERVER_QUERY_NO_GOOD_INDEX_USED 16 +#define SERVER_QUERY_NO_INDEX_USED 32 +/** + The server was able to fulfill the clients request and opened a + read-only non-scrollable cursor for a query. This flag comes + in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. +*/ +#define SERVER_STATUS_CURSOR_EXISTS 64 +/** + This flag is sent when a read-only cursor is exhausted, in reply to + COM_STMT_FETCH command. +*/ +#define SERVER_STATUS_LAST_ROW_SENT 128 +#define SERVER_STATUS_DB_DROPPED 256 /* A database was dropped */ +#define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512 +/** + Sent to the client if after a prepared statement reprepare + we discovered that the new statement returns a different + number of result set columns. +*/ +#define SERVER_STATUS_METADATA_CHANGED 1024 + +/** + Server status flags that must be cleared when starting + execution of a new SQL statement. + Flags from this set are only added to the + current server status by the execution engine, but + never removed -- the execution engine expects them + to disappear automagically by the next command. +*/ +#define SERVER_STATUS_CLEAR_SET (SERVER_QUERY_NO_GOOD_INDEX_USED| \ + SERVER_QUERY_NO_INDEX_USED|\ + SERVER_MORE_RESULTS_EXISTS|\ + SERVER_STATUS_METADATA_CHANGED) + +#define MYSQL_ERRMSG_SIZE 512 +#define NET_READ_TIMEOUT 30 /* Timeout on read */ +#define NET_WRITE_TIMEOUT 60 /* Timeout on write */ +#define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */ + +#define ONLY_KILL_QUERY 1 + + +struct st_vio; /* Only C */ +typedef struct st_vio Vio; + +#define MAX_TINYINT_WIDTH 3 /* Max width for a TINY w.o. sign */ +#define MAX_SMALLINT_WIDTH 5 /* Max width for a SHORT w.o. sign */ +#define MAX_MEDIUMINT_WIDTH 8 /* Max width for a INT24 w.o. sign */ +#define MAX_INT_WIDTH 10 /* Max width for a LONG w.o. sign */ +#define MAX_BIGINT_WIDTH 20 /* Max width for a LONGLONG */ +#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR colum */ +#define MAX_BLOB_WIDTH 16777216 /* Default width for blob */ + +typedef struct st_net { +#if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY) + Vio *vio; + unsigned char *buff,*buff_end,*write_pos,*read_pos; + my_socket fd; /* For Perl DBI/dbd */ + /* + The following variable is set if we are doing several queries in one + command ( as in LOAD TABLE ... FROM MASTER ), + and do not want to confuse the client with OK at the wrong time + */ + unsigned long remain_in_buf,length, buf_length, where_b; + unsigned long max_packet,max_packet_size; + unsigned int pkt_nr,compress_pkt_nr; + unsigned int write_timeout, read_timeout, retry_count; + int fcntl; + unsigned int *return_status; + unsigned char reading_or_writing; + char save_char; + my_bool unused0; /* Please remove with the next incompatible ABI change. */ + my_bool unused; /* Please remove with the next incompatible ABI change */ + my_bool compress; + my_bool unused1; /* Please remove with the next incompatible ABI change. */ + /* + Pointer to query object in query cache, do not equal NULL (0) for + queries in cache that have not stored its results yet + */ +#endif + /* + 'query_cache_query' should be accessed only via query cache + functions and methods to maintain proper locking. + */ + unsigned char *query_cache_query; + unsigned int last_errno; + unsigned char error; + my_bool unused2; /* Please remove with the next incompatible ABI change. */ + my_bool return_errno; + /** Client library error message buffer. Actually belongs to struct MYSQL. */ + char last_error[MYSQL_ERRMSG_SIZE]; + /** Client library sqlstate buffer. Set along with the error message. */ + char sqlstate[SQLSTATE_LENGTH+1]; + void *extension; +} NET; + + +#define packet_error (~(unsigned long) 0) + +enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY, + MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, + MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE, + MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP, + MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24, + MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, + MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, + MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR, + MYSQL_TYPE_BIT, + MYSQL_TYPE_NEWDECIMAL=246, + MYSQL_TYPE_ENUM=247, + MYSQL_TYPE_SET=248, + MYSQL_TYPE_TINY_BLOB=249, + MYSQL_TYPE_MEDIUM_BLOB=250, + MYSQL_TYPE_LONG_BLOB=251, + MYSQL_TYPE_BLOB=252, + MYSQL_TYPE_VAR_STRING=253, + MYSQL_TYPE_STRING=254, + MYSQL_TYPE_GEOMETRY=255 + +}; + +/* For backward compatibility */ +#define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS +#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL +#define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL +#define FIELD_TYPE_TINY MYSQL_TYPE_TINY +#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT +#define FIELD_TYPE_LONG MYSQL_TYPE_LONG +#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT +#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE +#define FIELD_TYPE_NULL MYSQL_TYPE_NULL +#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP +#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG +#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24 +#define FIELD_TYPE_DATE MYSQL_TYPE_DATE +#define FIELD_TYPE_TIME MYSQL_TYPE_TIME +#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME +#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR +#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE +#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM +#define FIELD_TYPE_SET MYSQL_TYPE_SET +#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB +#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB +#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB +#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB +#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING +#define FIELD_TYPE_STRING MYSQL_TYPE_STRING +#define FIELD_TYPE_CHAR MYSQL_TYPE_TINY +#define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM +#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY +#define FIELD_TYPE_BIT MYSQL_TYPE_BIT + + +/* Shutdown/kill enums and constants */ + +/* Bits for THD::killable. */ +#define MYSQL_SHUTDOWN_KILLABLE_CONNECT (unsigned char)(1 << 0) +#define MYSQL_SHUTDOWN_KILLABLE_TRANS (unsigned char)(1 << 1) +#define MYSQL_SHUTDOWN_KILLABLE_LOCK_TABLE (unsigned char)(1 << 2) +#define MYSQL_SHUTDOWN_KILLABLE_UPDATE (unsigned char)(1 << 3) + +enum mysql_enum_shutdown_level { + /* + We want levels to be in growing order of hardness (because we use number + comparisons). Note that DEFAULT does not respect the growing property, but + it's ok. + */ + SHUTDOWN_DEFAULT = 0, + /* wait for existing connections to finish */ + SHUTDOWN_WAIT_CONNECTIONS= MYSQL_SHUTDOWN_KILLABLE_CONNECT, + /* wait for existing trans to finish */ + SHUTDOWN_WAIT_TRANSACTIONS= MYSQL_SHUTDOWN_KILLABLE_TRANS, + /* wait for existing updates to finish (=> no partial MyISAM update) */ + SHUTDOWN_WAIT_UPDATES= MYSQL_SHUTDOWN_KILLABLE_UPDATE, + /* flush InnoDB buffers and other storage engines' buffers*/ + SHUTDOWN_WAIT_ALL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1), + /* don't flush InnoDB buffers, flush other storage engines' buffers*/ + SHUTDOWN_WAIT_CRITICAL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1) + 1, + /* Now the 2 levels of the KILL command */ +#if MYSQL_VERSION_ID >= 50000 + KILL_QUERY= 254, +#endif + KILL_CONNECTION= 255 +}; + + +enum enum_cursor_type +{ + CURSOR_TYPE_NO_CURSOR= 0, + CURSOR_TYPE_READ_ONLY= 1, + CURSOR_TYPE_FOR_UPDATE= 2, + CURSOR_TYPE_SCROLLABLE= 4 +}; + + +/* options for mysql_set_option */ +enum enum_mysql_set_option +{ + MYSQL_OPTION_MULTI_STATEMENTS_ON, + MYSQL_OPTION_MULTI_STATEMENTS_OFF +}; + +#define net_new_transaction(net) ((net)->pkt_nr=0) + +#ifdef __cplusplus +extern "C" { +#endif + +my_bool my_net_init(NET *net, Vio* vio); +void my_net_local_init(NET *net); +void net_end(NET *net); + void net_clear(NET *net, my_bool clear_buffer); +my_bool net_realloc(NET *net, size_t length); +my_bool net_flush(NET *net); +my_bool my_net_write(NET *net,const unsigned char *packet, size_t len); +my_bool net_write_command(NET *net,unsigned char command, + const unsigned char *header, size_t head_len, + const unsigned char *packet, size_t len); +int net_real_write(NET *net,const unsigned char *packet, size_t len); +unsigned long my_net_read(NET *net); + +#ifdef _global_h +void my_net_set_write_timeout(NET *net, uint timeout); +void my_net_set_read_timeout(NET *net, uint timeout); +#endif + +/* + The following function is not meant for normal usage + Currently it's used internally by manager.c +*/ +struct sockaddr; +int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen, + unsigned int timeout); + +struct rand_struct { + unsigned long seed1,seed2,max_value; + double max_value_dbl; +}; + +#ifdef __cplusplus +} +#endif + + /* The following is for user defined functions */ + +enum Item_result {STRING_RESULT=0, REAL_RESULT, INT_RESULT, ROW_RESULT, + DECIMAL_RESULT}; + +typedef struct st_udf_args +{ + unsigned int arg_count; /* Number of arguments */ + enum Item_result *arg_type; /* Pointer to item_results */ + char **args; /* Pointer to argument */ + unsigned long *lengths; /* Length of string arguments */ + char *maybe_null; /* Set to 1 for all maybe_null args */ + char **attributes; /* Pointer to attribute name */ + unsigned long *attribute_lengths; /* Length of attribute arguments */ + void *extension; +} UDF_ARGS; + + /* This holds information about the result */ + +typedef struct st_udf_init +{ + my_bool maybe_null; /* 1 if function can return NULL */ + unsigned int decimals; /* for real functions */ + unsigned long max_length; /* For string functions */ + char *ptr; /* free pointer for function data */ + my_bool const_item; /* 1 if function always returns the same value */ + void *extension; +} UDF_INIT; +/* + TODO: add a notion for determinism of the UDF. + See Item_udf_func::update_used_tables () +*/ + + /* Constants when using compression */ +#define NET_HEADER_SIZE 4 /* standard header size */ +#define COMP_HEADER_SIZE 3 /* compression header extra size */ + + /* Prototypes to password functions */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + These functions are used for authentication by client and server and + implemented in sql/password.c +*/ + +void randominit(struct rand_struct *, unsigned long seed1, + unsigned long seed2); +double my_rnd(struct rand_struct *); +void create_random_string(char *to, unsigned int length, struct rand_struct *rand_st); + +void hash_password(unsigned long *to, const char *password, unsigned int password_len); +void make_scrambled_password_323(char *to, const char *password); +void scramble_323(char *to, const char *message, const char *password); +my_bool check_scramble_323(const char *, const char *message, + unsigned long *salt); +void get_salt_from_password_323(unsigned long *res, const char *password); +void make_password_from_salt_323(char *to, const unsigned long *salt); + +void make_scrambled_password(char *to, const char *password); +void scramble(char *to, const char *message, const char *password); +my_bool check_scramble(const char *reply, const char *message, + const unsigned char *hash_stage2); +void get_salt_from_password(unsigned char *res, const char *password); +void make_password_from_salt(char *to, const unsigned char *hash_stage2); +char *octet2hex(char *to, const char *str, unsigned int len); + +/* end of password.c */ + +char *get_tty_password(const char *opt_message); +const char *mysql_errno_to_sqlstate(unsigned int mysql_errno); + +/* Some other useful functions */ + +my_bool my_thread_init(void); +void my_thread_end(void); + +#ifdef _global_h +ulong STDCALL net_field_length(uchar **packet); +my_ulonglong net_field_length_ll(uchar **packet); +uchar *net_store_length(uchar *pkg, ulonglong length); +#endif + +#ifdef __cplusplus +} +#endif + +#define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */ +#define MYSQL_STMT_HEADER 4 +#define MYSQL_LONG_DATA_HEADER 6 + +#endif diff --git a/dbcon/mysql/install_calpont_mysql.sh b/dbcon/mysql/install_calpont_mysql.sh index 0f26a62b..af5f6fd3 100755 --- a/dbcon/mysql/install_calpont_mysql.sh +++ b/dbcon/mysql/install_calpont_mysql.sh @@ -4,52 +4,25 @@ # prefix=/usr/local -installdir=$prefix/Calpont rpmmode=install pwprompt=" " - for arg in "$@"; do if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then prefix="`echo $arg | awk -F= '{print $2}'`" - installdir=$prefix/Calpont elif [ `expr -- "$arg" : '--rpmmode='` -eq 10 ]; then rpmmode="`echo $arg | awk -F= '{print $2}'`" elif [ `expr -- "$arg" : '--password='` -eq 11 ]; then password="`echo $arg | awk -F= '{print $2}'`" pwprompt="--password=$password" - elif [ `expr -- "$arg" : '--installdir='` -eq 13 ]; then - installdir="`echo $arg | awk -F= '{print $2}'`" - prefix=`dirname $installdir` else echo "ignoring unknown argument: $arg" 1>&2 fi done -df=$installdir/mysql/my.cnf +df=$prefix/Calpont/mysql/my.cnf -$installdir/mysql/bin/mysql --defaults-file=$df --force --user=root $pwprompt mysql 2>/tmp/mysql_install.log </dev/null </dev/null <$installdir/mysql/syscatalog_mysql.sql -$installdir/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$installdir/mysql/calsetuserpriority.sql -$installdir/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$installdir/mysql/calremoveuserpriority.sql -$installdir/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$installdir/mysql/calshowprocesslist.sql - -sed -i 's/infinidb_compression_type=1/infinidb_compression_type=2/' $installdir/mysql/my.cnf >/dev/null 2>&1 - +$prefix/Calpont/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$prefix/Calpont/mysql/syscatalog_mysql.sql +$prefix/Calpont/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$prefix/Calpont/mysql/calsetuserpriority.sql +$prefix/Calpont/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$prefix/Calpont/mysql/calremoveuserpriority.sql +$prefix/Calpont/mysql/bin/mysql --defaults-file=$df --user=root $pwprompt mysql 2>/dev/null <$prefix/Calpont/mysql/calshowprocesslist.sql diff --git a/dbcon/mysql/item.cc b/dbcon/mysql/item.cc new file mode 100644 index 00000000..3884ed07 --- /dev/null +++ b/dbcon/mysql/item.cc @@ -0,0 +1,7711 @@ + /* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif +#include "mysql_priv.h" +#include +#include +#include "my_dir.h" +#include "sp_rcontext.h" +#include "sp_head.h" +#include "sql_trigger.h" +#include "sql_select.h" + +const String my_null_string("NULL", 4, default_charset_info); + +/****************************************************************************/ + +/* Hybrid_type_traits {_real} */ + +void Hybrid_type_traits::fix_length_and_dec(Item *item, Item *arg) const +{ + item->decimals= NOT_FIXED_DEC; + item->max_length= item->float_length(arg->decimals); +} + +static const Hybrid_type_traits real_traits_instance; + +const Hybrid_type_traits *Hybrid_type_traits::instance() +{ + return &real_traits_instance; +} + + +my_decimal * +Hybrid_type_traits::val_decimal(Hybrid_type *val, my_decimal *to) const +{ + double2my_decimal(E_DEC_FATAL_ERROR, val->real, val->dec_buf); + return val->dec_buf; +} + + +String * +Hybrid_type_traits::val_str(Hybrid_type *val, String *to, uint8 decimals) const +{ + to->set_real(val->real, decimals, &my_charset_bin); + return to; +} + +/* Hybrid_type_traits_decimal */ +static const Hybrid_type_traits_decimal decimal_traits_instance; + +const Hybrid_type_traits_decimal *Hybrid_type_traits_decimal::instance() +{ + return &decimal_traits_instance; +} + + +void +Hybrid_type_traits_decimal::fix_length_and_dec(Item *item, Item *arg) const +{ + item->decimals= arg->decimals; + item->max_length= min(arg->max_length + DECIMAL_LONGLONG_DIGITS, + DECIMAL_MAX_STR_LENGTH); +} + + +void Hybrid_type_traits_decimal::set_zero(Hybrid_type *val) const +{ + my_decimal_set_zero(&val->dec_buf[0]); + val->used_dec_buf_no= 0; +} + + +void Hybrid_type_traits_decimal::add(Hybrid_type *val, Field *f) const +{ + my_decimal_add(E_DEC_FATAL_ERROR, + &val->dec_buf[val->used_dec_buf_no ^ 1], + &val->dec_buf[val->used_dec_buf_no], + f->val_decimal(&val->dec_buf[2])); + val->used_dec_buf_no^= 1; +} + + +/** + @todo + what is '4' for scale? +*/ +void Hybrid_type_traits_decimal::div(Hybrid_type *val, ulonglong u) const +{ + int2my_decimal(E_DEC_FATAL_ERROR, u, TRUE, &val->dec_buf[2]); + /* XXX: what is '4' for scale? */ + my_decimal_div(E_DEC_FATAL_ERROR, + &val->dec_buf[val->used_dec_buf_no ^ 1], + &val->dec_buf[val->used_dec_buf_no], + &val->dec_buf[2], 4); + val->used_dec_buf_no^= 1; +} + + +longlong +Hybrid_type_traits_decimal::val_int(Hybrid_type *val, bool unsigned_flag) const +{ + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no], + unsigned_flag, &result); + return result; +} + + +double +Hybrid_type_traits_decimal::val_real(Hybrid_type *val) const +{ + my_decimal2double(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no], + &val->real); + return val->real; +} + + +String * +Hybrid_type_traits_decimal::val_str(Hybrid_type *val, String *to, + uint8 decimals) const +{ + my_decimal_round(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no], + decimals, FALSE, &val->dec_buf[2]); + my_decimal2string(E_DEC_FATAL_ERROR, &val->dec_buf[2], 0, 0, 0, to); + return to; +} + +/* Hybrid_type_traits_integer */ +static const Hybrid_type_traits_integer integer_traits_instance; + +const Hybrid_type_traits_integer *Hybrid_type_traits_integer::instance() +{ + return &integer_traits_instance; +} + +void +Hybrid_type_traits_integer::fix_length_and_dec(Item *item, Item *arg) const +{ + item->decimals= 0; + item->max_length= MY_INT64_NUM_DECIMAL_DIGITS; + item->unsigned_flag= 0; +} + +/***************************************************************************** +** Item functions +*****************************************************************************/ + +/** + Init all special items. +*/ + +void item_init(void) +{ + item_user_lock_init(); + uuid_short_init(); +} + + +/** + @todo + Make this functions class dependent +*/ + +bool Item::val_bool() +{ + switch(result_type()) { + case INT_RESULT: + return val_int() != 0; + case DECIMAL_RESULT: + { + my_decimal decimal_value; + my_decimal *val= val_decimal(&decimal_value); + if (val) + return !my_decimal_is_zero(val); + return 0; + } + case REAL_RESULT: + case STRING_RESULT: + return val_real() != 0.0; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + return 0; // Wrong (but safe) + } +} + + +String *Item::val_string_from_real(String *str) +{ + double nr= val_real(); + if (null_value) + return 0; /* purecov: inspected */ + str->set_real(nr,decimals, &my_charset_bin); + return str; +} + + +String *Item::val_string_from_int(String *str) +{ + longlong nr= val_int(); + if (null_value) + return 0; + str->set_int(nr, unsigned_flag, &my_charset_bin); + return str; +} + + +String *Item::val_string_from_decimal(String *str) +{ + my_decimal dec_buf, *dec= val_decimal(&dec_buf); + if (null_value) + return 0; + my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf); + my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str); + return str; +} + + +my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value) +{ + double nr= val_real(); + if (null_value) + return 0; + double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value); + return (decimal_value); +} + + +my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value) +{ + longlong nr= val_int(); + if (null_value) + return 0; + int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value); + return decimal_value; +} + + +my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value) +{ + String *res; + char *end_ptr; + if (!(res= val_str(&str_value))) + return 0; // NULL or EOM + + end_ptr= (char*) res->ptr()+ res->length(); + if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM, + res->ptr(), res->length(), res->charset(), + decimal_value) & E_DEC_BAD_NUM) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE, + ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL", + str_value.c_ptr()); + } + return decimal_value; +} + + +my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_date(<ime, TIME_FUZZY_DATE)) + { + my_decimal_set_zero(decimal_value); + null_value= 1; // set NULL, stop processing + return 0; + } + return date2my_decimal(<ime, decimal_value); +} + + +my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_time(<ime)) + { + my_decimal_set_zero(decimal_value); + return 0; + } + return date2my_decimal(<ime, decimal_value); +} + + +double Item::val_real_from_decimal() +{ + /* Note that fix_fields may not be called for Item_avg_field items */ + double result; + my_decimal value_buff, *dec_val= val_decimal(&value_buff); + if (null_value) + return 0.0; + my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result); + return result; +} + + +longlong Item::val_int_from_decimal() +{ + /* Note that fix_fields may not be called for Item_avg_field items */ + longlong result; + my_decimal value, *dec_val= val_decimal(&value); + if (null_value) + return 0; + my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result); + return result; +} + +int Item::save_time_in_field(Field *field) +{ + MYSQL_TIME ltime; + if (get_time(<ime)) + return set_field_to_null_with_conversions(field, 0); + field->set_notnull(); + return field->store_time(<ime, MYSQL_TIMESTAMP_TIME); +} + + +int Item::save_date_in_field(Field *field) +{ + MYSQL_TIME ltime; + if (get_date(<ime, TIME_FUZZY_DATE)) + return set_field_to_null_with_conversions(field, 0); + field->set_notnull(); + return field->store_time(<ime, MYSQL_TIMESTAMP_DATETIME); +} + + +/* + Store the string value in field directly + + SYNOPSIS + Item::save_str_value_in_field() + field a pointer to field where to store + result the pointer to the string value to be stored + + DESCRIPTION + The method is used by Item_*::save_in_field implementations + when we don't need to calculate the value to store + See Item_string::save_in_field() implementation for example + + IMPLEMENTATION + Check if the Item is null and stores the NULL or the + result value in the field accordingly. + + RETURN + Nonzero value if error +*/ + +int Item::save_str_value_in_field(Field *field, String *result) +{ + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + return field->store(result->ptr(), result->length(), + collation.collation); +} + + +Item::Item(): + rsize(0), name(0), orig_name(0), name_length(0), fixed(0), + is_autogenerated_name(TRUE), + collation(&my_charset_bin, DERIVATION_COERCIBLE) +{ + marker= 0; + maybe_null=null_value=with_sum_func=unsigned_flag=0; + decimals= 0; max_length= 0; + with_subselect= 0; + cmp_context= (Item_result)-1; + + /* Put item in free list so that we can free all items at end */ + THD *thd= current_thd; + next= thd->free_list; + thd->free_list= this; + /* + Item constructor can be called during execution other then SQL_COM + command => we should check thd->lex->current_select on zero (thd->lex + can be uninitialised) + */ + if (thd->lex->current_select) + { + enum_parsing_place place= + thd->lex->current_select->parsing_place; + if (place == SELECT_LIST || + place == IN_HAVING) + thd->lex->current_select->select_n_having_items++; + } +} + +/** + Constructor used by Item_field, Item_ref & aggregate (sum) + functions. + + Used for duplicating lists in processing queries with temporary + tables. +*/ +Item::Item(THD *thd, Item *item): + rsize(0), + str_value(item->str_value), + name(item->name), + orig_name(item->orig_name), + max_length(item->max_length), + name_length(item->name_length), + marker(item->marker), + decimals(item->decimals), + maybe_null(item->maybe_null), + null_value(item->null_value), + unsigned_flag(item->unsigned_flag), + with_sum_func(item->with_sum_func), + fixed(item->fixed), + is_autogenerated_name(item->is_autogenerated_name), + collation(item->collation), + with_subselect(item->with_subselect), + cmp_context(item->cmp_context) +{ + next= thd->free_list; // Put in free list + thd->free_list= this; +} + + +/** + Decimal precision of the item. + + @remark The precision must not be capped as it can be used in conjunction + with Item::decimals to determine the size of the integer part when + constructing a decimal data type. + + @see Item::decimal_int_part() + @see Item::decimals +*/ + +uint Item::decimal_precision() const +{ + uint precision= max_length; + Item_result restype= result_type(); + + if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT)) + precision= my_decimal_length_to_precision(max_length, decimals, unsigned_flag); + + return precision; +} + + +void Item::print_item_w_name(String *str, enum_query_type query_type) +{ + print(str, query_type); + + if (name) + { + THD *thd= current_thd; + str->append(STRING_WITH_LEN(" AS ")); + append_identifier(thd, str, name, (uint) strlen(name)); + } +} + + +void Item::cleanup() +{ + DBUG_ENTER("Item::cleanup"); + fixed=0; + marker= 0; + if (orig_name) + name= orig_name; + DBUG_VOID_RETURN; +} + + +/** + cleanup() item if it is 'fixed'. + + @param arg a dummy parameter, is not used here +*/ + +bool Item::cleanup_processor(uchar *arg) +{ + if (fixed) + cleanup(); + return FALSE; +} + + +/** + rename item (used for views, cleanup() return original name). + + @param new_name new name of item; +*/ + +void Item::rename(char *new_name) +{ + /* + we can compare pointers to names here, because if name was not changed, + pointer will be same + */ + if (!orig_name && new_name != name) + orig_name= name; + name= new_name; +} + + +/** + Traverse item tree possibly transforming it (replacing items). + + This function is designed to ease transformation of Item trees. + Re-execution note: every such transformation is registered for + rollback by THD::change_item_tree() and is rolled back at the end + of execution by THD::rollback_item_tree_changes(). + + Therefore: + - this function can not be used at prepared statement prepare + (in particular, in fix_fields!), as only permanent + transformation of Item trees are allowed at prepare. + - the transformer function shall allocate new Items in execution + memory root (thd->mem_root) and not anywhere else: allocated + items will be gone in the end of execution. + + If you don't need to transform an item tree, but only traverse + it, please use Item::walk() instead. + + + @param transformer functor that performs transformation of a subtree + @param arg opaque argument passed to the functor + + @return + Returns pointer to the new subtree root. THD::change_item_tree() + should be called for it if transformation took place, i.e. if a + pointer to newly allocated item is returned. +*/ + +Item* Item::transform(Item_transformer transformer, uchar *arg) +{ + DBUG_ASSERT(!current_thd->is_stmt_prepare()); + + return (this->*transformer)(arg); +} + + +Item_ident::Item_ident(Name_resolution_context *context_arg, + const char *db_name_arg,const char *table_name_arg, + const char *field_name_arg) + :orig_db_name(db_name_arg), orig_table_name(table_name_arg), + orig_field_name(field_name_arg), context(context_arg), + db_name(db_name_arg), table_name(table_name_arg), + field_name(field_name_arg), + alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX), + cached_table(0), depended_from(0) +{ + name = (char*) field_name_arg; +} + + +/** + Constructor used by Item_field & Item_*_ref (see Item comment) +*/ + +Item_ident::Item_ident(THD *thd, Item_ident *item) + :Item(thd, item), + orig_db_name(item->orig_db_name), + orig_table_name(item->orig_table_name), + orig_field_name(item->orig_field_name), + context(item->context), + db_name(item->db_name), + table_name(item->table_name), + field_name(item->field_name), + alias_name_used(item->alias_name_used), + cached_field_index(item->cached_field_index), + cached_table(item->cached_table), + depended_from(item->depended_from) +{} + +void Item_ident::cleanup() +{ + DBUG_ENTER("Item_ident::cleanup"); +#ifdef CANT_BE_USED_AS_MEMORY_IS_FREED + db_name ? db_name : "(null)", + orig_db_name ? orig_db_name : "(null)", + table_name ? table_name : "(null)", + orig_table_name ? orig_table_name : "(null)", + field_name ? field_name : "(null)", + orig_field_name ? orig_field_name : "(null)")); +#endif + Item::cleanup(); + db_name= orig_db_name; + table_name= orig_table_name; + field_name= orig_field_name; + depended_from= 0; + DBUG_VOID_RETURN; +} + +bool Item_ident::remove_dependence_processor(uchar * arg) +{ + DBUG_ENTER("Item_ident::remove_dependence_processor"); + if (depended_from == (st_select_lex *) arg) + depended_from= 0; + context= &((st_select_lex *) arg)->context; + DBUG_RETURN(0); +} + + +/** + Store the pointer to this item field into a list if not already there. + + The method is used by Item::walk to collect all unique Item_field objects + from a tree of Items into a set of items represented as a list. + + Item_cond::walk() and Item_func::walk() stop the evaluation of the + processor function for its arguments once the processor returns + true.Therefore in order to force this method being called for all item + arguments in a condition the method must return false. + + @param arg pointer to a List + + @return + FALSE to force the evaluation of collect_item_field_processor + for the subsequent items. +*/ + +bool Item_field::collect_item_field_processor(uchar *arg) +{ + DBUG_ENTER("Item_field::collect_item_field_processor"); + DBUG_PRINT("info", ("%s", field->field_name ? field->field_name : "noname")); + List *item_list= (List*) arg; + List_iterator item_list_it(*item_list); + Item_field *curr_item; + while ((curr_item= item_list_it++)) + { + if (curr_item->eq(this, 1)) + DBUG_RETURN(FALSE); /* Already in the set. */ + } + item_list->push_back(this); + DBUG_RETURN(FALSE); +} + + +/** + Check if an Item_field references some field from a list of fields. + + Check whether the Item_field represented by 'this' references any + of the fields in the keyparts passed via 'arg'. Used with the + method Item::walk() to test whether any keypart in a sequence of + keyparts is referenced in an expression. + + @param arg Field being compared, arg must be of type Field + + @retval + TRUE if 'this' references the field 'arg' + @retval + FALSE otherwise +*/ + +bool Item_field::find_item_in_field_list_processor(uchar *arg) +{ + KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg); + KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1); + KEY_PART_INFO *cur_part; + + for (cur_part= first_non_group_part; cur_part != last_part; cur_part++) + { + if (field->eq(cur_part->field)) + return TRUE; + } + return FALSE; +} + + +/* + Mark field in read_map + + NOTES + This is used by filesort to register used fields in a a temporary + column read set or to register used fields in a view +*/ + +bool Item_field::register_field_in_read_map(uchar *arg) +{ + TABLE *table= (TABLE *) arg; + if (field->table == table || !table) + bitmap_set_bit(field->table->read_set, field->field_index); + return 0; +} + + +bool Item::check_cols(uint c) +{ + if (c != 1) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), c); + return 1; + } + return 0; +} + + +void Item::set_name(const char *str, uint length, CHARSET_INFO *cs) +{ + if (!length) + { + /* Empty string, used by AS or internal function like last_insert_id() */ + name= (char*) str; + name_length= 0; + return; + } + if (cs->ctype) + { + uint orig_len= length; + /* + This will probably need a better implementation in the future: + a function in CHARSET_INFO structure. + */ + while (length && !my_isgraph(cs,*str)) + { // Fix problem with yacc + length--; + str++; + } + if (orig_len != length && !is_autogenerated_name) + { + if (length == 0) + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY), + str + length - orig_len); + else + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES), + str + length - orig_len); + } + } + if (!my_charset_same(cs, system_charset_info)) + { + size_t res_length; + name= sql_strmake_with_convert(str, name_length= length, cs, + MAX_ALIAS_NAME, system_charset_info, + &res_length); + } + else + name= sql_strmake(str, (name_length= min(length,MAX_ALIAS_NAME))); +} + + +/** + @details + This function is called when: + - Comparing items in the WHERE clause (when doing where optimization) + - When trying to find an ORDER BY/GROUP BY item in the SELECT part +*/ + +bool Item::eq(const Item *item, bool binary_cmp) const +{ + /* + Note, that this is never TRUE if item is a Item_param: + for all basic constants we have special checks, and Item_param's + type() can be only among basic constant types. + */ + return type() == item->type() && name && item->name && + !my_strcasecmp(system_charset_info,name,item->name); +} + + +Item *Item::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1); + return conv->safe ? conv : NULL; +} + + +/** + @details + Created mostly for mysql_prepare_table(). Important + when a string ENUM/SET column is described with a numeric default value: + + CREATE TABLE t1(a SET('a') DEFAULT 1); + + We cannot use generic Item::safe_charset_converter(), because + the latter returns a non-fixed Item, so val_str() crashes afterwards. + Override Item_num method, to return a fixed item. +*/ +Item *Item_num::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_string *conv; + char buf[64]; + String *s, tmp(buf, sizeof(buf), &my_charset_bin); + s= val_str(&tmp); + if ((conv= new Item_string(s->ptr(), s->length(), s->charset()))) + { + conv->str_value.copy(); + conv->str_value.mark_as_const(); + } + return conv; +} + + +Item *Item_static_float_func::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_string *conv; + char buf[64]; + String *s, tmp(buf, sizeof(buf), &my_charset_bin); + s= val_str(&tmp); + if ((conv= new Item_static_string_func(func_name, s->ptr(), s->length(), + s->charset()))) + { + conv->str_value.copy(); + conv->str_value.mark_as_const(); + } + return conv; +} + + +Item *Item_string::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_string *conv; + uint conv_errors; + char *ptr; + String tmp, cstr, *ostr= val_str(&tmp); + cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors); + if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(), + cstr.charset(), + collation.derivation))) + { + /* + Safe conversion is not possible (or EOM). + We could not convert a string into the requested character set + without data loss. The target charset does not cover all the + characters from the string. Operation cannot be done correctly. + */ + return NULL; + } + if (!(ptr= current_thd->strmake(cstr.ptr(), cstr.length()))) + return NULL; + conv->str_value.set(ptr, cstr.length(), cstr.charset()); + /* Ensure that no one is going to change the result string */ + conv->str_value.mark_as_const(); + return conv; +} + + +Item *Item_param::safe_charset_converter(CHARSET_INFO *tocs) +{ + if (const_item()) + { + uint cnv_errors; + String *ostr= val_str(&cnvstr); + cnvitem->str_value.copy(ostr->ptr(), ostr->length(), + ostr->charset(), tocs, &cnv_errors); + if (cnv_errors) + return NULL; + cnvitem->str_value.mark_as_const(); + cnvitem->max_length= cnvitem->str_value.numchars() * tocs->mbmaxlen; + return cnvitem; + } + return NULL; +} + + +Item *Item_static_string_func::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_string *conv; + uint conv_errors; + String tmp, cstr, *ostr= val_str(&tmp); + cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors); + if (conv_errors || + !(conv= new Item_static_string_func(func_name, + cstr.ptr(), cstr.length(), + cstr.charset(), + collation.derivation))) + { + /* + Safe conversion is not possible (or EOM). + We could not convert a string into the requested character set + without data loss. The target charset does not cover all the + characters from the string. Operation cannot be done correctly. + */ + return NULL; + } + conv->str_value.copy(); + /* Ensure that no one is going to change the result string */ + conv->str_value.mark_as_const(); + return conv; +} + + +bool Item_string::eq(const Item *item, bool binary_cmp) const +{ + if (type() == item->type() && item->basic_const_item()) + { + if (binary_cmp) + return !stringcmp(&str_value, &item->str_value); + return (collation.collation == item->collation.collation && + !sortcmp(&str_value, &item->str_value, collation.collation)); + } + return 0; +} + + +/** + Get the value of the function as a MYSQL_TIME structure. + As a extra convenience the time structure is reset on error! +*/ + +bool Item::get_date(MYSQL_TIME *ltime,uint fuzzydate) +{ + if (result_type() == STRING_RESULT) + { + char buff[40]; + String tmp(buff,sizeof(buff), &my_charset_bin),*res; + if (!(res=val_str(&tmp)) || + str_to_datetime_with_warn(res->ptr(), res->length(), + ltime, fuzzydate) <= MYSQL_TIMESTAMP_ERROR) + goto err; + } + else + { + longlong value= val_int(); + int was_cut; + if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == LL(-1)) + { + char buff[22], *end; + end= longlong10_to_str(value, buff, -10); + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + buff, (int) (end-buff), MYSQL_TIMESTAMP_NONE, + NullS); + goto err; + } + } + return 0; + +err: + bzero((char*) ltime,sizeof(*ltime)); + return 1; +} + +/** + Get time of first argument.\ + + As a extra convenience the time structure is reset on error! +*/ + +bool Item::get_time(MYSQL_TIME *ltime) +{ + char buff[40]; + String tmp(buff,sizeof(buff),&my_charset_bin),*res; + if (!(res=val_str(&tmp)) || + str_to_time_with_warn(res->ptr(), res->length(), ltime)) + { + bzero((char*) ltime,sizeof(*ltime)); + return 1; + } + return 0; +} + +CHARSET_INFO *Item::default_charset() +{ + return current_thd->variables.collation_connection; +} + + +/* + Save value in field, but don't give any warnings + + NOTES + This is used to temporary store and retrieve a value in a column, + for example in opt_range to adjust the key value to fit the column. +*/ + +int Item::save_in_field_no_warnings(Field *field, bool no_conversions) +{ + int res; + TABLE *table= field->table; + THD *thd= table->in_use; + enum_check_fields tmp= thd->count_cuted_fields; + my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set); + ulong sql_mode= thd->variables.sql_mode; + thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE); + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + res= save_in_field(field, no_conversions); + thd->count_cuted_fields= tmp; + dbug_tmp_restore_column_map(table->write_set, old_map); + thd->variables.sql_mode= sql_mode; + return res; +} + + +/***************************************************************************** + Item_sp_variable methods +*****************************************************************************/ + +Item_sp_variable::Item_sp_variable(char *sp_var_name_str, + uint sp_var_name_length) + :m_thd(0) +#ifndef DBUG_OFF + , m_sp(0) +#endif +{ + m_name.str= sp_var_name_str; + m_name.length= sp_var_name_length; +} + + +bool Item_sp_variable::fix_fields(THD *thd, Item **) +{ + Item *it; + + m_thd= thd; /* NOTE: this must be set before any this_xxx() */ + it= this_item(); + + DBUG_ASSERT(it->fixed); + + max_length= it->max_length; + decimals= it->decimals; + unsigned_flag= it->unsigned_flag; + fixed= 1; + collation.set(it->collation.collation, it->collation.derivation); + + return FALSE; +} + + +double Item_sp_variable::val_real() +{ + DBUG_ASSERT(fixed); + Item *it= this_item(); + double ret= it->val_real(); + null_value= it->null_value; + return ret; +} + + +longlong Item_sp_variable::val_int() +{ + DBUG_ASSERT(fixed); + Item *it= this_item(); + longlong ret= it->val_int(); + null_value= it->null_value; + return ret; +} + + +String *Item_sp_variable::val_str(String *sp) +{ + DBUG_ASSERT(fixed); + Item *it= this_item(); + String *res= it->val_str(sp); + + null_value= it->null_value; + + if (!res) + return NULL; + + /* + This way we mark returned value of val_str as const, + so that various functions (e.g. CONCAT) won't try to + modify the value of the Item. Analogous mechanism is + implemented for Item_param. + Without this trick Item_splocal could be changed as a + side-effect of expression computation. Here is an example + of what happens without it: suppose x is varchar local + variable in a SP with initial value 'ab' Then + select concat(x,'c'); + would change x's value to 'abc', as Item_func_concat::val_str() + would use x's internal buffer to compute the result. + This is intended behaviour of Item_func_concat. Comments to + Item_param class contain some more details on the topic. + */ + + if (res != &str_value) + str_value.set(res->ptr(), res->length(), res->charset()); + else + res->mark_as_const(); + + return &str_value; +} + + +my_decimal *Item_sp_variable::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed); + Item *it= this_item(); + my_decimal *val= it->val_decimal(decimal_value); + null_value= it->null_value; + return val; +} + + +bool Item_sp_variable::is_null() +{ + return this_item()->is_null(); +} + + +/***************************************************************************** + Item_splocal methods +*****************************************************************************/ + +Item_splocal::Item_splocal(const LEX_STRING &sp_var_name, + uint sp_var_idx, + enum_field_types sp_var_type, + uint pos_in_q, uint len_in_q) + :Item_sp_variable(sp_var_name.str, sp_var_name.length), + m_var_idx(sp_var_idx), pos_in_query(pos_in_q), len_in_query(len_in_q) +{ + maybe_null= TRUE; + + m_type= sp_map_item_type(sp_var_type); + m_field_type= sp_var_type; + m_result_type= sp_map_result_type(sp_var_type); +} + + +Item * +Item_splocal::this_item() +{ + DBUG_ASSERT(m_sp == m_thd->spcont->sp); + + return m_thd->spcont->get_item(m_var_idx); +} + +const Item * +Item_splocal::this_item() const +{ + DBUG_ASSERT(m_sp == m_thd->spcont->sp); + + return m_thd->spcont->get_item(m_var_idx); +} + + +Item ** +Item_splocal::this_item_addr(THD *thd, Item **) +{ + DBUG_ASSERT(m_sp == thd->spcont->sp); + + return thd->spcont->get_item_addr(m_var_idx); +} + + +void Item_splocal::print(String *str, enum_query_type) +{ + str->reserve(m_name.length+8); + str->append(m_name.str, m_name.length); + str->append('@'); + str->qs_append(m_var_idx); +} + + +bool Item_splocal::set_value(THD *thd, sp_rcontext *ctx, Item **it) +{ + return ctx->set_variable(thd, get_var_idx(), it); +} + + +/***************************************************************************** + Item_case_expr methods +*****************************************************************************/ + +Item_case_expr::Item_case_expr(uint case_expr_id) + :Item_sp_variable( C_STRING_WITH_LEN("case_expr")), + m_case_expr_id(case_expr_id) +{ +} + + +Item * +Item_case_expr::this_item() +{ + DBUG_ASSERT(m_sp == m_thd->spcont->sp); + + return m_thd->spcont->get_case_expr(m_case_expr_id); +} + + + +const Item * +Item_case_expr::this_item() const +{ + DBUG_ASSERT(m_sp == m_thd->spcont->sp); + + return m_thd->spcont->get_case_expr(m_case_expr_id); +} + + +Item ** +Item_case_expr::this_item_addr(THD *thd, Item **) +{ + DBUG_ASSERT(m_sp == thd->spcont->sp); + + return thd->spcont->get_case_expr_addr(m_case_expr_id); +} + + +void Item_case_expr::print(String *str, enum_query_type) +{ + if (str->reserve(MAX_INT_WIDTH + sizeof("case_expr@"))) + return; /* purecov: inspected */ + VOID(str->append(STRING_WITH_LEN("case_expr@"))); + str->qs_append(m_case_expr_id); +} + + +/***************************************************************************** + Item_name_const methods +*****************************************************************************/ + +double Item_name_const::val_real() +{ + DBUG_ASSERT(fixed); + double ret= value_item->val_real(); + null_value= value_item->null_value; + return ret; +} + + +longlong Item_name_const::val_int() +{ + DBUG_ASSERT(fixed); + longlong ret= value_item->val_int(); + null_value= value_item->null_value; + return ret; +} + + +String *Item_name_const::val_str(String *sp) +{ + DBUG_ASSERT(fixed); + String *ret= value_item->val_str(sp); + null_value= value_item->null_value; + return ret; +} + + +my_decimal *Item_name_const::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed); + my_decimal *val= value_item->val_decimal(decimal_value); + null_value= value_item->null_value; + return val; +} + + +bool Item_name_const::is_null() +{ + return value_item->is_null(); +} + + +Item_name_const::Item_name_const(Item *name_arg, Item *val): + value_item(val), name_item(name_arg) +{ + if (!(valid_args= name_item->basic_const_item() && + (value_item->basic_const_item() || + ((value_item->type() == FUNC_ITEM) && + ((((Item_func *) value_item)->functype() == + Item_func::COLLATE_FUNC) || + ((((Item_func *) value_item)->functype() == + Item_func::NEG_FUNC) && + (((Item_func *) value_item)->key_item()->type() != + FUNC_ITEM))))))) + my_error(ER_WRONG_ARGUMENTS, MYF(0), "NAME_CONST"); + Item::maybe_null= TRUE; +} + + +Item::Type Item_name_const::type() const +{ + /* + As + 1. one can try to create the Item_name_const passing non-constant + arguments, although it's incorrect and + 2. the type() method can be called before the fix_fields() to get + type information for a further type cast, e.g. + if (item->type() == FIELD_ITEM) + ((Item_field *) item)->... + we return NULL_ITEM in the case to avoid wrong casting. + + valid_args guarantees value_item->basic_const_item(); if type is + FUNC_ITEM, then we have a fudged item_func_neg() on our hands + and return the underlying type. + For Item_func_set_collation() + e.g. NAME_CONST('name', 'value' COLLATE collation) we return its + 'value' argument type. + */ + if (!valid_args) + return NULL_ITEM; + Item::Type value_type= value_item->type(); + if (value_type == FUNC_ITEM) + { + /* + The second argument of NAME_CONST('name', 'value') must be + a simple constant item or a NEG_FUNC/COLLATE_FUNC. + */ + DBUG_ASSERT(((Item_func *) value_item)->functype() == + Item_func::NEG_FUNC || + ((Item_func *) value_item)->functype() == + Item_func::COLLATE_FUNC); + return ((Item_func *) value_item)->key_item()->type(); + } + return value_type; +} + + +bool Item_name_const::fix_fields(THD *thd, Item **ref) +{ + char buf[128]; + String *item_name; + String s(buf, sizeof(buf), &my_charset_bin); + s.length(0); + + if (value_item->fix_fields(thd, &value_item) || + name_item->fix_fields(thd, &name_item) || + !value_item->const_item() || + !name_item->const_item() || + !(item_name= name_item->val_str(&s))) // Can't have a NULL name + { + my_error(ER_RESERVED_SYNTAX, MYF(0), "NAME_CONST"); + return TRUE; + } + if (is_autogenerated_name) + { + set_name(item_name->ptr(), (uint) item_name->length(), system_charset_info); + } + collation.set(value_item->collation.collation, DERIVATION_IMPLICIT); + max_length= value_item->max_length; + decimals= value_item->decimals; + fixed= 1; + return FALSE; +} + + +void Item_name_const::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("NAME_CONST(")); + name_item->print(str, query_type); + str->append(','); + value_item->print(str, query_type); + str->append(')'); +} + + +/* + need a special class to adjust printing : references to aggregate functions + must not be printed as refs because the aggregate functions that are added to + the front of select list are not printed as well. +*/ +class Item_aggregate_ref : public Item_ref +{ +public: + Item_aggregate_ref(Name_resolution_context *context_arg, Item **item, + const char *table_name_arg, const char *field_name_arg) + :Item_ref(context_arg, item, table_name_arg, field_name_arg) {} + + virtual inline void print (String *str, enum_query_type query_type) + { + if (ref) + (*ref)->print(str, query_type); + else + Item_ident::print(str, query_type); + } + virtual Ref_Type ref_type() { return AGGREGATE_REF; } +}; + + +/** + Move SUM items out from item tree and replace with reference. + + @param thd Thread handler + @param ref_pointer_array Pointer to array of reference fields + @param fields All fields in select + @param ref Pointer to item + @param skip_registered <=> function be must skipped for registered + SUM items + + @note + This is from split_sum_func2() for items that should be split + + All found SUM items are added FIRST in the fields list and + we replace the item with a reference. + + thd->fatal_error() may be called if we are out of memory +*/ + +void Item::split_sum_func2(THD *thd, Item **ref_pointer_array, + List &fields, Item **ref, + bool skip_registered) +{ + /* An item of type Item_sum is registered <=> ref_by != 0 */ + if (type() == SUM_FUNC_ITEM && skip_registered && + ((Item_sum *) this)->ref_by) + return; + if ((type() != SUM_FUNC_ITEM && with_sum_func) || + (type() == FUNC_ITEM && + (((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC || + ((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC))) + { + /* Will split complicated items and ignore simple ones */ + split_sum_func(thd, ref_pointer_array, fields); + } + else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) && + type() != SUBSELECT_ITEM && + (type() != REF_ITEM || + ((Item_ref*)this)->ref_type() == Item_ref::VIEW_REF)) + { + /* + Replace item with a reference so that we can easily calculate + it (in case of sum functions) or copy it (in case of fields) + + The test above is to ensure we don't do a reference for things + that are constants (PARAM_TABLE_BIT is in effect a constant) + or already referenced (for example an item in HAVING) + Exception is Item_direct_view_ref which we need to convert to + Item_ref to allow fields from view being stored in tmp table. + */ + Item_aggregate_ref *item_ref; + uint el= fields.elements; + Item *real_itm= real_item(); + + ref_pointer_array[el]= real_itm; + if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context, + ref_pointer_array + el, 0, name))) + return; // fatal_error is set + if (type() == SUM_FUNC_ITEM) + item_ref->depended_from= ((Item_sum *) this)->depended_from(); + fields.push_front(real_itm); + thd->change_item_tree(ref, item_ref); + } +} + + +static bool +left_is_superset(DTCollation *left, DTCollation *right) +{ + /* Allow convert to Unicode */ + if (left->collation->state & MY_CS_UNICODE && + (left->derivation < right->derivation || + (left->derivation == right->derivation && + !(right->collation->state & MY_CS_UNICODE)))) + return TRUE; + /* Allow convert from ASCII */ + if (right->repertoire == MY_REPERTOIRE_ASCII && + (left->derivation < right->derivation || + (left->derivation == right->derivation && + !(left->repertoire == MY_REPERTOIRE_ASCII)))) + return TRUE; + /* Disallow conversion otherwise */ + return FALSE; +} + +/** + Aggregate two collations together taking + into account their coercibility (aka derivation):. + + 0 == DERIVATION_EXPLICIT - an explicitly written COLLATE clause @n + 1 == DERIVATION_NONE - a mix of two different collations @n + 2 == DERIVATION_IMPLICIT - a column @n + 3 == DERIVATION_COERCIBLE - a string constant. + + The most important rules are: + -# If collations are the same: + chose this collation, and the strongest derivation. + -# If collations are different: + - Character sets may differ, but only if conversion without + data loss is possible. The caller provides flags whether + character set conversion attempts should be done. If no + flags are substituted, then the character sets must be the same. + Currently processed flags are: + MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset + MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value + - two EXPLICIT collations produce an error, e.g. this is wrong: + CONCAT(expr1 collate latin1_swedish_ci, expr2 collate latin1_german_ci) + - the side with smaller derivation value wins, + i.e. a column is stronger than a string constant, + an explicit COLLATE clause is stronger than a column. + - if derivations are the same, we have DERIVATION_NONE, + we'll wait for an explicit COLLATE clause which possibly can + come from another argument later: for example, this is valid, + but we don't know yet when collecting the first two arguments: + @code + CONCAT(latin1_swedish_ci_column, + latin1_german1_ci_column, + expr COLLATE latin1_german2_ci) + @endcode +*/ + +bool DTCollation::aggregate(DTCollation &dt, uint flags) +{ + if (!my_charset_same(collation, dt.collation)) + { + /* + We do allow to use binary strings (like BLOBS) + together with character strings. + Binaries have more precedence than a character + string of the same derivation. + */ + if (collation == &my_charset_bin) + { + //if (derivation <= dt.derivation) + // ; // Do nothing + // @InfiniDB @bug5426 + if (derivation <= dt.derivation) + { + if (collation->mbmaxlen < dt.collation->mbmaxlen) + set(dt); + } + else + { + set(dt); + } + } + else if (dt.collation == &my_charset_bin) + { + if (dt.derivation <= derivation) + { + set(dt); + } + } + else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) && + left_is_superset(this, &dt)) + { + // Do nothing + } + else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) && + left_is_superset(&dt, this)) + { + set(dt); + } + else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) && + derivation < dt.derivation && + dt.derivation >= DERIVATION_SYSCONST) + { + // Do nothing; + } + else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) && + dt.derivation < derivation && + derivation >= DERIVATION_SYSCONST) + { + set(dt); + } + else + { + // Cannot apply conversion + set(&my_charset_bin, DERIVATION_NONE, + (dt.repertoire|repertoire)); + return 1; + } + } + else if (derivation < dt.derivation) + { + // Do nothing + } + else if (dt.derivation < derivation) + { + set(dt); + } + else + { + if (collation == dt.collation) + { + // Do nothing + } + else + { + if (derivation == DERIVATION_EXPLICIT) + { + set(0, DERIVATION_NONE, 0); + return 1; + } + if (collation->state & MY_CS_BINSORT) + return 0; + if (dt.collation->state & MY_CS_BINSORT) + { + set(dt); + return 0; + } + CHARSET_INFO *bin= get_charset_by_csname(collation->csname, + MY_CS_BINSORT,MYF(0)); + set(bin, DERIVATION_NONE); + } + } + repertoire|= dt.repertoire; + return 0; +} + +/******************************/ +static +void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname) +{ + my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0), + c1.collation->name,c1.derivation_name(), + c2.collation->name,c2.derivation_name(), + fname); +} + + +static +void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3, + const char *fname) +{ + my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0), + c1.collation->name,c1.derivation_name(), + c2.collation->name,c2.derivation_name(), + c3.collation->name,c3.derivation_name(), + fname); +} + + +static +void my_coll_agg_error(Item** args, uint count, const char *fname, + int item_sep) +{ + if (count == 2) + my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname); + else if (count == 3) + my_coll_agg_error(args[0]->collation, args[item_sep]->collation, + args[2*item_sep]->collation, fname); + else + my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname); +} + + +bool agg_item_collations(DTCollation &c, const char *fname, + Item **av, uint count, uint flags, int item_sep) +{ + uint i; + Item **arg; + bool unknown_cs= 0; + + c.set(av[0]->collation); + for (i= 1, arg= &av[item_sep]; i < count; i++, arg++) + { + if (c.aggregate((*arg)->collation, flags)) + { + if (c.derivation == DERIVATION_NONE && + c.collation == &my_charset_bin) + { + unknown_cs= 1; + continue; + } + my_coll_agg_error(av, count, fname, item_sep); + return TRUE; + } + } + + if (unknown_cs && + c.derivation != DERIVATION_EXPLICIT) + { + my_coll_agg_error(av, count, fname, item_sep); + return TRUE; + } + + if ((flags & MY_COLL_DISALLOW_NONE) && + c.derivation == DERIVATION_NONE) + { + my_coll_agg_error(av, count, fname, item_sep); + return TRUE; + } + return FALSE; +} + + +bool agg_item_collations_for_comparison(DTCollation &c, const char *fname, + Item **av, uint count, uint flags) +{ + return (agg_item_collations(c, fname, av, count, + flags | MY_COLL_DISALLOW_NONE, 1)); +} + + +bool agg_item_set_converter(DTCollation &coll, const char *fname, + Item **args, uint nargs, uint flags, int item_sep) +{ + Item **arg, *safe_args[2]= {NULL, NULL}; + + /* + For better error reporting: save the first and the second argument. + We need this only if the the number of args is 3 or 2: + - for a longer argument list, "Illegal mix of collations" + doesn't display each argument's characteristics. + - if nargs is 1, then this error cannot happen. + */ + if (nargs >=2 && nargs <= 3) + { + safe_args[0]= args[0]; + safe_args[1]= args[item_sep]; + } + + THD *thd= current_thd; + Query_arena *arena, backup; + bool res= FALSE; + uint i; + /* + In case we're in statement prepare, create conversion item + in its memory: it will be reused on each execute. + */ + arena= thd->is_stmt_prepare() ? thd->activate_stmt_arena_if_needed(&backup) + : NULL; + + for (i= 0, arg= args; i < nargs; i++, arg+= item_sep) + { + Item* conv; + uint32 dummy_offset; + if (!String::needs_conversion(0, (*arg)->collation.collation, + coll.collation, + &dummy_offset)) + continue; + + if (!(conv= (*arg)->safe_charset_converter(coll.collation)) && + ((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII)) + conv= new Item_func_conv_charset(*arg, coll.collation, 1); + + if (!conv) + { + if (nargs >=2 && nargs <= 3) + { + /* restore the original arguments for better error message */ + args[0]= safe_args[0]; + args[item_sep]= safe_args[1]; + } + my_coll_agg_error(args, nargs, fname, item_sep); + res= TRUE; + break; // we cannot return here, we need to restore "arena". + } + if ((*arg)->type() == Item::FIELD_ITEM) + ((Item_field *)(*arg))->no_const_subst= 1; + /* + If in statement prepare, then we create a converter for two + constant items, do it once and then reuse it. + If we're in execution of a prepared statement, arena is NULL, + and the conv was created in runtime memory. This can be + the case only if the argument is a parameter marker ('?'), + because for all true constants the charset converter has already + been created in prepare. In this case register the change for + rollback. + */ + if (thd->is_stmt_prepare()) + *arg= conv; + else + thd->change_item_tree(arg, conv); + /* + We do not check conv->fixed, because Item_func_conv_charset which can + be return by safe_charset_converter can't be fixed at creation + */ + conv->fix_fields(thd, arg); + } + if (arena) + thd->restore_active_arena(arena, &backup); + return res; +} + + +/* + Collect arguments' character sets together. + We allow to apply automatic character set conversion in some cases. + The conditions when conversion is possible are: + - arguments A and B have different charsets + - A wins according to coercibility rules + (i.e. a column is stronger than a string constant, + an explicit COLLATE clause is stronger than a column) + - character set of A is either superset for character set of B, + or B is a string constant which can be converted into the + character set of A without data loss. + + If all of the above is true, then it's possible to convert + B into the character set of A, and then compare according + to the collation of A. + + For functions with more than two arguments: + + collect(A,B,C) ::= collect(collect(A,B),C) + + Since this function calls THD::change_item_tree() on the passed Item ** + pointers, it is necessary to pass the original Item **'s, not copies. + Otherwise their values will not be properly restored (see BUG#20769). + If the items are not consecutive (eg. args[2] and args[5]), use the + item_sep argument, ie. + + agg_item_charsets(coll, fname, &args[2], 2, flags, 3) + +*/ + +bool agg_item_charsets(DTCollation &coll, const char *fname, + Item **args, uint nargs, uint flags, int item_sep) +{ + if (agg_item_collations(coll, fname, args, nargs, flags, item_sep)) + return TRUE; + + return agg_item_set_converter(coll, fname, args, nargs, flags, item_sep); +} + + +void Item_ident_for_show::make_field(Send_field *tmp_field) +{ + tmp_field->table_name= tmp_field->org_table_name= table_name; + tmp_field->db_name= db_name; + tmp_field->col_name= tmp_field->org_col_name= field->field_name; + tmp_field->charsetnr= field->charset()->number; + tmp_field->length=field->field_length; + tmp_field->type=field->type(); + tmp_field->flags= field->table->maybe_null ? + (field->flags & ~NOT_NULL_FLAG) : field->flags; + tmp_field->decimals= field->decimals(); +} + +/**********************************************/ + +Item_field::Item_field(Field *f) + :Item_ident(0, NullS, *f->table_name, f->field_name), + item_equal(0), no_const_subst(0), + have_privileges(0), any_privileges(0) +{ + set_field(f); + /* + field_name and table_name should not point to garbage + if this item is to be reused + */ + orig_table_name= orig_field_name= ""; +} + + +/** + Constructor used inside setup_wild(). + + Ensures that field, table, and database names will live as long as + Item_field (this is important in prepared statements). +*/ + +Item_field::Item_field(THD *thd, Name_resolution_context *context_arg, + Field *f) + :Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name), + item_equal(0), no_const_subst(0), + have_privileges(0), any_privileges(0) +{ + /* + We always need to provide Item_field with a fully qualified field + name to avoid ambiguity when executing prepared statements like + SELECT * from d1.t1, d2.t1; (assuming d1.t1 and d2.t1 have columns + with same names). + This is because prepared statements never deal with wildcards in + select list ('*') and always fix fields using fully specified path + (i.e. db.table.column). + No check for OOM: if db_name is NULL, we'll just get + "Field not found" error. + We need to copy db_name, table_name and field_name because they must + be allocated in the statement memory, not in table memory (the table + structure can go away and pop up again between subsequent executions + of a prepared statement or after the close_tables_for_reopen() call + in mysql_multi_update_prepare() or due to wildcard expansion in stored + procedures). + */ + { + if (db_name) + orig_db_name= thd->strdup(db_name); + if (table_name) + orig_table_name= thd->strdup(table_name); + if (field_name) + orig_field_name= thd->strdup(field_name); + /* + We don't restore 'name' in cleanup because it's not changed + during execution. Still we need it to point to persistent + memory if this item is to be reused. + */ + name= (char*) orig_field_name; + } + set_field(f); +} + + +Item_field::Item_field(Name_resolution_context *context_arg, + const char *db_arg,const char *table_name_arg, + const char *field_name_arg) + :Item_ident(context_arg, db_arg,table_name_arg,field_name_arg), + field(0), result_field(0), item_equal(0), no_const_subst(0), + have_privileges(0), any_privileges(0) +{ + SELECT_LEX *select= current_thd->lex->current_select; + collation.set(DERIVATION_IMPLICIT); + if (select && select->parsing_place != IN_HAVING) + select->select_n_where_fields++; +} + +/** + Constructor need to process subselect with temporary tables (see Item) +*/ + +Item_field::Item_field(THD *thd, Item_field *item) + :Item_ident(thd, item), + field(item->field), + result_field(item->result_field), + item_equal(item->item_equal), + no_const_subst(item->no_const_subst), + have_privileges(item->have_privileges), + any_privileges(item->any_privileges) +{ + collation.set(DERIVATION_IMPLICIT); +} + +void Item_field::set_field(Field *field_par) +{ + field=result_field=field_par; // for easy coding with fields + maybe_null=field->maybe_null(); + decimals= field->decimals(); + max_length= field_par->max_display_length(); + table_name= *field_par->table_name; + field_name= field_par->field_name; + db_name= field_par->table->s->db.str; + alias_name_used= field_par->table->alias_name_used; + unsigned_flag=test(field_par->flags & UNSIGNED_FLAG); + collation.set(field_par->charset(), field_par->derivation()); + fixed= 1; + if (field->table->s->tmp_table == SYSTEM_TMP_TABLE) + any_privileges= 0; +} + + +/** + Reset this item to point to a field from the new temporary table. + This is used when we create a new temporary table for each execution + of prepared statement. +*/ + +void Item_field::reset_field(Field *f) +{ + set_field(f); + /* 'name' is pointing at field->field_name of old field */ + name= (char*) f->field_name; +} + +const char *Item_ident::full_name() const +{ + char *tmp; + if (!table_name || !field_name) + return field_name ? field_name : name ? name : "tmp_field"; + if (db_name && db_name[0]) + { + tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+ + (uint) strlen(field_name)+3); + strxmov(tmp,db_name,".",table_name,".",field_name,NullS); + } + else + { + if (table_name[0]) + { + tmp= (char*) sql_alloc((uint) strlen(table_name) + + (uint) strlen(field_name) + 2); + strxmov(tmp, table_name, ".", field_name, NullS); + } + else + tmp= (char*) field_name; + } + return tmp; +} + +void Item_ident::print(String *str, enum_query_type query_type) +{ + THD *thd= current_thd; + char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME]; + const char *d_name= db_name, *t_name= table_name; + + // @infiniDB + if (query_type == QT_INFINIDB || query_type == QT_INFINIDB_NO_QUOTE || query_type == QT_INFINIDB_DERIVED) + { + if (query_type != QT_INFINIDB_NO_QUOTE && query_type != QT_INFINIDB_DERIVED) + str->append('`'); + + // print referencing view name for IDB post process + if (cached_table) + { + if (cached_table->db && strlen(cached_table->db) > 0) + { + str->append(cached_table->db, (uint) strlen(cached_table->db)); + str->append('.'); + } + // IDB: table referenced by view is represented by "viewAlias_tableAlias" + if (cached_table->referencing_view && query_type != QT_INFINIDB_DERIVED) + { + str->append(cached_table->referencing_view->alias, (uint)strlen(cached_table->referencing_view->alias)); + str->append("_"); + } + str->append(cached_table->alias, (uint)strlen(cached_table->alias)); + str->append('.'); + } + else + { + if (d_name && strlen(d_name) > 0) + { + str->append(d_name, (uint) strlen(d_name)); + str->append('.'); + } + if (t_name && strlen(t_name) > 0) + { + str->append(t_name, (uint) strlen(t_name)); + str->append('.'); + } + } + str->append(field_name, (uint) strlen(field_name)); + if (query_type != QT_INFINIDB_NO_QUOTE && query_type != QT_INFINIDB_DERIVED) + str->append('`'); + return; + } + + if (lower_case_table_names== 1 || + (lower_case_table_names == 2 && !alias_name_used)) + { + if (table_name && table_name[0]) + { + strmov(t_name_buff, table_name); + my_casedn_str(files_charset_info, t_name_buff); + t_name= t_name_buff; + } + if (db_name && db_name[0]) + { + strmov(d_name_buff, db_name); + my_casedn_str(files_charset_info, d_name_buff); + d_name= d_name_buff; + } + } + + if (!table_name || !field_name || !field_name[0]) + { + const char *nm= (field_name && field_name[0]) ? + field_name : name ? name : "tmp_field"; + append_identifier(thd, str, nm, (uint) strlen(nm)); + return; + } + if (db_name && db_name[0] && !alias_name_used) + { + if (!(cached_table && cached_table->belong_to_view && + cached_table->belong_to_view->compact_view_format)) + { + append_identifier(thd, str, d_name, (uint)strlen(d_name)); + str->append('.'); + } + append_identifier(thd, str, t_name, (uint)strlen(t_name)); + str->append('.'); + append_identifier(thd, str, field_name, (uint)strlen(field_name)); + } + else + { + if (table_name[0]) + { + append_identifier(thd, str, t_name, (uint) strlen(t_name)); + str->append('.'); + append_identifier(thd, str, field_name, (uint) strlen(field_name)); + } + else + append_identifier(thd, str, field_name, (uint) strlen(field_name)); + } +} + +/* ARGSUSED */ +String *Item_field::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + if ((null_value=field->is_null())) + return 0; + str->set_charset(str_value.charset()); + return field->val_str(str,&str_value); +} + + +double Item_field::val_real() +{ + DBUG_ASSERT(fixed == 1); + if ((null_value=field->is_null())) + return 0.0; + return field->val_real(); +} + + +longlong Item_field::val_int() +{ + DBUG_ASSERT(fixed == 1); + if ((null_value=field->is_null())) + return 0; + return field->val_int(); +} + + +my_decimal *Item_field::val_decimal(my_decimal *decimal_value) +{ + if ((null_value= field->is_null())) + return 0; + return field->val_decimal(decimal_value); +} + + +String *Item_field::str_result(String *str) +{ + if ((null_value=result_field->is_null())) + return 0; + str->set_charset(str_value.charset()); + return result_field->val_str(str,&str_value); +} + +bool Item_field::get_date(MYSQL_TIME *ltime,uint fuzzydate) +{ + if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate)) + { + bzero((char*) ltime,sizeof(*ltime)); + return 1; + } + return 0; +} + +bool Item_field::get_date_result(MYSQL_TIME *ltime,uint fuzzydate) +{ + if ((null_value=result_field->is_null()) || + result_field->get_date(ltime,fuzzydate)) + { + bzero((char*) ltime,sizeof(*ltime)); + return 1; + } + return 0; +} + +bool Item_field::get_time(MYSQL_TIME *ltime) +{ + if ((null_value=field->is_null()) || field->get_time(ltime)) + { + bzero((char*) ltime,sizeof(*ltime)); + return 1; + } + return 0; +} + +double Item_field::val_result() +{ + if ((null_value=result_field->is_null())) + return 0.0; + return result_field->val_real(); +} + +longlong Item_field::val_int_result() +{ + if ((null_value=result_field->is_null())) + return 0; + return result_field->val_int(); +} + + +my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value) +{ + if ((null_value= result_field->is_null())) + return 0; + return result_field->val_decimal(decimal_value); +} + + +bool Item_field::val_bool_result() +{ + if ((null_value= result_field->is_null())) + return FALSE; + switch (result_field->result_type()) { + case INT_RESULT: + return result_field->val_int() != 0; + case DECIMAL_RESULT: + { + my_decimal decimal_value; + my_decimal *val= result_field->val_decimal(&decimal_value); + if (val) + return !my_decimal_is_zero(val); + return 0; + } + case REAL_RESULT: + case STRING_RESULT: + return result_field->val_real() != 0.0; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + return 0; // Shut up compiler + } +} + + +bool Item_field::is_null_result() +{ + return (null_value=result_field->is_null()); +} + + +bool Item_field::eq(const Item *item, bool binary_cmp) const +{ + Item *real_item= ((Item *) item)->real_item(); + if (real_item->type() != FIELD_ITEM) + return 0; + + Item_field *item_field= (Item_field*) real_item; + if (item_field->field && field) + return item_field->field == field; + /* + We may come here when we are trying to find a function in a GROUP BY + clause from the select list. + In this case the '100 % correct' way to do this would be to first + run fix_fields() on the GROUP BY item and then retry this function, but + I think it's better to relax the checking a bit as we will in + most cases do the correct thing by just checking the field name. + (In cases where we would choose wrong we would have to generate a + ER_NON_UNIQ_ERROR). + */ + return (!my_strcasecmp(system_charset_info, item_field->name, + field_name) && + (!item_field->table_name || !table_name || + (!my_strcasecmp(table_alias_charset, item_field->table_name, + table_name) && + (!item_field->db_name || !db_name || + (item_field->db_name && !strcmp(item_field->db_name, + db_name)))))); +} + + +table_map Item_field::used_tables() const +{ + if (field->table->const_table) + return 0; // const item + return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map); +} + + +Item *Item_field::get_tmp_table_item(THD *thd) +{ + Item_field *new_item= new Item_field(thd, this); + if (new_item) + new_item->field= new_item->result_field; + return new_item; +} + +longlong Item_field::val_int_endpoint(bool left_endp, bool *incl_endp) +{ + longlong res= val_int(); + return null_value? LONGLONG_MIN : res; +} + +/** + Create an item from a string we KNOW points to a valid longlong + end \\0 terminated number string. + This is always 'signed'. Unsigned values are created with Item_uint() +*/ + +Item_int::Item_int(const char *str_arg, uint length) +{ + char *end_ptr= (char*) str_arg + length; + int error; + value= my_strtoll10(str_arg, &end_ptr, &error); + max_length= (uint) (end_ptr - str_arg); + name= (char*) str_arg; + fixed= 1; +} + + +my_decimal *Item_int::val_decimal(my_decimal *decimal_value) +{ + int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value); + return decimal_value; +} + +String *Item_int::val_str(String *str) +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + str->set(value, &my_charset_bin); + return str; +} + +void Item_int::print(String *str, enum_query_type query_type) +{ + // my_charset_bin is good enough for numbers + str_value.set(value, &my_charset_bin); + str->append(str_value); +} + + +Item_uint::Item_uint(const char *str_arg, uint length): + Item_int(str_arg, length) +{ + unsigned_flag= 1; +} + + +Item_uint::Item_uint(const char *str_arg, longlong i, uint length): + Item_int(str_arg, i, length) +{ + unsigned_flag= 1; +} + + +String *Item_uint::val_str(String *str) +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + str->set((ulonglong) value, &my_charset_bin); + return str; +} + + +void Item_uint::print(String *str, enum_query_type query_type) +{ + // latin1 is good enough for numbers + str_value.set((ulonglong) value, default_charset()); + str->append(str_value); +} + + +Item_decimal::Item_decimal(const char *str_arg, uint length, + CHARSET_INFO *charset) +{ + str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value); + name= (char*) str_arg; + decimals= (uint8) decimal_value.frac; + fixed= 1; + max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg + + decimals, + decimals, + unsigned_flag); +} + +Item_decimal::Item_decimal(longlong val, bool unsig) +{ + int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value); + decimals= (uint8) decimal_value.frac; + fixed= 1; + max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg + + decimals, + decimals, + unsigned_flag); +} + + +Item_decimal::Item_decimal(double val, int precision, int scale) +{ + double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value); + decimals= (uint8) decimal_value.frac; + fixed= 1; + max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg + + decimals, + decimals, + unsigned_flag); +} + + +Item_decimal::Item_decimal(const char *str, const my_decimal *val_arg, + uint decimal_par, uint length) +{ + my_decimal2decimal(val_arg, &decimal_value); + name= (char*) str; + decimals= (uint8) decimal_par; + max_length= length; + fixed= 1; +} + + +Item_decimal::Item_decimal(my_decimal *value_par) +{ + my_decimal2decimal(value_par, &decimal_value); + decimals= (uint8) decimal_value.frac; + fixed= 1; + max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg + + decimals, + decimals, + unsigned_flag); +} + + +Item_decimal::Item_decimal(const uchar *bin, int precision, int scale) +{ + binary2my_decimal(E_DEC_FATAL_ERROR, bin, + &decimal_value, precision, scale); + decimals= (uint8) decimal_value.frac; + fixed= 1; + max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, + unsigned_flag); +} + + +longlong Item_decimal::val_int() +{ + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result); + return result; +} + +double Item_decimal::val_real() +{ + double result; + my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result); + return result; +} + +String *Item_decimal::val_str(String *result) +{ + result->set_charset(&my_charset_bin); + my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result); + return result; +} + +void Item_decimal::print(String *str, enum_query_type query_type) +{ + my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value); + str->append(str_value); +} + + +bool Item_decimal::eq(const Item *item, bool binary_cmp) const +{ + if (type() == item->type() && item->basic_const_item()) + { + /* + We need to cast off const to call val_decimal(). This should + be OK for a basic constant. Additionally, we can pass 0 as + a true decimal constant will return its internal decimal + storage and ignore the argument. + */ + Item *arg= (Item*) item; + my_decimal *value= arg->val_decimal(0); + return !my_decimal_cmp(&decimal_value, value); + } + return 0; +} + + +void Item_decimal::set_decimal_value(my_decimal *value_par) +{ + my_decimal2decimal(value_par, &decimal_value); + decimals= (uint8) decimal_value.frac; + unsigned_flag= !decimal_value.sign(); + max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg + + decimals, + decimals, + unsigned_flag); +} + + +String *Item_float::val_str(String *str) +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + str->set_real(value,decimals,&my_charset_bin); + return str; +} + + +my_decimal *Item_float::val_decimal(my_decimal *decimal_value) +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value); + return (decimal_value); +} + + +void Item_string::print(String *str, enum_query_type query_type) +{ + if (query_type == QT_ORDINARY && is_cs_specified()) + { + str->append('_'); + str->append(collation.collation->csname); + } + + str->append('\''); + + if (query_type == QT_ORDINARY || + my_charset_same(str_value.charset(), system_charset_info)) + { + str_value.print(str); + } + else + { + THD *thd= current_thd; + LEX_STRING utf8_lex_str; + + thd->convert_string(&utf8_lex_str, + system_charset_info, + str_value.c_ptr_safe(), + str_value.length(), + str_value.charset()); + + String utf8_str(utf8_lex_str.str, + utf8_lex_str.length, + system_charset_info); + + utf8_str.print(str); + } + + str->append('\''); +} + + +double +double_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end) +{ + int error; + char *org_end; + double tmp; + + org_end= end; + tmp= my_strntod(cs, (char*) cptr, end - cptr, &end, &error); + if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end))) + { + /* + We can use str_value.ptr() here as Item_string is gurantee to put an + end \0 here. + */ + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE, + ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE", + cptr); + } + return tmp; +} + + +double Item_string::val_real() +{ + DBUG_ASSERT(fixed == 1); + return double_from_string_with_check (str_value.charset(), str_value.ptr(), + (char *) str_value.ptr() + str_value.length()); +} + + +longlong +longlong_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end) +{ + int err; + longlong tmp; + char *org_end= end; + + tmp= (*(cs->cset->strtoll10))(cs, cptr, &end, &err); + /* + TODO: Give error if we wanted a signed integer and we got an unsigned + one + */ + if (!current_thd->no_errors && + (err > 0 || + (end != org_end && !check_if_only_end_space(cs, end, org_end)))) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE, + ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER", + cptr); + } + return tmp; +} + + +/** + @todo + Give error if we wanted a signed integer and we got an unsigned one +*/ +longlong Item_string::val_int() +{ + DBUG_ASSERT(fixed == 1); + return longlong_from_string_with_check(str_value.charset(), str_value.ptr(), + (char *) str_value.ptr()+ str_value.length()); +} + + +my_decimal *Item_string::val_decimal(my_decimal *decimal_value) +{ + return val_decimal_from_string(decimal_value); +} + + +bool Item_null::eq(const Item *item, bool binary_cmp) const +{ return item->type() == type(); } + + +double Item_null::val_real() +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + null_value=1; + return 0.0; +} +longlong Item_null::val_int() +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + null_value=1; + return 0; +} +/* ARGSUSED */ +String *Item_null::val_str(String *str) +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + null_value=1; + return 0; +} + +my_decimal *Item_null::val_decimal(my_decimal *decimal_value) +{ + return 0; +} + + +Item *Item_null::safe_charset_converter(CHARSET_INFO *tocs) +{ + collation.set(tocs); + return this; +} + +/*********************** Item_param related ******************************/ + +/** + Default function of Item_param::set_param_func, so in case + of malformed packet the server won't SIGSEGV. +*/ + +static void +default_set_param_func(Item_param *param, + uchar **pos __attribute__((unused)), + ulong len __attribute__((unused))) +{ + param->set_null(); +} + + +Item_param::Item_param(uint pos_in_query_arg) : + state(NO_VALUE), + item_result_type(STRING_RESULT), + /* Don't pretend to be a literal unless value for this item is set. */ + item_type(PARAM_ITEM), + param_type(MYSQL_TYPE_VARCHAR), + pos_in_query(pos_in_query_arg), + set_param_func(default_set_param_func), + limit_clause_param(FALSE) +{ + name= (char*) "?"; + /* + Since we can't say whenever this item can be NULL or cannot be NULL + before mysql_stmt_execute(), so we assuming that it can be NULL until + value is set. + */ + maybe_null= 1; + cnvitem= new Item_string("", 0, &my_charset_bin, DERIVATION_COERCIBLE); + cnvstr.set(cnvbuf, sizeof(cnvbuf), &my_charset_bin); +} + + +void Item_param::set_null() +{ + DBUG_ENTER("Item_param::set_null"); + /* These are cleared after each execution by reset() method */ + null_value= 1; + /* + Because of NULL and string values we need to set max_length for each new + placeholder value: user can submit NULL for any placeholder type, and + string length can be different in each execution. + */ + max_length= 0; + decimals= 0; + state= NULL_VALUE; + item_type= Item::NULL_ITEM; + DBUG_VOID_RETURN; +} + +void Item_param::set_int(longlong i, uint32 max_length_arg) +{ + DBUG_ENTER("Item_param::set_int"); + value.integer= (longlong) i; + state= INT_VALUE; + max_length= max_length_arg; + decimals= 0; + maybe_null= 0; + DBUG_VOID_RETURN; +} + +void Item_param::set_double(double d) +{ + DBUG_ENTER("Item_param::set_double"); + value.real= d; + state= REAL_VALUE; + max_length= DBL_DIG + 8; + decimals= NOT_FIXED_DEC; + maybe_null= 0; + DBUG_VOID_RETURN; +} + + +/** + Set decimal parameter value from string. + + @param str character string + @param length string length + + @note + As we use character strings to send decimal values in + binary protocol, we use str2my_decimal to convert it to + internal decimal value. +*/ + +void Item_param::set_decimal(const char *str, ulong length) +{ + char *end; + DBUG_ENTER("Item_param::set_decimal"); + + end= (char*) str+length; + str2my_decimal(E_DEC_FATAL_ERROR, str, &decimal_value, &end); + state= DECIMAL_VALUE; + decimals= decimal_value.frac; + max_length= + my_decimal_precision_to_length_no_truncation(decimal_value.precision(), + decimals, unsigned_flag); + maybe_null= 0; + DBUG_VOID_RETURN; +} + + +/** + Set parameter value from MYSQL_TIME value. + + @param tm datetime value to set (time_type is ignored) + @param type type of datetime value + @param max_length_arg max length of datetime value as string + + @note + If we value to be stored is not normalized, zero value will be stored + instead and proper warning will be produced. This function relies on + the fact that even wrong value sent over binary protocol fits into + MAX_DATE_STRING_REP_LENGTH buffer. +*/ +void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type, + uint32 max_length_arg) +{ + DBUG_ENTER("Item_param::set_time"); + + value.time= *tm; + value.time.time_type= time_type; + + if (value.time.year > 9999 || value.time.month > 12 || + value.time.day > 31 || + (time_type != MYSQL_TIMESTAMP_TIME && value.time.hour > 23) || + value.time.minute > 59 || value.time.second > 59) + { + char buff[MAX_DATE_STRING_REP_LENGTH]; + uint length= my_TIME_to_str(&value.time, buff); + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + buff, length, time_type, 0); + set_zero_time(&value.time, MYSQL_TIMESTAMP_ERROR); + } + + state= TIME_VALUE; + maybe_null= 0; + max_length= max_length_arg; + decimals= 0; + DBUG_VOID_RETURN; +} + + +bool Item_param::set_str(const char *str, ulong length) +{ + DBUG_ENTER("Item_param::set_str"); + /* + Assign string with no conversion: data is converted only after it's + been written to the binary log. + */ + uint dummy_errors; + if (str_value.copy(str, length, &my_charset_bin, &my_charset_bin, + &dummy_errors)) + DBUG_RETURN(TRUE); + state= STRING_VALUE; + max_length= length; + maybe_null= 0; + /* max_length and decimals are set after charset conversion */ + /* sic: str may be not null-terminated, don't add DBUG_PRINT here */ + DBUG_RETURN(FALSE); +} + + +bool Item_param::set_longdata(const char *str, ulong length) +{ + DBUG_ENTER("Item_param::set_longdata"); + + /* + If client character set is multibyte, end of long data packet + may hit at the middle of a multibyte character. Additionally, + if binary log is open we must write long data value to the + binary log in character set of client. This is why we can't + convert long data to connection character set as it comes + (here), and first have to concatenate all pieces together, + write query to the binary log and only then perform conversion. + */ + if (str_value.append(str, length, &my_charset_bin)) + DBUG_RETURN(TRUE); + state= LONG_DATA_VALUE; + maybe_null= 0; + + DBUG_RETURN(FALSE); +} + + +/** + Set parameter value from user variable value. + + @param thd Current thread + @param entry User variable structure (NULL means use NULL value) + + @retval + 0 OK + @retval + 1 Out of memory +*/ + +bool Item_param::set_from_user_var(THD *thd, const user_var_entry *entry) +{ + DBUG_ENTER("Item_param::set_from_user_var"); + if (entry && entry->value) + { + item_result_type= entry->type; + unsigned_flag= entry->unsigned_flag; + if (limit_clause_param) + { + my_bool unused; + set_int(entry->val_int(&unused), MY_INT64_NUM_DECIMAL_DIGITS); + item_type= Item::INT_ITEM; + DBUG_RETURN(!unsigned_flag && value.integer < 0 ? 1 : 0); + } + switch (item_result_type) { + case REAL_RESULT: + set_double(*(double*)entry->value); + item_type= Item::REAL_ITEM; + break; + case INT_RESULT: + set_int(*(longlong*)entry->value, MY_INT64_NUM_DECIMAL_DIGITS); + item_type= Item::INT_ITEM; + break; + case STRING_RESULT: + { + CHARSET_INFO *fromcs= entry->collation.collation; + CHARSET_INFO *tocs= thd->variables.collation_connection; + uint32 dummy_offset; + + value.cs_info.character_set_of_placeholder= fromcs; + value.cs_info.character_set_client= thd->variables.character_set_client; + /* + Setup source and destination character sets so that they + are different only if conversion is necessary: this will + make later checks easier. + */ + value.cs_info.final_character_set_of_str_value= + String::needs_conversion(0, fromcs, tocs, &dummy_offset) ? + tocs : fromcs; + /* + Exact value of max_length is not known unless data is converted to + charset of connection, so we have to set it later. + */ + item_type= Item::STRING_ITEM; + + if (set_str((const char *)entry->value, entry->length)) + DBUG_RETURN(1); + break; + } + case DECIMAL_RESULT: + { + const my_decimal *ent_value= (const my_decimal *)entry->value; + my_decimal2decimal(ent_value, &decimal_value); + state= DECIMAL_VALUE; + decimals= ent_value->frac; + max_length= + my_decimal_precision_to_length_no_truncation(ent_value->precision(), + decimals, unsigned_flag); + item_type= Item::DECIMAL_ITEM; + break; + } + default: + DBUG_ASSERT(0); + set_null(); + } + } + else + set_null(); + + DBUG_RETURN(0); +} + +/** + Resets parameter after execution. + + @note + We clear null_value here instead of setting it in set_* methods, + because we want more easily handle case for long data. +*/ + +void Item_param::reset() +{ + DBUG_ENTER("Item_param::reset"); + /* Shrink string buffer if it's bigger than max possible CHAR column */ + if (str_value.alloced_length() > MAX_CHAR_WIDTH) + str_value.free(); + else + str_value.length(0); + str_value_ptr.length(0); + /* + We must prevent all charset conversions until data has been written + to the binary log. + */ + str_value.set_charset(&my_charset_bin); + collation.set(&my_charset_bin, DERIVATION_COERCIBLE); + state= NO_VALUE; + maybe_null= 1; + null_value= 0; + /* + Don't reset item_type to PARAM_ITEM: it's only needed to guard + us from item optimizations at prepare stage, when item doesn't yet + contain a literal of some kind. + In all other cases when this object is accessed its value is + set (this assumption is guarded by 'state' and + DBUG_ASSERTS(state != NO_VALUE) in all Item_param::get_* + methods). + */ + DBUG_VOID_RETURN; +} + + +int Item_param::save_in_field(Field *field, bool no_conversions) +{ + field->set_notnull(); + + switch (state) { + case INT_VALUE: + return field->store(value.integer, unsigned_flag); + case REAL_VALUE: + return field->store(value.real); + case DECIMAL_VALUE: + return field->store_decimal(&decimal_value); + case TIME_VALUE: + field->store_time(&value.time, value.time.time_type); + return 0; + case STRING_VALUE: + case LONG_DATA_VALUE: + return field->store(str_value.ptr(), str_value.length(), + str_value.charset()); + case NULL_VALUE: + return set_field_to_null_with_conversions(field, no_conversions); + case NO_VALUE: + default: + DBUG_ASSERT(0); + } + return 1; +} + + +bool Item_param::get_time(MYSQL_TIME *res) +{ + if (state == TIME_VALUE) + { + *res= value.time; + return 0; + } + /* + If parameter value isn't supplied assertion will fire in val_str() + which is called from Item::get_time(). + */ + return Item::get_time(res); +} + + +bool Item_param::get_date(MYSQL_TIME *res, uint fuzzydate) +{ + if (state == TIME_VALUE) + { + *res= value.time; + return 0; + } + return Item::get_date(res, fuzzydate); +} + + +double Item_param::val_real() +{ + switch (state) { + case REAL_VALUE: + return value.real; + case INT_VALUE: + return (double) value.integer; + case DECIMAL_VALUE: + { + double result; + my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result); + return result; + } + case STRING_VALUE: + case LONG_DATA_VALUE: + { + int dummy_err; + char *end_not_used; + return my_strntod(str_value.charset(), (char*) str_value.ptr(), + str_value.length(), &end_not_used, &dummy_err); + } + case TIME_VALUE: + /* + This works for example when user says SELECT ?+0.0 and supplies + time value for the placeholder. + */ + return ulonglong2double(TIME_to_ulonglong(&value.time)); + case NULL_VALUE: + return 0.0; + default: + DBUG_ASSERT(0); + } + return 0.0; +} + + +longlong Item_param::val_int() +{ + switch (state) { + case REAL_VALUE: + return (longlong) rint(value.real); + case INT_VALUE: + return value.integer; + case DECIMAL_VALUE: + { + longlong i; + my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &i); + return i; + } + case STRING_VALUE: + case LONG_DATA_VALUE: + { + int dummy_err; + return my_strntoll(str_value.charset(), str_value.ptr(), + str_value.length(), 10, (char**) 0, &dummy_err); + } + case TIME_VALUE: + return (longlong) TIME_to_ulonglong(&value.time); + case NULL_VALUE: + return 0; + default: + DBUG_ASSERT(0); + } + return 0; +} + + +my_decimal *Item_param::val_decimal(my_decimal *dec) +{ + switch (state) { + case DECIMAL_VALUE: + return &decimal_value; + case REAL_VALUE: + double2my_decimal(E_DEC_FATAL_ERROR, value.real, dec); + return dec; + case INT_VALUE: + int2my_decimal(E_DEC_FATAL_ERROR, value.integer, unsigned_flag, dec); + return dec; + case STRING_VALUE: + case LONG_DATA_VALUE: + string2my_decimal(E_DEC_FATAL_ERROR, &str_value, dec); + return dec; + case TIME_VALUE: + { + longlong i= (longlong) TIME_to_ulonglong(&value.time); + int2my_decimal(E_DEC_FATAL_ERROR, i, 0, dec); + return dec; + } + case NULL_VALUE: + return 0; + default: + DBUG_ASSERT(0); + } + return 0; +} + + +String *Item_param::val_str(String* str) +{ + switch (state) { + case STRING_VALUE: + case LONG_DATA_VALUE: + return &str_value_ptr; + case REAL_VALUE: + str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin); + return str; + case INT_VALUE: + str->set(value.integer, &my_charset_bin); + return str; + case DECIMAL_VALUE: + if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, + 0, 0, 0, str) <= 1) + return str; + return NULL; + case TIME_VALUE: + { + if (str->reserve(MAX_DATE_STRING_REP_LENGTH)) + break; + str->length((uint) my_TIME_to_str(&value.time, (char*) str->ptr())); + str->set_charset(&my_charset_bin); + return str; + } + case NULL_VALUE: + return NULL; + default: + DBUG_ASSERT(0); + } + return str; +} + +/** + Return Param item values in string format, for generating the dynamic + query used in update/binary logs. + + @todo + - Change interface and implementation to fill log data in place + and avoid one more memcpy/alloc between str and log string. + - In case of error we need to notify replication + that binary log contains wrong statement +*/ + +const String *Item_param::query_val_str(String* str) const +{ + switch (state) { + case INT_VALUE: + str->set_int(value.integer, unsigned_flag, &my_charset_bin); + break; + case REAL_VALUE: + str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin); + break; + case DECIMAL_VALUE: + if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, + 0, 0, 0, str) > 1) + return &my_null_string; + break; + case TIME_VALUE: + { + char *buf, *ptr; + str->length(0); + /* + TODO: in case of error we need to notify replication + that binary log contains wrong statement + */ + if (str->reserve(MAX_DATE_STRING_REP_LENGTH+3)) + break; + + /* Create date string inplace */ + buf= str->c_ptr_quick(); + ptr= buf; + *ptr++= '\''; + ptr+= (uint) my_TIME_to_str(&value.time, ptr); + *ptr++= '\''; + str->length((uint32) (ptr - buf)); + break; + } + case STRING_VALUE: + case LONG_DATA_VALUE: + { + str->length(0); + append_query_string(value.cs_info.character_set_client, &str_value, str); + break; + } + case NULL_VALUE: + return &my_null_string; + default: + DBUG_ASSERT(0); + } + return str; +} + + +/** + Convert string from client character set to the character set of + connection. +*/ + +bool Item_param::convert_str_value(THD *thd) +{ + bool rc= FALSE; + if (state == STRING_VALUE || state == LONG_DATA_VALUE) + { + /* + Check is so simple because all charsets were set up properly + in setup_one_conversion_function, where typecode of + placeholder was also taken into account: the variables are different + here only if conversion is really necessary. + */ + if (value.cs_info.final_character_set_of_str_value != + value.cs_info.character_set_of_placeholder) + { + rc= thd->convert_string(&str_value, + value.cs_info.character_set_of_placeholder, + value.cs_info.final_character_set_of_str_value); + } + else + str_value.set_charset(value.cs_info.final_character_set_of_str_value); + /* Here str_value is guaranteed to be in final_character_set_of_str_value */ + + max_length= str_value.numchars() * str_value.charset()->mbmaxlen; + decimals= 0; + /* + str_value_ptr is returned from val_str(). It must be not alloced + to prevent it's modification by val_str() invoker. + */ + str_value_ptr.set(str_value.ptr(), str_value.length(), + str_value.charset()); + /* Synchronize item charset with value charset */ + collation.set(str_value.charset(), DERIVATION_COERCIBLE); + } + return rc; +} + + +bool Item_param::basic_const_item() const +{ + if (state == NO_VALUE || state == TIME_VALUE) + return FALSE; + return TRUE; +} + + +Item * +Item_param::clone_item() +{ + /* see comments in the header file */ + switch (state) { + case NULL_VALUE: + return new Item_null(name); + case INT_VALUE: + return (unsigned_flag ? + new Item_uint(name, value.integer, max_length) : + new Item_int(name, value.integer, max_length)); + case REAL_VALUE: + return new Item_float(name, value.real, decimals, max_length); + case STRING_VALUE: + case LONG_DATA_VALUE: + return new Item_string(name, str_value.c_ptr_quick(), str_value.length(), + str_value.charset()); + case TIME_VALUE: + break; + case NO_VALUE: + default: + DBUG_ASSERT(0); + }; + return 0; +} + + +bool +Item_param::eq(const Item *arg, bool binary_cmp) const +{ + Item *item; + if (!basic_const_item() || !arg->basic_const_item() || arg->type() != type()) + return FALSE; + /* + We need to cast off const to call val_int(). This should be OK for + a basic constant. + */ + item= (Item*) arg; + + switch (state) { + case NULL_VALUE: + return TRUE; + case INT_VALUE: + return value.integer == item->val_int() && + unsigned_flag == item->unsigned_flag; + case REAL_VALUE: + return value.real == item->val_real(); + case STRING_VALUE: + case LONG_DATA_VALUE: + if (binary_cmp) + return !stringcmp(&str_value, &item->str_value); + return !sortcmp(&str_value, &item->str_value, collation.collation); + default: + break; + } + return FALSE; +} + +/* End of Item_param related */ + +void Item_param::print(String *str, enum_query_type query_type) +{ + if (state == NO_VALUE) + { + str->append('?'); + } + else + { + char buffer[STRING_BUFFER_USUAL_SIZE]; + String tmp(buffer, sizeof(buffer), &my_charset_bin); + const String *res; + res= query_val_str(&tmp); + str->append(*res); + } +} + + +/** + Preserve the original parameter types and values + when re-preparing a prepared statement. + + @details Copy parameter type information and conversion + function pointers from a parameter of the old statement + to the corresponding parameter of the new one. + + Move parameter values from the old parameters to the new + one. We simply "exchange" the values, which allows + to save on allocation and character set conversion in + case a parameter is a string or a blob/clob. + + The old parameter gets the value of this one, which + ensures that all memory of this parameter is freed + correctly. + + @param[in] src parameter item of the original + prepared statement +*/ + +void +Item_param::set_param_type_and_swap_value(Item_param *src) +{ + unsigned_flag= src->unsigned_flag; + param_type= src->param_type; + set_param_func= src->set_param_func; + item_type= src->item_type; + item_result_type= src->item_result_type; + + collation.set(src->collation); + maybe_null= src->maybe_null; + null_value= src->null_value; + max_length= src->max_length; + decimals= src->decimals; + state= src->state; + value= src->value; + + decimal_value.swap(src->decimal_value); + str_value.swap(src->str_value); + str_value_ptr.swap(src->str_value_ptr); +} + +/**************************************************************************** + Item_copy +****************************************************************************/ +Item_copy *Item_copy::create (Item *item) +{ + switch (item->result_type()) + { + case STRING_RESULT: + return new Item_copy_string (item); + case REAL_RESULT: + return new Item_copy_float (item); + case INT_RESULT: + return item->unsigned_flag ? + new Item_copy_uint (item) : new Item_copy_int (item); + case DECIMAL_RESULT: + return new Item_copy_decimal (item); + default: + DBUG_ASSERT (0); + } + /* should not happen */ + return NULL; +} + +/**************************************************************************** + Item_copy_string +****************************************************************************/ + +double Item_copy_string::val_real() +{ + int err_not_used; + char *end_not_used; + return (null_value ? 0.0 : + my_strntod(str_value.charset(), (char*) str_value.ptr(), + str_value.length(), &end_not_used, &err_not_used)); +} + +longlong Item_copy_string::val_int() +{ + int err; + return null_value ? LL(0) : my_strntoll(str_value.charset(),str_value.ptr(), + str_value.length(),10, (char**) 0, + &err); +} + + +int Item_copy_string::save_in_field(Field *field, bool no_conversions) +{ + return save_str_value_in_field(field, &str_value); +} + + +void Item_copy_string::copy() +{ + String *res=item->val_str(&str_value); + if (res && res != &str_value) + str_value.copy(*res); + null_value=item->null_value; +} + +/* ARGSUSED */ +String *Item_copy_string::val_str(String *str) +{ + // Item_copy_string is used without fix_fields call + if (null_value) + return (String*) 0; + return &str_value; +} + + +my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value) +{ + // Item_copy_string is used without fix_fields call + if (null_value) + return (my_decimal *) 0; + string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value); + return (decimal_value); +} + + +/**************************************************************************** + Item_copy_int +****************************************************************************/ + +void Item_copy_int::copy() +{ + cached_value= item->val_int(); + null_value=item->null_value; +} + +static int save_int_value_in_field (Field *field, longlong nr, + bool null_value, bool unsigned_flag); + +int Item_copy_int::save_in_field(Field *field, bool no_conversions) +{ + return save_int_value_in_field(field, cached_value, + null_value, unsigned_flag); +} + + +String *Item_copy_int::val_str(String *str) +{ + if (null_value) + return (String *) 0; + + str->set(cached_value, &my_charset_bin); + return str; +} + + +my_decimal *Item_copy_int::val_decimal(my_decimal *decimal_value) +{ + if (null_value) + return (my_decimal *) 0; + + int2my_decimal(E_DEC_FATAL_ERROR, cached_value, unsigned_flag, decimal_value); + return decimal_value; +} + + +/**************************************************************************** + Item_copy_uint +****************************************************************************/ + +String *Item_copy_uint::val_str(String *str) +{ + if (null_value) + return (String *) 0; + + str->set((ulonglong) cached_value, &my_charset_bin); + return str; +} + + +/**************************************************************************** + Item_copy_float +****************************************************************************/ + +String *Item_copy_float::val_str(String *str) +{ + if (null_value) + return (String *) 0; + else + { + double nr= val_real(); + str->set_real(nr,decimals, &my_charset_bin); + return str; + } +} + + +my_decimal *Item_copy_float::val_decimal(my_decimal *decimal_value) +{ + if (null_value) + return (my_decimal *) 0; + else + { + double nr= val_real(); + double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value); + return decimal_value; + } +} + + +int Item_copy_float::save_in_field(Field *field, bool no_conversions) +{ + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + return field->store(cached_value); +} + + +/**************************************************************************** + Item_copy_decimal +****************************************************************************/ + +int Item_copy_decimal::save_in_field(Field *field, bool no_conversions) +{ + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + return field->store_decimal(&cached_value); +} + + +String *Item_copy_decimal::val_str(String *result) +{ + if (null_value) + return (String *) 0; + result->set_charset(&my_charset_bin); + my_decimal2string(E_DEC_FATAL_ERROR, &cached_value, 0, 0, 0, result); + return result; +} + + +double Item_copy_decimal::val_real() +{ + if (null_value) + return 0.0; + else + { + double result; + my_decimal2double(E_DEC_FATAL_ERROR, &cached_value, &result); + return result; + } +} + + +longlong Item_copy_decimal::val_int() +{ + if (null_value) + return LL(0); + else + { + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, &cached_value, unsigned_flag, &result); + return result; + } +} + + +void Item_copy_decimal::copy() +{ + my_decimal *nr= item->val_decimal(&cached_value); + if (nr && nr != &cached_value) + memcpy (&cached_value, nr, sizeof (my_decimal)); + null_value= item->null_value; +} + + +/* + Functions to convert item to field (for send_fields) +*/ + +/* ARGSUSED */ +bool Item::fix_fields(THD *thd, Item **ref) +{ + + // We do not check fields which are fixed during construction + DBUG_ASSERT(fixed == 0 || basic_const_item()); + fixed= 1; + return FALSE; +} + +double Item_ref_null_helper::val_real() +{ + DBUG_ASSERT(fixed == 1); + double tmp= (*ref)->val_result(); + owner->was_null|= null_value= (*ref)->null_value; + return tmp; +} + + +longlong Item_ref_null_helper::val_int() +{ + DBUG_ASSERT(fixed == 1); + longlong tmp= (*ref)->val_int_result(); + owner->was_null|= null_value= (*ref)->null_value; + return tmp; +} + + +my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + my_decimal *val= (*ref)->val_decimal_result(decimal_value); + owner->was_null|= null_value= (*ref)->null_value; + return val; +} + + +bool Item_ref_null_helper::val_bool() +{ + DBUG_ASSERT(fixed == 1); + bool val= (*ref)->val_bool_result(); + owner->was_null|= null_value= (*ref)->null_value; + return val; +} + + +String* Item_ref_null_helper::val_str(String* s) +{ + DBUG_ASSERT(fixed == 1); + String* tmp= (*ref)->str_result(s); + owner->was_null|= null_value= (*ref)->null_value; + return tmp; +} + + +bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, uint fuzzydate) +{ + return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate)); +} + + +/** + Mark item and SELECT_LEXs as dependent if item was resolved in + outer SELECT. + + @param thd thread handler + @param last select from which current item depend + @param current current select + @param resolved_item item which was resolved in outer SELECT(for warning) + @param mark_item item which should be marked (can be differ in case of + substitution) +*/ + +static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current, + Item_ident *resolved_item, + Item_ident *mark_item) +{ + const char *db_name= (resolved_item->db_name ? + resolved_item->db_name : ""); + const char *table_name= (resolved_item->table_name ? + resolved_item->table_name : ""); + /* store pointer on SELECT_LEX from which item is dependent */ + if (mark_item) + mark_item->depended_from= last; + current->mark_as_dependent(last); + if (thd->lex->describe & DESCRIBE_EXTENDED) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_WARN_FIELD_RESOLVED, ER(ER_WARN_FIELD_RESOLVED), + db_name, (db_name[0] ? "." : ""), + table_name, (table_name [0] ? "." : ""), + resolved_item->field_name, + current->select_number, last->select_number); + } +} + + +/** + Mark range of selects and resolved identifier (field/reference) + item as dependent. + + @param thd thread handler + @param last_select select where resolved_item was resolved + @param current_sel current select (select where resolved_item was placed) + @param found_field field which was found during resolving + @param found_item Item which was found during resolving (if resolved + identifier belongs to VIEW) + @param resolved_item Identifier which was resolved + + @note + We have to mark all items between current_sel (including) and + last_select (excluding) as dependend (select before last_select should + be marked with actual table mask used by resolved item, all other with + OUTER_REF_TABLE_BIT) and also write dependence information to Item of + resolved identifier. +*/ + +void mark_select_range_as_dependent(THD *thd, + SELECT_LEX *last_select, + SELECT_LEX *current_sel, + Field *found_field, Item *found_item, + Item_ident *resolved_item) +{ + /* + Go from current SELECT to SELECT where field was resolved (it + have to be reachable from current SELECT, because it was already + done once when we resolved this field and cached result of + resolving) + */ + SELECT_LEX *previous_select= current_sel; + for (; previous_select->outer_select() != last_select; + previous_select= previous_select->outer_select()) + { + Item_subselect *prev_subselect_item= + previous_select->master_unit()->item; + prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT; + prev_subselect_item->const_item_cache= 0; + } + { + Item_subselect *prev_subselect_item= + previous_select->master_unit()->item; + Item_ident *dependent= resolved_item; + if (found_field == view_ref_found) + { + Item::Type type= found_item->type(); + prev_subselect_item->used_tables_cache|= + found_item->used_tables(); + dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ? + (Item_ident*) found_item : + 0); + } + else + prev_subselect_item->used_tables_cache|= + found_field->table->map; + prev_subselect_item->const_item_cache= 0; + mark_as_dependent(thd, last_select, current_sel, resolved_item, + dependent); + } +} + + +/** + Search a GROUP BY clause for a field with a certain name. + + Search the GROUP BY list for a column named as find_item. When searching + preference is given to columns that are qualified with the same table (and + database) name as the one being searched for. + + @param find_item the item being searched for + @param group_list GROUP BY clause + + @return + - the found item on success + - NULL if find_item is not in group_list +*/ + +static Item** find_field_in_group_list(Item *find_item, ORDER *group_list) +{ + const char *db_name; + const char *table_name; + const char *field_name; + ORDER *found_group= NULL; + int found_match_degree= 0; + Item_ident *cur_field; + int cur_match_degree= 0; + char name_buff[NAME_LEN+1]; + + if (find_item->type() == Item::FIELD_ITEM || + find_item->type() == Item::REF_ITEM) + { + db_name= ((Item_ident*) find_item)->db_name; + table_name= ((Item_ident*) find_item)->table_name; + field_name= ((Item_ident*) find_item)->field_name; + } + else + return NULL; + + if (db_name && lower_case_table_names) + { + /* Convert database to lower case for comparison */ + strmake(name_buff, db_name, sizeof(name_buff)-1); + my_casedn_str(files_charset_info, name_buff); + db_name= name_buff; + } + + DBUG_ASSERT(field_name != 0); + + for (ORDER *cur_group= group_list ; cur_group ; cur_group= cur_group->next) + { + if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM) + { + cur_field= (Item_ident*) *cur_group->item; + cur_match_degree= 0; + + DBUG_ASSERT(cur_field->field_name != 0); + + if (!my_strcasecmp(system_charset_info, + cur_field->field_name, field_name)) + ++cur_match_degree; + else + continue; + + if (cur_field->table_name && table_name) + { + /* If field_name is qualified by a table name. */ + if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name)) + /* Same field names, different tables. */ + return NULL; + + ++cur_match_degree; + if (cur_field->db_name && db_name) + { + /* If field_name is also qualified by a database name. */ + if (strcmp(cur_field->db_name, db_name)) + /* Same field names, different databases. */ + return NULL; + ++cur_match_degree; + } + } + + if (cur_match_degree > found_match_degree) + { + found_match_degree= cur_match_degree; + found_group= cur_group; + } + else if (found_group && (cur_match_degree == found_match_degree) && + ! (*(found_group->item))->eq(cur_field, 0)) + { + /* + If the current resolve candidate matches equally well as the current + best match, they must reference the same column, otherwise the field + is ambiguous. + */ + my_error(ER_NON_UNIQ_ERROR, MYF(0), + find_item->full_name(), current_thd->where); + return NULL; + } + } + } + + if (found_group) + return found_group->item; + else + return NULL; +} + + +/** + Resolve a column reference in a sub-select. + + Resolve a column reference (usually inside a HAVING clause) against the + SELECT and GROUP BY clauses of the query described by 'select'. The name + resolution algorithm searches both the SELECT and GROUP BY clauses, and in + case of a name conflict prefers GROUP BY column names over SELECT names. If + both clauses contain different fields with the same names, a warning is + issued that name of 'ref' is ambiguous. We extend ANSI SQL in that when no + GROUP BY column is found, then a HAVING name is resolved as a possibly + derived SELECT column. This extension is allowed only if the + MODE_ONLY_FULL_GROUP_BY sql mode isn't enabled. + + @param thd current thread + @param ref column reference being resolved + @param select the select that ref is resolved against + + @note + The resolution procedure is: + - Search for a column or derived column named col_ref_i [in table T_j] + in the SELECT clause of Q. + - Search for a column named col_ref_i [in table T_j] + in the GROUP BY clause of Q. + - If found different columns with the same name in GROUP BY and SELECT + - issue a warning and return the GROUP BY column, + - otherwise + - if the MODE_ONLY_FULL_GROUP_BY mode is enabled return error + - else return the found SELECT column. + + + @return + - NULL - there was an error, and the error was already reported + - not_found_item - the item was not resolved, no error was reported + - resolved item - if the item was resolved +*/ + +static Item** +resolve_ref_in_select_and_group(THD *thd, Item_ident *ref, SELECT_LEX *select) +{ + Item **group_by_ref= NULL; + Item **select_ref= NULL; + ORDER *group_list= (ORDER*) select->group_list.first; + bool ambiguous_fields= FALSE; + uint counter; + enum_resolution_type resolution; + + /* + Search for a column or derived column named as 'ref' in the SELECT + clause of the current select. + */ + if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()), + &counter, REPORT_EXCEPT_NOT_FOUND, + &resolution))) + return NULL; /* Some error occurred. */ + if (resolution == RESOLVED_AGAINST_ALIAS) + ref->alias_name_used= TRUE; + + /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */ + if (select->having_fix_field && !ref->with_sum_func && group_list) + { + group_by_ref= find_field_in_group_list(ref, group_list); + + /* Check if the fields found in SELECT and GROUP BY are the same field. */ + if (group_by_ref && (select_ref != not_found_item) && + !((*group_by_ref)->eq(*select_ref, 0))) + { + ambiguous_fields= TRUE; + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR, + ER(ER_NON_UNIQ_ERROR), ref->full_name(), + current_thd->where); + + } + } + + if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY && + select->having_fix_field && + select_ref != not_found_item && !group_by_ref) + { + /* + Report the error if fields was found only in the SELECT item list and + the strict mode is enabled. + */ + my_error(ER_NON_GROUPING_FIELD_USED, MYF(0), + ref->name, "HAVING"); + return NULL; + } + if (select_ref != not_found_item || group_by_ref) + { + if (select_ref != not_found_item && !ambiguous_fields) + { + DBUG_ASSERT(*select_ref != 0); + if (!select->ref_pointer_array[counter]) + { + my_error(ER_ILLEGAL_REFERENCE, MYF(0), + ref->name, "forward reference in item list"); + return NULL; + } + DBUG_ASSERT((*select_ref)->fixed); + return (select->ref_pointer_array + counter); + } + if (group_by_ref) + return group_by_ref; + DBUG_ASSERT(FALSE); + return NULL; /* So there is no compiler warning. */ + } + + return (Item**) not_found_item; +} + + +/** + Resolve the name of an outer select column reference. + + The method resolves the column reference represented by 'this' as a column + present in outer selects that contain current select. + + In prepared statements, because of cache, find_field_in_tables() + can resolve fields even if they don't belong to current context. + In this case this method only finds appropriate context and marks + current select as dependent. The found reference of field should be + provided in 'from_field'. + + @param[in] thd current thread + @param[in,out] from_field found field reference or (Field*)not_found_field + @param[in,out] reference view column if this item was resolved to a + view column + + @note + This is the inner loop of Item_field::fix_fields: + @code + for each outer query Q_k beginning from the inner-most one + { + search for a column or derived column named col_ref_i + [in table T_j] in the FROM clause of Q_k; + + if such a column is not found + Search for a column or derived column named col_ref_i + [in table T_j] in the SELECT and GROUP clauses of Q_k. + } + @endcode + + @retval + 1 column succefully resolved and fix_fields() should continue. + @retval + 0 column fully fixed and fix_fields() should return FALSE + @retval + -1 error occured +*/ + +int +Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference) +{ + enum_parsing_place place= NO_MATTER; + bool field_found= (*from_field != not_found_field); + bool upward_lookup= FALSE; + + /* + If there are outer contexts (outer selects, but current select is + not derived table or view) try to resolve this reference in the + outer contexts. + + We treat each subselect as a separate namespace, so that different + subselects may contain columns with the same names. The subselects + are searched starting from the innermost. + */ + Name_resolution_context *last_checked_context= context; + Item **ref= (Item **) not_found_item; + SELECT_LEX *current_sel= (SELECT_LEX *) thd->lex->current_select; + Name_resolution_context *outer_context= 0; + SELECT_LEX *select= 0; + /* Currently derived tables cannot be correlated */ + if (current_sel->master_unit()->first_select()->linkage != + DERIVED_TABLE_TYPE) + outer_context= context->outer_context; + for (; + outer_context; + outer_context= outer_context->outer_context) + { + select= outer_context->select_lex; + Item_subselect *prev_subselect_item= + last_checked_context->select_lex->master_unit()->item; + last_checked_context= outer_context; + upward_lookup= TRUE; + + place= prev_subselect_item->parsing_place; + /* + If outer_field is set, field was already found by first call + to find_field_in_tables(). Only need to find appropriate context. + */ + if (field_found && outer_context->select_lex != + cached_table->select_lex) + continue; + /* + In case of a view, find_field_in_tables() writes the pointer to + the found view field into '*reference', in other words, it + substitutes this Item_field with the found expression. + */ + if (field_found || (*from_field= find_field_in_tables(thd, this, + outer_context-> + first_name_resolution_table, + outer_context-> + last_name_resolution_table, + reference, + IGNORE_EXCEPT_NON_UNIQUE, + TRUE, TRUE)) != + not_found_field) + { + if (*from_field) + { + if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY && + select->cur_pos_in_select_list != UNDEF_POS) + { + /* + As this is an outer field it should be added to the list of + non aggregated fields of the outer select. + */ + marker= select->cur_pos_in_select_list; + select->non_agg_fields.push_back(this); + } + if (*from_field != view_ref_found) + { + prev_subselect_item->used_tables_cache|= (*from_field)->table->map; + prev_subselect_item->const_item_cache= 0; + set_field(*from_field); + if (!last_checked_context->select_lex->having_fix_field && + select->group_list.elements && + (place == SELECT_LIST || place == IN_HAVING)) + { + Item_outer_ref *rf; + /* + If an outer field is resolved in a grouping select then it + is replaced for an Item_outer_ref object. Otherwise an + Item_field object is used. + The new Item_outer_ref object is saved in the inner_refs_list of + the outer select. Here it is only created. It can be fixed only + after the original field has been fixed and this is done in the + fix_inner_refs() function. + */ + ; + if (!(rf= new Item_outer_ref(context, this))) + return -1; + thd->change_item_tree(reference, rf); + select->inner_refs_list.push_back(rf); + rf->in_sum_func= thd->lex->in_sum_func; + } + /* + A reference is resolved to a nest level that's outer or the same as + the nest level of the enclosing set function : adjust the value of + max_arg_level for the function if it's needed. + */ + if (thd->lex->in_sum_func && + thd->lex->in_sum_func->nest_level >= select->nest_level) + { + Item::Type ref_type= (*reference)->type(); + set_if_bigger(thd->lex->in_sum_func->max_arg_level, + select->nest_level); + set_field(*from_field); + fixed= 1; + mark_as_dependent(thd, last_checked_context->select_lex, + context->select_lex, this, + ((ref_type == REF_ITEM || + ref_type == FIELD_ITEM) ? + (Item_ident*) (*reference) : 0)); + return 0; + } + } + else + { + Item::Type ref_type= (*reference)->type(); + prev_subselect_item->used_tables_cache|= + (*reference)->used_tables(); + prev_subselect_item->const_item_cache&= + (*reference)->const_item(); + mark_as_dependent(thd, last_checked_context->select_lex, + context->select_lex, this, + ((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ? + (Item_ident*) (*reference) : + 0)); + /* + A reference to a view field had been found and we + substituted it instead of this Item (find_field_in_tables + does it by assigning the new value to *reference), so now + we can return from this function. + */ + return 0; + } + } + break; + } + + /* Search in SELECT and GROUP lists of the outer select. */ + if (place != IN_WHERE && place != IN_ON) + { + if (!(ref= resolve_ref_in_select_and_group(thd, this, select))) + return -1; /* Some error occurred (e.g. ambiguous names). */ + if (ref != not_found_item) + { + DBUG_ASSERT(*ref && (*ref)->fixed); + prev_subselect_item->used_tables_cache|= (*ref)->used_tables(); + prev_subselect_item->const_item_cache&= (*ref)->const_item(); + break; + } + } + + /* + Reference is not found in this select => this subquery depend on + outer select (or we just trying to find wrong identifier, in this + case it does not matter which used tables bits we set) + */ + prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT; + prev_subselect_item->const_item_cache= 0; + } + + DBUG_ASSERT(ref != 0); + if (!*from_field) + return -1; + if (ref == not_found_item && *from_field == not_found_field) + { + if (upward_lookup) + { + // We can't say exactly what absent table or field + my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where); + } + else + { + /* Call find_field_in_tables only to report the error */ + find_field_in_tables(thd, this, + context->first_name_resolution_table, + context->last_name_resolution_table, + reference, REPORT_ALL_ERRORS, + !any_privileges && + TRUE, TRUE); + } + return -1; + } + else if (ref != not_found_item) + { + Item *save; + Item_ref *rf; + + /* Should have been checked in resolve_ref_in_select_and_group(). */ + DBUG_ASSERT(*ref && (*ref)->fixed); + /* + Here, a subset of actions performed by Item_ref::set_properties + is not enough. So we pass ptr to NULL into Item_[direct]_ref + constructor, so no initialization is performed, and call + fix_fields() below. + */ + save= *ref; + *ref= NULL; // Don't call set_properties() + rf= (place == IN_HAVING ? + new Item_ref(context, ref, (char*) table_name, + (char*) field_name, alias_name_used) : + (!select->group_list.elements ? + new Item_direct_ref(context, ref, (char*) table_name, + (char*) field_name, alias_name_used) : + new Item_outer_ref(context, ref, (char*) table_name, + (char*) field_name, alias_name_used))); + *ref= save; + if (!rf) + return -1; + + if (place != IN_HAVING && select->group_list.elements) + { + outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf); + ((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func; + } + thd->change_item_tree(reference, rf); + /* + rf is Item_ref => never substitute other items (in this case) + during fix_fields() => we can use rf after fix_fields() + */ + DBUG_ASSERT(!rf->fixed); // Assured by Item_ref() + if (rf->fix_fields(thd, reference) || rf->check_cols(1)) + return -1; + + mark_as_dependent(thd, last_checked_context->select_lex, + context->select_lex, this, + rf); + return 0; + } + else + { + mark_as_dependent(thd, last_checked_context->select_lex, + context->select_lex, + this, (Item_ident*)*reference); + if (last_checked_context->select_lex->having_fix_field) + { + Item_ref *rf; + rf= new Item_ref(context, + (cached_table->db[0] ? cached_table->db : 0), + (char*) cached_table->alias, (char*) field_name); + if (!rf) + return -1; + thd->change_item_tree(reference, rf); + /* + rf is Item_ref => never substitute other items (in this case) + during fix_fields() => we can use rf after fix_fields() + */ + DBUG_ASSERT(!rf->fixed); // Assured by Item_ref() + if (rf->fix_fields(thd, reference) || rf->check_cols(1)) + return -1; + return 0; + } + } + return 1; +} + + +/** + Resolve the name of a column reference. + + The method resolves the column reference represented by 'this' as a column + present in one of: FROM clause, SELECT clause, GROUP BY clause of a query + Q, or in outer queries that contain Q. + + The name resolution algorithm used is (where [T_j] is an optional table + name that qualifies the column name): + + @code + resolve_column_reference([T_j].col_ref_i) + { + search for a column or derived column named col_ref_i + [in table T_j] in the FROM clause of Q; + + if such a column is NOT found AND // Lookup in outer queries. + there are outer queries + { + for each outer query Q_k beginning from the inner-most one + { + search for a column or derived column named col_ref_i + [in table T_j] in the FROM clause of Q_k; + + if such a column is not found + Search for a column or derived column named col_ref_i + [in table T_j] in the SELECT and GROUP clauses of Q_k. + } + } + } + @endcode + + Notice that compared to Item_ref::fix_fields, here we first search the FROM + clause, and then we search the SELECT and GROUP BY clauses. + + @param[in] thd current thread + @param[in,out] reference view column if this item was resolved to a + view column + + @retval + TRUE if error + @retval + FALSE on success +*/ + +bool Item_field::fix_fields(THD *thd, Item **reference) +{ + DBUG_ASSERT(fixed == 0); + Field *from_field= (Field *)not_found_field; + bool outer_fixed= false; + + if (!field) // If field is not checked + { + /* + In case of view, find_field_in_tables() write pointer to view field + expression to 'reference', i.e. it substitute that expression instead + of this Item_field + */ + if ((from_field= find_field_in_tables(thd, this, + context->first_name_resolution_table, + context->last_name_resolution_table, + reference, + thd->lex->use_only_table_context ? + REPORT_ALL_ERRORS : + IGNORE_EXCEPT_NON_UNIQUE, + !any_privileges, + TRUE)) == + not_found_field) + { + int ret; + /* Look up in current select's item_list to find aliased fields */ + if (thd->lex->current_select->is_item_list_lookup) + { + uint counter; + enum_resolution_type resolution; + Item** res= find_item_in_list(this, thd->lex->current_select->item_list, + &counter, REPORT_EXCEPT_NOT_FOUND, + &resolution); + if (!res) + return 1; + if (resolution == RESOLVED_AGAINST_ALIAS) + alias_name_used= TRUE; + if (res != (Item **)not_found_item) + { + if ((*res)->type() == Item::FIELD_ITEM) + { + /* + It's an Item_field referencing another Item_field in the select + list. + Use the field from the Item_field in the select list and leave + the Item_field instance in place. + */ + + Field *new_field= (*((Item_field**)res))->field; + + if (new_field == NULL) + { + /* The column to which we link isn't valid. */ + my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name, + current_thd->where); + return(1); + } + + set_field(new_field); + return 0; + } + else + { + /* + It's not an Item_field in the select list so we must make a new + Item_ref to point to the Item in the select list and replace the + Item_field created by the parser with the new Item_ref. + */ + Item_ref *rf= new Item_ref(context, db_name,table_name,field_name); + if (!rf) + return 1; + thd->change_item_tree(reference, rf); + /* + Because Item_ref never substitutes itself with other items + in Item_ref::fix_fields(), we can safely use the original + pointer to it even after fix_fields() + */ + return rf->fix_fields(thd, reference) || rf->check_cols(1); + } + } + } + if ((ret= fix_outer_field(thd, &from_field, reference)) < 0) + goto error; + outer_fixed= TRUE; + if (!ret) + goto mark_non_agg_field; + } + else if (!from_field) + goto error; + + if (!outer_fixed && cached_table && cached_table->select_lex && + context->select_lex && + cached_table->select_lex != context->select_lex) + { + int ret; + if ((ret= fix_outer_field(thd, &from_field, reference)) < 0) + goto error; + outer_fixed= 1; + if (!ret) + goto mark_non_agg_field; + } + + /* + if it is not expression from merged VIEW we will set this field. + + We can leave expression substituted from view for next PS/SP rexecution + (i.e. do not register this substitution for reverting on cleanup() + (register_item_tree_changing())), because this subtree will be + fix_field'ed during setup_tables()->setup_underlying() (i.e. before + all other expressions of query, and references on tables which do + not present in query will not make problems. + + Also we suppose that view can't be changed during PS/SP life. + */ + if (from_field == view_ref_found) + return FALSE; + + set_field(from_field); + if (thd->lex->in_sum_func && + thd->lex->in_sum_func->nest_level == + thd->lex->current_select->nest_level) + set_if_bigger(thd->lex->in_sum_func->max_arg_level, + thd->lex->current_select->nest_level); + } + else if (thd->mark_used_columns != MARK_COLUMNS_NONE) + { + TABLE *table= field->table; + MY_BITMAP *current_bitmap, *other_bitmap; + if (thd->mark_used_columns == MARK_COLUMNS_READ) + { + current_bitmap= table->read_set; + other_bitmap= table->write_set; + } + else + { + current_bitmap= table->write_set; + other_bitmap= table->read_set; + } + if (!bitmap_fast_test_and_set(current_bitmap, field->field_index)) + { + if (!bitmap_is_set(other_bitmap, field->field_index)) + { + /* First usage of column */ + table->used_fields++; // Used to optimize loops + /* purecov: begin inspected */ + table->covering_keys.intersect(field->part_of_key); + /* purecov: end */ + } + } + } +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (any_privileges) + { + char *db, *tab; + db= cached_table->get_db_name(); + tab= cached_table->get_table_name(); + if (!(have_privileges= (get_column_grant(thd, &field->table->grant, + db, tab, field_name) & + VIEW_ANY_ACL))) + { + my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0), + "ANY", thd->security_ctx->priv_user, + thd->security_ctx->host_or_ip, field_name, tab); + goto error; + } + } +#endif + fixed= 1; + if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY && + !outer_fixed && !thd->lex->in_sum_func && + thd->lex->current_select->cur_pos_in_select_list != UNDEF_POS) + { + thd->lex->current_select->non_agg_fields.push_back(this); + marker= thd->lex->current_select->cur_pos_in_select_list; + } +mark_non_agg_field: + if (fixed && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) + { + /* + Mark selects according to presence of non aggregated fields. + Fields from outer selects added to the aggregate function + outer_fields list as its unknown at the moment whether it's + aggregated or not. + We're using either the select lex of the cached table (if present) + or the field's resolution context. context->select_lex is + safe for use because it's either the SELECT we want to use + (the current level) or a stub added by non-SELECT queries. + */ + SELECT_LEX *select_lex= cached_table ? + cached_table->select_lex : context->select_lex; + if (!thd->lex->in_sum_func) + select_lex->full_group_by_flag|= NON_AGG_FIELD_USED; + else + { + if (outer_fixed) + thd->lex->in_sum_func->outer_fields.push_back(this); + else if (thd->lex->in_sum_func->nest_level != + thd->lex->current_select->nest_level) + select_lex->full_group_by_flag|= NON_AGG_FIELD_USED; + } + } + return FALSE; + +error: + context->process_error(thd); + return TRUE; +} + + +Item *Item_field::safe_charset_converter(CHARSET_INFO *tocs) +{ + no_const_subst= 1; + return Item::safe_charset_converter(tocs); +} + + +void Item_field::cleanup() +{ + DBUG_ENTER("Item_field::cleanup"); + Item_ident::cleanup(); + /* + Even if this object was created by direct link to field in setup_wild() + it will be linked correctly next time by name of field and table alias. + I.e. we can drop 'field'. + */ + field= result_field= 0; + null_value= FALSE; + DBUG_VOID_RETURN; +} + +/** + Find a field among specified multiple equalities. + + The function first searches the field among multiple equalities + of the current level (in the cond_equal->current_level list). + If it fails, it continues searching in upper levels accessed + through a pointer cond_equal->upper_levels. + The search terminates as soon as a multiple equality containing + the field is found. + + @param cond_equal reference to list of multiple equalities where + the field (this object) is to be looked for + + @return + - First Item_equal containing the field, if success + - 0, otherwise +*/ + +Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal) +{ + Item_equal *item= 0; + while (cond_equal) + { + List_iterator_fast li(cond_equal->current_level); + while ((item= li++)) + { + if (item->contains(field)) + return item; + } + /* + The field is not found in any of the multiple equalities + of the current level. Look for it in upper levels + */ + cond_equal= cond_equal->upper_levels; + } + return 0; +} + + +/** + Check whether a field can be substituted by an equal item. + + The function checks whether a substitution of the field + occurrence for an equal item is valid. + + @param arg *arg != NULL <-> the field is in the context where + substitution for an equal item is valid + + @note + The following statement is not always true: + @n + x=y => F(x)=F(x/y). + @n + This means substitution of an item for an equal item not always + yields an equavalent condition. Here's an example: + @code + 'a'='a ' + (LENGTH('a')=1) != (LENGTH('a ')=2) + @endcode + Such a substitution is surely valid if either the substituted + field is not of a STRING type or if it is an argument of + a comparison predicate. + + @retval + TRUE substitution is valid + @retval + FALSE otherwise +*/ + +bool Item_field::subst_argument_checker(uchar **arg) +{ + return (result_type() != STRING_RESULT) || (*arg); +} + + +/** + Convert a numeric value to a zero-filled string + + @param[in,out] item the item to operate on + @param field The field that this value is equated to + + This function converts a numeric value to a string. In this conversion + the zero-fill flag of the field is taken into account. + This is required so the resulting string value can be used instead of + the field reference when propagating equalities. +*/ + +static void convert_zerofill_number_to_string(Item **item, Field_num *field) +{ + char buff[MAX_FIELD_WIDTH],*pos; + String tmp(buff,sizeof(buff), field->charset()), *res; + + res= (*item)->val_str(&tmp); + if ((*item)->is_null()) + *item= new Item_null(); + else + { + field->prepend_zeros(res); + pos= (char *) sql_strmake (res->ptr(), res->length()); + *item= new Item_string(pos, res->length(), field->charset()); + } +} + + +/** + Set a pointer to the multiple equality the field reference belongs to + (if any). + + The function looks for a multiple equality containing the field item + among those referenced by arg. + In the case such equality exists the function does the following. + If the found multiple equality contains a constant, then the field + reference is substituted for this constant, otherwise it sets a pointer + to the multiple equality in the field item. + + + @param arg reference to list of multiple equalities where + the field (this object) is to be looked for + + @note + This function is supposed to be called as a callback parameter in calls + of the compile method. + + @return + - pointer to the replacing constant item, if the field item was substituted + - pointer to the field item, otherwise. +*/ + +Item *Item_field::equal_fields_propagator(uchar *arg) +{ + if (no_const_subst) + return this; + item_equal= find_item_equal((COND_EQUAL *) arg); + Item *item= 0; + if (item_equal) + item= item_equal->get_const(); + /* + Disable const propagation for items used in different comparison contexts. + This must be done because, for example, Item_hex_string->val_int() is not + the same as (Item_hex_string->val_str() in BINARY column)->val_int(). + We cannot simply disable the replacement in a particular context ( + e.g. = AND = ) since + Items don't know the context they are in and there are functions like + IF (, 'yes', 'no'). + The same problem occurs when comparing a DATE/TIME field with a + DATE/TIME represented as an int and as a string. + */ + if (!item || + (cmp_context != (Item_result)-1 && item->cmp_context != cmp_context)) + item= this; + else if (field && (field->flags & ZEROFILL_FLAG) && IS_NUM(field->type())) + { + /* + We don't need to zero-fill timestamp columns here because they will be + first converted to a string (in date/time format) and compared as such if + compared with another string. + */ + if (item && field->type() != FIELD_TYPE_TIMESTAMP && cmp_context != INT_RESULT) + convert_zerofill_number_to_string(&item, (Field_num *)field); + else + item= this; + } + return item; +} + + +/** + Mark the item to not be part of substitution if it's not a binary item. + + See comments in Arg_comparator::set_compare_func() for details. +*/ + +bool Item_field::set_no_const_sub(uchar *arg) +{ + if (field->charset() != &my_charset_bin) + no_const_subst=1; + return FALSE; +} + + +/** + Replace an Item_field for an equal Item_field that evaluated earlier + (if any). + + The function returns a pointer to an item that is taken from + the very beginning of the item_equal list which the Item_field + object refers to (belongs to) unless item_equal contains a constant + item. In this case the function returns this constant item, + (if the substitution does not require conversion). + If the Item_field object does not refer any Item_equal object + 'this' is returned . + + @param arg a dummy parameter, is not used here + + + @note + This function is supposed to be called as a callback parameter in calls + of the thransformer method. + + @return + - pointer to a replacement Item_field if there is a better equal item or + a pointer to a constant equal item; + - this - otherwise. +*/ + +Item *Item_field::replace_equal_field(uchar *arg) +{ + if (item_equal) + { + Item *const_item= item_equal->get_const(); + if (const_item) + { + if (cmp_context != (Item_result)-1 && + const_item->cmp_context != cmp_context) + return this; + return const_item; + } + Item_field *subst= item_equal->get_first(); + if (subst && field->table != subst->field->table && !field->eq(subst->field)) + return subst; + } + return this; +} + + +void Item::init_make_field(Send_field *tmp_field, + enum enum_field_types field_type_arg) +{ + char *empty_name= (char*) ""; + tmp_field->db_name= empty_name; + tmp_field->org_table_name= empty_name; + tmp_field->org_col_name= empty_name; + tmp_field->table_name= empty_name; + tmp_field->col_name= name; + tmp_field->charsetnr= collation.collation->number; + tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) | + (my_binary_compare(collation.collation) ? + BINARY_FLAG : 0); + tmp_field->type= field_type_arg; + tmp_field->length=max_length; + tmp_field->decimals=decimals; + if (unsigned_flag) + tmp_field->flags |= UNSIGNED_FLAG; +} + +void Item::make_field(Send_field *tmp_field) +{ + init_make_field(tmp_field, field_type()); +} + + +enum_field_types Item::string_field_type() const +{ + enum_field_types f_type= MYSQL_TYPE_VAR_STRING; + if (max_length >= 16777216) + f_type= MYSQL_TYPE_LONG_BLOB; + else if (max_length >= 65536) + f_type= MYSQL_TYPE_MEDIUM_BLOB; + return f_type; +} + + +void Item_empty_string::make_field(Send_field *tmp_field) +{ + init_make_field(tmp_field, string_field_type()); +} + + +enum_field_types Item::field_type() const +{ + switch (result_type()) { + case STRING_RESULT: return string_field_type(); + case INT_RESULT: return MYSQL_TYPE_LONGLONG; + case DECIMAL_RESULT: return MYSQL_TYPE_NEWDECIMAL; + case REAL_RESULT: return MYSQL_TYPE_DOUBLE; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + return MYSQL_TYPE_VARCHAR; + } +} + + +bool Item::is_datetime() +{ + switch (field_type()) + { + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_DATETIME: + case MYSQL_TYPE_TIMESTAMP: + return TRUE; + default: + break; + } + return FALSE; +} + + +String *Item::check_well_formed_result(String *str, bool send_error) +{ + /* Check whether we got a well-formed string */ + CHARSET_INFO *cs= str->charset(); + int well_formed_error; + uint wlen= cs->cset->well_formed_len(cs, + str->ptr(), str->ptr() + str->length(), + str->length(), &well_formed_error); + if (wlen < str->length()) + { + THD *thd= current_thd; + char hexbuf[7]; + enum MYSQL_ERROR::enum_warning_level level; + uint diff= str->length() - wlen; + set_if_smaller(diff, 3); + octet2hex(hexbuf, str->ptr() + wlen, diff); + if (send_error) + { + my_error(ER_INVALID_CHARACTER_STRING, MYF(0), + cs->csname, hexbuf); + return 0; + } + if ((thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES))) + { + level= MYSQL_ERROR::WARN_LEVEL_ERROR; + null_value= 1; + str= 0; + } + else + { + level= MYSQL_ERROR::WARN_LEVEL_WARN; + str->length(wlen); + } + push_warning_printf(thd, level, ER_INVALID_CHARACTER_STRING, + ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf); + } + return str; +} + +/* + Compare two items using a given collation + + SYNOPSIS + eq_by_collation() + item item to compare with + binary_cmp TRUE <-> compare as binaries + cs collation to use when comparing strings + + DESCRIPTION + This method works exactly as Item::eq if the collation cs coincides with + the collation of the compared objects. Otherwise, first the collations that + differ from cs are replaced for cs and then the items are compared by + Item::eq. After the comparison the original collations of items are + restored. + + RETURN + 1 compared items has been detected as equal + 0 otherwise +*/ + +bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs) +{ + CHARSET_INFO *save_cs= 0; + CHARSET_INFO *save_item_cs= 0; + if (collation.collation != cs) + { + save_cs= collation.collation; + collation.collation= cs; + } + if (item->collation.collation != cs) + { + save_item_cs= item->collation.collation; + item->collation.collation= cs; + } + bool res= eq(item, binary_cmp); + if (save_cs) + collation.collation= save_cs; + if (save_item_cs) + item->collation.collation= save_item_cs; + return res; +} + + +/** + Create a field to hold a string value from an item. + + If max_length > CONVERT_IF_BIGGER_TO_BLOB create a blob @n + If max_length > 0 create a varchar @n + If max_length == 0 create a CHAR(0) + + @param table Table for which the field is created +*/ + +Field *Item::make_string_field(TABLE *table, THD* IDB_thd) +{ + Field *field; + DBUG_ASSERT(collation.collation); + + //@InfiniDB @bug3720 + //@InfiniDB @bug3783 + //@InfiniDB @bug5956 + //pass thd here for vtable state checking. skip creating blob field for vtable creation. + bool skipBlob = false; + if (IDB_thd) + { + if (IDB_thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE) + { + skipBlob = true; + } + else + { + TABLE_LIST* global_list = IDB_thd->lex->query_tables; + for (; global_list; global_list = global_list->next_global) + { + if (global_list->table && global_list->table->isInfiniDB()) + { + skipBlob = true; + break; + } + } + } + } + else if (!IDB_thd && type() == Item::SUM_FUNC_ITEM && ((Item_sum*)this)->thd() && + ((Item_sum*)this)->thd()->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE) + { + skipBlob = true; + } + + if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB && !skipBlob) + field= new Field_blob(max_length, maybe_null, name, + collation.collation); + /* Item_type_holder holds the exact type, do not change it */ + else if (max_length > 0 && + (type() != Item::TYPE_HOLDER || field_type() != MYSQL_TYPE_STRING)) + field= new Field_varstring(max_length, maybe_null, name, table->s, + collation.collation); + else + field= new Field_string(max_length, maybe_null, name, + collation.collation); + if (field) + field->init(table); + return field; +} + + +/** + Create a field based on field_type of argument. + + For now, this is only used to create a field for + IFNULL(x,something) and time functions + + @retval + NULL error + @retval + \# Created field +*/ + +Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length, THD* IDB_thd) +{ + /* + The field functions defines a field to be not null if null_ptr is not 0 + */ + uchar *null_ptr= maybe_null ? (uchar*) "" : 0; + Field *field; + + switch (field_type()) { + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_NEWDECIMAL: + field= Field_new_decimal::new_decimal_field(this); + break; + case MYSQL_TYPE_TINY: + field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, 0, unsigned_flag); + break; + case MYSQL_TYPE_SHORT: + field= new Field_short((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, 0, unsigned_flag); + break; + case MYSQL_TYPE_LONG: + field= new Field_long((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, 0, unsigned_flag); + break; +#ifdef HAVE_LONG_LONG + case MYSQL_TYPE_LONGLONG: + field= new Field_longlong((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, 0, unsigned_flag); + break; +#endif + case MYSQL_TYPE_FLOAT: + field= new Field_float((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, decimals, 0, unsigned_flag); + break; + case MYSQL_TYPE_DOUBLE: + field= new Field_double((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, decimals, 0, unsigned_flag); + break; + case MYSQL_TYPE_NULL: + field= new Field_null((uchar*) 0, max_length, Field::NONE, + name, &my_charset_bin); + break; + case MYSQL_TYPE_INT24: + field= new Field_medium((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name, 0, unsigned_flag); + break; + case MYSQL_TYPE_NEWDATE: + case MYSQL_TYPE_DATE: + field= new Field_newdate(maybe_null, name, &my_charset_bin); + break; + case MYSQL_TYPE_TIME: + field= new Field_time(maybe_null, name, &my_charset_bin); + break; + case MYSQL_TYPE_TIMESTAMP: + field= new Field_timestamp(maybe_null, name, &my_charset_bin); + break; + case MYSQL_TYPE_DATETIME: + field= new Field_datetime(maybe_null, name, &my_charset_bin); + break; + case MYSQL_TYPE_YEAR: + field= new Field_year((uchar*) 0, max_length, null_ptr, 0, Field::NONE, + name); + break; + case MYSQL_TYPE_BIT: + field= new Field_bit_as_char(NULL, max_length, null_ptr, 0, + Field::NONE, name); + break; + default: + /* This case should never be chosen */ + DBUG_ASSERT(0); + /* If something goes awfully wrong, it's better to get a string than die */ + case MYSQL_TYPE_STRING: + if (fixed_length && max_length < CONVERT_IF_BIGGER_TO_BLOB) + { + field= new Field_string(max_length, maybe_null, name, + collation.collation); + break; + } + /* Fall through to make_string_field() */ + case MYSQL_TYPE_ENUM: + case MYSQL_TYPE_SET: + case MYSQL_TYPE_VAR_STRING: + case MYSQL_TYPE_VARCHAR: + return make_string_field(table, IDB_thd); //@infinidb pass in the thd pointer + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + if (this->type() == Item::TYPE_HOLDER) + field= new Field_blob(max_length, maybe_null, name, collation.collation, + 1); + else + field= new Field_blob(max_length, maybe_null, name, collation.collation); + break; // Blob handled outside of case +#ifdef HAVE_SPATIAL + case MYSQL_TYPE_GEOMETRY: + field= new Field_geom(max_length, maybe_null, + name, table->s, get_geometry_type()); +#endif /* HAVE_SPATIAL */ + } + if (field) + field->init(table); + return field; +} + + +/* ARGSUSED */ +void Item_field::make_field(Send_field *tmp_field) +{ + field->make_field(tmp_field); + DBUG_ASSERT(tmp_field->table_name != 0); + if (name) + tmp_field->col_name=name; // Use user supplied name + if (table_name) + tmp_field->table_name= table_name; + if (db_name) + tmp_field->db_name= db_name; +} + + +/** + Set a field's value from a item. +*/ + +void Item_field::save_org_in_field(Field *to) +{ + if (field->is_null()) + { + null_value=1; + set_field_to_null_with_conversions(to, 1); + } + else + { + to->set_notnull(); + field_conv(to,field); + null_value=0; + } +} + +int Item_field::save_in_field(Field *to, bool no_conversions) +{ + int res; + if (result_field->is_null()) + { + null_value=1; + res= set_field_to_null_with_conversions(to, no_conversions); + } + else + { + to->set_notnull(); + res= field_conv(to,result_field); + null_value=0; + } + return res; +} + + +/** + Store null in field. + + This is used on INSERT. + Allow NULL to be inserted in timestamp and auto_increment values. + + @param field Field where we want to store NULL + + @retval + 0 ok + @retval + 1 Field doesn't support NULL values and can't handle 'field = NULL' +*/ + +int Item_null::save_in_field(Field *field, bool no_conversions) +{ + return set_field_to_null_with_conversions(field, no_conversions); +} + + +/** + Store null in field. + + @param field Field where we want to store NULL + + @retval + 0 OK + @retval + 1 Field doesn't support NULL values +*/ + +int Item_null::save_safe_in_field(Field *field) +{ + return set_field_to_null(field); +} + + +/* + This implementation can lose str_value content, so if the + Item uses str_value to store something, it should + reimplement it's ::save_in_field() as Item_string, for example, does. + + Note: all Item_XXX::val_str(str) methods must NOT rely on the fact that + str != str_value. For example, see fix for bug #44743. +*/ + +int Item::save_in_field(Field *field, bool no_conversions) +{ + int error; + if (result_type() == STRING_RESULT || + (result_type() == REAL_RESULT && + field->result_type() == STRING_RESULT)) + { + String *result; + CHARSET_INFO *cs= collation.collation; + char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns + str_value.set_quick(buff, sizeof(buff), cs); + result=val_str(&str_value); + if (null_value) + { + str_value.set_quick(0, 0, cs); + return set_field_to_null_with_conversions(field, no_conversions); + } + + /* NOTE: If null_value == FALSE, "result" must be not NULL. */ + + field->set_notnull(); + error=field->store(result->ptr(),result->length(),cs); + str_value.set_quick(0, 0, cs); + } + else if (result_type() == REAL_RESULT) + { + double nr= val_real(); + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + error=field->store(nr); + } + else if (result_type() == DECIMAL_RESULT) + { + my_decimal decimal_value; + my_decimal *value= val_decimal(&decimal_value); + if (null_value) + return set_field_to_null_with_conversions(field, no_conversions); + field->set_notnull(); + error=field->store_decimal(value); + } + else + { + longlong nr=val_int(); + if (null_value) + return set_field_to_null_with_conversions(field, no_conversions); + field->set_notnull(); + error=field->store(nr, unsigned_flag); + } + return error; +} + + +int Item_string::save_in_field(Field *field, bool no_conversions) +{ + String *result; + result=val_str(&str_value); + return save_str_value_in_field(field, result); +} + + +int Item_uint::save_in_field(Field *field, bool no_conversions) +{ + /* Item_int::save_in_field handles both signed and unsigned. */ + return Item_int::save_in_field(field, no_conversions); +} + +static int save_int_value_in_field (Field *field, longlong nr, + bool null_value, bool unsigned_flag) +{ + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + return field->store(nr, unsigned_flag); +} + + +int Item_int::save_in_field(Field *field, bool no_conversions) +{ + return save_int_value_in_field (field, val_int(), null_value, unsigned_flag); +} + + +int Item_decimal::save_in_field(Field *field, bool no_conversions) +{ + field->set_notnull(); + return field->store_decimal(&decimal_value); +} + + +bool Item_int::eq(const Item *arg, bool binary_cmp) const +{ + /* No need to check for null value as basic constant can't be NULL */ + if (arg->basic_const_item() && arg->type() == type()) + { + /* + We need to cast off const to call val_int(). This should be OK for + a basic constant. + */ + Item *item= (Item*) arg; + return item->val_int() == value && item->unsigned_flag == unsigned_flag; + } + return FALSE; +} + + +Item *Item_int_with_ref::clone_item() +{ + DBUG_ASSERT(ref->const_item()); + /* + We need to evaluate the constant to make sure it works with + parameter markers. + */ + return (ref->unsigned_flag ? + new Item_uint(ref->name, ref->val_int(), ref->max_length) : + new Item_int(ref->name, ref->val_int(), ref->max_length)); +} + + +Item_num *Item_uint::neg() +{ + Item_decimal *item= new Item_decimal(value, 1); + return item->neg(); +} + + +static uint nr_of_decimals(const char *str, const char *end) +{ + const char *decimal_point; + + /* Find position for '.' */ + for (;;) + { + if (str == end) + return 0; + if (*str == 'e' || *str == 'E') + return NOT_FIXED_DEC; + if (*str++ == '.') + break; + } + decimal_point= str; + for (; my_isdigit(system_charset_info, *str) ; str++) + ; + if (*str == 'e' || *str == 'E') + return NOT_FIXED_DEC; + return (uint) (str - decimal_point); +} + + +/** + This function is only called during parsing. We will signal an error if + value is not a true double value (overflow) +*/ + +Item_float::Item_float(const char *str_arg, uint length) +{ + int error; + char *end_not_used; + value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used, + &error); + if (error) + { + /* + Note that we depend on that str_arg is null terminated, which is true + when we are in the parser + */ + DBUG_ASSERT(str_arg[length] == 0); + my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", (char*) str_arg); + } + presentation= name=(char*) str_arg; + decimals=(uint8) nr_of_decimals(str_arg, str_arg+length); + max_length=length; + fixed= 1; +} + + +int Item_float::save_in_field(Field *field, bool no_conversions) +{ + double nr= val_real(); + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + return field->store(nr); +} + + +void Item_float::print(String *str, enum_query_type query_type) +{ + if (presentation) + { + str->append(presentation); + return; + } + char buffer[20]; + String num(buffer, sizeof(buffer), &my_charset_bin); + num.set_real(value, decimals, &my_charset_bin); + str->append(num); +} + + +/* + hex item + In string context this is a binary string. + In number context this is a longlong value. +*/ + +bool Item_float::eq(const Item *arg, bool binary_cmp) const +{ + if (arg->basic_const_item() && arg->type() == type()) + { + /* + We need to cast off const to call val_int(). This should be OK for + a basic constant. + */ + Item *item= (Item*) arg; + return item->val_real() == value; + } + return FALSE; +} + + +inline uint char_val(char X) +{ + return (uint) (X >= '0' && X <= '9' ? X-'0' : + X >= 'A' && X <= 'Z' ? X-'A'+10 : + X-'a'+10); +} + + +Item_hex_string::Item_hex_string(const char *str, uint str_length) +{ + max_length=(str_length+1)/2; + char *ptr=(char*) sql_alloc(max_length+1); + if (!ptr) + return; + str_value.set(ptr,max_length,&my_charset_bin); + char *end=ptr+max_length; + if (max_length*2 != str_length) + *ptr++=char_val(*str++); // Not even, assume 0 prefix + while (ptr != end) + { + *ptr++= (char) (char_val(str[0])*16+char_val(str[1])); + str+=2; + } + *ptr=0; // Keep purify happy + collation.set(&my_charset_bin, DERIVATION_COERCIBLE); + fixed= 1; + unsigned_flag= 1; +} + +longlong Item_hex_string::val_int() +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + char *end=(char*) str_value.ptr()+str_value.length(), + *ptr=end-min(str_value.length(),sizeof(longlong)); + + ulonglong value=0; + for (; ptr != end ; ptr++) + value=(value << 8)+ (ulonglong) (uchar) *ptr; + return (longlong) value; +} + + +my_decimal *Item_hex_string::val_decimal(my_decimal *decimal_value) +{ + // following assert is redundant, because fixed=1 assigned in constructor + DBUG_ASSERT(fixed == 1); + ulonglong value= (ulonglong)val_int(); + int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value); + return (decimal_value); +} + + +int Item_hex_string::save_in_field(Field *field, bool no_conversions) +{ + field->set_notnull(); + if (field->result_type() == STRING_RESULT) + return field->store(str_value.ptr(), str_value.length(), + collation.collation); + + ulonglong nr; + uint32 length= str_value.length(); + if (!length) + return 1; + + if (length > 8) + { + nr= field->flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX; + goto warn; + } + nr= (ulonglong) val_int(); + if ((length == 8) && !(field->flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX)) + { + nr= LONGLONG_MAX; + goto warn; + } + return field->store((longlong) nr, TRUE); // Assume hex numbers are unsigned + +warn: + if (!field->store((longlong) nr, TRUE)) + field->set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, + 1); + return 1; +} + + +void Item_hex_string::print(String *str, enum_query_type query_type) +{ + char *end= (char*) str_value.ptr() + str_value.length(), + *ptr= end - min(str_value.length(), sizeof(longlong)); + str->append("0x"); + for (; ptr != end ; ptr++) + { + str->append(_dig_vec_lower[((uchar) *ptr) >> 4]); + str->append(_dig_vec_lower[((uchar) *ptr) & 0x0F]); + } +} + + +bool Item_hex_string::eq(const Item *arg, bool binary_cmp) const +{ + if (arg->basic_const_item() && arg->type() == type()) + { + if (binary_cmp) + return !stringcmp(&str_value, &arg->str_value); + return !sortcmp(&str_value, &arg->str_value, collation.collation); + } + return FALSE; +} + + +Item *Item_hex_string::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_string *conv; + String tmp, *str= val_str(&tmp); + + if (!(conv= new Item_string(str->ptr(), str->length(), tocs))) + return NULL; + conv->str_value.copy(); + conv->str_value.mark_as_const(); + return conv; +} + + +/* + bin item. + In string context this is a binary string. + In number context this is a longlong value. +*/ + +Item_bin_string::Item_bin_string(const char *str, uint str_length) +{ + const char *end= str + str_length - 1; + uchar bits= 0; + uint power= 1; + + max_length= (str_length + 7) >> 3; + char *ptr= (char*) sql_alloc(max_length + 1); + if (!ptr) + return; + str_value.set(ptr, max_length, &my_charset_bin); + + if (max_length > 0) + { + ptr+= max_length - 1; + ptr[1]= 0; // Set end null for string + for (; end >= str; end--) + { + if (power == 256) + { + power= 1; + *ptr--= bits; + bits= 0; + } + if (*end == '1') + bits|= power; + power<<= 1; + } + *ptr= (char) bits; + } + else + ptr[0]= 0; + + collation.set(&my_charset_bin, DERIVATION_COERCIBLE); + fixed= 1; +} + + +/** + Pack data in buffer for sending. +*/ + +bool Item_null::send(Protocol *protocol, String *packet) +{ + return protocol->store_null(); +} + +/** + This is only called from items that is not of type item_field. +*/ + +bool Item::send(Protocol *protocol, String *buffer) +{ + bool UNINIT_VAR(result); // Will be set if null_value == 0 + enum_field_types f_type; + + switch ((f_type=field_type())) { + default: + case MYSQL_TYPE_NULL: + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_ENUM: + case MYSQL_TYPE_SET: + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_GEOMETRY: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_VAR_STRING: + case MYSQL_TYPE_VARCHAR: + case MYSQL_TYPE_BIT: + case MYSQL_TYPE_NEWDECIMAL: + { + String *res; + if ((res=val_str(buffer))) + result= protocol->store(res->ptr(),res->length(),res->charset()); + break; + } + case MYSQL_TYPE_TINY: + { + longlong nr; + nr= val_int(); + if (!null_value) + result= protocol->store_tiny(nr); + break; + } + case MYSQL_TYPE_SHORT: + case MYSQL_TYPE_YEAR: + { + longlong nr; + nr= val_int(); + if (!null_value) + result= protocol->store_short(nr); + break; + } + case MYSQL_TYPE_INT24: + case MYSQL_TYPE_LONG: + { + longlong nr; + nr= val_int(); + if (!null_value) + result= protocol->store_long(nr); + break; + } + case MYSQL_TYPE_LONGLONG: + { + longlong nr; + nr= val_int(); + if (!null_value) + result= protocol->store_longlong(nr, unsigned_flag); + break; + } + case MYSQL_TYPE_FLOAT: + { + float nr; + nr= (float) val_real(); + if (!null_value) + result= protocol->store(nr, decimals, buffer); + break; + } + case MYSQL_TYPE_DOUBLE: + { + double nr= val_real(); + if (!null_value) + result= protocol->store(nr, decimals, buffer); + break; + } + case MYSQL_TYPE_DATETIME: + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_TIMESTAMP: + { + MYSQL_TIME tm; + get_date(&tm, TIME_FUZZY_DATE); + if (!null_value) + { + if (f_type == MYSQL_TYPE_DATE) + return protocol->store_date(&tm); + else + result= protocol->store(&tm); + } + break; + } + case MYSQL_TYPE_TIME: + { + MYSQL_TIME tm; + get_time(&tm); + if (!null_value) + result= protocol->store_time(&tm); + break; + } + } + if (null_value) + result= protocol->store_null(); + return result; +} + + +bool Item_field::send(Protocol *protocol, String *buffer) +{ + return protocol->store(result_field); +} + + +void Item_field::update_null_value() +{ + /* + need to set no_errors to prevent warnings about type conversion + popping up. + */ + THD *thd= field->table->in_use; + int no_errors; + + no_errors= thd->no_errors; + thd->no_errors= 1; + Item::update_null_value(); + thd->no_errors= no_errors; +} + + +/* + Add the field to the select list and substitute it for the reference to + the field. + + SYNOPSIS + Item_field::update_value_transformer() + select_arg current select + + DESCRIPTION + If the field doesn't belong to the table being inserted into then it is + added to the select list, pointer to it is stored in the ref_pointer_array + of the select and the field itself is substituted for the Item_ref object. + This is done in order to get correct values from update fields that + belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY + UPDATE statement. + + RETURN + 0 if error occured + ref if all conditions are met + this field otherwise +*/ + +Item *Item_field::update_value_transformer(uchar *select_arg) +{ + SELECT_LEX *select= (SELECT_LEX*)select_arg; + DBUG_ASSERT(fixed); + + if (field->table != select->context.table_list->table && + type() != Item::TRIGGER_FIELD_ITEM) + { + List *all_fields= &select->join->all_fields; + Item **ref_pointer_array= select->ref_pointer_array; + int el= all_fields->elements; + Item_ref *ref; + + ref_pointer_array[el]= (Item*)this; + all_fields->push_front((Item*)this); + ref= new Item_ref(&select->context, ref_pointer_array + el, + table_name, field_name); + return ref; + } + return this; +} + + +void Item_field::print(String *str, enum_query_type query_type) +{ + // @InfiniDB + if (field && field->table && field->table->const_table && field->table->const_table != 1) + { + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff),str->charset()); + field->val_str(&tmp); + str->append('\''); + str->append(tmp); + str->append('\''); + return; + } + Item_ident::print(str, query_type); +} + + +Item_ref::Item_ref(Name_resolution_context *context_arg, + Item **item, const char *table_name_arg, + const char *field_name_arg, + bool alias_name_used_arg) + :Item_ident(context_arg, NullS, table_name_arg, field_name_arg), + result_field(0), ref(item) +{ + alias_name_used= alias_name_used_arg; + /* + This constructor used to create some internals references over fixed items + */ + if (ref && *ref && (*ref)->fixed) + set_properties(); +} + + +/** + Resolve the name of a reference to a column reference. + + The method resolves the column reference represented by 'this' as a column + present in one of: GROUP BY clause, SELECT clause, outer queries. It is + used typically for columns in the HAVING clause which are not under + aggregate functions. + + POSTCONDITION @n + Item_ref::ref is 0 or points to a valid item. + + @note + The name resolution algorithm used is (where [T_j] is an optional table + name that qualifies the column name): + + @code + resolve_extended([T_j].col_ref_i) + { + Search for a column or derived column named col_ref_i [in table T_j] + in the SELECT and GROUP clauses of Q. + + if such a column is NOT found AND // Lookup in outer queries. + there are outer queries + { + for each outer query Q_k beginning from the inner-most one + { + Search for a column or derived column named col_ref_i + [in table T_j] in the SELECT and GROUP clauses of Q_k. + + if such a column is not found AND + - Q_k is not a group query AND + - Q_k is not inside an aggregate function + OR + - Q_(k-1) is not in a HAVING or SELECT clause of Q_k + { + search for a column or derived column named col_ref_i + [in table T_j] in the FROM clause of Q_k; + } + } + } + } + @endcode + @n + This procedure treats GROUP BY and SELECT clauses as one namespace for + column references in HAVING. Notice that compared to + Item_field::fix_fields, here we first search the SELECT and GROUP BY + clauses, and then we search the FROM clause. + + @param[in] thd current thread + @param[in,out] reference view column if this item was resolved to a + view column + + @todo + Here we could first find the field anyway, and then test this + condition, so that we can give a better error message - + ER_WRONG_FIELD_WITH_GROUP, instead of the less informative + ER_BAD_FIELD_ERROR which we produce now. + + @retval + TRUE if error + @retval + FALSE on success +*/ + +bool Item_ref::fix_fields(THD *thd, Item **reference) +{ + enum_parsing_place place= NO_MATTER; + DBUG_ASSERT(fixed == 0); + SELECT_LEX *current_sel= thd->lex->current_select; + + if (!ref || ref == not_found_item) + { + if (!(ref= resolve_ref_in_select_and_group(thd, this, + context->select_lex))) + goto error; /* Some error occurred (e.g. ambiguous names). */ + + if (ref == not_found_item) /* This reference was not resolved. */ + { + Name_resolution_context *last_checked_context= context; + Name_resolution_context *outer_context= context->outer_context; + Field *from_field; + ref= 0; + + if (!outer_context) + { + /* The current reference cannot be resolved in this query. */ + my_error(ER_BAD_FIELD_ERROR,MYF(0), + this->full_name(), current_thd->where); + goto error; + } + + /* + If there is an outer context (select), and it is not a derived table + (which do not support the use of outer fields for now), try to + resolve this reference in the outer select(s). + + We treat each subselect as a separate namespace, so that different + subselects may contain columns with the same names. The subselects are + searched starting from the innermost. + */ + from_field= (Field*) not_found_field; + + do + { + SELECT_LEX *select= outer_context->select_lex; + Item_subselect *prev_subselect_item= + last_checked_context->select_lex->master_unit()->item; + last_checked_context= outer_context; + + /* Search in the SELECT and GROUP lists of the outer select. */ + if (outer_context->resolve_in_select_list) + { + if (!(ref= resolve_ref_in_select_and_group(thd, this, select))) + goto error; /* Some error occurred (e.g. ambiguous names). */ + if (ref != not_found_item) + { + DBUG_ASSERT(*ref && (*ref)->fixed); + prev_subselect_item->used_tables_cache|= (*ref)->used_tables(); + prev_subselect_item->const_item_cache&= (*ref)->const_item(); + break; + } + /* + Set ref to 0 to ensure that we get an error in case we replaced + this item with another item and still use this item in some + other place of the parse tree. + */ + ref= 0; + } + + place= prev_subselect_item->parsing_place; + /* + Check table fields only if the subquery is used somewhere out of + HAVING or the outer SELECT does not use grouping (i.e. tables are + accessible). + TODO: + Here we could first find the field anyway, and then test this + condition, so that we can give a better error message - + ER_WRONG_FIELD_WITH_GROUP, instead of the less informative + ER_BAD_FIELD_ERROR which we produce now. + */ + if ((place != IN_HAVING || + (!select->with_sum_func && + select->group_list.elements == 0))) + { + /* + In case of view, find_field_in_tables() write pointer to view + field expression to 'reference', i.e. it substitute that + expression instead of this Item_ref + */ + from_field= find_field_in_tables(thd, this, + outer_context-> + first_name_resolution_table, + outer_context-> + last_name_resolution_table, + reference, + IGNORE_EXCEPT_NON_UNIQUE, + TRUE, TRUE); + if (! from_field) + goto error; + if (from_field == view_ref_found) + { + Item::Type refer_type= (*reference)->type(); + prev_subselect_item->used_tables_cache|= + (*reference)->used_tables(); + prev_subselect_item->const_item_cache&= + (*reference)->const_item(); + DBUG_ASSERT((*reference)->type() == REF_ITEM); + mark_as_dependent(thd, last_checked_context->select_lex, + context->select_lex, this, + ((refer_type == REF_ITEM || + refer_type == FIELD_ITEM) ? + (Item_ident*) (*reference) : + 0)); + /* + view reference found, we substituted it instead of this + Item, so can quit + */ + return FALSE; + } + if (from_field != not_found_field) + { + if (cached_table && cached_table->select_lex && + outer_context->select_lex && + cached_table->select_lex != outer_context->select_lex) + { + /* + Due to cache, find_field_in_tables() can return field which + doesn't belong to provided outer_context. In this case we have + to find proper field context in order to fix field correcly. + */ + do + { + outer_context= outer_context->outer_context; + select= outer_context->select_lex; + prev_subselect_item= + last_checked_context->select_lex->master_unit()->item; + last_checked_context= outer_context; + } while (outer_context && outer_context->select_lex && + cached_table->select_lex != outer_context->select_lex); + } + prev_subselect_item->used_tables_cache|= from_field->table->map; + prev_subselect_item->const_item_cache= 0; + break; + } + } + DBUG_ASSERT(from_field == not_found_field); + + /* Reference is not found => depend on outer (or just error). */ + prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT; + prev_subselect_item->const_item_cache= 0; + + outer_context= outer_context->outer_context; + } while (outer_context); + + DBUG_ASSERT(from_field != 0 && from_field != view_ref_found); + if (from_field != not_found_field) + { + Item_field* fld; + if (!(fld= new Item_field(from_field))) + goto error; + thd->change_item_tree(reference, fld); + mark_as_dependent(thd, last_checked_context->select_lex, + thd->lex->current_select, this, fld); + /* + A reference is resolved to a nest level that's outer or the same as + the nest level of the enclosing set function : adjust the value of + max_arg_level for the function if it's needed. + */ + if (thd->lex->in_sum_func && + thd->lex->in_sum_func->nest_level >= + last_checked_context->select_lex->nest_level) + set_if_bigger(thd->lex->in_sum_func->max_arg_level, + last_checked_context->select_lex->nest_level); + return FALSE; + } + if (ref == 0) + { + /* The item was not a table field and not a reference */ + my_error(ER_BAD_FIELD_ERROR, MYF(0), + this->full_name(), current_thd->where); + goto error; + } + /* Should be checked in resolve_ref_in_select_and_group(). */ + DBUG_ASSERT(*ref && (*ref)->fixed); + mark_as_dependent(thd, last_checked_context->select_lex, + context->select_lex, this, this); + /* + A reference is resolved to a nest level that's outer or the same as + the nest level of the enclosing set function : adjust the value of + max_arg_level for the function if it's needed. + */ + if (thd->lex->in_sum_func && + thd->lex->in_sum_func->nest_level >= + last_checked_context->select_lex->nest_level) + set_if_bigger(thd->lex->in_sum_func->max_arg_level, + last_checked_context->select_lex->nest_level); + } + } + + DBUG_ASSERT(*ref); + /* + Check if this is an incorrect reference in a group function or forward + reference. Do not issue an error if this is: + 1. outer reference (will be fixed later by the fix_inner_refs function); + 2. an unnamed reference inside an aggregate function. + */ + if (!((*ref)->type() == REF_ITEM && + ((Item_ref *)(*ref))->ref_type() == OUTER_REF) && + (((*ref)->with_sum_func && name && + !(current_sel->linkage != GLOBAL_OPTIONS_TYPE && + current_sel->having_fix_field)) || + !(*ref)->fixed)) + { + my_error(ER_ILLEGAL_REFERENCE, MYF(0), + name, ((*ref)->with_sum_func? + "reference to group function": + "forward reference in item list")); + goto error; + } + + set_properties(); + + if ((*ref)->check_cols(1)) + goto error; + return FALSE; + +error: + context->process_error(thd); + return TRUE; +} + + +void Item_ref::set_properties() +{ + max_length= (*ref)->max_length; + maybe_null= (*ref)->maybe_null; + decimals= (*ref)->decimals; + collation.set((*ref)->collation); + /* + We have to remember if we refer to a sum function, to ensure that + split_sum_func() doesn't try to change the reference. + */ + with_sum_func= (*ref)->with_sum_func; + unsigned_flag= (*ref)->unsigned_flag; + fixed= 1; + if (alias_name_used) + return; + if ((*ref)->type() == FIELD_ITEM) + alias_name_used= ((Item_ident *) (*ref))->alias_name_used; + else + alias_name_used= TRUE; // it is not field, so it is was resolved by alias +} + + +void Item_ref::cleanup() +{ + DBUG_ENTER("Item_ref::cleanup"); + Item_ident::cleanup(); + result_field= 0; + DBUG_VOID_RETURN; +} + + +void Item_ref::print(String *str, enum_query_type query_type) +{ + if (ref) + { + if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF && + !table_name && name && alias_name_used) + { + THD *thd= current_thd; + append_identifier(thd, str, (*ref)->real_item()->name, + (*ref)->real_item()->name_length); + } + else + (*ref)->print(str, query_type); + } + else + Item_ident::print(str, query_type); +} + + +bool Item_ref::send(Protocol *prot, String *tmp) +{ + if (result_field) + return prot->store(result_field); + return (*ref)->send(prot, tmp); +} + + +double Item_ref::val_result() +{ + if (result_field) + { + if ((null_value= result_field->is_null())) + return 0.0; + return result_field->val_real(); + } + return val_real(); +} + + +bool Item_ref::is_null_result() +{ + if (result_field) + return (null_value=result_field->is_null()); + + return is_null(); +} + + +longlong Item_ref::val_int_result() +{ + if (result_field) + { + if ((null_value= result_field->is_null())) + return 0; + return result_field->val_int(); + } + return val_int(); +} + + +String *Item_ref::str_result(String* str) +{ + if (result_field) + { + if ((null_value= result_field->is_null())) + return 0; + str->set_charset(str_value.charset()); + return result_field->val_str(str, &str_value); + } + return val_str(str); +} + + +my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value) +{ + if (result_field) + { + if ((null_value= result_field->is_null())) + return 0; + return result_field->val_decimal(decimal_value); + } + return val_decimal(decimal_value); +} + + +bool Item_ref::val_bool_result() +{ + if (result_field) + { + if ((null_value= result_field->is_null())) + return 0; + switch (result_field->result_type()) { + case INT_RESULT: + return result_field->val_int() != 0; + case DECIMAL_RESULT: + { + my_decimal decimal_value; + my_decimal *val= result_field->val_decimal(&decimal_value); + if (val) + return !my_decimal_is_zero(val); + return 0; + } + case REAL_RESULT: + case STRING_RESULT: + return result_field->val_real() != 0.0; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + } + return val_bool(); +} + + +double Item_ref::val_real() +{ + DBUG_ASSERT(fixed); + double tmp=(*ref)->val_result(); + null_value=(*ref)->null_value; + return tmp; +} + + +longlong Item_ref::val_int() +{ + DBUG_ASSERT(fixed); + longlong tmp=(*ref)->val_int_result(); + null_value=(*ref)->null_value; + return tmp; +} + + +bool Item_ref::val_bool() +{ + DBUG_ASSERT(fixed); + bool tmp= (*ref)->val_bool_result(); + null_value= (*ref)->null_value; + return tmp; +} + + +String *Item_ref::val_str(String* tmp) +{ + DBUG_ASSERT(fixed); + tmp=(*ref)->str_result(tmp); + null_value=(*ref)->null_value; + return tmp; +} + + +bool Item_ref::is_null() +{ + DBUG_ASSERT(fixed); + bool tmp=(*ref)->is_null_result(); + null_value=(*ref)->null_value; + return tmp; +} + + +bool Item_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate) +{ + return (null_value=(*ref)->get_date_result(ltime,fuzzydate)); +} + + +my_decimal *Item_ref::val_decimal(my_decimal *decimal_value) +{ + my_decimal *val= (*ref)->val_decimal_result(decimal_value); + null_value= (*ref)->null_value; + return val; +} + +int Item_ref::save_in_field(Field *to, bool no_conversions) +{ + int res; + DBUG_ASSERT(!result_field); + res= (*ref)->save_in_field(to, no_conversions); + null_value= (*ref)->null_value; + return res; +} + + +void Item_ref::save_org_in_field(Field *field) +{ + (*ref)->save_org_in_field(field); +} + + +void Item_ref::make_field(Send_field *field) +{ + (*ref)->make_field(field); + /* Non-zero in case of a view */ + if (name) + field->col_name= name; + if (table_name) + field->table_name= table_name; + if (db_name) + field->db_name= db_name; + if (orig_field_name) + field->org_col_name= orig_field_name; + if (orig_table_name) + field->org_table_name= orig_table_name; +} + + +Item *Item_ref::get_tmp_table_item(THD *thd) +{ + if (!result_field) + return (*ref)->get_tmp_table_item(thd); + + Item_field *item= new Item_field(result_field); + if (item) + { + item->table_name= table_name; + item->db_name= db_name; + } + return item; +} + + +void Item_ref_null_helper::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("(")); + if (ref) + (*ref)->print(str, query_type); + else + str->append('?'); + str->append(')'); +} + + +double Item_direct_ref::val_real() +{ + double tmp=(*ref)->val_real(); + null_value=(*ref)->null_value; + return tmp; +} + + +longlong Item_direct_ref::val_int() +{ + longlong tmp=(*ref)->val_int(); + null_value=(*ref)->null_value; + return tmp; +} + + +String *Item_direct_ref::val_str(String* tmp) +{ + tmp=(*ref)->val_str(tmp); + null_value=(*ref)->null_value; + return tmp; +} + + +my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value) +{ + my_decimal *tmp= (*ref)->val_decimal(decimal_value); + null_value=(*ref)->null_value; + return tmp; +} + + +bool Item_direct_ref::val_bool() +{ + bool tmp= (*ref)->val_bool(); + null_value=(*ref)->null_value; + return tmp; +} + + +bool Item_direct_ref::is_null() +{ + return (*ref)->is_null(); +} + + +bool Item_direct_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate) +{ + return (null_value=(*ref)->get_date(ltime,fuzzydate)); +} + + +/** + Prepare referenced field then call usual Item_direct_ref::fix_fields . + + @param thd thread handler + @param reference reference on reference where this item stored + + @retval + FALSE OK + @retval + TRUE Error +*/ + +bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference) +{ + /* view fild reference must be defined */ + DBUG_ASSERT(*ref); + /* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */ + if (!(*ref)->fixed && + ((*ref)->fix_fields(thd, ref))) + return TRUE; + return Item_direct_ref::fix_fields(thd, reference); +} + +/* + Prepare referenced outer field then call usual Item_direct_ref::fix_fields + + SYNOPSIS + Item_outer_ref::fix_fields() + thd thread handler + reference reference on reference where this item stored + + RETURN + FALSE OK + TRUE Error +*/ + +bool Item_outer_ref::fix_fields(THD *thd, Item **reference) +{ + bool err; + /* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */ + if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference))) + return TRUE; + err= Item_direct_ref::fix_fields(thd, reference); + if (!outer_ref) + outer_ref= *ref; + if ((*ref)->type() == Item::FIELD_ITEM) + table_name= ((Item_field*)outer_ref)->table_name; + return err; +} + + +/** + Compare two view column references for equality. + + A view column reference is considered equal to another column + reference if the second one is a view column and if both column + references resolve to the same item. It is assumed that both + items are of the same type. + + @param item item to compare with + @param binary_cmp make binary comparison + + @retval + TRUE Referenced item is equal to given item + @retval + FALSE otherwise +*/ + +bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const +{ + if (item->type() == REF_ITEM) + { + Item_ref *item_ref= (Item_ref*) item; + if (item_ref->ref_type() == VIEW_REF) + { + Item *item_ref_ref= *(item_ref->ref); + return ((*ref)->real_item() == item_ref_ref->real_item()); + } + } + return FALSE; +} + +bool Item_default_value::eq(const Item *item, bool binary_cmp) const +{ + return item->type() == DEFAULT_VALUE_ITEM && + ((Item_default_value *)item)->arg->eq(arg, binary_cmp); +} + + +bool Item_default_value::fix_fields(THD *thd, Item **items) +{ + Item *real_arg; + Item_field *field_arg; + Field *def_field; + DBUG_ASSERT(fixed == 0); + + if (!arg) + { + fixed= 1; + return FALSE; + } + if (!arg->fixed && arg->fix_fields(thd, &arg)) + goto error; + + + real_arg= arg->real_item(); + if (real_arg->type() != FIELD_ITEM) + { + my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name); + goto error; + } + + field_arg= (Item_field *)real_arg; + if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG) + { + my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name); + goto error; + } + if (!(def_field= (Field*) sql_alloc(field_arg->field->size_of()))) + goto error; + memcpy(def_field, field_arg->field, field_arg->field->size_of()); + def_field->move_field_offset((my_ptrdiff_t) + (def_field->table->s->default_values - + def_field->table->record[0])); + set_field(def_field); + return FALSE; + +error: + context->process_error(thd); + return TRUE; +} + + +void Item_default_value::print(String *str, enum_query_type query_type) +{ + if (!arg) + { + str->append(STRING_WITH_LEN("default")); + return; + } + str->append(STRING_WITH_LEN("default(")); + arg->print(str, query_type); + str->append(')'); +} + + +int Item_default_value::save_in_field(Field *field_arg, bool no_conversions) +{ + if (!arg) + { + if (field_arg->flags & NO_DEFAULT_VALUE_FLAG) + { + if (field_arg->reset()) + { + my_message(ER_CANT_CREATE_GEOMETRY_OBJECT, + ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0)); + return -1; + } + + if (context->error_processor == &view_error_processor) + { + TABLE_LIST *view= cached_table->top_table(); + push_warning_printf(field_arg->table->in_use, + MYSQL_ERROR::WARN_LEVEL_WARN, + ER_NO_DEFAULT_FOR_VIEW_FIELD, + ER(ER_NO_DEFAULT_FOR_VIEW_FIELD), + view->view_db.str, + view->view_name.str); + } + else + { + push_warning_printf(field_arg->table->in_use, + MYSQL_ERROR::WARN_LEVEL_WARN, + ER_NO_DEFAULT_FOR_FIELD, + ER(ER_NO_DEFAULT_FOR_FIELD), + field_arg->field_name); + } + return 1; + } + field_arg->set_default(); + return 0; + } + return Item_field::save_in_field(field_arg, no_conversions); +} + + +/** + This method like the walk method traverses the item tree, but at the + same time it can replace some nodes in the tree. +*/ + +Item *Item_default_value::transform(Item_transformer transformer, uchar *args) +{ + DBUG_ASSERT(!current_thd->is_stmt_prepare()); + + /* + If the value of arg is NULL, then this object represents a constant, + so further transformation is unnecessary (and impossible). + */ + if (!arg) + return 0; + + Item *new_item= arg->transform(transformer, args); + if (!new_item) + return 0; + + /* + THD::change_item_tree() should be called only if the tree was + really transformed, i.e. when a new item has been created. + Otherwise we'll be allocating a lot of unnecessary memory for + change records at each execution. + */ + if (arg != new_item) + current_thd->change_item_tree(&arg, new_item); + return (this->*transformer)(args); +} + + +bool Item_insert_value::eq(const Item *item, bool binary_cmp) const +{ + return item->type() == INSERT_VALUE_ITEM && + ((Item_default_value *)item)->arg->eq(arg, binary_cmp); +} + + +bool Item_insert_value::fix_fields(THD *thd, Item **items) +{ + DBUG_ASSERT(fixed == 0); + /* We should only check that arg is in first table */ + if (!arg->fixed) + { + bool res; + TABLE_LIST *orig_next_table= context->last_name_resolution_table; + context->last_name_resolution_table= context->first_name_resolution_table; + res= arg->fix_fields(thd, &arg); + context->last_name_resolution_table= orig_next_table; + if (res) + return TRUE; + } + + if (arg->type() == REF_ITEM) + { + Item_ref *ref= (Item_ref *)arg; + if (ref->ref[0]->type() != FIELD_ITEM) + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function"); + return TRUE; + } + arg= ref->ref[0]; + } + /* + According to our SQL grammar, VALUES() function can reference + only to a column. + */ + DBUG_ASSERT(arg->type() == FIELD_ITEM); + + Item_field *field_arg= (Item_field *)arg; + + if (field_arg->field->table->insert_values) + { + Field *def_field= (Field*) sql_alloc(field_arg->field->size_of()); + if (!def_field) + return TRUE; + memcpy(def_field, field_arg->field, field_arg->field->size_of()); + def_field->move_field_offset((my_ptrdiff_t) + (def_field->table->insert_values - + def_field->table->record[0])); + set_field(def_field); + } + else + { + Field *tmp_field= field_arg->field; + /* charset doesn't matter here, it's to avoid sigsegv only */ + tmp_field= new Field_null(0, 0, Field::NONE, field_arg->field->field_name, + &my_charset_bin); + if (tmp_field) + { + tmp_field->init(field_arg->field->table); + set_field(tmp_field); + } + } + return FALSE; +} + +void Item_insert_value::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("values(")); + arg->print(str, query_type); + str->append(')'); +} + + +/** + Find index of Field object which will be appropriate for item + representing field of row being changed in trigger. + + @param thd current thread context + @param table table of trigger (and where we looking for fields) + @param table_grant_info GRANT_INFO of the subject table + + @note + This function does almost the same as fix_fields() for Item_field + but is invoked right after trigger definition parsing. Since at + this stage we can't say exactly what Field object (corresponding + to TABLE::record[0] or TABLE::record[1]) should be bound to this + Item, we only find out index of the Field and then select concrete + Field object in fix_fields() (by that time Table_trigger_list::old_field/ + new_field should point to proper array of Fields). + It also binds Item_trigger_field to Table_triggers_list object for + table of trigger which uses this item. +*/ + +void Item_trigger_field::setup_field(THD *thd, TABLE *table, + GRANT_INFO *table_grant_info) +{ + /* + It is too early to mark fields used here, because before execution + of statement that will invoke trigger other statements may use same + TABLE object, so all such mark-up will be wiped out. + So instead we do it in Table_triggers_list::mark_fields_used() + method which is called during execution of these statements. + */ + enum_mark_columns save_mark_used_columns= thd->mark_used_columns; + thd->mark_used_columns= MARK_COLUMNS_NONE; + /* + Try to find field by its name and if it will be found + set field_idx properly. + */ + (void)find_field_in_table(thd, table, field_name, (uint) strlen(field_name), + 0, &field_idx); + thd->mark_used_columns= save_mark_used_columns; + triggers= table->triggers; + table_grants= table_grant_info; +} + + +bool Item_trigger_field::eq(const Item *item, bool binary_cmp) const +{ + return item->type() == TRIGGER_FIELD_ITEM && + row_version == ((Item_trigger_field *)item)->row_version && + !my_strcasecmp(system_charset_info, field_name, + ((Item_trigger_field *)item)->field_name); +} + + +void Item_trigger_field::set_required_privilege(bool rw) +{ + /* + Require SELECT and UPDATE privilege if this field will be read and + set, and only UPDATE privilege for setting the field. + */ + want_privilege= (rw ? SELECT_ACL | UPDATE_ACL : UPDATE_ACL); +} + + +bool Item_trigger_field::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it) +{ + Item *item= sp_prepare_func_item(thd, it); + + return (!item || (!fixed && fix_fields(thd, 0)) || + (item->save_in_field(field, 0) < 0)); +} + + +bool Item_trigger_field::fix_fields(THD *thd, Item **items) +{ + /* + Since trigger is object tightly associated with TABLE object most + of its set up can be performed during trigger loading i.e. trigger + parsing! So we have little to do in fix_fields. :) + */ + + DBUG_ASSERT(fixed == 0); + + /* Set field. */ + + if (field_idx != (uint)-1) + { +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* + Check access privileges for the subject table. We check privileges only + in runtime. + */ + + if (table_grants) + { + table_grants->want_privilege= want_privilege; + + if (check_grant_column(thd, table_grants, triggers->trigger_table->s->db.str, + triggers->trigger_table->s->table_name.str, field_name, + strlen(field_name), thd->security_ctx)) + return TRUE; + } +#endif // NO_EMBEDDED_ACCESS_CHECKS + + field= (row_version == OLD_ROW) ? triggers->old_field[field_idx] : + triggers->new_field[field_idx]; + set_field(field); + fixed= 1; + return FALSE; + } + + my_error(ER_BAD_FIELD_ERROR, MYF(0), field_name, + (row_version == NEW_ROW) ? "NEW" : "OLD"); + return TRUE; +} + + +void Item_trigger_field::print(String *str, enum_query_type query_type) +{ + str->append((row_version == NEW_ROW) ? "NEW" : "OLD", 3); + str->append('.'); + str->append(field_name); +} + + +void Item_trigger_field::cleanup() +{ + want_privilege= original_privilege; + /* + Since special nature of Item_trigger_field we should not do most of + things from Item_field::cleanup() or Item_ident::cleanup() here. + */ + Item::cleanup(); +} + + +Item_result item_cmp_type(Item_result a,Item_result b) +{ + if (a == STRING_RESULT && b == STRING_RESULT) + return STRING_RESULT; + if (a == INT_RESULT && b == INT_RESULT) + return INT_RESULT; + else if (a == ROW_RESULT || b == ROW_RESULT) + return ROW_RESULT; + if ((a == INT_RESULT || a == DECIMAL_RESULT) && + (b == INT_RESULT || b == DECIMAL_RESULT)) + return DECIMAL_RESULT; + return REAL_RESULT; +} + + +void resolve_const_item(THD *thd, Item **ref, Item *comp_item) +{ + Item *item= *ref; + Item *new_item= NULL; + if (item->basic_const_item()) + return; // Can't be better + Item_result res_type=item_cmp_type(comp_item->result_type(), + item->result_type()); + char *name=item->name; // Alloced by sql_alloc + + switch (res_type) { + case STRING_RESULT: + { + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff),&my_charset_bin),*result; + result=item->val_str(&tmp); + if (item->null_value) + new_item= new Item_null(name); + else + { + uint length= result->length(); + char *tmp_str= sql_strmake(result->ptr(), length); + new_item= new Item_string(name, tmp_str, length, result->charset()); + } + break; + } + case INT_RESULT: + { + longlong result=item->val_int(); + uint length=item->max_length; + bool null_value=item->null_value; + new_item= (null_value ? (Item*) new Item_null(name) : + (Item*) new Item_int(name, result, length)); + break; + } + case ROW_RESULT: + if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM) + { + /* + Substitute constants only in Item_rows. Don't affect other Items + with ROW_RESULT (eg Item_singlerow_subselect). + + For such Items more optimal is to detect if it is constant and replace + it with Item_row. This would optimize queries like this: + SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1); + */ + Item_row *item_row= (Item_row*) item; + Item_row *comp_item_row= (Item_row*) comp_item; + uint col; + new_item= 0; + /* + If item and comp_item are both Item_rows and have same number of cols + then process items in Item_row one by one. + We can't ignore NULL values here as this item may be used with <=>, in + which case NULL's are significant. + */ + DBUG_ASSERT(item->result_type() == comp_item->result_type()); + DBUG_ASSERT(item_row->cols() == comp_item_row->cols()); + col= item_row->cols(); + while (col-- > 0) + resolve_const_item(thd, item_row->addr(col), + comp_item_row->element_index(col)); + break; + } + /* Fallthrough */ + case REAL_RESULT: + { // It must REAL_RESULT + double result= item->val_real(); + uint length=item->max_length,decimals=item->decimals; + bool null_value=item->null_value; + new_item= (null_value ? (Item*) new Item_null(name) : (Item*) + new Item_float(name, result, decimals, length)); + break; + } + case DECIMAL_RESULT: + { + my_decimal decimal_value; + my_decimal *result= item->val_decimal(&decimal_value); + uint length= item->max_length, decimals= item->decimals; + bool null_value= item->null_value; + new_item= (null_value ? + (Item*) new Item_null(name) : + (Item*) new Item_decimal(name, result, length, decimals)); + break; + } + default: + DBUG_ASSERT(0); + } + if (new_item) + thd->change_item_tree(ref, new_item); +} + +/** + Compare the value stored in field, with the original item. + + @param field field which the item is converted and stored in + @param item original item + + @return Return an integer greater than, equal to, or less than 0 if + the value stored in the field is greater than, equal to, + or less than the original item + + @note We only use this on the range optimizer/partition pruning, + because in some cases we can't store the value in the field + without some precision/character loss. +*/ + +int stored_field_cmp_to_item(Field *field, Item *item) +{ + + Item_result res_type=item_cmp_type(field->result_type(), + item->result_type()); + if (res_type == STRING_RESULT) + { + char item_buff[MAX_FIELD_WIDTH]; + char field_buff[MAX_FIELD_WIDTH]; + String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result; + String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin); + enum_field_types field_type; + item_result=item->val_str(&item_tmp); + if (item->null_value) + return 0; + field->val_str(&field_tmp); + + /* + If comparing DATE with DATETIME, append the time-part to the DATE. + So that the strings are equally formatted. + A DATE converted to string is 10 characters, and a DATETIME converted + to string is 19 characters. + */ + field_type= field->type(); + if (field_type == MYSQL_TYPE_DATE && + item_result->length() == 19) + field_tmp.append(" 00:00:00"); + else if (field_type == MYSQL_TYPE_DATETIME && + item_result->length() == 10) + item_result->append(" 00:00:00"); + + return stringcmp(&field_tmp,item_result); + } + if (res_type == INT_RESULT) + return 0; // Both are of type int + if (res_type == DECIMAL_RESULT) + { + my_decimal item_buf, *item_val, + field_buf, *field_val; + item_val= item->val_decimal(&item_buf); + if (item->null_value) + return 0; + field_val= field->val_decimal(&field_buf); + return my_decimal_cmp(item_val, field_val); + } + double result= item->val_real(); + if (item->null_value) + return 0; + double field_result= field->val_real(); + if (field_result < result) + return -1; + else if (field_result > result) + return 1; + return 0; +} + +Item_cache* Item_cache::get_cache(const Item *item) +{ + switch (item->result_type()) { + case INT_RESULT: + return new Item_cache_int(); + case REAL_RESULT: + return new Item_cache_real(); + case DECIMAL_RESULT: + return new Item_cache_decimal(); + case STRING_RESULT: + return new Item_cache_str(item); + case ROW_RESULT: + return new Item_cache_row(); + default: + // should never be in real life + DBUG_ASSERT(0); + return 0; + } +} + + +void Item_cache::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("(")); + if (example) + example->print(str, query_type); + else + Item::print(str, query_type); + str->append(')'); +} + + +void Item_cache_int::store(Item *item) +{ + value= item->val_int_result(); + null_value= item->null_value; + unsigned_flag= item->unsigned_flag; +} + + +void Item_cache_int::store(Item *item, longlong val_arg) +{ + value= val_arg; + null_value= item->null_value; + unsigned_flag= item->unsigned_flag; +} + + +String *Item_cache_int::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + str->set(value, default_charset()); + return str; +} + + +my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val) +{ + DBUG_ASSERT(fixed == 1); + int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val); + return decimal_val; +} + + +void Item_cache_real::store(Item *item) +{ + value= item->val_result(); + null_value= item->null_value; +} + + +longlong Item_cache_real::val_int() +{ + DBUG_ASSERT(fixed == 1); + return (longlong) rint(value); +} + + +String* Item_cache_real::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + str->set_real(value, decimals, default_charset()); + return str; +} + + +my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val) +{ + DBUG_ASSERT(fixed == 1); + double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val); + return decimal_val; +} + + +void Item_cache_decimal::store(Item *item) +{ + my_decimal *val= item->val_decimal_result(&decimal_value); + if (!(null_value= item->null_value) && val != &decimal_value) + my_decimal2decimal(val, &decimal_value); +} + +double Item_cache_decimal::val_real() +{ + DBUG_ASSERT(fixed); + double res; + my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res); + return res; +} + +longlong Item_cache_decimal::val_int() +{ + DBUG_ASSERT(fixed); + longlong res; + my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res); + return res; +} + +String* Item_cache_decimal::val_str(String *str) +{ + DBUG_ASSERT(fixed); + my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE, + &decimal_value); + my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str); + return str; +} + +my_decimal *Item_cache_decimal::val_decimal(my_decimal *val) +{ + DBUG_ASSERT(fixed); + return &decimal_value; +} + + +void Item_cache_str::store(Item *item) +{ + value_buff.set(buffer, sizeof(buffer), item->collation.collation); + value= item->str_result(&value_buff); + if ((null_value= item->null_value)) + value= 0; + else if (value != &value_buff) + { + /* + We copy string value to avoid changing value if 'item' is table field + in queries like following (where t1.c is varchar): + select a, + (select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'), + (select c from t1 where a=t2.a) + from t2; + */ + value_buff.copy(*value); + value= &value_buff; + } +} + +double Item_cache_str::val_real() +{ + DBUG_ASSERT(fixed == 1); + int err_not_used; + char *end_not_used; + if (value) + return my_strntod(value->charset(), (char*) value->ptr(), + value->length(), &end_not_used, &err_not_used); + return (double) 0; +} + + +longlong Item_cache_str::val_int() +{ + DBUG_ASSERT(fixed == 1); + int err; + if (value) + return my_strntoll(value->charset(), value->ptr(), + value->length(), 10, (char**) 0, &err); + else + return (longlong)0; +} + +my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val) +{ + DBUG_ASSERT(fixed == 1); + if (value) + string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val); + else + decimal_val= 0; + return decimal_val; +} + + +int Item_cache_str::save_in_field(Field *field, bool no_conversions) +{ + int res= Item_cache::save_in_field(field, no_conversions); + return (is_varbinary && field->type() == MYSQL_TYPE_STRING && + value->length() < field->field_length) ? 1 : res; +} + + +bool Item_cache_row::allocate(uint num) +{ + item_count= num; + THD *thd= current_thd; + return (!(values= + (Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count))); +} + + +bool Item_cache_row::setup(Item * item) +{ + example= item; + if (!values && allocate(item->cols())) + return 1; + for (uint i= 0; i < item_count; i++) + { + Item *el= item->element_index(i); + Item_cache *tmp; + if (!(tmp= values[i]= Item_cache::get_cache(el))) + return 1; + tmp->setup(el); + } + return 0; +} + + +void Item_cache_row::store(Item * item) +{ + null_value= 0; + item->bring_value(); + for (uint i= 0; i < item_count; i++) + { + values[i]->store(item->element_index(i)); + null_value|= values[i]->null_value; + } +} + + +void Item_cache_row::illegal_method_call(const char *method) +{ + DBUG_ENTER("Item_cache_row::illegal_method_call"); + DBUG_PRINT("error", ("!!! %s method was called for row item", method)); + DBUG_ASSERT(0); + my_error(ER_OPERAND_COLUMNS, MYF(0), 1); + DBUG_VOID_RETURN; +} + + +bool Item_cache_row::check_cols(uint c) +{ + if (c != item_count) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), c); + return 1; + } + return 0; +} + + +bool Item_cache_row::null_inside() +{ + for (uint i= 0; i < item_count; i++) + { + if (values[i]->cols() > 1) + { + if (values[i]->null_inside()) + return 1; + } + else + { + values[i]->update_null_value(); + if (values[i]->null_value) + return 1; + } + } + return 0; +} + + +void Item_cache_row::bring_value() +{ + for (uint i= 0; i < item_count; i++) + values[i]->bring_value(); + return; +} + + +Item_type_holder::Item_type_holder(THD *thd, Item *item) + :Item(thd, item), enum_set_typelib(0), fld_type(get_real_type(item)) +{ + DBUG_ASSERT(item->fixed); + maybe_null= item->maybe_null; + collation.set(item->collation); + get_full_info(item); + /* fix variable decimals which always is NOT_FIXED_DEC */ + if (Field::result_merge_type(fld_type) == INT_RESULT) + decimals= 0; + prev_decimal_int_part= item->decimal_int_part(); +#ifdef HAVE_SPATIAL + if (item->field_type() == MYSQL_TYPE_GEOMETRY) + geometry_type= item->get_geometry_type(); +#endif /* HAVE_SPATIAL */ +} + + +/** + Return expression type of Item_type_holder. + + @return + Item_result (type of internal MySQL expression result) +*/ + +Item_result Item_type_holder::result_type() const +{ + return Field::result_merge_type(fld_type); +} + + +/** + Find real field type of item. + + @return + type of field which should be created to store item value +*/ + +enum_field_types Item_type_holder::get_real_type(Item *item) +{ + switch(item->type()) + { + case FIELD_ITEM: + { + /* + Item_fields::field_type ask Field_type() but sometimes field return + a different type, like for enum/set, so we need to ask real type. + */ + Field *field= ((Item_field *) item)->field; + enum_field_types type= field->real_type(); + if (field->is_created_from_null_item) + return MYSQL_TYPE_NULL; + /* work around about varchar type field detection */ + if (type == MYSQL_TYPE_STRING && field->type() == MYSQL_TYPE_VAR_STRING) + return MYSQL_TYPE_VAR_STRING; + return type; + } + case SUM_FUNC_ITEM: + { + /* + Argument of aggregate function sometimes should be asked about field + type + */ + Item_sum *item_sum= (Item_sum *) item; + if (item_sum->keep_field_type()) + return get_real_type(item_sum->get_arg(0)); + break; + } + case FUNC_ITEM: + if (((Item_func *) item)->functype() == Item_func::GUSERVAR_FUNC) + { + /* + There are work around of problem with changing variable type on the + fly and variable always report "string" as field type to get + acceptable information for client in send_field, so we make field + type from expression type. + */ + switch (item->result_type()) { + case STRING_RESULT: + return MYSQL_TYPE_VAR_STRING; + case INT_RESULT: + return MYSQL_TYPE_LONGLONG; + case REAL_RESULT: + return MYSQL_TYPE_DOUBLE; + case DECIMAL_RESULT: + return MYSQL_TYPE_NEWDECIMAL; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + return MYSQL_TYPE_VAR_STRING; + } + } + break; + default: + break; + } + return item->field_type(); +} + +/** + Find field type which can carry current Item_type_holder type and + type of given Item. + + @param thd thread handler + @param item given item to join its parameters with this item ones + + @retval + TRUE error - types are incompatible + @retval + FALSE OK +*/ + +bool Item_type_holder::join_types(THD *thd, Item *item) +{ + uint max_length_orig= max_length; + uint decimals_orig= decimals; + DBUG_ENTER("Item_type_holder::join_types"); + DBUG_PRINT("info:", ("was type %d len %d, dec %d name %s", + fld_type, max_length, decimals, + (name ? name : ""))); + DBUG_PRINT("info:", ("in type %d len %d, dec %d", + get_real_type(item), + item->max_length, item->decimals)); + fld_type= Field::field_type_merge(fld_type, get_real_type(item)); + { + int item_decimals= item->decimals; + /* fix variable decimals which always is NOT_FIXED_DEC */ + if (Field::result_merge_type(fld_type) == INT_RESULT) + item_decimals= 0; + decimals= max(decimals, item_decimals); + } + if (Field::result_merge_type(fld_type) == DECIMAL_RESULT) + { + decimals= min(max(decimals, item->decimals), DECIMAL_MAX_SCALE); + int item_int_part= item->decimal_int_part(); + int item_prec = max(prev_decimal_int_part, item_int_part) + decimals; + int precision= min(item_prec, DECIMAL_MAX_PRECISION); + unsigned_flag&= item->unsigned_flag; + max_length= my_decimal_precision_to_length_no_truncation(precision, + decimals, + unsigned_flag); + } + + switch (Field::result_merge_type(fld_type)) + { + case STRING_RESULT: + { + const char *old_cs, *old_derivation; + uint32 old_max_chars= max_length / collation.collation->mbmaxlen; + old_cs= collation.collation->name; + old_derivation= collation.derivation_name(); + if (collation.aggregate(item->collation, MY_COLL_ALLOW_CONV)) + { + my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0), + old_cs, old_derivation, + item->collation.collation->name, + item->collation.derivation_name(), + "UNION"); + DBUG_RETURN(TRUE); + } + /* + To figure out max_length, we have to take into account possible + expansion of the size of the values because of character set + conversions. + */ + if (collation.collation != &my_charset_bin) + { + max_length= max(old_max_chars * collation.collation->mbmaxlen, + display_length(item) / + item->collation.collation->mbmaxlen * + collation.collation->mbmaxlen); + } + else + set_if_bigger(max_length, display_length(item)); + break; + } + case REAL_RESULT: + { + if (decimals != NOT_FIXED_DEC) + { + /* + For FLOAT(M,D)/DOUBLE(M,D) do not change precision + if both fields have the same M and D + */ + if (item->max_length != max_length_orig || + item->decimals != decimals_orig) + { + int delta1= max_length_orig - decimals_orig; + int delta2= item->max_length - item->decimals; + max_length= max(delta1, delta2) + decimals; + if (fld_type == MYSQL_TYPE_FLOAT && max_length > FLT_DIG + 2) + { + max_length= MAX_FLOAT_STR_LENGTH; + decimals= NOT_FIXED_DEC; + } + else if (fld_type == MYSQL_TYPE_DOUBLE && max_length > DBL_DIG + 2) + { + max_length= MAX_DOUBLE_STR_LENGTH; + decimals= NOT_FIXED_DEC; + } + } + } + else + max_length= (fld_type == MYSQL_TYPE_FLOAT) ? FLT_DIG+6 : DBL_DIG+7; + break; + } + default: + max_length= max(max_length, display_length(item)); + }; + maybe_null|= item->maybe_null; + get_full_info(item); + + /* Remember decimal integer part to be used in DECIMAL_RESULT handleng */ + prev_decimal_int_part= decimal_int_part(); + DBUG_PRINT("info", ("become type: %d len: %u dec: %u", + (int) fld_type, max_length, (uint) decimals)); + DBUG_RETURN(FALSE); +} + +/** + Calculate lenth for merging result for given Item type. + + @param item Item for length detection + + @return + length +*/ + +uint32 Item_type_holder::display_length(Item *item) +{ + if (item->type() == Item::FIELD_ITEM) + return ((Item_field *)item)->max_disp_length(); + + switch (item->field_type()) + { + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_TIMESTAMP: + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_TIME: + case MYSQL_TYPE_DATETIME: + case MYSQL_TYPE_YEAR: + case MYSQL_TYPE_NEWDATE: + case MYSQL_TYPE_VARCHAR: + case MYSQL_TYPE_BIT: + case MYSQL_TYPE_NEWDECIMAL: + case MYSQL_TYPE_ENUM: + case MYSQL_TYPE_SET: + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_VAR_STRING: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_GEOMETRY: + return item->max_length; + case MYSQL_TYPE_TINY: + return 4; + case MYSQL_TYPE_SHORT: + return 6; + case MYSQL_TYPE_LONG: + return MY_INT32_NUM_DECIMAL_DIGITS; + case MYSQL_TYPE_FLOAT: + return 25; + case MYSQL_TYPE_DOUBLE: + return 53; + case MYSQL_TYPE_NULL: + return 0; + case MYSQL_TYPE_LONGLONG: + return 20; + case MYSQL_TYPE_INT24: + return 8; + default: + DBUG_ASSERT(0); // we should never go there + return 0; + } +} + + +/** + Make temporary table field according collected information about type + of UNION result. + + @param table temporary table for which we create fields + + @return + created field +*/ + +//@infinidb pass in the thd pointer +Field *Item_type_holder::make_field_by_type(TABLE *table, THD* IDB_thd) +{ + /* + The field functions defines a field to be not null if null_ptr is not 0 + */ + uchar *null_ptr= maybe_null ? (uchar*) "" : 0; + Field *field; + + switch (fld_type) { + case MYSQL_TYPE_ENUM: + DBUG_ASSERT(enum_set_typelib); + field= new Field_enum((uchar *) 0, max_length, null_ptr, 0, + Field::NONE, name, + get_enum_pack_length(enum_set_typelib->count), + enum_set_typelib, collation.collation); + if (field) + field->init(table); + return field; + case MYSQL_TYPE_SET: + DBUG_ASSERT(enum_set_typelib); + field= new Field_set((uchar *) 0, max_length, null_ptr, 0, + Field::NONE, name, + get_set_pack_length(enum_set_typelib->count), + enum_set_typelib, collation.collation); + if (field) + field->init(table); + return field; + case MYSQL_TYPE_NULL: + return make_string_field(table, IDB_thd); + default: + break; + } + return tmp_table_field_from_field_type(table, 0, IDB_thd); // @infinidb pass in thd pointer +} + + +/** + Get full information from Item about enum/set fields to be able to create + them later. + + @param item Item for information collection +*/ +void Item_type_holder::get_full_info(Item *item) +{ + if (fld_type == MYSQL_TYPE_ENUM || + fld_type == MYSQL_TYPE_SET) + { + if (item->type() == Item::SUM_FUNC_ITEM && + (((Item_sum*)item)->sum_func() == Item_sum::MAX_FUNC || + ((Item_sum*)item)->sum_func() == Item_sum::MIN_FUNC)) + item = ((Item_sum*)item)->get_arg(0); + /* + We can have enum/set type after merging only if we have one enum|set + field (or MIN|MAX(enum|set field)) and number of NULL fields + */ + DBUG_ASSERT((enum_set_typelib && + get_real_type(item) == MYSQL_TYPE_NULL) || + (!enum_set_typelib && + item->type() == Item::FIELD_ITEM && + (get_real_type(item) == MYSQL_TYPE_ENUM || + get_real_type(item) == MYSQL_TYPE_SET) && + ((Field_enum*)((Item_field *) item)->field)->typelib)); + if (!enum_set_typelib) + { + enum_set_typelib= ((Field_enum*)((Item_field *) item)->field)->typelib; + } + } +} + + +double Item_type_holder::val_real() +{ + DBUG_ASSERT(0); // should never be called + return 0.0; +} + + +longlong Item_type_holder::val_int() +{ + DBUG_ASSERT(0); // should never be called + return 0; +} + +my_decimal *Item_type_holder::val_decimal(my_decimal *) +{ + DBUG_ASSERT(0); // should never be called + return 0; +} + +String *Item_type_holder::val_str(String*) +{ + DBUG_ASSERT(0); // should never be called + return 0; +} + +void Item_result_field::cleanup() +{ + DBUG_ENTER("Item_result_field::cleanup()"); + Item::cleanup(); + result_field= 0; + DBUG_VOID_RETURN; +} + +/** + Dummy error processor used by default by Name_resolution_context. + + @note + do nothing +*/ + +void dummy_error_processor(THD *thd, void *data) +{} + +/** + Wrapper of hide_view_error call for Name_resolution_context error + processor. + + @note + hide view underlying tables details in error messages +*/ + +void view_error_processor(THD *thd, void *data) +{ + ((TABLE_LIST *)data)->hide_view_error(thd); +} + +/***************************************************************************** +** Instantiate templates +*****************************************************************************/ + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +template class List; +template class List_iterator; +template class List_iterator_fast; +template class List_iterator_fast; +template class List; +#endif diff --git a/dbcon/mysql/item.h b/dbcon/mysql/item.h new file mode 100644 index 00000000..a91e65cc --- /dev/null +++ b/dbcon/mysql/item.h @@ -0,0 +1,3133 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +class Protocol; +struct TABLE_LIST; +void item_init(void); /* Init item functions */ +class Item_field; + +/* + "Declared Type Collation" + A combination of collation and its derivation. + + Flags for collation aggregation modes: + MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset + MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value + (i.e. constant). + MY_COLL_ALLOW_CONV - allow any kind of conversion + (combination of the above two) + MY_COLL_DISALLOW_NONE - don't allow return DERIVATION_NONE + (e.g. when aggregating for comparison) + MY_COLL_CMP_CONV - combination of MY_COLL_ALLOW_CONV + and MY_COLL_DISALLOW_NONE +*/ + +#define MY_COLL_ALLOW_SUPERSET_CONV 1 +#define MY_COLL_ALLOW_COERCIBLE_CONV 2 +#define MY_COLL_ALLOW_CONV 3 +#define MY_COLL_DISALLOW_NONE 4 +#define MY_COLL_CMP_CONV 7 + +class DTCollation { +public: + CHARSET_INFO *collation; + enum Derivation derivation; + uint repertoire; + + void set_repertoire_from_charset(CHARSET_INFO *cs) + { + repertoire= cs->state & MY_CS_PUREASCII ? + MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; + } + DTCollation() + { + collation= &my_charset_bin; + derivation= DERIVATION_NONE; + repertoire= MY_REPERTOIRE_UNICODE30; + } + DTCollation(CHARSET_INFO *collation_arg, Derivation derivation_arg) + { + collation= collation_arg; + derivation= derivation_arg; + set_repertoire_from_charset(collation_arg); + } + void set(DTCollation &dt) + { + collation= dt.collation; + derivation= dt.derivation; + repertoire= dt.repertoire; + } + void set(CHARSET_INFO *collation_arg, Derivation derivation_arg) + { + collation= collation_arg; + derivation= derivation_arg; + set_repertoire_from_charset(collation_arg); + } + void set(CHARSET_INFO *collation_arg, + Derivation derivation_arg, + uint repertoire_arg) + { + collation= collation_arg; + derivation= derivation_arg; + repertoire= repertoire_arg; + } + void set(CHARSET_INFO *collation_arg) + { + collation= collation_arg; + set_repertoire_from_charset(collation_arg); + } + void set(Derivation derivation_arg) + { derivation= derivation_arg; } + bool aggregate(DTCollation &dt, uint flags= 0); + bool set(DTCollation &dt1, DTCollation &dt2, uint flags= 0) + { set(dt1); return aggregate(dt2, flags); } + const char *derivation_name() const + { + switch(derivation) + { + case DERIVATION_IGNORABLE: return "IGNORABLE"; + case DERIVATION_COERCIBLE: return "COERCIBLE"; + case DERIVATION_IMPLICIT: return "IMPLICIT"; + case DERIVATION_SYSCONST: return "SYSCONST"; + case DERIVATION_EXPLICIT: return "EXPLICIT"; + case DERIVATION_NONE: return "NONE"; + default: return "UNKNOWN"; + } + } +}; + +/*************************************************************************/ +/* + A framework to easily handle different return types for hybrid items + (hybrid item is an item whose operand can be of any type, e.g. integer, + real, decimal). +*/ + +struct Hybrid_type_traits; + +struct Hybrid_type +{ + longlong integer; + + double real; + /* + Use two decimal buffers interchangeably to speed up += operation + which has no native support in decimal library. + Hybrid_type+= arg is implemented as dec_buf[1]= dec_buf[0] + arg. + The third decimal is used as a handy temporary storage. + */ + my_decimal dec_buf[3]; + int used_dec_buf_no; + + /* + Traits moved to a separate class to + a) be able to easily change object traits in runtime + b) they work as a differentiator for the union above + */ + const Hybrid_type_traits *traits; + + Hybrid_type() {} + /* XXX: add traits->copy() when needed */ + Hybrid_type(const Hybrid_type &rhs) :traits(rhs.traits) {} +}; + + +/* Hybryd_type_traits interface + default implementation for REAL_RESULT */ + +struct Hybrid_type_traits +{ + virtual Item_result type() const { return REAL_RESULT; } + + virtual void + fix_length_and_dec(Item *item, Item *arg) const; + + /* Hybrid_type operations. */ + virtual void set_zero(Hybrid_type *val) const { val->real= 0.0; } + virtual void add(Hybrid_type *val, Field *f) const + { val->real+= f->val_real(); } + virtual void div(Hybrid_type *val, ulonglong u) const + { val->real/= ulonglong2double(u); } + + virtual longlong val_int(Hybrid_type *val, bool unsigned_flag) const + { return (longlong) rint(val->real); } + virtual double val_real(Hybrid_type *val) const { return val->real; } + virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const; + virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const; + static const Hybrid_type_traits *instance(); + Hybrid_type_traits() {} + virtual ~Hybrid_type_traits() {} +}; + + +struct Hybrid_type_traits_decimal: public Hybrid_type_traits +{ + virtual Item_result type() const { return DECIMAL_RESULT; } + + virtual void + fix_length_and_dec(Item *arg, Item *item) const; + + /* Hybrid_type operations. */ + virtual void set_zero(Hybrid_type *val) const; + virtual void add(Hybrid_type *val, Field *f) const; + virtual void div(Hybrid_type *val, ulonglong u) const; + + virtual longlong val_int(Hybrid_type *val, bool unsigned_flag) const; + virtual double val_real(Hybrid_type *val) const; + virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const + { return &val->dec_buf[val->used_dec_buf_no]; } + virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const; + static const Hybrid_type_traits_decimal *instance(); + Hybrid_type_traits_decimal() {}; +}; + + +struct Hybrid_type_traits_integer: public Hybrid_type_traits +{ + virtual Item_result type() const { return INT_RESULT; } + + virtual void + fix_length_and_dec(Item *arg, Item *item) const; + + /* Hybrid_type operations. */ + virtual void set_zero(Hybrid_type *val) const + { val->integer= 0; } + virtual void add(Hybrid_type *val, Field *f) const + { val->integer+= f->val_int(); } + virtual void div(Hybrid_type *val, ulonglong u) const + { val->integer/= (longlong) u; } + + virtual longlong val_int(Hybrid_type *val, bool unsigned_flag) const + { return val->integer; } + virtual double val_real(Hybrid_type *val) const + { return (double) val->integer; } + virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const + { + int2my_decimal(E_DEC_FATAL_ERROR, val->integer, 0, &val->dec_buf[2]); + return &val->dec_buf[2]; + } + virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const + { buf->set(val->integer, &my_charset_bin); return buf;} + static const Hybrid_type_traits_integer *instance(); + Hybrid_type_traits_integer() {}; +}; + + +void dummy_error_processor(THD *thd, void *data); + +void view_error_processor(THD *thd, void *data); + +/* + Instances of Name_resolution_context store the information necesary for + name resolution of Items and other context analysis of a query made in + fix_fields(). + + This structure is a part of SELECT_LEX, a pointer to this structure is + assigned when an item is created (which happens mostly during parsing + (sql_yacc.yy)), but the structure itself will be initialized after parsing + is complete + + TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to + separate SELECT_LEX which allow to remove tricks of changing this + structure before and after INSERT/CREATE and its SELECT to make correct + field name resolution. +*/ +struct Name_resolution_context: Sql_alloc +{ + /* + The name resolution context to search in when an Item cannot be + resolved in this context (the context of an outer select) + */ + Name_resolution_context *outer_context; + + /* + List of tables used to resolve the items of this context. Usually these + are tables from the FROM clause of SELECT statement. The exceptions are + INSERT ... SELECT and CREATE ... SELECT statements, where SELECT + subquery is not moved to a separate SELECT_LEX. For these types of + statements we have to change this member dynamically to ensure correct + name resolution of different parts of the statement. + */ + TABLE_LIST *table_list; + /* + In most cases the two table references below replace 'table_list' above + for the purpose of name resolution. The first and last name resolution + table references allow us to search only in a sub-tree of the nested + join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING + and JOIN ... ON. + */ + TABLE_LIST *first_name_resolution_table; + /* + Last table to search in the list of leaf table references that begins + with first_name_resolution_table. + */ + TABLE_LIST *last_name_resolution_table; + + /* + SELECT_LEX item belong to, in case of merged VIEW it can differ from + SELECT_LEX where item was created, so we can't use table_list/field_list + from there + */ + st_select_lex *select_lex; + + /* + Processor of errors caused during Item name resolving, now used only to + hide underlying tables in errors about views (i.e. it substitute some + errors for views) + */ + void (*error_processor)(THD *, void *); + void *error_processor_data; + + /* + When TRUE items are resolved in this context both against the + SELECT list and this->table_list. If FALSE, items are resolved + only against this->table_list. + */ + bool resolve_in_select_list; + + /* + Security context of this name resolution context. It's used for views + and is non-zero only if the view is defined with SQL SECURITY DEFINER. + */ + Security_context *security_ctx; + + Name_resolution_context() + :outer_context(0), table_list(0), select_lex(0), + error_processor_data(0), + security_ctx(0) + {} + + void init() + { + resolve_in_select_list= FALSE; + error_processor= &dummy_error_processor; + first_name_resolution_table= NULL; + last_name_resolution_table= NULL; + } + + void resolve_in_table_list_only(TABLE_LIST *tables) + { + table_list= first_name_resolution_table= tables; + resolve_in_select_list= FALSE; + } + + void process_error(THD *thd) + { + (*error_processor)(thd, error_processor_data); + } +}; + + +/* + Store and restore the current state of a name resolution context. +*/ + +class Name_resolution_context_state +{ +private: + TABLE_LIST *save_table_list; + TABLE_LIST *save_first_name_resolution_table; + TABLE_LIST *save_next_name_resolution_table; + bool save_resolve_in_select_list; + TABLE_LIST *save_next_local; + +public: + Name_resolution_context_state() {} /* Remove gcc warning */ + +public: + /* Save the state of a name resolution context. */ + void save_state(Name_resolution_context *context, TABLE_LIST *table_list) + { + save_table_list= context->table_list; + save_first_name_resolution_table= context->first_name_resolution_table; + save_resolve_in_select_list= context->resolve_in_select_list; + save_next_local= table_list->next_local; + save_next_name_resolution_table= table_list->next_name_resolution_table; + } + + /* Restore a name resolution context from saved state. */ + void restore_state(Name_resolution_context *context, TABLE_LIST *table_list) + { + table_list->next_local= save_next_local; + table_list->next_name_resolution_table= save_next_name_resolution_table; + context->table_list= save_table_list; + context->first_name_resolution_table= save_first_name_resolution_table; + context->resolve_in_select_list= save_resolve_in_select_list; + } + + TABLE_LIST *get_first_name_resolution_table() + { + return save_first_name_resolution_table; + } +}; + + +/* + This enum is used to report information about monotonicity of function + represented by Item* tree. + Monotonicity is defined only for Item* trees that represent table + partitioning expressions (i.e. have no subselects/user vars/PS parameters + etc etc). An Item* tree is assumed to have the same monotonicity properties + as its correspoinding function F: + + [signed] longlong F(field1, field2, ...) { + put values of field_i into table record buffer; + return item->val_int(); + } + + NOTE + At the moment function monotonicity is not well defined (and so may be + incorrect) for Item trees with parameters/return types that are different + from INT_RESULT, may be NULL, or are unsigned. + It will be possible to address this issue once the related partitioning bugs + (BUG#16002, BUG#15447, BUG#13436) are fixed. + + The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns + NULL which puts those rows into the NULL partition, but + '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed + for this (see Bug#20577). +*/ + +typedef enum monotonicity_info +{ + NON_MONOTONIC, /* none of the below holds */ + MONOTONIC_INCREASING, /* F() is unary and (x < y) => (F(x) <= F(y)) */ + MONOTONIC_INCREASING_NOT_NULL, /* But only for valid/real x and y */ + MONOTONIC_STRICT_INCREASING,/* F() is unary and (x < y) => (F(x) < F(y)) */ + MONOTONIC_STRICT_INCREASING_NOT_NULL /* But only for valid/real x and y */ +} enum_monotonicity_info; + +/*************************************************************************/ + +class sp_rcontext; + + +class Settable_routine_parameter +{ +public: + /* + Set required privileges for accessing the parameter. + + SYNOPSIS + set_required_privilege() + rw if 'rw' is true then we are going to read and set the + parameter, so SELECT and UPDATE privileges might be + required, otherwise we only reading it and SELECT + privilege might be required. + */ + Settable_routine_parameter() {} + virtual ~Settable_routine_parameter() {} + virtual void set_required_privilege(bool rw) {}; + + /* + Set parameter value. + + SYNOPSIS + set_value() + thd thread handle + ctx context to which parameter belongs (if it is local + variable). + it item which represents new value + + RETURN + FALSE if parameter value has been set, + TRUE if error has occured. + */ + virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it)= 0; +}; + + +typedef bool (Item::*Item_processor) (uchar *arg); +/* + Analyzer function + SYNOPSIS + argp in/out IN: Analysis parameter + OUT: Parameter to be passed to the transformer + + RETURN + TRUE Invoke the transformer + FALSE Don't do it + +*/ +typedef bool (Item::*Item_analyzer) (uchar **argp); +typedef Item* (Item::*Item_transformer) (uchar *arg); +typedef void (*Cond_traverser) (const Item *item, void *arg); + + +class Item { + Item(const Item &); /* Prevent use of these */ + void operator=(Item &); +public: + static void *operator new(size_t size) throw () + { return sql_alloc(size); } + static void *operator new(size_t size, MEM_ROOT *mem_root) throw () + { return alloc_root(mem_root, size); } + static void operator delete(void *ptr,size_t size) { TRASH(ptr, size); } + static void operator delete(void *ptr, MEM_ROOT *mem_root) {} + + enum Type {FIELD_ITEM= 0, FUNC_ITEM, SUM_FUNC_ITEM, STRING_ITEM, + INT_ITEM, REAL_ITEM, NULL_ITEM, VARBIN_ITEM, + COPY_STR_ITEM, FIELD_AVG_ITEM, DEFAULT_VALUE_ITEM, + PROC_ITEM,COND_ITEM, REF_ITEM, FIELD_STD_ITEM, + FIELD_VARIANCE_ITEM, INSERT_VALUE_ITEM, + SUBSELECT_ITEM, ROW_ITEM, CACHE_ITEM, TYPE_HOLDER, + PARAM_ITEM, TRIGGER_FIELD_ITEM, DECIMAL_ITEM, + XPATH_NODESET, XPATH_NODESET_CMP, + VIEW_FIXER_ITEM}; + + enum cond_result { COND_UNDEF,COND_OK,COND_TRUE,COND_FALSE }; + + enum traverse_order { POSTFIX, PREFIX }; + + /* Reuse size, only used by SP local variable assignment, otherwize 0 */ + uint rsize; + + /* + str_values's main purpose is to be used to cache the value in + save_in_field + */ + String str_value; + char * name; /* Name from select */ + /* Original item name (if it was renamed)*/ + char * orig_name; + Item *next; + uint32 max_length; + uint name_length; /* Length of name */ + int8 marker; + uint8 decimals; + my_bool maybe_null; /* If item may be null */ + my_bool null_value; /* if item is null */ + my_bool unsigned_flag; + my_bool with_sum_func; + my_bool fixed; /* If item fixed with fix_fields */ + my_bool is_autogenerated_name; /* indicate was name of this Item + autogenerated or set by user */ + DTCollation collation; + my_bool with_subselect; /* If this item is a subselect or some + of its arguments is or contains a + subselect */ + Item_result cmp_context; /* Comparison context */ + // alloc & destruct is done as start of select using sql_alloc + Item(); + /* + Constructor used by Item_field, Item_ref & aggregate (sum) functions. + Used for duplicating lists in processing queries with temporary + tables + Also it used for Item_cond_and/Item_cond_or for creating + top AND/OR structure of WHERE clause to protect it of + optimisation changes in prepared statements + */ + Item(THD *thd, Item *item); + virtual ~Item() + { +#ifdef EXTRA_DEBUG + name=0; +#endif + } /*lint -e1509 */ + void set_name(const char *str, uint length, CHARSET_INFO *cs); + void rename(char *new_name); + void init_make_field(Send_field *tmp_field,enum enum_field_types type); + virtual void cleanup(); + virtual void make_field(Send_field *field); + // @infinidb pass in thd pointer + Field *make_string_field(TABLE *table, THD* IDB_thd = 0); + virtual bool fix_fields(THD *, Item **); + /* + should be used in case where we are sure that we do not need + complete fix_fields() procedure. + */ + inline void quick_fix_field() { fixed= 1; } + /* Function returns 1 on overflow and -1 on fatal errors */ + int save_in_field_no_warnings(Field *field, bool no_conversions); + virtual int save_in_field(Field *field, bool no_conversions); + virtual void save_org_in_field(Field *field) + { (void) save_in_field(field, 1); } + virtual int save_safe_in_field(Field *field) + { return save_in_field(field, 1); } + virtual bool send(Protocol *protocol, String *str); + virtual bool eq(const Item *, bool binary_cmp) const; + virtual Item_result result_type() const { return REAL_RESULT; } + virtual Item_result cast_to_int_type() const { return result_type(); } + virtual enum_field_types string_field_type() const; + virtual enum_field_types field_type() const; + virtual enum Type type() const =0; + + /* + Return information about function monotonicity. See comment for + enum_monotonicity_info for details. This function can only be called + after fix_fields() call. + */ + virtual enum_monotonicity_info get_monotonicity_info() const + { return NON_MONOTONIC; } + + /* + Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$ const2" + + SYNOPSIS + val_int_endpoint() + left_endp FALSE <=> The interval is "x < const" or "x <= const" + TRUE <=> The interval is "x > const" or "x >= const" + + incl_endp IN FALSE <=> the comparison is '<' or '>' + TRUE <=> the comparison is '<=' or '>=' + OUT The same but for the "F(x) $CMP$ F(const)" comparison + + DESCRIPTION + This function is defined only for unary monotonic functions. The caller + supplies the source half-interval + + x $CMP$ const + + The value of const is supplied implicitly as the value this item's + argument, the form of $CMP$ comparison is specified through the + function's arguments. The calle returns the result interval + + F(x) $CMP2$ F(const) + + passing back F(const) as the return value, and the form of $CMP2$ + through the out parameter. NULL values are assumed to be comparable and + be less than any non-NULL values. + + RETURN + The output range bound, which equal to the value of val_int() + - If the value of the function is NULL then the bound is the + smallest possible value of LONGLONG_MIN + */ + virtual longlong val_int_endpoint(bool left_endp, bool *incl_endp) + { DBUG_ASSERT(0); return 0; } + + + /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */ + /* + Return double precision floating point representation of item. + + SYNOPSIS + val_real() + + RETURN + In case of NULL value return 0.0 and set null_value flag to TRUE. + If value is not null null_value flag will be reset to FALSE. + */ + virtual double val_real()=0; + /* + Return integer representation of item. + + SYNOPSIS + val_int() + + RETURN + In case of NULL value return 0 and set null_value flag to TRUE. + If value is not null null_value flag will be reset to FALSE. + */ + virtual longlong val_int()=0; + /* + This is just a shortcut to avoid the cast. You should still use + unsigned_flag to check the sign of the item. + */ + inline ulonglong val_uint() { return (ulonglong) val_int(); } + /* + Return string representation of this item object. + + SYNOPSIS + val_str() + str an allocated buffer this or any nested Item object can use to + store return value of this method. + + NOTE + Buffer passed via argument should only be used if the item itself + doesn't have an own String buffer. In case when the item maintains + it's own string buffer, it's preferable to return it instead to + minimize number of mallocs/memcpys. + The caller of this method can modify returned string, but only in case + when it was allocated on heap, (is_alloced() is true). This allows + the caller to efficiently use a buffer allocated by a child without + having to allocate a buffer of it's own. The buffer, given to + val_str() as argument, belongs to the caller and is later used by the + caller at it's own choosing. + A few implications from the above: + - unless you return a string object which only points to your buffer + but doesn't manages it you should be ready that it will be + modified. + - even for not allocated strings (is_alloced() == false) the caller + can change charset (see Item_func_{typecast/binary}. XXX: is this + a bug? + - still you should try to minimize data copying and return internal + object whenever possible. + + RETURN + In case of NULL value return 0 (NULL pointer) and set null_value flag + to TRUE. + If value is not null null_value flag will be reset to FALSE. + */ + virtual String *val_str(String *str)=0; + /* + Return decimal representation of item with fixed point. + + SYNOPSIS + val_decimal() + decimal_buffer buffer which can be used by Item for returning value + (but can be not) + + NOTE + Returned value should not be changed if it is not the same which was + passed via argument. + + RETURN + Return pointer on my_decimal (it can be other then passed via argument) + if value is not NULL (null_value flag will be reset to FALSE). + In case of NULL value it return 0 pointer and set null_value flag + to TRUE. + */ + virtual my_decimal *val_decimal(my_decimal *decimal_buffer)= 0; + /* + Return boolean value of item. + + RETURN + FALSE value is false or NULL + TRUE value is true (not equal to 0) + */ + virtual bool val_bool(); + virtual String *val_nodeset(String*) { return 0; } + /* Helper functions, see item_sum.cc */ + String *val_string_from_real(String *str); + String *val_string_from_int(String *str); + String *val_string_from_decimal(String *str); + my_decimal *val_decimal_from_real(my_decimal *decimal_value); + my_decimal *val_decimal_from_int(my_decimal *decimal_value); + my_decimal *val_decimal_from_string(my_decimal *decimal_value); + my_decimal *val_decimal_from_date(my_decimal *decimal_value); + my_decimal *val_decimal_from_time(my_decimal *decimal_value); + longlong val_int_from_decimal(); + double val_real_from_decimal(); + + int save_time_in_field(Field *field); + int save_date_in_field(Field *field); + int save_str_value_in_field(Field *field, String *result); + + virtual Field *get_tmp_table_field() { return 0; } + /* This is also used to create fields in CREATE ... SELECT: */ + virtual Field *tmp_table_field(TABLE *t_arg) { return 0; } + virtual const char *full_name() const { return name ? name : "???"; } + + /* + *result* family of methods is analog of *val* family (see above) but + return value of result_field of item if it is present. If Item have not + result field, it return val(). This methods set null_value flag in same + way as *val* methods do it. + */ + virtual double val_result() { return val_real(); } + virtual longlong val_int_result() { return val_int(); } + virtual String *str_result(String* tmp) { return val_str(tmp); } + virtual my_decimal *val_decimal_result(my_decimal *val) + { return val_decimal(val); } + virtual bool val_bool_result() { return val_bool(); } + virtual bool is_null_result() { return is_null(); } + + /* bit map of tables used by item */ + virtual table_map used_tables() const { return (table_map) 0L; } + /* + Return table map of tables that can't be NULL tables (tables that are + used in a context where if they would contain a NULL row generated + by a LEFT or RIGHT join, the item would not be true). + This expression is used on WHERE item to determinate if a LEFT JOIN can be + converted to a normal join. + Generally this function should return used_tables() if the function + would return null if any of the arguments are null + As this is only used in the beginning of optimization, the value don't + have to be updated in update_used_tables() + */ + virtual table_map not_null_tables() const { return used_tables(); } + /* + Returns true if this is a simple constant item like an integer, not + a constant expression. Used in the optimizer to propagate basic constants. + */ + virtual bool basic_const_item() const { return 0; } + /* cloning of constant items (0 if it is not const) */ + virtual Item *clone_item() { return 0; } + virtual cond_result eq_cmp_result() const { return COND_OK; } + inline uint float_length(uint decimals_par) const + { return decimals != NOT_FIXED_DEC ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;} + /** Returns the uncapped decimal precision of this item. */ + virtual uint decimal_precision() const; + inline int decimal_int_part() const + { return decimal_precision() - decimals; } + /* + Returns true if this is constant (during query execution, i.e. its value + will not change until next fix_fields) and its value is known. + */ + virtual bool const_item() const { return used_tables() == 0; } + /* + Returns true if this is constant but its value may be not known yet. + (Can be used for parameters of prep. stmts or of stored procedures.) + */ + virtual bool const_during_execution() const + { return (used_tables() & ~PARAM_TABLE_BIT) == 0; } + + /** + This method is used for to: + - to generate a view definition query (SELECT-statement); + - to generate a SQL-query for EXPLAIN EXTENDED; + - to generate a SQL-query to be shown in INFORMATION_SCHEMA; + - debug. + + For more information about view definition query, INFORMATION_SCHEMA + query and why they should be generated from the Item-tree, @see + mysql_register_view(). + */ + virtual inline void print(String *str, enum_query_type query_type) + { + str->append(full_name()); + } + + void print_item_w_name(String *, enum_query_type query_type); + virtual void update_used_tables() {} + virtual void split_sum_func(THD *thd, Item **ref_pointer_array, + List &fields) {} + /* Called for items that really have to be split */ + void split_sum_func2(THD *thd, Item **ref_pointer_array, List &fields, + Item **ref, bool skip_registered); + virtual bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + virtual bool get_time(MYSQL_TIME *ltime); + virtual bool get_date_result(MYSQL_TIME *ltime,uint fuzzydate) + { return get_date(ltime,fuzzydate); } + /* + The method allows to determine nullness of a complex expression + without fully evaluating it, instead of calling val/result*() then + checking null_value. Used in Item_func_isnull/Item_func_isnotnull + and Item_sum_count/Item_sum_count_distinct. + Any new item which can be NULL must implement this method. + */ + virtual bool is_null() { return 0; } + + /* + Make sure the null_value member has a correct value. + */ + virtual void update_null_value () { (void) val_int(); } + + /* + Inform the item that there will be no distinction between its result + being FALSE or NULL. + + NOTE + This function will be called for eg. Items that are top-level AND-parts + of the WHERE clause. Items implementing this function (currently + Item_cond_and and subquery-related item) enable special optimizations + when they are "top level". + */ + virtual void top_level_item() {} + /* + set field of temporary table for Item which can be switched on temporary + table during query processing (grouping and so on) + */ + virtual void set_result_field(Field *field) {} + virtual bool is_result_field() { return 0; } + virtual bool is_bool_func() { return 0; } + virtual void save_in_result_field(bool no_conversions) {} + /* + set value of aggregate function in case of no rows for grouping were found + */ + virtual void no_rows_in_result() {} + virtual Item *copy_or_same(THD *thd) { return this; } + virtual Item *copy_andor_structure(THD *thd) { return this; } + virtual Item *real_item() { return this; } + virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); } + + static CHARSET_INFO *default_charset(); + virtual CHARSET_INFO *compare_collation() { return NULL; } + + virtual bool walk(Item_processor processor, bool walk_subquery, uchar *arg) + { + return (this->*processor)(arg); + } + + virtual Item* transform(Item_transformer transformer, uchar *arg); + + /* + This function performs a generic "compilation" of the Item tree. + The process of compilation is assumed to go as follows: + + compile() + { + if (this->*some_analyzer(...)) + { + compile children if any; + this->*some_transformer(...); + } + } + + i.e. analysis is performed top-down while transformation is done + bottom-up. + */ + virtual Item* compile(Item_analyzer analyzer, uchar **arg_p, + Item_transformer transformer, uchar *arg_t) + { + if ((this->*analyzer) (arg_p)) + return ((this->*transformer) (arg_t)); + return 0; + } + + virtual void traverse_cond(Cond_traverser traverser, + void *arg, traverse_order order) + { + (*traverser)(this, arg); + } + + virtual bool remove_dependence_processor(uchar * arg) { return 0; } + virtual bool remove_fixed(uchar * arg) { fixed= 0; return 0; } + virtual bool cleanup_processor(uchar *arg); + virtual bool collect_item_field_processor(uchar * arg) { return 0; } + virtual bool find_item_in_field_list_processor(uchar *arg) { return 0; } + virtual bool change_context_processor(uchar *context) { return 0; } + virtual bool reset_query_id_processor(uchar *query_id_arg) { return 0; } + virtual bool is_expensive_processor(uchar *arg) { return 0; } + virtual bool register_field_in_read_map(uchar *arg) { return 0; } + /* + Check if a partition function is allowed + SYNOPSIS + check_partition_func_processor() + int_arg Ignored + RETURN VALUE + TRUE Partition function not accepted + FALSE Partition function accepted + + DESCRIPTION + check_partition_func_processor is used to check if a partition function + uses an allowed function. An allowed function will always ensure that + X=Y guarantees that also part_function(X)=part_function(Y) where X is + a set of partition fields and so is Y. The problems comes mainly from + character sets where two equal strings can be quite unequal. E.g. the + german character for double s is equal to 2 s. + + The default is that an item is not allowed + in a partition function. Allowed functions + can never depend on server version, they cannot depend on anything + related to the environment. They can also only depend on a set of + fields in the table itself. They cannot depend on other tables and + cannot contain any queries and cannot contain udf's or similar. + If a new Item class is defined and it inherits from a class that is + allowed in a partition function then it is very important to consider + whether this should be inherited to the new class. If not the function + below should be defined in the new Item class. + + The general behaviour is that most integer functions are allowed. + If the partition function contains any multi-byte collations then + the function check_part_func_fields will report an error on the + partition function independent of what functions are used. So the + only character sets allowed are single character collation and + even for those only a limited set of functions are allowed. The + problem with multi-byte collations is that almost every string + function has the ability to change things such that two strings + that are equal will not be equal after manipulated by a string + function. E.g. two strings one contains a double s, there is a + special german character that is equal to two s. Now assume a + string function removes one character at this place, then in + one the double s will be removed and in the other there will + still be one s remaining and the strings are no longer equal + and thus the partition function will not sort equal strings into + the same partitions. + + So the check if a partition function is valid is two steps. First + check that the field types are valid, next check that the partition + function is valid. The current set of partition functions valid + assumes that there are no multi-byte collations amongst the partition + fields. + */ + virtual bool check_partition_func_processor(uchar *bool_arg) { return TRUE;} + virtual bool subst_argument_checker(uchar **arg) + { + if (*arg) + *arg= NULL; + return TRUE; + } + + virtual Item *equal_fields_propagator(uchar * arg) { return this; } + virtual bool set_no_const_sub(uchar *arg) { return FALSE; } + virtual Item *replace_equal_field(uchar * arg) { return this; } + + /* + For SP local variable returns pointer to Item representing its + current value and pointer to current Item otherwise. + */ + virtual Item *this_item() { return this; } + virtual const Item *this_item() const { return this; } + + /* + For SP local variable returns address of pointer to Item representing its + current value and pointer passed via parameter otherwise. + */ + virtual Item **this_item_addr(THD *thd, Item **addr_arg) { return addr_arg; } + + // Row emulation + virtual uint cols() { return 1; } + virtual Item* element_index(uint i) { return this; } + virtual Item** addr(uint i) { return 0; } + virtual bool check_cols(uint c); + // It is not row => null inside is impossible + virtual bool null_inside() { return 0; } + // used in row subselects to get value of elements + virtual void bring_value() {} + + // @infinidb pass in thd + Field *tmp_table_field_from_field_type(TABLE *table, bool fixed_length, THD* IDB_thd = 0); + virtual Item_field *filed_for_view_update() { return 0; } + + virtual Item *neg_transformer(THD *thd) { return NULL; } + virtual Item *update_value_transformer(uchar *select_arg) { return this; } + virtual Item *safe_charset_converter(CHARSET_INFO *tocs); + void delete_self() + { + cleanup(); + delete this; + } + + virtual bool is_splocal() { return 0; } /* Needed for error checking */ + + /* + Return Settable_routine_parameter interface of the Item. Return 0 + if this Item is not Settable_routine_parameter. + */ + virtual Settable_routine_parameter *get_settable_routine_parameter() + { + return 0; + } + /* + result_as_longlong() must return TRUE for Items representing DATE/TIME + functions and DATE/TIME table fields. + Those Items have result_type()==STRING_RESULT (and not INT_RESULT), but + their values should be compared as integers (because the integer + representation is more precise than the string one). + */ + virtual bool result_as_longlong() { return FALSE; } + bool is_datetime(); + virtual Field::geometry_type get_geometry_type() const + { return Field::GEOM_GEOMETRY; }; + String *check_well_formed_result(String *str, bool send_error= 0); + bool eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs); +}; + + +class sp_head; + + +class Item_basic_constant :public Item +{ +public: + /* to prevent drop fixed flag (no need parent cleanup call) */ + void cleanup() + { + /* + Restore the original field name as it might not have been allocated + in the statement memory. If the name is auto generated, it must be + done again between subsequent executions of a prepared statement. + */ + if (orig_name) + name= orig_name; + } +}; + + +/***************************************************************************** + The class is a base class for representation of stored routine variables in + the Item-hierarchy. There are the following kinds of SP-vars: + - local variables (Item_splocal); + - CASE expression (Item_case_expr); +*****************************************************************************/ + +class Item_sp_variable :public Item +{ +protected: + /* + THD, which is stored in fix_fields() and is used in this_item() to avoid + current_thd use. + */ + THD *m_thd; + +public: + LEX_STRING m_name; + +public: +#ifndef DBUG_OFF + /* + Routine to which this Item_splocal belongs. Used for checking if correct + runtime context is used for variable handling. + */ + sp_head *m_sp; +#endif + +public: + Item_sp_variable(char *sp_var_name_str, uint sp_var_name_length); + +public: + bool fix_fields(THD *thd, Item **); + + double val_real(); + longlong val_int(); + String *val_str(String *sp); + my_decimal *val_decimal(my_decimal *decimal_value); + bool is_null(); + +public: + inline void make_field(Send_field *field); + + inline bool const_item() const; + + inline int save_in_field(Field *field, bool no_conversions); + inline bool send(Protocol *protocol, String *str); +}; + +/***************************************************************************** + Item_sp_variable inline implementation. +*****************************************************************************/ + +inline void Item_sp_variable::make_field(Send_field *field) +{ + Item *it= this_item(); + + if (name) + it->set_name(name, (uint) strlen(name), system_charset_info); + else + it->set_name(m_name.str, (uint) m_name.length, system_charset_info); + it->make_field(field); +} + +inline bool Item_sp_variable::const_item() const +{ + return TRUE; +} + +inline int Item_sp_variable::save_in_field(Field *field, bool no_conversions) +{ + return this_item()->save_in_field(field, no_conversions); +} + +inline bool Item_sp_variable::send(Protocol *protocol, String *str) +{ + return this_item()->send(protocol, str); +} + + +/***************************************************************************** + A reference to local SP variable (incl. reference to SP parameter), used in + runtime. +*****************************************************************************/ + +class Item_splocal :public Item_sp_variable, + private Settable_routine_parameter +{ + uint m_var_idx; + + Type m_type; + Item_result m_result_type; + enum_field_types m_field_type; +public: + /* + Position of this reference to SP variable in the statement (the + statement itself is in sp_instr_stmt::m_query). + This is valid only for references to SP variables in statements, + excluding DECLARE CURSOR statement. It is used to replace references to SP + variables with NAME_CONST calls when putting statements into the binary + log. + Value of 0 means that this object doesn't corresponding to reference to + SP variable in query text. + */ + uint pos_in_query; + /* + Byte length of SP variable name in the statement (see pos_in_query). + The value of this field may differ from the name_length value because + name_length contains byte length of UTF8-encoded item name, but + the query string (see sp_instr_stmt::m_query) is currently stored with + a charset from the SET NAMES statement. + */ + uint len_in_query; + + Item_splocal(const LEX_STRING &sp_var_name, uint sp_var_idx, + enum_field_types sp_var_type, + uint pos_in_q= 0, uint len_in_q= 0); + + bool is_splocal() { return 1; } /* Needed for error checking */ + + Item *this_item(); + const Item *this_item() const; + Item **this_item_addr(THD *thd, Item **); + + virtual void print(String *str, enum_query_type query_type); + +public: + inline const LEX_STRING *my_name() const; + + inline uint get_var_idx() const; + + inline enum Type type() const; + inline Item_result result_type() const; + inline enum_field_types field_type() const { return m_field_type; } + +private: + bool set_value(THD *thd, sp_rcontext *ctx, Item **it); + +public: + Settable_routine_parameter *get_settable_routine_parameter() + { + return this; + } +}; + +/***************************************************************************** + Item_splocal inline implementation. +*****************************************************************************/ + +inline const LEX_STRING *Item_splocal::my_name() const +{ + return &m_name; +} + +inline uint Item_splocal::get_var_idx() const +{ + return m_var_idx; +} + +inline enum Item::Type Item_splocal::type() const +{ + return m_type; +} + +inline Item_result Item_splocal::result_type() const +{ + return m_result_type; +} + + +/***************************************************************************** + A reference to case expression in SP, used in runtime. +*****************************************************************************/ + +class Item_case_expr :public Item_sp_variable +{ +public: + Item_case_expr(uint case_expr_id); + +public: + Item *this_item(); + const Item *this_item() const; + Item **this_item_addr(THD *thd, Item **); + + inline enum Type type() const; + inline Item_result result_type() const; + +public: + /* + NOTE: print() is intended to be used from views and for debug. + Item_case_expr can not occur in views, so here it is only for debug + purposes. + */ + virtual void print(String *str, enum_query_type query_type); + +private: + uint m_case_expr_id; +}; + +/***************************************************************************** + Item_case_expr inline implementation. +*****************************************************************************/ + +inline enum Item::Type Item_case_expr::type() const +{ + return this_item()->type(); +} + +inline Item_result Item_case_expr::result_type() const +{ + return this_item()->result_type(); +} + + +/* + NAME_CONST(given_name, const_value). + This 'function' has all properties of the supplied const_value (which is + assumed to be a literal constant), and the name given_name. + + This is used to replace references to SP variables when we write PROCEDURE + statements into the binary log. + + TODO + Together with Item_splocal and Item::this_item() we can actually extract + common a base of this class and Item_splocal. Maybe it is possible to + extract a common base with class Item_ref, too. +*/ + +class Item_name_const : public Item +{ + Item *value_item; + Item *name_item; + bool valid_args; +public: + Item_name_const(Item *name_arg, Item *val); + + bool fix_fields(THD *, Item **); + + enum Type type() const; + double val_real(); + longlong val_int(); + String *val_str(String *sp); + my_decimal *val_decimal(my_decimal *); + bool is_null(); + virtual void print(String *str, enum_query_type query_type); + + Item_result result_type() const + { + return value_item->result_type(); + } + + bool const_item() const + { + return TRUE; + } + + int save_in_field(Field *field, bool no_conversions) + { + return value_item->save_in_field(field, no_conversions); + } + + bool send(Protocol *protocol, String *str) + { + return value_item->send(protocol, str); + } +}; + +bool agg_item_collations(DTCollation &c, const char *name, + Item **items, uint nitems, uint flags, int item_sep); +bool agg_item_collations_for_comparison(DTCollation &c, const char *name, + Item **items, uint nitems, uint flags); +bool agg_item_set_converter(DTCollation &coll, const char *fname, + Item **args, uint nargs, uint flags, int item_sep); +bool agg_item_charsets(DTCollation &c, const char *name, + Item **items, uint nitems, uint flags, int item_sep); + + +class Item_num: public Item_basic_constant +{ +public: + Item_num() {} /* Remove gcc warning */ + virtual Item_num *neg()= 0; + Item *safe_charset_converter(CHARSET_INFO *tocs); + bool check_partition_func_processor(uchar *int_arg) { return FALSE;} +}; + +#define NO_CACHED_FIELD_INDEX ((uint)(-1)) + +class st_select_lex; +class Item_ident :public Item +{ +protected: + /* + We have to store initial values of db_name, table_name and field_name + to be able to restore them during cleanup() because they can be + updated during fix_fields() to values from Field object and life-time + of those is shorter than life-time of Item_field. + */ + const char *orig_db_name; + const char *orig_table_name; + const char *orig_field_name; + +public: + Name_resolution_context *context; + const char *db_name; + const char *table_name; + const char *field_name; + bool alias_name_used; /* true if item was resolved against alias */ + /* + Cached value of index for this field in table->field array, used by prep. + stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX + if index value is not known. + */ + uint cached_field_index; + /* + Cached pointer to table which contains this field, used for the same reason + by prep. stmt. too in case then we have not-fully qualified field. + 0 - means no cached value. + */ + TABLE_LIST *cached_table; + st_select_lex *depended_from; + Item_ident(Name_resolution_context *context_arg, + const char *db_name_arg, const char *table_name_arg, + const char *field_name_arg); + Item_ident(THD *thd, Item_ident *item); + const char *full_name() const; + void cleanup(); + bool remove_dependence_processor(uchar * arg); + virtual void print(String *str, enum_query_type query_type); + virtual bool change_context_processor(uchar *cntx) + { context= (Name_resolution_context *)cntx; return FALSE; } + friend bool insert_fields(THD *thd, Name_resolution_context *context, + const char *db_name, + const char *table_name, List_iterator *it, + bool any_privileges); +}; + + +class Item_ident_for_show :public Item +{ +public: + Field *field; + const char *db_name; + const char *table_name; + + Item_ident_for_show(Field *par_field, const char *db_arg, + const char *table_name_arg) + :field(par_field), db_name(db_arg), table_name(table_name_arg) + {} + + enum Type type() const { return FIELD_ITEM; } + double val_real() { return field->val_real(); } + longlong val_int() { return field->val_int(); } + String *val_str(String *str) { return field->val_str(str); } + my_decimal *val_decimal(my_decimal *dec) { return field->val_decimal(dec); } + void make_field(Send_field *tmp_field); +}; + + +class Item_equal; +class COND_EQUAL; + +class Item_field :public Item_ident +{ +protected: + void set_field(Field *field); +public: + Field *field,*result_field; + Item_equal *item_equal; + bool no_const_subst; + /* + if any_privileges set to TRUE then here real effective privileges will + be stored + */ + uint have_privileges; + /* field need any privileges (for VIEW creation) */ + bool any_privileges; + Item_field(Name_resolution_context *context_arg, + const char *db_arg,const char *table_name_arg, + const char *field_name_arg); + /* + Constructor needed to process subselect with temporary tables (see Item) + */ + Item_field(THD *thd, Item_field *item); + /* + Constructor used inside setup_wild(), ensures that field, table, + and database names will live as long as Item_field (this is important + in prepared statements). + */ + Item_field(THD *thd, Name_resolution_context *context_arg, Field *field); + /* + If this constructor is used, fix_fields() won't work, because + db_name, table_name and column_name are unknown. It's necessary to call + reset_field() before fix_fields() for all fields created this way. + */ + Item_field(Field *field); + enum Type type() const { return FIELD_ITEM; } + bool eq(const Item *item, bool binary_cmp) const; + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + String *val_str(String*); + double val_result(); + longlong val_int_result(); + String *str_result(String* tmp); + my_decimal *val_decimal_result(my_decimal *); + bool val_bool_result(); + bool is_null_result(); + bool send(Protocol *protocol, String *str_arg); + void reset_field(Field *f); + bool fix_fields(THD *, Item **); + void make_field(Send_field *tmp_field); + int save_in_field(Field *field,bool no_conversions); + void save_org_in_field(Field *field); + table_map used_tables() const; + enum Item_result result_type () const + { + return field->result_type(); + } + Item_result cast_to_int_type() const + { + return field->cast_to_int_type(); + } + enum_field_types field_type() const + { + return field->type(); + } + enum_monotonicity_info get_monotonicity_info() const + { + return MONOTONIC_STRICT_INCREASING; + } + longlong val_int_endpoint(bool left_endp, bool *incl_endp); + Field *get_tmp_table_field() { return result_field; } + Field *tmp_table_field(TABLE *t_arg) { return result_field; } + bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + bool get_date_result(MYSQL_TIME *ltime,uint fuzzydate); + bool get_time(MYSQL_TIME *ltime); + bool is_null() { return field->is_null(); } + void update_null_value(); + Item *get_tmp_table_item(THD *thd); + bool collect_item_field_processor(uchar * arg); + bool find_item_in_field_list_processor(uchar *arg); + bool register_field_in_read_map(uchar *arg); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} + void cleanup(); + bool result_as_longlong() + { + return field->can_be_compared_as_longlong(); + } + Item_equal *find_item_equal(COND_EQUAL *cond_equal); + bool subst_argument_checker(uchar **arg); + Item *equal_fields_propagator(uchar *arg); + bool set_no_const_sub(uchar *arg); + Item *replace_equal_field(uchar *arg); + inline uint32 max_disp_length() { return field->max_display_length(); } + Item_field *filed_for_view_update() { return this; } + Item *safe_charset_converter(CHARSET_INFO *tocs); + int fix_outer_field(THD *thd, Field **field, Item **reference); + virtual Item *update_value_transformer(uchar *select_arg); + virtual void print(String *str, enum_query_type query_type); + Field::geometry_type get_geometry_type() const + { + DBUG_ASSERT(field_type() == MYSQL_TYPE_GEOMETRY); + return field->get_geometry_type(); + } + friend class Item_default_value; + friend class Item_insert_value; + friend class st_select_lex_unit; +}; + +class Item_null :public Item_basic_constant +{ +public: + Item_null(char *name_par=0) + { + maybe_null= null_value= TRUE; + max_length= 0; + name= name_par ? name_par : (char*) "NULL"; + fixed= 1; + collation.set(&my_charset_bin, DERIVATION_IGNORABLE); + } + enum Type type() const { return NULL_ITEM; } + bool eq(const Item *item, bool binary_cmp) const; + double val_real(); + longlong val_int(); + String *val_str(String *str); + my_decimal *val_decimal(my_decimal *); + int save_in_field(Field *field, bool no_conversions); + int save_safe_in_field(Field *field); + bool send(Protocol *protocol, String *str); + enum Item_result result_type () const { return STRING_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_NULL; } + bool basic_const_item() const { return 1; } + Item *clone_item() { return new Item_null(name); } + bool is_null() { return 1; } + + virtual inline void print(String *str, enum_query_type query_type) + { + str->append(STRING_WITH_LEN("NULL")); + } + + Item *safe_charset_converter(CHARSET_INFO *tocs); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + +class Item_null_result :public Item_null +{ +public: + Field *result_field; + Item_null_result() : Item_null(), result_field(0) {} + bool is_result_field() { return result_field != 0; } + void save_in_result_field(bool no_conversions) + { + save_in_field(result_field, no_conversions); + } + bool check_partition_func_processor(uchar *int_arg) {return TRUE;} +}; + +/* Item represents one placeholder ('?') of prepared statement */ + +class Item_param :public Item +{ + char cnvbuf[MAX_FIELD_WIDTH]; + String cnvstr; + Item *cnvitem; + +public: + enum enum_item_param_state + { + NO_VALUE, NULL_VALUE, INT_VALUE, REAL_VALUE, + STRING_VALUE, TIME_VALUE, LONG_DATA_VALUE, + DECIMAL_VALUE + } state; + + /* + A buffer for string and long data values. Historically all allocated + values returned from val_str() were treated as eligible to + modification. I. e. in some cases Item_func_concat can append it's + second argument to return value of the first one. Because of that we + can't return the original buffer holding string data from val_str(), + and have to have one buffer for data and another just pointing to + the data. This is the latter one and it's returned from val_str(). + Can not be declared inside the union as it's not a POD type. + */ + String str_value_ptr; + my_decimal decimal_value; + union + { + longlong integer; + double real; + /* + Character sets conversion info for string values. + Character sets of client and connection defined at bind time are used + for all conversions, even if one of them is later changed (i.e. + between subsequent calls to mysql_stmt_execute). + */ + struct CONVERSION_INFO + { + CHARSET_INFO *character_set_client; + CHARSET_INFO *character_set_of_placeholder; + /* + This points at character set of connection if conversion + to it is required (i. e. if placeholder typecode is not BLOB). + Otherwise it's equal to character_set_client (to simplify + check in convert_str_value()). + */ + CHARSET_INFO *final_character_set_of_str_value; + } cs_info; + MYSQL_TIME time; + } value; + + /* Cached values for virtual methods to save us one switch. */ + enum Item_result item_result_type; + enum Type item_type; + + /* + Used when this item is used in a temporary table. + This is NOT placeholder metadata sent to client, as this value + is assigned after sending metadata (in setup_one_conversion_function). + For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both + in result set and placeholders metadata, no matter what type you will + supply for this placeholder in mysql_stmt_execute. + */ + enum enum_field_types param_type; + /* + Offset of placeholder inside statement text. Used to create + no-placeholders version of this statement for the binary log. + */ + uint pos_in_query; + + Item_param(uint pos_in_query_arg); + + enum Item_result result_type () const { return item_result_type; } + enum Type type() const { return item_type; } + enum_field_types field_type() const { return param_type; } + + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal*); + String *val_str(String*); + bool get_time(MYSQL_TIME *tm); + bool get_date(MYSQL_TIME *tm, uint fuzzydate); + int save_in_field(Field *field, bool no_conversions); + + void set_null(); + void set_int(longlong i, uint32 max_length_arg); + void set_double(double i); + void set_decimal(const char *str, ulong length); + bool set_str(const char *str, ulong length); + bool set_longdata(const char *str, ulong length); + void set_time(MYSQL_TIME *tm, timestamp_type type, uint32 max_length_arg); + bool set_from_user_var(THD *thd, const user_var_entry *entry); + void reset(); + /* + Assign placeholder value from bind data. + Note, that 'len' has different semantics in embedded library (as we + don't need to check that packet is not broken there). See + sql_prepare.cc for details. + */ + void (*set_param_func)(Item_param *param, uchar **pos, ulong len); + + const String *query_val_str(String *str) const; + + bool convert_str_value(THD *thd); + + /* + If value for parameter was not set we treat it as non-const + so noone will use parameters value in fix_fields still + parameter is constant during execution. + */ + virtual table_map used_tables() const + { return state != NO_VALUE ? (table_map)0 : PARAM_TABLE_BIT; } + virtual void print(String *str, enum_query_type query_type); + bool is_null() + { DBUG_ASSERT(state != NO_VALUE); return state == NULL_VALUE; } + bool basic_const_item() const; + /* + This method is used to make a copy of a basic constant item when + propagating constants in the optimizer. The reason to create a new + item and not use the existing one is not precisely known (2005/04/16). + Probably we are trying to preserve tree structure of items, in other + words, avoid pointing at one item from two different nodes of the tree. + Return a new basic constant item if parameter value is a basic + constant, assert otherwise. This method is called only if + basic_const_item returned TRUE. + */ + Item *safe_charset_converter(CHARSET_INFO *tocs); + Item *clone_item(); + /* + Implement by-value equality evaluation if parameter value + is set and is a basic constant (integer, real or string). + Otherwise return FALSE. + */ + bool eq(const Item *item, bool binary_cmp) const; + /** Item is a argument to a limit clause. */ + bool limit_clause_param; + void set_param_type_and_swap_value(Item_param *from); +}; + + +class Item_int :public Item_num +{ +public: + longlong value; + Item_int(int32 i,uint length= MY_INT32_NUM_DECIMAL_DIGITS) + :value((longlong) i) + { max_length=length; fixed= 1; } + Item_int(longlong i,uint length= MY_INT64_NUM_DECIMAL_DIGITS) + :value(i) + { max_length=length; fixed= 1; } + Item_int(ulonglong i, uint length= MY_INT64_NUM_DECIMAL_DIGITS) + :value((longlong)i) + { max_length=length; fixed= 1; unsigned_flag= 1; } + Item_int(const char *str_arg,longlong i,uint length) :value(i) + { max_length=length; name=(char*) str_arg; fixed= 1; } + Item_int(const char *str_arg, uint length=64); + enum Type type() const { return INT_ITEM; } + enum Item_result result_type () const { return INT_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_LONGLONG; } + longlong val_int() { DBUG_ASSERT(fixed == 1); return value; } + double val_real() { DBUG_ASSERT(fixed == 1); return (double) value; } + my_decimal *val_decimal(my_decimal *); + String *val_str(String*); + int save_in_field(Field *field, bool no_conversions); + bool basic_const_item() const { return 1; } + Item *clone_item() { return new Item_int(name,value,max_length); } + virtual void print(String *str, enum_query_type query_type); + Item_num *neg() { value= -value; return this; } + uint decimal_precision() const + { return (uint)(max_length - test(value < 0)); } + bool eq(const Item *, bool binary_cmp) const; + bool check_partition_func_processor(uchar *bool_arg) { return FALSE;} +}; + + +class Item_uint :public Item_int +{ +public: + Item_uint(const char *str_arg, uint length); + Item_uint(ulonglong i) :Item_int((ulonglong) i, 10) {} + Item_uint(const char *str_arg, longlong i, uint length); + double val_real() + { DBUG_ASSERT(fixed == 1); return ulonglong2double((ulonglong)value); } + String *val_str(String*); + Item *clone_item() { return new Item_uint(name, value, max_length); } + int save_in_field(Field *field, bool no_conversions); + virtual void print(String *str, enum_query_type query_type); + Item_num *neg (); + uint decimal_precision() const { return max_length; } + bool check_partition_func_processor(uchar *bool_arg) { return FALSE;} +}; + + +/* decimal (fixed point) constant */ +class Item_decimal :public Item_num +{ +protected: + my_decimal decimal_value; +public: + Item_decimal(const char *str_arg, uint length, CHARSET_INFO *charset); + Item_decimal(const char *str, const my_decimal *val_arg, + uint decimal_par, uint length); + Item_decimal(my_decimal *value_par); + Item_decimal(longlong val, bool unsig); + Item_decimal(double val, int precision, int scale); + Item_decimal(const uchar *bin, int precision, int scale); + + enum Type type() const { return DECIMAL_ITEM; } + enum Item_result result_type () const { return DECIMAL_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_NEWDECIMAL; } + longlong val_int(); + double val_real(); + String *val_str(String*); + my_decimal *val_decimal(my_decimal *val) { return &decimal_value; } + int save_in_field(Field *field, bool no_conversions); + bool basic_const_item() const { return 1; } + Item *clone_item() + { + return new Item_decimal(name, &decimal_value, decimals, max_length); + } + virtual void print(String *str, enum_query_type query_type); + Item_num *neg() + { + my_decimal_neg(&decimal_value); + unsigned_flag= !decimal_value.sign(); + return this; + } + uint decimal_precision() const { return decimal_value.precision(); } + bool eq(const Item *, bool binary_cmp) const; + void set_decimal_value(my_decimal *value_par); + bool check_partition_func_processor(uchar *bool_arg) { return FALSE;} +}; + + +class Item_float :public Item_num +{ + char *presentation; +public: + double value; + // Item_real() :value(0) {} + Item_float(const char *str_arg, uint length); + Item_float(const char *str,double val_arg,uint decimal_par,uint length) + :value(val_arg) + { + presentation= name=(char*) str; + decimals=(uint8) decimal_par; + max_length=length; + fixed= 1; + } + Item_float(double value_par, uint decimal_par) :presentation(0), value(value_par) + { + decimals= (uint8) decimal_par; + fixed= 1; + } + int save_in_field(Field *field, bool no_conversions); + enum Type type() const { return REAL_ITEM; } + enum_field_types field_type() const { return MYSQL_TYPE_DOUBLE; } + double val_real() { DBUG_ASSERT(fixed == 1); return value; } + longlong val_int() + { + DBUG_ASSERT(fixed == 1); + if (value <= (double) LONGLONG_MIN) + { + return LONGLONG_MIN; + } + else if (value >= (double) (ulonglong) LONGLONG_MAX) + { + return LONGLONG_MAX; + } + return (longlong) rint(value); + } + String *val_str(String*); + my_decimal *val_decimal(my_decimal *); + bool basic_const_item() const { return 1; } + Item *clone_item() + { return new Item_float(name, value, decimals, max_length); } + Item_num *neg() { value= -value; return this; } + virtual void print(String *str, enum_query_type query_type); + bool eq(const Item *, bool binary_cmp) const; +}; + + +class Item_static_float_func :public Item_float +{ + const char *func_name; +public: + Item_static_float_func(const char *str, double val_arg, uint decimal_par, + uint length) + :Item_float(NullS, val_arg, decimal_par, length), func_name(str) + {} + + virtual inline void print(String *str, enum_query_type query_type) + { + str->append(func_name); + } + + Item *safe_charset_converter(CHARSET_INFO *tocs); +}; + + +class Item_string :public Item_basic_constant +{ +public: + Item_string(const char *str,uint length, + CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE, + uint repertoire= MY_REPERTOIRE_UNICODE30) + : m_cs_specified(FALSE) + { + str_value.set_or_copy_aligned(str, length, cs); + collation.set(cs, dv, repertoire); + /* + We have to have a different max_length than 'length' here to + ensure that we get the right length if we do use the item + to create a new table. In this case max_length must be the maximum + number of chars for a string of this type because we in Create_field:: + divide the max_length with mbmaxlen). + */ + max_length= str_value.numchars()*cs->mbmaxlen; + set_name(str, length, cs); + decimals=NOT_FIXED_DEC; + // it is constant => can be used without fix_fields (and frequently used) + fixed= 1; + } + /* Just create an item and do not fill string representation */ + Item_string(CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE) + : m_cs_specified(FALSE) + { + collation.set(cs, dv); + max_length= 0; + set_name(NULL, 0, cs); + decimals= NOT_FIXED_DEC; + fixed= 1; + } + Item_string(const char *name_par, const char *str, uint length, + CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE, + uint repertoire= MY_REPERTOIRE_UNICODE30) + : m_cs_specified(FALSE) + { + str_value.set_or_copy_aligned(str, length, cs); + collation.set(cs, dv, repertoire); + max_length= str_value.numchars()*cs->mbmaxlen; + set_name(name_par, 0, cs); + decimals=NOT_FIXED_DEC; + // it is constant => can be used without fix_fields (and frequently used) + fixed= 1; + } + /* + This is used in stored procedures to avoid memory leaks and + does a deep copy of its argument. + */ + void set_str_with_copy(const char *str_arg, uint length_arg) + { + str_value.copy(str_arg, length_arg, collation.collation); + max_length= str_value.numchars() * collation.collation->mbmaxlen; + } + void set_repertoire_from_value() + { + collation.repertoire= my_string_repertoire(str_value.charset(), + str_value.ptr(), + str_value.length()); + } + enum Type type() const { return STRING_ITEM; } + double val_real(); + longlong val_int(); + String *val_str(String*) + { + DBUG_ASSERT(fixed == 1); + return (String*) &str_value; + } + my_decimal *val_decimal(my_decimal *); + int save_in_field(Field *field, bool no_conversions); + enum Item_result result_type () const { return STRING_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_VARCHAR; } + bool basic_const_item() const { return 1; } + bool eq(const Item *item, bool binary_cmp) const; + Item *clone_item() + { + return new Item_string(name, str_value.ptr(), + str_value.length(), collation.collation); + } + Item *safe_charset_converter(CHARSET_INFO *tocs); + inline void append(char *str, uint length) + { + str_value.append(str, length); + max_length= str_value.numchars() * collation.collation->mbmaxlen; + } + virtual void print(String *str, enum_query_type query_type); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} + + /** + Return TRUE if character-set-introducer was explicitly specified in the + original query for this item (text literal). + + This operation is to be called from Item_string::print(). The idea is + that when a query is generated (re-constructed) from the Item-tree, + character-set-introducers should appear only for those literals, where + they were explicitly specified by the user. Otherwise, that may lead to + loss collation information (character set introducers implies default + collation for the literal). + + Basically, that makes sense only for views and hopefully will be gone + one day when we start using original query as a view definition. + + @return This operation returns the value of m_cs_specified attribute. + @retval TRUE if character set introducer was explicitly specified in + the original query. + @retval FALSE otherwise. + */ + inline bool is_cs_specified() const + { + return m_cs_specified; + } + + /** + Set the value of m_cs_specified attribute. + + m_cs_specified attribute shows whether character-set-introducer was + explicitly specified in the original query for this text literal or + not. The attribute makes sense (is used) only for views. + + This operation is to be called from the parser during parsing an input + query. + */ + inline void set_cs_specified(bool cs_specified) + { + m_cs_specified= cs_specified; + } + +private: + bool m_cs_specified; +}; + + +longlong +longlong_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end); +double +double_from_string_with_check (CHARSET_INFO *cs, const char *cptr, char *end); + +class Item_static_string_func :public Item_string +{ + const char *func_name; +public: + Item_static_string_func(const char *name_par, const char *str, uint length, + CHARSET_INFO *cs, + Derivation dv= DERIVATION_COERCIBLE) + :Item_string(NullS, str, length, cs, dv), func_name(name_par) + {} + Item *safe_charset_converter(CHARSET_INFO *tocs); + + virtual inline void print(String *str, enum_query_type query_type) + { + str->append(func_name); + } + + bool check_partition_func_processor(uchar *int_arg) {return TRUE;} +}; + + +/* for show tables */ +class Item_partition_func_safe_string: public Item_string +{ +public: + Item_partition_func_safe_string(const char *name, uint length, + CHARSET_INFO *cs= NULL): + Item_string(name, length, cs) + {} +}; + + +class Item_return_date_time :public Item_partition_func_safe_string +{ + enum_field_types date_time_field_type; +public: + Item_return_date_time(const char *name_arg, enum_field_types field_type_arg) + :Item_partition_func_safe_string(name_arg, 0, &my_charset_bin), + date_time_field_type(field_type_arg) + { } + enum_field_types field_type() const { return date_time_field_type; } +}; + + +class Item_blob :public Item_partition_func_safe_string +{ +public: + Item_blob(const char *name, uint length) : + Item_partition_func_safe_string(name, length, &my_charset_bin) + { max_length= length; } + enum Type type() const { return TYPE_HOLDER; } + enum_field_types field_type() const { return MYSQL_TYPE_BLOB; } +}; + + +/** + Item_empty_string -- is a utility class to put an item into List + which is then used in protocol.send_fields() when sending SHOW output to + the client. +*/ + +class Item_empty_string :public Item_partition_func_safe_string +{ +public: + Item_empty_string(const char *header,uint length, CHARSET_INFO *cs= NULL) : + Item_partition_func_safe_string("",0, cs ? cs : &my_charset_utf8_general_ci) + { name=(char*) header; max_length= length * collation.collation->mbmaxlen; } + void make_field(Send_field *field); +}; + + +class Item_return_int :public Item_int +{ + enum_field_types int_field_type; +public: + Item_return_int(const char *name_arg, uint length, + enum_field_types field_type_arg, longlong value= 0) + :Item_int(name_arg, value, length), int_field_type(field_type_arg) + { + unsigned_flag=1; + } + enum_field_types field_type() const { return int_field_type; } +}; + + +class Item_hex_string: public Item_basic_constant +{ +public: + Item_hex_string() {} + Item_hex_string(const char *str,uint str_length); + enum Type type() const { return VARBIN_ITEM; } + double val_real() + { + DBUG_ASSERT(fixed == 1); + return (double) (ulonglong) Item_hex_string::val_int(); + } + longlong val_int(); + bool basic_const_item() const { return 1; } + String *val_str(String*) { DBUG_ASSERT(fixed == 1); return &str_value; } + my_decimal *val_decimal(my_decimal *); + int save_in_field(Field *field, bool no_conversions); + enum Item_result result_type () const { return STRING_RESULT; } + enum Item_result cast_to_int_type() const { return INT_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_VARCHAR; } + virtual void print(String *str, enum_query_type query_type); + bool eq(const Item *item, bool binary_cmp) const; + virtual Item *safe_charset_converter(CHARSET_INFO *tocs); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_bin_string: public Item_hex_string +{ +public: + Item_bin_string(const char *str,uint str_length); +}; + +class Item_result_field :public Item /* Item with result field */ +{ +public: + Field *result_field; /* Save result here */ + Item_result_field() :result_field(0) {} + // Constructor used for Item_sum/Item_cond_and/or (see Item comment) + Item_result_field(THD *thd, Item_result_field *item): + Item(thd, item), result_field(item->result_field) + {} + ~Item_result_field() {} /* Required with gcc 2.95 */ + Field *get_tmp_table_field() { return result_field; } + Field *tmp_table_field(TABLE *t_arg) { return result_field; } + table_map used_tables() const { return 1; } + virtual void fix_length_and_dec()=0; + void set_result_field(Field *field) { result_field= field; } + bool is_result_field() { return 1; } + void save_in_result_field(bool no_conversions) + { + save_in_field(result_field, no_conversions); + } + void cleanup(); +}; + + +class Item_ref :public Item_ident +{ +protected: + void set_properties(); +public: + enum Ref_Type { REF, DIRECT_REF, VIEW_REF, OUTER_REF, AGGREGATE_REF }; + Field *result_field; /* Save result here */ + Item **ref; + Item_ref(Name_resolution_context *context_arg, + const char *db_arg, const char *table_name_arg, + const char *field_name_arg) + :Item_ident(context_arg, db_arg, table_name_arg, field_name_arg), + result_field(0), ref(0) {} + /* + This constructor is used in two scenarios: + A) *item = NULL + No initialization is performed, fix_fields() call will be necessary. + + B) *item points to an Item this Item_ref will refer to. This is + used for GROUP BY. fix_fields() will not be called in this case, + so we call set_properties to make this item "fixed". set_properties + performs a subset of action Item_ref::fix_fields does, and this subset + is enough for Item_ref's used in GROUP BY. + + TODO we probably fix a superset of problems like in BUG#6658. Check this + with Bar, and if we have a more broader set of problems like this. + */ + Item_ref(Name_resolution_context *context_arg, Item **item, + const char *table_name_arg, const char *field_name_arg, + bool alias_name_used_arg= FALSE); + + /* Constructor need to process subselect with temporary tables (see Item) */ + Item_ref(THD *thd, Item_ref *item) + :Item_ident(thd, item), result_field(item->result_field), ref(item->ref) {} + enum Type type() const { return REF_ITEM; } + bool eq(const Item *item, bool binary_cmp) const + { + Item *it= ((Item *) item)->real_item(); + return ref && (*ref)->eq(it, binary_cmp); + } + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + bool val_bool(); + String *val_str(String* tmp); + bool is_null(); + bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + double val_result(); + longlong val_int_result(); + String *str_result(String* tmp); + my_decimal *val_decimal_result(my_decimal *); + bool val_bool_result(); + bool is_null_result(); + bool send(Protocol *prot, String *tmp); + void make_field(Send_field *field); + bool fix_fields(THD *, Item **); + int save_in_field(Field *field, bool no_conversions); + void save_org_in_field(Field *field); + enum Item_result result_type () const { return (*ref)->result_type(); } + enum_field_types field_type() const { return (*ref)->field_type(); } + Field *get_tmp_table_field() + { return result_field ? result_field : (*ref)->get_tmp_table_field(); } + Item *get_tmp_table_item(THD *thd); + table_map used_tables() const + { + return depended_from ? OUTER_REF_TABLE_BIT : (*ref)->used_tables(); + } + void update_used_tables() + { + if (!depended_from) + (*ref)->update_used_tables(); + } + table_map not_null_tables() const { return (*ref)->not_null_tables(); } + void set_result_field(Field *field) { result_field= field; } + bool is_result_field() { return 1; } + void save_in_result_field(bool no_conversions) + { + (*ref)->save_in_field(result_field, no_conversions); + } + Item *real_item() + { + return ref ? (*ref)->real_item() : this; + } + bool walk(Item_processor processor, bool walk_subquery, uchar *arg) + { return (*ref)->walk(processor, walk_subquery, arg); } + virtual void print(String *str, enum_query_type query_type); + bool result_as_longlong() + { + return (*ref)->result_as_longlong(); + } + void cleanup(); + Item_field *filed_for_view_update() + { return (*ref)->filed_for_view_update(); } + virtual Ref_Type ref_type() { return REF; } + + // Row emulation: forwarding of ROW-related calls to ref + uint cols() + { + return ref && result_type() == ROW_RESULT ? (*ref)->cols() : 1; + } + Item* element_index(uint i) + { + return ref && result_type() == ROW_RESULT ? (*ref)->element_index(i) : this; + } + Item** addr(uint i) + { + return ref && result_type() == ROW_RESULT ? (*ref)->addr(i) : 0; + } + bool check_cols(uint c) + { + return ref && result_type() == ROW_RESULT ? (*ref)->check_cols(c) + : Item::check_cols(c); + } + bool null_inside() + { + return ref && result_type() == ROW_RESULT ? (*ref)->null_inside() : 0; + } + void bring_value() + { + if (ref && result_type() == ROW_RESULT) + (*ref)->bring_value(); + } + +}; + + +/* + The same as Item_ref, but get value from val_* family of method to get + value of item on which it referred instead of result* family. +*/ +class Item_direct_ref :public Item_ref +{ +public: + Item_direct_ref(Name_resolution_context *context_arg, Item **item, + const char *table_name_arg, + const char *field_name_arg, + bool alias_name_used_arg= FALSE) + :Item_ref(context_arg, item, table_name_arg, + field_name_arg, alias_name_used_arg) + {} + /* Constructor need to process subselect with temporary tables (see Item) */ + Item_direct_ref(THD *thd, Item_direct_ref *item) : Item_ref(thd, item) {} + + double val_real(); + longlong val_int(); + String *val_str(String* tmp); + my_decimal *val_decimal(my_decimal *); + bool val_bool(); + bool is_null(); + bool get_date(MYSQL_TIME *ltime,uint fuzzydate); + virtual Ref_Type ref_type() { return DIRECT_REF; } +}; + +/* + Class for view fields, the same as Item_direct_ref, but call fix_fields + of reference if it is not called yet +*/ +class Item_direct_view_ref :public Item_direct_ref +{ +public: + Item_direct_view_ref(Name_resolution_context *context_arg, Item **item, + const char *table_name_arg, + const char *field_name_arg) + :Item_direct_ref(context_arg, item, table_name_arg, field_name_arg) {} + /* Constructor need to process subselect with temporary tables (see Item) */ + Item_direct_view_ref(THD *thd, Item_direct_ref *item) + :Item_direct_ref(thd, item) {} + + bool fix_fields(THD *, Item **); + bool eq(const Item *item, bool binary_cmp) const; + Item *get_tmp_table_item(THD *thd) + { + Item *item= Item_ref::get_tmp_table_item(thd); + item->name= name; + return item; + } + virtual Ref_Type ref_type() { return VIEW_REF; } +}; + + +/* + Class for outer fields. + An object of this class is created when the select where the outer field was + resolved is a grouping one. After it has been fixed the ref field will point + to either an Item_ref or an Item_direct_ref object which will be used to + access the field. + See also comments for the fix_inner_refs() and the + Item_field::fix_outer_field() functions. +*/ + +class Item_sum; +class Item_outer_ref :public Item_direct_ref +{ +public: + Item *outer_ref; + /* The aggregate function under which this outer ref is used, if any. */ + Item_sum *in_sum_func; + /* + TRUE <=> that the outer_ref is already present in the select list + of the outer select. + */ + bool found_in_select_list; + Item_outer_ref(Name_resolution_context *context_arg, + Item_field *outer_field_arg) + :Item_direct_ref(context_arg, 0, outer_field_arg->table_name, + outer_field_arg->field_name), + outer_ref(outer_field_arg), in_sum_func(0), + found_in_select_list(0) + { + ref= &outer_ref; + set_properties(); + fixed= 0; + } + Item_outer_ref(Name_resolution_context *context_arg, Item **item, + const char *table_name_arg, const char *field_name_arg, + bool alias_name_used_arg) + :Item_direct_ref(context_arg, item, table_name_arg, field_name_arg, + alias_name_used_arg), + outer_ref(0), in_sum_func(0), found_in_select_list(1) + {} + void save_in_result_field(bool no_conversions) + { + outer_ref->save_org_in_field(result_field); + } + bool fix_fields(THD *, Item **); + table_map used_tables() const + { + return (*ref)->const_item() ? 0 : OUTER_REF_TABLE_BIT; + } + virtual Ref_Type ref_type() { return OUTER_REF; } +}; + + +class Item_in_subselect; + + +/* + An object of this class: + - Converts val_XXX() calls to ref->val_XXX_result() calls, like Item_ref. + - Sets owner->was_null=TRUE if it has returned a NULL value from any + val_XXX() function. This allows to inject an Item_ref_null_helper + object into subquery and then check if the subquery has produced a row + with NULL value. +*/ + +class Item_ref_null_helper: public Item_ref +{ +protected: + Item_in_subselect* owner; +public: + Item_ref_null_helper(Name_resolution_context *context_arg, + Item_in_subselect* master, Item **item, + const char *table_name_arg, const char *field_name_arg) + :Item_ref(context_arg, item, table_name_arg, field_name_arg), + owner(master) {} + double val_real(); + longlong val_int(); + String* val_str(String* s); + my_decimal *val_decimal(my_decimal *); + bool val_bool(); + bool get_date(MYSQL_TIME *ltime, uint fuzzydate); + virtual void print(String *str, enum_query_type query_type); + /* + we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE + */ + table_map used_tables() const + { + return (depended_from ? + OUTER_REF_TABLE_BIT : + (*ref)->used_tables() | RAND_TABLE_BIT); + } +}; + +/* + The following class is used to optimize comparing of date and bigint columns + We need to save the original item ('ref') to be able to call + ref->save_in_field(). This is used to create index search keys. + + An instance of Item_int_with_ref may have signed or unsigned integer value. + +*/ + +class Item_int_with_ref :public Item_int +{ + Item *ref; +public: + Item_int_with_ref(longlong i, Item *ref_arg, my_bool unsigned_arg) : + Item_int(i), ref(ref_arg) + { + unsigned_flag= unsigned_arg; + } + int save_in_field(Field *field, bool no_conversions) + { + return ref->save_in_field(field, no_conversions); + } + Item *clone_item(); + virtual Item *real_item() { return ref; } +}; + +#ifdef MYSQL_SERVER +#include "gstream.h" +#include "spatial.h" +#include "item_sum.h" +#include "item_func.h" +#include "item_row.h" +#include "item_cmpfunc.h" +#include "item_strfunc.h" +#include "item_geofunc.h" +#include "item_timefunc.h" +#include "item_subselect.h" +#include "item_xmlfunc.h" +#endif + +/** + Base class to implement typed value caching Item classes + + Item_copy_ classes are very similar to the corresponding Item_ + classes (e.g. Item_copy_int is similar to Item_int) but they add + the following additional functionality to Item_ : + 1. Nullability + 2. Possibility to store the value not only on instantiation time, + but also later. + Item_copy_ classes are a functionality subset of Item_cache_ + classes, as e.g. they don't support comparisons with the original Item + as Item_cache_ classes do. + Item_copy_ classes are used in GROUP BY calculation. + TODO: Item_copy should be made an abstract interface and Item_copy_ + classes should inherit both the respective Item_ class and the interface. + Ideally we should drop Item_copy_ classes altogether and merge + their functionality to Item_cache_ (and these should be made to inherit + from Item_). +*/ + +class Item_copy :public Item +{ +protected: + + /** + Stores the type of the resulting field that would be used to store the data + in the cache. This is to avoid calls to the original item. + */ + enum enum_field_types cached_field_type; + + /** The original item that is copied */ + Item *item; + + /** + Stores the result type of the original item, so it can be returned + without calling the original item's method + */ + Item_result cached_result_type; + + /** + Constructor of the Item_copy class + + stores metadata information about the original class as well as a + pointer to it. + */ + Item_copy(Item *i) + { + item= i; + null_value=maybe_null=item->maybe_null; + decimals=item->decimals; + max_length=item->max_length; + name=item->name; + cached_field_type= item->field_type(); + cached_result_type= item->result_type(); + unsigned_flag= item->unsigned_flag; + } + +public: + /** + Factory method to create the appropriate subclass dependent on the type of + the original item. + + @param item the original item. + */ + static Item_copy *create (Item *item); + + /** + Update the cache with the value of the original item + + This is the method that updates the cached value. + It must be explicitly called by the user of this class to store the value + of the orginal item in the cache. + */ + virtual void copy() = 0; + + Item *get_item() { return item; } + /** All of the subclasses should have the same type tag */ + enum Type type() const { return COPY_STR_ITEM; } + enum_field_types field_type() const { return cached_field_type; } + enum Item_result result_type () const { return cached_result_type; } + + void make_field(Send_field *field) { item->make_field(field); } + table_map used_tables() const { return (table_map) 1L; } + bool const_item() const { return 0; } + bool is_null() { return null_value; } + + /* + Override the methods below as pure virtual to make sure all the + sub-classes implement them. + */ + + virtual String *val_str(String*) = 0; + virtual my_decimal *val_decimal(my_decimal *) = 0; + virtual double val_real() = 0; + virtual longlong val_int() = 0; + virtual int save_in_field(Field *field, bool no_conversions) = 0; +}; + +/** + Implementation of a string cache. + + Uses Item::str_value for storage +*/ +class Item_copy_string : public Item_copy +{ +public: + Item_copy_string (Item *item) : Item_copy(item) {} + + String *val_str(String*); + my_decimal *val_decimal(my_decimal *); + double val_real(); + longlong val_int(); + void copy(); + int save_in_field(Field *field, bool no_conversions); +}; + + +class Item_copy_int : public Item_copy +{ +protected: + longlong cached_value; +public: + Item_copy_int (Item *i) : Item_copy(i) {} + int save_in_field(Field *field, bool no_conversions); + + virtual String *val_str(String*); + virtual my_decimal *val_decimal(my_decimal *); + virtual double val_real() + { + return null_value ? 0.0 : (double) cached_value; + } + virtual longlong val_int() + { + return null_value ? LL(0) : cached_value; + } + virtual void copy(); +}; + + +class Item_copy_uint : public Item_copy_int +{ +public: + Item_copy_uint (Item *item) : Item_copy_int(item) + { + unsigned_flag= 1; + } + + String *val_str(String*); + double val_real() + { + return null_value ? 0.0 : (double) (ulonglong) cached_value; + } +}; + + +class Item_copy_float : public Item_copy +{ +protected: + double cached_value; +public: + Item_copy_float (Item *i) : Item_copy(i) {} + int save_in_field(Field *field, bool no_conversions); + + String *val_str(String*); + my_decimal *val_decimal(my_decimal *); + double val_real() + { + return null_value ? 0.0 : cached_value; + } + longlong val_int() + { + return (longlong) rint(val_real()); + } + void copy() + { + cached_value= item->val_real(); + null_value= item->null_value; + } +}; + + +class Item_copy_decimal : public Item_copy +{ +protected: + my_decimal cached_value; +public: + Item_copy_decimal (Item *i) : Item_copy(i) {} + int save_in_field(Field *field, bool no_conversions); + + String *val_str(String*); + my_decimal *val_decimal(my_decimal *) + { + return null_value ? NULL: &cached_value; + } + double val_real(); + longlong val_int(); + void copy(); +}; + + +class Cached_item :public Sql_alloc +{ +public: + my_bool null_value; + Cached_item() :null_value(0) {} + virtual bool cmp(void)=0; + virtual ~Cached_item(); /*line -e1509 */ +}; + +class Cached_item_str :public Cached_item +{ + Item *item; + String value,tmp_value; +public: + Cached_item_str(THD *thd, Item *arg); + bool cmp(void); + ~Cached_item_str(); // Deallocate String:s +}; + + +class Cached_item_real :public Cached_item +{ + Item *item; + double value; +public: + Cached_item_real(Item *item_par) :item(item_par),value(0.0) {} + bool cmp(void); +}; + +class Cached_item_int :public Cached_item +{ + Item *item; + longlong value; +public: + Cached_item_int(Item *item_par) :item(item_par),value(0) {} + bool cmp(void); +}; + + +class Cached_item_decimal :public Cached_item +{ + Item *item; + my_decimal value; +public: + Cached_item_decimal(Item *item_par); + bool cmp(void); +}; + +class Cached_item_field :public Cached_item +{ + uchar *buff; + Field *field; + uint length; + +public: + Cached_item_field(Item_field *item) + { + field= item->field; + buff= (uchar*) sql_calloc(length=field->pack_length()); + } + bool cmp(void); +}; + +class Item_default_value : public Item_field +{ +public: + Item *arg; + Item_default_value(Name_resolution_context *context_arg) + :Item_field(context_arg, (const char *)NULL, (const char *)NULL, + (const char *)NULL), + arg(NULL) {} + Item_default_value(Name_resolution_context *context_arg, Item *a) + :Item_field(context_arg, (const char *)NULL, (const char *)NULL, + (const char *)NULL), + arg(a) {} + enum Type type() const { return DEFAULT_VALUE_ITEM; } + bool eq(const Item *item, bool binary_cmp) const; + bool fix_fields(THD *, Item **); + virtual void print(String *str, enum_query_type query_type); + int save_in_field(Field *field_arg, bool no_conversions); + table_map used_tables() const { return (table_map)0L; } + + bool walk(Item_processor processor, bool walk_subquery, uchar *args) + { + return arg->walk(processor, walk_subquery, args) || + (this->*processor)(args); + } + + Item *transform(Item_transformer transformer, uchar *args); +}; + +/* + Item_insert_value -- an implementation of VALUES() function. + You can use the VALUES(col_name) function in the UPDATE clause + to refer to column values from the INSERT portion of the INSERT + ... UPDATE statement. In other words, VALUES(col_name) in the + UPDATE clause refers to the value of col_name that would be + inserted, had no duplicate-key conflict occurred. + In all other places this function returns NULL. +*/ + +class Item_insert_value : public Item_field +{ +public: + Item *arg; + Item_insert_value(Name_resolution_context *context_arg, Item *a) + :Item_field(context_arg, (const char *)NULL, (const char *)NULL, + (const char *)NULL), + arg(a) {} + bool eq(const Item *item, bool binary_cmp) const; + bool fix_fields(THD *, Item **); + virtual void print(String *str, enum_query_type query_type); + int save_in_field(Field *field_arg, bool no_conversions) + { + return Item_field::save_in_field(field_arg, no_conversions); + } + /* + We use RAND_TABLE_BIT to prevent Item_insert_value from + being treated as a constant and precalculated before execution + */ + table_map used_tables() const { return RAND_TABLE_BIT; } + + bool walk(Item_processor processor, bool walk_subquery, uchar *args) + { + return arg->walk(processor, walk_subquery, args) || + (this->*processor)(args); + } +}; + + +/* + We need this two enums here instead of sql_lex.h because + at least one of them is used by Item_trigger_field interface. + + Time when trigger is invoked (i.e. before or after row actually + inserted/updated/deleted). +*/ +enum trg_action_time_type +{ + TRG_ACTION_BEFORE= 0, TRG_ACTION_AFTER= 1, TRG_ACTION_MAX +}; + +class Table_triggers_list; + +/* + Represents NEW/OLD version of field of row which is + changed/read in trigger. + + Note: For this item main part of actual binding to Field object happens + not during fix_fields() call (like for Item_field) but right after + parsing of trigger definition, when table is opened, with special + setup_field() call. On fix_fields() stage we simply choose one of + two Field instances representing either OLD or NEW version of this + field. +*/ +class Item_trigger_field : public Item_field, + private Settable_routine_parameter +{ +public: + /* Is this item represents row from NEW or OLD row ? */ + enum row_version_type {OLD_ROW, NEW_ROW}; + row_version_type row_version; + /* Next in list of all Item_trigger_field's in trigger */ + Item_trigger_field *next_trg_field; + /* Index of the field in the TABLE::field array */ + uint field_idx; + /* Pointer to Table_trigger_list object for table of this trigger */ + Table_triggers_list *triggers; + + Item_trigger_field(Name_resolution_context *context_arg, + row_version_type row_ver_arg, + const char *field_name_arg, + ulong priv, const bool ro) + :Item_field(context_arg, + (const char *)NULL, (const char *)NULL, field_name_arg), + row_version(row_ver_arg), field_idx((uint)-1), original_privilege(priv), + want_privilege(priv), table_grants(NULL), read_only (ro) + {} + void setup_field(THD *thd, TABLE *table, GRANT_INFO *table_grant_info); + enum Type type() const { return TRIGGER_FIELD_ITEM; } + bool eq(const Item *item, bool binary_cmp) const; + bool fix_fields(THD *, Item **); + virtual void print(String *str, enum_query_type query_type); + table_map used_tables() const { return (table_map)0L; } + Field *get_tmp_table_field() { return 0; } + Item *copy_or_same(THD *thd) { return this; } + Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); } + void cleanup(); + +private: + void set_required_privilege(bool rw); + bool set_value(THD *thd, sp_rcontext *ctx, Item **it); + +public: + Settable_routine_parameter *get_settable_routine_parameter() + { + return (read_only ? 0 : this); + } + + bool set_value(THD *thd, Item **it) + { + return set_value(thd, NULL, it); + } + +private: + /* + 'want_privilege' holds privileges required to perform operation on + this trigger field (SELECT_ACL if we are going to read it and + UPDATE_ACL if we are going to update it). It is initialized at + parse time but can be updated later if this trigger field is used + as OUT or INOUT parameter of stored routine (in this case + set_required_privilege() is called to appropriately update + want_privilege and cleanup() is responsible for restoring of + original want_privilege once parameter's value is updated). + */ + ulong original_privilege; + ulong want_privilege; + GRANT_INFO *table_grants; + /* + Trigger field is read-only unless it belongs to the NEW row in a + BEFORE INSERT of BEFORE UPDATE trigger. + */ + bool read_only; +}; + + +class Item_cache: public Item_basic_constant +{ +protected: + Item *example; + table_map used_table_map; + /* + Field that this object will get value from. This is set/used by + index-based subquery engines to detect and remove the equality injected + by IN->EXISTS transformation. + For all other uses of Item_cache, cached_field doesn't matter. + */ + Field *cached_field; + enum enum_field_types cached_field_type; +public: + Item_cache(): + example(0), used_table_map(0), cached_field(0), cached_field_type(MYSQL_TYPE_STRING) + { + fixed= 1; + null_value= 1; + } + Item_cache(enum_field_types field_type_arg): + example(0), used_table_map(0), cached_field(0), cached_field_type(field_type_arg) + { + fixed= 1; + null_value= 1; + } + + void set_used_tables(table_map map) { used_table_map= map; } + + virtual bool allocate(uint i) { return 0; } + virtual bool setup(Item *item) + { + example= item; + max_length= item->max_length; + decimals= item->decimals; + collation.set(item->collation); + unsigned_flag= item->unsigned_flag; + if (item->type() == FIELD_ITEM) + cached_field= ((Item_field *)item)->field; + return 0; + }; + virtual void store(Item *)= 0; + enum Type type() const { return CACHE_ITEM; } + enum_field_types field_type() const { return cached_field_type; } + static Item_cache* get_cache(const Item *item); + table_map used_tables() const { return used_table_map; } + virtual void keep_array() {} + virtual void print(String *str, enum_query_type query_type); + bool eq_def(Field *field) + { + return cached_field ? cached_field->eq_def (field) : FALSE; + } + bool eq(const Item *item, bool binary_cmp) const + { + return this == item; + } + // @InfiniDB + Item * get_example() { return example; } +}; + + +class Item_cache_int: public Item_cache +{ +protected: + longlong value; +public: + Item_cache_int(): Item_cache(), value(0) {} + Item_cache_int(enum_field_types field_type_arg): + Item_cache(field_type_arg), value(0) {} + + void store(Item *item); + void store(Item *item, longlong val_arg); + double val_real() { DBUG_ASSERT(fixed == 1); return (double) value; } + longlong val_int() { DBUG_ASSERT(fixed == 1); return value; } + String* val_str(String *str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type() const { return INT_RESULT; } + bool result_as_longlong() { return TRUE; } +}; + + +class Item_cache_real: public Item_cache +{ + double value; +public: + Item_cache_real(): Item_cache(), value(0) {} + + void store(Item *item); + double val_real() { DBUG_ASSERT(fixed == 1); return value; } + longlong val_int(); + String* val_str(String *str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type() const { return REAL_RESULT; } +}; + + +class Item_cache_decimal: public Item_cache +{ +protected: + my_decimal decimal_value; +public: + Item_cache_decimal(): Item_cache() {} + + void store(Item *item); + double val_real(); + longlong val_int(); + String* val_str(String *str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type() const { return DECIMAL_RESULT; } +}; + + +class Item_cache_str: public Item_cache +{ + char buffer[STRING_BUFFER_USUAL_SIZE]; + String *value, value_buff; + bool is_varbinary; + +public: + Item_cache_str(const Item *item) : + Item_cache(), value(0), + is_varbinary(item->type() == FIELD_ITEM && + ((const Item_field *) item)->field->type() == + MYSQL_TYPE_VARCHAR && + !((const Item_field *) item)->field->has_charset()) + {} + void store(Item *item); + double val_real(); + longlong val_int(); + String* val_str(String *) { DBUG_ASSERT(fixed == 1); return value; } + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type() const { return STRING_RESULT; } + CHARSET_INFO *charset() const { return value->charset(); }; + int save_in_field(Field *field, bool no_conversions); +}; + +class Item_cache_row: public Item_cache +{ + Item_cache **values; + uint item_count; + bool save_array; +public: + Item_cache_row() + :Item_cache(), values(0), item_count(2), save_array(0) {} + + /* + 'allocate' used only in row transformer, to preallocate space for row + cache. + */ + bool allocate(uint num); + /* + 'setup' is needed only by row => it not called by simple row subselect + (only by IN subselect (in subselect optimizer)) + */ + bool setup(Item *item); + void store(Item *item); + void illegal_method_call(const char *); + void make_field(Send_field *) + { + illegal_method_call((const char*)"make_field"); + }; + double val_real() + { + illegal_method_call((const char*)"val"); + return 0; + }; + longlong val_int() + { + illegal_method_call((const char*)"val_int"); + return 0; + }; + String *val_str(String *) + { + illegal_method_call((const char*)"val_str"); + return 0; + }; + my_decimal *val_decimal(my_decimal *val) + { + illegal_method_call((const char*)"val_decimal"); + return 0; + }; + + enum Item_result result_type() const { return ROW_RESULT; } + + uint cols() { return item_count; } + Item *element_index(uint i) { return values[i]; } + Item **addr(uint i) { return (Item **) (values + i); } + bool check_cols(uint c); + bool null_inside(); + void bring_value(); + void keep_array() { save_array= 1; } + void cleanup() + { + DBUG_ENTER("Item_cache_row::cleanup"); + Item_cache::cleanup(); + if (save_array) + bzero(values, item_count*sizeof(Item**)); + else + values= 0; + DBUG_VOID_RETURN; + } +}; + + +/* + Item_type_holder used to store type. name, length of Item for UNIONS & + derived tables. + + Item_type_holder do not need cleanup() because its time of live limited by + single SP/PS execution. +*/ +class Item_type_holder: public Item +{ +protected: + TYPELIB *enum_set_typelib; + enum_field_types fld_type; + Field::geometry_type geometry_type; + + void get_full_info(Item *item); + + /* It is used to count decimal precision in join_types */ + int prev_decimal_int_part; +public: + Item_type_holder(THD*, Item*); + + Item_result result_type() const; + enum_field_types field_type() const { return fld_type; }; + enum Type type() const { return TYPE_HOLDER; } + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + String *val_str(String*); + bool join_types(THD *thd, Item *); + // @infinidb pass in thd + Field *make_field_by_type(TABLE *table, THD* IDB_thd = 0); + static uint32 display_length(Item *item); + static enum_field_types get_real_type(Item *); + Field::geometry_type get_geometry_type() const { return geometry_type; }; +}; + + +class st_select_lex; +void mark_select_range_as_dependent(THD *thd, + st_select_lex *last_select, + st_select_lex *current_sel, + Field *found_field, Item *found_item, + Item_ident *resolved_item); + +extern Cached_item *new_Cached_item(THD *thd, Item *item); +extern Item_result item_cmp_type(Item_result a,Item_result b); +extern void resolve_const_item(THD *thd, Item **ref, Item *cmp_item); +extern int stored_field_cmp_to_item(Field *field, Item *item); diff --git a/dbcon/mysql/item_cmpfunc.cc b/dbcon/mysql/item_cmpfunc.cc new file mode 100644 index 00000000..7ff77015 --- /dev/null +++ b/dbcon/mysql/item_cmpfunc.cc @@ -0,0 +1,5344 @@ +/* Copyright (C) 2000-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/** + @file + + @brief + This file defines all compare functions +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include +#include "sql_select.h" + +static bool convert_constant_item(THD *, Item_field *, Item **); + +static Item_result item_store_type(Item_result a, Item *item, + my_bool unsigned_flag) +{ + Item_result b= item->result_type(); + + if (a == STRING_RESULT || b == STRING_RESULT) + return STRING_RESULT; + else if (a == REAL_RESULT || b == REAL_RESULT) + return REAL_RESULT; + else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT || + unsigned_flag != item->unsigned_flag) + return DECIMAL_RESULT; + else + return INT_RESULT; +} + +static void agg_result_type(Item_result *type, Item **items, uint nitems) +{ + Item **item, **item_end; + my_bool unsigned_flag= 0; + + *type= STRING_RESULT; + /* Skip beginning NULL items */ + for (item= items, item_end= item + nitems; item < item_end; item++) + { + if ((*item)->type() != Item::NULL_ITEM) + { + *type= (*item)->result_type(); + unsigned_flag= (*item)->unsigned_flag; + item++; + break; + } + } + /* Combine result types. Note: NULL items don't affect the result */ + for (; item < item_end; item++) + { + if ((*item)->type() != Item::NULL_ITEM) + *type= item_store_type(*type, *item, unsigned_flag); + } +} + + +/* + Compare row signature of two expressions + + SYNOPSIS: + cmp_row_type() + item1 the first expression + item2 the second expression + + DESCRIPTION + The function checks that two expressions have compatible row signatures + i.e. that the number of columns they return are the same and that if they + are both row expressions then each component from the first expression has + a row signature compatible with the signature of the corresponding component + of the second expression. + + RETURN VALUES + 1 type incompatibility has been detected + 0 otherwise +*/ + +static int cmp_row_type(Item* item1, Item* item2) +{ + uint n= item1->cols(); + if (item2->check_cols(n)) + return 1; + for (uint i=0; ielement_index(i)->check_cols(item1->element_index(i)->cols()) || + (item1->element_index(i)->result_type() == ROW_RESULT && + cmp_row_type(item1->element_index(i), item2->element_index(i)))) + return 1; + } + return 0; +} + + +/** + Aggregates result types from the array of items. + + SYNOPSIS: + agg_cmp_type() + type [out] the aggregated type + items array of items to aggregate the type from + nitems number of items in the array + + DESCRIPTION + This function aggregates result types from the array of items. Found type + supposed to be used later for comparison of values of these items. + Aggregation itself is performed by the item_cmp_type() function. + @param[out] type the aggregated type + @param items array of items to aggregate the type from + @param nitems number of items in the array + + @retval + 1 type incompatibility has been detected + @retval + 0 otherwise +*/ + +static int agg_cmp_type(Item_result *type, Item **items, uint nitems) +{ + uint i; + type[0]= items[0]->result_type(); + for (i= 1 ; i < nitems ; i++) + { + type[0]= item_cmp_type(type[0], items[i]->result_type()); + /* + When aggregating types of two row expressions we have to check + that they have the same cardinality and that each component + of the first row expression has a compatible row signature with + the signature of the corresponding component of the second row + expression. + */ + if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i])) + return 1; // error found: invalid usage of rows + } + return 0; +} + + +/** + @brief Aggregates field types from the array of items. + + @param[in] items array of items to aggregate the type from + @paran[in] nitems number of items in the array + + @details This function aggregates field types from the array of items. + Found type is supposed to be used later as the result field type + of a multi-argument function. + Aggregation itself is performed by the Field::field_type_merge() + function. + + @note The term "aggregation" is used here in the sense of inferring the + result type of a function from its argument types. + + @return aggregated field type. +*/ + +enum_field_types agg_field_type(Item **items, uint nitems) +{ + uint i; + if (!nitems || items[0]->result_type() == ROW_RESULT ) + return (enum_field_types)-1; + enum_field_types res= items[0]->field_type(); + for (i= 1 ; i < nitems ; i++) + res= Field::field_type_merge(res, items[i]->field_type()); + return res; +} + +/* + Collects different types for comparison of first item with each other items + + SYNOPSIS + collect_cmp_types() + items Array of items to collect types from + nitems Number of items in the array + + DESCRIPTION + This function collects different result types for comparison of the first + item in the list with each of the remaining items in the 'items' array. + + RETURN + 0 - if row type incompatibility has been detected (see cmp_row_type) + Bitmap of collected types - otherwise +*/ + +static uint collect_cmp_types(Item **items, uint nitems) +{ + uint i; + uint found_types; + Item_result left_result= items[0]->result_type(); + DBUG_ASSERT(nitems > 1); + found_types= 0; + for (i= 1; i < nitems ; i++) + { + if ((left_result == ROW_RESULT || + items[i]->result_type() == ROW_RESULT) && + cmp_row_type(items[0], items[i])) + return 0; + found_types|= 1<< (uint)item_cmp_type(left_result, + items[i]->result_type()); + } + return found_types; +} + +static void my_coll_agg_error(DTCollation &c1, DTCollation &c2, + const char *fname) +{ + my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0), + c1.collation->name,c1.derivation_name(), + c2.collation->name,c2.derivation_name(), + fname); +} + + +Item_bool_func2* Eq_creator::create(Item *a, Item *b) const +{ + return new Item_func_eq(a, b); +} + + +Item_bool_func2* Ne_creator::create(Item *a, Item *b) const +{ + return new Item_func_ne(a, b); +} + + +Item_bool_func2* Gt_creator::create(Item *a, Item *b) const +{ + return new Item_func_gt(a, b); +} + + +Item_bool_func2* Lt_creator::create(Item *a, Item *b) const +{ + return new Item_func_lt(a, b); +} + + +Item_bool_func2* Ge_creator::create(Item *a, Item *b) const +{ + return new Item_func_ge(a, b); +} + + +Item_bool_func2* Le_creator::create(Item *a, Item *b) const +{ + return new Item_func_le(a, b); +} + +/* + Test functions + Most of these returns 0LL if false and 1LL if true and + NULL if some arg is NULL. +*/ + +longlong Item_func_not::val_int() +{ + DBUG_ASSERT(fixed == 1); + bool value= args[0]->val_bool(); + null_value=args[0]->null_value; + return ((!null_value && value == 0) ? 1 : 0); +} + +/* + We put any NOT expression into parenthesis to avoid + possible problems with internal view representations where + any '!' is converted to NOT. It may cause a problem if + '!' is used in an expression together with other operators + whose precedence is lower than the precedence of '!' yet + higher than the precedence of NOT. +*/ + +void Item_func_not::print(String *str, enum_query_type query_type) +{ + str->append('('); + Item_func::print(str, query_type); + str->append(')'); +} + +/** + special NOT for ALL subquery. +*/ + + +longlong Item_func_not_all::val_int() +{ + DBUG_ASSERT(fixed == 1); + bool value= args[0]->val_bool(); + + /* + return TRUE if there was records in underlying select in max/min + optimization (ALL subquery) + */ + if (empty_underlying_subquery()) + return 1; + + null_value= args[0]->null_value; + return ((!null_value && value == 0) ? 1 : 0); +} + + +bool Item_func_not_all::empty_underlying_subquery() +{ + return ((test_sum_item && !test_sum_item->any_value()) || + (test_sub_item && !test_sub_item->any_value())); +} + +void Item_func_not_all::print(String *str, enum_query_type query_type) +{ + if (show) + Item_func::print(str, query_type); + else + args[0]->print(str, query_type); +} + + +/** + Special NOP (No OPeration) for ALL subquery. It is like + Item_func_not_all. + + @return + (return TRUE if underlying subquery do not return rows) but if subquery + returns some rows it return same value as argument (TRUE/FALSE). +*/ + +longlong Item_func_nop_all::val_int() +{ + DBUG_ASSERT(fixed == 1); + longlong value= args[0]->val_int(); + + /* + return FALSE if there was records in underlying select in max/min + optimization (SAME/ANY subquery) + */ + if (empty_underlying_subquery()) + return 0; + + null_value= args[0]->null_value; + return (null_value || value == 0) ? 0 : 1; +} + + +/** + Convert a constant item to an int and replace the original item. + + The function converts a constant expression or string to an integer. + On successful conversion the original item is substituted for the + result of the item evaluation. + This is done when comparing DATE/TIME of different formats and + also when comparing bigint to strings (in which case strings + are converted to bigints). + + @param thd thread handle + @param field item will be converted using the type of this field + @param[in,out] item reference to the item to convert + + @note + This function is called only at prepare stage. + As all derived tables are filled only after all derived tables + are prepared we do not evaluate items with subselects here because + they can contain derived tables and thus we may attempt to use a + table that has not been populated yet. + + @retval + 0 Can't convert item + @retval + 1 Item was replaced with an integer version of the item +*/ + +static bool convert_constant_item(THD *thd, Item_field *field_item, + Item **item) +{ + Field *field= field_item->field; + int result= 0; + + if (!(*item)->with_subselect && (*item)->const_item()) + { + TABLE *table= field->table; + ulong orig_sql_mode= thd->variables.sql_mode; + enum_check_fields orig_count_cuted_fields= thd->count_cuted_fields; + my_bitmap_map *old_maps[2]; + ulonglong UNINIT_VAR(orig_field_val); /* original field value if valid */ + + LINT_INIT(old_maps[0]); + LINT_INIT(old_maps[1]); + + if (table) + dbug_tmp_use_all_columns(table, old_maps, + table->read_set, table->write_set); + /* For comparison purposes allow invalid dates like 2000-01-32 */ + thd->variables.sql_mode= (orig_sql_mode & ~MODE_NO_ZERO_DATE) | + MODE_INVALID_DATES; + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + + /* + Store the value of the field/constant if it references an outer field + because the call to save_in_field below overrides that value. + Don't save field value if no data has been read yet. + Outer constant values are always saved. + */ + bool save_field_value= (field_item->depended_from && + (field_item->const_item() || + !(field->table->status & STATUS_NO_RECORD))); + if (save_field_value) + orig_field_val= field->val_int(); + if (!(*item)->is_null() && !(*item)->save_in_field(field, 1)) + { + Item *tmp= new Item_int_with_ref(field->val_int(), *item, + test(field->flags & UNSIGNED_FLAG)); + if (tmp) + thd->change_item_tree(item, tmp); + result= 1; // Item was replaced + } + /* Restore the original field value. */ + if (save_field_value) + { + result= field->store(orig_field_val, TRUE); + /* orig_field_val must be a valid value that can be restored back. */ + DBUG_ASSERT(!result); + } + thd->variables.sql_mode= orig_sql_mode; + thd->count_cuted_fields= orig_count_cuted_fields; + if (table) + dbug_tmp_restore_column_maps(table->read_set, table->write_set, old_maps); + } + return result; +} + + +void Item_bool_func2::fix_length_and_dec() +{ + max_length= 1; // Function returns 0 or 1 + THD *thd; + + /* + As some compare functions are generated after sql_yacc, + we have to check for out of memory conditions here + */ + if (!args[0] || !args[1]) + return; + + /* + We allow to convert to Unicode character sets in some cases. + The conditions when conversion is possible are: + - arguments A and B have different charsets + - A wins according to coercibility rules + - character set of A is superset for character set of B + + If all of the above is true, then it's possible to convert + B into the character set of A, and then compare according + to the collation of A. + */ + + + DTCollation coll; + if (args[0]->result_type() == STRING_RESULT && + args[1]->result_type() == STRING_RESULT && + agg_arg_charsets(coll, args, 2, MY_COLL_CMP_CONV, 1)) + return; + + args[0]->cmp_context= args[1]->cmp_context= + item_cmp_type(args[0]->result_type(), args[1]->result_type()); + // Make a special case of compare with fields to get nicer DATE comparisons + + if (functype() == LIKE_FUNC) // Disable conversion in case of LIKE function. + { + set_cmp_func(); + return; + } + + thd= current_thd; + if (!thd->is_context_analysis_only()) + { + if (args[0]->real_item()->type() == FIELD_ITEM) + { + Item_field *field_item= (Item_field*) (args[0]->real_item()); + if (field_item->field->can_be_compared_as_longlong() && + !(field_item->is_datetime() && + args[1]->result_type() == STRING_RESULT)) + { + if (convert_constant_item(thd, field_item, &args[1])) + { + cmp.set_cmp_func(this, tmp_arg, tmp_arg+1, + INT_RESULT); // Works for all types. + args[0]->cmp_context= args[1]->cmp_context= INT_RESULT; + return; + } + } + } + if (args[1]->real_item()->type() == FIELD_ITEM) + { + Item_field *field_item= (Item_field*) (args[1]->real_item()); + if (field_item->field->can_be_compared_as_longlong() && + !(field_item->is_datetime() && + args[0]->result_type() == STRING_RESULT)) + { + if (convert_constant_item(thd, field_item, &args[0])) + { + cmp.set_cmp_func(this, tmp_arg, tmp_arg+1, + INT_RESULT); // Works for all types. + args[0]->cmp_context= args[1]->cmp_context= INT_RESULT; + return; + } + } + } + } + set_cmp_func(); +} + + +int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type) +{ + owner= item; + func= comparator_matrix[type] + [test(owner->functype() == Item_func::EQUAL_FUNC)]; + switch (type) { + case ROW_RESULT: + { + uint n= (*a)->cols(); + if (n != (*b)->cols()) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), n); + comparators= 0; + return 1; + } + if (!(comparators= new Arg_comparator[n])) + return 1; + for (uint i=0; i < n; i++) + { + if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols()) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols()); + return 1; + } + if (comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i))) + return 1; + } + break; + } + case STRING_RESULT: + { + /* + We must set cmp_charset here as we may be called from for an automatic + generated item, like in natural join + */ + if (cmp_collation.set((*a)->collation, (*b)->collation) || + cmp_collation.derivation == DERIVATION_NONE) + { + my_coll_agg_error((*a)->collation, (*b)->collation, owner->func_name()); + return 1; + } + if (cmp_collation.collation == &my_charset_bin) + { + /* + We are using BLOB/BINARY/VARBINARY, change to compare byte by byte, + without removing end space + */ + if (func == &Arg_comparator::compare_string) + func= &Arg_comparator::compare_binary_string; + else if (func == &Arg_comparator::compare_e_string) + func= &Arg_comparator::compare_e_binary_string; + + /* + As this is binary compassion, mark all fields that they can't be + transformed. Otherwise we would get into trouble with comparisons + like: + WHERE col= 'j' AND col LIKE BINARY 'j' + which would be transformed to: + WHERE col= 'j' + */ + (*a)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0); + (*b)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0); + } + break; + } + case INT_RESULT: + { + if (func == &Arg_comparator::compare_int_signed) + { + if ((*a)->unsigned_flag) + func= (((*b)->unsigned_flag)? + &Arg_comparator::compare_int_unsigned : + &Arg_comparator::compare_int_unsigned_signed); + else if ((*b)->unsigned_flag) + func= &Arg_comparator::compare_int_signed_unsigned; + } + else if (func== &Arg_comparator::compare_e_int) + { + if ((*a)->unsigned_flag ^ (*b)->unsigned_flag) + func= &Arg_comparator::compare_e_int_diff_signedness; + } + break; + } + case DECIMAL_RESULT: + break; + case REAL_RESULT: + { + if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC) + { + precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1]; + if (func == &Arg_comparator::compare_real) + func= &Arg_comparator::compare_real_fixed; + else if (func == &Arg_comparator::compare_e_real) + func= &Arg_comparator::compare_e_real_fixed; + } + break; + } + default: + DBUG_ASSERT(0); + } + return 0; +} + + +/** + @brief Convert date provided in a string to the int representation. + + @param[in] thd thread handle + @param[in] str a string to convert + @param[in] warn_type type of the timestamp for issuing the warning + @param[in] warn_name field name for issuing the warning + @param[out] error_arg could not extract a DATE or DATETIME + + @details Convert date provided in the string str to the int + representation. If the string contains wrong date or doesn't + contain it at all then a warning is issued. The warn_type and + the warn_name arguments are used as the name and the type of the + field when issuing the warning. If any input was discarded + (trailing or non-timestampy characters), was_cut will be non-zero. + was_type will return the type str_to_datetime() could correctly + extract. + + @return + converted value. 0 on error and on zero-dates -- check 'failure' +*/ + +static ulonglong +get_date_from_str(THD *thd, String *str, timestamp_type warn_type, + char *warn_name, bool *error_arg) +{ + ulonglong value= 0; + int error; + MYSQL_TIME l_time; + enum_mysql_timestamp_type ret; + + ret= str_to_datetime(str->ptr(), str->length(), &l_time, + (TIME_FUZZY_DATE | MODE_INVALID_DATES | + (thd->variables.sql_mode & + (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE))), + &error); + + if (ret == MYSQL_TIMESTAMP_DATETIME || ret == MYSQL_TIMESTAMP_DATE) + { + /* + Do not return yet, we may still want to throw a "trailing garbage" + warning. + */ + *error_arg= FALSE; + value= TIME_to_ulonglong_datetime(&l_time); + } + else + { + *error_arg= TRUE; + error= 1; /* force warning */ + } + + if (error > 0) + make_truncated_value_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + str->ptr(), str->length(), + warn_type, warn_name); + + return value; +} + + +/* + Check whether compare_datetime() can be used to compare items. + + SYNOPSIS + Arg_comparator::can_compare_as_dates() + a, b [in] items to be compared + const_value [out] converted value of the string constant, if any + + DESCRIPTION + Check several cases when the DATE/DATETIME comparator should be used. + The following cases are checked: + 1. Both a and b is a DATE/DATETIME field/function returning string or + int result. + 2. Only a or b is a DATE/DATETIME field/function returning string or + int result and the other item (b or a) is an item with string result. + If the second item is a constant one then it's checked to be + convertible to the DATE/DATETIME type. If the constant can't be + converted to a DATE/DATETIME then the compare_datetime() comparator + isn't used and the warning about wrong DATE/DATETIME value is issued. + In all other cases (date-[int|real|decimal]/[int|real|decimal]-date) + the comparison is handled by other comparators. + If the datetime comparator can be used and one the operands of the + comparison is a string constant that was successfully converted to a + DATE/DATETIME type then the result of the conversion is returned in the + const_value if it is provided. If there is no constant or + compare_datetime() isn't applicable then the *const_value remains + unchanged. + + RETURN + the found type of date comparison +*/ + +enum Arg_comparator::enum_date_cmp_type +Arg_comparator::can_compare_as_dates(Item *a, Item *b, ulonglong *const_value) +{ + enum enum_date_cmp_type cmp_type= CMP_DATE_DFLT; + Item *str_arg= 0, *date_arg= 0; + + if (a->type() == Item::ROW_ITEM || b->type() == Item::ROW_ITEM) + return CMP_DATE_DFLT; + + if (a->is_datetime()) + { + if (b->is_datetime()) + cmp_type= CMP_DATE_WITH_DATE; + else if (b->result_type() == STRING_RESULT) + { + cmp_type= CMP_DATE_WITH_STR; + date_arg= a; + str_arg= b; + } + } + else if (b->is_datetime() && a->result_type() == STRING_RESULT) + { + cmp_type= CMP_STR_WITH_DATE; + date_arg= b; + str_arg= a; + } + + if (cmp_type != CMP_DATE_DFLT) + { + /* + Do not cache GET_USER_VAR() function as its const_item() may return TRUE + for the current thread but it still may change during the execution. + */ + if (cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() && + (str_arg->type() != Item::FUNC_ITEM || + ((Item_func*)str_arg)->functype() != Item_func::GUSERVAR_FUNC)) + { + THD *thd= current_thd; + ulonglong value; + bool error; + String tmp, *str_val= 0; + timestamp_type t_type= (date_arg->field_type() == MYSQL_TYPE_DATE ? + MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME); + + str_val= str_arg->val_str(&tmp); + if (str_arg->null_value) + return CMP_DATE_DFLT; + value= get_date_from_str(thd, str_val, t_type, date_arg->name, &error); + if (error) + return CMP_DATE_DFLT; + if (const_value) + *const_value= value; + } + } + return cmp_type; +} + + +/* + Retrieves correct TIME value from the given item. + + SYNOPSIS + get_time_value() + thd thread handle + item_arg [in/out] item to retrieve TIME value from + cache_arg [in/out] pointer to place to store the cache item to + warn_item [in] unused + is_null [out] TRUE <=> the item_arg is null + + DESCRIPTION + Retrieves the correct TIME value from given item for comparison by the + compare_datetime() function. + If item's result can be compared as longlong then its int value is used + and a value returned by get_time function is used otherwise. + If an item is a constant one then its value is cached and it isn't + get parsed again. An Item_cache_int object is used for for cached values. + It seamlessly substitutes the original item. The cache item is marked as + non-constant to prevent re-caching it again. + + RETURN + obtained value +*/ + +longlong +get_time_value(THD *thd, Item ***item_arg, Item **cache_arg, + Item *warn_item, bool *is_null) +{ + longlong value; + Item *item= **item_arg; + MYSQL_TIME ltime; + + if (item->result_as_longlong()) + { + value= item->val_int(); + *is_null= item->null_value; + } + else + { + *is_null= item->get_time(<ime); + value= !*is_null ? (longlong) TIME_to_ulonglong_datetime(<ime) : 0; + } + /* + Do not cache GET_USER_VAR() function as its const_item() may return TRUE + for the current thread but it still may change during the execution. + */ + if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM || + ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC)) + { + Item_cache_int *cache= new Item_cache_int(); + /* Mark the cache as non-const to prevent re-caching. */ + cache->set_used_tables(1); + cache->store(item, value); + *cache_arg= cache; + *item_arg= cache_arg; + } + return value; +} + + +int Arg_comparator::set_cmp_func(Item_bool_func2 *owner_arg, + Item **a1, Item **a2, + Item_result type) +{ + enum enum_date_cmp_type cmp_type; + ulonglong const_value= (ulonglong)-1; + a= a1; + b= a2; + + if ((cmp_type= can_compare_as_dates(*a, *b, &const_value))) + { + thd= current_thd; + owner= owner_arg; + a_type= (*a)->field_type(); + b_type= (*b)->field_type(); + a_cache= 0; + b_cache= 0; + + if (const_value != (ulonglong)-1) + { + Item_cache_int *cache= new Item_cache_int(); + /* Mark the cache as non-const to prevent re-caching. */ + cache->set_used_tables(1); + if (!(*a)->is_datetime()) + { + cache->store((*a), const_value); + a_cache= cache; + a= (Item **)&a_cache; + } + else + { + cache->store((*b), const_value); + b_cache= cache; + b= (Item **)&b_cache; + } + } + is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC); + func= &Arg_comparator::compare_datetime; + get_value_func= &get_datetime_value; + return 0; + } + else if (type == STRING_RESULT && (*a)->field_type() == MYSQL_TYPE_TIME && + (*b)->field_type() == MYSQL_TYPE_TIME) + { + /* Compare TIME values as integers. */ + thd= current_thd; + owner= owner_arg; + a_cache= 0; + b_cache= 0; + is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC); + func= &Arg_comparator::compare_datetime; + get_value_func= &get_time_value; + return 0; + } + else if (type == STRING_RESULT && + (*a)->result_type() == STRING_RESULT && + (*b)->result_type() == STRING_RESULT) + { + DTCollation coll; + coll.set((*a)->collation.collation); + if (agg_item_set_converter(coll, owner_arg->func_name(), + b, 1, MY_COLL_CMP_CONV, 1)) + return 1; + } + + return set_compare_func(owner_arg, type); +} + + +void Arg_comparator::set_datetime_cmp_func(Item **a1, Item **b1) +{ + thd= current_thd; + /* A caller will handle null values by itself. */ + owner= NULL; + a= a1; + b= b1; + a_type= (*a)->field_type(); + b_type= (*b)->field_type(); + a_cache= 0; + b_cache= 0; + is_nulls_eq= FALSE; + func= &Arg_comparator::compare_datetime; + get_value_func= &get_datetime_value; +} + + +/* + Retrieves correct DATETIME value from given item. + + SYNOPSIS + get_datetime_value() + thd thread handle + item_arg [in/out] item to retrieve DATETIME value from + cache_arg [in/out] pointer to place to store the caching item to + warn_item [in] item for issuing the conversion warning + is_null [out] TRUE <=> the item_arg is null + + DESCRIPTION + Retrieves the correct DATETIME value from given item for comparison by the + compare_datetime() function. + If item's result can be compared as longlong then its int value is used + and its string value is used otherwise. Strings are always parsed and + converted to int values by the get_date_from_str() function. + This allows us to compare correctly string dates with missed insignificant + zeros. If an item is a constant one then its value is cached and it isn't + get parsed again. An Item_cache_int object is used for caching values. It + seamlessly substitutes the original item. The cache item is marked as + non-constant to prevent re-caching it again. In order to compare + correctly DATE and DATETIME items the result of the former are treated as + a DATETIME with zero time (00:00:00). + + RETURN + obtained value +*/ + +longlong +get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg, + Item *warn_item, bool *is_null) +{ + longlong value= 0; + String buf, *str= 0; + Item *item= **item_arg; + + if (item->result_as_longlong()) + { + value= item->val_int(); + *is_null= item->null_value; + enum_field_types f_type= item->field_type(); + /* + Item_date_add_interval may return MYSQL_TYPE_STRING as the result + field type. To detect that the DATE value has been returned we + compare it with 100000000L - any DATE value should be less than it. + Don't shift cached DATETIME values up for the second time. + */ + if (f_type == MYSQL_TYPE_DATE || + (f_type != MYSQL_TYPE_DATETIME && value < 100000000L)) + value*= 1000000L; + } + else + { + str= item->val_str(&buf); + *is_null= item->null_value; + } + if (*is_null) + return ~(ulonglong) 0; + /* + Convert strings to the integer DATE/DATETIME representation. + Even if both dates provided in strings we can't compare them directly as + strings as there is no warranty that they are correct and do not miss + some insignificant zeros. + */ + if (str) + { + bool error; + enum_field_types f_type= warn_item->field_type(); + timestamp_type t_type= f_type == + MYSQL_TYPE_DATE ? MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME; + value= (longlong) get_date_from_str(thd, str, t_type, warn_item->name, &error); + /* + If str did not contain a valid date according to the current + SQL_MODE, get_date_from_str() has already thrown a warning, + and we don't want to throw NULL on invalid date (see 5.2.6 + "SQL modes" in the manual), so we're done here. + */ + } + /* + Do not cache GET_USER_VAR() function as its const_item() may return TRUE + for the current thread but it still may change during the execution. + */ + if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM || + ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC)) + { + Item_cache_int *cache= new Item_cache_int(MYSQL_TYPE_DATETIME); + /* Mark the cache as non-const to prevent re-caching. */ + cache->set_used_tables(1); + cache->store(item, value); + *cache_arg= cache; + *item_arg= cache_arg; + } + return value; +} + +/* + Compare items values as dates. + + SYNOPSIS + Arg_comparator::compare_datetime() + + DESCRIPTION + Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other + comparison functions. The correct DATETIME values are obtained + with help of the get_datetime_value() function. + + RETURN + If is_nulls_eq is TRUE: + 1 if items are equal or both are null + 0 otherwise + If is_nulls_eq is FALSE: + -1 a < b or at least one item is null + 0 a == b + 1 a > b + See the table: + is_nulls_eq | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | + a_is_null | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | + b_is_null | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | + result | 1 | 0 | 0 |0/1|-1 |-1 |-1 |-1/0/1| +*/ + +int Arg_comparator::compare_datetime() +{ + bool a_is_null, b_is_null; + longlong a_value, b_value; + + /* Get DATE/DATETIME/TIME value of the 'a' item. */ + a_value= (*get_value_func)(thd, &a, &a_cache, *b, &a_is_null); + if (!is_nulls_eq && a_is_null) + { + if (owner) + owner->null_value= 1; + return -1; + } + + /* Get DATE/DATETIME/TIME value of the 'b' item. */ + b_value= (*get_value_func)(thd, &b, &b_cache, *a, &b_is_null); + if (a_is_null || b_is_null) + { + if (owner) + owner->null_value= is_nulls_eq ? 0 : 1; + return is_nulls_eq ? (a_is_null == b_is_null) : -1; + } + + /* Here we have two not-NULL values. */ + if (owner) + owner->null_value= 0; + + /* Compare values. */ + if (is_nulls_eq) + return (a_value == b_value); + return a_value < b_value ? -1 : (a_value > b_value ? 1 : 0); +} + + +int Arg_comparator::compare_string() +{ + String *res1,*res2; + if ((res1= (*a)->val_str(&owner->tmp_value1))) + { + if ((res2= (*b)->val_str(&owner->tmp_value2))) + { + owner->null_value= 0; + return sortcmp(res1,res2,cmp_collation.collation); + } + } + owner->null_value= 1; + return -1; +} + + +/** + Compare strings byte by byte. End spaces are also compared. + + @retval + <0 *a < *b + @retval + 0 *b == *b + @retval + >0 *a > *b +*/ + +int Arg_comparator::compare_binary_string() +{ + String *res1,*res2; + if ((res1= (*a)->val_str(&owner->tmp_value1))) + { + if ((res2= (*b)->val_str(&owner->tmp_value2))) + { + owner->null_value= 0; + uint res1_length= res1->length(); + uint res2_length= res2->length(); + int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length)); + return cmp ? cmp : (int) (res1_length - res2_length); + } + } + owner->null_value= 1; + return -1; +} + + +/** + Compare strings, but take into account that NULL == NULL. +*/ + + +int Arg_comparator::compare_e_string() +{ + String *res1,*res2; + res1= (*a)->val_str(&owner->tmp_value1); + res2= (*b)->val_str(&owner->tmp_value2); + if (!res1 || !res2) + return test(res1 == res2); + return test(sortcmp(res1, res2, cmp_collation.collation) == 0); +} + + +int Arg_comparator::compare_e_binary_string() +{ + String *res1,*res2; + res1= (*a)->val_str(&owner->tmp_value1); + res2= (*b)->val_str(&owner->tmp_value2); + if (!res1 || !res2) + return test(res1 == res2); + return test(stringcmp(res1, res2) == 0); +} + + +int Arg_comparator::compare_real() +{ + /* + Fix yet another manifestation of Bug#2338. 'Volatile' will instruct + gcc to flush double values out of 80-bit Intel FPU registers before + performing the comparison. + */ + volatile double val1, val2; + val1= (*a)->val_real(); + if (!(*a)->null_value) + { + val2= (*b)->val_real(); + if (!(*b)->null_value) + { + owner->null_value= 0; + if (val1 < val2) return -1; + if (val1 == val2) return 0; + return 1; + } + } + owner->null_value= 1; + return -1; +} + +int Arg_comparator::compare_decimal() +{ + my_decimal value1; + my_decimal *val1= (*a)->val_decimal(&value1); + if (!(*a)->null_value) + { + my_decimal value2; + my_decimal *val2= (*b)->val_decimal(&value2); + if (!(*b)->null_value) + { + owner->null_value= 0; + return my_decimal_cmp(val1, val2); + } + } + owner->null_value= 1; + return -1; +} + +int Arg_comparator::compare_e_real() +{ + double val1= (*a)->val_real(); + double val2= (*b)->val_real(); + if ((*a)->null_value || (*b)->null_value) + return test((*a)->null_value && (*b)->null_value); + return test(val1 == val2); +} + +int Arg_comparator::compare_e_decimal() +{ + my_decimal value1, value2; + my_decimal *val1= (*a)->val_decimal(&value1); + my_decimal *val2= (*b)->val_decimal(&value2); + if ((*a)->null_value || (*b)->null_value) + return test((*a)->null_value && (*b)->null_value); + return test(my_decimal_cmp(val1, val2) == 0); +} + + +int Arg_comparator::compare_real_fixed() +{ + /* + Fix yet another manifestation of Bug#2338. 'Volatile' will instruct + gcc to flush double values out of 80-bit Intel FPU registers before + performing the comparison. + */ + volatile double val1, val2; + val1= (*a)->val_real(); + if (!(*a)->null_value) + { + val2= (*b)->val_real(); + if (!(*b)->null_value) + { + owner->null_value= 0; + if (val1 == val2 || fabs(val1 - val2) < precision) + return 0; + if (val1 < val2) + return -1; + return 1; + } + } + owner->null_value= 1; + return -1; +} + + +int Arg_comparator::compare_e_real_fixed() +{ + double val1= (*a)->val_real(); + double val2= (*b)->val_real(); + if ((*a)->null_value || (*b)->null_value) + return test((*a)->null_value && (*b)->null_value); + return test(val1 == val2 || fabs(val1 - val2) < precision); +} + + +int Arg_comparator::compare_int_signed() +{ + longlong val1= (*a)->val_int(); + if (!(*a)->null_value) + { + longlong val2= (*b)->val_int(); + if (!(*b)->null_value) + { + owner->null_value= 0; + if (val1 < val2) return -1; + if (val1 == val2) return 0; + return 1; + } + } + owner->null_value= 1; + return -1; +} + + +/** + Compare values as BIGINT UNSIGNED. +*/ + +int Arg_comparator::compare_int_unsigned() +{ + ulonglong val1= (*a)->val_int(); + if (!(*a)->null_value) + { + ulonglong val2= (*b)->val_int(); + if (!(*b)->null_value) + { + owner->null_value= 0; + if (val1 < val2) return -1; + if (val1 == val2) return 0; + return 1; + } + } + owner->null_value= 1; + return -1; +} + + +/** + Compare signed (*a) with unsigned (*B) +*/ + +int Arg_comparator::compare_int_signed_unsigned() +{ + longlong sval1= (*a)->val_int(); + if (!(*a)->null_value) + { + ulonglong uval2= (ulonglong)(*b)->val_int(); + if (!(*b)->null_value) + { + owner->null_value= 0; + if (sval1 < 0 || (ulonglong)sval1 < uval2) + return -1; + if ((ulonglong)sval1 == uval2) + return 0; + return 1; + } + } + owner->null_value= 1; + return -1; +} + + +/** + Compare unsigned (*a) with signed (*B) +*/ + +int Arg_comparator::compare_int_unsigned_signed() +{ + ulonglong uval1= (ulonglong)(*a)->val_int(); + if (!(*a)->null_value) + { + longlong sval2= (*b)->val_int(); + if (!(*b)->null_value) + { + owner->null_value= 0; + if (sval2 < 0) + return 1; + if (uval1 < (ulonglong)sval2) + return -1; + if (uval1 == (ulonglong)sval2) + return 0; + return 1; + } + } + owner->null_value= 1; + return -1; +} + + +int Arg_comparator::compare_e_int() +{ + longlong val1= (*a)->val_int(); + longlong val2= (*b)->val_int(); + if ((*a)->null_value || (*b)->null_value) + return test((*a)->null_value && (*b)->null_value); + return test(val1 == val2); +} + +/** + Compare unsigned *a with signed *b or signed *a with unsigned *b. +*/ +int Arg_comparator::compare_e_int_diff_signedness() +{ + longlong val1= (*a)->val_int(); + longlong val2= (*b)->val_int(); + if ((*a)->null_value || (*b)->null_value) + return test((*a)->null_value && (*b)->null_value); + return (val1 >= 0) && test(val1 == val2); +} + +int Arg_comparator::compare_row() +{ + int res= 0; + bool was_null= 0; + (*a)->bring_value(); + (*b)->bring_value(); + uint n= (*a)->cols(); + for (uint i= 0; inull_value) + { + // NULL was compared + switch (owner->functype()) { + case Item_func::NE_FUNC: + break; // NE never aborts on NULL even if abort_on_null is set + case Item_func::LT_FUNC: + case Item_func::LE_FUNC: + case Item_func::GT_FUNC: + case Item_func::GE_FUNC: + return -1; // <, <=, > and >= always fail on NULL + default: // EQ_FUNC + if (owner->abort_on_null) + return -1; // We do not need correct NULL returning + } + was_null= 1; + owner->null_value= 0; + res= 0; // continue comparison (maybe we will meet explicit difference) + } + else if (res) + return res; + } + if (was_null) + { + /* + There was NULL(s) in comparison in some parts, but there was no + explicit difference in other parts, so we have to return NULL. + */ + owner->null_value= 1; + return -1; + } + return 0; +} + + +int Arg_comparator::compare_e_row() +{ + (*a)->bring_value(); + (*b)->bring_value(); + uint n= (*a)->cols(); + for (uint i= 0; iappend('('); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" is ")); + if (! affirmative) + str->append(STRING_WITH_LEN("not ")); + if (value) + str->append(STRING_WITH_LEN("true")); + else + str->append(STRING_WITH_LEN("false")); + str->append(')'); +} + + +bool Item_func_truth::val_bool() +{ + bool val= args[0]->val_bool(); + if (args[0]->null_value) + { + /* + NULL val IS {TRUE, FALSE} --> FALSE + NULL val IS NOT {TRUE, FALSE} --> TRUE + */ + return (! affirmative); + } + + if (affirmative) + { + /* {TRUE, FALSE} val IS {TRUE, FALSE} value */ + return (val == value); + } + + /* {TRUE, FALSE} val IS NOT {TRUE, FALSE} value */ + return (val != value); +} + + +longlong Item_func_truth::val_int() +{ + return (val_bool() ? 1 : 0); +} + + +bool Item_in_optimizer::fix_left(THD *thd, Item **ref) +{ + if ((!args[0]->fixed && args[0]->fix_fields(thd, args)) || + (!cache && !(cache= Item_cache::get_cache(args[0])))) + return 1; + + cache->setup(args[0]); + if (cache->cols() == 1) + { + if ((used_tables_cache= args[0]->used_tables())) + cache->set_used_tables(OUTER_REF_TABLE_BIT); + else + cache->set_used_tables(0); + } + else + { + uint n= cache->cols(); + for (uint i= 0; i < n; i++) + { + if (args[0]->element_index(i)->used_tables()) + ((Item_cache *)cache->element_index(i))->set_used_tables(OUTER_REF_TABLE_BIT); + else + ((Item_cache *)cache->element_index(i))->set_used_tables(0); + } + used_tables_cache= args[0]->used_tables(); + } + not_null_tables_cache= args[0]->not_null_tables(); + with_sum_func= args[0]->with_sum_func; + if ((const_item_cache= args[0]->const_item())) + cache->store(args[0]); + return 0; +} + + +bool Item_in_optimizer::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + if (fix_left(thd, ref)) + return TRUE; + if (args[0]->maybe_null) + maybe_null=1; + + if (!args[1]->fixed && args[1]->fix_fields(thd, args+1)) + return TRUE; + Item_in_subselect * sub= (Item_in_subselect *)args[1]; + if (args[0]->cols() != sub->engine->cols()) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), args[0]->cols()); + return TRUE; + } + if (args[1]->maybe_null) + maybe_null=1; + with_sum_func= with_sum_func || args[1]->with_sum_func; + used_tables_cache|= args[1]->used_tables(); + not_null_tables_cache|= args[1]->not_null_tables(); + const_item_cache&= args[1]->const_item(); + fixed= 1; + return FALSE; +} + + +longlong Item_in_optimizer::val_int() +{ + bool tmp; + DBUG_ASSERT(fixed == 1); + cache->store(args[0]); + + if (cache->null_value) + { + if (((Item_in_subselect*)args[1])->is_top_level_item()) + { + /* + We're evaluating "NULL IN (SELECT ...)". The result can be NULL or + FALSE, and we can return one instead of another. Just return NULL. + */ + null_value= 1; + } + else + { + if (!((Item_in_subselect*)args[1])->is_correlated && + result_for_null_param != UNKNOWN) + { + /* Use cached value from previous execution */ + null_value= result_for_null_param; + } + else + { + /* + We're evaluating "NULL IN (SELECT ...)". The result is: + FALSE if SELECT produces an empty set, or + NULL otherwise. + We disable the predicates we've pushed down into subselect, run the + subselect and see if it has produced any rows. + */ + Item_in_subselect *item_subs=(Item_in_subselect*)args[1]; + if (cache->cols() == 1) + { + item_subs->set_cond_guard_var(0, FALSE); + (void) args[1]->val_bool_result(); + result_for_null_param= null_value= !item_subs->engine->no_rows(); + item_subs->set_cond_guard_var(0, TRUE); + } + else + { + uint i; + uint ncols= cache->cols(); + /* + Turn off the predicates that are based on column compares for + which the left part is currently NULL + */ + for (i= 0; i < ncols; i++) + { + if (cache->element_index(i)->null_value) + item_subs->set_cond_guard_var(i, FALSE); + } + + (void) args[1]->val_bool_result(); + result_for_null_param= null_value= !item_subs->engine->no_rows(); + + /* Turn all predicates back on */ + for (i= 0; i < ncols; i++) + item_subs->set_cond_guard_var(i, TRUE); + } + } + } + return 0; + } + tmp= args[1]->val_bool_result(); + null_value= args[1]->null_value; + return tmp; +} + + +void Item_in_optimizer::keep_top_level_cache() +{ + cache->keep_array(); + save_cache= 1; +} + + +void Item_in_optimizer::cleanup() +{ + DBUG_ENTER("Item_in_optimizer::cleanup"); + Item_bool_func::cleanup(); + if (!save_cache) + cache= 0; + DBUG_VOID_RETURN; +} + + +bool Item_in_optimizer::is_null() +{ + val_int(); + return null_value; +} + + +longlong Item_func_eq::val_int() +{ + DBUG_ASSERT(fixed == 1); + int value= cmp.compare(); + return value == 0 ? 1 : 0; +} + + +/** Same as Item_func_eq, but NULL = NULL. */ + +void Item_func_equal::fix_length_and_dec() +{ + Item_bool_func2::fix_length_and_dec(); + maybe_null=null_value=0; +} + +longlong Item_func_equal::val_int() +{ + DBUG_ASSERT(fixed == 1); + return cmp.compare(); +} + +longlong Item_func_ne::val_int() +{ + DBUG_ASSERT(fixed == 1); + int value= cmp.compare(); + return value != 0 && !null_value ? 1 : 0; +} + + +longlong Item_func_ge::val_int() +{ + DBUG_ASSERT(fixed == 1); + int value= cmp.compare(); + return value >= 0 ? 1 : 0; +} + + +longlong Item_func_gt::val_int() +{ + DBUG_ASSERT(fixed == 1); + int value= cmp.compare(); + return value > 0 ? 1 : 0; +} + +longlong Item_func_le::val_int() +{ + DBUG_ASSERT(fixed == 1); + int value= cmp.compare(); + return value <= 0 && !null_value ? 1 : 0; +} + + +longlong Item_func_lt::val_int() +{ + DBUG_ASSERT(fixed == 1); + int value= cmp.compare(); + return value < 0 && !null_value ? 1 : 0; +} + + +longlong Item_func_strcmp::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *a=args[0]->val_str(&tmp_value1); + String *b=args[1]->val_str(&tmp_value2); + if (!a || !b) + { + null_value=1; + return 0; + } + int value= sortcmp(a,b,cmp.cmp_collation.collation); + null_value=0; + return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1); +} + + +bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const +{ + /* Assume we don't have rtti */ + if (this == item) + return 1; + if (item->type() != FUNC_ITEM) + return 0; + Item_func *item_func=(Item_func*) item; + if (arg_count != item_func->arg_count || + functype() != item_func->functype()) + return 0; + if (negated != ((Item_func_opt_neg *) item_func)->negated) + return 0; + for (uint i=0; i < arg_count ; i++) + if (!args[i]->eq(item_func->arguments()[i], binary_cmp)) + return 0; + return 1; +} + + +void Item_func_interval::fix_length_and_dec() +{ + uint rows= row->cols(); + + use_decimal_comparison= ((row->element_index(0)->result_type() == + DECIMAL_RESULT) || + (row->element_index(0)->result_type() == + INT_RESULT)); + if (rows > 8) + { + bool not_null_consts= TRUE; + + for (uint i= 1; not_null_consts && i < rows; i++) + { + Item *el= row->element_index(i); + not_null_consts&= el->const_item() & !el->is_null(); + } + + if (not_null_consts && + (intervals= + (interval_range*) sql_alloc(sizeof(interval_range) * (rows - 1)))) + { + if (use_decimal_comparison) + { + for (uint i= 1; i < rows; i++) + { + Item *el= row->element_index(i); + interval_range *range= intervals + (i-1); + if ((el->result_type() == DECIMAL_RESULT) || + (el->result_type() == INT_RESULT)) + { + range->type= DECIMAL_RESULT; + range->dec.init(); + my_decimal *dec= el->val_decimal(&range->dec); + if (dec != &range->dec) + { + range->dec= *dec; + range->dec.fix_buffer_pointer(); + } + } + else + { + range->type= REAL_RESULT; + range->dbl= el->val_real(); + } + } + } + else + { + for (uint i= 1; i < rows; i++) + { + intervals[i-1].dbl= row->element_index(i)->val_real(); + } + } + } + } + maybe_null= 0; + max_length= 2; + used_tables_cache|= row->used_tables(); + not_null_tables_cache= row->not_null_tables(); + with_sum_func= with_sum_func || row->with_sum_func; + const_item_cache&= row->const_item(); +} + + +/** + Execute Item_func_interval(). + + @note + If we are doing a decimal comparison, we are evaluating the first + item twice. + + @return + - -1 if null value, + - 0 if lower than lowest + - 1 - arg_count-1 if between args[n] and args[n+1] + - arg_count if higher than biggest argument +*/ + +longlong Item_func_interval::val_int() +{ + DBUG_ASSERT(fixed == 1); + double value; + my_decimal dec_buf, *dec= NULL; + uint i; + + if (use_decimal_comparison) + { + dec= row->element_index(0)->val_decimal(&dec_buf); + if (row->element_index(0)->null_value) + return -1; + my_decimal2double(E_DEC_FATAL_ERROR, dec, &value); + } + else + { + value= row->element_index(0)->val_real(); + if (row->element_index(0)->null_value) + return -1; + } + + if (intervals) + { // Use binary search to find interval + uint start,end; + start= 0; + end= row->cols()-2; + while (start != end) + { + uint mid= (start + end + 1) / 2; + interval_range *range= intervals + mid; + my_bool cmp_result; + /* + The values in the range intervall may have different types, + Only do a decimal comparision of the first argument is a decimal + and we are comparing against a decimal + */ + if (dec && range->type == DECIMAL_RESULT) + cmp_result= my_decimal_cmp(&range->dec, dec) <= 0; + else + cmp_result= (range->dbl <= value); + if (cmp_result) + start= mid; + else + end= mid - 1; + } + interval_range *range= intervals+start; + return ((dec && range->type == DECIMAL_RESULT) ? + my_decimal_cmp(dec, &range->dec) < 0 : + value < range->dbl) ? 0 : start + 1; + } + + for (i=1 ; i < row->cols() ; i++) + { + Item *el= row->element_index(i); + if (use_decimal_comparison && + ((el->result_type() == DECIMAL_RESULT) || + (el->result_type() == INT_RESULT))) + { + my_decimal e_dec_buf, *e_dec= el->val_decimal(&e_dec_buf); + /* Skip NULL ranges. */ + if (el->null_value) + continue; + if (my_decimal_cmp(e_dec, dec) > 0) + return i - 1; + } + else + { + double val= el->val_real(); + /* Skip NULL ranges. */ + if (el->null_value) + continue; + if (val > value) + return i - 1; + } + } + return i-1; +} + + +/** + Perform context analysis of a BETWEEN item tree. + + This function performs context analysis (name resolution) and calculates + various attributes of the item tree with Item_func_between as its root. + The function saves in ref the pointer to the item or to a newly created + item that is considered as a replacement for the original one. + + @param thd reference to the global context of the query thread + @param ref pointer to Item* variable where pointer to resulting "fixed" + item is to be assigned + + @note + Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on + a predicate/function level. Then it's easy to show that: + @verbatim + T0(e BETWEEN e1 AND e2) = union(T1(e),T1(e1),T1(e2)) + T1(e BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2))) + T0(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2))) + T1(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2))) + @endverbatim + + @retval + 0 ok + @retval + 1 got error +*/ + +bool Item_func_between::fix_fields(THD *thd, Item **ref) +{ + if (Item_func_opt_neg::fix_fields(thd, ref)) + return 1; + + thd->lex->current_select->between_count++; + + /* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */ + if (pred_level && !negated) + return 0; + + /* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */ + not_null_tables_cache= (args[0]->not_null_tables() | + (args[1]->not_null_tables() & + args[2]->not_null_tables())); + + return 0; +} + + +void Item_func_between::fix_length_and_dec() +{ + max_length= 1; + int i; + bool datetime_found= FALSE; + int time_items_found= 0; + compare_as_dates= TRUE; + THD *thd= current_thd; + + /* + As some compare functions are generated after sql_yacc, + we have to check for out of memory conditions here + */ + if (!args[0] || !args[1] || !args[2]) + return; + if ( agg_cmp_type(&cmp_type, args, 3)) + return; + if (cmp_type == STRING_RESULT && + agg_arg_charsets(cmp_collation, args, 3, MY_COLL_CMP_CONV, 1)) + return; + + /* + Detect the comparison of DATE/DATETIME items. + At least one of items should be a DATE/DATETIME item and other items + should return the STRING result. + */ + if (cmp_type == STRING_RESULT) + { + for (i= 0; i < 3; i++) + { + if (args[i]->is_datetime()) + { + datetime_found= TRUE; + continue; + } + if (args[i]->field_type() == MYSQL_TYPE_TIME && + args[i]->result_as_longlong()) + time_items_found++; + } + } + if (!datetime_found) + compare_as_dates= FALSE; + + if (compare_as_dates) + { + ge_cmp.set_datetime_cmp_func(args, args + 1); + le_cmp.set_datetime_cmp_func(args, args + 2); + } + else if (time_items_found == 3) + { + /* Compare TIME items as integers. */ + cmp_type= INT_RESULT; + } + else if (args[0]->real_item()->type() == FIELD_ITEM && + thd->lex->sql_command != SQLCOM_CREATE_VIEW && + thd->lex->sql_command != SQLCOM_SHOW_CREATE) + { + Item_field *field_item= (Item_field*) (args[0]->real_item()); + if (field_item->field->can_be_compared_as_longlong()) + { + /* + The following can't be recoded with || as convert_constant_item + changes the argument + */ + if (convert_constant_item(thd, field_item, &args[1])) + cmp_type=INT_RESULT; // Works for all types. + if (convert_constant_item(thd, field_item, &args[2])) + cmp_type=INT_RESULT; // Works for all types. + } + } +} + + +longlong Item_func_between::val_int() +{ // ANSI BETWEEN + DBUG_ASSERT(fixed == 1); + if (compare_as_dates) + { + int ge_res, le_res; + + ge_res= ge_cmp.compare(); + if ((null_value= args[0]->null_value)) + return 0; + le_res= le_cmp.compare(); + + if (!args[1]->null_value && !args[2]->null_value) + return (longlong) ((ge_res >= 0 && le_res <=0) != negated); + else if (args[1]->null_value) + { + null_value= le_res > 0; // not null if false range. + } + else + { + null_value= ge_res < 0; + } + } + else if (cmp_type == STRING_RESULT) + { + String *value,*a,*b; + value=args[0]->val_str(&value0); + if ((null_value=args[0]->null_value)) + return 0; + a=args[1]->val_str(&value1); + b=args[2]->val_str(&value2); + if (!args[1]->null_value && !args[2]->null_value) + return (longlong) ((sortcmp(value,a,cmp_collation.collation) >= 0 && + sortcmp(value,b,cmp_collation.collation) <= 0) != + negated); + if (args[1]->null_value && args[2]->null_value) + null_value=1; + else if (args[1]->null_value) + { + // Set to not null if false range. + null_value= sortcmp(value,b,cmp_collation.collation) <= 0; + } + else + { + // Set to not null if false range. + null_value= sortcmp(value,a,cmp_collation.collation) >= 0; + } + } + else if (cmp_type == INT_RESULT) + { + longlong value=args[0]->val_int(), a, b; + if ((null_value=args[0]->null_value)) + return 0; /* purecov: inspected */ + a=args[1]->val_int(); + b=args[2]->val_int(); + if (!args[1]->null_value && !args[2]->null_value) + return (longlong) ((value >= a && value <= b) != negated); + if (args[1]->null_value && args[2]->null_value) + null_value=1; + else if (args[1]->null_value) + { + null_value= value <= b; // not null if false range. + } + else + { + null_value= value >= a; + } + } + else if (cmp_type == DECIMAL_RESULT) + { + my_decimal dec_buf, *dec= args[0]->val_decimal(&dec_buf), + a_buf, *a_dec, b_buf, *b_dec; + if ((null_value=args[0]->null_value)) + return 0; /* purecov: inspected */ + a_dec= args[1]->val_decimal(&a_buf); + b_dec= args[2]->val_decimal(&b_buf); + if (!args[1]->null_value && !args[2]->null_value) + return (longlong) ((my_decimal_cmp(dec, a_dec) >= 0 && + my_decimal_cmp(dec, b_dec) <= 0) != negated); + if (args[1]->null_value && args[2]->null_value) + null_value=1; + else if (args[1]->null_value) + null_value= (my_decimal_cmp(dec, b_dec) <= 0); + else + null_value= (my_decimal_cmp(dec, a_dec) >= 0); + } + else + { + double value= args[0]->val_real(),a,b; + if ((null_value=args[0]->null_value)) + return 0; /* purecov: inspected */ + a= args[1]->val_real(); + b= args[2]->val_real(); + if (!args[1]->null_value && !args[2]->null_value) + return (longlong) ((value >= a && value <= b) != negated); + if (args[1]->null_value && args[2]->null_value) + null_value=1; + else if (args[1]->null_value) + { + null_value= value <= b; // not null if false range. + } + else + { + null_value= value >= a; + } + } + return (longlong) (!null_value && negated); +} + + +void Item_func_between::print(String *str, enum_query_type query_type) +{ + str->append('('); + args[0]->print(str, query_type); + if (negated) + str->append(STRING_WITH_LEN(" not")); + str->append(STRING_WITH_LEN(" between ")); + args[1]->print(str, query_type); + str->append(STRING_WITH_LEN(" and ")); + args[2]->print(str, query_type); + str->append(')'); +} + +void +Item_func_ifnull::fix_length_and_dec() +{ + agg_result_type(&hybrid_type, args, 2); + maybe_null=args[1]->maybe_null; + decimals= max(args[0]->decimals, args[1]->decimals); + unsigned_flag= args[0]->unsigned_flag && args[1]->unsigned_flag; + + if (hybrid_type == DECIMAL_RESULT || hybrid_type == INT_RESULT) + { + int len0= args[0]->max_length - args[0]->decimals + - (args[0]->unsigned_flag ? 0 : 1); + + int len1= args[1]->max_length - args[1]->decimals + - (args[1]->unsigned_flag ? 0 : 1); + + max_length= max(len0, len1) + decimals + (unsigned_flag ? 0 : 1); + } + else + max_length= max(args[0]->max_length, args[1]->max_length); + + switch (hybrid_type) { + case STRING_RESULT: + agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1); + break; + case DECIMAL_RESULT: + case REAL_RESULT: + break; + case INT_RESULT: + decimals= 0; + break; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + + //@bug6153, update max_length for utf8 + if (strcmp((collation.collation)->csname, "utf8") == 0 && max_length < 60 && + (INT_RESULT == args[0]->result_type() || INT_RESULT == args[1]->result_type() || + REAL_RESULT == args[0]->result_type() || REAL_RESULT == args[1]->result_type() || + DECIMAL_RESULT == args[0]->result_type() || DECIMAL_RESULT == args[1]->result_type())) + max_length *= (collation.collation)->mbmaxlen; + cached_field_type= agg_field_type(args, 2); +} + + +uint Item_func_ifnull::decimal_precision() const +{ + int arg0_int_part= args[0]->decimal_int_part(); + int arg1_int_part= args[1]->decimal_int_part(); + int max_int_part= max(arg0_int_part, arg1_int_part); + int precision= max_int_part + decimals; + return precision; +} + + +enum_field_types Item_func_ifnull::field_type() const +{ + return cached_field_type; +} + +Field *Item_func_ifnull::tmp_table_field(TABLE *table) +{ + return tmp_table_field_from_field_type(table, 0); +} + +double +Item_func_ifnull::real_op() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if (!args[0]->null_value) + { + null_value=0; + return value; + } + value= args[1]->val_real(); + if ((null_value=args[1]->null_value)) + return 0.0; + return value; +} + +longlong +Item_func_ifnull::int_op() +{ + DBUG_ASSERT(fixed == 1); + longlong value=args[0]->val_int(); + if (!args[0]->null_value) + { + null_value=0; + return value; + } + value=args[1]->val_int(); + if ((null_value=args[1]->null_value)) + return 0; + return value; +} + + +my_decimal *Item_func_ifnull::decimal_op(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + my_decimal *value= args[0]->val_decimal(decimal_value); + if (!args[0]->null_value) + { + null_value= 0; + return value; + } + value= args[1]->val_decimal(decimal_value); + if ((null_value= args[1]->null_value)) + return 0; + return value; +} + + +String * +Item_func_ifnull::str_op(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res =args[0]->val_str(str); + if (!args[0]->null_value) + { + null_value=0; + res->set_charset(collation.collation); + return res; + } + res=args[1]->val_str(str); + if ((null_value=args[1]->null_value)) + return 0; + res->set_charset(collation.collation); + return res; +} + + +/** + Perform context analysis of an IF item tree. + + This function performs context analysis (name resolution) and calculates + various attributes of the item tree with Item_func_if as its root. + The function saves in ref the pointer to the item or to a newly created + item that is considered as a replacement for the original one. + + @param thd reference to the global context of the query thread + @param ref pointer to Item* variable where pointer to resulting "fixed" + item is to be assigned + + @note + Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on + a predicate/function level. Then it's easy to show that: + @verbatim + T0(IF(e,e1,e2) = T1(IF(e,e1,e2)) + T1(IF(e,e1,e2)) = intersection(T1(e1),T1(e2)) + @endverbatim + + @retval + 0 ok + @retval + 1 got error +*/ + +bool +Item_func_if::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + args[0]->top_level_item(); + + if (Item_func::fix_fields(thd, ref)) + return 1; + + not_null_tables_cache= (args[1]->not_null_tables() & + args[2]->not_null_tables()); + + return 0; +} + + +void +Item_func_if::fix_length_and_dec() +{ + maybe_null=args[1]->maybe_null || args[2]->maybe_null; + decimals= max(args[1]->decimals, args[2]->decimals); + unsigned_flag=args[1]->unsigned_flag && args[2]->unsigned_flag; + + enum Item_result arg1_type=args[1]->result_type(); + enum Item_result arg2_type=args[2]->result_type(); + bool null1=args[1]->const_item() && args[1]->null_value; + bool null2=args[2]->const_item() && args[2]->null_value; + + if (null1) + { + cached_result_type= arg2_type; + collation.set(args[2]->collation.collation); + cached_field_type= args[2]->field_type(); + } + else if (null2) + { + cached_result_type= arg1_type; + collation.set(args[1]->collation.collation); + cached_field_type= args[1]->field_type(); + } + else + { + agg_result_type(&cached_result_type, args+1, 2); + if (cached_result_type == STRING_RESULT) + { + if (agg_arg_charsets(collation, args+1, 2, MY_COLL_ALLOW_CONV, 1)) + return; + } + else + { + collation.set(&my_charset_bin); // Number + } + cached_field_type= agg_field_type(args + 1, 2); + } + + if ((cached_result_type == DECIMAL_RESULT ) + || (cached_result_type == INT_RESULT)) + { + int len1= args[1]->max_length - args[1]->decimals + - (args[1]->unsigned_flag ? 0 : 1); + + int len2= args[2]->max_length - args[2]->decimals + - (args[2]->unsigned_flag ? 0 : 1); + + max_length=max(len1, len2) + decimals + (unsigned_flag ? 0 : 1); + } + else + max_length= max(args[1]->max_length, args[2]->max_length); +} + + +uint Item_func_if::decimal_precision() const +{ + int arg1_prec= args[1]->decimal_int_part(); + int arg2_prec= args[2]->decimal_int_part(); + int precision=max(arg1_prec,arg2_prec) + decimals; + return precision; +} + + +double +Item_func_if::val_real() +{ + DBUG_ASSERT(fixed == 1); + Item *arg= args[0]->val_bool() ? args[1] : args[2]; + double value= arg->val_real(); + null_value=arg->null_value; + return value; +} + +longlong +Item_func_if::val_int() +{ + DBUG_ASSERT(fixed == 1); + Item *arg= args[0]->val_bool() ? args[1] : args[2]; + longlong value=arg->val_int(); + null_value=arg->null_value; + return value; +} + +String * +Item_func_if::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + Item *arg= args[0]->val_bool() ? args[1] : args[2]; + String *res=arg->val_str(str); + if (res) + res->set_charset(collation.collation); + null_value=arg->null_value; + return res; +} + + +my_decimal * +Item_func_if::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + Item *arg= args[0]->val_bool() ? args[1] : args[2]; + my_decimal *value= arg->val_decimal(decimal_value); + null_value= arg->null_value; + return value; +} + + +void +Item_func_nullif::fix_length_and_dec() +{ + Item_bool_func2::fix_length_and_dec(); + maybe_null=1; + if (args[0]) // Only false if EOM + { + max_length=args[0]->max_length; + decimals=args[0]->decimals; + unsigned_flag= args[0]->unsigned_flag; + cached_result_type= args[0]->result_type(); + if (cached_result_type == STRING_RESULT && + agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1)) + return; + } +} + + +/** + @note + Note that we have to evaluate the first argument twice as the compare + may have been done with a different type than return value + @return + NULL if arguments are equal + @return + the first argument if not equal +*/ + +double +Item_func_nullif::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value; + if (!cmp.compare()) + { + null_value=1; + return 0.0; + } + value= args[0]->val_real(); + null_value=args[0]->null_value; + return value; +} + +longlong +Item_func_nullif::val_int() +{ + DBUG_ASSERT(fixed == 1); + longlong value; + if (!cmp.compare()) + { + null_value=1; + return 0; + } + value=args[0]->val_int(); + null_value=args[0]->null_value; + return value; +} + +String * +Item_func_nullif::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res; + if (!cmp.compare()) + { + null_value=1; + return 0; + } + res=args[0]->val_str(str); + null_value=args[0]->null_value; + return res; +} + + +my_decimal * +Item_func_nullif::val_decimal(my_decimal * decimal_value) +{ + DBUG_ASSERT(fixed == 1); + my_decimal *res; + if (!cmp.compare()) + { + null_value=1; + return 0; + } + res= args[0]->val_decimal(decimal_value); + null_value= args[0]->null_value; + return res; +} + + +bool +Item_func_nullif::is_null() +{ + return (null_value= (!cmp.compare() ? 1 : args[0]->null_value)); +} + + +/** + Find and return matching items for CASE or ELSE item if all compares + are failed or NULL if ELSE item isn't defined. + + IMPLEMENTATION + In order to do correct comparisons of the CASE expression (the expression + between CASE and the first WHEN) with each WHEN expression several + comparators are used. One for each result type. CASE expression can be + evaluated up to # of different result types are used. To check whether + the CASE expression already was evaluated for a particular result type + a bit mapped variable value_added_map is used. Result types are mapped + to it according to their int values i.e. STRING_RESULT is mapped to bit + 0, REAL_RESULT to bit 1, so on. + + @retval + NULL Nothing found and there is no ELSE expression defined + @retval + item Found item or ELSE item if defined and all comparisons are + failed +*/ + +Item *Item_func_case::find_item(String *str) +{ + uint value_added_map= 0; + + if (first_expr_num == -1) + { + for (uint i=0 ; i < ncases ; i+=2) + { + // No expression between CASE and the first WHEN + if (args[i]->val_bool()) + return args[i+1]; + continue; + } + } + else + { + /* Compare every WHEN argument with it and return the first match */ + for (uint i=0 ; i < ncases ; i+=2) + { + cmp_type= item_cmp_type(left_result_type, args[i]->result_type()); + DBUG_ASSERT(cmp_type != ROW_RESULT); + DBUG_ASSERT(cmp_items[(uint)cmp_type]); + if (!(value_added_map & (1<<(uint)cmp_type))) + { + cmp_items[(uint)cmp_type]->store_value(args[first_expr_num]); + if ((null_value=args[first_expr_num]->null_value)) + return else_expr_num != -1 ? args[else_expr_num] : 0; + value_added_map|= 1<<(uint)cmp_type; + } + if (!cmp_items[(uint)cmp_type]->cmp(args[i]) && !args[i]->null_value) + return args[i + 1]; + } + } + // No, WHEN clauses all missed, return ELSE expression + return else_expr_num != -1 ? args[else_expr_num] : 0; +} + + +String *Item_func_case::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res; + Item *item=find_item(str); + + if (!item) + { + null_value=1; + return 0; + } + null_value= 0; + if (!(res=item->val_str(str))) + null_value= 1; + return res; +} + + +longlong Item_func_case::val_int() +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH]; + String dummy_str(buff,sizeof(buff),default_charset()); + Item *item=find_item(&dummy_str); + longlong res; + + if (!item) + { + null_value=1; + return 0; + } + res=item->val_int(); + null_value=item->null_value; + return res; +} + +double Item_func_case::val_real() +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH]; + String dummy_str(buff,sizeof(buff),default_charset()); + Item *item=find_item(&dummy_str); + double res; + + if (!item) + { + null_value=1; + return 0; + } + res= item->val_real(); + null_value=item->null_value; + return res; +} + + +my_decimal *Item_func_case::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH]; + String dummy_str(buff, sizeof(buff), default_charset()); + Item *item= find_item(&dummy_str); + my_decimal *res; + + if (!item) + { + null_value=1; + return 0; + } + + res= item->val_decimal(decimal_value); + null_value= item->null_value; + return res; +} + + +bool Item_func_case::fix_fields(THD *thd, Item **ref) +{ + /* + buff should match stack usage from + Item_func_case::val_int() -> Item_func_case::find_item() + */ +#ifndef EMBEDDED_LIBRARY + uchar buff[MAX_FIELD_WIDTH*2+sizeof(String)*2+sizeof(String*)*2+sizeof(double)*2+sizeof(longlong)*2]; +#endif + bool res= Item_func::fix_fields(thd, ref); + /* + Call check_stack_overrun after fix_fields to be sure that stack variable + is not optimized away + */ + if (check_stack_overrun(thd, STACK_MIN_SIZE, buff)) + return TRUE; // Fatal error flag is set! + return res; +} + + +void Item_func_case::agg_str_lengths(Item* arg) +{ + set_if_bigger(max_length, arg->max_length); + set_if_bigger(decimals, arg->decimals); + unsigned_flag= unsigned_flag && arg->unsigned_flag; +} + + +void Item_func_case::agg_num_lengths(Item *arg) +{ + uint len= my_decimal_length_to_precision(arg->max_length, arg->decimals, + arg->unsigned_flag) - arg->decimals; + set_if_bigger(max_length, len); + set_if_bigger(decimals, arg->decimals); + unsigned_flag= unsigned_flag && arg->unsigned_flag; +} + + +void Item_func_case::fix_length_and_dec() +{ + Item **agg; + uint nagg; + uint found_types= 0; + if (!(agg= (Item**) sql_alloc(sizeof(Item*)*(ncases+1)))) + return; + + /* + Aggregate all THEN and ELSE expression types + and collations when string result + */ + + for (nagg= 0 ; nagg < ncases/2 ; nagg++) + agg[nagg]= args[nagg*2+1]; + + if (else_expr_num != -1) + agg[nagg++]= args[else_expr_num]; + + agg_result_type(&cached_result_type, agg, nagg); + if ((cached_result_type == STRING_RESULT) && + agg_arg_charsets(collation, agg, nagg, MY_COLL_ALLOW_CONV, 1)) + return; + + cached_field_type= agg_field_type(agg, nagg); + /* + Aggregate first expression and all THEN expression types + and collations when string comparison + */ + if (first_expr_num != -1) + { + uint i; + agg[0]= args[first_expr_num]; + left_result_type= agg[0]->result_type(); + + for (nagg= 0; nagg < ncases/2 ; nagg++) + agg[nagg+1]= args[nagg*2]; + nagg++; + if (!(found_types= collect_cmp_types(agg, nagg))) + return; + + for (i= 0; i <= (uint)DECIMAL_RESULT; i++) + { + if (found_types & (1 << i) && !cmp_items[i]) + { + DBUG_ASSERT((Item_result)i != ROW_RESULT); + if ((Item_result)i == STRING_RESULT && + agg_arg_charsets(cmp_collation, agg, nagg, MY_COLL_CMP_CONV, 1)) + return; + if (!(cmp_items[i]= + cmp_item::get_comparator((Item_result)i, + cmp_collation.collation))) + return; + } + } + } + + if (else_expr_num == -1 || args[else_expr_num]->maybe_null) + maybe_null=1; + + max_length=0; + decimals=0; + unsigned_flag= TRUE; + if (cached_result_type == STRING_RESULT) + { + for (uint i= 0; i < ncases; i+= 2) + agg_str_lengths(args[i + 1]); + if (else_expr_num != -1) + agg_str_lengths(args[else_expr_num]); + } + else + { + for (uint i= 0; i < ncases; i+= 2) + agg_num_lengths(args[i + 1]); + if (else_expr_num != -1) + agg_num_lengths(args[else_expr_num]); + max_length= my_decimal_precision_to_length_no_truncation(max_length + + decimals, decimals, + unsigned_flag); + } +} + + +uint Item_func_case::decimal_precision() const +{ + int max_int_part=0; + for (uint i=0 ; i < ncases ; i+=2) + set_if_bigger(max_int_part, args[i+1]->decimal_int_part()); + + if (else_expr_num != -1) + set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part()); + return max_int_part + decimals; +} + + +/** + @todo + Fix this so that it prints the whole CASE expression +*/ + +void Item_func_case::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("(case ")); + if (first_expr_num != -1) + { + args[first_expr_num]->print(str, query_type); + str->append(' '); + } + for (uint i=0 ; i < ncases ; i+=2) + { + str->append(STRING_WITH_LEN("when ")); + args[i]->print(str, query_type); + str->append(STRING_WITH_LEN(" then ")); + args[i+1]->print(str, query_type); + str->append(' '); + } + if (else_expr_num != -1) + { + str->append(STRING_WITH_LEN("else ")); + args[else_expr_num]->print(str, query_type); + str->append(' '); + } + str->append(STRING_WITH_LEN("end)")); +} + + +void Item_func_case::cleanup() +{ + uint i; + DBUG_ENTER("Item_func_case::cleanup"); + Item_func::cleanup(); + for (i= 0; i <= (uint)DECIMAL_RESULT; i++) + { + delete cmp_items[i]; + cmp_items[i]= 0; + } + DBUG_VOID_RETURN; +} + + +/** + Coalesce - return first not NULL argument. +*/ + +String *Item_func_coalesce::str_op(String *str) +{ + DBUG_ASSERT(fixed == 1); + null_value=0; + for (uint i=0 ; i < arg_count ; i++) + { + String *res; + if ((res=args[i]->val_str(str))) + return res; + } + null_value=1; + return 0; +} + +longlong Item_func_coalesce::int_op() +{ + DBUG_ASSERT(fixed == 1); + null_value=0; + for (uint i=0 ; i < arg_count ; i++) + { + longlong res=args[i]->val_int(); + if (!args[i]->null_value) + return res; + } + null_value=1; + return 0; +} + +double Item_func_coalesce::real_op() +{ + DBUG_ASSERT(fixed == 1); + null_value=0; + for (uint i=0 ; i < arg_count ; i++) + { + double res= args[i]->val_real(); + if (!args[i]->null_value) + return res; + } + null_value=1; + return 0; +} + + +my_decimal *Item_func_coalesce::decimal_op(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + null_value= 0; + for (uint i= 0; i < arg_count; i++) + { + my_decimal *res= args[i]->val_decimal(decimal_value); + if (!args[i]->null_value) + return res; + } + null_value=1; + return 0; +} + + +void Item_func_coalesce::fix_length_and_dec() +{ + cached_field_type= agg_field_type(args, arg_count); + agg_result_type(&hybrid_type, args, arg_count); + switch (hybrid_type) { + case STRING_RESULT: + count_only_length(); + decimals= NOT_FIXED_DEC; + agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1); + break; + case DECIMAL_RESULT: + count_decimal_length(); + break; + case REAL_RESULT: + count_real_length(); + break; + case INT_RESULT: + count_only_length(); + decimals= 0; + break; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } +} + +/**************************************************************************** + Classes and function for the IN operator +****************************************************************************/ + +/* + Determine which of the signed longlong arguments is bigger + + SYNOPSIS + cmp_longs() + a_val left argument + b_val right argument + + DESCRIPTION + This function will compare two signed longlong arguments + and will return -1, 0, or 1 if left argument is smaller than, + equal to or greater than the right argument. + + RETURN VALUE + -1 left argument is smaller than the right argument. + 0 left argument is equal to the right argument. + 1 left argument is greater than the right argument. +*/ +static inline int cmp_longs (longlong a_val, longlong b_val) +{ + return a_val < b_val ? -1 : a_val == b_val ? 0 : 1; +} + + +/* + Determine which of the unsigned longlong arguments is bigger + + SYNOPSIS + cmp_ulongs() + a_val left argument + b_val right argument + + DESCRIPTION + This function will compare two unsigned longlong arguments + and will return -1, 0, or 1 if left argument is smaller than, + equal to or greater than the right argument. + + RETURN VALUE + -1 left argument is smaller than the right argument. + 0 left argument is equal to the right argument. + 1 left argument is greater than the right argument. +*/ +static inline int cmp_ulongs (ulonglong a_val, ulonglong b_val) +{ + return a_val < b_val ? -1 : a_val == b_val ? 0 : 1; +} + + +/* + Compare two integers in IN value list format (packed_longlong) + + SYNOPSIS + cmp_longlong() + cmp_arg an argument passed to the calling function (my_qsort2) + a left argument + b right argument + + DESCRIPTION + This function will compare two integer arguments in the IN value list + format and will return -1, 0, or 1 if left argument is smaller than, + equal to or greater than the right argument. + It's used in sorting the IN values list and finding an element in it. + Depending on the signedness of the arguments cmp_longlong() will + compare them as either signed (using cmp_longs()) or unsigned (using + cmp_ulongs()). + + RETURN VALUE + -1 left argument is smaller than the right argument. + 0 left argument is equal to the right argument. + 1 left argument is greater than the right argument. +*/ +int cmp_longlong(void *cmp_arg, + in_longlong::packed_longlong *a, + in_longlong::packed_longlong *b) +{ + if (a->unsigned_flag != b->unsigned_flag) + { + /* + One of the args is unsigned and is too big to fit into the + positive signed range. Report no match. + */ + if ((a->unsigned_flag && ((ulonglong) a->val) > (ulonglong) LONGLONG_MAX) || + (b->unsigned_flag && ((ulonglong) b->val) > (ulonglong) LONGLONG_MAX)) + return a->unsigned_flag ? 1 : -1; + /* + Although the signedness differs both args can fit into the signed + positive range. Make them signed and compare as usual. + */ + return cmp_longs (a->val, b->val); + } + if (a->unsigned_flag) + return cmp_ulongs ((ulonglong) a->val, (ulonglong) b->val); + else + return cmp_longs (a->val, b->val); +} + +static int cmp_double(void *cmp_arg, double *a,double *b) +{ + return *a < *b ? -1 : *a == *b ? 0 : 1; +} + +static int cmp_row(void *cmp_arg, cmp_item_row *a, cmp_item_row *b) +{ + return a->compare(b); +} + + +static int cmp_decimal(void *cmp_arg, my_decimal *a, my_decimal *b) +{ + /* + We need call of fixing buffer pointer, because fast sort just copy + decimal buffers in memory and pointers left pointing on old buffer place + */ + a->fix_buffer_pointer(); + b->fix_buffer_pointer(); + return my_decimal_cmp(a, b); +} + + +int in_vector::find(Item *item) +{ + uchar *result=get_value(item); + if (!result || !used_count) + return 0; // Null value + + uint start,end; + start=0; end=used_count-1; + while (start != end) + { + uint mid=(start+end+1)/2; + int res; + if ((res=(*compare)(collation, base+mid*size, result)) == 0) + return 1; + if (res < 0) + start=mid; + else + end=mid-1; + } + return (int) ((*compare)(collation, base+start*size, result) == 0); +} + +in_string::in_string(uint elements,qsort2_cmp cmp_func, CHARSET_INFO *cs) + :in_vector(elements, sizeof(String), cmp_func, cs), + tmp(buff, sizeof(buff), &my_charset_bin) +{} + +in_string::~in_string() +{ + if (base) + { + // base was allocated with help of sql_alloc => following is OK + for (uint i=0 ; i < count ; i++) + ((String*) base)[i].free(); + } +} + +void in_string::set(uint pos,Item *item) +{ + String *str=((String*) base)+pos; + String *res=item->val_str(str); + if (res && res != str) + { + if (res->uses_buffer_owned_by(str)) + res->copy(); + if (item->type() == Item::FUNC_ITEM) + str->copy(*res); + else + *str= *res; + } + if (!str->charset()) + { + CHARSET_INFO *cs; + if (!(cs= item->collation.collation)) + cs= &my_charset_bin; // Should never happen for STR items + str->set_charset(cs); + } +} + + +uchar *in_string::get_value(Item *item) +{ + return (uchar*) item->val_str(&tmp); +} + +in_row::in_row(uint elements, Item * item) +{ + base= (char*) new cmp_item_row[count= elements]; + size= sizeof(cmp_item_row); + compare= (qsort2_cmp) cmp_row; + /* + We need to reset these as otherwise we will call sort() with + uninitialized (even if not used) elements + */ + used_count= elements; + collation= 0; +} + +in_row::~in_row() +{ + if (base) + delete [] (cmp_item_row*) base; +} + +uchar *in_row::get_value(Item *item) +{ + tmp.store_value(item); + if (item->is_null()) + return 0; + return (uchar *)&tmp; +} + +void in_row::set(uint pos, Item *item) +{ + DBUG_ENTER("in_row::set"); + DBUG_PRINT("enter", ("pos: %u item: 0x%lx", pos, (ulong) item)); + ((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item); + DBUG_VOID_RETURN; +} + +in_longlong::in_longlong(uint elements) + :in_vector(elements,sizeof(packed_longlong),(qsort2_cmp) cmp_longlong, 0) +{} + +void in_longlong::set(uint pos,Item *item) +{ + struct packed_longlong *buff= &((packed_longlong*) base)[pos]; + + buff->val= item->val_int(); + buff->unsigned_flag= item->unsigned_flag; +} + +uchar *in_longlong::get_value(Item *item) +{ + tmp.val= item->val_int(); + if (item->null_value) + return 0; + tmp.unsigned_flag= item->unsigned_flag; + return (uchar*) &tmp; +} + +void in_datetime::set(uint pos,Item *item) +{ + Item **tmp_item= &item; + bool is_null; + struct packed_longlong *buff= &((packed_longlong*) base)[pos]; + + buff->val= get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null); + buff->unsigned_flag= 1L; +} + +uchar *in_datetime::get_value(Item *item) +{ + bool is_null; + Item **tmp_item= lval_cache ? &lval_cache : &item; + tmp.val= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null); + if (item->null_value) + return 0; + tmp.unsigned_flag= 1L; + return (uchar*) &tmp; +} + +in_double::in_double(uint elements) + :in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0) +{} + +void in_double::set(uint pos,Item *item) +{ + ((double*) base)[pos]= item->val_real(); +} + +uchar *in_double::get_value(Item *item) +{ + tmp= item->val_real(); + if (item->null_value) + return 0; /* purecov: inspected */ + return (uchar*) &tmp; +} + + +in_decimal::in_decimal(uint elements) + :in_vector(elements, sizeof(my_decimal),(qsort2_cmp) cmp_decimal, 0) +{} + + +void in_decimal::set(uint pos, Item *item) +{ + /* as far as 'item' is constant, we can store reference on my_decimal */ + my_decimal *dec= ((my_decimal *)base) + pos; + dec->len= DECIMAL_BUFF_LENGTH; + dec->fix_buffer_pointer(); + my_decimal *res= item->val_decimal(dec); + /* if item->val_decimal() is evaluated to NULL then res == 0 */ + if (!item->null_value && res != dec) + my_decimal2decimal(res, dec); +} + + +uchar *in_decimal::get_value(Item *item) +{ + my_decimal *result= item->val_decimal(&val); + if (item->null_value) + return 0; + return (uchar *)result; +} + + +cmp_item* cmp_item::get_comparator(Item_result type, + CHARSET_INFO *cs) +{ + switch (type) { + case STRING_RESULT: + return new cmp_item_sort_string(cs); + case INT_RESULT: + return new cmp_item_int; + case REAL_RESULT: + return new cmp_item_real; + case ROW_RESULT: + return new cmp_item_row; + case DECIMAL_RESULT: + return new cmp_item_decimal; + default: + DBUG_ASSERT(0); + break; + } + return 0; // to satisfy compiler :) +} + + +cmp_item* cmp_item_sort_string::make_same() +{ + return new cmp_item_sort_string_in_static(cmp_charset); +} + +cmp_item* cmp_item_int::make_same() +{ + return new cmp_item_int(); +} + +cmp_item* cmp_item_real::make_same() +{ + return new cmp_item_real(); +} + +cmp_item* cmp_item_row::make_same() +{ + return new cmp_item_row(); +} + + +cmp_item_row::~cmp_item_row() +{ + DBUG_ENTER("~cmp_item_row"); + DBUG_PRINT("enter",("this: 0x%lx", (long) this)); + if (comparators) + { + for (uint i= 0; i < n; i++) + { + if (comparators[i]) + delete comparators[i]; + } + } + DBUG_VOID_RETURN; +} + + +void cmp_item_row::alloc_comparators() +{ + if (!comparators) + comparators= (cmp_item **) current_thd->calloc(sizeof(cmp_item *)*n); +} + + +void cmp_item_row::store_value(Item *item) +{ + DBUG_ENTER("cmp_item_row::store_value"); + n= item->cols(); + alloc_comparators(); + if (comparators) + { + item->bring_value(); + item->null_value= 0; + for (uint i=0; i < n; i++) + { + if (!comparators[i]) + if (!(comparators[i]= + cmp_item::get_comparator(item->element_index(i)->result_type(), + item->element_index(i)->collation.collation))) + break; // new failed + comparators[i]->store_value(item->element_index(i)); + item->null_value|= item->element_index(i)->null_value; + } + } + DBUG_VOID_RETURN; +} + + +void cmp_item_row::store_value_by_template(cmp_item *t, Item *item) +{ + cmp_item_row *tmpl= (cmp_item_row*) t; + if (tmpl->n != item->cols()) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n); + return; + } + n= tmpl->n; + if ((comparators= (cmp_item **) sql_alloc(sizeof(cmp_item *)*n))) + { + item->bring_value(); + item->null_value= 0; + for (uint i=0; i < n; i++) + { + if (!(comparators[i]= tmpl->comparators[i]->make_same())) + break; // new failed + comparators[i]->store_value_by_template(tmpl->comparators[i], + item->element_index(i)); + item->null_value|= item->element_index(i)->null_value; + } + } +} + + +int cmp_item_row::cmp(Item *arg) +{ + arg->null_value= 0; + if (arg->cols() != n) + { + my_error(ER_OPERAND_COLUMNS, MYF(0), n); + return 1; + } + bool was_null= 0; + arg->bring_value(); + for (uint i=0; i < n; i++) + { + if (comparators[i]->cmp(arg->element_index(i))) + { + if (!arg->element_index(i)->null_value) + return 1; + was_null= 1; + } + } + return (arg->null_value= was_null); +} + + +int cmp_item_row::compare(cmp_item *c) +{ + cmp_item_row *l_cmp= (cmp_item_row *) c; + for (uint i=0; i < n; i++) + { + int res; + if ((res= comparators[i]->compare(l_cmp->comparators[i]))) + return res; + } + return 0; +} + + +void cmp_item_decimal::store_value(Item *item) +{ + my_decimal *val= item->val_decimal(&value); + /* val may be zero if item is nnull */ + if (val && val != &value) + my_decimal2decimal(val, &value); +} + + +int cmp_item_decimal::cmp(Item *arg) +{ + my_decimal tmp_buf, *tmp= arg->val_decimal(&tmp_buf); + if (arg->null_value) + return 1; + return my_decimal_cmp(&value, tmp); +} + + +int cmp_item_decimal::compare(cmp_item *arg) +{ + cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg; + return my_decimal_cmp(&value, &l_cmp->value); +} + + +cmp_item* cmp_item_decimal::make_same() +{ + return new cmp_item_decimal(); +} + + +void cmp_item_datetime::store_value(Item *item) +{ + bool is_null; + Item **tmp_item= lval_cache ? &lval_cache : &item; + value= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null); +} + + +int cmp_item_datetime::cmp(Item *arg) +{ + bool is_null; + Item **tmp_item= &arg; + return value != + get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null); +} + + +int cmp_item_datetime::compare(cmp_item *ci) +{ + cmp_item_datetime *l_cmp= (cmp_item_datetime *)ci; + return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1); +} + + +cmp_item *cmp_item_datetime::make_same() +{ + return new cmp_item_datetime(warn_item); +} + + +bool Item_func_in::nulls_in_row() +{ + Item **arg,**arg_end; + for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++) + { + if ((*arg)->null_inside()) + return 1; + } + return 0; +} + + +/** + Perform context analysis of an IN item tree. + + This function performs context analysis (name resolution) and calculates + various attributes of the item tree with Item_func_in as its root. + The function saves in ref the pointer to the item or to a newly created + item that is considered as a replacement for the original one. + + @param thd reference to the global context of the query thread + @param ref pointer to Item* variable where pointer to resulting "fixed" + item is to be assigned + + @note + Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on + a predicate/function level. Then it's easy to show that: + @verbatim + T0(e IN(e1,...,en)) = union(T1(e),intersection(T1(ei))) + T1(e IN(e1,...,en)) = union(T1(e),intersection(T1(ei))) + T0(e NOT IN(e1,...,en)) = union(T1(e),union(T1(ei))) + T1(e NOT IN(e1,...,en)) = union(T1(e),intersection(T1(ei))) + @endverbatim + + @retval + 0 ok + @retval + 1 got error +*/ + +bool +Item_func_in::fix_fields(THD *thd, Item **ref) +{ + Item **arg, **arg_end; + + if (Item_func_opt_neg::fix_fields(thd, ref)) + return 1; + + /* not_null_tables_cache == union(T1(e),union(T1(ei))) */ + if (pred_level && negated) + return 0; + + /* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */ + not_null_tables_cache= ~(table_map) 0; + for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++) + not_null_tables_cache&= (*arg)->not_null_tables(); + not_null_tables_cache|= (*args)->not_null_tables(); + return 0; +} + + +static int srtcmp_in(CHARSET_INFO *cs, const String *x,const String *y) +{ + return cs->coll->strnncollsp(cs, + (uchar *) x->ptr(),x->length(), + (uchar *) y->ptr(),y->length(), 0); +} + + +void Item_func_in::fix_length_and_dec() +{ + Item **arg, **arg_end; + bool const_itm= 1; + THD *thd= current_thd; + bool datetime_found= FALSE; + /* TRUE <=> arguments values will be compared as DATETIMEs. */ + bool compare_as_datetime= FALSE; + Item *date_arg= 0; + uint found_types= 0; + uint type_cnt= 0, i; + Item_result cmp_type= STRING_RESULT; + left_result_type= args[0]->result_type(); + if (!(found_types= collect_cmp_types(args, arg_count))) + return; + + for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++) + { + if (!arg[0]->const_item()) + { + const_itm= 0; + break; + } + } + for (i= 0; i <= (uint)DECIMAL_RESULT; i++) + { + if (found_types & 1 << i) + { + (type_cnt)++; + cmp_type= (Item_result) i; + } + } + + if (type_cnt == 1) + { + if (cmp_type == STRING_RESULT && + agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1)) + return; + arg_types_compatible= TRUE; + } + if (type_cnt == 1) + { + /* + When comparing rows create the row comparator object beforehand to ease + the DATETIME comparison detection procedure. + */ + if (cmp_type == ROW_RESULT) + { + cmp_item_row *cmp= 0; + if (const_itm && !nulls_in_row()) + { + array= new in_row(arg_count-1, 0); + cmp= &((in_row*)array)->tmp; + } + else + { + if (!(cmp= new cmp_item_row)) + return; + cmp_items[ROW_RESULT]= cmp; + } + cmp->n= args[0]->cols(); + cmp->alloc_comparators(); + } + /* All DATE/DATETIME fields/functions has the STRING result type. */ + if (cmp_type == STRING_RESULT || cmp_type == ROW_RESULT) + { + uint col, cols= args[0]->cols(); + + for (col= 0; col < cols; col++) + { + bool skip_column= FALSE; + /* + Check that all items to be compared has the STRING result type and at + least one of them is a DATE/DATETIME item. + */ + for (arg= args, arg_end= args + arg_count; arg != arg_end ; arg++) + { + Item *itm= ((cmp_type == STRING_RESULT) ? arg[0] : + arg[0]->element_index(col)); + if (itm->result_type() != STRING_RESULT) + { + skip_column= TRUE; + break; + } + else if (itm->is_datetime()) + { + datetime_found= TRUE; + /* + Internally all DATE/DATETIME values are converted to the DATETIME + type. So try to find a DATETIME item to issue correct warnings. + */ + if (!date_arg) + date_arg= itm; + else if (itm->field_type() == MYSQL_TYPE_DATETIME) + { + date_arg= itm; + /* All arguments are already checked to have the STRING result. */ + if (cmp_type == STRING_RESULT) + break; + } + } + } + if (skip_column) + continue; + if (datetime_found) + { + if (cmp_type == ROW_RESULT) + { + cmp_item **cmp= 0; + if (array) + cmp= ((in_row*)array)->tmp.comparators + col; + else + cmp= ((cmp_item_row*)cmp_items[ROW_RESULT])->comparators + col; + *cmp= new cmp_item_datetime(date_arg); + /* Reset variables for the next column. */ + date_arg= 0; + datetime_found= FALSE; + } + else + compare_as_datetime= TRUE; + } + } + } + } + /* + Row item with NULLs inside can return NULL or FALSE => + they can't be processed as static + */ + if (type_cnt == 1 && const_itm && !nulls_in_row()) + { + if (compare_as_datetime) + array= new in_datetime(date_arg, arg_count - 1); + else + { + /* + IN must compare INT columns and constants as int values (the same + way as equality does). + So we must check here if the column on the left and all the constant + values on the right can be compared as integers and adjust the + comparison type accordingly. + */ + if (args[0]->real_item()->type() == FIELD_ITEM && + thd->lex->sql_command != SQLCOM_CREATE_VIEW && + thd->lex->sql_command != SQLCOM_SHOW_CREATE && + cmp_type != INT_RESULT) + { + Item_field *field_item= (Item_field*) (args[0]->real_item()); + if (field_item->field->can_be_compared_as_longlong()) + { + bool all_converted= TRUE; + for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++) + { + if (!convert_constant_item (thd, field_item, &arg[0])) + all_converted= FALSE; + } + if (all_converted) + cmp_type= INT_RESULT; + } + } + switch (cmp_type) { + case STRING_RESULT: + array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in, + cmp_collation.collation); + break; + case INT_RESULT: + array= new in_longlong(arg_count-1); + break; + case REAL_RESULT: + array= new in_double(arg_count-1); + break; + case ROW_RESULT: + /* + The row comparator was created at the beginning but only DATETIME + items comparators were initialized. Call store_value() to setup + others. + */ + ((in_row*)array)->tmp.store_value(args[0]); + break; + case DECIMAL_RESULT: + array= new in_decimal(arg_count - 1); + break; + default: + DBUG_ASSERT(0); + return; + } + } + if (array && !(thd->is_fatal_error)) // If not EOM + { + uint j=0; + for (uint i=1 ; i < arg_count ; i++) + { + array->set(j,args[i]); + if (!args[i]->null_value) // Skip NULL values + j++; + else + have_null= 1; + } + if ((array->used_count= j)) + array->sort(); + } + } + else + { + if (compare_as_datetime) + cmp_items[STRING_RESULT]= new cmp_item_datetime(date_arg); + else + { + for (i= 0; i <= (uint) DECIMAL_RESULT; i++) + { + if (found_types & (1 << i) && !cmp_items[i]) + { + if ((Item_result)i == STRING_RESULT && + agg_arg_charsets(cmp_collation, args, arg_count, + MY_COLL_CMP_CONV, 1)) + return; + if (!cmp_items[i] && !(cmp_items[i]= + cmp_item::get_comparator((Item_result)i, + cmp_collation.collation))) + return; + } + } + } + } + max_length= 1; +} + + +void Item_func_in::print(String *str, enum_query_type query_type) +{ + str->append('('); + args[0]->print(str, query_type); + if (negated) + str->append(STRING_WITH_LEN(" not")); + str->append(STRING_WITH_LEN(" in (")); + print_args(str, 1, query_type); + str->append(STRING_WITH_LEN("))")); +} + + +/* + Evaluate the function and return its value. + + SYNOPSIS + val_int() + + DESCRIPTION + Evaluate the function and return its value. + + IMPLEMENTATION + If the array object is defined then the value of the function is + calculated by means of this array. + Otherwise several cmp_item objects are used in order to do correct + comparison of left expression and an expression from the values list. + One cmp_item object correspond to one used comparison type. Left + expression can be evaluated up to number of different used comparison + types. A bit mapped variable value_added_map is used to check whether + the left expression already was evaluated for a particular result type. + Result types are mapped to it according to their integer values i.e. + STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on. + + RETURN + Value of the function +*/ + +longlong Item_func_in::val_int() +{ + cmp_item *in_item; + DBUG_ASSERT(fixed == 1); + uint value_added_map= 0; + if (array) + { + int tmp=array->find(args[0]); + null_value=args[0]->null_value || (!tmp && have_null); + return (longlong) (!null_value && tmp != negated); + } + + have_null= 0; + for (uint i= 1 ; i < arg_count ; i++) + { + Item_result cmp_type= item_cmp_type(left_result_type, args[i]->result_type()); + in_item= cmp_items[(uint)cmp_type]; + DBUG_ASSERT(in_item); + if (!(value_added_map & (1 << (uint)cmp_type))) + { + in_item->store_value(args[0]); + if ((null_value= args[0]->null_value)) + return 0; + value_added_map|= 1 << (uint)cmp_type; + } + if (!in_item->cmp(args[i]) && !args[i]->null_value) + return (longlong) (!negated); + have_null|= args[i]->null_value; + } + + null_value= have_null; + return (longlong) (!null_value && negated); +} + + +longlong Item_func_bit_or::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulonglong arg1= (ulonglong) args[0]->val_int(); + if (args[0]->null_value) + { + null_value=1; /* purecov: inspected */ + return 0; /* purecov: inspected */ + } + ulonglong arg2= (ulonglong) args[1]->val_int(); + if (args[1]->null_value) + { + null_value=1; + return 0; + } + null_value=0; + return (longlong) (arg1 | arg2); +} + + +longlong Item_func_bit_and::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulonglong arg1= (ulonglong) args[0]->val_int(); + if (args[0]->null_value) + { + null_value=1; /* purecov: inspected */ + return 0; /* purecov: inspected */ + } + ulonglong arg2= (ulonglong) args[1]->val_int(); + if (args[1]->null_value) + { + null_value=1; /* purecov: inspected */ + return 0; /* purecov: inspected */ + } + null_value=0; + return (longlong) (arg1 & arg2); +} + +Item_cond::Item_cond(THD *thd, Item_cond *item) + :Item_bool_func(thd, item), + abort_on_null(item->abort_on_null), + and_tables_cache(item->and_tables_cache) +{ + /* + item->list will be copied by copy_andor_arguments() call + */ +} + + +void Item_cond::copy_andor_arguments(THD *thd, Item_cond *item) +{ + List_iterator_fast li(item->list); + while (Item *it= li++) + list.push_back(it->copy_andor_structure(thd)); +} + + +bool +Item_cond::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + List_iterator li(list); + Item *item; +#ifndef EMBEDDED_LIBRARY + uchar buff[sizeof(char*)]; // Max local vars in function +#endif + not_null_tables_cache= used_tables_cache= 0; + const_item_cache= 1; + /* + and_table_cache is the value that Item_cond_or() returns for + not_null_tables() + */ + and_tables_cache= ~(table_map) 0; + + if (check_stack_overrun(thd, STACK_MIN_SIZE, buff)) + return TRUE; // Fatal error flag is set! + /* + The following optimization reduces the depth of an AND-OR tree. + E.g. a WHERE clause like + F1 AND (F2 AND (F2 AND F4)) + is parsed into a tree with the same nested structure as defined + by braces. This optimization will transform such tree into + AND (F1, F2, F3, F4). + Trees of OR items are flattened as well: + ((F1 OR F2) OR (F3 OR F4)) => OR (F1, F2, F3, F4) + Items for removed AND/OR levels will dangle until the death of the + entire statement. + The optimization is currently prepared statements and stored procedures + friendly as it doesn't allocate any memory and its effects are durable + (i.e. do not depend on PS/SP arguments). + */ + while ((item=li++)) + { + table_map tmp_table_map; + while (item->type() == Item::COND_ITEM && + ((Item_cond*) item)->functype() == functype() && + !((Item_cond*) item)->list.is_empty()) + { // Identical function + li.replace(((Item_cond*) item)->list); + ((Item_cond*) item)->list.empty(); + item= *li.ref(); // new current item + } + if (abort_on_null) + item->top_level_item(); + + // item can be substituted in fix_fields + if ((!item->fixed && + item->fix_fields(thd, li.ref())) || + (item= *li.ref())->check_cols(1)) + return TRUE; /* purecov: inspected */ + used_tables_cache|= item->used_tables(); + if (item->const_item()) + and_tables_cache= (table_map) 0; + else + { + tmp_table_map= item->not_null_tables(); + not_null_tables_cache|= tmp_table_map; + and_tables_cache&= tmp_table_map; + const_item_cache= FALSE; + } + with_sum_func= with_sum_func || item->with_sum_func; + with_subselect|= item->with_subselect; + if (item->maybe_null) + maybe_null=1; + } + thd->lex->current_select->cond_count+= list.elements; + fix_length_and_dec(); + fixed= 1; + return FALSE; +} + +bool Item_cond::walk(Item_processor processor, bool walk_subquery, uchar *arg) +{ + List_iterator_fast li(list); + Item *item; + while ((item= li++)) + if (item->walk(processor, walk_subquery, arg)) + return 1; + return Item_func::walk(processor, walk_subquery, arg); +} + + +/** + Transform an Item_cond object with a transformer callback function. + + The function recursively applies the transform method to each + member item of the condition list. + If the call of the method for a member item returns a new item + the old item is substituted for a new one. + After this the transformer is applied to the root node + of the Item_cond object. + + @param transformer the transformer callback function to be applied to + the nodes of the tree of the object + @param arg parameter to be passed to the transformer + + @return + Item returned as the result of transformation of the root node +*/ + +Item *Item_cond::transform(Item_transformer transformer, uchar *arg) +{ + DBUG_ASSERT(!current_thd->is_stmt_prepare()); + + List_iterator li(list); + Item *item; + while ((item= li++)) + { + Item *new_item= item->transform(transformer, arg); + if (!new_item) + return 0; + + /* + THD::change_item_tree() should be called only if the tree was + really transformed, i.e. when a new item has been created. + Otherwise we'll be allocating a lot of unnecessary memory for + change records at each execution. + */ + if (new_item != item) + current_thd->change_item_tree(li.ref(), new_item); + } + return Item_func::transform(transformer, arg); +} + + +/** + Compile Item_cond object with a processor and a transformer + callback functions. + + First the function applies the analyzer to the root node of + the Item_func object. Then if the analyzer succeeeds (returns TRUE) + the function recursively applies the compile method to member + item of the condition list. + If the call of the method for a member item returns a new item + the old item is substituted for a new one. + After this the transformer is applied to the root node + of the Item_cond object. + + @param analyzer the analyzer callback function to be applied to the + nodes of the tree of the object + @param[in,out] arg_p parameter to be passed to the analyzer + @param transformer the transformer callback function to be applied to the + nodes of the tree of the object + @param arg_t parameter to be passed to the transformer + + @return + Item returned as the result of transformation of the root node +*/ + +Item *Item_cond::compile(Item_analyzer analyzer, uchar **arg_p, + Item_transformer transformer, uchar *arg_t) +{ + if (!(this->*analyzer)(arg_p)) + return 0; + + List_iterator li(list); + Item *item; + while ((item= li++)) + { + /* + The same parameter value of arg_p must be passed + to analyze any argument of the condition formula. + */ + uchar *arg_v= *arg_p; + Item *new_item= item->compile(analyzer, &arg_v, transformer, arg_t); + if (new_item && new_item != item) + li.replace(new_item); + } + return Item_func::transform(transformer, arg_t); +} + +void Item_cond::traverse_cond(Cond_traverser traverser, + void *arg, traverse_order order) +{ + List_iterator li(list); + Item *item; + + switch(order) { + case(PREFIX): + (*traverser)(this, arg); + while ((item= li++)) + { + item->traverse_cond(traverser, arg, order); + } + (*traverser)(NULL, arg); + break; + case(POSTFIX): + while ((item= li++)) + { + item->traverse_cond(traverser, arg, order); + } + (*traverser)(this, arg); + } +} + +/** + Move SUM items out from item tree and replace with reference. + + The split is done to get an unique item for each SUM function + so that we can easily find and calculate them. + (Calculation done by update_sum_func() and copy_sum_funcs() in + sql_select.cc) + + @param thd Thread handler + @param ref_pointer_array Pointer to array of reference fields + @param fields All fields in select + + @note + This function is run on all expression (SELECT list, WHERE, HAVING etc) + that have or refer (HAVING) to a SUM expression. +*/ + +void Item_cond::split_sum_func(THD *thd, Item **ref_pointer_array, + List &fields) +{ + List_iterator li(list); + Item *item; + while ((item= li++)) + item->split_sum_func2(thd, ref_pointer_array, fields, li.ref(), TRUE); +} + + +table_map +Item_cond::used_tables() const +{ // This caches used_tables + return used_tables_cache; +} + + +void Item_cond::update_used_tables() +{ + List_iterator_fast li(list); + Item *item; + + used_tables_cache=0; + const_item_cache=1; + while ((item=li++)) + { + item->update_used_tables(); + used_tables_cache|= item->used_tables(); + const_item_cache&= item->const_item(); + } +} + + +void Item_cond::print(String *str, enum_query_type query_type) +{ + str->append('('); + List_iterator_fast li(list); + Item *item; + if ((item=li++)) + item->print(str, query_type); + while ((item=li++)) + { + str->append(' '); + str->append(func_name()); + str->append(' '); + item->print(str, query_type); + } + str->append(')'); +} + + +void Item_cond::neg_arguments(THD *thd) +{ + List_iterator li(list); + Item *item; + while ((item= li++)) /* Apply not transformation to the arguments */ + { + Item *new_item= item->neg_transformer(thd); + if (!new_item) + { + if (!(new_item= new Item_func_not(item))) + return; // Fatal OEM error + } + VOID(li.replace(new_item)); + } +} + + +/** + Evaluation of AND(expr, expr, expr ...). + + @note + abort_if_null is set for AND expressions for which we don't care if the + result is NULL or 0. This is set for: + - WHERE clause + - HAVING clause + - IF(expression) + + @retval + 1 If all expressions are true + @retval + 0 If all expressions are false or if we find a NULL expression and + 'abort_on_null' is set. + @retval + NULL if all expression are either 1 or NULL +*/ + + +longlong Item_cond_and::val_int() +{ + DBUG_ASSERT(fixed == 1); + List_iterator_fast li(list); + Item *item; + null_value= 0; + while ((item=li++)) + { + if (!item->val_bool()) + { + if (abort_on_null || !(null_value= item->null_value)) + return 0; // return FALSE + } + } + return null_value ? 0 : 1; +} + + +longlong Item_cond_or::val_int() +{ + DBUG_ASSERT(fixed == 1); + List_iterator_fast li(list); + Item *item; + null_value=0; + while ((item=li++)) + { + if (item->val_bool()) + { + null_value=0; + return 1; + } + if (item->null_value) + null_value=1; + } + return 0; +} + +/** + Create an AND expression from two expressions. + + @param a expression or NULL + @param b expression. + @param org_item Don't modify a if a == *org_item. + If a == NULL, org_item is set to point at b, + to ensure that future calls will not modify b. + + @note + This will not modify item pointed to by org_item or b + The idea is that one can call this in a loop and create and + 'and' over all items without modifying any of the original items. + + @retval + NULL Error + @retval + Item +*/ + +Item *and_expressions(Item *a, Item *b, Item **org_item) +{ + if (!a) + return (*org_item= (Item*) b); + if (a == *org_item) + { + Item_cond *res; + if ((res= new Item_cond_and(a, (Item*) b))) + { + res->used_tables_cache= a->used_tables() | b->used_tables(); + res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables(); + } + return res; + } + if (((Item_cond_and*) a)->add((Item*) b)) + return 0; + ((Item_cond_and*) a)->used_tables_cache|= b->used_tables(); + ((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables(); + return a; +} + + +longlong Item_func_isnull::val_int() +{ + DBUG_ASSERT(fixed == 1); + /* + Handle optimization if the argument can't be null + This has to be here because of the test in update_used_tables(). + */ + if (!used_tables_cache && !with_subselect) + return cached_value; + return args[0]->is_null() ? 1: 0; +} + +longlong Item_is_not_null_test::val_int() +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_is_not_null_test::val_int"); + if (!used_tables_cache && !with_subselect) + { + owner->was_null|= (!cached_value); + DBUG_PRINT("info", ("cached: %ld", (long) cached_value)); + DBUG_RETURN(cached_value); + } + if (args[0]->is_null()) + { + DBUG_PRINT("info", ("null")); + owner->was_null|= 1; + DBUG_RETURN(0); + } + else + DBUG_RETURN(1); +} + +/** + Optimize case of not_null_column IS NULL. +*/ +void Item_is_not_null_test::update_used_tables() +{ + if (!args[0]->maybe_null) + { + used_tables_cache= 0; /* is always true */ + cached_value= (longlong) 1; + } + else + { + args[0]->update_used_tables(); + if (!(used_tables_cache=args[0]->used_tables()) && !with_subselect) + { + /* Remember if the value is always NULL or never NULL */ + cached_value= (longlong) !args[0]->is_null(); + } + } +} + + +longlong Item_func_isnotnull::val_int() +{ + DBUG_ASSERT(fixed == 1); + return args[0]->is_null() ? 0 : 1; +} + + +void Item_func_isnotnull::print(String *str, enum_query_type query_type) +{ + str->append('('); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" is not null)")); +} + + +longlong Item_func_like::val_int() +{ + DBUG_ASSERT(fixed == 1); + String* res = args[0]->val_str(&tmp_value1); + if (args[0]->null_value) + { + null_value=1; + return 0; + } + String* res2 = args[1]->val_str(&tmp_value2); + if (args[1]->null_value) + { + null_value=1; + return 0; + } + null_value=0; + if (canDoTurboBM) + return turboBM_matches(res->ptr(), res->length()) ? 1 : 0; + return my_wildcmp(cmp.cmp_collation.collation, + res->ptr(),res->ptr()+res->length(), + res2->ptr(),res2->ptr()+res2->length(), + escape,wild_one,wild_many) ? 0 : 1; +} + + +/** + We can optimize a where if first character isn't a wildcard +*/ + +Item_func::optimize_type Item_func_like::select_optimize() const +{ + if (args[1]->const_item()) + { + String* res2= args[1]->val_str((String *)&tmp_value2); + + if (!res2) + return OPTIMIZE_NONE; + + if (*res2->ptr() != wild_many) + { + if (args[0]->result_type() != STRING_RESULT || *res2->ptr() != wild_one) + return OPTIMIZE_OP; + } + } + return OPTIMIZE_NONE; +} + + +bool Item_func_like::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + if (Item_bool_func2::fix_fields(thd, ref) || + escape_item->fix_fields(thd, &escape_item)) + return TRUE; + + if (!escape_item->const_during_execution()) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE"); + return TRUE; + } + + if (escape_item->const_item()) + { + /* If we are on execution stage */ + String *escape_str= escape_item->val_str(&tmp_value1); + if (escape_str) + { + if (escape_used_in_parsing && ( + (((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) && + escape_str->numchars() != 1) || + escape_str->numchars() > 1))) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE"); + return TRUE; + } + + if (use_mb(cmp.cmp_collation.collation)) + { + CHARSET_INFO *cs= escape_str->charset(); + my_wc_t wc; + int rc= cs->cset->mb_wc(cs, &wc, + (const uchar*) escape_str->ptr(), + (const uchar*) escape_str->ptr() + + escape_str->length()); + escape= (int) (rc > 0 ? wc : '\\'); + } + else + { + /* + In the case of 8bit character set, we pass native + code instead of Unicode code as "escape" argument. + Convert to "cs" if charset of escape differs. + */ + CHARSET_INFO *cs= cmp.cmp_collation.collation; + uint32 unused; + if (escape_str->needs_conversion(escape_str->length(), + escape_str->charset(), cs, &unused)) + { + char ch; + uint errors; + uint32 cnvlen= copy_and_convert(&ch, 1, cs, escape_str->ptr(), + escape_str->length(), + escape_str->charset(), &errors); + escape= cnvlen ? ch : '\\'; + } + else + escape= *(escape_str->ptr()); + } + } + else + escape= '\\'; + + /* + We could also do boyer-more for non-const items, but as we would have to + recompute the tables for each row it's not worth it. + */ + if (args[1]->const_item() && !use_strnxfrm(collation.collation) && + !(specialflag & SPECIAL_NO_NEW_FUNC)) + { + String* res2 = args[1]->val_str(&tmp_value2); + if (!res2) + return FALSE; // Null argument + + const size_t len = res2->length(); + const char* first = res2->ptr(); + const char* last = first + len - 1; + /* + len must be > 2 ('%pattern%') + heuristic: only do TurboBM for pattern_len > 2 + */ + + if (len > MIN_TURBOBM_PATTERN_LEN + 2 && + *first == wild_many && + *last == wild_many) + { + const char* tmp = first + 1; + for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ; + canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation); + } + if (canDoTurboBM) + { + pattern = first + 1; + pattern_len = (int) len - 2; + DBUG_PRINT("info", ("Initializing pattern: '%s'", first)); + int *suff = (int*) thd->alloc((int) (sizeof(int)* + ((pattern_len + 1)*2+ + alphabet_size))); + bmGs = suff + pattern_len + 1; + bmBc = bmGs + pattern_len + 1; + turboBM_compute_good_suffix_shifts(suff); + turboBM_compute_bad_character_shifts(); + DBUG_PRINT("info",("done")); + } + } + } + return FALSE; +} + +void Item_func_like::cleanup() +{ + canDoTurboBM= FALSE; + Item_bool_func2::cleanup(); +} + +#ifdef USE_REGEX + +/** + @brief Compile regular expression. + + @param[in] send_error send error message if any. + + @details Make necessary character set conversion then + compile regular expression passed in the args[1]. + + @retval 0 success. + @retval 1 error occurred. + @retval -1 given null regular expression. + */ + +int Item_func_regex::regcomp(bool send_error) +{ + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff),&my_charset_bin); + String *res= args[1]->val_str(&tmp); + int error; + + if (args[1]->null_value) + return -1; + + if (regex_compiled) + { + if (!stringcmp(res, &prev_regexp)) + return 0; + prev_regexp.copy(*res); + my_regfree(&preg); + regex_compiled= 0; + } + + if (cmp_collation.collation != regex_lib_charset) + { + /* Convert UCS2 strings to UTF8 */ + uint dummy_errors; + if (conv.copy(res->ptr(), res->length(), res->charset(), + regex_lib_charset, &dummy_errors)) + return 1; + res= &conv; + } + + if ((error= my_regcomp(&preg, res->c_ptr_safe(), + regex_lib_flags, regex_lib_charset))) + { + if (send_error) + { + (void) my_regerror(error, &preg, buff, sizeof(buff)); + my_error(ER_REGEXP_ERROR, MYF(0), buff); + } + return 1; + } + regex_compiled= 1; + return 0; +} + + +bool +Item_func_regex::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + if ((!args[0]->fixed && + args[0]->fix_fields(thd, args)) || args[0]->check_cols(1) || + (!args[1]->fixed && + args[1]->fix_fields(thd, args + 1)) || args[1]->check_cols(1)) + return TRUE; /* purecov: inspected */ + with_sum_func=args[0]->with_sum_func || args[1]->with_sum_func; + max_length= 1; + decimals= 0; + + if (agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1)) + return TRUE; + + regex_lib_flags= (cmp_collation.collation->state & + (MY_CS_BINSORT | MY_CS_CSSORT)) ? + REG_EXTENDED | REG_NOSUB : + REG_EXTENDED | REG_NOSUB | REG_ICASE; + /* + If the case of UCS2 and other non-ASCII character sets, + we will convert patterns and strings to UTF8. + */ + regex_lib_charset= (cmp_collation.collation->mbminlen > 1) ? + &my_charset_utf8_general_ci : + cmp_collation.collation; + + used_tables_cache=args[0]->used_tables() | args[1]->used_tables(); + not_null_tables_cache= (args[0]->not_null_tables() | + args[1]->not_null_tables()); + const_item_cache=args[0]->const_item() && args[1]->const_item(); + if (!regex_compiled && args[1]->const_item()) + { + int comp_res= regcomp(TRUE); + if (comp_res == -1) + { // Will always return NULL + maybe_null=1; + fixed= 1; + return FALSE; + } + else if (comp_res) + return TRUE; + regex_is_const= 1; + maybe_null= args[0]->maybe_null; + } + else + maybe_null=1; + fixed= 1; + return FALSE; +} + + +longlong Item_func_regex::val_int() +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff),&my_charset_bin); + String *res= args[0]->val_str(&tmp); + + if ((null_value= (args[0]->null_value || + (!regex_is_const && regcomp(FALSE))))) + return 0; + + if (cmp_collation.collation != regex_lib_charset) + { + /* Convert UCS2 strings to UTF8 */ + uint dummy_errors; + if (conv.copy(res->ptr(), res->length(), res->charset(), + regex_lib_charset, &dummy_errors)) + { + null_value= 1; + return 0; + } + res= &conv; + } + return my_regexec(&preg,res->c_ptr_safe(),0,(my_regmatch_t*) 0,0) ? 0 : 1; +} + + +void Item_func_regex::cleanup() +{ + DBUG_ENTER("Item_func_regex::cleanup"); + Item_bool_func::cleanup(); + if (regex_compiled) + { + my_regfree(&preg); + regex_compiled=0; + prev_regexp.length(0); + } + DBUG_VOID_RETURN; +} + + +#endif /* USE_REGEX */ + + +#ifdef LIKE_CMP_TOUPPER +#define likeconv(cs,A) (uchar) (cs)->toupper(A) +#else +#define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)] +#endif + + +/** + Precomputation dependent only on pattern_len. +*/ + +void Item_func_like::turboBM_compute_suffixes(int *suff) +{ + const int plm1 = pattern_len - 1; + int f = 0; + int g = plm1; + int *const splm1 = suff + plm1; + CHARSET_INFO *cs= cmp.cmp_collation.collation; + + *splm1 = pattern_len; + + if (!cs->sort_order) + { + int i; + for (i = pattern_len - 2; i >= 0; i--) + { + int tmp = *(splm1 + i - f); + if (g < i && tmp < i - g) + suff[i] = tmp; + else + { + if (i < g) + g = i; // g = min(i, g) + f = i; + while (g >= 0 && pattern[g] == pattern[g + plm1 - f]) + g--; + suff[i] = f - g; + } + } + } + else + { + int i; + for (i = pattern_len - 2; 0 <= i; --i) + { + int tmp = *(splm1 + i - f); + if (g < i && tmp < i - g) + suff[i] = tmp; + else + { + if (i < g) + g = i; // g = min(i, g) + f = i; + while (g >= 0 && + likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f])) + g--; + suff[i] = f - g; + } + } + } +} + + +/** + Precomputation dependent only on pattern_len. +*/ + +void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff) +{ + turboBM_compute_suffixes(suff); + + int *end = bmGs + pattern_len; + int *k; + for (k = bmGs; k < end; k++) + *k = pattern_len; + + int tmp; + int i; + int j = 0; + const int plm1 = pattern_len - 1; + for (i = plm1; i > -1; i--) + { + if (suff[i] == i + 1) + { + for (tmp = plm1 - i; j < tmp; j++) + { + int *tmp2 = bmGs + j; + if (*tmp2 == pattern_len) + *tmp2 = tmp; + } + } + } + + int *tmp2; + for (tmp = plm1 - i; j < tmp; j++) + { + tmp2 = bmGs + j; + if (*tmp2 == pattern_len) + *tmp2 = tmp; + } + + tmp2 = bmGs + plm1; + for (i = 0; i <= pattern_len - 2; i++) + *(tmp2 - suff[i]) = plm1 - i; +} + + +/** + Precomputation dependent on pattern_len. +*/ + +void Item_func_like::turboBM_compute_bad_character_shifts() +{ + int *i; + int *end = bmBc + alphabet_size; + int j; + const int plm1 = pattern_len - 1; + CHARSET_INFO *cs= cmp.cmp_collation.collation; + + for (i = bmBc; i < end; i++) + *i = pattern_len; + + if (!cs->sort_order) + { + for (j = 0; j < plm1; j++) + bmBc[(uint) (uchar) pattern[j]] = plm1 - j; + } + else + { + for (j = 0; j < plm1; j++) + bmBc[(uint) likeconv(cs,pattern[j])] = plm1 - j; + } +} + + +/** + Search for pattern in text. + + @return + returns true/false for match/no match +*/ + +bool Item_func_like::turboBM_matches(const char* text, int text_len) const +{ + register int bcShift; + register int turboShift; + int shift = pattern_len; + int j = 0; + int u = 0; + CHARSET_INFO *cs= cmp.cmp_collation.collation; + + const int plm1= pattern_len - 1; + const int tlmpl= text_len - pattern_len; + + /* Searching */ + if (!cs->sort_order) + { + while (j <= tlmpl) + { + register int i= plm1; + while (i >= 0 && pattern[i] == text[i + j]) + { + i--; + if (i == plm1 - shift) + i-= u; + } + if (i < 0) + return 1; + + register const int v = plm1 - i; + turboShift = u - v; + bcShift = bmBc[(uint) (uchar) text[i + j]] - plm1 + i; + shift = max(turboShift, bcShift); + shift = max(shift, bmGs[i]); + if (shift == bmGs[i]) + u = min(pattern_len - shift, v); + else + { + if (turboShift < bcShift) + shift = max(shift, u + 1); + u = 0; + } + j+= shift; + } + return 0; + } + else + { + while (j <= tlmpl) + { + register int i = plm1; + while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j])) + { + i--; + if (i == plm1 - shift) + i-= u; + } + if (i < 0) + return 1; + + register const int v = plm1 - i; + turboShift = u - v; + bcShift = bmBc[(uint) likeconv(cs, text[i + j])] - plm1 + i; + shift = max(turboShift, bcShift); + shift = max(shift, bmGs[i]); + if (shift == bmGs[i]) + u = min(pattern_len - shift, v); + else + { + if (turboShift < bcShift) + shift = max(shift, u + 1); + u = 0; + } + j+= shift; + } + return 0; + } +} + + +/** + Make a logical XOR of the arguments. + + If either operator is NULL, return NULL. + + @todo + (low priority) Change this to be optimized as: @n + A XOR B -> (A) == 1 AND (B) <> 1) OR (A <> 1 AND (B) == 1) @n + To be able to do this, we would however first have to extend the MySQL + range optimizer to handle OR better. + + @note + As we don't do any index optimization on XOR this is not going to be + very fast to use. +*/ + +longlong Item_cond_xor::val_int() +{ + DBUG_ASSERT(fixed == 1); + List_iterator li(list); + Item *item; + int result=0; + null_value=0; + while ((item=li++)) + { + result^= (item->val_int() != 0); + if (item->null_value) + { + null_value=1; + return 0; + } + } + return (longlong) result; +} + +/** + Apply NOT transformation to the item and return a new one. + + + Transform the item using next rules: + @verbatim + a AND b AND ... -> NOT(a) OR NOT(b) OR ... + a OR b OR ... -> NOT(a) AND NOT(b) AND ... + NOT(a) -> a + a = b -> a != b + a != b -> a = b + a < b -> a >= b + a >= b -> a < b + a > b -> a <= b + a <= b -> a > b + IS NULL(a) -> IS NOT NULL(a) + IS NOT NULL(a) -> IS NULL(a) + @endverbatim + + @param thd thread handler + + @return + New item or + NULL if we cannot apply NOT transformation (see Item::neg_transformer()). +*/ + +Item *Item_func_not::neg_transformer(THD *thd) /* NOT(x) -> x */ +{ + return args[0]; +} + + +Item *Item_bool_rowready_func2::neg_transformer(THD *thd) +{ + Item *item= negated_item(); + return item; +} + + +/** + a IS NULL -> a IS NOT NULL. +*/ +Item *Item_func_isnull::neg_transformer(THD *thd) +{ + Item *item= new Item_func_isnotnull(args[0]); + return item; +} + + +/** + a IS NOT NULL -> a IS NULL. +*/ +Item *Item_func_isnotnull::neg_transformer(THD *thd) +{ + Item *item= new Item_func_isnull(args[0]); + return item; +} + + +Item *Item_cond_and::neg_transformer(THD *thd) /* NOT(a AND b AND ...) -> */ + /* NOT a OR NOT b OR ... */ +{ + neg_arguments(thd); + Item *item= new Item_cond_or(list); + return item; +} + + +Item *Item_cond_or::neg_transformer(THD *thd) /* NOT(a OR b OR ...) -> */ + /* NOT a AND NOT b AND ... */ +{ + neg_arguments(thd); + Item *item= new Item_cond_and(list); + return item; +} + + +Item *Item_func_nop_all::neg_transformer(THD *thd) +{ + /* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */ + Item_func_not_all *new_item= new Item_func_not_all(args[0]); + Item_allany_subselect *allany= (Item_allany_subselect*)args[0]; + allany->func= allany->func_creator(FALSE); + allany->all= !allany->all; + allany->upper_item= new_item; + return new_item; +} + +Item *Item_func_not_all::neg_transformer(THD *thd) +{ + /* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */ + Item_func_nop_all *new_item= new Item_func_nop_all(args[0]); + Item_allany_subselect *allany= (Item_allany_subselect*)args[0]; + allany->all= !allany->all; + allany->func= allany->func_creator(TRUE); + allany->upper_item= new_item; + return new_item; +} + +Item *Item_func_eq::negated_item() /* a = b -> a != b */ +{ + return new Item_func_ne(args[0], args[1]); +} + + +Item *Item_func_ne::negated_item() /* a != b -> a = b */ +{ + return new Item_func_eq(args[0], args[1]); +} + + +Item *Item_func_lt::negated_item() /* a < b -> a >= b */ +{ + return new Item_func_ge(args[0], args[1]); +} + + +Item *Item_func_ge::negated_item() /* a >= b -> a < b */ +{ + return new Item_func_lt(args[0], args[1]); +} + + +Item *Item_func_gt::negated_item() /* a > b -> a <= b */ +{ + return new Item_func_le(args[0], args[1]); +} + + +Item *Item_func_le::negated_item() /* a <= b -> a > b */ +{ + return new Item_func_gt(args[0], args[1]); +} + +/** + just fake method, should never be called. +*/ +Item *Item_bool_rowready_func2::negated_item() +{ + DBUG_ASSERT(0); + return 0; +} + +Item_equal::Item_equal(Item_field *f1, Item_field *f2) + : Item_bool_func(), const_item(0), eval_item(0), cond_false(0) +{ + const_item_cache= 0; + fields.push_back(f1); + fields.push_back(f2); +} + +Item_equal::Item_equal(Item *c, Item_field *f) + : Item_bool_func(), eval_item(0), cond_false(0) +{ + const_item_cache= 0; + fields.push_back(f); + const_item= c; +} + + +Item_equal::Item_equal(Item_equal *item_equal) + : Item_bool_func(), eval_item(0), cond_false(0) +{ + const_item_cache= 0; + List_iterator_fast li(item_equal->fields); + Item_field *item; + while ((item= li++)) + { + fields.push_back(item); + } + const_item= item_equal->const_item; + cond_false= item_equal->cond_false; +} + +void Item_equal::add(Item *c) +{ + if (cond_false) + return; + if (!const_item) + { + const_item= c; + return; + } + Item_func_eq *func= new Item_func_eq(c, const_item); + func->set_cmp_func(); + func->quick_fix_field(); + if ((cond_false= !func->val_int())) + const_item_cache= 1; +} + +void Item_equal::add(Item_field *f) +{ + fields.push_back(f); +} + +uint Item_equal::members() +{ + return fields.elements; +} + + +/** + Check whether a field is referred in the multiple equality. + + The function checks whether field is occurred in the Item_equal object . + + @param field field whose occurrence is to be checked + + @retval + 1 if nultiple equality contains a reference to field + @retval + 0 otherwise +*/ + +bool Item_equal::contains(Field *field) +{ + List_iterator_fast it(fields); + Item_field *item; + while ((item= it++)) + { + if (field->eq(item->field)) + return 1; + } + return 0; +} + + +/** + Join members of another Item_equal object. + + The function actually merges two multiple equalities. + After this operation the Item_equal object additionally contains + the field items of another item of the type Item_equal. + If the optional constant items are not equal the cond_false flag is + set to 1. + @param item multiple equality whose members are to be joined +*/ + +void Item_equal::merge(Item_equal *item) +{ + fields.concat(&item->fields); + Item *c= item->const_item; + if (c) + { + /* + The flag cond_false will be set to 1 after this, if + the multiple equality already contains a constant and its + value is not equal to the value of c. + */ + add(c); + } + cond_false|= item->cond_false; +} + + +/** + Order field items in multiple equality according to a sorting criteria. + + The function perform ordering of the field items in the Item_equal + object according to the criteria determined by the cmp callback parameter. + If cmp(item_field1,item_field2,arg)<0 than item_field1 must be + placed after item_fiel2. + + The function sorts field items by the exchange sort algorithm. + The list of field items is looked through and whenever two neighboring + members follow in a wrong order they are swapped. This is performed + again and again until we get all members in a right order. + + @param cmp function to compare field item + @param arg context extra parameter for the cmp function +*/ + +void Item_equal::sort(Item_field_cmpfunc cmp, void *arg) +{ + bool swap; + List_iterator it(fields); + do + { + Item_field *item1= it++; + Item_field **ref1= it.ref(); + Item_field *item2; + + swap= FALSE; + while ((item2= it++)) + { + Item_field **ref2= it.ref(); + if (cmp(item1, item2, arg) < 0) + { + Item_field *item= *ref1; + *ref1= *ref2; + *ref2= item; + swap= TRUE; + } + else + { + item1= item2; + ref1= ref2; + } + } + it.rewind(); + } while (swap); +} + + +/** + Check appearance of new constant items in the multiple equality object. + + The function checks appearance of new constant items among + the members of multiple equalities. Each new constant item is + compared with the designated constant item if there is any in the + multiple equality. If there is none the first new constant item + becomes designated. +*/ + +void Item_equal::update_const() +{ + List_iterator it(fields); + Item *item; + while ((item= it++)) + { + if (item->const_item()) + { + it.remove(); + add(item); + } + } +} + +bool Item_equal::fix_fields(THD *thd, Item **ref) +{ + List_iterator_fast li(fields); + Item *item; + not_null_tables_cache= used_tables_cache= 0; + const_item_cache= 0; + while ((item= li++)) + { + table_map tmp_table_map; + used_tables_cache|= item->used_tables(); + tmp_table_map= item->not_null_tables(); + not_null_tables_cache|= tmp_table_map; + if (item->maybe_null) + maybe_null=1; + } + fix_length_and_dec(); + fixed= 1; + return 0; +} + +void Item_equal::update_used_tables() +{ + List_iterator_fast li(fields); + Item *item; + not_null_tables_cache= used_tables_cache= 0; + if ((const_item_cache= cond_false)) + return; + while ((item=li++)) + { + item->update_used_tables(); + used_tables_cache|= item->used_tables(); + const_item_cache&= item->const_item(); + } +} + +longlong Item_equal::val_int() +{ + Item_field *item_field; + if (cond_false) + return 0; + List_iterator_fast it(fields); + Item *item= const_item ? const_item : it++; + if ((null_value= item->null_value)) + return 0; + eval_item->store_value(item); + while ((item_field= it++)) + { + /* Skip fields of non-const tables. They haven't been read yet */ + if (item_field->field->table->const_table) + { + if ((null_value= item_field->null_value) || eval_item->cmp(item_field)) + return 0; + } + } + return 1; +} + +void Item_equal::fix_length_and_dec() +{ + Item *item= get_first(); + eval_item= cmp_item::get_comparator(item->result_type(), + item->collation.collation); +} + +bool Item_equal::walk(Item_processor processor, bool walk_subquery, uchar *arg) +{ + List_iterator_fast it(fields); + Item *item; + while ((item= it++)) + { + if (item->walk(processor, walk_subquery, arg)) + return 1; + } + return Item_func::walk(processor, walk_subquery, arg); +} + +Item *Item_equal::transform(Item_transformer transformer, uchar *arg) +{ + DBUG_ASSERT(!current_thd->is_stmt_prepare()); + + List_iterator it(fields); + Item *item; + while ((item= it++)) + { + Item *new_item= item->transform(transformer, arg); + if (!new_item) + return 0; + + /* + THD::change_item_tree() should be called only if the tree was + really transformed, i.e. when a new item has been created. + Otherwise we'll be allocating a lot of unnecessary memory for + change records at each execution. + */ + if (new_item != item) + current_thd->change_item_tree((Item **) it.ref(), new_item); + } + return Item_func::transform(transformer, arg); +} + +void Item_equal::print(String *str, enum_query_type query_type) +{ + str->append(func_name()); + str->append('('); + List_iterator_fast it(fields); + Item *item; + if (const_item) + const_item->print(str, query_type); + else + { + item= it++; + item->print(str, query_type); + } + while ((item= it++)) + { + str->append(','); + str->append(' '); + item->print(str, query_type); + } + str->append(')'); +} + diff --git a/dbcon/mysql/item_cmpfunc.h b/dbcon/mysql/item_cmpfunc.h new file mode 100644 index 00000000..85bb8410 --- /dev/null +++ b/dbcon/mysql/item_cmpfunc.h @@ -0,0 +1,1725 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* compare and test functions */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +extern Item_result item_cmp_type(Item_result a,Item_result b); +class Item_bool_func2; +class Arg_comparator; + +typedef int (Arg_comparator::*arg_cmp_func)(); + +typedef int (*Item_field_cmpfunc)(Item_field *f1, Item_field *f2, void *arg); + +class Arg_comparator: public Sql_alloc +{ + Item **a, **b; + arg_cmp_func func; + Item_bool_func2 *owner; + Arg_comparator *comparators; // used only for compare_row() + double precision; + /* Fields used in DATE/DATETIME comparison. */ + THD *thd; + enum_field_types a_type, b_type; // Types of a and b items + Item *a_cache, *b_cache; // Cached values of a and b items + bool is_nulls_eq; // TRUE <=> compare for the EQUAL_FUNC + enum enum_date_cmp_type { CMP_DATE_DFLT= 0, CMP_DATE_WITH_DATE, + CMP_DATE_WITH_STR, CMP_STR_WITH_DATE }; + longlong (*get_value_func)(THD *thd, Item ***item_arg, Item **cache_arg, + Item *warn_item, bool *is_null); +public: + DTCollation cmp_collation; + + Arg_comparator(): thd(0), a_cache(0), b_cache(0) {}; + Arg_comparator(Item **a1, Item **a2): a(a1), b(a2), thd(0), + a_cache(0), b_cache(0) {}; + + int set_compare_func(Item_bool_func2 *owner, Item_result type); + inline int set_compare_func(Item_bool_func2 *owner_arg) + { + return set_compare_func(owner_arg, item_cmp_type((*a)->result_type(), + (*b)->result_type())); + } + int set_cmp_func(Item_bool_func2 *owner_arg, + Item **a1, Item **a2, + Item_result type); + + inline int set_cmp_func(Item_bool_func2 *owner_arg, + Item **a1, Item **a2) + { + return set_cmp_func(owner_arg, a1, a2, + item_cmp_type((*a1)->result_type(), + (*a2)->result_type())); + } + inline int compare() { return (this->*func)(); } + + int compare_string(); // compare args[0] & args[1] + int compare_binary_string(); // compare args[0] & args[1] + int compare_real(); // compare args[0] & args[1] + int compare_decimal(); // compare args[0] & args[1] + int compare_int_signed(); // compare args[0] & args[1] + int compare_int_signed_unsigned(); + int compare_int_unsigned_signed(); + int compare_int_unsigned(); + int compare_row(); // compare args[0] & args[1] + int compare_e_string(); // compare args[0] & args[1] + int compare_e_binary_string(); // compare args[0] & args[1] + int compare_e_real(); // compare args[0] & args[1] + int compare_e_decimal(); // compare args[0] & args[1] + int compare_e_int(); // compare args[0] & args[1] + int compare_e_int_diff_signedness(); + int compare_e_row(); // compare args[0] & args[1] + int compare_real_fixed(); + int compare_e_real_fixed(); + int compare_datetime(); // compare args[0] & args[1] as DATETIMEs + + static enum enum_date_cmp_type can_compare_as_dates(Item *a, Item *b, + ulonglong *const_val_arg); + + void set_datetime_cmp_func(Item **a1, Item **b1); + static arg_cmp_func comparator_matrix [5][2]; + + friend class Item_func; +}; + +class Item_bool_func :public Item_int_func +{ +public: + Item_bool_func() :Item_int_func() {} + Item_bool_func(Item *a) :Item_int_func(a) {} + Item_bool_func(Item *a,Item *b) :Item_int_func(a,b) {} + Item_bool_func(THD *thd, Item_bool_func *item) :Item_int_func(thd, item) {} + bool is_bool_func() { return 1; } + void fix_length_and_dec() { decimals=0; max_length=1; } + uint decimal_precision() const { return 1; } +}; + + +/** + Abstract Item class, to represent X IS [NOT] (TRUE | FALSE) + boolean predicates. +*/ + +class Item_func_truth : public Item_bool_func +{ +public: + virtual bool val_bool(); + virtual longlong val_int(); + virtual void fix_length_and_dec(); + virtual void print(String *str, enum_query_type query_type); + +protected: + Item_func_truth(Item *a, bool a_value, bool a_affirmative) + : Item_bool_func(a), value(a_value), affirmative(a_affirmative) + {} + + ~Item_func_truth() + {} +private: + /** + True for X IS [NOT] TRUE, + false for X IS [NOT] FALSE predicates. + */ + const bool value; + /** + True for X IS Y, false for X IS NOT Y predicates. + */ + const bool affirmative; +}; + + +/** + This Item represents a X IS TRUE boolean predicate. +*/ + +class Item_func_istrue : public Item_func_truth +{ +public: + Item_func_istrue(Item *a) : Item_func_truth(a, true, true) {} + ~Item_func_istrue() {} + virtual const char* func_name() const { return "istrue"; } +}; + + +/** + This Item represents a X IS NOT TRUE boolean predicate. +*/ + +class Item_func_isnottrue : public Item_func_truth +{ +public: + Item_func_isnottrue(Item *a) : Item_func_truth(a, true, false) {} + ~Item_func_isnottrue() {} + virtual const char* func_name() const { return "isnottrue"; } +}; + + +/** + This Item represents a X IS FALSE boolean predicate. +*/ + +class Item_func_isfalse : public Item_func_truth +{ +public: + Item_func_isfalse(Item *a) : Item_func_truth(a, false, true) {} + ~Item_func_isfalse() {} + virtual const char* func_name() const { return "isfalse"; } +}; + + +/** + This Item represents a X IS NOT FALSE boolean predicate. +*/ + +class Item_func_isnotfalse : public Item_func_truth +{ +public: + Item_func_isnotfalse(Item *a) : Item_func_truth(a, false, false) {} + ~Item_func_isnotfalse() {} + virtual const char* func_name() const { return "isnotfalse"; } +}; + + +class Item_cache; +#define UNKNOWN ((my_bool)-1) + + +/* + Item_in_optimizer(left_expr, Item_in_subselect(...)) + + Item_in_optimizer is used to wrap an instance of Item_in_subselect. This + class does the following: + - Evaluate the left expression and store it in Item_cache_* object (to + avoid re-evaluating it many times during subquery execution) + - Shortcut the evaluation of "NULL IN (...)" to NULL in the cases where we + don't care if the result is NULL or FALSE. + + NOTE + It is not quite clear why the above listed functionality should be + placed into a separate class called 'Item_in_optimizer'. +*/ + +class Item_in_optimizer: public Item_bool_func +{ +protected: + Item_cache *cache; + bool save_cache; + /* + Stores the value of "NULL IN (SELECT ...)" for uncorrelated subqueries: + UNKNOWN - "NULL in (SELECT ...)" has not yet been evaluated + FALSE - result is FALSE + TRUE - result is NULL + */ + my_bool result_for_null_param; +public: + Item_in_optimizer(Item *a, Item_in_subselect *b): + Item_bool_func(a, my_reinterpret_cast(Item *)(b)), cache(0), + save_cache(0), result_for_null_param(UNKNOWN) + {} + bool fix_fields(THD *, Item **); + bool fix_left(THD *thd, Item **ref); + bool is_null(); + longlong val_int(); + void cleanup(); + const char *func_name() const { return ""; } + Item_cache **get_cache() { return &cache; } + void keep_top_level_cache(); +}; + +class Comp_creator +{ +public: + Comp_creator() {} /* Remove gcc warning */ + virtual ~Comp_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const = 0; + virtual const char* symbol(bool invert) const = 0; + virtual bool eqne_op() const = 0; + virtual bool l_op() const = 0; +}; + +class Eq_creator :public Comp_creator +{ +public: + Eq_creator() {} /* Remove gcc warning */ + virtual ~Eq_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const; + virtual const char* symbol(bool invert) const { return invert? "<>" : "="; } + virtual bool eqne_op() const { return 1; } + virtual bool l_op() const { return 0; } +}; + +class Ne_creator :public Comp_creator +{ +public: + Ne_creator() {} /* Remove gcc warning */ + virtual ~Ne_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const; + virtual const char* symbol(bool invert) const { return invert? "=" : "<>"; } + virtual bool eqne_op() const { return 1; } + virtual bool l_op() const { return 0; } +}; + +class Gt_creator :public Comp_creator +{ +public: + Gt_creator() {} /* Remove gcc warning */ + virtual ~Gt_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const; + virtual const char* symbol(bool invert) const { return invert? "<=" : ">"; } + virtual bool eqne_op() const { return 0; } + virtual bool l_op() const { return 0; } +}; + +class Lt_creator :public Comp_creator +{ +public: + Lt_creator() {} /* Remove gcc warning */ + virtual ~Lt_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const; + virtual const char* symbol(bool invert) const { return invert? ">=" : "<"; } + virtual bool eqne_op() const { return 0; } + virtual bool l_op() const { return 1; } +}; + +class Ge_creator :public Comp_creator +{ +public: + Ge_creator() {} /* Remove gcc warning */ + virtual ~Ge_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const; + virtual const char* symbol(bool invert) const { return invert? "<" : ">="; } + virtual bool eqne_op() const { return 0; } + virtual bool l_op() const { return 0; } +}; + +class Le_creator :public Comp_creator +{ +public: + Le_creator() {} /* Remove gcc warning */ + virtual ~Le_creator() {} /* Remove gcc warning */ + virtual Item_bool_func2* create(Item *a, Item *b) const; + virtual const char* symbol(bool invert) const { return invert? ">" : "<="; } + virtual bool eqne_op() const { return 0; } + virtual bool l_op() const { return 1; } +}; + +class Item_bool_func2 :public Item_int_func +{ /* Bool with 2 string args */ +protected: + Arg_comparator cmp; + String tmp_value1,tmp_value2; + bool abort_on_null; + +public: + Item_bool_func2(Item *a,Item *b) + :Item_int_func(a,b), cmp(tmp_arg, tmp_arg+1), abort_on_null(FALSE) {} + void fix_length_and_dec(); + void set_cmp_func() + { + cmp.set_cmp_func(this, tmp_arg, tmp_arg+1); + } + optimize_type select_optimize() const { return OPTIMIZE_OP; } + virtual enum Functype rev_functype() const { return UNKNOWN_FUNC; } + bool have_rev_func() const { return rev_functype() != UNKNOWN_FUNC; } + + virtual inline void print(String *str, enum_query_type query_type) + { + Item_func::print_op(str, query_type); + } + + bool is_null() { return test(args[0]->is_null() || args[1]->is_null()); } + bool is_bool_func() { return 1; } + CHARSET_INFO *compare_collation() { return cmp.cmp_collation.collation; } + uint decimal_precision() const { return 1; } + void top_level_item() { abort_on_null= TRUE; } + + friend class Arg_comparator; +}; + +class Item_bool_rowready_func2 :public Item_bool_func2 +{ +public: + Item_bool_rowready_func2(Item *a, Item *b) :Item_bool_func2(a, b) + { + allowed_arg_cols= 0; // Fetch this value from first argument + } + Item *neg_transformer(THD *thd); + virtual Item *negated_item(); + bool subst_argument_checker(uchar **arg) { return TRUE; } +}; + +class Item_func_not :public Item_bool_func +{ +public: + Item_func_not(Item *a) :Item_bool_func(a) {} + longlong val_int(); + enum Functype functype() const { return NOT_FUNC; } + const char *func_name() const { return "not"; } + Item *neg_transformer(THD *thd); + virtual void print(String *str, enum_query_type query_type); +}; + +class Item_maxmin_subselect; + +/* + trigcond(arg) ::= param? arg : TRUE + + The class Item_func_trig_cond is used for guarded predicates + which are employed only for internal purposes. + A guarded predicate is an object consisting of an a regular or + a guarded predicate P and a pointer to a boolean guard variable g. + A guarded predicate P/g is evaluated to true if the value of the + guard g is false, otherwise it is evaluated to the same value that + the predicate P: val(P/g)= g ? val(P):true. + Guarded predicates allow us to include predicates into a conjunction + conditionally. Currently they are utilized for pushed down predicates + in queries with outer join operations. + + In the future, probably, it makes sense to extend this class to + the objects consisting of three elements: a predicate P, a pointer + to a variable g and a firing value s with following evaluation + rule: val(P/g,s)= g==s? val(P) : true. It will allow us to build only + one item for the objects of the form P/g1/g2... + + Objects of this class are built only for query execution after + the execution plan has been already selected. That's why this + class needs only val_int out of generic methods. + + Current uses of Item_func_trig_cond objects: + - To wrap selection conditions when executing outer joins + - To wrap condition that is pushed down into subquery +*/ + +class Item_func_trig_cond: public Item_bool_func +{ + bool *trig_var; +public: + Item_func_trig_cond(Item *a, bool *f) : Item_bool_func(a) { trig_var= f; } + longlong val_int() { return *trig_var ? args[0]->val_int() : 1; } + enum Functype functype() const { return TRIG_COND_FUNC; }; + const char *func_name() const { return "trigcond"; }; + bool const_item() const { return FALSE; } + bool *get_trig_var() { return trig_var; } +}; + +class Item_func_not_all :public Item_func_not +{ + /* allow to check presence of values in max/min optimization */ + Item_sum_hybrid *test_sum_item; + Item_maxmin_subselect *test_sub_item; + + bool abort_on_null; +public: + bool show; + + Item_func_not_all(Item *a) + :Item_func_not(a), test_sum_item(0), test_sub_item(0), abort_on_null(0), + show(0) + {} + virtual void top_level_item() { abort_on_null= 1; } + bool top_level() { return abort_on_null; } + longlong val_int(); + enum Functype functype() const { return NOT_ALL_FUNC; } + const char *func_name() const { return ""; } + virtual void print(String *str, enum_query_type query_type); + void set_sum_test(Item_sum_hybrid *item) { test_sum_item= item; }; + void set_sub_test(Item_maxmin_subselect *item) { test_sub_item= item; }; + bool empty_underlying_subquery(); + Item *neg_transformer(THD *thd); +}; + + +class Item_func_nop_all :public Item_func_not_all +{ +public: + + Item_func_nop_all(Item *a) :Item_func_not_all(a) {} + longlong val_int(); + const char *func_name() const { return ""; } + Item *neg_transformer(THD *thd); +}; + + +class Item_func_eq :public Item_bool_rowready_func2 +{ +public: + Item_func_eq(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {} + longlong val_int(); + enum Functype functype() const { return EQ_FUNC; } + enum Functype rev_functype() const { return EQ_FUNC; } + cond_result eq_cmp_result() const { return COND_TRUE; } + const char *func_name() const { return "="; } + Item *negated_item(); +}; + +class Item_func_equal :public Item_bool_rowready_func2 +{ +public: + Item_func_equal(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {}; + longlong val_int(); + void fix_length_and_dec(); + table_map not_null_tables() const { return 0; } + enum Functype functype() const { return EQUAL_FUNC; } + enum Functype rev_functype() const { return EQUAL_FUNC; } + cond_result eq_cmp_result() const { return COND_TRUE; } + const char *func_name() const { return "<=>"; } + Item *neg_transformer(THD *thd) { return 0; } +}; + + +class Item_func_ge :public Item_bool_rowready_func2 +{ +public: + Item_func_ge(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {}; + longlong val_int(); + enum Functype functype() const { return GE_FUNC; } + enum Functype rev_functype() const { return LE_FUNC; } + cond_result eq_cmp_result() const { return COND_TRUE; } + const char *func_name() const { return ">="; } + Item *negated_item(); +}; + + +class Item_func_gt :public Item_bool_rowready_func2 +{ +public: + Item_func_gt(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {}; + longlong val_int(); + enum Functype functype() const { return GT_FUNC; } + enum Functype rev_functype() const { return LT_FUNC; } + cond_result eq_cmp_result() const { return COND_FALSE; } + const char *func_name() const { return ">"; } + Item *negated_item(); +}; + + +class Item_func_le :public Item_bool_rowready_func2 +{ +public: + Item_func_le(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {}; + longlong val_int(); + enum Functype functype() const { return LE_FUNC; } + enum Functype rev_functype() const { return GE_FUNC; } + cond_result eq_cmp_result() const { return COND_TRUE; } + const char *func_name() const { return "<="; } + Item *negated_item(); +}; + + +class Item_func_lt :public Item_bool_rowready_func2 +{ +public: + Item_func_lt(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {} + longlong val_int(); + enum Functype functype() const { return LT_FUNC; } + enum Functype rev_functype() const { return GT_FUNC; } + cond_result eq_cmp_result() const { return COND_FALSE; } + const char *func_name() const { return "<"; } + Item *negated_item(); +}; + + +class Item_func_ne :public Item_bool_rowready_func2 +{ +public: + Item_func_ne(Item *a,Item *b) :Item_bool_rowready_func2(a,b) {} + longlong val_int(); + enum Functype functype() const { return NE_FUNC; } + cond_result eq_cmp_result() const { return COND_FALSE; } + optimize_type select_optimize() const { return OPTIMIZE_KEY; } + const char *func_name() const { return "<>"; } + Item *negated_item(); +}; + + +/* + The class Item_func_opt_neg is defined to factor out the functionality + common for the classes Item_func_between and Item_func_in. The objects + of these classes can express predicates or there negations. + The alternative approach would be to create pairs Item_func_between, + Item_func_notbetween and Item_func_in, Item_func_notin. + +*/ + +class Item_func_opt_neg :public Item_int_func +{ +public: + bool negated; /* <=> the item represents NOT */ + bool pred_level; /* <=> [NOT] is used on a predicate level */ +public: + Item_func_opt_neg(Item *a, Item *b, Item *c) + :Item_int_func(a, b, c), negated(0), pred_level(0) {} + Item_func_opt_neg(List &list) + :Item_int_func(list), negated(0), pred_level(0) {} +public: + inline void negate() { negated= !negated; } + inline void top_level_item() { pred_level= 1; } + Item *neg_transformer(THD *thd) + { + negated= !negated; + return this; + } + bool eq(const Item *item, bool binary_cmp) const; + bool subst_argument_checker(uchar **arg) { return TRUE; } +}; + + +class Item_func_between :public Item_func_opt_neg +{ + DTCollation cmp_collation; +public: + Item_result cmp_type; + String value0,value1,value2; + /* TRUE <=> arguments will be compared as dates. */ + bool compare_as_dates; + /* Comparators used for DATE/DATETIME comparison. */ + Arg_comparator ge_cmp, le_cmp; + Item_func_between(Item *a, Item *b, Item *c) + :Item_func_opt_neg(a, b, c), compare_as_dates(FALSE) {} + longlong val_int(); + optimize_type select_optimize() const { return OPTIMIZE_KEY; } + enum Functype functype() const { return BETWEEN; } + const char *func_name() const { return "between"; } + bool fix_fields(THD *, Item **); + void fix_length_and_dec(); + virtual void print(String *str, enum_query_type query_type); + bool is_bool_func() { return 1; } + CHARSET_INFO *compare_collation() { return cmp_collation.collation; } + uint decimal_precision() const { return 1; } +}; + + +class Item_func_strcmp :public Item_bool_func2 +{ +public: + Item_func_strcmp(Item *a,Item *b) :Item_bool_func2(a,b) {} + longlong val_int(); + optimize_type select_optimize() const { return OPTIMIZE_NONE; } + const char *func_name() const { return "strcmp"; } + + virtual inline void print(String *str, enum_query_type query_type) + { + Item_func::print(str, query_type); + } +}; + + +struct interval_range +{ + Item_result type; + double dbl; + my_decimal dec; +}; + +class Item_func_interval :public Item_int_func +{ + Item_row *row; + my_bool use_decimal_comparison; + interval_range *intervals; +public: + Item_func_interval(Item_row *a) + :Item_int_func(a),row(a),intervals(0) + { + allowed_arg_cols= 0; // Fetch this value from first argument + } + longlong val_int(); + void fix_length_and_dec(); + const char *func_name() const { return "interval"; } + uint decimal_precision() const { return 2; } +}; + + +class Item_func_coalesce :public Item_func_numhybrid +{ +protected: + enum_field_types cached_field_type; + Item_func_coalesce(Item *a, Item *b) :Item_func_numhybrid(a, b) {} +public: + Item_func_coalesce(List &list) :Item_func_numhybrid(list) {} + double real_op(); + longlong int_op(); + String *str_op(String *); + my_decimal *decimal_op(my_decimal *); + void fix_length_and_dec(); + void find_num_type() {} + enum Item_result result_type () const { return hybrid_type; } + const char *func_name() const { return "coalesce"; } + table_map not_null_tables() const { return 0; } + enum_field_types field_type() const { return cached_field_type; } +}; + + +class Item_func_ifnull :public Item_func_coalesce +{ +protected: + bool field_type_defined; +public: + Item_func_ifnull(Item *a, Item *b) :Item_func_coalesce(a,b) {} + double real_op(); + longlong int_op(); + String *str_op(String *str); + my_decimal *decimal_op(my_decimal *); + enum_field_types field_type() const; + void fix_length_and_dec(); + const char *func_name() const { return "ifnull"; } + Field *tmp_table_field(TABLE *table); + uint decimal_precision() const; +}; + + +class Item_func_if :public Item_func +{ + enum Item_result cached_result_type; + enum_field_types cached_field_type; +public: + Item_func_if(Item *a,Item *b,Item *c) + :Item_func(a,b,c), cached_result_type(INT_RESULT) + {} + double val_real(); + longlong val_int(); + String *val_str(String *str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return cached_result_type; } + enum_field_types field_type() const { return cached_field_type; } + bool fix_fields(THD *, Item **); + void fix_length_and_dec(); + uint decimal_precision() const; + const char *func_name() const { return "if"; } +}; + + +class Item_func_nullif :public Item_bool_func2 +{ + enum Item_result cached_result_type; +public: + Item_func_nullif(Item *a,Item *b) + :Item_bool_func2(a,b), cached_result_type(INT_RESULT) + {} + double val_real(); + longlong val_int(); + String *val_str(String *str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return cached_result_type; } + void fix_length_and_dec(); + uint decimal_precision() const { return args[0]->decimal_precision(); } + const char *func_name() const { return "nullif"; } + + virtual inline void print(String *str, enum_query_type query_type) + { + Item_func::print(str, query_type); + } + + table_map not_null_tables() const { return 0; } + bool is_null(); +}; + + +/* Functions to handle the optimized IN */ + + +/* A vector of values of some type */ + +class in_vector :public Sql_alloc +{ +public: + char *base; + uint size; + qsort2_cmp compare; + CHARSET_INFO *collation; + uint count; + uint used_count; + in_vector() {} + in_vector(uint elements,uint element_length,qsort2_cmp cmp_func, + CHARSET_INFO *cmp_coll) + :base((char*) sql_calloc(elements*element_length)), + size(element_length), compare(cmp_func), collation(cmp_coll), + count(elements), used_count(elements) {} + virtual ~in_vector() {} + virtual void set(uint pos,Item *item)=0; + virtual uchar *get_value(Item *item)=0; + void sort() + { + my_qsort2(base,used_count,size,compare,collation); + } + int find(Item *item); + + /* + Create an instance of Item_{type} (e.g. Item_decimal) constant object + which type allows it to hold an element of this vector without any + conversions. + The purpose of this function is to be able to get elements of this + vector in form of Item_xxx constants without creating Item_xxx object + for every array element you get (i.e. this implements "FlyWeight" pattern) + */ + virtual Item* create_item() { return NULL; } + + /* + Store the value at position #pos into provided item object + SYNOPSIS + value_to_item() + pos Index of value to store + item Constant item to store value into. The item must be of the same + type that create_item() returns. + */ + virtual void value_to_item(uint pos, Item *item) { } + + /* Compare values number pos1 and pos2 for equality */ + bool compare_elems(uint pos1, uint pos2) + { + return test(compare(collation, base + pos1*size, base + pos2*size)); + } + virtual Item_result result_type()= 0; +}; + +class in_string :public in_vector +{ + char buff[STRING_BUFFER_USUAL_SIZE]; + String tmp; +public: + in_string(uint elements,qsort2_cmp cmp_func, CHARSET_INFO *cs); + ~in_string(); + void set(uint pos,Item *item); + uchar *get_value(Item *item); + Item* create_item() + { + return new Item_string(collation); + } + void value_to_item(uint pos, Item *item) + { + String *str=((String*) base)+pos; + Item_string *to= (Item_string*)item; + to->str_value= *str; + } + Item_result result_type() { return STRING_RESULT; } +}; + +class in_longlong :public in_vector +{ +protected: + /* + Here we declare a temporary variable (tmp) of the same type as the + elements of this vector. tmp is used in finding if a given value is in + the list. + */ + struct packed_longlong + { + longlong val; + longlong unsigned_flag; // Use longlong, not bool, to preserve alignment + } tmp; +public: + in_longlong(uint elements); + void set(uint pos,Item *item); + uchar *get_value(Item *item); + + Item* create_item() + { + /* + We're created a signed INT, this may not be correct in + general case (see BUG#19342). + */ + return new Item_int((longlong)0); + } + void value_to_item(uint pos, Item *item) + { + ((Item_int*) item)->value= ((packed_longlong*) base)[pos].val; + ((Item_int*) item)->unsigned_flag= (my_bool) + ((packed_longlong*) base)[pos].unsigned_flag; + } + Item_result result_type() { return INT_RESULT; } + + friend int cmp_longlong(void *cmp_arg, packed_longlong *a,packed_longlong *b); +}; + + +/* + Class to represent a vector of constant DATE/DATETIME values. + Values are obtained with help of the get_datetime_value() function. + If the left item is a constant one then its value is cached in the + lval_cache variable. +*/ +class in_datetime :public in_longlong +{ +public: + THD *thd; + /* An item used to issue warnings. */ + Item *warn_item; + /* Cache for the left item. */ + Item *lval_cache; + + in_datetime(Item *warn_item_arg, uint elements) + :in_longlong(elements), thd(current_thd), warn_item(warn_item_arg), + lval_cache(0) {}; + void set(uint pos,Item *item); + uchar *get_value(Item *item); + friend int cmp_longlong(void *cmp_arg, packed_longlong *a,packed_longlong *b); +}; + + +class in_double :public in_vector +{ + double tmp; +public: + in_double(uint elements); + void set(uint pos,Item *item); + uchar *get_value(Item *item); + Item *create_item() + { + return new Item_float(0.0, 0); + } + void value_to_item(uint pos, Item *item) + { + ((Item_float*)item)->value= ((double*) base)[pos]; + } + Item_result result_type() { return REAL_RESULT; } +}; + + +class in_decimal :public in_vector +{ + my_decimal val; +public: + in_decimal(uint elements); + void set(uint pos, Item *item); + uchar *get_value(Item *item); + Item *create_item() + { + return new Item_decimal(0, FALSE); + } + void value_to_item(uint pos, Item *item) + { + my_decimal *dec= ((my_decimal *)base) + pos; + Item_decimal *item_dec= (Item_decimal*)item; + item_dec->set_decimal_value(dec); + } + Item_result result_type() { return DECIMAL_RESULT; } + +}; + + +/* +** Classes for easy comparing of non const items +*/ + +class cmp_item :public Sql_alloc +{ +public: + CHARSET_INFO *cmp_charset; + cmp_item() { cmp_charset= &my_charset_bin; } + virtual ~cmp_item() {} + virtual void store_value(Item *item)= 0; + virtual int cmp(Item *item)= 0; + // for optimized IN with row + virtual int compare(cmp_item *item)= 0; + static cmp_item* get_comparator(Item_result type, CHARSET_INFO *cs); + virtual cmp_item *make_same()= 0; + virtual void store_value_by_template(cmp_item *tmpl, Item *item) + { + store_value(item); + } +}; + +class cmp_item_string :public cmp_item +{ +protected: + String *value_res; +public: + cmp_item_string () {} + cmp_item_string (CHARSET_INFO *cs) { cmp_charset= cs; } + void set_charset(CHARSET_INFO *cs) { cmp_charset= cs; } + friend class cmp_item_sort_string; + friend class cmp_item_sort_string_in_static; +}; + +class cmp_item_sort_string :public cmp_item_string +{ +protected: + char value_buff[STRING_BUFFER_USUAL_SIZE]; + String value; +public: + cmp_item_sort_string(): + cmp_item_string() {} + cmp_item_sort_string(CHARSET_INFO *cs): + cmp_item_string(cs), + value(value_buff, sizeof(value_buff), cs) {} + void store_value(Item *item) + { + value_res= item->val_str(&value); + } + int cmp(Item *arg) + { + char buff[STRING_BUFFER_USUAL_SIZE]; + String tmp(buff, sizeof(buff), cmp_charset), *res; + res= arg->val_str(&tmp); + return (value_res ? (res ? sortcmp(value_res, res, cmp_charset) : 1) : + (res ? -1 : 0)); + } + int compare(cmp_item *ci) + { + cmp_item_string *l_cmp= (cmp_item_string *) ci; + return sortcmp(value_res, l_cmp->value_res, cmp_charset); + } + cmp_item *make_same(); + void set_charset(CHARSET_INFO *cs) + { + cmp_charset= cs; + value.set_quick(value_buff, sizeof(value_buff), cs); + } +}; + +class cmp_item_int :public cmp_item +{ + longlong value; +public: + cmp_item_int() {} /* Remove gcc warning */ + void store_value(Item *item) + { + value= item->val_int(); + } + int cmp(Item *arg) + { + return value != arg->val_int(); + } + int compare(cmp_item *ci) + { + cmp_item_int *l_cmp= (cmp_item_int *)ci; + return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1); + } + cmp_item *make_same(); +}; + +/* + Compare items in the DATETIME context. + Values are obtained with help of the get_datetime_value() function. + If the left item is a constant one then its value is cached in the + lval_cache variable. +*/ +class cmp_item_datetime :public cmp_item +{ + longlong value; +public: + THD *thd; + /* Item used for issuing warnings. */ + Item *warn_item; + /* Cache for the left item. */ + Item *lval_cache; + + cmp_item_datetime(Item *warn_item_arg) + :thd(current_thd), warn_item(warn_item_arg), lval_cache(0) {} + void store_value(Item *item); + int cmp(Item *arg); + int compare(cmp_item *ci); + cmp_item *make_same(); +}; + +class cmp_item_real :public cmp_item +{ + double value; +public: + cmp_item_real() {} /* Remove gcc warning */ + void store_value(Item *item) + { + value= item->val_real(); + } + int cmp(Item *arg) + { + return value != arg->val_real(); + } + int compare(cmp_item *ci) + { + cmp_item_real *l_cmp= (cmp_item_real *) ci; + return (value < l_cmp->value)? -1 : ((value == l_cmp->value) ? 0 : 1); + } + cmp_item *make_same(); +}; + + +class cmp_item_decimal :public cmp_item +{ + my_decimal value; +public: + cmp_item_decimal() {} /* Remove gcc warning */ + void store_value(Item *item); + int cmp(Item *arg); + int compare(cmp_item *c); + cmp_item *make_same(); +}; + + +/* + cmp_item for optimized IN with row (right part string, which never + be changed) +*/ + +class cmp_item_sort_string_in_static :public cmp_item_string +{ + protected: + String value; +public: + cmp_item_sort_string_in_static(CHARSET_INFO *cs): + cmp_item_string(cs) {} + void store_value(Item *item) + { + value_res= item->val_str(&value); + } + int cmp(Item *item) + { + // Should never be called + DBUG_ASSERT(0); + return 1; + } + int compare(cmp_item *ci) + { + cmp_item_string *l_cmp= (cmp_item_string *) ci; + return sortcmp(value_res, l_cmp->value_res, cmp_charset); + } + cmp_item *make_same() + { + return new cmp_item_sort_string_in_static(cmp_charset); + } +}; + + +/* + The class Item_func_case is the CASE ... WHEN ... THEN ... END function + implementation. + + When there is no expression between CASE and the first WHEN + (the CASE expression) then this function simple checks all WHEN expressions + one after another. When some WHEN expression evaluated to TRUE then the + value of the corresponding THEN expression is returned. + + When the CASE expression is specified then it is compared to each WHEN + expression individually. When an equal WHEN expression is found + corresponding THEN expression is returned. + In order to do correct comparisons several comparators are used. One for + each result type. Different result types that are used in particular + CASE ... END expression are collected in the fix_length_and_dec() member + function and only comparators for there result types are used. +*/ + +class Item_func_case :public Item_func +{ + enum Item_result cached_result_type, left_result_type; + String tmp_value; + uint ncases; + Item_result cmp_type; + DTCollation cmp_collation; + enum_field_types cached_field_type; + cmp_item *cmp_items[5]; /* For all result types */ + cmp_item *case_item; +public: + Item_func_case(List &list, Item *first_expr_arg, Item *else_expr_arg) + :Item_func(), + cached_result_type(INT_RESULT), left_result_type(INT_RESULT), case_item(0), + first_expr_num(-1), else_expr_num(-1) //@InfiniDB + { + ncases= list.elements; + if (first_expr_arg) + { + first_expr_num= list.elements; + list.push_back(first_expr_arg); + } + if (else_expr_arg) + { + else_expr_num= list.elements; + list.push_back(else_expr_arg); + } + set_arguments(list); + bzero(&cmp_items, sizeof(cmp_items)); + } + double val_real(); + longlong val_int(); + String *val_str(String *); + my_decimal *val_decimal(my_decimal *); + bool fix_fields(THD *thd, Item **ref); + void fix_length_and_dec(); + uint decimal_precision() const; + table_map not_null_tables() const { return 0; } + enum Item_result result_type () const { return cached_result_type; } + enum_field_types field_type() const { return cached_field_type; } + const char *func_name() const { return "case"; } + virtual void print(String *str, enum_query_type query_type); + Item *find_item(String *str); + CHARSET_INFO *compare_collation() { return cmp_collation.collation; } + void cleanup(); + void agg_str_lengths(Item *arg); + void agg_num_lengths(Item *arg); + // @InfiniDB. Moved this to public place + int first_expr_num, else_expr_num; +}; + +/* + The Item_func_in class implements the in_expr IN(values_list) function. + + The current implementation distinguishes 2 cases: + 1) all items in the value_list are constants and have the same + result type. This case is handled by in_vector class. + 2) items in the value_list have different result types or there is some + non-constant items. + In this case Item_func_in employs several cmp_item objects to performs + comparisons of in_expr and an item from the values_list. One cmp_item + object for each result type. Different result types are collected in the + fix_length_and_dec() member function by means of collect_cmp_types() + function. +*/ +class Item_func_in :public Item_func_opt_neg +{ +public: + /* + an array of values when the right hand arguments of IN + are all SQL constant and there are no nulls + */ + in_vector *array; + bool have_null; + /* + true when all arguments of the IN clause are of compatible types + and can be used safely as comparisons for key conditions + */ + bool arg_types_compatible; + Item_result left_result_type; + cmp_item *cmp_items[6]; /* One cmp_item for each result type */ + DTCollation cmp_collation; + + Item_func_in(List &list) + :Item_func_opt_neg(list), array(0), have_null(0), + arg_types_compatible(FALSE) + { + bzero(&cmp_items, sizeof(cmp_items)); + allowed_arg_cols= 0; // Fetch this value from first argument + } + longlong val_int(); + bool fix_fields(THD *, Item **); + void fix_length_and_dec(); + uint decimal_precision() const { return 1; } + void cleanup() + { + uint i; + DBUG_ENTER("Item_func_in::cleanup"); + Item_int_func::cleanup(); + delete array; + array= 0; + for (i= 0; i <= (uint)DECIMAL_RESULT + 1; i++) + { + delete cmp_items[i]; + cmp_items[i]= 0; + } + DBUG_VOID_RETURN; + } + optimize_type select_optimize() const + { return OPTIMIZE_KEY; } + virtual void print(String *str, enum_query_type query_type); + enum Functype functype() const { return IN_FUNC; } + const char *func_name() const { return " IN "; } + bool nulls_in_row(); + bool is_bool_func() { return 1; } + CHARSET_INFO *compare_collation() { return cmp_collation.collation; } +}; + +class cmp_item_row :public cmp_item +{ + cmp_item **comparators; + uint n; +public: + cmp_item_row(): comparators(0), n(0) {} + ~cmp_item_row(); + void store_value(Item *item); + inline void alloc_comparators(); + int cmp(Item *arg); + int compare(cmp_item *arg); + cmp_item *make_same(); + void store_value_by_template(cmp_item *tmpl, Item *); + friend void Item_func_in::fix_length_and_dec(); +}; + + +class in_row :public in_vector +{ + cmp_item_row tmp; +public: + in_row(uint elements, Item *); + ~in_row(); + void set(uint pos,Item *item); + uchar *get_value(Item *item); + friend void Item_func_in::fix_length_and_dec(); + Item_result result_type() { return ROW_RESULT; } +}; + +/* Functions used by where clause */ + +class Item_func_isnull :public Item_bool_func +{ +protected: + longlong cached_value; +public: + Item_func_isnull(Item *a) :Item_bool_func(a) {} + longlong val_int(); + enum Functype functype() const { return ISNULL_FUNC; } + void fix_length_and_dec() + { + decimals=0; max_length=1; maybe_null=0; + update_used_tables(); + } + const char *func_name() const { return "isnull"; } + /* Optimize case of not_null_column IS NULL */ + virtual void update_used_tables() + { + if (!args[0]->maybe_null) + { + used_tables_cache= 0; /* is always false */ + const_item_cache= 1; + cached_value= (longlong) 0; + } + else + { + args[0]->update_used_tables(); + if ((const_item_cache= !(used_tables_cache= args[0]->used_tables())) && + !with_subselect) + { + /* Remember if the value is always NULL or never NULL */ + cached_value= (longlong) args[0]->is_null(); + } + } + } + table_map not_null_tables() const { return 0; } + optimize_type select_optimize() const { return OPTIMIZE_NULL; } + Item *neg_transformer(THD *thd); + CHARSET_INFO *compare_collation() { return args[0]->collation.collation; } +}; + +/* Functions used by HAVING for rewriting IN subquery */ + +class Item_in_subselect; + +/* + This is like IS NOT NULL but it also remembers if it ever has + encountered a NULL. +*/ +class Item_is_not_null_test :public Item_func_isnull +{ + Item_in_subselect* owner; +public: + Item_is_not_null_test(Item_in_subselect* ow, Item *a) + :Item_func_isnull(a), owner(ow) + {} + enum Functype functype() const { return ISNOTNULLTEST_FUNC; } + longlong val_int(); + const char *func_name() const { return ""; } + void update_used_tables(); + /* + we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE + */ + table_map used_tables() const + { return used_tables_cache | RAND_TABLE_BIT; } +}; + + +class Item_func_isnotnull :public Item_bool_func +{ + bool abort_on_null; +public: + Item_func_isnotnull(Item *a) :Item_bool_func(a), abort_on_null(0) {} + longlong val_int(); + enum Functype functype() const { return ISNOTNULL_FUNC; } + void fix_length_and_dec() + { + decimals=0; max_length=1; maybe_null=0; + } + const char *func_name() const { return "isnotnull"; } + optimize_type select_optimize() const { return OPTIMIZE_NULL; } + table_map not_null_tables() const + { return abort_on_null ? not_null_tables_cache : 0; } + Item *neg_transformer(THD *thd); + virtual void print(String *str, enum_query_type query_type); + CHARSET_INFO *compare_collation() { return args[0]->collation.collation; } + void top_level_item() { abort_on_null=1; } +}; + + +class Item_func_like :public Item_bool_func2 +{ + // Turbo Boyer-Moore data + bool canDoTurboBM; // pattern is '%abcd%' case + const char* pattern; + int pattern_len; + + // TurboBM buffers, *this is owner + int* bmGs; // good suffix shift table, size is pattern_len + 1 + int* bmBc; // bad character shift table, size is alphabet_size + + void turboBM_compute_suffixes(int* suff); + void turboBM_compute_good_suffix_shifts(int* suff); + void turboBM_compute_bad_character_shifts(); + bool turboBM_matches(const char* text, int text_len) const; + enum { alphabet_size = 256 }; + + Item *escape_item; + + bool escape_used_in_parsing; + +public: + int escape; + + Item_func_like(Item *a,Item *b, Item *escape_arg, bool escape_used) + :Item_bool_func2(a,b), canDoTurboBM(FALSE), pattern(0), pattern_len(0), + bmGs(0), bmBc(0), escape_item(escape_arg), + escape_used_in_parsing(escape_used) {} + longlong val_int(); + enum Functype functype() const { return LIKE_FUNC; } + optimize_type select_optimize() const; + cond_result eq_cmp_result() const { return COND_TRUE; } + const char *func_name() const { return "like"; } + bool fix_fields(THD *thd, Item **ref); + void cleanup(); +}; + +#ifdef USE_REGEX + +#include "my_regex.h" + +class Item_func_regex :public Item_bool_func +{ + my_regex_t preg; + bool regex_compiled; + bool regex_is_const; + String prev_regexp; + DTCollation cmp_collation; + CHARSET_INFO *regex_lib_charset; + int regex_lib_flags; + String conv; + int regcomp(bool send_error); +public: + Item_func_regex(Item *a,Item *b) :Item_bool_func(a,b), + regex_compiled(0),regex_is_const(0) {} + void cleanup(); + longlong val_int(); + bool fix_fields(THD *thd, Item **ref); + const char *func_name() const { return "regexp"; } + + virtual inline void print(String *str, enum_query_type query_type) + { + print_op(str, query_type); + } + + CHARSET_INFO *compare_collation() { return cmp_collation.collation; } +}; + +#else + +class Item_func_regex :public Item_bool_func +{ +public: + Item_func_regex(Item *a,Item *b) :Item_bool_func(a,b) {} + longlong val_int() { return 0;} + const char *func_name() const { return "regex"; } + + virtual inline void print(String *str, enum_query_type query_type) + { + print_op(str, query_type); + } +}; + +#endif /* USE_REGEX */ + + +typedef class Item COND; + +class Item_cond :public Item_bool_func +{ +protected: + List list; + bool abort_on_null; + table_map and_tables_cache; + +public: + /* Item_cond() is only used to create top level items */ + Item_cond(): Item_bool_func(), abort_on_null(1) + { const_item_cache=0; } + Item_cond(Item *i1,Item *i2) + :Item_bool_func(), abort_on_null(0) + { + list.push_back(i1); + list.push_back(i2); + } + Item_cond(THD *thd, Item_cond *item); + Item_cond(List &nlist) + :Item_bool_func(), list(nlist), abort_on_null(0) {} + bool add(Item *item) { return list.push_back(item); } + bool add_at_head(Item *item) { return list.push_front(item); } + void add_at_head(List *nlist) { list.prepand(nlist); } + bool fix_fields(THD *, Item **ref); + + enum Type type() const { return COND_ITEM; } + List* argument_list() { return &list; } + table_map used_tables() const; + void update_used_tables(); + virtual void print(String *str, enum_query_type query_type); + void split_sum_func(THD *thd, Item **ref_pointer_array, List &fields); + friend int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves, + COND **conds); + void top_level_item() { abort_on_null=1; } + void copy_andor_arguments(THD *thd, Item_cond *item); + bool walk(Item_processor processor, bool walk_subquery, uchar *arg); + Item *transform(Item_transformer transformer, uchar *arg); + void traverse_cond(Cond_traverser, void *arg, traverse_order order); + void neg_arguments(THD *thd); + enum_field_types field_type() const { return MYSQL_TYPE_LONGLONG; } + bool subst_argument_checker(uchar **arg) { return TRUE; } + Item *compile(Item_analyzer analyzer, uchar **arg_p, + Item_transformer transformer, uchar *arg_t); +}; + + +/* + The class Item_equal is used to represent conjunctions of equality + predicates of the form field1 = field2, and field=const in where + conditions and on expressions. + + All equality predicates of the form field1=field2 contained in a + conjunction are substituted for a sequence of items of this class. + An item of this class Item_equal(f1,f2,...fk) represents a + multiple equality f1=f2=...=fk. + + If a conjunction contains predicates f1=f2 and f2=f3, a new item of + this class is created Item_equal(f1,f2,f3) representing the multiple + equality f1=f2=f3 that substitutes the above equality predicates in + the conjunction. + A conjunction of the predicates f2=f1 and f3=f1 and f3=f2 will be + substituted for the item representing the same multiple equality + f1=f2=f3. + An item Item_equal(f1,f2) can appear instead of a conjunction of + f2=f1 and f1=f2, or instead of just the predicate f1=f2. + + An item of the class Item_equal inherits equalities from outer + conjunctive levels. + + Suppose we have a where condition of the following form: + WHERE f1=f2 AND f3=f4 AND f3=f5 AND ... AND (...OR (f1=f3 AND ...)). + In this case: + f1=f2 will be substituted for Item_equal(f1,f2); + f3=f4 and f3=f5 will be substituted for Item_equal(f3,f4,f5); + f1=f3 will be substituted for Item_equal(f1,f2,f3,f4,f5); + + An object of the class Item_equal can contain an optional constant + item c. Then it represents a multiple equality of the form + c=f1=...=fk. + + Objects of the class Item_equal are used for the following: + + 1. An object Item_equal(t1.f1,...,tk.fk) allows us to consider any + pair of tables ti and tj as joined by an equi-condition. + Thus it provide us with additional access paths from table to table. + + 2. An object Item_equal(t1.f1,...,tk.fk) is applied to deduce new + SARGable predicates: + f1=...=fk AND P(fi) => f1=...=fk AND P(fi) AND P(fj). + It also can give us additional index scans and can allow us to + improve selectivity estimates. + + 3. An object Item_equal(t1.f1,...,tk.fk) is used to optimize the + selected execution plan for the query: if table ti is accessed + before the table tj then in any predicate P in the where condition + the occurrence of tj.fj is substituted for ti.fi. This can allow + an evaluation of the predicate at an earlier step. + + When feature 1 is supported they say that join transitive closure + is employed. + When feature 2 is supported they say that search argument transitive + closure is employed. + Both features are usually supported by preprocessing original query and + adding additional predicates. + We do not just add predicates, we rather dynamically replace some + predicates that can not be used to access tables in the investigated + plan for those, obtained by substitution of some fields for equal fields, + that can be used. + + Prepared Statements/Stored Procedures note: instances of class + Item_equal are created only at the time a PS/SP is executed and + are deleted in the end of execution. All changes made to these + objects need not be registered in the list of changes of the parse + tree and do not harm PS/SP re-execution. + + Item equal objects are employed only at the optimize phase. Usually they are + not supposed to be evaluated. Yet in some cases we call the method val_int() + for them. We have to take care of restricting the predicate such an + object represents f1=f2= ...=fn to the projection of known fields fi1=...=fik. +*/ + +class Item_equal: public Item_bool_func +{ + List fields; /* list of equal field items */ + Item *const_item; /* optional constant item equal to fields items */ + cmp_item *eval_item; + bool cond_false; +public: + inline Item_equal() + : Item_bool_func(), const_item(0), eval_item(0), cond_false(0) + { const_item_cache=0 ;} + Item_equal(Item_field *f1, Item_field *f2); + Item_equal(Item *c, Item_field *f); + Item_equal(Item_equal *item_equal); + inline Item* get_const() { return const_item; } + void add(Item *c); + void add(Item_field *f); + uint members(); + bool contains(Field *field); + Item_field* get_first() { return fields.head(); } + void merge(Item_equal *item); + void update_const(); + enum Functype functype() const { return MULT_EQUAL_FUNC; } + longlong val_int(); + const char *func_name() const { return "multiple equal"; } + optimize_type select_optimize() const { return OPTIMIZE_EQUAL; } + void sort(Item_field_cmpfunc cmp, void *arg); + friend class Item_equal_iterator; + void fix_length_and_dec(); + bool fix_fields(THD *thd, Item **ref); + void update_used_tables(); + bool walk(Item_processor processor, bool walk_subquery, uchar *arg); + Item *transform(Item_transformer transformer, uchar *arg); + virtual void print(String *str, enum_query_type query_type); + CHARSET_INFO *compare_collation() + { return fields.head()->collation.collation; } +}; + +class COND_EQUAL: public Sql_alloc +{ +public: + uint max_members; /* max number of members the current level + list and all lower level lists */ + COND_EQUAL *upper_levels; /* multiple equalities of upper and levels */ + List current_level; /* list of multiple equalities of + the current and level */ + COND_EQUAL() + { + upper_levels= 0; + } +}; + + +class Item_equal_iterator : public List_iterator_fast +{ +public: + inline Item_equal_iterator(Item_equal &item_equal) + :List_iterator_fast (item_equal.fields) + {} + inline Item_field* operator++(int) + { + Item_field *item= (*(List_iterator_fast *) this)++; + return item; + } + inline void rewind(void) + { + List_iterator_fast::rewind(); + } +}; + +class Item_cond_and :public Item_cond +{ +public: + COND_EQUAL cond_equal; /* contains list of Item_equal objects for + the current and level and reference + to multiple equalities of upper and levels */ + Item_cond_and() :Item_cond() {} + Item_cond_and(Item *i1,Item *i2) :Item_cond(i1,i2) {} + Item_cond_and(THD *thd, Item_cond_and *item) :Item_cond(thd, item) {} + Item_cond_and(List &list_arg): Item_cond(list_arg) {} + enum Functype functype() const { return COND_AND_FUNC; } + longlong val_int(); + const char *func_name() const { return "and"; } + table_map not_null_tables() const + { return abort_on_null ? not_null_tables_cache: and_tables_cache; } + Item* copy_andor_structure(THD *thd) + { + Item_cond_and *item; + if ((item= new Item_cond_and(thd, this))) + item->copy_andor_arguments(thd, this); + return item; + } + Item *neg_transformer(THD *thd); +}; + +inline bool is_cond_and(Item *item) +{ + if (item->type() != Item::COND_ITEM) + return FALSE; + + Item_cond *cond_item= (Item_cond*) item; + return (cond_item->functype() == Item_func::COND_AND_FUNC); +} + +class Item_cond_or :public Item_cond +{ +public: + Item_cond_or() :Item_cond() {} + Item_cond_or(Item *i1,Item *i2) :Item_cond(i1,i2) {} + Item_cond_or(THD *thd, Item_cond_or *item) :Item_cond(thd, item) {} + Item_cond_or(List &list_arg): Item_cond(list_arg) {} + enum Functype functype() const { return COND_OR_FUNC; } + longlong val_int(); + const char *func_name() const { return "or"; } + table_map not_null_tables() const { return and_tables_cache; } + Item* copy_andor_structure(THD *thd) + { + Item_cond_or *item; + if ((item= new Item_cond_or(thd, this))) + item->copy_andor_arguments(thd, this); + return item; + } + Item *neg_transformer(THD *thd); +}; + +inline bool is_cond_or(Item *item) +{ + if (item->type() != Item::COND_ITEM) + return FALSE; + + Item_cond *cond_item= (Item_cond*) item; + return (cond_item->functype() == Item_func::COND_OR_FUNC); +} + +/* + XOR is Item_cond, not an Item_int_func because we could like to + optimize (a XOR b) later on. It's low prio, though +*/ + +class Item_cond_xor :public Item_cond +{ +public: + Item_cond_xor() :Item_cond() {} + Item_cond_xor(Item *i1,Item *i2) :Item_cond(i1,i2) {} + enum Functype functype() const { return COND_XOR_FUNC; } + /* TODO: remove the next line when implementing XOR optimization */ + //enum Type type() const { return FUNC_ITEM; } // @InfiniDB treat as COND_ITEM + longlong val_int(); + const char *func_name() const { return "xor"; } + void top_level_item() {} +}; + + +/* Some useful inline functions */ + +inline Item *and_conds(Item *a, Item *b) +{ + if (!b) return a; + if (!a) return b; + return new Item_cond_and(a, b); +} + +Item *and_expressions(Item *a, Item *b, Item **org_item); diff --git a/dbcon/mysql/item_func.cc b/dbcon/mysql/item_func.cc new file mode 100644 index 00000000..0e48b7ed --- /dev/null +++ b/dbcon/mysql/item_func.cc @@ -0,0 +1,6194 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/** + @file + + @brief + This file defines all numerical functions +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include "slave.h" // for wait_for_master_pos +#include "rpl_mi.h" +#include +#include +#include +#include +#include + +#include "sp_head.h" +#include "sp_rcontext.h" +#include "sp.h" + +#ifdef NO_EMBEDDED_ACCESS_CHECKS +#define sp_restore_security_context(A,B) while (0) {} +#endif + +bool check_reserved_words(LEX_STRING *name) +{ + if (!my_strcasecmp(system_charset_info, name->str, "GLOBAL") || + !my_strcasecmp(system_charset_info, name->str, "LOCAL") || + !my_strcasecmp(system_charset_info, name->str, "SESSION")) + return TRUE; + return FALSE; +} + + +/** + @return + TRUE if item is a constant +*/ + +bool +eval_const_cond(COND *cond) +{ + return ((Item_func*) cond)->val_int() ? TRUE : FALSE; +} + + +void Item_func::set_arguments(List &list) +{ + allowed_arg_cols= 1; + arg_count=list.elements; + args= tmp_arg; // If 2 arguments + if (arg_count <= 2 || (args=(Item**) sql_alloc(sizeof(Item*)*arg_count))) + { + List_iterator_fast li(list); + Item *item; + Item **save_args= args; + + while ((item=li++)) + { + *(save_args++)= item; + with_sum_func|=item->with_sum_func; + } + } + list.empty(); // Fields are used +} + +Item_func::Item_func(List &list) + :allowed_arg_cols(1) +{ + set_arguments(list); +} + +Item_func::Item_func(THD *thd, Item_func *item) + :Item_result_field(thd, item), + allowed_arg_cols(item->allowed_arg_cols), + arg_count(item->arg_count), + used_tables_cache(item->used_tables_cache), + not_null_tables_cache(item->not_null_tables_cache), + const_item_cache(item->const_item_cache) +{ + fThd = thd; + if (arg_count) + { + if (arg_count <=2) + args= tmp_arg; + else + { + if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count))) + return; + } + memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count); + } +} + + +/* + Resolve references to table column for a function and its argument + + SYNOPSIS: + fix_fields() + thd Thread object + ref Pointer to where this object is used. This reference + is used if we want to replace this object with another + one (for example in the summary functions). + + DESCRIPTION + Call fix_fields() for all arguments to the function. The main intention + is to allow all Item_field() objects to setup pointers to the table fields. + + Sets as a side effect the following class variables: + maybe_null Set if any argument may return NULL + with_sum_func Set if any of the arguments contains a sum function + used_tables_cache Set to union of the tables used by arguments + + str_value.charset If this is a string function, set this to the + character set for the first argument. + If any argument is binary, this is set to binary + + If for any item any of the defaults are wrong, then this can + be fixed in the fix_length_and_dec() function that is called + after this one or by writing a specialized fix_fields() for the + item. + + RETURN VALUES + FALSE ok + TRUE Got error. Stored with my_error(). +*/ + +bool +Item_func::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + //@InfiniDB. Assign new protected field thd for some functions use. + fThd = thd; + Item **arg,**arg_end; +#ifndef EMBEDDED_LIBRARY // Avoid compiler warning + uchar buff[STACK_BUFF_ALLOC]; // Max argument in function +#endif + + used_tables_cache= not_null_tables_cache= 0; + const_item_cache=1; + + if (check_stack_overrun(thd, STACK_MIN_SIZE, buff)) + return TRUE; // Fatal error if flag is set! + if (arg_count) + { // Print purify happy + for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++) + { + Item *item; + /* + We can't yet set item to *arg as fix_fields may change *arg + We shouldn't call fix_fields() twice, so check 'fixed' field first + */ + if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg))) + return TRUE; /* purecov: inspected */ + item= *arg; + + if (allowed_arg_cols) + { + if (item->check_cols(allowed_arg_cols)) + return 1; + } + else + { + /* we have to fetch allowed_arg_cols from first argument */ + DBUG_ASSERT(arg == args); // it is first argument + allowed_arg_cols= item->cols(); + DBUG_ASSERT(allowed_arg_cols); // Can't be 0 any more + } + + if (item->maybe_null) + maybe_null=1; + + with_sum_func= with_sum_func || item->with_sum_func; + used_tables_cache|= item->used_tables(); + not_null_tables_cache|= item->not_null_tables(); + const_item_cache&= item->const_item(); + with_subselect|= item->with_subselect; + } + } + fix_length_and_dec(); + if (thd->is_error()) // An error inside fix_length_and_dec occured + return TRUE; + fixed= 1; + return FALSE; +} + + +bool Item_func::walk(Item_processor processor, bool walk_subquery, + uchar *argument) +{ + if (arg_count) + { + Item **arg,**arg_end; + for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) + { + if ((*arg)->walk(processor, walk_subquery, argument)) + return 1; + } + } + return (this->*processor)(argument); +} + +void Item_func::traverse_cond(Cond_traverser traverser, + void *argument, traverse_order order) +{ + if (arg_count) + { + Item **arg,**arg_end; + + switch (order) { + case(PREFIX): + (*traverser)(this, argument); + for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) + { + (*arg)->traverse_cond(traverser, argument, order); + } + break; + case (POSTFIX): + for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) + { + (*arg)->traverse_cond(traverser, argument, order); + } + (*traverser)(this, argument); + } + } + else + (*traverser)(this, argument); +} + + +/** + Transform an Item_func object with a transformer callback function. + + The function recursively applies the transform method to each + argument of the Item_func node. + If the call of the method for an argument item returns a new item + the old item is substituted for a new one. + After this the transformer is applied to the root node + of the Item_func object. + @param transformer the transformer callback function to be applied to + the nodes of the tree of the object + @param argument parameter to be passed to the transformer + + @return + Item returned as the result of transformation of the root node +*/ + +Item *Item_func::transform(Item_transformer transformer, uchar *argument) +{ + DBUG_ASSERT(!current_thd->is_stmt_prepare()); + + if (arg_count) + { + Item **arg,**arg_end; + for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) + { + Item *new_item= (*arg)->transform(transformer, argument); + if (!new_item) + return 0; + + /* + THD::change_item_tree() should be called only if the tree was + really transformed, i.e. when a new item has been created. + Otherwise we'll be allocating a lot of unnecessary memory for + change records at each execution. + */ + if (*arg != new_item) + current_thd->change_item_tree(arg, new_item); + } + } + return (this->*transformer)(argument); +} + + +/** + Compile Item_func object with a processor and a transformer + callback functions. + + First the function applies the analyzer to the root node of + the Item_func object. Then if the analizer succeeeds (returns TRUE) + the function recursively applies the compile method to each argument + of the Item_func node. + If the call of the method for an argument item returns a new item + the old item is substituted for a new one. + After this the transformer is applied to the root node + of the Item_func object. + + @param analyzer the analyzer callback function to be applied to the + nodes of the tree of the object + @param[in,out] arg_p parameter to be passed to the processor + @param transformer the transformer callback function to be applied to the + nodes of the tree of the object + @param arg_t parameter to be passed to the transformer + + @return + Item returned as the result of transformation of the root node +*/ + +Item *Item_func::compile(Item_analyzer analyzer, uchar **arg_p, + Item_transformer transformer, uchar *arg_t) +{ + if (!(this->*analyzer)(arg_p)) + return 0; + if (arg_count) + { + Item **arg,**arg_end; + for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) + { + /* + The same parameter value of arg_p must be passed + to analyze any argument of the condition formula. + */ + uchar *arg_v= *arg_p; + Item *new_item= (*arg)->compile(analyzer, &arg_v, transformer, arg_t); + if (new_item && *arg != new_item) + current_thd->change_item_tree(arg, new_item); + } + } + return (this->*transformer)(arg_t); +} + +/** + See comments in Item_cmp_func::split_sum_func() +*/ + +void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array, + List &fields) +{ + Item **arg, **arg_end; + for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++) + (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg, TRUE); +} + + +void Item_func::update_used_tables() +{ + used_tables_cache=0; + const_item_cache=1; + for (uint i=0 ; i < arg_count ; i++) + { + args[i]->update_used_tables(); + used_tables_cache|=args[i]->used_tables(); + const_item_cache&=args[i]->const_item(); + } +} + + +table_map Item_func::used_tables() const +{ + return used_tables_cache; +} + + +table_map Item_func::not_null_tables() const +{ + return not_null_tables_cache; +} + + +void Item_func::print(String *str, enum_query_type query_type) +{ + str->append(func_name()); + str->append('('); + print_args(str, 0, query_type); + str->append(')'); +} + + +void Item_func::print_args(String *str, uint from, enum_query_type query_type) +{ + for (uint i=from ; i < arg_count ; i++) + { + if (i != from) + str->append(','); + args[i]->print(str, query_type); + } +} + + +void Item_func::print_op(String *str, enum_query_type query_type) +{ + str->append('('); + for (uint i=0 ; i < arg_count-1 ; i++) + { + args[i]->print(str, query_type); + str->append(' '); + str->append(func_name()); + str->append(' '); + } + args[arg_count-1]->print(str, query_type); + str->append(')'); +} + + +bool Item_func::eq(const Item *item, bool binary_cmp) const +{ + /* Assume we don't have rtti */ + if (this == item) + return 1; + if (item->type() != FUNC_ITEM) + return 0; + Item_func *item_func=(Item_func*) item; + Item_func::Functype func_type; + if ((func_type= functype()) != item_func->functype() || + arg_count != item_func->arg_count || + (func_type != Item_func::FUNC_SP && + func_name() != item_func->func_name()) || + (func_type == Item_func::FUNC_SP && + my_strcasecmp(system_charset_info, func_name(), item_func->func_name()))) + return 0; + for (uint i=0; i < arg_count ; i++) + if (!args[i]->eq(item_func->args[i], binary_cmp)) + return 0; + return 1; +} + + +Field *Item_func::tmp_table_field(TABLE *table) +{ + Field *field; + LINT_INIT(field); + + switch (result_type()) { + case INT_RESULT: + if (max_length > MY_INT32_NUM_DECIMAL_DIGITS) + field= new Field_longlong(max_length, maybe_null, name, unsigned_flag); + else + field= new Field_long(max_length, maybe_null, name, unsigned_flag); + break; + case REAL_RESULT: + field= new Field_double(max_length, maybe_null, name, decimals); + break; + case STRING_RESULT: + return make_string_field(table); + break; + case DECIMAL_RESULT: + field= Field_new_decimal::new_decimal_field(this); + break; + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + field= 0; + break; + } + if (field) + field->init(table); + return field; +} + + +bool Item_func::is_expensive_processor(uchar *arg) +{ + return is_expensive(); +} + + +my_decimal *Item_func::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed); + int2my_decimal(E_DEC_FATAL_ERROR, val_int(), unsigned_flag, decimal_value); + return decimal_value; +} + + +String *Item_real_func::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + double nr= val_real(); + if (null_value) + return 0; /* purecov: inspected */ + str->set_real(nr,decimals, &my_charset_bin); + return str; +} + + +my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed); + double nr= val_real(); + if (null_value) + return 0; /* purecov: inspected */ + double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value); + return decimal_value; +} + + +void Item_func::fix_num_length_and_dec() +{ + uint fl_length= 0; + decimals=0; + for (uint i=0 ; i < arg_count ; i++) + { + set_if_bigger(decimals,args[i]->decimals); + set_if_bigger(fl_length, args[i]->max_length); + } + max_length=float_length(decimals); + if (fl_length > max_length) + { + decimals= NOT_FIXED_DEC; + max_length= float_length(NOT_FIXED_DEC); + } +} + + +void Item_func_numhybrid::fix_num_length_and_dec() +{} + + +/** + Set max_length/decimals of function if function is fixed point and + result length/precision depends on argument ones. +*/ + +void Item_func::count_decimal_length() +{ + int max_int_part= 0; + decimals= 0; + unsigned_flag= 1; + for (uint i=0 ; i < arg_count ; i++) + { + set_if_bigger(decimals, args[i]->decimals); + set_if_bigger(max_int_part, args[i]->decimal_int_part()); + set_if_smaller(unsigned_flag, args[i]->unsigned_flag); + } + int precision= min(max_int_part + decimals, DECIMAL_MAX_PRECISION); + max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, + unsigned_flag); +} + + +/** + Set max_length of if it is maximum length of its arguments. +*/ + +void Item_func::count_only_length() +{ + max_length= 0; + unsigned_flag= 0; + for (uint i=0 ; i < arg_count ; i++) + { + set_if_bigger(max_length, args[i]->max_length); + set_if_bigger(unsigned_flag, args[i]->unsigned_flag); + } +} + + +/** + Set max_length/decimals of function if function is floating point and + result length/precision depends on argument ones. +*/ + +void Item_func::count_real_length() +{ + uint32 length= 0; + decimals= 0; + max_length= 0; + for (uint i=0 ; i < arg_count ; i++) + { + if (decimals != NOT_FIXED_DEC) + { + set_if_bigger(decimals, args[i]->decimals); + set_if_bigger(length, (args[i]->max_length - args[i]->decimals)); + } + set_if_bigger(max_length, args[i]->max_length); + } + if (decimals != NOT_FIXED_DEC) + { + max_length= length; + length+= decimals; + if (length < max_length) // If previous operation gave overflow + max_length= UINT_MAX32; + else + max_length= length; + } +} + + + +void Item_func::signal_divide_by_null() +{ + THD *thd= current_thd; + if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DIVISION_BY_ZERO, + ER(ER_DIVISION_BY_ZERO)); + null_value= 1; +} + + +Item *Item_func::get_tmp_table_item(THD *thd) +{ + if (!with_sum_func && !const_item() && functype() != SUSERVAR_FUNC) + return new Item_field(result_field); + return copy_or_same(thd); +} + +double Item_int_func::val_real() +{ + DBUG_ASSERT(fixed == 1); + + return unsigned_flag ? (double) ((ulonglong) val_int()) : (double) val_int(); +} + + +String *Item_int_func::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + longlong nr=val_int(); + if (null_value) + return 0; + str->set_int(nr, unsigned_flag, &my_charset_bin); + return str; +} + + +void Item_func_connection_id::fix_length_and_dec() +{ + Item_int_func::fix_length_and_dec(); + max_length= 10; +} + + +bool Item_func_connection_id::fix_fields(THD *thd, Item **ref) +{ + if (Item_int_func::fix_fields(thd, ref)) + return TRUE; + thd->thread_specific_used= TRUE; + value= thd->variables.pseudo_thread_id; + return FALSE; +} + + +/** + Check arguments here to determine result's type for a numeric + function of two arguments. +*/ + +void Item_num_op::find_num_type(void) +{ + DBUG_ENTER("Item_num_op::find_num_type"); + DBUG_PRINT("info", ("name %s", func_name())); + DBUG_ASSERT(arg_count == 2); + Item_result r0= args[0]->result_type(); + Item_result r1= args[1]->result_type(); + + if (r0 == REAL_RESULT || r1 == REAL_RESULT || + r0 == STRING_RESULT || r1 ==STRING_RESULT) + { + count_real_length(); + max_length= float_length(decimals); + hybrid_type= REAL_RESULT; + } + else if (r0 == DECIMAL_RESULT || r1 == DECIMAL_RESULT) + { + hybrid_type= DECIMAL_RESULT; + result_precision(); + } + else + { + DBUG_ASSERT(r0 == INT_RESULT && r1 == INT_RESULT); + decimals= 0; + hybrid_type=INT_RESULT; + result_precision(); + } + DBUG_PRINT("info", ("Type: %s", + (hybrid_type == REAL_RESULT ? "REAL_RESULT" : + hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : + hybrid_type == INT_RESULT ? "INT_RESULT" : + "--ILLEGAL!!!--"))); + DBUG_VOID_RETURN; +} + + +/** + Set result type for a numeric function of one argument + (can be also used by a numeric function of many arguments, if the result + type depends only on the first argument) +*/ + +void Item_func_num1::find_num_type() +{ + DBUG_ENTER("Item_func_num1::find_num_type"); + DBUG_PRINT("info", ("name %s", func_name())); + switch (hybrid_type= args[0]->result_type()) { + case INT_RESULT: + unsigned_flag= args[0]->unsigned_flag; + break; + case STRING_RESULT: + case REAL_RESULT: + hybrid_type= REAL_RESULT; + max_length= float_length(decimals); + break; + case DECIMAL_RESULT: + break; + default: + DBUG_ASSERT(0); + } + DBUG_PRINT("info", ("Type: %s", + (hybrid_type == REAL_RESULT ? "REAL_RESULT" : + hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : + hybrid_type == INT_RESULT ? "INT_RESULT" : + "--ILLEGAL!!!--"))); + DBUG_VOID_RETURN; +} + + +void Item_func_num1::fix_num_length_and_dec() +{ + decimals= args[0]->decimals; + max_length= args[0]->max_length; +} + + +void Item_func_numhybrid::fix_length_and_dec() +{ + fix_num_length_and_dec(); + find_num_type(); +} + + +String *Item_func_numhybrid::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + switch (hybrid_type) { + case DECIMAL_RESULT: + { + my_decimal decimal_value, *val; + if (!(val= decimal_op(&decimal_value))) + return 0; // null is set + my_decimal_round(E_DEC_FATAL_ERROR, val, decimals, FALSE, val); + my_decimal2string(E_DEC_FATAL_ERROR, val, 0, 0, 0, str); + break; + } + case INT_RESULT: + { + longlong nr= int_op(); + if (null_value) + return 0; /* purecov: inspected */ + str->set_int(nr, unsigned_flag, &my_charset_bin); + break; + } + case REAL_RESULT: + { + double nr= real_op(); + if (null_value) + return 0; /* purecov: inspected */ + str->set_real(nr,decimals,&my_charset_bin); + break; + } + case STRING_RESULT: + return str_op(&str_value); + default: + DBUG_ASSERT(0); + } + return str; +} + + +double Item_func_numhybrid::val_real() +{ + DBUG_ASSERT(fixed == 1); + switch (hybrid_type) { + case DECIMAL_RESULT: + { + my_decimal decimal_value, *val; + double result; + if (!(val= decimal_op(&decimal_value))) + return 0.0; // null is set + my_decimal2double(E_DEC_FATAL_ERROR, val, &result); + return result; + } + case INT_RESULT: + { + longlong result= int_op(); + return unsigned_flag ? (double) ((ulonglong) result) : (double) result; + } + case REAL_RESULT: + return real_op(); + case STRING_RESULT: + { + char *end_not_used; + int err_not_used; + String *res= str_op(&str_value); + return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(), + &end_not_used, &err_not_used) : 0.0); + } + default: + DBUG_ASSERT(0); + } + return 0.0; +} + + +longlong Item_func_numhybrid::val_int() +{ + DBUG_ASSERT(fixed == 1); + switch (hybrid_type) { + case DECIMAL_RESULT: + { + my_decimal decimal_value, *val; + if (!(val= decimal_op(&decimal_value))) + return 0; // null is set + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result); + return result; + } + case INT_RESULT: + return int_op(); + case REAL_RESULT: + return (longlong) rint(real_op()); + case STRING_RESULT: + { + int err_not_used; + String *res; + if (!(res= str_op(&str_value))) + return 0; + + char *end= (char*) res->ptr() + res->length(); + CHARSET_INFO *cs= str_value.charset(); + return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used); + } + default: + DBUG_ASSERT(0); + } + return 0; +} + + +my_decimal *Item_func_numhybrid::val_decimal(my_decimal *decimal_value) +{ + my_decimal *val= decimal_value; + DBUG_ASSERT(fixed == 1); + switch (hybrid_type) { + case DECIMAL_RESULT: + val= decimal_op(decimal_value); + break; + case INT_RESULT: + { + longlong result= int_op(); + int2my_decimal(E_DEC_FATAL_ERROR, result, unsigned_flag, decimal_value); + break; + } + case REAL_RESULT: + { + double result= (double)real_op(); + double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value); + break; + } + case STRING_RESULT: + { + String *res; + if (!(res= str_op(&str_value))) + return NULL; + + str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(), + res->length(), res->charset(), decimal_value); + break; + } + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + return val; +} + + +void Item_func_signed::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("cast(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" as signed)")); + +} + + +longlong Item_func_signed::val_int_from_str(int *error) +{ + char buff[MAX_FIELD_WIDTH], *end, *start; + uint32 length; + String tmp(buff,sizeof(buff), &my_charset_bin), *res; + longlong value; + + /* + For a string result, we must first get the string and then convert it + to a longlong + */ + + if (!(res= args[0]->val_str(&tmp))) + { + null_value= 1; + *error= 0; + return 0; + } + null_value= 0; + start= (char *)res->ptr(); + length= res->length(); + + end= start + length; + value= my_strtoll10(start, &end, error); + if (*error > 0 || end != start+ length) + { + char err_buff[128]; + String err_tmp(err_buff,(uint32) sizeof(err_buff), system_charset_info); + err_tmp.copy(start, length, system_charset_info); + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE, + ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER", + err_tmp.c_ptr()); + } + return value; +} + + +longlong Item_func_signed::val_int() +{ + longlong value; + int error; + + if (args[0]->cast_to_int_type() != STRING_RESULT || + args[0]->result_as_longlong()) + { + value= args[0]->val_int(); + null_value= args[0]->null_value; + return value; + } + + value= val_int_from_str(&error); + if (value < 0 && error == 0) + { + push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, + "Cast to signed converted positive out-of-range integer to " + "it's negative complement"); + } + return value; +} + + +void Item_func_unsigned::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("cast(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" as unsigned)")); + +} + + +longlong Item_func_unsigned::val_int() +{ + longlong value; + int error; + + if (args[0]->cast_to_int_type() == DECIMAL_RESULT) + { + my_decimal tmp, *dec= args[0]->val_decimal(&tmp); + if (!(null_value= args[0]->null_value)) + my_decimal2int(E_DEC_FATAL_ERROR, dec, 1, &value); + else + value= 0; + return value; + } + else if (args[0]->cast_to_int_type() != STRING_RESULT || + args[0]->result_as_longlong()) + { + value= args[0]->val_int(); + null_value= args[0]->null_value; + return value; + } + + value= val_int_from_str(&error); + if (error < 0) + push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, + "Cast to unsigned converted negative integer to it's " + "positive complement"); + return value; +} + + +String *Item_decimal_typecast::val_str(String *str) +{ + my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf); + if (null_value) + return NULL; + my_decimal2string(E_DEC_FATAL_ERROR, tmp, 0, 0, 0, str); + return str; +} + + +double Item_decimal_typecast::val_real() +{ + my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf); + double res; + if (null_value) + return 0.0; + my_decimal2double(E_DEC_FATAL_ERROR, tmp, &res); + return res; +} + + +longlong Item_decimal_typecast::val_int() +{ + my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf); + longlong res; + if (null_value) + return 0; + my_decimal2int(E_DEC_FATAL_ERROR, tmp, unsigned_flag, &res); + return res; +} + + +my_decimal *Item_decimal_typecast::val_decimal(my_decimal *dec) +{ + my_decimal tmp_buf, *tmp= args[0]->val_decimal(&tmp_buf); + bool sign; + uint precision; + + if ((null_value= args[0]->null_value)) + return NULL; + my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec); + sign= dec->sign(); + if (unsigned_flag) + { + if (sign) + { + my_decimal_set_zero(dec); + goto err; + } + } + precision= my_decimal_length_to_precision(max_length, + decimals, unsigned_flag); + if (precision - decimals < (uint) my_decimal_intg(dec)) + { + max_my_decimal(dec, precision, decimals); + dec->sign(sign); + goto err; + } + return dec; + +err: + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_WARN_DATA_OUT_OF_RANGE, + ER(ER_WARN_DATA_OUT_OF_RANGE), + name, 1); + return dec; +} + + +void Item_decimal_typecast::print(String *str, enum_query_type query_type) +{ + char len_buf[20*3 + 1]; + char *end; + + uint precision= my_decimal_length_to_precision(max_length, decimals, + unsigned_flag); + str->append(STRING_WITH_LEN("cast(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" as decimal(")); + + end=int10_to_str(precision, len_buf,10); + str->append(len_buf, (uint32) (end - len_buf)); + + str->append(','); + + end=int10_to_str(decimals, len_buf,10); + str->append(len_buf, (uint32) (end - len_buf)); + + str->append(')'); + str->append(')'); +} + + +double Item_func_plus::real_op() +{ + double value= args[0]->val_real() + args[1]->val_real(); + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0.0; + return fix_result(value); +} + + +longlong Item_func_plus::int_op() +{ + longlong value=args[0]->val_int()+args[1]->val_int(); + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0; + return value; +} + + +/** + Calculate plus of two decimals. + + @param decimal_value Buffer that can be used to store result + + @retval + 0 Value was NULL; In this case null_value is set + @retval + \# Value of operation as a decimal +*/ + +my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value) +{ + my_decimal value1, *val1; + my_decimal value2, *val2; + val1= args[0]->val_decimal(&value1); + if ((null_value= args[0]->null_value)) + return 0; + val2= args[1]->val_decimal(&value2); + if (!(null_value= (args[1]->null_value || + (my_decimal_add(E_DEC_FATAL_ERROR, decimal_value, val1, + val2) > 3)))) + return decimal_value; + return 0; +} + +/** + Set precision of results for additive operations (+ and -) +*/ +void Item_func_additive_op::result_precision() +{ + decimals= max(args[0]->decimals, args[1]->decimals); + int arg1_int= args[0]->decimal_precision() - args[0]->decimals; + int arg2_int= args[1]->decimal_precision() - args[1]->decimals; + int precision= max(arg1_int, arg2_int) + 1 + decimals; + + /* Integer operations keep unsigned_flag if one of arguments is unsigned */ + if (result_type() == INT_RESULT) + unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; + else + unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; + max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, + unsigned_flag); +} + + +/** + The following function is here to allow the user to force + subtraction of UNSIGNED BIGINT to return negative values. +*/ + +void Item_func_minus::fix_length_and_dec() +{ + Item_num_op::fix_length_and_dec(); + if (unsigned_flag && + (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION)) + unsigned_flag=0; +} + + +double Item_func_minus::real_op() +{ + double value= args[0]->val_real() - args[1]->val_real(); + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0.0; + return fix_result(value); +} + + +longlong Item_func_minus::int_op() +{ + longlong value=args[0]->val_int() - args[1]->val_int(); + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0; + return value; +} + + +/** + See Item_func_plus::decimal_op for comments. +*/ + +my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value) +{ + my_decimal value1, *val1; + my_decimal value2, *val2= + + val1= args[0]->val_decimal(&value1); + if ((null_value= args[0]->null_value)) + return 0; + val2= args[1]->val_decimal(&value2); + if (!(null_value= (args[1]->null_value || + (my_decimal_sub(E_DEC_FATAL_ERROR, decimal_value, val1, + val2) > 3)))) + return decimal_value; + return 0; +} + + +double Item_func_mul::real_op() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real() * args[1]->val_real(); + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0.0; + return fix_result(value); +} + + +longlong Item_func_mul::int_op() +{ + DBUG_ASSERT(fixed == 1); + longlong value=args[0]->val_int()*args[1]->val_int(); + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0; + return value; +} + + +/** See Item_func_plus::decimal_op for comments. */ + +my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value) +{ + my_decimal value1, *val1; + my_decimal value2, *val2; + val1= args[0]->val_decimal(&value1); + if ((null_value= args[0]->null_value)) + return 0; + val2= args[1]->val_decimal(&value2); + if (!(null_value= (args[1]->null_value || + (my_decimal_mul(E_DEC_FATAL_ERROR, decimal_value, val1, + val2) > 3)))) + return decimal_value; + return 0; +} + + +void Item_func_mul::result_precision() +{ + /* Integer operations keep unsigned_flag if one of arguments is unsigned */ + if (result_type() == INT_RESULT) + unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; + else + unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; + decimals= min(args[0]->decimals + args[1]->decimals, DECIMAL_MAX_SCALE); + uint est_prec = args[0]->decimal_precision() + args[1]->decimal_precision(); + uint precision= min(est_prec, DECIMAL_MAX_PRECISION); + max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, + unsigned_flag); +} + + +double Item_func_div::real_op() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + double val2= args[1]->val_real(); + if ((null_value= args[0]->null_value || args[1]->null_value)) + return 0.0; + if (val2 == 0.0) + { + signal_divide_by_null(); + return 0.0; + } + return fix_result(value/val2); +} + + +my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value) +{ + my_decimal value1, *val1; + my_decimal value2, *val2; + int err; + + val1= args[0]->val_decimal(&value1); + if ((null_value= args[0]->null_value)) + return 0; + val2= args[1]->val_decimal(&value2); + if ((null_value= args[1]->null_value)) + return 0; + if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value, + val1, val2, prec_increment)) > 3) + { + if (err == E_DEC_DIV_ZERO) + signal_divide_by_null(); + null_value= 1; + return 0; + } + return decimal_value; +} + + +void Item_func_div::result_precision() +{ + uint precision=min(args[0]->decimal_precision() + + args[1]->decimals + prec_increment, + DECIMAL_MAX_PRECISION); + + /* Integer operations keep unsigned_flag if one of arguments is unsigned */ + if (result_type() == INT_RESULT) + unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; + else + unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; + decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE); + max_length= my_decimal_precision_to_length_no_truncation(precision, decimals, + unsigned_flag); +} + + +void Item_func_div::fix_length_and_dec() +{ + DBUG_ENTER("Item_func_div::fix_length_and_dec"); + prec_increment= current_thd->variables.div_precincrement; + Item_num_op::fix_length_and_dec(); + switch(hybrid_type) { + case REAL_RESULT: + { + decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment; + set_if_smaller(decimals, NOT_FIXED_DEC); + max_length=args[0]->max_length - args[0]->decimals + decimals; + uint tmp=float_length(decimals); + set_if_smaller(max_length,tmp); + break; + } + case INT_RESULT: + hybrid_type= DECIMAL_RESULT; + DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT")); + result_precision(); + break; + case DECIMAL_RESULT: + result_precision(); + break; + default: + DBUG_ASSERT(0); + } + maybe_null= 1; // devision by zero + DBUG_VOID_RETURN; +} + + +/* Integer division */ +longlong Item_func_int_div::val_int() +{ + DBUG_ASSERT(fixed == 1); + longlong value=args[0]->val_int(); + longlong val2=args[1]->val_int(); + if ((null_value= (args[0]->null_value || args[1]->null_value))) + return 0; + if (val2 == 0) + { + signal_divide_by_null(); + return 0; + } + return (unsigned_flag ? + (ulonglong) value / (ulonglong) val2 : + value / val2); +} + + +void Item_func_int_div::fix_length_and_dec() +{ + Item_result argtype= args[0]->result_type(); + /* use precision ony for the data type it is applicable for and valid */ + max_length=args[0]->max_length - + (argtype == DECIMAL_RESULT || argtype == INT_RESULT ? + args[0]->decimals : 0); + maybe_null=1; + unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag; +} + + +longlong Item_func_mod::int_op() +{ + DBUG_ASSERT(fixed == 1); + longlong value= args[0]->val_int(); + longlong val2= args[1]->val_int(); + longlong result; + + if ((null_value= args[0]->null_value || args[1]->null_value)) + return 0; /* purecov: inspected */ + if (val2 == 0) + { + signal_divide_by_null(); + return 0; + } + + if (args[0]->unsigned_flag) + result= args[1]->unsigned_flag ? + ((ulonglong) value) % ((ulonglong) val2) : ((ulonglong) value) % val2; + else + result= args[1]->unsigned_flag ? + value % ((ulonglong) val2) : value % val2; + + return result; +} + +double Item_func_mod::real_op() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + double val2= args[1]->val_real(); + if ((null_value= args[0]->null_value || args[1]->null_value)) + return 0.0; /* purecov: inspected */ + if (val2 == 0.0) + { + signal_divide_by_null(); + return 0.0; + } + return fmod(value,val2); +} + + +my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value) +{ + my_decimal value1, *val1; + my_decimal value2, *val2; + + val1= args[0]->val_decimal(&value1); + if ((null_value= args[0]->null_value)) + return 0; + val2= args[1]->val_decimal(&value2); + if ((null_value= args[1]->null_value)) + return 0; + switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value, + val1, val2)) { + case E_DEC_TRUNCATED: + case E_DEC_OK: + return decimal_value; + case E_DEC_DIV_ZERO: + signal_divide_by_null(); + default: + null_value= 1; + return 0; + } +} + + +void Item_func_mod::result_precision() +{ + decimals= max(args[0]->decimals, args[1]->decimals); + max_length= max(args[0]->max_length, args[1]->max_length); +} + + +void Item_func_mod::fix_length_and_dec() +{ + Item_num_op::fix_length_and_dec(); + maybe_null= 1; + unsigned_flag= args[0]->unsigned_flag; +} + + +double Item_func_neg::real_op() +{ + double value= args[0]->val_real(); + null_value= args[0]->null_value; + return -value; +} + + +longlong Item_func_neg::int_op() +{ + longlong value= args[0]->val_int(); + null_value= args[0]->null_value; + return -value; +} + + +my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value) +{ + my_decimal val, *value= args[0]->val_decimal(&val); + if (!(null_value= args[0]->null_value)) + { + my_decimal2decimal(value, decimal_value); + my_decimal_neg(decimal_value); + return decimal_value; + } + return 0; +} + + +void Item_func_neg::fix_num_length_and_dec() +{ + decimals= args[0]->decimals; + /* 1 add because sign can appear */ + max_length= args[0]->max_length + 1; +} + + +void Item_func_neg::fix_length_and_dec() +{ + DBUG_ENTER("Item_func_neg::fix_length_and_dec"); + Item_func_num1::fix_length_and_dec(); + + /* + If this is in integer context keep the context as integer if possible + (This is how multiplication and other integer functions works) + Use val() to get value as arg_type doesn't mean that item is + Item_int or Item_real due to existence of Item_param. + */ + if (hybrid_type == INT_RESULT && args[0]->const_item()) + { + longlong val= args[0]->val_int(); + if ((ulonglong) val >= (ulonglong) LONGLONG_MIN && + ((ulonglong) val != (ulonglong) LONGLONG_MIN || + args[0]->type() != INT_ITEM)) + { + /* + Ensure that result is converted to DECIMAL, as longlong can't hold + the negated number + */ + hybrid_type= DECIMAL_RESULT; + DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT")); + } + } + unsigned_flag= 0; + DBUG_VOID_RETURN; +} + + +double Item_func_abs::real_op() +{ + double value= args[0]->val_real(); + null_value= args[0]->null_value; + return fabs(value); +} + + +longlong Item_func_abs::int_op() +{ + longlong value= args[0]->val_int(); + if ((null_value= args[0]->null_value)) + return 0; + return (value >= 0) || unsigned_flag ? value : -value; +} + + +my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value) +{ + my_decimal val, *value= args[0]->val_decimal(&val); + if (!(null_value= args[0]->null_value)) + { + my_decimal2decimal(value, decimal_value); + if (decimal_value->sign()) + my_decimal_neg(decimal_value); + return decimal_value; + } + return 0; +} + + +void Item_func_abs::fix_length_and_dec() +{ + Item_func_num1::fix_length_and_dec(); + unsigned_flag= args[0]->unsigned_flag; +} + + +/** Gateway to natural LOG function. */ +double Item_func_ln::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value= args[0]->null_value)) + return 0.0; + if (value <= 0.0) + { + signal_divide_by_null(); + return 0.0; + } + return log(value); +} + +/** + Extended but so slower LOG function. + + We have to check if all values are > zero and first one is not one + as these are the cases then result is not a number. +*/ +double Item_func_log::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value= args[0]->null_value)) + return 0.0; + if (value <= 0.0) + { + signal_divide_by_null(); + return 0.0; + } + if (arg_count == 2) + { + double value2= args[1]->val_real(); + if ((null_value= args[1]->null_value)) + return 0.0; + if (value2 <= 0.0 || value == 1.0) + { + signal_divide_by_null(); + return 0.0; + } + return log(value2) / log(value); + } + return log(value); +} + +double Item_func_log2::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + + if ((null_value=args[0]->null_value)) + return 0.0; + if (value <= 0.0) + { + signal_divide_by_null(); + return 0.0; + } + return log(value) / M_LN2; +} + +double Item_func_log10::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value= args[0]->null_value)) + return 0.0; + if (value <= 0.0) + { + signal_divide_by_null(); + return 0.0; + } + return log10(value); +} + +double Item_func_exp::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0.0; /* purecov: inspected */ + return fix_result(exp(value)); +} + +double Item_func_sqrt::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=(args[0]->null_value || value < 0))) + return 0.0; /* purecov: inspected */ + return sqrt(value); +} + +double Item_func_pow::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + double val2= args[1]->val_real(); + if ((null_value=(args[0]->null_value || args[1]->null_value))) + return 0.0; /* purecov: inspected */ + return fix_result(pow(value,val2)); +} + +// Trigonometric functions + +double Item_func_acos::val_real() +{ + DBUG_ASSERT(fixed == 1); + // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug) + volatile double value= args[0]->val_real(); + if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0)))) + return 0.0; + return acos(value); +} + +double Item_func_asin::val_real() +{ + DBUG_ASSERT(fixed == 1); + // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug) + volatile double value= args[0]->val_real(); + if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0)))) + return 0.0; + return asin(value); +} + +double Item_func_atan::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0.0; + if (arg_count == 2) + { + double val2= args[1]->val_real(); + if ((null_value=args[1]->null_value)) + return 0.0; + return fix_result(atan2(value,val2)); + } + return atan(value); +} + +double Item_func_cos::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0.0; + return cos(value); +} + +double Item_func_sin::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0.0; + return sin(value); +} + +double Item_func_tan::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0.0; + return fix_result(tan(value)); +} + + +// Shift-functions, same as << and >> in C/C++ + + +longlong Item_func_shift_left::val_int() +{ + DBUG_ASSERT(fixed == 1); + uint shift; + ulonglong res= ((ulonglong) args[0]->val_int() << + (shift=(uint) args[1]->val_int())); + if (args[0]->null_value || args[1]->null_value) + { + null_value=1; + return 0; + } + null_value=0; + return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0)); +} + +longlong Item_func_shift_right::val_int() +{ + DBUG_ASSERT(fixed == 1); + uint shift; + ulonglong res= (ulonglong) args[0]->val_int() >> + (shift=(uint) args[1]->val_int()); + if (args[0]->null_value || args[1]->null_value) + { + null_value=1; + return 0; + } + null_value=0; + return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0)); +} + + +longlong Item_func_bit_neg::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulonglong res= (ulonglong) args[0]->val_int(); + if ((null_value=args[0]->null_value)) + return 0; + return ~res; +} + + +// Conversion functions + +void Item_func_integer::fix_length_and_dec() +{ + max_length=args[0]->max_length - args[0]->decimals+1; + uint tmp=float_length(decimals); + set_if_smaller(max_length,tmp); + decimals=0; +} + +void Item_func_int_val::fix_num_length_and_dec() +{ + max_length= args[0]->max_length - (args[0]->decimals ? + args[0]->decimals + 1 : + 0) + 2; + uint tmp= float_length(decimals); + set_if_smaller(max_length,tmp); + decimals= 0; +} + + +void Item_func_int_val::find_num_type() +{ + DBUG_ENTER("Item_func_int_val::find_num_type"); + DBUG_PRINT("info", ("name %s", func_name())); + switch(hybrid_type= args[0]->result_type()) + { + case STRING_RESULT: + case REAL_RESULT: + hybrid_type= REAL_RESULT; + max_length= float_length(decimals); + break; + case INT_RESULT: + case DECIMAL_RESULT: + /* + -2 because in most high position can't be used any digit for longlong + and one position for increasing value during operation + */ + if ((args[0]->max_length - args[0]->decimals) >= + (DECIMAL_LONGLONG_DIGITS - 2)) + { + hybrid_type= DECIMAL_RESULT; + } + else + { + unsigned_flag= args[0]->unsigned_flag; + hybrid_type= INT_RESULT; + } + break; + default: + DBUG_ASSERT(0); + } + DBUG_PRINT("info", ("Type: %s", + (hybrid_type == REAL_RESULT ? "REAL_RESULT" : + hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : + hybrid_type == INT_RESULT ? "INT_RESULT" : + "--ILLEGAL!!!--"))); + + DBUG_VOID_RETURN; +} + + +longlong Item_func_ceiling::int_op() +{ + longlong result; + switch (args[0]->result_type()) { + case INT_RESULT: + result= args[0]->val_int(); + null_value= args[0]->null_value; + break; + case DECIMAL_RESULT: + { + my_decimal dec_buf, *dec; + if ((dec= Item_func_ceiling::decimal_op(&dec_buf))) + my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result); + else + result= 0; + break; + } + default: + result= (longlong)Item_func_ceiling::real_op(); + }; + return result; +} + + +double Item_func_ceiling::real_op() +{ + /* + the volatile's for BUG #3051 to calm optimizer down (because of gcc's + bug) + */ + volatile double value= args[0]->val_real(); + null_value= args[0]->null_value; + return ceil(value); +} + + +my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value) +{ + my_decimal val, *value= args[0]->val_decimal(&val); + if (!(null_value= (args[0]->null_value || + my_decimal_ceiling(E_DEC_FATAL_ERROR, value, + decimal_value) > 1))) + return decimal_value; + return 0; +} + + +longlong Item_func_floor::int_op() +{ + longlong result; + switch (args[0]->result_type()) { + case INT_RESULT: + result= args[0]->val_int(); + null_value= args[0]->null_value; + break; + case DECIMAL_RESULT: + { + my_decimal dec_buf, *dec; + if ((dec= Item_func_floor::decimal_op(&dec_buf))) + my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result); + else + result= 0; + break; + } + default: + result= (longlong)Item_func_floor::real_op(); + }; + return result; +} + + +double Item_func_floor::real_op() +{ + /* + the volatile's for BUG #3051 to calm optimizer down (because of gcc's + bug) + */ + volatile double value= args[0]->val_real(); + null_value= args[0]->null_value; + return floor(value); +} + + +my_decimal *Item_func_floor::decimal_op(my_decimal *decimal_value) +{ + my_decimal val, *value= args[0]->val_decimal(&val); + if (!(null_value= (args[0]->null_value || + my_decimal_floor(E_DEC_FATAL_ERROR, value, + decimal_value) > 1))) + return decimal_value; + return 0; +} + + +void Item_func_round::fix_length_and_dec() +{ + int decimals_to_set; + longlong val1; + bool val1_unsigned; + + unsigned_flag= args[0]->unsigned_flag; + if (!args[1]->const_item()) + { + decimals= args[0]->decimals; + max_length= float_length(decimals); + if (args[0]->result_type() == DECIMAL_RESULT) + { + max_length++; + hybrid_type= DECIMAL_RESULT; + } + else + hybrid_type= REAL_RESULT; + return; + } + + val1= args[1]->val_int(); + val1_unsigned= args[1]->unsigned_flag; + if (val1 < 0) + decimals_to_set= val1_unsigned ? INT_MAX : 0; + else + decimals_to_set= (val1 > INT_MAX) ? INT_MAX : (int) val1; + + if (args[0]->decimals == NOT_FIXED_DEC) + { + decimals= min(decimals_to_set, NOT_FIXED_DEC); + max_length= float_length(decimals); + hybrid_type= REAL_RESULT; + return; + } + + switch (args[0]->result_type()) { + case REAL_RESULT: + case STRING_RESULT: + hybrid_type= REAL_RESULT; + decimals= min(decimals_to_set, NOT_FIXED_DEC); + max_length= float_length(decimals); + break; + case INT_RESULT: + if ((!decimals_to_set && truncate) || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS)) + { + int length_can_increase= test(!truncate && (val1 < 0) && !val1_unsigned); + max_length= args[0]->max_length + length_can_increase; + /* Here we can keep INT_RESULT */ + hybrid_type= INT_RESULT; + decimals= 0; + break; + } + /* fall through */ + case DECIMAL_RESULT: + { + hybrid_type= DECIMAL_RESULT; + decimals_to_set= min(DECIMAL_MAX_SCALE, decimals_to_set); + int decimals_delta= args[0]->decimals - decimals_to_set; + int precision= args[0]->decimal_precision(); + int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1; + + precision-= decimals_delta - length_increase; + decimals= min(decimals_to_set, DECIMAL_MAX_SCALE); + max_length= my_decimal_precision_to_length_no_truncation(precision, + decimals, + unsigned_flag); + break; + } + default: + DBUG_ASSERT(0); /* This result type isn't handled */ + } +} + +double my_double_round(double value, longlong dec, bool dec_unsigned, + bool truncate) +{ + double tmp; + bool dec_negative= (dec < 0) && !dec_unsigned; + ulonglong abs_dec= dec_negative ? -dec : dec; + /* + tmp2 is here to avoid return the value with 80 bit precision + This will fix that the test round(0.1,1) = round(0.1,1) is true + */ + volatile double tmp2; + + tmp=(abs_dec < array_elements(log_10) ? + log_10[abs_dec] : pow(10.0,(double) abs_dec)); + + if (dec_negative && my_isinf(tmp)) + tmp2= 0; + else if (!dec_negative && my_isinf(value * tmp)) + tmp2= value; + else if (truncate) + { + if (value >= 0) + tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp; + else + tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp; + } + else + tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp; + return tmp2; +} + + +double Item_func_round::real_op() +{ + double value= args[0]->val_real(); + + if (!(null_value= args[0]->null_value || args[1]->null_value)) + return my_double_round(value, args[1]->val_int(), args[1]->unsigned_flag, + truncate); + + return 0.0; +} + +/* + Rounds a given value to a power of 10 specified as the 'to' argument, + avoiding overflows when the value is close to the ulonglong range boundary. +*/ + +static inline ulonglong my_unsigned_round(ulonglong value, ulonglong to) +{ + ulonglong tmp= value / to * to; + return (value - tmp < (to >> 1)) ? tmp : tmp + to; +} + + +longlong Item_func_round::int_op() +{ + longlong value= args[0]->val_int(); + longlong dec= args[1]->val_int(); + decimals= 0; + ulonglong abs_dec; + if ((null_value= args[0]->null_value || args[1]->null_value)) + return 0; + if ((dec >= 0) || args[1]->unsigned_flag) + return value; // integer have not digits after point + + abs_dec= -dec; + longlong tmp; + + if(abs_dec >= array_elements(log_10_int)) + return 0; + + tmp= log_10_int[abs_dec]; + + if (truncate) + value= (unsigned_flag) ? + ((ulonglong) value / tmp) * tmp : (value / tmp) * tmp; + else + value= (unsigned_flag || value >= 0) ? + my_unsigned_round((ulonglong) value, tmp) : + -(longlong) my_unsigned_round((ulonglong) -value, tmp); + return value; +} + + +my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value) +{ + my_decimal val, *value= args[0]->val_decimal(&val); + longlong dec= args[1]->val_int(); + if (dec >= 0 || args[1]->unsigned_flag) + dec= min((ulonglong) dec, decimals); + else if (dec < INT_MIN) + dec= INT_MIN; + + if (!(null_value= (args[0]->null_value || args[1]->null_value || + my_decimal_round(E_DEC_FATAL_ERROR, value, (int) dec, + truncate, decimal_value) > 1))) + { + decimal_value->frac= decimals; + return decimal_value; + } + return 0; +} + + +void Item_func_rand::seed_random(Item *arg) +{ + /* + TODO: do not do reinit 'rand' for every execute of PS/SP if + args[0] is a constant. + */ + uint32 tmp= (uint32) arg->val_int(); + randominit(rand, (uint32) (tmp*0x10001L+55555555L), + (uint32) (tmp*0x10000001L)); +} + + +bool Item_func_rand::fix_fields(THD *thd,Item **ref) +{ + if (Item_real_func::fix_fields(thd, ref)) + return TRUE; + used_tables_cache|= RAND_TABLE_BIT; + if (arg_count) + { // Only use argument once in query + /* + Allocate rand structure once: we must use thd->stmt_arena + to create rand in proper mem_root if it's a prepared statement or + stored procedure. + + No need to send a Rand log event if seed was given eg: RAND(seed), + as it will be replicated in the query as such. + */ + if (!rand && !(rand= (struct rand_struct*) + thd->stmt_arena->alloc(sizeof(*rand)))) + return TRUE; + } + else + { + /* + Save the seed only the first time RAND() is used in the query + Once events are forwarded rather than recreated, + the following can be skipped if inside the slave thread + */ + if (!thd->rand_used) + { + thd->rand_used= 1; + thd->rand_saved_seed1= thd->rand.seed1; + thd->rand_saved_seed2= thd->rand.seed2; + } + rand= &thd->rand; + } + return FALSE; +} + +void Item_func_rand::update_used_tables() +{ + Item_real_func::update_used_tables(); + used_tables_cache|= RAND_TABLE_BIT; +} + + +double Item_func_rand::val_real() +{ + DBUG_ASSERT(fixed == 1); + if (arg_count) + { + if (!args[0]->const_item()) + seed_random(args[0]); + else if (first_eval) + { + /* + Constantness of args[0] may be set during JOIN::optimize(), if arg[0] + is a field item of "constant" table. Thus, we have to evaluate + seed_random() for constant arg there but not at the fix_fields method. + */ + first_eval= FALSE; + seed_random(args[0]); + } + } + return my_rnd(rand); +} + +longlong Item_func_sign::val_int() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + null_value=args[0]->null_value; + return value < 0.0 ? -1 : (value > 0 ? 1 : 0); +} + + +double Item_func_units::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0; + return value*mul+add; +} + + +void Item_func_min_max::fix_length_and_dec() +{ + int max_int_part=0; + bool datetime_found= FALSE; + decimals=0; + max_length=0; + maybe_null=0; + cmp_type=args[0]->result_type(); + + for (uint i=0 ; i < arg_count ; i++) + { + set_if_bigger(max_length, args[i]->max_length); + set_if_bigger(decimals, args[i]->decimals); + set_if_bigger(max_int_part, args[i]->decimal_int_part()); + if (args[i]->maybe_null) + maybe_null=1; + cmp_type=item_cmp_type(cmp_type,args[i]->result_type()); + if (args[i]->result_type() != ROW_RESULT && args[i]->is_datetime()) + { + datetime_found= TRUE; + if (!datetime_item || args[i]->field_type() == MYSQL_TYPE_DATETIME) + datetime_item= args[i]; + } + } + if (cmp_type == STRING_RESULT) + { + agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1); + if (datetime_found) + { + thd= current_thd; + compare_as_dates= TRUE; + } + } + else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT)) + max_length= my_decimal_precision_to_length_no_truncation(max_int_part + + decimals, decimals, + unsigned_flag); + cached_field_type= agg_field_type(args, arg_count); +} + + +/* + Compare item arguments in the DATETIME context. + + SYNOPSIS + cmp_datetimes() + value [out] found least/greatest DATE/DATETIME value + + DESCRIPTION + Compare item arguments as DATETIME values and return the index of the + least/greatest argument in the arguments array. + The correct integer DATE/DATETIME value of the found argument is + stored to the value pointer, if latter is provided. + + RETURN + 0 If one of arguments is NULL + # index of the least/greatest argument +*/ + +uint Item_func_min_max::cmp_datetimes(ulonglong *value) +{ + longlong UNINIT_VAR(min_max); + uint min_max_idx= 0; + + for (uint i=0; i < arg_count ; i++) + { + Item **arg= args + i; + bool is_null; + longlong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null); + if ((null_value= args[i]->null_value)) + return 0; + if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0) + { + min_max= res; + min_max_idx= i; + } + } + if (value) + { + *value= min_max; + if (datetime_item->field_type() == MYSQL_TYPE_DATE) + *value/= 1000000L; + } + return min_max_idx; +} + + +String *Item_func_min_max::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + if (compare_as_dates) + { + String *str_res; + uint min_max_idx= cmp_datetimes(NULL); + if (null_value) + return 0; + str_res= args[min_max_idx]->val_str(str); + str_res->set_charset(collation.collation); + return str_res; + } + switch (cmp_type) { + case INT_RESULT: + { + longlong nr=val_int(); + if (null_value) + return 0; + str->set_int(nr, unsigned_flag, &my_charset_bin); + return str; + } + case DECIMAL_RESULT: + { + my_decimal dec_buf, *dec_val= val_decimal(&dec_buf); + if (null_value) + return 0; + my_decimal2string(E_DEC_FATAL_ERROR, dec_val, 0, 0, 0, str); + return str; + } + case REAL_RESULT: + { + double nr= val_real(); + if (null_value) + return 0; /* purecov: inspected */ + str->set_real(nr,decimals,&my_charset_bin); + return str; + } + case STRING_RESULT: + { + String *UNINIT_VAR(res); + for (uint i=0; i < arg_count ; i++) + { + if (i == 0) + res=args[i]->val_str(str); + else + { + String *res2; + res2= args[i]->val_str(res == str ? &tmp_value : str); + if (res2) + { + int cmp= sortcmp(res,res2,collation.collation); + if ((cmp_sign < 0 ? cmp : -cmp) < 0) + res=res2; + } + } + if ((null_value= args[i]->null_value)) + return 0; + } + res->set_charset(collation.collation); + return res; + } + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + return 0; + } + return 0; // Keep compiler happy +} + + +double Item_func_min_max::val_real() +{ + DBUG_ASSERT(fixed == 1); + double value=0.0; + if (compare_as_dates) + { + ulonglong result= 0; + (void)cmp_datetimes(&result); + return (double)result; + } + for (uint i=0; i < arg_count ; i++) + { + if (i == 0) + value= args[i]->val_real(); + else + { + double tmp= args[i]->val_real(); + if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0) + value=tmp; + } + if ((null_value= args[i]->null_value)) + break; + } + return value; +} + + +longlong Item_func_min_max::val_int() +{ + DBUG_ASSERT(fixed == 1); + longlong value=0; + if (compare_as_dates) + { + ulonglong result= 0; + (void)cmp_datetimes(&result); + return (longlong)result; + } + for (uint i=0; i < arg_count ; i++) + { + if (i == 0) + value=args[i]->val_int(); + else + { + longlong tmp=args[i]->val_int(); + if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0) + value=tmp; + } + if ((null_value= args[i]->null_value)) + break; + } + return value; +} + + +my_decimal *Item_func_min_max::val_decimal(my_decimal *dec) +{ + DBUG_ASSERT(fixed == 1); + my_decimal tmp_buf, *tmp, *UNINIT_VAR(res); + + if (compare_as_dates) + { + ulonglong value= 0; + (void)cmp_datetimes(&value); + ulonglong2decimal(value, dec); + return dec; + } + for (uint i=0; i < arg_count ; i++) + { + if (i == 0) + res= args[i]->val_decimal(dec); + else + { + tmp= args[i]->val_decimal(&tmp_buf); // Zero if NULL + if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0) + { + if (tmp == &tmp_buf) + { + /* Move value out of tmp_buf as this will be reused on next loop */ + my_decimal2decimal(tmp, dec); + res= dec; + } + else + res= tmp; + } + } + if ((null_value= args[i]->null_value)) + { + res= 0; + break; + } + } + return res; +} + + +longlong Item_func_length::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + if (!res) + { + null_value=1; + return 0; /* purecov: inspected */ + } + null_value=0; + return (longlong) res->length(); +} + + +longlong Item_func_char_length::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + if (!res) + { + null_value=1; + return 0; /* purecov: inspected */ + } + null_value=0; + return (longlong) res->numchars(); +} + + +longlong Item_func_coercibility::val_int() +{ + DBUG_ASSERT(fixed == 1); + null_value= 0; + return (longlong) args[0]->collation.derivation; +} + + +void Item_func_locate::fix_length_and_dec() +{ + max_length= MY_INT32_NUM_DECIMAL_DIGITS; + agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1); +} + + +longlong Item_func_locate::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *a=args[0]->val_str(&value1); + String *b=args[1]->val_str(&value2); + if (!a || !b) + { + null_value=1; + return 0; /* purecov: inspected */ + } + null_value=0; + /* must be longlong to avoid truncation */ + longlong start= 0; + longlong start0= 0; + my_match_t match; + + if (arg_count == 3) + { + start0= start= args[2]->val_int() - 1; + + if ((start < 0) || (start > a->length())) + return 0; + + /* start is now sufficiently valid to pass to charpos function */ + start= a->charpos((int) start); + + if (start + b->length() > a->length()) + return 0; + } + + if (!b->length()) // Found empty string at start + return start + 1; + + if (!cmp_collation.collation->coll->instr(cmp_collation.collation, + a->ptr()+start, + (uint) (a->length()-start), + b->ptr(), b->length(), + &match, 1)) + return 0; + return (longlong) match.mb_len + start0 + 1; +} + + +void Item_func_locate::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("locate(")); + args[1]->print(str, query_type); + str->append(','); + args[0]->print(str, query_type); + if (arg_count == 3) + { + str->append(','); + args[2]->print(str, query_type); + } + str->append(')'); +} + + +longlong Item_func_field::val_int() +{ + DBUG_ASSERT(fixed == 1); + + if (cmp_type == STRING_RESULT) + { + String *field; + if (!(field= args[0]->val_str(&value))) + return 0; + for (uint i=1 ; i < arg_count ; i++) + { + String *tmp_value=args[i]->val_str(&tmp); + if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation)) + return (longlong) (i); + } + } + else if (cmp_type == INT_RESULT) + { + longlong val= args[0]->val_int(); + if (args[0]->null_value) + return 0; + for (uint i=1; i < arg_count ; i++) + { + if (val == args[i]->val_int() && !args[i]->null_value) + return (longlong) (i); + } + } + else if (cmp_type == DECIMAL_RESULT) + { + my_decimal dec_arg_buf, *dec_arg, + dec_buf, *dec= args[0]->val_decimal(&dec_buf); + if (args[0]->null_value) + return 0; + for (uint i=1; i < arg_count; i++) + { + dec_arg= args[i]->val_decimal(&dec_arg_buf); + if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec)) + return (longlong) (i); + } + } + else + { + double val= args[0]->val_real(); + if (args[0]->null_value) + return 0; + for (uint i=1; i < arg_count ; i++) + { + if (val == args[i]->val_real() && !args[i]->null_value) + return (longlong) (i); + } + } + return 0; +} + + +void Item_func_field::fix_length_and_dec() +{ + maybe_null=0; max_length=3; + cmp_type= args[0]->result_type(); + for (uint i=1; i < arg_count ; i++) + cmp_type= item_cmp_type(cmp_type, args[i]->result_type()); + if (cmp_type == STRING_RESULT) + agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1); +} + + +longlong Item_func_ascii::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + if (!res) + { + null_value=1; + return 0; + } + null_value=0; + return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0); +} + +longlong Item_func_ord::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + if (!res) + { + null_value=1; + return 0; + } + null_value=0; + if (!res->length()) return 0; +#ifdef USE_MB + if (use_mb(res->charset())) + { + register const char *str=res->ptr(); + register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length()); + if (!l) + return (longlong)((uchar) *str); + while (l--) + n=(n<<8)|(uint32)((uchar) *str++); + return (longlong) n; + } +#endif + return (longlong) ((uchar) (*res)[0]); +} + + /* Search after a string in a string of strings separated by ',' */ + /* Returns number of found type >= 1 or 0 if not found */ + /* This optimizes searching in enums to bit testing! */ + +void Item_func_find_in_set::fix_length_and_dec() +{ + decimals=0; + max_length=3; // 1-999 + if (args[0]->const_item() && args[1]->type() == FIELD_ITEM) + { + Field *field= ((Item_field*) args[1])->field; + if (field->real_type() == MYSQL_TYPE_SET) + { + String *find=args[0]->val_str(&value); + if (find) + { + enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(), + find->length(), 0); + enum_bit=0; + if (enum_value) + enum_bit=LL(1) << (enum_value-1); + } + } + } + agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1); +} + +static const char separator=','; + +longlong Item_func_find_in_set::val_int() +{ + DBUG_ASSERT(fixed == 1); + if (enum_value) + { + ulonglong tmp=(ulonglong) args[1]->val_int(); + if (!(null_value=args[1]->null_value || args[0]->null_value)) + { + if (tmp & enum_bit) + return enum_value; + } + return 0L; + } + + String *find=args[0]->val_str(&value); + String *buffer=args[1]->val_str(&value2); + if (!find || !buffer) + { + null_value=1; + return 0; /* purecov: inspected */ + } + null_value=0; + + int diff; + if ((diff=buffer->length() - find->length()) >= 0) + { + my_wc_t wc= 0; + CHARSET_INFO *cs= cmp_collation.collation; + const char *str_begin= buffer->ptr(); + const char *str_end= buffer->ptr(); + const char *real_end= str_end+buffer->length(); + const uchar *find_str= (const uchar *) find->ptr(); + uint find_str_len= find->length(); + int position= 0; + while (1) + { + int symbol_len; + if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, + (uchar*) real_end)) > 0) + { + const char *substr_end= str_end + symbol_len; + bool is_last_item= (substr_end == real_end); + bool is_separator= (wc == (my_wc_t) separator); + if (is_separator || is_last_item) + { + position++; + if (is_last_item && !is_separator) + str_end= substr_end; + if (!my_strnncoll(cs, (const uchar *) str_begin, + (uint) (str_end - str_begin), + find_str, find_str_len)) + return (longlong) position; + else + str_begin= substr_end; + } + str_end= substr_end; + } + else if (str_end - str_begin == 0 && + find_str_len == 0 && + wc == (my_wc_t) separator) + return (longlong) ++position; + else + return LL(0); + } + } + return 0; +} + +longlong Item_func_bit_count::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulonglong value= (ulonglong) args[0]->val_int(); + if ((null_value= args[0]->null_value)) + return 0; /* purecov: inspected */ + return (longlong) my_count_bits(value); +} + + +/**************************************************************************** +** Functions to handle dynamic loadable functions +** Original source by: Alexis Mikhailov +** Rewritten by monty. +****************************************************************************/ + +#ifdef HAVE_DLOPEN + +void udf_handler::cleanup() +{ + if (!not_original) + { + if (initialized) + { + if (u_d->func_deinit != NULL) + { + Udf_func_deinit deinit= u_d->func_deinit; + (*deinit)(&initid); + } + free_udf(u_d); + initialized= FALSE; + } + if (buffers) // Because of bug in ecc + delete [] buffers; + buffers= 0; + } +} + + +bool +udf_handler::fix_fields(THD *thd, Item_result_field *func, + uint arg_count, Item **arguments) +{ +#ifndef EMBEDDED_LIBRARY // Avoid compiler warning + uchar buff[STACK_BUFF_ALLOC]; // Max argument in function +#endif + DBUG_ENTER("Item_udf_func::fix_fields"); + + if (check_stack_overrun(thd, STACK_MIN_SIZE, buff)) + DBUG_RETURN(TRUE); // Fatal error flag is set! + + udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1); + + if (!tmp_udf) + { + my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno); + DBUG_RETURN(TRUE); + } + u_d=tmp_udf; + args=arguments; + + /* Fix all arguments */ + func->maybe_null=0; + used_tables_cache=0; + const_item_cache=1; + + if ((f_args.arg_count=arg_count)) + { + if (!(f_args.arg_type= (Item_result*) + sql_alloc(f_args.arg_count*sizeof(Item_result)))) + + { + free_udf(u_d); + DBUG_RETURN(TRUE); + } + uint i; + Item **arg,**arg_end; + for (i=0, arg=arguments, arg_end=arguments+arg_count; + arg != arg_end ; + arg++,i++) + { + if (!(*arg)->fixed && + (*arg)->fix_fields(thd, arg)) + DBUG_RETURN(1); + // we can't assign 'item' before, because fix_fields() can change arg + Item *item= *arg; + if (item->check_cols(1)) + DBUG_RETURN(TRUE); + /* + TODO: We should think about this. It is not always + right way just to set an UDF result to return my_charset_bin + if one argument has binary sorting order. + The result collation should be calculated according to arguments + derivations in some cases and should not in other cases. + Moreover, some arguments can represent a numeric input + which doesn't effect the result character set and collation. + There is no a general rule for UDF. Everything depends on + the particular user defined function. + */ + if (item->collation.collation->state & MY_CS_BINSORT) + func->collation.set(&my_charset_bin); + if (item->maybe_null) + func->maybe_null=1; + func->with_sum_func= func->with_sum_func || item->with_sum_func; + used_tables_cache|=item->used_tables(); + const_item_cache&=item->const_item(); + f_args.arg_type[i]=item->result_type(); + } + //TODO: why all following memory is not allocated with 1 call of sql_alloc? + if (!(buffers=new String[arg_count]) || + !(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) || + !(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) || + !(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) || + !(num_buffer= (char*) sql_alloc(arg_count * + ALIGN_SIZE(sizeof(double)))) || + !(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) || + !(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count * + sizeof(long)))) + { + free_udf(u_d); + DBUG_RETURN(TRUE); + } + } + func->fix_length_and_dec(); + initid.max_length=func->max_length; + initid.maybe_null=func->maybe_null; + initid.const_item=const_item_cache; + initid.decimals=func->decimals; + initid.ptr=0; + + if (u_d->func_init) + { + char init_msg_buff[MYSQL_ERRMSG_SIZE]; + char *to=num_buffer; + for (uint i=0; i < arg_count; i++) + { + /* + For a constant argument i, args->args[i] points to the argument value. + For non-constant, args->args[i] is NULL. + */ + f_args.args[i]= NULL; /* Non-const unless updated below. */ + + f_args.lengths[i]= arguments[i]->max_length; + f_args.maybe_null[i]= (char) arguments[i]->maybe_null; + f_args.attributes[i]= arguments[i]->name; + f_args.attribute_lengths[i]= arguments[i]->name_length; + + if (arguments[i]->const_item()) + { + switch (arguments[i]->result_type()) + { + case STRING_RESULT: + case DECIMAL_RESULT: + { + String *res= arguments[i]->val_str(&buffers[i]); + if (arguments[i]->null_value) + continue; + f_args.args[i]= (char*) res->c_ptr(); + f_args.lengths[i]= res->length(); + break; + } + case INT_RESULT: + *((longlong*) to)= arguments[i]->val_int(); + if (arguments[i]->null_value) + continue; + f_args.args[i]= to; + to+= ALIGN_SIZE(sizeof(longlong)); + break; + case REAL_RESULT: + *((double*) to)= arguments[i]->val_real(); + if (arguments[i]->null_value) + continue; + f_args.args[i]= to; + to+= ALIGN_SIZE(sizeof(double)); + break; + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + break; + } + } + } + Udf_func_init init= u_d->func_init; + if ((error=(uchar) init(&initid, &f_args, init_msg_buff))) + { + my_error(ER_CANT_INITIALIZE_UDF, MYF(0), + u_d->name.str, init_msg_buff); + free_udf(u_d); + DBUG_RETURN(TRUE); + } + func->max_length=min(initid.max_length,MAX_BLOB_WIDTH); + func->maybe_null=initid.maybe_null; + const_item_cache=initid.const_item; + /* + Keep used_tables_cache in sync with const_item_cache. + See the comment in Item_udf_func::update_used tables. + */ + if (!const_item_cache && !used_tables_cache) + used_tables_cache= RAND_TABLE_BIT; + func->decimals=min(initid.decimals,NOT_FIXED_DEC); + } + initialized=1; + if (error) + { + my_error(ER_CANT_INITIALIZE_UDF, MYF(0), + u_d->name.str, ER(ER_UNKNOWN_ERROR)); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + + +bool udf_handler::get_arguments() +{ + if (error) + return 1; // Got an error earlier + char *to= num_buffer; + uint str_count=0; + for (uint i=0; i < f_args.arg_count; i++) + { + f_args.args[i]=0; + switch (f_args.arg_type[i]) { + case STRING_RESULT: + case DECIMAL_RESULT: + { + String *res=args[i]->val_str(&buffers[str_count++]); + if (!(args[i]->null_value)) + { + f_args.args[i]= (char*) res->ptr(); + f_args.lengths[i]= res->length(); + break; + } + } + case INT_RESULT: + *((longlong*) to) = args[i]->val_int(); + if (!args[i]->null_value) + { + f_args.args[i]=to; + to+= ALIGN_SIZE(sizeof(longlong)); + } + break; + case REAL_RESULT: + *((double*) to)= args[i]->val_real(); + if (!args[i]->null_value) + { + f_args.args[i]=to; + to+= ALIGN_SIZE(sizeof(double)); + } + break; + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + break; + } + } + return 0; +} + +/** + @return + (String*)NULL in case of NULL values +*/ +String *udf_handler::val_str(String *str,String *save_str) +{ + uchar is_null_tmp=0; + ulong res_length; + DBUG_ENTER("udf_handler::val_str"); + + if (get_arguments()) + DBUG_RETURN(0); + char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)= + (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)) + u_d->func; + + if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH) + { // This happens VERY seldom + if (str->alloc(MAX_FIELD_WIDTH)) + { + error=1; + DBUG_RETURN(0); + } + } + char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length, + &is_null_tmp, &error); + DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length)); + if (is_null_tmp || !res || error) // The !res is for safety + { + DBUG_PRINT("info", ("Null or error")); + DBUG_RETURN(0); + } + if (res == str->ptr()) + { + str->length(res_length); + DBUG_PRINT("exit", ("str: %s", str->ptr())); + DBUG_RETURN(str); + } + save_str->set(res, res_length, str->charset()); + DBUG_PRINT("exit", ("save_str: %s", save_str->ptr())); + DBUG_RETURN(save_str); +} + + +/* + For the moment, UDF functions are returning DECIMAL values as strings +*/ + +my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf) +{ + char buf[DECIMAL_MAX_STR_LENGTH+1], *end; + ulong res_length= DECIMAL_MAX_STR_LENGTH; + + if (get_arguments()) + { + *null_value=1; + return 0; + } + char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)= + (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)) + u_d->func; + + char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error); + if (is_null || error) + { + *null_value= 1; + return 0; + } + end= res+ res_length; + str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end); + return dec_buf; +} + + +void Item_udf_func::cleanup() +{ + udf.cleanup(); + Item_func::cleanup(); +} + + +void Item_udf_func::print(String *str, enum_query_type query_type) +{ + str->append(func_name()); + str->append('('); + for (uint i=0 ; i < arg_count ; i++) + { + if (i != 0) + str->append(','); + args[i]->print_item_w_name(str, query_type); + } + str->append(')'); +} + + +double Item_func_udf_float::val_real() +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_func_udf_float::val"); + DBUG_PRINT("info",("result_type: %d arg_count: %d", + args[0]->result_type(), arg_count)); + DBUG_RETURN(udf.val(&null_value)); +} + + +String *Item_func_udf_float::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + double nr= val_real(); + if (null_value) + return 0; /* purecov: inspected */ + str->set_real(nr,decimals,&my_charset_bin); + return str; +} + + +longlong Item_func_udf_int::val_int() +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_func_udf_int::val_int"); + DBUG_RETURN(udf.val_int(&null_value)); +} + + +String *Item_func_udf_int::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + longlong nr=val_int(); + if (null_value) + return 0; + str->set_int(nr, unsigned_flag, &my_charset_bin); + return str; +} + + +longlong Item_func_udf_decimal::val_int() +{ + my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf); + longlong result; + if (null_value) + return 0; + my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result); + return result; +} + + +double Item_func_udf_decimal::val_real() +{ + my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf); + double result; + if (null_value) + return 0.0; + my_decimal2double(E_DEC_FATAL_ERROR, dec, &result); + return result; +} + + +my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf) +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_func_udf_decimal::val_decimal"); + DBUG_PRINT("info",("result_type: %d arg_count: %d", + args[0]->result_type(), arg_count)); + + DBUG_RETURN(udf.val_decimal(&null_value, dec_buf)); +} + + +String *Item_func_udf_decimal::val_str(String *str) +{ + my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf); + if (null_value) + return 0; + if (str->length() < DECIMAL_MAX_STR_LENGTH) + str->length(DECIMAL_MAX_STR_LENGTH); + my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf); + my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, '0', str); + return str; +} + + +void Item_func_udf_decimal::fix_length_and_dec() +{ + fix_num_length_and_dec(); +} + + +/* Default max_length is max argument length */ + +void Item_func_udf_str::fix_length_and_dec() +{ + DBUG_ENTER("Item_func_udf_str::fix_length_and_dec"); + max_length=0; + for (uint i = 0; i < arg_count; i++) + set_if_bigger(max_length,args[i]->max_length); + DBUG_VOID_RETURN; +} + +String *Item_func_udf_str::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res=udf.val_str(str,&str_value); + null_value = !res; + return res; +} + + +/** + @note + This has to come last in the udf_handler methods, or C for AIX + version 6.0.0.0 fails to compile with debugging enabled. (Yes, really.) +*/ + +udf_handler::~udf_handler() +{ + /* Everything should be properly cleaned up by this moment. */ + DBUG_ASSERT(not_original || !(initialized || buffers)); +} + +#else +bool udf_handler::get_arguments() { return 0; } +#endif /* HAVE_DLOPEN */ + +/* +** User level locks +*/ + +pthread_mutex_t LOCK_user_locks; +static HASH hash_user_locks; + +class User_level_lock +{ + uchar *key; + size_t key_length; + +public: + int count; + bool locked; + pthread_cond_t cond; + my_thread_id thread_id; + void set_thread(THD *thd) { thread_id= thd->thread_id; } + + User_level_lock(const uchar *key_arg,uint length, ulong id) + :key_length(length),count(1),locked(1), thread_id(id) + { + key= (uchar*) my_memdup(key_arg,length,MYF(0)); + pthread_cond_init(&cond,NULL); + if (key) + { + if (my_hash_insert(&hash_user_locks,(uchar*) this)) + { + my_free(key,MYF(0)); + key=0; + } + } + } + ~User_level_lock() + { + if (key) + { + hash_delete(&hash_user_locks,(uchar*) this); + my_free(key, MYF(0)); + } + pthread_cond_destroy(&cond); + } + inline bool initialized() { return key != 0; } + friend void item_user_lock_release(User_level_lock *ull); + friend uchar *ull_get_key(const User_level_lock *ull, size_t *length, + my_bool not_used); +}; + +uchar *ull_get_key(const User_level_lock *ull, size_t *length, + my_bool not_used __attribute__((unused))) +{ + *length= ull->key_length; + return ull->key; +} + + +static bool item_user_lock_inited= 0; + +void item_user_lock_init(void) +{ + pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW); + hash_init(&hash_user_locks,system_charset_info, + 16,0,0,(hash_get_key) ull_get_key,NULL,0); + item_user_lock_inited= 1; +} + +void item_user_lock_free(void) +{ + if (item_user_lock_inited) + { + item_user_lock_inited= 0; + hash_free(&hash_user_locks); + pthread_mutex_destroy(&LOCK_user_locks); + } +} + +void item_user_lock_release(User_level_lock *ull) +{ + ull->locked=0; + ull->thread_id= 0; + if (--ull->count) + pthread_cond_signal(&ull->cond); + else + delete ull; +} + +/** + Wait until we are at or past the given position in the master binlog + on the slave. +*/ + +longlong Item_master_pos_wait::val_int() +{ + DBUG_ASSERT(fixed == 1); + THD* thd = current_thd; + String *log_name = args[0]->val_str(&value); + int event_count= 0; + + null_value=0; + if (thd->slave_thread || !log_name || !log_name->length()) + { + null_value = 1; + return 0; + } +#ifdef HAVE_REPLICATION + longlong pos = (ulong)args[1]->val_int(); + longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ; + if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2) + { + null_value = 1; + event_count=0; + } +#endif + return event_count; +} + +#ifdef EXTRA_DEBUG +void debug_sync_point(const char* lock_name, uint lock_timeout) +{ + THD* thd=current_thd; + User_level_lock* ull; + struct timespec abstime; + size_t lock_name_len; + lock_name_len= strlen(lock_name); + pthread_mutex_lock(&LOCK_user_locks); + + if (thd->ull) + { + item_user_lock_release(thd->ull); + thd->ull=0; + } + + /* + If the lock has not been aquired by some client, we do not want to + create an entry for it, since we immediately release the lock. In + this case, we will not be waiting, but rather, just waste CPU and + memory on the whole deal + */ + if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks, + (uchar*) lock_name, + lock_name_len)))) + { + pthread_mutex_unlock(&LOCK_user_locks); + return; + } + ull->count++; + + /* + Structure is now initialized. Try to get the lock. + Set up control struct to allow others to abort locks + */ + thd_proc_info(thd, "User lock"); + thd->mysys_var->current_mutex= &LOCK_user_locks; + thd->mysys_var->current_cond= &ull->cond; + + set_timespec(abstime,lock_timeout); + while (ull->locked && !thd->killed) + { + int error= pthread_cond_timedwait(&ull->cond, &LOCK_user_locks, &abstime); + if (error == ETIMEDOUT || error == ETIME) + break; + } + + if (ull->locked) + { + if (!--ull->count) + delete ull; // Should never happen + } + else + { + ull->locked=1; + ull->set_thread(thd); + thd->ull=ull; + } + pthread_mutex_unlock(&LOCK_user_locks); + pthread_mutex_lock(&thd->mysys_var->mutex); + thd_proc_info(thd, 0); + thd->mysys_var->current_mutex= 0; + thd->mysys_var->current_cond= 0; + pthread_mutex_unlock(&thd->mysys_var->mutex); + pthread_mutex_lock(&LOCK_user_locks); + if (thd->ull) + { + item_user_lock_release(thd->ull); + thd->ull=0; + } + pthread_mutex_unlock(&LOCK_user_locks); +} + +#endif + +/** + Get a user level lock. If the thread has an old lock this is first released. + + @retval + 1 : Got lock + @retval + 0 : Timeout + @retval + NULL : Error +*/ + +longlong Item_func_get_lock::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + longlong timeout=args[1]->val_int(); + struct timespec abstime; + THD *thd=current_thd; + User_level_lock *ull; + int error; + DBUG_ENTER("Item_func_get_lock::val_int"); + + /* + In slave thread no need to get locks, everything is serialized. Anyway + there is no way to make GET_LOCK() work on slave like it did on master + (i.e. make it return exactly the same value) because we don't have the + same other concurrent threads environment. No matter what we return here, + it's not guaranteed to be same as on master. + */ + if (thd->slave_thread) + DBUG_RETURN(1); + + pthread_mutex_lock(&LOCK_user_locks); + + if (!res || !res->length()) + { + pthread_mutex_unlock(&LOCK_user_locks); + null_value=1; + DBUG_RETURN(0); + } + DBUG_PRINT("info", ("lock %.*s, thd=%ld", res->length(), res->ptr(), + (long) thd->real_id)); + null_value=0; + + if (thd->ull) + { + item_user_lock_release(thd->ull); + thd->ull=0; + } + + if (!(ull= ((User_level_lock *) hash_search(&hash_user_locks, + (uchar*) res->ptr(), + (size_t) res->length())))) + { + ull= new User_level_lock((uchar*) res->ptr(), (size_t) res->length(), + thd->thread_id); + if (!ull || !ull->initialized()) + { + delete ull; + pthread_mutex_unlock(&LOCK_user_locks); + null_value=1; // Probably out of memory + DBUG_RETURN(0); + } + ull->set_thread(thd); + thd->ull=ull; + pthread_mutex_unlock(&LOCK_user_locks); + DBUG_PRINT("info", ("made new lock")); + DBUG_RETURN(1); // Got new lock + } + ull->count++; + DBUG_PRINT("info", ("ull->count=%d", ull->count)); + + /* + Structure is now initialized. Try to get the lock. + Set up control struct to allow others to abort locks. + */ + thd_proc_info(thd, "User lock"); + thd->mysys_var->current_mutex= &LOCK_user_locks; + thd->mysys_var->current_cond= &ull->cond; + + set_timespec(abstime,timeout); + error= 0; + while (ull->locked && !thd->killed) + { + DBUG_PRINT("info", ("waiting on lock")); + error= pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime); + if (error == ETIMEDOUT || error == ETIME) + { + DBUG_PRINT("info", ("lock wait timeout")); + break; + } + error= 0; + } + + if (ull->locked) + { + if (!--ull->count) + { + DBUG_ASSERT(0); + delete ull; // Should never happen + } + if (!error) // Killed (thd->killed != 0) + { + error=1; + null_value=1; // Return NULL + } + } + else // We got the lock + { + ull->locked=1; + ull->set_thread(thd); + ull->thread_id= thd->thread_id; + thd->ull=ull; + error=0; + DBUG_PRINT("info", ("got the lock")); + } + pthread_mutex_unlock(&LOCK_user_locks); + + pthread_mutex_lock(&thd->mysys_var->mutex); + thd_proc_info(thd, 0); + thd->mysys_var->current_mutex= 0; + thd->mysys_var->current_cond= 0; + pthread_mutex_unlock(&thd->mysys_var->mutex); + + DBUG_RETURN(!error ? 1 : 0); +} + + +/** + Release a user level lock. + @return + - 1 if lock released + - 0 if lock wasn't held + - (SQL) NULL if no such lock +*/ + +longlong Item_func_release_lock::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + User_level_lock *ull; + longlong result; + THD *thd=current_thd; + DBUG_ENTER("Item_func_release_lock::val_int"); + if (!res || !res->length()) + { + null_value=1; + DBUG_RETURN(0); + } + DBUG_PRINT("info", ("lock %.*s", res->length(), res->ptr())); + null_value=0; + + result=0; + pthread_mutex_lock(&LOCK_user_locks); + if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks, + (const uchar*) res->ptr(), + (size_t) res->length())))) + { + null_value=1; + } + else + { + DBUG_PRINT("info", ("ull->locked=%d ull->thread=%lu thd=%lu", + (int) ull->locked, + (long)ull->thread_id, + (long)thd->thread_id)); + if (ull->locked && current_thd->thread_id == ull->thread_id) + { + DBUG_PRINT("info", ("release lock")); + result=1; // Release is ok + item_user_lock_release(ull); + thd->ull=0; + } + } + pthread_mutex_unlock(&LOCK_user_locks); + DBUG_RETURN(result); +} + + +longlong Item_func_last_insert_id::val_int() +{ + THD *thd= current_thd; + DBUG_ASSERT(fixed == 1); + if (arg_count) + { + longlong value= args[0]->val_int(); + null_value= args[0]->null_value; + /* + LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as + documented in the manual. We don't want to touch + first_successful_insert_id_in_cur_stmt because it would make + LAST_INSERT_ID(X) take precedence over an generated auto_increment + value for this row. + */ + thd->arg_of_last_insert_id_function= TRUE; + thd->first_successful_insert_id_in_prev_stmt= value; + return value; + } + return thd->read_first_successful_insert_id_in_prev_stmt(); +} + + +bool Item_func_last_insert_id::fix_fields(THD *thd, Item **ref) +{ + thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT); + return Item_int_func::fix_fields(thd, ref); +} + + +/* This function is just used to test speed of different functions */ + +longlong Item_func_benchmark::val_int() +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff), &my_charset_bin); + my_decimal tmp_decimal; + THD *thd=current_thd; + ulonglong loop_count; + + loop_count= (ulonglong) args[0]->val_int(); + + if (args[0]->null_value || + (!args[0]->unsigned_flag && (((longlong) loop_count) < 0))) + { + if (!args[0]->null_value) + { + char buff[22]; + llstr(((longlong) loop_count), buff); + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE), + "count", buff, "benchmark"); + } + + null_value= 1; + return 0; + } + + null_value=0; + for (ulonglong loop=0 ; loop < loop_count && !thd->killed; loop++) + { + switch (args[1]->result_type()) { + case REAL_RESULT: + (void) args[1]->val_real(); + break; + case INT_RESULT: + (void) args[1]->val_int(); + break; + case STRING_RESULT: + (void) args[1]->val_str(&tmp); + break; + case DECIMAL_RESULT: + (void) args[1]->val_decimal(&tmp_decimal); + break; + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + return 0; + } + } + return 0; +} + + +void Item_func_benchmark::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("benchmark(")); + args[0]->print(str, query_type); + str->append(','); + args[1]->print(str, query_type); + str->append(')'); +} + + +/** This function is just used to create tests with time gaps. */ + +longlong Item_func_sleep::val_int() +{ + THD *thd= current_thd; + struct timespec abstime; + pthread_cond_t cond; + int error; + + DBUG_ASSERT(fixed == 1); + + double time= args[0]->val_real(); + /* + On 64-bit OSX pthread_cond_timedwait() waits forever + if passed abstime time has already been exceeded by + the system time. + When given a very short timeout (< 10 mcs) just return + immediately. + We assume that the lines between this test and the call + to pthread_cond_timedwait() will be executed in less than 0.00001 sec. + */ + if (time < 0.00001) + return 0; + + set_timespec_nsec(abstime, (ulonglong)(time * ULL(1000000000))); + + pthread_cond_init(&cond, NULL); + pthread_mutex_lock(&LOCK_user_locks); + + thd_proc_info(thd, "User sleep"); + thd->mysys_var->current_mutex= &LOCK_user_locks; + thd->mysys_var->current_cond= &cond; + + error= 0; + while (!thd->killed) + { + error= pthread_cond_timedwait(&cond, &LOCK_user_locks, &abstime); + if (error == ETIMEDOUT || error == ETIME) + break; + error= 0; + } + thd_proc_info(thd, 0); + pthread_mutex_unlock(&LOCK_user_locks); + pthread_mutex_lock(&thd->mysys_var->mutex); + thd->mysys_var->current_mutex= 0; + thd->mysys_var->current_cond= 0; + pthread_mutex_unlock(&thd->mysys_var->mutex); + + pthread_cond_destroy(&cond); + + return test(!error); // Return 1 killed +} + + +#define extra_size sizeof(double) + +static user_var_entry *get_variable(HASH *hash, LEX_STRING &name, + bool create_if_not_exists) +{ + user_var_entry *entry; + + if (!(entry = (user_var_entry*) hash_search(hash, (uchar*) name.str, + name.length)) && + create_if_not_exists) + { + uint size=ALIGN_SIZE(sizeof(user_var_entry))+name.length+1+extra_size; + if (!hash_inited(hash)) + return 0; + if (!(entry = (user_var_entry*) my_malloc(size,MYF(MY_WME)))) + return 0; + entry->name.str=(char*) entry+ ALIGN_SIZE(sizeof(user_var_entry))+ + extra_size; + entry->name.length=name.length; + entry->value=0; + entry->length=0; + entry->update_query_id=0; + entry->collation.set(NULL, DERIVATION_IMPLICIT, 0); + entry->unsigned_flag= 0; + /* + If we are here, we were called from a SET or a query which sets a + variable. Imagine it is this: + INSERT INTO t SELECT @a:=10, @a:=@a+1. + Then when we have a Item_func_get_user_var (because of the @a+1) so we + think we have to write the value of @a to the binlog. But before that, + we have a Item_func_set_user_var to create @a (@a:=10), in this we mark + the variable as "already logged" (line below) so that it won't be logged + by Item_func_get_user_var (because that's not necessary). + */ + entry->used_query_id=current_thd->query_id; + entry->type=STRING_RESULT; + memcpy(entry->name.str, name.str, name.length+1); + if (my_hash_insert(hash,(uchar*) entry)) + { + my_free((char*) entry,MYF(0)); + return 0; + } + } + return entry; +} + + +void Item_func_set_user_var::cleanup() +{ + Item_func::cleanup(); + entry= NULL; +} + + +bool Item_func_set_user_var::set_entry(THD *thd, bool create_if_not_exists) +{ + if (entry && thd->thread_id == entry_thread_id) + goto end; // update entry->update_query_id for PS + if (!(entry= get_variable(&thd->user_vars, name, create_if_not_exists))) + { + entry_thread_id= 0; + return TRUE; + } + entry_thread_id= thd->thread_id; + /* + Remember the last query which updated it, this way a query can later know + if this variable is a constant item in the query (it is if update_query_id + is different from query_id). + */ +end: + entry->update_query_id= thd->query_id; + return FALSE; +} + + +/* + When a user variable is updated (in a SET command or a query like + SELECT @a:= ). +*/ + +bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */ + if (Item_func::fix_fields(thd, ref) || set_entry(thd, TRUE)) + return TRUE; + /* + As it is wrong and confusing to associate any + character set with NULL, @a should be latin2 + after this query sequence: + + SET @a=_latin2'string'; + SET @a=NULL; + + I.e. the second query should not change the charset + to the current default value, but should keep the + original value assigned during the first query. + In order to do it, we don't copy charset + from the argument if the argument is NULL + and the variable has previously been initialized. + */ + null_item= (args[0]->type() == NULL_ITEM); + if (!entry->collation.collation || !null_item) + entry->collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT); + collation.set(entry->collation.collation, DERIVATION_IMPLICIT); + cached_result_type= args[0]->result_type(); + return FALSE; +} + + +void +Item_func_set_user_var::fix_length_and_dec() +{ + maybe_null=args[0]->maybe_null; + max_length=args[0]->max_length; + decimals=args[0]->decimals; + collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT); +} + + +/* + Mark field in read_map + + NOTES + This is used by filesort to register used fields in a a temporary + column read set or to register used fields in a view +*/ + +bool Item_func_set_user_var::register_field_in_read_map(uchar *arg) +{ + if (result_field) + { + TABLE *table= (TABLE *) arg; + if (result_field->table == table || !table) + bitmap_set_bit(result_field->table->read_set, result_field->field_index); + } + return 0; +} + + +/** + Set value to user variable. + + @param entry pointer to structure representing variable + @param set_null should we set NULL value ? + @param ptr pointer to buffer with new value + @param length length of new value + @param type type of new value + @param cs charset info for new value + @param dv derivation for new value + @param unsigned_arg indiates if a value of type INT_RESULT is unsigned + + @retval + false success + @retval + true failure +*/ + +static bool +update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length, + Item_result type, CHARSET_INFO *cs, Derivation dv, + bool unsigned_arg) +{ + if (set_null) + { + char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry)); + if (entry->value && entry->value != pos) + my_free(entry->value,MYF(0)); + entry->value= 0; + entry->length= 0; + } + else + { + if (type == STRING_RESULT) + length++; // Store strings with end \0 + if (length <= extra_size) + { + /* Save value in value struct */ + char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry)); + if (entry->value != pos) + { + if (entry->value) + my_free(entry->value,MYF(0)); + entry->value=pos; + } + } + else + { + /* Allocate variable */ + if (entry->length != length) + { + char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry)); + if (entry->value == pos) + entry->value=0; + entry->value= (char*) my_realloc(entry->value, length, + MYF(MY_ALLOW_ZERO_PTR | MY_WME)); + if (!entry->value) + return 1; + } + } + if (type == STRING_RESULT) + { + length--; // Fix length change above + entry->value[length]= 0; // Store end \0 + } + memcpy(entry->value,ptr,length); + if (type == DECIMAL_RESULT) + ((my_decimal*)entry->value)->fix_buffer_pointer(); + entry->length= length; + entry->collation.set(cs, dv); + entry->unsigned_flag= unsigned_arg; + } + entry->type=type; + return 0; +} + + +bool +Item_func_set_user_var::update_hash(void *ptr, uint length, + Item_result res_type, + CHARSET_INFO *cs, Derivation dv, + bool unsigned_arg) +{ + /* + If we set a variable explicitely to NULL then keep the old + result type of the variable + */ + if ((null_value= args[0]->null_value) && null_item) + res_type= entry->type; // Don't change type of item + if (::update_hash(entry, (null_value= args[0]->null_value), + ptr, length, res_type, cs, dv, unsigned_arg)) + { + current_thd->fatal_error(); // Probably end of memory + null_value= 1; + return 1; + } + return 0; +} + + +/** Get the value of a variable as a double. */ + +double user_var_entry::val_real(my_bool *null_value) +{ + if ((*null_value= (value == 0))) + return 0.0; + + switch (type) { + case REAL_RESULT: + return *(double*) value; + case INT_RESULT: + return (double) *(longlong*) value; + case DECIMAL_RESULT: + { + double result; + my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *)value, &result); + return result; + } + case STRING_RESULT: + return my_atof(value); // This is null terminated + case ROW_RESULT: + DBUG_ASSERT(1); // Impossible + break; + } + return 0.0; // Impossible +} + + +/** Get the value of a variable as an integer. */ + +longlong user_var_entry::val_int(my_bool *null_value) const +{ + if ((*null_value= (value == 0))) + return LL(0); + + switch (type) { + case REAL_RESULT: + return (longlong) *(double*) value; + case INT_RESULT: + return *(longlong*) value; + case DECIMAL_RESULT: + { + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, &result); + return result; + } + case STRING_RESULT: + { + int error; + return my_strtoll10(value, (char**) 0, &error);// String is null terminated + } + case ROW_RESULT: + DBUG_ASSERT(1); // Impossible + break; + } + return LL(0); // Impossible +} + + +/** Get the value of a variable as a string. */ + +String *user_var_entry::val_str(my_bool *null_value, String *str, + uint decimals) +{ + if ((*null_value= (value == 0))) + return (String*) 0; + + switch (type) { + case REAL_RESULT: + str->set_real(*(double*) value, decimals, &my_charset_bin); + break; + case INT_RESULT: + if (!unsigned_flag) + str->set(*(longlong*) value, &my_charset_bin); + else + str->set(*(ulonglong*) value, &my_charset_bin); + break; + case DECIMAL_RESULT: + my_decimal2string(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, 0, 0, str); + break; + case STRING_RESULT: + if (str->copy(value, length, collation.collation)) + str= 0; // EOM error + case ROW_RESULT: + DBUG_ASSERT(1); // Impossible + break; + } + return(str); +} + +/** Get the value of a variable as a decimal. */ + +my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val) +{ + if ((*null_value= (value == 0))) + return 0; + + switch (type) { + case REAL_RESULT: + double2my_decimal(E_DEC_FATAL_ERROR, *(double*) value, val); + break; + case INT_RESULT: + int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) value, 0, val); + break; + case DECIMAL_RESULT: + val= (my_decimal *)value; + break; + case STRING_RESULT: + str2my_decimal(E_DEC_FATAL_ERROR, value, length, collation.collation, val); + break; + case ROW_RESULT: + DBUG_ASSERT(1); // Impossible + break; + } + return(val); +} + +/** + This functions is invoked on SET \@variable or + \@variable:= expression. + + Evaluate (and check expression), store results. + + @note + For now it always return OK. All problem with value evaluating + will be caught by thd->is_error() check in sql_set_variables(). + + @retval + FALSE OK. +*/ + +bool +Item_func_set_user_var::check(bool use_result_field) +{ + DBUG_ENTER("Item_func_set_user_var::check"); + if (use_result_field && !result_field) + use_result_field= FALSE; + + switch (cached_result_type) { + case REAL_RESULT: + { + save_result.vreal= use_result_field ? result_field->val_real() : + args[0]->val_real(); + break; + } + case INT_RESULT: + { + save_result.vint= use_result_field ? result_field->val_int() : + args[0]->val_int(); + unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag: + args[0]->unsigned_flag; + break; + } + case STRING_RESULT: + { + save_result.vstr= use_result_field ? result_field->val_str(&value) : + args[0]->val_str(&value); + break; + } + case DECIMAL_RESULT: + { + save_result.vdec= use_result_field ? + result_field->val_decimal(&decimal_buff) : + args[0]->val_decimal(&decimal_buff); + break; + } + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + break; + } + DBUG_RETURN(FALSE); +} + + +/** + @brief Evaluate and store item's result. + This function is invoked on "SELECT ... INTO @var ...". + + @param item An item to get value from. +*/ + +void Item_func_set_user_var::save_item_result(Item *item) +{ + DBUG_ENTER("Item_func_set_user_var::save_item_result"); + + switch (cached_result_type) { + case REAL_RESULT: + save_result.vreal= item->val_result(); + break; + case INT_RESULT: + save_result.vint= item->val_int_result(); + unsigned_flag= item->unsigned_flag; + break; + case STRING_RESULT: + save_result.vstr= item->str_result(&value); + break; + case DECIMAL_RESULT: + save_result.vdec= item->val_decimal_result(&decimal_buff); + break; + case ROW_RESULT: + default: + // Should never happen + DBUG_ASSERT(0); + break; + } + DBUG_VOID_RETURN; +} + + +/** + This functions is invoked on + SET \@variable or \@variable:= expression. + + @note + We have to store the expression as such in the variable, independent of + the value method used by the user + + @retval + 0 OK + @retval + 1 EOM Error + +*/ + +bool +Item_func_set_user_var::update() +{ + bool res; + DBUG_ENTER("Item_func_set_user_var::update"); + LINT_INIT(res); + + switch (cached_result_type) { + case REAL_RESULT: + { + res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal), + REAL_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, 0); + break; + } + case INT_RESULT: + { + res= update_hash((void*) &save_result.vint, sizeof(save_result.vint), + INT_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, + unsigned_flag); + break; + } + case STRING_RESULT: + { + if (!save_result.vstr) // Null value + res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin, + DERIVATION_IMPLICIT, 0); + else + res= update_hash((void*) save_result.vstr->ptr(), + save_result.vstr->length(), STRING_RESULT, + save_result.vstr->charset(), + DERIVATION_IMPLICIT, 0); + break; + } + case DECIMAL_RESULT: + { + if (!save_result.vdec) // Null value + res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin, + DERIVATION_IMPLICIT, 0); + else + res= update_hash((void*) save_result.vdec, + sizeof(my_decimal), DECIMAL_RESULT, + &my_charset_bin, DERIVATION_IMPLICIT, 0); + break; + } + case ROW_RESULT: + default: + // This case should never be chosen + DBUG_ASSERT(0); + break; + } + DBUG_RETURN(res); +} + + +double Item_func_set_user_var::val_real() +{ + DBUG_ASSERT(fixed == 1); + check(0); + update(); // Store expression + return entry->val_real(&null_value); +} + +longlong Item_func_set_user_var::val_int() +{ + DBUG_ASSERT(fixed == 1); + check(0); + update(); // Store expression + return entry->val_int(&null_value); +} + +String *Item_func_set_user_var::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + check(0); + update(); // Store expression + return entry->val_str(&null_value, str, decimals); +} + + +my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val) +{ + DBUG_ASSERT(fixed == 1); + check(0); + update(); // Store expression + return entry->val_decimal(&null_value, val); +} + + +double Item_func_set_user_var::val_result() +{ + DBUG_ASSERT(fixed == 1); + check(TRUE); + update(); // Store expression + return entry->val_real(&null_value); +} + +longlong Item_func_set_user_var::val_int_result() +{ + DBUG_ASSERT(fixed == 1); + check(TRUE); + update(); // Store expression + return entry->val_int(&null_value); +} + +String *Item_func_set_user_var::str_result(String *str) +{ + DBUG_ASSERT(fixed == 1); + check(TRUE); + update(); // Store expression + return entry->val_str(&null_value, str, decimals); +} + + +my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val) +{ + DBUG_ASSERT(fixed == 1); + check(TRUE); + update(); // Store expression + return entry->val_decimal(&null_value, val); +} + + +bool Item_func_set_user_var::is_null_result() +{ + DBUG_ASSERT(fixed == 1); + check(TRUE); + update(); // Store expression + return is_null(); +} + + +void Item_func_set_user_var::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("(@")); + str->append(name.str, name.length); + str->append(STRING_WITH_LEN(":=")); + args[0]->print(str, query_type); + str->append(')'); +} + + +void Item_func_set_user_var::print_as_stmt(String *str, + enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("set @")); + str->append(name.str, name.length); + str->append(STRING_WITH_LEN(":=")); + args[0]->print(str, query_type); + str->append(')'); +} + +bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg) +{ + if (result_field) + { + check(1); + update(); + return protocol->store(result_field); + } + return Item::send(protocol, str_arg); +} + +void Item_func_set_user_var::make_field(Send_field *tmp_field) +{ + if (result_field) + { + result_field->make_field(tmp_field); + DBUG_ASSERT(tmp_field->table_name != 0); + if (Item::name) + tmp_field->col_name=Item::name; // Use user supplied name + } + else + Item::make_field(tmp_field); +} + + +/* + Save the value of a user variable into a field + + SYNOPSIS + save_in_field() + field target field to save the value to + no_conversion flag indicating whether conversions are allowed + + DESCRIPTION + Save the function value into a field and update the user variable + accordingly. If a result field is defined and the target field doesn't + coincide with it then the value from the result field will be used as + the new value of the user variable. + + The reason to have this method rather than simply using the result + field in the val_xxx() methods is that the value from the result field + not always can be used when the result field is defined. + Let's consider the following cases: + 1) when filling a tmp table the result field is defined but the value of it + is undefined because it has to be produced yet. Thus we can't use it. + 2) on execution of an INSERT ... SELECT statement the save_in_field() + function will be called to fill the data in the new record. If the SELECT + part uses a tmp table then the result field is defined and should be + used in order to get the correct result. + + The difference between the SET_USER_VAR function and regular functions + like CONCAT is that the Item_func objects for the regular functions are + replaced by Item_field objects after the values of these functions have + been stored in a tmp table. Yet an object of the Item_field class cannot + be used to update a user variable. + Due to this we have to handle the result field in a special way here and + in the Item_func_set_user_var::send() function. + + RETURN VALUES + FALSE Ok + TRUE Error +*/ + +int Item_func_set_user_var::save_in_field(Field *field, bool no_conversions, + bool can_use_result_field) +{ + bool use_result_field= (!can_use_result_field ? 0 : + (result_field && result_field != field)); + int error; + + /* Update the value of the user variable */ + check(use_result_field); + update(); + + if (result_type() == STRING_RESULT || + (result_type() == REAL_RESULT && + field->result_type() == STRING_RESULT)) + { + String *result; + CHARSET_INFO *cs= collation.collation; + char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns + str_value.set_quick(buff, sizeof(buff), cs); + result= entry->val_str(&null_value, &str_value, decimals); + + if (null_value) + { + str_value.set_quick(0, 0, cs); + return set_field_to_null_with_conversions(field, no_conversions); + } + + /* NOTE: If null_value == FALSE, "result" must be not NULL. */ + + field->set_notnull(); + error=field->store(result->ptr(),result->length(),cs); + str_value.set_quick(0, 0, cs); + } + else if (result_type() == REAL_RESULT) + { + double nr= entry->val_real(&null_value); + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + error=field->store(nr); + } + else if (result_type() == DECIMAL_RESULT) + { + my_decimal decimal_value; + my_decimal *val= entry->val_decimal(&null_value, &decimal_value); + if (null_value) + return set_field_to_null(field); + field->set_notnull(); + error=field->store_decimal(val); + } + else + { + longlong nr= entry->val_int(&null_value); + if (null_value) + return set_field_to_null_with_conversions(field, no_conversions); + field->set_notnull(); + error=field->store(nr, unsigned_flag); + } + return error; +} + + +String * +Item_func_get_user_var::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_func_get_user_var::val_str"); + if (!var_entry) + DBUG_RETURN((String*) 0); // No such variable + DBUG_RETURN(var_entry->val_str(&null_value, str, decimals)); +} + + +double Item_func_get_user_var::val_real() +{ + DBUG_ASSERT(fixed == 1); + if (!var_entry) + return 0.0; // No such variable + return (var_entry->val_real(&null_value)); +} + + +my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec) +{ + DBUG_ASSERT(fixed == 1); + if (!var_entry) + return 0; + return var_entry->val_decimal(&null_value, dec); +} + + +longlong Item_func_get_user_var::val_int() +{ + DBUG_ASSERT(fixed == 1); + if (!var_entry) + return LL(0); // No such variable + return (var_entry->val_int(&null_value)); +} + + +/** + Get variable by name and, if necessary, put the record of variable + use into the binary log. + + When a user variable is invoked from an update query (INSERT, UPDATE etc), + stores this variable and its value in thd->user_var_events, so that it can be + written to the binlog (will be written just before the query is written, see + log.cc). + + @param thd Current thread + @param name Variable name + @param[out] out_entry variable structure or NULL. The pointer is set + regardless of whether function succeeded or not. + + @retval + 0 OK + @retval + 1 Failed to put appropriate record into binary log + +*/ + +int get_var_with_binlog(THD *thd, enum_sql_command sql_command, + LEX_STRING &name, user_var_entry **out_entry) +{ + BINLOG_USER_VAR_EVENT *user_var_event; + user_var_entry *var_entry; + var_entry= get_variable(&thd->user_vars, name, 0); + + /* + Any reference to user-defined variable which is done from stored + function or trigger affects their execution and the execution of the + calling statement. We must log all such variables even if they are + not involved in table-updating statements. + */ + if (!(opt_bin_log && + (is_update_query(sql_command) || thd->in_sub_stmt))) + { + *out_entry= var_entry; + return 0; + } + + if (!var_entry) + { + /* + If the variable does not exist, it's NULL, but we want to create it so + that it gets into the binlog (if it didn't, the slave could be + influenced by a variable of the same name previously set by another + thread). + We create it like if it had been explicitly set with SET before. + The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'. + sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION' + in dispatch_command()). Instead of building a one-element list to pass to + sql_set_variables(), we could instead manually call check() and update(); + this would save memory and time; but calling sql_set_variables() makes + one unique place to maintain (sql_set_variables()). + + Manipulation with lex is necessary since free_underlaid_joins + is going to release memory belonging to the main query. + */ + + List tmp_var_list; + LEX *sav_lex= thd->lex, lex_tmp; + thd->lex= &lex_tmp; + lex_start(thd); + tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name, + new Item_null()))); + /* Create the variable */ + if (sql_set_variables(thd, &tmp_var_list)) + { + thd->lex= sav_lex; + goto err; + } + thd->lex= sav_lex; + if (!(var_entry= get_variable(&thd->user_vars, name, 0))) + goto err; + } + else if (var_entry->used_query_id == thd->query_id || + mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id)) + { + /* + If this variable was already stored in user_var_events by this query + (because it's used in more than one place in the query), don't store + it. + */ + *out_entry= var_entry; + return 0; + } + + uint size; + /* + First we need to store value of var_entry, when the next situation + appears: + > set @a:=1; + > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1); + We have to write to binlog value @a= 1. + + We allocate the user_var_event on user_var_events_alloc pool, not on + the this-statement-execution pool because in SPs user_var_event objects + may need to be valid after current [SP] statement execution pool is + destroyed. + */ + size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length; + if (!(user_var_event= (BINLOG_USER_VAR_EVENT *) + alloc_root(thd->user_var_events_alloc, size))) + goto err; + + user_var_event->value= (char*) user_var_event + + ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)); + user_var_event->user_var_event= var_entry; + user_var_event->type= var_entry->type; + user_var_event->charset_number= var_entry->collation.collation->number; + if (!var_entry->value) + { + /* NULL value*/ + user_var_event->length= 0; + user_var_event->value= 0; + } + else + { + user_var_event->length= var_entry->length; + memcpy(user_var_event->value, var_entry->value, + var_entry->length); + } + /* Mark that this variable has been used by this query */ + var_entry->used_query_id= thd->query_id; + if (insert_dynamic(&thd->user_var_events, (uchar*) &user_var_event)) + goto err; + + *out_entry= var_entry; + return 0; + +err: + *out_entry= var_entry; + return 1; +} + +void Item_func_get_user_var::fix_length_and_dec() +{ + THD *thd=current_thd; + int error; + maybe_null=1; + decimals=NOT_FIXED_DEC; + max_length=MAX_BLOB_WIDTH; + + error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry); + + /* + If the variable didn't exist it has been created as a STRING-type. + 'var_entry' is NULL only if there occured an error during the call to + get_var_with_binlog. + */ + if (var_entry) + { + m_cached_result_type= var_entry->type; + unsigned_flag= var_entry->unsigned_flag; + max_length= var_entry->length; + + collation.set(var_entry->collation); + switch(m_cached_result_type) { + case REAL_RESULT: + max_length= DBL_DIG + 8; + break; + case INT_RESULT: + max_length= MAX_BIGINT_WIDTH; + decimals=0; + break; + case STRING_RESULT: + max_length= MAX_BLOB_WIDTH; + break; + case DECIMAL_RESULT: + max_length= DECIMAL_MAX_STR_LENGTH; + decimals= DECIMAL_MAX_SCALE; + break; + case ROW_RESULT: // Keep compiler happy + default: + DBUG_ASSERT(0); + break; + } + } + else + { + collation.set(&my_charset_bin, DERIVATION_IMPLICIT); + null_value= 1; + m_cached_result_type= STRING_RESULT; + max_length= MAX_BLOB_WIDTH; + } + + if (error) + thd->fatal_error(); + + return; +} + + +uint Item_func_get_user_var::decimal_precision() const +{ + uint precision= max_length; + Item_result restype= result_type(); + + /* Default to maximum as the precision is unknown a priori. */ + if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT)) + precision= DECIMAL_MAX_PRECISION; + + return precision; +} + + +bool Item_func_get_user_var::const_item() const +{ + return (!var_entry || current_thd->query_id != var_entry->update_query_id); +} + + +enum Item_result Item_func_get_user_var::result_type() const +{ + return m_cached_result_type; +} + + +void Item_func_get_user_var::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("(@")); + str->append(name.str,name.length); + str->append(')'); +} + + +bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const +{ + /* Assume we don't have rtti */ + if (this == item) + return 1; // Same item is same. + /* Check if other type is also a get_user_var() object */ + if (item->type() != FUNC_ITEM || + ((Item_func*) item)->functype() != functype()) + return 0; + Item_func_get_user_var *other=(Item_func_get_user_var*) item; + return (name.length == other->name.length && + !memcmp(name.str, other->name.str, name.length)); +} + + +bool Item_func_get_user_var::set_value(THD *thd, + sp_rcontext * /*ctx*/, Item **it) +{ + Item_func_set_user_var *suv= new Item_func_set_user_var(get_name(), *it); + /* + Item_func_set_user_var is not fixed after construction, call + fix_fields(). + */ + return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update()); +} + + +bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + if (Item::fix_fields(thd, ref) || + !(entry= get_variable(&thd->user_vars, name, 1))) + return TRUE; + entry->type= STRING_RESULT; + /* + Let us set the same collation which is used for loading + of fields in LOAD DATA INFILE. + (Since Item_user_var_as_out_param is used only there). + */ + entry->collation.set(thd->variables.collation_database); + entry->update_query_id= thd->query_id; + return FALSE; +} + + +void Item_user_var_as_out_param::set_null_value(CHARSET_INFO* cs) +{ + if (::update_hash(entry, TRUE, 0, 0, STRING_RESULT, cs, + DERIVATION_IMPLICIT, 0 /* unsigned_arg */)) + current_thd->fatal_error(); // Probably end of memory +} + + +void Item_user_var_as_out_param::set_value(const char *str, uint length, + CHARSET_INFO* cs) +{ + if (::update_hash(entry, FALSE, (void*)str, length, STRING_RESULT, cs, + DERIVATION_IMPLICIT, 0 /* unsigned_arg */)) + current_thd->fatal_error(); // Probably end of memory +} + + +double Item_user_var_as_out_param::val_real() +{ + DBUG_ASSERT(0); + return 0.0; +} + + +longlong Item_user_var_as_out_param::val_int() +{ + DBUG_ASSERT(0); + return 0; +} + + +String* Item_user_var_as_out_param::val_str(String *str) +{ + DBUG_ASSERT(0); + return 0; +} + + +my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer) +{ + DBUG_ASSERT(0); + return 0; +} + + +void Item_user_var_as_out_param::print(String *str, enum_query_type query_type) +{ + str->append('@'); + str->append(name.str,name.length); +} + + +Item_func_get_system_var:: +Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg, + LEX_STRING *component_arg, const char *name_arg, + size_t name_len_arg) + :var(var_arg), var_type(var_type_arg), orig_var_type(var_type_arg), + component(*component_arg), cache_present(0) +{ + /* set_name() will allocate the name */ + set_name(name_arg, (uint) name_len_arg, system_charset_info); +} + + +bool Item_func_get_system_var::is_written_to_binlog() +{ + return var->is_written_to_binlog(var_type); +} + + +void Item_func_get_system_var::update_null_value() +{ + THD *thd= current_thd; + int save_no_errors= thd->no_errors; + thd->no_errors= TRUE; + Item::update_null_value(); + thd->no_errors= save_no_errors; +} + + +void Item_func_get_system_var::fix_length_and_dec() +{ + char *cptr; + maybe_null= TRUE; + max_length= 0; + + if (var->check_type(var_type)) + { + if (var_type != OPT_DEFAULT) + { + my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0), + var->name, var_type == OPT_GLOBAL ? "SESSION" : "GLOBAL"); + return; + } + /* As there was no local variable, return the global value */ + var_type= OPT_GLOBAL; + } + + switch (var->show_type()) + { + case SHOW_LONG: + case SHOW_INT: + case SHOW_HA_ROWS: + unsigned_flag= TRUE; + max_length= MY_INT64_NUM_DECIMAL_DIGITS; + decimals=0; + break; + case SHOW_LONGLONG: + unsigned_flag= FALSE; + max_length= MY_INT64_NUM_DECIMAL_DIGITS; + decimals=0; + break; + case SHOW_CHAR: + case SHOW_CHAR_PTR: + pthread_mutex_lock(&LOCK_global_system_variables); + cptr= var->show_type() == SHOW_CHAR_PTR ? + *(char**) var->value_ptr(current_thd, var_type, &component) : + (char*) var->value_ptr(current_thd, var_type, &component); + if (cptr) + max_length= strlen(cptr) * system_charset_info->mbmaxlen; + pthread_mutex_unlock(&LOCK_global_system_variables); + collation.set(system_charset_info, DERIVATION_SYSCONST); + decimals=NOT_FIXED_DEC; + break; + case SHOW_BOOL: + case SHOW_MY_BOOL: + unsigned_flag= FALSE; + max_length= 1; + decimals=0; + break; + case SHOW_DOUBLE: + unsigned_flag= FALSE; + decimals= 6; + max_length= DBL_DIG + 6; + break; + default: + my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name); + break; + } +} + + +void Item_func_get_system_var::print(String *str, enum_query_type query_type) +{ + str->append(name, name_length); +} + + +enum Item_result Item_func_get_system_var::result_type() const +{ + switch (var->show_type()) + { + case SHOW_BOOL: + case SHOW_MY_BOOL: + case SHOW_INT: + case SHOW_LONG: + case SHOW_LONGLONG: + case SHOW_HA_ROWS: + return INT_RESULT; + case SHOW_CHAR: + case SHOW_CHAR_PTR: + return STRING_RESULT; + case SHOW_DOUBLE: + return REAL_RESULT; + default: + my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name); + return STRING_RESULT; // keep the compiler happy + } +} + + +enum_field_types Item_func_get_system_var::field_type() const +{ + switch (var->show_type()) + { + case SHOW_BOOL: + case SHOW_MY_BOOL: + case SHOW_INT: + case SHOW_LONG: + case SHOW_LONGLONG: + case SHOW_HA_ROWS: + return MYSQL_TYPE_LONGLONG; + case SHOW_CHAR: + case SHOW_CHAR_PTR: + return MYSQL_TYPE_VARCHAR; + case SHOW_DOUBLE: + return MYSQL_TYPE_DOUBLE; + default: + my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name); + return MYSQL_TYPE_VARCHAR; // keep the compiler happy + } +} + + +/* + Uses var, var_type, component, cache_present, used_query_id, thd, + cached_llval, null_value, cached_null_value +*/ +#define get_sys_var_safe(type) \ +do { \ + type value; \ + pthread_mutex_lock(&LOCK_global_system_variables); \ + value= *(type*) var->value_ptr(thd, var_type, &component); \ + pthread_mutex_unlock(&LOCK_global_system_variables); \ + cache_present |= GET_SYS_VAR_CACHE_LONG; \ + used_query_id= thd->query_id; \ + cached_llval= null_value ? 0 : (longlong) value; \ + cached_null_value= null_value; \ + return cached_llval; \ +} while (0) + + +longlong Item_func_get_system_var::val_int() +{ + THD *thd= current_thd; + + if (cache_present && thd->query_id == used_query_id) + { + if (cache_present & GET_SYS_VAR_CACHE_LONG) + { + null_value= cached_null_value; + return cached_llval; + } + else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE) + { + null_value= cached_null_value; + cached_llval= (longlong) cached_dval; + cache_present|= GET_SYS_VAR_CACHE_LONG; + return cached_llval; + } + else if (cache_present & GET_SYS_VAR_CACHE_STRING) + { + null_value= cached_null_value; + if (!null_value) + cached_llval= longlong_from_string_with_check (cached_strval.charset(), + cached_strval.c_ptr(), + cached_strval.c_ptr() + + cached_strval.length()); + else + cached_llval= 0; + cache_present|= GET_SYS_VAR_CACHE_LONG; + return cached_llval; + } + } + + switch (var->show_type()) + { + case SHOW_INT: get_sys_var_safe (uint); + case SHOW_LONG: get_sys_var_safe (ulong); + case SHOW_LONGLONG: get_sys_var_safe (longlong); + case SHOW_HA_ROWS: get_sys_var_safe (ha_rows); + case SHOW_BOOL: get_sys_var_safe (bool); + case SHOW_MY_BOOL: get_sys_var_safe (my_bool); + case SHOW_DOUBLE: + { + double dval= val_real(); + + used_query_id= thd->query_id; + cached_llval= (longlong) dval; + cache_present|= GET_SYS_VAR_CACHE_LONG; + return cached_llval; + } + case SHOW_CHAR: + case SHOW_CHAR_PTR: + { + String *str_val= val_str(NULL); + + if (str_val && str_val->length()) + cached_llval= longlong_from_string_with_check (system_charset_info, + str_val->c_ptr(), + str_val->c_ptr() + + str_val->length()); + else + { + null_value= TRUE; + cached_llval= 0; + } + + cache_present|= GET_SYS_VAR_CACHE_LONG; + return cached_llval; + } + + default: + my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name); + return 0; // keep the compiler happy + } +} + + +String* Item_func_get_system_var::val_str(String* str) +{ + THD *thd= current_thd; + + if (cache_present && thd->query_id == used_query_id) + { + if (cache_present & GET_SYS_VAR_CACHE_STRING) + { + null_value= cached_null_value; + return null_value ? NULL : &cached_strval; + } + else if (cache_present & GET_SYS_VAR_CACHE_LONG) + { + null_value= cached_null_value; + if (!null_value) + cached_strval.set (cached_llval, collation.collation); + cache_present|= GET_SYS_VAR_CACHE_STRING; + return null_value ? NULL : &cached_strval; + } + else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE) + { + null_value= cached_null_value; + if (!null_value) + cached_strval.set_real (cached_dval, decimals, collation.collation); + cache_present|= GET_SYS_VAR_CACHE_STRING; + return null_value ? NULL : &cached_strval; + } + } + + str= &cached_strval; + switch (var->show_type()) + { + case SHOW_CHAR: + case SHOW_CHAR_PTR: + { + pthread_mutex_lock(&LOCK_global_system_variables); + char *cptr= var->show_type() == SHOW_CHAR_PTR ? + *(char**) var->value_ptr(thd, var_type, &component) : + (char*) var->value_ptr(thd, var_type, &component); + if (cptr) + { + if (str->copy(cptr, strlen(cptr), collation.collation)) + { + null_value= TRUE; + str= NULL; + } + } + else + { + null_value= TRUE; + str= NULL; + } + pthread_mutex_unlock(&LOCK_global_system_variables); + break; + } + + case SHOW_INT: + case SHOW_LONG: + case SHOW_LONGLONG: + case SHOW_HA_ROWS: + case SHOW_BOOL: + case SHOW_MY_BOOL: + str->set (val_int(), collation.collation); + break; + case SHOW_DOUBLE: + str->set_real (val_real(), decimals, collation.collation); + break; + + default: + my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name); + str= NULL; + break; + } + + cache_present|= GET_SYS_VAR_CACHE_STRING; + used_query_id= thd->query_id; + cached_null_value= null_value; + return str; +} + + +double Item_func_get_system_var::val_real() +{ + THD *thd= current_thd; + + if (cache_present && thd->query_id == used_query_id) + { + if (cache_present & GET_SYS_VAR_CACHE_DOUBLE) + { + null_value= cached_null_value; + return cached_dval; + } + else if (cache_present & GET_SYS_VAR_CACHE_LONG) + { + null_value= cached_null_value; + cached_dval= (double)cached_llval; + cache_present|= GET_SYS_VAR_CACHE_DOUBLE; + return cached_dval; + } + else if (cache_present & GET_SYS_VAR_CACHE_STRING) + { + null_value= cached_null_value; + if (!null_value) + cached_dval= double_from_string_with_check (cached_strval.charset(), + cached_strval.c_ptr(), + cached_strval.c_ptr() + + cached_strval.length()); + else + cached_dval= 0; + cache_present|= GET_SYS_VAR_CACHE_DOUBLE; + return cached_dval; + } + } + + switch (var->show_type()) + { + case SHOW_DOUBLE: + pthread_mutex_lock(&LOCK_global_system_variables); + cached_dval= *(double*) var->value_ptr(thd, var_type, &component); + pthread_mutex_unlock(&LOCK_global_system_variables); + used_query_id= thd->query_id; + cached_null_value= null_value; + if (null_value) + cached_dval= 0; + cache_present|= GET_SYS_VAR_CACHE_DOUBLE; + return cached_dval; + case SHOW_CHAR: + case SHOW_CHAR_PTR: + { + char *cptr; + + pthread_mutex_lock(&LOCK_global_system_variables); + cptr= var->show_type() == SHOW_CHAR ? + (char*) var->value_ptr(thd, var_type, &component) : + *(char**) var->value_ptr(thd, var_type, &component); + if (cptr) + cached_dval= double_from_string_with_check (system_charset_info, + cptr, cptr + strlen (cptr)); + else + { + null_value= TRUE; + cached_dval= 0; + } + pthread_mutex_unlock(&LOCK_global_system_variables); + used_query_id= thd->query_id; + cached_null_value= null_value; + cache_present|= GET_SYS_VAR_CACHE_DOUBLE; + return cached_dval; + } + case SHOW_INT: + case SHOW_LONG: + case SHOW_LONGLONG: + case SHOW_HA_ROWS: + case SHOW_BOOL: + case SHOW_MY_BOOL: + cached_dval= (double) val_int(); + cache_present|= GET_SYS_VAR_CACHE_DOUBLE; + used_query_id= thd->query_id; + cached_null_value= null_value; + return cached_dval; + default: + my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name); + return 0; + } +} + + +bool Item_func_get_system_var::eq(const Item *item, bool binary_cmp) const +{ + /* Assume we don't have rtti */ + if (this == item) + return 1; // Same item is same. + /* Check if other type is also a get_user_var() object */ + if (item->type() != FUNC_ITEM || + ((Item_func*) item)->functype() != functype()) + return 0; + Item_func_get_system_var *other=(Item_func_get_system_var*) item; + return (var == other->var && var_type == other->var_type); +} + + +void Item_func_get_system_var::cleanup() +{ + Item_func::cleanup(); + cache_present= 0; + var_type= orig_var_type; + cached_strval.free(); +} + + +longlong Item_func_inet_aton::val_int() +{ + DBUG_ASSERT(fixed == 1); + uint byte_result = 0; + ulonglong result = 0; // We are ready for 64 bit addresses + const char *p,* end; + char c = '.'; // we mark c to indicate invalid IP in case length is 0 + char buff[36]; + int dot_count= 0; + + String *s,tmp(buff,sizeof(buff),&my_charset_bin); + if (!(s = args[0]->val_str(&tmp))) // If null value + goto err; + null_value=0; + + end= (p = s->ptr()) + s->length(); + while (p < end) + { + c = *p++; + int digit = (int) (c - '0'); // Assume ascii + if (digit >= 0 && digit <= 9) + { + if ((byte_result = byte_result * 10 + digit) > 255) + goto err; // Wrong address + } + else if (c == '.') + { + dot_count++; + result= (result << 8) + (ulonglong) byte_result; + byte_result = 0; + } + else + goto err; // Invalid character + } + if (c != '.') // IP number can't end on '.' + { + /* + Handle short-forms addresses according to standard. Examples: + 127 -> 0.0.0.127 + 127.1 -> 127.0.0.1 + 127.2.1 -> 127.2.0.1 + */ + switch (dot_count) { + case 1: result<<= 8; /* Fall through */ + case 2: result<<= 8; /* Fall through */ + } + return (result << 8) + (ulonglong) byte_result; + } + +err: + null_value=1; + return 0; +} + + +void Item_func_match::init_search(bool no_order) +{ + DBUG_ENTER("Item_func_match::init_search"); + + /* Check if init_search() has been called before */ + if (ft_handler) + DBUG_VOID_RETURN; + + if (key == NO_SUCH_KEY) + { + List fields; + fields.push_back(new Item_string(" ",1, cmp_collation.collation)); + for (uint i=1; i < arg_count; i++) + fields.push_back(args[i]); + concat_ws=new Item_func_concat_ws(fields); + /* + Above function used only to get value and do not need fix_fields for it: + Item_string - basic constant + fields - fix_fields() was already called for this arguments + Item_func_concat_ws - do not need fix_fields() to produce value + */ + concat_ws->quick_fix_field(); + } + + if (master) + { + join_key=master->join_key=join_key|master->join_key; + master->init_search(no_order); + ft_handler=master->ft_handler; + join_key=master->join_key; + DBUG_VOID_RETURN; + } + + String *ft_tmp= 0; + + // MATCH ... AGAINST (NULL) is meaningless, but possible + if (!(ft_tmp=key_item()->val_str(&value))) + { + ft_tmp= &value; + value.set("",0,cmp_collation.collation); + } + + if (ft_tmp->charset() != cmp_collation.collation) + { + uint dummy_errors; + search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(), + cmp_collation.collation, &dummy_errors); + ft_tmp= &search_value; + } + + if (join_key && !no_order) + flags|=FT_SORTED; + ft_handler=table->file->ft_init_ext(flags, key, ft_tmp); + + if (join_key) + table->file->ft_handler=ft_handler; + + DBUG_VOID_RETURN; +} + + +bool Item_func_match::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + Item *UNINIT_VAR(item); // Safe as arg_count is > 1 + + maybe_null=1; + join_key=0; + + /* + const_item is assumed in quite a bit of places, so it would be difficult + to remove; If it would ever to be removed, this should include + modifications to find_best and auto_close as complement to auto_init code + above. + */ + if (Item_func::fix_fields(thd, ref) || + !args[0]->const_during_execution()) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST"); + return TRUE; + } + + const_item_cache=0; + for (uint i=1 ; i < arg_count ; i++) + { + item=args[i]; + if (item->type() == Item::REF_ITEM) + args[i]= item= *((Item_ref *)item)->ref; + if (item->type() != Item::FIELD_ITEM) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "AGAINST"); + return TRUE; + } + } + /* + Check that all columns come from the same table. + We've already checked that columns in MATCH are fields so + PARAM_TABLE_BIT can only appear from AGAINST argument. + */ + if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables()) + key=NO_SUCH_KEY; + + if (key == NO_SUCH_KEY && !(flags & FT_BOOL)) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH"); + return TRUE; + } + table=((Item_field *)item)->field->table; + if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT)) + { + my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0)); + return 1; + } + table->fulltext_searched=1; + return agg_arg_collations_for_comparison(cmp_collation, + args+1, arg_count-1, 0); +} + +bool Item_func_match::fix_index() +{ + Item_field *item; + uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr; + uint max_cnt=0, mkeys=0, i; + + if (key == NO_SUCH_KEY) + return 0; + + if (!table) + goto err; + + for (keynr=0 ; keynr < table->s->keys ; keynr++) + { + if ((table->key_info[keynr].flags & HA_FULLTEXT) && + (flags & FT_BOOL ? table->keys_in_use_for_query.is_set(keynr) : + table->s->keys_in_use.is_set(keynr))) + + { + ft_to_key[fts]=keynr; + ft_cnt[fts]=0; + fts++; + } + } + + if (!fts) + goto err; + + for (i=1; i < arg_count; i++) + { + item=(Item_field*)args[i]; + for (keynr=0 ; keynr < fts ; keynr++) + { + KEY *ft_key=&table->key_info[ft_to_key[keynr]]; + uint key_parts=ft_key->key_parts; + + for (uint part=0 ; part < key_parts ; part++) + { + if (item->field->eq(ft_key->key_part[part].field)) + ft_cnt[keynr]++; + } + } + } + + for (keynr=0 ; keynr < fts ; keynr++) + { + if (ft_cnt[keynr] > max_cnt) + { + mkeys=0; + max_cnt=ft_cnt[mkeys]=ft_cnt[keynr]; + ft_to_key[mkeys]=ft_to_key[keynr]; + continue; + } + if (max_cnt && ft_cnt[keynr] == max_cnt) + { + mkeys++; + ft_cnt[mkeys]=ft_cnt[keynr]; + ft_to_key[mkeys]=ft_to_key[keynr]; + continue; + } + } + + for (keynr=0 ; keynr <= mkeys ; keynr++) + { + // partial keys doesn't work + if (max_cnt < arg_count-1 || + max_cnt < table->key_info[ft_to_key[keynr]].key_parts) + continue; + + key=ft_to_key[keynr]; + + return 0; + } + +err: + if (flags & FT_BOOL) + { + key=NO_SUCH_KEY; + return 0; + } + my_message(ER_FT_MATCHING_KEY_NOT_FOUND, + ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0)); + return 1; +} + + +bool Item_func_match::eq(const Item *item, bool binary_cmp) const +{ + if (item->type() != FUNC_ITEM || + ((Item_func*)item)->functype() != FT_FUNC || + flags != ((Item_func_match*)item)->flags) + return 0; + + Item_func_match *ifm=(Item_func_match*) item; + + if (key == ifm->key && table == ifm->table && + key_item()->eq(ifm->key_item(), binary_cmp)) + return 1; + + return 0; +} + + +double Item_func_match::val_real() +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_func_match::val"); + if (ft_handler == NULL) + DBUG_RETURN(-1.0); + + if (key != NO_SUCH_KEY && table->null_row) /* NULL row from an outer join */ + DBUG_RETURN(0.0); + + if (join_key) + { + if (table->file->ft_handler) + DBUG_RETURN(ft_handler->please->get_relevance(ft_handler)); + join_key=0; + } + + if (key == NO_SUCH_KEY) + { + String *a= concat_ws->val_str(&value); + if ((null_value= (a == 0)) || !a->length()) + DBUG_RETURN(0); + DBUG_RETURN(ft_handler->please->find_relevance(ft_handler, + (uchar *)a->ptr(), a->length())); + } + DBUG_RETURN(ft_handler->please->find_relevance(ft_handler, + table->record[0], 0)); +} + +void Item_func_match::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("(match ")); + print_args(str, 1, query_type); + str->append(STRING_WITH_LEN(" against (")); + args[0]->print(str, query_type); + if (flags & FT_BOOL) + str->append(STRING_WITH_LEN(" in boolean mode")); + else if (flags & FT_EXPAND) + str->append(STRING_WITH_LEN(" with query expansion")); + str->append(STRING_WITH_LEN("))")); +} + +longlong Item_func_bit_xor::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulonglong arg1= (ulonglong) args[0]->val_int(); + ulonglong arg2= (ulonglong) args[1]->val_int(); + if ((null_value= (args[0]->null_value || args[1]->null_value))) + return 0; + return (longlong) (arg1 ^ arg2); +} + + +/*************************************************************************** + System variables +****************************************************************************/ + +/** + Return value of an system variable base[.name] as a constant item. + + @param thd Thread handler + @param var_type global / session + @param name Name of base or system variable + @param component Component. + + @note + If component.str = 0 then the variable name is in 'name' + + @return + - 0 : error + - # : constant item +*/ + + +Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name, + LEX_STRING component) +{ + sys_var *var; + LEX_STRING *base_name, *component_name; + + if (component.str) + { + base_name= &component; + component_name= &name; + } + else + { + base_name= &name; + component_name= &component; // Empty string + } + + if (!(var= find_sys_var(thd, base_name->str, base_name->length))) + return 0; + if (component.str) + { + if (!var->is_struct()) + { + my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str); + return 0; + } + } + thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT); + + set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH); + + return new Item_func_get_system_var(var, var_type, component_name, + NULL, 0); +} + + +/** + Check a user level lock. + + Sets null_value=TRUE on error. + + @retval + 1 Available + @retval + 0 Already taken, or error +*/ + +longlong Item_func_is_free_lock::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + User_level_lock *ull; + + null_value=0; + if (!res || !res->length()) + { + null_value=1; + return 0; + } + + pthread_mutex_lock(&LOCK_user_locks); + ull= (User_level_lock *) hash_search(&hash_user_locks, (uchar*) res->ptr(), + (size_t) res->length()); + pthread_mutex_unlock(&LOCK_user_locks); + if (!ull || !ull->locked) + return 1; + return 0; +} + +longlong Item_func_is_used_lock::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + User_level_lock *ull; + + null_value=1; + if (!res || !res->length()) + return 0; + + pthread_mutex_lock(&LOCK_user_locks); + ull= (User_level_lock *) hash_search(&hash_user_locks, (uchar*) res->ptr(), + (size_t) res->length()); + pthread_mutex_unlock(&LOCK_user_locks); + if (!ull || !ull->locked) + return 0; + + null_value=0; + return ull->thread_id; +} + + +longlong Item_func_row_count::val_int() +{ + DBUG_ASSERT(fixed == 1); + THD *thd= current_thd; + + return thd->row_count_func; +} + + + + +Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name) + :Item_func(), context(context_arg), m_name(name), m_sp(NULL), sp_result_field(NULL) +{ + maybe_null= 1; + m_name->init_qname(current_thd); + dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE)); + dummy_table->s= (TABLE_SHARE*) (dummy_table+1); +} + + +Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, + sp_name *name, List &list) + :Item_func(list), context(context_arg), m_name(name), m_sp(NULL),sp_result_field(NULL) +{ + maybe_null= 1; + m_name->init_qname(current_thd); + dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE)); + dummy_table->s= (TABLE_SHARE*) (dummy_table+1); +} + + +void +Item_func_sp::cleanup() +{ + if (sp_result_field) + { + delete sp_result_field; + sp_result_field= NULL; + } + m_sp= NULL; + dummy_table->alias= NULL; + Item_func::cleanup(); +} + +const char * +Item_func_sp::func_name() const +{ + THD *thd= current_thd; + /* Calculate length to avoid reallocation of string for sure */ + uint len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) + + m_name->m_name.length)*2 + //characters*quoting + 2 + // ` and ` + (m_name->m_explicit_name ? + 3 : 0) + // '`', '`' and '.' for the db + 1 + // end of string + ALIGN_SIZE(1)); // to avoid String reallocation + String qname((char *)alloc_root(thd->mem_root, len), len, + system_charset_info); + + qname.length(0); + if (m_name->m_explicit_name) + { + append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length); + qname.append('.'); + } + append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length); + return qname.ptr(); +} + + +int my_missing_function_error(const LEX_STRING &token, const char *func_name) +{ + if (token.length && is_lex_native_function (&token)) + return my_error(ER_FUNC_INEXISTENT_NAME_COLLISION, MYF(0), func_name); + else + return my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", func_name); +} + + +/** + @brief Initialize the result field by creating a temporary dummy table + and assign it to a newly created field object. Meta data used to + create the field is fetched from the sp_head belonging to the stored + proceedure found in the stored procedure functon cache. + + @note This function should be called from fix_fields to init the result + field. It is some what related to Item_field. + + @see Item_field + + @param thd A pointer to the session and thread context. + + @return Function return error status. + @retval TRUE is returned on an error + @retval FALSE is returned on success. +*/ + +bool +Item_func_sp::init_result_field(THD *thd) +{ + LEX_STRING empty_name= { C_STRING_WITH_LEN("") }; + TABLE_SHARE *share; + DBUG_ENTER("Item_func_sp::init_result_field"); + + DBUG_ASSERT(m_sp == NULL); + DBUG_ASSERT(sp_result_field == NULL); + + if (!(m_sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, m_name, + &thd->sp_func_cache, TRUE))) + { + my_missing_function_error (m_name->m_name, m_name->m_qname.str); + context->process_error(thd); + DBUG_RETURN(TRUE); + } + + /* + A Field need to be attached to a Table. + Below we "create" a dummy table by initializing + the needed pointers. + */ + + share= dummy_table->s; + dummy_table->alias = ""; + dummy_table->maybe_null = maybe_null; + dummy_table->in_use= thd; + dummy_table->copy_blobs= TRUE; + share->table_cache_key = empty_name; + share->table_name = empty_name; + + if (!(sp_result_field= m_sp->create_result_field(max_length, name, + dummy_table))) + { + DBUG_RETURN(TRUE); + } + + if (sp_result_field->pack_length() > sizeof(result_buf)) + { + void *tmp; + if (!(tmp= sql_alloc(sp_result_field->pack_length()))) + DBUG_RETURN(TRUE); + sp_result_field->move_field((uchar*) tmp); + } + else + sp_result_field->move_field(result_buf); + + sp_result_field->null_ptr= (uchar *) &null_value; + sp_result_field->null_bit= 1; + DBUG_RETURN(FALSE); +} + + +/** + @brief Initialize local members with values from the Field interface. + + @note called from Item::fix_fields. +*/ + +void Item_func_sp::fix_length_and_dec() +{ + DBUG_ENTER("Item_func_sp::fix_length_and_dec"); + + DBUG_ASSERT(sp_result_field); + decimals= sp_result_field->decimals(); + max_length= sp_result_field->field_length; + collation.set(sp_result_field->charset()); + maybe_null= 1; + unsigned_flag= test(sp_result_field->flags & UNSIGNED_FLAG); + + DBUG_VOID_RETURN; +} + + +/** + @brief Execute function & store value in field. + + @return Function returns error status. + @retval FALSE on success. + @retval TRUE if an error occurred. +*/ + +bool +Item_func_sp::execute() +{ + THD *thd= current_thd; + + /* Execute function and store the return value in the field. */ + + if (execute_impl(thd)) + { + null_value= 1; + context->process_error(thd); + if (thd->killed) + thd->send_kill_message(); + return TRUE; + } + + /* Check that the field (the value) is not NULL. */ + + null_value= sp_result_field->is_null(); + + return null_value; +} + + +/** + @brief Execute function and store the return value in the field. + + @note This function was intended to be the concrete implementation of + the interface function execute. This was never realized. + + @return The error state. + @retval FALSE on success + @retval TRUE if an error occurred. +*/ +bool +Item_func_sp::execute_impl(THD *thd) +{ + bool err_status= TRUE; + Sub_statement_state statement_state; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + Security_context *save_security_ctx= thd->security_ctx; +#endif + enum enum_sp_data_access access= + (m_sp->m_chistics->daccess == SP_DEFAULT_ACCESS) ? + SP_DEFAULT_ACCESS_MAPPING : m_sp->m_chistics->daccess; + + DBUG_ENTER("Item_func_sp::execute_impl"); + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (context->security_ctx) + { + /* Set view definer security context */ + thd->security_ctx= context->security_ctx; + } +#endif + if (sp_check_access(thd)) + goto error; + + /* + Throw an error if a non-deterministic function is called while + statement-based replication (SBR) is active. + */ + + if (!m_sp->m_chistics->detistic && !trust_function_creators && + (access == SP_CONTAINS_SQL || access == SP_MODIFIES_SQL_DATA) && + (mysql_bin_log.is_open() && + thd->variables.binlog_format == BINLOG_FORMAT_STMT)) + { + my_error(ER_BINLOG_UNSAFE_ROUTINE, MYF(0)); + goto error; + } + + /* + Disable the binlogging if this is not a SELECT statement. If this is a + SELECT, leave binlogging on, so execute_function() code writes the + function call into binlog. + */ + thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION); + err_status= m_sp->execute_function(thd, args, arg_count, sp_result_field); + thd->restore_sub_statement_state(&statement_state); + +error: +#ifndef NO_EMBEDDED_ACCESS_CHECKS + thd->security_ctx= save_security_ctx; +#endif + + DBUG_RETURN(err_status); +} + + +void +Item_func_sp::make_field(Send_field *tmp_field) +{ + DBUG_ENTER("Item_func_sp::make_field"); + DBUG_ASSERT(sp_result_field); + sp_result_field->make_field(tmp_field); + if (name) + tmp_field->col_name= name; + DBUG_VOID_RETURN; +} + + +enum enum_field_types +Item_func_sp::field_type() const +{ + DBUG_ENTER("Item_func_sp::field_type"); + DBUG_ASSERT(sp_result_field); + DBUG_RETURN(sp_result_field->type()); +} + +Item_result +Item_func_sp::result_type() const +{ + DBUG_ENTER("Item_func_sp::result_type"); + DBUG_PRINT("info", ("m_sp = %p", (void *) m_sp)); + DBUG_ASSERT(sp_result_field); + DBUG_RETURN(sp_result_field->result_type()); +} + +longlong Item_func_found_rows::val_int() +{ + DBUG_ASSERT(fixed == 1); + return current_thd->found_rows(); +} + + +Field * +Item_func_sp::tmp_table_field(TABLE *t_arg) +{ + DBUG_ENTER("Item_func_sp::tmp_table_field"); + + DBUG_ASSERT(sp_result_field); + DBUG_RETURN(sp_result_field); +} + + +/** + @brief Checks if requested access to function can be granted to user. + If function isn't found yet, it searches function first. + If function can't be found or user don't have requested access + error is raised. + + @param thd thread handler + + @return Indication if the access was granted or not. + @retval FALSE Access is granted. + @retval TRUE Requested access can't be granted or function doesn't exists. + +*/ + +bool +Item_func_sp::sp_check_access(THD *thd) +{ + DBUG_ENTER("Item_func_sp::sp_check_access"); + DBUG_ASSERT(m_sp); +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (check_routine_access(thd, EXECUTE_ACL, + m_sp->m_db.str, m_sp->m_name.str, 0, FALSE)) + DBUG_RETURN(TRUE); +#endif + + DBUG_RETURN(FALSE); +} + + +bool +Item_func_sp::fix_fields(THD *thd, Item **ref) +{ + bool res; + DBUG_ENTER("Item_func_sp::fix_fields"); + DBUG_ASSERT(fixed == 0); + + /* + We must call init_result_field before Item_func::fix_fields() + to make m_sp and result_field members available to fix_length_and_dec(), + which is called from Item_func::fix_fields(). + */ + res= init_result_field(thd); + + if (res) + DBUG_RETURN(res); + + res= Item_func::fix_fields(thd, ref); + + if (res) + DBUG_RETURN(res); + + if (thd->lex->view_prepare_mode) + { + /* + Here we check privileges of the stored routine only during view + creation, in order to validate the view. A runtime check is + perfomed in Item_func_sp::execute(), and this method is not + called during context analysis. Notice, that during view + creation we do not infer into stored routine bodies and do not + check privileges of its statements, which would probably be a + good idea especially if the view has SQL SECURITY DEFINER and + the used stored procedure has SQL SECURITY DEFINER. + */ + res= sp_check_access(thd); +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* + Try to set and restore the security context to see whether it's valid + */ + Security_context *save_secutiry_ctx; + res= set_routine_security_ctx(thd, m_sp, false, &save_secutiry_ctx); + if (!res) + m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx); + +#endif /* ! NO_EMBEDDED_ACCESS_CHECKS */ + } + + if (!m_sp->m_chistics->detistic) + { + used_tables_cache |= RAND_TABLE_BIT; + const_item_cache= FALSE; + } + + DBUG_RETURN(res); +} + + +void Item_func_sp::update_used_tables() +{ + Item_func::update_used_tables(); + + if (!m_sp->m_chistics->detistic) + { + used_tables_cache |= RAND_TABLE_BIT; + const_item_cache= FALSE; + } +} + + +/* + uuid_short handling. + + The short uuid is defined as a longlong that contains the following bytes: + + Bytes Comment + 1 Server_id & 255 + 4 Startup time of server in seconds + 3 Incrementor + + This means that an uuid is guaranteed to be unique + even in a replication environment if the following holds: + + - The last byte of the server id is unique + - If you between two shutdown of the server don't get more than + an average of 2^24 = 16M calls to uuid_short() per second. +*/ + +ulonglong uuid_value; + +void uuid_short_init() +{ + uuid_value= ((((ulonglong) server_id) << 56) + + (((ulonglong) server_start_time) << 24)); +} + + +longlong Item_func_uuid_short::val_int() +{ + ulonglong val; + pthread_mutex_lock(&LOCK_uuid_generator); + val= uuid_value++; + pthread_mutex_unlock(&LOCK_uuid_generator); + return (longlong) val; +} diff --git a/dbcon/mysql/item_func.h b/dbcon/mysql/item_func.h new file mode 100644 index 00000000..1c3c9c42 --- /dev/null +++ b/dbcon/mysql/item_func.h @@ -0,0 +1,1722 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Function items used by mysql */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +#ifdef HAVE_IEEEFP_H +extern "C" /* Bug in BSDI include file */ +{ +#include +} +#endif + +class Item_func :public Item_result_field +{ +protected: + Item **args, *tmp_arg[2]; + /* + Allowed numbers of columns in result (usually 1, which means scalar value) + 0 means get this number from first argument + */ + uint allowed_arg_cols; + // @InfiniDB. Added for the use of some functi + THD* fThd; // will be assinged by fix_fields() +public: + uint arg_count; + table_map used_tables_cache, not_null_tables_cache; + bool const_item_cache; + enum Functype { UNKNOWN_FUNC,EQ_FUNC,EQUAL_FUNC,NE_FUNC,LT_FUNC,LE_FUNC, + GE_FUNC,GT_FUNC,FT_FUNC, + LIKE_FUNC,ISNULL_FUNC,ISNOTNULL_FUNC, + COND_AND_FUNC, COND_OR_FUNC, COND_XOR_FUNC, + BETWEEN, IN_FUNC, MULT_EQUAL_FUNC, + INTERVAL_FUNC, ISNOTNULLTEST_FUNC, + SP_EQUALS_FUNC, SP_DISJOINT_FUNC,SP_INTERSECTS_FUNC, + SP_TOUCHES_FUNC,SP_CROSSES_FUNC,SP_WITHIN_FUNC, + SP_CONTAINS_FUNC,SP_OVERLAPS_FUNC, + SP_STARTPOINT,SP_ENDPOINT,SP_EXTERIORRING, + SP_POINTN,SP_GEOMETRYN,SP_INTERIORRINGN, + NOT_FUNC, NOT_ALL_FUNC, + NOW_FUNC, TRIG_COND_FUNC, + SUSERVAR_FUNC, GUSERVAR_FUNC, COLLATE_FUNC, + EXTRACT_FUNC, CHAR_TYPECAST_FUNC, FUNC_SP, UDF_FUNC, + NEG_FUNC, GSYSVAR_FUNC }; + enum optimize_type { OPTIMIZE_NONE,OPTIMIZE_KEY,OPTIMIZE_OP, OPTIMIZE_NULL, + OPTIMIZE_EQUAL }; + enum Type type() const { return FUNC_ITEM; } + virtual enum Functype functype() const { return UNKNOWN_FUNC; } + Item_func(void): + allowed_arg_cols(1), fThd(0), arg_count(0) + { + with_sum_func= 0; + } + Item_func(Item *a): + allowed_arg_cols(1), fThd(0), arg_count(1) + { + args= tmp_arg; + args[0]= a; + with_sum_func= a->with_sum_func; + } + Item_func(Item *a,Item *b): + allowed_arg_cols(1), fThd(0), arg_count(2) + { + args= tmp_arg; + args[0]= a; args[1]= b; + with_sum_func= a->with_sum_func || b->with_sum_func; + } + Item_func(Item *a,Item *b,Item *c): + allowed_arg_cols(1), fThd(0) + { + arg_count= 0; + if ((args= (Item**) sql_alloc(sizeof(Item*)*3))) + { + arg_count= 3; + args[0]= a; args[1]= b; args[2]= c; + with_sum_func= a->with_sum_func || b->with_sum_func || c->with_sum_func; + } + } + Item_func(Item *a,Item *b,Item *c,Item *d): + allowed_arg_cols(1), fThd(0) + { + arg_count= 0; + if ((args= (Item**) sql_alloc(sizeof(Item*)*4))) + { + arg_count= 4; + args[0]= a; args[1]= b; args[2]= c; args[3]= d; + with_sum_func= a->with_sum_func || b->with_sum_func || + c->with_sum_func || d->with_sum_func; + } + } + Item_func(Item *a,Item *b,Item *c,Item *d,Item* e): + allowed_arg_cols(1), fThd(0) + { + arg_count= 5; + if ((args= (Item**) sql_alloc(sizeof(Item*)*5))) + { + args[0]= a; args[1]= b; args[2]= c; args[3]= d; args[4]= e; + with_sum_func= a->with_sum_func || b->with_sum_func || + c->with_sum_func || d->with_sum_func || e->with_sum_func ; + } + } + Item_func(List &list); + // Constructor used for Item_cond_and/or (see Item comment) + Item_func(THD *thd, Item_func *item); + bool fix_fields(THD *, Item **ref); + table_map used_tables() const; + table_map not_null_tables() const; + void update_used_tables(); + bool eq(const Item *item, bool binary_cmp) const; + virtual optimize_type select_optimize() const { return OPTIMIZE_NONE; } + virtual bool have_rev_func() const { return 0; } + virtual Item *key_item() const { return args[0]; } + /* + This method is used for debug purposes to print the name of an + item to the debug log. The second use of this method is as + a helper function of print(), where it is applicable. + To suit both goals it should return a meaningful, + distinguishable and sintactically correct string. This method + should not be used for runtime type identification, use enum + {Sum}Functype and Item_func::functype()/Item_sum::sum_func() + instead. + */ + virtual const char *func_name() const= 0; + virtual bool const_item() const { return const_item_cache; } + inline Item **arguments() const { return args; } + void set_arguments(List &list); + inline uint argument_count() const { return arg_count; } + inline void remove_arguments() { arg_count=0; } + void split_sum_func(THD *thd, Item **ref_pointer_array, List &fields); + virtual void print(String *str, enum_query_type query_type); + void print_op(String *str, enum_query_type query_type); + void print_args(String *str, uint from, enum_query_type query_type); + virtual void fix_num_length_and_dec(); + void count_only_length(); + void count_real_length(); + void count_decimal_length(); + inline bool get_arg0_date(MYSQL_TIME *ltime, uint fuzzy_date) + { + return (null_value=args[0]->get_date(ltime, fuzzy_date)); + } + inline bool get_arg0_time(MYSQL_TIME *ltime) + { + return (null_value=args[0]->get_time(ltime)); + } + bool is_null() { + update_null_value(); + return null_value; + } + void signal_divide_by_null(); + friend class udf_handler; + Field *tmp_table_field() { return result_field; } + Field *tmp_table_field(TABLE *t_arg); + Item *get_tmp_table_item(THD *thd); + + my_decimal *val_decimal(my_decimal *); + + bool agg_arg_collations(DTCollation &c, Item **items, uint nitems, + uint flags) + { + return agg_item_collations(c, func_name(), items, nitems, flags, 1); + } + bool agg_arg_collations_for_comparison(DTCollation &c, + Item **items, uint nitems, + uint flags) + { + return agg_item_collations_for_comparison(c, func_name(), + items, nitems, flags); + } + bool agg_arg_charsets(DTCollation &c, Item **items, uint nitems, + uint flags, int item_sep) + { + return agg_item_charsets(c, func_name(), items, nitems, flags, item_sep); + } + bool walk(Item_processor processor, bool walk_subquery, uchar *arg); + Item *transform(Item_transformer transformer, uchar *arg); + Item* compile(Item_analyzer analyzer, uchar **arg_p, + Item_transformer transformer, uchar *arg_t); + void traverse_cond(Cond_traverser traverser, + void * arg, traverse_order order); + bool is_expensive_processor(uchar *arg); + virtual bool is_expensive() { return 0; } + inline double fix_result(double value) + { + if (isfinite(value)) + return value; + null_value=1; + return 0.0; + } +}; + + +class Item_real_func :public Item_func +{ +public: + Item_real_func() :Item_func() {} + Item_real_func(Item *a) :Item_func(a) {} + Item_real_func(Item *a,Item *b) :Item_func(a,b) {} + Item_real_func(List &list) :Item_func(list) {} + String *val_str(String*str); + my_decimal *val_decimal(my_decimal *decimal_value); + longlong val_int() + { DBUG_ASSERT(fixed == 1); return (longlong) rint(val_real()); } + enum Item_result result_type () const { return REAL_RESULT; } + void fix_length_and_dec() + { decimals= NOT_FIXED_DEC; max_length= float_length(decimals); } +}; + + +class Item_func_numhybrid: public Item_func +{ +protected: + Item_result hybrid_type; +public: + Item_func_numhybrid(Item *a) :Item_func(a), hybrid_type(REAL_RESULT) + {} + Item_func_numhybrid(Item *a,Item *b) + :Item_func(a,b), hybrid_type(REAL_RESULT) + {} + Item_func_numhybrid(List &list) + :Item_func(list), hybrid_type(REAL_RESULT) + {} + + enum Item_result result_type () const { return hybrid_type; } + void fix_length_and_dec(); + void fix_num_length_and_dec(); + virtual void find_num_type()= 0; /* To be called from fix_length_and_dec */ + + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + String *val_str(String*str); + + /** + @brief Performs the operation that this functions implements when the + result type is INT. + + @return The result of the operation. + */ + virtual longlong int_op()= 0; + + /** + @brief Performs the operation that this functions implements when the + result type is REAL. + + @return The result of the operation. + */ + virtual double real_op()= 0; + + /** + @brief Performs the operation that this functions implements when the + result type is DECIMAL. + + @param A pointer where the DECIMAL value will be allocated. + @return + - 0 If the result is NULL + - The same pointer it was given, with the area initialized to the + result of the operation. + */ + virtual my_decimal *decimal_op(my_decimal *)= 0; + + /** + @brief Performs the operation that this functions implements when the + result type is a string type. + + @return The result of the operation. + */ + virtual String *str_op(String *)= 0; + bool is_null() { update_null_value(); return null_value; } +}; + +/* function where type of result detected by first argument */ +class Item_func_num1: public Item_func_numhybrid +{ +public: + Item_func_num1(Item *a) :Item_func_numhybrid(a) {} + Item_func_num1(Item *a, Item *b) :Item_func_numhybrid(a, b) {} + + void fix_num_length_and_dec(); + void find_num_type(); + String *str_op(String *str) { DBUG_ASSERT(0); return 0; } +}; + + +/* Base class for operations like '+', '-', '*' */ +class Item_num_op :public Item_func_numhybrid +{ + public: + Item_num_op(Item *a,Item *b) :Item_func_numhybrid(a, b) {} + virtual void result_precision()= 0; + + virtual inline void print(String *str, enum_query_type query_type) + { + print_op(str, query_type); + } + + void find_num_type(); + String *str_op(String *str) { DBUG_ASSERT(0); return 0; } +}; + + +class Item_int_func :public Item_func +{ +public: + Item_int_func() :Item_func() { max_length= 21; } + Item_int_func(Item *a) :Item_func(a) { max_length= 21; } + Item_int_func(Item *a,Item *b) :Item_func(a,b) { max_length= 21; } + Item_int_func(Item *a,Item *b,Item *c) :Item_func(a,b,c) + { max_length= 21; } + Item_int_func(List &list) :Item_func(list) { max_length= 21; } + Item_int_func(THD *thd, Item_int_func *item) :Item_func(thd, item) {} + double val_real(); + String *val_str(String*str); + enum Item_result result_type () const { return INT_RESULT; } + void fix_length_and_dec() {} +}; + + +class Item_func_connection_id :public Item_int_func +{ + longlong value; + +public: + Item_func_connection_id() {} + const char *func_name() const { return "connection_id"; } + void fix_length_and_dec(); + bool fix_fields(THD *thd, Item **ref); + longlong val_int() { DBUG_ASSERT(fixed == 1); return value; } +}; + + +class Item_func_signed :public Item_int_func +{ +public: + Item_func_signed(Item *a) :Item_int_func(a) {} + const char *func_name() const { return "cast_as_signed"; } + longlong val_int(); + longlong val_int_from_str(int *error); + void fix_length_and_dec() + { max_length=args[0]->max_length; unsigned_flag=0; } + virtual void print(String *str, enum_query_type query_type); + uint decimal_precision() const { return args[0]->decimal_precision(); } +}; + + +class Item_func_unsigned :public Item_func_signed +{ +public: + Item_func_unsigned(Item *a) :Item_func_signed(a) {} + const char *func_name() const { return "cast_as_unsigned"; } + void fix_length_and_dec() + { + max_length= min(args[0]->max_length, DECIMAL_MAX_PRECISION + 2); + unsigned_flag=1; + } + longlong val_int(); + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_decimal_typecast :public Item_func +{ + my_decimal decimal_value; +public: + Item_decimal_typecast(Item *a, int len, int dec) :Item_func(a) + { + decimals= dec; + max_length= my_decimal_precision_to_length_no_truncation(len, dec, + unsigned_flag); + } + String *val_str(String *str); + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal*); + enum Item_result result_type () const { return DECIMAL_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_NEWDECIMAL; } + void fix_length_and_dec() {}; + const char *func_name() const { return "decimal_typecast"; } + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_additive_op :public Item_num_op +{ +public: + Item_func_additive_op(Item *a,Item *b) :Item_num_op(a,b) {} + void result_precision(); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_plus :public Item_func_additive_op +{ +public: + Item_func_plus(Item *a,Item *b) :Item_func_additive_op(a,b) {} + const char *func_name() const { return "+"; } + longlong int_op(); + double real_op(); + my_decimal *decimal_op(my_decimal *); +}; + +class Item_func_minus :public Item_func_additive_op +{ +public: + Item_func_minus(Item *a,Item *b) :Item_func_additive_op(a,b) {} + const char *func_name() const { return "-"; } + longlong int_op(); + double real_op(); + my_decimal *decimal_op(my_decimal *); + void fix_length_and_dec(); +}; + + +class Item_func_mul :public Item_num_op +{ +public: + Item_func_mul(Item *a,Item *b) :Item_num_op(a,b) {} + const char *func_name() const { return "*"; } + longlong int_op(); + double real_op(); + my_decimal *decimal_op(my_decimal *); + void result_precision(); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_div :public Item_num_op +{ +public: + uint prec_increment; + Item_func_div(Item *a,Item *b) :Item_num_op(a,b) {} + longlong int_op() { DBUG_ASSERT(0); return 0; } + double real_op(); + my_decimal *decimal_op(my_decimal *); + const char *func_name() const { return "/"; } + void fix_length_and_dec(); + void result_precision(); +}; + + +class Item_func_int_div :public Item_int_func +{ +public: + Item_func_int_div(Item *a,Item *b) :Item_int_func(a,b) + {} + longlong val_int(); + const char *func_name() const { return "DIV"; } + void fix_length_and_dec(); + + virtual inline void print(String *str, enum_query_type query_type) + { + print_op(str, query_type); + } + + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_mod :public Item_num_op +{ +public: + Item_func_mod(Item *a,Item *b) :Item_num_op(a,b) {} + longlong int_op(); + double real_op(); + my_decimal *decimal_op(my_decimal *); + const char *func_name() const { return "%"; } + void result_precision(); + void fix_length_and_dec(); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_neg :public Item_func_num1 +{ +public: + Item_func_neg(Item *a) :Item_func_num1(a) {} + double real_op(); + longlong int_op(); + my_decimal *decimal_op(my_decimal *); + const char *func_name() const { return "-"; } + enum Functype functype() const { return NEG_FUNC; } + void fix_length_and_dec(); + void fix_num_length_and_dec(); + uint decimal_precision() const { return args[0]->decimal_precision(); } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_abs :public Item_func_num1 +{ +public: + Item_func_abs(Item *a) :Item_func_num1(a) {} + double real_op(); + longlong int_op(); + my_decimal *decimal_op(my_decimal *); + const char *func_name() const { return "abs"; } + void fix_length_and_dec(); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + +// A class to handle logarithmic and trigonometric functions + +class Item_dec_func :public Item_real_func +{ + public: + Item_dec_func(Item *a) :Item_real_func(a) {} + Item_dec_func(Item *a,Item *b) :Item_real_func(a,b) {} + void fix_length_and_dec() + { + decimals=NOT_FIXED_DEC; max_length=float_length(decimals); + maybe_null=1; + } +}; + +class Item_func_exp :public Item_dec_func +{ +public: + Item_func_exp(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "exp"; } +}; + + +class Item_func_ln :public Item_dec_func +{ +public: + Item_func_ln(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "ln"; } +}; + + +class Item_func_log :public Item_dec_func +{ +public: + Item_func_log(Item *a) :Item_dec_func(a) {} + Item_func_log(Item *a,Item *b) :Item_dec_func(a,b) {} + double val_real(); + const char *func_name() const { return "log"; } +}; + + +class Item_func_log2 :public Item_dec_func +{ +public: + Item_func_log2(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "log2"; } +}; + + +class Item_func_log10 :public Item_dec_func +{ +public: + Item_func_log10(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "log10"; } +}; + + +class Item_func_sqrt :public Item_dec_func +{ +public: + Item_func_sqrt(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "sqrt"; } +}; + + +class Item_func_pow :public Item_dec_func +{ +public: + Item_func_pow(Item *a,Item *b) :Item_dec_func(a,b) {} + double val_real(); + const char *func_name() const { return "pow"; } +}; + + +class Item_func_acos :public Item_dec_func +{ +public: + Item_func_acos(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "acos"; } +}; + +class Item_func_asin :public Item_dec_func +{ +public: + Item_func_asin(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "asin"; } +}; + +class Item_func_atan :public Item_dec_func +{ +public: + Item_func_atan(Item *a) :Item_dec_func(a) {} + Item_func_atan(Item *a,Item *b) :Item_dec_func(a,b) {} + double val_real(); + const char *func_name() const { return "atan"; } +}; + +class Item_func_cos :public Item_dec_func +{ +public: + Item_func_cos(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "cos"; } +}; + +class Item_func_sin :public Item_dec_func +{ +public: + Item_func_sin(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "sin"; } +}; + +class Item_func_tan :public Item_dec_func +{ +public: + Item_func_tan(Item *a) :Item_dec_func(a) {} + double val_real(); + const char *func_name() const { return "tan"; } +}; + +class Item_func_integer :public Item_int_func +{ +public: + inline Item_func_integer(Item *a) :Item_int_func(a) {} + void fix_length_and_dec(); +}; + + +class Item_func_int_val :public Item_func_num1 +{ +public: + Item_func_int_val(Item *a) :Item_func_num1(a) {} + void fix_num_length_and_dec(); + void find_num_type(); +}; + + +class Item_func_ceiling :public Item_func_int_val +{ +public: + Item_func_ceiling(Item *a) :Item_func_int_val(a) {} + const char *func_name() const { return "ceiling"; } + longlong int_op(); + double real_op(); + my_decimal *decimal_op(my_decimal *); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_floor :public Item_func_int_val +{ +public: + Item_func_floor(Item *a) :Item_func_int_val(a) {} + const char *func_name() const { return "floor"; } + longlong int_op(); + double real_op(); + my_decimal *decimal_op(my_decimal *); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + +/* This handles round and truncate */ + +class Item_func_round :public Item_func_num1 +{ + bool truncate; +public: + Item_func_round(Item *a, Item *b, bool trunc_arg) + :Item_func_num1(a,b), truncate(trunc_arg) {} + const char *func_name() const { return truncate ? "truncate" : "round"; } + double real_op(); + longlong int_op(); + my_decimal *decimal_op(my_decimal *); + void fix_length_and_dec(); +}; + + +class Item_func_rand :public Item_real_func +{ + struct rand_struct *rand; + bool first_eval; // TRUE if val_real() is called 1st time +public: + Item_func_rand(Item *a) :Item_real_func(a), rand(0), first_eval(TRUE) {} + Item_func_rand() :Item_real_func() {} + double val_real(); + const char *func_name() const { return "rand"; } + bool const_item() const { return 0; } + void update_used_tables(); + bool fix_fields(THD *thd, Item **ref); + void cleanup() { first_eval= TRUE; Item_real_func::cleanup(); } +private: + void seed_random (Item * val); +}; + + +class Item_func_sign :public Item_int_func +{ +public: + Item_func_sign(Item *a) :Item_int_func(a) {} + const char *func_name() const { return "sign"; } + longlong val_int(); +}; + + +class Item_func_units :public Item_real_func +{ + char *name; + double mul,add; +public: + Item_func_units(char *name_arg,Item *a,double mul_arg,double add_arg) + :Item_real_func(a),name(name_arg),mul(mul_arg),add(add_arg) {} + double val_real(); + const char *func_name() const { return name; } + void fix_length_and_dec() + { decimals= NOT_FIXED_DEC; max_length= float_length(decimals); } +}; + + +class Item_func_min_max :public Item_func +{ + Item_result cmp_type; + String tmp_value; + int cmp_sign; + /* TRUE <=> arguments should be compared in the DATETIME context. */ + bool compare_as_dates; + /* An item used for issuing warnings while string to DATETIME conversion. */ + Item *datetime_item; + THD *thd; +protected: + enum_field_types cached_field_type; +public: + Item_func_min_max(List &list,int cmp_sign_arg) :Item_func(list), + cmp_type(INT_RESULT), cmp_sign(cmp_sign_arg), compare_as_dates(FALSE), + datetime_item(0) {} + double val_real(); + longlong val_int(); + String *val_str(String *); + my_decimal *val_decimal(my_decimal *); + void fix_length_and_dec(); + enum Item_result result_type () const { return cmp_type; } + bool result_as_longlong() { return compare_as_dates; }; + uint cmp_datetimes(ulonglong *value); + enum_field_types field_type() const { return cached_field_type; } +}; + +class Item_func_min :public Item_func_min_max +{ +public: + Item_func_min(List &list) :Item_func_min_max(list,1) {} + const char *func_name() const { return "least"; } +}; + +class Item_func_max :public Item_func_min_max +{ +public: + Item_func_max(List &list) :Item_func_min_max(list,-1) {} + const char *func_name() const { return "greatest"; } +}; + + +/* + Objects of this class are used for ROLLUP queries to wrap up + each constant item referred to in GROUP BY list. +*/ + +class Item_func_rollup_const :public Item_func +{ +public: + Item_func_rollup_const(Item *a) :Item_func(a) + { + name= a->name; + name_length= a->name_length; + } + double val_real() { return args[0]->val_real(); } + longlong val_int() { return args[0]->val_int(); } + String *val_str(String *str) { return args[0]->val_str(str); } + my_decimal *val_decimal(my_decimal *dec) { return args[0]->val_decimal(dec); } + const char *func_name() const { return "rollup_const"; } + bool const_item() const { return 0; } + Item_result result_type() const { return args[0]->result_type(); } + void fix_length_and_dec() + { + collation= args[0]->collation; + max_length= args[0]->max_length; + decimals=args[0]->decimals; + /* The item could be a NULL constant. */ + null_value= args[0]->is_null(); + } +}; + + +class Item_func_length :public Item_int_func +{ + String value; +public: + Item_func_length(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "length"; } + void fix_length_and_dec() { max_length=10; } +}; + +class Item_func_bit_length :public Item_func_length +{ +public: + Item_func_bit_length(Item *a) :Item_func_length(a) {} + longlong val_int() + { DBUG_ASSERT(fixed == 1); return Item_func_length::val_int()*8; } + const char *func_name() const { return "bit_length"; } +}; + +class Item_func_char_length :public Item_int_func +{ + String value; +public: + Item_func_char_length(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "char_length"; } + void fix_length_and_dec() { max_length=10; } +}; + +class Item_func_coercibility :public Item_int_func +{ +public: + Item_func_coercibility(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "coercibility"; } + void fix_length_and_dec() { max_length=10; maybe_null= 0; } + table_map not_null_tables() const { return 0; } +}; + +class Item_func_locate :public Item_int_func +{ + String value1,value2; + DTCollation cmp_collation; +public: + Item_func_locate(Item *a,Item *b) :Item_int_func(a,b) {} + Item_func_locate(Item *a,Item *b,Item *c) :Item_int_func(a,b,c) {} + const char *func_name() const { return "locate"; } + longlong val_int(); + void fix_length_and_dec(); + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_field :public Item_int_func +{ + String value,tmp; + Item_result cmp_type; + DTCollation cmp_collation; +public: + Item_func_field(List &list) :Item_int_func(list) {} + longlong val_int(); + const char *func_name() const { return "field"; } + void fix_length_and_dec(); +}; + + +class Item_func_ascii :public Item_int_func +{ + String value; +public: + Item_func_ascii(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "ascii"; } + void fix_length_and_dec() { max_length=3; } +}; + +class Item_func_ord :public Item_int_func +{ + String value; +public: + Item_func_ord(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "ord"; } +}; + +class Item_func_find_in_set :public Item_int_func +{ + String value,value2; + uint enum_value; + ulonglong enum_bit; + DTCollation cmp_collation; +public: + Item_func_find_in_set(Item *a,Item *b) :Item_int_func(a,b),enum_value(0) {} + longlong val_int(); + const char *func_name() const { return "find_in_set"; } + void fix_length_and_dec(); +}; + +/* Base class for all bit functions: '~', '|', '^', '&', '>>', '<<' */ + +class Item_func_bit: public Item_int_func +{ +public: + Item_func_bit(Item *a, Item *b) :Item_int_func(a, b) {} + Item_func_bit(Item *a) :Item_int_func(a) {} + void fix_length_and_dec() { unsigned_flag= 1; } + + virtual inline void print(String *str, enum_query_type query_type) + { + print_op(str, query_type); + } +}; + +class Item_func_bit_or :public Item_func_bit +{ +public: + Item_func_bit_or(Item *a, Item *b) :Item_func_bit(a, b) {} + longlong val_int(); + const char *func_name() const { return "|"; } +}; + +class Item_func_bit_and :public Item_func_bit +{ +public: + Item_func_bit_and(Item *a, Item *b) :Item_func_bit(a, b) {} + longlong val_int(); + const char *func_name() const { return "&"; } +}; + +class Item_func_bit_count :public Item_int_func +{ +public: + Item_func_bit_count(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "bit_count"; } + void fix_length_and_dec() { max_length=2; } +}; + +class Item_func_shift_left :public Item_func_bit +{ +public: + Item_func_shift_left(Item *a, Item *b) :Item_func_bit(a, b) {} + longlong val_int(); + const char *func_name() const { return "<<"; } +}; + +class Item_func_shift_right :public Item_func_bit +{ +public: + Item_func_shift_right(Item *a, Item *b) :Item_func_bit(a, b) {} + longlong val_int(); + const char *func_name() const { return ">>"; } +}; + +class Item_func_bit_neg :public Item_func_bit +{ +public: + Item_func_bit_neg(Item *a) :Item_func_bit(a) {} + longlong val_int(); + const char *func_name() const { return "~"; } + + virtual inline void print(String *str, enum_query_type query_type) + { + Item_func::print(str, query_type); + } +}; + + +class Item_func_last_insert_id :public Item_int_func +{ +public: + Item_func_last_insert_id() :Item_int_func() {} + Item_func_last_insert_id(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "last_insert_id"; } + void fix_length_and_dec() + { + if (arg_count) + max_length= args[0]->max_length; + } + bool fix_fields(THD *thd, Item **ref); +}; + + +class Item_func_benchmark :public Item_int_func +{ +public: + Item_func_benchmark(Item *count_expr, Item *expr) + :Item_int_func(count_expr, expr) + {} + longlong val_int(); + const char *func_name() const { return "benchmark"; } + void fix_length_and_dec() { max_length=1; maybe_null=0; } + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_sleep :public Item_int_func +{ +public: + Item_func_sleep(Item *a) :Item_int_func(a) {} + bool const_item() const { return 0; } + const char *func_name() const { return "sleep"; } + void update_used_tables() + { + Item_int_func::update_used_tables(); + used_tables_cache|= RAND_TABLE_BIT; + } + longlong val_int(); +}; + + + +#ifdef HAVE_DLOPEN + +class Item_udf_func :public Item_func +{ +protected: + udf_handler udf; + +public: + Item_udf_func(udf_func *udf_arg) + :Item_func(), udf(udf_arg) {} + Item_udf_func(udf_func *udf_arg, List &list) + :Item_func(list), udf(udf_arg) {} + const char *func_name() const { return udf.name(); } + enum Functype functype() const { return UDF_FUNC; } + bool fix_fields(THD *thd, Item **ref) + { + DBUG_ASSERT(fixed == 0); + bool res= udf.fix_fields(thd, this, arg_count, args); + used_tables_cache= udf.used_tables_cache; + const_item_cache= udf.const_item_cache; + fixed= 1; + return res; + } + void update_used_tables() + { + /* + TODO: Make a member in UDF_INIT and return if a UDF is deterministic or + not. + Currently UDF_INIT has a member (const_item) that is an in/out + parameter to the init() call. + The code in udf_handler::fix_fields also duplicates the arguments + handling code in Item_func::fix_fields(). + + The lack of information if a UDF is deterministic makes writing + a correct update_used_tables() for UDFs impossible. + One solution to this would be : + - Add a is_deterministic member of UDF_INIT + - (optionally) deprecate the const_item member of UDF_INIT + - Take away the duplicate code from udf_handler::fix_fields() and + make Item_udf_func call Item_func::fix_fields() to process its + arguments as for any other function. + - Store the deterministic flag returned by _init into the + udf_handler. + - Don't implement Item_udf_func::fix_fields, implement + Item_udf_func::fix_length_and_dec() instead (similar to non-UDF + functions). + - Override Item_func::update_used_tables to call + Item_func::update_used_tables() and add a RAND_TABLE_BIT to the + result of Item_func::update_used_tables() if the UDF is + non-deterministic. + - (optionally) rename RAND_TABLE_BIT to NONDETERMINISTIC_BIT to + better describe its usage. + + The above would require a change of the UDF API. + Until that change is done here's how the current code works: + We call Item_func::update_used_tables() only when we know that + the function depends on real non-const tables and is deterministic. + This can be done only because we know that the optimizer will + call update_used_tables() only when there's possibly a new const + table. So update_used_tables() can only make a Item_func more + constant than it is currently. + That's why we don't need to do anything if a function is guaranteed + to return non-constant (it's non-deterministic) or is already a + const. + */ + if ((used_tables_cache & ~PSEUDO_TABLE_BITS) && + !(used_tables_cache & RAND_TABLE_BIT)) + { + Item_func::update_used_tables(); + if (!const_item_cache && !used_tables_cache) + used_tables_cache= RAND_TABLE_BIT; + } + } + void cleanup(); + Item_result result_type () const { return udf.result_type(); } + table_map not_null_tables() const { return 0; } + bool is_expensive() { return 1; } + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_udf_float :public Item_udf_func +{ + public: + Item_func_udf_float(udf_func *udf_arg) + :Item_udf_func(udf_arg) {} + Item_func_udf_float(udf_func *udf_arg, + List &list) + :Item_udf_func(udf_arg, list) {} + longlong val_int() + { + DBUG_ASSERT(fixed == 1); + return (longlong) rint(Item_func_udf_float::val_real()); + } + my_decimal *val_decimal(my_decimal *dec_buf) + { + double res=val_real(); + if (null_value) + return NULL; + double2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf); + return dec_buf; + } + double val_real(); + String *val_str(String *str); + void fix_length_and_dec() { fix_num_length_and_dec(); } +}; + + +class Item_func_udf_int :public Item_udf_func +{ +public: + Item_func_udf_int(udf_func *udf_arg) + :Item_udf_func(udf_arg) {} + Item_func_udf_int(udf_func *udf_arg, + List &list) + :Item_udf_func(udf_arg, list) {} + longlong val_int(); + double val_real() { return (double) Item_func_udf_int::val_int(); } + String *val_str(String *str); + enum Item_result result_type () const { return INT_RESULT; } + void fix_length_and_dec() { decimals= 0; max_length= 21; } +}; + + +class Item_func_udf_decimal :public Item_udf_func +{ +public: + Item_func_udf_decimal(udf_func *udf_arg) + :Item_udf_func(udf_arg) {} + Item_func_udf_decimal(udf_func *udf_arg, List &list) + :Item_udf_func(udf_arg, list) {} + longlong val_int(); + double val_real(); + my_decimal *val_decimal(my_decimal *); + String *val_str(String *str); + enum Item_result result_type () const { return DECIMAL_RESULT; } + void fix_length_and_dec(); +}; + + +class Item_func_udf_str :public Item_udf_func +{ +public: + Item_func_udf_str(udf_func *udf_arg) + :Item_udf_func(udf_arg) {} + Item_func_udf_str(udf_func *udf_arg, List &list) + :Item_udf_func(udf_arg, list) {} + String *val_str(String *); + double val_real() + { + int err_not_used; + char *end_not_used; + String *res; + res= val_str(&str_value); + return res ? my_strntod(res->charset(),(char*) res->ptr(), + res->length(), &end_not_used, &err_not_used) : 0.0; + } + longlong val_int() + { + int err_not_used; + String *res; res=val_str(&str_value); + return res ? my_strntoll(res->charset(),res->ptr(),res->length(),10, + (char**) 0, &err_not_used) : (longlong) 0; + } + my_decimal *val_decimal(my_decimal *dec_buf) + { + String *res=val_str(&str_value); + if (!res) + return NULL; + string2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf); + return dec_buf; + } + enum Item_result result_type () const { return STRING_RESULT; } + void fix_length_and_dec(); +}; + +#else /* Dummy functions to get sql_yacc.cc compiled */ + +class Item_func_udf_float :public Item_real_func +{ + public: + Item_func_udf_float(udf_func *udf_arg) + :Item_real_func() {} + Item_func_udf_float(udf_func *udf_arg, List &list) + :Item_real_func(list) {} + double val_real() { DBUG_ASSERT(fixed == 1); return 0.0; } +}; + + +class Item_func_udf_int :public Item_int_func +{ +public: + Item_func_udf_int(udf_func *udf_arg) + :Item_int_func() {} + Item_func_udf_int(udf_func *udf_arg, List &list) + :Item_int_func(list) {} + longlong val_int() { DBUG_ASSERT(fixed == 1); return 0; } +}; + + +class Item_func_udf_decimal :public Item_int_func +{ +public: + Item_func_udf_decimal(udf_func *udf_arg) + :Item_int_func() {} + Item_func_udf_decimal(udf_func *udf_arg, List &list) + :Item_int_func(list) {} + my_decimal *val_decimal(my_decimal *) { DBUG_ASSERT(fixed == 1); return 0; } +}; + + +class Item_func_udf_str :public Item_func +{ +public: + Item_func_udf_str(udf_func *udf_arg) + :Item_func() {} + Item_func_udf_str(udf_func *udf_arg, List &list) + :Item_func(list) {} + String *val_str(String *) + { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } + double val_real() { DBUG_ASSERT(fixed == 1); null_value= 1; return 0.0; } + longlong val_int() { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } + enum Item_result result_type () const { return STRING_RESULT; } + void fix_length_and_dec() { maybe_null=1; max_length=0; } +}; + +#endif /* HAVE_DLOPEN */ + +/* +** User level locks +*/ + +class User_level_lock; +void item_user_lock_init(void); +void item_user_lock_release(User_level_lock *ull); +void item_user_lock_free(void); + +class Item_func_get_lock :public Item_int_func +{ + String value; + public: + Item_func_get_lock(Item *a,Item *b) :Item_int_func(a,b) {} + longlong val_int(); + const char *func_name() const { return "get_lock"; } + void fix_length_and_dec() { max_length=1; maybe_null=1;} +}; + +class Item_func_release_lock :public Item_int_func +{ + String value; +public: + Item_func_release_lock(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "release_lock"; } + void fix_length_and_dec() { max_length=1; maybe_null=1;} +}; + +/* replication functions */ + +class Item_master_pos_wait :public Item_int_func +{ + String value; +public: + Item_master_pos_wait(Item *a,Item *b) :Item_int_func(a,b) {} + Item_master_pos_wait(Item *a,Item *b,Item *c) :Item_int_func(a,b,c) {} + longlong val_int(); + const char *func_name() const { return "master_pos_wait"; } + void fix_length_and_dec() { max_length=21; maybe_null=1;} +}; + + +/* Handling of user definable variables */ + +class user_var_entry; + +class Item_func_set_user_var :public Item_func +{ + enum Item_result cached_result_type; + user_var_entry *entry; + /* + The entry_thread_id variable is used: + 1) to skip unnecessary updates of the entry field (see above); + 2) to reset the entry field that was initialized in the other thread + (for example, an item tree of a trigger that updates user variables + may be shared between several connections, and the entry_thread_id field + prevents updates of one connection user variables from a concurrent + connection calling the same trigger that initially updated some + user variable it the first connection context). + */ + my_thread_id entry_thread_id; + char buffer[MAX_FIELD_WIDTH]; + String value; + my_decimal decimal_buff; + bool null_item; + union + { + longlong vint; + double vreal; + String *vstr; + my_decimal *vdec; + } save_result; + +public: + LEX_STRING name; // keep it public + Item_func_set_user_var(LEX_STRING a,Item *b) + :Item_func(b), cached_result_type(INT_RESULT), + entry(NULL), entry_thread_id(0), name(a) + {} + enum Functype functype() const { return SUSERVAR_FUNC; } + double val_real(); + longlong val_int(); + String *val_str(String *str); + my_decimal *val_decimal(my_decimal *); + double val_result(); + longlong val_int_result(); + String *str_result(String *str); + my_decimal *val_decimal_result(my_decimal *); + bool is_null_result(); + bool update_hash(void *ptr, uint length, enum Item_result type, + CHARSET_INFO *cs, Derivation dv, bool unsigned_arg); + bool send(Protocol *protocol, String *str_arg); + void make_field(Send_field *tmp_field); + bool check(bool use_result_field); + void save_item_result(Item *item); + bool update(); + enum Item_result result_type () const { return cached_result_type; } + bool fix_fields(THD *thd, Item **ref); + void fix_length_and_dec(); + virtual void print(String *str, enum_query_type query_type); + void print_as_stmt(String *str, enum_query_type query_type); + const char *func_name() const { return "set_user_var"; } + int save_in_field(Field *field, bool no_conversions, + bool can_use_result_field); + int save_in_field(Field *field, bool no_conversions) + { + return save_in_field(field, no_conversions, 1); + } + void save_org_in_field(Field *field) { (void)save_in_field(field, 1, 0); } + bool register_field_in_read_map(uchar *arg); + bool set_entry(THD *thd, bool create_if_not_exists); + void cleanup(); +}; + + +class Item_func_get_user_var :public Item_func, + private Settable_routine_parameter +{ + user_var_entry *var_entry; + Item_result m_cached_result_type; + +public: + LEX_STRING name; // keep it public + Item_func_get_user_var(LEX_STRING a): + Item_func(), m_cached_result_type(STRING_RESULT), name(a) {} + enum Functype functype() const { return GUSERVAR_FUNC; } + LEX_STRING get_name() { return name; } + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal*); + String *val_str(String* str); + void fix_length_and_dec(); + virtual void print(String *str, enum_query_type query_type); + enum Item_result result_type() const; + /* + We must always return variables as strings to guard against selects of type + select @t1:=1,@t1,@t:="hello",@t from foo where (@t1:= t2.b) + */ + const char *func_name() const { return "get_user_var"; } + bool const_item() const; + table_map used_tables() const + { return const_item() ? 0 : RAND_TABLE_BIT; } + bool eq(const Item *item, bool binary_cmp) const; + uint decimal_precision() const; +private: + bool set_value(THD *thd, sp_rcontext *ctx, Item **it); + +public: + Settable_routine_parameter *get_settable_routine_parameter() + { + return this; + } +}; + + +/* + This item represents user variable used as out parameter (e.g in LOAD DATA), + and it is supposed to be used only for this purprose. So it is simplified + a lot. Actually you should never obtain its value. + + The only two reasons for this thing being an Item is possibility to store it + in List and desire to place this code somewhere near other functions + working with user variables. +*/ +class Item_user_var_as_out_param :public Item +{ + LEX_STRING name; + user_var_entry *entry; +public: + Item_user_var_as_out_param(LEX_STRING a) : name(a) {} + /* We should return something different from FIELD_ITEM here */ + enum Type type() const { return STRING_ITEM;} + double val_real(); + longlong val_int(); + String *val_str(String *str); + my_decimal *val_decimal(my_decimal *decimal_buffer); + /* fix_fields() binds variable name with its entry structure */ + bool fix_fields(THD *thd, Item **ref); + virtual void print(String *str, enum_query_type query_type); + void set_null_value(CHARSET_INFO* cs); + void set_value(const char *str, uint length, CHARSET_INFO* cs); +}; + + +/* A system variable */ + +#define GET_SYS_VAR_CACHE_LONG 1 +#define GET_SYS_VAR_CACHE_DOUBLE 2 +#define GET_SYS_VAR_CACHE_STRING 4 + +class Item_func_get_system_var :public Item_func +{ + sys_var *var; + enum_var_type var_type, orig_var_type; + LEX_STRING component; + longlong cached_llval; + double cached_dval; + String cached_strval; + my_bool cached_null_value; + query_id_t used_query_id; + uchar cache_present; + +public: + Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg, + LEX_STRING *component_arg, const char *name_arg, + size_t name_len_arg); + enum Functype functype() const { return GSYSVAR_FUNC; } + void update_null_value(); + void fix_length_and_dec(); + void print(String *str, enum_query_type query_type); + bool const_item() const { return true; } + table_map used_tables() const { return 0; } + enum Item_result result_type() const; + enum_field_types field_type() const; + double val_real(); + longlong val_int(); + String* val_str(String*); + /* TODO: fix to support views */ + const char *func_name() const { return "get_system_var"; } + /** + Indicates whether this system variable is written to the binlog or not. + + Variables are written to the binlog as part of "status_vars" in + Query_log_event, as an Intvar_log_event, or a Rand_log_event. + + @return true if the variable is written to the binlog, false otherwise. + */ + bool is_written_to_binlog(); + bool eq(const Item *item, bool binary_cmp) const; + + void cleanup(); +}; + + +class Item_func_inet_aton : public Item_int_func +{ +public: + Item_func_inet_aton(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "inet_aton"; } + void fix_length_and_dec() { decimals= 0; max_length= 21; maybe_null= 1; unsigned_flag= 1;} +}; + + +/* for fulltext search */ +#include + +class Item_func_match :public Item_real_func +{ +public: + uint key, flags; + bool join_key; + DTCollation cmp_collation; + FT_INFO *ft_handler; + TABLE *table; + Item_func_match *master; // for master-slave optimization + Item *concat_ws; // Item_func_concat_ws + String value; // value of concat_ws + String search_value; // key_item()'s value converted to cmp_collation + + Item_func_match(List &a, uint b): Item_real_func(a), key(0), flags(b), + join_key(0), ft_handler(0), table(0), master(0), concat_ws(0) { } + void cleanup() + { + DBUG_ENTER("Item_func_match"); + Item_real_func::cleanup(); + if (!master && ft_handler) + ft_handler->please->close_search(ft_handler); + ft_handler= 0; + concat_ws= 0; + table= 0; // required by Item_func_match::eq() + DBUG_VOID_RETURN; + } + enum Functype functype() const { return FT_FUNC; } + const char *func_name() const { return "match"; } + void update_used_tables() {} + table_map not_null_tables() const { return 0; } + bool fix_fields(THD *thd, Item **ref); + bool eq(const Item *, bool binary_cmp) const; + /* The following should be safe, even if we compare doubles */ + longlong val_int() { DBUG_ASSERT(fixed == 1); return val_real() != 0.0; } + double val_real(); + virtual void print(String *str, enum_query_type query_type); + + bool fix_index(); + void init_search(bool no_order); +}; + + +class Item_func_bit_xor : public Item_func_bit +{ +public: + Item_func_bit_xor(Item *a, Item *b) :Item_func_bit(a, b) {} + longlong val_int(); + const char *func_name() const { return "^"; } +}; + +class Item_func_is_free_lock :public Item_int_func +{ + String value; +public: + Item_func_is_free_lock(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "is_free_lock"; } + void fix_length_and_dec() { decimals=0; max_length=1; maybe_null=1;} +}; + +class Item_func_is_used_lock :public Item_int_func +{ + String value; +public: + Item_func_is_used_lock(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "is_used_lock"; } + void fix_length_and_dec() { decimals=0; max_length=10; maybe_null=1;} +}; + +/* For type casts */ + +enum Cast_target +{ + ITEM_CAST_BINARY, ITEM_CAST_SIGNED_INT, ITEM_CAST_UNSIGNED_INT, + ITEM_CAST_DATE, ITEM_CAST_TIME, ITEM_CAST_DATETIME, ITEM_CAST_CHAR, + ITEM_CAST_DECIMAL +}; + + +class Item_func_row_count :public Item_int_func +{ +public: + Item_func_row_count() :Item_int_func() {} + longlong val_int(); + const char *func_name() const { return "row_count"; } + void fix_length_and_dec() { decimals= 0; maybe_null=0; } +}; + + +/* + * + * Stored FUNCTIONs + * + */ + +class sp_head; +class sp_name; +struct st_sp_security_context; + +class Item_func_sp :public Item_func +{ +private: + Name_resolution_context *context; + sp_name *m_name; + mutable sp_head *m_sp; + TABLE *dummy_table; + uchar result_buf[64]; + /* + The result field of the concrete stored function. + */ + Field *sp_result_field; + + bool execute(); + bool execute_impl(THD *thd); + bool init_result_field(THD *thd); + +public: + + Item_func_sp(Name_resolution_context *context_arg, sp_name *name); + + Item_func_sp(Name_resolution_context *context_arg, + sp_name *name, List &list); + + virtual ~Item_func_sp() + {} + + void update_used_tables(); + + void cleanup(); + + const char *func_name() const; + + enum enum_field_types field_type() const; + + Field *tmp_table_field(TABLE *t_arg); + + void make_field(Send_field *tmp_field); + + Item_result result_type() const; + + longlong val_int() + { + if (execute()) + return (longlong) 0; + return sp_result_field->val_int(); + } + + double val_real() + { + if (execute()) + return 0.0; + return sp_result_field->val_real(); + } + + my_decimal *val_decimal(my_decimal *dec_buf) + { + if (execute()) + return NULL; + return sp_result_field->val_decimal(dec_buf); + } + + String *val_str(String *str) + { + String buf; + char buff[20]; + buf.set(buff, 20, str->charset()); + buf.length(0); + if (execute()) + return NULL; + /* + result_field will set buf pointing to internal buffer + of the resul_field. Due to this it will change any time + when SP is executed. In order to prevent occasional + corruption of returned value, we make here a copy. + */ + sp_result_field->val_str(&buf); + str->copy(buf); + return str; + } + + virtual bool change_context_processor(uchar *cntx) + { context= (Name_resolution_context *)cntx; return FALSE; } + + bool sp_check_access(THD * thd); + virtual enum Functype functype() const { return FUNC_SP; } + + bool fix_fields(THD *thd, Item **ref); + void fix_length_and_dec(void); + bool is_expensive() { return 1; } + + inline Field *get_sp_result_field() + { + return sp_result_field; + } +}; + + +class Item_func_found_rows :public Item_int_func +{ +public: + Item_func_found_rows() :Item_int_func() {} + longlong val_int(); + const char *func_name() const { return "found_rows"; } + void fix_length_and_dec() { decimals= 0; maybe_null=0; } +}; + + +void uuid_short_init(); + +class Item_func_uuid_short :public Item_int_func +{ +public: + Item_func_uuid_short() :Item_int_func() {} + const char *func_name() const { return "uuid_short"; } + longlong val_int(); + void fix_length_and_dec() + { max_length= 21; unsigned_flag=1; } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + diff --git a/dbcon/mysql/item_strfunc.cc b/dbcon/mysql/item_strfunc.cc new file mode 100644 index 00000000..1ea9a273 --- /dev/null +++ b/dbcon/mysql/item_strfunc.cc @@ -0,0 +1,3558 @@ +/* Copyright (C) 2000-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/** + @file + + @brief + This file defines all string functions + + @warning + Some string functions don't always put and end-null on a String. + (This shouldn't be needed) +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include +#include "my_md5.h" +#include "sha1.h" +#include "my_aes.h" +#include +C_MODE_START +#include "../mysys/my_static.h" // For soundex_map +C_MODE_END + +String my_empty_string("",default_charset_info); + + + + +bool Item_str_func::fix_fields(THD *thd, Item **ref) +{ + bool res= Item_func::fix_fields(thd, ref); + /* + In Item_str_func::check_well_formed_result() we may set null_value + flag on the same condition as in test() below. + */ + maybe_null= (maybe_null || + test(thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES))); + return res; +} + + +my_decimal *Item_str_func::val_decimal(my_decimal *decimal_value) +{ + DBUG_ASSERT(fixed == 1); + char buff[64]; + String *res, tmp(buff,sizeof(buff), &my_charset_bin); + res= val_str(&tmp); + if (!res) + return 0; + (void)str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(), + res->length(), res->charset(), decimal_value); + return decimal_value; +} + + +double Item_str_func::val_real() +{ + DBUG_ASSERT(fixed == 1); + int err_not_used; + char *end_not_used, buff[64]; + String *res, tmp(buff,sizeof(buff), &my_charset_bin); + res= val_str(&tmp); + return res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(), + &end_not_used, &err_not_used) : 0.0; +} + + +longlong Item_str_func::val_int() +{ + DBUG_ASSERT(fixed == 1); + int err; + char buff[22]; + String *res, tmp(buff,sizeof(buff), &my_charset_bin); + res= val_str(&tmp); + return (res ? + my_strntoll(res->charset(), res->ptr(), res->length(), 10, NULL, + &err) : + (longlong) 0); +} + + +String *Item_func_md5::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String * sptr= args[0]->val_str(str); + str->set_charset(&my_charset_bin); + if (sptr) + { + uchar digest[16]; + + null_value=0; + MY_MD5_HASH(digest,(uchar *) sptr->ptr(), sptr->length()); + if (str->alloc(32)) // Ensure that memory is free + { + null_value=1; + return 0; + } + sprintf((char *) str->ptr(), + "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + digest[0], digest[1], digest[2], digest[3], + digest[4], digest[5], digest[6], digest[7], + digest[8], digest[9], digest[10], digest[11], + digest[12], digest[13], digest[14], digest[15]); + str->length((uint) 32); + return str; + } + null_value=1; + return 0; +} + + +void Item_func_md5::fix_length_and_dec() +{ + max_length=32; + /* + The MD5() function treats its parameter as being a case sensitive. Thus + we set binary collation on it so different instances of MD5() will be + compared properly. + */ + args[0]->collation.set( + get_charset_by_csname(args[0]->collation.collation->csname, + MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE); +} + + +String *Item_func_sha::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String * sptr= args[0]->val_str(str); + str->set_charset(&my_charset_bin); + if (sptr) /* If we got value different from NULL */ + { + SHA1_CONTEXT context; /* Context used to generate SHA1 hash */ + /* Temporary buffer to store 160bit digest */ + uint8 digest[SHA1_HASH_SIZE]; + mysql_sha1_reset(&context); /* We do not have to check for error here */ + /* No need to check error as the only case would be too long message */ + mysql_sha1_input(&context, + (const uchar *) sptr->ptr(), sptr->length()); + /* Ensure that memory is free and we got result */ + if (!( str->alloc(SHA1_HASH_SIZE*2) || + (mysql_sha1_result(&context,digest)))) + { + sprintf((char *) str->ptr(), + "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\ +%02x%02x%02x%02x%02x%02x%02x%02x", + digest[0], digest[1], digest[2], digest[3], + digest[4], digest[5], digest[6], digest[7], + digest[8], digest[9], digest[10], digest[11], + digest[12], digest[13], digest[14], digest[15], + digest[16], digest[17], digest[18], digest[19]); + + str->length((uint) SHA1_HASH_SIZE*2); + null_value=0; + return str; + } + } + null_value=1; + return 0; +} + +void Item_func_sha::fix_length_and_dec() +{ + max_length=SHA1_HASH_SIZE*2; // size of hex representation of hash + /* + The SHA() function treats its parameter as being a case sensitive. Thus + we set binary collation on it so different instances of MD5() will be + compared properly. + */ + args[0]->collation.set( + get_charset_by_csname(args[0]->collation.collation->csname, + MY_CS_BINSORT,MYF(0)), DERIVATION_COERCIBLE); +} + + +/* Implementation of AES encryption routines */ + +String *Item_func_aes_encrypt::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char key_buff[80]; + String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info); + String *sptr= args[0]->val_str(str); // String to encrypt + String *key= args[1]->val_str(&tmp_key_value); // key + int aes_length; + if (sptr && key) // we need both arguments to be not NULL + { + null_value=0; + aes_length=my_aes_get_size(sptr->length()); // Calculate result length + + if (!str_value.alloc(aes_length)) // Ensure that memory is free + { + // finally encrypt directly to allocated buffer. + if (my_aes_encrypt(sptr->ptr(),sptr->length(), (char*) str_value.ptr(), + key->ptr(), key->length()) == aes_length) + { + // We got the expected result length + str_value.length((uint) aes_length); + return &str_value; + } + } + } + null_value=1; + return 0; +} + + +void Item_func_aes_encrypt::fix_length_and_dec() +{ + max_length=my_aes_get_size(args[0]->max_length); +} + + +String *Item_func_aes_decrypt::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char key_buff[80]; + String tmp_key_value(key_buff, sizeof(key_buff), system_charset_info); + String *sptr, *key; + DBUG_ENTER("Item_func_aes_decrypt::val_str"); + + sptr= args[0]->val_str(str); // String to decrypt + key= args[1]->val_str(&tmp_key_value); // Key + if (sptr && key) // Need to have both arguments not NULL + { + null_value=0; + if (!str_value.alloc(sptr->length())) // Ensure that memory is free + { + // finally decrypt directly to allocated buffer. + int length; + length=my_aes_decrypt(sptr->ptr(), sptr->length(), + (char*) str_value.ptr(), + key->ptr(), key->length()); + if (length >= 0) // if we got correct data data + { + str_value.length((uint) length); + DBUG_RETURN(&str_value); + } + } + } + // Bad parameters. No memory or bad data will all go here + null_value=1; + DBUG_RETURN(0); +} + + +void Item_func_aes_decrypt::fix_length_and_dec() +{ + max_length=args[0]->max_length; + maybe_null= 1; +} + + +/** + Concatenate args with the following premises: + If only one arg (which is ok), return value of arg; + Don't reallocate val_str() if not absolute necessary. +*/ + +String *Item_func_concat::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res,*res2,*use_as_buff; + uint i; + bool is_const= 0; + + null_value=0; + if (!(res=args[0]->val_str(str))) + goto null; + use_as_buff= &tmp_value; + /* Item_subselect in --ps-protocol mode will state it as a non-const */ + is_const= args[0]->const_item() || !args[0]->used_tables(); + for (i=1 ; i < arg_count ; i++) + { + if (res->length() == 0) + { + if (!(res=args[i]->val_str(str))) + goto null; + /* + CONCAT accumulates its result in the result of its the first + non-empty argument. Because of this we need is_const to be + evaluated only for it. + */ + is_const= args[i]->const_item() || !args[i]->used_tables(); + } + else + { + if (!(res2=args[i]->val_str(use_as_buff))) + goto null; + if (res2->length() == 0) + continue; + if (res->length()+res2->length() > + current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(), + current_thd->variables.max_allowed_packet); + goto null; + } + if (!is_const && res->alloced_length() >= res->length()+res2->length()) + { // Use old buffer + res->append(*res2); + } + else if (str->alloced_length() >= res->length()+res2->length()) + { + if (str == res2) + str->replace(0,0,*res); + else + { + str->copy(*res); + str->append(*res2); + } + res= str; + use_as_buff= &tmp_value; + } + else if (res == &tmp_value) + { + if (res->append(*res2)) // Must be a blob + goto null; + } + else if (res2 == &tmp_value) + { // This can happend only 1 time + if (tmp_value.replace(0,0,*res)) + goto null; + res= &tmp_value; + use_as_buff=str; // Put next arg here + } + else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() && + res2->ptr() <= tmp_value.ptr() + tmp_value.alloced_length()) + { + /* + This happens really seldom: + In this case res2 is sub string of tmp_value. We will + now work in place in tmp_value to set it to res | res2 + */ + /* Chop the last characters in tmp_value that isn't in res2 */ + tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) + + res2->length()); + /* Place res2 at start of tmp_value, remove chars before res2 */ + if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()), + *res)) + goto null; + res= &tmp_value; + use_as_buff=str; // Put next arg here + } + else + { // Two big const strings + /* + NOTE: We should be prudent in the initial allocation unit -- the + size of the arguments is a function of data distribution, which + can be any. Instead of overcommitting at the first row, we grow + the allocated amount by the factor of 2. This ensures that no + more than 25% of memory will be overcommitted on average. + */ + + uint concat_len= res->length() + res2->length(); + + if (tmp_value.alloced_length() < concat_len) + { + if (tmp_value.alloced_length() == 0) + { + if (tmp_value.alloc(concat_len)) + goto null; + } + else + { + uint new_len = max(tmp_value.alloced_length() * 2, concat_len); + + if (tmp_value.realloc(new_len)) + goto null; + } + } + + if (tmp_value.copy(*res) || tmp_value.append(*res2)) + goto null; + + res= &tmp_value; + use_as_buff=str; + } + is_const= 0; + } + } + res->set_charset(collation.collation); + return res; + +null: + null_value=1; + return 0; +} + + +void Item_func_concat::fix_length_and_dec() +{ + ulonglong max_result_length= 0; + + if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1)) + return; + + for (uint i=0 ; i < arg_count ; i++) + { + if (args[i]->collation.collation->mbmaxlen != collation.collation->mbmaxlen) + max_result_length+= (args[i]->max_length / + args[i]->collation.collation->mbmaxlen) * + collation.collation->mbmaxlen; + else + max_result_length+= args[i]->max_length; + } + + if (max_result_length >= MAX_BLOB_WIDTH) + { + max_result_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) max_result_length; +} + +/** + @details + Function des_encrypt() by tonu@spam.ee & monty + Works only if compiled with OpenSSL library support. + @return + A binary string where first character is CHAR(128 | key-number). + If one uses a string key key_number is 127. + Encryption result is longer than original by formula: + @code new_length= org_length + (8-(org_length % 8))+1 @endcode +*/ + +String *Item_func_des_encrypt::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); +#ifdef HAVE_OPENSSL + uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE; + DES_cblock ivec; + struct st_des_keyblock keyblock; + struct st_des_keyschedule keyschedule; + const char *append_str="********"; + uint key_number, res_length, tail; + String *res= args[0]->val_str(str); + + if ((null_value= args[0]->null_value)) + return 0; // ENCRYPT(NULL) == NULL + if ((res_length=res->length()) == 0) + return &my_empty_string; + + if (arg_count == 1) + { + /* Protect against someone doing FLUSH DES_KEY_FILE */ + VOID(pthread_mutex_lock(&LOCK_des_key_file)); + keyschedule= des_keyschedule[key_number=des_default_key]; + VOID(pthread_mutex_unlock(&LOCK_des_key_file)); + } + else if (args[1]->result_type() == INT_RESULT) + { + key_number= (uint) args[1]->val_int(); + if (key_number > 9) + goto error; + VOID(pthread_mutex_lock(&LOCK_des_key_file)); + keyschedule= des_keyschedule[key_number]; + VOID(pthread_mutex_unlock(&LOCK_des_key_file)); + } + else + { + String *keystr=args[1]->val_str(&tmp_value); + if (!keystr) + goto error; + key_number=127; // User key string + + /* We make good 24-byte (168 bit) key from given plaintext key with MD5 */ + bzero((char*) &ivec,sizeof(ivec)); + EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL, + (uchar*) keystr->ptr(), (int) keystr->length(), + 1, (uchar*) &keyblock,ivec); + DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1); + DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2); + DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3); + } + + /* + The problem: DES algorithm requires original data to be in 8-bytes + chunks. Missing bytes get filled with '*'s and result of encryption + can be up to 8 bytes longer than original string. When decrypted, + we do not know the size of original string :( + We add one byte with value 0x1..0x8 as the last byte of the padded + string marking change of string length. + */ + + tail= 8 - (res_length % 8); // 1..8 marking extra length + res_length+=tail; + tmp_arg.realloc(res_length); + tmp_arg.length(0); + tmp_arg.append(res->ptr(), res->length()); + code= ER_OUT_OF_RESOURCES; + if (tmp_arg.append(append_str, tail) || tmp_value.alloc(res_length+1)) + goto error; + tmp_arg[res_length-1]=tail; // save extra length + tmp_value.realloc(res_length+1); + tmp_value.length(res_length+1); + tmp_value[0]=(char) (128 | key_number); + // Real encryption + bzero((char*) &ivec,sizeof(ivec)); + DES_ede3_cbc_encrypt((const uchar*) (tmp_arg.ptr()), + (uchar*) (tmp_value.ptr()+1), + res_length, + &keyschedule.ks1, + &keyschedule.ks2, + &keyschedule.ks3, + &ivec, TRUE); + return &tmp_value; + +error: + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR, + code, ER(code), + "des_encrypt"); +#else + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED), + "des_encrypt","--with-openssl"); +#endif /* HAVE_OPENSSL */ + null_value=1; + return 0; +} + + +String *Item_func_des_decrypt::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); +#ifdef HAVE_OPENSSL + uint code= ER_WRONG_PARAMETERS_TO_PROCEDURE; + DES_cblock ivec; + struct st_des_keyblock keyblock; + struct st_des_keyschedule keyschedule; + String *res= args[0]->val_str(str); + uint length,tail; + + if ((null_value= args[0]->null_value)) + return 0; + length= res->length(); + if (length < 9 || (length % 8) != 1 || !((*res)[0] & 128)) + return res; // Skip decryption if not encrypted + + if (arg_count == 1) // If automatic uncompression + { + uint key_number=(uint) (*res)[0] & 127; + // Check if automatic key and that we have privilege to uncompress using it + if (!(current_thd->security_ctx->master_access & SUPER_ACL) || + key_number > 9) + goto error; + + VOID(pthread_mutex_lock(&LOCK_des_key_file)); + keyschedule= des_keyschedule[key_number]; + VOID(pthread_mutex_unlock(&LOCK_des_key_file)); + } + else + { + // We make good 24-byte (168 bit) key from given plaintext key with MD5 + String *keystr=args[1]->val_str(&tmp_value); + if (!keystr) + goto error; + + bzero((char*) &ivec,sizeof(ivec)); + EVP_BytesToKey(EVP_des_ede3_cbc(),EVP_md5(),NULL, + (uchar*) keystr->ptr(),(int) keystr->length(), + 1,(uchar*) &keyblock,ivec); + // Here we set all 64-bit keys (56 effective) one by one + DES_set_key_unchecked(&keyblock.key1,&keyschedule.ks1); + DES_set_key_unchecked(&keyblock.key2,&keyschedule.ks2); + DES_set_key_unchecked(&keyblock.key3,&keyschedule.ks3); + } + code= ER_OUT_OF_RESOURCES; + if (tmp_value.alloc(length-1)) + goto error; + + bzero((char*) &ivec,sizeof(ivec)); + DES_ede3_cbc_encrypt((const uchar*) res->ptr()+1, + (uchar*) (tmp_value.ptr()), + length-1, + &keyschedule.ks1, + &keyschedule.ks2, + &keyschedule.ks3, + &ivec, FALSE); + /* Restore old length of key */ + if ((tail=(uint) (uchar) tmp_value[length-2]) > 8) + goto wrong_key; // Wrong key + tmp_value.length(length-1-tail); + return &tmp_value; + +error: + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR, + code, ER(code), + "des_decrypt"); +wrong_key: +#else + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_FEATURE_DISABLED, ER(ER_FEATURE_DISABLED), + "des_decrypt","--with-openssl"); +#endif /* HAVE_OPENSSL */ + null_value=1; + return 0; +} + + +/** + concat with separator. First arg is the separator + concat_ws takes at least two arguments. +*/ + +String *Item_func_concat_ws::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char tmp_str_buff[10]; + String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info), + *sep_str, *res, *res2,*use_as_buff; + uint i; + + null_value=0; + if (!(sep_str= args[0]->val_str(&tmp_sep_str))) + goto null; + + use_as_buff= &tmp_value; + str->length(0); // QQ; Should be removed + res=str; + + // Skip until non-null argument is found. + // If not, return the empty string + for (i=1; i < arg_count; i++) + if ((res= args[i]->val_str(str))) + break; + if (i == arg_count) + return &my_empty_string; + + for (i++; i < arg_count ; i++) + { + if (!(res2= args[i]->val_str(use_as_buff))) + continue; // Skip NULL + + if (res->length() + sep_str->length() + res2->length() > + current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(), + current_thd->variables.max_allowed_packet); + goto null; + } + if (res->alloced_length() >= + res->length() + sep_str->length() + res2->length()) + { // Use old buffer + res->append(*sep_str); // res->length() > 0 always + res->append(*res2); + } + else if (str->alloced_length() >= + res->length() + sep_str->length() + res2->length()) + { + /* We have room in str; We can't get any errors here */ + if (str == res2) + { // This is quote uncommon! + str->replace(0,0,*sep_str); + str->replace(0,0,*res); + } + else + { + str->copy(*res); + str->append(*sep_str); + str->append(*res2); + } + res=str; + use_as_buff= &tmp_value; + } + else if (res == &tmp_value) + { + if (res->append(*sep_str) || res->append(*res2)) + goto null; // Must be a blob + } + else if (res2 == &tmp_value) + { // This can happend only 1 time + if (tmp_value.replace(0,0,*sep_str) || tmp_value.replace(0,0,*res)) + goto null; + res= &tmp_value; + use_as_buff=str; // Put next arg here + } + else if (tmp_value.is_alloced() && res2->ptr() >= tmp_value.ptr() && + res2->ptr() < tmp_value.ptr() + tmp_value.alloced_length()) + { + /* + This happens really seldom: + In this case res2 is sub string of tmp_value. We will + now work in place in tmp_value to set it to res | sep_str | res2 + */ + /* Chop the last characters in tmp_value that isn't in res2 */ + tmp_value.length((uint32) (res2->ptr() - tmp_value.ptr()) + + res2->length()); + /* Place res2 at start of tmp_value, remove chars before res2 */ + if (tmp_value.replace(0,(uint32) (res2->ptr() - tmp_value.ptr()), + *res) || + tmp_value.replace(res->length(),0, *sep_str)) + goto null; + res= &tmp_value; + use_as_buff=str; // Put next arg here + } + else + { // Two big const strings + /* + NOTE: We should be prudent in the initial allocation unit -- the + size of the arguments is a function of data distribution, which can + be any. Instead of overcommitting at the first row, we grow the + allocated amount by the factor of 2. This ensures that no more than + 25% of memory will be overcommitted on average. + */ + + uint concat_len= res->length() + sep_str->length() + res2->length(); + + if (tmp_value.alloced_length() < concat_len) + { + if (tmp_value.alloced_length() == 0) + { + if (tmp_value.alloc(concat_len)) + goto null; + } + else + { + uint new_len = max(tmp_value.alloced_length() * 2, concat_len); + + if (tmp_value.realloc(new_len)) + goto null; + } + } + + if (tmp_value.copy(*res) || + tmp_value.append(*sep_str) || + tmp_value.append(*res2)) + goto null; + res= &tmp_value; + use_as_buff=str; + } + } + res->set_charset(collation.collation); + return res; + +null: + null_value=1; + return 0; +} + + +void Item_func_concat_ws::fix_length_and_dec() +{ + ulonglong max_result_length; + + if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1)) + return; + + /* + arg_count cannot be less than 2, + it is done on parser level in sql_yacc.yy + so, (arg_count - 2) is safe here. + */ + max_result_length= (ulonglong) args[0]->max_length * (arg_count - 2); + for (uint i=1 ; i < arg_count ; i++) + max_result_length+=args[i]->max_length; + + if (max_result_length >= MAX_BLOB_WIDTH) + { + max_result_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) max_result_length; +} + + +String *Item_func_reverse::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res = args[0]->val_str(str); + char *ptr, *end, *tmp; + + if ((null_value=args[0]->null_value)) + return 0; + /* An empty string is a special case as the string pointer may be null */ + if (!res->length()) + return &my_empty_string; + if (tmp_value.alloced_length() < res->length() && + tmp_value.realloc(res->length())) + { + null_value= 1; + return 0; + } + tmp_value.length(res->length()); + tmp_value.set_charset(res->charset()); + ptr= (char *) res->ptr(); + end= ptr + res->length(); + tmp= (char *) tmp_value.ptr() + tmp_value.length(); +#ifdef USE_MB + if (use_mb(res->charset())) + { + register uint32 l; + while (ptr < end) + { + if ((l= my_ismbchar(res->charset(),ptr,end))) + { + tmp-= l; + memcpy(tmp,ptr,l); + ptr+= l; + } + else + *--tmp= *ptr++; + } + } + else +#endif /* USE_MB */ + { + while (ptr < end) + *--tmp= *ptr++; + } + return &tmp_value; +} + + +void Item_func_reverse::fix_length_and_dec() +{ + collation.set(args[0]->collation); + max_length = args[0]->max_length; +} + +/** + Replace all occurences of string2 in string1 with string3. + + Don't reallocate val_str() if not needed. + + @todo + Fix that this works with binary strings when using USE_MB +*/ + +String *Item_func_replace::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res,*res2,*res3; + int offset; + uint from_length,to_length; + bool alloced=0; +#ifdef USE_MB + const char *ptr,*end,*strend,*search,*search_end; + register uint32 l; + bool binary_cmp; +#endif + + null_value=0; + res=args[0]->val_str(str); + if (args[0]->null_value) + goto null; + res2=args[1]->val_str(&tmp_value); + if (args[1]->null_value) + goto null; + + res->set_charset(collation.collation); + +#ifdef USE_MB + binary_cmp = ((res->charset()->state & MY_CS_BINSORT) || !use_mb(res->charset())); +#endif + + if (res2->length() == 0) + return res; +#ifndef USE_MB + if ((offset=res->strstr(*res2)) < 0) + return res; +#else + offset=0; + if (binary_cmp && (offset=res->strstr(*res2)) < 0) + return res; +#endif + if (!(res3=args[2]->val_str(&tmp_value2))) + goto null; + from_length= res2->length(); + to_length= res3->length(); + +#ifdef USE_MB + if (!binary_cmp) + { + search=res2->ptr(); + search_end=search+from_length; +redo: + ptr=res->ptr()+offset; + strend=res->ptr()+res->length(); + end=strend-from_length+1; + while (ptr < end) + { + if (*ptr == *search) + { + register char *i,*j; + i=(char*) ptr+1; j=(char*) search+1; + while (j != search_end) + if (*i++ != *j++) goto skip; + offset= (int) (ptr-res->ptr()); + if (res->length()-from_length + to_length > + current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), + func_name(), + current_thd->variables.max_allowed_packet); + + goto null; + } + if (!alloced) + { + alloced=1; + res=copy_if_not_alloced(str,res,res->length()+to_length); + } + res->replace((uint) offset,from_length,*res3); + offset+=(int) to_length; + goto redo; + } +skip: + if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l; + else ++ptr; + } + } + else +#endif /* USE_MB */ + do + { + if (res->length()-from_length + to_length > + current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), func_name(), + current_thd->variables.max_allowed_packet); + goto null; + } + if (!alloced) + { + alloced=1; + res=copy_if_not_alloced(str,res,res->length()+to_length); + } + res->replace((uint) offset,from_length,*res3); + offset+=(int) to_length; + } + while ((offset=res->strstr(*res2,(uint) offset)) >= 0); + return res; + +null: + null_value=1; + return 0; +} + + +void Item_func_replace::fix_length_and_dec() +{ + ulonglong max_result_length= args[0]->max_length; + int diff=(int) (args[2]->max_length - args[1]->max_length); + if (diff > 0 && args[1]->max_length) + { // Calculate of maxreplaces + ulonglong max_substrs= max_result_length/args[1]->max_length; + max_result_length+= max_substrs * (uint) diff; + } + if (max_result_length >= MAX_BLOB_WIDTH) + { + max_result_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) max_result_length; + + if (agg_arg_charsets(collation, args, 3, MY_COLL_CMP_CONV, 1)) + return; +} + + +String *Item_func_insert::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res,*res2; + longlong start, length; /* must be longlong to avoid truncation */ + + null_value=0; + res=args[0]->val_str(str); + res2=args[3]->val_str(&tmp_value); + start= args[1]->val_int() - 1; + length= args[2]->val_int(); + + if (args[0]->null_value || args[1]->null_value || args[2]->null_value || + args[3]->null_value) + goto null; /* purecov: inspected */ + + if ((start < 0) || (start > res->length())) + return res; // Wrong param; skip insert + if ((length < 0) || (length > res->length())) + length= res->length(); + + /* start and length are now sufficiently valid to pass to charpos function */ + start= res->charpos((int) start); + length= res->charpos((int) length, (uint32) start); + + /* Re-testing with corrected params */ + if (start > res->length()) + return res; /* purecov: inspected */ // Wrong param; skip insert + if (length > res->length() - start) + length= res->length() - start; + + if ((ulonglong) (res->length() - length + res2->length()) > + (ulonglong) current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), + func_name(), current_thd->variables.max_allowed_packet); + goto null; + } + res=copy_if_not_alloced(str,res,res->length()); + res->replace((uint32) start,(uint32) length,*res2); + return res; +null: + null_value=1; + return 0; +} + + +void Item_func_insert::fix_length_and_dec() +{ + ulonglong max_result_length; + + // Handle character set for args[0] and args[3]. + if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 3)) + return; + max_result_length= ((ulonglong) args[0]->max_length+ + (ulonglong) args[3]->max_length); + if (max_result_length >= MAX_BLOB_WIDTH) + { + max_result_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) max_result_length; +} + + +String *Item_str_conv::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res; + if (!(res=args[0]->val_str(str))) + { + null_value=1; /* purecov: inspected */ + return 0; /* purecov: inspected */ + } + null_value=0; + if (multiply == 1) + { + uint len; + res= copy_if_not_alloced(str,res,res->length()); + len= converter(collation.collation, (char*) res->ptr(), res->length(), + (char*) res->ptr(), res->length()); + DBUG_ASSERT(len <= res->length()); + res->length(len); + } + else + { + uint len= res->length() * multiply; + tmp_value.alloc(len); + tmp_value.set_charset(collation.collation); + len= converter(collation.collation, (char*) res->ptr(), res->length(), + (char*) tmp_value.ptr(), len); + tmp_value.length(len); + res= &tmp_value; + } + return res; +} + + +void Item_func_lcase::fix_length_and_dec() +{ + collation.set(args[0]->collation); + multiply= collation.collation->casedn_multiply; + converter= collation.collation->cset->casedn; + max_length= args[0]->max_length * multiply; +} + +void Item_func_ucase::fix_length_and_dec() +{ + collation.set(args[0]->collation); + multiply= collation.collation->caseup_multiply; + converter= collation.collation->cset->caseup; + max_length= args[0]->max_length * multiply; +} + + +String *Item_func_left::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + + /* must be longlong to avoid truncation */ + longlong length= args[1]->val_int(); + uint char_pos; + + if ((null_value=(args[0]->null_value || args[1]->null_value))) + return 0; + + /* if "unsigned_flag" is set, we have a *huge* positive number. */ + if ((length <= 0) && (!args[1]->unsigned_flag)) + return &my_empty_string; + + if ((res->length() <= (ulonglong) length) || + (res->length() <= (char_pos= res->charpos((int) length)))) + return res; + + tmp_value.set(*res, 0, char_pos); + return &tmp_value; +} + + +void Item_str_func::left_right_max_length() +{ + max_length=args[0]->max_length; + if (args[1]->const_item()) + { + int length=(int) args[1]->val_int()*collation.collation->mbmaxlen; + if (length <= 0) + max_length=0; + else + set_if_smaller(max_length,(uint) length); + } +} + + +void Item_func_left::fix_length_and_dec() +{ + collation.set(args[0]->collation); + left_right_max_length(); +} + + +String *Item_func_right::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + /* must be longlong to avoid truncation */ + longlong length= args[1]->val_int(); + + if ((null_value=(args[0]->null_value || args[1]->null_value))) + return 0; /* purecov: inspected */ + + /* if "unsigned_flag" is set, we have a *huge* positive number. */ + if ((length <= 0) && (!args[1]->unsigned_flag)) + return &my_empty_string; /* purecov: inspected */ + + if (res->length() <= (ulonglong) length) + return res; /* purecov: inspected */ + + uint start=res->numchars(); + if (start <= (uint) length) + return res; + start=res->charpos(start - (uint) length); + tmp_value.set(*res,start,res->length()-start); + return &tmp_value; +} + + +void Item_func_right::fix_length_and_dec() +{ + collation.set(args[0]->collation); + left_right_max_length(); +} + + +String *Item_func_substr::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res = args[0]->val_str(str); + /* must be longlong to avoid truncation */ + longlong start= args[1]->val_int(); + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Limit so that code sees out-of-bound value properly. */ + longlong length= arg_count == 3 ? args[2]->val_int() : INT_MAX32; + longlong tmp_length; + + if ((null_value=(args[0]->null_value || args[1]->null_value || + (arg_count == 3 && args[2]->null_value)))) + return 0; /* purecov: inspected */ + + /* Negative or zero length, will return empty string. */ + if ((arg_count == 3) && (length <= 0) && + (length == 0 || !args[2]->unsigned_flag)) + return &my_empty_string; + + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Set here so that rest of code sees out-of-bound value as such. */ + if ((length <= 0) || (length > INT_MAX32)) + length= INT_MAX32; + + /* if "unsigned_flag" is set, we have a *huge* positive number. */ + /* Assumes that the maximum length of a String is < INT_MAX32. */ + if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) || + (args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32))) + return &my_empty_string; + + start= ((start < 0) ? res->numchars() + start : start - 1); + start= res->charpos((int) start); + if ((start < 0) || ((uint) start + 1 > res->length())) + return &my_empty_string; + + length= res->charpos((int) length, (uint32) start); + tmp_length= res->length() - start; + length= min(length, tmp_length); + + if (!start && (longlong) res->length() == length) + return res; + tmp_value.set(*res, (uint32) start, (uint32) length); + return &tmp_value; +} + + +void Item_func_substr::fix_length_and_dec() +{ + max_length=args[0]->max_length; + + collation.set(args[0]->collation); + if (args[1]->const_item()) + { + int32 start= (int32) args[1]->val_int(); + if (start < 0) + max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start); + else + max_length-= min((uint)(start - 1), max_length); + } + if (arg_count == 3 && args[2]->const_item()) + { + int32 length= (int32) args[2]->val_int(); + if (length <= 0) + max_length=0; /* purecov: inspected */ + else + set_if_smaller(max_length,(uint) length); + } + max_length*= collation.collation->mbmaxlen; +} + + +void Item_func_substr_index::fix_length_and_dec() +{ + max_length= args[0]->max_length; + + if (agg_arg_charsets(collation, args, 2, MY_COLL_CMP_CONV, 1)) + return; +} + + +String *Item_func_substr_index::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + String *delimiter= args[1]->val_str(&tmp_value); + int32 count= (int32) args[2]->val_int(); + uint offset; + + if (args[0]->null_value || args[1]->null_value || args[2]->null_value) + { // string and/or delim are null + null_value=1; + return 0; + } + null_value=0; + uint delimiter_length= delimiter->length(); + if (!res->length() || !delimiter_length || !count) + return &my_empty_string; // Wrong parameters + + res->set_charset(collation.collation); + +#ifdef USE_MB + if (use_mb(res->charset())) + { + const char *ptr= res->ptr(); + const char *strend= ptr+res->length(); + const char *end= strend-delimiter_length+1; + const char *search= delimiter->ptr(); + const char *search_end= search+delimiter_length; + int32 n=0,c=count,pass; + register uint32 l; + for (pass=(count>0);pass<2;++pass) + { + while (ptr < end) + { + if (*ptr == *search) + { + register char *i,*j; + i=(char*) ptr+1; j=(char*) search+1; + while (j != search_end) + if (*i++ != *j++) goto skip; + if (pass==0) ++n; + else if (!--c) break; + ptr+= delimiter_length; + continue; + } + skip: + if ((l=my_ismbchar(res->charset(), ptr,strend))) ptr+=l; + else ++ptr; + } /* either not found or got total number when count<0 */ + if (pass == 0) /* count<0 */ + { + c+=n+1; + if (c<=0) return res; /* not found, return original string */ + ptr=res->ptr(); + } + else + { + if (c) return res; /* Not found, return original string */ + if (count>0) /* return left part */ + { + tmp_value.set(*res,0,(ulong) (ptr-res->ptr())); + } + else /* return right part */ + { + ptr+= delimiter_length; + tmp_value.set(*res,(ulong) (ptr-res->ptr()), (ulong) (strend-ptr)); + } + } + } + } + else +#endif /* USE_MB */ + { + if (count > 0) + { // start counting from the beginning + for (offset=0; ; offset+= delimiter_length) + { + if ((int) (offset= res->strstr(*delimiter, offset)) < 0) + return res; // Didn't find, return org string + if (!--count) + { + tmp_value.set(*res,0,offset); + break; + } + } + } + else + { + /* + Negative index, start counting at the end + */ + for (offset=res->length(); offset ;) + { + /* + this call will result in finding the position pointing to one + address space less than where the found substring is located + in res + */ + if ((int) (offset= res->strrstr(*delimiter, offset)) < 0) + return res; // Didn't find, return org string + /* + At this point, we've searched for the substring + the number of times as supplied by the index value + */ + if (!++count) + { + offset+= delimiter_length; + tmp_value.set(*res,offset,res->length()- offset); + break; + } + } + } + } + /* + We always mark tmp_value as const so that if val_str() is called again + on this object, we don't disrupt the contents of tmp_value when it was + derived from another String. + */ + tmp_value.mark_as_const(); + return (&tmp_value); +} + +/* +** The trim functions are extension to ANSI SQL because they trim substrings +** They ltrim() and rtrim() functions are optimized for 1 byte strings +** They also return the original string if possible, else they return +** a substring that points at the original string. +*/ + + +String *Item_func_ltrim::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH], *ptr, *end; + String tmp(buff,sizeof(buff),system_charset_info); + String *res, *remove_str; + uint remove_length; + LINT_INIT(remove_length); + + res= args[0]->val_str(str); + if ((null_value=args[0]->null_value)) + return 0; + remove_str= &remove; /* Default value. */ + if (arg_count == 2) + { + remove_str= args[1]->val_str(&tmp); + if ((null_value= args[1]->null_value)) + return 0; + } + + if ((remove_length= remove_str->length()) == 0 || + remove_length > res->length()) + return res; + + ptr= (char*) res->ptr(); + end= ptr+res->length(); + if (remove_length == 1) + { + char chr=(*remove_str)[0]; + while (ptr != end && *ptr == chr) + ptr++; + } + else + { + const char *r_ptr=remove_str->ptr(); + end-=remove_length; + while (ptr <= end && !memcmp(ptr, r_ptr, remove_length)) + ptr+=remove_length; + end+=remove_length; + } + if (ptr == res->ptr()) + return res; + tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr)); + return &tmp_value; +} + + +String *Item_func_rtrim::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH], *ptr, *end; + String tmp(buff, sizeof(buff), system_charset_info); + String *res, *remove_str; + uint remove_length; + LINT_INIT(remove_length); + + res= args[0]->val_str(str); + if ((null_value=args[0]->null_value)) + return 0; + remove_str= &remove; /* Default value. */ + if (arg_count == 2) + { + remove_str= args[1]->val_str(&tmp); + if ((null_value= args[1]->null_value)) + return 0; + } + + if ((remove_length= remove_str->length()) == 0 || + remove_length > res->length()) + return res; + + ptr= (char*) res->ptr(); + end= ptr+res->length(); +#ifdef USE_MB + char *p=ptr; + register uint32 l; +#endif + if (remove_length == 1) + { + char chr=(*remove_str)[0]; +#ifdef USE_MB + if (use_mb(res->charset())) + { + while (ptr < end) + { + if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l,p=ptr; + else ++ptr; + } + ptr=p; + } +#endif + while (ptr != end && end[-1] == chr) + end--; + } + else + { + const char *r_ptr=remove_str->ptr(); +#ifdef USE_MB + if (use_mb(res->charset())) + { + loop: + while (ptr + remove_length < end) + { + if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l; + else ++ptr; + } + if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length)) + { + end-=remove_length; + ptr=p; + goto loop; + } + } + else +#endif /* USE_MB */ + { + while (ptr + remove_length <= end && + !memcmp(end-remove_length, r_ptr, remove_length)) + end-=remove_length; + } + } + if (end == res->ptr()+res->length()) + return res; + tmp_value.set(*res,0,(uint) (end-res->ptr())); + return &tmp_value; +} + + +String *Item_func_trim::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char buff[MAX_FIELD_WIDTH], *ptr, *end; + const char *r_ptr; + String tmp(buff, sizeof(buff), system_charset_info); + String *res, *remove_str; + uint remove_length; + LINT_INIT(remove_length); + + res= args[0]->val_str(str); + if ((null_value=args[0]->null_value)) + return 0; + remove_str= &remove; /* Default value. */ + if (arg_count == 2) + { + remove_str= args[1]->val_str(&tmp); + if ((null_value= args[1]->null_value)) + return 0; + } + + if ((remove_length= remove_str->length()) == 0 || + remove_length > res->length()) + return res; + + ptr= (char*) res->ptr(); + end= ptr+res->length(); + r_ptr= remove_str->ptr(); + while (ptr+remove_length <= end && !memcmp(ptr,r_ptr,remove_length)) + ptr+=remove_length; +#ifdef USE_MB + if (use_mb(res->charset())) + { + char *p=ptr; + register uint32 l; + loop: + while (ptr + remove_length < end) + { + if ((l=my_ismbchar(res->charset(), ptr,end))) ptr+=l; + else ++ptr; + } + if (ptr + remove_length == end && !memcmp(ptr,r_ptr,remove_length)) + { + end-=remove_length; + ptr=p; + goto loop; + } + ptr=p; + } + else +#endif /* USE_MB */ + { + while (ptr + remove_length <= end && + !memcmp(end-remove_length,r_ptr,remove_length)) + end-=remove_length; + } + if (ptr == res->ptr() && end == ptr+res->length()) + return res; + tmp_value.set(*res,(uint) (ptr - res->ptr()),(uint) (end-ptr)); + return &tmp_value; +} + +void Item_func_trim::fix_length_and_dec() +{ + max_length= args[0]->max_length; + if (arg_count == 1) + { + collation.set(args[0]->collation); + remove.set_charset(collation.collation); + remove.set_ascii(" ",1); + } + else + { + // Handle character set for args[1] and args[0]. + // Note that we pass args[1] as the first item, and args[0] as the second. + if (agg_arg_charsets(collation, &args[1], 2, MY_COLL_CMP_CONV, -1)) + return; + } +} + +void Item_func_trim::print(String *str, enum_query_type query_type) +{ + if (arg_count == 1) + { + Item_func::print(str, query_type); + return; + } + str->append(Item_func_trim::func_name()); + str->append('('); + str->append(mode_name()); + str->append(' '); + args[1]->print(str, query_type); + str->append(STRING_WITH_LEN(" from ")); + args[0]->print(str, query_type); + str->append(')'); +} + + +/* Item_func_password */ + +String *Item_func_password::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + if ((null_value=args[0]->null_value)) + return 0; + if (res->length() == 0) + return &my_empty_string; + my_make_scrambled_password(tmp_value, res->ptr(), res->length()); + str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, res->charset()); + return str; +} + +char *Item_func_password::alloc(THD *thd, const char *password, + size_t pass_len) +{ + char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1); + if (buff) + my_make_scrambled_password(buff, password, pass_len); + return buff; +} + +/* Item_func_old_password */ + +String *Item_func_old_password::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + if ((null_value=args[0]->null_value)) + return 0; + if (res->length() == 0) + return &my_empty_string; + my_make_scrambled_password_323(tmp_value, res->ptr(), res->length()); + str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, res->charset()); + return str; +} + +char *Item_func_old_password::alloc(THD *thd, const char *password, + size_t pass_len) +{ + char *buff= (char *) thd->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1); + if (buff) + my_make_scrambled_password_323(buff, password, pass_len); + return buff; +} + + +#define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.') + +String *Item_func_encrypt::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res =args[0]->val_str(str); + +#ifdef HAVE_CRYPT + char salt[3],*salt_ptr; + if ((null_value=args[0]->null_value)) + return 0; + if (res->length() == 0) + return &my_empty_string; + + if (arg_count == 1) + { // generate random salt + time_t timestamp=current_thd->query_start(); + salt[0] = bin_to_ascii( (ulong) timestamp & 0x3f); + salt[1] = bin_to_ascii(( (ulong) timestamp >> 5) & 0x3f); + salt[2] = 0; + salt_ptr=salt; + } + else + { // obtain salt from the first two bytes + String *salt_str=args[1]->val_str(&tmp_value); + if ((null_value= (args[1]->null_value || salt_str->length() < 2))) + return 0; + salt_ptr= salt_str->c_ptr_safe(); + } + pthread_mutex_lock(&LOCK_crypt); + char *tmp= crypt(res->c_ptr_safe(),salt_ptr); + if (!tmp) + { + pthread_mutex_unlock(&LOCK_crypt); + null_value= 1; + return 0; + } + str->set(tmp, (uint) strlen(tmp), &my_charset_bin); + str->copy(); + pthread_mutex_unlock(&LOCK_crypt); + return str; +#else + null_value=1; + return 0; +#endif /* HAVE_CRYPT */ +} + +void Item_func_encode::fix_length_and_dec() +{ + max_length=args[0]->max_length; + maybe_null=args[0]->maybe_null || args[1]->maybe_null; + collation.set(&my_charset_bin); +} + +String *Item_func_encode::val_str(String *str) +{ + String *res; + char pw_buff[80]; + String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info); + String *password; + DBUG_ASSERT(fixed == 1); + + if (!(res=args[0]->val_str(str))) + { + null_value=1; /* purecov: inspected */ + return 0; /* purecov: inspected */ + } + + if (!(password=args[1]->val_str(& tmp_pw_value))) + { + null_value=1; + return 0; + } + + null_value=0; + res=copy_if_not_alloced(str,res,res->length()); + SQL_CRYPT sql_crypt(password->ptr(), password->length()); + sql_crypt.init(); + sql_crypt.encode((char*) res->ptr(),res->length()); + res->set_charset(&my_charset_bin); + return res; +} + +String *Item_func_decode::val_str(String *str) +{ + String *res; + char pw_buff[80]; + String tmp_pw_value(pw_buff, sizeof(pw_buff), system_charset_info); + String *password; + DBUG_ASSERT(fixed == 1); + + if (!(res=args[0]->val_str(str))) + { + null_value=1; /* purecov: inspected */ + return 0; /* purecov: inspected */ + } + + if (!(password=args[1]->val_str(& tmp_pw_value))) + { + null_value=1; + return 0; + } + + null_value=0; + res=copy_if_not_alloced(str,res,res->length()); + SQL_CRYPT sql_crypt(password->ptr(), password->length()); + sql_crypt.init(); + sql_crypt.decode((char*) res->ptr(),res->length()); + return res; +} + + +Item *Item_func_sysconst::safe_charset_converter(CHARSET_INFO *tocs) +{ + Item_string *conv; + uint conv_errors; + String tmp, cstr, *ostr= val_str(&tmp); + if (null_value) + { + Item *null_item= new Item_null((char *) fully_qualified_func_name()); + null_item->collation.set (tocs); + return null_item; + } + cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors); + if (conv_errors || + !(conv= new Item_static_string_func(fully_qualified_func_name(), + cstr.ptr(), cstr.length(), + cstr.charset(), + collation.derivation))) + { + return NULL; + } + conv->str_value.copy(); + conv->str_value.mark_as_const(); + return conv; +} + + +String *Item_func_database::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + THD *thd= current_thd; + if (thd->db == NULL) + { + null_value= 1; + return 0; + } + else + str->copy(thd->db, thd->db_length, system_charset_info); + return str; +} + + +/** + @todo + make USER() replicate properly (currently it is replicated to "") +*/ +bool Item_func_user::init(const char *user, const char *host) +{ + DBUG_ASSERT(fixed == 1); + + // For system threads (e.g. replication SQL thread) user may be empty + if (user) + { + CHARSET_INFO *cs= str_value.charset(); + size_t res_length= (strlen(user)+strlen(host)+2) * cs->mbmaxlen; + + if (str_value.alloc((uint) res_length)) + { + null_value=1; + return TRUE; + } + + res_length=cs->cset->snprintf(cs, (char*)str_value.ptr(), (uint) res_length, + "%s@%s", user, host); + str_value.length((uint) res_length); + str_value.mark_as_const(); + } + return FALSE; +} + + +bool Item_func_user::fix_fields(THD *thd, Item **ref) +{ + return (Item_func_sysconst::fix_fields(thd, ref) || + init(thd->main_security_ctx.user, + thd->main_security_ctx.host_or_ip)); +} + + +bool Item_func_current_user::fix_fields(THD *thd, Item **ref) +{ + if (Item_func_sysconst::fix_fields(thd, ref)) + return TRUE; + + Security_context *ctx= +#ifndef NO_EMBEDDED_ACCESS_CHECKS + (context->security_ctx + ? context->security_ctx : thd->security_ctx); +#else + thd->security_ctx; +#endif /*NO_EMBEDDED_ACCESS_CHECKS*/ + return init(ctx->priv_user, ctx->priv_host); +} + + +void Item_func_soundex::fix_length_and_dec() +{ + collation.set(args[0]->collation); + max_length=args[0]->max_length; + set_if_bigger(max_length, 4 * collation.collation->mbminlen); + tmp_value.set_charset(collation.collation); +} + + +/** + If alpha, map input letter to soundex code. + If not alpha and remove_garbage is set then skip to next char + else return 0 +*/ + +static int soundex_toupper(int ch) +{ + return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch; +} + + +static char get_scode(int wc) +{ + int ch= soundex_toupper(wc); + if (ch < 'A' || ch > 'Z') + { + // Thread extended alfa (country spec) + return '0'; // as vokal + } + return(soundex_map[ch-'A']); +} + + +static bool my_uni_isalpha(int wc) +{ + /* + Return true for all Basic Latin letters: a..z A..Z. + Return true for all Unicode characters with code higher than U+00C0: + - characters between 'z' and U+00C0 are controls and punctuations. + - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'. + */ + return (wc >= 'a' && wc <= 'z') || + (wc >= 'A' && wc <= 'Z') || + (wc >= 0xC0); +} + + +String *Item_func_soundex::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res =args[0]->val_str(str); + char last_ch,ch; + CHARSET_INFO *cs= collation.collation; + my_wc_t wc; + uint nchars; + int rc; + + if ((null_value= args[0]->null_value)) + return 0; /* purecov: inspected */ + + if (tmp_value.alloc(max(res->length(), 4 * cs->mbminlen))) + return str; /* purecov: inspected */ + char *to= (char *) tmp_value.ptr(); + char *to_end= to + tmp_value.alloced_length(); + char *from= (char *) res->ptr(), *end= from + res->length(); + + for ( ; ; ) /* Skip pre-space */ + { + if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0) + return &my_empty_string; /* EOL or invalid byte sequence */ + + if (rc == 1 && cs->ctype) + { + /* Single byte letter found */ + if (my_isalpha(cs, *from)) + { + last_ch= get_scode(*from); // Code of the first letter + *to++= soundex_toupper(*from++); // Copy first letter + break; + } + from++; + } + else + { + from+= rc; + if (my_uni_isalpha(wc)) + { + /* Multibyte letter found */ + wc= soundex_toupper(wc); + last_ch= get_scode(wc); // Code of the first letter + if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0) + { + /* Extra safety - should not really happen */ + DBUG_ASSERT(false); + return &my_empty_string; + } + to+= rc; + break; + } + } + } + + /* + last_ch is now set to the first 'double-letter' check. + loop on input letters until end of input + */ + for (nchars= 1 ; ; ) + { + if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0) + break; /* EOL or invalid byte sequence */ + + if (rc == 1 && cs->ctype) + { + if (!my_isalpha(cs, *from++)) + continue; + } + else + { + from+= rc; + if (!my_uni_isalpha(wc)) + continue; + } + + ch= get_scode(wc); + if ((ch != '0') && (ch != last_ch)) // if not skipped or double + { + // letter, copy to output + if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch, + (uchar*) to, (uchar*) to_end)) <= 0) + { + // Extra safety - should not really happen + DBUG_ASSERT(false); + break; + } + to+= rc; + nchars++; + last_ch= ch; // save code of last input letter + } // for next double-letter check + } + + /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */ + if (nchars < 4) + { + uint nbytes= (4 - nchars) * cs->mbminlen; + cs->cset->fill(cs, to, nbytes, '0'); + to+= nbytes; + } + + tmp_value.length((uint) (to-tmp_value.ptr())); + return &tmp_value; +} + + +/** + Change a number to format '3,333,333,333.000'. + + This should be 'internationalized' sometimes. +*/ + +const int FORMAT_MAX_DECIMALS= 30; + +Item_func_format::Item_func_format(Item *org, Item *dec) +: Item_str_func(org, dec) +{ +} + +void Item_func_format::fix_length_and_dec() +{ + uint char_length= args[0]->max_length/args[0]->collation.collation->mbmaxlen; + //@InfiniDB. @bug3488, update max_length for formatting double data. + if (args[0]->result_type() == REAL_RESULT && char_length < 310) + char_length = 310; + + uint max_sep_count= char_length/3 + (decimals ? 1 : 0) + /*sign*/1; + collation.set(default_charset()); + max_length= (char_length + max_sep_count + decimals) * + collation.collation->mbmaxlen; +} + + +/** + @todo + This needs to be fixed for multi-byte character set where numbers + are stored in more than one byte +*/ + +String *Item_func_format::val_str(String *str) +{ + uint32 length; + uint32 str_length; + /* Number of decimal digits */ + int dec; + /* Number of characters used to represent the decimals, including '.' */ + uint32 dec_length; + int diff; + DBUG_ASSERT(fixed == 1); + + dec= (int) args[1]->val_int(); + if (args[1]->null_value) + { + null_value=1; + return NULL; + } + + dec= set_zone(dec, 0, FORMAT_MAX_DECIMALS); + dec_length= dec ? dec+1 : 0; + null_value=0; + + if (args[0]->result_type() == DECIMAL_RESULT || + args[0]->result_type() == INT_RESULT) + { + my_decimal dec_val, rnd_dec, *res; + res= args[0]->val_decimal(&dec_val); + if ((null_value=args[0]->null_value)) + return 0; /* purecov: inspected */ + my_decimal_round(E_DEC_FATAL_ERROR, res, dec, false, &rnd_dec); + my_decimal2string(E_DEC_FATAL_ERROR, &rnd_dec, 0, 0, 0, str); + str_length= str->length(); + if (rnd_dec.sign()) + str_length--; + } + else + { + double nr= args[0]->val_real(); + if ((null_value=args[0]->null_value)) + return 0; /* purecov: inspected */ + nr= my_double_round(nr, (longlong) dec, FALSE, FALSE); + /* Here default_charset() is right as this is not an automatic conversion */ + str->set_real(nr, dec, default_charset()); + if (isnan(nr)) + return str; + str_length=str->length(); + if (nr < 0) + str_length--; // Don't count sign + } + /* We need this test to handle 'nan' values */ + if (str_length >= dec_length+4) + { + char *tmp,*pos; + length= str->length()+(diff=((int)(str_length- dec_length-1))/3); + str= copy_if_not_alloced(&tmp_str,str,length); + str->length(length); + tmp= (char*) str->ptr()+length - dec_length-1; + for (pos= (char*) str->ptr()+length-1; pos != tmp; pos--) + pos[0]= pos[-diff]; + while (diff) + { + *pos= *(pos - diff); + pos--; + *pos= *(pos - diff); + pos--; + *pos= *(pos - diff); + pos--; + pos[0]=','; + pos--; + diff--; + } + } + return str; +} + + +void Item_func_format::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("format(")); + args[0]->print(str, query_type); + str->append(','); + args[1]->print(str, query_type); + str->append(')'); +} + +void Item_func_elt::fix_length_and_dec() +{ + max_length=0; + decimals=0; + + if (agg_arg_charsets(collation, args+1, arg_count-1, MY_COLL_ALLOW_CONV, 1)) + return; + + for (uint i= 1 ; i < arg_count ; i++) + { + set_if_bigger(max_length,args[i]->max_length); + set_if_bigger(decimals,args[i]->decimals); + } + maybe_null=1; // NULL if wrong first arg +} + + +double Item_func_elt::val_real() +{ + DBUG_ASSERT(fixed == 1); + uint tmp; + null_value=1; + if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count) + return 0.0; + double result= args[tmp]->val_real(); + null_value= args[tmp]->null_value; + return result; +} + + +longlong Item_func_elt::val_int() +{ + DBUG_ASSERT(fixed == 1); + uint tmp; + null_value=1; + if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count) + return 0; + + longlong result= args[tmp]->val_int(); + null_value= args[tmp]->null_value; + return result; +} + + +String *Item_func_elt::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + uint tmp; + null_value=1; + if ((tmp=(uint) args[0]->val_int()) == 0 || tmp >= arg_count) + return NULL; + + String *result= args[tmp]->val_str(str); + if (result) + result->set_charset(collation.collation); + null_value= args[tmp]->null_value; + return result; +} + + +void Item_func_make_set::split_sum_func(THD *thd, Item **ref_pointer_array, + List &fields) +{ + item->split_sum_func2(thd, ref_pointer_array, fields, &item, TRUE); + Item_str_func::split_sum_func(thd, ref_pointer_array, fields); +} + + +void Item_func_make_set::fix_length_and_dec() +{ + max_length=arg_count-1; + + if (agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1)) + return; + + for (uint i=0 ; i < arg_count ; i++) + max_length+=args[i]->max_length; + + used_tables_cache|= item->used_tables(); + not_null_tables_cache&= item->not_null_tables(); + const_item_cache&= item->const_item(); + with_sum_func= with_sum_func || item->with_sum_func; +} + + +void Item_func_make_set::update_used_tables() +{ + Item_func::update_used_tables(); + item->update_used_tables(); + used_tables_cache|=item->used_tables(); + const_item_cache&=item->const_item(); +} + + +String *Item_func_make_set::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + ulonglong bits; + bool first_found=0; + Item **ptr=args; + String *result=&my_empty_string; + + bits=item->val_int(); + if ((null_value=item->null_value)) + return NULL; + + if (arg_count < 64) + bits &= ((ulonglong) 1 << arg_count)-1; + + for (; bits; bits >>= 1, ptr++) + { + if (bits & 1) + { + String *res= (*ptr)->val_str(str); + if (res) // Skip nulls + { + if (!first_found) + { // First argument + first_found=1; + if (res != str) + result=res; // Use original string + else + { + if (tmp_str.copy(*res)) // Don't use 'str' + return &my_empty_string; + result= &tmp_str; + } + } + else + { + if (result != &tmp_str) + { // Copy data to tmp_str + if (tmp_str.alloc(result->length()+res->length()+1) || + tmp_str.copy(*result)) + return &my_empty_string; + result= &tmp_str; + } + if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res)) + return &my_empty_string; + } + } + } + } + return result; +} + + +Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg) +{ + DBUG_ASSERT(!current_thd->is_stmt_prepare()); + + Item *new_item= item->transform(transformer, arg); + if (!new_item) + return 0; + + /* + THD::change_item_tree() should be called only if the tree was + really transformed, i.e. when a new item has been created. + Otherwise we'll be allocating a lot of unnecessary memory for + change records at each execution. + */ + if (item != new_item) + current_thd->change_item_tree(&item, new_item); + return Item_str_func::transform(transformer, arg); +} + + +void Item_func_make_set::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("make_set(")); + item->print(str, query_type); + if (arg_count) + { + str->append(','); + print_args(str, 0, query_type); + } + str->append(')'); +} + + +String *Item_func_char::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + str->length(0); + str->set_charset(collation.collation); + for (uint i=0 ; i < arg_count ; i++) + { + int32 num=(int32) args[i]->val_int(); + if (!args[i]->null_value) + { + char char_num= (char) num; + if (num&0xFF000000L) { + str->append((char)(num>>24)); + goto b2; + } else if (num&0xFF0000L) { + b2: str->append((char)(num>>16)); + goto b1; + } else if (num&0xFF00L) { + b1: str->append((char)(num>>8)); + } + str->append(&char_num, 1); + } + } + str->realloc(str->length()); // Add end 0 (for Purify) + return check_well_formed_result(str); +} + + +inline String* alloc_buffer(String *res,String *str,String *tmp_value, + ulong length) +{ + if (res->alloced_length() < length) + { + if (str->alloced_length() >= length) + { + (void) str->copy(*res); + str->length(length); + return str; + } + if (tmp_value->alloc(length)) + return 0; + (void) tmp_value->copy(*res); + tmp_value->length(length); + return tmp_value; + } + res->length(length); + return res; +} + + +void Item_func_repeat::fix_length_and_dec() +{ + collation.set(args[0]->collation); + if (args[1]->const_item()) + { + /* must be longlong to avoid truncation */ + longlong count= args[1]->val_int(); + + // @InfiniDB. For negative count, MySQL returns empty string, IDB returns NULL. + // set length to 0 so order by can go through + if (count < 0 && fThd && (fThd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE || + fThd->variables.infinidb_vtable_mode == 0)) + { + max_length = 0; + maybe_null = 1; + return; + } + + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Set here so that rest of code sees out-of-bound value as such. */ + if (count > INT_MAX32) + count= INT_MAX32; + + ulonglong max_result_length= (ulonglong) args[0]->max_length * count; + if (max_result_length >= MAX_BLOB_WIDTH) + { + max_result_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) max_result_length; + } + + else + { + // @InfiniDB. For dynamic (column) count, IDB sets length 256 for order by to go through + if (fThd && fThd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE || + fThd->variables.infinidb_vtable_mode == 0) + max_length = 256; + else + max_length = MAX_BLOB_WIDTH; + maybe_null= 1; + } +} + +/** + Item_func_repeat::str is carefully written to avoid reallocs + as much as possible at the cost of a local buffer +*/ + +String *Item_func_repeat::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + uint length,tot_length; + char *to; + /* must be longlong to avoid truncation */ + longlong count= args[1]->val_int(); + String *res= args[0]->val_str(str); + + if (args[0]->null_value || args[1]->null_value) + goto err; // string and/or delim are null + null_value= 0; + + if (count <= 0 && (count == 0 || !args[1]->unsigned_flag)) + return &my_empty_string; + + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Bounds check on count: If this is triggered, we will error. */ + if ((ulonglong) count > INT_MAX32) + count= INT_MAX32; + if (count == 1) // To avoid reallocs + return res; + length=res->length(); + // Safe length check + if (length > current_thd->variables.max_allowed_packet / (uint) count) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), + func_name(), current_thd->variables.max_allowed_packet); + goto err; + } + tot_length= length*(uint) count; + if (!(res= alloc_buffer(res,str,&tmp_value,tot_length))) + goto err; + + to=(char*) res->ptr()+length; + while (--count) + { + memcpy(to,res->ptr(),length); + to+=length; + } + return (res); + +err: + null_value=1; + return 0; +} + + +void Item_func_rpad::fix_length_and_dec() +{ + // Handle character set for args[0] and args[2]. + if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2)) + return; + if (args[1]->const_item()) + { + ulonglong length= 0; + + if (collation.collation->mbmaxlen > 0) + { + ulonglong temp= (ulonglong) args[1]->val_int(); + + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Set here so that rest of code sees out-of-bound value as such. */ + if (temp > INT_MAX32) + temp = INT_MAX32; + + length= temp * collation.collation->mbmaxlen; + } + + if (length >= MAX_BLOB_WIDTH) + { + length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) length; + } + else + { + max_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } +} + + +String *Item_func_rpad::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + uint32 res_byte_length,res_char_length,pad_char_length,pad_byte_length; + char *to; + const char *ptr_pad; + /* must be longlong to avoid truncation */ + longlong count= args[1]->val_int(); + longlong byte_count; + String *res= args[0]->val_str(str); + String *rpad= args[2]->val_str(&rpad_str); + + if (!res || args[1]->null_value || !rpad || + ((count < 0) && !args[1]->unsigned_flag)) + goto err; + null_value=0; + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Set here so that rest of code sees out-of-bound value as such. */ + if ((ulonglong) count > INT_MAX32) + count= INT_MAX32; + if (count <= (res_char_length= res->numchars())) + { // String to pad is big enough + res->length(res->charpos((int) count)); // Shorten result if longer + return (res); + } + pad_char_length= rpad->numchars(); + + byte_count= count * collation.collation->mbmaxlen; + if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), + func_name(), current_thd->variables.max_allowed_packet); + goto err; + } + if (args[2]->null_value || !pad_char_length) + goto err; + res_byte_length= res->length(); /* Must be done before alloc_buffer */ + if (!(res= alloc_buffer(res,str,&tmp_value, (ulong) byte_count))) + goto err; + + to= (char*) res->ptr()+res_byte_length; + ptr_pad=rpad->ptr(); + pad_byte_length= rpad->length(); + count-= res_char_length; + for ( ; (uint32) count > pad_char_length; count-= pad_char_length) + { + memcpy(to,ptr_pad,pad_byte_length); + to+= pad_byte_length; + } + if (count) + { + pad_byte_length= rpad->charpos((int) count); + memcpy(to,ptr_pad,(size_t) pad_byte_length); + to+= pad_byte_length; + } + res->length((uint) (to- (char*) res->ptr())); + return (res); + + err: + null_value=1; + return 0; +} + + +void Item_func_lpad::fix_length_and_dec() +{ + // Handle character set for args[0] and args[2]. + if (agg_arg_charsets(collation, &args[0], 2, MY_COLL_ALLOW_CONV, 2)) + return; + + if (args[1]->const_item()) + { + ulonglong length= 0; + + if (collation.collation->mbmaxlen > 0) + { + ulonglong temp= (ulonglong) args[1]->val_int(); + + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Set here so that rest of code sees out-of-bound value as such. */ + if (temp > INT_MAX32) + temp= INT_MAX32; + + length= temp * collation.collation->mbmaxlen; + } + + if (length >= MAX_BLOB_WIDTH) + { + length= MAX_BLOB_WIDTH; + maybe_null= 1; + } + max_length= (ulong) length; + } + else + { + max_length= MAX_BLOB_WIDTH; + maybe_null= 1; + } +} + + +String *Item_func_lpad::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + uint32 res_char_length,pad_char_length; + /* must be longlong to avoid truncation */ + longlong count= args[1]->val_int(); + longlong byte_count; + String *res= args[0]->val_str(&tmp_value); + String *pad= args[2]->val_str(&lpad_str); + + if (!res || args[1]->null_value || !pad || + ((count < 0) && !args[1]->unsigned_flag)) + goto err; + null_value=0; + /* Assumes that the maximum length of a String is < INT_MAX32. */ + /* Set here so that rest of code sees out-of-bound value as such. */ + if ((ulonglong) count > INT_MAX32) + count= INT_MAX32; + + res_char_length= res->numchars(); + + if (count <= res_char_length) + { + res->length(res->charpos((int) count)); + return res; + } + + pad_char_length= pad->numchars(); + byte_count= count * collation.collation->mbmaxlen; + + if ((ulonglong) byte_count > current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), + func_name(), current_thd->variables.max_allowed_packet); + goto err; + } + + if (args[2]->null_value || !pad_char_length || + str->alloc((uint32) byte_count)) + goto err; + + str->length(0); + str->set_charset(collation.collation); + count-= res_char_length; + while (count >= pad_char_length) + { + str->append(*pad); + count-= pad_char_length; + } + if (count > 0) + str->append(pad->ptr(), pad->charpos((int) count), collation.collation); + + str->append(*res); + null_value= 0; + return str; + +err: + null_value= 1; + return 0; +} + + +String *Item_func_conv::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + char *endptr,ans[65],*ptr; + longlong dec; + int from_base= (int) args[1]->val_int(); + int to_base= (int) args[2]->val_int(); + int err; + + if (args[0]->null_value || args[1]->null_value || args[2]->null_value || + abs(to_base) > 36 || abs(to_base) < 2 || + abs(from_base) > 36 || abs(from_base) < 2 || !(res->length())) + { + null_value= 1; + return NULL; + } + null_value= 0; + unsigned_flag= !(from_base < 0); + + if (args[0]->field_type() == MYSQL_TYPE_BIT) + { + /* + Special case: The string representation of BIT doesn't resemble the + decimal representation, so we shouldn't change it to string and then to + decimal. + */ + dec= args[0]->val_int(); + } + else + { + if (from_base < 0) + dec= my_strntoll(res->charset(), res->ptr(), res->length(), + -from_base, &endptr, &err); + else + dec= (longlong) my_strntoull(res->charset(), res->ptr(), res->length(), + from_base, &endptr, &err); + } + + ptr= longlong2str(dec, ans, to_base); + if (str->copy(ans, (uint32) (ptr-ans), default_charset())) + return &my_empty_string; + return str; +} + + +String *Item_func_conv_charset::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + if (use_cached_value) + return null_value ? 0 : &str_value; + /* + Here we don't pass 'str' as a parameter to args[0]->val_str() + as 'str' may point to 'str_value' (e.g. see Item::save_in_field()), + which we use below to convert string. + Use argument's 'str_value' instead. + */ + String *arg= args[0]->val_str(&args[0]->str_value); + uint dummy_errors; + if (!arg) + { + null_value=1; + return 0; + } + null_value= str_value.copy(arg->ptr(),arg->length(),arg->charset(), + conv_charset, &dummy_errors); + return null_value ? 0 : check_well_formed_result(&str_value); +} + +void Item_func_conv_charset::fix_length_and_dec() +{ + collation.set(conv_charset, DERIVATION_IMPLICIT); + max_length = args[0]->max_length*conv_charset->mbmaxlen; +} + +void Item_func_conv_charset::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("convert(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" using ")); + str->append(conv_charset->csname); + str->append(')'); +} + +String *Item_func_set_collation::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + str=args[0]->val_str(str); + if ((null_value=args[0]->null_value)) + return 0; + str->set_charset(collation.collation); + return str; +} + +void Item_func_set_collation::fix_length_and_dec() +{ + CHARSET_INFO *set_collation; + const char *colname; + String tmp, *str= args[1]->val_str(&tmp); + colname= str->c_ptr(); + if (colname == binary_keyword) + set_collation= get_charset_by_csname(args[0]->collation.collation->csname, + MY_CS_BINSORT,MYF(0)); + else + { + if (!(set_collation= get_charset_by_name(colname,MYF(0)))) + { + my_error(ER_UNKNOWN_COLLATION, MYF(0), colname); + return; + } + } + + if (!set_collation || + !my_charset_same(args[0]->collation.collation,set_collation)) + { + my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), + colname, args[0]->collation.collation->csname); + return; + } + collation.set(set_collation, DERIVATION_EXPLICIT, + args[0]->collation.repertoire); + max_length= args[0]->max_length; +} + + +bool Item_func_set_collation::eq(const Item *item, bool binary_cmp) const +{ + /* Assume we don't have rtti */ + if (this == item) + return 1; + if (item->type() != FUNC_ITEM) + return 0; + Item_func *item_func=(Item_func*) item; + if (arg_count != item_func->arg_count || + functype() != item_func->functype()) + return 0; + Item_func_set_collation *item_func_sc=(Item_func_set_collation*) item; + if (collation.collation != item_func_sc->collation.collation) + return 0; + for (uint i=0; i < arg_count ; i++) + if (!args[i]->eq(item_func_sc->args[i], binary_cmp)) + return 0; + return 1; +} + + +void Item_func_set_collation::print(String *str, enum_query_type query_type) +{ + str->append('('); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" collate ")); + DBUG_ASSERT(args[1]->basic_const_item() && + args[1]->type() == Item::STRING_ITEM); + args[1]->str_value.print(str); + str->append(')'); +} + +String *Item_func_charset::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + uint dummy_errors; + + CHARSET_INFO *cs= args[0]->collation.collation; + null_value= 0; + str->copy(cs->csname, (uint) strlen(cs->csname), + &my_charset_latin1, collation.collation, &dummy_errors); + return str; +} + +String *Item_func_collation::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + uint dummy_errors; + CHARSET_INFO *cs= args[0]->collation.collation; + + null_value= 0; + str->copy(cs->name, (uint) strlen(cs->name), + &my_charset_latin1, collation.collation, &dummy_errors); + return str; +} + + +String *Item_func_hex::val_str(String *str) +{ + String *res; + DBUG_ASSERT(fixed == 1); + if (args[0]->result_type() != STRING_RESULT) + { + ulonglong dec; + char ans[65],*ptr; + /* Return hex of unsigned longlong value */ + if (args[0]->result_type() == REAL_RESULT || + args[0]->result_type() == DECIMAL_RESULT) + { + double val= args[0]->val_real(); + if ((val <= (double) LONGLONG_MIN) || + (val >= (double) (ulonglong) ULONGLONG_MAX)) + dec= ~(longlong) 0; + else + dec= (ulonglong) (val + (val > 0 ? 0.5 : -0.5)); + } + else + dec= (ulonglong) args[0]->val_int(); + + if ((null_value= args[0]->null_value)) + return 0; + ptr= longlong2str(dec,ans,16); + if (str->copy(ans,(uint32) (ptr-ans),default_charset())) + return &my_empty_string; // End of memory + return str; + } + + /* Convert given string to a hex string, character by character */ + res= args[0]->val_str(str); + if (!res || tmp_value.alloc(res->length()*2+1)) + { + null_value=1; + return 0; + } + null_value=0; + tmp_value.length(res->length()*2); + + octet2hex((char*) tmp_value.ptr(), res->ptr(), res->length()); + return &tmp_value; +} + + /** Convert given hex string to a binary string. */ + +String *Item_func_unhex::val_str(String *str) +{ + const char *from, *end; + char *to; + String *res; + uint length; + DBUG_ASSERT(fixed == 1); + + res= args[0]->val_str(str); + if (!res || tmp_value.alloc(length= (1+res->length())/2)) + { + null_value=1; + return 0; + } + + from= res->ptr(); + null_value= 0; + tmp_value.length(length); + to= (char*) tmp_value.ptr(); + if (res->length() % 2) + { + int hex_char; + *to++= hex_char= hexchar_to_int(*from++); + if ((null_value= (hex_char == -1))) + return 0; + } + for (end=res->ptr()+res->length(); from < end ; from+=2, to++) + { + int hex_char; + *to= (hex_char= hexchar_to_int(from[0])) << 4; + if ((null_value= (hex_char == -1))) + return 0; + *to|= hex_char= hexchar_to_int(from[1]); + if ((null_value= (hex_char == -1))) + return 0; + } + return &tmp_value; +} + + +void Item_func_binary::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("cast(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" as binary)")); +} + + +#include // For my_stat + +String *Item_load_file::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *file_name; + File file; + MY_STAT stat_info; + char path[FN_REFLEN]; + DBUG_ENTER("load_file"); + + if (!(file_name= args[0]->val_str(str)) +#ifndef NO_EMBEDDED_ACCESS_CHECKS + || !(current_thd->security_ctx->master_access & FILE_ACL) +#endif + ) + goto err; + + (void) fn_format(path, file_name->c_ptr_safe(), mysql_real_data_home, "", + MY_RELATIVE_PATH | MY_UNPACK_FILENAME); + + /* Read only allowed from within dir specified by secure_file_priv */ + if (opt_secure_file_priv && + strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv))) + goto err; + + if (!my_stat(path, &stat_info, MYF(0))) + goto err; + + if (!(stat_info.st_mode & S_IROTH)) + { + /* my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr()); */ + goto err; + } + if (stat_info.st_size > (long) current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_ALLOWED_PACKET_OVERFLOWED, + ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED), + func_name(), current_thd->variables.max_allowed_packet); + goto err; + } + if (tmp_value.alloc(stat_info.st_size)) + goto err; + if ((file = my_open(file_name->ptr(), O_RDONLY, MYF(0))) < 0) + goto err; + if (my_read(file, (uchar*) tmp_value.ptr(), stat_info.st_size, MYF(MY_NABP))) + { + my_close(file, MYF(0)); + goto err; + } + tmp_value.length(stat_info.st_size); + my_close(file, MYF(0)); + null_value = 0; + DBUG_RETURN(&tmp_value); + +err: + null_value = 1; + DBUG_RETURN(0); +} + + +String* Item_func_export_set::val_str(String* str) +{ + DBUG_ASSERT(fixed == 1); + ulonglong the_set = (ulonglong) args[0]->val_int(); + String yes_buf, *yes; + yes = args[1]->val_str(&yes_buf); + String no_buf, *no; + no = args[2]->val_str(&no_buf); + String *sep = NULL, sep_buf ; + + uint num_set_values = 64; + ulonglong mask = 0x1; + str->length(0); + str->set_charset(collation.collation); + + /* Check if some argument is a NULL value */ + if (args[0]->null_value || args[1]->null_value || args[2]->null_value) + { + null_value=1; + return 0; + } + /* + Arg count can only be 3, 4 or 5 here. This is guaranteed from the + grammar for EXPORT_SET() + */ + switch(arg_count) { + case 5: + num_set_values = (uint) args[4]->val_int(); + if (num_set_values > 64) + num_set_values=64; + if (args[4]->null_value) + { + null_value=1; + return 0; + } + /* Fall through */ + case 4: + if (!(sep = args[3]->val_str(&sep_buf))) // Only true if NULL + { + null_value=1; + return 0; + } + break; + case 3: + { + /* errors is not checked - assume "," can always be converted */ + uint errors; + sep_buf.copy(STRING_WITH_LEN(","), &my_charset_bin, collation.collation, &errors); + sep = &sep_buf; + } + break; + default: + DBUG_ASSERT(0); // cannot happen + } + null_value=0; + + for (uint i = 0; i < num_set_values; i++, mask = (mask << 1)) + { + if (the_set & mask) + str->append(*yes); + else + str->append(*no); + if (i != num_set_values - 1) + str->append(*sep); + } + return str; +} + +void Item_func_export_set::fix_length_and_dec() +{ + uint length=max(args[1]->max_length,args[2]->max_length); + uint sep_length=(arg_count > 3 ? args[3]->max_length : 1); + max_length=length*64+sep_length*63; + + if (agg_arg_charsets(collation, args+1, min(4,arg_count)-1, + MY_COLL_ALLOW_CONV, 1)) + return; +} + +String* Item_func_inet_ntoa::val_str(String* str) +{ + DBUG_ASSERT(fixed == 1); + uchar buf[8], *p; + ulonglong n = (ulonglong) args[0]->val_int(); + char num[4]; + + /* + We do not know if args[0] is NULL until we have called + some val function on it if args[0] is not a constant! + + Also return null if n > 255.255.255.255 + */ + if ((null_value= (args[0]->null_value || n > (ulonglong) LL(4294967295)))) + return 0; // Null value + + str->length(0); + int4store(buf,n); + + /* Now we can assume little endian. */ + + num[3]='.'; + for (p=buf+4 ; p-- > buf ; ) + { + uint c = *p; + uint n1,n2; // Try to avoid divisions + n1= c / 100; // 100 digits + c-= n1*100; + n2= c / 10; // 10 digits + c-=n2*10; // last digit + num[0]=(char) n1+'0'; + num[1]=(char) n2+'0'; + num[2]=(char) c+'0'; + uint length=(n1 ? 4 : n2 ? 3 : 2); // Remove pre-zero + + (void) str->append(num+4-length,length); + } + str->length(str->length()-1); // Remove last '.'; + return str; +} + + +#define get_esc_bit(mask, num) (1 & (*((mask) + ((num) >> 3))) >> ((num) & 7)) + +/** + QUOTE() function returns argument string in single quotes suitable for + using in a SQL statement. + + Adds a \\ before all characters that needs to be escaped in a SQL string. + We also escape '^Z' (END-OF-FILE in windows) to avoid probelms when + running commands from a file in windows. + + This function is very useful when you want to generate SQL statements. + + @note + QUOTE(NULL) returns the string 'NULL' (4 letters, without quotes). + + @retval + str Quoted string + @retval + NULL Out of memory. +*/ + +String *Item_func_quote::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + /* + Bit mask that has 1 for set for the position of the following characters: + 0, \, ' and ^Z + */ + + static uchar escmask[32]= + { + 0x01, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + char *from, *to, *end, *start; + String *arg= args[0]->val_str(str); + uint arg_length, new_length; + if (!arg) // Null argument + { + /* Return the string 'NULL' */ + str->copy(STRING_WITH_LEN("NULL"), collation.collation); + null_value= 0; + return str; + } + + arg_length= arg->length(); + new_length= arg_length+2; /* for beginning and ending ' signs */ + + for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++) + new_length+= get_esc_bit(escmask, (uchar) *from); + + if (tmp_value.alloc(new_length)) + goto null; + + /* + We replace characters from the end to the beginning + */ + to= (char*) tmp_value.ptr() + new_length - 1; + *to--= '\''; + for (start= (char*) arg->ptr(),end= start + arg_length; end-- != start; to--) + { + /* + We can't use the bitmask here as we want to replace \O and ^Z with 0 + and Z + */ + switch (*end) { + case 0: + *to--= '0'; + *to= '\\'; + break; + case '\032': + *to--= 'Z'; + *to= '\\'; + break; + case '\'': + case '\\': + *to--= *end; + *to= '\\'; + break; + default: + *to= *end; + break; + } + } + *to= '\''; + tmp_value.length(new_length); + tmp_value.set_charset(collation.collation); + null_value= 0; + return &tmp_value; + +null: + null_value= 1; + return 0; +} + +longlong Item_func_uncompressed_length::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(&value); + if (!res) + { + null_value=1; + return 0; /* purecov: inspected */ + } + null_value=0; + if (res->is_empty()) return 0; + + /* + If length is <= 4 bytes, data is corrupt. This is the best we can do + to detect garbage input without decompressing it. + */ + if (res->length() <= 4) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_ZLIB_Z_DATA_ERROR, + ER(ER_ZLIB_Z_DATA_ERROR)); + null_value= 1; + return 0; + } + + /* + res->ptr() using is safe because we have tested that string is at least + 5 bytes long. + res->c_ptr() is not used because: + - we do not need \0 terminated string to get first 4 bytes + - c_ptr() tests simbol after string end (uninitialiozed memory) which + confuse valgrind + */ + return uint4korr(res->ptr()) & 0x3FFFFFFF; +} + +longlong Item_func_crc32::val_int() +{ + DBUG_ASSERT(fixed == 1); + String *res=args[0]->val_str(&value); + if (!res) + { + null_value=1; + return 0; /* purecov: inspected */ + } + null_value=0; + return (longlong) crc32(0L, (uchar*)res->ptr(), res->length()); +} + +#ifdef HAVE_COMPRESS +#include "zlib.h" + +String *Item_func_compress::val_str(String *str) +{ + int err= Z_OK, code; + ulong new_size; + String *res; + Byte *body; + char *tmp, *last_char; + DBUG_ASSERT(fixed == 1); + + if (!(res= args[0]->val_str(str))) + { + null_value= 1; + return 0; + } + null_value= 0; + if (res->is_empty()) return res; + + /* + Citation from zlib.h (comment for compress function): + + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least 0.1% larger than + sourceLen plus 12 bytes. + We assume here that the buffer can't grow more than .25 %. + */ + new_size= res->length() + res->length() / 5 + 12; + + // Check new_size overflow: new_size <= res->length() + if (((uint32) (new_size+5) <= res->length()) || + buffer.realloc((uint32) new_size + 4 + 1)) + { + null_value= 1; + return 0; + } + + body= ((Byte*)buffer.ptr()) + 4; + + // As far as we have checked res->is_empty() we can use ptr() + if ((err= compress(body, &new_size, + (const Bytef*)res->ptr(), res->length())) != Z_OK) + { + code= err==Z_MEM_ERROR ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_BUF_ERROR; + push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code)); + null_value= 1; + return 0; + } + + tmp= (char*)buffer.ptr(); // int4store is a macro; avoid side effects + int4store(tmp, res->length() & 0x3FFFFFFF); + + /* This is to ensure that things works for CHAR fields, which trim ' ': */ + last_char= ((char*)body)+new_size-1; + if (*last_char == ' ') + { + *++last_char= '.'; + new_size++; + } + + buffer.length((uint32)new_size + 4); + return &buffer; +} + + +String *Item_func_uncompress::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res= args[0]->val_str(str); + ulong new_size; + int err; + uint code; + + if (!res) + goto err; + null_value= 0; + if (res->is_empty()) + return res; + + /* If length is less than 4 bytes, data is corrupt */ + if (res->length() <= 4) + { + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_ZLIB_Z_DATA_ERROR, + ER(ER_ZLIB_Z_DATA_ERROR)); + goto err; + } + + /* Size of uncompressed data is stored as first 4 bytes of field */ + new_size= uint4korr(res->ptr()) & 0x3FFFFFFF; + if (new_size > current_thd->variables.max_allowed_packet) + { + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_TOO_BIG_FOR_UNCOMPRESS, + ER(ER_TOO_BIG_FOR_UNCOMPRESS), + current_thd->variables.max_allowed_packet); + goto err; + } + if (buffer.realloc((uint32)new_size)) + goto err; + + if ((err= uncompress((Byte*)buffer.ptr(), &new_size, + ((const Bytef*)res->ptr())+4,res->length())) == Z_OK) + { + buffer.length((uint32) new_size); + return &buffer; + } + + code= ((err == Z_BUF_ERROR) ? ER_ZLIB_Z_BUF_ERROR : + ((err == Z_MEM_ERROR) ? ER_ZLIB_Z_MEM_ERROR : ER_ZLIB_Z_DATA_ERROR)); + push_warning(current_thd,MYSQL_ERROR::WARN_LEVEL_ERROR,code,ER(code)); + +err: + null_value= 1; + return 0; +} +#endif + +/* + UUID, as in + DCE 1.1: Remote Procedure Call, + Open Group Technical Standard Document Number C706, October 1997, + (supersedes C309 DCE: Remote Procedure Call 8/1994, + which was basis for ISO/IEC 11578:1996 specification) +*/ + +static struct rand_struct uuid_rand; +static uint nanoseq; +static ulonglong uuid_time=0; +static char clock_seq_and_node_str[]="-0000-000000000000"; + +/** + number of 100-nanosecond intervals between + 1582-10-15 00:00:00.00 and 1970-01-01 00:00:00.00. +*/ +#define UUID_TIME_OFFSET ((ulonglong) 141427 * 24 * 60 * 60 * \ + 1000 * 1000 * 10) + +#define UUID_VERSION 0x1000 +#define UUID_VARIANT 0x8000 + +static void tohex(char *to, uint from, uint len) +{ + to+= len; + while (len--) + { + *--to= _dig_vec_lower[from & 15]; + from >>= 4; + } +} + +static void set_clock_seq_str() +{ + uint16 clock_seq= ((uint)(my_rnd(&uuid_rand)*16383)) | UUID_VARIANT; + tohex(clock_seq_and_node_str+1, clock_seq, 4); + nanoseq= 0; +} + +String *Item_func_uuid::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + char *s; + THD *thd= current_thd; + + pthread_mutex_lock(&LOCK_uuid_generator); + if (! uuid_time) /* first UUID() call. initializing data */ + { + ulong tmp=sql_rnd_with_mutex(); + uchar mac[6]; + int i; + if (my_gethwaddr(mac)) + { + /* purecov: begin inspected */ + /* + generating random "hardware addr" + and because specs explicitly specify that it should NOT correlate + with a clock_seq value (initialized random below), we use a separate + randominit() here + */ + randominit(&uuid_rand, tmp + (ulong) thd, tmp + (ulong)global_query_id); + for (i=0; i < (int)sizeof(mac); i++) + mac[i]=(uchar)(my_rnd(&uuid_rand)*255); + /* purecov: end */ + } + s=clock_seq_and_node_str+sizeof(clock_seq_and_node_str)-1; + for (i=sizeof(mac)-1 ; i>=0 ; i--) + { + *--s=_dig_vec_lower[mac[i] & 15]; + *--s=_dig_vec_lower[mac[i] >> 4]; + } + randominit(&uuid_rand, tmp + (ulong) server_start_time, + tmp + (ulong) thd->status_var.bytes_sent); + set_clock_seq_str(); + } + + ulonglong tv= my_getsystime() + UUID_TIME_OFFSET + nanoseq; + + if (likely(tv > uuid_time)) + { + /* + Current time is ahead of last timestamp, as it should be. + If we "borrowed time", give it back, just as long as we + stay ahead of the previous timestamp. + */ + if (nanoseq) + { + DBUG_ASSERT((tv > uuid_time) && (nanoseq > 0)); + /* + -1 so we won't make tv= uuid_time for nanoseq >= (tv - uuid_time) + */ + ulong delta= min(nanoseq, (ulong) (tv - uuid_time -1)); + tv-= delta; + nanoseq-= delta; + } + } + else + { + if (unlikely(tv == uuid_time)) + { + /* + For low-res system clocks. If several requests for UUIDs + end up on the same tick, we add a nano-second to make them + different. + ( current_timestamp + nanoseq * calls_in_this_period ) + may end up > next_timestamp; this is OK. Nonetheless, we'll + try to unwind nanoseq when we get a chance to. + If nanoseq overflows, we'll start over with a new numberspace + (so the if() below is needed so we can avoid the ++tv and thus + match the follow-up if() if nanoseq overflows!). + */ + if (likely(++nanoseq)) + ++tv; + } + + if (unlikely(tv <= uuid_time)) + { + /* + If the admin changes the system clock (or due to Daylight + Saving Time), the system clock may be turned *back* so we + go through a period once more for which we already gave out + UUIDs. To avoid duplicate UUIDs despite potentially identical + times, we make a new random component. + We also come here if the nanoseq "borrowing" overflows. + In either case, we throw away any nanoseq borrowing since it's + irrelevant in the new numberspace. + */ + set_clock_seq_str(); + tv= my_getsystime() + UUID_TIME_OFFSET; + nanoseq= 0; + DBUG_PRINT("uuid",("making new numberspace")); + } + } + + uuid_time=tv; + pthread_mutex_unlock(&LOCK_uuid_generator); + + uint32 time_low= (uint32) (tv & 0xFFFFFFFF); + uint16 time_mid= (uint16) ((tv >> 32) & 0xFFFF); + uint16 time_hi_and_version= (uint16) ((tv >> 48) | UUID_VERSION); + + str->realloc(UUID_LENGTH+1); + str->length(UUID_LENGTH); + str->set_charset(system_charset_info); + s=(char *) str->ptr(); + s[8]=s[13]='-'; + tohex(s, time_low, 8); + tohex(s+9, time_mid, 4); + tohex(s+14, time_hi_and_version, 4); + strmov(s+18, clock_seq_and_node_str); + return str; +} diff --git a/dbcon/mysql/item_strfunc.h b/dbcon/mysql/item_strfunc.h new file mode 100644 index 00000000..9b3f996c --- /dev/null +++ b/dbcon/mysql/item_strfunc.h @@ -0,0 +1,850 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* This file defines all string functions */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +class Item_str_func :public Item_func +{ +public: + Item_str_func() :Item_func() { decimals=NOT_FIXED_DEC; } + Item_str_func(Item *a) :Item_func(a) {decimals=NOT_FIXED_DEC; } + Item_str_func(Item *a,Item *b) :Item_func(a,b) { decimals=NOT_FIXED_DEC; } + Item_str_func(Item *a,Item *b,Item *c) :Item_func(a,b,c) { decimals=NOT_FIXED_DEC; } + Item_str_func(Item *a,Item *b,Item *c,Item *d) :Item_func(a,b,c,d) {decimals=NOT_FIXED_DEC; } + Item_str_func(Item *a,Item *b,Item *c,Item *d, Item* e) :Item_func(a,b,c,d,e) {decimals=NOT_FIXED_DEC; } + Item_str_func(List &list) :Item_func(list) {decimals=NOT_FIXED_DEC; } + longlong val_int(); + double val_real(); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return STRING_RESULT; } + void left_right_max_length(); + bool fix_fields(THD *thd, Item **ref); +}; + +class Item_func_md5 :public Item_str_func +{ + String tmp_value; +public: + Item_func_md5(Item *a) :Item_str_func(a) + { + collation.set(&my_charset_bin); + } + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "md5"; } +}; + + +class Item_func_sha :public Item_str_func +{ +public: + Item_func_sha(Item *a) :Item_str_func(a) + { + collation.set(&my_charset_bin); + } + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "sha"; } +}; + +class Item_func_aes_encrypt :public Item_str_func +{ +public: + Item_func_aes_encrypt(Item *a, Item *b) :Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "aes_encrypt"; } +}; + +class Item_func_aes_decrypt :public Item_str_func +{ +public: + Item_func_aes_decrypt(Item *a, Item *b) :Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "aes_decrypt"; } +}; + + +class Item_func_concat :public Item_str_func +{ + String tmp_value; +public: + Item_func_concat(List &list) :Item_str_func(list) {} + Item_func_concat(Item *a,Item *b) :Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "concat"; } +}; + +class Item_func_concat_ws :public Item_str_func +{ + String tmp_value; +public: + Item_func_concat_ws(List &list) :Item_str_func(list) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "concat_ws"; } + table_map not_null_tables() const { return 0; } +}; + +class Item_func_reverse :public Item_str_func +{ + String tmp_value; +public: + Item_func_reverse(Item *a) :Item_str_func(a) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "reverse"; } +}; + + +class Item_func_replace :public Item_str_func +{ + String tmp_value,tmp_value2; +public: + Item_func_replace(Item *org,Item *find,Item *replace) + :Item_str_func(org,find,replace) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "replace"; } +}; + + +class Item_func_insert :public Item_str_func +{ + String tmp_value; +public: + Item_func_insert(Item *org,Item *start,Item *length,Item *new_str) + :Item_str_func(org,start,length,new_str) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "insert"; } +}; + + +class Item_str_conv :public Item_str_func +{ +protected: + uint multiply; + my_charset_conv_case converter; + String tmp_value; +public: + Item_str_conv(Item *item) :Item_str_func(item) {} + String *val_str(String *); +}; + + +class Item_func_lcase :public Item_str_conv +{ +public: + Item_func_lcase(Item *item) :Item_str_conv(item) {} + const char *func_name() const { return "lcase"; } + void fix_length_and_dec(); +}; + +class Item_func_ucase :public Item_str_conv +{ +public: + Item_func_ucase(Item *item) :Item_str_conv(item) {} + const char *func_name() const { return "ucase"; } + void fix_length_and_dec(); +}; + + +class Item_func_left :public Item_str_func +{ + String tmp_value; +public: + Item_func_left(Item *a,Item *b) :Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "left"; } +}; + + +class Item_func_right :public Item_str_func +{ + String tmp_value; +public: + Item_func_right(Item *a,Item *b) :Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "right"; } +}; + + +class Item_func_substr :public Item_str_func +{ + String tmp_value; +public: + Item_func_substr(Item *a,Item *b) :Item_str_func(a,b) {} + Item_func_substr(Item *a,Item *b,Item *c) :Item_str_func(a,b,c) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "substr"; } +}; + + +class Item_func_substr_index :public Item_str_func +{ + String tmp_value; +public: + Item_func_substr_index(Item *a,Item *b,Item *c) :Item_str_func(a,b,c) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "substring_index"; } +}; + + +class Item_func_trim :public Item_str_func +{ +protected: + String tmp_value; + String remove; +public: + Item_func_trim(Item *a,Item *b) :Item_str_func(a,b) {} + Item_func_trim(Item *a) :Item_str_func(a) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "trim"; } + virtual void print(String *str, enum_query_type query_type); + virtual const char *mode_name() const { return "both"; } +}; + + +class Item_func_ltrim :public Item_func_trim +{ +public: + Item_func_ltrim(Item *a,Item *b) :Item_func_trim(a,b) {} + Item_func_ltrim(Item *a) :Item_func_trim(a) {} + String *val_str(String *); + const char *func_name() const { return "ltrim"; } + const char *mode_name() const { return "leading"; } +}; + + +class Item_func_rtrim :public Item_func_trim +{ +public: + Item_func_rtrim(Item *a,Item *b) :Item_func_trim(a,b) {} + Item_func_rtrim(Item *a) :Item_func_trim(a) {} + String *val_str(String *); + const char *func_name() const { return "rtrim"; } + const char *mode_name() const { return "trailing"; } +}; + + +/* + Item_func_password -- new (4.1.1) PASSWORD() function implementation. + Returns strcat('*', octet2hex(sha1(sha1(password)))). '*' stands for new + password format, sha1(sha1(password) is so-called hash_stage2 value. + Length of returned string is always 41 byte. To find out how entire + authentication procedure works, see comments in password.c. +*/ + +class Item_func_password :public Item_str_func +{ + char tmp_value[SCRAMBLED_PASSWORD_CHAR_LENGTH+1]; +public: + Item_func_password(Item *a) :Item_str_func(a) {} + String *val_str(String *str); + void fix_length_and_dec() { max_length= SCRAMBLED_PASSWORD_CHAR_LENGTH; } + const char *func_name() const { return "password"; } + static char *alloc(THD *thd, const char *password, size_t pass_len); +}; + + +/* + Item_func_old_password -- PASSWORD() implementation used in MySQL 3.21 - 4.0 + compatibility mode. This item is created in sql_yacc.yy when + 'old_passwords' session variable is set, and to handle OLD_PASSWORD() + function. +*/ + +class Item_func_old_password :public Item_str_func +{ + char tmp_value[SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1]; +public: + Item_func_old_password(Item *a) :Item_str_func(a) {} + String *val_str(String *str); + void fix_length_and_dec() { max_length= SCRAMBLED_PASSWORD_CHAR_LENGTH_323; } + const char *func_name() const { return "old_password"; } + static char *alloc(THD *thd, const char *password, size_t pass_len); +}; + + +class Item_func_des_encrypt :public Item_str_func +{ + String tmp_value,tmp_arg; +public: + Item_func_des_encrypt(Item *a) :Item_str_func(a) {} + Item_func_des_encrypt(Item *a, Item *b): Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec() + { + maybe_null=1; + /* 9 = MAX ((8- (arg_len % 8)) + 1) */ + max_length = args[0]->max_length + 9; + } + const char *func_name() const { return "des_encrypt"; } +}; + +class Item_func_des_decrypt :public Item_str_func +{ + String tmp_value; +public: + Item_func_des_decrypt(Item *a) :Item_str_func(a) {} + Item_func_des_decrypt(Item *a, Item *b): Item_str_func(a,b) {} + String *val_str(String *); + void fix_length_and_dec() + { + maybe_null=1; + /* 9 = MAX ((8- (arg_len % 8)) + 1) */ + max_length = args[0]->max_length - 9; + } + const char *func_name() const { return "des_decrypt"; } +}; + +class Item_func_encrypt :public Item_str_func +{ + String tmp_value; + + /* Encapsulate common constructor actions */ + void constructor_helper() + { + collation.set(&my_charset_bin); + } +public: + Item_func_encrypt(Item *a) :Item_str_func(a) + { + constructor_helper(); + } + Item_func_encrypt(Item *a, Item *b): Item_str_func(a,b) + { + constructor_helper(); + } + String *val_str(String *); + void fix_length_and_dec() { maybe_null=1; max_length = 13; } + const char *func_name() const { return "encrypt"; } +}; + +#include "sql_crypt.h" + + +class Item_func_encode :public Item_str_func +{ +public: + Item_func_encode(Item *a, Item *seed): + Item_str_func(a, seed) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "encode"; } +}; + + +class Item_func_decode :public Item_func_encode +{ +public: + Item_func_decode(Item *a, Item *seed): Item_func_encode(a, seed) {} + String *val_str(String *); + const char *func_name() const { return "decode"; } +}; + + +class Item_func_sysconst :public Item_str_func +{ +public: + Item_func_sysconst() + { collation.set(system_charset_info,DERIVATION_SYSCONST); } + Item *safe_charset_converter(CHARSET_INFO *tocs); + /* + Used to create correct Item name in new converted item in + safe_charset_converter, return string representation of this function + call + */ + virtual const char *fully_qualified_func_name() const = 0; +}; + + +class Item_func_database :public Item_func_sysconst +{ +public: + Item_func_database() :Item_func_sysconst() {} + String *val_str(String *); + void fix_length_and_dec() + { + max_length= MAX_FIELD_NAME * system_charset_info->mbmaxlen; + maybe_null=1; + } + const char *func_name() const { return "database"; } + const char *fully_qualified_func_name() const { return "database()"; } +}; + + +class Item_func_user :public Item_func_sysconst +{ +protected: + bool init (const char *user, const char *host); + +public: + Item_func_user() + { + str_value.set("", 0, system_charset_info); + } + String *val_str(String *) + { + DBUG_ASSERT(fixed == 1); + return (null_value ? 0 : &str_value); + } + bool fix_fields(THD *thd, Item **ref); + void fix_length_and_dec() + { + max_length= (USERNAME_LENGTH + + (HOSTNAME_LENGTH + 1) * SYSTEM_CHARSET_MBMAXLEN); + } + const char *func_name() const { return "user"; } + const char *fully_qualified_func_name() const { return "user()"; } + int save_in_field(Field *field, bool no_conversions) + { + return save_str_value_in_field(field, &str_value); + } +}; + + +class Item_func_current_user :public Item_func_user +{ + Name_resolution_context *context; + +public: + Item_func_current_user(Name_resolution_context *context_arg) + : context(context_arg) {} + bool fix_fields(THD *thd, Item **ref); + const char *func_name() const { return "current_user"; } + const char *fully_qualified_func_name() const { return "current_user()"; } +}; + + +class Item_func_soundex :public Item_str_func +{ + String tmp_value; +public: + Item_func_soundex(Item *a) :Item_str_func(a) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "soundex"; } +}; + + +class Item_func_elt :public Item_str_func +{ +public: + Item_func_elt(List &list) :Item_str_func(list) {} + double val_real(); + longlong val_int(); + String *val_str(String *str); + void fix_length_and_dec(); + const char *func_name() const { return "elt"; } +}; + + +class Item_func_make_set :public Item_str_func +{ + Item *item; + String tmp_str; + +public: + Item_func_make_set(Item *a,List &list) :Item_str_func(list),item(a) {} + String *val_str(String *str); + bool fix_fields(THD *thd, Item **ref) + { + DBUG_ASSERT(fixed == 0); + return ((!item->fixed && item->fix_fields(thd, &item)) || + item->check_cols(1) || + Item_func::fix_fields(thd, ref)); + } + void split_sum_func(THD *thd, Item **ref_pointer_array, List &fields); + void fix_length_and_dec(); + void update_used_tables(); + const char *func_name() const { return "make_set"; } + + bool walk(Item_processor processor, bool walk_subquery, uchar *arg) + { + return item->walk(processor, walk_subquery, arg) || + Item_str_func::walk(processor, walk_subquery, arg); + } + Item *transform(Item_transformer transformer, uchar *arg); + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_format :public Item_str_func +{ + String tmp_str; +public: + Item_func_format(Item *org, Item *dec); + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "format"; } + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_char :public Item_str_func +{ +public: + Item_func_char(List &list) :Item_str_func(list) + { collation.set(&my_charset_bin); } + Item_func_char(List &list, CHARSET_INFO *cs) :Item_str_func(list) + { collation.set(cs); } + String *val_str(String *); + void fix_length_and_dec() + { + max_length= arg_count * 4; + } + const char *func_name() const { return "char"; } +}; + + +class Item_func_repeat :public Item_str_func +{ + String tmp_value; +public: + Item_func_repeat(Item *arg1,Item *arg2) :Item_str_func(arg1,arg2) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "repeat"; } +}; + + +class Item_func_rpad :public Item_str_func +{ + String tmp_value, rpad_str; +public: + Item_func_rpad(Item *arg1,Item *arg2,Item *arg3) + :Item_str_func(arg1,arg2,arg3) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "rpad"; } +}; + + +class Item_func_lpad :public Item_str_func +{ + String tmp_value, lpad_str; +public: + Item_func_lpad(Item *arg1,Item *arg2,Item *arg3) + :Item_str_func(arg1,arg2,arg3) {} + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "lpad"; } +}; + + +class Item_func_conv :public Item_str_func +{ +public: + Item_func_conv(Item *a,Item *b,Item *c) :Item_str_func(a,b,c) {} + const char *func_name() const { return "conv"; } + String *val_str(String *); + void fix_length_and_dec() + { + collation.set(default_charset()); + max_length=64; + maybe_null= 1; + } +}; + + +class Item_func_hex :public Item_str_func +{ + String tmp_value; +public: + Item_func_hex(Item *a) :Item_str_func(a) {} + const char *func_name() const { return "hex"; } + String *val_str(String *); + void fix_length_and_dec() + { + collation.set(default_charset()); + decimals=0; + // InfiniDB fix max length to be 16 for numeric argument + if (args[0]->result_type() == DECIMAL_RESULT || + args[0]->result_type() == REAL_RESULT || + args[0]->result_type() == INT_RESULT) + max_length=16*collation.collation->mbmaxlen; + else + max_length=args[0]->max_length*2*collation.collation->mbmaxlen; + } +}; + +class Item_func_unhex :public Item_str_func +{ + String tmp_value; +public: + Item_func_unhex(Item *a) :Item_str_func(a) + { + /* there can be bad hex strings */ + maybe_null= 1; + } + const char *func_name() const { return "unhex"; } + String *val_str(String *); + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + decimals=0; + max_length=(1+args[0]->max_length)/2; + } +}; + + +class Item_func_binary :public Item_str_func +{ +public: + Item_func_binary(Item *a) :Item_str_func(a) {} + String *val_str(String *a) + { + DBUG_ASSERT(fixed == 1); + String *tmp=args[0]->val_str(a); + null_value=args[0]->null_value; + if (tmp) + tmp->set_charset(&my_charset_bin); + return tmp; + } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + max_length=args[0]->max_length; + } + virtual void print(String *str, enum_query_type query_type); + const char *func_name() const { return "cast_as_binary"; } +}; + + +class Item_load_file :public Item_str_func +{ + String tmp_value; +public: + Item_load_file(Item *a) :Item_str_func(a) {} + String *val_str(String *); + const char *func_name() const { return "load_file"; } + void fix_length_and_dec() + { + collation.set(&my_charset_bin, DERIVATION_COERCIBLE); + maybe_null=1; + max_length=MAX_BLOB_WIDTH; + } +}; + + +class Item_func_export_set: public Item_str_func +{ + public: + Item_func_export_set(Item *a,Item *b,Item* c) :Item_str_func(a,b,c) {} + Item_func_export_set(Item *a,Item *b,Item* c,Item* d) :Item_str_func(a,b,c,d) {} + Item_func_export_set(Item *a,Item *b,Item* c,Item* d,Item* e) :Item_str_func(a,b,c,d,e) {} + String *val_str(String *str); + void fix_length_and_dec(); + const char *func_name() const { return "export_set"; } +}; + +class Item_func_inet_ntoa : public Item_str_func +{ +public: + Item_func_inet_ntoa(Item *a) :Item_str_func(a) + { + } + String* val_str(String* str); + const char *func_name() const { return "inet_ntoa"; } + void fix_length_and_dec() + { + decimals= 0; + max_length= 3 * 8 + 7; + maybe_null= 1; + } +}; + +class Item_func_quote :public Item_str_func +{ + String tmp_value; +public: + Item_func_quote(Item *a) :Item_str_func(a) {} + const char *func_name() const { return "quote"; } + String *val_str(String *); + void fix_length_and_dec() + { + collation.set(args[0]->collation); + max_length= args[0]->max_length * 2 + 2; + } +}; + +class Item_func_conv_charset :public Item_str_func +{ + bool use_cached_value; +public: + bool safe; + CHARSET_INFO *conv_charset; // keep it public + Item_func_conv_charset(Item *a, CHARSET_INFO *cs) :Item_str_func(a) + { conv_charset= cs; use_cached_value= 0; safe= 0; } + Item_func_conv_charset(Item *a, CHARSET_INFO *cs, bool cache_if_const) + :Item_str_func(a) + { + DBUG_ASSERT(args[0]->fixed); + conv_charset= cs; + if (cache_if_const && args[0]->const_item()) + { + uint errors= 0; + String tmp, *str= args[0]->val_str(&tmp); + if (!str || str_value.copy(str->ptr(), str->length(), + str->charset(), conv_charset, &errors)) + null_value= 1; + use_cached_value= 1; + str_value.mark_as_const(); + safe= (errors == 0); + } + else + { + use_cached_value= 0; + /* + Conversion from and to "binary" is safe. + Conversion to Unicode is safe. + Other kind of conversions are potentially lossy. + */ + safe= (args[0]->collation.collation == &my_charset_bin || + cs == &my_charset_bin || + (cs->state & MY_CS_UNICODE)); + } + } + String *val_str(String *); + void fix_length_and_dec(); + const char *func_name() const { return "convert"; } + virtual void print(String *str, enum_query_type query_type); +}; + +class Item_func_set_collation :public Item_str_func +{ +public: + Item_func_set_collation(Item *a, Item *b) :Item_str_func(a,b) {}; + String *val_str(String *); + void fix_length_and_dec(); + bool eq(const Item *item, bool binary_cmp) const; + const char *func_name() const { return "collate"; } + enum Functype functype() const { return COLLATE_FUNC; } + virtual void print(String *str, enum_query_type query_type); + Item_field *filed_for_view_update() + { + /* this function is transparent for view updating */ + return args[0]->filed_for_view_update(); + } +}; + +class Item_func_charset :public Item_str_func +{ +public: + Item_func_charset(Item *a) :Item_str_func(a) {} + String *val_str(String *); + const char *func_name() const { return "charset"; } + void fix_length_and_dec() + { + collation.set(system_charset_info); + max_length= 64 * collation.collation->mbmaxlen; // should be enough + maybe_null= 0; + }; + table_map not_null_tables() const { return 0; } +}; + +class Item_func_collation :public Item_str_func +{ +public: + Item_func_collation(Item *a) :Item_str_func(a) {} + String *val_str(String *); + const char *func_name() const { return "collation"; } + void fix_length_and_dec() + { + collation.set(system_charset_info); + max_length= 64 * collation.collation->mbmaxlen; // should be enough + maybe_null= 0; + }; + table_map not_null_tables() const { return 0; } +}; + +class Item_func_crc32 :public Item_int_func +{ + String value; +public: + Item_func_crc32(Item *a) :Item_int_func(a) { unsigned_flag= 1; } + const char *func_name() const { return "crc32"; } + void fix_length_and_dec() { max_length=10; } + longlong val_int(); +}; + +class Item_func_uncompressed_length : public Item_int_func +{ + String value; +public: + Item_func_uncompressed_length(Item *a):Item_int_func(a){} + const char *func_name() const{return "uncompressed_length";} + void fix_length_and_dec() { max_length=10; } + longlong val_int(); +}; + +#ifdef HAVE_COMPRESS +#define ZLIB_DEPENDED_FUNCTION ; +#else +#define ZLIB_DEPENDED_FUNCTION { null_value=1; return 0; } +#endif + +class Item_func_compress: public Item_str_func +{ + String buffer; +public: + Item_func_compress(Item *a):Item_str_func(a){} + void fix_length_and_dec(){max_length= (args[0]->max_length*120)/100+12;} + const char *func_name() const{return "compress";} + String *val_str(String *) ZLIB_DEPENDED_FUNCTION +}; + +class Item_func_uncompress: public Item_str_func +{ + String buffer; +public: + Item_func_uncompress(Item *a): Item_str_func(a){} + void fix_length_and_dec(){ maybe_null= 1; max_length= MAX_BLOB_WIDTH; } + const char *func_name() const{return "uncompress";} + String *val_str(String *) ZLIB_DEPENDED_FUNCTION +}; + +#define UUID_LENGTH (8+1+4+1+4+1+4+1+12) +class Item_func_uuid: public Item_str_func +{ +public: + Item_func_uuid(): Item_str_func() {} + void fix_length_and_dec() { + collation.set(system_charset_info); + /* + NOTE! uuid() should be changed to use 'ascii' + charset when hex(), format(), md5(), etc, and implicit + number-to-string conversion will use 'ascii' + */ + max_length= UUID_LENGTH * system_charset_info->mbmaxlen; + } + const char *func_name() const{ return "uuid"; } + String *val_str(String *); +}; + diff --git a/dbcon/mysql/item_sum.cc b/dbcon/mysql/item_sum.cc new file mode 100644 index 00000000..0a313216 --- /dev/null +++ b/dbcon/mysql/item_sum.cc @@ -0,0 +1,3622 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/** + @file + + @brief + Sum functions (COUNT, MIN...) +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include "sql_select.h" + +/** + Prepare an aggregate function item for checking context conditions. + + The function initializes the members of the Item_sum object created + for a set function that are used to check validity of the set function + occurrence. + If the set function is not allowed in any subquery where it occurs + an error is reported immediately. + + @param thd reference to the thread context info + + @note + This function is to be called for any item created for a set function + object when the traversal of trees built for expressions used in the query + is performed at the phase of context analysis. This function is to + be invoked at the descent of this traversal. + @retval + TRUE if an error is reported + @retval + FALSE otherwise +*/ + +bool Item_sum::init_sum_func_check(THD *thd) +{ + if (!thd->lex->allow_sum_func) + { + my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE), + MYF(0)); + return TRUE; + } + /* Set a reference to the nesting set function if there is any */ + in_sum_func= thd->lex->in_sum_func; + /* Save a pointer to object to be used in items for nested set functions */ + thd->lex->in_sum_func= this; + nest_level= thd->lex->current_select->nest_level; + ref_by= 0; + aggr_level= -1; + aggr_sel= NULL; + max_arg_level= -1; + max_sum_func_level= -1; + outer_fields.empty(); + return FALSE; +} + +/** + Check constraints imposed on a usage of a set function. + + The method verifies whether context conditions imposed on a usage + of any set function are met for this occurrence. + It checks whether the set function occurs in the position where it + can be aggregated and, when it happens to occur in argument of another + set function, the method checks that these two functions are aggregated in + different subqueries. + If the context conditions are not met the method reports an error. + If the set function is aggregated in some outer subquery the method + adds it to the chain of items for such set functions that is attached + to the the st_select_lex structure for this subquery. + + A number of designated members of the object are used to check the + conditions. They are specified in the comment before the Item_sum + class declaration. + Additionally a bitmap variable called allow_sum_func is employed. + It is included into the thd->lex structure. + The bitmap contains 1 at n-th position if the set function happens + to occur under a construct of the n-th level subquery where usage + of set functions are allowed (i.e either in the SELECT list or + in the HAVING clause of the corresponding subquery) + Consider the query: + @code + SELECT SUM(t1.b) FROM t1 GROUP BY t1.a + HAVING t1.a IN (SELECT t2.c FROM t2 WHERE AVG(t1.b) > 20) AND + t1.a > (SELECT MIN(t2.d) FROM t2); + @endcode + allow_sum_func will contain: + - for SUM(t1.b) - 1 at the first position + - for AVG(t1.b) - 1 at the first position, 0 at the second position + - for MIN(t2.d) - 1 at the first position, 1 at the second position. + + @param thd reference to the thread context info + @param ref location of the pointer to this item in the embedding expression + + @note + This function is to be called for any item created for a set function + object when the traversal of trees built for expressions used in the query + is performed at the phase of context analysis. This function is to + be invoked at the ascent of this traversal. + + @retval + TRUE if an error is reported + @retval + FALSE otherwise +*/ + +bool Item_sum::check_sum_func(THD *thd, Item **ref) +{ + bool invalid= FALSE; + nesting_map allow_sum_func= thd->lex->allow_sum_func; + /* + The value of max_arg_level is updated if an argument of the set function + contains a column reference resolved against a subquery whose level is + greater than the current value of max_arg_level. + max_arg_level cannot be greater than nest level. + nest level is always >= 0 + */ + if (nest_level == max_arg_level) + { + /* + The function must be aggregated in the current subquery, + If it is there under a construct where it is not allowed + we report an error. + */ + invalid= !(allow_sum_func & (1 << max_arg_level)); + } + else if (max_arg_level >= 0 || !(allow_sum_func & (1 << nest_level))) + { + /* + The set function can be aggregated only in outer subqueries. + Try to find a subquery where it can be aggregated; + If we fail to find such a subquery report an error. + */ + if (register_sum_func(thd, ref)) + return TRUE; + invalid= aggr_level < 0 && !(allow_sum_func & (1 << nest_level)); + if (!invalid && thd->variables.sql_mode & MODE_ANSI) + invalid= aggr_level < 0 && max_arg_level < nest_level; + } + if (!invalid && aggr_level < 0) + { + aggr_level= nest_level; + aggr_sel= thd->lex->current_select; + } + /* + By this moment we either found a subquery where the set function is + to be aggregated and assigned a value that is >= 0 to aggr_level, + or set the value of 'invalid' to TRUE to report later an error. + */ + /* + Additionally we have to check whether possible nested set functions + are acceptable here: they are not, if the level of aggregation of + some of them is less than aggr_level. + */ + if (!invalid) + invalid= aggr_level <= max_sum_func_level; + if (invalid) + { + my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE), + MYF(0)); + return TRUE; + } + + if (in_sum_func) + { + /* + If the set function is nested adjust the value of + max_sum_func_level for the nesting set function. + We take into account only enclosed set functions that are to be + aggregated on the same level or above of the nest level of + the enclosing set function. + But we must always pass up the max_sum_func_level because it is + the maximum nested level of all directly and indirectly enclosed + set functions. We must do that even for set functions that are + aggregated inside of their enclosing set function's nest level + because the enclosing function may contain another enclosing + function that is to be aggregated outside or on the same level + as its parent's nest level. + */ + if (in_sum_func->nest_level >= aggr_level) + set_if_bigger(in_sum_func->max_sum_func_level, aggr_level); + set_if_bigger(in_sum_func->max_sum_func_level, max_sum_func_level); + } + + /* + Check that non-aggregated fields and sum functions aren't mixed in the + same select in the ONLY_FULL_GROUP_BY mode. + */ + if (outer_fields.elements) + { + Item_field *field; + /* + Here we compare the nesting level of the select to which an outer field + belongs to with the aggregation level of the sum function. All fields in + the outer_fields list are checked. + + If the nesting level is equal to the aggregation level then the field is + aggregated by this sum function. + If the nesting level is less than the aggregation level then the field + belongs to an outer select. In this case if there is an embedding sum + function add current field to functions outer_fields list. If there is + no embedding function then the current field treated as non aggregated + and the select it belongs to is marked accordingly. + If the nesting level is greater than the aggregation level then it means + that this field was added by an inner sum function. + Consider an example: + + select avg ( <-- we are here, checking outer.f1 + select ( + select sum(outer.f1 + inner.f1) from inner + ) from outer) + from most_outer; + + In this case we check that no aggregate functions are used in the + select the field belongs to. If there are some then an error is + raised. + */ + List_iterator of(outer_fields); + while ((field= of++)) + { + SELECT_LEX *sel= field->cached_table->select_lex; + if (sel->nest_level < aggr_level) + { + if (in_sum_func) + { + /* + Let upper function decide whether this field is a non + aggregated one. + */ + in_sum_func->outer_fields.push_back(field); + } + else + sel->full_group_by_flag|= NON_AGG_FIELD_USED; + } + if (sel->nest_level > aggr_level && + (sel->full_group_by_flag & SUM_FUNC_USED) && + !sel->group_list.elements) + { + my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS, + ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0)); + return TRUE; + } + } + } + aggr_sel->full_group_by_flag|= SUM_FUNC_USED; + update_used_tables(); + thd->lex->in_sum_func= in_sum_func; + return FALSE; +} + +/** + Attach a set function to the subquery where it must be aggregated. + + The function looks for an outer subquery where the set function must be + aggregated. If it finds such a subquery then aggr_level is set to + the nest level of this subquery and the item for the set function + is added to the list of set functions used in nested subqueries + inner_sum_func_list defined for each subquery. When the item is placed + there the field 'ref_by' is set to ref. + + @note + Now we 'register' only set functions that are aggregated in outer + subqueries. Actually it makes sense to link all set function for + a subquery in one chain. It would simplify the process of 'splitting' + for set functions. + + @param thd reference to the thread context info + @param ref location of the pointer to this item in the embedding expression + + @retval + FALSE if the executes without failures (currently always) + @retval + TRUE otherwise +*/ + +bool Item_sum::register_sum_func(THD *thd, Item **ref) +{ + SELECT_LEX *sl; + nesting_map allow_sum_func= thd->lex->allow_sum_func; + for (sl= thd->lex->current_select->master_unit()->outer_select() ; + sl && sl->nest_level > max_arg_level; + sl= sl->master_unit()->outer_select() ) + { + if (aggr_level < 0 && (allow_sum_func & (1 << sl->nest_level))) + { + /* Found the most nested subquery where the function can be aggregated */ + aggr_level= sl->nest_level; + aggr_sel= sl; + } + } + if (sl && (allow_sum_func & (1 << sl->nest_level))) + { + /* + We reached the subquery of level max_arg_level and checked + that the function can be aggregated here. + The set function will be aggregated in this subquery. + */ + aggr_level= sl->nest_level; + aggr_sel= sl; + + } + if (aggr_level >= 0) + { + ref_by= ref; + /* Add the object to the list of registered objects assigned to aggr_sel */ + if (!aggr_sel->inner_sum_func_list) + next= this; + else + { + next= aggr_sel->inner_sum_func_list->next; + aggr_sel->inner_sum_func_list->next= this; + } + aggr_sel->inner_sum_func_list= this; + aggr_sel->with_sum_func= 1; + + /* + Mark Item_subselect(s) as containing aggregate function all the way up + to aggregate function's calculation context. + Note that we must not mark the Item of calculation context itself + because with_sum_func on the calculation context st_select_lex is + already set above. + + with_sum_func being set for an Item means that this Item refers + (somewhere in it, e.g. one of its arguments if it's a function) directly + or through intermediate items to an aggregate function that is calculated + in a context "outside" of the Item (e.g. in the current or outer select). + + with_sum_func being set for an st_select_lex means that this st_select_lex + has aggregate functions directly referenced (i.e. not through a sub-select). + */ + for (sl= thd->lex->current_select; + sl && sl != aggr_sel && sl->master_unit()->item; + sl= sl->master_unit()->outer_select() ) + sl->master_unit()->item->with_sum_func= 1; + } + thd->lex->current_select->mark_as_dependent(aggr_sel); + return FALSE; +} + + +Item_sum::Item_sum(List &list) :arg_count(list.elements), + forced_const(FALSE), IDB_thd(0) +{ + if ((args=(Item**) sql_alloc(sizeof(Item*)*arg_count))) + { + uint i=0; + List_iterator_fast li(list); + Item *item; + + while ((item=li++)) + { + args[i++]= item; + } + } + if (!(orig_args= (Item **) sql_alloc(sizeof(Item *) * arg_count))) + { + args= NULL; + } + mark_as_sum_func(); + list.empty(); // Fields are used +} + + +/** + Constructor used in processing select with temporary tebles. +*/ + +Item_sum::Item_sum(THD *thd, Item_sum *item): + Item_result_field(thd, item), + aggr_sel(item->aggr_sel), + nest_level(item->nest_level), aggr_level(item->aggr_level), + quick_group(item->quick_group), + arg_count(item->arg_count), orig_args(NULL), + used_tables_cache(item->used_tables_cache), + forced_const(item->forced_const), + IDB_thd(thd) +{ + if (arg_count <= 2) + { + args=tmp_args; + orig_args=tmp_orig_args; + } + else + { + if (!(args= (Item**) thd->alloc(sizeof(Item*)*arg_count))) + return; + if (!(orig_args= (Item**) thd->alloc(sizeof(Item*)*arg_count))) + return; + } + memcpy(args, item->args, sizeof(Item*)*arg_count); + memcpy(orig_args, item->orig_args, sizeof(Item*)*arg_count); +} + + +void Item_sum::mark_as_sum_func() +{ + SELECT_LEX *cur_select= current_thd->lex->current_select; + cur_select->n_sum_items++; + cur_select->with_sum_func= 1; + with_sum_func= 1; + // @InfiniDB. Store thd pointer for future reference. + IDB_thd = current_thd; +} + + +void Item_sum::make_field(Send_field *tmp_field) +{ + if (args[0]->type() == Item::FIELD_ITEM && keep_field_type()) + { + ((Item_field*) args[0])->field->make_field(tmp_field); + /* For expressions only col_name should be non-empty string. */ + char *empty_string= (char*)""; + tmp_field->db_name= empty_string; + tmp_field->org_table_name= empty_string; + tmp_field->table_name= empty_string; + tmp_field->org_col_name= empty_string; + tmp_field->col_name= name; + if (maybe_null) + tmp_field->flags&= ~NOT_NULL_FLAG; + } + else + init_make_field(tmp_field, field_type()); +} + + +void Item_sum::print(String *str, enum_query_type query_type) +{ + /* orig_args is not filled with valid values until fix_fields() */ + Item **pargs= fixed ? orig_args : args; + str->append(func_name()); + for (uint i=0 ; i < arg_count ; i++) + { + if (i) + str->append(','); + pargs[i]->print(str, query_type); + } + str->append(')'); +} + +void Item_sum::fix_num_length_and_dec() +{ + decimals=0; + for (uint i=0 ; i < arg_count ; i++) + set_if_bigger(decimals,args[i]->decimals); + max_length=float_length(decimals); +} + +Item *Item_sum::get_tmp_table_item(THD *thd) +{ + Item_sum* sum_item= (Item_sum *) copy_or_same(thd); + if (sum_item && sum_item->result_field) // If not a const sum func + { + Field *result_field_tmp= sum_item->result_field; + for (uint i=0 ; i < sum_item->arg_count ; i++) + { + Item *arg= sum_item->args[i]; + if (!arg->const_item()) + { + if (arg->type() == Item::FIELD_ITEM) + ((Item_field*) arg)->field= result_field_tmp++; + else + sum_item->args[i]= new Item_field(result_field_tmp++); + } + } + } + return sum_item; +} + + +bool Item_sum::walk (Item_processor processor, bool walk_subquery, + uchar *argument) +{ + if (arg_count) + { + Item **arg,**arg_end; + for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++) + { + if ((*arg)->walk(processor, walk_subquery, argument)) + return 1; + } + } + return (this->*processor)(argument); +} + + +Field *Item_sum::create_tmp_field(bool group, TABLE *table, + uint convert_blob_length) +{ + Field *field; + switch (result_type()) { + case REAL_RESULT: + field= new Field_double(max_length, maybe_null, name, decimals, TRUE); + break; + case INT_RESULT: + field= new Field_longlong(max_length, maybe_null, name, unsigned_flag); + break; + case STRING_RESULT: + if (max_length/collation.collation->mbmaxlen <= 255 || + convert_blob_length > Field_varstring::MAX_SIZE || + !convert_blob_length) + return make_string_field(table); + field= new Field_varstring(convert_blob_length, maybe_null, + name, table->s, collation.collation); + break; + case DECIMAL_RESULT: + field= Field_new_decimal::new_decimal_field(this); + break; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + return 0; + } + if (field) + field->init(table); + return field; +} + + +void Item_sum::update_used_tables () +{ + if (!forced_const) + { + used_tables_cache= 0; + for (uint i=0 ; i < arg_count ; i++) + { + args[i]->update_used_tables(); + used_tables_cache|= args[i]->used_tables(); + } + + used_tables_cache&= PSEUDO_TABLE_BITS; + + /* the aggregate function is aggregated into its local context */ + used_tables_cache |= (1 << aggr_sel->join->tables) - 1; + } +} + + +Item *Item_sum::set_arg(int i, THD *thd, Item *new_val) +{ + thd->change_item_tree(args + i, new_val); + return new_val; +} + + +String * +Item_sum_num::val_str(String *str) +{ + return val_string_from_real(str); +} + + +my_decimal *Item_sum_num::val_decimal(my_decimal *decimal_value) +{ + return val_decimal_from_real(decimal_value); +} + + +String * +Item_sum_int::val_str(String *str) +{ + return val_string_from_int(str); +} + + +my_decimal *Item_sum_int::val_decimal(my_decimal *decimal_value) +{ + return val_decimal_from_int(decimal_value); +} + + +bool +Item_sum_num::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + + if (init_sum_func_check(thd)) + return TRUE; + + decimals=0; + maybe_null=0; + for (uint i=0 ; i < arg_count ; i++) + { + if (args[i]->fix_fields(thd, args + i) || args[i]->check_cols(1)) + return TRUE; + set_if_bigger(decimals, args[i]->decimals); + maybe_null |= args[i]->maybe_null; + } + result_field=0; + max_length=float_length(decimals); + null_value=1; + fix_length_and_dec(); + + if (check_sum_func(thd, ref)) + return TRUE; + + memcpy (orig_args, args, sizeof (Item *) * arg_count); + fixed= 1; + return FALSE; +} + + +Item_sum_hybrid::Item_sum_hybrid(THD *thd, Item_sum_hybrid *item) + :Item_sum(thd, item), value(item->value), hybrid_type(item->hybrid_type), + hybrid_field_type(item->hybrid_field_type), cmp_sign(item->cmp_sign), + was_values(item->was_values) +{ + /* copy results from old value */ + switch (hybrid_type) { + case INT_RESULT: + sum_int= item->sum_int; + break; + case DECIMAL_RESULT: + my_decimal2decimal(&item->sum_dec, &sum_dec); + break; + case REAL_RESULT: + sum= item->sum; + break; + case STRING_RESULT: + /* + This can happen with ROLLUP. Note that the value is already + copied at function call. + */ + break; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + collation.set(item->collation); +} + +bool +Item_sum_hybrid::fix_fields(THD *thd, Item **ref) +{ + DBUG_ASSERT(fixed == 0); + + Item *item= args[0]; + + if (init_sum_func_check(thd)) + return TRUE; + + // 'item' can be changed during fix_fields + if ((!item->fixed && item->fix_fields(thd, args)) || + (item= args[0])->check_cols(1)) + return TRUE; + decimals=item->decimals; + + switch (hybrid_type= item->result_type()) { + case INT_RESULT: + max_length= 20; + sum_int= 0; + break; + case DECIMAL_RESULT: + max_length= item->max_length; + my_decimal_set_zero(&sum_dec); + break; + case REAL_RESULT: + max_length= float_length(decimals); + sum= 0.0; + break; + case STRING_RESULT: + max_length= item->max_length; + break; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + }; + /* MIN/MAX can return NULL for empty set indepedent of the used column */ + maybe_null= 1; + unsigned_flag=item->unsigned_flag; + collation.set(item->collation); + result_field=0; + null_value=1; + fix_length_and_dec(); + item= item->real_item(); + if (item->type() == Item::FIELD_ITEM) + hybrid_field_type= ((Item_field*) item)->field->type(); + else + hybrid_field_type= Item::field_type(); + + if (check_sum_func(thd, ref)) + return TRUE; + + orig_args[0]= args[0]; + fixed= 1; + return FALSE; +} + +Field *Item_sum_hybrid::create_tmp_field(bool group, TABLE *table, + uint convert_blob_length) +{ + Field *field; + if (args[0]->type() == Item::FIELD_ITEM) + { + field= ((Item_field*) args[0])->field; + + if ((field= create_tmp_field_from_field(current_thd, field, name, table, + NULL, convert_blob_length))) + field->flags&= ~NOT_NULL_FLAG; + return field; + } + /* + DATE/TIME fields have STRING_RESULT result types. + In order to preserve field type, it's needed to handle DATE/TIME + fields creations separately. + */ + switch (args[0]->field_type()) { + case MYSQL_TYPE_DATE: + field= new Field_newdate(maybe_null, name, collation.collation); + break; + case MYSQL_TYPE_TIME: + field= new Field_time(maybe_null, name, collation.collation); + break; + case MYSQL_TYPE_TIMESTAMP: + case MYSQL_TYPE_DATETIME: + field= new Field_datetime(maybe_null, name, collation.collation); + break; + default: + return Item_sum::create_tmp_field(group, table, convert_blob_length); + } + if (field) + field->init(table); + return field; +} + + +/*********************************************************************** +** reset and add of sum_func +***********************************************************************/ + +/** + @todo + check if the following assignments are really needed +*/ +Item_sum_sum::Item_sum_sum(THD *thd, Item_sum_sum *item) + :Item_sum_num(thd, item), hybrid_type(item->hybrid_type), + curr_dec_buff(item->curr_dec_buff) +{ + /* TODO: check if the following assignments are really needed */ + if (hybrid_type == DECIMAL_RESULT) + { + my_decimal2decimal(item->dec_buffs, dec_buffs); + my_decimal2decimal(item->dec_buffs + 1, dec_buffs + 1); + } + else + sum= item->sum; +} + +Item *Item_sum_sum::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_sum(thd, this); +} + + +void Item_sum_sum::clear() +{ + DBUG_ENTER("Item_sum_sum::clear"); + null_value=1; + if (hybrid_type == DECIMAL_RESULT) + { + curr_dec_buff= 0; + my_decimal_set_zero(dec_buffs); + } + else + sum= 0.0; + DBUG_VOID_RETURN; +} + + +void Item_sum_sum::fix_length_and_dec() +{ + DBUG_ENTER("Item_sum_sum::fix_length_and_dec"); + maybe_null=null_value=1; + decimals= args[0]->decimals; + switch (args[0]->result_type()) { + case REAL_RESULT: + case STRING_RESULT: + hybrid_type= REAL_RESULT; + sum= 0.0; + break; + case INT_RESULT: + case DECIMAL_RESULT: + { + /* SUM result can't be longer than length(arg) + length(MAX_ROWS) */ + int precision= args[0]->decimal_precision() + DECIMAL_LONGLONG_DIGITS; + max_length= my_decimal_precision_to_length_no_truncation(precision, + decimals, + unsigned_flag); + curr_dec_buff= 0; + hybrid_type= DECIMAL_RESULT; + my_decimal_set_zero(dec_buffs); + break; + } + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + DBUG_PRINT("info", ("Type: %s (%d, %d)", + (hybrid_type == REAL_RESULT ? "REAL_RESULT" : + hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" : + hybrid_type == INT_RESULT ? "INT_RESULT" : + "--ILLEGAL!!!--"), + max_length, + (int)decimals)); + DBUG_VOID_RETURN; +} + + +bool Item_sum_sum::add() +{ + DBUG_ENTER("Item_sum_sum::add"); + if (hybrid_type == DECIMAL_RESULT) + { + my_decimal value, *val= args[0]->val_decimal(&value); + if (!args[0]->null_value) + { + my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs + (curr_dec_buff^1), + val, dec_buffs + curr_dec_buff); + curr_dec_buff^= 1; + null_value= 0; + } + } + else + { + sum+= args[0]->val_real(); + if (!args[0]->null_value) + null_value= 0; + } + DBUG_RETURN(0); +} + + +longlong Item_sum_sum::val_int() +{ + DBUG_ASSERT(fixed == 1); + if (hybrid_type == DECIMAL_RESULT) + { + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, dec_buffs + curr_dec_buff, unsigned_flag, + &result); + return result; + } + return (longlong) rint(val_real()); +} + + +double Item_sum_sum::val_real() +{ + DBUG_ASSERT(fixed == 1); + if (hybrid_type == DECIMAL_RESULT) + my_decimal2double(E_DEC_FATAL_ERROR, dec_buffs + curr_dec_buff, &sum); + return sum; +} + + +String *Item_sum_sum::val_str(String *str) +{ + if (hybrid_type == DECIMAL_RESULT) + return val_string_from_decimal(str); + return val_string_from_real(str); +} + + +my_decimal *Item_sum_sum::val_decimal(my_decimal *val) +{ + if (hybrid_type == DECIMAL_RESULT) + return (dec_buffs + curr_dec_buff); + return val_decimal_from_real(val); +} + +/***************************************************************************/ + +C_MODE_START + +/* Declarations for auxilary C-callbacks */ + +static int simple_raw_key_cmp(void* arg, const void* key1, const void* key2) +{ + return memcmp(key1, key2, *(uint *) arg); +} + + +static int item_sum_distinct_walk(void *element, element_count num_of_dups, + void *item) +{ + return ((Item_sum_distinct*) (item))->unique_walk_function(element); +} + +C_MODE_END + +/* Item_sum_distinct */ + +Item_sum_distinct::Item_sum_distinct(Item *item_arg) + :Item_sum_num(item_arg), tree(0) +{ + /* + quick_group is an optimizer hint, which means that GROUP BY can be + handled with help of index on grouped columns. + By setting quick_group to zero we force creation of temporary table + to perform GROUP BY. + */ + quick_group= 0; +} + + +Item_sum_distinct::Item_sum_distinct(THD *thd, Item_sum_distinct *original) + :Item_sum_num(thd, original), val(original->val), tree(0), + table_field_type(original->table_field_type) +{ + quick_group= 0; +} + + +/** + Behaves like an Integer except to fix_length_and_dec(). + Additionally div() converts val with this traits to a val with true + decimal traits along with conversion of integer value to decimal value. + This is to speedup SUM/AVG(DISTINCT) evaluation for 8-32 bit integer + values. +*/ +struct Hybrid_type_traits_fast_decimal: public + Hybrid_type_traits_integer +{ + virtual Item_result type() const { return DECIMAL_RESULT; } + virtual void fix_length_and_dec(Item *item, Item *arg) const + { Hybrid_type_traits_decimal::instance()->fix_length_and_dec(item, arg); } + + virtual void div(Hybrid_type *val, ulonglong u) const + { + int2my_decimal(E_DEC_FATAL_ERROR, val->integer, 0, val->dec_buf); + val->used_dec_buf_no= 0; + val->traits= Hybrid_type_traits_decimal::instance(); + val->traits->div(val, u); + } + static const Hybrid_type_traits_fast_decimal *instance(); + Hybrid_type_traits_fast_decimal() {}; +}; + +static const Hybrid_type_traits_fast_decimal fast_decimal_traits_instance; + +const Hybrid_type_traits_fast_decimal + *Hybrid_type_traits_fast_decimal::instance() +{ + return &fast_decimal_traits_instance; +} + +void Item_sum_distinct::fix_length_and_dec() +{ + DBUG_ASSERT(args[0]->fixed); + + table_field_type= args[0]->field_type(); + + /* Adjust tmp table type according to the chosen aggregation type */ + switch (args[0]->result_type()) { + case STRING_RESULT: + case REAL_RESULT: + val.traits= Hybrid_type_traits::instance(); + if (table_field_type != MYSQL_TYPE_FLOAT) + table_field_type= MYSQL_TYPE_DOUBLE; + break; + case INT_RESULT: + /* + Preserving int8, int16, int32 field types gives ~10% performance boost + as the size of result tree becomes significantly smaller. + Another speed up we gain by using longlong for intermediate + calculations. The range of int64 is enough to hold sum 2^32 distinct + integers each <= 2^32. + */ + if (table_field_type == MYSQL_TYPE_INT24 || + (table_field_type >= MYSQL_TYPE_TINY && + table_field_type <= MYSQL_TYPE_LONG)) + { + val.traits= Hybrid_type_traits_fast_decimal::instance(); + break; + } + table_field_type= MYSQL_TYPE_LONGLONG; + /* fallthrough */ + case DECIMAL_RESULT: + val.traits= Hybrid_type_traits_decimal::instance(); + if (table_field_type != MYSQL_TYPE_LONGLONG) + table_field_type= MYSQL_TYPE_NEWDECIMAL; + break; + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + val.traits->fix_length_and_dec(this, args[0]); +} + + +/** + @todo + check that the case of CHAR(0) works OK +*/ +bool Item_sum_distinct::setup(THD *thd) +{ + List field_list; + Create_field field_def; /* field definition */ + DBUG_ENTER("Item_sum_distinct::setup"); + /* It's legal to call setup() more than once when in a subquery */ + if (tree) + DBUG_RETURN(FALSE); + + /* + Virtual table and the tree are created anew on each re-execution of + PS/SP. Hence all further allocations are performed in the runtime + mem_root. + */ + if (field_list.push_back(&field_def)) + DBUG_RETURN(TRUE); + + null_value= maybe_null= 1; + quick_group= 0; + + DBUG_ASSERT(args[0]->fixed); + + field_def.init_for_tmp_table(table_field_type, args[0]->max_length, + args[0]->decimals, args[0]->maybe_null, + args[0]->unsigned_flag); + + if (! (table= create_virtual_tmp_table(thd, field_list))) + DBUG_RETURN(TRUE); + + /* XXX: check that the case of CHAR(0) works OK */ + tree_key_length= table->s->reclength - table->s->null_bytes; + + /* + Unique handles all unique elements in a tree until they can't fit + in. Then the tree is dumped to the temporary file. We can use + simple_raw_key_cmp because the table contains numbers only; decimals + are converted to binary representation as well. + */ + tree= new Unique(simple_raw_key_cmp, &tree_key_length, tree_key_length, + thd->variables.max_heap_table_size); + + is_evaluated= FALSE; + DBUG_RETURN(tree == 0); +} + + +bool Item_sum_distinct::add() +{ + args[0]->save_in_field(table->field[0], FALSE); + is_evaluated= FALSE; + if (!table->field[0]->is_null()) + { + DBUG_ASSERT(tree); + null_value= 0; + /* + '0' values are also stored in the tree. This doesn't matter + for SUM(DISTINCT), but is important for AVG(DISTINCT) + */ + return tree->unique_add(table->field[0]->ptr); + } + return 0; +} + + +bool Item_sum_distinct::unique_walk_function(void *element) +{ + memcpy(table->field[0]->ptr, element, tree_key_length); + ++count; + val.traits->add(&val, table->field[0]); + return 0; +} + + +void Item_sum_distinct::clear() +{ + DBUG_ENTER("Item_sum_distinct::clear"); + DBUG_ASSERT(tree != 0); /* we always have a tree */ + null_value= 1; + tree->reset(); + is_evaluated= FALSE; + DBUG_VOID_RETURN; +} + +void Item_sum_distinct::cleanup() +{ + Item_sum_num::cleanup(); + delete tree; + tree= 0; + table= 0; + is_evaluated= FALSE; +} + +Item_sum_distinct::~Item_sum_distinct() +{ + delete tree; + /* no need to free the table */ +} + + +void Item_sum_distinct::calculate_val_and_count() +{ + if (!is_evaluated) + { + count= 0; + val.traits->set_zero(&val); + /* + We don't have a tree only if 'setup()' hasn't been called; + this is the case of sql_select.cc:return_zero_rows. + */ + if (tree) + { + table->field[0]->set_notnull(); + tree->walk(item_sum_distinct_walk, (void*) this); + } + is_evaluated= TRUE; + } +} + + +double Item_sum_distinct::val_real() +{ + calculate_val_and_count(); + return val.traits->val_real(&val); +} + + +my_decimal *Item_sum_distinct::val_decimal(my_decimal *to) +{ + calculate_val_and_count(); + if (null_value) + return 0; + return val.traits->val_decimal(&val, to); +} + + +longlong Item_sum_distinct::val_int() +{ + calculate_val_and_count(); + return val.traits->val_int(&val, unsigned_flag); +} + + +String *Item_sum_distinct::val_str(String *str) +{ + calculate_val_and_count(); + if (null_value) + return 0; + return val.traits->val_str(&val, str, decimals); +} + +/* end of Item_sum_distinct */ + +/* Item_sum_avg_distinct */ + +void +Item_sum_avg_distinct::fix_length_and_dec() +{ + Item_sum_distinct::fix_length_and_dec(); + prec_increment= current_thd->variables.div_precincrement; + /* + AVG() will divide val by count. We need to reserve digits + after decimal point as the result can be fractional. + */ + decimals= min(decimals + prec_increment, NOT_FIXED_DEC); +} + + +void +Item_sum_avg_distinct::calculate_val_and_count() +{ + if (!is_evaluated) + { + Item_sum_distinct::calculate_val_and_count(); + if (count) + val.traits->div(&val, count); + is_evaluated= TRUE; + } +} + + +Item *Item_sum_count::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_count(thd, this); +} + + +void Item_sum_count::clear() +{ + count= 0; +} + + +bool Item_sum_count::add() +{ + if (!args[0]->maybe_null || !args[0]->is_null()) + count++; + return 0; +} + +longlong Item_sum_count::val_int() +{ + DBUG_ASSERT(fixed == 1); + return (longlong) count; +} + + +void Item_sum_count::cleanup() +{ + DBUG_ENTER("Item_sum_count::cleanup"); + count= 0; + Item_sum_int::cleanup(); + DBUG_VOID_RETURN; +} + + +/* + Avgerage +*/ +void Item_sum_avg::fix_length_and_dec() +{ + Item_sum_sum::fix_length_and_dec(); + maybe_null=null_value=1; + prec_increment= current_thd->variables.div_precincrement; + if (hybrid_type == DECIMAL_RESULT) + { + int precision= args[0]->decimal_precision() + prec_increment; + decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE); + max_length= my_decimal_precision_to_length_no_truncation(precision, + decimals, + unsigned_flag); + f_precision= min(precision+DECIMAL_LONGLONG_DIGITS, DECIMAL_MAX_PRECISION); + f_scale= args[0]->decimals; + dec_bin_size= my_decimal_get_binary_size(f_precision, f_scale); + } + else { + decimals= min(args[0]->decimals + prec_increment, NOT_FIXED_DEC); + max_length= args[0]->max_length + prec_increment; + } +} + + +Item *Item_sum_avg::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_avg(thd, this); +} + + +Field *Item_sum_avg::create_tmp_field(bool group, TABLE *table, + uint convert_blob_len) +{ + Field *field; + if (group) + { + /* + We must store both value and counter in the temporary table in one field. + The easiest way is to do this is to store both value in a string + and unpack on access. + */ + field= new Field_string(((hybrid_type == DECIMAL_RESULT) ? + dec_bin_size : sizeof(double)) + sizeof(longlong), + 0, name, &my_charset_bin); + } + else if (hybrid_type == DECIMAL_RESULT) + field= new Field_new_decimal(max_length, maybe_null, name, + decimals, unsigned_flag); + else + field= new Field_double(max_length, maybe_null, name, decimals, TRUE); + if (field) + field->init(table); + return field; +} + + +void Item_sum_avg::clear() +{ + Item_sum_sum::clear(); + count=0; +} + + +bool Item_sum_avg::add() +{ + if (Item_sum_sum::add()) + return TRUE; + if (!args[0]->null_value) + count++; + return FALSE; +} + +double Item_sum_avg::val_real() +{ + DBUG_ASSERT(fixed == 1); + if (!count) + { + null_value=1; + return 0.0; + } + return Item_sum_sum::val_real() / ulonglong2double(count); +} + + +my_decimal *Item_sum_avg::val_decimal(my_decimal *val) +{ + my_decimal sum_buff, cnt; + const my_decimal *sum_dec; + DBUG_ASSERT(fixed == 1); + if (!count) + { + null_value=1; + return NULL; + } + + /* + For non-DECIMAL hybrid_type the division will be done in + Item_sum_avg::val_real(). + */ + if (hybrid_type != DECIMAL_RESULT) + return val_decimal_from_real(val); + + sum_dec= dec_buffs + curr_dec_buff; + int2my_decimal(E_DEC_FATAL_ERROR, count, 0, &cnt); + my_decimal_div(E_DEC_FATAL_ERROR, val, sum_dec, &cnt, prec_increment); + return val; +} + + +String *Item_sum_avg::val_str(String *str) +{ + if (hybrid_type == DECIMAL_RESULT) + return val_string_from_decimal(str); + return val_string_from_real(str); +} + + +/* + Standard deviation +*/ + +double Item_sum_std::val_real() +{ + DBUG_ASSERT(fixed == 1); + double nr= Item_sum_variance::val_real(); + DBUG_ASSERT(nr >= 0.0); + return sqrt(nr); +} + +Item *Item_sum_std::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_std(thd, this); +} + + +/* + Variance +*/ + + +/** + Variance implementation for floating-point implementations, without + catastrophic cancellation, from Knuth's _TAoCP_, 3rd ed, volume 2, pg232. + This alters the value at m, s, and increments count. +*/ + +/* + These two functions are used by the Item_sum_variance and the + Item_variance_field classes, which are unrelated, and each need to calculate + variance. The difference between the two classes is that the first is used + for a mundane SELECT, while the latter is used in a GROUPing SELECT. +*/ +static void variance_fp_recurrence_next(double *m, double *s, ulonglong *count, double nr) +{ + *count += 1; + + if (*count == 1) + { + *m= nr; + *s= 0; + } + else + { + double m_kminusone= *m; + *m= m_kminusone + (nr - m_kminusone) / (double) *count; + *s= *s + (nr - m_kminusone) * (nr - *m); + } +} + + +static double variance_fp_recurrence_result(double s, ulonglong count, bool is_sample_variance) +{ + if (count == 1) + return 0.0; + + if (is_sample_variance) + return s / (count - 1); + + /* else, is a population variance */ + return s / count; +} + + +Item_sum_variance::Item_sum_variance(THD *thd, Item_sum_variance *item): + Item_sum_num(thd, item), hybrid_type(item->hybrid_type), + count(item->count), sample(item->sample), + prec_increment(item->prec_increment) +{ + recurrence_m= item->recurrence_m; + recurrence_s= item->recurrence_s; +} + + +void Item_sum_variance::fix_length_and_dec() +{ + DBUG_ENTER("Item_sum_variance::fix_length_and_dec"); + maybe_null= null_value= 1; + prec_increment= current_thd->variables.div_precincrement; + + /* + According to the SQL2003 standard (Part 2, Foundations; sec 10.9, + aggregate function; paragraph 7h of Syntax Rules), "the declared + type of the result is an implementation-defined aproximate numeric + type. + */ + hybrid_type= REAL_RESULT; + + switch (args[0]->result_type()) { + case REAL_RESULT: + case STRING_RESULT: + decimals= min(args[0]->decimals + 4, NOT_FIXED_DEC); + break; + case INT_RESULT: + case DECIMAL_RESULT: + { + int precision= args[0]->decimal_precision()*2 + prec_increment; + decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE); + max_length= my_decimal_precision_to_length_no_truncation(precision, + decimals, + unsigned_flag); + + break; + } + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } + DBUG_PRINT("info", ("Type: REAL_RESULT (%d, %d)", max_length, (int)decimals)); + DBUG_VOID_RETURN; +} + + +Item *Item_sum_variance::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_variance(thd, this); +} + + +/** + Create a new field to match the type of value we're expected to yield. + If we're grouping, then we need some space to serialize variables into, to + pass around. +*/ +Field *Item_sum_variance::create_tmp_field(bool group, TABLE *table, + uint convert_blob_len) +{ + Field *field; + if (group) + { + /* + We must store both value and counter in the temporary table in one field. + The easiest way is to do this is to store both value in a string + and unpack on access. + */ + field= new Field_string(sizeof(double)*2 + sizeof(longlong), 0, name, &my_charset_bin); + } + else + field= new Field_double(max_length, maybe_null, name, decimals, TRUE); + + if (field != NULL) + field->init(table); + + return field; +} + + +void Item_sum_variance::clear() +{ + count= 0; +} + +bool Item_sum_variance::add() +{ + /* + Why use a temporary variable? We don't know if it is null until we + evaluate it, which has the side-effect of setting null_value . + */ + double nr= args[0]->val_real(); + + if (!args[0]->null_value) + variance_fp_recurrence_next(&recurrence_m, &recurrence_s, &count, nr); + return 0; +} + +double Item_sum_variance::val_real() +{ + DBUG_ASSERT(fixed == 1); + + /* + 'sample' is a 1/0 boolean value. If it is 1/true, id est this is a sample + variance call, then we should set nullness when the count of the items + is one or zero. If it's zero, i.e. a population variance, then we only + set nullness when the count is zero. + + Another way to read it is that 'sample' is the numerical threshhold, at and + below which a 'count' number of items is called NULL. + */ + DBUG_ASSERT((sample == 0) || (sample == 1)); + if (count <= sample) + { + null_value=1; + return 0.0; + } + + null_value=0; + return variance_fp_recurrence_result(recurrence_s, count, sample); +} + + +my_decimal *Item_sum_variance::val_decimal(my_decimal *dec_buf) +{ + DBUG_ASSERT(fixed == 1); + return val_decimal_from_real(dec_buf); +} + + +void Item_sum_variance::reset_field() +{ + double nr; + uchar *res= result_field->ptr; + + nr= args[0]->val_real(); /* sets null_value as side-effect */ + + if (args[0]->null_value) + bzero(res,sizeof(double)*2+sizeof(longlong)); + else + { + /* Serialize format is (double)m, (double)s, (longlong)count */ + ulonglong tmp_count; + double tmp_s; + float8store(res, nr); /* recurrence variable m */ + tmp_s= 0.0; + float8store(res + sizeof(double), tmp_s); + tmp_count= 1; + int8store(res + sizeof(double)*2, tmp_count); + } +} + + +void Item_sum_variance::update_field() +{ + ulonglong field_count; + uchar *res=result_field->ptr; + + double nr= args[0]->val_real(); /* sets null_value as side-effect */ + + if (args[0]->null_value) + return; + + /* Serialize format is (double)m, (double)s, (longlong)count */ + double field_recurrence_m, field_recurrence_s; + float8get(field_recurrence_m, res); + float8get(field_recurrence_s, res + sizeof(double)); + field_count=sint8korr(res+sizeof(double)*2); + + variance_fp_recurrence_next(&field_recurrence_m, &field_recurrence_s, &field_count, nr); + + float8store(res, field_recurrence_m); + float8store(res + sizeof(double), field_recurrence_s); + res+= sizeof(double)*2; + int8store(res,field_count); +} + + +/* min & max */ + +void Item_sum_hybrid::clear() +{ + switch (hybrid_type) { + case INT_RESULT: + sum_int= 0; + break; + case DECIMAL_RESULT: + my_decimal_set_zero(&sum_dec); + break; + case REAL_RESULT: + sum= 0.0; + break; + default: + value.length(0); + } + null_value= 1; +} + +double Item_sum_hybrid::val_real() +{ + DBUG_ASSERT(fixed == 1); + if (null_value) + return 0.0; + switch (hybrid_type) { + case STRING_RESULT: + { + char *end_not_used; + int err_not_used; + String *res; res=val_str(&str_value); + return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(), + &end_not_used, &err_not_used) : 0.0); + } + case INT_RESULT: + if (unsigned_flag) + return ulonglong2double(sum_int); + return (double) sum_int; + case DECIMAL_RESULT: + my_decimal2double(E_DEC_FATAL_ERROR, &sum_dec, &sum); + return sum; + case REAL_RESULT: + return sum; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + return 0; + } +} + +longlong Item_sum_hybrid::val_int() +{ + DBUG_ASSERT(fixed == 1); + if (null_value) + return 0; + switch (hybrid_type) { + case INT_RESULT: + return sum_int; + case DECIMAL_RESULT: + { + longlong result; + my_decimal2int(E_DEC_FATAL_ERROR, &sum_dec, unsigned_flag, &result); + return sum_int; + } + default: + return (longlong) rint(Item_sum_hybrid::val_real()); + } +} + + +my_decimal *Item_sum_hybrid::val_decimal(my_decimal *val) +{ + DBUG_ASSERT(fixed == 1); + if (null_value) + return 0; + switch (hybrid_type) { + case STRING_RESULT: + string2my_decimal(E_DEC_FATAL_ERROR, &value, val); + break; + case REAL_RESULT: + double2my_decimal(E_DEC_FATAL_ERROR, sum, val); + break; + case DECIMAL_RESULT: + val= &sum_dec; + break; + case INT_RESULT: + int2my_decimal(E_DEC_FATAL_ERROR, sum_int, unsigned_flag, val); + break; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + break; + } + return val; // Keep compiler happy +} + + +String * +Item_sum_hybrid::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + if (null_value) + return 0; + switch (hybrid_type) { + case STRING_RESULT: + return &value; + case REAL_RESULT: + str->set_real(sum,decimals, &my_charset_bin); + break; + case DECIMAL_RESULT: + my_decimal2string(E_DEC_FATAL_ERROR, &sum_dec, 0, 0, 0, str); + return str; + case INT_RESULT: + str->set_int(sum_int, unsigned_flag, &my_charset_bin); + break; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + break; + } + return str; // Keep compiler happy +} + + +void Item_sum_hybrid::cleanup() +{ + DBUG_ENTER("Item_sum_hybrid::cleanup"); + Item_sum::cleanup(); + forced_const= FALSE; + + /* + by default it is TRUE to avoid TRUE reporting by + Item_func_not_all/Item_func_nop_all if this item was never called. + + no_rows_in_result() set it to FALSE if was not results found. + If some results found it will be left unchanged. + */ + was_values= TRUE; + DBUG_VOID_RETURN; +} + +void Item_sum_hybrid::no_rows_in_result() +{ + was_values= FALSE; + clear(); +} + + +Item *Item_sum_min::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_min(thd, this); +} + + +bool Item_sum_min::add() +{ + switch (hybrid_type) { + case STRING_RESULT: + { + String *result=args[0]->val_str(&tmp_value); + if (!args[0]->null_value && + (null_value || sortcmp(&value,result,collation.collation) > 0)) + { + value.copy(*result); + null_value=0; + } + } + break; + case INT_RESULT: + { + longlong nr=args[0]->val_int(); + if (!args[0]->null_value && (null_value || + (unsigned_flag && + (ulonglong) nr < (ulonglong) sum_int) || + (!unsigned_flag && nr < sum_int))) + { + sum_int=nr; + null_value=0; + } + } + break; + case DECIMAL_RESULT: + { + my_decimal value_buff, *val= args[0]->val_decimal(&value_buff); + if (!args[0]->null_value && + (null_value || (my_decimal_cmp(&sum_dec, val) > 0))) + { + my_decimal2decimal(val, &sum_dec); + null_value= 0; + } + } + break; + case REAL_RESULT: + { + double nr= args[0]->val_real(); + if (!args[0]->null_value && (null_value || nr < sum)) + { + sum=nr; + null_value=0; + } + } + break; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + break; + } + return 0; +} + + +Item *Item_sum_max::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_max(thd, this); +} + + +bool Item_sum_max::add() +{ + switch (hybrid_type) { + case STRING_RESULT: + { + String *result=args[0]->val_str(&tmp_value); + if (!args[0]->null_value && + (null_value || sortcmp(&value,result,collation.collation) < 0)) + { + value.copy(*result); + null_value=0; + } + } + break; + case INT_RESULT: + { + longlong nr=args[0]->val_int(); + if (!args[0]->null_value && (null_value || + (unsigned_flag && + (ulonglong) nr > (ulonglong) sum_int) || + (!unsigned_flag && nr > sum_int))) + { + sum_int=nr; + null_value=0; + } + } + break; + case DECIMAL_RESULT: + { + my_decimal value_buff, *val= args[0]->val_decimal(&value_buff); + if (!args[0]->null_value && + (null_value || (my_decimal_cmp(val, &sum_dec) > 0))) + { + my_decimal2decimal(val, &sum_dec); + null_value= 0; + } + } + break; + case REAL_RESULT: + { + double nr= args[0]->val_real(); + if (!args[0]->null_value && (null_value || nr > sum)) + { + sum=nr; + null_value=0; + } + } + break; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + break; + } + return 0; +} + + +/* bit_or and bit_and */ + +longlong Item_sum_bit::val_int() +{ + DBUG_ASSERT(fixed == 1); + return (longlong) bits; +} + + +void Item_sum_bit::clear() +{ + bits= reset_bits; +} + +Item *Item_sum_or::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_or(thd, this); +} + + +bool Item_sum_or::add() +{ + ulonglong value= (ulonglong) args[0]->val_int(); + if (!args[0]->null_value) + bits|=value; + return 0; +} + +Item *Item_sum_xor::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_xor(thd, this); +} + + +bool Item_sum_xor::add() +{ + ulonglong value= (ulonglong) args[0]->val_int(); + if (!args[0]->null_value) + bits^=value; + return 0; +} + +Item *Item_sum_and::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_and(thd, this); +} + + +bool Item_sum_and::add() +{ + ulonglong value= (ulonglong) args[0]->val_int(); + if (!args[0]->null_value) + bits&=value; + return 0; +} + +/************************************************************************ +** reset result of a Item_sum with is saved in a tmp_table +*************************************************************************/ + +void Item_sum_num::reset_field() +{ + double nr= args[0]->val_real(); + uchar *res=result_field->ptr; + + if (maybe_null) + { + if (args[0]->null_value) + { + nr=0.0; + result_field->set_null(); + } + else + result_field->set_notnull(); + } + float8store(res,nr); +} + + +void Item_sum_hybrid::reset_field() +{ + switch(hybrid_type) { + case STRING_RESULT: + { + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff),result_field->charset()),*res; + + res=args[0]->val_str(&tmp); + if (args[0]->null_value) + { + result_field->set_null(); + result_field->reset(); + } + else + { + result_field->set_notnull(); + result_field->store(res->ptr(),res->length(),tmp.charset()); + } + break; + } + case INT_RESULT: + { + longlong nr=args[0]->val_int(); + + if (maybe_null) + { + if (args[0]->null_value) + { + nr=0; + result_field->set_null(); + } + else + result_field->set_notnull(); + } + result_field->store(nr, unsigned_flag); + break; + } + case REAL_RESULT: + { + double nr= args[0]->val_real(); + + if (maybe_null) + { + if (args[0]->null_value) + { + nr=0.0; + result_field->set_null(); + } + else + result_field->set_notnull(); + } + result_field->store(nr); + break; + } + case DECIMAL_RESULT: + { + my_decimal value_buff, *arg_dec= args[0]->val_decimal(&value_buff); + + if (maybe_null) + { + if (args[0]->null_value) + result_field->set_null(); + else + result_field->set_notnull(); + } + /* + We must store zero in the field as we will use the field value in + add() + */ + if (!arg_dec) // Null + arg_dec= &decimal_zero; + result_field->store_decimal(arg_dec); + break; + } + case ROW_RESULT: + default: + DBUG_ASSERT(0); + } +} + + +void Item_sum_sum::reset_field() +{ + if (hybrid_type == DECIMAL_RESULT) + { + my_decimal value, *arg_val= args[0]->val_decimal(&value); + if (!arg_val) // Null + arg_val= &decimal_zero; + result_field->store_decimal(arg_val); + } + else + { + DBUG_ASSERT(hybrid_type == REAL_RESULT); + double nr= args[0]->val_real(); // Nulls also return 0 + float8store(result_field->ptr, nr); + } + if (args[0]->null_value) + result_field->set_null(); + else + result_field->set_notnull(); +} + + +void Item_sum_count::reset_field() +{ + uchar *res=result_field->ptr; + longlong nr=0; + + if (!args[0]->maybe_null || !args[0]->is_null()) + nr=1; + int8store(res,nr); +} + + +void Item_sum_avg::reset_field() +{ + uchar *res=result_field->ptr; + if (hybrid_type == DECIMAL_RESULT) + { + longlong tmp; + my_decimal value, *arg_dec= args[0]->val_decimal(&value); + if (args[0]->null_value) + { + arg_dec= &decimal_zero; + tmp= 0; + } + else + tmp= 1; + my_decimal2binary(E_DEC_FATAL_ERROR, arg_dec, res, f_precision, f_scale); + res+= dec_bin_size; + int8store(res, tmp); + } + else + { + double nr= args[0]->val_real(); + + if (args[0]->null_value) + bzero(res,sizeof(double)+sizeof(longlong)); + else + { + longlong tmp= 1; + float8store(res,nr); + res+=sizeof(double); + int8store(res,tmp); + } + } +} + + +void Item_sum_bit::reset_field() +{ + reset(); + int8store(result_field->ptr, bits); +} + +void Item_sum_bit::update_field() +{ + uchar *res=result_field->ptr; + bits= uint8korr(res); + add(); + int8store(res, bits); +} + + +/** + calc next value and merge it with field_value. +*/ + +void Item_sum_sum::update_field() +{ + if (hybrid_type == DECIMAL_RESULT) + { + my_decimal value, *arg_val= args[0]->val_decimal(&value); + if (!args[0]->null_value) + { + if (!result_field->is_null()) + { + my_decimal field_value, + *field_val= result_field->val_decimal(&field_value); + my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs, arg_val, field_val); + result_field->store_decimal(dec_buffs); + } + else + { + result_field->store_decimal(arg_val); + result_field->set_notnull(); + } + } + } + else + { + double old_nr,nr; + uchar *res=result_field->ptr; + + float8get(old_nr,res); + nr= args[0]->val_real(); + if (!args[0]->null_value) + { + old_nr+=nr; + result_field->set_notnull(); + } + float8store(res,old_nr); + } +} + + +void Item_sum_count::update_field() +{ + longlong nr; + uchar *res=result_field->ptr; + + nr=sint8korr(res); + if (!args[0]->maybe_null || !args[0]->is_null()) + nr++; + int8store(res,nr); +} + + +void Item_sum_avg::update_field() +{ + longlong field_count; + uchar *res=result_field->ptr; + if (hybrid_type == DECIMAL_RESULT) + { + my_decimal value, *arg_val= args[0]->val_decimal(&value); + if (!args[0]->null_value) + { + binary2my_decimal(E_DEC_FATAL_ERROR, res, + dec_buffs + 1, f_precision, f_scale); + field_count= sint8korr(res + dec_bin_size); + my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs, arg_val, dec_buffs + 1); + my_decimal2binary(E_DEC_FATAL_ERROR, dec_buffs, + res, f_precision, f_scale); + res+= dec_bin_size; + field_count++; + int8store(res, field_count); + } + } + else + { + double nr; + + nr= args[0]->val_real(); + if (!args[0]->null_value) + { + double old_nr; + float8get(old_nr, res); + field_count= sint8korr(res + sizeof(double)); + old_nr+= nr; + float8store(res,old_nr); + res+= sizeof(double); + field_count++; + int8store(res, field_count); + } + } +} + + +void Item_sum_hybrid::update_field() +{ + switch (hybrid_type) { + case STRING_RESULT: + min_max_update_str_field(); + break; + case INT_RESULT: + min_max_update_int_field(); + break; + case DECIMAL_RESULT: + min_max_update_decimal_field(); + break; + default: + min_max_update_real_field(); + } +} + + +void +Item_sum_hybrid::min_max_update_str_field() +{ + String *res_str=args[0]->val_str(&value); + + if (!args[0]->null_value) + { + result_field->val_str(&tmp_value); + + if (result_field->is_null() || + (cmp_sign * sortcmp(res_str,&tmp_value,collation.collation)) < 0) + result_field->store(res_str->ptr(),res_str->length(),res_str->charset()); + result_field->set_notnull(); + } +} + + +void +Item_sum_hybrid::min_max_update_real_field() +{ + double nr,old_nr; + + old_nr=result_field->val_real(); + nr= args[0]->val_real(); + if (!args[0]->null_value) + { + if (result_field->is_null(0) || + (cmp_sign > 0 ? old_nr > nr : old_nr < nr)) + old_nr=nr; + result_field->set_notnull(); + } + else if (result_field->is_null(0)) + result_field->set_null(); + result_field->store(old_nr); +} + + +void +Item_sum_hybrid::min_max_update_int_field() +{ + longlong nr,old_nr; + + old_nr=result_field->val_int(); + nr=args[0]->val_int(); + if (!args[0]->null_value) + { + if (result_field->is_null(0)) + old_nr=nr; + else + { + bool res=(unsigned_flag ? + (ulonglong) old_nr > (ulonglong) nr : + old_nr > nr); + /* (cmp_sign > 0 && res) || (!(cmp_sign > 0) && !res) */ + if ((cmp_sign > 0) ^ (!res)) + old_nr=nr; + } + result_field->set_notnull(); + } + else if (result_field->is_null(0)) + result_field->set_null(); + result_field->store(old_nr, unsigned_flag); +} + + +/** + @todo + optimize: do not get result_field in case of args[0] is NULL +*/ +void +Item_sum_hybrid::min_max_update_decimal_field() +{ + /* TODO: optimize: do not get result_field in case of args[0] is NULL */ + my_decimal old_val, nr_val; + const my_decimal *old_nr= result_field->val_decimal(&old_val); + const my_decimal *nr= args[0]->val_decimal(&nr_val); + if (!args[0]->null_value) + { + if (result_field->is_null(0)) + old_nr=nr; + else + { + bool res= my_decimal_cmp(old_nr, nr) > 0; + /* (cmp_sign > 0 && res) || (!(cmp_sign > 0) && !res) */ + if ((cmp_sign > 0) ^ (!res)) + old_nr=nr; + } + result_field->set_notnull(); + } + else if (result_field->is_null(0)) + result_field->set_null(); + result_field->store_decimal(old_nr); +} + + +Item_avg_field::Item_avg_field(Item_result res_type, Item_sum_avg *item) +{ + name=item->name; + decimals=item->decimals; + max_length= item->max_length; + unsigned_flag= item->unsigned_flag; + field=item->result_field; + maybe_null=1; + hybrid_type= res_type; + prec_increment= item->prec_increment; + if (hybrid_type == DECIMAL_RESULT) + { + f_scale= item->f_scale; + f_precision= item->f_precision; + dec_bin_size= item->dec_bin_size; + } +} + +double Item_avg_field::val_real() +{ + // fix_fields() never calls for this Item + double nr; + longlong count; + uchar *res; + + if (hybrid_type == DECIMAL_RESULT) + return val_real_from_decimal(); + + float8get(nr,field->ptr); + res= (field->ptr+sizeof(double)); + count= sint8korr(res); + + if ((null_value= !count)) + return 0.0; + return nr/(double) count; +} + + +longlong Item_avg_field::val_int() +{ + return (longlong) rint(val_real()); +} + + +my_decimal *Item_avg_field::val_decimal(my_decimal *dec_buf) +{ + // fix_fields() never calls for this Item + if (hybrid_type == REAL_RESULT) + return val_decimal_from_real(dec_buf); + + longlong count= sint8korr(field->ptr + dec_bin_size); + if ((null_value= !count)) + return 0; + + my_decimal dec_count, dec_field; + binary2my_decimal(E_DEC_FATAL_ERROR, + field->ptr, &dec_field, f_precision, f_scale); + int2my_decimal(E_DEC_FATAL_ERROR, count, 0, &dec_count); + my_decimal_div(E_DEC_FATAL_ERROR, dec_buf, + &dec_field, &dec_count, prec_increment); + return dec_buf; +} + + +String *Item_avg_field::val_str(String *str) +{ + // fix_fields() never calls for this Item + if (hybrid_type == DECIMAL_RESULT) + return val_string_from_decimal(str); + return val_string_from_real(str); +} + + +Item_std_field::Item_std_field(Item_sum_std *item) + : Item_variance_field(item) +{ +} + + +double Item_std_field::val_real() +{ + double nr; + // fix_fields() never calls for this Item + nr= Item_variance_field::val_real(); + DBUG_ASSERT(nr >= 0.0); + return sqrt(nr); +} + + +my_decimal *Item_std_field::val_decimal(my_decimal *dec_buf) +{ + /* + We can't call val_decimal_from_real() for DECIMAL_RESULT as + Item_variance_field::val_real() would cause an infinite loop + */ + my_decimal tmp_dec, *dec; + double nr; + if (hybrid_type == REAL_RESULT) + return val_decimal_from_real(dec_buf); + + dec= Item_variance_field::val_decimal(dec_buf); + if (!dec) + return 0; + my_decimal2double(E_DEC_FATAL_ERROR, dec, &nr); + DBUG_ASSERT(nr >= 0.0); + nr= sqrt(nr); + double2my_decimal(E_DEC_FATAL_ERROR, nr, &tmp_dec); + my_decimal_round(E_DEC_FATAL_ERROR, &tmp_dec, decimals, FALSE, dec_buf); + return dec_buf; +} + + +Item_variance_field::Item_variance_field(Item_sum_variance *item) +{ + name=item->name; + decimals=item->decimals; + max_length=item->max_length; + unsigned_flag= item->unsigned_flag; + field=item->result_field; + maybe_null=1; + sample= item->sample; + prec_increment= item->prec_increment; + if ((hybrid_type= item->hybrid_type) == DECIMAL_RESULT) + { + f_scale0= item->f_scale0; + f_precision0= item->f_precision0; + dec_bin_size0= item->dec_bin_size0; + f_scale1= item->f_scale1; + f_precision1= item->f_precision1; + dec_bin_size1= item->dec_bin_size1; + } +} + + +double Item_variance_field::val_real() +{ + // fix_fields() never calls for this Item + if (hybrid_type == DECIMAL_RESULT) + return val_real_from_decimal(); + + double recurrence_s; + ulonglong count; + float8get(recurrence_s, (field->ptr + sizeof(double))); + count=sint8korr(field->ptr+sizeof(double)*2); + + if ((null_value= (count <= sample))) + return 0.0; + + return variance_fp_recurrence_result(recurrence_s, count, sample); +} + + +/**************************************************************************** +** COUNT(DISTINCT ...) +****************************************************************************/ + +int simple_str_key_cmp(void* arg, uchar* key1, uchar* key2) +{ + Field *f= (Field*) arg; + return f->cmp(key1, key2); +} + +/** + Did not make this one static - at least gcc gets confused when + I try to declare a static function as a friend. If you can figure + out the syntax to make a static function a friend, make this one + static +*/ + +int composite_key_cmp(void* arg, uchar* key1, uchar* key2) +{ + Item_sum_count_distinct* item = (Item_sum_count_distinct*)arg; + Field **field = item->table->field; + Field **field_end= field + item->table->s->fields; + uint32 *lengths=item->field_lengths; + for (; field < field_end; ++field) + { + Field* f = *field; + int len = *lengths++; + int res = f->cmp(key1, key2); + if (res) + return res; + key1 += len; + key2 += len; + } + return 0; +} + + +C_MODE_START + +static int count_distinct_walk(void *elem, element_count count, void *arg) +{ + (*((ulonglong*)arg))++; + return 0; +} + +C_MODE_END + + +void Item_sum_count_distinct::cleanup() +{ + DBUG_ENTER("Item_sum_count_distinct::cleanup"); + Item_sum_int::cleanup(); + + /* Free objects only if we own them. */ + if (!original) + { + /* + We need to delete the table and the tree in cleanup() as + they were allocated in the runtime memroot. Using the runtime + memroot reduces memory footprint for PS/SP and simplifies setup(). + */ + delete tree; + tree= 0; + is_evaluated= FALSE; + if (table) + { + free_tmp_table(table->in_use, table); + table= 0; + } + delete tmp_table_param; + tmp_table_param= 0; + } + always_null= FALSE; + DBUG_VOID_RETURN; +} + + +/** + This is used by rollup to create a separate usable copy of + the function. +*/ + +void Item_sum_count_distinct::make_unique() +{ + table=0; + original= 0; + force_copy_fields= 1; + tree= 0; + is_evaluated= FALSE; + tmp_table_param= 0; + always_null= FALSE; +} + + +Item_sum_count_distinct::~Item_sum_count_distinct() +{ + cleanup(); +} + + +bool Item_sum_count_distinct::setup(THD *thd) +{ + List list; + SELECT_LEX *select_lex= thd->lex->current_select; + + /* + Setup can be called twice for ROLLUP items. This is a bug. + Please add DBUG_ASSERT(tree == 0) here when it's fixed. + It's legal to call setup() more than once when in a subquery + */ + if (tree || table || tmp_table_param) + return FALSE; + + if (!(tmp_table_param= new TMP_TABLE_PARAM)) + return TRUE; + + /* Create a table with an unique key over all parameters */ + for (uint i=0; i < arg_count ; i++) + { + Item *item=args[i]; + if (list.push_back(item)) + return TRUE; // End of memory + if (item->const_item() && item->is_null()) + always_null= 1; + } + if (always_null) + return FALSE; + count_field_types(select_lex, tmp_table_param, list, 0); + tmp_table_param->force_copy_fields= force_copy_fields; + DBUG_ASSERT(table == 0); + /* + Make create_tmp_table() convert BIT columns to BIGINT. + This is needed because BIT fields store parts of their data in table's + null bits, and we don't have methods to compare two table records, which + is needed by Unique which is used when HEAP table is used. + */ + { + List_iterator_fast li(list); + Item *item; + while ((item= li++)) + { + if (item->type() == Item::FIELD_ITEM && + ((Item_field*)item)->field->type() == FIELD_TYPE_BIT) + item->marker=4; + } + } + + if (!(table= create_tmp_table(thd, tmp_table_param, list, (ORDER*) 0, 1, + 0, + (select_lex->options | thd->options), + HA_POS_ERROR, (char*)""))) + return TRUE; + table->file->extra(HA_EXTRA_NO_ROWS); // Don't update rows + table->no_rows=1; + + if (table->s->db_type() == heap_hton) + { + /* + No blobs, otherwise it would have been MyISAM: set up a compare + function and its arguments to use with Unique. + */ + qsort_cmp2 compare_key; + void* cmp_arg; + Field **field= table->field; + Field **field_end= field + table->s->fields; + bool all_binary= TRUE; + + for (tree_key_length= 0; field < field_end; ++field) + { + Field *f= *field; + enum enum_field_types f_type= f->type(); + tree_key_length+= f->pack_length(); + if ((f_type == MYSQL_TYPE_VARCHAR) || + (!f->binary() && (f_type == MYSQL_TYPE_STRING || + f_type == MYSQL_TYPE_VAR_STRING))) + { + all_binary= FALSE; + break; + } + } + if (all_binary) + { + cmp_arg= (void*) &tree_key_length; + compare_key= (qsort_cmp2) simple_raw_key_cmp; + } + else + { + if (table->s->fields == 1) + { + /* + If we have only one field, which is the most common use of + count(distinct), it is much faster to use a simpler key + compare method that can take advantage of not having to worry + about other fields. + */ + compare_key= (qsort_cmp2) simple_str_key_cmp; + cmp_arg= (void*) table->field[0]; + /* tree_key_length has been set already */ + } + else + { + uint32 *length; + compare_key= (qsort_cmp2) composite_key_cmp; + cmp_arg= (void*) this; + field_lengths= (uint32*) thd->alloc(table->s->fields * sizeof(uint32)); + for (tree_key_length= 0, length= field_lengths, field= table->field; + field < field_end; ++field, ++length) + { + *length= (*field)->pack_length(); + tree_key_length+= *length; + } + } + } + DBUG_ASSERT(tree == 0); + tree= new Unique(compare_key, cmp_arg, tree_key_length, + thd->variables.max_heap_table_size); + /* + The only time tree_key_length could be 0 is if someone does + count(distinct) on a char(0) field - stupid thing to do, + but this has to be handled - otherwise someone can crash + the server with a DoS attack + */ + is_evaluated= FALSE; + if (! tree) + return TRUE; + } + return FALSE; +} + + +Item *Item_sum_count_distinct::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_count_distinct(thd, this); +} + + +void Item_sum_count_distinct::clear() +{ + /* tree and table can be both null only if always_null */ + is_evaluated= FALSE; + if (tree) + { + tree->reset(); + } + else if (table) + { + table->file->extra(HA_EXTRA_NO_CACHE); + table->file->ha_delete_all_rows(); + table->file->extra(HA_EXTRA_WRITE_CACHE); + } +} + +bool Item_sum_count_distinct::add() +{ + int error; + if (always_null) + return 0; + copy_fields(tmp_table_param); + copy_funcs(tmp_table_param->items_to_copy); + + for (Field **field=table->field ; *field ; field++) + if ((*field)->is_real_null(0)) + return 0; // Don't count NULL + + is_evaluated= FALSE; + if (tree) + { + /* + The first few bytes of record (at least one) are just markers + for deleted and NULLs. We want to skip them since they will + bloat the tree without providing any valuable info. Besides, + key_length used to initialize the tree didn't include space for them. + */ + return tree->unique_add(table->record[0] + table->s->null_bytes); + } + if ((error= table->file->ha_write_row(table->record[0])) && + table->file->is_fatal_error(error, HA_CHECK_DUP)) + return TRUE; + return FALSE; +} + + +longlong Item_sum_count_distinct::val_int() +{ + int error; + DBUG_ASSERT(fixed == 1); + if (!table) // Empty query + return LL(0); + if (tree) + { + if (is_evaluated) + return count; + + if (tree->elements == 0) + return (longlong) tree->elements_in_tree(); // everything fits in memory + count= 0; + tree->walk(count_distinct_walk, (void*) &count); + is_evaluated= TRUE; + return (longlong) count; + } + + error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); + + if(error) + { + table->file->print_error(error, MYF(0)); + } + + return table->file->stats.records; +} + + +/**************************************************************************** +** Functions to handle dynamic loadable aggregates +** Original source by: Alexis Mikhailov +** Adapted for UDAs by: Andreas F. Bobak . +** Rewritten by: Monty. +****************************************************************************/ + +#ifdef HAVE_DLOPEN + +void Item_udf_sum::clear() +{ + DBUG_ENTER("Item_udf_sum::clear"); + udf.clear(); + DBUG_VOID_RETURN; +} + +bool Item_udf_sum::add() +{ + DBUG_ENTER("Item_udf_sum::add"); + udf.add(&null_value); + DBUG_RETURN(0); +} + +void Item_udf_sum::cleanup() +{ + /* + udf_handler::cleanup() nicely handles case when we have not + original item but one created by copy_or_same() method. + */ + udf.cleanup(); + Item_sum::cleanup(); +} + + +void Item_udf_sum::print(String *str, enum_query_type query_type) +{ + str->append(func_name()); + str->append('('); + for (uint i=0 ; i < arg_count ; i++) + { + if (i) + str->append(','); + args[i]->print(str, query_type); + } + str->append(')'); +} + + +Item *Item_sum_udf_float::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_udf_float(thd, this); +} + +double Item_sum_udf_float::val_real() +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_sum_udf_float::val"); + DBUG_PRINT("info",("result_type: %d arg_count: %d", + args[0]->result_type(), arg_count)); + DBUG_RETURN(udf.val(&null_value)); +} + + +String *Item_sum_udf_float::val_str(String *str) +{ + return val_string_from_real(str); +} + + +my_decimal *Item_sum_udf_float::val_decimal(my_decimal *dec) +{ + return val_decimal_from_real(dec); +} + + +String *Item_sum_udf_decimal::val_str(String *str) +{ + return val_string_from_decimal(str); +} + + +double Item_sum_udf_decimal::val_real() +{ + return val_real_from_decimal(); +} + + +longlong Item_sum_udf_decimal::val_int() +{ + return val_int_from_decimal(); +} + + +my_decimal *Item_sum_udf_decimal::val_decimal(my_decimal *dec_buf) +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_func_udf_decimal::val_decimal"); + DBUG_PRINT("info",("result_type: %d arg_count: %d", + args[0]->result_type(), arg_count)); + + DBUG_RETURN(udf.val_decimal(&null_value, dec_buf)); +} + + +Item *Item_sum_udf_decimal::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_udf_decimal(thd, this); +} + + +Item *Item_sum_udf_int::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_udf_int(thd, this); +} + +longlong Item_sum_udf_int::val_int() +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_sum_udf_int::val_int"); + DBUG_PRINT("info",("result_type: %d arg_count: %d", + args[0]->result_type(), arg_count)); + DBUG_RETURN(udf.val_int(&null_value)); +} + + +String *Item_sum_udf_int::val_str(String *str) +{ + return val_string_from_int(str); +} + +my_decimal *Item_sum_udf_int::val_decimal(my_decimal *dec) +{ + return val_decimal_from_int(dec); +} + + +/** Default max_length is max argument length. */ + +void Item_sum_udf_str::fix_length_and_dec() +{ + DBUG_ENTER("Item_sum_udf_str::fix_length_and_dec"); + max_length=0; + for (uint i = 0; i < arg_count; i++) + set_if_bigger(max_length,args[i]->max_length); + DBUG_VOID_RETURN; +} + + +Item *Item_sum_udf_str::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_sum_udf_str(thd, this); +} + + +my_decimal *Item_sum_udf_str::val_decimal(my_decimal *dec) +{ + return val_decimal_from_string(dec); +} + +String *Item_sum_udf_str::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + DBUG_ENTER("Item_sum_udf_str::str"); + String *res=udf.val_str(str,&str_value); + null_value = !res; + DBUG_RETURN(res); +} + +#endif /* HAVE_DLOPEN */ + + +/***************************************************************************** + GROUP_CONCAT function + + SQL SYNTAX: + GROUP_CONCAT([DISTINCT] expr,... [ORDER BY col [ASC|DESC],...] + [SEPARATOR str_const]) + + concat of values from "group by" operation + + BUGS + Blobs doesn't work with DISTINCT or ORDER BY +*****************************************************************************/ + + + +/** + Compares the values for fields in expr list of GROUP_CONCAT. + @note + + GROUP_CONCAT([DISTINCT] expr [,expr ...] + [ORDER BY {unsigned_integer | col_name | expr} + [ASC | DESC] [,col_name ...]] + [SEPARATOR str_val]) + + @return + @retval -1 : key1 < key2 + @retval 0 : key1 = key2 + @retval 1 : key1 > key2 +*/ + +int group_concat_key_cmp_with_distinct(void* arg, const void* key1, + const void* key2) +{ + Item_func_group_concat *item_func= (Item_func_group_concat*)arg; + TABLE *table= item_func->table; + + for (uint i= 0; i < item_func->arg_count_field; i++) + { + Item *item= item_func->args[i]; + /* + If field_item is a const item then either get_tp_table_field returns 0 + or it is an item over a const table. + */ + if (item->const_item()) + continue; + /* + We have to use get_tmp_table_field() instead of + real_item()->get_tmp_table_field() because we want the field in + the temporary table, not the original field + */ + Field *field= item->get_tmp_table_field(); + int res; + uint offset= field->offset(field->table->record[0])-table->s->null_bytes; + if((res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset))) + return res; + } + return 0; +} + + +/** + function of sort for syntax: GROUP_CONCAT(expr,... ORDER BY col,... ) +*/ + +int group_concat_key_cmp_with_order(void* arg, const void* key1, + const void* key2) +{ + Item_func_group_concat* grp_item= (Item_func_group_concat*) arg; + ORDER **order_item, **end; + TABLE *table= grp_item->table; + + for (order_item= grp_item->order, end=order_item+ grp_item->arg_count_order; + order_item < end; + order_item++) + { + Item *item= *(*order_item)->item; + /* + We have to use get_tmp_table_field() instead of + real_item()->get_tmp_table_field() because we want the field in + the temporary table, not the original field + */ + Field *field= item->get_tmp_table_field(); + /* + If item is a const item then either get_tp_table_field returns 0 + or it is an item over a const table. + */ + if (field && !item->const_item()) + { + int res; + uint offset= (field->offset(field->table->record[0]) - + table->s->null_bytes); + if ((res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset))) + return (*order_item)->asc ? res : -res; + } + } + /* + We can't return 0 because in that case the tree class would remove this + item as double value. This would cause problems for case-changes and + if the returned values are not the same we do the sort on. + */ + return 1; +} + + +/** + Append data from current leaf to item->result. +*/ + +int dump_leaf_key(uchar* key, element_count count __attribute__((unused)), + Item_func_group_concat *item) +{ + TABLE *table= item->table; + String tmp((char *)table->record[1], table->s->reclength, + default_charset_info); + String tmp2; + String *result= &item->result; + Item **arg= item->args, **arg_end= item->args + item->arg_count_field; + uint old_length= result->length(); + + if (item->no_appended) + item->no_appended= FALSE; + else + result->append(*item->separator); + + tmp.length(0); + + for (; arg < arg_end; arg++) + { + String *res; + if (! (*arg)->const_item()) + { + /* + We have to use get_tmp_table_field() instead of + real_item()->get_tmp_table_field() because we want the field in + the temporary table, not the original field + We also can't use table->field array to access the fields + because it contains both order and arg list fields. + */ + Field *field= (*arg)->get_tmp_table_field(); + uint offset= (field->offset(field->table->record[0]) - + table->s->null_bytes); + DBUG_ASSERT(offset < table->s->reclength); + res= field->val_str(&tmp, key + offset); + } + else + res= (*arg)->val_str(&tmp); + if (res) + result->append(*res); + } + + /* stop if length of result more than max_length */ + if (result->length() > item->max_length) + { + int well_formed_error; + CHARSET_INFO *cs= item->collation.collation; + const char *ptr= result->ptr(); + uint add_length; + /* + It's ok to use item->result.length() as the fourth argument + as this is never used to limit the length of the data. + Cut is done with the third argument. + */ + add_length= cs->cset->well_formed_len(cs, + ptr + old_length, + ptr + item->max_length, + result->length(), + &well_formed_error); + result->length(old_length + add_length); + item->count_cut_values++; + item->warning_for_row= TRUE; + return 1; + } + return 0; +} + + +/** + Constructor of Item_func_group_concat. + + @param distinct_arg distinct + @param select_list list of expression for show values + @param order_list list of sort columns + @param separator_arg string value of separator. +*/ + +Item_func_group_concat:: +Item_func_group_concat(Name_resolution_context *context_arg, + bool distinct_arg, List *select_list, + SQL_LIST *order_list, String *separator_arg) + :tmp_table_param(0), warning(0), + separator(separator_arg), tree(0), unique_filter(NULL), table(0), + order(0), context(context_arg), + arg_count_order(order_list ? order_list->elements : 0), + arg_count_field(select_list->elements), + count_cut_values(0), + distinct(distinct_arg), + warning_for_row(FALSE), + force_copy_fields(0), original(0) +{ + Item *item_select; + Item **arg_ptr; + + quick_group= FALSE; + arg_count= arg_count_field + arg_count_order; + + /* + We need to allocate: + args - arg_count_field+arg_count_order + (for possible order items in temporare tables) + order - arg_count_order + */ + if (!(args= (Item**) sql_alloc(sizeof(Item*) * arg_count + + sizeof(ORDER*)*arg_count_order))) + return; + + if (!(orig_args= (Item **) sql_alloc(sizeof(Item *) * arg_count))) + { + args= NULL; + return; + } + + order= (ORDER**)(args + arg_count); + + /* fill args items of show and sort */ + List_iterator_fast li(*select_list); + + for (arg_ptr=args ; (item_select= li++) ; arg_ptr++) + *arg_ptr= item_select; + + if (arg_count_order) + { + ORDER **order_ptr= order; + for (ORDER *order_item= (ORDER*) order_list->first; + order_item != NULL; + order_item= order_item->next) + { + (*order_ptr++)= order_item; + *arg_ptr= *order_item->item; + order_item->item= arg_ptr++; + } + } +} + + +Item_func_group_concat::Item_func_group_concat(THD *thd, + Item_func_group_concat *item) + :Item_sum(thd, item), + tmp_table_param(item->tmp_table_param), + warning(item->warning), + separator(item->separator), + tree(item->tree), + unique_filter(item->unique_filter), + table(item->table), + order(item->order), + context(item->context), + arg_count_order(item->arg_count_order), + arg_count_field(item->arg_count_field), + count_cut_values(item->count_cut_values), + distinct(item->distinct), + warning_for_row(item->warning_for_row), + always_null(item->always_null), + force_copy_fields(item->force_copy_fields), + original(item) +{ + quick_group= item->quick_group; + result.set_charset(collation.collation); +} + +//@InfiniDB. Moved this function to .cc file to access select_lex. +enum_field_types Item_func_group_concat::field_type() const +{ + if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB && + !(context && context->select_lex && context->select_lex->join && + context->select_lex->join->thd && + context->select_lex->join->thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE)) + return MYSQL_TYPE_BLOB; + else + return MYSQL_TYPE_VARCHAR; +} + +void Item_func_group_concat::cleanup() +{ + DBUG_ENTER("Item_func_group_concat::cleanup"); + Item_sum::cleanup(); + + /* Adjust warning message to include total number of cut values */ + if (warning) + { + char warn_buff[MYSQL_ERRMSG_SIZE]; + sprintf(warn_buff, ER(ER_CUT_VALUE_GROUP_CONCAT), count_cut_values); + warning->set_msg(current_thd, warn_buff); + warning= 0; + } + + /* + Free table and tree if they belong to this item (if item have not pointer + to original item from which was made copy => it own its objects ) + */ + if (!original) + { + delete tmp_table_param; + tmp_table_param= 0; + if (table) + { + THD *thd= table->in_use; + free_tmp_table(thd, table); + table= 0; + if (tree) + { + delete_tree(tree); + tree= 0; + } + if (unique_filter) + { + delete unique_filter; + unique_filter= NULL; + } + if (warning) + { + char warn_buff[MYSQL_ERRMSG_SIZE]; + sprintf(warn_buff, ER(ER_CUT_VALUE_GROUP_CONCAT), count_cut_values); + warning->set_msg(thd, warn_buff); + warning= 0; + } + } + DBUG_ASSERT(tree == 0 && warning == 0); + } + DBUG_VOID_RETURN; +} + + +Item *Item_func_group_concat::copy_or_same(THD* thd) +{ + return new (thd->mem_root) Item_func_group_concat(thd, this); +} + + +void Item_func_group_concat::clear() +{ + result.length(0); + result.copy(); + null_value= TRUE; + warning_for_row= FALSE; + no_appended= TRUE; + if (tree) + reset_tree(tree); + if (unique_filter) + unique_filter->reset(); + /* No need to reset the table as we never call write_row */ +} + + +bool Item_func_group_concat::add() +{ + if (always_null) + return 0; + copy_fields(tmp_table_param); + copy_funcs(tmp_table_param->items_to_copy); + + for (uint i= 0; i < arg_count_field; i++) + { + Item *show_item= args[i]; + if (!show_item->const_item()) + { + Field *f= show_item->get_tmp_table_field(); + if (f->is_null_in_record((const uchar*) table->record[0])) + return 0; // Skip row if it contains null + } + } + + null_value= FALSE; + bool row_eligible= TRUE; + + if (distinct) + { + /* Filter out duplicate rows. */ + uint count= unique_filter->elements_in_tree(); + unique_filter->unique_add(table->record[0] + table->s->null_bytes); + if (count == unique_filter->elements_in_tree()) + row_eligible= FALSE; + } + + TREE_ELEMENT *el= 0; // Only for safety + if (row_eligible && tree) + { + el= tree_insert(tree, table->record[0] + table->s->null_bytes, 0, + tree->custom_arg); + /* check if there was enough memory to insert the row */ + if (!el) + return 1; + } + /* + If the row is not a duplicate (el->count == 1) + we can dump the row here in case of GROUP_CONCAT(DISTINCT...) + instead of doing tree traverse later. + */ + if (row_eligible && !warning_for_row && + (!tree || (el->count == 1 && distinct && !arg_count_order))) + dump_leaf_key(table->record[0] + table->s->null_bytes, 1, this); + + return 0; +} + + +bool +Item_func_group_concat::fix_fields(THD *thd, Item **ref) +{ + uint i; /* for loop variable */ + DBUG_ASSERT(fixed == 0); + + if (init_sum_func_check(thd)) + return TRUE; + + maybe_null= 1; + + /* + Fix fields for select list and ORDER clause + */ + + for (i=0 ; i < arg_count ; i++) + { + if ((!args[i]->fixed && + args[i]->fix_fields(thd, args + i)) || + args[i]->check_cols(1)) + return TRUE; + } + + if (agg_item_charsets(collation, func_name(), + args, + /* skip charset aggregation for order columns */ + arg_count - arg_count_order, + MY_COLL_ALLOW_CONV, 1)) + return 1; + + result.set_charset(collation.collation); + result_field= 0; + null_value= 1; + max_length= thd->variables.group_concat_max_len; + + uint32 offset; + if (separator->needs_conversion(separator->length(), separator->charset(), + collation.collation, &offset)) + { + uint32 buflen= collation.collation->mbmaxlen * separator->length(); + uint errors, conv_length; + char *buf; + String *new_separator; + + if (!(buf= (char*) thd->stmt_arena->alloc(buflen)) || + !(new_separator= new(thd->stmt_arena->mem_root) + String(buf, buflen, collation.collation))) + return TRUE; + + conv_length= copy_and_convert(buf, buflen, collation.collation, + separator->ptr(), separator->length(), + separator->charset(), &errors); + new_separator->length(conv_length); + separator= new_separator; + } + + if (check_sum_func(thd, ref)) + return TRUE; + + memcpy (orig_args, args, sizeof (Item *) * arg_count); + fixed= 1; + return FALSE; +} + + +bool Item_func_group_concat::setup(THD *thd) +{ + List list; + SELECT_LEX *select_lex= thd->lex->current_select; + DBUG_ENTER("Item_func_group_concat::setup"); + + /* + Currently setup() can be called twice. Please add + assertion here when this is fixed. + */ + if (table || tree) + DBUG_RETURN(FALSE); + + if (!(tmp_table_param= new TMP_TABLE_PARAM)) + DBUG_RETURN(TRUE); + + /* We'll convert all blobs to varchar fields in the temporary table */ + tmp_table_param->convert_blob_length= max_length * + collation.collation->mbmaxlen; + /* Push all not constant fields to the list and create a temp table */ + always_null= 0; + for (uint i= 0; i < arg_count_field; i++) + { + Item *item= args[i]; + if (list.push_back(item)) + DBUG_RETURN(TRUE); + if (item->const_item()) + { + if (item->is_null()) + { + always_null= 1; + DBUG_RETURN(FALSE); + } + } + } + + List all_fields(list); + /* + Try to find every ORDER expression in the list of GROUP_CONCAT + arguments. If an expression is not found, prepend it to + "all_fields". The resulting field list is used as input to create + tmp table columns. + */ + if (arg_count_order && + setup_order(thd, args, context->table_list, list, all_fields, *order)) + DBUG_RETURN(TRUE); + + count_field_types(select_lex, tmp_table_param, all_fields, 0); + tmp_table_param->force_copy_fields= force_copy_fields; + DBUG_ASSERT(table == 0); + if (arg_count_order > 0 || distinct) + { + /* + Currently we have to force conversion of BLOB values to VARCHAR's + if we are to store them in TREE objects used for ORDER BY and + DISTINCT. This leads to truncation if the BLOB's size exceeds + Field_varstring::MAX_SIZE. + */ + set_if_smaller(tmp_table_param->convert_blob_length, + Field_varstring::MAX_SIZE); + + /* + Force the create_tmp_table() to convert BIT columns to INT + as we cannot compare two table records containg BIT fields + stored in the the tree used for distinct/order by. + Moreover we don't even save in the tree record null bits + where BIT fields store parts of their data. + */ + List_iterator_fast li(all_fields); + Item *item; + while ((item= li++)) + { + if (item->type() == Item::FIELD_ITEM && + ((Item_field*) item)->field->type() == FIELD_TYPE_BIT) + item->marker= 4; + } + } + + /* + We have to create a temporary table to get descriptions of fields + (types, sizes and so on). + + Note that in the table, we first have the ORDER BY fields, then the + field list. + */ + if (!(table= create_tmp_table(thd, tmp_table_param, all_fields, + (ORDER*) 0, 0, TRUE, + (select_lex->options | thd->options), + HA_POS_ERROR, (char*) ""))) + DBUG_RETURN(TRUE); + table->file->extra(HA_EXTRA_NO_ROWS); + table->no_rows= 1; + + /* + Need sorting or uniqueness: init tree and choose a function to sort. + Don't reserve space for NULLs: if any of gconcat arguments is NULL, + the row is not added to the result. + */ + uint tree_key_length= table->s->reclength - table->s->null_bytes; + + if (arg_count_order) + { + tree= &tree_base; + /* + Create a tree for sorting. The tree is used to sort (according to the + syntax of this function). If there is no ORDER BY clause, we don't + create this tree. + */ + init_tree(tree, (uint) min(thd->variables.max_heap_table_size, + thd->variables.sortbuff_size/16), 0, + tree_key_length, + group_concat_key_cmp_with_order , 0, NULL, (void*) this); + } + + if (distinct) + unique_filter= new Unique(group_concat_key_cmp_with_distinct, + (void*)this, + tree_key_length, + thd->variables.max_heap_table_size); + + DBUG_RETURN(FALSE); +} + + +/* This is used by rollup to create a separate usable copy of the function */ + +void Item_func_group_concat::make_unique() +{ + tmp_table_param= 0; + table=0; + original= 0; + force_copy_fields= 1; + tree= 0; +} + + +String* Item_func_group_concat::val_str(String* str) +{ + DBUG_ASSERT(fixed == 1); + if (null_value) + return 0; + if (no_appended && tree) + /* Tree is used for sorting as in ORDER BY */ + tree_walk(tree, (tree_walk_action)&dump_leaf_key, (void*)this, + left_root_right); + if (count_cut_values && !warning) + { + /* + ER_CUT_VALUE_GROUP_CONCAT needs an argument, but this gets set in + Item_func_group_concat::cleanup(). + */ + DBUG_ASSERT(table); + warning= push_warning(table->in_use, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_CUT_VALUE_GROUP_CONCAT, + ER(ER_CUT_VALUE_GROUP_CONCAT)); + } + return &result; +} + + +void Item_func_group_concat::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("group_concat(")); + if (distinct) + str->append(STRING_WITH_LEN("distinct ")); + for (uint i= 0; i < arg_count_field; i++) + { + if (i) + str->append(','); + args[i]->print(str, query_type); + } + if (arg_count_order) + { + str->append(STRING_WITH_LEN(" order by ")); + for (uint i= 0 ; i < arg_count_order ; i++) + { + if (i) + str->append(','); + (*order[i]->item)->print(str, query_type); + if (order[i]->asc) + str->append(STRING_WITH_LEN(" ASC")); + else + str->append(STRING_WITH_LEN(" DESC")); + } + } + str->append(STRING_WITH_LEN(" separator \'")); + str->append(*separator); + str->append(STRING_WITH_LEN("\')")); +} + + +Item_func_group_concat::~Item_func_group_concat() +{ + if (!original && unique_filter) + delete unique_filter; +} diff --git a/dbcon/mysql/item_sum.h b/dbcon/mysql/item_sum.h new file mode 100644 index 00000000..7453a7e3 --- /dev/null +++ b/dbcon/mysql/item_sum.h @@ -0,0 +1,1283 @@ +/* Copyright (C) 2000-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* classes for sum functions */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +#include +/* + Class Item_sum is the base class used for special expressions that SQL calls + 'set functions'. These expressions are formed with the help of aggregate + functions such as SUM, MAX, GROUP_CONCAT etc. + + GENERAL NOTES + + A set function cannot be used in certain positions where expressions are + accepted. There are some quite explicable restrictions for the usage of + set functions. + + In the query: + SELECT AVG(b) FROM t1 WHERE SUM(b) > 20 GROUP by a + the usage of the set function AVG(b) is legal, while the usage of SUM(b) + is illegal. A WHERE condition must contain expressions that can be + evaluated for each row of the table. Yet the expression SUM(b) can be + evaluated only for each group of rows with the same value of column a. + In the query: + SELECT AVG(b) FROM t1 WHERE c > 30 GROUP BY a HAVING SUM(b) > 20 + both set function expressions AVG(b) and SUM(b) are legal. + + We can say that in a query without nested selects an occurrence of a + set function in an expression of the SELECT list or/and in the HAVING + clause is legal, while in the WHERE clause it's illegal. + + The general rule to detect whether a set function is legal in a query with + nested subqueries is much more complicated. + + Consider the the following query: + SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a > ALL (SELECT t2.c FROM t2 WHERE SUM(t1.b) < t2.c). + The set function SUM(b) is used here in the WHERE clause of the subquery. + Nevertheless it is legal since it is under the HAVING clause of the query + to which this function relates. The expression SUM(t1.b) is evaluated + for each group defined in the main query, not for groups of the subquery. + + The problem of finding the query where to aggregate a particular + set function is not so simple as it seems to be. + + In the query: + SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a > ALL(SELECT t2.c FROM t2 GROUP BY t2.c + HAVING SUM(t1.a) < t2.c) + the set function can be evaluated for both outer and inner selects. + If we evaluate SUM(t1.a) for the outer query then we get the value of t1.a + multiplied by the cardinality of a group in table t1. In this case + in each correlated subquery SUM(t1.a) is used as a constant. But we also + can evaluate SUM(t1.a) for the inner query. In this case t1.a will be a + constant for each correlated subquery and summation is performed + for each group of table t2. + (Here it makes sense to remind that the query + SELECT c FROM t GROUP BY a HAVING SUM(1) < a + is quite legal in our SQL). + + So depending on what query we assign the set function to we + can get different result sets. + + The general rule to detect the query where a set function is to be + evaluated can be formulated as follows. + Consider a set function S(E) where E is an expression with occurrences + of column references C1, ..., CN. Resolve these column references against + subqueries that contain the set function S(E). Let Q be the innermost + subquery of those subqueries. (It should be noted here that S(E) + in no way can be evaluated in the subquery embedding the subquery Q, + otherwise S(E) would refer to at least one unbound column reference) + If S(E) is used in a construct of Q where set functions are allowed then + we evaluate S(E) in Q. + Otherwise we look for a innermost subquery containing S(E) of those where + usage of S(E) is allowed. + + Let's demonstrate how this rule is applied to the following queries. + + 1. SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b + HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c + HAVING SUM(t1.a+t2.b) < t3.c)) + For this query the set function SUM(t1.a+t2.b) depends on t1.a and t2.b + with t1.a defined in the outermost query, and t2.b defined for its + subquery. The set function is in the HAVING clause of the subquery and can + be evaluated in this subquery. + + 2. SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a > ALL(SELECT t2.b FROM t2 + WHERE t2.b > ALL (SELECT t3.c FROM t3 GROUP BY t3.c + HAVING SUM(t1.a+t2.b) < t3.c)) + Here the set function SUM(t1.a+t2.b)is in the WHERE clause of the second + subquery - the most upper subquery where t1.a and t2.b are defined. + If we evaluate the function in this subquery we violate the context rules. + So we evaluate the function in the third subquery (over table t3) where it + is used under the HAVING clause. + + 3. SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a > ALL(SELECT t2.b FROM t2 + WHERE t2.b > ALL (SELECT t3.c FROM t3 + WHERE SUM(t1.a+t2.b) < t3.c)) + In this query evaluation of SUM(t1.a+t2.b) is not legal neither in the second + nor in the third subqueries. So this query is invalid. + + Mostly set functions cannot be nested. In the query + SELECT t1.a from t1 GROUP BY t1.a HAVING AVG(SUM(t1.b)) > 20 + the expression SUM(b) is not acceptable, though it is under a HAVING clause. + Yet it is acceptable in the query: + SELECT t.1 FROM t1 GROUP BY t1.a HAVING SUM(t1.b) > 20. + + An argument of a set function does not have to be a reference to a table + column as we saw it in examples above. This can be a more complex expression + SELECT t1.a FROM t1 GROUP BY t1.a HAVING SUM(t1.b+1) > 20. + The expression SUM(t1.b+1) has a very clear semantics in this context: + we sum up the values of t1.b+1 where t1.b varies for all values within a + group of rows that contain the same t1.a value. + + A set function for an outer query yields a constant within a subquery. So + the semantics of the query + SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c + HAVING AVG(t2.c+SUM(t1.b)) > 20) + is still clear. For a group of the rows with the same t1.a values we + calculate the value of SUM(t1.b). This value 's' is substituted in the + the subquery: + SELECT t2.c FROM t2 GROUP BY t2.c HAVING AVG(t2.c+s) + than returns some result set. + + By the same reason the following query with a subquery + SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c + HAVING AVG(SUM(t1.b)) > 20) + is also acceptable. + + IMPLEMENTATION NOTES + + Three methods were added to the class to check the constraints specified + in the previous section. These methods utilize several new members. + + The field 'nest_level' contains the number of the level for the subquery + containing the set function. The main SELECT is of level 0, its subqueries + are of levels 1, the subqueries of the latter are of level 2 and so on. + + The field 'aggr_level' is to contain the nest level of the subquery + where the set function is aggregated. + + The field 'max_arg_level' is for the maximun of the nest levels of the + unbound column references occurred in the set function. A column reference + is unbound within a set function if it is not bound by any subquery + used as a subexpression in this function. A column reference is bound by + a subquery if it is a reference to the column by which the aggregation + of some set function that is used in the subquery is calculated. + For the set function used in the query + SELECT t1.a FROM t1 GROUP BY t1.a + HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b + HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c + HAVING SUM(t1.a+t2.b) < t3.c)) + the value of max_arg_level is equal to 1 since t1.a is bound in the main + query, and t2.b is bound by the first subquery whose nest level is 1. + Obviously a set function cannot be aggregated in the subquery whose + nest level is less than max_arg_level. (Yet it can be aggregated in the + subqueries whose nest level is greater than max_arg_level.) + In the query + SELECT t.a FROM t1 HAVING AVG(t1.a+(SELECT MIN(t2.c) FROM t2)) + the value of the max_arg_level for the AVG set function is 0 since + the reference t2.c is bound in the subquery. + + The field 'max_sum_func_level' is to contain the maximum of the + nest levels of the set functions that are used as subexpressions of + the arguments of the given set function, but not aggregated in any + subquery within this set function. A nested set function s1 can be + used within set function s0 only if s1.max_sum_func_level < + s0.max_sum_func_level. Set function s1 is considered as nested + for set function s0 if s1 is not calculated in any subquery + within s0. + + A set function that is used as a subexpression in an argument of another + set function refers to the latter via the field 'in_sum_func'. + + The condition imposed on the usage of set functions are checked when + we traverse query subexpressions with the help of the recursive method + fix_fields. When we apply this method to an object of the class + Item_sum, first, on the descent, we call the method init_sum_func_check + that initialize members used at checking. Then, on the ascent, we + call the method check_sum_func that validates the set function usage + and reports an error if it is illegal. + The method register_sum_func serves to link the items for the set functions + that are aggregated in the embedding (sub)queries. Circular chains of such + functions are attached to the corresponding st_select_lex structures + through the field inner_sum_func_list. + + Exploiting the fact that the members mentioned above are used in one + recursive function we could have allocated them on the thread stack. + Yet we don't do it now. + + We assume that the nesting level of subquries does not exceed 127. + TODO: to catch queries where the limit is exceeded to make the + code clean here. + +*/ + +class st_select_lex; + +class Item_sum :public Item_result_field +{ +public: + enum Sumfunctype + { COUNT_FUNC, COUNT_DISTINCT_FUNC, SUM_FUNC, SUM_DISTINCT_FUNC, AVG_FUNC, + AVG_DISTINCT_FUNC, MIN_FUNC, MAX_FUNC, STD_FUNC, + VARIANCE_FUNC, SUM_BIT_FUNC, UDF_SUM_FUNC, GROUP_CONCAT_FUNC + }; + + Item **ref_by; /* pointer to a ref to the object used to register it */ + Item_sum *next; /* next in the circular chain of registered objects */ + Item_sum *in_sum_func; /* embedding set function if any */ + st_select_lex * aggr_sel; /* select where the function is aggregated */ + int8 nest_level; /* number of the nesting level of the set function */ + int8 aggr_level; /* nesting level of the aggregating subquery */ + int8 max_arg_level; /* max level of unbound column references */ + int8 max_sum_func_level;/* max level of aggregation for embedded functions */ + bool quick_group; /* If incremental update of fields */ + /* + This list is used by the check for mixing non aggregated fields and + sum functions in the ONLY_FULL_GROUP_BY_MODE. We save all outer fields + directly or indirectly used under this function it as it's unclear + at the moment of fixing outer field whether it's aggregated or not. + */ + List outer_fields; + + uint arg_count; + Item **args, *tmp_args[2]; + THD* thd() { return IDB_thd; } +protected: + /* + Copy of the arguments list to hold the original set of arguments. + Used in EXPLAIN EXTENDED instead of the current argument list because + the current argument list can be altered by usage of temporary tables. + */ + Item **orig_args, *tmp_orig_args[2]; + table_map used_tables_cache; + bool forced_const; + THD* IDB_thd; // @InfiniDB. save current thd pointer here for IDB use. + +public: + + void mark_as_sum_func(); + Item_sum() :quick_group(1), arg_count(0), forced_const(FALSE), IDB_thd(0) + { + mark_as_sum_func(); + } + Item_sum(Item *a) :quick_group(1), arg_count(1), args(tmp_args), + orig_args(tmp_orig_args), forced_const(FALSE), IDB_thd(0) + { + args[0]=a; + mark_as_sum_func(); + } + Item_sum( Item *a, Item *b ) :quick_group(1), arg_count(2), args(tmp_args), + orig_args(tmp_orig_args), forced_const(FALSE), IDB_thd(0) + { + args[0]=a; args[1]=b; + mark_as_sum_func(); + } + Item_sum(List &list); + //Copy constructor, need to perform subselects with temporary tables + Item_sum(THD *thd, Item_sum *item); + enum Type type() const { return SUM_FUNC_ITEM; } + virtual enum Sumfunctype sum_func () const=0; + + /* + This method is similar to add(), but it is called when the current + aggregation group changes. Thus it performs a combination of + clear() and add(). + */ + inline bool reset() { clear(); return add(); }; + + /* + Prepare this item for evaluation of an aggregate value. This is + called by reset() when a group changes, or, for correlated + subqueries, between subquery executions. E.g. for COUNT(), this + method should set count= 0; + */ + virtual void clear()= 0; + + /* + This method is called for the next row in the same group. Its + purpose is to aggregate the new value to the previous values in + the group (i.e. since clear() was called last time). For example, + for COUNT(), do count++. + */ + virtual bool add()=0; + + /* + Called when new group is started and results are being saved in + a temporary table. Similar to reset(), but must also store value in + result_field. Like reset() it is supposed to reset start value to + default. + This set of methods (reult_field(), reset_field, update_field()) of + Item_sum is used only if quick_group is not null. Otherwise + copy_or_same() is used to obtain a copy of this item. + */ + virtual void reset_field()=0; + /* + Called for each new value in the group, when temporary table is in use. + Similar to add(), but uses temporary table field to obtain current value, + Updated value is then saved in the field. + */ + virtual void update_field()=0; + virtual bool keep_field_type(void) const { return 0; } + virtual void fix_length_and_dec() { maybe_null=1; null_value=1; } + /* + This method is used for debug purposes to print the name of an + item to the debug log. The second use of this method is as + a helper function of print(), where it is applicable. + To suit both goals it should return a meaningful, + distinguishable and sintactically correct string. This method + should not be used for runtime type identification, use enum + {Sum}Functype and Item_func::functype()/Item_sum::sum_func() + instead. + + NOTE: for Items inherited from Item_sum, func_name() return part of + function name till first argument (including '(') to make difference in + names for functions with 'distinct' clause and without 'distinct' and + also to make printing of items inherited from Item_sum uniform. + */ + virtual const char *func_name() const= 0; + virtual Item *result_item(Field *field) + { return new Item_field(field); } + table_map used_tables() const { return used_tables_cache; } + void update_used_tables (); + void cleanup() + { + Item::cleanup(); + forced_const= FALSE; + } + bool is_null() { return null_value; } + void make_const () + { + used_tables_cache= 0; + forced_const= TRUE; + } + virtual bool const_item() const { return forced_const; } + void make_field(Send_field *field); + virtual void print(String *str, enum_query_type query_type); + void fix_num_length_and_dec(); + + /* + This function is called by the execution engine to assign 'NO ROWS + FOUND' value to an aggregate item, when the underlying result set + has no rows. Such value, in a general case, may be different from + the default value of the item after 'clear()': e.g. a numeric item + may be initialized to 0 by clear() and to NULL by + no_rows_in_result(). + */ + void no_rows_in_result() { clear(); } + + virtual bool setup(THD *thd) {return 0;} + virtual void make_unique() {} + Item *get_tmp_table_item(THD *thd); + virtual Field *create_tmp_field(bool group, TABLE *table, + uint convert_blob_length); + bool walk(Item_processor processor, bool walk_subquery, uchar *argument); + bool init_sum_func_check(THD *thd); + bool check_sum_func(THD *thd, Item **ref); + bool register_sum_func(THD *thd, Item **ref); + st_select_lex *depended_from() + { return (nest_level == aggr_level ? 0 : aggr_sel); } + + Item *get_arg(int i) { return args[i]; } + Item *set_arg(int i, THD *thd, Item *new_val); + uint get_arg_count() { return arg_count; } +}; + + +class Item_sum_num :public Item_sum +{ +protected: + /* + val_xxx() functions may be called several times during the execution of a + query. Derived classes that require extensive calculation in val_xxx() + maintain cache of aggregate value. This variable governs the validity of + that cache. + */ + bool is_evaluated; +public: + Item_sum_num() :Item_sum(),is_evaluated(FALSE) {} + Item_sum_num(Item *item_par) + :Item_sum(item_par), is_evaluated(FALSE) {} + Item_sum_num(Item *a, Item* b) :Item_sum(a,b),is_evaluated(FALSE) {} + Item_sum_num(List &list) + :Item_sum(list), is_evaluated(FALSE) {} + Item_sum_num(THD *thd, Item_sum_num *item) + :Item_sum(thd, item),is_evaluated(item->is_evaluated) {} + bool fix_fields(THD *, Item **); + longlong val_int() + { + DBUG_ASSERT(fixed == 1); + return (longlong) rint(val_real()); /* Real as default */ + } + String *val_str(String*str); + my_decimal *val_decimal(my_decimal *); + void reset_field(); +}; + + +class Item_sum_int :public Item_sum_num +{ +public: + Item_sum_int(Item *item_par) :Item_sum_num(item_par) {} + Item_sum_int(List &list) :Item_sum_num(list) {} + Item_sum_int(THD *thd, Item_sum_int *item) :Item_sum_num(thd, item) {} + double val_real() { DBUG_ASSERT(fixed == 1); return (double) val_int(); } + String *val_str(String*str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return INT_RESULT; } + void fix_length_and_dec() + { decimals=0; max_length=21; maybe_null=null_value=0; } +}; + + +class Item_sum_sum :public Item_sum_num +{ +protected: + Item_result hybrid_type; + double sum; + my_decimal dec_buffs[2]; + uint curr_dec_buff; + void fix_length_and_dec(); + +public: + Item_sum_sum(Item *item_par) :Item_sum_num(item_par) {} + Item_sum_sum(THD *thd, Item_sum_sum *item); + enum Sumfunctype sum_func () const {return SUM_FUNC;} + void clear(); + bool add(); + double val_real(); + longlong val_int(); + String *val_str(String*str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return hybrid_type; } + void reset_field(); + void update_field(); + void no_rows_in_result() {} + const char *func_name() const { return "sum("; } + Item *copy_or_same(THD* thd); +}; + + + +/* Common class for SUM(DISTINCT), AVG(DISTINCT) */ + +class Unique; + +class Item_sum_distinct :public Item_sum_num +{ +protected: + /* storage for the summation result */ + ulonglong count; + Hybrid_type val; + /* storage for unique elements */ + Unique *tree; + TABLE *table; + enum enum_field_types table_field_type; + uint tree_key_length; +protected: + Item_sum_distinct(THD *thd, Item_sum_distinct *item); +public: + Item_sum_distinct(Item *item_par); + ~Item_sum_distinct(); + + bool setup(THD *thd); + void clear(); + void cleanup(); + bool add(); + double val_real(); + my_decimal *val_decimal(my_decimal *); + longlong val_int(); + String *val_str(String *str); + + /* XXX: does it need make_unique? */ + + enum Sumfunctype sum_func () const { return SUM_DISTINCT_FUNC; } + void reset_field() {} // not used + void update_field() {} // not used + virtual void no_rows_in_result() {} + void fix_length_and_dec(); + enum Item_result result_type () const { return val.traits->type(); } + virtual void calculate_val_and_count(); + virtual bool unique_walk_function(void *elem); +}; + + +/* + Item_sum_sum_distinct - implementation of SUM(DISTINCT expr). + See also: MySQL manual, chapter 'Adding New Functions To MySQL' + and comments in item_sum.cc. +*/ + +class Item_sum_sum_distinct :public Item_sum_distinct +{ +private: + Item_sum_sum_distinct(THD *thd, Item_sum_sum_distinct *item) + :Item_sum_distinct(thd, item) {} +public: + Item_sum_sum_distinct(Item *item_arg) :Item_sum_distinct(item_arg) {} + + enum Sumfunctype sum_func () const { return SUM_DISTINCT_FUNC; } + const char *func_name() const { return "sum(distinct "; } + Item *copy_or_same(THD* thd) { return new Item_sum_sum_distinct(thd, this); } +}; + + +/* Item_sum_avg_distinct - SELECT AVG(DISTINCT expr) FROM ... */ + +class Item_sum_avg_distinct: public Item_sum_distinct +{ +private: + Item_sum_avg_distinct(THD *thd, Item_sum_avg_distinct *original) + :Item_sum_distinct(thd, original) {} +public: + uint prec_increment; + Item_sum_avg_distinct(Item *item_arg) : Item_sum_distinct(item_arg) {} + + void fix_length_and_dec(); + virtual void calculate_val_and_count(); + enum Sumfunctype sum_func () const { return AVG_DISTINCT_FUNC; } + const char *func_name() const { return "avg(distinct "; } + Item *copy_or_same(THD* thd) { return new Item_sum_avg_distinct(thd, this); } +}; + + +class Item_sum_count :public Item_sum_int +{ + longlong count; + + public: + Item_sum_count(Item *item_par) + :Item_sum_int(item_par),count(0) + {} + Item_sum_count(THD *thd, Item_sum_count *item) + :Item_sum_int(thd, item), count(item->count) + {} + enum Sumfunctype sum_func () const { return COUNT_FUNC; } + void clear(); + void no_rows_in_result() { count=0; } + bool add(); + void make_const(longlong count_arg) + { + count=count_arg; + Item_sum::make_const(); + } + longlong val_int(); + void reset_field(); + void cleanup(); + void update_field(); + const char *func_name() const { return "count("; } + Item *copy_or_same(THD* thd); +}; + + +class TMP_TABLE_PARAM; + +class Item_sum_count_distinct :public Item_sum_int +{ + TABLE *table; + uint32 *field_lengths; + TMP_TABLE_PARAM *tmp_table_param; + bool force_copy_fields; + /* + If there are no blobs, we can use a tree, which + is faster than heap table. In that case, we still use the table + to help get things set up, but we insert nothing in it + */ + Unique *tree; + /* + Storage for the value of count between calls to val_int() so val_int() + will not recalculate on each call. Validitiy of the value is stored in + is_evaluated. + */ + longlong count; + /* + Following is 0 normal object and pointer to original one for copy + (to correctly free resources) + */ + Item_sum_count_distinct *original; + uint tree_key_length; + + + bool always_null; // Set to 1 if the result is always NULL + + + friend int composite_key_cmp(void* arg, uchar* key1, uchar* key2); + friend int simple_str_key_cmp(void* arg, uchar* key1, uchar* key2); + +public: + Item_sum_count_distinct(List &list) + :Item_sum_int(list), table(0), field_lengths(0), tmp_table_param(0), + force_copy_fields(0), tree(0), count(0), + original(0), always_null(FALSE) + { quick_group= 0; } + Item_sum_count_distinct(THD *thd, Item_sum_count_distinct *item) + :Item_sum_int(thd, item), table(item->table), + field_lengths(item->field_lengths), + tmp_table_param(item->tmp_table_param), + force_copy_fields(0), tree(item->tree), count(item->count), + original(item), tree_key_length(item->tree_key_length), + always_null(item->always_null) + {} + ~Item_sum_count_distinct(); + + void cleanup(); + + enum Sumfunctype sum_func () const { return COUNT_DISTINCT_FUNC; } + void clear(); + bool add(); + longlong val_int(); + void reset_field() { return ;} // Never called + void update_field() { return ; } // Never called + const char *func_name() const { return "count(distinct "; } + bool setup(THD *thd); + void make_unique(); + Item *copy_or_same(THD* thd); + void no_rows_in_result() {} +}; + + +/* Item to get the value of a stored sum function */ + +class Item_sum_avg; + +class Item_avg_field :public Item_result_field +{ +public: + Field *field; + Item_result hybrid_type; + uint f_precision, f_scale, dec_bin_size; + uint prec_increment; + Item_avg_field(Item_result res_type, Item_sum_avg *item); + enum Type type() const { return FIELD_AVG_ITEM; } + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + bool is_null() { update_null_value(); return null_value; } + String *val_str(String*); + enum_field_types field_type() const + { + return hybrid_type == DECIMAL_RESULT ? + MYSQL_TYPE_NEWDECIMAL : MYSQL_TYPE_DOUBLE; + } + void fix_length_and_dec() {} + enum Item_result result_type () const { return hybrid_type; } +}; + + +class Item_sum_avg :public Item_sum_sum +{ +public: + ulonglong count; + uint prec_increment; + uint f_precision, f_scale, dec_bin_size; + + Item_sum_avg(Item *item_par) :Item_sum_sum(item_par), count(0) {} + Item_sum_avg(THD *thd, Item_sum_avg *item) + :Item_sum_sum(thd, item), count(item->count), + prec_increment(item->prec_increment) {} + + void fix_length_and_dec(); + enum Sumfunctype sum_func () const {return AVG_FUNC;} + void clear(); + bool add(); + double val_real(); + // In SPs we might force the "wrong" type with select into a declare variable + longlong val_int() { return (longlong) rint(val_real()); } + my_decimal *val_decimal(my_decimal *); + String *val_str(String *str); + void reset_field(); + void update_field(); + Item *result_item(Field *field) + { return new Item_avg_field(hybrid_type, this); } + void no_rows_in_result() {} + const char *func_name() const { return "avg("; } + Item *copy_or_same(THD* thd); + Field *create_tmp_field(bool group, TABLE *table, uint convert_blob_length); + void cleanup() + { + count= 0; + Item_sum_sum::cleanup(); + } +}; + +class Item_sum_variance; + +class Item_variance_field :public Item_result_field +{ +public: + Field *field; + Item_result hybrid_type; + uint f_precision0, f_scale0; + uint f_precision1, f_scale1; + uint dec_bin_size0, dec_bin_size1; + uint sample; + uint prec_increment; + Item_variance_field(Item_sum_variance *item); + enum Type type() const {return FIELD_VARIANCE_ITEM; } + double val_real(); + longlong val_int() + { /* can't be fix_fields()ed */ return (longlong) rint(val_real()); } + String *val_str(String *str) + { return val_string_from_real(str); } + my_decimal *val_decimal(my_decimal *dec_buf) + { return val_decimal_from_real(dec_buf); } + bool is_null() { update_null_value(); return null_value; } + enum_field_types field_type() const + { + return hybrid_type == DECIMAL_RESULT ? + MYSQL_TYPE_NEWDECIMAL : MYSQL_TYPE_DOUBLE; + } + void fix_length_and_dec() {} + enum Item_result result_type () const { return hybrid_type; } +}; + + +/* + variance(a) = + + = sum (ai - avg(a))^2 / count(a) ) + = sum (ai^2 - 2*ai*avg(a) + avg(a)^2) / count(a) + = (sum(ai^2) - sum(2*ai*avg(a)) + sum(avg(a)^2))/count(a) = + = (sum(ai^2) - 2*avg(a)*sum(a) + count(a)*avg(a)^2)/count(a) = + = (sum(ai^2) - 2*sum(a)*sum(a)/count(a) + count(a)*sum(a)^2/count(a)^2 )/count(a) = + = (sum(ai^2) - 2*sum(a)^2/count(a) + sum(a)^2/count(a) )/count(a) = + = (sum(ai^2) - sum(a)^2/count(a))/count(a) + +But, this falls prey to catastrophic cancellation. Instead, use the recurrence formulas + + M_{1} = x_{1}, ~ M_{k} = M_{k-1} + (x_{k} - M_{k-1}) / k newline + S_{1} = 0, ~ S_{k} = S_{k-1} + (x_{k} - M_{k-1}) times (x_{k} - M_{k}) newline + for 2 <= k <= n newline + ital variance = S_{n} / (n-1) + +*/ + +class Item_sum_variance : public Item_sum_num +{ + void fix_length_and_dec(); + +public: + Item_result hybrid_type; + int cur_dec; + double recurrence_m, recurrence_s; /* Used in recurrence relation. */ + ulonglong count; + uint f_precision0, f_scale0; + uint f_precision1, f_scale1; + uint dec_bin_size0, dec_bin_size1; + uint sample; + uint prec_increment; + + Item_sum_variance(Item *item_par, uint sample_arg) :Item_sum_num(item_par), + hybrid_type(REAL_RESULT), count(0), sample(sample_arg) + {} + Item_sum_variance(THD *thd, Item_sum_variance *item); + enum Sumfunctype sum_func () const { return VARIANCE_FUNC; } + void clear(); + bool add(); + double val_real(); + my_decimal *val_decimal(my_decimal *); + void reset_field(); + void update_field(); + Item *result_item(Field *field) + { return new Item_variance_field(this); } + void no_rows_in_result() {} + const char *func_name() const + { return sample ? "var_samp(" : "variance("; } + Item *copy_or_same(THD* thd); + Field *create_tmp_field(bool group, TABLE *table, uint convert_blob_length); + enum Item_result result_type () const { return REAL_RESULT; } + void cleanup() + { + count= 0; + Item_sum_num::cleanup(); + } +}; + +class Item_sum_std; + +class Item_std_field :public Item_variance_field +{ +public: + Item_std_field(Item_sum_std *item); + enum Type type() const { return FIELD_STD_ITEM; } + double val_real(); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return REAL_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_DOUBLE;} +}; + +/* + standard_deviation(a) = sqrt(variance(a)) +*/ + +class Item_sum_std :public Item_sum_variance +{ + public: + Item_sum_std(Item *item_par, uint sample_arg) + :Item_sum_variance(item_par, sample_arg) {} + Item_sum_std(THD *thd, Item_sum_std *item) + :Item_sum_variance(thd, item) + {} + enum Sumfunctype sum_func () const { return STD_FUNC; } + double val_real(); + Item *result_item(Field *field) + { return new Item_std_field(this); } + const char *func_name() const { return "std("; } + Item *copy_or_same(THD* thd); + enum Item_result result_type () const { return REAL_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_DOUBLE;} +}; + +// This class is a string or number function depending on num_func + +class Item_sum_hybrid :public Item_sum +{ +protected: + String value,tmp_value; + double sum; + longlong sum_int; + my_decimal sum_dec; + Item_result hybrid_type; + enum_field_types hybrid_field_type; + int cmp_sign; + bool was_values; // Set if we have found at least one row (for max/min only) + + public: + Item_sum_hybrid(Item *item_par,int sign) + :Item_sum(item_par), sum(0.0), sum_int(0), + hybrid_type(INT_RESULT), hybrid_field_type(MYSQL_TYPE_LONGLONG), + cmp_sign(sign), was_values(TRUE) + { collation.set(&my_charset_bin); } + Item_sum_hybrid(THD *thd, Item_sum_hybrid *item); + bool fix_fields(THD *, Item **); + void clear(); + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + void reset_field(); + String *val_str(String *); + bool keep_field_type(void) const { return 1; } + enum Item_result result_type () const { return hybrid_type; } + enum enum_field_types field_type() const { return hybrid_field_type; } + void update_field(); + void min_max_update_str_field(); + void min_max_update_real_field(); + void min_max_update_int_field(); + void min_max_update_decimal_field(); + void cleanup(); + bool any_value() { return was_values; } + void no_rows_in_result(); + Field *create_tmp_field(bool group, TABLE *table, + uint convert_blob_length); +}; + + +class Item_sum_min :public Item_sum_hybrid +{ +public: + Item_sum_min(Item *item_par) :Item_sum_hybrid(item_par,1) {} + Item_sum_min(THD *thd, Item_sum_min *item) :Item_sum_hybrid(thd, item) {} + enum Sumfunctype sum_func () const {return MIN_FUNC;} + + bool add(); + const char *func_name() const { return "min("; } + Item *copy_or_same(THD* thd); +}; + + +class Item_sum_max :public Item_sum_hybrid +{ +public: + Item_sum_max(Item *item_par) :Item_sum_hybrid(item_par,-1) {} + Item_sum_max(THD *thd, Item_sum_max *item) :Item_sum_hybrid(thd, item) {} + enum Sumfunctype sum_func () const {return MAX_FUNC;} + + bool add(); + const char *func_name() const { return "max("; } + Item *copy_or_same(THD* thd); +}; + + +class Item_sum_bit :public Item_sum_int +{ +protected: + ulonglong reset_bits,bits; + +public: + Item_sum_bit(Item *item_par,ulonglong reset_arg) + :Item_sum_int(item_par),reset_bits(reset_arg),bits(reset_arg) {} + Item_sum_bit(THD *thd, Item_sum_bit *item): + Item_sum_int(thd, item), reset_bits(item->reset_bits), bits(item->bits) {} + enum Sumfunctype sum_func () const {return SUM_BIT_FUNC;} + void clear(); + longlong val_int(); + void reset_field(); + void update_field(); + void fix_length_and_dec() + { decimals= 0; max_length=21; unsigned_flag= 1; maybe_null= null_value= 0; } + void cleanup() + { + bits= reset_bits; + Item_sum_int::cleanup(); + } +}; + + +class Item_sum_or :public Item_sum_bit +{ +public: + Item_sum_or(Item *item_par) :Item_sum_bit(item_par,LL(0)) {} + Item_sum_or(THD *thd, Item_sum_or *item) :Item_sum_bit(thd, item) {} + bool add(); + const char *func_name() const { return "bit_or("; } + Item *copy_or_same(THD* thd); +}; + + +class Item_sum_and :public Item_sum_bit +{ + public: + Item_sum_and(Item *item_par) :Item_sum_bit(item_par, ULONGLONG_MAX) {} + Item_sum_and(THD *thd, Item_sum_and *item) :Item_sum_bit(thd, item) {} + bool add(); + const char *func_name() const { return "bit_and("; } + Item *copy_or_same(THD* thd); +}; + +class Item_sum_xor :public Item_sum_bit +{ + public: + Item_sum_xor(Item *item_par) :Item_sum_bit(item_par,LL(0)) {} + Item_sum_xor(THD *thd, Item_sum_xor *item) :Item_sum_bit(thd, item) {} + bool add(); + const char *func_name() const { return "bit_xor("; } + Item *copy_or_same(THD* thd); +}; + + +/* + User defined aggregates +*/ + +#ifdef HAVE_DLOPEN + +class Item_udf_sum : public Item_sum +{ +protected: + udf_handler udf; + +public: + Item_udf_sum(udf_func *udf_arg) + :Item_sum(), udf(udf_arg) + { quick_group=0; } + Item_udf_sum(udf_func *udf_arg, List &list) + :Item_sum(list), udf(udf_arg) + { quick_group=0;} + Item_udf_sum(THD *thd, Item_udf_sum *item) + :Item_sum(thd, item), udf(item->udf) + { udf.not_original= TRUE; } + const char *func_name() const { return udf.name(); } + bool fix_fields(THD *thd, Item **ref) + { + DBUG_ASSERT(fixed == 0); + + if (init_sum_func_check(thd)) + return TRUE; + + fixed= 1; + if (udf.fix_fields(thd, this, this->arg_count, this->args)) + return TRUE; + + memcpy (orig_args, args, sizeof (Item *) * arg_count); + return check_sum_func(thd, ref); + } + enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } + virtual bool have_field_update(void) const { return 0; } + + void clear(); + bool add(); + void reset_field() {}; + void update_field() {}; + void cleanup(); + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_sum_udf_float :public Item_udf_sum +{ + public: + Item_sum_udf_float(udf_func *udf_arg) + :Item_udf_sum(udf_arg) {} + Item_sum_udf_float(udf_func *udf_arg, List &list) + :Item_udf_sum(udf_arg, list) {} + Item_sum_udf_float(THD *thd, Item_sum_udf_float *item) + :Item_udf_sum(thd, item) {} + longlong val_int() + { + DBUG_ASSERT(fixed == 1); + return (longlong) rint(Item_sum_udf_float::val_real()); + } + double val_real(); + String *val_str(String*str); + my_decimal *val_decimal(my_decimal *); + void fix_length_and_dec() { fix_num_length_and_dec(); } + Item *copy_or_same(THD* thd); +}; + + +class Item_sum_udf_int :public Item_udf_sum +{ +public: + Item_sum_udf_int(udf_func *udf_arg) + :Item_udf_sum(udf_arg) {} + Item_sum_udf_int(udf_func *udf_arg, List &list) + :Item_udf_sum(udf_arg, list) {} + Item_sum_udf_int(THD *thd, Item_sum_udf_int *item) + :Item_udf_sum(thd, item) {} + longlong val_int(); + double val_real() + { DBUG_ASSERT(fixed == 1); return (double) Item_sum_udf_int::val_int(); } + String *val_str(String*str); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return INT_RESULT; } + void fix_length_and_dec() { decimals=0; max_length=21; } + Item *copy_or_same(THD* thd); +}; + + +class Item_sum_udf_str :public Item_udf_sum +{ +public: + Item_sum_udf_str(udf_func *udf_arg) + :Item_udf_sum(udf_arg) {} + Item_sum_udf_str(udf_func *udf_arg, List &list) + :Item_udf_sum(udf_arg,list) {} + Item_sum_udf_str(THD *thd, Item_sum_udf_str *item) + :Item_udf_sum(thd, item) {} + String *val_str(String *); + double val_real() + { + int err_not_used; + char *end_not_used; + String *res; + res=val_str(&str_value); + return res ? my_strntod(res->charset(),(char*) res->ptr(),res->length(), + &end_not_used, &err_not_used) : 0.0; + } + longlong val_int() + { + int err_not_used; + char *end; + String *res; + CHARSET_INFO *cs; + + if (!(res= val_str(&str_value))) + return 0; /* Null value */ + cs= res->charset(); + end= (char*) res->ptr()+res->length(); + return cs->cset->strtoll10(cs, res->ptr(), &end, &err_not_used); + } + my_decimal *val_decimal(my_decimal *dec); + enum Item_result result_type () const { return STRING_RESULT; } + void fix_length_and_dec(); + Item *copy_or_same(THD* thd); +}; + + +class Item_sum_udf_decimal :public Item_udf_sum +{ +public: + Item_sum_udf_decimal(udf_func *udf_arg) + :Item_udf_sum(udf_arg) {} + Item_sum_udf_decimal(udf_func *udf_arg, List &list) + :Item_udf_sum(udf_arg, list) {} + Item_sum_udf_decimal(THD *thd, Item_sum_udf_decimal *item) + :Item_udf_sum(thd, item) {} + String *val_str(String *); + double val_real(); + longlong val_int(); + my_decimal *val_decimal(my_decimal *); + enum Item_result result_type () const { return DECIMAL_RESULT; } + void fix_length_and_dec() { fix_num_length_and_dec(); } + Item *copy_or_same(THD* thd); +}; + +#else /* Dummy functions to get sql_yacc.cc compiled */ + +class Item_sum_udf_float :public Item_sum_num +{ + public: + Item_sum_udf_float(udf_func *udf_arg) + :Item_sum_num() {} + Item_sum_udf_float(udf_func *udf_arg, List &list) :Item_sum_num() {} + Item_sum_udf_float(THD *thd, Item_sum_udf_float *item) + :Item_sum_num(thd, item) {} + enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } + double val_real() { DBUG_ASSERT(fixed == 1); return 0.0; } + void clear() {} + bool add() { return 0; } + void update_field() {} +}; + + +class Item_sum_udf_int :public Item_sum_num +{ +public: + Item_sum_udf_int(udf_func *udf_arg) + :Item_sum_num() {} + Item_sum_udf_int(udf_func *udf_arg, List &list) :Item_sum_num() {} + Item_sum_udf_int(THD *thd, Item_sum_udf_int *item) + :Item_sum_num(thd, item) {} + enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } + longlong val_int() { DBUG_ASSERT(fixed == 1); return 0; } + double val_real() { DBUG_ASSERT(fixed == 1); return 0; } + void clear() {} + bool add() { return 0; } + void update_field() {} +}; + + +class Item_sum_udf_decimal :public Item_sum_num +{ + public: + Item_sum_udf_decimal(udf_func *udf_arg) + :Item_sum_num() {} + Item_sum_udf_decimal(udf_func *udf_arg, List &list) + :Item_sum_num() {} + Item_sum_udf_decimal(THD *thd, Item_sum_udf_float *item) + :Item_sum_num(thd, item) {} + enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } + double val_real() { DBUG_ASSERT(fixed == 1); return 0.0; } + my_decimal *val_decimal(my_decimal *) { DBUG_ASSERT(fixed == 1); return 0; } + void clear() {} + bool add() { return 0; } + void update_field() {} +}; + + +class Item_sum_udf_str :public Item_sum_num +{ +public: + Item_sum_udf_str(udf_func *udf_arg) + :Item_sum_num() {} + Item_sum_udf_str(udf_func *udf_arg, List &list) + :Item_sum_num() {} + Item_sum_udf_str(THD *thd, Item_sum_udf_str *item) + :Item_sum_num(thd, item) {} + String *val_str(String *) + { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } + double val_real() { DBUG_ASSERT(fixed == 1); null_value=1; return 0.0; } + longlong val_int() { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } + enum Item_result result_type () const { return STRING_RESULT; } + void fix_length_and_dec() { maybe_null=1; max_length=0; } + enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } + void clear() {} + bool add() { return 0; } + void update_field() {} +}; + +#endif /* HAVE_DLOPEN */ + +class MYSQL_ERROR; + +class Item_func_group_concat : public Item_sum +{ + TMP_TABLE_PARAM *tmp_table_param; + MYSQL_ERROR *warning; + String result; + String *separator; + TREE tree_base; + TREE *tree; + + /** + If DISTINCT is used with this GROUP_CONCAT, this member is used to filter + out duplicates. + @see Item_func_group_concat::setup + @see Item_func_group_concat::add + @see Item_func_group_concat::clear + */ + Unique *unique_filter; + TABLE *table; + //ORDER **order; + //Name_resolution_context *context; + /** The number of ORDER BY items. */ + uint arg_count_order; + /** The number of selected items, aka the expr list. */ + uint arg_count_field; + uint count_cut_values; + bool distinct; + bool warning_for_row; + bool always_null; + bool force_copy_fields; + bool no_appended; + /* + Following is 0 normal object and pointer to original one for copy + (to correctly free resources) + */ + Item_func_group_concat *original; + + friend int group_concat_key_cmp_with_distinct(void* arg, const void* key1, + const void* key2); + friend int group_concat_key_cmp_with_order(void* arg, const void* key1, + const void* key2); + friend int dump_leaf_key(uchar* key, + element_count count __attribute__((unused)), + Item_func_group_concat *group_concat_item); + +public: + Item_func_group_concat(Name_resolution_context *context_arg, + bool is_distinct, List *is_select, + SQL_LIST *is_order, String *is_separator); + + Item_func_group_concat(THD *thd, Item_func_group_concat *item); + ~Item_func_group_concat(); + void cleanup(); + + enum Sumfunctype sum_func () const {return GROUP_CONCAT_FUNC;} + const char *func_name() const { return "group_concat"; } + virtual Item_result result_type () const { return STRING_RESULT; } + enum_field_types field_type() const; + void clear(); + bool add(); + void reset_field() { DBUG_ASSERT(0); } // not used + void update_field() { DBUG_ASSERT(0); } // not used + bool fix_fields(THD *,Item **); + bool setup(THD *thd); + void make_unique(); + double val_real() + { + String *res; res=val_str(&str_value); + return res ? my_atof(res->c_ptr()) : 0.0; + } + longlong val_int() + { + String *res; + char *end_ptr; + int error; + if (!(res= val_str(&str_value))) + return (longlong) 0; + end_ptr= (char*) res->ptr()+ res->length(); + return my_strtoll10(res->ptr(), &end_ptr, &error); + } + my_decimal *val_decimal(my_decimal *decimal_value) + { + return val_decimal_from_string(decimal_value); + } + String* val_str(String* str); + Item *copy_or_same(THD* thd); + void no_rows_in_result() {} + virtual void print(String *str, enum_query_type query_type); + virtual bool change_context_processor(uchar *cntx) + { context= (Name_resolution_context *)cntx; return FALSE; } + // InfiniDB added interface + bool isDistinct() { return distinct; } + uint count_field() { return arg_count_field; } + uint order_field() { return arg_count_order; } + String* str_separator() { return separator; } + ORDER **order; // InfiniDB: keep it in public place + Name_resolution_context *context; // InfiniDB: keep it in public place +}; diff --git a/dbcon/mysql/item_timefunc.cc b/dbcon/mysql/item_timefunc.cc new file mode 100644 index 00000000..0910969e --- /dev/null +++ b/dbcon/mysql/item_timefunc.cc @@ -0,0 +1,3420 @@ +/* Copyright (C) 2000-2003 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/** + @file + + @brief + This file defines all time functions + + @todo + Move month and days to language files +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include +#include + +/** Day number for Dec 31st, 9999. */ +#define MAX_DAY_NUMBER 3652424L + +/** + @todo + OPTIMIZATION + - Replace the switch with a function that should be called for each + date type. + - Remove sprintf and opencode the conversion, like we do in + Field_datetime. + + The reason for this functions existence is that as we don't have a + way to know if a datetime/time value has microseconds in them + we are now only adding microseconds to the output if the + value has microseconds. + + We can't use a standard make_date_time() for this as we don't know + if someone will use %f in the format specifier in which case we would get + the microseconds twice. +*/ + +static bool make_datetime(date_time_format_types format, MYSQL_TIME *ltime, + String *str) +{ + char *buff; + CHARSET_INFO *cs= &my_charset_bin; + uint length= MAX_DATE_STRING_REP_LENGTH; + + if (str->alloc(length)) + return 1; + buff= (char*) str->ptr(); + + switch (format) { + case TIME_ONLY: + length= cs->cset->snprintf(cs, buff, length, "%s%02d:%02d:%02d", + ltime->neg ? "-" : "", + ltime->hour, ltime->minute, ltime->second); + break; + case TIME_MICROSECOND: + length= cs->cset->snprintf(cs, buff, length, "%s%02d:%02d:%02d.%06ld", + ltime->neg ? "-" : "", + ltime->hour, ltime->minute, ltime->second, + ltime->second_part); + break; + case DATE_ONLY: + length= cs->cset->snprintf(cs, buff, length, "%04d-%02d-%02d", + ltime->year, ltime->month, ltime->day); + break; + case DATE_TIME: + length= cs->cset->snprintf(cs, buff, length, + "%04d-%02d-%02d %02d:%02d:%02d", + ltime->year, ltime->month, ltime->day, + ltime->hour, ltime->minute, ltime->second); + break; + case DATE_TIME_MICROSECOND: + length= cs->cset->snprintf(cs, buff, length, + "%04d-%02d-%02d %02d:%02d:%02d.%06ld", + ltime->year, ltime->month, ltime->day, + ltime->hour, ltime->minute, ltime->second, + ltime->second_part); + break; + } + + str->length(length); + str->set_charset(cs); + return 0; +} + + +/* + Wrapper over make_datetime() with validation of the input MYSQL_TIME value + + NOTE + see make_datetime() for more information + + RETURN + 1 if there was an error during converion + 0 otherwise +*/ + +static bool make_datetime_with_warn(date_time_format_types format, MYSQL_TIME *ltime, + String *str) +{ + int warning= 0; + + if (make_datetime(format, ltime, str)) + return 1; + if (check_time_range(ltime, &warning)) + return 1; + if (!warning) + return 0; + + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + str->ptr(), str->length(), + MYSQL_TIMESTAMP_TIME, NullS); + return make_datetime(format, ltime, str); +} + + +/* + Wrapper over make_time() with validation of the input MYSQL_TIME value + + NOTE + see make_time() for more info + + RETURN + 1 if there was an error during conversion + 0 otherwise +*/ + +static bool make_time_with_warn(const DATE_TIME_FORMAT *format, + MYSQL_TIME *l_time, String *str) +{ + int warning= 0; + make_time(format, l_time, str); + if (check_time_range(l_time, &warning)) + return 1; + if (warning) + { + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + str->ptr(), str->length(), + MYSQL_TIMESTAMP_TIME, NullS); + make_time(format, l_time, str); + } + + return 0; +} + + +/* + Convert seconds to MYSQL_TIME value with overflow checking + + SYNOPSIS: + sec_to_time() + seconds number of seconds + unsigned_flag 1, if 'seconds' is unsigned, 0, otherwise + ltime output MYSQL_TIME value + + DESCRIPTION + If the 'seconds' argument is inside MYSQL_TIME data range, convert it to a + corresponding value. + Otherwise, truncate the resulting value to the nearest endpoint, and + produce a warning message. + + RETURN + 1 if the value was truncated during conversion + 0 otherwise +*/ + +static bool sec_to_time(longlong seconds, bool unsigned_flag, MYSQL_TIME *ltime) +{ + uint sec; + + bzero((char *)ltime, sizeof(*ltime)); + + if (seconds < 0) + { + if (unsigned_flag) + goto overflow; + ltime->neg= 1; + if (seconds < -3020399) + goto overflow; + seconds= -seconds; + } + else if (seconds > 3020399) + goto overflow; + + sec= (uint) ((ulonglong) seconds % 3600); + ltime->hour= (uint) (seconds/3600); + ltime->minute= sec/60; + ltime->second= sec % 60; + + return 0; + +overflow: + ltime->hour= TIME_MAX_HOUR; + ltime->minute= TIME_MAX_MINUTE; + ltime->second= TIME_MAX_SECOND; + + char buf[22]; + int len= (int)(longlong10_to_str(seconds, buf, unsigned_flag ? 10 : -10) + - buf); + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + buf, len, MYSQL_TIMESTAMP_TIME, + NullS); + + return 1; +} + + +/* + Date formats corresponding to compound %r and %T conversion specifiers + + Note: We should init at least first element of "positions" array + (first member) or hpux11 compiler will die horribly. +*/ +static DATE_TIME_FORMAT time_ampm_format= {{0}, '\0', 0, + {(char *)"%I:%i:%S %p", 11}}; +static DATE_TIME_FORMAT time_24hrs_format= {{0}, '\0', 0, + {(char *)"%H:%i:%S", 8}}; + +/** + Extract datetime value to MYSQL_TIME struct from string value + according to format string. + + @param format date/time format specification + @param val String to decode + @param length Length of string + @param l_time Store result here + @param cached_timestamp_type It uses to get an appropriate warning + in the case when the value is truncated. + @param sub_pattern_end if non-zero then we are parsing string which + should correspond compound specifier (like %T or + %r) and this parameter is pointer to place where + pointer to end of string matching this specifier + should be stored. + + @note + Possibility to parse strings matching to patterns equivalent to compound + specifiers is mainly intended for use from inside of this function in + order to understand %T and %r conversion specifiers, so number of + conversion specifiers that can be used in such sub-patterns is limited. + Also most of checks are skipped in this case. + + @note + If one adds new format specifiers to this function he should also + consider adding them to get_date_time_result_type() function. + + @retval + 0 ok + @retval + 1 error +*/ + +static bool extract_date_time(DATE_TIME_FORMAT *format, + const char *val, uint length, MYSQL_TIME *l_time, + timestamp_type cached_timestamp_type, + const char **sub_pattern_end, + const char *date_time_type) +{ + int weekday= 0, yearday= 0, daypart= 0; + int week_number= -1; + int error= 0; + int strict_week_number_year= -1; + int frac_part; + bool usa_time= 0; + bool sunday_first_n_first_week_non_iso; + bool strict_week_number; + bool strict_week_number_year_type; + const char *val_begin= val; + const char *val_end= val + length; + const char *ptr= format->format.str; + const char *end= ptr + format->format.length; + CHARSET_INFO *cs= &my_charset_bin; + DBUG_ENTER("extract_date_time"); + + LINT_INIT(strict_week_number); + /* Remove valgrind varnings when using gcc 3.3 and -O1 */ + PURIFY_OR_LINT_INIT(strict_week_number_year_type); + PURIFY_OR_LINT_INIT(sunday_first_n_first_week_non_iso); + + if (!sub_pattern_end) + bzero((char*) l_time, sizeof(*l_time)); + + for (; ptr != end && val != val_end; ptr++) + { + /* Skip pre-space between each argument */ + while (val != val_end && my_isspace(cs, *val)) + val++; + + if (*ptr == '%' && ptr+1 != end) + { + int val_len; + char *tmp; + + error= 0; + + val_len= (uint) (val_end - val); + switch (*++ptr) { + /* Year */ + case 'Y': + tmp= (char*) val + min(4, val_len); + l_time->year= (int) my_strtoll10(val, &tmp, &error); + if ((int) (tmp-val) <= 2) + l_time->year= year_2000_handling(l_time->year); + val= tmp; + break; + case 'y': + tmp= (char*) val + min(2, val_len); + l_time->year= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + l_time->year= year_2000_handling(l_time->year); + break; + + /* Month */ + case 'm': + case 'c': + tmp= (char*) val + min(2, val_len); + l_time->month= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + case 'M': + if ((l_time->month= check_word(my_locale_en_US.month_names, + val, val_end, &val)) <= 0) + goto err; + break; + case 'b': + if ((l_time->month= check_word(my_locale_en_US.ab_month_names, + val, val_end, &val)) <= 0) + goto err; + break; + /* Day */ + case 'd': + case 'e': + tmp= (char*) val + min(2, val_len); + l_time->day= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + case 'D': + tmp= (char*) val + min(2, val_len); + l_time->day= (int) my_strtoll10(val, &tmp, &error); + /* Skip 'st, 'nd, 'th .. */ + val= tmp + min((int) (val_end-tmp), 2); + break; + + /* Hour */ + case 'h': + case 'I': + case 'l': + usa_time= 1; + /* fall through */ + case 'k': + case 'H': + tmp= (char*) val + min(2, val_len); + l_time->hour= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + + /* Minute */ + case 'i': + tmp= (char*) val + min(2, val_len); + l_time->minute= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + + /* Second */ + case 's': + case 'S': + tmp= (char*) val + min(2, val_len); + l_time->second= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + + /* Second part */ + case 'f': + tmp= (char*) val_end; + if (tmp - val > 6) + tmp= (char*) val + 6; + l_time->second_part= (int) my_strtoll10(val, &tmp, &error); + frac_part= 6 - (uint) (tmp - val); + if (frac_part > 0) + l_time->second_part*= (ulong) log_10_int[frac_part]; + val= tmp; + break; + + /* AM / PM */ + case 'p': + if (val_len < 2 || ! usa_time) + goto err; + if (!my_strnncoll(&my_charset_latin1, + (const uchar *) val, 2, + (const uchar *) "PM", 2)) + daypart= 12; + else if (my_strnncoll(&my_charset_latin1, + (const uchar *) val, 2, + (const uchar *) "AM", 2)) + goto err; + val+= 2; + break; + + /* Exotic things */ + case 'W': + if ((weekday= check_word(my_locale_en_US.day_names, val, val_end, &val)) <= 0) + goto err; + break; + case 'a': + if ((weekday= check_word(my_locale_en_US.ab_day_names, val, val_end, &val)) <= 0) + goto err; + break; + case 'w': + tmp= (char*) val + 1; + if ((weekday= (int) my_strtoll10(val, &tmp, &error)) < 0 || + weekday >= 7) + goto err; + /* We should use the same 1 - 7 scale for %w as for %W */ + if (!weekday) + weekday= 7; + val= tmp; + break; + case 'j': + tmp= (char*) val + min(val_len, 3); + yearday= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + + /* Week numbers */ + case 'V': + case 'U': + case 'v': + case 'u': + sunday_first_n_first_week_non_iso= (*ptr=='U' || *ptr== 'V'); + strict_week_number= (*ptr=='V' || *ptr=='v'); + tmp= (char*) val + min(val_len, 2); + if ((week_number= (int) my_strtoll10(val, &tmp, &error)) < 0 || + (strict_week_number && !week_number) || + week_number > 53) + goto err; + val= tmp; + break; + + /* Year used with 'strict' %V and %v week numbers */ + case 'X': + case 'x': + strict_week_number_year_type= (*ptr=='X'); + tmp= (char*) val + min(4, val_len); + strict_week_number_year= (int) my_strtoll10(val, &tmp, &error); + val= tmp; + break; + + /* Time in AM/PM notation */ + case 'r': + /* + We can't just set error here, as we don't want to generate two + warnings in case of errors + */ + if (extract_date_time(&time_ampm_format, val, + (uint)(val_end - val), l_time, + cached_timestamp_type, &val, "time")) + DBUG_RETURN(1); + break; + + /* Time in 24-hour notation */ + case 'T': + if (extract_date_time(&time_24hrs_format, val, + (uint)(val_end - val), l_time, + cached_timestamp_type, &val, "time")) + DBUG_RETURN(1); + break; + + /* Conversion specifiers that match classes of characters */ + case '.': + while (my_ispunct(cs, *val) && val != val_end) + val++; + break; + case '@': + while (my_isalpha(cs, *val) && val != val_end) + val++; + break; + case '#': + while (my_isdigit(cs, *val) && val != val_end) + val++; + break; + default: + goto err; + } + if (error) // Error from my_strtoll10 + goto err; + } + else if (!my_isspace(cs, *ptr)) + { + if (*val != *ptr) + goto err; + val++; + } + } + if (usa_time) + { + if (l_time->hour > 12 || l_time->hour < 1) + goto err; + l_time->hour= l_time->hour%12+daypart; + } + + /* + If we are recursively called for parsing string matching compound + specifiers we are already done. + */ + if (sub_pattern_end) + { + *sub_pattern_end= val; + DBUG_RETURN(0); + } + + if (yearday > 0) + { + uint days; + days= calc_daynr(l_time->year,1,1) + yearday - 1; + if (days <= 0 || days > MAX_DAY_NUMBER) + goto err; + get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day); + } + + if (week_number >= 0 && weekday) + { + int days; + uint weekday_b; + + /* + %V,%v require %X,%x resprectively, + %U,%u should be used with %Y and not %X or %x + */ + if ((strict_week_number && + (strict_week_number_year < 0 || + strict_week_number_year_type != sunday_first_n_first_week_non_iso)) || + (!strict_week_number && strict_week_number_year >= 0)) + goto err; + + /* Number of days since year 0 till 1st Jan of this year */ + days= calc_daynr((strict_week_number ? strict_week_number_year : + l_time->year), + 1, 1); + /* Which day of week is 1st Jan of this year */ + weekday_b= calc_weekday(days, sunday_first_n_first_week_non_iso); + + /* + Below we are going to sum: + 1) number of days since year 0 till 1st day of 1st week of this year + 2) number of days between 1st week and our week + 3) and position of our day in the week + */ + if (sunday_first_n_first_week_non_iso) + { + days+= ((weekday_b == 0) ? 0 : 7) - weekday_b + + (week_number - 1) * 7 + + weekday % 7; + } + else + { + days+= ((weekday_b <= 3) ? 0 : 7) - weekday_b + + (week_number - 1) * 7 + + (weekday - 1); + } + + if (days <= 0 || days > MAX_DAY_NUMBER) + goto err; + get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day); + } + + if (l_time->month > 12 || l_time->day > 31 || l_time->hour > 23 || + l_time->minute > 59 || l_time->second > 59) + goto err; + + if (val != val_end) + { + do + { + if (!my_isspace(&my_charset_latin1,*val)) + { + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + val_begin, length, + cached_timestamp_type, NullS); + break; + } + } while (++val != val_end); + } + DBUG_RETURN(0); + +err: + { + char buff[128]; + strmake(buff, val_begin, min(length, sizeof(buff)-1)); + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE), + date_time_type, buff, "str_to_date"); + } + DBUG_RETURN(1); +} + + +/** + Create a formated date/time value in a string. +*/ + +bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time, + timestamp_type type, String *str) +{ + char intbuff[15]; + uint hours_i; + uint weekday; + ulong length; + const char *ptr, *end; + THD *thd= current_thd; + MY_LOCALE *locale= thd->variables.lc_time_names; + + str->length(0); + + if (l_time->neg) + str->append('-'); + + end= (ptr= format->format.str) + format->format.length; + for (; ptr != end ; ptr++) + { + if (*ptr != '%' || ptr+1 == end) + str->append(*ptr); + else + { + switch (*++ptr) { + case 'M': + if (!l_time->month) + return 1; + str->append(locale->month_names->type_names[l_time->month-1], + (uint) strlen(locale->month_names->type_names[l_time->month-1]), + system_charset_info); + break; + case 'b': + if (!l_time->month) + return 1; + str->append(locale->ab_month_names->type_names[l_time->month-1], + (uint) strlen(locale->ab_month_names->type_names[l_time->month-1]), + system_charset_info); + break; + case 'W': + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + weekday= calc_weekday(calc_daynr(l_time->year,l_time->month, + l_time->day),0); + str->append(locale->day_names->type_names[weekday], + (uint) strlen(locale->day_names->type_names[weekday]), + system_charset_info); + break; + case 'a': + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + weekday=calc_weekday(calc_daynr(l_time->year,l_time->month, + l_time->day),0); + str->append(locale->ab_day_names->type_names[weekday], + (uint) strlen(locale->ab_day_names->type_names[weekday]), + system_charset_info); + break; + case 'D': + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 1, '0'); + if (l_time->day >= 10 && l_time->day <= 19) + str->append(STRING_WITH_LEN("th")); + else + { + switch (l_time->day %10) { + case 1: + str->append(STRING_WITH_LEN("st")); + break; + case 2: + str->append(STRING_WITH_LEN("nd")); + break; + case 3: + str->append(STRING_WITH_LEN("rd")); + break; + default: + str->append(STRING_WITH_LEN("th")); + break; + } + } + break; + case 'Y': + length= (uint) (int10_to_str(l_time->year, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 4, '0'); + break; + case 'y': + length= (uint) (int10_to_str(l_time->year%100, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'm': + length= (uint) (int10_to_str(l_time->month, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'c': + length= (uint) (int10_to_str(l_time->month, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 1, '0'); + break; + case 'd': + length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'e': + length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 1, '0'); + break; + case 'f': + length= (uint) (int10_to_str(l_time->second_part, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 6, '0'); + break; + case 'H': + length= (uint) (int10_to_str(l_time->hour, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'h': + case 'I': + hours_i= (l_time->hour%24 + 11)%12+1; + length= (uint) (int10_to_str(hours_i, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'i': /* minutes */ + length= (uint) (int10_to_str(l_time->minute, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'j': + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + length= (uint) (int10_to_str(calc_daynr(l_time->year,l_time->month, + l_time->day) - + calc_daynr(l_time->year,1,1) + 1, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 3, '0'); + break; + case 'k': + length= (uint) (int10_to_str(l_time->hour, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 1, '0'); + break; + case 'l': + hours_i= (l_time->hour%24 + 11)%12+1; + length= (uint) (int10_to_str(hours_i, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 1, '0'); + break; + case 'p': + hours_i= l_time->hour%24; + str->append(hours_i < 12 ? "AM" : "PM",2); + break; + case 'r': + length= my_sprintf(intbuff, + (intbuff, + ((l_time->hour % 24) < 12) ? + "%02d:%02d:%02d AM" : "%02d:%02d:%02d PM", + (l_time->hour+11)%12+1, + l_time->minute, + l_time->second)); + str->append(intbuff, length); + break; + case 'S': + case 's': + length= (uint) (int10_to_str(l_time->second, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + break; + case 'T': + length= my_sprintf(intbuff, + (intbuff, + "%02d:%02d:%02d", + l_time->hour, + l_time->minute, + l_time->second)); + str->append(intbuff, length); + break; + case 'U': + case 'u': + { + uint year; + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + length= (uint) (int10_to_str(calc_week(l_time, + (*ptr) == 'U' ? + WEEK_FIRST_WEEKDAY : WEEK_MONDAY_FIRST, + &year), + intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + } + break; + case 'v': + case 'V': + { + uint year; + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + length= (uint) (int10_to_str(calc_week(l_time, + ((*ptr) == 'V' ? + (WEEK_YEAR | WEEK_FIRST_WEEKDAY) : + (WEEK_YEAR | WEEK_MONDAY_FIRST)), + &year), + intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 2, '0'); + } + break; + case 'x': + case 'X': + { + uint year; + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + (void) calc_week(l_time, + ((*ptr) == 'X' ? + WEEK_YEAR | WEEK_FIRST_WEEKDAY : + WEEK_YEAR | WEEK_MONDAY_FIRST), + &year); + length= (uint) (int10_to_str(year, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 4, '0'); + } + break; + case 'w': + if (type == MYSQL_TIMESTAMP_TIME) + return 1; + weekday=calc_weekday(calc_daynr(l_time->year,l_time->month, + l_time->day),1); + length= (uint) (int10_to_str(weekday, intbuff, 10) - intbuff); + str->append_with_prefill(intbuff, length, 1, '0'); + break; + + default: + str->append(*ptr); + break; + } + } + } + return 0; +} + + +/** + @details + Get a array of positive numbers from a string object. + Each number is separated by 1 non digit character + Return error if there is too many numbers. + If there is too few numbers, assume that the numbers are left out + from the high end. This allows one to give: + DAY_TO_SECOND as "D MM:HH:SS", "MM:HH:SS" "HH:SS" or as seconds. + + @param length: length of str + @param cs: charset of str + @param values: array of results + @param count: count of elements in result array + @param transform_msec: if value is true we suppose + that the last part of string value is microseconds + and we should transform value to six digit value. + For example, '1.1' -> '1.100000' +*/ + +static bool get_interval_info(const char *str,uint length,CHARSET_INFO *cs, + uint count, ulonglong *values, + bool transform_msec) +{ + const char *end=str+length; + uint i; + while (str != end && !my_isdigit(cs,*str)) + str++; + + for (i=0 ; i < count ; i++) + { + longlong value; + const char *start= str; + for (value=0; str != end && my_isdigit(cs,*str) ; str++) + value= value*LL(10) + (longlong) (*str - '0'); + if (transform_msec && i == count - 1) // microseconds always last + { + long msec_length= 6 - (uint) (str - start); + if (msec_length > 0) + value*= (long) log_10_int[msec_length]; + } + values[i]= value; + while (str != end && !my_isdigit(cs,*str)) + str++; + if (str == end && i != count-1) + { + i++; + /* Change values[0...i-1] -> values[0...count-1] */ + bmove_upp((uchar*) (values+count), (uchar*) (values+i), + sizeof(*values)*i); + bzero((uchar*) values, sizeof(*values)*(count-i)); + break; + } + } + return (str != end); +} + + +longlong Item_func_period_add::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulong period=(ulong) args[0]->val_int(); + int months=(int) args[1]->val_int(); + + if ((null_value=args[0]->null_value || args[1]->null_value) || + period == 0L) + return 0; /* purecov: inspected */ + return (longlong) + convert_month_to_period((uint) ((int) convert_period_to_month(period)+ + months)); +} + + +longlong Item_func_period_diff::val_int() +{ + DBUG_ASSERT(fixed == 1); + ulong period1=(ulong) args[0]->val_int(); + ulong period2=(ulong) args[1]->val_int(); + + if ((null_value=args[0]->null_value || args[1]->null_value)) + return 0; /* purecov: inspected */ + return (longlong) ((long) convert_period_to_month(period1)- + (long) convert_period_to_month(period2)); +} + + + +longlong Item_func_to_days::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_arg0_date(<ime, TIME_NO_ZERO_DATE)) + return 0; + return (longlong) calc_daynr(ltime.year,ltime.month,ltime.day); +} + + +/* + Get information about this Item tree monotonicity + + SYNOPSIS + Item_func_to_days::get_monotonicity_info() + + DESCRIPTION + Get information about monotonicity of the function represented by this item + tree. + + RETURN + See enum_monotonicity_info. +*/ + +enum_monotonicity_info Item_func_to_days::get_monotonicity_info() const +{ + if (args[0]->type() == Item::FIELD_ITEM) + { + if (args[0]->field_type() == MYSQL_TYPE_DATE) + return MONOTONIC_STRICT_INCREASING_NOT_NULL; + if (args[0]->field_type() == MYSQL_TYPE_DATETIME) + return MONOTONIC_INCREASING_NOT_NULL; + } + return NON_MONOTONIC; +} + + +longlong Item_func_to_days::val_int_endpoint(bool left_endp, bool *incl_endp) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + longlong res; + int dummy; /* unused */ + if (get_arg0_date(<ime, TIME_FUZZY_DATE)) + { + /* got NULL, leave the incl_endp intact */ + return LONGLONG_MIN; + } + res=(longlong) calc_daynr(ltime.year,ltime.month,ltime.day); + /* Set to NULL if invalid date, but keep the value */ + null_value= check_date(<ime, + (ltime.year || ltime.month || ltime.day), + (TIME_NO_ZERO_IN_DATE | TIME_NO_ZERO_DATE), + &dummy); + if (null_value) + { + /* + Even if the evaluation return NULL, the calc_daynr is useful for pruning + */ + if (args[0]->field_type() != MYSQL_TYPE_DATE) + *incl_endp= TRUE; + return res; + } + + if (args[0]->field_type() == MYSQL_TYPE_DATE) + { + // TO_DAYS() is strictly monotonic for dates, leave incl_endp intact + return res; + } + + /* + Handle the special but practically useful case of datetime values that + point to day bound ("strictly less" comparison stays intact): + + col < '2007-09-15 00:00:00' -> TO_DAYS(col) < TO_DAYS('2007-09-15') + col > '2007-09-15 23:59:59' -> TO_DAYS(col) > TO_DAYS('2007-09-15') + + which is different from the general case ("strictly less" changes to + "less or equal"): + + col < '2007-09-15 12:34:56' -> TO_DAYS(col) <= TO_DAYS('2007-09-15') + */ + if ((!left_endp && !(ltime.hour || ltime.minute || ltime.second || + ltime.second_part)) || + (left_endp && ltime.hour == 23 && ltime.minute == 59 && + ltime.second == 59)) + /* do nothing */ + ; + else + *incl_endp= TRUE; + return res; +} + + +longlong Item_func_dayofyear::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_arg0_date(<ime,TIME_NO_ZERO_DATE)) + return 0; + return (longlong) calc_daynr(ltime.year,ltime.month,ltime.day) - + calc_daynr(ltime.year,1,1) + 1; +} + +longlong Item_func_dayofmonth::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + (void) get_arg0_date(<ime, TIME_FUZZY_DATE); + return (longlong) ltime.day; +} + +longlong Item_func_month::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + (void) get_arg0_date(<ime, TIME_FUZZY_DATE); + return (longlong) ltime.month; +} + + +void Item_func_monthname::fix_length_and_dec() +{ + THD* thd= current_thd; + CHARSET_INFO *cs= thd->variables.collation_connection; + uint32 repertoire= my_charset_repertoire(cs); + locale= thd->variables.lc_time_names; + collation.set(cs, DERIVATION_COERCIBLE, repertoire); + decimals=0; + max_length= locale->max_month_name_length * collation.collation->mbmaxlen; + maybe_null=1; +} + + +String* Item_func_monthname::val_str(String* str) +{ + DBUG_ASSERT(fixed == 1); + const char *month_name; + uint month= (uint) val_int(); + uint err; + + if (null_value || !month) + { + null_value=1; + return (String*) 0; + } + null_value=0; + month_name= locale->month_names->type_names[month-1]; + str->copy(month_name, (uint) strlen(month_name), &my_charset_utf8_bin, + collation.collation, &err); + return str; +} + + +/** + Returns the quarter of the year. +*/ + +longlong Item_func_quarter::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_arg0_date(<ime, TIME_FUZZY_DATE)) + return 0; + return (longlong) ((ltime.month+2)/3); +} + +longlong Item_func_hour::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + (void) get_arg0_time(<ime); + return ltime.hour; +} + +longlong Item_func_minute::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + (void) get_arg0_time(<ime); + return ltime.minute; +} + +/** + Returns the second in time_exp in the range of 0 - 59. +*/ +longlong Item_func_second::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + (void) get_arg0_time(<ime); + return ltime.second; +} + + +uint week_mode(uint mode) +{ + uint week_format= (mode & 7); + if (!(week_format & WEEK_MONDAY_FIRST)) + week_format^= WEEK_FIRST_WEEKDAY; + return week_format; +} + +/** + @verbatim + The bits in week_format(for calc_week() function) has the following meaning: + WEEK_MONDAY_FIRST (0) If not set Sunday is first day of week + If set Monday is first day of week + WEEK_YEAR (1) If not set Week is in range 0-53 + + Week 0 is returned for the the last week of the previous year (for + a date at start of january) In this case one can get 53 for the + first week of next year. This flag ensures that the week is + relevant for the given year. Note that this flag is only + releveant if WEEK_JANUARY is not set. + + If set Week is in range 1-53. + + In this case one may get week 53 for a date in January (when + the week is that last week of previous year) and week 1 for a + date in December. + + WEEK_FIRST_WEEKDAY (2) If not set Weeks are numbered according + to ISO 8601:1988 + If set The week that contains the first + 'first-day-of-week' is week 1. + + ISO 8601:1988 means that if the week containing January 1 has + four or more days in the new year, then it is week 1; + Otherwise it is the last week of the previous year, and the + next week is week 1. + @endverbatim +*/ + +longlong Item_func_week::val_int() +{ + DBUG_ASSERT(fixed == 1); + uint year; + MYSQL_TIME ltime; + if (get_arg0_date(<ime, TIME_NO_ZERO_DATE)) + return 0; + return (longlong) calc_week(<ime, + week_mode((uint) args[1]->val_int()), + &year); +} + + +longlong Item_func_yearweek::val_int() +{ + DBUG_ASSERT(fixed == 1); + uint year,week; + MYSQL_TIME ltime; + if (get_arg0_date(<ime, TIME_NO_ZERO_DATE)) + return 0; + week= calc_week(<ime, + (week_mode((uint) args[1]->val_int()) | WEEK_YEAR), + &year); + return week+year*100; +} + + +longlong Item_func_weekday::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + + if (get_arg0_date(<ime, TIME_NO_ZERO_DATE)) + return 0; + + return (longlong) calc_weekday(calc_daynr(ltime.year, ltime.month, + ltime.day), + odbc_type) + test(odbc_type); +} + +void Item_func_dayname::fix_length_and_dec() +{ + THD* thd= current_thd; + CHARSET_INFO *cs= thd->variables.collation_connection; + uint32 repertoire= my_charset_repertoire(cs); + locale= thd->variables.lc_time_names; + collation.set(cs, DERIVATION_COERCIBLE, repertoire); + decimals=0; + max_length= locale->max_day_name_length * collation.collation->mbmaxlen; + maybe_null=1; +} + + +String* Item_func_dayname::val_str(String* str) +{ + DBUG_ASSERT(fixed == 1); + uint weekday=(uint) val_int(); // Always Item_func_daynr() + const char *day_name; + uint err; + + if (null_value) + return (String*) 0; + + day_name= locale->day_names->type_names[weekday]; + str->copy(day_name, (uint) strlen(day_name), &my_charset_utf8_bin, + collation.collation, &err); + return str; +} + + +longlong Item_func_year::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + (void) get_arg0_date(<ime, TIME_FUZZY_DATE); + return (longlong) ltime.year; +} + + +/* + Get information about this Item tree monotonicity + + SYNOPSIS + Item_func_year::get_monotonicity_info() + + DESCRIPTION + Get information about monotonicity of the function represented by this item + tree. + + RETURN + See enum_monotonicity_info. +*/ + +enum_monotonicity_info Item_func_year::get_monotonicity_info() const +{ + if (args[0]->type() == Item::FIELD_ITEM && + (args[0]->field_type() == MYSQL_TYPE_DATE || + args[0]->field_type() == MYSQL_TYPE_DATETIME)) + return MONOTONIC_INCREASING; + return NON_MONOTONIC; +} + + +longlong Item_func_year::val_int_endpoint(bool left_endp, bool *incl_endp) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_arg0_date(<ime, TIME_FUZZY_DATE)) + { + /* got NULL, leave the incl_endp intact */ + return LONGLONG_MIN; + } + + /* + Handle the special but practically useful case of datetime values that + point to year bound ("strictly less" comparison stays intact) : + + col < '2007-01-01 00:00:00' -> YEAR(col) < 2007 + + which is different from the general case ("strictly less" changes to + "less or equal"): + + col < '2007-09-15 23:00:00' -> YEAR(col) <= 2007 + */ + if (!left_endp && ltime.day == 1 && ltime.month == 1 && + !(ltime.hour || ltime.minute || ltime.second || ltime.second_part)) + ; /* do nothing */ + else + *incl_endp= TRUE; + return ltime.year; +} + + +longlong Item_func_unix_timestamp::val_int() +{ + MYSQL_TIME ltime; + my_bool not_used; + + DBUG_ASSERT(fixed == 1); + if (arg_count == 0) + return (longlong) current_thd->query_start(); + if (args[0]->type() == FIELD_ITEM) + { // Optimize timestamp field + Field *field=((Item_field*) args[0])->field; + if (field->type() == MYSQL_TYPE_TIMESTAMP) + return ((Field_timestamp*) field)->get_timestamp(&null_value); + } + + if (get_arg0_date(<ime, 0)) + { + /* + We have to set null_value again because get_arg0_date will also set it + to true if we have wrong datetime parameter (and we should return 0 in + this case). + */ + null_value= args[0]->null_value; + return 0; + } + + return (longlong) TIME_to_timestamp(current_thd, <ime, ¬_used); +} + + +longlong Item_func_time_to_sec::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + longlong seconds; + (void) get_arg0_time(<ime); + seconds=ltime.hour*3600L+ltime.minute*60+ltime.second; + return ltime.neg ? -seconds : seconds; +} + + +/** + Convert a string to a interval value. + + To make code easy, allow interval objects without separators. +*/ + +bool get_interval_value(Item *args,interval_type int_type, + String *str_value, INTERVAL *interval) +{ + ulonglong array[5]; + longlong value; + const char *str; + size_t length; + CHARSET_INFO *cs=str_value->charset(); + + LINT_INIT(value); + LINT_INIT(str); + LINT_INIT(length); + + bzero((char*) interval,sizeof(*interval)); + if ((int) int_type <= INTERVAL_MICROSECOND) + { + value= args->val_int(); + if (args->null_value) + return 1; + if (value < 0) + { + interval->neg=1; + value= -value; + } + } + else + { + String *res; + if (!(res=args->val_str(str_value))) + return (1); + + /* record negative intervalls in interval->neg */ + str=res->ptr(); + const char *end=str+res->length(); + while (str != end && my_isspace(cs,*str)) + str++; + if (str != end && *str == '-') + { + interval->neg=1; + str++; + } + length= (size_t) (end-str); // Set up pointers to new str + } + + switch (int_type) { + case INTERVAL_YEAR: + interval->year= (ulong) value; + break; + case INTERVAL_QUARTER: + interval->month= (ulong)(value*3); + break; + case INTERVAL_MONTH: + interval->month= (ulong) value; + break; + case INTERVAL_WEEK: + interval->day= (ulong)(value*7); + break; + case INTERVAL_DAY: + interval->day= (ulong) value; + break; + case INTERVAL_HOUR: + interval->hour= (ulong) value; + break; + case INTERVAL_MICROSECOND: + interval->second_part=value; + break; + case INTERVAL_MINUTE: + interval->minute=value; + break; + case INTERVAL_SECOND: + interval->second=value; + break; + case INTERVAL_YEAR_MONTH: // Allow YEAR-MONTH YYYYYMM + if (get_interval_info(str,length,cs,2,array,0)) + return (1); + interval->year= (ulong) array[0]; + interval->month= (ulong) array[1]; + break; + case INTERVAL_DAY_HOUR: + if (get_interval_info(str,length,cs,2,array,0)) + return (1); + interval->day= (ulong) array[0]; + interval->hour= (ulong) array[1]; + break; + case INTERVAL_DAY_MICROSECOND: + if (get_interval_info(str,length,cs,5,array,1)) + return (1); + interval->day= (ulong) array[0]; + interval->hour= (ulong) array[1]; + interval->minute= array[2]; + interval->second= array[3]; + interval->second_part= array[4]; + break; + case INTERVAL_DAY_MINUTE: + if (get_interval_info(str,length,cs,3,array,0)) + return (1); + interval->day= (ulong) array[0]; + interval->hour= (ulong) array[1]; + interval->minute= array[2]; + break; + case INTERVAL_DAY_SECOND: + if (get_interval_info(str,length,cs,4,array,0)) + return (1); + interval->day= (ulong) array[0]; + interval->hour= (ulong) array[1]; + interval->minute= array[2]; + interval->second= array[3]; + break; + case INTERVAL_HOUR_MICROSECOND: + if (get_interval_info(str,length,cs,4,array,1)) + return (1); + interval->hour= (ulong) array[0]; + interval->minute= array[1]; + interval->second= array[2]; + interval->second_part= array[3]; + break; + case INTERVAL_HOUR_MINUTE: + if (get_interval_info(str,length,cs,2,array,0)) + return (1); + interval->hour= (ulong) array[0]; + interval->minute= array[1]; + break; + case INTERVAL_HOUR_SECOND: + if (get_interval_info(str,length,cs,3,array,0)) + return (1); + interval->hour= (ulong) array[0]; + interval->minute= array[1]; + interval->second= array[2]; + break; + case INTERVAL_MINUTE_MICROSECOND: + if (get_interval_info(str,length,cs,3,array,1)) + return (1); + interval->minute= array[0]; + interval->second= array[1]; + interval->second_part= array[2]; + break; + case INTERVAL_MINUTE_SECOND: + if (get_interval_info(str,length,cs,2,array,0)) + return (1); + interval->minute= array[0]; + interval->second= array[1]; + break; + case INTERVAL_SECOND_MICROSECOND: + if (get_interval_info(str,length,cs,2,array,1)) + return (1); + interval->second= array[0]; + interval->second_part= array[1]; + break; + case INTERVAL_LAST: /* purecov: begin deadcode */ + DBUG_ASSERT(0); + break; /* purecov: end */ + } + return 0; +} + + +String *Item_date::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_date(<ime, TIME_FUZZY_DATE)) + return (String *) 0; + if (str->alloc(MAX_DATE_STRING_REP_LENGTH)) + { + null_value= 1; + return (String *) 0; + } + make_date((DATE_TIME_FORMAT *) 0, <ime, str); + return str; +} + + +longlong Item_date::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_date(<ime, TIME_FUZZY_DATE)) + return 0; + return (longlong) (ltime.year*10000L+ltime.month*100+ltime.day); +} + + +bool Item_func_from_days::get_date(MYSQL_TIME *ltime, uint fuzzy_date) +{ + longlong value=args[0]->val_int(); + if ((null_value=args[0]->null_value)) + return 1; + bzero(ltime, sizeof(MYSQL_TIME)); + get_date_from_daynr((long) value, <ime->year, <ime->month, <ime->day); + ltime->time_type= MYSQL_TIMESTAMP_DATE; + return 0; +} + + +void Item_func_curdate::fix_length_and_dec() +{ + collation.set(&my_charset_bin); + decimals=0; + max_length=MAX_DATE_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + + store_now_in_TIME(<ime); + + /* We don't need to set second_part and neg because they already 0 */ + ltime.hour= ltime.minute= ltime.second= 0; + ltime.time_type= MYSQL_TIMESTAMP_DATE; + value= (longlong) TIME_to_ulonglong_date(<ime); +} + +String *Item_func_curdate::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + if (str->alloc(MAX_DATE_STRING_REP_LENGTH)) + { + null_value= 1; + return (String *) 0; + } + make_date((DATE_TIME_FORMAT *) 0, <ime, str); + return str; +} + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for local + time zone. Defines time zone (local) used for whole CURDATE function. +*/ +void Item_func_curdate_local::store_now_in_TIME(MYSQL_TIME *now_time) +{ + THD *thd= current_thd; + thd->variables.time_zone->gmt_sec_to_TIME(now_time, + (my_time_t)thd->query_start()); + thd->time_zone_used= 1; +} + + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for UTC + time zone. Defines time zone (UTC) used for whole UTC_DATE function. +*/ +void Item_func_curdate_utc::store_now_in_TIME(MYSQL_TIME *now_time) +{ + my_tz_UTC->gmt_sec_to_TIME(now_time, + (my_time_t)(current_thd->query_start())); + /* + We are not flagging this query as using time zone, since it uses fixed + UTC-SYSTEM time-zone. + */ +} + + +bool Item_func_curdate::get_date(MYSQL_TIME *res, + uint fuzzy_date __attribute__((unused))) +{ + *res=ltime; + return 0; +} + + +String *Item_func_curtime::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + str_value.set(buff, buff_length, &my_charset_bin); + return &str_value; +} + + +void Item_func_curtime::fix_length_and_dec() +{ + MYSQL_TIME ltime; + + decimals= DATETIME_DEC; + collation.set(&my_charset_bin); + store_now_in_TIME(<ime); + value= TIME_to_ulonglong_time(<ime); + buff_length= (uint) my_time_to_str(<ime, buff); + max_length= buff_length; +} + + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for local + time zone. Defines time zone (local) used for whole CURTIME function. +*/ +void Item_func_curtime_local::store_now_in_TIME(MYSQL_TIME *now_time) +{ + THD *thd= current_thd; + thd->variables.time_zone->gmt_sec_to_TIME(now_time, + (my_time_t)thd->query_start()); + thd->time_zone_used= 1; +} + + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for UTC + time zone. Defines time zone (UTC) used for whole UTC_TIME function. +*/ +void Item_func_curtime_utc::store_now_in_TIME(MYSQL_TIME *now_time) +{ + my_tz_UTC->gmt_sec_to_TIME(now_time, + (my_time_t)(current_thd->query_start())); + /* + We are not flagging this query as using time zone, since it uses fixed + UTC-SYSTEM time-zone. + */ +} + + +String *Item_func_now::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + str_value.set(buff,buff_length, &my_charset_bin); + return &str_value; +} + + +void Item_func_now::fix_length_and_dec() +{ + decimals= DATETIME_DEC; + collation.set(&my_charset_bin); + + store_now_in_TIME(<ime); + value= (longlong) TIME_to_ulonglong_datetime(<ime); + + buff_length= (uint) my_datetime_to_str(<ime, buff); + max_length= buff_length; +} + + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for local + time zone. Defines time zone (local) used for whole NOW function. +*/ +void Item_func_now_local::store_now_in_TIME(MYSQL_TIME *now_time) +{ + THD *thd= current_thd; + thd->variables.time_zone->gmt_sec_to_TIME(now_time, + (my_time_t)thd->query_start()); + thd->time_zone_used= 1; +} + + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for UTC + time zone. Defines time zone (UTC) used for whole UTC_TIMESTAMP function. +*/ +void Item_func_now_utc::store_now_in_TIME(MYSQL_TIME *now_time) +{ + my_tz_UTC->gmt_sec_to_TIME(now_time, + (my_time_t)(current_thd->query_start())); + /* + We are not flagging this query as using time zone, since it uses fixed + UTC-SYSTEM time-zone. + */ +} + + +bool Item_func_now::get_date(MYSQL_TIME *res, + uint fuzzy_date __attribute__((unused))) +{ + *res= ltime; + return 0; +} + + +int Item_func_now::save_in_field(Field *to, bool no_conversions) +{ + to->set_notnull(); + return to->store_time(<ime, MYSQL_TIMESTAMP_DATETIME); +} + + +/** + Converts current time in my_time_t to MYSQL_TIME represenatation for local + time zone. Defines time zone (local) used for whole SYSDATE function. +*/ +void Item_func_sysdate_local::store_now_in_TIME(MYSQL_TIME *now_time) +{ + THD *thd= current_thd; + thd->variables.time_zone->gmt_sec_to_TIME(now_time, (my_time_t) my_time(0)); + thd->time_zone_used= 1; +} + + +String *Item_func_sysdate_local::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + store_now_in_TIME(<ime); + buff_length= (uint) my_datetime_to_str(<ime, buff); + str_value.set(buff, buff_length, &my_charset_bin); + return &str_value; +} + + +longlong Item_func_sysdate_local::val_int() +{ + DBUG_ASSERT(fixed == 1); + store_now_in_TIME(<ime); + return (longlong) TIME_to_ulonglong_datetime(<ime); +} + + +double Item_func_sysdate_local::val_real() +{ + DBUG_ASSERT(fixed == 1); + store_now_in_TIME(<ime); + return ulonglong2double(TIME_to_ulonglong_datetime(<ime)); +} + + +void Item_func_sysdate_local::fix_length_and_dec() +{ + decimals= 0; + collation.set(&my_charset_bin); + max_length= MAX_DATETIME_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; +} + + +bool Item_func_sysdate_local::get_date(MYSQL_TIME *res, + uint fuzzy_date __attribute__((unused))) +{ + store_now_in_TIME(<ime); + *res= ltime; + return 0; +} + + +int Item_func_sysdate_local::save_in_field(Field *to, bool no_conversions) +{ + store_now_in_TIME(<ime); + to->set_notnull(); + to->store_time(<ime, MYSQL_TIMESTAMP_DATETIME); + return 0; +} + + +String *Item_func_sec_to_time::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + longlong arg_val= args[0]->val_int(); + + if ((null_value=args[0]->null_value) || + str->alloc(MAX_DATE_STRING_REP_LENGTH)) + { + null_value= 1; + return (String*) 0; + } + + sec_to_time(arg_val, args[0]->unsigned_flag, <ime); + + make_time((DATE_TIME_FORMAT *) 0, <ime, str); + return str; +} + + +longlong Item_func_sec_to_time::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + longlong arg_val= args[0]->val_int(); + + if ((null_value=args[0]->null_value)) + return 0; + + sec_to_time(arg_val, args[0]->unsigned_flag, <ime); + + return (ltime.neg ? -1 : 1) * + ((ltime.hour)*10000 + ltime.minute*100 + ltime.second); +} + + +void Item_func_date_format::fix_length_and_dec() +{ + THD* thd= current_thd; + /* + Must use this_item() in case it's a local SP variable + (for ->max_length and ->str_value) + */ + Item *arg1= args[1]->this_item(); + + decimals=0; + CHARSET_INFO *cs= thd->variables.collation_connection; + uint32 repertoire= arg1->collation.repertoire; + if (!thd->variables.lc_time_names->is_ascii) + repertoire|= MY_REPERTOIRE_EXTENDED; + collation.set(cs, arg1->collation.derivation, repertoire); + if (arg1->type() == STRING_ITEM) + { // Optimize the normal case + fixed_length=1; + max_length= format_length(&arg1->str_value) * + collation.collation->mbmaxlen; + } + else + { + fixed_length=0; + max_length=min(arg1->max_length, MAX_BLOB_WIDTH) * 10 * + collation.collation->mbmaxlen; + set_if_smaller(max_length,MAX_BLOB_WIDTH); + } + maybe_null=1; // If wrong date +} + + +bool Item_func_date_format::eq(const Item *item, bool binary_cmp) const +{ + Item_func_date_format *item_func; + + if (item->type() != FUNC_ITEM) + return 0; + if (func_name() != ((Item_func*) item)->func_name()) + return 0; + if (this == item) + return 1; + item_func= (Item_func_date_format*) item; + if (!args[0]->eq(item_func->args[0], binary_cmp)) + return 0; + /* + We must compare format string case sensitive. + This needed because format modifiers with different case, + for example %m and %M, have different meaning. + */ + if (!args[1]->eq(item_func->args[1], 1)) + return 0; + return 1; +} + + + +uint Item_func_date_format::format_length(const String *format) +{ + uint size=0; + const char *ptr=format->ptr(); + const char *end=ptr+format->length(); + + for (; ptr != end ; ptr++) + { + if (*ptr != '%' || ptr == end-1) + size++; + else + { + switch(*++ptr) { + case 'M': /* month, textual */ + case 'W': /* day (of the week), textual */ + size += 64; /* large for UTF8 locale data */ + break; + case 'D': /* day (of the month), numeric plus english suffix */ + case 'Y': /* year, numeric, 4 digits */ + case 'x': /* Year, used with 'v' */ + case 'X': /* Year, used with 'v, where week starts with Monday' */ + size += 4; + break; + case 'a': /* locale's abbreviated weekday name (Sun..Sat) */ + case 'b': /* locale's abbreviated month name (Jan.Dec) */ + size += 32; /* large for UTF8 locale data */ + break; + case 'j': /* day of year (001..366) */ + size += 3; + break; + case 'U': /* week (00..52) */ + case 'u': /* week (00..52), where week starts with Monday */ + case 'V': /* week 1..53 used with 'x' */ + case 'v': /* week 1..53 used with 'x', where week starts with Monday */ + case 'y': /* year, numeric, 2 digits */ + case 'm': /* month, numeric */ + case 'd': /* day (of the month), numeric */ + case 'h': /* hour (01..12) */ + case 'I': /* --||-- */ + case 'i': /* minutes, numeric */ + case 'l': /* hour ( 1..12) */ + case 'p': /* locale's AM or PM */ + case 'S': /* second (00..61) */ + case 's': /* seconds, numeric */ + case 'c': /* month (0..12) */ + case 'e': /* day (0..31) */ + size += 2; + break; + case 'k': /* hour ( 0..23) */ + case 'H': /* hour (00..23; value > 23 OK, padding always 2-digit) */ + size += 7; /* docs allow > 23, range depends on sizeof(unsigned int) */ + break; + case 'r': /* time, 12-hour (hh:mm:ss [AP]M) */ + size += 11; + break; + case 'T': /* time, 24-hour (hh:mm:ss) */ + size += 8; + break; + case 'f': /* microseconds */ + size += 6; + break; + case 'w': /* day (of the week), numeric */ + case '%': + default: + size++; + break; + } + } + } + return size; +} + + +String *Item_func_date_format::val_str(String *str) +{ + String *format; + MYSQL_TIME l_time; + uint size; + DBUG_ASSERT(fixed == 1); + + if (!is_time_format) + { + if (get_arg0_date(&l_time, TIME_FUZZY_DATE)) + return 0; + } + else + { + String *res; + if (!(res=args[0]->val_str(str)) || + (str_to_time_with_warn(res->ptr(), res->length(), &l_time))) + goto null_date; + + l_time.year=l_time.month=l_time.day=0; + null_value=0; + } + + if (!(format = args[1]->val_str(str)) || !format->length()) + goto null_date; + + if (fixed_length) + size=max_length; + else + size=format_length(format); + + if (size < MAX_DATE_STRING_REP_LENGTH) + size= MAX_DATE_STRING_REP_LENGTH; + + if (format == str) + str= &value; // Save result here + if (str->alloc(size)) + goto null_date; + + DATE_TIME_FORMAT date_time_format; + date_time_format.format.str= (char*) format->ptr(); + date_time_format.format.length= format->length(); + + /* Create the result string */ + str->set_charset(collation.collation); + if (!make_date_time(&date_time_format, &l_time, + is_time_format ? MYSQL_TIMESTAMP_TIME : + MYSQL_TIMESTAMP_DATE, + str)) + return str; + +null_date: + null_value=1; + return 0; +} + + +void Item_func_from_unixtime::fix_length_and_dec() +{ + thd= current_thd; + collation.set(&my_charset_bin); + decimals= DATETIME_DEC; + max_length=MAX_DATETIME_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null= 1; + thd->time_zone_used= 1; +} + + +String *Item_func_from_unixtime::val_str(String *str) +{ + MYSQL_TIME time_tmp; + + DBUG_ASSERT(fixed == 1); + + if (get_date(&time_tmp, 0)) + return 0; + + if (str->alloc(MAX_DATE_STRING_REP_LENGTH)) + { + null_value= 1; + return 0; + } + + make_datetime((DATE_TIME_FORMAT *) 0, &time_tmp, str); + + return str; +} + + +longlong Item_func_from_unixtime::val_int() +{ + MYSQL_TIME time_tmp; + + DBUG_ASSERT(fixed == 1); + + if (get_date(&time_tmp, 0)) + return 0; + + return (longlong) TIME_to_ulonglong_datetime(&time_tmp); +} + +bool Item_func_from_unixtime::get_date(MYSQL_TIME *ltime, + uint fuzzy_date __attribute__((unused))) +{ + ulonglong tmp= (ulonglong)(args[0]->val_int()); + /* + "tmp > TIMESTAMP_MAX_VALUE" check also covers case of negative + from_unixtime() argument since tmp is unsigned. + */ + if ((null_value= (args[0]->null_value || tmp > TIMESTAMP_MAX_VALUE))) + return 1; + + thd->variables.time_zone->gmt_sec_to_TIME(ltime, (my_time_t)tmp); + + return 0; +} + + +void Item_func_convert_tz::fix_length_and_dec() +{ + collation.set(&my_charset_bin); + decimals= 0; + max_length= MAX_DATETIME_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null= 1; +} + + +String *Item_func_convert_tz::val_str(String *str) +{ + MYSQL_TIME time_tmp; + + if (get_date(&time_tmp, 0)) + return 0; + + if (str->alloc(MAX_DATE_STRING_REP_LENGTH)) + { + null_value= 1; + return 0; + } + + make_datetime((DATE_TIME_FORMAT *) 0, &time_tmp, str); + + return str; +} + + +longlong Item_func_convert_tz::val_int() +{ + MYSQL_TIME time_tmp; + + if (get_date(&time_tmp, 0)) + return 0; + + return (longlong)TIME_to_ulonglong_datetime(&time_tmp); +} + + +bool Item_func_convert_tz::get_date(MYSQL_TIME *ltime, + uint fuzzy_date __attribute__((unused))) +{ + my_time_t my_time_tmp; + String str; + THD *thd= current_thd; + + if (!from_tz_cached) + { + from_tz= my_tz_find(thd, args[1]->val_str(&str)); + from_tz_cached= args[1]->const_item(); + } + + if (!to_tz_cached) + { + to_tz= my_tz_find(thd, args[2]->val_str(&str)); + to_tz_cached= args[2]->const_item(); + } + + if (from_tz==0 || to_tz==0 || get_arg0_date(ltime, TIME_NO_ZERO_DATE)) + { + null_value= 1; + return 1; + } + + { + my_bool not_used; + my_time_tmp= from_tz->TIME_to_gmt_sec(ltime, ¬_used); + /* my_time_tmp is guranteed to be in the allowed range */ + if (my_time_tmp) + to_tz->gmt_sec_to_TIME(ltime, my_time_tmp); + } + + null_value= 0; + return 0; +} + + +void Item_func_convert_tz::cleanup() +{ + from_tz_cached= to_tz_cached= 0; + Item_date_func::cleanup(); +} + + +void Item_date_add_interval::fix_length_and_dec() +{ + enum_field_types arg0_field_type; + + collation.set(&my_charset_bin); + maybe_null=1; + max_length=MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + value.alloc(max_length); + + /* + The field type for the result of an Item_date function is defined as + follows: + + - If first arg is a MYSQL_TYPE_DATETIME result is MYSQL_TYPE_DATETIME + - If first arg is a MYSQL_TYPE_DATE and the interval type uses hours, + minutes or seconds then type is MYSQL_TYPE_DATETIME. + - Otherwise the result is MYSQL_TYPE_STRING + (This is because you can't know if the string contains a DATE, MYSQL_TIME or + DATETIME argument) + */ + cached_field_type= MYSQL_TYPE_STRING; + arg0_field_type= args[0]->field_type(); + if (arg0_field_type == MYSQL_TYPE_DATETIME || + arg0_field_type == MYSQL_TYPE_TIMESTAMP) + cached_field_type= MYSQL_TYPE_DATETIME; + else if (arg0_field_type == MYSQL_TYPE_DATE) + { + if (int_type <= INTERVAL_DAY || int_type == INTERVAL_YEAR_MONTH) + cached_field_type= arg0_field_type; + else + cached_field_type= MYSQL_TYPE_DATETIME; + } +} + + +/* Here arg[1] is a Item_interval object */ + +bool Item_date_add_interval::get_date(MYSQL_TIME *ltime, uint fuzzy_date) +{ + INTERVAL interval; + + if (args[0]->get_date(ltime, TIME_NO_ZERO_DATE) || + get_interval_value(args[1], int_type, &value, &interval)) + return (null_value=1); + + if (date_sub_interval) + interval.neg = !interval.neg; + + if ((null_value= date_add_interval(ltime, int_type, interval))) + return 1; + return 0; +} + + +String *Item_date_add_interval::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + enum date_time_format_types format; + + if (Item_date_add_interval::get_date(<ime, TIME_NO_ZERO_DATE)) + return 0; + + if (ltime.time_type == MYSQL_TIMESTAMP_DATE) + format= DATE_ONLY; + else if (ltime.second_part) + format= DATE_TIME_MICROSECOND; + else + format= DATE_TIME; + + if (!make_datetime(format, <ime, str)) + return str; + + null_value=1; + return 0; +} + + +longlong Item_date_add_interval::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + longlong date; + if (Item_date_add_interval::get_date(<ime, TIME_NO_ZERO_DATE)) + return (longlong) 0; + date = (ltime.year*100L + ltime.month)*100L + ltime.day; + return ltime.time_type == MYSQL_TIMESTAMP_DATE ? date : + ((date*100L + ltime.hour)*100L+ ltime.minute)*100L + ltime.second; +} + + + +bool Item_date_add_interval::eq(const Item *item, bool binary_cmp) const +{ + Item_date_add_interval *other= (Item_date_add_interval*) item; + if (!Item_func::eq(item, binary_cmp)) + return 0; + return ((int_type == other->int_type) && + (date_sub_interval == other->date_sub_interval)); +} + +/* + 'interval_names' reflects the order of the enumeration interval_type. + See item_timefunc.h + */ + +static const char *interval_names[]= +{ + "year", "quarter", "month", "week", "day", + "hour", "minute", "second", "microsecond", + "year_month", "day_hour", "day_minute", + "day_second", "hour_minute", "hour_second", + "minute_second", "day_microsecond", + "hour_microsecond", "minute_microsecond", + "second_microsecond" +}; + +void Item_date_add_interval::print(String *str, enum_query_type query_type) +{ + str->append('('); + args[0]->print(str, query_type); + str->append(date_sub_interval?" - interval ":" + interval "); + args[1]->print(str, query_type); + str->append(' '); + str->append(interval_names[int_type]); + str->append(')'); +} + +void Item_extract::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("extract(")); + str->append(interval_names[int_type]); + str->append(STRING_WITH_LEN(" from ")); + args[0]->print(str, query_type); + str->append(')'); +} + +void Item_extract::fix_length_and_dec() +{ + value.alloc(32); // alloc buffer + + maybe_null=1; // If wrong date + switch (int_type) { + case INTERVAL_YEAR: max_length=4; date_value=1; break; + case INTERVAL_YEAR_MONTH: max_length=6; date_value=1; break; + case INTERVAL_QUARTER: max_length=2; date_value=1; break; + case INTERVAL_MONTH: max_length=2; date_value=1; break; + case INTERVAL_WEEK: max_length=2; date_value=1; break; + case INTERVAL_DAY: max_length=2; date_value=1; break; + case INTERVAL_DAY_HOUR: max_length=9; date_value=0; break; + case INTERVAL_DAY_MINUTE: max_length=11; date_value=0; break; + case INTERVAL_DAY_SECOND: max_length=13; date_value=0; break; + case INTERVAL_HOUR: max_length=2; date_value=0; break; + case INTERVAL_HOUR_MINUTE: max_length=4; date_value=0; break; + case INTERVAL_HOUR_SECOND: max_length=6; date_value=0; break; + case INTERVAL_MINUTE: max_length=2; date_value=0; break; + case INTERVAL_MINUTE_SECOND: max_length=4; date_value=0; break; + case INTERVAL_SECOND: max_length=2; date_value=0; break; + case INTERVAL_MICROSECOND: max_length=2; date_value=0; break; + case INTERVAL_DAY_MICROSECOND: max_length=20; date_value=0; break; + case INTERVAL_HOUR_MICROSECOND: max_length=13; date_value=0; break; + case INTERVAL_MINUTE_MICROSECOND: max_length=11; date_value=0; break; + case INTERVAL_SECOND_MICROSECOND: max_length=9; date_value=0; break; + case INTERVAL_LAST: DBUG_ASSERT(0); break; /* purecov: deadcode */ + } +} + + +longlong Item_extract::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + uint year; + ulong week_format; + long neg; + if (date_value) + { + if (get_arg0_date(<ime, TIME_FUZZY_DATE)) + return 0; + neg=1; + } + else + { + String *res= args[0]->val_str(&value); + if (!res || str_to_time_with_warn(res->ptr(), res->length(), <ime)) + { + null_value=1; + return 0; + } + neg= ltime.neg ? -1 : 1; + null_value=0; + } + switch (int_type) { + case INTERVAL_YEAR: return ltime.year; + case INTERVAL_YEAR_MONTH: return ltime.year*100L+ltime.month; + case INTERVAL_QUARTER: return (ltime.month+2)/3; + case INTERVAL_MONTH: return ltime.month; + case INTERVAL_WEEK: + { + week_format= current_thd->variables.default_week_format; + return calc_week(<ime, week_mode(week_format), &year); + } + case INTERVAL_DAY: return ltime.day; + case INTERVAL_DAY_HOUR: return (long) (ltime.day*100L+ltime.hour)*neg; + case INTERVAL_DAY_MINUTE: return (long) (ltime.day*10000L+ + ltime.hour*100L+ + ltime.minute)*neg; + case INTERVAL_DAY_SECOND: return ((longlong) ltime.day*1000000L+ + (longlong) (ltime.hour*10000L+ + ltime.minute*100+ + ltime.second))*neg; + case INTERVAL_HOUR: return (long) ltime.hour*neg; + case INTERVAL_HOUR_MINUTE: return (long) (ltime.hour*100+ltime.minute)*neg; + case INTERVAL_HOUR_SECOND: return (long) (ltime.hour*10000+ltime.minute*100+ + ltime.second)*neg; + case INTERVAL_MINUTE: return (long) ltime.minute*neg; + case INTERVAL_MINUTE_SECOND: return (long) (ltime.minute*100+ltime.second)*neg; + case INTERVAL_SECOND: return (long) ltime.second*neg; + case INTERVAL_MICROSECOND: return (long) ltime.second_part*neg; + case INTERVAL_DAY_MICROSECOND: return (((longlong)ltime.day*1000000L + + (longlong)ltime.hour*10000L + + ltime.minute*100 + + ltime.second)*1000000L + + ltime.second_part)*neg; + case INTERVAL_HOUR_MICROSECOND: return (((longlong)ltime.hour*10000L + + ltime.minute*100 + + ltime.second)*1000000L + + ltime.second_part)*neg; + case INTERVAL_MINUTE_MICROSECOND: return (((longlong)(ltime.minute*100+ + ltime.second))*1000000L+ + ltime.second_part)*neg; + case INTERVAL_SECOND_MICROSECOND: return ((longlong)ltime.second*1000000L+ + ltime.second_part)*neg; + case INTERVAL_LAST: DBUG_ASSERT(0); break; /* purecov: deadcode */ + } + return 0; // Impossible +} + +bool Item_extract::eq(const Item *item, bool binary_cmp) const +{ + if (this == item) + return 1; + if (item->type() != FUNC_ITEM || + functype() != ((Item_func*)item)->functype()) + return 0; + + Item_extract* ie= (Item_extract*)item; + if (ie->int_type != int_type) + return 0; + + if (!args[0]->eq(ie->args[0], binary_cmp)) + return 0; + return 1; +} + + +bool Item_char_typecast::eq(const Item *item, bool binary_cmp) const +{ + if (this == item) + return 1; + if (item->type() != FUNC_ITEM || + functype() != ((Item_func*)item)->functype()) + return 0; + + Item_char_typecast *cast= (Item_char_typecast*)item; + if (cast_length != cast->cast_length || + cast_cs != cast->cast_cs) + return 0; + + if (!args[0]->eq(cast->args[0], binary_cmp)) + return 0; + return 1; +} + +void Item_typecast::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("cast(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" as ")); + str->append(cast_type()); + str->append(')'); +} + + +void Item_char_typecast::print(String *str, enum_query_type query_type) +{ + str->append(STRING_WITH_LEN("cast(")); + args[0]->print(str, query_type); + str->append(STRING_WITH_LEN(" as char")); + if (cast_length >= 0) + { + str->append('('); + char buffer[20]; + // my_charset_bin is good enough for numbers + String st(buffer, sizeof(buffer), &my_charset_bin); + st.set((ulonglong)cast_length, &my_charset_bin); + str->append(st); + str->append(')'); + } + if (cast_cs) + { + str->append(STRING_WITH_LEN(" charset ")); + str->append(cast_cs->csname); + } + str->append(')'); +} + +String *Item_char_typecast::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + String *res; + uint32 length; + + if (!charset_conversion) + { + if (!(res= args[0]->val_str(str))) + { + null_value= 1; + return 0; + } + } + else + { + // Convert character set if differ + uint dummy_errors; + if (!(res= args[0]->val_str(&tmp_value)) || + str->copy(res->ptr(), res->length(), from_cs, + cast_cs, &dummy_errors)) + { + null_value= 1; + return 0; + } + res= str; + } + + res->set_charset(cast_cs); + + /* + Cut the tail if cast with length + and the result is longer than cast length, e.g. + CAST('string' AS CHAR(1)) + */ + if (cast_length >= 0) + { + if (res->length() > (length= (uint32) res->charpos(cast_length))) + { // Safe even if const arg + char char_type[40]; + my_snprintf(char_type, sizeof(char_type), "%s(%lu)", + cast_cs == &my_charset_bin ? "BINARY" : "CHAR", + (ulong) length); + + if (!res->alloced_length()) + { // Don't change const str + str_value= *res; // Not malloced string + res= &str_value; + } + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE, + ER(ER_TRUNCATED_WRONG_VALUE), char_type, + res->c_ptr_safe()); + res->length((uint) length); + } + else if (cast_cs == &my_charset_bin && res->length() < (uint) cast_length) + { + if (res->alloced_length() < (uint) cast_length) + { + str->alloc(cast_length); + str->copy(*res); + res= str; + } + bzero((char*) res->ptr() + res->length(), + (uint) cast_length - res->length()); + res->length(cast_length); + } + } + null_value= 0; + return res; +} + + +void Item_char_typecast::fix_length_and_dec() +{ + uint32 char_length; + /* + We always force character set conversion if cast_cs + is a multi-byte character set. It garantees that the + result of CAST is a well-formed string. + For single-byte character sets we allow just to copy + from the argument. A single-byte character sets string + is always well-formed. + + There is a special trick to convert form a number to ucs2. + As numbers have my_charset_bin as their character set, + it wouldn't do conversion to ucs2 without an additional action. + To force conversion, we should pretend to be non-binary. + Let's choose from_cs this way: + - If the argument in a number and cast_cs is ucs2 (i.e. mbminlen > 1), + then from_cs is set to latin1, to perform latin1 -> ucs2 conversion. + - If the argument is a number and cast_cs is ASCII-compatible + (i.e. mbminlen == 1), then from_cs is set to cast_cs, + which allows just to take over the args[0]->val_str() result + and thus avoid unnecessary character set conversion. + - If the argument is not a number, then from_cs is set to + the argument's charset. + + Note (TODO): we could use repertoire technique here. + */ + from_cs= (args[0]->result_type() == INT_RESULT || + args[0]->result_type() == DECIMAL_RESULT || + args[0]->result_type() == REAL_RESULT) ? + (cast_cs->mbminlen == 1 ? cast_cs : &my_charset_latin1) : + args[0]->collation.collation; + charset_conversion= (cast_cs->mbmaxlen > 1) || + (!my_charset_same(from_cs, cast_cs) && + from_cs != &my_charset_bin && + cast_cs != &my_charset_bin); + collation.set(cast_cs, DERIVATION_IMPLICIT); + char_length= (cast_length >= 0) ? + cast_length : + args[0]->max_length / args[0]->collation.collation->mbmaxlen; + max_length= char_length * cast_cs->mbmaxlen; +} + + +String *Item_datetime_typecast::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + + if (!get_arg0_date(<ime, TIME_FUZZY_DATE) && + !make_datetime(ltime.second_part ? DATE_TIME_MICROSECOND : DATE_TIME, + <ime, str)) + return str; + + null_value=1; + return 0; +} + + +longlong Item_datetime_typecast::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (get_arg0_date(<ime,1)) + { + null_value= 1; + return 0; + } + + return TIME_to_ulonglong_datetime(<ime); +} + + +bool Item_time_typecast::get_time(MYSQL_TIME *ltime) +{ + bool res= get_arg0_time(ltime); + /* + For MYSQL_TIMESTAMP_TIME value we can have non-zero day part, + which we should not lose. + */ + if (ltime->time_type == MYSQL_TIMESTAMP_DATETIME) + ltime->year= ltime->month= ltime->day= 0; + ltime->time_type= MYSQL_TIMESTAMP_TIME; + return res; +} + + +longlong Item_time_typecast::val_int() +{ + MYSQL_TIME ltime; + if (get_time(<ime)) + { + null_value= 1; + return 0; + } + return ltime.hour * 10000L + ltime.minute * 100 + ltime.second; +} + +String *Item_time_typecast::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + + if (!get_arg0_time(<ime) && + !make_datetime(ltime.second_part ? TIME_MICROSECOND : TIME_ONLY, + <ime, str)) + return str; + + null_value=1; + return 0; +} + + +bool Item_date_typecast::get_date(MYSQL_TIME *ltime, uint fuzzy_date) +{ + bool res= get_arg0_date(ltime, TIME_FUZZY_DATE); + ltime->hour= ltime->minute= ltime->second= ltime->second_part= 0; + ltime->time_type= MYSQL_TIMESTAMP_DATE; + return res; +} + + +bool Item_date_typecast::get_time(MYSQL_TIME *ltime) +{ + bzero((char *)ltime, sizeof(MYSQL_TIME)); + return args[0]->null_value; +} + + +String *Item_date_typecast::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + + if (!get_arg0_date(<ime, TIME_FUZZY_DATE) && + !str->alloc(MAX_DATE_STRING_REP_LENGTH)) + { + make_date((DATE_TIME_FORMAT *) 0, <ime, str); + return str; + } + + null_value=1; + return 0; +} + +longlong Item_date_typecast::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if ((null_value= args[0]->get_date(<ime, TIME_FUZZY_DATE))) + return 0; + return (longlong) (ltime.year * 10000L + ltime.month * 100 + ltime.day); +} + +/** + MAKEDATE(a,b) is a date function that creates a date value + from a year and day value. + + NOTES: + As arguments are integers, we can't know if the year is a 2 digit or 4 digit year. + In this case we treat all years < 100 as 2 digit years. Ie, this is not safe + for dates between 0000-01-01 and 0099-12-31 +*/ + +String *Item_func_makedate::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME l_time; + long daynr= (long) args[1]->val_int(); + long year= (long) args[0]->val_int(); + long days; + + if (args[0]->null_value || args[1]->null_value || + year < 0 || daynr <= 0) + goto err; + + if (year < 100) + year= year_2000_handling(year); + + days= calc_daynr(year,1,1) + daynr - 1; + /* Day number from year 0 to 9999-12-31 */ + if (days >= 0 && days <= MAX_DAY_NUMBER) + { + null_value=0; + get_date_from_daynr(days,&l_time.year,&l_time.month,&l_time.day); + if (str->alloc(MAX_DATE_STRING_REP_LENGTH)) + goto err; + make_date((DATE_TIME_FORMAT *) 0, &l_time, str); + return str; + } + +err: + null_value=1; + return 0; +} + + +/* + MAKEDATE(a,b) is a date function that creates a date value + from a year and day value. + + NOTES: + As arguments are integers, we can't know if the year is a 2 digit or 4 digit year. + In this case we treat all years < 100 as 2 digit years. Ie, this is not safe + for dates between 0000-01-01 and 0099-12-31 +*/ + +longlong Item_func_makedate::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME l_time; + long daynr= (long) args[1]->val_int(); + long year= (long) args[0]->val_int(); + long days; + + if (args[0]->null_value || args[1]->null_value || + year < 0 || daynr <= 0) + goto err; + + if (year < 100) + year= year_2000_handling(year); + + days= calc_daynr(year,1,1) + daynr - 1; + /* Day number from year 0 to 9999-12-31 */ + if (days >= 0 && days < MAX_DAY_NUMBER) + { + null_value=0; + get_date_from_daynr(days,&l_time.year,&l_time.month,&l_time.day); + return (longlong) (l_time.year * 10000L + l_time.month * 100 + l_time.day); + } + +err: + null_value= 1; + return 0; +} + + +void Item_func_add_time::fix_length_and_dec() +{ + enum_field_types arg0_field_type; + decimals=0; + max_length=MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null= 1; + + /* + The field type for the result of an Item_func_add_time function is defined + as follows: + + - If first arg is a MYSQL_TYPE_DATETIME or MYSQL_TYPE_TIMESTAMP + result is MYSQL_TYPE_DATETIME + - If first arg is a MYSQL_TYPE_TIME result is MYSQL_TYPE_TIME + - Otherwise the result is MYSQL_TYPE_STRING + */ + + cached_field_type= MYSQL_TYPE_STRING; + arg0_field_type= args[0]->field_type(); + if (arg0_field_type == MYSQL_TYPE_DATE || + arg0_field_type == MYSQL_TYPE_DATETIME || + arg0_field_type == MYSQL_TYPE_TIMESTAMP) + cached_field_type= MYSQL_TYPE_DATETIME; + else if (arg0_field_type == MYSQL_TYPE_TIME) + cached_field_type= MYSQL_TYPE_TIME; +} + +/** + ADDTIME(t,a) and SUBTIME(t,a) are time functions that calculate a + time/datetime value + + t: time_or_datetime_expression + a: time_expression + + Result: Time value or datetime value +*/ + +String *Item_func_add_time::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME l_time1, l_time2, l_time3; + bool is_time= 0; + long days, microseconds; + longlong seconds; + int l_sign= sign; + + null_value=0; + if (is_date) // TIMESTAMP function + { + if (get_arg0_date(&l_time1, TIME_FUZZY_DATE) || + args[1]->get_time(&l_time2) || + l_time1.time_type == MYSQL_TIMESTAMP_TIME || + l_time2.time_type != MYSQL_TIMESTAMP_TIME) + goto null_date; + } + else // ADDTIME function + { + if (args[0]->get_time(&l_time1) || + args[1]->get_time(&l_time2) || + l_time2.time_type == MYSQL_TIMESTAMP_DATETIME) + goto null_date; + is_time= (l_time1.time_type == MYSQL_TIMESTAMP_TIME); + } + if (l_time1.neg != l_time2.neg) + l_sign= -l_sign; + + bzero((char *)&l_time3, sizeof(l_time3)); + + l_time3.neg= calc_time_diff(&l_time1, &l_time2, -l_sign, + &seconds, µseconds); + + /* + If first argument was negative and diff between arguments + is non-zero we need to swap sign to get proper result. + */ + if (l_time1.neg && (seconds || microseconds)) + l_time3.neg= 1-l_time3.neg; // Swap sign of result + + if (!is_time && l_time3.neg) + goto null_date; + + days= (long)(seconds/86400L); + + calc_time_from_sec(&l_time3, (long)(seconds%86400L), microseconds); + + if (!is_time) + { + get_date_from_daynr(days,&l_time3.year,&l_time3.month,&l_time3.day); + if (l_time3.day && + !make_datetime(l_time1.second_part || l_time2.second_part ? + DATE_TIME_MICROSECOND : DATE_TIME, + &l_time3, str)) + return str; + goto null_date; + } + + l_time3.hour+= days*24; + if (!make_datetime_with_warn(l_time1.second_part || l_time2.second_part ? + TIME_MICROSECOND : TIME_ONLY, + &l_time3, str)) + return str; + +null_date: + null_value=1; + return 0; +} + + +void Item_func_add_time::print(String *str, enum_query_type query_type) +{ + if (is_date) + { + DBUG_ASSERT(sign > 0); + str->append(STRING_WITH_LEN("timestamp(")); + } + else + { + if (sign > 0) + str->append(STRING_WITH_LEN("addtime(")); + else + str->append(STRING_WITH_LEN("subtime(")); + } + args[0]->print(str, query_type); + str->append(','); + args[1]->print(str, query_type); + str->append(')'); +} + + +/** + TIMEDIFF(t,s) is a time function that calculates the + time value between a start and end time. + + t and s: time_or_datetime_expression + Result: Time value +*/ + +String *Item_func_timediff::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + longlong seconds; + long microseconds; + int l_sign= 1; + MYSQL_TIME l_time1 ,l_time2, l_time3; + + null_value= 0; + if (args[0]->get_time(&l_time1) || + args[1]->get_time(&l_time2) || + l_time1.time_type != l_time2.time_type) + goto null_date; + + if (l_time1.neg != l_time2.neg) + l_sign= -l_sign; + + bzero((char *)&l_time3, sizeof(l_time3)); + + l_time3.neg= calc_time_diff(&l_time1, &l_time2, l_sign, + &seconds, µseconds); + + /* + For MYSQL_TIMESTAMP_TIME only: + If first argument was negative and diff between arguments + is non-zero we need to swap sign to get proper result. + */ + if (l_time1.neg && (seconds || microseconds)) + l_time3.neg= 1-l_time3.neg; // Swap sign of result + + calc_time_from_sec(&l_time3, (long) seconds, microseconds); + + if (!make_datetime_with_warn(l_time1.second_part || l_time2.second_part ? + TIME_MICROSECOND : TIME_ONLY, + &l_time3, str)) + return str; + +null_date: + null_value=1; + return 0; +} + +/** + MAKETIME(h,m,s) is a time function that calculates a time value + from the total number of hours, minutes, and seconds. + Result: Time value +*/ + +String *Item_func_maketime::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + bool overflow= 0; + + longlong hour= args[0]->val_int(); + longlong minute= args[1]->val_int(); + longlong second= args[2]->val_int(); + + if ((null_value=(args[0]->null_value || + args[1]->null_value || + args[2]->null_value || + minute < 0 || minute > 59 || + second < 0 || second > 59 || + str->alloc(MAX_DATE_STRING_REP_LENGTH)))) + return 0; + + bzero((char *)<ime, sizeof(ltime)); + ltime.neg= 0; + + /* Check for integer overflows */ + if (hour < 0) + { + if (args[0]->unsigned_flag) + overflow= 1; + else + ltime.neg= 1; + } + if (-hour > UINT_MAX || hour > UINT_MAX) + overflow= 1; + + if (!overflow) + { + ltime.hour= (uint) ((hour < 0 ? -hour : hour)); + ltime.minute= (uint) minute; + ltime.second= (uint) second; + } + else + { + ltime.hour= TIME_MAX_HOUR; + ltime.minute= TIME_MAX_MINUTE; + ltime.second= TIME_MAX_SECOND; + char buf[28]; + char *ptr= longlong10_to_str(hour, buf, args[0]->unsigned_flag ? 10 : -10); + int len = (int)(ptr - buf) + + my_sprintf(ptr, (ptr, ":%02u:%02u", (uint)minute, (uint)second)); + make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + buf, len, MYSQL_TIMESTAMP_TIME, + NullS); + } + + if (make_time_with_warn((DATE_TIME_FORMAT *) 0, <ime, str)) + { + null_value= 1; + return 0; + } + return str; +} + + +/** + MICROSECOND(a) is a function ( extraction) that extracts the microseconds + from a. + + a: Datetime or time value + Result: int value +*/ + +longlong Item_func_microsecond::val_int() +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + if (!get_arg0_time(<ime)) + return ltime.second_part; + return 0; +} + + +longlong Item_func_timestamp_diff::val_int() +{ + MYSQL_TIME ltime1, ltime2; + longlong seconds; + long microseconds; + long months= 0; + int neg= 1; + + null_value= 0; + if (args[0]->get_date(<ime1, TIME_NO_ZERO_DATE) || + args[1]->get_date(<ime2, TIME_NO_ZERO_DATE)) + goto null_date; + + if (calc_time_diff(<ime2,<ime1, 1, + &seconds, µseconds)) + neg= -1; + + if (int_type == INTERVAL_YEAR || + int_type == INTERVAL_QUARTER || + int_type == INTERVAL_MONTH) + { + uint year_beg, year_end, month_beg, month_end, day_beg, day_end; + uint years= 0; + uint second_beg, second_end, microsecond_beg, microsecond_end; + + if (neg == -1) + { + year_beg= ltime2.year; + year_end= ltime1.year; + month_beg= ltime2.month; + month_end= ltime1.month; + day_beg= ltime2.day; + day_end= ltime1.day; + second_beg= ltime2.hour * 3600 + ltime2.minute * 60 + ltime2.second; + second_end= ltime1.hour * 3600 + ltime1.minute * 60 + ltime1.second; + microsecond_beg= ltime2.second_part; + microsecond_end= ltime1.second_part; + } + else + { + year_beg= ltime1.year; + year_end= ltime2.year; + month_beg= ltime1.month; + month_end= ltime2.month; + day_beg= ltime1.day; + day_end= ltime2.day; + second_beg= ltime1.hour * 3600 + ltime1.minute * 60 + ltime1.second; + second_end= ltime2.hour * 3600 + ltime2.minute * 60 + ltime2.second; + microsecond_beg= ltime1.second_part; + microsecond_end= ltime2.second_part; + } + + /* calc years */ + years= year_end - year_beg; + if (month_end < month_beg || (month_end == month_beg && day_end < day_beg)) + years-= 1; + + /* calc months */ + months= 12*years; + if (month_end < month_beg || (month_end == month_beg && day_end < day_beg)) + months+= 12 - (month_beg - month_end); + else + months+= (month_end - month_beg); + + if (day_end < day_beg) + months-= 1; + else if ((day_end == day_beg) && + ((second_end < second_beg) || + (second_end == second_beg && microsecond_end < microsecond_beg))) + months-= 1; + } + + switch (int_type) { + case INTERVAL_YEAR: + return months/12*neg; + case INTERVAL_QUARTER: + return months/3*neg; + case INTERVAL_MONTH: + return months*neg; + case INTERVAL_WEEK: + return seconds/86400L/7L*neg; + case INTERVAL_DAY: + return seconds/86400L*neg; + case INTERVAL_HOUR: + return seconds/3600L*neg; + case INTERVAL_MINUTE: + return seconds/60L*neg; + case INTERVAL_SECOND: + return seconds*neg; + case INTERVAL_MICROSECOND: + /* + In MySQL difference between any two valid datetime values + in microseconds fits into longlong. + */ + return (seconds*1000000L+microseconds)*neg; + default: + break; + } + +null_date: + null_value=1; + return 0; +} + + +void Item_func_timestamp_diff::print(String *str, enum_query_type query_type) +{ + str->append(func_name()); + str->append('('); + + switch (int_type) { + case INTERVAL_YEAR: + str->append(STRING_WITH_LEN("YEAR")); + break; + case INTERVAL_QUARTER: + str->append(STRING_WITH_LEN("QUARTER")); + break; + case INTERVAL_MONTH: + str->append(STRING_WITH_LEN("MONTH")); + break; + case INTERVAL_WEEK: + str->append(STRING_WITH_LEN("WEEK")); + break; + case INTERVAL_DAY: + str->append(STRING_WITH_LEN("DAY")); + break; + case INTERVAL_HOUR: + str->append(STRING_WITH_LEN("HOUR")); + break; + case INTERVAL_MINUTE: + str->append(STRING_WITH_LEN("MINUTE")); + break; + case INTERVAL_SECOND: + str->append(STRING_WITH_LEN("SECOND")); + break; + case INTERVAL_MICROSECOND: + // @infinidb bug4291. + if (query_type == QT_INFINIDB || query_type == QT_INFINIDB_NO_QUOTE || query_type == QT_INFINIDB_DERIVED) + str->append(STRING_WITH_LEN("MICROSECOND")); + else + str->append(STRING_WITH_LEN("SECOND_FRAC")); + break; + default: + break; + } + + for (uint i=0 ; i < 2 ; i++) + { + str->append(','); + args[i]->print(str, query_type); + } + str->append(')'); +} + + +String *Item_func_get_format::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + const char *format_name; + KNOWN_DATE_TIME_FORMAT *format; + String *val= args[0]->val_str(str); + ulong val_len; + + if ((null_value= args[0]->null_value)) + return 0; + + val_len= val->length(); + for (format= &known_date_time_formats[0]; + (format_name= format->format_name); + format++) + { + uint format_name_len; + format_name_len= (uint) strlen(format_name); + if (val_len == format_name_len && + !my_strnncoll(&my_charset_latin1, + (const uchar *) val->ptr(), val_len, + (const uchar *) format_name, val_len)) + { + const char *format_str= get_date_time_format_str(format, type); + str->set(format_str, (uint) strlen(format_str), &my_charset_bin); + return str; + } + } + + null_value= 1; + return 0; +} + + +void Item_func_get_format::print(String *str, enum_query_type query_type) +{ + str->append(func_name()); + str->append('('); + + switch (type) { + case MYSQL_TIMESTAMP_DATE: + str->append(STRING_WITH_LEN("DATE, ")); + break; + case MYSQL_TIMESTAMP_DATETIME: + str->append(STRING_WITH_LEN("DATETIME, ")); + break; + case MYSQL_TIMESTAMP_TIME: + str->append(STRING_WITH_LEN("TIME, ")); + break; + default: + DBUG_ASSERT(0); + } + args[0]->print(str, query_type); + str->append(')'); +} + + +/** + Get type of datetime value (DATE/TIME/...) which will be produced + according to format string. + + @param format format string + @param length length of format string + + @note + We don't process day format's characters('D', 'd', 'e') because day + may be a member of all date/time types. + + @note + Format specifiers supported by this function should be in sync with + specifiers supported by extract_date_time() function. + + @return + One of date_time_format_types values: + - DATE_TIME_MICROSECOND + - DATE_TIME + - DATE_ONLY + - TIME_MICROSECOND + - TIME_ONLY +*/ + +static date_time_format_types +get_date_time_result_type(const char *format, uint length) +{ + const char *time_part_frms= "HISThiklrs"; + const char *date_part_frms= "MVUXYWabcjmvuxyw"; + bool date_part_used= 0, time_part_used= 0, frac_second_used= 0; + + const char *val= format; + const char *end= format + length; + + for (; val != end && val != end; val++) + { + if (*val == '%' && val+1 != end) + { + val++; + if (*val == 'f') + frac_second_used= time_part_used= 1; + else if (!time_part_used && strchr(time_part_frms, *val)) + time_part_used= 1; + else if (!date_part_used && strchr(date_part_frms, *val)) + date_part_used= 1; + if (date_part_used && frac_second_used) + { + /* + frac_second_used implies time_part_used, and thus we already + have all types of date-time components and can end our search. + */ + return DATE_TIME_MICROSECOND; + } + } + } + + /* We don't have all three types of date-time components */ + if (frac_second_used) + return TIME_MICROSECOND; + if (time_part_used) + { + if (date_part_used) + return DATE_TIME; + return TIME_ONLY; + } + return DATE_ONLY; +} + + +void Item_func_str_to_date::fix_length_and_dec() +{ + maybe_null= 1; + decimals=0; + cached_field_type= MYSQL_TYPE_DATETIME; + max_length= MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + cached_timestamp_type= MYSQL_TIMESTAMP_NONE; + if ((const_item= args[1]->const_item())) + { + char format_buff[64]; + String format_str(format_buff, sizeof(format_buff), &my_charset_bin); + String *format= args[1]->val_str(&format_str); + if (!args[1]->null_value) + { + cached_format_type= get_date_time_result_type(format->ptr(), + format->length()); + switch (cached_format_type) { + case DATE_ONLY: + cached_timestamp_type= MYSQL_TIMESTAMP_DATE; + cached_field_type= MYSQL_TYPE_DATE; + max_length= MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN; + break; + case TIME_ONLY: + case TIME_MICROSECOND: + cached_timestamp_type= MYSQL_TIMESTAMP_TIME; + cached_field_type= MYSQL_TYPE_TIME; + max_length= MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN; + break; + default: + cached_timestamp_type= MYSQL_TIMESTAMP_DATETIME; + cached_field_type= MYSQL_TYPE_DATETIME; + break; + } + } + } +} + + +bool Item_func_str_to_date::get_date(MYSQL_TIME *ltime, uint fuzzy_date) +{ + DATE_TIME_FORMAT date_time_format; + char val_buff[64], format_buff[64]; + String val_string(val_buff, sizeof(val_buff), &my_charset_bin), *val; + String format_str(format_buff, sizeof(format_buff), &my_charset_bin), *format; + + val= args[0]->val_str(&val_string); + format= args[1]->val_str(&format_str); + if (args[0]->null_value || args[1]->null_value) + goto null_date; + + null_value= 0; + bzero((char*) ltime, sizeof(*ltime)); + date_time_format.format.str= (char*) format->ptr(); + date_time_format.format.length= format->length(); + if (extract_date_time(&date_time_format, val->ptr(), val->length(), + ltime, cached_timestamp_type, 0, "datetime") || + ((fuzzy_date & TIME_NO_ZERO_DATE) && + (ltime->year == 0 || ltime->month == 0 || ltime->day == 0))) + goto null_date; + if (cached_timestamp_type == MYSQL_TIMESTAMP_TIME && ltime->day) + { + /* + Day part for time type can be nonzero value and so + we should add hours from day part to hour part to + keep valid time value. + */ + ltime->hour+= ltime->day*24; + ltime->day= 0; + } + return 0; + +null_date: + return (null_value=1); +} + + +String *Item_func_str_to_date::val_str(String *str) +{ + DBUG_ASSERT(fixed == 1); + MYSQL_TIME ltime; + + if (Item_func_str_to_date::get_date(<ime, TIME_FUZZY_DATE)) + return 0; + + if (!make_datetime((const_item ? cached_format_type : + (ltime.second_part ? DATE_TIME_MICROSECOND : DATE_TIME)), + <ime, str)) + return str; + return 0; +} + + +bool Item_func_last_day::get_date(MYSQL_TIME *ltime, uint fuzzy_date) +{ + if (get_arg0_date(ltime, fuzzy_date & ~TIME_FUZZY_DATE) || + (ltime->month == 0)) + { + null_value= 1; + return 1; + } + null_value= 0; + uint month_idx= ltime->month-1; + ltime->day= days_in_month[month_idx]; + if ( month_idx == 1 && calc_days_in_year(ltime->year) == 366) + ltime->day= 29; + ltime->hour= ltime->minute= ltime->second= 0; + ltime->second_part= 0; + ltime->time_type= MYSQL_TIMESTAMP_DATE; + return 0; +} diff --git a/dbcon/mysql/item_timefunc.h b/dbcon/mysql/item_timefunc.h new file mode 100644 index 00000000..ab953c2f --- /dev/null +++ b/dbcon/mysql/item_timefunc.h @@ -0,0 +1,1033 @@ +/* Copyright (C) 2000-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Function items used by mysql */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +enum date_time_format_types +{ + TIME_ONLY= 0, TIME_MICROSECOND, DATE_ONLY, DATE_TIME, DATE_TIME_MICROSECOND +}; + +bool get_interval_value(Item *args,interval_type int_type, + String *str_value, INTERVAL *interval); + +class Item_func_period_add :public Item_int_func +{ +public: + Item_func_period_add(Item *a,Item *b) :Item_int_func(a,b) {} + longlong val_int(); + const char *func_name() const { return "period_add"; } + void fix_length_and_dec() + { + max_length=6*MY_CHARSET_BIN_MB_MAXLEN; + } +}; + + +class Item_func_period_diff :public Item_int_func +{ +public: + Item_func_period_diff(Item *a,Item *b) :Item_int_func(a,b) {} + longlong val_int(); + const char *func_name() const { return "period_diff"; } + void fix_length_and_dec() + { + decimals=0; + max_length=6*MY_CHARSET_BIN_MB_MAXLEN; + } +}; + + +class Item_func_to_days :public Item_int_func +{ +public: + Item_func_to_days(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "to_days"; } + void fix_length_and_dec() + { + decimals=0; + max_length=6*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + enum_monotonicity_info get_monotonicity_info() const; + longlong val_int_endpoint(bool left_endp, bool *incl_endp); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_dayofmonth :public Item_int_func +{ +public: + Item_func_dayofmonth(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "dayofmonth"; } + void fix_length_and_dec() + { + decimals=0; + max_length=2*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_month :public Item_func +{ +public: + Item_func_month(Item *a) :Item_func(a) {} + longlong val_int(); + double val_real() + { DBUG_ASSERT(fixed == 1); return (double) Item_func_month::val_int(); } + String *val_str(String *str) + { + str->set(val_int(), &my_charset_bin); + return null_value ? 0 : str; + } + const char *func_name() const { return "month"; } + enum Item_result result_type () const { return INT_RESULT; } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + decimals=0; + max_length=2*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_monthname :public Item_func_month +{ + MY_LOCALE *locale; +public: + Item_func_monthname(Item *a) :Item_func_month(a) {} + const char *func_name() const { return "monthname"; } + String *val_str(String *str); + enum Item_result result_type () const { return STRING_RESULT; } + void fix_length_and_dec(); + bool check_partition_func_processor(uchar *int_arg) {return TRUE;} +}; + + +class Item_func_dayofyear :public Item_int_func +{ +public: + Item_func_dayofyear(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "dayofyear"; } + void fix_length_and_dec() + { + decimals=0; + max_length=3*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_hour :public Item_int_func +{ +public: + Item_func_hour(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "hour"; } + void fix_length_and_dec() + { + decimals=0; + max_length=2*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_minute :public Item_int_func +{ +public: + Item_func_minute(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "minute"; } + void fix_length_and_dec() + { + decimals=0; + max_length=2*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_quarter :public Item_int_func +{ +public: + Item_func_quarter(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "quarter"; } + void fix_length_and_dec() + { + decimals=0; + max_length=1*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_second :public Item_int_func +{ +public: + Item_func_second(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "second"; } + void fix_length_and_dec() + { + decimals=0; + max_length=2*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_week :public Item_int_func +{ +public: + Item_func_week(Item *a,Item *b) :Item_int_func(a,b) {} + longlong val_int(); + const char *func_name() const { return "week"; } + void fix_length_and_dec() + { + decimals=0; + max_length=2*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } +}; + +class Item_func_yearweek :public Item_int_func +{ +public: + Item_func_yearweek(Item *a,Item *b) :Item_int_func(a,b) {} + longlong val_int(); + const char *func_name() const { return "yearweek"; } + void fix_length_and_dec() + { + decimals=0; + max_length=6*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_year :public Item_int_func +{ +public: + Item_func_year(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "year"; } + enum_monotonicity_info get_monotonicity_info() const; + longlong val_int_endpoint(bool left_endp, bool *incl_endp); + void fix_length_and_dec() + { + decimals=0; + max_length=4*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_weekday :public Item_func +{ + bool odbc_type; +public: + Item_func_weekday(Item *a,bool type_arg) + :Item_func(a), odbc_type(type_arg) {} + longlong val_int(); + double val_real() { DBUG_ASSERT(fixed == 1); return (double) val_int(); } + String *val_str(String *str) + { + DBUG_ASSERT(fixed == 1); + str->set(val_int(), &my_charset_bin); + return null_value ? 0 : str; + } + const char *func_name() const + { + return (odbc_type ? "dayofweek" : "weekday"); + } + enum Item_result result_type () const { return INT_RESULT; } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + decimals=0; + max_length=1*MY_CHARSET_BIN_MB_MAXLEN; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + +class Item_func_dayname :public Item_func_weekday +{ + MY_LOCALE *locale; + public: + Item_func_dayname(Item *a) :Item_func_weekday(a,0) {} + const char *func_name() const { return "dayname"; } + String *val_str(String *str); + enum Item_result result_type () const { return STRING_RESULT; } + void fix_length_and_dec(); + bool check_partition_func_processor(uchar *int_arg) {return TRUE;} +}; + + +class Item_func_unix_timestamp :public Item_int_func +{ + String value; +public: + Item_func_unix_timestamp() :Item_int_func() {} + Item_func_unix_timestamp(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "unix_timestamp"; } + void fix_length_and_dec() + { + decimals=0; + max_length=10*MY_CHARSET_BIN_MB_MAXLEN; + } +}; + + +class Item_func_time_to_sec :public Item_int_func +{ +public: + Item_func_time_to_sec(Item *item) :Item_int_func(item) {} + longlong val_int(); + const char *func_name() const { return "time_to_sec"; } + void fix_length_and_dec() + { + decimals=0; + max_length=10*MY_CHARSET_BIN_MB_MAXLEN; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +/* + This can't be a Item_str_func, because the val_real() functions are special +*/ + +class Item_date :public Item_func +{ +public: + Item_date() :Item_func() {} + Item_date(Item *a) :Item_func(a) {} + enum Item_result result_type () const { return STRING_RESULT; } + enum_field_types field_type() const { return MYSQL_TYPE_DATE; } + String *val_str(String *str); + longlong val_int(); + double val_real() { return val_real_from_decimal(); } + const char *func_name() const { return "date"; } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + decimals=0; + max_length=MAX_DATE_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + } + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + bool result_as_longlong() { return TRUE; } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + return val_decimal_from_date(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + return save_date_in_field(field); + } +}; + + +class Item_date_func :public Item_str_func +{ +public: + Item_date_func() :Item_str_func() {} + Item_date_func(Item *a) :Item_str_func(a) {} + Item_date_func(Item *a,Item *b) :Item_str_func(a,b) {} + Item_date_func(Item *a,Item *b, Item *c) :Item_str_func(a,b,c) {} + enum_field_types field_type() const { return MYSQL_TYPE_DATETIME; } + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + bool result_as_longlong() { return TRUE; } + double val_real() { return (double) val_int(); } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + return val_decimal_from_date(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + return save_date_in_field(field); + } +}; + + +class Item_str_timefunc :public Item_str_func +{ +public: + Item_str_timefunc() :Item_str_func() {} + Item_str_timefunc(Item *a) :Item_str_func(a) {} + Item_str_timefunc(Item *a,Item *b) :Item_str_func(a,b) {} + Item_str_timefunc(Item *a, Item *b, Item *c) :Item_str_func(a, b ,c) {} + enum_field_types field_type() const { return MYSQL_TYPE_TIME; } + void fix_length_and_dec() + { + decimals= DATETIME_DEC; + max_length=MAX_TIME_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + } + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + double val_real() { return val_real_from_decimal(); } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + return val_decimal_from_time(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + return save_time_in_field(field); + } + longlong val_int() { return val_int_from_decimal(); } + bool result_as_longlong() { return TRUE; } +}; + + +/* Abstract CURTIME function. Children should define what time zone is used */ + +class Item_func_curtime :public Item_str_timefunc +{ + longlong value; + char buff[9*2+32]; + uint buff_length; +public: + Item_func_curtime() :Item_str_timefunc() {} + Item_func_curtime(Item *a) :Item_str_timefunc(a) {} + double val_real() { DBUG_ASSERT(fixed == 1); return (double) value; } + longlong val_int() { DBUG_ASSERT(fixed == 1); return value; } + String *val_str(String *str); + void fix_length_and_dec(); + /* + Abstract method that defines which time zone is used for conversion. + Converts time current time in my_time_t representation to broken-down + MYSQL_TIME representation using UTC-SYSTEM or per-thread time zone. + */ + virtual void store_now_in_TIME(MYSQL_TIME *now_time)=0; + bool result_as_longlong() { return TRUE; } +}; + + +class Item_func_curtime_local :public Item_func_curtime +{ +public: + Item_func_curtime_local() :Item_func_curtime() {} + Item_func_curtime_local(Item *a) :Item_func_curtime(a) {} + const char *func_name() const { return "curtime"; } + virtual void store_now_in_TIME(MYSQL_TIME *now_time); +}; + + +class Item_func_curtime_utc :public Item_func_curtime +{ +public: + Item_func_curtime_utc() :Item_func_curtime() {} + Item_func_curtime_utc(Item *a) :Item_func_curtime(a) {} + const char *func_name() const { return "utc_time"; } + virtual void store_now_in_TIME(MYSQL_TIME *now_time); +}; + + +/* Abstract CURDATE function. See also Item_func_curtime. */ + +class Item_func_curdate :public Item_date +{ + longlong value; + MYSQL_TIME ltime; +public: + Item_func_curdate() :Item_date() {} + longlong val_int() { DBUG_ASSERT(fixed == 1); return (value) ; } + String *val_str(String *str); + void fix_length_and_dec(); + bool get_date(MYSQL_TIME *res, uint fuzzy_date); + virtual void store_now_in_TIME(MYSQL_TIME *now_time)=0; +}; + + +class Item_func_curdate_local :public Item_func_curdate +{ +public: + Item_func_curdate_local() :Item_func_curdate() {} + const char *func_name() const { return "curdate"; } + void store_now_in_TIME(MYSQL_TIME *now_time); +}; + + +class Item_func_curdate_utc :public Item_func_curdate +{ +public: + Item_func_curdate_utc() :Item_func_curdate() {} + const char *func_name() const { return "utc_date"; } + void store_now_in_TIME(MYSQL_TIME *now_time); +}; + + +/* Abstract CURRENT_TIMESTAMP function. See also Item_func_curtime */ + +class Item_func_now :public Item_date_func +{ +protected: + longlong value; + char buff[20*2+32]; // +32 to make my_snprintf_{8bit|ucs2} happy + uint buff_length; + MYSQL_TIME ltime; +public: + Item_func_now() :Item_date_func() {} + Item_func_now(Item *a) :Item_date_func(a) {} + enum Item_result result_type () const { return STRING_RESULT; } + longlong val_int() { DBUG_ASSERT(fixed == 1); return value; } + int save_in_field(Field *to, bool no_conversions); + String *val_str(String *str); + void fix_length_and_dec(); + bool get_date(MYSQL_TIME *res, uint fuzzy_date); + virtual void store_now_in_TIME(MYSQL_TIME *now_time)=0; +}; + + +class Item_func_now_local :public Item_func_now +{ +public: + Item_func_now_local() :Item_func_now() {} + Item_func_now_local(Item *a) :Item_func_now(a) {} + const char *func_name() const { return "now"; } + virtual void store_now_in_TIME(MYSQL_TIME *now_time); + virtual enum Functype functype() const { return NOW_FUNC; } +}; + + +class Item_func_now_utc :public Item_func_now +{ +public: + Item_func_now_utc() :Item_func_now() {} + Item_func_now_utc(Item *a) :Item_func_now(a) {} + const char *func_name() const { return "utc_timestamp"; } + virtual void store_now_in_TIME(MYSQL_TIME *now_time); +}; + + +/* + This is like NOW(), but always uses the real current time, not the + query_start(). This matches the Oracle behavior. +*/ +class Item_func_sysdate_local :public Item_func_now +{ +public: + Item_func_sysdate_local() :Item_func_now() {} + Item_func_sysdate_local(Item *a) :Item_func_now(a) {} + bool const_item() const { return 0; } + const char *func_name() const { return "sysdate"; } + void store_now_in_TIME(MYSQL_TIME *now_time); + double val_real(); + longlong val_int(); + int save_in_field(Field *to, bool no_conversions); + String *val_str(String *str); + void fix_length_and_dec(); + bool get_date(MYSQL_TIME *res, uint fuzzy_date); + void update_used_tables() + { + Item_func_now::update_used_tables(); + used_tables_cache|= RAND_TABLE_BIT; + } +}; + + +class Item_func_from_days :public Item_date +{ +public: + Item_func_from_days(Item *a) :Item_date(a) {} + const char *func_name() const { return "from_days"; } + bool get_date(MYSQL_TIME *res, uint fuzzy_date); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_date_format :public Item_str_func +{ + int fixed_length; + const bool is_time_format; + String value; +public: + Item_func_date_format(Item *a,Item *b,bool is_time_format_arg) + :Item_str_func(a,b),is_time_format(is_time_format_arg) {} + String *val_str(String *str); + const char *func_name() const + { return is_time_format ? "time_format" : "date_format"; } + void fix_length_and_dec(); + uint format_length(const String *format); + bool eq(const Item *item, bool binary_cmp) const; +}; + + +class Item_func_from_unixtime :public Item_date_func +{ + THD *thd; + public: + Item_func_from_unixtime(Item *a) :Item_date_func(a) {} + longlong val_int(); + String *val_str(String *str); + const char *func_name() const { return "from_unixtime"; } + void fix_length_and_dec(); + bool get_date(MYSQL_TIME *res, uint fuzzy_date); +}; + + +/* + We need Time_zone class declaration for storing pointers in + Item_func_convert_tz. +*/ +class Time_zone; + +/* + This class represents CONVERT_TZ() function. + The important fact about this function that it is handled in special way. + When such function is met in expression time_zone system tables are added + to global list of tables to open, so later those already opened and locked + tables can be used during this function calculation for loading time zone + descriptions. +*/ +class Item_func_convert_tz :public Item_date_func +{ + /* + If time zone parameters are constants we are caching objects that + represent them (we use separate from_tz_cached/to_tz_cached members + to indicate this fact, since NULL is legal value for from_tz/to_tz + members. + */ + bool from_tz_cached, to_tz_cached; + Time_zone *from_tz, *to_tz; + public: + Item_func_convert_tz(Item *a, Item *b, Item *c): + Item_date_func(a, b, c), from_tz_cached(0), to_tz_cached(0) {} + longlong val_int(); + String *val_str(String *str); + const char *func_name() const { return "convert_tz"; } + void fix_length_and_dec(); + bool get_date(MYSQL_TIME *res, uint fuzzy_date); + void cleanup(); +}; + + +class Item_func_sec_to_time :public Item_str_timefunc +{ +public: + Item_func_sec_to_time(Item *item) :Item_str_timefunc(item) {} + double val_real() + { + DBUG_ASSERT(fixed == 1); + return (double) Item_func_sec_to_time::val_int(); + } + longlong val_int(); + String *val_str(String *); + void fix_length_and_dec() + { + Item_str_timefunc::fix_length_and_dec(); + collation.set(&my_charset_bin); + maybe_null=1; + } + const char *func_name() const { return "sec_to_time"; } + bool result_as_longlong() { return TRUE; } +}; + + +class Item_date_add_interval :public Item_date_func +{ + String value; + enum_field_types cached_field_type; + +public: + const interval_type int_type; // keep it public + const bool date_sub_interval; // keep it public + Item_date_add_interval(Item *a,Item *b,interval_type type_arg,bool neg_arg) + :Item_date_func(a,b),int_type(type_arg), date_sub_interval(neg_arg) {} + String *val_str(String *); + const char *func_name() const { return "date_add_interval"; } + void fix_length_and_dec(); + enum_field_types field_type() const { return cached_field_type; } + longlong val_int(); + bool get_date(MYSQL_TIME *res, uint fuzzy_date); + bool eq(const Item *item, bool binary_cmp) const; + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_extract :public Item_int_func +{ + String value; + bool date_value; + public: + const interval_type int_type; // keep it public + Item_extract(interval_type type_arg, Item *a) + :Item_int_func(a), int_type(type_arg) {} + longlong val_int(); + enum Functype functype() const { return EXTRACT_FUNC; } + const char *func_name() const { return "extract"; } + void fix_length_and_dec(); + bool eq(const Item *item, bool binary_cmp) const; + virtual void print(String *str, enum_query_type query_type); + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_typecast :public Item_str_func +{ +public: + Item_typecast(Item *a) :Item_str_func(a) {} + String *val_str(String *a) + { + DBUG_ASSERT(fixed == 1); + String *tmp=args[0]->val_str(a); + null_value=args[0]->null_value; + if (tmp) + tmp->set_charset(collation.collation); + return tmp; + } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + max_length=args[0]->max_length; + } + virtual const char* cast_type() const= 0; + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_typecast_maybe_null :public Item_typecast +{ +public: + Item_typecast_maybe_null(Item *a) :Item_typecast(a) {} + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + max_length=args[0]->max_length; + maybe_null= 1; + } +}; + + +class Item_char_typecast :public Item_typecast +{ + int cast_length; + CHARSET_INFO *cast_cs, *from_cs; + bool charset_conversion; + String tmp_value; +public: + Item_char_typecast(Item *a, int length_arg, CHARSET_INFO *cs_arg) + :Item_typecast(a), cast_length(length_arg), cast_cs(cs_arg) {} + enum Functype functype() const { return CHAR_TYPECAST_FUNC; } + bool eq(const Item *item, bool binary_cmp) const; + const char *func_name() const { return "cast_as_char"; } + const char* cast_type() const { return "char"; }; + String *val_str(String *a); + void fix_length_and_dec(); + // @InfiniDB. add accessor + int castLength() { return (int) cast_length; } + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_date_typecast :public Item_typecast_maybe_null +{ +public: + Item_date_typecast(Item *a) :Item_typecast_maybe_null(a) {} + const char *func_name() const { return "cast_as_date"; } + String *val_str(String *str); + bool get_date(MYSQL_TIME *ltime, uint fuzzy_date); + bool get_time(MYSQL_TIME *ltime); + const char *cast_type() const { return "date"; } + enum_field_types field_type() const { return MYSQL_TYPE_DATE; } + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + max_length= 10; + maybe_null= 1; + } + bool result_as_longlong() { return TRUE; } + longlong val_int(); + double val_real() { return (double) val_int(); } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + return val_decimal_from_date(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + return save_date_in_field(field); + } +}; + + +class Item_time_typecast :public Item_typecast_maybe_null +{ +public: + Item_time_typecast(Item *a) :Item_typecast_maybe_null(a) {} + const char *func_name() const { return "cast_as_time"; } + String *val_str(String *str); + bool get_time(MYSQL_TIME *ltime); + const char *cast_type() const { return "time"; } + enum_field_types field_type() const { return MYSQL_TYPE_TIME; } + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + bool result_as_longlong() { return TRUE; } + longlong val_int(); + double val_real() { return val_real_from_decimal(); } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + return val_decimal_from_time(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + return save_time_in_field(field); + } +}; + + +class Item_datetime_typecast :public Item_typecast_maybe_null +{ +public: + Item_datetime_typecast(Item *a) :Item_typecast_maybe_null(a) {} + const char *func_name() const { return "cast_as_datetime"; } + String *val_str(String *str); + const char *cast_type() const { return "datetime"; } + enum_field_types field_type() const { return MYSQL_TYPE_DATETIME; } + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + void fix_length_and_dec() + { + collation.set(&my_charset_bin); + maybe_null= 1; + max_length= MAX_DATETIME_FULL_WIDTH * MY_CHARSET_BIN_MB_MAXLEN; + decimals= DATETIME_DEC; + } + bool result_as_longlong() { return TRUE; } + longlong val_int(); + double val_real() { return val_real_from_decimal(); } + double val() { return (double) val_int(); } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + return val_decimal_from_date(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + return save_date_in_field(field); + } +}; + +class Item_func_makedate :public Item_date_func +{ +public: + Item_func_makedate(Item *a,Item *b) :Item_date_func(a,b) {} + String *val_str(String *str); + const char *func_name() const { return "makedate"; } + enum_field_types field_type() const { return MYSQL_TYPE_DATE; } + void fix_length_and_dec() + { + decimals=0; + max_length=MAX_DATE_WIDTH*MY_CHARSET_BIN_MB_MAXLEN; + } + longlong val_int(); +}; + + +class Item_func_add_time :public Item_str_func +{ + const bool is_date; + int sign; + enum_field_types cached_field_type; + +public: + Item_func_add_time(Item *a, Item *b, bool type_arg, bool neg_arg) + :Item_str_func(a, b), is_date(type_arg) { sign= neg_arg ? -1 : 1; } + String *val_str(String *str); + enum_field_types field_type() const { return cached_field_type; } + void fix_length_and_dec(); + + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 0); + } + virtual void print(String *str, enum_query_type query_type); + const char *func_name() const { return "add_time"; } + double val_real() { return val_real_from_decimal(); } + my_decimal *val_decimal(my_decimal *decimal_value) + { + DBUG_ASSERT(fixed == 1); + if (cached_field_type == MYSQL_TYPE_TIME) + return val_decimal_from_time(decimal_value); + if (cached_field_type == MYSQL_TYPE_DATETIME) + return val_decimal_from_date(decimal_value); + return Item_str_func::val_decimal(decimal_value); + } + int save_in_field(Field *field, bool no_conversions) + { + if (cached_field_type == MYSQL_TYPE_TIME) + return save_time_in_field(field); + if (cached_field_type == MYSQL_TYPE_DATETIME) + return save_date_in_field(field); + return Item_str_func::save_in_field(field, no_conversions); + } + + // @InfiniDB add accessor + int get_sign() { return sign; } +}; + +class Item_func_timediff :public Item_str_timefunc +{ +public: + Item_func_timediff(Item *a, Item *b) + :Item_str_timefunc(a, b) {} + String *val_str(String *str); + const char *func_name() const { return "timediff"; } + void fix_length_and_dec() + { + Item_str_timefunc::fix_length_and_dec(); + maybe_null= 1; + } +}; + +class Item_func_maketime :public Item_str_timefunc +{ +public: + Item_func_maketime(Item *a, Item *b, Item *c) + :Item_str_timefunc(a, b, c) + { + maybe_null= TRUE; + } + String *val_str(String *str); + const char *func_name() const { return "maketime"; } +}; + +class Item_func_microsecond :public Item_int_func +{ +public: + Item_func_microsecond(Item *a) :Item_int_func(a) {} + longlong val_int(); + const char *func_name() const { return "microsecond"; } + void fix_length_and_dec() + { + decimals=0; + maybe_null=1; + } + bool check_partition_func_processor(uchar *int_arg) {return FALSE;} +}; + + +class Item_func_timestamp_diff :public Item_int_func +{ +public: + const interval_type int_type; // @InfiniDB keep in public + Item_func_timestamp_diff(Item *a,Item *b,interval_type type_arg) + :Item_int_func(a,b), int_type(type_arg) {} + const char *func_name() const { return "timestampdiff"; } + longlong val_int(); + void fix_length_and_dec() + { + decimals=0; + maybe_null=1; + } + virtual void print(String *str, enum_query_type query_type); +}; + + +enum date_time_format +{ + USA_FORMAT, JIS_FORMAT, ISO_FORMAT, EUR_FORMAT, INTERNAL_FORMAT +}; + +class Item_func_get_format :public Item_str_func +{ +public: + const timestamp_type type; // keep it public + Item_func_get_format(timestamp_type type_arg, Item *a) + :Item_str_func(a), type(type_arg) + {} + String *val_str(String *str); + const char *func_name() const { return "get_format"; } + void fix_length_and_dec() + { + maybe_null= 1; + decimals=0; + max_length=17*MY_CHARSET_BIN_MB_MAXLEN; + } + virtual void print(String *str, enum_query_type query_type); +}; + + +class Item_func_str_to_date :public Item_str_func +{ + enum_field_types cached_field_type; + date_time_format_types cached_format_type; + timestamp_type cached_timestamp_type; + bool const_item; +public: + Item_func_str_to_date(Item *a, Item *b) + :Item_str_func(a, b), const_item(false) + {} + String *val_str(String *str); + bool get_date(MYSQL_TIME *ltime, uint fuzzy_date); + const char *func_name() const { return "str_to_date"; } + enum_field_types field_type() const { return cached_field_type; } + void fix_length_and_dec(); + Field *tmp_table_field(TABLE *table) + { + return tmp_table_field_from_field_type(table, 1); + } +}; + + +class Item_func_last_day :public Item_date +{ +public: + Item_func_last_day(Item *a) :Item_date(a) {} + const char *func_name() const { return "last_day"; } + bool get_date(MYSQL_TIME *res, uint fuzzy_date); +}; diff --git a/dbcon/mysql/lex.h b/dbcon/mysql/lex.h new file mode 100644 index 00000000..142d8b70 --- /dev/null +++ b/dbcon/mysql/lex.h @@ -0,0 +1,637 @@ +/* Copyright (C) 2000-2002 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* This file includes all reserved words and functions */ + +#include "lex_symbol.h" + +SYM_GROUP sym_group_common= {"", ""}; +SYM_GROUP sym_group_geom= {"Spatial extentions", "HAVE_SPATIAL"}; +SYM_GROUP sym_group_rtree= {"RTree keys", "HAVE_RTREE_KEYS"}; + +/* We don't want to include sql_yacc.h into gen_lex_hash */ +#ifdef NO_YACC_SYMBOLS +#define SYM_OR_NULL(A) 0 +#else +#define SYM_OR_NULL(A) A +#endif + +#define SYM(A) SYM_OR_NULL(A),0,&sym_group_common + +/* + Symbols are broken into separated arrays to allow field names with + same name as functions. + These are kept sorted for human lookup (the symbols are hashed). + + NOTE! The symbol tables should be the same regardless of what features + are compiled into the server. Don't add ifdef'ed symbols to the + lists +*/ + +static SYMBOL symbols[] = { + { "&&", SYM(AND_AND_SYM)}, + { "<", SYM(LT)}, + { "<=", SYM(LE)}, + { "<>", SYM(NE)}, + { "!=", SYM(NE)}, + { "=", SYM(EQ)}, + { ">", SYM(GT_SYM)}, + { ">=", SYM(GE)}, + { "<<", SYM(SHIFT_LEFT)}, + { ">>", SYM(SHIFT_RIGHT)}, + { "<=>", SYM(EQUAL_SYM)}, + { "ACCESSIBLE", SYM(ACCESSIBLE_SYM)}, + { "ACTION", SYM(ACTION)}, + { "ADD", SYM(ADD)}, + { "AFTER", SYM(AFTER_SYM)}, + { "AGAINST", SYM(AGAINST)}, + { "AGGREGATE", SYM(AGGREGATE_SYM)}, + { "ALL", SYM(ALL)}, + { "ALGORITHM", SYM(ALGORITHM_SYM)}, + { "ALTER", SYM(ALTER)}, + { "ANALYZE", SYM(ANALYZE_SYM)}, + { "AND", SYM(AND_SYM)}, + { "ANY", SYM(ANY_SYM)}, + { "AS", SYM(AS)}, + { "ASC", SYM(ASC)}, + { "ASCII", SYM(ASCII_SYM)}, + { "ASENSITIVE", SYM(ASENSITIVE_SYM)}, + { "AT", SYM(AT_SYM)}, + { "AUTHORS", SYM(AUTHORS_SYM)}, + { "AUTO_INCREMENT", SYM(AUTO_INC)}, + { "AUTOEXTEND_SIZE", SYM(AUTOEXTEND_SIZE_SYM)}, + { "AVG", SYM(AVG_SYM)}, + { "AVG_ROW_LENGTH", SYM(AVG_ROW_LENGTH)}, + { "BACKUP", SYM(BACKUP_SYM)}, + { "BEFORE", SYM(BEFORE_SYM)}, + { "BEGIN", SYM(BEGIN_SYM)}, + { "BETWEEN", SYM(BETWEEN_SYM)}, + { "BIGINT", SYM(BIGINT)}, + { "BINARY", SYM(BINARY)}, + { "BINLOG", SYM(BINLOG_SYM)}, + { "BIT", SYM(BIT_SYM)}, + { "BLOB", SYM(BLOB_SYM)}, + { "BLOCK", SYM(BLOCK_SYM)}, + { "BOOL", SYM(BOOL_SYM)}, + { "BOOLEAN", SYM(BOOLEAN_SYM)}, + { "BOTH", SYM(BOTH)}, + { "BTREE", SYM(BTREE_SYM)}, + { "BY", SYM(BY)}, + { "BYTE", SYM(BYTE_SYM)}, + { "CACHE", SYM(CACHE_SYM)}, + { "CALL", SYM(CALL_SYM)}, + { "CASCADE", SYM(CASCADE)}, + { "CASCADED", SYM(CASCADED)}, + { "CASE", SYM(CASE_SYM)}, + { "CHAIN", SYM(CHAIN_SYM)}, + { "CHANGE", SYM(CHANGE)}, + { "CHANGED", SYM(CHANGED)}, + { "CHAR", SYM(CHAR_SYM)}, + { "CHARACTER", SYM(CHAR_SYM)}, + { "CHARSET", SYM(CHARSET)}, + { "CHECK", SYM(CHECK_SYM)}, + { "CHECKSUM", SYM(CHECKSUM_SYM)}, + { "CIPHER", SYM(CIPHER_SYM)}, + { "CLIENT", SYM(CLIENT_SYM)}, + { "CLOSE", SYM(CLOSE_SYM)}, + { "COALESCE", SYM(COALESCE)}, + { "CODE", SYM(CODE_SYM)}, + { "COLLATE", SYM(COLLATE_SYM)}, + { "COLLATION", SYM(COLLATION_SYM)}, + { "COLUMN", SYM(COLUMN_SYM)}, + { "COLUMNS", SYM(COLUMNS)}, + { "COMMENT", SYM(COMMENT_SYM)}, + { "COMMIT", SYM(COMMIT_SYM)}, + { "COMMITTED", SYM(COMMITTED_SYM)}, + { "COMPACT", SYM(COMPACT_SYM)}, + { "COMPLETION", SYM(COMPLETION_SYM)}, + { "COMPRESSED", SYM(COMPRESSED_SYM)}, + { "CONCURRENT", SYM(CONCURRENT)}, + { "CONDITION", SYM(CONDITION_SYM)}, + { "CONNECTION", SYM(CONNECTION_SYM)}, + { "CONSISTENT", SYM(CONSISTENT_SYM)}, + { "CONSTRAINT", SYM(CONSTRAINT)}, + { "CONTAINS", SYM(CONTAINS_SYM)}, + { "CONTEXT", SYM(CONTEXT_SYM)}, + { "CONTINUE", SYM(CONTINUE_SYM)}, + { "CONTRIBUTORS", SYM(CONTRIBUTORS_SYM)}, + { "CONVERT", SYM(CONVERT_SYM)}, + { "CPU", SYM(CPU_SYM)}, + { "CREATE", SYM(CREATE)}, + { "CROSS", SYM(CROSS)}, + { "CUBE", SYM(CUBE_SYM)}, + { "CURRENT_DATE", SYM(CURDATE)}, + { "CURRENT_TIME", SYM(CURTIME)}, + { "CURRENT_TIMESTAMP", SYM(NOW_SYM)}, + { "CURRENT_USER", SYM(CURRENT_USER)}, + { "CURSOR", SYM(CURSOR_SYM)}, + { "DATA", SYM(DATA_SYM)}, + { "DATABASE", SYM(DATABASE)}, + { "DATABASES", SYM(DATABASES)}, + { "DATAFILE", SYM(DATAFILE_SYM)}, + { "DATE", SYM(DATE_SYM)}, + { "DATETIME", SYM(DATETIME)}, + { "DAY", SYM(DAY_SYM)}, + { "DAY_HOUR", SYM(DAY_HOUR_SYM)}, + { "DAY_MICROSECOND", SYM(DAY_MICROSECOND_SYM)}, + { "DAY_MINUTE", SYM(DAY_MINUTE_SYM)}, + { "DAY_SECOND", SYM(DAY_SECOND_SYM)}, + { "DEALLOCATE", SYM(DEALLOCATE_SYM)}, + { "DEC", SYM(DECIMAL_SYM)}, + { "DECIMAL", SYM(DECIMAL_SYM)}, + { "DECLARE", SYM(DECLARE_SYM)}, + { "DEFAULT", SYM(DEFAULT)}, + { "DEFINER", SYM(DEFINER_SYM)}, + { "DELAYED", SYM(DELAYED_SYM)}, + { "DELAY_KEY_WRITE", SYM(DELAY_KEY_WRITE_SYM)}, + { "DELETE", SYM(DELETE_SYM)}, + { "DESC", SYM(DESC)}, + { "DESCRIBE", SYM(DESCRIBE)}, + { "DES_KEY_FILE", SYM(DES_KEY_FILE)}, + { "DETERMINISTIC", SYM(DETERMINISTIC_SYM)}, + { "DIRECTORY", SYM(DIRECTORY_SYM)}, + { "DISABLE", SYM(DISABLE_SYM)}, + { "DISCARD", SYM(DISCARD)}, + { "DISK", SYM(DISK_SYM)}, + { "DISTINCT", SYM(DISTINCT)}, + { "DISTINCTROW", SYM(DISTINCT)}, /* Access likes this */ + { "DIV", SYM(DIV_SYM)}, + { "DO", SYM(DO_SYM)}, + { "DOUBLE", SYM(DOUBLE_SYM)}, + { "DROP", SYM(DROP)}, + { "DUAL", SYM(DUAL_SYM)}, + { "DUMPFILE", SYM(DUMPFILE)}, + { "DUPLICATE", SYM(DUPLICATE_SYM)}, + { "DYNAMIC", SYM(DYNAMIC_SYM)}, + { "EACH", SYM(EACH_SYM)}, + { "ELSE", SYM(ELSE)}, + { "ELSEIF", SYM(ELSEIF_SYM)}, + { "ENABLE", SYM(ENABLE_SYM)}, + { "ENCLOSED", SYM(ENCLOSED)}, + { "END", SYM(END)}, + { "ENDS", SYM(ENDS_SYM)}, + { "ENGINE", SYM(ENGINE_SYM)}, + { "ENGINES", SYM(ENGINES_SYM)}, + { "ENUM", SYM(ENUM)}, + { "ERRORS", SYM(ERRORS)}, + { "ESCAPE", SYM(ESCAPE_SYM)}, + { "ESCAPED", SYM(ESCAPED)}, + { "EVENT", SYM(EVENT_SYM)}, + { "EVENTS", SYM(EVENTS_SYM)}, + { "EVERY", SYM(EVERY_SYM)}, + { "EXECUTE", SYM(EXECUTE_SYM)}, + { "EXISTS", SYM(EXISTS)}, + { "EXIT", SYM(EXIT_SYM)}, + { "EXPANSION", SYM(EXPANSION_SYM)}, + { "EXPLAIN", SYM(DESCRIBE)}, + { "EXTENDED", SYM(EXTENDED_SYM)}, + { "EXTENT_SIZE", SYM(EXTENT_SIZE_SYM)}, + { "FALSE", SYM(FALSE_SYM)}, + { "FAST", SYM(FAST_SYM)}, + { "FAULTS", SYM(FAULTS_SYM)}, + { "FETCH", SYM(FETCH_SYM)}, + { "FIELDS", SYM(COLUMNS)}, + { "FILE", SYM(FILE_SYM)}, + { "FIRST", SYM(FIRST_SYM)}, + { "FIXED", SYM(FIXED_SYM)}, + { "FLOAT", SYM(FLOAT_SYM)}, + { "FLOAT4", SYM(FLOAT_SYM)}, + { "FLOAT8", SYM(DOUBLE_SYM)}, + { "FLUSH", SYM(FLUSH_SYM)}, + { "FOR", SYM(FOR_SYM)}, + { "FORCE", SYM(FORCE_SYM)}, + { "FOREIGN", SYM(FOREIGN)}, + { "FOUND", SYM(FOUND_SYM)}, + { "FRAC_SECOND", SYM(FRAC_SECOND_SYM)}, + { "FROM", SYM(FROM)}, + { "FULL", SYM(FULL)}, + { "FULLTEXT", SYM(FULLTEXT_SYM)}, + { "FUNCTION", SYM(FUNCTION_SYM)}, + { "GEOMETRY", SYM(GEOMETRY_SYM)}, + { "GEOMETRYCOLLECTION",SYM(GEOMETRYCOLLECTION)}, + { "GET_FORMAT", SYM(GET_FORMAT)}, + { "GLOBAL", SYM(GLOBAL_SYM)}, + { "GRANT", SYM(GRANT)}, + { "GRANTS", SYM(GRANTS)}, + { "GROUP", SYM(GROUP_SYM)}, + { "HANDLER", SYM(HANDLER_SYM)}, + { "HASH", SYM(HASH_SYM)}, + { "HAVING", SYM(HAVING)}, + { "HELP", SYM(HELP_SYM)}, + { "HIGH_PRIORITY", SYM(HIGH_PRIORITY)}, + { "HOST", SYM(HOST_SYM)}, + { "HOSTS", SYM(HOSTS_SYM)}, + { "HOUR", SYM(HOUR_SYM)}, + { "HOUR_MICROSECOND", SYM(HOUR_MICROSECOND_SYM)}, + { "HOUR_MINUTE", SYM(HOUR_MINUTE_SYM)}, + { "HOUR_SECOND", SYM(HOUR_SECOND_SYM)}, + { "IDENTIFIED", SYM(IDENTIFIED_SYM)}, + { "IF", SYM(IF)}, + { "IGNORE", SYM(IGNORE_SYM)}, + { "IMPORT", SYM(IMPORT)}, + { "IN", SYM(IN_SYM)}, + { "INDEX", SYM(INDEX_SYM)}, + { "INDEXES", SYM(INDEXES)}, + { "INFILE", SYM(INFILE)}, + { "INITIAL_SIZE", SYM(INITIAL_SIZE_SYM)}, + { "INNER", SYM(INNER_SYM)}, + { "INNOBASE", SYM(INNOBASE_SYM)}, + { "INNODB", SYM(INNOBASE_SYM)}, + { "INOUT", SYM(INOUT_SYM)}, + { "INSENSITIVE", SYM(INSENSITIVE_SYM)}, + { "INSERT", SYM(INSERT)}, + { "INSERT_METHOD", SYM(INSERT_METHOD)}, + { "INSTALL", SYM(INSTALL_SYM)}, + { "INT", SYM(INT_SYM)}, + { "INT1", SYM(TINYINT)}, + { "INT2", SYM(SMALLINT)}, + { "INT3", SYM(MEDIUMINT)}, + { "INT4", SYM(INT_SYM)}, + { "INT8", SYM(BIGINT)}, + { "INTEGER", SYM(INT_SYM)}, + { "INTERVAL", SYM(INTERVAL_SYM)}, + { "INTO", SYM(INTO)}, + { "IO", SYM(IO_SYM)}, + { "IO_THREAD", SYM(RELAY_THREAD)}, + { "IPC", SYM(IPC_SYM)}, + { "IS", SYM(IS)}, + { "ISOLATION", SYM(ISOLATION)}, + { "ISSUER", SYM(ISSUER_SYM)}, + { "ITERATE", SYM(ITERATE_SYM)}, + { "INVOKER", SYM(INVOKER_SYM)}, + { "JOIN", SYM(JOIN_SYM)}, + { "KEY", SYM(KEY_SYM)}, + { "KEYS", SYM(KEYS)}, + { "KEY_BLOCK_SIZE", SYM(KEY_BLOCK_SIZE)}, + { "KILL", SYM(KILL_SYM)}, + { "LANGUAGE", SYM(LANGUAGE_SYM)}, + { "LAST", SYM(LAST_SYM)}, + { "LEADING", SYM(LEADING)}, + { "LEAVE", SYM(LEAVE_SYM)}, + { "LEAVES", SYM(LEAVES)}, + { "LEFT", SYM(LEFT)}, + { "LESS", SYM(LESS_SYM)}, + { "LEVEL", SYM(LEVEL_SYM)}, + { "LIKE", SYM(LIKE)}, + { "LIMIT", SYM(LIMIT)}, + { "LINEAR", SYM(LINEAR_SYM)}, + { "LINES", SYM(LINES)}, + { "LINESTRING", SYM(LINESTRING)}, + { "LIST", SYM(LIST_SYM)}, + { "LOAD", SYM(LOAD)}, + { "LOCAL", SYM(LOCAL_SYM)}, + { "LOCALTIME", SYM(NOW_SYM)}, + { "LOCALTIMESTAMP", SYM(NOW_SYM)}, + { "LOCK", SYM(LOCK_SYM)}, + { "LOCKS", SYM(LOCKS_SYM)}, + { "LOGFILE", SYM(LOGFILE_SYM)}, + { "LOGS", SYM(LOGS_SYM)}, + { "LONG", SYM(LONG_SYM)}, + { "LONGBLOB", SYM(LONGBLOB)}, + { "LONGTEXT", SYM(LONGTEXT)}, + { "LOOP", SYM(LOOP_SYM)}, + { "LOW_PRIORITY", SYM(LOW_PRIORITY)}, + { "MASTER", SYM(MASTER_SYM)}, + { "MASTER_CONNECT_RETRY", SYM(MASTER_CONNECT_RETRY_SYM)}, + { "MASTER_HOST", SYM(MASTER_HOST_SYM)}, + { "MASTER_LOG_FILE", SYM(MASTER_LOG_FILE_SYM)}, + { "MASTER_LOG_POS", SYM(MASTER_LOG_POS_SYM)}, + { "MASTER_PASSWORD", SYM(MASTER_PASSWORD_SYM)}, + { "MASTER_PORT", SYM(MASTER_PORT_SYM)}, + { "MASTER_SERVER_ID", SYM(MASTER_SERVER_ID_SYM)}, + { "MASTER_SSL", SYM(MASTER_SSL_SYM)}, + { "MASTER_SSL_CA", SYM(MASTER_SSL_CA_SYM)}, + { "MASTER_SSL_CAPATH",SYM(MASTER_SSL_CAPATH_SYM)}, + { "MASTER_SSL_CERT", SYM(MASTER_SSL_CERT_SYM)}, + { "MASTER_SSL_CIPHER",SYM(MASTER_SSL_CIPHER_SYM)}, + { "MASTER_SSL_KEY", SYM(MASTER_SSL_KEY_SYM)}, + { "MASTER_SSL_VERIFY_SERVER_CERT", SYM(MASTER_SSL_VERIFY_SERVER_CERT_SYM)}, + { "MASTER_USER", SYM(MASTER_USER_SYM)}, + { "MATCH", SYM(MATCH)}, + { "MAX_CONNECTIONS_PER_HOUR", SYM(MAX_CONNECTIONS_PER_HOUR)}, + { "MAX_QUERIES_PER_HOUR", SYM(MAX_QUERIES_PER_HOUR)}, + { "MAX_ROWS", SYM(MAX_ROWS)}, + { "MAX_SIZE", SYM(MAX_SIZE_SYM)}, + { "MAX_UPDATES_PER_HOUR", SYM(MAX_UPDATES_PER_HOUR)}, + { "MAX_USER_CONNECTIONS", SYM(MAX_USER_CONNECTIONS_SYM)}, + { "MAXVALUE", SYM(MAX_VALUE_SYM)}, + { "MEDIUM", SYM(MEDIUM_SYM)}, + { "MEDIUMBLOB", SYM(MEDIUMBLOB)}, + { "MEDIUMINT", SYM(MEDIUMINT)}, + { "MEDIUMTEXT", SYM(MEDIUMTEXT)}, + { "MEMORY", SYM(MEMORY_SYM)}, + { "MERGE", SYM(MERGE_SYM)}, + { "MICROSECOND", SYM(MICROSECOND_SYM)}, + { "MIDDLEINT", SYM(MEDIUMINT)}, /* For powerbuilder */ + { "MIGRATE", SYM(MIGRATE_SYM)}, + { "MINUTE", SYM(MINUTE_SYM)}, + { "MINUTE_MICROSECOND", SYM(MINUTE_MICROSECOND_SYM)}, + { "MINUTE_SECOND", SYM(MINUTE_SECOND_SYM)}, + { "MIN_ROWS", SYM(MIN_ROWS)}, + { "MOD", SYM(MOD_SYM)}, + { "MODE", SYM(MODE_SYM)}, + { "MODIFIES", SYM(MODIFIES_SYM)}, + { "MODIFY", SYM(MODIFY_SYM)}, + { "MONTH", SYM(MONTH_SYM)}, + { "MULTILINESTRING", SYM(MULTILINESTRING)}, + { "MULTIPOINT", SYM(MULTIPOINT)}, + { "MULTIPOLYGON", SYM(MULTIPOLYGON)}, + { "MUTEX", SYM(MUTEX_SYM)}, + { "NAME", SYM(NAME_SYM)}, + { "NAMES", SYM(NAMES_SYM)}, + { "NATIONAL", SYM(NATIONAL_SYM)}, + { "NATURAL", SYM(NATURAL)}, + { "NDB", SYM(NDBCLUSTER_SYM)}, + { "NDBCLUSTER", SYM(NDBCLUSTER_SYM)}, + { "NCHAR", SYM(NCHAR_SYM)}, + { "NEW", SYM(NEW_SYM)}, + { "NEXT", SYM(NEXT_SYM)}, + { "NO", SYM(NO_SYM)}, + { "NO_WAIT", SYM(NO_WAIT_SYM)}, + { "NODEGROUP", SYM(NODEGROUP_SYM)}, + { "NONE", SYM(NONE_SYM)}, + { "NOT", SYM(NOT_SYM)}, + { "NO_WRITE_TO_BINLOG", SYM(NO_WRITE_TO_BINLOG)}, + { "NULL", SYM(NULL_SYM)}, + { "NUMERIC", SYM(NUMERIC_SYM)}, + { "NVARCHAR", SYM(NVARCHAR_SYM)}, + { "OFFSET", SYM(OFFSET_SYM)}, + { "OLD_PASSWORD", SYM(OLD_PASSWORD)}, + { "ON", SYM(ON)}, + { "ONE", SYM(ONE_SYM)}, + { "ONE_SHOT", SYM(ONE_SHOT_SYM)}, + { "OPEN", SYM(OPEN_SYM)}, + { "OPTIMIZE", SYM(OPTIMIZE)}, + { "OPTIONS", SYM(OPTIONS_SYM)}, + { "OPTION", SYM(OPTION)}, + { "OPTIONALLY", SYM(OPTIONALLY)}, + { "OR", SYM(OR_SYM)}, + { "ORDER", SYM(ORDER_SYM)}, + { "OUT", SYM(OUT_SYM)}, + { "OUTER", SYM(OUTER)}, + { "OUTFILE", SYM(OUTFILE)}, + { "OWNER", SYM(OWNER_SYM)}, + { "PACK_KEYS", SYM(PACK_KEYS_SYM)}, + { "PARSER", SYM(PARSER_SYM)}, + { "PAGE", SYM(PAGE_SYM)}, + { "PARTIAL", SYM(PARTIAL)}, + { "PARTITION", SYM(PARTITION_SYM)}, + { "PARTITIONING", SYM(PARTITIONING_SYM)}, + { "PARTITIONS", SYM(PARTITIONS_SYM)}, + { "PASSWORD", SYM(PASSWORD)}, + { "PHASE", SYM(PHASE_SYM)}, + { "PLUGIN", SYM(PLUGIN_SYM)}, + { "PLUGINS", SYM(PLUGINS_SYM)}, + { "POINT", SYM(POINT_SYM)}, + { "POLYGON", SYM(POLYGON)}, + { "PORT", SYM(PORT_SYM)}, + { "PRECISION", SYM(PRECISION)}, + { "PREPARE", SYM(PREPARE_SYM)}, + { "PRESERVE", SYM(PRESERVE_SYM)}, + { "PREV", SYM(PREV_SYM)}, + { "PRIMARY", SYM(PRIMARY_SYM)}, + { "PRIVILEGES", SYM(PRIVILEGES)}, + { "PROCEDURE", SYM(PROCEDURE)}, + { "PROCESS" , SYM(PROCESS)}, + { "PROCESSLIST", SYM(PROCESSLIST_SYM)}, + { "PROFILE", SYM(PROFILE_SYM)}, + { "PROFILES", SYM(PROFILES_SYM)}, + { "PURGE", SYM(PURGE)}, + { "QUARTER", SYM(QUARTER_SYM)}, + { "QUERY", SYM(QUERY_SYM)}, + { "QUICK", SYM(QUICK)}, + { "RANGE", SYM(RANGE_SYM)}, + { "READ", SYM(READ_SYM)}, + { "READ_ONLY", SYM(READ_ONLY_SYM)}, + { "READ_WRITE", SYM(READ_WRITE_SYM)}, + { "READS", SYM(READS_SYM)}, + { "REAL", SYM(REAL)}, + { "REBUILD", SYM(REBUILD_SYM)}, + { "RECOVER", SYM(RECOVER_SYM)}, + { "REDO_BUFFER_SIZE", SYM(REDO_BUFFER_SIZE_SYM)}, + { "REDOFILE", SYM(REDOFILE_SYM)}, + { "REDUNDANT", SYM(REDUNDANT_SYM)}, + { "REFERENCES", SYM(REFERENCES)}, + { "REGEXP", SYM(REGEXP)}, + { "RELAY_LOG_FILE", SYM(RELAY_LOG_FILE_SYM)}, + { "RELAY_LOG_POS", SYM(RELAY_LOG_POS_SYM)}, + { "RELAY_THREAD", SYM(RELAY_THREAD)}, + { "RELEASE", SYM(RELEASE_SYM)}, + { "RELOAD", SYM(RELOAD)}, + { "REMOVE", SYM(REMOVE_SYM)}, + { "RENAME", SYM(RENAME)}, + { "REORGANIZE", SYM(REORGANIZE_SYM)}, + { "REPAIR", SYM(REPAIR)}, + { "REPEATABLE", SYM(REPEATABLE_SYM)}, + { "REPLACE", SYM(REPLACE)}, + { "REPLICATION", SYM(REPLICATION)}, + { "REPEAT", SYM(REPEAT_SYM)}, + { "REQUIRE", SYM(REQUIRE_SYM)}, + { "RESET", SYM(RESET_SYM)}, + { "RESTORE", SYM(RESTORE_SYM)}, + { "RESTRICT", SYM(RESTRICT)}, + { "RESUME", SYM(RESUME_SYM)}, + { "RETURN", SYM(RETURN_SYM)}, + { "RETURNS", SYM(RETURNS_SYM)}, + { "REVOKE", SYM(REVOKE)}, + { "RIGHT", SYM(RIGHT)}, + { "RLIKE", SYM(REGEXP)}, /* Like in mSQL2 */ + { "ROLLBACK", SYM(ROLLBACK_SYM)}, + { "ROLLUP", SYM(ROLLUP_SYM)}, + { "ROUTINE", SYM(ROUTINE_SYM)}, + { "ROW", SYM(ROW_SYM)}, + { "ROWS", SYM(ROWS_SYM)}, + { "ROW_FORMAT", SYM(ROW_FORMAT_SYM)}, + { "RTREE", SYM(RTREE_SYM)}, + { "SAVEPOINT", SYM(SAVEPOINT_SYM)}, + { "SCHEDULE", SYM(SCHEDULE_SYM)}, + { "SCHEMA", SYM(DATABASE)}, + { "SCHEMAS", SYM(DATABASES)}, + { "SECOND", SYM(SECOND_SYM)}, + { "SECOND_MICROSECOND", SYM(SECOND_MICROSECOND_SYM)}, + { "SECURITY", SYM(SECURITY_SYM)}, + { "SELECT", SYM(SELECT_SYM)}, + { "SENSITIVE", SYM(SENSITIVE_SYM)}, + { "SEPARATOR", SYM(SEPARATOR_SYM)}, + { "SERIAL", SYM(SERIAL_SYM)}, + { "SERIALIZABLE", SYM(SERIALIZABLE_SYM)}, + { "SESSION", SYM(SESSION_SYM)}, + { "SERVER", SYM(SERVER_SYM)}, + { "SET", SYM(SET)}, + { "SHARE", SYM(SHARE_SYM)}, + { "SHOW", SYM(SHOW)}, + { "SHUTDOWN", SYM(SHUTDOWN)}, + { "SIGNED", SYM(SIGNED_SYM)}, + { "SIMPLE", SYM(SIMPLE_SYM)}, + { "SLAVE", SYM(SLAVE)}, + { "SNAPSHOT", SYM(SNAPSHOT_SYM)}, + { "SMALLINT", SYM(SMALLINT)}, + { "SOCKET", SYM(SOCKET_SYM)}, + { "SOME", SYM(ANY_SYM)}, + { "SONAME", SYM(SONAME_SYM)}, + { "SOUNDS", SYM(SOUNDS_SYM)}, + { "SOURCE", SYM(SOURCE_SYM)}, + { "SPATIAL", SYM(SPATIAL_SYM)}, + { "SPECIFIC", SYM(SPECIFIC_SYM)}, + { "SQL", SYM(SQL_SYM)}, + { "SQLEXCEPTION", SYM(SQLEXCEPTION_SYM)}, + { "SQLSTATE", SYM(SQLSTATE_SYM)}, + { "SQLWARNING", SYM(SQLWARNING_SYM)}, + { "SQL_BIG_RESULT", SYM(SQL_BIG_RESULT)}, + { "SQL_BUFFER_RESULT", SYM(SQL_BUFFER_RESULT)}, + { "SQL_CACHE", SYM(SQL_CACHE_SYM)}, + { "SQL_CALC_FOUND_ROWS", SYM(SQL_CALC_FOUND_ROWS)}, + { "SQL_NO_CACHE", SYM(SQL_NO_CACHE_SYM)}, + { "INFINIDB_ORDERED", SYM(INFINIDB_ORDERED_SYM)}, + { "SQL_SMALL_RESULT", SYM(SQL_SMALL_RESULT)}, + { "SQL_THREAD", SYM(SQL_THREAD)}, + { "SQL_TSI_FRAC_SECOND", SYM(FRAC_SECOND_SYM)}, + { "SQL_TSI_SECOND", SYM(SECOND_SYM)}, + { "SQL_TSI_MINUTE", SYM(MINUTE_SYM)}, + { "SQL_TSI_HOUR", SYM(HOUR_SYM)}, + { "SQL_TSI_DAY", SYM(DAY_SYM)}, + { "SQL_TSI_WEEK", SYM(WEEK_SYM)}, + { "SQL_TSI_MONTH", SYM(MONTH_SYM)}, + { "SQL_TSI_QUARTER", SYM(QUARTER_SYM)}, + { "SQL_TSI_YEAR", SYM(YEAR_SYM)}, + { "SSL", SYM(SSL_SYM)}, + { "START", SYM(START_SYM)}, + { "STARTING", SYM(STARTING)}, + { "STARTS", SYM(STARTS_SYM)}, + { "STATUS", SYM(STATUS_SYM)}, + { "STOP", SYM(STOP_SYM)}, + { "STORAGE", SYM(STORAGE_SYM)}, + { "STRAIGHT_JOIN", SYM(STRAIGHT_JOIN)}, + { "STRING", SYM(STRING_SYM)}, + { "SUBJECT", SYM(SUBJECT_SYM)}, + { "SUBPARTITION", SYM(SUBPARTITION_SYM)}, + { "SUBPARTITIONS", SYM(SUBPARTITIONS_SYM)}, + { "SUPER", SYM(SUPER_SYM)}, + { "SUSPEND", SYM(SUSPEND_SYM)}, + { "SWAPS", SYM(SWAPS_SYM)}, + { "SWITCHES", SYM(SWITCHES_SYM)}, + { "TABLE", SYM(TABLE_SYM)}, + { "TABLES", SYM(TABLES)}, + { "TABLESPACE", SYM(TABLESPACE)}, + { "TABLE_CHECKSUM", SYM(TABLE_CHECKSUM_SYM)}, + { "TEMPORARY", SYM(TEMPORARY)}, + { "TEMPTABLE", SYM(TEMPTABLE_SYM)}, + { "TERMINATED", SYM(TERMINATED)}, + { "TEXT", SYM(TEXT_SYM)}, + { "THAN", SYM(THAN_SYM)}, + { "THEN", SYM(THEN_SYM)}, + { "TIME", SYM(TIME_SYM)}, + { "TIMESTAMP", SYM(TIMESTAMP)}, + { "TIMESTAMPADD", SYM(TIMESTAMP_ADD)}, + { "TIMESTAMPDIFF", SYM(TIMESTAMP_DIFF)}, + { "TINYBLOB", SYM(TINYBLOB)}, + { "TINYINT", SYM(TINYINT)}, + { "TINYTEXT", SYM(TINYTEXT)}, + { "TO", SYM(TO_SYM)}, + { "TRAILING", SYM(TRAILING)}, + { "TRANSACTION", SYM(TRANSACTION_SYM)}, + { "TRIGGER", SYM(TRIGGER_SYM)}, + { "TRIGGERS", SYM(TRIGGERS_SYM)}, + { "TRUE", SYM(TRUE_SYM)}, + { "TRUNCATE", SYM(TRUNCATE_SYM)}, + { "TYPE", SYM(TYPE_SYM)}, + { "TYPES", SYM(TYPES_SYM)}, + { "UNCOMMITTED", SYM(UNCOMMITTED_SYM)}, + { "UNDEFINED", SYM(UNDEFINED_SYM)}, + { "UNDO_BUFFER_SIZE", SYM(UNDO_BUFFER_SIZE_SYM)}, + { "UNDOFILE", SYM(UNDOFILE_SYM)}, + { "UNDO", SYM(UNDO_SYM)}, + { "UNICODE", SYM(UNICODE_SYM)}, + { "UNION", SYM(UNION_SYM)}, + { "UNIQUE", SYM(UNIQUE_SYM)}, + { "UNKNOWN", SYM(UNKNOWN_SYM)}, + { "UNLOCK", SYM(UNLOCK_SYM)}, + { "UNINSTALL", SYM(UNINSTALL_SYM)}, + { "UNSIGNED", SYM(UNSIGNED)}, + { "UNTIL", SYM(UNTIL_SYM)}, + { "UPDATE", SYM(UPDATE_SYM)}, + { "UPGRADE", SYM(UPGRADE_SYM)}, + { "USAGE", SYM(USAGE)}, + { "USE", SYM(USE_SYM)}, + { "USER", SYM(USER)}, + { "USER_RESOURCES", SYM(RESOURCES)}, + { "USE_FRM", SYM(USE_FRM)}, + { "USING", SYM(USING)}, + { "UTC_DATE", SYM(UTC_DATE_SYM)}, + { "UTC_TIME", SYM(UTC_TIME_SYM)}, + { "UTC_TIMESTAMP", SYM(UTC_TIMESTAMP_SYM)}, + { "VALUE", SYM(VALUE_SYM)}, + { "VALUES", SYM(VALUES)}, + { "VARBINARY", SYM(VARBINARY)}, + { "VARCHAR", SYM(VARCHAR)}, + { "VARCHARACTER", SYM(VARCHAR)}, + { "VARIABLES", SYM(VARIABLES)}, + { "VARYING", SYM(VARYING)}, + { "WAIT", SYM(WAIT_SYM)}, + { "WARNINGS", SYM(WARNINGS)}, + { "WEEK", SYM(WEEK_SYM)}, + { "WHEN", SYM(WHEN_SYM)}, + { "WHERE", SYM(WHERE)}, + { "WHILE", SYM(WHILE_SYM)}, + { "VIEW", SYM(VIEW_SYM)}, + { "WITH", SYM(WITH)}, + { "WORK", SYM(WORK_SYM)}, + { "WRAPPER", SYM(WRAPPER_SYM)}, + { "WRITE", SYM(WRITE_SYM)}, + { "X509", SYM(X509_SYM)}, + { "XOR", SYM(XOR)}, + { "XA", SYM(XA_SYM)}, + { "YEAR", SYM(YEAR_SYM)}, + { "YEAR_MONTH", SYM(YEAR_MONTH_SYM)}, + { "ZEROFILL", SYM(ZEROFILL)}, + { "||", SYM(OR_OR_SYM)} +}; + + +static SYMBOL sql_functions[] = { + { "ADDDATE", SYM(ADDDATE_SYM)}, + { "BIT_AND", SYM(BIT_AND)}, + { "BIT_OR", SYM(BIT_OR)}, + { "BIT_XOR", SYM(BIT_XOR)}, + { "CAST", SYM(CAST_SYM)}, + { "COUNT", SYM(COUNT_SYM)}, + { "CURDATE", SYM(CURDATE)}, + { "CURTIME", SYM(CURTIME)}, + { "DATE_ADD", SYM(DATE_ADD_INTERVAL)}, + { "DATE_SUB", SYM(DATE_SUB_INTERVAL)}, + { "EXTRACT", SYM(EXTRACT_SYM)}, + { "GROUP_CONCAT", SYM(GROUP_CONCAT_SYM)}, + { "MAX", SYM(MAX_SYM)}, + { "MID", SYM(SUBSTRING)}, /* unireg function */ + { "MIN", SYM(MIN_SYM)}, + { "NOW", SYM(NOW_SYM)}, + { "POSITION", SYM(POSITION_SYM)}, + { "SESSION_USER", SYM(USER)}, + { "STD", SYM(STD_SYM)}, + { "STDDEV", SYM(STD_SYM)}, + { "STDDEV_POP", SYM(STD_SYM)}, + { "STDDEV_SAMP", SYM(STDDEV_SAMP_SYM)}, + { "SUBDATE", SYM(SUBDATE_SYM)}, + { "SUBSTR", SYM(SUBSTRING)}, + { "SUBSTRING", SYM(SUBSTRING)}, + { "SUM", SYM(SUM_SYM)}, + { "SYSDATE", SYM(SYSDATE)}, + { "SYSTEM_USER", SYM(USER)}, + { "TRIM", SYM(TRIM)}, + { "VARIANCE", SYM(VARIANCE_SYM)}, + { "VAR_POP", SYM(VARIANCE_SYM)}, + { "VAR_SAMP", SYM(VAR_SAMP_SYM)}, +}; diff --git a/dbcon/mysql/libcalmysql.rc b/dbcon/mysql/libcalmysql.rc deleted file mode 100644 index 46f9a070..00000000 --- a/dbcon/mysql/libcalmysql.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB MySQL Connector API" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "libcalmysql" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "libcalmysql.dll" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/dbcon/mysql/libcalmysql.vcxproj b/dbcon/mysql/libcalmysql.vcxproj deleted file mode 100644 index ae0a69b9..00000000 --- a/dbcon/mysql/libcalmysql.vcxproj +++ /dev/null @@ -1,401 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {0049D0FD-6479-442C-B53A-F4C7FF7AD34F} - libcalmysql - - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - true - - - DynamicLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - .dll - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - false - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - false - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - false - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)../../mysql\include;$(SolutionDir)../../mysql\extra\yassl\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)../../mysql\sql;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - mysqld.lib;ws2_32.lib;iphlpapi.lib - C:\InfiniDB\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)../../mysql\include;$(SolutionDir)../../mysql\extra\yassl\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)../../mysql\sql;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - true - - - mysqld.lib;ws2_32.lib;iphlpapi.lib - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;$(SolutionDir)../../mysql\sql\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - false - true - 2000000 - 10000 - 2000000 - 10000 - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)../../mysql\include;$(SolutionDir)../../mysql\extra\yassl\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)../../mysql\sql;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_IDB_COMPRESSION;SKIP_VIEW;SKIP_INSERT_SELECT;SKIP_AUTOI;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - mysqld.lib;ws2_32.lib;iphlpapi.lib - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\sql\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)../../mysql\include;$(SolutionDir)../../mysql\extra\yassl\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)../../mysql\sql;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_IDB_COMPRESSION;SKIP_VIEW;SKIP_INSERT_SELECT;SKIP_AUTOI;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - true - - - mysqld.lib;ws2_32.lib;iphlpapi.lib - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;$(SolutionDir)../../mysql\sql\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - false - true - 2000000 - 10000 - 2000000 - 10000 - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB MySQL COnnector API" $(SolutionDir)..\..x64\Release\libcalmysql.dll - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)../../mysql\include;$(SolutionDir)../../mysql\extra\yassl\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)../../mysql\sql;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - mysqld.lib;ws2_32.lib;iphlpapi.lib - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\sql\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)../../mysql\include;$(SolutionDir)../../mysql\extra\yassl\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)../../mysql\sql;$(SolutionDir)..\utils\startup;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - false - - - true - - - mysqld.lib;ws2_32.lib;iphlpapi.lib - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;$(SolutionDir)../../mysql\sql\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - false - false - 2000000 - 10000 - 2000000 - 10000 - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB MySQL COnnector API" $(SolutionDir)..\..\x64\EnterpriseRelease\libcalmysql.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {0bbaeacb-3336-4406-acfb-255669a3b9cf} - - - {3238cd73-8ffd-44a7-aa5f-815beef8f402} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {033c6cba-d984-483f-adc8-825be20a699d} - - - {b9045bca-0955-4c5e-bca4-5ee516838119} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - - - - \ No newline at end of file diff --git a/dbcon/mysql/libcalmysql.vcxproj.filters b/dbcon/mysql/libcalmysql.vcxproj.filters deleted file mode 100644 index faadb073..00000000 --- a/dbcon/mysql/libcalmysql.vcxproj.filters +++ /dev/null @@ -1,116 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/dbcon/mysql/log.cc b/dbcon/mysql/log.cc new file mode 100644 index 00000000..02f577d2 --- /dev/null +++ b/dbcon/mysql/log.cc @@ -0,0 +1,5713 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/** + @file + + @brief + logging of commands + + @todo + Abort logging when we get an error in reading or writing log files +*/ + +#include "mysql_priv.h" +#include "sql_repl.h" +#include "rpl_filter.h" +#include "rpl_rli.h" + +#include +#include +#include // For test_if_number + +#ifdef __NT__ +#include "message.h" +#endif + +#include + +/* max size of the log message */ +#define MAX_LOG_BUFFER_SIZE 1024 +#define MAX_USER_HOST_SIZE 512 +#define MAX_TIME_SIZE 32 +#define MY_OFF_T_UNDEF (~(my_off_t)0UL) + +#define FLAGSTR(V,F) ((V)&(F)?#F" ":"") + +LOGGER logger; + +MYSQL_BIN_LOG mysql_bin_log; +ulong sync_binlog_counter= 0; + +static bool test_if_number(const char *str, + long *res, bool allow_wildcards); +static int binlog_init(void *p); +static int binlog_close_connection(handlerton *hton, THD *thd); +static int binlog_savepoint_set(handlerton *hton, THD *thd, void *sv); +static int binlog_savepoint_rollback(handlerton *hton, THD *thd, void *sv); +static int binlog_commit(handlerton *hton, THD *thd, bool all); +static int binlog_rollback(handlerton *hton, THD *thd, bool all); +static int binlog_prepare(handlerton *hton, THD *thd, bool all); + +/** + Silence all errors and warnings reported when performing a write + to a log table. + Errors and warnings are not reported to the client or SQL exception + handlers, so that the presence of logging does not interfere and affect + the logic of an application. +*/ +class Silence_log_table_errors : public Internal_error_handler +{ + char m_message[MYSQL_ERRMSG_SIZE]; +public: + Silence_log_table_errors() + { + m_message[0]= '\0'; + } + + virtual ~Silence_log_table_errors() {} + + virtual bool handle_error(uint sql_errno, const char *message, + MYSQL_ERROR::enum_warning_level level, + THD *thd); + const char *message() const { return m_message; } +}; + +bool +Silence_log_table_errors::handle_error(uint /* sql_errno */, + const char *message_arg, + MYSQL_ERROR::enum_warning_level /* level */, + THD * /* thd */) +{ + strmake(m_message, message_arg, sizeof(m_message)-1); + return TRUE; +} + + +sql_print_message_func sql_print_message_handlers[3] = +{ + sql_print_information, + sql_print_warning, + sql_print_error +}; + + +char *make_default_log_name(char *buff,const char* log_ext) +{ + strmake(buff, pidfile_name, FN_REFLEN-5); + return fn_format(buff, buff, mysql_data_home, log_ext, + MYF(MY_UNPACK_FILENAME|MY_REPLACE_EXT)); +} + +/* + Helper class to hold a mutex for the duration of the + block. + + Eliminates the need for explicit unlocking of mutexes on, e.g., + error returns. On passing a null pointer, the sentry will not do + anything. + */ +class Mutex_sentry +{ +public: + Mutex_sentry(pthread_mutex_t *mutex) + : m_mutex(mutex) + { + if (m_mutex) + pthread_mutex_lock(mutex); + } + + ~Mutex_sentry() + { + if (m_mutex) + pthread_mutex_unlock(m_mutex); +#ifndef DBUG_OFF + m_mutex= 0; +#endif + } + +private: + pthread_mutex_t *m_mutex; + + // It's not allowed to copy this object in any way + Mutex_sentry(Mutex_sentry const&); + void operator=(Mutex_sentry const&); +}; + +/* + Helper class to store binary log transaction data. +*/ +class binlog_trx_data { +public: + binlog_trx_data() + : at_least_one_stmt(0), incident(FALSE), m_pending(0), + before_stmt_pos(MY_OFF_T_UNDEF) + { + trans_log.end_of_file= max_binlog_cache_size; + } + + ~binlog_trx_data() + { + DBUG_ASSERT(pending() == NULL); + close_cached_file(&trans_log); + } + + my_off_t position() const { + return my_b_tell(&trans_log); + } + + bool empty() const + { + return pending() == NULL && my_b_tell(&trans_log) == 0; + } + + /* + Truncate the transaction cache to a certain position. This + includes deleting the pending event. + */ + void truncate(my_off_t pos) + { + DBUG_PRINT("info", ("truncating to position %lu", (ulong) pos)); + DBUG_PRINT("info", ("before_stmt_pos=%lu", (ulong) pos)); + delete pending(); + set_pending(0); + reinit_io_cache(&trans_log, WRITE_CACHE, pos, 0, 0); + trans_log.end_of_file= max_binlog_cache_size; + if (pos < before_stmt_pos) + before_stmt_pos= MY_OFF_T_UNDEF; + + /* + The only valid positions that can be truncated to are at the + beginning of a statement. We are relying on this fact to be able + to set the at_least_one_stmt flag correctly. In other word, if + we are truncating to the beginning of the transaction cache, + there will be no statements in the cache, otherwhise, we will + have at least one statement in the transaction cache. + */ + at_least_one_stmt= (pos > 0); + } + + /* + Reset the entire contents of the transaction cache, emptying it + completely. + */ + void reset() { + if (!empty()) + truncate(0); + before_stmt_pos= MY_OFF_T_UNDEF; + incident= FALSE; + trans_log.end_of_file= max_binlog_cache_size; + DBUG_ASSERT(empty()); + } + + Rows_log_event *pending() const + { + return m_pending; + } + + void set_pending(Rows_log_event *const pending) + { + m_pending= pending; + } + + IO_CACHE trans_log; // The transaction cache + + void set_incident(void) + { + incident= TRUE; + } + + bool has_incident(void) + { + return(incident); + } + + /** + Boolean that is true if there is at least one statement in the + transaction cache. + */ + bool at_least_one_stmt; + bool incident; + +private: + /* + Pending binrows event. This event is the event where the rows are + currently written. + */ + Rows_log_event *m_pending; + +public: + /* + Binlog position before the start of the current statement. + */ + my_off_t before_stmt_pos; +}; + +handlerton *binlog_hton; + +bool LOGGER::is_log_table_enabled(uint log_table_type) +{ + switch (log_table_type) { + case QUERY_LOG_SLOW: + return (table_log_handler != NULL) && opt_slow_log; + case QUERY_LOG_GENERAL: + return (table_log_handler != NULL) && opt_log ; + default: + DBUG_ASSERT(0); + return FALSE; /* make compiler happy */ + } +} + + +/* Check if a given table is opened log table */ +int check_if_log_table(uint db_len, const char *db, uint table_name_len, + const char *table_name, uint check_if_opened) +{ + if (db_len == 5 && + !(lower_case_table_names ? + my_strcasecmp(system_charset_info, db, "mysql") : + strcmp(db, "mysql"))) + { + if (table_name_len == 11 && !(lower_case_table_names ? + my_strcasecmp(system_charset_info, + table_name, "general_log") : + strcmp(table_name, "general_log"))) + { + if (!check_if_opened || logger.is_log_table_enabled(QUERY_LOG_GENERAL)) + return QUERY_LOG_GENERAL; + return 0; + } + + if (table_name_len == 8 && !(lower_case_table_names ? + my_strcasecmp(system_charset_info, table_name, "slow_log") : + strcmp(table_name, "slow_log"))) + { + if (!check_if_opened || logger.is_log_table_enabled(QUERY_LOG_SLOW)) + return QUERY_LOG_SLOW; + return 0; + } + } + return 0; +} + + +Log_to_csv_event_handler::Log_to_csv_event_handler() +{ +} + + +Log_to_csv_event_handler::~Log_to_csv_event_handler() +{ +} + + +void Log_to_csv_event_handler::cleanup() +{ + logger.is_log_tables_initialized= FALSE; +} + +/* log event handlers */ + +/** + Log command to the general log table + + Log given command to the general log table. + + @param event_time command start timestamp + @param user_host the pointer to the string with user@host info + @param user_host_len length of the user_host string. this is computed + once and passed to all general log event handlers + @param thread_id Id of the thread, issued a query + @param command_type the type of the command being logged + @param command_type_len the length of the string above + @param sql_text the very text of the query being executed + @param sql_text_len the length of sql_text string + + + @return This function attempts to never call my_error(). This is + necessary, because general logging happens already after a statement + status has been sent to the client, so the client can not see the + error anyway. Besides, the error is not related to the statement + being executed and is internal, and thus should be handled + internally (@todo: how?). + If a write to the table has failed, the function attempts to + write to a short error message to the file. The failure is also + indicated in the return value. + + @retval FALSE OK + @retval TRUE error occured +*/ + +bool Log_to_csv_event_handler:: + log_general(THD *thd, time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len, + CHARSET_INFO *client_cs) +{ + TABLE_LIST table_list; + TABLE *table; + bool result= TRUE; + bool need_close= FALSE; + bool need_pop= FALSE; + bool need_rnd_end= FALSE; + uint field_index; + Silence_log_table_errors error_handler; + Open_tables_state open_tables_backup; + ulonglong save_thd_options; + bool save_time_zone_used; + + /* + CSV uses TIME_to_timestamp() internally if table needs to be repaired + which will set thd->time_zone_used + */ + save_time_zone_used= thd->time_zone_used; + + save_thd_options= thd->options; + thd->options&= ~OPTION_BIN_LOG; + + bzero(& table_list, sizeof(TABLE_LIST)); + table_list.alias= table_list.table_name= GENERAL_LOG_NAME.str; + table_list.table_name_length= GENERAL_LOG_NAME.length; + + table_list.lock_type= TL_WRITE_CONCURRENT_INSERT; + + table_list.db= MYSQL_SCHEMA_NAME.str; + table_list.db_length= MYSQL_SCHEMA_NAME.length; + + /* + 1) open_performance_schema_table generates an error of the + table can not be opened or is corrupted. + 2) "INSERT INTO general_log" can generate warning sometimes. + + Suppress these warnings and errors, they can't be dealt with + properly anyway. + + QQ: this problem needs to be studied in more detail. + Comment this 2 lines and run "cast.test" to see what's happening. + */ + thd->push_internal_handler(& error_handler); + need_pop= TRUE; + + if (!(table= open_performance_schema_table(thd, & table_list, + & open_tables_backup))) + goto err; + + need_close= TRUE; + + if (table->file->extra(HA_EXTRA_MARK_AS_LOG_TABLE) || + table->file->ha_rnd_init(0)) + goto err; + + need_rnd_end= TRUE; + + /* Honor next number columns if present */ + table->next_number_field= table->found_next_number_field; + + /* + NOTE: we do not call restore_record() here, as all fields are + filled by the Logger (=> no need to load default ones). + */ + + /* + We do not set a value for table->field[0], as it will use + default value (which is CURRENT_TIMESTAMP). + */ + + /* check that all columns exist */ + if (table->s->fields < 6) + goto err; + + DBUG_ASSERT(table->field[0]->type() == MYSQL_TYPE_TIMESTAMP); + + ((Field_timestamp*) table->field[0])->store_timestamp((my_time_t) + event_time); + + /* do a write */ + if (table->field[1]->store(user_host, user_host_len, client_cs) || + table->field[2]->store((longlong) thread_id, TRUE) || + table->field[3]->store((longlong) server_id, TRUE) || + table->field[4]->store(command_type, command_type_len, client_cs)) + goto err; + + /* + A positive return value in store() means truncation. + Still logging a message in the log in this case. + */ + table->field[5]->flags|= FIELDFLAG_HEX_ESCAPE; + if (table->field[5]->store(sql_text, sql_text_len, client_cs) < 0) + goto err; + + /* mark all fields as not null */ + table->field[1]->set_notnull(); + table->field[2]->set_notnull(); + table->field[3]->set_notnull(); + table->field[4]->set_notnull(); + table->field[5]->set_notnull(); + + /* Set any extra columns to their default values */ + for (field_index= 6 ; field_index < table->s->fields ; field_index++) + { + table->field[field_index]->set_default(); + } + + /* log table entries are not replicated */ + if (table->file->ha_write_row(table->record[0])) + goto err; + + result= FALSE; + +err: + if (result && !thd->killed) + sql_print_error("Failed to write to mysql.general_log: %s", + error_handler.message()); + + if (need_rnd_end) + { + table->file->ha_rnd_end(); + table->file->ha_release_auto_increment(); + } + if (need_pop) + thd->pop_internal_handler(); + if (need_close) + close_performance_schema_table(thd, & open_tables_backup); + + thd->options= save_thd_options; + thd->time_zone_used= save_time_zone_used; + return result; +} + + +/* + Log a query to the slow log table + + SYNOPSIS + log_slow() + thd THD of the query + current_time current timestamp + query_start_arg command start timestamp + user_host the pointer to the string with user@host info + user_host_len length of the user_host string. this is computed once + and passed to all general log event handlers + query_time Amount of time the query took to execute (in microseconds) + lock_time Amount of time the query was locked (in microseconds) + is_command The flag, which determines, whether the sql_text is a + query or an administrator command (these are treated + differently by the old logging routines) + sql_text the very text of the query or administrator command + processed + sql_text_len the length of sql_text string + + DESCRIPTION + + Log a query to the slow log table + + RETURN + FALSE - OK + TRUE - error occured +*/ + +bool Log_to_csv_event_handler:: + log_slow(THD *thd, time_t current_time, time_t query_start_arg, + const char *user_host, uint user_host_len, + ulonglong query_utime, ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len) +{ + TABLE_LIST table_list; + TABLE *table; + bool result= TRUE; + bool need_close= FALSE; + bool need_rnd_end= FALSE; + Silence_log_table_errors error_handler; + Open_tables_state open_tables_backup; + CHARSET_INFO *client_cs= thd->variables.character_set_client; + bool save_time_zone_used; + DBUG_ENTER("Log_to_csv_event_handler::log_slow"); + + thd->push_internal_handler(& error_handler); + /* + CSV uses TIME_to_timestamp() internally if table needs to be repaired + which will set thd->time_zone_used + */ + save_time_zone_used= thd->time_zone_used; + + bzero(& table_list, sizeof(TABLE_LIST)); + table_list.alias= table_list.table_name= SLOW_LOG_NAME.str; + table_list.table_name_length= SLOW_LOG_NAME.length; + + table_list.lock_type= TL_WRITE_CONCURRENT_INSERT; + + table_list.db= MYSQL_SCHEMA_NAME.str; + table_list.db_length= MYSQL_SCHEMA_NAME.length; + + if (!(table= open_performance_schema_table(thd, & table_list, + & open_tables_backup))) + goto err; + + need_close= TRUE; + + if (table->file->extra(HA_EXTRA_MARK_AS_LOG_TABLE) || + table->file->ha_rnd_init(0)) + goto err; + + need_rnd_end= TRUE; + + /* Honor next number columns if present */ + table->next_number_field= table->found_next_number_field; + + restore_record(table, s->default_values); // Get empty record + + /* check that all columns exist */ + if (table->s->fields < 11) + goto err; + + /* store the time and user values */ + DBUG_ASSERT(table->field[0]->type() == MYSQL_TYPE_TIMESTAMP); + ((Field_timestamp*) table->field[0])->store_timestamp((my_time_t) + current_time); + if (table->field[1]->store(user_host, user_host_len, client_cs)) + goto err; + + if (query_start_arg) + { + longlong query_time= (longlong) (query_utime/1000000); + longlong lock_time= (longlong) (lock_utime/1000000); + /* + A TIME field can not hold the full longlong range; query_time or + lock_time may be truncated without warning here, if greater than + 839 hours (~35 days) + */ + MYSQL_TIME t; + t.neg= 0; + + /* fill in query_time field */ + calc_time_from_sec(&t, (long) min(query_time, (longlong) TIME_MAX_VALUE_SECONDS), 0); + if (table->field[2]->store_time(&t, MYSQL_TIMESTAMP_TIME)) + goto err; + /* lock_time */ + calc_time_from_sec(&t, (long) min(lock_time, (longlong) TIME_MAX_VALUE_SECONDS), 0); + if (table->field[3]->store_time(&t, MYSQL_TIMESTAMP_TIME)) + goto err; + /* rows_sent */ + if (table->field[4]->store((longlong) thd->sent_row_count, TRUE)) + goto err; + /* rows_examined */ + if (table->field[5]->store((longlong) thd->examined_row_count, TRUE)) + goto err; + } + else + { + table->field[2]->set_null(); + table->field[3]->set_null(); + table->field[4]->set_null(); + table->field[5]->set_null(); + } + /* fill database field */ + if (thd->db) + { + if (table->field[6]->store(thd->db, thd->db_length, client_cs)) + goto err; + table->field[6]->set_notnull(); + } + + if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt) + { + if (table-> + field[7]->store((longlong) + thd->first_successful_insert_id_in_prev_stmt_for_binlog, + TRUE)) + goto err; + table->field[7]->set_notnull(); + } + + /* + Set value if we do an insert on autoincrement column. Note that for + some engines (those for which get_auto_increment() does not leave a + table lock until the statement ends), this is just the first value and + the next ones used may not be contiguous to it. + */ + if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0) + { + if (table-> + field[8]->store((longlong) + thd->auto_inc_intervals_in_cur_stmt_for_binlog.minimum(), TRUE)) + goto err; + table->field[8]->set_notnull(); + } + + if (table->field[9]->store((longlong) server_id, TRUE)) + goto err; + table->field[9]->set_notnull(); + + /* + Column sql_text. + A positive return value in store() means truncation. + Still logging a message in the log in this case. + */ + if (table->field[10]->store(sql_text, sql_text_len, client_cs) < 0) + goto err; + + /* log table entries are not replicated */ + if (table->file->ha_write_row(table->record[0])) + goto err; + + result= FALSE; + +err: + thd->pop_internal_handler(); + + if (result && !thd->killed) + sql_print_error("Failed to write to mysql.slow_log: %s", + error_handler.message()); + + if (need_rnd_end) + { + table->file->ha_rnd_end(); + table->file->ha_release_auto_increment(); + } + if (need_close) + close_performance_schema_table(thd, & open_tables_backup); + thd->time_zone_used= save_time_zone_used; + DBUG_RETURN(result); +} + +int Log_to_csv_event_handler:: + activate_log(THD *thd, uint log_table_type) +{ + TABLE_LIST table_list; + TABLE *table; + int result; + Open_tables_state open_tables_backup; + + DBUG_ENTER("Log_to_csv_event_handler::activate_log"); + + bzero(& table_list, sizeof(TABLE_LIST)); + + if (log_table_type == QUERY_LOG_GENERAL) + { + table_list.alias= table_list.table_name= GENERAL_LOG_NAME.str; + table_list.table_name_length= GENERAL_LOG_NAME.length; + } + else + { + DBUG_ASSERT(log_table_type == QUERY_LOG_SLOW); + table_list.alias= table_list.table_name= SLOW_LOG_NAME.str; + table_list.table_name_length= SLOW_LOG_NAME.length; + } + + table_list.lock_type= TL_WRITE_CONCURRENT_INSERT; + + table_list.db= MYSQL_SCHEMA_NAME.str; + table_list.db_length= MYSQL_SCHEMA_NAME.length; + + table= open_performance_schema_table(thd, & table_list, + & open_tables_backup); + if (table) + { + result= 0; + close_performance_schema_table(thd, & open_tables_backup); + } + else + result= 1; + + DBUG_RETURN(result); +} + +bool Log_to_csv_event_handler:: + log_error(enum loglevel level, const char *format, va_list args) +{ + /* No log table is implemented */ + DBUG_ASSERT(0); + return FALSE; +} + +bool Log_to_file_event_handler:: + log_error(enum loglevel level, const char *format, + va_list args) +{ + return vprint_msg_to_log(level, format, args); +} + +void Log_to_file_event_handler::init_pthread_objects() +{ + mysql_log.init_pthread_objects(); + mysql_slow_log.init_pthread_objects(); +} + + +/** Wrapper around MYSQL_LOG::write() for slow log. */ + +bool Log_to_file_event_handler:: + log_slow(THD *thd, time_t current_time, time_t query_start_arg, + const char *user_host, uint user_host_len, + ulonglong query_utime, ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len) +{ + Silence_log_table_errors error_handler; + thd->push_internal_handler(&error_handler); + bool retval= mysql_slow_log.write(thd, current_time, query_start_arg, + user_host, user_host_len, + query_utime, lock_utime, is_command, + sql_text, sql_text_len); + thd->pop_internal_handler(); + return retval; +} + + +/** + Wrapper around MYSQL_LOG::write() for general log. We need it since we + want all log event handlers to have the same signature. +*/ + +bool Log_to_file_event_handler:: + log_general(THD *thd, time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len, + CHARSET_INFO *client_cs) +{ + Silence_log_table_errors error_handler; + thd->push_internal_handler(&error_handler); + bool retval= mysql_log.write(event_time, user_host, user_host_len, + thread_id, command_type, command_type_len, + sql_text, sql_text_len); + thd->pop_internal_handler(); + return retval; +} + + +bool Log_to_file_event_handler::init() +{ + if (!is_initialized) + { + if (opt_slow_log) + mysql_slow_log.open_slow_log(sys_var_slow_log_path.value); + + if (opt_log) + mysql_log.open_query_log(sys_var_general_log_path.value); + + is_initialized= TRUE; + } + + return FALSE; +} + + +void Log_to_file_event_handler::cleanup() +{ + mysql_log.cleanup(); + mysql_slow_log.cleanup(); +} + +void Log_to_file_event_handler::flush() +{ + /* reopen log files */ + if (opt_log) + mysql_log.reopen_file(); + if (opt_slow_log) + mysql_slow_log.reopen_file(); +} + +/* + Log error with all enabled log event handlers + + SYNOPSIS + error_log_print() + + level The level of the error significance: NOTE, + WARNING or ERROR. + format format string for the error message + args list of arguments for the format string + + RETURN + FALSE - OK + TRUE - error occured +*/ + +bool LOGGER::error_log_print(enum loglevel level, const char *format, + va_list args) +{ + bool error= FALSE; + Log_event_handler **current_handler; + + /* currently we don't need locking here as there is no error_log table */ + for (current_handler= error_log_handler_list ; *current_handler ;) + error= (*current_handler++)->log_error(level, format, args) || error; + + return error; +} + + +void LOGGER::cleanup_base() +{ + DBUG_ASSERT(inited == 1); + rwlock_destroy(&LOCK_logger); + if (table_log_handler) + { + table_log_handler->cleanup(); + delete table_log_handler; + table_log_handler= NULL; + } + if (file_log_handler) + file_log_handler->cleanup(); +} + + +void LOGGER::cleanup_end() +{ + DBUG_ASSERT(inited == 1); + if (file_log_handler) + { + delete file_log_handler; + file_log_handler=NULL; + } + inited= 0; +} + + +/** + Perform basic log initialization: create file-based log handler and + init error log. +*/ +void LOGGER::init_base() +{ + DBUG_ASSERT(inited == 0); + inited= 1; + + /* + Here we create file log handler. We don't do it for the table log handler + here as it cannot be created so early. The reason is THD initialization, + which depends on the system variables (parsed later). + */ + if (!file_log_handler) + file_log_handler= new Log_to_file_event_handler; + + /* by default we use traditional error log */ + init_error_log(LOG_FILE); + + file_log_handler->init_pthread_objects(); + my_rwlock_init(&LOCK_logger, NULL); +} + + +void LOGGER::init_log_tables() +{ + if (!table_log_handler) + table_log_handler= new Log_to_csv_event_handler; + + if (!is_log_tables_initialized && + !table_log_handler->init() && !file_log_handler->init()) + is_log_tables_initialized= TRUE; +} + + +bool LOGGER::flush_logs(THD *thd) +{ + int rc= 0; + + /* + Now we lock logger, as nobody should be able to use logging routines while + log tables are closed + */ + logger.lock_exclusive(); + + /* reopen log files */ + file_log_handler->flush(); + + /* end of log flush */ + logger.unlock(); + return rc; +} + + +/* + Log slow query with all enabled log event handlers + + SYNOPSIS + slow_log_print() + + thd THD of the query being logged + query The query being logged + query_length The length of the query string + current_utime Current time in microseconds (from undefined start) + + RETURN + FALSE OK + TRUE error occured +*/ + +bool LOGGER::slow_log_print(THD *thd, const char *query, uint query_length, + ulonglong current_utime) + +{ + bool error= FALSE; + Log_event_handler **current_handler; + bool is_command= FALSE; + char user_host_buff[MAX_USER_HOST_SIZE + 1]; + Security_context *sctx= thd->security_ctx; + uint user_host_len= 0; + ulonglong query_utime, lock_utime; + + /* + Print the message to the buffer if we have slow log enabled + */ + + if (*slow_log_handler_list) + { + time_t current_time; + + /* do not log slow queries from replication threads */ + if (thd->slave_thread && !opt_log_slow_slave_statements) + return 0; + + lock_shared(); + if (!opt_slow_log) + { + unlock(); + return 0; + } + + /* fill in user_host value: the format is "%s[%s] @ %s [%s]" */ + user_host_len= (strxnmov(user_host_buff, MAX_USER_HOST_SIZE, + sctx->priv_user ? sctx->priv_user : "", "[", + sctx->user ? sctx->user : "", "] @ ", + sctx->host ? sctx->host : "", " [", + sctx->ip ? sctx->ip : "", "]", NullS) - + user_host_buff); + + current_time= my_time_possible_from_micro(current_utime); + if (thd->start_utime) + { + query_utime= (current_utime - thd->start_utime); + lock_utime= (thd->utime_after_lock - thd->start_utime); + } + else + { + query_utime= lock_utime= 0; + } + + if (!query) + { + is_command= TRUE; + query= command_name[thd->command].str; + query_length= command_name[thd->command].length; + } + + for (current_handler= slow_log_handler_list; *current_handler ;) + error= (*current_handler++)->log_slow(thd, current_time, thd->start_time, + user_host_buff, user_host_len, + query_utime, lock_utime, is_command, + query, query_length) || error; + + unlock(); + } + return error; +} + +bool LOGGER::general_log_write(THD *thd, enum enum_server_command command, + const char *query, uint query_length) +{ + bool error= FALSE; + Log_event_handler **current_handler= general_log_handler_list; + char user_host_buff[MAX_USER_HOST_SIZE + 1]; + Security_context *sctx= thd->security_ctx; + ulong id; + uint user_host_len= 0; + time_t current_time; + + if (thd) + id= thd->thread_id; /* Normal thread */ + else + id= 0; /* Log from connect handler */ + + lock_shared(); + if (!opt_log) + { + unlock(); + return 0; + } + user_host_len= strxnmov(user_host_buff, MAX_USER_HOST_SIZE, + sctx->priv_user ? sctx->priv_user : "", "[", + sctx->user ? sctx->user : "", "] @ ", + sctx->host ? sctx->host : "", " [", + sctx->ip ? sctx->ip : "", "]", NullS) - + user_host_buff; + + current_time= my_time(0); + while (*current_handler) + error|= (*current_handler++)-> + log_general(thd, current_time, user_host_buff, + user_host_len, id, + command_name[(uint) command].str, + command_name[(uint) command].length, + query, query_length, + thd->variables.character_set_client) || error; + unlock(); + + return error; +} + +bool LOGGER::general_log_print(THD *thd, enum enum_server_command command, + const char *format, va_list args) +{ + uint message_buff_len= 0; + char message_buff[MAX_LOG_BUFFER_SIZE]; + + /* prepare message */ + if (format) + message_buff_len= my_vsnprintf(message_buff, sizeof(message_buff), + format, args); + else + message_buff[0]= '\0'; + + return general_log_write(thd, command, message_buff, message_buff_len); +} + +void LOGGER::init_error_log(uint error_log_printer) +{ + if (error_log_printer & LOG_NONE) + { + error_log_handler_list[0]= 0; + return; + } + + switch (error_log_printer) { + case LOG_FILE: + error_log_handler_list[0]= file_log_handler; + error_log_handler_list[1]= 0; + break; + /* these two are disabled for now */ + case LOG_TABLE: + DBUG_ASSERT(0); + break; + case LOG_TABLE|LOG_FILE: + DBUG_ASSERT(0); + break; + } +} + +void LOGGER::init_slow_log(uint slow_log_printer) +{ + if (slow_log_printer & LOG_NONE) + { + slow_log_handler_list[0]= 0; + return; + } + + switch (slow_log_printer) { + case LOG_FILE: + slow_log_handler_list[0]= file_log_handler; + slow_log_handler_list[1]= 0; + break; + case LOG_TABLE: + slow_log_handler_list[0]= table_log_handler; + slow_log_handler_list[1]= 0; + break; + case LOG_TABLE|LOG_FILE: + slow_log_handler_list[0]= file_log_handler; + slow_log_handler_list[1]= table_log_handler; + slow_log_handler_list[2]= 0; + break; + } +} + +void LOGGER::init_general_log(uint general_log_printer) +{ + if (general_log_printer & LOG_NONE) + { + general_log_handler_list[0]= 0; + return; + } + + switch (general_log_printer) { + case LOG_FILE: + general_log_handler_list[0]= file_log_handler; + general_log_handler_list[1]= 0; + break; + case LOG_TABLE: + general_log_handler_list[0]= table_log_handler; + general_log_handler_list[1]= 0; + break; + case LOG_TABLE|LOG_FILE: + general_log_handler_list[0]= file_log_handler; + general_log_handler_list[1]= table_log_handler; + general_log_handler_list[2]= 0; + break; + } +} + + +bool LOGGER::activate_log_handler(THD* thd, uint log_type) +{ + MYSQL_QUERY_LOG *file_log; + bool res= FALSE; + lock_exclusive(); + switch (log_type) { + case QUERY_LOG_SLOW: + if (!opt_slow_log) + { + file_log= file_log_handler->get_mysql_slow_log(); + + file_log->open_slow_log(sys_var_slow_log_path.value); + if (table_log_handler->activate_log(thd, QUERY_LOG_SLOW)) + { + /* Error printed by open table in activate_log() */ + res= TRUE; + file_log->close(0); + } + else + { + init_slow_log(log_output_options); + opt_slow_log= TRUE; + } + } + break; + case QUERY_LOG_GENERAL: + if (!opt_log) + { + file_log= file_log_handler->get_mysql_log(); + + file_log->open_query_log(sys_var_general_log_path.value); + if (table_log_handler->activate_log(thd, QUERY_LOG_GENERAL)) + { + /* Error printed by open table in activate_log() */ + res= TRUE; + file_log->close(0); + } + else + { + init_general_log(log_output_options); + opt_log= TRUE; + } + } + break; + default: + DBUG_ASSERT(0); + } + unlock(); + return res; +} + + +void LOGGER::deactivate_log_handler(THD *thd, uint log_type) +{ + my_bool *tmp_opt= 0; + MYSQL_LOG *file_log; + + switch (log_type) { + case QUERY_LOG_SLOW: + tmp_opt= &opt_slow_log; + file_log= file_log_handler->get_mysql_slow_log(); + break; + case QUERY_LOG_GENERAL: + tmp_opt= &opt_log; + file_log= file_log_handler->get_mysql_log(); + break; + default: + assert(0); // Impossible + } + + if (!(*tmp_opt)) + return; + + lock_exclusive(); + file_log->close(0); + *tmp_opt= FALSE; + unlock(); +} + + +/* the parameters are unused for the log tables */ +bool Log_to_csv_event_handler::init() +{ + return 0; +} + +int LOGGER::set_handlers(uint error_log_printer, + uint slow_log_printer, + uint general_log_printer) +{ + /* error log table is not supported yet */ + DBUG_ASSERT(error_log_printer < LOG_TABLE); + + lock_exclusive(); + + if ((slow_log_printer & LOG_TABLE || general_log_printer & LOG_TABLE) && + !is_log_tables_initialized) + { + slow_log_printer= (slow_log_printer & ~LOG_TABLE) | LOG_FILE; + general_log_printer= (general_log_printer & ~LOG_TABLE) | LOG_FILE; + + sql_print_error("Failed to initialize log tables. " + "Falling back to the old-fashioned logs"); + } + + init_error_log(error_log_printer); + init_slow_log(slow_log_printer); + init_general_log(general_log_printer); + + unlock(); + + return 0; +} + +/** + This function checks if a transactional talbe was updated by the + current statement. + + @param thd The client thread that executed the current statement. + @return + @c true if a transactional table was updated, @false otherwise. +*/ +static bool stmt_has_updated_trans_table(THD *thd) +{ + Ha_trx_info *ha_info; + + for (ha_info= thd->transaction.stmt.ha_list; ha_info; ha_info= ha_info->next()) + { + if (ha_info->is_trx_read_write() && ha_info->ht() != binlog_hton) + return (TRUE); + } + return (FALSE); +} + + /* + Save position of binary log transaction cache. + + SYNPOSIS + binlog_trans_log_savepos() + + thd The thread to take the binlog data from + pos Pointer to variable where the position will be stored + + DESCRIPTION + + Save the current position in the binary log transaction cache into + the variable pointed to by 'pos' + */ + +static void +binlog_trans_log_savepos(THD *thd, my_off_t *pos) +{ + DBUG_ENTER("binlog_trans_log_savepos"); + DBUG_ASSERT(pos != NULL); + if (thd_get_ha_data(thd, binlog_hton) == NULL) + thd->binlog_setup_trx_data(); + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + DBUG_ASSERT(mysql_bin_log.is_open()); + *pos= trx_data->position(); + DBUG_PRINT("return", ("*pos: %lu", (ulong) *pos)); + DBUG_VOID_RETURN; +} + + +/* + Truncate the binary log transaction cache. + + SYNPOSIS + binlog_trans_log_truncate() + + thd The thread to take the binlog data from + pos Position to truncate to + + DESCRIPTION + + Truncate the binary log to the given position. Will not change + anything else. + + */ +static void +binlog_trans_log_truncate(THD *thd, my_off_t pos) +{ + DBUG_ENTER("binlog_trans_log_truncate"); + DBUG_PRINT("enter", ("pos: %lu", (ulong) pos)); + + DBUG_ASSERT(thd_get_ha_data(thd, binlog_hton) != NULL); + /* Only true if binlog_trans_log_savepos() wasn't called before */ + DBUG_ASSERT(pos != ~(my_off_t) 0); + + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + trx_data->truncate(pos); + DBUG_VOID_RETURN; +} + + +/* + this function is mostly a placeholder. + conceptually, binlog initialization (now mostly done in MYSQL_BIN_LOG::open) + should be moved here. +*/ + +int binlog_init(void *p) +{ + binlog_hton= (handlerton *)p; + binlog_hton->state=opt_bin_log ? SHOW_OPTION_YES : SHOW_OPTION_NO; + binlog_hton->db_type=DB_TYPE_BINLOG; + binlog_hton->savepoint_offset= sizeof(my_off_t); + binlog_hton->close_connection= binlog_close_connection; + binlog_hton->savepoint_set= binlog_savepoint_set; + binlog_hton->savepoint_rollback= binlog_savepoint_rollback; + binlog_hton->commit= binlog_commit; + binlog_hton->rollback= binlog_rollback; + binlog_hton->prepare= binlog_prepare; + binlog_hton->flags= HTON_NOT_USER_SELECTABLE | HTON_HIDDEN; + return 0; +} + +static int binlog_close_connection(handlerton *hton, THD *thd) +{ + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + if (!trx_data) return 0; + DBUG_ASSERT(trx_data->empty()); + thd_set_ha_data(thd, binlog_hton, NULL); + trx_data->~binlog_trx_data(); + my_free((uchar*)trx_data, MYF(0)); + return 0; +} + +/* + End a transaction. + + SYNOPSIS + binlog_end_trans() + + thd The thread whose transaction should be ended + trx_data Pointer to the transaction data to use + end_ev The end event to use, or NULL + all True if the entire transaction should be ended, false if + only the statement transaction should be ended. + + DESCRIPTION + + End the currently open transaction. The transaction can be either + a real transaction (if 'all' is true) or a statement transaction + (if 'all' is false). + + If 'end_ev' is NULL, the transaction is a rollback of only + transactional tables, so the transaction cache will be truncated + to either just before the last opened statement transaction (if + 'all' is false), or reset completely (if 'all' is true). + */ +static int +binlog_end_trans(THD *thd, binlog_trx_data *trx_data, + Log_event *end_ev, bool all) +{ + DBUG_ENTER("binlog_end_trans"); + int error=0; + IO_CACHE *trans_log= &trx_data->trans_log; + DBUG_PRINT("enter", ("transaction: %s end_ev: 0x%lx", + all ? "all" : "stmt", (long) end_ev)); + DBUG_PRINT("info", ("thd->options={ %s%s}", + FLAGSTR(thd->options, OPTION_NOT_AUTOCOMMIT), + FLAGSTR(thd->options, OPTION_BEGIN))); + + /* + NULL denotes ROLLBACK with nothing to replicate: i.e., rollback of + only transactional tables. If the transaction contain changes to + any non-transactiona tables, we need write the transaction and log + a ROLLBACK last. + */ + if (end_ev != NULL) + { + if (thd->binlog_flush_pending_rows_event(TRUE)) + DBUG_RETURN(1); + /* + Doing a commit or a rollback including non-transactional tables, + i.e., ending a transaction where we might write the transaction + cache to the binary log. + + We can always end the statement when ending a transaction since + transactions are not allowed inside stored functions. If they + were, we would have to ensure that we're not ending a statement + inside a stored function. + */ + error= mysql_bin_log.write(thd, &trx_data->trans_log, end_ev, + trx_data->has_incident()); + trx_data->reset(); + + /* + We need to step the table map version after writing the + transaction cache to disk. + */ + mysql_bin_log.update_table_map_version(); + statistic_increment(binlog_cache_use, &LOCK_status); + if (trans_log->disk_writes != 0) + { + statistic_increment(binlog_cache_disk_use, &LOCK_status); + trans_log->disk_writes= 0; + } + } + else + { + /* + If rolling back an entire transaction or a single statement not + inside a transaction, we reset the transaction cache. + + If rolling back a statement in a transaction, we truncate the + transaction cache to remove the statement. + */ + thd->binlog_remove_pending_rows_event(TRUE); + if (all || !(thd->options & (OPTION_BEGIN | OPTION_NOT_AUTOCOMMIT))) + { + if (trx_data->has_incident()) + mysql_bin_log.write_incident(thd, TRUE); + trx_data->reset(); + } + else // ...statement + trx_data->truncate(trx_data->before_stmt_pos); + + /* + We need to step the table map version on a rollback to ensure + that a new table map event is generated instead of the one that + was written to the thrown-away transaction cache. + */ + mysql_bin_log.update_table_map_version(); + } + + DBUG_ASSERT(thd->binlog_get_pending_rows_event() == NULL); + DBUG_RETURN(error); +} + +static int binlog_prepare(handlerton *hton, THD *thd, bool all) +{ + /* + do nothing. + just pretend we can do 2pc, so that MySQL won't + switch to 1pc. + real work will be done in MYSQL_BIN_LOG::log_xid() + */ + return 0; +} + +/** + This function is called once after each statement. + + It has the responsibility to flush the transaction cache to the + binlog file on commits. + + @param hton The binlog handlerton. + @param thd The client thread that executes the transaction. + @param all This is @c true if this is a real transaction commit, and + @false otherwise. + + @see handlerton::commit +*/ +static int binlog_commit(handlerton *hton, THD *thd, bool all) +{ + int error= 0; + DBUG_ENTER("binlog_commit"); + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + + if (trx_data->empty()) + { + // we're here because trans_log was flushed in MYSQL_BIN_LOG::log_xid() + trx_data->reset(); + DBUG_RETURN(0); + } + + /* + We commit the transaction if: + + - We are not in a transaction and committing a statement, or + + - We are in a transaction and a full transaction is committed + + Otherwise, we accumulate the statement + */ + ulonglong const in_transaction= + thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN); + DBUG_PRINT("debug", + ("all: %d, empty: %s, in_transaction: %s, all.modified_non_trans_table: %s, stmt.modified_non_trans_table: %s", + all, + YESNO(trx_data->empty()), + YESNO(in_transaction), + YESNO(thd->transaction.all.modified_non_trans_table), + YESNO(thd->transaction.stmt.modified_non_trans_table))); + if (!in_transaction || all) + { + Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), TRUE, TRUE, 0); + error= binlog_end_trans(thd, trx_data, &qev, all); + goto end; + } + +end: + if (!all) + trx_data->before_stmt_pos = MY_OFF_T_UNDEF; // part of the stmt commit + DBUG_RETURN(error); +} + +/** + This function is called when a transaction involving a transactional + table is rolled back. + + It has the responsibility to flush the transaction cache to the + binlog file. However, if the transaction does not involve + non-transactional tables, nothing needs to be logged. + + @param hton The binlog handlerton. + @param thd The client thread that executes the transaction. + @param all This is @c true if this is a real transaction rollback, and + @false otherwise. + + @see handlerton::rollback +*/ +static int binlog_rollback(handlerton *hton, THD *thd, bool all) +{ + DBUG_ENTER("binlog_rollback"); + int error=0; + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + + if (trx_data->empty()) { + trx_data->reset(); + DBUG_RETURN(0); + } + + DBUG_PRINT("debug", ("all: %s, all.modified_non_trans_table: %s, stmt.modified_non_trans_table: %s", + YESNO(all), + YESNO(thd->transaction.all.modified_non_trans_table), + YESNO(thd->transaction.stmt.modified_non_trans_table))); + if (mysql_bin_log.check_write_error(thd)) + { + /* + "all == true" means that a "rollback statement" triggered the error and + this function was called. However, this must not happen as a rollback + is written directly to the binary log. And in auto-commit mode, a single + statement that is rolled back has the flag all == false. + */ + DBUG_ASSERT(!all); + /* + We reach this point if either only transactional tables were modified or + the effect of a statement that did not get into the binlog needs to be + rolled back. In the latter case, if a statement changed non-transactional + tables or had the OPTION_KEEP_LOG associated, we write an incident event + to the binlog in order to stop slaves and notify users that some changes + on the master did not get into the binlog and slaves will be inconsistent. + On the other hand, if a statement is transactional, we just safely roll it + back. + */ + if ((thd->transaction.stmt.modified_non_trans_table || + (thd->options & OPTION_KEEP_LOG)) && + mysql_bin_log.check_write_error(thd)) + trx_data->set_incident(); + error= binlog_end_trans(thd, trx_data, 0, all); + } + else + { + /* + We flush the cache with a rollback, wrapped in a beging/rollback if: + . aborting a transcation that modified a non-transactional table or; + . aborting a statement that modified both transactional and + non-transctional tables but which is not in the boundaries of any + transaction; + . the OPTION_KEEP_LOG is activate. + */ + if ((all && thd->transaction.all.modified_non_trans_table) || + (!all && thd->transaction.stmt.modified_non_trans_table && + !(thd->options & (OPTION_BEGIN | OPTION_NOT_AUTOCOMMIT))) || + ((thd->options & OPTION_KEEP_LOG))) + { + Query_log_event qev(thd, STRING_WITH_LEN("ROLLBACK"), TRUE, TRUE, 0); + error= binlog_end_trans(thd, trx_data, &qev, all); + } + /* + Otherwise, we simply truncate the cache as there is no change on + non-transactional tables as follows. + */ + else if ((all && !thd->transaction.all.modified_non_trans_table) || + (!all && !thd->transaction.stmt.modified_non_trans_table)) + error= binlog_end_trans(thd, trx_data, 0, all); + } + if (!all) + trx_data->before_stmt_pos = MY_OFF_T_UNDEF; // part of the stmt rollback + DBUG_RETURN(error); +} + +void MYSQL_BIN_LOG::set_write_error(THD *thd) +{ + DBUG_ENTER("MYSQL_BIN_LOG::set_write_error"); + + write_error= 1; + + if (check_write_error(thd)) + DBUG_VOID_RETURN; + + if (my_errno == EFBIG) + my_message(ER_TRANS_CACHE_FULL, ER(ER_TRANS_CACHE_FULL), MYF(MY_WME)); + else + my_error(ER_ERROR_ON_WRITE, MYF(MY_WME), name, errno); + + DBUG_VOID_RETURN; +} + +bool MYSQL_BIN_LOG::check_write_error(THD *thd) +{ + DBUG_ENTER("MYSQL_BIN_LOG::check_write_error"); + + bool checked= FALSE; + + if (!thd->is_error()) + DBUG_RETURN(checked); + + switch (thd->main_da.sql_errno()) + { + case ER_TRANS_CACHE_FULL: + case ER_ERROR_ON_WRITE: + case ER_BINLOG_LOGGING_IMPOSSIBLE: + checked= TRUE; + break; + } + + DBUG_RETURN(checked); +} + +/** + @note + How do we handle this (unlikely but legal) case: + @verbatim + [transaction] + [update to non-trans table] + [rollback to savepoint] ? + @endverbatim + The problem occurs when a savepoint is before the update to the + non-transactional table. Then when there's a rollback to the savepoint, if we + simply truncate the binlog cache, we lose the part of the binlog cache where + the update is. If we want to not lose it, we need to write the SAVEPOINT + command and the ROLLBACK TO SAVEPOINT command to the binlog cache. The latter + is easy: it's just write at the end of the binlog cache, but the former + should be *inserted* to the place where the user called SAVEPOINT. The + solution is that when the user calls SAVEPOINT, we write it to the binlog + cache (so no need to later insert it). As transactions are never intermixed + in the binary log (i.e. they are serialized), we won't have conflicts with + savepoint names when using mysqlbinlog or in the slave SQL thread. + Then when ROLLBACK TO SAVEPOINT is called, if we updated some + non-transactional table, we don't truncate the binlog cache but instead write + ROLLBACK TO SAVEPOINT to it; otherwise we truncate the binlog cache (which + will chop the SAVEPOINT command from the binlog cache, which is good as in + that case there is no need to have it in the binlog). +*/ + +static int binlog_savepoint_set(handlerton *hton, THD *thd, void *sv) +{ + DBUG_ENTER("binlog_savepoint_set"); + + binlog_trans_log_savepos(thd, (my_off_t*) sv); + /* Write it to the binary log */ + + int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + int const error= + thd->binlog_query(THD::STMT_QUERY_TYPE, + thd->query, thd->query_length, TRUE, FALSE, errcode); + DBUG_RETURN(error); +} + +static int binlog_savepoint_rollback(handlerton *hton, THD *thd, void *sv) +{ + DBUG_ENTER("binlog_savepoint_rollback"); + + /* + Write ROLLBACK TO SAVEPOINT to the binlog cache if we have updated some + non-transactional table. Otherwise, truncate the binlog cache starting + from the SAVEPOINT command. + */ + if (unlikely(thd->transaction.all.modified_non_trans_table || + (thd->options & OPTION_KEEP_LOG))) + { + int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + int error= + thd->binlog_query(THD::STMT_QUERY_TYPE, + thd->query, thd->query_length, TRUE, FALSE, errcode); + DBUG_RETURN(error); + } + binlog_trans_log_truncate(thd, *(my_off_t*)sv); + DBUG_RETURN(0); +} + + +int check_binlog_magic(IO_CACHE* log, const char** errmsg) +{ + char magic[4]; + DBUG_ASSERT(my_b_tell(log) == 0); + + if (my_b_read(log, (uchar*) magic, sizeof(magic))) + { + *errmsg = "I/O error reading the header from the binary log"; + sql_print_error("%s, errno=%d, io cache code=%d", *errmsg, my_errno, + log->error); + return 1; + } + if (memcmp(magic, BINLOG_MAGIC, sizeof(magic))) + { + *errmsg = "Binlog has bad magic number; It's not a binary log file that can be used by this version of MySQL"; + return 1; + } + return 0; +} + + +File open_binlog(IO_CACHE *log, const char *log_file_name, const char **errmsg) +{ + File file; + DBUG_ENTER("open_binlog"); + + if ((file = my_open(log_file_name, O_RDONLY | O_BINARY | O_SHARE, + MYF(MY_WME))) < 0) + { + sql_print_error("Failed to open log (file '%s', errno %d)", + log_file_name, my_errno); + *errmsg = "Could not open log file"; + goto err; + } + if (init_io_cache(log, file, IO_SIZE*2, READ_CACHE, 0, 0, + MYF(MY_WME|MY_DONT_CHECK_FILESIZE))) + { + sql_print_error("Failed to create a cache on log (file '%s')", + log_file_name); + *errmsg = "Could not open log file"; + goto err; + } + if (check_binlog_magic(log,errmsg)) + goto err; + DBUG_RETURN(file); + +err: + if (file >= 0) + { + my_close(file,MYF(0)); + end_io_cache(log); + } + DBUG_RETURN(-1); +} + +#ifdef __NT__ +static int eventSource = 0; + +static void setup_windows_event_source() +{ + HKEY hRegKey= NULL; + DWORD dwError= 0; + TCHAR szPath[MAX_PATH]; + DWORD dwTypes; + + if (eventSource) // Ensure that we are only called once + return; + eventSource= 1; + + // Create the event source registry key + dwError= RegCreateKey(HKEY_LOCAL_MACHINE, + "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\MySQL", + &hRegKey); + + /* Name of the PE module that contains the message resource */ + GetModuleFileName(NULL, szPath, MAX_PATH); + + /* Register EventMessageFile */ + dwError = RegSetValueEx(hRegKey, "EventMessageFile", 0, REG_EXPAND_SZ, + (PBYTE) szPath, (DWORD) (strlen(szPath) + 1)); + + /* Register supported event types */ + dwTypes= (EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | + EVENTLOG_INFORMATION_TYPE); + dwError= RegSetValueEx(hRegKey, "TypesSupported", 0, REG_DWORD, + (LPBYTE) &dwTypes, sizeof dwTypes); + + RegCloseKey(hRegKey); +} + +#endif /* __NT__ */ + + +/** + Find a unique filename for 'filename.#'. + + Set '#' to a number as low as possible. + + @return + nonzero if not possible to get unique filename +*/ + +static int find_uniq_filename(char *name) +{ + long number; + uint i; + char buff[FN_REFLEN]; + struct st_my_dir *dir_info; + reg1 struct fileinfo *file_info; + ulong max_found=0; + size_t buf_length, length; + char *start, *end; + DBUG_ENTER("find_uniq_filename"); + + length= dirname_part(buff, name, &buf_length); + start= name + length; + end= strend(start); + + *end='.'; + length= (size_t) (end-start+1); + + if (!(dir_info = my_dir(buff,MYF(MY_DONT_SORT)))) + { // This shouldn't happen + strmov(end,".1"); // use name+1 + DBUG_RETURN(0); + } + file_info= dir_info->dir_entry; + for (i=dir_info->number_off_files ; i-- ; file_info++) + { + if (bcmp((uchar*) file_info->name, (uchar*) start, length) == 0 && + test_if_number(file_info->name+length, &number,0)) + { + set_if_bigger(max_found,(ulong) number); + } + } + my_dirend(dir_info); + + *end++='.'; + sprintf(end,"%06ld",max_found+1); + DBUG_RETURN(0); +} + + +void MYSQL_LOG::init(enum_log_type log_type_arg, + enum cache_type io_cache_type_arg) +{ + DBUG_ENTER("MYSQL_LOG::init"); + log_type= log_type_arg; + io_cache_type= io_cache_type_arg; + DBUG_PRINT("info",("log_type: %d", log_type)); + DBUG_VOID_RETURN; +} + + +/* + Open a (new) log file. + + SYNOPSIS + open() + + log_name The name of the log to open + log_type_arg The type of the log. E.g. LOG_NORMAL + new_name The new name for the logfile. This is only needed + when the method is used to open the binlog file. + io_cache_type_arg The type of the IO_CACHE to use for this log file + + DESCRIPTION + Open the logfile, init IO_CACHE and write startup messages + (in case of general and slow query logs). + + RETURN VALUES + 0 ok + 1 error +*/ + +bool MYSQL_LOG::open(const char *log_name, enum_log_type log_type_arg, + const char *new_name, enum cache_type io_cache_type_arg) +{ + char buff[FN_REFLEN]; + File file= -1; + int open_flags= O_CREAT | O_BINARY; + DBUG_ENTER("MYSQL_LOG::open"); + DBUG_PRINT("enter", ("log_type: %d", (int) log_type_arg)); + + write_error= 0; + + init(log_type_arg, io_cache_type_arg); + + if (!(name= my_strdup(log_name, MYF(MY_WME)))) + { + name= (char *)log_name; // for the error message + goto err; + } + + if (new_name) + strmov(log_file_name, new_name); + else if (generate_new_name(log_file_name, name)) + goto err; + + if (io_cache_type == SEQ_READ_APPEND) + open_flags |= O_RDWR | O_APPEND; + else + open_flags |= O_WRONLY | (log_type == LOG_BIN ? 0 : O_APPEND); + + db[0]= 0; + + if ((file= my_open(log_file_name, open_flags, + MYF(MY_WME | ME_WAITTANG))) < 0 || + init_io_cache(&log_file, file, IO_SIZE, io_cache_type, + my_tell(file, MYF(MY_WME)), 0, + MYF(MY_WME | MY_NABP | + ((log_type == LOG_BIN) ? MY_WAIT_IF_FULL : 0)))) + goto err; + + if (log_type == LOG_NORMAL) + { + char *end; + int len=my_snprintf(buff, sizeof(buff), "%s, Version: %s (%s). " +#ifdef EMBEDDED_LIBRARY + "embedded library\n", + my_progname, server_version, MYSQL_COMPILATION_COMMENT +#elif __NT__ + "started with:\nTCP Port: %d, Named Pipe: %s\n", + my_progname, server_version, MYSQL_COMPILATION_COMMENT, + mysqld_port, mysqld_unix_port +#else + "started with:\nTcp port: %d Unix socket: %s\n", + my_progname, server_version, MYSQL_COMPILATION_COMMENT, + mysqld_port, mysqld_unix_port +#endif + ); + end= strnmov(buff + len, "Time Id Command Argument\n", + sizeof(buff) - len); + if (my_b_write(&log_file, (uchar*) buff, (uint) (end-buff)) || + flush_io_cache(&log_file)) + goto err; + } + + log_state= LOG_OPENED; + DBUG_RETURN(0); + +err: + sql_print_error("Could not use %s for logging (error %d). \ +Turning logging off for the whole duration of the MySQL server process. \ +To turn it on again: fix the cause, \ +shutdown the MySQL server and restart it.", name, errno); + if (file >= 0) + my_close(file, MYF(0)); + end_io_cache(&log_file); + safeFree(name); + log_state= LOG_CLOSED; + DBUG_RETURN(1); +} + +MYSQL_LOG::MYSQL_LOG() + : name(0), write_error(FALSE), inited(FALSE), log_type(LOG_UNKNOWN), + log_state(LOG_CLOSED) +{ + /* + We don't want to initialize LOCK_Log here as such initialization depends on + safe_mutex (when using safe_mutex) which depends on MY_INIT(), which is + called only in main(). Doing initialization here would make it happen + before main(). + */ + bzero((char*) &log_file, sizeof(log_file)); +} + +void MYSQL_LOG::init_pthread_objects() +{ + DBUG_ASSERT(inited == 0); + inited= 1; + (void) pthread_mutex_init(&LOCK_log, MY_MUTEX_INIT_SLOW); +} + +/* + Close the log file + + SYNOPSIS + close() + exiting Bitmask. For the slow and general logs the only used bit is + LOG_CLOSE_TO_BE_OPENED. This is used if we intend to call + open at once after close. + + NOTES + One can do an open on the object at once after doing a close. + The internal structures are not freed until cleanup() is called +*/ + +void MYSQL_LOG::close(uint exiting) +{ // One can't set log_type here! + DBUG_ENTER("MYSQL_LOG::close"); + DBUG_PRINT("enter",("exiting: %d", (int) exiting)); + if (log_state == LOG_OPENED) + { + end_io_cache(&log_file); + + if (my_sync(log_file.file, MYF(MY_WME)) && ! write_error) + { + write_error= 1; + sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno); + } + + if (my_close(log_file.file, MYF(MY_WME)) && ! write_error) + { + write_error= 1; + sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno); + } + } + + log_state= (exiting & LOG_CLOSE_TO_BE_OPENED) ? LOG_TO_BE_OPENED : LOG_CLOSED; + safeFree(name); + DBUG_VOID_RETURN; +} + +/** This is called only once. */ + +void MYSQL_LOG::cleanup() +{ + DBUG_ENTER("cleanup"); + if (inited) + { + inited= 0; + (void) pthread_mutex_destroy(&LOCK_log); + close(0); + } + DBUG_VOID_RETURN; +} + + +int MYSQL_LOG::generate_new_name(char *new_name, const char *log_name) +{ + fn_format(new_name, log_name, mysql_data_home, "", 4); + if (log_type == LOG_BIN) + { + if (!fn_ext(log_name)[0]) + { + if (find_uniq_filename(new_name)) + { + sql_print_error(ER(ER_NO_UNIQUE_LOGFILE), log_name); + return 1; + } + } + } + return 0; +} + + +/* + Reopen the log file + + SYNOPSIS + reopen_file() + + DESCRIPTION + Reopen the log file. The method is used during FLUSH LOGS + and locks LOCK_log mutex +*/ + + +void MYSQL_QUERY_LOG::reopen_file() +{ + char *save_name; + + DBUG_ENTER("MYSQL_LOG::reopen_file"); + if (!is_open()) + { + DBUG_PRINT("info",("log is closed")); + DBUG_VOID_RETURN; + } + + pthread_mutex_lock(&LOCK_log); + + save_name= name; + name= 0; // Don't free name + close(LOG_CLOSE_TO_BE_OPENED); + + /* + Note that at this point, log_state != LOG_CLOSED (important for is_open()). + */ + + open(save_name, log_type, 0, io_cache_type); + my_free(save_name, MYF(0)); + + pthread_mutex_unlock(&LOCK_log); + + DBUG_VOID_RETURN; +} + + +/* + Write a command to traditional general log file + + SYNOPSIS + write() + + event_time command start timestamp + user_host the pointer to the string with user@host info + user_host_len length of the user_host string. this is computed once + and passed to all general log event handlers + thread_id Id of the thread, issued a query + command_type the type of the command being logged + command_type_len the length of the string above + sql_text the very text of the query being executed + sql_text_len the length of sql_text string + + DESCRIPTION + + Log given command to to normal (not rotable) log file + + RETURN + FASE - OK + TRUE - error occured +*/ + +bool MYSQL_QUERY_LOG::write(time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len) +{ + char buff[32]; + uint length= 0; + char local_time_buff[MAX_TIME_SIZE]; + struct tm start; + uint time_buff_len= 0; + + (void) pthread_mutex_lock(&LOCK_log); + + /* Test if someone closed between the is_open test and lock */ + if (is_open()) + { + /* for testing output of timestamp and thread id */ + DBUG_EXECUTE_IF("reset_log_last_time", last_time= 0;); + + /* Note that my_b_write() assumes it knows the length for this */ + if (event_time != last_time) + { + last_time= event_time; + + localtime_r(&event_time, &start); + + time_buff_len= my_snprintf(local_time_buff, MAX_TIME_SIZE, + "%02d%02d%02d %2d:%02d:%02d\t", + start.tm_year % 100, start.tm_mon + 1, + start.tm_mday, start.tm_hour, + start.tm_min, start.tm_sec); + + if (my_b_write(&log_file, (uchar*) local_time_buff, time_buff_len)) + goto err; + } + else + if (my_b_write(&log_file, (uchar*) "\t\t" ,2) < 0) + goto err; + + /* command_type, thread_id */ + length= my_snprintf(buff, 32, "%5ld ", (long) thread_id); + + if (my_b_write(&log_file, (uchar*) buff, length)) + goto err; + + if (my_b_write(&log_file, (uchar*) command_type, command_type_len)) + goto err; + + if (my_b_write(&log_file, (uchar*) "\t", 1)) + goto err; + + /* sql_text */ + if (my_b_write(&log_file, (uchar*) sql_text, sql_text_len)) + goto err; + + if (my_b_write(&log_file, (uchar*) "\n", 1) || + flush_io_cache(&log_file)) + goto err; + } + + (void) pthread_mutex_unlock(&LOCK_log); + return FALSE; +err: + + if (!write_error) + { + write_error= 1; + sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno); + } + (void) pthread_mutex_unlock(&LOCK_log); + return TRUE; +} + + +/* + Log a query to the traditional slow log file + + SYNOPSIS + write() + + thd THD of the query + current_time current timestamp + query_start_arg command start timestamp + user_host the pointer to the string with user@host info + user_host_len length of the user_host string. this is computed once + and passed to all general log event handlers + query_utime Amount of time the query took to execute (in microseconds) + lock_utime Amount of time the query was locked (in microseconds) + is_command The flag, which determines, whether the sql_text is a + query or an administrator command. + sql_text the very text of the query or administrator command + processed + sql_text_len the length of sql_text string + + DESCRIPTION + + Log a query to the slow log file. + + RETURN + FALSE - OK + TRUE - error occured +*/ + +bool MYSQL_QUERY_LOG::write(THD *thd, time_t current_time, + time_t query_start_arg, const char *user_host, + uint user_host_len, ulonglong query_utime, + ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len) +{ + bool error= 0; + DBUG_ENTER("MYSQL_QUERY_LOG::write"); + + (void) pthread_mutex_lock(&LOCK_log); + + if (!is_open()) + { + (void) pthread_mutex_unlock(&LOCK_log); + DBUG_RETURN(0); + } + + if (is_open()) + { // Safety agains reopen + int tmp_errno= 0; + char buff[80], *end; + char query_time_buff[22+7], lock_time_buff[22+7]; + uint buff_len; + end= buff; + + if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT)) + { + if (current_time != last_time) + { + last_time= current_time; + struct tm start; + localtime_r(¤t_time, &start); + + buff_len= my_snprintf(buff, sizeof buff, + "# Time: %02d%02d%02d %2d:%02d:%02d\n", + start.tm_year % 100, start.tm_mon + 1, + start.tm_mday, start.tm_hour, + start.tm_min, start.tm_sec); + + /* Note that my_b_write() assumes it knows the length for this */ + if (my_b_write(&log_file, (uchar*) buff, buff_len)) + tmp_errno= errno; + } + const uchar uh[]= "# User@Host: "; + if (my_b_write(&log_file, uh, sizeof(uh) - 1)) + tmp_errno= errno; + if (my_b_write(&log_file, (uchar*) user_host, user_host_len)) + tmp_errno= errno; + if (my_b_write(&log_file, (uchar*) "\n", 1)) + tmp_errno= errno; + } + /* For slow query log */ + sprintf(query_time_buff, "%.6f", ulonglong2double(query_utime)/1000000.0); + sprintf(lock_time_buff, "%.6f", ulonglong2double(lock_utime)/1000000.0); + if (my_b_printf(&log_file, + "# Query_time: %s Lock_time: %s" + " Rows_sent: %lu Rows_examined: %lu\n", + query_time_buff, lock_time_buff, + (ulong) thd->sent_row_count, + (ulong) thd->examined_row_count) == (uint) -1) + tmp_errno= errno; + if (thd->db && strcmp(thd->db, db)) + { // Database changed + if (my_b_printf(&log_file,"use %s;\n",thd->db) == (uint) -1) + tmp_errno= errno; + strmov(db,thd->db); + } + if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt) + { + end=strmov(end, ",last_insert_id="); + end=longlong10_to_str((longlong) + thd->first_successful_insert_id_in_prev_stmt_for_binlog, + end, -10); + } + // Save value if we do an insert. + if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0) + { + if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT)) + { + end=strmov(end,",insert_id="); + end=longlong10_to_str((longlong) + thd->auto_inc_intervals_in_cur_stmt_for_binlog.minimum(), + end, -10); + } + } + + /* + This info used to show up randomly, depending on whether the query + checked the query start time or not. now we always write current + timestamp to the slow log + */ + end= strmov(end, ",timestamp="); + end= int10_to_str((long) current_time, end, 10); + + if (end != buff) + { + *end++=';'; + *end='\n'; + if (my_b_write(&log_file, (uchar*) "SET ", 4) || + my_b_write(&log_file, (uchar*) buff + 1, (uint) (end-buff))) + tmp_errno= errno; + } + if (is_command) + { + end= strxmov(buff, "# administrator command: ", NullS); + buff_len= (ulong) (end - buff); + my_b_write(&log_file, (uchar*) buff, buff_len); + } + if (my_b_write(&log_file, (uchar*) sql_text, sql_text_len) || + my_b_write(&log_file, (uchar*) ";\n",2) || + flush_io_cache(&log_file)) + tmp_errno= errno; + if (tmp_errno) + { + error= 1; + if (! write_error) + { + write_error= 1; + sql_print_error(ER(ER_ERROR_ON_WRITE), name, error); + } + } + } + (void) pthread_mutex_unlock(&LOCK_log); + DBUG_RETURN(error); +} + + +/** + @todo + The following should be using fn_format(); We just need to + first change fn_format() to cut the file name if it's too long. +*/ +const char *MYSQL_LOG::generate_name(const char *log_name, + const char *suffix, + bool strip_ext, char *buff) +{ + if (!log_name || !log_name[0]) + { + strmake(buff, pidfile_name, FN_REFLEN - strlen(suffix) - 1); + return (const char *) + fn_format(buff, buff, "", suffix, MYF(MY_REPLACE_EXT|MY_REPLACE_DIR)); + } + // get rid of extension if the log is binary to avoid problems + if (strip_ext) + { + char *p= fn_ext(log_name); + uint length= (uint) (p - log_name); + strmake(buff, log_name, min(length, FN_REFLEN)); + return (const char*)buff; + } + return log_name; +} + + + +MYSQL_BIN_LOG::MYSQL_BIN_LOG() + :bytes_written(0), prepared_xids(0), file_id(1), open_count(1), + need_start_event(TRUE), m_table_map_version(0), + is_relay_log(0), + description_event_for_exec(0), description_event_for_queue(0) +{ + /* + We don't want to initialize locks here as such initialization depends on + safe_mutex (when using safe_mutex) which depends on MY_INIT(), which is + called only in main(). Doing initialization here would make it happen + before main(). + */ + index_file_name[0] = 0; + bzero((char*) &index_file, sizeof(index_file)); + bzero((char*) &purge_temp, sizeof(purge_temp)); +} + +/* this is called only once */ + +void MYSQL_BIN_LOG::cleanup() +{ + DBUG_ENTER("cleanup"); + if (inited) + { + inited= 0; + close(LOG_CLOSE_INDEX|LOG_CLOSE_STOP_EVENT); + delete description_event_for_queue; + delete description_event_for_exec; + (void) pthread_mutex_destroy(&LOCK_log); + (void) pthread_mutex_destroy(&LOCK_index); + (void) pthread_cond_destroy(&update_cond); + } + DBUG_VOID_RETURN; +} + + +/* Init binlog-specific vars */ +void MYSQL_BIN_LOG::init(bool no_auto_events_arg, ulong max_size_arg) +{ + DBUG_ENTER("MYSQL_BIN_LOG::init"); + no_auto_events= no_auto_events_arg; + max_size= max_size_arg; + DBUG_PRINT("info",("max_size: %lu", max_size)); + DBUG_VOID_RETURN; +} + + +void MYSQL_BIN_LOG::init_pthread_objects() +{ + DBUG_ASSERT(inited == 0); + inited= 1; + (void) pthread_mutex_init(&LOCK_log, MY_MUTEX_INIT_SLOW); + (void) pthread_mutex_init(&LOCK_index, MY_MUTEX_INIT_SLOW); + (void) pthread_cond_init(&update_cond, 0); +} + + +bool MYSQL_BIN_LOG::open_index_file(const char *index_file_name_arg, + const char *log_name) +{ + File index_file_nr= -1; + DBUG_ASSERT(!my_b_inited(&index_file)); + + /* + First open of this class instance + Create an index file that will hold all file names uses for logging. + Add new entries to the end of it. + */ + myf opt= MY_UNPACK_FILENAME; + if (!index_file_name_arg) + { + index_file_name_arg= log_name; // Use same basename for index file + opt= MY_UNPACK_FILENAME | MY_REPLACE_EXT; + } + fn_format(index_file_name, index_file_name_arg, mysql_data_home, + ".index", opt); + if ((index_file_nr= my_open(index_file_name, + O_RDWR | O_CREAT | O_BINARY , + MYF(MY_WME))) < 0 || + my_sync(index_file_nr, MYF(MY_WME)) || + init_io_cache(&index_file, index_file_nr, + IO_SIZE, WRITE_CACHE, + my_seek(index_file_nr,0L,MY_SEEK_END,MYF(0)), + 0, MYF(MY_WME | MY_WAIT_IF_FULL))) + { + /* + TODO: all operations creating/deleting the index file or a log, should + call my_sync_dir() or my_sync_dir_by_file() to be durable. + TODO: file creation should be done with my_create() not my_open(). + */ + if (index_file_nr >= 0) + my_close(index_file_nr,MYF(0)); + return TRUE; + } + return FALSE; +} + + +/** + Open a (new) binlog file. + + - Open the log file and the index file. Register the new + file name in it + - When calling this when the file is in use, you must have a locks + on LOCK_log and LOCK_index. + + @retval + 0 ok + @retval + 1 error +*/ + +bool MYSQL_BIN_LOG::open(const char *log_name, + enum_log_type log_type_arg, + const char *new_name, + enum cache_type io_cache_type_arg, + bool no_auto_events_arg, + ulong max_size_arg, + bool null_created_arg) +{ + File file= -1; + DBUG_ENTER("MYSQL_BIN_LOG::open"); + DBUG_PRINT("enter",("log_type: %d",(int) log_type_arg)); + + write_error=0; + + /* open the main log file */ + if (MYSQL_LOG::open(log_name, log_type_arg, new_name, io_cache_type_arg)) + DBUG_RETURN(1); /* all warnings issued */ + + init(no_auto_events_arg, max_size_arg); + + open_count++; + + DBUG_ASSERT(log_type == LOG_BIN); + + { + bool write_file_name_to_index_file=0; + + if (!my_b_filelength(&log_file)) + { + /* + The binary log file was empty (probably newly created) + This is the normal case and happens when the user doesn't specify + an extension for the binary log files. + In this case we write a standard header to it. + */ + if (my_b_safe_write(&log_file, (uchar*) BINLOG_MAGIC, + BIN_LOG_HEADER_SIZE)) + goto err; + bytes_written+= BIN_LOG_HEADER_SIZE; + write_file_name_to_index_file= 1; + } + + DBUG_ASSERT(my_b_inited(&index_file) != 0); + reinit_io_cache(&index_file, WRITE_CACHE, + my_b_filelength(&index_file), 0, 0); + if (need_start_event && !no_auto_events) + { + /* + In 4.x we set need_start_event=0 here, but in 5.0 we want a Start event + even if this is not the very first binlog. + */ + Format_description_log_event s(BINLOG_VERSION); + /* + don't set LOG_EVENT_BINLOG_IN_USE_F for SEQ_READ_APPEND io_cache + as we won't be able to reset it later + */ + if (io_cache_type == WRITE_CACHE) + s.flags|= LOG_EVENT_BINLOG_IN_USE_F; + if (!s.is_valid()) + goto err; + s.dont_set_created= null_created_arg; + if (s.write(&log_file)) + goto err; + bytes_written+= s.data_written; + } + if (description_event_for_queue && + description_event_for_queue->binlog_version>=4) + { + /* + This is a relay log written to by the I/O slave thread. + Write the event so that others can later know the format of this relay + log. + Note that this event is very close to the original event from the + master (it has binlog version of the master, event types of the + master), so this is suitable to parse the next relay log's event. It + has been produced by + Format_description_log_event::Format_description_log_event(char* buf,). + Why don't we want to write the description_event_for_queue if this + event is for format<4 (3.23 or 4.x): this is because in that case, the + description_event_for_queue describes the data received from the + master, but not the data written to the relay log (*conversion*), + which is in format 4 (slave's). + */ + /* + Set 'created' to 0, so that in next relay logs this event does not + trigger cleaning actions on the slave in + Format_description_log_event::apply_event_impl(). + */ + description_event_for_queue->created= 0; + /* Don't set log_pos in event header */ + description_event_for_queue->set_artificial_event(); + + if (description_event_for_queue->write(&log_file)) + goto err; + bytes_written+= description_event_for_queue->data_written; + } + if (flush_io_cache(&log_file) || + my_sync(log_file.file, MYF(MY_WME))) + goto err; + + if (write_file_name_to_index_file) + { + /* + As this is a new log file, we write the file name to the index + file. As every time we write to the index file, we sync it. + */ + if (my_b_write(&index_file, (uchar*) log_file_name, + strlen(log_file_name)) || + my_b_write(&index_file, (uchar*) "\n", 1) || + flush_io_cache(&index_file) || + my_sync(index_file.file, MYF(MY_WME))) + goto err; + } + } + log_state= LOG_OPENED; + + DBUG_RETURN(0); + +err: + sql_print_error("Could not use %s for logging (error %d). \ +Turning logging off for the whole duration of the MySQL server process. \ +To turn it on again: fix the cause, \ +shutdown the MySQL server and restart it.", name, errno); + if (file >= 0) + my_close(file,MYF(0)); + end_io_cache(&log_file); + end_io_cache(&index_file); + safeFree(name); + log_state= LOG_CLOSED; + DBUG_RETURN(1); +} + + +int MYSQL_BIN_LOG::get_current_log(LOG_INFO* linfo) +{ + pthread_mutex_lock(&LOCK_log); + int ret = raw_get_current_log(linfo); + pthread_mutex_unlock(&LOCK_log); + return ret; +} + +int MYSQL_BIN_LOG::raw_get_current_log(LOG_INFO* linfo) +{ + strmake(linfo->log_file_name, log_file_name, sizeof(linfo->log_file_name)-1); + linfo->pos = my_b_tell(&log_file); + return 0; +} + +/** + Move all data up in a file in an filename index file. + + We do the copy outside of the IO_CACHE as the cache buffers would just + make things slower and more complicated. + In most cases the copy loop should only do one read. + + @param index_file File to move + @param offset Move everything from here to beginning + + @note + File will be truncated to be 'offset' shorter or filled up with newlines + + @retval + 0 ok +*/ + +#ifdef HAVE_REPLICATION + +static bool copy_up_file_and_fill(IO_CACHE *index_file, my_off_t offset) +{ + int bytes_read; + my_off_t init_offset= offset; + File file= index_file->file; + uchar io_buf[IO_SIZE*2]; + DBUG_ENTER("copy_up_file_and_fill"); + + for (;; offset+= bytes_read) + { + (void) my_seek(file, offset, MY_SEEK_SET, MYF(0)); + if ((bytes_read= (int) my_read(file, io_buf, sizeof(io_buf), MYF(MY_WME))) + < 0) + goto err; + if (!bytes_read) + break; // end of file + (void) my_seek(file, offset-init_offset, MY_SEEK_SET, MYF(0)); + if (my_write(file, io_buf, bytes_read, MYF(MY_WME | MY_NABP))) + goto err; + } + /* The following will either truncate the file or fill the end with \n' */ + if (my_chsize(file, offset - init_offset, '\n', MYF(MY_WME)) || + my_sync(file, MYF(MY_WME))) + goto err; + + /* Reset data in old index cache */ + reinit_io_cache(index_file, READ_CACHE, (my_off_t) 0, 0, 1); + DBUG_RETURN(0); + +err: + DBUG_RETURN(1); +} + +#endif /* HAVE_REPLICATION */ + +/** + Find the position in the log-index-file for the given log name. + + @param linfo Store here the found log file name and position to + the NEXT log file name in the index file. + @param log_name Filename to find in the index file. + Is a null pointer if we want to read the first entry + @param need_lock Set this to 1 if the parent doesn't already have a + lock on LOCK_index + + @note + On systems without the truncate function the file will end with one or + more empty lines. These will be ignored when reading the file. + + @retval + 0 ok + @retval + LOG_INFO_EOF End of log-index-file found + @retval + LOG_INFO_IO Got IO error while reading file +*/ + +int MYSQL_BIN_LOG::find_log_pos(LOG_INFO *linfo, const char *log_name, + bool need_lock) +{ + int error= 0; + char *fname= linfo->log_file_name; + uint log_name_len= log_name ? (uint) strlen(log_name) : 0; + DBUG_ENTER("find_log_pos"); + DBUG_PRINT("enter",("log_name: %s", log_name ? log_name : "NULL")); + + /* + Mutex needed because we need to make sure the file pointer does not + move from under our feet + */ + if (need_lock) + pthread_mutex_lock(&LOCK_index); + safe_mutex_assert_owner(&LOCK_index); + + /* As the file is flushed, we can't get an error here */ + (void) reinit_io_cache(&index_file, READ_CACHE, (my_off_t) 0, 0, 0); + + for (;;) + { + uint length; + my_off_t offset= my_b_tell(&index_file); + /* If we get 0 or 1 characters, this is the end of the file */ + + if ((length= my_b_gets(&index_file, fname, FN_REFLEN)) <= 1) + { + /* Did not find the given entry; Return not found or error */ + error= !index_file.error ? LOG_INFO_EOF : LOG_INFO_IO; + break; + } + + // if the log entry matches, null string matching anything + if (!log_name || + (log_name_len == length-1 && fname[log_name_len] == '\n' && + !memcmp(fname, log_name, log_name_len))) + { + DBUG_PRINT("info",("Found log file entry")); + fname[length-1]=0; // remove last \n + linfo->index_file_start_offset= offset; + linfo->index_file_offset = my_b_tell(&index_file); + break; + } + } + + if (need_lock) + pthread_mutex_unlock(&LOCK_index); + DBUG_RETURN(error); +} + + +/** + Find the position in the log-index-file for the given log name. + + @param + linfo Store here the next log file name and position to + the file name after that. + @param + need_lock Set this to 1 if the parent doesn't already have a + lock on LOCK_index + + @note + - Before calling this function, one has to call find_log_pos() + to set up 'linfo' + - Mutex needed because we need to make sure the file pointer does not move + from under our feet + + @retval + 0 ok + @retval + LOG_INFO_EOF End of log-index-file found + @retval + LOG_INFO_IO Got IO error while reading file +*/ + +int MYSQL_BIN_LOG::find_next_log(LOG_INFO* linfo, bool need_lock) +{ + int error= 0; + uint length; + char *fname= linfo->log_file_name; + + if (need_lock) + pthread_mutex_lock(&LOCK_index); + safe_mutex_assert_owner(&LOCK_index); + + /* As the file is flushed, we can't get an error here */ + (void) reinit_io_cache(&index_file, READ_CACHE, linfo->index_file_offset, 0, + 0); + + linfo->index_file_start_offset= linfo->index_file_offset; + if ((length=my_b_gets(&index_file, fname, FN_REFLEN)) <= 1) + { + error = !index_file.error ? LOG_INFO_EOF : LOG_INFO_IO; + goto err; + } + fname[length-1]=0; // kill \n + linfo->index_file_offset = my_b_tell(&index_file); + +err: + if (need_lock) + pthread_mutex_unlock(&LOCK_index); + return error; +} + + +/** + Delete all logs refered to in the index file. + Start writing to a new log file. + + The new index file will only contain this file. + + @param thd Thread + + @note + If not called from slave thread, write start event to new log + + @retval + 0 ok + @retval + 1 error +*/ + +bool MYSQL_BIN_LOG::reset_logs(THD* thd) +{ + LOG_INFO linfo; + bool error=0; + const char* save_name; + DBUG_ENTER("reset_logs"); + + ha_reset_logs(thd); + /* + We need to get both locks to be sure that no one is trying to + write to the index log file. + */ + pthread_mutex_lock(&LOCK_log); + pthread_mutex_lock(&LOCK_index); + + /* + The following mutex is needed to ensure that no threads call + 'delete thd' as we would then risk missing a 'rollback' from this + thread. If the transaction involved MyISAM tables, it should go + into binlog even on rollback. + */ + VOID(pthread_mutex_lock(&LOCK_thread_count)); + + /* Save variables so that we can reopen the log */ + save_name=name; + name=0; // Protect against free + close(LOG_CLOSE_TO_BE_OPENED); + + /* First delete all old log files */ + + if (find_log_pos(&linfo, NullS, 0)) + { + error=1; + goto err; + } + + for (;;) + { + if ((error= my_delete_allow_opened(linfo.log_file_name, MYF(0))) != 0) + { + if (my_errno == ENOENT) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE), + linfo.log_file_name); + sql_print_information("Failed to delete file '%s'", + linfo.log_file_name); + my_errno= 0; + error= 0; + } + else + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_BINLOG_PURGE_FATAL_ERR, + "a problem with deleting %s; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + linfo.log_file_name); + error= 1; + goto err; + } + } + if (find_next_log(&linfo, 0)) + break; + } + + /* Start logging with a new file */ + close(LOG_CLOSE_INDEX); + if ((error= my_delete_allow_opened(index_file_name, MYF(0)))) // Reset (open will update) + { + if (my_errno == ENOENT) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE), + index_file_name); + sql_print_information("Failed to delete file '%s'", + index_file_name); + my_errno= 0; + error= 0; + } + else + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_BINLOG_PURGE_FATAL_ERR, + "a problem with deleting %s; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + index_file_name); + error= 1; + goto err; + } + } + if (!thd->slave_thread) + need_start_event=1; + if (!open_index_file(index_file_name, 0)) + open(save_name, log_type, 0, io_cache_type, no_auto_events, max_size, 0); + my_free((uchar*) save_name, MYF(0)); + +err: + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + pthread_mutex_unlock(&LOCK_index); + pthread_mutex_unlock(&LOCK_log); + DBUG_RETURN(error); +} + + +/** + Delete relay log files prior to rli->group_relay_log_name + (i.e. all logs which are not involved in a non-finished group + (transaction)), remove them from the index file and start on next + relay log. + + IMPLEMENTATION + - Protects index file with LOCK_index + - Delete relevant relay log files + - Copy all file names after these ones to the front of the index file + - If the OS has truncate, truncate the file, else fill it with \n' + - Read the next file name from the index file and store in rli->linfo + + @param rli Relay log information + @param included If false, all relay logs that are strictly before + rli->group_relay_log_name are deleted ; if true, the + latter is deleted too (i.e. all relay logs + read by the SQL slave thread are deleted). + + @note + - This is only called from the slave-execute thread when it has read + all commands from a relay log and want to switch to a new relay log. + - When this happens, we can be in an active transaction as + a transaction can span over two relay logs + (although it is always written as a single block to the master's binary + log, hence cannot span over two master's binary logs). + + @retval + 0 ok + @retval + LOG_INFO_EOF End of log-index-file found + @retval + LOG_INFO_SEEK Could not allocate IO cache + @retval + LOG_INFO_IO Got IO error while reading file +*/ + +#ifdef HAVE_REPLICATION + +int MYSQL_BIN_LOG::purge_first_log(Relay_log_info* rli, bool included) +{ + int error; + char *to_purge_if_included= NULL; + DBUG_ENTER("purge_first_log"); + + DBUG_ASSERT(is_open()); + DBUG_ASSERT(rli->slave_running == 1); + DBUG_ASSERT(!strcmp(rli->linfo.log_file_name,rli->event_relay_log_name)); + + pthread_mutex_lock(&LOCK_index); + to_purge_if_included= my_strdup(rli->group_relay_log_name, MYF(0)); + + /* + Read the next log file name from the index file and pass it back to + the caller. + */ + if((error=find_log_pos(&rli->linfo, rli->event_relay_log_name, 0)) || + (error=find_next_log(&rli->linfo, 0))) + { + char buff[22]; + sql_print_error("next log error: %d offset: %s log: %s included: %d", + error, + llstr(rli->linfo.index_file_offset,buff), + rli->event_relay_log_name, + included); + goto err; + } + + /* + Reset rli's coordinates to the current log. + */ + rli->event_relay_log_pos= BIN_LOG_HEADER_SIZE; + strmake(rli->event_relay_log_name,rli->linfo.log_file_name, + sizeof(rli->event_relay_log_name)-1); + + /* + If we removed the rli->group_relay_log_name file, + we must update the rli->group* coordinates, otherwise do not touch it as the + group's execution is not finished (e.g. COMMIT not executed) + */ + if (included) + { + rli->group_relay_log_pos = BIN_LOG_HEADER_SIZE; + strmake(rli->group_relay_log_name,rli->linfo.log_file_name, + sizeof(rli->group_relay_log_name)-1); + rli->notify_group_relay_log_name_update(); + } + + /* Store where we are in the new file for the execution thread */ + flush_relay_log_info(rli); + + DBUG_EXECUTE_IF("crash_before_purge_logs", abort();); + + pthread_mutex_lock(&rli->log_space_lock); + rli->relay_log.purge_logs(to_purge_if_included, included, + 0, 0, &rli->log_space_total); + // Tell the I/O thread to take the relay_log_space_limit into account + rli->ignore_log_space_limit= 0; + pthread_mutex_unlock(&rli->log_space_lock); + + /* + Ok to broadcast after the critical region as there is no risk of + the mutex being destroyed by this thread later - this helps save + context switches + */ + pthread_cond_broadcast(&rli->log_space_cond); + + /* + * Need to update the log pos because purge logs has been called + * after fetching initially the log pos at the begining of the method. + */ + if((error=find_log_pos(&rli->linfo, rli->event_relay_log_name, 0))) + { + char buff[22]; + sql_print_error("next log error: %d offset: %s log: %s included: %d", + error, + llstr(rli->linfo.index_file_offset,buff), + rli->group_relay_log_name, + included); + goto err; + } + + /* If included was passed, rli->linfo should be the first entry. */ + DBUG_ASSERT(!included || rli->linfo.index_file_start_offset == 0); + +err: + my_free(to_purge_if_included, MYF(0)); + pthread_mutex_unlock(&LOCK_index); + DBUG_RETURN(error); +} + +/** + Update log index_file. +*/ + +int MYSQL_BIN_LOG::update_log_index(LOG_INFO* log_info, bool need_update_threads) +{ + if (copy_up_file_and_fill(&index_file, log_info->index_file_start_offset)) + return LOG_INFO_IO; + + // now update offsets in index file for running threads + if (need_update_threads) + adjust_linfo_offsets(log_info->index_file_start_offset); + return 0; +} + +/** + Remove all logs before the given log from disk and from the index file. + + @param to_log Delete all log file name before this file. + @param included If true, to_log is deleted too. + @param need_mutex + @param need_update_threads If we want to update the log coordinates of + all threads. False for relay logs, true otherwise. + @param freed_log_space If not null, decrement this variable of + the amount of log space freed + + @note + If any of the logs before the deleted one is in use, + only purge logs up to this one. + + @retval + 0 ok + @retval + LOG_INFO_EOF to_log not found + LOG_INFO_EMFILE too many files opened + LOG_INFO_FATAL if any other than ENOENT error from + my_stat() or my_delete() +*/ + +int MYSQL_BIN_LOG::purge_logs(const char *to_log, + bool included, + bool need_mutex, + bool need_update_threads, + ulonglong *decrease_log_space) +{ + int error; + bool exit_loop= 0; + LOG_INFO log_info; + THD *thd= current_thd; + DBUG_ENTER("purge_logs"); + DBUG_PRINT("info",("to_log= %s",to_log)); + + if (need_mutex) + pthread_mutex_lock(&LOCK_index); + if ((error=find_log_pos(&log_info, to_log, 0 /*no mutex*/))) + { + sql_print_error("MYSQL_LOG::purge_logs was called with file %s not " + "listed in the index.", to_log); + goto err; + } + + /* + For crash recovery reasons the index needs to be updated before + any files are deleted. Move files to be deleted into a temp file + to be processed after the index is updated. + */ + if (!my_b_inited(&purge_temp)) + { + if ((error=open_cached_file(&purge_temp, mysql_tmpdir, TEMP_PREFIX, + DISK_BUFFER_SIZE, MYF(MY_WME)))) + { + sql_print_error("MYSQL_LOG::purge_logs failed to open purge_temp"); + goto err; + } + } + else + { + if ((error=reinit_io_cache(&purge_temp, WRITE_CACHE, 0, 0, 1))) + { + sql_print_error("MYSQL_LOG::purge_logs failed to reinit purge_temp " + "for write"); + goto err; + } + } + + /* + File name exists in index file; delete until we find this file + or a file that is used. + */ + if ((error=find_log_pos(&log_info, NullS, 0 /*no mutex*/))) + goto err; + while ((strcmp(to_log,log_info.log_file_name) || (exit_loop=included)) && + !log_in_use(log_info.log_file_name)) + { + if ((error=my_b_write(&purge_temp, (const uchar*)log_info.log_file_name, + strlen(log_info.log_file_name))) || + (error=my_b_write(&purge_temp, (const uchar*)"\n", 1))) + { + sql_print_error("MYSQL_LOG::purge_logs failed to copy %s to purge_temp", + log_info.log_file_name); + goto err; + } + + if (find_next_log(&log_info, 0) || exit_loop) + break; + } + + /* We know how many files to delete. Update index file. */ + if ((error=update_log_index(&log_info, need_update_threads))) + { + sql_print_error("MSYQL_LOG::purge_logs failed to update the index file"); + goto err; + } + + DBUG_EXECUTE_IF("crash_after_update_index", abort();); + + /* Switch purge_temp for read. */ + if ((error=reinit_io_cache(&purge_temp, READ_CACHE, 0, 0, 0))) + { + sql_print_error("MSYQL_LOG::purge_logs failed to reinit purge_temp " + "for read"); + goto err; + } + + /* Read each entry from purge_temp and delete the file. */ + for (;;) + { + uint length; + + if ((length=my_b_gets(&purge_temp, log_info.log_file_name, + FN_REFLEN)) <= 1) + { + if (purge_temp.error) + { + error= purge_temp.error; + sql_print_error("MSYQL_LOG::purge_logs error %d reading from " + "purge_temp", error); + goto err; + } + + /* Reached EOF */ + break; + } + + /* Get rid of the trailing '\n' */ + log_info.log_file_name[length-1]= 0; + + ha_binlog_index_purge_file(current_thd, log_info.log_file_name); + + MY_STAT s; + if (!my_stat(log_info.log_file_name, &s, MYF(0))) + { + if (my_errno == ENOENT) + { + /* + It's not fatal if we can't stat a log file that does not exist; + If we could not stat, we won't delete. + */ + if (thd) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE), + log_info.log_file_name); + } + sql_print_information("Failed to execute my_stat on file '%s'", + log_info.log_file_name); + my_errno= 0; + } + else + { + /* + Other than ENOENT are fatal + */ + if (thd) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_BINLOG_PURGE_FATAL_ERR, + "a problem with getting info on being purged %s; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + log_info.log_file_name); + } + else + { + sql_print_information("Failed to delete log file '%s'; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + log_info.log_file_name); + } + error= LOG_INFO_FATAL; + goto err; + } + } + else + { + DBUG_PRINT("info",("purging %s",log_info.log_file_name)); + if (!my_delete(log_info.log_file_name, MYF(0))) + { + if (decrease_log_space) + *decrease_log_space-= s.st_size; + } + else + { + if (my_errno == ENOENT) + { + if (thd) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE), + log_info.log_file_name); + } + sql_print_information("Failed to delete file '%s'", + log_info.log_file_name); + my_errno= 0; + } + else + { + if (thd) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_BINLOG_PURGE_FATAL_ERR, + "a problem with deleting %s; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + log_info.log_file_name); + } + else + { + sql_print_information("Failed to delete file '%s'; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + log_info.log_file_name); + } + if (my_errno == EMFILE) + { + DBUG_PRINT("info", + ("my_errno: %d, set ret = LOG_INFO_EMFILE", my_errno)); + error= LOG_INFO_EMFILE; + goto err; + } + error= LOG_INFO_FATAL; + goto err; + } + } + } + } + +err: + close_cached_file(&purge_temp); + if (need_mutex) + pthread_mutex_unlock(&LOCK_index); + DBUG_RETURN(error); +} + +/** + Remove all logs before the given file date from disk and from the + index file. + + @param thd Thread pointer + @param purge_time Delete all log files before given date. + + @note + If any of the logs before the deleted one is in use, + only purge logs up to this one. + + @retval + 0 ok + @retval + LOG_INFO_PURGE_NO_ROTATE Binary file that can't be rotated + LOG_INFO_FATAL if any other than ENOENT error from + my_stat() or my_delete() +*/ + +int MYSQL_BIN_LOG::purge_logs_before_date(time_t purge_time) +{ + int error; + char to_log[FN_REFLEN]; + LOG_INFO log_info; + MY_STAT stat_area; + THD *thd= current_thd; + + DBUG_ENTER("purge_logs_before_date"); + + pthread_mutex_lock(&LOCK_index); + to_log[0]= 0; + + if ((error=find_log_pos(&log_info, NullS, 0 /*no mutex*/))) + goto err; + + while (strcmp(log_file_name, log_info.log_file_name) && + !log_in_use(log_info.log_file_name)) + { + if (!my_stat(log_info.log_file_name, &stat_area, MYF(0))) + { + if (my_errno == ENOENT) + { + /* + It's not fatal if we can't stat a log file that does not exist. + */ + if (thd) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_LOG_PURGE_NO_FILE, ER(ER_LOG_PURGE_NO_FILE), + log_info.log_file_name); + } + sql_print_information("Failed to execute my_stat on file '%s'", + log_info.log_file_name); + my_errno= 0; + } + else + { + /* + Other than ENOENT are fatal + */ + if (thd) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_BINLOG_PURGE_FATAL_ERR, + "a problem with getting info on being purged %s; " + "consider examining correspondence " + "of your binlog index file " + "to the actual binlog files", + log_info.log_file_name); + } + else + { + sql_print_information("Failed to delete log file '%s'", + log_info.log_file_name); + } + error= LOG_INFO_FATAL; + goto err; + } + } + else + { + if (stat_area.st_mtime < purge_time) + strmake(to_log, + log_info.log_file_name, + sizeof(log_info.log_file_name)); + else + break; + } + if (find_next_log(&log_info, 0)) + break; + } + + error= (to_log[0] ? purge_logs(to_log, 1, 0, 1, (ulonglong *) 0) : 0); + +err: + pthread_mutex_unlock(&LOCK_index); + DBUG_RETURN(error); +} +#endif /* HAVE_REPLICATION */ + + +/** + Create a new log file name. + + @param buf buf of at least FN_REFLEN where new name is stored + + @note + If file name will be longer then FN_REFLEN it will be truncated +*/ + +void MYSQL_BIN_LOG::make_log_name(char* buf, const char* log_ident) +{ + uint dir_len = dirname_length(log_file_name); + if (dir_len >= FN_REFLEN) + dir_len=FN_REFLEN-1; + strnmov(buf, log_file_name, dir_len); + strmake(buf+dir_len, log_ident, FN_REFLEN - dir_len -1); +} + + +/** + Check if we are writing/reading to the given log file. +*/ + +bool MYSQL_BIN_LOG::is_active(const char *log_file_name_arg) +{ + return !strcmp(log_file_name, log_file_name_arg); +} + + +/* + Wrappers around new_file_impl to avoid using argument + to control locking. The argument 1) less readable 2) breaks + incapsulation 3) allows external access to the class without + a lock (which is not possible with private new_file_without_locking + method). +*/ + +void MYSQL_BIN_LOG::new_file() +{ + new_file_impl(1); +} + + +void MYSQL_BIN_LOG::new_file_without_locking() +{ + new_file_impl(0); +} + + +/** + Start writing to a new log file or reopen the old file. + + @param need_lock Set to 1 if caller has not locked LOCK_log + + @note + The new file name is stored last in the index file +*/ + +void MYSQL_BIN_LOG::new_file_impl(bool need_lock) +{ + char new_name[FN_REFLEN], *new_name_ptr, *old_name; + + DBUG_ENTER("MYSQL_BIN_LOG::new_file_impl"); + if (!is_open()) + { + DBUG_PRINT("info",("log is closed")); + DBUG_VOID_RETURN; + } + + if (need_lock) + pthread_mutex_lock(&LOCK_log); + pthread_mutex_lock(&LOCK_index); + + safe_mutex_assert_owner(&LOCK_log); + safe_mutex_assert_owner(&LOCK_index); + + /* + if binlog is used as tc log, be sure all xids are "unlogged", + so that on recover we only need to scan one - latest - binlog file + for prepared xids. As this is expected to be a rare event, + simple wait strategy is enough. We're locking LOCK_log to be sure no + new Xid_log_event's are added to the log (and prepared_xids is not + increased), and waiting on COND_prep_xids for late threads to + catch up. + */ + if (prepared_xids) + { + tc_log_page_waits++; + pthread_mutex_lock(&LOCK_prep_xids); + while (prepared_xids) { + DBUG_PRINT("info", ("prepared_xids=%lu", prepared_xids)); + pthread_cond_wait(&COND_prep_xids, &LOCK_prep_xids); + } + pthread_mutex_unlock(&LOCK_prep_xids); + } + + /* Reuse old name if not binlog and not update log */ + new_name_ptr= name; + + /* + If user hasn't specified an extension, generate a new log name + We have to do this here and not in open as we want to store the + new file name in the current binary log file. + */ + if (generate_new_name(new_name, name)) + goto end; + new_name_ptr=new_name; + + if (log_type == LOG_BIN) + { + if (!no_auto_events) + { + /* + We log the whole file name for log file as the user may decide + to change base names at some point. + */ + Rotate_log_event r(new_name+dirname_length(new_name), + 0, LOG_EVENT_OFFSET, is_relay_log ? Rotate_log_event::RELAY_LOG : 0); + r.write(&log_file); + bytes_written += r.data_written; + } + /* + Update needs to be signalled even if there is no rotate event + log rotation should give the waiting thread a signal to + discover EOF and move on to the next log. + */ + signal_update(); + } + old_name=name; + name=0; // Don't free name + close(LOG_CLOSE_TO_BE_OPENED); + + /* + Note that at this point, log_state != LOG_CLOSED (important for is_open()). + */ + + /* + new_file() is only used for rotation (in FLUSH LOGS or because size > + max_binlog_size or max_relay_log_size). + If this is a binary log, the Format_description_log_event at the beginning of + the new file should have created=0 (to distinguish with the + Format_description_log_event written at server startup, which should + trigger temp tables deletion on slaves. + */ + + open(old_name, log_type, new_name_ptr, + io_cache_type, no_auto_events, max_size, 1); + my_free(old_name,MYF(0)); + +end: + if (need_lock) + pthread_mutex_unlock(&LOCK_log); + pthread_mutex_unlock(&LOCK_index); + + DBUG_VOID_RETURN; +} + + +bool MYSQL_BIN_LOG::append(Log_event* ev) +{ + bool error = 0; + pthread_mutex_lock(&LOCK_log); + DBUG_ENTER("MYSQL_BIN_LOG::append"); + + DBUG_ASSERT(log_file.type == SEQ_READ_APPEND); + /* + Log_event::write() is smart enough to use my_b_write() or + my_b_append() depending on the kind of cache we have. + */ + if (ev->write(&log_file)) + { + error=1; + goto err; + } + bytes_written+= ev->data_written; + DBUG_PRINT("info",("max_size: %lu",max_size)); + if ((uint) my_b_append_tell(&log_file) > max_size) + new_file_without_locking(); + +err: + pthread_mutex_unlock(&LOCK_log); + signal_update(); // Safe as we don't call close + DBUG_RETURN(error); +} + + +bool MYSQL_BIN_LOG::appendv(const char* buf, uint len,...) +{ + bool error= 0; + DBUG_ENTER("MYSQL_BIN_LOG::appendv"); + va_list(args); + va_start(args,len); + + DBUG_ASSERT(log_file.type == SEQ_READ_APPEND); + + safe_mutex_assert_owner(&LOCK_log); + do + { + if (my_b_append(&log_file,(uchar*) buf,len)) + { + error= 1; + goto err; + } + bytes_written += len; + } while ((buf=va_arg(args,const char*)) && (len=va_arg(args,uint))); + DBUG_PRINT("info",("max_size: %lu",max_size)); + if ((uint) my_b_append_tell(&log_file) > max_size) + new_file_without_locking(); + +err: + if (!error) + signal_update(); + DBUG_RETURN(error); +} + + +bool MYSQL_BIN_LOG::flush_and_sync() +{ + int err=0, fd=log_file.file; + safe_mutex_assert_owner(&LOCK_log); + if (flush_io_cache(&log_file)) + return 1; + if (++sync_binlog_counter >= sync_binlog_period && sync_binlog_period) + { + sync_binlog_counter= 0; + err=my_sync(fd, MYF(MY_WME)); + } + return err; +} + +void MYSQL_BIN_LOG::start_union_events(THD *thd, query_id_t query_id_param) +{ + DBUG_ASSERT(!thd->binlog_evt_union.do_union); + thd->binlog_evt_union.do_union= TRUE; + thd->binlog_evt_union.unioned_events= FALSE; + thd->binlog_evt_union.unioned_events_trans= FALSE; + thd->binlog_evt_union.first_query_id= query_id_param; +} + +void MYSQL_BIN_LOG::stop_union_events(THD *thd) +{ + DBUG_ASSERT(thd->binlog_evt_union.do_union); + thd->binlog_evt_union.do_union= FALSE; +} + +bool MYSQL_BIN_LOG::is_query_in_union(THD *thd, query_id_t query_id_param) +{ + return (thd->binlog_evt_union.do_union && + query_id_param >= thd->binlog_evt_union.first_query_id); +} + + +/* + These functions are placed in this file since they need access to + binlog_hton, which has internal linkage. +*/ + +int THD::binlog_setup_trx_data() +{ + DBUG_ENTER("THD::binlog_setup_trx_data"); + binlog_trx_data *trx_data= + (binlog_trx_data*) thd_get_ha_data(this, binlog_hton); + + if (trx_data) + DBUG_RETURN(0); // Already set up + + trx_data= (binlog_trx_data*) my_malloc(sizeof(binlog_trx_data), MYF(MY_ZEROFILL)); + if (!trx_data || + open_cached_file(&trx_data->trans_log, mysql_tmpdir, + LOG_PREFIX, binlog_cache_size, MYF(MY_WME))) + { + my_free((uchar*)trx_data, MYF(MY_ALLOW_ZERO_PTR)); + DBUG_RETURN(1); // Didn't manage to set it up + } + thd_set_ha_data(this, binlog_hton, trx_data); + + trx_data= new (thd_get_ha_data(this, binlog_hton)) binlog_trx_data; + + DBUG_RETURN(0); +} + +/* + Function to start a statement and optionally a transaction for the + binary log. + + SYNOPSIS + binlog_start_trans_and_stmt() + + DESCRIPTION + + This function does three things: + - Start a transaction if not in autocommit mode or if a BEGIN + statement has been seen. + + - Start a statement transaction to allow us to truncate the binary + log. + + - Save the currrent binlog position so that we can roll back the + statement by truncating the transaction log. + + We only update the saved position if the old one was undefined, + the reason is that there are some cases (e.g., for CREATE-SELECT) + where the position is saved twice (e.g., both in + select_create::prepare() and THD::binlog_write_table_map()) , but + we should use the first. This means that calls to this function + can be used to start the statement before the first table map + event, to include some extra events. + */ + +void +THD::binlog_start_trans_and_stmt() +{ + binlog_trx_data *trx_data= (binlog_trx_data*) thd_get_ha_data(this, binlog_hton); + DBUG_ENTER("binlog_start_trans_and_stmt"); + DBUG_PRINT("enter", ("trx_data: 0x%lx trx_data->before_stmt_pos: %lu", + (long) trx_data, + (trx_data ? (ulong) trx_data->before_stmt_pos : + (ulong) 0))); + + if (trx_data == NULL || + trx_data->before_stmt_pos == MY_OFF_T_UNDEF) + { + this->binlog_set_stmt_begin(); + if (options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) + trans_register_ha(this, TRUE, binlog_hton); + trans_register_ha(this, FALSE, binlog_hton); + /* + Mark statement transaction as read/write. We never start + a binary log transaction and keep it read-only, + therefore it's best to mark the transaction read/write just + at the same time we start it. + Not necessary to mark the normal transaction read/write + since the statement-level flag will be propagated automatically + inside ha_commit_trans. + */ + ha_data[binlog_hton->slot].ha_info[0].set_trx_read_write(); + } + DBUG_VOID_RETURN; +} + +void THD::binlog_set_stmt_begin() { + binlog_trx_data *trx_data= + (binlog_trx_data*) thd_get_ha_data(this, binlog_hton); + + /* + The call to binlog_trans_log_savepos() might create the trx_data + structure, if it didn't exist before, so we save the position + into an auto variable and then write it into the transaction + data for the binary log (i.e., trx_data). + */ + my_off_t pos= 0; + binlog_trans_log_savepos(this, &pos); + trx_data= (binlog_trx_data*) thd_get_ha_data(this, binlog_hton); + trx_data->before_stmt_pos= pos; +} + + +/* + Write a table map to the binary log. + */ + +int THD::binlog_write_table_map(TABLE *table, bool is_trans) +{ + int error; + DBUG_ENTER("THD::binlog_write_table_map"); + DBUG_PRINT("enter", ("table: 0x%lx (%s: #%lu)", + (long) table, table->s->table_name.str, + table->s->table_map_id)); + + /* Pre-conditions */ + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); + DBUG_ASSERT(table->s->table_map_id != ULONG_MAX); + + Table_map_log_event::flag_set const + flags= Table_map_log_event::TM_NO_FLAGS; + + Table_map_log_event + the_event(this, table, table->s->table_map_id, is_trans, flags); + + if (is_trans && binlog_table_maps == 0) + binlog_start_trans_and_stmt(); + + if ((error= mysql_bin_log.write(&the_event))) + DBUG_RETURN(error); + + binlog_table_maps++; + table->s->table_map_version= mysql_bin_log.table_map_version(); + DBUG_RETURN(0); +} + +Rows_log_event* +THD::binlog_get_pending_rows_event() const +{ + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(this, binlog_hton); + /* + This is less than ideal, but here's the story: If there is no + trx_data, prepare_pending_rows_event() has never been called + (since the trx_data is set up there). In that case, we just return + NULL. + */ + return trx_data ? trx_data->pending() : NULL; +} + +void +THD::binlog_set_pending_rows_event(Rows_log_event* ev) +{ + if (thd_get_ha_data(this, binlog_hton) == NULL) + binlog_setup_trx_data(); + + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(this, binlog_hton); + + DBUG_ASSERT(trx_data); + trx_data->set_pending(ev); +} + + +/** + Remove the pending rows event, discarding any outstanding rows. + + If there is no pending rows event available, this is effectively a + no-op. + */ +int +MYSQL_BIN_LOG::remove_pending_rows_event(THD *thd) +{ + DBUG_ENTER("MYSQL_BIN_LOG::remove_pending_rows_event"); + + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + + DBUG_ASSERT(trx_data); + + if (Rows_log_event* pending= trx_data->pending()) + { + delete pending; + trx_data->set_pending(NULL); + } + + DBUG_RETURN(0); +} + +/* + Moves the last bunch of rows from the pending Rows event to the binlog + (either cached binlog if transaction, or disk binlog). Sets a new pending + event. +*/ +int +MYSQL_BIN_LOG::flush_and_set_pending_rows_event(THD *thd, + Rows_log_event* event) +{ + DBUG_ENTER("MYSQL_BIN_LOG::flush_and_set_pending_rows_event(event)"); + DBUG_ASSERT(mysql_bin_log.is_open()); + DBUG_PRINT("enter", ("event: 0x%lx", (long) event)); + + int error= 0; + + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + + DBUG_ASSERT(trx_data); + + DBUG_PRINT("info", ("trx_data->pending(): 0x%lx", (long) trx_data->pending())); + + if (Rows_log_event* pending= trx_data->pending()) + { + IO_CACHE *file= &log_file; + + /* + Decide if we should write to the log file directly or to the + transaction log. + */ + if (pending->get_cache_stmt() || my_b_tell(&trx_data->trans_log)) + file= &trx_data->trans_log; + + /* + If we are writing to the log file directly, we could avoid + locking the log. This does not work since we need to step the + m_table_map_version below, and that change has to be protected + by the LOCK_log mutex. + */ + pthread_mutex_lock(&LOCK_log); + + /* + Write pending event to log file or transaction cache + */ + if (pending->write(file)) + { + pthread_mutex_unlock(&LOCK_log); + set_write_error(thd); + DBUG_RETURN(1); + } + + /* + We step the table map version if we are writing an event + representing the end of a statement. We do this regardless of + wheather we write to the transaction cache or to directly to the + file. + + In an ideal world, we could avoid stepping the table map version + if we were writing to a transaction cache, since we could then + reuse the table map that was written earlier in the transaction + cache. This does not work since STMT_END_F implies closing all + table mappings on the slave side. + + TODO: Find a solution so that table maps does not have to be + written several times within a transaction. + */ + if (pending->get_flags(Rows_log_event::STMT_END_F)) + ++m_table_map_version; + + delete pending; + + if (file == &log_file) + { + error= flush_and_sync(); + if (!error) + { + signal_update(); + rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED); + } + } + + pthread_mutex_unlock(&LOCK_log); + } + + thd->binlog_set_pending_rows_event(event); + + DBUG_RETURN(error); +} + +/** + Write an event to the binary log. +*/ + +bool MYSQL_BIN_LOG::write(Log_event *event_info) +{ + THD *thd= event_info->thd; + bool error= 1; + DBUG_ENTER("MYSQL_BIN_LOG::write(Log_event *)"); + + if (thd->binlog_evt_union.do_union) + { + /* + In Stored function; Remember that function call caused an update. + We will log the function call to the binary log on function exit + */ + thd->binlog_evt_union.unioned_events= TRUE; + thd->binlog_evt_union.unioned_events_trans |= event_info->cache_stmt; + DBUG_RETURN(0); + } + + /* + Flush the pending rows event to the transaction cache or to the + log file. Since this function potentially aquire the LOCK_log + mutex, we do this before aquiring the LOCK_log mutex in this + function. + + We only end the statement if we are in a top-level statement. If + we are inside a stored function, we do not end the statement since + this will close all tables on the slave. + */ + bool const end_stmt= + thd->prelocked_mode && thd->lex->requires_prelocking(); + if (thd->binlog_flush_pending_rows_event(end_stmt)) + DBUG_RETURN(error); + + pthread_mutex_lock(&LOCK_log); + + /* + In most cases this is only called if 'is_open()' is true; in fact this is + mostly called if is_open() *was* true a few instructions before, but it + could have changed since. + */ + if (likely(is_open())) + { + IO_CACHE *file= &log_file; +#ifdef HAVE_REPLICATION + /* + In the future we need to add to the following if tests like + "do the involved tables match (to be implemented) + binlog_[wild_]{do|ignore}_table?" (WL#1049)" + */ + const char *local_db= event_info->get_db(); + if ((thd && !(thd->options & OPTION_BIN_LOG)) || + (!binlog_filter->db_ok(local_db))) + { + VOID(pthread_mutex_unlock(&LOCK_log)); + DBUG_RETURN(0); + } +#endif /* HAVE_REPLICATION */ + +#if defined(USING_TRANSACTIONS) + /* + Should we write to the binlog cache or to the binlog on disk? + Write to the binlog cache if: + - it is already not empty (meaning we're in a transaction; note that the + present event could be about a non-transactional table, but still we need + to write to the binlog cache in that case to handle updates to mixed + trans/non-trans table types the best possible in binlogging) + - or if the event asks for it (cache_stmt == TRUE). + */ + if (opt_using_transactions && thd) + { + if (thd->binlog_setup_trx_data()) + goto err; + + binlog_trx_data *const trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + IO_CACHE *trans_log= &trx_data->trans_log; + my_off_t trans_log_pos= my_b_tell(trans_log); + if (event_info->get_cache_stmt() || trans_log_pos != 0 || + stmt_has_updated_trans_table(thd)) + { + DBUG_PRINT("info", ("Using trans_log: cache: %d, trans_log_pos: %lu", + event_info->get_cache_stmt(), + (ulong) trans_log_pos)); + thd->binlog_start_trans_and_stmt(); + file= trans_log; + } + /* + TODO as Mats suggested, for all the cases above where we write to + trans_log, it sounds unnecessary to lock LOCK_log. We should rather + test first if we want to write to trans_log, and if not, lock + LOCK_log. + */ + } +#endif /* USING_TRANSACTIONS */ + DBUG_PRINT("info",("event type: %d",event_info->get_type_code())); + + /* + No check for auto events flag here - this write method should + never be called if auto-events are enabled + */ + + /* + 1. Write first log events which describe the 'run environment' + of the SQL command + */ + + /* + If row-based binlogging, Insert_id, Rand and other kind of "setting + context" events are not needed. + */ + if (thd) + { + if (!thd->current_stmt_binlog_row_based) + { + if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt) + { + Intvar_log_event e(thd,(uchar) LAST_INSERT_ID_EVENT, + thd->first_successful_insert_id_in_prev_stmt_for_binlog); + if (e.write(file)) + goto err; + } + if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0) + { + DBUG_PRINT("info",("number of auto_inc intervals: %u", + thd->auto_inc_intervals_in_cur_stmt_for_binlog. + nb_elements())); + Intvar_log_event e(thd, (uchar) INSERT_ID_EVENT, + thd->auto_inc_intervals_in_cur_stmt_for_binlog. + minimum()); + if (e.write(file)) + goto err; + } + if (thd->rand_used) + { + Rand_log_event e(thd,thd->rand_saved_seed1,thd->rand_saved_seed2); + if (e.write(file)) + goto err; + } + if (thd->user_var_events.elements) + { + for (uint i= 0; i < thd->user_var_events.elements; i++) + { + BINLOG_USER_VAR_EVENT *user_var_event; + get_dynamic(&thd->user_var_events,(uchar*) &user_var_event, i); + User_var_log_event e(thd, user_var_event->user_var_event->name.str, + user_var_event->user_var_event->name.length, + user_var_event->value, + user_var_event->length, + user_var_event->type, + user_var_event->charset_number); + if (e.write(file)) + goto err; + } + } + } + } + + /* + Write the SQL command + */ + + if (event_info->write(file) || + DBUG_EVALUATE_IF("injecting_fault_writing", 1, 0)) + goto err; + + if (file == &log_file) // we are writing to the real log (disk) + { + if (flush_and_sync()) + goto err; + signal_update(); + rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED); + } + error=0; + +err: + if (error) + set_write_error(thd); + } + + if (event_info->flags & LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F) + ++m_table_map_version; + + pthread_mutex_unlock(&LOCK_log); + DBUG_RETURN(error); +} + + +int error_log_print(enum loglevel level, const char *format, + va_list args) +{ + return logger.error_log_print(level, format, args); +} + + +bool slow_log_print(THD *thd, const char *query, uint query_length, + ulonglong current_utime) +{ + return logger.slow_log_print(thd, query, query_length, current_utime); +} + + +bool LOGGER::log_command(THD *thd, enum enum_server_command command) +{ +#ifndef NO_EMBEDDED_ACCESS_CHECKS + Security_context *sctx= thd->security_ctx; +#endif + /* + Log command if we have at least one log event handler enabled and want + to log this king of commands + */ + if (*general_log_handler_list && (what_to_log & (1L << (uint) command))) + { + if ((thd->options & OPTION_LOG_OFF) +#ifndef NO_EMBEDDED_ACCESS_CHECKS + && (sctx->master_access & SUPER_ACL) +#endif + ) + { + /* No logging */ + return FALSE; + } + + return TRUE; + } + + return FALSE; +} + + +bool general_log_print(THD *thd, enum enum_server_command command, + const char *format, ...) +{ + va_list args; + uint error= 0; + + /* Print the message to the buffer if we want to log this king of commands */ + if (! logger.log_command(thd, command)) + return FALSE; + + va_start(args, format); + error= logger.general_log_print(thd, command, format, args); + va_end(args); + + return error; +} + +bool general_log_write(THD *thd, enum enum_server_command command, + const char *query, uint query_length) +{ + /* Write the message to the log if we want to log this king of commands */ + if (logger.log_command(thd, command)) + return logger.general_log_write(thd, command, query, query_length); + + return FALSE; +} + +void MYSQL_BIN_LOG::rotate_and_purge(uint flags) +{ + if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED)) + pthread_mutex_lock(&LOCK_log); + if ((flags & RP_FORCE_ROTATE) || + (my_b_tell(&log_file) >= (my_off_t) max_size)) + { + new_file_without_locking(); +#ifdef HAVE_REPLICATION + if (expire_logs_days) + { + time_t purge_time= my_time(0) - expire_logs_days*24*60*60; + if (purge_time >= 0) + purge_logs_before_date(purge_time); + } +#endif + } + if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED)) + pthread_mutex_unlock(&LOCK_log); +} + +uint MYSQL_BIN_LOG::next_file_id() +{ + uint res; + pthread_mutex_lock(&LOCK_log); + res = file_id++; + pthread_mutex_unlock(&LOCK_log); + return res; +} + + +/* + Write the contents of a cache to the binary log. + + SYNOPSIS + write_cache() + cache Cache to write to the binary log + lock_log True if the LOCK_log mutex should be aquired, false otherwise + sync_log True if the log should be flushed and sync:ed + + DESCRIPTION + Write the contents of the cache to the binary log. The cache will + be reset as a READ_CACHE to be able to read the contents from it. + */ + +int MYSQL_BIN_LOG::write_cache(IO_CACHE *cache, bool lock_log, bool sync_log) +{ + Mutex_sentry sentry(lock_log ? &LOCK_log : NULL); + + if (reinit_io_cache(cache, READ_CACHE, 0, 0, 0)) + return ER_ERROR_ON_WRITE; + uint length= my_b_bytes_in_cache(cache), group, carry, hdr_offs; + long val; + uchar header[LOG_EVENT_HEADER_LEN]; + + /* + The events in the buffer have incorrect end_log_pos data + (relative to beginning of group rather than absolute), + so we'll recalculate them in situ so the binlog is always + correct, even in the middle of a group. This is possible + because we now know the start position of the group (the + offset of this cache in the log, if you will); all we need + to do is to find all event-headers, and add the position of + the group to the end_log_pos of each event. This is pretty + straight forward, except that we read the cache in segments, + so an event-header might end up on the cache-border and get + split. + */ + + group= (uint)my_b_tell(&log_file); + hdr_offs= carry= 0; + + do + { + + /* + if we only got a partial header in the last iteration, + get the other half now and process a full header. + */ + if (unlikely(carry > 0)) + { + DBUG_ASSERT(carry < LOG_EVENT_HEADER_LEN); + + /* assemble both halves */ + memcpy(&header[carry], (char *)cache->read_pos, LOG_EVENT_HEADER_LEN - carry); + + /* fix end_log_pos */ + val= uint4korr(&header[LOG_POS_OFFSET]) + group; + int4store(&header[LOG_POS_OFFSET], val); + + /* write the first half of the split header */ + if (my_b_write(&log_file, header, carry)) + return ER_ERROR_ON_WRITE; + + /* + copy fixed second half of header to cache so the correct + version will be written later. + */ + memcpy((char *)cache->read_pos, &header[carry], LOG_EVENT_HEADER_LEN - carry); + + /* next event header at ... */ + hdr_offs = uint4korr(&header[EVENT_LEN_OFFSET]) - carry; + + carry= 0; + } + + /* if there is anything to write, process it. */ + + if (likely(length > 0)) + { + /* + process all event-headers in this (partial) cache. + if next header is beyond current read-buffer, + we'll get it later (though not necessarily in the + very next iteration, just "eventually"). + */ + + while (hdr_offs < length) + { + /* + partial header only? save what we can get, process once + we get the rest. + */ + + if (hdr_offs + LOG_EVENT_HEADER_LEN > length) + { + carry= length - hdr_offs; + memcpy(header, (char *)cache->read_pos + hdr_offs, carry); + length= hdr_offs; + } + else + { + /* we've got a full event-header, and it came in one piece */ + + uchar *log_pos= (uchar *)cache->read_pos + hdr_offs + LOG_POS_OFFSET; + + /* fix end_log_pos */ + val= uint4korr(log_pos) + group; + int4store(log_pos, val); + + /* next event header at ... */ + log_pos= (uchar *)cache->read_pos + hdr_offs + EVENT_LEN_OFFSET; + hdr_offs += uint4korr(log_pos); + + } + } + + /* + Adjust hdr_offs. Note that it may still point beyond the segment + read in the next iteration; if the current event is very long, + it may take a couple of read-iterations (and subsequent adjustments + of hdr_offs) for it to point into the then-current segment. + If we have a split header (!carry), hdr_offs will be set at the + beginning of the next iteration, overwriting the value we set here: + */ + hdr_offs -= length; + } + + /* Write data to the binary log file */ + if (my_b_write(&log_file, cache->read_pos, length)) + return ER_ERROR_ON_WRITE; + cache->read_pos=cache->read_end; // Mark buffer used up + } while ((length= my_b_fill(cache))); + + DBUG_ASSERT(carry == 0); + + if (sync_log) + flush_and_sync(); + + return 0; // All OK +} + +/* + Helper function to get the error code of the query to be binlogged. + */ +int query_error_code(THD *thd, bool not_killed) +{ + int error; + + if (not_killed) + { + error= thd->is_error() ? thd->main_da.sql_errno() : 0; + + /* thd->main_da.sql_errno() might be ER_SERVER_SHUTDOWN or + ER_QUERY_INTERRUPTED, So here we need to make sure that error + is not set to these errors when specified not_killed by the + caller. + */ + if (error == ER_SERVER_SHUTDOWN || error == ER_QUERY_INTERRUPTED) + error= 0; + } + else + { + /* killed status for DELAYED INSERT thread should never be used */ + DBUG_ASSERT(!(thd->system_thread & SYSTEM_THREAD_DELAYED_INSERT)); + error= thd->killed_errno(); + } + + return error; +} + +bool MYSQL_BIN_LOG::write_incident(THD *thd, bool lock) +{ + uint error= 0; + DBUG_ENTER("MYSQL_BIN_LOG::write_incident"); + LEX_STRING const write_error_msg= + { C_STRING_WITH_LEN("error writing to the binary log") }; + Incident incident= INCIDENT_LOST_EVENTS; + Incident_log_event ev(thd, incident, write_error_msg); + if (lock) + pthread_mutex_lock(&LOCK_log); + ev.write(&log_file); + if (lock) + { + if (!error && !(error= flush_and_sync())) + { + signal_update(); + rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED); + } + pthread_mutex_unlock(&LOCK_log); + } + DBUG_RETURN(error); +} + +/** + Write a cached log entry to the binary log. + - To support transaction over replication, we wrap the transaction + with BEGIN/COMMIT or BEGIN/ROLLBACK in the binary log. + We want to write a BEGIN/ROLLBACK block when a non-transactional table + was updated in a transaction which was rolled back. This is to ensure + that the same updates are run on the slave. + + @param thd + @param cache The cache to copy to the binlog + @param commit_event The commit event to print after writing the + contents of the cache. + @param incident Defines if an incident event should be created to + notify that some non-transactional changes did + not get into the binlog. + + @note + We only come here if there is something in the cache. + @note + The thing in the cache is always a complete transaction. + @note + 'cache' needs to be reinitialized after this functions returns. +*/ + +bool MYSQL_BIN_LOG::write(THD *thd, IO_CACHE *cache, Log_event *commit_event, + bool incident) +{ + DBUG_ENTER("MYSQL_BIN_LOG::write(THD *, IO_CACHE *, Log_event *)"); + VOID(pthread_mutex_lock(&LOCK_log)); + + /* NULL would represent nothing to replicate after ROLLBACK */ + DBUG_ASSERT(commit_event != NULL); + + DBUG_ASSERT(is_open()); + if (likely(is_open())) // Should always be true + { + /* + We only bother to write to the binary log if there is anything + to write. + */ + if (my_b_tell(cache) > 0) + { + /* + Log "BEGIN" at the beginning of every transaction. Here, a + transaction is either a BEGIN..COMMIT block or a single + statement in autocommit mode. + */ + Query_log_event qinfo(thd, STRING_WITH_LEN("BEGIN"), TRUE, TRUE, 0); + + /* + Now this Query_log_event has artificial log_pos 0. It must be + adjusted to reflect the real position in the log. Not doing it + would confuse the slave: it would prevent this one from + knowing where he is in the master's binlog, which would result + in wrong positions being shown to the user, MASTER_POS_WAIT + undue waiting etc. + */ + if (qinfo.write(&log_file)) + goto err; + + DBUG_EXECUTE_IF("crash_before_writing_xid", + { + if ((write_error= write_cache(cache, false, true))) + DBUG_PRINT("info", ("error writing binlog cache: %d", + write_error)); + DBUG_PRINT("info", ("crashing before writing xid")); + abort(); + }); + + if ((write_error= write_cache(cache, false, false))) + goto err; + + if (commit_event && commit_event->write(&log_file)) + goto err; + + if (incident && write_incident(thd, FALSE)) + goto err; + + if (flush_and_sync()) + goto err; + DBUG_EXECUTE_IF("half_binlogged_transaction", abort();); + if (cache->error) // Error on read + { + sql_print_error(ER(ER_ERROR_ON_READ), cache->file_name, errno); + write_error=1; // Don't give more errors + goto err; + } + signal_update(); + } + + /* + if commit_event is Xid_log_event, increase the number of + prepared_xids (it's decreasd in ::unlog()). Binlog cannot be rotated + if there're prepared xids in it - see the comment in new_file() for + an explanation. + If the commit_event is not Xid_log_event (then it's a Query_log_event) + rotate binlog, if necessary. + */ + if (commit_event && commit_event->get_type_code() == XID_EVENT) + { + pthread_mutex_lock(&LOCK_prep_xids); + prepared_xids++; + pthread_mutex_unlock(&LOCK_prep_xids); + } + else + rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED); + } + VOID(pthread_mutex_unlock(&LOCK_log)); + + DBUG_RETURN(0); + +err: + if (!write_error) + { + write_error= 1; + sql_print_error(ER(ER_ERROR_ON_WRITE), name, errno); + } + VOID(pthread_mutex_unlock(&LOCK_log)); + DBUG_RETURN(1); +} + + +/** + Wait until we get a signal that the binary log has been updated. + + @param thd Thread variable + @param is_slave If 0, the caller is the Binlog_dump thread from master; + if 1, the caller is the SQL thread from the slave. This + influences only thd->proc_info. + + @note + One must have a lock on LOCK_log before calling this function. + This lock will be released before return! That's required by + THD::enter_cond() (see NOTES in sql_class.h). +*/ + +void MYSQL_BIN_LOG::wait_for_update(THD* thd, bool is_slave) +{ + const char *old_msg; + DBUG_ENTER("wait_for_update"); + + old_msg= thd->enter_cond(&update_cond, &LOCK_log, + is_slave ? + "Has read all relay log; waiting for the slave I/O " + "thread to update it" : + "Has sent all binlog to slave; waiting for binlog " + "to be updated"); + pthread_cond_wait(&update_cond, &LOCK_log); + thd->exit_cond(old_msg); + DBUG_VOID_RETURN; +} + + +/** + Close the log file. + + @param exiting Bitmask for one or more of the following bits: + - LOG_CLOSE_INDEX : if we should close the index file + - LOG_CLOSE_TO_BE_OPENED : if we intend to call open + at once after close. + - LOG_CLOSE_STOP_EVENT : write a 'stop' event to the log + + @note + One can do an open on the object at once after doing a close. + The internal structures are not freed until cleanup() is called +*/ + +void MYSQL_BIN_LOG::close(uint exiting) +{ // One can't set log_type here! + DBUG_ENTER("MYSQL_BIN_LOG::close"); + DBUG_PRINT("enter",("exiting: %d", (int) exiting)); + if (log_state == LOG_OPENED) + { +#ifdef HAVE_REPLICATION + if (log_type == LOG_BIN && !no_auto_events && + (exiting & LOG_CLOSE_STOP_EVENT)) + { + Stop_log_event s; + s.write(&log_file); + bytes_written+= s.data_written; + signal_update(); + } +#endif /* HAVE_REPLICATION */ + + /* don't pwrite in a file opened with O_APPEND - it doesn't work */ + if (log_file.type == WRITE_CACHE && log_type == LOG_BIN) + { + my_off_t offset= BIN_LOG_HEADER_SIZE + FLAGS_OFFSET; + my_off_t org_position= my_tell(log_file.file, MYF(0)); + uchar flags= 0; // clearing LOG_EVENT_BINLOG_IN_USE_F + my_pwrite(log_file.file, &flags, 1, offset, MYF(0)); + /* + Restore position so that anything we have in the IO_cache is written + to the correct position. + We need the seek here, as my_pwrite() is not guaranteed to keep the + original position on system that doesn't support pwrite(). + */ + my_seek(log_file.file, org_position, MY_SEEK_SET, MYF(0)); + } + + /* this will cleanup IO_CACHE, sync and close the file */ + MYSQL_LOG::close(exiting); + } + + /* + The following test is needed even if is_open() is not set, as we may have + called a not complete close earlier and the index file is still open. + */ + + if ((exiting & LOG_CLOSE_INDEX) && my_b_inited(&index_file)) + { + end_io_cache(&index_file); + if (my_close(index_file.file, MYF(0)) < 0 && ! write_error) + { + write_error= 1; + sql_print_error(ER(ER_ERROR_ON_WRITE), index_file_name, errno); + } + } + log_state= (exiting & LOG_CLOSE_TO_BE_OPENED) ? LOG_TO_BE_OPENED : LOG_CLOSED; + safeFree(name); + DBUG_VOID_RETURN; +} + + +void MYSQL_BIN_LOG::set_max_size(ulong max_size_arg) +{ + /* + We need to take locks, otherwise this may happen: + new_file() is called, calls open(old_max_size), then before open() starts, + set_max_size() sets max_size to max_size_arg, then open() starts and + uses the old_max_size argument, so max_size_arg has been overwritten and + it's like if the SET command was never run. + */ + DBUG_ENTER("MYSQL_BIN_LOG::set_max_size"); + pthread_mutex_lock(&LOCK_log); + if (is_open()) + max_size= max_size_arg; + pthread_mutex_unlock(&LOCK_log); + DBUG_VOID_RETURN; +} + + +/** + Check if a string is a valid number. + + @param str String to test + @param res Store value here + @param allow_wildcards Set to 1 if we should ignore '%' and '_' + + @note + For the moment the allow_wildcards argument is not used + Should be move to some other file. + + @retval + 1 String is a number + @retval + 0 Error +*/ + +static bool test_if_number(register const char *str, + long *res, bool allow_wildcards) +{ + reg2 int flag; + const char *start; + DBUG_ENTER("test_if_number"); + + flag=0; start=str; + while (*str++ == ' ') ; + if (*--str == '-' || *str == '+') + str++; + while (my_isdigit(files_charset_info,*str) || + (allow_wildcards && (*str == wild_many || *str == wild_one))) + { + flag=1; + str++; + } + if (*str == '.') + { + for (str++ ; + my_isdigit(files_charset_info,*str) || + (allow_wildcards && (*str == wild_many || *str == wild_one)) ; + str++, flag=1) ; + } + if (*str != 0 || flag == 0) + DBUG_RETURN(0); + if (res) + *res=atol(start); + DBUG_RETURN(1); /* Number ok */ +} /* test_if_number */ + + +void sql_perror(const char *message) +{ +#ifdef HAVE_STRERROR + sql_print_error("%s: %s",message, strerror(errno)); +#else + perror(message); +#endif +} + + +bool flush_error_log() +{ + bool result=0; + if (opt_error_log) + { + char err_renamed[FN_REFLEN], *end; + end= strmake(err_renamed,log_error_file,FN_REFLEN-4); + strmov(end, "-old"); + VOID(pthread_mutex_lock(&LOCK_error_log)); +#ifdef __WIN__ + char err_temp[FN_REFLEN+4]; + /* + On Windows is necessary a temporary file for to rename + the current error file. + */ + strxmov(err_temp, err_renamed,"-tmp",NullS); + (void) my_delete(err_temp, MYF(0)); + if (freopen(err_temp,"a+",stdout)) + { + int fd; + size_t bytes; + uchar buf[IO_SIZE]; + + freopen(err_temp,"a+",stderr); + setbuf(stderr, NULL); + (void) my_delete(err_renamed, MYF(0)); + my_rename(log_error_file,err_renamed,MYF(0)); + if (freopen(log_error_file,"a+",stdout)) + { + freopen(log_error_file,"a+",stderr); + setbuf(stderr, NULL); + } + + if ((fd = my_open(err_temp, O_RDONLY, MYF(0))) >= 0) + { + while ((bytes= my_read(fd, buf, IO_SIZE, MYF(0))) && + bytes != MY_FILE_ERROR) + my_fwrite(stderr, buf, bytes, MYF(0)); + my_close(fd, MYF(0)); + } + (void) my_delete(err_temp, MYF(0)); + } + else + result= 1; +#else + my_rename(log_error_file,err_renamed,MYF(0)); + if (freopen(log_error_file,"a+",stdout)) + { + FILE *reopen; + reopen= freopen(log_error_file,"a+",stderr); + setbuf(stderr, NULL); + } + else + result= 1; +#endif + VOID(pthread_mutex_unlock(&LOCK_error_log)); + } + return result; +} + +void MYSQL_BIN_LOG::signal_update() +{ + DBUG_ENTER("MYSQL_BIN_LOG::signal_update"); + pthread_cond_broadcast(&update_cond); + DBUG_VOID_RETURN; +} + +#ifdef __NT__ +static void print_buffer_to_nt_eventlog(enum loglevel level, char *buff, + size_t length, size_t buffLen) +{ + HANDLE event; + char *buffptr= buff; + DBUG_ENTER("print_buffer_to_nt_eventlog"); + + /* Add ending CR/LF's to string, overwrite last chars if necessary */ + strmov(buffptr+min(length, buffLen-5), "\r\n\r\n"); + + setup_windows_event_source(); + if ((event= RegisterEventSource(NULL,"MySQL"))) + { + switch (level) { + case ERROR_LEVEL: + ReportEvent(event, EVENTLOG_ERROR_TYPE, 0, MSG_DEFAULT, NULL, 1, 0, + (LPCSTR*)&buffptr, NULL); + break; + case WARNING_LEVEL: + ReportEvent(event, EVENTLOG_WARNING_TYPE, 0, MSG_DEFAULT, NULL, 1, 0, + (LPCSTR*) &buffptr, NULL); + break; + case INFORMATION_LEVEL: + ReportEvent(event, EVENTLOG_INFORMATION_TYPE, 0, MSG_DEFAULT, NULL, 1, + 0, (LPCSTR*) &buffptr, NULL); + break; + } + DeregisterEventSource(event); + } + + DBUG_VOID_RETURN; +} +#endif /* __NT__ */ + + +/** + Prints a printf style message to the error log and, under NT, to the + Windows event log. + + This function prints the message into a buffer and then sends that buffer + to other functions to write that message to other logging sources. + + @param event_type Type of event to write (Error, Warning, or Info) + @param format Printf style format of message + @param args va_list list of arguments for the message + + @returns + The function always returns 0. The return value is present in the + signature to be compatible with other logging routines, which could + return an error (e.g. logging to the log tables) +*/ + +#ifndef EMBEDDED_LIBRARY +static void print_buffer_to_file(enum loglevel level, const char *buffer) +{ + time_t skr; + struct tm tm_tmp; + struct tm *start; + DBUG_ENTER("print_buffer_to_file"); + DBUG_PRINT("enter",("buffer: %s", buffer)); + + VOID(pthread_mutex_lock(&LOCK_error_log)); + + skr= my_time(0); + localtime_r(&skr, &tm_tmp); + start=&tm_tmp; + + fprintf(stderr, "%02d%02d%02d %2d:%02d:%02d [%s] %s\n", + start->tm_year % 100, + start->tm_mon+1, + start->tm_mday, + start->tm_hour, + start->tm_min, + start->tm_sec, + (level == ERROR_LEVEL ? "ERROR" : level == WARNING_LEVEL ? + "Warning" : "Note"), + buffer); + + fflush(stderr); + + VOID(pthread_mutex_unlock(&LOCK_error_log)); + DBUG_VOID_RETURN; +} + + +int vprint_msg_to_log(enum loglevel level, const char *format, va_list args) +{ + char buff[1024]; + size_t length; + DBUG_ENTER("vprint_msg_to_log"); + + length= my_vsnprintf(buff, sizeof(buff), format, args); + print_buffer_to_file(level, buff); + +#ifdef __NT__ + print_buffer_to_nt_eventlog(level, buff, length, sizeof(buff)); +#endif + + DBUG_RETURN(0); +} +#endif /*EMBEDDED_LIBRARY*/ + + +void sql_print_error(const char *format, ...) +{ + va_list args; + DBUG_ENTER("sql_print_error"); + + va_start(args, format); + error_log_print(ERROR_LEVEL, format, args); + va_end(args); + + DBUG_VOID_RETURN; +} + + +void sql_print_warning(const char *format, ...) +{ + va_list args; + DBUG_ENTER("sql_print_warning"); + + va_start(args, format); + error_log_print(WARNING_LEVEL, format, args); + va_end(args); + + DBUG_VOID_RETURN; +} + + +void sql_print_information(const char *format, ...) +{ + va_list args; + DBUG_ENTER("sql_print_information"); + + va_start(args, format); + error_log_print(INFORMATION_LEVEL, format, args); + va_end(args); + + DBUG_VOID_RETURN; +} + + +/********* transaction coordinator log for 2pc - mmap() based solution *******/ + +/* + the log consists of a file, mmapped to a memory. + file is divided on pages of tc_log_page_size size. + (usable size of the first page is smaller because of log header) + there's PAGE control structure for each page + each page (or rather PAGE control structure) can be in one of three + states - active, syncing, pool. + there could be only one page in active or syncing states, + but many in pool - pool is fifo queue. + usual lifecycle of a page is pool->active->syncing->pool + "active" page - is a page where new xid's are logged. + the page stays active as long as syncing slot is taken. + "syncing" page is being synced to disk. no new xid can be added to it. + when the sync is done the page is moved to a pool and an active page + becomes "syncing". + + the result of such an architecture is a natural "commit grouping" - + If commits are coming faster than the system can sync, they do not + stall. Instead, all commit that came since the last sync are + logged to the same page, and they all are synced with the next - + one - sync. Thus, thought individual commits are delayed, throughput + is not decreasing. + + when a xid is added to an active page, the thread of this xid waits + for a page's condition until the page is synced. when syncing slot + becomes vacant one of these waiters is awaken to take care of syncing. + it syncs the page and signals all waiters that the page is synced. + PAGE::waiters is used to count these waiters, and a page may never + become active again until waiters==0 (that is all waiters from the + previous sync have noticed the sync was completed) + + note, that the page becomes "dirty" and has to be synced only when a + new xid is added into it. Removing a xid from a page does not make it + dirty - we don't sync removals to disk. +*/ + +ulong tc_log_page_waits= 0; + +#ifdef HAVE_MMAP + +#define TC_LOG_HEADER_SIZE (sizeof(tc_log_magic)+1) + +static const char tc_log_magic[]={(char) 254, 0x23, 0x05, 0x74}; + +ulong opt_tc_log_size= TC_LOG_MIN_SIZE; +ulong tc_log_max_pages_used=0, tc_log_page_size=0, tc_log_cur_pages_used=0; + +int TC_LOG_MMAP::open(const char *opt_name) +{ + uint i; + bool crashed=FALSE; + PAGE *pg; + + DBUG_ASSERT(total_ha_2pc > 1); + DBUG_ASSERT(opt_name && opt_name[0]); + + tc_log_page_size= my_getpagesize(); + DBUG_ASSERT(TC_LOG_PAGE_SIZE % tc_log_page_size == 0); + + fn_format(logname,opt_name,mysql_data_home,"",MY_UNPACK_FILENAME); + if ((fd= my_open(logname, O_RDWR, MYF(0))) < 0) + { + if (my_errno != ENOENT) + goto err; + if (using_heuristic_recover()) + return 1; + if ((fd= my_create(logname, CREATE_MODE, O_RDWR, MYF(MY_WME))) < 0) + goto err; + inited=1; + file_length= opt_tc_log_size; + if (my_chsize(fd, file_length, 0, MYF(MY_WME))) + goto err; + } + else + { + inited= 1; + crashed= TRUE; + sql_print_information("Recovering after a crash using %s", opt_name); + if (tc_heuristic_recover) + { + sql_print_error("Cannot perform automatic crash recovery when " + "--tc-heuristic-recover is used"); + goto err; + } + file_length= my_seek(fd, 0L, MY_SEEK_END, MYF(MY_WME+MY_FAE)); + if (file_length == MY_FILEPOS_ERROR || file_length % tc_log_page_size) + goto err; + } + + data= (uchar *)my_mmap(0, (size_t)file_length, PROT_READ|PROT_WRITE, + MAP_NOSYNC|MAP_SHARED, fd, 0); + if (data == MAP_FAILED) + { + my_errno=errno; + goto err; + } + inited=2; + + npages=(uint)file_length/tc_log_page_size; + DBUG_ASSERT(npages >= 3); // to guarantee non-empty pool + if (!(pages=(PAGE *)my_malloc(npages*sizeof(PAGE), MYF(MY_WME|MY_ZEROFILL)))) + goto err; + inited=3; + for (pg=pages, i=0; i < npages; i++, pg++) + { + pg->next=pg+1; + pg->waiters=0; + pg->state=POOL; + pthread_mutex_init(&pg->lock, MY_MUTEX_INIT_FAST); + pthread_cond_init (&pg->cond, 0); + pg->start=(my_xid *)(data + i*tc_log_page_size); + pg->end=(my_xid *)(pg->start + tc_log_page_size); + pg->size=pg->free=tc_log_page_size/sizeof(my_xid); + } + pages[0].size=pages[0].free= + (tc_log_page_size-TC_LOG_HEADER_SIZE)/sizeof(my_xid); + pages[0].start=pages[0].end-pages[0].size; + pages[npages-1].next=0; + inited=4; + + if (crashed && recover()) + goto err; + + memcpy(data, tc_log_magic, sizeof(tc_log_magic)); + data[sizeof(tc_log_magic)]= (uchar)total_ha_2pc; + my_msync(fd, data, tc_log_page_size, MS_SYNC); + inited=5; + + pthread_mutex_init(&LOCK_sync, MY_MUTEX_INIT_FAST); + pthread_mutex_init(&LOCK_active, MY_MUTEX_INIT_FAST); + pthread_mutex_init(&LOCK_pool, MY_MUTEX_INIT_FAST); + pthread_cond_init(&COND_active, 0); + pthread_cond_init(&COND_pool, 0); + + inited=6; + + syncing= 0; + active=pages; + pool=pages+1; + pool_last=pages+npages-1; + + return 0; + +err: + close(); + return 1; +} + +/** + there is no active page, let's got one from the pool. + + Two strategies here: + -# take the first from the pool + -# if there're waiters - take the one with the most free space. + + @todo + TODO page merging. try to allocate adjacent page first, + so that they can be flushed both in one sync +*/ + +void TC_LOG_MMAP::get_active_from_pool() +{ + PAGE **p, **best_p=0; + int best_free; + + if (syncing) + pthread_mutex_lock(&LOCK_pool); + + do + { + best_p= p= &pool; + if ((*p)->waiters == 0) // can the first page be used ? + break; // yes - take it. + + best_free=0; // no - trying second strategy + for (p=&(*p)->next; *p; p=&(*p)->next) + { + if ((*p)->waiters == 0 && (*p)->free > best_free) + { + best_free=(*p)->free; + best_p=p; + } + } + } + while ((*best_p == 0 || best_free == 0) && overflow()); + + active=*best_p; + if (active->free == active->size) // we've chosen an empty page + { + tc_log_cur_pages_used++; + set_if_bigger(tc_log_max_pages_used, tc_log_cur_pages_used); + } + + if ((*best_p)->next) // unlink the page from the pool + *best_p=(*best_p)->next; + else + pool_last=*best_p; + + if (syncing) + pthread_mutex_unlock(&LOCK_pool); +} + +/** + @todo + perhaps, increase log size ? +*/ +int TC_LOG_MMAP::overflow() +{ + /* + simple overflow handling - just wait + TODO perhaps, increase log size ? + let's check the behaviour of tc_log_page_waits first + */ + tc_log_page_waits++; + pthread_cond_wait(&COND_pool, &LOCK_pool); + return 1; // always return 1 +} + +/** + Record that transaction XID is committed on the persistent storage. + + This function is called in the middle of two-phase commit: + First all resources prepare the transaction, then tc_log->log() is called, + then all resources commit the transaction, then tc_log->unlog() is called. + + All access to active page is serialized but it's not a problem, as + we're assuming that fsync() will be a main bottleneck. + That is, parallelizing writes to log pages we'll decrease number of + threads waiting for a page, but then all these threads will be waiting + for a fsync() anyway + + If tc_log == MYSQL_LOG then tc_log writes transaction to binlog and + records XID in a special Xid_log_event. + If tc_log = TC_LOG_MMAP then xid is written in a special memory-mapped + log. + + @retval + 0 - error + @retval + \# - otherwise, "cookie", a number that will be passed as an argument + to unlog() call. tc_log can define it any way it wants, + and use for whatever purposes. TC_LOG_MMAP sets it + to the position in memory where xid was logged to. +*/ + +int TC_LOG_MMAP::log_xid(THD *thd, my_xid xid) +{ + int err; + PAGE *p; + ulong cookie; + + pthread_mutex_lock(&LOCK_active); + + /* + if active page is full - just wait... + frankly speaking, active->free here accessed outside of mutex + protection, but it's safe, because it only means we may miss an + unlog() for the active page, and we're not waiting for it here - + unlog() does not signal COND_active. + */ + while (unlikely(active && active->free == 0)) + pthread_cond_wait(&COND_active, &LOCK_active); + + /* no active page ? take one from the pool */ + if (active == 0) + get_active_from_pool(); + + p=active; + pthread_mutex_lock(&p->lock); + + /* searching for an empty slot */ + while (*p->ptr) + { + p->ptr++; + DBUG_ASSERT(p->ptr < p->end); // because p->free > 0 + } + + /* found! store xid there and mark the page dirty */ + cookie= (ulong)((uchar *)p->ptr - data); // can never be zero + *p->ptr++= xid; + p->free--; + p->state= DIRTY; + + /* to sync or not to sync - this is the question */ + pthread_mutex_unlock(&LOCK_active); + pthread_mutex_lock(&LOCK_sync); + pthread_mutex_unlock(&p->lock); + + if (syncing) + { // somebody's syncing. let's wait + p->waiters++; + /* + note - it must be while (), not do ... while () here + as p->state may be not DIRTY when we come here + */ + while (p->state == DIRTY && syncing) + pthread_cond_wait(&p->cond, &LOCK_sync); + p->waiters--; + err= p->state == ERROR; + if (p->state != DIRTY) // page was synced + { + if (p->waiters == 0) + pthread_cond_signal(&COND_pool); // in case somebody's waiting + pthread_mutex_unlock(&LOCK_sync); + goto done; // we're done + } + } // page was not synced! do it now + DBUG_ASSERT(active == p && syncing == 0); + pthread_mutex_lock(&LOCK_active); + syncing=p; // place is vacant - take it + active=0; // page is not active anymore + pthread_cond_broadcast(&COND_active); // in case somebody's waiting + pthread_mutex_unlock(&LOCK_active); + pthread_mutex_unlock(&LOCK_sync); + err= sync(); + +done: + return err ? 0 : cookie; +} + +int TC_LOG_MMAP::sync() +{ + int err; + + DBUG_ASSERT(syncing != active); + + /* + sit down and relax - this can take a while... + note - no locks are held at this point + */ + err= my_msync(fd, syncing->start, 1, MS_SYNC); + + /* page is synced. let's move it to the pool */ + pthread_mutex_lock(&LOCK_pool); + pool_last->next=syncing; + pool_last=syncing; + syncing->next=0; + syncing->state= err ? ERROR : POOL; + pthread_cond_broadcast(&syncing->cond); // signal "sync done" + pthread_cond_signal(&COND_pool); // in case somebody's waiting + pthread_mutex_unlock(&LOCK_pool); + + /* marking 'syncing' slot free */ + pthread_mutex_lock(&LOCK_sync); + syncing=0; + pthread_cond_signal(&active->cond); // wake up a new syncer + pthread_mutex_unlock(&LOCK_sync); + return err; +} + +/** + erase xid from the page, update page free space counters/pointers. + cookie points directly to the memory where xid was logged. +*/ + +void TC_LOG_MMAP::unlog(ulong cookie, my_xid xid) +{ + PAGE *p=pages+(cookie/tc_log_page_size); + my_xid *x=(my_xid *)(data+cookie); + + DBUG_ASSERT(*x == xid); + DBUG_ASSERT(x >= p->start && x < p->end); + *x=0; + + pthread_mutex_lock(&p->lock); + p->free++; + DBUG_ASSERT(p->free <= p->size); + set_if_smaller(p->ptr, x); + if (p->free == p->size) // the page is completely empty + statistic_decrement(tc_log_cur_pages_used, &LOCK_status); + if (p->waiters == 0) // the page is in pool and ready to rock + pthread_cond_signal(&COND_pool); // ping ... for overflow() + pthread_mutex_unlock(&p->lock); +} + +void TC_LOG_MMAP::close() +{ + uint i; + switch (inited) { + case 6: + pthread_mutex_destroy(&LOCK_sync); + pthread_mutex_destroy(&LOCK_active); + pthread_mutex_destroy(&LOCK_pool); + pthread_cond_destroy(&COND_pool); + case 5: + data[0]='A'; // garble the first (signature) byte, in case my_delete fails + case 4: + for (i=0; i < npages; i++) + { + if (pages[i].ptr == 0) + break; + pthread_mutex_destroy(&pages[i].lock); + pthread_cond_destroy(&pages[i].cond); + } + case 3: + my_free((uchar*)pages, MYF(0)); + case 2: + my_munmap((char*)data, (size_t)file_length); + case 1: + my_close(fd, MYF(0)); + } + if (inited>=5) // cannot do in the switch because of Windows + my_delete(logname, MYF(MY_WME)); + inited=0; +} + +int TC_LOG_MMAP::recover() +{ + HASH xids; + PAGE *p=pages, *end_p=pages+npages; + + if (memcmp(data, tc_log_magic, sizeof(tc_log_magic))) + { + sql_print_error("Bad magic header in tc log"); + goto err1; + } + + /* + the first byte after magic signature is set to current + number of storage engines on startup + */ + if (data[sizeof(tc_log_magic)] != total_ha_2pc) + { + sql_print_error("Recovery failed! You must enable " + "exactly %d storage engines that support " + "two-phase commit protocol", + data[sizeof(tc_log_magic)]); + goto err1; + } + + if (hash_init(&xids, &my_charset_bin, tc_log_page_size/3, 0, + sizeof(my_xid), 0, 0, MYF(0))) + goto err1; + + for ( ; p < end_p ; p++) + { + for (my_xid *x=p->start; x < p->end; x++) + if (*x && my_hash_insert(&xids, (uchar *)x)) + goto err2; // OOM + } + + if (ha_recover(&xids)) + goto err2; + + hash_free(&xids); + bzero(data, (size_t)file_length); + return 0; + +err2: + hash_free(&xids); +err1: + sql_print_error("Crash recovery failed. Either correct the problem " + "(if it's, for example, out of memory error) and restart, " + "or delete tc log and start mysqld with " + "--tc-heuristic-recover={commit|rollback}"); + return 1; +} +#endif + +TC_LOG *tc_log; +TC_LOG_DUMMY tc_log_dummy; +TC_LOG_MMAP tc_log_mmap; + +/** + Perform heuristic recovery, if --tc-heuristic-recover was used. + + @note + no matter whether heuristic recovery was successful or not + mysqld must exit. So, return value is the same in both cases. + + @retval + 0 no heuristic recovery was requested + @retval + 1 heuristic recovery was performed +*/ + +int TC_LOG::using_heuristic_recover() +{ + if (!tc_heuristic_recover) + return 0; + + sql_print_information("Heuristic crash recovery mode"); + if (ha_recover(0)) + sql_print_error("Heuristic crash recovery failed"); + sql_print_information("Please restart mysqld without --tc-heuristic-recover"); + return 1; +} + +/****** transaction coordinator log for 2pc - binlog() based solution ******/ +#define TC_LOG_BINLOG MYSQL_BIN_LOG + +/** + @todo + keep in-memory list of prepared transactions + (add to list in log(), remove on unlog()) + and copy it to the new binlog if rotated + but let's check the behaviour of tc_log_page_waits first! +*/ + +int TC_LOG_BINLOG::open(const char *opt_name) +{ + LOG_INFO log_info; + int error= 1; + + DBUG_ASSERT(total_ha_2pc > 1); + DBUG_ASSERT(opt_name && opt_name[0]); + + pthread_mutex_init(&LOCK_prep_xids, MY_MUTEX_INIT_FAST); + pthread_cond_init (&COND_prep_xids, 0); + + if (!my_b_inited(&index_file)) + { + /* There was a failure to open the index file, can't open the binlog */ + cleanup(); + return 1; + } + + if (using_heuristic_recover()) + { + /* generate a new binlog to mask a corrupted one */ + open(opt_name, LOG_BIN, 0, WRITE_CACHE, 0, max_binlog_size, 0); + cleanup(); + return 1; + } + + if ((error= find_log_pos(&log_info, NullS, 1))) + { + if (error != LOG_INFO_EOF) + sql_print_error("find_log_pos() failed (error: %d)", error); + else + error= 0; + goto err; + } + + { + const char *errmsg; + IO_CACHE log; + File file; + Log_event *ev=0; + Format_description_log_event fdle(BINLOG_VERSION); + char log_name[FN_REFLEN]; + + if (! fdle.is_valid()) + goto err; + + do + { + strmake(log_name, log_info.log_file_name, sizeof(log_name)-1); + } while (!(error= find_next_log(&log_info, 1))); + + if (error != LOG_INFO_EOF) + { + sql_print_error("find_log_pos() failed (error: %d)", error); + goto err; + } + + if ((file= open_binlog(&log, log_name, &errmsg)) < 0) + { + sql_print_error("%s", errmsg); + goto err; + } + + if ((ev= Log_event::read_log_event(&log, 0, &fdle)) && + ev->get_type_code() == FORMAT_DESCRIPTION_EVENT && + ev->flags & LOG_EVENT_BINLOG_IN_USE_F) + { + sql_print_information("Recovering after a crash using %s", opt_name); + error= recover(&log, (Format_description_log_event *)ev); + } + else + error=0; + + delete ev; + end_io_cache(&log); + my_close(file, MYF(MY_WME)); + + if (error) + goto err; + } + +err: + return error; +} + +/** This is called on shutdown, after ha_panic. */ +void TC_LOG_BINLOG::close() +{ + DBUG_ASSERT(prepared_xids==0); + pthread_mutex_destroy(&LOCK_prep_xids); + pthread_cond_destroy (&COND_prep_xids); +} + +/** + @todo + group commit + + @retval + 0 error + @retval + 1 success +*/ +int TC_LOG_BINLOG::log_xid(THD *thd, my_xid xid) +{ + DBUG_ENTER("TC_LOG_BINLOG::log"); + Xid_log_event xle(thd, xid); + binlog_trx_data *trx_data= + (binlog_trx_data*) thd_get_ha_data(thd, binlog_hton); + /* + We always commit the entire transaction when writing an XID. Also + note that the return value is inverted. + */ + DBUG_RETURN(!binlog_end_trans(thd, trx_data, &xle, TRUE)); +} + +void TC_LOG_BINLOG::unlog(ulong cookie, my_xid xid) +{ + pthread_mutex_lock(&LOCK_prep_xids); + DBUG_ASSERT(prepared_xids > 0); + if (--prepared_xids == 0) { + DBUG_PRINT("info", ("prepared_xids=%lu", prepared_xids)); + pthread_cond_signal(&COND_prep_xids); + } + pthread_mutex_unlock(&LOCK_prep_xids); + rotate_and_purge(0); // as ::write() did not rotate +} + +int TC_LOG_BINLOG::recover(IO_CACHE *log, Format_description_log_event *fdle) +{ + Log_event *ev; + HASH xids; + MEM_ROOT mem_root; + + if (! fdle->is_valid() || + hash_init(&xids, &my_charset_bin, TC_LOG_PAGE_SIZE/3, 0, + sizeof(my_xid), 0, 0, MYF(0))) + goto err1; + + init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE); + + fdle->flags&= ~LOG_EVENT_BINLOG_IN_USE_F; // abort on the first error + + while ((ev= Log_event::read_log_event(log,0,fdle)) && ev->is_valid()) + { + if (ev->get_type_code() == XID_EVENT) + { + Xid_log_event *xev=(Xid_log_event *)ev; + uchar *x= (uchar *) memdup_root(&mem_root, (uchar*) &xev->xid, + sizeof(xev->xid)); + if (! x) + goto err2; + my_hash_insert(&xids, x); + } + delete ev; + } + + if (ha_recover(&xids)) + goto err2; + + free_root(&mem_root, MYF(0)); + hash_free(&xids); + return 0; + +err2: + free_root(&mem_root, MYF(0)); + hash_free(&xids); +err1: + sql_print_error("Crash recovery failed. Either correct the problem " + "(if it's, for example, out of memory error) and restart, " + "or delete (or rename) binary log and start mysqld with " + "--tc-heuristic-recover={commit|rollback}"); + return 1; +} + + +#ifdef INNODB_COMPATIBILITY_HOOKS +/** + Get the file name of the MySQL binlog. + @return the name of the binlog file +*/ +extern "C" +const char* mysql_bin_log_file_name(void) +{ + return mysql_bin_log.get_log_fname(); +} +/** + Get the current position of the MySQL binlog. + @return byte offset from the beginning of the binlog +*/ +extern "C" +ulonglong mysql_bin_log_file_pos(void) +{ + return (ulonglong) mysql_bin_log.get_log_file()->pos_in_file; +} +#endif /* INNODB_COMPATIBILITY_HOOKS */ + + +struct st_mysql_storage_engine binlog_storage_engine= +{ MYSQL_HANDLERTON_INTERFACE_VERSION }; + +mysql_declare_plugin(binlog) +{ + MYSQL_STORAGE_ENGINE_PLUGIN, + &binlog_storage_engine, + "binlog", + "MySQL AB", + "This is a pseudo storage engine to represent the binlog in a transaction", + PLUGIN_LICENSE_GPL, + binlog_init, /* Plugin Init */ + NULL, /* Plugin Deinit */ + 0x0100 /* 1.0 */, + NULL, /* status variables */ + NULL, /* system variables */ + NULL /* config options */ +} +mysql_declare_plugin_end; diff --git a/dbcon/mysql/log.h b/dbcon/mysql/log.h new file mode 100644 index 00000000..d306d6f7 --- /dev/null +++ b/dbcon/mysql/log.h @@ -0,0 +1,589 @@ +/* Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef LOG_H +#define LOG_H + +class Relay_log_info; + +class Format_description_log_event; + +/* + Transaction Coordinator log - a base abstract class + for two different implementations +*/ +class TC_LOG +{ + public: + int using_heuristic_recover(); + TC_LOG() {} + virtual ~TC_LOG() {} + + virtual int open(const char *opt_name)=0; + virtual void close()=0; + virtual int log_xid(THD *thd, my_xid xid)=0; + virtual void unlog(ulong cookie, my_xid xid)=0; +}; + +class TC_LOG_DUMMY: public TC_LOG // use it to disable the logging +{ +public: + TC_LOG_DUMMY() {} + int open(const char *opt_name) { return 0; } + void close() { } + int log_xid(THD *thd, my_xid xid) { return 1; } + void unlog(ulong cookie, my_xid xid) { } +}; + +#ifdef HAVE_MMAP +class TC_LOG_MMAP: public TC_LOG +{ + public: // only to keep Sun Forte on sol9x86 happy + typedef enum { + POOL, // page is in pool + ERROR, // last sync failed + DIRTY // new xids added since last sync + } PAGE_STATE; + + private: + typedef struct st_page { + struct st_page *next; // page a linked in a fifo queue + my_xid *start, *end; // usable area of a page + my_xid *ptr; // next xid will be written here + int size, free; // max and current number of free xid slots on the page + int waiters; // number of waiters on condition + PAGE_STATE state; // see above + pthread_mutex_t lock; // to access page data or control structure + pthread_cond_t cond; // to wait for a sync + } PAGE; + + char logname[FN_REFLEN]; + File fd; + my_off_t file_length; + uint npages, inited; + uchar *data; + struct st_page *pages, *syncing, *active, *pool, *pool_last; + /* + note that, e.g. LOCK_active is only used to protect + 'active' pointer, to protect the content of the active page + one has to use active->lock. + Same for LOCK_pool and LOCK_sync + */ + pthread_mutex_t LOCK_active, LOCK_pool, LOCK_sync; + pthread_cond_t COND_pool, COND_active; + + public: + TC_LOG_MMAP(): inited(0) {} + int open(const char *opt_name); + void close(); + int log_xid(THD *thd, my_xid xid); + void unlog(ulong cookie, my_xid xid); + int recover(); + + private: + void get_active_from_pool(); + int sync(); + int overflow(); +}; +#else +#define TC_LOG_MMAP TC_LOG_DUMMY +#endif + +extern TC_LOG *tc_log; +extern TC_LOG_MMAP tc_log_mmap; +extern TC_LOG_DUMMY tc_log_dummy; + +/* log info errors */ +#define LOG_INFO_EOF -1 +#define LOG_INFO_IO -2 +#define LOG_INFO_INVALID -3 +#define LOG_INFO_SEEK -4 +#define LOG_INFO_MEM -6 +#define LOG_INFO_FATAL -7 +#define LOG_INFO_IN_USE -8 +#define LOG_INFO_EMFILE -9 + + +/* bitmap to SQL_LOG::close() */ +#define LOG_CLOSE_INDEX 1 +#define LOG_CLOSE_TO_BE_OPENED 2 +#define LOG_CLOSE_STOP_EVENT 4 + +class Relay_log_info; + +typedef struct st_log_info +{ + char log_file_name[FN_REFLEN]; + my_off_t index_file_offset, index_file_start_offset; + my_off_t pos; + bool fatal; // if the purge happens to give us a negative offset + pthread_mutex_t lock; + st_log_info() + : index_file_offset(0), index_file_start_offset(0), + pos(0), fatal(0) + { + log_file_name[0] = '\0'; + pthread_mutex_init(&lock, MY_MUTEX_INIT_FAST); + } + ~st_log_info() { pthread_mutex_destroy(&lock);} +} LOG_INFO; + +/* + Currently we have only 3 kinds of logging functions: old-fashioned + logs, stdout and csv logging routines. +*/ +#define MAX_LOG_HANDLERS_NUM 3 + +/* log event handler flags */ +#define LOG_NONE 1 +#define LOG_FILE 2 +#define LOG_TABLE 4 + +class Log_event; +class Rows_log_event; + +enum enum_log_type { LOG_UNKNOWN, LOG_NORMAL, LOG_BIN }; +enum enum_log_state { LOG_OPENED, LOG_CLOSED, LOG_TO_BE_OPENED }; + +/* + TODO use mmap instead of IO_CACHE for binlog + (mmap+fsync is two times faster than write+fsync) +*/ + +class MYSQL_LOG +{ +public: + MYSQL_LOG(); + void init_pthread_objects(); + void cleanup(); + bool open(const char *log_name, + enum_log_type log_type, + const char *new_name, + enum cache_type io_cache_type_arg); + void init(enum_log_type log_type_arg, + enum cache_type io_cache_type_arg); + void close(uint exiting); + inline bool is_open() { return log_state != LOG_CLOSED; } + const char *generate_name(const char *log_name, const char *suffix, + bool strip_ext, char *buff); + int generate_new_name(char *new_name, const char *log_name); + protected: + /* LOCK_log is inited by init_pthread_objects() */ + pthread_mutex_t LOCK_log; + char *name; + char log_file_name[FN_REFLEN]; + char time_buff[20], db[NAME_LEN + 1]; + bool write_error, inited; + IO_CACHE log_file; + enum_log_type log_type; + volatile enum_log_state log_state; + enum cache_type io_cache_type; + friend class Log_event; +}; + +class MYSQL_QUERY_LOG: public MYSQL_LOG +{ +public: + MYSQL_QUERY_LOG() : last_time(0) {} + void reopen_file(); + bool write(time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len); + bool write(THD *thd, time_t current_time, time_t query_start_arg, + const char *user_host, uint user_host_len, + ulonglong query_utime, ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len); + bool open_slow_log(const char *log_name) + { + char buf[FN_REFLEN]; + return open(generate_name(log_name, "-slow.log", 0, buf), LOG_NORMAL, 0, + WRITE_CACHE); + } + bool open_query_log(const char *log_name) + { + char buf[FN_REFLEN]; + return open(generate_name(log_name, ".log", 0, buf), LOG_NORMAL, 0, + WRITE_CACHE); + } + +private: + time_t last_time; +}; + +class MYSQL_BIN_LOG: public TC_LOG, private MYSQL_LOG +{ + private: + /* LOCK_log and LOCK_index are inited by init_pthread_objects() */ + pthread_mutex_t LOCK_index; + pthread_mutex_t LOCK_prep_xids; + pthread_cond_t COND_prep_xids; + pthread_cond_t update_cond; + ulonglong bytes_written; + IO_CACHE index_file; + /* + purge_temp is a temp file used in purge_logs so that the index file + can be updated before deleting files from disk, yielding better crash + recovery. It is created on demand the first time purge_logs is called + and then reused for subsequent calls. It is cleaned up in cleanup(). + */ + IO_CACHE purge_temp; + char index_file_name[FN_REFLEN]; + /* + The max size before rotation (usable only if log_type == LOG_BIN: binary + logs and relay logs). + For a binlog, max_size should be max_binlog_size. + For a relay log, it should be max_relay_log_size if this is non-zero, + max_binlog_size otherwise. + max_size is set in init(), and dynamically changed (when one does SET + GLOBAL MAX_BINLOG_SIZE|MAX_RELAY_LOG_SIZE) by fix_max_binlog_size and + fix_max_relay_log_size). + */ + ulong max_size; + long prepared_xids; /* for tc log - number of xids to remember */ + // current file sequence number for load data infile binary logging + uint file_id; + uint open_count; // For replication + int readers_count; + bool need_start_event; + /* + no_auto_events means we don't want any of these automatic events : + Start/Rotate/Stop. That is, in 4.x when we rotate a relay log, we don't + want a Rotate_log event to be written to the relay log. When we start a + relay log etc. So in 4.x this is 1 for relay logs, 0 for binlogs. + In 5.0 it's 0 for relay logs too! + */ + bool no_auto_events; + + ulonglong m_table_map_version; + + int write_to_file(IO_CACHE *cache); + /* + This is used to start writing to a new log file. The difference from + new_file() is locking. new_file_without_locking() does not acquire + LOCK_log. + */ + void new_file_without_locking(); + void new_file_impl(bool need_lock); + +public: + MYSQL_LOG::generate_name; + MYSQL_LOG::is_open; + + /* This is relay log */ + bool is_relay_log; + + /* + These describe the log's format. This is used only for relay logs. + _for_exec is used by the SQL thread, _for_queue by the I/O thread. It's + necessary to have 2 distinct objects, because the I/O thread may be reading + events in a different format from what the SQL thread is reading (consider + the case of a master which has been upgraded from 5.0 to 5.1 without doing + RESET MASTER, or from 4.x to 5.0). + */ + Format_description_log_event *description_event_for_exec, + *description_event_for_queue; + + MYSQL_BIN_LOG(); + /* + note that there's no destructor ~MYSQL_BIN_LOG() ! + The reason is that we don't want it to be automatically called + on exit() - but only during the correct shutdown process + */ + + int open(const char *opt_name); + void close(); + int log_xid(THD *thd, my_xid xid); + void unlog(ulong cookie, my_xid xid); + int recover(IO_CACHE *log, Format_description_log_event *fdle); +#if !defined(MYSQL_CLIENT) + bool is_table_mapped(TABLE *table) const + { + return table->s->table_map_version == table_map_version(); + } + + ulonglong table_map_version() const { return m_table_map_version; } + void update_table_map_version() { ++m_table_map_version; } + + int flush_and_set_pending_rows_event(THD *thd, Rows_log_event* event); + int remove_pending_rows_event(THD *thd); + +#endif /* !defined(MYSQL_CLIENT) */ + void reset_bytes_written() + { + bytes_written = 0; + } + void harvest_bytes_written(ulonglong* counter) + { +#ifndef DBUG_OFF + char buf1[22],buf2[22]; +#endif + DBUG_ENTER("harvest_bytes_written"); + (*counter)+=bytes_written; + DBUG_PRINT("info",("counter: %s bytes_written: %s", llstr(*counter,buf1), + llstr(bytes_written,buf2))); + bytes_written=0; + DBUG_VOID_RETURN; + } + void set_max_size(ulong max_size_arg); + void signal_update(); + void wait_for_update(THD* thd, bool master_or_slave); + void set_need_start_event() { need_start_event = 1; } + void init(bool no_auto_events_arg, ulong max_size); + void init_pthread_objects(); + void cleanup(); + bool open(const char *log_name, + enum_log_type log_type, + const char *new_name, + enum cache_type io_cache_type_arg, + bool no_auto_events_arg, ulong max_size, + bool null_created); + bool open_index_file(const char *index_file_name_arg, + const char *log_name); + /* Use this to start writing a new log file */ + void new_file(); + + bool write(Log_event* event_info); // binary log write + bool write(THD *thd, IO_CACHE *cache, Log_event *commit_event, bool incident); + bool write_incident(THD *thd, bool lock); + + int write_cache(IO_CACHE *cache, bool lock_log, bool flush_and_sync); + void set_write_error(THD *thd); + bool check_write_error(THD *thd); + + void start_union_events(THD *thd, query_id_t query_id_param); + void stop_union_events(THD *thd); + bool is_query_in_union(THD *thd, query_id_t query_id_param); + + /* + v stands for vector + invoked as appendv(buf1,len1,buf2,len2,...,bufn,lenn,0) + */ + bool appendv(const char* buf,uint len,...); + bool append(Log_event* ev); + + void make_log_name(char* buf, const char* log_ident); + bool is_active(const char* log_file_name); + int update_log_index(LOG_INFO* linfo, bool need_update_threads); + void rotate_and_purge(uint flags); + bool flush_and_sync(); + int purge_logs(const char *to_log, bool included, + bool need_mutex, bool need_update_threads, + ulonglong *decrease_log_space); + int purge_logs_before_date(time_t purge_time); + int purge_first_log(Relay_log_info* rli, bool included); + bool reset_logs(THD* thd); + void close(uint exiting); + + // iterating through the log index file + int find_log_pos(LOG_INFO* linfo, const char* log_name, + bool need_mutex); + int find_next_log(LOG_INFO* linfo, bool need_mutex); + int get_current_log(LOG_INFO* linfo); + int raw_get_current_log(LOG_INFO* linfo); + uint next_file_id(); + inline char* get_index_fname() { return index_file_name;} + inline char* get_log_fname() { return log_file_name; } + inline char* get_name() { return name; } + inline pthread_mutex_t* get_log_lock() { return &LOCK_log; } + inline IO_CACHE* get_log_file() { return &log_file; } + + inline void lock_index() { pthread_mutex_lock(&LOCK_index);} + inline void unlock_index() { pthread_mutex_unlock(&LOCK_index);} + inline IO_CACHE *get_index_file() { return &index_file;} + inline uint32 get_open_count() { return open_count; } +}; + +class Log_event_handler +{ +public: + Log_event_handler() {} + virtual bool init()= 0; + virtual void cleanup()= 0; + + virtual bool log_slow(THD *thd, time_t current_time, + time_t query_start_arg, const char *user_host, + uint user_host_len, ulonglong query_utime, + ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len)= 0; + virtual bool log_error(enum loglevel level, const char *format, + va_list args)= 0; + virtual bool log_general(THD *thd, time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len, + CHARSET_INFO *client_cs)= 0; + virtual ~Log_event_handler() {} +}; + + +int check_if_log_table(uint db_len, const char *db, uint table_name_len, + const char *table_name, uint check_if_opened); + +class Log_to_csv_event_handler: public Log_event_handler +{ + friend class LOGGER; + +public: + Log_to_csv_event_handler(); + ~Log_to_csv_event_handler(); + virtual bool init(); + virtual void cleanup(); + + virtual bool log_slow(THD *thd, time_t current_time, + time_t query_start_arg, const char *user_host, + uint user_host_len, ulonglong query_utime, + ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len); + virtual bool log_error(enum loglevel level, const char *format, + va_list args); + virtual bool log_general(THD *thd, time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len, + CHARSET_INFO *client_cs); + + int activate_log(THD *thd, uint log_type); +}; + + +/* type of the log table */ +#define QUERY_LOG_SLOW 1 +#define QUERY_LOG_GENERAL 2 + +class Log_to_file_event_handler: public Log_event_handler +{ + MYSQL_QUERY_LOG mysql_log; + MYSQL_QUERY_LOG mysql_slow_log; + bool is_initialized; +public: + Log_to_file_event_handler(): is_initialized(FALSE) + {} + virtual bool init(); + virtual void cleanup(); + + virtual bool log_slow(THD *thd, time_t current_time, + time_t query_start_arg, const char *user_host, + uint user_host_len, ulonglong query_utime, + ulonglong lock_utime, bool is_command, + const char *sql_text, uint sql_text_len); + virtual bool log_error(enum loglevel level, const char *format, + va_list args); + virtual bool log_general(THD *thd, time_t event_time, const char *user_host, + uint user_host_len, int thread_id, + const char *command_type, uint command_type_len, + const char *sql_text, uint sql_text_len, + CHARSET_INFO *client_cs); + void flush(); + void init_pthread_objects(); + MYSQL_QUERY_LOG *get_mysql_slow_log() { return &mysql_slow_log; } + MYSQL_QUERY_LOG *get_mysql_log() { return &mysql_log; } +}; + + +/* Class which manages slow, general and error log event handlers */ +class LOGGER +{ + rw_lock_t LOCK_logger; + /* flag to check whether logger mutex is initialized */ + uint inited; + + /* available log handlers */ + Log_to_csv_event_handler *table_log_handler; + Log_to_file_event_handler *file_log_handler; + + /* NULL-terminated arrays of log handlers */ + Log_event_handler *error_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; + Log_event_handler *slow_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; + Log_event_handler *general_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; + +public: + + bool is_log_tables_initialized; + + LOGGER() : inited(0), table_log_handler(NULL), + file_log_handler(NULL), is_log_tables_initialized(FALSE) + {} + void lock_shared() { rw_rdlock(&LOCK_logger); } + void lock_exclusive() { rw_wrlock(&LOCK_logger); } + void unlock() { rw_unlock(&LOCK_logger); } + bool is_log_table_enabled(uint log_table_type); + bool log_command(THD *thd, enum enum_server_command command); + + /* + We want to initialize all log mutexes as soon as possible, + but we cannot do it in constructor, as safe_mutex relies on + initialization, performed by MY_INIT(). This why this is done in + this function. + */ + void init_base(); + void init_log_tables(); + bool flush_logs(THD *thd); + /* Perform basic logger cleanup. this will leave e.g. error log open. */ + void cleanup_base(); + /* Free memory. Nothing could be logged after this function is called */ + void cleanup_end(); + bool error_log_print(enum loglevel level, const char *format, + va_list args); + bool slow_log_print(THD *thd, const char *query, uint query_length, + ulonglong current_utime); + bool general_log_print(THD *thd,enum enum_server_command command, + const char *format, va_list args); + bool general_log_write(THD *thd, enum enum_server_command command, + const char *query, uint query_length); + + /* we use this function to setup all enabled log event handlers */ + int set_handlers(uint error_log_printer, + uint slow_log_printer, + uint general_log_printer); + void init_error_log(uint error_log_printer); + void init_slow_log(uint slow_log_printer); + void init_general_log(uint general_log_printer); + void deactivate_log_handler(THD* thd, uint log_type); + bool activate_log_handler(THD* thd, uint log_type); + MYSQL_QUERY_LOG *get_slow_log_file_handler() + { + if (file_log_handler) + return file_log_handler->get_mysql_slow_log(); + return NULL; + } + MYSQL_QUERY_LOG *get_log_file_handler() + { + if (file_log_handler) + return file_log_handler->get_mysql_log(); + return NULL; + } +}; + +enum enum_binlog_format { + /* + statement-based except for cases where only row-based can work (UUID() + etc): + */ + BINLOG_FORMAT_MIXED= 0, + BINLOG_FORMAT_STMT= 1, // statement-based + BINLOG_FORMAT_ROW= 2, // row_based +/* + This value is last, after the end of binlog_format_typelib: it has no + corresponding cell in this typelib. We use this value to be able to know if + the user has explicitely specified a binlog format at startup or not. +*/ + BINLOG_FORMAT_UNSPEC= 3 +}; +extern TYPELIB binlog_format_typelib; + +int query_error_code(THD *thd, bool not_killed); + +#endif /* LOG_H */ diff --git a/dbcon/mysql/my.cnf b/dbcon/mysql/my.cnf index 6bd18ce3..4201bd56 100644 --- a/dbcon/mysql/my.cnf +++ b/dbcon/mysql/my.cnf @@ -1,5 +1,5 @@ # -# $Id: my.cnf 9502 2013-05-09 15:37:30Z pleblanc $ +# $Id: my.cnf 6014 2009-11-04 16:13:04Z rdempsey $ # # Example MySQL config file for very large systems. # @@ -29,7 +29,7 @@ socket = /usr/local/Calpont/mysql/lib/mysql/mysql.sock port = 3306 socket = /usr/local/Calpont/mysql/lib/mysql/mysql.sock datadir = /usr/local/Calpont/mysql/db -skip-external-locking +skip-locking key_buffer = 512M max_allowed_packet = 1M table_cache = 512 @@ -43,24 +43,7 @@ query_cache_size = 0 thread_concurrency = 8 thread_stack = 512K join_buffer_size = 128M -lower_case_table_names=1 - -# Enable compression by default on create, set to 0 to turn off -infinidb_compression_type=2 - -# Default for string table threshhold -infinidb_stringtable_threshold=20 - -# infinidb local query flag -# infinidb_local_query=1 - -infinidb_diskjoin_smallsidelimit=0 -infinidb_diskjoin_largesidelimit=0 -infinidb_diskjoin_bucketsize=100 -infinidb_um_mem_limit=0 - -infinidb_use_import_for_batchinsert=1 -infinidb_import_for_batchinsert_delimiter=7 +set-variable =lower_case_table_names=1 basedir = /usr/local/Calpont/mysql/ character-sets-dir = /usr/local/Calpont/mysql/share/mysql/charsets/ @@ -80,9 +63,9 @@ plugin_dir = /usr/local/Calpont/mysql/lib/mysql/plugin # log-bin=mysql-bin # required unique id between 1 and 2^32 - 1 -# defaults to 1 if master-host -# uses to 2+ if slave-host -server-id = 1 +# defaults to 1 if master-host is not set +# but will not function as a master if omitted +server-id = 1 # Replication Slave (comment out master section to use this) # @@ -115,6 +98,11 @@ server-id = 1 # For that reason, you may want to leave the lines below untouched # (commented) and instead use CHANGE MASTER TO (see above) # +# required unique id between 2 and 2^32 - 1 +# (and different from the master) +# defaults to 2 if master-host is set +# but will not function as a slave if omitted +#server-id = 2 # # The replication master for this slave - required #master-host = @@ -133,7 +121,6 @@ server-id = 1 # # binary logging - not required for slaves, but recommended #log-bin=mysql-bin -#relay-log=HOSTNAME-relay-bin # Point the following paths to different dedicated disks #tmpdir = /tmp/ diff --git a/dbcon/mysql/mysql-Calpont b/dbcon/mysql/mysql-Calpont index 875952b3..ba03f1a3 100755 --- a/dbcon/mysql/mysql-Calpont +++ b/dbcon/mysql/mysql-Calpont @@ -1,9 +1,5 @@ #!/bin/bash -# -# $Id: mysql-Calpont 9604 2013-06-05 15:56:49Z dhill $ -# - # Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB # This file is public domain and comes with NO WARRANTY of any kind @@ -56,7 +52,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR basedir=$INFINIDB_INSTALL_DIR/mysql datadir=$basedir/db @@ -225,17 +221,22 @@ wait_for_pid () { kill_by_pid() { # let's see if we can kill the 2 mysql procs by hand - # get the our mysql from ps - eval $(ps -ef | grep "$INFINIDB_INSTALL_DIR/mysql/libexec/mysqld" | grep -v grep | head -1 | awk '{printf "pid=%d\n", $2}') - - if [ -n "$pid" ]; then - ppid=$(ps -o ppid= -p $pid) + # get the port # mysqld is listening on (we can't just kill every mysql on the host + # we can only kill ours...) + port=$(awk '-F[ =]' '/^port/ {print $NF}' $basedir/my.cnf | head -1) + if [ -n "$port" ]; then + if [ -x /usr/sbin/lsof ]; then + eval $(/usr/sbin/lsof -P -i:$port | tail -1 | awk '{printf "pname=%s\npid=%d\n", $1, $2}') + if [ x$pname = xmysqld ]; then + ppid=$(ps -o ppid= -p $pid) $SUDO kill -9 $ppid sleep 1 $SUDO kill -9 $pid echo $echo_n "Force shutting down (no/bad pid file)" log_success_msg exit 0 + fi + fi fi return } diff --git a/dbcon/mysql/mysql_priv.h b/dbcon/mysql/mysql_priv.h new file mode 100644 index 00000000..27809d07 --- /dev/null +++ b/dbcon/mysql/mysql_priv.h @@ -0,0 +1,2562 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** + @file + + @details + Mostly this file is used in the server. But a little part of it is used in + mysqlbinlog too (definition of SELECT_DISTINCT and others). + The consequence is that 90% of the file is wrapped in \#ifndef MYSQL_CLIENT, + except the part which must be in the server and in the client. +*/ + +#ifndef MYSQL_PRIV_H +#define MYSQL_PRIV_H + +#ifndef MYSQL_CLIENT + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* Needed by field.h */ +#include +#include "sql_bitmap.h" +#include "sql_array.h" +#include "sql_plugin.h" +#include "scheduler.h" + +class Parser_state; + +/** + Query type constants. + + QT_ORDINARY -- ordinary SQL query. + QT_IS -- SQL query to be shown in INFORMATION_SCHEMA (in utf8 and without + character set introducers). +*/ +enum enum_query_type +{ + QT_ORDINARY, + QT_IS, + QT_INFINIDB, // this is for InfiniDB post process to customerize item::print() functions. + QT_INFINIDB_NO_QUOTE, // customized item:print() without quote delimiter + QT_INFINIDB_DERIVED // for union view as derived table. no view name is appended to the table alias. +}; + +/* TODO convert all these three maps to Bitmap classes */ +typedef ulonglong table_map; /* Used for table bits in join */ +#if MAX_INDEXES <= 64 +typedef Bitmap<64> key_map; /* Used for finding keys */ +#else +typedef Bitmap<((MAX_INDEXES+7)/8*8)> key_map; /* Used for finding keys */ +#endif +typedef ulong nesting_map; /* Used for flags of nesting constructs */ +/* + Used to identify NESTED_JOIN structures within a join (applicable only to + structures that have not been simplified away and embed more the one + element) +*/ +typedef ulonglong nested_join_map; + +/* query_id */ +typedef ulonglong query_id_t; +extern query_id_t global_query_id; + +/* increment query_id and return it. */ +inline query_id_t next_query_id() { return global_query_id++; } + +/* useful constants */ +extern MYSQL_PLUGIN_IMPORT const key_map key_map_empty; +extern MYSQL_PLUGIN_IMPORT key_map key_map_full; /* Should be threaded as const */ +extern MYSQL_PLUGIN_IMPORT const char *primary_key_name; + +#include "mysql_com.h" +#include +#include "unireg.h" + +void init_sql_alloc(MEM_ROOT *root, uint block_size, uint pre_alloc_size); +void *sql_alloc(size_t); +void *sql_calloc(size_t); +char *sql_strdup(const char *str); +char *sql_strmake(const char *str, size_t len); +void *sql_memdup(const void * ptr, size_t size); +void sql_element_free(void *ptr); +char *sql_strmake_with_convert(const char *str, size_t arg_length, + CHARSET_INFO *from_cs, + size_t max_res_length, + CHARSET_INFO *to_cs, size_t *result_length); +uint kill_one_thread(THD *thd, ulong id, bool only_kill_query); +void sql_kill(THD *thd, ulong id, bool only_kill_query); +bool net_request_file(NET* net, const char* fname); +char* query_table_status(THD *thd,const char *db,const char *table_name); + +#define x_free(A) { my_free((uchar*) (A),MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR)); } +#define safeFree(x) { if(x) { my_free((uchar*) x,MYF(0)); x = NULL; } } +#define PREV_BITS(type,A) ((type) (((type) 1 << (A)) -1)) +#define all_bits_set(A,B) ((A) & (B) != (B)) + +#define WARN_DEPRECATED(Thd,Ver,Old,New) \ + do { \ + DBUG_ASSERT(strncmp(Ver, MYSQL_SERVER_VERSION, sizeof(Ver)-1) > 0); \ + if (((uchar*)Thd) != NULL) \ + push_warning_printf(((THD *)Thd), MYSQL_ERROR::WARN_LEVEL_WARN, \ + ER_WARN_DEPRECATED_SYNTAX, ER(ER_WARN_DEPRECATED_SYNTAX_WITH_VER), \ + (Old), (Ver), (New)); \ + else \ + sql_print_warning("The syntax '%s' is deprecated and will be removed " \ + "in MySQL %s. Please use %s instead.", (Old), (Ver), (New)); \ + } while(0) + +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *system_charset_info; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *files_charset_info ; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *national_charset_info; +extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *table_alias_charset; + + +enum Derivation +{ + DERIVATION_IGNORABLE= 5, + DERIVATION_COERCIBLE= 4, + DERIVATION_SYSCONST= 3, + DERIVATION_IMPLICIT= 2, + DERIVATION_NONE= 1, + DERIVATION_EXPLICIT= 0 +}; + + +typedef struct my_locale_st +{ + uint number; + const char *name; + const char *description; + const bool is_ascii; + TYPELIB *month_names; + TYPELIB *ab_month_names; + TYPELIB *day_names; + TYPELIB *ab_day_names; + uint max_month_name_length; + uint max_day_name_length; +#ifdef __cplusplus + my_locale_st(uint number_par, + const char *name_par, const char *descr_par, bool is_ascii_par, + TYPELIB *month_names_par, TYPELIB *ab_month_names_par, + TYPELIB *day_names_par, TYPELIB *ab_day_names_par, + uint max_month_name_length_par, uint max_day_name_length_par) : + number(number_par), + name(name_par), description(descr_par), is_ascii(is_ascii_par), + month_names(month_names_par), ab_month_names(ab_month_names_par), + day_names(day_names_par), ab_day_names(ab_day_names_par), + max_month_name_length(max_month_name_length_par), + max_day_name_length(max_day_name_length_par) + {} +#endif +} MY_LOCALE; + +extern MY_LOCALE my_locale_en_US; +extern MY_LOCALE *my_locales[]; +extern MY_LOCALE *my_default_lc_time_names; + +MY_LOCALE *my_locale_by_name(const char *name); +MY_LOCALE *my_locale_by_number(uint number); + +/*************************************************************************/ + +/** + Object_creation_ctx -- interface for creation context of database objects + (views, stored routines, events, triggers). Creation context -- is a set + of attributes, that should be fixed at the creation time and then be used + each time the object is parsed or executed. +*/ + +class Object_creation_ctx +{ +public: + Object_creation_ctx *set_n_backup(THD *thd); + + void restore_env(THD *thd, Object_creation_ctx *backup_ctx); + +protected: + Object_creation_ctx() {} + virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0; + + virtual void change_env(THD *thd) const = 0; + +public: + virtual ~Object_creation_ctx() + { } +}; + +/*************************************************************************/ + +/** + Default_object_creation_ctx -- default implementation of + Object_creation_ctx. +*/ + +class Default_object_creation_ctx : public Object_creation_ctx +{ +public: + CHARSET_INFO *get_client_cs() + { + return m_client_cs; + } + + CHARSET_INFO *get_connection_cl() + { + return m_connection_cl; + } + +protected: + Default_object_creation_ctx(THD *thd); + + Default_object_creation_ctx(CHARSET_INFO *client_cs, + CHARSET_INFO *connection_cl); + +protected: + virtual Object_creation_ctx *create_backup_ctx(THD *thd) const; + + virtual void change_env(THD *thd) const; + +protected: + /** + client_cs stores the value of character_set_client session variable. + The only character set attribute is used. + + Client character set is included into query context, because we save + query in the original character set, which is client character set. So, + in order to parse the query properly we have to switch client character + set on parsing. + */ + CHARSET_INFO *m_client_cs; + + /** + connection_cl stores the value of collation_connection session + variable. Both character set and collation attributes are used. + + Connection collation is included into query context, becase it defines + the character set and collation of text literals in internal + representation of query (item-objects). + */ + CHARSET_INFO *m_connection_cl; +}; + +/*************************************************************************** + Configuration parameters +****************************************************************************/ + +#define ACL_CACHE_SIZE 256 +#define MAX_PASSWORD_LENGTH 32 +#define HOST_CACHE_SIZE 128 +#define MAX_ACCEPT_RETRY 10 // Test accept this many times +#define MAX_FIELDS_BEFORE_HASH 32 +#define USER_VARS_HASH_SIZE 16 +#define TABLE_OPEN_CACHE_MIN 64 +#define TABLE_OPEN_CACHE_DEFAULT 64 +#define TABLE_DEF_CACHE_DEFAULT 256 +/** + We must have room for at least 256 table definitions in the table + cache, since otherwise there is no chance prepared + statements that use these many tables can work. + Prepared statements use table definition cache ids (table_map_id) + as table version identifiers. If the table definition + cache size is less than the number of tables used in a statement, + the contents of the table definition cache is guaranteed to rotate + between a prepare and execute. This leads to stable validation + errors. In future we shall use more stable version identifiers, + for now the only solution is to ensure that the table definition + cache can contain at least all tables of a given statement. +*/ +#define TABLE_DEF_CACHE_MIN 256 + +/* + Stack reservation. + Feel free to raise this by the smallest amount you can to get the + "execution_constants" test to pass. +*/ +#define STACK_MIN_SIZE 16000 // Abort if less stack during eval. + +#define STACK_MIN_SIZE_FOR_OPEN 1024*80 +#define STACK_BUFF_ALLOC 352 ///< For stack overrun checks +#ifndef MYSQLD_NET_RETRY_COUNT +#define MYSQLD_NET_RETRY_COUNT 10 ///< Abort read after this many int. +#endif +#define TEMP_POOL_SIZE 128 + +#define QUERY_ALLOC_BLOCK_SIZE 8192 +#define QUERY_ALLOC_PREALLOC_SIZE 8192 +#define TRANS_ALLOC_BLOCK_SIZE 4096 +#define TRANS_ALLOC_PREALLOC_SIZE 4096 +#define RANGE_ALLOC_BLOCK_SIZE 4096 +#define ACL_ALLOC_BLOCK_SIZE 1024 +#define UDF_ALLOC_BLOCK_SIZE 1024 +#define TABLE_ALLOC_BLOCK_SIZE 1024 +#define BDB_LOG_ALLOC_BLOCK_SIZE 1024 +#define WARN_ALLOC_BLOCK_SIZE 2048 +#define WARN_ALLOC_PREALLOC_SIZE 1024 +#define PROFILE_ALLOC_BLOCK_SIZE 2048 +#define PROFILE_ALLOC_PREALLOC_SIZE 1024 + +/* + The following parameters is to decide when to use an extra cache to + optimise seeks when reading a big table in sorted order +*/ +#define MIN_FILE_LENGTH_TO_USE_ROW_CACHE (10L*1024*1024) +#define MIN_ROWS_TO_USE_TABLE_CACHE 100 +#define MIN_ROWS_TO_USE_BULK_INSERT 100 + +/** + The following is used to decide if MySQL should use table scanning + instead of reading with keys. The number says how many evaluation of the + WHERE clause is comparable to reading one extra row from a table. +*/ +#define TIME_FOR_COMPARE 5 // 5 compares == one read + +/** + Number of comparisons of table rowids equivalent to reading one row from a + table. +*/ +#define TIME_FOR_COMPARE_ROWID (TIME_FOR_COMPARE*2) + +/* + For sequential disk seeks the cost formula is: + DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST * #blocks_to_skip + + The cost of average seek + DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST*BLOCKS_IN_AVG_SEEK =1.0. +*/ +#define DISK_SEEK_BASE_COST ((double)0.5) + +#define BLOCKS_IN_AVG_SEEK 128 + +#define DISK_SEEK_PROP_COST ((double)0.5/BLOCKS_IN_AVG_SEEK) + + +/** + Number of rows in a reference table when refereed through a not unique key. + This value is only used when we don't know anything about the key + distribution. +*/ +#define MATCHING_ROWS_IN_OTHER_TABLE 10 + +/** Don't pack string keys shorter than this (if PACK_KEYS=1 isn't used). */ +#define KEY_DEFAULT_PACK_LENGTH 8 + +/** Characters shown for the command in 'show processlist'. */ +#define PROCESS_LIST_WIDTH 100 +/* Characters shown for the command in 'information_schema.processlist' */ +#define PROCESS_LIST_INFO_WIDTH 65535 + +#define PRECISION_FOR_DOUBLE 53 +#define PRECISION_FOR_FLOAT 24 + +/* -[digits].E+## */ +#define MAX_FLOAT_STR_LENGTH (FLT_DIG + 6) +/* -[digits].E+### */ +#define MAX_DOUBLE_STR_LENGTH (DBL_DIG + 7) + +/* + Default time to wait before aborting a new client connection + that does not respond to "initial server greeting" timely +*/ +#define CONNECT_TIMEOUT 10 + +/* The following can also be changed from the command line */ +#define DEFAULT_CONCURRENCY 10 +#define DELAYED_LIMIT 100 /**< pause after xxx inserts */ +#define DELAYED_QUEUE_SIZE 1000 +#define DELAYED_WAIT_TIMEOUT 5*60 /**< Wait for delayed insert */ +#define FLUSH_TIME 0 /**< Don't flush tables */ +#define MAX_CONNECT_ERRORS 10 ///< errors before disabling host + +#ifdef __NETWARE__ +#define IF_NETWARE(A,B) A +#else +#define IF_NETWARE(A,B) B +#endif + +#if defined(__WIN__) +#undef FLUSH_TIME +#define FLUSH_TIME 1800 /**< Flush every half hour */ + +#define INTERRUPT_PRIOR -2 +#define CONNECT_PRIOR -1 +#define WAIT_PRIOR 0 +#define QUERY_PRIOR 2 +#else +#define INTERRUPT_PRIOR 10 +#define CONNECT_PRIOR 9 +#define WAIT_PRIOR 8 +#define QUERY_PRIOR 6 +#endif /* __WIN92__ */ + + /* Bits from testflag */ +#define TEST_PRINT_CACHED_TABLES 1 +#define TEST_NO_KEY_GROUP 2 +#define TEST_MIT_THREAD 4 +#define TEST_BLOCKING 8 +#define TEST_KEEP_TMP_TABLES 16 +#define TEST_READCHECK 64 /**< Force use of readcheck */ +#define TEST_NO_EXTRA 128 +#define TEST_CORE_ON_SIGNAL 256 /**< Give core if signal */ +#define TEST_NO_STACKTRACE 512 +#define TEST_SIGINT 1024 /**< Allow sigint on threads */ +#define TEST_SYNCHRONIZATION 2048 /**< get server to do sleep in + some places */ +#endif + +/* + This is included in the server and in the client. + Options for select set by the yacc parser (stored in lex->options). + + XXX: + log_event.h defines OPTIONS_WRITTEN_TO_BIN_LOG to specify what THD + options list are written into binlog. These options can NOT change their + values, or it will break replication between version. + + context is encoded as following: + SELECT - SELECT_LEX_NODE::options + THD - THD::options + intern - neither. used only as + func(..., select_node->options | thd->options | OPTION_XXX, ...) + + TODO: separate three contexts above, move them to separate bitfields. +*/ + +#define SELECT_DISTINCT (ULL(1) << 0) // SELECT, user +#define SELECT_STRAIGHT_JOIN (ULL(1) << 1) // SELECT, user +#define SELECT_DESCRIBE (ULL(1) << 2) // SELECT, user +#define SELECT_SMALL_RESULT (ULL(1) << 3) // SELECT, user +#define SELECT_BIG_RESULT (ULL(1) << 4) // SELECT, user +#define OPTION_FOUND_ROWS (ULL(1) << 5) // SELECT, user +#define OPTION_TO_QUERY_CACHE (ULL(1) << 6) // SELECT, user +#define SELECT_NO_JOIN_CACHE (ULL(1) << 7) // intern +#define OPTION_BIG_TABLES (ULL(1) << 8) // THD, user +#define OPTION_BIG_SELECTS (ULL(1) << 9) // THD, user +#define OPTION_LOG_OFF (ULL(1) << 10) // THD, user +#define OPTION_QUOTE_SHOW_CREATE (ULL(1) << 11) // THD, user, unused +#define TMP_TABLE_ALL_COLUMNS (ULL(1) << 12) // SELECT, intern +#define OPTION_WARNINGS (ULL(1) << 13) // THD, user +#define OPTION_AUTO_IS_NULL (ULL(1) << 14) // THD, user, binlog +#define OPTION_FOUND_COMMENT (ULL(1) << 15) // SELECT, intern, parser +#define OPTION_SAFE_UPDATES (ULL(1) << 16) // THD, user +#define OPTION_BUFFER_RESULT (ULL(1) << 17) // SELECT, user +#define OPTION_BIN_LOG (ULL(1) << 18) // THD, user +#define OPTION_NOT_AUTOCOMMIT (ULL(1) << 19) // THD, user +#define OPTION_BEGIN (ULL(1) << 20) // THD, intern +#define OPTION_TABLE_LOCK (ULL(1) << 21) // THD, intern +#define OPTION_QUICK (ULL(1) << 22) // SELECT (for DELETE) +#define OPTION_KEEP_LOG (ULL(1) << 23) // THD, user + +/* The following is used to detect a conflict with DISTINCT */ +#define SELECT_ALL (ULL(1) << 24) // SELECT, user, parser + +/** The following can be set when importing tables in a 'wrong order' + to suppress foreign key checks */ +#define OPTION_NO_FOREIGN_KEY_CHECKS (ULL(1) << 26) // THD, user, binlog +/** The following speeds up inserts to InnoDB tables by suppressing unique + key checks in some cases */ +#define OPTION_RELAXED_UNIQUE_CHECKS (ULL(1) << 27) // THD, user, binlog +#define SELECT_NO_UNLOCK (ULL(1) << 28) // SELECT, intern +#define OPTION_SCHEMA_TABLE (ULL(1) << 29) // SELECT, intern +/** Flag set if setup_tables already done */ +#define OPTION_SETUP_TABLES_DONE (ULL(1) << 30) // intern +/** If not set then the thread will ignore all warnings with level notes. */ +#define OPTION_SQL_NOTES (ULL(1) << 31) // THD, user +/** + Force the used temporary table to be a MyISAM table (because we will use + fulltext functions when reading from it. +*/ +#define TMP_TABLE_FORCE_MYISAM (ULL(1) << 32) +#define OPTION_PROFILING (ULL(1) << 33) + + + +/** + Maximum length of time zone name that we support + (Time zone name is char(64) in db). mysqlbinlog needs it. +*/ +#define MAX_TIME_ZONE_NAME_LENGTH (NAME_LEN + 1) + +/* The rest of the file is included in the server only */ +#ifndef MYSQL_CLIENT + +/* Bits for different SQL modes modes (including ANSI mode) */ +#define MODE_REAL_AS_FLOAT 1 +#define MODE_PIPES_AS_CONCAT 2 +#define MODE_ANSI_QUOTES 4 +#define MODE_IGNORE_SPACE 8 +#define MODE_NOT_USED 16 +#define MODE_ONLY_FULL_GROUP_BY 32 +#define MODE_NO_UNSIGNED_SUBTRACTION 64 +#define MODE_NO_DIR_IN_CREATE 128 +#define MODE_POSTGRESQL 256 +#define MODE_ORACLE 512 +#define MODE_MSSQL 1024 +#define MODE_DB2 2048 +#define MODE_MAXDB 4096 +#define MODE_NO_KEY_OPTIONS 8192 +#define MODE_NO_TABLE_OPTIONS 16384 +#define MODE_NO_FIELD_OPTIONS 32768 +#define MODE_MYSQL323 65536L +#define MODE_MYSQL40 (MODE_MYSQL323*2) +#define MODE_ANSI (MODE_MYSQL40*2) +#define MODE_NO_AUTO_VALUE_ON_ZERO (MODE_ANSI*2) +#define MODE_NO_BACKSLASH_ESCAPES (MODE_NO_AUTO_VALUE_ON_ZERO*2) +#define MODE_STRICT_TRANS_TABLES (MODE_NO_BACKSLASH_ESCAPES*2) +#define MODE_STRICT_ALL_TABLES (MODE_STRICT_TRANS_TABLES*2) +#define MODE_NO_ZERO_IN_DATE (MODE_STRICT_ALL_TABLES*2) +#define MODE_NO_ZERO_DATE (MODE_NO_ZERO_IN_DATE*2) +#define MODE_INVALID_DATES (MODE_NO_ZERO_DATE*2) +#define MODE_ERROR_FOR_DIVISION_BY_ZERO (MODE_INVALID_DATES*2) +#define MODE_TRADITIONAL (MODE_ERROR_FOR_DIVISION_BY_ZERO*2) +#define MODE_NO_AUTO_CREATE_USER (MODE_TRADITIONAL*2) +#define MODE_HIGH_NOT_PRECEDENCE (MODE_NO_AUTO_CREATE_USER*2) +#define MODE_NO_ENGINE_SUBSTITUTION (MODE_HIGH_NOT_PRECEDENCE*2) +#define MODE_PAD_CHAR_TO_FULL_LENGTH (ULL(1) << 31) + +/* @@optimizer_switch flags. These must be in sync with optimizer_switch_typelib */ +#define OPTIMIZER_SWITCH_INDEX_MERGE 1 +#define OPTIMIZER_SWITCH_INDEX_MERGE_UNION 2 +#define OPTIMIZER_SWITCH_INDEX_MERGE_SORT_UNION 4 +#define OPTIMIZER_SWITCH_INDEX_MERGE_INTERSECT 8 +#define OPTIMIZER_SWITCH_LAST 16 + +/* The following must be kept in sync with optimizer_switch_str in mysqld.cc */ +#define OPTIMIZER_SWITCH_DEFAULT (OPTIMIZER_SWITCH_INDEX_MERGE | \ + OPTIMIZER_SWITCH_INDEX_MERGE_UNION | \ + OPTIMIZER_SWITCH_INDEX_MERGE_SORT_UNION | \ + OPTIMIZER_SWITCH_INDEX_MERGE_INTERSECT) + + +/* + Replication uses 8 bytes to store SQL_MODE in the binary log. The day you + use strictly more than 64 bits by adding one more define above, you should + contact the replication team because the replication code should then be + updated (to store more bytes on disk). + + NOTE: When adding new SQL_MODE types, make sure to also add them to + the scripts used for creating the MySQL system tables + in scripts/mysql_system_tables.sql and scripts/mysql_system_tables_fix.sql + +*/ + +#define RAID_BLOCK_SIZE 1024 + +#define MY_CHARSET_BIN_MB_MAXLEN 1 + +// uncachable cause +#define UNCACHEABLE_DEPENDENT 1 +#define UNCACHEABLE_RAND 2 +#define UNCACHEABLE_SIDEEFFECT 4 +/// forcing to save JOIN for explain +#define UNCACHEABLE_EXPLAIN 8 +/** Don't evaluate subqueries in prepare even if they're not correlated */ +#define UNCACHEABLE_PREPARE 16 +/* For uncorrelated SELECT in an UNION with some correlated SELECTs */ +#define UNCACHEABLE_UNITED 32 +#define UNCACHEABLE_CHECKOPTION 64 + +/* Used to check GROUP BY list in the MODE_ONLY_FULL_GROUP_BY mode */ +#define UNDEF_POS (-1) +#ifdef EXTRA_DEBUG +/** + Sync points allow us to force the server to reach a certain line of code + and block there until the client tells the server it is ok to go on. + The client tells the server to block with SELECT GET_LOCK() + and unblocks it with SELECT RELEASE_LOCK(). Used for debugging difficult + concurrency problems +*/ +#define DBUG_SYNC_POINT(lock_name,lock_timeout) \ + debug_sync_point(lock_name,lock_timeout) +void debug_sync_point(const char* lock_name, uint lock_timeout); +#else +#define DBUG_SYNC_POINT(lock_name,lock_timeout) +#endif /* EXTRA_DEBUG */ + +/* BINLOG_DUMP options */ + +#define BINLOG_DUMP_NON_BLOCK 1 + +/* sql_show.cc:show_log_files() */ +#define SHOW_LOG_STATUS_FREE "FREE" +#define SHOW_LOG_STATUS_INUSE "IN USE" + +struct TABLE_LIST; +class String; +void view_store_options(THD *thd, TABLE_LIST *table, String *buff); + +/* Options to add_table_to_list() */ +#define TL_OPTION_UPDATING 1 +#define TL_OPTION_FORCE_INDEX 2 +#define TL_OPTION_IGNORE_LEAVES 4 +#define TL_OPTION_ALIAS 8 + +/* Some portable defines */ + +#define portable_sizeof_char_ptr 8 + +#define tmp_file_prefix "#sql" /**< Prefix for tmp tables */ +#define tmp_file_prefix_length 4 + +/* Flags for calc_week() function. */ +#define WEEK_MONDAY_FIRST 1 +#define WEEK_YEAR 2 +#define WEEK_FIRST_WEEKDAY 4 + +#define STRING_BUFFER_USUAL_SIZE 80 + +/* + Some defines for exit codes for ::is_equal class functions. +*/ +#define IS_EQUAL_NO 0 +#define IS_EQUAL_YES 1 +#define IS_EQUAL_PACK_LENGTH 2 + +enum enum_parsing_place +{ + NO_MATTER, + IN_HAVING, + SELECT_LIST, + IN_WHERE, + IN_ON +}; + +struct st_table; + +#define thd_proc_info(thd, msg) set_thd_proc_info(thd, msg, __func__, __FILE__, __LINE__) +class THD; + +enum enum_check_fields +{ + CHECK_FIELD_IGNORE, + CHECK_FIELD_WARN, + CHECK_FIELD_ERROR_FOR_NULL +}; + + +/** Struct to handle simple linked lists. */ +typedef struct st_sql_list { + uint elements; + uchar *first; + uchar **next; + + st_sql_list() {} /* Remove gcc warning */ + inline void empty() + { + elements=0; + first=0; + next= &first; + } + inline void link_in_list(uchar *element,uchar **next_ptr) + { + elements++; + (*next)=element; + next= next_ptr; + *next=0; + } + inline void save_and_clear(struct st_sql_list *save) + { + *save= *this; + empty(); + } + inline void push_front(struct st_sql_list *save) + { + *save->next= first; /* link current list last */ + first= save->first; + elements+= save->elements; + } + inline void push_back(struct st_sql_list *save) + { + if (save->first) + { + *next= save->first; + next= save->next; + elements+= save->elements; + } + } +} SQL_LIST; + +#if defined(MYSQL_DYNAMIC_PLUGIN) && defined(_WIN32) +extern "C" THD *_current_thd_noinline(); +#define _current_thd() _current_thd_noinline() +#else +extern pthread_key(THD*, THR_THD); +inline THD *_current_thd(void) +{ + return my_pthread_getspecific_ptr(THD*,THR_THD); +} +#endif +#define current_thd _current_thd() + + +/** + The meat of thd_proc_info(THD*, char*), a macro that packs the last + three calling-info parameters. +*/ +extern "C" +const char *set_thd_proc_info(THD *thd, const char *info, + const char *calling_func, + const char *calling_file, + const unsigned int calling_line); + +/** + Enumerate possible types of a table from re-execution + standpoint. + TABLE_LIST class has a member of this type. + At prepared statement prepare, this member is assigned a value + as of the current state of the database. Before (re-)execution + of a prepared statement, we check that the value recorded at + prepare matches the type of the object we obtained from the + table definition cache. + + @sa check_and_update_table_version() + @sa Execute_observer + @sa Prepared_statement::reprepare() +*/ + +enum enum_table_ref_type +{ + /** Initial value set by the parser */ + TABLE_REF_NULL= 0, + TABLE_REF_VIEW, + TABLE_REF_BASE_TABLE, + TABLE_REF_I_S_TABLE, + TABLE_REF_TMP_TABLE +}; + +/* + External variables +*/ +extern ulong server_id, concurrency; + + +typedef my_bool (*qc_engine_callback)(THD *thd, char *table_key, + uint key_length, + ulonglong *engine_data); +#include "sql_string.h" +#include "sql_list.h" +#include "sql_map.h" +#include "my_decimal.h" +#include "handler.h" +#include "parse_file.h" +#include "table.h" +#include "sql_error.h" +#include "field.h" /* Field definitions */ +#include "protocol.h" +#include "sql_udf.h" +#include "sql_profile.h" +#include "sql_partition.h" + +class user_var_entry; +class Security_context; +enum enum_var_type +{ + OPT_DEFAULT= 0, OPT_SESSION, OPT_GLOBAL +}; +class sys_var; +#ifdef MYSQL_SERVER +class Comp_creator; +typedef Comp_creator* (*chooser_compare_func_creator)(bool invert); +#endif +#ifdef USE_CALPONT_REGEX +#undef USE_REGEX +#endif +#include "item.h" +extern my_decimal decimal_zero; + +/* sql_parse.cc */ +void free_items(Item *item); +void cleanup_items(Item *item); +class THD; +void close_thread_tables(THD *thd); + +#ifndef NO_EMBEDDED_ACCESS_CHECKS +bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *tables); +bool check_single_table_access(THD *thd, ulong privilege, + TABLE_LIST *tables, bool no_errors); +bool check_routine_access(THD *thd,ulong want_access,char *db,char *name, + bool is_proc, bool no_errors); +bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table); +bool check_some_routine_access(THD *thd, const char *db, const char *name, bool is_proc); +#else +inline bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *tables) +{ return false; } +inline bool check_single_table_access(THD *thd, ulong privilege, + TABLE_LIST *tables, bool no_errors) +{ return false; } +inline bool check_routine_access(THD *thd,ulong want_access,char *db, + char *name, bool is_proc, bool no_errors) +{ return false; } +inline bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table) +{ return false; } +inline bool check_merge_table_access(THD *thd, char *db, TABLE_LIST *table_list) +{ return false; } +inline bool check_some_routine_access(THD *thd, const char *db, + const char *name, bool is_proc) +{ return false; } +#endif /*NO_EMBEDDED_ACCESS_CHECKS*/ + +bool multi_update_precheck(THD *thd, TABLE_LIST *tables); +bool multi_delete_precheck(THD *thd, TABLE_LIST *tables); +int mysql_multi_update_prepare(THD *thd); +int mysql_multi_delete_prepare(THD *thd); +bool mysql_insert_select_prepare(THD *thd); +bool update_precheck(THD *thd, TABLE_LIST *tables); +bool delete_precheck(THD *thd, TABLE_LIST *tables); +bool insert_precheck(THD *thd, TABLE_LIST *tables); +bool create_table_precheck(THD *thd, TABLE_LIST *tables, + TABLE_LIST *create_table); +int append_query_string(CHARSET_INFO *csinfo, + String const *from, String *to); + +void get_default_definer(THD *thd, LEX_USER *definer); +LEX_USER *create_default_definer(THD *thd); +LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name); +LEX_USER *get_current_user(THD *thd, LEX_USER *user); +bool check_string_byte_length(LEX_STRING *str, const char *err_msg, + uint max_byte_length); +bool check_string_char_length(LEX_STRING *str, const char *err_msg, + uint max_char_length, CHARSET_INFO *cs, + bool no_error); +bool check_host_name(LEX_STRING *str); + +bool parse_sql(THD *thd, + Parser_state *parser_state, + Object_creation_ctx *creation_ctx); + +enum enum_mysql_completiontype { + ROLLBACK_RELEASE=-2, ROLLBACK=1, ROLLBACK_AND_CHAIN=7, + COMMIT_RELEASE=-1, COMMIT=0, COMMIT_AND_CHAIN=6 +}; + +bool begin_trans(THD *thd); +bool end_active_trans(THD *thd); +int end_trans(THD *thd, enum enum_mysql_completiontype completion); + +Item *negate_expression(THD *thd, Item *expr); + +/* log.cc */ +int vprint_msg_to_log(enum loglevel level, const char *format, va_list args); +void sql_print_error(const char *format, ...) ATTRIBUTE_FORMAT(printf, 1, 2); +void sql_print_warning(const char *format, ...) ATTRIBUTE_FORMAT(printf, 1, 2); +void sql_print_information(const char *format, ...) + ATTRIBUTE_FORMAT(printf, 1, 2); +typedef void (*sql_print_message_func)(const char *format, ...) + ATTRIBUTE_FORMAT(printf, 1, 2); +extern sql_print_message_func sql_print_message_handlers[]; + +int error_log_print(enum loglevel level, const char *format, + va_list args); + +bool slow_log_print(THD *thd, const char *query, uint query_length, + ulonglong current_utime); + +bool general_log_print(THD *thd, enum enum_server_command command, + const char *format,...); + +bool general_log_write(THD *thd, enum enum_server_command command, + const char *query, uint query_length); + +#include "sql_class.h" +#include "sql_acl.h" +#include "tztime.h" +#ifdef MYSQL_SERVER +#include "sql_servers.h" +#include "opt_range.h" + +#ifdef HAVE_QUERY_CACHE +struct Query_cache_query_flags +{ + unsigned int client_long_flag:1; + unsigned int client_protocol_41:1; + unsigned int result_in_binary_protocol:1; + unsigned int more_results_exists:1; + unsigned int in_trans:1; + unsigned int autocommit:1; + unsigned int pkt_nr; + uint character_set_client_num; + uint character_set_results_num; + uint collation_connection_num; + ha_rows limit; + Time_zone *time_zone; + ulong sql_mode; + ulong max_sort_length; + ulong group_concat_max_len; + ulong default_week_format; + ulong div_precision_increment; + MY_LOCALE *lc_time_names; +}; +#define QUERY_CACHE_FLAGS_SIZE sizeof(Query_cache_query_flags) +#include "sql_cache.h" +#define query_cache_store_query(A, B) query_cache.store_query(A, B) +#define query_cache_destroy() query_cache.destroy() +#define query_cache_result_size_limit(A) query_cache.result_size_limit(A) +#define query_cache_init() query_cache.init() +#define query_cache_resize(A) query_cache.resize(A) +#define query_cache_set_min_res_unit(A) query_cache.set_min_res_unit(A) +#define query_cache_invalidate3(A, B, C) query_cache.invalidate(A, B, C) +#define query_cache_invalidate1(A) query_cache.invalidate(A) +#define query_cache_send_result_to_client(A, B, C) \ + query_cache.send_result_to_client(A, B, C) +#define query_cache_invalidate_by_MyISAM_filename_ref \ + &query_cache_invalidate_by_MyISAM_filename +/* note the "maybe": it's a read without mutex */ +#define query_cache_maybe_disabled(T) \ + (T->variables.query_cache_type == 0 || query_cache.query_cache_size == 0) +#define query_cache_is_cacheable_query(L) \ + (((L)->sql_command == SQLCOM_SELECT) && (L)->safe_to_cache_query) +#else +#define QUERY_CACHE_FLAGS_SIZE 0 +#define query_cache_store_query(A, B) +#define query_cache_destroy() +#define query_cache_result_size_limit(A) +#define query_cache_init() +#define query_cache_resize(A) +#define query_cache_set_min_res_unit(A) +#define query_cache_invalidate3(A, B, C) +#define query_cache_invalidate1(A) +#define query_cache_send_result_to_client(A, B, C) 0 +#define query_cache_invalidate_by_MyISAM_filename_ref NULL + +#define query_cache_abort(A) +#define query_cache_end_of_result(A) +#define query_cache_invalidate_by_MyISAM_filename_ref NULL +#define query_cache_maybe_disabled(T) 1 +#define query_cache_is_cacheable_query(L) 0 +#endif /*HAVE_QUERY_CACHE*/ + +/* + Error injector Macros to enable easy testing of recovery after failures + in various error cases. +*/ +#ifndef ERROR_INJECT_SUPPORT + +#define ERROR_INJECT(x) 0 +#define ERROR_INJECT_ACTION(x,action) 0 +#define ERROR_INJECT_CRASH(x) 0 +#define ERROR_INJECT_VALUE(x) 0 +#define ERROR_INJECT_VALUE_ACTION(x,action) 0 +#define ERROR_INJECT_VALUE_CRASH(x) 0 +#define SET_ERROR_INJECT_VALUE(x) + +#else + +inline bool check_and_unset_keyword(const char *dbug_str) +{ + const char *extra_str= "-d,"; + char total_str[200]; + if (_db_strict_keyword_ (dbug_str)) + { + strxmov(total_str, extra_str, dbug_str, NullS); + DBUG_SET(total_str); + return 1; + } + return 0; +} + + +inline bool +check_and_unset_inject_value(int value) +{ + THD *thd= current_thd; + if (thd->error_inject_value == (uint)value) + { + thd->error_inject_value= 0; + return 1; + } + return 0; +} + +/* + ERROR INJECT MODULE: + -------------------- + These macros are used to insert macros from the application code. + The event that activates those error injections can be activated + from SQL by using: + SET SESSION dbug=+d,code; + + After the error has been injected, the macros will automatically + remove the debug code, thus similar to using: + SET SESSION dbug=-d,code + from SQL. + + ERROR_INJECT_CRASH will inject a crash of the MySQL Server if code + is set when macro is called. ERROR_INJECT_CRASH can be used in + if-statements, it will always return FALSE unless of course it + crashes in which case it doesn't return at all. + + ERROR_INJECT_ACTION will inject the action specified in the action + parameter of the macro, before performing the action the code will + be removed such that no more events occur. ERROR_INJECT_ACTION + can also be used in if-statements and always returns FALSE. + ERROR_INJECT can be used in a normal if-statement, where the action + part is performed in the if-block. The macro returns TRUE if the + error was activated and otherwise returns FALSE. If activated the + code is removed. + + Sometimes it is necessary to perform error inject actions as a serie + of events. In this case one can use one variable on the THD object. + Thus one sets this value by using e.g. SET_ERROR_INJECT_VALUE(100). + Then one can later test for it by using ERROR_INJECT_CRASH_VALUE, + ERROR_INJECT_ACTION_VALUE and ERROR_INJECT_VALUE. This have the same + behaviour as the above described macros except that they use the + error inject value instead of a code used by DBUG macros. +*/ +#define SET_ERROR_INJECT_VALUE(x) \ + current_thd->error_inject_value= (x) +#define ERROR_INJECT_CRASH(code) \ + DBUG_EVALUATE_IF(code, (abort(), 0), 0) +#define ERROR_INJECT_ACTION(code, action) \ + (check_and_unset_keyword(code) ? ((action), 0) : 0) +#define ERROR_INJECT(code) \ + check_and_unset_keyword(code) +#define ERROR_INJECT_VALUE(value) \ + check_and_unset_inject_value(value) +#define ERROR_INJECT_VALUE_ACTION(value,action) \ + (check_and_unset_inject_value(value) ? (action) : 0) +#define ERROR_INJECT_VALUE_CRASH(value) \ + ERROR_INJECT_VALUE_ACTION(value, (abort(), 0)) + +#endif + +void write_bin_log(THD *thd, bool clear_error, + char const *query, ulong query_length); + +/* sql_connect.cc */ +int check_user(THD *thd, enum enum_server_command command, + const char *passwd, uint passwd_len, const char *db, + bool check_count); +pthread_handler_t handle_one_connection(void *arg); +bool init_new_connection_handler_thread(); +void reset_mqh(LEX_USER *lu, bool get_them); +bool check_mqh(THD *thd, uint check_command); +void time_out_user_resource_limits(THD *thd, USER_CONN *uc); +void decrease_user_connections(USER_CONN *uc); +void thd_init_client_charset(THD *thd, uint cs_number); +bool setup_connection_thread_globals(THD *thd); + +int mysql_create_db(THD *thd, char *db, HA_CREATE_INFO *create, bool silent); +bool mysql_alter_db(THD *thd, const char *db, HA_CREATE_INFO *create); +bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent); +bool mysql_upgrade_db(THD *thd, LEX_STRING *old_db); +void mysql_binlog_send(THD* thd, char* log_ident, my_off_t pos, ushort flags); +void mysql_client_binlog_statement(THD *thd); +bool mysql_rm_table(THD *thd,TABLE_LIST *tables, my_bool if_exists, + my_bool drop_temporary); +int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, + bool drop_temporary, bool drop_view, bool log_query); +bool quick_rm_table(handlerton *base,const char *db, + const char *table_name, uint flags); +void close_cached_table(THD *thd, TABLE *table); +bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent); +bool do_rename(THD *thd, TABLE_LIST *ren_table, char *new_db, + char *new_table_name, char *new_table_alias, + bool skip_error); + +bool mysql_change_db(THD *thd, const LEX_STRING *new_db_name, + bool force_switch); + +bool mysql_opt_change_db(THD *thd, + const LEX_STRING *new_db_name, + LEX_STRING *saved_db_name, + bool force_switch, + bool *cur_db_changed); + +void mysql_parse(THD *thd, const char *inBuf, uint length, + const char ** semicolon); + +bool mysql_test_parse_for_slave(THD *thd,char *inBuf,uint length); +bool is_update_query(enum enum_sql_command command); +bool is_log_table_write_query(enum enum_sql_command command); +bool alloc_query(THD *thd, const char *packet, uint packet_length); +void mysql_init_select(LEX *lex); +void mysql_reset_thd_for_next_command(THD *thd); +bool mysql_new_select(LEX *lex, bool move_down); +void create_select_for_variable(const char *var_name); +void mysql_init_multi_delete(LEX *lex); +bool multi_delete_set_locks_and_link_aux_tables(LEX *lex); +void init_max_user_conn(void); +void init_update_queries(void); +void free_max_user_conn(void); +pthread_handler_t handle_bootstrap(void *arg); +int mysql_execute_command(THD *thd); +bool do_command(THD *thd); +bool dispatch_command(enum enum_server_command command, THD *thd, + char* packet, uint packet_length); +void log_slow_statement(THD *thd); +bool check_dup(const char *db, const char *name, TABLE_LIST *tables); +bool compare_record(TABLE *table); +bool append_file_to_dir(THD *thd, const char **filename_ptr, + const char *table_name); +void wait_while_table_is_used(THD *thd, TABLE *table, + enum ha_extra_function function); +bool table_cache_init(void); +void table_cache_free(void); +bool table_def_init(void); +void table_def_free(void); +void assign_new_table_id(TABLE_SHARE *share); +uint cached_open_tables(void); +uint cached_table_definitions(void); +void kill_mysql(void); +void close_connection(THD *thd, uint errcode, bool lock); +bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables, + bool *write_to_binlog); +#ifndef NO_EMBEDDED_ACCESS_CHECKS +bool check_access(THD *thd, ulong access, const char *db, ulong *save_priv, + bool no_grant, bool no_errors, bool schema_db); +bool check_table_access(THD *thd, ulong want_access, TABLE_LIST *tables, + uint number, bool no_errors); +#else +inline bool check_access(THD *thd, ulong access, const char *db, + ulong *save_priv, bool no_grant, bool no_errors, + bool schema_db) +{ + if (save_priv) + *save_priv= GLOBAL_ACLS; + return false; +} +inline bool check_table_access(THD *thd, ulong want_access, TABLE_LIST *tables, + uint number, bool no_errors) +{ return false; } +#endif /*NO_EMBEDDED_ACCESS_CHECKS*/ + +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +bool check_global_access(THD *thd, ulong want_access); +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER + +/* + Support routine for SQL parser on partitioning syntax +*/ +my_bool is_partition_management(LEX *lex); +/* + General routine to change field->ptr of a NULL-terminated array of Field + objects. Useful when needed to call val_int, val_str or similar and the + field data is not in table->record[0] but in some other structure. + set_key_field_ptr changes all fields of an index using a key_info object. + All methods presume that there is at least one field to change. +*/ + +void set_field_ptr(Field **ptr, const uchar *new_buf, const uchar *old_buf); +void set_key_field_ptr(KEY *key_info, const uchar *new_buf, + const uchar *old_buf); + +bool mysql_backup_table(THD* thd, TABLE_LIST* table_list); +bool mysql_restore_table(THD* thd, TABLE_LIST* table_list); + +bool mysql_checksum_table(THD* thd, TABLE_LIST* table_list, + HA_CHECK_OPT* check_opt); +bool mysql_check_table(THD* thd, TABLE_LIST* table_list, + HA_CHECK_OPT* check_opt); +bool mysql_repair_table(THD* thd, TABLE_LIST* table_list, + HA_CHECK_OPT* check_opt); +bool mysql_analyze_table(THD* thd, TABLE_LIST* table_list, + HA_CHECK_OPT* check_opt); +bool mysql_optimize_table(THD* thd, TABLE_LIST* table_list, + HA_CHECK_OPT* check_opt); +bool mysql_assign_to_keycache(THD* thd, TABLE_LIST* table_list, + LEX_STRING *key_cache_name); +bool mysql_preload_keys(THD* thd, TABLE_LIST* table_list); +int reassign_keycache_tables(THD* thd, KEY_CACHE *src_cache, + KEY_CACHE *dst_cache); +TABLE *create_virtual_tmp_table(THD *thd, List &field_list); + +bool mysql_xa_recover(THD *thd); + +bool check_simple_select(); +int mysql_alter_tablespace(THD* thd, st_alter_tablespace *ts_info); + +SORT_FIELD * make_unireg_sortorder(ORDER *order, uint *length, + SORT_FIELD *sortorder); +int setup_order(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables, + List &fields, List &all_fields, ORDER *order); +int setup_group(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables, + List &fields, List &all_fields, ORDER *order, + bool *hidden_group_fields); +bool fix_inner_refs(THD *thd, List &all_fields, SELECT_LEX *select, + Item **ref_pointer_array); + +bool handle_select(THD *thd, LEX *lex, select_result *result, + ulong setup_tables_done_option); +bool mysql_select(THD *thd, Item ***rref_pointer_array, + TABLE_LIST *tables, uint wild_num, List &list, + COND *conds, uint og_num, ORDER *order, ORDER *group, + Item *having, ORDER *proc_param, ulonglong select_type, + select_result *result, SELECT_LEX_UNIT *unit, + SELECT_LEX *select_lex); +void free_underlaid_joins(THD *thd, SELECT_LEX *select); +bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, + select_result *result); +int mysql_explain_select(THD *thd, SELECT_LEX *sl, char const *type, + select_result *result); +bool mysql_union(THD *thd, LEX *lex, select_result *result, + SELECT_LEX_UNIT *unit, ulong setup_tables_done_option); +bool mysql_handle_derived(LEX *lex, bool (*processor)(THD *thd, + LEX *lex, + TABLE_LIST *table)); +bool mysql_derived_prepare(THD *thd, LEX *lex, TABLE_LIST *t); +bool mysql_derived_filling(THD *thd, LEX *lex, TABLE_LIST *t); +Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type, + Item ***copy_func, Field **from_field, + Field **def_field, + bool group, bool modify_item, + bool table_cant_handle_bit_fields, + bool make_copy_field, + uint convert_blob_length); +void sp_prepare_create_field(THD *thd, Create_field *sql_field); +int prepare_create_field(Create_field *sql_field, + uint *blob_columns, + int *timestamps, int *timestamps_with_niladic, + longlong table_flags); +bool mysql_create_table(THD *thd,const char *db, const char *table_name, + HA_CREATE_INFO *create_info, + Alter_info *alter_info, + bool tmp_table, uint select_field_count); +bool mysql_create_table_no_lock(THD *thd, const char *db, + const char *table_name, + HA_CREATE_INFO *create_info, + Alter_info *alter_info, + bool tmp_table, uint select_field_count); + +bool mysql_alter_table(THD *thd, char *new_db, char *new_name, + HA_CREATE_INFO *create_info, + TABLE_LIST *table_list, + Alter_info *alter_info, + uint order_num, ORDER *order, bool ignore); +bool mysql_recreate_table(THD *thd, TABLE_LIST *table_list); +bool mysql_create_like_table(THD *thd, TABLE_LIST *table, + TABLE_LIST *src_table, + HA_CREATE_INFO *create_info); +bool mysql_rename_table(handlerton *base, const char *old_db, + const char * old_name, const char *new_db, + const char * new_name, uint flags); +bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list, + Item **conds, uint order_num, ORDER *order); +// @InfiniDB. Make conds argument reference to pointer so the optimization +// result can be passed in to the InfiniDB connector. +int mysql_update(THD *thd,TABLE_LIST *tables,List &fields, + List &values,COND *& conds, + uint order_num, ORDER *order, ha_rows limit, + enum enum_duplicates handle_duplicates, bool ignore); +// @InfiniDB. Make conds argument reference to pointer so the optimization +// result can be passed in to the InfiniDB connector. +bool mysql_multi_update(THD *thd, TABLE_LIST *table_list, + List *fields, List *values, + COND *& conds, ulonglong options, + enum enum_duplicates handle_duplicates, bool ignore, + SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex); +bool mysql_prepare_insert(THD *thd, TABLE_LIST *table_list, TABLE *table, + List &fields, List_item *values, + List &update_fields, + List &update_values, enum_duplicates duplic, + COND **where, bool select_insert, + bool check_fields, bool abort_on_warning); +bool mysql_insert(THD *thd,TABLE_LIST *table,List &fields, + List &values, List &update_fields, + List &update_values, enum_duplicates flag, + bool ignore); +int check_that_all_fields_are_given_values(THD *thd, TABLE *entry, + TABLE_LIST *table_list); +void prepare_triggers_for_insert_stmt(TABLE *table); +int mysql_prepare_delete(THD *thd, TABLE_LIST *table_list, Item **conds); +// @InfiniDB. Make conds argument reference to pointer so the optimization +// result can be passed in to the InfiniDB connector. +bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *& conds, + SQL_LIST *order, ha_rows rows, ulonglong options, + bool reset_auto_increment); +bool mysql_truncate(THD *thd, TABLE_LIST *table_list, bool dont_send_ok); +bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create); +uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list, + bool tmp_table); +TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key, + uint key_length, uint db_flags, int *error); +void release_table_share(TABLE_SHARE *share, enum release_type type); +TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name); +TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type update, + uint lock_flags); +TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT* mem, + bool *refresh, uint flags); +bool name_lock_locked_table(THD *thd, TABLE_LIST *tables); +bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in); +TABLE *table_cache_insert_placeholder(THD *thd, const char *key, + uint key_length); +bool lock_table_name_if_not_cached(THD *thd, const char *db, + const char *table_name, TABLE **table); +TABLE *find_locked_table(THD *thd, const char *db,const char *table_name); +void detach_merge_children(TABLE *table, bool clear_refs); +bool fix_merge_after_open(TABLE_LIST *old_child_list, TABLE_LIST **old_last, + TABLE_LIST *new_child_list, TABLE_LIST **new_last); +bool reopen_table(TABLE *table); +bool reopen_tables(THD *thd,bool get_locks,bool in_refresh); +thr_lock_type read_lock_type_for_table(THD *thd, TABLE *table); +void close_data_files_and_morph_locks(THD *thd, const char *db, + const char *table_name); +void close_handle_and_leave_table_as_lock(TABLE *table); +bool wait_for_tables(THD *thd); +bool table_is_used(TABLE *table, bool wait_for_name_lock); +TABLE *drop_locked_tables(THD *thd,const char *db, const char *table_name); +void abort_locked_tables(THD *thd,const char *db, const char *table_name); +void execute_init_command(THD *thd, sys_var_str *init_command_var, + rw_lock_t *var_mutex); +extern Field *not_found_field; +extern Field *view_ref_found; + +enum find_item_error_report_type {REPORT_ALL_ERRORS, REPORT_EXCEPT_NOT_FOUND, + IGNORE_ERRORS, REPORT_EXCEPT_NON_UNIQUE, + IGNORE_EXCEPT_NON_UNIQUE}; +Field * +find_field_in_tables(THD *thd, Item_ident *item, + TABLE_LIST *first_table, TABLE_LIST *last_table, + Item **ref, find_item_error_report_type report_error, + bool check_privileges, bool register_tree_change); +Field * +find_field_in_table_ref(THD *thd, TABLE_LIST *table_list, + const char *name, uint length, + const char *item_name, const char *db_name, + const char *table_name, Item **ref, + bool check_privileges, bool allow_rowid, + uint *cached_field_index_ptr, + bool register_tree_change, TABLE_LIST **actual_table); +Field * +find_field_in_table(THD *thd, TABLE *table, const char *name, uint length, + bool allow_rowid, uint *cached_field_index_ptr); +Field * +find_field_in_table_sef(TABLE *table, const char *name); + +#endif /* MYSQL_SERVER */ + +#ifdef HAVE_OPENSSL +#include +struct st_des_keyblock +{ + DES_cblock key1, key2, key3; +}; +struct st_des_keyschedule +{ + DES_key_schedule ks1, ks2, ks3; +}; +extern char *des_key_file; +extern struct st_des_keyschedule des_keyschedule[10]; +extern uint des_default_key; +extern pthread_mutex_t LOCK_des_key_file; +bool load_des_key_file(const char *file_name); +#endif /* HAVE_OPENSSL */ + +#ifdef MYSQL_SERVER +/* sql_do.cc */ +bool mysql_do(THD *thd, List &values); + +/* sql_analyse.h */ +bool append_escaped(String *to_str, String *from_str); + +/* sql_show.cc */ +bool mysqld_show_open_tables(THD *thd,const char *wild); +bool mysqld_show_logs(THD *thd); +void append_identifier(THD *thd, String *packet, const char *name, + uint length); +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +int get_quote_char_for_identifier(THD *thd, const char *name, uint length); +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +void mysqld_list_fields(THD *thd,TABLE_LIST *table, const char *wild); +int mysqld_dump_create_info(THD *thd, TABLE_LIST *table_list, int fd); +bool mysqld_show_create(THD *thd, TABLE_LIST *table_list); +bool mysqld_show_create_db(THD *thd, char *dbname, HA_CREATE_INFO *create); + +void mysqld_list_processes(THD *thd,const char *user,bool verbose); +int mysqld_show_status(THD *thd); +int mysqld_show_variables(THD *thd,const char *wild); +bool mysqld_show_storage_engines(THD *thd); +bool mysqld_show_authors(THD *thd); +bool mysqld_show_contributors(THD *thd); +bool mysqld_show_privileges(THD *thd); +bool mysqld_show_column_types(THD *thd); +bool mysqld_help (THD *thd, const char *text); +void calc_sum_of_all_status(STATUS_VAR *to); + +void append_definer(THD *thd, String *buffer, const LEX_STRING *definer_user, + const LEX_STRING *definer_host); + +int add_status_vars(SHOW_VAR *list); +void remove_status_vars(SHOW_VAR *list); +void init_status_vars(); +void free_status_vars(); +void reset_status_vars(); + +/* information schema */ +extern LEX_STRING INFORMATION_SCHEMA_NAME; +/* log tables */ +extern LEX_STRING MYSQL_SCHEMA_NAME; +extern LEX_STRING GENERAL_LOG_NAME; +extern LEX_STRING SLOW_LOG_NAME; + +extern const LEX_STRING partition_keywords[]; +ST_SCHEMA_TABLE *find_schema_table(THD *thd, const char* table_name); +ST_SCHEMA_TABLE *get_schema_table(enum enum_schema_tables schema_table_idx); +int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident, + enum enum_schema_tables schema_table_idx); +int make_schema_select(THD *thd, SELECT_LEX *sel, + enum enum_schema_tables schema_table_idx); +int mysql_schema_table(THD *thd, LEX *lex, TABLE_LIST *table_list); +int fill_schema_user_privileges(THD *thd, TABLE_LIST *tables, COND *cond); +int fill_schema_schema_privileges(THD *thd, TABLE_LIST *tables, COND *cond); +int fill_schema_table_privileges(THD *thd, TABLE_LIST *tables, COND *cond); +int fill_schema_column_privileges(THD *thd, TABLE_LIST *tables, COND *cond); +bool get_schema_tables_result(JOIN *join, + enum enum_schema_table_state executed_place); +enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table); + +#define is_schema_db(X) \ + !my_strcasecmp(system_charset_info, INFORMATION_SCHEMA_NAME.str, (X)) + +/* sql_prepare.cc */ + +void mysqld_stmt_prepare(THD *thd, const char *packet, uint packet_length); +void mysqld_stmt_execute(THD *thd, char *packet, uint packet_length); +void mysqld_stmt_close(THD *thd, char *packet); +void mysql_sql_stmt_prepare(THD *thd); +void mysql_sql_stmt_execute(THD *thd); +void mysql_sql_stmt_close(THD *thd); +void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length); +void mysqld_stmt_reset(THD *thd, char *packet); +void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length); +void reinit_stmt_before_use(THD *thd, LEX *lex); + +/* sql_handler.cc */ +bool mysql_ha_open(THD *thd, TABLE_LIST *tables, bool reopen); +bool mysql_ha_close(THD *thd, TABLE_LIST *tables); +bool mysql_ha_read(THD *, TABLE_LIST *,enum enum_ha_read_modes,char *, + List *,enum ha_rkey_function,Item *,ha_rows,ha_rows); +void mysql_ha_flush(THD *thd); +void mysql_ha_rm_tables(THD *thd, TABLE_LIST *tables, bool is_locked); +void mysql_ha_cleanup(THD *thd); + +/* sql_base.cc */ +#define TMP_TABLE_KEY_EXTRA 8 +void set_item_name(Item *item,char *pos,uint length); +bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum enum_field_types type, + char *length, char *decimal, + uint type_modifier, + Item *default_value, Item *on_update_value, + LEX_STRING *comment, + char *change, List *interval_list, + CHARSET_INFO *cs, + uint uint_geom_type); +Create_field * new_create_field(THD *thd, char *field_name, enum_field_types type, + char *length, char *decimals, + uint type_modifier, + Item *default_value, Item *on_update_value, + LEX_STRING *comment, char *change, + List *interval_list, CHARSET_INFO *cs, + uint uint_geom_type); +void store_position_for_column(const char *name); +bool add_to_list(THD *thd, SQL_LIST &list,Item *group,bool asc); +bool push_new_name_resolution_context(THD *thd, + TABLE_LIST *left_op, + TABLE_LIST *right_op); +void add_join_on(TABLE_LIST *b,Item *expr); +void add_join_natural(TABLE_LIST *a,TABLE_LIST *b,List *using_fields, + SELECT_LEX *lex); +bool add_proc_to_list(THD *thd, Item *item); +void unlink_open_table(THD *thd, TABLE *find, bool unlock); +void drop_open_table(THD *thd, TABLE *table, const char *db_name, + const char *table_name); +void update_non_unique_table_error(TABLE_LIST *update, + const char *operation, + TABLE_LIST *duplicate); + +SQL_SELECT *make_select(TABLE *head, table_map const_tables, + table_map read_tables, COND *conds, + bool allow_null_cond, int *error); +extern Item **not_found_item; + +/* + A set of constants used for checking non aggregated fields and sum + functions mixture in the ONLY_FULL_GROUP_BY_MODE. +*/ +#define NON_AGG_FIELD_USED 1 +#define SUM_FUNC_USED 2 + +/* + This enumeration type is used only by the function find_item_in_list + to return the info on how an item has been resolved against a list + of possibly aliased items. + The item can be resolved: + - against an alias name of the list's element (RESOLVED_AGAINST_ALIAS) + - against non-aliased field name of the list (RESOLVED_WITH_NO_ALIAS) + - against an aliased field name of the list (RESOLVED_BEHIND_ALIAS) + - ignoring the alias name in cases when SQL requires to ignore aliases + (e.g. when the resolved field reference contains a table name or + when the resolved item is an expression) (RESOLVED_IGNORING_ALIAS) +*/ +enum enum_resolution_type { + NOT_RESOLVED=0, + RESOLVED_IGNORING_ALIAS, + RESOLVED_BEHIND_ALIAS, + RESOLVED_WITH_NO_ALIAS, + RESOLVED_AGAINST_ALIAS +}; +Item ** find_item_in_list(Item *item, List &items, uint *counter, + find_item_error_report_type report_error, + enum_resolution_type *resolution); +bool get_key_map_from_key_list(key_map *map, TABLE *table, + List *index_list); +bool insert_fields(THD *thd, Name_resolution_context *context, + const char *db_name, const char *table_name, + List_iterator *it, bool any_privileges); +bool setup_tables(THD *thd, Name_resolution_context *context, + List *from_clause, TABLE_LIST *tables, + TABLE_LIST **leaves, bool select_insert); +bool setup_tables_and_check_access(THD *thd, + Name_resolution_context *context, + List *from_clause, + TABLE_LIST *tables, + TABLE_LIST **leaves, + bool select_insert, + ulong want_access_first, + ulong want_access); +int setup_wild(THD *thd, TABLE_LIST *tables, List &fields, + List *sum_func_list, uint wild_num); +bool setup_fields(THD *thd, Item** ref_pointer_array, + List &item, enum_mark_columns mark_used_columns, + List *sum_func_list, bool allow_sum_func); +inline bool setup_fields_with_no_wrap(THD *thd, Item **ref_pointer_array, + List &item, + enum_mark_columns mark_used_columns, + List *sum_func_list, + bool allow_sum_func) +{ + bool res; + thd->lex->select_lex.no_wrap_view_item= TRUE; + res= setup_fields(thd, ref_pointer_array, item, mark_used_columns, sum_func_list, + allow_sum_func); + thd->lex->select_lex.no_wrap_view_item= FALSE; + return res; +} +int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves, + COND **conds); +int setup_ftfuncs(SELECT_LEX* select); +int init_ftfuncs(THD *thd, SELECT_LEX* select, bool no_order); +void wait_for_condition(THD *thd, pthread_mutex_t *mutex, + pthread_cond_t *cond); +int open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags); +/* open_and_lock_tables with optional derived handling */ +int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived); +/* simple open_and_lock_tables without derived handling */ +inline int simple_open_n_lock_tables(THD *thd, TABLE_LIST *tables) +{ + return open_and_lock_tables_derived(thd, tables, FALSE); +} +/* open_and_lock_tables with derived handling */ +inline int open_and_lock_tables(THD *thd, TABLE_LIST *tables) +{ + return open_and_lock_tables_derived(thd, tables, TRUE); +} +/* simple open_and_lock_tables without derived handling for single table */ +TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l, + thr_lock_type lock_type); +bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags); +int lock_tables(THD *thd, TABLE_LIST *tables, uint counter, bool *need_reopen); +int decide_logging_format(THD *thd, TABLE_LIST *tables); +TABLE *open_temporary_table(THD *thd, const char *path, const char *db, + const char *table_name, bool link_in_list); +bool rm_temporary_table(handlerton *base, char *path); +void free_io_cache(TABLE *entry); +void intern_close_table(TABLE *entry); +bool close_thread_table(THD *thd, TABLE **table_ptr); +void close_temporary_tables(THD *thd); +void close_tables_for_reopen(THD *thd, TABLE_LIST **tables); +TABLE_LIST *find_table_in_list(TABLE_LIST *table, + TABLE_LIST *TABLE_LIST::*link, + const char *db_name, + const char *table_name); +TABLE_LIST *unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list, + bool check_alias); +TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name); +TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list); +int drop_temporary_table(THD *thd, TABLE_LIST *table_list); +void close_temporary_table(THD *thd, TABLE *table, bool free_share, + bool delete_table); +void close_temporary(TABLE *table, bool free_share, bool delete_table); +bool rename_temporary_table(THD* thd, TABLE *table, const char *new_db, + const char *table_name); +void remove_db_from_cache(const char *db); +void flush_tables(); +bool is_equal(const LEX_STRING *a, const LEX_STRING *b); +char *make_default_log_name(char *buff,const char* log_ext); + +#ifdef WITH_PARTITION_STORAGE_ENGINE +uint fast_alter_partition_table(THD *thd, TABLE *table, + Alter_info *alter_info, + HA_CREATE_INFO *create_info, + TABLE_LIST *table_list, + char *db, + const char *table_name, + uint fast_alter_partition); +uint set_part_state(Alter_info *alter_info, partition_info *tab_part_info, + enum partition_state part_state); +uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info, + HA_CREATE_INFO *create_info, + handlerton *old_db_type, + bool *partition_changed, + uint *fast_alter_partition); +#endif + +/* bits for last argument to remove_table_from_cache() */ +#define RTFC_NO_FLAG 0x0000 +#define RTFC_OWNED_BY_THD_FLAG 0x0001 +#define RTFC_WAIT_OTHER_THREAD_FLAG 0x0002 +#define RTFC_CHECK_KILLED_FLAG 0x0004 +bool remove_table_from_cache(THD *thd, const char *db, const char *table, + uint flags); + +#define NORMAL_PART_NAME 0 +#define TEMP_PART_NAME 1 +#define RENAMED_PART_NAME 2 +void create_partition_name(char *out, const char *in1, + const char *in2, uint name_variant, + bool translate); +void create_subpartition_name(char *out, const char *in1, + const char *in2, const char *in3, + uint name_variant); + +typedef struct st_lock_param_type +{ + TABLE_LIST table_list; + ulonglong copied; + ulonglong deleted; + THD *thd; + HA_CREATE_INFO *create_info; + Alter_info *alter_info; + TABLE *table; + KEY *key_info_buffer; + const char *db; + const char *table_name; + uchar *pack_frm_data; + enum thr_lock_type old_lock_type; + uint key_count; + uint db_options; + size_t pack_frm_len; + partition_info *part_info; +} ALTER_PARTITION_PARAM_TYPE; + +void mem_alloc_error(size_t size); + +enum ddl_log_entry_code +{ + /* + DDL_LOG_EXECUTE_CODE: + This is a code that indicates that this is a log entry to + be executed, from this entry a linked list of log entries + can be found and executed. + DDL_LOG_ENTRY_CODE: + An entry to be executed in a linked list from an execute log + entry. + DDL_IGNORE_LOG_ENTRY_CODE: + An entry that is to be ignored + */ + DDL_LOG_EXECUTE_CODE = 'e', + DDL_LOG_ENTRY_CODE = 'l', + DDL_IGNORE_LOG_ENTRY_CODE = 'i' +}; + +enum ddl_log_action_code +{ + /* + The type of action that a DDL_LOG_ENTRY_CODE entry is to + perform. + DDL_LOG_DELETE_ACTION: + Delete an entity + DDL_LOG_RENAME_ACTION: + Rename an entity + DDL_LOG_REPLACE_ACTION: + Rename an entity after removing the previous entry with the + new name, that is replace this entry. + */ + DDL_LOG_DELETE_ACTION = 'd', + DDL_LOG_RENAME_ACTION = 'r', + DDL_LOG_REPLACE_ACTION = 's' +}; + + +typedef struct st_ddl_log_entry +{ + const char *name; + const char *from_name; + const char *handler_name; + uint next_entry; + uint entry_pos; + enum ddl_log_entry_code entry_type; + enum ddl_log_action_code action_type; + /* + Most actions have only one phase. REPLACE does however have two + phases. The first phase removes the file with the new name if + there was one there before and the second phase renames the + old name to the new name. + */ + char phase; +} DDL_LOG_ENTRY; + +typedef struct st_ddl_log_memory_entry +{ + uint entry_pos; + struct st_ddl_log_memory_entry *next_log_entry; + struct st_ddl_log_memory_entry *prev_log_entry; + struct st_ddl_log_memory_entry *next_active_log_entry; +} DDL_LOG_MEMORY_ENTRY; + + +bool write_ddl_log_entry(DDL_LOG_ENTRY *ddl_log_entry, + DDL_LOG_MEMORY_ENTRY **active_entry); +bool write_execute_ddl_log_entry(uint first_entry, + bool complete, + DDL_LOG_MEMORY_ENTRY **active_entry); +bool deactivate_ddl_log_entry(uint entry_no); +void release_ddl_log_memory_entry(DDL_LOG_MEMORY_ENTRY *log_entry); +bool sync_ddl_log(); +void release_ddl_log(); +void execute_ddl_log_recovery(); +bool execute_ddl_log_entry(THD *thd, uint first_entry); + +extern pthread_mutex_t LOCK_gdl; + +#define WFRM_WRITE_SHADOW 1 +#define WFRM_INSTALL_SHADOW 2 +#define WFRM_PACK_FRM 4 +#define WFRM_KEEP_SHARE 8 +bool mysql_write_frm(ALTER_PARTITION_PARAM_TYPE *lpt, uint flags); +int abort_and_upgrade_lock(ALTER_PARTITION_PARAM_TYPE *lpt); +void close_open_tables_and_downgrade(ALTER_PARTITION_PARAM_TYPE *lpt); +void mysql_wait_completed_table(ALTER_PARTITION_PARAM_TYPE *lpt, TABLE *my_table); + +/* Functions to work with system tables. */ +bool open_system_tables_for_read(THD *thd, TABLE_LIST *table_list, + Open_tables_state *backup); +void close_system_tables(THD *thd, Open_tables_state *backup); +TABLE *open_system_table_for_update(THD *thd, TABLE_LIST *one_table); + +TABLE *open_performance_schema_table(THD *thd, TABLE_LIST *one_table, + Open_tables_state *backup); +void close_performance_schema_table(THD *thd, Open_tables_state *backup); + +bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool have_lock, + bool wait_for_refresh, bool wait_for_placeholders); +bool close_cached_connection_tables(THD *thd, bool wait_for_refresh, + LEX_STRING *connect_string, + bool have_lock = FALSE); +void copy_field_from_tmp_record(Field *field,int offset); +bool fill_record(THD *thd, Field **field, List &values, + bool ignore_errors); +bool fill_record_n_invoke_before_triggers(THD *thd, List &fields, + List &values, + bool ignore_errors, + Table_triggers_list *triggers, + enum trg_event_type event); +bool fill_record_n_invoke_before_triggers(THD *thd, Field **field, + List &values, + bool ignore_errors, + Table_triggers_list *triggers, + enum trg_event_type event); +OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild); + +inline TABLE_LIST *find_table_in_global_list(TABLE_LIST *table, + const char *db_name, + const char *table_name) +{ + return find_table_in_list(table, &TABLE_LIST::next_global, + db_name, table_name); +} + +inline TABLE_LIST *find_table_in_local_list(TABLE_LIST *table, + const char *db_name, + const char *table_name) +{ + return find_table_in_list(table, &TABLE_LIST::next_local, + db_name, table_name); +} + + +/* sql_calc.cc */ +bool eval_const_cond(COND *cond); + +/* sql_load.cc */ +int mysql_load(THD *thd, sql_exchange *ex, TABLE_LIST *table_list, + List &fields_vars, List &set_fields, + List &set_values_list, + enum enum_duplicates handle_duplicates, bool ignore, + bool local_file); +int write_record(THD *thd, TABLE *table, COPY_INFO *info); + +/* sql_manager.cc */ +extern bool volatile mqh_used; +void start_handle_manager(); +void stop_handle_manager(); +bool mysql_manager_submit(void (*action)()); + + +/* sql_test.cc */ +#ifndef DBUG_OFF +void print_where(COND *cond,const char *info, enum_query_type query_type); +void print_cached_tables(void); +void TEST_filesort(SORT_FIELD *sortorder,uint s_length); +void print_plan(JOIN* join,uint idx, double record_count, double read_time, + double current_read_time, const char *info); +#endif +void mysql_print_status(); +/* key.cc */ +int find_ref_key(KEY *key, uint key_count, uchar *record, Field *field, + uint *key_length, uint *keypart); +void key_copy(uchar *to_key, uchar *from_record, KEY *key_info, uint key_length); +void key_restore(uchar *to_record, uchar *from_key, KEY *key_info, + uint key_length); +bool key_cmp_if_same(TABLE *form,const uchar *key,uint index,uint key_length); +void key_unpack(String *to,TABLE *form,uint index); +bool is_key_used(TABLE *table, uint idx, const MY_BITMAP *fields); +int key_cmp(KEY_PART_INFO *key_part, const uchar *key, uint key_length); +extern "C" int key_rec_cmp(void *key_info, uchar *a, uchar *b); + +bool init_errmessage(void); +#endif /* MYSQL_SERVER */ +void sql_perror(const char *message); + +bool fn_format_relative_to_data_home(char * to, const char *name, + const char *dir, const char *extension); +#ifdef MYSQL_SERVER +File open_binlog(IO_CACHE *log, const char *log_file_name, + const char **errmsg); + +/* mysqld.cc */ +extern void MYSQLerror(const char*); +void refresh_status(THD *thd); +my_bool mysql_rm_tmp_tables(void); +void handle_connection_in_main_thread(THD *thd); +void create_thread_to_handle_connection(THD *thd); +void unlink_thd(THD *thd); +bool one_thread_per_connection_end(THD *thd, bool put_in_cache); +void flush_thread_cache(); + +/* item_func.cc */ +extern bool check_reserved_words(LEX_STRING *name); +extern enum_field_types agg_field_type(Item **items, uint nitems); + +/* strfunc.cc */ +ulonglong find_set(TYPELIB *lib, const char *x, uint length, CHARSET_INFO *cs, + char **err_pos, uint *err_len, bool *set_warning); +ulonglong find_set_from_flags(TYPELIB *lib, uint default_name, + ulonglong cur_set, ulonglong default_set, + const char *str, uint length, CHARSET_INFO *cs, + char **err_pos, uint *err_len, bool *set_warning); +uint find_type(const TYPELIB *lib, const char *find, uint length, + bool part_match); +uint find_type2(const TYPELIB *lib, const char *find, uint length, + CHARSET_INFO *cs); +void unhex_type2(TYPELIB *lib); +uint check_word(TYPELIB *lib, const char *val, const char *end, + const char **end_of_word); +int find_string_in_array(LEX_STRING * const haystack, LEX_STRING * const needle, + CHARSET_INFO * const cs); + + +bool is_keyword(const char *name, uint len); + +#define MY_DB_OPT_FILE "db.opt" +bool my_database_names_init(void); +void my_database_names_free(void); +bool check_db_dir_existence(const char *db_name); +bool load_db_opt(THD *thd, const char *path, HA_CREATE_INFO *create); +bool load_db_opt_by_name(THD *thd, const char *db_name, + HA_CREATE_INFO *db_create_info); +CHARSET_INFO *get_default_db_collation(THD *thd, const char *db_name); +bool my_dbopt_init(void); +void my_dbopt_cleanup(void); +extern int creating_database; // How many database locks are made +extern int creating_table; // How many mysql_create_table() are running + +/* + External variables +*/ + +extern time_t server_start_time, flush_status_time; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern uint mysql_data_home_len; + +extern MYSQL_PLUGIN_IMPORT char *mysql_data_home; +extern char server_version[SERVER_VERSION_LENGTH]; +extern MYSQL_PLUGIN_IMPORT char mysql_real_data_home[]; +extern char mysql_unpacked_real_data_home[]; + +extern CHARSET_INFO *character_set_filesystem; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern char *opt_mysql_tmpdir, mysql_charsets_dir[], + def_ft_boolean_syntax[sizeof(ft_boolean_syntax)]; +extern int mysql_unpacked_real_data_home_len; +#define mysql_tmpdir (my_tmpdir(&mysql_tmpdir_list)) +extern MYSQL_PLUGIN_IMPORT MY_TMPDIR mysql_tmpdir_list; +extern const LEX_STRING command_name[]; + +extern const char *first_keyword, *delayed_user, *binary_keyword; +extern MYSQL_PLUGIN_IMPORT const char *my_localhost; +extern MYSQL_PLUGIN_IMPORT const char **errmesg; /* Error messages */ + +extern const char *myisam_recover_options_str; +extern const char *in_left_expr_name, *in_additional_cond, *in_having_cond; +extern const char * const TRG_EXT; +extern const char * const TRN_EXT; +extern Eq_creator eq_creator; +extern Ne_creator ne_creator; +extern Gt_creator gt_creator; +extern Lt_creator lt_creator; +extern Ge_creator ge_creator; +extern Le_creator le_creator; +extern char language[FN_REFLEN]; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern MYSQL_PLUGIN_IMPORT char reg_ext[FN_EXTLEN]; +extern MYSQL_PLUGIN_IMPORT uint reg_ext_length; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern char glob_hostname[FN_REFLEN], mysql_home[FN_REFLEN]; +extern char pidfile_name[FN_REFLEN], system_time_zone[30], *opt_init_file; +extern char log_error_file[FN_REFLEN], *opt_tc_log_file; +extern ulonglong log_10_int[20]; +extern ulonglong keybuff_size; +extern ulonglong thd_startup_options; +extern ulong thread_id; +extern ulong binlog_cache_use, binlog_cache_disk_use; +extern ulong aborted_threads,aborted_connects; +extern ulong delayed_insert_timeout; +extern ulong delayed_insert_limit, delayed_queue_size; +extern ulong delayed_insert_threads, delayed_insert_writes; +extern ulong delayed_rows_in_use,delayed_insert_errors; +extern ulong slave_open_temp_tables; +extern ulong query_cache_size, query_cache_min_res_unit; +extern ulong slow_launch_threads, slow_launch_time; +extern ulong table_cache_size, table_def_size; +extern MYSQL_PLUGIN_IMPORT ulong max_connections; +extern ulong max_connect_errors, connect_timeout; +extern ulong slave_net_timeout, slave_trans_retries; +extern uint max_user_connections; +extern ulong what_to_log,flush_time; +extern ulong query_buff_size; +extern ulong max_prepared_stmt_count, prepared_stmt_count; +extern ulong binlog_cache_size, open_files_limit; +extern ulonglong max_binlog_cache_size; +extern ulong max_binlog_size, max_relay_log_size; +extern ulong opt_binlog_rows_event_max_size; +extern ulong rpl_recovery_rank, thread_cache_size, thread_pool_size; +extern ulong back_log; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern ulong MYSQL_PLUGIN_IMPORT specialflag; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern ulong current_pid; +extern ulong expire_logs_days, sync_binlog_period, sync_binlog_counter; +extern ulong opt_tc_log_size, tc_log_max_pages_used, tc_log_page_size; +extern ulong tc_log_page_waits; +extern my_bool relay_log_purge, opt_innodb_safe_binlog, opt_innodb; +extern uint test_flags,select_errors,ha_open_options; +extern uint protocol_version, mysqld_port, dropping_tables; +extern uint delay_key_write_options; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern MYSQL_PLUGIN_IMPORT uint lower_case_table_names; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern bool opt_endinfo, using_udf_functions; +extern my_bool locked_in_memory; +extern bool opt_using_transactions; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern MYSQL_PLUGIN_IMPORT bool mysqld_embedded; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern bool opt_large_files, server_id_supplied; +extern bool opt_update_log, opt_bin_log, opt_error_log; +extern my_bool opt_log, opt_slow_log; +extern ulong log_output_options; +extern my_bool opt_log_queries_not_using_indexes; +extern bool opt_disable_networking, opt_skip_show_db; +extern bool opt_ignore_builtin_innodb; +extern my_bool opt_character_set_client_handshake; +extern bool volatile abort_loop, shutdown_in_progress; +extern bool in_bootstrap; +extern uint volatile thread_count, thread_running, global_read_lock; +extern uint connection_count; +extern my_bool opt_sql_bin_update, opt_safe_user_create, opt_no_mix_types; +extern my_bool opt_safe_show_db, opt_local_infile, opt_myisam_use_mmap; +extern my_bool opt_slave_compressed_protocol, use_temp_pool; +extern ulong slave_exec_mode_options; +extern my_bool opt_readonly, lower_case_file_system; +extern my_bool opt_enable_named_pipe, opt_sync_frm, opt_allow_suspicious_udfs; +extern my_bool opt_secure_auth; +extern char* opt_secure_file_priv; +extern my_bool opt_log_slow_admin_statements, opt_log_slow_slave_statements; +extern my_bool sp_automatic_privileges, opt_noacl; +extern my_bool opt_old_style_user_limits, trust_function_creators; +extern uint opt_crash_binlog_innodb; +extern char *shared_memory_base_name, *mysqld_unix_port; +extern my_bool opt_enable_shared_memory; +extern char *default_tz_name; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern my_bool opt_large_pages; +extern uint opt_large_page_size; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern char *opt_logname, *opt_slow_logname; +extern const char *log_output_str; + +extern MYSQL_PLUGIN_IMPORT MYSQL_BIN_LOG mysql_bin_log; +extern LOGGER logger; +extern TABLE_LIST general_log, slow_log; +extern FILE *bootstrap_file; +extern int bootstrap_error; +extern FILE *stderror_file; +extern pthread_key(MEM_ROOT**,THR_MALLOC); +extern pthread_mutex_t LOCK_mysql_create_db,LOCK_Acl,LOCK_open, LOCK_lock_db, + LOCK_mapped_file,LOCK_user_locks, LOCK_status, + LOCK_error_log, LOCK_delayed_insert, LOCK_uuid_generator, + LOCK_delayed_status, LOCK_delayed_create, LOCK_crypt, LOCK_timezone, + LOCK_slave_list, LOCK_active_mi, LOCK_manager, LOCK_global_read_lock, + LOCK_global_system_variables, LOCK_user_conn, + LOCK_prepared_stmt_count, + LOCK_bytes_sent, LOCK_bytes_received, LOCK_connection_count; +extern MYSQL_PLUGIN_IMPORT pthread_mutex_t LOCK_thread_count; +#ifdef HAVE_OPENSSL +extern pthread_mutex_t LOCK_des_key_file; +#endif +extern pthread_mutex_t LOCK_server_started; +extern pthread_cond_t COND_server_started; +extern int mysqld_server_started; +extern rw_lock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave; +extern rw_lock_t LOCK_system_variables_hash; +extern pthread_cond_t COND_refresh, COND_thread_count, COND_manager; +extern pthread_cond_t COND_global_read_lock; +extern pthread_attr_t connection_attrib; +extern I_List threads; +extern I_List key_caches; +extern MY_BITMAP temp_pool; +extern String my_empty_string; +extern const String my_null_string; +extern SHOW_VAR status_vars[]; +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +extern MYSQL_PLUGIN_IMPORT struct system_variables global_system_variables; +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +extern struct system_variables max_system_variables; +extern struct system_status_var global_status_var; +extern struct rand_struct sql_rand; + +extern const char *opt_date_time_formats[]; +extern KNOWN_DATE_TIME_FORMAT known_date_time_formats[]; + +extern String null_string; +extern HASH open_cache, lock_db_cache; +extern TABLE *unused_tables; +extern const char* any_db; +extern struct my_option my_long_options[]; +extern const LEX_STRING view_type; +extern scheduler_functions thread_scheduler; +extern TYPELIB thread_handling_typelib; +extern uint8 uc_update_queries[SQLCOM_END+1]; +extern uint sql_command_flags[]; +extern TYPELIB log_output_typelib; + +/* optional things, have_* variables */ +extern SHOW_COMP_OPTION have_community_features; + +extern handlerton *partition_hton; +extern handlerton *myisam_hton; +extern handlerton *heap_hton; + +extern SHOW_COMP_OPTION have_ssl, have_symlink, have_dlopen; +extern SHOW_COMP_OPTION have_query_cache; +extern SHOW_COMP_OPTION have_geometry, have_rtree_keys; +extern SHOW_COMP_OPTION have_crypt; +extern SHOW_COMP_OPTION have_compress; + +extern int orig_argc; +extern char **orig_argv; +extern const char *load_default_groups[]; + +#ifndef __WIN__ +extern pthread_t signal_thread; +#endif + +#ifdef HAVE_OPENSSL +extern struct st_VioSSLFd * ssl_acceptor_fd; +#endif /* HAVE_OPENSSL */ + +MYSQL_LOCK *mysql_lock_tables(THD *thd, TABLE **table, uint count, + uint flags, bool *need_reopen); +/* mysql_lock_tables() and open_table() flags bits */ +#define MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK 0x0001 +#define MYSQL_LOCK_IGNORE_FLUSH 0x0002 +#define MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN 0x0004 +#define MYSQL_OPEN_TEMPORARY_ONLY 0x0008 +#define MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY 0x0010 +#define MYSQL_LOCK_PERF_SCHEMA 0x0020 + +void mysql_unlock_tables(THD *thd, MYSQL_LOCK *sql_lock); +void mysql_unlock_read_tables(THD *thd, MYSQL_LOCK *sql_lock); +void mysql_unlock_some_tables(THD *thd, TABLE **table,uint count); +void mysql_lock_remove(THD *thd, MYSQL_LOCK *locked,TABLE *table, + bool always_unlock); +void mysql_lock_abort(THD *thd, TABLE *table, bool upgrade_lock); +void mysql_lock_downgrade_write(THD *thd, TABLE *table, + thr_lock_type new_lock_type); +bool mysql_lock_abort_for_thread(THD *thd, TABLE *table); +MYSQL_LOCK *mysql_lock_merge(MYSQL_LOCK *a,MYSQL_LOCK *b); +TABLE_LIST *mysql_lock_have_duplicate(THD *thd, TABLE_LIST *needle, + TABLE_LIST *haystack); +bool lock_global_read_lock(THD *thd); +void unlock_global_read_lock(THD *thd); +bool wait_if_global_read_lock(THD *thd, bool abort_on_refresh, + bool is_not_commit); +void start_waiting_global_read_lock(THD *thd); +bool make_global_read_lock_block_commit(THD *thd); +bool set_protect_against_global_read_lock(void); +void unset_protect_against_global_read_lock(void); +void broadcast_refresh(void); + +/* Lock based on name */ +int lock_and_wait_for_table_name(THD *thd, TABLE_LIST *table_list); +int lock_table_name(THD *thd, TABLE_LIST *table_list, bool check_in_use); +void unlock_table_name(THD *thd, TABLE_LIST *table_list); +bool wait_for_locked_table_names(THD *thd, TABLE_LIST *table_list); +bool lock_table_names(THD *thd, TABLE_LIST *table_list); +void unlock_table_names(THD *thd, TABLE_LIST *table_list, + TABLE_LIST *last_table); +bool lock_table_names_exclusively(THD *thd, TABLE_LIST *table_list); +bool is_table_name_exclusively_locked_by_this_thread(THD *thd, + TABLE_LIST *table_list); +bool is_table_name_exclusively_locked_by_this_thread(THD *thd, uchar *key, + int key_length); + + +/* old unireg functions */ + +void unireg_init(ulong options); +void unireg_end(void) __attribute__((noreturn)); +bool mysql_create_frm(THD *thd, const char *file_name, + const char *db, const char *table, + HA_CREATE_INFO *create_info, + List &create_field, + uint key_count,KEY *key_info,handler *db_type); +int rea_create_table(THD *thd, const char *path, + const char *db, const char *table_name, + HA_CREATE_INFO *create_info, + List &create_field, + uint key_count,KEY *key_info, + handler *file); +int format_number(uint inputflag,uint max_length,char * pos,uint length, + char * *errpos); + +/* table.cc */ +TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key, + uint key_length); +void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key, + uint key_length, + const char *table_name, const char *path); +void free_table_share(TABLE_SHARE *share); +int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags); +void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg); +int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, + uint db_stat, uint prgflag, uint ha_open_flags, + TABLE *outparam, bool is_create_table); +int readfrm(const char *name, uchar **data, size_t *length); +int writefrm(const char* name, const uchar* data, size_t len); +int closefrm(TABLE *table, bool free_share); +int read_string(File file, uchar* *to, size_t length); +void free_blobs(TABLE *table); +void free_field_buffers_larger_than(TABLE *table, uint32 size); +int set_zone(int nr,int min_zone,int max_zone); +ulong convert_period_to_month(ulong period); +ulong convert_month_to_period(ulong month); +void get_date_from_daynr(long daynr,uint *year, uint *month, + uint *day); +my_time_t TIME_to_timestamp(THD *thd, const MYSQL_TIME *t, my_bool *not_exist); +bool str_to_time_with_warn(const char *str,uint length,MYSQL_TIME *l_time); +timestamp_type str_to_datetime_with_warn(const char *str, uint length, + MYSQL_TIME *l_time, uint flags); +void localtime_to_TIME(MYSQL_TIME *to, struct tm *from); +void calc_time_from_sec(MYSQL_TIME *to, long seconds, long microseconds); + +void make_truncated_value_warning(THD *thd, MYSQL_ERROR::enum_warning_level level, + const char *str_val, + uint str_length, timestamp_type time_type, + const char *field_name); + +bool date_add_interval(MYSQL_TIME *ltime, interval_type int_type, INTERVAL interval); +bool calc_time_diff(MYSQL_TIME *l_time1, MYSQL_TIME *l_time2, int l_sign, + longlong *seconds_out, long *microseconds_out); + +extern LEX_STRING interval_type_to_name[]; + +extern DATE_TIME_FORMAT *date_time_format_make(timestamp_type format_type, + const char *format_str, + uint format_length); +extern DATE_TIME_FORMAT *date_time_format_copy(THD *thd, + DATE_TIME_FORMAT *format); +const char *get_date_time_format_str(KNOWN_DATE_TIME_FORMAT *format, + timestamp_type type); +extern bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time, + timestamp_type type, String *str); +void make_datetime(const DATE_TIME_FORMAT *format, const MYSQL_TIME *l_time, + String *str); +void make_date(const DATE_TIME_FORMAT *format, const MYSQL_TIME *l_time, + String *str); +void make_time(const DATE_TIME_FORMAT *format, const MYSQL_TIME *l_time, + String *str); +int my_time_compare(MYSQL_TIME *a, MYSQL_TIME *b); +longlong get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg, + Item *warn_item, bool *is_null); + +int test_if_number(char *str,int *res,bool allow_wildcards); +void change_byte(uchar *,uint,char,char); +void init_read_record(READ_RECORD *info, THD *thd, TABLE *reg_form, + SQL_SELECT *select, int use_record_cache, + bool print_errors, bool disable_rr_cache); +void init_read_record_idx(READ_RECORD *info, THD *thd, TABLE *table, + bool print_error, uint idx); +void end_read_record(READ_RECORD *info); +ha_rows filesort(THD *thd, TABLE *form,struct st_sort_field *sortorder, + uint s_length, SQL_SELECT *select, + ha_rows max_rows, bool sort_positions, + ha_rows *examined_rows); +void filesort_free_buffers(TABLE *table, bool full); +void change_double_for_sort(double nr,uchar *to); +double my_double_round(double value, longlong dec, bool dec_unsigned, + bool truncate); +int get_quick_record(SQL_SELECT *select); + +int calc_weekday(long daynr,bool sunday_first_day_of_week); +uint calc_week(MYSQL_TIME *l_time, uint week_behaviour, uint *year); +void find_date(char *pos,uint *vek,uint flag); +TYPELIB *convert_strings_to_array_type(char * *typelibs, char * *end); +TYPELIB *typelib(MEM_ROOT *mem_root, List &strings); +ulong get_form_pos(File file, uchar *head, TYPELIB *save_names); +ulong make_new_entry(File file,uchar *fileinfo,TYPELIB *formnames, + const char *newname); +ulong next_io_size(ulong pos); +void append_unescaped(String *res, const char *pos, uint length); +int create_frm(THD *thd, const char *name, const char *db, const char *table, + uint reclength, uchar *fileinfo, + HA_CREATE_INFO *create_info, uint keys); +void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form); +int rename_file_ext(const char * from,const char * to,const char * ext); +bool check_db_name(LEX_STRING *db); +bool check_column_name(const char *name); +bool check_table_name(const char *name, uint length); +char *get_field(MEM_ROOT *mem, Field *field); +bool get_field(MEM_ROOT *mem, Field *field, class String *res); +int wild_case_compare(CHARSET_INFO *cs, const char *str,const char *wildstr); +char *fn_rext(char *name); + +/* Conversion functions */ +#endif /* MYSQL_SERVER */ +#if defined MYSQL_SERVER || defined INNODB_COMPATIBILITY_HOOKS +uint strconvert(CHARSET_INFO *from_cs, const char *from, + CHARSET_INFO *to_cs, char *to, uint to_length, uint *errors); +/* depends on errmsg.txt Database `db`, Table `t` ... */ +#define EXPLAIN_FILENAME_MAX_EXTRA_LENGTH 63 +enum enum_explain_filename_mode +{ + EXPLAIN_ALL_VERBOSE= 0, + EXPLAIN_PARTITIONS_VERBOSE, + EXPLAIN_PARTITIONS_AS_COMMENT, + EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING +}; +uint explain_filename(const char *from, char *to, uint to_length, + enum_explain_filename_mode explain_mode); +uint filename_to_tablename(const char *from, char *to, uint to_length); +uint tablename_to_filename(const char *from, char *to, uint to_length); +uint check_n_cut_mysql50_prefix(const char *from, char *to, uint to_length); +#endif /* MYSQL_SERVER || INNODB_COMPATIBILITY_HOOKS */ +#ifdef MYSQL_SERVER +uint build_table_filename(char *buff, size_t bufflen, const char *db, + const char *table, const char *ext, uint flags); +const char *get_canonical_filename(handler *file, const char *path, + char *tmp_path); + +#define MYSQL50_TABLE_NAME_PREFIX "#mysql50#" +#define MYSQL50_TABLE_NAME_PREFIX_LENGTH 9 + +uint build_table_shadow_filename(char *buff, size_t bufflen, + ALTER_PARTITION_PARAM_TYPE *lpt); +/* Flags for conversion functions. */ +#define FN_FROM_IS_TMP (1 << 0) +#define FN_TO_IS_TMP (1 << 1) +#define FN_IS_TMP (FN_FROM_IS_TMP | FN_TO_IS_TMP) +#define NO_FRM_RENAME (1 << 2) +#define FRM_ONLY (1 << 3) + +/* from hostname.cc */ +struct in_addr; +char * ip_to_hostname(struct in_addr *in,uint *errors); +void inc_host_errors(struct in_addr *in); +void reset_host_errors(struct in_addr *in); +bool hostname_cache_init(); +void hostname_cache_free(); +void hostname_cache_refresh(void); + +/* sql_cache.cc */ +extern bool sql_cache_init(); +extern void sql_cache_free(); +extern int sql_cache_hit(THD *thd, char *inBuf, uint length); + +/* item_func.cc */ +Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name, + LEX_STRING component); +int get_var_with_binlog(THD *thd, enum_sql_command sql_command, + LEX_STRING &name, user_var_entry **out_entry); +/* log.cc */ +bool flush_error_log(void); + +/* sql_list.cc */ +void free_list(I_List *list); +void free_list(I_List *list); + +/* sql_yacc.cc */ +#ifndef DBUG_OFF +extern void turn_parser_debug_on(); +#endif + +/* frm_crypt.cc */ +#ifdef HAVE_CRYPTED_FRM +SQL_CRYPT *get_crypt_for_frm(void); +#endif + +/* password.c */ +extern "C" void my_make_scrambled_password_323(char *to, const char *password, + size_t pass_len); +extern "C" void my_make_scrambled_password(char *to, const char *password, + size_t pass_len); + +#include "sql_view.h" + +/* Some inline functions for more speed */ + +inline bool add_item_to_list(THD *thd, Item *item) +{ + return thd->lex->current_select->add_item_to_list(thd, item); +} + +inline bool add_value_to_list(THD *thd, Item *value) +{ + return thd->lex->value_list.push_back(value); +} + +inline bool add_order_to_list(THD *thd, Item *item, bool asc) +{ + return thd->lex->current_select->add_order_to_list(thd, item, asc); +} + +inline bool add_group_to_list(THD *thd, Item *item, bool asc) +{ + return thd->lex->current_select->add_group_to_list(thd, item, asc); +} + +inline void mark_as_null_row(TABLE *table) +{ + table->null_row=1; + table->status|=STATUS_NULL_ROW; + bfill(table->null_flags,table->s->null_bytes,255); +} + +inline void table_case_convert(char * name, uint length) +{ + if (lower_case_table_names) + files_charset_info->cset->casedn(files_charset_info, + name, length, name, length); +} + +inline const char *table_case_name(HA_CREATE_INFO *info, const char *name) +{ + return ((lower_case_table_names == 2 && info->alias) ? info->alias : name); +} + +inline ulong sql_rnd_with_mutex() +{ + pthread_mutex_lock(&LOCK_thread_count); + ulong tmp=(ulong) (my_rnd(&sql_rand) * 0xffffffff); /* make all bits random */ + pthread_mutex_unlock(&LOCK_thread_count); + return tmp; +} + +Comp_creator *comp_eq_creator(bool invert); +Comp_creator *comp_ge_creator(bool invert); +Comp_creator *comp_gt_creator(bool invert); +Comp_creator *comp_le_creator(bool invert); +Comp_creator *comp_lt_creator(bool invert); +Comp_creator *comp_ne_creator(bool invert); + +Item * all_any_subquery_creator(Item *left_expr, + chooser_compare_func_creator cmp, + bool all, + SELECT_LEX *select_lex); + +/** + clean/setup table fields and map. + + @param table TABLE structure pointer (which should be setup) + @param table_list TABLE_LIST structure pointer (owner of TABLE) + @param tablenr table number +*/ + + +inline void setup_table_map(TABLE *table, TABLE_LIST *table_list, uint tablenr) +{ + table->used_fields= 0; + table->const_table= 0; + table->null_row= 0; + table->status= STATUS_NO_RECORD; + table->maybe_null= table_list->outer_join; + TABLE_LIST *embedding= table_list->embedding; + while (!table->maybe_null && embedding) + { + table->maybe_null= embedding->outer_join; + embedding= embedding->embedding; + } + table->tablenr= tablenr; + table->map= (table_map) 1 << tablenr; + table->force_index= table_list->force_index; + table->covering_keys= table->s->keys_for_keyread; + table->merge_keys.clear_all(); +} + + +/** + convert a hex digit into number. +*/ + +inline int hexchar_to_int(char c) +{ + if (c <= '9' && c >= '0') + return c-'0'; + c|=32; + if (c <= 'f' && c >= 'a') + return c-'a'+10; + return -1; +} + +/** + return true if the table was created explicitly. +*/ +inline bool is_user_table(TABLE * table) +{ + const char *name= table->s->table_name.str; + return strncmp(name, tmp_file_prefix, tmp_file_prefix_length); +} + +/* + Some functions that are different in the embedded library and the normal + server +*/ + +#ifndef EMBEDDED_LIBRARY +extern "C" void unireg_abort(int exit_code) __attribute__((noreturn)); +void kill_delayed_threads(void); +bool check_stack_overrun(THD *thd, long margin, uchar *dummy); +#else +extern "C" void unireg_clear(int exit_code); +#define unireg_abort(exit_code) do { unireg_clear(exit_code); DBUG_RETURN(exit_code); } while(0) +inline void kill_delayed_threads(void) {} +#define check_stack_overrun(A, B, C) 0 +#endif + +/* Used by handlers to store things in schema tables */ +#define IS_FILES_FILE_ID 0 +#define IS_FILES_FILE_NAME 1 +#define IS_FILES_FILE_TYPE 2 +#define IS_FILES_TABLESPACE_NAME 3 +#define IS_FILES_TABLE_CATALOG 4 +#define IS_FILES_TABLE_SCHEMA 5 +#define IS_FILES_TABLE_NAME 6 +#define IS_FILES_LOGFILE_GROUP_NAME 7 +#define IS_FILES_LOGFILE_GROUP_NUMBER 8 +#define IS_FILES_ENGINE 9 +#define IS_FILES_FULLTEXT_KEYS 10 +#define IS_FILES_DELETED_ROWS 11 +#define IS_FILES_UPDATE_COUNT 12 +#define IS_FILES_FREE_EXTENTS 13 +#define IS_FILES_TOTAL_EXTENTS 14 +#define IS_FILES_EXTENT_SIZE 15 +#define IS_FILES_INITIAL_SIZE 16 +#define IS_FILES_MAXIMUM_SIZE 17 +#define IS_FILES_AUTOEXTEND_SIZE 18 +#define IS_FILES_CREATION_TIME 19 +#define IS_FILES_LAST_UPDATE_TIME 20 +#define IS_FILES_LAST_ACCESS_TIME 21 +#define IS_FILES_RECOVER_TIME 22 +#define IS_FILES_TRANSACTION_COUNTER 23 +#define IS_FILES_VERSION 24 +#define IS_FILES_ROW_FORMAT 25 +#define IS_FILES_TABLE_ROWS 26 +#define IS_FILES_AVG_ROW_LENGTH 27 +#define IS_FILES_DATA_LENGTH 28 +#define IS_FILES_MAX_DATA_LENGTH 29 +#define IS_FILES_INDEX_LENGTH 30 +#define IS_FILES_DATA_FREE 31 +#define IS_FILES_CREATE_TIME 32 +#define IS_FILES_UPDATE_TIME 33 +#define IS_FILES_CHECK_TIME 34 +#define IS_FILES_CHECKSUM 35 +#define IS_FILES_STATUS 36 +#define IS_FILES_EXTRA 37 +void init_fill_schema_files_row(TABLE* table); +bool schema_table_store_record(THD *thd, TABLE *table); + +/* sql/item_create.cc */ +int item_create_init(); +void item_create_cleanup(); + +bool show_create_trigger(THD *thd, const sp_name *trg_name); + +inline void lex_string_set(LEX_STRING *lex_str, const char *c_str) +{ + lex_str->str= (char *) c_str; + lex_str->length= strlen(c_str); +} + +bool load_charset(MEM_ROOT *mem_root, + Field *field, + CHARSET_INFO *dflt_cs, + CHARSET_INFO **cs); + +bool load_collation(MEM_ROOT *mem_root, + Field *field, + CHARSET_INFO *dflt_cl, + CHARSET_INFO **cl); + +#endif /* MYSQL_SERVER */ +extern "C" int test_if_data_home_dir(const char *dir); + +#endif /* MYSQL_CLIENT */ + +#endif /* MYSQL_PRIV_H */ diff --git a/dbcon/mysql/mysqld.cc b/dbcon/mysql/mysqld.cc new file mode 100644 index 00000000..d44f1881 --- /dev/null +++ b/dbcon/mysql/mysqld.cc @@ -0,0 +1,8958 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#include "mysql_priv.h" +#include +#include +#include +#include "slave.h" +#include "rpl_mi.h" +#include "sql_repl.h" +#include "rpl_filter.h" +#include "repl_failsafe.h" +#include +#include "mysqld_suffix.h" +#include "mysys_err.h" +#include "events.h" + +#include "../storage/myisam/ha_myisam.h" + +#include "rpl_injector.h" + +#ifdef HAVE_SYS_PRCTL_H +#include +#endif + +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE +#if defined(NOT_ENOUGH_TESTED) \ + && defined(NDB_SHM_TRANSPORTER) && MYSQL_VERSION_ID >= 50000 +#define OPT_NDB_SHM_DEFAULT 1 +#else +#define OPT_NDB_SHM_DEFAULT 0 +#endif +#endif + +#ifndef DEFAULT_SKIP_THREAD_PRIORITY +#define DEFAULT_SKIP_THREAD_PRIORITY 0 +#endif + +#include +#include +#include +#include "sp_rcontext.h" +#include "sp_cache.h" + +#define mysqld_charset &my_charset_latin1 + +#ifdef HAVE_purify +#define IF_PURIFY(A,B) (A) +#else +#define IF_PURIFY(A,B) (B) +#endif + +#if SIZEOF_CHARP == 4 +#define MAX_MEM_TABLE_SIZE ~(ulong) 0 +#else +#define MAX_MEM_TABLE_SIZE ~(ulonglong) 0 +#endif + +/* stack traces are only supported on linux intel */ +#if defined(__linux__) && defined(__i386__) && defined(USE_PSTACK) +#define HAVE_STACK_TRACE_ON_SEGV +#include "../pstack/pstack.h" +char pstack_file_name[80]; +#endif /* __linux__ */ + +/* We have HAVE_purify below as this speeds up the shutdown of MySQL */ + +#if defined(HAVE_DEC_3_2_THREADS) || defined(SIGNALS_DONT_BREAK_READ) || defined(HAVE_purify) && defined(__linux__) +#define HAVE_CLOSE_SERVER_SOCK 1 +#endif + +extern "C" { // Because of SCO 3.2V4.2 +#include +#include +#ifndef __GNU_LIBRARY__ +#define __GNU_LIBRARY__ // Skip warnings in getopt.h +#endif +#include +#ifdef HAVE_SYSENT_H +#include +#endif +#ifdef HAVE_PWD_H +#include // For getpwent +#endif +#ifdef HAVE_GRP_H +#include +#endif +#include + +#if !defined(__WIN__) +# ifndef __NETWARE__ +#include +# endif /* __NETWARE__ */ +#ifdef HAVE_SYS_UN_H +# include +#endif +#include +#ifdef HAVE_SELECT_H +# include +#endif +#ifdef HAVE_SYS_SELECT_H +#include +#endif +#include +#endif /* __WIN__ */ + +#include + +#ifdef HAVE_SYS_MMAN_H +#include +#endif + +#ifdef __WIN__ +#include +#define SIGNAL_FMT "exception 0x%x" +#else +#define SIGNAL_FMT "signal %d" +#endif + +#ifdef __NETWARE__ +#define zVOLSTATE_ACTIVE 6 +#define zVOLSTATE_DEACTIVE 2 +#define zVOLSTATE_MAINTENANCE 3 + +#undef __event_h__ +#include <../include/event.h> +/* + This #undef exists here because both libc of NetWare and MySQL have + files named event.h which causes compilation errors. +*/ + +#include +#include +#include +#include +#include //For NEB +#include //For NEB +#include //For NEB +#include //For NSS event structures +#include + +static void *neb_consumer_id= NULL; //For storing NEB consumer id +static char datavolname[256]= {0}; +static VolumeID_t datavolid; +static event_handle_t eh; +static Report_t ref; +static void *refneb= NULL; +my_bool event_flag= FALSE; +static int volumeid= -1; + + /* NEB event callback */ +unsigned long neb_event_callback(struct EventBlock *eblock); +static void registerwithneb(); +static void getvolumename(); +static void getvolumeID(BYTE *volumeName); +#endif /* __NETWARE__ */ + + +#ifdef _AIX41 +int initgroups(const char *,unsigned int); +#endif + +#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H) +#include +#ifdef HAVE_FP_EXCEPT // Fix type conflict +typedef fp_except fp_except_t; +#endif +#endif /* __FreeBSD__ && HAVE_IEEEFP_H */ +#ifdef HAVE_SYS_FPU_H +/* for IRIX to use set_fpc_csr() */ +#include +#endif + +inline void setup_fpu() +{ +#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H) + /* We can't handle floating point exceptions with threads, so disable + this on freebsd + Don't fall for overflow, underflow,divide-by-zero or loss of precision + */ +#if defined(__i386__) + fpsetmask(~(FP_X_INV | FP_X_DNML | FP_X_OFL | FP_X_UFL | FP_X_DZ | + FP_X_IMP)); +#else + fpsetmask(~(FP_X_INV | FP_X_OFL | FP_X_UFL | FP_X_DZ | + FP_X_IMP)); +#endif /* __i386__ */ +#endif /* __FreeBSD__ && HAVE_IEEEFP_H */ + +#ifdef HAVE_FESETROUND + /* Set FPU rounding mode to "round-to-nearest" */ + fesetround(FE_TONEAREST); +#endif /* HAVE_FESETROUND */ + +#if defined(__sgi) && defined(HAVE_SYS_FPU_H) + /* Enable denormalized DOUBLE values support for IRIX */ + union fpc_csr n; + n.fc_word = get_fpc_csr(); + n.fc_struct.flush = 0; + set_fpc_csr(n.fc_word); +#endif +} + +} /* cplusplus */ + +#define MYSQL_KILL_SIGNAL SIGTERM + +#ifdef HAVE_GLIBC2_STYLE_GETHOSTBYNAME_R +#include +#else +#include // For thr_setconcurency() +#endif + +#ifdef SOLARIS +extern "C" int gethostname(char *name, int namelen); +#endif + +extern "C" sig_handler handle_segfault(int sig); + +#if defined(__linux__) +#define ENABLE_TEMP_POOL 1 +#else +#define ENABLE_TEMP_POOL 0 +#endif + +/* Constants */ + +const char *show_comp_option_name[]= {"YES", "NO", "DISABLED"}; +/* + WARNING: When adding new SQL modes don't forget to update the + tables definitions that stores it's value. + (ie: mysql.event, mysql.proc) +*/ +static const char *sql_mode_names[]= +{ + "REAL_AS_FLOAT", "PIPES_AS_CONCAT", "ANSI_QUOTES", "IGNORE_SPACE", + "?", "ONLY_FULL_GROUP_BY", "NO_UNSIGNED_SUBTRACTION", + "NO_DIR_IN_CREATE", + "POSTGRESQL", "ORACLE", "MSSQL", "DB2", "MAXDB", "NO_KEY_OPTIONS", + "NO_TABLE_OPTIONS", "NO_FIELD_OPTIONS", "MYSQL323", "MYSQL40", "ANSI", + "NO_AUTO_VALUE_ON_ZERO", "NO_BACKSLASH_ESCAPES", "STRICT_TRANS_TABLES", + "STRICT_ALL_TABLES", + "NO_ZERO_IN_DATE", "NO_ZERO_DATE", "ALLOW_INVALID_DATES", + "ERROR_FOR_DIVISION_BY_ZERO", + "TRADITIONAL", "NO_AUTO_CREATE_USER", "HIGH_NOT_PRECEDENCE", + "NO_ENGINE_SUBSTITUTION", + "PAD_CHAR_TO_FULL_LENGTH", + NullS +}; + +static const unsigned int sql_mode_names_len[]= +{ + /*REAL_AS_FLOAT*/ 13, + /*PIPES_AS_CONCAT*/ 15, + /*ANSI_QUOTES*/ 11, + /*IGNORE_SPACE*/ 12, + /*?*/ 1, + /*ONLY_FULL_GROUP_BY*/ 18, + /*NO_UNSIGNED_SUBTRACTION*/ 23, + /*NO_DIR_IN_CREATE*/ 16, + /*POSTGRESQL*/ 10, + /*ORACLE*/ 6, + /*MSSQL*/ 5, + /*DB2*/ 3, + /*MAXDB*/ 5, + /*NO_KEY_OPTIONS*/ 14, + /*NO_TABLE_OPTIONS*/ 16, + /*NO_FIELD_OPTIONS*/ 16, + /*MYSQL323*/ 8, + /*MYSQL40*/ 7, + /*ANSI*/ 4, + /*NO_AUTO_VALUE_ON_ZERO*/ 21, + /*NO_BACKSLASH_ESCAPES*/ 20, + /*STRICT_TRANS_TABLES*/ 19, + /*STRICT_ALL_TABLES*/ 17, + /*NO_ZERO_IN_DATE*/ 15, + /*NO_ZERO_DATE*/ 12, + /*ALLOW_INVALID_DATES*/ 19, + /*ERROR_FOR_DIVISION_BY_ZERO*/ 26, + /*TRADITIONAL*/ 11, + /*NO_AUTO_CREATE_USER*/ 19, + /*HIGH_NOT_PRECEDENCE*/ 19, + /*NO_ENGINE_SUBSTITUTION*/ 22, + /*PAD_CHAR_TO_FULL_LENGTH*/ 23 +}; + +TYPELIB sql_mode_typelib= { array_elements(sql_mode_names)-1,"", + sql_mode_names, + (unsigned int *)sql_mode_names_len }; + +static const char *optimizer_switch_names[]= +{ + "index_merge","index_merge_union","index_merge_sort_union", + "index_merge_intersection", "default", NullS +}; +/* Corresponding defines are named OPTIMIZER_SWITCH_XXX */ +static const unsigned int optimizer_switch_names_len[]= +{ + sizeof("index_merge") - 1, + sizeof("index_merge_union") - 1, + sizeof("index_merge_sort_union") - 1, + sizeof("index_merge_intersection") - 1, + sizeof("default") - 1 +}; +TYPELIB optimizer_switch_typelib= { array_elements(optimizer_switch_names)-1,"", + optimizer_switch_names, + (unsigned int *)optimizer_switch_names_len }; + +static const char *tc_heuristic_recover_names[]= +{ + "COMMIT", "ROLLBACK", NullS +}; +static TYPELIB tc_heuristic_recover_typelib= +{ + array_elements(tc_heuristic_recover_names)-1,"", + tc_heuristic_recover_names, NULL +}; + +static const char *thread_handling_names[]= +{ "one-thread-per-connection", "no-threads", +#if HAVE_POOL_OF_THREADS == 1 + "pool-of-threads", +#endif + NullS}; + +TYPELIB thread_handling_typelib= +{ + array_elements(thread_handling_names) - 1, "", + thread_handling_names, NULL +}; + +const char *first_keyword= "first", *binary_keyword= "BINARY"; +const char *my_localhost= "localhost", *delayed_user= "DELAYED"; +#if SIZEOF_OFF_T > 4 && defined(BIG_TABLES) +#define GET_HA_ROWS GET_ULL +#else +#define GET_HA_ROWS GET_ULONG +#endif + +bool opt_large_files= sizeof(my_off_t) > 4; + +/* + Used with --help for detailed option +*/ +static my_bool opt_help= 0, opt_verbose= 0; + +arg_cmp_func Arg_comparator::comparator_matrix[5][2] = +{{&Arg_comparator::compare_string, &Arg_comparator::compare_e_string}, + {&Arg_comparator::compare_real, &Arg_comparator::compare_e_real}, + {&Arg_comparator::compare_int_signed, &Arg_comparator::compare_e_int}, + {&Arg_comparator::compare_row, &Arg_comparator::compare_e_row}, + {&Arg_comparator::compare_decimal, &Arg_comparator::compare_e_decimal}}; + +const char *log_output_names[] = { "NONE", "FILE", "TABLE", NullS}; +static const unsigned int log_output_names_len[]= { 4, 4, 5, 0 }; +TYPELIB log_output_typelib= {array_elements(log_output_names)-1,"", + log_output_names, + (unsigned int *) log_output_names_len}; + +/* static variables */ + +/* the default log output is log tables */ +static bool lower_case_table_names_used= 0; +static bool volatile select_thread_in_use, signal_thread_in_use; +static bool volatile ready_to_exit; +static my_bool opt_debugging= 0, opt_external_locking= 0, opt_console= 0; +static my_bool opt_short_log_format= 0; +static uint kill_cached_threads, wake_thread; +static ulong killed_threads, thread_created; +static ulong max_used_connections; +static ulong my_bind_addr; /**< the address we bind to */ +static volatile ulong cached_thread_count= 0; +static const char *sql_mode_str= "OFF"; +/* Text representation for OPTIMIZER_SWITCH_DEFAULT */ +static const char *optimizer_switch_str="index_merge=on,index_merge_union=on," + "index_merge_sort_union=on," + "index_merge_intersection=on"; +static char *mysqld_user, *mysqld_chroot, *log_error_file_ptr; +static char *opt_init_slave, *language_ptr, *opt_init_connect; +static char *default_character_set_name; +static char *character_set_filesystem_name; +static char *lc_time_names_name; +static char *my_bind_addr_str; +static char *default_collation_name; +static char *default_storage_engine_str; +static char compiled_default_collation_name[]= MYSQL_DEFAULT_COLLATION_NAME; +static I_List thread_cache; +static double long_query_time; + +static pthread_cond_t COND_thread_cache, COND_flush_thread_cache; + +/* Global variables */ + +bool opt_update_log, opt_bin_log, opt_ignore_builtin_innodb= 0; +my_bool opt_log, opt_slow_log; +ulong log_output_options; +my_bool opt_log_queries_not_using_indexes= 0; +bool opt_error_log= IF_WIN(1,0); +bool opt_disable_networking=0, opt_skip_show_db=0; +my_bool opt_character_set_client_handshake= 1; +bool server_id_supplied = 0; +bool opt_endinfo, using_udf_functions; +my_bool locked_in_memory; +bool opt_using_transactions; +bool volatile abort_loop; +bool volatile shutdown_in_progress; +/* + True if the bootstrap thread is running. Protected by LOCK_thread_count, + just like thread_count. + Used in bootstrap() function to determine if the bootstrap thread + has completed. Note, that we can't use 'thread_count' instead, + since in 5.1, in presence of the Event Scheduler, there may be + event threads running in parallel, so it's impossible to know + what value of 'thread_count' is a sign of completion of the + bootstrap thread. + + At the same time, we can't start the event scheduler after + bootstrap either, since we want to be able to process event-related + SQL commands in the init file and in --bootstrap mode. +*/ +bool in_bootstrap= FALSE; +/** + @brief 'grant_option' is used to indicate if privileges needs + to be checked, in which case the lock, LOCK_grant, is used + to protect access to the grant table. + @note This flag is dropped in 5.1 + @see grant_init() + */ +bool volatile grant_option; + +my_bool opt_skip_slave_start = 0; ///< If set, slave is not autostarted +my_bool opt_reckless_slave = 0; +my_bool opt_enable_named_pipe= 0; +my_bool opt_local_infile, opt_slave_compressed_protocol; +my_bool opt_safe_user_create = 0, opt_no_mix_types = 0; +my_bool opt_show_slave_auth_info, opt_sql_bin_update = 0; +my_bool opt_log_slave_updates= 0; +bool slave_warning_issued = false; + +/* + Legacy global handlerton. These will be removed (please do not add more). +*/ +handlerton *heap_hton; +handlerton *myisam_hton; +handlerton *partition_hton; + +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE +const char *opt_ndbcluster_connectstring= 0; +const char *opt_ndb_connectstring= 0; +char opt_ndb_constrbuf[1024]= {0}; +unsigned opt_ndb_constrbuf_len= 0; +my_bool opt_ndb_shm, opt_ndb_optimized_node_selection; +ulong opt_ndb_cache_check_time; +const char *opt_ndb_mgmd; +ulong opt_ndb_nodeid; +ulong ndb_extra_logging; +#ifdef HAVE_NDB_BINLOG +ulong ndb_report_thresh_binlog_epoch_slip; +ulong ndb_report_thresh_binlog_mem_usage; +#endif + +extern const char *ndb_distribution_names[]; +extern TYPELIB ndb_distribution_typelib; +extern const char *opt_ndb_distribution; +extern enum ndb_distribution opt_ndb_distribution_id; +#endif +my_bool opt_readonly, use_temp_pool, relay_log_purge; +my_bool opt_sync_frm, opt_allow_suspicious_udfs; +my_bool opt_secure_auth= 0; +char* opt_secure_file_priv= 0; +my_bool opt_log_slow_admin_statements= 0; +my_bool opt_log_slow_slave_statements= 0; +my_bool lower_case_file_system= 0; +my_bool opt_large_pages= 0; +my_bool opt_myisam_use_mmap= 0; +uint opt_large_page_size= 0; +my_bool opt_old_style_user_limits= 0, trust_function_creators= 0; +/* + True if there is at least one per-hour limit for some user, so we should + check them before each query (and possibly reset counters when hour is + changed). False otherwise. +*/ +volatile bool mqh_used = 0; +my_bool opt_noacl; +my_bool sp_automatic_privileges= 1; + +ulong opt_binlog_rows_event_max_size; +const char *binlog_format_names[]= {"MIXED", "STATEMENT", "ROW", NullS}; +TYPELIB binlog_format_typelib= + { array_elements(binlog_format_names) - 1, "", + binlog_format_names, NULL }; +ulong opt_binlog_format_id= (ulong) BINLOG_FORMAT_UNSPEC; +const char *opt_binlog_format= binlog_format_names[opt_binlog_format_id]; +#ifdef HAVE_INITGROUPS +static bool calling_initgroups= FALSE; /**< Used in SIGSEGV handler. */ +#endif +uint mysqld_port, test_flags, select_errors, dropping_tables, ha_open_options; +uint mysqld_port_timeout; +uint delay_key_write_options, protocol_version; +uint lower_case_table_names; +uint tc_heuristic_recover= 0; +uint volatile thread_count, thread_running; +ulonglong thd_startup_options; +ulong back_log, connect_timeout, concurrency, server_id; +ulong table_cache_size, table_def_size; +ulong what_to_log; +ulong query_buff_size, slow_launch_time, slave_open_temp_tables; +ulong open_files_limit, max_binlog_size, max_relay_log_size; +ulong slave_net_timeout, slave_trans_retries; +ulong slave_exec_mode_options; +const char *slave_exec_mode_str= "STRICT"; +ulong thread_cache_size=0, thread_pool_size= 0; +ulong binlog_cache_size=0; +ulonglong max_binlog_cache_size=0; +ulong query_cache_size=0; +ulong refresh_version; /* Increments on each reload */ +query_id_t global_query_id; +ulong aborted_threads, aborted_connects; +ulong delayed_insert_timeout, delayed_insert_limit, delayed_queue_size; +ulong delayed_insert_threads, delayed_insert_writes, delayed_rows_in_use; +ulong delayed_insert_errors,flush_time; +ulong specialflag=0; +ulong binlog_cache_use= 0, binlog_cache_disk_use= 0; +ulong max_connections, max_connect_errors; +uint max_user_connections= 0; +/** + Limit of the total number of prepared statements in the server. + Is necessary to protect the server against out-of-memory attacks. +*/ +ulong max_prepared_stmt_count; +/** + Current total number of prepared statements in the server. This number + is exact, and therefore may not be equal to the difference between + `com_stmt_prepare' and `com_stmt_close' (global status variables), as + the latter ones account for all registered attempts to prepare + a statement (including unsuccessful ones). Prepared statements are + currently connection-local: if the same SQL query text is prepared in + two different connections, this counts as two distinct prepared + statements. +*/ +ulong prepared_stmt_count=0; +ulong thread_id=1L,current_pid; +ulong slow_launch_threads = 0, sync_binlog_period; +ulong expire_logs_days = 0; +ulong rpl_recovery_rank=0; +const char *log_output_str= "FILE"; + +time_t server_start_time, flush_status_time; + +char mysql_home[FN_REFLEN], pidfile_name[FN_REFLEN], system_time_zone[30]; +char *default_tz_name; +char log_error_file[FN_REFLEN], glob_hostname[FN_REFLEN]; +char mysql_real_data_home[FN_REFLEN], + language[FN_REFLEN], reg_ext[FN_EXTLEN], mysql_charsets_dir[FN_REFLEN], + *opt_init_file, *opt_tc_log_file, + def_ft_boolean_syntax[sizeof(ft_boolean_syntax)]; +char mysql_unpacked_real_data_home[FN_REFLEN]; +int mysql_unpacked_real_data_home_len; +uint reg_ext_length; +const key_map key_map_empty(0); +key_map key_map_full(0); // Will be initialized later + +const char *opt_date_time_formats[3]; + +uint mysql_data_home_len; +char mysql_data_home_buff[2], *mysql_data_home=mysql_real_data_home; +char server_version[SERVER_VERSION_LENGTH]; +char *mysqld_unix_port, *opt_mysql_tmpdir; +const char **errmesg; /**< Error messages */ +const char *myisam_recover_options_str="OFF"; +const char *myisam_stats_method_str="nulls_unequal"; + +/** name of reference on left espression in rewritten IN subquery */ +const char *in_left_expr_name= ""; +/** name of additional condition */ +const char *in_additional_cond= ""; +const char *in_having_cond= ""; + +my_decimal decimal_zero; +/* classes for comparation parsing/processing */ +Eq_creator eq_creator; +Ne_creator ne_creator; +Gt_creator gt_creator; +Lt_creator lt_creator; +Ge_creator ge_creator; +Le_creator le_creator; + +FILE *bootstrap_file; +int bootstrap_error; +FILE *stderror_file=0; + +I_List threads; +I_List key_caches; +Rpl_filter* rpl_filter; +Rpl_filter* binlog_filter; + +struct system_variables global_system_variables; +struct system_variables max_system_variables; +struct system_status_var global_status_var; + +MY_TMPDIR mysql_tmpdir_list; +MY_BITMAP temp_pool; + +CHARSET_INFO *system_charset_info, *files_charset_info ; +CHARSET_INFO *national_charset_info, *table_alias_charset; +CHARSET_INFO *character_set_filesystem; + +MY_LOCALE *my_default_lc_time_names; + +SHOW_COMP_OPTION have_ssl, have_symlink, have_dlopen, have_query_cache; +SHOW_COMP_OPTION have_geometry, have_rtree_keys; +SHOW_COMP_OPTION have_crypt, have_compress; +SHOW_COMP_OPTION have_community_features; + +/* Thread specific variables */ + +pthread_key(MEM_ROOT**,THR_MALLOC); +pthread_key(THD*, THR_THD); +pthread_mutex_t LOCK_mysql_create_db, LOCK_Acl, LOCK_open, LOCK_thread_count, + LOCK_mapped_file, LOCK_status, LOCK_global_read_lock, + LOCK_error_log, LOCK_uuid_generator, + LOCK_delayed_insert, LOCK_delayed_status, LOCK_delayed_create, + LOCK_crypt, LOCK_bytes_sent, LOCK_bytes_received, + LOCK_global_system_variables, + LOCK_user_conn, LOCK_slave_list, LOCK_active_mi, + LOCK_connection_count; +/** + The below lock protects access to two global server variables: + max_prepared_stmt_count and prepared_stmt_count. These variables + set the limit and hold the current total number of prepared statements + in the server, respectively. As PREPARE/DEALLOCATE rate in a loaded + server may be fairly high, we need a dedicated lock. +*/ +pthread_mutex_t LOCK_prepared_stmt_count; +#ifdef HAVE_OPENSSL +pthread_mutex_t LOCK_des_key_file; +#endif +rw_lock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave; +rw_lock_t LOCK_system_variables_hash; +pthread_cond_t COND_refresh, COND_thread_count, COND_global_read_lock; +pthread_t signal_thread; +pthread_attr_t connection_attrib; +pthread_mutex_t LOCK_server_started; +pthread_cond_t COND_server_started; + +int mysqld_server_started= 0; + +File_parser_dummy_hook file_parser_dummy_hook; + +/* replication parameters, if master_host is not NULL, we are a slave */ +uint master_port= MYSQL_PORT, master_connect_retry = 60; +uint report_port= MYSQL_PORT; +ulong master_retry_count=0; +char *master_user, *master_password, *master_host, *master_info_file; +char *relay_log_info_file, *report_user, *report_password, *report_host; +char *opt_relay_logname = 0, *opt_relaylog_index_name=0; +my_bool master_ssl; +char *master_ssl_key, *master_ssl_cert; +char *master_ssl_ca, *master_ssl_capath, *master_ssl_cipher; +char *opt_logname, *opt_slow_logname; + +/* Static variables */ + +static bool kill_in_progress, segfaulted; +#ifdef HAVE_STACK_TRACE_ON_SEGV +static my_bool opt_do_pstack; +#endif /* HAVE_STACK_TRACE_ON_SEGV */ +static my_bool opt_bootstrap, opt_myisam_log; +static int cleanup_done; +static ulong opt_specialflag, opt_myisam_block_size; +static char *opt_update_logname, *opt_binlog_index_name; +static char *opt_tc_heuristic_recover; +static char *mysql_home_ptr, *pidfile_name_ptr; +static int defaults_argc; +static char **defaults_argv; +static char *opt_bin_logname; + +int orig_argc; +char **orig_argv; + +static my_socket unix_sock,ip_sock; +struct rand_struct sql_rand; ///< used by sql_class.cc:THD::THD() + +#ifndef EMBEDDED_LIBRARY +struct passwd *user_info; +static pthread_t select_thread; +static uint thr_kill_signal; +#endif + +/* OS specific variables */ + +#ifdef __WIN__ +#undef getpid +#include + +static pthread_cond_t COND_handler_count; +static uint handler_count; +static bool start_mode=0, use_opt_args; +static int opt_argc; +static char **opt_argv; + +#if !defined(EMBEDDED_LIBRARY) +static HANDLE hEventShutdown; +static char shutdown_event_name[40]; +#include "nt_servc.h" +static NTService Service; ///< Service object for WinNT +#endif /* EMBEDDED_LIBRARY */ +#endif /* __WIN__ */ + +#ifdef __NT__ +static char pipe_name[512]; +static SECURITY_ATTRIBUTES saPipeSecurity; +static SECURITY_DESCRIPTOR sdPipeDescriptor; +static HANDLE hPipe = INVALID_HANDLE_VALUE; +#endif + +#ifndef EMBEDDED_LIBRARY +bool mysqld_embedded=0; +#else +bool mysqld_embedded=1; +#endif + +static my_bool plugins_are_initialized= FALSE; + +#ifndef DBUG_OFF +static const char* default_dbug_option; +#endif +#ifdef HAVE_LIBWRAP +const char *libwrapName= NULL; +int allow_severity = LOG_INFO; +int deny_severity = LOG_WARNING; +#endif +#ifdef HAVE_QUERY_CACHE +static ulong query_cache_limit= 0; +ulong query_cache_min_res_unit= QUERY_CACHE_MIN_RESULT_DATA_SIZE; +Query_cache query_cache; +#endif +#ifdef HAVE_SMEM +char *shared_memory_base_name= default_shared_memory_base_name; +my_bool opt_enable_shared_memory; +HANDLE smem_event_connect_request= 0; +#endif + +scheduler_functions thread_scheduler; + +#define SSL_VARS_NOT_STATIC +#include "sslopt-vars.h" +#ifdef HAVE_OPENSSL +#include +#ifndef HAVE_YASSL +typedef struct CRYPTO_dynlock_value +{ + rw_lock_t lock; +} openssl_lock_t; + +static openssl_lock_t *openssl_stdlocks; +static openssl_lock_t *openssl_dynlock_create(const char *, int); +static void openssl_dynlock_destroy(openssl_lock_t *, const char *, int); +static void openssl_lock_function(int, int, const char *, int); +static void openssl_lock(int, openssl_lock_t *, const char *, int); +static unsigned long openssl_id_function(); +#endif +char *des_key_file; +struct st_VioSSLFd *ssl_acceptor_fd; +#endif /* HAVE_OPENSSL */ + +/** + Number of currently active user connections. The variable is protected by + LOCK_connection_count. +*/ +uint connection_count= 0; + +/* Function declarations */ + +pthread_handler_t signal_hand(void *arg); +static int mysql_init_variables(void); +static int get_options(int *argc,char **argv); +extern "C" my_bool mysqld_get_one_option(int, const struct my_option *, char *); +static void set_server_version(void); +static int init_thread_environment(); +static char *get_relative_path(const char *path); +static int fix_paths(void); +pthread_handler_t handle_connections_sockets(void *arg); +pthread_handler_t kill_server_thread(void *arg); +static void bootstrap(FILE *file); +static bool read_init_file(char *file_name); +#ifdef __NT__ +pthread_handler_t handle_connections_namedpipes(void *arg); +#endif +#ifdef HAVE_SMEM +pthread_handler_t handle_connections_shared_memory(void *arg); +#endif +pthread_handler_t handle_slave(void *arg); +static ulong find_bit_type(const char *x, TYPELIB *bit_lib); +static ulong find_bit_type_or_exit(const char *x, TYPELIB *bit_lib, + const char *option, int *error); +static void clean_up(bool print_message); +static int test_if_case_insensitive(const char *dir_name); + +#ifndef EMBEDDED_LIBRARY +static void usage(void); +static void start_signal_handler(void); +static void close_server_sock(); +static void clean_up_mutexes(void); +static void wait_for_signal_thread_to_end(void); +static void create_pid_file(); +static void end_ssl(); +#endif + + +#ifndef EMBEDDED_LIBRARY +/**************************************************************************** +** Code to end mysqld +****************************************************************************/ + +static void close_connections(void) +{ +#ifdef EXTRA_DEBUG + int count=0; +#endif + DBUG_ENTER("close_connections"); + + /* Clear thread cache */ + kill_cached_threads++; + flush_thread_cache(); + + /* kill connection thread */ +#if !defined(__WIN__) && !defined(__NETWARE__) + DBUG_PRINT("quit", ("waiting for select thread: 0x%lx", + (ulong) select_thread)); + (void) pthread_mutex_lock(&LOCK_thread_count); + + while (select_thread_in_use) + { + struct timespec abstime; + int error; + LINT_INIT(error); + DBUG_PRINT("info",("Waiting for select thread")); + +#ifndef DONT_USE_THR_ALARM + if (pthread_kill(select_thread, thr_client_alarm)) + break; // allready dead +#endif + set_timespec(abstime, 2); + for (uint tmp=0 ; tmp < 10 && select_thread_in_use; tmp++) + { + error=pthread_cond_timedwait(&COND_thread_count,&LOCK_thread_count, + &abstime); + if (error != EINTR) + break; + } +#ifdef EXTRA_DEBUG + if (error != 0 && !count++) + sql_print_error("Got error %d from pthread_cond_timedwait",error); +#endif + close_server_sock(); + } + (void) pthread_mutex_unlock(&LOCK_thread_count); +#endif /* __WIN__ */ + + + /* Abort listening to new connections */ + DBUG_PRINT("quit",("Closing sockets")); + if (!opt_disable_networking ) + { + if (ip_sock != INVALID_SOCKET) + { + (void) shutdown(ip_sock, SHUT_RDWR); + (void) closesocket(ip_sock); + ip_sock= INVALID_SOCKET; + } + } +#ifdef __NT__ + if (hPipe != INVALID_HANDLE_VALUE && opt_enable_named_pipe) + { + HANDLE temp; + DBUG_PRINT("quit", ("Closing named pipes") ); + + /* Create connection to the handle named pipe handler to break the loop */ + if ((temp = CreateFile(pipe_name, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + 0, + NULL )) != INVALID_HANDLE_VALUE) + { + WaitNamedPipe(pipe_name, 1000); + DWORD dwMode = PIPE_READMODE_BYTE | PIPE_WAIT; + SetNamedPipeHandleState(temp, &dwMode, NULL, NULL); + CancelIo(temp); + DisconnectNamedPipe(temp); + CloseHandle(temp); + } + } +#endif +#ifdef HAVE_SYS_UN_H + if (unix_sock != INVALID_SOCKET) + { + (void) shutdown(unix_sock, SHUT_RDWR); + (void) closesocket(unix_sock); + (void) unlink(mysqld_unix_port); + unix_sock= INVALID_SOCKET; + } +#endif + end_thr_alarm(0); // Abort old alarms. + + /* + First signal all threads that it's time to die + This will give the threads some time to gracefully abort their + statements and inform their clients that the server is about to die. + */ + + THD *tmp; + (void) pthread_mutex_lock(&LOCK_thread_count); // For unlink from list + + I_List_iterator it(threads); + while ((tmp=it++)) + { + DBUG_PRINT("quit",("Informing thread %ld that it's time to die", + tmp->thread_id)); + /* We skip slave threads & scheduler on this first loop through. */ + if (tmp->slave_thread) + continue; + + tmp->killed= THD::KILL_CONNECTION; + thread_scheduler.post_kill_notification(tmp); + if (tmp->mysys_var) + { + tmp->mysys_var->abort=1; + pthread_mutex_lock(&tmp->mysys_var->mutex); + if (tmp->mysys_var->current_cond) + { + pthread_mutex_lock(tmp->mysys_var->current_mutex); + pthread_cond_broadcast(tmp->mysys_var->current_cond); + pthread_mutex_unlock(tmp->mysys_var->current_mutex); + } + pthread_mutex_unlock(&tmp->mysys_var->mutex); + } + } + (void) pthread_mutex_unlock(&LOCK_thread_count); // For unlink from list + + Events::deinit(); + end_slave(); + + if (thread_count) + sleep(2); // Give threads time to die + + /* + Force remaining threads to die by closing the connection to the client + This will ensure that threads that are waiting for a command from the + client on a blocking read call are aborted. + */ + + for (;;) + { + DBUG_PRINT("quit",("Locking LOCK_thread_count")); + (void) pthread_mutex_lock(&LOCK_thread_count); // For unlink from list + if (!(tmp=threads.get())) + { + DBUG_PRINT("quit",("Unlocking LOCK_thread_count")); + (void) pthread_mutex_unlock(&LOCK_thread_count); + break; + } +#ifndef __bsdi__ // Bug in BSDI kernel + if (tmp->vio_ok()) + { + if (global_system_variables.log_warnings) + sql_print_warning(ER(ER_FORCING_CLOSE),my_progname, + tmp->thread_id, + (tmp->main_security_ctx.user ? + tmp->main_security_ctx.user : "")); + close_connection(tmp,0,0); + } +#endif + DBUG_PRINT("quit",("Unlocking LOCK_thread_count")); + (void) pthread_mutex_unlock(&LOCK_thread_count); + } + /* All threads has now been aborted */ + DBUG_PRINT("quit",("Waiting for threads to die (count=%u)",thread_count)); + (void) pthread_mutex_lock(&LOCK_thread_count); + while (thread_count) + { + (void) pthread_cond_wait(&COND_thread_count,&LOCK_thread_count); + DBUG_PRINT("quit",("One thread died (count=%u)",thread_count)); + } + (void) pthread_mutex_unlock(&LOCK_thread_count); + + close_active_mi(); + DBUG_PRINT("quit",("close_connections thread")); + DBUG_VOID_RETURN; +} + + +static void close_server_sock() +{ +#ifdef HAVE_CLOSE_SERVER_SOCK + DBUG_ENTER("close_server_sock"); + my_socket tmp_sock; + tmp_sock=ip_sock; + if (tmp_sock != INVALID_SOCKET) + { + ip_sock=INVALID_SOCKET; + DBUG_PRINT("info",("calling shutdown on TCP/IP socket")); + VOID(shutdown(tmp_sock, SHUT_RDWR)); +#if defined(__NETWARE__) + /* + The following code is disabled for normal systems as it causes MySQL + to hang on AIX 4.3 during shutdown + */ + DBUG_PRINT("info",("calling closesocket on TCP/IP socket")); + VOID(closesocket(tmp_sock)); +#endif + } + tmp_sock=unix_sock; + if (tmp_sock != INVALID_SOCKET) + { + unix_sock=INVALID_SOCKET; + DBUG_PRINT("info",("calling shutdown on unix socket")); + VOID(shutdown(tmp_sock, SHUT_RDWR)); +#if defined(__NETWARE__) + /* + The following code is disabled for normal systems as it may cause MySQL + to hang on AIX 4.3 during shutdown + */ + DBUG_PRINT("info",("calling closesocket on unix/IP socket")); + VOID(closesocket(tmp_sock)); +#endif + VOID(unlink(mysqld_unix_port)); + } + DBUG_VOID_RETURN; +#endif +} + +#endif /*EMBEDDED_LIBRARY*/ + + +void kill_mysql(void) +{ + DBUG_ENTER("kill_mysql"); + +#if defined(SIGNALS_DONT_BREAK_READ) && !defined(EMBEDDED_LIBRARY) + abort_loop=1; // Break connection loops + close_server_sock(); // Force accept to wake up +#endif + +#if defined(__WIN__) +#if !defined(EMBEDDED_LIBRARY) + { + if (!SetEvent(hEventShutdown)) + { + DBUG_PRINT("error",("Got error: %ld from SetEvent",GetLastError())); + } + /* + or: + HANDLE hEvent=OpenEvent(0, FALSE, "MySqlShutdown"); + SetEvent(hEventShutdown); + CloseHandle(hEvent); + */ + } +#endif +#elif defined(HAVE_PTHREAD_KILL) + if (pthread_kill(signal_thread, MYSQL_KILL_SIGNAL)) + { + DBUG_PRINT("error",("Got error %d from pthread_kill",errno)); /* purecov: inspected */ + } +#elif !defined(SIGNALS_DONT_BREAK_READ) + kill(current_pid, MYSQL_KILL_SIGNAL); +#endif + DBUG_PRINT("quit",("After pthread_kill")); + shutdown_in_progress=1; // Safety if kill didn't work +#ifdef SIGNALS_DONT_BREAK_READ + if (!kill_in_progress) + { + pthread_t tmp; + abort_loop=1; + if (pthread_create(&tmp,&connection_attrib, kill_server_thread, + (void*) 0)) + sql_print_error("Can't create thread to kill server"); + } +#endif + DBUG_VOID_RETURN; +} + +/** + Force server down. Kill all connections and threads and exit. + + @param sig_ptr Signal number that caused kill_server to be called. + + @note + A signal number of 0 mean that the function was not called + from a signal handler and there is thus no signal to block + or stop, we just want to kill the server. +*/ + +#if defined(__NETWARE__) +extern "C" void kill_server(int sig_ptr) +#define RETURN_FROM_KILL_SERVER DBUG_VOID_RETURN +#elif !defined(__WIN__) +static void *kill_server(void *sig_ptr) +#define RETURN_FROM_KILL_SERVER DBUG_RETURN(0) +#else +static void __cdecl kill_server(int sig_ptr) +#define RETURN_FROM_KILL_SERVER DBUG_VOID_RETURN +#endif +{ + DBUG_ENTER("kill_server"); +#ifndef EMBEDDED_LIBRARY + int sig=(int) (long) sig_ptr; // This is passed a int + // if there is a signal during the kill in progress, ignore the other + if (kill_in_progress) // Safety + RETURN_FROM_KILL_SERVER; + kill_in_progress=TRUE; + abort_loop=1; // This should be set + if (sig != 0) // 0 is not a valid signal number + my_sigset(sig, SIG_IGN); /* purify inspected */ + if (sig == MYSQL_KILL_SIGNAL || sig == 0) + sql_print_information(ER(ER_NORMAL_SHUTDOWN),my_progname); + else + sql_print_error(ER(ER_GOT_SIGNAL),my_progname,sig); /* purecov: inspected */ + +#if defined(HAVE_SMEM) && defined(__WIN__) + /* + Send event to smem_event_connect_request for aborting + */ + if (!SetEvent(smem_event_connect_request)) + { + DBUG_PRINT("error", + ("Got error: %ld from SetEvent of smem_event_connect_request", + GetLastError())); + } +#endif + + close_connections(); + if (sig != MYSQL_KILL_SIGNAL && + sig != 0) + unireg_abort(1); /* purecov: inspected */ + else + unireg_end(); + + /* purecov: begin deadcode */ +#ifdef __NETWARE__ + if (!event_flag) + pthread_join(select_thread, NULL); // wait for main thread +#endif /* __NETWARE__ */ + + my_thread_end(); + pthread_exit(0); + /* purecov: end */ + +#endif /* EMBEDDED_LIBRARY */ + RETURN_FROM_KILL_SERVER; +} + + +#if defined(USE_ONE_SIGNAL_HAND) || (defined(__NETWARE__) && defined(SIGNALS_DONT_BREAK_READ)) +pthread_handler_t kill_server_thread(void *arg __attribute__((unused))) +{ + my_thread_init(); // Initialize new thread + kill_server(0); + /* purecov: begin deadcode */ + my_thread_end(); + pthread_exit(0); + return 0; + /* purecov: end */ +} +#endif + + +extern "C" sig_handler print_signal_warning(int sig) +{ + if (global_system_variables.log_warnings) + sql_print_warning("Got signal %d from thread %ld", sig,my_thread_id()); +#ifdef DONT_REMEMBER_SIGNAL + my_sigset(sig,print_signal_warning); /* int. thread system calls */ +#endif +#if !defined(__WIN__) && !defined(__NETWARE__) + if (sig == SIGALRM) + alarm(2); /* reschedule alarm */ +#endif +} + +#ifndef EMBEDDED_LIBRARY + +/** + cleanup all memory and end program nicely. + + If SIGNALS_DONT_BREAK_READ is defined, this function is called + by the main thread. To get MySQL to shut down nicely in this case + (Mac OS X) we have to call exit() instead if pthread_exit(). + + @note + This function never returns. +*/ +void unireg_end(void) +{ + clean_up(1); + my_thread_end(); +#if defined(SIGNALS_DONT_BREAK_READ) && !defined(__NETWARE__) + exit(0); +#else + pthread_exit(0); // Exit is in main thread +#endif +} + +extern "C" void unireg_abort(int exit_code) +{ + DBUG_ENTER("unireg_abort"); + + if (opt_help) + usage(); + if (exit_code) + sql_print_error("Aborting\n"); + clean_up(!opt_help && (exit_code || !opt_bootstrap)); /* purecov: inspected */ + DBUG_PRINT("quit",("done with cleanup in unireg_abort")); + wait_for_signal_thread_to_end(); + clean_up_mutexes(); + my_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0); + exit(exit_code); /* purecov: inspected */ +} + +#endif /*EMBEDDED_LIBRARY*/ + + +void clean_up(bool print_message) +{ + DBUG_PRINT("exit",("clean_up")); + if (cleanup_done++) + return; /* purecov: inspected */ + + stop_handle_manager(); + release_ddl_log(); + + /* + make sure that handlers finish up + what they have that is dependent on the binlog + */ + ha_binlog_end(current_thd); + + logger.cleanup_base(); + + injector::free_instance(); + mysql_bin_log.cleanup(); + +#ifdef HAVE_REPLICATION + if (use_slave_mask) + bitmap_free(&slave_error_mask); +#endif + my_tz_free(); + my_database_names_free(); +#ifndef NO_EMBEDDED_ACCESS_CHECKS + servers_free(1); + acl_free(1); + grant_free(); +#endif + query_cache_destroy(); + table_cache_free(); + table_def_free(); + hostname_cache_free(); + item_user_lock_free(); + lex_free(); /* Free some memory */ + item_create_cleanup(); + set_var_free(); + free_charsets(); + if (!opt_noacl) + { +#ifdef HAVE_DLOPEN + udf_free(); +#endif + } + plugin_shutdown(); + ha_end(); + if (tc_log) + tc_log->close(); + xid_cache_free(); + delete_elements(&key_caches, (void (*)(const char*, uchar*)) free_key_cache); + multi_keycache_free(); + free_status_vars(); + end_thr_alarm(1); /* Free allocated memory */ + my_free_open_file_info(); + my_free((char*) global_system_variables.date_format, + MYF(MY_ALLOW_ZERO_PTR)); + my_free((char*) global_system_variables.time_format, + MYF(MY_ALLOW_ZERO_PTR)); + my_free((char*) global_system_variables.datetime_format, + MYF(MY_ALLOW_ZERO_PTR)); + if (defaults_argv) + free_defaults(defaults_argv); + my_free(sys_init_connect.value, MYF(MY_ALLOW_ZERO_PTR)); + my_free(sys_init_slave.value, MYF(MY_ALLOW_ZERO_PTR)); + my_free(sys_var_general_log_path.value, MYF(MY_ALLOW_ZERO_PTR)); + my_free(sys_var_slow_log_path.value, MYF(MY_ALLOW_ZERO_PTR)); + free_tmpdir(&mysql_tmpdir_list); +#ifdef HAVE_REPLICATION + my_free(slave_load_tmpdir,MYF(MY_ALLOW_ZERO_PTR)); +#endif + x_free(opt_bin_logname); + x_free(opt_relay_logname); + x_free(opt_secure_file_priv); + bitmap_free(&temp_pool); + free_max_user_conn(); +#ifdef HAVE_REPLICATION + end_slave_list(); +#endif + delete binlog_filter; + delete rpl_filter; +#ifndef EMBEDDED_LIBRARY + end_ssl(); +#endif + vio_end(); +#ifdef USE_REGEX + my_regex_end(); +#endif + +#if !defined(EMBEDDED_LIBRARY) + if (!opt_bootstrap) + (void) my_delete(pidfile_name,MYF(0)); // This may not always exist +#endif + if (print_message && errmesg && server_start_time) + sql_print_information(ER(ER_SHUTDOWN_COMPLETE),my_progname); + thread_scheduler.end(); + finish_client_errs(); + my_free((uchar*) my_error_unregister(ER_ERROR_FIRST, ER_ERROR_LAST), + MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR)); + DBUG_PRINT("quit", ("Error messages freed")); + /* Tell main we are ready */ + logger.cleanup_end(); + (void) pthread_mutex_lock(&LOCK_thread_count); + DBUG_PRINT("quit", ("got thread count lock")); + ready_to_exit=1; + /* do the broadcast inside the lock to ensure that my_end() is not called */ + (void) pthread_cond_broadcast(&COND_thread_count); + (void) pthread_mutex_unlock(&LOCK_thread_count); + + /* + The following lines may never be executed as the main thread may have + killed us + */ + DBUG_PRINT("quit", ("done with cleanup")); +} /* clean_up */ + + +#ifndef EMBEDDED_LIBRARY + +/** + This is mainly needed when running with purify, but it's still nice to + know that all child threads have died when mysqld exits. +*/ +static void wait_for_signal_thread_to_end() +{ +#ifndef __NETWARE__ + uint i; + /* + Wait up to 10 seconds for signal thread to die. We use this mainly to + avoid getting warnings that my_thread_end has not been called + */ + for (i= 0 ; i < 100 && signal_thread_in_use; i++) + { + if (pthread_kill(signal_thread, MYSQL_KILL_SIGNAL) != ESRCH) + break; + my_sleep(100); // Give it time to die + } +#endif +} + + +static void clean_up_mutexes() +{ + (void) pthread_mutex_destroy(&LOCK_mysql_create_db); + (void) pthread_mutex_destroy(&LOCK_lock_db); + (void) pthread_mutex_destroy(&LOCK_Acl); + (void) rwlock_destroy(&LOCK_grant); + (void) pthread_mutex_destroy(&LOCK_open); + (void) pthread_mutex_destroy(&LOCK_thread_count); + (void) pthread_mutex_destroy(&LOCK_mapped_file); + (void) pthread_mutex_destroy(&LOCK_status); + (void) pthread_mutex_destroy(&LOCK_error_log); + (void) pthread_mutex_destroy(&LOCK_delayed_insert); + (void) pthread_mutex_destroy(&LOCK_delayed_status); + (void) pthread_mutex_destroy(&LOCK_delayed_create); + (void) pthread_mutex_destroy(&LOCK_manager); + (void) pthread_mutex_destroy(&LOCK_crypt); + (void) pthread_mutex_destroy(&LOCK_bytes_sent); + (void) pthread_mutex_destroy(&LOCK_bytes_received); + (void) pthread_mutex_destroy(&LOCK_user_conn); + (void) pthread_mutex_destroy(&LOCK_connection_count); + Events::destroy_mutexes(); +#ifdef HAVE_OPENSSL + (void) pthread_mutex_destroy(&LOCK_des_key_file); +#ifndef HAVE_YASSL + for (int i= 0; i < CRYPTO_num_locks(); ++i) + (void) rwlock_destroy(&openssl_stdlocks[i].lock); + OPENSSL_free(openssl_stdlocks); +#endif +#endif +#ifdef HAVE_REPLICATION + (void) pthread_mutex_destroy(&LOCK_rpl_status); + (void) pthread_cond_destroy(&COND_rpl_status); +#endif + (void) pthread_mutex_destroy(&LOCK_active_mi); + (void) rwlock_destroy(&LOCK_sys_init_connect); + (void) rwlock_destroy(&LOCK_sys_init_slave); + (void) pthread_mutex_destroy(&LOCK_global_system_variables); + (void) rwlock_destroy(&LOCK_system_variables_hash); + (void) pthread_mutex_destroy(&LOCK_global_read_lock); + (void) pthread_mutex_destroy(&LOCK_uuid_generator); + (void) pthread_mutex_destroy(&LOCK_prepared_stmt_count); + (void) pthread_cond_destroy(&COND_thread_count); + (void) pthread_cond_destroy(&COND_refresh); + (void) pthread_cond_destroy(&COND_global_read_lock); + (void) pthread_cond_destroy(&COND_thread_cache); + (void) pthread_cond_destroy(&COND_flush_thread_cache); + (void) pthread_cond_destroy(&COND_manager); +} + +#endif /*EMBEDDED_LIBRARY*/ + + +/**************************************************************************** +** Init IP and UNIX socket +****************************************************************************/ + +#ifndef EMBEDDED_LIBRARY +static void set_ports() +{ + char *env; + if (!mysqld_port && !opt_disable_networking) + { // Get port if not from commandline + mysqld_port= MYSQL_PORT; + + /* + if builder specifically requested a default port, use that + (even if it coincides with our factory default). + only if they didn't do we check /etc/services (and, failing + on that, fall back to the factory default of 3306). + either default can be overridden by the environment variable + MYSQL_TCP_PORT, which in turn can be overridden with command + line options. + */ + +#if MYSQL_PORT_DEFAULT == 0 + struct servent *serv_ptr; + if ((serv_ptr= getservbyname("mysql", "tcp"))) + mysqld_port= ntohs((u_short) serv_ptr->s_port); /* purecov: inspected */ +#endif + if ((env = getenv("MYSQL_TCP_PORT"))) + mysqld_port= (uint) atoi(env); /* purecov: inspected */ + } + if (!mysqld_unix_port) + { +#ifdef __WIN__ + mysqld_unix_port= (char*) MYSQL_NAMEDPIPE; +#else + mysqld_unix_port= (char*) MYSQL_UNIX_ADDR; +#endif + if ((env = getenv("MYSQL_UNIX_PORT"))) + mysqld_unix_port= env; /* purecov: inspected */ + } +} + +/* Change to run as another user if started with --user */ + +static struct passwd *check_user(const char *user) +{ +#if !defined(__WIN__) && !defined(__NETWARE__) + struct passwd *tmp_user_info; + uid_t user_id= geteuid(); + + // Don't bother if we aren't superuser + if (user_id) + { + if (user) + { + /* Don't give a warning, if real user is same as given with --user */ + /* purecov: begin tested */ + tmp_user_info= getpwnam(user); + if ((!tmp_user_info || user_id != tmp_user_info->pw_uid) && + global_system_variables.log_warnings) + sql_print_warning( + "One can only use the --user switch if running as root\n"); + /* purecov: end */ + } + return NULL; + } + if (!user) + { + if (!opt_bootstrap) + { + sql_print_error("Fatal error: Please read \"Security\" section of the manual to find out how to run mysqld as root!\n"); + unireg_abort(1); + } + return NULL; + } + /* purecov: begin tested */ + if (!strcmp(user,"root")) + return NULL; // Avoid problem with dynamic libraries + + if (!(tmp_user_info= getpwnam(user))) + { + // Allow a numeric uid to be used + const char *pos; + for (pos= user; my_isdigit(mysqld_charset,*pos); pos++) ; + if (*pos) // Not numeric id + goto err; + if (!(tmp_user_info= getpwuid(atoi(user)))) + goto err; + } + return tmp_user_info; + /* purecov: end */ + +err: + sql_print_error("Fatal error: Can't change to run as user '%s' ; Please check that the user exists!\n",user); + unireg_abort(1); + +#ifdef PR_SET_DUMPABLE + if (test_flags & TEST_CORE_ON_SIGNAL) + { + /* inform kernel that process is dumpable */ + (void) prctl(PR_SET_DUMPABLE, 1); + } +#endif + +#endif + return NULL; +} + +static void set_user(const char *user, struct passwd *user_info_arg) +{ + /* purecov: begin tested */ +#if !defined(__WIN__) && !defined(__NETWARE__) + DBUG_ASSERT(user_info_arg != 0); +#ifdef HAVE_INITGROUPS + /* + We can get a SIGSEGV when calling initgroups() on some systems when NSS + is configured to use LDAP and the server is statically linked. We set + calling_initgroups as a flag to the SIGSEGV handler that is then used to + output a specific message to help the user resolve this problem. + */ + calling_initgroups= TRUE; + initgroups((char*) user, user_info_arg->pw_gid); + calling_initgroups= FALSE; +#endif + if (setgid(user_info_arg->pw_gid) == -1) + { + sql_perror("setgid"); + unireg_abort(1); + } + if (setuid(user_info_arg->pw_uid) == -1) + { + sql_perror("setuid"); + unireg_abort(1); + } +#endif + /* purecov: end */ +} + + +static void set_effective_user(struct passwd *user_info_arg) +{ +#if !defined(__WIN__) && !defined(__NETWARE__) + DBUG_ASSERT(user_info_arg != 0); + if (setregid((gid_t)-1, user_info_arg->pw_gid) == -1) + { + sql_perror("setregid"); + unireg_abort(1); + } + if (setreuid((uid_t)-1, user_info_arg->pw_uid) == -1) + { + sql_perror("setreuid"); + unireg_abort(1); + } +#endif +} + + +/** Change root user if started with @c --chroot . */ +static void set_root(const char *path) +{ +#if !defined(__WIN__) && !defined(__NETWARE__) + if (chroot(path) == -1) + { + sql_perror("chroot"); + unireg_abort(1); + } + my_setwd("/", MYF(0)); +#endif +} + +static void network_init(void) +{ + struct sockaddr_in IPaddr; +#ifdef HAVE_SYS_UN_H + struct sockaddr_un UNIXaddr; +#endif + int arg=1; + int ret; + uint waited; + uint this_wait; + uint retry; + DBUG_ENTER("network_init"); + LINT_INIT(ret); + + if (thread_scheduler.init()) + unireg_abort(1); /* purecov: inspected */ + + set_ports(); + + if (mysqld_port != 0 && !opt_disable_networking && !opt_bootstrap) + { + DBUG_PRINT("general",("IP Socket is %d",mysqld_port)); + ip_sock = socket(AF_INET, SOCK_STREAM, 0); + if (ip_sock == INVALID_SOCKET) + { + DBUG_PRINT("error",("Got error: %d from socket()",socket_errno)); + sql_perror(ER(ER_IPSOCK_ERROR)); /* purecov: tested */ + unireg_abort(1); /* purecov: tested */ + } + bzero((char*) &IPaddr, sizeof(IPaddr)); + IPaddr.sin_family = AF_INET; + IPaddr.sin_addr.s_addr = my_bind_addr; + IPaddr.sin_port = (unsigned short) htons((unsigned short) mysqld_port); + +#ifndef __WIN__ + /* + We should not use SO_REUSEADDR on windows as this would enable a + user to open two mysqld servers with the same TCP/IP port. + */ + (void) setsockopt(ip_sock,SOL_SOCKET,SO_REUSEADDR,(char*)&arg,sizeof(arg)); +#endif /* __WIN__ */ + /* + Sometimes the port is not released fast enough when stopping and + restarting the server. This happens quite often with the test suite + on busy Linux systems. Retry to bind the address at these intervals: + Sleep intervals: 1, 2, 4, 6, 9, 13, 17, 22, ... + Retry at second: 1, 3, 7, 13, 22, 35, 52, 74, ... + Limit the sequence by mysqld_port_timeout (set --port-open-timeout=#). + */ + for (waited= 0, retry= 1; ; retry++, waited+= this_wait) + { + if (((ret= bind(ip_sock, my_reinterpret_cast(struct sockaddr *) (&IPaddr), + sizeof(IPaddr))) >= 0) || + (socket_errno != SOCKET_EADDRINUSE) || + (waited >= mysqld_port_timeout)) + break; + sql_print_information("Retrying bind on TCP/IP port %u", mysqld_port); + this_wait= retry * retry / 3 + 1; + sleep(this_wait); + } + if (ret < 0) + { + DBUG_PRINT("error",("Got error: %d from bind",socket_errno)); + sql_perror("Can't start server: Bind on TCP/IP port"); + sql_print_error("Do you already have another mysqld server running on port: %d ?",mysqld_port); + unireg_abort(1); + } + if (listen(ip_sock,(int) back_log) < 0) + { + sql_perror("Can't start server: listen() on TCP/IP port"); + sql_print_error("listen() on TCP/IP failed with error %d", + socket_errno); + unireg_abort(1); + } + } + +#ifdef __NT__ + /* create named pipe */ + if (Service.IsNT() && mysqld_unix_port[0] && !opt_bootstrap && + opt_enable_named_pipe) + { + + strxnmov(pipe_name, sizeof(pipe_name)-1, "\\\\.\\pipe\\", + mysqld_unix_port, NullS); + bzero((char*) &saPipeSecurity, sizeof(saPipeSecurity)); + bzero((char*) &sdPipeDescriptor, sizeof(sdPipeDescriptor)); + if (!InitializeSecurityDescriptor(&sdPipeDescriptor, + SECURITY_DESCRIPTOR_REVISION)) + { + sql_perror("Can't start server : Initialize security descriptor"); + unireg_abort(1); + } + if (!SetSecurityDescriptorDacl(&sdPipeDescriptor, TRUE, NULL, FALSE)) + { + sql_perror("Can't start server : Set security descriptor"); + unireg_abort(1); + } + saPipeSecurity.nLength = sizeof(SECURITY_ATTRIBUTES); + saPipeSecurity.lpSecurityDescriptor = &sdPipeDescriptor; + saPipeSecurity.bInheritHandle = FALSE; + if ((hPipe= CreateNamedPipe(pipe_name, + PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | + PIPE_READMODE_BYTE | + PIPE_WAIT, + PIPE_UNLIMITED_INSTANCES, + (int) global_system_variables.net_buffer_length, + (int) global_system_variables.net_buffer_length, + NMPWAIT_USE_DEFAULT_WAIT, + &saPipeSecurity)) == INVALID_HANDLE_VALUE) + { + LPVOID lpMsgBuf; + int error=GetLastError(); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, 0, NULL ); + sql_perror((char *)lpMsgBuf); + LocalFree(lpMsgBuf); + unireg_abort(1); + } + } +#endif + +#if defined(HAVE_SYS_UN_H) + /* + ** Create the UNIX socket + */ + if (mysqld_unix_port[0] && !opt_bootstrap) + { + DBUG_PRINT("general",("UNIX Socket is %s",mysqld_unix_port)); + + if (strlen(mysqld_unix_port) > (sizeof(UNIXaddr.sun_path) - 1)) + { + sql_print_error("The socket file path is too long (> %u): %s", + (uint) sizeof(UNIXaddr.sun_path) - 1, mysqld_unix_port); + unireg_abort(1); + } + if ((unix_sock= socket(AF_UNIX, SOCK_STREAM, 0)) < 0) + { + sql_perror("Can't start server : UNIX Socket "); /* purecov: inspected */ + unireg_abort(1); /* purecov: inspected */ + } + bzero((char*) &UNIXaddr, sizeof(UNIXaddr)); + UNIXaddr.sun_family = AF_UNIX; + strmov(UNIXaddr.sun_path, mysqld_unix_port); + (void) unlink(mysqld_unix_port); + (void) setsockopt(unix_sock,SOL_SOCKET,SO_REUSEADDR,(char*)&arg, + sizeof(arg)); + umask(0); + if (bind(unix_sock, my_reinterpret_cast(struct sockaddr *) (&UNIXaddr), + sizeof(UNIXaddr)) < 0) + { + sql_perror("Can't start server : Bind on unix socket"); /* purecov: tested */ + sql_print_error("Do you already have another mysqld server running on socket: %s ?",mysqld_unix_port); + unireg_abort(1); /* purecov: tested */ + } + umask(((~my_umask) & 0666)); +#if defined(S_IFSOCK) && defined(SECURE_SOCKETS) + (void) chmod(mysqld_unix_port,S_IFSOCK); /* Fix solaris 2.6 bug */ +#endif + if (listen(unix_sock,(int) back_log) < 0) + sql_print_warning("listen() on Unix socket failed with error %d", + socket_errno); + } +#endif + DBUG_PRINT("info",("server started")); + DBUG_VOID_RETURN; +} + +#endif /*!EMBEDDED_LIBRARY*/ + + +#ifndef EMBEDDED_LIBRARY +/** + Close a connection. + + @param thd Thread handle + @param errcode Error code to print to console + @param lock 1 if we have have to lock LOCK_thread_count + + @note + For the connection that is doing shutdown, this is called twice +*/ +void close_connection(THD *thd, uint errcode, bool lock) +{ + st_vio *vio; + DBUG_ENTER("close_connection"); + DBUG_PRINT("enter",("fd: %s error: '%s'", + thd->net.vio ? vio_description(thd->net.vio) : + "(not connected)", + errcode ? ER(errcode) : "")); + if (lock) + (void) pthread_mutex_lock(&LOCK_thread_count); + thd->killed= THD::KILL_CONNECTION; + if ((vio= thd->net.vio) != 0) + { + if (errcode) + net_send_error(thd, errcode, ER(errcode)); /* purecov: inspected */ + vio_close(vio); /* vio is freed in delete thd */ + } + if (lock) + (void) pthread_mutex_unlock(&LOCK_thread_count); + DBUG_VOID_RETURN; +} +#endif /* EMBEDDED_LIBRARY */ + + +/** Called when a thread is aborted. */ +/* ARGSUSED */ +extern "C" sig_handler end_thread_signal(int sig __attribute__((unused))) +{ + THD *thd=current_thd; + DBUG_ENTER("end_thread_signal"); + if (thd && ! thd->bootstrap) + { + statistic_increment(killed_threads, &LOCK_status); + thread_scheduler.end_thread(thd,0); /* purecov: inspected */ + } + DBUG_VOID_RETURN; /* purecov: deadcode */ +} + + +/* + Unlink thd from global list of available connections and free thd + + SYNOPSIS + unlink_thd() + thd Thread handler + + NOTES + LOCK_thread_count is locked and left locked +*/ + +void unlink_thd(THD *thd) +{ + DBUG_ENTER("unlink_thd"); + DBUG_PRINT("enter", ("thd: 0x%lx", (long) thd)); + thd->cleanup(); + + pthread_mutex_lock(&LOCK_connection_count); + --connection_count; + pthread_mutex_unlock(&LOCK_connection_count); + + (void) pthread_mutex_lock(&LOCK_thread_count); + thread_count--; + delete thd; + DBUG_VOID_RETURN; +} + + +/* + Store thread in cache for reuse by new connections + + SYNOPSIS + cache_thread() + + NOTES + LOCK_thread_count has to be locked + + RETURN + 0 Thread was not put in cache + 1 Thread is to be reused by new connection. + (ie, caller should return, not abort with pthread_exit()) +*/ + + +static bool cache_thread() +{ + safe_mutex_assert_owner(&LOCK_thread_count); + if (cached_thread_count < thread_cache_size && + ! abort_loop && !kill_cached_threads) + { + /* Don't kill the thread, just put it in cache for reuse */ + DBUG_PRINT("info", ("Adding thread to cache")); + cached_thread_count++; + while (!abort_loop && ! wake_thread && ! kill_cached_threads) + (void) pthread_cond_wait(&COND_thread_cache, &LOCK_thread_count); + cached_thread_count--; + if (kill_cached_threads) + pthread_cond_signal(&COND_flush_thread_cache); + if (wake_thread) + { + THD *thd; + wake_thread--; + thd= thread_cache.get(); + thd->thread_stack= (char*) &thd; // For store_globals + (void) thd->store_globals(); + /* + THD::mysys_var::abort is associated with physical thread rather + than with THD object. So we need to reset this flag before using + this thread for handling of new THD object/connection. + */ + thd->mysys_var->abort= 0; + thd->thr_create_utime= my_micro_time(); + threads.append(thd); + return(1); + } + } + return(0); +} + + +/* + End thread for the current connection + + SYNOPSIS + one_thread_per_connection_end() + thd Thread handler + put_in_cache Store thread in cache, if there is room in it + Normally this is true in all cases except when we got + out of resources initializing the current thread + + NOTES + If thread is cached, we will wait until thread is scheduled to be + reused and then we will return. + If thread is not cached, we end the thread. + + RETURN + 0 Signal to handle_one_connection to reuse connection +*/ + +bool one_thread_per_connection_end(THD *thd, bool put_in_cache) +{ + DBUG_ENTER("one_thread_per_connection_end"); + unlink_thd(thd); + if (put_in_cache) + put_in_cache= cache_thread(); + pthread_mutex_unlock(&LOCK_thread_count); + if (put_in_cache) + DBUG_RETURN(0); // Thread is reused + + /* It's safe to broadcast outside a lock (COND... is not deleted here) */ + DBUG_PRINT("signal", ("Broadcasting COND_thread_count")); + my_thread_end(); + (void) pthread_cond_broadcast(&COND_thread_count); + + pthread_exit(0); + DBUG_RETURN(0); // Impossible +} + + +void flush_thread_cache() +{ + (void) pthread_mutex_lock(&LOCK_thread_count); + kill_cached_threads++; + while (cached_thread_count) + { + pthread_cond_broadcast(&COND_thread_cache); + pthread_cond_wait(&COND_flush_thread_cache,&LOCK_thread_count); + } + kill_cached_threads--; + (void) pthread_mutex_unlock(&LOCK_thread_count); +} + + +#ifdef THREAD_SPECIFIC_SIGPIPE +/** + Aborts a thread nicely. Comes here on SIGPIPE. + + @todo + One should have to fix that thr_alarm know about this thread too. +*/ +extern "C" sig_handler abort_thread(int sig __attribute__((unused))) +{ + THD *thd=current_thd; + DBUG_ENTER("abort_thread"); + if (thd) + thd->killed= THD::KILL_CONNECTION; + DBUG_VOID_RETURN; +} +#endif + + +/****************************************************************************** + Setup a signal thread with handles all signals. + Because Linux doesn't support schemas use a mutex to check that + the signal thread is ready before continuing +******************************************************************************/ + +#if defined(__WIN__) + + +/* + On Windows, we use native SetConsoleCtrlHandler for handle events like Ctrl-C + with graceful shutdown. + Also, we do not use signal(), but SetUnhandledExceptionFilter instead - as it + provides possibility to pass the exception to just-in-time debugger, collect + dumps and potentially also the exception and thread context used to output + callstack. +*/ + +static BOOL WINAPI console_event_handler( DWORD type ) +{ + DBUG_ENTER("console_event_handler"); +#ifndef EMBEDDED_LIBRARY + if(type == CTRL_C_EVENT) + { + /* + Do not shutdown before startup is finished and shutdown + thread is initialized. Otherwise there is a race condition + between main thread doing initialization and CTRL-C thread doing + cleanup, which can result into crash. + */ +#ifndef EMBEDDED_LIBRARY + if(hEventShutdown) + kill_mysql(); + else +#endif + sql_print_warning("CTRL-C ignored during startup"); + DBUG_RETURN(TRUE); + } +#endif + DBUG_RETURN(FALSE); +} + + +/* + In Visual Studio 2005 and later, default SIGABRT handler will overwrite + any unhandled exception filter set by the application and will try to + call JIT debugger. This is not what we want, this we calling __debugbreak + to stop in debugger, if process is being debugged or to generate + EXCEPTION_BREAKPOINT and then handle_segfault will do its magic. +*/ + +#if (_MSC_VER >= 1400) +static void my_sigabrt_handler(int sig) +{ + __debugbreak(); +} +#endif /*_MSC_VER >=1400 */ + +void win_install_sigabrt_handler(void) +{ +#if (_MSC_VER >=1400) + /*abort() should not override our exception filter*/ + _set_abort_behavior(0,_CALL_REPORTFAULT); + signal(SIGABRT,my_sigabrt_handler); +#endif /* _MSC_VER >=1400 */ +} + +#ifdef DEBUG_UNHANDLED_EXCEPTION_FILTER +#define DEBUGGER_ATTACH_TIMEOUT 120 +/* + Wait for debugger to attach and break into debugger. If debugger is not attached, + resume after timeout. +*/ +static void wait_for_debugger(int timeout_sec) +{ + if(!IsDebuggerPresent()) + { + int i; + printf("Waiting for debugger to attach, pid=%u\n",GetCurrentProcessId()); + fflush(stdout); + for(i= 0; i < timeout_sec; i++) + { + Sleep(1000); + if(IsDebuggerPresent()) + { + /* Break into debugger */ + __debugbreak(); + return; + } + } + printf("pid=%u, debugger not attached after %d seconds, resuming\n",GetCurrentProcessId(), + timeout_sec); + fflush(stdout); + } +} +#endif /* DEBUG_UNHANDLED_EXCEPTION_FILTER */ + +LONG WINAPI my_unhandler_exception_filter(EXCEPTION_POINTERS *ex_pointers) +{ + static BOOL first_time= TRUE; + if(!first_time) + { + /* + This routine can be called twice, typically + when detaching in JIT debugger. + Return EXCEPTION_EXECUTE_HANDLER to terminate process. + */ + return EXCEPTION_EXECUTE_HANDLER; + } + first_time= FALSE; +#ifdef DEBUG_UNHANDLED_EXCEPTION_FILTER + /* + Unfortunately there is no clean way to debug unhandled exception filters, + as debugger does not stop there(also documented in MSDN) + To overcome, one could put a MessageBox, but this will not work in service. + Better solution is to print error message and sleep some minutes + until debugger is attached + */ + wait_for_debugger(DEBUGGER_ATTACH_TIMEOUT); +#endif /* DEBUG_UNHANDLED_EXCEPTION_FILTER */ + __try + { + my_set_exception_pointers(ex_pointers); + handle_segfault(ex_pointers->ExceptionRecord->ExceptionCode); + } + __except(EXCEPTION_EXECUTE_HANDLER) + { + DWORD written; + const char msg[] = "Got exception in exception handler!\n"; + WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),msg, sizeof(msg)-1, + &written,NULL); + } + /* + Return EXCEPTION_CONTINUE_SEARCH to give JIT debugger + (drwtsn32 or vsjitdebugger) possibility to attach, + if JIT debugger is configured. + Windows Error reporting might generate a dump here. + */ + return EXCEPTION_CONTINUE_SEARCH; +} + + +static void init_signals(void) +{ + win_install_sigabrt_handler(); + if(opt_console) + SetConsoleCtrlHandler(console_event_handler,TRUE); + else + { + /* Avoid MessageBox()es*/ + _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); + + /* + Do not use SEM_NOGPFAULTERRORBOX in the following SetErrorMode (), + because it would prevent JIT debugger and Windows error reporting + from working. We need WER or JIT-debugging, since our own unhandled + exception filter is not guaranteed to work in all situation + (like heap corruption or stack overflow) + */ + SetErrorMode(SetErrorMode(0)|SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); + } + SetUnhandledExceptionFilter(my_unhandler_exception_filter); +} + + +static void start_signal_handler(void) +{ +#ifndef EMBEDDED_LIBRARY + // Save vm id of this process + if (!opt_bootstrap) + create_pid_file(); +#endif /* EMBEDDED_LIBRARY */ +} + + +static void check_data_home(const char *path) +{} + + +#elif defined(__NETWARE__) + +/// down server event callback. +void mysql_down_server_cb(void *, void *) +{ + event_flag= TRUE; + kill_server(0); +} + + +/// destroy callback resources. +void mysql_cb_destroy(void *) +{ + UnRegisterEventNotification(eh); // cleanup down event notification + NX_UNWRAP_INTERFACE(ref); + /* Deregister NSS volume deactivation event */ + NX_UNWRAP_INTERFACE(refneb); + if (neb_consumer_id) + UnRegisterConsumer(neb_consumer_id, NULL); +} + + +/// initialize callbacks. +void mysql_cb_init() +{ + // register for down server event + void *handle = getnlmhandle(); + rtag_t rt= AllocateResourceTag(handle, "MySQL Down Server Callback", + EventSignature); + NX_WRAP_INTERFACE((void *)mysql_down_server_cb, 2, (void **)&ref); + eh= RegisterForEventNotification(rt, EVENT_PRE_DOWN_SERVER, + EVENT_PRIORITY_APPLICATION, + NULL, ref, NULL); + + /* + Register for volume deactivation event + Wrap the callback function, as it is called by non-LibC thread + */ + (void *) NX_WRAP_INTERFACE(neb_event_callback, 1, &refneb); + registerwithneb(); + + NXVmRegisterExitHandler(mysql_cb_destroy, NULL); // clean-up +} + + +/** To get the name of the NetWare volume having MySQL data folder. */ +static void getvolumename() +{ + char *p; + /* + We assume that data path is already set. + If not it won't come here. Terminate after volume name + */ + if ((p= strchr(mysql_real_data_home, ':'))) + strmake(datavolname, mysql_real_data_home, + (uint) (p - mysql_real_data_home)); +} + + +/** + Registering with NEB for NSS Volume Deactivation event. +*/ + +static void registerwithneb() +{ + + ConsumerRegistrationInfo reg_info; + + /* Clear NEB registration structure */ + bzero((char*) ®_info, sizeof(struct ConsumerRegistrationInfo)); + + /* Fill the NEB consumer information structure */ + reg_info.CRIVersion= 1; // NEB version + /* NEB Consumer name */ + reg_info.CRIConsumerName= (BYTE *) "MySQL Database Server"; + /* Event of interest */ + reg_info.CRIEventName= (BYTE *) "NSS.ChangeVolState.Enter"; + reg_info.CRIUserParameter= NULL; // Consumer Info + reg_info.CRIEventFlags= 0; // Event flags + /* Consumer NLM handle */ + reg_info.CRIOwnerID= (LoadDefinitionStructure *)getnlmhandle(); + reg_info.CRIConsumerESR= NULL; // No consumer ESR required + reg_info.CRISecurityToken= 0; // No security token for the event + reg_info.CRIConsumerFlags= 0; // SMP_ENABLED_BIT; + reg_info.CRIFilterName= 0; // No event filtering + reg_info.CRIFilterDataLength= 0; // No filtering data + reg_info.CRIFilterData= 0; // No filtering data + /* Callback function for the event */ + (void *)reg_info.CRIConsumerCallback= (void *) refneb; + reg_info.CRIOrder= 0; // Event callback order + reg_info.CRIConsumerType= CHECK_CONSUMER; // Consumer type + + /* Register for the event with NEB */ + if (RegisterConsumer(®_info)) + { + consoleprintf("Failed to register for NSS Volume Deactivation event \n"); + return; + } + /* This ID is required for deregistration */ + neb_consumer_id= reg_info.CRIConsumerID; + + /* Get MySQL data volume name, stored in global variable datavolname */ + getvolumename(); + + /* + Get the NSS volume ID of the MySQL Data volume. + Volume ID is stored in a global variable + */ + getvolumeID((BYTE*) datavolname); +} + + +/** + Callback for NSS Volume Deactivation event. +*/ + +ulong neb_event_callback(struct EventBlock *eblock) +{ + EventChangeVolStateEnter_s *voldata; + extern bool nw_panic; + + voldata= (EventChangeVolStateEnter_s *)eblock->EBEventData; + + /* Deactivation of a volume */ + if ((voldata->oldState == zVOLSTATE_ACTIVE && + voldata->newState == zVOLSTATE_DEACTIVE || + voldata->newState == zVOLSTATE_MAINTENANCE)) + { + /* + Ensure that we bring down MySQL server only for MySQL data + volume deactivation + */ + if (!memcmp(&voldata->volID, &datavolid, sizeof(VolumeID_t))) + { + consoleprintf("MySQL data volume is deactivated, shutting down MySQL Server \n"); + event_flag= TRUE; + nw_panic = TRUE; + event_flag= TRUE; + kill_server(0); + } + } + return 0; +} + + +#define ADMIN_VOL_PATH "_ADMIN:/Volumes/" + +/** + Function to get NSS volume ID of the MySQL data. +*/ +static void getvolumeID(BYTE *volumeName) +{ + char path[zMAX_FULL_NAME]; + Key_t rootKey= 0, fileKey= 0; + QUAD getInfoMask; + zInfo_s info; + STATUS status; + + /* Get the root key */ + if ((status= zRootKey(0, &rootKey)) != zOK) + { + consoleprintf("\nGetNSSVolumeProperties - Failed to get root key, status: %d\n.", (int) status); + goto exit; + } + + /* + Get the file key. This is the key to the volume object in the + NSS admin volumes directory. + */ + + strxmov(path, (const char *) ADMIN_VOL_PATH, (const char *) volumeName, + NullS); + if ((status= zOpen(rootKey, zNSS_TASK, zNSPACE_LONG|zMODE_UTF8, + (BYTE *) path, zRR_READ_ACCESS, &fileKey)) != zOK) + { + consoleprintf("\nGetNSSVolumeProperties - Failed to get file, status: %d\n.", (int) status); + goto exit; + } + + getInfoMask= zGET_IDS | zGET_VOLUME_INFO ; + if ((status= zGetInfo(fileKey, getInfoMask, sizeof(info), + zINFO_VERSION_A, &info)) != zOK) + { + consoleprintf("\nGetNSSVolumeProperties - Failed in zGetInfo, status: %d\n.", (int) status); + goto exit; + } + + /* Copy the data to global variable */ + datavolid.timeLow= info.vol.volumeID.timeLow; + datavolid.timeMid= info.vol.volumeID.timeMid; + datavolid.timeHighAndVersion= info.vol.volumeID.timeHighAndVersion; + datavolid.clockSeqHighAndReserved= info.vol.volumeID.clockSeqHighAndReserved; + datavolid.clockSeqLow= info.vol.volumeID.clockSeqLow; + /* This is guranteed to be 6-byte length (but sizeof() would be better) */ + memcpy(datavolid.node, info.vol.volumeID.node, (unsigned int) 6); + +exit: + if (rootKey) + zClose(rootKey); + if (fileKey) + zClose(fileKey); +} + + +static void init_signals(void) +{ + int signals[] = {SIGINT,SIGILL,SIGFPE,SIGSEGV,SIGTERM,SIGABRT}; + + for (uint i=0 ; i < sizeof(signals)/sizeof(int) ; i++) + signal(signals[i], kill_server); + mysql_cb_init(); // initialize callbacks + +} + + +static void start_signal_handler(void) +{ + // Save vm id of this process + if (!opt_bootstrap) + create_pid_file(); + // no signal handler +} + + +/** + Warn if the data is on a Traditional volume. + + @note + Already done by mysqld_safe +*/ + +static void check_data_home(const char *path) +{ +} + +#endif /*__WIN__ || __NETWARE */ + +#ifdef HAVE_LINUXTHREADS +#define UNSAFE_DEFAULT_LINUX_THREADS 200 +#endif + + +#if BACKTRACE_DEMANGLE +#include +extern "C" char *my_demangle(const char *mangled_name, int *status) +{ + return abi::__cxa_demangle(mangled_name, NULL, NULL, status); +} +#endif + + +extern "C" sig_handler handle_segfault(int sig) +{ + time_t curr_time; + struct tm tm; + THD *thd=current_thd; + + /* + Strictly speaking, one needs a mutex here + but since we have got SIGSEGV already, things are a mess + so not having the mutex is not as bad as possibly using a buggy + mutex - so we keep things simple + */ + if (segfaulted) + { + fprintf(stderr, "Fatal " SIGNAL_FMT " while backtracing\n", sig); + exit(1); + } + + segfaulted = 1; + + curr_time= my_time(0); + localtime_r(&curr_time, &tm); + + fprintf(stderr,"\ +%02d%02d%02d %2d:%02d:%02d - mysqld got " SIGNAL_FMT " ;\n\ +This could be because you hit a bug. It is also possible that this binary\n\ +or one of the libraries it was linked against is corrupt, improperly built,\n\ +or misconfigured. This error can also be caused by malfunctioning hardware.\n", + tm.tm_year % 100, tm.tm_mon+1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec, + sig); + fprintf(stderr, "\ +We will try our best to scrape up some info that will hopefully help diagnose\n\ +the problem, but since we have already crashed, something is definitely wrong\n\ +and this may fail.\n\n"); + fprintf(stderr, "key_buffer_size=%lu\n", + (ulong) dflt_key_cache->key_cache_mem_size); + fprintf(stderr, "read_buffer_size=%ld\n", (long) global_system_variables.read_buff_size); + fprintf(stderr, "max_used_connections=%lu\n", max_used_connections); + fprintf(stderr, "max_threads=%u\n", thread_scheduler.max_threads); + fprintf(stderr, "threads_connected=%u\n", thread_count); + fprintf(stderr, "It is possible that mysqld could use up to \n\ +key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = %lu K\n\ +bytes of memory\n", ((ulong) dflt_key_cache->key_cache_mem_size + + (global_system_variables.read_buff_size + + global_system_variables.sortbuff_size) * + thread_scheduler.max_threads + + max_connections * sizeof(THD)) / 1024); + fprintf(stderr, "Hope that's ok; if not, decrease some variables in the equation.\n\n"); + +#if defined(HAVE_LINUXTHREADS) + if (sizeof(char*) == 4 && thread_count > UNSAFE_DEFAULT_LINUX_THREADS) + { + fprintf(stderr, "\ +You seem to be running 32-bit Linux and have %d concurrent connections.\n\ +If you have not changed STACK_SIZE in LinuxThreads and built the binary \n\ +yourself, LinuxThreads is quite likely to steal a part of the global heap for\n\ +the thread stack. Please read http://dev.mysql.com/doc/mysql/en/linux.html\n\n", + thread_count); + } +#endif /* HAVE_LINUXTHREADS */ + +#ifdef HAVE_STACKTRACE + if (!(test_flags & TEST_NO_STACKTRACE)) + { + fprintf(stderr,"thd: 0x%lx\n",(long) thd); + fprintf(stderr,"\ +Attempting backtrace. You can use the following information to find out\n\ +where mysqld died. If you see no messages after this, something went\n\ +terribly wrong...\n"); + my_print_stacktrace(thd ? (uchar*) thd->thread_stack : NULL, + my_thread_stack_size); + } + if (thd) + { + const char *kreason= "UNKNOWN"; + switch (thd->killed) { + case THD::NOT_KILLED: + kreason= "NOT_KILLED"; + break; + case THD::KILL_BAD_DATA: + kreason= "KILL_BAD_DATA"; + break; + case THD::KILL_CONNECTION: + kreason= "KILL_CONNECTION"; + break; + case THD::KILL_QUERY: + kreason= "KILL_QUERY"; + break; + case THD::KILLED_NO_VALUE: + kreason= "KILLED_NO_VALUE"; + break; + } + fprintf(stderr, "Trying to get some variables.\n\ +Some pointers may be invalid and cause the dump to abort...\n"); + my_safe_print_str("thd->query", thd->query, 1024); + fprintf(stderr, "thd->thread_id=%lu\n", (ulong) thd->thread_id); + fprintf(stderr, "thd->killed=%s\n", kreason); + } + fprintf(stderr, "\ +The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains\n\ +information that should help you find out what is causing the crash.\n"); + fflush(stderr); +#endif /* HAVE_STACKTRACE */ + +#ifdef HAVE_INITGROUPS + if (calling_initgroups) + fprintf(stderr, "\n\ +This crash occured while the server was calling initgroups(). This is\n\ +often due to the use of a mysqld that is statically linked against glibc\n\ +and configured to use LDAP in /etc/nsswitch.conf. You will need to either\n\ +upgrade to a version of glibc that does not have this problem (2.3.4 or\n\ +later when used with nscd), disable LDAP in your nsswitch.conf, or use a\n\ +mysqld that is not statically linked.\n"); +#endif + +#ifdef HAVE_NPTL + if (thd_lib_detected == THD_LIB_LT && !getenv("LD_ASSUME_KERNEL")) + fprintf(stderr,"\n\ +You are running a statically-linked LinuxThreads binary on an NPTL system.\n\ +This can result in crashes on some distributions due to LT/NPTL conflicts.\n\ +You should either build a dynamically-linked binary, or force LinuxThreads\n\ +to be used with the LD_ASSUME_KERNEL environment variable. Please consult\n\ +the documentation for your distribution on how to do that.\n"); +#endif + + if (locked_in_memory) + { + fprintf(stderr, "\n\ +The \"--memlock\" argument, which was enabled, uses system calls that are\n\ +unreliable and unstable on some operating systems and operating-system\n\ +versions (notably, some versions of Linux). This crash could be due to use\n\ +of those buggy OS calls. You should consider whether you really need the\n\ +\"--memlock\" parameter and/or consult the OS distributer about \"mlockall\"\n\ +bugs.\n"); + } + +#ifdef HAVE_WRITE_CORE + if (test_flags & TEST_CORE_ON_SIGNAL) + { + fprintf(stderr, "Writing a core file\n"); + fflush(stderr); + my_write_core(sig); + } +#endif + +#ifndef __WIN__ + /* On Windows, do not terminate, but pass control to exception filter */ + exit(1); +#endif +} + +#if !defined(__WIN__) && !defined(__NETWARE__) +#ifndef SA_RESETHAND +#define SA_RESETHAND 0 +#endif +#ifndef SA_NODEFER +#define SA_NODEFER 0 +#endif + +#ifndef EMBEDDED_LIBRARY + +static void init_signals(void) +{ + sigset_t set; + struct sigaction sa; + DBUG_ENTER("init_signals"); + + my_sigset(THR_SERVER_ALARM,print_signal_warning); // Should never be called! + + if (!(test_flags & TEST_NO_STACKTRACE) || (test_flags & TEST_CORE_ON_SIGNAL)) + { + sa.sa_flags = SA_RESETHAND | SA_NODEFER; + sigemptyset(&sa.sa_mask); + sigprocmask(SIG_SETMASK,&sa.sa_mask,NULL); + +#ifdef HAVE_STACKTRACE + my_init_stacktrace(); +#endif +#if defined(__amiga__) + sa.sa_handler=(void(*)())handle_segfault; +#else + sa.sa_handler=handle_segfault; +#endif + sigaction(SIGSEGV, &sa, NULL); + sigaction(SIGABRT, &sa, NULL); +#ifdef SIGBUS + sigaction(SIGBUS, &sa, NULL); +#endif + sigaction(SIGILL, &sa, NULL); + sigaction(SIGFPE, &sa, NULL); + } + +#ifdef HAVE_GETRLIMIT + if (test_flags & TEST_CORE_ON_SIGNAL) + { + /* Change limits so that we will get a core file */ + STRUCT_RLIMIT rl; + rl.rlim_cur = rl.rlim_max = RLIM_INFINITY; + if (setrlimit(RLIMIT_CORE, &rl) && global_system_variables.log_warnings) + sql_print_warning("setrlimit could not change the size of core files to 'infinity'; We may not be able to generate a core file on signals"); + } +#endif + (void) sigemptyset(&set); + my_sigset(SIGPIPE,SIG_IGN); + sigaddset(&set,SIGPIPE); +#ifndef IGNORE_SIGHUP_SIGQUIT + sigaddset(&set,SIGQUIT); + sigaddset(&set,SIGHUP); +#endif + sigaddset(&set,SIGTERM); + + /* Fix signals if blocked by parents (can happen on Mac OS X) */ + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = print_signal_warning; + sigaction(SIGTERM, &sa, (struct sigaction*) 0); + sa.sa_flags = 0; + sa.sa_handler = print_signal_warning; + sigaction(SIGHUP, &sa, (struct sigaction*) 0); +#ifdef SIGTSTP + sigaddset(&set,SIGTSTP); +#endif + if (thd_lib_detected != THD_LIB_LT) + sigaddset(&set,THR_SERVER_ALARM); + if (test_flags & TEST_SIGINT) + { + my_sigset(thr_kill_signal, end_thread_signal); + // May be SIGINT + sigdelset(&set, thr_kill_signal); + } + else + sigaddset(&set,SIGINT); + sigprocmask(SIG_SETMASK,&set,NULL); + pthread_sigmask(SIG_SETMASK,&set,NULL); + DBUG_VOID_RETURN; +} + + +static void start_signal_handler(void) +{ + int error; + pthread_attr_t thr_attr; + DBUG_ENTER("start_signal_handler"); + + (void) pthread_attr_init(&thr_attr); +#if !defined(HAVE_DEC_3_2_THREADS) + pthread_attr_setscope(&thr_attr,PTHREAD_SCOPE_SYSTEM); + (void) pthread_attr_setdetachstate(&thr_attr,PTHREAD_CREATE_DETACHED); + if (!(opt_specialflag & SPECIAL_NO_PRIOR)) + my_pthread_attr_setprio(&thr_attr,INTERRUPT_PRIOR); +#if defined(__ia64__) || defined(__ia64) + /* + Peculiar things with ia64 platforms - it seems we only have half the + stack size in reality, so we have to double it here + */ + pthread_attr_setstacksize(&thr_attr,my_thread_stack_size*2); +#else + pthread_attr_setstacksize(&thr_attr,my_thread_stack_size); +#endif +#endif + + (void) pthread_mutex_lock(&LOCK_thread_count); + if ((error=pthread_create(&signal_thread,&thr_attr,signal_hand,0))) + { + sql_print_error("Can't create interrupt-thread (error %d, errno: %d)", + error,errno); + exit(1); + } + (void) pthread_cond_wait(&COND_thread_count,&LOCK_thread_count); + pthread_mutex_unlock(&LOCK_thread_count); + + (void) pthread_attr_destroy(&thr_attr); + DBUG_VOID_RETURN; +} + + +/** This threads handles all signals and alarms. */ +/* ARGSUSED */ +pthread_handler_t signal_hand(void *arg __attribute__((unused))) +{ + sigset_t set; + int sig; + my_thread_init(); // Init new thread + DBUG_ENTER("signal_hand"); + signal_thread_in_use= 1; + + /* + Setup alarm handler + This should actually be '+ max_number_of_slaves' instead of +10, + but the +10 should be quite safe. + */ + init_thr_alarm(thread_scheduler.max_threads + + global_system_variables.max_insert_delayed_threads + 10); + if (thd_lib_detected != THD_LIB_LT && (test_flags & TEST_SIGINT)) + { + (void) sigemptyset(&set); // Setup up SIGINT for debug + (void) sigaddset(&set,SIGINT); // For debugging + (void) pthread_sigmask(SIG_UNBLOCK,&set,NULL); + } + (void) sigemptyset(&set); // Setup up SIGINT for debug +#ifdef USE_ONE_SIGNAL_HAND + (void) sigaddset(&set,THR_SERVER_ALARM); // For alarms +#endif +#ifndef IGNORE_SIGHUP_SIGQUIT + (void) sigaddset(&set,SIGQUIT); + (void) sigaddset(&set,SIGHUP); +#endif + (void) sigaddset(&set,SIGTERM); + (void) sigaddset(&set,SIGTSTP); + + /* Save pid to this process (or thread on Linux) */ + if (!opt_bootstrap) + create_pid_file(); + +#ifdef HAVE_STACK_TRACE_ON_SEGV + if (opt_do_pstack) + { + sprintf(pstack_file_name,"mysqld-%lu-%%d-%%d.backtrace", (ulong)getpid()); + pstack_install_segv_action(pstack_file_name); + } +#endif /* HAVE_STACK_TRACE_ON_SEGV */ + + /* + signal to start_signal_handler that we are ready + This works by waiting for start_signal_handler to free mutex, + after which we signal it that we are ready. + At this pointer there is no other threads running, so there + should not be any other pthread_cond_signal() calls. + */ + (void) pthread_mutex_lock(&LOCK_thread_count); + (void) pthread_mutex_unlock(&LOCK_thread_count); + (void) pthread_cond_broadcast(&COND_thread_count); + + (void) pthread_sigmask(SIG_BLOCK,&set,NULL); + for (;;) + { + int error; // Used when debugging + if (shutdown_in_progress && !abort_loop) + { + sig= SIGTERM; + error=0; + } + else + while ((error=my_sigwait(&set,&sig)) == EINTR) ; + if (cleanup_done) + { + DBUG_PRINT("quit",("signal_handler: calling my_thread_end()")); + my_thread_end(); + signal_thread_in_use= 0; + pthread_exit(0); // Safety + } + switch (sig) { + case SIGTERM: + case SIGQUIT: + case SIGKILL: +#ifdef EXTRA_DEBUG + sql_print_information("Got signal %d to shutdown mysqld",sig); +#endif + /* switch to the old log message processing */ + logger.set_handlers(LOG_FILE, opt_slow_log ? LOG_FILE:LOG_NONE, + opt_log ? LOG_FILE:LOG_NONE); + DBUG_PRINT("info",("Got signal: %d abort_loop: %d",sig,abort_loop)); + if (!abort_loop) + { + abort_loop=1; // mark abort for threads +#ifdef USE_ONE_SIGNAL_HAND + pthread_t tmp; + if (!(opt_specialflag & SPECIAL_NO_PRIOR)) + my_pthread_attr_setprio(&connection_attrib,INTERRUPT_PRIOR); + if (pthread_create(&tmp,&connection_attrib, kill_server_thread, + (void*) &sig)) + sql_print_error("Can't create thread to kill server"); +#else + kill_server((void*) sig); // MIT THREAD has a alarm thread +#endif + } + break; + case SIGHUP: + if (!abort_loop) + { + bool not_used; + mysql_print_status(); // Print some debug info + reload_acl_and_cache((THD*) 0, + (REFRESH_LOG | REFRESH_TABLES | REFRESH_FAST | + REFRESH_GRANT | + REFRESH_THREADS | REFRESH_HOSTS), + (TABLE_LIST*) 0, ¬_used); // Flush logs + } + /* reenable logs after the options were reloaded */ + if (log_output_options & LOG_NONE) + { + logger.set_handlers(LOG_FILE, + opt_slow_log ? LOG_TABLE : LOG_NONE, + opt_log ? LOG_TABLE : LOG_NONE); + } + else + { + logger.set_handlers(LOG_FILE, + opt_slow_log ? log_output_options : LOG_NONE, + opt_log ? log_output_options : LOG_NONE); + } + break; +#ifdef USE_ONE_SIGNAL_HAND + case THR_SERVER_ALARM: + process_alarm(sig); // Trigger alarms. + break; +#endif + default: +#ifdef EXTRA_DEBUG + sql_print_warning("Got signal: %d error: %d",sig,error); /* purecov: tested */ +#endif + break; /* purecov: tested */ + } + } + return(0); /* purecov: deadcode */ +} + +static void check_data_home(const char *path) +{} + +#endif /*!EMBEDDED_LIBRARY*/ +#endif /* __WIN__*/ + + +/** + All global error messages are sent here where the first one is stored + for the client. +*/ +/* ARGSUSED */ +extern "C" int my_message_sql(uint error, const char *str, myf MyFlags); + +int my_message_sql(uint error, const char *str, myf MyFlags) +{ + THD *thd; + DBUG_ENTER("my_message_sql"); + DBUG_PRINT("error", ("error: %u message: '%s'", error, str)); + + DBUG_ASSERT(str != NULL); + /* + An error should have a valid error number (!= 0), so it can be caught + in stored procedures by SQL exception handlers. + Calling my_error() with error == 0 is a bug. + Remaining known places to fix: + - storage/myisam/mi_create.c, my_printf_error() + TODO: + DBUG_ASSERT(error != 0); + */ + + if (error == 0) + { + /* At least, prevent new abuse ... */ + DBUG_ASSERT(strncmp(str, "MyISAM table", 12) == 0); + error= ER_UNKNOWN_ERROR; + } + + if ((thd= current_thd)) + { + /* + TODO: There are two exceptions mechanism (THD and sp_rcontext), + this could be improved by having a common stack of handlers. + */ + if (thd->handle_error(error, str, + MYSQL_ERROR::WARN_LEVEL_ERROR)) + DBUG_RETURN(0); + + thd->is_slave_error= 1; // needed to catch query errors during replication + + /* + thd->lex->current_select == 0 if lex structure is not inited + (not query command (COM_QUERY)) + */ + if (thd->lex->current_select && + thd->lex->current_select->no_error && !thd->is_fatal_error) + { + DBUG_PRINT("error", + ("Error converted to warning: current_select: no_error %d " + "fatal_error: %d", + (thd->lex->current_select ? + thd->lex->current_select->no_error : 0), + (int) thd->is_fatal_error)); + } + else + { + if (! thd->main_da.is_error()) // Return only first message + { + thd->main_da.set_error_status(thd, error, str); + } + query_cache_abort(&thd->net); + } + /* + If a continue handler is found, the error message will be cleared + by the stored procedures code. + */ + if (thd->spcont && + ! (MyFlags & ME_NO_SP_HANDLER) && + thd->spcont->handle_error(error, MYSQL_ERROR::WARN_LEVEL_ERROR, thd)) + { + /* + Do not push any warnings, a handled error must be completely + silenced. + */ + DBUG_RETURN(0); + } + + if (!thd->no_warnings_for_error && + !(MyFlags & ME_NO_WARNING_FOR_ERROR)) + { + /* + Suppress infinite recursion if there a memory allocation error + inside push_warning. + */ + thd->no_warnings_for_error= TRUE; + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, error, str); + thd->no_warnings_for_error= FALSE; + } + } + if (!thd || MyFlags & ME_NOREFRESH) + sql_print_error("%s: %s",my_progname,str); /* purecov: inspected */ + DBUG_RETURN(0); +} + + +#ifndef EMBEDDED_LIBRARY +extern "C" void *my_str_malloc_mysqld(size_t size); +extern "C" void my_str_free_mysqld(void *ptr); + +void *my_str_malloc_mysqld(size_t size) +{ + return my_malloc(size, MYF(MY_FAE)); +} + + +void my_str_free_mysqld(void *ptr) +{ + my_free((uchar*)ptr, MYF(MY_FAE)); +} +#endif /* EMBEDDED_LIBRARY */ + + +#ifdef __WIN__ + +pthread_handler_t handle_shutdown(void *arg) +{ + MSG msg; + my_thread_init(); + + /* this call should create the message queue for this thread */ + PeekMessage(&msg, NULL, 1, 65534,PM_NOREMOVE); +#if !defined(EMBEDDED_LIBRARY) + if (WaitForSingleObject(hEventShutdown,INFINITE)==WAIT_OBJECT_0) +#endif /* EMBEDDED_LIBRARY */ + kill_server(MYSQL_KILL_SIGNAL); + return 0; +} +#endif + +const char *load_default_groups[]= { +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE +"mysql_cluster", +#endif +"mysqld","server", MYSQL_BASE_VERSION, 0, 0}; + +#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY) +static const int load_default_groups_sz= +sizeof(load_default_groups)/sizeof(load_default_groups[0]); +#endif + + +/** + Initialize one of the global date/time format variables. + + @param format_type What kind of format should be supported + @param var_ptr Pointer to variable that should be updated + + @note + The default value is taken from either opt_date_time_formats[] or + the ISO format (ANSI SQL) + + @retval + 0 ok + @retval + 1 error +*/ + +static bool init_global_datetime_format(timestamp_type format_type, + DATE_TIME_FORMAT **var_ptr) +{ + /* Get command line option */ + const char *str= opt_date_time_formats[format_type]; + + if (!str) // No specified format + { + str= get_date_time_format_str(&known_date_time_formats[ISO_FORMAT], + format_type); + /* + Set the "command line" option to point to the generated string so + that we can set global formats back to default + */ + opt_date_time_formats[format_type]= str; + } + if (!(*var_ptr= date_time_format_make(format_type, str, strlen(str)))) + { + fprintf(stderr, "Wrong date/time format specifier: %s\n", str); + return 1; + } + return 0; +} + +SHOW_VAR com_status_vars[]= { + {"admin_commands", (char*) offsetof(STATUS_VAR, com_other), SHOW_LONG_STATUS}, + {"assign_to_keycache", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ASSIGN_TO_KEYCACHE]), SHOW_LONG_STATUS}, + {"alter_db", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_DB]), SHOW_LONG_STATUS}, + {"alter_db_upgrade", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_DB_UPGRADE]), SHOW_LONG_STATUS}, + {"alter_event", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_EVENT]), SHOW_LONG_STATUS}, + {"alter_function", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_FUNCTION]), SHOW_LONG_STATUS}, + {"alter_procedure", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_PROCEDURE]), SHOW_LONG_STATUS}, + {"alter_server", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_SERVER]), SHOW_LONG_STATUS}, + {"alter_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_TABLE]), SHOW_LONG_STATUS}, + {"alter_tablespace", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_TABLESPACE]), SHOW_LONG_STATUS}, + {"analyze", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ANALYZE]), SHOW_LONG_STATUS}, + {"backup_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_BACKUP_TABLE]), SHOW_LONG_STATUS}, + {"begin", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_BEGIN]), SHOW_LONG_STATUS}, + {"binlog", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_BINLOG_BASE64_EVENT]), SHOW_LONG_STATUS}, + {"call_procedure", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CALL]), SHOW_LONG_STATUS}, + {"change_db", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHANGE_DB]), SHOW_LONG_STATUS}, + {"change_master", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHANGE_MASTER]), SHOW_LONG_STATUS}, + {"check", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHECK]), SHOW_LONG_STATUS}, + {"checksum", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHECKSUM]), SHOW_LONG_STATUS}, + {"commit", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_COMMIT]), SHOW_LONG_STATUS}, + {"create_db", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_DB]), SHOW_LONG_STATUS}, + {"create_event", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_EVENT]), SHOW_LONG_STATUS}, + {"create_function", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_SPFUNCTION]), SHOW_LONG_STATUS}, + {"create_index", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_INDEX]), SHOW_LONG_STATUS}, + {"create_procedure", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_PROCEDURE]), SHOW_LONG_STATUS}, + {"create_server", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_SERVER]), SHOW_LONG_STATUS}, + {"create_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_TABLE]), SHOW_LONG_STATUS}, + {"create_trigger", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_TRIGGER]), SHOW_LONG_STATUS}, + {"create_udf", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_FUNCTION]), SHOW_LONG_STATUS}, + {"create_user", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_USER]), SHOW_LONG_STATUS}, + {"create_view", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_VIEW]), SHOW_LONG_STATUS}, + {"dealloc_sql", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DEALLOCATE_PREPARE]), SHOW_LONG_STATUS}, + {"delete", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DELETE]), SHOW_LONG_STATUS}, + {"delete_multi", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DELETE_MULTI]), SHOW_LONG_STATUS}, + {"do", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DO]), SHOW_LONG_STATUS}, + {"drop_db", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_DB]), SHOW_LONG_STATUS}, + {"drop_event", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_EVENT]), SHOW_LONG_STATUS}, + {"drop_function", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_FUNCTION]), SHOW_LONG_STATUS}, + {"drop_index", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_INDEX]), SHOW_LONG_STATUS}, + {"drop_procedure", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_PROCEDURE]), SHOW_LONG_STATUS}, + {"drop_server", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_SERVER]), SHOW_LONG_STATUS}, + {"drop_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_TABLE]), SHOW_LONG_STATUS}, + {"drop_trigger", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_TRIGGER]), SHOW_LONG_STATUS}, + {"drop_user", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_USER]), SHOW_LONG_STATUS}, + {"drop_view", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_VIEW]), SHOW_LONG_STATUS}, + {"empty_query", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_EMPTY_QUERY]), SHOW_LONG_STATUS}, + {"execute_sql", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_EXECUTE]), SHOW_LONG_STATUS}, + {"flush", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_FLUSH]), SHOW_LONG_STATUS}, + {"grant", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_GRANT]), SHOW_LONG_STATUS}, + {"ha_close", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HA_CLOSE]), SHOW_LONG_STATUS}, + {"ha_open", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HA_OPEN]), SHOW_LONG_STATUS}, + {"ha_read", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HA_READ]), SHOW_LONG_STATUS}, + {"help", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HELP]), SHOW_LONG_STATUS}, + {"insert", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_INSERT]), SHOW_LONG_STATUS}, + {"insert_select", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_INSERT_SELECT]), SHOW_LONG_STATUS}, + {"install_plugin", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_INSTALL_PLUGIN]), SHOW_LONG_STATUS}, + {"kill", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_KILL]), SHOW_LONG_STATUS}, + {"load", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_LOAD]), SHOW_LONG_STATUS}, + {"load_master_data", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_LOAD_MASTER_DATA]), SHOW_LONG_STATUS}, + {"load_master_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_LOAD_MASTER_TABLE]), SHOW_LONG_STATUS}, + {"lock_tables", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_LOCK_TABLES]), SHOW_LONG_STATUS}, + {"optimize", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_OPTIMIZE]), SHOW_LONG_STATUS}, + {"preload_keys", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PRELOAD_KEYS]), SHOW_LONG_STATUS}, + {"prepare_sql", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PREPARE]), SHOW_LONG_STATUS}, + {"purge", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PURGE]), SHOW_LONG_STATUS}, + {"purge_before_date", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PURGE_BEFORE]), SHOW_LONG_STATUS}, + {"release_savepoint", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RELEASE_SAVEPOINT]), SHOW_LONG_STATUS}, + {"rename_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RENAME_TABLE]), SHOW_LONG_STATUS}, + {"rename_user", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RENAME_USER]), SHOW_LONG_STATUS}, + {"repair", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REPAIR]), SHOW_LONG_STATUS}, + {"replace", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REPLACE]), SHOW_LONG_STATUS}, + {"replace_select", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REPLACE_SELECT]), SHOW_LONG_STATUS}, + {"reset", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RESET]), SHOW_LONG_STATUS}, + {"restore_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RESTORE_TABLE]), SHOW_LONG_STATUS}, + {"revoke", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REVOKE]), SHOW_LONG_STATUS}, + {"revoke_all", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REVOKE_ALL]), SHOW_LONG_STATUS}, + {"rollback", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ROLLBACK]), SHOW_LONG_STATUS}, + {"rollback_to_savepoint",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ROLLBACK_TO_SAVEPOINT]), SHOW_LONG_STATUS}, + {"savepoint", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SAVEPOINT]), SHOW_LONG_STATUS}, + {"select", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SELECT]), SHOW_LONG_STATUS}, + {"set_option", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SET_OPTION]), SHOW_LONG_STATUS}, + {"show_authors", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_AUTHORS]), SHOW_LONG_STATUS}, + {"show_binlog_events", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_BINLOG_EVENTS]), SHOW_LONG_STATUS}, + {"show_binlogs", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_BINLOGS]), SHOW_LONG_STATUS}, + {"show_charsets", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CHARSETS]), SHOW_LONG_STATUS}, + {"show_collations", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_COLLATIONS]), SHOW_LONG_STATUS}, + {"show_column_types", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_COLUMN_TYPES]), SHOW_LONG_STATUS}, + {"show_contributors", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CONTRIBUTORS]), SHOW_LONG_STATUS}, + {"show_create_db", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_DB]), SHOW_LONG_STATUS}, + {"show_create_event", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_EVENT]), SHOW_LONG_STATUS}, + {"show_create_func", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_FUNC]), SHOW_LONG_STATUS}, + {"show_create_proc", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_PROC]), SHOW_LONG_STATUS}, + {"show_create_table", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE]), SHOW_LONG_STATUS}, + {"show_create_trigger", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_TRIGGER]), SHOW_LONG_STATUS}, + {"show_databases", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_DATABASES]), SHOW_LONG_STATUS}, + {"show_engine_logs", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ENGINE_LOGS]), SHOW_LONG_STATUS}, + {"show_engine_mutex", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ENGINE_MUTEX]), SHOW_LONG_STATUS}, + {"show_engine_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ENGINE_STATUS]), SHOW_LONG_STATUS}, + {"show_events", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_EVENTS]), SHOW_LONG_STATUS}, + {"show_errors", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ERRORS]), SHOW_LONG_STATUS}, + {"show_fields", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_FIELDS]), SHOW_LONG_STATUS}, +#ifndef DBUG_OFF + {"show_function_code", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_FUNC_CODE]), SHOW_LONG_STATUS}, +#endif + {"show_function_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS_FUNC]), SHOW_LONG_STATUS}, + {"show_grants", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_GRANTS]), SHOW_LONG_STATUS}, + {"show_keys", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_KEYS]), SHOW_LONG_STATUS}, + {"show_master_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_MASTER_STAT]), SHOW_LONG_STATUS}, + {"show_new_master", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_NEW_MASTER]), SHOW_LONG_STATUS}, + {"show_open_tables", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_OPEN_TABLES]), SHOW_LONG_STATUS}, + {"show_plugins", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PLUGINS]), SHOW_LONG_STATUS}, + {"show_privileges", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PRIVILEGES]), SHOW_LONG_STATUS}, +#ifndef DBUG_OFF + {"show_procedure_code", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROC_CODE]), SHOW_LONG_STATUS}, +#endif + {"show_procedure_status",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS_PROC]), SHOW_LONG_STATUS}, + {"show_processlist", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROCESSLIST]), SHOW_LONG_STATUS}, + {"show_profile", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROFILE]), SHOW_LONG_STATUS}, + {"show_profiles", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROFILES]), SHOW_LONG_STATUS}, + {"show_slave_hosts", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_SLAVE_HOSTS]), SHOW_LONG_STATUS}, + {"show_slave_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_SLAVE_STAT]), SHOW_LONG_STATUS}, + {"show_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS]), SHOW_LONG_STATUS}, + {"show_storage_engines", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STORAGE_ENGINES]), SHOW_LONG_STATUS}, + {"show_table_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLE_STATUS]), SHOW_LONG_STATUS}, + {"show_tables", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLES]), SHOW_LONG_STATUS}, + {"show_triggers", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TRIGGERS]), SHOW_LONG_STATUS}, + {"show_variables", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_VARIABLES]), SHOW_LONG_STATUS}, + {"show_warnings", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_WARNS]), SHOW_LONG_STATUS}, + {"slave_start", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SLAVE_START]), SHOW_LONG_STATUS}, + {"slave_stop", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SLAVE_STOP]), SHOW_LONG_STATUS}, + {"stmt_close", (char*) offsetof(STATUS_VAR, com_stmt_close), SHOW_LONG_STATUS}, + {"stmt_execute", (char*) offsetof(STATUS_VAR, com_stmt_execute), SHOW_LONG_STATUS}, + {"stmt_fetch", (char*) offsetof(STATUS_VAR, com_stmt_fetch), SHOW_LONG_STATUS}, + {"stmt_prepare", (char*) offsetof(STATUS_VAR, com_stmt_prepare), SHOW_LONG_STATUS}, + {"stmt_reprepare", (char*) offsetof(STATUS_VAR, com_stmt_reprepare), SHOW_LONG_STATUS}, + {"stmt_reset", (char*) offsetof(STATUS_VAR, com_stmt_reset), SHOW_LONG_STATUS}, + {"stmt_send_long_data", (char*) offsetof(STATUS_VAR, com_stmt_send_long_data), SHOW_LONG_STATUS}, + {"truncate", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_TRUNCATE]), SHOW_LONG_STATUS}, + {"uninstall_plugin", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UNINSTALL_PLUGIN]), SHOW_LONG_STATUS}, + {"unlock_tables", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UNLOCK_TABLES]), SHOW_LONG_STATUS}, + {"update", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UPDATE]), SHOW_LONG_STATUS}, + {"update_multi", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UPDATE_MULTI]), SHOW_LONG_STATUS}, + {"xa_commit", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_COMMIT]),SHOW_LONG_STATUS}, + {"xa_end", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_END]),SHOW_LONG_STATUS}, + {"xa_prepare", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_PREPARE]),SHOW_LONG_STATUS}, + {"xa_recover", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_RECOVER]),SHOW_LONG_STATUS}, + {"xa_rollback", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_ROLLBACK]),SHOW_LONG_STATUS}, + {"xa_start", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_START]),SHOW_LONG_STATUS}, + {NullS, NullS, SHOW_LONG} +}; + +static int init_common_variables(const char *conf_file_name, int argc, + char **argv, const char **groups) +{ + char buff[FN_REFLEN], *s; + umask(((~my_umask) & 0666)); + my_decimal_set_zero(&decimal_zero); // set decimal_zero constant; + tzset(); // Set tzname + + max_system_variables.pseudo_thread_id= (ulong)~0; + server_start_time= flush_status_time= my_time(0); + rpl_filter= new Rpl_filter; + binlog_filter= new Rpl_filter; + if (!rpl_filter || !binlog_filter) + { + sql_perror("Could not allocate replication and binlog filters"); + return 1; + } + + if (init_thread_environment() || + mysql_init_variables()) + return 1; + +#ifdef HAVE_TZNAME + { + struct tm tm_tmp; + localtime_r(&server_start_time,&tm_tmp); + strmake(system_time_zone, tzname[tm_tmp.tm_isdst != 0 ? 1 : 0], + sizeof(system_time_zone)-1); + + } +#endif + /* + We set SYSTEM time zone as reasonable default and + also for failure of my_tz_init() and bootstrap mode. + If user explicitly set time zone with --default-time-zone + option we will change this value in my_tz_init(). + */ + global_system_variables.time_zone= my_tz_SYSTEM; + + /* + Init mutexes for the global MYSQL_BIN_LOG objects. + As safe_mutex depends on what MY_INIT() does, we can't init the mutexes of + global MYSQL_BIN_LOGs in their constructors, because then they would be + inited before MY_INIT(). So we do it here. + */ + mysql_bin_log.init_pthread_objects(); + + if (gethostname(glob_hostname,sizeof(glob_hostname)) < 0) + { + strmake(glob_hostname, STRING_WITH_LEN("localhost")); + sql_print_warning("gethostname failed, using '%s' as hostname", + glob_hostname); + strmake(pidfile_name, STRING_WITH_LEN("mysql")); + } + else + strmake(pidfile_name, glob_hostname, sizeof(pidfile_name)-5); + strmov(fn_ext(pidfile_name),".pid"); // Add proper extension + + /* + Add server status variables to the dynamic list of + status variables that is shown by SHOW STATUS. + Later, in plugin_init, and mysql_install_plugin + new entries could be added to that list. + */ + if (add_status_vars(status_vars)) + return 1; // an error was already reported + +#ifndef DBUG_OFF + /* + We have few debug-only commands in com_status_vars, only visible in debug + builds. for simplicity we enable the assert only in debug builds + + There are 8 Com_ variables which don't have corresponding SQLCOM_ values: + (TODO strictly speaking they shouldn't be here, should not have Com_ prefix + that is. Perhaps Stmt_ ? Comstmt_ ? Prepstmt_ ?) + + Com_admin_commands => com_other + Com_stmt_close => com_stmt_close + Com_stmt_execute => com_stmt_execute + Com_stmt_fetch => com_stmt_fetch + Com_stmt_prepare => com_stmt_prepare + Com_stmt_reprepare => com_stmt_reprepare + Com_stmt_reset => com_stmt_reset + Com_stmt_send_long_data => com_stmt_send_long_data + + With this correction the number of Com_ variables (number of elements in + the array, excluding the last element - terminator) must match the number + of SQLCOM_ constants. + */ + compile_time_assert(sizeof(com_status_vars)/sizeof(com_status_vars[0]) - 1 == + SQLCOM_END + 8); +#endif + + orig_argc=argc; + orig_argv=argv; + load_defaults(conf_file_name, groups, &argc, &argv); + defaults_argv=argv; + defaults_argc=argc; + if (get_options(&defaults_argc, defaults_argv)) + return 1; + set_server_version(); + + DBUG_PRINT("info",("%s Ver %s for %s on %s\n",my_progname, + server_version, SYSTEM_TYPE,MACHINE_TYPE)); + +#ifdef HAVE_LARGE_PAGES + /* Initialize large page size */ + if (opt_large_pages && (opt_large_page_size= my_get_large_page_size())) + { + my_use_large_pages= 1; + my_large_page_size= opt_large_page_size; + } +#endif /* HAVE_LARGE_PAGES */ + + /* connections and databases needs lots of files */ + { + uint files, wanted_files, max_open_files; + + /* MyISAM requires two file handles per table. */ + wanted_files= 10+max_connections+table_cache_size*2; + /* + We are trying to allocate no less than max_connections*5 file + handles (i.e. we are trying to set the limit so that they will + be available). In addition, we allocate no less than how much + was already allocated. However below we report a warning and + recompute values only if we got less file handles than were + explicitly requested. No warning and re-computation occur if we + can't get max_connections*5 but still got no less than was + requested (value of wanted_files). + */ + max_open_files= max(max(wanted_files, max_connections*5), + open_files_limit); + files= my_set_max_open_files(max_open_files); + + if (files < wanted_files) + { + if (!open_files_limit) + { + /* + If we have requested too much file handles than we bring + max_connections in supported bounds. + */ + max_connections= (ulong) min(files-10-TABLE_OPEN_CACHE_MIN*2, + max_connections); + /* + Decrease table_cache_size according to max_connections, but + not below TABLE_OPEN_CACHE_MIN. Outer min() ensures that we + never increase table_cache_size automatically (that could + happen if max_connections is decreased above). + */ + table_cache_size= (ulong) min(max((files-10-max_connections)/2, + TABLE_OPEN_CACHE_MIN), + table_cache_size); + DBUG_PRINT("warning", + ("Changed limits: max_open_files: %u max_connections: %ld table_cache: %ld", + files, max_connections, table_cache_size)); + if (global_system_variables.log_warnings) + sql_print_warning("Changed limits: max_open_files: %u max_connections: %ld table_cache: %ld", + files, max_connections, table_cache_size); + } + else if (global_system_variables.log_warnings) + sql_print_warning("Could not increase number of max_open_files to more than %u (request: %u)", files, wanted_files); + } + open_files_limit= files; + } + unireg_init(opt_specialflag); /* Set up extern variabels */ + if (init_errmessage()) /* Read error messages from file */ + return 1; + init_client_errs(); + lex_init(); + if (item_create_init()) + return 1; + item_init(); + if (set_var_init()) + return 1; +#ifdef HAVE_REPLICATION + if (init_replication_sys_vars()) + return 1; +#endif + mysys_uses_curses=0; +#ifdef USE_REGEX + my_regex_init(&my_charset_latin1); +#endif + /* + Process a comma-separated character set list and choose + the first available character set. This is mostly for + test purposes, to be able to start "mysqld" even if + the requested character set is not available (see bug#18743). + */ + for (;;) + { + char *next_character_set_name= strchr(default_character_set_name, ','); + if (next_character_set_name) + *next_character_set_name++= '\0'; + if (!(default_charset_info= + get_charset_by_csname(default_character_set_name, + MY_CS_PRIMARY, MYF(MY_WME)))) + { + if (next_character_set_name) + { + default_character_set_name= next_character_set_name; + default_collation_name= 0; // Ignore collation + } + else + return 1; // Eof of the list + } + else + break; + } + + if (default_collation_name) + { + CHARSET_INFO *default_collation; + default_collation= get_charset_by_name(default_collation_name, MYF(0)); + if (!default_collation) + { + sql_print_error(ER(ER_UNKNOWN_COLLATION), default_collation_name); + return 1; + } + if (!my_charset_same(default_charset_info, default_collation)) + { + sql_print_error(ER(ER_COLLATION_CHARSET_MISMATCH), + default_collation_name, + default_charset_info->csname); + return 1; + } + default_charset_info= default_collation; + } + /* Set collactions that depends on the default collation */ + global_system_variables.collation_server= default_charset_info; + global_system_variables.collation_database= default_charset_info; + global_system_variables.collation_connection= default_charset_info; + global_system_variables.character_set_results= default_charset_info; + global_system_variables.character_set_client= default_charset_info; + + if (!(character_set_filesystem= + get_charset_by_csname(character_set_filesystem_name, + MY_CS_PRIMARY, MYF(MY_WME)))) + return 1; + global_system_variables.character_set_filesystem= character_set_filesystem; + + if (!(my_default_lc_time_names= + my_locale_by_name(lc_time_names_name))) + { + sql_print_error("Unknown locale: '%s'", lc_time_names_name); + return 1; + } + global_system_variables.lc_time_names= my_default_lc_time_names; + + sys_init_connect.value_length= 0; + if ((sys_init_connect.value= opt_init_connect)) + sys_init_connect.value_length= strlen(opt_init_connect); + else + sys_init_connect.value=my_strdup("",MYF(0)); + sys_init_connect.is_os_charset= TRUE; + + sys_init_slave.value_length= 0; + if ((sys_init_slave.value= opt_init_slave)) + sys_init_slave.value_length= strlen(opt_init_slave); + else + sys_init_slave.value=my_strdup("",MYF(0)); + sys_init_slave.is_os_charset= TRUE; + + /* check log options and issue warnings if needed */ + if (opt_log && opt_logname && !(log_output_options & LOG_FILE) && + !(log_output_options & LOG_NONE)) + sql_print_warning("Although a path was specified for the " + "--log option, log tables are used. " + "To enable logging to files use the --log-output option."); + + if (opt_slow_log && opt_slow_logname && !(log_output_options & LOG_FILE) + && !(log_output_options & LOG_NONE)) + sql_print_warning("Although a path was specified for the " + "--log_slow_queries option, log tables are used. " + "To enable logging to files use the --log-output=file option."); + + s= opt_logname ? opt_logname : make_default_log_name(buff, ".log"); + sys_var_general_log_path.value= my_strdup(s, MYF(0)); + sys_var_general_log_path.value_length= strlen(s); + + s= opt_slow_logname ? opt_slow_logname : make_default_log_name(buff, "-slow.log"); + sys_var_slow_log_path.value= my_strdup(s, MYF(0)); + sys_var_slow_log_path.value_length= strlen(s); + +#if (ENABLE_TEMP_POOL) + if (use_temp_pool && bitmap_init(&temp_pool,0,1024,1)) + return 1; +#else + use_temp_pool= 0; +#endif + + if (my_database_names_init()) + return 1; + + /* + Ensure that lower_case_table_names is set on system where we have case + insensitive names. If this is not done the users MyISAM tables will + get corrupted if accesses with names of different case. + */ + DBUG_PRINT("info", ("lower_case_table_names: %d", lower_case_table_names)); + lower_case_file_system= test_if_case_insensitive(mysql_real_data_home); + if (!lower_case_table_names && lower_case_file_system == 1) + { + if (lower_case_table_names_used) + { + if (global_system_variables.log_warnings) + sql_print_warning("\ +You have forced lower_case_table_names to 0 through a command-line \ +option, even though your file system '%s' is case insensitive. This means \ +that you can corrupt a MyISAM table by accessing it with different cases. \ +You should consider changing lower_case_table_names to 1 or 2", + mysql_real_data_home); + } + else + { + if (global_system_variables.log_warnings) + sql_print_warning("Setting lower_case_table_names=2 because file system for %s is case insensitive", mysql_real_data_home); + lower_case_table_names= 2; + } + } + else if (lower_case_table_names == 2 && + !(lower_case_file_system= + (test_if_case_insensitive(mysql_real_data_home) == 1))) + { + if (global_system_variables.log_warnings) + sql_print_warning("lower_case_table_names was set to 2, even though your " + "the file system '%s' is case sensitive. Now setting " + "lower_case_table_names to 0 to avoid future problems.", + mysql_real_data_home); + lower_case_table_names= 0; + } + else + { + lower_case_file_system= + (test_if_case_insensitive(mysql_real_data_home) == 1); + } + + /* Reset table_alias_charset, now that lower_case_table_names is set. */ + table_alias_charset= (lower_case_table_names ? + files_charset_info : + &my_charset_bin); + + return 0; +} + + +static int init_thread_environment() +{ + (void) pthread_mutex_init(&LOCK_mysql_create_db,MY_MUTEX_INIT_SLOW); + (void) pthread_mutex_init(&LOCK_lock_db,MY_MUTEX_INIT_SLOW); + (void) pthread_mutex_init(&LOCK_Acl,MY_MUTEX_INIT_SLOW); + (void) pthread_mutex_init(&LOCK_open, MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_thread_count,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_mapped_file,MY_MUTEX_INIT_SLOW); + (void) pthread_mutex_init(&LOCK_status,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_error_log,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_delayed_insert,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_delayed_status,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_delayed_create,MY_MUTEX_INIT_SLOW); + (void) pthread_mutex_init(&LOCK_manager,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_crypt,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_bytes_sent,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_bytes_received,MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_user_conn, MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_active_mi, MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_global_system_variables, MY_MUTEX_INIT_FAST); + (void) my_rwlock_init(&LOCK_system_variables_hash, NULL); + (void) pthread_mutex_init(&LOCK_global_read_lock, MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_prepared_stmt_count, MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_uuid_generator, MY_MUTEX_INIT_FAST); + (void) pthread_mutex_init(&LOCK_connection_count, MY_MUTEX_INIT_FAST); +#ifdef HAVE_OPENSSL + (void) pthread_mutex_init(&LOCK_des_key_file,MY_MUTEX_INIT_FAST); +#ifndef HAVE_YASSL + openssl_stdlocks= (openssl_lock_t*) OPENSSL_malloc(CRYPTO_num_locks() * + sizeof(openssl_lock_t)); + for (int i= 0; i < CRYPTO_num_locks(); ++i) + (void) my_rwlock_init(&openssl_stdlocks[i].lock, NULL); + CRYPTO_set_dynlock_create_callback(openssl_dynlock_create); + CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy); + CRYPTO_set_dynlock_lock_callback(openssl_lock); + CRYPTO_set_locking_callback(openssl_lock_function); + CRYPTO_set_id_callback(openssl_id_function); +#endif +#endif + (void) my_rwlock_init(&LOCK_sys_init_connect, NULL); + (void) my_rwlock_init(&LOCK_sys_init_slave, NULL); + (void) my_rwlock_init(&LOCK_grant, NULL); + (void) pthread_cond_init(&COND_thread_count,NULL); + (void) pthread_cond_init(&COND_refresh,NULL); + (void) pthread_cond_init(&COND_global_read_lock,NULL); + (void) pthread_cond_init(&COND_thread_cache,NULL); + (void) pthread_cond_init(&COND_flush_thread_cache,NULL); + (void) pthread_cond_init(&COND_manager,NULL); +#ifdef HAVE_REPLICATION + (void) pthread_mutex_init(&LOCK_rpl_status, MY_MUTEX_INIT_FAST); + (void) pthread_cond_init(&COND_rpl_status, NULL); +#endif + (void) pthread_mutex_init(&LOCK_server_started, MY_MUTEX_INIT_FAST); + (void) pthread_cond_init(&COND_server_started,NULL); + sp_cache_init(); +#ifdef HAVE_EVENT_SCHEDULER + Events::init_mutexes(); +#endif + /* Parameter for threads created for connections */ + (void) pthread_attr_init(&connection_attrib); + (void) pthread_attr_setdetachstate(&connection_attrib, + PTHREAD_CREATE_DETACHED); + pthread_attr_setscope(&connection_attrib, PTHREAD_SCOPE_SYSTEM); + if (!(opt_specialflag & SPECIAL_NO_PRIOR)) + my_pthread_attr_setprio(&connection_attrib,WAIT_PRIOR); + + if (pthread_key_create(&THR_THD,NULL) || + pthread_key_create(&THR_MALLOC,NULL)) + { + sql_print_error("Can't create thread-keys"); + return 1; + } + return 0; +} + + +#if defined(HAVE_OPENSSL) && !defined(HAVE_YASSL) +static unsigned long openssl_id_function() +{ + return (unsigned long) pthread_self(); +} + + +static openssl_lock_t *openssl_dynlock_create(const char *file, int line) +{ + openssl_lock_t *lock= new openssl_lock_t; + my_rwlock_init(&lock->lock, NULL); + return lock; +} + + +static void openssl_dynlock_destroy(openssl_lock_t *lock, const char *file, + int line) +{ + rwlock_destroy(&lock->lock); + delete lock; +} + + +static void openssl_lock_function(int mode, int n, const char *file, int line) +{ + if (n < 0 || n > CRYPTO_num_locks()) + { + /* Lock number out of bounds. */ + sql_print_error("Fatal: OpenSSL interface problem (n = %d)", n); + abort(); + } + openssl_lock(mode, &openssl_stdlocks[n], file, line); +} + + +static void openssl_lock(int mode, openssl_lock_t *lock, const char *file, + int line) +{ + int err; + char const *what; + + switch (mode) { + case CRYPTO_LOCK|CRYPTO_READ: + what = "read lock"; + err = rw_rdlock(&lock->lock); + break; + case CRYPTO_LOCK|CRYPTO_WRITE: + what = "write lock"; + err = rw_wrlock(&lock->lock); + break; + case CRYPTO_UNLOCK|CRYPTO_READ: + case CRYPTO_UNLOCK|CRYPTO_WRITE: + what = "unlock"; + err = rw_unlock(&lock->lock); + break; + default: + /* Unknown locking mode. */ + sql_print_error("Fatal: OpenSSL interface problem (mode=0x%x)", mode); + abort(); + } + if (err) + { + sql_print_error("Fatal: can't %s OpenSSL lock", what); + abort(); + } +} +#endif /* HAVE_OPENSSL */ + + +#ifndef EMBEDDED_LIBRARY + +static void init_ssl() +{ +#ifdef HAVE_OPENSSL + if (opt_use_ssl) + { + enum enum_ssl_init_error error= SSL_INITERR_NOERROR; + + /* having ssl_acceptor_fd != 0 signals the use of SSL */ + ssl_acceptor_fd= new_VioSSLAcceptorFd(opt_ssl_key, opt_ssl_cert, + opt_ssl_ca, opt_ssl_capath, + opt_ssl_cipher, &error); + DBUG_PRINT("info",("ssl_acceptor_fd: 0x%lx", (long) ssl_acceptor_fd)); + if (!ssl_acceptor_fd) + { + sql_print_warning("Failed to setup SSL"); + sql_print_warning("SSL error: %s", sslGetErrString(error)); + opt_use_ssl = 0; + have_ssl= SHOW_OPTION_DISABLED; + } + } + else + { + have_ssl= SHOW_OPTION_DISABLED; + } + if (des_key_file) + load_des_key_file(des_key_file); +#endif /* HAVE_OPENSSL */ +} + + +static void end_ssl() +{ +#ifdef HAVE_OPENSSL + if (ssl_acceptor_fd) + { + free_vio_ssl_acceptor_fd(ssl_acceptor_fd); + ssl_acceptor_fd= 0; + } +#endif /* HAVE_OPENSSL */ +} + +#endif /* EMBEDDED_LIBRARY */ + + +static int init_server_components() +{ + DBUG_ENTER("init_server_components"); + /* + We need to call each of these following functions to ensure that + all things are initialized so that unireg_abort() doesn't fail + */ + if (table_cache_init() | table_def_init() | hostname_cache_init()) + unireg_abort(1); + + query_cache_result_size_limit(query_cache_limit); + query_cache_set_min_res_unit(query_cache_min_res_unit); + query_cache_init(); + query_cache_resize(query_cache_size); + randominit(&sql_rand,(ulong) server_start_time,(ulong) server_start_time/2); + setup_fpu(); + init_thr_lock(); +#ifdef HAVE_REPLICATION + init_slave_list(); +#endif + + /* Setup logs */ + + /* + Enable old-fashioned error log, except when the user has requested + help information. Since the implementation of plugin server + variables the help output is now written much later. + */ + if (opt_error_log && !opt_help) + { + if (!log_error_file_ptr[0]) + fn_format(log_error_file, pidfile_name, mysql_data_home, ".err", + MY_REPLACE_EXT); /* replace '.' by '.err', bug#4997 */ + else + fn_format(log_error_file, log_error_file_ptr, mysql_data_home, ".err", + MY_UNPACK_FILENAME | MY_SAFE_PATH); + if (!log_error_file[0]) + opt_error_log= 1; // Too long file name + else + { +#ifndef EMBEDDED_LIBRARY + if (freopen(log_error_file, "a+", stdout)) +#endif + { + freopen(log_error_file, "a+", stderr); + setbuf(stderr, NULL); + } + } + } + + if (xid_cache_init()) + { + sql_print_error("Out of memory"); + unireg_abort(1); + } + + /* need to configure logging before initializing storage engines */ + if (opt_update_log) + { + /* + Update log is removed since 5.0. But we still accept the option. + The idea is if the user already uses the binlog and the update log, + we completely ignore any option/variable related to the update log, like + if the update log did not exist. But if the user uses only the update + log, then we translate everything into binlog for him (with warnings). + Implementation of the above : + - If mysqld is started with --log-update and --log-bin, + ignore --log-update (print a warning), push a warning when SQL_LOG_UPDATE + is used, and turn off --sql-bin-update-same. + This will completely ignore SQL_LOG_UPDATE + - If mysqld is started with --log-update only, + change it to --log-bin (with the filename passed to log-update, + plus '-bin') (print a warning), push a warning when SQL_LOG_UPDATE is + used, and turn on --sql-bin-update-same. + This will translate SQL_LOG_UPDATE to SQL_LOG_BIN. + + Note that we tell the user that --sql-bin-update-same is deprecated and + does nothing, and we don't take into account if he used this option or + not; but internally we give this variable a value to have the behaviour + we want (i.e. have SQL_LOG_UPDATE influence SQL_LOG_BIN or not). + As sql-bin-update-same, log-update and log-bin cannot be changed by the + user after starting the server (they are not variables), the user will + not later interfere with the settings we do here. + */ + if (opt_bin_log) + { + opt_sql_bin_update= 0; + sql_print_error("The update log is no longer supported by MySQL in \ +version 5.0 and above. It is replaced by the binary log."); + } + else + { + opt_sql_bin_update= 1; + opt_bin_log= 1; + if (opt_update_logname) + { + /* as opt_bin_log==0, no need to free opt_bin_logname */ + if (!(opt_bin_logname= my_strdup(opt_update_logname, MYF(MY_WME)))) + { + sql_print_error("Out of memory"); + return EXIT_OUT_OF_MEMORY; + } + sql_print_error("The update log is no longer supported by MySQL in \ +version 5.0 and above. It is replaced by the binary log. Now starting MySQL \ +with --log-bin='%s' instead.",opt_bin_logname); + } + else + sql_print_error("The update log is no longer supported by MySQL in \ +version 5.0 and above. It is replaced by the binary log. Now starting MySQL \ +with --log-bin instead."); + } + } + if (opt_log_slave_updates && !opt_bin_log) + { + sql_print_error("You need to use --log-bin to make " + "--log-slave-updates work."); + unireg_abort(1); + } + if (!opt_bin_log) + { + if (opt_binlog_format_id != BINLOG_FORMAT_UNSPEC) + { + sql_print_error("You need to use --log-bin to make " + "--binlog-format work."); + unireg_abort(1); + } + else + { + global_system_variables.binlog_format= BINLOG_FORMAT_STMT; + } + } + else + if (opt_binlog_format_id == BINLOG_FORMAT_UNSPEC) + global_system_variables.binlog_format= BINLOG_FORMAT_STMT; + else + { + DBUG_ASSERT(global_system_variables.binlog_format != BINLOG_FORMAT_UNSPEC); + } + + /* Check that we have not let the format to unspecified at this point */ + DBUG_ASSERT((uint)global_system_variables.binlog_format <= + array_elements(binlog_format_names)-1); + +#ifdef HAVE_REPLICATION + if (opt_log_slave_updates && replicate_same_server_id) + { + sql_print_error("\ +using --replicate-same-server-id in conjunction with \ +--log-slave-updates is impossible, it would lead to infinite loops in this \ +server."); + unireg_abort(1); + } +#endif + + if (opt_bin_log) + { + char buf[FN_REFLEN]; + const char *ln; + ln= mysql_bin_log.generate_name(opt_bin_logname, "-bin", 1, buf); + if (!opt_bin_logname && !opt_binlog_index_name) + { + /* + User didn't give us info to name the binlog index file. + Picking `hostname`-bin.index like did in 4.x, causes replication to + fail if the hostname is changed later. So, we would like to instead + require a name. But as we don't want to break many existing setups, we + only give warning, not error. + */ + sql_print_warning("No argument was provided to --log-bin, and " + "--log-bin-index was not used; so replication " + "may break when this MySQL server acts as a " + "master and has his hostname changed!! Please " + "use '--log-bin=%s' to avoid this problem.", ln); + } + if (ln == buf) + { + my_free(opt_bin_logname, MYF(MY_ALLOW_ZERO_PTR)); + opt_bin_logname=my_strdup(buf, MYF(0)); + } + if (mysql_bin_log.open_index_file(opt_binlog_index_name, ln)) + { + unireg_abort(1); + } + } + + /* call ha_init_key_cache() on all key caches to init them */ + process_key_caches(&ha_init_key_cache); + + /* Allow storage engine to give real error messages */ + if (ha_init_errors()) + DBUG_RETURN(1); + + { + if (plugin_init(&defaults_argc, defaults_argv, + (opt_noacl ? PLUGIN_INIT_SKIP_PLUGIN_TABLE : 0) | + (opt_help ? PLUGIN_INIT_SKIP_INITIALIZATION : 0))) + { + sql_print_error("Failed to initialize plugins."); + unireg_abort(1); + } + plugins_are_initialized= TRUE; /* Don't separate from init function */ + } + + if (opt_help) + unireg_abort(0); + + /* we do want to exit if there are any other unknown options */ + if (defaults_argc > 1) + { + int ho_error; + char **tmp_argv= defaults_argv; + struct my_option no_opts[]= + { + {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0} + }; + /* + We need to eat any 'loose' arguments first before we conclude + that there are unprocessed options. + But we need to preserve defaults_argv pointer intact for + free_defaults() to work. Thus we use a copy here. + */ + my_getopt_skip_unknown= 0; + + if ((ho_error= handle_options(&defaults_argc, &tmp_argv, no_opts, + mysqld_get_one_option))) + unireg_abort(ho_error); + my_getopt_skip_unknown= TRUE; + + if (defaults_argc) + { + fprintf(stderr, "%s: Too many arguments (first extra is '%s').\n" + "Use --verbose --help to get a list of available options\n", + my_progname, *tmp_argv); + unireg_abort(1); + } + } + + /* if the errmsg.sys is not loaded, terminate to maintain behaviour */ + if (!errmesg[0][0]) + unireg_abort(1); + + /* We have to initialize the storage engines before CSV logging */ + if (ha_init()) + { + sql_print_error("Can't init databases"); + unireg_abort(1); + } + +#ifdef WITH_CSV_STORAGE_ENGINE + if (opt_bootstrap) + log_output_options= LOG_FILE; + else + logger.init_log_tables(); + + if (log_output_options & LOG_NONE) + { + /* + Issue a warining if there were specified additional options to the + log-output along with NONE. Probably this wasn't what user wanted. + */ + if ((log_output_options & LOG_NONE) && (log_output_options & ~LOG_NONE)) + sql_print_warning("There were other values specified to " + "log-output besides NONE. Disabling slow " + "and general logs anyway."); + logger.set_handlers(LOG_FILE, LOG_NONE, LOG_NONE); + } + else + { + /* fall back to the log files if tables are not present */ + LEX_STRING csv_name={C_STRING_WITH_LEN("csv")}; + if (!plugin_is_ready(&csv_name, MYSQL_STORAGE_ENGINE_PLUGIN)) + { + /* purecov: begin inspected */ + sql_print_error("CSV engine is not present, falling back to the " + "log files"); + log_output_options= (log_output_options & ~LOG_TABLE) | LOG_FILE; + /* purecov: end */ + } + + logger.set_handlers(LOG_FILE, opt_slow_log ? log_output_options:LOG_NONE, + opt_log ? log_output_options:LOG_NONE); + } +#else + logger.set_handlers(LOG_FILE, opt_slow_log ? LOG_FILE:LOG_NONE, + opt_log ? LOG_FILE:LOG_NONE); +#endif + + /* + Check that the default storage engine is actually available. + */ + if (default_storage_engine_str) + { + LEX_STRING name= { default_storage_engine_str, + strlen(default_storage_engine_str) }; + plugin_ref plugin; + handlerton *hton; + + if ((plugin= ha_resolve_by_name(0, &name))) + hton= plugin_data(plugin, handlerton*); + else + { + sql_print_error("Unknown/unsupported table type: %s", + default_storage_engine_str); + unireg_abort(1); + } + if (!ha_storage_engine_is_enabled(hton)) + { + if (!opt_bootstrap) + { + sql_print_error("Default storage engine (%s) is not available", + default_storage_engine_str); + unireg_abort(1); + } + DBUG_ASSERT(global_system_variables.table_plugin); + } + else + { + /* + Need to unlock as global_system_variables.table_plugin + was acquired during plugin_init() + */ + plugin_unlock(0, global_system_variables.table_plugin); + global_system_variables.table_plugin= plugin; + } + } + + tc_log= (total_ha_2pc > 1 ? (opt_bin_log ? + (TC_LOG *) &mysql_bin_log : + (TC_LOG *) &tc_log_mmap) : + (TC_LOG *) &tc_log_dummy); + + if (tc_log->open(opt_bin_log ? opt_bin_logname : opt_tc_log_file)) + { + sql_print_error("Can't init tc log"); + unireg_abort(1); + } + + if (ha_recover(0)) + { + unireg_abort(1); + } + + if (opt_bin_log && mysql_bin_log.open(opt_bin_logname, LOG_BIN, 0, + WRITE_CACHE, 0, max_binlog_size, 0)) + unireg_abort(1); + +#ifdef HAVE_REPLICATION + if (opt_bin_log && expire_logs_days) + { + time_t purge_time= server_start_time - expire_logs_days*24*60*60; + if (purge_time >= 0) + mysql_bin_log.purge_logs_before_date(purge_time); + } +#endif +#ifdef __NETWARE__ + /* Increasing stacksize of threads on NetWare */ + pthread_attr_setstacksize(&connection_attrib, NW_THD_STACKSIZE); +#endif + + if (opt_myisam_log) + (void) mi_log(1); + +#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && !defined(EMBEDDED_LIBRARY) + if (locked_in_memory && !getuid()) + { + if (setreuid((uid_t)-1, 0) == -1) + { // this should never happen + sql_perror("setreuid"); + unireg_abort(1); + } + if (mlockall(MCL_CURRENT)) + { + if (global_system_variables.log_warnings) + sql_print_warning("Failed to lock memory. Errno: %d\n",errno); + locked_in_memory= 0; + } + if (user_info) + set_user(mysqld_user, user_info); + } + else +#endif + locked_in_memory=0; + + ft_init_stopwords(); + + init_max_user_conn(); + init_update_queries(); + DBUG_RETURN(0); +} + + +#ifndef EMBEDDED_LIBRARY + +static void create_shutdown_thread() +{ +#ifdef __WIN__ + hEventShutdown=CreateEvent(0, FALSE, FALSE, shutdown_event_name); + pthread_t hThread; + if (pthread_create(&hThread,&connection_attrib,handle_shutdown,0)) + sql_print_warning("Can't create thread to handle shutdown requests"); + + // On "Stop Service" we have to do regular shutdown + Service.SetShutdownEvent(hEventShutdown); +#endif /* __WIN__ */ +} + +#endif /* EMBEDDED_LIBRARY */ + + +#if (defined(__NT__) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY) +static void handle_connections_methods() +{ + pthread_t hThread; + DBUG_ENTER("handle_connections_methods"); +#ifdef __NT__ + if (hPipe == INVALID_HANDLE_VALUE && + (!have_tcpip || opt_disable_networking) && + !opt_enable_shared_memory) + { + sql_print_error("TCP/IP, --shared-memory, or --named-pipe should be configured on NT OS"); + unireg_abort(1); // Will not return + } +#endif + + pthread_mutex_lock(&LOCK_thread_count); + (void) pthread_cond_init(&COND_handler_count,NULL); + handler_count=0; +#ifdef __NT__ + if (hPipe != INVALID_HANDLE_VALUE) + { + handler_count++; + if (pthread_create(&hThread,&connection_attrib, + handle_connections_namedpipes, 0)) + { + sql_print_warning("Can't create thread to handle named pipes"); + handler_count--; + } + } +#endif /* __NT__ */ + if (have_tcpip && !opt_disable_networking) + { + handler_count++; + if (pthread_create(&hThread,&connection_attrib, + handle_connections_sockets, 0)) + { + sql_print_warning("Can't create thread to handle TCP/IP"); + handler_count--; + } + } +#ifdef HAVE_SMEM + if (opt_enable_shared_memory) + { + handler_count++; + if (pthread_create(&hThread,&connection_attrib, + handle_connections_shared_memory, 0)) + { + sql_print_warning("Can't create thread to handle shared memory"); + handler_count--; + } + } +#endif + + while (handler_count > 0) + pthread_cond_wait(&COND_handler_count,&LOCK_thread_count); + pthread_mutex_unlock(&LOCK_thread_count); + DBUG_VOID_RETURN; +} + +void decrement_handler_count() +{ + pthread_mutex_lock(&LOCK_thread_count); + handler_count--; + pthread_cond_signal(&COND_handler_count); + pthread_mutex_unlock(&LOCK_thread_count); + my_thread_end(); +} +#else +#define decrement_handler_count() +#endif /* defined(__NT__) || defined(HAVE_SMEM) */ + + +#ifndef EMBEDDED_LIBRARY +#ifndef DBUG_OFF +/* + Debugging helper function to keep the locale database + (see sql_locale.cc) and max_month_name_length and + max_day_name_length variable values in consistent state. +*/ +static void test_lc_time_sz() +{ + DBUG_ENTER("test_lc_time_sz"); + for (MY_LOCALE **loc= my_locales; *loc; loc++) + { + uint max_month_len= 0; + uint max_day_len = 0; + for (const char **month= (*loc)->month_names->type_names; *month; month++) + { + set_if_bigger(max_month_len, + my_numchars_mb(&my_charset_utf8_general_ci, + *month, *month + strlen(*month))); + } + for (const char **day= (*loc)->day_names->type_names; *day; day++) + { + set_if_bigger(max_day_len, + my_numchars_mb(&my_charset_utf8_general_ci, + *day, *day + strlen(*day))); + } + if ((*loc)->max_month_name_length != max_month_len || + (*loc)->max_day_name_length != max_day_len) + { + DBUG_PRINT("Wrong max day name(or month name) length for locale:", + ("%s", (*loc)->name)); + DBUG_ASSERT(0); + } + } + DBUG_VOID_RETURN; +} +#endif//DBUG_OFF + + +#ifdef __WIN__ +int win_main(int argc, char **argv) +#else +int main(int argc, char **argv) +#endif +{ + MY_INIT(argv[0]); // init my_sys library & pthreads + /* nothing should come before this line ^^^ */ + + /* Set signal used to kill MySQL */ +#if defined(SIGUSR2) + thr_kill_signal= thd_lib_detected == THD_LIB_LT ? SIGINT : SIGUSR2; +#else + thr_kill_signal= SIGINT; +#endif + + /* + Perform basic logger initialization logger. Should be called after + MY_INIT, as it initializes mutexes. Log tables are inited later. + */ + logger.init_base(); + +#ifdef _CUSTOMSTARTUPCONFIG_ + if (_cust_check_startup()) + { + / * _cust_check_startup will report startup failure error * / + exit(1); + } +#endif + +#ifdef __WIN__ + /* + Before performing any socket operation (like retrieving hostname + in init_common_variables we have to call WSAStartup + */ + { + WSADATA WsaData; + if (SOCKET_ERROR == WSAStartup (0x0101, &WsaData)) + { + /* errors are not read yet, so we use english text here */ + my_message(ER_WSAS_FAILED, "WSAStartup Failed", MYF(0)); + unireg_abort(1); + } + } +#endif /* __WIN__ */ + + if (init_common_variables(MYSQL_CONFIG_NAME, + argc, argv, load_default_groups)) + unireg_abort(1); // Will do exit + + init_signals(); + if (!(opt_specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(),CONNECT_PRIOR); +#if defined(__ia64__) || defined(__ia64) + /* + Peculiar things with ia64 platforms - it seems we only have half the + stack size in reality, so we have to double it here + */ + pthread_attr_setstacksize(&connection_attrib,my_thread_stack_size*2); +#else + pthread_attr_setstacksize(&connection_attrib,my_thread_stack_size); +#endif +#ifdef HAVE_PTHREAD_ATTR_GETSTACKSIZE + { + /* Retrieve used stack size; Needed for checking stack overflows */ + size_t stack_size= 0; + pthread_attr_getstacksize(&connection_attrib, &stack_size); +#if defined(__ia64__) || defined(__ia64) + stack_size/= 2; +#endif + /* We must check if stack_size = 0 as Solaris 2.9 can return 0 here */ + if (stack_size && stack_size < my_thread_stack_size) + { + if (global_system_variables.log_warnings) + sql_print_warning("Asked for %lu thread stack, but got %ld", + my_thread_stack_size, (long) stack_size); +#if defined(__ia64__) || defined(__ia64) + my_thread_stack_size= stack_size*2; +#else + my_thread_stack_size= stack_size; +#endif + } + } +#endif +#ifdef __NETWARE__ + /* Increasing stacksize of threads on NetWare */ + pthread_attr_setstacksize(&connection_attrib, NW_THD_STACKSIZE); +#endif + + (void) thr_setconcurrency(concurrency); // 10 by default + + select_thread=pthread_self(); + select_thread_in_use=1; + +#ifdef HAVE_LIBWRAP + libwrapName= my_progname+dirname_length(my_progname); + openlog(libwrapName, LOG_PID, LOG_AUTH); +#endif + +#ifndef DBUG_OFF + test_lc_time_sz(); +#endif + + /* + We have enough space for fiddling with the argv, continue + */ + check_data_home(mysql_real_data_home); + if (my_setwd(mysql_real_data_home,MYF(MY_WME)) && !opt_help) + unireg_abort(1); /* purecov: inspected */ + mysql_data_home= mysql_data_home_buff; + mysql_data_home[0]=FN_CURLIB; // all paths are relative from here + mysql_data_home[1]=0; + mysql_data_home_len= 2; + + if ((user_info= check_user(mysqld_user))) + { +#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) + if (locked_in_memory) // getuid() == 0 here + set_effective_user(user_info); + else +#endif + set_user(mysqld_user, user_info); + } + + if (opt_bin_log && !server_id) + { + server_id= !master_host ? 1 : 2; +#ifdef EXTRA_DEBUG + switch (server_id) { + case 1: + sql_print_warning("\ +You have enabled the binary log, but you haven't set server-id to \ +a non-zero value: we force server id to 1; updates will be logged to the \ +binary log, but connections from slaves will not be accepted."); + break; + case 2: + sql_print_warning("\ +You should set server-id to a non-0 value if master_host is set; \ +we force server id to 2, but this MySQL server will not act as a slave."); + break; + } +#endif + } + + if (init_server_components()) + unireg_abort(1); + + init_ssl(); + network_init(); + +#ifdef __WIN__ + if (!opt_console) + { + freopen(log_error_file,"a+",stdout); + freopen(log_error_file,"a+",stderr); + setbuf(stderr, NULL); + FreeConsole(); // Remove window + } +#endif + + /* + Initialize my_str_malloc() and my_str_free() + */ + my_str_malloc= &my_str_malloc_mysqld; + my_str_free= &my_str_free_mysqld; + + /* + init signals & alarm + After this we can't quit by a simple unireg_abort + */ + error_handler_hook= my_message_sql; + start_signal_handler(); // Creates pidfile + + if (mysql_rm_tmp_tables() || acl_init(opt_noacl) || + my_tz_init((THD *)0, default_tz_name, opt_bootstrap)) + { + abort_loop=1; + select_thread_in_use=0; +#ifndef __NETWARE__ + (void) pthread_kill(signal_thread, MYSQL_KILL_SIGNAL); +#endif /* __NETWARE__ */ + + if (!opt_bootstrap) + (void) my_delete(pidfile_name,MYF(MY_WME)); // Not needed anymore + + if (unix_sock != INVALID_SOCKET) + unlink(mysqld_unix_port); + exit(1); + } + if (!opt_noacl) + (void) grant_init(); + + if (!opt_bootstrap) + servers_init(0); + + if (!opt_noacl) + { +#ifdef HAVE_DLOPEN + udf_init(); +#endif + } + + init_status_vars(); + if (opt_bootstrap) /* If running with bootstrap, do not start replication. */ + opt_skip_slave_start= 1; + /* + init_slave() must be called after the thread keys are created. + Some parts of the code (e.g. SHOW STATUS LIKE 'slave_running' and other + places) assume that active_mi != 0, so let's fail if it's 0 (out of + memory); a message has already been printed. + */ + if (init_slave() && !active_mi) + { + unireg_abort(1); + } + + execute_ddl_log_recovery(); + + if (Events::init(opt_noacl || opt_bootstrap)) + unireg_abort(1); + + if (opt_bootstrap) + { + select_thread_in_use= 0; // Allow 'kill' to work + bootstrap(stdin); + unireg_abort(bootstrap_error ? 1 : 0); + } + if (opt_init_file) + { + if (read_init_file(opt_init_file)) + unireg_abort(1); + } + + create_shutdown_thread(); + start_handle_manager(); + + sql_print_information(ER(ER_STARTUP),my_progname,server_version, + ((unix_sock == INVALID_SOCKET) ? (char*) "" + : mysqld_unix_port), + mysqld_port, + MYSQL_COMPILATION_COMMENT); +#if defined(_WIN32) && !defined(EMBEDDED_LIBRARY) + Service.SetRunning(); +#endif + + + /* Signal threads waiting for server to be started */ + pthread_mutex_lock(&LOCK_server_started); + mysqld_server_started= 1; + pthread_cond_signal(&COND_server_started); + pthread_mutex_unlock(&LOCK_server_started); + +#if defined(__NT__) || defined(HAVE_SMEM) + handle_connections_methods(); +#else +#ifdef __WIN__ + if (!have_tcpip || opt_disable_networking) + { + sql_print_error("TCP/IP unavailable or disabled with --skip-networking; no available interfaces"); + unireg_abort(1); + } +#endif + handle_connections_sockets(0); +#endif /* __NT__ */ + + /* (void) pthread_attr_destroy(&connection_attrib); */ + + DBUG_PRINT("quit",("Exiting main thread")); + +#ifndef __WIN__ +#ifdef EXTRA_DEBUG2 + sql_print_error("Before Lock_thread_count"); +#endif + (void) pthread_mutex_lock(&LOCK_thread_count); + DBUG_PRINT("quit", ("Got thread_count mutex")); + select_thread_in_use=0; // For close_connections + (void) pthread_mutex_unlock(&LOCK_thread_count); + (void) pthread_cond_broadcast(&COND_thread_count); +#ifdef EXTRA_DEBUG2 + sql_print_error("After lock_thread_count"); +#endif +#endif /* __WIN__ */ + + /* Wait until cleanup is done */ + (void) pthread_mutex_lock(&LOCK_thread_count); + while (!ready_to_exit) + pthread_cond_wait(&COND_thread_count,&LOCK_thread_count); + (void) pthread_mutex_unlock(&LOCK_thread_count); + +#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY) + if (Service.IsNT() && start_mode) + Service.Stop(); + else + { + Service.SetShutdownEvent(0); + if (hEventShutdown) + CloseHandle(hEventShutdown); + } +#endif + clean_up(1); + wait_for_signal_thread_to_end(); + clean_up_mutexes(); + my_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0); + + exit(0); + return(0); /* purecov: deadcode */ +} + +#endif /* EMBEDDED_LIBRARY */ + + +/**************************************************************************** + Main and thread entry function for Win32 + (all this is needed only to run mysqld as a service on WinNT) +****************************************************************************/ + +#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY) +int mysql_service(void *p) +{ + if (use_opt_args) + win_main(opt_argc, opt_argv); + else + win_main(Service.my_argc, Service.my_argv); + return 0; +} + + +/* Quote string if it contains space, else copy */ + +static char *add_quoted_string(char *to, const char *from, char *to_end) +{ + uint length= (uint) (to_end-to); + + if (!strchr(from, ' ')) + return strmake(to, from, length-1); + return strxnmov(to, length-1, "\"", from, "\"", NullS); +} + + +/** + Handle basic handling of services, like installation and removal. + + @param argv Pointer to argument list + @param servicename Internal name of service + @param displayname Display name of service (in taskbar ?) + @param file_path Path to this program + @param startup_option Startup option to mysqld + + @retval + 0 option handled + @retval + 1 Could not handle option +*/ + +static bool +default_service_handling(char **argv, + const char *servicename, + const char *displayname, + const char *file_path, + const char *extra_opt, + const char *account_name) +{ + char path_and_service[FN_REFLEN+FN_REFLEN+32], *pos, *end; + const char *opt_delim; + end= path_and_service + sizeof(path_and_service)-3; + + /* We have to quote filename if it contains spaces */ + pos= add_quoted_string(path_and_service, file_path, end); + if (*extra_opt) + { + /* + Add option after file_path. There will be zero or one extra option. It's + assumed to be --defaults-file=file but isn't checked. The variable (not + the option name) should be quoted if it contains a string. + */ + *pos++= ' '; + if (opt_delim= strchr(extra_opt, '=')) + { + size_t length= ++opt_delim - extra_opt; + strnmov(pos, extra_opt, length); + } + else + opt_delim= extra_opt; + + pos= add_quoted_string(pos, opt_delim, end); + } + /* We must have servicename last */ + *pos++= ' '; + (void) add_quoted_string(pos, servicename, end); + + if (Service.got_service_option(argv, "install")) + { + Service.Install(1, servicename, displayname, path_and_service, + account_name); + return 0; + } + if (Service.got_service_option(argv, "install-manual")) + { + Service.Install(0, servicename, displayname, path_and_service, + account_name); + return 0; + } + if (Service.got_service_option(argv, "remove")) + { + Service.Remove(servicename); + return 0; + } + return 1; +} + + +int main(int argc, char **argv) +{ + /* + When several instances are running on the same machine, we + need to have an unique named hEventShudown through the + application PID e.g.: MySQLShutdown1890; MySQLShutdown2342 + */ + int10_to_str((int) GetCurrentProcessId(),strmov(shutdown_event_name, + "MySQLShutdown"), 10); + + /* Must be initialized early for comparison of service name */ + system_charset_info= &my_charset_utf8_general_ci; + + if (Service.GetOS()) /* true NT family */ + { + char file_path[FN_REFLEN]; + my_path(file_path, argv[0], ""); /* Find name in path */ + fn_format(file_path,argv[0],file_path,"", + MY_REPLACE_DIR | MY_UNPACK_FILENAME | MY_RESOLVE_SYMLINKS); + + if (argc == 2) + { + if (!default_service_handling(argv, MYSQL_SERVICENAME, MYSQL_SERVICENAME, + file_path, "", NULL)) + return 0; + if (Service.IsService(argv[1])) /* Start an optional service */ + { + /* + Only add the service name to the groups read from the config file + if it's not "MySQL". (The default service name should be 'mysqld' + but we started a bad tradition by calling it MySQL from the start + and we are now stuck with it. + */ + if (my_strcasecmp(system_charset_info, argv[1],"mysql")) + load_default_groups[load_default_groups_sz-2]= argv[1]; + start_mode= 1; + Service.Init(argv[1], mysql_service); + return 0; + } + } + else if (argc == 3) /* install or remove any optional service */ + { + if (!default_service_handling(argv, argv[2], argv[2], file_path, "", + NULL)) + return 0; + if (Service.IsService(argv[2])) + { + /* + mysqld was started as + mysqld --defaults-file=my_path\my.ini service-name + */ + use_opt_args=1; + opt_argc= 2; // Skip service-name + opt_argv=argv; + start_mode= 1; + if (my_strcasecmp(system_charset_info, argv[2],"mysql")) + load_default_groups[load_default_groups_sz-2]= argv[2]; + Service.Init(argv[2], mysql_service); + return 0; + } + } + else if (argc == 4 || argc == 5) + { + /* + This may seem strange, because we handle --local-service while + preserving 4.1's behavior of allowing any one other argument that is + passed to the service on startup. (The assumption is that this is + --defaults-file=file, but that was not enforced in 4.1, so we don't + enforce it here.) + */ + const char *extra_opt= NullS; + const char *account_name = NullS; + int index; + for (index = 3; index < argc; index++) + { + if (!strcmp(argv[index], "--local-service")) + account_name= "NT AUTHORITY\\LocalService"; + else + extra_opt= argv[index]; + } + + if (argc == 4 || account_name) + if (!default_service_handling(argv, argv[2], argv[2], file_path, + extra_opt, account_name)) + return 0; + } + else if (argc == 1 && Service.IsService(MYSQL_SERVICENAME)) + { + /* start the default service */ + start_mode= 1; + Service.Init(MYSQL_SERVICENAME, mysql_service); + return 0; + } + } + /* Start as standalone server */ + Service.my_argc=argc; + Service.my_argv=argv; + mysql_service(NULL); + return 0; +} +#endif + + +/** + Execute all commands from a file. Used by the mysql_install_db script to + create MySQL privilege tables without having to start a full MySQL server. +*/ + +static void bootstrap(FILE *file) +{ + DBUG_ENTER("bootstrap"); + + THD *thd= new THD; + thd->bootstrap=1; + my_net_init(&thd->net,(st_vio*) 0); + thd->max_client_packet_length= thd->net.max_packet; + thd->security_ctx->master_access= ~(ulong)0; + thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; + thread_count++; + in_bootstrap= TRUE; + + bootstrap_file=file; +#ifndef EMBEDDED_LIBRARY // TODO: Enable this + if (pthread_create(&thd->real_id,&connection_attrib,handle_bootstrap, + (void*) thd)) + { + sql_print_warning("Can't create thread to handle bootstrap"); + bootstrap_error=-1; + DBUG_VOID_RETURN; + } + /* Wait for thread to die */ + (void) pthread_mutex_lock(&LOCK_thread_count); + while (in_bootstrap) + { + (void) pthread_cond_wait(&COND_thread_count,&LOCK_thread_count); + DBUG_PRINT("quit",("One thread died (count=%u)",thread_count)); + } + (void) pthread_mutex_unlock(&LOCK_thread_count); +#else + thd->mysql= 0; + handle_bootstrap((void *)thd); +#endif + + DBUG_VOID_RETURN; +} + + +static bool read_init_file(char *file_name) +{ + FILE *file; + DBUG_ENTER("read_init_file"); + DBUG_PRINT("enter",("name: %s",file_name)); + if (!(file=my_fopen(file_name,O_RDONLY,MYF(MY_WME)))) + return(1); + bootstrap(file); + (void) my_fclose(file,MYF(MY_WME)); + return 0; +} + + +#ifndef EMBEDDED_LIBRARY + +/* + Simple scheduler that use the main thread to handle the request + + NOTES + This is only used for debugging, when starting mysqld with + --thread-handling=no-threads or --one-thread + + When we enter this function, LOCK_thread_count is hold! +*/ + +void handle_connection_in_main_thread(THD *thd) +{ + safe_mutex_assert_owner(&LOCK_thread_count); + thread_cache_size=0; // Safety + threads.append(thd); + pthread_mutex_unlock(&LOCK_thread_count); + thd->start_utime= my_micro_time(); + handle_one_connection(thd); +} + + +/* + Scheduler that uses one thread per connection +*/ + +void create_thread_to_handle_connection(THD *thd) +{ + if (cached_thread_count > wake_thread) + { + /* Get thread from cache */ + thread_cache.append(thd); + wake_thread++; + pthread_cond_signal(&COND_thread_cache); + } + else + { + char error_message_buff[MYSQL_ERRMSG_SIZE]; + /* Create new thread to handle connection */ + int error; + thread_created++; + threads.append(thd); + DBUG_PRINT("info",(("creating thread %lu"), thd->thread_id)); + thd->prior_thr_create_utime= thd->start_utime= my_micro_time(); + if ((error=pthread_create(&thd->real_id,&connection_attrib, + handle_one_connection, + (void*) thd))) + { + /* purify: begin inspected */ + DBUG_PRINT("error", + ("Can't create thread to handle request (error %d)", + error)); + thread_count--; + thd->killed= THD::KILL_CONNECTION; // Safety + (void) pthread_mutex_unlock(&LOCK_thread_count); + + pthread_mutex_lock(&LOCK_connection_count); + --connection_count; + pthread_mutex_unlock(&LOCK_connection_count); + + statistic_increment(aborted_connects,&LOCK_status); + /* Can't use my_error() since store_globals has not been called. */ + my_snprintf(error_message_buff, sizeof(error_message_buff), + ER(ER_CANT_CREATE_THREAD), error); + net_send_error(thd, ER_CANT_CREATE_THREAD, error_message_buff); + (void) pthread_mutex_lock(&LOCK_thread_count); + close_connection(thd,0,0); + delete thd; + (void) pthread_mutex_unlock(&LOCK_thread_count); + return; + /* purecov: end */ + } + } + (void) pthread_mutex_unlock(&LOCK_thread_count); + DBUG_PRINT("info",("Thread created")); +} + + +/** + Create new thread to handle incoming connection. + + This function will create new thread to handle the incoming + connection. If there are idle cached threads one will be used. + 'thd' will be pushed into 'threads'. + + In single-threaded mode (\#define ONE_THREAD) connection will be + handled inside this function. + + @param[in,out] thd Thread handle of future thread. +*/ + +static void create_new_thread(THD *thd) +{ + NET *net=&thd->net; + DBUG_ENTER("create_new_thread"); + + if (protocol_version > 9) + net->return_errno=1; + + /* + Don't allow too many connections. We roughly check here that we allow + only (max_connections + 1) connections. + */ + + pthread_mutex_lock(&LOCK_connection_count); + + if (connection_count >= max_connections + 1 || abort_loop) + { + pthread_mutex_unlock(&LOCK_connection_count); + + DBUG_PRINT("error",("Too many connections")); + close_connection(thd, ER_CON_COUNT_ERROR, 1); + delete thd; + DBUG_VOID_RETURN; + } + + ++connection_count; + + if (connection_count > max_used_connections) + max_used_connections= connection_count; + + pthread_mutex_unlock(&LOCK_connection_count); + + /* Start a new thread to handle connection. */ + + pthread_mutex_lock(&LOCK_thread_count); + + /* + The initialization of thread_id is done in create_embedded_thd() for + the embedded library. + TODO: refactor this to avoid code duplication there + */ + thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; + + thread_count++; + + thread_scheduler.add_connection(thd); + + DBUG_VOID_RETURN; +} +#endif /* EMBEDDED_LIBRARY */ + + +#ifdef SIGNALS_DONT_BREAK_READ +inline void kill_broken_server() +{ + /* hack to get around signals ignored in syscalls for problem OS's */ + if ( +#if !defined(__NETWARE__) + unix_sock == INVALID_SOCKET || +#endif + (!opt_disable_networking && ip_sock == INVALID_SOCKET)) + { + select_thread_in_use = 0; + /* The following call will never return */ + kill_server(IF_NETWARE(MYSQL_KILL_SIGNAL, (void*) MYSQL_KILL_SIGNAL)); + } +} +#define MAYBE_BROKEN_SYSCALL kill_broken_server(); +#else +#define MAYBE_BROKEN_SYSCALL +#endif + + /* Handle new connections and spawn new process to handle them */ + +#ifndef EMBEDDED_LIBRARY +pthread_handler_t handle_connections_sockets(void *arg __attribute__((unused))) +{ + my_socket sock,new_sock; + uint error_count=0; + uint max_used_connection= (uint) (max(ip_sock,unix_sock)+1); + fd_set readFDs,clientFDs; + THD *thd; + struct sockaddr_in cAddr; + int ip_flags=0,socket_flags=0,flags; + st_vio *vio_tmp; + DBUG_ENTER("handle_connections_sockets"); + + LINT_INIT(new_sock); + + (void) my_pthread_getprio(pthread_self()); // For debugging + + FD_ZERO(&clientFDs); + if (ip_sock != INVALID_SOCKET) + { + FD_SET(ip_sock,&clientFDs); +#ifdef HAVE_FCNTL + ip_flags = fcntl(ip_sock, F_GETFL, 0); +#endif + } +#ifdef HAVE_SYS_UN_H + FD_SET(unix_sock,&clientFDs); +#ifdef HAVE_FCNTL + socket_flags=fcntl(unix_sock, F_GETFL, 0); +#endif +#endif + + DBUG_PRINT("general",("Waiting for connections.")); + MAYBE_BROKEN_SYSCALL; + while (!abort_loop) + { + readFDs=clientFDs; +#ifdef HPUX10 + if (select(max_used_connection,(int*) &readFDs,0,0,0) < 0) + continue; +#else + if (select((int) max_used_connection,&readFDs,0,0,0) < 0) + { + if (socket_errno != SOCKET_EINTR) + { + if (!select_errors++ && !abort_loop) /* purecov: inspected */ + sql_print_error("mysqld: Got error %d from select",socket_errno); /* purecov: inspected */ + } + MAYBE_BROKEN_SYSCALL + continue; + } +#endif /* HPUX10 */ + if (abort_loop) + { + MAYBE_BROKEN_SYSCALL; + break; + } + + /* Is this a new connection request ? */ +#ifdef HAVE_SYS_UN_H + if (FD_ISSET(unix_sock,&readFDs)) + { + sock = unix_sock; + flags= socket_flags; + } + else +#endif + { + sock = ip_sock; + flags= ip_flags; + } + +#if !defined(NO_FCNTL_NONBLOCK) + if (!(test_flags & TEST_BLOCKING)) + { +#if defined(O_NONBLOCK) + fcntl(sock, F_SETFL, flags | O_NONBLOCK); +#elif defined(O_NDELAY) + fcntl(sock, F_SETFL, flags | O_NDELAY); +#endif + } +#endif /* NO_FCNTL_NONBLOCK */ + for (uint retry=0; retry < MAX_ACCEPT_RETRY; retry++) + { + size_socket length=sizeof(struct sockaddr_in); + new_sock = accept(sock, my_reinterpret_cast(struct sockaddr *) (&cAddr), + &length); +#ifdef __NETWARE__ + // TODO: temporary fix, waiting for TCP/IP fix - DEFECT000303149 + if ((new_sock == INVALID_SOCKET) && (socket_errno == EINVAL)) + { + kill_server(SIGTERM); + } +#endif + if (new_sock != INVALID_SOCKET || + (socket_errno != SOCKET_EINTR && socket_errno != SOCKET_EAGAIN)) + break; + MAYBE_BROKEN_SYSCALL; +#if !defined(NO_FCNTL_NONBLOCK) + if (!(test_flags & TEST_BLOCKING)) + { + if (retry == MAX_ACCEPT_RETRY - 1) + fcntl(sock, F_SETFL, flags); // Try without O_NONBLOCK + } +#endif + } +#if !defined(NO_FCNTL_NONBLOCK) + if (!(test_flags & TEST_BLOCKING)) + fcntl(sock, F_SETFL, flags); +#endif + if (new_sock == INVALID_SOCKET) + { + if ((error_count++ & 255) == 0) // This can happen often + sql_perror("Error in accept"); + MAYBE_BROKEN_SYSCALL; + if (socket_errno == SOCKET_ENFILE || socket_errno == SOCKET_EMFILE) + sleep(1); // Give other threads some time + continue; + } + +#ifdef HAVE_LIBWRAP + { + if (sock == ip_sock) + { + struct request_info req; + signal(SIGCHLD, SIG_DFL); + request_init(&req, RQ_DAEMON, libwrapName, RQ_FILE, new_sock, NULL); + my_fromhost(&req); + if (!my_hosts_access(&req)) + { + /* + This may be stupid but refuse() includes an exit(0) + which we surely don't want... + clean_exit() - same stupid thing ... + */ + syslog(deny_severity, "refused connect from %s", + my_eval_client(&req)); + + /* + C++ sucks (the gibberish in front just translates the supplied + sink function pointer in the req structure from a void (*sink)(); + to a void(*sink)(int) if you omit the cast, the C++ compiler + will cry... + */ + if (req.sink) + ((void (*)(int))req.sink)(req.fd); + + (void) shutdown(new_sock, SHUT_RDWR); + (void) closesocket(new_sock); + continue; + } + } + } +#endif /* HAVE_LIBWRAP */ + + { + size_socket dummyLen; + struct sockaddr dummy; + dummyLen = sizeof(struct sockaddr); + if (getsockname(new_sock,&dummy, &dummyLen) < 0) + { + sql_perror("Error on new connection socket"); + (void) shutdown(new_sock, SHUT_RDWR); + (void) closesocket(new_sock); + continue; + } + } + + /* + ** Don't allow too many connections + */ + + if (!(thd= new THD)) + { + (void) shutdown(new_sock, SHUT_RDWR); + VOID(closesocket(new_sock)); + continue; + } + if (!(vio_tmp=vio_new(new_sock, + sock == unix_sock ? VIO_TYPE_SOCKET : + VIO_TYPE_TCPIP, + sock == unix_sock ? VIO_LOCALHOST: 0)) || + my_net_init(&thd->net,vio_tmp)) + { + /* + Only delete the temporary vio if we didn't already attach it to the + NET object. The destructor in THD will delete any initialized net + structure. + */ + if (vio_tmp && thd->net.vio != vio_tmp) + vio_delete(vio_tmp); + else + { + (void) shutdown(new_sock, SHUT_RDWR); + (void) closesocket(new_sock); + } + delete thd; + continue; + } + if (sock == unix_sock) + thd->security_ctx->host=(char*) my_localhost; + + create_new_thread(thd); + } + + decrement_handler_count(); + DBUG_RETURN(0); +} + + +#ifdef __NT__ +pthread_handler_t handle_connections_namedpipes(void *arg) +{ + HANDLE hConnectedPipe; + BOOL fConnected; + THD *thd; + my_thread_init(); + DBUG_ENTER("handle_connections_namedpipes"); + (void) my_pthread_getprio(pthread_self()); // For debugging + + DBUG_PRINT("general",("Waiting for named pipe connections.")); + while (!abort_loop) + { + /* wait for named pipe connection */ + fConnected = ConnectNamedPipe(hPipe, NULL); + if (abort_loop) + break; + if (!fConnected) + fConnected = GetLastError() == ERROR_PIPE_CONNECTED; + if (!fConnected) + { + CloseHandle(hPipe); + if ((hPipe= CreateNamedPipe(pipe_name, + PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | + PIPE_READMODE_BYTE | + PIPE_WAIT, + PIPE_UNLIMITED_INSTANCES, + (int) global_system_variables. + net_buffer_length, + (int) global_system_variables. + net_buffer_length, + NMPWAIT_USE_DEFAULT_WAIT, + &saPipeSecurity)) == + INVALID_HANDLE_VALUE) + { + sql_perror("Can't create new named pipe!"); + break; // Abort + } + } + hConnectedPipe = hPipe; + /* create new pipe for new connection */ + if ((hPipe = CreateNamedPipe(pipe_name, + PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | + PIPE_READMODE_BYTE | + PIPE_WAIT, + PIPE_UNLIMITED_INSTANCES, + (int) global_system_variables.net_buffer_length, + (int) global_system_variables.net_buffer_length, + NMPWAIT_USE_DEFAULT_WAIT, + &saPipeSecurity)) == + INVALID_HANDLE_VALUE) + { + sql_perror("Can't create new named pipe!"); + hPipe=hConnectedPipe; + continue; // We have to try again + } + + if (!(thd = new THD)) + { + DisconnectNamedPipe(hConnectedPipe); + CloseHandle(hConnectedPipe); + continue; + } + if (!(thd->net.vio = vio_new_win32pipe(hConnectedPipe)) || + my_net_init(&thd->net, thd->net.vio)) + { + close_connection(thd, ER_OUT_OF_RESOURCES, 1); + delete thd; + continue; + } + /* Host is unknown */ + thd->security_ctx->host= my_strdup(my_localhost, MYF(0)); + create_new_thread(thd); + } + + decrement_handler_count(); + DBUG_RETURN(0); +} +#endif /* __NT__ */ + + +#ifdef HAVE_SMEM + +/** + Thread of shared memory's service. + + @param arg Arguments of thread +*/ +pthread_handler_t handle_connections_shared_memory(void *arg) +{ + /* file-mapping object, use for create shared memory */ + HANDLE handle_connect_file_map= 0; + char *handle_connect_map= 0; // pointer on shared memory + HANDLE event_connect_answer= 0; + ulong smem_buffer_length= shared_memory_buffer_length + 4; + ulong connect_number= 1; + char *tmp= NULL; + char *suffix_pos; + char connect_number_char[22], *p; + const char *errmsg= 0; + SECURITY_ATTRIBUTES *sa_event= 0, *sa_mapping= 0; + my_thread_init(); + DBUG_ENTER("handle_connections_shared_memorys"); + DBUG_PRINT("general",("Waiting for allocated shared memory.")); + + /* + get enough space base-name + '_' + longest suffix we might ever send + */ + if (!(tmp= (char *)my_malloc(strlen(shared_memory_base_name) + 32L, MYF(MY_FAE)))) + goto error; + + if (my_security_attr_create(&sa_event, &errmsg, + GENERIC_ALL, SYNCHRONIZE | EVENT_MODIFY_STATE)) + goto error; + + if (my_security_attr_create(&sa_mapping, &errmsg, + GENERIC_ALL, FILE_MAP_READ | FILE_MAP_WRITE)) + goto error; + + /* + The name of event and file-mapping events create agree next rule: + shared_memory_base_name+unique_part + Where: + shared_memory_base_name is unique value for each server + unique_part is unique value for each object (events and file-mapping) + */ + suffix_pos= strxmov(tmp,shared_memory_base_name,"_",NullS); + strmov(suffix_pos, "CONNECT_REQUEST"); + if ((smem_event_connect_request= CreateEvent(sa_event, + FALSE, FALSE, tmp)) == 0) + { + errmsg= "Could not create request event"; + goto error; + } + strmov(suffix_pos, "CONNECT_ANSWER"); + if ((event_connect_answer= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0) + { + errmsg="Could not create answer event"; + goto error; + } + strmov(suffix_pos, "CONNECT_DATA"); + if ((handle_connect_file_map= + CreateFileMapping(INVALID_HANDLE_VALUE, sa_mapping, + PAGE_READWRITE, 0, sizeof(connect_number), tmp)) == 0) + { + errmsg= "Could not create file mapping"; + goto error; + } + if ((handle_connect_map= (char *)MapViewOfFile(handle_connect_file_map, + FILE_MAP_WRITE,0,0, + sizeof(DWORD))) == 0) + { + errmsg= "Could not create shared memory service"; + goto error; + } + + while (!abort_loop) + { + /* Wait a request from client */ + WaitForSingleObject(smem_event_connect_request,INFINITE); + + /* + it can be after shutdown command + */ + if (abort_loop) + goto error; + + HANDLE handle_client_file_map= 0; + char *handle_client_map= 0; + HANDLE event_client_wrote= 0; + HANDLE event_client_read= 0; // for transfer data server <-> client + HANDLE event_server_wrote= 0; + HANDLE event_server_read= 0; + HANDLE event_conn_closed= 0; + THD *thd= 0; + + p= int10_to_str(connect_number, connect_number_char, 10); + /* + The name of event and file-mapping events create agree next rule: + shared_memory_base_name+unique_part+number_of_connection + Where: + shared_memory_base_name is uniquel value for each server + unique_part is unique value for each object (events and file-mapping) + number_of_connection is connection-number between server and client + */ + suffix_pos= strxmov(tmp,shared_memory_base_name,"_",connect_number_char, + "_",NullS); + strmov(suffix_pos, "DATA"); + if ((handle_client_file_map= + CreateFileMapping(INVALID_HANDLE_VALUE, sa_mapping, + PAGE_READWRITE, 0, smem_buffer_length, tmp)) == 0) + { + errmsg= "Could not create file mapping"; + goto errorconn; + } + if ((handle_client_map= (char*)MapViewOfFile(handle_client_file_map, + FILE_MAP_WRITE,0,0, + smem_buffer_length)) == 0) + { + errmsg= "Could not create memory map"; + goto errorconn; + } + strmov(suffix_pos, "CLIENT_WROTE"); + if ((event_client_wrote= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0) + { + errmsg= "Could not create client write event"; + goto errorconn; + } + strmov(suffix_pos, "CLIENT_READ"); + if ((event_client_read= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0) + { + errmsg= "Could not create client read event"; + goto errorconn; + } + strmov(suffix_pos, "SERVER_READ"); + if ((event_server_read= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0) + { + errmsg= "Could not create server read event"; + goto errorconn; + } + strmov(suffix_pos, "SERVER_WROTE"); + if ((event_server_wrote= CreateEvent(sa_event, + FALSE, FALSE, tmp)) == 0) + { + errmsg= "Could not create server write event"; + goto errorconn; + } + strmov(suffix_pos, "CONNECTION_CLOSED"); + if ((event_conn_closed= CreateEvent(sa_event, + TRUE, FALSE, tmp)) == 0) + { + errmsg= "Could not create closed connection event"; + goto errorconn; + } + if (abort_loop) + goto errorconn; + if (!(thd= new THD)) + goto errorconn; + /* Send number of connection to client */ + int4store(handle_connect_map, connect_number); + if (!SetEvent(event_connect_answer)) + { + errmsg= "Could not send answer event"; + goto errorconn; + } + /* Set event that client should receive data */ + if (!SetEvent(event_client_read)) + { + errmsg= "Could not set client to read mode"; + goto errorconn; + } + if (!(thd->net.vio= vio_new_win32shared_memory(&thd->net, + handle_client_file_map, + handle_client_map, + event_client_wrote, + event_client_read, + event_server_wrote, + event_server_read, + event_conn_closed)) || + my_net_init(&thd->net, thd->net.vio)) + { + close_connection(thd, ER_OUT_OF_RESOURCES, 1); + errmsg= 0; + goto errorconn; + } + thd->security_ctx->host= my_strdup(my_localhost, MYF(0)); /* Host is unknown */ + create_new_thread(thd); + connect_number++; + continue; + +errorconn: + /* Could not form connection; Free used handlers/memort and retry */ + if (errmsg) + { + char buff[180]; + strxmov(buff, "Can't create shared memory connection: ", errmsg, ".", + NullS); + sql_perror(buff); + } + if (handle_client_file_map) + CloseHandle(handle_client_file_map); + if (handle_client_map) + UnmapViewOfFile(handle_client_map); + if (event_server_wrote) + CloseHandle(event_server_wrote); + if (event_server_read) + CloseHandle(event_server_read); + if (event_client_wrote) + CloseHandle(event_client_wrote); + if (event_client_read) + CloseHandle(event_client_read); + if (event_conn_closed) + CloseHandle(event_conn_closed); + delete thd; + } + + /* End shared memory handling */ +error: + if (tmp) + my_free(tmp, MYF(0)); + + if (errmsg) + { + char buff[180]; + strxmov(buff, "Can't create shared memory service: ", errmsg, ".", NullS); + sql_perror(buff); + } + my_security_attr_free(sa_event); + my_security_attr_free(sa_mapping); + if (handle_connect_map) UnmapViewOfFile(handle_connect_map); + if (handle_connect_file_map) CloseHandle(handle_connect_file_map); + if (event_connect_answer) CloseHandle(event_connect_answer); + if (smem_event_connect_request) CloseHandle(smem_event_connect_request); + + decrement_handler_count(); + DBUG_RETURN(0); +} +#endif /* HAVE_SMEM */ +#endif /* EMBEDDED_LIBRARY */ + + +/**************************************************************************** + Handle start options +******************************************************************************/ + +enum options_mysqld +{ + OPT_ISAM_LOG=256, OPT_SKIP_NEW, + OPT_SKIP_GRANT, OPT_SKIP_LOCK, + OPT_ENABLE_LOCK, OPT_USE_LOCKING, + OPT_SOCKET, OPT_UPDATE_LOG, + OPT_BIN_LOG, OPT_SKIP_RESOLVE, + OPT_SKIP_NETWORKING, OPT_BIN_LOG_INDEX, + OPT_BIND_ADDRESS, OPT_PID_FILE, + OPT_SKIP_PRIOR, OPT_BIG_TABLES, + OPT_STANDALONE, OPT_ONE_THREAD, + OPT_CONSOLE, OPT_LOW_PRIORITY_UPDATES, + OPT_SKIP_HOST_CACHE, OPT_SHORT_LOG_FORMAT, + OPT_FLUSH, OPT_SAFE, + OPT_BOOTSTRAP, OPT_SKIP_SHOW_DB, + OPT_STORAGE_ENGINE, OPT_INIT_FILE, + OPT_DELAY_KEY_WRITE_ALL, OPT_SLOW_QUERY_LOG, + OPT_DELAY_KEY_WRITE, OPT_CHARSETS_DIR, + OPT_MASTER_HOST, OPT_MASTER_USER, + OPT_MASTER_PASSWORD, OPT_MASTER_PORT, + OPT_MASTER_INFO_FILE, OPT_MASTER_CONNECT_RETRY, + OPT_MASTER_RETRY_COUNT, OPT_LOG_TC, OPT_LOG_TC_SIZE, + OPT_MASTER_SSL, OPT_MASTER_SSL_KEY, + OPT_MASTER_SSL_CERT, OPT_MASTER_SSL_CAPATH, + OPT_MASTER_SSL_CIPHER, OPT_MASTER_SSL_CA, + OPT_SQL_BIN_UPDATE_SAME, OPT_REPLICATE_DO_DB, + OPT_REPLICATE_IGNORE_DB, OPT_LOG_SLAVE_UPDATES, + OPT_BINLOG_DO_DB, OPT_BINLOG_IGNORE_DB, + OPT_BINLOG_FORMAT, +#ifndef DBUG_OFF + OPT_BINLOG_SHOW_XID, +#endif + OPT_BINLOG_ROWS_EVENT_MAX_SIZE, + OPT_WANT_CORE, OPT_CONCURRENT_INSERT, + OPT_MEMLOCK, OPT_MYISAM_RECOVER, + OPT_REPLICATE_REWRITE_DB, OPT_SERVER_ID, + OPT_SKIP_SLAVE_START, OPT_SAFE_SHOW_DB, + OPT_SAFEMALLOC_MEM_LIMIT, OPT_REPLICATE_DO_TABLE, + OPT_REPLICATE_IGNORE_TABLE, OPT_REPLICATE_WILD_DO_TABLE, + OPT_REPLICATE_WILD_IGNORE_TABLE, OPT_REPLICATE_SAME_SERVER_ID, + OPT_DISCONNECT_SLAVE_EVENT_COUNT, OPT_TC_HEURISTIC_RECOVER, + OPT_ABORT_SLAVE_EVENT_COUNT, + OPT_LOG_BIN_TRUST_FUNCTION_CREATORS, + OPT_ENGINE_CONDITION_PUSHDOWN, OPT_NDB_CONNECTSTRING, + OPT_NDB_USE_EXACT_COUNT, OPT_NDB_USE_TRANSACTIONS, + OPT_NDB_FORCE_SEND, OPT_NDB_AUTOINCREMENT_PREFETCH_SZ, + OPT_NDB_SHM, OPT_NDB_OPTIMIZED_NODE_SELECTION, OPT_NDB_CACHE_CHECK_TIME, + OPT_NDB_MGMD, OPT_NDB_NODEID, + OPT_NDB_DISTRIBUTION, + OPT_NDB_INDEX_STAT_ENABLE, + OPT_NDB_EXTRA_LOGGING, + OPT_NDB_REPORT_THRESH_BINLOG_EPOCH_SLIP, + OPT_NDB_REPORT_THRESH_BINLOG_MEM_USAGE, + OPT_NDB_USE_COPYING_ALTER_TABLE, + OPT_SKIP_SAFEMALLOC, + OPT_TEMP_POOL, OPT_TX_ISOLATION, OPT_COMPLETION_TYPE, + OPT_SKIP_STACK_TRACE, OPT_SKIP_SYMLINKS, + OPT_MAX_BINLOG_DUMP_EVENTS, OPT_SPORADIC_BINLOG_DUMP_FAIL, + OPT_SAFE_USER_CREATE, OPT_SQL_MODE, + OPT_HAVE_NAMED_PIPE, + OPT_DO_PSTACK, OPT_EVENT_SCHEDULER, OPT_REPORT_HOST, + OPT_REPORT_USER, OPT_REPORT_PASSWORD, OPT_REPORT_PORT, + OPT_SHOW_SLAVE_AUTH_INFO, + OPT_SLAVE_LOAD_TMPDIR, OPT_NO_MIX_TYPE, + OPT_RPL_RECOVERY_RANK,OPT_INIT_RPL_ROLE, + OPT_RELAY_LOG, OPT_RELAY_LOG_INDEX, OPT_RELAY_LOG_INFO_FILE, + OPT_SLAVE_SKIP_ERRORS, OPT_DES_KEY_FILE, OPT_LOCAL_INFILE, + OPT_SSL_SSL, OPT_SSL_KEY, OPT_SSL_CERT, OPT_SSL_CA, + OPT_SSL_CAPATH, OPT_SSL_CIPHER, + OPT_BACK_LOG, OPT_BINLOG_CACHE_SIZE, + OPT_CONNECT_TIMEOUT, OPT_DELAYED_INSERT_TIMEOUT, + OPT_DELAYED_INSERT_LIMIT, OPT_DELAYED_QUEUE_SIZE, + OPT_FLUSH_TIME, OPT_FT_MIN_WORD_LEN, OPT_FT_BOOLEAN_SYNTAX, + OPT_FT_MAX_WORD_LEN, OPT_FT_QUERY_EXPANSION_LIMIT, OPT_FT_STOPWORD_FILE, + OPT_INTERACTIVE_TIMEOUT, OPT_JOIN_BUFF_SIZE, + OPT_KEY_BUFFER_SIZE, OPT_KEY_CACHE_BLOCK_SIZE, + OPT_KEY_CACHE_DIVISION_LIMIT, OPT_KEY_CACHE_AGE_THRESHOLD, + OPT_LONG_QUERY_TIME, + OPT_LOWER_CASE_TABLE_NAMES, OPT_MAX_ALLOWED_PACKET, + OPT_MAX_BINLOG_CACHE_SIZE, OPT_MAX_BINLOG_SIZE, + OPT_MAX_CONNECTIONS, OPT_MAX_CONNECT_ERRORS, + OPT_MAX_DELAYED_THREADS, OPT_MAX_HEP_TABLE_SIZE, + OPT_MAX_JOIN_SIZE, OPT_MAX_PREPARED_STMT_COUNT, + OPT_MAX_RELAY_LOG_SIZE, OPT_MAX_SORT_LENGTH, + OPT_MAX_SEEKS_FOR_KEY, OPT_MAX_TMP_TABLES, OPT_MAX_USER_CONNECTIONS, + OPT_MAX_LENGTH_FOR_SORT_DATA, + OPT_MAX_WRITE_LOCK_COUNT, OPT_BULK_INSERT_BUFFER_SIZE, + OPT_MAX_ERROR_COUNT, OPT_MULTI_RANGE_COUNT, OPT_MYISAM_DATA_POINTER_SIZE, + OPT_MYISAM_BLOCK_SIZE, OPT_MYISAM_MAX_EXTRA_SORT_FILE_SIZE, + OPT_MYISAM_MAX_SORT_FILE_SIZE, OPT_MYISAM_SORT_BUFFER_SIZE, + OPT_MYISAM_USE_MMAP, OPT_MYISAM_REPAIR_THREADS, + OPT_MYISAM_STATS_METHOD, + OPT_NET_BUFFER_LENGTH, OPT_NET_RETRY_COUNT, + OPT_NET_READ_TIMEOUT, OPT_NET_WRITE_TIMEOUT, + OPT_OPEN_FILES_LIMIT, + OPT_PRELOAD_BUFFER_SIZE, + OPT_QUERY_CACHE_LIMIT, OPT_QUERY_CACHE_MIN_RES_UNIT, OPT_QUERY_CACHE_SIZE, + OPT_QUERY_CACHE_TYPE, OPT_QUERY_CACHE_WLOCK_INVALIDATE, OPT_RECORD_BUFFER, + OPT_RECORD_RND_BUFFER, OPT_DIV_PRECINCREMENT, OPT_RELAY_LOG_SPACE_LIMIT, + OPT_RELAY_LOG_PURGE, + OPT_SLAVE_NET_TIMEOUT, OPT_SLAVE_COMPRESSED_PROTOCOL, OPT_SLOW_LAUNCH_TIME, + OPT_SLAVE_TRANS_RETRIES, OPT_READONLY, OPT_DEBUGGING, + OPT_SORT_BUFFER, OPT_TABLE_OPEN_CACHE, OPT_TABLE_DEF_CACHE, + OPT_THREAD_CONCURRENCY, OPT_THREAD_CACHE_SIZE, + OPT_TMP_TABLE_SIZE, OPT_THREAD_STACK, + OPT_WAIT_TIMEOUT, + OPT_ERROR_LOG_FILE, + OPT_DEFAULT_WEEK_FORMAT, + OPT_RANGE_ALLOC_BLOCK_SIZE, OPT_ALLOW_SUSPICIOUS_UDFS, + OPT_QUERY_ALLOC_BLOCK_SIZE, OPT_QUERY_PREALLOC_SIZE, + OPT_TRANS_ALLOC_BLOCK_SIZE, OPT_TRANS_PREALLOC_SIZE, + OPT_SYNC_FRM, OPT_SYNC_BINLOG, + OPT_SYNC_REPLICATION, + OPT_SYNC_REPLICATION_SLAVE_ID, + OPT_SYNC_REPLICATION_TIMEOUT, + OPT_ENABLE_SHARED_MEMORY, + OPT_SHARED_MEMORY_BASE_NAME, + OPT_OLD_PASSWORDS, + OPT_OLD_ALTER_TABLE, + OPT_EXPIRE_LOGS_DAYS, + OPT_GROUP_CONCAT_MAX_LEN, + OPT_DEFAULT_COLLATION, + OPT_CHARACTER_SET_CLIENT_HANDSHAKE, + OPT_CHARACTER_SET_FILESYSTEM, + OPT_LC_TIME_NAMES, + OPT_INIT_CONNECT, + OPT_INIT_SLAVE, + OPT_SECURE_AUTH, + OPT_DATE_FORMAT, + OPT_TIME_FORMAT, + OPT_DATETIME_FORMAT, + OPT_LOG_QUERIES_NOT_USING_INDEXES, + OPT_DEFAULT_TIME_ZONE, + OPT_SYSDATE_IS_NOW, + OPT_OPTIMIZER_SEARCH_DEPTH, + OPT_OPTIMIZER_PRUNE_LEVEL, + OPT_OPTIMIZER_SWITCH, + OPT_UPDATABLE_VIEWS_WITH_LIMIT, + OPT_SP_AUTOMATIC_PRIVILEGES, + OPT_MAX_SP_RECURSION_DEPTH, + OPT_AUTO_INCREMENT, OPT_AUTO_INCREMENT_OFFSET, + OPT_ENABLE_LARGE_PAGES, + OPT_TIMED_MUTEXES, + OPT_OLD_STYLE_USER_LIMITS, + OPT_LOG_SLOW_ADMIN_STATEMENTS, + OPT_TABLE_LOCK_WAIT_TIMEOUT, + OPT_PLUGIN_LOAD, + OPT_PLUGIN_DIR, + OPT_LOG_OUTPUT, + OPT_PORT_OPEN_TIMEOUT, + OPT_PROFILING, + OPT_KEEP_FILES_ON_CREATE, + OPT_GENERAL_LOG, + OPT_SLOW_LOG, + OPT_THREAD_HANDLING, + OPT_INNODB_ROLLBACK_ON_TIMEOUT, + OPT_SECURE_FILE_PRIV, + OPT_MIN_EXAMINED_ROW_LIMIT, + OPT_LOG_SLOW_SLAVE_STATEMENTS, + OPT_OLD_MODE, + OPT_SLAVE_EXEC_MODE, + OPT_GENERAL_LOG_FILE, + OPT_SLOW_QUERY_LOG_FILE, + OPT_IGNORE_BUILTIN_INNODB, + /* InfiniDB */ + OPT_INFINIDB_VTABLE_MODE, + OPT_INFINIDB_DECIMAL_SCALE, + OPT_INFINIDB_USE_DECIMAL_SCALE, + OPT_INFINIDB_ORDERED_ONLY, + OPT_INFINIDB_STRING_SCAN_THRESHOLD, + OPT_INFINIDB_COMPRESSION_TYPE, + OPT_INFINIDB_VARBIN_ALWAYS_HEX, + /* InfiniDB */ +}; + + +#define LONG_TIMEOUT ((ulong) 3600L*24L*365L) + +struct my_option my_long_options[] = +{ + {"help", '?', "Display this help and exit.", + (uchar**) &opt_help, (uchar**) &opt_help, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, + 0, 0}, +#ifdef HAVE_REPLICATION + {"abort-slave-event-count", OPT_ABORT_SLAVE_EVENT_COUNT, + "Option used by mysql-test for debugging and testing of replication.", + (uchar**) &abort_slave_event_count, (uchar**) &abort_slave_event_count, + 0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#endif /* HAVE_REPLICATION */ + {"allow-suspicious-udfs", OPT_ALLOW_SUSPICIOUS_UDFS, + "Allows use of UDFs consisting of only one symbol xxx() " + "without corresponding xxx_init() or xxx_deinit(). That also means " + "that one can load any function from any library, for example exit() " + "from libc.so", + (uchar**) &opt_allow_suspicious_udfs, (uchar**) &opt_allow_suspicious_udfs, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"ansi", 'a', "Use ANSI SQL syntax instead of MySQL syntax. This mode will also set transaction isolation level 'serializable'.", 0, 0, 0, + GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"auto-increment-increment", OPT_AUTO_INCREMENT, + "Auto-increment columns are incremented by this", + (uchar**) &global_system_variables.auto_increment_increment, + (uchar**) &max_system_variables.auto_increment_increment, 0, GET_ULONG, + OPT_ARG, 1, 1, 65535, 0, 1, 0 }, + {"auto-increment-offset", OPT_AUTO_INCREMENT_OFFSET, + "Offset added to Auto-increment columns. Used when auto-increment-increment != 1", + (uchar**) &global_system_variables.auto_increment_offset, + (uchar**) &max_system_variables.auto_increment_offset, 0, GET_ULONG, OPT_ARG, + 1, 1, 65535, 0, 1, 0 }, + {"automatic-sp-privileges", OPT_SP_AUTOMATIC_PRIVILEGES, + "Creating and dropping stored procedures alters ACLs. Disable with --skip-automatic-sp-privileges.", + (uchar**) &sp_automatic_privileges, (uchar**) &sp_automatic_privileges, + 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0}, + {"basedir", 'b', + "Path to installation directory. All paths are usually resolved relative to this.", + (uchar**) &mysql_home_ptr, (uchar**) &mysql_home_ptr, 0, GET_STR, REQUIRED_ARG, + 0, 0, 0, 0, 0, 0}, + {"big-tables", OPT_BIG_TABLES, + "Allow big result sets by saving all temporary sets on file (Solves most 'table full' errors).", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"bind-address", OPT_BIND_ADDRESS, "IP address to bind to.", + (uchar**) &my_bind_addr_str, (uchar**) &my_bind_addr_str, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"binlog_format", OPT_BINLOG_FORMAT, + "Does not have any effect without '--log-bin'. " + "Tell the master the form of binary logging to use: either 'row' for " + "row-based binary logging, or 'statement' for statement-based binary " + "logging, or 'mixed'. 'mixed' is statement-based binary logging except " + "for those statements where only row-based is correct: those which " + "involve user-defined functions (i.e. UDFs) or the UUID() function; for " + "those, row-based binary logging is automatically used. " +#ifdef HAVE_NDB_BINLOG + "If ndbcluster is enabled and binlog_format is `mixed', the format switches" + " to 'row' and back implicitly per each query accessing a NDB table." +#endif + ,(uchar**) &opt_binlog_format, (uchar**) &opt_binlog_format, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"binlog-do-db", OPT_BINLOG_DO_DB, + "Tells the master it should log updates for the specified database, and exclude all others not explicitly mentioned.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"binlog-ignore-db", OPT_BINLOG_IGNORE_DB, + "Tells the master that updates to the given database should not be logged tothe binary log.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"binlog-row-event-max-size", OPT_BINLOG_ROWS_EVENT_MAX_SIZE, + "The maximum size of a row-based binary log event in bytes. Rows will be " + "grouped into events smaller than this size if possible. " + "The value has to be a multiple of 256.", + (uchar**) &opt_binlog_rows_event_max_size, + (uchar**) &opt_binlog_rows_event_max_size, 0, + GET_ULONG, REQUIRED_ARG, + /* def_value */ 1024, /* min_value */ 256, /* max_value */ ULONG_MAX, + /* sub_size */ 0, /* block_size */ 256, + /* app_type */ 0 + }, +#ifndef DISABLE_GRANT_OPTIONS + {"bootstrap", OPT_BOOTSTRAP, "Used by mysql installation scripts.", 0, 0, 0, + GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"character-set-client-handshake", OPT_CHARACTER_SET_CLIENT_HANDSHAKE, + "Don't ignore client side character set value sent during handshake.", + (uchar**) &opt_character_set_client_handshake, + (uchar**) &opt_character_set_client_handshake, + 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0}, + {"character-set-filesystem", OPT_CHARACTER_SET_FILESYSTEM, + "Set the filesystem character set.", + (uchar**) &character_set_filesystem_name, + (uchar**) &character_set_filesystem_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"character-set-server", 'C', "Set the default character set.", + (uchar**) &default_character_set_name, (uchar**) &default_character_set_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"character-sets-dir", OPT_CHARSETS_DIR, + "Directory where character sets are.", (uchar**) &charsets_dir, + (uchar**) &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"chroot", 'r', "Chroot mysqld daemon during startup.", + (uchar**) &mysqld_chroot, (uchar**) &mysqld_chroot, 0, GET_STR, REQUIRED_ARG, + 0, 0, 0, 0, 0, 0}, + {"collation-server", OPT_DEFAULT_COLLATION, "Set the default collation.", + (uchar**) &default_collation_name, (uchar**) &default_collation_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"completion-type", OPT_COMPLETION_TYPE, "Default completion type.", + (uchar**) &global_system_variables.completion_type, + (uchar**) &max_system_variables.completion_type, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, 2, 0, 1, 0}, + {"concurrent-insert", OPT_CONCURRENT_INSERT, + "Use concurrent insert with MyISAM. Disable with --concurrent-insert=0", + (uchar**) &myisam_concurrent_insert, (uchar**) &myisam_concurrent_insert, + 0, GET_ULONG, OPT_ARG, 1, 0, 2, 0, 0, 0}, + {"console", OPT_CONSOLE, "Write error output on screen; Don't remove the console window on windows.", + (uchar**) &opt_console, (uchar**) &opt_console, 0, GET_BOOL, NO_ARG, 0, 0, 0, + 0, 0, 0}, + {"core-file", OPT_WANT_CORE, "Write core on errors.", 0, 0, 0, GET_NO_ARG, + NO_ARG, 0, 0, 0, 0, 0, 0}, + {"datadir", 'h', "Path to the database root.", (uchar**) &mysql_data_home, + (uchar**) &mysql_data_home, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifndef DBUG_OFF + {"debug", '#', "Debug log.", (uchar**) &default_dbug_option, + (uchar**) &default_dbug_option, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"default-character-set", 'C', "Set the default character set (deprecated option, use --character-set-server instead).", + (uchar**) &default_character_set_name, (uchar**) &default_character_set_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"default-collation", OPT_DEFAULT_COLLATION, "Set the default collation (deprecated option, use --collation-server instead).", + (uchar**) &default_collation_name, (uchar**) &default_collation_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"default-storage-engine", OPT_STORAGE_ENGINE, + "Set the default storage engine (table type) for tables.", + (uchar**)&default_storage_engine_str, (uchar**)&default_storage_engine_str, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"default-table-type", OPT_STORAGE_ENGINE, + "(deprecated) Use --default-storage-engine.", + (uchar**)&default_storage_engine_str, (uchar**)&default_storage_engine_str, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"default-time-zone", OPT_DEFAULT_TIME_ZONE, "Set the default time zone.", + (uchar**) &default_tz_name, (uchar**) &default_tz_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"delay-key-write", OPT_DELAY_KEY_WRITE, "Type of DELAY_KEY_WRITE.", + 0,0,0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"delay-key-write-for-all-tables", OPT_DELAY_KEY_WRITE_ALL, + "Don't flush key buffers between writes for any MyISAM table (Deprecated option, use --delay-key-write=all instead).", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_OPENSSL + {"des-key-file", OPT_DES_KEY_FILE, + "Load keys for des_encrypt() and des_encrypt from given file.", + (uchar**) &des_key_file, (uchar**) &des_key_file, 0, GET_STR, REQUIRED_ARG, + 0, 0, 0, 0, 0, 0}, +#endif /* HAVE_OPENSSL */ +#ifdef HAVE_REPLICATION + {"disconnect-slave-event-count", OPT_DISCONNECT_SLAVE_EVENT_COUNT, + "Option used by mysql-test for debugging and testing of replication.", + (uchar**) &disconnect_slave_event_count, + (uchar**) &disconnect_slave_event_count, 0, GET_INT, REQUIRED_ARG, 0, 0, 0, + 0, 0, 0}, +#endif /* HAVE_REPLICATION */ + {"enable-locking", OPT_ENABLE_LOCK, + "Deprecated option, use --external-locking instead.", + (uchar**) &opt_external_locking, (uchar**) &opt_external_locking, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef __NT__ + {"enable-named-pipe", OPT_HAVE_NAMED_PIPE, "Enable the named pipe (NT).", + (uchar**) &opt_enable_named_pipe, (uchar**) &opt_enable_named_pipe, 0, GET_BOOL, + NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif +#ifdef HAVE_STACK_TRACE_ON_SEGV + {"enable-pstack", OPT_DO_PSTACK, "Print a symbolic stack trace on failure.", + (uchar**) &opt_do_pstack, (uchar**) &opt_do_pstack, 0, GET_BOOL, NO_ARG, 0, 0, + 0, 0, 0, 0}, +#endif /* HAVE_STACK_TRACE_ON_SEGV */ + {"engine-condition-pushdown", + OPT_ENGINE_CONDITION_PUSHDOWN, + "Push supported query conditions to the storage engine.", + (uchar**) &global_system_variables.engine_condition_pushdown, + (uchar**) &global_system_variables.engine_condition_pushdown, + 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0}, + /* See how it's handled in get_one_option() */ + {"event-scheduler", OPT_EVENT_SCHEDULER, "Enable/disable the event scheduler.", + NULL, NULL, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"exit-info", 'T', "Used for debugging; Use at your own risk!", 0, 0, 0, + GET_LONG, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"external-locking", OPT_USE_LOCKING, "Use system (external) locking (disabled by default). With this option enabled you can run myisamchk to test (not repair) tables while the MySQL server is running. Disable with --skip-external-locking.", + (uchar**) &opt_external_locking, (uchar**) &opt_external_locking, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"flush", OPT_FLUSH, "Flush tables to disk between SQL commands.", 0, 0, 0, + GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + /* We must always support the next option to make scripts like mysqltest + easier to do */ + {"gdb", OPT_DEBUGGING, + "Set up signals usable for debugging", + (uchar**) &opt_debugging, (uchar**) &opt_debugging, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"general_log", OPT_GENERAL_LOG, + "Enable|disable general log", (uchar**) &opt_log, + (uchar**) &opt_log, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_LARGE_PAGES + {"large-pages", OPT_ENABLE_LARGE_PAGES, "Enable support for large pages. \ +Disable with --skip-large-pages.", + (uchar**) &opt_large_pages, (uchar**) &opt_large_pages, 0, GET_BOOL, NO_ARG, 0, 0, 0, + 0, 0, 0}, +#endif + {"ignore-builtin-innodb", OPT_IGNORE_BUILTIN_INNODB , + "Disable initialization of builtin InnoDB plugin", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"init-connect", OPT_INIT_CONNECT, "Command(s) that are executed for each new connection", + (uchar**) &opt_init_connect, (uchar**) &opt_init_connect, 0, GET_STR_ALLOC, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifndef DISABLE_GRANT_OPTIONS + {"init-file", OPT_INIT_FILE, "Read SQL commands from this file at startup.", + (uchar**) &opt_init_file, (uchar**) &opt_init_file, 0, GET_STR, REQUIRED_ARG, + 0, 0, 0, 0, 0, 0}, +#endif + {"init-rpl-role", OPT_INIT_RPL_ROLE, "Set the replication role.", 0, 0, 0, + GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"init-slave", OPT_INIT_SLAVE, "Command(s) that are executed when a slave connects to this master", + (uchar**) &opt_init_slave, (uchar**) &opt_init_slave, 0, GET_STR_ALLOC, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"language", 'L', + "Client error messages in given language. May be given as a full path.", + (uchar**) &language_ptr, (uchar**) &language_ptr, 0, GET_STR, REQUIRED_ARG, + 0, 0, 0, 0, 0, 0}, + {"lc-time-names", OPT_LC_TIME_NAMES, + "Set the language used for the month names and the days of the week.", + (uchar**) &lc_time_names_name, + (uchar**) &lc_time_names_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + {"local-infile", OPT_LOCAL_INFILE, + "Enable/disable LOAD DATA LOCAL INFILE (takes values 1|0).", + (uchar**) &opt_local_infile, + (uchar**) &opt_local_infile, 0, GET_BOOL, OPT_ARG, + 1, 0, 0, 0, 0, 0}, + {"log", 'l', "Log connections and queries to file (deprecated option, use " + "--general_log/--general_log_file instead).", (uchar**) &opt_logname, + (uchar**) &opt_logname, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"general_log_file", OPT_GENERAL_LOG_FILE, + "Log connections and queries to given file.", (uchar**) &opt_logname, + (uchar**) &opt_logname, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"log-bin", OPT_BIN_LOG, + "Log update queries in binary format. Optional (but strongly recommended " + "to avoid replication problems if server's hostname changes) argument " + "should be the chosen location for the binary log files.", + (uchar**) &opt_bin_logname, (uchar**) &opt_bin_logname, 0, GET_STR_ALLOC, + OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"log-bin-index", OPT_BIN_LOG_INDEX, + "File that holds the names for last binary log files.", + (uchar**) &opt_binlog_index_name, (uchar**) &opt_binlog_index_name, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifndef TO_BE_REMOVED_IN_5_1_OR_6_0 + /* + In 5.0.6 we introduced the below option, then in 5.0.16 we renamed it to + log-bin-trust-function-creators but kept also the old name for + compatibility; the behaviour was also changed to apply only to functions + (and triggers). In a future release this old name could be removed. + */ + {"log-bin-trust-routine-creators", OPT_LOG_BIN_TRUST_FUNCTION_CREATORS, + "(deprecated) Use log-bin-trust-function-creators.", + (uchar**) &trust_function_creators, (uchar**) &trust_function_creators, 0, + GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif + /* + This option starts with "log-bin" to emphasize that it is specific of + binary logging. + */ + {"log-bin-trust-function-creators", OPT_LOG_BIN_TRUST_FUNCTION_CREATORS, + "If equal to 0 (the default), then when --log-bin is used, creation of " + "a stored function (or trigger) is allowed only to users having the SUPER privilege " + "and only if this stored function (trigger) may not break binary logging." + "Note that if ALL connections to this server ALWAYS use row-based binary " + "logging, the security issues do not exist and the binary logging cannot " + "break, so you can safely set this to 1." + ,(uchar**) &trust_function_creators, (uchar**) &trust_function_creators, 0, + GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"log-error", OPT_ERROR_LOG_FILE, "Error log file.", + (uchar**) &log_error_file_ptr, (uchar**) &log_error_file_ptr, 0, GET_STR, + OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"log-isam", OPT_ISAM_LOG, "Log all MyISAM changes to file.", + (uchar**) &myisam_log_filename, (uchar**) &myisam_log_filename, 0, GET_STR, + OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"log-long-format", '0', + "Log some extra information to update log. Please note that this option is deprecated; see --log-short-format option.", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef WITH_CSV_STORAGE_ENGINE + {"log-output", OPT_LOG_OUTPUT, + "Syntax: log-output[=value[,value...]], where \"value\" could be TABLE, " + "FILE or NONE.", + (uchar**) &log_output_str, (uchar**) &log_output_str, 0, + GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"log-queries-not-using-indexes", OPT_LOG_QUERIES_NOT_USING_INDEXES, + "Log queries that are executed without benefit of any index to the slow log if it is open.", + (uchar**) &opt_log_queries_not_using_indexes, (uchar**) &opt_log_queries_not_using_indexes, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"log-short-format", OPT_SHORT_LOG_FORMAT, + "Don't log extra information to update and slow-query logs.", + (uchar**) &opt_short_log_format, (uchar**) &opt_short_log_format, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"log-slave-updates", OPT_LOG_SLAVE_UPDATES, + "Tells the slave to log the updates from the slave thread to the binary log. You will need to turn it on if you plan to daisy-chain the slaves.", + (uchar**) &opt_log_slave_updates, (uchar**) &opt_log_slave_updates, 0, GET_BOOL, + NO_ARG, 0, 0, 0, 0, 0, 0}, + {"log-slow-admin-statements", OPT_LOG_SLOW_ADMIN_STATEMENTS, + "Log slow OPTIMIZE, ANALYZE, ALTER and other administrative statements to the slow log if it is open.", + (uchar**) &opt_log_slow_admin_statements, + (uchar**) &opt_log_slow_admin_statements, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"log-slow-slave-statements", OPT_LOG_SLOW_SLAVE_STATEMENTS, + "Log slow statements executed by slave thread to the slow log if it is open.", + (uchar**) &opt_log_slow_slave_statements, + (uchar**) &opt_log_slow_slave_statements, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"log_slow_queries", OPT_SLOW_QUERY_LOG, + "Log slow queries to a table or log file. Defaults logging to table " + "mysql.slow_log or hostname-slow.log if --log-output=file is used. " + "Must be enabled to activate other slow log options. " + "(deprecated option, use --slow_query_log/--slow_query_log_file instead)", + (uchar**) &opt_slow_logname, (uchar**) &opt_slow_logname, 0, GET_STR, OPT_ARG, + 0, 0, 0, 0, 0, 0}, + {"slow_query_log_file", OPT_SLOW_QUERY_LOG_FILE, + "Log slow queries to given log file. Defaults logging to hostname-slow.log. Must be enabled to activate other slow log options.", + (uchar**) &opt_slow_logname, (uchar**) &opt_slow_logname, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"log-tc", OPT_LOG_TC, + "Path to transaction coordinator log (used for transactions that affect " + "more than one storage engine, when binary log is disabled)", + (uchar**) &opt_tc_log_file, (uchar**) &opt_tc_log_file, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_MMAP + {"log-tc-size", OPT_LOG_TC_SIZE, "Size of transaction coordinator log.", + (uchar**) &opt_tc_log_size, (uchar**) &opt_tc_log_size, 0, GET_ULONG, + REQUIRED_ARG, TC_LOG_MIN_SIZE, TC_LOG_MIN_SIZE, ULONG_MAX, 0, + TC_LOG_PAGE_SIZE, 0}, +#endif + {"log-update", OPT_UPDATE_LOG, + "The update log is deprecated since version 5.0, is replaced by the binary \ +log and this option justs turns on --log-bin instead.", + (uchar**) &opt_update_logname, (uchar**) &opt_update_logname, 0, GET_STR, + OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"log-warnings", 'W', "Log some not critical warnings to the log file.", + (uchar**) &global_system_variables.log_warnings, + (uchar**) &max_system_variables.log_warnings, 0, GET_ULONG, OPT_ARG, 1, 0, 0, + 0, 0, 0}, + {"low-priority-updates", OPT_LOW_PRIORITY_UPDATES, + "INSERT/DELETE/UPDATE has lower priority than selects.", + (uchar**) &global_system_variables.low_priority_updates, + (uchar**) &max_system_variables.low_priority_updates, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"master-connect-retry", OPT_MASTER_CONNECT_RETRY, + "The number of seconds the slave thread will sleep before retrying to connect to the master in case the master goes down or the connection is lost.", + (uchar**) &master_connect_retry, (uchar**) &master_connect_retry, 0, GET_UINT, + REQUIRED_ARG, 60, 0, 0, 0, 0, 0}, + {"master-host", OPT_MASTER_HOST, + "Master hostname or IP address for replication. If not set, the slave thread will not be started. Note that the setting of master-host will be ignored if there exists a valid master.info file.", + (uchar**) &master_host, (uchar**) &master_host, 0, GET_STR, REQUIRED_ARG, 0, 0, + 0, 0, 0, 0}, + {"master-info-file", OPT_MASTER_INFO_FILE, + "The location and name of the file that remembers the master and where the I/O replication \ +thread is in the master's binlogs.", + (uchar**) &master_info_file, (uchar**) &master_info_file, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"master-password", OPT_MASTER_PASSWORD, + "The password the slave thread will authenticate with when connecting to the master. If not set, an empty password is assumed.The value in master.info will take precedence if it can be read.", + (uchar**)&master_password, (uchar**)&master_password, 0, + GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"master-port", OPT_MASTER_PORT, + "The port the master is listening on. If not set, the compiled setting of MYSQL_PORT is assumed. If you have not tinkered with configure options, this should be 3306. The value in master.info will take precedence if it can be read.", + (uchar**) &master_port, (uchar**) &master_port, 0, GET_UINT, REQUIRED_ARG, + MYSQL_PORT, 0, 0, 0, 0, 0}, + {"master-retry-count", OPT_MASTER_RETRY_COUNT, + "The number of tries the slave will make to connect to the master before giving up.", + (uchar**) &master_retry_count, (uchar**) &master_retry_count, 0, GET_ULONG, + REQUIRED_ARG, 3600*24, 0, 0, 0, 0, 0}, + {"master-ssl", OPT_MASTER_SSL, + "Enable the slave to connect to the master using SSL.", + (uchar**) &master_ssl, (uchar**) &master_ssl, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, + 0, 0}, + {"master-ssl-ca", OPT_MASTER_SSL_CA, + "Master SSL CA file. Only applies if you have enabled master-ssl.", + (uchar**) &master_ssl_ca, (uchar**) &master_ssl_ca, 0, GET_STR, OPT_ARG, + 0, 0, 0, 0, 0, 0}, + {"master-ssl-capath", OPT_MASTER_SSL_CAPATH, + "Master SSL CA path. Only applies if you have enabled master-ssl.", + (uchar**) &master_ssl_capath, (uchar**) &master_ssl_capath, 0, GET_STR, OPT_ARG, + 0, 0, 0, 0, 0, 0}, + {"master-ssl-cert", OPT_MASTER_SSL_CERT, + "Master SSL certificate file name. Only applies if you have enabled \ +master-ssl", + (uchar**) &master_ssl_cert, (uchar**) &master_ssl_cert, 0, GET_STR, OPT_ARG, + 0, 0, 0, 0, 0, 0}, + {"master-ssl-cipher", OPT_MASTER_SSL_CIPHER, + "Master SSL cipher. Only applies if you have enabled master-ssl.", + (uchar**) &master_ssl_cipher, (uchar**) &master_ssl_capath, 0, GET_STR, OPT_ARG, + 0, 0, 0, 0, 0, 0}, + {"master-ssl-key", OPT_MASTER_SSL_KEY, + "Master SSL keyfile name. Only applies if you have enabled master-ssl.", + (uchar**) &master_ssl_key, (uchar**) &master_ssl_key, 0, GET_STR, OPT_ARG, + 0, 0, 0, 0, 0, 0}, + {"master-user", OPT_MASTER_USER, + "The username the slave thread will use for authentication when connecting to the master. The user must have FILE privilege. If the master user is not set, user test is assumed. The value in master.info will take precedence if it can be read.", + (uchar**) &master_user, (uchar**) &master_user, 0, GET_STR, REQUIRED_ARG, 0, 0, + 0, 0, 0, 0}, +#ifdef HAVE_REPLICATION + {"max-binlog-dump-events", OPT_MAX_BINLOG_DUMP_EVENTS, + "Option used by mysql-test for debugging and testing of replication.", + (uchar**) &max_binlog_dump_events, (uchar**) &max_binlog_dump_events, 0, + GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#endif /* HAVE_REPLICATION */ + {"memlock", OPT_MEMLOCK, "Lock mysqld in memory.", (uchar**) &locked_in_memory, + (uchar**) &locked_in_memory, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"myisam-recover", OPT_MYISAM_RECOVER, + "Syntax: myisam-recover[=option[,option...]], where option can be DEFAULT, BACKUP, FORCE or QUICK.", + (uchar**) &myisam_recover_options_str, (uchar**) &myisam_recover_options_str, 0, + GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE + {"ndb-connectstring", OPT_NDB_CONNECTSTRING, + "Connect string for ndbcluster.", + (uchar**) &opt_ndb_connectstring, + (uchar**) &opt_ndb_connectstring, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"ndb-mgmd-host", OPT_NDB_MGMD, + "Set host and port for ndb_mgmd. Syntax: hostname[:port]", + (uchar**) &opt_ndb_mgmd, + (uchar**) &opt_ndb_mgmd, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"ndb-nodeid", OPT_NDB_NODEID, + "Nodeid for this mysqlserver in the cluster.", + (uchar**) &opt_ndb_nodeid, + (uchar**) &opt_ndb_nodeid, + 0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"ndb-autoincrement-prefetch-sz", OPT_NDB_AUTOINCREMENT_PREFETCH_SZ, + "Specify number of autoincrement values that are prefetched.", + (uchar**) &global_system_variables.ndb_autoincrement_prefetch_sz, + (uchar**) &max_system_variables.ndb_autoincrement_prefetch_sz, + 0, GET_ULONG, REQUIRED_ARG, 1, 1, 256, 0, 0, 0}, + {"ndb-force-send", OPT_NDB_FORCE_SEND, + "Force send of buffers to ndb immediately without waiting for " + "other threads.", + (uchar**) &global_system_variables.ndb_force_send, + (uchar**) &global_system_variables.ndb_force_send, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"ndb_force_send", OPT_NDB_FORCE_SEND, + "same as --ndb-force-send.", + (uchar**) &global_system_variables.ndb_force_send, + (uchar**) &global_system_variables.ndb_force_send, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"ndb-extra-logging", OPT_NDB_EXTRA_LOGGING, + "Turn on more logging in the error log.", + (uchar**) &ndb_extra_logging, + (uchar**) &ndb_extra_logging, + 0, GET_INT, OPT_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_NDB_BINLOG + {"ndb-report-thresh-binlog-epoch-slip", OPT_NDB_REPORT_THRESH_BINLOG_EPOCH_SLIP, + "Threshold on number of epochs to be behind before reporting binlog status. " + "E.g. 3 means that if the difference between what epoch has been received " + "from the storage nodes and what has been applied to the binlog is 3 or more, " + "a status message will be sent to the cluster log.", + (uchar**) &ndb_report_thresh_binlog_epoch_slip, + (uchar**) &ndb_report_thresh_binlog_epoch_slip, + 0, GET_ULONG, REQUIRED_ARG, 3, 0, 256, 0, 0, 0}, + {"ndb-report-thresh-binlog-mem-usage", OPT_NDB_REPORT_THRESH_BINLOG_MEM_USAGE, + "Threshold on percentage of free memory before reporting binlog status. E.g. " + "10 means that if amount of available memory for receiving binlog data from " + "the storage nodes goes below 10%, " + "a status message will be sent to the cluster log.", + (uchar**) &ndb_report_thresh_binlog_mem_usage, + (uchar**) &ndb_report_thresh_binlog_mem_usage, + 0, GET_ULONG, REQUIRED_ARG, 10, 0, 100, 0, 0, 0}, +#endif + {"ndb-use-exact-count", OPT_NDB_USE_EXACT_COUNT, + "Use exact records count during query planning and for fast " + "select count(*), disable for faster queries.", + (uchar**) &global_system_variables.ndb_use_exact_count, + (uchar**) &global_system_variables.ndb_use_exact_count, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"ndb_use_exact_count", OPT_NDB_USE_EXACT_COUNT, + "same as --ndb-use-exact-count.", + (uchar**) &global_system_variables.ndb_use_exact_count, + (uchar**) &global_system_variables.ndb_use_exact_count, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"ndb-use-transactions", OPT_NDB_USE_TRANSACTIONS, + "Use transactions for large inserts, if enabled then large " + "inserts will be split into several smaller transactions", + (uchar**) &global_system_variables.ndb_use_transactions, + (uchar**) &global_system_variables.ndb_use_transactions, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"ndb_use_transactions", OPT_NDB_USE_TRANSACTIONS, + "same as --ndb-use-transactions.", + (uchar**) &global_system_variables.ndb_use_transactions, + (uchar**) &global_system_variables.ndb_use_transactions, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"ndb-shm", OPT_NDB_SHM, + "Use shared memory connections when available.", + (uchar**) &opt_ndb_shm, + (uchar**) &opt_ndb_shm, + 0, GET_BOOL, OPT_ARG, OPT_NDB_SHM_DEFAULT, 0, 0, 0, 0, 0}, + {"ndb-optimized-node-selection", OPT_NDB_OPTIMIZED_NODE_SELECTION, + "Select nodes for transactions in a more optimal way.", + (uchar**) &opt_ndb_optimized_node_selection, + (uchar**) &opt_ndb_optimized_node_selection, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + { "ndb-cache-check-time", OPT_NDB_CACHE_CHECK_TIME, + "A dedicated thread is created to, at the given millisecons interval, invalidate the query cache if another MySQL server in the cluster has changed the data in the database.", + (uchar**) &opt_ndb_cache_check_time, (uchar**) &opt_ndb_cache_check_time, 0, GET_ULONG, REQUIRED_ARG, + 0, 0, LONG_TIMEOUT, 0, 1, 0}, + {"ndb-index-stat-enable", OPT_NDB_INDEX_STAT_ENABLE, + "Use ndb index statistics in query optimization.", + (uchar**) &global_system_variables.ndb_index_stat_enable, + (uchar**) &max_system_variables.ndb_index_stat_enable, + 0, GET_BOOL, OPT_ARG, 0, 0, 1, 0, 0, 0}, +#endif + {"ndb-use-copying-alter-table", + OPT_NDB_USE_COPYING_ALTER_TABLE, + "Force ndbcluster to always copy tables at alter table (should only be used if on-line alter table fails).", + (uchar**) &global_system_variables.ndb_use_copying_alter_table, + (uchar**) &global_system_variables.ndb_use_copying_alter_table, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"new", 'n', "Use very new possible 'unsafe' functions.", + (uchar**) &global_system_variables.new_mode, + (uchar**) &max_system_variables.new_mode, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef NOT_YET + {"no-mix-table-types", OPT_NO_MIX_TYPE, "Don't allow commands with uses two different table types.", + (uchar**) &opt_no_mix_types, (uchar**) &opt_no_mix_types, 0, GET_BOOL, NO_ARG, + 0, 0, 0, 0, 0, 0}, +#endif + {"old-alter-table", OPT_OLD_ALTER_TABLE, + "Use old, non-optimized alter table.", + (uchar**) &global_system_variables.old_alter_table, + (uchar**) &max_system_variables.old_alter_table, 0, GET_BOOL, NO_ARG, + 0, 0, 0, 0, 0, 0}, + {"old-passwords", OPT_OLD_PASSWORDS, "Use old password encryption method (needed for 4.0 and older clients).", + (uchar**) &global_system_variables.old_passwords, + (uchar**) &max_system_variables.old_passwords, 0, GET_BOOL, NO_ARG, + 0, 0, 0, 0, 0, 0}, + {"one-thread", OPT_ONE_THREAD, + "(deprecated): Only use one thread (for debugging under Linux). Use thread-handling=no-threads instead", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"old-style-user-limits", OPT_OLD_STYLE_USER_LIMITS, + "Enable old-style user limits (before 5.0.3 user resources were counted per each user+host vs. per account)", + (uchar**) &opt_old_style_user_limits, (uchar**) &opt_old_style_user_limits, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"pid-file", OPT_PID_FILE, "Pid file used by safe_mysqld.", + (uchar**) &pidfile_name_ptr, (uchar**) &pidfile_name_ptr, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"port", 'P', "Port number to use for connection or 0 for default to, in " + "order of preference, my.cnf, $MYSQL_TCP_PORT, " +#if MYSQL_PORT_DEFAULT == 0 + "/etc/services, " +#endif + "built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").", + (uchar**) &mysqld_port, + (uchar**) &mysqld_port, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"port-open-timeout", OPT_PORT_OPEN_TIMEOUT, + "Maximum time in seconds to wait for the port to become free. " + "(Default: no wait)", (uchar**) &mysqld_port_timeout, + (uchar**) &mysqld_port_timeout, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + {"profiling_history_size", OPT_PROFILING, "Limit of query profiling memory", + (uchar**) &global_system_variables.profiling_history_size, + (uchar**) &max_system_variables.profiling_history_size, + 0, GET_ULONG, REQUIRED_ARG, 15, 0, 100, 0, 0, 0}, +#endif + {"relay-log", OPT_RELAY_LOG, + "The location and name to use for relay logs.", + (uchar**) &opt_relay_logname, (uchar**) &opt_relay_logname, 0, + GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"relay-log-index", OPT_RELAY_LOG_INDEX, + "The location and name to use for the file that keeps a list of the last \ +relay logs.", + (uchar**) &opt_relaylog_index_name, (uchar**) &opt_relaylog_index_name, 0, + GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"relay-log-info-file", OPT_RELAY_LOG_INFO_FILE, + "The location and name of the file that remembers where the SQL replication \ +thread is in the relay logs.", + (uchar**) &relay_log_info_file, (uchar**) &relay_log_info_file, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-do-db", OPT_REPLICATE_DO_DB, + "Tells the slave thread to restrict replication to the specified database. To specify more than one database, use the directive multiple times, once for each database. Note that this will only work if you do not use cross-database queries such as UPDATE some_db.some_table SET foo='bar' while having selected a different or no database. If you need cross database updates to work, make sure you have 3.23.28 or later, and use replicate-wild-do-table=db_name.%.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-do-table", OPT_REPLICATE_DO_TABLE, + "Tells the slave thread to restrict replication to the specified table. To specify more than one table, use the directive multiple times, once for each table. This will work for cross-database updates, in contrast to replicate-do-db.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-ignore-db", OPT_REPLICATE_IGNORE_DB, + "Tells the slave thread to not replicate to the specified database. To specify more than one database to ignore, use the directive multiple times, once for each database. This option will not work if you use cross database updates. If you need cross database updates to work, make sure you have 3.23.28 or later, and use replicate-wild-ignore-table=db_name.%. ", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-ignore-table", OPT_REPLICATE_IGNORE_TABLE, + "Tells the slave thread to not replicate to the specified table. To specify more than one table to ignore, use the directive multiple times, once for each table. This will work for cross-datbase updates, in contrast to replicate-ignore-db.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-rewrite-db", OPT_REPLICATE_REWRITE_DB, + "Updates to a database with a different name than the original. Example: replicate-rewrite-db=master_db_name->slave_db_name.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_REPLICATION + {"replicate-same-server-id", OPT_REPLICATE_SAME_SERVER_ID, + "In replication, if set to 1, do not skip events having our server id. \ +Default value is 0 (to break infinite loops in circular replication). \ +Can't be set to 1 if --log-slave-updates is used.", + (uchar**) &replicate_same_server_id, + (uchar**) &replicate_same_server_id, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"replicate-wild-do-table", OPT_REPLICATE_WILD_DO_TABLE, + "Tells the slave thread to restrict replication to the tables that match the specified wildcard pattern. To specify more than one table, use the directive multiple times, once for each table. This will work for cross-database updates. Example: replicate-wild-do-table=foo%.bar% will replicate only updates to tables in all databases that start with foo and whose table names start with bar.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-wild-ignore-table", OPT_REPLICATE_WILD_IGNORE_TABLE, + "Tells the slave thread to not replicate to the tables that match the given wildcard pattern. To specify more than one table to ignore, use the directive multiple times, once for each table. This will work for cross-database updates. Example: replicate-wild-ignore-table=foo%.bar% will not do updates to tables in databases that start with foo and whose table names start with bar.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + // In replication, we may need to tell the other servers how to connect + {"report-host", OPT_REPORT_HOST, + "Hostname or IP of the slave to be reported to to the master during slave registration. Will appear in the output of SHOW SLAVE HOSTS. Leave unset if you do not want the slave to register itself with the master. Note that it is not sufficient for the master to simply read the IP of the slave off the socket once the slave connects. Due to NAT and other routing issues, that IP may not be valid for connecting to the slave from the master or other hosts.", + (uchar**) &report_host, (uchar**) &report_host, 0, GET_STR, REQUIRED_ARG, 0, 0, + 0, 0, 0, 0}, + {"report-password", OPT_REPORT_PASSWORD, "Undocumented.", + (uchar**) &report_password, (uchar**) &report_password, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"report-port", OPT_REPORT_PORT, + "Port for connecting to slave reported to the master during slave registration. Set it only if the slave is listening on a non-default port or if you have a special tunnel from the master or other clients to the slave. If not sure, leave this option unset.", + (uchar**) &report_port, (uchar**) &report_port, 0, GET_UINT, REQUIRED_ARG, + MYSQL_PORT, 0, 0, 0, 0, 0}, + {"report-user", OPT_REPORT_USER, "Undocumented.", (uchar**) &report_user, + (uchar**) &report_user, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"rpl-recovery-rank", OPT_RPL_RECOVERY_RANK, "Undocumented.", + (uchar**) &rpl_recovery_rank, (uchar**) &rpl_recovery_rank, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"safe-mode", OPT_SAFE, "Skip some optimize stages (for testing).", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifndef TO_BE_DELETED + {"safe-show-database", OPT_SAFE_SHOW_DB, + "Deprecated option; use GRANT SHOW DATABASES instead...", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"safe-user-create", OPT_SAFE_USER_CREATE, + "Don't allow new user creation by the user who has no write privileges to the mysql.user table.", + (uchar**) &opt_safe_user_create, (uchar**) &opt_safe_user_create, 0, GET_BOOL, + NO_ARG, 0, 0, 0, 0, 0, 0}, + {"safemalloc-mem-limit", OPT_SAFEMALLOC_MEM_LIMIT, + "Simulate memory shortage when compiled with the --with-debug=full option.", + 0, 0, 0, GET_ULL, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"secure-auth", OPT_SECURE_AUTH, "Disallow authentication for accounts that have old (pre-4.1) passwords.", + (uchar**) &opt_secure_auth, (uchar**) &opt_secure_auth, 0, GET_BOOL, NO_ARG, + my_bool(0), 0, 0, 0, 0, 0}, + {"secure-file-priv", OPT_SECURE_FILE_PRIV, + "Limit LOAD DATA, SELECT ... OUTFILE, and LOAD_FILE() to files within specified directory", + (uchar**) &opt_secure_file_priv, (uchar**) &opt_secure_file_priv, 0, + GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"server-id", OPT_SERVER_ID, + "Uniquely identifies the server instance in the community of replication partners.", + (uchar**) &server_id, (uchar**) &server_id, 0, GET_ULONG, REQUIRED_ARG, 0, 0, UINT_MAX32, + 0, 0, 0}, + {"set-variable", 'O', + "Change the value of a variable. Please note that this option is deprecated;you can set variables directly with --variable-name=value.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_SMEM + {"shared-memory", OPT_ENABLE_SHARED_MEMORY, + "Enable the shared memory.",(uchar**) &opt_enable_shared_memory, (uchar**) &opt_enable_shared_memory, + 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif +#ifdef HAVE_SMEM + {"shared-memory-base-name",OPT_SHARED_MEMORY_BASE_NAME, + "Base name of shared memory.", (uchar**) &shared_memory_base_name, (uchar**) &shared_memory_base_name, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"show-slave-auth-info", OPT_SHOW_SLAVE_AUTH_INFO, + "Show user and password in SHOW SLAVE HOSTS on this master", + (uchar**) &opt_show_slave_auth_info, (uchar**) &opt_show_slave_auth_info, 0, + GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifndef DISABLE_GRANT_OPTIONS + {"skip-grant-tables", OPT_SKIP_GRANT, + "Start without grant tables. This gives all users FULL ACCESS to all tables!", + (uchar**) &opt_noacl, (uchar**) &opt_noacl, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, + 0}, +#endif + {"skip-host-cache", OPT_SKIP_HOST_CACHE, "Don't cache host names.", 0, 0, 0, + GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"skip-locking", OPT_SKIP_LOCK, + "Deprecated option, use --skip-external-locking instead.", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"skip-name-resolve", OPT_SKIP_RESOLVE, + "Don't resolve hostnames. All hostnames are IP's or 'localhost'.", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"skip-networking", OPT_SKIP_NETWORKING, + "Don't allow connection with TCP/IP.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, + 0, 0, 0}, + {"skip-new", OPT_SKIP_NEW, "Don't use new, possible wrong routines.", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, +#ifndef DBUG_OFF +#ifdef SAFEMALLOC + {"skip-safemalloc", OPT_SKIP_SAFEMALLOC, + "Don't use the memory allocation checking.", 0, 0, 0, GET_NO_ARG, NO_ARG, + 0, 0, 0, 0, 0, 0}, +#endif +#endif + {"skip-show-database", OPT_SKIP_SHOW_DB, + "Don't allow 'SHOW DATABASE' commands.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, + 0, 0, 0, 0}, + {"skip-slave-start", OPT_SKIP_SLAVE_START, + "If set, slave is not autostarted.", (uchar**) &opt_skip_slave_start, + (uchar**) &opt_skip_slave_start, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"skip-stack-trace", OPT_SKIP_STACK_TRACE, + "Don't print a stack trace on failure.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, + 0, 0, 0, 0}, + {"skip-symlink", OPT_SKIP_SYMLINKS, "Don't allow symlinking of tables. Deprecated option. Use --skip-symbolic-links instead.", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"skip-thread-priority", OPT_SKIP_PRIOR, + "Don't give threads different priorities. Deprecated option.", 0, 0, 0, GET_NO_ARG, NO_ARG, + DEFAULT_SKIP_THREAD_PRIORITY, 0, 0, 0, 0, 0}, +#ifdef HAVE_REPLICATION + {"slave-load-tmpdir", OPT_SLAVE_LOAD_TMPDIR, + "The location where the slave should put its temporary files when \ +replicating a LOAD DATA INFILE command.", + (uchar**) &slave_load_tmpdir, (uchar**) &slave_load_tmpdir, 0, GET_STR_ALLOC, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"slave-skip-errors", OPT_SLAVE_SKIP_ERRORS, + "Tells the slave thread to continue replication when a query event returns an error from the provided list.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"slave-exec-mode", OPT_SLAVE_EXEC_MODE, + "Modes for how replication events should be executed. Legal values are STRICT (default) and IDEMPOTENT. In IDEMPOTENT mode, replication will not stop for operations that are idempotent. In STRICT mode, replication will stop on any unexpected difference between the master and the slave.", + (uchar**) &slave_exec_mode_str, (uchar**) &slave_exec_mode_str, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"slow-query-log", OPT_SLOW_LOG, + "Enable|disable slow query log", (uchar**) &opt_slow_log, + (uchar**) &opt_slow_log, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"socket", OPT_SOCKET, "Socket file to use for connection.", + (uchar**) &mysqld_unix_port, (uchar**) &mysqld_unix_port, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, +#ifdef HAVE_REPLICATION + {"sporadic-binlog-dump-fail", OPT_SPORADIC_BINLOG_DUMP_FAIL, + "Option used by mysql-test for debugging and testing of replication.", + (uchar**) &opt_sporadic_binlog_dump_fail, + (uchar**) &opt_sporadic_binlog_dump_fail, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, + 0}, +#endif /* HAVE_REPLICATION */ + {"sql-bin-update-same", OPT_SQL_BIN_UPDATE_SAME, + "The update log is deprecated since version 5.0, is replaced by the binary \ +log and this option does nothing anymore.", + 0, 0, 0, GET_DISABLED, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"sql-mode", OPT_SQL_MODE, + "Syntax: sql-mode=option[,option[,option...]] where option can be one of: REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, ONLY_FULL_GROUP_BY, NO_UNSIGNED_SUBTRACTION.", + (uchar**) &sql_mode_str, (uchar**) &sql_mode_str, 0, GET_STR, REQUIRED_ARG, 0, + 0, 0, 0, 0, 0}, +#ifdef HAVE_OPENSSL +#include "sslopt-longopts.h" +#endif +#ifdef __WIN__ + {"standalone", OPT_STANDALONE, + "Dummy option to start as a standalone program (NT).", 0, 0, 0, GET_NO_ARG, + NO_ARG, 0, 0, 0, 0, 0, 0}, +#endif + {"symbolic-links", 's', "Enable symbolic link support.", + (uchar**) &my_use_symdir, (uchar**) &my_use_symdir, 0, GET_BOOL, NO_ARG, + /* + The system call realpath() produces warnings under valgrind and + purify. These are not suppressed: instead we disable symlinks + option if compiled with valgrind support. + */ + IF_PURIFY(0,1), 0, 0, 0, 0, 0}, + {"sysdate-is-now", OPT_SYSDATE_IS_NOW, + "Non-default option to alias SYSDATE() to NOW() to make it safe-replicable. Since 5.0, SYSDATE() returns a `dynamic' value different for different invocations, even within the same statement.", + (uchar**) &global_system_variables.sysdate_is_now, + 0, 0, GET_BOOL, NO_ARG, 0, 0, 1, 0, 1, 0}, + {"tc-heuristic-recover", OPT_TC_HEURISTIC_RECOVER, + "Decision to use in heuristic recover process. Possible values are COMMIT or ROLLBACK.", + (uchar**) &opt_tc_heuristic_recover, (uchar**) &opt_tc_heuristic_recover, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"temp-pool", OPT_TEMP_POOL, +#if (ENABLE_TEMP_POOL) + "Using this option will cause most temporary files created to use a small set of names, rather than a unique name for each new file.", +#else + "This option is ignored on this OS.", +#endif + (uchar**) &use_temp_pool, (uchar**) &use_temp_pool, 0, GET_BOOL, NO_ARG, 1, + 0, 0, 0, 0, 0}, + + {"timed_mutexes", OPT_TIMED_MUTEXES, + "Specify whether to time mutexes (only InnoDB mutexes are currently supported)", + (uchar**) &timed_mutexes, (uchar**) &timed_mutexes, 0, GET_BOOL, NO_ARG, 0, + 0, 0, 0, 0, 0}, + {"tmpdir", 't', + "Path for temporary files. Several paths may be specified, separated by a " +#if defined(__WIN__) || defined(__NETWARE__) + "semicolon (;)" +#else + "colon (:)" +#endif + ", in this case they are used in a round-robin fashion.", + (uchar**) &opt_mysql_tmpdir, + (uchar**) &opt_mysql_tmpdir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"transaction-isolation", OPT_TX_ISOLATION, + "Default transaction isolation level.", 0, 0, 0, GET_STR, REQUIRED_ARG, 0, + 0, 0, 0, 0, 0}, + {"use-symbolic-links", 's', "Enable symbolic link support. Deprecated option; use --symbolic-links instead.", + (uchar**) &my_use_symdir, (uchar**) &my_use_symdir, 0, GET_BOOL, NO_ARG, + IF_PURIFY(0,1), 0, 0, 0, 0, 0}, + {"user", 'u', "Run mysqld daemon as user.", 0, 0, 0, GET_STR, REQUIRED_ARG, + 0, 0, 0, 0, 0, 0}, + {"verbose", 'v', "Used with --help option for detailed help", + (uchar**) &opt_verbose, (uchar**) &opt_verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, + 0, 0}, + {"version", 'V', "Output version information and exit.", 0, 0, 0, GET_NO_ARG, + NO_ARG, 0, 0, 0, 0, 0, 0}, + {"warnings", 'W', "Deprecated; use --log-warnings instead.", + (uchar**) &global_system_variables.log_warnings, + (uchar**) &max_system_variables.log_warnings, 0, GET_ULONG, OPT_ARG, + 1, 0, ULONG_MAX, 0, 0, 0}, + { "back_log", OPT_BACK_LOG, + "The number of outstanding connection requests MySQL can have. This comes into play when the main MySQL thread gets very many connection requests in a very short time.", + (uchar**) &back_log, (uchar**) &back_log, 0, GET_ULONG, + REQUIRED_ARG, 50, 1, 65535, 0, 1, 0 }, + {"binlog_cache_size", OPT_BINLOG_CACHE_SIZE, + "The size of the cache to hold the SQL statements for the binary log during a transaction. If you often use big, multi-statement transactions you can increase this to get more performance.", + (uchar**) &binlog_cache_size, (uchar**) &binlog_cache_size, 0, GET_ULONG, + REQUIRED_ARG, 32*1024L, IO_SIZE, ULONG_MAX, 0, IO_SIZE, 0}, + {"bulk_insert_buffer_size", OPT_BULK_INSERT_BUFFER_SIZE, + "Size of tree cache used in bulk insert optimisation. Note that this is a limit per thread!", + (uchar**) &global_system_variables.bulk_insert_buff_size, + (uchar**) &max_system_variables.bulk_insert_buff_size, + 0, GET_ULONG, REQUIRED_ARG, 8192*1024, 0, ULONG_MAX, 0, 1, 0}, + {"connect_timeout", OPT_CONNECT_TIMEOUT, + "The number of seconds the mysqld server is waiting for a connect packet before responding with 'Bad handshake'.", + (uchar**) &connect_timeout, (uchar**) &connect_timeout, + 0, GET_ULONG, REQUIRED_ARG, CONNECT_TIMEOUT, 2, LONG_TIMEOUT, 0, 1, 0 }, + { "date_format", OPT_DATE_FORMAT, + "The DATE format (For future).", + (uchar**) &opt_date_time_formats[MYSQL_TIMESTAMP_DATE], + (uchar**) &opt_date_time_formats[MYSQL_TIMESTAMP_DATE], + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + { "datetime_format", OPT_DATETIME_FORMAT, + "The DATETIME/TIMESTAMP format (for future).", + (uchar**) &opt_date_time_formats[MYSQL_TIMESTAMP_DATETIME], + (uchar**) &opt_date_time_formats[MYSQL_TIMESTAMP_DATETIME], + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + { "default_week_format", OPT_DEFAULT_WEEK_FORMAT, + "The default week format used by WEEK() functions.", + (uchar**) &global_system_variables.default_week_format, + (uchar**) &max_system_variables.default_week_format, + 0, GET_ULONG, REQUIRED_ARG, 0, 0, 7L, 0, 1, 0}, + {"delayed_insert_limit", OPT_DELAYED_INSERT_LIMIT, + "After inserting delayed_insert_limit rows, the INSERT DELAYED handler will check if there are any SELECT statements pending. If so, it allows these to execute before continuing.", + (uchar**) &delayed_insert_limit, (uchar**) &delayed_insert_limit, 0, GET_ULONG, + REQUIRED_ARG, DELAYED_LIMIT, 1, ULONG_MAX, 0, 1, 0}, + {"delayed_insert_timeout", OPT_DELAYED_INSERT_TIMEOUT, + "How long a INSERT DELAYED thread should wait for INSERT statements before terminating.", + (uchar**) &delayed_insert_timeout, (uchar**) &delayed_insert_timeout, 0, + GET_ULONG, REQUIRED_ARG, DELAYED_WAIT_TIMEOUT, 1, LONG_TIMEOUT, 0, 1, 0}, + { "delayed_queue_size", OPT_DELAYED_QUEUE_SIZE, + "What size queue (in rows) should be allocated for handling INSERT DELAYED. If the queue becomes full, any client that does INSERT DELAYED will wait until there is room in the queue again.", + (uchar**) &delayed_queue_size, (uchar**) &delayed_queue_size, 0, GET_ULONG, + REQUIRED_ARG, DELAYED_QUEUE_SIZE, 1, ULONG_MAX, 0, 1, 0}, + {"div_precision_increment", OPT_DIV_PRECINCREMENT, + "Precision of the result of '/' operator will be increased on that value.", + (uchar**) &global_system_variables.div_precincrement, + (uchar**) &max_system_variables.div_precincrement, 0, GET_ULONG, + REQUIRED_ARG, 4, 0, DECIMAL_MAX_SCALE, 0, 0, 0}, + {"expire_logs_days", OPT_EXPIRE_LOGS_DAYS, + "If non-zero, binary logs will be purged after expire_logs_days " + "days; possible purges happen at startup and at binary log rotation.", + (uchar**) &expire_logs_days, + (uchar**) &expire_logs_days, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, 99, 0, 1, 0}, + { "flush_time", OPT_FLUSH_TIME, + "A dedicated thread is created to flush all tables at the given interval.", + (uchar**) &flush_time, (uchar**) &flush_time, 0, GET_ULONG, REQUIRED_ARG, + FLUSH_TIME, 0, LONG_TIMEOUT, 0, 1, 0}, + { "ft_boolean_syntax", OPT_FT_BOOLEAN_SYNTAX, + "List of operators for MATCH ... AGAINST ( ... IN BOOLEAN MODE)", + 0, 0, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + { "ft_max_word_len", OPT_FT_MAX_WORD_LEN, + "The maximum length of the word to be included in a FULLTEXT index. Note: FULLTEXT indexes must be rebuilt after changing this variable.", + (uchar**) &ft_max_word_len, (uchar**) &ft_max_word_len, 0, GET_ULONG, + REQUIRED_ARG, HA_FT_MAXCHARLEN, 10, HA_FT_MAXCHARLEN, 0, 1, 0}, + { "ft_min_word_len", OPT_FT_MIN_WORD_LEN, + "The minimum length of the word to be included in a FULLTEXT index. Note: FULLTEXT indexes must be rebuilt after changing this variable.", + (uchar**) &ft_min_word_len, (uchar**) &ft_min_word_len, 0, GET_ULONG, + REQUIRED_ARG, 4, 1, HA_FT_MAXCHARLEN, 0, 1, 0}, + { "ft_query_expansion_limit", OPT_FT_QUERY_EXPANSION_LIMIT, + "Number of best matches to use for query expansion", + (uchar**) &ft_query_expansion_limit, (uchar**) &ft_query_expansion_limit, 0, GET_ULONG, + REQUIRED_ARG, 20, 0, 1000, 0, 1, 0}, + { "ft_stopword_file", OPT_FT_STOPWORD_FILE, + "Use stopwords from this file instead of built-in list.", + (uchar**) &ft_stopword_file, (uchar**) &ft_stopword_file, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + { "group_concat_max_len", OPT_GROUP_CONCAT_MAX_LEN, + "The maximum length of the result of function group_concat.", + (uchar**) &global_system_variables.group_concat_max_len, + (uchar**) &max_system_variables.group_concat_max_len, 0, GET_ULONG, + REQUIRED_ARG, 1024, 4, ULONG_MAX, 0, 1, 0}, + {"interactive_timeout", OPT_INTERACTIVE_TIMEOUT, + "The number of seconds the server waits for activity on an interactive connection before closing it.", + (uchar**) &global_system_variables.net_interactive_timeout, + (uchar**) &max_system_variables.net_interactive_timeout, 0, + GET_ULONG, REQUIRED_ARG, NET_WAIT_TIMEOUT, 1, LONG_TIMEOUT, 0, 1, 0}, + {"join_buffer_size", OPT_JOIN_BUFF_SIZE, + "The size of the buffer that is used for full joins.", + (uchar**) &global_system_variables.join_buff_size, + (uchar**) &max_system_variables.join_buff_size, 0, GET_ULONG, + REQUIRED_ARG, 128*1024L, IO_SIZE*2+MALLOC_OVERHEAD, ULONG_MAX, + MALLOC_OVERHEAD, IO_SIZE, 0}, + {"keep_files_on_create", OPT_KEEP_FILES_ON_CREATE, + "Don't overwrite stale .MYD and .MYI even if no directory is specified.", + (uchar**) &global_system_variables.keep_files_on_create, + (uchar**) &max_system_variables.keep_files_on_create, + 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"key_buffer_size", OPT_KEY_BUFFER_SIZE, + "The size of the buffer used for index blocks for MyISAM tables. Increase this to get better index handling (for all reads and multiple writes) to as much as you can afford; 64M on a 256M machine that mainly runs MySQL is quite common.", + (uchar**) &dflt_key_cache_var.param_buff_size, + (uchar**) 0, + 0, (GET_ULL | GET_ASK_ADDR), + REQUIRED_ARG, KEY_CACHE_SIZE, MALLOC_OVERHEAD, SIZE_T_MAX, MALLOC_OVERHEAD, + IO_SIZE, 0}, + {"key_cache_age_threshold", OPT_KEY_CACHE_AGE_THRESHOLD, + "This characterizes the number of hits a hot block has to be untouched until it is considered aged enough to be downgraded to a warm block. This specifies the percentage ratio of that number of hits to the total number of blocks in key cache", + (uchar**) &dflt_key_cache_var.param_age_threshold, + (uchar**) 0, + 0, (GET_ULONG | GET_ASK_ADDR), REQUIRED_ARG, + 300, 100, ULONG_MAX, 0, 100, 0}, + {"key_cache_block_size", OPT_KEY_CACHE_BLOCK_SIZE, + "The default size of key cache blocks", + (uchar**) &dflt_key_cache_var.param_block_size, + (uchar**) 0, + 0, (GET_ULONG | GET_ASK_ADDR), REQUIRED_ARG, + KEY_CACHE_BLOCK_SIZE, 512, 1024 * 16, 0, 512, 0}, + {"key_cache_division_limit", OPT_KEY_CACHE_DIVISION_LIMIT, + "The minimum percentage of warm blocks in key cache", + (uchar**) &dflt_key_cache_var.param_division_limit, + (uchar**) 0, + 0, (GET_ULONG | GET_ASK_ADDR) , REQUIRED_ARG, 100, + 1, 100, 0, 1, 0}, + {"long_query_time", OPT_LONG_QUERY_TIME, + "Log all queries that have taken more than long_query_time seconds to execute to file. " + "The argument will be treated as a decimal value with microsecond precission.", + (uchar**) &long_query_time, (uchar**) &long_query_time, 0, GET_DOUBLE, + REQUIRED_ARG, 10, 0, LONG_TIMEOUT, 0, 0, 0}, + {"lower_case_table_names", OPT_LOWER_CASE_TABLE_NAMES, + "If set to 1 table names are stored in lowercase on disk and table names will be case-insensitive. Should be set to 2 if you are using a case insensitive file system", + (uchar**) &lower_case_table_names, + (uchar**) &lower_case_table_names, 0, GET_UINT, OPT_ARG, +#ifdef FN_NO_CASE_SENCE + 1 +#else + 0 +#endif + , 0, 2, 0, 1, 0}, + {"max_allowed_packet", OPT_MAX_ALLOWED_PACKET, + "Max packetlength to send/receive from to server.", + (uchar**) &global_system_variables.max_allowed_packet, + (uchar**) &max_system_variables.max_allowed_packet, 0, GET_ULONG, + REQUIRED_ARG, 1024*1024L, 1024, 1024L*1024L*1024L, MALLOC_OVERHEAD, 1024, 0}, + {"max_binlog_cache_size", OPT_MAX_BINLOG_CACHE_SIZE, + "Can be used to restrict the total size used to cache a multi-transaction query.", + (uchar**) &max_binlog_cache_size, (uchar**) &max_binlog_cache_size, 0, + GET_ULL, REQUIRED_ARG, ULONG_MAX, IO_SIZE, ULONGLONG_MAX, 0, IO_SIZE, 0}, + {"max_binlog_size", OPT_MAX_BINLOG_SIZE, + "Binary log will be rotated automatically when the size exceeds this \ +value. Will also apply to relay logs if max_relay_log_size is 0. \ +The minimum value for this variable is 4096.", + (uchar**) &max_binlog_size, (uchar**) &max_binlog_size, 0, GET_ULONG, + REQUIRED_ARG, 1024*1024L*1024L, IO_SIZE, 1024*1024L*1024L, 0, IO_SIZE, 0}, + {"max_connect_errors", OPT_MAX_CONNECT_ERRORS, + "If there is more than this number of interrupted connections from a host this host will be blocked from further connections.", + (uchar**) &max_connect_errors, (uchar**) &max_connect_errors, 0, GET_ULONG, + REQUIRED_ARG, MAX_CONNECT_ERRORS, 1, ULONG_MAX, 0, 1, 0}, + // Default max_connections of 151 is larger than Apache's default max + // children, to avoid "too many connections" error in a common setup + {"max_connections", OPT_MAX_CONNECTIONS, + "The number of simultaneous clients allowed.", (uchar**) &max_connections, + (uchar**) &max_connections, 0, GET_ULONG, REQUIRED_ARG, 151, 1, 100000, 0, 1, + 0}, + {"max_delayed_threads", OPT_MAX_DELAYED_THREADS, + "Don't start more than this number of threads to handle INSERT DELAYED statements. If set to zero, which means INSERT DELAYED is not used.", + (uchar**) &global_system_variables.max_insert_delayed_threads, + (uchar**) &max_system_variables.max_insert_delayed_threads, + 0, GET_ULONG, REQUIRED_ARG, 20, 0, 16384, 0, 1, 0}, + {"max_error_count", OPT_MAX_ERROR_COUNT, + "Max number of errors/warnings to store for a statement.", + (uchar**) &global_system_variables.max_error_count, + (uchar**) &max_system_variables.max_error_count, + 0, GET_ULONG, REQUIRED_ARG, DEFAULT_ERROR_COUNT, 0, 65535, 0, 1, 0}, + {"max_heap_table_size", OPT_MAX_HEP_TABLE_SIZE, + "Don't allow creation of heap tables bigger than this.", + (uchar**) &global_system_variables.max_heap_table_size, + (uchar**) &max_system_variables.max_heap_table_size, 0, GET_ULL, + REQUIRED_ARG, 16*1024*1024L, 16384, MAX_MEM_TABLE_SIZE, + MALLOC_OVERHEAD, 1024, 0}, + {"max_join_size", OPT_MAX_JOIN_SIZE, + "Joins that are probably going to read more than max_join_size records return an error.", + (uchar**) &global_system_variables.max_join_size, + (uchar**) &max_system_variables.max_join_size, 0, GET_HA_ROWS, REQUIRED_ARG, + HA_POS_ERROR, 1, HA_POS_ERROR, 0, 1, 0}, + {"max_length_for_sort_data", OPT_MAX_LENGTH_FOR_SORT_DATA, + "Max number of bytes in sorted records.", + (uchar**) &global_system_variables.max_length_for_sort_data, + (uchar**) &max_system_variables.max_length_for_sort_data, 0, GET_ULONG, + REQUIRED_ARG, 1024, 4, 8192*1024L, 0, 1, 0}, + {"max_prepared_stmt_count", OPT_MAX_PREPARED_STMT_COUNT, + "Maximum number of prepared statements in the server.", + (uchar**) &max_prepared_stmt_count, (uchar**) &max_prepared_stmt_count, + 0, GET_ULONG, REQUIRED_ARG, 16382, 0, 1*1024*1024, 0, 1, 0}, + {"max_relay_log_size", OPT_MAX_RELAY_LOG_SIZE, + "If non-zero: relay log will be rotated automatically when the size exceeds this value; if zero (the default): when the size exceeds max_binlog_size. 0 excepted, the minimum value for this variable is 4096.", + (uchar**) &max_relay_log_size, (uchar**) &max_relay_log_size, 0, GET_ULONG, + REQUIRED_ARG, 0L, 0L, 1024*1024L*1024L, 0, IO_SIZE, 0}, + { "max_seeks_for_key", OPT_MAX_SEEKS_FOR_KEY, + "Limit assumed max number of seeks when looking up rows based on a key", + (uchar**) &global_system_variables.max_seeks_for_key, + (uchar**) &max_system_variables.max_seeks_for_key, 0, GET_ULONG, + REQUIRED_ARG, ULONG_MAX, 1, ULONG_MAX, 0, 1, 0 }, + {"max_sort_length", OPT_MAX_SORT_LENGTH, + "The number of bytes to use when sorting BLOB or TEXT values (only the first max_sort_length bytes of each value are used; the rest are ignored).", + (uchar**) &global_system_variables.max_sort_length, + (uchar**) &max_system_variables.max_sort_length, 0, GET_ULONG, + REQUIRED_ARG, 1024, 4, 8192*1024L, 0, 1, 0}, + {"max_sp_recursion_depth", OPT_MAX_SP_RECURSION_DEPTH, + "Maximum stored procedure recursion depth. (discussed with docs).", + (uchar**) &global_system_variables.max_sp_recursion_depth, + (uchar**) &max_system_variables.max_sp_recursion_depth, 0, GET_ULONG, + OPT_ARG, 0, 0, 255, 0, 1, 0 }, + {"max_tmp_tables", OPT_MAX_TMP_TABLES, + "Maximum number of temporary tables a client can keep open at a time.", + (uchar**) &global_system_variables.max_tmp_tables, + (uchar**) &max_system_variables.max_tmp_tables, 0, GET_ULONG, + REQUIRED_ARG, 32, 1, ULONG_MAX, 0, 1, 0}, + {"max_user_connections", OPT_MAX_USER_CONNECTIONS, + "The maximum number of active connections for a single user (0 = no limit).", + (uchar**) &max_user_connections, (uchar**) &max_user_connections, 0, GET_UINT, + REQUIRED_ARG, 0, 0, UINT_MAX, 0, 1, 0}, + {"max_write_lock_count", OPT_MAX_WRITE_LOCK_COUNT, + "After this many write locks, allow some read locks to run in between.", + (uchar**) &max_write_lock_count, (uchar**) &max_write_lock_count, 0, GET_ULONG, + REQUIRED_ARG, ULONG_MAX, 1, ULONG_MAX, 0, 1, 0}, + {"min_examined_row_limit", OPT_MIN_EXAMINED_ROW_LIMIT, + "Don't log queries which examine less than min_examined_row_limit rows to file.", + (uchar**) &global_system_variables.min_examined_row_limit, + (uchar**) &max_system_variables.min_examined_row_limit, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, ULONG_MAX, 0, 1L, 0}, + {"multi_range_count", OPT_MULTI_RANGE_COUNT, + "Number of key ranges to request at once.", + (uchar**) &global_system_variables.multi_range_count, + (uchar**) &max_system_variables.multi_range_count, 0, + GET_ULONG, REQUIRED_ARG, 256, 1, ULONG_MAX, 0, 1, 0}, + {"myisam_block_size", OPT_MYISAM_BLOCK_SIZE, + "Block size to be used for MyISAM index pages.", + (uchar**) &opt_myisam_block_size, + (uchar**) &opt_myisam_block_size, 0, GET_ULONG, REQUIRED_ARG, + MI_KEY_BLOCK_LENGTH, MI_MIN_KEY_BLOCK_LENGTH, MI_MAX_KEY_BLOCK_LENGTH, + 0, MI_MIN_KEY_BLOCK_LENGTH, 0}, + {"myisam_data_pointer_size", OPT_MYISAM_DATA_POINTER_SIZE, + "Default pointer size to be used for MyISAM tables.", + (uchar**) &myisam_data_pointer_size, + (uchar**) &myisam_data_pointer_size, 0, GET_ULONG, REQUIRED_ARG, + 6, 2, 7, 0, 1, 0}, + {"myisam_max_extra_sort_file_size", OPT_MYISAM_MAX_EXTRA_SORT_FILE_SIZE, + "Deprecated option", + (uchar**) &global_system_variables.myisam_max_extra_sort_file_size, + (uchar**) &max_system_variables.myisam_max_extra_sort_file_size, + 0, GET_ULL, REQUIRED_ARG, (ulonglong) MI_MAX_TEMP_LENGTH, + 0, (ulonglong) MAX_FILE_SIZE, 0, 1, 0}, + {"myisam_max_sort_file_size", OPT_MYISAM_MAX_SORT_FILE_SIZE, + "Don't use the fast sort index method to created index if the temporary file would get bigger than this.", + (uchar**) &global_system_variables.myisam_max_sort_file_size, + (uchar**) &max_system_variables.myisam_max_sort_file_size, 0, + GET_ULL, REQUIRED_ARG, (longlong) LONG_MAX, 0, (ulonglong) MAX_FILE_SIZE, + 0, 1024*1024, 0}, + {"myisam_repair_threads", OPT_MYISAM_REPAIR_THREADS, + "Number of threads to use when repairing MyISAM tables. The value of 1 disables parallel repair.", + (uchar**) &global_system_variables.myisam_repair_threads, + (uchar**) &max_system_variables.myisam_repair_threads, 0, + GET_ULONG, REQUIRED_ARG, 1, 1, ULONG_MAX, 0, 1, 0}, + {"myisam_sort_buffer_size", OPT_MYISAM_SORT_BUFFER_SIZE, + "The buffer that is allocated when sorting the index when doing a REPAIR or when creating indexes with CREATE INDEX or ALTER TABLE.", + (uchar**) &global_system_variables.myisam_sort_buff_size, + (uchar**) &max_system_variables.myisam_sort_buff_size, 0, + GET_ULONG, REQUIRED_ARG, 8192*1024, 4, ~0L, 0, 1, 0}, + {"myisam_use_mmap", OPT_MYISAM_USE_MMAP, + "Use memory mapping for reading and writing MyISAM tables", + (uchar**) &opt_myisam_use_mmap, + (uchar**) &opt_myisam_use_mmap, 0, GET_BOOL, NO_ARG, 0, + 0, 0, 0, 0, 0}, + {"myisam_stats_method", OPT_MYISAM_STATS_METHOD, + "Specifies how MyISAM index statistics collection code should threat NULLs. " + "Possible values of name are \"nulls_unequal\" (default behavior for 4.1/5.0), " + "\"nulls_equal\" (emulate 4.0 behavior), and \"nulls_ignored\".", + (uchar**) &myisam_stats_method_str, (uchar**) &myisam_stats_method_str, 0, + GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"net_buffer_length", OPT_NET_BUFFER_LENGTH, + "Buffer length for TCP/IP and socket communication.", + (uchar**) &global_system_variables.net_buffer_length, + (uchar**) &max_system_variables.net_buffer_length, 0, GET_ULONG, + REQUIRED_ARG, 16384, 1024, 1024*1024L, 0, 1024, 0}, + {"net_read_timeout", OPT_NET_READ_TIMEOUT, + "Number of seconds to wait for more data from a connection before aborting the read.", + (uchar**) &global_system_variables.net_read_timeout, + (uchar**) &max_system_variables.net_read_timeout, 0, GET_ULONG, + REQUIRED_ARG, NET_READ_TIMEOUT, 1, LONG_TIMEOUT, 0, 1, 0}, + {"net_retry_count", OPT_NET_RETRY_COUNT, + "If a read on a communication port is interrupted, retry this many times before giving up.", + (uchar**) &global_system_variables.net_retry_count, + (uchar**) &max_system_variables.net_retry_count,0, + GET_ULONG, REQUIRED_ARG, MYSQLD_NET_RETRY_COUNT, 1, ULONG_MAX, 0, 1, 0}, + {"net_write_timeout", OPT_NET_WRITE_TIMEOUT, + "Number of seconds to wait for a block to be written to a connection before aborting the write.", + (uchar**) &global_system_variables.net_write_timeout, + (uchar**) &max_system_variables.net_write_timeout, 0, GET_ULONG, + REQUIRED_ARG, NET_WRITE_TIMEOUT, 1, LONG_TIMEOUT, 0, 1, 0}, + { "old", OPT_OLD_MODE, "Use compatible behavior.", + (uchar**) &global_system_variables.old_mode, + (uchar**) &max_system_variables.old_mode, 0, GET_BOOL, NO_ARG, + 0, 0, 0, 0, 0, 0}, + {"open_files_limit", OPT_OPEN_FILES_LIMIT, + "If this is not 0, then mysqld will use this value to reserve file descriptors to use with setrlimit(). If this value is 0 then mysqld will reserve max_connections*5 or max_connections + table_cache*2 (whichever is larger) number of files.", + (uchar**) &open_files_limit, (uchar**) &open_files_limit, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, OS_FILE_LIMIT, 0, 1, 0}, + {"optimizer_prune_level", OPT_OPTIMIZER_PRUNE_LEVEL, + "Controls the heuristic(s) applied during query optimization to prune less-promising partial plans from the optimizer search space. Meaning: 0 - do not apply any heuristic, thus perform exhaustive search; 1 - prune plans based on number of retrieved rows.", + (uchar**) &global_system_variables.optimizer_prune_level, + (uchar**) &max_system_variables.optimizer_prune_level, + 0, GET_ULONG, OPT_ARG, 1, 0, 1, 0, 1, 0}, + {"optimizer_search_depth", OPT_OPTIMIZER_SEARCH_DEPTH, + "Maximum depth of search performed by the query optimizer. Values larger than the number of relations in a query result in better query plans, but take longer to compile a query. Smaller values than the number of tables in a relation result in faster optimization, but may produce very bad query plans. If set to 0, the system will automatically pick a reasonable value; if set to MAX_TABLES+2, the optimizer will switch to the original find_best (used for testing/comparison).", + (uchar**) &global_system_variables.optimizer_search_depth, + (uchar**) &max_system_variables.optimizer_search_depth, + 0, GET_ULONG, OPT_ARG, MAX_TABLES+1, 0, MAX_TABLES+2, 0, 1, 0}, + {"optimizer_switch", OPT_OPTIMIZER_SWITCH, + "optimizer_switch=option=val[,option=val...], where option={index_merge, " + "index_merge_union, index_merge_sort_union, index_merge_intersection} and " + "val={on, off, default}.", + (uchar**) &optimizer_switch_str, (uchar**) &optimizer_switch_str, 0, GET_STR, REQUIRED_ARG, + /*OPTIMIZER_SWITCH_DEFAULT*/0, + 0, 0, 0, 0, 0}, + {"plugin_dir", OPT_PLUGIN_DIR, + "Directory for plugins.", + (uchar**) &opt_plugin_dir_ptr, (uchar**) &opt_plugin_dir_ptr, 0, + GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"plugin-load", OPT_PLUGIN_LOAD, + "Optional semicolon-separated list of plugins to load, where each plugin is " + "identified as name=library, where name is the plugin name and library " + "is the plugin library in plugin_dir.", + (uchar**) &opt_plugin_load, (uchar**) &opt_plugin_load, 0, + GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"preload_buffer_size", OPT_PRELOAD_BUFFER_SIZE, + "The size of the buffer that is allocated when preloading indexes", + (uchar**) &global_system_variables.preload_buff_size, + (uchar**) &max_system_variables.preload_buff_size, 0, GET_ULONG, + REQUIRED_ARG, 32*1024L, 1024, 1024*1024*1024L, 0, 1, 0}, + {"query_alloc_block_size", OPT_QUERY_ALLOC_BLOCK_SIZE, + "Allocation block size for query parsing and execution", + (uchar**) &global_system_variables.query_alloc_block_size, + (uchar**) &max_system_variables.query_alloc_block_size, 0, GET_ULONG, + REQUIRED_ARG, QUERY_ALLOC_BLOCK_SIZE, 1024, ULONG_MAX, 0, 1024, 0}, +#ifdef HAVE_QUERY_CACHE + {"query_cache_limit", OPT_QUERY_CACHE_LIMIT, + "Don't cache results that are bigger than this.", + (uchar**) &query_cache_limit, (uchar**) &query_cache_limit, 0, GET_ULONG, + REQUIRED_ARG, 1024*1024L, 0, ULONG_MAX, 0, 1, 0}, + {"query_cache_min_res_unit", OPT_QUERY_CACHE_MIN_RES_UNIT, + "minimal size of unit in wich space for results is allocated (last unit will be trimed after writing all result data.", + (uchar**) &query_cache_min_res_unit, (uchar**) &query_cache_min_res_unit, + 0, GET_ULONG, REQUIRED_ARG, QUERY_CACHE_MIN_RESULT_DATA_SIZE, + 0, ULONG_MAX, 0, 1, 0}, +#endif /*HAVE_QUERY_CACHE*/ + {"query_cache_size", OPT_QUERY_CACHE_SIZE, + "The memory allocated to store results from old queries.", + (uchar**) &query_cache_size, (uchar**) &query_cache_size, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, (longlong) ULONG_MAX, 0, 1024, 0}, +#ifdef HAVE_QUERY_CACHE + {"query_cache_type", OPT_QUERY_CACHE_TYPE, + "0 = OFF = Don't cache or retrieve results. 1 = ON = Cache all results except SELECT SQL_NO_CACHE ... queries. 2 = DEMAND = Cache only SELECT SQL_CACHE ... queries.", + (uchar**) &global_system_variables.query_cache_type, + (uchar**) &max_system_variables.query_cache_type, + 0, GET_ULONG, REQUIRED_ARG, 1, 0, 2, 0, 1, 0}, + {"query_cache_wlock_invalidate", OPT_QUERY_CACHE_WLOCK_INVALIDATE, + "Invalidate queries in query cache on LOCK for write", + (uchar**) &global_system_variables.query_cache_wlock_invalidate, + (uchar**) &max_system_variables.query_cache_wlock_invalidate, + 0, GET_BOOL, NO_ARG, 0, 0, 1, 0, 1, 0}, +#endif /*HAVE_QUERY_CACHE*/ + {"query_prealloc_size", OPT_QUERY_PREALLOC_SIZE, + "Persistent buffer for query parsing and execution", + (uchar**) &global_system_variables.query_prealloc_size, + (uchar**) &max_system_variables.query_prealloc_size, 0, GET_ULONG, + REQUIRED_ARG, QUERY_ALLOC_PREALLOC_SIZE, QUERY_ALLOC_PREALLOC_SIZE, + ULONG_MAX, 0, 1024, 0}, + {"range_alloc_block_size", OPT_RANGE_ALLOC_BLOCK_SIZE, + "Allocation block size for storing ranges during optimization", + (uchar**) &global_system_variables.range_alloc_block_size, + (uchar**) &max_system_variables.range_alloc_block_size, 0, GET_ULONG, + REQUIRED_ARG, RANGE_ALLOC_BLOCK_SIZE, RANGE_ALLOC_BLOCK_SIZE, ULONG_MAX, + 0, 1024, 0}, + {"read_buffer_size", OPT_RECORD_BUFFER, + "Each thread that does a sequential scan allocates a buffer of this size for each table it scans. If you do many sequential scans, you may want to increase this value.", + (uchar**) &global_system_variables.read_buff_size, + (uchar**) &max_system_variables.read_buff_size,0, GET_ULONG, REQUIRED_ARG, + 128*1024L, IO_SIZE*2+MALLOC_OVERHEAD, INT_MAX32, MALLOC_OVERHEAD, IO_SIZE, + 0}, + {"read_only", OPT_READONLY, + "Make all non-temporary tables read-only, with the exception for replication (slave) threads and users with the SUPER privilege", + (uchar**) &opt_readonly, + (uchar**) &opt_readonly, + 0, GET_BOOL, NO_ARG, 0, 0, 1, 0, 1, 0}, + {"read_rnd_buffer_size", OPT_RECORD_RND_BUFFER, + "When reading rows in sorted order after a sort, the rows are read through this buffer to avoid a disk seeks. If not set, then it's set to the value of record_buffer.", + (uchar**) &global_system_variables.read_rnd_buff_size, + (uchar**) &max_system_variables.read_rnd_buff_size, 0, + GET_ULONG, REQUIRED_ARG, 256*1024L, IO_SIZE*2+MALLOC_OVERHEAD, + INT_MAX32, MALLOC_OVERHEAD, IO_SIZE, 0}, + +/* InfiniDB */ + {"infinidb_vtable_mode", OPT_INFINIDB_VTABLE_MODE, + "The default mode in which to start InfiniDB.", + (uchar**) &global_system_variables.infinidb_vtable_mode, + (uchar**) &max_system_variables.infinidb_vtable_mode, 0, + GET_ULONG, REQUIRED_ARG, + 1, /* Default value */ + 0, /* Min allowed value */ + 2, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 1, /* Value should be a mult. of this */ + 0}, + + {"infinidb_decimal_scale", OPT_INFINIDB_DECIMAL_SCALE, + "The default decimal precision for calculated column suboperations in InfiniDB.", + (uchar**) &global_system_variables.infinidb_decimal_scale, + (uchar**) &max_system_variables.infinidb_decimal_scale, 0, + GET_ULONG, REQUIRED_ARG, + 8, /* Default value */ + 0, /* Min allowed value */ + 18, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 1, /* Value should be a mult. of this */ + 0}, + + // InfiniDB boolean variable + {"infinidb_use_decimal_scale", OPT_INFINIDB_USE_DECIMAL_SCALE, + "Enable/disable the InfiniDB decimal scale to be used internally", + (uchar**)&global_system_variables.infinidb_use_decimal_scale, + (uchar**)&max_system_variables.infinidb_use_decimal_scale, + 0, GET_BOOL, NO_ARG, + 0, /* Default value */ + 0, /* Min allowed value */ + 1, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 1, /* Value should be a mult. of this */ + 0}, + + // InfiniDB boolean variable - use first table in from clause as large side table in joins + {"infinidb_ordered_only", OPT_INFINIDB_ORDERED_ONLY, + "Always use the first table in the from clause as the large side table for joins", + NULL, NULL, 0, GET_STR, OPT_ARG, + 0, /* Default value */ + 0, /* Min allowed value */ + 0, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 0, /* Value should be a mult. of this */ + 0}, + + {"infinidb_string_scan_threshold", OPT_INFINIDB_STRING_SCAN_THRESHOLD, + "Max number of blocks in a dictionary file to be scanned for filtering", + (uchar**) &global_system_variables.infinidb_string_scan_threshold, + (uchar**) &max_system_variables.infinidb_string_scan_threshold, 0, + GET_ULONG, REQUIRED_ARG, + 10, /* Default value */ + 0, /* Min allowed value */ + ULONG_MAX, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 0, /* Value should be a mult. of this */ + 0}, + + {"infinidb_compression_type", OPT_INFINIDB_COMPRESSION_TYPE, + "The column compression algorithm to use for InfiniDB tables.", + (uchar**) &global_system_variables.infinidb_compression_type, + (uchar**) &max_system_variables.infinidb_compression_type, 0, + GET_ULONG, REQUIRED_ARG, + 0, /* Default value */ + 0, /* Min allowed value */ + ULONG_MAX, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 1, /* Value should be a mult. of this */ + 0}, + + // InfiniDB boolean variable + {"infinidb_varbin_always_hex", OPT_INFINIDB_VARBIN_ALWAYS_HEX, + "Always display/process varbinary columns as if they have been hexified.", + (uchar**)&global_system_variables.infinidb_varbin_always_hex, + (uchar**)&max_system_variables.infinidb_varbin_always_hex, + 0, GET_BOOL, NO_ARG, + 0, /* Default value */ + 0, /* Min allowed value */ + 1, /* Max allowed value */ + 0, /* Subtract this overhead from given value before setting var */ + 1, /* Value should be a mult. of this */ + 0}, + +/* InfiniDB */ + + {"record_buffer", OPT_RECORD_BUFFER, + "Alias for read_buffer_size", + (uchar**) &global_system_variables.read_buff_size, + (uchar**) &max_system_variables.read_buff_size,0, GET_ULONG, REQUIRED_ARG, + 128*1024L, IO_SIZE*2+MALLOC_OVERHEAD, INT_MAX32, MALLOC_OVERHEAD, IO_SIZE, 0}, +#ifdef HAVE_REPLICATION + {"relay_log_purge", OPT_RELAY_LOG_PURGE, + "0 = do not purge relay logs. 1 = purge them as soon as they are no more needed.", + (uchar**) &relay_log_purge, + (uchar**) &relay_log_purge, 0, GET_BOOL, NO_ARG, + 1, 0, 1, 0, 1, 0}, + {"relay_log_space_limit", OPT_RELAY_LOG_SPACE_LIMIT, + "Maximum space to use for all relay logs.", + (uchar**) &relay_log_space_limit, + (uchar**) &relay_log_space_limit, 0, GET_ULL, REQUIRED_ARG, 0L, 0L, + (longlong) ULONG_MAX, 0, 1, 0}, + {"slave_compressed_protocol", OPT_SLAVE_COMPRESSED_PROTOCOL, + "Use compression on master/slave protocol.", + (uchar**) &opt_slave_compressed_protocol, + (uchar**) &opt_slave_compressed_protocol, + 0, GET_BOOL, NO_ARG, 0, 0, 1, 0, 1, 0}, + {"slave_net_timeout", OPT_SLAVE_NET_TIMEOUT, + "Number of seconds to wait for more data from a master/slave connection before aborting the read.", + (uchar**) &slave_net_timeout, (uchar**) &slave_net_timeout, 0, + GET_ULONG, REQUIRED_ARG, SLAVE_NET_TIMEOUT, 1, LONG_TIMEOUT, 0, 1, 0}, + {"slave_transaction_retries", OPT_SLAVE_TRANS_RETRIES, + "Number of times the slave SQL thread will retry a transaction in case " + "it failed with a deadlock or elapsed lock wait timeout, " + "before giving up and stopping.", + (uchar**) &slave_trans_retries, (uchar**) &slave_trans_retries, 0, + GET_ULONG, REQUIRED_ARG, 10L, 0L, (longlong) ULONG_MAX, 0, 1, 0}, +#endif /* HAVE_REPLICATION */ + {"slow_launch_time", OPT_SLOW_LAUNCH_TIME, + "If creating the thread takes longer than this value (in seconds), the Slow_launch_threads counter will be incremented.", + (uchar**) &slow_launch_time, (uchar**) &slow_launch_time, 0, GET_ULONG, + REQUIRED_ARG, 2L, 0L, LONG_TIMEOUT, 0, 1, 0}, + {"sort_buffer_size", OPT_SORT_BUFFER, + "Each thread that needs to do a sort allocates a buffer of this size.", + (uchar**) &global_system_variables.sortbuff_size, + (uchar**) &max_system_variables.sortbuff_size, 0, GET_ULONG, REQUIRED_ARG, + MAX_SORT_MEMORY, MIN_SORT_MEMORY+MALLOC_OVERHEAD*2, ~0L, MALLOC_OVERHEAD, + 1, 0}, + {"sync-binlog", OPT_SYNC_BINLOG, + "Synchronously flush binary log to disk after every #th event. " + "Use 0 (default) to disable synchronous flushing.", + (uchar**) &sync_binlog_period, (uchar**) &sync_binlog_period, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, ULONG_MAX, 0, 1, 0}, + {"sync-frm", OPT_SYNC_FRM, "Sync .frm to disk on create. Enabled by default.", + (uchar**) &opt_sync_frm, (uchar**) &opt_sync_frm, 0, GET_BOOL, NO_ARG, 1, 0, + 0, 0, 0, 0}, + {"table_cache", OPT_TABLE_OPEN_CACHE, + "Deprecated; use --table_open_cache instead.", + (uchar**) &table_cache_size, (uchar**) &table_cache_size, 0, GET_ULONG, + REQUIRED_ARG, TABLE_OPEN_CACHE_DEFAULT, 1, 512*1024L, 0, 1, 0}, + {"table_definition_cache", OPT_TABLE_DEF_CACHE, + "The number of cached table definitions.", + (uchar**) &table_def_size, (uchar**) &table_def_size, + 0, GET_ULONG, REQUIRED_ARG, TABLE_DEF_CACHE_DEFAULT, TABLE_DEF_CACHE_MIN, + 512*1024L, 0, 1, 0}, + {"table_open_cache", OPT_TABLE_OPEN_CACHE, + "The number of cached open tables.", + (uchar**) &table_cache_size, (uchar**) &table_cache_size, 0, GET_ULONG, + REQUIRED_ARG, TABLE_OPEN_CACHE_DEFAULT, 1, 512*1024L, 0, 1, 0}, + {"table_lock_wait_timeout", OPT_TABLE_LOCK_WAIT_TIMEOUT, + "Timeout in seconds to wait for a table level lock before returning an " + "error. Used only if the connection has active cursors.", + (uchar**) &table_lock_wait_timeout, (uchar**) &table_lock_wait_timeout, + 0, GET_ULONG, REQUIRED_ARG, 50, 1, 1024 * 1024 * 1024, 0, 1, 0}, + {"thread_cache_size", OPT_THREAD_CACHE_SIZE, + "How many threads we should keep in a cache for reuse.", + (uchar**) &thread_cache_size, (uchar**) &thread_cache_size, 0, GET_ULONG, + REQUIRED_ARG, 0, 0, 16384, 0, 1, 0}, + {"thread_concurrency", OPT_THREAD_CONCURRENCY, + "Permits the application to give the threads system a hint for the desired number of threads that should be run at the same time.", + (uchar**) &concurrency, (uchar**) &concurrency, 0, GET_ULONG, REQUIRED_ARG, + DEFAULT_CONCURRENCY, 1, 512, 0, 1, 0}, +#if HAVE_POOL_OF_THREADS == 1 + {"thread_pool_size", OPT_THREAD_CACHE_SIZE, + "How many threads we should create to handle query requests in case of 'thread_handling=pool-of-threads'", + (uchar**) &thread_pool_size, (uchar**) &thread_pool_size, 0, GET_ULONG, + REQUIRED_ARG, 20, 1, 16384, 0, 1, 0}, +#endif + {"thread_stack", OPT_THREAD_STACK, + "The stack size for each thread.", (uchar**) &my_thread_stack_size, + (uchar**) &my_thread_stack_size, 0, GET_ULONG, REQUIRED_ARG,DEFAULT_THREAD_STACK, + 1024L*128L, ULONG_MAX, 0, 1024, 0}, + { "time_format", OPT_TIME_FORMAT, + "The TIME format (for future).", + (uchar**) &opt_date_time_formats[MYSQL_TIMESTAMP_TIME], + (uchar**) &opt_date_time_formats[MYSQL_TIMESTAMP_TIME], + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"tmp_table_size", OPT_TMP_TABLE_SIZE, + "If an internal in-memory temporary table exceeds this size, MySQL will" + " automatically convert it to an on-disk MyISAM table.", + (uchar**) &global_system_variables.tmp_table_size, + (uchar**) &max_system_variables.tmp_table_size, 0, GET_ULL, + REQUIRED_ARG, 16*1024*1024L, 1024, MAX_MEM_TABLE_SIZE, 0, 1, 0}, + {"transaction_alloc_block_size", OPT_TRANS_ALLOC_BLOCK_SIZE, + "Allocation block size for transactions to be stored in binary log", + (uchar**) &global_system_variables.trans_alloc_block_size, + (uchar**) &max_system_variables.trans_alloc_block_size, 0, GET_ULONG, + REQUIRED_ARG, QUERY_ALLOC_BLOCK_SIZE, 1024, ULONG_MAX, 0, 1024, 0}, + {"transaction_prealloc_size", OPT_TRANS_PREALLOC_SIZE, + "Persistent buffer for transactions to be stored in binary log", + (uchar**) &global_system_variables.trans_prealloc_size, + (uchar**) &max_system_variables.trans_prealloc_size, 0, GET_ULONG, + REQUIRED_ARG, TRANS_ALLOC_PREALLOC_SIZE, 1024, ULONG_MAX, 0, 1024, 0}, + {"thread_handling", OPT_THREAD_HANDLING, + "Define threads usage for handling queries: " + "one-thread-per-connection or no-threads", 0, 0, + 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"updatable_views_with_limit", OPT_UPDATABLE_VIEWS_WITH_LIMIT, + "1 = YES = Don't issue an error message (warning only) if a VIEW without presence of a key of the underlying table is used in queries with a LIMIT clause for updating. 0 = NO = Prohibit update of a VIEW, which does not contain a key of the underlying table and the query uses a LIMIT clause (usually get from GUI tools).", + (uchar**) &global_system_variables.updatable_views_with_limit, + (uchar**) &max_system_variables.updatable_views_with_limit, + 0, GET_ULONG, REQUIRED_ARG, 1, 0, 1, 0, 1, 0}, + {"wait_timeout", OPT_WAIT_TIMEOUT, + "The number of seconds the server waits for activity on a connection before closing it.", + (uchar**) &global_system_variables.net_wait_timeout, + (uchar**) &max_system_variables.net_wait_timeout, 0, GET_ULONG, + REQUIRED_ARG, NET_WAIT_TIMEOUT, 1, IF_WIN(INT_MAX32/1000, LONG_TIMEOUT), + 0, 1, 0}, + {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0} +}; + + +static int show_queries(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONGLONG; + var->value= (char *)&thd->query_id; + return 0; +} + + +static int show_net_compression(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_MY_BOOL; + var->value= (char *)&thd->net.compress; + return 0; +} + +static int show_starttime(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (long) (thd->query_start() - server_start_time); + return 0; +} + +#ifdef COMMUNITY_SERVER +static int show_flushstatustime(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (long) (thd->query_start() - flush_status_time); + return 0; +} +#endif + +#ifdef HAVE_REPLICATION +static int show_rpl_status(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_CHAR; + var->value= const_cast(rpl_status_type[(int)rpl_status]); + return 0; +} + +static int show_slave_running(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_MY_BOOL; + pthread_mutex_lock(&LOCK_active_mi); + var->value= buff; + *((my_bool *)buff)= (my_bool) (active_mi && active_mi->slave_running && + active_mi->rli.slave_running); + pthread_mutex_unlock(&LOCK_active_mi); + return 0; +} + +static int show_slave_retried_trans(THD *thd, SHOW_VAR *var, char *buff) +{ + /* + TODO: with multimaster, have one such counter per line in + SHOW SLAVE STATUS, and have the sum over all lines here. + */ + pthread_mutex_lock(&LOCK_active_mi); + if (active_mi) + { + var->type= SHOW_LONG; + var->value= buff; + pthread_mutex_lock(&active_mi->rli.data_lock); + *((long *)buff)= (long)active_mi->rli.retried_trans; + pthread_mutex_unlock(&active_mi->rli.data_lock); + } + else + var->type= SHOW_UNDEF; + pthread_mutex_unlock(&LOCK_active_mi); + return 0; +} +#endif /* HAVE_REPLICATION */ + +static int show_open_tables(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (long)cached_open_tables(); + return 0; +} + +static int show_prepared_stmt_count(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + pthread_mutex_lock(&LOCK_prepared_stmt_count); + *((long *)buff)= (long)prepared_stmt_count; + pthread_mutex_unlock(&LOCK_prepared_stmt_count); + return 0; +} + +static int show_table_definitions(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (long)cached_table_definitions(); + return 0; +} + +#ifdef HAVE_OPENSSL +/* Functions relying on CTX */ +static int show_ssl_ctx_sess_accept(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_accept(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_accept_good(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_accept_good(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_connect_good(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_connect_good(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_accept_renegotiate(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_accept_renegotiate(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_connect_renegotiate(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_connect_renegotiate(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_cb_hits(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_cb_hits(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_hits(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_hits(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_cache_full(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_cache_full(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_misses(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_misses(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_timeouts(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_timeouts(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_number(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_number(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_connect(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_connect(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_sess_get_cache_size(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_sess_get_cache_size(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_get_verify_mode(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_get_verify_mode(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_get_verify_depth(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + *((long *)buff)= (!ssl_acceptor_fd ? 0 : + SSL_CTX_get_verify_depth(ssl_acceptor_fd->ssl_context)); + return 0; +} + +static int show_ssl_ctx_get_session_cache_mode(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_CHAR; + if (!ssl_acceptor_fd) + var->value= const_cast("NONE"); + else + switch (SSL_CTX_get_session_cache_mode(ssl_acceptor_fd->ssl_context)) + { + case SSL_SESS_CACHE_OFF: + var->value= const_cast("OFF"); break; + case SSL_SESS_CACHE_CLIENT: + var->value= const_cast("CLIENT"); break; + case SSL_SESS_CACHE_SERVER: + var->value= const_cast("SERVER"); break; + case SSL_SESS_CACHE_BOTH: + var->value= const_cast("BOTH"); break; + case SSL_SESS_CACHE_NO_AUTO_CLEAR: + var->value= const_cast("NO_AUTO_CLEAR"); break; + case SSL_SESS_CACHE_NO_INTERNAL_LOOKUP: + var->value= const_cast("NO_INTERNAL_LOOKUP"); break; + default: + var->value= const_cast("Unknown"); break; + } + return 0; +} + +/* + Functions relying on SSL + Note: In the show_ssl_* functions, we need to check if we have a + valid vio-object since this isn't always true, specifically + when session_status or global_status is requested from + inside an Event. + */ +static int show_ssl_get_version(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_CHAR; + if( thd->vio_ok() && thd->net.vio->ssl_arg ) + var->value= const_cast(SSL_get_version((SSL*) thd->net.vio->ssl_arg)); + else + var->value= (char *)""; + return 0; +} + +static int show_ssl_session_reused(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + if( thd->vio_ok() && thd->net.vio->ssl_arg ) + *((long *)buff)= (long)SSL_session_reused((SSL*) thd->net.vio->ssl_arg); + else + *((long *)buff)= 0; + return 0; +} + +static int show_ssl_get_default_timeout(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + if( thd->vio_ok() && thd->net.vio->ssl_arg ) + *((long *)buff)= (long)SSL_get_default_timeout((SSL*)thd->net.vio->ssl_arg); + else + *((long *)buff)= 0; + return 0; +} + +static int show_ssl_get_verify_mode(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + if( thd->net.vio && thd->net.vio->ssl_arg ) + *((long *)buff)= (long)SSL_get_verify_mode((SSL*)thd->net.vio->ssl_arg); + else + *((long *)buff)= 0; + return 0; +} + +static int show_ssl_get_verify_depth(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_LONG; + var->value= buff; + if( thd->vio_ok() && thd->net.vio->ssl_arg ) + *((long *)buff)= (long)SSL_get_verify_depth((SSL*)thd->net.vio->ssl_arg); + else + *((long *)buff)= 0; + return 0; +} + +static int show_ssl_get_cipher(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_CHAR; + if( thd->vio_ok() && thd->net.vio->ssl_arg ) + var->value= const_cast(SSL_get_cipher((SSL*) thd->net.vio->ssl_arg)); + else + var->value= (char *)""; + return 0; +} + +static int show_ssl_get_cipher_list(THD *thd, SHOW_VAR *var, char *buff) +{ + var->type= SHOW_CHAR; + var->value= buff; + if (thd->vio_ok() && thd->net.vio->ssl_arg) + { + int i; + const char *p; + char *end= buff + SHOW_VAR_FUNC_BUFF_SIZE; + for (i=0; (p= SSL_get_cipher_list((SSL*) thd->net.vio->ssl_arg,i)) && + buff < end; i++) + { + buff= strnmov(buff, p, end-buff-1); + *buff++= ':'; + } + if (i) + buff--; + } + *buff=0; + return 0; +} + +#endif /* HAVE_OPENSSL */ + + +/* + Variables shown by SHOW STATUS in alphabetical order +*/ + +SHOW_VAR status_vars[]= { + {"Aborted_clients", (char*) &aborted_threads, SHOW_LONG}, + {"Aborted_connects", (char*) &aborted_connects, SHOW_LONG}, + {"Binlog_cache_disk_use", (char*) &binlog_cache_disk_use, SHOW_LONG}, + {"Binlog_cache_use", (char*) &binlog_cache_use, SHOW_LONG}, + {"Bytes_received", (char*) offsetof(STATUS_VAR, bytes_received), SHOW_LONGLONG_STATUS}, + {"Bytes_sent", (char*) offsetof(STATUS_VAR, bytes_sent), SHOW_LONGLONG_STATUS}, + {"Com", (char*) com_status_vars, SHOW_ARRAY}, + {"Compression", (char*) &show_net_compression, SHOW_FUNC}, + {"Connections", (char*) &thread_id, SHOW_LONG_NOFLUSH}, + {"Created_tmp_disk_tables", (char*) offsetof(STATUS_VAR, created_tmp_disk_tables), SHOW_LONG_STATUS}, + {"Created_tmp_files", (char*) &my_tmp_file_created, SHOW_LONG}, + {"Created_tmp_tables", (char*) offsetof(STATUS_VAR, created_tmp_tables), SHOW_LONG_STATUS}, + {"Delayed_errors", (char*) &delayed_insert_errors, SHOW_LONG}, + {"Delayed_insert_threads", (char*) &delayed_insert_threads, SHOW_LONG_NOFLUSH}, + {"Delayed_writes", (char*) &delayed_insert_writes, SHOW_LONG}, + {"Flush_commands", (char*) &refresh_version, SHOW_LONG_NOFLUSH}, + {"Handler_commit", (char*) offsetof(STATUS_VAR, ha_commit_count), SHOW_LONG_STATUS}, + {"Handler_delete", (char*) offsetof(STATUS_VAR, ha_delete_count), SHOW_LONG_STATUS}, + {"Handler_discover", (char*) offsetof(STATUS_VAR, ha_discover_count), SHOW_LONG_STATUS}, + {"Handler_prepare", (char*) offsetof(STATUS_VAR, ha_prepare_count), SHOW_LONG_STATUS}, + {"Handler_read_first", (char*) offsetof(STATUS_VAR, ha_read_first_count), SHOW_LONG_STATUS}, + {"Handler_read_key", (char*) offsetof(STATUS_VAR, ha_read_key_count), SHOW_LONG_STATUS}, + {"Handler_read_next", (char*) offsetof(STATUS_VAR, ha_read_next_count), SHOW_LONG_STATUS}, + {"Handler_read_prev", (char*) offsetof(STATUS_VAR, ha_read_prev_count), SHOW_LONG_STATUS}, + {"Handler_read_rnd", (char*) offsetof(STATUS_VAR, ha_read_rnd_count), SHOW_LONG_STATUS}, + {"Handler_read_rnd_next", (char*) offsetof(STATUS_VAR, ha_read_rnd_next_count), SHOW_LONG_STATUS}, + {"Handler_rollback", (char*) offsetof(STATUS_VAR, ha_rollback_count), SHOW_LONG_STATUS}, + {"Handler_savepoint", (char*) offsetof(STATUS_VAR, ha_savepoint_count), SHOW_LONG_STATUS}, + {"Handler_savepoint_rollback",(char*) offsetof(STATUS_VAR, ha_savepoint_rollback_count), SHOW_LONG_STATUS}, + {"Handler_update", (char*) offsetof(STATUS_VAR, ha_update_count), SHOW_LONG_STATUS}, + {"Handler_write", (char*) offsetof(STATUS_VAR, ha_write_count), SHOW_LONG_STATUS}, + {"Key_blocks_not_flushed", (char*) offsetof(KEY_CACHE, global_blocks_changed), SHOW_KEY_CACHE_LONG}, + {"Key_blocks_unused", (char*) offsetof(KEY_CACHE, blocks_unused), SHOW_KEY_CACHE_LONG}, + {"Key_blocks_used", (char*) offsetof(KEY_CACHE, blocks_used), SHOW_KEY_CACHE_LONG}, + {"Key_read_requests", (char*) offsetof(KEY_CACHE, global_cache_r_requests), SHOW_KEY_CACHE_LONGLONG}, + {"Key_reads", (char*) offsetof(KEY_CACHE, global_cache_read), SHOW_KEY_CACHE_LONGLONG}, + {"Key_write_requests", (char*) offsetof(KEY_CACHE, global_cache_w_requests), SHOW_KEY_CACHE_LONGLONG}, + {"Key_writes", (char*) offsetof(KEY_CACHE, global_cache_write), SHOW_KEY_CACHE_LONGLONG}, + {"Last_query_cost", (char*) offsetof(STATUS_VAR, last_query_cost), SHOW_DOUBLE_STATUS}, + {"Max_used_connections", (char*) &max_used_connections, SHOW_LONG}, + {"Not_flushed_delayed_rows", (char*) &delayed_rows_in_use, SHOW_LONG_NOFLUSH}, + {"Open_files", (char*) &my_file_opened, SHOW_LONG_NOFLUSH}, + {"Open_streams", (char*) &my_stream_opened, SHOW_LONG_NOFLUSH}, + {"Open_table_definitions", (char*) &show_table_definitions, SHOW_FUNC}, + {"Open_tables", (char*) &show_open_tables, SHOW_FUNC}, + {"Opened_files", (char*) &my_file_total_opened, SHOW_LONG_NOFLUSH}, + {"Opened_tables", (char*) offsetof(STATUS_VAR, opened_tables), SHOW_LONG_STATUS}, + {"Opened_table_definitions", (char*) offsetof(STATUS_VAR, opened_shares), SHOW_LONG_STATUS}, + {"Prepared_stmt_count", (char*) &show_prepared_stmt_count, SHOW_FUNC}, +#ifdef HAVE_QUERY_CACHE + {"Qcache_free_blocks", (char*) &query_cache.free_memory_blocks, SHOW_LONG_NOFLUSH}, + {"Qcache_free_memory", (char*) &query_cache.free_memory, SHOW_LONG_NOFLUSH}, + {"Qcache_hits", (char*) &query_cache.hits, SHOW_LONG}, + {"Qcache_inserts", (char*) &query_cache.inserts, SHOW_LONG}, + {"Qcache_lowmem_prunes", (char*) &query_cache.lowmem_prunes, SHOW_LONG}, + {"Qcache_not_cached", (char*) &query_cache.refused, SHOW_LONG}, + {"Qcache_queries_in_cache", (char*) &query_cache.queries_in_cache, SHOW_LONG_NOFLUSH}, + {"Qcache_total_blocks", (char*) &query_cache.total_blocks, SHOW_LONG_NOFLUSH}, +#endif /*HAVE_QUERY_CACHE*/ + {"Queries", (char*) &show_queries, SHOW_FUNC}, + {"Questions", (char*) offsetof(STATUS_VAR, questions), SHOW_LONG_STATUS}, +#ifdef HAVE_REPLICATION + {"Rpl_status", (char*) &show_rpl_status, SHOW_FUNC}, +#endif + {"Select_full_join", (char*) offsetof(STATUS_VAR, select_full_join_count), SHOW_LONG_STATUS}, + {"Select_full_range_join", (char*) offsetof(STATUS_VAR, select_full_range_join_count), SHOW_LONG_STATUS}, + {"Select_range", (char*) offsetof(STATUS_VAR, select_range_count), SHOW_LONG_STATUS}, + {"Select_range_check", (char*) offsetof(STATUS_VAR, select_range_check_count), SHOW_LONG_STATUS}, + {"Select_scan", (char*) offsetof(STATUS_VAR, select_scan_count), SHOW_LONG_STATUS}, + {"Slave_open_temp_tables", (char*) &slave_open_temp_tables, SHOW_LONG}, +#ifdef HAVE_REPLICATION + {"Slave_retried_transactions",(char*) &show_slave_retried_trans, SHOW_FUNC}, + {"Slave_running", (char*) &show_slave_running, SHOW_FUNC}, +#endif + {"Slow_launch_threads", (char*) &slow_launch_threads, SHOW_LONG}, + {"Slow_queries", (char*) offsetof(STATUS_VAR, long_query_count), SHOW_LONG_STATUS}, + {"Sort_merge_passes", (char*) offsetof(STATUS_VAR, filesort_merge_passes), SHOW_LONG_STATUS}, + {"Sort_range", (char*) offsetof(STATUS_VAR, filesort_range_count), SHOW_LONG_STATUS}, + {"Sort_rows", (char*) offsetof(STATUS_VAR, filesort_rows), SHOW_LONG_STATUS}, + {"Sort_scan", (char*) offsetof(STATUS_VAR, filesort_scan_count), SHOW_LONG_STATUS}, +#ifdef HAVE_OPENSSL + {"Ssl_accept_renegotiates", (char*) &show_ssl_ctx_sess_accept_renegotiate, SHOW_FUNC}, + {"Ssl_accepts", (char*) &show_ssl_ctx_sess_accept, SHOW_FUNC}, + {"Ssl_callback_cache_hits", (char*) &show_ssl_ctx_sess_cb_hits, SHOW_FUNC}, + {"Ssl_cipher", (char*) &show_ssl_get_cipher, SHOW_FUNC}, + {"Ssl_cipher_list", (char*) &show_ssl_get_cipher_list, SHOW_FUNC}, + {"Ssl_client_connects", (char*) &show_ssl_ctx_sess_connect, SHOW_FUNC}, + {"Ssl_connect_renegotiates", (char*) &show_ssl_ctx_sess_connect_renegotiate, SHOW_FUNC}, + {"Ssl_ctx_verify_depth", (char*) &show_ssl_ctx_get_verify_depth, SHOW_FUNC}, + {"Ssl_ctx_verify_mode", (char*) &show_ssl_ctx_get_verify_mode, SHOW_FUNC}, + {"Ssl_default_timeout", (char*) &show_ssl_get_default_timeout, SHOW_FUNC}, + {"Ssl_finished_accepts", (char*) &show_ssl_ctx_sess_accept_good, SHOW_FUNC}, + {"Ssl_finished_connects", (char*) &show_ssl_ctx_sess_connect_good, SHOW_FUNC}, + {"Ssl_session_cache_hits", (char*) &show_ssl_ctx_sess_hits, SHOW_FUNC}, + {"Ssl_session_cache_misses", (char*) &show_ssl_ctx_sess_misses, SHOW_FUNC}, + {"Ssl_session_cache_mode", (char*) &show_ssl_ctx_get_session_cache_mode, SHOW_FUNC}, + {"Ssl_session_cache_overflows", (char*) &show_ssl_ctx_sess_cache_full, SHOW_FUNC}, + {"Ssl_session_cache_size", (char*) &show_ssl_ctx_sess_get_cache_size, SHOW_FUNC}, + {"Ssl_session_cache_timeouts", (char*) &show_ssl_ctx_sess_timeouts, SHOW_FUNC}, + {"Ssl_sessions_reused", (char*) &show_ssl_session_reused, SHOW_FUNC}, + {"Ssl_used_session_cache_entries",(char*) &show_ssl_ctx_sess_number, SHOW_FUNC}, + {"Ssl_verify_depth", (char*) &show_ssl_get_verify_depth, SHOW_FUNC}, + {"Ssl_verify_mode", (char*) &show_ssl_get_verify_mode, SHOW_FUNC}, + {"Ssl_version", (char*) &show_ssl_get_version, SHOW_FUNC}, +#endif /* HAVE_OPENSSL */ + {"Table_locks_immediate", (char*) &locks_immediate, SHOW_LONG}, + {"Table_locks_waited", (char*) &locks_waited, SHOW_LONG}, +#ifdef HAVE_MMAP + {"Tc_log_max_pages_used", (char*) &tc_log_max_pages_used, SHOW_LONG}, + {"Tc_log_page_size", (char*) &tc_log_page_size, SHOW_LONG}, + {"Tc_log_page_waits", (char*) &tc_log_page_waits, SHOW_LONG}, +#endif + {"Threads_cached", (char*) &cached_thread_count, SHOW_LONG_NOFLUSH}, + {"Threads_connected", (char*) &thread_count, SHOW_INT}, + {"Threads_created", (char*) &thread_created, SHOW_LONG_NOFLUSH}, + {"Threads_running", (char*) &thread_running, SHOW_INT}, + {"Uptime", (char*) &show_starttime, SHOW_FUNC}, +#ifdef COMMUNITY_SERVER + {"Uptime_since_flush_status",(char*) &show_flushstatustime, SHOW_FUNC}, +#endif + {NullS, NullS, SHOW_LONG} +}; + +#ifndef EMBEDDED_LIBRARY +static void print_version(void) +{ + set_server_version(); + /* + Note: the instance manager keys off the string 'Ver' so it can find the + version from the output of 'mysqld --version', so don't change it! + */ + printf("%s Ver %s for %s on %s (%s)\n",my_progname, + server_version,SYSTEM_TYPE,MACHINE_TYPE, MYSQL_COMPILATION_COMMENT); +} + +static void usage(void) +{ + if (!(default_charset_info= get_charset_by_csname(default_character_set_name, + MY_CS_PRIMARY, + MYF(MY_WME)))) + exit(1); + if (!default_collation_name) + default_collation_name= (char*) default_charset_info->name; + print_version(); + puts("\ +Copyright (C) 2000-2008 MySQL AB, by Monty and others\n\ +Copyright (C) 2008 Sun Microsystems, Inc.\n\ +This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n\ +and you are welcome to modify and redistribute it under the GPL license\n\n\ +Starts the MySQL database server\n"); + + printf("Usage: %s [OPTIONS]\n", my_progname); + if (!opt_verbose) + puts("\nFor more help options (several pages), use mysqld --verbose --help"); + else + { +#ifdef __WIN__ + puts("NT and Win32 specific options:\n\ + --install Install the default service (NT)\n\ + --install-manual Install the default service started manually (NT)\n\ + --install service_name Install an optional service (NT)\n\ + --install-manual service_name Install an optional service started manually (NT)\n\ + --remove Remove the default service from the service list (NT)\n\ + --remove service_name Remove the service_name from the service list (NT)\n\ + --enable-named-pipe Only to be used for the default server (NT)\n\ + --standalone Dummy option to start as a standalone server (NT)\ +"); + puts(""); +#endif + print_defaults(MYSQL_CONFIG_NAME,load_default_groups); + puts(""); + set_ports(); + + /* Print out all the options including plugin supplied options */ + my_print_help_inc_plugins(my_long_options, sizeof(my_long_options)/sizeof(my_option)); + + if (! plugins_are_initialized) + { + puts("\n\ +Plugins have parameters that are not reflected in this list\n\ +because execution stopped before plugins were initialized."); + } + + puts("\n\ +To see what values a running MySQL server is using, type\n\ +'mysqladmin variables' instead of 'mysqld --verbose --help'."); + } +} +#endif /*!EMBEDDED_LIBRARY*/ + + +/** + Initialize all MySQL global variables to default values. + + We don't need to set numeric variables refered to in my_long_options + as these are initialized by my_getopt. + + @note + The reason to set a lot of global variables to zero is to allow one to + restart the embedded server with a clean environment + It's also needed on some exotic platforms where global variables are + not set to 0 when a program starts. + + We don't need to set numeric variables refered to in my_long_options + as these are initialized by my_getopt. +*/ + +static int mysql_init_variables(void) +{ + int error; + /* Things reset to zero */ + opt_skip_slave_start= opt_reckless_slave = 0; + mysql_home[0]= pidfile_name[0]= log_error_file[0]= 0; + myisam_test_invalid_symlink= test_if_data_home_dir; + opt_log= opt_slow_log= 0; + opt_update_log= 0; + log_output_options= find_bit_type(log_output_str, &log_output_typelib); + opt_bin_log= 0; + opt_disable_networking= opt_skip_show_db=0; + opt_ignore_builtin_innodb= 0; + opt_logname= opt_update_logname= opt_binlog_index_name= opt_slow_logname= 0; + opt_tc_log_file= (char *)"tc.log"; // no hostname in tc_log file name ! + opt_secure_auth= 0; + opt_secure_file_priv= 0; + opt_bootstrap= opt_myisam_log= 0; + mqh_used= 0; + segfaulted= kill_in_progress= 0; + cleanup_done= 0; + defaults_argc= 0; + defaults_argv= 0; + server_id_supplied= 0; + test_flags= select_errors= dropping_tables= ha_open_options=0; + thread_count= thread_running= kill_cached_threads= wake_thread=0; + slave_open_temp_tables= 0; + cached_thread_count= 0; + opt_endinfo= using_udf_functions= 0; + opt_using_transactions= 0; + abort_loop= select_thread_in_use= signal_thread_in_use= 0; + ready_to_exit= shutdown_in_progress= grant_option= 0; + aborted_threads= aborted_connects= 0; + delayed_insert_threads= delayed_insert_writes= delayed_rows_in_use= 0; + delayed_insert_errors= thread_created= 0; + specialflag= 0; + binlog_cache_use= binlog_cache_disk_use= 0; + max_used_connections= slow_launch_threads = 0; + mysqld_user= mysqld_chroot= opt_init_file= opt_bin_logname = 0; + prepared_stmt_count= 0; + errmesg= 0; + mysqld_unix_port= opt_mysql_tmpdir= my_bind_addr_str= NullS; + bzero((uchar*) &mysql_tmpdir_list, sizeof(mysql_tmpdir_list)); + bzero((char *) &global_status_var, sizeof(global_status_var)); + opt_large_pages= 0; + key_map_full.set_all(); + + /* Character sets */ + system_charset_info= &my_charset_utf8_general_ci; + files_charset_info= &my_charset_utf8_general_ci; + national_charset_info= &my_charset_utf8_general_ci; + table_alias_charset= &my_charset_bin; + character_set_filesystem= &my_charset_bin; + + opt_date_time_formats[0]= opt_date_time_formats[1]= opt_date_time_formats[2]= 0; + + /* Things with default values that are not zero */ + delay_key_write_options= (uint) DELAY_KEY_WRITE_ON; + slave_exec_mode_options= 0; + slave_exec_mode_options= (uint) + find_bit_type_or_exit(slave_exec_mode_str, &slave_exec_mode_typelib, NULL, + &error); + if (error) + return 1; + opt_specialflag= SPECIAL_ENGLISH; + unix_sock= ip_sock= INVALID_SOCKET; + mysql_home_ptr= mysql_home; + pidfile_name_ptr= pidfile_name; + log_error_file_ptr= log_error_file; + language_ptr= language; + mysql_data_home= mysql_real_data_home; + thd_startup_options= (OPTION_AUTO_IS_NULL | OPTION_BIN_LOG | + OPTION_QUOTE_SHOW_CREATE | OPTION_SQL_NOTES); + protocol_version= PROTOCOL_VERSION; + what_to_log= ~ (1L << (uint) COM_TIME); + refresh_version= 1L; /* Increments on each reload */ + global_query_id= thread_id= 1L; + strmov(server_version, MYSQL_SERVER_VERSION); + myisam_recover_options_str= sql_mode_str= "OFF"; + myisam_stats_method_str= "nulls_unequal"; + my_bind_addr = htonl(INADDR_ANY); + threads.empty(); + thread_cache.empty(); + key_caches.empty(); + if (!(dflt_key_cache= get_or_create_key_cache(default_key_cache_base.str, + default_key_cache_base.length))) + { + sql_print_error("Cannot allocate the keycache"); + return 1; + } + /* set key_cache_hash.default_value = dflt_key_cache */ + multi_keycache_init(); + + /* Set directory paths */ + strmake(language, LANGUAGE, sizeof(language)-1); + strmake(mysql_real_data_home, get_relative_path(MYSQL_DATADIR), + sizeof(mysql_real_data_home)-1); + mysql_data_home_buff[0]=FN_CURLIB; // all paths are relative from here + mysql_data_home_buff[1]=0; + mysql_data_home_len= 2; + + /* Replication parameters */ + master_user= (char*) "test"; + master_password= master_host= 0; + master_info_file= (char*) "master.info", + relay_log_info_file= (char*) "relay-log.info"; + master_ssl_key= master_ssl_cert= master_ssl_ca= + master_ssl_capath= master_ssl_cipher= 0; + report_user= report_password = report_host= 0; /* TO BE DELETED */ + opt_relay_logname= opt_relaylog_index_name= 0; + + /* Variables in libraries */ + charsets_dir= 0; + default_character_set_name= (char*) MYSQL_DEFAULT_CHARSET_NAME; + default_collation_name= compiled_default_collation_name; + sys_charset_system.value= (char*) system_charset_info->csname; + character_set_filesystem_name= (char*) "binary"; + lc_time_names_name= (char*) "en_US"; + /* Set default values for some option variables */ + default_storage_engine_str= (char*) "MyISAM"; + global_system_variables.table_plugin= NULL; + global_system_variables.tx_isolation= ISO_REPEATABLE_READ; + global_system_variables.select_limit= (ulonglong) HA_POS_ERROR; + max_system_variables.select_limit= (ulonglong) HA_POS_ERROR; + global_system_variables.max_join_size= (ulonglong) HA_POS_ERROR; + max_system_variables.max_join_size= (ulonglong) HA_POS_ERROR; + global_system_variables.old_passwords= 0; + global_system_variables.old_alter_table= 0; + global_system_variables.binlog_format= BINLOG_FORMAT_UNSPEC; + /* + Default behavior for 4.1 and 5.0 is to treat NULL values as unequal + when collecting index statistics for MyISAM tables. + */ + global_system_variables.myisam_stats_method= MI_STATS_METHOD_NULLS_NOT_EQUAL; + + global_system_variables.optimizer_switch= OPTIMIZER_SWITCH_DEFAULT; + /* Variables that depends on compile options */ +#ifndef DBUG_OFF + default_dbug_option=IF_WIN("d:t:i:O,\\mysqld.trace", + "d:t:i:o,/tmp/mysqld.trace"); +#endif + opt_error_log= IF_WIN(1,0); +#ifdef COMMUNITY_SERVER + have_community_features = SHOW_OPTION_YES; +#else + have_community_features = SHOW_OPTION_NO; +#endif + global_system_variables.ndb_index_stat_enable=FALSE; + max_system_variables.ndb_index_stat_enable=TRUE; + global_system_variables.ndb_index_stat_cache_entries=32; + max_system_variables.ndb_index_stat_cache_entries=~0L; + global_system_variables.ndb_index_stat_update_freq=20; + max_system_variables.ndb_index_stat_update_freq=~0L; +#ifdef HAVE_OPENSSL + have_ssl=SHOW_OPTION_YES; +#else + have_ssl=SHOW_OPTION_NO; +#endif +#ifdef HAVE_BROKEN_REALPATH + have_symlink=SHOW_OPTION_NO; +#else + have_symlink=SHOW_OPTION_YES; +#endif +#ifdef HAVE_DLOPEN + have_dlopen=SHOW_OPTION_YES; +#else + have_dlopen=SHOW_OPTION_NO; +#endif +#ifdef HAVE_QUERY_CACHE + have_query_cache=SHOW_OPTION_YES; +#else + have_query_cache=SHOW_OPTION_NO; +#endif +#ifdef HAVE_SPATIAL + have_geometry=SHOW_OPTION_YES; +#else + have_geometry=SHOW_OPTION_NO; +#endif +#ifdef HAVE_RTREE_KEYS + have_rtree_keys=SHOW_OPTION_YES; +#else + have_rtree_keys=SHOW_OPTION_NO; +#endif +#ifdef HAVE_CRYPT + have_crypt=SHOW_OPTION_YES; +#else + have_crypt=SHOW_OPTION_NO; +#endif +#ifdef HAVE_COMPRESS + have_compress= SHOW_OPTION_YES; +#else + have_compress= SHOW_OPTION_NO; +#endif +#ifdef HAVE_LIBWRAP + libwrapName= NullS; +#endif +#ifdef HAVE_OPENSSL + des_key_file = 0; + ssl_acceptor_fd= 0; +#endif +#ifdef HAVE_SMEM + shared_memory_base_name= default_shared_memory_base_name; +#endif +#if !defined(my_pthread_setprio) && !defined(HAVE_PTHREAD_SETSCHEDPARAM) + opt_specialflag |= SPECIAL_NO_PRIOR; +#endif + +#if defined(__WIN__) || defined(__NETWARE__) + /* Allow Win32 and NetWare users to move MySQL anywhere */ + { + char prg_dev[LIBLEN]; +#if defined __WIN__ + char executing_path_name[LIBLEN]; + if (!test_if_hard_path(my_progname)) + { + // we don't want to use GetModuleFileName inside of my_path since + // my_path is a generic path dereferencing function and here we care + // only about the executing binary. + GetModuleFileName(NULL, executing_path_name, sizeof(executing_path_name)); + my_path(prg_dev, executing_path_name, NULL); + } + else +#endif + my_path(prg_dev,my_progname,"mysql/bin"); + strcat(prg_dev,"/../"); // Remove 'bin' to get base dir + cleanup_dirname(mysql_home,prg_dev); + } +#else + const char *tmpenv; + if (!(tmpenv = getenv("MY_BASEDIR_VERSION"))) + tmpenv = DEFAULT_MYSQL_HOME; + (void) strmake(mysql_home, tmpenv, sizeof(mysql_home)-1); +#endif + return 0; +} + + +my_bool +mysqld_get_one_option(int optid, + const struct my_option *opt __attribute__((unused)), + char *argument) +{ + int error; + + switch(optid) { + case '#': +#ifndef DBUG_OFF + DBUG_SET_INITIAL(argument ? argument : default_dbug_option); +#endif + opt_endinfo=1; /* unireg: memory allocation */ + break; + case 'a': + global_system_variables.sql_mode= fix_sql_mode(MODE_ANSI); + global_system_variables.tx_isolation= ISO_SERIALIZABLE; + break; + case 'b': + strmake(mysql_home,argument,sizeof(mysql_home)-1); + break; + case 'C': + if (default_collation_name == compiled_default_collation_name) + default_collation_name= 0; + break; + case 'l': + WARN_DEPRECATED(NULL, "7.0", "--log", "'--general_log'/'--general_log_file'"); + opt_log=1; + break; + case 'h': + strmake(mysql_real_data_home,argument, sizeof(mysql_real_data_home)-1); + /* Correct pointer set by my_getopt (for embedded library) */ + mysql_data_home= mysql_real_data_home; + mysql_data_home_len= strlen(mysql_data_home); + break; + case 'u': + if (!mysqld_user || !strcmp(mysqld_user, argument)) + mysqld_user= argument; + else + sql_print_warning("Ignoring user change to '%s' because the user was set to '%s' earlier on the command line\n", argument, mysqld_user); + break; + case 'L': + strmake(language, argument, sizeof(language)-1); + break; +#ifdef HAVE_REPLICATION + case OPT_SLAVE_SKIP_ERRORS: + init_slave_skip_errors(argument); + break; + case OPT_SLAVE_EXEC_MODE: + slave_exec_mode_options= (uint) + find_bit_type_or_exit(argument, &slave_exec_mode_typelib, "", &error); + if (error) + return 1; + break; +#endif + case OPT_SAFEMALLOC_MEM_LIMIT: +#if !defined(DBUG_OFF) && defined(SAFEMALLOC) + sf_malloc_mem_limit = atoi(argument); +#endif + break; +#include +#ifndef EMBEDDED_LIBRARY + case 'V': + print_version(); + exit(0); +#endif /*EMBEDDED_LIBRARY*/ + case 'W': + if (!argument) + global_system_variables.log_warnings++; + else if (argument == disabled_my_option) + global_system_variables.log_warnings= 0L; + else + global_system_variables.log_warnings= atoi(argument); + break; + case 'T': + test_flags= argument ? (uint) atoi(argument) : 0; + opt_endinfo=1; + break; + case (int) OPT_BIG_TABLES: + thd_startup_options|=OPTION_BIG_TABLES; + break; + case (int) OPT_IGNORE_BUILTIN_INNODB: + opt_ignore_builtin_innodb= 1; + break; + case (int) OPT_ISAM_LOG: + opt_myisam_log=1; + break; + case (int) OPT_UPDATE_LOG: + opt_update_log=1; + break; + case (int) OPT_BIN_LOG: + opt_bin_log= test(argument != disabled_my_option); + break; + case (int) OPT_ERROR_LOG_FILE: + opt_error_log= 1; + break; +#ifdef HAVE_REPLICATION + case (int) OPT_INIT_RPL_ROLE: + { + int role; + role= find_type_or_exit(argument, &rpl_role_typelib, opt->name); + rpl_status = (role == 1) ? RPL_AUTH_MASTER : RPL_IDLE_SLAVE; + break; + } + case (int)OPT_REPLICATE_IGNORE_DB: + { + rpl_filter->add_ignore_db(argument); + break; + } + case (int)OPT_REPLICATE_DO_DB: + { + rpl_filter->add_do_db(argument); + break; + } + case (int)OPT_REPLICATE_REWRITE_DB: + { + char* key = argument,*p, *val; + + if (!(p= strstr(argument, "->"))) + { + sql_print_error("Bad syntax in replicate-rewrite-db - missing '->'!\n"); + return 1; + } + val= p--; + while (my_isspace(mysqld_charset, *p) && p > argument) + *p-- = 0; + if (p == argument) + { + sql_print_error("Bad syntax in replicate-rewrite-db - empty FROM db!\n"); + return 1; + } + *val= 0; + val+= 2; + while (*val && my_isspace(mysqld_charset, *val)) + *val++; + if (!*val) + { + sql_print_error("Bad syntax in replicate-rewrite-db - empty TO db!\n"); + return 1; + } + + rpl_filter->add_db_rewrite(key, val); + break; + } + + case (int)OPT_BINLOG_IGNORE_DB: + { + binlog_filter->add_ignore_db(argument); + break; + } + case OPT_BINLOG_FORMAT: + { + int id; + id= find_type_or_exit(argument, &binlog_format_typelib, opt->name); + global_system_variables.binlog_format= opt_binlog_format_id= id - 1; + break; + } + case (int)OPT_BINLOG_DO_DB: + { + binlog_filter->add_do_db(argument); + break; + } + case (int)OPT_REPLICATE_DO_TABLE: + { + if (rpl_filter->add_do_table(argument)) + { + sql_print_error("Could not add do table rule '%s'!\n", argument); + return 1; + } + break; + } + case (int)OPT_REPLICATE_WILD_DO_TABLE: + { + if (rpl_filter->add_wild_do_table(argument)) + { + sql_print_error("Could not add do table rule '%s'!\n", argument); + return 1; + } + break; + } + case (int)OPT_REPLICATE_WILD_IGNORE_TABLE: + { + if (rpl_filter->add_wild_ignore_table(argument)) + { + sql_print_error("Could not add ignore table rule '%s'!\n", argument); + return 1; + } + break; + } + case (int)OPT_REPLICATE_IGNORE_TABLE: + { + if (rpl_filter->add_ignore_table(argument)) + { + sql_print_error("Could not add ignore table rule '%s'!\n", argument); + return 1; + } + break; + } +#endif /* HAVE_REPLICATION */ + case (int) OPT_SLOW_QUERY_LOG: + WARN_DEPRECATED(NULL, "7.0", "--log_slow_queries", "'--slow_query_log'/'--slow_query_log_file'"); + opt_slow_log= 1; + break; +#ifdef WITH_CSV_STORAGE_ENGINE + case OPT_LOG_OUTPUT: + { + if (!argument || !argument[0]) + { + log_output_options= LOG_FILE; + log_output_str= log_output_typelib.type_names[1]; + } + else + { + log_output_str= argument; + log_output_options= + find_bit_type_or_exit(argument, &log_output_typelib, opt->name, &error); + if (error) + return 1; + } + break; + } +#endif + case OPT_EVENT_SCHEDULER: +#ifndef HAVE_EVENT_SCHEDULER + sql_perror("Event scheduler is not supported in embedded build."); +#else + if (Events::set_opt_event_scheduler(argument)) + return 1; +#endif + break; + case (int) OPT_SKIP_NEW: + opt_specialflag|= SPECIAL_NO_NEW_FUNC; + delay_key_write_options= (uint) DELAY_KEY_WRITE_NONE; + myisam_concurrent_insert=0; + myisam_recover_options= HA_RECOVER_NONE; + sp_automatic_privileges=0; + my_use_symdir=0; + ha_open_options&= ~(HA_OPEN_ABORT_IF_CRASHED | HA_OPEN_DELAY_KEY_WRITE); +#ifdef HAVE_QUERY_CACHE + query_cache_size=0; +#endif + break; + case (int) OPT_SAFE: + opt_specialflag|= SPECIAL_SAFE_MODE; + delay_key_write_options= (uint) DELAY_KEY_WRITE_NONE; + myisam_recover_options= HA_RECOVER_DEFAULT; + ha_open_options&= ~(HA_OPEN_DELAY_KEY_WRITE); + break; + case (int) OPT_SKIP_PRIOR: + opt_specialflag|= SPECIAL_NO_PRIOR; + sql_print_warning("The --skip-thread-priority startup option is deprecated " + "and will be removed in MySQL 7.0. MySQL 6.0 and up do not " + "give threads different priorities."); + break; + case (int) OPT_SKIP_LOCK: + opt_external_locking=0; + break; + case (int) OPT_SKIP_HOST_CACHE: + opt_specialflag|= SPECIAL_NO_HOST_CACHE; + break; + case (int) OPT_SKIP_RESOLVE: + opt_specialflag|=SPECIAL_NO_RESOLVE; + break; + case (int) OPT_SKIP_NETWORKING: +#if defined(__NETWARE__) + sql_perror("Can't start server: skip-networking option is currently not supported on NetWare"); + return 1; +#endif + opt_disable_networking=1; + mysqld_port=0; + break; + case (int) OPT_SKIP_SHOW_DB: + opt_skip_show_db=1; + opt_specialflag|=SPECIAL_SKIP_SHOW_DB; + break; + case (int) OPT_WANT_CORE: + test_flags |= TEST_CORE_ON_SIGNAL; + break; + case (int) OPT_SKIP_STACK_TRACE: + test_flags|=TEST_NO_STACKTRACE; + break; + case (int) OPT_SKIP_SYMLINKS: + my_use_symdir=0; + break; + case (int) OPT_BIND_ADDRESS: + if ((my_bind_addr= (ulong) inet_addr(argument)) == INADDR_NONE) + { + struct hostent *ent; + if (argument[0]) + ent=gethostbyname(argument); + else + { + char myhostname[255]; + if (gethostname(myhostname,sizeof(myhostname)) < 0) + { + sql_perror("Can't start server: cannot get my own hostname!"); + return 1; + } + ent=gethostbyname(myhostname); + } + if (!ent) + { + sql_perror("Can't start server: cannot resolve hostname!"); + return 1; + } + my_bind_addr = (ulong) ((in_addr*)ent->h_addr_list[0])->s_addr; + } + break; + case (int) OPT_PID_FILE: + strmake(pidfile_name, argument, sizeof(pidfile_name)-1); + break; +#ifdef __WIN__ + case (int) OPT_STANDALONE: /* Dummy option for NT */ + break; +#endif + /* + The following change issues a deprecation warning if the slave + configuration is specified either in the my.cnf file or on + the command-line. See BUG#21490. + */ + case OPT_MASTER_HOST: + case OPT_MASTER_USER: + case OPT_MASTER_PASSWORD: + case OPT_MASTER_PORT: + case OPT_MASTER_CONNECT_RETRY: + case OPT_MASTER_SSL: + case OPT_MASTER_SSL_KEY: + case OPT_MASTER_SSL_CERT: + case OPT_MASTER_SSL_CAPATH: + case OPT_MASTER_SSL_CIPHER: + case OPT_MASTER_SSL_CA: + if (!slave_warning_issued) //only show the warning once + { + slave_warning_issued = true; + WARN_DEPRECATED(NULL, "6.0", "for replication startup options", + "'CHANGE MASTER'"); + } + break; + case OPT_CONSOLE: + if (opt_console) + opt_error_log= 0; // Force logs to stdout + break; + case (int) OPT_FLUSH: + myisam_flush=1; + flush_time=0; // No auto flush + break; + case OPT_LOW_PRIORITY_UPDATES: + thr_upgraded_concurrent_insert_lock= TL_WRITE_LOW_PRIORITY; + global_system_variables.low_priority_updates=1; + break; + case OPT_BOOTSTRAP: + opt_noacl=opt_bootstrap=1; + break; + case OPT_SERVER_ID: + server_id_supplied = 1; + break; + case OPT_DELAY_KEY_WRITE_ALL: + if (argument != disabled_my_option) + argument= (char*) "ALL"; + /* Fall through */ + case OPT_DELAY_KEY_WRITE: + if (argument == disabled_my_option) + delay_key_write_options= (uint) DELAY_KEY_WRITE_NONE; + else if (! argument) + delay_key_write_options= (uint) DELAY_KEY_WRITE_ON; + else + { + int type; + type= find_type_or_exit(argument, &delay_key_write_typelib, opt->name); + delay_key_write_options= (uint) type-1; + } + break; + case OPT_CHARSETS_DIR: + strmake(mysql_charsets_dir, argument, sizeof(mysql_charsets_dir)-1); + charsets_dir = mysql_charsets_dir; + break; + case OPT_TX_ISOLATION: + { + int type; + type= find_type_or_exit(argument, &tx_isolation_typelib, opt->name); + global_system_variables.tx_isolation= (type-1); + break; + } +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE + case OPT_NDB_MGMD: + case OPT_NDB_NODEID: + { + int len= my_snprintf(opt_ndb_constrbuf+opt_ndb_constrbuf_len, + sizeof(opt_ndb_constrbuf)-opt_ndb_constrbuf_len, + "%s%s%s",opt_ndb_constrbuf_len > 0 ? ",":"", + optid == OPT_NDB_NODEID ? "nodeid=" : "", + argument); + opt_ndb_constrbuf_len+= len; + } + /* fall through to add the connectstring to the end + * and set opt_ndbcluster_connectstring + */ + case OPT_NDB_CONNECTSTRING: + if (opt_ndb_connectstring && opt_ndb_connectstring[0]) + my_snprintf(opt_ndb_constrbuf+opt_ndb_constrbuf_len, + sizeof(opt_ndb_constrbuf)-opt_ndb_constrbuf_len, + "%s%s", opt_ndb_constrbuf_len > 0 ? ",":"", + opt_ndb_connectstring); + else + opt_ndb_constrbuf[opt_ndb_constrbuf_len]= 0; + opt_ndbcluster_connectstring= opt_ndb_constrbuf; + break; + case OPT_NDB_DISTRIBUTION: + int id; + id= find_type_or_exit(argument, &ndb_distribution_typelib, opt->name); + opt_ndb_distribution_id= (enum ndb_distribution)(id-1); + break; + case OPT_NDB_EXTRA_LOGGING: + if (!argument) + ndb_extra_logging++; + else if (argument == disabled_my_option) + ndb_extra_logging= 0L; + else + ndb_extra_logging= atoi(argument); + break; +#endif + case OPT_MYISAM_RECOVER: + { + if (!argument) + { + myisam_recover_options= HA_RECOVER_DEFAULT; + myisam_recover_options_str= myisam_recover_typelib.type_names[0]; + } + else if (!argument[0]) + { + myisam_recover_options= HA_RECOVER_NONE; + myisam_recover_options_str= "OFF"; + } + else + { + myisam_recover_options_str=argument; + myisam_recover_options= + find_bit_type_or_exit(argument, &myisam_recover_typelib, opt->name, + &error); + if (error) + return 1; + } + ha_open_options|=HA_OPEN_ABORT_IF_CRASHED; + break; + } + case OPT_CONCURRENT_INSERT: + /* The following code is mainly here to emulate old behavior */ + if (!argument) /* --concurrent-insert */ + myisam_concurrent_insert= 1; + else if (argument == disabled_my_option) + myisam_concurrent_insert= 0; /* --skip-concurrent-insert */ + break; + case OPT_TC_HEURISTIC_RECOVER: + tc_heuristic_recover= find_type_or_exit(argument, + &tc_heuristic_recover_typelib, + opt->name); + break; + case OPT_MYISAM_STATS_METHOD: + { + ulong method_conv; + int method; + LINT_INIT(method_conv); + + myisam_stats_method_str= argument; + method= find_type_or_exit(argument, &myisam_stats_method_typelib, + opt->name); + switch (method-1) { + case 2: + method_conv= MI_STATS_METHOD_IGNORE_NULLS; + break; + case 1: + method_conv= MI_STATS_METHOD_NULLS_EQUAL; + break; + case 0: + default: + method_conv= MI_STATS_METHOD_NULLS_NOT_EQUAL; + break; + } + global_system_variables.myisam_stats_method= method_conv; + break; + } + case OPT_SQL_MODE: + { + sql_mode_str= argument; + global_system_variables.sql_mode= + find_bit_type_or_exit(argument, &sql_mode_typelib, opt->name, &error); + if (error) + return 1; + global_system_variables.sql_mode= fix_sql_mode(global_system_variables. + sql_mode); + break; + } + case OPT_OPTIMIZER_SWITCH: + { + bool not_used; + char *error= 0; + uint error_len= 0; + optimizer_switch_str= argument; + global_system_variables.optimizer_switch= + (ulong)find_set_from_flags(&optimizer_switch_typelib, + optimizer_switch_typelib.count, + global_system_variables.optimizer_switch, + global_system_variables.optimizer_switch, + argument, strlen(argument), NULL, + &error, &error_len, ¬_used); + if (error) + { + char buf[512]; + char *cbuf= buf; + cbuf += my_snprintf(buf, 512, "Error in parsing optimizer_switch setting near %*s\n", error_len, error); + sql_perror(buf); + return 1; + } + break; + } + case OPT_ONE_THREAD: + global_system_variables.thread_handling= + SCHEDULER_ONE_THREAD_PER_CONNECTION; + break; + case OPT_THREAD_HANDLING: + { + global_system_variables.thread_handling= + find_type_or_exit(argument, &thread_handling_typelib, opt->name)-1; + break; + } + case OPT_FT_BOOLEAN_SYNTAX: + if (ft_boolean_check_syntax_string((uchar*) argument)) + { + sql_print_error("Invalid ft-boolean-syntax string: %s\n", argument); + return 1; + } + strmake(ft_boolean_syntax, argument, sizeof(ft_boolean_syntax)-1); + break; + case OPT_SKIP_SAFEMALLOC: +#ifdef SAFEMALLOC + sf_malloc_quick=1; +#endif + break; + case OPT_LOWER_CASE_TABLE_NAMES: + lower_case_table_names= argument ? atoi(argument) : 1; + lower_case_table_names_used= 1; + break; + } + return 0; +} + + +/** Handle arguments for multiple key caches. */ + +extern "C" int mysql_getopt_value(uchar **value, + const char *keyname, uint key_length, + const struct my_option *option, + int *error); + +static uchar* * +mysql_getopt_value(const char *keyname, uint key_length, + const struct my_option *option, int *error) +{ + if (error) + *error= 0; + switch (option->id) { + case OPT_KEY_BUFFER_SIZE: + case OPT_KEY_CACHE_BLOCK_SIZE: + case OPT_KEY_CACHE_DIVISION_LIMIT: + case OPT_KEY_CACHE_AGE_THRESHOLD: + { + KEY_CACHE *key_cache; + if (!(key_cache= get_or_create_key_cache(keyname, key_length))) + { + if (error) + *error= EXIT_OUT_OF_MEMORY; + return 0; + } + switch (option->id) { + case OPT_KEY_BUFFER_SIZE: + return (uchar**) &key_cache->param_buff_size; + case OPT_KEY_CACHE_BLOCK_SIZE: + return (uchar**) &key_cache->param_block_size; + case OPT_KEY_CACHE_DIVISION_LIMIT: + return (uchar**) &key_cache->param_division_limit; + case OPT_KEY_CACHE_AGE_THRESHOLD: + return (uchar**) &key_cache->param_age_threshold; + } + } + } + return option->value; +} + + +extern "C" void option_error_reporter(enum loglevel level, const char *format, ...); + +void option_error_reporter(enum loglevel level, const char *format, ...) +{ + va_list args; + va_start(args, format); + + /* Don't print warnings for --loose options during bootstrap */ + if (level == ERROR_LEVEL || !opt_bootstrap || + global_system_variables.log_warnings) + { + vprint_msg_to_log(level, format, args); + } + va_end(args); +} + + +/** + @todo + - FIXME add EXIT_TOO_MANY_ARGUMENTS to "mysys_err.h" and return that code? +*/ +static int get_options(int *argc,char **argv) +{ + int ho_error; + + my_getopt_register_get_addr(mysql_getopt_value); + strmake(def_ft_boolean_syntax, ft_boolean_syntax, + sizeof(ft_boolean_syntax)-1); + my_getopt_error_reporter= option_error_reporter; + + /* Skip unknown options so that they may be processed later by plugins */ + my_getopt_skip_unknown= TRUE; + + if ((ho_error= handle_options(argc, &argv, my_long_options, + mysqld_get_one_option))) + return ho_error; + (*argc)++; /* add back one for the progname handle_options removes */ + /* no need to do this for argv as we are discarding it. */ + + if ((opt_log_slow_admin_statements || opt_log_queries_not_using_indexes || + opt_log_slow_slave_statements) && + !opt_slow_log) + sql_print_warning("options --log-slow-admin-statements, --log-queries-not-using-indexes and --log-slow-slave-statements have no effect if --log_slow_queries is not set"); + +#if defined(HAVE_BROKEN_REALPATH) + my_use_symdir=0; + my_disable_symlinks=1; + have_symlink=SHOW_OPTION_NO; +#else + if (!my_use_symdir) + { + my_disable_symlinks=1; + have_symlink=SHOW_OPTION_DISABLED; + } +#endif + if (opt_debugging) + { + /* Allow break with SIGINT, no core or stack trace */ + test_flags|= TEST_SIGINT | TEST_NO_STACKTRACE; + test_flags&= ~TEST_CORE_ON_SIGNAL; + } + /* Set global MyISAM variables from delay_key_write_options */ + fix_delay_key_write((THD*) 0, OPT_GLOBAL); + /* Set global slave_exec_mode from its option */ + fix_slave_exec_mode(OPT_GLOBAL); + +#ifndef EMBEDDED_LIBRARY + if (mysqld_chroot) + set_root(mysqld_chroot); +#else + global_system_variables.thread_handling = SCHEDULER_NO_THREADS; + max_allowed_packet= global_system_variables.max_allowed_packet; + net_buffer_length= global_system_variables.net_buffer_length; +#endif + if (fix_paths()) + return 1; + + /* + Set some global variables from the global_system_variables + In most cases the global variables will not be used + */ + my_disable_locking= myisam_single_user= test(opt_external_locking == 0); + my_default_record_cache_size=global_system_variables.read_buff_size; + myisam_max_temp_length= + (my_off_t) global_system_variables.myisam_max_sort_file_size; + + /* Set global variables based on startup options */ + myisam_block_size=(uint) 1 << my_bit_log2(opt_myisam_block_size); + + /* long_query_time is in microseconds */ + global_system_variables.long_query_time= max_system_variables.long_query_time= + (longlong) (long_query_time * 1000000.0); + + if (opt_short_log_format) + opt_specialflag|= SPECIAL_SHORT_LOG_FORMAT; + + if (init_global_datetime_format(MYSQL_TIMESTAMP_DATE, + &global_system_variables.date_format) || + init_global_datetime_format(MYSQL_TIMESTAMP_TIME, + &global_system_variables.time_format) || + init_global_datetime_format(MYSQL_TIMESTAMP_DATETIME, + &global_system_variables.datetime_format)) + return 1; + +#ifdef EMBEDDED_LIBRARY + one_thread_scheduler(&thread_scheduler); +#else + if (global_system_variables.thread_handling <= + SCHEDULER_ONE_THREAD_PER_CONNECTION) + one_thread_per_connection_scheduler(&thread_scheduler); + else if (global_system_variables.thread_handling == SCHEDULER_NO_THREADS) + one_thread_scheduler(&thread_scheduler); + else + pool_of_threads_scheduler(&thread_scheduler); /* purecov: tested */ +#endif + return 0; +} + + +/* + Create version name for running mysqld version + We automaticly add suffixes -debug, -embedded and -log to the version + name to make the version more descriptive. + (MYSQL_SERVER_SUFFIX is set by the compilation environment) +*/ + +static void set_server_version(void) +{ + char *end= strxmov(server_version, MYSQL_SERVER_VERSION, + MYSQL_SERVER_SUFFIX_STR, NullS); +#ifdef EMBEDDED_LIBRARY + end= strmov(end, "-embedded"); +#endif +#ifndef DBUG_OFF + if (!strstr(MYSQL_SERVER_SUFFIX_STR, "-debug")) + end= strmov(end, "-debug"); +#endif + if (opt_log || opt_update_log || opt_slow_log || opt_bin_log) + strmov(end, "-log"); // This may slow down system +} + + +static char *get_relative_path(const char *path) +{ + if (test_if_hard_path(path) && + is_prefix(path,DEFAULT_MYSQL_HOME) && + strcmp(DEFAULT_MYSQL_HOME,FN_ROOTDIR)) + { + path+=(uint) strlen(DEFAULT_MYSQL_HOME); + while (*path == FN_LIBCHAR) + path++; + } + return (char*) path; +} + + +/** + Fix filename and replace extension where 'dir' is relative to + mysql_real_data_home. + @return + 1 if len(path) > FN_REFLEN +*/ + +bool +fn_format_relative_to_data_home(char * to, const char *name, + const char *dir, const char *extension) +{ + char tmp_path[FN_REFLEN]; + if (!test_if_hard_path(dir)) + { + strxnmov(tmp_path,sizeof(tmp_path)-1, mysql_real_data_home, + dir, NullS); + dir=tmp_path; + } + return !fn_format(to, name, dir, extension, + MY_APPEND_EXT | MY_UNPACK_FILENAME | MY_SAFE_PATH); +} + + +static int fix_paths(void) +{ + char buff[FN_REFLEN],*pos; + convert_dirname(mysql_home,mysql_home,NullS); + /* Resolve symlinks to allow 'mysql_home' to be a relative symlink */ + my_realpath(mysql_home,mysql_home,MYF(0)); + /* Ensure that mysql_home ends in FN_LIBCHAR */ + pos=strend(mysql_home); + if (pos[-1] != FN_LIBCHAR) + { + pos[0]= FN_LIBCHAR; + pos[1]= 0; + } + convert_dirname(mysql_real_data_home,mysql_real_data_home,NullS); + my_realpath(mysql_unpacked_real_data_home, mysql_real_data_home, MYF(0)); + mysql_unpacked_real_data_home_len= strlen(mysql_unpacked_real_data_home); + if (mysql_unpacked_real_data_home[mysql_unpacked_real_data_home_len-1] == FN_LIBCHAR) + --mysql_unpacked_real_data_home_len; + + + convert_dirname(language,language,NullS); + (void) my_load_path(mysql_home,mysql_home,""); // Resolve current dir + (void) my_load_path(mysql_real_data_home,mysql_real_data_home,mysql_home); + (void) my_load_path(pidfile_name,pidfile_name,mysql_real_data_home); + (void) my_load_path(opt_plugin_dir, opt_plugin_dir_ptr ? opt_plugin_dir_ptr : + get_relative_path(PLUGINDIR), mysql_home); + opt_plugin_dir_ptr= opt_plugin_dir; + + char *sharedir=get_relative_path(SHAREDIR); + if (test_if_hard_path(sharedir)) + strmake(buff,sharedir,sizeof(buff)-1); /* purecov: tested */ + else + strxnmov(buff,sizeof(buff)-1,mysql_home,sharedir,NullS); + convert_dirname(buff,buff,NullS); + (void) my_load_path(language,language,buff); + + /* If --character-sets-dir isn't given, use shared library dir */ + if (charsets_dir != mysql_charsets_dir) + { + strxnmov(mysql_charsets_dir, sizeof(mysql_charsets_dir)-1, buff, + CHARSET_DIR, NullS); + } + (void) my_load_path(mysql_charsets_dir, mysql_charsets_dir, buff); + convert_dirname(mysql_charsets_dir, mysql_charsets_dir, NullS); + charsets_dir=mysql_charsets_dir; + + if (init_tmpdir(&mysql_tmpdir_list, opt_mysql_tmpdir)) + return 1; +#ifdef HAVE_REPLICATION + if (!slave_load_tmpdir) + { + if (!(slave_load_tmpdir = (char*) my_strdup(mysql_tmpdir, MYF(MY_FAE)))) + return 1; + } +#endif /* HAVE_REPLICATION */ + /* + Convert the secure-file-priv option to system format, allowing + a quick strcmp to check if read or write is in an allowed dir + */ + if (opt_secure_file_priv) + { + convert_dirname(buff, opt_secure_file_priv, NullS); + my_free(opt_secure_file_priv, MYF(0)); + opt_secure_file_priv= my_strdup(buff, MYF(MY_FAE)); + } + return 0; +} + + +static ulong find_bit_type_or_exit(const char *x, TYPELIB *bit_lib, + const char *option, int *error) +{ + ulong result; + const char **ptr; + + *error= 0; + if ((result= find_bit_type(x, bit_lib)) == ~(ulong) 0) + { + char *buff= (char *) my_alloca(2048); + char *cbuf; + ptr= bit_lib->type_names; + cbuf= buff + ((!*x) ? + my_snprintf(buff, 2048, "No option given to %s\n", option) : + my_snprintf(buff, 2048, "Wrong option to %s. Option(s) given: %s\n", + option, x)); + cbuf+= my_snprintf(cbuf, 2048 - (cbuf-buff), "Alternatives are: '%s'", *ptr); + while (*++ptr) + cbuf+= my_snprintf(cbuf, 2048 - (cbuf-buff), ",'%s'", *ptr); + my_snprintf(cbuf, 2048 - (cbuf-buff), "\n"); + sql_perror(buff); + *error= 1; + my_afree(buff); + return 0; + } + + return result; +} + + +/** + @return + a bitfield from a string of substrings separated by ',' + or + ~(ulong) 0 on error. +*/ + +static ulong find_bit_type(const char *x, TYPELIB *bit_lib) +{ + bool found_end; + int found_count; + const char *end,*i,*j; + const char **array, *pos; + ulong found,found_int,bit; + DBUG_ENTER("find_bit_type"); + DBUG_PRINT("enter",("x: '%s'",x)); + + found=0; + found_end= 0; + pos=(char *) x; + while (*pos == ' ') pos++; + found_end= *pos == 0; + while (!found_end) + { + if (!*(end=strcend(pos,','))) /* Let end point at fieldend */ + { + while (end > pos && end[-1] == ' ') + end--; /* Skip end-space */ + found_end=1; + } + found_int=0; found_count=0; + for (array=bit_lib->type_names, bit=1 ; (i= *array++) ; bit<<=1) + { + j=pos; + while (j != end) + { + if (my_toupper(mysqld_charset,*i++) != + my_toupper(mysqld_charset,*j++)) + goto skip; + } + found_int=bit; + if (! *i) + { + found_count=1; + break; + } + else if (j != pos) // Half field found + { + found_count++; // Could be one of two values + } +skip: ; + } + if (found_count != 1) + DBUG_RETURN(~(ulong) 0); // No unique value + found|=found_int; + pos=end+1; + } + + DBUG_PRINT("exit",("bit-field: %ld",(ulong) found)); + DBUG_RETURN(found); +} /* find_bit_type */ + + +/** + Check if file system used for databases is case insensitive. + + @param dir_name Directory to test + + @retval + -1 Don't know (Test failed) + @retval + 0 File system is case sensitive + @retval + 1 File system is case insensitive +*/ + +static int test_if_case_insensitive(const char *dir_name) +{ + int result= 0; + File file; + char buff[FN_REFLEN], buff2[FN_REFLEN]; + MY_STAT stat_info; + DBUG_ENTER("test_if_case_insensitive"); + + fn_format(buff, glob_hostname, dir_name, ".lower-test", + MY_UNPACK_FILENAME | MY_REPLACE_EXT | MY_REPLACE_DIR); + fn_format(buff2, glob_hostname, dir_name, ".LOWER-TEST", + MY_UNPACK_FILENAME | MY_REPLACE_EXT | MY_REPLACE_DIR); + (void) my_delete(buff2, MYF(0)); + if ((file= my_create(buff, 0666, O_RDWR, MYF(0))) < 0) + { + sql_print_warning("Can't create test file %s", buff); + DBUG_RETURN(-1); + } + my_close(file, MYF(0)); + if (my_stat(buff2, &stat_info, MYF(0))) + result= 1; // Can access file + (void) my_delete(buff, MYF(MY_WME)); + DBUG_PRINT("exit", ("result: %d", result)); + DBUG_RETURN(result); +} + + +#ifndef EMBEDDED_LIBRARY + +/** + Create file to store pid number. +*/ +static void create_pid_file() +{ + File file; + if ((file = my_create(pidfile_name,0664, + O_WRONLY | O_TRUNC, MYF(MY_WME))) >= 0) + { + char buff[21], *end; + end= int10_to_str((long) getpid(), buff, 10); + *end++= '\n'; + if (!my_write(file, (uchar*) buff, (uint) (end-buff), MYF(MY_WME | MY_NABP))) + { + (void) my_close(file, MYF(0)); + return; + } + (void) my_close(file, MYF(0)); + } + sql_perror("Can't start server: can't create PID file"); + exit(1); +} +#endif /* EMBEDDED_LIBRARY */ + +/** Clear most status variables. */ +void refresh_status(THD *thd) +{ + pthread_mutex_lock(&LOCK_status); + + /* Add thread's status variabes to global status */ + add_to_status(&global_status_var, &thd->status_var); + + /* Reset thread's status variables */ + bzero((uchar*) &thd->status_var, sizeof(thd->status_var)); + + /* Reset some global variables */ + reset_status_vars(); + + /* Reset the counters of all key caches (default and named). */ + process_key_caches(reset_key_cache_counters); +#ifdef COMMUNITY_SERVER + flush_status_time= time((time_t*) 0); +#endif + pthread_mutex_unlock(&LOCK_status); + + /* + Set max_used_connections to the number of currently open + connections. Lock LOCK_thread_count out of LOCK_status to avoid + deadlocks. Status reset becomes not atomic, but status data is + not exact anyway. + */ + pthread_mutex_lock(&LOCK_thread_count); + max_used_connections= thread_count-delayed_insert_threads; + pthread_mutex_unlock(&LOCK_thread_count); +} + + +/***************************************************************************** + Instantiate variables for missing storage engines + This section should go away soon +*****************************************************************************/ + +#ifndef WITH_NDBCLUSTER_STORAGE_ENGINE +ulong ndb_cache_check_time; +ulong ndb_extra_logging; +#endif + +/***************************************************************************** + Instantiate templates +*****************************************************************************/ + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +/* Used templates */ +template class I_List; +template class I_List_iterator; +template class I_List; +template class I_List; +template class I_List; +template class I_List; +template class I_List_iterator; +#endif diff --git a/dbcon/mysql/mysys/my_handler_errors.h b/dbcon/mysql/mysys/my_handler_errors.h new file mode 100644 index 00000000..9447bf8f --- /dev/null +++ b/dbcon/mysql/mysys/my_handler_errors.h @@ -0,0 +1,72 @@ + +/* + Errors a handler can give you +*/ + +static const char *handler_error_messages[]= +{ + "Didn't find key on read or update", + "Duplicate key on write or update", + "Internal (unspecified) error in handler", + "Someone has changed the row since it was read (while the table was locked to prevent it)", + "Wrong index given to function", + "Undefined handler error 125", + "Index file is crashed", + "Record file is crashed", + "Out of memory in engine", + "Undefined handler error 129", + "Incorrect file format", + "Command not supported by database", + "Old database file", + "No record read before update", + "Record was already deleted (or record file crashed)", + "No more room in record file", + "No more room in index file", + "No more records (read after end of file)", + "Unsupported extension used for table", + "Too big row", + "Wrong create options", + "Duplicate unique key or constraint on write or update", + "Unknown character set used in table", + "Conflicting table definitions in sub-tables of MERGE table", + "Table is crashed and last repair failed", + "Table was marked as crashed and should be repaired", + "Lock timed out; Retry transaction", + "Lock table is full; Restart program with a larger locktable", + "Updates are not allowed under a read only transactions", + "Lock deadlock; Retry transaction", + "Foreign key constraint is incorrectly formed", + "Cannot add a child row", + "Cannot delete a parent row", + "No savepoint with that name", + "Non unique key block size", + "The table does not exist in engine", + "The table already existed in storage engine", + "Could not connect to storage engine", + "Unexpected null pointer found when using spatial index", + "The table changed in storage engine", + "There's no partition in table for the given value", + "Row-based binlogging of row failed", + "Index needed in foreign key constraint", + "Upholding foreign key constraints would lead to a duplicate key error in " + "some other table", + "Table needs to be upgraded before it can be used", + "Table is read only", + "Failed to get next auto increment value", + "Failed to set row auto increment value", + "Unknown (generic) error from engine", + "Record is the same", + "It is not possible to log this statement", + "The event was corrupt, leading to illegal data being read", + "The table is of a new format not supported by this version", + "The event could not be processed no other hanlder error happened", + "Got a fatal error during initialzaction of handler", + "File to short; Expected more data in file", + "Read page with wrong checksum", + "Too many active concurrent transactions", + "", /* @InfiniDB @bug4585 for InnoDB upgrade */ + "", + "", + "Table is being used in foreign key check" /* HA_ERR_TABLE_IN_FK_CHECK */ +}; + diff --git a/dbcon/mysql/resource.h b/dbcon/mysql/resource.h deleted file mode 100644 index 54c359c8..00000000 --- a/dbcon/mysql/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by libcalmysql.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/dbcon/mysql/schemaSync.pl b/dbcon/mysql/schemaSync.pl index 22edb1c1..dac5dc9d 100755 --- a/dbcon/mysql/schemaSync.pl +++ b/dbcon/mysql/schemaSync.pl @@ -1,6 +1,6 @@ #!/usr/bin/perl -w # -# $Id: schemaSync.pl 9731 2013-08-01 16:58:35Z rdempsey $ +# $Id: schemaSync.pl 7431 2011-02-15 14:21:52Z rdempsey $ use DBI; use DBD::mysql; @@ -115,49 +115,13 @@ sub datatype2name $dts = 'varchar'; } elsif ($dt == 13) - { - $dts = 'varbinary'; - } - elsif ($dt == 14) { $dts = 'clob'; } - elsif ($dt == 15) + elsif ($dt == 14) { $dts = 'blob'; } - elsif ($dt == 16) - { - $dts = 'tinyint unsigned'; - } - elsif ($dt == 17) - { - $dts = 'smallint unsigned'; - } - elsif ($dt == 18) - { - $dts = 'decimal unsigned'; - } - elsif ($dt == 19) - { - $dts = 'medint unsigned'; - } - elsif ($dt == 20) - { - $dts = 'int unsigned'; - } - elsif ($dt == 21) - { - $dts = 'float unsigned'; - } - elsif ($dt == 22) - { - $dts = 'bigint unsigned'; - } - elsif ($dt == 23) - { - $dts = 'double unsigned'; - } else { $dts = "$dt"; @@ -216,7 +180,7 @@ sub datatype2name print ", "; } print "$@$co->[2] $nm"; - if ($nm eq 'char' || $nm eq 'varchar' || $nm eq 'varbinary') + if ($nm eq 'char' || $nm eq 'varchar') { print "($@$co->[8])"; } diff --git a/dbcon/mysql/set_var.cc b/dbcon/mysql/set_var.cc new file mode 100644 index 00000000..fa55453d --- /dev/null +++ b/dbcon/mysql/set_var.cc @@ -0,0 +1,4300 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** + @file + + @brief + Handling of MySQL SQL variables + + @details + To add a new variable, one has to do the following: + + - Use one of the 'sys_var... classes from set_var.h or write a specific + one for the variable type. + - Define it in the 'variable definition list' in this file. + - If the variable is thread specific, add it to 'system_variables' struct. + If not, add it to mysqld.cc and an declaration in 'mysql_priv.h' + - If the variable should be changed from the command line, add a definition + of it in the my_option structure list in mysqld.cc + - Don't forget to initialize new fields in global_system_variables and + max_system_variables! + + @todo + Add full support for the variable character_set (for 4.1) + + @todo + When updating myisam_delay_key_write, we should do a 'flush tables' + of all MyISAM tables to ensure that they are reopen with the + new attribute. + + @note + Be careful with var->save_result: sys_var::check() only updates + ulonglong_value; so other members of the union are garbage then; to use + them you must first assign a value to them (in specific ::check() for + example). +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include +#include "slave.h" +#include "rpl_mi.h" +#include +#include +#include +#include + +#include "events.h" + +/* WITH_NDBCLUSTER_STORAGE_ENGINE */ +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE +extern ulong ndb_cache_check_time; +extern char opt_ndb_constrbuf[]; +extern ulong ndb_extra_logging; +#endif + +#ifdef HAVE_NDB_BINLOG +extern ulong ndb_report_thresh_binlog_epoch_slip; +extern ulong ndb_report_thresh_binlog_mem_usage; +#endif + +extern CHARSET_INFO *character_set_filesystem; + + +static HASH system_variable_hash; + +const char *bool_type_names[]= { "OFF", "ON", NullS }; +TYPELIB bool_typelib= +{ + array_elements(bool_type_names)-1, "", bool_type_names, NULL +}; + +const char *delay_key_write_type_names[]= { "OFF", "ON", "ALL", NullS }; +TYPELIB delay_key_write_typelib= +{ + array_elements(delay_key_write_type_names)-1, "", + delay_key_write_type_names, NULL +}; + +const char *slave_exec_mode_names[]= +{ "STRICT", "IDEMPOTENT", NullS }; +static const unsigned int slave_exec_mode_names_len[]= +{ sizeof("STRICT") - 1, sizeof("IDEMPOTENT") - 1, 0 }; +TYPELIB slave_exec_mode_typelib= +{ + array_elements(slave_exec_mode_names)-1, "", + slave_exec_mode_names, (unsigned int *) slave_exec_mode_names_len +}; + +static int sys_check_ftb_syntax(THD *thd, set_var *var); +static bool sys_update_ftb_syntax(THD *thd, set_var * var); +static void sys_default_ftb_syntax(THD *thd, enum_var_type type); +static bool sys_update_init_connect(THD*, set_var*); +static void sys_default_init_connect(THD*, enum_var_type type); +static bool sys_update_init_slave(THD*, set_var*); +static void sys_default_init_slave(THD*, enum_var_type type); +static bool set_option_bit(THD *thd, set_var *var); +static bool set_option_log_bin_bit(THD *thd, set_var *var); +static bool set_option_autocommit(THD *thd, set_var *var); +static int check_log_update(THD *thd, set_var *var); +static bool set_log_update(THD *thd, set_var *var); +static int check_pseudo_thread_id(THD *thd, set_var *var); +void fix_binlog_format_after_update(THD *thd, enum_var_type type); +static void fix_low_priority_updates(THD *thd, enum_var_type type); +static int check_tx_isolation(THD *thd, set_var *var); +static void fix_tx_isolation(THD *thd, enum_var_type type); +static int check_completion_type(THD *thd, set_var *var); +static void fix_completion_type(THD *thd, enum_var_type type); +static void fix_net_read_timeout(THD *thd, enum_var_type type); +static void fix_net_write_timeout(THD *thd, enum_var_type type); +static void fix_net_retry_count(THD *thd, enum_var_type type); +static void fix_max_join_size(THD *thd, enum_var_type type); +static void fix_query_cache_size(THD *thd, enum_var_type type); +static void fix_query_cache_min_res_unit(THD *thd, enum_var_type type); +static void fix_myisam_max_sort_file_size(THD *thd, enum_var_type type); +static void fix_max_binlog_size(THD *thd, enum_var_type type); +static void fix_max_relay_log_size(THD *thd, enum_var_type type); +static void fix_max_connections(THD *thd, enum_var_type type); +static int check_max_delayed_threads(THD *thd, set_var *var); +static void fix_thd_mem_root(THD *thd, enum_var_type type); +static void fix_trans_mem_root(THD *thd, enum_var_type type); +static void fix_server_id(THD *thd, enum_var_type type); +bool throw_bounds_warning(THD *thd, bool fixed, bool unsignd, + const char *name, longlong val); +static KEY_CACHE *create_key_cache(const char *name, uint length); +void fix_sql_mode_var(THD *thd, enum_var_type type); +static uchar *get_error_count(THD *thd); +static uchar *get_warning_count(THD *thd); +static uchar *get_tmpdir(THD *thd); +static int sys_check_log_path(THD *thd, set_var *var); +static bool sys_update_general_log_path(THD *thd, set_var * var); +static void sys_default_general_log_path(THD *thd, enum_var_type type); +static bool sys_update_slow_log_path(THD *thd, set_var * var); +static void sys_default_slow_log_path(THD *thd, enum_var_type type); + +/* + Variable definition list + + These are variables that can be set from the command line, in + alphabetic order. + + The variables are linked into the list. A variable is added to + it in the constructor (see sys_var class for details). +*/ + +static sys_var_chain vars = { NULL, NULL }; + +static sys_var_thd_ulong +sys_auto_increment_increment(&vars, "auto_increment_increment", + &SV::auto_increment_increment, NULL, NULL, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_thd_ulong +sys_auto_increment_offset(&vars, "auto_increment_offset", + &SV::auto_increment_offset, NULL, NULL, + sys_var::SESSION_VARIABLE_IN_BINLOG); + +static sys_var_bool_ptr sys_automatic_sp_privileges(&vars, "automatic_sp_privileges", + &sp_automatic_privileges); + +static sys_var_const sys_back_log(&vars, "back_log", + OPT_GLOBAL, SHOW_LONG, + (uchar*) &back_log); +static sys_var_const_os_str sys_basedir(&vars, "basedir", mysql_home); +static sys_var_long_ptr sys_binlog_cache_size(&vars, "binlog_cache_size", + &binlog_cache_size); +static sys_var_thd_binlog_format sys_binlog_format(&vars, "binlog_format", + &SV::binlog_format); +static sys_var_thd_ulong sys_bulk_insert_buff_size(&vars, "bulk_insert_buffer_size", + &SV::bulk_insert_buff_size); +static sys_var_const_os sys_character_sets_dir(&vars, + "character_sets_dir", + OPT_GLOBAL, SHOW_CHAR, + (uchar*) + mysql_charsets_dir); +static sys_var_character_set_sv +sys_character_set_server(&vars, "character_set_server", + &SV::collation_server, &default_charset_info, 0, + sys_var::SESSION_VARIABLE_IN_BINLOG); +sys_var_const_str sys_charset_system(&vars, "character_set_system", + (char *)my_charset_utf8_general_ci.name); +static sys_var_character_set_database +sys_character_set_database(&vars, "character_set_database", + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_character_set_client +sys_character_set_client(&vars, "character_set_client", + &SV::character_set_client, + &default_charset_info, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_character_set_sv +sys_character_set_connection(&vars, "character_set_connection", + &SV::collation_connection, + &default_charset_info, 0, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_character_set_sv sys_character_set_results(&vars, "character_set_results", + &SV::character_set_results, + &default_charset_info, true); +static sys_var_character_set_sv sys_character_set_filesystem(&vars, "character_set_filesystem", + &SV::character_set_filesystem, + &character_set_filesystem); +static sys_var_thd_ulong sys_completion_type(&vars, "completion_type", + &SV::completion_type, + check_completion_type, + fix_completion_type); +static sys_var_collation_sv +sys_collation_connection(&vars, "collation_connection", + &SV::collation_connection, &default_charset_info, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_collation_sv +sys_collation_database(&vars, "collation_database", &SV::collation_database, + &default_charset_info, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_collation_sv +sys_collation_server(&vars, "collation_server", &SV::collation_server, + &default_charset_info, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_long_ptr sys_concurrent_insert(&vars, "concurrent_insert", + &myisam_concurrent_insert); +static sys_var_long_ptr sys_connect_timeout(&vars, "connect_timeout", + &connect_timeout); +static sys_var_const_os_str sys_datadir(&vars, "datadir", mysql_real_data_home); +#ifndef DBUG_OFF +static sys_var_thd_dbug sys_dbug(&vars, "debug"); +#endif +static sys_var_enum sys_delay_key_write(&vars, "delay_key_write", + &delay_key_write_options, + &delay_key_write_typelib, + fix_delay_key_write); +static sys_var_long_ptr sys_delayed_insert_limit(&vars, "delayed_insert_limit", + &delayed_insert_limit); +static sys_var_long_ptr sys_delayed_insert_timeout(&vars, "delayed_insert_timeout", + &delayed_insert_timeout); +static sys_var_long_ptr sys_delayed_queue_size(&vars, "delayed_queue_size", + &delayed_queue_size); + +#ifdef HAVE_EVENT_SCHEDULER +static sys_var_event_scheduler sys_event_scheduler(&vars, "event_scheduler"); +#endif + +static sys_var_long_ptr sys_expire_logs_days(&vars, "expire_logs_days", + &expire_logs_days); +static sys_var_bool_ptr sys_flush(&vars, "flush", &myisam_flush); +static sys_var_long_ptr sys_flush_time(&vars, "flush_time", &flush_time); +static sys_var_str sys_ft_boolean_syntax(&vars, "ft_boolean_syntax", + sys_check_ftb_syntax, + sys_update_ftb_syntax, + sys_default_ftb_syntax, + ft_boolean_syntax); +static sys_var_const sys_ft_max_word_len(&vars, "ft_max_word_len", + OPT_GLOBAL, SHOW_LONG, + (uchar*) &ft_max_word_len); +static sys_var_const sys_ft_min_word_len(&vars, "ft_min_word_len", + OPT_GLOBAL, SHOW_LONG, + (uchar*) &ft_min_word_len); +static sys_var_const sys_ft_query_expansion_limit(&vars, + "ft_query_expansion_limit", + OPT_GLOBAL, SHOW_LONG, + (uchar*) + &ft_query_expansion_limit); +static sys_var_const sys_ft_stopword_file(&vars, "ft_stopword_file", + OPT_GLOBAL, SHOW_CHAR_PTR, + (uchar*) &ft_stopword_file); + +static sys_var_const sys_ignore_builtin_innodb(&vars, "ignore_builtin_innodb", + OPT_GLOBAL, SHOW_BOOL, + (uchar*) &opt_ignore_builtin_innodb); + +sys_var_str sys_init_connect(&vars, "init_connect", 0, + sys_update_init_connect, + sys_default_init_connect,0); +static sys_var_const sys_init_file(&vars, "init_file", + OPT_GLOBAL, SHOW_CHAR_PTR, + (uchar*) &opt_init_file); +sys_var_str sys_init_slave(&vars, "init_slave", 0, + sys_update_init_slave, + sys_default_init_slave,0); +static sys_var_thd_ulong sys_interactive_timeout(&vars, "interactive_timeout", + &SV::net_interactive_timeout); +static sys_var_thd_ulong sys_join_buffer_size(&vars, "join_buffer_size", + &SV::join_buff_size); +static sys_var_key_buffer_size sys_key_buffer_size(&vars, "key_buffer_size"); +static sys_var_key_cache_long sys_key_cache_block_size(&vars, "key_cache_block_size", + offsetof(KEY_CACHE, + param_block_size)); +static sys_var_key_cache_long sys_key_cache_division_limit(&vars, "key_cache_division_limit", + offsetof(KEY_CACHE, + param_division_limit)); +static sys_var_key_cache_long sys_key_cache_age_threshold(&vars, "key_cache_age_threshold", + offsetof(KEY_CACHE, + param_age_threshold)); +static sys_var_const sys_language(&vars, "language", + OPT_GLOBAL, SHOW_CHAR, + (uchar*) language); +static sys_var_const sys_large_files_support(&vars, "large_files_support", + OPT_GLOBAL, SHOW_BOOL, + (uchar*) &opt_large_files); +static sys_var_const sys_large_page_size(&vars, "large_page_size", + OPT_GLOBAL, SHOW_INT, + (uchar*) &opt_large_page_size); +static sys_var_const sys_large_pages(&vars, "large_pages", + OPT_GLOBAL, SHOW_MY_BOOL, + (uchar*) &opt_large_pages); +static sys_var_bool_ptr sys_local_infile(&vars, "local_infile", + &opt_local_infile); +#ifdef HAVE_MLOCKALL +static sys_var_const sys_locked_in_memory(&vars, "locked_in_memory", + OPT_GLOBAL, SHOW_MY_BOOL, + (uchar*) &locked_in_memory); +#endif +static sys_var_const sys_log_bin(&vars, "log_bin", + OPT_GLOBAL, SHOW_BOOL, + (uchar*) &opt_bin_log); +static sys_var_trust_routine_creators +sys_trust_routine_creators(&vars, "log_bin_trust_routine_creators", + &trust_function_creators); +static sys_var_bool_ptr +sys_trust_function_creators(&vars, "log_bin_trust_function_creators", + &trust_function_creators); +static sys_var_const sys_log_error(&vars, "log_error", + OPT_GLOBAL, SHOW_CHAR, + (uchar*) log_error_file); +static sys_var_bool_ptr + sys_log_queries_not_using_indexes(&vars, "log_queries_not_using_indexes", + &opt_log_queries_not_using_indexes); +static sys_var_thd_ulong sys_log_warnings(&vars, "log_warnings", &SV::log_warnings); +static sys_var_microseconds sys_var_long_query_time(&vars, "long_query_time", + &SV::long_query_time); +static sys_var_thd_bool sys_low_priority_updates(&vars, "low_priority_updates", + &SV::low_priority_updates, + fix_low_priority_updates); +#ifndef TO_BE_DELETED /* Alias for the low_priority_updates */ +static sys_var_thd_bool sys_sql_low_priority_updates(&vars, "sql_low_priority_updates", + &SV::low_priority_updates, + fix_low_priority_updates); +#endif +static sys_var_const sys_lower_case_file_system(&vars, + "lower_case_file_system", + OPT_GLOBAL, SHOW_MY_BOOL, + (uchar*) + &lower_case_file_system); +static sys_var_const sys_lower_case_table_names(&vars, + "lower_case_table_names", + OPT_GLOBAL, SHOW_INT, + (uchar*) + &lower_case_table_names); +static sys_var_thd_ulong_session_readonly sys_max_allowed_packet(&vars, "max_allowed_packet", + &SV::max_allowed_packet); +static sys_var_ulonglong_ptr sys_max_binlog_cache_size(&vars, "max_binlog_cache_size", + &max_binlog_cache_size); +static sys_var_long_ptr sys_max_binlog_size(&vars, "max_binlog_size", + &max_binlog_size, + fix_max_binlog_size); +static sys_var_long_ptr sys_max_connections(&vars, "max_connections", + &max_connections, + fix_max_connections); +static sys_var_long_ptr sys_max_connect_errors(&vars, "max_connect_errors", + &max_connect_errors); +static sys_var_thd_ulong sys_max_insert_delayed_threads(&vars, "max_insert_delayed_threads", + &SV::max_insert_delayed_threads, + check_max_delayed_threads, + fix_max_connections); +static sys_var_thd_ulong sys_max_delayed_threads(&vars, "max_delayed_threads", + &SV::max_insert_delayed_threads, + check_max_delayed_threads, + fix_max_connections); +static sys_var_thd_ulong sys_max_error_count(&vars, "max_error_count", + &SV::max_error_count); +static sys_var_thd_ulonglong sys_max_heap_table_size(&vars, "max_heap_table_size", + &SV::max_heap_table_size); +static sys_var_thd_ulong sys_pseudo_thread_id(&vars, "pseudo_thread_id", + &SV::pseudo_thread_id, + check_pseudo_thread_id, 0, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_thd_ha_rows sys_max_join_size(&vars, "max_join_size", + &SV::max_join_size, + fix_max_join_size); +static sys_var_thd_ulong sys_max_seeks_for_key(&vars, "max_seeks_for_key", + &SV::max_seeks_for_key); +static sys_var_thd_ulong sys_max_length_for_sort_data(&vars, "max_length_for_sort_data", + &SV::max_length_for_sort_data); +#ifndef TO_BE_DELETED /* Alias for max_join_size */ +static sys_var_thd_ha_rows sys_sql_max_join_size(&vars, "sql_max_join_size", + &SV::max_join_size, + fix_max_join_size); +#endif +static sys_var_long_ptr_global +sys_max_prepared_stmt_count(&vars, "max_prepared_stmt_count", + &max_prepared_stmt_count, + &LOCK_prepared_stmt_count); +static sys_var_long_ptr sys_max_relay_log_size(&vars, "max_relay_log_size", + &max_relay_log_size, + fix_max_relay_log_size); +static sys_var_thd_ulong sys_max_sort_length(&vars, "max_sort_length", + &SV::max_sort_length); +static sys_var_thd_ulong sys_max_sp_recursion_depth(&vars, "max_sp_recursion_depth", + &SV::max_sp_recursion_depth); +static sys_var_max_user_conn sys_max_user_connections(&vars, "max_user_connections"); +static sys_var_thd_ulong sys_max_tmp_tables(&vars, "max_tmp_tables", + &SV::max_tmp_tables); +static sys_var_long_ptr sys_max_write_lock_count(&vars, "max_write_lock_count", + &max_write_lock_count); +static sys_var_thd_ulong sys_min_examined_row_limit(&vars, "min_examined_row_limit", + &SV::min_examined_row_limit); +static sys_var_thd_ulong sys_multi_range_count(&vars, "multi_range_count", + &SV::multi_range_count); +static sys_var_long_ptr sys_myisam_data_pointer_size(&vars, "myisam_data_pointer_size", + &myisam_data_pointer_size); +static sys_var_thd_ulonglong sys_myisam_max_sort_file_size(&vars, "myisam_max_sort_file_size", &SV::myisam_max_sort_file_size, fix_myisam_max_sort_file_size, 1); +static sys_var_const sys_myisam_recover_options(&vars, "myisam_recover_options", + OPT_GLOBAL, SHOW_CHAR_PTR, + (uchar*) + &myisam_recover_options_str); +static sys_var_thd_ulong sys_myisam_repair_threads(&vars, "myisam_repair_threads", &SV::myisam_repair_threads); +static sys_var_thd_ulong sys_myisam_sort_buffer_size(&vars, "myisam_sort_buffer_size", &SV::myisam_sort_buff_size); +static sys_var_bool_ptr sys_myisam_use_mmap(&vars, "myisam_use_mmap", + &opt_myisam_use_mmap); + +static sys_var_thd_enum sys_myisam_stats_method(&vars, "myisam_stats_method", + &SV::myisam_stats_method, + &myisam_stats_method_typelib, + NULL); + +#ifdef __NT__ +/* purecov: begin inspected */ +static sys_var_const sys_named_pipe(&vars, "named_pipe", + OPT_GLOBAL, SHOW_MY_BOOL, + (uchar*) &opt_enable_named_pipe); +/* purecov: end */ +#endif +static sys_var_thd_ulong_session_readonly sys_net_buffer_length(&vars, "net_buffer_length", + &SV::net_buffer_length); +static sys_var_thd_ulong sys_net_read_timeout(&vars, "net_read_timeout", + &SV::net_read_timeout, + 0, fix_net_read_timeout); +static sys_var_thd_ulong sys_net_write_timeout(&vars, "net_write_timeout", + &SV::net_write_timeout, + 0, fix_net_write_timeout); +static sys_var_thd_ulong sys_net_retry_count(&vars, "net_retry_count", + &SV::net_retry_count, + 0, fix_net_retry_count); +static sys_var_thd_bool sys_new_mode(&vars, "new", &SV::new_mode); +static sys_var_bool_ptr_readonly sys_old_mode(&vars, "old", + &global_system_variables.old_mode); +/* these two cannot be static */ +sys_var_thd_bool sys_old_alter_table(&vars, "old_alter_table", + &SV::old_alter_table); +sys_var_thd_bool sys_old_passwords(&vars, "old_passwords", &SV::old_passwords); +static sys_var_const sys_open_files_limit(&vars, "open_files_limit", + OPT_GLOBAL, SHOW_LONG, + (uchar*) + &open_files_limit); +static sys_var_thd_ulong sys_optimizer_prune_level(&vars, "optimizer_prune_level", + &SV::optimizer_prune_level); +static sys_var_thd_ulong sys_optimizer_search_depth(&vars, "optimizer_search_depth", + &SV::optimizer_search_depth); +static sys_var_thd_optimizer_switch sys_optimizer_switch(&vars, "optimizer_switch", + &SV::optimizer_switch); +static sys_var_const sys_pid_file(&vars, "pid_file", + OPT_GLOBAL, SHOW_CHAR, + (uchar*) pidfile_name); +static sys_var_const_os sys_plugin_dir(&vars, "plugin_dir", + OPT_GLOBAL, SHOW_CHAR, + (uchar*) opt_plugin_dir); +static sys_var_const sys_port(&vars, "port", + OPT_GLOBAL, SHOW_INT, + (uchar*) &mysqld_port); +static sys_var_thd_ulong sys_preload_buff_size(&vars, "preload_buffer_size", + &SV::preload_buff_size); +static sys_var_const sys_protocol_version(&vars, "protocol_version", + OPT_GLOBAL, SHOW_INT, + (uchar*) + &protocol_version); +static sys_var_thd_ulong sys_read_buff_size(&vars, "read_buffer_size", + &SV::read_buff_size); +static sys_var_opt_readonly sys_readonly(&vars, "read_only", &opt_readonly); +static sys_var_thd_ulong sys_read_rnd_buff_size(&vars, "read_rnd_buffer_size", + &SV::read_rnd_buff_size); +/* InfiniDB */ +static sys_var_thd_ulong sys_infinidb_vtable_mode(&vars, "infinidb_vtable_mode", + &SV::infinidb_vtable_mode); +static sys_var_thd_ulong sys_infinidb_decimal_scale(&vars, "infinidb_decimal_scale", + &SV::infinidb_decimal_scale); +static sys_var_thd_bool sys_infinidb_use_decimal_scale(&vars, "infinidb_use_decimal_scale", + &SV::infinidb_use_decimal_scale); +static sys_var_thd_bool sys_infinidb_ordered_only(&vars, "infinidb_ordered_only", + &SV::infinidb_ordered_only); +static sys_var_thd_ulong sys_infinidb_string_scan_threshold(&vars, + "infinidb_string_scan_threshold", + &SV::infinidb_string_scan_threshold); +static sys_var_thd_ulong sys_infinidb_compression_type(&vars, "infinidb_compression_type", + &SV::infinidb_compression_type); +static sys_var_thd_bool sys_infinidb_varbin_always_hex(&vars, "infinidb_varbin_always_hex", + &SV::infinidb_varbin_always_hex); +/* InfiniDB */ +static sys_var_thd_ulong sys_div_precincrement(&vars, "div_precision_increment", + &SV::div_precincrement); +static sys_var_long_ptr sys_rpl_recovery_rank(&vars, "rpl_recovery_rank", + &rpl_recovery_rank); +static sys_var_long_ptr sys_query_cache_size(&vars, "query_cache_size", + &query_cache_size, + fix_query_cache_size); + +static sys_var_thd_ulong sys_range_alloc_block_size(&vars, "range_alloc_block_size", + &SV::range_alloc_block_size); +static sys_var_thd_ulong sys_query_alloc_block_size(&vars, "query_alloc_block_size", + &SV::query_alloc_block_size, + 0, fix_thd_mem_root); +static sys_var_thd_ulong sys_query_prealloc_size(&vars, "query_prealloc_size", + &SV::query_prealloc_size, + 0, fix_thd_mem_root); +#ifdef HAVE_SMEM +/* purecov: begin tested */ +static sys_var_const sys_shared_memory(&vars, "shared_memory", + OPT_GLOBAL, SHOW_MY_BOOL, + (uchar*) + &opt_enable_shared_memory); +static sys_var_const sys_shared_memory_base_name(&vars, + "shared_memory_base_name", + OPT_GLOBAL, SHOW_CHAR_PTR, + (uchar*) + &shared_memory_base_name); +/* purecov: end */ +#endif +static sys_var_const sys_skip_external_locking(&vars, + "skip_external_locking", + OPT_GLOBAL, SHOW_MY_BOOL, + (uchar*) + &my_disable_locking); +static sys_var_const sys_skip_networking(&vars, "skip_networking", + OPT_GLOBAL, SHOW_BOOL, + (uchar*) &opt_disable_networking); +static sys_var_const sys_skip_show_database(&vars, "skip_show_database", + OPT_GLOBAL, SHOW_BOOL, + (uchar*) &opt_skip_show_db); +#ifdef HAVE_SYS_UN_H +static sys_var_const sys_socket(&vars, "socket", + OPT_GLOBAL, SHOW_CHAR_PTR, + (uchar*) &mysqld_unix_port); +#endif +#ifdef HAVE_THR_SETCONCURRENCY +/* purecov: begin tested */ +static sys_var_const sys_thread_concurrency(&vars, "thread_concurrency", + OPT_GLOBAL, SHOW_LONG, + (uchar*) &concurrency); +/* purecov: end */ +#endif +static sys_var_const sys_thread_stack(&vars, "thread_stack", + OPT_GLOBAL, SHOW_LONG, + (uchar*) &my_thread_stack_size); +static sys_var_readonly_os sys_tmpdir(&vars, "tmpdir", OPT_GLOBAL, SHOW_CHAR, get_tmpdir); +static sys_var_thd_ulong sys_trans_alloc_block_size(&vars, "transaction_alloc_block_size", + &SV::trans_alloc_block_size, + 0, fix_trans_mem_root); +static sys_var_thd_ulong sys_trans_prealloc_size(&vars, "transaction_prealloc_size", + &SV::trans_prealloc_size, + 0, fix_trans_mem_root); +sys_var_enum_const sys_thread_handling(&vars, "thread_handling", + &SV::thread_handling, + &thread_handling_typelib, + NULL); + +#ifdef HAVE_QUERY_CACHE +static sys_var_long_ptr sys_query_cache_limit(&vars, "query_cache_limit", + &query_cache.query_cache_limit); +static sys_var_long_ptr sys_query_cache_min_res_unit(&vars, "query_cache_min_res_unit", + &query_cache_min_res_unit, + fix_query_cache_min_res_unit); +static sys_var_thd_enum sys_query_cache_type(&vars, "query_cache_type", + &SV::query_cache_type, + &query_cache_type_typelib); +static sys_var_thd_bool +sys_query_cache_wlock_invalidate(&vars, "query_cache_wlock_invalidate", + &SV::query_cache_wlock_invalidate); +#endif /* HAVE_QUERY_CACHE */ +static sys_var_bool_ptr sys_secure_auth(&vars, "secure_auth", &opt_secure_auth); +static sys_var_const_str_ptr sys_secure_file_priv(&vars, "secure_file_priv", + &opt_secure_file_priv); +static sys_var_long_ptr sys_server_id(&vars, "server_id", &server_id, fix_server_id); +static sys_var_bool_ptr sys_slave_compressed_protocol(&vars, "slave_compressed_protocol", + &opt_slave_compressed_protocol); +static sys_var_set_slave_mode slave_exec_mode(&vars, + "slave_exec_mode", + &slave_exec_mode_options, + &slave_exec_mode_typelib, + 0); +static sys_var_long_ptr sys_slow_launch_time(&vars, "slow_launch_time", + &slow_launch_time); +static sys_var_thd_ulong sys_sort_buffer(&vars, "sort_buffer_size", + &SV::sortbuff_size); +/* + sql_mode should *not* have binlog_mode=SESSION_VARIABLE_IN_BINLOG: + even though it is written to the binlog, the slave ignores the + MODE_NO_DIR_IN_CREATE variable, so slave's value differs from + master's (see log_event.cc: Query_log_event::do_apply_event()). +*/ +static sys_var_thd_sql_mode sys_sql_mode(&vars, "sql_mode", + &SV::sql_mode); +#ifdef HAVE_OPENSSL +extern char *opt_ssl_ca, *opt_ssl_capath, *opt_ssl_cert, *opt_ssl_cipher, + *opt_ssl_key; +static sys_var_const_os_str_ptr sys_ssl_ca(&vars, "ssl_ca", &opt_ssl_ca); +static sys_var_const_os_str_ptr sys_ssl_capath(&vars, "ssl_capath", &opt_ssl_capath); +static sys_var_const_os_str_ptr sys_ssl_cert(&vars, "ssl_cert", &opt_ssl_cert); +static sys_var_const_os_str_ptr sys_ssl_cipher(&vars, "ssl_cipher", &opt_ssl_cipher); +static sys_var_const_os_str_ptr sys_ssl_key(&vars, "ssl_key", &opt_ssl_key); +#else +static sys_var_const_os_str sys_ssl_ca(&vars, "ssl_ca", NULL); +static sys_var_const_os_str sys_ssl_capath(&vars, "ssl_capath", NULL); +static sys_var_const_os_str sys_ssl_cert(&vars, "ssl_cert", NULL); +static sys_var_const_os_str sys_ssl_cipher(&vars, "ssl_cipher", NULL); +static sys_var_const_os_str sys_ssl_key(&vars, "ssl_key", NULL); +#endif +static sys_var_thd_enum +sys_updatable_views_with_limit(&vars, "updatable_views_with_limit", + &SV::updatable_views_with_limit, + &updatable_views_with_limit_typelib); + +static sys_var_thd_table_type sys_table_type(&vars, "table_type", + &SV::table_plugin); +static sys_var_thd_storage_engine sys_storage_engine(&vars, "storage_engine", + &SV::table_plugin); +static sys_var_bool_ptr sys_sync_frm(&vars, "sync_frm", &opt_sync_frm); +static sys_var_const_str sys_system_time_zone(&vars, "system_time_zone", + system_time_zone); +static sys_var_long_ptr sys_table_def_size(&vars, "table_definition_cache", + &table_def_size); +static sys_var_long_ptr sys_table_cache_size(&vars, "table_open_cache", + &table_cache_size); +static sys_var_long_ptr sys_table_lock_wait_timeout(&vars, "table_lock_wait_timeout", + &table_lock_wait_timeout); +static sys_var_long_ptr sys_thread_cache_size(&vars, "thread_cache_size", + &thread_cache_size); +#if HAVE_POOL_OF_THREADS == 1 +sys_var_long_ptr sys_thread_pool_size(&vars, "thread_pool_size", + &thread_pool_size); +#endif +static sys_var_thd_enum sys_tx_isolation(&vars, "tx_isolation", + &SV::tx_isolation, + &tx_isolation_typelib, + fix_tx_isolation, + check_tx_isolation); +static sys_var_thd_ulonglong sys_tmp_table_size(&vars, "tmp_table_size", + &SV::tmp_table_size); +static sys_var_bool_ptr sys_timed_mutexes(&vars, "timed_mutexes", + &timed_mutexes); +static sys_var_const_str sys_version(&vars, "version", server_version); +static sys_var_const_str sys_version_comment(&vars, "version_comment", + MYSQL_COMPILATION_COMMENT); +static sys_var_const_str sys_version_compile_machine(&vars, "version_compile_machine", + MACHINE_TYPE); +static sys_var_const_str sys_version_compile_os(&vars, "version_compile_os", + SYSTEM_TYPE); +static sys_var_thd_ulong sys_net_wait_timeout(&vars, "wait_timeout", + &SV::net_wait_timeout); + +/* Condition pushdown to storage engine */ +static sys_var_thd_bool +sys_engine_condition_pushdown(&vars, "engine_condition_pushdown", + &SV::engine_condition_pushdown); + +#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE +/* ndb thread specific variable settings */ +static sys_var_thd_ulong +sys_ndb_autoincrement_prefetch_sz(&vars, "ndb_autoincrement_prefetch_sz", + &SV::ndb_autoincrement_prefetch_sz); +static sys_var_thd_bool +sys_ndb_force_send(&vars, "ndb_force_send", &SV::ndb_force_send); +#ifdef HAVE_NDB_BINLOG +static sys_var_long_ptr +sys_ndb_report_thresh_binlog_epoch_slip(&vars, "ndb_report_thresh_binlog_epoch_slip", + &ndb_report_thresh_binlog_epoch_slip); +static sys_var_long_ptr +sys_ndb_report_thresh_binlog_mem_usage(&vars, "ndb_report_thresh_binlog_mem_usage", + &ndb_report_thresh_binlog_mem_usage); +#endif +static sys_var_thd_bool +sys_ndb_use_exact_count(&vars, "ndb_use_exact_count", &SV::ndb_use_exact_count); +static sys_var_thd_bool +sys_ndb_use_transactions(&vars, "ndb_use_transactions", &SV::ndb_use_transactions); +static sys_var_long_ptr +sys_ndb_cache_check_time(&vars, "ndb_cache_check_time", &ndb_cache_check_time); +static sys_var_const_str +sys_ndb_connectstring(&vars, "ndb_connectstring", opt_ndb_constrbuf); +static sys_var_thd_bool +sys_ndb_index_stat_enable(&vars, "ndb_index_stat_enable", + &SV::ndb_index_stat_enable); +static sys_var_thd_ulong +sys_ndb_index_stat_cache_entries(&vars, "ndb_index_stat_cache_entries", + &SV::ndb_index_stat_cache_entries); +static sys_var_thd_ulong +sys_ndb_index_stat_update_freq(&vars, "ndb_index_stat_update_freq", + &SV::ndb_index_stat_update_freq); +static sys_var_long_ptr +sys_ndb_extra_logging(&vars, "ndb_extra_logging", &ndb_extra_logging); +static sys_var_thd_bool +sys_ndb_use_copying_alter_table(&vars, "ndb_use_copying_alter_table", &SV::ndb_use_copying_alter_table); +#endif //WITH_NDBCLUSTER_STORAGE_ENGINE + +/* Time/date/datetime formats */ + +static sys_var_thd_date_time_format sys_time_format(&vars, "time_format", + &SV::time_format, + MYSQL_TIMESTAMP_TIME); +static sys_var_thd_date_time_format sys_date_format(&vars, "date_format", + &SV::date_format, + MYSQL_TIMESTAMP_DATE); +static sys_var_thd_date_time_format sys_datetime_format(&vars, "datetime_format", + &SV::datetime_format, + MYSQL_TIMESTAMP_DATETIME); + +/* Variables that are bits in THD */ + +sys_var_thd_bit sys_autocommit(&vars, "autocommit", 0, + set_option_autocommit, + OPTION_NOT_AUTOCOMMIT, + 1); +static sys_var_thd_bit sys_big_tables(&vars, "big_tables", 0, + set_option_bit, + OPTION_BIG_TABLES); +#ifndef TO_BE_DELETED /* Alias for big_tables */ +static sys_var_thd_bit sys_sql_big_tables(&vars, "sql_big_tables", 0, + set_option_bit, + OPTION_BIG_TABLES); +#endif +static sys_var_thd_bit sys_big_selects(&vars, "sql_big_selects", 0, + set_option_bit, + OPTION_BIG_SELECTS); +static sys_var_thd_bit sys_log_off(&vars, "sql_log_off", + check_log_update, + set_option_bit, + OPTION_LOG_OFF); +static sys_var_thd_bit sys_log_update(&vars, "sql_log_update", + check_log_update, + set_log_update, + OPTION_BIN_LOG); +static sys_var_thd_bit sys_log_binlog(&vars, "sql_log_bin", + check_log_update, + set_option_log_bin_bit, + OPTION_BIN_LOG); +static sys_var_thd_bit sys_sql_warnings(&vars, "sql_warnings", 0, + set_option_bit, + OPTION_WARNINGS); +static sys_var_thd_bit sys_sql_notes(&vars, "sql_notes", 0, + set_option_bit, + OPTION_SQL_NOTES); +static sys_var_thd_bit sys_auto_is_null(&vars, "sql_auto_is_null", 0, + set_option_bit, + OPTION_AUTO_IS_NULL, 0, + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_thd_bit sys_safe_updates(&vars, "sql_safe_updates", 0, + set_option_bit, + OPTION_SAFE_UPDATES); +static sys_var_thd_bit sys_buffer_results(&vars, "sql_buffer_result", 0, + set_option_bit, + OPTION_BUFFER_RESULT); +static sys_var_thd_bit sys_quote_show_create(&vars, "sql_quote_show_create", 0, + set_option_bit, + OPTION_QUOTE_SHOW_CREATE); +static sys_var_thd_bit sys_foreign_key_checks(&vars, "foreign_key_checks", 0, + set_option_bit, + OPTION_NO_FOREIGN_KEY_CHECKS, + 1, sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_thd_bit sys_unique_checks(&vars, "unique_checks", 0, + set_option_bit, + OPTION_RELAXED_UNIQUE_CHECKS, + 1, + sys_var::SESSION_VARIABLE_IN_BINLOG); +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) +static sys_var_thd_bit sys_profiling(&vars, "profiling", NULL, + set_option_bit, + ulonglong(OPTION_PROFILING)); +static sys_var_thd_ulong sys_profiling_history_size(&vars, "profiling_history_size", + &SV::profiling_history_size); +#endif + +/* Local state variables */ + +static sys_var_thd_ha_rows sys_select_limit(&vars, "sql_select_limit", + &SV::select_limit); +static sys_var_timestamp sys_timestamp(&vars, "timestamp", + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_last_insert_id +sys_last_insert_id(&vars, "last_insert_id", + sys_var::SESSION_VARIABLE_IN_BINLOG); +/* + identity is an alias for last_insert_id(), so that we are compatible + with Sybase +*/ +static sys_var_last_insert_id +sys_identity(&vars, "identity", sys_var::SESSION_VARIABLE_IN_BINLOG); + +static sys_var_thd_lc_time_names +sys_lc_time_names(&vars, "lc_time_names", sys_var::SESSION_VARIABLE_IN_BINLOG); + +/* + insert_id should *not* be marked as written to the binlog (i.e., it + should *not* have binlog_status==SESSION_VARIABLE_IN_BINLOG), + because we want any statement that refers to insert_id explicitly to + be unsafe. (By "explicitly", we mean using @@session.insert_id, + whereas insert_id is used "implicitly" when NULL value is inserted + into an auto_increment column). + + We want statements referring explicitly to @@session.insert_id to be + unsafe, because insert_id is modified internally by the slave sql + thread when NULL values are inserted in an AUTO_INCREMENT column. + This modification interfers with the value of the + @@session.insert_id variable if @@session.insert_id is referred + explicitly by an insert statement (as is seen by executing "SET + @@session.insert_id=0; CREATE TABLE t (a INT, b INT KEY + AUTO_INCREMENT); INSERT INTO t(a) VALUES (@@session.insert_id);" in + statement-based logging mode: t will be different on master and + slave). +*/ +static sys_var_insert_id sys_insert_id(&vars, "insert_id"); +static sys_var_readonly sys_error_count(&vars, "error_count", + OPT_SESSION, + SHOW_LONG, + get_error_count); +static sys_var_readonly sys_warning_count(&vars, "warning_count", + OPT_SESSION, + SHOW_LONG, + get_warning_count); + +static sys_var_rand_seed1 sys_rand_seed1(&vars, "rand_seed1", + sys_var::SESSION_VARIABLE_IN_BINLOG); +static sys_var_rand_seed2 sys_rand_seed2(&vars, "rand_seed2", + sys_var::SESSION_VARIABLE_IN_BINLOG); + +static sys_var_thd_ulong sys_default_week_format(&vars, "default_week_format", + &SV::default_week_format); + +sys_var_thd_ulong sys_group_concat_max_len(&vars, "group_concat_max_len", + &SV::group_concat_max_len); + +sys_var_thd_time_zone sys_time_zone(&vars, "time_zone", + sys_var::SESSION_VARIABLE_IN_BINLOG); + +/* Global read-only variable containing hostname */ +static sys_var_const_str sys_hostname(&vars, "hostname", glob_hostname); + +#ifndef EMBEDDED_LIBRARY +static sys_var_const_str_ptr sys_repl_report_host(&vars, "report_host", &report_host); +static sys_var_const_str_ptr sys_repl_report_user(&vars, "report_user", &report_user); +static sys_var_const_str_ptr sys_repl_report_password(&vars, "report_password", &report_password); + +static uchar *slave_get_report_port(THD *thd) +{ + thd->sys_var_tmp.long_value= report_port; + return (uchar*) &thd->sys_var_tmp.long_value; +} + +static sys_var_readonly sys_repl_report_port(&vars, "report_port", OPT_GLOBAL, SHOW_LONG, slave_get_report_port); + +#endif + +sys_var_thd_bool sys_keep_files_on_create(&vars, "keep_files_on_create", + &SV::keep_files_on_create); +/* Read only variables */ + +static sys_var_have_variable sys_have_compress(&vars, "have_compress", &have_compress); +static sys_var_have_variable sys_have_crypt(&vars, "have_crypt", &have_crypt); +static sys_var_have_plugin sys_have_csv(&vars, "have_csv", C_STRING_WITH_LEN("csv"), MYSQL_STORAGE_ENGINE_PLUGIN); +static sys_var_have_variable sys_have_dlopen(&vars, "have_dynamic_loading", &have_dlopen); +static sys_var_have_variable sys_have_geometry(&vars, "have_geometry", &have_geometry); +static sys_var_have_plugin sys_have_innodb(&vars, "have_innodb", C_STRING_WITH_LEN("innodb"), MYSQL_STORAGE_ENGINE_PLUGIN); +static sys_var_have_plugin sys_have_ndbcluster(&vars, "have_ndbcluster", C_STRING_WITH_LEN("ndbcluster"), MYSQL_STORAGE_ENGINE_PLUGIN); +static sys_var_have_variable sys_have_openssl(&vars, "have_openssl", &have_ssl); +static sys_var_have_variable sys_have_ssl(&vars, "have_ssl", &have_ssl); +static sys_var_have_plugin sys_have_partition_db(&vars, "have_partitioning", C_STRING_WITH_LEN("partition"), MYSQL_STORAGE_ENGINE_PLUGIN); +static sys_var_have_variable sys_have_query_cache(&vars, "have_query_cache", + &have_query_cache); +static sys_var_have_variable sys_have_community_features(&vars, "have_community_features", &have_community_features); +static sys_var_have_variable sys_have_rtree_keys(&vars, "have_rtree_keys", &have_rtree_keys); +static sys_var_have_variable sys_have_symlink(&vars, "have_symlink", &have_symlink); +/* Global read-only variable describing server license */ +static sys_var_const_str sys_license(&vars, "license", STRINGIFY_ARG(LICENSE)); +/* Global variables which enable|disable logging */ +static sys_var_log_state sys_var_general_log(&vars, "general_log", &opt_log, + QUERY_LOG_GENERAL); +/* Synonym of "general_log" for consistency with SHOW VARIABLES output */ +static sys_var_log_state sys_var_log(&vars, "log", &opt_log, + QUERY_LOG_GENERAL); +static sys_var_log_state sys_var_slow_query_log(&vars, "slow_query_log", &opt_slow_log, + QUERY_LOG_SLOW); +/* Synonym of "slow_query_log" for consistency with SHOW VARIABLES output */ +static sys_var_log_state sys_var_log_slow(&vars, "log_slow_queries", + &opt_slow_log, QUERY_LOG_SLOW); +sys_var_str sys_var_general_log_path(&vars, "general_log_file", sys_check_log_path, + sys_update_general_log_path, + sys_default_general_log_path, + opt_logname); +sys_var_str sys_var_slow_log_path(&vars, "slow_query_log_file", sys_check_log_path, + sys_update_slow_log_path, + sys_default_slow_log_path, + opt_slow_logname); +static sys_var_log_output sys_var_log_output_state(&vars, "log_output", &log_output_options, + &log_output_typelib, 0); + + +bool sys_var::check(THD *thd, set_var *var) +{ + var->save_result.ulonglong_value= var->value->val_int(); + return 0; +} + +bool sys_var_str::check(THD *thd, set_var *var) +{ + int res; + if (!check_func) + return 0; + + if ((res=(*check_func)(thd, var)) < 0) + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), + name, var->value->str_value.ptr()); + return res; +} + +/* + Functions to check and update variables +*/ + + +/* + Update variables 'init_connect, init_slave'. + + In case of 'DEFAULT' value + (for example: 'set GLOBAL init_connect=DEFAULT') + 'var' parameter is NULL pointer. +*/ + +bool update_sys_var_str(sys_var_str *var_str, rw_lock_t *var_mutex, + set_var *var) +{ + char *res= 0, *old_value=(char *)(var ? var->value->str_value.ptr() : 0); + uint new_length= (var ? var->value->str_value.length() : 0); + if (!old_value) + old_value= (char*) ""; + if (!(res= my_strndup(old_value, new_length, MYF(0)))) + return 1; + /* + Replace the old value in such a way that the any thread using + the value will work. + */ + rw_wrlock(var_mutex); + old_value= var_str->value; + var_str->value= res; + var_str->value_length= new_length; + var_str->is_os_charset= FALSE; + rw_unlock(var_mutex); + my_free(old_value, MYF(MY_ALLOW_ZERO_PTR)); + return 0; +} + + +static bool sys_update_init_connect(THD *thd, set_var *var) +{ + return update_sys_var_str(&sys_init_connect, &LOCK_sys_init_connect, var); +} + + +static void sys_default_init_connect(THD* thd, enum_var_type type) +{ + update_sys_var_str(&sys_init_connect, &LOCK_sys_init_connect, 0); +} + + +static bool sys_update_init_slave(THD *thd, set_var *var) +{ + return update_sys_var_str(&sys_init_slave, &LOCK_sys_init_slave, var); +} + + +static void sys_default_init_slave(THD* thd, enum_var_type type) +{ + update_sys_var_str(&sys_init_slave, &LOCK_sys_init_slave, 0); +} + +static int sys_check_ftb_syntax(THD *thd, set_var *var) +{ + if (thd->security_ctx->master_access & SUPER_ACL) + return (ft_boolean_check_syntax_string((uchar*) + var->value->str_value.c_ptr()) ? + -1 : 0); + else + { + my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER"); + return 1; + } +} + +static bool sys_update_ftb_syntax(THD *thd, set_var * var) +{ + strmake(ft_boolean_syntax, var->value->str_value.c_ptr(), + sizeof(ft_boolean_syntax)-1); + +#ifdef HAVE_QUERY_CACHE + query_cache.flush(); +#endif /* HAVE_QUERY_CACHE */ + + return 0; +} + +static void sys_default_ftb_syntax(THD *thd, enum_var_type type) +{ + strmake(ft_boolean_syntax, def_ft_boolean_syntax, + sizeof(ft_boolean_syntax)-1); +} + + +/** + If one sets the LOW_PRIORIY UPDATES flag, we also must change the + used lock type. +*/ + +static void fix_low_priority_updates(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + thr_upgraded_concurrent_insert_lock= + (global_system_variables.low_priority_updates ? + TL_WRITE_LOW_PRIORITY : TL_WRITE); + else + thd->update_lock_default= (thd->variables.low_priority_updates ? + TL_WRITE_LOW_PRIORITY : TL_WRITE); +} + + +static void +fix_myisam_max_sort_file_size(THD *thd, enum_var_type type) +{ + myisam_max_temp_length= + (my_off_t) global_system_variables.myisam_max_sort_file_size; +} + +/** + Set the OPTION_BIG_SELECTS flag if max_join_size == HA_POS_ERROR. +*/ + +static void fix_max_join_size(THD *thd, enum_var_type type) +{ + if (type != OPT_GLOBAL) + { + if (thd->variables.max_join_size == HA_POS_ERROR) + thd->options|= OPTION_BIG_SELECTS; + else + thd->options&= ~OPTION_BIG_SELECTS; + } +} + + +/** + Can't change the 'next' tx_isolation while we are already in + a transaction +*/ +static int check_tx_isolation(THD *thd, set_var *var) +{ + if (var->type == OPT_DEFAULT && (thd->server_status & SERVER_STATUS_IN_TRANS)) + { + my_error(ER_CANT_CHANGE_TX_ISOLATION, MYF(0)); + return 1; + } + return 0; +} + +/* + If one doesn't use the SESSION modifier, the isolation level + is only active for the next command. +*/ +static void fix_tx_isolation(THD *thd, enum_var_type type) +{ + if (type == OPT_SESSION) + thd->session_tx_isolation= ((enum_tx_isolation) + thd->variables.tx_isolation); +} + +static void fix_completion_type(THD *thd __attribute__((unused)), + enum_var_type type __attribute__((unused))) {} + +static int check_completion_type(THD *thd, set_var *var) +{ + longlong val= var->value->val_int(); + if (val < 0 || val > 2) + { + char buf[64]; + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), var->var->name, llstr(val, buf)); + return 1; + } + return 0; +} + + +/* + If we are changing the thread variable, we have to copy it to NET too +*/ + +#ifdef HAVE_REPLICATION +static void fix_net_read_timeout(THD *thd, enum_var_type type) +{ + if (type != OPT_GLOBAL) + my_net_set_read_timeout(&thd->net, thd->variables.net_read_timeout); +} + + +static void fix_net_write_timeout(THD *thd, enum_var_type type) +{ + if (type != OPT_GLOBAL) + my_net_set_write_timeout(&thd->net, thd->variables.net_write_timeout); +} + +static void fix_net_retry_count(THD *thd, enum_var_type type) +{ + if (type != OPT_GLOBAL) + thd->net.retry_count=thd->variables.net_retry_count; +} +#else /* HAVE_REPLICATION */ +static void fix_net_read_timeout(THD *thd __attribute__((unused)), + enum_var_type type __attribute__((unused))) +{} +static void fix_net_write_timeout(THD *thd __attribute__((unused)), + enum_var_type type __attribute__((unused))) +{} +static void fix_net_retry_count(THD *thd __attribute__((unused)), + enum_var_type type __attribute__((unused))) +{} +#endif /* HAVE_REPLICATION */ + + +static void fix_query_cache_size(THD *thd, enum_var_type type) +{ +#ifdef HAVE_QUERY_CACHE + ulong new_cache_size= query_cache.resize(query_cache_size); + + /* + Note: query_cache_size is a global variable reflecting the + requested cache size. See also query_cache_size_arg + */ + + if (query_cache_size != new_cache_size) + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_QC_RESIZE, ER(ER_WARN_QC_RESIZE), + query_cache_size, new_cache_size); + + query_cache_size= new_cache_size; +#endif +} + + +#ifdef HAVE_QUERY_CACHE +static void fix_query_cache_min_res_unit(THD *thd, enum_var_type type) +{ + query_cache_min_res_unit= + query_cache.set_min_res_unit(query_cache_min_res_unit); +} +#endif + + +extern void fix_delay_key_write(THD *thd, enum_var_type type) +{ + switch ((enum_delay_key_write) delay_key_write_options) { + case DELAY_KEY_WRITE_NONE: + myisam_delay_key_write=0; + break; + case DELAY_KEY_WRITE_ON: + myisam_delay_key_write=1; + break; + case DELAY_KEY_WRITE_ALL: + myisam_delay_key_write=1; + ha_open_options|= HA_OPEN_DELAY_KEY_WRITE; + break; + } +} + +bool sys_var_set::update(THD *thd, set_var *var) +{ + *value= var->save_result.ulong_value; + return 0; +} + +uchar *sys_var_set::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + char buff[256]; + String tmp(buff, sizeof(buff), &my_charset_latin1); + ulong length; + ulong val= *value; + + tmp.length(0); + for (uint i= 0; val; val>>= 1, i++) + { + if (val & 1) + { + tmp.append(enum_names->type_names[i], + enum_names->type_lengths[i]); + tmp.append(','); + } + } + + if ((length= tmp.length())) + length--; + return (uchar*) thd->strmake(tmp.ptr(), length); +} + +void sys_var_set_slave_mode::set_default(THD *thd, enum_var_type type) +{ + slave_exec_mode_options= 0; + bit_do_set(slave_exec_mode_options, SLAVE_EXEC_MODE_STRICT); +} + +bool sys_var_set_slave_mode::check(THD *thd, set_var *var) +{ + bool rc= sys_var_set::check(thd, var); + if (!rc && + bit_is_set(var->save_result.ulong_value, SLAVE_EXEC_MODE_STRICT) == 1 && + bit_is_set(var->save_result.ulong_value, SLAVE_EXEC_MODE_IDEMPOTENT) == 1) + { + rc= true; + my_error(ER_SLAVE_AMBIGOUS_EXEC_MODE, MYF(0), ""); + } + return rc; +} + +bool sys_var_set_slave_mode::update(THD *thd, set_var *var) +{ + bool rc; + pthread_mutex_lock(&LOCK_global_system_variables); + rc= sys_var_set::update(thd, var); + pthread_mutex_unlock(&LOCK_global_system_variables); + return rc; +} + +void fix_slave_exec_mode(enum_var_type type) +{ + DBUG_ENTER("fix_slave_exec_mode"); + compile_time_assert(sizeof(slave_exec_mode_options) * CHAR_BIT + > SLAVE_EXEC_MODE_LAST_BIT - 1); + if (bit_is_set(slave_exec_mode_options, SLAVE_EXEC_MODE_STRICT) == 1 && + bit_is_set(slave_exec_mode_options, SLAVE_EXEC_MODE_IDEMPOTENT) == 1) + { + sql_print_error("Ambiguous slave modes combination." + " STRICT will be used"); + bit_do_clear(slave_exec_mode_options, SLAVE_EXEC_MODE_IDEMPOTENT); + } + if (bit_is_set(slave_exec_mode_options, SLAVE_EXEC_MODE_IDEMPOTENT) == 0) + bit_do_set(slave_exec_mode_options, SLAVE_EXEC_MODE_STRICT); +} + + +bool sys_var_thd_binlog_format::check(THD *thd, set_var *var) { + /* + All variables that affect writing to binary log (either format or + turning logging on and off) use the same checking. We call the + superclass ::check function to assign the variable correctly, and + then check the value. + */ + bool result= sys_var_thd_enum::check(thd, var); + if (!result) + result= check_log_update(thd, var); + return result; +} + + +bool sys_var_thd_binlog_format::is_readonly() const +{ + /* + Under certain circumstances, the variable is read-only (unchangeable): + */ + THD *thd= current_thd; + /* + If RBR and open temporary tables, their CREATE TABLE may not be in the + binlog, so we can't toggle to SBR in this connection. + The test below will also prevent SET GLOBAL, well it was not easy to test + if global or not here. + And this test will also prevent switching from RBR to RBR (a no-op which + should not happen too often). + + If we don't have row-based replication compiled in, the variable + is always read-only. + */ + if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW) && + thd->temporary_tables) + { + my_error(ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR, MYF(0)); + return 1; + } + /* + if in a stored function/trigger, it's too late to change mode + */ + if (thd->in_sub_stmt) + { + my_error(ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT, MYF(0)); + return 1; + } + return sys_var_thd_enum::is_readonly(); +} + + +void fix_binlog_format_after_update(THD *thd, enum_var_type type) +{ + thd->reset_current_stmt_binlog_row_based(); +} + + +static void fix_max_binlog_size(THD *thd, enum_var_type type) +{ + DBUG_ENTER("fix_max_binlog_size"); + DBUG_PRINT("info",("max_binlog_size=%lu max_relay_log_size=%lu", + max_binlog_size, max_relay_log_size)); + mysql_bin_log.set_max_size(max_binlog_size); +#ifdef HAVE_REPLICATION + if (!max_relay_log_size) + active_mi->rli.relay_log.set_max_size(max_binlog_size); +#endif + DBUG_VOID_RETURN; +} + +static void fix_max_relay_log_size(THD *thd, enum_var_type type) +{ + DBUG_ENTER("fix_max_relay_log_size"); + DBUG_PRINT("info",("max_binlog_size=%lu max_relay_log_size=%lu", + max_binlog_size, max_relay_log_size)); +#ifdef HAVE_REPLICATION + active_mi->rli.relay_log.set_max_size(max_relay_log_size ? + max_relay_log_size: max_binlog_size); +#endif + DBUG_VOID_RETURN; +} + + +static int check_max_delayed_threads(THD *thd, set_var *var) +{ + longlong val= var->value->val_int(); + if (var->type != OPT_GLOBAL && val != 0 && + val != (longlong) global_system_variables.max_insert_delayed_threads) + { + char buf[64]; + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), var->var->name, llstr(val, buf)); + return 1; + } + return 0; +} + +static void fix_max_connections(THD *thd, enum_var_type type) +{ +#ifndef EMBEDDED_LIBRARY + resize_thr_alarm(max_connections + + global_system_variables.max_insert_delayed_threads + 10); +#endif +} + + +static void fix_thd_mem_root(THD *thd, enum_var_type type) +{ + if (type != OPT_GLOBAL) + reset_root_defaults(thd->mem_root, + thd->variables.query_alloc_block_size, + thd->variables.query_prealloc_size); +} + + +static void fix_trans_mem_root(THD *thd, enum_var_type type) +{ +#ifdef USING_TRANSACTIONS + if (type != OPT_GLOBAL) + reset_root_defaults(&thd->transaction.mem_root, + thd->variables.trans_alloc_block_size, + thd->variables.trans_prealloc_size); +#endif +} + + +static void fix_server_id(THD *thd, enum_var_type type) +{ + server_id_supplied = 1; + thd->server_id= server_id; +} + + +/** + Throw warning (error in STRICT mode) if value for variable needed bounding. + Only call from check(), not update(), because an error in update() would be + bad mojo. Plug-in interface also uses this. + + @param thd thread handle + @param fixed did we have to correct the value? (throw warn/err if so) + @param unsignd is value's type unsigned? + @param name variable's name + @param val variable's value + + @retval TRUE on error, FALSE otherwise (warning or OK) + */ +bool throw_bounds_warning(THD *thd, bool fixed, bool unsignd, + const char *name, longlong val) +{ + if (fixed) + { + char buf[22]; + + if (unsignd) + ullstr((ulonglong) val, buf); + else + llstr(val, buf); + + if (thd->variables.sql_mode & MODE_STRICT_ALL_TABLES) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, buf); + return TRUE; + } + + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE, + ER(ER_TRUNCATED_WRONG_VALUE), name, buf); + } + return FALSE; +} + + +/** + check an unsigned user-supplied value for a systemvariable against bounds. + + TODO: This is a wrapper function to call clipping from within an update() + function. Calling bounds from within update() is fair game in theory, + but we can only send warnings from in there, not errors, and besides, + it violates our model of separating check from update phase. + To avoid breaking out of the server with an ASSERT() in strict mode, + we pretend we're not in strict mode when we go through here. Bug#43233 + was opened to remind us to replace this kludge with The Right Thing, + which of course is to do the check in the actual check phase, and then + throw an error or warning accordingly. + + @param thd thread handle + @param num the value to limit + @param option_limits the bounds-record, or NULL if none + */ +static void bound_unsigned(THD *thd, ulonglong *num, + const struct my_option *option_limits) +{ + if (option_limits) + { + my_bool fixed = FALSE; + ulonglong unadjusted= *num; + + *num= getopt_ull_limit_value(unadjusted, option_limits, &fixed); + + if (fixed) + { + ulong ssm= thd->variables.sql_mode; + thd->variables.sql_mode&= ~MODE_STRICT_ALL_TABLES; + throw_bounds_warning(thd, fixed, TRUE, option_limits->name, unadjusted); + thd->variables.sql_mode= ssm; + } + } +} + + +/** + Get unsigned system-variable. + Negative value does not wrap around, but becomes zero. + Check user-supplied value for a systemvariable against bounds. + If we needed to adjust the value, throw a warning or error depending + on SQL-mode. + + @param thd thread handle + @param var the system-variable to get + @param user_max a limit given with --maximum-variable-name=... or 0 + @param var_type function will bound on systems where necessary. + + @retval TRUE on error, FALSE otherwise (warning or OK) + */ +static bool get_unsigned(THD *thd, set_var *var, ulonglong user_max, + ulong var_type) +{ + int warnings= 0; + ulonglong unadjusted; + const struct my_option *limits= var->var->option_limits; + struct my_option fallback; + + /* get_unsigned() */ + if (var->value->unsigned_flag) + var->save_result.ulonglong_value= (ulonglong) var->value->val_int(); + else + { + longlong v= var->value->val_int(); + var->save_result.ulonglong_value= (ulonglong) ((v < 0) ? 0 : v); + if (v < 0) + { + warnings++; + if (throw_bounds_warning(thd, TRUE, FALSE, var->var->name, v)) + return TRUE; /* warning was promoted to error, give up */ + } + } + + unadjusted= var->save_result.ulonglong_value; + + /* max, if any */ + + if ((user_max > 0) && (unadjusted > user_max)) + { + var->save_result.ulonglong_value= user_max; + + if ((warnings == 0) && throw_bounds_warning(thd, TRUE, TRUE, + var->var->name, + (longlong) unadjusted)) + return TRUE; + + warnings++; + } + + /* + if the sysvar doesn't have a proper bounds record but the check + function would like bounding to ULONG where its size differs from + that of ULONGLONG, we make up a bogus limits record here and let + the usual suspects handle the actual limiting. + */ + + if (!limits && var_type != GET_ULL) + { + bzero(&fallback, sizeof(fallback)); + fallback.var_type= var_type; + limits= &fallback; + } + + /* fix_unsigned() */ + if (limits) + { + my_bool fixed; + + var->save_result.ulonglong_value= getopt_ull_limit_value(var->save_result. + ulonglong_value, + limits, &fixed); + + if ((warnings == 0) && throw_bounds_warning(thd, fixed, TRUE, + var->var->name, + (longlong) unadjusted)) + return TRUE; + } + + return FALSE; +} + + +sys_var_long_ptr:: +sys_var_long_ptr(sys_var_chain *chain, const char *name_arg, ulong *value_ptr_arg, + sys_after_update_func after_update_arg) + :sys_var_long_ptr_global(chain, name_arg, value_ptr_arg, + &LOCK_global_system_variables, after_update_arg) +{} + + +bool sys_var_long_ptr_global::check(THD *thd, set_var *var) +{ + return get_unsigned(thd, var, 0, GET_ULONG); +} + +bool sys_var_long_ptr_global::update(THD *thd, set_var *var) +{ + pthread_mutex_lock(guard); + *value= (ulong) var->save_result.ulonglong_value; + pthread_mutex_unlock(guard); + return 0; +} + + +void sys_var_long_ptr_global::set_default(THD *thd, enum_var_type type) +{ + my_bool not_used; + pthread_mutex_lock(guard); + *value= (ulong) getopt_ull_limit_value((ulong) option_limits->def_value, + option_limits, ¬_used); + pthread_mutex_unlock(guard); +} + + +bool sys_var_ulonglong_ptr::update(THD *thd, set_var *var) +{ + ulonglong tmp= var->save_result.ulonglong_value; + pthread_mutex_lock(&LOCK_global_system_variables); + bound_unsigned(thd, &tmp, option_limits); + *value= (ulonglong) tmp; + pthread_mutex_unlock(&LOCK_global_system_variables); + return 0; +} + + +void sys_var_ulonglong_ptr::set_default(THD *thd, enum_var_type type) +{ + my_bool not_used; + pthread_mutex_lock(&LOCK_global_system_variables); + *value= getopt_ull_limit_value((ulonglong) option_limits->def_value, + option_limits, ¬_used); + pthread_mutex_unlock(&LOCK_global_system_variables); +} + + +bool sys_var_bool_ptr::update(THD *thd, set_var *var) +{ + *value= (my_bool) var->save_result.ulong_value; + return 0; +} + + +void sys_var_bool_ptr::set_default(THD *thd, enum_var_type type) +{ + *value= (my_bool) option_limits->def_value; +} + + +bool sys_var_enum::update(THD *thd, set_var *var) +{ + *value= (uint) var->save_result.ulong_value; + return 0; +} + + +uchar *sys_var_enum::value_ptr(THD *thd, enum_var_type type, LEX_STRING *base) +{ + return (uchar*) enum_names->type_names[*value]; +} + + +uchar *sys_var_enum_const::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + return (uchar*) enum_names->type_names[global_system_variables.*offset]; +} + +bool sys_var_thd_ulong::check(THD *thd, set_var *var) +{ + if (get_unsigned(thd, var, max_system_variables.*offset, GET_ULONG)) + return TRUE; + DBUG_ASSERT(var->save_result.ulonglong_value <= ULONG_MAX); + return ((check_func && (*check_func)(thd, var))); +} + +bool sys_var_thd_ulong::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + global_system_variables.*offset= (ulong) var->save_result.ulonglong_value; + else + thd->variables.*offset= (ulong) var->save_result.ulonglong_value; + + return 0; +} + + +void sys_var_thd_ulong::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + { + my_bool not_used; + /* We will not come here if option_limits is not set */ + global_system_variables.*offset= + (ulong) getopt_ull_limit_value((ulong) option_limits->def_value, + option_limits, ¬_used); + } + else + thd->variables.*offset= global_system_variables.*offset; +} + + +uchar *sys_var_thd_ulong::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + if (type == OPT_GLOBAL) + return (uchar*) &(global_system_variables.*offset); + return (uchar*) &(thd->variables.*offset); +} + + +bool sys_var_thd_ha_rows::update(THD *thd, set_var *var) +{ + ulonglong tmp= var->save_result.ulonglong_value; + + /* Don't use bigger value than given with --maximum-variable-name=.. */ + if ((ha_rows) tmp > max_system_variables.*offset) + tmp= max_system_variables.*offset; + + bound_unsigned(thd, &tmp, option_limits); + + if (var->type == OPT_GLOBAL) + { + /* Lock is needed to make things safe on 32 bit systems */ + pthread_mutex_lock(&LOCK_global_system_variables); + global_system_variables.*offset= (ha_rows) tmp; + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.*offset= (ha_rows) tmp; + return 0; +} + + +void sys_var_thd_ha_rows::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + { + my_bool not_used; + /* We will not come here if option_limits is not set */ + pthread_mutex_lock(&LOCK_global_system_variables); + global_system_variables.*offset= + (ha_rows) getopt_ull_limit_value((ha_rows) option_limits->def_value, + option_limits, ¬_used); + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.*offset= global_system_variables.*offset; +} + + +uchar *sys_var_thd_ha_rows::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + if (type == OPT_GLOBAL) + return (uchar*) &(global_system_variables.*offset); + return (uchar*) &(thd->variables.*offset); +} + +bool sys_var_thd_ulonglong::check(THD *thd, set_var *var) +{ + return get_unsigned(thd, var, max_system_variables.*offset, GET_ULL); +} + +bool sys_var_thd_ulonglong::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + { + /* Lock is needed to make things safe on 32 bit systems */ + pthread_mutex_lock(&LOCK_global_system_variables); + global_system_variables.*offset= (ulonglong) + var->save_result.ulonglong_value; + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.*offset= (ulonglong) var->save_result.ulonglong_value; + return 0; +} + + +void sys_var_thd_ulonglong::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + { + my_bool not_used; + pthread_mutex_lock(&LOCK_global_system_variables); + global_system_variables.*offset= + getopt_ull_limit_value((ulonglong) option_limits->def_value, + option_limits, ¬_used); + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.*offset= global_system_variables.*offset; +} + + +uchar *sys_var_thd_ulonglong::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + if (type == OPT_GLOBAL) + return (uchar*) &(global_system_variables.*offset); + return (uchar*) &(thd->variables.*offset); +} + + +bool sys_var_thd_bool::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + global_system_variables.*offset= (my_bool) var->save_result.ulong_value; + else + thd->variables.*offset= (my_bool) var->save_result.ulong_value; + return 0; +} + + +void sys_var_thd_bool::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.*offset= (my_bool) option_limits->def_value; + else + thd->variables.*offset= global_system_variables.*offset; +} + + +uchar *sys_var_thd_bool::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + if (type == OPT_GLOBAL) + return (uchar*) &(global_system_variables.*offset); + return (uchar*) &(thd->variables.*offset); +} + + +bool sys_var::check_enum(THD *thd, set_var *var, const TYPELIB *enum_names) +{ + char buff[STRING_BUFFER_USUAL_SIZE]; + const char *value; + String str(buff, sizeof(buff), system_charset_info), *res; + + if (var->value->result_type() == STRING_RESULT) + { + if (!(res=var->value->val_str(&str)) || + ((long) (var->save_result.ulong_value= + (ulong) find_type(enum_names, res->ptr(), + res->length(),1)-1)) < 0) + { + value= res ? res->c_ptr() : "NULL"; + goto err; + } + } + else + { + ulonglong tmp=var->value->val_int(); + if (tmp >= enum_names->count) + { + llstr(tmp,buff); + value=buff; // Wrong value is here + goto err; + } + var->save_result.ulong_value= (ulong) tmp; // Save for update + } + return 0; + +err: + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, value); + return 1; +} + + +bool sys_var::check_set(THD *thd, set_var *var, TYPELIB *enum_names) +{ + bool not_used; + char buff[STRING_BUFFER_USUAL_SIZE], *error= 0; + uint error_len= 0; + String str(buff, sizeof(buff), system_charset_info), *res; + + if (var->value->result_type() == STRING_RESULT) + { + if (!(res= var->value->val_str(&str))) + { + strmov(buff, "NULL"); + goto err; + } + + if (!m_allow_empty_value && + res->length() == 0) + { + buff[0]= 0; + goto err; + } + + var->save_result.ulong_value= ((ulong) + find_set(enum_names, res->c_ptr(), + res->length(), + NULL, + &error, &error_len, + ¬_used)); + if (error_len) + { + strmake(buff, error, min(sizeof(buff) - 1, error_len)); + goto err; + } + } + else + { + ulonglong tmp= var->value->val_int(); + + if (!m_allow_empty_value && + tmp == 0) + { + buff[0]= '0'; + buff[1]= 0; + goto err; + } + + /* + For when the enum is made to contain 64 elements, as 1ULL<<64 is + undefined, we guard with a "count<64" test. + */ + if (unlikely((tmp >= ((ULL(1)) << enum_names->count)) && + (enum_names->count < 64))) + { + llstr(tmp, buff); + goto err; + } + var->save_result.ulong_value= (ulong) tmp; // Save for update + } + return 0; + +err: + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, buff); + return 1; +} + + +CHARSET_INFO *sys_var::charset(THD *thd) +{ + return is_os_charset ? thd->variables.character_set_filesystem : + system_charset_info; +} + + +bool sys_var_thd_enum::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + global_system_variables.*offset= var->save_result.ulong_value; + else + thd->variables.*offset= var->save_result.ulong_value; + return 0; +} + + +void sys_var_thd_enum::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.*offset= (ulong) option_limits->def_value; + else + thd->variables.*offset= global_system_variables.*offset; +} + + +uchar *sys_var_thd_enum::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + ulong tmp= ((type == OPT_GLOBAL) ? + global_system_variables.*offset : + thd->variables.*offset); + return (uchar*) enum_names->type_names[tmp]; +} + +bool sys_var_thd_bit::check(THD *thd, set_var *var) +{ + return (check_enum(thd, var, &bool_typelib) || + (check_func && (*check_func)(thd, var))); +} + +bool sys_var_thd_bit::update(THD *thd, set_var *var) +{ + int res= (*update_func)(thd, var); + return res; +} + + +uchar *sys_var_thd_bit::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + /* + If reverse is 0 (default) return 1 if bit is set. + If reverse is 1, return 0 if bit is set + */ + thd->sys_var_tmp.my_bool_value= ((thd->options & bit_flag) ? + !reverse : reverse); + return (uchar*) &thd->sys_var_tmp.my_bool_value; +} + + +/** Update a date_time format variable based on given value. */ + +void sys_var_thd_date_time_format::update2(THD *thd, enum_var_type type, + DATE_TIME_FORMAT *new_value) +{ + DATE_TIME_FORMAT *old; + DBUG_ENTER("sys_var_date_time_format::update2"); + DBUG_DUMP("positions", (uchar*) new_value->positions, + sizeof(new_value->positions)); + + if (type == OPT_GLOBAL) + { + pthread_mutex_lock(&LOCK_global_system_variables); + old= (global_system_variables.*offset); + (global_system_variables.*offset)= new_value; + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + { + old= (thd->variables.*offset); + (thd->variables.*offset)= new_value; + } + my_free((char*) old, MYF(MY_ALLOW_ZERO_PTR)); + DBUG_VOID_RETURN; +} + + +bool sys_var_thd_date_time_format::update(THD *thd, set_var *var) +{ + DATE_TIME_FORMAT *new_value; + /* We must make a copy of the last value to get it into normal memory */ + new_value= date_time_format_copy((THD*) 0, + var->save_result.date_time_format); + if (!new_value) + return 1; // Out of memory + update2(thd, var->type, new_value); // Can't fail + return 0; +} + + +bool sys_var_thd_date_time_format::check(THD *thd, set_var *var) +{ + char buff[STRING_BUFFER_USUAL_SIZE]; + String str(buff,sizeof(buff), system_charset_info), *res; + DATE_TIME_FORMAT *format; + + if (!(res=var->value->val_str(&str))) + res= &my_empty_string; + + if (!(format= date_time_format_make(date_time_type, + res->ptr(), res->length()))) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, res->c_ptr()); + return 1; + } + + /* + We must copy result to thread space to not get a memory leak if + update is aborted + */ + var->save_result.date_time_format= date_time_format_copy(thd, format); + my_free((char*) format, MYF(0)); + return var->save_result.date_time_format == 0; +} + + +void sys_var_thd_date_time_format::set_default(THD *thd, enum_var_type type) +{ + DATE_TIME_FORMAT *res= 0; + + if (type == OPT_GLOBAL) + { + const char *format; + if ((format= opt_date_time_formats[date_time_type])) + res= date_time_format_make(date_time_type, format, strlen(format)); + } + else + { + /* Make copy with malloc */ + res= date_time_format_copy((THD *) 0, global_system_variables.*offset); + } + + if (res) // Should always be true + update2(thd, type, res); +} + + +uchar *sys_var_thd_date_time_format::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + if (type == OPT_GLOBAL) + { + char *res; + /* + We do a copy here just to be sure things will work even if someone + is modifying the original string while the copy is accessed + (Can't happen now in SQL SHOW, but this is a good safety for the future) + */ + res= thd->strmake((global_system_variables.*offset)->format.str, + (global_system_variables.*offset)->format.length); + return (uchar*) res; + } + return (uchar*) (thd->variables.*offset)->format.str; +} + + +typedef struct old_names_map_st +{ + const char *old_name; + const char *new_name; +} my_old_conv; + +static my_old_conv old_conv[]= +{ + { "cp1251_koi8" , "cp1251" }, + { "cp1250_latin2" , "cp1250" }, + { "kam_latin2" , "keybcs2" }, + { "mac_latin2" , "MacRoman" }, + { "macce_latin2" , "MacCE" }, + { "pc2_latin2" , "pclatin2" }, + { "vga_latin2" , "pclatin1" }, + { "koi8_cp1251" , "koi8r" }, + { "win1251ukr_koi8_ukr" , "win1251ukr" }, + { "koi8_ukr_win1251ukr" , "koi8u" }, + { NULL , NULL } +}; + +CHARSET_INFO *get_old_charset_by_name(const char *name) +{ + my_old_conv *conv; + + for (conv= old_conv; conv->old_name; conv++) + { + if (!my_strcasecmp(&my_charset_latin1, name, conv->old_name)) + return get_charset_by_csname(conv->new_name, MY_CS_PRIMARY, MYF(0)); + } + return NULL; +} + + +bool sys_var_collation::check(THD *thd, set_var *var) +{ + CHARSET_INFO *tmp; + LINT_INIT(tmp); + + if (var->value->result_type() == STRING_RESULT) + { + char buff[STRING_BUFFER_USUAL_SIZE]; + String str(buff,sizeof(buff), system_charset_info), *res; + if (!(res=var->value->val_str(&str))) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, "NULL"); + return 1; + } + if (!(tmp=get_charset_by_name(res->c_ptr(),MYF(0)))) + { + my_error(ER_UNKNOWN_COLLATION, MYF(0), res->c_ptr()); + return 1; + } + } + else // INT_RESULT + { + if (!(tmp=get_charset((int) var->value->val_int(),MYF(0)))) + { + char buf[20]; + int10_to_str((int) var->value->val_int(), buf, -10); + my_error(ER_UNKNOWN_COLLATION, MYF(0), buf); + return 1; + } + } + var->save_result.charset= tmp; // Save for update + return 0; +} + + +bool sys_var_character_set::check(THD *thd, set_var *var) +{ + CHARSET_INFO *tmp; + LINT_INIT(tmp); + + if (var->value->result_type() == STRING_RESULT) + { + char buff[STRING_BUFFER_USUAL_SIZE]; + String str(buff,sizeof(buff), system_charset_info), *res; + if (!(res=var->value->val_str(&str))) + { + if (!nullable) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, "NULL"); + return 1; + } + tmp= NULL; + } + else if (!(tmp=get_charset_by_csname(res->c_ptr(),MY_CS_PRIMARY,MYF(0))) && + !(tmp=get_old_charset_by_name(res->c_ptr()))) + { + my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), res->c_ptr()); + return 1; + } + } + else // INT_RESULT + { + if (!(tmp=get_charset((int) var->value->val_int(),MYF(0)))) + { + char buf[20]; + int10_to_str((int) var->value->val_int(), buf, -10); + my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), buf); + return 1; + } + } + var->save_result.charset= tmp; // Save for update + return 0; +} + + +bool sys_var_character_set::update(THD *thd, set_var *var) +{ + ci_ptr(thd,var->type)[0]= var->save_result.charset; + thd->update_charset(); + return 0; +} + + +uchar *sys_var_character_set::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + CHARSET_INFO *cs= ci_ptr(thd,type)[0]; + return cs ? (uchar*) cs->csname : (uchar*) NULL; +} + + +void sys_var_character_set_sv::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.*offset= *global_default; + else + { + thd->variables.*offset= global_system_variables.*offset; + thd->update_charset(); + } +} +CHARSET_INFO **sys_var_character_set_sv::ci_ptr(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + return &(global_system_variables.*offset); + else + return &(thd->variables.*offset); +} + + +bool sys_var_character_set_client::check(THD *thd, set_var *var) +{ + if (sys_var_character_set_sv::check(thd, var)) + return 1; + /* Currently, UCS-2 cannot be used as a client character set */ + if (var->save_result.charset->mbminlen > 1) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, + var->save_result.charset->csname); + return 1; + } + return 0; +} + + +CHARSET_INFO ** sys_var_character_set_database::ci_ptr(THD *thd, + enum_var_type type) +{ + if (type == OPT_GLOBAL) + return &global_system_variables.collation_database; + else + return &thd->variables.collation_database; +} + + +void sys_var_character_set_database::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.collation_database= default_charset_info; + else + { + thd->variables.collation_database= thd->db_charset; + thd->update_charset(); + } +} + + +bool sys_var_collation_sv::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + global_system_variables.*offset= var->save_result.charset; + else + { + thd->variables.*offset= var->save_result.charset; + thd->update_charset(); + } + return 0; +} + + +void sys_var_collation_sv::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.*offset= *global_default; + else + { + thd->variables.*offset= global_system_variables.*offset; + thd->update_charset(); + } +} + + +uchar *sys_var_collation_sv::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + CHARSET_INFO *cs= ((type == OPT_GLOBAL) ? + global_system_variables.*offset : thd->variables.*offset); + return cs ? (uchar*) cs->name : (uchar*) "NULL"; +} + + +LEX_STRING default_key_cache_base= {(char *) "default", 7 }; + +static KEY_CACHE zero_key_cache; + +KEY_CACHE *get_key_cache(LEX_STRING *cache_name) +{ + safe_mutex_assert_owner(&LOCK_global_system_variables); + if (!cache_name || ! cache_name->length) + cache_name= &default_key_cache_base; + return ((KEY_CACHE*) find_named(&key_caches, + cache_name->str, cache_name->length, 0)); +} + + +uchar *sys_var_key_cache_param::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + KEY_CACHE *key_cache= get_key_cache(base); + if (!key_cache) + key_cache= &zero_key_cache; + return (uchar*) key_cache + offset ; +} + + +bool sys_var_key_buffer_size::update(THD *thd, set_var *var) +{ + ulonglong tmp= var->save_result.ulonglong_value; + LEX_STRING *base_name= &var->base; + KEY_CACHE *key_cache; + bool error= 0; + + /* If no basename, assume it's for the key cache named 'default' */ + if (!base_name->length) + base_name= &default_key_cache_base; + + pthread_mutex_lock(&LOCK_global_system_variables); + key_cache= get_key_cache(base_name); + + if (!key_cache) + { + /* Key cache didn't exists */ + if (!tmp) // Tried to delete cache + goto end; // Ok, nothing to do + if (!(key_cache= create_key_cache(base_name->str, base_name->length))) + { + error= 1; + goto end; + } + } + + /* + Abort if some other thread is changing the key cache + TODO: This should be changed so that we wait until the previous + assignment is done and then do the new assign + */ + if (key_cache->in_init) + goto end; + + if (!tmp) // Zero size means delete + { + if (key_cache == dflt_key_cache) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_CANT_DROP_DEFAULT_KEYCACHE, + ER(ER_WARN_CANT_DROP_DEFAULT_KEYCACHE)); + goto end; // Ignore default key cache + } + + if (key_cache->key_cache_inited) // If initied + { + /* + Move tables using this key cache to the default key cache + and clear the old key cache. + */ + NAMED_LIST *list; + key_cache= (KEY_CACHE *) find_named(&key_caches, base_name->str, + base_name->length, &list); + key_cache->in_init= 1; + pthread_mutex_unlock(&LOCK_global_system_variables); + error= reassign_keycache_tables(thd, key_cache, dflt_key_cache); + pthread_mutex_lock(&LOCK_global_system_variables); + key_cache->in_init= 0; + } + /* + We don't delete the key cache as some running threads my still be + in the key cache code with a pointer to the deleted (empty) key cache + */ + goto end; + } + + bound_unsigned(thd, &tmp, option_limits); + key_cache->param_buff_size= (ulonglong) tmp; + + /* If key cache didn't exist initialize it, else resize it */ + key_cache->in_init= 1; + pthread_mutex_unlock(&LOCK_global_system_variables); + + if (!key_cache->key_cache_inited) + error= (bool) (ha_init_key_cache("", key_cache)); + else + error= (bool)(ha_resize_key_cache(key_cache)); + + pthread_mutex_lock(&LOCK_global_system_variables); + key_cache->in_init= 0; + +end: + pthread_mutex_unlock(&LOCK_global_system_variables); + return error; +} + + +/** + @todo + Abort if some other thread is changing the key cache. + This should be changed so that we wait until the previous + assignment is done and then do the new assign +*/ +bool sys_var_key_cache_long::update(THD *thd, set_var *var) +{ + ulonglong tmp= var->value->val_int(); + LEX_STRING *base_name= &var->base; + bool error= 0; + + if (!base_name->length) + base_name= &default_key_cache_base; + + pthread_mutex_lock(&LOCK_global_system_variables); + KEY_CACHE *key_cache= get_key_cache(base_name); + + if (!key_cache && !(key_cache= create_key_cache(base_name->str, + base_name->length))) + { + error= 1; + goto end; + } + + /* + Abort if some other thread is changing the key cache + TODO: This should be changed so that we wait until the previous + assignment is done and then do the new assign + */ + if (key_cache->in_init) + goto end; + + bound_unsigned(thd, &tmp, option_limits); + *((ulong*) (((char*) key_cache) + offset))= (ulong) tmp; + + /* + Don't create a new key cache if it didn't exist + (key_caches are created only when the user sets block_size) + */ + key_cache->in_init= 1; + + pthread_mutex_unlock(&LOCK_global_system_variables); + + error= (bool) (ha_resize_key_cache(key_cache)); + + pthread_mutex_lock(&LOCK_global_system_variables); + key_cache->in_init= 0; + +end: + pthread_mutex_unlock(&LOCK_global_system_variables); + return error; +} + + +bool sys_var_log_state::update(THD *thd, set_var *var) +{ + bool res; + + if (this == &sys_var_log) + WARN_DEPRECATED(thd, "7.0", "@@log", "'@@general_log'"); + else if (this == &sys_var_log_slow) + WARN_DEPRECATED(thd, "7.0", "@@log_slow_queries", "'@@slow_query_log'"); + + pthread_mutex_lock(&LOCK_global_system_variables); + if (!var->save_result.ulong_value) + { + logger.deactivate_log_handler(thd, log_type); + res= false; + } + else + res= logger.activate_log_handler(thd, log_type); + pthread_mutex_unlock(&LOCK_global_system_variables); + return res; +} + +void sys_var_log_state::set_default(THD *thd, enum_var_type type) +{ + if (this == &sys_var_log) + WARN_DEPRECATED(thd, "7.0", "@@log", "'@@general_log'"); + else if (this == &sys_var_log_slow) + WARN_DEPRECATED(thd, "7.0", "@@log_slow_queries", "'@@slow_query_log'"); + + pthread_mutex_lock(&LOCK_global_system_variables); + logger.deactivate_log_handler(thd, log_type); + pthread_mutex_unlock(&LOCK_global_system_variables); +} + + +static int sys_check_log_path(THD *thd, set_var *var) +{ + char path[FN_REFLEN], buff[FN_REFLEN]; + MY_STAT f_stat; + String str(buff, sizeof(buff), system_charset_info), *res; + const char *log_file_str; + size_t path_length; + + if (!(res= var->value->val_str(&str))) + goto err; + + log_file_str= res->c_ptr(); + bzero(&f_stat, sizeof(MY_STAT)); + + path_length= unpack_filename(path, log_file_str); + + if (!path_length) + { + /* File name is empty. */ + + goto err; + } + + if (my_stat(path, &f_stat, MYF(0))) + { + /* + A file system object exists. Check if argument is a file and we have + 'write' permission. + */ + + if (!MY_S_ISREG(f_stat.st_mode) || + !(f_stat.st_mode & MY_S_IWRITE)) + goto err; + + return 0; + } + + /* Get dirname of the file path. */ + (void) dirname_part(path, log_file_str, &path_length); + + /* Dirname is empty if file path is relative. */ + if (!path_length) + return 0; + + /* + Check if directory exists and we have permission to create file and + write to file. + */ + if (my_access(path, (F_OK|W_OK))) + goto err; + + return 0; + +err: + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), var->var->name, + res ? log_file_str : "NULL"); + return 1; +} + + +bool update_sys_var_str_path(THD *thd, sys_var_str *var_str, + set_var *var, const char *log_ext, + bool log_state, uint log_type) +{ + MYSQL_QUERY_LOG *file_log; + char buff[FN_REFLEN]; + char *res= 0, *old_value=(char *)(var ? var->value->str_value.ptr() : 0); + bool result= 0; + uint str_length= (var ? var->value->str_value.length() : 0); + + switch (log_type) { + case QUERY_LOG_SLOW: + file_log= logger.get_slow_log_file_handler(); + break; + case QUERY_LOG_GENERAL: + file_log= logger.get_log_file_handler(); + break; + default: + assert(0); // Impossible + } + + if (!old_value) + { + old_value= make_default_log_name(buff, log_ext); + str_length= strlen(old_value); + } + if (!(res= my_strndup(old_value, str_length, MYF(MY_FAE+MY_WME)))) + { + result= 1; + goto err; + } + + pthread_mutex_lock(&LOCK_global_system_variables); + logger.lock_exclusive(); + + if (file_log && log_state) + file_log->close(0); + old_value= var_str->value; + var_str->value= res; + var_str->value_length= str_length; + my_free(old_value, MYF(MY_ALLOW_ZERO_PTR)); + if (file_log && log_state) + { + switch (log_type) { + case QUERY_LOG_SLOW: + file_log->open_slow_log(sys_var_slow_log_path.value); + break; + case QUERY_LOG_GENERAL: + file_log->open_query_log(sys_var_general_log_path.value); + break; + default: + DBUG_ASSERT(0); + } + } + + logger.unlock(); + pthread_mutex_unlock(&LOCK_global_system_variables); + +err: + return result; +} + + +static bool sys_update_general_log_path(THD *thd, set_var * var) +{ + return update_sys_var_str_path(thd, &sys_var_general_log_path, + var, ".log", opt_log, QUERY_LOG_GENERAL); +} + + +static void sys_default_general_log_path(THD *thd, enum_var_type type) +{ + (void) update_sys_var_str_path(thd, &sys_var_general_log_path, + 0, ".log", opt_log, QUERY_LOG_GENERAL); +} + + +static bool sys_update_slow_log_path(THD *thd, set_var * var) +{ + return update_sys_var_str_path(thd, &sys_var_slow_log_path, + var, "-slow.log", opt_slow_log, + QUERY_LOG_SLOW); +} + + +static void sys_default_slow_log_path(THD *thd, enum_var_type type) +{ + (void) update_sys_var_str_path(thd, &sys_var_slow_log_path, + 0, "-slow.log", opt_slow_log, + QUERY_LOG_SLOW); +} + + +bool sys_var_log_output::update(THD *thd, set_var *var) +{ + pthread_mutex_lock(&LOCK_global_system_variables); + logger.lock_exclusive(); + logger.init_slow_log(var->save_result.ulong_value); + logger.init_general_log(var->save_result.ulong_value); + *value= var->save_result.ulong_value; + logger.unlock(); + pthread_mutex_unlock(&LOCK_global_system_variables); + return 0; +} + + +void sys_var_log_output::set_default(THD *thd, enum_var_type type) +{ + pthread_mutex_lock(&LOCK_global_system_variables); + logger.lock_exclusive(); + logger.init_slow_log(LOG_FILE); + logger.init_general_log(LOG_FILE); + *value= LOG_FILE; + logger.unlock(); + pthread_mutex_unlock(&LOCK_global_system_variables); +} + + +uchar *sys_var_log_output::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + char buff[256]; + String tmp(buff, sizeof(buff), &my_charset_latin1); + ulong length; + ulong val= *value; + + tmp.length(0); + for (uint i= 0; val; val>>= 1, i++) + { + if (val & 1) + { + tmp.append(log_output_typelib.type_names[i], + log_output_typelib.type_lengths[i]); + tmp.append(','); + } + } + + if ((length= tmp.length())) + length--; + return (uchar*) thd->strmake(tmp.ptr(), length); +} + + +/***************************************************************************** + Functions to handle SET NAMES and SET CHARACTER SET +*****************************************************************************/ + +int set_var_collation_client::check(THD *thd) +{ + /* Currently, UCS-2 cannot be used as a client character set */ + if (character_set_client->mbminlen > 1) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), "character_set_client", + character_set_client->csname); + return 1; + } + return 0; +} + +int set_var_collation_client::update(THD *thd) +{ + thd->variables.character_set_client= character_set_client; + thd->variables.character_set_results= character_set_results; + thd->variables.collation_connection= collation_connection; + thd->update_charset(); + thd->protocol_text.init(thd); + thd->protocol_binary.init(thd); + return 0; +} + +/****************************************************************************/ + +bool sys_var_timestamp::update(THD *thd, set_var *var) +{ + thd->set_time((time_t) var->save_result.ulonglong_value); + return 0; +} + + +void sys_var_timestamp::set_default(THD *thd, enum_var_type type) +{ + thd->user_time=0; +} + + +uchar *sys_var_timestamp::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + thd->sys_var_tmp.long_value= (long) thd->start_time; + return (uchar*) &thd->sys_var_tmp.long_value; +} + + +bool sys_var_last_insert_id::update(THD *thd, set_var *var) +{ + thd->first_successful_insert_id_in_prev_stmt= + var->save_result.ulonglong_value; + return 0; +} + + +uchar *sys_var_last_insert_id::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + /* + this tmp var makes it robust againt change of type of + read_first_successful_insert_id_in_prev_stmt(). + */ + thd->sys_var_tmp.ulonglong_value= + thd->read_first_successful_insert_id_in_prev_stmt(); + return (uchar*) &thd->sys_var_tmp.ulonglong_value; +} + + +bool sys_var_insert_id::update(THD *thd, set_var *var) +{ + thd->force_one_auto_inc_interval(var->save_result.ulonglong_value); + return 0; +} + + +uchar *sys_var_insert_id::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + thd->sys_var_tmp.ulonglong_value= + thd->auto_inc_intervals_forced.minimum(); + return (uchar*) &thd->sys_var_tmp.ulonglong_value; +} + + +bool sys_var_rand_seed1::update(THD *thd, set_var *var) +{ + thd->rand.seed1= (ulong) var->save_result.ulonglong_value; + return 0; +} + +bool sys_var_rand_seed2::update(THD *thd, set_var *var) +{ + thd->rand.seed2= (ulong) var->save_result.ulonglong_value; + return 0; +} + + +bool sys_var_thd_time_zone::check(THD *thd, set_var *var) +{ + char buff[MAX_TIME_ZONE_NAME_LENGTH]; + String str(buff, sizeof(buff), &my_charset_latin1); + String *res= var->value->val_str(&str); + + if (!(var->save_result.time_zone= my_tz_find(thd, res))) + { + my_error(ER_UNKNOWN_TIME_ZONE, MYF(0), res ? res->c_ptr() : "NULL"); + return 1; + } + return 0; +} + + +bool sys_var_thd_time_zone::update(THD *thd, set_var *var) +{ + /* We are using Time_zone object found during check() phase. */ + if (var->type == OPT_GLOBAL) + { + pthread_mutex_lock(&LOCK_global_system_variables); + global_system_variables.time_zone= var->save_result.time_zone; + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.time_zone= var->save_result.time_zone; + return 0; +} + + +uchar *sys_var_thd_time_zone::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + /* + We can use ptr() instead of c_ptr() here because String contaning + time zone name is guaranteed to be zero ended. + */ + if (type == OPT_GLOBAL) + return (uchar *)(global_system_variables.time_zone->get_name()->ptr()); + else + { + /* + This is an ugly fix for replication: we don't replicate properly queries + invoking system variables' values to update tables; but + CONVERT_TZ(,,@@session.time_zone) is so popular that we make it + replicable (i.e. we tell the binlog code to store the session + timezone). If it's the global value which was used we can't replicate + (binlog code stores session value only). + */ + thd->time_zone_used= 1; + return (uchar *)(thd->variables.time_zone->get_name()->ptr()); + } +} + + +void sys_var_thd_time_zone::set_default(THD *thd, enum_var_type type) +{ + pthread_mutex_lock(&LOCK_global_system_variables); + if (type == OPT_GLOBAL) + { + if (default_tz_name) + { + String str(default_tz_name, &my_charset_latin1); + /* + We are guaranteed to find this time zone since its existence + is checked during start-up. + */ + global_system_variables.time_zone= my_tz_find(thd, &str); + } + else + global_system_variables.time_zone= my_tz_SYSTEM; + } + else + thd->variables.time_zone= global_system_variables.time_zone; + pthread_mutex_unlock(&LOCK_global_system_variables); +} + + +bool sys_var_max_user_conn::check(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + return sys_var_thd::check(thd, var); + else + { + /* + Per-session values of max_user_connections can't be set directly. + May be we should have a separate error message for this? + */ + my_error(ER_GLOBAL_VARIABLE, MYF(0), name); + return TRUE; + } +} + +bool sys_var_max_user_conn::update(THD *thd, set_var *var) +{ + DBUG_ASSERT(var->type == OPT_GLOBAL); + pthread_mutex_lock(&LOCK_global_system_variables); + max_user_connections= (uint)var->save_result.ulonglong_value; + pthread_mutex_unlock(&LOCK_global_system_variables); + return 0; +} + + +void sys_var_max_user_conn::set_default(THD *thd, enum_var_type type) +{ + DBUG_ASSERT(type == OPT_GLOBAL); + pthread_mutex_lock(&LOCK_global_system_variables); + max_user_connections= (ulong) option_limits->def_value; + pthread_mutex_unlock(&LOCK_global_system_variables); +} + + +uchar *sys_var_max_user_conn::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + if (type != OPT_GLOBAL && + thd->user_connect && thd->user_connect->user_resources.user_conn) + return (uchar*) &(thd->user_connect->user_resources.user_conn); + return (uchar*) &(max_user_connections); +} + + +bool sys_var_thd_ulong_session_readonly::check(THD *thd, set_var *var) +{ + if (var->type != OPT_GLOBAL) + { + my_error(ER_VARIABLE_IS_READONLY, MYF(0), "SESSION", name, "GLOBAL"); + return TRUE; + } + + return sys_var_thd_ulong::check(thd, var); +} + + +bool sys_var_thd_lc_time_names::check(THD *thd, set_var *var) +{ + MY_LOCALE *locale_match; + + if (var->value->result_type() == INT_RESULT) + { + if (!(locale_match= my_locale_by_number((uint) var->value->val_int()))) + { + char buf[20]; + int10_to_str((int) var->value->val_int(), buf, -10); + my_printf_error(ER_UNKNOWN_ERROR, "Unknown locale: '%s'", MYF(0), buf); + return 1; + } + } + else // STRING_RESULT + { + char buff[6]; + String str(buff, sizeof(buff), &my_charset_latin1), *res; + if (!(res=var->value->val_str(&str))) + { + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, "NULL"); + return 1; + } + const char *locale_str= res->c_ptr(); + if (!(locale_match= my_locale_by_name(locale_str))) + { + my_printf_error(ER_UNKNOWN_ERROR, + "Unknown locale: '%s'", MYF(0), locale_str); + return 1; + } + } + + var->save_result.locale_value= locale_match; + return 0; +} + + +bool sys_var_thd_lc_time_names::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + global_system_variables.lc_time_names= var->save_result.locale_value; + else + thd->variables.lc_time_names= var->save_result.locale_value; + return 0; +} + + +uchar *sys_var_thd_lc_time_names::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + return type == OPT_GLOBAL ? + (uchar *) global_system_variables.lc_time_names->name : + (uchar *) thd->variables.lc_time_names->name; +} + + +void sys_var_thd_lc_time_names::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.lc_time_names= my_default_lc_time_names; + else + thd->variables.lc_time_names= global_system_variables.lc_time_names; +} + +/* + Handling of microseoncds given as seconds.part_seconds + + NOTES + The argument to long query time is in seconds in decimal + which is converted to ulonglong integer holding microseconds for storage. + This is used for handling long_query_time +*/ + +bool sys_var_microseconds::update(THD *thd, set_var *var) +{ + double num= var->value->val_real(); + longlong microseconds; + if (num > (double) option_limits->max_value) + num= (double) option_limits->max_value; + if (num < (double) option_limits->min_value) + num= (double) option_limits->min_value; + microseconds= (longlong) (num * 1000000.0 + 0.5); + if (var->type == OPT_GLOBAL) + { + pthread_mutex_lock(&LOCK_global_system_variables); + (global_system_variables.*offset)= microseconds; + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.*offset= microseconds; + return 0; +} + + +void sys_var_microseconds::set_default(THD *thd, enum_var_type type) +{ + longlong microseconds= (longlong) (option_limits->def_value * 1000000.0); + if (type == OPT_GLOBAL) + { + pthread_mutex_lock(&LOCK_global_system_variables); + global_system_variables.*offset= microseconds; + pthread_mutex_unlock(&LOCK_global_system_variables); + } + else + thd->variables.*offset= microseconds; +} + + +uchar *sys_var_microseconds::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + thd->tmp_double_value= (double) ((type == OPT_GLOBAL) ? + global_system_variables.*offset : + thd->variables.*offset) / 1000000.0; + return (uchar*) &thd->tmp_double_value; +} + + +/* + Functions to update thd->options bits +*/ + +static bool set_option_bit(THD *thd, set_var *var) +{ + sys_var_thd_bit *sys_var= ((sys_var_thd_bit*) var->var); + if ((var->save_result.ulong_value != 0) == sys_var->reverse) + thd->options&= ~sys_var->bit_flag; + else + thd->options|= sys_var->bit_flag; + return 0; +} + +/* + Functions to be only used to update thd->options OPTION_BIN_LOG bit +*/ +static bool set_option_log_bin_bit(THD *thd, set_var *var) +{ + set_option_bit(thd, var); + if (!thd->in_sub_stmt) + thd->sql_log_bin_toplevel= thd->options & OPTION_BIN_LOG; + return 0; +} + +static bool set_option_autocommit(THD *thd, set_var *var) +{ + /* The test is negative as the flag we use is NOT autocommit */ + + ulonglong org_options= thd->options; + + if (var->save_result.ulong_value != 0) + thd->options&= ~((sys_var_thd_bit*) var->var)->bit_flag; + else + thd->options|= ((sys_var_thd_bit*) var->var)->bit_flag; + + if ((org_options ^ thd->options) & OPTION_NOT_AUTOCOMMIT) + { + if ((org_options & OPTION_NOT_AUTOCOMMIT)) + { + /* We changed to auto_commit mode */ + thd->options&= ~(ulonglong) (OPTION_BEGIN | OPTION_KEEP_LOG); + thd->transaction.all.modified_non_trans_table= FALSE; + thd->server_status|= SERVER_STATUS_AUTOCOMMIT; + if (ha_commit(thd)) + return 1; + } + else + { + thd->transaction.all.modified_non_trans_table= FALSE; + thd->server_status&= ~SERVER_STATUS_AUTOCOMMIT; + } + } + return 0; +} + +static int check_log_update(THD *thd, set_var *var) +{ +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (!(thd->security_ctx->master_access & SUPER_ACL)) + { + my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER"); + return 1; + } +#endif + return 0; +} + +static bool set_log_update(THD *thd, set_var *var) +{ + /* + The update log is not supported anymore since 5.0. + See sql/mysqld.cc/, comments in function init_server_components() for an + explaination of the different warnings we send below + */ + + if (opt_sql_bin_update) + { + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_UPDATE_LOG_DEPRECATED_TRANSLATED, + ER(ER_UPDATE_LOG_DEPRECATED_TRANSLATED)); + } + else + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_UPDATE_LOG_DEPRECATED_IGNORED, + ER(ER_UPDATE_LOG_DEPRECATED_IGNORED)); + set_option_bit(thd, var); + return 0; +} + + +static int check_pseudo_thread_id(THD *thd, set_var *var) +{ + var->save_result.ulonglong_value= var->value->val_int(); +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (thd->security_ctx->master_access & SUPER_ACL) + return 0; + else + { + my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER"); + return 1; + } +#else + return 0; +#endif +} + +static uchar *get_warning_count(THD *thd) +{ + thd->sys_var_tmp.long_value= + (thd->warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_NOTE] + + thd->warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_ERROR] + + thd->warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_WARN]); + return (uchar*) &thd->sys_var_tmp.long_value; +} + +static uchar *get_error_count(THD *thd) +{ + thd->sys_var_tmp.long_value= + thd->warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_ERROR]; + return (uchar*) &thd->sys_var_tmp.long_value; +} + + +/** + Get the tmpdir that was specified or chosen by default. + + This is necessary because if the user does not specify a temporary + directory via the command line, one is chosen based on the environment + or system defaults. But we can't just always use mysql_tmpdir, because + that is actually a call to my_tmpdir() which cycles among possible + temporary directories. + + @param thd thread handle + + @retval + ptr pointer to NUL-terminated string +*/ +static uchar *get_tmpdir(THD *thd) +{ + if (opt_mysql_tmpdir) + return (uchar *)opt_mysql_tmpdir; + return (uchar*)mysql_tmpdir; +} + +/**************************************************************************** + Main handling of variables: + - Initialisation + - Searching during parsing + - Update loop +****************************************************************************/ + +/** + Find variable name in option my_getopt structure used for + command line args. + + @param opt option structure array to search in + @param name variable name + + @retval + 0 Error + @retval + ptr pointer to option structure +*/ + +static struct my_option *find_option(struct my_option *opt, const char *name) +{ + uint length=strlen(name); + for (; opt->name; opt++) + { + if (!getopt_compare_strings(opt->name, name, length) && + !opt->name[length]) + { + /* + Only accept the option if one can set values through it. + If not, there is no default value or limits in the option. + */ + return (opt->value) ? opt : 0; + } + } + return 0; +} + + +/** + Return variable name and length for hashing of variables. +*/ + +static uchar *get_sys_var_length(const sys_var *var, size_t *length, + my_bool first) +{ + *length= var->name_length; + return (uchar*) var->name; +} + + +/* + Add variables to the dynamic hash of system variables + + SYNOPSIS + mysql_add_sys_var_chain() + first Pointer to first system variable to add + long_opt (optional)command line arguments may be tied for limit checks. + + RETURN VALUES + 0 SUCCESS + otherwise FAILURE +*/ + + +int mysql_add_sys_var_chain(sys_var *first, struct my_option *long_options) +{ + sys_var *var; + + /* A write lock should be held on LOCK_system_variables_hash */ + + for (var= first; var; var= var->next) + { + var->name_length= strlen(var->name); + /* this fails if there is a conflicting variable name. see HASH_UNIQUE */ + if (my_hash_insert(&system_variable_hash, (uchar*) var)) + goto error; + if (long_options) + var->option_limits= find_option(long_options, var->name); + } + return 0; + +error: + for (; first != var; first= first->next) + hash_delete(&system_variable_hash, (uchar*) first); + return 1; +} + + +/* + Remove variables to the dynamic hash of system variables + + SYNOPSIS + mysql_del_sys_var_chain() + first Pointer to first system variable to remove + + RETURN VALUES + 0 SUCCESS + otherwise FAILURE +*/ + +int mysql_del_sys_var_chain(sys_var *first) +{ + int result= 0; + + /* A write lock should be held on LOCK_system_variables_hash */ + + for (sys_var *var= first; var; var= var->next) + result|= hash_delete(&system_variable_hash, (uchar*) var); + + return result; +} + + +static int show_cmp(SHOW_VAR *a, SHOW_VAR *b) +{ + return strcmp(a->name, b->name); +} + + +/* + Constructs an array of system variables for display to the user. + + SYNOPSIS + enumerate_sys_vars() + thd current thread + sorted If TRUE, the system variables should be sorted + + RETURN VALUES + pointer Array of SHOW_VAR elements for display + NULL FAILURE +*/ + +SHOW_VAR* enumerate_sys_vars(THD *thd, bool sorted) +{ + int count= system_variable_hash.records, i; + int size= sizeof(SHOW_VAR) * (count + 1); + SHOW_VAR *result= (SHOW_VAR*) thd->alloc(size); + + if (result) + { + SHOW_VAR *show= result; + + for (i= 0; i < count; i++) + { + sys_var *var= (sys_var*) hash_element(&system_variable_hash, i); + show->name= var->name; + show->value= (char*) var; + show->type= SHOW_SYS; + show++; + } + + /* sort into order */ + if (sorted) + my_qsort(result, count, sizeof(SHOW_VAR), + (qsort_cmp) show_cmp); + + /* make last element empty */ + bzero(show, sizeof(SHOW_VAR)); + } + return result; +} + + +/* + Initialize the system variables + + SYNOPSIS + set_var_init() + + RETURN VALUES + 0 SUCCESS + otherwise FAILURE +*/ + +int set_var_init() +{ + uint count= 0; + DBUG_ENTER("set_var_init"); + + for (sys_var *var=vars.first; var; var= var->next, count++); + + if (hash_init(&system_variable_hash, system_charset_info, count, 0, + 0, (hash_get_key) get_sys_var_length, 0, HASH_UNIQUE)) + goto error; + + vars.last->next= NULL; + if (mysql_add_sys_var_chain(vars.first, my_long_options)) + goto error; + + /* + Special cases + Needed because MySQL can't find the limits for a variable it it has + a different name than the command line option. + As these variables are deprecated, this code will disappear soon... + */ + sys_sql_max_join_size.option_limits= sys_max_join_size.option_limits; + + DBUG_RETURN(0); + +error: + fprintf(stderr, "failed to initialize system variables"); + DBUG_RETURN(1); +} + + +void set_var_free() +{ + hash_free(&system_variable_hash); +} + + +/** + Find a user set-table variable. + + @param str Name of system variable to find + @param length Length of variable. zero means that we should use strlen() + on the variable + @param no_error Refuse to emit an error, even if one occurred. + + @retval + pointer pointer to variable definitions + @retval + 0 Unknown variable (error message is given) +*/ + +sys_var *intern_find_sys_var(const char *str, uint length, bool no_error) +{ + sys_var *var; + + /* + This function is only called from the sql_plugin.cc. + A lock on LOCK_system_variable_hash should be held + */ + var= (sys_var*) hash_search(&system_variable_hash, + (uchar*) str, length ? length : strlen(str)); + if (!(var || no_error)) + my_error(ER_UNKNOWN_SYSTEM_VARIABLE, MYF(0), (char*) str); + + return var; +} + + +/** + Execute update of all variables. + + First run a check of all variables that all updates will go ok. + If yes, then execute all updates, returning an error if any one failed. + + This should ensure that in all normal cases none all or variables are + updated. + + @param THD Thread id + @param var_list List of variables to update + + @retval + 0 ok + @retval + 1 ERROR, message sent (normally no variables was updated) + @retval + -1 ERROR, message not sent +*/ + +int sql_set_variables(THD *thd, List *var_list) +{ + int error; + List_iterator_fast it(*var_list); + DBUG_ENTER("sql_set_variables"); + + set_var_base *var; + while ((var=it++)) + { + if ((error= var->check(thd))) + goto err; + } + if (!(error= test(thd->is_error()))) + { + it.rewind(); + while ((var= it++)) + error|= var->update(thd); // Returns 0, -1 or 1 + } + +err: + free_underlaid_joins(thd, &thd->lex->select_lex); + DBUG_RETURN(error); +} + + +/** + Say if all variables set by a SET support the ONE_SHOT keyword + (currently, only character set and collation do; later timezones + will). + + @param var_list List of variables to update + + @note + It has a "not_" because it makes faster tests (no need to "!") + + @retval + 0 all variables of the list support ONE_SHOT + @retval + 1 at least one does not support ONE_SHOT +*/ + +bool not_all_support_one_shot(List *var_list) +{ + List_iterator_fast it(*var_list); + set_var_base *var; + while ((var= it++)) + { + if (var->no_support_one_shot()) + return 1; + } + return 0; +} + + +/***************************************************************************** + Functions to handle SET mysql_internal_variable=const_expr +*****************************************************************************/ + +int set_var::check(THD *thd) +{ + if (var->is_readonly()) + { + my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0), var->name, "read only"); + return -1; + } + if (var->check_type(type)) + { + int err= type == OPT_GLOBAL ? ER_LOCAL_VARIABLE : ER_GLOBAL_VARIABLE; + my_error(err, MYF(0), var->name); + return -1; + } + if ((type == OPT_GLOBAL && check_global_access(thd, SUPER_ACL))) + return 1; + /* value is a NULL pointer if we are using SET ... = DEFAULT */ + if (!value) + { + if (var->check_default(type)) + { + my_error(ER_NO_DEFAULT, MYF(0), var->name); + return -1; + } + return 0; + } + + if ((!value->fixed && + value->fix_fields(thd, &value)) || value->check_cols(1)) + return -1; + if (var->check_update_type(value->result_type())) + { + my_error(ER_WRONG_TYPE_FOR_VAR, MYF(0), var->name); + return -1; + } + return var->check(thd, this) ? -1 : 0; +} + + +/** + Check variable, but without assigning value (used by PS). + + @param thd thread handler + + @retval + 0 ok + @retval + 1 ERROR, message sent (normally no variables was updated) + @retval + -1 ERROR, message not sent +*/ +int set_var::light_check(THD *thd) +{ + if (var->check_type(type)) + { + int err= type == OPT_GLOBAL ? ER_LOCAL_VARIABLE : ER_GLOBAL_VARIABLE; + my_error(err, MYF(0), var->name); + return -1; + } + if (type == OPT_GLOBAL && check_global_access(thd, SUPER_ACL)) + return 1; + + if (value && ((!value->fixed && value->fix_fields(thd, &value)) || + value->check_cols(1))) + return -1; + return 0; +} + +/** + Update variable + + @param thd thread handler + @returns 0|1 ok or ERROR + + @note ERROR can be only due to abnormal operations involving + the server's execution evironment such as + out of memory, hard disk failure or the computer blows up. + Consider set_var::check() method if there is a need to return + an error due to logics. +*/ +int set_var::update(THD *thd) +{ + if (!value) + var->set_default(thd, type); + else if (var->update(thd, this)) + return -1; // should never happen + if (var->after_update) + (*var->after_update)(thd, type); + return 0; +} + + +/***************************************************************************** + Functions to handle SET @user_variable=const_expr +*****************************************************************************/ + +int set_var_user::check(THD *thd) +{ + /* + Item_func_set_user_var can't substitute something else on its place => + 0 can be passed as last argument (reference on item) + */ + return (user_var_item->fix_fields(thd, (Item**) 0) || + user_var_item->check(0)) ? -1 : 0; +} + + +/** + Check variable, but without assigning value (used by PS). + + @param thd thread handler + + @retval + 0 ok + @retval + 1 ERROR, message sent (normally no variables was updated) + @retval + -1 ERROR, message not sent +*/ +int set_var_user::light_check(THD *thd) +{ + /* + Item_func_set_user_var can't substitute something else on its place => + 0 can be passed as last argument (reference on item) + */ + return (user_var_item->fix_fields(thd, (Item**) 0)); +} + + +int set_var_user::update(THD *thd) +{ + if (user_var_item->update()) + { + /* Give an error if it's not given already */ + my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY), MYF(0)); + return -1; + } + return 0; +} + + +/***************************************************************************** + Functions to handle SET PASSWORD +*****************************************************************************/ + +int set_var_password::check(THD *thd) +{ +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (!user->host.str) + { + DBUG_ASSERT(thd->security_ctx->priv_host); + if (*thd->security_ctx->priv_host != 0) + { + user->host.str= (char *) thd->security_ctx->priv_host; + user->host.length= strlen(thd->security_ctx->priv_host); + } + else + { + user->host.str= (char *)"%"; + user->host.length= 1; + } + } + if (!user->user.str) + { + DBUG_ASSERT(thd->security_ctx->priv_user); + user->user.str= (char *) thd->security_ctx->priv_user; + user->user.length= strlen(thd->security_ctx->priv_user); + } + /* Returns 1 as the function sends error to client */ + return check_change_password(thd, user->host.str, user->user.str, + password, strlen(password)) ? 1 : 0; +#else + return 0; +#endif +} + +int set_var_password::update(THD *thd) +{ +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* Returns 1 as the function sends error to client */ + return change_password(thd, user->host.str, user->user.str, password) ? + 1 : 0; +#else + return 0; +#endif +} + +/**************************************************************************** + Functions to handle table_type +****************************************************************************/ + +/* Based upon sys_var::check_enum() */ + +bool sys_var_thd_storage_engine::check(THD *thd, set_var *var) +{ + char buff[STRING_BUFFER_USUAL_SIZE]; + const char *value; + String str(buff, sizeof(buff), &my_charset_latin1), *res; + + var->save_result.plugin= NULL; + if (var->value->result_type() == STRING_RESULT) + { + LEX_STRING engine_name; + handlerton *hton; + if (!(res=var->value->val_str(&str)) || + !(engine_name.str= (char *)res->ptr()) || + !(engine_name.length= res->length()) || + !(var->save_result.plugin= ha_resolve_by_name(thd, &engine_name)) || + !(hton= plugin_data(var->save_result.plugin, handlerton *)) || + ha_checktype(thd, ha_legacy_type(hton), 1, 0) != hton) + { + value= res ? res->c_ptr() : "NULL"; + goto err; + } + return 0; + } + value= "unknown"; + +err: + my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), value); + return 1; +} + + +uchar *sys_var_thd_storage_engine::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + uchar* result; + handlerton *hton; + LEX_STRING *engine_name; + plugin_ref plugin= thd->variables.*offset; + if (type == OPT_GLOBAL) + plugin= my_plugin_lock(thd, &(global_system_variables.*offset)); + hton= plugin_data(plugin, handlerton*); + engine_name= &hton2plugin[hton->slot]->name; + result= (uchar *) thd->strmake(engine_name->str, engine_name->length); + if (type == OPT_GLOBAL) + plugin_unlock(thd, plugin); + return result; +} + + +void sys_var_thd_storage_engine::set_default(THD *thd, enum_var_type type) +{ + plugin_ref old_value, new_value, *value; + if (type == OPT_GLOBAL) + { + value= &(global_system_variables.*offset); + new_value= ha_lock_engine(NULL, myisam_hton); + } + else + { + value= &(thd->variables.*offset); + new_value= my_plugin_lock(NULL, &(global_system_variables.*offset)); + } + DBUG_ASSERT(new_value); + old_value= *value; + *value= new_value; + plugin_unlock(NULL, old_value); +} + + +bool sys_var_thd_storage_engine::update(THD *thd, set_var *var) +{ + plugin_ref *value= &(global_system_variables.*offset), old_value; + if (var->type != OPT_GLOBAL) + value= &(thd->variables.*offset); + old_value= *value; + if (old_value != var->save_result.plugin) + { + *value= my_plugin_lock(NULL, &var->save_result.plugin); + plugin_unlock(NULL, old_value); + } + return 0; +} + +void sys_var_thd_table_type::warn_deprecated(THD *thd) +{ + WARN_DEPRECATED(thd, "6.0", "@@table_type", "'@@storage_engine'"); +} + +void sys_var_thd_table_type::set_default(THD *thd, enum_var_type type) +{ + warn_deprecated(thd); + sys_var_thd_storage_engine::set_default(thd, type); +} + +bool sys_var_thd_table_type::update(THD *thd, set_var *var) +{ + warn_deprecated(thd); + return sys_var_thd_storage_engine::update(thd, var); +} + + +/**************************************************************************** + Functions to handle sql_mode +****************************************************************************/ + +/** + Make string representation of mode. + + @param[in] thd thread handler + @param[in] val sql_mode value + @param[out] len pointer on length of string + + @return + pointer to string with sql_mode representation +*/ + +bool +sys_var_thd_sql_mode:: +symbolic_mode_representation(THD *thd, ulonglong val, LEX_STRING *rep) +{ + char buff[STRING_BUFFER_USUAL_SIZE*8]; + String tmp(buff, sizeof(buff), &my_charset_latin1); + + tmp.length(0); + + for (uint i= 0; val; val>>= 1, i++) + { + if (val & 1) + { + tmp.append(sql_mode_typelib.type_names[i], + sql_mode_typelib.type_lengths[i]); + tmp.append(','); + } + } + + if (tmp.length()) + tmp.length(tmp.length() - 1); /* trim the trailing comma */ + + rep->str= thd->strmake(tmp.ptr(), tmp.length()); + + rep->length= rep->str ? tmp.length() : 0; + + return rep->length != tmp.length(); +} + + +uchar *sys_var_thd_sql_mode::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + LEX_STRING sql_mode; + ulonglong val= ((type == OPT_GLOBAL) ? global_system_variables.*offset : + thd->variables.*offset); + (void) symbolic_mode_representation(thd, val, &sql_mode); + return (uchar *) sql_mode.str; +} + + +void sys_var_thd_sql_mode::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.*offset= 0; + else + thd->variables.*offset= global_system_variables.*offset; +} + + +void fix_sql_mode_var(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.sql_mode= + fix_sql_mode(global_system_variables.sql_mode); + else + { + thd->variables.sql_mode= fix_sql_mode(thd->variables.sql_mode); + /* + Update thd->server_status + */ + if (thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) + thd->server_status|= SERVER_STATUS_NO_BACKSLASH_ESCAPES; + else + thd->server_status&= ~SERVER_STATUS_NO_BACKSLASH_ESCAPES; + } +} + +/** Map database specific bits to function bits. */ + +ulong fix_sql_mode(ulong sql_mode) +{ + /* + Note that we dont set + MODE_NO_KEY_OPTIONS | MODE_NO_TABLE_OPTIONS | MODE_NO_FIELD_OPTIONS + to allow one to get full use of MySQL in this mode. + */ + + if (sql_mode & MODE_ANSI) + { + sql_mode|= (MODE_REAL_AS_FLOAT | MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | + MODE_IGNORE_SPACE); + /* + MODE_ONLY_FULL_GROUP_BY removed from ANSI mode because it is currently + overly restrictive (see BUG#8510). + */ + } + if (sql_mode & MODE_ORACLE) + sql_mode|= (MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | + MODE_IGNORE_SPACE | + MODE_NO_KEY_OPTIONS | MODE_NO_TABLE_OPTIONS | + MODE_NO_FIELD_OPTIONS | MODE_NO_AUTO_CREATE_USER); + if (sql_mode & MODE_MSSQL) + sql_mode|= (MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | + MODE_IGNORE_SPACE | + MODE_NO_KEY_OPTIONS | MODE_NO_TABLE_OPTIONS | + MODE_NO_FIELD_OPTIONS); + if (sql_mode & MODE_POSTGRESQL) + sql_mode|= (MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | + MODE_IGNORE_SPACE | + MODE_NO_KEY_OPTIONS | MODE_NO_TABLE_OPTIONS | + MODE_NO_FIELD_OPTIONS); + if (sql_mode & MODE_DB2) + sql_mode|= (MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | + MODE_IGNORE_SPACE | + MODE_NO_KEY_OPTIONS | MODE_NO_TABLE_OPTIONS | + MODE_NO_FIELD_OPTIONS); + if (sql_mode & MODE_MAXDB) + sql_mode|= (MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | + MODE_IGNORE_SPACE | + MODE_NO_KEY_OPTIONS | MODE_NO_TABLE_OPTIONS | + MODE_NO_FIELD_OPTIONS | MODE_NO_AUTO_CREATE_USER); + if (sql_mode & MODE_MYSQL40) + sql_mode|= MODE_HIGH_NOT_PRECEDENCE; + if (sql_mode & MODE_MYSQL323) + sql_mode|= MODE_HIGH_NOT_PRECEDENCE; + if (sql_mode & MODE_TRADITIONAL) + sql_mode|= (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES | + MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE | + MODE_ERROR_FOR_DIVISION_BY_ZERO | MODE_NO_AUTO_CREATE_USER); + return sql_mode; +} + + +bool +sys_var_thd_optimizer_switch:: +symbolic_mode_representation(THD *thd, ulonglong val, LEX_STRING *rep) +{ + char buff[STRING_BUFFER_USUAL_SIZE*8]; + String tmp(buff, sizeof(buff), &my_charset_latin1); + int i; + ulonglong bit; + tmp.length(0); + + for (i= 0, bit=1; bit != OPTIMIZER_SWITCH_LAST; i++, bit= bit << 1) + { + tmp.append(optimizer_switch_typelib.type_names[i], + optimizer_switch_typelib.type_lengths[i]); + tmp.append('='); + tmp.append((val & bit)? "on":"off"); + tmp.append(','); + } + + if (tmp.length()) + tmp.length(tmp.length() - 1); /* trim the trailing comma */ + + rep->str= thd->strmake(tmp.ptr(), tmp.length()); + + rep->length= rep->str ? tmp.length() : 0; + + return rep->length != tmp.length(); +} + + +uchar *sys_var_thd_optimizer_switch::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + LEX_STRING opts; + ulonglong val= ((type == OPT_GLOBAL) ? global_system_variables.*offset : + thd->variables.*offset); + (void) symbolic_mode_representation(thd, val, &opts); + return (uchar *) opts.str; +} + + +/* + Check (and actually parse) string representation of @@optimizer_switch. +*/ + +bool sys_var_thd_optimizer_switch::check(THD *thd, set_var *var) +{ + bool not_used; + char buff[STRING_BUFFER_USUAL_SIZE], *error= 0; + uint error_len= 0; + String str(buff, sizeof(buff), system_charset_info), *res; + + if (!(res= var->value->val_str(&str))) + { + strmov(buff, "NULL"); + goto err; + } + + if (res->length() == 0) + { + buff[0]= 0; + goto err; + } + + var->save_result.ulong_value= + (ulong)find_set_from_flags(&optimizer_switch_typelib, + optimizer_switch_typelib.count, + thd->variables.optimizer_switch, + global_system_variables.optimizer_switch, + res->c_ptr_safe(), res->length(), NULL, + &error, &error_len, ¬_used); + if (error_len) + { + strmake(buff, error, min(sizeof(buff) - 1, error_len)); + goto err; + } + return FALSE; +err: + my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), name, buff); + return TRUE; +} + + +void sys_var_thd_optimizer_switch::set_default(THD *thd, enum_var_type type) +{ + if (type == OPT_GLOBAL) + global_system_variables.*offset= OPTIMIZER_SWITCH_DEFAULT; + else + thd->variables.*offset= global_system_variables.*offset; +} + +/**************************************************************************** + Named list handling +****************************************************************************/ + +uchar* find_named(I_List *list, const char *name, uint length, + NAMED_LIST **found) +{ + I_List_iterator it(*list); + NAMED_LIST *element; + while ((element= it++)) + { + if (element->cmp(name, length)) + { + if (found) + *found= element; + return element->data; + } + } + return 0; +} + + +void delete_elements(I_List *list, + void (*free_element)(const char *name, uchar*)) +{ + NAMED_LIST *element; + DBUG_ENTER("delete_elements"); + while ((element= list->get())) + { + (*free_element)(element->name, element->data); + delete element; + } + DBUG_VOID_RETURN; +} + + +/* Key cache functions */ + +static KEY_CACHE *create_key_cache(const char *name, uint length) +{ + KEY_CACHE *key_cache; + DBUG_ENTER("create_key_cache"); + DBUG_PRINT("enter",("name: %.*s", length, name)); + + if ((key_cache= (KEY_CACHE*) my_malloc(sizeof(KEY_CACHE), + MYF(MY_ZEROFILL | MY_WME)))) + { + if (!new NAMED_LIST(&key_caches, name, length, (uchar*) key_cache)) + { + my_free((char*) key_cache, MYF(0)); + key_cache= 0; + } + else + { + /* + Set default values for a key cache + The values in dflt_key_cache_var is set by my_getopt() at startup + + We don't set 'buff_size' as this is used to enable the key cache + */ + key_cache->param_block_size= dflt_key_cache_var.param_block_size; + key_cache->param_division_limit= dflt_key_cache_var.param_division_limit; + key_cache->param_age_threshold= dflt_key_cache_var.param_age_threshold; + } + } + DBUG_RETURN(key_cache); +} + + +KEY_CACHE *get_or_create_key_cache(const char *name, uint length) +{ + LEX_STRING key_cache_name; + KEY_CACHE *key_cache; + + key_cache_name.str= (char *) name; + key_cache_name.length= length; + pthread_mutex_lock(&LOCK_global_system_variables); + if (!(key_cache= get_key_cache(&key_cache_name))) + key_cache= create_key_cache(name, length); + pthread_mutex_unlock(&LOCK_global_system_variables); + return key_cache; +} + + +void free_key_cache(const char *name, KEY_CACHE *key_cache) +{ + ha_end_key_cache(key_cache); + my_free((char*) key_cache, MYF(0)); +} + + +bool process_key_caches(process_key_cache_t func) +{ + I_List_iterator it(key_caches); + NAMED_LIST *element; + + while ((element= it++)) + { + KEY_CACHE *key_cache= (KEY_CACHE *) element->data; + func(element->name, key_cache); + } + return 0; +} + + +void sys_var_trust_routine_creators::warn_deprecated(THD *thd) +{ + WARN_DEPRECATED(thd, "6.0", "@@log_bin_trust_routine_creators", + "'@@log_bin_trust_function_creators'"); +} + +void sys_var_trust_routine_creators::set_default(THD *thd, enum_var_type type) +{ + warn_deprecated(thd); + sys_var_bool_ptr::set_default(thd, type); +} + +bool sys_var_trust_routine_creators::update(THD *thd, set_var *var) +{ + warn_deprecated(thd); + return sys_var_bool_ptr::update(thd, var); +} + +bool sys_var_opt_readonly::update(THD *thd, set_var *var) +{ + bool result; + + DBUG_ENTER("sys_var_opt_readonly::update"); + + /* Prevent self dead-lock */ + if (thd->locked_tables || thd->active_transaction()) + { + my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0)); + DBUG_RETURN(true); + } + + if (thd->global_read_lock) + { + /* + This connection already holds the global read lock. + This can be the case with: + - FLUSH TABLES WITH READ LOCK + - SET GLOBAL READ_ONLY = 1 + */ + result= sys_var_bool_ptr::update(thd, var); + DBUG_RETURN(result); + } + + /* + Perform a 'FLUSH TABLES WITH READ LOCK'. + This is a 3 step process: + - [1] lock_global_read_lock() + - [2] close_cached_tables() + - [3] make_global_read_lock_block_commit() + [1] prevents new connections from obtaining tables locked for write. + [2] waits until all existing connections close their tables. + [3] prevents transactions from being committed. + */ + + if (lock_global_read_lock(thd)) + DBUG_RETURN(true); + + /* + This call will be blocked by any connection holding a READ or WRITE lock. + Ideally, we want to wait only for pending WRITE locks, but since: + con 1> LOCK TABLE T FOR READ; + con 2> LOCK TABLE T FOR WRITE; (blocked by con 1) + con 3> SET GLOBAL READ ONLY=1; (blocked by con 2) + can cause to wait on a read lock, it's required for the client application + to unlock everything, and acceptable for the server to wait on all locks. + */ + if (result= close_cached_tables(thd, NULL, FALSE, TRUE, TRUE)) + goto end_with_read_lock; + + if (result= make_global_read_lock_block_commit(thd)) + goto end_with_read_lock; + + /* Change the opt_readonly system variable, safe because the lock is held */ + result= sys_var_bool_ptr::update(thd, var); + +end_with_read_lock: + /* Release the lock */ + unlock_global_read_lock(thd); + DBUG_RETURN(result); +} + + +/* even session variable here requires SUPER, because of -#o,file */ +bool sys_var_thd_dbug::check(THD *thd, set_var *var) +{ + return check_global_access(thd, SUPER_ACL); +} + +bool sys_var_thd_dbug::update(THD *thd, set_var *var) +{ + if (var->type == OPT_GLOBAL) + DBUG_SET_INITIAL(var ? var->value->str_value.c_ptr() : ""); + else + DBUG_SET(var ? var->value->str_value.c_ptr() : ""); + + return 0; +} + + +uchar *sys_var_thd_dbug::value_ptr(THD *thd, enum_var_type type, LEX_STRING *b) +{ + char buf[256]; + if (type == OPT_GLOBAL) + DBUG_EXPLAIN_INITIAL(buf, sizeof(buf)); + else + DBUG_EXPLAIN(buf, sizeof(buf)); + return (uchar*) thd->strdup(buf); +} + +#ifdef HAVE_EVENT_SCHEDULER +bool sys_var_event_scheduler::check(THD *thd, set_var *var) +{ + return check_enum(thd, var, &Events::var_typelib); +} + +/* + The update method of the global variable event_scheduler. + If event_scheduler is switched from 0 to 1 then the scheduler main + thread is resumed and if from 1 to 0 the scheduler thread is suspended + + SYNOPSIS + sys_var_event_scheduler::update() + thd Thread context (unused) + var The new value + + Returns + FALSE OK + TRUE Error +*/ + +bool +sys_var_event_scheduler::update(THD *thd, set_var *var) +{ + int res; + /* here start the thread if not running. */ + DBUG_ENTER("sys_var_event_scheduler::update"); + DBUG_PRINT("info", ("new_value: %d", (int) var->save_result.ulong_value)); + + enum Events::enum_opt_event_scheduler + new_state= + (enum Events::enum_opt_event_scheduler) var->save_result.ulong_value; + + res= Events::switch_event_scheduler_state(new_state); + + DBUG_RETURN((bool) res); +} + + +uchar *sys_var_event_scheduler::value_ptr(THD *thd, enum_var_type type, + LEX_STRING *base) +{ + return (uchar *) Events::get_opt_event_scheduler_str(); +} +#endif + +/**************************************************************************** + Used templates +****************************************************************************/ + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +template class List; +template class List_iterator_fast; +template class I_List_iterator; +#endif diff --git a/dbcon/mysql/sm.cpp b/dbcon/mysql/sm.cpp deleted file mode 100644 index f48ed66f..00000000 --- a/dbcon/mysql/sm.cpp +++ /dev/null @@ -1,460 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** - * $Id: sm.cpp 9254 2013-02-04 19:40:31Z rdempsey $ - * - ***********************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#if __FreeBSD__ -typedef sig_t sighandler_t; -#endif -using namespace std; - -#include - -#include "calpontsystemcatalog.h" -using namespace execplan; - -#include "bytestream.h" -using namespace messageqcpp; - -#include "errorcodes.h" -using namespace logging; - -#include "querystats.h" -using namespace querystats; - -#include "sm.h" - -namespace { -using namespace sm; - -// @bug 159 fix. clean up routine when error happened -void cleanup(cpsm_conhdl_t* hndl) -{ - // remove system catalog instance for this statement. - CalpontSystemCatalog::removeCalpontSystemCatalog(hndl->sessionID); - hndl->queryState = NO_QUERY; - hndl->resultSet.erase(hndl->resultSet.begin(), hndl->resultSet.end()); -} - -status_t tpl_scan_fetch_getband(cpsm_conhdl_t* hndl, sp_cpsm_tplsch_t& ntplsch, int* killed) -{ - // @bug 649 check keybandmap first - map::iterator keyBandMapIter = hndl->keyBandMap.find(ntplsch->key); - - try { - if (keyBandMapIter != hndl->keyBandMap.end()) - { - ByteStream bs; - ostringstream oss; - oss << DEFAULT_SAVE_PATH << '/' << hndl->sessionID << '/' << ntplsch->key << '_' << ntplsch->bandID << ".band"; - ifstream bandFile (oss.str().c_str(), ios::in); - bandFile >> bs; - unlink (oss.str().c_str()); - - // not possible for vtable - ntplsch->deserializeTable(bs); - ntplsch->bandID++; - - // end of result set - if (ntplsch->bandID == keyBandMapIter->second) - { - hndl->keyBandMap.erase(keyBandMapIter); - return SQL_NOT_FOUND; - } - } - else - { - ByteStream bs; - // @bug 626. check saveFlag. If SAVING, read band from socket and save to disk - if (ntplsch->saveFlag == SAVING) - { - ByteStream bs; - // @bug 2244. Bypass ClientRotator::read() because if I/O error occurs, it tries - // to reestablish a connection with ExeMgr which ends up causing mysql - // session to hang. - bs = hndl->exeMgr->read(); - ostringstream oss; - oss << DEFAULT_SAVE_PATH << '/' << hndl->sessionID << '/' << ntplsch->tableid << '_' << ntplsch->bandsReturned << ".band"; - ofstream saveFile (oss.str().c_str(), ios::out); - saveFile << bs; - saveFile.close(); - ntplsch->bandsReturned++; - // not possible for vtable - ntplsch->deserializeTable(bs); - } - // if SAVED, read from saved file. not possible for vtable - else if (ntplsch->saveFlag == SAVED) - { - ostringstream oss; - oss << DEFAULT_SAVE_PATH << '/' << hndl->sessionID << '/' << ntplsch->tableid << '_' << ntplsch->bandsReturned << ".band"; - ifstream saveFile (oss.str().c_str(), ios::in); - saveFile >> bs; - saveFile.close(); - ntplsch->bandsReturned++; - ntplsch->deserializeTable(bs); - } - // most normal path. also the path for vtable - else - { - ntplsch->bs.restart(); - // @bug 2244. Bypass ClientRotator::read() because if I/O error occurs, it tries - // to reestablish a connection with ExeMgr which ends up causing mysql - // session to hang. - // @bug 3386. need to abort the query when user does ctrl+c - timespec t; - t.tv_sec = 5L; - t.tv_nsec = 0L; - if (killed && *killed) - return SQL_KILLED; - ntplsch->bs = hndl->exeMgr->read(); - - if (ntplsch->bs.length() != 0) - { - ntplsch->deserializeTable(ntplsch->bs); - if (ntplsch->rowGroup && ntplsch->rowGroup->getRGData() == NULL) - { - ntplsch->bs.restart(); - // @bug 2244. Bypass ClientRotator::read() because if I/O error occurs, it tries - // to reestablish a connection with ExeMgr which ends up causing mysql - // session to hang. - bool timeout = true; - while (timeout) - { - timeout = false; - ntplsch->bs = hndl->exeMgr->getClient()->read(&t, &timeout); - - if (killed && *killed) - return SQL_KILLED; - } - - if (ntplsch->bs.length() == 0) - { - hndl->curFetchTb = 0; - return logging::ERR_LOST_CONN_EXEMGR; - } - ntplsch->deserializeTable(ntplsch->bs); - } - - uint16_t error = ntplsch->getStatus(); - if (0 != error) - { - ntplsch->setErrMsg(); - return error; - } - } - else // @todo error handling - { - hndl->curFetchTb = 0; - if (ntplsch->saveFlag == NO_SAVE) - hndl->tidScanMap[ntplsch->tableid] = ntplsch; - ntplsch->errMsg = IDBErrorInfo::instance()->errorMsg(ERR_LOST_CONN_EXEMGR); - return logging::ERR_LOST_CONN_EXEMGR; - } - } - - // All done with this table. reset curFetchTb when finish SOCKET reading - if (ntplsch->getRowCount() == 0) - { - hndl->curFetchTb = 0; - if (ntplsch->saveFlag == NO_SAVE) - hndl->tidScanMap[ntplsch->tableid] = ntplsch; - return SQL_NOT_FOUND; - } - } - } catch (std::exception &e) - { - hndl->curFetchTb = 0; - if (ntplsch->saveFlag == NO_SAVE) - hndl->tidScanMap[ntplsch->tableid] = ntplsch; - ntplsch->errMsg = e.what(); - return logging::ERR_LOST_CONN_EXEMGR; - } - ntplsch->rowsreturned = 0; - return STATUS_OK; -} - -void end_query(cpsm_conhdl_t* hndl) -{ - // remove system catalog instance for this statement. - // @bug 695. turn on system catalog session cache for FE - // CalpontSystemCatalog::removeCalpontSystemCatalog(hndl->sessionID); - hndl->queryState = NO_QUERY; - // reset at the end of query - hndl->curFetchTb = 0; - // @bug 626 clear up - hndl->tidMap.clear(); - hndl->tidScanMap.clear(); - hndl->keyBandMap.clear(); - // Tell ExeMgr we are done with this query - try { - ByteStream bs; - ByteStream::quadbyte qb = 0; - bs << qb; - hndl->write(bs); - } - catch(...) - { - throw; - } -} - -// @bug 1054, 863 - SIGPIPE handler -bool sigFlag = false; -void sighandler(int sig_num) -{ - FILE* p; - char buf[1024]; - - if ((p = fopen("/tmp/f1.dat", "a")) != NULL) - { - snprintf(buf, 1024, "sighandler() hit with %d\n", sig_num); - fwrite(buf, 1, strlen(buf), p); - fclose(p); - } - sigFlag = true; - throw runtime_error("zerror"); -} - -} - -namespace sm -{ -#ifdef _MSC_VER - const std::string DEFAULT_SAVE_PATH = "C:\\Calpont\\tmp"; -#else - const std::string DEFAULT_SAVE_PATH = "/var/tmp"; -#endif - -status_t -tpl_open ( tableid_t tableid, - cpsm_tplh_t* ntplh, - cpsm_conhdl_t* conn_hdl) -{ - SMDEBUGLOG << "tpl_open: " << conn_hdl << " tableid: " << tableid << endl; - - // if first time enter this function for a statement, set - // queryState to QUERY_IN_PRCOESS and get execution plan. - if (conn_hdl->queryState == NO_QUERY) - { - conn_hdl->queryState = QUERY_IN_PROCESS; - } - - try { - // @bug 626. check saveFlag, if SAVED, do not project - if (ntplh->saveFlag != SAVED) - { - // Request ExeMgr to start projecting table tableid - CalpontSystemCatalog::OID tableOID = static_cast(tableid); - ByteStream::quadbyte qb = static_cast(tableOID); - ByteStream bs; - bs << qb; - conn_hdl->write(bs); - } - } - catch (std::exception& ex) - { - SMDEBUGLOG << "Exception caught in tpl_open: " << ex.what() << endl; - cleanup(conn_hdl); - return CALPONT_INTERNAL_ERROR; - } - - ntplh->tableid = tableid; - - return STATUS_OK; -} - -status_t -tpl_scan_open ( tableid_t tableid, - sp_cpsm_tplsch_t& ntplsch, - cpsm_conhdl_t* conn_hdl ) -{ - SMDEBUGLOG << "tpl_scan_open: " << conn_hdl << " tableid: " << tableid << endl; - - // @bug 649. No initialization here. take passed in reference - ntplsch->tableid = tableid; - - ntplsch->rowsreturned = 0; - return STATUS_OK; -} - -status_t -tpl_scan_fetch ( sp_cpsm_tplsch_t& ntplsch, - cpsm_conhdl_t* conn_hdl, - int* killed ) -{ - // @770. force end of result set when this is not the first table to be fetched. - if (ntplsch->traceFlags & CalpontSelectExecutionPlan::TRACE_NO_ROWS2) - if (conn_hdl->tidScanMap.size() >= 1) - return SQL_NOT_FOUND; - - // need another band - status_t status = STATUS_OK; - if (ntplsch->rowsreturned == ntplsch->getRowCount()) - status = tpl_scan_fetch_getband(conn_hdl, ntplsch, killed); - - return status; -} - -status_t -tpl_scan_close ( sp_cpsm_tplsch_t& ntplsch ) -{ -#if IDB_SM_DEBUG - SMDEBUGLOG << "tpl_scan_close: "; - if (ntplsch) - SMDEBUGLOG << " tableid: " << ntplsch->tableid << endl; -#endif - ntplsch.reset(); - - return STATUS_OK; -} - -status_t -tpl_close ( cpsm_tplh_t* ntplh, - cpsm_conhdl_t** conn_hdl, - QueryStats& stats ) -{ - cpsm_conhdl_t* hndl = *conn_hdl; -#if IDB_SM_DEBUG - SMDEBUGLOG << "tpl_close: " << hndl; - if (ntplh) - SMDEBUGLOG << " tableid: " << ntplh->tableid; - SMDEBUGLOG << endl; -#endif - delete ntplh; - - // determine end of result set and end of statement execution - if (hndl->queryState == QUERY_IN_PROCESS) - { - // Get the query stats - ByteStream bs; - ByteStream::quadbyte qb = 3; - bs << qb; - hndl->write(bs); - //keep reading until we get a string - //TODO: really need to fix this! Why is ExeMgr sending other stuff? - for (int tries = 0; tries < 10; tries++) - { - bs = hndl->exeMgr->read(); - if (bs.length() == 0) break; - try { - bs >> hndl->queryStats; - bs >> hndl->extendedStats; - bs >> hndl->miniStats; - stats.unserialize(bs); - stats.setEndTime(); - stats.insert(); - break; - } catch (IDBExcept&) - { - // @bug4732 - end_query(hndl); - throw; - } - catch (...) { - // querystats messed up. close connection. - // no need to throw for querystats protocol error, like for tablemode. - end_query(hndl); - sm_cleanup(hndl); - *conn_hdl = 0; - return STATUS_OK; - //throw runtime_error(string("tbl_close catch exception: ") + e.what()); - } - } - end_query(hndl); - } - return STATUS_OK; -} - -status_t -sm_init ( uint32_t sid, - cpsm_conhdl_t **conn_hdl, - uint32_t infinidb_local_query) -{ - // clear file content -#if IDB_SM_DEBUG - smlog.close(); - smlog.open("/tmp/sm.log"); - SMDEBUGLOG << "sm_init: " << dboptions << endl; -#endif - - // @bug5660 Connection changes related to the local pm setting - /** - * when local PM is detected, or infinidb_local_query is set: - * 1. SELECT query connect to local ExeMgr 127.0.0.1:8601; - * 2. DML/DDL is disallowed. - * once local connection is determined, no need to check - * again because it will not switch back. - **/ - if (*conn_hdl) - { - // existing connection is local, ok. - if ((*conn_hdl)->exeMgr->localQuery() || ! infinidb_local_query) - return STATUS_OK; - // if session variable changes to local, re-establish the connection to loopback. - else - sm_cleanup(*conn_hdl); - } - - cpsm_conhdl_t* hndl = new cpsm_conhdl_t(time(0), sid, infinidb_local_query); - *conn_hdl = hndl; - hndl->sessionID = sid; - - // profiling statistics - GET_PF_TIME(hndl->pf.login); - - return STATUS_OK; -} - -status_t -sm_cleanup ( cpsm_conhdl_t* conn_hdl ) -{ -#if IDB_SM_DEBUG - SMDEBUGLOG << "sm_cleanup: " << conn_hdl << endl; - SMDEBUGLOG.close(); -#endif - - delete conn_hdl; - - return STATUS_OK; -} - -void cpsm_conhdl_t::write(ByteStream bs) -{ -#ifdef _MSC_VER - exeMgr->write(bs); -#else - sighandler_t old_handler = signal(SIGPIPE, sighandler); - sigFlag = false; - exeMgr->write(bs); - signal(SIGPIPE, old_handler); - if (sigFlag) - throw runtime_error("Broken Pipe Error"); -#endif -} - -} diff --git a/dbcon/mysql/sm.h b/dbcon/mysql/sm.h deleted file mode 100644 index 2d1ffde1..00000000 --- a/dbcon/mysql/sm.h +++ /dev/null @@ -1,279 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*********************************************************************** - * $Id: sm.h 9254 2013-02-04 19:40:31Z rdempsey $ - * - ***********************************************************************/ -/** @file */ - -#ifndef SM_H__ -#define SM_H__ - -#include -#include -#include -#include -#include -#include - -#include "calpontsystemcatalog.h" -#include "clientrotator.h" -#include "rowgroup.h" -#include "calpontselectexecutionplan.h" -#include "querystats.h" - -#define IDB_SM_DEBUG 0 -#define IDB_SM_PROFILE 0 - -#if defined(_MSC_VER) && defined(xxxDLLEXPORT) -#define EXPORT __declspec(dllexport) -#else -#define EXPORT -#endif - -#if IDB_SM_PROFILE -#include -#define GET_PF_TIME(n) {gettimeofday(&n, NULL);} -#else -#define GET_PF_TIME(n) {} -#endif - -namespace sm -{ -const int STATUS_OK=0; -const int SQL_NOT_FOUND=-1000; -const int SQL_KILLED=-1001; -const int CALPONT_INTERNAL_ERROR=-1007; - -#if IDB_SM_DEBUG -extern std::ofstream smlog; -#define SMDEBUGLOG smlog -#else -#define SMDEBUGLOG if (false) std::cerr -#endif -extern const std::string DEFAULT_SAVE_PATH; - -typedef uint64_t tableid_t; -typedef int32_t status_t; - -enum QueryState -{ - NO_QUERY = 0, - QUERY_IN_PROCESS -}; - -typedef struct Column { - Column():tableID(-1) {} - ~Column() {} - int tableID; - int colPos; - int dataType; - std::vector data; -} Column; - -typedef std::map ResultMap; - -struct Profiler -{ - struct timeval login; - struct timeval beforePlan; - struct timeval afterPlan; - struct timeval resultArrival; - struct timeval resultReady; - struct timeval endProcess; - long prePlan(){ - return (beforePlan.tv_sec-login.tv_sec) * 1000 + - (beforePlan.tv_usec - login.tv_usec)/1000; } - long buildPlan() { - return (afterPlan.tv_sec - beforePlan.tv_sec) * 1000 + - (afterPlan.tv_usec - beforePlan.tv_usec)/1000; } - long jobProcess() { - return (resultArrival.tv_sec - afterPlan.tv_sec) * 1000 + - (resultArrival.tv_usec - afterPlan.tv_usec)/1000; } - long buildResult() { - return (resultReady.tv_sec - resultArrival.tv_sec) * 1000 + - (resultReady.tv_usec - resultArrival.tv_usec)/1000; } - long tableFetch () { - return (endProcess.tv_sec - resultReady.tv_sec) * 1000 + - (endProcess.tv_usec - resultReady.tv_usec)/1000; } -}; - -/** @brief Calpont table scan handle */ -struct cpsm_tplsch_t -{ - cpsm_tplsch_t() : tableid(0), rowsreturned(0), rowGroup(0), traceFlags(0), bandID(0), saveFlag(0), bandsReturned(0), - ctp(0) {} - ~cpsm_tplsch_t() - { - delete rowGroup; - } - - tableid_t tableid; - uint64_t rowsreturned; - rowgroup::RowGroup *rowGroup; - messageqcpp::ByteStream bs; // rowgroup bytestream. need to stay with the life span of rowgroup - uint32_t traceFlags; - // @bug 649 - int bandID; // the band that being read from the disk - int key; // unique key for the table's scan context - // @bug 626 - uint16_t saveFlag; - uint32_t bandsReturned; - std::vector ctp; - std::string errMsg; - rowgroup::RGData rgData; - void deserializeTable(messageqcpp::ByteStream& bs) - { - if (!rowGroup) - { - rowGroup = new rowgroup::RowGroup(); - rowGroup->deserialize(bs); - } - else - { - // XXXST: the 'true' is to ease the transition to RGDatas. Take it out when the - // transition is done. - rgData.deserialize(bs, true); - rowGroup->setData(&rgData); - //rowGroup->setData(const_cast(bs.buf())); - } - } - - uint16_t getStatus() - { - idbassert(rowGroup != 0); - return rowGroup->getStatus(); - } - - uint64_t getRowCount() - { - if (rowGroup) - return rowGroup->getRowCount(); - else - return 0; - } - - void setErrMsg() - { - if (rowGroup && getStatus()) - { - //bs.advance(rowGroup->getDataSize()); - bs >> errMsg; - } - else - { - errMsg = "NOERROR"; - } - } -}; -typedef boost::shared_ptr sp_cpsm_tplsch_t; - -/** @brief Calpont connection handle structure */ -class cpsm_conhdl_t -{ -public: - cpsm_conhdl_t(time_t v, const uint32_t sid, bool infinidb_local_query) : - value(v), sessionID(sid), queryState (NO_QUERY), - exeMgr( new execplan::ClientRotator(sid, "ExeMgr", infinidb_local_query)), - tblinfo_idx(0), idxinfo_idx(0), curFetchTb (0) - { } - - -/** @brief connnect ExeMgr - * - * Try connecting to ExeMgr. If no connection, try ExeMgr1, - * ExeMgr2... until timeout lapses. Then throw exception. - */ - void connect(double timeout=0.005) { - exeMgr->connect(timeout); - } - EXPORT void write(messageqcpp::ByteStream bs); - - ~cpsm_conhdl_t() { - delete exeMgr; - } - EXPORT const std::string toString() const; - time_t value; - uint32_t sessionID; - short queryState; // 0 -- NO_QUERY; 1 -- QUERY_IN_PROCESS - execplan::ClientRotator* exeMgr; - ResultMap resultSet; - Profiler pf; - int tblinfo_idx; - int idxinfo_idx; - std::string schemaname; - std::string tablename; - int tboid; - short requestType; // 0 -- ID2NAME; 1 -- NAME2ID - boost::shared_ptr csc; - // @bug 649; @bug 626 - std::map tidMap; // tableid-tableStartCount map - std::map tidScanMap; - std::map keyBandMap; // key-savedBandCount map - int curFetchTb; // current fetching table key - std::string queryStats; - std::string extendedStats; - std::string miniStats; -private: -}; -std::ostream& operator<<(std::ostream& output, const cpsm_conhdl_t& rhs); - -// @bug 626 save table bands to avoid sending plan too many times -enum SavingFlag -{ - NO_SAVE = 0, - SAVING, - SAVED -}; - -/** @brief Calpont table handle */ -struct cpsm_tplh_t -{ - cpsm_tplh_t() : tableid(0), rowsintable(0), bandID(0), saveFlag(NO_SAVE), bandsInTable(0) {} - tableid_t tableid; - int rowsintable; - // @bug 649 - int bandID; // the band that being read from the disk - int key; // unique key for the table's scan context - // @bug 626 - uint16_t saveFlag; - int bandsInTable; -}; - -struct cpsm_tid_t -{ - cpsm_tid_t() : valid(false), value(0) {} - bool valid; - int value; -}; - -extern status_t sm_init(uint32_t, cpsm_conhdl_t**, uint32_t infinidb_local_query = false); -extern status_t sm_cleanup(cpsm_conhdl_t*); - -extern status_t tpl_open(tableid_t, cpsm_tplh_t*, cpsm_conhdl_t*); -extern status_t tpl_scan_open(tableid_t, sp_cpsm_tplsch_t&, cpsm_conhdl_t*); -extern status_t tpl_scan_fetch(sp_cpsm_tplsch_t&, cpsm_conhdl_t*, int* k=0); -extern status_t tpl_scan_close(sp_cpsm_tplsch_t&); -extern status_t tpl_close(cpsm_tplh_t*, cpsm_conhdl_t**, querystats::QueryStats& stats); - -} - -#undef EXPORT - -#endif - diff --git a/dbcon/mysql/sp_head.h b/dbcon/mysql/sp_head.h new file mode 100644 index 00000000..6ffd7f9c --- /dev/null +++ b/dbcon/mysql/sp_head.h @@ -0,0 +1,1341 @@ +/* -*- C++ -*- */ +/* Copyright (C) 2002 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#ifndef _SP_HEAD_H_ +#define _SP_HEAD_H_ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +#include + +/** + @defgroup Stored_Routines Stored Routines + @ingroup Runtime_Environment + @{ +*/ +// Values for the type enum. This reflects the order of the enum declaration +// in the CREATE TABLE command. +#define TYPE_ENUM_FUNCTION 1 +#define TYPE_ENUM_PROCEDURE 2 +#define TYPE_ENUM_TRIGGER 3 + +Item_result +sp_map_result_type(enum enum_field_types type); + +Item::Type +sp_map_item_type(enum enum_field_types type); + +uint +sp_get_flags_for_command(LEX *lex); + +struct sp_label; +class sp_instr; +class sp_instr_opt_meta; +class sp_instr_jump_if_not; +struct sp_cond_type; +struct sp_variable; + +/*************************************************************************/ + +/** + Stored_program_creation_ctx -- base class for creation context of stored + programs (stored routines, triggers, events). +*/ + +class Stored_program_creation_ctx :public Default_object_creation_ctx +{ +public: + CHARSET_INFO *get_db_cl() + { + return m_db_cl; + } + +public: + virtual Stored_program_creation_ctx *clone(MEM_ROOT *mem_root) = 0; + +protected: + Stored_program_creation_ctx(THD *thd) + : Default_object_creation_ctx(thd), + m_db_cl(thd->variables.collation_database) + { } + + Stored_program_creation_ctx(CHARSET_INFO *client_cs, + CHARSET_INFO *connection_cl, + CHARSET_INFO *db_cl) + : Default_object_creation_ctx(client_cs, connection_cl), + m_db_cl(db_cl) + { } + +protected: + virtual void change_env(THD *thd) const + { + thd->variables.collation_database= m_db_cl; + + Default_object_creation_ctx::change_env(thd); + } + +protected: + /** + db_cl stores the value of the database collation. Both character set + and collation attributes are used. + + Database collation is included into the context because it defines the + default collation for stored-program variables. + */ + CHARSET_INFO *m_db_cl; +}; + +/*************************************************************************/ + +class sp_name : public Sql_alloc +{ +public: + + LEX_STRING m_db; + LEX_STRING m_name; + LEX_STRING m_qname; + /** + Key representing routine in the set of stored routines used by statement. + Consists of 1-byte routine type and m_qname (which usually refences to + same buffer). Note that one must complete initialization of the key by + calling set_routine_type(). + */ + LEX_STRING m_sroutines_key; + bool m_explicit_name; /**< Prepend the db name? */ + + sp_name(LEX_STRING db, LEX_STRING name, bool use_explicit_name) + : m_db(db), m_name(name), m_explicit_name(use_explicit_name) + { + m_qname.str= m_sroutines_key.str= 0; + m_qname.length= m_sroutines_key.length= 0; + } + + /** + Creates temporary sp_name object from key, used mainly + for SP-cache lookups. + */ + sp_name(THD *thd, char *key, uint key_len); + + // Init. the qualified name from the db and name. + void init_qname(THD *thd); // thd for memroot allocation + + void set_routine_type(char type) + { + m_sroutines_key.str[0]= type; + } + + ~sp_name() + {} +}; + + +bool +check_routine_name(LEX_STRING *ident); + +class sp_head :private Query_arena +{ + sp_head(const sp_head &); /**< Prevent use of these */ + void operator=(sp_head &); + + MEM_ROOT main_mem_root; +public: + /** Possible values of m_flags */ + enum { + HAS_RETURN= 1, // For FUNCTIONs only: is set if has RETURN + MULTI_RESULTS= 8, // Is set if a procedure with SELECT(s) + CONTAINS_DYNAMIC_SQL= 16, // Is set if a procedure with PREPARE/EXECUTE + IS_INVOKED= 32, // Is set if this sp_head is being used + HAS_SET_AUTOCOMMIT_STMT= 64,// Is set if a procedure with 'set autocommit' + /* Is set if a procedure with COMMIT (implicit or explicit) | ROLLBACK */ + HAS_COMMIT_OR_ROLLBACK= 128, + LOG_SLOW_STATEMENTS= 256, // Used by events + LOG_GENERAL_LOG= 512, // Used by events + BINLOG_ROW_BASED_IF_MIXED= 1024, + HAS_SQLCOM_RESET= 2048, + HAS_SQLCOM_FLUSH= 4096 + }; + + /** TYPE_ENUM_FUNCTION, TYPE_ENUM_PROCEDURE or TYPE_ENUM_TRIGGER */ + int m_type; + uint m_flags; // Boolean attributes of a stored routine + + Create_field m_return_field_def; /**< This is used for FUNCTIONs only. */ + + const char *m_tmp_query; ///< Temporary pointer to sub query string + st_sp_chistics *m_chistics; + ulong m_sql_mode; ///< For SHOW CREATE and execution + LEX_STRING m_qname; ///< db.name + bool m_explicit_name; ///< Prepend the db name? */ + /** + Key representing routine in the set of stored routines used by statement. + [routine_type]db.name + @sa sp_name::m_sroutines_key + */ + LEX_STRING m_sroutines_key; + LEX_STRING m_db; + LEX_STRING m_name; + LEX_STRING m_params; + LEX_STRING m_body; + LEX_STRING m_body_utf8; + LEX_STRING m_defstr; + LEX_STRING m_definer_user; + LEX_STRING m_definer_host; + +private: + Stored_program_creation_ctx *m_creation_ctx; + +public: + inline Stored_program_creation_ctx *get_creation_ctx() + { + return m_creation_ctx; + } + + inline void set_creation_ctx(Stored_program_creation_ctx *creation_ctx) + { + m_creation_ctx= creation_ctx->clone(mem_root); + } + + longlong m_created; + longlong m_modified; + /** Recursion level of the current SP instance. The levels are numbered from 0 */ + ulong m_recursion_level; + /** + A list of diferent recursion level instances for the same procedure. + For every recursion level we have a sp_head instance. This instances + connected in the list. The list ordered by increasing recursion level + (m_recursion_level). + */ + sp_head *m_next_cached_sp; + /** + Pointer to the first element of the above list + */ + sp_head *m_first_instance; + /** + Pointer to the first free (non-INVOKED) routine in the list of + cached instances for this SP. This pointer is set only for the first + SP in the list of instences (see above m_first_cached_sp pointer). + The pointer equal to 0 if we have no free instances. + For non-first instance value of this pointer meanless (point to itself); + */ + sp_head *m_first_free_instance; + /** + Pointer to the last element in the list of instances of the SP. + For non-first instance value of this pointer meanless (point to itself); + */ + sp_head *m_last_cached_sp; + /** + Set containing names of stored routines used by this routine. + Note that unlike elements of similar set for statement elements of this + set are not linked in one list. Because of this we are able save memory + by using for this set same objects that are used in 'sroutines' sets + for statements of which this stored routine consists. + */ + HASH m_sroutines; + // Pointers set during parsing + const char *m_param_begin; + const char *m_param_end; + +private: + const char *m_body_begin; + +public: + /* + Security context for stored routine which should be run under + definer privileges. + */ + Security_context m_security_ctx; + + static void * + operator new(size_t size) throw (); + + static void + operator delete(void *ptr, size_t size) throw (); + + sp_head(); + + /// Initialize after we have reset mem_root + void + init(LEX *lex); + + /** Copy sp name from parser. */ + void + init_sp_name(THD *thd, sp_name *spname); + + /** Set the body-definition start position. */ + void + set_body_start(THD *thd, const char *begin_ptr); + + /** Set the statement-definition (body-definition) end position. */ + void + set_stmt_end(THD *thd); + + int + create(THD *thd); + + virtual ~sp_head(); + + /// Free memory + void + destroy(); + + bool + execute_trigger(THD *thd, + const LEX_STRING *db_name, + const LEX_STRING *table_name, + GRANT_INFO *grant_info); + + bool + execute_function(THD *thd, Item **args, uint argcount, Field *return_fld); + + bool + execute_procedure(THD *thd, List *args); + + bool + show_create_routine(THD *thd, int type); + + int + add_instr(sp_instr *instr); + + inline uint + instructions() + { + return m_instr.elements; + } + + inline sp_instr * + last_instruction() + { + sp_instr *i; + + get_dynamic(&m_instr, (uchar*)&i, m_instr.elements-1); + return i; + } + + /* + Resets lex in 'thd' and keeps a copy of the old one. + + @todo Conflicting comment in sp_head.cc + */ + bool + reset_lex(THD *thd); + + /** + Restores lex in 'thd' from our copy, but keeps some status from the + one in 'thd', like ptr, tables, fields, etc. + + @todo Conflicting comment in sp_head.cc + */ + void + restore_lex(THD *thd); + + /// Put the instruction on the backpatch list, associated with the label. + int + push_backpatch(sp_instr *, struct sp_label *); + + /// Update all instruction with this label in the backpatch list to + /// the current position. + void + backpatch(struct sp_label *); + + /// Start a new cont. backpatch level. If 'i' is NULL, the level is just incr. + int + new_cont_backpatch(sp_instr_opt_meta *i); + + /// Add an instruction to the current level + int + add_cont_backpatch(sp_instr_opt_meta *i); + + /// Backpatch (and pop) the current level to the current position. + void + do_cont_backpatch(); + + char *name(uint *lenp = 0) const + { + if (lenp) + *lenp= (uint) m_name.length; + return m_name.str; + } + + char *create_string(THD *thd, ulong *lenp); + + Field *create_result_field(uint field_max_length, const char *field_name, + TABLE *table); + + bool fill_field_definition(THD *thd, LEX *lex, + enum enum_field_types field_type, + Create_field *field_def); + + void set_info(longlong created, longlong modified, + st_sp_chistics *chistics, ulong sql_mode); + + void set_definer(const char *definer, uint definerlen); + void set_definer(const LEX_STRING *user_name, const LEX_STRING *host_name); + + void reset_thd_mem_root(THD *thd); + + void restore_thd_mem_root(THD *thd); + + /** + Optimize the code. + */ + void optimize(); + + /** + Helper used during flow analysis during code optimization. + See the implementation of opt_mark(). + @param ip the instruction to add to the leads list + @param leads the list of remaining paths to explore in the graph that + represents the code, during flow analysis. + */ + void add_mark_lead(uint ip, List *leads); + + void recursion_level_error(THD *thd); + + inline sp_instr * + get_instr(uint i) + { + sp_instr *ip; + + if (i < m_instr.elements) + get_dynamic(&m_instr, (uchar*)&ip, i); + else + ip= NULL; + return ip; + } + + /* Add tables used by routine to the table list. */ + bool add_used_tables_to_table_list(THD *thd, + TABLE_LIST ***query_tables_last_ptr, + TABLE_LIST *belong_to_view); + + /** + Check if this stored routine contains statements disallowed + in a stored function or trigger, and set an appropriate error message + if this is the case. + */ + bool is_not_allowed_in_function(const char *where) + { + if (m_flags & CONTAINS_DYNAMIC_SQL) + my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "Dynamic SQL"); + else if (m_flags & MULTI_RESULTS) + my_error(ER_SP_NO_RETSET, MYF(0), where); + else if (m_flags & HAS_SET_AUTOCOMMIT_STMT) + my_error(ER_SP_CANT_SET_AUTOCOMMIT, MYF(0)); + else if (m_flags & HAS_COMMIT_OR_ROLLBACK) + my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); + else if (m_flags & HAS_SQLCOM_RESET) + my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "RESET"); + else if (m_flags & HAS_SQLCOM_FLUSH) + my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "FLUSH"); + + return test(m_flags & + (CONTAINS_DYNAMIC_SQL|MULTI_RESULTS|HAS_SET_AUTOCOMMIT_STMT| + HAS_COMMIT_OR_ROLLBACK|HAS_SQLCOM_RESET|HAS_SQLCOM_FLUSH)); + } + +#ifndef DBUG_OFF + int show_routine_code(THD *thd); +#endif + + /* + This method is intended for attributes of a routine which need + to propagate upwards to the LEX of the caller (when a property of a + sp_head needs to "taint" the caller). + */ + void propagate_attributes(LEX *lex) + { + /* + If this routine needs row-based binary logging, the entire top statement + too (we cannot switch from statement-based to row-based only for this + routine, as in statement-based the top-statement may be binlogged and + the substatements not). + */ + if (m_flags & BINLOG_ROW_BASED_IF_MIXED) + lex->set_stmt_unsafe(); + } + + // InfiniDB adds accessor + sp_pcontext* context() { return m_pcont; } + const uint sp_elements() {return m_instr.elements;} + +private: + + MEM_ROOT *m_thd_root; ///< Temp. store for thd's mem_root + THD *m_thd; ///< Set if we have reset mem_root + + sp_pcontext *m_pcont; ///< Parse context + List m_lex; ///< Temp. store for the other lex + DYNAMIC_ARRAY m_instr; ///< The "instructions" + typedef struct + { + struct sp_label *lab; + sp_instr *instr; + } bp_t; + List m_backpatch; ///< Instructions needing backpatching + /** + We need a special list for backpatching of instructions with a continue + destination (in the case of a continue handler catching an error in + the test), since it would otherwise interfere with the normal backpatch + mechanism - e.g. jump_if_not instructions have two different destinations + which are to be patched differently. + Since these occur in a more restricted way (always the same "level" in + the code), we don't need the label. + */ + List m_cont_backpatch; + uint m_cont_level; // The current cont. backpatch level + + /** + Multi-set representing optimized list of tables to be locked by this + routine. Does not include tables which are used by invoked routines. + + @note + For prelocking-free SPs this multiset is constructed too. + We do so because the same instance of sp_head may be called both + in prelocked mode and in non-prelocked mode. + */ + HASH m_sptabs; + + bool + execute(THD *thd); + + /** + Perform a forward flow analysis in the generated code. + Mark reachable instructions, for the optimizer. + */ + void opt_mark(); + + /** + Merge the list of tables used by query into the multi-set of tables used + by routine. + */ + bool merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check); +}; // class sp_head : public Sql_alloc + + +// +// "Instructions"... +// + +class sp_instr :public Query_arena, public Sql_alloc +{ + sp_instr(const sp_instr &); /**< Prevent use of these */ + void operator=(sp_instr &); + +public: + + uint marked; + uint m_ip; ///< My index + sp_pcontext *m_ctx; ///< My parse context + + /// Should give each a name or type code for debugging purposes? + sp_instr(uint ip, sp_pcontext *ctx) + :Query_arena(0, INITIALIZED_FOR_SP), marked(0), m_ip(ip), m_ctx(ctx) + {} + + virtual ~sp_instr() + { free_items(); } + + + /** + Execute this instruction + + + @param thd Thread handle + @param[out] nextp index of the next instruction to execute. (For most + instructions this will be the instruction following this + one). Note that this parameter is undefined in case of + errors, use get_cont_dest() to find the continuation + instruction for CONTINUE error handlers. + + @retval 0 on success, + @retval other if some error occured + */ + + virtual int execute(THD *thd, uint *nextp) = 0; + + /** + Execute open_and_lock_tables() for this statement. + Open and lock the tables used by this statement, as a pre-requisite + to execute the core logic of this instruction with + exec_core(). + @param thd the current thread + @param tables the list of tables to open and lock + @return zero on success, non zero on failure. + */ + int exec_open_and_lock_tables(THD *thd, TABLE_LIST *tables); + + /** + Get the continuation destination of this instruction. + @return the continuation destination + */ + virtual uint get_cont_dest(); + + /* + Execute core function of instruction after all preparations (e.g. + setting of proper LEX, saving part of the thread context have been + done). + + Should be implemented for instructions using expressions or whole + statements (thus having to have own LEX). Used in concert with + sp_lex_keeper class and its descendants (there are none currently). + */ + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str) = 0; + + virtual void backpatch(uint dest, sp_pcontext *dst_ctx) + {} + + /** + Mark this instruction as reachable during optimization and return the + index to the next instruction. Jump instruction will add their + destination to the leads list. + */ + virtual uint opt_mark(sp_head *sp, List *leads) + { + marked= 1; + return m_ip+1; + } + + /** + Short-cut jumps to jumps during optimization. This is used by the + jump instructions' opt_mark() methods. 'start' is the starting point, + used to prevent the mark sweep from looping for ever. Return the + end destination. + */ + virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) + { + return m_ip; + } + + /** + Inform the instruction that it has been moved during optimization. + Most instructions will simply update its index, but jump instructions + must also take care of their destination pointers. Forward jumps get + pushed to the backpatch list 'ibp'. + */ + virtual void opt_move(uint dst, List *ibp) + { + m_ip= dst; + } + +}; // class sp_instr : public Sql_alloc + + +/** + Auxilary class to which instructions delegate responsibility + for handling LEX and preparations before executing statement + or calculating complex expression. + + Exist mainly to avoid having double hierarchy between instruction + classes. + + @todo + Add ability to not store LEX and do any preparations if + expression used is simple. +*/ + +class sp_lex_keeper +{ + /** Prevent use of these */ + sp_lex_keeper(const sp_lex_keeper &); + void operator=(sp_lex_keeper &); +public: + + sp_lex_keeper(LEX *lex, bool lex_resp) + : m_lex(lex), m_lex_resp(lex_resp), + lex_query_tables_own_last(NULL) + { + lex->sp_lex_in_use= TRUE; + } + virtual ~sp_lex_keeper() + { + if (m_lex_resp) + { + lex_end(m_lex); + delete m_lex; + } + } + + /** + Prepare execution of instruction using LEX, if requested check whenever + we have read access to tables used and open/lock them, call instruction's + exec_core() method, perform cleanup afterwards. + + @todo Conflicting comment in sp_head.cc + */ + int reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, + sp_instr* instr); + + inline uint sql_command() const + { + return (uint)m_lex->sql_command; + } + + void disable_query_cache() + { + m_lex->safe_to_cache_query= 0; + } +private: + + LEX *m_lex; + /** + Indicates whenever this sp_lex_keeper instance responsible + for LEX deletion. + */ + bool m_lex_resp; + + /* + Support for being able to execute this statement in two modes: + a) inside prelocked mode set by the calling procedure or its ancestor. + b) outside of prelocked mode, when this statement enters/leaves + prelocked mode itself. + */ + + /** + List of additional tables this statement needs to lock when it + enters/leaves prelocked mode on its own. + */ + TABLE_LIST *prelocking_tables; + + /** + The value m_lex->query_tables_own_last should be set to this when the + statement enters/leaves prelocked mode on its own. + */ + TABLE_LIST **lex_query_tables_own_last; +}; + + +/** + Call out to some prepared SQL statement. +*/ +class sp_instr_stmt : public sp_instr +{ + sp_instr_stmt(const sp_instr_stmt &); /**< Prevent use of these */ + void operator=(sp_instr_stmt &); + +public: + + LEX_STRING m_query; ///< For thd->query + + sp_instr_stmt(uint ip, sp_pcontext *ctx, LEX *lex) + : sp_instr(ip, ctx), m_lex_keeper(lex, TRUE) + { + m_query.str= 0; + m_query.length= 0; + } + + virtual ~sp_instr_stmt() + {}; + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + + sp_lex_keeper m_lex_keeper; + +}; // class sp_instr_stmt : public sp_instr + + +class sp_instr_set : public sp_instr +{ + sp_instr_set(const sp_instr_set &); /**< Prevent use of these */ + void operator=(sp_instr_set &); + +public: + + sp_instr_set(uint ip, sp_pcontext *ctx, + uint offset, Item *val, enum enum_field_types type_arg, + LEX *lex, bool lex_resp) + : sp_instr(ip, ctx), m_offset(offset), m_value(val), m_type(type_arg), + m_lex_keeper(lex, lex_resp) + {} + + virtual ~sp_instr_set() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + + uint m_offset; ///< Frame offset + Item *m_value; + enum enum_field_types m_type; ///< The declared type + sp_lex_keeper m_lex_keeper; + +}; // class sp_instr_set : public sp_instr + + +/** + Set NEW/OLD row field value instruction. Used in triggers. +*/ +class sp_instr_set_trigger_field : public sp_instr +{ + sp_instr_set_trigger_field(const sp_instr_set_trigger_field &); + void operator=(sp_instr_set_trigger_field &); + +public: + + sp_instr_set_trigger_field(uint ip, sp_pcontext *ctx, + Item_trigger_field *trg_fld, + Item *val, LEX *lex) + : sp_instr(ip, ctx), + trigger_field(trg_fld), + value(val), m_lex_keeper(lex, TRUE) + {} + + virtual ~sp_instr_set_trigger_field() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + Item_trigger_field *trigger_field; + Item *value; + sp_lex_keeper m_lex_keeper; +}; // class sp_instr_trigger_field : public sp_instr + + +/** + An abstract class for all instructions with destinations that + needs to be updated by the optimizer. + + Even if not all subclasses will use both the normal destination and + the continuation destination, we put them both here for simplicity. +*/ +class sp_instr_opt_meta : public sp_instr +{ +public: + + uint m_dest; ///< Where we will go + uint m_cont_dest; ///< Where continue handlers will go + + sp_instr_opt_meta(uint ip, sp_pcontext *ctx) + : sp_instr(ip, ctx), + m_dest(0), m_cont_dest(0), m_optdest(0), m_cont_optdest(0) + {} + + sp_instr_opt_meta(uint ip, sp_pcontext *ctx, uint dest) + : sp_instr(ip, ctx), + m_dest(dest), m_cont_dest(0), m_optdest(0), m_cont_optdest(0) + {} + + virtual ~sp_instr_opt_meta() + {} + + virtual void set_destination(uint old_dest, uint new_dest) + = 0; + + virtual uint get_cont_dest(); + +protected: + + sp_instr *m_optdest; ///< Used during optimization + sp_instr *m_cont_optdest; ///< Used during optimization + +}; // class sp_instr_opt_meta : public sp_instr + +class sp_instr_jump : public sp_instr_opt_meta +{ + sp_instr_jump(const sp_instr_jump &); /**< Prevent use of these */ + void operator=(sp_instr_jump &); + +public: + + sp_instr_jump(uint ip, sp_pcontext *ctx) + : sp_instr_opt_meta(ip, ctx) + {} + + sp_instr_jump(uint ip, sp_pcontext *ctx, uint dest) + : sp_instr_opt_meta(ip, ctx, dest) + {} + + virtual ~sp_instr_jump() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + + virtual uint opt_mark(sp_head *sp, List *leads); + + virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start); + + virtual void opt_move(uint dst, List *ibp); + + virtual void backpatch(uint dest, sp_pcontext *dst_ctx) + { + /* Calling backpatch twice is a logic flaw in jump resolution. */ + DBUG_ASSERT(m_dest == 0); + m_dest= dest; + } + + /** + Update the destination; used by the optimizer. + */ + virtual void set_destination(uint old_dest, uint new_dest) + { + if (m_dest == old_dest) + m_dest= new_dest; + } + +}; // class sp_instr_jump : public sp_instr_opt_meta + + +class sp_instr_jump_if_not : public sp_instr_jump +{ + sp_instr_jump_if_not(const sp_instr_jump_if_not &); /**< Prevent use of these */ + void operator=(sp_instr_jump_if_not &); + +public: + + sp_instr_jump_if_not(uint ip, sp_pcontext *ctx, Item *i, LEX *lex) + : sp_instr_jump(ip, ctx), m_expr(i), + m_lex_keeper(lex, TRUE) + {} + + sp_instr_jump_if_not(uint ip, sp_pcontext *ctx, Item *i, uint dest, LEX *lex) + : sp_instr_jump(ip, ctx, dest), m_expr(i), + m_lex_keeper(lex, TRUE) + {} + + virtual ~sp_instr_jump_if_not() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + + virtual uint opt_mark(sp_head *sp, List *leads); + + /** Override sp_instr_jump's shortcut; we stop here */ + virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) + { + return m_ip; + } + + virtual void opt_move(uint dst, List *ibp); + + virtual void set_destination(uint old_dest, uint new_dest) + { + sp_instr_jump::set_destination(old_dest, new_dest); + if (m_cont_dest == old_dest) + m_cont_dest= new_dest; + } + +private: + + Item *m_expr; ///< The condition + sp_lex_keeper m_lex_keeper; + +}; // class sp_instr_jump_if_not : public sp_instr_jump + + +class sp_instr_freturn : public sp_instr +{ + sp_instr_freturn(const sp_instr_freturn &); /**< Prevent use of these */ + void operator=(sp_instr_freturn &); + +public: + + sp_instr_freturn(uint ip, sp_pcontext *ctx, + Item *val, enum enum_field_types type_arg, LEX *lex) + : sp_instr(ip, ctx), m_value(val), m_type(type_arg), + m_lex_keeper(lex, TRUE) + {} + + virtual ~sp_instr_freturn() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + + virtual uint opt_mark(sp_head *sp, List *leads) + { + marked= 1; + return UINT_MAX; + } + +protected: + + Item *m_value; + enum enum_field_types m_type; + sp_lex_keeper m_lex_keeper; + +}; // class sp_instr_freturn : public sp_instr + + +class sp_instr_hpush_jump : public sp_instr_jump +{ + sp_instr_hpush_jump(const sp_instr_hpush_jump &); /**< Prevent use of these */ + void operator=(sp_instr_hpush_jump &); + +public: + + sp_instr_hpush_jump(uint ip, sp_pcontext *ctx, int htype, uint fp) + : sp_instr_jump(ip, ctx), m_type(htype), m_frame(fp) + { + m_cond.empty(); + } + + virtual ~sp_instr_hpush_jump() + { + m_cond.empty(); + } + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + + virtual uint opt_mark(sp_head *sp, List *leads); + + /** Override sp_instr_jump's shortcut; we stop here. */ + virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) + { + return m_ip; + } + + inline void add_condition(struct sp_cond_type *cond) + { + m_cond.push_front(cond); + } + +private: + + int m_type; ///< Handler type + uint m_frame; + List m_cond; + +}; // class sp_instr_hpush_jump : public sp_instr_jump + + +class sp_instr_hpop : public sp_instr +{ + sp_instr_hpop(const sp_instr_hpop &); /**< Prevent use of these */ + void operator=(sp_instr_hpop &); + +public: + + sp_instr_hpop(uint ip, sp_pcontext *ctx, uint count) + : sp_instr(ip, ctx), m_count(count) + {} + + virtual ~sp_instr_hpop() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + + uint m_count; + +}; // class sp_instr_hpop : public sp_instr + + +class sp_instr_hreturn : public sp_instr_jump +{ + sp_instr_hreturn(const sp_instr_hreturn &); /**< Prevent use of these */ + void operator=(sp_instr_hreturn &); + +public: + + sp_instr_hreturn(uint ip, sp_pcontext *ctx, uint fp) + : sp_instr_jump(ip, ctx), m_frame(fp) + {} + + virtual ~sp_instr_hreturn() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + + /* This instruction will not be short cut optimized. */ + virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) + { + return m_ip; + } + + virtual uint opt_mark(sp_head *sp, List *leads); + +private: + + uint m_frame; + +}; // class sp_instr_hreturn : public sp_instr_jump + + +/** This is DECLARE CURSOR */ +class sp_instr_cpush : public sp_instr +{ + sp_instr_cpush(const sp_instr_cpush &); /**< Prevent use of these */ + void operator=(sp_instr_cpush &); + +public: + + sp_instr_cpush(uint ip, sp_pcontext *ctx, LEX *lex, uint offset) + : sp_instr(ip, ctx), m_lex_keeper(lex, TRUE), m_cursor(offset) + {} + + virtual ~sp_instr_cpush() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + + /** + This call is used to cleanup the instruction when a sensitive + cursor is closed. For now stored procedures always use materialized + cursors and the call is not used. + */ + virtual void cleanup_stmt() { /* no op */ } +private: + + sp_lex_keeper m_lex_keeper; + uint m_cursor; /**< Frame offset (for debugging) */ + +}; // class sp_instr_cpush : public sp_instr + + +class sp_instr_cpop : public sp_instr +{ + sp_instr_cpop(const sp_instr_cpop &); /**< Prevent use of these */ + void operator=(sp_instr_cpop &); + +public: + + sp_instr_cpop(uint ip, sp_pcontext *ctx, uint count) + : sp_instr(ip, ctx), m_count(count) + {} + + virtual ~sp_instr_cpop() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + + uint m_count; + +}; // class sp_instr_cpop : public sp_instr + + +class sp_instr_copen : public sp_instr +{ + sp_instr_copen(const sp_instr_copen &); /**< Prevent use of these */ + void operator=(sp_instr_copen &); + +public: + + sp_instr_copen(uint ip, sp_pcontext *ctx, uint c) + : sp_instr(ip, ctx), m_cursor(c) + {} + + virtual ~sp_instr_copen() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + + uint m_cursor; ///< Stack index + +}; // class sp_instr_copen : public sp_instr_stmt + + +class sp_instr_cclose : public sp_instr +{ + sp_instr_cclose(const sp_instr_cclose &); /**< Prevent use of these */ + void operator=(sp_instr_cclose &); + +public: + + sp_instr_cclose(uint ip, sp_pcontext *ctx, uint c) + : sp_instr(ip, ctx), m_cursor(c) + {} + + virtual ~sp_instr_cclose() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + +private: + + uint m_cursor; + +}; // class sp_instr_cclose : public sp_instr + + +class sp_instr_cfetch : public sp_instr +{ + sp_instr_cfetch(const sp_instr_cfetch &); /**< Prevent use of these */ + void operator=(sp_instr_cfetch &); + +public: + + sp_instr_cfetch(uint ip, sp_pcontext *ctx, uint c) + : sp_instr(ip, ctx), m_cursor(c) + { + m_varlist.empty(); + } + + virtual ~sp_instr_cfetch() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + + void add_to_varlist(struct sp_variable *var) + { + m_varlist.push_back(var); + } + +private: + + uint m_cursor; + List m_varlist; + +}; // class sp_instr_cfetch : public sp_instr + + +class sp_instr_error : public sp_instr +{ + sp_instr_error(const sp_instr_error &); /**< Prevent use of these */ + void operator=(sp_instr_error &); + +public: + + sp_instr_error(uint ip, sp_pcontext *ctx, int errcode) + : sp_instr(ip, ctx), m_errcode(errcode) + {} + + virtual ~sp_instr_error() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual void print(String *str); + + virtual uint opt_mark(sp_head *sp, List *leads) + { + marked= 1; + return UINT_MAX; + } + +private: + + int m_errcode; + +}; // class sp_instr_error : public sp_instr + + +class sp_instr_set_case_expr : public sp_instr_opt_meta +{ +public: + + sp_instr_set_case_expr(uint ip, sp_pcontext *ctx, uint case_expr_id, + Item *case_expr, LEX *lex) + : sp_instr_opt_meta(ip, ctx), + m_case_expr_id(case_expr_id), m_case_expr(case_expr), + m_lex_keeper(lex, TRUE) + {} + + virtual ~sp_instr_set_case_expr() + {} + + virtual int execute(THD *thd, uint *nextp); + + virtual int exec_core(THD *thd, uint *nextp); + + virtual void print(String *str); + + virtual uint opt_mark(sp_head *sp, List *leads); + + virtual void opt_move(uint dst, List *ibp); + + virtual void set_destination(uint old_dest, uint new_dest) + { + if (m_cont_dest == old_dest) + m_cont_dest= new_dest; + } + +private: + + uint m_case_expr_id; + Item *m_case_expr; + sp_lex_keeper m_lex_keeper; + +}; // class sp_instr_set_case_expr : public sp_instr_opt_meta + + +#ifndef NO_EMBEDDED_ACCESS_CHECKS +bool +sp_change_security_context(THD *thd, sp_head *sp, + Security_context **backup); +void +sp_restore_security_context(THD *thd, Security_context *backup); + +bool +set_routine_security_ctx(THD *thd, sp_head *sp, bool is_proc, + Security_context **save_ctx); +#endif /* NO_EMBEDDED_ACCESS_CHECKS */ + +TABLE_LIST * +sp_add_to_query_tables(THD *thd, LEX *lex, + const char *db, const char *name, + thr_lock_type locktype); +Item * +sp_prepare_func_item(THD* thd, Item **it_addr); + +bool +sp_eval_expr(THD *thd, Field *result_field, Item **expr_item_ptr); + +/** + @} (end of group Stored_Routines) +*/ + +#endif /* _SP_HEAD_H_ */ diff --git a/dbcon/mysql/sql_base.cc b/dbcon/mysql/sql_base.cc new file mode 100644 index 00000000..d84498f2 --- /dev/null +++ b/dbcon/mysql/sql_base.cc @@ -0,0 +1,9098 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Basic functions needed by many modules */ + +#include "mysql_priv.h" +#include "sql_select.h" +#include "sp_head.h" +#include "sp.h" +#include "sql_trigger.h" +#include +#include +#include +#ifdef __WIN__ +#include +#endif + +#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "") + +/** + This internal handler is used to trap internally + errors that can occur when executing open table + during the prelocking phase. +*/ +class Prelock_error_handler : public Internal_error_handler +{ +public: + Prelock_error_handler() + : m_handled_errors(0), m_unhandled_errors(0) + {} + + virtual ~Prelock_error_handler() {} + + virtual bool handle_error(uint sql_errno, const char *message, + MYSQL_ERROR::enum_warning_level level, + THD *thd); + + bool safely_trapped_errors(); + +private: + int m_handled_errors; + int m_unhandled_errors; +}; + + +bool +Prelock_error_handler::handle_error(uint sql_errno, + const char * /* message */, + MYSQL_ERROR::enum_warning_level /* level */, + THD * /* thd */) +{ + if (sql_errno == ER_NO_SUCH_TABLE) + { + m_handled_errors++; + return TRUE; + } + + m_unhandled_errors++; + return FALSE; +} + + +bool Prelock_error_handler::safely_trapped_errors() +{ + /* + If m_unhandled_errors != 0, something else, unanticipated, happened, + so the error is not trapped but returned to the caller. + Multiple ER_NO_SUCH_TABLE can be raised in case of views. + */ + return ((m_handled_errors > 0) && (m_unhandled_errors == 0)); +} + +/** + @defgroup Data_Dictionary Data Dictionary + @{ +*/ +TABLE *unused_tables; /* Used by mysql_test */ +HASH open_cache; /* Used by mysql_test */ +static HASH table_def_cache; +static TABLE_SHARE *oldest_unused_share, end_of_unused_share; +static pthread_mutex_t LOCK_table_share; +static bool table_def_inited= 0; + +static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list, + const char *alias, + char *cache_key, uint cache_key_length, + MEM_ROOT *mem_root, uint flags); +static void free_cache_entry(TABLE *entry); +static bool open_new_frm(THD *thd, TABLE_SHARE *share, const char *alias, + uint db_stat, uint prgflag, + uint ha_open_flags, TABLE *outparam, + TABLE_LIST *table_desc, MEM_ROOT *mem_root); +static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks, + bool send_refresh); +static bool +has_two_write_locked_tables_with_auto_increment(TABLE_LIST *tables); + + +extern "C" uchar *table_cache_key(const uchar *record, size_t *length, + my_bool not_used __attribute__((unused))) +{ + TABLE *entry=(TABLE*) record; + *length= entry->s->table_cache_key.length; + return (uchar*) entry->s->table_cache_key.str; +} + + +bool table_cache_init(void) +{ + return hash_init(&open_cache, &my_charset_bin, table_cache_size+16, + 0, 0, table_cache_key, + (hash_free_key) free_cache_entry, 0) != 0; +} + +void table_cache_free(void) +{ + DBUG_ENTER("table_cache_free"); + if (table_def_inited) + { + close_cached_tables(NULL, NULL, FALSE, FALSE, FALSE); + if (!open_cache.records) // Safety first + hash_free(&open_cache); + } + DBUG_VOID_RETURN; +} + +uint cached_open_tables(void) +{ + return open_cache.records; +} + + +#ifdef EXTRA_DEBUG +static void check_unused(void) +{ + uint count= 0, open_files= 0, idx= 0; + TABLE *cur_link,*start_link; + + if ((start_link=cur_link=unused_tables)) + { + do + { + if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next) + { + DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */ + return; /* purecov: inspected */ + } + } while (count++ < open_cache.records && + (cur_link=cur_link->next) != start_link); + if (cur_link != start_link) + { + DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */ + } + } + for (idx=0 ; idx < open_cache.records ; idx++) + { + TABLE *entry=(TABLE*) hash_element(&open_cache,idx); + if (!entry->in_use) + count--; + if (entry->file) + open_files++; + } + if (count != 0) + { + DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */ + count)); /* purecov: inspected */ + } + +#ifdef NOT_SAFE_FOR_REPAIR + /* + check that open cache and table definition cache has same number of + aktive tables + */ + count= 0; + for (idx=0 ; idx < table_def_cache.records ; idx++) + { + TABLE_SHARE *entry= (TABLE_SHARE*) hash_element(&table_def_cache,idx); + count+= entry->ref_count; + } + if (count != open_files) + { + DBUG_PRINT("error", ("table_def ref_count: %u open_cache: %u", + count, open_files)); + DBUG_ASSERT(count == open_files); + } +#endif +} +#else +#define check_unused() +#endif + + +/* + Create a table cache key + + SYNOPSIS + create_table_def_key() + thd Thread handler + key Create key here (must be of size MAX_DBKEY_LENGTH) + table_list Table definition + tmp_table Set if table is a tmp table + + IMPLEMENTATION + The table cache_key is created from: + db_name + \0 + table_name + \0 + + if the table is a tmp table, we add the following to make each tmp table + unique on the slave: + + 4 bytes for master thread id + 4 bytes pseudo thread id + + RETURN + Length of key +*/ + +uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list, + bool tmp_table) +{ + uint key_length= (uint) (strmov(strmov(key, table_list->db)+1, + table_list->table_name)-key)+1; + if (tmp_table) + { + int4store(key + key_length, thd->server_id); + int4store(key + key_length + 4, thd->variables.pseudo_thread_id); + key_length+= TMP_TABLE_KEY_EXTRA; + } + return key_length; +} + + + +/***************************************************************************** + Functions to handle table definition cach (TABLE_SHARE) +*****************************************************************************/ + +extern "C" uchar *table_def_key(const uchar *record, size_t *length, + my_bool not_used __attribute__((unused))) +{ + TABLE_SHARE *entry=(TABLE_SHARE*) record; + *length= entry->table_cache_key.length; + return (uchar*) entry->table_cache_key.str; +} + + +static void table_def_free_entry(TABLE_SHARE *share) +{ + DBUG_ENTER("table_def_free_entry"); + if (share->prev) + { + /* remove from old_unused_share list */ + pthread_mutex_lock(&LOCK_table_share); + *share->prev= share->next; + share->next->prev= share->prev; + pthread_mutex_unlock(&LOCK_table_share); + } + free_table_share(share); + DBUG_VOID_RETURN; +} + + +bool table_def_init(void) +{ + table_def_inited= 1; + pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST); + oldest_unused_share= &end_of_unused_share; + end_of_unused_share.prev= &oldest_unused_share; + + return hash_init(&table_def_cache, &my_charset_bin, table_def_size, + 0, 0, table_def_key, + (hash_free_key) table_def_free_entry, 0) != 0; +} + + +void table_def_free(void) +{ + DBUG_ENTER("table_def_free"); + if (table_def_inited) + { + table_def_inited= 0; + pthread_mutex_destroy(&LOCK_table_share); + hash_free(&table_def_cache); + } + DBUG_VOID_RETURN; +} + + +uint cached_table_definitions(void) +{ + return table_def_cache.records; +} + + +/* + Get TABLE_SHARE for a table. + + get_table_share() + thd Thread handle + table_list Table that should be opened + key Table cache key + key_length Length of key + db_flags Flags to open_table_def(): + OPEN_VIEW + error out: Error code from open_table_def() + + IMPLEMENTATION + Get a table definition from the table definition cache. + If it doesn't exist, create a new from the table definition file. + + NOTES + We must have wrlock on LOCK_open when we come here + (To be changed later) + + RETURN + 0 Error + # Share for table +*/ + +TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key, + uint key_length, uint db_flags, int *error) +{ + TABLE_SHARE *share; + DBUG_ENTER("get_table_share"); + + *error= 0; + + /* Read table definition from cache */ + if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, + key_length))) + goto found; + + if (!(share= alloc_table_share(table_list, key, key_length))) + { + DBUG_RETURN(0); + } + + /* + Lock mutex to be able to read table definition from file without + conflicts + */ + (void) pthread_mutex_lock(&share->mutex); + + /* + We assign a new table id under the protection of the LOCK_open and + the share's own mutex. We do this insted of creating a new mutex + and using it for the sole purpose of serializing accesses to a + static variable, we assign the table id here. We assign it to the + share before inserting it into the table_def_cache to be really + sure that it cannot be read from the cache without having a table + id assigned. + + CAVEAT. This means that the table cannot be used for + binlogging/replication purposes, unless get_table_share() has been + called directly or indirectly. + */ + assign_new_table_id(share); + + if (my_hash_insert(&table_def_cache, (uchar*) share)) + { + free_table_share(share); + DBUG_RETURN(0); // return error + } + if (open_table_def(thd, share, db_flags)) + { + *error= share->error; + (void) hash_delete(&table_def_cache, (uchar*) share); + DBUG_RETURN(0); + } + share->ref_count++; // Mark in use + DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u", + (ulong) share, share->ref_count)); + (void) pthread_mutex_unlock(&share->mutex); + DBUG_RETURN(share); + +found: + /* + We found an existing table definition. Return it if we didn't get + an error when reading the table definition from file. + */ + + /* We must do a lock to ensure that the structure is initialized */ + (void) pthread_mutex_lock(&share->mutex); + if (share->error) + { + /* Table definition contained an error */ + open_table_error(share, share->error, share->open_errno, share->errarg); + (void) pthread_mutex_unlock(&share->mutex); + DBUG_RETURN(0); + } + if (share->is_view && !(db_flags & OPEN_VIEW)) + { + open_table_error(share, 1, ENOENT, 0); + (void) pthread_mutex_unlock(&share->mutex); + DBUG_RETURN(0); + } + + if (!share->ref_count++ && share->prev) + { + /* + Share was not used before and it was in the old_unused_share list + Unlink share from this list + */ + DBUG_PRINT("info", ("Unlinking from not used list")); + pthread_mutex_lock(&LOCK_table_share); + *share->prev= share->next; + share->next->prev= share->prev; + share->next= 0; + share->prev= 0; + pthread_mutex_unlock(&LOCK_table_share); + } + (void) pthread_mutex_unlock(&share->mutex); + + /* Free cache if too big */ + while (table_def_cache.records > table_def_size && + oldest_unused_share->next) + { + pthread_mutex_lock(&oldest_unused_share->mutex); + VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share)); + } + + DBUG_PRINT("exit", ("share: 0x%lx ref_count: %u", + (ulong) share, share->ref_count)); + DBUG_RETURN(share); +} + + +/* + Get a table share. If it didn't exist, try creating it from engine + + For arguments and return values, see get_table_from_share() +*/ + +static TABLE_SHARE +*get_table_share_with_create(THD *thd, TABLE_LIST *table_list, + char *key, uint key_length, + uint db_flags, int *error) +{ + TABLE_SHARE *share; + int tmp; + DBUG_ENTER("get_table_share_with_create"); + + share= get_table_share(thd, table_list, key, key_length, db_flags, error); + /* + If share is not NULL, we found an existing share. + + If share is NULL, and there is no error, we're inside + pre-locking, which silences 'ER_NO_SUCH_TABLE' errors + with the intention to silently drop non-existing tables + from the pre-locking list. In this case we still need to try + auto-discover before returning a NULL share. + + If share is NULL and the error is ER_NO_SUCH_TABLE, this is + the same as above, only that the error was not silenced by + pre-locking. Once again, we need to try to auto-discover + the share. + + Finally, if share is still NULL, it's a real error and we need + to abort. + + @todo Rework alternative ways to deal with ER_NO_SUCH TABLE. + */ + if (share || (thd->is_error() && thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)) + + DBUG_RETURN(share); + + /* Table didn't exist. Check if some engine can provide it */ + tmp= ha_create_table_from_engine(thd, table_list->db, + table_list->table_name); + if (tmp < 0) + { + /* + No such table in any engine. + Hide "Table doesn't exist" errors if the table belongs to a view. + The check for thd->is_error() is necessary to not push an + unwanted error in case of pre-locking, which silences + "no such table" errors. + @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE. + */ + if (thd->is_error()) + { + if (table_list->parent_l) + { + thd->clear_error(); + my_error(ER_WRONG_MRG_TABLE, MYF(0)); + } + else if (table_list->belong_to_view) + { + TABLE_LIST *view= table_list->belong_to_view; + thd->clear_error(); + my_error(ER_VIEW_INVALID, MYF(0), + view->view_db.str, view->view_name.str); + } + } + DBUG_RETURN(0); + } + if (tmp) + { + /* Give right error message */ + thd->clear_error(); + DBUG_PRINT("error", ("Discovery of %s/%s failed", table_list->db, + table_list->table_name)); + my_printf_error(ER_UNKNOWN_ERROR, + "Failed to open '%-.64s', error while " + "unpacking from engine", + MYF(0), table_list->table_name); + DBUG_RETURN(0); + } + /* Table existed in engine. Let's open it */ + mysql_reset_errors(thd, 1); // Clear warnings + thd->clear_error(); // Clear error message + DBUG_RETURN(get_table_share(thd, table_list, key, key_length, + db_flags, error)); +} + + +/* + Mark that we are not using table share anymore. + + SYNOPSIS + release_table_share() + share Table share + release_type How the release should be done: + RELEASE_NORMAL + - Release without checking + RELEASE_WAIT_FOR_DROP + - Don't return until we get a signal that the + table is deleted or the thread is killed. + + IMPLEMENTATION + If ref_count goes to zero and (we have done a refresh or if we have + already too many open table shares) then delete the definition. + + If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal + that the table is deleted or the thread is killed. +*/ + +void release_table_share(TABLE_SHARE *share, enum release_type type) +{ + bool to_be_deleted= 0; + DBUG_ENTER("release_table_share"); + DBUG_PRINT("enter", + ("share: 0x%lx table: %s.%s ref_count: %u version: %lu", + (ulong) share, share->db.str, share->table_name.str, + share->ref_count, share->version)); + + safe_mutex_assert_owner(&LOCK_open); + + pthread_mutex_lock(&share->mutex); + if (!--share->ref_count) + { + if (share->version != refresh_version) + to_be_deleted=1; + else + { + /* Link share last in used_table_share list */ + DBUG_PRINT("info",("moving share to unused list")); + + DBUG_ASSERT(share->next == 0); + pthread_mutex_lock(&LOCK_table_share); + share->prev= end_of_unused_share.prev; + *end_of_unused_share.prev= share; + end_of_unused_share.prev= &share->next; + share->next= &end_of_unused_share; + pthread_mutex_unlock(&LOCK_table_share); + + to_be_deleted= (table_def_cache.records > table_def_size); + } + } + + if (to_be_deleted) + { + DBUG_PRINT("info", ("Deleting share")); + hash_delete(&table_def_cache, (uchar*) share); + DBUG_VOID_RETURN; + } + pthread_mutex_unlock(&share->mutex); + DBUG_VOID_RETURN; +} + + +/* + Check if table definition exits in cache + + SYNOPSIS + get_cached_table_share() + db Database name + table_name Table name + + RETURN + 0 Not cached + # TABLE_SHARE for table +*/ + +TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name) +{ + char key[NAME_LEN*2+2]; + TABLE_LIST table_list; + uint key_length; + safe_mutex_assert_owner(&LOCK_open); + + table_list.db= (char*) db; + table_list.table_name= (char*) table_name; + key_length= create_table_def_key((THD*) 0, key, &table_list, 0); + return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length); +} + + +/* + Close file handle, but leave the table in the table cache + + SYNOPSIS + close_handle_and_leave_table_as_lock() + table Table handler + + NOTES + By leaving the table in the table cache, it disallows any other thread + to open the table + + thd->killed will be set if we run out of memory + + If closing a MERGE child, the calling function has to take care for + closing the parent too, if necessary. +*/ + + +void close_handle_and_leave_table_as_lock(TABLE *table) +{ + TABLE_SHARE *share, *old_share= table->s; + char *key_buff; + MEM_ROOT *mem_root= &table->mem_root; + DBUG_ENTER("close_handle_and_leave_table_as_lock"); + + DBUG_ASSERT(table->db_stat); + + /* + Make a local copy of the table share and free the current one. + This has to be done to ensure that the table share is removed from + the table defintion cache as soon as the last instance is removed + */ + if (multi_alloc_root(mem_root, + &share, sizeof(*share), + &key_buff, old_share->table_cache_key.length, + NULL)) + { + bzero((char*) share, sizeof(*share)); + share->set_table_cache_key(key_buff, old_share->table_cache_key.str, + old_share->table_cache_key.length); + share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table() + } + + /* + When closing a MERGE parent or child table, detach the children first. + Do not clear child table references to allow for reopen. + */ + if (table->child_l || table->parent) + detach_merge_children(table, FALSE); + table->file->close(); + table->db_stat= 0; // Mark file closed + release_table_share(table->s, RELEASE_NORMAL); + table->s= share; + table->file->change_table_ptr(table, table->s); + + DBUG_VOID_RETURN; +} + + + +/* + Create a list for all open tables matching SQL expression + + SYNOPSIS + list_open_tables() + thd Thread THD + wild SQL like expression + + NOTES + One gets only a list of tables for which one has any kind of privilege. + db and table names are allocated in result struct, so one doesn't need + a lock on LOCK_open when traversing the return list. + + RETURN VALUES + NULL Error (Probably OOM) + # Pointer to list of names of open tables. +*/ + +OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild) +{ + int result = 0; + OPEN_TABLE_LIST **start_list, *open_list; + TABLE_LIST table_list; + DBUG_ENTER("list_open_tables"); + + VOID(pthread_mutex_lock(&LOCK_open)); + bzero((char*) &table_list,sizeof(table_list)); + start_list= &open_list; + open_list=0; + + for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++) + { + OPEN_TABLE_LIST *table; + TABLE *entry=(TABLE*) hash_element(&open_cache,idx); + TABLE_SHARE *share= entry->s; + + if (db && my_strcasecmp(system_charset_info, db, share->db.str)) + continue; + if (wild && wild_compare(share->table_name.str, wild, 0)) + continue; + + /* Check if user has SELECT privilege for any column in the table */ + table_list.db= share->db.str; + table_list.table_name= share->table_name.str; + table_list.grant.privilege=0; + + if (check_table_access(thd,SELECT_ACL | EXTRA_ACL,&table_list, 1, TRUE)) + continue; + /* need to check if we haven't already listed it */ + for (table= open_list ; table ; table=table->next) + { + if (!strcmp(table->table, share->table_name.str) && + !strcmp(table->db, share->db.str)) + { + if (entry->in_use) + table->in_use++; + if (entry->locked_by_name) + table->locked++; + break; + } + } + if (table) + continue; + if (!(*start_list = (OPEN_TABLE_LIST *) + sql_alloc(sizeof(**start_list)+share->table_cache_key.length))) + { + open_list=0; // Out of memory + break; + } + strmov((*start_list)->table= + strmov(((*start_list)->db= (char*) ((*start_list)+1)), + share->db.str)+1, + share->table_name.str); + (*start_list)->in_use= entry->in_use ? 1 : 0; + (*start_list)->locked= entry->locked_by_name ? 1 : 0; + start_list= &(*start_list)->next; + *start_list=0; + } + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(open_list); +} + +/***************************************************************************** + * Functions to free open table cache + ****************************************************************************/ + + +void intern_close_table(TABLE *table) +{ // Free all structures + DBUG_ENTER("intern_close_table"); + DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", + table->s ? table->s->db.str : "?", + table->s ? table->s->table_name.str : "?", + (long) table)); + + free_io_cache(table); + delete table->triggers; + if (table->file) // Not true if name lock + VOID(closefrm(table, 1)); // close file + DBUG_VOID_RETURN; +} + +/* + Remove table from the open table cache + + SYNOPSIS + free_cache_entry() + table Table to remove + + NOTE + We need to have a lock on LOCK_open when calling this +*/ + +static void free_cache_entry(TABLE *table) +{ + DBUG_ENTER("free_cache_entry"); + + /* Assert that MERGE children are not attached before final close. */ + DBUG_ASSERT(!table->is_children_attached()); + + intern_close_table(table); + if (!table->in_use) + { + table->next->prev=table->prev; /* remove from used chain */ + table->prev->next=table->next; + if (table == unused_tables) + { + unused_tables=unused_tables->next; + if (table == unused_tables) + unused_tables=0; + } + check_unused(); // consisty check + } + my_free((uchar*) table,MYF(0)); + DBUG_VOID_RETURN; +} + +/* Free resources allocated by filesort() and read_record() */ + +void free_io_cache(TABLE *table) +{ + DBUG_ENTER("free_io_cache"); + if (table->sort.io_cache) + { + close_cached_file(table->sort.io_cache); + my_free((uchar*) table->sort.io_cache,MYF(0)); + table->sort.io_cache=0; + } + DBUG_VOID_RETURN; +} + + +/* + Close all tables which aren't in use by any thread + + @param thd Thread context + @param tables List of tables to remove from the cache + @param have_lock If LOCK_open is locked + @param wait_for_refresh Wait for a impending flush + @param wait_for_placeholders Wait for tables being reopened so that the GRL + won't proceed while write-locked tables are being reopened by other + threads. + + @remark THD can be NULL, but then wait_for_refresh must be FALSE + and tables must be NULL. +*/ + +bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool have_lock, + bool wait_for_refresh, bool wait_for_placeholders) +{ + bool result=0; + DBUG_ENTER("close_cached_tables"); + DBUG_ASSERT(thd || (!wait_for_refresh && !tables)); + + if (!have_lock) + VOID(pthread_mutex_lock(&LOCK_open)); + if (!tables) + { + refresh_version++; // Force close of open tables + while (unused_tables) + { +#ifdef EXTRA_DEBUG + if (hash_delete(&open_cache,(uchar*) unused_tables)) + printf("Warning: Couldn't delete open table from hash\n"); +#else + VOID(hash_delete(&open_cache,(uchar*) unused_tables)); +#endif + } + /* Free table shares */ + while (oldest_unused_share->next) + { + pthread_mutex_lock(&oldest_unused_share->mutex); + VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share)); + } + DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu", + refresh_version)); + if (wait_for_refresh) + { + /* + Other threads could wait in a loop in open_and_lock_tables(), + trying to lock one or more of our tables. + + If they wait for the locks in thr_multi_lock(), their lock + request is aborted. They loop in open_and_lock_tables() and + enter open_table(). Here they notice the table is refreshed and + wait for COND_refresh. Then they loop again in + open_and_lock_tables() and this time open_table() succeeds. At + this moment, if we (the FLUSH TABLES thread) are scheduled and + on another FLUSH TABLES enter close_cached_tables(), they could + awake while we sleep below, waiting for others threads (us) to + close their open tables. If this happens, the other threads + would find the tables unlocked. They would get the locks, one + after the other, and could do their destructive work. This is an + issue if we have LOCK TABLES in effect. + + The problem is that the other threads passed all checks in + open_table() before we refresh the table. + + The fix for this problem is to set some_tables_deleted for all + threads with open tables. These threads can still get their + locks, but will immediately release them again after checking + this variable. They will then loop in open_and_lock_tables() + again. There they will wait until we update all tables version + below. + + Setting some_tables_deleted is done by remove_table_from_cache() + in the other branch. + + In other words (reviewer suggestion): You need this setting of + some_tables_deleted for the case when table was opened and all + related checks were passed before incrementing refresh_version + (which you already have) but attempt to lock the table happened + after the call to close_old_data_files() i.e. after removal of + current thread locks. + */ + for (uint idx=0 ; idx < open_cache.records ; idx++) + { + TABLE *table=(TABLE*) hash_element(&open_cache,idx); + if (table->in_use) + table->in_use->some_tables_deleted= 1; + } + } + } + else + { + bool found=0; + for (TABLE_LIST *table= tables; table; table= table->next_local) + { + if (remove_table_from_cache(thd, table->db, table->table_name, + RTFC_OWNED_BY_THD_FLAG)) + found=1; + } + if (!found) + wait_for_refresh=0; // Nothing to wait for + } +#ifndef EMBEDDED_LIBRARY + if (!tables) + kill_delayed_threads(); +#endif + if (wait_for_refresh) + { + /* + If there is any table that has a lower refresh_version, wait until + this is closed (or this thread is killed) before returning + */ + thd->mysys_var->current_mutex= &LOCK_open; + thd->mysys_var->current_cond= &COND_refresh; + thd_proc_info(thd, "Flushing tables"); + + close_old_data_files(thd,thd->open_tables,1,1); + mysql_ha_flush(thd); + + bool found=1; + /* Wait until all threads has closed all the tables we had locked */ + DBUG_PRINT("info", + ("Waiting for other threads to close their open tables")); + while (found && ! thd->killed) + { + found=0; + for (uint idx=0 ; idx < open_cache.records ; idx++) + { + TABLE *table=(TABLE*) hash_element(&open_cache,idx); + /* Avoid a self-deadlock. */ + if (table->in_use == thd) + continue; + /* + Note that we wait here only for tables which are actually open, and + not for placeholders with TABLE::open_placeholder set. Waiting for + latter will cause deadlock in the following scenario, for example: + + conn1: lock table t1 write; + conn2: lock table t2 write; + conn1: flush tables; + conn2: flush tables; + + It also does not make sense to wait for those of placeholders that + are employed by CREATE TABLE as in this case table simply does not + exist yet. + */ + if (table->needs_reopen_or_name_lock() && (table->db_stat || + (table->open_placeholder && wait_for_placeholders))) + { + found=1; + DBUG_PRINT("signal", ("Waiting for COND_refresh")); + pthread_cond_wait(&COND_refresh,&LOCK_open); + break; + } + } + } + /* + No other thread has the locked tables open; reopen them and get the + old locks. This should always succeed (unless some external process + has removed the tables) + */ + thd->in_lock_tables=1; + result=reopen_tables(thd,1,1); + thd->in_lock_tables=0; + /* Set version for table */ + for (TABLE *table=thd->open_tables; table ; table= table->next) + { + /* + Preserve the version (0) of write locked tables so that a impending + global read lock won't sneak in. + */ + if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE) + table->s->version= refresh_version; + } + } + if (!have_lock) + VOID(pthread_mutex_unlock(&LOCK_open)); + if (wait_for_refresh) + { + pthread_mutex_lock(&thd->mysys_var->mutex); + thd->mysys_var->current_mutex= 0; + thd->mysys_var->current_cond= 0; + thd_proc_info(thd, 0); + pthread_mutex_unlock(&thd->mysys_var->mutex); + } + DBUG_RETURN(result); +} + + +/* + Close all tables which match specified connection string or + if specified string is NULL, then any table with a connection string. +*/ + +bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh, + LEX_STRING *connection, bool have_lock) +{ + uint idx; + TABLE_LIST tmp, *tables= NULL; + bool result= FALSE; + DBUG_ENTER("close_cached_connections"); + DBUG_ASSERT(thd); + + bzero(&tmp, sizeof(TABLE_LIST)); + + if (!have_lock) + VOID(pthread_mutex_lock(&LOCK_open)); + + for (idx= 0; idx < table_def_cache.records; idx++) + { + TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx); + + /* Ignore if table is not open or does not have a connect_string */ + if (!share->connect_string.length || !share->ref_count) + continue; + + /* Compare the connection string */ + if (connection && + (connection->length > share->connect_string.length || + (connection->length < share->connect_string.length && + (share->connect_string.str[connection->length] != '/' && + share->connect_string.str[connection->length] != '\\')) || + strncasecmp(connection->str, share->connect_string.str, + connection->length))) + continue; + + /* close_cached_tables() only uses these elements */ + tmp.db= share->db.str; + tmp.table_name= share->table_name.str; + tmp.next_local= tables; + + tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp, + sizeof(TABLE_LIST)); + } + + if (tables) + result= close_cached_tables(thd, tables, TRUE, FALSE, FALSE); + + if (!have_lock) + VOID(pthread_mutex_unlock(&LOCK_open)); + + if (if_wait_for_refresh) + { + pthread_mutex_lock(&thd->mysys_var->mutex); + thd->mysys_var->current_mutex= 0; + thd->mysys_var->current_cond= 0; + thd->proc_info=0; + pthread_mutex_unlock(&thd->mysys_var->mutex); + } + + DBUG_RETURN(result); +} + + +/** + Mark all temporary tables which were used by the current statement or + substatement as free for reuse, but only if the query_id can be cleared. + + @param thd thread context + + @remark For temp tables associated with a open SQL HANDLER the query_id + is not reset until the HANDLER is closed. +*/ + +static void mark_temp_tables_as_free_for_reuse(THD *thd) +{ + for (TABLE *table= thd->temporary_tables ; table ; table= table->next) + { + if ((table->query_id == thd->query_id) && ! table->open_by_handler) + { + table->query_id= 0; + table->file->ha_reset(); + /* + Detach temporary MERGE children from temporary parent to allow new + attach at next open. Do not do the detach, if close_thread_tables() + is called from a sub-statement. The temporary table might still be + used in the top-level statement. + */ + if (table->child_l || table->parent) + detach_merge_children(table, TRUE); + /* + Reset temporary table lock type to it's default value (TL_WRITE). + + Statements such as INSERT INTO .. SELECT FROM tmp, CREATE TABLE + .. SELECT FROM tmp and UPDATE may under some circumstances modify + the lock type of the tables participating in the statement. This + isn't a problem for non-temporary tables since their lock type is + reset at every open, but the same does not occur for temporary + tables for historical reasons. + + Furthermore, the lock type of temporary tables is not really that + important because they can only be used by one query at a time and + not even twice in a query -- a temporary table is represented by + only one TABLE object. Nonetheless, it's safer from a maintenance + point of view to reset the lock type of this singleton TABLE object + as to not cause problems when the table is reused. + + Even under LOCK TABLES mode its okay to reset the lock type as + LOCK TABLES is allowed (but ignored) for a temporary table. + */ + table->reginfo.lock_type= TL_WRITE; + } + } +} + + +/* + Mark all tables in the list which were used by current substatement + as free for reuse. + + SYNOPSIS + mark_used_tables_as_free_for_reuse() + thd - thread context + table - head of the list of tables + + DESCRIPTION + Marks all tables in the list which were used by current substatement + (they are marked by its query_id) as free for reuse. + + NOTE + The reason we reset query_id is that it's not enough to just test + if table->query_id != thd->query_id to know if a table is in use. + + For example + SELECT f1_that_uses_t1() FROM t1; + In f1_that_uses_t1() we will see one instance of t1 where query_id is + set to query_id of original query. +*/ + +static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table) +{ + for (; table ; table= table->next) + { + if (table->query_id == thd->query_id) + { + table->query_id= 0; + table->file->ha_reset(); + } + } +} + + +/** + Auxiliary function to close all tables in the open_tables list. + + @param thd Thread context. + + @remark It should not ordinarily be called directly. +*/ + +static void close_open_tables(THD *thd) +{ + bool found_old_table= 0; + + safe_mutex_assert_not_owner(&LOCK_open); + + VOID(pthread_mutex_lock(&LOCK_open)); + + DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables)); + + while (thd->open_tables) + found_old_table|= close_thread_table(thd, &thd->open_tables); + thd->some_tables_deleted= 0; + + /* Free tables to hold down open files */ + while (open_cache.records > table_cache_size && unused_tables) + VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */ + check_unused(); + if (found_old_table) + { + /* Tell threads waiting for refresh that something has happened */ + broadcast_refresh(); + } + + VOID(pthread_mutex_unlock(&LOCK_open)); +} + + +/* + Close all tables used by the current substatement, or all tables + used by this thread if we are on the upper level. + + SYNOPSIS + close_thread_tables() + thd Thread handler + + IMPLEMENTATION + Unlocks tables and frees derived tables. + Put all normal tables used by thread in free list. + + It will only close/mark as free for reuse tables opened by this + substatement, it will also check if we are closing tables after + execution of complete query (i.e. we are on upper level) and will + leave prelocked mode if needed. +*/ + +void close_thread_tables(THD *thd) +{ + TABLE *table; + prelocked_mode_type prelocked_mode= thd->prelocked_mode; + DBUG_ENTER("close_thread_tables"); + +#ifdef EXTRA_DEBUG + DBUG_PRINT("tcache", ("open tables:")); + for (table= thd->open_tables; table; table= table->next) + DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str, + table->s->table_name.str, (long) table)); +#endif + + /* + We are assuming here that thd->derived_tables contains ONLY derived + tables for this substatement. i.e. instead of approach which uses + query_id matching for determining which of the derived tables belong + to this substatement we rely on the ability of substatements to + save/restore thd->derived_tables during their execution. + + TODO: Probably even better approach is to simply associate list of + derived tables with (sub-)statement instead of thread and destroy + them at the end of its execution. + */ + if (thd->derived_tables) + { + TABLE *next; + /* + Close all derived tables generated in queries like + SELECT * FROM (SELECT * FROM t1) + */ + for (table= thd->derived_tables ; table ; table= next) + { + next= table->next; + free_tmp_table(thd, table); + } + thd->derived_tables= 0; + } + + /* + Mark all temporary tables used by this statement as free for reuse. + */ + mark_temp_tables_as_free_for_reuse(thd); + /* + Let us commit transaction for statement. Since in 5.0 we only have + one statement transaction and don't allow several nested statement + transactions this call will do nothing if we are inside of stored + function or trigger (i.e. statement transaction is already active and + does not belong to statement for which we do close_thread_tables()). + TODO: This should be fixed in later releases. + */ + if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL)) + { + thd->main_da.can_overwrite_status= TRUE; + ha_autocommit_or_rollback(thd, thd->is_error()); + thd->main_da.can_overwrite_status= FALSE; + + /* + Reset transaction state, but only if we're not inside a + sub-statement of a prelocked statement. + */ + if (! prelocked_mode || thd->lex->requires_prelocking()) + thd->transaction.stmt.reset(); + } + + if (thd->locked_tables || prelocked_mode) + { + + /* Ensure we are calling ha_reset() for all used tables */ + mark_used_tables_as_free_for_reuse(thd, thd->open_tables); + + /* + We are under simple LOCK TABLES or we're inside a sub-statement + of a prelocked statement, so should not do anything else. + */ + if (!prelocked_mode || !thd->lex->requires_prelocking()) + DBUG_VOID_RETURN; + + /* + We are in the top-level statement of a prelocked statement, + so we have to leave the prelocked mode now with doing implicit + UNLOCK TABLES if needed. + */ + DBUG_PRINT("info",("thd->prelocked_mode= NON_PRELOCKED")); + thd->prelocked_mode= NON_PRELOCKED; + + if (prelocked_mode == PRELOCKED_UNDER_LOCK_TABLES) + DBUG_VOID_RETURN; + + thd->lock= thd->locked_tables; + thd->locked_tables= 0; + /* Fallthrough */ + } + + if (thd->lock) + { + /* + For RBR we flush the pending event just before we unlock all the + tables. This means that we are at the end of a topmost + statement, so we ensure that the STMT_END_F flag is set on the + pending event. For statements that are *inside* stored + functions, the pending event will not be flushed: that will be + handled either before writing a query log event (inside + binlog_query()) or when preparing a pending event. + */ + thd->binlog_flush_pending_rows_event(TRUE); + mysql_unlock_tables(thd, thd->lock); + thd->lock=0; + } + /* + Note that we need to hold LOCK_open while changing the + open_tables list. Another thread may work on it. + (See: remove_table_from_cache(), mysql_wait_completed_table()) + Closing a MERGE child before the parent would be fatal if the + other thread tries to abort the MERGE lock in between. + */ + if (thd->open_tables) + close_open_tables(thd); + + if (prelocked_mode == PRELOCKED) + { + /* + If we are here then we are leaving normal prelocked mode, so it is + good idea to turn off OPTION_TABLE_LOCK flag. + */ + DBUG_ASSERT(thd->lex->requires_prelocking()); + thd->options&= ~(OPTION_TABLE_LOCK); + } + + DBUG_VOID_RETURN; +} + + +/* move one table to free list */ + +bool close_thread_table(THD *thd, TABLE **table_ptr) +{ + bool found_old_table= 0; + TABLE *table= *table_ptr; + DBUG_ENTER("close_thread_table"); + DBUG_ASSERT(table->key_read == 0); + DBUG_ASSERT(!table->file || table->file->inited == handler::NONE); + DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str, + table->s->table_name.str, (long) table)); + + *table_ptr=table->next; + /* + When closing a MERGE parent or child table, detach the children first. + Clear child table references to force new assignment at next open. + */ + if (table->child_l || table->parent) + detach_merge_children(table, TRUE); + + if (table->needs_reopen_or_name_lock() || + thd->version != refresh_version || !table->db_stat) + { + VOID(hash_delete(&open_cache,(uchar*) table)); + found_old_table=1; + } + else + { + /* + Open placeholders have TABLE::db_stat set to 0, so they should be + handled by the first alternative. + */ + DBUG_ASSERT(!table->open_placeholder); + + /* Assert that MERGE children are not attached in unused_tables. */ + DBUG_ASSERT(!table->is_children_attached()); + + /* Free memory and reset for next loop */ + free_field_buffers_larger_than(table,MAX_TDC_BLOB_SIZE); + + table->file->ha_reset(); + table->in_use=0; + if (unused_tables) + { + table->next=unused_tables; /* Link in last */ + table->prev=unused_tables->prev; + unused_tables->prev=table; + table->prev->next=table; + } + else + unused_tables=table->next=table->prev=table; + } + DBUG_RETURN(found_old_table); +} + + +/* close_temporary_tables' internal, 4 is due to uint4korr definition */ +static inline uint tmpkeyval(THD *thd, TABLE *table) +{ + return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4); +} + + +/* + Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread + creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread +*/ + +void close_temporary_tables(THD *thd) +{ + TABLE *table; + TABLE *next= NULL; + TABLE *prev_table; + /* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */ + bool was_quote_show= TRUE; + + if (!thd->temporary_tables) + return; + + if (!mysql_bin_log.is_open() || + (thd->current_stmt_binlog_row_based && thd->variables.binlog_format == BINLOG_FORMAT_ROW)) + { + TABLE *tmp_next; + for (table= thd->temporary_tables; table; table= tmp_next) + { + tmp_next= table->next; + close_temporary(table, 1, 1); + } + thd->temporary_tables= 0; + return; + } + + /* Better add "if exists", in case a RESET MASTER has been done */ + const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS "; + uint stub_len= sizeof(stub) - 1; + char buf[256]; + String s_query= String(buf, sizeof(buf), system_charset_info); + bool found_user_tables= FALSE; + + memcpy(buf, stub, stub_len); + + /* + Insertion sort of temp tables by pseudo_thread_id to build ordered list + of sublists of equal pseudo_thread_id + */ + + for (prev_table= thd->temporary_tables, table= prev_table->next; + table; + prev_table= table, table= table->next) + { + TABLE *prev_sorted /* same as for prev_table */, *sorted; + if (is_user_table(table)) + { + if (!found_user_tables) + found_user_tables= true; + for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table; + prev_sorted= sorted, sorted= sorted->next) + { + if (!is_user_table(sorted) || + tmpkeyval(thd, sorted) > tmpkeyval(thd, table)) + { + /* move into the sorted part of the list from the unsorted */ + prev_table->next= table->next; + table->next= sorted; + if (prev_sorted) + { + prev_sorted->next= table; + } + else + { + thd->temporary_tables= table; + } + table= prev_table; + break; + } + } + } + } + + /* We always quote db,table names though it is slight overkill */ + if (found_user_tables && + !(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE))) + { + thd->options |= OPTION_QUOTE_SHOW_CREATE; + } + + /* scan sorted tmps to generate sequence of DROP */ + for (table= thd->temporary_tables; table; table= next) + { + if (is_user_table(table)) + { + my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id; + /* Set pseudo_thread_id to be that of the processed table */ + thd->variables.pseudo_thread_id= tmpkeyval(thd, table); + String db; + db.append(table->s->db.str); + /* Loop forward through all tables that belong to a common database + within the sublist of common pseudo_thread_id to create single + DROP query + */ + for (s_query.length(stub_len); + table && is_user_table(table) && + tmpkeyval(thd, table) == thd->variables.pseudo_thread_id && + table->s->db.length == db.length() && + strcmp(table->s->db.str, db.ptr()) == 0; + table= next) + { + /* + We are going to add ` around the table names and possible more + due to special characters + */ + append_identifier(thd, &s_query, table->s->table_name.str, + strlen(table->s->table_name.str)); + s_query.append(','); + next= table->next; + close_temporary(table, 1, 1); + } + thd->clear_error(); + CHARSET_INFO *cs_save= thd->variables.character_set_client; + thd->variables.character_set_client= system_charset_info; + Query_log_event qinfo(thd, s_query.ptr(), + s_query.length() - 1 /* to remove trailing ',' */, + 0, FALSE, 0); + qinfo.db= db.ptr(); + thd->variables.character_set_client= cs_save; + mysql_bin_log.write(&qinfo); + thd->variables.pseudo_thread_id= save_pseudo_thread_id; + } + else + { + next= table->next; + close_temporary(table, 1, 1); + } + } + if (!was_quote_show) + thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */ + thd->temporary_tables=0; +} + +/* + Find table in list. + + SYNOPSIS + find_table_in_list() + table Pointer to table list + offset Offset to which list in table structure to use + db_name Data base name + table_name Table name + + NOTES: + This is called by find_table_in_local_list() and + find_table_in_global_list(). + + RETURN VALUES + NULL Table not found + # Pointer to found table. +*/ + +TABLE_LIST *find_table_in_list(TABLE_LIST *table, + TABLE_LIST *TABLE_LIST::*link, + const char *db_name, + const char *table_name) +{ + for (; table; table= table->*link ) + { + if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) && + strcmp(table->db, db_name) == 0 && + strcmp(table->table_name, table_name) == 0) + break; + } + return table; +} + + +/* + Test that table is unique (It's only exists once in the table list) + + SYNOPSIS + unique_table() + thd thread handle + table table which should be checked + table_list list of tables + check_alias whether to check tables' aliases + + NOTE: to exclude derived tables from check we use following mechanism: + a) during derived table processing set THD::derived_tables_processing + b) JOIN::prepare set SELECT::exclude_from_table_unique_test if + THD::derived_tables_processing set. (we can't use JOIN::execute + because for PS we perform only JOIN::prepare, but we can't set this + flag in JOIN::prepare if we are not sure that we are in derived table + processing loop, because multi-update call fix_fields() for some its + items (which mean JOIN::prepare for subqueries) before unique_table + call to detect which tables should be locked for write). + c) unique_table skip all tables which belong to SELECT with + SELECT::exclude_from_table_unique_test set. + Also SELECT::exclude_from_table_unique_test used to exclude from check + tables of main SELECT of multi-delete and multi-update + + We also skip tables with TABLE_LIST::prelocking_placeholder set, + because we want to allow SELECTs from them, and their modification + will rise the error anyway. + + TODO: when we will have table/view change detection we can do this check + only once for PS/SP + + RETURN + found duplicate + 0 if table is unique +*/ + +TABLE_LIST* unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list, + bool check_alias) +{ + TABLE_LIST *res; + const char *d_name, *t_name, *t_alias; + DBUG_ENTER("unique_table"); + DBUG_PRINT("enter", ("table alias: %s", table->alias)); + + /* + If this function called for query which update table (INSERT/UPDATE/...) + then we have in table->table pointer to TABLE object which we are + updating even if it is VIEW so we need TABLE_LIST of this TABLE object + to get right names (even if lower_case_table_names used). + + If this function called for CREATE command that we have not opened table + (table->table equal to 0) and right names is in current TABLE_LIST + object. + */ + if (table->table) + { + /* temporary table is always unique */ + if (table->table && table->table->s->tmp_table != NO_TMP_TABLE) + DBUG_RETURN(0); + table= table->find_underlying_table(table->table); + /* + as far as we have table->table we have to find real TABLE_LIST of + it in underlying tables + */ + DBUG_ASSERT(table); + } + d_name= table->db; + t_name= table->table_name; + t_alias= table->alias; + + DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name)); + for (;;) + { + if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) && + (! (res= mysql_lock_have_duplicate(thd, table, table_list)))) || + ((!res->table || res->table != table->table) && + (!check_alias || !(lower_case_table_names ? + my_strcasecmp(files_charset_info, t_alias, res->alias) : + strcmp(t_alias, res->alias))) && + res->select_lex && !res->select_lex->exclude_from_table_unique_test && + !res->prelocking_placeholder)) + break; + /* + If we found entry of this table or table of SELECT which already + processed in derived table or top select of multi-update/multi-delete + (exclude_from_table_unique_test) or prelocking placeholder. + */ + table_list= res->next_global; + DBUG_PRINT("info", + ("found same copy of table or table which we should skip")); + } + DBUG_RETURN(res); +} + + +/* + Issue correct error message in case we found 2 duplicate tables which + prevent some update operation + + SYNOPSIS + update_non_unique_table_error() + update table which we try to update + operation name of update operation + duplicate duplicate table which we found + + NOTE: + here we hide view underlying tables if we have them +*/ + +void update_non_unique_table_error(TABLE_LIST *update, + const char *operation, + TABLE_LIST *duplicate) +{ + update= update->top_table(); + duplicate= duplicate->top_table(); + if (!update->view || !duplicate->view || + update->view == duplicate->view || + update->view_name.length != duplicate->view_name.length || + update->view_db.length != duplicate->view_db.length || + my_strcasecmp(table_alias_charset, + update->view_name.str, duplicate->view_name.str) != 0 || + my_strcasecmp(table_alias_charset, + update->view_db.str, duplicate->view_db.str) != 0) + { + /* + it is not the same view repeated (but it can be parts of the same copy + of view), so we have to hide underlying tables. + */ + if (update->view) + { + /* Issue the ER_NON_INSERTABLE_TABLE error for an INSERT */ + if (update->view == duplicate->view) + my_error(!strncmp(operation, "INSERT", 6) ? + ER_NON_INSERTABLE_TABLE : ER_NON_UPDATABLE_TABLE, MYF(0), + update->alias, operation); + else + my_error(ER_VIEW_PREVENT_UPDATE, MYF(0), + (duplicate->view ? duplicate->alias : update->alias), + operation, update->alias); + return; + } + if (duplicate->view) + { + my_error(ER_VIEW_PREVENT_UPDATE, MYF(0), duplicate->alias, operation, + update->alias); + return; + } + } + my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias); +} + + +TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name) +{ + TABLE_LIST table_list; + + table_list.db= (char*) db; + table_list.table_name= (char*) table_name; + return find_temporary_table(thd, &table_list); +} + + +TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list) +{ + char key[MAX_DBKEY_LENGTH]; + uint key_length; + TABLE *table; + DBUG_ENTER("find_temporary_table"); + DBUG_PRINT("enter", ("table: '%s'.'%s'", + table_list->db, table_list->table_name)); + + key_length= create_table_def_key(thd, key, table_list, 1); + for (table=thd->temporary_tables ; table ; table= table->next) + { + if (table->s->table_cache_key.length == key_length && + !memcmp(table->s->table_cache_key.str, key, key_length)) + { + DBUG_PRINT("info", + ("Found table. server_id: %u pseudo_thread_id: %lu", + (uint) thd->server_id, + (ulong) thd->variables.pseudo_thread_id)); + DBUG_RETURN(table); + } + } + DBUG_RETURN(0); // Not a temporary table +} + + +/** + Drop a temporary table. + + Try to locate the table in the list of thd->temporary_tables. + If the table is found: + - if the table is being used by some outer statement, fail. + - if the table is in thd->locked_tables, unlock it and + remove it from the list of locked tables. Currently only transactional + temporary tables are present in the locked_tables list. + - Close the temporary table, remove its .FRM + - remove the table from the list of temporary tables + + This function is used to drop user temporary tables, as well as + internal tables created in CREATE TEMPORARY TABLE ... SELECT + or ALTER TABLE. Even though part of the work done by this function + is redundant when the table is internal, as long as we + link both internal and user temporary tables into the same + thd->temporary_tables list, it's impossible to tell here whether + we're dealing with an internal or a user temporary table. + + @retval 0 the table was found and dropped successfully. + @retval 1 the table was not found in the list of temporary tables + of this thread + @retval -1 the table is in use by a outer query +*/ + +int drop_temporary_table(THD *thd, TABLE_LIST *table_list) +{ + TABLE *table; + DBUG_ENTER("drop_temporary_table"); + DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'", + table_list->db, table_list->table_name)); + + if (!(table= find_temporary_table(thd, table_list))) + DBUG_RETURN(1); + + /* Table might be in use by some outer statement. */ + if (table->query_id && table->query_id != thd->query_id) + { + my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias); + DBUG_RETURN(-1); + } + + /* + If LOCK TABLES list is not empty and contains this table, + unlock the table and remove the table from this list. + */ + mysql_lock_remove(thd, thd->locked_tables, table, FALSE); + close_temporary_table(thd, table, 1, 1); + DBUG_RETURN(0); +} + +/* + unlink from thd->temporary tables and close temporary table +*/ + +void close_temporary_table(THD *thd, TABLE *table, + bool free_share, bool delete_table) +{ + DBUG_ENTER("close_temporary_table"); + DBUG_PRINT("tmptable", ("closing table: '%s'.'%s' 0x%lx alias: '%s'", + table->s->db.str, table->s->table_name.str, + (long) table, table->alias)); + + /* + When closing a MERGE parent or child table, detach the children + first. Clear child table references as MERGE table cannot be + reopened after final close of one of its tables. + + This is necessary here because it is sometimes called with attached + tables and without prior close_thread_tables(). E.g. in + mysql_alter_table(), mysql_rm_table_part2(), mysql_truncate(), + drop_open_table(). + */ + if (table->child_l || table->parent) + detach_merge_children(table, TRUE); + + if (table->prev) + { + table->prev->next= table->next; + if (table->prev->next) + table->next->prev= table->prev; + } + else + { + /* removing the item from the list */ + DBUG_ASSERT(table == thd->temporary_tables); + /* + slave must reset its temporary list pointer to zero to exclude + passing non-zero value to end_slave via rli->save_temporary_tables + when no temp tables opened, see an invariant below. + */ + thd->temporary_tables= table->next; + if (thd->temporary_tables) + table->next->prev= 0; + } + if (thd->slave_thread) + { + /* natural invariant of temporary_tables */ + DBUG_ASSERT(slave_open_temp_tables || !thd->temporary_tables); + slave_open_temp_tables--; + } + close_temporary(table, free_share, delete_table); + DBUG_VOID_RETURN; +} + + +/* + Close and delete a temporary table + + NOTE + This dosn't unlink table from thd->temporary + If this is needed, use close_temporary_table() +*/ + +void close_temporary(TABLE *table, bool free_share, bool delete_table) +{ + handlerton *table_type= table->s->db_type(); + DBUG_ENTER("close_temporary"); + DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'", + table->s->db.str, table->s->table_name.str)); + + free_io_cache(table); + closefrm(table, 0); + if (delete_table) + rm_temporary_table(table_type, table->s->path.str); + if (free_share) + { + free_table_share(table->s); + my_free((char*) table,MYF(0)); + } + DBUG_VOID_RETURN; +} + + +/* + Used by ALTER TABLE when the table is a temporary one. It changes something + only if the ALTER contained a RENAME clause (otherwise, table_name is the old + name). + Prepares a table cache key, which is the concatenation of db, table_name and + thd->slave_proxy_id, separated by '\0'. +*/ + +bool rename_temporary_table(THD* thd, TABLE *table, const char *db, + const char *table_name) +{ + char *key; + uint key_length; + TABLE_SHARE *share= table->s; + TABLE_LIST table_list; + DBUG_ENTER("rename_temporary_table"); + + if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH))) + DBUG_RETURN(1); /* purecov: inspected */ + + table_list.db= (char*) db; + table_list.table_name= (char*) table_name; + key_length= create_table_def_key(thd, key, &table_list, 1); + share->set_table_cache_key(key, key_length); + DBUG_RETURN(0); +} + + + /* move table first in unused links */ + +static void relink_unused(TABLE *table) +{ + /* Assert that MERGE children are not attached in unused_tables. */ + DBUG_ASSERT(!table->is_children_attached()); + + if (table != unused_tables) + { + table->prev->next=table->next; /* Remove from unused list */ + table->next->prev=table->prev; + table->next=unused_tables; /* Link in unused tables */ + table->prev=unused_tables->prev; + unused_tables->prev->next=table; + unused_tables->prev=table; + unused_tables=table; + check_unused(); + } +} + + +/** + Prepare an open merge table for close. + + @param[in] thd thread context + @param[in] table table to prepare + @param[in,out] prev_pp pointer to pointer of previous table + + @detail + If the table is a MERGE parent, just detach the children. + If the table is a MERGE child, close the parent (incl. detach). +*/ + +static void unlink_open_merge(THD *thd, TABLE *table, TABLE ***prev_pp) +{ + DBUG_ENTER("unlink_open_merge"); + + if (table->parent) + { + /* + If MERGE child, close parent too. Closing includes detaching. + + This is used for example in ALTER TABLE t1 RENAME TO t5 under + LOCK TABLES where t1 is a MERGE child: + CREATE TABLE t1 (c1 INT); + CREATE TABLE t2 (c1 INT) ENGINE=MRG_MYISAM UNION=(t1); + LOCK TABLES t1 WRITE, t2 WRITE; + ALTER TABLE t1 RENAME TO t5; + */ + TABLE *parent= table->parent; + TABLE **prv_p; + + /* Find parent in open_tables list. */ + for (prv_p= &thd->open_tables; + *prv_p && (*prv_p != parent); + prv_p= &(*prv_p)->next) {} + if (*prv_p) + { + /* Special treatment required if child follows parent in list. */ + if (*prev_pp == &parent->next) + *prev_pp= prv_p; + /* + Remove parent from open_tables list and close it. + This includes detaching and hence clearing parent references. + */ + close_thread_table(thd, prv_p); + } + } + else if (table->child_l) + { + /* + When closing a MERGE parent, detach the children first. It is + not necessary to clear the child or parent table reference of + this table because the TABLE is freed. But we need to clear + the child or parent references of the other belonging tables + so that they cannot be moved into the unused_tables chain with + these pointers set. + + This is used for example in ALTER TABLE t2 RENAME TO t5 under + LOCK TABLES where t2 is a MERGE parent: + CREATE TABLE t1 (c1 INT); + CREATE TABLE t2 (c1 INT) ENGINE=MRG_MYISAM UNION=(t1); + LOCK TABLES t1 WRITE, t2 WRITE; + ALTER TABLE t2 RENAME TO t5; + */ + detach_merge_children(table, TRUE); + } + + DBUG_VOID_RETURN; +} + + +/** + Remove all instances of table from thread's open list and + table cache. + + @param thd Thread context + @param find Table to remove + @param unlock TRUE - free all locks on tables removed that are + done with LOCK TABLES + FALSE - otherwise + + @note When unlock parameter is FALSE or current thread doesn't have + any tables locked with LOCK TABLES, tables are assumed to be + not locked (for example already unlocked). +*/ + +void unlink_open_table(THD *thd, TABLE *find, bool unlock) +{ + char key[MAX_DBKEY_LENGTH]; + uint key_length= find->s->table_cache_key.length; + TABLE *list, **prev; + DBUG_ENTER("unlink_open_table"); + + safe_mutex_assert_owner(&LOCK_open); + + memcpy(key, find->s->table_cache_key.str, key_length); + /* + Note that we need to hold LOCK_open while changing the + open_tables list. Another thread may work on it. + (See: remove_table_from_cache(), mysql_wait_completed_table()) + Closing a MERGE child before the parent would be fatal if the + other thread tries to abort the MERGE lock in between. + */ + for (prev= &thd->open_tables; *prev; ) + { + list= *prev; + + if (list->s->table_cache_key.length == key_length && + !memcmp(list->s->table_cache_key.str, key, key_length)) + { + if (unlock && thd->locked_tables) + mysql_lock_remove(thd, thd->locked_tables, + list->parent ? list->parent : list, TRUE); + + /* Prepare MERGE table for close. Close parent if necessary. */ + unlink_open_merge(thd, list, &prev); + + /* Remove table from open_tables list. */ + *prev= list->next; + /* Close table. */ + VOID(hash_delete(&open_cache,(uchar*) list)); // Close table + } + else + { + /* Step to next entry in open_tables list. */ + prev= &list->next; + } + } + + // Notify any 'refresh' threads + broadcast_refresh(); + DBUG_VOID_RETURN; +} + + +/** + Auxiliary routine which closes and drops open table. + + @param thd Thread handle + @param table TABLE object for table to be dropped + @param db_name Name of database for this table + @param table_name Name of this table + + @note This routine assumes that table to be closed is open only + by calling thread so we needn't wait until other threads + will close the table. Also unless called under implicit or + explicit LOCK TABLES mode it assumes that table to be + dropped is already unlocked. In the former case it will + also remove lock on the table. But one should not rely on + this behaviour as it may change in future. + Currently, however, this function is never called for a + table that was locked with LOCK TABLES. +*/ + +void drop_open_table(THD *thd, TABLE *table, const char *db_name, + const char *table_name) +{ + if (table->s->tmp_table) + close_temporary_table(thd, table, 1, 1); + else + { + handlerton *table_type= table->s->db_type(); + VOID(pthread_mutex_lock(&LOCK_open)); + /* + unlink_open_table() also tells threads waiting for refresh or close + that something has happened. + */ + unlink_open_table(thd, table, FALSE); + quick_rm_table(table_type, db_name, table_name, 0); + VOID(pthread_mutex_unlock(&LOCK_open)); + } +} + + +/* + Wait for condition but allow the user to send a kill to mysqld + + SYNOPSIS + wait_for_condition() + thd Thread handler + mutex mutex that is currently hold that is associated with condition + Will be unlocked on return + cond Condition to wait for +*/ + +void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond) +{ + /* Wait until the current table is up to date */ + const char *proc_info; + thd->mysys_var->current_mutex= mutex; + thd->mysys_var->current_cond= cond; + proc_info=thd->proc_info; + thd_proc_info(thd, "Waiting for table"); + DBUG_ENTER("wait_for_condition"); + if (!thd->killed) + (void) pthread_cond_wait(cond, mutex); + + /* + We must unlock mutex first to avoid deadlock becasue conditions are + sent to this thread by doing locks in the following order: + lock(mysys_var->mutex) + lock(mysys_var->current_mutex) + + One by effect of this that one can only use wait_for_condition with + condition variables that are guranteed to not disapper (freed) even if this + mutex is unlocked + */ + + pthread_mutex_unlock(mutex); + pthread_mutex_lock(&thd->mysys_var->mutex); + thd->mysys_var->current_mutex= 0; + thd->mysys_var->current_cond= 0; + thd_proc_info(thd, proc_info); + pthread_mutex_unlock(&thd->mysys_var->mutex); + DBUG_VOID_RETURN; +} + + +/** + Exclusively name-lock a table that is already write-locked by the + current thread. + + @param thd current thread context + @param tables table list containing one table to open. + + @return FALSE on success, TRUE otherwise. +*/ + +bool name_lock_locked_table(THD *thd, TABLE_LIST *tables) +{ + DBUG_ENTER("name_lock_locked_table"); + + // @infinidb + if (tables->alias && tables->alias[0] == '$') + DBUG_RETURN(TRUE); + + /* Under LOCK TABLES we must only accept write locked tables. */ + tables->table= find_locked_table(thd, tables->db, tables->table_name); + + if (!tables->table) + my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias); + else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY) + my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias); + else + { + /* + Ensures that table is opened only by this thread and that no + other statement will open this table. + */ + wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN); + DBUG_RETURN(FALSE); + } + + DBUG_RETURN(TRUE); +} + + +/* + Open table which is already name-locked by this thread. + + SYNOPSIS + reopen_name_locked_table() + thd Thread handle + table_list TABLE_LIST object for table to be open, TABLE_LIST::table + member should point to TABLE object which was used for + name-locking. + link_in TRUE - if TABLE object for table to be opened should be + linked into THD::open_tables list. + FALSE - placeholder used for name-locking is already in + this list so we only need to preserve TABLE::next + pointer. + + NOTE + This function assumes that its caller already acquired LOCK_open mutex. + + RETURN VALUE + FALSE - Success + TRUE - Error +*/ + +bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in) +{ + TABLE *table= table_list->table; + TABLE_SHARE *share; + char *table_name= table_list->table_name; + TABLE orig_table; + DBUG_ENTER("reopen_name_locked_table"); + + safe_mutex_assert_owner(&LOCK_open); + + if (thd->killed || !table) + DBUG_RETURN(TRUE); + + orig_table= *table; + + if (open_unireg_entry(thd, table, table_list, table_name, + table->s->table_cache_key.str, + table->s->table_cache_key.length, thd->mem_root, 0)) + { + intern_close_table(table); + /* + If there was an error during opening of table (for example if it + does not exist) '*table' object can be wiped out. To be able + properly release name-lock in this case we should restore this + object to its original state. + */ + *table= orig_table; + DBUG_RETURN(TRUE); + } + + share= table->s; + /* + We want to prevent other connections from opening this table until end + of statement as it is likely that modifications of table's metadata are + not yet finished (for example CREATE TRIGGER have to change .TRG file, + or we might want to drop table if CREATE TABLE ... SELECT fails). + This also allows us to assume that no other connection will sneak in + before we will get table-level lock on this table. + */ + share->version=0; + table->in_use = thd; + check_unused(); + + if (link_in) + { + table->next= thd->open_tables; + thd->open_tables= table; + } + else + { + /* + TABLE object should be already in THD::open_tables list so we just + need to set TABLE::next correctly. + */ + table->next= orig_table.next; + } + + table->tablenr=thd->current_tablenr++; + table->used_fields=0; + table->const_table=0; + table->null_row= table->maybe_null= table->force_index= 0; + table->status=STATUS_NO_RECORD; + DBUG_RETURN(FALSE); +} + + +/** + Create and insert into table cache placeholder for table + which will prevent its opening (or creation) (a.k.a lock + table name). + + @param thd Thread context + @param key Table cache key for name to be locked + @param key_length Table cache key length + + @return Pointer to TABLE object used for name locking or 0 in + case of failure. +*/ + +TABLE *table_cache_insert_placeholder(THD *thd, const char *key, + uint key_length) +{ + TABLE *table; + TABLE_SHARE *share; + char *key_buff; + DBUG_ENTER("table_cache_insert_placeholder"); + + safe_mutex_assert_owner(&LOCK_open); + + /* + Create a table entry with the right key and with an old refresh version + Note that we must use my_multi_malloc() here as this is freed by the + table cache + */ + if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL), + &table, sizeof(*table), + &share, sizeof(*share), + &key_buff, key_length, + NULL)) + DBUG_RETURN(NULL); + + table->s= share; + share->set_table_cache_key(key_buff, key, key_length); + share->tmp_table= INTERNAL_TMP_TABLE; // for intern_close_table + table->in_use= thd; + table->locked_by_name=1; + + if (my_hash_insert(&open_cache, (uchar*)table)) + { + my_free((uchar*) table, MYF(0)); + DBUG_RETURN(NULL); + } + + DBUG_RETURN(table); +} + + +/** + Obtain an exclusive name lock on the table if it is not cached + in the table cache. + + @param thd Thread context + @param db Name of database + @param table_name Name of table + @param[out] table Out parameter which is either: + - set to NULL if table cache contains record for + the table or + - set to point to the TABLE instance used for + name-locking. + + @note This function takes into account all records for table in table + cache, even placeholders used for name-locking. This means that + 'table' parameter can be set to NULL for some situations when + table does not really exist. + + @retval TRUE Error occured (OOM) + @retval FALSE Success. 'table' parameter set according to above rules. +*/ + +bool lock_table_name_if_not_cached(THD *thd, const char *db, + const char *table_name, TABLE **table) +{ + char key[MAX_DBKEY_LENGTH]; + uint key_length; + DBUG_ENTER("lock_table_name_if_not_cached"); + + key_length= (uint)(strmov(strmov(key, db) + 1, table_name) - key) + 1; + VOID(pthread_mutex_lock(&LOCK_open)); + + if (hash_search(&open_cache, (uchar *)key, key_length)) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_PRINT("info", ("Table is cached, name-lock is not obtained")); + *table= 0; + DBUG_RETURN(FALSE); + } + if (!(*table= table_cache_insert_placeholder(thd, key, key_length))) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(TRUE); + } + (*table)->open_placeholder= 1; + (*table)->next= thd->open_tables; + thd->open_tables= *table; + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(FALSE); +} + + +/** + Check that table exists in table definition cache, on disk + or in some storage engine. + + @param thd Thread context + @param table Table list element + @param[out] exists Out parameter which is set to TRUE if table + exists and to FALSE otherwise. + + @note This function assumes that caller owns LOCK_open mutex. + It also assumes that the fact that there are no name-locks + on the table was checked beforehand. + + @note If there is no .FRM file for the table but it exists in one + of engines (e.g. it was created on another node of NDB cluster) + this function will fetch and create proper .FRM file for it. + + @retval TRUE Some error occured + @retval FALSE No error. 'exists' out parameter set accordingly. +*/ + +bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists) +{ + char path[FN_REFLEN + 1]; + int rc; + DBUG_ENTER("check_if_table_exists"); + + safe_mutex_assert_owner(&LOCK_open); + + *exists= TRUE; + + if (get_cached_table_share(table->db, table->table_name)) + DBUG_RETURN(FALSE); + + build_table_filename(path, sizeof(path) - 1, table->db, table->table_name, + reg_ext, 0); + + if (!access(path, F_OK)) + DBUG_RETURN(FALSE); + + /* .FRM file doesn't exist. Check if some engine can provide it. */ + + rc= ha_create_table_from_engine(thd, table->db, table->table_name); + + if (rc < 0) + { + /* Table does not exists in engines as well. */ + *exists= FALSE; + DBUG_RETURN(FALSE); + } + else if (!rc) + { + /* Table exists in some engine and .FRM for it was created. */ + DBUG_RETURN(FALSE); + } + else /* (rc > 0) */ + { + my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while " + "unpacking from engine", MYF(0), table->table_name); + DBUG_RETURN(TRUE); + } +} + + +/* + Open a table. + + SYNOPSIS + open_table() + thd Thread context. + table_list Open first table in list. + refresh INOUT Pointer to memory that will be set to 1 if + we need to close all tables and reopen them. + If this is a NULL pointer, then the table is not + put in the thread-open-list. + flags Bitmap of flags to modify how open works: + MYSQL_LOCK_IGNORE_FLUSH - Open table even if + someone has done a flush or namelock on it. + No version number checking is done. + MYSQL_OPEN_TEMPORARY_ONLY - Open only temporary + table not the base table or view. + + IMPLEMENTATION + Uses a cache of open tables to find a table not in use. + + If table list element for the table to be opened has "create" flag + set and table does not exist, this function will automatically insert + a placeholder for exclusive name lock into the open tables cache and + will return the TABLE instance that corresponds to this placeholder. + + RETURN + NULL Open failed. If refresh is set then one should close + all other tables and retry the open. + # Success. Pointer to TABLE object for open table. +*/ + + +TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root, + bool *refresh, uint flags) +{ + reg1 TABLE *table; + char key[MAX_DBKEY_LENGTH]; + uint key_length; + char *alias= table_list->alias; + HASH_SEARCH_STATE state; + DBUG_ENTER("open_table"); + + /* Parsing of partitioning information from .frm needs thd->lex set up. */ + DBUG_ASSERT(thd->lex->is_lex_started); + + /* find a unused table in the open table cache */ + if (refresh) + *refresh=0; + + /* an open table operation needs a lot of the stack space */ + if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias)) + DBUG_RETURN(0); + + if (thd->killed) + DBUG_RETURN(0); + + key_length= (create_table_def_key(thd, key, table_list, 1) - + TMP_TABLE_KEY_EXTRA); + + /* + Unless requested otherwise, try to resolve this table in the list + of temporary tables of this thread. In MySQL temporary tables + are always thread-local and "shadow" possible base tables with the + same name. This block implements the behaviour. + TODO: move this block into a separate function. + */ + if (!table_list->skip_temporary) + { + for (table= thd->temporary_tables; table ; table=table->next) + { + if (table->s->table_cache_key.length == key_length + + TMP_TABLE_KEY_EXTRA && + !memcmp(table->s->table_cache_key.str, key, + key_length + TMP_TABLE_KEY_EXTRA)) + { + /* + We're trying to use the same temporary table twice in a query. + Right now we don't support this because a temporary table + is always represented by only one TABLE object in THD, and + it can not be cloned. Emit an error for an unsupported behaviour. + */ + if (table->query_id) + { + DBUG_PRINT("error", + ("query_id: %lu server_id: %u pseudo_thread_id: %lu", + (ulong) table->query_id, (uint) thd->server_id, + (ulong) thd->variables.pseudo_thread_id)); + my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias); + DBUG_RETURN(0); + } + table->query_id= thd->query_id; + thd->thread_specific_used= TRUE; + DBUG_PRINT("info",("Using temporary table")); + goto reset; + } + } + } + + if (flags & MYSQL_OPEN_TEMPORARY_ONLY) + { + my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name); + DBUG_RETURN(0); + } + + /* + The table is not temporary - if we're in pre-locked or LOCK TABLES + mode, let's try to find the requested table in the list of pre-opened + and locked tables. If the table is not there, return an error - we can't + open not pre-opened tables in pre-locked/LOCK TABLES mode. + TODO: move this block into a separate function. + */ + if (thd->locked_tables || thd->prelocked_mode) + { // Using table locks + TABLE *best_table= 0; + int best_distance= INT_MIN; + for (table=thd->open_tables; table ; table=table->next) + { + if (table->s->table_cache_key.length == key_length && + !memcmp(table->s->table_cache_key.str, key, key_length)) + { + /* + When looking for a usable TABLE, ignore MERGE children, as they + belong to their parent and cannot be used explicitly. + */ + if (!my_strcasecmp(system_charset_info, table->alias, alias) && + table->query_id != thd->query_id && /* skip tables already used */ + !(thd->prelocked_mode && table->query_id) && + !table->parent) + { + int distance= ((int) table->reginfo.lock_type - + (int) table_list->lock_type); + /* + Find a table that either has the exact lock type requested, + or has the best suitable lock. In case there is no locked + table that has an equal or higher lock than requested, + we us the closest matching lock to be able to produce an error + message about wrong lock mode on the table. The best_table + is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd. + + distance < 0 - No suitable lock found + distance > 0 - we have lock mode higher then we require + distance == 0 - we have lock mode exactly which we need + */ + if ((best_distance < 0 && distance > best_distance) || + (distance >= 0 && distance < best_distance)) + { + best_distance= distance; + best_table= table; + if (best_distance == 0) + { + /* + We have found a perfect match and can finish iterating + through open tables list. Check for table use conflict + between calling statement and SP/trigger is done in + lock_tables(). + */ + break; + } + } + } + } + } + if (best_table) + { + table= best_table; + table->query_id= thd->query_id; + DBUG_PRINT("info",("Using locked table")); + goto reset; + } + /* + Is this table a view and not a base table? + (it is work around to allow to open view with locked tables, + real fix will be made after definition cache will be made) + */ + { + char path[FN_REFLEN + 1]; + enum legacy_db_type not_used; + build_table_filename(path, sizeof(path) - 1, + table_list->db, table_list->table_name, reg_ext, 0); + if (mysql_frm_type(thd, path, ¬_used) == FRMTYPE_VIEW) + { + /* + Will not be used (because it's VIEW) but has to be passed. + Also we will not free it (because it is a stack variable). + */ + TABLE tab; + table= &tab; + VOID(pthread_mutex_lock(&LOCK_open)); + if (!open_unireg_entry(thd, table, table_list, alias, + key, key_length, mem_root, 0)) + { + DBUG_ASSERT(table_list->view != 0); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(0); // VIEW + } + VOID(pthread_mutex_unlock(&LOCK_open)); + } + } + /* + No table in the locked tables list. In case of explicit LOCK TABLES + this can happen if a user did not include the able into the list. + In case of pre-locked mode locked tables list is generated automatically, + so we may only end up here if the table did not exist when + locked tables list was created. + */ + if (table_list->alias && table_list->alias[0] == '$') + DBUG_RETURN(table); + if (thd->prelocked_mode == PRELOCKED) + my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias); + else + my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias); + DBUG_RETURN(0); + } + + /* + Non pre-locked/LOCK TABLES mode, and the table is not temporary: + this is the normal use case. + Now we should: + - try to find the table in the table cache. + - if one of the discovered TABLE instances is name-locked + (table->s->version == 0) or some thread has started FLUSH TABLES + (refresh_version > table->s->version), back off -- we have to wait + until no one holds a name lock on the table. + - if there is no such TABLE in the name cache, read the table definition + and insert it into the cache. + We perform all of the above under LOCK_open which currently protects + the open cache (also known as table cache) and table definitions stored + on disk. + */ + + VOID(pthread_mutex_lock(&LOCK_open)); + + /* + If it's the first table from a list of tables used in a query, + remember refresh_version (the version of open_cache state). + If the version changes while we're opening the remaining tables, + we will have to back off, close all the tables opened-so-far, + and try to reopen them. + Note: refresh_version is currently changed only during FLUSH TABLES. + */ + if (!thd->open_tables) + thd->version=refresh_version; + else if ((thd->version != refresh_version) && + ! (flags & MYSQL_LOCK_IGNORE_FLUSH)) + { + /* Someone did a refresh while thread was opening tables */ + if (refresh) + *refresh=1; + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(0); + } + + /* + In order for the back off and re-start process to work properly, + handler tables having old versions (due to FLUSH TABLES or pending + name-lock) MUST be closed. This is specially important if a name-lock + is pending for any table of the handler_tables list, otherwise a + deadlock may occur. + */ + if (thd->handler_tables) + mysql_ha_flush(thd); + + /* + Actually try to find the table in the open_cache. + The cache may contain several "TABLE" instances for the same + physical table. The instances that are currently "in use" by + some thread have their "in_use" member != NULL. + There is no good reason for having more than one entry in the + hash for the same physical table, except that we use this as + an implicit "pending locks queue" - see + wait_for_locked_table_names for details. + */ + for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length, + &state); + table && table->in_use ; + table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length, + &state)) + { + DBUG_PRINT("tcache", ("in_use table: '%s'.'%s' 0x%lx", table->s->db.str, + table->s->table_name.str, (long) table)); + /* + Here we flush tables marked for flush. + Normally, table->s->version contains the value of + refresh_version from the moment when this table was + (re-)opened and added to the cache. + If since then we did (or just started) FLUSH TABLES + statement, refresh_version has been increased. + For "name-locked" TABLE instances, table->s->version is set + to 0 (see lock_table_name for details). + In case there is a pending FLUSH TABLES or a name lock, we + need to back off and re-start opening tables. + If we do not back off now, we may dead lock in case of lock + order mismatch with some other thread: + c1: name lock t1; -- sort of exclusive lock + c2: open t2; -- sort of shared lock + c1: name lock t2; -- blocks + c2: open t1; -- blocks + */ + if (table->needs_reopen_or_name_lock()) + { + DBUG_PRINT("note", + ("Found table '%s.%s' with different refresh version", + table_list->db, table_list->table_name)); + + if (flags & MYSQL_LOCK_IGNORE_FLUSH) + { + /* Force close at once after usage */ + thd->version= table->s->version; + continue; + } + + /* Avoid self-deadlocks by detecting self-dependencies. */ + if (table->open_placeholder && table->in_use == thd) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str); + DBUG_RETURN(0); + } + + /* + Back off, part 1: mark the table as "unused" for the + purpose of name-locking by setting table->db_stat to 0. Do + that only for the tables in this thread that have an old + table->s->version (this is an optimization (?)). + table->db_stat == 0 signals wait_for_locked_table_names + that the tables in question are not used any more. See + table_is_used call for details. + + Notice that HANDLER tables were already taken care of by + the earlier call to mysql_ha_flush() in this same critical + section. + */ + close_old_data_files(thd,thd->open_tables,0,0); + /* + Back-off part 2: try to avoid "busy waiting" on the table: + if the table is in use by some other thread, we suspend + and wait till the operation is complete: when any + operation that juggles with table->s->version completes, + it broadcasts COND_refresh condition variable. + If 'old' table we met is in use by current thread we return + without waiting since in this situation it's this thread + which is responsible for broadcasting on COND_refresh + (and this was done already in close_old_data_files()). + Good example of such situation is when we have statement + that needs two instances of table and FLUSH TABLES comes + after we open first instance but before we open second + instance. + */ + if (table->in_use != thd) + { + /* wait_for_conditionwill unlock LOCK_open for us */ + wait_for_condition(thd, &LOCK_open, &COND_refresh); + } + else + { + VOID(pthread_mutex_unlock(&LOCK_open)); + } + /* + There is a refresh in progress for this table. + Signal the caller that it has to try again. + */ + if (refresh) + *refresh=1; + DBUG_RETURN(0); + } + } + if (table) + { + DBUG_PRINT("tcache", ("unused table: '%s'.'%s' 0x%lx", table->s->db.str, + table->s->table_name.str, (long) table)); + /* Unlink the table from "unused_tables" list. */ + if (table == unused_tables) + { // First unused + unused_tables=unused_tables->next; // Remove from link + if (table == unused_tables) + unused_tables=0; + } + table->prev->next=table->next; /* Remove from unused list */ + table->next->prev=table->prev; + table->in_use= thd; + } + else + { + /* Insert a new TABLE instance into the open cache */ + int error; + DBUG_PRINT("tcache", ("opening new table")); + /* Free cache if too big */ + while (open_cache.records > table_cache_size && unused_tables) + VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */ + + if (table_list->create) + { + bool exists; + + if (check_if_table_exists(thd, table_list, &exists)) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(NULL); + } + + if (!exists) + { + /* + Table to be created, so we need to create placeholder in table-cache. + */ + if (!(table= table_cache_insert_placeholder(thd, key, key_length))) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(NULL); + } + /* + Link placeholder to the open tables list so it will be automatically + removed once tables are closed. Also mark it so it won't be ignored + by other trying to take name-lock. + */ + table->open_placeholder= 1; + table->next= thd->open_tables; + thd->open_tables= table; + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(table); + } + /* Table exists. Let us try to open it. */ + } + + /* make a new table */ + if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME)))) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(NULL); + } + + error= open_unireg_entry(thd, table, table_list, alias, key, key_length, + mem_root, (flags & OPEN_VIEW_NO_PARSE)); + if (error > 0) + { + my_free((uchar*)table, MYF(0)); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(NULL); + } + if (table_list->view || error < 0) + { + /* + VIEW not really opened, only frm were read. + Set 1 as a flag here + */ + if (error < 0) + table_list->view= (st_lex*)1; + + my_free((uchar*)table, MYF(0)); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(0); // VIEW + } + DBUG_PRINT("info", ("inserting table '%s'.'%s' 0x%lx into the cache", + table->s->db.str, table->s->table_name.str, + (long) table)); + VOID(my_hash_insert(&open_cache,(uchar*) table)); + } + + check_unused(); // Debugging call + + VOID(pthread_mutex_unlock(&LOCK_open)); + if (refresh) + { + table->next=thd->open_tables; /* Link into simple list */ + thd->open_tables=table; + } + table->reginfo.lock_type=TL_READ; /* Assume read */ + + reset: + DBUG_ASSERT(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE); + + if (thd->lex->need_correct_ident()) + table->alias_name_used= my_strcasecmp(table_alias_charset, + table->s->table_name.str, alias); + /* Fix alias if table name changes */ + if (strcmp(table->alias, alias)) + { + uint length=(uint) strlen(alias)+1; + table->alias= (char*) my_realloc((char*) table->alias, length, + MYF(MY_WME)); + memcpy((char*) table->alias, alias, length); + } + /* These variables are also set in reopen_table() */ + table->tablenr=thd->current_tablenr++; + table->used_fields=0; + table->const_table=0; + table->null_row= table->maybe_null= table->force_index= 0; + table->status=STATUS_NO_RECORD; + table->insert_values= 0; + table->fulltext_searched= 0; + table->file->ft_handler= 0; + table->reginfo.impossible_range= 0; + /* Catch wrong handling of the auto_increment_field_not_null. */ + DBUG_ASSERT(!table->auto_increment_field_not_null); + table->auto_increment_field_not_null= FALSE; + if (table->timestamp_field) + table->timestamp_field_type= table->timestamp_field->get_auto_set_type(); + table->pos_in_table_list= table_list; + table_list->updatable= 1; // It is not derived table nor non-updatable VIEW + table->clear_column_bitmaps(); + DBUG_ASSERT(table->key_read == 0); + DBUG_RETURN(table); +} + + +TABLE *find_locked_table(THD *thd, const char *db,const char *table_name) +{ + char key[MAX_DBKEY_LENGTH]; + uint key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1; + + for (TABLE *table=thd->open_tables; table ; table=table->next) + { + if (table->s->table_cache_key.length == key_length && + !memcmp(table->s->table_cache_key.str, key, key_length)) + return table; + } + return(0); +} + + +/* + Reopen an table because the definition has changed. + + SYNOPSIS + reopen_table() + table Table object + + NOTES + The data file for the table is already closed and the share is released + The table has a 'dummy' share that mainly contains database and table name. + + RETURN + 0 ok + 1 error. The old table object is not changed. +*/ + +bool reopen_table(TABLE *table) +{ + TABLE tmp; + bool error= 1; + Field **field; + uint key,part; + TABLE_LIST table_list; + THD *thd= table->in_use; + DBUG_ENTER("reopen_table"); + DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str, + table->s->table_name.str, (long) table)); + + DBUG_ASSERT(table->s->ref_count == 0); + DBUG_ASSERT(!table->sort.io_cache); + DBUG_ASSERT(!table->children_attached); + +#ifdef EXTRA_DEBUG + if (table->db_stat) + sql_print_error("Table %s had a open data handler in reopen_table", + table->alias); +#endif + bzero((char*) &table_list, sizeof(TABLE_LIST)); + table_list.db= table->s->db.str; + table_list.table_name= table->s->table_name.str; + table_list.table= table; + + if (wait_for_locked_table_names(thd, &table_list)) + DBUG_RETURN(1); // Thread was killed + + if (open_unireg_entry(thd, &tmp, &table_list, + table->alias, + table->s->table_cache_key.str, + table->s->table_cache_key.length, + thd->mem_root, 0)) + goto end; + + /* This list copies variables set by open_table */ + tmp.tablenr= table->tablenr; + tmp.used_fields= table->used_fields; + tmp.const_table= table->const_table; + tmp.null_row= table->null_row; + tmp.maybe_null= table->maybe_null; + tmp.status= table->status; + + tmp.s->table_map_id= table->s->table_map_id; + + /* Get state */ + tmp.in_use= thd; + tmp.reginfo.lock_type=table->reginfo.lock_type; + tmp.grant= table->grant; + + /* Replace table in open list */ + tmp.next= table->next; + tmp.prev= table->prev; + + /* Preserve MERGE parent. */ + tmp.parent= table->parent; + /* Fix MERGE child list and check for unchanged union. */ + if ((table->child_l || tmp.child_l) && + fix_merge_after_open(table->child_l, table->child_last_l, + tmp.child_l, tmp.child_last_l)) + { + VOID(closefrm(&tmp, 1)); // close file, free everything + goto end; + } + + delete table->triggers; + if (table->file) + VOID(closefrm(table, 1)); // close file, free everything + + *table= tmp; + table->default_column_bitmaps(); + table->file->change_table_ptr(table, table->s); + + DBUG_ASSERT(table->alias != 0); + for (field=table->field ; *field ; field++) + { + (*field)->table= (*field)->orig_table= table; + (*field)->table_name= &table->alias; + } + for (key=0 ; key < table->s->keys ; key++) + { + for (part=0 ; part < table->key_info[key].usable_key_parts ; part++) + { + table->key_info[key].key_part[part].field->table= table; + table->key_info[key].key_part[part].field->orig_table= table; + } + } + if (table->triggers) + table->triggers->set_table(table); + /* + Do not attach MERGE children here. The children might be reopened + after the parent. Attach children after reopening all tables that + require reopen. See for example reopen_tables(). + */ + + broadcast_refresh(); + error=0; + + end: + DBUG_RETURN(error); +} + + +/** + Close all instances of a table open by this thread and replace + them with exclusive name-locks. + + @param thd Thread context + @param db Database name for the table to be closed + @param table_name Name of the table to be closed + + @note This function assumes that if we are not under LOCK TABLES, + then there is only one table open and locked. This means that + the function probably has to be adjusted before it can be used + anywhere outside ALTER TABLE. + + @note Must not use TABLE_SHARE::table_name/db of the table being closed, + the strings are used in a loop even after the share may be freed. +*/ + +void close_data_files_and_morph_locks(THD *thd, const char *db, + const char *table_name) +{ + TABLE *table; + DBUG_ENTER("close_data_files_and_morph_locks"); + + safe_mutex_assert_owner(&LOCK_open); + + if (thd->lock) + { + /* + If we are not under LOCK TABLES we should have only one table + open and locked so it makes sense to remove the lock at once. + */ + mysql_unlock_tables(thd, thd->lock); + thd->lock= 0; + } + + /* + Note that open table list may contain a name-lock placeholder + for target table name if we process ALTER TABLE ... RENAME. + So loop below makes sense even if we are not under LOCK TABLES. + */ + for (table=thd->open_tables; table ; table=table->next) + { + if (!strcmp(table->s->table_name.str, table_name) && + !strcmp(table->s->db.str, db)) + { + if (thd->locked_tables) + { + if (table->parent) + { + /* + If MERGE child, need to reopen parent too. This means that + the first child to be closed will detach all children from + the parent and close it. OTOH in most cases a MERGE table + won't have multiple children with the same db.table_name. + */ + mysql_lock_remove(thd, thd->locked_tables, table->parent, TRUE); + table->parent->open_placeholder= 1; + close_handle_and_leave_table_as_lock(table->parent); + } + else + mysql_lock_remove(thd, thd->locked_tables, table, TRUE); + } + table->open_placeholder= 1; + close_handle_and_leave_table_as_lock(table); + } + } + DBUG_VOID_RETURN; +} + + +/** + Reattach MERGE children after reopen. + + @param[in] thd thread context + @param[in,out] err_tables_p pointer to pointer of tables in error + + @return status + @retval FALSE OK, err_tables_p unchanged + @retval TRUE Error, err_tables_p contains table(s) +*/ + +static bool reattach_merge(THD *thd, TABLE **err_tables_p) +{ + TABLE *table; + TABLE *next; + TABLE **prv_p= &thd->open_tables; + bool error= FALSE; + DBUG_ENTER("reattach_merge"); + + for (table= thd->open_tables; table; table= next) + { + next= table->next; + DBUG_PRINT("tcache", ("check table: '%s'.'%s' 0x%lx next: 0x%lx", + table->s->db.str, table->s->table_name.str, + (long) table, (long) next)); + /* Reattach children for MERGE tables with "closed data files" only. */ + if (table->child_l && !table->children_attached) + { + DBUG_PRINT("tcache", ("MERGE parent, attach children")); + if(table->file->extra(HA_EXTRA_ATTACH_CHILDREN)) + { + my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias); + error= TRUE; + /* Remove table from open_tables. */ + *prv_p= next; + if (next) + prv_p= &next->next; + /* Stack table on error list. */ + table->next= *err_tables_p; + *err_tables_p= table; + continue; + } + else + { + table->children_attached= TRUE; + DBUG_PRINT("myrg", ("attached parent: '%s'.'%s' 0x%lx", + table->s->db.str, + table->s->table_name.str, (long) table)); + } + } + prv_p= &table->next; + } + DBUG_RETURN(error); +} + + +/** + Reopen all tables with closed data files. + + @param thd Thread context + @param get_locks Should we get locks after reopening tables ? + @param mark_share_as_old Mark share as old to protect from a impending + global read lock. + + @note Since this function can't properly handle prelocking and + create placeholders it should be used in very special + situations like FLUSH TABLES or ALTER TABLE. In general + case one should just repeat open_tables()/lock_tables() + combination when one needs tables to be reopened (for + example see open_and_lock_tables()). + + @note One should have lock on LOCK_open when calling this. + + @return FALSE in case of success, TRUE - otherwise. +*/ + +bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old) +{ + TABLE *table,*next,**prev; + TABLE **tables,**tables_ptr; // For locks + TABLE *err_tables= NULL; + bool error=0, not_used; + bool merge_table_found= FALSE; + const uint flags= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN | + MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK | + MYSQL_LOCK_IGNORE_FLUSH; + + DBUG_ENTER("reopen_tables"); + + if (!thd->open_tables) + DBUG_RETURN(0); + + safe_mutex_assert_owner(&LOCK_open); + if (get_locks) + { + /* + The ptr is checked later + Do not handle locks of MERGE children. + */ + uint opens=0; + for (table= thd->open_tables; table ; table=table->next) + if (!table->parent) + opens++; + DBUG_PRINT("tcache", ("open tables to lock: %u", opens)); + tables= (TABLE**) my_alloca(sizeof(TABLE*)*opens); + } + else + tables= &thd->open_tables; + tables_ptr =tables; + + prev= &thd->open_tables; + for (table=thd->open_tables; table ; table=next) + { + uint db_stat=table->db_stat; + next=table->next; + DBUG_PRINT("tcache", ("open table: '%s'.'%s' 0x%lx " + "parent: 0x%lx db_stat: %u", + table->s->db.str, table->s->table_name.str, + (long) table, (long) table->parent, db_stat)); + if (table->child_l && !db_stat) + merge_table_found= TRUE; + if (!tables || (!db_stat && reopen_table(table))) + { + my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias); + /* + If we could not allocate 'tables', we may close open tables + here. If a MERGE table is affected, detach the children first. + It is not necessary to clear the child or parent table reference + of this table because the TABLE is freed. But we need to clear + the child or parent references of the other belonging tables so + that they cannot be moved into the unused_tables chain with + these pointers set. + */ + if (table->child_l || table->parent) + detach_merge_children(table, TRUE); + VOID(hash_delete(&open_cache,(uchar*) table)); + error=1; + } + else + { + DBUG_PRINT("tcache", ("opened. need lock: %d", + get_locks && !db_stat && !table->parent)); + *prev= table; + prev= &table->next; + /* Do not handle locks of MERGE children. */ + if (get_locks && !db_stat && !table->parent) + *tables_ptr++= table; // need new lock on this + if (mark_share_as_old) + { + table->s->version=0; + table->open_placeholder= 0; + } + } + } + *prev=0; + /* + When all tables are open again, we can re-attach MERGE children to + their parents. All TABLE objects are still present. + */ + DBUG_PRINT("tcache", ("re-attaching MERGE tables: %d", merge_table_found)); + if (!error && merge_table_found && reattach_merge(thd, &err_tables)) + { + while (err_tables) + { + VOID(hash_delete(&open_cache, (uchar*) err_tables)); + err_tables= err_tables->next; + } + } + DBUG_PRINT("tcache", ("open tables to lock: %u", + (uint) (tables_ptr - tables))); + if (tables != tables_ptr) // Should we get back old locks + { + MYSQL_LOCK *lock; + /* + We should always get these locks. Anyway, we must not go into + wait_for_tables() as it tries to acquire LOCK_open, which is + already locked. + */ + thd->some_tables_deleted=0; + if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables), + flags, ¬_used))) + { + thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock); + } + else + { + /* + This case should only happen if there is a bug in the reopen logic. + Need to issue error message to have a reply for the application. + Not exactly what happened though, but close enough. + */ + my_error(ER_LOCK_DEADLOCK, MYF(0)); + error=1; + } + } + if (get_locks && tables) + { + my_afree((uchar*) tables); + } + broadcast_refresh(); + DBUG_RETURN(error); +} + + +/** + Close handlers for tables in list, but leave the TABLE structure + intact so that we can re-open these quickly. + + @param thd Thread context + @param table Head of the list of TABLE objects + @param morph_locks TRUE - remove locks which we have on tables being closed + but ensure that no DML or DDL will sneak in before + we will re-open the table (i.e. temporarily morph + our table-level locks into name-locks). + FALSE - otherwise + @param send_refresh Should we awake waiters even if we didn't close any tables? +*/ + +static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks, + bool send_refresh) +{ + bool found= send_refresh; + DBUG_ENTER("close_old_data_files"); + + for (; table ; table=table->next) + { + DBUG_PRINT("tcache", ("checking table: '%s'.'%s' 0x%lx", + table->s->db.str, table->s->table_name.str, + (long) table)); + DBUG_PRINT("tcache", ("needs refresh: %d is open: %u", + table->needs_reopen_or_name_lock(), table->db_stat)); + /* + Reopen marked for flush. + */ + if (table->needs_reopen_or_name_lock()) + { + found=1; + if (table->db_stat) + { + if (morph_locks) + { + /* + Forward lock handling to MERGE parent. But unlock parent + once only. + */ + TABLE *ulcktbl= table->parent ? table->parent : table; + if (ulcktbl->lock_count) + { + /* + Wake up threads waiting for table-level lock on this table + so they won't sneak in when we will temporarily remove our + lock on it. This will also give them a chance to close their + instances of this table. + */ + mysql_lock_abort(thd, ulcktbl, TRUE); + mysql_lock_remove(thd, thd->locked_tables, ulcktbl, TRUE); + ulcktbl->lock_count= 0; + } + if ((ulcktbl != table) && ulcktbl->db_stat) + { + /* + Close the parent too. Note that parent can come later in + the list of tables. It will then be noticed as closed and + as a placeholder. When this happens, do not clear the + placeholder flag. See the branch below ("***"). + */ + ulcktbl->open_placeholder= 1; + close_handle_and_leave_table_as_lock(ulcktbl); + } + /* + We want to protect the table from concurrent DDL operations + (like RENAME TABLE) until we will re-open and re-lock it. + */ + table->open_placeholder= 1; + } + close_handle_and_leave_table_as_lock(table); + } + else if (table->open_placeholder && !morph_locks) + { + /* + We come here only in close-for-back-off scenario. So we have to + "close" create placeholder here to avoid deadlocks (for example, + in case of concurrent execution of CREATE TABLE t1 SELECT * FROM t2 + and RENAME TABLE t2 TO t1). In close-for-re-open scenario we will + probably want to let it stay. + + Note "***": We must not enter this branch if the placeholder + flag has been set because of a former close through a child. + See above the comment that refers to this note. + */ + table->open_placeholder= 0; + } + } + } + if (found) + broadcast_refresh(); + DBUG_VOID_RETURN; +} + + +/* + Wait until all threads has closed the tables in the list + We have also to wait if there is thread that has a lock on this table even + if the table is closed +*/ + +bool table_is_used(TABLE *table, bool wait_for_name_lock) +{ + DBUG_ENTER("table_is_used"); + do + { + char *key= table->s->table_cache_key.str; + uint key_length= table->s->table_cache_key.length; + + DBUG_PRINT("loop", ("table_name: %s", table->alias)); + HASH_SEARCH_STATE state; + for (TABLE *search= (TABLE*) hash_first(&open_cache, (uchar*) key, + key_length, &state); + search ; + search= (TABLE*) hash_next(&open_cache, (uchar*) key, + key_length, &state)) + { + DBUG_PRINT("info", ("share: 0x%lx " + "open_placeholder: %d locked_by_name: %d " + "db_stat: %u version: %lu", + (ulong) search->s, + search->open_placeholder, search->locked_by_name, + search->db_stat, + search->s->version)); + if (search->in_use == table->in_use) + continue; // Name locked by this thread + /* + We can't use the table under any of the following conditions: + - There is an name lock on it (Table is to be deleted or altered) + - If we are in flush table and we didn't execute the flush + - If the table engine is open and it's an old version + (We must wait until all engines are shut down to use the table) + */ + if ( (search->locked_by_name && wait_for_name_lock) || + (search->is_name_opened() && search->needs_reopen_or_name_lock())) + DBUG_RETURN(1); + } + } while ((table=table->next)); + DBUG_RETURN(0); +} + + +/* Wait until all used tables are refreshed */ + +bool wait_for_tables(THD *thd) +{ + bool result; + DBUG_ENTER("wait_for_tables"); + + thd_proc_info(thd, "Waiting for tables"); + pthread_mutex_lock(&LOCK_open); + while (!thd->killed) + { + thd->some_tables_deleted=0; + close_old_data_files(thd,thd->open_tables,0,dropping_tables != 0); + mysql_ha_flush(thd); + if (!table_is_used(thd->open_tables,1)) + break; + (void) pthread_cond_wait(&COND_refresh,&LOCK_open); + } + if (thd->killed) + result= 1; // aborted + else + { + /* Now we can open all tables without any interference */ + thd_proc_info(thd, "Reopen tables"); + thd->version= refresh_version; + result=reopen_tables(thd,0,0); + } + pthread_mutex_unlock(&LOCK_open); + thd_proc_info(thd, 0); + DBUG_RETURN(result); +} + + +/* + drop tables from locked list + + SYNOPSIS + drop_locked_tables() + thd Thread thandler + db Database + table_name Table name + + INFORMATION + This is only called on drop tables + + The TABLE object for the dropped table is unlocked but still kept around + as a name lock, which means that the table will be available for other + thread as soon as we call unlock_table_names(). + If there is multiple copies of the table locked, all copies except + the first, which acts as a name lock, is removed. + + RETURN + # If table existed, return table + 0 Table was not locked +*/ + + +TABLE *drop_locked_tables(THD *thd,const char *db, const char *table_name) +{ + TABLE *table,*next,**prev, *found= 0; + prev= &thd->open_tables; + DBUG_ENTER("drop_locked_tables"); + + /* + Note that we need to hold LOCK_open while changing the + open_tables list. Another thread may work on it. + (See: remove_table_from_cache(), mysql_wait_completed_table()) + Closing a MERGE child before the parent would be fatal if the + other thread tries to abort the MERGE lock in between. + */ + for (table= thd->open_tables; table ; table=next) + { + next=table->next; + if (!strcmp(table->s->table_name.str, table_name) && + !strcmp(table->s->db.str, db)) + { + /* If MERGE child, forward lock handling to parent. */ + mysql_lock_remove(thd, thd->locked_tables, + table->parent ? table->parent : table, TRUE); + /* + When closing a MERGE parent or child table, detach the children first. + Clear child table references in case this object is opened again. + */ + if (table->child_l || table->parent) + detach_merge_children(table, TRUE); + + if (!found) + { + found= table; + /* Close engine table, but keep object around as a name lock */ + if (table->db_stat) + { + table->db_stat= 0; + table->file->close(); + } + } + else + { + /* We already have a name lock, remove copy */ + VOID(hash_delete(&open_cache,(uchar*) table)); + } + } + else + { + *prev=table; + prev= &table->next; + } + } + *prev=0; + if (found) + broadcast_refresh(); + if (thd->locked_tables && thd->locked_tables->table_count == 0) + { + my_free((uchar*) thd->locked_tables,MYF(0)); + thd->locked_tables=0; + } + DBUG_RETURN(found); +} + + +/* + If we have the table open, which only happens when a LOCK TABLE has been + done on the table, change the lock type to a lock that will abort all + other threads trying to get the lock. +*/ + +void abort_locked_tables(THD *thd,const char *db, const char *table_name) +{ + TABLE *table; + for (table= thd->open_tables; table ; table= table->next) + { + if (!strcmp(table->s->table_name.str, table_name) && + !strcmp(table->s->db.str, db)) + { + /* If MERGE child, forward lock handling to parent. */ + mysql_lock_abort(thd, table->parent ? table->parent : table, TRUE); + break; + } + } +} + + +/* + Function to assign a new table map id to a table share. + + PARAMETERS + + share - Pointer to table share structure + + DESCRIPTION + + We are intentionally not checking that share->mutex is locked + since this function should only be called when opening a table + share and before it is entered into the table_def_cache (meaning + that it cannot be fetched by another thread, even accidentally). + + PRE-CONDITION(S) + + share is non-NULL + The LOCK_open mutex is locked + + POST-CONDITION(S) + + share->table_map_id is given a value that with a high certainty is + not used by any other table (the only case where a table id can be + reused is on wrap-around, which means more than 4 billion table + share opens have been executed while one table was open all the + time). + + share->table_map_id is not ~0UL. + */ +static ulong last_table_id= ~0UL; + +void assign_new_table_id(TABLE_SHARE *share) +{ + + DBUG_ENTER("assign_new_table_id"); + + /* Preconditions */ + DBUG_ASSERT(share != NULL); + safe_mutex_assert_owner(&LOCK_open); + + ulong tid= ++last_table_id; /* get next id */ + /* + There is one reserved number that cannot be used. Remember to + change this when 6-byte global table id's are introduced. + */ + if (unlikely(tid == ~0UL)) + tid= ++last_table_id; + share->table_map_id= tid; + DBUG_PRINT("info", ("table_id=%lu", tid)); + + /* Post conditions */ + DBUG_ASSERT(share->table_map_id != ~0UL); + + DBUG_VOID_RETURN; +} + +#ifndef DBUG_OFF +/* Cause a spurious statement reprepare for debug purposes. */ +static bool inject_reprepare(THD *thd) +{ + if (thd->m_reprepare_observer && thd->stmt_arena->is_reprepared == FALSE) + { + thd->m_reprepare_observer->report_error(thd); + return TRUE; + } + + return FALSE; +} +#endif + +/** + Compare metadata versions of an element obtained from the table + definition cache and its corresponding node in the parse tree. + + @details If the new and the old values mismatch, invoke + Metadata_version_observer. + At prepared statement prepare, all TABLE_LIST version values are + NULL and we always have a mismatch. But there is no observer set + in THD, and therefore no error is reported. Instead, we update + the value in the parse tree, effectively recording the original + version. + At prepared statement execute, an observer may be installed. If + there is a version mismatch, we push an error and return TRUE. + + For conventional execution (no prepared statements), the + observer is never installed. + + @sa Execute_observer + @sa check_prepared_statement() to see cases when an observer is installed + @sa TABLE_LIST::is_table_ref_id_equal() + @sa TABLE_SHARE::get_table_ref_id() + + @param[in] thd used to report errors + @param[in,out] tables TABLE_LIST instance created by the parser + Metadata version information in this object + is updated upon success. + @param[in] table_share an element from the table definition cache + + @retval TRUE an error, which has been reported + @retval FALSE success, version in TABLE_LIST has been updated +*/ + +bool +check_and_update_table_version(THD *thd, + TABLE_LIST *tables, TABLE_SHARE *table_share) +{ + if (! tables->is_table_ref_id_equal(table_share)) + { + if (thd->m_reprepare_observer && + thd->m_reprepare_observer->report_error(thd)) + { + /* + Version of the table share is different from the + previous execution of the prepared statement, and it is + unacceptable for this SQLCOM. Error has been reported. + */ + DBUG_ASSERT(thd->is_error()); + return TRUE; + } + /* Always maintain the latest version and type */ + tables->set_table_ref_id(table_share); + } + + DBUG_EXECUTE_IF("reprepare_each_statement", return inject_reprepare(thd);); + + return FALSE; +} + +/* + Load a table definition from file and open unireg table + + SYNOPSIS + open_unireg_entry() + thd Thread handle + entry Store open table definition here + table_list TABLE_LIST with db, table_name & belong_to_view + alias Alias name + cache_key Key for share_cache + cache_key_length length of cache_key + mem_root temporary mem_root for parsing + flags the OPEN_VIEW_NO_PARSE flag to be passed to + openfrm()/open_new_frm() + + NOTES + Extra argument for open is taken from thd->open_options + One must have a lock on LOCK_open when calling this function + + RETURN + 0 ok + # Error +*/ + +static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list, + const char *alias, + char *cache_key, uint cache_key_length, + MEM_ROOT *mem_root, uint flags) +{ + int error; + TABLE_SHARE *share; + uint discover_retry_count= 0; + DBUG_ENTER("open_unireg_entry"); + + safe_mutex_assert_owner(&LOCK_open); +retry: + if (!(share= get_table_share_with_create(thd, table_list, cache_key, + cache_key_length, + OPEN_VIEW | + table_list->i_s_requested_object, + &error))) + DBUG_RETURN(1); + + if (share->is_view) + { + /* + If parent_l of the table_list is non null then a merge table + has this view as child table, which is not supported. + */ + if (table_list->parent_l) + { + my_error(ER_WRONG_MRG_TABLE, MYF(0)); + goto err; + } + + /* + This table is a view. Validate its metadata version: in particular, + that it was a view when the statement was prepared. + */ + if (check_and_update_table_version(thd, table_list, share)) + goto err; + if (table_list->i_s_requested_object & OPEN_TABLE_ONLY) + goto err; + + /* Open view */ + error= (int) open_new_frm(thd, share, alias, + (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE | + HA_GET_INDEX | HA_TRY_READ_ONLY), + READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD | + (flags & OPEN_VIEW_NO_PARSE), + thd->open_options, entry, table_list, + mem_root); + if (error) + goto err; + /* TODO: Don't free this */ + release_table_share(share, RELEASE_NORMAL); + DBUG_RETURN((flags & OPEN_VIEW_NO_PARSE)? -1 : 0); + } + else if (table_list->view) + { + /* + We're trying to open a table for what was a view. + This can only happen during (re-)execution. + At prepared statement prepare the view has been opened and + merged into the statement parse tree. After that, someone + performed a DDL and replaced the view with a base table. + Don't try to open the table inside a prepared statement, + invalidate it instead. + + Note, the assert below is known to fail inside stored + procedures (Bug#27011). + */ + DBUG_ASSERT(thd->m_reprepare_observer); + check_and_update_table_version(thd, table_list, share); + /* Always an error. */ + DBUG_ASSERT(thd->is_error()); + goto err; + } + + if (table_list->i_s_requested_object & OPEN_VIEW_ONLY) + goto err; + + while ((error= open_table_from_share(thd, share, alias, + (uint) (HA_OPEN_KEYFILE | + HA_OPEN_RNDFILE | + HA_GET_INDEX | + HA_TRY_READ_ONLY), + (READ_KEYINFO | COMPUTE_TYPES | + EXTRA_RECORD), + thd->open_options, entry, FALSE))) + { + if (error == 7) // Table def changed + { + share->version= 0; // Mark share as old + if (discover_retry_count++) // Retry once + goto err; + + /* + TODO: + Here we should wait until all threads has released the table. + For now we do one retry. This may cause a deadlock if there + is other threads waiting for other tables used by this thread. + + Proper fix would be to if the second retry failed: + - Mark that table def changed + - Return from open table + - Close all tables used by this thread + - Start waiting that the share is released + - Retry by opening all tables again + */ + if (ha_create_table_from_engine(thd, table_list->db, + table_list->table_name)) + goto err; + /* + TO BE FIXED + To avoid deadlock, only wait for release if no one else is + using the share. + */ + if (share->ref_count != 1) + goto err; + /* Free share and wait until it's released by all threads */ + release_table_share(share, RELEASE_WAIT_FOR_DROP); + if (!thd->killed) + { + mysql_reset_errors(thd, 1); // Clear warnings + thd->clear_error(); // Clear error message + goto retry; + } + DBUG_RETURN(1); + } + if (!entry->s || !entry->s->crashed) + goto err; + // Code below is for repairing a crashed file + if ((error= lock_table_name(thd, table_list, TRUE))) + { + if (error < 0) + goto err; + if (wait_for_locked_table_names(thd, table_list)) + { + unlock_table_name(thd, table_list); + goto err; + } + } + pthread_mutex_unlock(&LOCK_open); + thd->clear_error(); // Clear error message + error= 0; + if (open_table_from_share(thd, share, alias, + (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE | + HA_GET_INDEX | + HA_TRY_READ_ONLY), + READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD, + ha_open_options | HA_OPEN_FOR_REPAIR, + entry, FALSE) || ! entry->file || + (entry->file->is_crashed() && entry->file->ha_check_and_repair(thd))) + { + /* Give right error message */ + thd->clear_error(); + my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno); + sql_print_error("Couldn't repair table: %s.%s", share->db.str, + share->table_name.str); + if (entry->file) + closefrm(entry, 0); + error=1; + } + else + thd->clear_error(); // Clear error message + pthread_mutex_lock(&LOCK_open); + unlock_table_name(thd, table_list); + + if (error) + goto err; + break; + } + + if (Table_triggers_list::check_n_load(thd, share->db.str, + share->table_name.str, entry, 0)) + { + closefrm(entry, 0); + goto err; + } + + /* + If we are here, there was no fatal error (but error may be still + unitialized). + */ + if (unlikely(entry->file->implicit_emptied)) + { + entry->file->implicit_emptied= 0; + if (mysql_bin_log.is_open()) + { + char *query, *end; + uint query_buf_size= 20 + share->db.length + share->table_name.length +1; + if ((query= (char*) my_malloc(query_buf_size,MYF(MY_WME)))) + { + /* this DELETE FROM is needed even with row-based binlogging */ + end = strxmov(strmov(query, "DELETE FROM `"), + share->db.str,"`.`",share->table_name.str,"`", NullS); + int errcode= query_error_code(thd, TRUE); + thd->binlog_query(THD::STMT_QUERY_TYPE, + query, (ulong)(end-query), + FALSE, FALSE, errcode); + my_free(query, MYF(0)); + } + else + { + /* + As replication is maybe going to be corrupted, we need to warn the + DBA on top of warning the client (which will automatically be done + because of MYF(MY_WME) in my_malloc() above). + */ + sql_print_error("When opening HEAP table, could not allocate memory " + "to write 'DELETE FROM `%s`.`%s`' to the binary log", + table_list->db, table_list->table_name); + delete entry->triggers; + closefrm(entry, 0); + goto err; + } + } + } + DBUG_RETURN(0); + +err: + release_table_share(share, RELEASE_NORMAL); + DBUG_RETURN(1); +} + + +/** + @brief Add list of MERGE children to a TABLE_LIST list. + + @param[in] tlist the parent TABLE_LIST object just opened + + @return status + @retval 0 OK + @retval != 0 Error + + @detail + When a MERGE parent table has just been opened, insert the + TABLE_LIST chain from the MERGE handle into the table list used for + opening tables for this statement. This lets the children be opened + too. +*/ + +static int add_merge_table_list(TABLE_LIST *tlist) +{ + TABLE *parent= tlist->table; + TABLE_LIST *child_l; + DBUG_ENTER("add_merge_table_list"); + DBUG_PRINT("myrg", ("table: '%s'.'%s' 0x%lx", parent->s->db.str, + parent->s->table_name.str, (long) parent)); + + /* Must not call this with attached children. */ + DBUG_ASSERT(!parent->children_attached); + /* Must not call this with children list in place. */ + DBUG_ASSERT(tlist->next_global != parent->child_l); + /* Prevent inclusion of another MERGE table. Could make infinite recursion. */ + if (tlist->parent_l) + { + my_error(ER_ADMIN_WRONG_MRG_TABLE, MYF(0), tlist->alias); + DBUG_RETURN(1); + } + + /* Fix children.*/ + for (child_l= parent->child_l; ; child_l= child_l->next_global) + { + /* + Note: child_l->table may still be set if this parent was taken + from the unused_tables chain. Ignore this fact here. The + reference will be replaced by the handler in + ::extra(HA_EXTRA_ATTACH_CHILDREN). + */ + + /* Set lock type. */ + child_l->lock_type= tlist->lock_type; + + /* Set parent reference. */ + child_l->parent_l= tlist; + + /* Break when this was the last child. */ + if (&child_l->next_global == parent->child_last_l) + break; + } + + /* Insert children into the table list. */ + *parent->child_last_l= tlist->next_global; + tlist->next_global= parent->child_l; + + /* + Do not fix the prev_global pointers. We will remove the + chain soon anyway. + */ + + DBUG_RETURN(0); +} + + +/** + @brief Attach MERGE children to the parent. + + @param[in] tlist the child TABLE_LIST object just opened + + @return status + @retval 0 OK + @retval != 0 Error + + @note + This is called when the last MERGE child has just been opened, let + the handler attach the MyISAM tables to the MERGE table. Remove + MERGE TABLE_LIST chain from the statement list so that it cannot be + changed or freed. +*/ + +static int attach_merge_children(TABLE_LIST *tlist) +{ + TABLE *parent= tlist->parent_l->table; + int error; + DBUG_ENTER("attach_merge_children"); + DBUG_PRINT("myrg", ("table: '%s'.'%s' 0x%lx", parent->s->db.str, + parent->s->table_name.str, (long) parent)); + + /* Must not call this with attached children. */ + DBUG_ASSERT(!parent->children_attached); + /* Must call this with children list in place. */ + DBUG_ASSERT(tlist->parent_l->next_global == parent->child_l); + + /* Attach MyISAM tables to MERGE table. */ + error= parent->file->extra(HA_EXTRA_ATTACH_CHILDREN); + + /* + Remove children from the table list. Even in case of an error. + This should prevent tampering with them. + */ + tlist->parent_l->next_global= *parent->child_last_l; + + /* + Do not fix the last childs next_global pointer. It is needed for + stepping to the next table in the enclosing loop in open_tables(). + Do not fix prev_global pointers. We did not set them. + */ + + if (error) + { + DBUG_PRINT("error", ("attaching MERGE children failed: %d", my_errno)); + parent->file->print_error(error, MYF(0)); + DBUG_RETURN(1); + } + + parent->children_attached= TRUE; + DBUG_PRINT("myrg", ("attached parent: '%s'.'%s' 0x%lx", parent->s->db.str, + parent->s->table_name.str, (long) parent)); + + /* + Note that we have the cildren in the thd->open_tables list at this + point. + */ + + DBUG_RETURN(0); +} + + +/** + @brief Detach MERGE children from the parent. + + @note + Call this before the first table of a MERGE table (parent or child) + is closed. + + When closing thread tables at end of statement, both parent and + children are in thd->open_tables and will be closed. In most cases + the children will be closed before the parent. They are opened after + the parent and thus stacked into thd->open_tables before it. + + To avoid that we touch a closed children in any way, we must detach + the children from the parent when the first belonging table is + closed (parent or child). + + All references to the children should be removed on handler level + and optionally on table level. + + @note + Assure that you call it for a MERGE parent or child only. + Either table->child_l or table->parent must be set. + + @param[in] table the TABLE object of the parent + @param[in] clear_refs if to clear TABLE references + this must be true when called from + close_thread_tables() to enable fresh + open in open_tables() + it must be false when called in preparation + for reopen_tables() +*/ + +void detach_merge_children(TABLE *table, bool clear_refs) +{ + TABLE_LIST *child_l; + TABLE *parent= table->child_l ? table : table->parent; + bool first_detach; + DBUG_ENTER("detach_merge_children"); + /* + Either table->child_l or table->parent must be set. Parent must have + child_l set. + */ + DBUG_ASSERT(parent && parent->child_l); + DBUG_PRINT("myrg", ("table: '%s'.'%s' 0x%lx clear_refs: %d", + table->s->db.str, table->s->table_name.str, + (long) table, clear_refs)); + DBUG_PRINT("myrg", ("parent: '%s'.'%s' 0x%lx", parent->s->db.str, + parent->s->table_name.str, (long) parent)); + + /* + In a open_tables() loop it can happen that not all tables have their + children attached yet. Also this is called for every child and the + parent from close_thread_tables(). + */ + if ((first_detach= parent->children_attached)) + { + VOID(parent->file->extra(HA_EXTRA_DETACH_CHILDREN)); + parent->children_attached= FALSE; + DBUG_PRINT("myrg", ("detached parent: '%s'.'%s' 0x%lx", parent->s->db.str, + parent->s->table_name.str, (long) parent)); + } + else + DBUG_PRINT("myrg", ("parent is already detached")); + + if (clear_refs) + { + /* In any case clear the own parent reference. (***) */ + table->parent= NULL; + + /* + On the first detach, clear all references. If this table is the + parent, we still may need to clear the child references. The first + detach might not have done this. + */ + if (first_detach || (table == parent)) + { + /* Clear TABLE references to force new assignment at next open. */ + for (child_l= parent->child_l; ; child_l= child_l->next_global) + { + /* + Do not DBUG_ASSERT(child_l->table); open_tables might be + incomplete. + + Clear the parent reference of the children only on the first + detach. The children might already be closed. They will clear + it themseves when this function is called for them with + 'clear_refs' true. See above "(***)". + */ + if (first_detach && child_l->table) + child_l->table->parent= NULL; + + /* Clear the table reference to force new assignment at next open. */ + child_l->table= NULL; + + /* Break when this was the last child. */ + if (&child_l->next_global == parent->child_last_l) + break; + } + } + } + + DBUG_VOID_RETURN; +} + + +/** + @brief Fix MERGE children after open. + + @param[in] old_child_list first list member from original table + @param[in] old_last pointer to &next_global of last list member + @param[in] new_child_list first list member from freshly opened table + @param[in] new_last pointer to &next_global of last list member + + @return mismatch + @retval FALSE OK, no mismatch + @retval TRUE Error, lists mismatch + + @detail + Main action is to copy TABLE reference for each member of original + child list to new child list. After a fresh open these references + are NULL. Assign the old children to the new table. Some of them + might also be reopened or will be reopened soon. + + Other action is to verify that the table definition with respect to + the UNION list did not change. + + @note + This function terminates the child list if the respective '*_last' + pointer is non-NULL. Do not call it from a place where the list is + embedded in another list and this would break it. + + Terminating the list is required for example in the first + reopen_table() after open_tables(). open_tables() requires the end + of the list not to be terminated because other tables could follow + behind the child list. + + If a '*_last' pointer is NULL, the respective list is assumed to be + NULL terminated. +*/ + +bool fix_merge_after_open(TABLE_LIST *old_child_list, TABLE_LIST **old_last, + TABLE_LIST *new_child_list, TABLE_LIST **new_last) +{ + bool mismatch= FALSE; + DBUG_ENTER("fix_merge_after_open"); + DBUG_PRINT("myrg", ("old last addr: 0x%lx new last addr: 0x%lx", + (long) old_last, (long) new_last)); + + /* Terminate the lists for easier check of list end. */ + if (old_last) + *old_last= NULL; + if (new_last) + *new_last= NULL; + + for (;;) + { + DBUG_PRINT("myrg", ("old list item: 0x%lx new list item: 0x%lx", + (long) old_child_list, (long) new_child_list)); + /* Break if one of the list is at its end. */ + if (!old_child_list || !new_child_list) + break; + /* Old table has references to child TABLEs. */ + DBUG_ASSERT(old_child_list->table); + /* New table does not yet have references to child TABLEs. */ + DBUG_ASSERT(!new_child_list->table); + DBUG_PRINT("myrg", ("old table: '%s'.'%s' new table: '%s'.'%s'", + old_child_list->db, old_child_list->table_name, + new_child_list->db, new_child_list->table_name)); + /* Child db.table names must match. */ + if (strcmp(old_child_list->table_name, new_child_list->table_name) || + strcmp(old_child_list->db, new_child_list->db)) + break; + /* + Copy TABLE reference. Child TABLE objects are still in place + though not necessarily open yet. + */ + DBUG_PRINT("myrg", ("old table ref: 0x%lx replaces new table ref: 0x%lx", + (long) old_child_list->table, + (long) new_child_list->table)); + new_child_list->table= old_child_list->table; + /* Step both lists. */ + old_child_list= old_child_list->next_global; + new_child_list= new_child_list->next_global; + } + DBUG_PRINT("myrg", ("end of list, mismatch: %d", mismatch)); + /* + If the list pointers are not both NULL after the loop, then the + lists differ. If the are both identical, but not NULL, then they + have at least one table in common and hence the rest of the list + would be identical too. But in this case the loop woul run until the + list end, where both pointers would become NULL. + */ + if (old_child_list != new_child_list) + mismatch= TRUE; + if (mismatch) + my_error(ER_TABLE_DEF_CHANGED, MYF(0)); + + DBUG_RETURN(mismatch); +} + + +/* + Return a appropriate read lock type given a table object. + + @param thd Thread context + @param table TABLE object for table to be locked + + @remark Due to a statement-based replication limitation, statements such as + INSERT INTO .. SELECT FROM .. and CREATE TABLE .. SELECT FROM need + to grab a TL_READ_NO_INSERT lock on the source table in order to + prevent the replication of a concurrent statement that modifies the + source table. If such a statement gets applied on the slave before + the INSERT .. SELECT statement finishes, data on the master could + differ from data on the slave and end-up with a discrepancy between + the binary log and table state. Furthermore, this does not apply to + I_S and log tables as it's always unsafe to replicate such tables + under statement-based replication as the table on the slave might + contain other data (ie: general_log is enabled on the slave). The + statement will be marked as unsafe for SBR in decide_logging_format(). +*/ + +thr_lock_type read_lock_type_for_table(THD *thd, TABLE *table) +{ + bool log_on= mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG); + ulong binlog_format= thd->variables.binlog_format; + if ((log_on == FALSE) || (binlog_format == BINLOG_FORMAT_ROW) || + (table->s->table_category == TABLE_CATEGORY_PERFORMANCE)) + return TL_READ; + else + return TL_READ_NO_INSERT; +} + + +/* + Open all tables in list + + SYNOPSIS + open_tables() + thd - thread handler + start - list of tables in/out + counter - number of opened tables will be return using this parameter + flags - bitmap of flags to modify how the tables will be open: + MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has + done a flush or namelock on it. + + NOTE + Unless we are already in prelocked mode, this function will also precache + all SP/SFs explicitly or implicitly (via views and triggers) used by the + query and add tables needed for their execution to table list. If resulting + tables list will be non empty it will mark query as requiring precaching. + Prelocked mode will be enabled for such query during lock_tables() call. + + If query for which we are opening tables is already marked as requiring + prelocking it won't do such precaching and will simply reuse table list + which is already built. + + If any table has a trigger and start->trg_event_map is non-zero + the final lock will end up in thd->locked_tables, otherwise, the + lock will be placed in thd->lock. See also comments in + st_lex::set_trg_event_type_for_tables(). + + RETURN + 0 - OK + -1 - error +*/ + +int open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags) +{ + TABLE_LIST *tables= NULL; + bool refresh; + int result=0; + MEM_ROOT new_frm_mem; + /* Also used for indicating that prelocking is need */ + TABLE_LIST **query_tables_last_own; + bool safe_to_ignore_table; + + DBUG_ENTER("open_tables"); + /* + temporary mem_root for new .frm parsing. + TODO: variables for size + */ + init_sql_alloc(&new_frm_mem, 8024, 8024); + + thd->current_tablenr= 0; + restart: + *counter= 0; + query_tables_last_own= 0; + thd_proc_info(thd, "Opening tables"); + + /* + If we are not already executing prelocked statement and don't have + statement for which table list for prelocking is already built, let + us cache routines and try to build such table list. + + */ + + if (!thd->prelocked_mode && !thd->lex->requires_prelocking() && + thd->lex->uses_stored_routines()) + { + bool first_no_prelocking, need_prelocking; + TABLE_LIST **save_query_tables_last= thd->lex->query_tables_last; + + DBUG_ASSERT(thd->lex->query_tables == *start); + sp_get_prelocking_info(thd, &need_prelocking, &first_no_prelocking); + + if (sp_cache_routines_and_add_tables(thd, thd->lex, first_no_prelocking)) + { + /* + Serious error during reading stored routines from mysql.proc table. + Something's wrong with the table or its contents, and an error has + been emitted; we must abort. + */ + result= -1; + goto err; + } + else if (need_prelocking) + { + query_tables_last_own= save_query_tables_last; + *start= thd->lex->query_tables; + } + } + + /* + For every table in the list of tables to open, try to find or open + a table. + */ + for (tables= *start; tables ;tables= tables->next_global) + { + DBUG_PRINT("tcache", ("opening table: '%s'.'%s' item: 0x%lx", + tables->db, tables->table_name, (long) tables)); + + safe_to_ignore_table= FALSE; + + /* + Ignore placeholders for derived tables. After derived tables + processing, link to created temporary table will be put here. + If this is derived table for view then we still want to process + routines used by this view. + */ + if (tables->derived) + { + if (tables->view) + goto process_view_routines; + continue; + } + /* + If this TABLE_LIST object is a placeholder for an information_schema + table, create a temporary table to represent the information_schema + table in the query. Do not fill it yet - will be filled during + execution. + */ + if (tables->schema_table) + { + /* + If this information_schema table is merged into a mergeable + view, ignore it for now -- it will be filled when its respective + TABLE_LIST is processed. This code works only during re-execution. + */ + if (tables->view) + goto process_view_routines; + if (!mysql_schema_table(thd, thd->lex, tables) && + !check_and_update_table_version(thd, tables, tables->table->s)) + { + continue; + } + DBUG_RETURN(-1); + } + (*counter)++; + + /* + Not a placeholder: must be a base table or a view, and the table is + not opened yet. Try to open the table. + */ + if (!tables->table) + { + if (tables->prelocking_placeholder) + { + /* + For the tables added by the pre-locking code, attempt to open + the table but fail silently if the table does not exist. + The real failure will occur when/if a statement attempts to use + that table. + */ + Prelock_error_handler prelock_handler; + thd->push_internal_handler(& prelock_handler); + tables->table= open_table(thd, tables, &new_frm_mem, &refresh, flags); + thd->pop_internal_handler(); + safe_to_ignore_table= prelock_handler.safely_trapped_errors(); + } + else + tables->table= open_table(thd, tables, &new_frm_mem, &refresh, flags); + } + else + DBUG_PRINT("tcache", ("referenced table: '%s'.'%s' 0x%lx", + tables->db, tables->table_name, + (long) tables->table)); + + if (!tables->table) + { + free_root(&new_frm_mem, MYF(MY_KEEP_PREALLOC)); + + if (tables->view) + { + /* VIEW placeholder */ + (*counter)--; + + /* + tables->next_global list consists of two parts: + 1) Query tables and underlying tables of views. + 2) Tables used by all stored routines that this statement invokes on + execution. + We need to know where the bound between these two parts is. If we've + just opened a view, which was the last table in part #1, and it + has added its base tables after itself, adjust the boundary pointer + accordingly. + */ + if (query_tables_last_own == &(tables->next_global) && + tables->view->query_tables) + query_tables_last_own= tables->view->query_tables_last; + /* + Let us free memory used by 'sroutines' hash here since we never + call destructor for this LEX. + */ + hash_free(&tables->view->sroutines); + goto process_view_routines; + } + + /* + If in a MERGE table open, we need to remove the children list + from statement table list before restarting. Otherwise the list + will be inserted another time. + */ + if (tables->parent_l) + { + TABLE_LIST *parent_l= tables->parent_l; + /* The parent table should be correctly open at this point. */ + DBUG_ASSERT(parent_l->table); + parent_l->next_global= *parent_l->table->child_last_l; + } + + if (refresh) // Refresh in progress + { + /* + We have met name-locked or old version of table. Now we have + to close all tables which are not up to date. We also have to + throw away set of prelocked tables (and thus close tables from + this set that were open by now) since it possible that one of + tables which determined its content was changed. + + Instead of implementing complex/non-robust logic mentioned + above we simply close and then reopen all tables. + + In order to prepare for recalculation of set of prelocked tables + we pretend that we have finished calculation which we were doing + currently. + */ + if (query_tables_last_own) + thd->lex->mark_as_requiring_prelocking(query_tables_last_own); + close_tables_for_reopen(thd, start); + goto restart; + } + + if (safe_to_ignore_table) + { + DBUG_PRINT("info", ("open_table: ignoring table '%s'.'%s'", + tables->db, tables->alias)); + continue; + } + + result= -1; // Fatal error + break; + } + else + { + /* + If we are not already in prelocked mode and extended table list is not + yet built and we have trigger for table being opened then we should + cache all routines used by its triggers and add their tables to + prelocking list. + If we lock table for reading we won't update it so there is no need to + process its triggers since they never will be activated. + */ + if (!thd->prelocked_mode && !thd->lex->requires_prelocking() && + tables->trg_event_map && tables->table->triggers && + tables->lock_type >= TL_WRITE_ALLOW_WRITE) + { + if (!query_tables_last_own) + query_tables_last_own= thd->lex->query_tables_last; + if (sp_cache_routines_and_add_tables_for_triggers(thd, thd->lex, + tables)) + { + /* + Serious error during reading stored routines from mysql.proc table. + Something's wrong with the table or its contents, and an error has + been emitted; we must abort. + */ + result= -1; + goto err; + } + } + free_root(&new_frm_mem, MYF(MY_KEEP_PREALLOC)); + } + + if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables) + { + if (tables->lock_type == TL_WRITE_DEFAULT) + tables->table->reginfo.lock_type= thd->update_lock_default; + else if (tables->lock_type == TL_READ_DEFAULT) + tables->table->reginfo.lock_type= + read_lock_type_for_table(thd, tables->table); + else + tables->table->reginfo.lock_type= tables->lock_type; + } + tables->table->grant= tables->grant; + + // @InfiniDB relax checking for vtable create with prepare stmt execute + /* Check and update metadata version of a base table. */ + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE && + check_and_update_table_version(thd, tables, tables->table->s)) + { + result= -1; + goto err; + } + + /* Attach MERGE children if not locked already. */ + DBUG_PRINT("tcache", ("is parent: %d is child: %d", + test(tables->table->child_l), + test(tables->parent_l))); + DBUG_PRINT("tcache", ("in lock tables: %d in prelock mode: %d", + test(thd->locked_tables), test(thd->prelocked_mode))); + if (((!thd->locked_tables && !thd->prelocked_mode) || + tables->table->s->tmp_table) && + ((tables->table->child_l && + add_merge_table_list(tables)) || + (tables->parent_l && + (&tables->next_global == tables->parent_l->table->child_last_l) && + attach_merge_children(tables)))) + { + result= -1; + goto err; + } + +process_view_routines: + /* + Again we may need cache all routines used by this view and add + tables used by them to table list. + */ + if (tables->view && !thd->prelocked_mode && + !thd->lex->requires_prelocking() && + tables->view->uses_stored_routines()) + { + /* We have at least one table in TL here. */ + if (!query_tables_last_own) + query_tables_last_own= thd->lex->query_tables_last; + if (sp_cache_routines_and_add_tables_for_view(thd, thd->lex, tables)) + { + /* + Serious error during reading stored routines from mysql.proc table. + Something is wrong with the table or its contents, and an error has + been emitted; we must abort. + */ + result= -1; + goto err; + } + } + } + + err: + thd_proc_info(thd, 0); + free_root(&new_frm_mem, MYF(0)); // Free pre-alloced block + + if (query_tables_last_own) + thd->lex->mark_as_requiring_prelocking(query_tables_last_own); + + if (result && tables) + { + /* + Some functions determine success as (tables->table != NULL). + tables->table is in thd->open_tables. It won't go lost. If the + error happens on a MERGE child, clear the parents TABLE reference. + */ + if (tables->parent_l) + { + if (tables->parent_l->next_global == tables->parent_l->table->child_l) + tables->parent_l->next_global= *tables->parent_l->table->child_last_l; + tables->parent_l->table= NULL; + } + tables->table= NULL; + } + DBUG_PRINT("tcache", ("returning: %d", result)); + DBUG_RETURN(result); +} + + +/* + Check that lock is ok for tables; Call start stmt if ok + + SYNOPSIS + check_lock_and_start_stmt() + thd Thread handle + table_list Table to check + lock_type Lock used for table + + RETURN VALUES + 0 ok + 1 error +*/ + +static bool check_lock_and_start_stmt(THD *thd, TABLE *table, + thr_lock_type lock_type) +{ + int error; + DBUG_ENTER("check_lock_and_start_stmt"); + + if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ && + (int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ) + { + my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias); + DBUG_RETURN(1); + } + if ((error=table->file->start_stmt(thd, lock_type))) + { + table->file->print_error(error,MYF(0)); + DBUG_RETURN(1); + } + DBUG_RETURN(0); +} + + +/** + @brief Open and lock one table + + @param[in] thd thread handle + @param[in] table_l table to open is first table in this list + @param[in] lock_type lock to use for table + + @return table + @retval != NULL OK, opened table returned + @retval NULL Error + + @note + If ok, the following are also set: + table_list->lock_type lock_type + table_list->table table + + @note + If table_l is a list, not a single table, the list is temporarily + broken. + + @detail + This function is meant as a replacement for open_ltable() when + MERGE tables can be opened. open_ltable() cannot open MERGE tables. + + There may be more differences between open_n_lock_single_table() and + open_ltable(). One known difference is that open_ltable() does + neither call decide_logging_format() nor handle some other logging + and locking issues because it does not call lock_tables(). +*/ + +TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l, + thr_lock_type lock_type) +{ + TABLE_LIST *save_next_global; + DBUG_ENTER("open_n_lock_single_table"); + + /* Remember old 'next' pointer. */ + save_next_global= table_l->next_global; + /* Break list. */ + table_l->next_global= NULL; + + /* Set requested lock type. */ + table_l->lock_type= lock_type; + /* Allow to open real tables only. */ + table_l->required_type= FRMTYPE_TABLE; + + /* Open the table. */ + if (simple_open_n_lock_tables(thd, table_l)) + table_l->table= NULL; /* Just to be sure. */ + + /* Restore list. */ + table_l->next_global= save_next_global; + + DBUG_RETURN(table_l->table); +} + + +/* + Open and lock one table + + SYNOPSIS + open_ltable() + thd Thread handler + table_list Table to open is first table in this list + lock_type Lock to use for open + lock_flags Flags passed to mysql_lock_table + + NOTE + This function doesn't do anything like SP/SF/views/triggers analysis done + in open_table()/lock_tables(). It is intended for opening of only one + concrete table. And used only in special contexts. + + RETURN VALUES + table Opened table + 0 Error + + If ok, the following are also set: + table_list->lock_type lock_type + table_list->table table +*/ + +TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type, + uint lock_flags) +{ + TABLE *table; + bool refresh; + DBUG_ENTER("open_ltable"); + + /* should not be used in a prelocked_mode context, see NOTE above */ + DBUG_ASSERT(!thd->prelocked_mode); + + thd_proc_info(thd, "Opening table"); + thd->current_tablenr= 0; + /* open_ltable can be used only for BASIC TABLEs */ + table_list->required_type= FRMTYPE_TABLE; + while (!(table= open_table(thd, table_list, thd->mem_root, &refresh, 0)) && + refresh) + ; + + if (table) + { + if (table->child_l) + { + /* A MERGE table must not come here. */ + /* purecov: begin tested */ + my_error(ER_WRONG_OBJECT, MYF(0), table->s->db.str, + table->s->table_name.str, "BASE TABLE"); + table= 0; + goto end; + /* purecov: end */ + } + + table_list->lock_type= lock_type; + table_list->table= table; + table->grant= table_list->grant; + if (thd->locked_tables) + { + if (check_lock_and_start_stmt(thd, table, lock_type)) + table= 0; + } + else + { + DBUG_ASSERT(thd->lock == 0); // You must lock everything at once + if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK) + if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1, + lock_flags, &refresh))) + table= 0; + } + } + + end: + thd_proc_info(thd, 0); + DBUG_RETURN(table); +} + + +/* + Open all tables in list, locks them and optionally process derived tables. + + SYNOPSIS + open_and_lock_tables_derived() + thd - thread handler + tables - list of tables for open&locking + derived - if to handle derived tables + + RETURN + FALSE - ok + TRUE - error + + NOTE + The lock will automaticaly be freed by close_thread_tables() + + NOTE + There are two convenience functions: + - simple_open_n_lock_tables(thd, tables) without derived handling + - open_and_lock_tables(thd, tables) with derived handling + Both inline functions call open_and_lock_tables_derived() with + the third argument set appropriately. +*/ + +int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived) +{ + uint counter; + bool need_reopen; + DBUG_ENTER("open_and_lock_tables_derived"); + DBUG_PRINT("enter", ("derived handling: %d", derived)); + + for ( ; ; ) + { + if (open_tables(thd, &tables, &counter, 0)) + DBUG_RETURN(-1); + + DBUG_EXECUTE_IF("sleep_open_and_lock_after_open", { + const char *old_proc_info= thd->proc_info; + thd->proc_info= "DBUG sleep"; + my_sleep(6000000); + thd->proc_info= old_proc_info;}); + + if (!lock_tables(thd, tables, counter, &need_reopen)) + break; + if (!need_reopen) + DBUG_RETURN(-1); + close_tables_for_reopen(thd, &tables); + } + if (derived && + (mysql_handle_derived(thd->lex, &mysql_derived_prepare) || + (thd->fill_derived_tables() && + mysql_handle_derived(thd->lex, &mysql_derived_filling)))) + DBUG_RETURN(TRUE); /* purecov: inspected */ + DBUG_RETURN(0); +} + + +/* + Open all tables in list and process derived tables + + SYNOPSIS + open_normal_and_derived_tables + thd - thread handler + tables - list of tables for open + flags - bitmap of flags to modify how the tables will be open: + MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has + done a flush or namelock on it. + + RETURN + FALSE - ok + TRUE - error + + NOTE + This is to be used on prepare stage when you don't read any + data from the tables. +*/ + +bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags) +{ + uint counter; + DBUG_ENTER("open_normal_and_derived_tables"); + DBUG_ASSERT(!thd->fill_derived_tables()); + if (open_tables(thd, &tables, &counter, flags) || + mysql_handle_derived(thd->lex, &mysql_derived_prepare)) + DBUG_RETURN(TRUE); /* purecov: inspected */ + DBUG_RETURN(0); +} + + +/* + Mark all real tables in the list as free for reuse. + + SYNOPSIS + mark_real_tables_as_free_for_reuse() + thd - thread context + table - head of the list of tables + + DESCRIPTION + Marks all real tables in the list (i.e. not views, derived + or schema tables) as free for reuse. +*/ + +static void mark_real_tables_as_free_for_reuse(TABLE_LIST *table) +{ + for (; table; table= table->next_global) + if (!table->placeholder()) + table->table->query_id= 0; +} + + +/** + Decide on logging format to use for the statement. + + Compute the capabilities vector for the involved storage engines + and mask out the flags for the binary log. Right now, the binlog + flags only include the capabilities of the storage engines, so this + is safe. + + We now have three alternatives that prevent the statement from + being loggable: + + 1. If there are no capabilities left (all flags are clear) it is + not possible to log the statement at all, so we roll back the + statement and report an error. + + 2. Statement mode is set, but the capabilities indicate that + statement format is not possible. + + 3. Row mode is set, but the capabilities indicate that row + format is not possible. + + 4. Statement is unsafe, but the capabilities indicate that row + format is not possible. + + If we are in MIXED mode, we then decide what logging format to use: + + 1. If the statement is unsafe, row-based logging is used. + + 2. If statement-based logging is not possible, row-based logging is + used. + + 3. Otherwise, statement-based logging is used. + + @param thd Client thread + @param tables Tables involved in the query + */ + +int decide_logging_format(THD *thd, TABLE_LIST *tables) +{ + if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG)) + { + /* + Compute the starting vectors for the computations by creating a + set with all the capabilities bits set and one with no + capabilities bits set. + */ + handler::Table_flags flags_some_set= 0; + handler::Table_flags flags_all_set= + HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE; + + my_bool multi_engine= FALSE; + void* prev_ht= NULL; + for (TABLE_LIST *table= tables; table; table= table->next_global) + { + if (table->placeholder()) + continue; + if (table->table->s->table_category == TABLE_CATEGORY_PERFORMANCE) + thd->lex->set_stmt_unsafe(); + if (table->lock_type >= TL_WRITE_ALLOW_WRITE) + { + ulonglong const flags= table->table->file->ha_table_flags(); + DBUG_PRINT("info", ("table: %s; ha_table_flags: %s%s", + table->table_name, + FLAGSTR(flags, HA_BINLOG_STMT_CAPABLE), + FLAGSTR(flags, HA_BINLOG_ROW_CAPABLE))); + if (prev_ht && prev_ht != table->table->file->ht) + multi_engine= TRUE; + prev_ht= table->table->file->ht; + flags_all_set &= flags; + flags_some_set |= flags; + } + } + + DBUG_PRINT("info", ("flags_all_set: %s%s", + FLAGSTR(flags_all_set, HA_BINLOG_STMT_CAPABLE), + FLAGSTR(flags_all_set, HA_BINLOG_ROW_CAPABLE))); + DBUG_PRINT("info", ("flags_some_set: %s%s", + FLAGSTR(flags_some_set, HA_BINLOG_STMT_CAPABLE), + FLAGSTR(flags_some_set, HA_BINLOG_ROW_CAPABLE))); + DBUG_PRINT("info", ("thd->variables.binlog_format: %ld", + thd->variables.binlog_format)); + DBUG_PRINT("info", ("multi_engine: %s", + multi_engine ? "TRUE" : "FALSE")); + + int error= 0; + if (flags_all_set == 0) + { + my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0), + "Statement cannot be logged to the binary log in" + " row-based nor statement-based format"); + } + else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT && + (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0) + { + my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0), + "Statement-based format required for this statement," + " but not allowed by this combination of engines"); + } + else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW || + thd->lex->is_stmt_unsafe()) && + (flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0) + { + my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0), + "Row-based format required for this statement," + " but not allowed by this combination of engines"); + } + + /* + If more than one engine is involved in the statement and at + least one is doing it's own logging (is *self-logging*), the + statement cannot be logged atomically, so we generate an error + rather than allowing the binlog to become corrupt. + */ + if (multi_engine && + (flags_some_set & HA_HAS_OWN_BINLOGGING)) + { + error= ER_BINLOG_LOGGING_IMPOSSIBLE; + my_error(error, MYF(0), + "Statement cannot be written atomically since more" + " than one engine involved and at least one engine" + " is self-logging"); + } + + DBUG_PRINT("info", ("error: %d", error)); + + if (error) + return -1; + + /* + We switch to row-based format if we are in mixed mode and one of + the following are true: + + 1. If the statement is unsafe + 2. If statement format cannot be used + + Observe that point to cannot be decided before the tables + involved in a statement has been checked, i.e., we cannot put + this code in reset_current_stmt_binlog_row_based(), it has to be + here. + */ + if (thd->lex->is_stmt_unsafe() || + (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0) + { + thd->set_current_stmt_binlog_row_based_if_mixed(); + } + } + + return 0; +} + +/* + Lock all tables in list + + SYNOPSIS + lock_tables() + thd Thread handler + tables Tables to lock + count Number of opened tables + need_reopen Out parameter which if TRUE indicates that some + tables were dropped or altered during this call + and therefore invoker should reopen tables and + try to lock them once again (in this case + lock_tables() will also return error). + + NOTES + You can't call lock_tables twice, as this would break the dead-lock-free + handling thr_lock gives us. You most always get all needed locks at + once. + + If query for which we are calling this function marked as requring + prelocking, this function will do implicit LOCK TABLES and change + thd::prelocked_mode accordingly. + + RETURN VALUES + 0 ok + -1 Error +*/ + +int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen) +{ + TABLE_LIST *table; + + DBUG_ENTER("lock_tables"); + /* + We can't meet statement requiring prelocking if we already + in prelocked mode. + */ + DBUG_ASSERT(!thd->prelocked_mode || !thd->lex->requires_prelocking()); + *need_reopen= FALSE; + + if (!tables && !thd->lex->requires_prelocking()) + DBUG_RETURN(decide_logging_format(thd, tables)); + + /* + We need this extra check for thd->prelocked_mode because we want to avoid + attempts to lock tables in substatements. Checking for thd->locked_tables + is not enough in some situations. For example for SP containing + "drop table t3; create temporary t3 ..; insert into t3 ...;" + thd->locked_tables may be 0 after drop tables, and without this extra + check insert will try to lock temporary table t3, that will lead + to memory leak... + */ + if (!thd->locked_tables && !thd->prelocked_mode) + { + DBUG_ASSERT(thd->lock == 0); // You must lock everything at once + TABLE **start,**ptr; + uint lock_flag= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN; + + if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count))) + DBUG_RETURN(-1); + for (table= tables; table; table= table->next_global) + { + if (!table->placeholder()) + *(ptr++)= table->table; + } + + /* We have to emulate LOCK TABLES if we are statement needs prelocking. */ + if (thd->lex->requires_prelocking()) + { + thd->in_lock_tables=1; + thd->options|= OPTION_TABLE_LOCK; + /* + If we have >= 2 different tables to update with auto_inc columns, + statement-based binlogging won't work. We can solve this problem in + mixed mode by switching to row-based binlogging: + */ + if (thd->variables.binlog_format == BINLOG_FORMAT_MIXED && + has_two_write_locked_tables_with_auto_increment(tables)) + { + thd->lex->set_stmt_unsafe(); + thd->set_current_stmt_binlog_row_based_if_mixed(); + } + } + + if (! (thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start), + lock_flag, need_reopen))) + { + if (thd->lex->requires_prelocking()) + { + thd->options&= ~(OPTION_TABLE_LOCK); + thd->in_lock_tables=0; + } + DBUG_RETURN(-1); + } + + if (thd->lex->requires_prelocking() && + thd->lex->sql_command != SQLCOM_LOCK_TABLES) + { + TABLE_LIST *first_not_own= thd->lex->first_not_own_table(); + /* + We just have done implicit LOCK TABLES, and now we have + to emulate first open_and_lock_tables() after it. + + Note that "LOCK TABLES" can also be marked as requiring prelocking + (e.g. if one locks view which uses functions). We should not emulate + such open_and_lock_tables() in this case. We also should not set + THD::prelocked_mode or first close_thread_tables() call will do + "UNLOCK TABLES". + */ + thd->locked_tables= thd->lock; + thd->lock= 0; + thd->in_lock_tables=0; + + /* + When open_and_lock_tables() is called for a single table out of + a table list, the 'next_global' chain is temporarily broken. We + may not find 'first_not_own' before the end of the "list". + Look for example at those places where open_n_lock_single_table() + is called. That function implements the temporary breaking of + a table list for opening a single table. + */ + for (table= tables; + table && table != first_not_own; + table= table->next_global) + { + if (!table->placeholder()) + { + table->table->query_id= thd->query_id; + if (check_lock_and_start_stmt(thd, table->table, table->lock_type)) + { + mysql_unlock_tables(thd, thd->locked_tables); + thd->locked_tables= 0; + thd->options&= ~(OPTION_TABLE_LOCK); + DBUG_RETURN(-1); + } + } + } + /* + Let us mark all tables which don't belong to the statement itself, + and was marked as occupied during open_tables() as free for reuse. + */ + mark_real_tables_as_free_for_reuse(first_not_own); + DBUG_PRINT("info",("prelocked_mode= PRELOCKED")); + thd->prelocked_mode= PRELOCKED; + } + } + else + { + TABLE_LIST *first_not_own= thd->lex->first_not_own_table(); + /* + When open_and_lock_tables() is called for a single table out of + a table list, the 'next_global' chain is temporarily broken. We + may not find 'first_not_own' before the end of the "list". + Look for example at those places where open_n_lock_single_table() + is called. That function implements the temporary breaking of + a table list for opening a single table. + */ + for (table= tables; + table && table != first_not_own; + table= table->next_global) + { + if (table->placeholder()) + continue; + + /* + In a stored function or trigger we should ensure that we won't change + a table that is already used by the calling statement. + */ + if (thd->prelocked_mode && + table->lock_type >= TL_WRITE_ALLOW_WRITE) + { + for (TABLE* opentab= thd->open_tables; opentab; opentab= opentab->next) + { + if (table->table->s == opentab->s && opentab->query_id && + table->table->query_id != opentab->query_id) + { + my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0), + table->table->s->table_name.str); + DBUG_RETURN(-1); + } + } + } + + if (check_lock_and_start_stmt(thd, table->table, table->lock_type)) + { + DBUG_RETURN(-1); + } + } + /* + If we are under explicit LOCK TABLES and our statement requires + prelocking, we should mark all "additional" tables as free for use + and enter prelocked mode. + */ + if (thd->lex->requires_prelocking()) + { + mark_real_tables_as_free_for_reuse(first_not_own); + DBUG_PRINT("info", ("thd->prelocked_mode= PRELOCKED_UNDER_LOCK_TABLES")); + thd->prelocked_mode= PRELOCKED_UNDER_LOCK_TABLES; + } + } + + DBUG_RETURN(decide_logging_format(thd, tables)); +} + + +/* + Prepare statement for reopening of tables and recalculation of set of + prelocked tables. + + SYNOPSIS + close_tables_for_reopen() + thd in Thread context + tables in/out List of tables which we were trying to open and lock + +*/ + +void close_tables_for_reopen(THD *thd, TABLE_LIST **tables) +{ + /* + If table list consists only from tables from prelocking set, table list + for new attempt should be empty, so we have to update list's root pointer. + */ + if (thd->lex->first_not_own_table() == *tables) + *tables= 0; + thd->lex->chop_off_not_own_tables(); + sp_remove_not_own_routines(thd->lex); + for (TABLE_LIST *tmp= *tables; tmp; tmp= tmp->next_global) + tmp->table= 0; + close_thread_tables(thd); +} + + +/* + Open a single table without table caching and don't set it in open_list + + SYNPOSIS + open_temporary_table() + thd Thread object + path Path (without .frm) + db database + table_name Table name + link_in_list 1 if table should be linked into thd->temporary_tables + + NOTES: + Used by alter_table to open a temporary table and when creating + a temporary table with CREATE TEMPORARY ... + + RETURN + 0 Error + # TABLE object +*/ + +TABLE *open_temporary_table(THD *thd, const char *path, const char *db, + const char *table_name, bool link_in_list) +{ + TABLE *tmp_table; + TABLE_SHARE *share; + char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path; + uint key_length; + TABLE_LIST table_list; + DBUG_ENTER("open_temporary_table"); + DBUG_PRINT("enter", + ("table: '%s'.'%s' path: '%s' server_id: %u " + "pseudo_thread_id: %lu", + db, table_name, path, + (uint) thd->server_id, (ulong) thd->variables.pseudo_thread_id)); + + table_list.db= (char*) db; + table_list.table_name= (char*) table_name; + /* Create the cache_key for temporary tables */ + key_length= create_table_def_key(thd, cache_key, &table_list, 1); + + if (!(tmp_table= (TABLE*) my_malloc(sizeof(*tmp_table) + sizeof(*share) + + strlen(path)+1 + key_length, + MYF(MY_WME)))) + DBUG_RETURN(0); /* purecov: inspected */ + + share= (TABLE_SHARE*) (tmp_table+1); + tmp_path= (char*) (share+1); + saved_cache_key= strmov(tmp_path, path)+1; + memcpy(saved_cache_key, cache_key, key_length); + + init_tmp_table_share(thd, share, saved_cache_key, key_length, + strend(saved_cache_key)+1, tmp_path); + + if (open_table_def(thd, share, 0) || + open_table_from_share(thd, share, table_name, + (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE | + HA_GET_INDEX), + READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD, + ha_open_options, + tmp_table, FALSE)) + { + /* No need to lock share->mutex as this is not needed for tmp tables */ + free_table_share(share); + my_free((char*) tmp_table,MYF(0)); + DBUG_RETURN(0); + } + + tmp_table->reginfo.lock_type= TL_WRITE; // Simulate locked + share->tmp_table= (tmp_table->file->has_transactions() ? + TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE); + + if (link_in_list) + { + /* growing temp list at the head */ + tmp_table->next= thd->temporary_tables; + if (tmp_table->next) + tmp_table->next->prev= tmp_table; + thd->temporary_tables= tmp_table; + thd->temporary_tables->prev= 0; + if (thd->slave_thread) + slave_open_temp_tables++; + } + tmp_table->pos_in_table_list= 0; + DBUG_PRINT("tmptable", ("opened table: '%s'.'%s' 0x%lx", tmp_table->s->db.str, + tmp_table->s->table_name.str, (long) tmp_table)); + DBUG_RETURN(tmp_table); +} + + +bool rm_temporary_table(handlerton *base, char *path) +{ + bool error=0; + handler *file; + char *ext; + DBUG_ENTER("rm_temporary_table"); + + strmov(ext= strend(path), reg_ext); + if (my_delete(path,MYF(0))) + error=1; /* purecov: inspected */ + *ext= 0; // remove extension + file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base); + if (file && file->ha_delete_table(path)) + { + error=1; + sql_print_warning("Could not remove temporary table: '%s', error: %d", + path, my_errno); + } + delete file; + DBUG_RETURN(error); +} + + +/***************************************************************************** +* The following find_field_in_XXX procedures implement the core of the +* name resolution functionality. The entry point to resolve a column name in a +* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref' +* for each table reference. In turn, depending on the type of table reference, +* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures +* below specific for the type of table reference. +******************************************************************************/ + +/* Special Field pointers as return values of find_field_in_XXX functions. */ +Field *not_found_field= (Field*) 0x1; +Field *view_ref_found= (Field*) 0x2; + +#define WRONG_GRANT (Field*) -1 + +static void update_field_dependencies(THD *thd, Field *field, TABLE *table) +{ + DBUG_ENTER("update_field_dependencies"); + if (thd->mark_used_columns != MARK_COLUMNS_NONE) + { + MY_BITMAP *current_bitmap, *other_bitmap; + + /* + We always want to register the used keys, as the column bitmap may have + been set for all fields (for example for view). + */ + + table->covering_keys.intersect(field->part_of_key); + table->merge_keys.merge(field->part_of_key); + + if (thd->mark_used_columns == MARK_COLUMNS_READ) + { + current_bitmap= table->read_set; + other_bitmap= table->write_set; + } + else + { + current_bitmap= table->write_set; + other_bitmap= table->read_set; + } + + /* + The test-and-set mechanism in the bitmap is not reliable during + multi-UPDATE statements under MARK_COLUMNS_READ mode + (thd->mark_used_columns == MARK_COLUMNS_READ), as this bitmap contains + only those columns that are used in the SET clause. I.e they are being + set here. See multi_update::prepare() + */ + if (bitmap_fast_test_and_set(current_bitmap, field->field_index)) + { + if (thd->mark_used_columns == MARK_COLUMNS_WRITE) + { + DBUG_PRINT("warning", ("Found duplicated field")); + thd->dup_field= field; + } + else + { + DBUG_PRINT("note", ("Field found before")); + } + DBUG_VOID_RETURN; + } + if (table->get_fields_in_item_tree) + field->flags|= GET_FIXED_FIELDS_FLAG; + table->used_fields++; + } + else if (table->get_fields_in_item_tree) + field->flags|= GET_FIXED_FIELDS_FLAG; + DBUG_VOID_RETURN; +} + + +/* + Find a field by name in a view that uses merge algorithm. + + SYNOPSIS + find_field_in_view() + thd thread handler + table_list view to search for 'name' + name name of field + length length of name + item_name name of item if it will be created (VIEW) + ref expression substituted in VIEW should be passed + using this reference (return view_ref_found) + register_tree_change TRUE if ref is not stack variable and we + need register changes in item tree + + RETURN + 0 field is not found + view_ref_found found value in VIEW (real result is in *ref) + # pointer to field - only for schema table fields +*/ + +static Field * +find_field_in_view(THD *thd, TABLE_LIST *table_list, + const char *name, uint length, + const char *item_name, Item **ref, + bool register_tree_change) +{ + DBUG_ENTER("find_field_in_view"); + DBUG_PRINT("enter", + ("view: '%s', field name: '%s', item name: '%s', ref 0x%lx", + table_list->alias, name, item_name, (ulong) ref)); + Field_iterator_view field_it; + field_it.set(table_list); + Query_arena *arena= 0, backup; + + DBUG_ASSERT(table_list->schema_table_reformed || + (ref != 0 && table_list->view != 0)); + for (; !field_it.end_of_fields(); field_it.next()) + { + if (!my_strcasecmp(system_charset_info, field_it.name(), name)) + { + // in PS use own arena or data will be freed after prepare + if (register_tree_change && thd->stmt_arena->is_stmt_prepare_or_first_sp_execute()) + arena= thd->activate_stmt_arena_if_needed(&backup); + /* + create_item() may, or may not create a new Item, depending on + the column reference. See create_view_field() for details. + */ + Item *item= field_it.create_item(thd); + if (arena) + thd->restore_active_arena(arena, &backup); + + if (!item) + DBUG_RETURN(0); + /* + *ref != NULL means that *ref contains the item that we need to + replace. If the item was aliased by the user, set the alias to + the replacing item. + We need to set alias on both ref itself and on ref real item. + */ + if (*ref && !(*ref)->is_autogenerated_name) + { + item->set_name((*ref)->name, (*ref)->name_length, + system_charset_info); + item->real_item()->set_name((*ref)->name, (*ref)->name_length, + system_charset_info); + } + if (register_tree_change) + thd->change_item_tree(ref, item); + else + *ref= item; + DBUG_RETURN((Field*) view_ref_found); + } + } + DBUG_RETURN(0); +} + + +/* + Find field by name in a NATURAL/USING join table reference. + + SYNOPSIS + find_field_in_natural_join() + thd [in] thread handler + table_ref [in] table reference to search + name [in] name of field + length [in] length of name + ref [in/out] if 'name' is resolved to a view field, ref is + set to point to the found view field + register_tree_change [in] TRUE if ref is not stack variable and we + need register changes in item tree + actual_table [out] the original table reference where the field + belongs - differs from 'table_list' only for + NATURAL/USING joins + + DESCRIPTION + Search for a field among the result fields of a NATURAL/USING join. + Notice that this procedure is called only for non-qualified field + names. In the case of qualified fields, we search directly the base + tables of a natural join. + + RETURN + NULL if the field was not found + WRONG_GRANT if no access rights to the found field + # Pointer to the found Field +*/ + +static Field * +find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name, + uint length, Item **ref, bool register_tree_change, + TABLE_LIST **actual_table) +{ + List_iterator_fast + field_it(*(table_ref->join_columns)); + Natural_join_column *nj_col, *curr_nj_col; + Field *found_field; + Query_arena *arena, backup; + DBUG_ENTER("find_field_in_natural_join"); + DBUG_PRINT("enter", ("field name: '%s', ref 0x%lx", + name, (ulong) ref)); + DBUG_ASSERT(table_ref->is_natural_join && table_ref->join_columns); + DBUG_ASSERT(*actual_table == NULL); + + LINT_INIT(arena); + LINT_INIT(found_field); + + for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col; + curr_nj_col= field_it++) + { + if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name)) + { + if (nj_col) + { + my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where); + DBUG_RETURN(NULL); + } + nj_col= curr_nj_col; + } + } + if (!nj_col) + DBUG_RETURN(NULL); + + if (nj_col->view_field) + { + Item *item; + LINT_INIT(arena); + if (register_tree_change) + arena= thd->activate_stmt_arena_if_needed(&backup); + /* + create_item() may, or may not create a new Item, depending on the + column reference. See create_view_field() for details. + */ + item= nj_col->create_item(thd); + /* + *ref != NULL means that *ref contains the item that we need to + replace. If the item was aliased by the user, set the alias to + the replacing item. + We need to set alias on both ref itself and on ref real item. + */ + if (*ref && !(*ref)->is_autogenerated_name) + { + item->set_name((*ref)->name, (*ref)->name_length, + system_charset_info); + item->real_item()->set_name((*ref)->name, (*ref)->name_length, + system_charset_info); + } + if (register_tree_change && arena) + thd->restore_active_arena(arena, &backup); + + if (!item) + DBUG_RETURN(NULL); + DBUG_ASSERT(nj_col->table_field == NULL); + if (nj_col->table_ref->schema_table_reformed) + { + /* + Translation table items are always Item_fields and fixed + already('mysql_schema_table' function). So we can return + ->field. It is used only for 'show & where' commands. + */ + DBUG_RETURN(((Item_field*) (nj_col->view_field->item))->field); + } + if (register_tree_change) + thd->change_item_tree(ref, item); + else + *ref= item; + found_field= (Field*) view_ref_found; + } + else + { + /* This is a base table. */ + DBUG_ASSERT(nj_col->view_field == NULL); + /* + This fix_fields is not necessary (initially this item is fixed by + the Item_field constructor; after reopen_tables the Item_func_eq + calls fix_fields on that item), it's just a check during table + reopening for columns that was dropped by the concurrent connection. + */ + if (!nj_col->table_field->fixed && + nj_col->table_field->fix_fields(thd, (Item **)&nj_col->table_field)) + { + DBUG_PRINT("info", ("column '%s' was dropped by the concurrent connection", + nj_col->table_field->name)); + DBUG_RETURN(NULL); + } + DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->field->table); + found_field= nj_col->table_field->field; + update_field_dependencies(thd, found_field, nj_col->table_ref->table); + } + + *actual_table= nj_col->table_ref; + + DBUG_RETURN(found_field); +} + + +/* + Find field by name in a base table or a view with temp table algorithm. + + SYNOPSIS + find_field_in_table() + thd thread handler + table table where to search for the field + name name of field + length length of name + allow_rowid do allow finding of "_rowid" field? + cached_field_index_ptr cached position in field list (used to speedup + lookup for fields in prepared tables) + + RETURN + 0 field is not found + # pointer to field +*/ + +Field * +find_field_in_table(THD *thd, TABLE *table, const char *name, uint length, + bool allow_rowid, uint *cached_field_index_ptr) +{ + Field **field_ptr, *field; + uint cached_field_index= *cached_field_index_ptr; + DBUG_ENTER("find_field_in_table"); + DBUG_PRINT("enter", ("table: '%s', field name: '%s'", table->alias, name)); + + /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */ + if (cached_field_index < table->s->fields && + !my_strcasecmp(system_charset_info, + table->field[cached_field_index]->field_name, name)) + field_ptr= table->field + cached_field_index; + else if (table->s->name_hash.records) + { + field_ptr= (Field**) hash_search(&table->s->name_hash, (uchar*) name, + length); + if (field_ptr) + { + /* + field_ptr points to field in TABLE_SHARE. Convert it to the matching + field in table + */ + field_ptr= (table->field + (field_ptr - table->s->field)); + } + } + else + { + if (!(field_ptr= table->field)) + DBUG_RETURN((Field *)0); + for (; *field_ptr; ++field_ptr) + if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name)) + break; + } + + if (field_ptr && *field_ptr) + { + *cached_field_index_ptr= field_ptr - table->field; + field= *field_ptr; + } + else + { + if (!allow_rowid || + my_strcasecmp(system_charset_info, name, "_rowid") || + table->s->rowid_field_offset == 0) + DBUG_RETURN((Field*) 0); + field= table->field[table->s->rowid_field_offset-1]; + } + + update_field_dependencies(thd, field, table); + + DBUG_RETURN(field); +} + + +/* + Find field in a table reference. + + SYNOPSIS + find_field_in_table_ref() + thd [in] thread handler + table_list [in] table reference to search + name [in] name of field + length [in] field length of name + item_name [in] name of item if it will be created (VIEW) + db_name [in] optional database name that qualifies the + table_name [in] optional table name that qualifies the field + ref [in/out] if 'name' is resolved to a view field, ref + is set to point to the found view field + check_privileges [in] check privileges + allow_rowid [in] do allow finding of "_rowid" field? + cached_field_index_ptr [in] cached position in field list (used to + speedup lookup for fields in prepared tables) + register_tree_change [in] TRUE if ref is not stack variable and we + need register changes in item tree + actual_table [out] the original table reference where the field + belongs - differs from 'table_list' only for + NATURAL_USING joins. + + DESCRIPTION + Find a field in a table reference depending on the type of table + reference. There are three types of table references with respect + to the representation of their result columns: + - an array of Field_translator objects for MERGE views and some + information_schema tables, + - an array of Field objects (and possibly a name hash) for stored + tables, + - a list of Natural_join_column objects for NATURAL/USING joins. + This procedure detects the type of the table reference 'table_list' + and calls the corresponding search routine. + + RETURN + 0 field is not found + view_ref_found found value in VIEW (real result is in *ref) + # pointer to field +*/ + +Field * +find_field_in_table_ref(THD *thd, TABLE_LIST *table_list, + const char *name, uint length, + const char *item_name, const char *db_name, + const char *table_name, Item **ref, + bool check_privileges, bool allow_rowid, + uint *cached_field_index_ptr, + bool register_tree_change, TABLE_LIST **actual_table) +{ + Field *fld; + DBUG_ENTER("find_field_in_table_ref"); + DBUG_ASSERT(table_list->alias); + DBUG_ASSERT(name); + DBUG_ASSERT(item_name); + DBUG_PRINT("enter", + ("table: '%s' field name: '%s' item name: '%s' ref 0x%lx", + table_list->alias, name, item_name, (ulong) ref)); + + /* + Check that the table and database that qualify the current field name + are the same as the table reference we are going to search for the field. + + Exclude from the test below nested joins because the columns in a + nested join generally originate from different tables. Nested joins + also have no table name, except when a nested join is a merge view + or an information schema table. + + We include explicitly table references with a 'field_translation' table, + because if there are views over natural joins we don't want to search + inside the view, but we want to search directly in the view columns + which are represented as a 'field_translation'. + + TODO: Ensure that table_name, db_name and tables->db always points to + something ! + */ + if (/* Exclude nested joins. */ + (!table_list->nested_join || + /* Include merge views and information schema tables. */ + table_list->field_translation) && + /* + Test if the field qualifiers match the table reference we plan + to search. + */ + table_name && table_name[0] && + (my_strcasecmp(table_alias_charset, table_list->alias, table_name) || + (db_name && db_name[0] && table_list->db && table_list->db[0] && + strcmp(db_name, table_list->db)))) + DBUG_RETURN(0); + + *actual_table= NULL; + + if (table_list->field_translation) + { + /* 'table_list' is a view or an information schema table. */ + if ((fld= find_field_in_view(thd, table_list, name, length, item_name, ref, + register_tree_change))) + *actual_table= table_list; + } + else if (!table_list->nested_join) + { + /* 'table_list' is a stored table. */ + DBUG_ASSERT(table_list->table); + if ((fld= find_field_in_table(thd, table_list->table, name, length, + allow_rowid, + cached_field_index_ptr))) + *actual_table= table_list; + } + else + { + /* + 'table_list' is a NATURAL/USING join, or an operand of such join that + is a nested join itself. + + If the field name we search for is qualified, then search for the field + in the table references used by NATURAL/USING the join. + */ + if (table_name && table_name[0]) + { + List_iterator it(table_list->nested_join->join_list); + TABLE_LIST *table; + while ((table= it++)) + { + if ((fld= find_field_in_table_ref(thd, table, name, length, item_name, + db_name, table_name, ref, + check_privileges, allow_rowid, + cached_field_index_ptr, + register_tree_change, actual_table))) + DBUG_RETURN(fld); + } + DBUG_RETURN(0); + } + /* + Non-qualified field, search directly in the result columns of the + natural join. The condition of the outer IF is true for the top-most + natural join, thus if the field is not qualified, we will search + directly the top-most NATURAL/USING join. + */ + fld= find_field_in_natural_join(thd, table_list, name, length, ref, + register_tree_change, actual_table); + } + + if (fld) + { +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* Check if there are sufficient access rights to the found field. */ + if (check_privileges && + check_column_grant_in_table_ref(thd, *actual_table, name, length)) + fld= WRONG_GRANT; + else +#endif + if (thd->mark_used_columns != MARK_COLUMNS_NONE) + { + /* + Get rw_set correct for this field so that the handler + knows that this field is involved in the query and gets + retrieved/updated + */ + Field *field_to_set= NULL; + if (fld == view_ref_found) + { + Item *it= (*ref)->real_item(); + if (it->type() == Item::FIELD_ITEM) + field_to_set= ((Item_field*)it)->field; + else + { + if (thd->mark_used_columns == MARK_COLUMNS_READ) + it->walk(&Item::register_field_in_read_map, 1, (uchar *) 0); + } + } + else + field_to_set= fld; + if (field_to_set) + { + TABLE *table= field_to_set->table; + if (thd->mark_used_columns == MARK_COLUMNS_READ) + bitmap_set_bit(table->read_set, field_to_set->field_index); + else + bitmap_set_bit(table->write_set, field_to_set->field_index); + } + } + } + DBUG_RETURN(fld); +} + + +/* + Find field in table, no side effects, only purpose is to check for field + in table object and get reference to the field if found. + + SYNOPSIS + find_field_in_table_sef() + + table table where to find + name Name of field searched for + + RETURN + 0 field is not found + # pointer to field +*/ + +Field *find_field_in_table_sef(TABLE *table, const char *name) +{ + Field **field_ptr; + if (table->s->name_hash.records) + { + field_ptr= (Field**)hash_search(&table->s->name_hash,(uchar*) name, + strlen(name)); + if (field_ptr) + { + /* + field_ptr points to field in TABLE_SHARE. Convert it to the matching + field in table + */ + field_ptr= (table->field + (field_ptr - table->s->field)); + } + } + else + { + if (!(field_ptr= table->field)) + return (Field *)0; + for (; *field_ptr; ++field_ptr) + if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name)) + break; + } + if (field_ptr) + return *field_ptr; + else + return (Field *)0; +} + + +/* + Find field in table list. + + SYNOPSIS + find_field_in_tables() + thd pointer to current thread structure + item field item that should be found + first_table list of tables to be searched for item + last_table end of the list of tables to search for item. If NULL + then search to the end of the list 'first_table'. + ref if 'item' is resolved to a view field, ref is set to + point to the found view field + report_error Degree of error reporting: + - IGNORE_ERRORS then do not report any error + - IGNORE_EXCEPT_NON_UNIQUE report only non-unique + fields, suppress all other errors + - REPORT_EXCEPT_NON_UNIQUE report all other errors + except when non-unique fields were found + - REPORT_ALL_ERRORS + check_privileges need to check privileges + register_tree_change TRUE if ref is not a stack variable and we + to need register changes in item tree + + RETURN VALUES + 0 If error: the found field is not unique, or there are + no sufficient access priviliges for the found field, + or the field is qualified with non-existing table. + not_found_field The function was called with report_error == + (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a + field was not found. + view_ref_found View field is found, item passed through ref parameter + found field If a item was resolved to some field +*/ + +Field * +find_field_in_tables(THD *thd, Item_ident *item, + TABLE_LIST *first_table, TABLE_LIST *last_table, + Item **ref, find_item_error_report_type report_error, + bool check_privileges, bool register_tree_change) +{ + Field *found=0; + const char *db= item->db_name; + const char *table_name= item->table_name; + const char *name= item->field_name; + uint length=(uint) strlen(name); + char name_buff[NAME_LEN+1]; + TABLE_LIST *cur_table= first_table; + TABLE_LIST *actual_table; + bool allow_rowid; + + if (!table_name || !table_name[0]) + { + table_name= 0; // For easier test + db= 0; + } + + allow_rowid= table_name || (cur_table && !cur_table->next_local); + + if (item->cached_table) + { + /* + This shortcut is used by prepared statements. We assume that + TABLE_LIST *first_table is not changed during query execution (which + is true for all queries except RENAME but luckily RENAME doesn't + use fields...) so we can rely on reusing pointer to its member. + With this optimization we also miss case when addition of one more + field makes some prepared query ambiguous and so erroneous, but we + accept this trade off. + */ + TABLE_LIST *table_ref= item->cached_table; + /* + The condition (table_ref->view == NULL) ensures that we will call + find_field_in_table even in the case of information schema tables + when table_ref->field_translation != NULL. + */ + if (table_ref->table && !table_ref->view) + found= find_field_in_table(thd, table_ref->table, name, length, + TRUE, &(item->cached_field_index)); + else + found= find_field_in_table_ref(thd, table_ref, name, length, item->name, + NULL, NULL, ref, check_privileges, + TRUE, &(item->cached_field_index), + register_tree_change, + &actual_table); + if (found) + { + if (found == WRONG_GRANT) + return (Field*) 0; + + /* + Only views fields should be marked as dependent, not an underlying + fields. + */ + if (!table_ref->belong_to_view) + { + SELECT_LEX *current_sel= thd->lex->current_select; + SELECT_LEX *last_select= table_ref->select_lex; + /* + If the field was an outer referencee, mark all selects using this + sub query as dependent on the outer query + */ + if (current_sel != last_select) + mark_select_range_as_dependent(thd, last_select, current_sel, + found, *ref, item); + } + return found; + } + } + + if (db && lower_case_table_names) + { + /* + convert database to lower case for comparison. + We can't do this in Item_field as this would change the + 'name' of the item which may be used in the select list + */ + strmake(name_buff, db, sizeof(name_buff)-1); + my_casedn_str(files_charset_info, name_buff); + db= name_buff; + } + + if (last_table) + last_table= last_table->next_name_resolution_table; + + for (; cur_table != last_table ; + cur_table= cur_table->next_name_resolution_table) + { + Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length, + item->name, db, table_name, ref, + (thd->lex->sql_command == + SQLCOM_SHOW_FIELDS) + ? false : check_privileges, + allow_rowid, + &(item->cached_field_index), + register_tree_change, + &actual_table); + if (cur_field) + { + if (cur_field == WRONG_GRANT) + { + if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS) + return (Field*) 0; + + thd->clear_error(); + cur_field= find_field_in_table_ref(thd, cur_table, name, length, + item->name, db, table_name, ref, + false, + allow_rowid, + &(item->cached_field_index), + register_tree_change, + &actual_table); + if (cur_field) + { + Field *nf=new Field_null(NULL,0,Field::NONE, + cur_field->field_name, + &my_charset_bin); + nf->init(cur_table->table); + cur_field= nf; + } + } + + /* + Store the original table of the field, which may be different from + cur_table in the case of NATURAL/USING join. + */ + item->cached_table= (!actual_table->cacheable_table || found) ? + 0 : actual_table; + + DBUG_ASSERT(thd->where); + /* + If we found a fully qualified field we return it directly as it can't + have duplicates. + */ + if (db) + return cur_field; + + if (found) + { + if (report_error == REPORT_ALL_ERRORS || + report_error == IGNORE_EXCEPT_NON_UNIQUE) + my_error(ER_NON_UNIQ_ERROR, MYF(0), + table_name ? item->full_name() : name, thd->where); + return (Field*) 0; + } + found= cur_field; + } + } + + if (found) + return found; + + /* + If the field was qualified and there were no tables to search, issue + an error that an unknown table was given. The situation is detected + as follows: if there were no tables we wouldn't go through the loop + and cur_table wouldn't be updated by the loop increment part, so it + will be equal to the first table. + */ + if (table_name && (cur_table == first_table) && + (report_error == REPORT_ALL_ERRORS || + report_error == REPORT_EXCEPT_NON_UNIQUE)) + { + char buff[NAME_LEN*2 + 2]; + if (db && db[0]) + { + strxnmov(buff,sizeof(buff)-1,db,".",table_name,NullS); + table_name=buff; + } + my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where); + } + else + { + if (report_error == REPORT_ALL_ERRORS || + report_error == REPORT_EXCEPT_NON_UNIQUE) + my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where); + else + found= not_found_field; + } + return found; +} + + +/* + Find Item in list of items (find_field_in_tables analog) + + TODO + is it better return only counter? + + SYNOPSIS + find_item_in_list() + find Item to find + items List of items + counter To return number of found item + report_error + REPORT_ALL_ERRORS report errors, return 0 if error + REPORT_EXCEPT_NOT_FOUND Do not report 'not found' error and + return not_found_item, report other errors, + return 0 + IGNORE_ERRORS Do not report errors, return 0 if error + resolution Set to the resolution type if the item is found + (it says whether the item is resolved + against an alias name, + or as a field name without alias, + or as a field hidden by alias, + or ignoring alias) + + RETURN VALUES + 0 Item is not found or item is not unique, + error message is reported + not_found_item Function was called with + report_error == REPORT_EXCEPT_NOT_FOUND and + item was not found. No error message was reported + found field +*/ + +/* Special Item pointer to serve as a return value from find_item_in_list(). */ +Item **not_found_item= (Item**) 0x1; + + +Item ** +find_item_in_list(Item *find, List &items, uint *counter, + find_item_error_report_type report_error, + enum_resolution_type *resolution) +{ + List_iterator li(items); + Item **found=0, **found_unaliased= 0, *item; + const char *db_name=0; + const char *field_name=0; + const char *table_name=0; + bool found_unaliased_non_uniq= 0; + /* + true if the item that we search for is a valid name reference + (and not an item that happens to have a name). + */ + bool is_ref_by_name= 0; + uint unaliased_counter= 0; + + *resolution= NOT_RESOLVED; + + is_ref_by_name= (find->type() == Item::FIELD_ITEM || + find->type() == Item::REF_ITEM); + if (is_ref_by_name) + { + field_name= ((Item_ident*) find)->field_name; + table_name= ((Item_ident*) find)->table_name; + db_name= ((Item_ident*) find)->db_name; + } + + for (uint i= 0; (item=li++); i++) + { + if (field_name && item->real_item()->type() == Item::FIELD_ITEM) + { + Item_ident *item_field= (Item_ident*) item; + + /* + In case of group_concat() with ORDER BY condition in the QUERY + item_field can be field of temporary table without item name + (if this field created from expression argument of group_concat()), + => we have to check presence of name before compare + */ + if (!item_field->name) + continue; + + if (table_name) + { + /* + If table name is specified we should find field 'field_name' in + table 'table_name'. According to SQL-standard we should ignore + aliases in this case. + + Since we should NOT prefer fields from the select list over + other fields from the tables participating in this select in + case of ambiguity we have to do extra check outside this function. + + We use strcmp for table names and database names as these may be + case sensitive. In cases where they are not case sensitive, they + are always in lower case. + + item_field->field_name and item_field->table_name can be 0x0 if + item is not fix_field()'ed yet. + */ + if (item_field->field_name && item_field->table_name && + !my_strcasecmp(system_charset_info, item_field->field_name, + field_name) && + !my_strcasecmp(table_alias_charset, item_field->table_name, + table_name) && + (!db_name || (item_field->db_name && + !strcmp(item_field->db_name, db_name)))) + { + if (found_unaliased) + { + if ((*found_unaliased)->eq(item, 0)) + continue; + /* + Two matching fields in select list. + We already can bail out because we are searching through + unaliased names only and will have duplicate error anyway. + */ + if (report_error != IGNORE_ERRORS) + my_error(ER_NON_UNIQ_ERROR, MYF(0), + find->full_name(), current_thd->where); + return (Item**) 0; + } + found_unaliased= li.ref(); + unaliased_counter= i; + *resolution= RESOLVED_IGNORING_ALIAS; + if (db_name) + break; // Perfect match + } + } + else + { + int fname_cmp= my_strcasecmp(system_charset_info, + item_field->field_name, + field_name); + if (!my_strcasecmp(system_charset_info, + item_field->name,field_name)) + { + /* + If table name was not given we should scan through aliases + and non-aliased fields first. We are also checking unaliased + name of the field in then next else-if, to be able to find + instantly field (hidden by alias) if no suitable alias or + non-aliased field was found. + */ + if (found) + { + if ((*found)->eq(item, 0)) + continue; // Same field twice + if (report_error != IGNORE_ERRORS) + my_error(ER_NON_UNIQ_ERROR, MYF(0), + find->full_name(), current_thd->where); + return (Item**) 0; + } + found= li.ref(); + *counter= i; + *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS: + RESOLVED_WITH_NO_ALIAS; + } + else if (!fname_cmp) + { + /* + We will use non-aliased field or react on such ambiguities only if + we won't be able to find aliased field. + Again if we have ambiguity with field outside of select list + we should prefer fields from select list. + */ + if (found_unaliased) + { + if ((*found_unaliased)->eq(item, 0)) + continue; // Same field twice + found_unaliased_non_uniq= 1; + } + found_unaliased= li.ref(); + unaliased_counter= i; + } + } + } + else if (!table_name) + { + if (is_ref_by_name && find->name && item->name && + !my_strcasecmp(system_charset_info,item->name,find->name)) + { + found= li.ref(); + *counter= i; + *resolution= RESOLVED_AGAINST_ALIAS; + break; + } + else if (find->eq(item,0)) + { + found= li.ref(); + *counter= i; + *resolution= RESOLVED_IGNORING_ALIAS; + break; + } + } + else if (table_name && item->type() == Item::REF_ITEM && + ((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF) + { + /* + TODO:Here we process prefixed view references only. What we should + really do is process all types of Item_refs. But this will currently + lead to a clash with the way references to outer SELECTs (from the + HAVING clause) are handled in e.g. : + SELECT 1 FROM t1 AS t1_o GROUP BY a + HAVING (SELECT t1_o.a FROM t1 AS t1_i GROUP BY t1_i.a LIMIT 1). + Processing all Item_refs here will cause t1_o.a to resolve to itself. + We still need to process the special case of Item_direct_view_ref + because in the context of views they have the same meaning as + Item_field for tables. + */ + Item_ident *item_ref= (Item_ident *) item; + if (item_ref->name && item_ref->table_name && + !my_strcasecmp(system_charset_info, item_ref->name, field_name) && + !my_strcasecmp(table_alias_charset, item_ref->table_name, + table_name) && + (!db_name || (item_ref->db_name && + !strcmp (item_ref->db_name, db_name)))) + { + found= li.ref(); + *counter= i; + *resolution= RESOLVED_IGNORING_ALIAS; + break; + } + } + } + if (!found) + { + if (found_unaliased_non_uniq) + { + if (report_error != IGNORE_ERRORS) + my_error(ER_NON_UNIQ_ERROR, MYF(0), + find->full_name(), current_thd->where); + return (Item **) 0; + } + if (found_unaliased) + { + found= found_unaliased; + *counter= unaliased_counter; + *resolution= RESOLVED_BEHIND_ALIAS; + } + } + if (found) + return found; + if (report_error != REPORT_EXCEPT_NOT_FOUND) + { + if (report_error == REPORT_ALL_ERRORS) + my_error(ER_BAD_FIELD_ERROR, MYF(0), + find->full_name(), current_thd->where); + return (Item **) 0; + } + else + return (Item **) not_found_item; +} + + +/* + Test if a string is a member of a list of strings. + + SYNOPSIS + test_if_string_in_list() + find the string to look for + str_list a list of strings to be searched + + DESCRIPTION + Sequentially search a list of strings for a string, and test whether + the list contains the same string. + + RETURN + TRUE if find is in str_list + FALSE otherwise +*/ + +static bool +test_if_string_in_list(const char *find, List *str_list) +{ + List_iterator str_list_it(*str_list); + String *curr_str; + size_t find_length= strlen(find); + while ((curr_str= str_list_it++)) + { + if (find_length != curr_str->length()) + continue; + if (!my_strcasecmp(system_charset_info, find, curr_str->ptr())) + return TRUE; + } + return FALSE; +} + + +/* + Create a new name resolution context for an item so that it is + being resolved in a specific table reference. + + SYNOPSIS + set_new_item_local_context() + thd pointer to current thread + item item for which new context is created and set + table_ref table ref where an item showld be resolved + + DESCRIPTION + Create a new name resolution context for an item, so that the item + is resolved only the supplied 'table_ref'. + + RETURN + FALSE if all OK + TRUE otherwise +*/ + +static bool +set_new_item_local_context(THD *thd, Item_ident *item, TABLE_LIST *table_ref) +{ + Name_resolution_context *context; + if (!(context= new (thd->mem_root) Name_resolution_context)) + return TRUE; + context->init(); + context->first_name_resolution_table= + context->last_name_resolution_table= table_ref; + item->context= context; + return FALSE; +} + + +/* + Find and mark the common columns of two table references. + + SYNOPSIS + mark_common_columns() + thd [in] current thread + table_ref_1 [in] the first (left) join operand + table_ref_2 [in] the second (right) join operand + using_fields [in] if the join is JOIN...USING - the join columns, + if NATURAL join, then NULL + found_using_fields [out] number of fields from the USING clause that were + found among the common fields + + DESCRIPTION + The procedure finds the common columns of two relations (either + tables or intermediate join results), and adds an equi-join condition + to the ON clause of 'table_ref_2' for each pair of matching columns. + If some of table_ref_XXX represents a base table or view, then we + create new 'Natural_join_column' instances for each column + reference and store them in the 'join_columns' of the table + reference. + + IMPLEMENTATION + The procedure assumes that store_natural_using_join_columns() was + called for the previous level of NATURAL/USING joins. + + RETURN + TRUE error when some common column is non-unique, or out of memory + FALSE OK +*/ + +static bool +mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2, + List *using_fields, uint *found_using_fields) +{ + Field_iterator_table_ref it_1, it_2; + Natural_join_column *nj_col_1, *nj_col_2; + Query_arena *arena, backup; + bool result= TRUE; + bool first_outer_loop= TRUE; + /* + Leaf table references to which new natural join columns are added + if the leaves are != NULL. + */ + TABLE_LIST *leaf_1= (table_ref_1->nested_join && + !table_ref_1->is_natural_join) ? + NULL : table_ref_1; + TABLE_LIST *leaf_2= (table_ref_2->nested_join && + !table_ref_2->is_natural_join) ? + NULL : table_ref_2; + + DBUG_ENTER("mark_common_columns"); + DBUG_PRINT("info", ("operand_1: %s operand_2: %s", + table_ref_1->alias, table_ref_2->alias)); + + *found_using_fields= 0; + arena= thd->activate_stmt_arena_if_needed(&backup); + + for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next()) + { + bool found= FALSE; + const char *field_name_1; + /* true if field_name_1 is a member of using_fields */ + bool is_using_column_1; + if (!(nj_col_1= it_1.get_or_create_column_ref(thd, leaf_1))) + goto err; + field_name_1= nj_col_1->name(); + is_using_column_1= using_fields && + test_if_string_in_list(field_name_1, using_fields); + DBUG_PRINT ("info", ("field_name_1=%s.%s", + nj_col_1->table_name() ? nj_col_1->table_name() : "", + field_name_1)); + + /* + Find a field with the same name in table_ref_2. + + Note that for the second loop, it_2.set() will iterate over + table_ref_2->join_columns and not generate any new elements or + lists. + */ + nj_col_2= NULL; + for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next()) + { + Natural_join_column *cur_nj_col_2; + const char *cur_field_name_2; + if (!(cur_nj_col_2= it_2.get_or_create_column_ref(thd, leaf_2))) + goto err; + cur_field_name_2= cur_nj_col_2->name(); + DBUG_PRINT ("info", ("cur_field_name_2=%s.%s", + cur_nj_col_2->table_name() ? + cur_nj_col_2->table_name() : "", + cur_field_name_2)); + + /* + Compare the two columns and check for duplicate common fields. + A common field is duplicate either if it was already found in + table_ref_2 (then found == TRUE), or if a field in table_ref_2 + was already matched by some previous field in table_ref_1 + (then cur_nj_col_2->is_common == TRUE). + Note that it is too early to check the columns outside of the + USING list for ambiguity because they are not actually "referenced" + here. These columns must be checked only on unqualified reference + by name (e.g. in SELECT list). + */ + if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2)) + { + DBUG_PRINT ("info", ("match c1.is_common=%d", nj_col_1->is_common)); + if (cur_nj_col_2->is_common || + (found && (!using_fields || is_using_column_1))) + { + my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where); + goto err; + } + nj_col_2= cur_nj_col_2; + found= TRUE; + } + } + if (first_outer_loop && leaf_2) + { + /* + Make sure that the next inner loop "knows" that all columns + are materialized already. + */ + leaf_2->is_join_columns_complete= TRUE; + first_outer_loop= FALSE; + } + if (!found) + continue; // No matching field + + /* + field_1 and field_2 have the same names. Check if they are in the USING + clause (if present), mark them as common fields, and add a new + equi-join condition to the ON clause. + */ + if (nj_col_2 && (!using_fields ||is_using_column_1)) + { + Item *item_1= nj_col_1->create_item(thd); + Item *item_2= nj_col_2->create_item(thd); + Field *field_1= nj_col_1->field(); + Field *field_2= nj_col_2->field(); + Item_ident *item_ident_1, *item_ident_2; + Item_func_eq *eq_cond; + + if (!item_1 || !item_2) + goto err; // out of memory + + /* + The following assert checks that the two created items are of + type Item_ident. + */ + DBUG_ASSERT(!thd->lex->current_select->no_wrap_view_item); + /* + In the case of no_wrap_view_item == 0, the created items must be + of sub-classes of Item_ident. + */ + DBUG_ASSERT(item_1->type() == Item::FIELD_ITEM || + item_1->type() == Item::REF_ITEM); + DBUG_ASSERT(item_2->type() == Item::FIELD_ITEM || + item_2->type() == Item::REF_ITEM); + + /* + We need to cast item_1,2 to Item_ident, because we need to hook name + resolution contexts specific to each item. + */ + item_ident_1= (Item_ident*) item_1; + item_ident_2= (Item_ident*) item_2; + /* + Create and hook special name resolution contexts to each item in the + new join condition . We need this to both speed-up subsequent name + resolution of these items, and to enable proper name resolution of + the items during the execute phase of PS. + */ + if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) || + set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref)) + goto err; + + if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2))) + goto err; /* Out of memory. */ + + /* + Add the new equi-join condition to the ON clause. Notice that + fix_fields() is applied to all ON conditions in setup_conds() + so we don't do it here. + */ + add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ? + table_ref_1 : table_ref_2), + eq_cond); + + nj_col_1->is_common= nj_col_2->is_common= TRUE; + DBUG_PRINT ("info", ("%s.%s and %s.%s are common", + nj_col_1->table_name() ? + nj_col_1->table_name() : "", + nj_col_1->name(), + nj_col_2->table_name() ? + nj_col_2->table_name() : "", + nj_col_2->name())); + + if (field_1) + { + TABLE *table_1= nj_col_1->table_ref->table; + /* Mark field_1 used for table cache. */ + bitmap_set_bit(table_1->read_set, field_1->field_index); + table_1->covering_keys.intersect(field_1->part_of_key); + table_1->merge_keys.merge(field_1->part_of_key); + } + if (field_2) + { + TABLE *table_2= nj_col_2->table_ref->table; + /* Mark field_2 used for table cache. */ + bitmap_set_bit(table_2->read_set, field_2->field_index); + table_2->covering_keys.intersect(field_2->part_of_key); + table_2->merge_keys.merge(field_2->part_of_key); + } + + if (using_fields != NULL) + ++(*found_using_fields); + } + } + if (leaf_1) + leaf_1->is_join_columns_complete= TRUE; + + /* + Everything is OK. + Notice that at this point there may be some column names in the USING + clause that are not among the common columns. This is an SQL error and + we check for this error in store_natural_using_join_columns() when + (found_using_fields < length(join_using_fields)). + */ + result= FALSE; + +err: + if (arena) + thd->restore_active_arena(arena, &backup); + DBUG_RETURN(result); +} + + + +/* + Materialize and store the row type of NATURAL/USING join. + + SYNOPSIS + store_natural_using_join_columns() + thd current thread + natural_using_join the table reference of the NATURAL/USING join + table_ref_1 the first (left) operand (of a NATURAL/USING join). + table_ref_2 the second (right) operand (of a NATURAL/USING join). + using_fields if the join is JOIN...USING - the join columns, + if NATURAL join, then NULL + found_using_fields number of fields from the USING clause that were + found among the common fields + + DESCRIPTION + Iterate over the columns of both join operands and sort and store + all columns into the 'join_columns' list of natural_using_join + where the list is formed by three parts: + part1: The coalesced columns of table_ref_1 and table_ref_2, + sorted according to the column order of the first table. + part2: The other columns of the first table, in the order in + which they were defined in CREATE TABLE. + part3: The other columns of the second table, in the order in + which they were defined in CREATE TABLE. + Time complexity - O(N1+N2), where Ni = length(table_ref_i). + + IMPLEMENTATION + The procedure assumes that mark_common_columns() has been called + for the join that is being processed. + + RETURN + TRUE error: Some common column is ambiguous + FALSE OK +*/ + +static bool +store_natural_using_join_columns(THD *thd, TABLE_LIST *natural_using_join, + TABLE_LIST *table_ref_1, + TABLE_LIST *table_ref_2, + List *using_fields, + uint found_using_fields) +{ + Field_iterator_table_ref it_1, it_2; + Natural_join_column *nj_col_1, *nj_col_2; + Query_arena *arena, backup; + bool result= TRUE; + List *non_join_columns; + DBUG_ENTER("store_natural_using_join_columns"); + + DBUG_ASSERT(!natural_using_join->join_columns); + + arena= thd->activate_stmt_arena_if_needed(&backup); + + if (!(non_join_columns= new List) || + !(natural_using_join->join_columns= new List)) + goto err; + + /* Append the columns of the first join operand. */ + for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next()) + { + nj_col_1= it_1.get_natural_column_ref(); + if (nj_col_1->is_common) + { + natural_using_join->join_columns->push_back(nj_col_1); + /* Reset the common columns for the next call to mark_common_columns. */ + nj_col_1->is_common= FALSE; + } + else + non_join_columns->push_back(nj_col_1); + } + + /* + Check that all columns in the USING clause are among the common + columns. If this is not the case, report the first one that was + not found in an error. + */ + if (using_fields && found_using_fields < using_fields->elements) + { + String *using_field_name; + List_iterator_fast using_fields_it(*using_fields); + while ((using_field_name= using_fields_it++)) + { + const char *using_field_name_ptr= using_field_name->c_ptr(); + List_iterator_fast + it(*(natural_using_join->join_columns)); + Natural_join_column *common_field; + + for (;;) + { + /* If reached the end of fields, and none was found, report error. */ + if (!(common_field= it++)) + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr, + current_thd->where); + goto err; + } + if (!my_strcasecmp(system_charset_info, + common_field->name(), using_field_name_ptr)) + break; // Found match + } + } + } + + /* Append the non-equi-join columns of the second join operand. */ + for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next()) + { + nj_col_2= it_2.get_natural_column_ref(); + if (!nj_col_2->is_common) + non_join_columns->push_back(nj_col_2); + else + { + /* Reset the common columns for the next call to mark_common_columns. */ + nj_col_2->is_common= FALSE; + } + } + + if (non_join_columns->elements > 0) + natural_using_join->join_columns->concat(non_join_columns); + natural_using_join->is_join_columns_complete= TRUE; + + result= FALSE; + +err: + if (arena) + thd->restore_active_arena(arena, &backup); + DBUG_RETURN(result); +} + + +/* + Precompute and store the row types of the top-most NATURAL/USING joins. + + SYNOPSIS + store_top_level_join_columns() + thd current thread + table_ref nested join or table in a FROM clause + left_neighbor neighbor table reference to the left of table_ref at the + same level in the join tree + right_neighbor neighbor table reference to the right of table_ref at the + same level in the join tree + + DESCRIPTION + The procedure performs a post-order traversal of a nested join tree + and materializes the row types of NATURAL/USING joins in a + bottom-up manner until it reaches the TABLE_LIST elements that + represent the top-most NATURAL/USING joins. The procedure should be + applied to each element of SELECT_LEX::top_join_list (i.e. to each + top-level element of the FROM clause). + + IMPLEMENTATION + Notice that the table references in the list nested_join->join_list + are in reverse order, thus when we iterate over it, we are moving + from the right to the left in the FROM clause. + + RETURN + TRUE Error + FALSE OK +*/ + +static bool +store_top_level_join_columns(THD *thd, TABLE_LIST *table_ref, + TABLE_LIST *left_neighbor, + TABLE_LIST *right_neighbor) +{ + Query_arena *arena, backup; + bool result= TRUE; + + DBUG_ENTER("store_top_level_join_columns"); + + arena= thd->activate_stmt_arena_if_needed(&backup); + + /* Call the procedure recursively for each nested table reference. */ + if (table_ref->nested_join) + { + List_iterator_fast nested_it(table_ref->nested_join->join_list); + TABLE_LIST *same_level_left_neighbor= nested_it++; + TABLE_LIST *same_level_right_neighbor= NULL; + /* Left/right-most neighbors, possibly at higher levels in the join tree. */ + TABLE_LIST *real_left_neighbor, *real_right_neighbor; + + while (same_level_left_neighbor) + { + TABLE_LIST *cur_table_ref= same_level_left_neighbor; + same_level_left_neighbor= nested_it++; + /* + The order of RIGHT JOIN operands is reversed in 'join list' to + transform it into a LEFT JOIN. However, in this procedure we need + the join operands in their lexical order, so below we reverse the + join operands. Notice that this happens only in the first loop, + and not in the second one, as in the second loop + same_level_left_neighbor == NULL. + This is the correct behavior, because the second loop sets + cur_table_ref reference correctly after the join operands are + swapped in the first loop. + */ + if (same_level_left_neighbor && + cur_table_ref->outer_join & JOIN_TYPE_RIGHT) + { + /* This can happen only for JOIN ... ON. */ + DBUG_ASSERT(table_ref->nested_join->join_list.elements == 2); + swap_variables(TABLE_LIST*, same_level_left_neighbor, cur_table_ref); + } + + /* + Pick the parent's left and right neighbors if there are no immediate + neighbors at the same level. + */ + real_left_neighbor= (same_level_left_neighbor) ? + same_level_left_neighbor : left_neighbor; + real_right_neighbor= (same_level_right_neighbor) ? + same_level_right_neighbor : right_neighbor; + + if (cur_table_ref->nested_join && + store_top_level_join_columns(thd, cur_table_ref, + real_left_neighbor, real_right_neighbor)) + goto err; + same_level_right_neighbor= cur_table_ref; + } + } + + /* + If this is a NATURAL/USING join, materialize its result columns and + convert to a JOIN ... ON. + */ + if (table_ref->is_natural_join) + { + DBUG_ASSERT(table_ref->nested_join && + table_ref->nested_join->join_list.elements == 2); + List_iterator_fast operand_it(table_ref->nested_join->join_list); + /* + Notice that the order of join operands depends on whether table_ref + represents a LEFT or a RIGHT join. In a RIGHT join, the operands are + in inverted order. + */ + TABLE_LIST *table_ref_2= operand_it++; /* Second NATURAL join operand.*/ + TABLE_LIST *table_ref_1= operand_it++; /* First NATURAL join operand. */ + List *using_fields= table_ref->join_using_fields; + uint found_using_fields; + + /* + The two join operands were interchanged in the parser, change the order + back for 'mark_common_columns'. + */ + if (table_ref_2->outer_join & JOIN_TYPE_RIGHT) + swap_variables(TABLE_LIST*, table_ref_1, table_ref_2); + if (mark_common_columns(thd, table_ref_1, table_ref_2, + using_fields, &found_using_fields)) + goto err; + + /* + Swap the join operands back, so that we pick the columns of the second + one as the coalesced columns. In this way the coalesced columns are the + same as of an equivalent LEFT JOIN. + */ + if (table_ref_1->outer_join & JOIN_TYPE_RIGHT) + swap_variables(TABLE_LIST*, table_ref_1, table_ref_2); + if (store_natural_using_join_columns(thd, table_ref, table_ref_1, + table_ref_2, using_fields, + found_using_fields)) + goto err; + + /* + Change NATURAL JOIN to JOIN ... ON. We do this for both operands + because either one of them or the other is the one with the + natural join flag because RIGHT joins are transformed into LEFT, + and the two tables may be reordered. + */ + table_ref_1->natural_join= table_ref_2->natural_join= NULL; + + /* Add a TRUE condition to outer joins that have no common columns. */ + if (table_ref_2->outer_join && + !table_ref_1->on_expr && !table_ref_2->on_expr) + table_ref_2->on_expr= new Item_int((longlong) 1,1); /* Always true. */ + + /* Change this table reference to become a leaf for name resolution. */ + if (left_neighbor) + { + TABLE_LIST *last_leaf_on_the_left; + last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution(); + last_leaf_on_the_left->next_name_resolution_table= table_ref; + } + if (right_neighbor) + { + TABLE_LIST *first_leaf_on_the_right; + first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution(); + table_ref->next_name_resolution_table= first_leaf_on_the_right; + } + else + table_ref->next_name_resolution_table= NULL; + } + result= FALSE; /* All is OK. */ + +err: + if (arena) + thd->restore_active_arena(arena, &backup); + DBUG_RETURN(result); +} + + +/* + Compute and store the row types of the top-most NATURAL/USING joins + in a FROM clause. + + SYNOPSIS + setup_natural_join_row_types() + thd current thread + from_clause list of top-level table references in a FROM clause + + DESCRIPTION + Apply the procedure 'store_top_level_join_columns' to each of the + top-level table referencs of the FROM clause. Adjust the list of tables + for name resolution - context->first_name_resolution_table to the + top-most, lef-most NATURAL/USING join. + + IMPLEMENTATION + Notice that the table references in 'from_clause' are in reverse + order, thus when we iterate over it, we are moving from the right + to the left in the FROM clause. + + RETURN + TRUE Error + FALSE OK +*/ +static bool setup_natural_join_row_types(THD *thd, + List *from_clause, + Name_resolution_context *context) +{ + thd->where= "from clause"; + if (from_clause->elements == 0) + return FALSE; /* We come here in the case of UNIONs. */ + + List_iterator_fast table_ref_it(*from_clause); + TABLE_LIST *table_ref; /* Current table reference. */ + /* Table reference to the left of the current. */ + TABLE_LIST *left_neighbor; + /* Table reference to the right of the current. */ + TABLE_LIST *right_neighbor= NULL; + bool save_first_natural_join_processing= + context->select_lex->first_natural_join_processing; + + context->select_lex->first_natural_join_processing= FALSE; + + /* Note that tables in the list are in reversed order */ + for (left_neighbor= table_ref_it++; left_neighbor ; ) + { + table_ref= left_neighbor; + left_neighbor= table_ref_it++; + /* + Do not redo work if already done: + 1) for stored procedures, + 2) for multitable update after lock failure and table reopening. + */ + if (save_first_natural_join_processing) + { + context->select_lex->first_natural_join_processing= FALSE; + if (store_top_level_join_columns(thd, table_ref, + left_neighbor, right_neighbor)) + return TRUE; + if (left_neighbor) + { + TABLE_LIST *first_leaf_on_the_right; + first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution(); + left_neighbor->next_name_resolution_table= first_leaf_on_the_right; + } + } + right_neighbor= table_ref; + } + + /* + Store the top-most, left-most NATURAL/USING join, so that we start + the search from that one instead of context->table_list. At this point + right_neighbor points to the left-most top-level table reference in the + FROM clause. + */ + DBUG_ASSERT(right_neighbor); + context->first_name_resolution_table= + right_neighbor->first_leaf_for_name_resolution(); + + return FALSE; +} + + +/**************************************************************************** +** Expand all '*' in given fields +****************************************************************************/ + +int setup_wild(THD *thd, TABLE_LIST *tables, List &fields, + List *sum_func_list, + uint wild_num) +{ + if (!wild_num) + return(0); + + Item *item; + List_iterator it(fields); + Query_arena *arena, backup; + DBUG_ENTER("setup_wild"); + + /* + Don't use arena if we are not in prepared statements or stored procedures + For PS/SP we have to use arena to remember the changes + */ + arena= thd->activate_stmt_arena_if_needed(&backup); + + thd->lex->current_select->cur_pos_in_select_list= 0; + while (wild_num && (item= it++)) + { + if (item->type() == Item::FIELD_ITEM && + ((Item_field*) item)->field_name && + ((Item_field*) item)->field_name[0] == '*' && + !((Item_field*) item)->field) + { + uint elem= fields.elements; + bool any_privileges= ((Item_field *) item)->any_privileges; + Item_subselect *subsel= thd->lex->current_select->master_unit()->item; + if (subsel && + subsel->substype() == Item_subselect::EXISTS_SUBS) + { + /* + It is EXISTS(SELECT * ...) and we can replace * by any constant. + + Item_int do not need fix_fields() because it is basic constant. + */ + it.replace(new Item_int("Not_used", (longlong) 1, + MY_INT64_NUM_DECIMAL_DIGITS)); + } + else if (insert_fields(thd, ((Item_field*) item)->context, + ((Item_field*) item)->db_name, + ((Item_field*) item)->table_name, &it, + any_privileges)) + { + if (arena) + thd->restore_active_arena(arena, &backup); + DBUG_RETURN(-1); + } + if (sum_func_list) + { + /* + sum_func_list is a list that has the fields list as a tail. + Because of this we have to update the element count also for this + list after expanding the '*' entry. + */ + sum_func_list->elements+= fields.elements - elem; + } + wild_num--; + } + else + thd->lex->current_select->cur_pos_in_select_list++; + } + thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS; + if (arena) + { + /* make * substituting permanent */ + SELECT_LEX *select_lex= thd->lex->current_select; + select_lex->with_wild= 0; + /* + The assignment below is translated to memcpy() call (at least on some + platforms). memcpy() expects that source and destination areas do not + overlap. That problem was detected by valgrind. + */ + if (&select_lex->item_list != &fields) + select_lex->item_list= fields; + + thd->restore_active_arena(arena, &backup); + } + DBUG_RETURN(0); +} + +/**************************************************************************** +** Check that all given fields exists and fill struct with current data +****************************************************************************/ + +bool setup_fields(THD *thd, Item **ref_pointer_array, + List &fields, enum_mark_columns mark_used_columns, + List *sum_func_list, bool allow_sum_func) +{ + reg2 Item *item; + enum_mark_columns save_mark_used_columns= thd->mark_used_columns; + nesting_map save_allow_sum_func= thd->lex->allow_sum_func; + List_iterator it(fields); + bool save_is_item_list_lookup; + DBUG_ENTER("setup_fields"); + + thd->mark_used_columns= mark_used_columns; + DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); + if (allow_sum_func) + thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level; + thd->where= THD::DEFAULT_WHERE; + save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup; + thd->lex->current_select->is_item_list_lookup= 0; + + /* + To prevent fail on forward lookup we fill it with zerows, + then if we got pointer on zero after find_item_in_list we will know + that it is forward lookup. + + There is other way to solve problem: fill array with pointers to list, + but it will be slower. + + TODO: remove it when (if) we made one list for allfields and + ref_pointer_array + */ + if (ref_pointer_array) + bzero(ref_pointer_array, sizeof(Item *) * fields.elements); + + /* + We call set_entry() there (before fix_fields() of the whole list of field + items) because: + 1) the list of field items has same order as in the query, and the + Item_func_get_user_var item may go before the Item_func_set_user_var: + SELECT @a, @a := 10 FROM t; + 2) The entry->update_query_id value controls constantness of + Item_func_get_user_var items, so in presence of Item_func_set_user_var + items we have to refresh their entries before fixing of + Item_func_get_user_var items. + */ + List_iterator li(thd->lex->set_var_list); + Item_func_set_user_var *var; + while ((var= li++)) + var->set_entry(thd, FALSE); + + Item **ref= ref_pointer_array; + thd->lex->current_select->cur_pos_in_select_list= 0; + while ((item= it++)) + { + if ((!item->fixed && item->fix_fields(thd, it.ref())) || + (item= *(it.ref()))->check_cols(1)) + { + thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup; + thd->lex->allow_sum_func= save_allow_sum_func; + thd->mark_used_columns= save_mark_used_columns; + DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); + DBUG_RETURN(TRUE); /* purecov: inspected */ + } + if (ref) + *(ref++)= item; + if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM && + sum_func_list) + item->split_sum_func(thd, ref_pointer_array, *sum_func_list); + thd->used_tables|= item->used_tables(); + thd->lex->current_select->cur_pos_in_select_list++; + } + thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup; + thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS; + + thd->lex->allow_sum_func= save_allow_sum_func; + thd->mark_used_columns= save_mark_used_columns; + DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); + DBUG_RETURN(test(thd->is_error())); +} + + +/* + make list of leaves of join table tree + + SYNOPSIS + make_leaves_list() + list pointer to pointer on list first element + tables table list + + RETURN pointer on pointer to next_leaf of last element +*/ + +TABLE_LIST **make_leaves_list(TABLE_LIST **list, TABLE_LIST *tables) +{ + for (TABLE_LIST *table= tables; table; table= table->next_local) + { + if (table->merge_underlying_list) + { + DBUG_ASSERT(table->view && + table->effective_algorithm == VIEW_ALGORITHM_MERGE); + list= make_leaves_list(list, table->merge_underlying_list); + } + else + { + *list= table; + list= &table->next_leaf; + } + } + return list; +} + +/* + prepare tables + + SYNOPSIS + setup_tables() + thd Thread handler + context name resolution contest to setup table list there + from_clause Top-level list of table references in the FROM clause + tables Table list (select_lex->table_list) + leaves List of join table leaves list (select_lex->leaf_tables) + refresh It is onle refresh for subquery + select_insert It is SELECT ... INSERT command + + NOTE + Check also that the 'used keys' and 'ignored keys' exists and set up the + table structure accordingly. + Create a list of leaf tables. For queries with NATURAL/USING JOINs, + compute the row types of the top most natural/using join table references + and link these into a list of table references for name resolution. + + This has to be called for all tables that are used by items, as otherwise + table->map is not set and all Item_field will be regarded as const items. + + RETURN + FALSE ok; In this case *map will includes the chosen index + TRUE error +*/ + +bool setup_tables(THD *thd, Name_resolution_context *context, + List *from_clause, TABLE_LIST *tables, + TABLE_LIST **leaves, bool select_insert) +{ + uint tablenr= 0; + DBUG_ENTER("setup_tables"); + + DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables || + (context->table_list && context->first_name_resolution_table)); + /* + this is used for INSERT ... SELECT. + For select we setup tables except first (and its underlying tables) + */ + TABLE_LIST *first_select_table= (select_insert ? + tables->next_local: + 0); + if (!(*leaves)) + make_leaves_list(leaves, tables); + + TABLE_LIST *table_list; + for (table_list= *leaves; + table_list; + table_list= table_list->next_leaf, tablenr++) + { + TABLE *table= table_list->table; + table->pos_in_table_list= table_list; + if (first_select_table && + table_list->top_table() == first_select_table) + { + /* new counting for SELECT of INSERT ... SELECT command */ + first_select_table= 0; + tablenr= 0; + } + setup_table_map(table, table_list, tablenr); + if (table_list->process_index_hints(table)) + DBUG_RETURN(1); + } + if (tablenr > MAX_TABLES) + { + my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES); + DBUG_RETURN(1); + } + for (table_list= tables; + table_list; + table_list= table_list->next_local) + { + if (table_list->merge_underlying_list) + { + DBUG_ASSERT(table_list->view && + table_list->effective_algorithm == VIEW_ALGORITHM_MERGE); + Query_arena *arena= thd->stmt_arena, backup; + bool res; + if (arena->is_conventional()) + arena= 0; // For easier test + else + thd->set_n_backup_active_arena(arena, &backup); + res= table_list->setup_underlying(thd); + if (arena) + thd->restore_active_arena(arena, &backup); + if (res) + DBUG_RETURN(1); + } + } + + /* Precompute and store the row types of NATURAL/USING joins. */ + if (setup_natural_join_row_types(thd, from_clause, context)) + DBUG_RETURN(1); + + DBUG_RETURN(0); +} + + +/* + prepare tables and check access for the view tables + + SYNOPSIS + setup_tables_and_check_view_access() + thd Thread handler + context name resolution contest to setup table list there + from_clause Top-level list of table references in the FROM clause + tables Table list (select_lex->table_list) + conds Condition of current SELECT (can be changed by VIEW) + leaves List of join table leaves list (select_lex->leaf_tables) + refresh It is onle refresh for subquery + select_insert It is SELECT ... INSERT command + want_access what access is needed + + NOTE + a wrapper for check_tables that will also check the resulting + table leaves list for access to all the tables that belong to a view + + RETURN + FALSE ok; In this case *map will include the chosen index + TRUE error +*/ +bool setup_tables_and_check_access(THD *thd, + Name_resolution_context *context, + List *from_clause, + TABLE_LIST *tables, + TABLE_LIST **leaves, + bool select_insert, + ulong want_access_first, + ulong want_access) +{ + TABLE_LIST *leaves_tmp= NULL; + bool first_table= true; + + if (setup_tables(thd, context, from_clause, tables, + &leaves_tmp, select_insert)) + return TRUE; + + if (leaves) + *leaves= leaves_tmp; + + for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf) + { + if (leaves_tmp->belong_to_view && + check_single_table_access(thd, first_table ? want_access_first : + want_access, leaves_tmp, FALSE)) + { + tables->hide_view_error(thd); + return TRUE; + } + first_table= 0; + } + return FALSE; +} + + +/* + Create a key_map from a list of index names + + SYNOPSIS + get_key_map_from_key_list() + map key_map to fill in + table Table + index_list List of index names + + RETURN + 0 ok; In this case *map will includes the choosed index + 1 error +*/ + +bool get_key_map_from_key_list(key_map *map, TABLE *table, + List *index_list) +{ + List_iterator_fast it(*index_list); + String *name; + uint pos; + + map->clear_all(); + while ((name=it++)) + { + if (table->s->keynames.type_names == 0 || + (pos= find_type(&table->s->keynames, name->ptr(), + name->length(), 1)) <= + 0) + { + my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(), + table->pos_in_table_list->alias); + map->set_all(); + return 1; + } + map->set_bit(pos-1); + } + return 0; +} + + +/* + Drops in all fields instead of current '*' field + + SYNOPSIS + insert_fields() + thd Thread handler + context Context for name resolution + db_name Database name in case of 'database_name.table_name.*' + table_name Table name in case of 'table_name.*' + it Pointer to '*' + any_privileges 0 If we should ensure that we have SELECT privileges + for all columns + 1 If any privilege is ok + RETURN + 0 ok 'it' is updated to point at last inserted + 1 error. Error message is generated but not sent to client +*/ + +bool +insert_fields(THD *thd, Name_resolution_context *context, const char *db_name, + const char *table_name, List_iterator *it, + bool any_privileges) +{ + Field_iterator_table_ref field_iterator; + bool found; + char name_buff[NAME_LEN+1]; + DBUG_ENTER("insert_fields"); + DBUG_PRINT("arena", ("stmt arena: 0x%lx", (ulong)thd->stmt_arena)); + + if (db_name && lower_case_table_names) + { + /* + convert database to lower case for comparison + We can't do this in Item_field as this would change the + 'name' of the item which may be used in the select list + */ + strmake(name_buff, db_name, sizeof(name_buff)-1); + my_casedn_str(files_charset_info, name_buff); + db_name= name_buff; + } + + found= FALSE; + + /* + If table names are qualified, then loop over all tables used in the query, + else treat natural joins as leaves and do not iterate over their underlying + tables. + */ + for (TABLE_LIST *tables= (table_name ? context->table_list : + context->first_name_resolution_table); + tables; + tables= (table_name ? tables->next_local : + tables->next_name_resolution_table) + ) + { + Field *field; + TABLE *table= tables->table; + + DBUG_ASSERT(tables->is_leaf_for_name_resolution()); + + if ((table_name && my_strcasecmp(table_alias_charset, table_name, + tables->alias)) || + (db_name && strcmp(tables->db,db_name))) + continue; + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* + Ensure that we have access rights to all fields to be inserted. Under + some circumstances, this check may be skipped. + + - If any_privileges is true, skip the check. + + - If the SELECT privilege has been found as fulfilled already for both + the TABLE and TABLE_LIST objects (and both of these exist, of + course), the check is skipped. + + - If the SELECT privilege has been found fulfilled for the TABLE object + and the TABLE_LIST represents a derived table other than a view (see + below), the check is skipped. + + - If the TABLE_LIST object represents a view, we may skip checking if + the SELECT privilege has been found fulfilled for it, regardless of + the TABLE object. + + - If there is no TABLE object, the test is skipped if either + * the TABLE_LIST does not represent a view, or + * the SELECT privilege has been found fulfilled. + + A TABLE_LIST that is not a view may be a subquery, an + information_schema table, or a nested table reference. See the comment + for TABLE_LIST. + */ + if (!((table && !tables->view && (table->grant.privilege & SELECT_ACL)) || + (tables->view && (tables->grant.privilege & SELECT_ACL))) && + !any_privileges) + { + field_iterator.set(tables); + if (check_grant_all_columns(thd, SELECT_ACL, &field_iterator)) + DBUG_RETURN(TRUE); + } +#endif + + /* + Update the tables used in the query based on the referenced fields. For + views and natural joins this update is performed inside the loop below. + */ + if (table) + thd->used_tables|= table->map; + + /* + Initialize a generic field iterator for the current table reference. + Notice that it is guaranteed that this iterator will iterate over the + fields of a single table reference, because 'tables' is a leaf (for + name resolution purposes). + */ + field_iterator.set(tables); + + for (; !field_iterator.end_of_fields(); field_iterator.next()) + { + Item *item; + + if (!(item= field_iterator.create_item(thd))) + DBUG_RETURN(TRUE); + DBUG_ASSERT(item->fixed); + /* cache the table for the Item_fields inserted by expanding stars */ + if (item->type() == Item::FIELD_ITEM && tables->cacheable_table) + ((Item_field *)item)->cached_table= tables; + + if (!found) + { + found= TRUE; + it->replace(item); /* Replace '*' with the first found item. */ + } + else + it->after(item); /* Add 'item' to the SELECT list. */ + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* + Set privilege information for the fields of newly created views. + We have that (any_priviliges == TRUE) if and only if we are creating + a view. In the time of view creation we can't use the MERGE algorithm, + therefore if 'tables' is itself a view, it is represented by a + temporary table. Thus in this case we can be sure that 'item' is an + Item_field. + */ + if (any_privileges) + { + DBUG_ASSERT((tables->field_translation == NULL && table) || + tables->is_natural_join); + DBUG_ASSERT(item->type() == Item::FIELD_ITEM); + Item_field *fld= (Item_field*) item; + const char *field_table_name= field_iterator.get_table_name(); + + if (!tables->schema_table && + !(fld->have_privileges= + (get_column_grant(thd, field_iterator.grant(), + field_iterator.get_db_name(), + field_table_name, fld->field_name) & + VIEW_ANY_ACL))) + { + my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), "ANY", + thd->security_ctx->priv_user, + thd->security_ctx->host_or_ip, + field_table_name); + DBUG_RETURN(TRUE); + } + } +#endif + + if ((field= field_iterator.field())) + { + /* Mark fields as used to allow storage engine to optimze access */ + bitmap_set_bit(field->table->read_set, field->field_index); + if (table) + { + table->covering_keys.intersect(field->part_of_key); + table->merge_keys.merge(field->part_of_key); + } + if (tables->is_natural_join) + { + TABLE *field_table; + /* + In this case we are sure that the column ref will not be created + because it was already created and stored with the natural join. + */ + Natural_join_column *nj_col; + if (!(nj_col= field_iterator.get_natural_column_ref())) + DBUG_RETURN(TRUE); + DBUG_ASSERT(nj_col->table_field); + field_table= nj_col->table_ref->table; + if (field_table) + { + thd->used_tables|= field_table->map; + field_table->covering_keys.intersect(field->part_of_key); + field_table->merge_keys.merge(field->part_of_key); + field_table->used_fields++; + } + } + } + else + thd->used_tables|= item->used_tables(); + thd->lex->current_select->cur_pos_in_select_list++; + } + /* + In case of stored tables, all fields are considered as used, + while in the case of views, the fields considered as used are the + ones marked in setup_tables during fix_fields of view columns. + For NATURAL joins, used_tables is updated in the IF above. + */ + if (table) + table->used_fields= table->s->fields; + } + if (found) + DBUG_RETURN(FALSE); + + /* + TODO: in the case when we skipped all columns because there was a + qualified '*', and all columns were coalesced, we have to give a more + meaningful message than ER_BAD_TABLE_ERROR. + */ + if (!table_name) + my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0)); + else + my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name); + + DBUG_RETURN(TRUE); +} + + +/* + Fix all conditions and outer join expressions. + + SYNOPSIS + setup_conds() + thd thread handler + tables list of tables for name resolving (select_lex->table_list) + leaves list of leaves of join table tree (select_lex->leaf_tables) + conds WHERE clause + + DESCRIPTION + TODO + + RETURN + TRUE if some error occured (e.g. out of memory) + FALSE if all is OK +*/ + +int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves, + COND **conds) +{ + SELECT_LEX *select_lex= thd->lex->current_select; + Query_arena *arena= thd->stmt_arena, backup; + TABLE_LIST *table= NULL; // For HP compilers + /* + it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX + which belong to LEX, i.e. most up SELECT) will be updated by + INSERT/UPDATE/LOAD + NOTE: using this condition helps to prevent call of prepare_check_option() + from subquery of VIEW, because tables of subquery belongs to VIEW + (see condition before prepare_check_option() call) + */ + bool it_is_update= (select_lex == &thd->lex->select_lex) && + thd->lex->which_check_option_applicable(); + bool save_is_item_list_lookup= select_lex->is_item_list_lookup; + select_lex->is_item_list_lookup= 0; + DBUG_ENTER("setup_conds"); + + if (select_lex->conds_processed_with_permanent_arena || + arena->is_conventional()) + arena= 0; // For easier test + + thd->mark_used_columns= MARK_COLUMNS_READ; + DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); + select_lex->cond_count= 0; + select_lex->between_count= 0; + select_lex->max_equal_elems= 0; + + for (table= tables; table; table= table->next_local) + { + if (table->prepare_where(thd, conds, FALSE)) + goto err_no_arena; + } + + if (*conds) + { + thd->where="where clause"; + if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) || + (*conds)->check_cols(1)) + goto err_no_arena; + } + + /* + Apply fix_fields() to all ON clauses at all levels of nesting, + including the ones inside view definitions. + */ + for (table= leaves; table; table= table->next_leaf) + { + TABLE_LIST *embedded; /* The table at the current level of nesting. */ + TABLE_LIST *embedding= table; /* The parent nested table reference. */ + do + { + embedded= embedding; + if (embedded->on_expr) + { + /* Make a join an a expression */ + thd->where="on clause"; + if ((!embedded->on_expr->fixed && + embedded->on_expr->fix_fields(thd, &embedded->on_expr)) || + embedded->on_expr->check_cols(1)) + goto err_no_arena; + select_lex->cond_count++; + } + embedding= embedded->embedding; + } + while (embedding && + embedding->nested_join->join_list.head() == embedded); + + /* process CHECK OPTION */ + if (it_is_update) + { + TABLE_LIST *view= table->top_table(); + if (view->effective_with_check) + { + if (view->prepare_check_option(thd)) + goto err_no_arena; + thd->change_item_tree(&table->check_option, view->check_option); + } + } + } + + if (!thd->stmt_arena->is_conventional()) + { + /* + We are in prepared statement preparation code => we should store + WHERE clause changing for next executions. + + We do this ON -> WHERE transformation only once per PS/SP statement. + */ + select_lex->where= *conds; + select_lex->conds_processed_with_permanent_arena= 1; + } + thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup; + DBUG_RETURN(test(thd->is_error())); + +err_no_arena: + select_lex->is_item_list_lookup= save_is_item_list_lookup; + DBUG_RETURN(1); +} + + +/****************************************************************************** +** Fill a record with data (for INSERT or UPDATE) +** Returns : 1 if some field has wrong type +******************************************************************************/ + + +/* + Fill fields with given items. + + SYNOPSIS + fill_record() + thd thread handler + fields Item_fields list to be filled + values values to fill with + ignore_errors TRUE if we should ignore errors + + NOTE + fill_record() may set table->auto_increment_field_not_null and a + caller should make sure that it is reset after their last call to this + function. + + RETURN + FALSE OK + TRUE error occured +*/ + +static bool +fill_record(THD * thd, List &fields, List &values, + bool ignore_errors) +{ + List_iterator_fast f(fields),v(values); + Item *value, *fld; + Item_field *field; + TABLE *table= 0; + DBUG_ENTER("fill_record"); + + /* + Reset the table->auto_increment_field_not_null as it is valid for + only one row. + */ + if (fields.elements) + { + /* + On INSERT or UPDATE fields are checked to be from the same table, + thus we safely can take table from the first field. + */ + fld= (Item_field*)f++; + if (!(field= fld->filed_for_view_update())) + { + my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name); + goto err; + } + table= field->field->table; + table->auto_increment_field_not_null= FALSE; + f.rewind(); + } + while ((fld= f++)) + { + if (!(field= fld->filed_for_view_update())) + { + my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name); + goto err; + } + value=v++; + Field *rfield= field->field; + table= rfield->table; + if (rfield == table->next_number_field) + table->auto_increment_field_not_null= TRUE; + if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors) + { + my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0)); + goto err; + } + } + DBUG_RETURN(thd->is_error()); +err: + if (table) + table->auto_increment_field_not_null= FALSE; + DBUG_RETURN(TRUE); +} + + +/* + Fill fields in list with values from the list of items and invoke + before triggers. + + SYNOPSIS + fill_record_n_invoke_before_triggers() + thd thread context + fields Item_fields list to be filled + values values to fill with + ignore_errors TRUE if we should ignore errors + triggers object holding list of triggers to be invoked + event event type for triggers to be invoked + + NOTE + This function assumes that fields which values will be set and triggers + to be invoked belong to the same table, and that TABLE::record[0] and + record[1] buffers correspond to new and old versions of row respectively. + + RETURN + FALSE OK + TRUE error occured +*/ + +bool +fill_record_n_invoke_before_triggers(THD *thd, List &fields, + List &values, bool ignore_errors, + Table_triggers_list *triggers, + enum trg_event_type event) +{ + return (fill_record(thd, fields, values, ignore_errors) || + (triggers && triggers->process_triggers(thd, event, + TRG_ACTION_BEFORE, TRUE))); +} + + +/* + Fill field buffer with values from Field list + + SYNOPSIS + fill_record() + thd thread handler + ptr pointer on pointer to record + values list of fields + ignore_errors TRUE if we should ignore errors + + NOTE + fill_record() may set table->auto_increment_field_not_null and a + caller should make sure that it is reset after their last call to this + function. + + RETURN + FALSE OK + TRUE error occured +*/ + +bool +fill_record(THD *thd, Field **ptr, List &values, bool ignore_errors) +{ + List_iterator_fast v(values); + Item *value; + TABLE *table= 0; + DBUG_ENTER("fill_record"); + + Field *field; + /* + Reset the table->auto_increment_field_not_null as it is valid for + only one row. + */ + if (*ptr) + { + /* + On INSERT or UPDATE fields are checked to be from the same table, + thus we safely can take table from the first field. + */ + table= (*ptr)->table; + table->auto_increment_field_not_null= FALSE; + } + while ((field = *ptr++) && ! thd->is_error()) + { + value=v++; + table= field->table; + if (field == table->next_number_field) + table->auto_increment_field_not_null= TRUE; + if (value->save_in_field(field, 0) < 0) + goto err; + } + DBUG_RETURN(thd->is_error()); + +err: + if (table) + table->auto_increment_field_not_null= FALSE; + DBUG_RETURN(TRUE); +} + + +/* + Fill fields in array with values from the list of items and invoke + before triggers. + + SYNOPSIS + fill_record_n_invoke_before_triggers() + thd thread context + ptr NULL-ended array of fields to be filled + values values to fill with + ignore_errors TRUE if we should ignore errors + triggers object holding list of triggers to be invoked + event event type for triggers to be invoked + + NOTE + This function assumes that fields which values will be set and triggers + to be invoked belong to the same table, and that TABLE::record[0] and + record[1] buffers correspond to new and old versions of row respectively. + + RETURN + FALSE OK + TRUE error occured +*/ + +bool +fill_record_n_invoke_before_triggers(THD *thd, Field **ptr, + List &values, bool ignore_errors, + Table_triggers_list *triggers, + enum trg_event_type event) +{ + return (fill_record(thd, ptr, values, ignore_errors) || + (triggers && triggers->process_triggers(thd, event, + TRG_ACTION_BEFORE, TRUE))); +} + + +my_bool mysql_rm_tmp_tables(void) +{ + uint i, idx; + char filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN]; + MY_DIR *dirp; + FILEINFO *file; + TABLE_SHARE share; + THD *thd; + DBUG_ENTER("mysql_rm_tmp_tables"); + + if (!(thd= new THD)) + DBUG_RETURN(1); + thd->thread_stack= (char*) &thd; + thd->store_globals(); + + for (i=0; i<=mysql_tmpdir_list.max; i++) + { + tmpdir=mysql_tmpdir_list.list[i]; + /* See if the directory exists */ + if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT)))) + continue; + + /* Remove all SQLxxx tables from directory */ + + for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++) + { + file=dirp->dir_entry+idx; + + /* skiping . and .. */ + if (file->name[0] == '.' && (!file->name[1] || + (file->name[1] == '.' && !file->name[2]))) + continue; + + if (!bcmp((uchar*) file->name, (uchar*) tmp_file_prefix, + tmp_file_prefix_length)) + { + char *ext= fn_ext(file->name); + uint ext_len= strlen(ext); + uint filePath_len= my_snprintf(filePath, sizeof(filePath), + "%s%c%s", tmpdir, FN_LIBCHAR, + file->name); + if (!bcmp((uchar*) reg_ext, (uchar*) ext, ext_len)) + { + handler *handler_file= 0; + /* We should cut file extention before deleting of table */ + memcpy(filePathCopy, filePath, filePath_len - ext_len); + filePathCopy[filePath_len - ext_len]= 0; + init_tmp_table_share(thd, &share, "", 0, "", filePathCopy); + if (!open_table_def(thd, &share, 0) && + ((handler_file= get_new_handler(&share, thd->mem_root, + share.db_type())))) + { + handler_file->ha_delete_table(filePathCopy); + delete handler_file; + } + free_table_share(&share); + } + /* + File can be already deleted by tmp_table.file->delete_table(). + So we hide error messages which happnes during deleting of these + files(MYF(0)). + */ + VOID(my_delete(filePath, MYF(0))); + } + } + my_dirend(dirp); + } + delete thd; + my_pthread_setspecific_ptr(THR_THD, 0); + DBUG_RETURN(0); +} + + + +/***************************************************************************** + unireg support functions +*****************************************************************************/ + +/* + Invalidate any cache entries that are for some DB + + SYNOPSIS + remove_db_from_cache() + db Database name. This will be in lower case if + lower_case_table_name is set + + NOTE: + We can't use hash_delete when looping hash_elements. We mark them first + and afterwards delete those marked unused. +*/ + +void remove_db_from_cache(const char *db) +{ + for (uint idx=0 ; idx < open_cache.records ; idx++) + { + TABLE *table=(TABLE*) hash_element(&open_cache,idx); + if (!strcmp(table->s->db.str, db)) + { + table->s->version= 0L; /* Free when thread is ready */ + if (!table->in_use) + relink_unused(table); + } + } + while (unused_tables && !unused_tables->s->version) + VOID(hash_delete(&open_cache,(uchar*) unused_tables)); +} + + +/* + free all unused tables + + NOTE + This is called by 'handle_manager' when one wants to periodicly flush + all not used tables. +*/ + +void flush_tables() +{ + (void) pthread_mutex_lock(&LOCK_open); + while (unused_tables) + hash_delete(&open_cache,(uchar*) unused_tables); + (void) pthread_mutex_unlock(&LOCK_open); +} + + +/* + Mark all entries with the table as deleted to force an reopen of the table + + The table will be closed (not stored in cache) by the current thread when + close_thread_tables() is called. + + PREREQUISITES + Lock on LOCK_open() + + RETURN + 0 This thread now have exclusive access to this table and no other thread + can access the table until close_thread_tables() is called. + 1 Table is in use by another thread +*/ + +bool remove_table_from_cache(THD *thd, const char *db, const char *table_name, + uint flags) +{ + char key[MAX_DBKEY_LENGTH]; + uint key_length; + TABLE *table; + TABLE_SHARE *share; + bool result= 0, signalled= 0; + DBUG_ENTER("remove_table_from_cache"); + DBUG_PRINT("enter", ("table: '%s'.'%s' flags: %u", db, table_name, flags)); + + key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1; + for (;;) + { + HASH_SEARCH_STATE state; + result= signalled= 0; + + for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length, + &state); + table; + table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length, + &state)) + { + THD *in_use; + DBUG_PRINT("tcache", ("found table: '%s'.'%s' 0x%lx", table->s->db.str, + table->s->table_name.str, (long) table)); + + table->s->version=0L; /* Free when thread is ready */ + if (!(in_use=table->in_use)) + { + DBUG_PRINT("info",("Table was not in use")); + relink_unused(table); + } + else if (in_use != thd) + { + DBUG_PRINT("info", ("Table was in use by other thread")); + /* + Mark that table is going to be deleted from cache. This will + force threads that are in mysql_lock_tables() (but not yet + in thr_multi_lock()) to abort it's locks, close all tables and retry + */ + in_use->some_tables_deleted= 1; + if (table->is_name_opened()) + { + DBUG_PRINT("info", ("Found another active instance of the table")); + result=1; + } + /* Kill delayed insert threads */ + if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) && + ! in_use->killed) + { + in_use->killed= THD::KILL_CONNECTION; + pthread_mutex_lock(&in_use->mysys_var->mutex); + if (in_use->mysys_var->current_cond) + { + pthread_mutex_lock(in_use->mysys_var->current_mutex); + signalled= 1; + pthread_cond_broadcast(in_use->mysys_var->current_cond); + pthread_mutex_unlock(in_use->mysys_var->current_mutex); + } + pthread_mutex_unlock(&in_use->mysys_var->mutex); + } + /* + Now we must abort all tables locks used by this thread + as the thread may be waiting to get a lock for another table. + Note that we need to hold LOCK_open while going through the + list. So that the other thread cannot change it. The other + thread must also hold LOCK_open whenever changing the + open_tables list. Aborting the MERGE lock after a child was + closed and before the parent is closed would be fatal. + */ + for (TABLE *thd_table= in_use->open_tables; + thd_table ; + thd_table= thd_table->next) + { + /* Do not handle locks of MERGE children. */ + if (thd_table->db_stat && !thd_table->parent) // If table is open + signalled|= mysql_lock_abort_for_thread(thd, thd_table); + } + } + else + { + DBUG_PRINT("info", ("Table was in use by current thread. db_stat: %u", + table->db_stat)); + result= result || (flags & RTFC_OWNED_BY_THD_FLAG); + } + } + while (unused_tables && !unused_tables->s->version) + VOID(hash_delete(&open_cache,(uchar*) unused_tables)); + + DBUG_PRINT("info", ("Removing table from table_def_cache")); + /* Remove table from table definition cache if it's not in use */ + if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, + key_length))) + { + DBUG_PRINT("info", ("share version: %lu ref_count: %u", + share->version, share->ref_count)); + share->version= 0; // Mark for delete + if (share->ref_count == 0) + { + pthread_mutex_lock(&share->mutex); + VOID(hash_delete(&table_def_cache, (uchar*) share)); + } + } + + if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG)) + { + /* + Signal any thread waiting for tables to be freed to + reopen their tables + */ + broadcast_refresh(); + DBUG_PRINT("info", ("Waiting for refresh signal")); + if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed) + { + dropping_tables++; + if (likely(signalled)) + (void) pthread_cond_wait(&COND_refresh, &LOCK_open); + else + { + struct timespec abstime; + /* + It can happen that another thread has opened the + table but has not yet locked any table at all. Since + it can be locked waiting for a table that our thread + has done LOCK TABLE x WRITE on previously, we need to + ensure that the thread actually hears our signal + before we go to sleep. Thus we wait for a short time + and then we retry another loop in the + remove_table_from_cache routine. + */ + set_timespec(abstime, 10); + pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime); + } + dropping_tables--; + continue; + } + } + break; + } + DBUG_RETURN(result); +} + + +int setup_ftfuncs(SELECT_LEX *select_lex) +{ + List_iterator li(*(select_lex->ftfunc_list)), + lj(*(select_lex->ftfunc_list)); + Item_func_match *ftf, *ftf2; + + while ((ftf=li++)) + { + if (ftf->fix_index()) + return 1; + lj.rewind(); + while ((ftf2=lj++) != ftf) + { + if (ftf->eq(ftf2,1) && !ftf2->master) + ftf2->master=ftf; + } + } + + return 0; +} + + +int init_ftfuncs(THD *thd, SELECT_LEX *select_lex, bool no_order) +{ + if (select_lex->ftfunc_list->elements) + { + List_iterator li(*(select_lex->ftfunc_list)); + Item_func_match *ifm; + DBUG_PRINT("info",("Performing FULLTEXT search")); + thd_proc_info(thd, "FULLTEXT initialization"); + + while ((ifm=li++)) + ifm->init_search(no_order); + } + return 0; +} + + +/* + open new .frm format table + + SYNOPSIS + open_new_frm() + THD thread handler + path path to .frm file (without extension) + alias alias for table + db database + table_name name of table + db_stat open flags (for example ->OPEN_KEYFILE|HA_OPEN_RNDFILE..) + can be 0 (example in ha_example_table) + prgflag READ_ALL etc.. + ha_open_flags HA_OPEN_ABORT_IF_LOCKED etc.. + outparam result table + table_desc TABLE_LIST descriptor + mem_root temporary MEM_ROOT for parsing +*/ + +static bool +open_new_frm(THD *thd, TABLE_SHARE *share, const char *alias, + uint db_stat, uint prgflag, + uint ha_open_flags, TABLE *outparam, TABLE_LIST *table_desc, + MEM_ROOT *mem_root) +{ + LEX_STRING pathstr; + File_parser *parser; + char path[FN_REFLEN]; + DBUG_ENTER("open_new_frm"); + + /* Create path with extension */ + pathstr.length= (uint) (strxmov(path, share->normalized_path.str, reg_ext, + NullS)- path); + pathstr.str= path; + + if ((parser= sql_parse_prepare(&pathstr, mem_root, 1))) + { + if (is_equal(&view_type, parser->type())) + { + if (table_desc == 0 || table_desc->required_type == FRMTYPE_TABLE) + { + my_error(ER_WRONG_OBJECT, MYF(0), share->db.str, share->table_name.str, + "BASE TABLE"); + goto err; + } + if (mysql_make_view(thd, parser, table_desc, + (prgflag & OPEN_VIEW_NO_PARSE))) + goto err; + } + else + { + /* only VIEWs are supported now */ + my_error(ER_FRM_UNKNOWN_TYPE, MYF(0), share->path.str, parser->type()->str); + goto err; + } + DBUG_RETURN(0); + } + +err: + bzero(outparam, sizeof(TABLE)); // do not run repair + DBUG_RETURN(1); +} + + +bool is_equal(const LEX_STRING *a, const LEX_STRING *b) +{ + return a->length == b->length && !strncmp(a->str, b->str, a->length); +} + + +/* + SYNOPSIS + abort_and_upgrade_lock() + lpt Parameter passing struct + All parameters passed through the ALTER_PARTITION_PARAM_TYPE object + RETURN VALUE + 0 + DESCRIPTION + Remember old lock level (for possible downgrade later on), abort all + waiting threads and ensure that all keeping locks currently are + completed such that we own the lock exclusively and no other interaction + is ongoing. + + thd Thread object + table Table object + db Database name + table_name Table name + old_lock_level Old lock level +*/ + +int abort_and_upgrade_lock(ALTER_PARTITION_PARAM_TYPE *lpt) +{ + uint flags= RTFC_WAIT_OTHER_THREAD_FLAG | RTFC_CHECK_KILLED_FLAG; + DBUG_ENTER("abort_and_upgrade_locks"); + + lpt->old_lock_type= lpt->table->reginfo.lock_type; + VOID(pthread_mutex_lock(&LOCK_open)); + /* If MERGE child, forward lock handling to parent. */ + mysql_lock_abort(lpt->thd, lpt->table->parent ? lpt->table->parent : + lpt->table, TRUE); + VOID(remove_table_from_cache(lpt->thd, lpt->db, lpt->table_name, flags)); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(0); +} + + +/* + SYNOPSIS + close_open_tables_and_downgrade() + RESULT VALUES + NONE + DESCRIPTION + We need to ensure that any thread that has managed to open the table + but not yet encountered our lock on the table is also thrown out to + ensure that no threads see our frm changes premature to the final + version. The intermediate versions are only meant for use after a + crash and later REPAIR TABLE. + We also downgrade locks after the upgrade to WRITE_ONLY +*/ + +/* purecov: begin deadcode */ +void close_open_tables_and_downgrade(ALTER_PARTITION_PARAM_TYPE *lpt) +{ + VOID(pthread_mutex_lock(&LOCK_open)); + remove_table_from_cache(lpt->thd, lpt->db, lpt->table_name, + RTFC_WAIT_OTHER_THREAD_FLAG); + VOID(pthread_mutex_unlock(&LOCK_open)); + /* If MERGE child, forward lock handling to parent. */ + mysql_lock_downgrade_write(lpt->thd, lpt->table->parent ? lpt->table->parent : + lpt->table, lpt->old_lock_type); +} +/* purecov: end */ + + +/* + SYNOPSIS + mysql_wait_completed_table() + lpt Parameter passing struct + my_table My table object + All parameters passed through the ALTER_PARTITION_PARAM object + RETURN VALUES + TRUE Failure + FALSE Success + DESCRIPTION + We have changed the frm file and now we want to wait for all users of + the old frm to complete before proceeding to ensure that no one + remains that uses the old frm definition. + Start by ensuring that all users of the table will be removed from cache + once they are done. Then abort all that have stumbled on locks and + haven't been started yet. + + thd Thread object + table Table object + db Database name + table_name Table name +*/ + +void mysql_wait_completed_table(ALTER_PARTITION_PARAM_TYPE *lpt, TABLE *my_table) +{ + char key[MAX_DBKEY_LENGTH]; + uint key_length; + TABLE *table; + DBUG_ENTER("mysql_wait_completed_table"); + + key_length=(uint) (strmov(strmov(key,lpt->db)+1,lpt->table_name)-key)+1; + VOID(pthread_mutex_lock(&LOCK_open)); + HASH_SEARCH_STATE state; + for (table= (TABLE*) hash_first(&open_cache,(uchar*) key,key_length, + &state) ; + table; + table= (TABLE*) hash_next(&open_cache,(uchar*) key,key_length, + &state)) + { + THD *in_use= table->in_use; + table->s->version= 0L; + if (!in_use) + { + relink_unused(table); + } + else + { + /* Kill delayed insert threads */ + if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) && + ! in_use->killed) + { + in_use->killed= THD::KILL_CONNECTION; + pthread_mutex_lock(&in_use->mysys_var->mutex); + if (in_use->mysys_var->current_cond) + { + pthread_mutex_lock(in_use->mysys_var->current_mutex); + pthread_cond_broadcast(in_use->mysys_var->current_cond); + pthread_mutex_unlock(in_use->mysys_var->current_mutex); + } + pthread_mutex_unlock(&in_use->mysys_var->mutex); + } + /* + Now we must abort all tables locks used by this thread + as the thread may be waiting to get a lock for another table. + Note that we need to hold LOCK_open while going through the + list. So that the other thread cannot change it. The other + thread must also hold LOCK_open whenever changing the + open_tables list. Aborting the MERGE lock after a child was + closed and before the parent is closed would be fatal. + */ + for (TABLE *thd_table= in_use->open_tables; + thd_table ; + thd_table= thd_table->next) + { + /* Do not handle locks of MERGE children. */ + if (thd_table->db_stat && !thd_table->parent) // If table is open + mysql_lock_abort_for_thread(lpt->thd, thd_table); + } + } + } + /* + We start by removing all unused objects from the cache and marking + those in use for removal after completion. Now we also need to abort + all that are locked and are not progressing due to being locked + by our lock. We don't upgrade our lock here. + If MERGE child, forward lock handling to parent. + */ + mysql_lock_abort(lpt->thd, my_table->parent ? my_table->parent : my_table, + FALSE); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_VOID_RETURN; +} + + +/* + Tells if two (or more) tables have auto_increment columns and we want to + lock those tables with a write lock. + + SYNOPSIS + has_two_write_locked_tables_with_auto_increment + tables Table list + + NOTES: + Call this function only when you have established the list of all tables + which you'll want to update (including stored functions, triggers, views + inside your statement). + + RETURN + 0 No + 1 Yes +*/ + +static bool +has_two_write_locked_tables_with_auto_increment(TABLE_LIST *tables) +{ + char *first_table_name= NULL, *first_db; + LINT_INIT(first_db); + + for (TABLE_LIST *table= tables; table; table= table->next_global) + { + /* we must do preliminary checks as table->table may be NULL */ + if (!table->placeholder() && + table->table->found_next_number_field && + (table->lock_type >= TL_WRITE_ALLOW_WRITE)) + { + if (first_table_name == NULL) + { + first_table_name= table->table_name; + first_db= table->db; + DBUG_ASSERT(first_db); + } + else if (strcmp(first_db, table->db) || + strcmp(first_table_name, table->table_name)) + return 1; + } + } + return 0; +} + + +/* + Open and lock system tables for read. + + SYNOPSIS + open_system_tables_for_read() + thd Thread context. + table_list List of tables to open. + backup Pointer to Open_tables_state instance where + information about currently open tables will be + saved, and from which will be restored when we will + end work with system tables. + + NOTES + Thanks to restrictions which we put on opening and locking of + system tables for writing, we can open and lock them for reading + even when we already have some other tables open and locked. One + must call close_system_tables() to close systems tables opened + with this call. + + RETURN + FALSE Success + TRUE Error +*/ + +bool +open_system_tables_for_read(THD *thd, TABLE_LIST *table_list, + Open_tables_state *backup) +{ + DBUG_ENTER("open_system_tables_for_read"); + + thd->reset_n_backup_open_tables_state(backup); + + uint count= 0; + bool not_used; + for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global) + { + TABLE *table= open_table(thd, tables, thd->mem_root, ¬_used, + MYSQL_LOCK_IGNORE_FLUSH); + if (!table) + goto error; + + DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM); + + table->use_all_columns(); + table->reginfo.lock_type= tables->lock_type; + tables->table= table; + count++; + } + + { + TABLE **list= (TABLE**) thd->alloc(sizeof(TABLE*) * count); + TABLE **ptr= list; + for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global) + *(ptr++)= tables->table; + + thd->lock= mysql_lock_tables(thd, list, count, + MYSQL_LOCK_IGNORE_FLUSH, ¬_used); + } + if (thd->lock) + DBUG_RETURN(FALSE); + +error: + close_system_tables(thd, backup); + + DBUG_RETURN(TRUE); +} + + +/* + Close system tables, opened with open_system_tables_for_read(). + + SYNOPSIS + close_system_tables() + thd Thread context + backup Pointer to Open_tables_state instance which holds + information about tables which were open before we + decided to access system tables. +*/ + +void +close_system_tables(THD *thd, Open_tables_state *backup) +{ + close_thread_tables(thd); + thd->restore_backup_open_tables_state(backup); +} + + +/* + Open and lock one system table for update. + + SYNOPSIS + open_system_table_for_update() + thd Thread context. + one_table Table to open. + + NOTES + Table opened with this call should closed using close_thread_tables(). + + RETURN + 0 Error + # Pointer to TABLE object of system table +*/ + +TABLE * +open_system_table_for_update(THD *thd, TABLE_LIST *one_table) +{ + DBUG_ENTER("open_system_table_for_update"); + + TABLE *table= open_ltable(thd, one_table, one_table->lock_type, 0); + if (table) + { + DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM); + table->use_all_columns(); + } + + DBUG_RETURN(table); +} + +/** + Open a performance schema table. + Opening such tables is performed internally in the server + implementation, and is a 'nested' open, since some tables + might be already opened by the current thread. + The thread context before this call is saved, and is restored + when calling close_performance_schema_table(). + @param thd The current thread + @param one_table Performance schema table to open + @param backup [out] Temporary storage used to save the thread context +*/ +TABLE * +open_performance_schema_table(THD *thd, TABLE_LIST *one_table, + Open_tables_state *backup) +{ + uint flags= ( MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK | + MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY | + MYSQL_LOCK_IGNORE_FLUSH | + MYSQL_LOCK_PERF_SCHEMA); + TABLE *table; + /* Save value that is changed in mysql_lock_tables() */ + ulonglong save_utime_after_lock= thd->utime_after_lock; + DBUG_ENTER("open_performance_schema_table"); + + thd->reset_n_backup_open_tables_state(backup); + + if ((table= open_ltable(thd, one_table, one_table->lock_type, flags))) + { + DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_PERFORMANCE); + /* Make sure all columns get assigned to a default value */ + table->use_all_columns(); + table->no_replicate= 1; + /* + Don't set automatic timestamps as we may want to use time of logging, + not from query start + */ + table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET; + } + else + { + /* + If error in mysql_lock_tables(), open_ltable doesn't close the + table. Thread kill during mysql_lock_tables() is such error. But + open tables cannot be accepted when restoring the open tables + state. + */ + if (thd->killed) + close_thread_tables(thd); + thd->restore_backup_open_tables_state(backup); + } + + thd->utime_after_lock= save_utime_after_lock; + DBUG_RETURN(table); +} + +/** + Close a performance schema table. + The last table opened by open_performance_schema_table() + is closed, then the thread context is restored. + @param thd The current thread + @param backup [in] the context to restore. +*/ +void close_performance_schema_table(THD *thd, Open_tables_state *backup) +{ + bool found_old_table; + + /* + If open_performance_schema_table() fails, + this function should not be called. + */ + DBUG_ASSERT(thd->lock != NULL); + + /* + Note: + We do not create explicitly a separate transaction for the + performance table I/O, but borrow the current transaction. + lock + unlock will autocommit the change done in the + performance schema table: this is the expected result. + The current transaction should not be affected by this code. + TODO: Note that if a transactional engine is used for log tables, + this code will need to be revised, as a separate transaction + might be needed. + */ + mysql_unlock_tables(thd, thd->lock); + thd->lock= 0; + + pthread_mutex_lock(&LOCK_open); + + found_old_table= false; + /* + Note that we need to hold LOCK_open while changing the + open_tables list. Another thread may work on it. + (See: remove_table_from_cache(), mysql_wait_completed_table()) + Closing a MERGE child before the parent would be fatal if the + other thread tries to abort the MERGE lock in between. + */ + while (thd->open_tables) + found_old_table|= close_thread_table(thd, &thd->open_tables); + + if (found_old_table) + broadcast_refresh(); + + pthread_mutex_unlock(&LOCK_open); + + thd->restore_backup_open_tables_state(backup); +} + +/** + @} (end of group Data_Dictionary) +*/ diff --git a/dbcon/mysql/sql_class.cc b/dbcon/mysql/sql_class.cc new file mode 100644 index 00000000..e4ed2472 --- /dev/null +++ b/dbcon/mysql/sql_class.cc @@ -0,0 +1,3886 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/***************************************************************************** +** +** This file implements classes defined in sql_class.h +** Especially the classes to handle a result from a select +** +*****************************************************************************/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "mysql_priv.h" +#include "rpl_rli.h" +#include "rpl_filter.h" +#include "rpl_record.h" +#include "slave.h" +#include +#include "log_event.h" +#include +#include +#include +#ifdef __WIN__ +#include +#endif +#include + +#include "sp_rcontext.h" +#include "sp_cache.h" + +/* + The following is used to initialise Table_ident with a internal + table name +*/ +char internal_table_name[2]= "*"; +char empty_c_string[1]= {0}; /* used for not defined db */ + +const char * const THD::DEFAULT_WHERE= "field list"; + + +/***************************************************************************** +** Instansiate templates +*****************************************************************************/ + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +/* Used templates */ +template class List; +template class List_iterator; +template class List; +template class List_iterator; +template class List; +template class List_iterator; +template class List; +template class List_iterator; +#endif + +/**************************************************************************** +** User variables +****************************************************************************/ + +extern "C" uchar *get_var_key(user_var_entry *entry, size_t *length, + my_bool not_used __attribute__((unused))) +{ + *length= entry->name.length; + return (uchar*) entry->name.str; +} + +extern "C" void free_user_var(user_var_entry *entry) +{ + char *pos= (char*) entry+ALIGN_SIZE(sizeof(*entry)); + if (entry->value && entry->value != pos) + my_free(entry->value, MYF(0)); + my_free((char*) entry,MYF(0)); +} + +bool Key_part_spec::operator==(const Key_part_spec& other) const +{ + return length == other.length && !strcmp(field_name, other.field_name); +} + +/** + Construct an (almost) deep copy of this key. Only those + elements that are known to never change are not copied. + If out of memory, a partial copy is returned and an error is set + in THD. +*/ + +Key::Key(const Key &rhs, MEM_ROOT *mem_root) + :type(rhs.type), + key_create_info(rhs.key_create_info), + columns(rhs.columns, mem_root), + name(rhs.name), + generated(rhs.generated) +{ + list_copy_and_replace_each_value(columns, mem_root); +} + +/** + Construct an (almost) deep copy of this foreign key. Only those + elements that are known to never change are not copied. + If out of memory, a partial copy is returned and an error is set + in THD. +*/ + +Foreign_key::Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root) + :Key(rhs), + ref_table(rhs.ref_table), + ref_columns(rhs.ref_columns), + delete_opt(rhs.delete_opt), + update_opt(rhs.update_opt), + match_opt(rhs.match_opt) +{ + list_copy_and_replace_each_value(ref_columns, mem_root); +} + +/* + Test if a foreign key (= generated key) is a prefix of the given key + (ignoring key name, key type and order of columns) + + NOTES: + This is only used to test if an index for a FOREIGN KEY exists + + IMPLEMENTATION + We only compare field names + + RETURN + 0 Generated key is a prefix of other key + 1 Not equal +*/ + +bool foreign_key_prefix(Key *a, Key *b) +{ + /* Ensure that 'a' is the generated key */ + if (a->generated) + { + if (b->generated && a->columns.elements > b->columns.elements) + swap_variables(Key*, a, b); // Put shorter key in 'a' + } + else + { + if (!b->generated) + return TRUE; // No foreign key + swap_variables(Key*, a, b); // Put generated key in 'a' + } + + /* Test if 'a' is a prefix of 'b' */ + if (a->columns.elements > b->columns.elements) + return TRUE; // Can't be prefix + + List_iterator col_it1(a->columns); + List_iterator col_it2(b->columns); + const Key_part_spec *col1, *col2; + +#ifdef ENABLE_WHEN_INNODB_CAN_HANDLE_SWAPED_FOREIGN_KEY_COLUMNS + while ((col1= col_it1++)) + { + bool found= 0; + col_it2.rewind(); + while ((col2= col_it2++)) + { + if (*col1 == *col2) + { + found= TRUE; + break; + } + } + if (!found) + return TRUE; // Error + } + return FALSE; // Is prefix +#else + while ((col1= col_it1++)) + { + col2= col_it2++; + if (!(*col1 == *col2)) + return TRUE; + } + return FALSE; // Is prefix +#endif +} + + +/**************************************************************************** +** Thread specific functions +****************************************************************************/ + +/** Push an error to the error stack and return TRUE for now. */ + +bool +Reprepare_observer::report_error(THD *thd) +{ + my_error(ER_NEED_REPREPARE, MYF(ME_NO_WARNING_FOR_ERROR|ME_NO_SP_HANDLER)); + + m_invalidated= TRUE; + + return TRUE; +} + + +Open_tables_state::Open_tables_state(ulong version_arg) + :version(version_arg), state_flags(0U) +{ + reset_open_tables_state(); +} + +/* + The following functions form part of the C plugin API +*/ + +extern "C" int mysql_tmpfile(const char *prefix) +{ + char filename[FN_REFLEN]; + File fd = create_temp_file(filename, mysql_tmpdir, prefix, +#ifdef __WIN__ + O_BINARY | O_TRUNC | O_SEQUENTIAL | + O_SHORT_LIVED | +#endif /* __WIN__ */ + O_CREAT | O_EXCL | O_RDWR | O_TEMPORARY, + MYF(MY_WME)); + if (fd >= 0) { +#ifndef __WIN__ + /* + This can be removed once the following bug is fixed: + Bug #28903 create_temp_file() doesn't honor O_TEMPORARY option + (file not removed) (Unix) + */ + unlink(filename); +#endif /* !__WIN__ */ + } + + return fd; +} + + +extern "C" +int thd_in_lock_tables(const THD *thd) +{ + return test(thd->in_lock_tables); +} + + +extern "C" +int thd_tablespace_op(const THD *thd) +{ + return test(thd->tablespace_op); +} + + +extern "C" +const char *set_thd_proc_info(THD *thd, const char *info, + const char *calling_function, + const char *calling_file, + const unsigned int calling_line) +{ + const char *old_info= thd->proc_info; + DBUG_PRINT("proc_info", ("%s:%d %s", calling_file, calling_line, + (info != NULL) ? info : "(null)")); +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.status_change(info, calling_function, calling_file, calling_line); +#endif + thd->proc_info= info; + return old_info; +} + +extern "C" +void **thd_ha_data(const THD *thd, const struct handlerton *hton) +{ + return (void **) &thd->ha_data[hton->slot].ha_ptr; +} + +extern "C" +long long thd_test_options(const THD *thd, long long test_options) +{ + return thd->options & test_options; +} + +extern "C" +int thd_sql_command(const THD *thd) +{ + return (int) thd->lex->sql_command; +} + +extern "C" +int thd_tx_isolation(const THD *thd) +{ + return (int) thd->variables.tx_isolation; +} + +extern "C" +void thd_inc_row_count(THD *thd) +{ + thd->row_count++; +} + + +/** + Dumps a text description of a thread, its security context + (user, host) and the current query. + + @param thd thread context + @param buffer pointer to preferred result buffer + @param length length of buffer + @param max_query_len how many chars of query to copy (0 for all) + + @req LOCK_thread_count + + @note LOCK_thread_count mutex is not necessary when the function is invoked on + the currently running thread (current_thd) or if the caller in some other + way guarantees that access to thd->query is serialized. + + @return Pointer to string +*/ + +extern "C" +char *thd_security_context(THD *thd, char *buffer, unsigned int length, + unsigned int max_query_len) +{ + String str(buffer, length, &my_charset_latin1); + const Security_context *sctx= &thd->main_security_ctx; + char header[64]; + int len; + /* + The pointers thd->query and thd->proc_info might change since they are + being modified concurrently. This is acceptable for proc_info since its + values doesn't have to very accurate and the memory it points to is static, + but we need to attempt a snapshot on the pointer values to avoid using NULL + values. The pointer to thd->query however, doesn't point to static memory + and has to be protected by LOCK_thread_count or risk pointing to + uninitialized memory. + */ + const char *proc_info= thd->proc_info; + + len= my_snprintf(header, sizeof(header), + "MySQL thread id %lu, query id %lu", + thd->thread_id, (ulong) thd->query_id); + str.length(0); + str.append(header, len); + + if (sctx->host) + { + str.append(' '); + str.append(sctx->host); + } + + if (sctx->ip) + { + str.append(' '); + str.append(sctx->ip); + } + + if (sctx->user) + { + str.append(' '); + str.append(sctx->user); + } + + if (proc_info) + { + str.append(' '); + str.append(proc_info); + } + + if (thd->query) + { + if (max_query_len < 1) + len= thd->query_length; + else + len= min(thd->query_length, max_query_len); + str.append('\n'); + str.append(thd->query, len); + } + if (str.c_ptr_safe() == buffer) + return buffer; + + /* + We have to copy the new string to the destination buffer because the string + was reallocated to a larger buffer to be able to fit. + */ + DBUG_ASSERT(buffer != NULL); + length= min(str.length(), length-1); + memcpy(buffer, str.c_ptr_quick(), length); + /* Make sure that the new string is null terminated */ + buffer[length]= '\0'; + return buffer; +} + +/** + Clear this diagnostics area. + + Normally called at the end of a statement. +*/ + +void +Diagnostics_area::reset_diagnostics_area() +{ +#ifdef DBUG_OFF + can_overwrite_status= FALSE; + /** Don't take chances in production */ + m_message[0]= '\0'; + m_sql_errno= 0; + m_server_status= 0; + m_affected_rows= 0; + m_last_insert_id= 0; + m_total_warn_count= 0; +#endif + is_sent= FALSE; + /** Tiny reset in debug mode to see garbage right away */ + m_status= DA_EMPTY; +} + + +/** + Set OK status -- ends commands that do not return a + result set, e.g. INSERT/UPDATE/DELETE. +*/ + +void +Diagnostics_area::set_ok_status(THD *thd, ha_rows affected_rows_arg, + ulonglong last_insert_id_arg, + const char *message_arg) +{ + DBUG_ASSERT(! is_set()); +#ifdef DBUG_OFF + /* + In production, refuse to overwrite an error or a custom response + with an OK packet. + */ + if (is_error() || is_disabled()) + return; +#endif + /** Only allowed to report success if has not yet reported an error */ + + m_server_status= thd->server_status; + m_total_warn_count= thd->total_warn_count; + m_affected_rows= affected_rows_arg; + m_last_insert_id= last_insert_id_arg; + if (message_arg) + strmake(m_message, message_arg, sizeof(m_message) - 1); + else + m_message[0]= '\0'; + m_status= DA_OK; +} + + +/** + Set EOF status. +*/ + +void +Diagnostics_area::set_eof_status(THD *thd) +{ + /** Only allowed to report eof if has not yet reported an error */ + + DBUG_ASSERT(! is_set()); +#ifdef DBUG_OFF + /* + In production, refuse to overwrite an error or a custom response + with an EOF packet. + */ + if (is_error() || is_disabled()) + return; +#endif + + m_server_status= thd->server_status; + /* + If inside a stored procedure, do not return the total + number of warnings, since they are not available to the client + anyway. + */ + m_total_warn_count= thd->spcont ? 0 : thd->total_warn_count; + + m_status= DA_EOF; +} + +/** + Set ERROR status. +*/ + +void +Diagnostics_area::set_error_status(THD *thd, uint sql_errno_arg, + const char *message_arg) +{ + /* + Only allowed to report error if has not yet reported a success + The only exception is when we flush the message to the client, + an error can happen during the flush. + */ + DBUG_ASSERT(! is_set() || can_overwrite_status); +#ifdef DBUG_OFF + /* + In production, refuse to overwrite a custom response with an + ERROR packet. + */ + if (is_disabled()) + return; +#endif + + m_sql_errno= sql_errno_arg; + strmake(m_message, message_arg, sizeof(m_message) - 1); + + m_status= DA_ERROR; +} + + +/** + Mark the diagnostics area as 'DISABLED'. + + This is used in rare cases when the COM_ command at hand sends a response + in a custom format. One example is the query cache, another is + COM_STMT_PREPARE. +*/ + +void +Diagnostics_area::disable_status() +{ + DBUG_ASSERT(! is_set()); + m_status= DA_DISABLED; +} + + +THD::THD() + :Statement(&main_lex, &main_mem_root, CONVENTIONAL_EXECUTION, + /* statement id */ 0), + Open_tables_state(refresh_version), rli_fake(0), + lock_id(&main_lock_id), + user_time(0), in_sub_stmt(0), + sql_log_bin_toplevel(false), + binlog_table_maps(0), binlog_flags(0UL), + table_map_for_update(0), + arg_of_last_insert_id_function(FALSE), + first_successful_insert_id_in_prev_stmt(0), + first_successful_insert_id_in_prev_stmt_for_binlog(0), + first_successful_insert_id_in_cur_stmt(0), + stmt_depends_on_first_successful_insert_id_in_prev_stmt(FALSE), + examined_row_count(0), + global_read_lock(0), + is_fatal_error(0), + transaction_rollback_request(0), + is_fatal_sub_stmt_error(0), + rand_used(0), + time_zone_used(0), + in_lock_tables(0), + bootstrap(0), + derived_tables_processing(FALSE), + spcont(NULL), + m_parser_state(NULL) +{ + ulong tmp; + + /* + Pass nominal parameters to init_alloc_root only to ensure that + the destructor works OK in case of an error. The main_mem_root + will be re-initialized in init_for_queries(). + */ + init_sql_alloc(&main_mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0); + stmt_arena= this; + thread_stack= 0; + catalog= (char*)"std"; // the only catalog we have for now + main_security_ctx.init(); + security_ctx= &main_security_ctx; + locked=some_tables_deleted=no_errors=password= 0; + query_start_used= 0; + count_cuted_fields= CHECK_FIELD_IGNORE; + killed= NOT_KILLED; + col_access=0; + is_slave_error= thread_specific_used= FALSE; + hash_clear(&handler_tables_hash); + tmp_table=0; + used_tables=0; + cuted_fields= sent_row_count= row_count= 0L; + limit_found_rows= 0; + row_count_func= -1; + statement_id_counter= 0UL; +#ifdef ERROR_INJECT_SUPPORT + error_inject_value= 0UL; +#endif + // Must be reset to handle error with THD's created for init of mysqld + lex->current_select= 0; + start_time=(time_t) 0; + start_utime= prior_thr_create_utime= 0L; + utime_after_lock= 0L; + current_linfo = 0; + slave_thread = 0; + bzero(&variables, sizeof(variables)); + thread_id= 0; + one_shot_set= 0; + file_id = 0; + query_id= 0; + query_name_consts= 0; + warn_id= 0; + db_charset= global_system_variables.collation_database; + bzero(ha_data, sizeof(ha_data)); + mysys_var=0; + binlog_evt_union.do_union= FALSE; + enable_slow_log= 0; +#ifndef DBUG_OFF + dbug_sentry=THD_SENTRY_MAGIC; +#endif +#ifndef EMBEDDED_LIBRARY + net.vio=0; +#endif + client_capabilities= 0; // minimalistic client +#ifdef HAVE_QUERY_CACHE + query_cache_init_query(&net); // If error on boot +#endif + ull=0; + system_thread= NON_SYSTEM_THREAD; + cleanup_done= abort_on_warning= no_warnings_for_error= 0; + peer_port= 0; // For SHOW PROCESSLIST + transaction.m_pending_rows_event= 0; + transaction.on= 1; +#ifdef SIGNAL_WITH_VIO_CLOSE + active_vio = 0; +#endif + pthread_mutex_init(&LOCK_thd_data, MY_MUTEX_INIT_FAST); + + /* Variables with default values */ + proc_info="login"; + where= THD::DEFAULT_WHERE; + server_id = ::server_id; + slave_net = 0; + command=COM_CONNECT; + *scramble= '\0'; + + init(); + /* Initialize sub structures */ + init_sql_alloc(&warn_root, WARN_ALLOC_BLOCK_SIZE, WARN_ALLOC_PREALLOC_SIZE); +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + profiling.set_thd(this); +#endif + user_connect=(USER_CONN *)0; + hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0, + (hash_get_key) get_var_key, + (hash_free_key) free_user_var, 0); + + sp_proc_cache= NULL; + sp_func_cache= NULL; + + /* For user vars replication*/ + if (opt_bin_log) + my_init_dynamic_array(&user_var_events, + sizeof(BINLOG_USER_VAR_EVENT *), 16, 16); + else + bzero((char*) &user_var_events, sizeof(user_var_events)); + + /* Protocol */ + protocol= &protocol_text; // Default protocol + protocol_text.init(this); + protocol_binary.init(this); + + tablespace_op=FALSE; + tmp= sql_rnd_with_mutex(); + randominit(&rand, tmp + (ulong) &rand, tmp + (ulong) ::global_query_id); + substitute_null_with_insert_id = FALSE; + thr_lock_info_init(&lock_info); /* safety: will be reset after start */ + thr_lock_owner_init(&main_lock_id, &lock_info); + + m_internal_handler= NULL; + + // ------------------------------ Calpont InfiniDB ------------------------------ + infinidb_vtable.vtable_state = INFINIDB_INIT; + infinidb_vtable.has_order_by = false; + infinidb_vtable.mysql_optimizer_off = false; + infinidb_vtable.duplicate_field_name = false; + infinidb_vtable.autoswitch = false; + if (variables.infinidb_vtable_mode == 0) + infinidb_vtable.vtable_state = INFINIDB_DISABLE_VTABLE; + else if (variables.infinidb_vtable_mode == 2) + infinidb_vtable.autoswitch = true; + infinidb_vtable.call_sp = false; + infinidb_vtable.override_largeside_estimate = false; + infinidb_vtable.cal_conn_info = 0; + infinidb_vtable.isUnion = false; + infinidb_vtable.impossibleWhereOnUnion = false; + infinidb_vtable.isUpdateWithDerive = false; + infinidb_vtable.isInfiniDBDML = false; + // ------------------------------ Calpont InfiniDB ------------------------------ +} + + +void THD::push_internal_handler(Internal_error_handler *handler) +{ + if (m_internal_handler) + { + handler->m_prev_internal_handler= m_internal_handler; + m_internal_handler= handler; + } + else + { + m_internal_handler= handler; + } +} + + +bool THD::handle_error(uint sql_errno, const char *message, + MYSQL_ERROR::enum_warning_level level) +{ + if (!m_internal_handler) + return FALSE; + + for (Internal_error_handler *error_handler= m_internal_handler; + error_handler; + error_handler= m_internal_handler->m_prev_internal_handler) + { + if (error_handler->handle_error(sql_errno, message, level, this)) + return TRUE; + } + + return FALSE; +} + + +void THD::pop_internal_handler() +{ + DBUG_ASSERT(m_internal_handler != NULL); + m_internal_handler= m_internal_handler->m_prev_internal_handler; +} + +extern "C" +void *thd_alloc(MYSQL_THD thd, unsigned int size) +{ + return thd->alloc(size); +} + +extern "C" +void *thd_calloc(MYSQL_THD thd, unsigned int size) +{ + return thd->calloc(size); +} + +extern "C" +char *thd_strdup(MYSQL_THD thd, const char *str) +{ + return thd->strdup(str); +} + +extern "C" +char *thd_strmake(MYSQL_THD thd, const char *str, unsigned int size) +{ + return thd->strmake(str, size); +} + +extern "C" +LEX_STRING *thd_make_lex_string(THD *thd, LEX_STRING *lex_str, + const char *str, unsigned int size, + int allocate_lex_string) +{ + return thd->make_lex_string(lex_str, str, size, + (bool) allocate_lex_string); +} + +extern "C" +void *thd_memdup(MYSQL_THD thd, const void* str, unsigned int size) +{ + return thd->memdup(str, size); +} + +extern "C" +void thd_get_xid(const MYSQL_THD thd, MYSQL_XID *xid) +{ + *xid = *(MYSQL_XID *) &thd->transaction.xid_state.xid; +} + +#ifdef _WIN32 +extern "C" THD *_current_thd_noinline(void) +{ + return my_pthread_getspecific_ptr(THD*,THR_THD); +} +#endif +/* + Init common variables that has to be reset on start and on change_user +*/ + +void THD::init(void) +{ + pthread_mutex_lock(&LOCK_global_system_variables); + plugin_thdvar_init(this); + variables.time_format= date_time_format_copy((THD*) 0, + variables.time_format); + variables.date_format= date_time_format_copy((THD*) 0, + variables.date_format); + variables.datetime_format= date_time_format_copy((THD*) 0, + variables.datetime_format); + /* + variables= global_system_variables above has reset + variables.pseudo_thread_id to 0. We need to correct it here to + avoid temporary tables replication failure. + */ + variables.pseudo_thread_id= thread_id; + pthread_mutex_unlock(&LOCK_global_system_variables); + server_status= SERVER_STATUS_AUTOCOMMIT; + if (variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) + server_status|= SERVER_STATUS_NO_BACKSLASH_ESCAPES; + options= thd_startup_options; + + if (variables.max_join_size == HA_POS_ERROR) + options |= OPTION_BIG_SELECTS; + else + options &= ~OPTION_BIG_SELECTS; + + transaction.all.modified_non_trans_table= transaction.stmt.modified_non_trans_table= FALSE; + open_options=ha_open_options; + update_lock_default= (variables.low_priority_updates ? + TL_WRITE_LOW_PRIORITY : + TL_WRITE); + session_tx_isolation= (enum_tx_isolation) variables.tx_isolation; + warn_list.empty(); + bzero((char*) warn_count, sizeof(warn_count)); + total_warn_count= 0; + update_charset(); + reset_current_stmt_binlog_row_based(); + bzero((char *) &status_var, sizeof(status_var)); + sql_log_bin_toplevel= options & OPTION_BIN_LOG; +} + + +/* + Init THD for query processing. + This has to be called once before we call mysql_parse. + See also comments in sql_class.h. +*/ + +void THD::init_for_queries() +{ + set_time(); + ha_enable_transaction(this,TRUE); + + reset_root_defaults(mem_root, variables.query_alloc_block_size, + variables.query_prealloc_size); +#ifdef USING_TRANSACTIONS + reset_root_defaults(&transaction.mem_root, + variables.trans_alloc_block_size, + variables.trans_prealloc_size); +#endif + transaction.xid_state.xid.null(); + transaction.xid_state.in_thd=1; +} + + +/* + Do what's needed when one invokes change user + + SYNOPSIS + change_user() + + IMPLEMENTATION + Reset all resources that are connection specific +*/ + + +void THD::change_user(void) +{ + pthread_mutex_lock(&LOCK_status); + add_to_status(&global_status_var, &status_var); + pthread_mutex_unlock(&LOCK_status); + + cleanup(); + killed= NOT_KILLED; + cleanup_done= 0; + init(); + stmt_map.reset(); + hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0, + (hash_get_key) get_var_key, + (hash_free_key) free_user_var, 0); + sp_cache_clear(&sp_proc_cache); + sp_cache_clear(&sp_func_cache); +} + + +/* Do operations that may take a long time */ + +void THD::cleanup(void) +{ + DBUG_ENTER("THD::cleanup"); + DBUG_ASSERT(cleanup_done == 0); + + killed= KILL_CONNECTION; +#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE + if (transaction.xid_state.xa_state == XA_PREPARED) + { +#error xid_state in the cache should be replaced by the allocated value + } +#endif + { + ha_rollback(this); + xid_cache_delete(&transaction.xid_state); + } + if (locked_tables) + { + lock=locked_tables; locked_tables=0; + close_thread_tables(this); + } + mysql_ha_cleanup(this); + delete_dynamic(&user_var_events); + hash_free(&user_vars); + close_temporary_tables(this); + my_free((char*) variables.time_format, MYF(MY_ALLOW_ZERO_PTR)); + my_free((char*) variables.date_format, MYF(MY_ALLOW_ZERO_PTR)); + my_free((char*) variables.datetime_format, MYF(MY_ALLOW_ZERO_PTR)); + + sp_cache_clear(&sp_proc_cache); + sp_cache_clear(&sp_func_cache); + + if (global_read_lock) + unlock_global_read_lock(this); + if (ull) + { + pthread_mutex_lock(&LOCK_user_locks); + item_user_lock_release(ull); + pthread_mutex_unlock(&LOCK_user_locks); + ull= NULL; + } + + cleanup_done=1; + DBUG_VOID_RETURN; +} + + +THD::~THD() +{ + THD_CHECK_SENTRY(this); + DBUG_ENTER("~THD()"); + /* Ensure that no one is using THD */ + pthread_mutex_lock(&LOCK_thd_data); + pthread_mutex_unlock(&LOCK_thd_data); + add_to_status(&global_status_var, &status_var); + + /* Close connection */ +#ifndef EMBEDDED_LIBRARY + if (net.vio) + { + vio_delete(net.vio); + net_end(&net); + } +#endif + stmt_map.reset(); /* close all prepared statements */ + DBUG_ASSERT(lock_info.n_cursors == 0); + if (!cleanup_done) + cleanup(); + + ha_close_connection(this); + plugin_thdvar_cleanup(this); + + DBUG_PRINT("info", ("freeing security context")); + main_security_ctx.destroy(); + safeFree(db); + free_root(&warn_root,MYF(0)); +#ifdef USING_TRANSACTIONS + free_root(&transaction.mem_root,MYF(0)); +#endif + mysys_var=0; // Safety (shouldn't be needed) + pthread_mutex_destroy(&LOCK_thd_data); +#ifndef DBUG_OFF + dbug_sentry= THD_SENTRY_GONE; +#endif +#ifndef EMBEDDED_LIBRARY + if (rli_fake) + { + delete rli_fake; + rli_fake= NULL; + } +#endif + + free_root(&main_mem_root, MYF(0)); + DBUG_VOID_RETURN; +} + + +/* + Add all status variables to another status variable array + + SYNOPSIS + add_to_status() + to_var add to this array + from_var from this array + + NOTES + This function assumes that all variables are long/ulong. + If this assumption will change, then we have to explictely add + the other variables after the while loop +*/ + +void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var) +{ + ulong *end= (ulong*) ((uchar*) to_var + + offsetof(STATUS_VAR, last_system_status_var) + + sizeof(ulong)); + ulong *to= (ulong*) to_var, *from= (ulong*) from_var; + + while (to != end) + *(to++)+= *(from++); +} + +/* + Add the difference between two status variable arrays to another one. + + SYNOPSIS + add_diff_to_status + to_var add to this array + from_var from this array + dec_var minus this array + + NOTE + This function assumes that all variables are long/ulong. +*/ + +void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var, + STATUS_VAR *dec_var) +{ + ulong *end= (ulong*) ((uchar*) to_var + offsetof(STATUS_VAR, + last_system_status_var) + + sizeof(ulong)); + ulong *to= (ulong*) to_var, *from= (ulong*) from_var, *dec= (ulong*) dec_var; + + while (to != end) + *(to++)+= *(from++) - *(dec++); +} + + +void THD::awake(THD::killed_state state_to_set) +{ + DBUG_ENTER("THD::awake"); + DBUG_PRINT("enter", ("this: 0x%lx", (long) this)); + THD_CHECK_SENTRY(this); + safe_mutex_assert_owner(&LOCK_thd_data); + + killed= state_to_set; + if (state_to_set != THD::KILL_QUERY) + { + thr_alarm_kill(thread_id); + if (!slave_thread) + thread_scheduler.post_kill_notification(this); +#ifdef SIGNAL_WITH_VIO_CLOSE + if (this != current_thd) + { + /* + In addition to a signal, let's close the socket of the thread that + is being killed. This is to make sure it does not block if the + signal is lost. This needs to be done only on platforms where + signals are not a reliable interruption mechanism. + + If we're killing ourselves, we know that we're not blocked, so this + hack is not used. + */ + + close_active_vio(); + } +#endif + } + if (mysys_var) + { + pthread_mutex_lock(&mysys_var->mutex); + if (!system_thread) // Don't abort locks + mysys_var->abort=1; + /* + This broadcast could be up in the air if the victim thread + exits the cond in the time between read and broadcast, but that is + ok since all we want to do is to make the victim thread get out + of waiting on current_cond. + If we see a non-zero current_cond: it cannot be an old value (because + then exit_cond() should have run and it can't because we have mutex); so + it is the true value but maybe current_mutex is not yet non-zero (we're + in the middle of enter_cond() and there is a "memory order + inversion"). So we test the mutex too to not lock 0. + + Note that there is a small chance we fail to kill. If victim has locked + current_mutex, but hasn't yet entered enter_cond() (which means that + current_cond and current_mutex are 0), then the victim will not get + a signal and it may wait "forever" on the cond (until + we issue a second KILL or the status it's waiting for happens). + It's true that we have set its thd->killed but it may not + see it immediately and so may have time to reach the cond_wait(). + */ + if (mysys_var->current_cond && mysys_var->current_mutex) + { + pthread_mutex_lock(mysys_var->current_mutex); + pthread_cond_broadcast(mysys_var->current_cond); + pthread_mutex_unlock(mysys_var->current_mutex); + } + pthread_mutex_unlock(&mysys_var->mutex); + } + DBUG_VOID_RETURN; +} + +/* + Remember the location of thread info, the structure needed for + sql_alloc() and the structure for the net buffer +*/ + +bool THD::store_globals() +{ + /* + Assert that thread_stack is initialized: it's necessary to be able + to track stack overrun. + */ + DBUG_ASSERT(thread_stack); + + if (my_pthread_setspecific_ptr(THR_THD, this) || + my_pthread_setspecific_ptr(THR_MALLOC, &mem_root)) + return 1; + mysys_var=my_thread_var; + /* + Let mysqld define the thread id (not mysys) + This allows us to move THD to different threads if needed. + */ + mysys_var->id= thread_id; + real_id= pthread_self(); // For debugging + + /* + We have to call thr_lock_info_init() again here as THD may have been + created in another thread + */ + thr_lock_info_init(&lock_info); + return 0; +} + + +/* + Cleanup after query. + + SYNOPSIS + THD::cleanup_after_query() + + DESCRIPTION + This function is used to reset thread data to its default state. + + NOTE + This function is not suitable for setting thread data to some + non-default values, as there is only one replication thread, so + different master threads may overwrite data of each other on + slave. +*/ + +void THD::cleanup_after_query() +{ + /* + Reset rand_used so that detection of calls to rand() will save random + seeds if needed by the slave. + + Do not reset rand_used if inside a stored function or trigger because + only the call to these operations is logged. Thus only the calling + statement needs to detect rand() calls made by its substatements. These + substatements must not set rand_used to 0 because it would remove the + detection of rand() by the calling statement. + */ + if (!in_sub_stmt) /* stored functions and triggers are a special case */ + { + /* Forget those values, for next binlogger: */ + stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0; + auto_inc_intervals_in_cur_stmt_for_binlog.empty(); + rand_used= 0; + } + if (first_successful_insert_id_in_cur_stmt > 0) + { + /* set what LAST_INSERT_ID() will return */ + first_successful_insert_id_in_prev_stmt= + first_successful_insert_id_in_cur_stmt; + first_successful_insert_id_in_cur_stmt= 0; + substitute_null_with_insert_id= TRUE; + } + arg_of_last_insert_id_function= 0; + /* Free Items that were created during this execution */ + free_items(); + /* Reset where. */ + where= THD::DEFAULT_WHERE; + /* reset table map for multi-table update */ + table_map_for_update= 0; +} + + +/** + Create a LEX_STRING in this connection. + + @param lex_str pointer to LEX_STRING object to be initialized + @param str initializer to be copied into lex_str + @param length length of str, in bytes + @param allocate_lex_string if TRUE, allocate new LEX_STRING object, + instead of using lex_str value + @return NULL on failure, or pointer to the LEX_STRING object +*/ +LEX_STRING *THD::make_lex_string(LEX_STRING *lex_str, + const char* str, uint length, + bool allocate_lex_string) +{ + if (allocate_lex_string) + if (!(lex_str= (LEX_STRING *)alloc(sizeof(LEX_STRING)))) + return 0; + if (!(lex_str->str= strmake_root(mem_root, str, length))) + return 0; + lex_str->length= length; + return lex_str; +} + + +/* + Convert a string to another character set + + SYNOPSIS + convert_string() + to Store new allocated string here + to_cs New character set for allocated string + from String to convert + from_length Length of string to convert + from_cs Original character set + + NOTES + to will be 0-terminated to make it easy to pass to system funcs + + RETURN + 0 ok + 1 End of memory. + In this case to->str will point to 0 and to->length will be 0. +*/ + +bool THD::convert_string(LEX_STRING *to, CHARSET_INFO *to_cs, + const char *from, uint from_length, + CHARSET_INFO *from_cs) +{ + DBUG_ENTER("convert_string"); + size_t new_length= to_cs->mbmaxlen * from_length; + uint dummy_errors; + if (!(to->str= (char*) alloc(new_length+1))) + { + to->length= 0; // Safety fix + DBUG_RETURN(1); // EOM + } + to->length= copy_and_convert((char*) to->str, new_length, to_cs, + from, from_length, from_cs, &dummy_errors); + to->str[to->length]=0; // Safety + DBUG_RETURN(0); +} + + +/* + Convert string from source character set to target character set inplace. + + SYNOPSIS + THD::convert_string + + DESCRIPTION + Convert string using convert_buffer - buffer for character set + conversion shared between all protocols. + + RETURN + 0 ok + !0 out of memory +*/ + +bool THD::convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs) +{ + uint dummy_errors; + if (convert_buffer.copy(s->ptr(), s->length(), from_cs, to_cs, &dummy_errors)) + return TRUE; + /* If convert_buffer >> s copying is more efficient long term */ + if (convert_buffer.alloced_length() >= convert_buffer.length() * 2 || + !s->is_alloced()) + { + return s->copy(convert_buffer); + } + s->swap(convert_buffer); + return FALSE; +} + + +/* + Update some cache variables when character set changes +*/ + +void THD::update_charset() +{ + uint32 not_used; + charset_is_system_charset= !String::needs_conversion(0,charset(), + system_charset_info, + ¬_used); + charset_is_collation_connection= + !String::needs_conversion(0,charset(),variables.collation_connection, + ¬_used); + charset_is_character_set_filesystem= + !String::needs_conversion(0, charset(), + variables.character_set_filesystem, ¬_used); +} + + +/* routings to adding tables to list of changed in transaction tables */ + +inline static void list_include(CHANGED_TABLE_LIST** prev, + CHANGED_TABLE_LIST* curr, + CHANGED_TABLE_LIST* new_table) +{ + if (new_table) + { + *prev = new_table; + (*prev)->next = curr; + } +} + +/* add table to list of changed in transaction tables */ + +void THD::add_changed_table(TABLE *table) +{ + DBUG_ENTER("THD::add_changed_table(table)"); + + DBUG_ASSERT((options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) && + table->file->has_transactions()); + add_changed_table(table->s->table_cache_key.str, + (long) table->s->table_cache_key.length); + DBUG_VOID_RETURN; +} + + +void THD::add_changed_table(const char *key, long key_length) +{ + DBUG_ENTER("THD::add_changed_table(key)"); + CHANGED_TABLE_LIST **prev_changed = &transaction.changed_tables; + CHANGED_TABLE_LIST *curr = transaction.changed_tables; + + for (; curr; prev_changed = &(curr->next), curr = curr->next) + { + int cmp = (long)curr->key_length - (long)key_length; + if (cmp < 0) + { + list_include(prev_changed, curr, changed_table_dup(key, key_length)); + DBUG_PRINT("info", + ("key_length: %ld %u", key_length, + (*prev_changed)->key_length)); + DBUG_VOID_RETURN; + } + else if (cmp == 0) + { + cmp = memcmp(curr->key, key, curr->key_length); + if (cmp < 0) + { + list_include(prev_changed, curr, changed_table_dup(key, key_length)); + DBUG_PRINT("info", + ("key_length: %ld %u", key_length, + (*prev_changed)->key_length)); + DBUG_VOID_RETURN; + } + else if (cmp == 0) + { + DBUG_PRINT("info", ("already in list")); + DBUG_VOID_RETURN; + } + } + } + *prev_changed = changed_table_dup(key, key_length); + DBUG_PRINT("info", ("key_length: %ld %u", key_length, + (*prev_changed)->key_length)); + DBUG_VOID_RETURN; +} + + +CHANGED_TABLE_LIST* THD::changed_table_dup(const char *key, long key_length) +{ + CHANGED_TABLE_LIST* new_table = + (CHANGED_TABLE_LIST*) trans_alloc(ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST))+ + key_length + 1); + if (!new_table) + { + my_error(EE_OUTOFMEMORY, MYF(ME_BELL), + ALIGN_SIZE(sizeof(TABLE_LIST)) + key_length + 1); + killed= KILL_CONNECTION; + return 0; + } + + new_table->key= ((char*)new_table)+ ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST)); + new_table->next = 0; + new_table->key_length = key_length; + ::memcpy(new_table->key, key, key_length); + return new_table; +} + + +int THD::send_explain_fields(select_result *result) +{ + List field_list; + Item *item; + CHARSET_INFO *cs= system_charset_info; + field_list.push_back(new Item_return_int("id",3, MYSQL_TYPE_LONGLONG)); + field_list.push_back(new Item_empty_string("select_type", 19, cs)); + field_list.push_back(item= new Item_empty_string("table", NAME_CHAR_LEN, cs)); + item->maybe_null= 1; + if (lex->describe & DESCRIBE_PARTITIONS) + { + /* Maximum length of string that make_used_partitions_str() can produce */ + item= new Item_empty_string("partitions", MAX_PARTITIONS * (1 + FN_LEN), + cs); + field_list.push_back(item); + item->maybe_null= 1; + } + field_list.push_back(item= new Item_empty_string("type", 10, cs)); + item->maybe_null= 1; + field_list.push_back(item=new Item_empty_string("possible_keys", + NAME_CHAR_LEN*MAX_KEY, cs)); + item->maybe_null=1; + field_list.push_back(item=new Item_empty_string("key", NAME_CHAR_LEN, cs)); + item->maybe_null=1; + field_list.push_back(item=new Item_empty_string("key_len", + NAME_CHAR_LEN*MAX_KEY)); + item->maybe_null=1; + field_list.push_back(item=new Item_empty_string("ref", + NAME_CHAR_LEN*MAX_REF_PARTS, + cs)); + item->maybe_null=1; + field_list.push_back(item= new Item_return_int("rows", 10, + MYSQL_TYPE_LONGLONG)); + if (lex->describe & DESCRIBE_EXTENDED) + { + field_list.push_back(item= new Item_float("filtered", 0.1234, 2, 4)); + item->maybe_null=1; + } + item->maybe_null= 1; + field_list.push_back(new Item_empty_string("Extra", 255, cs)); + return (result->send_fields(field_list, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)); +} + +#ifdef SIGNAL_WITH_VIO_CLOSE +void THD::close_active_vio() +{ + DBUG_ENTER("close_active_vio"); + safe_mutex_assert_owner(&LOCK_thd_data); +#ifndef EMBEDDED_LIBRARY + if (active_vio) + { + vio_close(active_vio); + active_vio = 0; + } +#endif + DBUG_VOID_RETURN; +} +#endif + + +struct Item_change_record: public ilink +{ + Item **place; + Item *old_value; + /* Placement new was hidden by `new' in ilink (TODO: check): */ + static void *operator new(size_t size, void *mem) { return mem; } + static void operator delete(void *ptr, size_t size) {} + static void operator delete(void *ptr, void *mem) { /* never called */ } +}; + + +/* + Register an item tree tree transformation, performed by the query + optimizer. We need a pointer to runtime_memroot because it may be != + thd->mem_root (due to possible set_n_backup_active_arena called for thd). +*/ + +void THD::nocheck_register_item_tree_change(Item **place, Item *old_value, + MEM_ROOT *runtime_memroot) +{ + Item_change_record *change; + /* + Now we use one node per change, which adds some memory overhead, + but still is rather fast as we use alloc_root for allocations. + A list of item tree changes of an average query should be short. + */ + void *change_mem= alloc_root(runtime_memroot, sizeof(*change)); + if (change_mem == 0) + { + /* + OOM, thd->fatal_error() is called by the error handler of the + memroot. Just return. + */ + return; + } + change= new (change_mem) Item_change_record; + change->place= place; + change->old_value= old_value; + change_list.append(change); +} + + +void THD::rollback_item_tree_changes() +{ + I_List_iterator it(change_list); + Item_change_record *change; + DBUG_ENTER("rollback_item_tree_changes"); + + while ((change= it++)) + *change->place= change->old_value; + /* We can forget about changes memory: it's allocated in runtime memroot */ + change_list.empty(); + DBUG_VOID_RETURN; +} + + +/***************************************************************************** +** Functions to provide a interface to select results +*****************************************************************************/ + +select_result::select_result() +{ + thd=current_thd; + nest_level= -1; +} + +void select_result::send_error(uint errcode,const char *err) +{ + my_message(errcode, err, MYF(0)); +} + + +void select_result::cleanup() +{ + /* do nothing */ +} + +bool select_result::check_simple_select() const +{ + my_error(ER_SP_BAD_CURSOR_QUERY, MYF(0)); + return TRUE; +} + + +static String default_line_term("\n",default_charset_info); +static String default_escaped("\\",default_charset_info); +static String default_field_term("\t",default_charset_info); + +sql_exchange::sql_exchange(char *name,bool flag) + :file_name(name), opt_enclosed(0), dumpfile(flag), skip_lines(0) +{ + field_term= &default_field_term; + enclosed= line_start= &my_empty_string; + line_term= &default_line_term; + escaped= &default_escaped; + cs= NULL; +} + +bool sql_exchange::escaped_given(void) +{ + return escaped != &default_escaped; +} + + +bool select_send::send_fields(List &list, uint flags) +{ + bool res; + if (!(res= thd->protocol->send_fields(&list, flags))) + is_result_set_started= 1; + return res; +} + +void select_send::abort() +{ + DBUG_ENTER("select_send::abort"); + if (is_result_set_started && thd->spcont && + thd->spcont->find_handler(thd, thd->main_da.sql_errno(), + MYSQL_ERROR::WARN_LEVEL_ERROR)) + { + /* + We're executing a stored procedure, have an open result + set, an SQL exception condition and a handler for it. + In this situation we must abort the current statement, + silence the error and start executing the continue/exit + handler. + Before aborting the statement, let's end the open result set, as + otherwise the client will hang due to the violation of the + client/server protocol. + */ + thd->protocol->end_partial_result_set(thd); + } + DBUG_VOID_RETURN; +} + + +/** + Cleanup an instance of this class for re-use + at next execution of a prepared statement/ + stored procedure statement. +*/ + +void select_send::cleanup() +{ + is_result_set_started= FALSE; +} + +/* Send data to client. Returns 0 if ok */ + +bool select_send::send_data(List &items) +{ + if (unit->offset_limit_cnt) + { // using limit offset,count + unit->offset_limit_cnt--; + return 0; + } + + /* + We may be passing the control from mysqld to the client: release the + InnoDB adaptive hash S-latch to avoid thread deadlocks if it was reserved + by thd + */ + ha_release_temporary_latches(thd); + + List_iterator_fast li(items); + Protocol *protocol= thd->protocol; + char buff[MAX_FIELD_WIDTH]; + String buffer(buff, sizeof(buff), &my_charset_bin); + DBUG_ENTER("select_send::send_data"); + + protocol->prepare_for_resend(); + Item *item; + while ((item=li++)) + { + if (item->send(protocol, &buffer)) + { + protocol->free(); // Free used buffer + my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0)); + break; + } + /* + Reset buffer to its original state, as it may have been altered in + Item::send(). + */ + buffer.set(buff, sizeof(buff), &my_charset_bin); + } + thd->sent_row_count++; + if (thd->is_error()) + { + protocol->remove_last_row(); + DBUG_RETURN(1); + } + if (thd->vio_ok()) + DBUG_RETURN(protocol->write()); + DBUG_RETURN(0); +} + +bool select_send::send_eof() +{ + /* + We may be passing the control from mysqld to the client: release the + InnoDB adaptive hash S-latch to avoid thread deadlocks if it was reserved + by thd + */ + ha_release_temporary_latches(thd); + + /* Unlock tables before sending packet to gain some speed */ + if (thd->lock) + { + mysql_unlock_tables(thd, thd->lock); + thd->lock=0; + } + /* + Don't send EOF if we're in error condition (which implies we've already + sent or are sending an error) + */ + if (thd->is_error()) + return TRUE; + ::my_eof(thd); + is_result_set_started= 0; + return FALSE; +} + + +/************************************************************************ + Handling writing to file +************************************************************************/ + +void select_to_file::send_error(uint errcode,const char *err) +{ + my_message(errcode, err, MYF(0)); + if (file > 0) + { + (void) end_io_cache(&cache); + (void) my_close(file,MYF(0)); + (void) my_delete(path,MYF(0)); // Delete file on error + file= -1; + } +} + + +bool select_to_file::send_eof() +{ + int error= test(end_io_cache(&cache)); + if (my_close(file,MYF(MY_WME))) + error= 1; + if (!error) + { + /* + In order to remember the value of affected rows for ROW_COUNT() + function, SELECT INTO has to have an own SQLCOM. + TODO: split from SQLCOM_SELECT + */ + ::my_ok(thd,row_count); + } + file= -1; + return error; +} + + +void select_to_file::cleanup() +{ + /* In case of error send_eof() may be not called: close the file here. */ + if (file >= 0) + { + (void) end_io_cache(&cache); + (void) my_close(file,MYF(0)); + file= -1; + } + path[0]= '\0'; + row_count= 0; +} + + +select_to_file::~select_to_file() +{ + if (file >= 0) + { // This only happens in case of error + (void) end_io_cache(&cache); + (void) my_close(file,MYF(0)); + file= -1; + } +} + +/*************************************************************************** +** Export of select to textfile +***************************************************************************/ + +select_export::~select_export() +{ + thd->sent_row_count=row_count; +} + + +/* + Create file with IO cache + + SYNOPSIS + create_file() + thd Thread handle + path File name + exchange Excange class + cache IO cache + + RETURN + >= 0 File handle + -1 Error +*/ + + +static File create_file(THD *thd, char *path, sql_exchange *exchange, + IO_CACHE *cache) +{ + File file; + uint option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH; + +#ifdef DONT_ALLOW_FULL_LOAD_DATA_PATHS + option|= MY_REPLACE_DIR; // Force use of db directory +#endif + + if (!dirname_length(exchange->file_name)) + { + strxnmov(path, FN_REFLEN-1, mysql_real_data_home, thd->db ? thd->db : "", + NullS); + (void) fn_format(path, exchange->file_name, path, "", option); + } + else + (void) fn_format(path, exchange->file_name, mysql_real_data_home, "", option); + + if (opt_secure_file_priv && + strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv))) + { + /* Write only allowed to dir or subdir specified by secure_file_priv */ + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv"); + return -1; + } + + if (!access(path, F_OK)) + { + my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name); + return -1; + } + /* Create the file world readable */ + if ((file= my_create(path, 0666, O_WRONLY|O_EXCL, MYF(MY_WME))) < 0) + return file; +#ifdef HAVE_FCHMOD + (void) fchmod(file, 0666); // Because of umask() +#else + (void) chmod(path, 0666); +#endif + if (init_io_cache(cache, file, 0L, WRITE_CACHE, 0L, 1, MYF(MY_WME))) + { + my_close(file, MYF(0)); + my_delete(path, MYF(0)); // Delete file on error, it was just created + return -1; + } + return file; +} + + +int +select_export::prepare(List &list, SELECT_LEX_UNIT *u) +{ + bool blob_flag=0; + bool string_results= FALSE, non_string_results= FALSE; + unit= u; + if ((uint) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN) + strmake(path,exchange->file_name,FN_REFLEN-1); + + write_cs= exchange->cs ? exchange->cs : &my_charset_bin; + + if ((file= create_file(thd, path, exchange, &cache)) < 0) + return 1; + /* Check if there is any blobs in data */ + { + List_iterator_fast li(list); + Item *item; + while ((item=li++)) + { + if (item->max_length >= MAX_BLOB_WIDTH) + { + blob_flag=1; + break; + } + if (item->result_type() == STRING_RESULT) + string_results= TRUE; + else + non_string_results= TRUE; + } + } + if (exchange->escaped->numchars() > 1 || exchange->enclosed->numchars() > 1) + { + my_error(ER_WRONG_FIELD_TERMINATORS, MYF(0)); + return TRUE; + } + if (exchange->escaped->length() > 1 || exchange->enclosed->length() > 1 || + !my_isascii(exchange->escaped->ptr()[0]) || + !my_isascii(exchange->enclosed->ptr()[0]) || + !exchange->field_term->is_ascii() || !exchange->line_term->is_ascii() || + !exchange->line_start->is_ascii()) + { + /* + Current LOAD DATA INFILE recognizes field/line separators "as is" without + converting from client charset to data file charset. So, it is supposed, + that input file of LOAD DATA INFILE consists of data in one charset and + separators in other charset. For the compatibility with that [buggy] + behaviour SELECT INTO OUTFILE implementation has been saved "as is" too, + but the new warning message has been added: + + Non-ASCII separator arguments are not fully supported + */ + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED, + ER(WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED)); + } + field_term_length=exchange->field_term->length(); + field_term_char= field_term_length ? + (int) (uchar) (*exchange->field_term)[0] : INT_MAX; + if (!exchange->line_term->length()) + exchange->line_term=exchange->field_term; // Use this if it exists + field_sep_char= (exchange->enclosed->length() ? + (int) (uchar) (*exchange->enclosed)[0] : field_term_char); + if (exchange->escaped->length() && (exchange->escaped_given() || + !(thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))) + escape_char= (int) (uchar) (*exchange->escaped)[0]; + else + escape_char= -1; + is_ambiguous_field_sep= test(strchr(ESCAPE_CHARS, field_sep_char)); + is_unsafe_field_sep= test(strchr(NUMERIC_CHARS, field_sep_char)); + line_sep_char= (exchange->line_term->length() ? + (int) (uchar) (*exchange->line_term)[0] : INT_MAX); + if (!field_term_length) + exchange->opt_enclosed=0; + if (!exchange->enclosed->length()) + exchange->opt_enclosed=1; // A little quicker loop + fixed_row_size= (!field_term_length && !exchange->enclosed->length() && + !blob_flag); + if ((is_ambiguous_field_sep && exchange->enclosed->is_empty() && + (string_results || is_unsafe_field_sep)) || + (exchange->opt_enclosed && non_string_results && + field_term_length && strchr(NUMERIC_CHARS, field_term_char))) + { + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_AMBIGUOUS_FIELD_TERM, ER(ER_AMBIGUOUS_FIELD_TERM)); + is_ambiguous_field_term= TRUE; + } + else + is_ambiguous_field_term= FALSE; + + return 0; +} + + +#define NEED_ESCAPING(x) ((int) (uchar) (x) == escape_char || \ + (enclosed ? (int) (uchar) (x) == field_sep_char \ + : (int) (uchar) (x) == field_term_char) || \ + (int) (uchar) (x) == line_sep_char || \ + !(x)) + +bool select_export::send_data(List &items) +{ + + DBUG_ENTER("select_export::send_data"); + char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH]; + char cvt_buff[MAX_FIELD_WIDTH]; + String cvt_str(cvt_buff, sizeof(cvt_buff), write_cs); + bool space_inited=0; + String tmp(buff,sizeof(buff),&my_charset_bin),*res; + tmp.length(0); + + if (unit->offset_limit_cnt) + { // using limit offset,count + unit->offset_limit_cnt--; + DBUG_RETURN(0); + } + row_count++; + Item *item; + uint used_length=0,items_left=items.elements; + List_iterator_fast li(items); + + if (my_b_write(&cache,(uchar*) exchange->line_start->ptr(), + exchange->line_start->length())) + goto err; + while ((item=li++)) + { + Item_result result_type=item->result_type(); + bool enclosed = (exchange->enclosed->length() && + (!exchange->opt_enclosed || result_type == STRING_RESULT)); + res=item->str_result(&tmp); + if (res && !my_charset_same(write_cs, res->charset()) && + !my_charset_same(write_cs, &my_charset_bin)) + { + const char *well_formed_error_pos; + const char *cannot_convert_error_pos; + const char *from_end_pos; + const char *error_pos; + uint32 bytes; + bytes= well_formed_copy_nchars(write_cs, cvt_buff, sizeof(cvt_buff), + res->charset(), res->ptr(), res->length(), + sizeof(cvt_buff), + &well_formed_error_pos, + &cannot_convert_error_pos, + &from_end_pos); + error_pos= well_formed_error_pos ? well_formed_error_pos + : cannot_convert_error_pos; + if (error_pos) + { + char printable_buff[32]; + convert_to_printable(printable_buff, sizeof(printable_buff), + error_pos, res->ptr() + res->length() - error_pos, + res->charset(), 6); + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TRUNCATED_WRONG_VALUE_FOR_FIELD, + ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD), + "string", printable_buff, + item->name, row_count); + } + cvt_str.length(bytes); + res= &cvt_str; + } + if (res && enclosed) + { + if (my_b_write(&cache,(uchar*) exchange->enclosed->ptr(), + exchange->enclosed->length())) + goto err; + } + if (!res) + { // NULL + if (!fixed_row_size) + { + if (escape_char != -1) // Use \N syntax + { + null_buff[0]=escape_char; + null_buff[1]='N'; + if (my_b_write(&cache,(uchar*) null_buff,2)) + goto err; + } + else if (my_b_write(&cache,(uchar*) "NULL",4)) + goto err; + } + else + { + used_length=0; // Fill with space + } + } + else + { + if (fixed_row_size) + used_length=min(res->length(),item->max_length); + else + used_length=res->length(); + if ((result_type == STRING_RESULT || is_unsafe_field_sep) && + escape_char != -1) + { + char *pos, *start, *end; + CHARSET_INFO *res_charset= res->charset(); + CHARSET_INFO *character_set_client= thd->variables. + character_set_client; + bool check_second_byte= (res_charset == &my_charset_bin) && + character_set_client-> + escape_with_backslash_is_dangerous; + DBUG_ASSERT(character_set_client->mbmaxlen == 2 || + !character_set_client->escape_with_backslash_is_dangerous); + for (start=pos=(char*) res->ptr(),end=pos+used_length ; + pos != end ; + pos++) + { +#ifdef USE_MB + if (use_mb(res_charset)) + { + int l; + if ((l=my_ismbchar(res_charset, pos, end))) + { + pos += l-1; + continue; + } + } +#endif + + /* + Special case when dumping BINARY/VARBINARY/BLOB values + for the clients with character sets big5, cp932, gbk and sjis, + which can have the escape character (0x5C "\" by default) + as the second byte of a multi-byte sequence. + + If + - pos[0] is a valid multi-byte head (e.g 0xEE) and + - pos[1] is 0x00, which will be escaped as "\0", + + then we'll get "0xEE + 0x5C + 0x30" in the output file. + + If this file is later loaded using this sequence of commands: + + mysql> create table t1 (a varchar(128)) character set big5; + mysql> LOAD DATA INFILE 'dump.txt' INTO TABLE t1; + + then 0x5C will be misinterpreted as the second byte + of a multi-byte character "0xEE + 0x5C", instead of + escape character for 0x00. + + To avoid this confusion, we'll escape the multi-byte + head character too, so the sequence "0xEE + 0x00" will be + dumped as "0x5C + 0xEE + 0x5C + 0x30". + + Note, in the condition below we only check if + mbcharlen is equal to 2, because there are no + character sets with mbmaxlen longer than 2 + and with escape_with_backslash_is_dangerous set. + DBUG_ASSERT before the loop makes that sure. + */ + + if ((NEED_ESCAPING(*pos) || + (check_second_byte && + my_mbcharlen(character_set_client, (uchar) *pos) == 2 && + pos + 1 < end && + NEED_ESCAPING(pos[1]))) && + /* + Don't escape field_term_char by doubling - doubling is only + valid for ENCLOSED BY characters: + */ + (enclosed || !is_ambiguous_field_term || + (int) (uchar) *pos != field_term_char)) + { + char tmp_buff[2]; + tmp_buff[0]= ((int) (uchar) *pos == field_sep_char && + is_ambiguous_field_sep) ? + field_sep_char : escape_char; + tmp_buff[1]= *pos ? *pos : '0'; + if (my_b_write(&cache,(uchar*) start,(uint) (pos-start)) || + my_b_write(&cache,(uchar*) tmp_buff,2)) + goto err; + start=pos+1; + } + } + if (my_b_write(&cache,(uchar*) start,(uint) (pos-start))) + goto err; + } + else if (my_b_write(&cache,(uchar*) res->ptr(),used_length)) + goto err; + } + if (fixed_row_size) + { // Fill with space + if (item->max_length > used_length) + { + /* QQ: Fix by adding a my_b_fill() function */ + if (!space_inited) + { + space_inited=1; + bfill(space,sizeof(space),' '); + } + uint length=item->max_length-used_length; + for (; length > sizeof(space) ; length-=sizeof(space)) + { + if (my_b_write(&cache,(uchar*) space,sizeof(space))) + goto err; + } + if (my_b_write(&cache,(uchar*) space,length)) + goto err; + } + } + if (res && enclosed) + { + if (my_b_write(&cache, (uchar*) exchange->enclosed->ptr(), + exchange->enclosed->length())) + goto err; + } + if (--items_left) + { + if (my_b_write(&cache, (uchar*) exchange->field_term->ptr(), + field_term_length)) + goto err; + } + } + if (my_b_write(&cache,(uchar*) exchange->line_term->ptr(), + exchange->line_term->length())) + goto err; + DBUG_RETURN(0); +err: + DBUG_RETURN(1); +} + + +/*************************************************************************** +** Dump of select to a binary file +***************************************************************************/ + + +int +select_dump::prepare(List &list __attribute__((unused)), + SELECT_LEX_UNIT *u) +{ + unit= u; + return (int) ((file= create_file(thd, path, exchange, &cache)) < 0); +} + + +bool select_dump::send_data(List &items) +{ + List_iterator_fast li(items); + char buff[MAX_FIELD_WIDTH]; + String tmp(buff,sizeof(buff),&my_charset_bin),*res; + tmp.length(0); + Item *item; + DBUG_ENTER("select_dump::send_data"); + + if (unit->offset_limit_cnt) + { // using limit offset,count + unit->offset_limit_cnt--; + DBUG_RETURN(0); + } + if (row_count++ > 1) + { + my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0)); + goto err; + } + while ((item=li++)) + { + res=item->str_result(&tmp); + if (!res) // If NULL + { + if (my_b_write(&cache,(uchar*) "",1)) + goto err; + } + else if (my_b_write(&cache,(uchar*) res->ptr(),res->length())) + { + my_error(ER_ERROR_ON_WRITE, MYF(0), path, my_errno); + goto err; + } + } + DBUG_RETURN(0); +err: + DBUG_RETURN(1); +} + + +select_subselect::select_subselect(Item_subselect *item_arg) +{ + item= item_arg; +} + + +bool select_singlerow_subselect::send_data(List &items) +{ + DBUG_ENTER("select_singlerow_subselect::send_data"); + Item_singlerow_subselect *it= (Item_singlerow_subselect *)item; + if (it->assigned()) + { + my_message(ER_SUBQUERY_NO_1_ROW, ER(ER_SUBQUERY_NO_1_ROW), MYF(0)); + DBUG_RETURN(1); + } + if (unit->offset_limit_cnt) + { // Using limit offset,count + unit->offset_limit_cnt--; + DBUG_RETURN(0); + } + List_iterator_fast li(items); + Item *val_item; + for (uint i= 0; (val_item= li++); i++) + it->store(i, val_item); + it->assigned(1); + DBUG_RETURN(0); +} + + +void select_max_min_finder_subselect::cleanup() +{ + DBUG_ENTER("select_max_min_finder_subselect::cleanup"); + cache= 0; + DBUG_VOID_RETURN; +} + + +bool select_max_min_finder_subselect::send_data(List &items) +{ + DBUG_ENTER("select_max_min_finder_subselect::send_data"); + Item_maxmin_subselect *it= (Item_maxmin_subselect *)item; + List_iterator_fast li(items); + Item *val_item= li++; + it->register_value(); + if (it->assigned()) + { + cache->store(val_item); + if ((this->*op)()) + it->store(0, cache); + } + else + { + if (!cache) + { + cache= Item_cache::get_cache(val_item); + switch (val_item->result_type()) + { + case REAL_RESULT: + op= &select_max_min_finder_subselect::cmp_real; + break; + case INT_RESULT: + op= &select_max_min_finder_subselect::cmp_int; + break; + case STRING_RESULT: + op= &select_max_min_finder_subselect::cmp_str; + break; + case DECIMAL_RESULT: + op= &select_max_min_finder_subselect::cmp_decimal; + break; + case ROW_RESULT: + // This case should never be choosen + DBUG_ASSERT(0); + op= 0; + } + } + cache->store(val_item); + it->store(0, cache); + } + it->assigned(1); + DBUG_RETURN(0); +} + +bool select_max_min_finder_subselect::cmp_real() +{ + Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0); + double val1= cache->val_real(), val2= maxmin->val_real(); + if (fmax) + return (cache->null_value && !maxmin->null_value) || + (!cache->null_value && !maxmin->null_value && + val1 > val2); + return (maxmin->null_value && !cache->null_value) || + (!cache->null_value && !maxmin->null_value && + val1 < val2); +} + +bool select_max_min_finder_subselect::cmp_int() +{ + Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0); + longlong val1= cache->val_int(), val2= maxmin->val_int(); + if (fmax) + return (cache->null_value && !maxmin->null_value) || + (!cache->null_value && !maxmin->null_value && + val1 > val2); + return (maxmin->null_value && !cache->null_value) || + (!cache->null_value && !maxmin->null_value && + val1 < val2); +} + +bool select_max_min_finder_subselect::cmp_decimal() +{ + Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0); + my_decimal cval, *cvalue= cache->val_decimal(&cval); + my_decimal mval, *mvalue= maxmin->val_decimal(&mval); + if (fmax) + return (cache->null_value && !maxmin->null_value) || + (!cache->null_value && !maxmin->null_value && + my_decimal_cmp(cvalue, mvalue) > 0) ; + return (maxmin->null_value && !cache->null_value) || + (!cache->null_value && !maxmin->null_value && + my_decimal_cmp(cvalue,mvalue) < 0); +} + +bool select_max_min_finder_subselect::cmp_str() +{ + String *val1, *val2, buf1, buf2; + Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0); + /* + as far as both operand is Item_cache buf1 & buf2 will not be used, + but added for safety + */ + val1= cache->val_str(&buf1); + val2= maxmin->val_str(&buf1); + if (fmax) + return (cache->null_value && !maxmin->null_value) || + (!cache->null_value && !maxmin->null_value && + sortcmp(val1, val2, cache->collation.collation) > 0) ; + return (maxmin->null_value && !cache->null_value) || + (!cache->null_value && !maxmin->null_value && + sortcmp(val1, val2, cache->collation.collation) < 0); +} + +bool select_exists_subselect::send_data(List &items) +{ + DBUG_ENTER("select_exists_subselect::send_data"); + Item_exists_subselect *it= (Item_exists_subselect *)item; + if (unit->offset_limit_cnt) + { // Using limit offset,count + unit->offset_limit_cnt--; + DBUG_RETURN(0); + } + it->value= 1; + it->assigned(1); + DBUG_RETURN(0); +} + + +/*************************************************************************** + Dump of select to variables +***************************************************************************/ + +int select_dumpvar::prepare(List &list, SELECT_LEX_UNIT *u) +{ + unit= u; + + if (var_list.elements != list.elements) + { + my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT, + ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), MYF(0)); + return 1; + } + return 0; +} + + +bool select_dumpvar::check_simple_select() const +{ + my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0)); + return TRUE; +} + + +void select_dumpvar::cleanup() +{ + row_count= 0; +} + + +Query_arena::Type Query_arena::type() const +{ + DBUG_ASSERT(0); /* Should never be called */ + return STATEMENT; +} + + +void Query_arena::free_items() +{ + Item *next; + DBUG_ENTER("Query_arena::free_items"); + /* This works because items are allocated with sql_alloc() */ + for (; free_list; free_list= next) + { + next= free_list->next; + free_list->delete_self(); + } + /* Postcondition: free_list is 0 */ + DBUG_VOID_RETURN; +} + + +void Query_arena::set_query_arena(Query_arena *set) +{ + mem_root= set->mem_root; + free_list= set->free_list; + state= set->state; +} + + +void Query_arena::cleanup_stmt() +{ + DBUG_ASSERT(! "Query_arena::cleanup_stmt() not implemented"); +} + +/* + Statement functions +*/ + +Statement::Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg, + enum enum_state state_arg, ulong id_arg) + :Query_arena(mem_root_arg, state_arg), + id(id_arg), + mark_used_columns(MARK_COLUMNS_READ), + lex(lex_arg), + query(0), + query_length(0), + cursor(0), + db(NULL), + db_length(0) +{ + name.str= NULL; +} + + +Query_arena::Type Statement::type() const +{ + return STATEMENT; +} + + +void Statement::set_statement(Statement *stmt) +{ + id= stmt->id; + mark_used_columns= stmt->mark_used_columns; + lex= stmt->lex; + query= stmt->query; + query_length= stmt->query_length; + cursor= stmt->cursor; +} + + +void +Statement::set_n_backup_statement(Statement *stmt, Statement *backup) +{ + DBUG_ENTER("Statement::set_n_backup_statement"); + backup->set_statement(this); + set_statement(stmt); + DBUG_VOID_RETURN; +} + + +void Statement::restore_backup_statement(Statement *stmt, Statement *backup) +{ + DBUG_ENTER("Statement::restore_backup_statement"); + stmt->set_statement(this); + set_statement(backup); + DBUG_VOID_RETURN; +} + + +void THD::end_statement() +{ + /* Cleanup SQL processing state to reuse this statement in next query. */ + lex_end(lex); + delete lex->result; + lex->result= 0; + /* Note that free_list is freed in cleanup_after_query() */ + + /* + Don't free mem_root, as mem_root is freed in the end of dispatch_command + (once for any command). + */ +} + + +void THD::set_n_backup_active_arena(Query_arena *set, Query_arena *backup) +{ + DBUG_ENTER("THD::set_n_backup_active_arena"); + DBUG_ASSERT(backup->is_backup_arena == FALSE); + + backup->set_query_arena(this); + set_query_arena(set); +#ifndef DBUG_OFF + backup->is_backup_arena= TRUE; +#endif + DBUG_VOID_RETURN; +} + + +void THD::restore_active_arena(Query_arena *set, Query_arena *backup) +{ + DBUG_ENTER("THD::restore_active_arena"); + DBUG_ASSERT(backup->is_backup_arena); + set->set_query_arena(this); + set_query_arena(backup); +#ifndef DBUG_OFF + backup->is_backup_arena= FALSE; +#endif + DBUG_VOID_RETURN; +} + +Statement::~Statement() +{ +} + +C_MODE_START + +static uchar * +get_statement_id_as_hash_key(const uchar *record, size_t *key_length, + my_bool not_used __attribute__((unused))) +{ + const Statement *statement= (const Statement *) record; + *key_length= sizeof(statement->id); + return (uchar *) &((const Statement *) statement)->id; +} + +static void delete_statement_as_hash_key(void *key) +{ + delete (Statement *) key; +} + +static uchar *get_stmt_name_hash_key(Statement *entry, size_t *length, + my_bool not_used __attribute__((unused))) +{ + *length= entry->name.length; + return (uchar*) entry->name.str; +} + +C_MODE_END + +Statement_map::Statement_map() : + last_found_statement(0) +{ + enum + { + START_STMT_HASH_SIZE = 16, + START_NAME_HASH_SIZE = 16 + }; + hash_init(&st_hash, &my_charset_bin, START_STMT_HASH_SIZE, 0, 0, + get_statement_id_as_hash_key, + delete_statement_as_hash_key, MYF(0)); + hash_init(&names_hash, system_charset_info, START_NAME_HASH_SIZE, 0, 0, + (hash_get_key) get_stmt_name_hash_key, + NULL,MYF(0)); +} + + +/* + Insert a new statement to the thread-local statement map. + + DESCRIPTION + If there was an old statement with the same name, replace it with the + new one. Otherwise, check if max_prepared_stmt_count is not reached yet, + increase prepared_stmt_count, and insert the new statement. It's okay + to delete an old statement and fail to insert the new one. + + POSTCONDITIONS + All named prepared statements are also present in names_hash. + Statement names in names_hash are unique. + The statement is added only if prepared_stmt_count < max_prepard_stmt_count + last_found_statement always points to a valid statement or is 0 + + RETURN VALUE + 0 success + 1 error: out of resources or max_prepared_stmt_count limit has been + reached. An error is sent to the client, the statement is deleted. +*/ + +int Statement_map::insert(THD *thd, Statement *statement) +{ + if (my_hash_insert(&st_hash, (uchar*) statement)) + { + /* + Delete is needed only in case of an insert failure. In all other + cases hash_delete will also delete the statement. + */ + delete statement; + my_error(ER_OUT_OF_RESOURCES, MYF(0)); + goto err_st_hash; + } + if (statement->name.str && my_hash_insert(&names_hash, (uchar*) statement)) + { + my_error(ER_OUT_OF_RESOURCES, MYF(0)); + goto err_names_hash; + } + pthread_mutex_lock(&LOCK_prepared_stmt_count); + /* + We don't check that prepared_stmt_count is <= max_prepared_stmt_count + because we would like to allow to lower the total limit + of prepared statements below the current count. In that case + no new statements can be added until prepared_stmt_count drops below + the limit. + */ + if (prepared_stmt_count >= max_prepared_stmt_count) + { + pthread_mutex_unlock(&LOCK_prepared_stmt_count); + my_error(ER_MAX_PREPARED_STMT_COUNT_REACHED, MYF(0), + max_prepared_stmt_count); + goto err_max; + } + prepared_stmt_count++; + pthread_mutex_unlock(&LOCK_prepared_stmt_count); + + last_found_statement= statement; + return 0; + +err_max: + if (statement->name.str) + hash_delete(&names_hash, (uchar*) statement); +err_names_hash: + hash_delete(&st_hash, (uchar*) statement); +err_st_hash: + return 1; +} + + +void Statement_map::close_transient_cursors() +{ +#ifdef TO_BE_IMPLEMENTED + Statement *stmt; + while ((stmt= transient_cursor_list.head())) + stmt->close_cursor(); /* deletes itself from the list */ +#endif +} + + +void Statement_map::erase(Statement *statement) +{ + if (statement == last_found_statement) + last_found_statement= 0; + if (statement->name.str) + hash_delete(&names_hash, (uchar *) statement); + + hash_delete(&st_hash, (uchar *) statement); + pthread_mutex_lock(&LOCK_prepared_stmt_count); + DBUG_ASSERT(prepared_stmt_count > 0); + prepared_stmt_count--; + pthread_mutex_unlock(&LOCK_prepared_stmt_count); +} + + +void Statement_map::reset() +{ + /* Must be first, hash_free will reset st_hash.records */ + pthread_mutex_lock(&LOCK_prepared_stmt_count); + DBUG_ASSERT(prepared_stmt_count >= st_hash.records); + prepared_stmt_count-= st_hash.records; + pthread_mutex_unlock(&LOCK_prepared_stmt_count); + + my_hash_reset(&names_hash); + my_hash_reset(&st_hash); + last_found_statement= 0; +} + + +Statement_map::~Statement_map() +{ + /* Must go first, hash_free will reset st_hash.records */ + pthread_mutex_lock(&LOCK_prepared_stmt_count); + DBUG_ASSERT(prepared_stmt_count >= st_hash.records); + prepared_stmt_count-= st_hash.records; + pthread_mutex_unlock(&LOCK_prepared_stmt_count); + + hash_free(&names_hash); + hash_free(&st_hash); +} + +bool select_dumpvar::send_data(List &items) +{ + List_iterator_fast var_li(var_list); + List_iterator it(items); + Item *item; + my_var *mv; + DBUG_ENTER("select_dumpvar::send_data"); + + if (unit->offset_limit_cnt) + { // using limit offset,count + unit->offset_limit_cnt--; + DBUG_RETURN(0); + } + if (row_count++) + { + my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0)); + DBUG_RETURN(1); + } + while ((mv= var_li++) && (item= it++)) + { + if (mv->local) + { + if (thd->spcont->set_variable(thd, mv->offset, &item)) + DBUG_RETURN(1); + } + else + { + Item_func_set_user_var *suv= new Item_func_set_user_var(mv->s, item); + suv->fix_fields(thd, 0); + suv->save_item_result(item); + suv->update(); + } + } + DBUG_RETURN(thd->is_error()); +} + +bool select_dumpvar::send_eof() +{ + if (! row_count) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_SP_FETCH_NO_DATA, ER(ER_SP_FETCH_NO_DATA)); + /* + In order to remember the value of affected rows for ROW_COUNT() + function, SELECT INTO has to have an own SQLCOM. + TODO: split from SQLCOM_SELECT + */ + ::my_ok(thd,row_count); + return 0; +} + +/**************************************************************************** + TMP_TABLE_PARAM +****************************************************************************/ + +void TMP_TABLE_PARAM::init() +{ + DBUG_ENTER("TMP_TABLE_PARAM::init"); + DBUG_PRINT("enter", ("this: 0x%lx", (ulong)this)); + field_count= sum_func_count= func_count= hidden_field_count= 0; + group_parts= group_length= group_null_parts= 0; + quick_group= 1; + table_charset= 0; + precomputed_group_by= 0; + DBUG_VOID_RETURN; +} + + +void thd_increment_bytes_sent(ulong length) +{ + THD *thd=current_thd; + if (likely(thd != 0)) + { /* current_thd==0 when close_connection() calls net_send_error() */ + thd->status_var.bytes_sent+= length; + } +} + + +void thd_increment_bytes_received(ulong length) +{ + current_thd->status_var.bytes_received+= length; +} + + +void thd_increment_net_big_packet_count(ulong length) +{ + current_thd->status_var.net_big_packet_count+= length; +} + + +void THD::set_status_var_init() +{ + bzero((char*) &status_var, sizeof(status_var)); +} + + +void Security_context::init() +{ + host= user= priv_user= ip= 0; + host_or_ip= "connecting host"; + priv_host[0]= '\0'; + master_access= 0; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + db_access= NO_ACCESS; +#endif +} + + +void Security_context::destroy() +{ + // If not pointer to constant + if (host != my_localhost) + safeFree(host); + if (user != delayed_user) + safeFree(user); + safeFree(ip); +} + + +void Security_context::skip_grants() +{ + /* privileges for the user are unknown everything is allowed */ + host_or_ip= (char *)""; + master_access= ~NO_ACCESS; + priv_user= (char *)""; + *priv_host= '\0'; +} + + +bool Security_context::set_user(char *user_arg) +{ + safeFree(user); + user= my_strdup(user_arg, MYF(0)); + return user == 0; +} + +#ifndef NO_EMBEDDED_ACCESS_CHECKS +/** + Initialize this security context from the passed in credentials + and activate it in the current thread. + + @param thd + @param definer_user + @param definer_host + @param db + @param[out] backup Save a pointer to the current security context + in the thread. In case of success it points to the + saved old context, otherwise it points to NULL. + + + During execution of a statement, multiple security contexts may + be needed: + - the security context of the authenticated user, used as the + default security context for all top-level statements + - in case of a view or a stored program, possibly the security + context of the definer of the routine, if the object is + defined with SQL SECURITY DEFINER option. + + The currently "active" security context is parameterized in THD + member security_ctx. By default, after a connection is + established, this member points at the "main" security context + - the credentials of the authenticated user. + + Later, if we would like to execute some sub-statement or a part + of a statement under credentials of a different user, e.g. + definer of a procedure, we authenticate this user in a local + instance of Security_context by means of this method (and + ultimately by means of acl_getroot_no_password), and make the + local instance active in the thread by re-setting + thd->security_ctx pointer. + + Note, that the life cycle and memory management of the "main" and + temporary security contexts are different. + For the main security context, the memory for user/host/ip is + allocated on system heap, and the THD class frees this memory in + its destructor. The only case when contents of the main security + context may change during its life time is when someone issued + CHANGE USER command. + Memory management of a "temporary" security context is + responsibility of the module that creates it. + + @retval TRUE there is no user with the given credentials. The erro + is reported in the thread. + @retval FALSE success +*/ + +bool +Security_context:: +change_security_context(THD *thd, + LEX_STRING *definer_user, + LEX_STRING *definer_host, + LEX_STRING *db, + Security_context **backup) +{ + bool needs_change; + + DBUG_ENTER("Security_context::change_security_context"); + + DBUG_ASSERT(definer_user->str && definer_host->str); + + *backup= NULL; + /* + The current security context may have NULL members + if we have just started the thread and not authenticated + any user. This use case is currently in events worker thread. + */ + needs_change= (thd->security_ctx->priv_user == NULL || + strcmp(definer_user->str, thd->security_ctx->priv_user) || + thd->security_ctx->priv_host == NULL || + my_strcasecmp(system_charset_info, definer_host->str, + thd->security_ctx->priv_host)); + if (needs_change) + { + if (acl_getroot_no_password(this, definer_user->str, definer_host->str, + definer_host->str, db->str)) + { + my_error(ER_NO_SUCH_USER, MYF(0), definer_user->str, + definer_host->str); + DBUG_RETURN(TRUE); + } + *backup= thd->security_ctx; + thd->security_ctx= this; + } + + DBUG_RETURN(FALSE); +} + + +void +Security_context::restore_security_context(THD *thd, + Security_context *backup) +{ + if (backup) + thd->security_ctx= backup; +} +#endif + + +bool Security_context::user_matches(Security_context *them) +{ + return ((user != NULL) && (them->user != NULL) && + !strcmp(user, them->user)); +} + + +/**************************************************************************** + Handling of open and locked tables states. + + This is used when we want to open/lock (and then close) some tables when + we already have a set of tables open and locked. We use these methods for + access to mysql.proc table to find definitions of stored routines. +****************************************************************************/ + +void THD::reset_n_backup_open_tables_state(Open_tables_state *backup) +{ + DBUG_ENTER("reset_n_backup_open_tables_state"); + backup->set_open_tables_state(this); + reset_open_tables_state(); + state_flags|= Open_tables_state::BACKUPS_AVAIL; + DBUG_VOID_RETURN; +} + + +void THD::restore_backup_open_tables_state(Open_tables_state *backup) +{ + DBUG_ENTER("restore_backup_open_tables_state"); + /* + Before we will throw away current open tables state we want + to be sure that it was properly cleaned up. + */ + DBUG_ASSERT(open_tables == 0 && temporary_tables == 0 && + handler_tables == 0 && derived_tables == 0 && + lock == 0 && locked_tables == 0 && + prelocked_mode == NON_PRELOCKED && + m_reprepare_observer == NULL); + set_open_tables_state(backup); + DBUG_VOID_RETURN; +} + +/** + Check the killed state of a user thread + @param thd user thread + @retval 0 the user thread is active + @retval 1 the user thread has been killed +*/ +extern "C" int thd_killed(const MYSQL_THD thd) +{ + return(thd->killed); +} + +/** + Return the thread id of a user thread + @param thd user thread + @return thread id +*/ +extern "C" unsigned long thd_get_thread_id(const MYSQL_THD thd) +{ + return((unsigned long)thd->thread_id); +} + + +#ifdef INNODB_COMPATIBILITY_HOOKS +extern "C" struct charset_info_st *thd_charset(MYSQL_THD thd) +{ + return(thd->charset()); +} + +extern "C" char **thd_query(MYSQL_THD thd) +{ + return(&thd->query); +} + +extern "C" int thd_slave_thread(const MYSQL_THD thd) +{ + return(thd->slave_thread); +} + +extern "C" int thd_non_transactional_update(const MYSQL_THD thd) +{ + return(thd->transaction.all.modified_non_trans_table); +} + +extern "C" int thd_binlog_format(const MYSQL_THD thd) +{ + if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG)) + return (int) thd->variables.binlog_format; + else + return BINLOG_FORMAT_UNSPEC; +} + +extern "C" void thd_mark_transaction_to_rollback(MYSQL_THD thd, bool all) +{ + mark_transaction_to_rollback(thd, all); +} +#endif // INNODB_COMPATIBILITY_HOOKS */ + +/**************************************************************************** + Handling of statement states in functions and triggers. + + This is used to ensure that the function/trigger gets a clean state + to work with and does not cause any side effects of the calling statement. + + It also allows most stored functions and triggers to replicate even + if they are used items that would normally be stored in the binary + replication (like last_insert_id() etc...) + + The following things is done + - Disable binary logging for the duration of the statement + - Disable multi-result-sets for the duration of the statement + - Value of last_insert_id() is saved and restored + - Value set by 'SET INSERT_ID=#' is reset and restored + - Value for found_rows() is reset and restored + - examined_row_count is added to the total + - cuted_fields is added to the total + - new savepoint level is created and destroyed + + NOTES: + Seed for random() is saved for the first! usage of RAND() + We reset examined_row_count and cuted_fields and add these to the + result to ensure that if we have a bug that would reset these within + a function, we are not loosing any rows from the main statement. + + We do not reset value of last_insert_id(). +****************************************************************************/ + +void THD::reset_sub_statement_state(Sub_statement_state *backup, + uint new_state) +{ +#ifndef EMBEDDED_LIBRARY + /* BUG#33029, if we are replicating from a buggy master, reset + auto_inc_intervals_forced to prevent substatement + (triggers/functions) from using erroneous INSERT_ID value + */ + if (rpl_master_erroneous_autoinc(this)) + { + DBUG_ASSERT(backup->auto_inc_intervals_forced.nb_elements() == 0); + auto_inc_intervals_forced.swap(&backup->auto_inc_intervals_forced); + } +#endif + + backup->options= options; + backup->in_sub_stmt= in_sub_stmt; + backup->enable_slow_log= enable_slow_log; + backup->limit_found_rows= limit_found_rows; + backup->examined_row_count= examined_row_count; + backup->sent_row_count= sent_row_count; + backup->cuted_fields= cuted_fields; + backup->client_capabilities= client_capabilities; + backup->savepoints= transaction.savepoints; + backup->first_successful_insert_id_in_prev_stmt= + first_successful_insert_id_in_prev_stmt; + backup->first_successful_insert_id_in_cur_stmt= + first_successful_insert_id_in_cur_stmt; + + if ((!lex->requires_prelocking() || is_update_query(lex->sql_command)) && + !current_stmt_binlog_row_based) + { + options&= ~OPTION_BIN_LOG; + } + + if ((backup->options & OPTION_BIN_LOG) && is_update_query(lex->sql_command)&& + !current_stmt_binlog_row_based) + mysql_bin_log.start_union_events(this, this->query_id); + + /* Disable result sets */ + client_capabilities &= ~CLIENT_MULTI_RESULTS; + in_sub_stmt|= new_state; + examined_row_count= 0; + sent_row_count= 0; + cuted_fields= 0; + transaction.savepoints= 0; + first_successful_insert_id_in_cur_stmt= 0; +} + + +void THD::restore_sub_statement_state(Sub_statement_state *backup) +{ +#ifndef EMBEDDED_LIBRARY + /* BUG#33029, if we are replicating from a buggy master, restore + auto_inc_intervals_forced so that the top statement can use the + INSERT_ID value set before this statement. + */ + if (rpl_master_erroneous_autoinc(this)) + { + backup->auto_inc_intervals_forced.swap(&auto_inc_intervals_forced); + DBUG_ASSERT(backup->auto_inc_intervals_forced.nb_elements() == 0); + } +#endif + + /* + To save resources we want to release savepoints which were created + during execution of function or trigger before leaving their savepoint + level. It is enough to release first savepoint set on this level since + all later savepoints will be released automatically. + */ + if (transaction.savepoints) + { + SAVEPOINT *sv; + for (sv= transaction.savepoints; sv->prev; sv= sv->prev) + {} + /* ha_release_savepoint() never returns error. */ + (void)ha_release_savepoint(this, sv); + } + transaction.savepoints= backup->savepoints; + options= backup->options; + in_sub_stmt= backup->in_sub_stmt; + enable_slow_log= backup->enable_slow_log; + first_successful_insert_id_in_prev_stmt= + backup->first_successful_insert_id_in_prev_stmt; + first_successful_insert_id_in_cur_stmt= + backup->first_successful_insert_id_in_cur_stmt; + limit_found_rows= backup->limit_found_rows; + sent_row_count= backup->sent_row_count; + client_capabilities= backup->client_capabilities; + /* + If we've left sub-statement mode, reset the fatal error flag. + Otherwise keep the current value, to propagate it up the sub-statement + stack. + */ + if (!in_sub_stmt) + is_fatal_sub_stmt_error= FALSE; + + if ((options & OPTION_BIN_LOG) && is_update_query(lex->sql_command) && + !current_stmt_binlog_row_based) + mysql_bin_log.stop_union_events(this); + + /* + The following is added to the old values as we are interested in the + total complexity of the query + */ + examined_row_count+= backup->examined_row_count; + cuted_fields+= backup->cuted_fields; +} + + +void THD::set_statement(Statement *stmt) +{ + pthread_mutex_lock(&LOCK_thd_data); + Statement::set_statement(stmt); + pthread_mutex_unlock(&LOCK_thd_data); +} + + +/** Assign a new value to thd->query. */ + +void THD::set_query(char *query_arg, uint32 query_length_arg) +{ + pthread_mutex_lock(&LOCK_thd_data); + query= query_arg; + query_length= query_length_arg; + pthread_mutex_unlock(&LOCK_thd_data); +} + + +/** + Mark transaction to rollback and mark error as fatal to a sub-statement. + + @param thd Thread handle + @param all TRUE <=> rollback main transaction. +*/ + +void mark_transaction_to_rollback(THD *thd, bool all) +{ + if (thd) + { + thd->is_fatal_sub_stmt_error= TRUE; + thd->transaction_rollback_request= all; + } +} +/*************************************************************************** + Handling of XA id cacheing +***************************************************************************/ + +pthread_mutex_t LOCK_xid_cache; +HASH xid_cache; + +extern "C" uchar *xid_get_hash_key(const uchar *, size_t *, my_bool); +extern "C" void xid_free_hash(void *); + +uchar *xid_get_hash_key(const uchar *ptr, size_t *length, + my_bool not_used __attribute__((unused))) +{ + *length=((XID_STATE*)ptr)->xid.key_length(); + return ((XID_STATE*)ptr)->xid.key(); +} + +void xid_free_hash(void *ptr) +{ + if (!((XID_STATE*)ptr)->in_thd) + my_free((uchar*)ptr, MYF(0)); +} + +bool xid_cache_init() +{ + pthread_mutex_init(&LOCK_xid_cache, MY_MUTEX_INIT_FAST); + return hash_init(&xid_cache, &my_charset_bin, 100, 0, 0, + xid_get_hash_key, xid_free_hash, 0) != 0; +} + +void xid_cache_free() +{ + if (hash_inited(&xid_cache)) + { + hash_free(&xid_cache); + pthread_mutex_destroy(&LOCK_xid_cache); + } +} + +XID_STATE *xid_cache_search(XID *xid) +{ + pthread_mutex_lock(&LOCK_xid_cache); + XID_STATE *res=(XID_STATE *)hash_search(&xid_cache, xid->key(), xid->key_length()); + pthread_mutex_unlock(&LOCK_xid_cache); + return res; +} + + +bool xid_cache_insert(XID *xid, enum xa_states xa_state) +{ + XID_STATE *xs; + my_bool res; + pthread_mutex_lock(&LOCK_xid_cache); + if (hash_search(&xid_cache, xid->key(), xid->key_length())) + res=0; + else if (!(xs=(XID_STATE *)my_malloc(sizeof(*xs), MYF(MY_WME)))) + res=1; + else + { + xs->xa_state=xa_state; + xs->xid.set(xid); + xs->in_thd=0; + res=my_hash_insert(&xid_cache, (uchar*)xs); + } + pthread_mutex_unlock(&LOCK_xid_cache); + return res; +} + + +bool xid_cache_insert(XID_STATE *xid_state) +{ + pthread_mutex_lock(&LOCK_xid_cache); + DBUG_ASSERT(hash_search(&xid_cache, xid_state->xid.key(), + xid_state->xid.key_length())==0); + my_bool res=my_hash_insert(&xid_cache, (uchar*)xid_state); + pthread_mutex_unlock(&LOCK_xid_cache); + return res; +} + + +void xid_cache_delete(XID_STATE *xid_state) +{ + pthread_mutex_lock(&LOCK_xid_cache); + hash_delete(&xid_cache, (uchar *)xid_state); + pthread_mutex_unlock(&LOCK_xid_cache); +} + +/* + Implementation of interface to write rows to the binary log through the + thread. The thread is responsible for writing the rows it has + inserted/updated/deleted. +*/ + +#ifndef MYSQL_CLIENT + +/* + Template member function for ensuring that there is an rows log + event of the apropriate type before proceeding. + + PRE CONDITION: + - Events of type 'RowEventT' have the type code 'type_code'. + + POST CONDITION: + If a non-NULL pointer is returned, the pending event for thread 'thd' will + be an event of type 'RowEventT' (which have the type code 'type_code') + will either empty or have enough space to hold 'needed' bytes. In + addition, the columns bitmap will be correct for the row, meaning that + the pending event will be flushed if the columns in the event differ from + the columns suppled to the function. + + RETURNS + If no error, a non-NULL pending event (either one which already existed or + the newly created one). + If error, NULL. + */ + +template Rows_log_event* +THD::binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id, + MY_BITMAP const* cols, + size_t colcnt, + size_t needed, + bool is_transactional, + RowsEventT *hint __attribute__((unused))) +{ + DBUG_ENTER("binlog_prepare_pending_rows_event"); + /* Pre-conditions */ + DBUG_ASSERT(table->s->table_map_id != ~0UL); + + /* Fetch the type code for the RowsEventT template parameter */ + int const type_code= RowsEventT::TYPE_CODE; + + /* + There is no good place to set up the transactional data, so we + have to do it here. + */ + if (binlog_setup_trx_data()) + DBUG_RETURN(NULL); + + Rows_log_event* pending= binlog_get_pending_rows_event(); + + if (unlikely(pending && !pending->is_valid())) + DBUG_RETURN(NULL); + + /* + Check if the current event is non-NULL and a write-rows + event. Also check if the table provided is mapped: if it is not, + then we have switched to writing to a new table. + If there is no pending event, we need to create one. If there is a pending + event, but it's not about the same table id, or not of the same type + (between Write, Update and Delete), or not the same affected columns, or + going to be too big, flush this event to disk and create a new pending + event. + */ + if (!pending || + pending->server_id != serv_id || + pending->get_table_id() != table->s->table_map_id || + pending->get_type_code() != type_code || + pending->get_data_size() + needed > opt_binlog_rows_event_max_size || + pending->get_width() != colcnt || + !bitmap_cmp(pending->get_cols(), cols)) + { + /* Create a new RowsEventT... */ + Rows_log_event* const + ev= new RowsEventT(this, table, table->s->table_map_id, cols, + is_transactional); + if (unlikely(!ev)) + DBUG_RETURN(NULL); + ev->server_id= serv_id; // I don't like this, it's too easy to forget. + /* + flush the pending event and replace it with the newly created + event... + */ + if (unlikely(mysql_bin_log.flush_and_set_pending_rows_event(this, ev))) + { + delete ev; + DBUG_RETURN(NULL); + } + + DBUG_RETURN(ev); /* This is the new pending event */ + } + DBUG_RETURN(pending); /* This is the current pending event */ +} + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +/* + Instantiate the versions we need, we have -fno-implicit-template as + compiling option. +*/ +template Rows_log_event* +THD::binlog_prepare_pending_rows_event(TABLE*, uint32, MY_BITMAP const*, + size_t, size_t, bool, + Write_rows_log_event*); + +template Rows_log_event* +THD::binlog_prepare_pending_rows_event(TABLE*, uint32, MY_BITMAP const*, + size_t colcnt, size_t, bool, + Delete_rows_log_event *); + +template Rows_log_event* +THD::binlog_prepare_pending_rows_event(TABLE*, uint32, MY_BITMAP const*, + size_t colcnt, size_t, bool, + Update_rows_log_event *); +#endif + +#ifdef NOT_USED +static char const* +field_type_name(enum_field_types type) +{ + switch (type) { + case MYSQL_TYPE_DECIMAL: + return "MYSQL_TYPE_DECIMAL"; + case MYSQL_TYPE_TINY: + return "MYSQL_TYPE_TINY"; + case MYSQL_TYPE_SHORT: + return "MYSQL_TYPE_SHORT"; + case MYSQL_TYPE_LONG: + return "MYSQL_TYPE_LONG"; + case MYSQL_TYPE_FLOAT: + return "MYSQL_TYPE_FLOAT"; + case MYSQL_TYPE_DOUBLE: + return "MYSQL_TYPE_DOUBLE"; + case MYSQL_TYPE_NULL: + return "MYSQL_TYPE_NULL"; + case MYSQL_TYPE_TIMESTAMP: + return "MYSQL_TYPE_TIMESTAMP"; + case MYSQL_TYPE_LONGLONG: + return "MYSQL_TYPE_LONGLONG"; + case MYSQL_TYPE_INT24: + return "MYSQL_TYPE_INT24"; + case MYSQL_TYPE_DATE: + return "MYSQL_TYPE_DATE"; + case MYSQL_TYPE_TIME: + return "MYSQL_TYPE_TIME"; + case MYSQL_TYPE_DATETIME: + return "MYSQL_TYPE_DATETIME"; + case MYSQL_TYPE_YEAR: + return "MYSQL_TYPE_YEAR"; + case MYSQL_TYPE_NEWDATE: + return "MYSQL_TYPE_NEWDATE"; + case MYSQL_TYPE_VARCHAR: + return "MYSQL_TYPE_VARCHAR"; + case MYSQL_TYPE_BIT: + return "MYSQL_TYPE_BIT"; + case MYSQL_TYPE_NEWDECIMAL: + return "MYSQL_TYPE_NEWDECIMAL"; + case MYSQL_TYPE_ENUM: + return "MYSQL_TYPE_ENUM"; + case MYSQL_TYPE_SET: + return "MYSQL_TYPE_SET"; + case MYSQL_TYPE_TINY_BLOB: + return "MYSQL_TYPE_TINY_BLOB"; + case MYSQL_TYPE_MEDIUM_BLOB: + return "MYSQL_TYPE_MEDIUM_BLOB"; + case MYSQL_TYPE_LONG_BLOB: + return "MYSQL_TYPE_LONG_BLOB"; + case MYSQL_TYPE_BLOB: + return "MYSQL_TYPE_BLOB"; + case MYSQL_TYPE_VAR_STRING: + return "MYSQL_TYPE_VAR_STRING"; + case MYSQL_TYPE_STRING: + return "MYSQL_TYPE_STRING"; + case MYSQL_TYPE_GEOMETRY: + return "MYSQL_TYPE_GEOMETRY"; + } + return "Unknown"; +} +#endif + + +namespace { + /** + Class to handle temporary allocation of memory for row data. + + The responsibilities of the class is to provide memory for + packing one or two rows of packed data (depending on what + constructor is called). + + In order to make the allocation more efficient for "simple" rows, + i.e., rows that do not contain any blobs, a pointer to the + allocated memory is of memory is stored in the table structure + for simple rows. If memory for a table containing a blob field + is requested, only memory for that is allocated, and subsequently + released when the object is destroyed. + + */ + class Row_data_memory { + public: + /** + Build an object to keep track of a block-local piece of memory + for storing a row of data. + + @param table + Table where the pre-allocated memory is stored. + + @param length + Length of data that is needed, if the record contain blobs. + */ + Row_data_memory(TABLE *table, size_t const len1) + : m_memory(0) + { +#ifndef DBUG_OFF + m_alloc_checked= FALSE; +#endif + allocate_memory(table, len1); + m_ptr[0]= has_memory() ? m_memory : 0; + m_ptr[1]= 0; + } + + Row_data_memory(TABLE *table, size_t const len1, size_t const len2) + : m_memory(0) + { +#ifndef DBUG_OFF + m_alloc_checked= FALSE; +#endif + allocate_memory(table, len1 + len2); + m_ptr[0]= has_memory() ? m_memory : 0; + m_ptr[1]= has_memory() ? m_memory + len1 : 0; + } + + ~Row_data_memory() + { + if (m_memory != 0 && m_release_memory_on_destruction) + my_free((uchar*) m_memory, MYF(MY_WME)); + } + + /** + Is there memory allocated? + + @retval true There is memory allocated + @retval false Memory allocation failed + */ + bool has_memory() const { +#ifndef DBUG_OFF + m_alloc_checked= TRUE; +#endif + return m_memory != 0; + } + + uchar *slot(uint s) + { + DBUG_ASSERT(s < sizeof(m_ptr)/sizeof(*m_ptr)); + DBUG_ASSERT(m_ptr[s] != 0); + DBUG_ASSERT(m_alloc_checked == TRUE); + return m_ptr[s]; + } + + private: + void allocate_memory(TABLE *const table, size_t const total_length) + { + if (table->s->blob_fields == 0) + { + /* + The maximum length of a packed record is less than this + length. We use this value instead of the supplied length + when allocating memory for records, since we don't know how + the memory will be used in future allocations. + + Since table->s->reclength is for unpacked records, we have + to add two bytes for each field, which can potentially be + added to hold the length of a packed field. + */ + size_t const maxlen= table->s->reclength + 2 * table->s->fields; + + /* + Allocate memory for two records if memory hasn't been + allocated. We allocate memory for two records so that it can + be used when processing update rows as well. + */ + if (table->write_row_record == 0) + table->write_row_record= + (uchar *) alloc_root(&table->mem_root, 2 * maxlen); + m_memory= table->write_row_record; + m_release_memory_on_destruction= FALSE; + } + else + { + m_memory= (uchar *) my_malloc(total_length, MYF(MY_WME)); + m_release_memory_on_destruction= TRUE; + } + } + +#ifndef DBUG_OFF + mutable bool m_alloc_checked; +#endif + bool m_release_memory_on_destruction; + uchar *m_memory; + uchar *m_ptr[2]; + }; +} + + +int THD::binlog_write_row(TABLE* table, bool is_trans, + MY_BITMAP const* cols, size_t colcnt, + uchar const *record) +{ + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); + + /* + Pack records into format for transfer. We are allocating more + memory than needed, but that doesn't matter. + */ + Row_data_memory memory(table, max_row_length(table, record)); + if (!memory.has_memory()) + return HA_ERR_OUT_OF_MEM; + + uchar *row_data= memory.slot(0); + + size_t const len= pack_row(table, cols, row_data, record); + + Rows_log_event* const ev= + binlog_prepare_pending_rows_event(table, server_id, cols, colcnt, + len, is_trans, + static_cast(0)); + + if (unlikely(ev == 0)) + return HA_ERR_OUT_OF_MEM; + + return ev->add_row_data(row_data, len); +} + +int THD::binlog_update_row(TABLE* table, bool is_trans, + MY_BITMAP const* cols, size_t colcnt, + const uchar *before_record, + const uchar *after_record) +{ + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); + + size_t const before_maxlen = max_row_length(table, before_record); + size_t const after_maxlen = max_row_length(table, after_record); + + Row_data_memory row_data(table, before_maxlen, after_maxlen); + if (!row_data.has_memory()) + return HA_ERR_OUT_OF_MEM; + + uchar *before_row= row_data.slot(0); + uchar *after_row= row_data.slot(1); + + size_t const before_size= pack_row(table, cols, before_row, + before_record); + size_t const after_size= pack_row(table, cols, after_row, + after_record); + + /* + Don't print debug messages when running valgrind since they can + trigger false warnings. + */ +#ifndef HAVE_purify + DBUG_DUMP("before_record", before_record, table->s->reclength); + DBUG_DUMP("after_record", after_record, table->s->reclength); + DBUG_DUMP("before_row", before_row, before_size); + DBUG_DUMP("after_row", after_row, after_size); +#endif + + Rows_log_event* const ev= + binlog_prepare_pending_rows_event(table, server_id, cols, colcnt, + before_size + after_size, is_trans, + static_cast(0)); + + if (unlikely(ev == 0)) + return HA_ERR_OUT_OF_MEM; + + return + ev->add_row_data(before_row, before_size) || + ev->add_row_data(after_row, after_size); +} + +int THD::binlog_delete_row(TABLE* table, bool is_trans, + MY_BITMAP const* cols, size_t colcnt, + uchar const *record) +{ + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); + + /* + Pack records into format for transfer. We are allocating more + memory than needed, but that doesn't matter. + */ + Row_data_memory memory(table, max_row_length(table, record)); + if (unlikely(!memory.has_memory())) + return HA_ERR_OUT_OF_MEM; + + uchar *row_data= memory.slot(0); + + size_t const len= pack_row(table, cols, row_data, record); + + Rows_log_event* const ev= + binlog_prepare_pending_rows_event(table, server_id, cols, colcnt, + len, is_trans, + static_cast(0)); + + if (unlikely(ev == 0)) + return HA_ERR_OUT_OF_MEM; + + return ev->add_row_data(row_data, len); +} + + +int THD::binlog_remove_pending_rows_event(bool clear_maps) +{ + DBUG_ENTER("THD::binlog_remove_pending_rows_event"); + + if (!mysql_bin_log.is_open()) + DBUG_RETURN(0); + + mysql_bin_log.remove_pending_rows_event(this); + + if (clear_maps) + binlog_table_maps= 0; + + DBUG_RETURN(0); +} + +int THD::binlog_flush_pending_rows_event(bool stmt_end) +{ + DBUG_ENTER("THD::binlog_flush_pending_rows_event"); + /* + We shall flush the pending event even if we are not in row-based + mode: it might be the case that we left row-based mode before + flushing anything (e.g., if we have explicitly locked tables). + */ + if (!mysql_bin_log.is_open()) + DBUG_RETURN(0); + + /* + Mark the event as the last event of a statement if the stmt_end + flag is set. + */ + int error= 0; + if (Rows_log_event *pending= binlog_get_pending_rows_event()) + { + if (stmt_end) + { + pending->set_flags(Rows_log_event::STMT_END_F); + pending->flags|= LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F; + binlog_table_maps= 0; + } + + error= mysql_bin_log.flush_and_set_pending_rows_event(this, 0); + } + + DBUG_RETURN(error); +} + + +#if !defined(DBUG_OFF) && !defined(_lint) +static const char * +show_query_type(THD::enum_binlog_query_type qtype) +{ + switch (qtype) { + case THD::ROW_QUERY_TYPE: + return "ROW"; + case THD::STMT_QUERY_TYPE: + return "STMT"; + case THD::MYSQL_QUERY_TYPE: + return "MYSQL"; + case THD::QUERY_TYPE_COUNT: + default: + DBUG_ASSERT(0 <= qtype && qtype < THD::QUERY_TYPE_COUNT); + } + static char buf[64]; + sprintf(buf, "UNKNOWN#%d", qtype); + return buf; +} +#endif + + +/* + Member function that will log query, either row-based or + statement-based depending on the value of the 'current_stmt_binlog_row_based' + the value of the 'qtype' flag. + + This function should be called after the all calls to ha_*_row() + functions have been issued, but before tables are unlocked and + closed. + + OBSERVE + There shall be no writes to any system table after calling + binlog_query(), so these writes has to be moved to before the call + of binlog_query() for correct functioning. + + This is necessesary not only for RBR, but the master might crash + after binlogging the query but before changing the system tables. + This means that the slave and the master are not in the same state + (after the master has restarted), so therefore we have to + eliminate this problem. + + RETURN VALUE + Error code, or 0 if no error. +*/ +int THD::binlog_query(THD::enum_binlog_query_type qtype, char const *query_arg, + ulong query_len, bool is_trans, bool suppress_use, + int errcode) +{ + DBUG_ENTER("THD::binlog_query"); + DBUG_PRINT("enter", ("qtype: %s query: '%s'", + show_query_type(qtype), query_arg)); + DBUG_ASSERT(query_arg && mysql_bin_log.is_open()); + + /* + If we are not in prelocked mode, mysql_unlock_tables() will be + called after this binlog_query(), so we have to flush the pending + rows event with the STMT_END_F set to unlock all tables at the + slave side as well. + + If we are in prelocked mode, the flushing will be done inside the + top-most close_thread_tables(). + */ + if (this->prelocked_mode == NON_PRELOCKED) + if (int error= binlog_flush_pending_rows_event(TRUE)) + DBUG_RETURN(error); + + /* + If we are in statement mode and trying to log an unsafe statement, + we should print a warning. + */ + if (sql_log_bin_toplevel && lex->is_stmt_unsafe() && + variables.binlog_format == BINLOG_FORMAT_STMT && + binlog_filter->db_ok(this->db)) + { + /* + A warning can be elevated a error when STRICT sql mode. + But we don't want to elevate binlog warning to error here. + */ + push_warning(this, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_BINLOG_UNSAFE_STATEMENT, + ER(ER_BINLOG_UNSAFE_STATEMENT)); + if (global_system_variables.log_warnings && + !(binlog_flags & BINLOG_FLAG_UNSAFE_STMT_PRINTED)) + { + sql_print_warning("%s Statement: %.*s", + ER(ER_BINLOG_UNSAFE_STATEMENT), + MYSQL_ERRMSG_SIZE, query_arg); + binlog_flags|= BINLOG_FLAG_UNSAFE_STMT_PRINTED; + } + } + + switch (qtype) { + case THD::ROW_QUERY_TYPE: + DBUG_PRINT("debug", + ("current_stmt_binlog_row_based: %d", + current_stmt_binlog_row_based)); + if (current_stmt_binlog_row_based) + DBUG_RETURN(0); + /* Otherwise, we fall through */ + case THD::MYSQL_QUERY_TYPE: + /* + Using this query type is a conveniece hack, since we have been + moving back and forth between using RBR for replication of + system tables and not using it. + + Make sure to change in check_table_binlog_row_based() according + to how you treat this. + */ + case THD::STMT_QUERY_TYPE: + /* + The MYSQL_LOG::write() function will set the STMT_END_F flag and + flush the pending rows event if necessary. + */ + { + Query_log_event qinfo(this, query_arg, query_len, is_trans, suppress_use, + errcode); + qinfo.flags|= LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F; + /* + Binlog table maps will be irrelevant after a Query_log_event + (they are just removed on the slave side) so after the query + log event is written to the binary log, we pretend that no + table maps were written. + */ + int error= mysql_bin_log.write(&qinfo); + binlog_table_maps= 0; + DBUG_RETURN(error); + } + break; + + case THD::QUERY_TYPE_COUNT: + default: + DBUG_ASSERT(0 <= qtype && qtype < QUERY_TYPE_COUNT); + } + DBUG_RETURN(0); +} + +bool Discrete_intervals_list::append(ulonglong start, ulonglong val, + ulonglong incr) +{ + DBUG_ENTER("Discrete_intervals_list::append"); + /* first, see if this can be merged with previous */ + if ((head == NULL) || tail->merge_if_contiguous(start, val, incr)) + { + /* it cannot, so need to add a new interval */ + Discrete_interval *new_interval= new Discrete_interval(start, val, incr); + DBUG_RETURN(append(new_interval)); + } + DBUG_RETURN(0); +} + +bool Discrete_intervals_list::append(Discrete_interval *new_interval) +{ + DBUG_ENTER("Discrete_intervals_list::append"); + if (unlikely(new_interval == NULL)) + DBUG_RETURN(1); + DBUG_PRINT("info",("adding new auto_increment interval")); + if (head == NULL) + head= current= new_interval; + else + tail->next= new_interval; + tail= new_interval; + elements++; + DBUG_RETURN(0); +} + +#endif /* !defined(MYSQL_CLIENT) */ diff --git a/dbcon/mysql/sql_class.h b/dbcon/mysql/sql_class.h new file mode 100644 index 00000000..6d8429d1 --- /dev/null +++ b/dbcon/mysql/sql_class.h @@ -0,0 +1,3152 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Classes in mysql */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +#include "log.h" +#include "rpl_tblmap.h" + +/** + An interface that is used to take an action when + the locking module notices that a table version has changed + since the last execution. "Table" here may refer to any kind of + table -- a base table, a temporary table, a view or an + information schema table. + + When we open and lock tables for execution of a prepared + statement, we must verify that they did not change + since statement prepare. If some table did change, the statement + parse tree *may* be no longer valid, e.g. in case it contains + optimizations that depend on table metadata. + + This class provides an interface (a method) that is + invoked when such a situation takes place. + The implementation of the method simply reports an error, but + the exact details depend on the nature of the SQL statement. + + At most 1 instance of this class is active at a time, in which + case THD::m_reprepare_observer is not NULL. + + @sa check_and_update_table_version() for details of the + version tracking algorithm + + @sa Open_tables_state::m_reprepare_observer for the life cycle + of metadata observers. +*/ + +class Reprepare_observer +{ +public: + /** + Check if a change of metadata is OK. In future + the signature of this method may be extended to accept the old + and the new versions, but since currently the check is very + simple, we only need the THD to report an error. + */ + bool report_error(THD *thd); + bool is_invalidated() const { return m_invalidated; } + void reset_reprepare_observer() { m_invalidated= FALSE; } +private: + bool m_invalidated; +}; + + +class Relay_log_info; + +class Query_log_event; +class Load_log_event; +class Slave_log_event; +class sp_rcontext; +class sp_cache; +class Parser_state; +class Rows_log_event; + +enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE }; +enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME }; +enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE }; +enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON, + DELAY_KEY_WRITE_ALL }; +enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT, + SLAVE_EXEC_MODE_IDEMPOTENT, + SLAVE_EXEC_MODE_LAST_BIT}; +enum enum_mark_columns +{ MARK_COLUMNS_NONE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE}; + +extern char internal_table_name[2]; +extern char empty_c_string[1]; +extern MYSQL_PLUGIN_IMPORT const char **errmesg; + +#define TC_LOG_PAGE_SIZE 8192 +#define TC_LOG_MIN_SIZE (3*TC_LOG_PAGE_SIZE) + +#define TC_HEURISTIC_RECOVER_COMMIT 1 +#define TC_HEURISTIC_RECOVER_ROLLBACK 2 +extern uint tc_heuristic_recover; + +typedef struct st_user_var_events +{ + user_var_entry *user_var_event; + char *value; + ulong length; + Item_result type; + uint charset_number; +} BINLOG_USER_VAR_EVENT; + +#define RP_LOCK_LOG_IS_ALREADY_LOCKED 1 +#define RP_FORCE_ROTATE 2 + +/* + The COPY_INFO structure is used by INSERT/REPLACE code. + The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY + UPDATE code: + If a row is inserted then the copied variable is incremented. + If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the + new data differs from the old one then the copied and the updated + variables are incremented. + The touched variable is incremented if a row was touched by the update part + of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row + was actually changed or not. +*/ +typedef struct st_copy_info { + ha_rows records; /**< Number of processed records */ + ha_rows deleted; /**< Number of deleted records */ + ha_rows updated; /**< Number of updated records */ + ha_rows copied; /**< Number of copied records */ + ha_rows error_count; + ha_rows touched; /* Number of touched records */ + enum enum_duplicates handle_duplicates; + int escape_char, last_errno; + bool ignore; + /* for INSERT ... UPDATE */ + List *update_fields; + List *update_values; + /* for VIEW ... WITH CHECK OPTION */ + TABLE_LIST *view; +} COPY_INFO; + + +class Key_part_spec :public Sql_alloc { +public: + const char *field_name; + uint length; + Key_part_spec(const char *name,uint len=0) :field_name(name), length(len) {} + bool operator==(const Key_part_spec& other) const; + /** + Construct a copy of this Key_part_spec. field_name is copied + by-pointer as it is known to never change. At the same time + 'length' may be reset in mysql_prepare_create_table, and this + is why we supply it with a copy. + + @return If out of memory, 0 is returned and an error is set in + THD. + */ + Key_part_spec *clone(MEM_ROOT *mem_root) const + { return new (mem_root) Key_part_spec(*this); } +}; + + +class Alter_drop :public Sql_alloc { +public: + enum drop_type {KEY, COLUMN }; + const char *name; + enum drop_type type; + Alter_drop(enum drop_type par_type,const char *par_name) + :name(par_name), type(par_type) {} + /** + Used to make a clone of this object for ALTER/CREATE TABLE + @sa comment for Key_part_spec::clone + */ + Alter_drop *clone(MEM_ROOT *mem_root) const + { return new (mem_root) Alter_drop(*this); } +}; + + +class Alter_column :public Sql_alloc { +public: + const char *name; + Item *def; + Alter_column(const char *par_name,Item *literal) + :name(par_name), def(literal) {} + /** + Used to make a clone of this object for ALTER/CREATE TABLE + @sa comment for Key_part_spec::clone + */ + Alter_column *clone(MEM_ROOT *mem_root) const + { return new (mem_root) Alter_column(*this); } +}; + + +class Key :public Sql_alloc { +public: + enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY}; + enum Keytype type; + KEY_CREATE_INFO key_create_info; + List columns; + const char *name; + bool generated; + + Key(enum Keytype type_par, const char *name_arg, + KEY_CREATE_INFO *key_info_arg, + bool generated_arg, List &cols) + :type(type_par), key_create_info(*key_info_arg), columns(cols), + name(name_arg), generated(generated_arg) + {} + Key(const Key &rhs, MEM_ROOT *mem_root); + virtual ~Key() {} + /* Equality comparison of keys (ignoring name) */ + friend bool foreign_key_prefix(Key *a, Key *b); + /** + Used to make a clone of this object for ALTER/CREATE TABLE + @sa comment for Key_part_spec::clone + */ + virtual Key *clone(MEM_ROOT *mem_root) const + { return new (mem_root) Key(*this, mem_root); } +}; + +class Table_ident; + +class Foreign_key: public Key { +public: + enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL, + FK_MATCH_PARTIAL, FK_MATCH_SIMPLE}; + enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE, + FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT}; + + Table_ident *ref_table; + List ref_columns; + uint delete_opt, update_opt, match_opt; + Foreign_key(const char *name_arg, List &cols, + Table_ident *table, List &ref_cols, + uint delete_opt_arg, uint update_opt_arg, uint match_opt_arg) + :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols), + ref_table(table), ref_columns(ref_cols), + delete_opt(delete_opt_arg), update_opt(update_opt_arg), + match_opt(match_opt_arg) + {} + Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root); + /** + Used to make a clone of this object for ALTER/CREATE TABLE + @sa comment for Key_part_spec::clone + */ + virtual Key *clone(MEM_ROOT *mem_root) const + { return new (mem_root) Foreign_key(*this, mem_root); } +}; + +typedef struct st_mysql_lock +{ + TABLE **table; + uint table_count,lock_count; + THR_LOCK_DATA **locks; +} MYSQL_LOCK; + + +class LEX_COLUMN : public Sql_alloc +{ +public: + String column; + uint rights; + LEX_COLUMN (const String& x,const uint& y ): column (x),rights (y) {} +}; + +#include "sql_lex.h" /* Must be here */ + +class Delayed_insert; +class select_result; +class Time_zone; + +#define THD_SENTRY_MAGIC 0xfeedd1ff +#define THD_SENTRY_GONE 0xdeadbeef + +#define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC) + +struct system_variables +{ + /* + How dynamically allocated system variables are handled: + + The global_system_variables and max_system_variables are "authoritative" + They both should have the same 'version' and 'size'. + When attempting to access a dynamic variable, if the session version + is out of date, then the session version is updated and realloced if + neccessary and bytes copied from global to make up for missing data. + */ + ulong dynamic_variables_version; + char* dynamic_variables_ptr; + uint dynamic_variables_head; /* largest valid variable offset */ + uint dynamic_variables_size; /* how many bytes are in use */ + + ulonglong myisam_max_extra_sort_file_size; + ulonglong myisam_max_sort_file_size; + ulonglong max_heap_table_size; + ulonglong tmp_table_size; + ulonglong long_query_time; + ha_rows select_limit; + ha_rows max_join_size; + ulong auto_increment_increment, auto_increment_offset; + ulong bulk_insert_buff_size; + ulong join_buff_size; + ulong max_allowed_packet; + ulong max_error_count; + ulong max_length_for_sort_data; + ulong max_sort_length; + ulong max_tmp_tables; + ulong max_insert_delayed_threads; + ulong min_examined_row_limit; + ulong multi_range_count; + ulong myisam_repair_threads; + ulong myisam_sort_buff_size; + ulong myisam_stats_method; + ulong net_buffer_length; + ulong net_interactive_timeout; + ulong net_read_timeout; + ulong net_retry_count; + ulong net_wait_timeout; + ulong net_write_timeout; + ulong optimizer_prune_level; + ulong optimizer_search_depth; + /* A bitmap for switching optimizations on/off */ + ulong optimizer_switch; + ulong preload_buff_size; + ulong profiling_history_size; + ulong query_cache_type; + ulong read_buff_size; + ulong read_rnd_buff_size; +/* InfiniDB */ + ulong infinidb_vtable_mode; + ulong infinidb_decimal_scale; + my_bool infinidb_use_decimal_scale; + my_bool infinidb_ordered_only; + ulong infinidb_string_scan_threshold; + ulong infinidb_compression_type; + my_bool infinidb_varbin_always_hex; +/* InfiniDB */ + ulong div_precincrement; + ulong sortbuff_size; + ulong thread_handling; + ulong tx_isolation; + ulong completion_type; + /* Determines which non-standard SQL behaviour should be enabled */ + ulong sql_mode; + ulong max_sp_recursion_depth; + /* check of key presence in updatable view */ + ulong updatable_views_with_limit; + ulong default_week_format; + ulong max_seeks_for_key; + ulong range_alloc_block_size; + ulong query_alloc_block_size; + ulong query_prealloc_size; + ulong trans_alloc_block_size; + ulong trans_prealloc_size; + ulong log_warnings; + ulong group_concat_max_len; + ulong ndb_autoincrement_prefetch_sz; + ulong ndb_index_stat_cache_entries; + ulong ndb_index_stat_update_freq; + ulong binlog_format; // binlog format for this thd (see enum_binlog_format) + /* + In slave thread we need to know in behalf of which + thread the query is being run to replicate temp tables properly + */ + my_thread_id pseudo_thread_id; + + my_bool low_priority_updates; + my_bool new_mode; + /* + compatibility option: + - index usage hints (USE INDEX without a FOR clause) behave as in 5.0 + */ + my_bool old_mode; + my_bool query_cache_wlock_invalidate; + my_bool engine_condition_pushdown; + my_bool keep_files_on_create; + my_bool ndb_force_send; + my_bool ndb_use_copying_alter_table; + my_bool ndb_use_exact_count; + my_bool ndb_use_transactions; + my_bool ndb_index_stat_enable; + + my_bool old_alter_table; + my_bool old_passwords; + + plugin_ref table_plugin; + + /* Only charset part of these variables is sensible */ + CHARSET_INFO *character_set_filesystem; + CHARSET_INFO *character_set_client; + CHARSET_INFO *character_set_results; + + /* Both charset and collation parts of these variables are important */ + CHARSET_INFO *collation_server; + CHARSET_INFO *collation_database; + CHARSET_INFO *collation_connection; + + /* Locale Support */ + MY_LOCALE *lc_time_names; + + Time_zone *time_zone; + + /* DATE, DATETIME and MYSQL_TIME formats */ + DATE_TIME_FORMAT *date_format; + DATE_TIME_FORMAT *datetime_format; + DATE_TIME_FORMAT *time_format; + my_bool sysdate_is_now; +}; + + +/* per thread status variables */ + +typedef struct system_status_var +{ + ulonglong bytes_received; + ulonglong bytes_sent; + ulong com_other; + ulong com_stat[(uint) SQLCOM_END]; + ulong created_tmp_disk_tables; + ulong created_tmp_tables; + ulong ha_commit_count; + ulong ha_delete_count; + ulong ha_read_first_count; + ulong ha_read_last_count; + ulong ha_read_key_count; + ulong ha_read_next_count; + ulong ha_read_prev_count; + ulong ha_read_rnd_count; + ulong ha_read_rnd_next_count; + ulong ha_rollback_count; + ulong ha_update_count; + ulong ha_write_count; + ulong ha_prepare_count; + ulong ha_discover_count; + ulong ha_savepoint_count; + ulong ha_savepoint_rollback_count; + + /* KEY_CACHE parts. These are copies of the original */ + ulong key_blocks_changed; + ulong key_blocks_used; + ulong key_cache_r_requests; + ulong key_cache_read; + ulong key_cache_w_requests; + ulong key_cache_write; + /* END OF KEY_CACHE parts */ + + ulong net_big_packet_count; + ulong opened_tables; + ulong opened_shares; + ulong select_full_join_count; + ulong select_full_range_join_count; + ulong select_range_count; + ulong select_range_check_count; + ulong select_scan_count; + ulong long_query_count; + ulong filesort_merge_passes; + ulong filesort_range_count; + ulong filesort_rows; + ulong filesort_scan_count; + /* Prepared statements and binary protocol */ + ulong com_stmt_prepare; + ulong com_stmt_reprepare; + ulong com_stmt_execute; + ulong com_stmt_send_long_data; + ulong com_stmt_fetch; + ulong com_stmt_reset; + ulong com_stmt_close; + /* + Number of statements sent from the client + */ + ulong questions; + /* + IMPORTANT! + SEE last_system_status_var DEFINITION BELOW. + Below 'last_system_status_var' are all variables which doesn't make any + sense to add to the /global/ status variable counter. + Status variables which it does not make sense to add to + global status variable counter + */ + double last_query_cost; +} STATUS_VAR; + +/* + This is used for 'SHOW STATUS'. It must be updated to the last ulong + variable in system_status_var which is makes sens to add to the global + counter +*/ + +#define last_system_status_var questions + +void mark_transaction_to_rollback(THD *thd, bool all); + +#ifdef MYSQL_SERVER + +void free_tmp_table(THD *thd, TABLE *entry); + + +/* The following macro is to make init of Query_arena simpler */ +#ifndef DBUG_OFF +#define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE; +#else +#define INIT_ARENA_DBUG_INFO +#endif + +class Query_arena +{ +public: + /* + List of items created in the parser for this query. Every item puts + itself to the list on creation (see Item::Item() for details)) + */ + Item *free_list; + MEM_ROOT *mem_root; // Pointer to current memroot +#ifndef DBUG_OFF + bool is_backup_arena; /* True if this arena is used for backup. */ + bool is_reprepared; +#endif + /* + The states relfects three diffrent life cycles for three + different types of statements: + Prepared statement: INITIALIZED -> PREPARED -> EXECUTED. + Stored procedure: INITIALIZED_FOR_SP -> EXECUTED. + Other statements: CONVENTIONAL_EXECUTION never changes. + */ + enum enum_state + { + INITIALIZED= 0, INITIALIZED_FOR_SP= 1, PREPARED= 2, + CONVENTIONAL_EXECUTION= 3, EXECUTED= 4, ERROR= -1 + }; + + enum_state state; + + /* We build without RTTI, so dynamic_cast can't be used. */ + enum Type + { + STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE + }; + + Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) : + free_list(0), mem_root(mem_root_arg), state(state_arg) + { INIT_ARENA_DBUG_INFO; } + /* + This constructor is used only when Query_arena is created as + backup storage for another instance of Query_arena. + */ + Query_arena() { INIT_ARENA_DBUG_INFO; } + + virtual Type type() const; + virtual ~Query_arena() {}; + + inline bool is_stmt_prepare() const { return state == INITIALIZED; } + inline bool is_first_sp_execute() const + { return state == INITIALIZED_FOR_SP; } + inline bool is_stmt_prepare_or_first_sp_execute() const + { return (int)state < (int)PREPARED; } + inline bool is_first_stmt_execute() const { return state == PREPARED; } + inline bool is_stmt_execute() const + { return state == PREPARED || state == EXECUTED; } + inline bool is_conventional() const + { return state == CONVENTIONAL_EXECUTION; } + + inline void* alloc(size_t size) { return alloc_root(mem_root,size); } + inline void* calloc(size_t size) + { + void *ptr; + if ((ptr=alloc_root(mem_root,size))) + bzero(ptr, size); + return ptr; + } + inline char *strdup(const char *str) + { return strdup_root(mem_root,str); } + inline char *strmake(const char *str, size_t size) + { return strmake_root(mem_root,str,size); } + inline void *memdup(const void *str, size_t size) + { return memdup_root(mem_root,str,size); } + inline void *memdup_w_gap(const void *str, size_t size, uint gap) + { + void *ptr; + if ((ptr= alloc_root(mem_root,size+gap))) + memcpy(ptr,str,size); + return ptr; + } + + void set_query_arena(Query_arena *set); + + void free_items(); + /* Close the active state associated with execution of this statement */ + virtual void cleanup_stmt(); +}; + + +class Server_side_cursor; + +/** + @class Statement + @brief State of a single command executed against this connection. + + One connection can contain a lot of simultaneously running statements, + some of which could be: + - prepared, that is, contain placeholders, + - opened as cursors. We maintain 1 to 1 relationship between + statement and cursor - if user wants to create another cursor for his + query, we create another statement for it. + To perform some action with statement we reset THD part to the state of + that statement, do the action, and then save back modified state from THD + to the statement. It will be changed in near future, and Statement will + be used explicitly. +*/ + +class Statement: public ilink, public Query_arena +{ + Statement(const Statement &rhs); /* not implemented: */ + Statement &operator=(const Statement &rhs); /* non-copyable */ +public: + /* + Uniquely identifies each statement object in thread scope; change during + statement lifetime. FIXME: must be const + */ + ulong id; + + /* + MARK_COLUMNS_NONE: Means mark_used_colums is not set and no indicator to + handler of fields used is set + MARK_COLUMNS_READ: Means a bit in read set is set to inform handler + that the field is to be read. If field list contains + duplicates, then thd->dup_field is set to point + to the last found duplicate. + MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler + that it needs to update this field in write_row + and update_row. + */ + enum enum_mark_columns mark_used_columns; + + LEX_STRING name; /* name for named prepared statements */ + LEX *lex; // parse tree descriptor + /* + Points to the query associated with this statement. It's const, but + we need to declare it char * because all table handlers are written + in C and need to point to it. + + Note that if we set query = NULL, we must at the same time set + query_length = 0, and protect the whole operation with + LOCK_thd_data mutex. To avoid crashes in races, if we do not + know that thd->query cannot change at the moment, we should print + thd->query like this: + (1) reserve the LOCK_thd_data mutex; + (2) print or copy the value of query and query_length + (3) release LOCK_thd_data mutex. + This printing is needed at least in SHOW PROCESSLIST and SHOW + ENGINE INNODB STATUS. + */ + char *query; + uint32 query_length; // current query length + Server_side_cursor *cursor; + + /** + Name of the current (default) database. + + If there is the current (default) database, "db" contains its name. If + there is no current (default) database, "db" is NULL and "db_length" is + 0. In other words, "db", "db_length" must either be NULL, or contain a + valid database name. + + @note this attribute is set and alloced by the slave SQL thread (for + the THD of that thread); that thread is (and must remain, for now) the + only responsible for freeing this member. + */ + + char *db; + size_t db_length; + +public: + + /* This constructor is called for backup statements */ + Statement() {} + + Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg, + enum enum_state state_arg, ulong id_arg); + virtual ~Statement(); + + /* Assign execution context (note: not all members) of given stmt to self */ + virtual void set_statement(Statement *stmt); + void set_n_backup_statement(Statement *stmt, Statement *backup); + void restore_backup_statement(Statement *stmt, Statement *backup); + /* return class type */ + virtual Type type() const; +}; + + +/** + Container for all statements created/used in a connection. + Statements in Statement_map have unique Statement::id (guaranteed by id + assignment in Statement::Statement) + Non-empty statement names are unique too: attempt to insert a new statement + with duplicate name causes older statement to be deleted + + Statements are auto-deleted when they are removed from the map and when the + map is deleted. +*/ + +class Statement_map +{ +public: + Statement_map(); + + int insert(THD *thd, Statement *statement); + + Statement *find_by_name(LEX_STRING *name) + { + Statement *stmt; + stmt= (Statement*)hash_search(&names_hash, (uchar*)name->str, + name->length); + return stmt; + } + + Statement *find(ulong id) + { + if (last_found_statement == 0 || id != last_found_statement->id) + { + Statement *stmt; + stmt= (Statement *) hash_search(&st_hash, (uchar *) &id, sizeof(id)); + if (stmt && stmt->name.str) + return NULL; + last_found_statement= stmt; + } + return last_found_statement; + } + /* + Close all cursors of this connection that use tables of a storage + engine that has transaction-specific state and therefore can not + survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed. + */ + void close_transient_cursors(); + void erase(Statement *statement); + /* Erase all statements (calls Statement destructor) */ + void reset(); + ~Statement_map(); +private: + HASH st_hash; + HASH names_hash; + I_List transient_cursor_list; + Statement *last_found_statement; +}; + +struct st_savepoint { + struct st_savepoint *prev; + char *name; + uint length; + Ha_trx_info *ha_list; +}; + +enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY}; +extern const char *xa_state_names[]; + +typedef struct st_xid_state { + /* For now, this is only used to catch duplicated external xids */ + XID xid; // transaction identifier + enum xa_states xa_state; // used by external XA only + bool in_thd; + /* Error reported by the Resource Manager (RM) to the Transaction Manager. */ + uint rm_error; +} XID_STATE; + +extern pthread_mutex_t LOCK_xid_cache; +extern HASH xid_cache; +bool xid_cache_init(void); +void xid_cache_free(void); +XID_STATE *xid_cache_search(XID *xid); +bool xid_cache_insert(XID *xid, enum xa_states xa_state); +bool xid_cache_insert(XID_STATE *xid_state); +void xid_cache_delete(XID_STATE *xid_state); + +/** + @class Security_context + @brief A set of THD members describing the current authenticated user. +*/ + +class Security_context { +public: + Security_context() {} /* Remove gcc warning */ + /* + host - host of the client + user - user of the client, set to NULL until the user has been read from + the connection + priv_user - The user privilege we are using. May be "" for anonymous user. + ip - client IP + */ + char *host, *user, *priv_user, *ip; + /* The host privilege we are using */ + char priv_host[MAX_HOSTNAME]; + /* points to host if host is available, otherwise points to ip */ + const char *host_or_ip; + ulong master_access; /* Global privileges from mysql.user */ + ulong db_access; /* Privileges for current db */ + + void init(); + void destroy(); + void skip_grants(); + inline char *priv_host_name() + { + return (*priv_host ? priv_host : (char *)"%"); + } + + bool set_user(char *user_arg); + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + bool + change_security_context(THD *thd, + LEX_STRING *definer_user, + LEX_STRING *definer_host, + LEX_STRING *db, + Security_context **backup); + + void + restore_security_context(THD *thd, Security_context *backup); +#endif + bool user_matches(Security_context *); +}; + + +/** + A registry for item tree transformations performed during + query optimization. We register only those changes which require + a rollback to re-execute a prepared statement or stored procedure + yet another time. +*/ + +struct Item_change_record; +typedef I_List Item_change_list; + + +/** + Type of prelocked mode. + See comment for THD::prelocked_mode for complete description. +*/ + +enum prelocked_mode_type {NON_PRELOCKED= 0, PRELOCKED= 1, + PRELOCKED_UNDER_LOCK_TABLES= 2}; + + +/** + Class that holds information about tables which were opened and locked + by the thread. It is also used to save/restore this information in + push_open_tables_state()/pop_open_tables_state(). +*/ + +class Open_tables_state +{ +public: + /** + As part of class THD, this member is set during execution + of a prepared statement. When it is set, it is used + by the locking subsystem to report a change in table metadata. + + When Open_tables_state part of THD is reset to open + a system or INFORMATION_SCHEMA table, the member is cleared + to avoid spurious ER_NEED_REPREPARE errors -- system and + INFORMATION_SCHEMA tables are not subject to metadata version + tracking. + @sa check_and_update_table_version() + */ + Reprepare_observer *m_reprepare_observer; + + /** + List of regular tables in use by this thread. Contains temporary and + base tables that were opened with @see open_tables(). + */ + TABLE *open_tables; + /** + List of temporary tables used by this thread. Contains user-level + temporary tables, created with CREATE TEMPORARY TABLE, and + internal temporary tables, created, e.g., to resolve a SELECT, + or for an intermediate table used in ALTER. + XXX Why are internal temporary tables added to this list? + */ + TABLE *temporary_tables; + /** + List of tables that were opened with HANDLER OPEN and are + still in use by this thread. + */ + TABLE *handler_tables; + TABLE *derived_tables; + /* + During a MySQL session, one can lock tables in two modes: automatic + or manual. In automatic mode all necessary tables are locked just before + statement execution, and all acquired locks are stored in 'lock' + member. Unlocking takes place automatically as well, when the + statement ends. + Manual mode comes into play when a user issues a 'LOCK TABLES' + statement. In this mode the user can only use the locked tables. + Trying to use any other tables will give an error. The locked tables are + stored in 'locked_tables' member. Manual locking is described in + the 'LOCK_TABLES' chapter of the MySQL manual. + See also lock_tables() for details. + */ + MYSQL_LOCK *lock; + /* + Tables that were locked with explicit or implicit LOCK TABLES. + (Implicit LOCK TABLES happens when we are prelocking tables for + execution of statement which uses stored routines. See description + THD::prelocked_mode for more info.) + */ + MYSQL_LOCK *locked_tables; + + /* + CREATE-SELECT keeps an extra lock for the table being + created. This field is used to keep the extra lock available for + lower level routines, which would otherwise miss that lock. + */ + MYSQL_LOCK *extra_lock; + + /* + prelocked_mode_type enum and prelocked_mode member are used for + indicating whenever "prelocked mode" is on, and what type of + "prelocked mode" is it. + + Prelocked mode is used for execution of queries which explicitly + or implicitly (via views or triggers) use functions, thus may need + some additional tables (mentioned in query table list) for their + execution. + + First open_tables() call for such query will analyse all functions + used by it and add all additional tables to table its list. It will + also mark this query as requiring prelocking. After that lock_tables() + will issue implicit LOCK TABLES for the whole table list and change + thd::prelocked_mode to non-0. All queries called in functions invoked + by the main query will use prelocked tables. Non-0 prelocked_mode + will also surpress mentioned analysys in those queries thus saving + cycles. Prelocked mode will be turned off once close_thread_tables() + for the main query will be called. + + Note: Since not all "tables" present in table list are really locked + thd::prelocked_mode does not imply thd::locked_tables. + */ + prelocked_mode_type prelocked_mode; + ulong version; + uint current_tablenr; + + enum enum_flags { + BACKUPS_AVAIL = (1U << 0) /* There are backups available */ + }; + + /* + Flags with information about the open tables state. + */ + uint state_flags; + + /* + This constructor serves for creation of Open_tables_state instances + which are used as backup storage. + */ + Open_tables_state() : state_flags(0U) { } + + Open_tables_state(ulong version_arg); + + void set_open_tables_state(Open_tables_state *state) + { + *this= *state; + } + + void reset_open_tables_state() + { + open_tables= temporary_tables= handler_tables= derived_tables= 0; + extra_lock= lock= locked_tables= 0; + prelocked_mode= NON_PRELOCKED; + state_flags= 0U; + m_reprepare_observer= NULL; + } +}; + +/** + @class Sub_statement_state + @brief Used to save context when executing a function or trigger +*/ + +/* Defines used for Sub_statement_state::in_sub_stmt */ + +#define SUB_STMT_TRIGGER 1 +#define SUB_STMT_FUNCTION 2 + + +class Sub_statement_state +{ +public: + ulonglong options; + ulonglong first_successful_insert_id_in_prev_stmt; + ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row; + Discrete_interval auto_inc_interval_for_cur_row; + Discrete_intervals_list auto_inc_intervals_forced; + ulonglong limit_found_rows; + ha_rows cuted_fields, sent_row_count, examined_row_count; + ulong client_capabilities; + uint in_sub_stmt; + bool enable_slow_log; + bool last_insert_id_used; + SAVEPOINT *savepoints; +}; + + +/* Flags for the THD::system_thread variable */ +enum enum_thread_type +{ + NON_SYSTEM_THREAD= 0, + SYSTEM_THREAD_DELAYED_INSERT= 1, + SYSTEM_THREAD_SLAVE_IO= 2, + SYSTEM_THREAD_SLAVE_SQL= 4, + SYSTEM_THREAD_NDBCLUSTER_BINLOG= 8, + SYSTEM_THREAD_EVENT_SCHEDULER= 16, + SYSTEM_THREAD_EVENT_WORKER= 32 +}; + +inline char const * +show_system_thread(enum_thread_type thread) +{ +#define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME + switch (thread) { + static char buf[64]; + RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD); + RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT); + RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO); + RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL); + RETURN_NAME_AS_STRING(SYSTEM_THREAD_NDBCLUSTER_BINLOG); + RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER); + RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER); + default: + sprintf(buf, "", thread); + return buf; + } +#undef RETURN_NAME_AS_STRING +} + +/** + This class represents the interface for internal error handlers. + Internal error handlers are exception handlers used by the server + implementation. +*/ +class Internal_error_handler +{ +protected: + Internal_error_handler() : + m_prev_internal_handler(NULL) + {} + + virtual ~Internal_error_handler() {} + +public: + /** + Handle an error condition. + This method can be implemented by a subclass to achieve any of the + following: + - mask an error internally, prevent exposing it to the user, + - mask an error and throw another one instead. + When this method returns true, the error condition is considered + 'handled', and will not be propagated to upper layers. + It is the responsability of the code installing an internal handler + to then check for trapped conditions, and implement logic to recover + from the anticipated conditions trapped during runtime. + + This mechanism is similar to C++ try/throw/catch: + - 'try' correspond to THD::push_internal_handler(), + - 'throw' correspond to my_error(), + which invokes my_message_sql(), + - 'catch' correspond to checking how/if an internal handler was invoked, + before removing it from the exception stack with + THD::pop_internal_handler(). + + @param sql_errno the error number + @param level the error level + @param thd the calling thread + @return true if the error is handled + */ + virtual bool handle_error(uint sql_errno, + const char *message, + MYSQL_ERROR::enum_warning_level level, + THD *thd) = 0; +private: + Internal_error_handler *m_prev_internal_handler; + friend class THD; +}; + + +/** + Implements the trivial error handler which cancels all error states + and prevents an SQLSTATE to be set. +*/ + +class Dummy_error_handler : public Internal_error_handler +{ +public: + bool handle_error(uint sql_errno, + const char *message, + MYSQL_ERROR::enum_warning_level level, + THD *thd) + { + /* Ignore error */ + return TRUE; + } +}; + + +/** + Stores status of the currently executed statement. + Cleared at the beginning of the statement, and then + can hold either OK, ERROR, or EOF status. + Can not be assigned twice per statement. +*/ + +class Diagnostics_area +{ +public: + enum enum_diagnostics_status + { + /** The area is cleared at start of a statement. */ + DA_EMPTY= 0, + /** Set whenever one calls my_ok(). */ + DA_OK, + /** Set whenever one calls my_eof(). */ + DA_EOF, + /** Set whenever one calls my_error() or my_message(). */ + DA_ERROR, + /** Set in case of a custom response, such as one from COM_STMT_PREPARE. */ + DA_DISABLED + }; + /** True if status information is sent to the client. */ + bool is_sent; + /** Set to make set_error_status after set_{ok,eof}_status possible. */ + bool can_overwrite_status; + + void set_ok_status(THD *thd, ha_rows affected_rows_arg, + ulonglong last_insert_id_arg, + const char *message); + void set_eof_status(THD *thd); + void set_error_status(THD *thd, uint sql_errno_arg, const char *message_arg); + + void disable_status(); + + void reset_diagnostics_area(); + + bool is_set() const { return m_status != DA_EMPTY; } + bool is_error() const { return m_status == DA_ERROR; } + bool is_eof() const { return m_status == DA_EOF; } + bool is_ok() const { return m_status == DA_OK; } + bool is_disabled() const { return m_status == DA_DISABLED; } + enum_diagnostics_status status() const { return m_status; } + + const char *message() const + { DBUG_ASSERT(m_status == DA_ERROR || m_status == DA_OK); return m_message; } + + uint sql_errno() const + { DBUG_ASSERT(m_status == DA_ERROR); return m_sql_errno; } + + uint server_status() const + { + DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF); + return m_server_status; + } + + ha_rows affected_rows() const + { DBUG_ASSERT(m_status == DA_OK); return m_affected_rows; } + + ulonglong last_insert_id() const + { DBUG_ASSERT(m_status == DA_OK); return m_last_insert_id; } + + uint total_warn_count() const + { + DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF); + return m_total_warn_count; + } + + Diagnostics_area() { reset_diagnostics_area(); } + +private: + /** Message buffer. Can be used by OK or ERROR status. */ + char m_message[MYSQL_ERRMSG_SIZE]; + /** + SQL error number. One of ER_ codes from share/errmsg.txt. + Set by set_error_status. + */ + uint m_sql_errno; + + /** + Copied from thd->server_status when the diagnostics area is assigned. + We need this member as some places in the code use the following pattern: + thd->server_status|= ... + my_eof(thd); + thd->server_status&= ~... + Assigned by OK, EOF or ERROR. + */ + uint m_server_status; + /** + The number of rows affected by the last statement. This is + semantically close to thd->row_count_func, but has a different + life cycle. thd->row_count_func stores the value returned by + function ROW_COUNT() and is cleared only by statements that + update its value, such as INSERT, UPDATE, DELETE and few others. + This member is cleared at the beginning of the next statement. + + We could possibly merge the two, but life cycle of thd->row_count_func + can not be changed. + */ + ha_rows m_affected_rows; + /** + Similarly to the previous member, this is a replacement of + thd->first_successful_insert_id_in_prev_stmt, which is used + to implement LAST_INSERT_ID(). + */ + ulonglong m_last_insert_id; + /** The total number of warnings. */ + uint m_total_warn_count; + enum_diagnostics_status m_status; + /** + @todo: the following THD members belong here: + - warn_list, warn_count, + */ +}; + + +/** + Storage engine specific thread local data. +*/ + +struct Ha_data +{ + /** + Storage engine specific thread local data. + Lifetime: one user connection. + */ + void *ha_ptr; + /** + 0: Life time: one statement within a transaction. If @@autocommit is + on, also represents the entire transaction. + @sa trans_register_ha() + + 1: Life time: one transaction within a connection. + If the storage engine does not participate in a transaction, + this should not be used. + @sa trans_register_ha() + */ + Ha_trx_info ha_info[2]; + + Ha_data() :ha_ptr(NULL) {} +}; + + +/** + @class THD + For each client connection we create a separate thread with THD serving as + a thread/connection descriptor +*/ + +class THD :public Statement, + public Open_tables_state +{ +public: + + struct INFINIDB_VTABLE; // Calpont InfiniDB + + /* Used to execute base64 coded binlog events in MySQL server */ + Relay_log_info* rli_fake; + + /* + Constant for THD::where initialization in the beginning of every query. + + It's needed because we do not save/restore THD::where normally during + primary (non subselect) query execution. + */ + static const char * const DEFAULT_WHERE; + +#ifdef EMBEDDED_LIBRARY + struct st_mysql *mysql; + unsigned long client_stmt_id; + unsigned long client_param_count; + struct st_mysql_bind *client_params; + char *extra_data; + ulong extra_length; + struct st_mysql_data *cur_data; + struct st_mysql_data *first_data; + struct st_mysql_data **data_tail; + void clear_data_list(); + struct st_mysql_data *alloc_new_dataset(); + /* + In embedded server it points to the statement that is processed + in the current query. We store some results directly in statement + fields then. + */ + struct st_mysql_stmt *current_stmt; +#endif + NET net; // client connection descriptor + MEM_ROOT warn_root; // For warnings and errors + Protocol *protocol; // Current protocol + Protocol_text protocol_text; // Normal protocol + Protocol_binary protocol_binary; // Binary protocol + HASH user_vars; // hash for user variables + String packet; // dynamic buffer for network I/O + String convert_buffer; // buffer for charset conversions + struct sockaddr_in remote; // client socket address + struct rand_struct rand; // used for authentication + struct system_variables variables; // Changeable local variables + struct system_status_var status_var; // Per thread statistic vars + struct system_status_var *initial_status_var; /* used by show status */ + THR_LOCK_INFO lock_info; // Locking info of this thread + THR_LOCK_OWNER main_lock_id; // To use for conventional queries + THR_LOCK_OWNER *lock_id; // If not main_lock_id, points to + // the lock_id of a cursor. + /** + Protects THD data accessed from other threads: + - thd->query and thd->query_length (used by SHOW ENGINE + INNODB STATUS and SHOW PROCESSLIST + - thd->mysys_var (used by KILL statement and shutdown). + Is locked when THD is deleted. + */ + pthread_mutex_t LOCK_thd_data; + + /* all prepared statements and cursors of this connection */ + Statement_map stmt_map; + /* + A pointer to the stack frame of handle_one_connection(), + which is called first in the thread for handling a client + */ + char *thread_stack; + + /** + Currently selected catalog. + */ + char *catalog; + + /** + @note + Some members of THD (currently 'Statement::db', + 'catalog' and 'query') are set and alloced by the slave SQL thread + (for the THD of that thread); that thread is (and must remain, for now) + the only responsible for freeing these 3 members. If you add members + here, and you add code to set them in replication, don't forget to + free_them_and_set_them_to_0 in replication properly. For details see + the 'err:' label of the handle_slave_sql() in sql/slave.cc. + + @see handle_slave_sql + */ + + Security_context main_security_ctx; + Security_context *security_ctx; + + /* + Points to info-string that we show in SHOW PROCESSLIST + You are supposed to update thd->proc_info only if you have coded + a time-consuming piece that MySQL can get stuck in for a long time. + + Set it using the thd_proc_info(THD *thread, const char *message) + macro/function. + + This member is accessed and assigned without any synchronization. + Therefore, it may point only to constant (statically + allocated) strings, which memory won't go away over time. + */ + const char *proc_info; + + /* + Used in error messages to tell user in what part of MySQL we found an + error. E. g. when where= "having clause", if fix_fields() fails, user + will know that the error was in having clause. + */ + const char *where; + + double tmp_double_value; /* Used in set_var.cc */ + ulong client_capabilities; /* What the client supports */ + ulong max_client_packet_length; + + HASH handler_tables_hash; + /* + One thread can hold up to one named user-level lock. This variable + points to a lock object if the lock is present. See item_func.cc and + chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK. + */ + User_level_lock *ull; +#ifndef DBUG_OFF + uint dbug_sentry; // watch out for memory corruption +#endif + struct st_my_thread_var *mysys_var; + /* + Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from + first byte of the packet in do_command() + */ + enum enum_server_command command; + uint32 server_id; + uint32 file_id; // for LOAD DATA INFILE + /* remote (peer) port */ + uint16 peer_port; + time_t start_time, user_time; + // track down slow pthread_create + ulonglong prior_thr_create_utime, thr_create_utime; + ulonglong start_utime, utime_after_lock; + + thr_lock_type update_lock_default; + Delayed_insert *di; + + /* <> 0 if we are inside of trigger or stored function. */ + uint in_sub_stmt; + /* TRUE when the current top has SQL_LOG_BIN ON */ + bool sql_log_bin_toplevel; + + /* container for handler's private per-connection data */ + Ha_data ha_data[MAX_HA]; + +#ifndef MYSQL_CLIENT + int binlog_setup_trx_data(); + + /* + Public interface to write RBR events to the binlog + */ + void binlog_start_trans_and_stmt(); + void binlog_set_stmt_begin(); + int binlog_write_table_map(TABLE *table, bool is_transactional); + int binlog_write_row(TABLE* table, bool is_transactional, + MY_BITMAP const* cols, size_t colcnt, + const uchar *buf); + int binlog_delete_row(TABLE* table, bool is_transactional, + MY_BITMAP const* cols, size_t colcnt, + const uchar *buf); + int binlog_update_row(TABLE* table, bool is_transactional, + MY_BITMAP const* cols, size_t colcnt, + const uchar *old_data, const uchar *new_data); + + void set_server_id(uint32 sid) { server_id = sid; } + + /* + Member functions to handle pending event for row-level logging. + */ + template Rows_log_event* + binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id, + MY_BITMAP const* cols, + size_t colcnt, + size_t needed, + bool is_transactional, + RowsEventT* hint); + Rows_log_event* binlog_get_pending_rows_event() const; + void binlog_set_pending_rows_event(Rows_log_event* ev); + int binlog_flush_pending_rows_event(bool stmt_end); + int binlog_remove_pending_rows_event(bool clear_maps); + +private: + /* + Number of outstanding table maps, i.e., table maps in the + transaction cache. + */ + uint binlog_table_maps; + + enum enum_binlog_flag { + BINLOG_FLAG_UNSAFE_STMT_PRINTED, + BINLOG_FLAG_COUNT + }; + + /** + Flags with per-thread information regarding the status of the + binary log. + */ + uint32 binlog_flags; +public: + uint get_binlog_table_maps() const { + return binlog_table_maps; + } +#endif /* MYSQL_CLIENT */ + +public: + + struct st_transactions { + SAVEPOINT *savepoints; + THD_TRANS all; // Trans since BEGIN WORK + THD_TRANS stmt; // Trans for current statement + bool on; // see ha_enable_transaction() + XID_STATE xid_state; + Rows_log_event *m_pending_rows_event; + + /* + Tables changed in transaction (that must be invalidated in query cache). + List contain only transactional tables, that not invalidated in query + cache (instead of full list of changed in transaction tables). + */ + CHANGED_TABLE_LIST* changed_tables; + MEM_ROOT mem_root; // Transaction-life memory allocation pool + void cleanup() + { + changed_tables= 0; + savepoints= 0; + /* + If rm_error is raised, it means that this piece of a distributed + transaction has failed and must be rolled back. But the user must + rollback it explicitly, so don't start a new distributed XA until + then. + */ + if (!xid_state.rm_error) + xid_state.xid.null(); +#ifdef USING_TRANSACTIONS + free_root(&mem_root,MYF(MY_KEEP_PREALLOC)); +#endif + } + st_transactions() + { +#ifdef USING_TRANSACTIONS + bzero((char*)this, sizeof(*this)); + xid_state.xid.null(); + init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0); +#else + xid_state.xa_state= XA_NOTR; +#endif + } + } transaction; + Field *dup_field; +#ifndef __WIN__ + sigset_t signals; +#endif +#ifdef SIGNAL_WITH_VIO_CLOSE + Vio* active_vio; +#endif + /* + This is to track items changed during execution of a prepared + statement/stored procedure. It's created by + register_item_tree_change() in memory root of THD, and freed in + rollback_item_tree_changes(). For conventional execution it's always + empty. + */ + Item_change_list change_list; + + /* + A permanent memory area of the statement. For conventional + execution, the parsed tree and execution runtime reside in the same + memory root. In this case stmt_arena points to THD. In case of + a prepared statement or a stored procedure statement, thd->mem_root + conventionally points to runtime memory, and thd->stmt_arena + points to the memory of the PS/SP, where the parsed tree of the + statement resides. Whenever you need to perform a permanent + transformation of a parsed tree, you should allocate new memory in + stmt_arena, to allow correct re-execution of PS/SP. + Note: in the parser, stmt_arena == thd, even for PS/SP. + */ + Query_arena *stmt_arena; + + /* + map for tables that will be updated for a multi-table update query + statement, for other query statements, this will be zero. + */ + table_map table_map_for_update; + + /* Tells if LAST_INSERT_ID(#) was called for the current statement */ + bool arg_of_last_insert_id_function; + /* + ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for + insertion into an auto_increment column". + */ + /* + This is the first autogenerated insert id which was *successfully* + inserted by the previous statement (exactly, if the previous statement + didn't successfully insert an autogenerated insert id, then it's the one + of the statement before, etc). + It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#). + It is returned by LAST_INSERT_ID(). + */ + ulonglong first_successful_insert_id_in_prev_stmt; + /* + Variant of the above, used for storing in statement-based binlog. The + difference is that the one above can change as the execution of a stored + function progresses, while the one below is set once and then does not + change (which is the value which statement-based binlog needs). + */ + ulonglong first_successful_insert_id_in_prev_stmt_for_binlog; + /* + This is the first autogenerated insert id which was *successfully* + inserted by the current statement. It is maintained only to set + first_successful_insert_id_in_prev_stmt when statement ends. + */ + ulonglong first_successful_insert_id_in_cur_stmt; + /* + We follow this logic: + - when stmt starts, first_successful_insert_id_in_prev_stmt contains the + first insert id successfully inserted by the previous stmt. + - as stmt makes progress, handler::insert_id_for_cur_row changes; + every time get_auto_increment() is called, + auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the + reserved interval (if statement-based binlogging). + - at first successful insertion of an autogenerated value, + first_successful_insert_id_in_cur_stmt is set to + handler::insert_id_for_cur_row. + - when stmt goes to binlog, + auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if + non-empty. + - when stmt ends, first_successful_insert_id_in_prev_stmt is set to + first_successful_insert_id_in_cur_stmt. + */ + /* + stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when + LAST_INSERT_ID() is used by a statement. + If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be + stored in the statement-based binlog. + This variable is CUMULATIVE along the execution of a stored function or + trigger: if one substatement sets it to 1 it will stay 1 until the + function/trigger ends, thus making sure that + first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore + and is propagated to the caller for binlogging. + */ + bool stmt_depends_on_first_successful_insert_id_in_prev_stmt; + /* + List of auto_increment intervals reserved by the thread so far, for + storage in the statement-based binlog. + Note that its minimum is not first_successful_insert_id_in_cur_stmt: + assuming a table with an autoinc column, and this happens: + INSERT INTO ... VALUES(3); + SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL); + then the latter INSERT will insert no rows + (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3" + in the binlog is still needed; the list's minimum will contain 3. + This variable is cumulative: if several statements are written to binlog + as one (stored functions or triggers are used) this list is the + concatenation of all intervals reserved by all statements. + */ + Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog; + /* Used by replication and SET INSERT_ID */ + Discrete_intervals_list auto_inc_intervals_forced; + /* + There is BUG#19630 where statement-based replication of stored + functions/triggers with two auto_increment columns breaks. + We however ensure that it works when there is 0 or 1 auto_increment + column; our rules are + a) on master, while executing a top statement involving substatements, + first top- or sub- statement to generate auto_increment values wins the + exclusive right to see its values be written to binlog (the write + will be done by the statement or its caller), and the losers won't see + their values be written to binlog. + b) on slave, while replicating a top statement involving substatements, + first top- or sub- statement to need to read auto_increment values from + the master's binlog wins the exclusive right to read them (so the losers + won't read their values from binlog but instead generate on their own). + a) implies that we mustn't backup/restore + auto_inc_intervals_in_cur_stmt_for_binlog. + b) implies that we mustn't backup/restore auto_inc_intervals_forced. + + If there are more than 1 auto_increment columns, then intervals for + different columns may mix into the + auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong, + but there is no point in preventing this mixing by preventing intervals + from the secondly inserted column to come into the list, as such + prevention would be wrong too. + What will happen in the case of + INSERT INTO t1 (auto_inc) VALUES(NULL); + where t1 has a trigger which inserts into an auto_inc column of t2, is + that in binlog we'll store the interval of t1 and the interval of t2 (when + we store intervals, soon), then in slave, t1 will use both intervals, t2 + will use none; if t1 inserts the same number of rows as on master, + normally the 2nd interval will not be used by t1, which is fine. t2's + values will be wrong if t2's internal auto_increment counter is different + from what it was on master (which is likely). In 5.1, in mixed binlogging + mode, row-based binlogging is used for such cases where two + auto_increment columns are inserted. + */ + inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg) + { + if (first_successful_insert_id_in_cur_stmt == 0) + first_successful_insert_id_in_cur_stmt= id_arg; + } + inline ulonglong read_first_successful_insert_id_in_prev_stmt(void) + { + if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt) + { + /* It's the first time we read it */ + first_successful_insert_id_in_prev_stmt_for_binlog= + first_successful_insert_id_in_prev_stmt; + stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1; + } + return first_successful_insert_id_in_prev_stmt; + } + /* + Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#" + (mysqlbinlog). We'll soon add a variant which can take many intervals in + argument. + */ + inline void force_one_auto_inc_interval(ulonglong next_id) + { + auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID + auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0); + } + + ulonglong limit_found_rows; + ulonglong options; /* Bitmap of states */ + longlong row_count_func; /* For the ROW_COUNT() function */ + ha_rows cuted_fields; + + /* + number of rows we actually sent to the client, including "synthetic" + rows in ROLLUP etc. + */ + ha_rows sent_row_count; + + /* + number of rows we read, sent or not, including in create_sort_index() + */ + ha_rows examined_row_count; + + /* + The set of those tables whose fields are referenced in all subqueries + of the query. + TODO: possibly this it is incorrect to have used tables in THD because + with more than one subquery, it is not clear what does the field mean. + */ + table_map used_tables; + USER_CONN *user_connect; + CHARSET_INFO *db_charset; + /* + FIXME: this, and some other variables like 'count_cuted_fields' + maybe should be statement/cursor local, that is, moved to Statement + class. With current implementation warnings produced in each prepared + statement/cursor settle here. + */ + List warn_list; + uint warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END]; + uint total_warn_count; + Diagnostics_area main_da; +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + PROFILING profiling; +#endif + + /* + Id of current query. Statement can be reused to execute several queries + query_id is global in context of the whole MySQL server. + ID is automatically generated from mutex-protected counter. + It's used in handler code for various purposes: to check which columns + from table are necessary for this select, to check if it's necessary to + update auto-updatable fields (like auto_increment and timestamp). + */ + query_id_t query_id, warn_id; + ulong col_access; + +#ifdef ERROR_INJECT_SUPPORT + ulong error_inject_value; +#endif + /* Statement id is thread-wide. This counter is used to generate ids */ + ulong statement_id_counter; + ulong rand_saved_seed1, rand_saved_seed2; + /* + Row counter, mainly for errors and warnings. Not increased in + create_sort_index(); may differ from examined_row_count. + */ + ulong row_count; + pthread_t real_id; /* For debugging */ + my_thread_id thread_id; + uint tmp_table, global_read_lock; + uint server_status,open_options; + enum enum_thread_type system_thread; + uint select_number; //number of select (used for EXPLAIN) + /* variables.transaction_isolation is reset to this after each commit */ + enum_tx_isolation session_tx_isolation; + enum_check_fields count_cuted_fields; + + DYNAMIC_ARRAY user_var_events; /* For user variables replication */ + MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */ + + enum killed_state + { + NOT_KILLED=0, + KILL_BAD_DATA=1, + KILL_CONNECTION=ER_SERVER_SHUTDOWN, + KILL_QUERY=ER_QUERY_INTERRUPTED, + KILLED_NO_VALUE /* means neither of the states */ + }; + killed_state volatile killed; + + // ------------------------------ Calpont InfiniDB ------------------------------ + public: + + enum infinidb_state + { + INFINIDB_INIT_CONNECT = 0, // intend to use to drop leftover vtable when logon. not being used now. + INFINIDB_INIT, + INFINIDB_CREATE_VTABLE, + INFINIDB_ALTER_VTABLE, + INFINIDB_SELECT_VTABLE, + INFINIDB_DROP_VTABLE, + INFINIDB_DISABLE_VTABLE, + INFINIDB_REDO_PHASE1, // post process requires to re-create vtable + INFINIDB_ORDER_BY, // for Calpont handler to ignore the 2nd scan for order by + INFINIDB_REDO_QUERY, // redo query with the normal mysql path + INFINIDB_ERROR = 32, + }; + + struct INFINIDB_VTABLE + { + String original_query; + String create_vtable_query; + String alter_vtable_query; + String select_vtable_query; + String drop_vtable_query; + String insert_vtable_query; + infinidb_state vtable_state; // flag for Calpont MySQL virtual table structure + bool autoswitch; + bool has_order_by; + bool has_limit; // deprecated + bool mysql_optimizer_off; + bool duplicate_field_name; // @bug 1928. duplicate field name in create_phase will be ingored. + bool call_sp; + bool override_largeside_estimate; + void* cal_conn_info; + bool isUnion; + bool impossibleWhereOnUnion; + bool isInsertSelect; + bool isUpdateWithDerive; + bool isInfiniDBDML; // default false + }; + + INFINIDB_VTABLE infinidb_vtable; // Calpont InfiniDB custom structure + + // ------------------------------ Calpont InfiniDB ------------------------------ + + /* scramble - random string sent to client on handshake */ + char scramble[SCRAMBLE_LENGTH+1]; + + bool slave_thread, one_shot_set; + /* tells if current statement should binlog row-based(1) or stmt-based(0) */ + bool current_stmt_binlog_row_based; + bool locked, some_tables_deleted; + bool last_cuted_field; + bool no_errors, password; + /** + Set to TRUE if execution of the current compound statement + can not continue. In particular, disables activation of + CONTINUE or EXIT handlers of stored routines. + Reset in the end of processing of the current user request, in + @see mysql_reset_thd_for_next_command(). + */ + bool is_fatal_error; + /** + Set by a storage engine to request the entire + transaction (that possibly spans multiple engines) to + rollback. Reset in ha_rollback. + */ + bool transaction_rollback_request; + /** + TRUE if we are in a sub-statement and the current error can + not be safely recovered until we left the sub-statement mode. + In particular, disables activation of CONTINUE and EXIT + handlers inside sub-statements. E.g. if it is a deadlock + error and requires a transaction-wide rollback, this flag is + raised (traditionally, MySQL first has to close all the reads + via @see handler::ha_index_or_rnd_end() and only then perform + the rollback). + Reset to FALSE when we leave the sub-statement mode. + */ + bool is_fatal_sub_stmt_error; + bool query_start_used, rand_used, time_zone_used; + /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */ + bool substitute_null_with_insert_id; + bool in_lock_tables; + /** + True if a slave error. Causes the slave to stop. Not the same + as the statement execution error (is_error()), since + a statement may be expected to return an error, e.g. because + it returned an error on master, and this is OK on the slave. + */ + bool is_slave_error; + bool bootstrap, cleanup_done; + + /** is set if some thread specific value(s) used in a statement. */ + bool thread_specific_used; + bool charset_is_system_charset, charset_is_collation_connection; + bool charset_is_character_set_filesystem; + bool enable_slow_log; /* enable slow log for current statement */ + bool abort_on_warning; + bool got_warning; /* Set on call to push_warning() */ + bool no_warnings_for_error; /* no warnings on call to my_error() */ + /* set during loop of derived table processing */ + bool derived_tables_processing; + my_bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */ + + sp_rcontext *spcont; // SP runtime context + sp_cache *sp_proc_cache; + sp_cache *sp_func_cache; + + /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */ + uint query_name_consts; + + /* + If we do a purge of binary logs, log index info of the threads + that are currently reading it needs to be adjusted. To do that + each thread that is using LOG_INFO needs to adjust the pointer to it + */ + LOG_INFO* current_linfo; + NET* slave_net; // network connection from slave -> m. + /* Used by the sys_var class to store temporary values */ + union + { + my_bool my_bool_value; + long long_value; + ulong ulong_value; + ulonglong ulonglong_value; + } sys_var_tmp; + + struct { + /* + If true, mysql_bin_log::write(Log_event) call will not write events to + binlog, and maintain 2 below variables instead (use + mysql_bin_log.start_union_events to turn this on) + */ + bool do_union; + /* + If TRUE, at least one mysql_bin_log::write(Log_event) call has been + made after last mysql_bin_log.start_union_events() call. + */ + bool unioned_events; + /* + If TRUE, at least one mysql_bin_log::write(Log_event e), where + e.cache_stmt == TRUE call has been made after last + mysql_bin_log.start_union_events() call. + */ + bool unioned_events_trans; + + /* + 'queries' (actually SP statements) that run under inside this binlog + union have thd->query_id >= first_query_id. + */ + query_id_t first_query_id; + } binlog_evt_union; + + /** + Internal parser state. + Note that since the parser is not re-entrant, we keep only one parser + state here. This member is valid only when executing code during parsing. + */ + Parser_state *m_parser_state; + +#ifdef WITH_PARTITION_STORAGE_ENGINE + partition_info *work_part_info; +#endif + + THD(); + ~THD(); + + void init(void); + /* + Initialize memory roots necessary for query processing and (!) + pre-allocate memory for it. We can't do that in THD constructor because + there are use cases (acl_init, delayed inserts, watcher threads, + killing mysqld) where it's vital to not allocate excessive and not used + memory. Note, that we still don't return error from init_for_queries(): + if preallocation fails, we should notice that at the first call to + alloc_root. + */ + void init_for_queries(); + void change_user(void); + void cleanup(void); + void cleanup_after_query(); + bool store_globals(); +#ifdef SIGNAL_WITH_VIO_CLOSE + inline void set_active_vio(Vio* vio) + { + pthread_mutex_lock(&LOCK_thd_data); + active_vio = vio; + pthread_mutex_unlock(&LOCK_thd_data); + } + inline void clear_active_vio() + { + pthread_mutex_lock(&LOCK_thd_data); + active_vio = 0; + pthread_mutex_unlock(&LOCK_thd_data); + } + void close_active_vio(); +#endif + void awake(THD::killed_state state_to_set); + +#ifndef MYSQL_CLIENT + enum enum_binlog_query_type { + /* + The query can be logged row-based or statement-based + */ + ROW_QUERY_TYPE, + + /* + The query has to be logged statement-based + */ + STMT_QUERY_TYPE, + + /* + The query represents a change to a table in the "mysql" + database and is currently mapped to ROW_QUERY_TYPE. + */ + MYSQL_QUERY_TYPE, + QUERY_TYPE_COUNT + }; + + int binlog_query(enum_binlog_query_type qtype, + char const *query, ulong query_len, + bool is_trans, bool suppress_use, + int errcode); +#endif + + /* + For enter_cond() / exit_cond() to work the mutex must be got before + enter_cond(); this mutex is then released by exit_cond(). + Usage must be: lock mutex; enter_cond(); your code; exit_cond(). + */ + inline const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex, + const char* msg) + { + const char* old_msg = proc_info; + safe_mutex_assert_owner(mutex); + mysys_var->current_mutex = mutex; + mysys_var->current_cond = cond; + proc_info = msg; + return old_msg; + } + inline void exit_cond(const char* old_msg) + { + /* + Putting the mutex unlock in exit_cond() ensures that + mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is + locked (if that would not be the case, you'll get a deadlock if someone + does a THD::awake() on you). + */ + pthread_mutex_unlock(mysys_var->current_mutex); + pthread_mutex_lock(&mysys_var->mutex); + mysys_var->current_mutex = 0; + mysys_var->current_cond = 0; + proc_info = old_msg; + pthread_mutex_unlock(&mysys_var->mutex); + } + inline time_t query_start() { query_start_used=1; return start_time; } + inline void set_time() + { + if (user_time) + { + start_time= user_time; + start_utime= utime_after_lock= my_micro_time(); + } + else + start_utime= utime_after_lock= my_micro_time_and_time(&start_time); + } + inline void set_current_time() { start_time= my_time(MY_WME); } + inline void set_time(time_t t) + { + start_time= user_time= t; + start_utime= utime_after_lock= my_micro_time(); + } + void set_time_after_lock() { utime_after_lock= my_micro_time(); } + ulonglong current_utime() { return my_micro_time(); } + inline ulonglong found_rows(void) + { + return limit_found_rows; + } + inline bool active_transaction() + { +#ifdef USING_TRANSACTIONS + return server_status & SERVER_STATUS_IN_TRANS; +#else + return 0; +#endif + } + inline bool fill_derived_tables() + { + return !stmt_arena->is_stmt_prepare() && !lex->only_view_structure(); + } + inline bool fill_information_schema_tables() + { + return !stmt_arena->is_stmt_prepare(); + } + inline void* trans_alloc(unsigned int size) + { + return alloc_root(&transaction.mem_root,size); + } + + LEX_STRING *make_lex_string(LEX_STRING *lex_str, + const char* str, uint length, + bool allocate_lex_string); + + bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs, + const char *from, uint from_length, + CHARSET_INFO *from_cs); + + bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs); + + void add_changed_table(TABLE *table); + void add_changed_table(const char *key, long key_length); + CHANGED_TABLE_LIST * changed_table_dup(const char *key, long key_length); + int send_explain_fields(select_result *result); +#ifndef EMBEDDED_LIBRARY + /** + Clear the current error, if any. + We do not clear is_fatal_error or is_fatal_sub_stmt_error since we + assume this is never called if the fatal error is set. + @todo: To silence an error, one should use Internal_error_handler + mechanism. In future this function will be removed. + */ + inline void clear_error() + { + DBUG_ENTER("clear_error"); + if (main_da.is_error()) + main_da.reset_diagnostics_area(); + is_slave_error= 0; + DBUG_VOID_RETURN; + } + inline bool vio_ok() const { return net.vio != 0; } +#else + void clear_error(); + inline bool vio_ok() const { return true; } +#endif + /** + Mark the current error as fatal. Warning: this does not + set any error, it sets a property of the error, so must be + followed or prefixed with my_error(). + */ + inline void fatal_error() + { + is_fatal_error= 1; + DBUG_PRINT("error",("Fatal error set")); + } + /** + TRUE if there is an error in the error stack. + + Please use this method instead of direct access to + net.report_error. + + If TRUE, the current (sub)-statement should be aborted. + The main difference between this member and is_fatal_error + is that a fatal error can not be handled by a stored + procedure continue handler, whereas a normal error can. + + To raise this flag, use my_error(). + */ + inline bool is_error() const { return main_da.is_error(); } + inline CHARSET_INFO *charset() { return variables.character_set_client; } + void update_charset(); + + inline Query_arena *activate_stmt_arena_if_needed(Query_arena *backup) + { + /* + Use the persistent arena if we are in a prepared statement or a stored + procedure statement and we have not already changed to use this arena. + */ + if (!stmt_arena->is_conventional() && mem_root != stmt_arena->mem_root) + { + set_n_backup_active_arena(stmt_arena, backup); + return stmt_arena; + } + return 0; + } + + void change_item_tree(Item **place, Item *new_value) + { + /* TODO: check for OOM condition here */ + if (!stmt_arena->is_conventional()) + nocheck_register_item_tree_change(place, *place, mem_root); + *place= new_value; + } + void nocheck_register_item_tree_change(Item **place, Item *old_value, + MEM_ROOT *runtime_memroot); + void rollback_item_tree_changes(); + + /* + Cleanup statement parse state (parse tree, lex) and execution + state after execution of a non-prepared SQL statement. + */ + void end_statement(); + inline int killed_errno() const + { + killed_state killed_val; /* to cache the volatile 'killed' */ + return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0; + } + inline void send_kill_message() const + { + int err= killed_errno(); + if (err) + my_message(err, ER(err), MYF(0)); + } + /* return TRUE if we will abort query if we make a warning now */ + inline bool really_abort_on_warning() + { + return (abort_on_warning && + (!transaction.stmt.modified_non_trans_table || + (variables.sql_mode & MODE_STRICT_ALL_TABLES))); + } + void set_status_var_init(); + bool is_context_analysis_only() + { return stmt_arena->is_stmt_prepare() || lex->view_prepare_mode; } + void reset_n_backup_open_tables_state(Open_tables_state *backup); + void restore_backup_open_tables_state(Open_tables_state *backup); + void reset_sub_statement_state(Sub_statement_state *backup, uint new_state); + void restore_sub_statement_state(Sub_statement_state *backup); + void set_n_backup_active_arena(Query_arena *set, Query_arena *backup); + void restore_active_arena(Query_arena *set, Query_arena *backup); + + inline void set_current_stmt_binlog_row_based_if_mixed() + { + /* + If in a stored/function trigger, the caller should already have done the + change. We test in_sub_stmt to prevent introducing bugs where people + wouldn't ensure that, and would switch to row-based mode in the middle + of executing a stored function/trigger (which is too late, see also + reset_current_stmt_binlog_row_based()); this condition will make their + tests fail and so force them to propagate the + lex->binlog_row_based_if_mixed upwards to the caller. + */ + if ((variables.binlog_format == BINLOG_FORMAT_MIXED) && + (in_sub_stmt == 0)) + current_stmt_binlog_row_based= TRUE; + } + inline void set_current_stmt_binlog_row_based() + { + current_stmt_binlog_row_based= TRUE; + } + inline void clear_current_stmt_binlog_row_based() + { + current_stmt_binlog_row_based= FALSE; + } + inline void reset_current_stmt_binlog_row_based() + { + /* + If there are temporary tables, don't reset back to + statement-based. Indeed it could be that: + CREATE TEMPORARY TABLE t SELECT UUID(); # row-based + # and row-based does not store updates to temp tables + # in the binlog. + INSERT INTO u SELECT * FROM t; # stmt-based + and then the INSERT will fail as data inserted into t was not logged. + So we continue with row-based until the temp table is dropped. + If we are in a stored function or trigger, we mustn't reset in the + middle of its execution (as the binary logging way of a stored function + or trigger is decided when it starts executing, depending for example on + the caller (for a stored function: if caller is SELECT or + INSERT/UPDATE/DELETE...). + + Don't reset binlog format for NDB binlog injector thread. + */ + DBUG_PRINT("debug", + ("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s", + YESNO(temporary_tables), YESNO(in_sub_stmt), + show_system_thread(system_thread))); + if ((temporary_tables == NULL) && (in_sub_stmt == 0) && + (system_thread != SYSTEM_THREAD_NDBCLUSTER_BINLOG)) + { + current_stmt_binlog_row_based= + test(variables.binlog_format == BINLOG_FORMAT_ROW); + } + } + + /** + Set the current database; use deep copy of C-string. + + @param new_db a pointer to the new database name. + @param new_db_len length of the new database name. + + Initialize the current database from a NULL-terminated string with + length. If we run out of memory, we free the current database and + return TRUE. This way the user will notice the error as there will be + no current database selected (in addition to the error message set by + malloc). + + @note This operation just sets {db, db_length}. Switching the current + database usually involves other actions, like switching other database + attributes including security context. In the future, this operation + will be made private and more convenient interface will be provided. + + @return Operation status + @retval FALSE Success + @retval TRUE Out-of-memory error + */ + bool set_db(const char *new_db, size_t new_db_len) + { + /* Do not reallocate memory if current chunk is big enough. */ + if (db && new_db && db_length >= new_db_len) + memcpy(db, new_db, new_db_len+1); + else + { + x_free(db); + db= new_db ? my_strndup(new_db, new_db_len, MYF(MY_WME)) : NULL; + } + db_length= db ? new_db_len : 0; + return new_db && !db; + } + + /** + Set the current database; use shallow copy of C-string. + + @param new_db a pointer to the new database name. + @param new_db_len length of the new database name. + + @note This operation just sets {db, db_length}. Switching the current + database usually involves other actions, like switching other database + attributes including security context. In the future, this operation + will be made private and more convenient interface will be provided. + */ + void reset_db(char *new_db, size_t new_db_len) + { + db= new_db; + db_length= new_db_len; + } + /* + Copy the current database to the argument. Use the current arena to + allocate memory for a deep copy: current database may be freed after + a statement is parsed but before it's executed. + */ + bool copy_db_to(char **p_db, size_t *p_db_length) + { + if (db == NULL) + { + my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); + return TRUE; + } + *p_db= strmake(db, db_length); + *p_db_length= db_length; + return FALSE; + } + thd_scheduler scheduler; + +public: + inline Internal_error_handler *get_internal_handler() + { return m_internal_handler; } + + /** + Add an internal error handler to the thread execution context. + @param handler the exception handler to add + */ + void push_internal_handler(Internal_error_handler *handler); + + /** + Handle an error condition. + @param sql_errno the error number + @param level the error level + @return true if the error is handled + */ + virtual bool handle_error(uint sql_errno, const char *message, + MYSQL_ERROR::enum_warning_level level); + + /** + Remove the error handler last pushed. + */ + void pop_internal_handler(); + + /** Overloaded to guard query/query_length fields */ + virtual void set_statement(Statement *stmt); + + /** + Assign a new value to thd->query. + Protected with LOCK_thd_data mutex. + */ + void set_query(char *query_arg, uint32 query_length_arg); +private: + /** The current internal error handler for this thread, or NULL. */ + Internal_error_handler *m_internal_handler; + /** + The lex to hold the parsed tree of conventional (non-prepared) queries. + Whereas for prepared and stored procedure statements we use an own lex + instance for each new query, for conventional statements we reuse + the same lex. (@see mysql_parse for details). + */ + LEX main_lex; + /** + This memory root is used for two purposes: + - for conventional queries, to allocate structures stored in main_lex + during parsing, and allocate runtime data (execution plan, etc.) + during execution. + - for prepared queries, only to allocate runtime data. The parsed + tree itself is reused between executions and thus is stored elsewhere. + */ + MEM_ROOT main_mem_root; +}; + + +/** A short cut for thd->main_da.set_ok_status(). */ + +inline void +my_ok(THD *thd, ha_rows affected_rows= 0, ulonglong id= 0, + const char *message= NULL) +{ + thd->main_da.set_ok_status(thd, affected_rows, id, message); +} + + +/** A short cut for thd->main_da.set_eof_status(). */ + +inline void +my_eof(THD *thd) +{ + thd->main_da.set_eof_status(thd); +} + +#define tmp_disable_binlog(A) \ + {ulonglong tmp_disable_binlog__save_options= (A)->options; \ + (A)->options&= ~OPTION_BIN_LOG + +#define reenable_binlog(A) (A)->options= tmp_disable_binlog__save_options;} + + +/* + Used to hold information about file and file structure in exchange + via non-DB file (...INTO OUTFILE..., ...LOAD DATA...) + XXX: We never call destructor for objects of this class. +*/ + +class sql_exchange :public Sql_alloc +{ +public: + char *file_name; + String *field_term,*enclosed,*line_term,*line_start,*escaped; + bool opt_enclosed; + bool dumpfile; + ulong skip_lines; + CHARSET_INFO *cs; + sql_exchange(char *name,bool dumpfile_flag); + bool escaped_given(void); +}; + +#include "log_event.h" + +/* + This is used to get result from a select +*/ + +class JOIN; + +class select_result :public Sql_alloc { +protected: + THD *thd; + SELECT_LEX_UNIT *unit; + uint nest_level; +public: + select_result(); + virtual ~select_result() {}; + virtual int prepare(List &list, SELECT_LEX_UNIT *u) + { + unit= u; + return 0; + } + virtual int prepare2(void) { return 0; } + /* + Because of peculiarities of prepared statements protocol + we need to know number of columns in the result set (if + there is a result set) apart from sending columns metadata. + */ + virtual uint field_count(List &fields) const + { return fields.elements; } + virtual bool send_fields(List &list, uint flags)=0; + virtual bool send_data(List &items)=0; + virtual bool initialize_tables (JOIN *join=0) { return 0; } + virtual void send_error(uint errcode,const char *err); + virtual bool send_eof()=0; + /** + Check if this query returns a result set and therefore is allowed in + cursors and set an error message if it is not the case. + + @retval FALSE success + @retval TRUE error, an error message is set + */ + virtual bool check_simple_select() const; + virtual void abort() {} + /* + Cleanup instance of this class for next execution of a prepared + statement/stored procedure. + */ + virtual void cleanup(); + void set_thd(THD *thd_arg) { thd= thd_arg; } + /** + The nest level, if supported. + @return + -1 if nest level is undefined, otherwise a positive integer. + */ + int get_nest_level() { return nest_level; } +#ifdef EMBEDDED_LIBRARY + virtual void begin_dataset() {} +#else + void begin_dataset() {} +#endif +}; + + +/* + Base class for select_result descendands which intercept and + transform result set rows. As the rows are not sent to the client, + sending of result set metadata should be suppressed as well. +*/ + +class select_result_interceptor: public select_result +{ +public: + select_result_interceptor() {} /* Remove gcc warning */ + uint field_count(List &fields) const { return 0; } + bool send_fields(List &fields, uint flag) { return FALSE; } +}; + + +class select_send :public select_result { + /** + True if we have sent result set metadata to the client. + In this case the client always expects us to end the result + set with an eof or error packet + */ + bool is_result_set_started; +public: + select_send() :is_result_set_started(FALSE) {} + bool send_fields(List &list, uint flags); + bool send_data(List &items); + bool send_eof(); + virtual bool check_simple_select() const { return FALSE; } + void abort(); + virtual void cleanup(); +}; + + +class select_to_file :public select_result_interceptor { +protected: + sql_exchange *exchange; + File file; + IO_CACHE cache; + ha_rows row_count; + char path[FN_REFLEN]; + +public: + select_to_file(sql_exchange *ex) :exchange(ex), file(-1),row_count(0L) + { path[0]=0; } + ~select_to_file(); + void send_error(uint errcode,const char *err); + bool send_eof(); + void cleanup(); +}; + + +#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape + + +/* + List of all possible characters of a numeric value text representation. +*/ +#define NUMERIC_CHARS ".0123456789e+-" + + +class select_export :public select_to_file { + uint field_term_length; + int field_sep_char,escape_char,line_sep_char; + int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT + /* + The is_ambiguous_field_sep field is true if a value of the field_sep_char + field is one of the 'n', 't', 'r' etc characters + (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value). + */ + bool is_ambiguous_field_sep; + /* + The is_ambiguous_field_term is true if field_sep_char contains the first + char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can + contain this character. + */ + bool is_ambiguous_field_term; + /* + The is_unsafe_field_sep field is true if a value of the field_sep_char + field is one of the '0'..'9', '+', '-', '.' and 'e' characters + (see the NUMERIC_CHARS constant value). + */ + bool is_unsafe_field_sep; + bool fixed_row_size; + CHARSET_INFO *write_cs; // output charset +public: + select_export(sql_exchange *ex) :select_to_file(ex) {} + /** + Creates a select_export to represent INTO OUTFILE with a + defined level of subquery nesting. + */ + select_export(sql_exchange *ex, uint nest_level_arg) :select_to_file(ex) + { + nest_level= nest_level_arg; + } + ~select_export(); + int prepare(List &list, SELECT_LEX_UNIT *u); + bool send_data(List &items); +}; + + +class select_dump :public select_to_file { +public: + select_dump(sql_exchange *ex) :select_to_file(ex) {} + /** + Creates a select_export to represent INTO DUMPFILE with a + defined level of subquery nesting. + */ + select_dump(sql_exchange *ex, uint nest_level_arg) : + select_to_file(ex) + { + nest_level= nest_level_arg; + } + int prepare(List &list, SELECT_LEX_UNIT *u); + bool send_data(List &items); +}; + + +class select_insert :public select_result_interceptor { + public: + TABLE_LIST *table_list; + TABLE *table; + List *fields; + ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not + COPY_INFO info; + bool insert_into_view; + select_insert(TABLE_LIST *table_list_par, + TABLE *table_par, List *fields_par, + List *update_fields, List *update_values, + enum_duplicates duplic, bool ignore); + ~select_insert(); + int prepare(List &list, SELECT_LEX_UNIT *u); + virtual int prepare2(void); + bool send_data(List &items); + virtual void store_values(List &values); + virtual bool can_rollback_data() { return 0; } + void send_error(uint errcode,const char *err); + bool send_eof(); + void abort(); + /* not implemented: select_insert is never re-used in prepared statements */ + void cleanup(); +}; + + +class select_create: public select_insert { + ORDER *group; + TABLE_LIST *create_table; + HA_CREATE_INFO *create_info; + TABLE_LIST *select_tables; + Alter_info *alter_info; + Field **field; + /* lock data for tmp table */ + MYSQL_LOCK *m_lock; + /* m_lock or thd->extra_lock */ + MYSQL_LOCK **m_plock; +public: + select_create (TABLE_LIST *table_arg, + HA_CREATE_INFO *create_info_par, + Alter_info *alter_info_arg, + List &select_fields,enum_duplicates duplic, bool ignore, + TABLE_LIST *select_tables_arg) + :select_insert (NULL, NULL, &select_fields, 0, 0, duplic, ignore), + create_table(table_arg), + create_info(create_info_par), + select_tables(select_tables_arg), + alter_info(alter_info_arg), + m_plock(NULL) + {} + int prepare(List &list, SELECT_LEX_UNIT *u); + + void binlog_show_create_table(TABLE **tables, uint count); + void store_values(List &values); + void send_error(uint errcode,const char *err); + bool send_eof(); + void abort(); + virtual bool can_rollback_data() { return 1; } + + // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted. + const THD *get_thd(void) { return thd; } + const HA_CREATE_INFO *get_create_info() { return create_info; }; + int prepare2(void) { return 0; } +}; + +#include + +/* + Param to create temporary tables when doing SELECT:s + NOTE + This structure is copied using memcpy as a part of JOIN. +*/ + +class TMP_TABLE_PARAM :public Sql_alloc +{ +private: + /* Prevent use of these (not safe because of lists and copy_field) */ + TMP_TABLE_PARAM(const TMP_TABLE_PARAM &); + void operator=(TMP_TABLE_PARAM &); + +public: + List copy_funcs; + List save_copy_funcs; + Copy_field *copy_field, *copy_field_end; + Copy_field *save_copy_field, *save_copy_field_end; + uchar *group_buff; + Item **items_to_copy; /* Fields in tmp table */ + MI_COLUMNDEF *recinfo,*start_recinfo; + KEY *keyinfo; + ha_rows end_write_records; + uint field_count,sum_func_count,func_count; + uint hidden_field_count; + uint group_parts,group_length,group_null_parts; + uint quick_group; + bool using_indirect_summary_function; + /* If >0 convert all blob fields to varchar(convert_blob_length) */ + uint convert_blob_length; + CHARSET_INFO *table_charset; + bool schema_table; + /* + True if GROUP BY and its aggregate functions are already computed + by a table access method (e.g. by loose index scan). In this case + query execution should not perform aggregation and should treat + aggregate functions as normal functions. + */ + bool precomputed_group_by; + bool force_copy_fields; + + TMP_TABLE_PARAM() + :copy_field(0), group_parts(0), + group_length(0), group_null_parts(0), convert_blob_length(0), + schema_table(0), precomputed_group_by(0), force_copy_fields(0) + {} + ~TMP_TABLE_PARAM() + { + cleanup(); + } + void init(void); + inline void cleanup(void) + { + if (copy_field) /* Fix for Intel compiler */ + { + delete [] copy_field; + save_copy_field= copy_field= 0; + } + } +}; + +class select_union :public select_result_interceptor +{ + TMP_TABLE_PARAM tmp_table_param; +public: + TABLE *table; + + select_union() :table(0) {} + int prepare(List &list, SELECT_LEX_UNIT *u); + bool send_data(List &items); + bool send_eof(); + bool flush(); + + bool create_result_table(THD *thd, List *column_types, + bool is_distinct, ulonglong options, + const char *alias); +}; + +/* Base subselect interface class */ +class select_subselect :public select_result_interceptor +{ +protected: + Item_subselect *item; +public: + select_subselect(Item_subselect *item); + bool send_data(List &items)=0; + bool send_eof() { return 0; }; +}; + +/* Single value subselect interface class */ +class select_singlerow_subselect :public select_subselect +{ +public: + select_singlerow_subselect(Item_subselect *item_arg) + :select_subselect(item_arg) + {} + bool send_data(List &items); +}; + +/* used in independent ALL/ANY optimisation */ +class select_max_min_finder_subselect :public select_subselect +{ + Item_cache *cache; + bool (select_max_min_finder_subselect::*op)(); + bool fmax; +public: + select_max_min_finder_subselect(Item_subselect *item_arg, bool mx) + :select_subselect(item_arg), cache(0), fmax(mx) + {} + void cleanup(); + bool send_data(List &items); + bool cmp_real(); + bool cmp_int(); + bool cmp_decimal(); + bool cmp_str(); +}; + +/* EXISTS subselect interface class */ +class select_exists_subselect :public select_subselect +{ +public: + select_exists_subselect(Item_subselect *item_arg) + :select_subselect(item_arg){} + bool send_data(List &items); +}; + +/* Structs used when sorting */ + +typedef struct st_sort_field { + Field *field; /* Field to sort */ + Item *item; /* Item if not sorting fields */ + uint length; /* Length of sort field */ + uint suffix_length; /* Length suffix (0-4) */ + Item_result result_type; /* Type of item */ + bool reverse; /* if descending sort */ + bool need_strxnfrm; /* If we have to use strxnfrm() */ +} SORT_FIELD; + + +typedef struct st_sort_buffer { + uint index; /* 0 or 1 */ + uint sort_orders; + uint change_pos; /* If sort-fields changed */ + char **buff; + SORT_FIELD *sortorder; +} SORT_BUFFER; + +/* Structure for db & table in sql_yacc */ + +class Table_ident :public Sql_alloc +{ +public: + LEX_STRING db; + LEX_STRING table; + SELECT_LEX_UNIT *sel; + inline Table_ident(THD *thd, LEX_STRING db_arg, LEX_STRING table_arg, + bool force) + :table(table_arg), sel((SELECT_LEX_UNIT *)0) + { + if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA)) + db.str=0; + else + db= db_arg; + } + inline Table_ident(LEX_STRING table_arg) + :table(table_arg), sel((SELECT_LEX_UNIT *)0) + { + db.str=0; + } + /* + This constructor is used only for the case when we create a derived + table. A derived table has no name and doesn't belong to any database. + Later, if there was an alias specified for the table, it will be set + by add_table_to_list. + */ + inline Table_ident(SELECT_LEX_UNIT *s) : sel(s) + { + /* We must have a table name here as this is used with add_table_to_list */ + db.str= empty_c_string; /* a subject to casedn_str */ + db.length= 0; + table.str= internal_table_name; + table.length=1; + } + bool is_derived_table() const { return test(sel); } + inline void change_db(char *db_name) + { + db.str= db_name; db.length= (uint) strlen(db_name); + } +}; + +// this is needed for user_vars hash +class user_var_entry +{ + public: + user_var_entry() {} /* Remove gcc warning */ + LEX_STRING name; + char *value; + ulong length; + query_id_t update_query_id, used_query_id; + Item_result type; + bool unsigned_flag; + + double val_real(my_bool *null_value); + longlong val_int(my_bool *null_value) const; + String *val_str(my_bool *null_value, String *str, uint decimals); + my_decimal *val_decimal(my_bool *null_value, my_decimal *result); + DTCollation collation; +}; + +/* + Unique -- class for unique (removing of duplicates). + Puts all values to the TREE. If the tree becomes too big, + it's dumped to the file. User can request sorted values, or + just iterate through them. In the last case tree merging is performed in + memory simultaneously with iteration, so it should be ~2-3x faster. + */ + +class Unique :public Sql_alloc +{ + DYNAMIC_ARRAY file_ptrs; + ulong max_elements; + ulonglong max_in_memory_size; + IO_CACHE file; + TREE tree; + uchar *record_pointers; + bool flush(); + uint size; + +public: + ulong elements; + Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg, + uint size_arg, ulonglong max_in_memory_size_arg); + ~Unique(); + ulong elements_in_tree() { return tree.elements_in_tree; } + inline bool unique_add(void *ptr) + { + DBUG_ENTER("unique_add"); + DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements)); + if (tree.elements_in_tree > max_elements && flush()) + DBUG_RETURN(1); + DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg)); + } + + bool get(TABLE *table); + static double get_use_cost(uint *buffer, uint nkeys, uint key_size, + ulonglong max_in_memory_size); + inline static int get_cost_calc_buff_size(ulong nkeys, uint key_size, + ulonglong max_in_memory_size) + { + register ulonglong max_elems_in_tree= + (1 + max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size)); + return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree)); + } + + void reset(); + bool walk(tree_walk_action action, void *walk_action_arg); + + friend int unique_write_to_file(uchar* key, element_count count, Unique *unique); + friend int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique); +}; + + +class multi_delete :public select_result_interceptor +{ + TABLE_LIST *delete_tables, *table_being_deleted; + Unique **tempfiles; + ha_rows deleted, found; + uint num_of_tables; + int error; + bool do_delete; + /* True if at least one table we delete from is transactional */ + bool transactional_tables; + /* True if at least one table we delete from is not transactional */ + bool normal_tables; + bool delete_while_scanning; + /* + error handling (rollback and binlogging) can happen in send_eof() + so that afterward send_error() needs to find out that. + */ + bool error_handled; + +public: + multi_delete(TABLE_LIST *dt, uint num_of_tables); + ~multi_delete(); + int prepare(List &list, SELECT_LEX_UNIT *u); + bool send_data(List &items); + bool initialize_tables (JOIN *join); + void send_error(uint errcode,const char *err); + int do_deletes(); + bool send_eof(); + virtual void abort(); +}; + + +class multi_update :public select_result_interceptor +{ + TABLE_LIST *all_tables; /* query/update command tables */ + TABLE_LIST *leaves; /* list of leves of join table tree */ + TABLE_LIST *update_tables, *table_being_updated; + TABLE **tmp_tables, *main_table, *table_to_update; + TMP_TABLE_PARAM *tmp_table_param; + ha_rows updated, found; + List *fields, *values; + List **fields_for_table, **values_for_table; + uint table_count; + /* + List of tables referenced in the CHECK OPTION condition of + the updated view excluding the updated table. + */ + List
unupdated_check_opt_tables; + Copy_field *copy_field; + enum enum_duplicates handle_duplicates; + bool do_update, trans_safe; + /* True if the update operation has made a change in a transactional table */ + bool transactional_tables; + bool ignore; + /* + error handling (rollback and binlogging) can happen in send_eof() + so that afterward send_error() needs to find out that. + */ + bool error_handled; + +public: + multi_update(TABLE_LIST *ut, TABLE_LIST *leaves_list, + List *fields, List *values, + enum_duplicates handle_duplicates, bool ignore); + ~multi_update(); + int prepare(List &list, SELECT_LEX_UNIT *u); + bool send_data(List &items); + bool initialize_tables (JOIN *join); + void send_error(uint errcode,const char *err); + int do_updates(); + bool send_eof(); + virtual void abort(); +}; + +//@Bug 2703 Move class Select_fetch_protocol_binary and Prepared_statement's definition from sql_pare.cc here +/** + A result class used to send cursor rows using the binary protocol. +*/ + +class Select_fetch_protocol_binary: public select_send +{ + Protocol_binary protocol; +public: + Select_fetch_protocol_binary(THD *thd); + virtual bool send_fields(List &list, uint flags); + virtual bool send_data(List &items); + virtual bool send_eof(); +#ifdef EMBEDDED_LIBRARY + void begin_dataset() + { + protocol.begin_dataset(); + } +#endif +}; + +/****************************************************************************/ + +/** + Prepared_statement: a statement that can contain placeholders. +*/ + +class Prepared_statement: public Statement +{ +public: + enum flag_values + { + IS_IN_USE= 1, + IS_SQL_PREPARE= 2 + }; + + THD *thd; + Select_fetch_protocol_binary result; + Item_param **param_array; + uint param_count; + uint last_errno; + uint flags; + char last_error[MYSQL_ERRMSG_SIZE]; +#ifndef EMBEDDED_LIBRARY + bool (*set_params)(Prepared_statement *st, uchar *data, uchar *data_end, + uchar *read_pos, String *expanded_query); +#else + bool (*set_params_data)(Prepared_statement *st, String *expanded_query); +#endif + bool (*set_params_from_vars)(Prepared_statement *stmt, + List& varnames, + String *expanded_query); +public: + Prepared_statement(THD *thd_arg); + virtual ~Prepared_statement(); + void setup_set_params(); + virtual Query_arena::Type type() const; + virtual void cleanup_stmt(); + bool set_name(LEX_STRING *name); + void close_cursor(); + inline bool is_in_use() { return flags & (uint) IS_IN_USE; } + inline bool is_sql_prepare() const { return flags & (uint) IS_SQL_PREPARE; } + void set_sql_prepare() { flags|= (uint) IS_SQL_PREPARE; } + bool prepare(const char *packet, uint packet_length); + bool execute_loop(String *expanded_query, + bool open_cursor, + uchar *packet_arg, uchar *packet_end_arg); + /* Destroy this statement */ + void deallocate(); + bool set_parameters(String *expanded_query, + uchar *packet, uchar *packet_end); +private: + /** + The memory root to allocate parsed tree elements (instances of Item, + SELECT_LEX and other classes). + */ + MEM_ROOT main_mem_root; + /* Version of the stored functions cache at the time of prepare. */ + ulong m_sp_cache_version; +private: + bool set_db(const char *db, uint db_length); + bool execute(String *expanded_query, bool open_cursor); + bool reprepare(); + bool validate_metadata(Prepared_statement *copy); + void swap_prepared_statement(Prepared_statement *copy); +}; + + + +class my_var : public Sql_alloc { +public: + LEX_STRING s; +#ifndef DBUG_OFF + /* + Routine to which this Item_splocal belongs. Used for checking if correct + runtime context is used for variable handling. + */ + sp_head *sp; +#endif + bool local; + uint offset; + enum_field_types type; + my_var (LEX_STRING& j, bool i, uint o, enum_field_types t) + :s(j), local(i), offset(o), type(t) + {} + ~my_var() {} +}; + +class select_dumpvar :public select_result_interceptor { + ha_rows row_count; +public: + List var_list; + select_dumpvar() { var_list.empty(); row_count= 0;} + /** + Creates a select_dumpvar to represent INTO with a defined + level of subquery nesting. + */ + select_dumpvar(uint nest_level_arg) + { + var_list.empty(); + row_count= 0; + nest_level= nest_level_arg; + } + ~select_dumpvar() {} + int prepare(List &list, SELECT_LEX_UNIT *u); + bool send_data(List &items); + bool send_eof(); + virtual bool check_simple_select() const; + void cleanup(); +}; + +/* Bits in sql_command_flags */ + +#define CF_CHANGES_DATA 1 +#define CF_HAS_ROW_COUNT 2 +#define CF_STATUS_COMMAND 4 +#define CF_SHOW_TABLE_COMMAND 8 +#define CF_WRITE_LOGS_COMMAND 16 +/** + Must be set for SQL statements that may contain + Item expressions and/or use joins and tables. + Indicates that the parse tree of such statement may + contain rule-based optimizations that depend on metadata + (i.e. number of columns in a table), and consequently + that the statement must be re-prepared whenever + referenced metadata changes. Must not be set for + statements that themselves change metadata, e.g. RENAME, + ALTER and other DDL, since otherwise will trigger constant + reprepare. Consequently, complex item expressions and + joins are currently prohibited in these statements. +*/ +#define CF_REEXECUTION_FRAGILE 32 + +/* Functions in sql_class.cc */ + +void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var); + +void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var, + STATUS_VAR *dec_var); +void mark_transaction_to_rollback(THD *thd, bool all); + +#endif /* MYSQL_SERVER */ diff --git a/dbcon/mysql/sql_delete.cc b/dbcon/mysql/sql_delete.cc new file mode 100644 index 00000000..6904496e --- /dev/null +++ b/dbcon/mysql/sql_delete.cc @@ -0,0 +1,1170 @@ +/* Copyright (C) 2000 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* + Delete of records and truncate of tables. + + Multi-table deletes were introduced by Monty and Sinisa +*/ + +#include "mysql_priv.h" +#include "sql_select.h" +#include "sp_head.h" +#include "sql_trigger.h" + +/** + Implement DELETE SQL word. + + @note Like implementations of other DDL/DML in MySQL, this function + relies on the caller to close the thread tables. This is done in the + end of dispatch_command(). +*/ +// @InfiniDB. Make conds argument reference to pointer so the optimization +// result can be passed in to the InfiniDB connector. +bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *& conds, + SQL_LIST *order, ha_rows limit, ulonglong options, + bool reset_auto_increment) +{ + bool will_batch; + int error, loc_error; + TABLE *table; + SQL_SELECT *select=0; + READ_RECORD info; + bool using_limit=limit != HA_POS_ERROR; + bool transactional_table, safe_update, const_cond; + bool const_cond_result; + ha_rows deleted= 0; + bool triggers_applicable; + uint usable_index= MAX_KEY; + SELECT_LEX *select_lex= &thd->lex->select_lex; + THD::killed_state killed_status= THD::NOT_KILLED; + DBUG_ENTER("mysql_delete"); + + THD::enum_binlog_query_type query_type= + thd->lex->sql_command == SQLCOM_TRUNCATE ? + THD::STMT_QUERY_TYPE : + THD::ROW_QUERY_TYPE; + + if (open_and_lock_tables(thd, table_list)) + DBUG_RETURN(TRUE); + if (!(table= table_list->table)) + { + my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0), + table_list->view_db.str, table_list->view_name.str); + DBUG_RETURN(TRUE); + } + thd_proc_info(thd, "init"); + table->map=1; + + if (mysql_prepare_delete(thd, table_list, &conds)) + DBUG_RETURN(TRUE); + + /* check ORDER BY even if it can be ignored */ + if (order && order->elements) + { + TABLE_LIST tables; + List fields; + List all_fields; + + bzero((char*) &tables,sizeof(tables)); + tables.table = table; + tables.alias = table_list->alias; + + if (select_lex->setup_ref_array(thd, order->elements) || + setup_order(thd, select_lex->ref_pointer_array, &tables, + fields, all_fields, (ORDER*) order->first)) + { + delete select; + free_underlaid_joins(thd, &thd->lex->select_lex); + DBUG_RETURN(TRUE); + } + } + + const_cond= (!conds || conds->const_item()); + safe_update=test(thd->options & OPTION_SAFE_UPDATES); + if (safe_update && const_cond) + { + my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE, + ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0)); + DBUG_RETURN(TRUE); + } + + select_lex->no_error= thd->lex->ignore; + + const_cond_result= const_cond && (!conds || conds->val_int()); + if (thd->is_error()) + { + /* Error evaluating val_int(). */ + DBUG_RETURN(TRUE); + } + + /* + Test if the user wants to delete all rows and deletion doesn't have + any side-effects (because of triggers), so we can use optimized + handler::delete_all_rows() method. + + We implement fast TRUNCATE for InnoDB even if triggers are + present. TRUNCATE ignores triggers. + + We can use delete_all_rows() if and only if: + - We allow new functions (not using option --skip-new), and are + not in safe mode (not using option --safe-mode) + - There is no limit clause + - The condition is constant + - If there is a condition, then it it produces a non-zero value + - If the current command is DELETE FROM with no where clause + (i.e., not TRUNCATE) then: + - We should not be binlogging this statement row-based, and + - there should be no delete triggers associated with the table. + */ + if (!using_limit && const_cond_result && + !(specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE)) && + (thd->lex->sql_command == SQLCOM_TRUNCATE || + (!thd->current_stmt_binlog_row_based && + !(table->triggers && table->triggers->has_delete_triggers())))) + { + /* Update the table->file->stats.records number */ + table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); + ha_rows const maybe_deleted= table->file->stats.records; + DBUG_PRINT("debug", ("Trying to use delete_all_rows()")); + if (!(error=table->file->ha_delete_all_rows())) + { + /* + If delete_all_rows() is used, it is not possible to log the + query in row format, so we have to log it in statement format. + */ + query_type= THD::STMT_QUERY_TYPE; + error= -1; // ok + deleted= maybe_deleted; + goto cleanup; + } + if (error != HA_ERR_WRONG_COMMAND) + { + table->file->print_error(error,MYF(0)); + error=0; + goto cleanup; + } + /* Handler didn't support fast delete; Delete rows one by one */ + } + if (conds) + { + Item::cond_result result; + conds= remove_eq_conds(thd, conds, &result); + if (result == Item::COND_FALSE) // Impossible where + limit= 0; + } + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (prune_partitions(thd, table, conds)) + { + free_underlaid_joins(thd, select_lex); + thd->row_count_func= 0; + my_ok(thd, (ha_rows) thd->row_count_func); // No matching records + DBUG_RETURN(0); + } +#endif + /* Update the table->file->stats.records number */ + table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); + + table->covering_keys.clear_all(); + table->quick_keys.clear_all(); // Can't use 'only index' + select=make_select(table, 0, 0, conds, 0, &error); + if (error) + DBUG_RETURN(TRUE); + if ((select && select->check_quick(thd, safe_update, limit)) || !limit) + { + delete select; + free_underlaid_joins(thd, select_lex); + thd->row_count_func= 0; + /* + Error was already created by quick select evaluation (check_quick()). + TODO: Add error code output parameter to Item::val_xxx() methods. + Currently they rely on the user checking DA for + errors when unwinding the stack after calling Item::val_xxx(). + */ + if (thd->is_error()) + DBUG_RETURN(TRUE); + my_ok(thd, (ha_rows) thd->row_count_func); + /* + We don't need to call reset_auto_increment in this case, because + mysql_truncate always gives a NULL conds argument, hence we never + get here. + */ + DBUG_RETURN(0); // Nothing to delete + } + + /* If running in safe sql mode, don't allow updates without keys */ + if (table->quick_keys.is_clear_all()) + { + thd->server_status|=SERVER_QUERY_NO_INDEX_USED; + if (safe_update && !using_limit) + { + delete select; + free_underlaid_joins(thd, select_lex); + my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE, + ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0)); + DBUG_RETURN(TRUE); + } + } + if (options & OPTION_QUICK) + (void) table->file->extra(HA_EXTRA_QUICK); + + if (order && order->elements) + { + uint length= 0; + SORT_FIELD *sortorder; + ha_rows examined_rows; + + if ((!select || table->quick_keys.is_clear_all()) && limit != HA_POS_ERROR) + usable_index= get_index_for_order(table, (ORDER*)(order->first), limit); + + if (usable_index == MAX_KEY) + { + table->sort.io_cache= (IO_CACHE *) my_malloc(sizeof(IO_CACHE), + MYF(MY_FAE | MY_ZEROFILL)); + + if (!(sortorder= make_unireg_sortorder((ORDER*) order->first, + &length, NULL)) || + (table->sort.found_records = filesort(thd, table, sortorder, length, + select, HA_POS_ERROR, 1, + &examined_rows)) + == HA_POS_ERROR) + { + delete select; + free_underlaid_joins(thd, &thd->lex->select_lex); + DBUG_RETURN(TRUE); + } + /* + Filesort has already found and selected the rows we want to delete, + so we don't need the where clause + */ + delete select; + free_underlaid_joins(thd, select_lex); + select= 0; + } + } + + /* If quick select is used, initialize it before retrieving rows. */ + if (select && select->quick && select->quick->reset()) + { + delete select; + free_underlaid_joins(thd, select_lex); + DBUG_RETURN(TRUE); + } + if (usable_index==MAX_KEY) + init_read_record(&info, thd, table, select, 1, 1, FALSE); + else + init_read_record_idx(&info, thd, table, 1, usable_index); + + init_ftfuncs(thd, select_lex, 1); + thd_proc_info(thd, "updating"); + + /* NOTE: TRUNCATE must not invoke triggers. */ + + triggers_applicable= table->triggers && + thd->lex->sql_command != SQLCOM_TRUNCATE; + + if (triggers_applicable && + table->triggers->has_triggers(TRG_EVENT_DELETE, + TRG_ACTION_AFTER)) + { + /* + The table has AFTER DELETE triggers that might access to subject table + and therefore might need delete to be done immediately. So we turn-off + the batching. + */ + (void) table->file->extra(HA_EXTRA_DELETE_CANNOT_BATCH); + will_batch= FALSE; + } + else + will_batch= !table->file->start_bulk_delete(); + + + table->mark_columns_needed_for_delete(); + + while (!(error=info.read_record(&info)) && !thd->killed && + ! thd->is_error()) + { + // thd->is_error() is tested to disallow delete row on error + if (!(select && select->skip_record())&& ! thd->is_error() ) + { + + if (triggers_applicable && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_BEFORE, FALSE)) + { + error= 1; + break; + } + + if (!(error= table->file->ha_delete_row(table->record[0]))) + { + deleted++; + if (triggers_applicable && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_AFTER, FALSE)) + { + error= 1; + break; + } + if (!--limit && using_limit) + { + error= -1; + break; + } + } + else + { + table->file->print_error(error,MYF(0)); + /* + In < 4.0.14 we set the error number to 0 here, but that + was not sensible, because then MySQL would not roll back the + failed DELETE, and also wrote it to the binlog. For MyISAM + tables a DELETE probably never should fail (?), but for + InnoDB it can fail in a FOREIGN KEY error or an + out-of-tablespace error. + */ + error= 1; + break; + } + } + else + table->file->unlock_row(); // Row failed selection, release lock on it + } + killed_status= thd->killed; + if (killed_status != THD::NOT_KILLED || thd->is_error()) + error= 1; // Aborted + if (will_batch && (loc_error= table->file->end_bulk_delete())) + { + if (error != 1) + table->file->print_error(loc_error,MYF(0)); + error=1; + } + thd_proc_info(thd, "end"); + end_read_record(&info); + if (options & OPTION_QUICK) + (void) table->file->extra(HA_EXTRA_NORMAL); + + if (reset_auto_increment && (error < 0)) + { + /* + We're really doing a truncate and need to reset the table's + auto-increment counter. + */ + int error2= table->file->ha_reset_auto_increment(0); + + if (error2 && (error2 != HA_ERR_WRONG_COMMAND)) + { + table->file->print_error(error2, MYF(0)); + error= 1; + } + } + +cleanup: + /* + Invalidate the table in the query cache if something changed. This must + be before binlog writing and ha_autocommit_... + */ + if (deleted) + { + query_cache_invalidate3(thd, table_list, 1); + } + + delete select; + transactional_table= table->file->has_transactions(); + + if (!transactional_table && deleted > 0) + thd->transaction.stmt.modified_non_trans_table= TRUE; + + /* See similar binlogging code in sql_update.cc, for comments */ + if ((error < 0) || thd->transaction.stmt.modified_non_trans_table) + { + if (mysql_bin_log.is_open()) + { + bool const is_trans= + thd->lex->sql_command == SQLCOM_TRUNCATE ? + FALSE : + transactional_table; + + int errcode= 0; + if (error < 0) + thd->clear_error(); + else + errcode= query_error_code(thd, killed_status == THD::NOT_KILLED); + + /* + [binlog]: If 'handler::delete_all_rows()' was called and the + storage engine does not inject the rows itself, we replicate + statement-based; otherwise, 'ha_delete_row()' was used to + delete specific rows which we might log row-based. + + Note that TRUNCATE TABLE is not transactional and should + therefore be treated as a DDL. + */ + int log_result= thd->binlog_query(query_type, + thd->query, thd->query_length, + is_trans, FALSE, errcode); + + if (log_result) + { + error=1; + } + } + if (thd->transaction.stmt.modified_non_trans_table) + thd->transaction.all.modified_non_trans_table= TRUE; + } + DBUG_ASSERT(transactional_table || !deleted || thd->transaction.stmt.modified_non_trans_table); + free_underlaid_joins(thd, select_lex); + if (error < 0 || (thd->lex->ignore && !thd->is_fatal_error)) + { + /* + If a TRUNCATE TABLE was issued, the number of rows should be reported as + zero since the exact number is unknown. + */ + //@InfiniDB change. @bug4790 Only change for InfiniDB table. + // @bug5117. Add isInfiniDBDML to make sure it's InfiniDB dml stmt. + if (!(thd->infinidb_vtable.isInfiniDBDML)) + thd->row_count_func= reset_auto_increment ? 0 : deleted; + my_ok(thd, (ha_rows) thd->row_count_func); + DBUG_PRINT("info",("%ld records deleted",(long) deleted)); + } + DBUG_RETURN(error >= 0 || thd->is_error()); +} + + +/* + Prepare items in DELETE statement + + SYNOPSIS + mysql_prepare_delete() + thd - thread handler + table_list - global/local table list + conds - conditions + + RETURN VALUE + FALSE OK + TRUE error +*/ +int mysql_prepare_delete(THD *thd, TABLE_LIST *table_list, Item **conds) +{ + Item *fake_conds= 0; + SELECT_LEX *select_lex= &thd->lex->select_lex; + DBUG_ENTER("mysql_prepare_delete"); + List all_fields; + + /* + Statement-based replication of DELETE ... LIMIT is not safe as order of + rows is not defined, so in mixed mode we go to row-based. + + Note that we may consider a statement as safe if ORDER BY primary_key + is present. However it may confuse users to see very similiar statements + replicated differently. + */ + if (thd->lex->current_select->select_limit) + { + thd->lex->set_stmt_unsafe(); + thd->set_current_stmt_binlog_row_based_if_mixed(); + } + thd->lex->allow_sum_func= 0; + if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context, + &thd->lex->select_lex.top_join_list, + table_list, + &select_lex->leaf_tables, FALSE, + DELETE_ACL, SELECT_ACL) || + setup_conds(thd, table_list, select_lex->leaf_tables, conds) || + setup_ftfuncs(select_lex)) + DBUG_RETURN(TRUE); + if (!table_list->updatable || check_key_in_view(thd, table_list)) + { + my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "DELETE"); + DBUG_RETURN(TRUE); + } + { + TABLE_LIST *duplicate; + if ((duplicate= unique_table(thd, table_list, table_list->next_global, 0))) + { + update_non_unique_table_error(table_list, "DELETE", duplicate); + DBUG_RETURN(TRUE); + } + } + + if (select_lex->inner_refs_list.elements && + fix_inner_refs(thd, all_fields, select_lex, select_lex->ref_pointer_array)) + DBUG_RETURN(TRUE); + + select_lex->fix_prepare_information(thd, conds, &fake_conds); + DBUG_RETURN(FALSE); +} + + +/*************************************************************************** + Delete multiple tables from join +***************************************************************************/ + +#define MEM_STRIP_BUF_SIZE current_thd->variables.sortbuff_size + +extern "C" int refpos_order_cmp(void* arg, const void *a,const void *b) +{ + handler *file= (handler*)arg; + return file->cmp_ref((const uchar*)a, (const uchar*)b); +} + +/* + make delete specific preparation and checks after opening tables + + SYNOPSIS + mysql_multi_delete_prepare() + thd thread handler + + RETURN + FALSE OK + TRUE Error +*/ + +int mysql_multi_delete_prepare(THD *thd) +{ + LEX *lex= thd->lex; + TABLE_LIST *aux_tables= (TABLE_LIST *)lex->auxiliary_table_list.first; + TABLE_LIST *target_tbl; + DBUG_ENTER("mysql_multi_delete_prepare"); + + /* + setup_tables() need for VIEWs. JOIN::prepare() will not do it second + time. + + lex->query_tables also point on local list of DELETE SELECT_LEX + */ + if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context, + &thd->lex->select_lex.top_join_list, + lex->query_tables, + &lex->select_lex.leaf_tables, FALSE, + DELETE_ACL, SELECT_ACL)) + DBUG_RETURN(TRUE); + + + /* + Multi-delete can't be constructed over-union => we always have + single SELECT on top and have to check underlying SELECTs of it + */ + lex->select_lex.exclude_from_table_unique_test= TRUE; + /* Fix tables-to-be-deleted-from list to point at opened tables */ + for (target_tbl= (TABLE_LIST*) aux_tables; + target_tbl; + target_tbl= target_tbl->next_local) + { + if (!(target_tbl->table= target_tbl->correspondent_table->table)) + { + DBUG_ASSERT(target_tbl->correspondent_table->view && + target_tbl->correspondent_table->merge_underlying_list && + target_tbl->correspondent_table->merge_underlying_list-> + next_local); + my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0), + target_tbl->correspondent_table->view_db.str, + target_tbl->correspondent_table->view_name.str); + DBUG_RETURN(TRUE); + } + + if (!target_tbl->correspondent_table->updatable || + check_key_in_view(thd, target_tbl->correspondent_table)) + { + my_error(ER_NON_UPDATABLE_TABLE, MYF(0), + target_tbl->table_name, "DELETE"); + DBUG_RETURN(TRUE); + } + /* + Check that table from which we delete is not used somewhere + inside subqueries/view. + */ + { + TABLE_LIST *duplicate; + if ((duplicate= unique_table(thd, target_tbl->correspondent_table, + lex->query_tables, 0))) + { + update_non_unique_table_error(target_tbl->correspondent_table, + "DELETE", duplicate); + DBUG_RETURN(TRUE); + } + } + } + /* + Reset the exclude flag to false so it doesn't interfare + with further calls to unique_table + */ + lex->select_lex.exclude_from_table_unique_test= FALSE; + DBUG_RETURN(FALSE); +} + + +multi_delete::multi_delete(TABLE_LIST *dt, uint num_of_tables_arg) + : delete_tables(dt), deleted(0), found(0), + num_of_tables(num_of_tables_arg), error(0), + do_delete(0), transactional_tables(0), normal_tables(0), error_handled(0) +{ + tempfiles= (Unique **) sql_calloc(sizeof(Unique *) * num_of_tables); +} + + +int +multi_delete::prepare(List &values, SELECT_LEX_UNIT *u) +{ + DBUG_ENTER("multi_delete::prepare"); + unit= u; + do_delete= 1; + thd_proc_info(thd, "deleting from main table"); + DBUG_RETURN(0); +} + + +bool +multi_delete::initialize_tables(JOIN *join) +{ + TABLE_LIST *walk; + Unique **tempfiles_ptr; + DBUG_ENTER("initialize_tables"); + + if ((thd->options & OPTION_SAFE_UPDATES) && error_if_full_join(join)) + DBUG_RETURN(1); + + table_map tables_to_delete_from=0; + delete_while_scanning= 1; + for (walk= delete_tables; walk; walk= walk->next_local) + { + tables_to_delete_from|= walk->table->map; + if (delete_while_scanning && + unique_table(thd, walk, join->tables_list, false)) + { + /* + If the table we are going to delete from appears + in join, we need to defer delete. So the delete + doesn't interfers with the scaning of results. + */ + delete_while_scanning= 0; + } + } + + + walk= delete_tables; + for (JOIN_TAB *tab=join->join_tab, *end=join->join_tab+join->tables; + tab < end; + tab++) + { + if (tab->table->map & tables_to_delete_from) + { + /* We are going to delete from this table */ + TABLE *tbl=walk->table=tab->table; + walk= walk->next_local; + /* Don't use KEYREAD optimization on this table */ + tbl->no_keyread=1; + /* Don't use record cache */ + tbl->no_cache= 1; + tbl->covering_keys.clear_all(); + if (tbl->file->has_transactions()) + transactional_tables= 1; + else + normal_tables= 1; + if (tbl->triggers && + tbl->triggers->has_triggers(TRG_EVENT_DELETE, + TRG_ACTION_AFTER)) + { + /* + The table has AFTER DELETE triggers that might access to subject + table and therefore might need delete to be done immediately. + So we turn-off the batching. + */ + (void) tbl->file->extra(HA_EXTRA_DELETE_CANNOT_BATCH); + } + tbl->prepare_for_position(); + tbl->mark_columns_needed_for_delete(); + } + else if ((tab->type != JT_SYSTEM && tab->type != JT_CONST) && + walk == delete_tables) + { + /* + We are not deleting from the table we are scanning. In this + case send_data() shouldn't delete any rows a we may touch + the rows in the deleted table many times + */ + delete_while_scanning= 0; + } + } + walk= delete_tables; + tempfiles_ptr= tempfiles; + if (delete_while_scanning) + { + table_being_deleted= delete_tables; + walk= walk->next_local; + } + for (;walk ;walk= walk->next_local) + { + TABLE *table=walk->table; + *tempfiles_ptr++= new Unique (refpos_order_cmp, + (void *) table->file, + table->file->ref_length, + MEM_STRIP_BUF_SIZE); + } + init_ftfuncs(thd, thd->lex->current_select, 1); + DBUG_RETURN(thd->is_fatal_error != 0); +} + + +multi_delete::~multi_delete() +{ + for (table_being_deleted= delete_tables; + table_being_deleted; + table_being_deleted= table_being_deleted->next_local) + { + TABLE *table= table_being_deleted->table; + table->no_keyread=0; + } + + for (uint counter= 0; counter < num_of_tables; counter++) + { + if (tempfiles[counter]) + delete tempfiles[counter]; + } +} + + +bool multi_delete::send_data(List &values) +{ + int secure_counter= delete_while_scanning ? -1 : 0; + TABLE_LIST *del_table; + DBUG_ENTER("multi_delete::send_data"); + + bool ignore= thd->lex->current_select->no_error; + + for (del_table= delete_tables; + del_table; + del_table= del_table->next_local, secure_counter++) + { + TABLE *table= del_table->table; + + /* Check if we are using outer join and we didn't find the row */ + if (table->status & (STATUS_NULL_ROW | STATUS_DELETED)) + continue; + + table->file->position(table->record[0]); + found++; + + if (secure_counter < 0) + { + /* We are scanning the current table */ + DBUG_ASSERT(del_table == table_being_deleted); + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_BEFORE, FALSE)) + DBUG_RETURN(1); + table->status|= STATUS_DELETED; + if (!(error=table->file->ha_delete_row(table->record[0]))) + { + deleted++; + if (!table->file->has_transactions()) + thd->transaction.stmt.modified_non_trans_table= TRUE; + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_AFTER, FALSE)) + DBUG_RETURN(1); + } + else if (!ignore) + { + /* + If the IGNORE option is used errors caused by ha_delete_row don't + have to stop the iteration. + */ + table->file->print_error(error,MYF(0)); + DBUG_RETURN(1); + } + } + else + { + error=tempfiles[secure_counter]->unique_add((char*) table->file->ref); + if (error) + { + error= 1; // Fatal error + DBUG_RETURN(1); + } + } + } + DBUG_RETURN(0); +} + + +void multi_delete::send_error(uint errcode,const char *err) +{ + DBUG_ENTER("multi_delete::send_error"); + + /* First send error what ever it is ... */ + my_message(errcode, err, MYF(0)); + + DBUG_VOID_RETURN; +} + + +void multi_delete::abort() +{ + DBUG_ENTER("multi_delete::abort"); + + /* the error was handled or nothing deleted and no side effects return */ + if (error_handled || + (!thd->transaction.stmt.modified_non_trans_table && !deleted)) + DBUG_VOID_RETURN; + + /* Something already deleted so we have to invalidate cache */ + if (deleted) + query_cache_invalidate3(thd, delete_tables, 1); + + /* + If rows from the first table only has been deleted and it is + transactional, just do rollback. + The same if all tables are transactional, regardless of where we are. + In all other cases do attempt deletes ... + */ + if (do_delete && normal_tables && + (table_being_deleted != delete_tables || + !table_being_deleted->table->file->has_transactions())) + { + /* + We have to execute the recorded do_deletes() and write info into the + error log + */ + error= 1; + send_eof(); + DBUG_ASSERT(error_handled); + DBUG_VOID_RETURN; + } + + if (thd->transaction.stmt.modified_non_trans_table) + { + /* + there is only side effects; to binlog with the error + */ + if (mysql_bin_log.is_open()) + { + int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + transactional_tables, FALSE, errcode); + } + thd->transaction.all.modified_non_trans_table= true; + } + DBUG_VOID_RETURN; +} + + + +/* + Do delete from other tables. + Returns values: + 0 ok + 1 error +*/ + +int multi_delete::do_deletes() +{ + int local_error= 0, counter= 0, tmp_error; + bool will_batch; + /* + If the IGNORE option is used all non fatal errors will be translated + to warnings and we should not break the row-by-row iteration + */ + bool ignore= thd->lex->current_select->no_error; + DBUG_ENTER("do_deletes"); + DBUG_ASSERT(do_delete); + + do_delete= 0; // Mark called + if (!found) + DBUG_RETURN(0); + + table_being_deleted= (delete_while_scanning ? delete_tables->next_local : + delete_tables); + + for (; table_being_deleted; + table_being_deleted= table_being_deleted->next_local, counter++) + { + ha_rows last_deleted= deleted; + TABLE *table = table_being_deleted->table; + if (tempfiles[counter]->get(table)) + { + local_error=1; + break; + } + + READ_RECORD info; + init_read_record(&info, thd, table, NULL, 0, 1, FALSE); + /* + Ignore any rows not found in reference tables as they may already have + been deleted by foreign key handling + */ + info.ignore_not_found_rows= 1; + will_batch= !table->file->start_bulk_delete(); + while (!(local_error=info.read_record(&info)) && !thd->killed) + { + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_BEFORE, FALSE)) + { + local_error= 1; + break; + } + + local_error= table->file->ha_delete_row(table->record[0]); + if (local_error && !ignore) + { + table->file->print_error(local_error,MYF(0)); + break; + } + + /* + Increase the reported number of deleted rows only if no error occurred + during ha_delete_row. + Also, don't execute the AFTER trigger if the row operation failed. + */ + if (!local_error) + { + deleted++; + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_AFTER, FALSE)) + { + local_error= 1; + break; + } + } + } + if (will_batch && (tmp_error= table->file->end_bulk_delete())) + { + if (!local_error) + { + local_error= tmp_error; + table->file->print_error(local_error,MYF(0)); + } + } + if (last_deleted != deleted && !table->file->has_transactions()) + thd->transaction.stmt.modified_non_trans_table= TRUE; + end_read_record(&info); + if (thd->killed && !local_error) + local_error= 1; + if (local_error == -1) // End of file + local_error = 0; + } + DBUG_RETURN(local_error); +} + + +/* + Send ok to the client + + return: 0 sucess + 1 error +*/ + +bool multi_delete::send_eof() +{ + THD::killed_state killed_status= THD::NOT_KILLED; + thd_proc_info(thd, "deleting from reference tables"); + + /* Does deletes for the last n - 1 tables, returns 0 if ok */ + int local_error= do_deletes(); // returns 0 if success + + /* compute a total error to know if something failed */ + local_error= local_error || error; + killed_status= (local_error == 0)? THD::NOT_KILLED : thd->killed; + /* reset used flags */ + thd_proc_info(thd, "end"); + + /* + We must invalidate the query cache before binlog writing and + ha_autocommit_... + */ + if (deleted) + { + query_cache_invalidate3(thd, delete_tables, 1); + } + if ((local_error == 0) || thd->transaction.stmt.modified_non_trans_table) + { + if (mysql_bin_log.is_open()) + { + int errcode= 0; + if (local_error == 0) + thd->clear_error(); + else + errcode= query_error_code(thd, killed_status == THD::NOT_KILLED); + if (thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + transactional_tables, FALSE, errcode) && + !normal_tables) + { + local_error=1; // Log write failed: roll back the SQL statement + } + } + if (thd->transaction.stmt.modified_non_trans_table) + thd->transaction.all.modified_non_trans_table= TRUE; + } + if (local_error != 0) + error_handled= TRUE; // to force early leave from ::send_error() + + if (!local_error) + { + // @Infinidb change. + if ( deleted ) + thd->row_count_func= deleted; + ::my_ok(thd, (ha_rows) thd->row_count_func); + } + return 0; +} + + +/*************************************************************************** + TRUNCATE TABLE +****************************************************************************/ + +/* + Row-by-row truncation if the engine does not support table recreation. + Probably a InnoDB table. +*/ + +static bool mysql_truncate_by_delete(THD *thd, TABLE_LIST *table_list) +{ + bool error, save_binlog_row_based= thd->current_stmt_binlog_row_based; + DBUG_ENTER("mysql_truncate_by_delete"); + table_list->lock_type= TL_WRITE; + mysql_init_select(thd->lex); + thd->clear_current_stmt_binlog_row_based(); + // @InfiniDB. Make conds argument reference to pointer so the optimization + // result can be passed in to the InfiniDB connector. + COND *cond = NULL; + error= mysql_delete(thd, table_list, cond, NULL, HA_POS_ERROR, LL(0), TRUE); + ha_autocommit_or_rollback(thd, error); + end_trans(thd, error ? ROLLBACK : COMMIT); + thd->current_stmt_binlog_row_based= save_binlog_row_based; + DBUG_RETURN(error); +} + + +/* + Optimize delete of all rows by doing a full generate of the table + This will work even if the .ISM and .ISD tables are destroyed + + dont_send_ok should be set if: + - We should always wants to generate the table (even if the table type + normally can't safely do this. + - We don't want an ok to be sent to the end user. + - We don't want to log the truncate command + - If we want to have a name lock on the table on exit without errors. +*/ + +bool mysql_truncate(THD *thd, TABLE_LIST *table_list, bool dont_send_ok) +{ + HA_CREATE_INFO create_info; + char path[FN_REFLEN + 1]; + TABLE *table; + bool error; + uint path_length; + DBUG_ENTER("mysql_truncate"); + + bzero((char*) &create_info,sizeof(create_info)); + + /* Remove tables from the HANDLER's hash. */ + mysql_ha_rm_tables(thd, table_list, FALSE); + + /* If it is a temporary table, close and regenerate it */ + if (!dont_send_ok && (table= find_temporary_table(thd, table_list))) + { + handlerton *table_type= table->s->db_type(); + TABLE_SHARE *share= table->s; + if (!ha_check_storage_engine_flag(table_type, HTON_CAN_RECREATE)) + goto trunc_by_del; + + table->file->info(HA_STATUS_AUTO | HA_STATUS_NO_LOCK); + + close_temporary_table(thd, table, 0, 0); // Don't free share + ha_create_table(thd, share->normalized_path.str, + share->db.str, share->table_name.str, &create_info, 1); + // We don't need to call invalidate() because this table is not in cache + if ((error= (int) !(open_temporary_table(thd, share->path.str, + share->db.str, + share->table_name.str, 1)))) + (void) rm_temporary_table(table_type, path); + else + thd->thread_specific_used= TRUE; + + free_table_share(share); + my_free((char*) table,MYF(0)); + /* + If we return here we will not have logged the truncation to the bin log + and we will not my_ok() to the client. + */ + goto end; + } + + path_length= build_table_filename(path, sizeof(path) - 1, table_list->db, + table_list->table_name, reg_ext, 0); + + if (!dont_send_ok) + { + enum legacy_db_type table_type; + mysql_frm_type(thd, path, &table_type); + if (table_type == DB_TYPE_UNKNOWN) + { + my_error(ER_NO_SUCH_TABLE, MYF(0), + table_list->db, table_list->table_name); + DBUG_RETURN(TRUE); + } + if (!ha_check_storage_engine_flag(ha_resolve_by_legacy_type(thd, table_type), + HTON_CAN_RECREATE)) + goto trunc_by_del; + + if (lock_and_wait_for_table_name(thd, table_list)) + DBUG_RETURN(TRUE); + } + + // Remove the .frm extension AIX 5.2 64-bit compiler bug (BUG#16155): this + // crashes, replacement works. *(path + path_length - reg_ext_length)= + // '\0'; + path[path_length - reg_ext_length] = 0; + VOID(pthread_mutex_lock(&LOCK_open)); + error= ha_create_table(thd, path, table_list->db, table_list->table_name, + &create_info, 1); + VOID(pthread_mutex_unlock(&LOCK_open)); + query_cache_invalidate3(thd, table_list, 0); + +end: + if (!dont_send_ok) + { + if (!error) + { + /* + TRUNCATE must always be statement-based binlogged (not row-based) so + we don't test current_stmt_binlog_row_based. + */ + write_bin_log(thd, TRUE, thd->query, thd->query_length); + my_ok(thd); // This should return record count + } + VOID(pthread_mutex_lock(&LOCK_open)); + unlock_table_name(thd, table_list); + VOID(pthread_mutex_unlock(&LOCK_open)); + } + else if (error) + { + VOID(pthread_mutex_lock(&LOCK_open)); + unlock_table_name(thd, table_list); + VOID(pthread_mutex_unlock(&LOCK_open)); + } + DBUG_RETURN(error); + +trunc_by_del: + error= mysql_truncate_by_delete(thd, table_list); + DBUG_RETURN(error); +} diff --git a/dbcon/mysql/sql_insert.cc b/dbcon/mysql/sql_insert.cc new file mode 100644 index 00000000..20fbde52 --- /dev/null +++ b/dbcon/mysql/sql_insert.cc @@ -0,0 +1,3851 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Insert of records */ + +/* + INSERT DELAYED + + Insert delayed is distinguished from a normal insert by lock_type == + TL_WRITE_DELAYED instead of TL_WRITE. It first tries to open a + "delayed" table (delayed_get_table()), but falls back to + open_and_lock_tables() on error and proceeds as normal insert then. + + Opening a "delayed" table means to find a delayed insert thread that + has the table open already. If this fails, a new thread is created and + waited for to open and lock the table. + + If accessing the thread succeeded, in + Delayed_insert::get_local_table() the table of the thread is copied + for local use. A copy is required because the normal insert logic + works on a target table, but the other threads table object must not + be used. The insert logic uses the record buffer to create a record. + And the delayed insert thread uses the record buffer to pass the + record to the table handler. So there must be different objects. Also + the copied table is not included in the lock, so that the statement + can proceed even if the real table cannot be accessed at this moment. + + Copying a table object is not a trivial operation. Besides the TABLE + object there are the field pointer array, the field objects and the + record buffer. After copying the field objects, their pointers into + the record must be "moved" to point to the new record buffer. + + After this setup the normal insert logic is used. Only that for + delayed inserts write_delayed() is called instead of write_record(). + It inserts the rows into a queue and signals the delayed insert thread + instead of writing directly to the table. + + The delayed insert thread awakes from the signal. It locks the table, + inserts the rows from the queue, unlocks the table, and waits for the + next signal. It does normally live until a FLUSH TABLES or SHUTDOWN. + +*/ + +#include "mysql_priv.h" +#include "sp_head.h" +#include "sql_trigger.h" +#include "sql_select.h" +#include "sql_show.h" +#include "slave.h" +#include "rpl_mi.h" + +#ifndef EMBEDDED_LIBRARY +static bool delayed_get_table(THD *thd, TABLE_LIST *table_list); +static int write_delayed(THD *thd, TABLE *table, enum_duplicates duplic, + LEX_STRING query, bool ignore, bool log_on); +static void end_delayed_insert(THD *thd); +pthread_handler_t handle_delayed_insert(void *arg); +static void unlink_blobs(register TABLE *table); +#endif +static bool check_view_insertability(THD *thd, TABLE_LIST *view); + +/* Define to force use of my_malloc() if the allocated memory block is big */ + +#ifndef HAVE_ALLOCA +#define my_safe_alloca(size, min_length) my_alloca(size) +#define my_safe_afree(ptr, size, min_length) my_afree(ptr) +#else +#define my_safe_alloca(size, min_length) ((size <= min_length) ? my_alloca(size) : my_malloc(size,MYF(0))) +#define my_safe_afree(ptr, size, min_length) if (size > min_length) my_free(ptr,MYF(0)) +#endif + +/* + Check that insert/update fields are from the same single table of a view. + + SYNOPSIS + check_view_single_update() + fields The insert/update fields to be checked. + view The view for insert. + map [in/out] The insert table map. + + DESCRIPTION + This function is called in 2 cases: + 1. to check insert fields. In this case *map will be set to 0. + Insert fields are checked to be all from the same single underlying + table of the given view. Otherwise the error is thrown. Found table + map is returned in the map parameter. + 2. to check update fields of the ON DUPLICATE KEY UPDATE clause. + In this case *map contains table_map found on the previous call of + the function to check insert fields. Update fields are checked to be + from the same table as the insert fields. + + RETURN + 0 OK + 1 Error +*/ + +bool check_view_single_update(List &fields, TABLE_LIST *view, + table_map *map) +{ + /* it is join view => we need to find the table for update */ + List_iterator_fast it(fields); + Item *item; + TABLE_LIST *tbl= 0; // reset for call to check_single_table() + table_map tables= 0; + + while ((item= it++)) + tables|= item->used_tables(); + + /* Check found map against provided map */ + if (*map) + { + if (tables != *map) + goto error; + return FALSE; + } + + if (view->check_single_table(&tbl, tables, view) || tbl == 0) + goto error; + + view->table= tbl->table; + *map= tables; + + return FALSE; + +error: + my_error(ER_VIEW_MULTIUPDATE, MYF(0), + view->view_db.str, view->view_name.str); + return TRUE; +} + + +/* + Check if insert fields are correct. + + SYNOPSIS + check_insert_fields() + thd The current thread. + table The table for insert. + fields The insert fields. + values The insert values. + check_unique If duplicate values should be rejected. + + NOTE + Clears TIMESTAMP_AUTO_SET_ON_INSERT from table->timestamp_field_type + or leaves it as is, depending on if timestamp should be updated or + not. + + RETURN + 0 OK + -1 Error +*/ + +static int check_insert_fields(THD *thd, TABLE_LIST *table_list, + List &fields, List &values, + bool check_unique, table_map *map) +{ + TABLE *table= table_list->table; + + if (!table_list->updatable) + { + my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_list->alias, "INSERT"); + return -1; + } + + if (fields.elements == 0 && values.elements != 0) + { + if (!table) + { + my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0), + table_list->view_db.str, table_list->view_name.str); + return -1; + } + if (values.elements != table->s->fields) + { + my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L); + return -1; + } +#ifndef NO_EMBEDDED_ACCESS_CHECKS + Field_iterator_table_ref field_it; + field_it.set(table_list); + if (check_grant_all_columns(thd, INSERT_ACL, &field_it)) + return -1; +#endif + clear_timestamp_auto_bits(table->timestamp_field_type, + TIMESTAMP_AUTO_SET_ON_INSERT); + /* + No fields are provided so all fields must be provided in the values. + Thus we set all bits in the write set. + */ + bitmap_set_all(table->write_set); + } + else + { // Part field list + SELECT_LEX *select_lex= &thd->lex->select_lex; + Name_resolution_context *context= &select_lex->context; + Name_resolution_context_state ctx_state; + int res; + + if (fields.elements != values.elements) + { + my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L); + return -1; + } + + thd->dup_field= 0; + select_lex->no_wrap_view_item= TRUE; + + /* Save the state of the current name resolution context. */ + ctx_state.save_state(context, table_list); + + /* + Perform name resolution only in the first table - 'table_list', + which is the table that is inserted into. + */ + table_list->next_local= 0; + context->resolve_in_table_list_only(table_list); + res= setup_fields(thd, 0, fields, MARK_COLUMNS_WRITE, 0, 0); + + /* Restore the current context. */ + ctx_state.restore_state(context, table_list); + thd->lex->select_lex.no_wrap_view_item= FALSE; + + if (res) + return -1; + + if (table_list->effective_algorithm == VIEW_ALGORITHM_MERGE) + { + if (check_view_single_update(fields, table_list, map)) + return -1; + table= table_list->table; + } + + if (check_unique && thd->dup_field) + { + my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), thd->dup_field->field_name); + return -1; + } + if (table->timestamp_field) // Don't automaticly set timestamp if used + { + if (bitmap_is_set(table->write_set, + table->timestamp_field->field_index)) + clear_timestamp_auto_bits(table->timestamp_field_type, + TIMESTAMP_AUTO_SET_ON_INSERT); + else + { + bitmap_set_bit(table->write_set, + table->timestamp_field->field_index); + } + } + } + // For the values we need select_priv +#ifndef NO_EMBEDDED_ACCESS_CHECKS + table->grant.want_privilege= (SELECT_ACL & ~table->grant.privilege); +#endif + + if (check_key_in_view(thd, table_list) || + (table_list->view && + check_view_insertability(thd, table_list))) + { + my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_list->alias, "INSERT"); + return -1; + } + + return 0; +} + + +/* + Check update fields for the timestamp field. + + SYNOPSIS + check_update_fields() + thd The current thread. + insert_table_list The insert table list. + table The table for update. + update_fields The update fields. + + NOTE + If the update fields include the timestamp field, + remove TIMESTAMP_AUTO_SET_ON_UPDATE from table->timestamp_field_type. + + RETURN + 0 OK + -1 Error +*/ + +static int check_update_fields(THD *thd, TABLE_LIST *insert_table_list, + List &update_fields, table_map *map) +{ + TABLE *table= insert_table_list->table; + my_bool timestamp_mark= 0; + + if (table->timestamp_field) + { + /* + Unmark the timestamp field so that we can check if this is modified + by update_fields + */ + timestamp_mark= bitmap_test_and_clear(table->write_set, + table->timestamp_field->field_index); + } + + /* Check the fields we are going to modify */ + if (setup_fields(thd, 0, update_fields, MARK_COLUMNS_WRITE, 0, 0)) + return -1; + + if (insert_table_list->effective_algorithm == VIEW_ALGORITHM_MERGE && + check_view_single_update(update_fields, insert_table_list, map)) + return -1; + + if (table->timestamp_field) + { + /* Don't set timestamp column if this is modified. */ + if (bitmap_is_set(table->write_set, + table->timestamp_field->field_index)) + clear_timestamp_auto_bits(table->timestamp_field_type, + TIMESTAMP_AUTO_SET_ON_UPDATE); + if (timestamp_mark) + bitmap_set_bit(table->write_set, + table->timestamp_field->field_index); + } + return 0; +} + +/* + Prepare triggers for INSERT-like statement. + + SYNOPSIS + prepare_triggers_for_insert_stmt() + table Table to which insert will happen + + NOTE + Prepare triggers for INSERT-like statement by marking fields + used by triggers and inform handlers that batching of UPDATE/DELETE + cannot be done if there are BEFORE UPDATE/DELETE triggers. +*/ + +void prepare_triggers_for_insert_stmt(TABLE *table) +{ + if (table->triggers) + { + if (table->triggers->has_triggers(TRG_EVENT_DELETE, + TRG_ACTION_AFTER)) + { + /* + The table has AFTER DELETE triggers that might access to + subject table and therefore might need delete to be done + immediately. So we turn-off the batching. + */ + (void) table->file->extra(HA_EXTRA_DELETE_CANNOT_BATCH); + } + if (table->triggers->has_triggers(TRG_EVENT_UPDATE, + TRG_ACTION_AFTER)) + { + /* + The table has AFTER UPDATE triggers that might access to subject + table and therefore might need update to be done immediately. + So we turn-off the batching. + */ + (void) table->file->extra(HA_EXTRA_UPDATE_CANNOT_BATCH); + } + } + table->mark_columns_needed_for_insert(); +} + + +/** + Upgrade table-level lock of INSERT statement to TL_WRITE if + a more concurrent lock is infeasible for some reason. This is + necessary for engines without internal locking support (MyISAM). + An engine with internal locking implementation might later + downgrade the lock in handler::store_lock() method. +*/ + +static +void upgrade_lock_type(THD *thd, thr_lock_type *lock_type, + enum_duplicates duplic, + bool is_multi_insert) +{ + if (duplic == DUP_UPDATE || + (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT)) + { + *lock_type= TL_WRITE_DEFAULT; + return; + } + + if (*lock_type == TL_WRITE_DELAYED) + { + /* + We do not use delayed threads if: + - we're running in the safe mode or skip-new mode -- the + feature is disabled in these modes + - we're executing this statement on a replication slave -- + we need to ensure serial execution of queries on the + slave + - it is INSERT .. ON DUPLICATE KEY UPDATE - in this case the + insert cannot be concurrent + - this statement is directly or indirectly invoked from + a stored function or trigger (under pre-locking) - to + avoid deadlocks, since INSERT DELAYED involves a lock + upgrade (TL_WRITE_DELAYED -> TL_WRITE) which we should not + attempt while keeping other table level locks. + - this statement itself may require pre-locking. + We should upgrade the lock even though in most cases + delayed functionality may work. Unfortunately, we can't + easily identify whether the subject table is not used in + the statement indirectly via a stored function or trigger: + if it is used, that will lead to a deadlock between the + client connection and the delayed thread. + */ + if (specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE) || + thd->variables.max_insert_delayed_threads == 0 || + thd->prelocked_mode || + thd->lex->uses_stored_routines()) + { + *lock_type= TL_WRITE; + return; + } + if (thd->slave_thread) + { + /* Try concurrent insert */ + *lock_type= (duplic == DUP_UPDATE || duplic == DUP_REPLACE) ? + TL_WRITE : TL_WRITE_CONCURRENT_INSERT; + return; + } + + bool log_on= (thd->options & OPTION_BIN_LOG || + ! (thd->security_ctx->master_access & SUPER_ACL)); + if (global_system_variables.binlog_format == BINLOG_FORMAT_STMT && + log_on && mysql_bin_log.is_open() && is_multi_insert) + { + /* + Statement-based binary logging does not work in this case, because: + a) two concurrent statements may have their rows intermixed in the + queue, leading to autoincrement replication problems on slave (because + the values generated used for one statement don't depend only on the + value generated for the first row of this statement, so are not + replicable) + b) if first row of the statement has an error the full statement is + not binlogged, while next rows of the statement may be inserted. + c) if first row succeeds, statement is binlogged immediately with a + zero error code (i.e. "no error"), if then second row fails, query + will fail on slave too and slave will stop (wrongly believing that the + master got no error). + So we fallback to non-delayed INSERT. + Note that to be fully correct, we should test the "binlog format which + the delayed thread is going to use for this row". But in the common case + where the global binlog format is not changed and the session binlog + format may be changed, that is equal to the global binlog format. + We test it without mutex for speed reasons (condition rarely true), and + in the common case (global not changed) it is as good as without mutex; + if global value is changed, anyway there is uncertainty as the delayed + thread may be old and use the before-the-change value. + */ + *lock_type= TL_WRITE; + } + } +} + + +/** + Find or create a delayed insert thread for the first table in + the table list, then open and lock the remaining tables. + If a table can not be used with insert delayed, upgrade the lock + and open and lock all tables using the standard mechanism. + + @param thd thread context + @param table_list list of "descriptors" for tables referenced + directly in statement SQL text. + The first element in the list corresponds to + the destination table for inserts, remaining + tables, if any, are usually tables referenced + by sub-queries in the right part of the + INSERT. + + @return Status of the operation. In case of success 'table' + member of every table_list element points to an instance of + class TABLE. + + @sa open_and_lock_tables for more information about MySQL table + level locking +*/ + +static +bool open_and_lock_for_insert_delayed(THD *thd, TABLE_LIST *table_list) +{ + DBUG_ENTER("open_and_lock_for_insert_delayed"); + +#ifndef EMBEDDED_LIBRARY + if (delayed_get_table(thd, table_list)) + DBUG_RETURN(TRUE); + + if (table_list->table) + { + /* + Open tables used for sub-selects or in stored functions, will also + cache these functions. + */ + if (open_and_lock_tables(thd, table_list->next_global)) + { + end_delayed_insert(thd); + DBUG_RETURN(TRUE); + } + /* + First table was not processed by open_and_lock_tables(), + we need to set updatability flag "by hand". + */ + if (!table_list->derived && !table_list->view) + table_list->updatable= 1; // usual table + DBUG_RETURN(FALSE); + } +#endif + /* + * This is embedded library and we don't have auxiliary + threads OR + * a lock upgrade was requested inside delayed_get_table + because + - there are too many delayed insert threads OR + - the table has triggers. + Use a normal insert. + */ + table_list->lock_type= TL_WRITE; + DBUG_RETURN(open_and_lock_tables(thd, table_list)); +} + + +/** + INSERT statement implementation + + @note Like implementations of other DDL/DML in MySQL, this function + relies on the caller to close the thread tables. This is done in the + end of dispatch_command(). +*/ + +bool mysql_insert(THD *thd,TABLE_LIST *table_list, + List &fields, + List &values_list, + List &update_fields, + List &update_values, + enum_duplicates duplic, + bool ignore) +{ + int error, res; + bool transactional_table, joins_freed= FALSE; + bool changed; + bool was_insert_delayed= (table_list->lock_type == TL_WRITE_DELAYED); + uint value_count; + ulong counter = 1; + ulonglong id; + COPY_INFO info; + TABLE *table= 0; + List_iterator_fast its(values_list); + List_item *values; + Name_resolution_context *context; + Name_resolution_context_state ctx_state; +#ifndef EMBEDDED_LIBRARY + char *query= thd->query; + /* + log_on is about delayed inserts only. + By default, both logs are enabled (this won't cause problems if the server + runs without --log-update or --log-bin). + */ + bool log_on= ((thd->options & OPTION_BIN_LOG) || + (!(thd->security_ctx->master_access & SUPER_ACL))); +#endif + thr_lock_type lock_type; + Item *unused_conds= 0; + DBUG_ENTER("mysql_insert"); + + /* + Upgrade lock type if the requested lock is incompatible with + the current connection mode or table operation. + */ + upgrade_lock_type(thd, &table_list->lock_type, duplic, + values_list.elements > 1); + + /* + We can't write-delayed into a table locked with LOCK TABLES: + this will lead to a deadlock, since the delayed thread will + never be able to get a lock on the table. QQQ: why not + upgrade the lock here instead? + */ + if (table_list->lock_type == TL_WRITE_DELAYED && thd->locked_tables && + find_locked_table(thd, table_list->db, table_list->table_name)) + { + my_error(ER_DELAYED_INSERT_TABLE_LOCKED, MYF(0), + table_list->table_name); + DBUG_RETURN(TRUE); + } + + if (table_list->lock_type == TL_WRITE_DELAYED) + { + if (open_and_lock_for_insert_delayed(thd, table_list)) + DBUG_RETURN(TRUE); + } + else + { + if (open_and_lock_tables(thd, table_list)) + DBUG_RETURN(TRUE); + } + lock_type= table_list->lock_type; + + thd_proc_info(thd, "init"); + thd->used_tables=0; + values= its++; + value_count= values->elements; + + if (mysql_prepare_insert(thd, table_list, table, fields, values, + update_fields, update_values, duplic, &unused_conds, + FALSE, + (fields.elements || !value_count || + table_list->view != 0), + !ignore && (thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES)))) + goto abort; + + /* mysql_prepare_insert set table_list->table if it was not set */ + table= table_list->table; + + context= &thd->lex->select_lex.context; + /* + These three asserts test the hypothesis that the resetting of the name + resolution context below is not necessary at all since the list of local + tables for INSERT always consists of one table. + */ + DBUG_ASSERT(!table_list->next_local); + DBUG_ASSERT(!context->table_list->next_local); + DBUG_ASSERT(!context->first_name_resolution_table->next_name_resolution_table); + + /* Save the state of the current name resolution context. */ + ctx_state.save_state(context, table_list); + + /* + Perform name resolution only in the first table - 'table_list', + which is the table that is inserted into. + */ + table_list->next_local= 0; + context->resolve_in_table_list_only(table_list); + + while ((values= its++)) + { + counter++; + if (values->elements != value_count) + { + my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter); + goto abort; + } + if (setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0)) + goto abort; + } + its.rewind (); + + /* Restore the current context. */ + ctx_state.restore_state(context, table_list); + + /* + Fill in the given fields and dump it to the table file + */ + bzero((char*) &info,sizeof(info)); + info.ignore= ignore; + info.handle_duplicates=duplic; + info.update_fields= &update_fields; + info.update_values= &update_values; + info.view= (table_list->view ? table_list : 0); + + /* + Count warnings for all inserts. + For single line insert, generate an error if try to set a NOT NULL field + to NULL. + */ + thd->count_cuted_fields= ((values_list.elements == 1 && + !ignore) ? + CHECK_FIELD_ERROR_FOR_NULL : + CHECK_FIELD_WARN); + thd->cuted_fields = 0L; + table->next_number_field=table->found_next_number_field; + +#ifdef HAVE_REPLICATION + if (thd->slave_thread && + (info.handle_duplicates == DUP_UPDATE) && + (table->next_number_field != NULL) && + rpl_master_has_bug(&active_mi->rli, 24432, TRUE, NULL, NULL)) + goto abort; +#endif + + error=0; + thd_proc_info(thd, "update"); + if (duplic == DUP_REPLACE && + (!table->triggers || !table->triggers->has_delete_triggers())) + table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE); + if (duplic == DUP_UPDATE) + table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE); + /* + let's *try* to start bulk inserts. It won't necessary + start them as values_list.elements should be greater than + some - handler dependent - threshold. + We should not start bulk inserts if this statement uses + functions or invokes triggers since they may access + to the same table and therefore should not see its + inconsistent state created by this optimization. + So we call start_bulk_insert to perform nesessary checks on + values_list.elements, and - if nothing else - to initialize + the code to make the call of end_bulk_insert() below safe. + */ +#ifndef EMBEDDED_LIBRARY + if (lock_type != TL_WRITE_DELAYED) +#endif /* EMBEDDED_LIBRARY */ + { + if (duplic != DUP_ERROR || ignore) + table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + if (!thd->prelocked_mode) + table->file->ha_start_bulk_insert(values_list.elements); + } + + thd->abort_on_warning= (!ignore && (thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES))); + + prepare_triggers_for_insert_stmt(table); + + + if (table_list->prepare_where(thd, 0, TRUE) || + table_list->prepare_check_option(thd)) + error= 1; + + while ((values= its++)) + { + if (fields.elements || !value_count) + { + restore_record(table,s->default_values); // Get empty record + if (fill_record_n_invoke_before_triggers(thd, fields, *values, 0, + table->triggers, + TRG_EVENT_INSERT)) + { + if (values_list.elements != 1 && ! thd->is_error()) + { + info.records++; + continue; + } + /* + TODO: set thd->abort_on_warning if values_list.elements == 1 + and check that all items return warning in case of problem with + storing field. + */ + error=1; + break; + } + } + else + { + if (thd->used_tables) // Column used in values() + restore_record(table,s->default_values); // Get empty record + else + { + /* + Fix delete marker. No need to restore rest of record since it will + be overwritten by fill_record() anyway (and fill_record() does not + use default values in this case). + */ + table->record[0][0]= table->s->default_values[0]; + } + if (fill_record_n_invoke_before_triggers(thd, table->field, *values, 0, + table->triggers, + TRG_EVENT_INSERT)) + { + if (values_list.elements != 1 && ! thd->is_error()) + { + info.records++; + continue; + } + error=1; + break; + } + } + + if ((res= table_list->view_check_option(thd, + (values_list.elements == 1 ? + 0 : + ignore))) == + VIEW_CHECK_SKIP) + continue; + else if (res == VIEW_CHECK_ERROR) + { + error= 1; + break; + } +#ifndef EMBEDDED_LIBRARY + if (lock_type == TL_WRITE_DELAYED) + { + LEX_STRING const st_query = { query, thd->query_length }; + error=write_delayed(thd, table, duplic, st_query, ignore, log_on); + query=0; + } + else +#endif + error=write_record(thd, table ,&info); + if (error) + break; + thd->row_count++; + } + + free_underlaid_joins(thd, &thd->lex->select_lex); + joins_freed= TRUE; + + /* + Now all rows are inserted. Time to update logs and sends response to + user + */ +#ifndef EMBEDDED_LIBRARY + if (lock_type == TL_WRITE_DELAYED) + { + if (!error) + { + info.copied=values_list.elements; + end_delayed_insert(thd); + } + } + else +#endif + { + /* + Do not do this release if this is a delayed insert, it would steal + auto_inc values from the delayed_insert thread as they share TABLE. + */ + table->file->ha_release_auto_increment(); + if (!thd->prelocked_mode && table->file->ha_end_bulk_insert() && !error) + { + table->file->print_error(my_errno,MYF(0)); + error=1; + } + if (duplic != DUP_ERROR || ignore) + table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + + transactional_table= table->file->has_transactions(); + + if ((changed= (info.copied || info.deleted || info.updated))) + { + /* + Invalidate the table in the query cache if something changed. + For the transactional algorithm to work the invalidation must be + before binlog writing and ha_autocommit_or_rollback + */ + query_cache_invalidate3(thd, table_list, 1); + } + if ((changed && error <= 0) || + thd->transaction.stmt.modified_non_trans_table || + was_insert_delayed) + { + if (mysql_bin_log.is_open()) + { + int errcode= 0; + if (error <= 0) + { + /* + [Guilhem wrote] Temporary errors may have filled + thd->net.last_error/errno. For example if there has + been a disk full error when writing the row, and it was + MyISAM, then thd->net.last_error/errno will be set to + "disk full"... and the my_pwrite() will wait until free + space appears, and so when it finishes then the + write_row() was entirely successful + */ + /* todo: consider removing */ + thd->clear_error(); + } + else + errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + + /* bug#22725: + + A query which per-row-loop can not be interrupted with + KILLED, like INSERT, and that does not invoke stored + routines can be binlogged with neglecting the KILLED error. + + If there was no error (error == zero) until after the end of + inserting loop the KILLED flag that appeared later can be + disregarded since previously possible invocation of stored + routines did not result in any error due to the KILLED. In + such case the flag is ignored for constructing binlog event. + */ + DBUG_ASSERT(thd->killed != THD::KILL_BAD_DATA || error > 0); + if (thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + transactional_table, FALSE, + errcode)) + { + error=1; + } + } + if (thd->transaction.stmt.modified_non_trans_table) + thd->transaction.all.modified_non_trans_table= TRUE; + } + DBUG_ASSERT(transactional_table || !changed || + thd->transaction.stmt.modified_non_trans_table); + } + thd_proc_info(thd, "end"); + /* + We'll report to the client this id: + - if the table contains an autoincrement column and we successfully + inserted an autogenerated value, the autogenerated value. + - if the table contains no autoincrement column and LAST_INSERT_ID(X) was + called, X. + - if the table contains an autoincrement column, and some rows were + inserted, the id of the last "inserted" row (if IGNORE, that value may not + have been really inserted but ignored). + */ + id= (thd->first_successful_insert_id_in_cur_stmt > 0) ? + thd->first_successful_insert_id_in_cur_stmt : + (thd->arg_of_last_insert_id_function ? + thd->first_successful_insert_id_in_prev_stmt : + ((table->next_number_field && info.copied) ? + table->next_number_field->val_int() : 0)); + table->next_number_field=0; + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + table->auto_increment_field_not_null= FALSE; + if (duplic == DUP_REPLACE && + (!table->triggers || !table->triggers->has_delete_triggers())) + table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE); + + if (error) + goto abort; + if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) || + !thd->cuted_fields)) + { + thd->row_count_func= info.copied + info.deleted + + ((thd->client_capabilities & CLIENT_FOUND_ROWS) ? + info.touched : info.updated); + my_ok(thd, (ulong) thd->row_count_func, id); + } + else + { + char buff[160]; + ha_rows updated=((thd->client_capabilities & CLIENT_FOUND_ROWS) ? + info.touched : info.updated); + if (ignore) + sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records, + (lock_type == TL_WRITE_DELAYED) ? (ulong) 0 : + (ulong) (info.records - info.copied), (ulong) thd->cuted_fields); + else + sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records, + (ulong) (info.deleted + updated), (ulong) thd->cuted_fields); + thd->row_count_func= info.copied + info.deleted + updated; + ::my_ok(thd, (ulong) thd->row_count_func, id, buff); + } + thd->abort_on_warning= 0; + DBUG_RETURN(FALSE); + +abort: +#ifndef EMBEDDED_LIBRARY + if (lock_type == TL_WRITE_DELAYED) + end_delayed_insert(thd); +#endif + if (table != NULL) + table->file->ha_release_auto_increment(); + if (!joins_freed) + free_underlaid_joins(thd, &thd->lex->select_lex); + thd->abort_on_warning= 0; + DBUG_RETURN(TRUE); +} + + +/* + Additional check for insertability for VIEW + + SYNOPSIS + check_view_insertability() + thd - thread handler + view - reference on VIEW + + IMPLEMENTATION + A view is insertable if the folloings are true: + - All columns in the view are columns from a table + - All not used columns in table have a default values + - All field in view are unique (not referring to the same column) + + RETURN + FALSE - OK + view->contain_auto_increment is 1 if and only if the view contains an + auto_increment field + + TRUE - can't be used for insert +*/ + +static bool check_view_insertability(THD * thd, TABLE_LIST *view) +{ + uint num= view->view->select_lex.item_list.elements; + TABLE *table= view->table; + Field_translator *trans_start= view->field_translation, + *trans_end= trans_start + num; + Field_translator *trans; + uint used_fields_buff_size= bitmap_buffer_size(table->s->fields); + uint32 *used_fields_buff= (uint32*)thd->alloc(used_fields_buff_size); + MY_BITMAP used_fields; + enum_mark_columns save_mark_used_columns= thd->mark_used_columns; + DBUG_ENTER("check_key_in_view"); + + if (!used_fields_buff) + DBUG_RETURN(TRUE); // EOM + + DBUG_ASSERT(view->table != 0 && view->field_translation != 0); + + VOID(bitmap_init(&used_fields, used_fields_buff, table->s->fields, 0)); + bitmap_clear_all(&used_fields); + + view->contain_auto_increment= 0; + /* + we must not set query_id for fields as they're not + really used in this context + */ + thd->mark_used_columns= MARK_COLUMNS_NONE; + /* check simplicity and prepare unique test of view */ + for (trans= trans_start; trans != trans_end; trans++) + { + if (!trans->item->fixed && trans->item->fix_fields(thd, &trans->item)) + { + thd->mark_used_columns= save_mark_used_columns; + DBUG_RETURN(TRUE); + } + Item_field *field; + /* simple SELECT list entry (field without expression) */ + if (!(field= trans->item->filed_for_view_update())) + { + thd->mark_used_columns= save_mark_used_columns; + DBUG_RETURN(TRUE); + } + if (field->field->unireg_check == Field::NEXT_NUMBER) + view->contain_auto_increment= 1; + /* prepare unique test */ + /* + remove collation (or other transparent for update function) if we have + it + */ + trans->item= field; + } + thd->mark_used_columns= save_mark_used_columns; + /* unique test */ + for (trans= trans_start; trans != trans_end; trans++) + { + /* Thanks to test above, we know that all columns are of type Item_field */ + Item_field *field= (Item_field *)trans->item; + /* check fields belong to table in which we are inserting */ + if (field->field->table == table && + bitmap_fast_test_and_set(&used_fields, field->field->field_index)) + DBUG_RETURN(TRUE); + } + + DBUG_RETURN(FALSE); +} + + +/* + Check if table can be updated + + SYNOPSIS + mysql_prepare_insert_check_table() + thd Thread handle + table_list Table list + fields List of fields to be updated + where Pointer to where clause + select_insert Check is making for SELECT ... INSERT + + RETURN + FALSE ok + TRUE ERROR +*/ + +static bool mysql_prepare_insert_check_table(THD *thd, TABLE_LIST *table_list, + List &fields, + bool select_insert) +{ + bool insert_into_view= (table_list->view != 0); + DBUG_ENTER("mysql_prepare_insert_check_table"); + + /* + first table in list is the one we'll INSERT into, requires INSERT_ACL. + all others require SELECT_ACL only. the ACL requirement below is for + new leaves only anyway (view-constituents), so check for SELECT rather + than INSERT. + */ + + if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context, + &thd->lex->select_lex.top_join_list, + table_list, + &thd->lex->select_lex.leaf_tables, + select_insert, INSERT_ACL, SELECT_ACL)) + DBUG_RETURN(TRUE); + + if (insert_into_view && !fields.elements) + { + thd->lex->empty_field_list_on_rset= 1; + if (!table_list->table) + { + my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0), + table_list->view_db.str, table_list->view_name.str); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(insert_view_fields(thd, &fields, table_list)); + } + + DBUG_RETURN(FALSE); +} + + +/* + Get extra info for tables we insert into + + @param table table(TABLE object) we insert into, + might be NULL in case of view + @param table(TABLE_LIST object) or view we insert into +*/ + +static void prepare_for_positional_update(TABLE *table, TABLE_LIST *tables) +{ + if (table) + { + if(table->reginfo.lock_type != TL_WRITE_DELAYED) + table->prepare_for_position(); + return; + } + + DBUG_ASSERT(tables->view); + List_iterator it(*tables->view_tables); + TABLE_LIST *tbl; + while ((tbl= it++)) + prepare_for_positional_update(tbl->table, tbl); + + return; +} + + +/* + Prepare items in INSERT statement + + SYNOPSIS + mysql_prepare_insert() + thd Thread handler + table_list Global/local table list + table Table to insert into (can be NULL if table should + be taken from table_list->table) + where Where clause (for insert ... select) + select_insert TRUE if INSERT ... SELECT statement + check_fields TRUE if need to check that all INSERT fields are + given values. + abort_on_warning whether to report if some INSERT field is not + assigned as an error (TRUE) or as a warning (FALSE). + + TODO (in far future) + In cases of: + INSERT INTO t1 SELECT a, sum(a) as sum1 from t2 GROUP BY a + ON DUPLICATE KEY ... + we should be able to refer to sum1 in the ON DUPLICATE KEY part + + WARNING + You MUST set table->insert_values to 0 after calling this function + before releasing the table object. + + RETURN VALUE + FALSE OK + TRUE error +*/ + +bool mysql_prepare_insert(THD *thd, TABLE_LIST *table_list, + TABLE *table, List &fields, List_item *values, + List &update_fields, List &update_values, + enum_duplicates duplic, + COND **where, bool select_insert, + bool check_fields, bool abort_on_warning) +{ + SELECT_LEX *select_lex= &thd->lex->select_lex; + Name_resolution_context *context= &select_lex->context; + Name_resolution_context_state ctx_state; + bool insert_into_view= (table_list->view != 0); + bool res= 0; + table_map map= 0; + DBUG_ENTER("mysql_prepare_insert"); + DBUG_PRINT("enter", ("table_list 0x%lx, table 0x%lx, view %d", + (ulong)table_list, (ulong)table, + (int)insert_into_view)); + /* INSERT should have a SELECT or VALUES clause */ + DBUG_ASSERT (!select_insert || !values); + + /* + For subqueries in VALUES() we should not see the table in which we are + inserting (for INSERT ... SELECT this is done by changing table_list, + because INSERT ... SELECT share SELECT_LEX it with SELECT. + */ + if (!select_insert) + { + for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit(); + un; + un= un->next_unit()) + { + for (SELECT_LEX *sl= un->first_select(); + sl; + sl= sl->next_select()) + { + sl->context.outer_context= 0; + } + } + } + + if (duplic == DUP_UPDATE) + { + /* it should be allocated before Item::fix_fields() */ + if (table_list->set_insert_values(thd->mem_root)) + DBUG_RETURN(TRUE); + } + + if (mysql_prepare_insert_check_table(thd, table_list, fields, select_insert)) + DBUG_RETURN(TRUE); + + + /* Prepare the fields in the statement. */ + if (values) + { + /* if we have INSERT ... VALUES () we cannot have a GROUP BY clause */ + DBUG_ASSERT (!select_lex->group_list.elements); + + /* Save the state of the current name resolution context. */ + ctx_state.save_state(context, table_list); + + /* + Perform name resolution only in the first table - 'table_list', + which is the table that is inserted into. + */ + table_list->next_local= 0; + context->resolve_in_table_list_only(table_list); + + res= check_insert_fields(thd, context->table_list, fields, *values, + !insert_into_view, &map) || + setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0); + + if (!res && check_fields) + { + bool saved_abort_on_warning= thd->abort_on_warning; + thd->abort_on_warning= abort_on_warning; + res= check_that_all_fields_are_given_values(thd, + table ? table : + context->table_list->table, + context->table_list); + thd->abort_on_warning= saved_abort_on_warning; + } + + if (!res && duplic == DUP_UPDATE) + { + select_lex->no_wrap_view_item= TRUE; + res= check_update_fields(thd, context->table_list, update_fields, &map); + select_lex->no_wrap_view_item= FALSE; + } + + /* Restore the current context. */ + ctx_state.restore_state(context, table_list); + + if (!res) + res= setup_fields(thd, 0, update_values, MARK_COLUMNS_READ, 0, 0); + } + + if (res) + DBUG_RETURN(res); + + if (!table) + table= table_list->table; + + if (!select_insert) + { + Item *fake_conds= 0; + TABLE_LIST *duplicate; + if ((duplicate= unique_table(thd, table_list, table_list->next_global, 1))) + { + update_non_unique_table_error(table_list, "INSERT", duplicate); + DBUG_RETURN(TRUE); + } + select_lex->fix_prepare_information(thd, &fake_conds, &fake_conds); + select_lex->first_execution= 0; + } + /* + Only call prepare_for_posistion() if we are not performing a DELAYED + operation. It will instead be executed by delayed insert thread. + */ + if (duplic == DUP_UPDATE || duplic == DUP_REPLACE) + prepare_for_positional_update(table, table_list); + DBUG_RETURN(FALSE); +} + + + /* Check if there is more uniq keys after field */ + +static int last_uniq_key(TABLE *table,uint keynr) +{ + while (++keynr < table->s->keys) + if (table->key_info[keynr].flags & HA_NOSAME) + return 0; + return 1; +} + + +/* + Write a record to table with optional deleting of conflicting records, + invoke proper triggers if needed. + + SYNOPSIS + write_record() + thd - thread context + table - table to which record should be written + info - COPY_INFO structure describing handling of duplicates + and which is used for counting number of records inserted + and deleted. + + NOTE + Once this record will be written to table after insert trigger will + be invoked. If instead of inserting new record we will update old one + then both on update triggers will work instead. Similarly both on + delete triggers will be invoked if we will delete conflicting records. + + Sets thd->transaction.stmt.modified_non_trans_table to TRUE if table which is updated didn't have + transactions. + + RETURN VALUE + 0 - success + non-0 - error +*/ + + +int write_record(THD *thd, TABLE *table,COPY_INFO *info) +{ + int error, trg_error= 0; + char *key=0; + MY_BITMAP *save_read_set, *save_write_set; + ulonglong prev_insert_id= table->file->next_insert_id; + ulonglong insert_id_for_cur_row= 0; + DBUG_ENTER("write_record"); + + info->records++; + save_read_set= table->read_set; + save_write_set= table->write_set; + + if (info->handle_duplicates == DUP_REPLACE || + info->handle_duplicates == DUP_UPDATE) + { + while ((error=table->file->ha_write_row(table->record[0]))) + { + uint key_nr; + /* + If we do more than one iteration of this loop, from the second one the + row will have an explicit value in the autoinc field, which was set at + the first call of handler::update_auto_increment(). So we must save + the autogenerated value to avoid thd->insert_id_for_cur_row to become + 0. + */ + if (table->file->insert_id_for_cur_row > 0) + insert_id_for_cur_row= table->file->insert_id_for_cur_row; + else + table->file->insert_id_for_cur_row= insert_id_for_cur_row; + bool is_duplicate_key_error; + if (table->file->is_fatal_error(error, HA_CHECK_DUP)) + goto err; + is_duplicate_key_error= table->file->is_fatal_error(error, 0); + if (!is_duplicate_key_error) + { + /* + We come here when we had an ignorable error which is not a duplicate + key error. In this we ignore error if ignore flag is set, otherwise + report error as usual. We will not do any duplicate key processing. + */ + if (info->ignore) + goto ok_or_after_trg_err; /* Ignoring a not fatal error, return 0 */ + goto err; + } + if ((int) (key_nr = table->file->get_dup_key(error)) < 0) + { + error= HA_ERR_FOUND_DUPP_KEY; /* Database can't find key */ + goto err; + } + /* Read all columns for the row we are going to replace */ + table->use_all_columns(); + /* + Don't allow REPLACE to replace a row when a auto_increment column + was used. This ensures that we don't get a problem when the + whole range of the key has been used. + */ + if (info->handle_duplicates == DUP_REPLACE && + table->next_number_field && + key_nr == table->s->next_number_index && + (insert_id_for_cur_row > 0)) + goto err; + if (table->file->ha_table_flags() & HA_DUPLICATE_POS) + { + if (table->file->rnd_pos(table->record[1],table->file->dup_ref)) + goto err; + } + else + { + if (table->file->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */ + { + error=my_errno; + goto err; + } + + if (!key) + { + if (!(key=(char*) my_safe_alloca(table->s->max_unique_length, + MAX_KEY_LENGTH))) + { + error=ENOMEM; + goto err; + } + } + key_copy((uchar*) key,table->record[0],table->key_info+key_nr,0); + if ((error=(table->file->index_read_idx_map(table->record[1],key_nr, + (uchar*) key, HA_WHOLE_KEY, + HA_READ_KEY_EXACT)))) + goto err; + } + if (info->handle_duplicates == DUP_UPDATE) + { + int res= 0; + /* + We don't check for other UNIQUE keys - the first row + that matches, is updated. If update causes a conflict again, + an error is returned + */ + DBUG_ASSERT(table->insert_values != NULL); + store_record(table,insert_values); + restore_record(table,record[1]); + DBUG_ASSERT(info->update_fields->elements == + info->update_values->elements); + if (fill_record_n_invoke_before_triggers(thd, *info->update_fields, + *info->update_values, + info->ignore, + table->triggers, + TRG_EVENT_UPDATE)) + goto before_trg_err; + + /* CHECK OPTION for VIEW ... ON DUPLICATE KEY UPDATE ... */ + if (info->view && + (res= info->view->view_check_option(current_thd, info->ignore)) == + VIEW_CHECK_SKIP) + goto ok_or_after_trg_err; + if (res == VIEW_CHECK_ERROR) + goto before_trg_err; + + table->file->restore_auto_increment(prev_insert_id); + if (table->next_number_field) + table->file->adjust_next_insert_id_after_explicit_value( + table->next_number_field->val_int()); + info->touched++; + if ((table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ && + !bitmap_is_subset(table->write_set, table->read_set)) || + compare_record(table)) + { + if ((error=table->file->ha_update_row(table->record[1], + table->record[0])) && + error != HA_ERR_RECORD_IS_THE_SAME) + { + if (info->ignore && + !table->file->is_fatal_error(error, HA_CHECK_DUP_KEY)) + { + goto ok_or_after_trg_err; + } + goto err; + } + + if (error != HA_ERR_RECORD_IS_THE_SAME) + info->updated++; + else + error= 0; + /* + If ON DUP KEY UPDATE updates a row instead of inserting one, it's + like a regular UPDATE statement: it should not affect the value of a + next SELECT LAST_INSERT_ID() or mysql_insert_id(). + Except if LAST_INSERT_ID(#) was in the INSERT query, which is + handled separately by THD::arg_of_last_insert_id_function. + */ + insert_id_for_cur_row= table->file->insert_id_for_cur_row= 0; + trg_error= (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_UPDATE, + TRG_ACTION_AFTER, TRUE)); + info->copied++; + } + + if (table->next_number_field) + table->file->adjust_next_insert_id_after_explicit_value( + table->next_number_field->val_int()); + info->touched++; + + goto ok_or_after_trg_err; + } + else /* DUP_REPLACE */ + { + /* + The manual defines the REPLACE semantics that it is either + an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in + InnoDB do not function in the defined way if we allow MySQL + to convert the latter operation internally to an UPDATE. + We also should not perform this conversion if we have + timestamp field with ON UPDATE which is different from DEFAULT. + Another case when conversion should not be performed is when + we have ON DELETE trigger on table so user may notice that + we cheat here. Note that it is ok to do such conversion for + tables which have ON UPDATE but have no ON DELETE triggers, + we just should not expose this fact to users by invoking + ON UPDATE triggers. + */ + if (last_uniq_key(table,key_nr) && + !table->file->referenced_by_foreign_key() && + (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET || + table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH) && + (!table->triggers || !table->triggers->has_delete_triggers())) + { + if ((error=table->file->ha_update_row(table->record[1], + table->record[0])) && + error != HA_ERR_RECORD_IS_THE_SAME) + goto err; + if (error != HA_ERR_RECORD_IS_THE_SAME) + info->deleted++; + else + error= 0; + thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row); + /* + Since we pretend that we have done insert we should call + its after triggers. + */ + goto after_trg_n_copied_inc; + } + else + { + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_BEFORE, TRUE)) + goto before_trg_err; + if ((error=table->file->ha_delete_row(table->record[1]))) + goto err; + info->deleted++; + if (!table->file->has_transactions()) + thd->transaction.stmt.modified_non_trans_table= TRUE; + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_DELETE, + TRG_ACTION_AFTER, TRUE)) + { + trg_error= 1; + goto ok_or_after_trg_err; + } + /* Let us attempt do write_row() once more */ + } + } + } + + /* + If more than one iteration of the above while loop is done, from the second + one the row being inserted will have an explicit value in the autoinc field, + which was set at the first call of handler::update_auto_increment(). This + value is saved to avoid thd->insert_id_for_cur_row becoming 0. Use this saved + autoinc value. + */ + if (table->file->insert_id_for_cur_row == 0) + table->file->insert_id_for_cur_row= insert_id_for_cur_row; + + thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row); + /* + Restore column maps if they where replaced during an duplicate key + problem. + */ + if (table->read_set != save_read_set || + table->write_set != save_write_set) + table->column_bitmaps_set(save_read_set, save_write_set); + } + else if ((error=table->file->ha_write_row(table->record[0]))) + { + if (!info->ignore || + table->file->is_fatal_error(error, HA_CHECK_DUP)) + goto err; + table->file->restore_auto_increment(prev_insert_id); + goto ok_or_after_trg_err; + } + +after_trg_n_copied_inc: + info->copied++; + thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row); + trg_error= (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_INSERT, + TRG_ACTION_AFTER, TRUE)); + +ok_or_after_trg_err: + if (key) + my_safe_afree(key,table->s->max_unique_length,MAX_KEY_LENGTH); + if (!table->file->has_transactions()) + thd->transaction.stmt.modified_non_trans_table= TRUE; + DBUG_RETURN(trg_error); + +err: + info->last_errno= error; + /* current_select is NULL if this is a delayed insert */ + if (thd->lex->current_select) + thd->lex->current_select->no_error= 0; // Give error + table->file->print_error(error,MYF(0)); + +before_trg_err: + table->file->restore_auto_increment(prev_insert_id); + if (key) + my_safe_afree(key, table->s->max_unique_length, MAX_KEY_LENGTH); + table->column_bitmaps_set(save_read_set, save_write_set); + DBUG_RETURN(1); +} + + +/****************************************************************************** + Check that all fields with arn't null_fields are used +******************************************************************************/ + +int check_that_all_fields_are_given_values(THD *thd, TABLE *entry, + TABLE_LIST *table_list) +{ + int err= 0; + MY_BITMAP *write_set= entry->write_set; + + for (Field **field=entry->field ; *field ; field++) + { + if (!bitmap_is_set(write_set, (*field)->field_index) && + ((*field)->flags & NO_DEFAULT_VALUE_FLAG) && + ((*field)->real_type() != MYSQL_TYPE_ENUM)) + { + bool view= FALSE; + if (table_list) + { + table_list= table_list->top_table(); + view= test(table_list->view); + } + if (view) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_NO_DEFAULT_FOR_VIEW_FIELD, + ER(ER_NO_DEFAULT_FOR_VIEW_FIELD), + table_list->view_db.str, + table_list->view_name.str); + } + else + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_NO_DEFAULT_FOR_FIELD, + ER(ER_NO_DEFAULT_FOR_FIELD), + (*field)->field_name); + } + err= 1; + } + } + return thd->abort_on_warning ? err : 0; +} + +/***************************************************************************** + Handling of delayed inserts + A thread is created for each table that one uses with the DELAYED attribute. +*****************************************************************************/ + +#ifndef EMBEDDED_LIBRARY + +class delayed_row :public ilink { +public: + char *record; + enum_duplicates dup; + time_t start_time; + ulong sql_mode; + bool auto_increment_field_not_null; + bool query_start_used, ignore, log_query; + bool stmt_depends_on_first_successful_insert_id_in_prev_stmt; + ulonglong first_successful_insert_id_in_prev_stmt; + ulonglong forced_insert_id; + ulong auto_increment_increment; + ulong auto_increment_offset; + timestamp_auto_set_type timestamp_field_type; + LEX_STRING query; + Time_zone *time_zone; + + delayed_row(LEX_STRING const query_arg, enum_duplicates dup_arg, + bool ignore_arg, bool log_query_arg) + : record(0), dup(dup_arg), ignore(ignore_arg), log_query(log_query_arg), + forced_insert_id(0), query(query_arg), time_zone(0) + {} + ~delayed_row() + { + x_free(query.str); + x_free(record); + } +}; + +/** + Delayed_insert - context of a thread responsible for delayed insert + into one table. When processing delayed inserts, we create an own + thread for every distinct table. Later on all delayed inserts directed + into that table are handled by a dedicated thread. +*/ + +class Delayed_insert :public ilink { + uint locks_in_memory; + thr_lock_type delayed_lock; +public: + THD thd; + TABLE *table; + pthread_mutex_t mutex; + pthread_cond_t cond,cond_client; + volatile uint tables_in_use,stacked_inserts; + volatile bool status,dead; + COPY_INFO info; + I_List rows; + ulong group_count; + TABLE_LIST table_list; // Argument + + Delayed_insert() + :locks_in_memory(0), + table(0),tables_in_use(0),stacked_inserts(0), status(0), dead(0), + group_count(0) + { + thd.security_ctx->user=thd.security_ctx->priv_user=(char*) delayed_user; + thd.security_ctx->host=(char*) my_localhost; + thd.current_tablenr=0; + thd.version=refresh_version; + thd.command=COM_DELAYED_INSERT; + thd.lex->current_select= 0; // for my_message_sql + thd.lex->sql_command= SQLCOM_INSERT; // For innodb::store_lock() + /* + Statement-based replication of INSERT DELAYED has problems with RAND() + and user vars, so in mixed mode we go to row-based. + */ + thd.lex->set_stmt_unsafe(); + thd.set_current_stmt_binlog_row_based_if_mixed(); + + bzero((char*) &thd.net, sizeof(thd.net)); // Safety + bzero((char*) &table_list, sizeof(table_list)); // Safety + thd.system_thread= SYSTEM_THREAD_DELAYED_INSERT; + thd.security_ctx->host_or_ip= ""; + bzero((char*) &info,sizeof(info)); + pthread_mutex_init(&mutex,MY_MUTEX_INIT_FAST); + pthread_cond_init(&cond,NULL); + pthread_cond_init(&cond_client,NULL); + VOID(pthread_mutex_lock(&LOCK_thread_count)); + delayed_insert_threads++; + delayed_lock= global_system_variables.low_priority_updates ? + TL_WRITE_LOW_PRIORITY : TL_WRITE; + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + } + ~Delayed_insert() + { + /* The following is not really needed, but just for safety */ + delayed_row *row; + while ((row=rows.get())) + delete row; + if (table) + close_thread_tables(&thd); + VOID(pthread_mutex_lock(&LOCK_thread_count)); + pthread_mutex_destroy(&mutex); + pthread_cond_destroy(&cond); + pthread_cond_destroy(&cond_client); + thd.unlink(); // Must be unlinked under lock + x_free(thd.query); + thd.security_ctx->user= thd.security_ctx->host=0; + thread_count--; + delayed_insert_threads--; + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + VOID(pthread_cond_broadcast(&COND_thread_count)); /* Tell main we are ready */ + } + + /* The following is for checking when we can delete ourselves */ + inline void lock() + { + locks_in_memory++; // Assume LOCK_delay_insert + } + void unlock() + { + pthread_mutex_lock(&LOCK_delayed_insert); + if (!--locks_in_memory) + { + pthread_mutex_lock(&mutex); + if (thd.killed && ! stacked_inserts && ! tables_in_use) + { + pthread_cond_signal(&cond); + status=1; + } + pthread_mutex_unlock(&mutex); + } + pthread_mutex_unlock(&LOCK_delayed_insert); + } + inline uint lock_count() { return locks_in_memory; } + + TABLE* get_local_table(THD* client_thd); + bool handle_inserts(void); +}; + + +I_List delayed_threads; + + +/** + Return an instance of delayed insert thread that can handle + inserts into a given table, if it exists. Otherwise return NULL. +*/ + +static +Delayed_insert *find_handler(THD *thd, TABLE_LIST *table_list) +{ + thd_proc_info(thd, "waiting for delay_list"); + pthread_mutex_lock(&LOCK_delayed_insert); // Protect master list + I_List_iterator it(delayed_threads); + Delayed_insert *di; + while ((di= it++)) + { + if (!strcmp(table_list->db, di->table_list.db) && + !strcmp(table_list->table_name, di->table_list.table_name)) + { + di->lock(); + break; + } + } + pthread_mutex_unlock(&LOCK_delayed_insert); // For unlink from list + return di; +} + + +/** + Attempt to find or create a delayed insert thread to handle inserts + into this table. + + @return In case of success, table_list->table points to a local copy + of the delayed table or is set to NULL, which indicates a + request for lock upgrade. In case of failure, value of + table_list->table is undefined. + @retval TRUE - this thread ran out of resources OR + - a newly created delayed insert thread ran out of + resources OR + - the created thread failed to open and lock the table + (e.g. because it does not exist) OR + - the table opened in the created thread turned out to + be a view + @retval FALSE - table successfully opened OR + - too many delayed insert threads OR + - the table has triggers and we have to fall back to + a normal INSERT + Two latter cases indicate a request for lock upgrade. + + XXX: why do we regard INSERT DELAYED into a view as an error and + do not simply perform a lock upgrade? + + TODO: The approach with using two mutexes to work with the + delayed thread list -- LOCK_delayed_insert and + LOCK_delayed_create -- is redundant, and we only need one of + them to protect the list. The reason we have two locks is that + we do not want to block look-ups in the list while we're waiting + for the newly created thread to open the delayed table. However, + this wait itself is redundant -- we always call get_local_table + later on, and there wait again until the created thread acquires + a table lock. + + As is redundant the concept of locks_in_memory, since we already + have another counter with similar semantics - tables_in_use, + both of them are devoted to counting the number of producers for + a given consumer (delayed insert thread), only at different + stages of producer-consumer relationship. + + 'dead' and 'status' variables in Delayed_insert are redundant + too, since there is already 'di->thd.killed' and + di->stacked_inserts. +*/ + +static +bool delayed_get_table(THD *thd, TABLE_LIST *table_list) +{ + int error; + Delayed_insert *di; + DBUG_ENTER("delayed_get_table"); + + /* Must be set in the parser */ + DBUG_ASSERT(table_list->db); + + /* Find the thread which handles this table. */ + if (!(di= find_handler(thd, table_list))) + { + /* + No match. Create a new thread to handle the table, but + no more than max_insert_delayed_threads. + */ + if (delayed_insert_threads >= thd->variables.max_insert_delayed_threads) + DBUG_RETURN(0); + thd_proc_info(thd, "Creating delayed handler"); + pthread_mutex_lock(&LOCK_delayed_create); + /* + The first search above was done without LOCK_delayed_create. + Another thread might have created the handler in between. Search again. + */ + if (! (di= find_handler(thd, table_list))) + { + if (!(di= new Delayed_insert())) + { + thd->fatal_error(); + goto end_create; + } + pthread_mutex_lock(&LOCK_thread_count); + thread_count++; + pthread_mutex_unlock(&LOCK_thread_count); + di->thd.set_db(table_list->db, (uint) strlen(table_list->db)); + di->thd.set_query(my_strdup(table_list->table_name, MYF(MY_WME)), 0); + if (di->thd.db == NULL || di->thd.query == NULL) + { + /* The error is reported */ + delete di; + thd->fatal_error(); + goto end_create; + } + di->table_list= *table_list; // Needed to open table + /* Replace volatile strings with local copies */ + di->table_list.alias= di->table_list.table_name= di->thd.query; + di->table_list.db= di->thd.db; + di->lock(); + pthread_mutex_lock(&di->mutex); + if ((error= pthread_create(&di->thd.real_id, &connection_attrib, + handle_delayed_insert, (void*) di))) + { + DBUG_PRINT("error", + ("Can't create thread to handle delayed insert (error %d)", + error)); + pthread_mutex_unlock(&di->mutex); + di->unlock(); + delete di; + my_error(ER_CANT_CREATE_THREAD, MYF(0), error); + thd->fatal_error(); + goto end_create; + } + + /* Wait until table is open */ + thd_proc_info(thd, "waiting for handler open"); + while (!di->thd.killed && !di->table && !thd->killed) + { + pthread_cond_wait(&di->cond_client, &di->mutex); + } + pthread_mutex_unlock(&di->mutex); + thd_proc_info(thd, "got old table"); + if (di->thd.killed) + { + if (di->thd.is_error()) + { + /* + Copy the error message. Note that we don't treat fatal + errors in the delayed thread as fatal errors in the + main thread. Use of my_message will enable stored + procedures continue handlers. + */ + my_message(di->thd.main_da.sql_errno(), di->thd.main_da.message(), + MYF(0)); + } + di->unlock(); + goto end_create; + } + if (thd->killed) + { + di->unlock(); + goto end_create; + } + pthread_mutex_lock(&LOCK_delayed_insert); + delayed_threads.append(di); + pthread_mutex_unlock(&LOCK_delayed_insert); + } + pthread_mutex_unlock(&LOCK_delayed_create); + } + + pthread_mutex_lock(&di->mutex); + table_list->table= di->get_local_table(thd); + pthread_mutex_unlock(&di->mutex); + if (table_list->table) + { + DBUG_ASSERT(! thd->is_error()); + thd->di= di; + } + /* Unlock the delayed insert object after its last access. */ + di->unlock(); + DBUG_RETURN((table_list->table == NULL)); + +end_create: + pthread_mutex_unlock(&LOCK_delayed_create); + DBUG_RETURN(thd->is_error()); +} + + +/** + As we can't let many client threads modify the same TABLE + structure of the dedicated delayed insert thread, we create an + own structure for each client thread. This includes a row + buffer to save the column values and new fields that point to + the new row buffer. The memory is allocated in the client + thread and is freed automatically. + + @pre This function is called from the client thread. Delayed + insert thread mutex must be acquired before invoking this + function. + + @return Not-NULL table object on success. NULL in case of an error, + which is set in client_thd. +*/ + +TABLE *Delayed_insert::get_local_table(THD* client_thd) +{ + my_ptrdiff_t adjust_ptrs; + Field **field,**org_field, *found_next_number_field; + TABLE *copy; + TABLE_SHARE *share; + uchar *bitmap; + DBUG_ENTER("Delayed_insert::get_local_table"); + + /* First request insert thread to get a lock */ + status=1; + tables_in_use++; + if (!thd.lock) // Table is not locked + { + thd_proc_info(client_thd, "waiting for handler lock"); + pthread_cond_signal(&cond); // Tell handler to lock table + while (!dead && !thd.lock && ! client_thd->killed) + { + pthread_cond_wait(&cond_client,&mutex); + } + thd_proc_info(client_thd, "got handler lock"); + if (client_thd->killed) + goto error; + if (dead) + { + my_message(thd.main_da.sql_errno(), thd.main_da.message(), MYF(0)); + goto error; + } + } + share= table->s; + + /* + Allocate memory for the TABLE object, the field pointers array, and + one record buffer of reclength size. Normally a table has three + record buffers of rec_buff_length size, which includes alignment + bytes. Since the table copy is used for creating one record only, + the other record buffers and alignment are unnecessary. + */ + thd_proc_info(client_thd, "allocating local table"); + copy= (TABLE*) client_thd->alloc(sizeof(*copy)+ + (share->fields+1)*sizeof(Field**)+ + share->reclength + + share->column_bitmap_size*2); + if (!copy) + goto error; + + /* Copy the TABLE object. */ + *copy= *table; + /* We don't need to change the file handler here */ + /* Assign the pointers for the field pointers array and the record. */ + field= copy->field= (Field**) (copy + 1); + bitmap= (uchar*) (field + share->fields + 1); + copy->record[0]= (bitmap + share->column_bitmap_size * 2); + memcpy((char*) copy->record[0], (char*) table->record[0], share->reclength); + /* + Make a copy of all fields. + The copied fields need to point into the copied record. This is done + by copying the field objects with their old pointer values and then + "move" the pointers by the distance between the original and copied + records. That way we preserve the relative positions in the records. + */ + adjust_ptrs= PTR_BYTE_DIFF(copy->record[0], table->record[0]); + found_next_number_field= table->found_next_number_field; + for (org_field= table->field; *org_field; org_field++, field++) + { + if (!(*field= (*org_field)->new_field(client_thd->mem_root, copy, 1))) + goto error; + (*field)->orig_table= copy; // Remove connection + (*field)->move_field_offset(adjust_ptrs); // Point at copy->record[0] + if (*org_field == found_next_number_field) + (*field)->table->found_next_number_field= *field; + } + *field=0; + + /* Adjust timestamp */ + if (table->timestamp_field) + { + /* Restore offset as this may have been reset in handle_inserts */ + copy->timestamp_field= + (Field_timestamp*) copy->field[share->timestamp_field_offset]; + copy->timestamp_field->unireg_check= table->timestamp_field->unireg_check; + copy->timestamp_field_type= copy->timestamp_field->get_auto_set_type(); + } + + /* Adjust in_use for pointing to client thread */ + copy->in_use= client_thd; + + /* Adjust lock_count. This table object is not part of a lock. */ + copy->lock_count= 0; + + /* Adjust bitmaps */ + copy->def_read_set.bitmap= (my_bitmap_map*) bitmap; + copy->def_write_set.bitmap= ((my_bitmap_map*) + (bitmap + share->column_bitmap_size)); + copy->tmp_set.bitmap= 0; // To catch errors + bzero((char*) bitmap, share->column_bitmap_size*2); + copy->read_set= ©->def_read_set; + copy->write_set= ©->def_write_set; + + DBUG_RETURN(copy); + + /* Got fatal error */ + error: + tables_in_use--; + status=1; + pthread_cond_signal(&cond); // Inform thread about abort + DBUG_RETURN(0); +} + + +/* Put a question in queue */ + +static +int write_delayed(THD *thd, TABLE *table, enum_duplicates duplic, + LEX_STRING query, bool ignore, bool log_on) +{ + delayed_row *row= 0; + Delayed_insert *di=thd->di; + const Discrete_interval *forced_auto_inc; + DBUG_ENTER("write_delayed"); + DBUG_PRINT("enter", ("query = '%s' length %lu", query.str, + (ulong) query.length)); + + thd_proc_info(thd, "waiting for handler insert"); + pthread_mutex_lock(&di->mutex); + while (di->stacked_inserts >= delayed_queue_size && !thd->killed) + pthread_cond_wait(&di->cond_client,&di->mutex); + thd_proc_info(thd, "storing row into queue"); + + if (thd->killed) + goto err; + + /* + Take a copy of the query string, if there is any. The string will + be free'ed when the row is destroyed. If there is no query string, + we don't do anything special. + */ + + if (query.str) + { + char *str; + if (!(str= my_strndup(query.str, query.length, MYF(MY_WME)))) + goto err; + query.str= str; + } + row= new delayed_row(query, duplic, ignore, log_on); + if (row == NULL) + { + my_free(query.str, MYF(MY_WME)); + goto err; + } + + if (!(row->record= (char*) my_malloc(table->s->reclength, MYF(MY_WME)))) + goto err; + memcpy(row->record, table->record[0], table->s->reclength); + row->start_time= thd->start_time; + row->query_start_used= thd->query_start_used; + /* + those are for the binlog: LAST_INSERT_ID() has been evaluated at this + time, so record does not need it, but statement-based binlogging of the + INSERT will need when the row is actually inserted. + As for SET INSERT_ID, DELAYED does not honour it (BUG#20830). + */ + row->stmt_depends_on_first_successful_insert_id_in_prev_stmt= + thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt; + row->first_successful_insert_id_in_prev_stmt= + thd->first_successful_insert_id_in_prev_stmt; + row->timestamp_field_type= table->timestamp_field_type; + + /* Add session variable timezone + Time_zone object will not be freed even the thread is ended. + So we can get time_zone object from thread which handling delayed statement. + See the comment of my_tz_find() for detail. + */ + if (thd->time_zone_used) + { + row->time_zone = thd->variables.time_zone; + } + else + { + row->time_zone = NULL; + } + /* Copy session variables. */ + row->auto_increment_increment= thd->variables.auto_increment_increment; + row->auto_increment_offset= thd->variables.auto_increment_offset; + row->sql_mode= thd->variables.sql_mode; + row->auto_increment_field_not_null= table->auto_increment_field_not_null; + + /* Copy the next forced auto increment value, if any. */ + if ((forced_auto_inc= thd->auto_inc_intervals_forced.get_next())) + { + row->forced_insert_id= forced_auto_inc->minimum(); + DBUG_PRINT("delayed", ("transmitting auto_inc: %lu", + (ulong) row->forced_insert_id)); + } + + di->rows.push_back(row); + di->stacked_inserts++; + di->status=1; + if (table->s->blob_fields) + unlink_blobs(table); + pthread_cond_signal(&di->cond); + + thread_safe_increment(delayed_rows_in_use,&LOCK_delayed_status); + pthread_mutex_unlock(&di->mutex); + DBUG_RETURN(0); + + err: + delete row; + pthread_mutex_unlock(&di->mutex); + DBUG_RETURN(1); +} + +/** + Signal the delayed insert thread that this user connection + is finished using it for this statement. +*/ + +static void end_delayed_insert(THD *thd) +{ + DBUG_ENTER("end_delayed_insert"); + Delayed_insert *di=thd->di; + pthread_mutex_lock(&di->mutex); + DBUG_PRINT("info",("tables in use: %d",di->tables_in_use)); + if (!--di->tables_in_use || di->thd.killed) + { // Unlock table + di->status=1; + pthread_cond_signal(&di->cond); + } + pthread_mutex_unlock(&di->mutex); + DBUG_VOID_RETURN; +} + + +/* We kill all delayed threads when doing flush-tables */ + +void kill_delayed_threads(void) +{ + VOID(pthread_mutex_lock(&LOCK_delayed_insert)); // For unlink from list + + I_List_iterator it(delayed_threads); + Delayed_insert *di; + while ((di= it++)) + { + di->thd.killed= THD::KILL_CONNECTION; + if (di->thd.mysys_var) + { + pthread_mutex_lock(&di->thd.mysys_var->mutex); + if (di->thd.mysys_var->current_cond) + { + /* + We need the following test because the main mutex may be locked + in handle_delayed_insert() + */ + if (&di->mutex != di->thd.mysys_var->current_mutex) + pthread_mutex_lock(di->thd.mysys_var->current_mutex); + pthread_cond_broadcast(di->thd.mysys_var->current_cond); + if (&di->mutex != di->thd.mysys_var->current_mutex) + pthread_mutex_unlock(di->thd.mysys_var->current_mutex); + } + pthread_mutex_unlock(&di->thd.mysys_var->mutex); + } + } + VOID(pthread_mutex_unlock(&LOCK_delayed_insert)); // For unlink from list +} + + +/* + * Create a new delayed insert thread +*/ + +pthread_handler_t handle_delayed_insert(void *arg) +{ + Delayed_insert *di=(Delayed_insert*) arg; + THD *thd= &di->thd; + + pthread_detach_this_thread(); + /* Add thread to THD list so that's it's visible in 'show processlist' */ + pthread_mutex_lock(&LOCK_thread_count); + thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; + thd->set_current_time(); + threads.append(thd); + thd->killed=abort_loop ? THD::KILL_CONNECTION : THD::NOT_KILLED; + pthread_mutex_unlock(&LOCK_thread_count); + + /* + Wait until the client runs into pthread_cond_wait(), + where we free it after the table is opened and di linked in the list. + If we did not wait here, the client might detect the opened table + before it is linked to the list. It would release LOCK_delayed_create + and allow another thread to create another handler for the same table, + since it does not find one in the list. + */ + pthread_mutex_lock(&di->mutex); +#if !defined( __WIN__) /* Win32 calls this in pthread_create */ + if (my_thread_init()) + { + /* Can't use my_error since store_globals has not yet been called */ + thd->main_da.set_error_status(thd, ER_OUT_OF_RESOURCES, + ER(ER_OUT_OF_RESOURCES)); + goto end; + } +#endif + + DBUG_ENTER("handle_delayed_insert"); + thd->thread_stack= (char*) &thd; + if (init_thr_lock() || thd->store_globals()) + { + /* Can't use my_error since store_globals has perhaps failed */ + thd->main_da.set_error_status(thd, ER_OUT_OF_RESOURCES, + ER(ER_OUT_OF_RESOURCES)); + thd->fatal_error(); + goto err; + } + + /* + Open table requires an initialized lex in case the table is + partitioned. The .frm file contains a partial SQL string which is + parsed using a lex, that depends on initialized thd->lex. + */ + lex_start(thd); + thd->lex->sql_command= SQLCOM_INSERT; // For innodb::store_lock() + /* + Statement-based replication of INSERT DELAYED has problems with RAND() + and user vars, so in mixed mode we go to row-based. + */ + thd->lex->set_stmt_unsafe(); + thd->set_current_stmt_binlog_row_based_if_mixed(); + + /* Open table */ + if (!(di->table= open_n_lock_single_table(thd, &di->table_list, + TL_WRITE_DELAYED))) + { + thd->fatal_error(); // Abort waiting inserts + goto err; + } + if (!(di->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED)) + { + thd->fatal_error(); + my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), di->table_list.table_name); + goto err; + } + if (di->table->triggers) + { + /* + Table has triggers. This is not an error, but we do + not support triggers with delayed insert. Terminate the delayed + thread without an error and thus request lock upgrade. + */ + goto err; + } + di->table->copy_blobs=1; + + /* Tell client that the thread is initialized */ + pthread_cond_signal(&di->cond_client); + + /* Now wait until we get an insert or lock to handle */ + /* We will not abort as long as a client thread uses this thread */ + + for (;;) + { + if (thd->killed == THD::KILL_CONNECTION) + { + uint lock_count; + /* + Remove this from delay insert list so that no one can request a + table from this + */ + pthread_mutex_unlock(&di->mutex); + pthread_mutex_lock(&LOCK_delayed_insert); + di->unlink(); + lock_count=di->lock_count(); + pthread_mutex_unlock(&LOCK_delayed_insert); + pthread_mutex_lock(&di->mutex); + if (!lock_count && !di->tables_in_use && !di->stacked_inserts) + break; // Time to die + } + + if (!di->status && !di->stacked_inserts) + { + struct timespec abstime; + set_timespec(abstime, delayed_insert_timeout); + + /* Information for pthread_kill */ + di->thd.mysys_var->current_mutex= &di->mutex; + di->thd.mysys_var->current_cond= &di->cond; + thd_proc_info(&(di->thd), "Waiting for INSERT"); + + DBUG_PRINT("info",("Waiting for someone to insert rows")); + while (!thd->killed) + { + int error; +#if defined(HAVE_BROKEN_COND_TIMEDWAIT) + error=pthread_cond_wait(&di->cond,&di->mutex); +#else + error=pthread_cond_timedwait(&di->cond,&di->mutex,&abstime); +#ifdef EXTRA_DEBUG + if (error && error != EINTR && error != ETIMEDOUT) + { + fprintf(stderr, "Got error %d from pthread_cond_timedwait\n",error); + DBUG_PRINT("error",("Got error %d from pthread_cond_timedwait", + error)); + } +#endif +#endif + if (thd->killed || di->status) + break; + if (error == ETIMEDOUT || error == ETIME) + { + thd->killed= THD::KILL_CONNECTION; + break; + } + } + /* We can't lock di->mutex and mysys_var->mutex at the same time */ + pthread_mutex_unlock(&di->mutex); + pthread_mutex_lock(&di->thd.mysys_var->mutex); + di->thd.mysys_var->current_mutex= 0; + di->thd.mysys_var->current_cond= 0; + pthread_mutex_unlock(&di->thd.mysys_var->mutex); + pthread_mutex_lock(&di->mutex); + } + thd_proc_info(&(di->thd), 0); + + if (di->tables_in_use && ! thd->lock) + { + bool not_used; + /* + Request for new delayed insert. + Lock the table, but avoid to be blocked by a global read lock. + If we got here while a global read lock exists, then one or more + inserts started before the lock was requested. These are allowed + to complete their work before the server returns control to the + client which requested the global read lock. The delayed insert + handler will close the table and finish when the outstanding + inserts are done. + */ + if (! (thd->lock= mysql_lock_tables(thd, &di->table, 1, + MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK, + ¬_used))) + { + /* Fatal error */ + di->dead= 1; + thd->killed= THD::KILL_CONNECTION; + } + pthread_cond_broadcast(&di->cond_client); + } + if (di->stacked_inserts) + { + if (di->handle_inserts()) + { + /* Some fatal error */ + di->dead= 1; + thd->killed= THD::KILL_CONNECTION; + } + } + di->status=0; + if (!di->stacked_inserts && !di->tables_in_use && thd->lock) + { + /* + No one is doing a insert delayed + Unlock table so that other threads can use it + */ + MYSQL_LOCK *lock=thd->lock; + thd->lock=0; + pthread_mutex_unlock(&di->mutex); + /* + We need to release next_insert_id before unlocking. This is + enforced by handler::ha_external_lock(). + */ + di->table->file->ha_release_auto_increment(); + mysql_unlock_tables(thd, lock); + ha_autocommit_or_rollback(thd, 0); + di->group_count=0; + pthread_mutex_lock(&di->mutex); + } + if (di->tables_in_use) + pthread_cond_broadcast(&di->cond_client); // If waiting clients + } + +err: + /* + mysql_lock_tables() can potentially start a transaction and write + a table map. In the event of an error, that transaction has to be + rolled back. We only need to roll back a potential statement + transaction, since real transactions are rolled back in + close_thread_tables(). + + TODO: This is not true any more, table maps are generated on the + first call to ha_*_row() instead. Remove code that are used to + cover for the case outlined above. + */ + ha_autocommit_or_rollback(thd, 1); + +#ifndef __WIN__ +end: +#endif + /* + di should be unlinked from the thread handler list and have no active + clients + */ + + close_thread_tables(thd); // Free the table + di->table=0; + di->dead= 1; // If error + thd->killed= THD::KILL_CONNECTION; // If error + pthread_cond_broadcast(&di->cond_client); // Safety + pthread_mutex_unlock(&di->mutex); + + pthread_mutex_lock(&LOCK_delayed_create); // Because of delayed_get_table + pthread_mutex_lock(&LOCK_delayed_insert); + delete di; + pthread_mutex_unlock(&LOCK_delayed_insert); + pthread_mutex_unlock(&LOCK_delayed_create); + + my_thread_end(); + pthread_exit(0); + DBUG_RETURN(0); +} + + +/* Remove pointers from temporary fields to allocated values */ + +static void unlink_blobs(register TABLE *table) +{ + for (Field **ptr=table->field ; *ptr ; ptr++) + { + if ((*ptr)->flags & BLOB_FLAG) + ((Field_blob *) (*ptr))->clear_temporary(); + } +} + +/* Free blobs stored in current row */ + +static void free_delayed_insert_blobs(register TABLE *table) +{ + for (Field **ptr=table->field ; *ptr ; ptr++) + { + if ((*ptr)->flags & BLOB_FLAG) + { + uchar *str; + ((Field_blob *) (*ptr))->get_ptr(&str); + my_free(str,MYF(MY_ALLOW_ZERO_PTR)); + ((Field_blob *) (*ptr))->reset(); + } + } +} + + +bool Delayed_insert::handle_inserts(void) +{ + int error; + ulong max_rows; + bool using_ignore= 0, using_opt_replace= 0, + using_bin_log= mysql_bin_log.is_open(); + delayed_row *row; + DBUG_ENTER("handle_inserts"); + + /* Allow client to insert new rows */ + pthread_mutex_unlock(&mutex); + + table->next_number_field=table->found_next_number_field; + table->use_all_columns(); + + thd_proc_info(&thd, "upgrading lock"); + if (thr_upgrade_write_delay_lock(*thd.lock->locks, delayed_lock)) + { + /* + This can happen if thread is killed either by a shutdown + or if another thread is removing the current table definition + from the table cache. + */ + my_error(ER_DELAYED_CANT_CHANGE_LOCK,MYF(ME_FATALERROR), + table->s->table_name.str); + goto err; + } + + thd_proc_info(&thd, "insert"); + max_rows= delayed_insert_limit; + if (thd.killed || table->needs_reopen_or_name_lock()) + { + thd.killed= THD::KILL_CONNECTION; + max_rows= ULONG_MAX; // Do as much as possible + } + + /* + We can't use row caching when using the binary log because if + we get a crash, then binary log will contain rows that are not yet + written to disk, which will cause problems in replication. + */ + if (!using_bin_log) + table->file->extra(HA_EXTRA_WRITE_CACHE); + pthread_mutex_lock(&mutex); + + while ((row=rows.get())) + { + stacked_inserts--; + pthread_mutex_unlock(&mutex); + memcpy(table->record[0],row->record,table->s->reclength); + + thd.start_time=row->start_time; + thd.query_start_used=row->query_start_used; + /* + To get the exact auto_inc interval to store in the binlog we must not + use values from the previous interval (of the previous rows). + */ + bool log_query= (row->log_query && row->query.str != NULL); + DBUG_PRINT("delayed", ("query: '%s' length: %lu", row->query.str ? + row->query.str : "[NULL]", + (ulong) row->query.length)); + if (log_query) + { + /* + This is the first value of an INSERT statement. + It is the right place to clear a forced insert_id. + This is usually done after the last value of an INSERT statement, + but we won't know this in the insert delayed thread. But before + the first value is sufficiently equivalent to after the last + value of the previous statement. + */ + table->file->ha_release_auto_increment(); + thd.auto_inc_intervals_in_cur_stmt_for_binlog.empty(); + } + thd.first_successful_insert_id_in_prev_stmt= + row->first_successful_insert_id_in_prev_stmt; + thd.stmt_depends_on_first_successful_insert_id_in_prev_stmt= + row->stmt_depends_on_first_successful_insert_id_in_prev_stmt; + table->timestamp_field_type= row->timestamp_field_type; + table->auto_increment_field_not_null= row->auto_increment_field_not_null; + + /* Copy the session variables. */ + thd.variables.auto_increment_increment= row->auto_increment_increment; + thd.variables.auto_increment_offset= row->auto_increment_offset; + thd.variables.sql_mode= row->sql_mode; + + /* Copy a forced insert_id, if any. */ + if (row->forced_insert_id) + { + DBUG_PRINT("delayed", ("received auto_inc: %lu", + (ulong) row->forced_insert_id)); + thd.force_one_auto_inc_interval(row->forced_insert_id); + } + + info.ignore= row->ignore; + info.handle_duplicates= row->dup; + if (info.ignore || + info.handle_duplicates != DUP_ERROR) + { + table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + using_ignore=1; + } + if (info.handle_duplicates == DUP_REPLACE && + (!table->triggers || + !table->triggers->has_delete_triggers())) + { + table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE); + using_opt_replace= 1; + } + if (info.handle_duplicates == DUP_UPDATE) + table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE); + thd.clear_error(); // reset error for binlog + if (write_record(&thd, table, &info)) + { + info.error_count++; // Ignore errors + thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status); + row->log_query = 0; + } + + if (using_ignore) + { + using_ignore=0; + table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + } + if (using_opt_replace) + { + using_opt_replace= 0; + table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE); + } + + if (log_query && mysql_bin_log.is_open()) + { + bool backup_time_zone_used = thd.time_zone_used; + Time_zone *backup_time_zone = thd.variables.time_zone; + if (row->time_zone != NULL) + { + thd.time_zone_used = true; + thd.variables.time_zone = row->time_zone; + } + + /* if the delayed insert was killed, the killed status is + ignored while binlogging */ + int errcode= 0; + if (thd.killed == THD::NOT_KILLED) + errcode= query_error_code(&thd, TRUE); + + /* + If the query has several rows to insert, only the first row will come + here. In row-based binlogging, this means that the first row will be + written to binlog as one Table_map event and one Rows event (due to an + event flush done in binlog_query()), then all other rows of this query + will be binlogged together as one single Table_map event and one + single Rows event. + */ + thd.binlog_query(THD::ROW_QUERY_TYPE, + row->query.str, row->query.length, + FALSE, FALSE, errcode); + + thd.time_zone_used = backup_time_zone_used; + thd.variables.time_zone = backup_time_zone; + } + + if (table->s->blob_fields) + free_delayed_insert_blobs(table); + thread_safe_decrement(delayed_rows_in_use,&LOCK_delayed_status); + thread_safe_increment(delayed_insert_writes,&LOCK_delayed_status); + pthread_mutex_lock(&mutex); + + delete row; + /* + Let READ clients do something once in a while + We should however not break in the middle of a multi-line insert + if we have binary logging enabled as we don't want other commands + on this table until all entries has been processed + */ + if (group_count++ >= max_rows && (row= rows.head()) && + (!(row->log_query & using_bin_log))) + { + group_count=0; + if (stacked_inserts || tables_in_use) // Let these wait a while + { + if (tables_in_use) + pthread_cond_broadcast(&cond_client); // If waiting clients + thd_proc_info(&thd, "reschedule"); + pthread_mutex_unlock(&mutex); + if ((error=table->file->extra(HA_EXTRA_NO_CACHE))) + { + /* This should never happen */ + table->file->print_error(error,MYF(0)); + sql_print_error("%s", thd.main_da.message()); + DBUG_PRINT("error", ("HA_EXTRA_NO_CACHE failed in loop")); + goto err; + } + query_cache_invalidate3(&thd, table, 1); + if (thr_reschedule_write_lock(*thd.lock->locks)) + { + /* This is not known to happen. */ + my_error(ER_DELAYED_CANT_CHANGE_LOCK,MYF(ME_FATALERROR), + table->s->table_name.str); + goto err; + } + if (!using_bin_log) + table->file->extra(HA_EXTRA_WRITE_CACHE); + pthread_mutex_lock(&mutex); + thd_proc_info(&thd, "insert"); + } + if (tables_in_use) + pthread_cond_broadcast(&cond_client); // If waiting clients + } + } + thd_proc_info(&thd, 0); + pthread_mutex_unlock(&mutex); + + /* + We need to flush the pending event when using row-based + replication since the flushing normally done in binlog_query() is + not done last in the statement: for delayed inserts, the insert + statement is logged *before* all rows are inserted. + + We can flush the pending event without checking the thd->lock + since the delayed insert *thread* is not inside a stored function + or trigger. + + TODO: Move the logging to last in the sequence of rows. + */ + if (thd.current_stmt_binlog_row_based) + thd.binlog_flush_pending_rows_event(TRUE); + + if ((error=table->file->extra(HA_EXTRA_NO_CACHE))) + { // This shouldn't happen + table->file->print_error(error,MYF(0)); + sql_print_error("%s", thd.main_da.message()); + DBUG_PRINT("error", ("HA_EXTRA_NO_CACHE failed after loop")); + goto err; + } + query_cache_invalidate3(&thd, table, 1); + pthread_mutex_lock(&mutex); + DBUG_RETURN(0); + + err: +#ifndef DBUG_OFF + max_rows= 0; // For DBUG output +#endif + /* Remove all not used rows */ + while ((row=rows.get())) + { + if (table->s->blob_fields) + { + memcpy(table->record[0],row->record,table->s->reclength); + free_delayed_insert_blobs(table); + } + delete row; + thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status); + stacked_inserts--; +#ifndef DBUG_OFF + max_rows++; +#endif + } + DBUG_PRINT("error", ("dropped %lu rows after an error", max_rows)); + thread_safe_increment(delayed_insert_errors, &LOCK_delayed_status); + pthread_mutex_lock(&mutex); + DBUG_RETURN(1); +} +#endif /* EMBEDDED_LIBRARY */ + +/*************************************************************************** + Store records in INSERT ... SELECT * +***************************************************************************/ + + +/* + make insert specific preparation and checks after opening tables + + SYNOPSIS + mysql_insert_select_prepare() + thd thread handler + + RETURN + FALSE OK + TRUE Error +*/ + +bool mysql_insert_select_prepare(THD *thd) +{ + LEX *lex= thd->lex; + SELECT_LEX *select_lex= &lex->select_lex; + TABLE_LIST *first_select_leaf_table; + DBUG_ENTER("mysql_insert_select_prepare"); + + /* + Statement-based replication of INSERT ... SELECT ... LIMIT is not safe + as order of rows is not defined, so in mixed mode we go to row-based. + + Note that we may consider a statement as safe if ORDER BY primary_key + is present or we SELECT a constant. However it may confuse users to + see very similiar statements replicated differently. + */ + if (lex->current_select->select_limit) + { + lex->set_stmt_unsafe(); + thd->set_current_stmt_binlog_row_based_if_mixed(); + } + /* + SELECT_LEX do not belong to INSERT statement, so we can't add WHERE + clause if table is VIEW + */ + + if (mysql_prepare_insert(thd, lex->query_tables, + lex->query_tables->table, lex->field_list, 0, + lex->update_list, lex->value_list, + lex->duplicates, + &select_lex->where, TRUE, FALSE, FALSE)) + DBUG_RETURN(TRUE); + + /* + exclude first table from leaf tables list, because it belong to + INSERT + */ + DBUG_ASSERT(select_lex->leaf_tables != 0); + lex->leaf_tables_insert= select_lex->leaf_tables; + /* skip all leaf tables belonged to view where we are insert */ + for (first_select_leaf_table= select_lex->leaf_tables->next_leaf; + first_select_leaf_table && + first_select_leaf_table->belong_to_view && + first_select_leaf_table->belong_to_view == + lex->leaf_tables_insert->belong_to_view; + first_select_leaf_table= first_select_leaf_table->next_leaf) + {} + select_lex->leaf_tables= first_select_leaf_table; + DBUG_RETURN(FALSE); +} + + +select_insert::select_insert(TABLE_LIST *table_list_par, TABLE *table_par, + List *fields_par, + List *update_fields, + List *update_values, + enum_duplicates duplic, + bool ignore_check_option_errors) + :table_list(table_list_par), table(table_par), fields(fields_par), + autoinc_value_of_last_inserted_row(0), + insert_into_view(table_list_par && table_list_par->view != 0) +{ + bzero((char*) &info,sizeof(info)); + info.handle_duplicates= duplic; + info.ignore= ignore_check_option_errors; + info.update_fields= update_fields; + info.update_values= update_values; + if (table_list_par) + info.view= (table_list_par->view ? table_list_par : 0); +} + + +int +select_insert::prepare(List &values, SELECT_LEX_UNIT *u) +{ + LEX *lex= thd->lex; + int res; + table_map map= 0; + SELECT_LEX *lex_current_select_save= lex->current_select; + DBUG_ENTER("select_insert::prepare"); + + unit= u; + + /* + Since table in which we are going to insert is added to the first + select, LEX::current_select should point to the first select while + we are fixing fields from insert list. + */ + lex->current_select= &lex->select_lex; + res= check_insert_fields(thd, table_list, *fields, values, + !insert_into_view, &map) || + setup_fields(thd, 0, values, MARK_COLUMNS_READ, 0, 0); + + if (!res && fields->elements) + { + bool saved_abort_on_warning= thd->abort_on_warning; + thd->abort_on_warning= !info.ignore && (thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES)); + res= check_that_all_fields_are_given_values(thd, table_list->table, + table_list); + thd->abort_on_warning= saved_abort_on_warning; + } + + if (info.handle_duplicates == DUP_UPDATE && !res) + { + Name_resolution_context *context= &lex->select_lex.context; + Name_resolution_context_state ctx_state; + + /* Save the state of the current name resolution context. */ + ctx_state.save_state(context, table_list); + + /* Perform name resolution only in the first table - 'table_list'. */ + table_list->next_local= 0; + context->resolve_in_table_list_only(table_list); + + lex->select_lex.no_wrap_view_item= TRUE; + res= res || check_update_fields(thd, context->table_list, + *info.update_fields, &map); + lex->select_lex.no_wrap_view_item= FALSE; + /* + When we are not using GROUP BY and there are no ungrouped aggregate functions + we can refer to other tables in the ON DUPLICATE KEY part. + We use next_name_resolution_table descructively, so check it first (views?) + */ + DBUG_ASSERT (!table_list->next_name_resolution_table); + if (lex->select_lex.group_list.elements == 0 && + !lex->select_lex.with_sum_func) + /* + We must make a single context out of the two separate name resolution contexts : + the INSERT table and the tables in the SELECT part of INSERT ... SELECT. + To do that we must concatenate the two lists + */ + table_list->next_name_resolution_table= + ctx_state.get_first_name_resolution_table(); + + res= res || setup_fields(thd, 0, *info.update_values, + MARK_COLUMNS_READ, 0, 0); + if (!res) + { + /* + Traverse the update values list and substitute fields from the + select for references (Item_ref objects) to them. This is done in + order to get correct values from those fields when the select + employs a temporary table. + */ + List_iterator li(*info.update_values); + Item *item; + + while ((item= li++)) + { + item->transform(&Item::update_value_transformer, + (uchar*)lex->current_select); + } + } + + /* Restore the current context. */ + ctx_state.restore_state(context, table_list); + } + + lex->current_select= lex_current_select_save; + if (res) + DBUG_RETURN(1); + /* + if it is INSERT into join view then check_insert_fields already found + real table for insert + */ + table= table_list->table; + + /* + Is table which we are changing used somewhere in other parts of + query + */ + if (unique_table(thd, table_list, table_list->next_global, 0)) + { + /* Using same table for INSERT and SELECT */ + lex->current_select->options|= OPTION_BUFFER_RESULT; + lex->current_select->join->select_options|= OPTION_BUFFER_RESULT; + } + else if (!(lex->current_select->options & OPTION_BUFFER_RESULT) && + !thd->prelocked_mode) + { + /* + We must not yet prepare the result table if it is the same as one of the + source tables (INSERT SELECT). The preparation may disable + indexes on the result table, which may be used during the select, if it + is the same table (Bug #6034). Do the preparation after the select phase + in select_insert::prepare2(). + We won't start bulk inserts at all if this statement uses functions or + should invoke triggers since they may access to the same table too. + */ + table->file->ha_start_bulk_insert((ha_rows) 0); + } + restore_record(table,s->default_values); // Get empty record + table->next_number_field=table->found_next_number_field; + +#ifdef HAVE_REPLICATION + if (thd->slave_thread && + (info.handle_duplicates == DUP_UPDATE) && + (table->next_number_field != NULL) && + rpl_master_has_bug(&active_mi->rli, 24432, TRUE, NULL, NULL)) + DBUG_RETURN(1); +#endif + + thd->cuted_fields=0; + if (info.ignore || info.handle_duplicates != DUP_ERROR) + table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + if (info.handle_duplicates == DUP_REPLACE && + (!table->triggers || !table->triggers->has_delete_triggers())) + table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE); + if (info.handle_duplicates == DUP_UPDATE) + table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE); + thd->abort_on_warning= (!info.ignore && + (thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES))); + res= (table_list->prepare_where(thd, 0, TRUE) || + table_list->prepare_check_option(thd)); + + if (!res) + prepare_triggers_for_insert_stmt(table); + + DBUG_RETURN(res); +} + + +/* + Finish the preparation of the result table. + + SYNOPSIS + select_insert::prepare2() + void + + DESCRIPTION + If the result table is the same as one of the source tables (INSERT SELECT), + the result table is not finally prepared at the join prepair phase. + Do the final preparation now. + + RETURN + 0 OK +*/ + +int select_insert::prepare2(void) +{ + DBUG_ENTER("select_insert::prepare2"); + if (thd->lex->current_select->options & OPTION_BUFFER_RESULT && + !thd->prelocked_mode) + table->file->ha_start_bulk_insert((ha_rows) 0); + DBUG_RETURN(0); +} + + +void select_insert::cleanup() +{ + /* select_insert/select_create are never re-used in prepared statement */ + DBUG_ASSERT(0); +} + +select_insert::~select_insert() +{ + DBUG_ENTER("~select_insert"); + if (table) + { + table->next_number_field=0; + table->auto_increment_field_not_null= FALSE; + table->file->ha_reset(); + } + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + thd->abort_on_warning= 0; + DBUG_VOID_RETURN; +} + + +bool select_insert::send_data(List &values) +{ + DBUG_ENTER("select_insert::send_data"); + bool error=0; + + if (unit->offset_limit_cnt) + { // using limit offset,count + unit->offset_limit_cnt--; + DBUG_RETURN(0); + } + + thd->count_cuted_fields= CHECK_FIELD_WARN; // Calculate cuted fields + store_values(values); + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + if (thd->is_error()) + { + table->auto_increment_field_not_null= FALSE; + DBUG_RETURN(1); + } + if (table_list) // Not CREATE ... SELECT + { + switch (table_list->view_check_option(thd, info.ignore)) { + case VIEW_CHECK_SKIP: + DBUG_RETURN(0); + case VIEW_CHECK_ERROR: + DBUG_RETURN(1); + } + } + + // Release latches in case bulk insert takes a long time + ha_release_temporary_latches(thd); + + error= write_record(thd, table, &info); + table->auto_increment_field_not_null= FALSE; + + if (!error) + { + if (table->triggers || info.handle_duplicates == DUP_UPDATE) + { + /* + Restore fields of the record since it is possible that they were + changed by ON DUPLICATE KEY UPDATE clause. + + If triggers exist then whey can modify some fields which were not + originally touched by INSERT ... SELECT, so we have to restore + their original values for the next row. + */ + restore_record(table, s->default_values); + } + if (table->next_number_field) + { + /* + If no value has been autogenerated so far, we need to remember the + value we just saw, we may need to send it to client in the end. + */ + if (thd->first_successful_insert_id_in_cur_stmt == 0) // optimization + autoinc_value_of_last_inserted_row= + table->next_number_field->val_int(); + /* + Clear auto-increment field for the next record, if triggers are used + we will clear it twice, but this should be cheap. + */ + table->next_number_field->reset(); + } + } + DBUG_RETURN(error); +} + + +void select_insert::store_values(List &values) +{ + if (fields->elements) + fill_record_n_invoke_before_triggers(thd, *fields, values, 1, + table->triggers, TRG_EVENT_INSERT); + else + fill_record_n_invoke_before_triggers(thd, table->field, values, 1, + table->triggers, TRG_EVENT_INSERT); +} + +void select_insert::send_error(uint errcode,const char *err) +{ + DBUG_ENTER("select_insert::send_error"); + + my_message(errcode, err, MYF(0)); + + DBUG_VOID_RETURN; +} + + +bool select_insert::send_eof() +{ + int error; + bool const trans_table= table->file->has_transactions(); + ulonglong id; + bool changed; + THD::killed_state killed_status= thd->killed; + DBUG_ENTER("select_insert::send_eof"); + DBUG_PRINT("enter", ("trans_table=%d, table_type='%s'", + trans_table, table->file->table_type())); + + error= (!thd->prelocked_mode) ? table->file->ha_end_bulk_insert():0; + table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE); + + changed= (info.copied || info.deleted || info.updated); + if (changed) + { + /* + We must invalidate the table in the query cache before binlog writing + and ha_autocommit_or_rollback. + */ + query_cache_invalidate3(thd, table, 1); + if (thd->transaction.stmt.modified_non_trans_table) + thd->transaction.all.modified_non_trans_table= TRUE; + } + DBUG_ASSERT(trans_table || !changed || + thd->transaction.stmt.modified_non_trans_table); + + /* + Write to binlog before commiting transaction. No statement will + be written by the binlog_query() below in RBR mode. All the + events are in the transaction cache and will be written when + ha_autocommit_or_rollback() is issued below. + */ + if (mysql_bin_log.is_open()) + { + int errcode= 0; + if (!error) + thd->clear_error(); + else + errcode= query_error_code(thd, killed_status == THD::NOT_KILLED); + thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + trans_table, FALSE, errcode); + } + table->file->ha_release_auto_increment(); + + if (error) + { + table->file->print_error(error,MYF(0)); + DBUG_RETURN(1); + } + char buff[160]; + if (info.ignore) + sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records, + (ulong) (info.records - info.copied), (ulong) thd->cuted_fields); + else + sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records, + (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields); + thd->row_count_func= info.copied + info.deleted + + ((thd->client_capabilities & CLIENT_FOUND_ROWS) ? + info.touched : info.updated); + + id= (thd->first_successful_insert_id_in_cur_stmt > 0) ? + thd->first_successful_insert_id_in_cur_stmt : + (thd->arg_of_last_insert_id_function ? + thd->first_successful_insert_id_in_prev_stmt : + (info.copied ? autoinc_value_of_last_inserted_row : 0)); + ::my_ok(thd, (ulong) thd->row_count_func, id, buff); + DBUG_RETURN(0); +} + +void select_insert::abort() { + + DBUG_ENTER("select_insert::abort"); + /* + If the creation of the table failed (due to a syntax error, for + example), no table will have been opened and therefore 'table' + will be NULL. In that case, we still need to execute the rollback + and the end of the function. + */ + if (table) + { + bool changed, transactional_table; + /* + If we are not in prelocked mode, we end the bulk insert started + before. + */ + if (!thd->prelocked_mode) + table->file->ha_end_bulk_insert(); + + /* + If at least one row has been inserted/modified and will stay in + the table (the table doesn't have transactions) we must write to + the binlog (and the error code will make the slave stop). + + For many errors (example: we got a duplicate key error while + inserting into a MyISAM table), no row will be added to the table, + so passing the error to the slave will not help since there will + be an error code mismatch (the inserts will succeed on the slave + with no error). + + If table creation failed, the number of rows modified will also be + zero, so no check for that is made. + */ + changed= (info.copied || info.deleted || info.updated); + transactional_table= table->file->has_transactions(); + if (thd->transaction.stmt.modified_non_trans_table) + { + if (mysql_bin_log.is_open()) + { + int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + thd->binlog_query(THD::ROW_QUERY_TYPE, thd->query, thd->query_length, + transactional_table, FALSE, errcode); + } + if (!thd->current_stmt_binlog_row_based && !can_rollback_data()) + thd->transaction.all.modified_non_trans_table= TRUE; + if (changed) + query_cache_invalidate3(thd, table, 1); + } + DBUG_ASSERT(transactional_table || !changed || + thd->transaction.stmt.modified_non_trans_table); + table->file->ha_release_auto_increment(); + } + + DBUG_VOID_RETURN; +} + + +/*************************************************************************** + CREATE TABLE (SELECT) ... +***************************************************************************/ + +/* + Create table from lists of fields and items (or just return TABLE + object for pre-opened existing table). + + SYNOPSIS + create_table_from_items() + thd in Thread object + create_info in Create information (like MAX_ROWS, ENGINE or + temporary table flag) + create_table in Pointer to TABLE_LIST object providing database + and name for table to be created or to be open + alter_info in/out Initial list of columns and indexes for the table + to be created + items in List of items which should be used to produce rest + of fields for the table (corresponding fields will + be added to the end of alter_info->create_list) + lock out Pointer to the MYSQL_LOCK object for table created + (or open temporary table) will be returned in this + parameter. Since this table is not included in + THD::lock caller is responsible for explicitly + unlocking this table. + hooks + + NOTES + This function behaves differently for base and temporary tables: + - For base table we assume that either table exists and was pre-opened + and locked at open_and_lock_tables() stage (and in this case we just + emit error or warning and return pre-opened TABLE object) or special + placeholder was put in table cache that guarantees that this table + won't be created or opened until the placeholder will be removed + (so there is an exclusive lock on this table). + - We don't pre-open existing temporary table, instead we either open + or create and then open table in this function. + + Since this function contains some logic specific to CREATE TABLE ... + SELECT it should be changed before it can be used in other contexts. + + RETURN VALUES + non-zero Pointer to TABLE object for table created or opened + 0 Error +*/ + +static TABLE *create_table_from_items(THD *thd, HA_CREATE_INFO *create_info, + TABLE_LIST *create_table, + Alter_info *alter_info, + List *items, + MYSQL_LOCK **lock, + TABLEOP_HOOKS *hooks) +{ + TABLE tmp_table; // Used during 'Create_field()' + TABLE_SHARE share; + TABLE *table= 0; + uint select_field_count= items->elements; + /* Add selected items to field list */ + List_iterator_fast it(*items); + Item *item; + Field *tmp_field; + bool not_used; + DBUG_ENTER("create_table_from_items"); + + tmp_table.alias= 0; + tmp_table.timestamp_field= 0; + tmp_table.s= &share; + init_tmp_table_share(thd, &share, "", 0, "", ""); + + tmp_table.s->db_create_options=0; + tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr; + tmp_table.s->db_low_byte_first= + test(create_info->db_type == myisam_hton || + create_info->db_type == heap_hton); + tmp_table.null_row=tmp_table.maybe_null=0; + + while ((item=it++)) + { + Create_field *cr_field; + Field *field, *def_field; + if (item->type() == Item::FUNC_ITEM) + if (item->result_type() != STRING_RESULT) + field= item->tmp_table_field(&tmp_table); + else + field= item->tmp_table_field_from_field_type(&tmp_table, 0, thd); //@InfiniDB @bug3783. pass thd in. + else + field= create_tmp_field(thd, &tmp_table, item, item->type(), + (Item ***) 0, &tmp_field, &def_field, 0, 0, 0, 0, + 0); + if (!field || + !(cr_field=new Create_field(field,(item->type() == Item::FIELD_ITEM ? + ((Item_field *)item)->field : + (Field*) 0)))) + DBUG_RETURN(0); + if (item->maybe_null) + cr_field->flags &= ~NOT_NULL_FLAG; + alter_info->create_list.push_back(cr_field); + } + + DBUG_EXECUTE_IF("sleep_create_select_before_create", my_sleep(6000000);); + + /* + Create and lock table. + + Note that we either creating (or opening existing) temporary table or + creating base table on which name we have exclusive lock. So code below + should not cause deadlocks or races. + + We don't log the statement, it will be logged later. + + If this is a HEAP table, the automatic DELETE FROM which is written to the + binlog when a HEAP table is opened for the first time since startup, must + not be written: 1) it would be wrong (imagine we're in CREATE SELECT: we + don't want to delete from it) 2) it would be written before the CREATE + TABLE, which is a wrong order. So we keep binary logging disabled when we + open_table(). + */ + { + tmp_disable_binlog(thd); + if (!mysql_create_table_no_lock(thd, create_table->db, + create_table->table_name, + create_info, alter_info, 0, + select_field_count)) + { + if (create_info->table_existed && + !(create_info->options & HA_LEX_CREATE_TMP_TABLE)) + { + /* + This means that someone created table underneath server + or it was created via different mysqld front-end to the + cluster. We don't have much options but throw an error. + */ + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name); + DBUG_RETURN(0); + } + + DBUG_EXECUTE_IF("sleep_create_select_before_open", my_sleep(6000000);); + + if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) + { + VOID(pthread_mutex_lock(&LOCK_open)); + if (reopen_name_locked_table(thd, create_table, FALSE)) + { + quick_rm_table(create_info->db_type, create_table->db, + table_case_name(create_info, create_table->table_name), + 0); + } + else + table= create_table->table; + VOID(pthread_mutex_unlock(&LOCK_open)); + } + else + { + if (!(table= open_table(thd, create_table, thd->mem_root, (bool*) 0, + MYSQL_OPEN_TEMPORARY_ONLY)) && + !create_info->table_existed) + { + /* + This shouldn't happen as creation of temporary table should make + it preparable for open. But let us do close_temporary_table() here + just in case. + */ + drop_temporary_table(thd, create_table); + } + } + } + reenable_binlog(thd); + if (!table) // open failed + DBUG_RETURN(0); + } + + DBUG_EXECUTE_IF("sleep_create_select_before_lock", my_sleep(6000000);); + + table->reginfo.lock_type=TL_WRITE; + hooks->prelock(&table, 1); // Call prelock hooks + if (! ((*lock)= mysql_lock_tables(thd, &table, 1, + MYSQL_LOCK_IGNORE_FLUSH, ¬_used)) || + hooks->postlock(&table, 1)) + { + if (*lock) + { + mysql_unlock_tables(thd, *lock); + *lock= 0; + } + + if (!create_info->table_existed) + drop_open_table(thd, table, create_table->db, create_table->table_name); + DBUG_RETURN(0); + } + DBUG_RETURN(table); +} + + +int +select_create::prepare(List &values, SELECT_LEX_UNIT *u) +{ + MYSQL_LOCK *extra_lock= NULL; + DBUG_ENTER("select_create::prepare"); + + TABLEOP_HOOKS *hook_ptr= NULL; + /* + For row-based replication, the CREATE-SELECT statement is written + in two pieces: the first one contain the CREATE TABLE statement + necessary to create the table and the second part contain the rows + that should go into the table. + + For non-temporary tables, the start of the CREATE-SELECT + implicitly commits the previous transaction, and all events + forming the statement will be stored the transaction cache. At end + of the statement, the entire statement is committed as a + transaction, and all events are written to the binary log. + + On the master, the table is locked for the duration of the + statement, but since the CREATE part is replicated as a simple + statement, there is no way to lock the table for accesses on the + slave. Hence, we have to hold on to the CREATE part of the + statement until the statement has finished. + */ + class MY_HOOKS : public TABLEOP_HOOKS { + public: + MY_HOOKS(select_create *x, TABLE_LIST *create_table, + TABLE_LIST *select_tables) + : ptr(x), all_tables(*create_table) + { + all_tables.next_global= select_tables; + } + + private: + virtual int do_postlock(TABLE **tables, uint count) + { + THD *thd= const_cast(ptr->get_thd()); + if (int error= decide_logging_format(thd, &all_tables)) + return error; + + TABLE const *const table = *tables; + if (thd->current_stmt_binlog_row_based && + !table->s->tmp_table && + !ptr->get_create_info()->table_existed) + { + ptr->binlog_show_create_table(tables, count); + } + return 0; + } + + select_create *ptr; + TABLE_LIST all_tables; + }; + + MY_HOOKS hooks(this, create_table, select_tables); + hook_ptr= &hooks; + + unit= u; + + /* + Start a statement transaction before the create if we are using + row-based replication for the statement. If we are creating a + temporary table, we need to start a statement transaction. + */ + if ((thd->lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) == 0 && + thd->current_stmt_binlog_row_based && + mysql_bin_log.is_open()) + { + thd->binlog_start_trans_and_stmt(); + } + + DBUG_EXECUTE_IF("sleep_create_select_before_check_if_exists", my_sleep(6000000);); + + if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE) && + create_table->table->db_stat) + { + /* Table already exists and was open at open_and_lock_tables() stage. */ + if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS) + { + /* Mark that table existed */ + create_info->table_existed= 1; + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR), + create_table->table_name); + if (thd->current_stmt_binlog_row_based) + binlog_show_create_table(&(create_table->table), 1); + table= create_table->table; + } + else + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name); + DBUG_RETURN(-1); + } + } + else + if (!(table= create_table_from_items(thd, create_info, create_table, + alter_info, &values, + &extra_lock, hook_ptr))) + /* abort() deletes table */ + DBUG_RETURN(-1); + + if (extra_lock) + { + DBUG_ASSERT(m_plock == NULL); + + if (create_info->options & HA_LEX_CREATE_TMP_TABLE) + m_plock= &m_lock; + else + m_plock= &thd->extra_lock; + + *m_plock= extra_lock; + } + + if (table->s->fields < values.elements) + { + my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1); + DBUG_RETURN(-1); + } + + /* First field to copy */ + field= table->field+table->s->fields - values.elements; + + /* Mark all fields that are given values */ + for (Field **f= field ; *f ; f++) + bitmap_set_bit(table->write_set, (*f)->field_index); + + /* Don't set timestamp if used */ + table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET; + table->next_number_field=table->found_next_number_field; + + restore_record(table,s->default_values); // Get empty record + thd->cuted_fields=0; + if (info.ignore || info.handle_duplicates != DUP_ERROR) + table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + if (info.handle_duplicates == DUP_REPLACE && + (!table->triggers || !table->triggers->has_delete_triggers())) + table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE); + if (info.handle_duplicates == DUP_UPDATE) + table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE); + if (!thd->prelocked_mode) + table->file->ha_start_bulk_insert((ha_rows) 0); + thd->abort_on_warning= (!info.ignore && + (thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES))); + if (check_that_all_fields_are_given_values(thd, table, table_list)) + DBUG_RETURN(1); + table->mark_columns_needed_for_insert(); + table->file->extra(HA_EXTRA_WRITE_CACHE); + DBUG_RETURN(0); +} + +void +select_create::binlog_show_create_table(TABLE **tables, uint count) +{ + /* + Note 1: In RBR mode, we generate a CREATE TABLE statement for the + created table by calling store_create_info() (behaves as SHOW + CREATE TABLE). In the event of an error, nothing should be + written to the binary log, even if the table is non-transactional; + therefore we pretend that the generated CREATE TABLE statement is + for a transactional table. The event will then be put in the + transaction cache, and any subsequent events (e.g., table-map + events and binrow events) will also be put there. We can then use + ha_autocommit_or_rollback() to either throw away the entire + kaboodle of events, or write them to the binary log. + + We write the CREATE TABLE statement here and not in prepare() + since there potentially are sub-selects or accesses to information + schema that will do a close_thread_tables(), destroying the + statement transaction cache. + */ + DBUG_ASSERT(thd->current_stmt_binlog_row_based); + DBUG_ASSERT(tables && *tables && count > 0); + + char buf[2048]; + String query(buf, sizeof(buf), system_charset_info); + int result; + TABLE_LIST tmp_table_list; + + memset(&tmp_table_list, 0, sizeof(tmp_table_list)); + tmp_table_list.table = *tables; + query.length(0); // Have to zero it since constructor doesn't + + result= store_create_info(thd, &tmp_table_list, &query, create_info, + /* show_database */ TRUE); + DBUG_ASSERT(result == 0); /* store_create_info() always return 0 */ + + if (mysql_bin_log.is_open()) + { + int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + thd->binlog_query(THD::STMT_QUERY_TYPE, + query.ptr(), query.length(), + /* is_trans */ TRUE, + /* suppress_use */ FALSE, + errcode); + } +} + +void select_create::store_values(List &values) +{ + fill_record_n_invoke_before_triggers(thd, field, values, 1, + table->triggers, TRG_EVENT_INSERT); +} + + +void select_create::send_error(uint errcode,const char *err) +{ + DBUG_ENTER("select_create::send_error"); + + DBUG_PRINT("info", + ("Current statement %s row-based", + thd->current_stmt_binlog_row_based ? "is" : "is NOT")); + DBUG_PRINT("info", + ("Current table (at 0x%lu) %s a temporary (or non-existant) table", + (ulong) table, + table && !table->s->tmp_table ? "is NOT" : "is")); + DBUG_PRINT("info", + ("Table %s prior to executing this statement", + get_create_info()->table_existed ? "existed" : "did not exist")); + + /* + This will execute any rollbacks that are necessary before writing + the transcation cache. + + We disable the binary log since nothing should be written to the + binary log. This disabling is important, since we potentially do + a "roll back" of non-transactional tables by removing the table, + and the actual rollback might generate events that should not be + written to the binary log. + + */ + tmp_disable_binlog(thd); + select_insert::send_error(errcode, err); + reenable_binlog(thd); + + DBUG_VOID_RETURN; +} + + +bool select_create::send_eof() +{ + bool tmp=select_insert::send_eof(); + if (tmp) + abort(); + else + { + /* + Do an implicit commit at end of statement for non-temporary + tables. This can fail, but we should unlock the table + nevertheless. + */ + if (!table->s->tmp_table) + { + ha_autocommit_or_rollback(thd, 0); + end_active_trans(thd); + } + + table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE); + if (m_plock) + { + mysql_unlock_tables(thd, *m_plock); + *m_plock= NULL; + m_plock= NULL; + } + } + return tmp; +} + + +void select_create::abort() +{ + DBUG_ENTER("select_create::abort"); + + /* + In select_insert::abort() we roll back the statement, including + truncating the transaction cache of the binary log. To do this, we + pretend that the statement is transactional, even though it might + be the case that it was not. + + We roll back the statement prior to deleting the table and prior + to releasing the lock on the table, since there might be potential + for failure if the rollback is executed after the drop or after + unlocking the table. + + We also roll back the statement regardless of whether the creation + of the table succeeded or not, since we need to reset the binary + log state. + */ + tmp_disable_binlog(thd); + select_insert::abort(); + thd->transaction.stmt.modified_non_trans_table= FALSE; + reenable_binlog(thd); + thd->binlog_flush_pending_rows_event(TRUE); + + if (m_plock) + { + mysql_unlock_tables(thd, *m_plock); + *m_plock= NULL; + m_plock= NULL; + } + + if (table) + { + table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE); + if (!create_info->table_existed) + drop_open_table(thd, table, create_table->db, create_table->table_name); + table=0; // Safety + } + DBUG_VOID_RETURN; +} + + +/***************************************************************************** + Instansiate templates +*****************************************************************************/ + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +template class List_iterator_fast; +#ifndef EMBEDDED_LIBRARY +template class I_List; +template class I_List_iterator; +template class I_List; +#endif /* EMBEDDED_LIBRARY */ +#endif /* HAVE_EXPLICIT_TEMPLATE_INSTANTIATION */ diff --git a/dbcon/mysql/sql_parse.cc b/dbcon/mysql/sql_parse.cc new file mode 100644 index 00000000..cc4a4a62 --- /dev/null +++ b/dbcon/mysql/sql_parse.cc @@ -0,0 +1,8570 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +#define MYSQL_LEX 1 + +#include +#include +//#include + +#include "mysql_priv.h" +#include "sql_repl.h" +#include "rpl_filter.h" +#include "repl_failsafe.h" +#include +#include +#include + +#include "sp_head.h" +#include "sp.h" +#include "sp_cache.h" +#include "events.h" +#include "sql_trigger.h" +#include "sp_pcontext.h" + + +/** + @defgroup Runtime_Environment Runtime Environment + @{ +*/ + +/** + * InfiniDB Functions + */ +// InfiniDB vtable processing +int idb_vtable_process(THD* thd, Statement* stmt = NULL); + +// for vtable parsing use. String in quotes is converted to upper case, all other chars are +// converted to lower case. +static void idb_to_lower(char* str); + +// replace \t, \n to space. +static std::string idb_cleanQuery(char* str); + + +/* Used in error handling only */ +#define SP_TYPE_STRING(LP) \ + ((LP)->sphead->m_type == TYPE_ENUM_FUNCTION ? "FUNCTION" : "PROCEDURE") +#define SP_COM_STRING(LP) \ + ((LP)->sql_command == SQLCOM_CREATE_SPFUNCTION || \ + (LP)->sql_command == SQLCOM_ALTER_FUNCTION || \ + (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \ + (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \ + "FUNCTION" : "PROCEDURE") + +static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables); +static bool check_show_create_table_access(THD *thd, TABLE_LIST *table); + +const char *any_db="*any*"; // Special symbol for check_access + +const LEX_STRING command_name[]={ + { C_STRING_WITH_LEN("Sleep") }, + { C_STRING_WITH_LEN("Quit") }, + { C_STRING_WITH_LEN("Init DB") }, + { C_STRING_WITH_LEN("Query") }, + { C_STRING_WITH_LEN("Field List") }, + { C_STRING_WITH_LEN("Create DB") }, + { C_STRING_WITH_LEN("Drop DB") }, + { C_STRING_WITH_LEN("Refresh") }, + { C_STRING_WITH_LEN("Shutdown") }, + { C_STRING_WITH_LEN("Statistics") }, + { C_STRING_WITH_LEN("Processlist") }, + { C_STRING_WITH_LEN("Connect") }, + { C_STRING_WITH_LEN("Kill") }, + { C_STRING_WITH_LEN("Debug") }, + { C_STRING_WITH_LEN("Ping") }, + { C_STRING_WITH_LEN("Time") }, + { C_STRING_WITH_LEN("Delayed insert") }, + { C_STRING_WITH_LEN("Change user") }, + { C_STRING_WITH_LEN("Binlog Dump") }, + { C_STRING_WITH_LEN("Table Dump") }, + { C_STRING_WITH_LEN("Connect Out") }, + { C_STRING_WITH_LEN("Register Slave") }, + { C_STRING_WITH_LEN("Prepare") }, + { C_STRING_WITH_LEN("Execute") }, + { C_STRING_WITH_LEN("Long Data") }, + { C_STRING_WITH_LEN("Close stmt") }, + { C_STRING_WITH_LEN("Reset stmt") }, + { C_STRING_WITH_LEN("Set option") }, + { C_STRING_WITH_LEN("Fetch") }, + { C_STRING_WITH_LEN("Daemon") }, + { C_STRING_WITH_LEN("Error") } // Last command number +}; + +const char *xa_state_names[]={ + "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY" +}; + +/** + Mark a XA transaction as rollback-only if the RM unilaterally + rolled back the transaction branch. + + @note If a rollback was requested by the RM, this function sets + the appropriate rollback error code and transits the state + to XA_ROLLBACK_ONLY. + + @return TRUE if transaction was rolled back or if the transaction + state is XA_ROLLBACK_ONLY. FALSE otherwise. +*/ +static bool xa_trans_rolled_back(XID_STATE *xid_state) +{ + if (xid_state->rm_error) + { + switch (xid_state->rm_error) { + case ER_LOCK_WAIT_TIMEOUT: + my_error(ER_XA_RBTIMEOUT, MYF(0)); + break; + case ER_LOCK_DEADLOCK: + my_error(ER_XA_RBDEADLOCK, MYF(0)); + break; + default: + my_error(ER_XA_RBROLLBACK, MYF(0)); + } + xid_state->xa_state= XA_ROLLBACK_ONLY; + } + + return (xid_state->xa_state == XA_ROLLBACK_ONLY); +} + +/** + Rollback work done on behalf of at ransaction branch. +*/ +static bool xa_trans_rollback(THD *thd) +{ + bool status= test(ha_rollback(thd)); + + thd->options&= ~(ulong) OPTION_BEGIN; + thd->transaction.all.modified_non_trans_table= FALSE; + thd->server_status&= ~SERVER_STATUS_IN_TRANS; + xid_cache_delete(&thd->transaction.xid_state); + thd->transaction.xid_state.xa_state= XA_NOTR; + thd->transaction.xid_state.rm_error= 0; + + return status; +} + +// Calpont vtable error message +//const char* infinidb_err_msg = "\nThe query includes syntax that is not supported by InfiniDB. \ +// Use 'show warnings;' to get more infomation. \ +// Restructure the query with supported syntax."; + +static void unlock_locked_tables(THD *thd) +{ + if (thd->locked_tables) + { + thd->lock=thd->locked_tables; + thd->locked_tables=0; // Will be automatically closed + close_thread_tables(thd); // Free tables + } +} + + +bool end_active_trans(THD *thd) +{ + int error=0; + DBUG_ENTER("end_active_trans"); + /*Bug 5320 */ + if ((thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE) + || (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ALTER_VTABLE) + || (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DROP_VTABLE)) + DBUG_RETURN(error); + + if (unlikely(thd->in_sub_stmt)) + { + my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); + DBUG_RETURN(1); + } + if (thd->transaction.xid_state.xa_state != XA_NOTR) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + DBUG_RETURN(1); + } + if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN | + OPTION_TABLE_LOCK)) + { + DBUG_PRINT("info",("options: 0x%llx", thd->options)); + /* Safety if one did "drop table" on locked tables */ + if (!thd->locked_tables) + thd->options&= ~OPTION_TABLE_LOCK; + thd->server_status&= ~SERVER_STATUS_IN_TRANS; + if (ha_commit(thd)) + error=1; + } + thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG); + thd->transaction.all.modified_non_trans_table= FALSE; + DBUG_RETURN(error); +} + + +bool begin_trans(THD *thd) +{ + int error=0; + if (unlikely(thd->in_sub_stmt)) + { + my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); + return 1; + } + if (thd->locked_tables) + { + thd->lock=thd->locked_tables; + thd->locked_tables=0; // Will be automatically closed + close_thread_tables(thd); // Free tables + } + if (end_active_trans(thd)) + error= -1; + else + { + thd->options|= OPTION_BEGIN; + thd->server_status|= SERVER_STATUS_IN_TRANS; + } + return error; +} + +#ifdef HAVE_REPLICATION +/** + Returns true if all tables should be ignored. +*/ +inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables) +{ + return rpl_filter->is_on() && tables && !thd->spcont && + !rpl_filter->tables_ok(thd->db, tables); +} +#endif + + +static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables) +{ + for (TABLE_LIST *table= tables; table; table= table->next_global) + { + DBUG_ASSERT(table->db && table->table_name); + if (table->updating && + !find_temporary_table(thd, table->db, table->table_name)) + return 1; + } + return 0; +} + + +/** + Mark all commands that somehow changes a table. + + This is used to check number of updates / hour. + + sql_command is actually set to SQLCOM_END sometimes + so we need the +1 to include it in the array. + + See COMMAND_FLAG_xxx for different type of commands + 2 - query that returns meaningful ROW_COUNT() - + a number of modified rows +*/ + +uint sql_command_flags[SQLCOM_END+1]; + +void init_update_queries(void) +{ + bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags)); + + sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND; + sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND; + sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_BACKUP_TABLE]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_RESTORE_TABLE]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_CREATE_VIEW]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_DROP_VIEW]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_CREATE_EVENT]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_ALTER_EVENT]= CF_CHANGES_DATA; + sql_command_flags[SQLCOM_DROP_EVENT]= CF_CHANGES_DATA; + + sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_UPDATE_MULTI]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_DELETE_MULTI]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT | + CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SELECT]= CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SET_OPTION]= CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_DO]= CF_REEXECUTION_FRAGILE; + + sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_STATUS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_DATABASES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_TRIGGERS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_EVENTS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_PLUGINS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_FIELDS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_KEYS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_VARIABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_CHARSETS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_COLLATIONS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_NEW_MASTER]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_COLUMN_TYPES]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_AUTHORS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_PRIVILEGES]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_GRANTS]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CREATE_DB]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CREATE]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_MASTER_STAT]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_SHOW_PROC_CODE]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_FUNC_CODE]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_CREATE_EVENT]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_PROFILES]= CF_STATUS_COMMAND; + sql_command_flags[SQLCOM_SHOW_PROFILE]= CF_STATUS_COMMAND; + + sql_command_flags[SQLCOM_SHOW_TABLES]= (CF_STATUS_COMMAND | + CF_SHOW_TABLE_COMMAND | + CF_REEXECUTION_FRAGILE); + sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND | + CF_SHOW_TABLE_COMMAND | + CF_REEXECUTION_FRAGILE); + + /* + The following is used to preserver CF_ROW_COUNT during the + a CALL or EXECUTE statement, so the value generated by the + last called (or executed) statement is preserved. + See mysql_execute_command() for how CF_ROW_COUNT is used. + */ + sql_command_flags[SQLCOM_CALL]= CF_HAS_ROW_COUNT | CF_REEXECUTION_FRAGILE; + sql_command_flags[SQLCOM_EXECUTE]= CF_HAS_ROW_COUNT; + + /* + The following admin table operations are allowed + on log tables. + */ + sql_command_flags[SQLCOM_REPAIR]= CF_WRITE_LOGS_COMMAND; + sql_command_flags[SQLCOM_OPTIMIZE]= CF_WRITE_LOGS_COMMAND; + sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND; +} + + +bool is_update_query(enum enum_sql_command command) +{ + DBUG_ASSERT(command >= 0 && command <= SQLCOM_END); + return (sql_command_flags[command] & CF_CHANGES_DATA) != 0; +} + +/** + Check if a sql command is allowed to write to log tables. + @param command The SQL command + @return true if writing is allowed +*/ +bool is_log_table_write_query(enum enum_sql_command command) +{ + DBUG_ASSERT(command >= 0 && command <= SQLCOM_END); + return (sql_command_flags[command] & CF_WRITE_LOGS_COMMAND) != 0; +} + +void execute_init_command(THD *thd, sys_var_str *init_command_var, + rw_lock_t *var_mutex) +{ + Vio* save_vio; + ulong save_client_capabilities; + +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.start_new_query(); + thd->profiling.set_query_source(init_command_var->value, + init_command_var->value_length); +#endif + + thd_proc_info(thd, "Execution of init_command"); + /* + We need to lock init_command_var because + during execution of init_command_var query + values of init_command_var can't be changed + */ + rw_rdlock(var_mutex); + save_client_capabilities= thd->client_capabilities; + thd->client_capabilities|= CLIENT_MULTI_QUERIES; + /* + We don't need return result of execution to client side. + To forbid this we should set thd->net.vio to 0. + */ + save_vio= thd->net.vio; + thd->net.vio= 0; + dispatch_command(COM_QUERY, thd, + init_command_var->value, + init_command_var->value_length); + rw_unlock(var_mutex); + thd->client_capabilities= save_client_capabilities; + thd->net.vio= save_vio; + +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.finish_current_query(); +#endif +} + + +/** + Execute commands from bootstrap_file. + + Used when creating the initial grant tables. +*/ + +pthread_handler_t handle_bootstrap(void *arg) +{ + THD *thd=(THD*) arg; + FILE *file=bootstrap_file; + char *buff; + const char* found_semicolon= NULL; + + /* The following must be called before DBUG_ENTER */ + thd->thread_stack= (char*) &thd; + if (my_thread_init() || thd->store_globals()) + { +#ifndef EMBEDDED_LIBRARY + close_connection(thd, ER_OUT_OF_RESOURCES, 1); +#endif + thd->fatal_error(); + goto end; + } + DBUG_ENTER("handle_bootstrap"); + +#ifndef EMBEDDED_LIBRARY + pthread_detach_this_thread(); + thd->thread_stack= (char*) &thd; +#endif /* EMBEDDED_LIBRARY */ + + if (thd->variables.max_join_size == HA_POS_ERROR) + thd->options |= OPTION_BIG_SELECTS; + + thd_proc_info(thd, 0); + thd->version=refresh_version; + thd->security_ctx->priv_user= + thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME)); + thd->security_ctx->priv_host[0]=0; + /* + Make the "client" handle multiple results. This is necessary + to enable stored procedures with SELECTs and Dynamic SQL + in init-file. + */ + thd->client_capabilities|= CLIENT_MULTI_RESULTS; + + buff= (char*) thd->net.buff; + thd->init_for_queries(); + while (fgets(buff, thd->net.max_packet, file)) + { + char *query, *res; + /* strlen() can't be deleted because fgets() doesn't return length */ + ulong length= (ulong) strlen(buff); + while (buff[length-1] != '\n' && !feof(file)) + { + /* + We got only a part of the current string. Will try to increase + net buffer then read the rest of the current string. + */ + /* purecov: begin tested */ + if (net_realloc(&(thd->net), 2 * thd->net.max_packet)) + { + net_end_statement(thd); + bootstrap_error= 1; + break; + } + buff= (char*) thd->net.buff; + res= fgets(buff + length, thd->net.max_packet - length, file); + length+= (ulong) strlen(buff + length); + /* purecov: end */ + } + if (bootstrap_error) + break; /* purecov: inspected */ + + while (length && (my_isspace(thd->charset(), buff[length-1]) || + buff[length-1] == ';')) + length--; + buff[length]=0; + + /* Skip lines starting with delimiter */ + if (strncmp(buff, STRING_WITH_LEN("delimiter")) == 0) + continue; + + query= (char *) thd->memdup_w_gap(buff, length + 1, + thd->db_length + 1 + + QUERY_CACHE_FLAGS_SIZE); + thd->set_query(query, length); + DBUG_PRINT("query",("%-.4096s",thd->query)); +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.start_new_query(); + thd->profiling.set_query_source(thd->query, length); +#endif + + /* + We don't need to obtain LOCK_thread_count here because in bootstrap + mode we have only one thread. + */ + thd->query_id=next_query_id(); + thd->set_time(); + mysql_parse(thd, thd->query, length, & found_semicolon); + close_thread_tables(thd); // Free tables + + bootstrap_error= thd->is_error(); + net_end_statement(thd); + +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.finish_current_query(); +#endif + + if (bootstrap_error) + break; + + free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC)); +#ifdef USING_TRANSACTIONS + free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC)); +#endif + } + +end: + net_end(&thd->net); + thd->cleanup(); + delete thd; + +#ifndef EMBEDDED_LIBRARY + (void) pthread_mutex_lock(&LOCK_thread_count); + thread_count--; + in_bootstrap= FALSE; + (void) pthread_cond_broadcast(&COND_thread_count); + (void) pthread_mutex_unlock(&LOCK_thread_count); + my_thread_end(); + pthread_exit(0); +#endif + DBUG_RETURN(0); +} + + +/** + @brief Check access privs for a MERGE table and fix children lock types. + + @param[in] thd thread handle + @param[in] db database name + @param[in,out] table_list list of child tables (merge_list) + lock_type and optionally db set per table + + @return status + @retval 0 OK + @retval != 0 Error + + @detail + This function is used for write access to MERGE tables only + (CREATE TABLE, ALTER TABLE ... UNION=(...)). Set TL_WRITE for + every child. Set 'db' for every child if not present. +*/ +#ifndef NO_EMBEDDED_ACCESS_CHECKS +static bool check_merge_table_access(THD *thd, char *db, + TABLE_LIST *table_list) +{ + int error= 0; + + if (table_list) + { + /* Check that all tables use the current database */ + TABLE_LIST *tlist; + + for (tlist= table_list; tlist; tlist= tlist->next_local) + { + if (!tlist->db || !tlist->db[0]) + tlist->db= db; /* purecov: inspected */ + } + error= check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL, + table_list, UINT_MAX, FALSE); + } + return error; +} +#endif + +/* This works because items are allocated with sql_alloc() */ + +void free_items(Item *item) +{ + Item *next; + DBUG_ENTER("free_items"); + for (; item ; item=next) + { + next=item->next; + item->delete_self(); + } + DBUG_VOID_RETURN; +} + +/* This works because items are allocated with sql_alloc() */ + +void cleanup_items(Item *item) +{ + DBUG_ENTER("cleanup_items"); + for (; item ; item=item->next) + item->cleanup(); + DBUG_VOID_RETURN; +} + +/** + Handle COM_TABLE_DUMP command. + + @param thd thread handle + @param db database name or an empty string. If empty, + the current database of the connection is used + @param tbl_name name of the table to dump + + @note + This function is written to handle one specific command only. + + @retval + 0 success + @retval + 1 error, the error message is set in THD +*/ + +static +int mysql_table_dump(THD *thd, LEX_STRING *db, char *tbl_name) +{ + TABLE* table; + TABLE_LIST* table_list; + int error = 0; + DBUG_ENTER("mysql_table_dump"); + if (db->length == 0) + { + db->str= thd->db; /* purecov: inspected */ + db->length= thd->db_length; /* purecov: inspected */ + } + if (!(table_list = (TABLE_LIST*) thd->calloc(sizeof(TABLE_LIST)))) + DBUG_RETURN(1); // out of memory + table_list->db= db->str; + table_list->table_name= table_list->alias= tbl_name; + table_list->lock_type= TL_READ_NO_INSERT; + table_list->prev_global= &table_list; // can be removed after merge with 4.1 + + if (check_db_name(db)) + { + /* purecov: begin inspected */ + my_error(ER_WRONG_DB_NAME ,MYF(0), db->str ? db->str : "NULL"); + goto err; + /* purecov: end */ + } + if (lower_case_table_names) + my_casedn_str(files_charset_info, tbl_name); + + if (!(table=open_ltable(thd, table_list, TL_READ_NO_INSERT, 0))) + DBUG_RETURN(1); + + if (check_one_table_access(thd, SELECT_ACL, table_list)) + goto err; + thd->free_list = 0; + thd->set_query(tbl_name, (uint) strlen(tbl_name)); + if ((error = mysqld_dump_create_info(thd, table_list, -1))) + { + my_error(ER_GET_ERRNO, MYF(0), my_errno); + goto err; + } + net_flush(&thd->net); + if ((error= table->file->dump(thd,-1))) + my_error(ER_GET_ERRNO, MYF(0), error); + +err: + DBUG_RETURN(error); +} + +/** + Ends the current transaction and (maybe) begin the next. + + @param thd Current thread + @param completion Completion type + + @retval + 0 OK +*/ + +int end_trans(THD *thd, enum enum_mysql_completiontype completion) +{ + bool do_release= 0; + int res= 0; + DBUG_ENTER("end_trans"); + /*Bug 5320 */ + if ((thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE) + || (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ALTER_VTABLE) + || (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DROP_VTABLE)) + DBUG_RETURN(res); + + if (unlikely(thd->in_sub_stmt)) + { + my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); + DBUG_RETURN(1); + } + if (thd->transaction.xid_state.xa_state != XA_NOTR) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + DBUG_RETURN(1); + } + switch (completion) { + case COMMIT: + /* + We don't use end_active_trans() here to ensure that this works + even if there is a problem with the OPTION_AUTO_COMMIT flag + (Which of course should never happen...) + */ + thd->server_status&= ~SERVER_STATUS_IN_TRANS; + res= ha_commit(thd); + thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG); + thd->transaction.all.modified_non_trans_table= FALSE; + break; + case COMMIT_RELEASE: + do_release= 1; /* fall through */ + case COMMIT_AND_CHAIN: + res= end_active_trans(thd); + if (!res && completion == COMMIT_AND_CHAIN) + res= begin_trans(thd); + break; + case ROLLBACK_RELEASE: + do_release= 1; /* fall through */ + case ROLLBACK: + case ROLLBACK_AND_CHAIN: + { + thd->server_status&= ~SERVER_STATUS_IN_TRANS; + if (ha_rollback(thd)) + res= -1; + thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG); + thd->transaction.all.modified_non_trans_table= FALSE; + if (!res && (completion == ROLLBACK_AND_CHAIN)) + res= begin_trans(thd); + break; + } + default: + res= -1; + my_error(ER_UNKNOWN_COM_ERROR, MYF(0)); + DBUG_RETURN(-1); + } + + if (res < 0) + my_error(thd->killed_errno(), MYF(0)); + else if ((res == 0) && do_release) + thd->killed= THD::KILL_CONNECTION; + + DBUG_RETURN(res); +} + +#ifndef EMBEDDED_LIBRARY + +/** + Read one command from connection and execute it (query or simple command). + This function is called in loop from thread function. + + For profiling to work, it must never be called recursively. + + @retval + 0 success + @retval + 1 request of thread shutdown (see dispatch_command() description) +*/ + +bool do_command(THD *thd) +{ + bool return_value; + char *packet= 0; + ulong packet_length; + NET *net= &thd->net; + enum enum_server_command command; + DBUG_ENTER("do_command"); + + /* + indicator of uninitialized lex => normal flow of errors handling + (see my_message_sql) + */ + thd->lex->current_select= 0; + + /* + This thread will do a blocking read from the client which + will be interrupted when the next command is received from + the client, the connection is closed or "net_wait_timeout" + number of seconds has passed + */ + my_net_set_read_timeout(net, thd->variables.net_wait_timeout); + + /* + XXX: this code is here only to clear possible errors of init_connect. + Consider moving to init_connect() instead. + */ + thd->clear_error(); // Clear error message + thd->main_da.reset_diagnostics_area(); + + net_new_transaction(net); + + packet_length= my_net_read(net); +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.start_new_query(); +#endif + if (packet_length == packet_error) + { + DBUG_PRINT("info",("Got error %d reading command from socket %s", + net->error, + vio_description(net->vio))); + + /* Check if we can continue without closing the connection */ + + /* The error must be set. */ + DBUG_ASSERT(thd->is_error()); + net_end_statement(thd); + + if (net->error != 3) + { + return_value= TRUE; // We have to close it. + goto out; + } + + net->error= 0; + return_value= FALSE; + goto out; + } + + packet= (char*) net->read_pos; + /* + 'packet_length' contains length of data, as it was stored in packet + header. In case of malformed header, my_net_read returns zero. + If packet_length is not zero, my_net_read ensures that the returned + number of bytes was actually read from network. + There is also an extra safety measure in my_net_read: + it sets packet[packet_length]= 0, but only for non-zero packets. + */ + if (packet_length == 0) /* safety */ + { + /* Initialize with COM_SLEEP packet */ + packet[0]= (uchar) COM_SLEEP; + packet_length= 1; + } + /* Do not rely on my_net_read, extra safety against programming errors. */ + packet[packet_length]= '\0'; /* safety */ + + command= (enum enum_server_command) (uchar) packet[0]; + + if (command >= COM_END) + command= COM_END; // Wrong command + + DBUG_PRINT("info",("Command on %s = %d (%s)", + vio_description(net->vio), command, + command_name[command].str)); + + /* Restore read timeout value */ + my_net_set_read_timeout(net, thd->variables.net_read_timeout); + + DBUG_ASSERT(packet_length); + return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1)); + +out: +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.finish_current_query(); +#endif + DBUG_RETURN(return_value); +} +#endif /* EMBEDDED_LIBRARY */ + +/** + @brief Determine if an attempt to update a non-temporary table while the + read-only option was enabled has been made. + + This is a helper function to mysql_execute_command. + + @note SQLCOM_MULTI_UPDATE is an exception and delt with elsewhere. + + @see mysql_execute_command + @returns Status code + @retval TRUE The statement should be denied. + @retval FALSE The statement isn't updating any relevant tables. +*/ + +static my_bool deny_updates_if_read_only_option(THD *thd, + TABLE_LIST *all_tables) +{ + DBUG_ENTER("deny_updates_if_read_only_option"); + + if (!opt_readonly) + DBUG_RETURN(FALSE); + + LEX *lex= thd->lex; + + const my_bool user_is_super= + ((ulong)(thd->security_ctx->master_access & SUPER_ACL) == + (ulong)SUPER_ACL); + + if (user_is_super) + DBUG_RETURN(FALSE); + + if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA)) + DBUG_RETURN(FALSE); + + /* Multi update is an exception and is dealt with later. */ + if (lex->sql_command == SQLCOM_UPDATE_MULTI) + DBUG_RETURN(FALSE); + + const my_bool create_temp_tables= + (lex->sql_command == SQLCOM_CREATE_TABLE) && + (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE); + + const my_bool drop_temp_tables= + (lex->sql_command == SQLCOM_DROP_TABLE) && + lex->drop_temporary; + + const my_bool update_real_tables= + some_non_temp_table_to_be_updated(thd, all_tables) && + !(create_temp_tables || drop_temp_tables); + + + const my_bool create_or_drop_databases= + (lex->sql_command == SQLCOM_CREATE_DB) || + (lex->sql_command == SQLCOM_DROP_DB); + + if (update_real_tables || create_or_drop_databases) + { + /* + An attempt was made to modify one or more non-temporary tables. + */ + DBUG_RETURN(TRUE); + } + + + /* Assuming that only temporary tables are modified. */ + DBUG_RETURN(FALSE); +} + +/** + Perform one connection-level (COM_XXXX) command. + + @param command type of command to perform + @param thd connection handle + @param packet data for the command, packet is always null-terminated + @param packet_length length of packet + 1 (to show that data is + null-terminated) except for COM_SLEEP, where it + can be zero. + + @todo + set thd->lex->sql_command to SQLCOM_END here. + @todo + The following has to be changed to an 8 byte integer + + @retval + 0 ok + @retval + 1 request of thread shutdown, i. e. if command is + COM_QUIT/COM_SHUTDOWN +*/ +bool dispatch_command(enum enum_server_command command, THD *thd, + char* packet, uint packet_length) +{ + NET *net= &thd->net; + bool error= 0; + DBUG_ENTER("dispatch_command"); + DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command)); + + thd->command=command; + /* + Commands which always take a long time are logged into + the slow log only if opt_log_slow_admin_statements is set. + */ + thd->enable_slow_log= TRUE; + thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */ + thd->set_time(); + VOID(pthread_mutex_lock(&LOCK_thread_count)); + thd->query_id= global_query_id; + + switch( command ) { + /* Ignore these statements. */ + case COM_STATISTICS: + case COM_PING: + break; + /* Only increase id on these statements but don't count them. */ + case COM_STMT_PREPARE: + case COM_STMT_CLOSE: + case COM_STMT_RESET: + next_query_id(); + break; + /* Increase id and count all other statements. */ + default: + statistic_increment(thd->status_var.questions, &LOCK_status); + next_query_id(); + } + + thread_running++; + /* TODO: set thd->lex->sql_command to SQLCOM_END here */ + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + + /** + Clear the set of flags that are expected to be cleared at the + beginning of each command. + */ + thd->server_status&= ~SERVER_STATUS_CLEAR_SET; + switch (command) { + case COM_INIT_DB: + { + LEX_STRING tmp; + status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]); + thd->convert_string(&tmp, system_charset_info, + packet, packet_length, thd->charset()); + if (!mysql_change_db(thd, &tmp, FALSE)) + { + general_log_write(thd, command, thd->db, thd->db_length); + my_ok(thd); + } + break; + } +#ifdef HAVE_REPLICATION + case COM_REGISTER_SLAVE: + { + if (!register_slave(thd, (uchar*)packet, packet_length)) + my_ok(thd); + break; + } +#endif + case COM_TABLE_DUMP: + { + char *tbl_name; + LEX_STRING db; + /* Safe because there is always a trailing \0 at the end of the packet */ + uint db_len= *(uchar*) packet; + if (db_len + 1 > packet_length || db_len > NAME_LEN) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + /* Safe because there is always a trailing \0 at the end of the packet */ + uint tbl_len= *(uchar*) (packet + db_len + 1); + if (db_len + tbl_len + 2 > packet_length || tbl_len > NAME_LEN) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + + status_var_increment(thd->status_var.com_other); + thd->enable_slow_log= opt_log_slow_admin_statements; + db.str= (char*) thd->alloc(db_len + tbl_len + 2); + if (!db.str) + { + my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0)); + break; + } + db.length= db_len; + tbl_name= strmake(db.str, packet + 1, db_len)+1; + strmake(tbl_name, packet + db_len + 2, tbl_len); + if (mysql_table_dump(thd, &db, tbl_name) == 0) + thd->main_da.disable_status(); + break; + } + case COM_CHANGE_USER: + { + status_var_increment(thd->status_var.com_other); + char *user= (char*) packet, *packet_end= packet + packet_length; + /* Safe because there is always a trailing \0 at the end of the packet */ + char *passwd= strend(user)+1; + + thd->change_user(); + thd->clear_error(); // if errors from rollback + + /* + Old clients send null-terminated string ('\0' for empty string) for + password. New clients send the size (1 byte) + string (not null + terminated, so also '\0' for empty string). + + Cast *passwd to an unsigned char, so that it doesn't extend the sign + for *passwd > 127 and become 2**32-127 after casting to uint. + */ + char db_buff[NAME_LEN+1]; // buffer to store db in utf8 + char *db= passwd; + char *save_db; + /* + If there is no password supplied, the packet must contain '\0', + in any type of handshake (4.1 or pre-4.1). + */ + if (passwd >= packet_end) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ? + (uchar)(*passwd++) : strlen(passwd)); + uint dummy_errors, save_db_length, db_length; + int res; + Security_context save_security_ctx= *thd->security_ctx; + USER_CONN *save_user_connect; + + db+= passwd_len + 1; + /* + Database name is always NUL-terminated, so in case of empty database + the packet must contain at least the trailing '\0'. + */ + if (db >= packet_end) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + db_length= strlen(db); + + char *ptr= db + db_length + 1; + uint cs_number= 0; + + if (ptr < packet_end) + { + if (ptr + 2 > packet_end) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + + cs_number= uint2korr(ptr); + } + + /* Convert database name to utf8 */ + db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1, + system_charset_info, db, db_length, + thd->charset(), &dummy_errors)]= 0; + db= db_buff; + + /* Save user and privileges */ + save_db_length= thd->db_length; + save_db= thd->db; + save_user_connect= thd->user_connect; + + if (!(thd->security_ctx->user= my_strdup(user, MYF(0)))) + { + thd->security_ctx->user= save_security_ctx.user; + my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0)); + break; + } + + /* Clear variables that are allocated */ + thd->user_connect= 0; + thd->security_ctx->priv_user= thd->security_ctx->user; + res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE); + + if (res) + { + x_free(thd->security_ctx->user); + *thd->security_ctx= save_security_ctx; + thd->user_connect= save_user_connect; + thd->db= save_db; + thd->db_length= save_db_length; + } + else + { +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* we've authenticated new user */ + if (save_user_connect) + decrease_user_connections(save_user_connect); +#endif /* NO_EMBEDDED_ACCESS_CHECKS */ + x_free(save_db); + x_free(save_security_ctx.user); + + if (cs_number) + { + thd_init_client_charset(thd, cs_number); + thd->update_charset(); + } + } + break; + } + case COM_STMT_EXECUTE: + { + mysqld_stmt_execute(thd, packet, packet_length); + break; + } + case COM_STMT_FETCH: + { + mysqld_stmt_fetch(thd, packet, packet_length); + break; + } + case COM_STMT_SEND_LONG_DATA: + { + mysql_stmt_get_longdata(thd, packet, packet_length); + break; + } + case COM_STMT_PREPARE: + { + mysqld_stmt_prepare(thd, packet, packet_length); + break; + } + case COM_STMT_CLOSE: + { + mysqld_stmt_close(thd, packet); + break; + } + case COM_STMT_RESET: + { + mysqld_stmt_reset(thd, packet); + break; + } + case COM_QUERY: + { + if (alloc_query(thd, packet, packet_length)) + break; // fatal error is set + char *packet_end= thd->query + thd->query_length; + /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */ + const char* end_of_stmt= NULL; + + general_log_write(thd, command, thd->query, thd->query_length); + DBUG_PRINT("query",("%-.4096s",thd->query)); +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.set_query_source(thd->query, thd->query_length); +#endif + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(),QUERY_PRIOR); + + if (idb_vtable_process(thd)) + { + thd->row_count_func = 0; //Bug 5315 + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->infinidb_vtable.isInfiniDBDML = false; //@bug5117 + } + + while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error()) + { + char *beginning_of_next_stmt= (char*) end_of_stmt; + + net_end_statement(thd); + query_cache_end_of_result(thd); + /* + Multiple queries exits, execute them individually + */ + close_thread_tables(thd); + ulong length= (ulong)(packet_end - beginning_of_next_stmt); + + log_slow_statement(thd); + + /* Remove garbage at start of query */ + while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt)) + { + beginning_of_next_stmt++; + length--; + } + +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.finish_current_query(); + thd->profiling.start_new_query("continuing"); + thd->profiling.set_query_source(beginning_of_next_stmt, length); +#endif + + thd->set_query(beginning_of_next_stmt, length); + VOID(pthread_mutex_lock(&LOCK_thread_count)); + /* + Count each statement from the client. + */ + statistic_increment(thd->status_var.questions, &LOCK_status); + thd->query_id= next_query_id(); + thd->set_time(); /* Reset the query start time. */ + /* TODO: set thd->lex->sql_command to SQLCOM_END here */ + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt); + } + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(),WAIT_PRIOR); + DBUG_PRINT("info",("query ready")); + + + break; + } + case COM_FIELD_LIST: // This isn't actually needed +#ifdef DONT_ALLOW_SHOW_COMMANDS + my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), + MYF(0)); /* purecov: inspected */ + break; +#else + { + char *fields, *packet_end= packet + packet_length, *arg_end; + /* Locked closure of all tables */ + TABLE_LIST table_list; + LEX_STRING conv_name; + + /* used as fields initializator */ + lex_start(thd); + + status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]); + bzero((char*) &table_list,sizeof(table_list)); + if (thd->copy_db_to(&table_list.db, &table_list.db_length)) + break; + /* + We have name + wildcard in packet, separated by endzero + */ + arg_end= strend(packet); + thd->convert_string(&conv_name, system_charset_info, + packet, (uint) (arg_end - packet), thd->charset()); + table_list.alias= table_list.table_name= conv_name.str; + packet= arg_end + 1; + + if (!my_strcasecmp(system_charset_info, table_list.db, + INFORMATION_SCHEMA_NAME.str)) + { + ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias); + if (schema_table) + table_list.schema_table= schema_table; + } + + uint query_length= (uint) (packet_end - packet); // Don't count end \0 + if (!(fields= (char *) thd->memdup(packet, query_length + 1))) + break; + thd->set_query(fields, query_length); + general_log_print(thd, command, "%s %s", table_list.table_name, fields); + if (lower_case_table_names) + my_casedn_str(files_charset_info, table_list.table_name); + + if (check_access(thd,SELECT_ACL,table_list.db,&table_list.grant.privilege, + 0, 0, test(table_list.schema_table))) + break; + if (check_grant(thd, SELECT_ACL, &table_list, 2, UINT_MAX, 0)) + break; + /* init structures for VIEW processing */ + table_list.select_lex= &(thd->lex->select_lex); + + lex_start(thd); + mysql_reset_thd_for_next_command(thd); + + thd->lex-> + select_lex.table_list.link_in_list((uchar*) &table_list, + (uchar**) &table_list.next_local); + thd->lex->add_to_query_tables(&table_list); + + /* switch on VIEW optimisation: do not fill temporary tables */ + thd->lex->sql_command= SQLCOM_SHOW_FIELDS; + mysqld_list_fields(thd,&table_list,fields); + thd->lex->unit.cleanup(); + thd->cleanup_after_query(); + break; + } +#endif + case COM_QUIT: + /* We don't calculate statistics for this command */ + general_log_print(thd, command, NullS); + net->error=0; // Don't give 'abort' message + thd->main_da.disable_status(); // Don't send anything back + error=TRUE; // End server + break; + +#ifdef REMOVED + case COM_CREATE_DB: // QQ: To be removed + { + LEX_STRING db, alias; + HA_CREATE_INFO create_info; + + status_var_increment(thd->status_var.com_stat[SQLCOM_CREATE_DB]); + if (thd->make_lex_string(&db, packet, packet_length, FALSE) || + thd->make_lex_string(&alias, db.str, db.length, FALSE) || + check_db_name(&db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL"); + break; + } + if (check_access(thd, CREATE_ACL, db.str , 0, 1, 0, + is_schema_db(db.str))) + break; + general_log_print(thd, command, "%.*s", db.length, db.str); + bzero(&create_info, sizeof(create_info)); + mysql_create_db(thd, (lower_case_table_names == 2 ? alias.str : db.str), + &create_info, 0); + break; + } + case COM_DROP_DB: // QQ: To be removed + { + status_var_increment(thd->status_var.com_stat[SQLCOM_DROP_DB]); + LEX_STRING db; + + if (thd->make_lex_string(&db, packet, packet_length, FALSE) || + check_db_name(&db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), db.str ? db.str : "NULL"); + break; + } + if (check_access(thd, DROP_ACL, db.str, 0, 1, 0, is_schema_db(db.str))) + break; + if (thd->locked_tables || thd->active_transaction()) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + break; + } + general_log_write(thd, command, "%.*s", db.length, db.str); + mysql_rm_db(thd, db.str, 0, 0); + break; + } +#endif +#ifndef EMBEDDED_LIBRARY + case COM_BINLOG_DUMP: + { + ulong pos; + ushort flags; + uint32 slave_server_id; + + status_var_increment(thd->status_var.com_other); + thd->enable_slow_log= opt_log_slow_admin_statements; + if (check_global_access(thd, REPL_SLAVE_ACL)) + break; + + /* TODO: The following has to be changed to an 8 byte integer */ + pos = uint4korr(packet); + flags = uint2korr(packet + 4); + thd->server_id=0; /* avoid suicide */ + if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0 + kill_zombie_dump_threads(slave_server_id); + thd->server_id = slave_server_id; + + general_log_print(thd, command, "Log: '%s' Pos: %ld", packet+10, + (long) pos); + mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags); + unregister_slave(thd,1,1); + /* fake COM_QUIT -- if we get here, the thread needs to terminate */ + error = TRUE; + break; + } +#endif + case COM_REFRESH: + { + bool not_used; + status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]); + ulong options= (ulong) (uchar) packet[0]; + if (check_global_access(thd,RELOAD_ACL)) + break; + general_log_print(thd, command, NullS); + if (!reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, ¬_used)) + my_ok(thd); + break; + } +#ifndef EMBEDDED_LIBRARY + case COM_SHUTDOWN: + { + status_var_increment(thd->status_var.com_other); + if (check_global_access(thd,SHUTDOWN_ACL)) + break; /* purecov: inspected */ + /* + If the client is < 4.1.3, it is going to send us no argument; then + packet_length is 0, packet[0] is the end 0 of the packet. Note that + SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in + packet[0]. + */ + enum mysql_enum_shutdown_level level= + (enum mysql_enum_shutdown_level) (uchar) packet[0]; + if (level == SHUTDOWN_DEFAULT) + level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable + else if (level != SHUTDOWN_WAIT_ALL_BUFFERS) + { + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level"); + break; + } + DBUG_PRINT("quit",("Got shutdown command for level %u", level)); + general_log_print(thd, command, NullS); + my_eof(thd); + close_thread_tables(thd); // Free before kill + kill_mysql(); + error=TRUE; + break; + } +#endif + case COM_STATISTICS: + { + STATUS_VAR current_global_status_var; + ulong uptime; + uint length; + ulonglong queries_per_second1000; + char buff[250]; + uint buff_len= sizeof(buff); + + general_log_print(thd, command, NullS); + status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]); + calc_sum_of_all_status(¤t_global_status_var); + if (!(uptime= (ulong) (thd->start_time - server_start_time))) + queries_per_second1000= 0; + else + queries_per_second1000= thd->query_id * LL(1000) / uptime; + + length= my_snprintf((char*) buff, buff_len - 1, + "Uptime: %lu Threads: %d Questions: %lu " + "Slow queries: %lu Opens: %lu Flush tables: %lu " + "Open tables: %u Queries per second avg: %u.%u", + uptime, + (int) thread_count, (ulong) thd->query_id, + current_global_status_var.long_query_count, + current_global_status_var.opened_tables, + refresh_version, + cached_open_tables(), + (uint) (queries_per_second1000 / 1000), + (uint) (queries_per_second1000 % 1000)); +#ifdef EMBEDDED_LIBRARY + /* Store the buffer in permanent memory */ + my_ok(thd, 0, 0, buff); +#endif +#ifdef SAFEMALLOC + if (sf_malloc_cur_memory) // Using SAFEMALLOC + { + char *end= buff + length; + length+= my_snprintf(end, buff_len - length - 1, + end," Memory in use: %ldK Max memory used: %ldK", + (sf_malloc_cur_memory+1023L)/1024L, + (sf_malloc_max_memory+1023L)/1024L); + } +#endif +#ifndef EMBEDDED_LIBRARY + VOID(my_net_write(net, (uchar*) buff, length)); + VOID(net_flush(net)); + thd->main_da.disable_status(); +#endif + break; + } + case COM_PING: + status_var_increment(thd->status_var.com_other); + my_ok(thd); // Tell client we are alive + break; + case COM_PROCESS_INFO: + status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]); + if (!thd->security_ctx->priv_user[0] && + check_global_access(thd, PROCESS_ACL)) + break; + general_log_print(thd, command, NullS); + mysqld_list_processes(thd, + thd->security_ctx->master_access & PROCESS_ACL ? + NullS : thd->security_ctx->priv_user, 0); + break; + case COM_PROCESS_KILL: + { + status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]); + ulong id=(ulong) uint4korr(packet); + sql_kill(thd,id,false); + break; + } + case COM_SET_OPTION: + { + status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]); + uint opt_command= uint2korr(packet); + + switch (opt_command) { + case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON: + thd->client_capabilities|= CLIENT_MULTI_STATEMENTS; + my_eof(thd); + break; + case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF: + thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS; + my_eof(thd); + break; + default: + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + break; + } + case COM_DEBUG: + status_var_increment(thd->status_var.com_other); + if (check_global_access(thd, SUPER_ACL)) + break; /* purecov: inspected */ + mysql_print_status(); + general_log_print(thd, command, NullS); + my_eof(thd); + break; + case COM_SLEEP: + case COM_CONNECT: // Impossible here + case COM_TIME: // Impossible from client + case COM_DELAYED_INSERT: + case COM_END: + default: + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + break; + } + + /* report error issued during command execution */ + if (thd->killed_errno()) + { + if (! thd->main_da.is_set()) + thd->send_kill_message(); + } + if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA) + { + thd->killed= THD::NOT_KILLED; + thd->mysys_var->abort= 0; + } + + /* If commit fails, we should be able to reset the OK status. */ + thd->main_da.can_overwrite_status= TRUE; + ha_autocommit_or_rollback(thd, thd->is_error()); + thd->main_da.can_overwrite_status= FALSE; + + thd->transaction.stmt.reset(); + + net_end_statement(thd); + query_cache_end_of_result(thd); + + thd->proc_info= "closing tables"; + /* Free tables */ + close_thread_tables(thd); + + // @InfiniDB + if (thd->query && thd->infinidb_vtable.vtable_state != THD::INFINIDB_INIT + && thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE + && !(thd->lex->sql_command == SQLCOM_UPDATE_MULTI) && !(thd->lex->sql_command == SQLCOM_UPDATE) + && !(thd->lex->sql_command == SQLCOM_DELETE_MULTI) && !(thd->lex->sql_command == SQLCOM_DELETE)) + { + // @bug 3906. No dropping vtable at the end of the query. drop it at the begining of the next query. + thd->infinidb_vtable.vtable_state = THD::INFINIDB_INIT; + } + + log_slow_statement(thd); + + thd_proc_info(thd, "cleaning up"); + thd->set_query(NULL, 0); + thd->command=COM_SLEEP; + VOID(pthread_mutex_lock(&LOCK_thread_count)); // For process list + thread_running--; + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + thd_proc_info(thd, 0); + thd->packet.shrink(thd->variables.net_buffer_length); // Reclaim some memory + free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC)); + + + DBUG_RETURN(error); +} + + +void log_slow_statement(THD *thd) +{ + DBUG_ENTER("log_slow_statement"); + + /* + The following should never be true with our current code base, + but better to keep this here so we don't accidently try to log a + statement in a trigger or stored function + */ + if (unlikely(thd->in_sub_stmt)) + DBUG_VOID_RETURN; // Don't set time for sub stmt + + /* + Do not log administrative statements unless the appropriate option is + set; do not log into slow log if reading from backup. + */ + if (thd->enable_slow_log && !thd->user_time) + { + ulonglong end_utime_of_query= thd->current_utime(); + thd_proc_info(thd, "logging slow query"); + + if (((end_utime_of_query - thd->utime_after_lock) > + thd->variables.long_query_time || + ((thd->server_status & + (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) && + opt_log_queries_not_using_indexes && + !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) && + thd->examined_row_count >= thd->variables.min_examined_row_limit) + { + thd_proc_info(thd, "logging slow query"); + thd->status_var.long_query_count++; + slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query); + } + } + DBUG_VOID_RETURN; +} + + +/** + Create a TABLE_LIST object for an INFORMATION_SCHEMA table. + + This function is used in the parser to convert a SHOW or DESCRIBE + table_name command to a SELECT from INFORMATION_SCHEMA. + It prepares a SELECT_LEX and a TABLE_LIST object to represent the + given command as a SELECT parse tree. + + @param thd thread handle + @param lex current lex + @param table_ident table alias if it's used + @param schema_table_idx the type of the INFORMATION_SCHEMA table to be + created + + @note + Due to the way this function works with memory and LEX it cannot + be used outside the parser (parse tree transformations outside + the parser break PS and SP). + + @retval + 0 success + @retval + 1 out of memory or SHOW commands are not allowed + in this version of the server. +*/ + +int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident, + enum enum_schema_tables schema_table_idx) +{ + SELECT_LEX *schema_select_lex= NULL; + DBUG_ENTER("prepare_schema_table"); + + switch (schema_table_idx) { + case SCH_SCHEMATA: +#if defined(DONT_ALLOW_SHOW_COMMANDS) + my_message(ER_NOT_ALLOWED_COMMAND, + ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ + DBUG_RETURN(1); +#else + break; +#endif + + case SCH_TABLE_NAMES: + case SCH_TABLES: + case SCH_VIEWS: + case SCH_TRIGGERS: + case SCH_EVENTS: +#ifdef DONT_ALLOW_SHOW_COMMANDS + my_message(ER_NOT_ALLOWED_COMMAND, + ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ + DBUG_RETURN(1); +#else + { + LEX_STRING db; + size_t dummy; + if (lex->select_lex.db == NULL && + lex->copy_db_to(&lex->select_lex.db, &dummy)) + { + DBUG_RETURN(1); + } + schema_select_lex= new SELECT_LEX(); + db.str= schema_select_lex->db= lex->select_lex.db; + schema_select_lex->table_list.first= NULL; + db.length= strlen(db.str); + + if (check_db_name(&db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), db.str); + DBUG_RETURN(1); + } + break; + } +#endif + case SCH_COLUMNS: + case SCH_STATISTICS: + { +#ifdef DONT_ALLOW_SHOW_COMMANDS + my_message(ER_NOT_ALLOWED_COMMAND, + ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ + DBUG_RETURN(1); +#else + DBUG_ASSERT(table_ident); + TABLE_LIST **query_tables_last= lex->query_tables_last; + schema_select_lex= new SELECT_LEX(); + /* 'parent_lex' is used in init_query() so it must be before it. */ + schema_select_lex->parent_lex= lex; + schema_select_lex->init_query(); + if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ)) + DBUG_RETURN(1); + lex->query_tables_last= query_tables_last; + break; + } +#endif + case SCH_PROFILES: + /* + Mark this current profiling record to be discarded. We don't + wish to have SHOW commands show up in profiling. + */ +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.discard_current_query(); +#endif + break; + case SCH_OPEN_TABLES: + case SCH_VARIABLES: + case SCH_STATUS: + case SCH_PROCEDURES: + case SCH_CHARSETS: + case SCH_ENGINES: + case SCH_COLLATIONS: + case SCH_COLLATION_CHARACTER_SET_APPLICABILITY: + case SCH_USER_PRIVILEGES: + case SCH_SCHEMA_PRIVILEGES: + case SCH_TABLE_PRIVILEGES: + case SCH_COLUMN_PRIVILEGES: + case SCH_TABLE_CONSTRAINTS: + case SCH_KEY_COLUMN_USAGE: + default: + break; + } + + SELECT_LEX *select_lex= lex->current_select; + if (make_schema_select(thd, select_lex, schema_table_idx)) + { + DBUG_RETURN(1); + } + TABLE_LIST *table_list= (TABLE_LIST*) select_lex->table_list.first; + table_list->schema_select_lex= schema_select_lex; + table_list->schema_table_reformed= 1; + DBUG_RETURN(0); +} + + +/** + Read query from packet and store in thd->query. + Used in COM_QUERY and COM_STMT_PREPARE. + + Sets the following THD variables: + - query + - query_length + + @retval + FALSE ok + @retval + TRUE error; In this case thd->fatal_error is set +*/ + +bool alloc_query(THD *thd, const char *packet, uint packet_length) +{ + char *query; + /* Remove garbage at start and end of query */ + while (packet_length > 0 && my_isspace(thd->charset(), packet[0])) + { + packet++; + packet_length--; + } + const char *pos= packet + packet_length; // Point at end null + while (packet_length > 0 && + (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1]))) + { + pos--; + packet_length--; + } + /* We must allocate some extra memory for query cache */ + if (! (query= (char*) thd->memdup_w_gap(packet, + packet_length, + 1 + thd->db_length + + QUERY_CACHE_FLAGS_SIZE))) + return TRUE; + query[packet_length]= '\0'; + thd->set_query(query, packet_length); + + /* Reclaim some memory */ + thd->packet.shrink(thd->variables.net_buffer_length); + thd->convert_buffer.shrink(thd->variables.net_buffer_length); + + return FALSE; +} + +static void reset_one_shot_variables(THD *thd) +{ + thd->variables.character_set_client= + global_system_variables.character_set_client; + thd->variables.collation_connection= + global_system_variables.collation_connection; + thd->variables.collation_database= + global_system_variables.collation_database; + thd->variables.collation_server= + global_system_variables.collation_server; + thd->update_charset(); + thd->variables.time_zone= + global_system_variables.time_zone; + thd->variables.lc_time_names= &my_locale_en_US; + thd->one_shot_set= 0; +} + + +static +bool sp_process_definer(THD *thd) +{ + DBUG_ENTER("sp_process_definer"); + + LEX *lex= thd->lex; + + /* + If the definer is not specified, this means that CREATE-statement missed + DEFINER-clause. DEFINER-clause can be missed in two cases: + + - The user submitted a statement w/o the clause. This is a normal + case, we should assign CURRENT_USER as definer. + + - Our slave received an updated from the master, that does not + replicate definer for stored rountines. We should also assign + CURRENT_USER as definer here, but also we should mark this routine + as NON-SUID. This is essential for the sake of backward + compatibility. + + The problem is the slave thread is running under "special" user (@), + that actually does not exist. In the older versions we do not fail + execution of a stored routine if its definer does not exist and + continue the execution under the authorization of the invoker + (BUG#13198). And now if we try to switch to slave-current-user (@), + we will fail. + + Actually, this leads to the inconsistent state of master and + slave (different definers, different SUID behaviour), but it seems, + this is the best we can do. + */ + + if (!lex->definer) + { + Query_arena original_arena; + Query_arena *ps_arena= thd->activate_stmt_arena_if_needed(&original_arena); + + lex->definer= create_default_definer(thd); + + if (ps_arena) + thd->restore_active_arena(ps_arena, &original_arena); + + /* Error has been already reported. */ + if (lex->definer == NULL) + DBUG_RETURN(TRUE); + + if (thd->slave_thread && lex->sphead) + lex->sphead->m_chistics->suid= SP_IS_NOT_SUID; + } + else + { + /* + If the specified definer differs from the current user, we + should check that the current user has SUPER privilege (in order + to create a stored routine under another user one must have + SUPER privilege). + */ + if ((strcmp(lex->definer->user.str, thd->security_ctx->priv_user) || + my_strcasecmp(system_charset_info, lex->definer->host.str, + thd->security_ctx->priv_host)) && + check_global_access(thd, SUPER_ACL)) + { + my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER"); + DBUG_RETURN(TRUE); + } + } + + /* Check that the specified definer exists. Emit a warning if not. */ + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (!is_acl_user(lex->definer->host.str, lex->definer->user.str)) + { + push_warning_printf(thd, + MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_NO_SUCH_USER, + ER(ER_NO_SUCH_USER), + lex->definer->user.str, + lex->definer->host.str); + } +#endif /* NO_EMBEDDED_ACCESS_CHECKS */ + + DBUG_RETURN(FALSE); +} + + +/** + Execute command saved in thd and lex->sql_command. + + Before every operation that can request a write lock for a table + wait if a global read lock exists. However do not wait if this + thread has locked tables already. No new locks can be requested + until the other locks are released. The thread that requests the + global read lock waits for write locked tables to become unlocked. + + Note that wait_if_global_read_lock() sets a protection against a new + global read lock when it succeeds. This needs to be released by + start_waiting_global_read_lock() after the operation. + + @param thd Thread handle + + @todo + - Invalidate the table in the query cache if something changed + after unlocking when changes become visible. + TODO: this is workaround. right way will be move invalidating in + the unlock procedure. + - TODO: use check_change_password() + - JOIN is not supported yet. TODO + - SUSPEND and FOR MIGRATE are not supported yet. TODO + + @retval + FALSE OK + @retval + TRUE Error +*/ + +int +mysql_execute_command(THD *thd) +{ + int res= FALSE; + bool need_start_waiting= FALSE; // have protection against global read lock + int up_result= 0; + LEX *lex= thd->lex; + /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */ + SELECT_LEX *select_lex= &lex->select_lex; + /* first table of first SELECT_LEX */ + TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first; + /* list of all tables in query */ + TABLE_LIST *all_tables; + /* most outer SELECT_LEX_UNIT of query */ + SELECT_LEX_UNIT *unit= &lex->unit; +#ifdef HAVE_REPLICATION + /* have table map for update for multi-update statement (BUG#37051) */ + bool have_table_map_for_update= FALSE; +#endif + /* Saved variable value */ + DBUG_ENTER("mysql_execute_command"); +#ifdef WITH_PARTITION_STORAGE_ENGINE + thd->work_part_info= 0; +#endif + + /* + In many cases first table of main SELECT_LEX have special meaning => + check that it is first table in global list and relink it first in + queries_tables list if it is necessary (we need such relinking only + for queries with subqueries in select list, in this case tables of + subqueries will go to global list first) + + all_tables will differ from first_table only if most upper SELECT_LEX + do not contain tables. + + Because of above in place where should be at least one table in most + outer SELECT_LEX we have following check: + DBUG_ASSERT(first_table == all_tables); + DBUG_ASSERT(first_table == all_tables && first_table != 0); + */ + lex->first_lists_tables_same(); + /* should be assigned after making first tables same */ + all_tables= lex->query_tables; + /* set context for commands which do not use setup_tables */ + select_lex-> + context.resolve_in_table_list_only((TABLE_LIST*)select_lex-> + table_list.first); + + /* + Reset warning count for each query that uses tables + A better approach would be to reset this for any commands + that is not a SHOW command or a select that only access local + variables, but for now this is probably good enough. + Don't reset warnings when executing a stored routine. + */ + if ((all_tables || !lex->is_single_level_stmt()) && !thd->spcont) + mysql_reset_errors(thd, 0); + +#ifdef HAVE_REPLICATION + if (unlikely(thd->slave_thread)) + { + if (lex->sql_command == SQLCOM_DROP_TRIGGER) + { + /* + When dropping a trigger, we need to load its table name + before checking slave filter rules. + */ + add_table_for_trigger(thd, thd->lex->spname, 1, &all_tables); + + if (!all_tables) + { + /* + If table name cannot be loaded, + it means the trigger does not exists possibly because + CREATE TRIGGER was previously skipped for this trigger + according to slave filtering rules. + Returning success without producing any errors in this case. + */ + DBUG_RETURN(0); + } + + // force searching in slave.cc:tables_ok() + all_tables->updating= 1; + } + + /* + For fix of BUG#37051, the master stores the table map for update + in the Query_log_event, and the value is assigned to + thd->variables.table_map_for_update before executing the update + query. + + If thd->variables.table_map_for_update is set, then we are + replicating from a new master, we can use this value to apply + filter rules without opening all the tables. However If + thd->variables.table_map_for_update is not set, then we are + replicating from an old master, so we just skip this and + continue with the old method. And of course, the bug would still + exist for old masters. + */ + if (lex->sql_command == SQLCOM_UPDATE_MULTI && + thd->table_map_for_update) + { + have_table_map_for_update= TRUE; + table_map table_map_for_update= thd->table_map_for_update; + uint nr= 0; + TABLE_LIST *table; + for (table=all_tables; table; table=table->next_global, nr++) + { + if (table_map_for_update & ((table_map)1 << nr)) + table->updating= TRUE; + else + table->updating= FALSE; + } + + if (all_tables_not_ok(thd, all_tables)) + { + /* we warn the slave SQL thread */ + my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); + if (thd->one_shot_set) + reset_one_shot_variables(thd); + DBUG_RETURN(0); + } + + for (table=all_tables; table; table=table->next_global) + table->updating= TRUE; + } + + /* + Check if statment should be skipped because of slave filtering + rules + + Exceptions are: + - UPDATE MULTI: For this statement, we want to check the filtering + rules later in the code + - SET: we always execute it (Not that many SET commands exists in + the binary log anyway -- only 4.1 masters write SET statements, + in 5.0 there are no SET statements in the binary log) + - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we + have stale files on slave caused by exclusion of one tmp table). + */ + if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) && + !(lex->sql_command == SQLCOM_SET_OPTION) && + !(lex->sql_command == SQLCOM_DROP_TABLE && + lex->drop_temporary && lex->drop_if_exists) && + all_tables_not_ok(thd, all_tables)) + { + /* we warn the slave SQL thread */ + my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); + if (thd->one_shot_set) + { + /* + It's ok to check thd->one_shot_set here: + + The charsets in a MySQL 5.0 slave can change by both a binlogged + SET ONE_SHOT statement and the event-internal charset setting, + and these two ways to change charsets do not seems to work + together. + + At least there seems to be problems in the rli cache for + charsets if we are using ONE_SHOT. Note that this is normally no + problem because either the >= 5.0 slave reads a 4.1 binlog (with + ONE_SHOT) *or* or 5.0 binlog (without ONE_SHOT) but never both." + */ + reset_one_shot_variables(thd); + } + DBUG_RETURN(0); + } + } + else + { +#endif /* HAVE_REPLICATION */ + /* + When option readonly is set deny operations which change non-temporary + tables. Except for the replication thread and the 'super' users. + */ + if (deny_updates_if_read_only_option(thd, all_tables)) + { + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only"); + DBUG_RETURN(-1); + } +#ifdef HAVE_REPLICATION + } /* endif unlikely slave */ +#endif + status_var_increment(thd->status_var.com_stat[lex->sql_command]); + + DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE); + + switch (lex->sql_command) { + + case SQLCOM_SHOW_EVENTS: +#ifndef HAVE_EVENT_SCHEDULER + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server"); + break; +#endif + case SQLCOM_SHOW_STATUS_PROC: + case SQLCOM_SHOW_STATUS_FUNC: + if (!(res= check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE))) + res= execute_sqlcom_select(thd, all_tables); + break; + case SQLCOM_SHOW_STATUS: + { + system_status_var old_status_var= thd->status_var; + thd->initial_status_var= &old_status_var; + if (!(res= check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE))) + res= execute_sqlcom_select(thd, all_tables); + /* Don't log SHOW STATUS commands to slow query log */ + thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | + SERVER_QUERY_NO_GOOD_INDEX_USED); + /* + restore status variables, as we don't want 'show status' to cause + changes + */ + pthread_mutex_lock(&LOCK_status); + add_diff_to_status(&global_status_var, &thd->status_var, + &old_status_var); + thd->status_var= old_status_var; + pthread_mutex_unlock(&LOCK_status); + break; + } + case SQLCOM_SHOW_DATABASES: + case SQLCOM_SHOW_TABLES: + case SQLCOM_SHOW_TRIGGERS: + case SQLCOM_SHOW_TABLE_STATUS: + case SQLCOM_SHOW_OPEN_TABLES: + case SQLCOM_SHOW_PLUGINS: + case SQLCOM_SHOW_FIELDS: + case SQLCOM_SHOW_KEYS: + case SQLCOM_SHOW_VARIABLES: + case SQLCOM_SHOW_CHARSETS: + case SQLCOM_SHOW_COLLATIONS: + case SQLCOM_SHOW_STORAGE_ENGINES: + case SQLCOM_SHOW_PROFILE: + case SQLCOM_SELECT: + thd->status_var.last_query_cost= 0.0; + if (all_tables) + { + res= check_table_access(thd, + lex->exchange ? SELECT_ACL | FILE_ACL : + SELECT_ACL, + all_tables, UINT_MAX, FALSE); + } + else + res= check_access(thd, + lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL, + any_db, 0, 0, 0, 0); + + if (res) + break; + + if (!thd->locked_tables && lex->protect_against_global_read_lock && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + break; + + res= execute_sqlcom_select(thd, all_tables); + break; + case SQLCOM_PREPARE: + { + mysql_sql_stmt_prepare(thd); + break; + } + case SQLCOM_EXECUTE: + { + mysql_sql_stmt_execute(thd); + break; + } + case SQLCOM_DEALLOCATE_PREPARE: + { + mysql_sql_stmt_close(thd); + break; + } + case SQLCOM_DO: + if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) || + open_and_lock_tables(thd, all_tables)) + goto error; + + res= mysql_do(thd, *lex->insert_list); + break; + + case SQLCOM_EMPTY_QUERY: + my_ok(thd); + break; + + case SQLCOM_HELP: + res= mysqld_help(thd,lex->help_arg); + break; + +#ifndef EMBEDDED_LIBRARY + case SQLCOM_PURGE: + { + if (check_global_access(thd, SUPER_ACL)) + goto error; + /* PURGE MASTER LOGS TO 'file' */ + res = purge_master_logs(thd, lex->to_log); + break; + } + case SQLCOM_PURGE_BEFORE: + { + Item *it; + + if (check_global_access(thd, SUPER_ACL)) + goto error; + /* PURGE MASTER LOGS BEFORE 'data' */ + it= (Item *)lex->value_list.head(); + if ((!it->fixed && it->fix_fields(lex->thd, &it)) || + it->check_cols(1)) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE"); + goto error; + } + it= new Item_func_unix_timestamp(it); + /* + it is OK only emulate fix_fieds, because we need only + value of constant + */ + it->quick_fix_field(); + res = purge_master_logs_before_date(thd, (ulong)it->val_int()); + break; + } +#endif + case SQLCOM_SHOW_WARNS: + { + res= mysqld_show_warnings(thd, (ulong) + ((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) | + (1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) | + (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR) + )); + break; + } + case SQLCOM_SHOW_ERRORS: + { + res= mysqld_show_warnings(thd, (ulong) + (1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)); + break; + } + case SQLCOM_SHOW_PROFILES: + { +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.discard_current_query(); + res= thd->profiling.show_profiles(); + if (res) + goto error; +#else + my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling"); + goto error; +#endif + break; + } + case SQLCOM_SHOW_NEW_MASTER: + { + if (check_global_access(thd, REPL_SLAVE_ACL)) + goto error; + /* This query don't work now. See comment in repl_failsafe.cc */ +#ifndef WORKING_NEW_MASTER + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER"); + goto error; +#else + res = show_new_master(thd); + break; +#endif + } + +#ifdef HAVE_REPLICATION + case SQLCOM_SHOW_SLAVE_HOSTS: + { + if (check_global_access(thd, REPL_SLAVE_ACL)) + goto error; + res = show_slave_hosts(thd); + break; + } + case SQLCOM_SHOW_BINLOG_EVENTS: + { + if (check_global_access(thd, REPL_SLAVE_ACL)) + goto error; + res = mysql_show_binlog_events(thd); + break; + } +#endif + + case SQLCOM_BACKUP_TABLE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) || + check_global_access(thd, FILE_ACL)) + goto error; /* purecov: inspected */ + thd->enable_slow_log= opt_log_slow_admin_statements; + res = mysql_backup_table(thd, first_table); + select_lex->table_list.first= (uchar*) first_table; + lex->query_tables=all_tables; + break; + } + case SQLCOM_RESTORE_TABLE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, INSERT_ACL, all_tables, UINT_MAX, FALSE) || + check_global_access(thd, FILE_ACL)) + goto error; /* purecov: inspected */ + thd->enable_slow_log= opt_log_slow_admin_statements; + res = mysql_restore_table(thd, first_table); + select_lex->table_list.first= (uchar*) first_table; + lex->query_tables=all_tables; + break; + } + case SQLCOM_ASSIGN_TO_KEYCACHE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_access(thd, INDEX_ACL, first_table->db, + &first_table->grant.privilege, 0, 0, + test(first_table->schema_table))) + goto error; + res= mysql_assign_to_keycache(thd, first_table, &lex->ident); + break; + } + case SQLCOM_PRELOAD_KEYS: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_access(thd, INDEX_ACL, first_table->db, + &first_table->grant.privilege, 0, 0, + test(first_table->schema_table))) + goto error; + res = mysql_preload_keys(thd, first_table); + break; + } +#ifdef HAVE_REPLICATION + case SQLCOM_CHANGE_MASTER: + { + if (check_global_access(thd, SUPER_ACL)) + goto error; + pthread_mutex_lock(&LOCK_active_mi); + res = change_master(thd,active_mi); + pthread_mutex_unlock(&LOCK_active_mi); + break; + } + case SQLCOM_SHOW_SLAVE_STAT: + { + /* Accept one of two privileges */ + if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL)) + goto error; + pthread_mutex_lock(&LOCK_active_mi); + if (active_mi != NULL) + { + res = show_master_info(thd, active_mi); + } + else + { + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + WARN_NO_MASTER_INFO, ER(WARN_NO_MASTER_INFO)); + my_ok(thd); + } + pthread_mutex_unlock(&LOCK_active_mi); + break; + } + case SQLCOM_SHOW_MASTER_STAT: + { + /* Accept one of two privileges */ + if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL)) + goto error; + res = show_binlog_info(thd); + break; + } + + case SQLCOM_LOAD_MASTER_DATA: // sync with master + if (check_global_access(thd, SUPER_ACL)) + goto error; + if (end_active_trans(thd)) + goto error; + res = load_master_data(thd); + break; +#endif /* HAVE_REPLICATION */ + case SQLCOM_SHOW_ENGINE_STATUS: + { + if (check_global_access(thd, PROCESS_ACL)) + goto error; + res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS); + break; + } + case SQLCOM_SHOW_ENGINE_MUTEX: + { + if (check_global_access(thd, PROCESS_ACL)) + goto error; + res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX); + break; + } +#ifdef HAVE_REPLICATION + case SQLCOM_LOAD_MASTER_TABLE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + DBUG_ASSERT(first_table->db); /* Must be set in the parser */ + + if (check_access(thd, CREATE_ACL, first_table->db, + &first_table->grant.privilege, 0, 0, + test(first_table->schema_table))) + goto error; /* purecov: inspected */ + /* Check that the first table has CREATE privilege */ + if (check_grant(thd, CREATE_ACL, all_tables, 0, 1, 0)) + goto error; + + pthread_mutex_lock(&LOCK_active_mi); + /* + fetch_master_table will send the error to the client on failure. + Give error if the table already exists. + */ + if (!fetch_master_table(thd, first_table->db, first_table->table_name, + active_mi, 0, 0)) + { + my_ok(thd); + } + pthread_mutex_unlock(&LOCK_active_mi); + break; + } +#endif /* HAVE_REPLICATION */ + + case SQLCOM_CREATE_TABLE: + { + /* If CREATE TABLE of non-temporary table, do implicit commit */ + if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)) + { + if (end_active_trans(thd)) + { + res= -1; + break; + } + } + DBUG_ASSERT(first_table == all_tables && first_table != 0); + bool link_to_local; + // Skip first table, which is the table we are creating + TABLE_LIST *create_table= lex->unlink_first_table(&link_to_local); + TABLE_LIST *select_tables= lex->query_tables; + /* + Code below (especially in mysql_create_table() and select_create + methods) may modify HA_CREATE_INFO structure in LEX, so we have to + use a copy of this structure to make execution prepared statement- + safe. A shallow copy is enough as this code won't modify any memory + referenced from this structure. + */ + HA_CREATE_INFO create_info(lex->create_info); + /* + We need to copy alter_info for the same reasons of re-execution + safety, only in case of Alter_info we have to do (almost) a deep + copy. + */ + Alter_info alter_info(lex->alter_info, thd->mem_root); + + if (thd->is_fatal_error) + { + /* If out of memory when creating a copy of alter_info. */ + res= 1; + goto end_with_restore_list; + } + + if ((res= create_table_precheck(thd, select_tables, create_table))) + goto end_with_restore_list; + + /* Might have been updated in create_table_precheck */ + create_info.alias= create_table->alias; + +#ifdef HAVE_READLINK + /* Fix names if symlinked tables */ + if (append_file_to_dir(thd, &create_info.data_file_name, + create_table->table_name) || + append_file_to_dir(thd, &create_info.index_file_name, + create_table->table_name)) + goto end_with_restore_list; +#endif + /* + If we are using SET CHARSET without DEFAULT, add an implicit + DEFAULT to not confuse old users. (This may change). + */ + if ((create_info.used_fields & + (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) == + HA_CREATE_USED_CHARSET) + { + create_info.used_fields&= ~HA_CREATE_USED_CHARSET; + create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET; + create_info.default_table_charset= create_info.table_charset; + create_info.table_charset= 0; + } + /* + The create-select command will open and read-lock the select table + and then create, open and write-lock the new table. If a global + read lock steps in, we get a deadlock. The write lock waits for + the global read lock, while the global read lock waits for the + select table to be closed. So we wait until the global readlock is + gone before starting both steps. Note that + wait_if_global_read_lock() sets a protection against a new global + read lock when it succeeds. This needs to be released by + start_waiting_global_read_lock(). We protect the normal CREATE + TABLE in the same way. That way we avoid that a new table is + created during a gobal read lock. + */ + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + { + res= 1; + goto end_with_restore_list; + } +#ifdef WITH_PARTITION_STORAGE_ENGINE + { + partition_info *part_info= thd->lex->part_info; + if (part_info && !(part_info= thd->lex->part_info->get_clone())) + { + res= -1; + goto end_with_restore_list; + } + thd->work_part_info= part_info; + } +#endif + if (select_lex->item_list.elements) // With select + { + select_result *result; + + /* + If: + a) we inside an SP and there was NAME_CONST substitution, + b) binlogging is on (STMT mode), + c) we log the SP as separate statements + raise a warning, as it may cause problems + (see 'NAME_CONST issues' in 'Binary Logging of Stored Programs') + */ + if (thd->query_name_consts && + mysql_bin_log.is_open() && + thd->variables.binlog_format == BINLOG_FORMAT_STMT && + !mysql_bin_log.is_query_in_union(thd, thd->query_id)) + { + List_iterator_fast it(select_lex->item_list); + Item *item; + uint splocal_refs= 0; + /* Count SP local vars in the top-level SELECT list */ + while ((item= it++)) + { + if (item->is_splocal()) + splocal_refs++; + } + /* + If it differs from number of NAME_CONST substitution applied, + we may have a SOME_FUNC(NAME_CONST()) in the SELECT list, + that may cause a problem with binary log (see BUG#35383), + raise a warning. + */ + if (splocal_refs != thd->query_name_consts) + push_warning(thd, + MYSQL_ERROR::WARN_LEVEL_WARN, + ER_UNKNOWN_ERROR, +"Invoked routine ran a statement that may cause problems with " +"binary log, see 'NAME_CONST issues' in 'Binary Logging of Stored Programs' " +"section of the manual."); + } + + select_lex->options|= SELECT_NO_UNLOCK; + unit->set_limit(select_lex); + + /* + Disable non-empty MERGE tables with CREATE...SELECT. Too + complicated. See Bug #26379. Empty MERGE tables are read-only + and don't allow CREATE...SELECT anyway. + */ + if (create_info.used_fields & HA_CREATE_USED_UNION) + { + my_error(ER_WRONG_OBJECT, MYF(0), create_table->db, + create_table->table_name, "BASE TABLE"); + res= 1; + goto end_with_restore_list; + } + + if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE)) + { + lex->link_first_table_back(create_table, link_to_local); + create_table->create= TRUE; + } + + if (!(res= open_and_lock_tables(thd, lex->query_tables))) + { + /* + Is table which we are changing used somewhere in other parts + of query + */ + if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE)) + { + TABLE_LIST *duplicate; + create_table= lex->unlink_first_table(&link_to_local); + if ((duplicate= unique_table(thd, create_table, select_tables, 0))) + { + update_non_unique_table_error(create_table, "CREATE", duplicate); + res= 1; + goto end_with_restore_list; + } + } + /* If we create merge table, we have to test tables in merge, too */ + if (create_info.used_fields & HA_CREATE_USED_UNION) + { + TABLE_LIST *tab; + for (tab= (TABLE_LIST*) create_info.merge_list.first; + tab; + tab= tab->next_local) + { + TABLE_LIST *duplicate; + if ((duplicate= unique_table(thd, tab, select_tables, 0))) + { + update_non_unique_table_error(tab, "CREATE", duplicate); + res= 1; + goto end_with_restore_list; + } + } + } + + /* + select_create is currently not re-execution friendly and + needs to be created for every execution of a PS/SP. + */ + if ((result= new select_create(create_table, + &create_info, + &alter_info, + select_lex->item_list, + lex->duplicates, + lex->ignore, + select_tables))) + { + /* + CREATE from SELECT give its SELECT_LEX for SELECT, + and item_list belong to SELECT + */ + res= handle_select(thd, lex, result, 0); + delete result; + } + } + else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE)) + create_table= lex->unlink_first_table(&link_to_local); + + } + else + { + /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */ + if (create_info.options & HA_LEX_CREATE_TMP_TABLE) + thd->options|= OPTION_KEEP_LOG; + /* regular create */ + if (create_info.options & HA_LEX_CREATE_TABLE_LIKE) + res= mysql_create_like_table(thd, create_table, select_tables, + &create_info); + else + { + res= mysql_create_table(thd, create_table->db, + create_table->table_name, &create_info, + &alter_info, 0, 0); + } + if (!res) + my_ok(thd); + } + + /* put tables back for PS rexecuting */ +end_with_restore_list: + lex->link_first_table_back(create_table, link_to_local); + break; + } + case SQLCOM_CREATE_INDEX: + /* Fall through */ + case SQLCOM_DROP_INDEX: + /* + CREATE INDEX and DROP INDEX are implemented by calling ALTER + TABLE with proper arguments. + + In the future ALTER TABLE will notice that the request is to + only add indexes and create these one by one for the existing + table without having to do a full rebuild. + */ + { + /* Prepare stack copies to be re-execution safe */ + HA_CREATE_INFO create_info; + Alter_info alter_info(lex->alter_info, thd->mem_root); + + if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */ + goto error; + + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_one_table_access(thd, INDEX_ACL, all_tables)) + goto error; /* purecov: inspected */ + if (end_active_trans(thd)) + goto error; + /* + Currently CREATE INDEX or DROP INDEX cause a full table rebuild + and thus classify as slow administrative statements just like + ALTER TABLE. + */ + thd->enable_slow_log= opt_log_slow_admin_statements; + + bzero((char*) &create_info, sizeof(create_info)); + create_info.db_type= 0; + create_info.row_type= ROW_TYPE_NOT_USED; + create_info.default_table_charset= thd->variables.collation_database; + + res= mysql_alter_table(thd, first_table->db, first_table->table_name, + &create_info, first_table, &alter_info, + 0, (ORDER*) 0, 0); + break; + } +#ifdef HAVE_REPLICATION + case SQLCOM_SLAVE_START: + { + pthread_mutex_lock(&LOCK_active_mi); + start_slave(thd,active_mi,1 /* net report*/); + pthread_mutex_unlock(&LOCK_active_mi); + break; + } + case SQLCOM_SLAVE_STOP: + /* + If the client thread has locked tables, a deadlock is possible. + Assume that + - the client thread does LOCK TABLE t READ. + - then the master updates t. + - then the SQL slave thread wants to update t, + so it waits for the client thread because t is locked by it. + - then the client thread does SLAVE STOP. + SLAVE STOP waits for the SQL slave thread to terminate its + update t, which waits for the client thread because t is locked by it. + To prevent that, refuse SLAVE STOP if the + client thread has locked tables + */ + if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + goto error; + } + { + pthread_mutex_lock(&LOCK_active_mi); + stop_slave(thd,active_mi,1/* net report*/); + pthread_mutex_unlock(&LOCK_active_mi); + break; + } +#endif /* HAVE_REPLICATION */ + + case SQLCOM_ALTER_TABLE: + DBUG_ASSERT(first_table == all_tables && first_table != 0); + { + ulong priv=0; + ulong priv_needed= ALTER_ACL; + /* + Code in mysql_alter_table() may modify its HA_CREATE_INFO argument, + so we have to use a copy of this structure to make execution + prepared statement- safe. A shallow copy is enough as no memory + referenced from this structure will be modified. + */ + HA_CREATE_INFO create_info(lex->create_info); + Alter_info alter_info(lex->alter_info, thd->mem_root); + + if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */ + goto error; + /* + We also require DROP priv for ALTER TABLE ... DROP PARTITION, as well + as for RENAME TO, as being done by SQLCOM_RENAME_TABLE + */ + if (alter_info.flags & (ALTER_DROP_PARTITION | ALTER_RENAME)) + priv_needed|= DROP_ACL; + + /* Must be set in the parser */ + DBUG_ASSERT(select_lex->db); + if (check_access(thd, priv_needed, first_table->db, + &first_table->grant.privilege, 0, 0, + test(first_table->schema_table)) || + check_access(thd,INSERT_ACL | CREATE_ACL,select_lex->db,&priv,0,0, + is_schema_db(select_lex->db))|| + check_merge_table_access(thd, first_table->db, + (TABLE_LIST *) + create_info.merge_list.first)) + goto error; /* purecov: inspected */ + if (check_grant(thd, priv_needed, all_tables, 0, UINT_MAX, 0)) + goto error; + if (lex->name.str && !test_all_bits(priv,INSERT_ACL | CREATE_ACL)) + { // Rename of table + TABLE_LIST tmp_table; + bzero((char*) &tmp_table,sizeof(tmp_table)); + tmp_table.table_name= lex->name.str; + tmp_table.db=select_lex->db; + tmp_table.grant.privilege=priv; + if (check_grant(thd, INSERT_ACL | CREATE_ACL, &tmp_table, 0, + UINT_MAX, 0)) + goto error; + } + + /* Don't yet allow changing of symlinks with ALTER TABLE */ + if (create_info.data_file_name) + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED), + "DATA DIRECTORY"); + if (create_info.index_file_name) + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED), + "INDEX DIRECTORY"); + create_info.data_file_name= create_info.index_file_name= NULL; + /* ALTER TABLE ends previous transaction */ + if (end_active_trans(thd)) + goto error; + + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + { + res= 1; + break; + } + + thd->enable_slow_log= opt_log_slow_admin_statements; + res= mysql_alter_table(thd, select_lex->db, lex->name.str, + &create_info, + first_table, + &alter_info, + select_lex->order_list.elements, + (ORDER *) select_lex->order_list.first, + lex->ignore); + break; + } + case SQLCOM_RENAME_TABLE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + TABLE_LIST *table; + for (table= first_table; table; table= table->next_local->next_local) + { + if (check_access(thd, ALTER_ACL | DROP_ACL, table->db, + &table->grant.privilege,0,0, test(table->schema_table)) || + check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db, + &table->next_local->grant.privilege, 0, 0, + test(table->next_local->schema_table))) + goto error; + TABLE_LIST old_list, new_list; + /* + we do not need initialize old_list and new_list because we will + come table[0] and table->next[0] there + */ + old_list= table[0]; + new_list= table->next_local[0]; + if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, 0, 1, 0) || + (!test_all_bits(table->next_local->grant.privilege, + INSERT_ACL | CREATE_ACL) && + check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, 0, 1, 0))) + goto error; + } + + if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0)) + goto error; + break; + } +#ifndef EMBEDDED_LIBRARY + case SQLCOM_SHOW_BINLOGS: +#ifdef DONT_ALLOW_SHOW_COMMANDS + my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), + MYF(0)); /* purecov: inspected */ + goto error; +#else + { + if (check_global_access(thd, SUPER_ACL)) + goto error; + res = show_binlogs(thd); + break; + } +#endif +#endif /* EMBEDDED_LIBRARY */ + case SQLCOM_SHOW_CREATE: + DBUG_ASSERT(first_table == all_tables && first_table != 0); +#ifdef DONT_ALLOW_SHOW_COMMANDS + my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), + MYF(0)); /* purecov: inspected */ + goto error; +#else + { + /* Ignore temporary tables if this is "SHOW CREATE VIEW" */ + if (lex->only_view) + first_table->skip_temporary= 1; + if (check_show_create_table_access(thd, first_table)) + goto error; + res= mysqld_show_create(thd, first_table); + break; + } +#endif + case SQLCOM_CHECKSUM: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL | EXTRA_ACL, all_tables, + UINT_MAX, FALSE)) + goto error; /* purecov: inspected */ + res = mysql_checksum_table(thd, first_table, &lex->check_opt); + break; + } + case SQLCOM_REPAIR: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, + UINT_MAX, FALSE)) + goto error; /* purecov: inspected */ + thd->enable_slow_log= opt_log_slow_admin_statements; + res= mysql_repair_table(thd, first_table, &lex->check_opt); + /* ! we write after unlocking the table */ + if (!res && !lex->no_write_to_binlog) + { + /* + Presumably, REPAIR and binlog writing doesn't require synchronization + */ + write_bin_log(thd, TRUE, thd->query, thd->query_length); + } + select_lex->table_list.first= (uchar*) first_table; + lex->query_tables=all_tables; + break; + } + case SQLCOM_CHECK: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL | EXTRA_ACL , all_tables, + UINT_MAX, FALSE)) + goto error; /* purecov: inspected */ + thd->enable_slow_log= opt_log_slow_admin_statements; + res = mysql_check_table(thd, first_table, &lex->check_opt); + select_lex->table_list.first= (uchar*) first_table; + lex->query_tables=all_tables; + break; + } + case SQLCOM_ANALYZE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, + UINT_MAX, FALSE)) + goto error; /* purecov: inspected */ + thd->enable_slow_log= opt_log_slow_admin_statements; + res= mysql_analyze_table(thd, first_table, &lex->check_opt); + /* ! we write after unlocking the table */ + if (!res && !lex->no_write_to_binlog) + { + /* + Presumably, ANALYZE and binlog writing doesn't require synchronization + */ + write_bin_log(thd, TRUE, thd->query, thd->query_length); + } + select_lex->table_list.first= (uchar*) first_table; + lex->query_tables=all_tables; + break; + } + + case SQLCOM_OPTIMIZE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL | INSERT_ACL, all_tables, + UINT_MAX, FALSE)) + goto error; /* purecov: inspected */ + thd->enable_slow_log= opt_log_slow_admin_statements; + res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ? + mysql_recreate_table(thd, first_table) : + mysql_optimize_table(thd, first_table, &lex->check_opt); + /* ! we write after unlocking the table */ + if (!res && !lex->no_write_to_binlog) + { + /* + Presumably, OPTIMIZE and binlog writing doesn't require synchronization + */ + write_bin_log(thd, TRUE, thd->query, thd->query_length); + } + select_lex->table_list.first= (uchar*) first_table; + lex->query_tables=all_tables; + break; + } + case SQLCOM_UPDATE: + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (update_precheck(thd, all_tables)) + break; + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + goto error; + DBUG_ASSERT(select_lex->offset_limit == 0); + unit->set_limit(select_lex); + res= (up_result= mysql_update(thd, all_tables, + select_lex->item_list, + lex->value_list, + select_lex->where, + select_lex->order_list.elements, + (ORDER *) select_lex->order_list.first, + unit->select_limit_cnt, + lex->duplicates, lex->ignore)); + /* mysql_update return 2 if we need to switch to multi-update */ + if (up_result != 2) + break; + /* Fall through */ + case SQLCOM_UPDATE_MULTI: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + /* if we switched from normal update, rights are checked */ + if (up_result != 2) + { + if ((res= multi_update_precheck(thd, all_tables))) + break; + } + else + res= 0; + + /* + Protection might have already been risen if its a fall through + from the SQLCOM_UPDATE case above. + */ + if (!thd->locked_tables && + lex->sql_command == SQLCOM_UPDATE_MULTI && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + goto error; + + res= mysql_multi_update_prepare(thd); + +#ifdef HAVE_REPLICATION + /* Check slave filtering rules */ + if (unlikely(thd->slave_thread && !have_table_map_for_update)) + { + if (all_tables_not_ok(thd, all_tables)) + { + if (res!= 0) + { + res= 0; /* don't care of prev failure */ + thd->clear_error(); /* filters are of highest prior */ + } + /* we warn the slave SQL thread */ + my_error(ER_SLAVE_IGNORED_TABLE, MYF(0)); + break; + } + if (res) + break; + } + else + { +#endif /* HAVE_REPLICATION */ + if (res) + break; + if (opt_readonly && + !(thd->security_ctx->master_access & SUPER_ACL) && + some_non_temp_table_to_be_updated(thd, all_tables)) + { + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only"); + break; + } +#ifdef HAVE_REPLICATION + } /* unlikely */ +#endif + + res= mysql_multi_update(thd, all_tables, + &select_lex->item_list, + &lex->value_list, + select_lex->where, + select_lex->options, + lex->duplicates, lex->ignore, unit, select_lex); + break; + } + case SQLCOM_REPLACE: +#ifndef DBUG_OFF + if (mysql_bin_log.is_open()) + { + /* + Generate an incident log event before writing the real event + to the binary log. We put this event is before the statement + since that makes it simpler to check that the statement was + not executed on the slave (since incidents usually stop the + slave). + + Observe that any row events that are generated will be + generated before. + + This is only for testing purposes and will not be present in a + release build. + */ + + Incident incident= INCIDENT_NONE; + DBUG_PRINT("debug", ("Just before generate_incident()")); + DBUG_EXECUTE_IF("incident_database_resync_on_replace", + incident= INCIDENT_LOST_EVENTS;); + if (incident) + { + Incident_log_event ev(thd, incident); + mysql_bin_log.write(&ev); + mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE); + } + DBUG_PRINT("debug", ("Just after generate_incident()")); + } +#endif + case SQLCOM_INSERT: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if ((res= insert_precheck(thd, all_tables))) + break; + + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + { + res= 1; + break; + } + + res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values, + lex->update_list, lex->value_list, + lex->duplicates, lex->ignore); + + /* + If we have inserted into a VIEW, and the base table has + AUTO_INCREMENT column, but this column is not accessible through + a view, then we should restore LAST_INSERT_ID to the value it + had before the statement. + */ + if (first_table->view && !first_table->contain_auto_increment) + thd->first_successful_insert_id_in_cur_stmt= + thd->first_successful_insert_id_in_prev_stmt; + + break; + } + case SQLCOM_REPLACE_SELECT: + case SQLCOM_INSERT_SELECT: + { + select_result *sel_result; + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if ((res= insert_precheck(thd, all_tables))) + break; + + /* Fix lock for first table */ + if (first_table->lock_type == TL_WRITE_DELAYED) + first_table->lock_type= TL_WRITE; + + /* Don't unlock tables until command is written to binary log */ + select_lex->options|= SELECT_NO_UNLOCK; + + unit->set_limit(select_lex); + + if (! thd->locked_tables && + ! (need_start_waiting= ! wait_if_global_read_lock(thd, 0, 1))) + { + res= 1; + break; + } + + if (!(res= open_and_lock_tables(thd, all_tables))) + { + /* Skip first table, which is the table we are inserting in */ + TABLE_LIST *second_table= first_table->next_local; + select_lex->table_list.first= (uchar*) second_table; + select_lex->context.table_list= + select_lex->context.first_name_resolution_table= second_table; + res= mysql_insert_select_prepare(thd); + if (!res && (sel_result= new select_insert(first_table, + first_table->table, + &lex->field_list, + &lex->update_list, + &lex->value_list, + lex->duplicates, + lex->ignore))) + { + res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE); + /* + Invalidate the table in the query cache if something changed + after unlocking when changes become visible. + TODO: this is workaround. right way will be move invalidating in + the unlock procedure. + */ + if (first_table->lock_type == TL_WRITE_CONCURRENT_INSERT && + thd->lock) + { + /* INSERT ... SELECT should invalidate only the very first table */ + TABLE_LIST *save_table= first_table->next_local; + first_table->next_local= 0; + query_cache_invalidate3(thd, first_table, 1); + first_table->next_local= save_table; + } + delete sel_result; + } + /* revert changes for SP */ + select_lex->table_list.first= (uchar*) first_table; + } + + /* + If we have inserted into a VIEW, and the base table has + AUTO_INCREMENT column, but this column is not accessible through + a view, then we should restore LAST_INSERT_ID to the value it + had before the statement. + */ + if (first_table->view && !first_table->contain_auto_increment) + thd->first_successful_insert_id_in_cur_stmt= + thd->first_successful_insert_id_in_prev_stmt; + + break; + } + case SQLCOM_TRUNCATE: + if (end_active_trans(thd)) + { + res= -1; + break; + } + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_one_table_access(thd, DROP_ACL, all_tables)) + goto error; + /* + Don't allow this within a transaction because we want to use + re-generate table + */ + if (thd->locked_tables || thd->active_transaction()) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + goto error; + } + if (!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + goto error; + res= mysql_truncate(thd, first_table, 0); + break; + case SQLCOM_DELETE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if ((res= delete_precheck(thd, all_tables))) + break; + DBUG_ASSERT(select_lex->offset_limit == 0); + unit->set_limit(select_lex); + + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + { + res= 1; + break; + } + + res = mysql_delete(thd, all_tables, select_lex->where, + &select_lex->order_list, + unit->select_limit_cnt, select_lex->options, + FALSE); + break; + } + case SQLCOM_DELETE_MULTI: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + TABLE_LIST *aux_tables= + (TABLE_LIST *)thd->lex->auxiliary_table_list.first; + multi_delete *del_result; + + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + { + res= 1; + break; + } + + if ((res= multi_delete_precheck(thd, all_tables))) + break; + + /* condition will be TRUE on SP re-excuting */ + if (select_lex->item_list.elements != 0) + select_lex->item_list.empty(); + if (add_item_to_list(thd, new Item_null())) + goto error; + + thd_proc_info(thd, "init"); + if ((res= open_and_lock_tables(thd, all_tables))) + break; + + if ((res= mysql_multi_delete_prepare(thd))) + goto error; + + if (!thd->is_fatal_error && + (del_result= new multi_delete(aux_tables, lex->table_count))) + { + res= mysql_select(thd, &select_lex->ref_pointer_array, + select_lex->get_table_list(), + select_lex->with_wild, + select_lex->item_list, + select_lex->where, + 0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL, + (ORDER *)NULL, + select_lex->options | thd->options | + SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK | + OPTION_SETUP_TABLES_DONE, + del_result, unit, select_lex); + res|= thd->is_error(); + if (res) + del_result->abort(); + delete del_result; + } + else + res= TRUE; // Error + break; + } + case SQLCOM_DROP_TABLE: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (!lex->drop_temporary) + { + if (check_table_access(thd, DROP_ACL, all_tables, UINT_MAX, FALSE)) + goto error; /* purecov: inspected */ + if (end_active_trans(thd)) + goto error; + } + else + { + /* + If this is a slave thread, we may sometimes execute some + DROP / * 40005 TEMPORARY * / TABLE + that come from parts of binlogs (likely if we use RESET SLAVE or CHANGE + MASTER TO), while the temporary table has already been dropped. + To not generate such irrelevant "table does not exist errors", + we silently add IF EXISTS if TEMPORARY was used. + */ + if (thd->slave_thread) + lex->drop_if_exists= 1; + + /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */ + thd->options|= OPTION_KEEP_LOG; + } + /* DDL and binlog write order protected by LOCK_open */ + res= mysql_rm_table(thd, first_table, lex->drop_if_exists, + lex->drop_temporary); + } + break; + case SQLCOM_SHOW_PROCESSLIST: + if (!thd->security_ctx->priv_user[0] && + check_global_access(thd,PROCESS_ACL)) + break; + mysqld_list_processes(thd, + (thd->security_ctx->master_access & PROCESS_ACL ? + NullS : + thd->security_ctx->priv_user), + lex->verbose); + break; + case SQLCOM_SHOW_AUTHORS: + res= mysqld_show_authors(thd); + break; + case SQLCOM_SHOW_CONTRIBUTORS: + res= mysqld_show_contributors(thd); + break; + case SQLCOM_SHOW_PRIVILEGES: + res= mysqld_show_privileges(thd); + break; + case SQLCOM_SHOW_COLUMN_TYPES: + res= mysqld_show_column_types(thd); + break; + case SQLCOM_SHOW_ENGINE_LOGS: +#ifdef DONT_ALLOW_SHOW_COMMANDS + my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), + MYF(0)); /* purecov: inspected */ + goto error; +#else + { + if (check_access(thd, FILE_ACL, any_db,0,0,0,0)) + goto error; + res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS); + break; + } +#endif + case SQLCOM_CHANGE_DB: + { + LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) }; + + if (!mysql_change_db(thd, &db_str, FALSE)) + my_ok(thd); + + break; + } + + case SQLCOM_LOAD: + { + DBUG_ASSERT(first_table == all_tables && first_table != 0); + uint privilege= (lex->duplicates == DUP_REPLACE ? + INSERT_ACL | DELETE_ACL : INSERT_ACL) | + (lex->local_file ? 0 : FILE_ACL); + + if (lex->local_file) + { + if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) || + !opt_local_infile) + { + my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); + goto error; + } + } + + if (check_one_table_access(thd, privilege, all_tables)) + goto error; + + if (!thd->locked_tables && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + goto error; + + res= mysql_load(thd, lex->exchange, first_table, lex->field_list, + lex->update_list, lex->value_list, lex->duplicates, + lex->ignore, (bool) lex->local_file); + break; + } + + case SQLCOM_SET_OPTION: + { + List *lex_var_list= &lex->var_list; + + if (lex->autocommit && end_active_trans(thd)) + goto error; + + if ((check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) || + open_and_lock_tables(thd, all_tables))) + goto error; + if (lex->one_shot_set && not_all_support_one_shot(lex_var_list)) + { + my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT"); + goto error; + } + if (!(res= sql_set_variables(thd, lex_var_list))) + { + /* + If the previous command was a SET ONE_SHOT, we don't want to forget + about the ONE_SHOT property of that SET. So we use a |= instead of = . + */ + thd->one_shot_set|= lex->one_shot_set; + my_ok(thd); + } + else + { + /* + We encountered some sort of error, but no message was sent. + Send something semi-generic here since we don't know which + assignment in the list caused the error. + */ + if (!thd->is_error()) + my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET"); + goto error; + } + + break; + } + + case SQLCOM_UNLOCK_TABLES: + /* + It is critical for mysqldump --single-transaction --master-data that + UNLOCK TABLES does not implicitely commit a connection which has only + done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes + false, mysqldump will not work. + */ + unlock_locked_tables(thd); + if (thd->options & OPTION_TABLE_LOCK) + { + end_active_trans(thd); + thd->options&= ~(OPTION_TABLE_LOCK); + } + if (thd->global_read_lock) + unlock_global_read_lock(thd); + my_ok(thd); + break; + case SQLCOM_LOCK_TABLES: + unlock_locked_tables(thd); + /* we must end the trasaction first, regardless of anything */ + if (end_active_trans(thd)) + goto error; + if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables, + UINT_MAX, FALSE)) + goto error; + if (lex->protect_against_global_read_lock && + !(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1))) + goto error; + thd->in_lock_tables=1; + thd->options|= OPTION_TABLE_LOCK; + + if (!(res= simple_open_n_lock_tables(thd, all_tables))) + { +#ifdef HAVE_QUERY_CACHE + if (thd->variables.query_cache_wlock_invalidate) + query_cache.invalidate_locked_for_write(first_table); +#endif /*HAVE_QUERY_CACHE*/ + thd->locked_tables=thd->lock; + thd->lock=0; + my_ok(thd); + } + else + { + /* + Need to end the current transaction, so the storage engine (InnoDB) + can free its locks if LOCK TABLES locked some tables before finding + that it can't lock a table in its list + */ + ha_autocommit_or_rollback(thd, 1); + end_active_trans(thd); + thd->options&= ~(OPTION_TABLE_LOCK); + } + thd->in_lock_tables=0; + break; + case SQLCOM_CREATE_DB: + { + /* + As mysql_create_db() may modify HA_CREATE_INFO structure passed to + it, we need to use a copy of LEX::create_info to make execution + prepared statement- safe. + */ + HA_CREATE_INFO create_info(lex->create_info); + if (end_active_trans(thd)) + { + res= -1; + break; + } + char *alias; + if (!(alias=thd->strmake(lex->name.str, lex->name.length)) || + check_db_name(&lex->name)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str); + break; + } + /* + If in a slave thread : + CREATE DATABASE DB was certainly not preceded by USE DB. + For that reason, db_ok() in sql/slave.cc did not check the + do_db/ignore_db. And as this query involves no tables, tables_ok() + above was not called. So we have to check rules again here. + */ +#ifdef HAVE_REPLICATION + if (thd->slave_thread && + (!rpl_filter->db_ok(lex->name.str) || + !rpl_filter->db_ok_with_wild_table(lex->name.str))) + { + my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); + break; + } +#endif + if (check_access(thd,CREATE_ACL,lex->name.str, 0, 1, 0, + is_schema_db(lex->name.str))) + break; + res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias : + lex->name.str), &create_info, 0); + break; + } + case SQLCOM_DROP_DB: + { + if (end_active_trans(thd)) + { + res= -1; + break; + } + if (check_db_name(&lex->name)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str); + break; + } + /* + If in a slave thread : + DROP DATABASE DB may not be preceded by USE DB. + For that reason, maybe db_ok() in sql/slave.cc did not check the + do_db/ignore_db. And as this query involves no tables, tables_ok() + above was not called. So we have to check rules again here. + */ +#ifdef HAVE_REPLICATION + if (thd->slave_thread && + (!rpl_filter->db_ok(lex->name.str) || + !rpl_filter->db_ok_with_wild_table(lex->name.str))) + { + my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); + break; + } +#endif + if (check_access(thd,DROP_ACL,lex->name.str,0,1,0, + is_schema_db(lex->name.str))) + break; + if (thd->locked_tables || thd->active_transaction()) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + goto error; + } + res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0); + break; + } + case SQLCOM_ALTER_DB_UPGRADE: + { + LEX_STRING *db= & lex->name; + if (end_active_trans(thd)) + { + res= 1; + break; + } +#ifdef HAVE_REPLICATION + if (thd->slave_thread && + (!rpl_filter->db_ok(db->str) || + !rpl_filter->db_ok_with_wild_table(db->str))) + { + res= 1; + my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); + break; + } +#endif + if (check_db_name(db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), db->str); + break; + } + if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str)) || + check_access(thd, DROP_ACL, db->str, 0, 1, 0, is_schema_db(db->str)) || + check_access(thd, CREATE_ACL, db->str, 0, 1, 0, is_schema_db(db->str))) + { + res= 1; + break; + } + if (thd->locked_tables || thd->active_transaction()) + { + res= 1; + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + goto error; + } + + res= mysql_upgrade_db(thd, db); + if (!res) + my_ok(thd); + break; + } + case SQLCOM_ALTER_DB: + { + LEX_STRING *db= &lex->name; + HA_CREATE_INFO create_info(lex->create_info); + if (check_db_name(db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), db->str); + break; + } + /* + If in a slave thread : + ALTER DATABASE DB may not be preceded by USE DB. + For that reason, maybe db_ok() in sql/slave.cc did not check the + do_db/ignore_db. And as this query involves no tables, tables_ok() + above was not called. So we have to check rules again here. + */ +#ifdef HAVE_REPLICATION + if (thd->slave_thread && + (!rpl_filter->db_ok(db->str) || + !rpl_filter->db_ok_with_wild_table(db->str))) + { + my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); + break; + } +#endif + if (check_access(thd, ALTER_ACL, db->str, 0, 1, 0, is_schema_db(db->str))) + break; + if (thd->locked_tables || thd->active_transaction()) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + goto error; + } + res= mysql_alter_db(thd, db->str, &create_info); + break; + } + case SQLCOM_SHOW_CREATE_DB: + { + DBUG_EXECUTE_IF("4x_server_emul", + my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;); + if (check_db_name(&lex->name)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str); + break; + } + res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info); + break; + } + case SQLCOM_CREATE_EVENT: + case SQLCOM_ALTER_EVENT: + #ifdef HAVE_EVENT_SCHEDULER + do + { + DBUG_ASSERT(lex->event_parse_data); + if (lex->table_or_sp_used()) + { + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored " + "function calls as part of this statement"); + break; + } + + res= sp_process_definer(thd); + if (res) + break; + + switch (lex->sql_command) { + case SQLCOM_CREATE_EVENT: + { + bool if_not_exists= (lex->create_info.options & + HA_LEX_CREATE_IF_NOT_EXISTS); + res= Events::create_event(thd, lex->event_parse_data, if_not_exists); + break; + } + case SQLCOM_ALTER_EVENT: + res= Events::update_event(thd, lex->event_parse_data, + lex->spname ? &lex->spname->m_db : NULL, + lex->spname ? &lex->spname->m_name : NULL); + break; + default: + DBUG_ASSERT(0); + } + DBUG_PRINT("info",("DDL error code=%d", res)); + if (!res) + my_ok(thd); + + } while (0); + /* Don't do it, if we are inside a SP */ + if (!thd->spcont) + { + delete lex->sphead; + lex->sphead= NULL; + } + /* lex->unit.cleanup() is called outside, no need to call it here */ + break; + case SQLCOM_SHOW_CREATE_EVENT: + res= Events::show_create_event(thd, lex->spname->m_db, + lex->spname->m_name); + break; + case SQLCOM_DROP_EVENT: + if (!(res= Events::drop_event(thd, + lex->spname->m_db, lex->spname->m_name, + lex->drop_if_exists))) + my_ok(thd); + break; +#else + my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server"); + break; +#endif + case SQLCOM_CREATE_FUNCTION: // UDF function + { + if (check_access(thd,INSERT_ACL,"mysql",0,1,0,0)) + break; +#ifdef HAVE_DLOPEN + if (!(res = mysql_create_function(thd, &lex->udf))) + my_ok(thd); +#else + my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled"); + res= TRUE; +#endif + break; + } +#ifndef NO_EMBEDDED_ACCESS_CHECKS + case SQLCOM_CREATE_USER: + { + if (check_access(thd, INSERT_ACL, "mysql", 0, 1, 1, 0) && + check_global_access(thd,CREATE_USER_ACL)) + break; + if (end_active_trans(thd)) + goto error; + /* Conditionally writes to binlog */ + if (!(res= mysql_create_user(thd, lex->users_list))) + my_ok(thd); + break; + } + case SQLCOM_DROP_USER: + { + if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 1, 0) && + check_global_access(thd,CREATE_USER_ACL)) + break; + if (end_active_trans(thd)) + goto error; + /* Conditionally writes to binlog */ + if (!(res= mysql_drop_user(thd, lex->users_list))) + my_ok(thd); + break; + } + case SQLCOM_RENAME_USER: + { + if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) && + check_global_access(thd,CREATE_USER_ACL)) + break; + if (end_active_trans(thd)) + goto error; + /* Conditionally writes to binlog */ + if (!(res= mysql_rename_user(thd, lex->users_list))) + my_ok(thd); + break; + } + case SQLCOM_REVOKE_ALL: + { + if (end_active_trans(thd)) + goto error; + if (check_access(thd, UPDATE_ACL, "mysql", 0, 1, 1, 0) && + check_global_access(thd,CREATE_USER_ACL)) + break; + /* Conditionally writes to binlog */ + if (!(res = mysql_revoke_all(thd, lex->users_list))) + my_ok(thd); + break; + } + case SQLCOM_REVOKE: + case SQLCOM_GRANT: + { + if (end_active_trans(thd)) + goto error; + + if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL, + first_table ? first_table->db : select_lex->db, + first_table ? &first_table->grant.privilege : 0, + first_table ? 0 : 1, 0, + first_table ? (bool) first_table->schema_table : + select_lex->db ? is_schema_db(select_lex->db) : 0)) + goto error; + + if (thd->security_ctx->user) // If not replication + { + LEX_USER *user, *tmp_user; + + List_iterator user_list(lex->users_list); + while ((tmp_user= user_list++)) + { + if (!(user= get_current_user(thd, tmp_user))) + goto error; + if (specialflag & SPECIAL_NO_RESOLVE && + hostname_requires_resolving(user->host.str)) + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_HOSTNAME_WONT_WORK, + ER(ER_WARN_HOSTNAME_WONT_WORK), + user->host.str); + // Are we trying to change a password of another user + DBUG_ASSERT(user->host.str != 0); + if (strcmp(thd->security_ctx->user, user->user.str) || + my_strcasecmp(system_charset_info, + user->host.str, thd->security_ctx->host_or_ip)) + { + // TODO: use check_change_password() + if (is_acl_user(user->host.str, user->user.str) && + user->password.str && + check_access(thd, UPDATE_ACL,"mysql",0,1,1,0)) + { + my_message(ER_PASSWORD_NOT_ALLOWED, + ER(ER_PASSWORD_NOT_ALLOWED), MYF(0)); + goto error; + } + } + } + } + if (first_table) + { + if (lex->type == TYPE_ENUM_PROCEDURE || + lex->type == TYPE_ENUM_FUNCTION) + { + uint grants= lex->all_privileges + ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL) + : lex->grant; + if (check_grant_routine(thd, grants | GRANT_ACL, all_tables, + lex->type == TYPE_ENUM_PROCEDURE, 0)) + goto error; + /* Conditionally writes to binlog */ + res= mysql_routine_grant(thd, all_tables, + lex->type == TYPE_ENUM_PROCEDURE, + lex->users_list, grants, + lex->sql_command == SQLCOM_REVOKE, TRUE); + if (!res) + my_ok(thd); + } + else + { + if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL), + all_tables, 0, UINT_MAX, 0)) + goto error; + /* Conditionally writes to binlog */ + res= mysql_table_grant(thd, all_tables, lex->users_list, + lex->columns, lex->grant, + lex->sql_command == SQLCOM_REVOKE); + } + } + else + { + if (lex->columns.elements || lex->type) + { + my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE), + MYF(0)); + goto error; + } + else + /* Conditionally writes to binlog */ + res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant, + lex->sql_command == SQLCOM_REVOKE); + if (!res) + { + if (lex->sql_command == SQLCOM_GRANT) + { + List_iterator str_list(lex->users_list); + LEX_USER *user, *tmp_user; + while ((tmp_user=str_list++)) + { + if (!(user= get_current_user(thd, tmp_user))) + goto error; + reset_mqh(user, 0); + } + } + } + } + break; + } +#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/ + case SQLCOM_RESET: + /* + RESET commands are never written to the binary log, so we have to + initialize this variable because RESET shares the same code as FLUSH + */ + lex->no_write_to_binlog= 1; + case SQLCOM_FLUSH: + { + bool write_to_binlog; + if (check_global_access(thd,RELOAD_ACL)) + goto error; + + /* + reload_acl_and_cache() will tell us if we are allowed to write to the + binlog or not. + */ + if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog)) + { + /* + We WANT to write and we CAN write. + ! we write after unlocking the table. + */ + /* + Presumably, RESET and binlog writing doesn't require synchronization + */ + if (!lex->no_write_to_binlog && write_to_binlog) + { + write_bin_log(thd, FALSE, thd->query, thd->query_length); + } + my_ok(thd); + } + + break; + } + case SQLCOM_KILL: + { + Item *it= (Item *)lex->value_list.head(); + + if (lex->table_or_sp_used()) + { + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored " + "function calls as part of this statement"); + break; + } + + if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1)) + { + my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY), + MYF(0)); + goto error; + } + sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY); + break; + } +#ifndef NO_EMBEDDED_ACCESS_CHECKS + case SQLCOM_SHOW_GRANTS: + { + LEX_USER *grant_user= get_current_user(thd, lex->grant_user); + if (!grant_user) + goto error; + if ((thd->security_ctx->priv_user && + !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) || + !check_access(thd, SELECT_ACL, "mysql",0,1,0,0)) + { + res = mysql_show_grants(thd, grant_user); + } + break; + } +#endif + case SQLCOM_HA_OPEN: + DBUG_ASSERT(first_table == all_tables && first_table != 0); + if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE)) + goto error; + res= mysql_ha_open(thd, first_table, 0); + break; + case SQLCOM_HA_CLOSE: + DBUG_ASSERT(first_table == all_tables && first_table != 0); + res= mysql_ha_close(thd, first_table); + break; + case SQLCOM_HA_READ: + DBUG_ASSERT(first_table == all_tables && first_table != 0); + /* + There is no need to check for table permissions here, because + if a user has no permissions to read a table, he won't be + able to open it (with SQLCOM_HA_OPEN) in the first place. + */ + unit->set_limit(select_lex); + res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str, + lex->insert_list, lex->ha_rkey_mode, select_lex->where, + unit->select_limit_cnt, unit->offset_limit_cnt); + break; + + case SQLCOM_BEGIN: + if (thd->transaction.xid_state.xa_state != XA_NOTR) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + break; + } + if (begin_trans(thd)) + goto error; + if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT) + { + if (ha_start_consistent_snapshot(thd)) + goto error; + } + my_ok(thd); + break; + case SQLCOM_COMMIT: + if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE : + lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT)) + goto error; + my_ok(thd); + break; + case SQLCOM_ROLLBACK: + if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE : + lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK)) + goto error; + my_ok(thd); + break; + case SQLCOM_RELEASE_SAVEPOINT: + { + SAVEPOINT *sv; + for (sv=thd->transaction.savepoints; sv; sv=sv->prev) + { + if (my_strnncoll(system_charset_info, + (uchar *)lex->ident.str, lex->ident.length, + (uchar *)sv->name, sv->length) == 0) + break; + } + if (sv) + { + if (ha_release_savepoint(thd, sv)) + res= TRUE; // cannot happen + else + my_ok(thd); + thd->transaction.savepoints=sv->prev; + } + else + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str); + break; + } + case SQLCOM_ROLLBACK_TO_SAVEPOINT: + { + SAVEPOINT *sv; + for (sv=thd->transaction.savepoints; sv; sv=sv->prev) + { + if (my_strnncoll(system_charset_info, + (uchar *)lex->ident.str, lex->ident.length, + (uchar *)sv->name, sv->length) == 0) + break; + } + if (sv) + { + if (ha_rollback_to_savepoint(thd, sv)) + res= TRUE; // cannot happen + else + { + if (((thd->options & OPTION_KEEP_LOG) || + thd->transaction.all.modified_non_trans_table) && + !thd->slave_thread) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARNING_NOT_COMPLETE_ROLLBACK, + ER(ER_WARNING_NOT_COMPLETE_ROLLBACK)); + my_ok(thd); + } + thd->transaction.savepoints=sv; + } + else + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str); + break; + } + case SQLCOM_SAVEPOINT: + if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) || + thd->in_sub_stmt) || !opt_using_transactions) + my_ok(thd); + else + { + SAVEPOINT **sv, *newsv; + for (sv=&thd->transaction.savepoints; *sv; sv=&(*sv)->prev) + { + if (my_strnncoll(system_charset_info, + (uchar *)lex->ident.str, lex->ident.length, + (uchar *)(*sv)->name, (*sv)->length) == 0) + break; + } + if (*sv) /* old savepoint of the same name exists */ + { + newsv=*sv; + ha_release_savepoint(thd, *sv); // it cannot fail + *sv=(*sv)->prev; + } + else if ((newsv=(SAVEPOINT *) alloc_root(&thd->transaction.mem_root, + savepoint_alloc_size)) == 0) + { + my_error(ER_OUT_OF_RESOURCES, MYF(0)); + break; + } + newsv->name=strmake_root(&thd->transaction.mem_root, + lex->ident.str, lex->ident.length); + newsv->length=lex->ident.length; + /* + if we'll get an error here, don't add new savepoint to the list. + we'll lose a little bit of memory in transaction mem_root, but it'll + be free'd when transaction ends anyway + */ + if (ha_savepoint(thd, newsv)) + res= TRUE; + else + { + newsv->prev=thd->transaction.savepoints; + thd->transaction.savepoints=newsv; + my_ok(thd); + } + } + break; + case SQLCOM_CREATE_PROCEDURE: + case SQLCOM_CREATE_SPFUNCTION: + { + uint namelen; + char *name; + int sp_result= SP_INTERNAL_ERROR; + + DBUG_ASSERT(lex->sphead != 0); + DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */ + /* + Verify that the database name is allowed, optionally + lowercase it. + */ + if (check_db_name(&lex->sphead->m_db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str); + goto create_sp_error; + } + + /* + Check that a database directory with this name + exists. Design note: This won't work on virtual databases + like information_schema. + */ + if (check_db_dir_existence(lex->sphead->m_db.str)) + { + my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str); + goto create_sp_error; + } + + if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, 0, 0, 0, + is_schema_db(lex->sphead->m_db.str))) + goto create_sp_error; + + if (end_active_trans(thd)) + goto create_sp_error; + + name= lex->sphead->name(&namelen); +#ifdef HAVE_DLOPEN + if (lex->sphead->m_type == TYPE_ENUM_FUNCTION) + { + udf_func *udf = find_udf(name, namelen); + + if (udf) + { + my_error(ER_UDF_EXISTS, MYF(0), name); + goto create_sp_error; + } + } +#endif + + if (sp_process_definer(thd)) + goto create_sp_error; + + res= (sp_result= lex->sphead->create(thd)); + switch (sp_result) { + case SP_OK: { +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* only add privileges if really neccessary */ + + Security_context security_context; + bool restore_backup_context= false; + Security_context *backup= NULL; + LEX_USER *definer= thd->lex->definer; + /* + Check if the definer exists on slave, + then use definer privilege to insert routine privileges to mysql.procs_priv. + + For current user of SQL thread has GLOBAL_ACL privilege, + which doesn't any check routine privileges, + so no routine privilege record will insert into mysql.procs_priv. + */ + if (thd->slave_thread && is_acl_user(definer->host.str, definer->user.str)) + { + security_context.change_security_context(thd, + &thd->lex->definer->user, + &thd->lex->definer->host, + &thd->lex->sphead->m_db, + &backup); + restore_backup_context= true; + } + + if (sp_automatic_privileges && !opt_noacl && + check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS, + lex->sphead->m_db.str, name, + lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1)) + { + if (sp_grant_privileges(thd, lex->sphead->m_db.str, name, + lex->sql_command == SQLCOM_CREATE_PROCEDURE)) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_PROC_AUTO_GRANT_FAIL, + ER(ER_PROC_AUTO_GRANT_FAIL)); + } + + /* + Restore current user with GLOBAL_ACL privilege of SQL thread + */ + if (restore_backup_context) + { + DBUG_ASSERT(thd->slave_thread == 1); + thd->security_ctx->restore_security_context(thd, backup); + } + +#endif + break; + } + case SP_WRITE_ROW_FAILED: + my_error(ER_SP_ALREADY_EXISTS, MYF(0), SP_TYPE_STRING(lex), name); + break; + case SP_BAD_IDENTIFIER: + my_error(ER_TOO_LONG_IDENT, MYF(0), name); + break; + case SP_BODY_TOO_LONG: + my_error(ER_TOO_LONG_BODY, MYF(0), name); + break; + case SP_FLD_STORE_FAILED: + my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name); + break; + default: + my_error(ER_SP_STORE_FAILED, MYF(0), SP_TYPE_STRING(lex), name); + break; + } /* end switch */ + + /* + Capture all errors within this CASE and + clean up the environment. + */ +create_sp_error: + if (sp_result != SP_OK ) + goto error; + my_ok(thd); + break; /* break super switch */ + } /* end case group bracket */ + case SQLCOM_CALL: + { + sp_head *sp; + + /* + This will cache all SP and SF and open and lock all tables + required for execution. + */ + if (check_table_access(thd, SELECT_ACL, all_tables, UINT_MAX, FALSE) || + open_and_lock_tables(thd, all_tables)) + goto error; + + /* + By this moment all needed SPs should be in cache so no need to look + into DB. + */ + if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname, + &thd->sp_proc_cache, TRUE))) + { + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE", + lex->spname->m_qname.str); + goto error; + } + else + { + ha_rows select_limit; + /* bits that should be cleared in thd->server_status */ + uint bits_to_be_cleared= 0; + /* + Check that the stored procedure doesn't contain Dynamic SQL + and doesn't return result sets: such stored procedures can't + be called from a function or trigger. + */ + if (thd->in_sub_stmt) + { + const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ? + "trigger" : "function"); + if (sp->is_not_allowed_in_function(where)) + goto error; + } + + if (sp->m_flags & sp_head::MULTI_RESULTS) + { + if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS)) + { + /* + The client does not support multiple result sets being sent + back + */ + my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str); + goto error; + } + /* + If SERVER_MORE_RESULTS_EXISTS is not set, + then remember that it should be cleared + */ + bits_to_be_cleared= (~thd->server_status & + SERVER_MORE_RESULTS_EXISTS); + thd->server_status|= SERVER_MORE_RESULTS_EXISTS; + } + + if (check_routine_access(thd, EXECUTE_ACL, + sp->m_db.str, sp->m_name.str, TRUE, FALSE)) + { + goto error; + } + select_limit= thd->variables.select_limit; + thd->variables.select_limit= HA_POS_ERROR; + + /* + We never write CALL statements into binlog: + - If the mode is non-prelocked, each statement will be logged + separately. + - If the mode is prelocked, the invoking statement will care + about writing into binlog. + So just execute the statement. + */ + res= sp->execute_procedure(thd, &lex->value_list); + /* + If warnings have been cleared, we have to clear total_warn_count + too, otherwise the clients get confused. + */ + if (thd->warn_list.is_empty()) + thd->total_warn_count= 0; + + thd->variables.select_limit= select_limit; + + thd->server_status&= ~bits_to_be_cleared; + + if (!res) + my_ok(thd, (ulong) (thd->row_count_func < 0 ? 0 : + thd->row_count_func)); + else + { + DBUG_ASSERT(thd->is_error() || thd->killed); + goto error; // Substatement should already have sent error + } + } + break; + } + case SQLCOM_ALTER_PROCEDURE: + case SQLCOM_ALTER_FUNCTION: + { + int sp_result; + sp_head *sp; + st_sp_chistics chistics; + + memcpy(&chistics, &lex->sp_chistics, sizeof(chistics)); + if (lex->sql_command == SQLCOM_ALTER_PROCEDURE) + sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname, + &thd->sp_proc_cache, FALSE); + else + sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname, + &thd->sp_func_cache, FALSE); + mysql_reset_errors(thd, 0); + if (! sp) + { + if (lex->spname->m_db.str) + sp_result= SP_KEY_NOT_FOUND; + else + { + my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); + goto error; + } + } + else + { + if (check_routine_access(thd, ALTER_PROC_ACL, sp->m_db.str, + sp->m_name.str, + lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0)) + goto error; + + if (end_active_trans(thd)) + goto error; + memcpy(&lex->sp_chistics, &chistics, sizeof(lex->sp_chistics)); + if ((sp->m_type == TYPE_ENUM_FUNCTION) && + !trust_function_creators && mysql_bin_log.is_open() && + !sp->m_chistics->detistic && + (chistics.daccess == SP_CONTAINS_SQL || + chistics.daccess == SP_MODIFIES_SQL_DATA)) + { + my_message(ER_BINLOG_UNSAFE_ROUTINE, + ER(ER_BINLOG_UNSAFE_ROUTINE), MYF(0)); + sp_result= SP_INTERNAL_ERROR; + } + else + { + /* + Note that if you implement the capability of ALTER FUNCTION to + alter the body of the function, this command should be made to + follow the restrictions that log-bin-trust-function-creators=0 + already puts on CREATE FUNCTION. + */ + /* Conditionally writes to binlog */ + + int type= lex->sql_command == SQLCOM_ALTER_PROCEDURE ? + TYPE_ENUM_PROCEDURE : + TYPE_ENUM_FUNCTION; + + sp_result= sp_update_routine(thd, + type, + lex->spname, + &lex->sp_chistics); + } + } + switch (sp_result) + { + case SP_OK: + my_ok(thd); + break; + case SP_KEY_NOT_FOUND: + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), + SP_COM_STRING(lex), lex->spname->m_qname.str); + goto error; + default: + my_error(ER_SP_CANT_ALTER, MYF(0), + SP_COM_STRING(lex), lex->spname->m_qname.str); + goto error; + } + break; + } + case SQLCOM_DROP_PROCEDURE: + case SQLCOM_DROP_FUNCTION: + { + int sp_result; + int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ? + TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION); + + sp_result= sp_routine_exists_in_table(thd, type, lex->spname); + mysql_reset_errors(thd, 0); + if (sp_result == SP_OK) + { + char *db= lex->spname->m_db.str; + char *name= lex->spname->m_name.str; + + if (check_routine_access(thd, ALTER_PROC_ACL, db, name, + lex->sql_command == SQLCOM_DROP_PROCEDURE, 0)) + goto error; + + if (end_active_trans(thd)) + goto error; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (sp_automatic_privileges && !opt_noacl && + sp_revoke_privileges(thd, db, name, + lex->sql_command == SQLCOM_DROP_PROCEDURE)) + { + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_PROC_AUTO_REVOKE_FAIL, + ER(ER_PROC_AUTO_REVOKE_FAIL)); + } +#endif + /* Conditionally writes to binlog */ + + int type= lex->sql_command == SQLCOM_DROP_PROCEDURE ? + TYPE_ENUM_PROCEDURE : + TYPE_ENUM_FUNCTION; + + sp_result= sp_drop_routine(thd, type, lex->spname); + } + else + { +#ifdef HAVE_DLOPEN + if (lex->sql_command == SQLCOM_DROP_FUNCTION) + { + udf_func *udf = find_udf(lex->spname->m_name.str, + lex->spname->m_name.length); + if (udf) + { + if (check_access(thd, DELETE_ACL, "mysql", 0, 1, 0, 0)) + goto error; + + if (!(res = mysql_drop_function(thd, &lex->spname->m_name))) + { + my_ok(thd); + break; + } + } + } +#endif + if (lex->spname->m_db.str) + sp_result= SP_KEY_NOT_FOUND; + else + { + my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); + goto error; + } + } + res= sp_result; + switch (sp_result) { + case SP_OK: + my_ok(thd); + break; + case SP_KEY_NOT_FOUND: + if (lex->drop_if_exists) + { + write_bin_log(thd, TRUE, thd->query, thd->query_length); + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST), + SP_COM_STRING(lex), lex->spname->m_name.str); + res= FALSE; + my_ok(thd); + break; + } + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), + SP_COM_STRING(lex), lex->spname->m_qname.str); + goto error; + default: + my_error(ER_SP_DROP_FAILED, MYF(0), + SP_COM_STRING(lex), lex->spname->m_qname.str); + goto error; + } + break; + } + case SQLCOM_SHOW_CREATE_PROC: + { + if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname)) + { + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), + SP_COM_STRING(lex), lex->spname->m_name.str); + goto error; + } + break; + } + case SQLCOM_SHOW_CREATE_FUNC: + { + if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname)) + { + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), + SP_COM_STRING(lex), lex->spname->m_name.str); + goto error; + } + break; + } +#ifndef DBUG_OFF + case SQLCOM_SHOW_PROC_CODE: + case SQLCOM_SHOW_FUNC_CODE: + { + sp_head *sp; + + if (lex->sql_command == SQLCOM_SHOW_PROC_CODE) + sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname, + &thd->sp_proc_cache, FALSE); + else + sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, lex->spname, + &thd->sp_func_cache, FALSE); + if (!sp || sp->show_routine_code(thd)) + { + /* We don't distinguish between errors for now */ + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), + SP_COM_STRING(lex), lex->spname->m_name.str); + goto error; + } + break; + } +#endif // ifndef DBUG_OFF + case SQLCOM_SHOW_CREATE_TRIGGER: + { + if (lex->spname->m_name.length > NAME_LEN) + { + my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str); + goto error; + } + + if (show_create_trigger(thd, lex->spname)) + goto error; /* Error has been already logged. */ + + break; + } + case SQLCOM_CREATE_VIEW: + { + /* + Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands + as specified through the thd->lex->create_view_mode flag. + */ + if (end_active_trans(thd)) + goto error; + + res= mysql_create_view(thd, first_table, thd->lex->create_view_mode); + break; + } + case SQLCOM_DROP_VIEW: + { + if (check_table_access(thd, DROP_ACL, all_tables, UINT_MAX, FALSE) || + end_active_trans(thd)) + goto error; + /* Conditionally writes to binlog. */ + res= mysql_drop_view(thd, first_table, thd->lex->drop_mode); + break; + } + case SQLCOM_CREATE_TRIGGER: + { + if (end_active_trans(thd)) + goto error; + + /* Conditionally writes to binlog. */ + res= mysql_create_or_drop_trigger(thd, all_tables, 1); + + break; + } + case SQLCOM_DROP_TRIGGER: + { + if (end_active_trans(thd)) + goto error; + + /* Conditionally writes to binlog. */ + res= mysql_create_or_drop_trigger(thd, all_tables, 0); + break; + } + case SQLCOM_XA_START: + if (thd->transaction.xid_state.xa_state == XA_IDLE && + thd->lex->xa_opt == XA_RESUME) + { + if (! thd->transaction.xid_state.xid.eq(thd->lex->xid)) + { + my_error(ER_XAER_NOTA, MYF(0)); + break; + } + thd->transaction.xid_state.xa_state=XA_ACTIVE; + my_ok(thd); + break; + } + if (thd->lex->xa_opt != XA_NONE) + { // JOIN is not supported yet. TODO + my_error(ER_XAER_INVAL, MYF(0)); + break; + } + if (thd->transaction.xid_state.xa_state != XA_NOTR) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + break; + } + if (thd->active_transaction() || thd->locked_tables) + { + my_error(ER_XAER_OUTSIDE, MYF(0)); + break; + } + if (xid_cache_search(thd->lex->xid)) + { + my_error(ER_XAER_DUPID, MYF(0)); + break; + } + DBUG_ASSERT(thd->transaction.xid_state.xid.is_null()); + thd->transaction.xid_state.xa_state=XA_ACTIVE; + thd->transaction.xid_state.rm_error= 0; + thd->transaction.xid_state.xid.set(thd->lex->xid); + xid_cache_insert(&thd->transaction.xid_state); + thd->transaction.all.modified_non_trans_table= FALSE; + thd->options= ((thd->options & ~(OPTION_KEEP_LOG)) | OPTION_BEGIN); + thd->server_status|= SERVER_STATUS_IN_TRANS; + my_ok(thd); + break; + case SQLCOM_XA_END: + /* fake it */ + if (thd->lex->xa_opt != XA_NONE) + { // SUSPEND and FOR MIGRATE are not supported yet. TODO + my_error(ER_XAER_INVAL, MYF(0)); + break; + } + if (thd->transaction.xid_state.xa_state != XA_ACTIVE) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + break; + } + if (!thd->transaction.xid_state.xid.eq(thd->lex->xid)) + { + my_error(ER_XAER_NOTA, MYF(0)); + break; + } + if (xa_trans_rolled_back(&thd->transaction.xid_state)) + break; + thd->transaction.xid_state.xa_state=XA_IDLE; + my_ok(thd); + break; + case SQLCOM_XA_PREPARE: + if (thd->transaction.xid_state.xa_state != XA_IDLE) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + break; + } + if (!thd->transaction.xid_state.xid.eq(thd->lex->xid)) + { + my_error(ER_XAER_NOTA, MYF(0)); + break; + } + if (ha_prepare(thd)) + { + my_error(ER_XA_RBROLLBACK, MYF(0)); + xid_cache_delete(&thd->transaction.xid_state); + thd->transaction.xid_state.xa_state=XA_NOTR; + break; + } + thd->transaction.xid_state.xa_state=XA_PREPARED; + my_ok(thd); + break; + case SQLCOM_XA_COMMIT: + if (!thd->transaction.xid_state.xid.eq(thd->lex->xid)) + { + XID_STATE *xs=xid_cache_search(thd->lex->xid); + if (!xs || xs->in_thd) + my_error(ER_XAER_NOTA, MYF(0)); + else if (xa_trans_rolled_back(xs)) + { + ha_commit_or_rollback_by_xid(thd->lex->xid, 0); + xid_cache_delete(xs); + break; + } + else + { + ha_commit_or_rollback_by_xid(thd->lex->xid, 1); + xid_cache_delete(xs); + my_ok(thd); + } + break; + } + if (xa_trans_rolled_back(&thd->transaction.xid_state)) + { + xa_trans_rollback(thd); + break; + } + if (thd->transaction.xid_state.xa_state == XA_IDLE && + thd->lex->xa_opt == XA_ONE_PHASE) + { + int r; + if ((r= ha_commit(thd))) + my_error(r == 1 ? ER_XA_RBROLLBACK : ER_XAER_RMERR, MYF(0)); + else + my_ok(thd); + } + else if (thd->transaction.xid_state.xa_state == XA_PREPARED && + thd->lex->xa_opt == XA_NONE) + { + if (wait_if_global_read_lock(thd, 0, 0)) + { + ha_rollback(thd); + my_error(ER_XAER_RMERR, MYF(0)); + } + else + { + if (ha_commit_one_phase(thd, 1)) + my_error(ER_XAER_RMERR, MYF(0)); + else + my_ok(thd); + start_waiting_global_read_lock(thd); + } + } + else + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + break; + } + thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG); + thd->transaction.all.modified_non_trans_table= FALSE; + thd->server_status&= ~SERVER_STATUS_IN_TRANS; + xid_cache_delete(&thd->transaction.xid_state); + thd->transaction.xid_state.xa_state=XA_NOTR; + break; + case SQLCOM_XA_ROLLBACK: + if (!thd->transaction.xid_state.xid.eq(thd->lex->xid)) + { + XID_STATE *xs=xid_cache_search(thd->lex->xid); + if (!xs || xs->in_thd) + my_error(ER_XAER_NOTA, MYF(0)); + else + { + bool ok= !xa_trans_rolled_back(xs); + ha_commit_or_rollback_by_xid(thd->lex->xid, 0); + xid_cache_delete(xs); + if (ok) + my_ok(thd); + } + break; + } + if (thd->transaction.xid_state.xa_state != XA_IDLE && + thd->transaction.xid_state.xa_state != XA_PREPARED && + thd->transaction.xid_state.xa_state != XA_ROLLBACK_ONLY) + { + my_error(ER_XAER_RMFAIL, MYF(0), + xa_state_names[thd->transaction.xid_state.xa_state]); + break; + } + if (xa_trans_rollback(thd)) + my_error(ER_XAER_RMERR, MYF(0)); + else + my_ok(thd); + break; + case SQLCOM_XA_RECOVER: + res= mysql_xa_recover(thd); + break; + case SQLCOM_ALTER_TABLESPACE: + if (check_access(thd, ALTER_ACL, thd->db, 0, 1, 0, thd->db ? is_schema_db(thd->db) : 0)) + break; + if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info))) + my_ok(thd); + break; + case SQLCOM_INSTALL_PLUGIN: + if (! (res= mysql_install_plugin(thd, &thd->lex->comment, + &thd->lex->ident))) + my_ok(thd); + break; + case SQLCOM_UNINSTALL_PLUGIN: + if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment))) + my_ok(thd); + break; + case SQLCOM_BINLOG_BASE64_EVENT: + { +#ifndef EMBEDDED_LIBRARY + mysql_client_binlog_statement(thd); +#else /* EMBEDDED_LIBRARY */ + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded"); +#endif /* EMBEDDED_LIBRARY */ + break; + } + case SQLCOM_CREATE_SERVER: + { + int error; + LEX *lex= thd->lex; + DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER")); + + if (check_global_access(thd, SUPER_ACL)) + break; + + if ((error= create_server(thd, &lex->server_options))) + { + DBUG_PRINT("info", ("problem creating server <%s>", + lex->server_options.server_name)); + my_error(error, MYF(0), lex->server_options.server_name); + break; + } + my_ok(thd, 1); + break; + } + case SQLCOM_ALTER_SERVER: + { + int error; + LEX *lex= thd->lex; + DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER")); + + if (check_global_access(thd, SUPER_ACL)) + break; + + if ((error= alter_server(thd, &lex->server_options))) + { + DBUG_PRINT("info", ("problem altering server <%s>", + lex->server_options.server_name)); + my_error(error, MYF(0), lex->server_options.server_name); + break; + } + my_ok(thd, 1); + break; + } + case SQLCOM_DROP_SERVER: + { + int err_code; + LEX *lex= thd->lex; + DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER")); + + if (check_global_access(thd, SUPER_ACL)) + break; + + if ((err_code= drop_server(thd, &lex->server_options))) + { + if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST) + { + DBUG_PRINT("info", ("problem dropping server %s", + lex->server_options.server_name)); + my_error(err_code, MYF(0), lex->server_options.server_name); + } + else + { + my_ok(thd, 0); + } + break; + } + my_ok(thd, 1); + break; + } + default: +#ifndef EMBEDDED_LIBRARY + DBUG_ASSERT(0); /* Impossible */ +#endif + my_ok(thd); + break; + } + thd_proc_info(thd, "query end"); + + /* + Binlog-related cleanup: + Reset system variables temporarily modified by SET ONE SHOT. + + Exception: If this is a SET, do nothing. This is to allow + mysqlbinlog to print many SET commands (in this case we want the + charset temp setting to live until the real query). This is also + needed so that SET CHARACTER_SET_CLIENT... does not cancel itself + immediately. + */ + if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION) + reset_one_shot_variables(thd); + + /* + The return value for ROW_COUNT() is "implementation dependent" if the + statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC + wants. We also keep the last value in case of SQLCOM_CALL or + SQLCOM_EXECUTE. + */ + if (!(sql_command_flags[lex->sql_command] & CF_HAS_ROW_COUNT)) + thd->row_count_func= -1; + + goto finish; + +error: + res= TRUE; + +finish: + if (need_start_waiting) + { + /* + Release the protection against the global read lock and wake + everyone, who might want to set a global read lock. + */ + start_waiting_global_read_lock(thd); + } + DBUG_RETURN(res || thd->is_error()); +} + + +static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables) +{ + LEX *lex= thd->lex; + select_result *result=lex->result; + bool res; + /* assign global limit variable if limit is not given */ + { + SELECT_LEX *param= lex->unit.global_parameters; + if (!param->explicit_limit) + param->select_limit= + new Item_int((ulonglong) thd->variables.select_limit); + } + if (!(res= open_and_lock_tables(thd, all_tables))) + { + if (lex->describe) + { + /* + We always use select_send for EXPLAIN, even if it's an EXPLAIN + for SELECT ... INTO OUTFILE: a user application should be able + to prepend EXPLAIN to any query and receive output for it, + even if the query itself redirects the output. + */ + if (!(result= new select_send())) + return 1; /* purecov: inspected */ + thd->send_explain_fields(result); + res= mysql_explain_union(thd, &thd->lex->unit, result); + if (lex->describe & DESCRIBE_EXTENDED) + { + char buff[1024]; + String str(buff,(uint32) sizeof(buff), system_charset_info); + str.length(0); + thd->lex->unit.print(&str, QT_ORDINARY); + str.append('\0'); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_YES, str.ptr()); + } + if (res) + result->abort(); + else + result->send_eof(); + delete result; + } + else + { + if (!result && !(result= new select_send())) + return 1; /* purecov: inspected */ + query_cache_store_query(thd, all_tables); + res= handle_select(thd, lex, result, 0); + if (result != lex->result) + delete result; + } + } + return res; +} + + +#ifndef NO_EMBEDDED_ACCESS_CHECKS +/** + Check grants for commands which work only with one table. + + @param thd Thread handler + @param privilege requested privilege + @param all_tables global table list of query + @param no_errors FALSE/TRUE - report/don't report error to + the client (using my_error() call). + + @retval + 0 OK + @retval + 1 access denied, error is sent to client +*/ + +bool check_single_table_access(THD *thd, ulong privilege, + TABLE_LIST *all_tables, bool no_errors) +{ + Security_context * backup_ctx= thd->security_ctx; + + /* we need to switch to the saved context (if any) */ + if (all_tables->security_ctx) + thd->security_ctx= all_tables->security_ctx; + + const char *db_name; + if ((all_tables->view || all_tables->field_translation) && + !all_tables->schema_table) + db_name= all_tables->view_db.str; + else + db_name= all_tables->db; + + if (check_access(thd, privilege, db_name, + &all_tables->grant.privilege, 0, no_errors, + test(all_tables->schema_table))) + goto deny; + + /* Show only 1 table for check_grant */ + if (!(all_tables->belong_to_view && + (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) && + !(all_tables->view && + all_tables->effective_algorithm == VIEW_ALGORITHM_TMPTABLE) && + check_grant(thd, privilege, all_tables, 0, 1, no_errors)) + goto deny; + + thd->security_ctx= backup_ctx; + return 0; + +deny: + thd->security_ctx= backup_ctx; + return 1; +} + +/** + Check grants for commands which work only with one table and all other + tables belonging to subselects or implicitly opened tables. + + @param thd Thread handler + @param privilege requested privilege + @param all_tables global table list of query + + @retval + 0 OK + @retval + 1 access denied, error is sent to client +*/ + +bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables) +{ + if (check_single_table_access (thd,privilege,all_tables, FALSE)) + return 1; + + /* Check rights on tables of subselects and implictly opened tables */ + TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0; + if ((subselects_tables= all_tables->next_global)) + { + /* + Access rights asked for the first table of a view should be the same + as for the view + */ + if (view && subselects_tables->belong_to_view == view) + { + if (check_single_table_access (thd, privilege, subselects_tables, FALSE)) + return 1; + subselects_tables= subselects_tables->next_global; + } + if (subselects_tables && + (check_table_access(thd, SELECT_ACL, subselects_tables, UINT_MAX, FALSE))) + return 1; + } + return 0; +} + + +/** + Get the user (global) and database privileges for all used tables. + + @param save_priv In this we store global and db level grants for the + table. Note that we don't store db level grants if the + global grants is enough to satisfy the request and the + global grants contains a SELECT grant. + + @note + The idea of EXTRA_ACL is that one will be granted access to the table if + one has the asked privilege on any column combination of the table; For + example to be able to check a table one needs to have SELECT privilege on + any column of the table. + + @retval + 0 ok + @retval + 1 If we can't get the privileges and we don't use table/column + grants. +*/ +bool +check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv, + bool dont_check_global_grants, bool no_errors, bool schema_db) +{ + Security_context *sctx= thd->security_ctx; + ulong db_access; + /* + GRANT command: + In case of database level grant the database name may be a pattern, + in case of table|column level grant the database name can not be a pattern. + We use 'dont_check_global_grants' as a flag to determine + if it's database level grant command + (see SQLCOM_GRANT case, mysql_execute_command() function) and + set db_is_pattern according to 'dont_check_global_grants' value. + */ + bool db_is_pattern= (test(want_access & GRANT_ACL) && + dont_check_global_grants); + ulong dummy; + DBUG_ENTER("check_access"); + DBUG_PRINT("enter",("db: %s want_access: %lu master_access: %lu", + db ? db : "", want_access, sctx->master_access)); + if (save_priv) + *save_priv=0; + else + save_priv= &dummy; + + thd_proc_info(thd, "checking permissions"); + if ((!db || !db[0]) && !thd->db && !dont_check_global_grants) + { + DBUG_PRINT("error",("No database")); + if (!no_errors) + my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), + MYF(0)); /* purecov: tested */ + DBUG_RETURN(TRUE); /* purecov: tested */ + } + + if (schema_db) + { + if ((!(sctx->master_access & FILE_ACL) && (want_access & FILE_ACL)) || + (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL))) + { + if (!no_errors) + { + const char *db_name= db ? db : thd->db; + my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), + sctx->priv_user, sctx->priv_host, db_name); + } + DBUG_RETURN(TRUE); + } + else + { + *save_priv= SELECT_ACL; + DBUG_RETURN(FALSE); + } + } + + if ((sctx->master_access & want_access) == want_access) + { + /* + If we don't have a global SELECT privilege, we have to get the database + specific access rights to be able to handle queries of type + UPDATE t1 SET a=1 WHERE b > 0 + */ + db_access= sctx->db_access; + if (!(sctx->master_access & SELECT_ACL) && + (db && (!thd->db || db_is_pattern || strcmp(db,thd->db)))) + db_access=acl_get(sctx->host, sctx->ip, sctx->priv_user, db, + db_is_pattern); + *save_priv=sctx->master_access | db_access; + DBUG_RETURN(FALSE); + } + if (((want_access & ~sctx->master_access) & ~(DB_ACLS | EXTRA_ACL)) || + (! db && dont_check_global_grants)) + { // We can never grant this + DBUG_PRINT("error",("No possible access")); + if (!no_errors) + my_error(ER_ACCESS_DENIED_ERROR, MYF(0), + sctx->priv_user, + sctx->priv_host, + (thd->password ? + ER(ER_YES) : + ER(ER_NO))); /* purecov: tested */ + DBUG_RETURN(TRUE); /* purecov: tested */ + } + + if (db == any_db) + DBUG_RETURN(FALSE); // Allow select on anything + + if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db))) + db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, + db_is_pattern); + else + db_access= sctx->db_access; + DBUG_PRINT("info",("db_access: %lu", db_access)); + /* Remove SHOW attribute and access rights we already have */ + want_access &= ~(sctx->master_access | EXTRA_ACL); + DBUG_PRINT("info",("db_access: %lu want_access: %lu", + db_access, want_access)); + db_access= ((*save_priv=(db_access | sctx->master_access)) & want_access); + + if (db_access == want_access || + (!dont_check_global_grants && + !(want_access & ~(db_access | TABLE_ACLS | PROC_ACLS)))) + DBUG_RETURN(FALSE); /* Ok */ + + DBUG_PRINT("error",("Access denied")); + if (!no_errors) + my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), + sctx->priv_user, sctx->priv_host, + (db ? db : (thd->db ? + thd->db : + "unknown"))); /* purecov: tested */ + DBUG_RETURN(TRUE); /* purecov: tested */ +} + + +static bool check_show_access(THD *thd, TABLE_LIST *table) +{ + switch (get_schema_table_idx(table->schema_table)) { + case SCH_SCHEMATA: + return (specialflag & SPECIAL_SKIP_SHOW_DB) && + check_global_access(thd, SHOW_DB_ACL); + + case SCH_TABLE_NAMES: + case SCH_TABLES: + case SCH_VIEWS: + case SCH_TRIGGERS: + case SCH_EVENTS: + { + const char *dst_db_name= table->schema_select_lex->db; + + DBUG_ASSERT(dst_db_name); + + if (check_access(thd, SELECT_ACL, dst_db_name, + &thd->col_access, FALSE, FALSE, + is_schema_db(dst_db_name))) + return TRUE; + + if (!thd->col_access && check_grant_db(thd, dst_db_name)) + { + my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), + thd->security_ctx->priv_user, + thd->security_ctx->priv_host, + dst_db_name); + return TRUE; + } + + return FALSE; + } + + case SCH_COLUMNS: + case SCH_STATISTICS: + { + TABLE_LIST *dst_table; + dst_table= (TABLE_LIST *) table->schema_select_lex->table_list.first; + + DBUG_ASSERT(dst_table); + + if (check_access(thd, SELECT_ACL | EXTRA_ACL, + dst_table->db, + &dst_table->grant.privilege, + FALSE, FALSE, + test(dst_table->schema_table))) + return FALSE; + + return (check_grant(thd, SELECT_ACL, dst_table, 2, UINT_MAX, FALSE)); + } + default: + break; + } + + return FALSE; +} + + +/** + Check the privilege for all used tables. + + @param thd Thread context + @param want_access Privileges requested + @param tables List of tables to be checked + @param number Check at most this number of tables. + @param no_errors FALSE/TRUE - report/don't report error to + the client (using my_error() call). + + @note + Table privileges are cached in the table list for GRANT checking. + This functions assumes that table list used and + thd->lex->query_tables_own_last value correspond to each other + (the latter should be either 0 or point to next_global member + of one of elements of this table list). + + @retval FALSE OK + @retval TRUE Access denied +*/ + +bool +check_table_access(THD *thd, ulong want_access,TABLE_LIST *tables, + uint number, bool no_errors) +{ + TABLE_LIST *org_tables= tables; + TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table(); + uint i= 0; + Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx; + /* + The check that first_not_own_table is not reached is for the case when + the given table list refers to the list for prelocking (contains tables + of other queries). For simple queries first_not_own_table is 0. + */ + for (; i < number && tables != first_not_own_table; + tables= tables->next_global, i++) + { + if (tables->security_ctx) + sctx= tables->security_ctx; + else + sctx= backup_ctx; + + if (tables->schema_table && + (want_access & ~(SELECT_ACL | EXTRA_ACL | FILE_ACL))) + { + if (!no_errors) + my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), + sctx->priv_user, sctx->priv_host, + INFORMATION_SCHEMA_NAME.str); + return TRUE; + } + /* + Register access for view underlying table. + Remove SHOW_VIEW_ACL, because it will be checked during making view + */ + tables->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL); + + if (tables->schema_table_reformed) + { + if (check_show_access(thd, tables)) + goto deny; + + continue; + } + + if (tables->is_anonymous_derived_table() || + (tables->table && (int)tables->table->s->tmp_table)) + continue; + thd->security_ctx= sctx; + if ((sctx->master_access & want_access) == + (want_access & ~EXTRA_ACL) && + thd->db) + tables->grant.privilege= want_access; + else if (tables->db && thd->db && strcmp(tables->db, thd->db) == 0) + { + if (check_access(thd, want_access, tables->get_db_name(), + &tables->grant.privilege, 0, no_errors, + test(tables->schema_table))) + goto deny; // Access denied + } + else if (check_access(thd, want_access, tables->get_db_name(), + &tables->grant.privilege, 0, no_errors, + test(tables->schema_table))) + goto deny; + } + thd->security_ctx= backup_ctx; + return check_grant(thd,want_access & ~EXTRA_ACL,org_tables, + test(want_access & EXTRA_ACL), number, no_errors); +deny: + thd->security_ctx= backup_ctx; + return TRUE; +} + + +bool +check_routine_access(THD *thd, ulong want_access,char *db, char *name, + bool is_proc, bool no_errors) +{ + TABLE_LIST tables[1]; + + bzero((char *)tables, sizeof(TABLE_LIST)); + tables->db= db; + tables->table_name= tables->alias= name; + + /* + The following test is just a shortcut for check_access() (to avoid + calculating db_access) under the assumption that it's common to + give persons global right to execute all stored SP (but not + necessary to create them). + */ + if ((thd->security_ctx->master_access & want_access) == want_access) + tables->grant.privilege= want_access; + else if (check_access(thd,want_access,db,&tables->grant.privilege, + 0, no_errors, 0)) + return TRUE; + + return check_grant_routine(thd, want_access, tables, is_proc, no_errors); +} + + +/** + Check if the routine has any of the routine privileges. + + @param thd Thread handler + @param db Database name + @param name Routine name + + @retval + 0 ok + @retval + 1 error +*/ + +bool check_some_routine_access(THD *thd, const char *db, const char *name, + bool is_proc) +{ + ulong save_priv; + if (thd->security_ctx->master_access & SHOW_PROC_ACLS) + return FALSE; + /* + There are no routines in information_schema db. So we can safely + pass zero to last paramter of check_access function + */ + if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, 0, 1, 0) || + (save_priv & SHOW_PROC_ACLS)) + return FALSE; + return check_routine_level_acl(thd, db, name, is_proc); +} + + +/* + Check if the given table has any of the asked privileges + + @param thd Thread handler + @param want_access Bitmap of possible privileges to check for + + @retval + 0 ok + @retval + 1 error +*/ + +bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table) +{ + ulong access; + DBUG_ENTER("check_some_access"); + + /* This loop will work as long as we have less than 32 privileges */ + for (access= 1; access < want_access ; access<<= 1) + { + if (access & want_access) + { + if (!check_access(thd, access, table->db, + &table->grant.privilege, 0, 1, + test(table->schema_table)) && + !check_grant(thd, access, table, 0, 1, 1)) + DBUG_RETURN(0); + } + } + DBUG_PRINT("exit",("no matching access rights")); + DBUG_RETURN(1); +} + +#endif /*NO_EMBEDDED_ACCESS_CHECKS*/ + + +/** + check for global access and give descriptive error message if it fails. + + @param thd Thread handler + @param want_access Use should have any of these global rights + + @warning + One gets access right if one has ANY of the rights in want_access. + This is useful as one in most cases only need one global right, + but in some case we want to check if the user has SUPER or + REPL_CLIENT_ACL rights. + + @retval + 0 ok + @retval + 1 Access denied. In this case an error is sent to the client +*/ + +bool check_global_access(THD *thd, ulong want_access) +{ +#ifndef NO_EMBEDDED_ACCESS_CHECKS + char command[128]; + if ((thd->security_ctx->master_access & want_access)) + return 0; + get_privilege_desc(command, sizeof(command), want_access); + my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command); + return 1; +#else + return 0; +#endif +} + +/**************************************************************************** + Check stack size; Send error if there isn't enough stack to continue +****************************************************************************/ + +#ifndef EMBEDDED_LIBRARY + +#if STACK_DIRECTION < 0 +#define used_stack(A,B) (long) (A - B) +#else +#define used_stack(A,B) (long) (B - A) +#endif + +#ifndef DBUG_OFF +long max_stack_used; +#endif + +/** + @note + Note: The 'buf' parameter is necessary, even if it is unused here. + - fix_fields functions has a "dummy" buffer large enough for the + corresponding exec. (Thus we only have to check in fix_fields.) + - Passing to check_stack_overrun() prevents the compiler from removing it. +*/ +bool check_stack_overrun(THD *thd, long margin, + uchar *buf __attribute__((unused))) +{ + long stack_used; + DBUG_ASSERT(thd == current_thd); + if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >= + (long) (my_thread_stack_size - margin)) + { + char ebuff[MYSQL_ERRMSG_SIZE]; + my_snprintf(ebuff, sizeof(ebuff), ER(ER_STACK_OVERRUN_NEED_MORE), + stack_used, my_thread_stack_size, margin); + my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR)); + thd->fatal_error(); + return 1; + } +#ifndef DBUG_OFF + max_stack_used= max(max_stack_used, stack_used); +#endif + return 0; +} +#endif /* EMBEDDED_LIBRARY */ + +#define MY_YACC_INIT 1000 // Start with big alloc +#define MY_YACC_MAX 32000 // Because of 'short' + +bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize) +{ + Yacc_state *state= & current_thd->m_parser_state->m_yacc; + ulong old_info=0; + DBUG_ASSERT(state); + if ((uint) *yystacksize >= MY_YACC_MAX) + return 1; + if (!state->yacc_yyvs) + old_info= *yystacksize; + *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX); + if (!(state->yacc_yyvs= (uchar*) + my_realloc(state->yacc_yyvs, + *yystacksize*sizeof(**yyvs), + MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) || + !(state->yacc_yyss= (uchar*) + my_realloc(state->yacc_yyss, + *yystacksize*sizeof(**yyss), + MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR)))) + return 1; + if (old_info) + { + /* + Only copy the old stack on the first call to my_yyoverflow(), + when replacing a static stack (YYINITDEPTH) by a dynamic stack. + For subsequent calls, my_realloc already did preserve the old stack. + */ + memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss)); + memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs)); + } + *yyss= (short*) state->yacc_yyss; + *yyvs= (YYSTYPE*) state->yacc_yyvs; + return 0; +} + + +/** + Reset THD part responsible for command processing state. + + This needs to be called before execution of every statement + (prepared or conventional). + It is not called by substatements of routines. + + @todo + Make it a method of THD and align its name with the rest of + reset/end/start/init methods. + @todo + Call it after we use THD for queries, not before. +*/ + +void mysql_reset_thd_for_next_command(THD *thd) +{ + DBUG_ENTER("mysql_reset_thd_for_next_command"); + DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */ + DBUG_ASSERT(! thd->in_sub_stmt); + thd->free_list= 0; + thd->select_number= 1; + /* + Those two lines below are theoretically unneeded as + THD::cleanup_after_query() should take care of this already. + */ + thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty(); + thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0; + + thd->query_start_used= 0; + thd->is_fatal_error= thd->time_zone_used= 0; + /* + Clear the status flag that are expected to be cleared at the + beginning of each SQL statement. + */ + thd->server_status&= ~SERVER_STATUS_CLEAR_SET; + /* + If in autocommit mode and not in a transaction, reset + OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings + in ha_rollback_trans() about some tables couldn't be rolled back. + */ + if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) + { + thd->options&= ~OPTION_KEEP_LOG; + thd->transaction.all.modified_non_trans_table= FALSE; + } + DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx); + thd->thread_specific_used= FALSE; + + if (opt_bin_log) + { + reset_dynamic(&thd->user_var_events); + thd->user_var_events_alloc= thd->mem_root; + } + thd->clear_error(); + thd->main_da.reset_diagnostics_area(); + thd->total_warn_count=0; // Warnings for this query + thd->rand_used= 0; + thd->sent_row_count= thd->examined_row_count= 0; + + /* + Because we come here only for start of top-statements, binlog format is + constant inside a complex statement (using stored functions) etc. + */ + thd->reset_current_stmt_binlog_row_based(); + + DBUG_PRINT("debug", + ("current_stmt_binlog_row_based: %d", + thd->current_stmt_binlog_row_based)); + + DBUG_VOID_RETURN; +} + + +/** + Resets the lex->current_select object. + @note It is assumed that lex->current_select != NULL + + This function is a wrapper around select_lex->init_select() with an added + check for the special situation when using INTO OUTFILE and LOAD DATA. +*/ + +void +mysql_init_select(LEX *lex) +{ + SELECT_LEX *select_lex= lex->current_select; + select_lex->init_select(); + lex->wild= 0; + if (select_lex == &lex->select_lex) + { + DBUG_ASSERT(lex->result == 0); + lex->exchange= 0; + } +} + + +/** + Used to allocate a new SELECT_LEX object on the current thd mem_root and + link it into the relevant lists. + + This function is always followed by mysql_init_select. + + @see mysql_init_select + + @retval TRUE An error occurred + @retval FALSE The new SELECT_LEX was successfully allocated. +*/ + +bool +mysql_new_select(LEX *lex, bool move_down) +{ + SELECT_LEX *select_lex; + THD *thd= lex->thd; + DBUG_ENTER("mysql_new_select"); + + if (!(select_lex= new (thd->mem_root) SELECT_LEX())) + DBUG_RETURN(1); + select_lex->select_number= ++thd->select_number; + select_lex->parent_lex= lex; /* Used in init_query. */ + select_lex->init_query(); + select_lex->init_select(); + lex->nest_level++; + if (lex->nest_level > (int) MAX_SELECT_NESTING) + { + my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING); + DBUG_RETURN(1); + } + select_lex->nest_level= lex->nest_level; + /* + Don't evaluate this subquery during statement prepare even if + it's a constant one. The flag is switched off in the end of + mysqld_stmt_prepare. + */ + if (thd->stmt_arena->is_stmt_prepare()) + select_lex->uncacheable|= UNCACHEABLE_PREPARE; + if (move_down) + { + SELECT_LEX_UNIT *unit; + lex->subqueries= TRUE; + /* first select_lex of subselect or derived table */ + if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT())) + DBUG_RETURN(1); + + unit->init_query(); + unit->init_select(); + unit->thd= thd; + unit->include_down(lex->current_select); + unit->link_next= 0; + unit->link_prev= 0; + unit->return_to= lex->current_select; + select_lex->include_down(unit); + /* + By default we assume that it is usual subselect and we have outer name + resolution context, if no we will assign it to 0 later + */ + select_lex->context.outer_context= &select_lex->outer_select()->context; + } + else + { + if (lex->current_select->order_list.first && !lex->current_select->braces) + { + my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY"); + DBUG_RETURN(1); + } + select_lex->include_neighbour(lex->current_select); + SELECT_LEX_UNIT *unit= select_lex->master_unit(); + if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd)) + DBUG_RETURN(1); + select_lex->context.outer_context= + unit->first_select()->context.outer_context; + } + + select_lex->master_unit()->global_parameters= select_lex; + select_lex->include_global((st_select_lex_node**)&lex->all_selects_list); + lex->current_select= select_lex; + /* + in subquery is SELECT query and we allow resolution of names in SELECT + list + */ + select_lex->context.resolve_in_select_list= TRUE; + DBUG_RETURN(0); +} + +/** + Create a select to return the same output as 'SELECT @@var_name'. + + Used for SHOW COUNT(*) [ WARNINGS | ERROR]. + + This will crash with a core dump if the variable doesn't exists. + + @param var_name Variable name +*/ + +void create_select_for_variable(const char *var_name) +{ + THD *thd; + LEX *lex; + LEX_STRING tmp, null_lex_string; + Item *var; + char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end; + DBUG_ENTER("create_select_for_variable"); + + thd= current_thd; + lex= thd->lex; + mysql_init_select(lex); + lex->sql_command= SQLCOM_SELECT; + tmp.str= (char*) var_name; + tmp.length=strlen(var_name); + bzero((char*) &null_lex_string.str, sizeof(null_lex_string)); + /* + We set the name of Item to @@session.var_name because that then is used + as the column name in the output. + */ + if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string))) + { + end= strxmov(buff, "@@session.", var_name, NullS); + var->set_name(buff, end-buff, system_charset_info); + add_item_to_list(thd, var); + } + DBUG_VOID_RETURN; +} + + +void mysql_init_multi_delete(LEX *lex) +{ + lex->sql_command= SQLCOM_DELETE_MULTI; + mysql_init_select(lex); + lex->select_lex.select_limit= 0; + lex->unit.select_limit_cnt= HA_POS_ERROR; + lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list); + lex->lock_option= TL_READ_DEFAULT; + lex->query_tables= 0; + lex->query_tables_last= &lex->query_tables; +} + + +/* + When you modify mysql_parse(), you may need to mofify + mysql_test_parse_for_slave() in this same file. +*/ + +/** + Parse a query. + + @param thd Current thread + @param inBuf Begining of the query text + @param length Length of the query text + @param[out] found_semicolon For multi queries, position of the character of + the next query in the query text. +*/ + +void mysql_parse(THD *thd, const char *inBuf, uint length, + const char ** found_semicolon) +{ + DBUG_ENTER("mysql_parse"); + + DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on();); + + /* + Warning. + The purpose of query_cache_send_result_to_client() is to lookup the + query in the query cache first, to avoid parsing and executing it. + So, the natural implementation would be to: + - first, call query_cache_send_result_to_client, + - second, if caching failed, initialise the lexical and syntactic parser. + The problem is that the query cache depends on a clean initialization + of (among others) lex->safe_to_cache_query and thd->server_status, + which are reset respectively in + - lex_start() + - mysql_reset_thd_for_next_command() + So, initializing the lexical analyser *before* using the query cache + is required for the cache to work properly. + FIXME: cleanup the dependencies in the code to simplify this. + */ + lex_start(thd); + mysql_reset_thd_for_next_command(thd); + + if (query_cache_send_result_to_client(thd, (char*) inBuf, length) <= 0) + { + LEX *lex= thd->lex; + + sp_cache_flush_obsolete(&thd->sp_proc_cache); + sp_cache_flush_obsolete(&thd->sp_func_cache); + + Parser_state parser_state(thd, inBuf, length); + + bool err= parse_sql(thd, & parser_state, NULL); + *found_semicolon= parser_state.m_lip.found_semicolon; + + if (!err) + { +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (mqh_used && thd->user_connect && + check_mqh(thd, lex->sql_command)) + { + thd->net.error = 0; + } + else +#endif + { + if (! thd->is_error()) + { + /* + Binlog logs a string starting from thd->query and having length + thd->query_length; so we set thd->query_length correctly (to not + log several statements in one event, when we executed only first). + We set it to not see the ';' (otherwise it would get into binlog + and Query_log_event::print() would give ';;' output). + This also helps display only the current query in SHOW + PROCESSLIST. + Note that we don't need LOCK_thread_count to modify query_length. + */ + if (*found_semicolon && + (thd->query_length= (ulong)(*found_semicolon - thd->query))) + thd->query_length--; + /* Actually execute the query */ + if (*found_semicolon) + { + lex->safe_to_cache_query= 0; + thd->server_status|= SERVER_MORE_RESULTS_EXISTS; + } + lex->set_trg_event_type_for_tables(); + mysql_execute_command(thd); + } + } + } + else + { + DBUG_ASSERT(thd->is_error()); + DBUG_PRINT("info",("Command aborted. Fatal_error: %d", + thd->is_fatal_error)); + + query_cache_abort(&thd->net); + } + if (thd->lex->sphead) + { + delete thd->lex->sphead; + thd->lex->sphead= 0; + } + lex->unit.cleanup(); + thd_proc_info(thd, "freeing items"); + thd->end_statement(); + thd->cleanup_after_query(); + DBUG_ASSERT(thd->change_list.is_empty()); + } + else + { + /* There are no multi queries in the cache. */ + *found_semicolon= NULL; + } + + DBUG_VOID_RETURN; +} + + +#ifdef HAVE_REPLICATION +/* + Usable by the replication SQL thread only: just parse a query to know if it + can be ignored because of replicate-*-table rules. + + @retval + 0 cannot be ignored + @retval + 1 can be ignored +*/ + +bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length) +{ + LEX *lex= thd->lex; + bool error= 0; + DBUG_ENTER("mysql_test_parse_for_slave"); + + Parser_state parser_state(thd, inBuf, length); + lex_start(thd); + mysql_reset_thd_for_next_command(thd); + + if (!parse_sql(thd, & parser_state, NULL) && + all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first)) + error= 1; /* Ignore question */ + thd->end_statement(); + thd->cleanup_after_query(); + DBUG_RETURN(error); +} +#endif + + + +/** + Store field definition for create. + + @return + Return 0 if ok +*/ + +bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type, + char *length, char *decimals, + uint type_modifier, + Item *default_value, Item *on_update_value, + LEX_STRING *comment, + char *change, + List *interval_list, CHARSET_INFO *cs, + uint uint_geom_type) +{ + register Create_field *new_field; + LEX *lex= thd->lex; + DBUG_ENTER("add_field_to_list"); + + if (check_string_char_length(field_name, "", NAME_CHAR_LEN, + system_charset_info, 1)) + { + my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */ + DBUG_RETURN(1); /* purecov: inspected */ + } + if (type_modifier & PRI_KEY_FLAG) + { + Key *key; + lex->col_list.push_back(new Key_part_spec(field_name->str, 0)); + key= new Key(Key::PRIMARY, NullS, + &default_key_create_info, + 0, lex->col_list); + lex->alter_info.key_list.push_back(key); + lex->col_list.empty(); + } + if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG)) + { + Key *key; + lex->col_list.push_back(new Key_part_spec(field_name->str, 0)); + key= new Key(Key::UNIQUE, NullS, + &default_key_create_info, 0, + lex->col_list); + lex->alter_info.key_list.push_back(key); + lex->col_list.empty(); + } + + if (default_value) + { + /* + Default value should be literal => basic constants => + no need fix_fields() + + We allow only one function as part of default value - + NOW() as default for TIMESTAMP type. + */ + if (default_value->type() == Item::FUNC_ITEM && + !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC && + type == MYSQL_TYPE_TIMESTAMP)) + { + my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str); + DBUG_RETURN(1); + } + else if (default_value->type() == Item::NULL_ITEM) + { + default_value= 0; + if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == + NOT_NULL_FLAG) + { + my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str); + DBUG_RETURN(1); + } + } + else if (type_modifier & AUTO_INCREMENT_FLAG) + { + my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str); + DBUG_RETURN(1); + } + } + + if (on_update_value && type != MYSQL_TYPE_TIMESTAMP) + { + my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str); + DBUG_RETURN(1); + } + + if (type == MYSQL_TYPE_TIMESTAMP && length) + { + /* Display widths are no longer supported for TIMSTAMP as of MySQL 4.1. + In other words, for declarations such as TIMESTAMP(2), TIMESTAMP(4), + and so on, the display width is ignored. + */ + char buf[32]; + my_snprintf(buf, sizeof(buf), "TIMESTAMP(%s)", length); + WARN_DEPRECATED(thd, "6.0", buf, "'TIMESTAMP'"); + } + + if (!(new_field= new Create_field()) || + new_field->init(thd, field_name->str, type, length, decimals, type_modifier, + default_value, on_update_value, comment, change, + interval_list, cs, uint_geom_type)) + DBUG_RETURN(1); + + lex->alter_info.create_list.push_back(new_field); + lex->last_field=new_field; + DBUG_RETURN(0); +} + + +/** Store position for column in ALTER TABLE .. ADD column. */ + +void store_position_for_column(const char *name) +{ + current_thd->lex->last_field->after=my_const_cast(char*) (name); +} + +bool +add_proc_to_list(THD* thd, Item *item) +{ + ORDER *order; + Item **item_ptr; + + if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*)))) + return 1; + item_ptr = (Item**) (order+1); + *item_ptr= item; + order->item=item_ptr; + order->free_me=0; + thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next); + return 0; +} + + +/** + save order by and tables in own lists. +*/ + +bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc) +{ + ORDER *order; + DBUG_ENTER("add_to_list"); + if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)))) + DBUG_RETURN(1); + order->item_ptr= item; + order->item= &order->item_ptr; + order->asc = asc; + order->free_me=0; + order->used=0; + order->counter_used= 0; + list.link_in_list((uchar*) order,(uchar**) &order->next); + DBUG_RETURN(0); +} + + +/** + Add a table to list of used tables. + + @param table Table to add + @param alias alias for table (or null if no alias) + @param table_options A set of the following bits: + - TL_OPTION_UPDATING : Table will be updated + - TL_OPTION_FORCE_INDEX : Force usage of index + - TL_OPTION_ALIAS : an alias in multi table DELETE + @param lock_type How table should be locked + @param use_index List of indexed used in USE INDEX + @param ignore_index List of indexed used in IGNORE INDEX + + @retval + 0 Error + @retval + \# Pointer to TABLE_LIST element added to the total table list +*/ + +TABLE_LIST *st_select_lex::add_table_to_list(THD *thd, + Table_ident *table, + LEX_STRING *alias, + ulong table_options, + thr_lock_type lock_type, + List *index_hints_arg, + LEX_STRING *option) +{ + register TABLE_LIST *ptr; + TABLE_LIST *previous_table_ref; /* The table preceding the current one. */ + char *alias_str; + LEX *lex= thd->lex; + DBUG_ENTER("add_table_to_list"); + LINT_INIT(previous_table_ref); + + if (!table) + DBUG_RETURN(0); // End of memory + alias_str= alias ? alias->str : table->table.str; + if (!test(table_options & TL_OPTION_ALIAS) && + check_table_name(table->table.str, table->table.length)) + { + my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str); + DBUG_RETURN(0); + } + + if (table->is_derived_table() == FALSE && table->db.str && + check_db_name(&table->db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str); + DBUG_RETURN(0); + } + + if (!alias) /* Alias is case sensitive */ + { + if (table->sel) + { + my_message(ER_DERIVED_MUST_HAVE_ALIAS, + ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0)); + DBUG_RETURN(0); + } + if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1))) + DBUG_RETURN(0); + } + if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST)))) + DBUG_RETURN(0); /* purecov: inspected */ + if (table->db.str) + { + ptr->db= table->db.str; + ptr->db_length= table->db.length; + } + else if (lex->copy_db_to(&ptr->db, &ptr->db_length)) + DBUG_RETURN(0); + + ptr->alias= alias_str; + if (lower_case_table_names && table->table.length) + table->table.length= my_casedn_str(files_charset_info, table->table.str); + ptr->table_name=table->table.str; + ptr->table_name_length=table->table.length; + ptr->lock_type= lock_type; + ptr->updating= test(table_options & TL_OPTION_UPDATING); + ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX); + ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES); + ptr->derived= table->sel; + if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db, + INFORMATION_SCHEMA_NAME.str)) + { + ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name); + if (!schema_table || + (schema_table->hidden && + ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || + /* + this check is used for show columns|keys from I_S hidden table + */ + lex->sql_command == SQLCOM_SHOW_FIELDS || + lex->sql_command == SQLCOM_SHOW_KEYS))) + { + my_error(ER_UNKNOWN_TABLE, MYF(0), + ptr->table_name, INFORMATION_SCHEMA_NAME.str); + DBUG_RETURN(0); + } + ptr->schema_table_name= ptr->table_name; + ptr->schema_table= schema_table; + } + ptr->select_lex= lex->current_select; + ptr->cacheable_table= 1; + ptr->index_hints= index_hints_arg; + ptr->option= option ? option->str : 0; + /* check that used name is unique */ + if (lock_type != TL_IGNORE) + { + TABLE_LIST *first_table= (TABLE_LIST*) table_list.first; + if (lex->sql_command == SQLCOM_CREATE_VIEW) + first_table= first_table ? first_table->next_local : NULL; + for (TABLE_LIST *tables= first_table ; + tables ; + tables=tables->next_local) + { + if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) && + !strcmp(ptr->db, tables->db)) + { + my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */ + DBUG_RETURN(0); /* purecov: tested */ + } + } + } + /* Store the table reference preceding the current one. */ + if (table_list.elements > 0) + { + /* + table_list.next points to the last inserted TABLE_LIST->next_local' + element + We don't use the offsetof() macro here to avoid warnings from gcc + */ + previous_table_ref= (TABLE_LIST*) ((char*) table_list.next - + ((char*) &(ptr->next_local) - + (char*) ptr)); + /* + Set next_name_resolution_table of the previous table reference to point + to the current table reference. In effect the list + TABLE_LIST::next_name_resolution_table coincides with + TABLE_LIST::next_local. Later this may be changed in + store_top_level_join_columns() for NATURAL/USING joins. + */ + previous_table_ref->next_name_resolution_table= ptr; + } + + /* + Link the current table reference in a local list (list for current select). + Notice that as a side effect here we set the next_local field of the + previous table reference to 'ptr'. Here we also add one element to the + list 'table_list'. + */ + table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local); + ptr->next_name_resolution_table= NULL; + /* Link table in global list (all used tables) */ + lex->add_to_query_tables(ptr); + DBUG_RETURN(ptr); +} + + +/** + Initialize a new table list for a nested join. + + The function initializes a structure of the TABLE_LIST type + for a nested join. It sets up its nested join list as empty. + The created structure is added to the front of the current + join list in the st_select_lex object. Then the function + changes the current nest level for joins to refer to the newly + created empty list after having saved the info on the old level + in the initialized structure. + + @param thd current thread + + @retval + 0 if success + @retval + 1 otherwise +*/ + +bool st_select_lex::init_nested_join(THD *thd) +{ + TABLE_LIST *ptr; + NESTED_JOIN *nested_join; + DBUG_ENTER("init_nested_join"); + + if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+ + sizeof(NESTED_JOIN)))) + DBUG_RETURN(1); + nested_join= ptr->nested_join= + ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST)))); + + join_list->push_front(ptr); + ptr->embedding= embedding; + ptr->join_list= join_list; + ptr->alias= (char*) "(nested_join)"; + embedding= ptr; + join_list= &nested_join->join_list; + join_list->empty(); + DBUG_RETURN(0); +} + + +/** + End a nested join table list. + + The function returns to the previous join nest level. + If the current level contains only one member, the function + moves it one level up, eliminating the nest. + + @param thd current thread + + @return + - Pointer to TABLE_LIST element added to the total table list, if success + - 0, otherwise +*/ + +TABLE_LIST *st_select_lex::end_nested_join(THD *thd) +{ + TABLE_LIST *ptr; + NESTED_JOIN *nested_join; + DBUG_ENTER("end_nested_join"); + + DBUG_ASSERT(embedding); + ptr= embedding; + join_list= ptr->join_list; + embedding= ptr->embedding; + nested_join= ptr->nested_join; + if (nested_join->join_list.elements == 1) + { + TABLE_LIST *embedded= nested_join->join_list.head(); + join_list->pop(); + embedded->join_list= join_list; + embedded->embedding= embedding; + join_list->push_front(embedded); + ptr= embedded; + } + else if (nested_join->join_list.elements == 0) + { + join_list->pop(); + ptr= 0; // return value + } + DBUG_RETURN(ptr); +} + + +/** + Nest last join operation. + + The function nest last join operation as if it was enclosed in braces. + + @param thd current thread + + @retval + 0 Error + @retval + \# Pointer to TABLE_LIST element created for the new nested join +*/ + +TABLE_LIST *st_select_lex::nest_last_join(THD *thd) +{ + TABLE_LIST *ptr; + NESTED_JOIN *nested_join; + List *embedded_list; + DBUG_ENTER("nest_last_join"); + + if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+ + sizeof(NESTED_JOIN)))) + DBUG_RETURN(0); + nested_join= ptr->nested_join= + ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST)))); + + ptr->embedding= embedding; + ptr->join_list= join_list; + ptr->alias= (char*) "(nest_last_join)"; + embedded_list= &nested_join->join_list; + embedded_list->empty(); + + for (uint i=0; i < 2; i++) + { + TABLE_LIST *table= join_list->pop(); + table->join_list= embedded_list; + table->embedding= ptr; + embedded_list->push_back(table); + if (table->natural_join) + { + ptr->is_natural_join= TRUE; + /* + If this is a JOIN ... USING, move the list of joined fields to the + table reference that describes the join. + */ + if (prev_join_using) + ptr->join_using_fields= prev_join_using; + } + } + join_list->push_front(ptr); + nested_join->used_tables= nested_join->not_null_tables= (table_map) 0; + DBUG_RETURN(ptr); +} + + +/** + Add a table to the current join list. + + The function puts a table in front of the current join list + of st_select_lex object. + Thus, joined tables are put into this list in the reverse order + (the most outer join operation follows first). + + @param table the table to add + + @return + None +*/ + +void st_select_lex::add_joined_table(TABLE_LIST *table) +{ + DBUG_ENTER("add_joined_table"); + join_list->push_front(table); + table->join_list= join_list; + table->embedding= embedding; + DBUG_VOID_RETURN; +} + + +/** + Convert a right join into equivalent left join. + + The function takes the current join list t[0],t[1] ... and + effectively converts it into the list t[1],t[0] ... + Although the outer_join flag for the new nested table contains + JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join + operation. + + EXAMPLES + @verbatim + SELECT * FROM t1 RIGHT JOIN t2 ON on_expr => + SELECT * FROM t2 LEFT JOIN t1 ON on_expr + + SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr => + SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr + + SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr => + SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr + + SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3 ON on_expr2 => + SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1 + @endverbatim + + @param thd current thread + + @return + - Pointer to the table representing the inner table, if success + - 0, otherwise +*/ + +TABLE_LIST *st_select_lex::convert_right_join() +{ + TABLE_LIST *tab2= join_list->pop(); + TABLE_LIST *tab1= join_list->pop(); + DBUG_ENTER("convert_right_join"); + + join_list->push_front(tab2); + join_list->push_front(tab1); + tab1->outer_join|= JOIN_TYPE_RIGHT; + + DBUG_RETURN(tab1); +} + +/** + Set lock for all tables in current select level. + + @param lock_type Lock to set for tables + + @note + If lock is a write lock, then tables->updating is set 1 + This is to get tables_ok to know that the table is updated by the + query +*/ + +void st_select_lex::set_lock_for_tables(thr_lock_type lock_type) +{ + bool for_update= lock_type >= TL_READ_NO_INSERT; + DBUG_ENTER("set_lock_for_tables"); + DBUG_PRINT("enter", ("lock_type: %d for_update: %d", lock_type, + for_update)); + for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first; + tables; + tables= tables->next_local) + { + tables->lock_type= lock_type; + tables->updating= for_update; + } + DBUG_VOID_RETURN; +} + + +/** + Create a fake SELECT_LEX for a unit. + + The method create a fake SELECT_LEX object for a unit. + This object is created for any union construct containing a union + operation and also for any single select union construct of the form + @verbatim + (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... + @endvarbatim + or of the form + @varbatim + (SELECT ... ORDER BY LIMIT n) ORDER BY ... + @endvarbatim + + @param thd_arg thread handle + + @note + The object is used to retrieve rows from the temporary table + where the result on the union is obtained. + + @retval + 1 on failure to create the object + @retval + 0 on success +*/ + +bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg) +{ + SELECT_LEX *first_sl= first_select(); + DBUG_ENTER("add_fake_select_lex"); + DBUG_ASSERT(!fake_select_lex); + + if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX())) + DBUG_RETURN(1); + fake_select_lex->include_standalone(this, + (SELECT_LEX_NODE**)&fake_select_lex); + fake_select_lex->select_number= INT_MAX; + fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */ + fake_select_lex->make_empty_select(); + fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE; + fake_select_lex->select_limit= 0; + + fake_select_lex->context.outer_context=first_sl->context.outer_context; + /* allow item list resolving in fake select for ORDER BY */ + fake_select_lex->context.resolve_in_select_list= TRUE; + fake_select_lex->context.select_lex= fake_select_lex; + + if (!is_union()) + { + /* + This works only for + (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m], + (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m] + just before the parser starts processing order_list + */ + global_parameters= fake_select_lex; + fake_select_lex->no_table_names_allowed= 1; + thd_arg->lex->current_select= fake_select_lex; + } + thd_arg->lex->pop_context(); + DBUG_RETURN(0); +} + + +/** + Push a new name resolution context for a JOIN ... ON clause to the + context stack of a query block. + + Create a new name resolution context for a JOIN ... ON clause, + set the first and last leaves of the list of table references + to be used for name resolution, and push the newly created + context to the stack of contexts of the query. + + @param thd pointer to current thread + @param left_op left operand of the JOIN + @param right_op rigth operand of the JOIN + + @retval + FALSE if all is OK + @retval + TRUE if a memory allocation error occured +*/ + +bool +push_new_name_resolution_context(THD *thd, + TABLE_LIST *left_op, TABLE_LIST *right_op) +{ + Name_resolution_context *on_context; + if (!(on_context= new (thd->mem_root) Name_resolution_context)) + return TRUE; + on_context->init(); + on_context->first_name_resolution_table= + left_op->first_leaf_for_name_resolution(); + on_context->last_name_resolution_table= + right_op->last_leaf_for_name_resolution(); + return thd->lex->push_context(on_context); +} + + +/** + Add an ON condition to the second operand of a JOIN ... ON. + + Add an ON condition to the right operand of a JOIN ... ON clause. + + @param b the second operand of a JOIN ... ON + @param expr the condition to be added to the ON clause + + @retval + FALSE if there was some error + @retval + TRUE if all is OK +*/ + +void add_join_on(TABLE_LIST *b, Item *expr) +{ + if (expr) + { + if (!b->on_expr) + b->on_expr= expr; + else + { + /* + If called from the parser, this happens if you have both a + right and left join. If called later, it happens if we add more + than one condition to the ON clause. + */ + b->on_expr= new Item_cond_and(b->on_expr,expr); + } + b->on_expr->top_level_item(); + } +} + + +/** + Mark that there is a NATURAL JOIN or JOIN ... USING between two + tables. + + This function marks that table b should be joined with a either via + a NATURAL JOIN or via JOIN ... USING. Both join types are special + cases of each other, so we treat them together. The function + setup_conds() creates a list of equal condition between all fields + of the same name for NATURAL JOIN or the fields in 'using_fields' + for JOIN ... USING. The list of equality conditions is stored + either in b->on_expr, or in JOIN::conds, depending on whether there + was an outer join. + + EXAMPLE + @verbatim + SELECT * FROM t1 NATURAL LEFT JOIN t2 + <=> + SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... ) + + SELECT * FROM t1 NATURAL JOIN t2 WHERE + <=> + SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and ) + + SELECT * FROM t1 JOIN t2 USING(j) WHERE + <=> + SELECT * FROM t1, t2 WHERE (t1.j=t2.j and ) + @endverbatim + + @param a Left join argument + @param b Right join argument + @param using_fields Field names from USING clause +*/ + +void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List *using_fields, + SELECT_LEX *lex) +{ + b->natural_join= a; + lex->prev_join_using= using_fields; +} + + +/** + Reload/resets privileges and the different caches. + + @param thd Thread handler (can be NULL!) + @param options What should be reset/reloaded (tables, privileges, slave...) + @param tables Tables to flush (if any) + @param write_to_binlog True if we can write to the binlog. + + @note Depending on 'options', it may be very bad to write the + query to the binlog (e.g. FLUSH SLAVE); this is a + pointer where reload_acl_and_cache() will put 0 if + it thinks we really should not write to the binlog. + Otherwise it will put 1. + + @return Error status code + @retval 0 Ok + @retval !=0 Error; thd->killed is set or thd->is_error() is true +*/ + +bool reload_acl_and_cache(THD *thd, ulong options, TABLE_LIST *tables, + bool *write_to_binlog) +{ + bool result=0; + select_errors=0; /* Write if more errors */ + bool tmp_write_to_binlog= 1; + + DBUG_ASSERT(!thd || !thd->in_sub_stmt); + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (options & REFRESH_GRANT) + { + THD *tmp_thd= 0; + /* + If reload_acl_and_cache() is called from SIGHUP handler we have to + allocate temporary THD for execution of acl_reload()/grant_reload(). + */ + if (!thd && (thd= (tmp_thd= new THD))) + { + thd->thread_stack= (char*) &tmp_thd; + thd->store_globals(); + lex_start(thd); + } + + if (thd) + { + bool reload_acl_failed= acl_reload(thd); + bool reload_grants_failed= grant_reload(thd); + bool reload_servers_failed= servers_reload(thd); + + if (reload_acl_failed || reload_grants_failed || reload_servers_failed) + { + result= 1; + /* + When an error is returned, my_message may have not been called and + the client will hang waiting for a response. + */ + my_error(ER_UNKNOWN_ERROR, MYF(0), "FLUSH PRIVILEGES failed"); + } + } + + if (tmp_thd) + { + delete tmp_thd; + /* Remember that we don't have a THD */ + my_pthread_setspecific_ptr(THR_THD, 0); + thd= 0; + } + reset_mqh((LEX_USER *)NULL, TRUE); + } +#endif + if (options & REFRESH_LOG) + { + /* + Flush the normal query log, the update log, the binary log, + the slow query log, the relay log (if it exists) and the log + tables. + */ + + /* + Writing this command to the binlog may result in infinite loops + when doing mysqlbinlog|mysql, and anyway it does not really make + sense to log it automatically (would cause more trouble to users + than it would help them) + */ + tmp_write_to_binlog= 0; + if( mysql_bin_log.is_open() ) + { + mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE); + } +#ifdef HAVE_REPLICATION + pthread_mutex_lock(&LOCK_active_mi); + rotate_relay_log(active_mi); + pthread_mutex_unlock(&LOCK_active_mi); +#endif + + /* flush slow and general logs */ + logger.flush_logs(thd); + + if (ha_flush_logs(NULL)) + result=1; + if (flush_error_log()) + result=1; + } +#ifdef HAVE_QUERY_CACHE + if (options & REFRESH_QUERY_CACHE_FREE) + { + query_cache.pack(); // FLUSH QUERY CACHE + options &= ~REFRESH_QUERY_CACHE; // Don't flush cache, just free memory + } + if (options & (REFRESH_TABLES | REFRESH_QUERY_CACHE)) + { + query_cache.flush(); // RESET QUERY CACHE + } +#endif /*HAVE_QUERY_CACHE*/ + /* + Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too + (see sql_yacc.yy) + */ + if (options & (REFRESH_TABLES | REFRESH_READ_LOCK)) + { + if ((options & REFRESH_READ_LOCK) && thd) + { + /* + We must not try to aspire a global read lock if we have a write + locked table. This would lead to a deadlock when trying to + reopen (and re-lock) the table after the flush. + */ + if (thd->locked_tables) + { + THR_LOCK_DATA **lock_p= thd->locked_tables->locks; + THR_LOCK_DATA **end_p= lock_p + thd->locked_tables->lock_count; + + for (; lock_p < end_p; lock_p++) + { + if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE) + { + my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0)); + return 1; + } + } + } + /* + Writing to the binlog could cause deadlocks, as we don't log + UNLOCK TABLES + */ + tmp_write_to_binlog= 0; + if (lock_global_read_lock(thd)) + return 1; // Killed + if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ? + FALSE : TRUE, TRUE)) + result= 1; + + if (make_global_read_lock_block_commit(thd)) // Killed + { + /* Don't leave things in a half-locked state */ + unlock_global_read_lock(thd); + return 1; + } + } + else + { + if (close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ? + FALSE : TRUE, FALSE)) + result= 1; + } + my_dbopt_cleanup(); + } + if (options & REFRESH_HOSTS) + hostname_cache_refresh(); + if (thd && (options & REFRESH_STATUS)) + refresh_status(thd); + if (options & REFRESH_THREADS) + flush_thread_cache(); +#ifdef HAVE_REPLICATION + if (options & REFRESH_MASTER) + { + DBUG_ASSERT(thd); + tmp_write_to_binlog= 0; + if (reset_master(thd)) + { + result=1; + } + } +#endif +#ifdef OPENSSL + if (options & REFRESH_DES_KEY_FILE) + { + if (des_key_file && load_des_key_file(des_key_file)) + result= 1; + } +#endif +#ifdef HAVE_REPLICATION + if (options & REFRESH_SLAVE) + { + tmp_write_to_binlog= 0; + pthread_mutex_lock(&LOCK_active_mi); + if (reset_slave(thd, active_mi)) + result=1; + pthread_mutex_unlock(&LOCK_active_mi); + } +#endif + if (options & REFRESH_USER_RESOURCES) + reset_mqh((LEX_USER *) NULL, 0); /* purecov: inspected */ + *write_to_binlog= tmp_write_to_binlog; + return result; +} + + +/** + kill on thread. + + @param thd Thread class + @param id Thread id + @param only_kill_query Should it kill the query or the connection + + @note + This is written such that we have a short lock on LOCK_thread_count +*/ + +uint kill_one_thread(THD *thd, ulong id, bool only_kill_query) +{ + THD *tmp; + uint error=ER_NO_SUCH_THREAD; + DBUG_ENTER("kill_one_thread"); + DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query)); + VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list + I_List_iterator it(threads); + while ((tmp=it++)) + { + if (tmp->command == COM_DAEMON) + continue; + if (tmp->thread_id == id) + { + pthread_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete + break; + } + } + VOID(pthread_mutex_unlock(&LOCK_thread_count)); + if (tmp) + { + + /* + If we're SUPER, we can KILL anything, including system-threads. + No further checks. + + KILLer: thd->security_ctx->user could in theory be NULL while + we're still in "unauthenticated" state. This is a theoretical + case (the code suggests this could happen, so we play it safe). + + KILLee: tmp->security_ctx->user will be NULL for system threads. + We need to check so Jane Random User doesn't crash the server + when trying to kill a) system threads or b) unauthenticated users' + threads (Bug#43748). + + If user of both killer and killee are non-NULL, proceed with + slayage if both are string-equal. + */ + + if ((thd->security_ctx->master_access & SUPER_ACL) || + thd->security_ctx->user_matches(tmp->security_ctx)) + { + tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION); + error=0; + } + else + error=ER_KILL_DENIED_ERROR; + pthread_mutex_unlock(&tmp->LOCK_thd_data); + } + DBUG_PRINT("exit", ("%d", error)); + DBUG_RETURN(error); +} + + +/* + kills a thread and sends response + + SYNOPSIS + sql_kill() + thd Thread class + id Thread id + only_kill_query Should it kill the query or the connection +*/ + +void sql_kill(THD *thd, ulong id, bool only_kill_query) +{ + uint error; + if (!(error= kill_one_thread(thd, id, only_kill_query))) + my_ok(thd); + else + my_error(error, MYF(0), id); +} + + +/** If pointer is not a null pointer, append filename to it. */ + +bool append_file_to_dir(THD *thd, const char **filename_ptr, + const char *table_name) +{ + char buff[FN_REFLEN],*ptr, *end; + if (!*filename_ptr) + return 0; // nothing to do + + /* Check that the filename is not too long and it's a hard path */ + if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 || + !test_if_hard_path(*filename_ptr)) + { + my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr); + return 1; + } + /* Fix is using unix filename format on dos */ + strmov(buff,*filename_ptr); + end=convert_dirname(buff, *filename_ptr, NullS); + if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1))) + return 1; // End of memory + *filename_ptr=ptr; + strxmov(ptr,buff,table_name,NullS); + return 0; +} + + +/** + Check if the select is a simple select (not an union). + + @retval + 0 ok + @retval + 1 error ; In this case the error messege is sent to the client +*/ + +bool check_simple_select() +{ + THD *thd= current_thd; + LEX *lex= thd->lex; + if (lex->current_select != &lex->select_lex) + { + char command[80]; + Lex_input_stream *lip= & thd->m_parser_state->m_lip; + strmake(command, lip->yylval->symbol.str, + min(lip->yylval->symbol.length, sizeof(command)-1)); + my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command); + return 1; + } + return 0; +} + + +Comp_creator *comp_eq_creator(bool invert) +{ + return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator; +} + + +Comp_creator *comp_ge_creator(bool invert) +{ + return invert?(Comp_creator *)<_creator:(Comp_creator *)&ge_creator; +} + + +Comp_creator *comp_gt_creator(bool invert) +{ + return invert?(Comp_creator *)&le_creator:(Comp_creator *)>_creator; +} + + +Comp_creator *comp_le_creator(bool invert) +{ + return invert?(Comp_creator *)>_creator:(Comp_creator *)&le_creator; +} + + +Comp_creator *comp_lt_creator(bool invert) +{ + return invert?(Comp_creator *)&ge_creator:(Comp_creator *)<_creator; +} + + +Comp_creator *comp_ne_creator(bool invert) +{ + return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator; +} + + +/** + Construct ALL/ANY/SOME subquery Item. + + @param left_expr pointer to left expression + @param cmp compare function creator + @param all true if we create ALL subquery + @param select_lex pointer on parsed subquery structure + + @return + constructed Item (or 0 if out of memory) +*/ +Item * all_any_subquery_creator(Item *left_expr, + chooser_compare_func_creator cmp, + bool all, + SELECT_LEX *select_lex) +{ + if ((cmp == &comp_eq_creator) && !all) // = ANY <=> IN + return new Item_in_subselect(left_expr, select_lex); + + if ((cmp == &comp_ne_creator) && all) // <> ALL <=> NOT IN + return new Item_func_not(new Item_in_subselect(left_expr, select_lex)); + + Item_allany_subselect *it= + new Item_allany_subselect(left_expr, cmp, select_lex, all); + if (all) + return it->upper_item= new Item_func_not_all(it); /* ALL */ + + return it->upper_item= new Item_func_nop_all(it); /* ANY/SOME */ +} + + +/** + Multi update query pre-check. + + @param thd Thread handler + @param tables Global/local table list (have to be the same) + + @retval + FALSE OK + @retval + TRUE Error +*/ + +bool multi_update_precheck(THD *thd, TABLE_LIST *tables) +{ + const char *msg= 0; + TABLE_LIST *table; + LEX *lex= thd->lex; + SELECT_LEX *select_lex= &lex->select_lex; + DBUG_ENTER("multi_update_precheck"); + + if (select_lex->item_list.elements != lex->value_list.elements) + { + my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0)); + DBUG_RETURN(TRUE); + } + /* + Ensure that we have UPDATE or SELECT privilege for each table + The exact privilege is checked in mysql_multi_update() + */ + for (table= tables; table; table= table->next_local) + { + if (table->derived) + table->grant.privilege= SELECT_ACL; + else if ((check_access(thd, UPDATE_ACL, table->db, + &table->grant.privilege, 0, 1, + test(table->schema_table)) || + check_grant(thd, UPDATE_ACL, table, 0, 1, 1)) && + (check_access(thd, SELECT_ACL, table->db, + &table->grant.privilege, 0, 0, + test(table->schema_table)) || + check_grant(thd, SELECT_ACL, table, 0, 1, 0))) + DBUG_RETURN(TRUE); + + table->table_in_first_from_clause= 1; + } + /* + Is there tables of subqueries? + */ + if (&lex->select_lex != lex->all_selects_list) + { + DBUG_PRINT("info",("Checking sub query list")); + for (table= tables; table; table= table->next_global) + { + if (!table->table_in_first_from_clause) + { + if (check_access(thd, SELECT_ACL, table->db, + &table->grant.privilege, 0, 0, + test(table->schema_table)) || + check_grant(thd, SELECT_ACL, table, 0, 1, 0)) + DBUG_RETURN(TRUE); + } + } + } + + if (select_lex->order_list.elements) + msg= "ORDER BY"; + else if (select_lex->select_limit) + msg= "LIMIT"; + if (msg) + { + my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + +/** + Multi delete query pre-check. + + @param thd Thread handler + @param tables Global/local table list + + @retval + FALSE OK + @retval + TRUE error +*/ + +bool multi_delete_precheck(THD *thd, TABLE_LIST *tables) +{ + SELECT_LEX *select_lex= &thd->lex->select_lex; + TABLE_LIST *aux_tables= + (TABLE_LIST *)thd->lex->auxiliary_table_list.first; + TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last; + DBUG_ENTER("multi_delete_precheck"); + + /* sql_yacc guarantees that tables and aux_tables are not zero */ + DBUG_ASSERT(aux_tables != 0); + if (check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE)) + DBUG_RETURN(TRUE); + + /* + Since aux_tables list is not part of LEX::query_tables list we + have to juggle with LEX::query_tables_own_last value to be able + call check_table_access() safely. + */ + thd->lex->query_tables_own_last= 0; + if (check_table_access(thd, DELETE_ACL, aux_tables, UINT_MAX, FALSE)) + { + thd->lex->query_tables_own_last= save_query_tables_own_last; + DBUG_RETURN(TRUE); + } + thd->lex->query_tables_own_last= save_query_tables_own_last; + + if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where) + { + my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE, + ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0)); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + + +/** + Link tables in auxilary table list of multi-delete with corresponding + elements in main table list, and set proper locks for them. + + @param lex pointer to LEX representing multi-delete + + @retval + FALSE success + @retval + TRUE error +*/ + +bool multi_delete_set_locks_and_link_aux_tables(LEX *lex) +{ + TABLE_LIST *tables= (TABLE_LIST*)lex->select_lex.table_list.first; + TABLE_LIST *target_tbl; + DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables"); + + lex->table_count= 0; + + for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first; + target_tbl; target_tbl= target_tbl->next_local) + { + lex->table_count++; + /* All tables in aux_tables must be found in FROM PART */ + TABLE_LIST *walk; + for (walk= tables; walk; walk= walk->next_local) + { + if (!my_strcasecmp(table_alias_charset, + target_tbl->alias, walk->alias) && + !strcmp(walk->db, target_tbl->db)) + break; + } + if (!walk) + { + my_error(ER_UNKNOWN_TABLE, MYF(0), + target_tbl->table_name, "MULTI DELETE"); + DBUG_RETURN(TRUE); + } + if (!walk->derived) + { + target_tbl->table_name= walk->table_name; + target_tbl->table_name_length= walk->table_name_length; + } + walk->updating= target_tbl->updating; + walk->lock_type= target_tbl->lock_type; + target_tbl->correspondent_table= walk; // Remember corresponding table + } + DBUG_RETURN(FALSE); +} + + +/** + simple UPDATE query pre-check. + + @param thd Thread handler + @param tables Global table list + + @retval + FALSE OK + @retval + TRUE Error +*/ + +bool update_precheck(THD *thd, TABLE_LIST *tables) +{ + DBUG_ENTER("update_precheck"); + if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements) + { + my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0)); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables)); +} + + +/** + simple DELETE query pre-check. + + @param thd Thread handler + @param tables Global table list + + @retval + FALSE OK + @retval + TRUE error +*/ + +bool delete_precheck(THD *thd, TABLE_LIST *tables) +{ + DBUG_ENTER("delete_precheck"); + if (check_one_table_access(thd, DELETE_ACL, tables)) + DBUG_RETURN(TRUE); + /* Set privilege for the WHERE clause */ + tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege); + DBUG_RETURN(FALSE); +} + + +/** + simple INSERT query pre-check. + + @param thd Thread handler + @param tables Global table list + + @retval + FALSE OK + @retval + TRUE error +*/ + +bool insert_precheck(THD *thd, TABLE_LIST *tables) +{ + LEX *lex= thd->lex; + DBUG_ENTER("insert_precheck"); + + /* + Check that we have modify privileges for the first table and + select privileges for the rest + */ + ulong privilege= (INSERT_ACL | + (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) | + (lex->value_list.elements ? UPDATE_ACL : 0)); + + if (check_one_table_access(thd, privilege, tables)) + DBUG_RETURN(TRUE); + + if (lex->update_list.elements != lex->value_list.elements) + { + my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0)); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + + +/** + @brief Check privileges for SHOW CREATE TABLE statement. + + @param thd Thread context + @param table Target table + + @retval TRUE Failure + @retval FALSE Success +*/ + +static bool check_show_create_table_access(THD *thd, TABLE_LIST *table) +{ + return check_access(thd, SELECT_ACL | EXTRA_ACL, table->db, + &table->grant.privilege, 0, 0, + test(table->schema_table)) || + check_grant(thd, SELECT_ACL, table, 2, UINT_MAX, 0); +} + + +/** + CREATE TABLE query pre-check. + + @param thd Thread handler + @param tables Global table list + @param create_table Table which will be created + + @retval + FALSE OK + @retval + TRUE Error +*/ + +bool create_table_precheck(THD *thd, TABLE_LIST *tables, + TABLE_LIST *create_table) +{ + LEX *lex= thd->lex; + SELECT_LEX *select_lex= &lex->select_lex; + ulong want_priv; + bool error= TRUE; // Error message is given + DBUG_ENTER("create_table_precheck"); + + /* + Require CREATE [TEMPORARY] privilege on new table; for + CREATE TABLE ... SELECT, also require INSERT. + */ + + want_priv= ((lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) ? + CREATE_TMP_ACL : CREATE_ACL) | + (select_lex->item_list.elements ? INSERT_ACL : 0); + + if (check_access(thd, want_priv, create_table->db, + &create_table->grant.privilege, 0, 0, + test(create_table->schema_table)) || + check_merge_table_access(thd, create_table->db, + (TABLE_LIST *) + lex->create_info.merge_list.first)) + goto err; + if (want_priv != CREATE_TMP_ACL && + check_grant(thd, want_priv, create_table, 0, 1, 0)) + goto err; + + if (select_lex->item_list.elements) + { + /* Check permissions for used tables in CREATE TABLE ... SELECT */ + +#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT + /* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */ + /* + Only do the check for PS, because we on execute we have to check that + against the opened tables to ensure we don't use a table that is part + of the view (which can only be done after the table has been opened). + */ + if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute()) + { + /* + For temporary tables we don't have to check if the created table exists + */ + if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) && + find_table_in_global_list(tables, create_table->db, + create_table->table_name)) + { + error= FALSE; + goto err; + } + } +#endif + if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE)) + goto err; + } + else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE) + { + if (check_show_create_table_access(thd, tables)) + goto err; + } + error= FALSE; + +err: + DBUG_RETURN(error); +} + + +/** + negate given expression. + + @param thd thread handler + @param expr expression for negation + + @return + negated expression +*/ + +Item *negate_expression(THD *thd, Item *expr) +{ + Item *negated; + if (expr->type() == Item::FUNC_ITEM && + ((Item_func *) expr)->functype() == Item_func::NOT_FUNC) + { + /* it is NOT(NOT( ... )) */ + Item *arg= ((Item_func *) expr)->arguments()[0]; + enum_parsing_place place= thd->lex->current_select->parsing_place; + if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING) + return arg; + /* + if it is not boolean function then we have to emulate value of + not(not(a)), it will be a != 0 + */ + return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1)); + } + + if ((negated= expr->neg_transformer(thd)) != 0) + return negated; + return new Item_func_not(expr); +} + +/** + Set the specified definer to the default value, which is the + current user in the thread. + + @param[in] thd thread handler + @param[out] definer definer +*/ + +void get_default_definer(THD *thd, LEX_USER *definer) +{ + const Security_context *sctx= thd->security_ctx; + + definer->user.str= (char *) sctx->priv_user; + definer->user.length= strlen(definer->user.str); + + definer->host.str= (char *) sctx->priv_host; + definer->host.length= strlen(definer->host.str); +} + + +/** + Create default definer for the specified THD. + + @param[in] thd thread handler + + @return + - On success, return a valid pointer to the created and initialized + LEX_USER, which contains definer information. + - On error, return 0. +*/ + +LEX_USER *create_default_definer(THD *thd) +{ + LEX_USER *definer; + + if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))) + return 0; + + get_default_definer(thd, definer); + + return definer; +} + + +/** + Create definer with the given user and host names. + + @param[in] thd thread handler + @param[in] user_name user name + @param[in] host_name host name + + @return + - On success, return a valid pointer to the created and initialized + LEX_USER, which contains definer information. + - On error, return 0. +*/ + +LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name) +{ + LEX_USER *definer; + + /* Create and initialize. */ + + if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))) + return 0; + + definer->user= *user_name; + definer->host= *host_name; + + return definer; +} + + +/** + Retuns information about user or current user. + + @param[in] thd thread handler + @param[in] user user + + @return + - On success, return a valid pointer to initialized + LEX_USER, which contains user information. + - On error, return 0. +*/ + +LEX_USER *get_current_user(THD *thd, LEX_USER *user) +{ + if (!user->user.str) // current_user + return create_default_definer(thd); + + return user; +} + + +/** + Check that byte length of a string does not exceed some limit. + + @param str string to be checked + @param err_msg error message to be displayed if the string is too long + @param max_length max length + + @retval + FALSE the passed string is not longer than max_length + @retval + TRUE the passed string is longer than max_length + + NOTE + The function is not used in existing code but can be useful later? +*/ + +bool check_string_byte_length(LEX_STRING *str, const char *err_msg, + uint max_byte_length) +{ + if (str->length <= max_byte_length) + return FALSE; + + my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length); + + return TRUE; +} + + +/* + Check that char length of a string does not exceed some limit. + + SYNOPSIS + check_string_char_length() + str string to be checked + err_msg error message to be displayed if the string is too long + max_char_length max length in symbols + cs string charset + + RETURN + FALSE the passed string is not longer than max_char_length + TRUE the passed string is longer than max_char_length +*/ + + +bool check_string_char_length(LEX_STRING *str, const char *err_msg, + uint max_char_length, CHARSET_INFO *cs, + bool no_error) +{ + int well_formed_error; + uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length, + max_char_length, &well_formed_error); + + if (!well_formed_error && str->length == res) + return FALSE; + + if (!no_error) + my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length); + return TRUE; +} + + +/* + Check if path does not contain mysql data home directory + SYNOPSIS + test_if_data_home_dir() + dir directory + conv_home_dir converted data home directory + home_dir_len converted data home directory length + + RETURN VALUES + 0 ok + 1 error +*/ +C_MODE_START + +int test_if_data_home_dir(const char *dir) +{ + char path[FN_REFLEN]; + int dir_len; + DBUG_ENTER("test_if_data_home_dir"); + + if (!dir) + DBUG_RETURN(0); + + (void) fn_format(path, dir, "", "", + (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS)); + dir_len= strlen(path); + if (mysql_unpacked_real_data_home_len<= dir_len) + { + if (dir_len > mysql_unpacked_real_data_home_len && + path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR) + DBUG_RETURN(0); + + if (lower_case_file_system) + { + if (!my_strnncoll(default_charset_info, (const uchar*) path, + mysql_unpacked_real_data_home_len, + (const uchar*) mysql_unpacked_real_data_home, + mysql_unpacked_real_data_home_len)) + DBUG_RETURN(1); + } + else if (!memcmp(path, mysql_unpacked_real_data_home, + mysql_unpacked_real_data_home_len)) + DBUG_RETURN(1); + } + DBUG_RETURN(0); +} + +C_MODE_END + + +/** + Check that host name string is valid. + + @param[in] str string to be checked + + @return Operation status + @retval FALSE host name is ok + @retval TRUE host name string is longer than max_length or + has invalid symbols +*/ + +bool check_host_name(LEX_STRING *str) +{ + const char *name= str->str; + const char *end= str->str + str->length; + if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH)) + return TRUE; + + while (name != end) + { + if (*name == '@') + { + my_printf_error(ER_UNKNOWN_ERROR, + "Malformed hostname (illegal symbol: '%c')", MYF(0), + *name); + return TRUE; + } + name++; + } + return FALSE; +} + + +extern int MYSQLparse(void *thd); // from sql_yacc.cc + + +/** + This is a wrapper of MYSQLparse(). All the code should call parse_sql() + instead of MYSQLparse(). + + @param thd Thread context. + @param parser_state Parser state. + @param creation_ctx Object creation context. + + @return Error status. + @retval FALSE on success. + @retval TRUE on parsing error. +*/ + +bool parse_sql(THD *thd, + Parser_state *parser_state, + Object_creation_ctx *creation_ctx) +{ + DBUG_ASSERT(thd->m_parser_state == NULL); + + /* Backup creation context. */ + + Object_creation_ctx *backup_ctx= NULL; + + if (creation_ctx) + backup_ctx= creation_ctx->set_n_backup(thd); + + /* Set parser state. */ + + thd->m_parser_state= parser_state; + + /* Parse the query. */ + + bool mysql_parse_status= MYSQLparse(thd) != 0; + + /* Check that if MYSQLparse() failed, thd->is_error() is set. */ + + DBUG_ASSERT(!mysql_parse_status || + (mysql_parse_status && thd->is_error())); + + /* Reset parser state. */ + + thd->m_parser_state= NULL; + + /* Restore creation context. */ + + if (creation_ctx) + creation_ctx->restore_env(thd, backup_ctx); + + /* That's it. */ + + return mysql_parse_status || thd->is_fatal_error; +} + +/** + @} (end of group Runtime_Environment) +*/ + +/** + * InfiniDB Vtable Processing + */ + +// for vtable parsing use. String in quotes is converted +static void idb_to_lower(char* str) +{ + bool inquote = false; + char quote = 0; + uint length = strlen(str); + for (uint i = 0; i < length; i++) + { + if (str[i] == '`' || str[i] == '\'' || str[i] == '"') + { + // @bug3935. more careful to '"' cases. + if (inquote && quote == str[i]) + { + inquote = false; + } + else if (!inquote) + { + inquote = true; + quote = str[i]; + } + continue; + } + if (inquote) + str[i] = toupper(str[i]); + else + str[i] = tolower(str[i]); + } +} + +static std::string idb_cleanQuery(char* str) +{ + bool inquote = false; + std::string temp; + char quote = 0; + uint length = strlen(str); + for (uint i = 0; i < length; i++) + { + temp.append(1, str[i]); + // @bug3935. + if (str[i] == '`' || str[i] == '\'' || str[i] == '"') + { + if (inquote && quote == str[i]) + { + inquote = false; + } + else if (!inquote) + { + inquote = true; + quote = str[i]; + } + continue; + } + if (!inquote) + { + if (str[i] == '\t' || str[i] == '\n') + temp.replace(temp.length()-1, 1, 1, ' '); + //else if (str[i] == '(') + // temp.append(1, ' '); + } + } + return temp; +} + +/* InfiniDB */ +int idb_vtable_process(THD* thd, Statement* statement) +{ + const char* end_of_stmt= NULL; + + // @bug 2042. check global variable to determin vtable mode + if (thd->variables.infinidb_vtable_mode == 0) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + thd->infinidb_vtable.autoswitch = false; + } + else if (thd->variables.infinidb_vtable_mode == 2) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_INIT; + thd->infinidb_vtable.autoswitch = true; + } + else + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_INIT; + thd->infinidb_vtable.autoswitch = false; + } + + // @bug 3014. Infinidb does not support lock tables. So if the tables are locked, + // they must be myisam tables. Change vtable to disable_vtable to make it through. + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE || thd->locked_tables) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + } + else + { + // @bug 1685. pre-parse mysql to know the command type exactly instead of parsing the text. + lex_start(thd); + mysql_reset_thd_for_next_command(thd); + if (query_cache_send_result_to_client(thd, thd->query, thd->query_length) <= 0) + { + LEX *lex= thd->lex; + sp_cache_flush_obsolete(&thd->sp_proc_cache); + sp_cache_flush_obsolete(&thd->sp_func_cache); + Parser_state parser_state(thd, thd->query, thd->query_length); + bool err= parse_sql(thd, &parser_state, NULL); + } + + if (thd->query && + (! thd->db || strcmp(thd->db, "information_schema") != 0) && + // @bug 3089 + std::string(thd->query).find("@@version_comment") == std::string::npos) + { + thd->infinidb_vtable.isInsertSelect = false; + + // SELECT vtable processing + if (thd->lex->sql_command == SQLCOM_SELECT || + thd->lex->sql_command == SQLCOM_EXECUTE || + thd->lex->sql_command == SQLCOM_CALL || + thd->lex->sql_command == SQLCOM_INSERT_SELECT || + thd->command == COM_STMT_EXECUTE) + { + // select into variable + std::string sel_into, lower_case_sel_into, limit; + std::string create_query, insert_query; + std::string insert_dest_tb, on_duplicate/*, insert_low_priority*/; + + // bug 2134. Support for PREPARE-EXECUTE statement. + sp_head* sp = NULL; + bool INFINIDB_execute = true; + bool isSqlExecute = false; //This flag is used to tell prepared statement from stored procedure + bool isExplain = false; + std::string lower_case_query; + + // to replace all the non-quoted tab and \n with space. For text processing use. + std::string query = idb_cleanQuery(thd->query); + alloc_query(thd, query.c_str(), query.length()); + + /* + 1. sql_command == sqlcom_insert_select + 2. check the first table on list to get the table name + 3. take out the select statement + 4. process the select stmt in vtable mode. + 5. add "insert into" to the select phase statement + */ + if (thd->lex->sql_command == SQLCOM_INSERT_SELECT) + { + thd->infinidb_vtable.isInsertSelect = true; + } + else if (thd->lex->sql_command == SQLCOM_EXECUTE || thd->command == COM_STMT_EXECUTE) + { + //@Bug 2703 Added the support of prepared statement with and without variables binding + //Save the query in case we need set it back + char *query = thd->query; + uint32 query_length = thd->query_length; + Prepared_statement *stmt = (Prepared_statement*)statement; + LEX *lex= thd->lex; + String expanded_query ; + + if (!stmt) + { + //Bind variable and parse statement + LEX_STRING *name= &lex->prepared_stmt_name; + stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name); + } + + if ( stmt ) + { + if ( stmt->param_count == lex->prepared_stmt_params.elements ) + { + bool result_code = stmt->set_parameters(&expanded_query, NULL, NULL); + } + // replace ? with values + std::string tmp_query = std::string (stmt->query); + std::string::size_type p1 = tmp_query.find("?"); + std::string replaceStr; + Item_param **begin= stmt->param_array; + Item_param **end= begin + stmt->param_count; + while (p1 != std::string::npos) + { + Item_param *param= *begin; + if (param->state == Item_param::NO_VALUE) + { + replaceStr = "NULL"; + } + else + { + String val, *str; + str = param->val_str(&val); + if ( param->item_type == Item::STRING_ITEM ) + replaceStr = "'" + std::string(str->c_ptr()) + "'"; + else + replaceStr = std::string(str->c_ptr()); + } + + tmp_query.replace( p1, 1, replaceStr); + begin++; + p1 = tmp_query.find("?"); + } + alloc_query(thd, tmp_query.c_str(), tmp_query.length()); + + // pre parse statement to tell DML statement from select + lex_start(thd); + mysql_reset_thd_for_next_command(thd); + + Parser_state parser_state(thd, thd->query, thd->query_length); + bool err= parse_sql(thd, &parser_state, NULL); + + if (thd->lex->sql_command != SQLCOM_SELECT) + { + INFINIDB_execute = false; + if ( thd->lex->sql_command != SQLCOM_DELETE ) + { + // set original query back + thd->query= query; + thd->query_length= query_length; + } + //Set to table mode for DML statement + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + thd->infinidb_vtable.autoswitch = false; + isSqlExecute = true; + } + } + else + { + return -1; + } + } + else if (thd->lex->sql_command == SQLCOM_CALL) + { + thd->infinidb_vtable.original_query.free(); + thd->infinidb_vtable.original_query.append(thd->query, thd->query_length); + if (check_table_access(thd, SELECT_ACL, thd->lex->query_tables, UINT_MAX, FALSE) || open_and_lock_tables(thd, thd->lex->query_tables)) + { + // error out -- vtable mode = 1 + if (thd->killed != THD::KILL_QUERY) + thd->killed = THD::KILL_QUERY; + } + sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, thd->lex->spname, + &thd->sp_proc_cache, TRUE); + + if (!sp || sp->sp_elements() != 1) + { + INFINIDB_execute = false; + } + + // only handle SP with one select statement + while (INFINIDB_execute) + { + char *query = thd->query; + uint32 query_length = thd->query_length; + uint ip = 0; + List *args = &thd->lex->value_list; + sp_instr *i; + i = sp->get_instr(ip); + sp_instr_stmt *sel_query = (sp_instr_stmt*)i; + + // not sure if this will catch every invalid ptr. MySQL leaves some ptrs unintiallized + if (sel_query->m_query.str == 0) + { + INFINIDB_execute = false; + break; + } + + std::string tmp_query = std::string (sel_query->m_query.str); + #ifdef SAFE_MUTEX + printf("query: %s length: %d\n", tmp_query.c_str(), tmp_query.length()); + #endif + if (args->elements > 0) + { + List_iterator it_args(*args); + for (uint i= 0 ; i < args->elements ; i++) + { + Item *arg_item= it_args++; + if (!arg_item) + break; + + sp_variable_t *spvar= sp->context()->find_variable(i); + if (!spvar) + continue; + + if (spvar->mode != sp_param_in) + continue; + + std::string arg_name = spvar->name.str; + std::string arg_val = arg_item->name; + uint len = spvar->name.length; + if (arg_item->type() == Item::STRING_ITEM) + arg_val = "'" + arg_val + "'"; + + // replace arg_name in the query with arg_val + std::string::size_type p1 = tmp_query.find(arg_name); + while (p1 != std::string::npos) + { + // prelimnary check for found arg_name string. Make sure it's not part of an identifier + if ((tmp_query.c_str()[p1-1] >= 'a' && tmp_query.c_str()[p1-1] <= 'z' || + tmp_query.c_str()[p1-1] >= 'A' && tmp_query.c_str()[p1-1] <= 'Z') || + (tmp_query.c_str()[p1+len] >= 'a' && tmp_query.c_str()[p1+len] <= 'z' || + tmp_query.c_str()[p1+len] >= 'A' && tmp_query.c_str()[p1+len] <= 'Z')) + { + printf ("debug: %c\n", tmp_query.c_str()[p1-1]); + printf ("debug: %c\n", tmp_query.c_str()[p1+1]); + p1 = tmp_query.find(arg_name, p1+1); + continue; + } + tmp_query.replace(p1, spvar->name.length, arg_val); + p1 = tmp_query.find(arg_name, p1); + } + } + } + alloc_query(thd, tmp_query.c_str(), tmp_query.length()); + + // pre parse statement. is this step necessary? + lex_start(thd); + mysql_reset_thd_for_next_command(thd); + if (query_cache_send_result_to_client(thd, thd->query, thd->query_length) <= 0) + { + LEX *lex= thd->lex; + sp_cache_flush_obsolete(&thd->sp_proc_cache); + sp_cache_flush_obsolete(&thd->sp_func_cache); + Parser_state parser_state(thd, thd->query, thd->query_length); + bool err= parse_sql(thd, &parser_state, NULL); + } + + if (thd->lex->sql_command != SQLCOM_SELECT /*&& thd->lex->sql_command != SQLCOM_END*/) + { + INFINIDB_execute = false; + // set original query back + thd->query= query; + thd->query_length= query_length; + break; + } + break; + } + } + + if (!INFINIDB_execute) + { + thd->infinidb_vtable.call_sp = true; + if ( isSqlExecute ) + { + thd->infinidb_vtable.call_sp = false; + } + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->infinidb_vtable.call_sp = false; + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ERROR) + { + if (thd->infinidb_vtable.autoswitch) + { + // auto switch -- vtablemode = 2. rerun the original query + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + alloc_query(thd, thd->infinidb_vtable.original_query.c_ptr(), thd->infinidb_vtable.original_query.length()); + #ifdef SAFE_MUTEX + printf("<<< V-TABLE unsupported components encountered. Auto switch to table mode\n"); + #endif + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_INIT; + } + else + { + // error out -- vtable mode = 1 + if (thd->killed != THD::KILL_QUERY) + thd->killed = THD::KILL_QUERY; + } + } + } + else // normal INFINIDB_execute + { + + //@todo clean up the query and normalize space, tab, carriage return, etc. + if (thd->query) + { + lower_case_query = thd->query; + char* query = new char[thd->query_length+1]; + memcpy(query, thd->query, thd->query_length); + query[thd->query_length] = 0; + idb_to_lower(query); + lower_case_query = query; + delete [] query; + } + + // See if this is an explain ... + isExplain = (lower_case_query.find("explain ", 0) == 0); + create_query = thd->query; + std::string::size_type p1 = lower_case_query.find(" into"); + std::string::size_type p2 = lower_case_query.find(" from"); + if (thd->lex->sql_command == SQLCOM_SELECT && p1 != std::string::npos) + { + if (p2 > p1) + { + sel_into = std::string(thd->query).substr(p1, p2-p1); + lower_case_sel_into = std::string(lower_case_query).substr(p1, p2-p1); + create_query.replace(p1, p2-p1, " "); + } + else + { + sel_into = std::string(thd->query).substr(p1, strlen(thd->query)-p1); + lower_case_sel_into = std::string(lower_case_query).substr(p1, strlen(thd->query)-p1); + create_query.replace(p1, strlen(thd->query)-p1, " "); + } + } + + // infinidb bug 3409. pre-check the outfile access + p1 = lower_case_sel_into.find("outfile"); + std::string::size_type p3; + if (p1 != std::string::npos) + { + p2 = lower_case_sel_into.find("'", p1); + if (p2 == std::string::npos) + { + p2 = lower_case_sel_into.find("\"", p1); + p3 = lower_case_sel_into.find("\"", p2+1); + } + else + { + p3 = lower_case_sel_into.find("'", p2+1); + } + + //File file; + std::string fileName = sel_into.substr(p2+1, p3-p2-1); + std::string d_path; + char path[FN_REFLEN]; + uint option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH; + + #ifdef DONT_ALLOW_FULL_LOAD_DATA_PATHS + option|= MY_REPLACE_DIR; // Force use of db directory + #endif + + if (!dirname_length(fileName.c_str())) + { + strxnmov(path, FN_REFLEN-1, mysql_real_data_home, thd->db ? thd->db : "", + NullS); + } + + (void) fn_format(path, fileName.c_str(), mysql_real_data_home, "", option); + // get the directory path + d_path = path; +#ifndef _MSC_VER + p1 = d_path.find_last_of("/"); +#else + p1 = d_path.find_last_of("\\"); +#endif + d_path = d_path.substr(0, p1); + + if (opt_secure_file_priv && + strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv))) + { + /* Write only allowed to dir or subdir specified by secure_file_priv */ + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv"); + thd->lex->result = 0; + return 0; + } + + // @bug 3601. check directory first. +#ifdef _MSC_VER + if (d_path.empty()) d_path = "\\"; + if (_access(d_path.c_str(), 06) == 0) + { + // check file exists + if (!_access(path, 00)) +#else + if (access(d_path.c_str(), W_OK | X_OK) == 0 && errno == EINVAL) + { + // check file exists + if (!access(path, F_OK)) +#endif + { + my_error(ER_FILE_EXISTS_ERROR, MYF(0), fileName.c_str()); + thd->lex->result = 0; + return 0; + } + } + else + { + my_error(ER_CANT_CREATE_FILE, MYF(0), fileName.c_str()); + thd->lex->result = 0; + return 0; + } + } + + // vtable name + std::ostringstream oss; + oss << "infinidb_vtable.$vtable_" << thd->thread_id; + std::string vtable_name = oss.str(); + + // clear state + thd->infinidb_vtable.has_order_by = false; + thd->infinidb_vtable.original_query.free(); + thd->infinidb_vtable.original_query.append(thd->query, thd->query_length); + + // phase 1. create vtable + std::string create; + + // insert with select + if (thd->infinidb_vtable.isInsertSelect) + { + // on duplicate key + p1 = lower_case_query.find(" on duplicate key update"); + if (p1 != std::string::npos) + { + printf("on duplicate: %d/%d\n", (uint)p1, (uint)(create_query.length()-p1)); + on_duplicate = create_query.substr(p1, create_query.length()-p1); + create_query.replace(p1, create_query.length()-p1, " "); + printf("create_query: %s", create_query.c_str()); + } + + p1 = lower_case_query.find(" select ", 0); + if (p1 == std::string::npos) + { + p1 = lower_case_query.find("(select", 0); + if (p1 == std::string::npos) + { + p1 = lower_case_query.find(" select(", 0); + if (p1 == std::string::npos) + return -1; + } + } + insert_query = create_query.substr(0, p1); + create_query = create_query.substr(p1, create_query.length() - p1); + } + create = "create temporary table " + vtable_name + " as " + create_query; + thd->infinidb_vtable.create_vtable_query.free(); + thd->infinidb_vtable.create_vtable_query.append(create.c_str(), create.length()); + + // phase 2. alter vtable to IDB type + thd->infinidb_vtable.alter_vtable_query.free(); + thd->infinidb_vtable.alter_vtable_query.append(STRING_WITH_LEN("alter table ")); + thd->infinidb_vtable.alter_vtable_query.append(vtable_name.c_str(), vtable_name.length()); + thd->infinidb_vtable.alter_vtable_query.append(STRING_WITH_LEN(" engine=infinidb comment='SCHEMA SYNC ONLY'")); + + // phase 3. select vtable + std::string select; + select = "select * " + sel_into + " from " + vtable_name; + thd->infinidb_vtable.select_vtable_query.free(); + thd->infinidb_vtable.select_vtable_query.append(select.c_str(), select.length()); + + // phase 4. drop vtable + thd->infinidb_vtable.drop_vtable_query.free(); + thd->infinidb_vtable.drop_vtable_query.append(STRING_WITH_LEN("drop table ")); + thd->infinidb_vtable.drop_vtable_query.append(vtable_name.c_str(), vtable_name.length()); + thd->infinidb_vtable.drop_vtable_query.append(STRING_WITH_LEN(" restrict")); + + alloc_query(thd, thd->infinidb_vtable.drop_vtable_query.c_ptr(), thd->infinidb_vtable.drop_vtable_query.length()); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DROP_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->lex->result = 0; + thd->infinidb_vtable.vtable_state = THD::INFINIDB_INIT; + thd->infinidb_vtable.duplicate_field_name = false; + thd->infinidb_vtable.isUnion = false; + thd->infinidb_vtable.mysql_optimizer_off = false; + thd->infinidb_vtable.impossibleWhereOnUnion = false; + + // Execution starts + // Phase 1. + alloc_query(thd, thd->infinidb_vtable.create_vtable_query.c_ptr(), thd->infinidb_vtable.create_vtable_query.length()); +#ifdef SAFE_MUTEX + printf("<<< V-TABLE Phase 1: %s\n", thd->query); +#endif + thd->infinidb_vtable.vtable_state = THD::INFINIDB_CREATE_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + close_thread_tables(thd); + + // check MySQL parse error here + if (thd->main_da.is_error()) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; + } + else if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_PHASE1) + { + // redo phase 1; + while (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_PHASE1) + { + alloc_query(thd, thd->infinidb_vtable.drop_vtable_query.c_ptr(), thd->infinidb_vtable.drop_vtable_query.length()); + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + + // If the execution plan failed InfiniDB, turn off the optimizer constant re-write + // and let the query go through optimizer again. Change it to CREATE_PHASE + // because we want to re-generate and send InfiniDB plan. + if (thd->infinidb_vtable.mysql_optimizer_off) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_CREATE_VTABLE; + thd->infinidb_vtable.create_vtable_query.free(); + thd->infinidb_vtable.create_vtable_query.append(create.c_str(), create.length()); + thd->infinidb_vtable.select_vtable_query.free(); + thd->infinidb_vtable.select_vtable_query.append(select.c_str(), select.length()); + } + thd->query = thd->infinidb_vtable.create_vtable_query.c_ptr(); + thd->query_length = thd->infinidb_vtable.create_vtable_query.length(); + thd->infinidb_vtable.isUnion = false; // make state change to create_vtable in sql_select +#ifdef SAFE_MUTEX + printf("<<< V-TABLE Redo Phase 1: %s\n", thd->query); +#endif + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + close_thread_tables(thd); + if (thd->infinidb_vtable.mysql_optimizer_off) + thd->infinidb_vtable.mysql_optimizer_off = false; + if ((thd->main_da.is_error()) || ( thd->killed > 0 )) //@Bug 2974 Handle ctrl-c + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; + break; + } + } + } + else if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_QUERY) + { + alloc_query(thd, thd->infinidb_vtable.drop_vtable_query.c_ptr(), thd->infinidb_vtable.drop_vtable_query.length()); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DROP_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + thd->query = thd->infinidb_vtable.original_query.c_ptr(); + thd->query_length = thd->infinidb_vtable.original_query.length(); + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + } + + // error out Calpont non-supported error + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_ERROR) + { + if (thd->infinidb_vtable.autoswitch || isExplain) + { + // auto switch -- vtablemode = 2. rerun the original query + thd->query = thd->infinidb_vtable.drop_vtable_query.c_ptr(); + thd->query_length = thd->infinidb_vtable.drop_vtable_query.length(); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DROP_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + alloc_query(thd, thd->infinidb_vtable.original_query.c_ptr(), thd->infinidb_vtable.original_query.length()); +#ifdef SAFE_MUTEX + printf("<<< V-TABLE unsupported components encountered. Auto switch to table mode\n"); +#endif + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_INIT; + } + else + { + // error out -- vtable mode = 1 + if (thd->killed != THD::KILL_QUERY) + thd->killed = THD::KILL_QUERY; + } + } + else if ( thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE ) + { + alloc_query(thd, thd->infinidb_vtable.alter_vtable_query.c_ptr(), thd->infinidb_vtable.alter_vtable_query.length()); +#ifdef SAFE_MUTEX + printf("<<< V-TABLE Phase 2: %s\n", thd->query); +#endif + thd->infinidb_vtable.vtable_state = THD::INFINIDB_ALTER_VTABLE; + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + close_thread_tables(thd); + + // do insert vtable if INSERT_SELECT + if (thd->infinidb_vtable.isInsertSelect) + { + // phase 3 for insert select. insert dest from vtable + std::string insert; + insert = insert_query + " " + thd->infinidb_vtable.select_vtable_query.c_ptr() + " " + on_duplicate; + thd->infinidb_vtable.insert_vtable_query.free(); + thd->infinidb_vtable.insert_vtable_query.append(insert.c_str(), insert.length()); + + alloc_query(thd, thd->infinidb_vtable.insert_vtable_query.c_ptr(), thd->infinidb_vtable.insert_vtable_query.length()); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_SELECT_VTABLE; +#ifdef SAFE_MUTEX + printf("<<< V-TABLE Phase 3: %s\n", thd->query); +#endif + } + else + { + alloc_query(thd, thd->infinidb_vtable.select_vtable_query.c_ptr(), thd->infinidb_vtable.select_vtable_query.length()); + thd->infinidb_vtable.vtable_state = THD::INFINIDB_SELECT_VTABLE; + #ifdef SAFE_MUTEX + printf("<<< V-TABLE Phase 3: %s\n", thd->query); + #endif + } + mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt); + } + } + } + else + { + return -1; + } + } + else + { + return -1; + } + } + return 0; +} diff --git a/dbcon/mysql/sql_prepare.cc b/dbcon/mysql/sql_prepare.cc new file mode 100644 index 00000000..565acb8c --- /dev/null +++ b/dbcon/mysql/sql_prepare.cc @@ -0,0 +1,3631 @@ +/* Copyright (C) 1995-2002 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** + @file + +This file contains the implementation of prepared statements. + +When one prepares a statement: + + - Server gets the query from client with command 'COM_STMT_PREPARE'; + in the following format: + [COM_STMT_PREPARE:1] [query] + - Parse the query and recognize any parameter markers '?' and + store its information list in lex->param_list + - Allocate a new statement for this prepare; and keep this in + 'thd->stmt_map'. + - Without executing the query, return back to client the total + number of parameters along with result-set metadata information + (if any) in the following format: + @verbatim + [STMT_ID:4] + [Column_count:2] + [Param_count:2] + [Params meta info (stubs only for now)] (if Param_count > 0) + [Columns meta info] (if Column_count > 0) + @endverbatim + + During prepare the tables used in a statement are opened, but no + locks are acquired. Table opening will block any DDL during the + operation, and we do not need any locks as we neither read nor + modify any data during prepare. Tables are closed after prepare + finishes. + +When one executes a statement: + + - Server gets the command 'COM_STMT_EXECUTE' to execute the + previously prepared query. If there are any parameter markers, then the + client will send the data in the following format: + @verbatim + [COM_STMT_EXECUTE:1] + [STMT_ID:4] + [NULL_BITS:(param_count+7)/8)] + [TYPES_SUPPLIED_BY_CLIENT(0/1):1] + [[length]data] + [[length]data] .. [[length]data]. + @endverbatim + (Note: Except for string/binary types; all other types will not be + supplied with length field) + - If it is a first execute or types of parameters were altered by client, + then setup the conversion routines. + - Assign parameter items from the supplied data. + - Execute the query without re-parsing and send back the results + to client + + During execution of prepared statement tables are opened and locked + the same way they would for normal (non-prepared) statement + execution. Tables are unlocked and closed after the execution. + +When one supplies long data for a placeholder: + + - Server gets the long data in pieces with command type + 'COM_STMT_SEND_LONG_DATA'. + - The packet recieved will have the format as: + [COM_STMT_SEND_LONG_DATA:1][STMT_ID:4][parameter_number:2][data] + - data from the packet is appended to the long data value buffer for this + placeholder. + - It's up to the client to stop supplying data chunks at any point. The + server doesn't care; also, the server doesn't notify the client whether + it got the data or not; if there is any error, then it will be returned + at statement execute. +*/ +#include +#include + +#include "mysql_priv.h" +#include "sql_select.h" // for JOIN +#include "sql_cursor.h" +#include "sp_head.h" +#include "sp.h" +#include "sp_cache.h" +#ifdef EMBEDDED_LIBRARY +/* include MYSQL_BIND headers */ +#include +#else +#include +#endif + +#include "sp_head.h" +#include "sp.h" +#include "sp_cache.h" +#include "events.h" +#include "sql_trigger.h" +#include "sp_pcontext.h" + +// InfiniDB vtable processing +extern int idb_vtable_process(THD* thd, Statement* stmt = NULL); + + +/****************************************************************************** + Implementation +******************************************************************************/ + +inline bool is_param_null(const uchar *pos, ulong param_no) +{ + return pos[param_no/8] & (1 << (param_no & 7)); +} + +/** + Find a prepared statement in the statement map by id. + + Try to find a prepared statement and set THD error if it's not found. + + @param thd thread handle + @param id statement id + @param where the place from which this function is called (for + error reporting). + + @return + 0 if the statement was not found, a pointer otherwise. +*/ + +static Prepared_statement * +find_prepared_statement(THD *thd, ulong id) +{ + /* + To strictly separate namespaces of SQL prepared statements and C API + prepared statements find() will return 0 if there is a named prepared + statement with such id. + */ + Statement *stmt= thd->stmt_map.find(id); + + if (stmt == 0 || stmt->type() != Query_arena::PREPARED_STATEMENT) + return NULL; + + return (Prepared_statement *) stmt; +} + + +/** + Send prepared statement id and metadata to the client after prepare. + + @todo + Fix this nasty upcast from List to List + + @return + 0 in case of success, 1 otherwise +*/ + +#ifndef EMBEDDED_LIBRARY +static bool send_prep_stmt(Prepared_statement *stmt, uint columns) +{ + NET *net= &stmt->thd->net; + uchar buff[12]; + uint tmp; + int error; + THD *thd= stmt->thd; + DBUG_ENTER("send_prep_stmt"); + + buff[0]= 0; /* OK packet indicator */ + int4store(buff+1, stmt->id); + int2store(buff+5, columns); + int2store(buff+7, stmt->param_count); + buff[9]= 0; // Guard against a 4.1 client + tmp= min(stmt->thd->total_warn_count, 65535); + int2store(buff+10, tmp); + + /* + Send types and names of placeholders to the client + XXX: fix this nasty upcast from List to List + */ + error= my_net_write(net, buff, sizeof(buff)); + if (stmt->param_count && ! error) + { + error= thd->protocol_text.send_fields((List *) + &stmt->lex->param_list, + Protocol::SEND_EOF); + } + /* Flag that a response has already been sent */ + thd->main_da.disable_status(); + DBUG_RETURN(error); +} +#else +static bool send_prep_stmt(Prepared_statement *stmt, + uint columns __attribute__((unused))) +{ + THD *thd= stmt->thd; + + thd->client_stmt_id= stmt->id; + thd->client_param_count= stmt->param_count; + thd->clear_error(); + thd->main_da.disable_status(); + + return 0; +} +#endif /*!EMBEDDED_LIBRARY*/ + + +#ifndef EMBEDDED_LIBRARY + +/** + Read the length of the parameter data and return it back to + the caller. + + Read data length, position the packet to the first byte after it, + and return the length to the caller. + + @param packet a pointer to the data + @param len remaining packet length + + @return + Length of data piece. +*/ + +static ulong get_param_length(uchar **packet, ulong len) +{ + reg1 uchar *pos= *packet; + if (len < 1) + return 0; + if (*pos < 251) + { + (*packet)++; + return (ulong) *pos; + } + if (len < 3) + return 0; + if (*pos == 252) + { + (*packet)+=3; + return (ulong) uint2korr(pos+1); + } + if (len < 4) + return 0; + if (*pos == 253) + { + (*packet)+=4; + return (ulong) uint3korr(pos+1); + } + if (len < 5) + return 0; + (*packet)+=9; // Must be 254 when here + /* + In our client-server protocol all numbers bigger than 2^24 + stored as 8 bytes with uint8korr. Here we always know that + parameter length is less than 2^4 so don't look at the second + 4 bytes. But still we need to obey the protocol hence 9 in the + assignment above. + */ + return (ulong) uint4korr(pos+1); +} +#else +#define get_param_length(packet, len) len +#endif /*!EMBEDDED_LIBRARY*/ + +/** + Data conversion routines. + + All these functions read the data from pos, convert it to requested + type and assign to param; pos is advanced to predefined length. + + Make a note that the NULL handling is examined at first execution + (i.e. when input types altered) and for all subsequent executions + we don't read any values for this. + + @param param parameter item + @param pos input data buffer + @param len length of data in the buffer +*/ + +static void set_param_tiny(Item_param *param, uchar **pos, ulong len) +{ +#ifndef EMBEDDED_LIBRARY + if (len < 1) + return; +#endif + int8 value= (int8) **pos; + param->set_int(param->unsigned_flag ? (longlong) ((uint8) value) : + (longlong) value, 4); + *pos+= 1; +} + +static void set_param_short(Item_param *param, uchar **pos, ulong len) +{ + int16 value; +#ifndef EMBEDDED_LIBRARY + if (len < 2) + return; + value= sint2korr(*pos); +#else + shortget(value, *pos); +#endif + param->set_int(param->unsigned_flag ? (longlong) ((uint16) value) : + (longlong) value, 6); + *pos+= 2; +} + +static void set_param_int32(Item_param *param, uchar **pos, ulong len) +{ + int32 value; +#ifndef EMBEDDED_LIBRARY + if (len < 4) + return; + value= sint4korr(*pos); +#else + longget(value, *pos); +#endif + param->set_int(param->unsigned_flag ? (longlong) ((uint32) value) : + (longlong) value, 11); + *pos+= 4; +} + +static void set_param_int64(Item_param *param, uchar **pos, ulong len) +{ + longlong value; +#ifndef EMBEDDED_LIBRARY + if (len < 8) + return; + value= (longlong) sint8korr(*pos); +#else + longlongget(value, *pos); +#endif + param->set_int(value, 21); + *pos+= 8; +} + +static void set_param_float(Item_param *param, uchar **pos, ulong len) +{ + float data; +#ifndef EMBEDDED_LIBRARY + if (len < 4) + return; + float4get(data,*pos); +#else + floatget(data, *pos); +#endif + param->set_double((double) data); + *pos+= 4; +} + +static void set_param_double(Item_param *param, uchar **pos, ulong len) +{ + double data; +#ifndef EMBEDDED_LIBRARY + if (len < 8) + return; + float8get(data,*pos); +#else + doubleget(data, *pos); +#endif + param->set_double((double) data); + *pos+= 8; +} + +static void set_param_decimal(Item_param *param, uchar **pos, ulong len) +{ + ulong length= get_param_length(pos, len); + param->set_decimal((char*)*pos, length); + *pos+= length; +} + +#ifndef EMBEDDED_LIBRARY + +/* + Read date/time/datetime parameter values from network (binary + protocol). See writing counterparts of these functions in + libmysql.c (store_param_{time,date,datetime}). +*/ + +/** + @todo + Add warning 'Data truncated' here +*/ +static void set_param_time(Item_param *param, uchar **pos, ulong len) +{ + MYSQL_TIME tm; + ulong length= get_param_length(pos, len); + + if (length >= 8) + { + uchar *to= *pos; + uint day; + + tm.neg= (bool) to[0]; + day= (uint) sint4korr(to+1); + tm.hour= (uint) to[5] + day * 24; + tm.minute= (uint) to[6]; + tm.second= (uint) to[7]; + tm.second_part= (length > 8) ? (ulong) sint4korr(to+8) : 0; + if (tm.hour > 838) + { + /* TODO: add warning 'Data truncated' here */ + tm.hour= 838; + tm.minute= 59; + tm.second= 59; + } + tm.day= tm.year= tm.month= 0; + } + else + set_zero_time(&tm, MYSQL_TIMESTAMP_TIME); + param->set_time(&tm, MYSQL_TIMESTAMP_TIME, + MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN); + *pos+= length; +} + +static void set_param_datetime(Item_param *param, uchar **pos, ulong len) +{ + MYSQL_TIME tm; + ulong length= get_param_length(pos, len); + + if (length >= 4) + { + uchar *to= *pos; + + tm.neg= 0; + tm.year= (uint) sint2korr(to); + tm.month= (uint) to[2]; + tm.day= (uint) to[3]; + if (length > 4) + { + tm.hour= (uint) to[4]; + tm.minute= (uint) to[5]; + tm.second= (uint) to[6]; + } + else + tm.hour= tm.minute= tm.second= 0; + + tm.second_part= (length > 7) ? (ulong) sint4korr(to+7) : 0; + } + else + set_zero_time(&tm, MYSQL_TIMESTAMP_DATETIME); + param->set_time(&tm, MYSQL_TIMESTAMP_DATETIME, + MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN); + *pos+= length; +} + + +static void set_param_date(Item_param *param, uchar **pos, ulong len) +{ + MYSQL_TIME tm; + ulong length= get_param_length(pos, len); + + if (length >= 4) + { + uchar *to= *pos; + + tm.year= (uint) sint2korr(to); + tm.month= (uint) to[2]; + tm.day= (uint) to[3]; + + tm.hour= tm.minute= tm.second= 0; + tm.second_part= 0; + tm.neg= 0; + } + else + set_zero_time(&tm, MYSQL_TIMESTAMP_DATE); + param->set_time(&tm, MYSQL_TIMESTAMP_DATE, + MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN); + *pos+= length; +} + +#else/*!EMBEDDED_LIBRARY*/ +/** + @todo + Add warning 'Data truncated' here +*/ +void set_param_time(Item_param *param, uchar **pos, ulong len) +{ + MYSQL_TIME tm= *((MYSQL_TIME*)*pos); + tm.hour+= tm.day * 24; + tm.day= tm.year= tm.month= 0; + if (tm.hour > 838) + { + /* TODO: add warning 'Data truncated' here */ + tm.hour= 838; + tm.minute= 59; + tm.second= 59; + } + param->set_time(&tm, MYSQL_TIMESTAMP_TIME, + MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN); + +} + +void set_param_datetime(Item_param *param, uchar **pos, ulong len) +{ + MYSQL_TIME tm= *((MYSQL_TIME*)*pos); + tm.neg= 0; + + param->set_time(&tm, MYSQL_TIMESTAMP_DATETIME, + MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN); +} + +void set_param_date(Item_param *param, uchar **pos, ulong len) +{ + MYSQL_TIME *to= (MYSQL_TIME*)*pos; + + param->set_time(to, MYSQL_TIMESTAMP_DATE, + MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN); +} +#endif /*!EMBEDDED_LIBRARY*/ + + +static void set_param_str(Item_param *param, uchar **pos, ulong len) +{ + ulong length= get_param_length(pos, len); + if (length > len) + length= len; + param->set_str((const char *)*pos, length); + *pos+= length; +} + + +#undef get_param_length + +static void setup_one_conversion_function(THD *thd, Item_param *param, + uchar param_type) +{ + switch (param_type) { + case MYSQL_TYPE_TINY: + param->set_param_func= set_param_tiny; + param->item_type= Item::INT_ITEM; + param->item_result_type= INT_RESULT; + break; + case MYSQL_TYPE_SHORT: + param->set_param_func= set_param_short; + param->item_type= Item::INT_ITEM; + param->item_result_type= INT_RESULT; + break; + case MYSQL_TYPE_LONG: + param->set_param_func= set_param_int32; + param->item_type= Item::INT_ITEM; + param->item_result_type= INT_RESULT; + break; + case MYSQL_TYPE_LONGLONG: + param->set_param_func= set_param_int64; + param->item_type= Item::INT_ITEM; + param->item_result_type= INT_RESULT; + break; + case MYSQL_TYPE_FLOAT: + param->set_param_func= set_param_float; + param->item_type= Item::REAL_ITEM; + param->item_result_type= REAL_RESULT; + break; + case MYSQL_TYPE_DOUBLE: + param->set_param_func= set_param_double; + param->item_type= Item::REAL_ITEM; + param->item_result_type= REAL_RESULT; + break; + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_NEWDECIMAL: + param->set_param_func= set_param_decimal; + param->item_type= Item::DECIMAL_ITEM; + param->item_result_type= DECIMAL_RESULT; + break; + case MYSQL_TYPE_TIME: + param->set_param_func= set_param_time; + param->item_type= Item::STRING_ITEM; + param->item_result_type= STRING_RESULT; + break; + case MYSQL_TYPE_DATE: + param->set_param_func= set_param_date; + param->item_type= Item::STRING_ITEM; + param->item_result_type= STRING_RESULT; + break; + case MYSQL_TYPE_DATETIME: + case MYSQL_TYPE_TIMESTAMP: + param->set_param_func= set_param_datetime; + param->item_type= Item::STRING_ITEM; + param->item_result_type= STRING_RESULT; + break; + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + param->set_param_func= set_param_str; + param->value.cs_info.character_set_of_placeholder= &my_charset_bin; + param->value.cs_info.character_set_client= + thd->variables.character_set_client; + DBUG_ASSERT(thd->variables.character_set_client); + param->value.cs_info.final_character_set_of_str_value= &my_charset_bin; + param->item_type= Item::STRING_ITEM; + param->item_result_type= STRING_RESULT; + break; + default: + /* + The client library ensures that we won't get any other typecodes + except typecodes above and typecodes for string types. Marking + label as 'default' lets us to handle malformed packets as well. + */ + { + CHARSET_INFO *fromcs= thd->variables.character_set_client; + CHARSET_INFO *tocs= thd->variables.collation_connection; + uint32 dummy_offset; + + param->value.cs_info.character_set_of_placeholder= fromcs; + param->value.cs_info.character_set_client= fromcs; + + /* + Setup source and destination character sets so that they + are different only if conversion is necessary: this will + make later checks easier. + */ + param->value.cs_info.final_character_set_of_str_value= + String::needs_conversion(0, fromcs, tocs, &dummy_offset) ? + tocs : fromcs; + param->set_param_func= set_param_str; + /* + Exact value of max_length is not known unless data is converted to + charset of connection, so we have to set it later. + */ + param->item_type= Item::STRING_ITEM; + param->item_result_type= STRING_RESULT; + } + } + param->param_type= (enum enum_field_types) param_type; +} + +#ifndef EMBEDDED_LIBRARY +/** + Routines to assign parameters from data supplied by the client. + + Update the parameter markers by reading data from the packet and + and generate a valid query for logging. + + @note + This function, along with other _with_log functions is called when one of + binary, slow or general logs is open. Logging of prepared statements in + all cases is performed by means of conventional queries: if parameter + data was supplied from C API, each placeholder in the query is + replaced with its actual value; if we're logging a [Dynamic] SQL + prepared statement, parameter markers are replaced with variable names. + Example: + @verbatim + mysqld_stmt_prepare("UPDATE t1 SET a=a*1.25 WHERE a=?") + --> general logs gets [Prepare] UPDATE t1 SET a*1.25 WHERE a=?" + mysqld_stmt_execute(stmt); + --> general and binary logs get + [Execute] UPDATE t1 SET a*1.25 WHERE a=1" + @endverbatim + + If a statement has been prepared using SQL syntax: + @verbatim + PREPARE stmt FROM "UPDATE t1 SET a=a*1.25 WHERE a=?" + --> general log gets + [Query] PREPARE stmt FROM "UPDATE ..." + EXECUTE stmt USING @a + --> general log gets + [Query] EXECUTE stmt USING @a; + @endverbatim + + @retval + 0 if success + @retval + 1 otherwise +*/ + +static bool insert_params_with_log(Prepared_statement *stmt, uchar *null_array, + uchar *read_pos, uchar *data_end, + String *query) +{ + THD *thd= stmt->thd; + Item_param **begin= stmt->param_array; + Item_param **end= begin + stmt->param_count; + uint32 length= 0; + String str; + const String *res; + DBUG_ENTER("insert_params_with_log"); + + if (query->copy(stmt->query, stmt->query_length, default_charset_info)) + DBUG_RETURN(1); + + for (Item_param **it= begin; it < end; ++it) + { + Item_param *param= *it; + if (param->state != Item_param::LONG_DATA_VALUE) + { + if (is_param_null(null_array, (uint) (it - begin))) + param->set_null(); + else + { + if (read_pos >= data_end) + DBUG_RETURN(1); + param->set_param_func(param, &read_pos, (uint) (data_end - read_pos)); + if (param->state == Item_param::NO_VALUE) + DBUG_RETURN(1); + } + } + res= param->query_val_str(&str); + if (param->convert_str_value(thd)) + DBUG_RETURN(1); /* out of memory */ + + if (query->replace(param->pos_in_query+length, 1, *res)) + DBUG_RETURN(1); + + length+= res->length()-1; + } + DBUG_RETURN(0); +} + + +static bool insert_params(Prepared_statement *stmt, uchar *null_array, + uchar *read_pos, uchar *data_end, + String *expanded_query) +{ + Item_param **begin= stmt->param_array; + Item_param **end= begin + stmt->param_count; + + DBUG_ENTER("insert_params"); + + for (Item_param **it= begin; it < end; ++it) + { + Item_param *param= *it; + if (param->state != Item_param::LONG_DATA_VALUE) + { + if (is_param_null(null_array, (uint) (it - begin))) + param->set_null(); + else + { + if (read_pos >= data_end) + DBUG_RETURN(1); + param->set_param_func(param, &read_pos, (uint) (data_end - read_pos)); + if (param->state == Item_param::NO_VALUE) + DBUG_RETURN(1); + } + } + if (param->convert_str_value(stmt->thd)) + DBUG_RETURN(1); /* out of memory */ + } + DBUG_RETURN(0); +} + + +static bool setup_conversion_functions(Prepared_statement *stmt, + uchar **data, uchar *data_end) +{ + /* skip null bits */ + uchar *read_pos= *data + (stmt->param_count+7) / 8; + + DBUG_ENTER("setup_conversion_functions"); + + if (*read_pos++) //types supplied / first execute + { + /* + First execute or types altered by the client, setup the + conversion routines for all parameters (one time) + */ + Item_param **it= stmt->param_array; + Item_param **end= it + stmt->param_count; + THD *thd= stmt->thd; + for (; it < end; ++it) + { + ushort typecode; + const uint signed_bit= 1 << 15; + + if (read_pos >= data_end) + DBUG_RETURN(1); + + typecode= sint2korr(read_pos); + read_pos+= 2; + (**it).unsigned_flag= test(typecode & signed_bit); + setup_one_conversion_function(thd, *it, (uchar) (typecode & ~signed_bit)); + } + } + *data= read_pos; + DBUG_RETURN(0); +} + +#else + +/** + Embedded counterparts of parameter assignment routines. + + The main difference between the embedded library and the server is + that in embedded case we don't serialize/deserialize parameters data. + + Additionally, for unknown reason, the client-side flag raised for + changed types of placeholders is ignored and we simply setup conversion + functions at each execute (TODO: fix). +*/ + +static bool emb_insert_params(Prepared_statement *stmt, String *expanded_query) +{ + THD *thd= stmt->thd; + Item_param **it= stmt->param_array; + Item_param **end= it + stmt->param_count; + MYSQL_BIND *client_param= stmt->thd->client_params; + + DBUG_ENTER("emb_insert_params"); + + for (; it < end; ++it, ++client_param) + { + Item_param *param= *it; + setup_one_conversion_function(thd, param, client_param->buffer_type); + if (param->state != Item_param::LONG_DATA_VALUE) + { + if (*client_param->is_null) + param->set_null(); + else + { + uchar *buff= (uchar*) client_param->buffer; + param->unsigned_flag= client_param->is_unsigned; + param->set_param_func(param, &buff, + client_param->length ? + *client_param->length : + client_param->buffer_length); + if (param->state == Item_param::NO_VALUE) + DBUG_RETURN(1); + } + } + if (param->convert_str_value(thd)) + DBUG_RETURN(1); /* out of memory */ + } + DBUG_RETURN(0); +} + + +static bool emb_insert_params_with_log(Prepared_statement *stmt, + String *query) +{ + THD *thd= stmt->thd; + Item_param **it= stmt->param_array; + Item_param **end= it + stmt->param_count; + MYSQL_BIND *client_param= thd->client_params; + + String str; + const String *res; + uint32 length= 0; + + DBUG_ENTER("emb_insert_params_with_log"); + + if (query->copy(stmt->query, stmt->query_length, default_charset_info)) + DBUG_RETURN(1); + + for (; it < end; ++it, ++client_param) + { + Item_param *param= *it; + setup_one_conversion_function(thd, param, client_param->buffer_type); + if (param->state != Item_param::LONG_DATA_VALUE) + { + if (*client_param->is_null) + param->set_null(); + else + { + uchar *buff= (uchar*)client_param->buffer; + param->unsigned_flag= client_param->is_unsigned; + param->set_param_func(param, &buff, + client_param->length ? + *client_param->length : + client_param->buffer_length); + if (param->state == Item_param::NO_VALUE) + DBUG_RETURN(1); + } + } + res= param->query_val_str(&str); + if (param->convert_str_value(thd)) + DBUG_RETURN(1); /* out of memory */ + + if (query->replace(param->pos_in_query+length, 1, *res)) + DBUG_RETURN(1); + + length+= res->length()-1; + } + DBUG_RETURN(0); +} + +#endif /*!EMBEDDED_LIBRARY*/ + +/** + Setup data conversion routines using an array of parameter + markers from the original prepared statement. + Swap the parameter data of the original prepared + statement to the new one. + + Used only when we re-prepare a prepared statement. + There are two reasons for this function to exist: + + 1) In the binary client/server protocol, parameter metadata + is sent only at first execute. Consequently, if we need to + reprepare a prepared statement at a subsequent execution, + we may not have metadata information in the packet. + In that case we use the parameter array of the original + prepared statement to setup parameter types of the new + prepared statement. + + 2) In the binary client/server protocol, we may supply + long data in pieces. When the last piece is supplied, + we assemble the pieces and convert them from client + character set to the connection character set. After + that the parameter value is only available inside + the parameter, the original pieces are lost, and thus + we can only assign the corresponding parameter of the + reprepared statement from the original value. + + @param[out] param_array_dst parameter markers of the new statement + @param[in] param_array_src parameter markers of the original + statement + @param[in] param_count total number of parameters. Is the + same in src and dst arrays, since + the statement query is the same + + @return this function never fails +*/ + +static void +swap_parameter_array(Item_param **param_array_dst, + Item_param **param_array_src, + uint param_count) +{ + Item_param **dst= param_array_dst; + Item_param **src= param_array_src; + Item_param **end= param_array_dst + param_count; + + for (; dst < end; ++src, ++dst) + (*dst)->set_param_type_and_swap_value(*src); +} + + +/** + Assign prepared statement parameters from user variables. + + @param stmt Statement + @param varnames List of variables. Caller must ensure that number + of variables in the list is equal to number of statement + parameters + @param query Ignored +*/ + +static bool insert_params_from_vars(Prepared_statement *stmt, + List& varnames, + String *query __attribute__((unused))) +{ + Item_param **begin= stmt->param_array; + Item_param **end= begin + stmt->param_count; + user_var_entry *entry; + LEX_STRING *varname; + List_iterator var_it(varnames); + DBUG_ENTER("insert_params_from_vars"); + + for (Item_param **it= begin; it < end; ++it) + { + Item_param *param= *it; + varname= var_it++; + entry= (user_var_entry*)hash_search(&stmt->thd->user_vars, + (uchar*) varname->str, + varname->length); + if (param->set_from_user_var(stmt->thd, entry) || + param->convert_str_value(stmt->thd)) + DBUG_RETURN(1); + } + DBUG_RETURN(0); +} + + +/** + Do the same as insert_params_from_vars but also construct query text for + binary log. + + @param stmt Prepared statement + @param varnames List of variables. Caller must ensure that number of + variables in the list is equal to number of statement + parameters + @param query The query with parameter markers replaced with corresponding + user variables that were used to execute the query. +*/ + +static bool insert_params_from_vars_with_log(Prepared_statement *stmt, + List& varnames, + String *query) +{ + Item_param **begin= stmt->param_array; + Item_param **end= begin + stmt->param_count; + user_var_entry *entry; + LEX_STRING *varname; + List_iterator var_it(varnames); + String buf; + const String *val; + uint32 length= 0; + THD *thd= stmt->thd; + + DBUG_ENTER("insert_params_from_vars"); + + if (query->copy(stmt->query, stmt->query_length, default_charset_info)) + DBUG_RETURN(1); + + for (Item_param **it= begin; it < end; ++it) + { + Item_param *param= *it; + varname= var_it++; + + entry= (user_var_entry *) hash_search(&thd->user_vars, (uchar*) varname->str, + varname->length); + /* + We have to call the setup_one_conversion_function() here to set + the parameter's members that might be needed further + (e.g. value.cs_info.character_set_client is used in the query_val_str()). + */ + setup_one_conversion_function(thd, param, param->param_type); + if (param->set_from_user_var(thd, entry)) + DBUG_RETURN(1); + val= param->query_val_str(&buf); + + if (param->convert_str_value(thd)) + DBUG_RETURN(1); /* out of memory */ + + if (query->replace(param->pos_in_query+length, 1, *val)) + DBUG_RETURN(1); + length+= val->length()-1; + } + DBUG_RETURN(0); +} + +/** + Validate INSERT statement. + + @param stmt prepared statement + @param tables global/local table list + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_insert(Prepared_statement *stmt, + TABLE_LIST *table_list, + List &fields, + List &values_list, + List &update_fields, + List &update_values, + enum_duplicates duplic) +{ + THD *thd= stmt->thd; + List_iterator_fast its(values_list); + List_item *values; + DBUG_ENTER("mysql_test_insert"); + + if (insert_precheck(thd, table_list)) + goto error; + + /* + open temporary memory pool for temporary data allocated by derived + tables & preparation procedure + Note that this is done without locks (should not be needed as we will not + access any data here) + If we would use locks, then we have to ensure we are not using + TL_WRITE_DELAYED as having two such locks can cause table corruption. + */ + if (open_normal_and_derived_tables(thd, table_list, 0)) + goto error; + + if ((values= its++)) + { + uint value_count; + ulong counter= 0; + Item *unused_conds= 0; + + if (table_list->table) + { + // don't allocate insert_values + table_list->table->insert_values=(uchar *)1; + } + + if (mysql_prepare_insert(thd, table_list, table_list->table, + fields, values, update_fields, update_values, + duplic, &unused_conds, FALSE, FALSE, FALSE)) + goto error; + + value_count= values->elements; + its.rewind(); + + if (table_list->lock_type == TL_WRITE_DELAYED && + !(table_list->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED)) + { + my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), (table_list->view ? + table_list->view_name.str : + table_list->table_name)); + goto error; + } + while ((values= its++)) + { + counter++; + if (values->elements != value_count) + { + my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter); + goto error; + } + if (setup_fields(thd, 0, *values, MARK_COLUMNS_NONE, 0, 0)) + goto error; + } + } + DBUG_RETURN(FALSE); + +error: + /* insert_values is cleared in open_table */ + DBUG_RETURN(TRUE); +} + + +/** + Validate UPDATE statement. + + @param stmt prepared statement + @param tables list of tables used in this query + + @todo + - here we should send types of placeholders to the client. + + @retval + 0 success + @retval + 1 error, error message is set in THD + @retval + 2 convert to multi_update +*/ + +static int mysql_test_update(Prepared_statement *stmt, + TABLE_LIST *table_list) +{ + int res; + THD *thd= stmt->thd; + uint table_count= 0; + SELECT_LEX *select= &stmt->lex->select_lex; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + uint want_privilege; +#endif + DBUG_ENTER("mysql_test_update"); + + if (update_precheck(thd, table_list) || + open_tables(thd, &table_list, &table_count, 0)) + goto error; + + if (table_list->multitable_view) + { + DBUG_ASSERT(table_list->view != 0); + DBUG_PRINT("info", ("Switch to multi-update")); + /* pass counter value */ + thd->lex->table_count= table_count; + /* convert to multiupdate */ + DBUG_RETURN(2); + } + + /* + thd->fill_derived_tables() is false here for sure (because it is + preparation of PS, so we even do not check it). + */ + if (mysql_handle_derived(thd->lex, &mysql_derived_prepare)) + goto error; + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* Force privilege re-checking for views after they have been opened. */ + want_privilege= (table_list->view ? UPDATE_ACL : + table_list->grant.want_privilege); +#endif + + if (mysql_prepare_update(thd, table_list, &select->where, + select->order_list.elements, + (ORDER *) select->order_list.first)) + goto error; + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + table_list->grant.want_privilege= want_privilege; + table_list->table->grant.want_privilege= want_privilege; + table_list->register_want_access(want_privilege); +#endif + thd->lex->select_lex.no_wrap_view_item= TRUE; + res= setup_fields(thd, 0, select->item_list, MARK_COLUMNS_READ, 0, 0); + thd->lex->select_lex.no_wrap_view_item= FALSE; + if (res) + goto error; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* Check values */ + table_list->grant.want_privilege= + table_list->table->grant.want_privilege= + (SELECT_ACL & ~table_list->table->grant.privilege); + table_list->register_want_access(SELECT_ACL); +#endif + if (setup_fields(thd, 0, stmt->lex->value_list, MARK_COLUMNS_NONE, 0, 0)) + goto error; + /* TODO: here we should send types of placeholders to the client. */ + DBUG_RETURN(0); +error: + DBUG_RETURN(1); +} + + +/** + Validate DELETE statement. + + @param stmt prepared statement + @param tables list of tables used in this query + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_delete(Prepared_statement *stmt, + TABLE_LIST *table_list) +{ + THD *thd= stmt->thd; + LEX *lex= stmt->lex; + DBUG_ENTER("mysql_test_delete"); + + if (delete_precheck(thd, table_list) || + open_normal_and_derived_tables(thd, table_list, 0)) + goto error; + + if (!table_list->table) + { + my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0), + table_list->view_db.str, table_list->view_name.str); + goto error; + } + + DBUG_RETURN(mysql_prepare_delete(thd, table_list, &lex->select_lex.where)); +error: + DBUG_RETURN(TRUE); +} + + +/** + Validate SELECT statement. + + In case of success, if this query is not EXPLAIN, send column list info + back to the client. + + @param stmt prepared statement + @param tables list of tables used in the query + + @retval + 0 success + @retval + 1 error, error message is set in THD + @retval + 2 success, and statement metadata has been sent +*/ + +static int mysql_test_select(Prepared_statement *stmt, + TABLE_LIST *tables) +{ + THD *thd= stmt->thd; + LEX *lex= stmt->lex; + SELECT_LEX_UNIT *unit= &lex->unit; + DBUG_ENTER("mysql_test_select"); + + lex->select_lex.context.resolve_in_select_list= TRUE; + + ulong privilege= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL; + if (tables) + { + if (check_table_access(thd, privilege, tables, UINT_MAX, FALSE)) + goto error; + } + else if (check_access(thd, privilege, any_db,0,0,0,0)) + goto error; + + if (!lex->result && !(lex->result= new (stmt->mem_root) select_send)) + { + my_error(ER_OUTOFMEMORY, MYF(0), sizeof(select_send)); + goto error; + } + + if (open_normal_and_derived_tables(thd, tables, 0)) + goto error; + + thd->used_tables= 0; // Updated by setup_fields + + /* + JOIN::prepare calls + It is not SELECT COMMAND for sure, so setup_tables will be called as + usual, and we pass 0 as setup_tables_done_option + */ + if (unit->prepare(thd, 0, 0)) + goto error; + if (!lex->describe && !stmt->is_sql_prepare()) + { + /* Make copy of item list, as change_columns may change it */ + List fields(lex->select_lex.item_list); + + /* Change columns if a procedure like analyse() */ + if (unit->last_procedure && unit->last_procedure->change_columns(fields)) + goto error; + + /* + We can use lex->result as it should've been prepared in + unit->prepare call above. + */ + if (send_prep_stmt(stmt, lex->result->field_count(fields)) || + lex->result->send_fields(fields, Protocol::SEND_EOF) || + thd->protocol->flush()) + goto error; + DBUG_RETURN(2); + } + DBUG_RETURN(0); +error: + DBUG_RETURN(1); +} + + +/** + Validate and prepare for execution DO statement expressions. + + @param stmt prepared statement + @param tables list of tables used in this query + @param values list of expressions + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_do_fields(Prepared_statement *stmt, + TABLE_LIST *tables, + List *values) +{ + THD *thd= stmt->thd; + + DBUG_ENTER("mysql_test_do_fields"); + if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE)) + DBUG_RETURN(TRUE); + + if (open_normal_and_derived_tables(thd, tables, 0)) + DBUG_RETURN(TRUE); + DBUG_RETURN(setup_fields(thd, 0, *values, MARK_COLUMNS_NONE, 0, 0)); +} + + +/** + Validate and prepare for execution SET statement expressions. + + @param stmt prepared statement + @param tables list of tables used in this query + @param values list of expressions + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_set_fields(Prepared_statement *stmt, + TABLE_LIST *tables, + List *var_list) +{ + DBUG_ENTER("mysql_test_set_fields"); + List_iterator_fast it(*var_list); + THD *thd= stmt->thd; + set_var_base *var; + + if ((tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE)) + || open_normal_and_derived_tables(thd, tables, 0)) + goto error; + + while ((var= it++)) + { + if (var->light_check(thd)) + goto error; + } + DBUG_RETURN(FALSE); +error: + DBUG_RETURN(TRUE); +} + + +/** + Validate and prepare for execution CALL statement expressions. + + @param stmt prepared statement + @param tables list of tables used in this query + @param value_list list of expressions + + @retval FALSE success + @retval TRUE error, error message is set in THD +*/ + +static bool mysql_test_call_fields(Prepared_statement *stmt, + TABLE_LIST *tables, + List *value_list) +{ + DBUG_ENTER("mysql_test_call_fields"); + + List_iterator it(*value_list); + THD *thd= stmt->thd; + Item *item; + + if ((tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE)) || + open_normal_and_derived_tables(thd, tables, 0)) + goto err; + + while ((item= it++)) + { + if ((!item->fixed && item->fix_fields(thd, it.ref())) || + item->check_cols(1)) + goto err; + } + DBUG_RETURN(FALSE); +err: + DBUG_RETURN(TRUE); +} + + +/** + Check internal SELECT of the prepared command. + + @param stmt prepared statement + @param specific_prepare function of command specific prepare + @param setup_tables_done_option options to be passed to LEX::unit.prepare() + + @note + This function won't directly open tables used in select. They should + be opened either by calling function (and in this case you probably + should use select_like_stmt_test_with_open()) or by + "specific_prepare" call (like this happens in case of multi-update). + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool select_like_stmt_test(Prepared_statement *stmt, + int (*specific_prepare)(THD *thd), + ulong setup_tables_done_option) +{ + DBUG_ENTER("select_like_stmt_test"); + THD *thd= stmt->thd; + LEX *lex= stmt->lex; + + lex->select_lex.context.resolve_in_select_list= TRUE; + + if (specific_prepare && (*specific_prepare)(thd)) + DBUG_RETURN(TRUE); + + thd->used_tables= 0; // Updated by setup_fields + + /* Calls JOIN::prepare */ + DBUG_RETURN(lex->unit.prepare(thd, 0, setup_tables_done_option)); +} + +/** + Check internal SELECT of the prepared command (with opening of used + tables). + + @param stmt prepared statement + @param tables list of tables to be opened + before calling specific_prepare function + @param specific_prepare function of command specific prepare + @param setup_tables_done_option options to be passed to LEX::unit.prepare() + + @retval + FALSE success + @retval + TRUE error +*/ + +static bool +select_like_stmt_test_with_open(Prepared_statement *stmt, + TABLE_LIST *tables, + int (*specific_prepare)(THD *thd), + ulong setup_tables_done_option) +{ + DBUG_ENTER("select_like_stmt_test_with_open"); + + /* + We should not call LEX::unit.cleanup() after this + open_normal_and_derived_tables() call because we don't allow + prepared EXPLAIN yet so derived tables will clean up after + themself. + */ + if (open_normal_and_derived_tables(stmt->thd, tables, 0)) + DBUG_RETURN(TRUE); + + DBUG_RETURN(select_like_stmt_test(stmt, specific_prepare, + setup_tables_done_option)); +} + + +/** + Validate and prepare for execution CREATE TABLE statement. + + @param stmt prepared statement + @param tables list of tables used in this query + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_create_table(Prepared_statement *stmt) +{ + DBUG_ENTER("mysql_test_create_table"); + THD *thd= stmt->thd; + LEX *lex= stmt->lex; + SELECT_LEX *select_lex= &lex->select_lex; + bool res= FALSE; + /* Skip first table, which is the table we are creating */ + bool link_to_local; + TABLE_LIST *create_table= lex->unlink_first_table(&link_to_local); + TABLE_LIST *tables= lex->query_tables; + + if (create_table_precheck(thd, tables, create_table)) + DBUG_RETURN(TRUE); + + if (select_lex->item_list.elements) + { + if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)) + { + lex->link_first_table_back(create_table, link_to_local); + create_table->create= TRUE; + } + + if (open_normal_and_derived_tables(stmt->thd, lex->query_tables, 0)) + DBUG_RETURN(TRUE); + + if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)) + create_table= lex->unlink_first_table(&link_to_local); + + select_lex->context.resolve_in_select_list= TRUE; + + res= select_like_stmt_test(stmt, 0, 0); + } + else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE) + { + /* + Check that the source table exist, and also record + its metadata version. Even though not strictly necessary, + we validate metadata of all CREATE TABLE statements, + which keeps metadata validation code simple. + */ + if (open_normal_and_derived_tables(stmt->thd, lex->query_tables, 0)) + DBUG_RETURN(TRUE); + } + + /* put tables back for PS rexecuting */ + lex->link_first_table_back(create_table, link_to_local); + DBUG_RETURN(res); +} + + +/** + @brief Validate and prepare for execution CREATE VIEW statement + + @param stmt prepared statement + + @note This function handles create view commands. + + @retval FALSE Operation was a success. + @retval TRUE An error occured. +*/ + +static bool mysql_test_create_view(Prepared_statement *stmt) +{ + DBUG_ENTER("mysql_test_create_view"); + THD *thd= stmt->thd; + LEX *lex= stmt->lex; + bool res= TRUE; + /* Skip first table, which is the view we are creating */ + bool link_to_local; + TABLE_LIST *view= lex->unlink_first_table(&link_to_local); + TABLE_LIST *tables= lex->query_tables; + + if (create_view_precheck(thd, tables, view, lex->create_view_mode)) + goto err; + + if (open_normal_and_derived_tables(thd, tables, 0)) + goto err; + + lex->view_prepare_mode= 1; + res= select_like_stmt_test(stmt, 0, 0); + +err: + /* put view back for PS rexecuting */ + lex->link_first_table_back(view, link_to_local); + DBUG_RETURN(res); +} + + +/* + Validate and prepare for execution a multi update statement. + + @param stmt prepared statement + @param tables list of tables used in this query + @param converted converted to multi-update from usual update + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_multiupdate(Prepared_statement *stmt, + TABLE_LIST *tables, + bool converted) +{ + /* if we switched from normal update, rights are checked */ + if (!converted && multi_update_precheck(stmt->thd, tables)) + return TRUE; + + return select_like_stmt_test(stmt, &mysql_multi_update_prepare, + OPTION_SETUP_TABLES_DONE); +} + + +/** + Validate and prepare for execution a multi delete statement. + + @param stmt prepared statement + @param tables list of tables used in this query + + @retval + FALSE success + @retval + TRUE error, error message in THD is set. +*/ + +static bool mysql_test_multidelete(Prepared_statement *stmt, + TABLE_LIST *tables) +{ + stmt->thd->lex->current_select= &stmt->thd->lex->select_lex; + if (add_item_to_list(stmt->thd, new Item_null())) + { + my_error(ER_OUTOFMEMORY, MYF(0), 0); + goto error; + } + + if (multi_delete_precheck(stmt->thd, tables) || + select_like_stmt_test_with_open(stmt, tables, + &mysql_multi_delete_prepare, + OPTION_SETUP_TABLES_DONE)) + goto error; + if (!tables->table) + { + my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0), + tables->view_db.str, tables->view_name.str); + goto error; + } + return FALSE; +error: + return TRUE; +} + + +/** + Wrapper for mysql_insert_select_prepare, to make change of local tables + after open_normal_and_derived_tables() call. + + @param thd thread handle + + @note + We need to remove the first local table after + open_normal_and_derived_tables(), because mysql_handle_derived + uses local tables lists. +*/ + +static int mysql_insert_select_prepare_tester(THD *thd) +{ + SELECT_LEX *first_select= &thd->lex->select_lex; + TABLE_LIST *second_table= ((TABLE_LIST*)first_select->table_list.first)-> + next_local; + + /* Skip first table, which is the table we are inserting in */ + first_select->table_list.first= (uchar *) second_table; + thd->lex->select_lex.context.table_list= + thd->lex->select_lex.context.first_name_resolution_table= second_table; + + return mysql_insert_select_prepare(thd); +} + + +/** + Validate and prepare for execution INSERT ... SELECT statement. + + @param stmt prepared statement + @param tables list of tables used in this query + + @retval + FALSE success + @retval + TRUE error, error message is set in THD +*/ + +static bool mysql_test_insert_select(Prepared_statement *stmt, + TABLE_LIST *tables) +{ + int res; + LEX *lex= stmt->lex; + TABLE_LIST *first_local_table; + + if (tables->table) + { + // don't allocate insert_values + tables->table->insert_values=(uchar *)1; + } + + if (insert_precheck(stmt->thd, tables)) + return 1; + + /* store it, because mysql_insert_select_prepare_tester change it */ + first_local_table= (TABLE_LIST *)lex->select_lex.table_list.first; + DBUG_ASSERT(first_local_table != 0); + + res= + select_like_stmt_test_with_open(stmt, tables, + &mysql_insert_select_prepare_tester, + OPTION_SETUP_TABLES_DONE); + /* revert changes made by mysql_insert_select_prepare_tester */ + lex->select_lex.table_list.first= (uchar*) first_local_table; + return res; +} + + +/** + Perform semantic analysis of the parsed tree and send a response packet + to the client. + + This function + - opens all tables and checks access rights + - validates semantics of statement columns and SQL functions + by calling fix_fields. + + @param stmt prepared statement + + @retval + FALSE success, statement metadata is sent to client + @retval + TRUE error, error message is set in THD (but not sent) +*/ + +static bool check_prepared_statement(Prepared_statement *stmt) +{ + THD *thd= stmt->thd; + LEX *lex= stmt->lex; + SELECT_LEX *select_lex= &lex->select_lex; + TABLE_LIST *tables; + enum enum_sql_command sql_command= lex->sql_command; + int res= 0; + DBUG_ENTER("check_prepared_statement"); + DBUG_PRINT("enter",("command: %d param_count: %u", + sql_command, stmt->param_count)); + + lex->first_lists_tables_same(); + tables= lex->query_tables; + + /* set context for commands which do not use setup_tables */ + lex->select_lex.context.resolve_in_table_list_only(select_lex-> + get_table_list()); + + switch (sql_command) { + case SQLCOM_REPLACE: + case SQLCOM_INSERT: + res= mysql_test_insert(stmt, tables, lex->field_list, + lex->many_values, + lex->update_list, lex->value_list, + lex->duplicates); + break; + + case SQLCOM_UPDATE: + res= mysql_test_update(stmt, tables); + /* mysql_test_update returns 2 if we need to switch to multi-update */ + if (res != 2) + break; + + case SQLCOM_UPDATE_MULTI: + res= mysql_test_multiupdate(stmt, tables, res == 2); + break; + + case SQLCOM_DELETE: + res= mysql_test_delete(stmt, tables); + break; + /* The following allow WHERE clause, so they must be tested like SELECT */ + case SQLCOM_SHOW_DATABASES: + case SQLCOM_SHOW_TABLES: + case SQLCOM_SHOW_TRIGGERS: + case SQLCOM_SHOW_EVENTS: + case SQLCOM_SHOW_OPEN_TABLES: + case SQLCOM_SHOW_FIELDS: + case SQLCOM_SHOW_KEYS: + case SQLCOM_SHOW_COLLATIONS: + case SQLCOM_SHOW_CHARSETS: + case SQLCOM_SHOW_VARIABLES: + case SQLCOM_SHOW_STATUS: + case SQLCOM_SHOW_TABLE_STATUS: + case SQLCOM_SHOW_STATUS_PROC: + case SQLCOM_SHOW_STATUS_FUNC: + case SQLCOM_SELECT: + res= mysql_test_select(stmt, tables); + if (res == 2) + { + /* Statement and field info has already been sent */ + DBUG_RETURN(FALSE); + } + break; + case SQLCOM_CREATE_TABLE: + res= mysql_test_create_table(stmt); + break; + + case SQLCOM_CREATE_VIEW: + if (lex->create_view_mode == VIEW_ALTER) + { + my_message(ER_UNSUPPORTED_PS, ER(ER_UNSUPPORTED_PS), MYF(0)); + goto error; + } + res= mysql_test_create_view(stmt); + break; + case SQLCOM_DO: + res= mysql_test_do_fields(stmt, tables, lex->insert_list); + break; + + case SQLCOM_CALL: + res= mysql_test_call_fields(stmt, tables, &lex->value_list); + break; + case SQLCOM_SET_OPTION: + res= mysql_test_set_fields(stmt, tables, &lex->var_list); + break; + + case SQLCOM_DELETE_MULTI: + res= mysql_test_multidelete(stmt, tables); + break; + + case SQLCOM_INSERT_SELECT: + case SQLCOM_REPLACE_SELECT: + res= mysql_test_insert_select(stmt, tables); + break; + + /* + Note that we don't need to have cases in this list if they are + marked with CF_STATUS_COMMAND in sql_command_flags + */ + case SQLCOM_SHOW_PROCESSLIST: + case SQLCOM_SHOW_STORAGE_ENGINES: + case SQLCOM_SHOW_PRIVILEGES: + case SQLCOM_SHOW_COLUMN_TYPES: + case SQLCOM_SHOW_ENGINE_LOGS: + case SQLCOM_SHOW_ENGINE_STATUS: + case SQLCOM_SHOW_ENGINE_MUTEX: + case SQLCOM_SHOW_CREATE_DB: + case SQLCOM_SHOW_GRANTS: + case SQLCOM_SHOW_BINLOG_EVENTS: + case SQLCOM_SHOW_MASTER_STAT: + case SQLCOM_SHOW_SLAVE_STAT: + case SQLCOM_SHOW_CREATE_PROC: + case SQLCOM_SHOW_CREATE_FUNC: + case SQLCOM_SHOW_CREATE_EVENT: + case SQLCOM_SHOW_CREATE_TRIGGER: + case SQLCOM_SHOW_CREATE: + case SQLCOM_SHOW_PROC_CODE: + case SQLCOM_SHOW_FUNC_CODE: + case SQLCOM_SHOW_AUTHORS: + case SQLCOM_SHOW_CONTRIBUTORS: + case SQLCOM_SHOW_WARNS: + case SQLCOM_SHOW_ERRORS: + case SQLCOM_SHOW_BINLOGS: + case SQLCOM_DROP_TABLE: + case SQLCOM_RENAME_TABLE: + case SQLCOM_ALTER_TABLE: + case SQLCOM_COMMIT: + case SQLCOM_CREATE_INDEX: + case SQLCOM_DROP_INDEX: + case SQLCOM_ROLLBACK: + case SQLCOM_TRUNCATE: + case SQLCOM_DROP_VIEW: + case SQLCOM_REPAIR: + case SQLCOM_ANALYZE: + case SQLCOM_OPTIMIZE: + case SQLCOM_CHANGE_MASTER: + case SQLCOM_RESET: + case SQLCOM_FLUSH: + case SQLCOM_SLAVE_START: + case SQLCOM_SLAVE_STOP: + case SQLCOM_INSTALL_PLUGIN: + case SQLCOM_UNINSTALL_PLUGIN: + case SQLCOM_CREATE_DB: + case SQLCOM_DROP_DB: + case SQLCOM_ALTER_DB_UPGRADE: + case SQLCOM_CHECKSUM: + case SQLCOM_CREATE_USER: + case SQLCOM_RENAME_USER: + case SQLCOM_DROP_USER: + case SQLCOM_ASSIGN_TO_KEYCACHE: + case SQLCOM_PRELOAD_KEYS: + case SQLCOM_GRANT: + case SQLCOM_REVOKE: + case SQLCOM_KILL: + break; + + case SQLCOM_PREPARE: + case SQLCOM_EXECUTE: + case SQLCOM_DEALLOCATE_PREPARE: + default: + /* + Trivial check of all status commands. This is easier than having + things in the above case list, as it's less chance for mistakes. + */ + if (!(sql_command_flags[sql_command] & CF_STATUS_COMMAND)) + { + /* All other statements are not supported yet. */ + my_message(ER_UNSUPPORTED_PS, ER(ER_UNSUPPORTED_PS), MYF(0)); + goto error; + } + break; + } + if (res == 0) + DBUG_RETURN(stmt->is_sql_prepare() ? + FALSE : (send_prep_stmt(stmt, 0) || thd->protocol->flush())); +error: + DBUG_RETURN(TRUE); +} + +/** + Initialize array of parameters in statement from LEX. + (We need to have quick access to items by number in mysql_stmt_get_longdata). + This is to avoid using malloc/realloc in the parser. +*/ + +static bool init_param_array(Prepared_statement *stmt) +{ + LEX *lex= stmt->lex; + if ((stmt->param_count= lex->param_list.elements)) + { + if (stmt->param_count > (uint) UINT_MAX16) + { + /* Error code to be defined in 5.0 */ + my_message(ER_PS_MANY_PARAM, ER(ER_PS_MANY_PARAM), MYF(0)); + return TRUE; + } + Item_param **to; + List_iterator param_iterator(lex->param_list); + /* Use thd->mem_root as it points at statement mem_root */ + stmt->param_array= (Item_param **) + alloc_root(stmt->thd->mem_root, + sizeof(Item_param*) * stmt->param_count); + if (!stmt->param_array) + return TRUE; + for (to= stmt->param_array; + to < stmt->param_array + stmt->param_count; + ++to) + { + *to= param_iterator++; + } + } + return FALSE; +} + + +/** + COM_STMT_PREPARE handler. + + Given a query string with parameter markers, create a prepared + statement from it and send PS info back to the client. + + If parameter markers are found in the query, then store the information + using Item_param along with maintaining a list in lex->param_array, so + that a fast and direct retrieval can be made without going through all + field items. + + @param packet query to be prepared + @param packet_length query string length, including ignored + trailing NULL or quote char. + + @note + This function parses the query and sends the total number of parameters + and resultset metadata information back to client (if any), without + executing the query i.e. without any log/disk writes. This allows the + queries to be re-executed without re-parsing during execute. + + @return + none: in case of success a new statement id and metadata is sent + to the client, otherwise an error message is set in THD. +*/ + +void mysqld_stmt_prepare(THD *thd, const char *packet, uint packet_length) +{ + Protocol *save_protocol= thd->protocol; + Prepared_statement *stmt; + bool error; + DBUG_ENTER("mysqld_stmt_prepare"); + + DBUG_PRINT("prep_query", ("%s", packet)); + + /* First of all clear possible warnings from the previous command */ + mysql_reset_thd_for_next_command(thd); + + if (! (stmt= new Prepared_statement(thd))) + DBUG_VOID_RETURN; /* out of memory: error is set in Sql_alloc */ + + if (thd->stmt_map.insert(thd, stmt)) + { + /* + The error is set in the insert. The statement itself + will be also deleted there (this is how the hash works). + */ + DBUG_VOID_RETURN; + } + + /* Reset warnings from previous command */ + mysql_reset_errors(thd, 0); + sp_cache_flush_obsolete(&thd->sp_proc_cache); + sp_cache_flush_obsolete(&thd->sp_func_cache); + + thd->protocol= &thd->protocol_binary; + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(),QUERY_PRIOR); + + error= stmt->prepare(packet, packet_length); + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(),WAIT_PRIOR); + + if (error) + { + /* Statement map deletes statement on erase */ + thd->stmt_map.erase(stmt); + } + + thd->protocol= save_protocol; + + /* check_prepared_statemnt sends the metadata packet in case of success */ + DBUG_VOID_RETURN; +} + +/** + Get an SQL statement text from a user variable or from plain text. + + If the statement is plain text, just assign the + pointers, otherwise allocate memory in thd->mem_root and copy + the contents of the variable, possibly with character + set conversion. + + @param[in] lex main lex + @param[out] query_len length of the SQL statement (is set only + in case of success) + + @retval + non-zero success + @retval + 0 in case of error (out of memory) +*/ + +char *get_dynamic_sql_string(LEX *lex, uint *query_len) +{ + THD *thd= lex->thd; + char *query_str= 0; + + if (lex->prepared_stmt_code_is_varref) + { + /* This is PREPARE stmt FROM or EXECUTE IMMEDIATE @var. */ + String str; + CHARSET_INFO *to_cs= thd->variables.collation_connection; + bool needs_conversion; + user_var_entry *entry; + String *var_value= &str; + uint32 unused, len; + /* + Convert @var contents to string in connection character set. Although + it is known that int/real/NULL value cannot be a valid query we still + convert it for error messages to be uniform. + */ + if ((entry= + (user_var_entry*)hash_search(&thd->user_vars, + (uchar*)lex->prepared_stmt_code.str, + lex->prepared_stmt_code.length)) + && entry->value) + { + my_bool is_var_null; + var_value= entry->val_str(&is_var_null, &str, NOT_FIXED_DEC); + /* + NULL value of variable checked early as entry->value so here + we can't get NULL in normal conditions + */ + DBUG_ASSERT(!is_var_null); + if (!var_value) + goto end; + } + else + { + /* + variable absent or equal to NULL, so we need to set variable to + something reasonable to get a readable error message during parsing + */ + str.set(STRING_WITH_LEN("NULL"), &my_charset_latin1); + } + + needs_conversion= String::needs_conversion(var_value->length(), + var_value->charset(), to_cs, + &unused); + + len= (needs_conversion ? var_value->length() * to_cs->mbmaxlen : + var_value->length()); + if (!(query_str= (char*) alloc_root(thd->mem_root, len+1))) + goto end; + + if (needs_conversion) + { + uint dummy_errors; + len= copy_and_convert(query_str, len, to_cs, var_value->ptr(), + var_value->length(), var_value->charset(), + &dummy_errors); + } + else + memcpy(query_str, var_value->ptr(), var_value->length()); + query_str[len]= '\0'; // Safety (mostly for debug) + *query_len= len; + } + else + { + query_str= lex->prepared_stmt_code.str; + *query_len= lex->prepared_stmt_code.length; + } +end: + return query_str; +} + + +/** Init PS/SP specific parse tree members. */ + +static void init_stmt_after_parse(LEX *lex) +{ + SELECT_LEX *sl= lex->all_selects_list; + /* + Switch off a temporary flag that prevents evaluation of + subqueries in statement prepare. + */ + for (; sl; sl= sl->next_select_in_list()) + sl->uncacheable&= ~UNCACHEABLE_PREPARE; +} + +/** + SQLCOM_PREPARE implementation. + + Prepare an SQL prepared statement. This is called from + mysql_execute_command and should therefore behave like an + ordinary query (e.g. should not reset any global THD data). + + @param thd thread handle + + @return + none: in case of success, OK packet is sent to the client, + otherwise an error message is set in THD +*/ + +void mysql_sql_stmt_prepare(THD *thd) +{ + LEX *lex= thd->lex; + LEX_STRING *name= &lex->prepared_stmt_name; + Prepared_statement *stmt; + const char *query; + uint query_len= 0; + DBUG_ENTER("mysql_sql_stmt_prepare"); + + if ((stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name))) + { + /* + If there is a statement with the same name, remove it. It is ok to + remove old and fail to insert a new one at the same time. + */ + if (stmt->is_in_use()) + { + my_error(ER_PS_NO_RECURSION, MYF(0)); + DBUG_VOID_RETURN; + } + + stmt->deallocate(); + } + + if (! (query= get_dynamic_sql_string(lex, &query_len)) || + ! (stmt= new Prepared_statement(thd))) + { + DBUG_VOID_RETURN; /* out of memory */ + } + + stmt->set_sql_prepare(); + + /* Set the name first, insert should know that this statement has a name */ + if (stmt->set_name(name)) + { + delete stmt; + DBUG_VOID_RETURN; + } + + if (thd->stmt_map.insert(thd, stmt)) + { + /* The statement is deleted and an error is set if insert fails */ + DBUG_VOID_RETURN; + } + + if (stmt->prepare(query, query_len)) + { + /* Statement map deletes the statement on erase */ + thd->stmt_map.erase(stmt); + } + else + my_ok(thd, 0L, 0L, "Statement prepared"); + + DBUG_VOID_RETURN; +} + +/** + Reinit prepared statement/stored procedure before execution. + + @todo + When the new table structure is ready, then have a status bit + to indicate the table is altered, and re-do the setup_* + and open the tables back. +*/ + +void reinit_stmt_before_use(THD *thd, LEX *lex) +{ + SELECT_LEX *sl= lex->all_selects_list; + DBUG_ENTER("reinit_stmt_before_use"); + + /* + We have to update "thd" pointer in LEX, all its units and in LEX::result, + since statements which belong to trigger body are associated with TABLE + object and because of this can be used in different threads. + */ + lex->thd= thd; + + if (lex->empty_field_list_on_rset) + { + lex->empty_field_list_on_rset= 0; + lex->field_list.empty(); + } + for (; sl; sl= sl->next_select_in_list()) + { + if (!sl->first_execution) + { + /* remove option which was put by mysql_explain_union() */ + sl->options&= ~SELECT_DESCRIBE; + + /* see unique_table() */ + sl->exclude_from_table_unique_test= FALSE; + + /* + Copy WHERE, HAVING clause pointers to avoid damaging them + by optimisation + */ + if (sl->prep_where) + { + sl->where= sl->prep_where->copy_andor_structure(thd); + sl->where->cleanup(); + } + if (sl->prep_having) + { + sl->having= sl->prep_having->copy_andor_structure(thd); + sl->having->cleanup(); + } + DBUG_ASSERT(sl->join == 0); + ORDER *order; + /* Fix GROUP list */ + for (order= (ORDER *)sl->group_list.first; order; order= order->next) + order->item= &order->item_ptr; + /* Fix ORDER list */ + for (order= (ORDER *)sl->order_list.first; order; order= order->next) + order->item= &order->item_ptr; + } + { + SELECT_LEX_UNIT *unit= sl->master_unit(); + unit->unclean(); + unit->types.empty(); + /* for derived tables & PS (which can't be reset by Item_subquery) */ + unit->reinit_exec_mechanism(); + unit->set_thd(thd); + } + } + + /* + TODO: When the new table structure is ready, then have a status bit + to indicate the table is altered, and re-do the setup_* + and open the tables back. + */ + /* + NOTE: We should reset whole table list here including all tables added + by prelocking algorithm (it is not a problem for substatements since + they have their own table list). + */ + for (TABLE_LIST *tables= lex->query_tables; + tables; + tables= tables->next_global) + { + tables->reinit_before_use(thd); + } + /* + Cleanup of the special case of DELETE t1, t2 FROM t1, t2, t3 ... + (multi-delete). We do a full clean up, although at the moment all we + need to clean in the tables of MULTI-DELETE list is 'table' member. + */ + for (TABLE_LIST *tables= (TABLE_LIST*) lex->auxiliary_table_list.first; + tables; + tables= tables->next_global) + { + tables->reinit_before_use(thd); + } + lex->current_select= &lex->select_lex; + + /* restore original list used in INSERT ... SELECT */ + if (lex->leaf_tables_insert) + lex->select_lex.leaf_tables= lex->leaf_tables_insert; + + if (lex->result) + { + lex->result->cleanup(); + lex->result->set_thd(thd); + } + lex->allow_sum_func= 0; + lex->in_sum_func= NULL; + DBUG_VOID_RETURN; +} + + +/** + Clears parameters from data left from previous execution or long data. + + @param stmt prepared statement for which parameters should + be reset +*/ + +static void reset_stmt_params(Prepared_statement *stmt) +{ + Item_param **item= stmt->param_array; + Item_param **end= item + stmt->param_count; + for (;item < end ; ++item) + (**item).reset(); +} + + +/** + COM_STMT_EXECUTE handler: execute a previously prepared statement. + + If there are any parameters, then replace parameter markers with the + data supplied from the client, and then execute the statement. + This function uses binary protocol to send a possible result set + to the client. + + @param thd current thread + @param packet_arg parameter types and data, if any + @param packet_length packet length, including the terminator character. + + @return + none: in case of success OK packet or a result set is sent to the + client, otherwise an error message is set in THD. +*/ + +void mysqld_stmt_execute(THD *thd, char *packet_arg, uint packet_length) +{ + uchar *packet= (uchar*)packet_arg; // GCC 4.0.1 workaround + ulong stmt_id= uint4korr(packet); + ulong flags= (ulong) packet[4]; + /* Query text for binary, general or slow log, if any of them is open */ + String expanded_query; + uchar *packet_end= packet + packet_length; + Prepared_statement *stmt; + Protocol *save_protocol= thd->protocol; + bool open_cursor; + DBUG_ENTER("mysqld_stmt_execute"); + + packet+= 9; /* stmt_id + 5 bytes of flags */ + + /* First of all clear possible warnings from the previous command */ + mysql_reset_thd_for_next_command(thd); + + if (!(stmt= find_prepared_statement(thd, stmt_id))) + { + char llbuf[22]; + my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf), + llstr(stmt_id, llbuf), "mysqld_stmt_execute"); + DBUG_VOID_RETURN; + } + +#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER) + thd->profiling.set_query_source(stmt->query, stmt->query_length); +#endif + DBUG_PRINT("exec_query", ("%s", stmt->query)); + DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt)); + + sp_cache_flush_obsolete(&thd->sp_proc_cache); + sp_cache_flush_obsolete(&thd->sp_func_cache); + + open_cursor= test(flags & (ulong) CURSOR_TYPE_READ_ONLY); + + thd->protocol= &thd->protocol_binary; + stmt->execute_loop(&expanded_query, open_cursor, packet, packet_end); + thd->protocol= save_protocol; + + /* Close connection socket; for use with client testing (Bug#43560). */ + DBUG_EXECUTE_IF("close_conn_after_stmt_execute", vio_close(thd->net.vio);); + + DBUG_VOID_RETURN; + +} + + +/** + SQLCOM_EXECUTE implementation. + + Execute prepared statement using parameter values from + lex->prepared_stmt_params and send result to the client using + text protocol. This is called from mysql_execute_command and + therefore should behave like an ordinary query (e.g. not change + global THD data, such as warning count, server status, etc). + This function uses text protocol to send a possible result set. + + @param thd thread handle + + @return + none: in case of success, OK (or result set) packet is sent to the + client, otherwise an error is set in THD +*/ + +void mysql_sql_stmt_execute(THD *thd) +{ + LEX *lex= thd->lex; + Prepared_statement *stmt; + LEX_STRING *name= &lex->prepared_stmt_name; + /* Query text for binary, general or slow log, if any of them is open */ + String expanded_query; + DBUG_ENTER("mysql_sql_stmt_execute"); + DBUG_PRINT("info", ("EXECUTE: %.*s\n", (int) name->length, name->str)); + + if (!(stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name))) + { + my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), + name->length, name->str, "EXECUTE"); + DBUG_VOID_RETURN; + } + + if (stmt->param_count != lex->prepared_stmt_params.elements) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE"); + DBUG_VOID_RETURN; + } + + DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt)); + + (void) stmt->execute_loop(&expanded_query, FALSE, NULL, NULL); + + DBUG_VOID_RETURN; +} + + +/** + COM_STMT_FETCH handler: fetches requested amount of rows from cursor. + + @param thd Thread handle + @param packet Packet from client (with stmt_id & num_rows) + @param packet_length Length of packet +*/ + +void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length) +{ + /* assume there is always place for 8-16 bytes */ + ulong stmt_id= uint4korr(packet); + ulong num_rows= uint4korr(packet+4); + Prepared_statement *stmt; + Statement stmt_backup; + Server_side_cursor *cursor; + DBUG_ENTER("mysqld_stmt_fetch"); + + /* First of all clear possible warnings from the previous command */ + mysql_reset_thd_for_next_command(thd); + status_var_increment(thd->status_var.com_stmt_fetch); + if (!(stmt= find_prepared_statement(thd, stmt_id))) + { + char llbuf[22]; + my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf), + llstr(stmt_id, llbuf), "mysqld_stmt_fetch"); + DBUG_VOID_RETURN; + } + + cursor= stmt->cursor; + if (!cursor) + { + my_error(ER_STMT_HAS_NO_OPEN_CURSOR, MYF(0), stmt_id); + DBUG_VOID_RETURN; + } + + thd->stmt_arena= stmt; + thd->set_n_backup_statement(stmt, &stmt_backup); + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(), QUERY_PRIOR); + + cursor->fetch(num_rows); + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(), WAIT_PRIOR); + + if (!cursor->is_open()) + { + stmt->close_cursor(); + thd->cursor= 0; + reset_stmt_params(stmt); + } + + thd->restore_backup_statement(stmt, &stmt_backup); + thd->stmt_arena= thd; + + DBUG_VOID_RETURN; +} + + +/** + Reset a prepared statement in case there was a recoverable error. + + This function resets statement to the state it was right after prepare. + It can be used to: + - clear an error happened during mysqld_stmt_send_long_data + - cancel long data stream for all placeholders without + having to call mysqld_stmt_execute. + - close an open cursor + Sends 'OK' packet in case of success (statement was reset) + or 'ERROR' packet (unrecoverable error/statement not found/etc). + + @param thd Thread handle + @param packet Packet with stmt id +*/ + +void mysqld_stmt_reset(THD *thd, char *packet) +{ + /* There is always space for 4 bytes in buffer */ + ulong stmt_id= uint4korr(packet); + Prepared_statement *stmt; + DBUG_ENTER("mysqld_stmt_reset"); + + /* First of all clear possible warnings from the previous command */ + mysql_reset_thd_for_next_command(thd); + + status_var_increment(thd->status_var.com_stmt_reset); + if (!(stmt= find_prepared_statement(thd, stmt_id))) + { + char llbuf[22]; + my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf), + llstr(stmt_id, llbuf), "mysqld_stmt_reset"); + DBUG_VOID_RETURN; + } + + stmt->close_cursor(); + + /* + Clear parameters from data which could be set by + mysqld_stmt_send_long_data() call. + */ + reset_stmt_params(stmt); + + stmt->state= Query_arena::PREPARED; + + general_log_print(thd, thd->command, NullS); + + my_ok(thd); + + DBUG_VOID_RETURN; +} + + +/** + Delete a prepared statement from memory. + + @note + we don't send any reply to this command. +*/ + +void mysqld_stmt_close(THD *thd, char *packet) +{ + /* There is always space for 4 bytes in packet buffer */ + ulong stmt_id= uint4korr(packet); + Prepared_statement *stmt; + DBUG_ENTER("mysqld_stmt_close"); + + thd->main_da.disable_status(); + + if (!(stmt= find_prepared_statement(thd, stmt_id))) + DBUG_VOID_RETURN; + + /* + The only way currently a statement can be deallocated when it's + in use is from within Dynamic SQL. + */ + // @InfiniDB relax the assertion for vtable create + //if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) + // DBUG_ASSERT(! stmt->is_in_use()); + stmt->deallocate(); + general_log_print(thd, thd->command, NullS); + + DBUG_VOID_RETURN; +} + + +/** + SQLCOM_DEALLOCATE implementation. + + Close an SQL prepared statement. As this can be called from Dynamic + SQL, we should be careful to not close a statement that is currently + being executed. + + @return + none: OK packet is sent in case of success, otherwise an error + message is set in THD +*/ + +void mysql_sql_stmt_close(THD *thd) +{ + Prepared_statement* stmt; + LEX_STRING *name= &thd->lex->prepared_stmt_name; + DBUG_PRINT("info", ("DEALLOCATE PREPARE: %.*s\n", (int) name->length, + name->str)); + + if (! (stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name))) + my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), + name->length, name->str, "DEALLOCATE PREPARE"); + else if (stmt->is_in_use()) + my_error(ER_PS_NO_RECURSION, MYF(0)); + else + { + stmt->deallocate(); + my_ok(thd); + } +} + +/** + Handle long data in pieces from client. + + Get a part of a long data. To make the protocol efficient, we are + not sending any return packets here. If something goes wrong, then + we will send the error on 'execute' We assume that the client takes + care of checking that all parts are sent to the server. (No checking + that we get a 'end of column' in the server is performed). + + @param thd Thread handle + @param packet String to append + @param packet_length Length of string (including end \\0) +*/ + +void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length) +{ + ulong stmt_id; + uint param_number; + Prepared_statement *stmt; + Item_param *param; +#ifndef EMBEDDED_LIBRARY + char *packet_end= packet + packet_length; +#endif + DBUG_ENTER("mysql_stmt_get_longdata"); + + status_var_increment(thd->status_var.com_stmt_send_long_data); + + thd->main_da.disable_status(); +#ifndef EMBEDDED_LIBRARY + /* Minimal size of long data packet is 6 bytes */ + if (packet_length < MYSQL_LONG_DATA_HEADER) + DBUG_VOID_RETURN; +#endif + + stmt_id= uint4korr(packet); + packet+= 4; + + if (!(stmt=find_prepared_statement(thd, stmt_id))) + DBUG_VOID_RETURN; + + param_number= uint2korr(packet); + packet+= 2; +#ifndef EMBEDDED_LIBRARY + if (param_number >= stmt->param_count) + { + /* Error will be sent in execute call */ + stmt->state= Query_arena::ERROR; + stmt->last_errno= ER_WRONG_ARGUMENTS; + sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS), + "mysqld_stmt_send_long_data"); + DBUG_VOID_RETURN; + } +#endif + + param= stmt->param_array[param_number]; + +#ifndef EMBEDDED_LIBRARY + if (param->set_longdata(packet, (ulong) (packet_end - packet))) +#else + if (param->set_longdata(thd->extra_data, thd->extra_length)) +#endif + { + stmt->state= Query_arena::ERROR; + stmt->last_errno= ER_OUTOFMEMORY; + sprintf(stmt->last_error, ER(ER_OUTOFMEMORY), 0); + } + + general_log_print(thd, thd->command, NullS); + + DBUG_VOID_RETURN; +} + + +/*************************************************************************** + Select_fetch_protocol_binary +****************************************************************************/ + +Select_fetch_protocol_binary::Select_fetch_protocol_binary(THD *thd_arg) + :protocol(thd_arg) +{} + +bool Select_fetch_protocol_binary::send_fields(List &list, uint flags) +{ + bool rc; + Protocol *save_protocol= thd->protocol; + + /* + Protocol::send_fields caches the information about column types: + this information is later used to send data. Therefore, the same + dedicated Protocol object must be used for all operations with + a cursor. + */ + thd->protocol= &protocol; + rc= select_send::send_fields(list, flags); + thd->protocol= save_protocol; + + return rc; +} + +bool Select_fetch_protocol_binary::send_eof() +{ + ::my_eof(thd); + return FALSE; +} + + +bool +Select_fetch_protocol_binary::send_data(List &fields) +{ + Protocol *save_protocol= thd->protocol; + bool rc; + + thd->protocol= &protocol; + rc= select_send::send_data(fields); + thd->protocol= save_protocol; + return rc; +} + +/*************************************************************************** + Prepared_statement +****************************************************************************/ + +Prepared_statement::Prepared_statement(THD *thd_arg) + :Statement(NULL, &main_mem_root, + INITIALIZED, ++thd_arg->statement_id_counter), + thd(thd_arg), + result(thd_arg), + param_array(0), + param_count(0), + last_errno(0), + flags((uint) IS_IN_USE), + m_sp_cache_version(0) +{ + init_sql_alloc(&main_mem_root, thd_arg->variables.query_alloc_block_size, + thd_arg->variables.query_prealloc_size); + *last_error= '\0'; +} + + +void Prepared_statement::setup_set_params() +{ + /* + Note: BUG#25843 applies here too (query cache lookup uses thd->db, not + db from "prepare" time). + */ + if (query_cache_maybe_disabled(thd)) // we won't expand the query + lex->safe_to_cache_query= FALSE; // so don't cache it at Execution + + /* + Decide if we have to expand the query (because we must write it to logs or + because we want to look it up in the query cache) or not. + */ + if ((mysql_bin_log.is_open() && is_update_query(lex->sql_command)) || + opt_log || opt_slow_log || + query_cache_is_cacheable_query(lex)) + { + set_params_from_vars= insert_params_from_vars_with_log; +#ifndef EMBEDDED_LIBRARY + set_params= insert_params_with_log; +#else + set_params_data= emb_insert_params_with_log; +#endif + } + else + { + set_params_from_vars= insert_params_from_vars; +#ifndef EMBEDDED_LIBRARY + set_params= insert_params; +#else + set_params_data= emb_insert_params; +#endif + } +} + + +/** + Destroy this prepared statement, cleaning up all used memory + and resources. + + This is called from ::deallocate() to handle COM_STMT_CLOSE and + DEALLOCATE PREPARE or when THD ends and all prepared statements are freed. +*/ + +Prepared_statement::~Prepared_statement() +{ + DBUG_ENTER("Prepared_statement::~Prepared_statement"); + DBUG_PRINT("enter",("stmt: 0x%lx cursor: 0x%lx", + (long) this, (long) cursor)); + delete cursor; + /* + We have to call free on the items even if cleanup is called as some items, + like Item_param, don't free everything until free_items() + */ + free_items(); + if (lex) + { + delete lex->result; + delete (st_lex_local *) lex; + } + free_root(&main_mem_root, MYF(0)); + DBUG_VOID_RETURN; +} + + +Query_arena::Type Prepared_statement::type() const +{ + return PREPARED_STATEMENT; +} + + +void Prepared_statement::cleanup_stmt() +{ + DBUG_ENTER("Prepared_statement::cleanup_stmt"); + DBUG_PRINT("enter",("stmt: 0x%lx", (long) this)); + + DBUG_ASSERT(lex->sphead == 0); + /* The order is important */ + lex->unit.cleanup(); + cleanup_items(free_list); + thd->cleanup_after_query(); + close_thread_tables(thd); + thd->rollback_item_tree_changes(); + + DBUG_VOID_RETURN; +} + + +bool Prepared_statement::set_name(LEX_STRING *name_arg) +{ + name.length= name_arg->length; + name.str= (char*) memdup_root(mem_root, name_arg->str, name_arg->length); + return name.str == 0; +} + + +/** + Remember the current database. + + We must reset/restore the current database during execution of + a prepared statement since it affects execution environment: + privileges, @@character_set_database, and other. + + @return Returns an error if out of memory. +*/ + +bool +Prepared_statement::set_db(const char *db_arg, uint db_length_arg) +{ + /* Remember the current database. */ + if (db_arg && db_length_arg) + { + db= this->strmake(db_arg, db_length_arg); + db_length= db_length_arg; + } + else + { + db= NULL; + db_length= 0; + } + return db_arg != NULL && db == NULL; +} + +/************************************************************************** + Common parts of mysql_[sql]_stmt_prepare, mysql_[sql]_stmt_execute. + Essentially, these functions do all the magic of preparing/executing + a statement, leaving network communication, input data handling and + global THD state management to the caller. +***************************************************************************/ + +/** + Parse statement text, validate the statement, and prepare it for execution. + + You should not change global THD state in this function, if at all + possible: it may be called from any context, e.g. when executing + a COM_* command, and SQLCOM_* command, or a stored procedure. + + @param packet statement text + @param packet_len + + @note + Precondition: + The caller must ensure that thd->change_list and thd->free_list + is empty: this function will not back them up but will free + in the end of its execution. + + @note + Postcondition: + thd->mem_root contains unused memory allocated during validation. +*/ + +bool Prepared_statement::prepare(const char *packet, uint packet_len) +{ + bool error; + Statement stmt_backup; + Query_arena *old_stmt_arena; + DBUG_ENTER("Prepared_statement::prepare"); + /* + If this is an SQLCOM_PREPARE, we also increase Com_prepare_sql. + However, it seems handy if com_stmt_prepare is increased always, + no matter what kind of prepare is processed. + */ + status_var_increment(thd->status_var.com_stmt_prepare); + + if (! (lex= new (mem_root) st_lex_local)) + DBUG_RETURN(TRUE); + + if (set_db(thd->db, thd->db_length)) + DBUG_RETURN(TRUE); + + /* + alloc_query() uses thd->memroot && thd->query, so we should call + both of backup_statement() and backup_query_arena() here. + */ + thd->set_n_backup_statement(this, &stmt_backup); + thd->set_n_backup_active_arena(this, &stmt_backup); + + if (alloc_query(thd, packet, packet_len)) + { + thd->restore_backup_statement(this, &stmt_backup); + thd->restore_active_arena(this, &stmt_backup); + DBUG_RETURN(TRUE); + } + + old_stmt_arena= thd->stmt_arena; + thd->stmt_arena= this; + + Parser_state parser_state(thd, thd->query, thd->query_length); + parser_state.m_lip.stmt_prepare_mode= TRUE; + lex_start(thd); + + error= parse_sql(thd, & parser_state, NULL) || + thd->is_error() || + init_param_array(this); + + lex->set_trg_event_type_for_tables(); + + /* + While doing context analysis of the query (in check_prepared_statement) + we allocate a lot of additional memory: for open tables, JOINs, derived + tables, etc. Let's save a snapshot of current parse tree to the + statement and restore original THD. In cases when some tree + transformation can be reused on execute, we set again thd->mem_root from + stmt->mem_root (see setup_wild for one place where we do that). + */ + thd->restore_active_arena(this, &stmt_backup); + + /* + If called from a stored procedure, ensure that we won't rollback + external changes when cleaning up after validation. + */ + DBUG_ASSERT(thd->change_list.is_empty()); + + /* + The only case where we should have items in the thd->free_list is + after stmt->set_params_from_vars(), which may in some cases create + Item_null objects. + */ + + if (error == 0) + error= check_prepared_statement(this); + + /* + Currently CREATE PROCEDURE/TRIGGER/EVENT are prohibited in prepared + statements: ensure we have no memory leak here if by someone tries + to PREPARE stmt FROM "CREATE PROCEDURE ..." + */ + DBUG_ASSERT(lex->sphead == NULL || error != 0); + if (lex->sphead) + { + delete lex->sphead; + lex->sphead= NULL; + } + + lex_end(lex); + cleanup_stmt(); + thd->restore_backup_statement(this, &stmt_backup); + thd->stmt_arena= old_stmt_arena; + + if (error == 0) + { + setup_set_params(); + init_stmt_after_parse(lex); + state= Query_arena::PREPARED; + flags&= ~ (uint) IS_IN_USE; + /* + This is for prepared statement validation purposes. + A statement looks up and pre-loads all its stored functions + at prepare. Later on, if a function is gone from the cache, + execute may fail. + Remember the cache version to be able to invalidate the prepared + statement at execute if it changes. + We only need to care about version of the stored functions cache: + if a prepared statement uses a stored procedure, it's indirect, + via a stored function. The only exception is SQLCOM_CALL, + but the latter one looks up the stored procedure each time + it's invoked, rather than once at prepare. + */ + m_sp_cache_version= sp_cache_version(&thd->sp_func_cache); + + /* + Log COM_EXECUTE to the general log. Note, that in case of SQL + prepared statements this causes two records to be output: + + Query PREPARE stmt from @user_variable + Prepare + + This is considered user-friendly, since in the + second log entry we output the actual statement text. + + Do not print anything if this is an SQL prepared statement and + we're inside a stored procedure (also called Dynamic SQL) -- + sub-statements inside stored procedures are not logged into + the general log. + */ + if (thd->spcont == NULL) + general_log_write(thd, COM_STMT_PREPARE, query, query_length); + } + DBUG_RETURN(error); +} + +void +Prepared_statement::close_cursor() +{ delete cursor; cursor= 0; } +/** + Assign parameter values either from variables, in case of SQL PS + or from the execute packet. + + @param expanded_query a container with the original SQL statement. + '?' placeholders will be replaced with + their values in case of success. + The result is used for logging and replication + @param packet pointer to execute packet. + NULL in case of SQL PS + @param packet_end end of the packet. NULL in case of SQL PS + + @todo Use a paremeter source class family instead of 'if's, and + support stored procedure variables. + + @retval TRUE an error occurred when assigning a parameter (likely + a conversion error or out of memory, or malformed packet) + @retval FALSE success +*/ + +bool +Prepared_statement::set_parameters(String *expanded_query, + uchar *packet, uchar *packet_end) +{ + bool is_sql_ps= packet == NULL; + bool res= FALSE; + + if (is_sql_ps) + { + /* SQL prepared statement */ + res= set_params_from_vars(this, thd->lex->prepared_stmt_params, + expanded_query); + } + else if (param_count) + { +#ifndef EMBEDDED_LIBRARY + uchar *null_array= packet; + res= (setup_conversion_functions(this, &packet, packet_end) || + set_params(this, null_array, packet, packet_end, expanded_query)); +#else + /* + In embedded library we re-install conversion routines each time + we set parameters, and also we don't need to parse packet. + So we do it in one function. + */ + res= set_params_data(this, expanded_query); +#endif + } + if (res) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), + is_sql_ps ? "EXECUTE" : "mysqld_stmt_execute"); + reset_stmt_params(this); + } + return res; +} + + +/** + Execute a prepared statement. Re-prepare it a limited number + of times if necessary. + + Try to execute a prepared statement. If there is a metadata + validation error, prepare a new copy of the prepared statement, + swap the old and the new statements, and try again. + If there is a validation error again, repeat the above, but + perform no more than MAX_REPREPARE_ATTEMPTS. + + @note We have to try several times in a loop since we + release metadata locks on tables after prepared statement + prepare. Therefore, a DDL statement may sneak in between prepare + and execute of a new statement. If this happens repeatedly + more than MAX_REPREPARE_ATTEMPTS times, we give up. + + In future we need to be able to keep the metadata locks between + prepare and execute, but right now open_and_lock_tables(), as + well as close_thread_tables() are buried deep inside + execution code (mysql_execute_command()). + + @return TRUE if an error, FALSE if success + @retval TRUE either MAX_REPREPARE_ATTEMPTS has been reached, + or some general error + @retval FALSE successfully executed the statement, perhaps + after having reprepared it a few times. +*/ + +bool +Prepared_statement::execute_loop(String *expanded_query, + bool open_cursor, + uchar *packet, + uchar *packet_end) +{ + const int MAX_REPREPARE_ATTEMPTS= 3; + Reprepare_observer reprepare_observer; + bool error; + int reprepare_attempt= 0; + + if (set_parameters(expanded_query, packet, packet_end)) + return TRUE; + +reexecute: + reprepare_observer.reset_reprepare_observer(); + + /* + If the free_list is not empty, we'll wrongly free some externally + allocated items when cleaning up after validation of the prepared + statement. + */ + DBUG_ASSERT(thd->free_list == NULL); + + /* + Install the metadata observer. If some metadata version is + different from prepare time and an observer is installed, + the observer method will be invoked to push an error into + the error stack. + */ + if (sql_command_flags[lex->sql_command] & + CF_REEXECUTION_FRAGILE) + { + DBUG_ASSERT(thd->m_reprepare_observer == NULL); + thd->m_reprepare_observer = &reprepare_observer; + } + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(),QUERY_PRIOR); + + error= execute(expanded_query, open_cursor) || thd->is_error(); + + if (!(specialflag & SPECIAL_NO_PRIOR)) + my_pthread_setprio(pthread_self(), WAIT_PRIOR); + + thd->m_reprepare_observer= NULL; + + if (error && !thd->is_fatal_error && !thd->killed && + reprepare_observer.is_invalidated() && + reprepare_attempt++ < MAX_REPREPARE_ATTEMPTS) + { + DBUG_ASSERT(thd->main_da.sql_errno() == ER_NEED_REPREPARE); + thd->clear_error(); + + error= reprepare(); + + if (! error) /* Success */ + goto reexecute; + } + reset_stmt_params(this); + + return error; +} + + +/** + Reprepare this prepared statement. + + Currently this is implemented by creating a new prepared + statement, preparing it with the original query and then + swapping the new statement and the original one. + + @retval TRUE an error occurred. Possible errors include + incompatibility of new and old result set + metadata + @retval FALSE success, the statement has been reprepared +*/ + +bool +Prepared_statement::reprepare() +{ + char saved_cur_db_name_buf[NAME_LEN+1]; + LEX_STRING saved_cur_db_name= + { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) }; + LEX_STRING stmt_db_name= { db, db_length }; + bool cur_db_changed; + bool error; + + Prepared_statement copy(thd); + + copy.set_sql_prepare(); /* To suppress sending metadata to the client. */ + + status_var_increment(thd->status_var.com_stmt_reprepare); + + if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE, + &cur_db_changed)) + return TRUE; + + error= ((name.str && copy.set_name(&name)) || + copy.prepare(query, query_length) || + validate_metadata(©)); + + if (cur_db_changed) + mysql_change_db(thd, &saved_cur_db_name, TRUE); + + if (! error) + { + swap_prepared_statement(©); + swap_parameter_array(param_array, copy.param_array, param_count); +#ifndef DBUG_OFF + is_reprepared= TRUE; +#endif + /* + Clear possible warnings during reprepare, it has to be completely + transparent to the user. We use mysql_reset_errors() since + there were no separate query id issued for re-prepare. + Sic: we can't simply silence warnings during reprepare, because if + it's failed, we need to return all the warnings to the user. + */ + mysql_reset_errors(thd, TRUE); + } + return error; +} + + +/** + Validate statement result set metadata (if the statement returns + a result set). + + Currently we only check that the number of columns of the result + set did not change. + This is a helper method used during re-prepare. + + @param[in] copy the re-prepared prepared statement to verify + the metadata of + + @retval TRUE error, ER_PS_REBIND is reported + @retval FALSE statement return no or compatible metadata +*/ + + +bool Prepared_statement::validate_metadata(Prepared_statement *copy) +{ + /** + If this is an SQL prepared statement or EXPLAIN, + return FALSE -- the metadata of the original SELECT, + if any, has not been sent to the client. + */ + if (is_sql_prepare() || lex->describe) + return FALSE; + + if (lex->select_lex.item_list.elements != + copy->lex->select_lex.item_list.elements) + { + /** Column counts mismatch, update the client */ + thd->server_status|= SERVER_STATUS_METADATA_CHANGED; + } + + return FALSE; +} + + +/** + Replace the original prepared statement with a prepared copy. + + This is a private helper that is used as part of statement + reprepare + + @return This function does not return any errors. +*/ + +void +Prepared_statement::swap_prepared_statement(Prepared_statement *copy) +{ + Statement tmp_stmt; + + /* Swap memory roots. */ + swap_variables(MEM_ROOT, main_mem_root, copy->main_mem_root); + + /* Swap the arenas */ + tmp_stmt.set_query_arena(this); + set_query_arena(copy); + copy->set_query_arena(&tmp_stmt); + + /* Swap the statement parent classes */ + tmp_stmt.set_statement(this); + set_statement(copy); + copy->set_statement(&tmp_stmt); + + /* Swap ids back, we need the original id */ + swap_variables(ulong, id, copy->id); + /* Swap mem_roots back, they must continue pointing at the main_mem_roots */ + swap_variables(MEM_ROOT *, mem_root, copy->mem_root); + /* + Swap the old and the new parameters array. The old array + is allocated in the old arena. + */ + swap_variables(Item_param **, param_array, copy->param_array); + /* Swap flags: this is perhaps unnecessary */ + swap_variables(uint, flags, copy->flags); + /* Swap names, the old name is allocated in the wrong memory root */ + swap_variables(LEX_STRING, name, copy->name); + /* Ditto */ + swap_variables(char *, db, copy->db); + swap_variables(ulong, m_sp_cache_version, copy->m_sp_cache_version); + + DBUG_ASSERT(db_length == copy->db_length); + DBUG_ASSERT(param_count == copy->param_count); + DBUG_ASSERT(thd == copy->thd); + last_error[0]= '\0'; + last_errno= 0; +} + + +/** + Execute a prepared statement. + + You should not change global THD state in this function, if at all + possible: it may be called from any context, e.g. when executing + a COM_* command, and SQLCOM_* command, or a stored procedure. + + @param expanded_query A query for binlogging which has all parameter + markers ('?') replaced with their actual values. + @param open_cursor True if an attempt to open a cursor should be made. + Currenlty used only in the binary protocol. + + @note + Preconditions, postconditions. + - See the comment for Prepared_statement::prepare(). + + @retval + FALSE ok + @retval + TRUE Error +*/ + +bool Prepared_statement::execute(String *expanded_query, bool open_cursor) +{ + Statement stmt_backup; + Query_arena *old_stmt_arena; + bool error= TRUE; + + // @InfiniDB check infinidb table + TABLE_LIST* global_list = NULL; + bool hasCalpont = FALSE; + + char saved_cur_db_name_buf[NAME_LEN+1]; + LEX_STRING saved_cur_db_name= + { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) }; + bool cur_db_changed; + + LEX_STRING stmt_db_name= { db, db_length }; + + status_var_increment(thd->status_var.com_stmt_execute); + + /* Check if we got an error when sending long data */ + if (state == Query_arena::ERROR) + { + my_message(last_errno, last_error, MYF(0)); + return TRUE; + } + if (flags & (uint) IS_IN_USE) + { + my_error(ER_PS_NO_RECURSION, MYF(0)); + return TRUE; + } + + /* + Reprepare the statement if we're using stored functions + and the version of the stored routines cache has changed. + */ + if (lex->uses_stored_routines() && + m_sp_cache_version != sp_cache_version(&thd->sp_func_cache) && + thd->m_reprepare_observer && + thd->m_reprepare_observer->report_error(thd)) + { + return TRUE; + } + + + /* + For SHOW VARIABLES lex->result is NULL, as it's a non-SELECT + command. For such queries we don't return an error and don't + open a cursor -- the client library will recognize this case and + materialize the result set. + For SELECT statements lex->result is created in + check_prepared_statement. lex->result->simple_select() is FALSE + in INSERT ... SELECT and similar commands. + */ + + if (open_cursor && lex->result && lex->result->check_simple_select()) + { + DBUG_PRINT("info",("Cursor asked for not SELECT stmt")); + return TRUE; + } + + /* In case the command has a call to SP which re-uses this statement name */ + flags|= IS_IN_USE; + + close_cursor(); + + /* + If the free_list is not empty, we'll wrongly free some externally + allocated items when cleaning up after execution of this statement. + */ + DBUG_ASSERT(thd->change_list.is_empty()); + + /* + The only case where we should have items in the thd->free_list is + after stmt->set_params_from_vars(), which may in some cases create + Item_null objects. + */ + + thd->set_n_backup_statement(this, &stmt_backup); + + /* + Change the current database (if needed). + + Force switching, because the database of the prepared statement may be + NULL (prepared statements can be created while no current database + selected). + */ + + if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE, + &cur_db_changed)) + goto error; + + /* Allocate query. */ + + if (expanded_query->length() && + alloc_query(thd, (char*) expanded_query->ptr(), + expanded_query->length())) + { + my_error(ER_OUTOFMEMORY, 0, expanded_query->length()); + goto error; + } + + // @infinidb. vtable process around stmt_execute. + // @bug3742. mysqli php support for prepare/execute stmt + // @bug4833. the state checking will be done inside idb_vtable_process() function + // check infinidb table + // @bug2976. Check global tables for IDB table. If no IDB tables involved, redo this query with normal path. + // @bug5111. Skip InfiniDB process for queries without InfiniDB tables. + if (thd && thd->lex) + global_list = thd->lex->query_tables; + for (; global_list; global_list = global_list->next_global) + { + if (!(global_list->table && global_list->table->s && global_list->table->s->db_plugin)) + continue; + // @InfiniDB watch out for FROM clause derived table. union memeory table has tablename="union" + if (global_list->table && global_list->table->isInfiniDB()) + { + hasCalpont = true; + continue; + } +#if (defined(_MSC_VER) && defined(_DEBUG)) || defined(SAFE_MUTEX) + else if (global_list->table && + global_list->table->s && + global_list->table->s->db_plugin && + strcmp((*global_list->table->s->db_plugin)->name.str, "MEMORY") == 0 || + global_list->table->s->table_category == TABLE_CATEGORY_TEMPORARY) +#else + else if (global_list->table && + global_list->table->s && + global_list->table->s->db_plugin && + strcmp(global_list->table->s->db_plugin->name.str, "MEMORY") == 0 || + global_list->table->s->table_category == TABLE_CATEGORY_TEMPORARY) +#endif + { + continue; + } + } + + if (hasCalpont && thd->command == COM_STMT_EXECUTE) + { + // @bug5298. disable re-prepare observer for infinidb query + thd->m_reprepare_observer = NULL; + + if (thd->lex) + thd->lex->result = 0; + // @bug5962. reset the in_use flag so the prepared stmt + // can be executed again in IDB. + //flags|= IS_IN_USE; + flags&= ~ (uint) IS_IN_USE; + + if (idb_vtable_process(thd, this)) // if failed, fall through to normal path + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_DISABLE_VTABLE; + } + else + { + thd->set_statement(&stmt_backup); + return false; + } + } + + /* + Expanded query is needed for slow logging, so we want thd->query + to point at it even after we restore from backup. This is ok, as + expanded query was allocated in thd->mem_root. + */ + stmt_backup.query= thd->query; + stmt_backup.query_length= thd->query_length; + + /* + At first execution of prepared statement we may perform logical + transformations of the query tree. Such changes should be performed + on the parse tree of current prepared statement and new items should + be allocated in its memory root. Set the appropriate pointer in THD + to the arena of the statement. + */ + old_stmt_arena= thd->stmt_arena; + thd->stmt_arena= this; + reinit_stmt_before_use(thd, lex); + + /* Go! */ + + if (open_cursor) + error= mysql_open_cursor(thd, (uint) ALWAYS_MATERIALIZED_CURSOR, + &result, &cursor); + else + { + /* + Try to find it in the query cache, if not, execute it. + Note that multi-statements cannot exist here (they are not supported in + prepared statements). + */ + if (query_cache_send_result_to_client(thd, thd->query, + thd->query_length) <= 0) + { + error= mysql_execute_command(thd); + } + } + + /* + Restore the current database (if changed). + + Force switching back to the saved current database (if changed), + because it may be NULL. In this case, mysql_change_db() would generate + an error. + */ + + if (cur_db_changed) + mysql_change_db(thd, &saved_cur_db_name, TRUE); + + /* Assert that if an error, no cursor is open */ + DBUG_ASSERT(! (error && cursor)); + + if (! cursor) + cleanup_stmt(); + + thd->set_statement(&stmt_backup); + thd->stmt_arena= old_stmt_arena; + + if (state == Query_arena::PREPARED) + state= Query_arena::EXECUTED; + + /* + Log COM_EXECUTE to the general log. Note, that in case of SQL + prepared statements this causes two records to be output: + + Query EXECUTE + Execute + + This is considered user-friendly, since in the + second log entry we output values of parameter markers. + + Do not print anything if this is an SQL prepared statement and + we're inside a stored procedure (also called Dynamic SQL) -- + sub-statements inside stored procedures are not logged into + the general log. + */ + if (error == 0 && thd->spcont == NULL) + general_log_write(thd, COM_STMT_EXECUTE, thd->query, thd->query_length); + +error: + flags&= ~ (uint) IS_IN_USE; + return error; +} + + +/** Common part of DEALLOCATE PREPARE and mysqld_stmt_close. */ + +void Prepared_statement::deallocate() +{ + /* We account deallocate in the same manner as mysqld_stmt_close */ + status_var_increment(thd->status_var.com_stmt_close); + /* Statement map calls delete stmt on erase */ + thd->stmt_map.erase(this); +} diff --git a/dbcon/mysql/sql_select.cc b/dbcon/mysql/sql_select.cc new file mode 100644 index 00000000..eb8dfc86 --- /dev/null +++ b/dbcon/mysql/sql_select.cc @@ -0,0 +1,16975 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/** + @file + + @brief + mysql_select and join optimization + + + @defgroup Query_Optimizer Query Optimizer + @{ +*/ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation // gcc: Class implementation +#endif + +#include "iostream" +#include "mysql_priv.h" +#include "sql_select.h" +#include "sql_cursor.h" + +#include +#include +#include +#include + +const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref", + "MAYBE_REF","ALL","range","index","fulltext", + "ref_or_null","unique_subquery","index_subquery", + "index_merge" +}; + +struct st_sargable_param; + +static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array); +static bool make_join_statistics(JOIN *join, TABLE_LIST *leaves, COND *conds, + DYNAMIC_ARRAY *keyuse); +static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse, + JOIN_TAB *join_tab, + uint tables, COND *conds, + COND_EQUAL *cond_equal, + table_map table_map, SELECT_LEX *select_lex, + st_sargable_param **sargables); +static int sort_keyuse(KEYUSE *a,KEYUSE *b); +static void set_position(JOIN *join,uint index,JOIN_TAB *table,KEYUSE *key); +static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse, + table_map used_tables); +static bool choose_plan(JOIN *join,table_map join_tables); + +static void best_access_path(JOIN *join, JOIN_TAB *s, THD *thd, + table_map remaining_tables, uint idx, + double record_count, double read_time); +static void optimize_straight_join(JOIN *join, table_map join_tables); +static bool greedy_search(JOIN *join, table_map remaining_tables, + uint depth, uint prune_level); +static bool best_extension_by_limited_search(JOIN *join, + table_map remaining_tables, + uint idx, double record_count, + double read_time, uint depth, + uint prune_level); +static uint determine_search_depth(JOIN* join); +static int join_tab_cmp(const void* ptr1, const void* ptr2); +static int join_tab_cmp_straight(const void* ptr1, const void* ptr2); +/* + TODO: 'find_best' is here only temporarily until 'greedy_search' is + tested and approved. +*/ +static bool find_best(JOIN *join,table_map rest_tables,uint index, + double record_count,double read_time); +static uint cache_record_length(JOIN *join,uint index); +static double prev_record_reads(JOIN *join, uint idx, table_map found_ref); +static bool get_best_combination(JOIN *join); +static store_key *get_store_key(THD *thd, + KEYUSE *keyuse, table_map used_tables, + KEY_PART_INFO *key_part, uchar *key_buff, + uint maybe_null); +static void make_outerjoin_info(JOIN *join); +static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item); +static void make_join_readinfo(JOIN *join, ulonglong options); +static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables); +static void update_depend_map(JOIN *join); +static void update_depend_map(JOIN *join, ORDER *order); +static ORDER *remove_const(JOIN *join,ORDER *first_order,COND *cond, + bool change_list, bool *simple_order); +static int return_zero_rows(JOIN *join, select_result *res,TABLE_LIST *tables, + List &fields, bool send_row, + ulonglong select_options, const char *info, + Item *having); +static COND *build_equal_items(THD *thd, COND *cond, + COND_EQUAL *inherited, + List *join_list, + COND_EQUAL **cond_equal_ref); +static COND* substitute_for_best_equal_field(COND *cond, + COND_EQUAL *cond_equal, + void *table_join_idx); +static COND *simplify_joins(JOIN *join, List *join_list, + COND *conds, bool top); +static bool check_interleaving_with_nj(JOIN_TAB *next); +static void restore_prev_nj_state(JOIN_TAB *last); +static void reset_nj_counters(List *join_list); +static uint build_bitmap_for_nested_joins(List *join_list, + uint first_unused); + +static COND *optimize_cond(JOIN *join, COND *conds, + List *join_list, + Item::cond_result *cond_value); +static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item); +static bool open_tmp_table(TABLE *table); +static bool create_myisam_tmp_table(TABLE *table,TMP_TABLE_PARAM *param, + ulonglong options); +static int do_select(JOIN *join,List *fields,TABLE *tmp_table, + Procedure *proc); + +static enum_nested_loop_state +evaluate_join_record(JOIN *join, JOIN_TAB *join_tab, + int error); +static enum_nested_loop_state +evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab); +static enum_nested_loop_state +flush_cached_records(JOIN *join, JOIN_TAB *join_tab, bool skip_last); +static enum_nested_loop_state +end_send(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); +static enum_nested_loop_state +end_send_group(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); +static enum_nested_loop_state +end_write(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); +static enum_nested_loop_state +end_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); +static enum_nested_loop_state +end_unique_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); +static enum_nested_loop_state +end_write_group(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); + +static int test_if_group_changed(List &list); +static int join_read_const_table(JOIN_TAB *tab, POSITION *pos); +static int join_read_system(JOIN_TAB *tab); +static int join_read_const(JOIN_TAB *tab); +static int join_read_key(JOIN_TAB *tab); +static int join_read_always_key(JOIN_TAB *tab); +static int join_read_last_key(JOIN_TAB *tab); +static int join_no_more_records(READ_RECORD *info); +static int join_read_next(READ_RECORD *info); +static int join_init_quick_read_record(JOIN_TAB *tab); +static int test_if_quick_select(JOIN_TAB *tab); +static int join_init_read_record(JOIN_TAB *tab); +static int join_read_first(JOIN_TAB *tab); +static int join_read_next(READ_RECORD *info); +static int join_read_next_same(READ_RECORD *info); +static int join_read_last(JOIN_TAB *tab); +static int join_read_prev_same(READ_RECORD *info); +static int join_read_prev(READ_RECORD *info); +static int join_ft_read_first(JOIN_TAB *tab); +static int join_ft_read_next(READ_RECORD *info); +int join_read_always_key_or_null(JOIN_TAB *tab); +int join_read_next_same_or_null(READ_RECORD *info); +static COND *make_cond_for_table(COND *cond,table_map table, + table_map used_table); +static Item* part_of_refkey(TABLE *form,Field *field); +uint find_shortest_key(TABLE *table, const key_map *usable_keys); +static bool test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order, + ha_rows select_limit, bool no_changes, + key_map *map); +static bool list_contains_unique_index(TABLE *table, + bool (*find_func) (Field *, void *), void *data); +static bool find_field_in_item_list (Field *field, void *data); +static bool find_field_in_order_list (Field *field, void *data); +static int create_sort_index(THD *thd, JOIN *join, ORDER *order, + ha_rows filesort_limit, ha_rows select_limit, + bool is_order_by); +static int remove_duplicates(JOIN *join,TABLE *entry,List &fields, + Item *having); +static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field, + ulong offset,Item *having); +static int remove_dup_with_hash_index(THD *thd,TABLE *table, + uint field_count, Field **first_field, + + ulong key_length,Item *having); +static int join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count); +static ulong used_blob_length(CACHE_FIELD **ptr); +static bool store_record_in_cache(JOIN_CACHE *cache); +static void reset_cache_read(JOIN_CACHE *cache); +static void reset_cache_write(JOIN_CACHE *cache); +static void read_cached_record(JOIN_TAB *tab); +static bool cmp_buffer_with_ref(JOIN_TAB *tab); +static bool setup_new_fields(THD *thd, List &fields, + List &all_fields, ORDER *new_order); +static ORDER *create_distinct_group(THD *thd, Item **ref_pointer_array, + ORDER *order, List &fields, + List &all_fields, + bool *all_order_by_fields_used); +static bool test_if_subpart(ORDER *a,ORDER *b); +static TABLE *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables); +static void calc_group_buffer(JOIN *join,ORDER *group); +static bool make_group_fields(JOIN *main_join, JOIN *curr_join); +static bool alloc_group_fields(JOIN *join,ORDER *group); +// Create list for using with tempory table +static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array, + List &new_list1, + List &new_list2, + uint elements, List &items); +// Create list for using with tempory table +static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array, + List &new_list1, + List &new_list2, + uint elements, List &items); +static void init_tmptable_sum_functions(Item_sum **func); +static void update_tmptable_sum_func(Item_sum **func,TABLE *tmp_table); +static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end); +static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab); +static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr); +static bool init_sum_functions(Item_sum **func, Item_sum **end); +static bool update_sum_func(Item_sum **func); +static void select_describe(JOIN *join, bool need_tmp_table,bool need_order, + bool distinct, const char *message=NullS); +static Item *remove_additional_cond(Item* conds); +static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab); +static bool test_if_ref(Item_field *left_item,Item *right_item); + +// InfiniDB error constant +const unsigned ERR_NON_IDB_TABLE = 7001; + +/** + This handles SELECT with and without UNION. +*/ + +bool handle_select(THD *thd, LEX *lex, select_result *result, + ulong setup_tables_done_option) +{ + bool res; + register SELECT_LEX *select_lex = &lex->select_lex; + DBUG_ENTER("handle_select"); + + if (select_lex->master_unit()->is_union() || + select_lex->master_unit()->fake_select_lex) + res= mysql_union(thd, lex, result, &lex->unit, setup_tables_done_option); + else + { + SELECT_LEX_UNIT *unit= &lex->unit; + unit->set_limit(unit->global_parameters); + /* + 'options' of mysql_select will be set in JOIN, as far as JOIN for + every PS/SP execution new, we will not need reset this flag if + setup_tables_done_option changed for next rexecution + */ + res= mysql_select(thd, &select_lex->ref_pointer_array, + (TABLE_LIST*) select_lex->table_list.first, + select_lex->with_wild, select_lex->item_list, + select_lex->where, + select_lex->order_list.elements + + select_lex->group_list.elements, + (ORDER*) select_lex->order_list.first, + (ORDER*) select_lex->group_list.first, + select_lex->having, + (ORDER*) lex->proc_list.first, + select_lex->options | thd->options | + setup_tables_done_option, + result, unit, select_lex); + } + DBUG_PRINT("info",("res: %d report_error: %d", res, + thd->is_error())); + res|= thd->is_error(); + if (unlikely(res)) + result->abort(); + + DBUG_RETURN(res); +} + + +/* + Fix fields referenced from inner selects. + + SYNOPSIS + fix_inner_refs() + thd Thread handle + all_fields List of all fields used in select + select Current select + ref_pointer_array Array of references to Items used in current select + + DESCRIPTION + The function serves 3 purposes - adds fields referenced from inner + selects to the current select list, resolves which class to use + to access referenced item (Item_ref of Item_direct_ref) and fixes + references (Item_ref objects) to these fields. + + If a field isn't already in the select list and the ref_pointer_array + is provided then it is added to the all_fields list and the pointer to + it is saved in the ref_pointer_array. + + The class to access the outer field is determined by the following rules: + 1. If the outer field isn't used under an aggregate function + then the Item_ref class should be used. + 2. If the outer field is used under an aggregate function and this + function is aggregated in the select where the outer field was + resolved or in some more inner select then the Item_direct_ref + class should be used. + The resolution is done here and not at the fix_fields() stage as + it can be done only after sum functions are fixed and pulled up to + selects where they are have to be aggregated. + When the class is chosen it substitutes the original field in the + Item_outer_ref object. + + After this we proceed with fixing references (Item_outer_ref objects) to + this field from inner subqueries. + + RETURN + TRUE an error occured + FALSE ok +*/ + +bool +fix_inner_refs(THD *thd, List &all_fields, SELECT_LEX *select, + Item **ref_pointer_array) +{ + Item_outer_ref *ref; + bool res= FALSE; + bool direct_ref= FALSE; + + List_iterator ref_it(select->inner_refs_list); + while ((ref= ref_it++)) + { + Item *item= ref->outer_ref; + Item **item_ref= ref->ref; + Item_ref *new_ref; + /* + TODO: this field item already might be present in the select list. + In this case instead of adding new field item we could use an + existing one. The change will lead to less operations for copying fields, + smaller temporary tables and less data passed through filesort. + */ + if (ref_pointer_array && !ref->found_in_select_list) + { + int el= all_fields.elements; + ref_pointer_array[el]= item; + /* Add the field item to the select list of the current select. */ + all_fields.push_front(item); + /* + If it's needed reset each Item_ref item that refers this field with + a new reference taken from ref_pointer_array. + */ + item_ref= ref_pointer_array + el; + } + + if (ref->in_sum_func) + { + Item_sum *sum_func; + if (ref->in_sum_func->nest_level > select->nest_level) + direct_ref= TRUE; + else + { + for (sum_func= ref->in_sum_func; sum_func && + sum_func->aggr_level >= select->nest_level; + sum_func= sum_func->in_sum_func) + { + if (sum_func->aggr_level == select->nest_level) + { + direct_ref= TRUE; + break; + } + } + } + } + new_ref= direct_ref ? + new Item_direct_ref(ref->context, item_ref, ref->table_name, + ref->field_name, ref->alias_name_used) : + new Item_ref(ref->context, item_ref, ref->table_name, + ref->field_name, ref->alias_name_used); + if (!new_ref) + return TRUE; + ref->outer_ref= new_ref; + ref->ref= &ref->outer_ref; + + if (!ref->fixed && ref->fix_fields(thd, 0)) + return TRUE; + thd->used_tables|= item->used_tables(); + } + return res; +} + +/** + Function to setup clauses without sum functions. +*/ +inline int setup_without_group(THD *thd, Item **ref_pointer_array, + TABLE_LIST *tables, + TABLE_LIST *leaves, + List &fields, + List &all_fields, + COND **conds, + ORDER *order, + ORDER *group, bool *hidden_group_fields) +{ + int res; + nesting_map save_allow_sum_func=thd->lex->allow_sum_func ; + /* + Need to save the value, so we can turn off only the new NON_AGG_FIELD + additions coming from the WHERE + */ + uint8 saved_flag= thd->lex->current_select->full_group_by_flag; + DBUG_ENTER("setup_without_group"); + + thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level); + res= setup_conds(thd, tables, leaves, conds); + + /* it's not wrong to have non-aggregated columns in a WHERE */ + if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) + thd->lex->current_select->full_group_by_flag= saved_flag | + (thd->lex->current_select->full_group_by_flag & ~NON_AGG_FIELD_USED); + + thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level; + res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields, + order); + thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level); + res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields, + group, hidden_group_fields); + thd->lex->allow_sum_func= save_allow_sum_func; + DBUG_RETURN(res); +} + +/***************************************************************************** + Check fields, find best join, do the select and output fields. + mysql_select assumes that all tables are already opened +*****************************************************************************/ + +/** + Prepare of whole select (including sub queries in future). + + @todo + Add check of calculation of GROUP functions and fields: + SELECT COUNT(*)+table.col1 from table1; + + @retval + -1 on error + @retval + 0 on success +*/ +int +JOIN::prepare(Item ***rref_pointer_array, + TABLE_LIST *tables_init, + uint wild_num, COND *conds_init, uint og_num, + ORDER *order_init, ORDER *group_init, + Item *having_init, + ORDER *proc_param_init, SELECT_LEX *select_lex_arg, + SELECT_LEX_UNIT *unit_arg) +{ + DBUG_ENTER("JOIN::prepare"); + + // to prevent double initialization on EXPLAIN + if (optimized) + DBUG_RETURN(0); + + conds= conds_init; + order= order_init; + group_list= group_init; + having= having_init; + proc_param= proc_param_init; + tables_list= tables_init; + select_lex= select_lex_arg; + select_lex->join= this; + join_list= &select_lex->top_join_list; + union_part= unit_arg->is_union(); + + thd->lex->current_select->is_item_list_lookup= 1; + /* + If we have already executed SELECT, then it have not sense to prevent + its table from update (see unique_table()) + */ + if (thd->derived_tables_processing) + select_lex->exclude_from_table_unique_test= TRUE; + + /* Check that all tables, fields, conds and order are ok */ + + if (!(select_options & OPTION_SETUP_TABLES_DONE) && + setup_tables_and_check_access(thd, &select_lex->context, join_list, + tables_list, &select_lex->leaf_tables, + FALSE, SELECT_ACL, SELECT_ACL)) + DBUG_RETURN(-1); + + TABLE_LIST *table_ptr; + for (table_ptr= select_lex->leaf_tables; + table_ptr; + table_ptr= table_ptr->next_leaf) + tables++; + + if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) || + select_lex->setup_ref_array(thd, og_num) || + setup_fields(thd, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ, + &all_fields, 1) || + setup_without_group(thd, (*rref_pointer_array), tables_list, + select_lex->leaf_tables, fields_list, + all_fields, &conds, order, group_list, + &hidden_group_fields)) + DBUG_RETURN(-1); /* purecov: inspected */ + + ref_pointer_array= *rref_pointer_array; + + if (having) + { + nesting_map save_allow_sum_func= thd->lex->allow_sum_func; + thd->where="having clause"; + thd->lex->allow_sum_func|= 1 << select_lex_arg->nest_level; + select_lex->having_fix_field= 1; + bool having_fix_rc= (!having->fixed && + (having->fix_fields(thd, &having) || + having->check_cols(1))); + select_lex->having_fix_field= 0; + if (having_fix_rc || thd->is_error()) + DBUG_RETURN(-1); /* purecov: inspected */ + thd->lex->allow_sum_func= save_allow_sum_func; + } + + if (!thd->lex->view_prepare_mode) + { + Item_subselect *subselect; + /* Is it subselect? */ + if ((subselect= select_lex->master_unit()->item)) + { + Item_subselect::trans_res res; + if ((res= subselect->select_transformer(this)) != + Item_subselect::RES_OK) + { + select_lex->fix_prepare_information(thd, &conds, &having); + DBUG_RETURN((res == Item_subselect::RES_ERROR)); + } + } + } + + select_lex->fix_prepare_information(thd, &conds, &having); + + if (order) + { + ORDER *ord; + for (ord= order; ord; ord= ord->next) + { + Item *item= *ord->item; + if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) + item->split_sum_func(thd, ref_pointer_array, all_fields); + } + } + + if (having && having->with_sum_func) + having->split_sum_func2(thd, ref_pointer_array, all_fields, + &having, TRUE); + if (select_lex->inner_sum_func_list) + { + Item_sum *end=select_lex->inner_sum_func_list; + Item_sum *item_sum= end; + do + { + item_sum= item_sum->next; + item_sum->split_sum_func2(thd, ref_pointer_array, + all_fields, item_sum->ref_by, FALSE); + } while (item_sum != end); + } + + if (select_lex->inner_refs_list.elements && + fix_inner_refs(thd, all_fields, select_lex, ref_pointer_array)) + DBUG_RETURN(-1); + + if (group_list) + { + /* + Because HEAP tables can't index BIT fields we need to use an + additional hidden field for grouping because later it will be + converted to a LONG field. Original field will remain of the + BIT type and will be returned to a client. + */ + for (ORDER *ord= group_list; ord; ord= ord->next) + { + if ((*ord->item)->type() == Item::FIELD_ITEM && + (*ord->item)->field_type() == MYSQL_TYPE_BIT) + { + Item_field *field= new Item_field(thd, *(Item_field**)ord->item); + int el= all_fields.elements; + ref_pointer_array[el]= field; + all_fields.push_front(field); + ord->item= ref_pointer_array + el; + } + } + } + + if (setup_ftfuncs(select_lex)) /* should be after having->fix_fields */ + DBUG_RETURN(-1); + + + /* + Check if there are references to un-aggregated columns when computing + aggregate functions with implicit grouping (there is no GROUP BY). + */ + if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY && !group_list && + select_lex->full_group_by_flag == (NON_AGG_FIELD_USED | SUM_FUNC_USED)) + { + my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS, + ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0)); + DBUG_RETURN(-1); + } + { + /* Caclulate the number of groups */ + send_group_parts= 0; + for (ORDER *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next) + send_group_parts++; + } + + procedure= setup_procedure(thd, proc_param, result, fields_list, &error); + if (error) + goto err; /* purecov: inspected */ + if (procedure) + { + if (setup_new_fields(thd, fields_list, all_fields, + procedure->param_fields)) + goto err; /* purecov: inspected */ + if (procedure->group) + { + if (!test_if_subpart(procedure->group,group_list)) + { /* purecov: inspected */ + my_message(ER_DIFF_GROUPS_PROC, ER(ER_DIFF_GROUPS_PROC), + MYF(0)); /* purecov: inspected */ + goto err; /* purecov: inspected */ + } + } + if (order && (procedure->flags & PROC_NO_SORT)) + { /* purecov: inspected */ + my_message(ER_ORDER_WITH_PROC, ER(ER_ORDER_WITH_PROC), + MYF(0)); /* purecov: inspected */ + goto err; /* purecov: inspected */ + } + } + + if (!procedure && result && result->prepare(fields_list, unit_arg)) + goto err; /* purecov: inspected */ + + /* Init join struct */ + count_field_types(select_lex, &tmp_table_param, all_fields, 0); + ref_pointer_array_size= all_fields.elements*sizeof(Item*); + this->group= group_list != 0; + unit= unit_arg; + +#ifdef RESTRICTED_GROUP + if (sum_func_count && !group_list && (func_count || field_count)) + { + my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0)); + goto err; + } +#endif + if (select_lex->olap == ROLLUP_TYPE && rollup_init()) + goto err; + if (alloc_func_list()) + goto err; + + DBUG_RETURN(0); // All OK + +err: + delete procedure; /* purecov: inspected */ + procedure= 0; + DBUG_RETURN(-1); /* purecov: inspected */ +} + + +/* + Remove the predicates pushed down into the subquery + + SYNOPSIS + JOIN::remove_subq_pushed_predicates() + where IN Must be NULL + OUT The remaining WHERE condition, or NULL + + DESCRIPTION + Given that this join will be executed using (unique|index)_subquery, + without "checking NULL", remove the predicates that were pushed down + into the subquery. + + If the subquery compares scalar values, we can remove the condition that + was wrapped into trig_cond (it will be checked when needed by the subquery + engine) + + If the subquery compares row values, we need to keep the wrapped + equalities in the WHERE clause: when the left (outer) tuple has both NULL + and non-NULL values, we'll do a full table scan and will rely on the + equalities corresponding to non-NULL parts of left tuple to filter out + non-matching records. + + TODO: We can remove the equalities that will be guaranteed to be true by the + fact that subquery engine will be using index lookup. This must be done only + for cases where there are no conversion errors of significance, e.g. 257 + that is searched in a byte. But this requires homogenization of the return + codes of all Field*::store() methods. +*/ + +void JOIN::remove_subq_pushed_predicates(Item **where) +{ + if (conds->type() == Item::FUNC_ITEM && + ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC && + ((Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM && + ((Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM && + test_if_ref ((Item_field *)((Item_func *)conds)->arguments()[1], + ((Item_func *)conds)->arguments()[0])) + { + *where= 0; + return; + } +} + + +/* + Index lookup-based subquery: save some flags for EXPLAIN output + + SYNOPSIS + save_index_subquery_explain_info() + join_tab Subquery's join tab (there is only one as index lookup is + only used for subqueries that are single-table SELECTs) + where Subquery's WHERE clause + + DESCRIPTION + For index lookup-based subquery (i.e. one executed with + subselect_uniquesubquery_engine or subselect_indexsubquery_engine), + check its EXPLAIN output row should contain + "Using index" (TAB_INFO_FULL_SCAN_ON_NULL) + "Using Where" (TAB_INFO_USING_WHERE) + "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL) + and set appropriate flags in join_tab->packed_info. +*/ + +static void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where) +{ + join_tab->packed_info= TAB_INFO_HAVE_VALUE; + if (join_tab->table->covering_keys.is_set(join_tab->ref.key)) + join_tab->packed_info |= TAB_INFO_USING_INDEX; + if (where) + join_tab->packed_info |= TAB_INFO_USING_WHERE; + for (uint i = 0; i < join_tab->ref.key_parts; i++) + { + if (join_tab->ref.cond_guards[i]) + { + join_tab->packed_info |= TAB_INFO_FULL_SCAN_ON_NULL; + break; + } + } +} + + +/** + global select optimisation. + + @note + error code saved in field 'error' + + @retval + 0 success + @retval + 1 error +*/ + +int +JOIN::optimize() +{ + DBUG_ENTER("JOIN::optimize"); + // to prevent double initialization on EXPLAIN + if (optimized) + DBUG_RETURN(0); + optimized= 1; + + thd_proc_info(thd, "optimizing"); + row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR : + unit->select_limit_cnt); + /* select_limit is used to decide if we are likely to scan the whole table */ + select_limit= unit->select_limit_cnt; + if (having || (select_options & OPTION_FOUND_ROWS)) + select_limit= HA_POS_ERROR; + do_send_rows = (unit->select_limit_cnt) ? 1 : 0; + // Ignore errors of execution if option IGNORE present + if (thd->lex->ignore) + thd->lex->current_select->no_error= 1; +#ifdef HAVE_REF_TO_FIELDS // Not done yet + /* Add HAVING to WHERE if possible */ + if (having && !group_list && !sum_func_count) + { + if (!conds) + { + conds= having; + having= 0; + } + else if ((conds=new Item_cond_and(conds,having))) + { + /* + Item_cond_and can't be fixed after creation, so we do not check + conds->fixed + */ + conds->fix_fields(thd, &conds); + conds->change_ref_to_fields(thd, tables_list); + conds->top_level_item(); + having= 0; + } + } +#endif + SELECT_LEX *sel= thd->lex->current_select; + if (sel->first_cond_optimization) + { + /* + The following code will allocate the new items in a permanent + MEMROOT for prepared statements and stored procedures. + */ + + Query_arena *arena= thd->stmt_arena, backup; + if (arena->is_conventional()) + arena= 0; // For easier test + else + thd->set_n_backup_active_arena(arena, &backup); + + sel->first_cond_optimization= 0; + + /* Convert all outer joins to inner joins if possible */ + conds= simplify_joins(this, join_list, conds, TRUE); + build_bitmap_for_nested_joins(join_list, 0); + + sel->prep_where= conds ? conds->copy_andor_structure(thd) : 0; + + if (arena) + thd->restore_active_arena(arena, &backup); + } + + // Turn off constant optimization if this is a redo query. The original query failed + // at plan generation possibly becuase the optimizer re-write. + // @bug 2547. Turn off optimizer for union part and subselect part to avoid redo phase. + // turn off optimizer for join key substitute outer join + /*if (!thd->infinidb_vtable.mysql_optimizer_off + && !union_part + && select_lex == &thd->lex->select_lex + && (!conds || !conds->with_subselect) + && !outer_join)*/ + // InfiniDB: turn off the constant and join subsitute optimization for vtable mode now. + // It has been found so far that this optimization brings InfiniDB more harm than good. + if ((thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) && ((thd->lex)->sql_command != SQLCOM_UPDATE ) && + ( (thd->lex)->sql_command != SQLCOM_UPDATE_MULTI ) && ( (thd->lex)->sql_command != SQLCOM_DELETE ) && ( (thd->lex)->sql_command != SQLCOM_DELETE_MULTI ) ) + { + conds= optimize_cond(this, conds, join_list, &cond_value); + if (thd->is_error()) + { + error= 1; + DBUG_PRINT("error",("Error from optimize_cond")); + DBUG_RETURN(1); + } + } + else + { + // @bug 2203. This variable was not initialized and will be set in optimize_cond. + // Since we skipped optimization, we need to set the variable here. Otherwise it will + // randomly return COND_FALSE and cause an "Impossible Where clause". + cond_value = Item::COND_OK; + } + + { + having= optimize_cond(this, having, join_list, &having_value); + if (thd->is_error()) + { + error= 1; + DBUG_PRINT("error",("Error from optimize_cond")); + DBUG_RETURN(1); + } + if (select_lex->where) + select_lex->cond_value= cond_value; + if (select_lex->having) + select_lex->having_value= having_value; + + + + if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE || + (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS))) + { /* Impossible cond */ + DBUG_PRINT("info", (having_value == Item::COND_FALSE ? + "Impossible HAVING" : "Impossible WHERE")); + zero_result_cause= having_value == Item::COND_FALSE ? + "Impossible HAVING" : "Impossible WHERE"; + tables= 0; + error= 0; + DBUG_RETURN(0); + } + } + +#ifdef WITH_PARTITION_STORAGE_ENGINE + { + TABLE_LIST *tbl; + for (tbl= select_lex->leaf_tables; tbl; tbl= tbl->next_leaf) + { + /* + If tbl->embedding!=NULL that means that this table is in the inner + part of the nested outer join, and we can't do partition pruning + (TODO: check if this limitation can be lifted) + */ + if (!tbl->embedding) + { + Item *prune_cond= tbl->on_expr? tbl->on_expr : conds; + tbl->table->no_partitions_used= prune_partitions(thd, tbl->table, + prune_cond); + } + } + } +#endif + + /* Optimize count(*), min() and max() */ + if (tables_list && tmp_table_param.sum_func_count && ! group_list) + { + int res; + /* + opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match + to the WHERE conditions, + or 1 if all items were resolved, + or 0, or an error number HA_ERR_... + */ + if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds))) + { + if (res == HA_ERR_KEY_NOT_FOUND) + { + DBUG_PRINT("info",("No matching min/max row")); + zero_result_cause= "No matching min/max row"; + tables= 0; + error=0; + DBUG_RETURN(0); + } + if (res > 1) + { + error= res; + DBUG_PRINT("error",("Error from opt_sum_query")); + DBUG_RETURN(1); + } + if (res < 0) + { + DBUG_PRINT("info",("No matching min/max row")); + zero_result_cause= "No matching min/max row"; + tables= 0; + error=0; + DBUG_RETURN(0); + } + DBUG_PRINT("info",("Select tables optimized away")); + zero_result_cause= "Select tables optimized away"; + tables_list= 0; // All tables resolved + /* + Extract all table-independent conditions and replace the WHERE + clause with them. All other conditions were computed by opt_sum_query + and the MIN/MAX/COUNT function(s) have been replaced by constants, + so there is no need to compute the whole WHERE clause again. + Notice that make_cond_for_table() will always succeed to remove all + computed conditions, because opt_sum_query() is applicable only to + conjunctions. + Preserve conditions for EXPLAIN. + */ + if (conds && !(thd->lex->describe & DESCRIBE_EXTENDED)) + { + COND *table_independent_conds= + make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0); + DBUG_EXECUTE("where", + print_where(table_independent_conds, + "where after opt_sum_query()", + QT_ORDINARY);); + conds= table_independent_conds; + } + } + } + if (!tables_list) + { + DBUG_PRINT("info",("No tables")); + error= 0; + DBUG_RETURN(0); + } + error= -1; // Error is sent to client + sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables); + + /* Calculate how to do the join */ + thd_proc_info(thd, "statistics"); + if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) || + thd->is_fatal_error) + { + DBUG_PRINT("error",("Error: make_join_statistics() failed")); + DBUG_RETURN(1); + } + + /* Remove distinct if only const tables */ + select_distinct= select_distinct && (const_tables != tables); + thd_proc_info(thd, "preparing"); + if (result->initialize_tables(this)) + { + DBUG_PRINT("error",("Error: initialize_tables() failed")); + DBUG_RETURN(1); // error == -1 + } + if (const_table_map != found_const_table_map && + !(select_options & SELECT_DESCRIBE) && + (!conds || + !(conds->used_tables() & RAND_TABLE_BIT) || + select_lex->master_unit() == &thd->lex->unit) && // upper level SELECT + !thd->infinidb_vtable.isUpdateWithDerive ) // @bug4027. Do not let zero_result_cause set for IDB update + { + zero_result_cause= "no matching row in const table"; + DBUG_PRINT("error",("Error: %s", zero_result_cause)); + error= 0; + DBUG_RETURN(0); + } + thd->infinidb_vtable.isUpdateWithDerive = false; // reset + + if (!(thd->options & OPTION_BIG_SELECTS) && + best_read > (double) thd->variables.max_join_size && + !(select_options & SELECT_DESCRIBE)) + { /* purecov: inspected */ + my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0)); + error= -1; + DBUG_RETURN(1); + } + if (const_tables && !thd->locked_tables && + !(select_options & SELECT_NO_UNLOCK)) + mysql_unlock_some_tables(thd, table, const_tables); + if (!conds && outer_join) + { + /* Handle the case where we have an OUTER JOIN without a WHERE */ + conds=new Item_int((longlong) 1,1); // Always true + } + select= make_select(*table, const_table_map, + const_table_map, conds, 1, &error); + if (error) + { /* purecov: inspected */ + error= -1; /* purecov: inspected */ + DBUG_PRINT("error",("Error: make_select() failed")); + DBUG_RETURN(1); + } + + reset_nj_counters(join_list); + make_outerjoin_info(this); + + /* + Among the equal fields belonging to the same multiple equality + choose the one that is to be retrieved first and substitute + all references to these in where condition for a reference for + the selected field. + */ + if (conds) + { + conds= substitute_for_best_equal_field(conds, cond_equal, map2table); + conds->update_used_tables(); + DBUG_EXECUTE("where", + print_where(conds, + "after substitute_best_equal", + QT_ORDINARY);); + } + + /* + Permorm the the optimization on fields evaluation mentioned above + for all on expressions. + */ + for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++) + { + if (*tab->on_expr_ref) + { + *tab->on_expr_ref= substitute_for_best_equal_field(*tab->on_expr_ref, + tab->cond_equal, + map2table); + (*tab->on_expr_ref)->update_used_tables(); + } + } + + if (conds &&!outer_join && const_table_map != found_const_table_map && + (select_options & SELECT_DESCRIBE) && + select_lex->master_unit() == &thd->lex->unit) // upper level SELECT + { + conds=new Item_int((longlong) 0,1); // Always false + } + if (make_join_select(this, select, conds)) + { + zero_result_cause= + "Impossible WHERE noticed after reading const tables"; + DBUG_RETURN(0); // error == 0 + } + + error= -1; /* if goto err */ + + /* Optimize distinct away if possible */ + { + ORDER *org_order= order; + // @bug 3961. mysql treat subquery (with other engine?) as const table so will + // remove the columns from the subquery on the order by list. InfiniDB needs to + // keep them for the post process. So skip remove_const optimization. + if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_CREATE_VTABLE) + order=remove_const(this, order,conds,1, &simple_order); + if (thd->is_error()) + { + error= 1; + DBUG_PRINT("error",("Error from remove_const")); + DBUG_RETURN(1); + } + + /* + If we are using ORDER BY NULL or ORDER BY const_expression, + return result in any order (even if we are using a GROUP BY) + */ + if (!order && org_order) + skip_sort_order= 1; + } + /* + Check if we can optimize away GROUP BY/DISTINCT. + We can do that if there are no aggregate functions, the + fields in DISTINCT clause (if present) and/or columns in GROUP BY + (if present) contain direct references to all key parts of + an unique index (in whatever order) and if the key parts of the + unique index cannot contain NULLs. + Note that the unique keys for DISTINCT and GROUP BY should not + be the same (as long as they are unique). + + The FROM clause must contain a single non-constant table. + */ + if (tables - const_tables == 1 && (group_list || select_distinct) && + !tmp_table_param.sum_func_count && + (!join_tab[const_tables].select || + !join_tab[const_tables].select->quick || + join_tab[const_tables].select->quick->get_type() != + QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)) + { + if (group_list && + list_contains_unique_index(join_tab[const_tables].table, + find_field_in_order_list, + (void *) group_list)) + { + /* + We have found that grouping can be removed since groups correspond to + only one row anyway, but we still have to guarantee correct result + order. The line below effectively rewrites the query from GROUP BY + to ORDER BY . There are two exceptions: + - if skip_sort_order is set (see above), then we can simply skip + GROUP BY; + - we can only rewrite ORDER BY if the ORDER BY fields are 'compatible' + with the GROUP BY ones, i.e. either one is a prefix of another. + We only check if the ORDER BY is a prefix of GROUP BY. In this case + test_if_subpart() copies the ASC/DESC attributes from the original + ORDER BY fields. + If GROUP BY is a prefix of ORDER BY, then it is safe to leave + 'order' as is. + */ + if (!order || test_if_subpart(group_list, order)) + order= skip_sort_order ? 0 : group_list; + /* + If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be + rewritten to IGNORE INDEX FOR ORDER BY(fields). + */ + join_tab->table->keys_in_use_for_order_by= + join_tab->table->keys_in_use_for_group_by; + group_list= 0; + group= 0; + } + if (select_distinct && + list_contains_unique_index(join_tab[const_tables].table, + find_field_in_item_list, + (void *) &fields_list)) + { + select_distinct= 0; + } + } + if (group_list || tmp_table_param.sum_func_count) + { + if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE) + select_distinct=0; + } + else if (select_distinct && tables - const_tables == 1) + { + /* + We are only using one table. In this case we change DISTINCT to a + GROUP BY query if: + - The GROUP BY can be done through indexes (no sort) and the ORDER + BY only uses selected fields. + (In this case we can later optimize away GROUP BY and ORDER BY) + - We are scanning the whole table without LIMIT + This can happen if: + - We are using CALC_FOUND_ROWS + - We are using an ORDER BY that can't be optimized away. + + We don't want to use this optimization when we are using LIMIT + because in this case we can just create a temporary table that + holds LIMIT rows and stop when this table is full. + */ + JOIN_TAB *tab= &join_tab[const_tables]; + bool all_order_fields_used; + if (order) + skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1, + &tab->table->keys_in_use_for_order_by); + if ((group_list=create_distinct_group(thd, select_lex->ref_pointer_array, + order, fields_list, all_fields, + &all_order_fields_used))) + { + bool skip_group= (skip_sort_order && + test_if_skip_sort_order(tab, group_list, select_limit, 1, + &tab->table->keys_in_use_for_group_by) != 0); + count_field_types(select_lex, &tmp_table_param, all_fields, 0); + if ((skip_group && all_order_fields_used) || + select_limit == HA_POS_ERROR || + (order && !skip_sort_order)) + { + /* Change DISTINCT to GROUP BY */ + select_distinct= 0; + no_order= !order; + if (all_order_fields_used) + { + if (order && skip_sort_order) + { + /* + Force MySQL to read the table in sorted order to get result in + ORDER BY order. + */ + tmp_table_param.quick_group=0; + } + order=0; + } + group=1; // For end_write_group + } + else + group_list= 0; + } + else if (thd->is_fatal_error) // End of memory + DBUG_RETURN(1); + } + simple_group= 0; + { + ORDER *old_group_list = 0; + // Calpont InfiniDB skip MySQL optimization of group by list. @bug1804. + if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_CREATE_VTABLE) + group_list= remove_const(this, (old_group_list= group_list), conds, + rollup.state == ROLLUP::STATE_NONE, + &simple_group); + if (thd->is_error()) + { + error= 1; + DBUG_PRINT("error",("Error from remove_const")); + DBUG_RETURN(1); + } + if (old_group_list && !group_list) + select_distinct= 0; + } + if (!group_list && group) + { + order=0; // The output has only one row + simple_order=1; + select_distinct= 0; // No need in distinct for 1 row + group_optimized_away= 1; + } + + calc_group_buffer(this, group_list); + send_group_parts= tmp_table_param.group_parts; /* Save org parts */ + if (procedure && procedure->group) + { + group_list= procedure->group= remove_const(this, procedure->group, conds, + 1, &simple_group); + if (thd->is_error()) + { + error= 1; + DBUG_PRINT("error",("Error from remove_const")); + DBUG_RETURN(1); + } + calc_group_buffer(this, group_list); + } + + if (test_if_subpart(group_list, order) || + (!group_list && tmp_table_param.sum_func_count)) + order=0; + + // Can't use sort on head table if using row cache + if (full_join) + { + if (group_list) + simple_group=0; + if (order) + simple_order=0; + } + + /* + Check if we need to create a temporary table. + This has to be done if all tables are not already read (const tables) + and one of the following conditions holds: + - We are using DISTINCT (simple distinct's are already optimized away) + - We are using an ORDER BY or GROUP BY on fields not in the first table + - We are using different ORDER BY and GROUP BY orders + - The user wants us to buffer the result. + */ + // Calpont InfiniDB change. We don't need tmp table for vtable create phase. Plus + // to build tmp table may corrupt some field table_name & db_name (for some reason) + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE) + need_tmp = false; + else + need_tmp= (const_tables != tables && + ((select_distinct || !simple_order || !simple_group) || + (group_list && order) || + test(select_options & OPTION_BUFFER_RESULT))); + + // No cache for MATCH + make_join_readinfo(this, + (select_options & (SELECT_DESCRIBE | + SELECT_NO_JOIN_CACHE)) | + (select_lex->ftfunc_list->elements ? + SELECT_NO_JOIN_CACHE : 0)); + + /* Perform FULLTEXT search before all regular searches */ + if (!(select_options & SELECT_DESCRIBE)) + init_ftfuncs(thd, select_lex, test(order)); + + /* + is this simple IN subquery? + */ + if (!group_list && !order && + unit->item && unit->item->substype() == Item_subselect::IN_SUBS && + tables == 1 && conds && + !unit->is_union()) + { + if (!having) + { + Item *where= conds; + if (join_tab[0].type == JT_EQ_REF && + join_tab[0].ref.items[0]->name == in_left_expr_name) + { + remove_subq_pushed_predicates(&where); + save_index_subquery_explain_info(join_tab, where); + join_tab[0].type= JT_UNIQUE_SUBQUERY; + error= 0; + DBUG_RETURN(unit->item-> + change_engine(new + subselect_uniquesubquery_engine(thd, + join_tab, + unit->item, + where))); + } + else if (join_tab[0].type == JT_REF && + join_tab[0].ref.items[0]->name == in_left_expr_name) + { + remove_subq_pushed_predicates(&where); + save_index_subquery_explain_info(join_tab, where); + join_tab[0].type= JT_INDEX_SUBQUERY; + error= 0; + DBUG_RETURN(unit->item-> + change_engine(new + subselect_indexsubquery_engine(thd, + join_tab, + unit->item, + where, + NULL, + 0))); + } + } else if (join_tab[0].type == JT_REF_OR_NULL && + join_tab[0].ref.items[0]->name == in_left_expr_name && + having->name == in_having_cond) + { + join_tab[0].type= JT_INDEX_SUBQUERY; + error= 0; + conds= remove_additional_cond(conds); + save_index_subquery_explain_info(join_tab, conds); + DBUG_RETURN(unit->item-> + change_engine(new subselect_indexsubquery_engine(thd, + join_tab, + unit->item, + conds, + having, + 1))); + } + + } + /* + Need to tell handlers that to play it safe, it should fetch all + columns of the primary key of the tables: this is because MySQL may + build row pointers for the rows, and for all columns of the primary key + the read set has not necessarily been set by the server code. + */ + if (need_tmp || select_distinct || group_list || order) + { + for (uint i = const_tables; i < tables; i++) + join_tab[i].table->prepare_for_position(); + } + + DBUG_EXECUTE("info",TEST_join(this);); + + if (const_tables != tables) + { + /* + Because filesort always does a full table scan or a quick range scan + we must add the removed reference to the select for the table. + We only need to do this when we have a simple_order or simple_group + as in other cases the join is done before the sort. + */ + if ((order || group_list) && + join_tab[const_tables].type != JT_ALL && + join_tab[const_tables].type != JT_FT && + join_tab[const_tables].type != JT_REF_OR_NULL && + ((order && simple_order) || (group_list && simple_group))) + { + if (add_ref_to_table_cond(thd,&join_tab[const_tables])) { + DBUG_RETURN(1); + } + } + + if (!(select_options & SELECT_BIG_RESULT) && + ((group_list && + (!simple_group || + !test_if_skip_sort_order(&join_tab[const_tables], group_list, + unit->select_limit_cnt, 0, + &join_tab[const_tables].table-> + keys_in_use_for_group_by))) || + select_distinct) && + tmp_table_param.quick_group && !procedure && + thd->infinidb_vtable.vtable_state != THD::INFINIDB_CREATE_VTABLE) + { + need_tmp=1; simple_order=simple_group=0; // Force tmp table without sort + } + if (order) + { + /* + Force using of tmp table if sorting by a SP or UDF function due to + their expensive and probably non-deterministic nature. + */ + for (ORDER *tmp_order= order; tmp_order ; tmp_order=tmp_order->next) + { + Item *item= *tmp_order->item; + if (item->walk(&Item::is_expensive_processor, 0, (uchar*)0)) + { + /* Force tmp table without sort */ + need_tmp=1; simple_order=simple_group=0; + break; + } + } + } + } + + tmp_having= having; + if (select_options & SELECT_DESCRIBE) + { + error= 0; + DBUG_RETURN(0); + } + having= 0; + + /* + The loose index scan access method guarantees that all grouping or + duplicate row elimination (for distinct) is already performed + during data retrieval, and that all MIN/MAX functions are already + computed for each group. Thus all MIN/MAX functions should be + treated as regular functions, and there is no need to perform + grouping in the main execution loop. + Notice that currently loose index scan is applicable only for + single table queries, thus it is sufficient to test only the first + join_tab element of the plan for its access method. + */ + if (join_tab->is_using_loose_index_scan()) + tmp_table_param.precomputed_group_by= TRUE; + + /* Create a tmp table if distinct or if the sort is too complicated */ + if (need_tmp) + { + DBUG_PRINT("info",("Creating tmp table")); + thd_proc_info(thd, "Creating tmp table"); + + init_items_ref_array(); + + tmp_table_param.hidden_field_count= (all_fields.elements - + fields_list.elements); + ORDER *tmp_group= ((!simple_group && !procedure && + !(test_flags & TEST_NO_KEY_GROUP)) ? group_list : + (ORDER*) 0); + /* + Pushing LIMIT to the temporary table creation is not applicable + when there is ORDER BY or GROUP BY or there is no GROUP BY, but + there are aggregate functions, because in all these cases we need + all result rows. + */ + ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) && + !tmp_group && + !thd->lex->current_select->with_sum_func) ? + select_limit : HA_POS_ERROR; + + if (!(exec_tmp_table1= + create_tmp_table(thd, &tmp_table_param, all_fields, + tmp_group, + group_list ? 0 : select_distinct, + group_list && simple_group, + select_options, + tmp_rows_limit, + (char *) ""))) + { + DBUG_RETURN(1); + } + + /* + We don't have to store rows in temp table that doesn't match HAVING if: + - we are sorting the table and writing complete group rows to the + temp table. + - We are using DISTINCT without resolving the distinct as a GROUP BY + on all columns. + + If having is not handled here, it will be checked before the row + is sent to the client. + */ + if (tmp_having && + (sort_and_group || (exec_tmp_table1->distinct && !group_list))) + having= tmp_having; + + /* if group or order on first table, sort first */ + if (group_list && simple_group) + { + DBUG_PRINT("info",("Sorting for group")); + thd_proc_info(thd, "Sorting for group"); + if (create_sort_index(thd, this, group_list, + HA_POS_ERROR, HA_POS_ERROR, FALSE) || + alloc_group_fields(this, group_list) || + make_sum_func_list(all_fields, fields_list, 1) || + setup_sum_funcs(thd, sum_funcs)) + { + DBUG_RETURN(1); + } + group_list=0; + } + else + { + if (make_sum_func_list(all_fields, fields_list, 0) || + setup_sum_funcs(thd, sum_funcs)) + { + DBUG_RETURN(1); + } + + if (!group_list && ! exec_tmp_table1->distinct && order && simple_order) + { + thd_proc_info(thd, "Sorting for order"); + if (create_sort_index(thd, this, order, + HA_POS_ERROR, HA_POS_ERROR, TRUE)) + { + DBUG_RETURN(1); + } + order=0; + } + } + + /* + Optimize distinct when used on some of the tables + SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b + In this case we can stop scanning t2 when we have found one t1.a + */ + + if (exec_tmp_table1->distinct) + { + table_map used_tables= thd->used_tables; + JOIN_TAB *last_join_tab= join_tab+tables-1; + do + { + if (used_tables & last_join_tab->table->map) + break; + last_join_tab->not_used_in_distinct=1; + } while (last_join_tab-- != join_tab); + /* Optimize "select distinct b from t1 order by key_part_1 limit #" */ + if (order && skip_sort_order) + { + /* Should always succeed */ + if (test_if_skip_sort_order(&join_tab[const_tables], + order, unit->select_limit_cnt, 0, + &join_tab[const_tables].table-> + keys_in_use_for_order_by)) + order=0; + } + } + + /* + If this join belongs to an uncacheable subquery save + the original join + */ + if (select_lex->uncacheable && !is_top_level_join() && + init_save_join_tab()) + DBUG_RETURN(-1); /* purecov: inspected */ + } + + error= 0; + DBUG_RETURN(0); +} + + +/** + Restore values in temporary join. +*/ +void JOIN::restore_tmp() +{ + memcpy(tmp_join, this, (size_t) sizeof(JOIN)); +} + + +int +JOIN::reinit() +{ + DBUG_ENTER("JOIN::reinit"); + + unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ? + select_lex->offset_limit->val_uint() : + ULL(0)); + + first_record= 0; + + if (exec_tmp_table1) + { + exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE); + exec_tmp_table1->file->ha_delete_all_rows(); + free_io_cache(exec_tmp_table1); + filesort_free_buffers(exec_tmp_table1,0); + } + if (exec_tmp_table2) + { + exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE); + exec_tmp_table2->file->ha_delete_all_rows(); + free_io_cache(exec_tmp_table2); + filesort_free_buffers(exec_tmp_table2,0); + } + if (items0) + set_items_ref_array(items0); + + if (join_tab_save) + memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables); + + if (tmp_join) + restore_tmp(); + + /* Reset of sum functions */ + if (sum_funcs) + { + Item_sum *func, **func_ptr= sum_funcs; + while ((func= *(func_ptr++))) + func->clear(); + } + + DBUG_RETURN(0); +} + +/** + @brief Save the original join layout + + @details Saves the original join layout so it can be reused in + re-execution and for EXPLAIN. + + @return Operation status + @retval 0 success. + @retval 1 error occurred. +*/ + +bool +JOIN::init_save_join_tab() +{ + if (!(tmp_join= (JOIN*)thd->alloc(sizeof(JOIN)))) + return 1; /* purecov: inspected */ + error= 0; // Ensure that tmp_join.error= 0 + restore_tmp(); + return 0; +} + + +bool +JOIN::save_join_tab() +{ + if (!join_tab_save && select_lex->master_unit()->uncacheable) + { + if (!(join_tab_save= (JOIN_TAB*)thd->memdup((uchar*) join_tab, + sizeof(JOIN_TAB) * tables))) + return 1; + } + return 0; +} + + +/** + Exec select. + + @todo + Note, that create_sort_index calls test_if_skip_sort_order and may + finally replace sorting with index scan if there is a LIMIT clause in + the query. It's never shown in EXPLAIN! + + @todo + When can we have here thd->net.report_error not zero? +*/ +void +JOIN::exec() +{ + List *columns_list= &fields_list; + int tmp_error; + DBUG_ENTER("JOIN::exec"); + + thd_proc_info(thd, "executing"); + error= 0; + + // ------------------------------ Calpont InfiniDB ------------------------------ + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE/* && tables_list*/) + { + /* @InfiniDB We've found MySQL gives "Impossible Where" for such query: + * select * from region where 1 in (select n_regionkey from nation); + * which confused InfiniDB processing. Do not redo query if the query has subselect. + */ + if (zero_result_cause + && !union_part // not in a union unit + /* && select_lex == &thd->lex->select_lex && (!conds || !conds->with_subselect)*/ + && !(select_lex && select_lex->master_unit() && select_lex->master_unit()->item) // not a subselect unit + && !(select_lex && select_lex->first_inner_unit()) // not a query with subselect + // @bug5083. zero_result_cause was not set properly for outer join on derived + // table process phase. + && !(thd->derived_tables_processing) + ) + { + // @bug 1818. Make MySQL redo this query and return empty result set without going + // to Calpont engine. + thd->infinidb_vtable.vtable_state = THD::INFINIDB_REDO_QUERY; + DBUG_VOID_RETURN; + } + + // by pass MySQL union trips + if (thd->infinidb_vtable.isUnion) + DBUG_VOID_RETURN; + + //@todo special api to send plan + TABLE_LIST* tl = tables_list; + bool hasCalpont = false; + bool hasNonCalpont = false; + TABLE_LIST* IDBtable = NULL; + + // @bug 2976. Check global tables for IDB table. If no IDB tables involved, redo this query with normal path. + TABLE_LIST* global_list = thd->lex->query_tables; + + for (; global_list; global_list = global_list->next_global) + { + //if (!global_list->table || !global_list->table->s->db_plugin) + if (!(global_list->table && global_list->table->s && global_list->table->s->db_plugin)) + continue; + //Windows never has SAFE_MUTEX defined... + // @InfiniDB watch out for FROM clause derived table. union memeory table has tablename="union" + if (global_list->table && global_list->table->isInfiniDB()) + { + hasCalpont = true; + IDBtable = global_list; + continue; + } +#if (defined(_MSC_VER) && defined(_DEBUG)) || defined(SAFE_MUTEX) + else if (global_list->table && + global_list->table->s && + global_list->table->s->db_plugin && + strcmp((*global_list->table->s->db_plugin)->name.str, "MEMORY") == 0 || + global_list->table->s->table_category == TABLE_CATEGORY_TEMPORARY) +#else + else if (global_list->table && + global_list->table->s && + global_list->table->s->db_plugin && + strcmp(global_list->table->s->db_plugin->name.str, "MEMORY") == 0 || + global_list->table->s->table_category == TABLE_CATEGORY_TEMPORARY) +#endif + { + continue; + } + else + { + hasNonCalpont = true; + } + } + + // @bug 2839. only memory table in table list. redo_query. + if (!hasCalpont) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_REDO_QUERY; + DBUG_VOID_RETURN; + } + // @InfiniDB. Cross engine support + else if (/*hasNonCalpont && hasCalpont*/false) + { + const char* emsg = "IDB-7001: Non InfiniDB table(s) on the FROM clause."; + thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; + if (!thd->infinidb_vtable.autoswitch) + { + thd->killed = THD::KILL_QUERY; + thd->main_da.can_overwrite_status = true; + thd->main_da.set_error_status(thd, ER_UNKNOWN_ERROR, emsg); + } + else + { + thd->main_da.can_overwrite_status = true; + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 9999, emsg); + } + DBUG_VOID_RETURN; + } + + if (tables_list && tables_list->table && tables_list->table->isInfiniDB()) + // ZZ: In deriived_tables_processing phase, the plan out of mysql's optimizer may not be + // complete. IDB will skip the phase in case of plan error instead of error out, so + // MySQL will continue it's optimization. Now the first table in tables_list may not + // be an IDB table (could be a derived table, for example). In such case, we use an IDB table + // to trigger rnd_init; otherwise, still use the first table in the list. + // @todo always use IDBtable without checking the first table. Still have some plan + // mistery to solve. + IDBtable = tables_list; + if (IDBtable && IDBtable->table && IDBtable->table->file && IDBtable->table->file->ha_rnd_init(1)) + thd->infinidb_vtable.vtable_state = THD::INFINIDB_ERROR; + + for (global_list = thd->lex->query_tables; global_list; global_list = global_list->next_global) + { + if (global_list->table && global_list->table->file) + global_list->table->file->inited = handler::NONE; + } + + // @bug 2547 + if (zero_result_cause) + { + tl = tables_list; + + for (; tl; tl= tl->next_global) + { + // @InfiniDB. Bug4422. Need to check all pointer not null + if (tl->table && tl->table->file) + tl->table->file->inited = handler::NONE; + } + } + DBUG_VOID_RETURN; + } + + // for some derived table case, mysql make tables_list empty. + // example: select count(*) from (select * from nation) a; + else if (!(thd->infinidb_vtable.vtable_state == THD::INFINIDB_DISABLE_VTABLE) && + thd->lex && + thd->lex->derived_tables && + thd->infinidb_vtable.isUnion) + { + //thd->infinidb_vtable.isUnion = false; // imply derived table + DBUG_VOID_RETURN; + } + else if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE + && !tables_list + && !union_part + && thd->lex + && select_lex == &thd->lex->select_lex) // from dual case + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_REDO_QUERY; + DBUG_VOID_RETURN; + } + else if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_PHASE1) + { + if (!union_part) + { + thd->infinidb_vtable.vtable_state = THD::INFINIDB_CREATE_VTABLE; + thd->infinidb_vtable.isUnion = true; // make it skip rnd_init for redo phase. + } + DBUG_VOID_RETURN; + } + + if (procedure) + { + procedure_fields_list= fields_list; + if (procedure->change_columns(procedure_fields_list) || + result->prepare(procedure_fields_list, unit)) + { + thd->limit_found_rows= thd->examined_row_count= 0; + DBUG_VOID_RETURN; + } + columns_list= &procedure_fields_list; + } + (void) result->prepare2(); // Currently, this cannot fail. + + if (!tables_list && (tables || !select_lex->with_sum_func)) + { // Only test of functions + if (select_options & SELECT_DESCRIBE) + select_describe(this, FALSE, FALSE, FALSE, + (zero_result_cause?zero_result_cause:"No tables used")); + else + { + if (result->send_fields(*columns_list, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) + { + DBUG_VOID_RETURN; + } + /* + We have to test for 'conds' here as the WHERE may not be constant + even if we don't have any tables for prepared statements or if + conds uses something like 'rand()'. + If the HAVING clause is either impossible or always true, then + JOIN::having is set to NULL by optimize_cond. + In this case JOIN::exec must check for JOIN::having_value, in the + same way it checks for JOIN::cond_value. + */ + if (cond_value != Item::COND_FALSE && + having_value != Item::COND_FALSE && + (!conds || conds->val_int()) && + (!having || having->val_int())) + { + if (do_send_rows && + (procedure ? (procedure->send_row(procedure_fields_list) || + procedure->end_of_records()) : result->send_data(fields_list))) + error= 1; + else + { + error= (int) result->send_eof(); + send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 : + thd->sent_row_count); + } + } + else + { + error=(int) result->send_eof(); + send_records= 0; + } + } + /* Single select (without union) always returns 0 or 1 row */ + thd->limit_found_rows= send_records; + thd->examined_row_count= 0; + DBUG_VOID_RETURN; + } + /* + Don't reset the found rows count if there're no tables as + FOUND_ROWS() may be called. Never reset the examined row count here. + It must be accumulated from all join iterations of all join parts. + */ + if (tables) + thd->limit_found_rows= 0; + + if (zero_result_cause) + { + (void) return_zero_rows(this, result, select_lex->leaf_tables, + *columns_list, + send_row_on_empty_set(), + select_options, + zero_result_cause, + having); + DBUG_VOID_RETURN; + } + + if ((this->select_lex->options & OPTION_SCHEMA_TABLE) && + get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC)) + DBUG_VOID_RETURN; + + if (select_options & SELECT_DESCRIBE) + { + /* + Check if we managed to optimize ORDER BY away and don't use temporary + table to resolve ORDER BY: in that case, we only may need to do + filesort for GROUP BY. + */ + if (!order && !no_order && (!skip_sort_order || !need_tmp)) + { + /* + Reset 'order' to 'group_list' and reinit variables describing + 'order' + */ + order= group_list; + simple_order= simple_group; + skip_sort_order= 0; + } + if (order && + (order != group_list || !(select_options & SELECT_BIG_RESULT)) && + (const_tables == tables || + ((simple_order || skip_sort_order) && + test_if_skip_sort_order(&join_tab[const_tables], order, + select_limit, 0, + &join_tab[const_tables].table-> + keys_in_use_for_query)))) + order=0; + having= tmp_having; + select_describe(this, need_tmp, + order != 0 && !skip_sort_order, + select_distinct, + !tables ? "No tables used" : NullS); + DBUG_VOID_RETURN; + } + + JOIN *curr_join= this; + List *curr_all_fields= &all_fields; + List *curr_fields_list= &fields_list; + TABLE *curr_tmp_table= 0; + /* + Initialize examined rows here because the values from all join parts + must be accumulated in examined_row_count. Hence every join + iteration must count from zero. + */ + curr_join->examined_rows= 0; + + /* Create a tmp table if distinct or if the sort is too complicated */ + if (need_tmp) + { + if (tmp_join) + { + /* + We are in a non cacheable sub query. Get the saved join structure + after optimization. + (curr_join may have been modified during last exection and we need + to reset it) + */ + curr_join= tmp_join; + } + curr_tmp_table= exec_tmp_table1; + + /* Copy data to the temporary table */ + thd_proc_info(thd, "Copying to tmp table"); + DBUG_PRINT("info", ("%s", thd->proc_info)); + if (!curr_join->sort_and_group && + curr_join->const_tables != curr_join->tables) + curr_join->join_tab[curr_join->const_tables].sorted= 0; + if ((tmp_error= do_select(curr_join, (List *) 0, curr_tmp_table, 0))) + { + error= tmp_error; + DBUG_VOID_RETURN; + } + curr_tmp_table->file->info(HA_STATUS_VARIABLE); + + if (curr_join->having) + curr_join->having= curr_join->tmp_having= 0; // Allready done + + /* Change sum_fields reference to calculated fields in tmp_table */ + if (curr_join != this) + curr_join->all_fields= *curr_all_fields; + if (!items1) + { + items1= items0 + all_fields.elements; + if (sort_and_group || curr_tmp_table->group || + tmp_table_param.precomputed_group_by) + { + if (change_to_use_tmp_fields(thd, items1, + tmp_fields_list1, tmp_all_fields1, + fields_list.elements, all_fields)) + DBUG_VOID_RETURN; + } + else + { + if (change_refs_to_tmp_fields(thd, items1, + tmp_fields_list1, tmp_all_fields1, + fields_list.elements, all_fields)) + DBUG_VOID_RETURN; + } + if (curr_join != this) + { + curr_join->tmp_all_fields1= tmp_all_fields1; + curr_join->tmp_fields_list1= tmp_fields_list1; + } + curr_join->items1= items1; + } + curr_all_fields= &tmp_all_fields1; + curr_fields_list= &tmp_fields_list1; + curr_join->set_items_ref_array(items1); + + if (sort_and_group || curr_tmp_table->group) + { + curr_join->tmp_table_param.field_count+= + curr_join->tmp_table_param.sum_func_count+ + curr_join->tmp_table_param.func_count; + curr_join->tmp_table_param.sum_func_count= + curr_join->tmp_table_param.func_count= 0; + } + else + { + curr_join->tmp_table_param.field_count+= + curr_join->tmp_table_param.func_count; + curr_join->tmp_table_param.func_count= 0; + } + + // procedure can't be used inside subselect => we do nothing special for it + if (procedure) + procedure->update_refs(); + + if (curr_tmp_table->group) + { // Already grouped + if (!curr_join->order && !curr_join->no_order && !skip_sort_order) + curr_join->order= curr_join->group_list; /* order by group */ + curr_join->group_list= 0; + } + + /* + If we have different sort & group then we must sort the data by group + and copy it to another tmp table + This code is also used if we are using distinct something + we haven't been able to store in the temporary table yet + like SEC_TO_TIME(SUM(...)). + */ + + if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, + curr_join->order) || + curr_join->select_distinct)) || + (curr_join->select_distinct && + curr_join->tmp_table_param.using_indirect_summary_function)) + { /* Must copy to another table */ + DBUG_PRINT("info",("Creating group table")); + + /* Free first data from old join */ + curr_join->join_free(); + if (curr_join->make_simple_join(this, curr_tmp_table)) + DBUG_VOID_RETURN; + calc_group_buffer(curr_join, group_list); + count_field_types(select_lex, &curr_join->tmp_table_param, + curr_join->tmp_all_fields1, + curr_join->select_distinct && !curr_join->group_list); + curr_join->tmp_table_param.hidden_field_count= + (curr_join->tmp_all_fields1.elements- + curr_join->tmp_fields_list1.elements); + + + if (exec_tmp_table2) + curr_tmp_table= exec_tmp_table2; + else + { + /* group data to new table */ + + /* + If the access method is loose index scan then all MIN/MAX + functions are precomputed, and should be treated as regular + functions. See extended comment in JOIN::exec. + */ + if (curr_join->join_tab->is_using_loose_index_scan()) + curr_join->tmp_table_param.precomputed_group_by= TRUE; + + if (!(curr_tmp_table= + exec_tmp_table2= create_tmp_table(thd, + &curr_join->tmp_table_param, + *curr_all_fields, + (ORDER*) 0, + curr_join->select_distinct && + !curr_join->group_list, + 1, curr_join->select_options, + HA_POS_ERROR, + (char *) ""))) + DBUG_VOID_RETURN; + curr_join->exec_tmp_table2= exec_tmp_table2; + } + if (curr_join->group_list) + { + thd_proc_info(thd, "Creating sort index"); + if (curr_join->join_tab == join_tab && save_join_tab()) + { + DBUG_VOID_RETURN; + } + if (create_sort_index(thd, curr_join, curr_join->group_list, + HA_POS_ERROR, HA_POS_ERROR, FALSE) || + make_group_fields(this, curr_join)) + { + DBUG_VOID_RETURN; + } + sortorder= curr_join->sortorder; + } + + thd_proc_info(thd, "Copying to group table"); + DBUG_PRINT("info", ("%s", thd->proc_info)); + tmp_error= -1; + if (curr_join != this) + { + if (sum_funcs2) + { + curr_join->sum_funcs= sum_funcs2; + curr_join->sum_funcs_end= sum_funcs_end2; + } + else + { + curr_join->alloc_func_list(); + sum_funcs2= curr_join->sum_funcs; + sum_funcs_end2= curr_join->sum_funcs_end; + } + } + if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list, + 1, TRUE)) + DBUG_VOID_RETURN; + curr_join->group_list= 0; + if (!curr_join->sort_and_group && + curr_join->const_tables != curr_join->tables) + curr_join->join_tab[curr_join->const_tables].sorted= 0; + if (setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) || + (tmp_error= do_select(curr_join, (List *) 0, curr_tmp_table, + 0))) + { + error= tmp_error; + DBUG_VOID_RETURN; + } + end_read_record(&curr_join->join_tab->read_record); + curr_join->const_tables= curr_join->tables; // Mark free for cleanup() + curr_join->join_tab[0].table= 0; // Table is freed + + // No sum funcs anymore + if (!items2) + { + items2= items1 + all_fields.elements; + if (change_to_use_tmp_fields(thd, items2, + tmp_fields_list2, tmp_all_fields2, + fields_list.elements, tmp_all_fields1)) + DBUG_VOID_RETURN; + if (curr_join != this) + { + curr_join->tmp_fields_list2= tmp_fields_list2; + curr_join->tmp_all_fields2= tmp_all_fields2; + } + } + curr_fields_list= &curr_join->tmp_fields_list2; + curr_all_fields= &curr_join->tmp_all_fields2; + curr_join->set_items_ref_array(items2); + curr_join->tmp_table_param.field_count+= + curr_join->tmp_table_param.sum_func_count; + curr_join->tmp_table_param.sum_func_count= 0; + } + if (curr_tmp_table->distinct) + curr_join->select_distinct=0; /* Each row is unique */ + + curr_join->join_free(); /* Free quick selects */ + if (curr_join->select_distinct && ! curr_join->group_list) + { + thd_proc_info(thd, "Removing duplicates"); + if (curr_join->tmp_having) + curr_join->tmp_having->update_used_tables(); + if (remove_duplicates(curr_join, curr_tmp_table, + *curr_fields_list, curr_join->tmp_having)) + DBUG_VOID_RETURN; + curr_join->tmp_having=0; + curr_join->select_distinct=0; + } + curr_tmp_table->reginfo.lock_type= TL_UNLOCK; + if (curr_join->make_simple_join(this, curr_tmp_table)) + DBUG_VOID_RETURN; + calc_group_buffer(curr_join, curr_join->group_list); + count_field_types(select_lex, &curr_join->tmp_table_param, + *curr_all_fields, 0); + + } + if (procedure) + count_field_types(select_lex, &curr_join->tmp_table_param, + *curr_all_fields, 0); + + if (curr_join->group || curr_join->tmp_table_param.sum_func_count || + (procedure && (procedure->flags & PROC_GROUP))) + { + if (make_group_fields(this, curr_join)) + { + DBUG_VOID_RETURN; + } + if (!items3) + { + if (!items0) + init_items_ref_array(); + items3= ref_pointer_array + (all_fields.elements*4); + setup_copy_fields(thd, &curr_join->tmp_table_param, + items3, tmp_fields_list3, tmp_all_fields3, + curr_fields_list->elements, *curr_all_fields); + tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs; + tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field; + tmp_table_param.save_copy_field_end= + curr_join->tmp_table_param.copy_field_end; + if (curr_join != this) + { + curr_join->tmp_all_fields3= tmp_all_fields3; + curr_join->tmp_fields_list3= tmp_fields_list3; + } + } + else + { + curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs; + curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field; + curr_join->tmp_table_param.copy_field_end= + tmp_table_param.save_copy_field_end; + } + curr_fields_list= &tmp_fields_list3; + curr_all_fields= &tmp_all_fields3; + curr_join->set_items_ref_array(items3); + + if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list, + 1, TRUE) || + setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) || + thd->is_fatal_error) + DBUG_VOID_RETURN; + } + if (curr_join->group_list || curr_join->order) + { + DBUG_PRINT("info",("Sorting for send_fields")); + thd_proc_info(thd, "Sorting result"); + /* If we have already done the group, add HAVING to sorted table */ + if (curr_join->tmp_having && ! curr_join->group_list && + ! curr_join->sort_and_group) + { + // Some tables may have been const + curr_join->tmp_having->update_used_tables(); + JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables]; + table_map used_tables= (curr_join->const_table_map | + curr_table->table->map); + + Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having, + used_tables, + used_tables); + if (sort_table_cond) + { + if (!curr_table->select) + if (!(curr_table->select= new SQL_SELECT)) + DBUG_VOID_RETURN; + if (!curr_table->select->cond) + curr_table->select->cond= sort_table_cond; + else // This should never happen + { + if (!(curr_table->select->cond= + new Item_cond_and(curr_table->select->cond, + sort_table_cond))) + DBUG_VOID_RETURN; + /* + Item_cond_and do not need fix_fields for execution, its parameters + are fixed or do not need fix_fields, too + */ + curr_table->select->cond->quick_fix_field(); + } + curr_table->select_cond= curr_table->select->cond; + curr_table->select_cond->top_level_item(); + DBUG_EXECUTE("where",print_where(curr_table->select->cond, + "select and having", + QT_ORDINARY);); + curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having, + ~ (table_map) 0, + ~used_tables); + DBUG_EXECUTE("where",print_where(curr_join->tmp_having, + "having after sort", + QT_ORDINARY);); + } + } + { + if (group) + curr_join->select_limit= HA_POS_ERROR; + else + { + /* + We can abort sorting after thd->select_limit rows if we there is no + WHERE clause for any tables after the sorted one. + */ + JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1]; + JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables]; + for (; curr_table < end_table ; curr_table++) + { + /* + table->keyuse is set in the case there was an original WHERE clause + on the table that was optimized away. + */ + if (curr_table->select_cond || + (curr_table->keyuse && !curr_table->first_inner)) + { + /* We have to sort all rows */ + curr_join->select_limit= HA_POS_ERROR; + break; + } + } + } + if (curr_join->join_tab == join_tab && save_join_tab()) + { + DBUG_VOID_RETURN; + } + /* + Here we sort rows for ORDER BY/GROUP BY clause, if the optimiser + chose FILESORT to be faster than INDEX SCAN or there is no + suitable index present. + Note, that create_sort_index calls test_if_skip_sort_order and may + finally replace sorting with index scan if there is a LIMIT clause in + the query. XXX: it's never shown in EXPLAIN! + OPTION_FOUND_ROWS supersedes LIMIT and is taken into account. + */ + if (create_sort_index(thd, curr_join, + curr_join->group_list ? + curr_join->group_list : curr_join->order, + curr_join->select_limit, + (select_options & OPTION_FOUND_ROWS ? + HA_POS_ERROR : unit->select_limit_cnt), + curr_join->group_list ? TRUE : FALSE)) + DBUG_VOID_RETURN; + sortorder= curr_join->sortorder; + if (curr_join->const_tables != curr_join->tables && + !curr_join->join_tab[curr_join->const_tables].table->sort.io_cache) + { + /* + If no IO cache exists for the first table then we are using an + INDEX SCAN and no filesort. Thus we should not remove the sorted + attribute on the INDEX SCAN. + */ + skip_sort_order= 1; + } + } + } + /* XXX: When can we have here thd->is_error() not zero? */ + if (thd->is_error()) + { + error= thd->is_error(); + DBUG_VOID_RETURN; + } + curr_join->having= curr_join->tmp_having; + curr_join->fields= curr_fields_list; + curr_join->procedure= procedure; + + if (is_top_level_join() && thd->cursor && tables != const_tables) + { + /* + We are here if this is JOIN::exec for the last select of the main unit + and the client requested to open a cursor. + We check that not all tables are constant because this case is not + handled by do_select() separately, and this case is not implemented + for cursors yet. + */ + DBUG_ASSERT(error == 0); + /* + curr_join is used only for reusable joins - that is, + to perform SELECT for each outer row (like in subselects). + This join is main, so we know for sure that curr_join == join. + */ + DBUG_ASSERT(curr_join == this); + /* Open cursor for the last join sweep */ + error= thd->cursor->open(this); + } + else + { + thd_proc_info(thd, "Sending data"); + DBUG_PRINT("info", ("%s", thd->proc_info)); + result->send_fields((procedure ? curr_join->procedure_fields_list : + *curr_fields_list), + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF); + error= do_select(curr_join, curr_fields_list, NULL, procedure); + thd->limit_found_rows= curr_join->send_records; // ZZ : 5 + } + + /* Accumulate the counts from all join iterations of all join parts. */ + thd->examined_row_count+= curr_join->examined_rows; + DBUG_PRINT("counts", ("thd->examined_row_count: %lu", + (ulong) thd->examined_row_count)); + + /* + With EXPLAIN EXTENDED we have to restore original ref_array + for a derived table which is always materialized. + We also need to do this when we have temp table(s). + Otherwise we would not be able to print the query correctly. + */ + if (items0 && (thd->lex->describe & DESCRIBE_EXTENDED) && + (select_lex->linkage == DERIVED_TABLE_TYPE || + exec_tmp_table1 || exec_tmp_table2)) + set_items_ref_array(items0); + + DBUG_VOID_RETURN; +} + + +/** + Clean up join. + + @return + Return error that hold JOIN. +*/ + +int +JOIN::destroy() +{ + DBUG_ENTER("JOIN::destroy"); + select_lex->join= 0; + + if (tmp_join) + { + if (join_tab != tmp_join->join_tab) + { + JOIN_TAB *tab, *end; + for (tab= join_tab, end= tab+tables ; tab != end ; tab++) + tab->cleanup(); + } + tmp_join->tmp_join= 0; + tmp_table_param.copy_field=0; + DBUG_RETURN(tmp_join->destroy()); + } + cond_equal= 0; + + cleanup(1); + /* Cleanup items referencing temporary table columns */ + if (!tmp_all_fields3.is_empty()) + { + List_iterator_fast it(tmp_all_fields3); + Item *item; + while ((item= it++)) + item->cleanup(); + } + if (exec_tmp_table1) + free_tmp_table(thd, exec_tmp_table1); + if (exec_tmp_table2) + free_tmp_table(thd, exec_tmp_table2); + delete select; + delete_dynamic(&keyuse); + delete procedure; + DBUG_RETURN(error); +} + +/** + An entry point to single-unit select (a select without UNION). + + @param thd thread handler + @param rref_pointer_array a reference to ref_pointer_array of + the top-level select_lex for this query + @param tables list of all tables used in this query. + The tables have been pre-opened. + @param wild_num number of wildcards used in the top level + select of this query. + For example statement + SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2; + has 3 wildcards. + @param fields list of items in SELECT list of the top-level + select + e.g. SELECT a, b, c FROM t1 will have Item_field + for a, b and c in this list. + @param conds top level item of an expression representing + WHERE clause of the top level select + @param og_num total number of ORDER BY and GROUP BY clauses + arguments + @param order linked list of ORDER BY agruments + @param group linked list of GROUP BY arguments + @param having top level item of HAVING expression + @param proc_param list of PROCEDUREs + @param select_options select options (BIG_RESULT, etc) + @param result an instance of result set handling class. + This object is responsible for send result + set rows to the client or inserting them + into a table. + @param select_lex the only SELECT_LEX of this query + @param unit top-level UNIT of this query + UNIT is an artificial object created by the + parser for every SELECT clause. + e.g. + SELECT * FROM t1 WHERE a1 IN (SELECT * FROM t2) + has 2 unions. + + @retval + FALSE success + @retval + TRUE an error +*/ + +bool +mysql_select(THD *thd, Item ***rref_pointer_array, + TABLE_LIST *tables, uint wild_num, List &fields, + COND *conds, uint og_num, ORDER *order, ORDER *group, + Item *having, ORDER *proc_param, ulonglong select_options, + select_result *result, SELECT_LEX_UNIT *unit, + SELECT_LEX *select_lex) +{ + bool err; + bool free_join= 1; + DBUG_ENTER("mysql_select"); + + select_lex->context.resolve_in_select_list= TRUE; + JOIN *join; + if (select_lex->join != 0) + { + join= select_lex->join; + /* + is it single SELECT in derived table, called in derived table + creation + */ + if (select_lex->linkage != DERIVED_TABLE_TYPE || + (select_options & SELECT_DESCRIBE)) + { + if (select_lex->linkage != GLOBAL_OPTIONS_TYPE) + { + //here is EXPLAIN of subselect or derived table + if (join->change_result(result)) + { + DBUG_RETURN(TRUE); + } + } + else + { + err= join->prepare(rref_pointer_array, tables, wild_num, + conds, og_num, order, group, having, proc_param, + select_lex, unit); + if (err) + { + goto err; + } + } + } + free_join= 0; + join->select_options= select_options; + } + else + { + if (!(join= new JOIN(thd, fields, select_options, result))) + DBUG_RETURN(TRUE); + thd_proc_info(thd, "init"); + thd->used_tables=0; // Updated by setup_fields + err= join->prepare(rref_pointer_array, tables, wild_num, + conds, og_num, order, group, having, proc_param, + select_lex, unit); + if (err) + { + goto err; + } + } + + if ((err= join->optimize())) + { + goto err; // 1 + } + + if (thd->lex->describe & DESCRIBE_EXTENDED) + { + join->conds_history= join->conds; + join->having_history= (join->having?join->having:join->tmp_having); + } + + if (thd->is_error()) + goto err; + + join->exec(); + + if (thd->cursor && thd->cursor->is_open()) + { + /* + A cursor was opened for the last sweep in exec(). + We are here only if this is mysql_select for top-level SELECT_LEX_UNIT + and there were no error. + */ + free_join= 0; + } + + if (thd->lex->describe & DESCRIBE_EXTENDED) + { + select_lex->where= join->conds_history; + select_lex->having= join->having_history; + } + +err: + if (free_join) + { + thd_proc_info(thd, "end"); + err|= select_lex->cleanup(); + DBUG_RETURN(err || thd->is_error()); + } + + DBUG_RETURN(join->error); +} + +/***************************************************************************** + Create JOIN_TABS, make a guess about the table types, + Approximate how many records will be used in each table +*****************************************************************************/ + +static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select, + TABLE *table, + const key_map *keys,ha_rows limit) +{ + int error; + DBUG_ENTER("get_quick_record_count"); +#ifndef EMBEDDED_LIBRARY // Avoid compiler warning + uchar buff[STACK_BUFF_ALLOC]; +#endif + if (check_stack_overrun(thd, STACK_MIN_SIZE, buff)) + DBUG_RETURN(0); // Fatal error flag is set + if (select) + { + select->head=table; + if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0, + limit, 0)) == 1) + DBUG_RETURN(select->quick->records); + if (error == -1) + { + table->reginfo.impossible_range=1; + DBUG_RETURN(0); + } + DBUG_PRINT("warning",("Couldn't use record count on const keypart")); + } + DBUG_RETURN(HA_POS_ERROR); /* This shouldn't happend */ +} + +/* + This structure is used to collect info on potentially sargable + predicates in order to check whether they become sargable after + reading const tables. + We form a bitmap of indexes that can be used for sargable predicates. + Only such indexes are involved in range analysis. +*/ +typedef struct st_sargable_param +{ + Field *field; /* field against which to check sargability */ + Item **arg_value; /* values of potential keys for lookups */ + uint num_values; /* number of values in the above array */ +} SARGABLE_PARAM; + +/** + Calculate the best possible join and initialize the join structure. + + @retval + 0 ok + @retval + 1 Fatal error +*/ + +static bool +make_join_statistics(JOIN *join, TABLE_LIST *tables_arg, COND *conds, + DYNAMIC_ARRAY *keyuse_array) +{ + int error; + TABLE *table; + TABLE_LIST *tables= tables_arg; + uint i,table_count,const_count,key; + table_map found_const_table_map, all_table_map, found_ref, refs; + key_map const_ref, eq_part; + TABLE **table_vector; + JOIN_TAB *stat,*stat_end,*s,**stat_ref; + KEYUSE *keyuse,*start_keyuse; + table_map outer_join=0; + SARGABLE_PARAM *sargables= 0; + JOIN_TAB *stat_vector[MAX_TABLES+1]; + DBUG_ENTER("make_join_statistics"); + + table_count=join->tables; + stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count); + stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES); + table_vector=(TABLE**) join->thd->alloc(sizeof(TABLE*)*(table_count*2)); + if (!stat || !stat_ref || !table_vector) + DBUG_RETURN(1); // Eom /* purecov: inspected */ + + join->best_ref=stat_vector; + + stat_end=stat+table_count; + found_const_table_map= all_table_map=0; + const_count=0; + + for (s= stat, i= 0; + tables; + s++, tables= tables->next_leaf, i++) + { + TABLE_LIST *embedding= tables->embedding; + stat_vector[i]=s; + s->keys.init(); + s->const_keys.init(); + s->checked_keys.init(); + s->needed_reg.init(); + table_vector[i]=s->table=table=tables->table; + table->pos_in_table_list= tables; + error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); + if (error) + { + table->file->print_error(error, MYF(0)); + goto error; + } + table->quick_keys.clear_all(); + table->reginfo.join_tab=s; + table->reginfo.not_exists_optimize=0; + bzero((char*) table->const_key_parts, sizeof(key_part_map)*table->s->keys); + all_table_map|= table->map; + s->join=join; + s->info=0; // For describe + + s->dependent= tables->dep_tables; + s->key_dependent= 0; + if (tables->schema_table) + table->file->stats.records= 2; + table->quick_condition_rows= table->file->stats.records; + + s->on_expr_ref= &tables->on_expr; + if (*s->on_expr_ref) + { + /* s is the only inner table of an outer join */ +#ifdef WITH_PARTITION_STORAGE_ENGINE + if ((!table->file->stats.records || table->no_partitions_used) && !embedding) +#else + if (!table->file->stats.records && !embedding) +#endif + { // Empty table + s->dependent= 0; // Ignore LEFT JOIN depend. + set_position(join,const_count++,s,(KEYUSE*) 0); + continue; + } + outer_join|= table->map; + s->embedding_map= 0; + for (;embedding; embedding= embedding->embedding) + s->embedding_map|= embedding->nested_join->nj_map; + continue; + } + if (embedding) + { + /* s belongs to a nested join, maybe to several embedded joins */ + s->embedding_map= 0; + do + { + NESTED_JOIN *nested_join= embedding->nested_join; + s->embedding_map|=nested_join->nj_map; + s->dependent|= embedding->dep_tables; + embedding= embedding->embedding; + outer_join|= nested_join->used_tables; + } + while (embedding); + continue; + } +#ifdef WITH_PARTITION_STORAGE_ENGINE + const bool no_partitions_used= table->no_partitions_used; +#else + const bool no_partitions_used= FALSE; +#endif + if ((table->s->system || table->file->stats.records <= 1 || + no_partitions_used) && + !s->dependent && + (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && + !table->fulltext_searched && !join->no_const_tables) + { + set_position(join,const_count++,s,(KEYUSE*) 0); + } + } + stat_vector[i]=0; + join->outer_join=outer_join; + + if (join->outer_join) + { + /* + Build transitive closure for relation 'to be dependent on'. + This will speed up the plan search for many cases with outer joins, + as well as allow us to catch illegal cross references/ + Warshall's algorithm is used to build the transitive closure. + As we use bitmaps to represent the relation the complexity + of the algorithm is O((number of tables)^2). + */ + for (i= 0, s= stat ; i < table_count ; i++, s++) + { + for (uint j= 0 ; j < table_count ; j++) + { + table= stat[j].table; + if (s->dependent & table->map) + s->dependent |= table->reginfo.join_tab->dependent; + } + if (outer_join & s->table->map) + s->table->maybe_null= 1; + } + /* Catch illegal cross references for outer joins */ + for (i= 0, s= stat ; i < table_count ; i++, s++) + { + if (s->dependent & s->table->map) + { + join->tables=0; // Don't use join->table + my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0)); + goto error; + } + s->key_dependent= s->dependent; + } + } + + if (conds || outer_join) + if (update_ref_and_keys(join->thd, keyuse_array, stat, join->tables, + conds, join->cond_equal, + ~outer_join, join->select_lex, &sargables)) + goto error; + + /* Read tables with 0 or 1 rows (system tables) */ + join->const_table_map= 0; + + for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count; + p_pos < p_end ; + p_pos++) + { + int tmp; + s= p_pos->table; + s->type=JT_SYSTEM; + join->const_table_map|=s->table->map; + if ((tmp=join_read_const_table(s, p_pos))) + { + if (tmp > 0) + goto error; // Fatal error + } + else + found_const_table_map|= s->table->map; + } + + /* loop until no more const tables are found */ + int ref_changed; + do + { + more_const_tables_found: + ref_changed = 0; + found_ref=0; + + /* + We only have to loop from stat_vector + const_count as + set_position() will move all const_tables first in stat_vector + */ + + for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++) + { + table=s->table; + + /* + If equi-join condition by a key is null rejecting and after a + substitution of a const table the key value happens to be null + then we can state that there are no matches for this equi-join. + */ + if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map) + { + /* + When performing an outer join operation if there are no matching rows + for the single row of the outer table all the inner tables are to be + null complemented and thus considered as constant tables. + Here we apply this consideration to the case of outer join operations + with a single inner table only because the case with nested tables + would require a more thorough analysis. + TODO. Apply single row substitution to null complemented inner tables + for nested outer join operations. + */ + while (keyuse->table == table) + { + if (!(keyuse->val->used_tables() & ~join->const_table_map) && + keyuse->val->is_null() && keyuse->null_rejecting) + { + s->type= JT_CONST; + mark_as_null_row(table); + found_const_table_map|= table->map; + join->const_table_map|= table->map; + set_position(join,const_count++,s,(KEYUSE*) 0); + goto more_const_tables_found; + } + keyuse++; + } + } + + if (s->dependent) // If dependent on some table + { + // All dep. must be constants + if (s->dependent & ~(found_const_table_map)) + continue; + if (table->file->stats.records <= 1L && + (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && + !table->pos_in_table_list->embedding) + { // system table + int tmp= 0; + s->type=JT_SYSTEM; + join->const_table_map|=table->map; + set_position(join,const_count++,s,(KEYUSE*) 0); + if ((tmp= join_read_const_table(s, join->positions+const_count-1))) + { + if (tmp > 0) + goto error; // Fatal error + } + else + found_const_table_map|= table->map; + continue; + } + } + /* check if table can be read by key or table only uses const refs */ + if ((keyuse=s->keyuse)) + { + s->type= JT_REF; + while (keyuse->table == table) + { + start_keyuse=keyuse; + key=keyuse->key; + s->keys.set_bit(key); // QQ: remove this ? + + refs=0; + const_ref.clear_all(); + eq_part.clear_all(); + do + { + if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize) + { + if (!((~found_const_table_map) & keyuse->used_tables)) + const_ref.set_bit(keyuse->keypart); + else + refs|=keyuse->used_tables; + eq_part.set_bit(keyuse->keypart); + } + keyuse++; + } while (keyuse->table == table && keyuse->key == key); + + if (eq_part.is_prefix(table->key_info[key].key_parts) && + !table->fulltext_searched && + !table->pos_in_table_list->embedding) + { + if ((table->key_info[key].flags & (HA_NOSAME | HA_END_SPACE_KEY)) + == HA_NOSAME) + { + if (const_ref == eq_part) + { // Found everything for ref. + int tmp; + ref_changed = 1; + s->type= JT_CONST; + join->const_table_map|=table->map; + set_position(join,const_count++,s,start_keyuse); + if (create_ref_for_key(join, s, start_keyuse, + found_const_table_map)) + goto error; + if ((tmp=join_read_const_table(s, + join->positions+const_count-1))) + { + if (tmp > 0) + goto error; // Fatal error + } + else + found_const_table_map|= table->map; + break; + } + else + found_ref|= refs; // Table is const if all refs are const + } + else if (const_ref == eq_part) + s->const_keys.set_bit(key); + } + } + } + } + } while (join->const_table_map & found_ref && ref_changed); + + /* + Update info on indexes that can be used for search lookups as + reading const tables may has added new sargable predicates. + */ + if (const_count && sargables) + { + for( ; sargables->field ; sargables++) + { + Field *field= sargables->field; + JOIN_TAB *join_tab= field->table->reginfo.join_tab; + key_map possible_keys= field->key_start; + possible_keys.intersect(field->table->keys_in_use_for_query); + bool is_const= 1; + for (uint j=0; j < sargables->num_values; j++) + is_const&= sargables->arg_value[j]->const_item(); + if (is_const) + join_tab[0].const_keys.merge(possible_keys); + } + } + + /* Calc how many (possible) matched records in each table */ + + for (s=stat ; s < stat_end ; s++) + { + if (s->type == JT_SYSTEM || s->type == JT_CONST) + { + /* Only one matching row */ + s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0; + continue; + } + /* Approximate found rows and time to read them */ + s->found_records=s->records=s->table->file->stats.records; + s->read_time=(ha_rows) s->table->file->scan_time(); + + /* + Set a max range of how many seeks we can expect when using keys + This is can't be to high as otherwise we are likely to use + table scan. + */ + s->worst_seeks= min((double) s->found_records / 10, + (double) s->read_time*3); + if (s->worst_seeks < 2.0) // Fix for small tables + s->worst_seeks=2.0; + + /* + Add to stat->const_keys those indexes for which all group fields or + all select distinct fields participate in one index. + */ + add_group_and_distinct_keys(join, s); + + if (!s->const_keys.is_clear_all() && + !s->table->pos_in_table_list->embedding) + { + ha_rows records; + SQL_SELECT *select; + select= make_select(s->table, found_const_table_map, + found_const_table_map, + *s->on_expr_ref ? *s->on_expr_ref : conds, + 1, &error); + if (!select) + goto error; + records= get_quick_record_count(join->thd, select, s->table, + &s->const_keys, join->row_limit); + s->quick=select->quick; + s->needed_reg=select->needed_reg; + select->quick=0; + if (records == 0 && s->table->reginfo.impossible_range) + { + /* + Impossible WHERE or ON expression + In case of ON, we mark that the we match one empty NULL row. + In case of WHERE, don't set found_const_table_map to get the + caller to abort with a zero row result. + */ + join->const_table_map|= s->table->map; + set_position(join,const_count++,s,(KEYUSE*) 0); + s->type= JT_CONST; + if (*s->on_expr_ref) + { + /* Generate empty row */ + s->info= "Impossible ON condition"; + found_const_table_map|= s->table->map; + s->type= JT_CONST; + mark_as_null_row(s->table); // All fields are NULL + } + } + if (records != HA_POS_ERROR) + { + s->found_records=records; + s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0); + } + delete select; + } + } + + join->join_tab=stat; + join->map2table=stat_ref; + join->table= join->all_tables=table_vector; + join->const_tables=const_count; + join->found_const_table_map=found_const_table_map; + + /* Find an optimal join order of the non-constant tables. */ + if (join->const_tables != join->tables) + { + optimize_keyuse(join, keyuse_array); + if (choose_plan(join, all_table_map & ~join->const_table_map)) + goto error; + } + else + { + memcpy((uchar*) join->best_positions,(uchar*) join->positions, + sizeof(POSITION)*join->const_tables); + join->best_read=1.0; + } + /* Generate an execution plan from the found optimal join order. */ + DBUG_RETURN(join->thd->killed || get_best_combination(join)); + +error: + /* + Need to clean up join_tab from TABLEs in case of error. + They won't get cleaned up by JOIN::cleanup() because JOIN::join_tab + may not be assigned yet by this function (which is building join_tab). + Dangling TABLE::reginfo.join_tab may cause part_of_refkey to choke. + */ + for (tables= tables_arg; tables; tables= tables->next_leaf) + tables->table->reginfo.join_tab= NULL; + DBUG_RETURN (1); +} + + +/***************************************************************************** + Check with keys are used and with tables references with tables + Updates in stat: + keys Bitmap of all used keys + const_keys Bitmap of all keys with may be used with quick_select + keyuse Pointer to possible keys +*****************************************************************************/ + +/// Used when finding key fields +typedef struct key_field_t { + Field *field; + Item *val; ///< May be empty if diff constant + uint level; + uint optimize; + bool eq_func; + /** + If true, the condition this struct represents will not be satisfied + when val IS NULL. + */ + bool null_rejecting; + bool *cond_guard; /* See KEYUSE::cond_guard */ +} KEY_FIELD; + +/* Values in optimize */ +#define KEY_OPTIMIZE_EXISTS 1 +#define KEY_OPTIMIZE_REF_OR_NULL 2 + +/** + Merge new key definitions to old ones, remove those not used in both. + + This is called for OR between different levels. + + To be able to do 'ref_or_null' we merge a comparison of a column + and 'column IS NULL' to one test. This is useful for sub select queries + that are internally transformed to something like:. + + @code + SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL + @endcode + + KEY_FIELD::null_rejecting is processed as follows: @n + result has null_rejecting=true if it is set for both ORed references. + for example: + - (t2.key = t1.field OR t2.key = t1.field) -> null_rejecting=true + - (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false + + @todo + The result of this is that we're missing some 'ref' accesses. + OptimizerTeam: Fix this +*/ + +static KEY_FIELD * +merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end, + uint and_level) +{ + if (start == new_fields) + return start; // Impossible or + if (new_fields == end) + return start; // No new fields, skip all + + KEY_FIELD *first_free=new_fields; + + /* Mark all found fields in old array */ + for (; new_fields != end ; new_fields++) + { + for (KEY_FIELD *old=start ; old != first_free ; old++) + { + if (old->field == new_fields->field) + { + /* + NOTE: below const_item() call really works as "!used_tables()", i.e. + it can return FALSE where it is feasible to make it return TRUE. + + The cause is as follows: Some of the tables are already known to be + const tables (the detection code is in make_join_statistics(), + above the update_ref_and_keys() call), but we didn't propagate + information about this: TABLE::const_table is not set to TRUE, and + Item::update_used_tables() hasn't been called for each item. + The result of this is that we're missing some 'ref' accesses. + TODO: OptimizerTeam: Fix this + */ + if (!new_fields->val->const_item()) + { + /* + If the value matches, we can use the key reference. + If not, we keep it until we have examined all new values + */ + if (old->val->eq(new_fields->val, old->field->binary())) + { + old->level= and_level; + old->optimize= ((old->optimize & new_fields->optimize & + KEY_OPTIMIZE_EXISTS) | + ((old->optimize | new_fields->optimize) & + KEY_OPTIMIZE_REF_OR_NULL)); + old->null_rejecting= (old->null_rejecting && + new_fields->null_rejecting); + } + } + else if (old->eq_func && new_fields->eq_func && + old->val->eq_by_collation(new_fields->val, + old->field->binary(), + old->field->charset())) + + { + old->level= and_level; + old->optimize= ((old->optimize & new_fields->optimize & + KEY_OPTIMIZE_EXISTS) | + ((old->optimize | new_fields->optimize) & + KEY_OPTIMIZE_REF_OR_NULL)); + old->null_rejecting= (old->null_rejecting && + new_fields->null_rejecting); + } + else if (old->eq_func && new_fields->eq_func && + ((old->val->const_item() && old->val->is_null()) || + new_fields->val->is_null())) + { + /* field = expression OR field IS NULL */ + old->level= and_level; + old->optimize= KEY_OPTIMIZE_REF_OR_NULL; + /* + Remember the NOT NULL value unless the value does not depend + on other tables. + */ + if (!old->val->used_tables() && old->val->is_null()) + old->val= new_fields->val; + /* The referred expression can be NULL: */ + old->null_rejecting= 0; + } + else + { + /* + We are comparing two different const. In this case we can't + use a key-lookup on this so it's better to remove the value + and let the range optimzier handle it + */ + if (old == --first_free) // If last item + break; + *old= *first_free; // Remove old value + old--; // Retry this value + } + } + } + } + /* Remove all not used items */ + for (KEY_FIELD *old=start ; old != first_free ;) + { + if (old->level != and_level) + { // Not used in all levels + if (old == --first_free) + break; + *old= *first_free; // Remove old value + continue; + } + old++; + } + return first_free; +} + + +/** + Add a possible key to array of possible keys if it's usable as a key + + @param key_fields Pointer to add key, if usable + @param and_level And level, to be stored in KEY_FIELD + @param cond Condition predicate + @param field Field used in comparision + @param eq_func True if we used =, <=> or IS NULL + @param value Value used for comparison with field + @param usable_tables Tables which can be used for key optimization + @param sargables IN/OUT Array of found sargable candidates + + @note + If we are doing a NOT NULL comparison on a NOT NULL field in a outer join + table, we store this to be able to do not exists optimization later. + + @returns + *key_fields is incremented if we stored a key in the array +*/ + +static void +add_key_field(KEY_FIELD **key_fields,uint and_level, Item_func *cond, + Field *field, bool eq_func, Item **value, uint num_values, + table_map usable_tables, SARGABLE_PARAM **sargables) +{ + uint exists_optimize= 0; + if (!(field->flags & PART_KEY_FLAG)) + { + // Don't remove column IS NULL on a LEFT JOIN table + if (!eq_func || (*value)->type() != Item::NULL_ITEM || + !field->table->maybe_null || field->null_ptr) + return; // Not a key. Skip it + exists_optimize= KEY_OPTIMIZE_EXISTS; + DBUG_ASSERT(num_values == 1); + } + else + { + table_map used_tables=0; + bool optimizable=0; + for (uint i=0; iused_tables(); + if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT))) + optimizable=1; + } + if (!optimizable) + return; + if (!(usable_tables & field->table->map)) + { + if (!eq_func || (*value)->type() != Item::NULL_ITEM || + !field->table->maybe_null || field->null_ptr) + return; // Can't use left join optimize + exists_optimize= KEY_OPTIMIZE_EXISTS; + } + else + { + JOIN_TAB *stat=field->table->reginfo.join_tab; + key_map possible_keys=field->key_start; + possible_keys.intersect(field->table->keys_in_use_for_query); + stat[0].keys.merge(possible_keys); // Add possible keys + + /* + Save the following cases: + Field op constant + Field LIKE constant where constant doesn't start with a wildcard + Field = field2 where field2 is in a different table + Field op formula + Field IS NULL + Field IS NOT NULL + Field BETWEEN ... + Field IN ... + */ + stat[0].key_dependent|=used_tables; + + bool is_const=1; + for (uint i=0; iconst_item())) + break; + } + if (is_const) + stat[0].const_keys.merge(possible_keys); + else if (!eq_func) + { + /* + Save info to be able check whether this predicate can be + considered as sargable for range analisis after reading const tables. + We do not save info about equalities as update_const_equal_items + will take care of updating info on keys from sargable equalities. + */ + (*sargables)--; + (*sargables)->field= field; + (*sargables)->arg_value= value; + (*sargables)->num_values= num_values; + } + /* + We can't always use indexes when comparing a string index to a + number. cmp_type() is checked to allow compare of dates to numbers. + eq_func is NEVER true when num_values > 1 + */ + if (!eq_func) + { + /* + Additional optimization: if we're processing + "t.key BETWEEN c1 AND c1" then proceed as if we were processing + "t.key = c1". + TODO: This is a very limited fix. A more generic fix is possible. + There are 2 options: + A) Make equality propagation code be able to handle BETWEEN + (including cases like t1.key BETWEEN t2.key AND t3.key) + B) Make range optimizer to infer additional "t.key = c" equalities + and use them in equality propagation process (see details in + OptimizerKBAndTodo) + */ + if ((cond->functype() != Item_func::BETWEEN) || + ((Item_func_between*) cond)->negated || + !value[0]->eq(value[1], field->binary())) + return; + eq_func= TRUE; + } + + if (field->result_type() == STRING_RESULT) + { + if ((*value)->result_type() != STRING_RESULT) + { + if (field->cmp_type() != (*value)->result_type()) + return; + } + else + { + /* + We can't use indexes if the effective collation + of the operation differ from the field collation. + */ + if (field->cmp_type() == STRING_RESULT && + ((Field_str*)field)->charset() != cond->compare_collation()) + return; + } + } + } + } + /* + For the moment eq_func is always true. This slot is reserved for future + extensions where we want to remembers other things than just eq comparisons + */ + DBUG_ASSERT(eq_func); + /* Store possible eq field */ + (*key_fields)->field= field; + (*key_fields)->eq_func= eq_func; + (*key_fields)->val= *value; + (*key_fields)->level= and_level; + (*key_fields)->optimize= exists_optimize; + /* + If the condition has form "tbl.keypart = othertbl.field" and + othertbl.field can be NULL, there will be no matches if othertbl.field + has NULL value. + We use null_rejecting in add_not_null_conds() to add + 'othertbl.field IS NOT NULL' to tab->select_cond. + */ + (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC || + cond->functype() == Item_func::MULT_EQUAL_FUNC) && + ((*value)->type() == Item::FIELD_ITEM) && + ((Item_field*)*value)->field->maybe_null()); + (*key_fields)->cond_guard= NULL; + (*key_fields)++; +} + +/** + Add possible keys to array of possible keys originated from a simple + predicate. + + @param key_fields Pointer to add key, if usable + @param and_level And level, to be stored in KEY_FIELD + @param cond Condition predicate + @param field Field used in comparision + @param eq_func True if we used =, <=> or IS NULL + @param value Value used for comparison with field + Is NULL for BETWEEN and IN + @param usable_tables Tables which can be used for key optimization + @param sargables IN/OUT Array of found sargable candidates + + @note + If field items f1 and f2 belong to the same multiple equality and + a key is added for f1, the the same key is added for f2. + + @returns + *key_fields is incremented if we stored a key in the array +*/ + +static void +add_key_equal_fields(KEY_FIELD **key_fields, uint and_level, + Item_func *cond, Item_field *field_item, + bool eq_func, Item **val, + uint num_values, table_map usable_tables, + SARGABLE_PARAM **sargables) +{ + Field *field= field_item->field; + add_key_field(key_fields, and_level, cond, field, + eq_func, val, num_values, usable_tables, sargables); + Item_equal *item_equal= field_item->item_equal; + if (item_equal) + { + /* + Add to the set of possible key values every substitution of + the field for an equal field included into item_equal + */ + Item_equal_iterator it(*item_equal); + Item_field *item; + while ((item= it++)) + { + if (!field->eq(item->field)) + { + add_key_field(key_fields, and_level, cond, item->field, + eq_func, val, num_values, usable_tables, + sargables); + } + } + } +} + + +/** + Check if an expression is a non-outer field. + + Checks if an expression is a field and belongs to the current select. + + @param field Item expression to check + + @return boolean + @retval TRUE the expression is a local field + @retval FALSE it's something else +*/ + +inline static bool +is_local_field (Item *field) +{ + field= field->real_item(); + return field->type() == Item::FIELD_ITEM && + !((Item_field *)field)->depended_from; +} + + +static void +add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, + COND *cond, table_map usable_tables, + SARGABLE_PARAM **sargables) +{ + if (!cond) return; + if (cond->type() == Item_func::COND_ITEM) + { + List_iterator_fast li(*((Item_cond*) cond)->argument_list()); + KEY_FIELD *org_key_fields= *key_fields; + + if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) + { + Item *item; + while ((item=li++)) + add_key_fields(join, key_fields, and_level, item, usable_tables, + sargables); + for (; org_key_fields != *key_fields ; org_key_fields++) + org_key_fields->level= *and_level; + } + else + { + (*and_level)++; + add_key_fields(join, key_fields, and_level, li++, usable_tables, + sargables); + Item *item; + while ((item=li++)) + { + KEY_FIELD *start_key_fields= *key_fields; + (*and_level)++; + add_key_fields(join, key_fields, and_level, item, usable_tables, + sargables); + *key_fields=merge_key_fields(org_key_fields,start_key_fields, + *key_fields,++(*and_level)); + } + } + return; + } + + /* + Subquery optimization: Conditions that are pushed down into subqueries + are wrapped into Item_func_trig_cond. We process the wrapped condition + but need to set cond_guard for KEYUSE elements generated from it. + */ + { + if (cond->type() == Item::FUNC_ITEM && + ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC) + { + Item *cond_arg= ((Item_func*)cond)->arguments()[0]; + if (!join->group_list && !join->order && + join->unit->item && + join->unit->item->substype() == Item_subselect::IN_SUBS && + !join->unit->is_union()) + { + KEY_FIELD *save= *key_fields; + add_key_fields(join, key_fields, and_level, cond_arg, usable_tables, + sargables); + // Indicate that this ref access candidate is for subquery lookup: + for (; save != *key_fields; save++) + save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var(); + } + return; + } + } + + /* If item is of type 'field op field/constant' add it to key_fields */ + if (cond->type() != Item::FUNC_ITEM) + return; + Item_func *cond_func= (Item_func*) cond; + switch (cond_func->select_optimize()) { + case Item_func::OPTIMIZE_NONE: + break; + case Item_func::OPTIMIZE_KEY: + { + Item **values; + // BETWEEN, IN, NE + if (is_local_field (cond_func->key_item()) && + !(cond_func->used_tables() & OUTER_REF_TABLE_BIT)) + { + values= cond_func->arguments()+1; + if (cond_func->functype() == Item_func::NE_FUNC && + is_local_field (cond_func->arguments()[1])) + values--; + DBUG_ASSERT(cond_func->functype() != Item_func::IN_FUNC || + cond_func->argument_count() != 2); + add_key_equal_fields(key_fields, *and_level, cond_func, + (Item_field*) (cond_func->key_item()->real_item()), + 0, values, + cond_func->argument_count()-1, + usable_tables, sargables); + } + if (cond_func->functype() == Item_func::BETWEEN) + { + values= cond_func->arguments(); + for (uint i= 1 ; i < cond_func->argument_count() ; i++) + { + Item_field *field_item; + if (is_local_field (cond_func->arguments()[i])) + { + field_item= (Item_field *) (cond_func->arguments()[i]->real_item()); + add_key_equal_fields(key_fields, *and_level, cond_func, + field_item, 0, values, 1, usable_tables, + sargables); + } + } + } + break; + } + case Item_func::OPTIMIZE_OP: + { + bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC || + cond_func->functype() == Item_func::EQUAL_FUNC); + + if (is_local_field (cond_func->arguments()[0])) + { + add_key_equal_fields(key_fields, *and_level, cond_func, + (Item_field*) (cond_func->arguments()[0])->real_item(), + equal_func, + cond_func->arguments()+1, 1, usable_tables, + sargables); + } + if (is_local_field (cond_func->arguments()[1]) && + cond_func->functype() != Item_func::LIKE_FUNC) + { + add_key_equal_fields(key_fields, *and_level, cond_func, + (Item_field*) (cond_func->arguments()[1])->real_item(), + equal_func, + cond_func->arguments(),1,usable_tables, + sargables); + } + break; + } + case Item_func::OPTIMIZE_NULL: + /* column_name IS [NOT] NULL */ + if (is_local_field (cond_func->arguments()[0]) && + !(cond_func->used_tables() & OUTER_REF_TABLE_BIT)) + { + Item *tmp=new Item_null; + if (unlikely(!tmp)) // Should never be true + return; + add_key_equal_fields(key_fields, *and_level, cond_func, + (Item_field*) (cond_func->arguments()[0])->real_item(), + cond_func->functype() == Item_func::ISNULL_FUNC, + &tmp, 1, usable_tables, sargables); + } + break; + case Item_func::OPTIMIZE_EQUAL: + Item_equal *item_equal= (Item_equal *) cond; + Item *const_item= item_equal->get_const(); + Item_equal_iterator it(*item_equal); + Item_field *item; + if (const_item) + { + /* + For each field field1 from item_equal consider the equality + field1=const_item as a condition allowing an index access of the table + with field1 by the keys value of field1. + */ + while ((item= it++)) + { + add_key_field(key_fields, *and_level, cond_func, item->field, + TRUE, &const_item, 1, usable_tables, sargables); + } + } + else + { + /* + Consider all pairs of different fields included into item_equal. + For each of them (field1, field1) consider the equality + field1=field2 as a condition allowing an index access of the table + with field1 by the keys value of field2. + */ + Item_equal_iterator fi(*item_equal); + while ((item= fi++)) + { + Field *field= item->field; + while ((item= it++)) + { + if (!field->eq(item->field)) + { + add_key_field(key_fields, *and_level, cond_func, field, + TRUE, (Item **) &item, 1, usable_tables, + sargables); + } + } + it.rewind(); + } + } + break; + } +} + + +static uint +max_part_bit(key_part_map bits) +{ + uint found; + for (found=0; bits & 1 ; found++,bits>>=1) ; + return found; +} + +/* + Add all keys with uses 'field' for some keypart + If field->and_level != and_level then only mark key_part as const_part + + RETURN + 0 - OK + 1 - Out of memory. +*/ + +static bool +add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field) +{ + Field *field=key_field->field; + TABLE *form= field->table; + KEYUSE keyuse; + + if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS)) + { + for (uint key=0 ; key < form->s->keys ; key++) + { + if (!(form->keys_in_use_for_query.is_set(key))) + continue; + if (form->key_info[key].flags & HA_FULLTEXT) + continue; // ToDo: ft-keys in non-ft queries. SerG + + uint key_parts= (uint) form->key_info[key].key_parts; + for (uint part=0 ; part < key_parts ; part++) + { + if (field->eq(form->key_info[key].key_part[part].field)) + { + keyuse.table= field->table; + keyuse.val = key_field->val; + keyuse.key = key; + keyuse.keypart=part; + keyuse.keypart_map= (key_part_map) 1 << part; + keyuse.used_tables=key_field->val->used_tables(); + keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL; + keyuse.null_rejecting= key_field->null_rejecting; + keyuse.cond_guard= key_field->cond_guard; + if (insert_dynamic(keyuse_array,(uchar*) &keyuse)) + return TRUE; + } + } + } + } + return FALSE; +} + + +#define FT_KEYPART (MAX_REF_PARTS+10) + +static bool +add_ft_keys(DYNAMIC_ARRAY *keyuse_array, + JOIN_TAB *stat,COND *cond,table_map usable_tables) +{ + Item_func_match *cond_func=NULL; + + if (!cond) + return FALSE; + + if (cond->type() == Item::FUNC_ITEM) + { + Item_func *func=(Item_func *)cond; + Item_func::Functype functype= func->functype(); + if (functype == Item_func::FT_FUNC) + cond_func=(Item_func_match *)cond; + else if (func->arg_count == 2) + { + Item_func *arg0=(Item_func *)(func->arguments()[0]), + *arg1=(Item_func *)(func->arguments()[1]); + if (arg1->const_item() && + ((functype == Item_func::GE_FUNC && arg1->val_real() > 0) || + (functype == Item_func::GT_FUNC && arg1->val_real() >=0)) && + arg0->type() == Item::FUNC_ITEM && + arg0->functype() == Item_func::FT_FUNC) + cond_func=(Item_func_match *) arg0; + else if (arg0->const_item() && + ((functype == Item_func::LE_FUNC && arg0->val_real() > 0) || + (functype == Item_func::LT_FUNC && arg0->val_real() >=0)) && + arg1->type() == Item::FUNC_ITEM && + arg1->functype() == Item_func::FT_FUNC) + cond_func=(Item_func_match *) arg1; + } + } + else if (cond->type() == Item::COND_ITEM) + { + List_iterator_fast li(*((Item_cond*) cond)->argument_list()); + + if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) + { + Item *item; + while ((item=li++)) + { + if (add_ft_keys(keyuse_array,stat,item,usable_tables)) + return TRUE; + } + } + } + + if (!cond_func || cond_func->key == NO_SUCH_KEY || + !(usable_tables & cond_func->table->map)) + return FALSE; + + KEYUSE keyuse; + keyuse.table= cond_func->table; + keyuse.val = cond_func; + keyuse.key = cond_func->key; + keyuse.keypart= FT_KEYPART; + keyuse.used_tables=cond_func->key_item()->used_tables(); + keyuse.optimize= 0; + keyuse.keypart_map= 0; + return insert_dynamic(keyuse_array,(uchar*) &keyuse); +} + + +static int +sort_keyuse(KEYUSE *a,KEYUSE *b) +{ + int res; + if (a->table->tablenr != b->table->tablenr) + return (int) (a->table->tablenr - b->table->tablenr); + if (a->key != b->key) + return (int) (a->key - b->key); + if (a->keypart != b->keypart) + return (int) (a->keypart - b->keypart); + // Place const values before other ones + if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) - + test((b->used_tables & ~OUTER_REF_TABLE_BIT)))) + return res; + /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */ + return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) - + (b->optimize & KEY_OPTIMIZE_REF_OR_NULL)); +} + + +/* + Add to KEY_FIELD array all 'ref' access candidates within nested join. + + This function populates KEY_FIELD array with entries generated from the + ON condition of the given nested join, and does the same for nested joins + contained within this nested join. + + @param[in] nested_join_table Nested join pseudo-table to process + @param[in,out] end End of the key field array + @param[in,out] and_level And-level + @param[in,out] sargables Array of found sargable candidates + + + @note + We can add accesses to the tables that are direct children of this nested + join (1), and are not inner tables w.r.t their neighbours (2). + + Example for #1 (outer brackets pair denotes nested join this function is + invoked for): + @code + ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond + @endcode + Example for #2: + @code + ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond + @endcode + In examples 1-2 for condition cond, we can add 'ref' access candidates to + t1 only. + Example #3: + @code + ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond + @endcode + Here we can add 'ref' access candidates for t1 and t2, but not for t3. +*/ + +static void add_key_fields_for_nj(JOIN *join, TABLE_LIST *nested_join_table, + KEY_FIELD **end, uint *and_level, + SARGABLE_PARAM **sargables) +{ + List_iterator li(nested_join_table->nested_join->join_list); + table_map tables= 0; + TABLE_LIST *table; + DBUG_ASSERT(nested_join_table->nested_join); + + while ((table= li++)) + { + if (table->nested_join) + add_key_fields_for_nj(join, table, end, and_level, sargables); + else + if (!table->on_expr) + tables |= table->table->map; + } + add_key_fields(join, end, and_level, nested_join_table->on_expr, tables, + sargables); +} + + +/** + Update keyuse array with all possible keys we can use to fetch rows. + + @param thd + @param[out] keyuse Put here ordered array of KEYUSE structures + @param join_tab Array in tablenr_order + @param tables Number of tables in join + @param cond WHERE condition (note that the function analyzes + join_tab[i]->on_expr too) + @param normal_tables Tables not inner w.r.t some outer join (ones + for which we can make ref access based the WHERE + clause) + @param select_lex current SELECT + @param[out] sargables Array of found sargable candidates + + @retval + 0 OK + @retval + 1 Out of memory. +*/ + +static bool +update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab, + uint tables, COND *cond, COND_EQUAL *cond_equal, + table_map normal_tables, SELECT_LEX *select_lex, + SARGABLE_PARAM **sargables) +{ + uint and_level,i,found_eq_constant; + KEY_FIELD *key_fields, *end, *field; + uint sz; + uint m= max(select_lex->max_equal_elems,1); + + /* + We use the same piece of memory to store both KEY_FIELD + and SARGABLE_PARAM structure. + KEY_FIELD values are placed at the beginning this memory + while SARGABLE_PARAM values are put at the end. + All predicates that are used to fill arrays of KEY_FIELD + and SARGABLE_PARAM structures have at most 2 arguments + except BETWEEN predicates that have 3 arguments and + IN predicates. + This any predicate if it's not BETWEEN/IN can be used + directly to fill at most 2 array elements, either of KEY_FIELD + or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements + can be filled as this predicate is considered as + saragable with respect to each of its argument. + An IN predicate can require at most 1 element as currently + it is considered as sargable only for its first argument. + Multiple equality can add elements that are filled after + substitution of field arguments by equal fields. There + can be not more than select_lex->max_equal_elems such + substitutions. + */ + sz= max(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))* + (((thd->lex->current_select->cond_count+1)*2 + + thd->lex->current_select->between_count)*m+1); + if (!(key_fields=(KEY_FIELD*) thd->alloc(sz))) + return TRUE; /* purecov: inspected */ + and_level= 0; + field= end= key_fields; + *sargables= (SARGABLE_PARAM *) key_fields + + (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM); + /* set a barrier for the array of SARGABLE_PARAM */ + (*sargables)[0].field= 0; + + if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64)) + return TRUE; + if (cond) + { + add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables, + sargables); + for (; field != end ; field++) + { + if (add_key_part(keyuse,field)) + return TRUE; + /* Mark that we can optimize LEFT JOIN */ + if (field->val->type() == Item::NULL_ITEM && + !field->field->real_maybe_null()) + field->field->table->reginfo.not_exists_optimize=1; + } + } + for (i=0 ; i < tables ; i++) + { + /* + Block the creation of keys for inner tables of outer joins. + Here only the outer joins that can not be converted to + inner joins are left and all nests that can be eliminated + are flattened. + In the future when we introduce conditional accesses + for inner tables in outer joins these keys will be taken + into account as well. + */ + if (*join_tab[i].on_expr_ref) + add_key_fields(join_tab->join, &end, &and_level, + *join_tab[i].on_expr_ref, + join_tab[i].table->map, sargables); + } + + /* Process ON conditions for the nested joins */ + { + List_iterator li(*join_tab->join->join_list); + TABLE_LIST *table; + while ((table= li++)) + { + if (table->nested_join) + add_key_fields_for_nj(join_tab->join, table, &end, &and_level, + sargables); + } + } + + /* fill keyuse with found key parts */ + for ( ; field != end ; field++) + { + if (add_key_part(keyuse,field)) + return TRUE; + } + + if (select_lex->ftfunc_list->elements) + { + if (add_ft_keys(keyuse,join_tab,cond,normal_tables)) + return TRUE; + } + + /* + Sort the array of possible keys and remove the following key parts: + - ref if there is a keypart which is a ref and a const. + (e.g. if there is a key(a,b) and the clause is a=3 and b=7 and b=t2.d, + then we skip the key part corresponding to b=t2.d) + - keyparts without previous keyparts + (e.g. if there is a key(a,b,c) but only b < 5 (or a=2 and c < 3) is + used in the query, we drop the partial key parts from consideration). + Special treatment for ft-keys. + */ + if (keyuse->elements) + { + KEYUSE key_end,*prev,*save_pos,*use; + + my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE), + (qsort_cmp) sort_keyuse); + + bzero((char*) &key_end,sizeof(key_end)); /* Add for easy testing */ + if (insert_dynamic(keyuse,(uchar*) &key_end)) + return TRUE; + + use=save_pos=dynamic_element(keyuse,0,KEYUSE*); + prev= &key_end; + found_eq_constant=0; + for (i=0 ; i < keyuse->elements-1 ; i++,use++) + { + if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL) + use->table->const_key_parts[use->key]|= use->keypart_map; + if (use->keypart != FT_KEYPART) + { + if (use->key == prev->key && use->table == prev->table) + { + if (prev->keypart+1 < use->keypart || + (prev->keypart == use->keypart && found_eq_constant)) + continue; /* remove */ + } + else if (use->keypart != 0) // First found must be 0 + continue; + } + +#ifdef HAVE_purify + /* Valgrind complains about overlapped memcpy when save_pos==use. */ + if (save_pos != use) +#endif + *save_pos= *use; + prev=use; + found_eq_constant= !use->used_tables; + /* Save ptr to first use */ + if (!use->table->reginfo.join_tab->keyuse) + use->table->reginfo.join_tab->keyuse=save_pos; + use->table->reginfo.join_tab->checked_keys.set_bit(use->key); + save_pos++; + } + i=(uint) (save_pos-(KEYUSE*) keyuse->buffer); + VOID(set_dynamic(keyuse,(uchar*) &key_end,i)); + keyuse->elements=i; + } + return FALSE; +} + +/** + Update some values in keyuse for faster choose_plan() loop. +*/ + +static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array) +{ + KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*); + + for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++) + { + table_map map; + /* + If we find a ref, assume this table matches a proportional + part of this table. + For example 100 records matching a table with 5000 records + gives 5000/100 = 50 records per key + Constant tables are ignored. + To avoid bad matches, we don't make ref_table_rows less than 100. + */ + keyuse->ref_table_rows= ~(ha_rows) 0; // If no ref + if (keyuse->used_tables & + (map= (keyuse->used_tables & ~join->const_table_map & + ~OUTER_REF_TABLE_BIT))) + { + uint tablenr; + for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ; + if (map == 1) // Only one table + { + TABLE *tmp_table=join->all_tables[tablenr]; + keyuse->ref_table_rows= max(tmp_table->file->stats.records, 100); + } + } + /* + Outer reference (external field) is constant for single executing + of subquery + */ + if (keyuse->used_tables == OUTER_REF_TABLE_BIT) + keyuse->ref_table_rows= 1; + } +} + + +/** + Discover the indexes that can be used for GROUP BY or DISTINCT queries. + + If the query has a GROUP BY clause, find all indexes that contain all + GROUP BY fields, and add those indexes to join->const_keys. + + If the query has a DISTINCT clause, find all indexes that contain all + SELECT fields, and add those indexes to join->const_keys. + This allows later on such queries to be processed by a + QUICK_GROUP_MIN_MAX_SELECT. + + @param join + @param join_tab + + @return + None +*/ + +static void +add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab) +{ + List indexed_fields; + List_iterator indexed_fields_it(indexed_fields); + ORDER *cur_group; + Item_field *cur_item; + key_map possible_keys(0); + + if (join->group_list) + { /* Collect all query fields referenced in the GROUP clause. */ + for (cur_group= join->group_list; cur_group; cur_group= cur_group->next) + (*cur_group->item)->walk(&Item::collect_item_field_processor, 0, + (uchar*) &indexed_fields); + } + else if (join->select_distinct) + { /* Collect all query fields referenced in the SELECT clause. */ + List &select_items= join->fields_list; + List_iterator select_items_it(select_items); + Item *item; + while ((item= select_items_it++)) + item->walk(&Item::collect_item_field_processor, 0, + (uchar*) &indexed_fields); + } + else + return; + + if (indexed_fields.elements == 0) + return; + + /* Intersect the keys of all group fields. */ + cur_item= indexed_fields_it++; + possible_keys.merge(cur_item->field->part_of_key); + while ((cur_item= indexed_fields_it++)) + { + possible_keys.intersect(cur_item->field->part_of_key); + } + + if (!possible_keys.is_clear_all()) + join_tab->const_keys.merge(possible_keys); +} + + +/***************************************************************************** + Go through all combinations of not marked tables and find the one + which uses least records +*****************************************************************************/ + +/** Save const tables first as used tables. */ + +static void +set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key) +{ + join->positions[idx].table= table; + join->positions[idx].key=key; + join->positions[idx].records_read=1.0; /* This is a const table */ + join->positions[idx].ref_depend_map= 0; + + /* Move the const table as down as possible in best_ref */ + JOIN_TAB **pos=join->best_ref+idx+1; + JOIN_TAB *next=join->best_ref[idx]; + for (;next != table ; pos++) + { + JOIN_TAB *tmp=pos[0]; + pos[0]=next; + next=tmp; + } + join->best_ref[idx]=table; +} + + +/** + Find the best access path for an extension of a partial execution + plan and add this path to the plan. + + The function finds the best access path to table 's' from the passed + partial plan where an access path is the general term for any means to + access the data in 's'. An access path may use either an index or a scan, + whichever is cheaper. The input partial plan is passed via the array + 'join->positions' of length 'idx'. The chosen access method for 's' and its + cost are stored in 'join->positions[idx]'. + + @param join pointer to the structure providing all context info + for the query + @param s the table to be joined by the function + @param thd thread for the connection that submitted the query + @param remaining_tables set of tables not included into the partial plan yet + @param idx the length of the partial plan + @param record_count estimate for the number of records returned by the + partial plan + @param read_time the cost of the partial plan + + @return + None +*/ + +static void +best_access_path(JOIN *join, + JOIN_TAB *s, + THD *thd, + table_map remaining_tables, + uint idx, + double record_count, + double read_time) +{ + KEYUSE *best_key= 0; + uint best_max_key_part= 0; + my_bool found_constraint= 0; + double best= DBL_MAX; + double best_time= DBL_MAX; + double records= DBL_MAX; + table_map best_ref_depends_map= 0; + double tmp; + ha_rows rec; + DBUG_ENTER("best_access_path"); + + if (s->keyuse) + { /* Use key if possible */ + TABLE *table= s->table; + KEYUSE *keyuse,*start_key=0; + double best_records= DBL_MAX; + uint max_key_part=0; + + /* Test how we can use keys */ + rec= s->records/MATCHING_ROWS_IN_OTHER_TABLE; // Assumed records/key + for (keyuse=s->keyuse ; keyuse->table == table ;) + { + key_part_map found_part= 0; + table_map found_ref= 0; + uint key= keyuse->key; + KEY *keyinfo= table->key_info+key; + bool ft_key= (keyuse->keypart == FT_KEYPART); + /* Bitmap of keyparts where the ref access is over 'keypart=const': */ + key_part_map const_part= 0; + /* The or-null keypart in ref-or-null access: */ + key_part_map ref_or_null_part= 0; + + /* Calculate how many key segments of the current key we can use */ + start_key= keyuse; + + do /* For each keypart */ + { + uint keypart= keyuse->keypart; + table_map best_part_found_ref= 0; + double best_prev_record_reads= DBL_MAX; + + do /* For each way to access the keypart */ + { + + /* + if 1. expression doesn't refer to forward tables + 2. we won't get two ref-or-null's + */ + if (!(remaining_tables & keyuse->used_tables) && + !(ref_or_null_part && (keyuse->optimize & + KEY_OPTIMIZE_REF_OR_NULL))) + { + found_part|= keyuse->keypart_map; + if (!(keyuse->used_tables & ~join->const_table_map)) + const_part|= keyuse->keypart_map; + + double tmp2= prev_record_reads(join, idx, (found_ref | + keyuse->used_tables)); + if (tmp2 < best_prev_record_reads) + { + best_part_found_ref= keyuse->used_tables & ~join->const_table_map; + best_prev_record_reads= tmp2; + } + if (rec > keyuse->ref_table_rows) + rec= keyuse->ref_table_rows; + /* + If there is one 'key_column IS NULL' expression, we can + use this ref_or_null optimisation of this field + */ + if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) + ref_or_null_part |= keyuse->keypart_map; + } + keyuse++; + } while (keyuse->table == table && keyuse->key == key && + keyuse->keypart == keypart); + found_ref|= best_part_found_ref; + } while (keyuse->table == table && keyuse->key == key); + + /* + Assume that that each key matches a proportional part of table. + */ + if (!found_part && !ft_key) + continue; // Nothing usable found + + if (rec < MATCHING_ROWS_IN_OTHER_TABLE) + rec= MATCHING_ROWS_IN_OTHER_TABLE; // Fix for small tables + + /* + ft-keys require special treatment + */ + if (ft_key) + { + /* + Really, there should be records=0.0 (yes!) + but 1.0 would be probably safer + */ + tmp= prev_record_reads(join, idx, found_ref); + records= 1.0; + } + else + { + found_constraint= 1; + /* + Check if we found full key + */ + if (found_part == PREV_BITS(uint,keyinfo->key_parts) && + !ref_or_null_part) + { /* use eq key */ + max_key_part= (uint) ~0; + if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME) + { + tmp = prev_record_reads(join, idx, found_ref); + records=1.0; + } + else + { + if (!found_ref) + { /* We found a const key */ + /* + ReuseRangeEstimateForRef-1: + We get here if we've found a ref(const) (c_i are constants): + "(keypart1=c1) AND ... AND (keypartN=cN)" [ref_const_cond] + + If range optimizer was able to construct a "range" + access on this index, then its condition "quick_cond" was + eqivalent to ref_const_cond (*), and we can re-use E(#rows) + from the range optimizer. + + Proof of (*): By properties of range and ref optimizers + quick_cond will be equal or tighther than ref_const_cond. + ref_const_cond already covers "smallest" possible interval - + a singlepoint interval over all keyparts. Therefore, + quick_cond is equivalent to ref_const_cond (if it was an + empty interval we wouldn't have got here). + */ + if (table->quick_keys.is_set(key)) + records= (double) table->quick_rows[key]; + else + { + /* quick_range couldn't use key! */ + records= (double) s->records/rec; + } + } + else + { + if (!(records=keyinfo->rec_per_key[keyinfo->key_parts-1])) + { /* Prefer longer keys */ + records= + ((double) s->records / (double) rec * + (1.0 + + ((double) (table->s->max_key_length-keyinfo->key_length) / + (double) table->s->max_key_length))); + if (records < 2.0) + records=2.0; /* Can't be as good as a unique */ + } + /* + ReuseRangeEstimateForRef-2: We get here if we could not reuse + E(#rows) from range optimizer. Make another try: + + If range optimizer produced E(#rows) for a prefix of the ref + access we're considering, and that E(#rows) is lower then our + current estimate, make an adjustment. The criteria of when we + can make an adjustment is a special case of the criteria used + in ReuseRangeEstimateForRef-3. + */ + if (table->quick_keys.is_set(key) && + const_part & (1 << table->quick_key_parts[key]) && + table->quick_n_ranges[key] == 1 && + records > (double) table->quick_rows[key]) + { + records= (double) table->quick_rows[key]; + } + } + /* Limit the number of matched rows */ + tmp= records; + set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key); + if (table->covering_keys.is_set(key)) + { + /* we can use only index tree */ + uint keys_per_block= table->file->stats.block_size/2/ + (keyinfo->key_length+table->file->ref_length)+1; + tmp= record_count*(tmp+keys_per_block-1)/keys_per_block; + } + else + tmp= record_count*min(tmp,s->worst_seeks); + } + } + else + { + /* + Use as much key-parts as possible and a uniq key is better + than a not unique key + Set tmp to (previous record count) * (records / combination) + */ + if ((found_part & 1) && + (!(table->file->index_flags(key, 0, 0) & HA_ONLY_WHOLE_INDEX) || + found_part == PREV_BITS(uint,keyinfo->key_parts))) + { + max_key_part= max_part_bit(found_part); + /* + ReuseRangeEstimateForRef-3: + We're now considering a ref[or_null] access via + (t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR + (same-as-above but with one cond replaced + with "t.keypart_i IS NULL")] (**) + + Try re-using E(#rows) from "range" optimizer: + We can do so if "range" optimizer used the same intervals as + in (**). The intervals used by range optimizer may be not + available at this point (as "range" access might have choosen to + create quick select over another index), so we can't compare + them to (**). We'll make indirect judgements instead. + The sufficient conditions for re-use are: + (C1) All e_i in (**) are constants, i.e. found_ref==FALSE. (if + this is not satisfied we have no way to know which ranges + will be actually scanned by 'ref' until we execute the + join) + (C2) max #key parts in 'range' access == K == max_key_part (this + is apparently a necessary requirement) + + We also have a property that "range optimizer produces equal or + tighter set of scan intervals than ref(const) optimizer". Each + of the intervals in (**) are "tightest possible" intervals when + one limits itself to using keyparts 1..K (which we do in #2). + From here it follows that range access used either one, or + both of the (I1) and (I2) intervals: + + (t.keypart1=c1 AND ... AND t.keypartK=eK) (I1) + (same-as-above but with one cond replaced + with "t.keypart_i IS NULL") (I2) + + The remaining part is to exclude the situation where range + optimizer used one interval while we're considering + ref-or-null and looking for estimate for two intervals. This + is done by last limitation: + + (C3) "range optimizer used (have ref_or_null?2:1) intervals" + */ + if (table->quick_keys.is_set(key) && !found_ref && //(C1) + table->quick_key_parts[key] == max_key_part && //(C2) + table->quick_n_ranges[key] == 1+test(ref_or_null_part)) //(C3) + { + tmp= records= (double) table->quick_rows[key]; + } + else + { + /* Check if we have statistic about the distribution */ + if ((records= keyinfo->rec_per_key[max_key_part-1])) + { + /* + Fix for the case where the index statistics is too + optimistic: If + (1) We're considering ref(const) and there is quick select + on the same index, + (2) and that quick select uses more keyparts (i.e. it will + scan equal/smaller interval then this ref(const)) + (3) and E(#rows) for quick select is higher then our + estimate, + Then + We'll use E(#rows) from quick select. + + Q: Why do we choose to use 'ref'? Won't quick select be + cheaper in some cases ? + TODO: figure this out and adjust the plan choice if needed. + */ + if (!found_ref && table->quick_keys.is_set(key) && // (1) + table->quick_key_parts[key] > max_key_part && // (2) + records < (double)table->quick_rows[key]) // (3) + records= (double)table->quick_rows[key]; + + tmp= records; + } + else + { + /* + Assume that the first key part matches 1% of the file + and that the whole key matches 10 (duplicates) or 1 + (unique) records. + Assume also that more key matches proportionally more + records + This gives the formula: + records = (x * (b-a) + a*c-b)/(c-1) + + b = records matched by whole key + a = records matched by first key part (1% of all records?) + c = number of key parts in key + x = used key parts (1 <= x <= c) + */ + double rec_per_key; + if (!(rec_per_key=(double) + keyinfo->rec_per_key[keyinfo->key_parts-1])) + rec_per_key=(double) s->records/rec+1; + + if (!s->records) + tmp = 0; + else if (rec_per_key/(double) s->records >= 0.01) + tmp = rec_per_key; + else + { + double a=s->records*0.01; + if (keyinfo->key_parts > 1) + tmp= (max_key_part * (rec_per_key - a) + + a*keyinfo->key_parts - rec_per_key)/ + (keyinfo->key_parts-1); + else + tmp= a; + set_if_bigger(tmp,1.0); + } + records = (ulong) tmp; + } + + if (ref_or_null_part) + { + /* We need to do two key searches to find key */ + tmp *= 2.0; + records *= 2.0; + } + + /* + ReuseRangeEstimateForRef-4: We get here if we could not reuse + E(#rows) from range optimizer. Make another try: + + If range optimizer produced E(#rows) for a prefix of the ref + access we're considering, and that E(#rows) is lower then our + current estimate, make the adjustment. + + The decision whether we can re-use the estimate from the range + optimizer is the same as in ReuseRangeEstimateForRef-3, + applied to first table->quick_key_parts[key] key parts. + */ + if (table->quick_keys.is_set(key) && + table->quick_key_parts[key] <= max_key_part && + const_part & (1 << table->quick_key_parts[key]) && + table->quick_n_ranges[key] == 1 + test(ref_or_null_part & + const_part) && + records > (double) table->quick_rows[key]) + { + tmp= records= (double) table->quick_rows[key]; + } + } + + /* Limit the number of matched rows */ + set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key); + if (table->covering_keys.is_set(key)) + { + /* we can use only index tree */ + uint keys_per_block= table->file->stats.block_size/2/ + (keyinfo->key_length+table->file->ref_length)+1; + tmp= record_count*(tmp+keys_per_block-1)/keys_per_block; + } + else + tmp= record_count*min(tmp,s->worst_seeks); + } + else + tmp= best_time; // Do nothing + } + } /* not ft_key */ + if (tmp < best_time - records/(double) TIME_FOR_COMPARE) + { + best_time= tmp + records/(double) TIME_FOR_COMPARE; + best= tmp; + best_records= records; + best_key= start_key; + best_max_key_part= max_key_part; + best_ref_depends_map= found_ref; + } + } + records= best_records; + } + + /* + Don't test table scan if it can't be better. + Prefer key lookup if we would use the same key for scanning. + + Don't do a table scan on InnoDB tables, if we can read the used + parts of the row from any of the used index. + This is because table scans uses index and we would not win + anything by using a table scan. + + A word for word translation of the below if-statement in psergey's + understanding: we check if we should use table scan if: + (1) The found 'ref' access produces more records than a table scan + (or index scan, or quick select), or 'ref' is more expensive than + any of them. + (2) This doesn't hold: the best way to perform table scan is to to perform + 'range' access using index IDX, and the best way to perform 'ref' + access is to use the same index IDX, with the same or more key parts. + (note: it is not clear how this rule is/should be extended to + index_merge quick selects) + (3) See above note about InnoDB. + (4) NOT ("FORCE INDEX(...)" is used for table and there is 'ref' access + path, but there is no quick select) + If the condition in the above brackets holds, then the only possible + "table scan" access method is ALL/index (there is no quick select). + Since we have a 'ref' access path, and FORCE INDEX instructs us to + choose it over ALL/index, there is no need to consider a full table + scan. + */ + if ((records >= s->found_records || best > s->read_time) && // (1) + !(s->quick && best_key && s->quick->index == best_key->key && // (2) + best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&// (2) + !((s->table->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) && // (3) + ! s->table->covering_keys.is_clear_all() && best_key && !s->quick) &&// (3) + !(s->table->force_index && best_key && !s->quick)) // (4) + { // Check full join + ha_rows rnd_records= s->found_records; + /* + If there is a filtering condition on the table (i.e. ref analyzer found + at least one "table.keyXpartY= exprZ", where exprZ refers only to tables + preceding this table in the join order we're now considering), then + assume that 25% of the rows will be filtered out by this condition. + + This heuristic is supposed to force tables used in exprZ to be before + this table in join order. + */ + if (found_constraint) + rnd_records-= rnd_records/4; + + /* + If applicable, get a more accurate estimate. Don't use the two + heuristics at once. + */ + if (s->table->quick_condition_rows != s->found_records) + rnd_records= s->table->quick_condition_rows; + + /* + Range optimizer never proposes a RANGE if it isn't better + than FULL: so if RANGE is present, it's always preferred to FULL. + Here we estimate its cost. + */ + if (s->quick) + { + /* + For each record we: + - read record range through 'quick' + - skip rows which does not satisfy WHERE constraints + TODO: + We take into account possible use of join cache for ALL/index + access (see first else-branch below), but we don't take it into + account here for range/index_merge access. Find out why this is so. + */ + tmp= record_count * + (s->quick->read_time + + (s->found_records - rnd_records)/(double) TIME_FOR_COMPARE); + } + else + { + /* Estimate cost of reading table. */ + tmp= s->table->file->scan_time(); + if (s->table->map & join->outer_join) // Can't use join cache + { + /* + For each record we have to: + - read the whole table record + - skip rows which does not satisfy join condition + */ + tmp= record_count * + (tmp + + (s->records - rnd_records)/(double) TIME_FOR_COMPARE); + } + else + { + /* We read the table as many times as join buffer becomes full. */ + tmp*= (1.0 + floor((double) cache_record_length(join,idx) * + record_count / + (double) thd->variables.join_buff_size)); + /* + We don't make full cartesian product between rows in the scanned + table and existing records because we skip all rows from the + scanned table, which does not satisfy join condition when + we read the table (see flush_cached_records for details). Here we + take into account cost to read and skip these records. + */ + tmp+= (s->records - rnd_records)/(double) TIME_FOR_COMPARE; + } + } + + /* + We estimate the cost of evaluating WHERE clause for found records + as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus + tmp give us total cost of using TABLE SCAN + */ + if (best == DBL_MAX || + (tmp + record_count/(double) TIME_FOR_COMPARE*rnd_records < + best + record_count/(double) TIME_FOR_COMPARE*records)) + { + /* + If the table has a range (s->quick is set) make_join_select() + will ensure that this will be used + */ + best= tmp; + records= rows2double(rnd_records); + best_key= 0; + /* range/index_merge/ALL/index access method are "independent", so: */ + best_ref_depends_map= 0; + } + } + + /* Update the cost information for the current partial plan */ + join->positions[idx].records_read= records; + join->positions[idx].read_time= best; + join->positions[idx].key= best_key; + join->positions[idx].table= s; + join->positions[idx].ref_depend_map= best_ref_depends_map; + + if (!best_key && + idx == join->const_tables && + s->table == join->sort_by_table && + join->unit->select_limit_cnt >= records) + join->sort_by_table= (TABLE*) 1; // Must use temporary table + + DBUG_VOID_RETURN; +} + + +/** + Selects and invokes a search strategy for an optimal query plan. + + The function checks user-configurable parameters that control the search + strategy for an optimal plan, selects the search method and then invokes + it. Each specific optimization procedure stores the final optimal plan in + the array 'join->best_positions', and the cost of the plan in + 'join->best_read'. + + @param join pointer to the structure providing all context info for + the query + @param join_tables set of the tables in the query + + @todo + 'MAX_TABLES+2' denotes the old implementation of find_best before + the greedy version. Will be removed when greedy_search is approved. + + @retval + FALSE ok + @retval + TRUE Fatal error +*/ + +static bool +choose_plan(JOIN *join, table_map join_tables) +{ + uint search_depth= join->thd->variables.optimizer_search_depth; + uint prune_level= join->thd->variables.optimizer_prune_level; + bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN); + DBUG_ENTER("choose_plan"); + + join->cur_embedding_map= 0; + reset_nj_counters(join->join_list); + /* + if (SELECT_STRAIGHT_JOIN option is set) + reorder tables so dependent tables come after tables they depend + on, otherwise keep tables in the order they were specified in the query + else + Apply heuristic: pre-sort all access plans with respect to the number of + records accessed. + */ + my_qsort(join->best_ref + join->const_tables, + join->tables - join->const_tables, sizeof(JOIN_TAB*), + straight_join ? join_tab_cmp_straight : join_tab_cmp); + + if (straight_join) + { + optimize_straight_join(join, join_tables); + } + else + { + if (search_depth == MAX_TABLES+2) + { /* + TODO: 'MAX_TABLES+2' denotes the old implementation of find_best before + the greedy version. Will be removed when greedy_search is approved. + */ + join->best_read= DBL_MAX; + if (find_best(join, join_tables, join->const_tables, 1.0, 0.0)) + DBUG_RETURN(TRUE); + } + else + { + if (search_depth == 0) + /* Automatically determine a reasonable value for 'search_depth' */ + search_depth= determine_search_depth(join); + if (greedy_search(join, join_tables, search_depth, prune_level)) + DBUG_RETURN(TRUE); + } + } + + /* + Store the cost of this query into a user variable + Don't update last_query_cost for statements that are not "flat joins" : + i.e. they have subqueries, unions or call stored procedures. + TODO: calculate a correct cost for a query with subqueries and UNIONs. + */ + if (join->thd->lex->is_single_level_stmt()) + join->thd->status_var.last_query_cost= join->best_read; + DBUG_RETURN(FALSE); +} + + +/** + Compare two JOIN_TAB objects based on the number of accessed records. + + @param ptr1 pointer to first JOIN_TAB object + @param ptr2 pointer to second JOIN_TAB object + + NOTES + The order relation implemented by join_tab_cmp() is not transitive, + i.e. it is possible to choose such a, b and c that (a < b) && (b < c) + but (c < a). This implies that result of a sort using the relation + implemented by join_tab_cmp() depends on the order in which + elements are compared, i.e. the result is implementation-specific. + Example: + a: dependent = 0x0 table->map = 0x1 found_records = 3 ptr = 0x907e6b0 + b: dependent = 0x0 table->map = 0x2 found_records = 3 ptr = 0x907e838 + c: dependent = 0x6 table->map = 0x10 found_records = 2 ptr = 0x907ecd0 + + @retval + 1 if first is bigger + @retval + -1 if second is bigger + @retval + 0 if equal +*/ + +static int +join_tab_cmp(const void* ptr1, const void* ptr2) +{ + JOIN_TAB *jt1= *(JOIN_TAB**) ptr1; + JOIN_TAB *jt2= *(JOIN_TAB**) ptr2; + + if (jt1->dependent & jt2->table->map) + return 1; + if (jt2->dependent & jt1->table->map) + return -1; + if (jt1->found_records > jt2->found_records) + return 1; + if (jt1->found_records < jt2->found_records) + return -1; + return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0); +} + + +/** + Same as join_tab_cmp, but for use with SELECT_STRAIGHT_JOIN. +*/ + +static int +join_tab_cmp_straight(const void* ptr1, const void* ptr2) +{ + JOIN_TAB *jt1= *(JOIN_TAB**) ptr1; + JOIN_TAB *jt2= *(JOIN_TAB**) ptr2; + + if (jt1->dependent & jt2->table->map) + return 1; + if (jt2->dependent & jt1->table->map) + return -1; + return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0); +} + +/** + Heuristic procedure to automatically guess a reasonable degree of + exhaustiveness for the greedy search procedure. + + The procedure estimates the optimization time and selects a search depth + big enough to result in a near-optimal QEP, that doesn't take too long to + find. If the number of tables in the query exceeds some constant, then + search_depth is set to this constant. + + @param join pointer to the structure providing all context info for + the query + + @note + This is an extremely simplistic implementation that serves as a stub for a + more advanced analysis of the join. Ideally the search depth should be + determined by learning from previous query optimizations, because it will + depend on the CPU power (and other factors). + + @todo + this value should be determined dynamically, based on statistics: + uint max_tables_for_exhaustive_opt= 7; + + @todo + this value could be determined by some mapping of the form: + depth : table_count -> [max_tables_for_exhaustive_opt..MAX_EXHAUSTIVE] + + @return + A positive integer that specifies the search depth (and thus the + exhaustiveness) of the depth-first search algorithm used by + 'greedy_search'. +*/ + +static uint +determine_search_depth(JOIN *join) +{ + uint table_count= join->tables - join->const_tables; + uint search_depth; + /* TODO: this value should be determined dynamically, based on statistics: */ + uint max_tables_for_exhaustive_opt= 7; + + if (table_count <= max_tables_for_exhaustive_opt) + search_depth= table_count+1; // use exhaustive for small number of tables + else + /* + TODO: this value could be determined by some mapping of the form: + depth : table_count -> [max_tables_for_exhaustive_opt..MAX_EXHAUSTIVE] + */ + search_depth= max_tables_for_exhaustive_opt; // use greedy search + + return search_depth; +} + + +/** + Select the best ways to access the tables in a query without reordering them. + + Find the best access paths for each query table and compute their costs + according to their order in the array 'join->best_ref' (thus without + reordering the join tables). The function calls sequentially + 'best_access_path' for each table in the query to select the best table + access method. The final optimal plan is stored in the array + 'join->best_positions', and the corresponding cost in 'join->best_read'. + + @param join pointer to the structure providing all context info for + the query + @param join_tables set of the tables in the query + + @note + This function can be applied to: + - queries with STRAIGHT_JOIN + - internally to compute the cost of an arbitrary QEP + @par + Thus 'optimize_straight_join' can be used at any stage of the query + optimization process to finalize a QEP as it is. +*/ + +static void +optimize_straight_join(JOIN *join, table_map join_tables) +{ + JOIN_TAB *s; + uint idx= join->const_tables; + double record_count= 1.0; + double read_time= 0.0; + + for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++) + { + /* Find the best access method from 's' to the current partial plan */ + best_access_path(join, s, join->thd, join_tables, idx, + record_count, read_time); + /* compute the cost of the new plan extended with 's' */ + record_count*= join->positions[idx].records_read; + read_time+= join->positions[idx].read_time; + join_tables&= ~(s->table->map); + ++idx; + } + + read_time+= record_count / (double) TIME_FOR_COMPARE; + if (join->sort_by_table && + join->sort_by_table != join->positions[join->const_tables].table->table) + read_time+= record_count; // We have to make a temp table + memcpy((uchar*) join->best_positions, (uchar*) join->positions, + sizeof(POSITION)*idx); + join->best_read= read_time; +} + + +/** + Find a good, possibly optimal, query execution plan (QEP) by a greedy search. + + The search procedure uses a hybrid greedy/exhaustive search with controlled + exhaustiveness. The search is performed in N = card(remaining_tables) + steps. Each step evaluates how promising is each of the unoptimized tables, + selects the most promising table, and extends the current partial QEP with + that table. Currenly the most 'promising' table is the one with least + expensive extension.\ + + There are two extreme cases: + -# When (card(remaining_tables) < search_depth), the estimate finds the + best complete continuation of the partial QEP. This continuation can be + used directly as a result of the search. + -# When (search_depth == 1) the 'best_extension_by_limited_search' + consideres the extension of the current QEP with each of the remaining + unoptimized tables. + + All other cases are in-between these two extremes. Thus the parameter + 'search_depth' controlls the exhaustiveness of the search. The higher the + value, the longer the optimizaton time and possibly the better the + resulting plan. The lower the value, the fewer alternative plans are + estimated, but the more likely to get a bad QEP. + + All intermediate and final results of the procedure are stored in 'join': + - join->positions : modified for every partial QEP that is explored + - join->best_positions: modified for the current best complete QEP + - join->best_read : modified for the current best complete QEP + - join->best_ref : might be partially reordered + + The final optimal plan is stored in 'join->best_positions', and its + corresponding cost in 'join->best_read'. + + @note + The following pseudocode describes the algorithm of 'greedy_search': + + @code + procedure greedy_search + input: remaining_tables + output: pplan; + { + pplan = <>; + do { + (t, a) = best_extension(pplan, remaining_tables); + pplan = concat(pplan, (t, a)); + remaining_tables = remaining_tables - t; + } while (remaining_tables != {}) + return pplan; + } + + @endcode + where 'best_extension' is a placeholder for a procedure that selects the + most "promising" of all tables in 'remaining_tables'. + Currently this estimate is performed by calling + 'best_extension_by_limited_search' to evaluate all extensions of the + current QEP of size 'search_depth', thus the complexity of 'greedy_search' + mainly depends on that of 'best_extension_by_limited_search'. + + @par + If 'best_extension()' == 'best_extension_by_limited_search()', then the + worst-case complexity of this algorithm is <= + O(N*N^search_depth/search_depth). When serch_depth >= N, then the + complexity of greedy_search is O(N!). + + @par + In the future, 'greedy_search' might be extended to support other + implementations of 'best_extension', e.g. some simpler quadratic procedure. + + @param join pointer to the structure providing all context info + for the query + @param remaining_tables set of tables not included into the partial plan yet + @param search_depth controlls the exhaustiveness of the search + @param prune_level the pruning heuristics that should be applied during + search + + @retval + FALSE ok + @retval + TRUE Fatal error +*/ + +static bool +greedy_search(JOIN *join, + table_map remaining_tables, + uint search_depth, + uint prune_level) +{ + double record_count= 1.0; + double read_time= 0.0; + uint idx= join->const_tables; // index into 'join->best_ref' + uint best_idx; + uint size_remain; // cardinality of remaining_tables + POSITION best_pos; + JOIN_TAB *best_table; // the next plan node to be added to the curr QEP + + DBUG_ENTER("greedy_search"); + + /* number of tables that remain to be optimized */ + size_remain= my_count_bits(remaining_tables); + + do { + /* Find the extension of the current QEP with the lowest cost */ + join->best_read= DBL_MAX; + if (best_extension_by_limited_search(join, remaining_tables, idx, record_count, + read_time, search_depth, prune_level)) + DBUG_RETURN(TRUE); + + if (size_remain <= search_depth) + { + /* + 'join->best_positions' contains a complete optimal extension of the + current partial QEP. + */ + DBUG_EXECUTE("opt", print_plan(join, join->tables, + record_count, read_time, read_time, + "optimal");); + DBUG_RETURN(FALSE); + } + + /* select the first table in the optimal extension as most promising */ + best_pos= join->best_positions[idx]; + best_table= best_pos.table; + /* + Each subsequent loop of 'best_extension_by_limited_search' uses + 'join->positions' for cost estimates, therefore we have to update its + value. + */ + join->positions[idx]= best_pos; + + /* + Update the interleaving state after extending the current partial plan + with a new table. + We are doing this here because best_extension_by_limited_search reverts + the interleaving state to the one of the non-extended partial plan + on exit. + */ + IF_DBUG(bool is_interleave_error= ) + check_interleaving_with_nj (best_table); + /* This has been already checked by best_extension_by_limited_search */ + DBUG_ASSERT(!is_interleave_error); + + /* find the position of 'best_table' in 'join->best_ref' */ + best_idx= idx; + JOIN_TAB *pos= join->best_ref[best_idx]; + while (pos && best_table != pos) + pos= join->best_ref[++best_idx]; + DBUG_ASSERT((pos != NULL)); // should always find 'best_table' + /* move 'best_table' at the first free position in the array of joins */ + swap_variables(JOIN_TAB*, join->best_ref[idx], join->best_ref[best_idx]); + + /* compute the cost of the new plan extended with 'best_table' */ + record_count*= join->positions[idx].records_read; + read_time+= join->positions[idx].read_time; + + remaining_tables&= ~(best_table->table->map); + --size_remain; + ++idx; + + DBUG_EXECUTE("opt", print_plan(join, idx, + record_count, read_time, read_time, + "extended");); + } while (TRUE); +} + + +/** + Find a good, possibly optimal, query execution plan (QEP) by a possibly + exhaustive search. + + The procedure searches for the optimal ordering of the query tables in set + 'remaining_tables' of size N, and the corresponding optimal access paths to + each table. The choice of a table order and an access path for each table + constitutes a query execution plan (QEP) that fully specifies how to + execute the query. + + The maximal size of the found plan is controlled by the parameter + 'search_depth'. When search_depth == N, the resulting plan is complete and + can be used directly as a QEP. If search_depth < N, the found plan consists + of only some of the query tables. Such "partial" optimal plans are useful + only as input to query optimization procedures, and cannot be used directly + to execute a query. + + The algorithm begins with an empty partial plan stored in 'join->positions' + and a set of N tables - 'remaining_tables'. Each step of the algorithm + evaluates the cost of the partial plan extended by all access plans for + each of the relations in 'remaining_tables', expands the current partial + plan with the access plan that results in lowest cost of the expanded + partial plan, and removes the corresponding relation from + 'remaining_tables'. The algorithm continues until it either constructs a + complete optimal plan, or constructs an optimal plartial plan with size = + search_depth. + + The final optimal plan is stored in 'join->best_positions'. The + corresponding cost of the optimal plan is in 'join->best_read'. + + @note + The procedure uses a recursive depth-first search where the depth of the + recursion (and thus the exhaustiveness of the search) is controlled by the + parameter 'search_depth'. + + @note + The pseudocode below describes the algorithm of + 'best_extension_by_limited_search'. The worst-case complexity of this + algorithm is O(N*N^search_depth/search_depth). When serch_depth >= N, then + the complexity of greedy_search is O(N!). + + @code + procedure best_extension_by_limited_search( + pplan in, // in, partial plan of tables-joined-so-far + pplan_cost, // in, cost of pplan + remaining_tables, // in, set of tables not referenced in pplan + best_plan_so_far, // in/out, best plan found so far + best_plan_so_far_cost,// in/out, cost of best_plan_so_far + search_depth) // in, maximum size of the plans being considered + { + for each table T from remaining_tables + { + // Calculate the cost of using table T as above + cost = complex-series-of-calculations; + + // Add the cost to the cost so far. + pplan_cost+= cost; + + if (pplan_cost >= best_plan_so_far_cost) + // pplan_cost already too great, stop search + continue; + + pplan= expand pplan by best_access_method; + remaining_tables= remaining_tables - table T; + if (remaining_tables is not an empty set + and + search_depth > 1) + { + best_extension_by_limited_search(pplan, pplan_cost, + remaining_tables, + best_plan_so_far, + best_plan_so_far_cost, + search_depth - 1); + } + else + { + best_plan_so_far_cost= pplan_cost; + best_plan_so_far= pplan; + } + } + } + @endcode + + @note + When 'best_extension_by_limited_search' is called for the first time, + 'join->best_read' must be set to the largest possible value (e.g. DBL_MAX). + The actual implementation provides a way to optionally use pruning + heuristic (controlled by the parameter 'prune_level') to reduce the search + space by skipping some partial plans. + + @note + The parameter 'search_depth' provides control over the recursion + depth, and thus the size of the resulting optimal plan. + + @param join pointer to the structure providing all context info + for the query + @param remaining_tables set of tables not included into the partial plan yet + @param idx length of the partial QEP in 'join->positions'; + since a depth-first search is used, also corresponds + to the current depth of the search tree; + also an index in the array 'join->best_ref'; + @param record_count estimate for the number of records returned by the + best partial plan + @param read_time the cost of the best partial plan + @param search_depth maximum depth of the recursion and thus size of the + found optimal plan + (0 < search_depth <= join->tables+1). + @param prune_level pruning heuristics that should be applied during + optimization + (values: 0 = EXHAUSTIVE, 1 = PRUNE_BY_TIME_OR_ROWS) + + @retval + FALSE ok + @retval + TRUE Fatal error +*/ + +static bool +best_extension_by_limited_search(JOIN *join, + table_map remaining_tables, + uint idx, + double record_count, + double read_time, + uint search_depth, + uint prune_level) +{ + DBUG_ENTER("best_extension_by_limited_search"); + + THD *thd= join->thd; + if (thd->killed) // Abort + DBUG_RETURN(TRUE); + + DBUG_EXECUTE("opt", print_plan(join, idx, read_time, record_count, idx, + "SOFAR:");); + + /* + 'join' is a partial plan with lower cost than the best plan so far, + so continue expanding it further with the tables in 'remaining_tables'. + */ + JOIN_TAB *s; + double best_record_count= DBL_MAX; + double best_read_time= DBL_MAX; + + DBUG_EXECUTE("opt", print_plan(join, idx, record_count, read_time, read_time, + "part_plan");); + + for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++) + { + table_map real_table_bit= s->table->map; + if ((remaining_tables & real_table_bit) && + !(remaining_tables & s->dependent) && + (!idx || !check_interleaving_with_nj(s))) + { + double current_record_count, current_read_time; + + /* Find the best access method from 's' to the current partial plan */ + best_access_path(join, s, thd, remaining_tables, idx, + record_count, read_time); + /* Compute the cost of extending the plan with 's' */ + current_record_count= record_count * join->positions[idx].records_read; + current_read_time= read_time + join->positions[idx].read_time; + + /* Expand only partial plans with lower cost than the best QEP so far */ + if ((current_read_time + + current_record_count / (double) TIME_FOR_COMPARE) >= join->best_read) + { + DBUG_EXECUTE("opt", print_plan(join, idx+1, + current_record_count, + read_time, + (current_read_time + + current_record_count / + (double) TIME_FOR_COMPARE), + "prune_by_cost");); + restore_prev_nj_state(s); + continue; + } + + /* + Prune some less promising partial plans. This heuristic may miss + the optimal QEPs, thus it results in a non-exhaustive search. + */ + if (prune_level == 1) + { + if (best_record_count > current_record_count || + best_read_time > current_read_time || + (idx == join->const_tables && // 's' is the first table in the QEP + s->table == join->sort_by_table)) + { + if (best_record_count >= current_record_count && + best_read_time >= current_read_time && + /* TODO: What is the reasoning behind this condition? */ + (!(s->key_dependent & remaining_tables) || + join->positions[idx].records_read < 2.0)) + { + best_record_count= current_record_count; + best_read_time= current_read_time; + } + } + else + { + DBUG_EXECUTE("opt", print_plan(join, idx+1, + current_record_count, + read_time, + current_read_time, + "pruned_by_heuristic");); + restore_prev_nj_state(s); + continue; + } + } + + if ( (search_depth > 1) && (remaining_tables & ~real_table_bit) ) + { /* Recursively expand the current partial plan */ + swap_variables(JOIN_TAB*, join->best_ref[idx], *pos); + if (best_extension_by_limited_search(join, + remaining_tables & ~real_table_bit, + idx + 1, + current_record_count, + current_read_time, + search_depth - 1, + prune_level)) + DBUG_RETURN(TRUE); + swap_variables(JOIN_TAB*, join->best_ref[idx], *pos); + } + else + { /* + 'join' is either the best partial QEP with 'search_depth' relations, + or the best complete QEP so far, whichever is smaller. + */ + current_read_time+= current_record_count / (double) TIME_FOR_COMPARE; + if (join->sort_by_table && + join->sort_by_table != + join->positions[join->const_tables].table->table) + /* We have to make a temp table */ + current_read_time+= current_record_count; + if ((search_depth == 1) || (current_read_time < join->best_read)) + { + memcpy((uchar*) join->best_positions, (uchar*) join->positions, + sizeof(POSITION) * (idx + 1)); + join->best_read= current_read_time - 0.001; + } + DBUG_EXECUTE("opt", print_plan(join, idx+1, + current_record_count, + read_time, + current_read_time, + "full_plan");); + } + restore_prev_nj_state(s); + } + } + DBUG_RETURN(FALSE); +} + + +/** + @todo + - TODO: this function is here only temporarily until 'greedy_search' is + tested and accepted. + + RETURN VALUES + FALSE ok + TRUE Fatal error +*/ +static bool +find_best(JOIN *join,table_map rest_tables,uint idx,double record_count, + double read_time) +{ + DBUG_ENTER("find_best"); + THD *thd= join->thd; + if (thd->killed) + DBUG_RETURN(TRUE); + if (!rest_tables) + { + DBUG_PRINT("best",("read_time: %g record_count: %g",read_time, + record_count)); + + read_time+=record_count/(double) TIME_FOR_COMPARE; + if (join->sort_by_table && + join->sort_by_table != + join->positions[join->const_tables].table->table) + read_time+=record_count; // We have to make a temp table + if (read_time < join->best_read) + { + memcpy((uchar*) join->best_positions,(uchar*) join->positions, + sizeof(POSITION)*idx); + join->best_read= read_time - 0.001; + } + DBUG_RETURN(FALSE); + } + if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read) + DBUG_RETURN(FALSE); /* Found better before */ + + JOIN_TAB *s; + double best_record_count=DBL_MAX,best_read_time=DBL_MAX; + for (JOIN_TAB **pos=join->best_ref+idx ; (s=*pos) ; pos++) + { + table_map real_table_bit=s->table->map; + if ((rest_tables & real_table_bit) && !(rest_tables & s->dependent) && + (!idx|| !check_interleaving_with_nj(s))) + { + double records, best; + best_access_path(join, s, thd, rest_tables, idx, record_count, + read_time); + records= join->positions[idx].records_read; + best= join->positions[idx].read_time; + /* + Go to the next level only if there hasn't been a better key on + this level! This will cut down the search for a lot simple cases! + */ + double current_record_count=record_count*records; + double current_read_time=read_time+best; + if (best_record_count > current_record_count || + best_read_time > current_read_time || + (idx == join->const_tables && s->table == join->sort_by_table)) + { + if (best_record_count >= current_record_count && + best_read_time >= current_read_time && + (!(s->key_dependent & rest_tables) || records < 2.0)) + { + best_record_count=current_record_count; + best_read_time=current_read_time; + } + swap_variables(JOIN_TAB*, join->best_ref[idx], *pos); + if (find_best(join,rest_tables & ~real_table_bit,idx+1, + current_record_count,current_read_time)) + DBUG_RETURN(TRUE); + swap_variables(JOIN_TAB*, join->best_ref[idx], *pos); + } + restore_prev_nj_state(s); + if (join->select_options & SELECT_STRAIGHT_JOIN) + break; // Don't test all combinations + } + } + DBUG_RETURN(FALSE); +} + + +/** + Find how much space the prevous read not const tables takes in cache. +*/ + +static void calc_used_field_length(THD *thd, JOIN_TAB *join_tab) +{ + uint null_fields,blobs,fields,rec_length; + Field **f_ptr,*field; + MY_BITMAP *read_set= join_tab->table->read_set;; + + null_fields= blobs= fields= rec_length=0; + for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++) + { + if (bitmap_is_set(read_set, field->field_index)) + { + uint flags=field->flags; + fields++; + rec_length+=field->pack_length(); + if (flags & BLOB_FLAG) + blobs++; + if (!(flags & NOT_NULL_FLAG)) + null_fields++; + } + } + if (null_fields) + rec_length+=(join_tab->table->s->null_fields+7)/8; + if (join_tab->table->maybe_null) + rec_length+=sizeof(my_bool); + if (blobs) + { + uint blob_length=(uint) (join_tab->table->file->stats.mean_rec_length- + (join_tab->table->s->reclength- rec_length)); + rec_length+=(uint) max(4,blob_length); + } + join_tab->used_fields=fields; + join_tab->used_fieldlength=rec_length; + join_tab->used_blobs=blobs; +} + + +static uint +cache_record_length(JOIN *join,uint idx) +{ + uint length=0; + JOIN_TAB **pos,**end; + THD *thd=join->thd; + + for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ; + pos != end ; + pos++) + { + JOIN_TAB *join_tab= *pos; + if (!join_tab->used_fieldlength) /* Not calced yet */ + calc_used_field_length(thd, join_tab); + length+=join_tab->used_fieldlength; + } + return length; +} + + +/* + Get the number of different row combinations for subset of partial join + + SYNOPSIS + prev_record_reads() + join The join structure + idx Number of tables in the partial join order (i.e. the + partial join order is in join->positions[0..idx-1]) + found_ref Bitmap of tables for which we need to find # of distinct + row combinations. + + DESCRIPTION + Given a partial join order (in join->positions[0..idx-1]) and a subset of + tables within that join order (specified in found_ref), find out how many + distinct row combinations of subset tables will be in the result of the + partial join order. + + This is used as follows: Suppose we have a table accessed with a ref-based + method. The ref access depends on current rows of tables in found_ref. + We want to count # of different ref accesses. We assume two ref accesses + will be different if at least one of access parameters is different. + Example: consider a query + + SELECT * FROM t1, t2, t3 WHERE t1.key=c1 AND t2.key=c2 AND t3.key=t1.field + + and a join order: + t1, ref access on t1.key=c1 + t2, ref access on t2.key=c2 + t3, ref access on t3.key=t1.field + + For t1: n_ref_scans = 1, n_distinct_ref_scans = 1 + For t2: n_ref_scans = records_read(t1), n_distinct_ref_scans=1 + For t3: n_ref_scans = records_read(t1)*records_read(t2) + n_distinct_ref_scans = #records_read(t1) + + The reason for having this function (at least the latest version of it) + is that we need to account for buffering in join execution. + + An edge-case example: if we have a non-first table in join accessed via + ref(const) or ref(param) where there is a small number of different + values of param, then the access will likely hit the disk cache and will + not require any disk seeks. + + The proper solution would be to assume an LRU disk cache of some size, + calculate probability of cache hits, etc. For now we just count + identical ref accesses as one. + + RETURN + Expected number of row combinations +*/ + +static double +prev_record_reads(JOIN *join, uint idx, table_map found_ref) +{ + double found=1.0; + POSITION *pos_end= join->positions - 1; + for (POSITION *pos= join->positions + idx - 1; pos != pos_end; pos--) + { + if (pos->table->table->map & found_ref) + { + found_ref|= pos->ref_depend_map; + /* + For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table + with no matching row we will get position[t2].records_read==0. + Actually the size of output is one null-complemented row, therefore + we will use value of 1 whenever we get records_read==0. + + Note + - the above case can't occur if inner part of outer join has more + than one table: table with no matches will not be marked as const. + + - Ideally we should add 1 to records_read for every possible null- + complemented row. We're not doing it because: 1. it will require + non-trivial code and add overhead. 2. The value of records_read + is an inprecise estimate and adding 1 (or, in the worst case, + #max_nested_outer_joins=64-1) will not make it any more precise. + */ + if (pos->records_read) + found*= pos->records_read; + } + } + return found; +} + + +/** + Set up join struct according to best position. +*/ + +static bool +get_best_combination(JOIN *join) +{ + uint i,tablenr; + table_map used_tables; + JOIN_TAB *join_tab,*j; + KEYUSE *keyuse; + uint table_count; + THD *thd=join->thd; + DBUG_ENTER("get_best_combination"); + + table_count=join->tables; + if (!(join->join_tab=join_tab= + (JOIN_TAB*) thd->alloc(sizeof(JOIN_TAB)*table_count))) + DBUG_RETURN(TRUE); + + join->full_join=0; + + used_tables= OUTER_REF_TABLE_BIT; // Outer row is already read + for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++) + { + TABLE *form; + *j= *join->best_positions[tablenr].table; + form=join->table[tablenr]=j->table; + used_tables|= form->map; + form->reginfo.join_tab=j; + if (!*j->on_expr_ref) + form->reginfo.not_exists_optimize=0; // Only with LEFT JOIN + DBUG_PRINT("info",("type: %d", j->type)); + if (j->type == JT_CONST) + continue; // Handled in make_join_stat.. + + j->ref.key = -1; + j->ref.key_parts=0; + + if (j->type == JT_SYSTEM) + continue; + if (j->keys.is_clear_all() || !(keyuse= join->best_positions[tablenr].key)) + { + j->type=JT_ALL; + if (tablenr != join->const_tables) + join->full_join=1; + } + else if (create_ref_for_key(join, j, keyuse, used_tables)) + DBUG_RETURN(TRUE); // Something went wrong + } + + for (i=0 ; i < table_count ; i++) + join->map2table[join->join_tab[i].table->tablenr]=join->join_tab+i; + update_depend_map(join); + DBUG_RETURN(0); +} + + +static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse, + table_map used_tables) +{ + KEYUSE *keyuse=org_keyuse; + bool ftkey=(keyuse->keypart == FT_KEYPART); + THD *thd= join->thd; + uint keyparts,length,key; + TABLE *table; + KEY *keyinfo; + DBUG_ENTER("create_ref_for_key"); + + /* Use best key from find_best */ + table=j->table; + key=keyuse->key; + keyinfo=table->key_info+key; + + if (ftkey) + { + Item_func_match *ifm=(Item_func_match *)keyuse->val; + + length=0; + keyparts=1; + ifm->join_key=1; + } + else + { + keyparts=length=0; + uint found_part_ref_or_null= 0; + /* + Calculate length for the used key + Stop if there is a missing key part or when we find second key_part + with KEY_OPTIMIZE_REF_OR_NULL + */ + do + { + if (!(~used_tables & keyuse->used_tables)) + { + if (keyparts == keyuse->keypart && + !(found_part_ref_or_null & keyuse->optimize)) + { + keyparts++; + length+= keyinfo->key_part[keyuse->keypart].store_length; + found_part_ref_or_null|= keyuse->optimize; + } + } + keyuse++; + } while (keyuse->table == table && keyuse->key == key); + } /* not ftkey */ + + /* set up fieldref */ + keyinfo=table->key_info+key; + j->ref.key_parts=keyparts; + j->ref.key_length=length; + j->ref.key=(int) key; + if (!(j->ref.key_buff= (uchar*) thd->calloc(ALIGN_SIZE(length)*2)) || + !(j->ref.key_copy= (store_key**) thd->alloc((sizeof(store_key*) * + (keyparts+1)))) || + !(j->ref.items= (Item**) thd->alloc(sizeof(Item*)*keyparts)) || + !(j->ref.cond_guards= (bool**) thd->alloc(sizeof(uint*)*keyparts))) + { + DBUG_RETURN(TRUE); + } + j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length); + j->ref.key_err=1; + j->ref.null_rejecting= 0; + keyuse=org_keyuse; + + store_key **ref_key= j->ref.key_copy; + uchar *key_buff=j->ref.key_buff, *null_ref_key= 0; + bool keyuse_uses_no_tables= TRUE; + if (ftkey) + { + j->ref.items[0]=((Item_func*)(keyuse->val))->key_item(); + /* Predicates pushed down into subquery can't be used FT access */ + j->ref.cond_guards[0]= NULL; + if (keyuse->used_tables) + DBUG_RETURN(TRUE); // not supported yet. SerG + + j->type=JT_FT; + } + else + { + uint i; + for (i=0 ; i < keyparts ; keyuse++,i++) + { + while (keyuse->keypart != i || + ((~used_tables) & keyuse->used_tables)) + keyuse++; /* Skip other parts */ + + uint maybe_null= test(keyinfo->key_part[i].null_bit); + j->ref.items[i]=keyuse->val; // Save for cond removal + j->ref.cond_guards[i]= keyuse->cond_guard; + if (keyuse->null_rejecting) + j->ref.null_rejecting |= 1 << i; + keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables; + if (!keyuse->used_tables && + !(join->select_options & SELECT_DESCRIBE)) + { // Compare against constant + store_key_item tmp(thd, keyinfo->key_part[i].field, + key_buff + maybe_null, + maybe_null ? key_buff : 0, + keyinfo->key_part[i].length, keyuse->val); + if (thd->is_fatal_error) + DBUG_RETURN(TRUE); + tmp.copy(); + } + else + *ref_key++= get_store_key(thd, + keyuse,join->const_table_map, + &keyinfo->key_part[i], + key_buff, maybe_null); + /* + Remember if we are going to use REF_OR_NULL + But only if field _really_ can be null i.e. we force JT_REF + instead of JT_REF_OR_NULL in case if field can't be null + */ + if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null) + null_ref_key= key_buff; + key_buff+=keyinfo->key_part[i].store_length; + } + } /* not ftkey */ + *ref_key=0; // end_marker + if (j->type == JT_FT) + DBUG_RETURN(0); + if (j->type == JT_CONST) + j->table->const_table= 1; + else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY | + HA_END_SPACE_KEY)) != HA_NOSAME) || + keyparts != keyinfo->key_parts || null_ref_key) + { + /* Must read with repeat */ + j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF; + j->ref.null_ref_key= null_ref_key; + } + else if (keyuse_uses_no_tables) + { + /* + This happen if we are using a constant expression in the ON part + of an LEFT JOIN. + SELECT * FROM a LEFT JOIN b ON b.key=30 + Here we should not mark the table as a 'const' as a field may + have a 'normal' value or a NULL value. + */ + j->type=JT_CONST; + } + else + j->type=JT_EQ_REF; + DBUG_RETURN(0); +} + + + +static store_key * +get_store_key(THD *thd, KEYUSE *keyuse, table_map used_tables, + KEY_PART_INFO *key_part, uchar *key_buff, uint maybe_null) +{ + if (!((~used_tables) & keyuse->used_tables)) // if const item + { + return new store_key_const_item(thd, + key_part->field, + key_buff + maybe_null, + maybe_null ? key_buff : 0, + key_part->length, + keyuse->val); + } + else if (keyuse->val->type() == Item::FIELD_ITEM || + (keyuse->val->type() == Item::REF_ITEM && + ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF && + (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() == + Item_ref::DIRECT_REF && + keyuse->val->real_item()->type() == Item::FIELD_ITEM)) + return new store_key_field(thd, + key_part->field, + key_buff + maybe_null, + maybe_null ? key_buff : 0, + key_part->length, + ((Item_field*) keyuse->val->real_item())->field, + keyuse->val->full_name()); + return new store_key_item(thd, + key_part->field, + key_buff + maybe_null, + maybe_null ? key_buff : 0, + key_part->length, + keyuse->val); +} + +/** + This function is only called for const items on fields which are keys. + + @return + returns 1 if there was some conversion made when the field was stored. +*/ + +bool +store_val_in_field(Field *field, Item *item, enum_check_fields check_flag) +{ + bool error; + TABLE *table= field->table; + THD *thd= table->in_use; + ha_rows cuted_fields=thd->cuted_fields; + my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, + table->write_set); + + /* + we should restore old value of count_cuted_fields because + store_val_in_field can be called from mysql_insert + with select_insert, which make count_cuted_fields= 1 + */ + enum_check_fields old_count_cuted_fields= thd->count_cuted_fields; + thd->count_cuted_fields= check_flag; + error= item->save_in_field(field, 1); + thd->count_cuted_fields= old_count_cuted_fields; + dbug_tmp_restore_column_map(table->write_set, old_map); + return error || cuted_fields != thd->cuted_fields; +} + + +/** + @details Initialize a JOIN as a query execution plan + that accesses a single table via a table scan. + + @param parent contains JOIN_TAB and TABLE object buffers for this join + @param tmp_table temporary table + + @retval FALSE success + @retval TRUE error occurred +*/ +bool +JOIN::make_simple_join(JOIN *parent, TABLE *tmp_table) +{ + DBUG_ENTER("JOIN::make_simple_join"); + + /* + Reuse TABLE * and JOIN_TAB if already allocated by a previous call + to this function through JOIN::exec (may happen for sub-queries). + */ + if (!parent->join_tab_reexec && + !(parent->join_tab_reexec= (JOIN_TAB*) thd->alloc(sizeof(JOIN_TAB)))) + DBUG_RETURN(TRUE); /* purecov: inspected */ + + join_tab= parent->join_tab_reexec; + table= &parent->table_reexec[0]; parent->table_reexec[0]= tmp_table; + tables= 1; + const_tables= 0; + const_table_map= 0; + tmp_table_param.field_count= tmp_table_param.sum_func_count= + tmp_table_param.func_count= 0; + tmp_table_param.copy_field= tmp_table_param.copy_field_end=0; + first_record= sort_and_group=0; + send_records= (ha_rows) 0; + group= 0; + row_limit= unit->select_limit_cnt; + do_send_rows= row_limit ? 1 : 0; + + join_tab->cache.buff=0; /* No caching */ + join_tab->table=tmp_table; + join_tab->select=0; + join_tab->select_cond=0; + join_tab->quick=0; + join_tab->type= JT_ALL; /* Map through all records */ + join_tab->keys.init(); + join_tab->keys.set_all(); /* test everything in quick */ + join_tab->info=0; + join_tab->on_expr_ref=0; + join_tab->last_inner= 0; + join_tab->first_unmatched= 0; + join_tab->ref.key = -1; + join_tab->not_used_in_distinct=0; + join_tab->read_first_record= join_init_read_record; + join_tab->join= this; + join_tab->ref.key_parts= 0; + bzero((char*) &join_tab->read_record,sizeof(join_tab->read_record)); + tmp_table->status=0; + tmp_table->null_row=0; + DBUG_RETURN(FALSE); +} + + +inline void add_cond_and_fix(Item **e1, Item *e2) +{ + if (*e1) + { + Item *res; + if ((res= new Item_cond_and(*e1, e2))) + { + *e1= res; + res->quick_fix_field(); + } + } + else + *e1= e2; +} + + +/** + Add to join_tab->select_cond[i] "table.field IS NOT NULL" conditions + we've inferred from ref/eq_ref access performed. + + This function is a part of "Early NULL-values filtering for ref access" + optimization. + + Example of this optimization: + For query SELECT * FROM t1,t2 WHERE t2.key=t1.field @n + and plan " any-access(t1), ref(t2.key=t1.field) " @n + add "t1.field IS NOT NULL" to t1's table condition. @n + + Description of the optimization: + + We look through equalities choosen to perform ref/eq_ref access, + pick equalities that have form "tbl.part_of_key = othertbl.field" + (where othertbl is a non-const table and othertbl.field may be NULL) + and add them to conditions on correspoding tables (othertbl in this + example). + + Exception from that is the case when referred_tab->join != join. + I.e. don't add NOT NULL constraints from any embedded subquery. + Consider this query: + @code + SELECT A.f2 FROM t1 LEFT JOIN t2 A ON A.f2 = f1 + WHERE A.f3=(SELECT MIN(f3) FROM t2 C WHERE A.f4 = C.f4) OR A.f3 IS NULL; + @endocde + Here condition A.f3 IS NOT NULL is going to be added to the WHERE + condition of the embedding query. + Another example: + SELECT * FROM t10, t11 WHERE (t10.a < 10 OR t10.a IS NULL) + AND t11.b <=> t10.b AND (t11.a = (SELECT MAX(a) FROM t12 + WHERE t12.b = t10.a )); + Here condition t10.a IS NOT NULL is going to be added. + In both cases addition of NOT NULL condition will erroneously reject + some rows of the result set. + referred_tab->join != join constraint would disallow such additions. + + This optimization doesn't affect the choices that ref, range, or join + optimizer make. This was intentional because this was added after 4.1 + was GA. + + Implementation overview + 1. update_ref_and_keys() accumulates info about null-rejecting + predicates in in KEY_FIELD::null_rejecting + 1.1 add_key_part saves these to KEYUSE. + 2. create_ref_for_key copies them to TABLE_REF. + 3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of + appropiate JOIN_TAB members. +*/ + +static void add_not_null_conds(JOIN *join) +{ + DBUG_ENTER("add_not_null_conds"); + for (uint i=join->const_tables ; i < join->tables ; i++) + { + JOIN_TAB *tab=join->join_tab+i; + if ((tab->type == JT_REF || tab->type == JT_EQ_REF || + tab->type == JT_REF_OR_NULL) && + !tab->table->maybe_null) + { + for (uint keypart= 0; keypart < tab->ref.key_parts; keypart++) + { + if (tab->ref.null_rejecting & (1 << keypart)) + { + Item *item= tab->ref.items[keypart]; + Item *notnull; + DBUG_ASSERT(item->type() == Item::FIELD_ITEM); + Item_field *not_null_item= (Item_field*)item; + JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab; + /* + For UPDATE queries such as: + UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1); + not_null_item is the t1.f1, but it's referred_tab is 0. + */ + if (!referred_tab || referred_tab->join != join) + continue; + if (!(notnull= new Item_func_isnotnull(not_null_item))) + DBUG_VOID_RETURN; + /* + We need to do full fix_fields() call here in order to have correct + notnull->const_item(). This is needed e.g. by test_quick_select + when it is called from make_join_select after this function is + called. + */ + if (notnull->fix_fields(join->thd, ¬null)) + DBUG_VOID_RETURN; + DBUG_EXECUTE("where",print_where(notnull, + referred_tab->table->alias, + QT_ORDINARY);); + add_cond_and_fix(&referred_tab->select_cond, notnull); + } + } + } + } + DBUG_VOID_RETURN; +} + +/** + Build a predicate guarded by match variables for embedding outer joins. + The function recursively adds guards for predicate cond + assending from tab to the first inner table next embedding + nested outer join and so on until it reaches root_tab + (root_tab can be 0). + + @param tab the first inner table for most nested outer join + @param cond the predicate to be guarded (must be set) + @param root_tab the first inner table to stop + + @return + - pointer to the guarded predicate, if success + - 0, otherwise +*/ + +static COND* +add_found_match_trig_cond(JOIN_TAB *tab, COND *cond, JOIN_TAB *root_tab) +{ + COND *tmp; + DBUG_ASSERT(cond != 0); + if (tab == root_tab) + return cond; + if ((tmp= add_found_match_trig_cond(tab->first_upper, cond, root_tab))) + tmp= new Item_func_trig_cond(tmp, &tab->found); + if (tmp) + { + tmp->quick_fix_field(); + tmp->update_used_tables(); + } + return tmp; +} + + +/** + Fill in outer join related info for the execution plan structure. + + For each outer join operation left after simplification of the + original query the function set up the following pointers in the linear + structure join->join_tab representing the selected execution plan. + The first inner table t0 for the operation is set to refer to the last + inner table tk through the field t0->last_inner. + Any inner table ti for the operation are set to refer to the first + inner table ti->first_inner. + The first inner table t0 for the operation is set to refer to the + first inner table of the embedding outer join operation, if there is any, + through the field t0->first_upper. + The on expression for the outer join operation is attached to the + corresponding first inner table through the field t0->on_expr_ref. + Here ti are structures of the JOIN_TAB type. + + EXAMPLE. For the query: + @code + SELECT * FROM t1 + LEFT JOIN + (t2, t3 LEFT JOIN t4 ON t3.a=t4.a) + ON (t1.a=t2.a AND t1.b=t3.b) + WHERE t1.c > 5, + @endcode + + given the execution plan with the table order t1,t2,t3,t4 + is selected, the following references will be set; + t4->last_inner=[t4], t4->first_inner=[t4], t4->first_upper=[t2] + t2->last_inner=[t4], t2->first_inner=t3->first_inner=[t2], + on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to + *t2->on_expr_ref, while t3.a=t4.a will be attached to *t4->on_expr_ref. + + @param join reference to the info fully describing the query + + @note + The function assumes that the simplification procedure has been + already applied to the join query (see simplify_joins). + This function can be called only after the execution plan + has been chosen. +*/ + +static void +make_outerjoin_info(JOIN *join) +{ + DBUG_ENTER("make_outerjoin_info"); + for (uint i=join->const_tables ; i < join->tables ; i++) + { + JOIN_TAB *tab=join->join_tab+i; + TABLE *table=tab->table; + TABLE_LIST *tbl= table->pos_in_table_list; + TABLE_LIST *embedding= tbl->embedding; + + if (tbl->outer_join) + { + /* + Table tab is the only one inner table for outer join. + (Like table t4 for the table reference t3 LEFT JOIN t4 ON t3.a=t4.a + is in the query above.) + */ + tab->last_inner= tab->first_inner= tab; + tab->on_expr_ref= &tbl->on_expr; + tab->cond_equal= tbl->cond_equal; + if (embedding) + tab->first_upper= embedding->nested_join->first_nested; + } + for ( ; embedding ; embedding= embedding->embedding) + { + NESTED_JOIN *nested_join= embedding->nested_join; + if (!nested_join->counter) + { + /* + Table tab is the first inner table for nested_join. + Save reference to it in the nested join structure. + */ + nested_join->first_nested= tab; + tab->on_expr_ref= &embedding->on_expr; + tab->cond_equal= tbl->cond_equal; + if (embedding->embedding) + tab->first_upper= embedding->embedding->nested_join->first_nested; + } + if (!tab->first_inner) + tab->first_inner= nested_join->first_nested; + if (++nested_join->counter < nested_join->join_list.elements) + break; + /* Table tab is the last inner table for nested join. */ + nested_join->first_nested->last_inner= tab; + } + } + DBUG_VOID_RETURN; +} + + +static bool +make_join_select(JOIN *join,SQL_SELECT *select,COND *cond) +{ + THD *thd= join->thd; + DBUG_ENTER("make_join_select"); + if (select) + { + add_not_null_conds(join); + table_map used_tables; + if (cond) /* Because of QUICK_GROUP_MIN_MAX_SELECT */ + { /* there may be a select without a cond. */ + if (join->tables > 1) + cond->update_used_tables(); // Tablenr may have changed + if (join->const_tables == join->tables && + thd->lex->current_select->master_unit() == + &thd->lex->unit) // not upper level SELECT + join->const_table_map|=RAND_TABLE_BIT; + { // Check const tables + COND *const_cond= + make_cond_for_table(cond, + join->const_table_map, + (table_map) 0); + DBUG_EXECUTE("where",print_where(const_cond,"constants", QT_ORDINARY);); + for (JOIN_TAB *tab= join->join_tab+join->const_tables; + tab < join->join_tab+join->tables ; tab++) + { + if (*tab->on_expr_ref) + { + JOIN_TAB *cond_tab= tab->first_inner; + COND *tmp= make_cond_for_table(*tab->on_expr_ref, + join->const_table_map, + ( table_map) 0); + if (!tmp) + continue; + tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl); + if (!tmp) + DBUG_RETURN(1); + tmp->quick_fix_field(); + cond_tab->select_cond= !cond_tab->select_cond ? tmp : + new Item_cond_and(cond_tab->select_cond, + tmp); + if (!cond_tab->select_cond) + DBUG_RETURN(1); + cond_tab->select_cond->quick_fix_field(); + } + } + if (const_cond && !const_cond->val_int()) + { + DBUG_PRINT("info",("Found impossible WHERE condition")); + DBUG_RETURN(1); // Impossible const condition + } + } + } + used_tables=((select->const_tables=join->const_table_map) | + OUTER_REF_TABLE_BIT | RAND_TABLE_BIT); + for (uint i=join->const_tables ; i < join->tables ; i++) + { + JOIN_TAB *tab=join->join_tab+i; + /* + first_inner is the X in queries like: + SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X + */ + JOIN_TAB *first_inner_tab= tab->first_inner; + table_map current_map= tab->table->map; + bool use_quick_range=0; + COND *tmp; + + /* + Following force including random expression in last table condition. + It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5 + */ + if (i == join->tables-1) + current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT; + used_tables|=current_map; + + if (tab->type == JT_REF && tab->quick && + (uint) tab->ref.key == tab->quick->index && + tab->ref.key_length < tab->quick->max_used_key_length) + { + /* Range uses longer key; Use this instead of ref on key */ + tab->type=JT_ALL; + use_quick_range=1; + tab->use_quick=1; + tab->ref.key= -1; + tab->ref.key_parts=0; // Don't use ref key. + join->best_positions[i].records_read= rows2double(tab->quick->records); + /* + We will use join cache here : prevent sorting of the first + table only and sort at the end. + */ + if (i != join->const_tables && join->tables > join->const_tables + 1) + join->full_join= 1; + } + + tmp= NULL; + if (cond) + tmp= make_cond_for_table(cond,used_tables,current_map); + if (cond && !tmp && tab->quick) + { // Outer join + if (tab->type != JT_ALL) + { + /* + Don't use the quick method + We come here in the case where we have 'key=constant' and + the test is removed by make_cond_for_table() + */ + delete tab->quick; + tab->quick= 0; + } + else + { + /* + Hack to handle the case where we only refer to a table + in the ON part of an OUTER JOIN. In this case we want the code + below to check if we should use 'quick' instead. + */ + DBUG_PRINT("info", ("Item_int")); + tmp= new Item_int((longlong) 1,1); // Always true + } + + } + if (tmp || !cond || tab->type == JT_REF) + { + DBUG_EXECUTE("where",print_where(tmp,tab->table->alias, QT_ORDINARY);); + SQL_SELECT *sel= tab->select= ((SQL_SELECT*) + thd->memdup((uchar*) select, + sizeof(*select))); + if (!sel) + DBUG_RETURN(1); // End of memory + /* + If tab is an inner table of an outer join operation, + add a match guard to the pushed down predicate. + The guard will turn the predicate on only after + the first match for outer tables is encountered. + */ + if (cond && tmp) + { + /* + Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without + a cond, so neutralize the hack above. + */ + if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0))) + DBUG_RETURN(1); + tab->select_cond=sel->cond=tmp; + /* Push condition to storage engine if this is enabled + and the condition is not guarded */ + tab->table->file->pushed_cond= NULL; + if (thd->variables.engine_condition_pushdown) + { + COND *push_cond= + make_cond_for_table(tmp, current_map, current_map); + if (push_cond) + { + /* Push condition to handler */ + if (!tab->table->file->cond_push(push_cond)) + tab->table->file->pushed_cond= push_cond; + } + } + } + else + tab->select_cond= sel->cond= NULL; + + sel->head=tab->table; + DBUG_EXECUTE("where",print_where(tmp,tab->table->alias, QT_ORDINARY);); + if (tab->quick) + { + /* Use quick key read if it's a constant and it's not used + with key reading */ + if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF + && tab->type != JT_FT && (tab->type != JT_REF || + (uint) tab->ref.key == tab->quick->index)) + { + sel->quick=tab->quick; // Use value from get_quick_... + sel->quick_keys.clear_all(); + sel->needed_reg.clear_all(); + } + else + { + delete tab->quick; + } + tab->quick=0; + } + uint ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1; + if (i == join->const_tables && ref_key) + { + if (!tab->const_keys.is_clear_all() && + tab->table->reginfo.impossible_range) + DBUG_RETURN(1); + } + else if (tab->type == JT_ALL && ! use_quick_range) + { + if (!tab->const_keys.is_clear_all() && + tab->table->reginfo.impossible_range) + DBUG_RETURN(1); // Impossible range + /* + We plan to scan all rows. + Check again if we should use an index. + We could have used an column from a previous table in + the index if we are using limit and this is the first table + */ + + if ((cond && + !tab->keys.is_subset(tab->const_keys) && i > 0) || + (!tab->const_keys.is_clear_all() && i == join->const_tables && + join->unit->select_limit_cnt < + join->best_positions[i].records_read && + !(join->select_options & OPTION_FOUND_ROWS))) + { + /* Join with outer join condition */ + COND *orig_cond=sel->cond; + sel->cond= and_conds(sel->cond, *tab->on_expr_ref); + + /* + We can't call sel->cond->fix_fields, + as it will break tab->on_expr if it's AND condition + (fix_fields currently removes extra AND/OR levels). + Yet attributes of the just built condition are not needed. + Thus we call sel->cond->quick_fix_field for safety. + */ + if (sel->cond && !sel->cond->fixed) + sel->cond->quick_fix_field(); + + if (sel->test_quick_select(thd, tab->keys, + used_tables & ~ current_map, + (join->select_options & + OPTION_FOUND_ROWS ? + HA_POS_ERROR : + join->unit->select_limit_cnt), 0) < 0) + { + /* + Before reporting "Impossible WHERE" for the whole query + we have to check isn't it only "impossible ON" instead + */ + sel->cond=orig_cond; + if (!*tab->on_expr_ref || + sel->test_quick_select(thd, tab->keys, + used_tables & ~ current_map, + (join->select_options & + OPTION_FOUND_ROWS ? + HA_POS_ERROR : + join->unit->select_limit_cnt),0) < 0) + DBUG_RETURN(1); // Impossible WHERE + } + else + sel->cond=orig_cond; + + /* Fix for EXPLAIN */ + if (sel->quick) + join->best_positions[i].records_read= (double)sel->quick->records; + } + else + { + sel->needed_reg=tab->needed_reg; + sel->quick_keys.clear_all(); + } + if (!sel->quick_keys.is_subset(tab->checked_keys) || + !sel->needed_reg.is_subset(tab->checked_keys)) + { + tab->keys=sel->quick_keys; + tab->keys.merge(sel->needed_reg); + tab->use_quick= (!sel->needed_reg.is_clear_all() && + (select->quick_keys.is_clear_all() || + (select->quick && + (select->quick->records >= 100L)))) ? + 2 : 1; + sel->read_tables= used_tables & ~current_map; + } + if (i != join->const_tables && tab->use_quick != 2) + { /* Read with cache */ + if (cond && + (tmp=make_cond_for_table(cond, + join->const_table_map | + current_map, + current_map))) + { + DBUG_EXECUTE("where",print_where(tmp,"cache", QT_ORDINARY);); + tab->cache.select=(SQL_SELECT*) + thd->memdup((uchar*) sel, sizeof(SQL_SELECT)); + tab->cache.select->cond=tmp; + tab->cache.select->read_tables=join->const_table_map; + } + } + } + } + + /* + Push down conditions from all on expressions. + Each of these conditions are guarded by a variable + that turns if off just before null complemented row for + outer joins is formed. Thus, the condition from an + 'on expression' are guaranteed not to be checked for + the null complemented row. + */ + + /* First push down constant conditions from on expressions */ + for (JOIN_TAB *join_tab= join->join_tab+join->const_tables; + join_tab < join->join_tab+join->tables ; join_tab++) + { + if (*join_tab->on_expr_ref) + { + JOIN_TAB *cond_tab= join_tab->first_inner; + COND *tmp= make_cond_for_table(*join_tab->on_expr_ref, + join->const_table_map, + (table_map) 0); + if (!tmp) + continue; + tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl); + if (!tmp) + DBUG_RETURN(1); + tmp->quick_fix_field(); + cond_tab->select_cond= !cond_tab->select_cond ? tmp : + new Item_cond_and(cond_tab->select_cond,tmp); + if (!cond_tab->select_cond) + DBUG_RETURN(1); + cond_tab->select_cond->quick_fix_field(); + } + } + + /* Push down non-constant conditions from on expressions */ + JOIN_TAB *last_tab= tab; + while (first_inner_tab && first_inner_tab->last_inner == last_tab) + { + /* + Table tab is the last inner table of an outer join. + An on expression is always attached to it. + */ + COND *on_expr= *first_inner_tab->on_expr_ref; + + table_map used_tables2= (join->const_table_map | + OUTER_REF_TABLE_BIT | RAND_TABLE_BIT); + for (tab= join->join_tab+join->const_tables; tab <= last_tab ; tab++) + { + current_map= tab->table->map; + used_tables2|= current_map; + if (!on_expr) continue; + COND *tmp_cond= make_cond_for_table(on_expr, used_tables2, + current_map); + if (tmp_cond) + { + JOIN_TAB *cond_tab= tab < first_inner_tab ? first_inner_tab : tab; + /* + First add the guards for match variables of + all embedding outer join operations. + */ + if (!(tmp_cond= add_found_match_trig_cond(cond_tab->first_inner, + tmp_cond, + first_inner_tab))) + DBUG_RETURN(1); + /* + Now add the guard turning the predicate off for + the null complemented row. + */ + DBUG_PRINT("info", ("Item_func_trig_cond")); + tmp_cond= new Item_func_trig_cond(tmp_cond, + &first_inner_tab-> + not_null_compl); + DBUG_PRINT("info", ("Item_func_trig_cond 0x%lx", + (ulong) tmp_cond)); + if (tmp_cond) + tmp_cond->quick_fix_field(); + /* Add the predicate to other pushed down predicates */ + DBUG_PRINT("info", ("Item_cond_and")); + cond_tab->select_cond= !cond_tab->select_cond ? tmp_cond : + new Item_cond_and(cond_tab->select_cond, + tmp_cond); + DBUG_PRINT("info", ("Item_cond_and 0x%lx", + (ulong)cond_tab->select_cond)); + if (!cond_tab->select_cond) + DBUG_RETURN(1); + cond_tab->select_cond->quick_fix_field(); + } + } + first_inner_tab= first_inner_tab->first_upper; + } + } + } + DBUG_RETURN(0); +} + +static void +make_join_readinfo(JOIN *join, ulonglong options) +{ + uint i; + bool statistics= test(!(join->select_options & SELECT_DESCRIBE)); + bool ordered_set= 0; + bool sorted= 1; + DBUG_ENTER("make_join_readinfo"); + + for (i=join->const_tables ; i < join->tables ; i++) + { + JOIN_TAB *tab=join->join_tab+i; + TABLE *table=tab->table; + tab->read_record.table= table; + tab->read_record.file=table->file; + tab->next_select=sub_select; /* normal select */ + + /* + Determine if the set is already ordered for ORDER BY, so it can + disable join cache because it will change the ordering of the results. + Code handles sort table that is at any location (not only first after + the const tables) despite the fact that it's currently prohibited. + We must disable join cache if the first non-const table alone is + ordered. If there is a temp table the ordering is done as a last + operation and doesn't prevent join cache usage. + */ + if (!ordered_set && !join->need_tmp && + (table == join->sort_by_table || + (join->sort_by_table == (TABLE *) 1 && i != join->const_tables))) + ordered_set= 1; + + tab->sorted= sorted; + sorted= 0; // only first must be sorted + switch (tab->type) { + case JT_SYSTEM: // Only happens with left join + table->status=STATUS_NO_RECORD; + tab->read_first_record= join_read_system; + tab->read_record.read_record= join_no_more_records; + break; + case JT_CONST: // Only happens with left join + table->status=STATUS_NO_RECORD; + tab->read_first_record= join_read_const; + tab->read_record.read_record= join_no_more_records; + if (table->covering_keys.is_set(tab->ref.key) && + !table->no_keyread) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + break; + case JT_EQ_REF: + table->status=STATUS_NO_RECORD; + if (tab->select) + { + delete tab->select->quick; + tab->select->quick=0; + } + delete tab->quick; + tab->quick=0; + tab->read_first_record= join_read_key; + tab->read_record.read_record= join_no_more_records; + if (table->covering_keys.is_set(tab->ref.key) && + !table->no_keyread) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + break; + case JT_REF_OR_NULL: + case JT_REF: + table->status=STATUS_NO_RECORD; + if (tab->select) + { + delete tab->select->quick; + tab->select->quick=0; + } + delete tab->quick; + tab->quick=0; + if (table->covering_keys.is_set(tab->ref.key) && + !table->no_keyread) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + if (tab->type == JT_REF) + { + tab->read_first_record= join_read_always_key; + tab->read_record.read_record= join_read_next_same; + } + else + { + tab->read_first_record= join_read_always_key_or_null; + tab->read_record.read_record= join_read_next_same_or_null; + } + break; + case JT_FT: + table->status=STATUS_NO_RECORD; + tab->read_first_record= join_ft_read_first; + tab->read_record.read_record= join_ft_read_next; + break; + case JT_ALL: + /* + If previous table use cache + If the incoming data set is already sorted don't use cache. + */ + table->status=STATUS_NO_RECORD; + if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) && + tab->use_quick != 2 && !tab->first_inner && !ordered_set) + { + if ((options & SELECT_DESCRIBE) || + !join_init_cache(join->thd,join->join_tab+join->const_tables, + i-join->const_tables)) + { + tab[-1].next_select=sub_select_cache; /* Patch previous */ + } + } + /* These init changes read_record */ + if (tab->use_quick == 2) + { + join->thd->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED; + tab->read_first_record= join_init_quick_read_record; + if (statistics) + status_var_increment(join->thd->status_var.select_range_check_count); + } + else + { + tab->read_first_record= join_init_read_record; + if (i == join->const_tables) + { + if (tab->select && tab->select->quick) + { + if (statistics) + status_var_increment(join->thd->status_var.select_range_count); + } + else + { + join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED; + if (statistics) + status_var_increment(join->thd->status_var.select_scan_count); + } + } + else + { + if (tab->select && tab->select->quick) + { + if (statistics) + status_var_increment(join->thd->status_var.select_full_range_join_count); + } + else + { + join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED; + if (statistics) + status_var_increment(join->thd->status_var.select_full_join_count); + } + } + if (!table->no_keyread) + { + if (tab->select && tab->select->quick && + tab->select->quick->index != MAX_KEY && //not index_merge + table->covering_keys.is_set(tab->select->quick->index)) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + else if (!table->covering_keys.is_clear_all() && + !(tab->select && tab->select->quick)) + { // Only read index tree + /* + It has turned out that the below change, while speeding things + up for disk-bound loads, slows them down for cases when the data + is in disk cache (see BUG#35850): + // See bug #26447: "Using the clustered index for a table scan + // is always faster than using a secondary index". + if (table->s->primary_key != MAX_KEY && + table->file->primary_key_is_clustered()) + tab->index= table->s->primary_key; + else + */ + tab->index=find_shortest_key(table, & table->covering_keys); + tab->read_first_record= join_read_first; + tab->type=JT_NEXT; // Read with index_first / index_next + } + } + } + break; + default: + DBUG_PRINT("error",("Table type %d found",tab->type)); /* purecov: deadcode */ + break; /* purecov: deadcode */ + case JT_UNKNOWN: + case JT_MAYBE_REF: + abort(); /* purecov: deadcode */ + } + } + join->join_tab[join->tables-1].next_select=0; /* Set by do_select */ + DBUG_VOID_RETURN; +} + + +/** + Give error if we some tables are done with a full join. + + This is used by multi_table_update and multi_table_delete when running + in safe mode. + + @param join Join condition + + @retval + 0 ok + @retval + 1 Error (full join used) +*/ + +bool error_if_full_join(JOIN *join) +{ + for (JOIN_TAB *tab=join->join_tab, *end=join->join_tab+join->tables; + tab < end; + tab++) + { + if (tab->type == JT_ALL && (!tab->select || !tab->select->quick)) + { + my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE, + ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0)); + return(1); + } + } + return(0); +} + + +/** + cleanup JOIN_TAB. +*/ + +void JOIN_TAB::cleanup() +{ + delete select; + select= 0; + delete quick; + quick= 0; + x_free(cache.buff); + cache.buff= 0; + limit= 0; + if (table) + { + if (table->key_read) + { + table->key_read= 0; + table->file->extra(HA_EXTRA_NO_KEYREAD); + } + table->file->ha_index_or_rnd_end(); + /* + We need to reset this for next select + (Tested in part_of_refkey) + */ + table->reginfo.join_tab= 0; + } + end_read_record(&read_record); +} + + +/** + Partially cleanup JOIN after it has executed: close index or rnd read + (table cursors), free quick selects. + + This function is called in the end of execution of a JOIN, before the used + tables are unlocked and closed. + + For a join that is resolved using a temporary table, the first sweep is + performed against actual tables and an intermediate result is inserted + into the temprorary table. + The last sweep is performed against the temporary table. Therefore, + the base tables and associated buffers used to fill the temporary table + are no longer needed, and this function is called to free them. + + For a join that is performed without a temporary table, this function + is called after all rows are sent, but before EOF packet is sent. + + For a simple SELECT with no subqueries this function performs a full + cleanup of the JOIN and calls mysql_unlock_read_tables to free used base + tables. + + If a JOIN is executed for a subquery or if it has a subquery, we can't + do the full cleanup and need to do a partial cleanup only. + - If a JOIN is not the top level join, we must not unlock the tables + because the outer select may not have been evaluated yet, and we + can't unlock only selected tables of a query. + - Additionally, if this JOIN corresponds to a correlated subquery, we + should not free quick selects and join buffers because they will be + needed for the next execution of the correlated subquery. + - However, if this is a JOIN for a [sub]select, which is not + a correlated subquery itself, but has subqueries, we can free it + fully and also free JOINs of all its subqueries. The exception + is a subquery in SELECT list, e.g: @n + SELECT a, (select max(b) from t1) group by c @n + This subquery will not be evaluated at first sweep and its value will + not be inserted into the temporary table. Instead, it's evaluated + when selecting from the temporary table. Therefore, it can't be freed + here even though it's not correlated. + + @todo + Unlock tables even if the join isn't top level select in the tree +*/ + +void JOIN::join_free() +{ + SELECT_LEX_UNIT *tmp_unit; + SELECT_LEX *sl; + /* + Optimization: if not EXPLAIN and we are done with the JOIN, + free all tables. + */ + bool full= (!select_lex->uncacheable && !thd->lex->describe); + bool can_unlock= full; + DBUG_ENTER("JOIN::join_free"); + + cleanup(full); + + for (tmp_unit= select_lex->first_inner_unit(); + tmp_unit; + tmp_unit= tmp_unit->next_unit()) + for (sl= tmp_unit->first_select(); sl; sl= sl->next_select()) + { + Item_subselect *subselect= sl->master_unit()->item; + bool full_local= full && (!subselect || subselect->is_evaluated()); + /* + If this join is evaluated, we can fully clean it up and clean up all + its underlying joins even if they are correlated -- they will not be + used any more anyway. + If this join is not yet evaluated, we still must clean it up to + close its table cursors -- it may never get evaluated, as in case of + ... HAVING FALSE OR a IN (SELECT ...)) + but all table cursors must be closed before the unlock. + */ + sl->cleanup_all_joins(full_local); + /* Can't unlock if at least one JOIN is still needed */ + can_unlock= can_unlock && full_local; + } + + /* + We are not using tables anymore + Unlock all tables. We may be in an INSERT .... SELECT statement. + */ + if (can_unlock && lock && thd->lock && + !(select_options & SELECT_NO_UNLOCK) && + !select_lex->subquery_in_having && + (select_lex == (thd->lex->unit.fake_select_lex ? + thd->lex->unit.fake_select_lex : &thd->lex->select_lex))) + { + /* + TODO: unlock tables even if the join isn't top level select in the + tree. + */ + mysql_unlock_read_tables(thd, lock); // Don't free join->lock + lock= 0; + } + + DBUG_VOID_RETURN; +} + + +/** + Free resources of given join. + + @param fill true if we should free all resources, call with full==1 + should be last, before it this function can be called with + full==0 + + @note + With subquery this function definitely will be called several times, + but even for simple query it can be called several times. +*/ + +void JOIN::cleanup(bool full) +{ + DBUG_ENTER("JOIN::cleanup"); + + if (table) + { + JOIN_TAB *tab,*end; + /* + Only a sorted table may be cached. This sorted table is always the + first non const table in join->table + */ + if (tables > const_tables) // Test for not-const tables + { + free_io_cache(table[const_tables]); + filesort_free_buffers(table[const_tables],full); + } + + if (full) + { + for (tab= join_tab, end= tab+tables; tab != end; tab++) + tab->cleanup(); + table= 0; + } + else + { + for (tab= join_tab, end= tab+tables; tab != end; tab++) + { + if (tab->table) + tab->table->file->ha_index_or_rnd_end(); + } + } + } + /* + We are not using tables anymore + Unlock all tables. We may be in an INSERT .... SELECT statement. + */ + if (full) + { + if (tmp_join) + tmp_table_param.copy_field= 0; + group_fields.delete_elements(); + /* + Ensure that the above delete_elements() would not be called + twice for the same list. + */ + if (tmp_join && tmp_join != this) + tmp_join->group_fields= group_fields; + /* + We can't call delete_elements() on copy_funcs as this will cause + problems in free_elements() as some of the elements are then deleted. + */ + tmp_table_param.copy_funcs.empty(); + /* + If we have tmp_join and 'this' JOIN is not tmp_join and + tmp_table_param.copy_field's of them are equal then we have to remove + pointer to tmp_table_param.copy_field from tmp_join, because it qill + be removed in tmp_table_param.cleanup(). + */ + if (tmp_join && + tmp_join != this && + tmp_join->tmp_table_param.copy_field == + tmp_table_param.copy_field) + { + tmp_join->tmp_table_param.copy_field= + tmp_join->tmp_table_param.save_copy_field= 0; + } + tmp_table_param.cleanup(); + } + DBUG_VOID_RETURN; +} + + +/** + Remove the following expressions from ORDER BY and GROUP BY: + Constant expressions @n + Expression that only uses tables that are of type EQ_REF and the reference + is in the ORDER list or if all refereed tables are of the above type. + + In the following, the X field can be removed: + @code + SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X + SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X + @endcode + + These can't be optimized: + @code + SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a + SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c + SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a + @endcode +*/ + +static bool +eq_ref_table(JOIN *join, ORDER *start_order, JOIN_TAB *tab) +{ + if (tab->cached_eq_ref_table) // If cached + return tab->eq_ref_table; + tab->cached_eq_ref_table=1; + /* We can skip const tables only if not an outer table */ + if (tab->type == JT_CONST && !tab->first_inner) + return (tab->eq_ref_table=1); /* purecov: inspected */ + if (tab->type != JT_EQ_REF || tab->table->maybe_null) + return (tab->eq_ref_table=0); // We must use this + Item **ref_item=tab->ref.items; + Item **end=ref_item+tab->ref.key_parts; + uint found=0; + table_map map=tab->table->map; + + for (; ref_item != end ; ref_item++) + { + if (! (*ref_item)->const_item()) + { // Not a const ref + ORDER *order; + for (order=start_order ; order ; order=order->next) + { + if ((*ref_item)->eq(order->item[0],0)) + break; + } + if (order) + { + found++; + DBUG_ASSERT(!(order->used & map)); + order->used|=map; + continue; // Used in ORDER BY + } + if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables())) + return (tab->eq_ref_table=0); + } + } + /* Check that there was no reference to table before sort order */ + for (; found && start_order ; start_order=start_order->next) + { + if (start_order->used & map) + { + found--; + continue; + } + if (start_order->depend_map & map) + return (tab->eq_ref_table=0); + } + return tab->eq_ref_table=1; +} + + +static bool +only_eq_ref_tables(JOIN *join,ORDER *order,table_map tables) +{ + if (specialflag & SPECIAL_SAFE_MODE) + return 0; // skip this optimize /* purecov: inspected */ + tables&= ~PSEUDO_TABLE_BITS; + for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1) + { + if (tables & 1 && !eq_ref_table(join, order, *tab)) + return 0; + } + return 1; +} + + +/** Update the dependency map for the tables. */ + +static void update_depend_map(JOIN *join) +{ + JOIN_TAB *join_tab=join->join_tab, *end=join_tab+join->tables; + + for (; join_tab != end ; join_tab++) + { + TABLE_REF *ref= &join_tab->ref; + table_map depend_map=0; + Item **item=ref->items; + uint i; + for (i=0 ; i < ref->key_parts ; i++,item++) + depend_map|=(*item)->used_tables(); + ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT; + depend_map&= ~OUTER_REF_TABLE_BIT; + for (JOIN_TAB **tab=join->map2table; + depend_map ; + tab++,depend_map>>=1 ) + { + if (depend_map & 1) + ref->depend_map|=(*tab)->ref.depend_map; + } + } +} + + +/** Update the dependency map for the sort order. */ + +static void update_depend_map(JOIN *join, ORDER *order) +{ + for (; order ; order=order->next) + { + table_map depend_map; + order->item[0]->update_used_tables(); + order->depend_map=depend_map=order->item[0]->used_tables(); + // Not item_sum(), RAND() and no reference to table outside of sub select + if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT)) + && !order->item[0]->with_sum_func) + { + for (JOIN_TAB **tab=join->map2table; + depend_map ; + tab++, depend_map>>=1) + { + if (depend_map & 1) + order->depend_map|=(*tab)->ref.depend_map; + } + } + } +} + + +/** + Remove all constants and check if ORDER only contains simple + expressions. + + simple_order is set to 1 if sort_order only uses fields from head table + and the head table is not a LEFT JOIN table. + + @param join Join handler + @param first_order List of SORT or GROUP order + @param cond WHERE statement + @param change_list Set to 1 if we should remove things from list. + If this is not set, then only simple_order is + calculated. + @param simple_order Set to 1 if we are only using simple expressions + + @return + Returns new sort order +*/ + +static ORDER * +remove_const(JOIN *join,ORDER *first_order, COND *cond, + bool change_list, bool *simple_order) +{ + if (join->tables == join->const_tables) + return change_list ? 0 : first_order; // No need to sort + + ORDER *order,**prev_ptr; + table_map first_table= join->join_tab[join->const_tables].table->map; + table_map not_const_tables= ~join->const_table_map; + table_map ref; + DBUG_ENTER("remove_const"); + + prev_ptr= &first_order; + *simple_order= *join->join_tab[join->const_tables].on_expr_ref ? 0 : 1; + + /* NOTE: A variable of not_const_tables ^ first_table; breaks gcc 2.7 */ + + update_depend_map(join, first_order); + for (order=first_order; order ; order=order->next) + { + table_map order_tables=order->item[0]->used_tables(); + if (order->item[0]->with_sum_func) + *simple_order=0; // Must do a temp table to sort + else if (!(order_tables & not_const_tables)) + { + if (order->item[0]->with_subselect) + order->item[0]->val_str(&order->item[0]->str_value); + DBUG_PRINT("info",("removing: %s", order->item[0]->full_name())); + continue; // skip const item + } + else + { + if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)) + *simple_order=0; + else + { + Item *comp_item=0; + if (cond && const_expression_in_where(cond,order->item[0], &comp_item)) + { + DBUG_PRINT("info",("removing: %s", order->item[0]->full_name())); + continue; + } + if ((ref=order_tables & (not_const_tables ^ first_table))) + { + if (!(order_tables & first_table) && + only_eq_ref_tables(join,first_order, ref)) + { + DBUG_PRINT("info",("removing: %s", order->item[0]->full_name())); + continue; + } + *simple_order=0; // Must do a temp table to sort + } + } + } + if (change_list) + *prev_ptr= order; // use this entry + prev_ptr= &order->next; + } + if (change_list) + *prev_ptr=0; + if (prev_ptr == &first_order) // Nothing to sort/group + *simple_order=1; + DBUG_PRINT("exit",("simple_order: %d",(int) *simple_order)); + DBUG_RETURN(first_order); +} + + +static int +return_zero_rows(JOIN *join, select_result *result,TABLE_LIST *tables, + List &fields, bool send_row, ulonglong select_options, + const char *info, Item *having) +{ + DBUG_ENTER("return_zero_rows"); + + if (select_options & SELECT_DESCRIBE) + { + select_describe(join, FALSE, FALSE, FALSE, info); + DBUG_RETURN(0); + } + + join->join_free(); + + if (send_row) + { + for (TABLE_LIST *table= tables; table; table= table->next_leaf) + mark_as_null_row(table->table); // All fields are NULL + if (having && having->val_int() == 0) + send_row=0; + } + if (!(result->send_fields(fields, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))) + { + bool send_error= FALSE; + if (send_row) + { + List_iterator_fast it(fields); + Item *item; + while ((item= it++)) + item->no_rows_in_result(); + send_error= result->send_data(fields); + } + if (!send_error) + result->send_eof(); // Should be safe + } + /* Update results for FOUND_ROWS */ + join->thd->limit_found_rows= join->thd->examined_row_count= 0; + DBUG_RETURN(0); +} + +/* + used only in JOIN::clear +*/ +static void clear_tables(JOIN *join) +{ + /* + must clear only the non-const tables, as const tables + are not re-calculated. + */ + for (uint i=join->const_tables ; i < join->tables ; i++) + mark_as_null_row(join->table[i]); // All fields are NULL +} + +/***************************************************************************** + Make som simple condition optimization: + If there is a test 'field = const' change all refs to 'field' to 'const' + Remove all dummy tests 'item = item', 'const op const'. + Remove all 'item is NULL', when item can never be null! + item->marker should be 0 for all items on entry + Return in cond_value FALSE if condition is impossible (1 = 2) +*****************************************************************************/ + +class COND_CMP :public ilink { +public: + static void *operator new(size_t size) + { + return (void*) sql_alloc((uint) size); + } + static void operator delete(void *ptr __attribute__((unused)), + size_t size __attribute__((unused))) + { TRASH(ptr, size); } + + Item *and_level; + Item_func *cmp_func; + COND_CMP(Item *a,Item_func *b) :and_level(a),cmp_func(b) {} +}; + +#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION +template class I_List; +template class I_List_iterator; +template class List; +template class List_iterator; +#endif + + +/** + Find the multiple equality predicate containing a field. + + The function retrieves the multiple equalities accessed through + the con_equal structure from current level and up looking for + an equality containing field. It stops retrieval as soon as the equality + is found and set up inherited_fl to TRUE if it's found on upper levels. + + @param cond_equal multiple equalities to search in + @param field field to look for + @param[out] inherited_fl set up to TRUE if multiple equality is found + on upper levels (not on current level of + cond_equal) + + @return + - Item_equal for the found multiple equality predicate if a success; + - NULL otherwise. +*/ + +Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, + bool *inherited_fl) +{ + Item_equal *item= 0; + bool in_upper_level= FALSE; + while (cond_equal) + { + List_iterator_fast li(cond_equal->current_level); + while ((item= li++)) + { + if (item->contains(field)) + goto finish; + } + in_upper_level= TRUE; + cond_equal= cond_equal->upper_levels; + } + in_upper_level= FALSE; +finish: + *inherited_fl= in_upper_level; + return item; +} + + +/** + Check whether an equality can be used to build multiple equalities. + + This function first checks whether the equality (left_item=right_item) + is a simple equality i.e. the one that equates a field with another field + or a constant (field=field_item or field=const_item). + If this is the case the function looks for a multiple equality + in the lists referenced directly or indirectly by cond_equal inferring + the given simple equality. If it doesn't find any, it builds a multiple + equality that covers the predicate, i.e. the predicate can be inferred + from this multiple equality. + The built multiple equality could be obtained in such a way: + create a binary multiple equality equivalent to the predicate, then + merge it, if possible, with one of old multiple equalities. + This guarantees that the set of multiple equalities covering equality + predicates will be minimal. + + EXAMPLE: + For the where condition + @code + WHERE a=b AND b=c AND + (b=2 OR f=e) + @endcode + the check_equality will be called for the following equality + predicates a=b, b=c, b=2 and f=e. + - For a=b it will be called with *cond_equal=(0,[]) and will transform + *cond_equal into (0,[Item_equal(a,b)]). + - For b=c it will be called with *cond_equal=(0,[Item_equal(a,b)]) + and will transform *cond_equal into CE=(0,[Item_equal(a,b,c)]). + - For b=2 it will be called with *cond_equal=(ptr(CE),[]) + and will transform *cond_equal into (ptr(CE),[Item_equal(2,a,b,c)]). + - For f=e it will be called with *cond_equal=(ptr(CE), []) + and will transform *cond_equal into (ptr(CE),[Item_equal(f,e)]). + + @note + Now only fields that have the same type definitions (verified by + the Field::eq_def method) are placed to the same multiple equalities. + Because of this some equality predicates are not eliminated and + can be used in the constant propagation procedure. + We could weeken the equlity test as soon as at least one of the + equal fields is to be equal to a constant. It would require a + more complicated implementation: we would have to store, in + general case, its own constant for each fields from the multiple + equality. But at the same time it would allow us to get rid + of constant propagation completely: it would be done by the call + to build_equal_items_for_cond. + + + The implementation does not follow exactly the above rules to + build a new multiple equality for the equality predicate. + If it processes the equality of the form field1=field2, it + looks for multiple equalities me1 containig field1 and me2 containing + field2. If only one of them is found the fuction expands it with + the lacking field. If multiple equalities for both fields are + found they are merged. If both searches fail a new multiple equality + containing just field1 and field2 is added to the existing + multiple equalities. + If the function processes the predicate of the form field1=const, + it looks for a multiple equality containing field1. If found, the + function checks the constant of the multiple equality. If the value + is unknown, it is setup to const. Otherwise the value is compared with + const and the evaluation of the equality predicate is performed. + When expanding/merging equality predicates from the upper levels + the function first copies them for the current level. It looks + acceptable, as this happens rarely. The implementation without + copying would be much more complicated. + + @param left_item left term of the quality to be checked + @param right_item right term of the equality to be checked + @param item equality item if the equality originates from a condition + predicate, 0 if the equality is the result of row + elimination + @param cond_equal multiple equalities that must hold together with the + equality + + @retval + TRUE if the predicate is a simple equality predicate to be used + for building multiple equalities + @retval + FALSE otherwise +*/ + +static bool check_simple_equality(Item *left_item, Item *right_item, + Item *item, COND_EQUAL *cond_equal) +{ + if (left_item->type() == Item::REF_ITEM && + ((Item_ref*)left_item)->ref_type() == Item_ref::VIEW_REF) + { + if (((Item_ref*)left_item)->depended_from) + return FALSE; + left_item= left_item->real_item(); + } + if (right_item->type() == Item::REF_ITEM && + ((Item_ref*)right_item)->ref_type() == Item_ref::VIEW_REF) + { + if (((Item_ref*)right_item)->depended_from) + return FALSE; + right_item= right_item->real_item(); + } + if (left_item->type() == Item::FIELD_ITEM && + right_item->type() == Item::FIELD_ITEM && + !((Item_field*)left_item)->depended_from && + !((Item_field*)right_item)->depended_from) + { + /* The predicate the form field1=field2 is processed */ + + Field *left_field= ((Item_field*) left_item)->field; + Field *right_field= ((Item_field*) right_item)->field; + + if (!left_field->eq_def(right_field)) + return FALSE; + + /* Search for multiple equalities containing field1 and/or field2 */ + bool left_copyfl, right_copyfl; + Item_equal *left_item_equal= + find_item_equal(cond_equal, left_field, &left_copyfl); + Item_equal *right_item_equal= + find_item_equal(cond_equal, right_field, &right_copyfl); + + /* As (NULL=NULL) != TRUE we can't just remove the predicate f=f */ + if (left_field->eq(right_field)) /* f = f */ + return (!(left_field->maybe_null() && !left_item_equal)); + + if (left_item_equal && left_item_equal == right_item_equal) + { + /* + The equality predicate is inference of one of the existing + multiple equalities, i.e the condition is already covered + by upper level equalities + */ + return TRUE; + } + + /* Copy the found multiple equalities at the current level if needed */ + if (left_copyfl) + { + /* left_item_equal of an upper level contains left_item */ + left_item_equal= new Item_equal(left_item_equal); + cond_equal->current_level.push_back(left_item_equal); + } + if (right_copyfl) + { + /* right_item_equal of an upper level contains right_item */ + right_item_equal= new Item_equal(right_item_equal); + cond_equal->current_level.push_back(right_item_equal); + } + + if (left_item_equal) + { + /* left item was found in the current or one of the upper levels */ + if (! right_item_equal) + left_item_equal->add((Item_field *) right_item); + else + { + /* Merge two multiple equalities forming a new one */ + left_item_equal->merge(right_item_equal); + /* Remove the merged multiple equality from the list */ + List_iterator li(cond_equal->current_level); + while ((li++) != right_item_equal) ; + li.remove(); + } + } + else + { + /* left item was not found neither the current nor in upper levels */ + if (right_item_equal) + right_item_equal->add((Item_field *) left_item); + else + { + /* None of the fields was found in multiple equalities */ + Item_equal *item_equal= new Item_equal((Item_field *) left_item, + (Item_field *) right_item); + cond_equal->current_level.push_back(item_equal); + } + } + return TRUE; + } + + { + /* The predicate of the form field=const/const=field is processed */ + Item *const_item= 0; + Item_field *field_item= 0; + if (left_item->type() == Item::FIELD_ITEM && + !((Item_field*)left_item)->depended_from && + right_item->const_item()) + { + field_item= (Item_field*) left_item; + const_item= right_item; + } + else if (right_item->type() == Item::FIELD_ITEM && + !((Item_field*)right_item)->depended_from && + left_item->const_item()) + { + field_item= (Item_field*) right_item; + const_item= left_item; + } + + if (const_item && + field_item->result_type() == const_item->result_type()) + { + bool copyfl; + + if (field_item->result_type() == STRING_RESULT) + { + CHARSET_INFO *cs= ((Field_str*) field_item->field)->charset(); + if (!item) + { + Item_func_eq *eq_item; + if ((eq_item= new Item_func_eq(left_item, right_item))) + return FALSE; + eq_item->set_cmp_func(); + eq_item->quick_fix_field(); + item= eq_item; + } + if ((cs != ((Item_func *) item)->compare_collation()) || + !cs->coll->propagate(cs, 0, 0)) + return FALSE; + } + + Item_equal *item_equal = find_item_equal(cond_equal, + field_item->field, ©fl); + if (copyfl) + { + item_equal= new Item_equal(item_equal); + cond_equal->current_level.push_back(item_equal); + } + if (item_equal) + { + /* + The flag cond_false will be set to 1 after this, if item_equal + already contains a constant and its value is not equal to + the value of const_item. + */ + item_equal->add(const_item); + } + else + { + item_equal= new Item_equal(const_item, field_item); + cond_equal->current_level.push_back(item_equal); + } + return TRUE; + } + } + return FALSE; +} + + +/** + Convert row equalities into a conjunction of regular equalities. + + The function converts a row equality of the form (E1,...,En)=(E'1,...,E'n) + into a list of equalities E1=E'1,...,En=E'n. For each of these equalities + Ei=E'i the function checks whether it is a simple equality or a row + equality. If it is a simple equality it is used to expand multiple + equalities of cond_equal. If it is a row equality it converted to a + sequence of equalities between row elements. If Ei=E'i is neither a + simple equality nor a row equality the item for this predicate is added + to eq_list. + + @param thd thread handle + @param left_row left term of the row equality to be processed + @param right_row right term of the row equality to be processed + @param cond_equal multiple equalities that must hold together with the + predicate + @param eq_list results of conversions of row equalities that are not + simple enough to form multiple equalities + + @retval + TRUE if conversion has succeeded (no fatal error) + @retval + FALSE otherwise +*/ + +static bool check_row_equality(THD *thd, Item *left_row, Item_row *right_row, + COND_EQUAL *cond_equal, List* eq_list) +{ + uint n= left_row->cols(); + for (uint i= 0 ; i < n; i++) + { + bool is_converted; + Item *left_item= left_row->element_index(i); + Item *right_item= right_row->element_index(i); + if (left_item->type() == Item::ROW_ITEM && + right_item->type() == Item::ROW_ITEM) + { + is_converted= check_row_equality(thd, + (Item_row *) left_item, + (Item_row *) right_item, + cond_equal, eq_list); + if (!is_converted) + thd->lex->current_select->cond_count++; + } + else + { + is_converted= check_simple_equality(left_item, right_item, 0, cond_equal); + thd->lex->current_select->cond_count++; + } + + if (!is_converted) + { + Item_func_eq *eq_item; + if (!(eq_item= new Item_func_eq(left_item, right_item))) + return FALSE; + eq_item->set_cmp_func(); + eq_item->quick_fix_field(); + eq_list->push_back(eq_item); + } + } + return TRUE; +} + + +/** + Eliminate row equalities and form multiple equalities predicates. + + This function checks whether the item is a simple equality + i.e. the one that equates a field with another field or a constant + (field=field_item or field=constant_item), or, a row equality. + For a simple equality the function looks for a multiple equality + in the lists referenced directly or indirectly by cond_equal inferring + the given simple equality. If it doesn't find any, it builds/expands + multiple equality that covers the predicate. + Row equalities are eliminated substituted for conjunctive regular + equalities which are treated in the same way as original equality + predicates. + + @param thd thread handle + @param item predicate to process + @param cond_equal multiple equalities that must hold together with the + predicate + @param eq_list results of conversions of row equalities that are not + simple enough to form multiple equalities + + @retval + TRUE if re-writing rules have been applied + @retval + FALSE otherwise, i.e. + if the predicate is not an equality, + or, if the equality is neither a simple one nor a row equality, + or, if the procedure fails by a fatal error. +*/ + +static bool check_equality(THD *thd, Item *item, COND_EQUAL *cond_equal, + List *eq_list) +{ + if (item->type() == Item::FUNC_ITEM && + ((Item_func*) item)->functype() == Item_func::EQ_FUNC) + { + Item *left_item= ((Item_func*) item)->arguments()[0]; + Item *right_item= ((Item_func*) item)->arguments()[1]; + + if (left_item->type() == Item::ROW_ITEM && + right_item->type() == Item::ROW_ITEM) + { + thd->lex->current_select->cond_count--; + return check_row_equality(thd, + (Item_row *) left_item, + (Item_row *) right_item, + cond_equal, eq_list); + } + else + return check_simple_equality(left_item, right_item, item, cond_equal); + } + return FALSE; +} + + +/** + Replace all equality predicates in a condition by multiple equality items. + + At each 'and' level the function detects items for equality predicates + and replaced them by a set of multiple equality items of class Item_equal, + taking into account inherited equalities from upper levels. + If an equality predicate is used not in a conjunction it's just + replaced by a multiple equality predicate. + For each 'and' level the function set a pointer to the inherited + multiple equalities in the cond_equal field of the associated + object of the type Item_cond_and. + The function also traverses the cond tree and and for each field reference + sets a pointer to the multiple equality item containing the field, if there + is any. If this multiple equality equates fields to a constant the + function replaces the field reference by the constant in the cases + when the field is not of a string type or when the field reference is + just an argument of a comparison predicate. + The function also determines the maximum number of members in + equality lists of each Item_cond_and object assigning it to + thd->lex->current_select->max_equal_elems. + + @note + Multiple equality predicate =(f1,..fn) is equivalent to the conjuction of + f1=f2, .., fn-1=fn. It substitutes any inference from these + equality predicates that is equivalent to the conjunction. + Thus, =(a1,a2,a3) can substitute for ((a1=a3) AND (a2=a3) AND (a2=a1)) as + it is equivalent to ((a1=a2) AND (a2=a3)). + The function always makes a substitution of all equality predicates occured + in a conjuction for a minimal set of multiple equality predicates. + This set can be considered as a canonical representation of the + sub-conjunction of the equality predicates. + E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by + (=(t1.a,t2.b,t3.c) AND t2.b>5), not by + (=(t1.a,t2.b) AND =(t1.a,t3.c) AND t2.b>5); + while (t1.a=t2.b AND t2.b>5 AND t3.c=t4.d) is replaced by + (=(t1.a,t2.b) AND =(t3.c=t4.d) AND t2.b>5), + but if additionally =(t4.d,t2.b) is inherited, it + will be replaced by (=(t1.a,t2.b,t3.c,t4.d) AND t2.b>5) + + The function performs the substitution in a recursive descent by + the condtion tree, passing to the next AND level a chain of multiple + equality predicates which have been built at the upper levels. + The Item_equal items built at the level are attached to other + non-equality conjucts as a sublist. The pointer to the inherited + multiple equalities is saved in the and condition object (Item_cond_and). + This chain allows us for any field reference occurence easyly to find a + multiple equality that must be held for this occurence. + For each AND level we do the following: + - scan it for all equality predicate (=) items + - join them into disjoint Item_equal() groups + - process the included OR conditions recursively to do the same for + lower AND levels. + + We need to do things in this order as lower AND levels need to know about + all possible Item_equal objects in upper levels. + + @param thd thread handle + @param cond condition(expression) where to make replacement + @param inherited path to all inherited multiple equality items + + @return + pointer to the transformed condition +*/ + +static COND *build_equal_items_for_cond(THD *thd, COND *cond, + COND_EQUAL *inherited) +{ + Item_equal *item_equal; + COND_EQUAL cond_equal; + cond_equal.upper_levels= inherited; + + if (cond->type() == Item::COND_ITEM) + { + List eq_list; + bool and_level= ((Item_cond*) cond)->functype() == + Item_func::COND_AND_FUNC; + List *args= ((Item_cond*) cond)->argument_list(); + + List_iterator li(*args); + Item *item; + + if (and_level) + { + /* + Retrieve all conjuncts of this level detecting the equality + that are subject to substitution by multiple equality items and + removing each such predicate from the conjunction after having + found/created a multiple equality whose inference the predicate is. + */ + while ((item= li++)) + { + /* + PS/SP note: we can safely remove a node from AND-OR + structure here because it's restored before each + re-execution of any prepared statement/stored procedure. + */ + if (check_equality(thd, item, &cond_equal, &eq_list)) + li.remove(); + } + + /* + Check if we eliminated all the predicates of the level, e.g. + (a=a AND b=b AND a=a). + */ + if (!args->elements && + !cond_equal.current_level.elements && + !eq_list.elements) + return new Item_int((longlong) 1, 1); + + List_iterator_fast it(cond_equal.current_level); + while ((item_equal= it++)) + { + item_equal->fix_length_and_dec(); + item_equal->update_used_tables(); + set_if_bigger(thd->lex->current_select->max_equal_elems, + item_equal->members()); + } + + ((Item_cond_and*)cond)->cond_equal= cond_equal; + inherited= &(((Item_cond_and*)cond)->cond_equal); + } + /* + Make replacement of equality predicates for lower levels + of the condition expression. + */ + li.rewind(); + while ((item= li++)) + { + Item *new_item; + if ((new_item= build_equal_items_for_cond(thd, item, inherited)) != item) + { + /* This replacement happens only for standalone equalities */ + /* + This is ok with PS/SP as the replacement is done for + arguments of an AND/OR item, which are restored for each + execution of PS/SP. + */ + li.replace(new_item); + } + } + if (and_level) + { + args->concat(&eq_list); + args->concat((List *)&cond_equal.current_level); + } + } + else if (cond->type() == Item::FUNC_ITEM) + { + List eq_list; + /* + If an equality predicate forms the whole and level, + we call it standalone equality and it's processed here. + E.g. in the following where condition + WHERE a=5 AND (b=5 or a=c) + (b=5) and (a=c) are standalone equalities. + In general we can't leave alone standalone eqalities: + for WHERE a=b AND c=d AND (b=c OR d=5) + b=c is replaced by =(a,b,c,d). + */ + if (check_equality(thd, cond, &cond_equal, &eq_list)) + { + int n= cond_equal.current_level.elements + eq_list.elements; + if (n == 0) + return new Item_int((longlong) 1,1); + else if (n == 1) + { + if ((item_equal= cond_equal.current_level.pop())) + { + item_equal->fix_length_and_dec(); + item_equal->update_used_tables(); + } + else + item_equal= (Item_equal *) eq_list.pop(); + set_if_bigger(thd->lex->current_select->max_equal_elems, + item_equal->members()); + return item_equal; + } + else + { + /* + Here a new AND level must be created. It can happen only + when a row equality is processed as a standalone predicate. + */ + Item_cond_and *and_cond= new Item_cond_and(eq_list); + and_cond->quick_fix_field(); + List *args= and_cond->argument_list(); + List_iterator_fast it(cond_equal.current_level); + while ((item_equal= it++)) + { + item_equal->fix_length_and_dec(); + item_equal->update_used_tables(); + set_if_bigger(thd->lex->current_select->max_equal_elems, + item_equal->members()); + } + and_cond->cond_equal= cond_equal; + args->concat((List *)&cond_equal.current_level); + + return and_cond; + } + } + /* + For each field reference in cond, not from equal item predicates, + set a pointer to the multiple equality it belongs to (if there is any) + as soon the field is not of a string type or the field reference is + an argument of a comparison predicate. + */ + uchar *is_subst_valid= (uchar *) 1; + cond= cond->compile(&Item::subst_argument_checker, + &is_subst_valid, + &Item::equal_fields_propagator, + (uchar *) inherited); + cond->update_used_tables(); + } + return cond; +} + + +/** + Build multiple equalities for a condition and all on expressions that + inherit these multiple equalities. + + The function first applies the build_equal_items_for_cond function + to build all multiple equalities for condition cond utilizing equalities + referred through the parameter inherited. The extended set of + equalities is returned in the structure referred by the cond_equal_ref + parameter. After this the function calls itself recursively for + all on expressions whose direct references can be found in join_list + and who inherit directly the multiple equalities just having built. + + @note + The on expression used in an outer join operation inherits all equalities + from the on expression of the embedding join, if there is any, or + otherwise - from the where condition. + This fact is not obvious, but presumably can be proved. + Consider the following query: + @code + SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t1.a=t3.a AND t2.a=t4.a + WHERE t1.a=t2.a; + @endcode + If the on expression in the query inherits =(t1.a,t2.a), then we + can build the multiple equality =(t1.a,t2.a,t3.a,t4.a) that infers + the equality t3.a=t4.a. Although the on expression + t1.a=t3.a AND t2.a=t4.a AND t3.a=t4.a is not equivalent to the one + in the query the latter can be replaced by the former: the new query + will return the same result set as the original one. + + Interesting that multiple equality =(t1.a,t2.a,t3.a,t4.a) allows us + to use t1.a=t3.a AND t3.a=t4.a under the on condition: + @code + SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t1.a=t3.a AND t3.a=t4.a + WHERE t1.a=t2.a + @endcode + This query equivalent to: + @code + SELECT * FROM (t1 LEFT JOIN (t3,t4) ON t1.a=t3.a AND t3.a=t4.a),t2 + WHERE t1.a=t2.a + @endcode + Similarly the original query can be rewritten to the query: + @code + SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t2.a=t4.a AND t3.a=t4.a + WHERE t1.a=t2.a + @endcode + that is equivalent to: + @code + SELECT * FROM (t2 LEFT JOIN (t3,t4)ON t2.a=t4.a AND t3.a=t4.a), t1 + WHERE t1.a=t2.a + @endcode + Thus, applying equalities from the where condition we basically + can get more freedom in performing join operations. + Althogh we don't use this property now, it probably makes sense to use + it in the future. + @param thd Thread handler + @param cond condition to build the multiple equalities for + @param inherited path to all inherited multiple equality items + @param join_list list of join tables to which the condition + refers to + @param[out] cond_equal_ref pointer to the structure to place built + equalities in + + @return + pointer to the transformed condition containing multiple equalities +*/ + +static COND *build_equal_items(THD *thd, COND *cond, + COND_EQUAL *inherited, + List *join_list, + COND_EQUAL **cond_equal_ref) +{ + COND_EQUAL *cond_equal= 0; + + if (cond) + { + cond= build_equal_items_for_cond(thd, cond, inherited); + cond->update_used_tables(); + if (cond->type() == Item::COND_ITEM && + ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) + cond_equal= &((Item_cond_and*) cond)->cond_equal; + else if (cond->type() == Item::FUNC_ITEM && + ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC) + { + cond_equal= new COND_EQUAL; + cond_equal->current_level.push_back((Item_equal *) cond); + } + } + if (cond_equal) + { + cond_equal->upper_levels= inherited; + inherited= cond_equal; + } + *cond_equal_ref= cond_equal; + + if (join_list) + { + TABLE_LIST *table; + List_iterator li(*join_list); + + while ((table= li++)) + { + if (table->on_expr) + { + List *nested_join_list= table->nested_join ? + &table->nested_join->join_list : NULL; + /* + We can modify table->on_expr because its old value will + be restored before re-execution of PS/SP. + */ + table->on_expr= build_equal_items(thd, table->on_expr, inherited, + nested_join_list, + &table->cond_equal); + } + } + } + + return cond; +} + + +/** + Compare field items by table order in the execution plan. + + field1 considered as better than field2 if the table containing + field1 is accessed earlier than the table containing field2. + The function finds out what of two fields is better according + this criteria. + + @param field1 first field item to compare + @param field2 second field item to compare + @param table_join_idx index to tables determining table order + + @retval + 1 if field1 is better than field2 + @retval + -1 if field2 is better than field1 + @retval + 0 otherwise +*/ + +static int compare_fields_by_table_order(Item_field *field1, + Item_field *field2, + void *table_join_idx) +{ + int cmp= 0; + bool outer_ref= 0; + if (field2->used_tables() & OUTER_REF_TABLE_BIT) + { + outer_ref= 1; + cmp= -1; + } + if (field2->used_tables() & OUTER_REF_TABLE_BIT) + { + outer_ref= 1; + cmp++; + } + if (outer_ref) + return cmp; + JOIN_TAB **idx= (JOIN_TAB **) table_join_idx; + cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr]; + return cmp < 0 ? -1 : (cmp ? 1 : 0); +} + + +/** + Generate minimal set of simple equalities equivalent to a multiple equality. + + The function retrieves the fields of the multiple equality item + item_equal and for each field f: + - if item_equal contains const it generates the equality f=const_item; + - otherwise, if f is not the first field, generates the equality + f=item_equal->get_first(). + All generated equality are added to the cond conjunction. + + @param cond condition to add the generated equality to + @param upper_levels structure to access multiple equality of upper levels + @param item_equal multiple equality to generate simple equality from + + @note + Before generating an equality function checks that it has not + been generated for multiple equalities of the upper levels. + E.g. for the following where condition + WHERE a=5 AND ((a=b AND b=c) OR c>4) + the upper level AND condition will contain =(5,a), + while the lower level AND condition will contain =(5,a,b,c). + When splitting =(5,a,b,c) into a separate equality predicates + we should omit 5=a, as we have it already in the upper level. + The following where condition gives us a more complicated case: + WHERE t1.a=t2.b AND t3.c=t4.d AND (t2.b=t3.c OR t4.e>5 ...) AND ... + Given the tables are accessed in the order t1->t2->t3->t4 for + the selected query execution plan the lower level multiple + equality =(t1.a,t2.b,t3.c,t4.d) formally should be converted to + t1.a=t2.b AND t1.a=t3.c AND t1.a=t4.d. But t1.a=t2.a will be + generated for the upper level. Also t3.c=t4.d will be generated there. + So only t1.a=t3.c should be left in the lower level. + If cond is equal to 0, then not more then one equality is generated + and a pointer to it is returned as the result of the function. + + @return + - The condition with generated simple equalities or + a pointer to the simple generated equality, if success. + - 0, otherwise. +*/ + +static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels, + Item_equal *item_equal) +{ + List eq_list; + Item_func_eq *eq_item= 0; + if (((Item *) item_equal)->const_item() && !item_equal->val_int()) + return new Item_int((longlong) 0,1); + Item *item_const= item_equal->get_const(); + Item_equal_iterator it(*item_equal); + Item *head; + if (item_const) + head= item_const; + else + { + head= item_equal->get_first(); + it++; + } + Item_field *item_field; + while ((item_field= it++)) + { + Item_equal *upper= item_field->find_item_equal(upper_levels); + Item_field *item= item_field; + if (upper) + { + if (item_const && upper->get_const()) + item= 0; + else + { + Item_equal_iterator li(*item_equal); + while ((item= li++) != item_field) + { + if (item->find_item_equal(upper_levels) == upper) + break; + } + } + } + if (item == item_field) + { + if (eq_item) + eq_list.push_back(eq_item); + eq_item= new Item_func_eq(item_field, head); + if (!eq_item) + return 0; + eq_item->set_cmp_func(); + eq_item->quick_fix_field(); + } + } + + if (!cond && !eq_list.head()) + { + if (!eq_item) + return new Item_int((longlong) 1,1); + return eq_item; + } + + if (eq_item) + eq_list.push_back(eq_item); + if (!cond) + cond= new Item_cond_and(eq_list); + else + { + DBUG_ASSERT(cond->type() == Item::COND_ITEM); + ((Item_cond *) cond)->add_at_head(&eq_list); + } + + cond->quick_fix_field(); + cond->update_used_tables(); + + return cond; +} + + +/** + Substitute every field reference in a condition by the best equal field + and eliminate all multiple equality predicates. + + The function retrieves the cond condition and for each encountered + multiple equality predicate it sorts the field references in it + according to the order of tables specified by the table_join_idx + parameter. Then it eliminates the multiple equality predicate it + replacing it by the conjunction of simple equality predicates + equating every field from the multiple equality to the first + field in it, or to the constant, if there is any. + After this the function retrieves all other conjuncted + predicates substitute every field reference by the field reference + to the first equal field or equal constant if there are any. + @param cond condition to process + @param cond_equal multiple equalities to take into consideration + @param table_join_idx index to tables determining field preference + + @note + At the first glance full sort of fields in multiple equality + seems to be an overkill. Yet it's not the case due to possible + new fields in multiple equality item of lower levels. We want + the order in them to comply with the order of upper levels. + + @return + The transformed condition +*/ + +static COND* substitute_for_best_equal_field(COND *cond, + COND_EQUAL *cond_equal, + void *table_join_idx) +{ + Item_equal *item_equal; + + if (cond->type() == Item::COND_ITEM) + { + List *cond_list= ((Item_cond*) cond)->argument_list(); + + bool and_level= ((Item_cond*) cond)->functype() == + Item_func::COND_AND_FUNC; + if (and_level) + { + cond_equal= &((Item_cond_and *) cond)->cond_equal; + cond_list->disjoin((List *) &cond_equal->current_level); + + List_iterator_fast it(cond_equal->current_level); + while ((item_equal= it++)) + { + item_equal->sort(&compare_fields_by_table_order, table_join_idx); + } + } + + List_iterator li(*cond_list); + Item *item; + while ((item= li++)) + { + Item *new_item =substitute_for_best_equal_field(item, cond_equal, + table_join_idx); + /* + This works OK with PS/SP re-execution as changes are made to + the arguments of AND/OR items only + */ + if (new_item != item) + li.replace(new_item); + } + + if (and_level) + { + List_iterator_fast it(cond_equal->current_level); + while ((item_equal= it++)) + { + cond= eliminate_item_equal(cond, cond_equal->upper_levels, item_equal); + // This occurs when eliminate_item_equal() founds that cond is + // always false and substitutes it with Item_int 0. + // Due to this, value of item_equal will be 0, so just return it. + if (cond->type() != Item::COND_ITEM) + break; + } + } + if (cond->type() == Item::COND_ITEM && + !((Item_cond*)cond)->argument_list()->elements) + cond= new Item_int((int32)cond->val_bool()); + + } + else if (cond->type() == Item::FUNC_ITEM && + ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC) + { + item_equal= (Item_equal *) cond; + item_equal->sort(&compare_fields_by_table_order, table_join_idx); + if (cond_equal && cond_equal->current_level.head() == item_equal) + cond_equal= 0; + return eliminate_item_equal(0, cond_equal, item_equal); + } + // Calpont InfiniDB skip MySQL optimzation for substitute_best_equal. @bug 1680. + else if (current_thd && current_thd->infinidb_vtable.vtable_state != THD::INFINIDB_CREATE_VTABLE) + cond->transform(&Item::replace_equal_field, 0); + return cond; +} + + +/** + Check appearance of new constant items in multiple equalities + of a condition after reading a constant table. + + The function retrieves the cond condition and for each encountered + multiple equality checks whether new constants have appeared after + reading the constant (single row) table tab. If so it adjusts + the multiple equality appropriately. + + @param cond condition whose multiple equalities are to be checked + @param table constant table that has been read +*/ + +static void update_const_equal_items(COND *cond, JOIN_TAB *tab) +{ + if (!(cond->used_tables() & tab->table->map)) + return; + + if (cond->type() == Item::COND_ITEM) + { + List *cond_list= ((Item_cond*) cond)->argument_list(); + List_iterator_fast li(*cond_list); + Item *item; + while ((item= li++)) + update_const_equal_items(item, tab); + } + else if (cond->type() == Item::FUNC_ITEM && + ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC) + { + Item_equal *item_equal= (Item_equal *) cond; + bool contained_const= item_equal->get_const() != NULL; + item_equal->update_const(); + if (!contained_const && item_equal->get_const()) + { + /* Update keys for range analysis */ + Item_equal_iterator it(*item_equal); + Item_field *item_field; + while ((item_field= it++)) + { + Field *field= item_field->field; + JOIN_TAB *stat= field->table->reginfo.join_tab; + key_map possible_keys= field->key_start; + possible_keys.intersect(field->table->keys_in_use_for_query); + stat[0].const_keys.merge(possible_keys); + + /* + For each field in the multiple equality (for which we know that it + is a constant) we have to find its corresponding key part, and set + that key part in const_key_parts. + */ + if (!possible_keys.is_clear_all()) + { + TABLE *tab= field->table; + KEYUSE *use; + for (use= stat->keyuse; use && use->table == tab; use++) + if (possible_keys.is_set(use->key) && + tab->key_info[use->key].key_part[use->keypart].field == + field) + tab->const_key_parts[use->key]|= use->keypart_map; + } + } + } + } +} + + +/* + change field = field to field = const for each found field = const in the + and_level +*/ + +static void +change_cond_ref_to_const(THD *thd, I_List *save_list, + Item *and_father, Item *cond, + Item *field, Item *value) +{ + if (cond->type() == Item::COND_ITEM) + { + bool and_level= ((Item_cond*) cond)->functype() == + Item_func::COND_AND_FUNC; + List_iterator li(*((Item_cond*) cond)->argument_list()); + Item *item; + while ((item=li++)) + change_cond_ref_to_const(thd, save_list,and_level ? cond : item, item, + field, value); + return; + } + if (cond->eq_cmp_result() == Item::COND_OK) + return; // Not a boolean function + + Item_bool_func2 *func= (Item_bool_func2*) cond; + Item **args= func->arguments(); + Item *left_item= args[0]; + Item *right_item= args[1]; + Item_func::Functype functype= func->functype(); + + if (right_item->eq(field,0) && left_item != value && + right_item->cmp_context == field->cmp_context && + (left_item->result_type() != STRING_RESULT || + value->result_type() != STRING_RESULT || + left_item->collation.collation == value->collation.collation)) + { + Item *tmp=value->clone_item(); + tmp->collation.set(right_item->collation); + + if (tmp) + { + thd->change_item_tree(args + 1, tmp); + func->update_used_tables(); + if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) + && and_father != cond && !left_item->const_item()) + { + cond->marker=1; + COND_CMP *tmp2; + if ((tmp2=new COND_CMP(and_father,func))) + save_list->push_back(tmp2); + } + func->set_cmp_func(); + } + } + else if (left_item->eq(field,0) && right_item != value && + left_item->cmp_context == field->cmp_context && + (right_item->result_type() != STRING_RESULT || + value->result_type() != STRING_RESULT || + right_item->collation.collation == value->collation.collation)) + { + Item *tmp= value->clone_item(); + tmp->collation.set(left_item->collation); + + if (tmp) + { + thd->change_item_tree(args, tmp); + value= tmp; + func->update_used_tables(); + if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) + && and_father != cond && !right_item->const_item()) + { + args[0]= args[1]; // For easy check + thd->change_item_tree(args + 1, value); + cond->marker=1; + COND_CMP *tmp2; + if ((tmp2=new COND_CMP(and_father,func))) + save_list->push_back(tmp2); + } + func->set_cmp_func(); + } + } +} + +/** + Remove additional condition inserted by IN/ALL/ANY transformation. + + @param conds condition for processing + + @return + new conditions +*/ + +static Item *remove_additional_cond(Item* conds) +{ + if (conds->name == in_additional_cond) + return 0; + if (conds->type() == Item::COND_ITEM) + { + Item_cond *cnd= (Item_cond*) conds; + List_iterator li(*(cnd->argument_list())); + Item *item; + while ((item= li++)) + { + if (item->name == in_additional_cond) + { + li.remove(); + if (cnd->argument_list()->elements == 1) + return cnd->argument_list()->head(); + return conds; + } + } + } + return conds; +} + +static void +propagate_cond_constants(THD *thd, I_List *save_list, + COND *and_father, COND *cond) +{ + if (cond->type() == Item::COND_ITEM) + { + bool and_level= ((Item_cond*) cond)->functype() == + Item_func::COND_AND_FUNC; + List_iterator_fast li(*((Item_cond*) cond)->argument_list()); + Item *item; + I_List save; + while ((item=li++)) + { + propagate_cond_constants(thd, &save,and_level ? cond : item, item); + } + if (and_level) + { // Handle other found items + I_List_iterator cond_itr(save); + COND_CMP *cond_cmp; + while ((cond_cmp=cond_itr++)) + { + Item **args= cond_cmp->cmp_func->arguments(); + if (!args[0]->const_item()) + change_cond_ref_to_const(thd, &save,cond_cmp->and_level, + cond_cmp->and_level, args[0], args[1]); + } + } + } + else if (and_father != cond && !cond->marker) // In a AND group + { + if (cond->type() == Item::FUNC_ITEM && + (((Item_func*) cond)->functype() == Item_func::EQ_FUNC || + ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)) + { + Item_func_eq *func=(Item_func_eq*) cond; + Item **args= func->arguments(); + bool left_const= args[0]->const_item(); + bool right_const= args[1]->const_item(); + if (!(left_const && right_const) && + args[0]->result_type() == args[1]->result_type()) + { + if (right_const) + { + resolve_const_item(thd, &args[1], args[0]); + func->update_used_tables(); + change_cond_ref_to_const(thd, save_list, and_father, and_father, + args[0], args[1]); + } + else if (left_const) + { + resolve_const_item(thd, &args[0], args[1]); + func->update_used_tables(); + change_cond_ref_to_const(thd, save_list, and_father, and_father, + args[1], args[0]); + } + } + } + } +} + + +/** + Simplify joins replacing outer joins by inner joins whenever it's + possible. + + The function, during a retrieval of join_list, eliminates those + outer joins that can be converted into inner join, possibly nested. + It also moves the on expressions for the converted outer joins + and from inner joins to conds. + The function also calculates some attributes for nested joins: + - used_tables + - not_null_tables + - dep_tables. + - on_expr_dep_tables + The first two attributes are used to test whether an outer join can + be substituted for an inner join. The third attribute represents the + relation 'to be dependent on' for tables. If table t2 is dependent + on table t1, then in any evaluated execution plan table access to + table t2 must precede access to table t2. This relation is used also + to check whether the query contains invalid cross-references. + The forth attribute is an auxiliary one and is used to calculate + dep_tables. + As the attribute dep_tables qualifies possibles orders of tables in the + execution plan, the dependencies required by the straight join + modifiers are reflected in this attribute as well. + The function also removes all braces that can be removed from the join + expression without changing its meaning. + + @note + An outer join can be replaced by an inner join if the where condition + or the on expression for an embedding nested join contains a conjunctive + predicate rejecting null values for some attribute of the inner tables. + + E.g. in the query: + @code + SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5 + @endcode + the predicate t2.b < 5 rejects nulls. + The query is converted first to: + @code + SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5 + @endcode + then to the equivalent form: + @code + SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a + @endcode + + + Similarly the following query: + @code + SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b + WHERE t2.c < 5 + @endcode + is converted to: + @code + SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b + + @endcode + + One conversion might trigger another: + @code + SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a + LEFT JOIN t3 ON t3.b=t2.b + WHERE t3 IS NOT NULL => + SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3 + WHERE t3 IS NOT NULL AND t3.b=t2.b => + SELECT * FROM t1, t2, t3 + WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a + @endcode + + The function removes all unnecessary braces from the expression + produced by the conversions. + E.g. + @code + SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b + @endcode + finally is converted to: + @code + SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b + + @endcode + + + It also will remove braces from the following queries: + @code + SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b + SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b. + @endcode + + The benefit of this simplification procedure is that it might return + a query for which the optimizer can evaluate execution plan with more + join orders. With a left join operation the optimizer does not + consider any plan where one of the inner tables is before some of outer + tables. + + + The function is implemented by a recursive procedure. On the recursive + ascent all attributes are calculated, all outer joins that can be + converted are replaced and then all unnecessary braces are removed. + As join list contains join tables in the reverse order sequential + elimination of outer joins does not require extra recursive calls. + + Here is an example of a join query with invalid cross references: + @code + SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b + @endcode + + @param join reference to the query info + @param join_list list representation of the join to be converted + @param conds conditions to add on expressions for converted joins + @param top true <=> conds is the where condition + + @return + - The new condition, if success + - 0, otherwise +*/ + +static COND * +simplify_joins(JOIN *join, List *join_list, COND *conds, bool top) +{ + TABLE_LIST *table; + NESTED_JOIN *nested_join; + TABLE_LIST *prev_table= 0; + List_iterator li(*join_list); + DBUG_ENTER("simplify_joins"); + + /* + Try to simplify join operations from join_list. + The most outer join operation is checked for conversion first. + */ + while ((table= li++)) + { + table_map used_tables; + table_map not_null_tables= (table_map) 0; + + if ((nested_join= table->nested_join)) + { + /* + If the element of join_list is a nested join apply + the procedure to its nested join list first. + */ + if (table->on_expr) + { + Item *expr= table->on_expr; + /* + If an on expression E is attached to the table, + check all null rejected predicates in this expression. + If such a predicate over an attribute belonging to + an inner table of an embedded outer join is found, + the outer join is converted to an inner join and + the corresponding on expression is added to E. + */ + expr= simplify_joins(join, &nested_join->join_list, + expr, FALSE); + + if (!table->prep_on_expr || expr != table->on_expr) + { + DBUG_ASSERT(expr); + + table->on_expr= expr; + table->prep_on_expr= expr->copy_andor_structure(join->thd); + } + } + nested_join->used_tables= (table_map) 0; + nested_join->not_null_tables=(table_map) 0; + conds= simplify_joins(join, &nested_join->join_list, conds, top); + used_tables= nested_join->used_tables; + not_null_tables= nested_join->not_null_tables; + } + else + { + if (!table->prep_on_expr) + table->prep_on_expr= table->on_expr; + used_tables= table->table->map; + if (conds) + not_null_tables= conds->not_null_tables(); + } + + if (table->embedding) + { + table->embedding->nested_join->used_tables|= used_tables; + table->embedding->nested_join->not_null_tables|= not_null_tables; + } + + if (!table->outer_join || (used_tables & not_null_tables)) + { + /* + For some of the inner tables there are conjunctive predicates + that reject nulls => the outer join can be replaced by an inner join. + */ + table->outer_join= 0; + if (table->on_expr) + { + /* Add on expression to the where condition. */ + if (conds) + { + conds= and_conds(conds, table->on_expr); + conds->top_level_item(); + /* conds is always a new item as both cond and on_expr existed */ + DBUG_ASSERT(!conds->fixed); + conds->fix_fields(join->thd, &conds); + } + else + conds= table->on_expr; + table->prep_on_expr= table->on_expr= 0; + } + } + + if (!top) + continue; + + /* + Only inner tables of non-convertible outer joins + remain with on_expr. + */ + if (table->on_expr) + { + table->dep_tables|= table->on_expr->used_tables(); + if (table->embedding) + { + table->dep_tables&= ~table->embedding->nested_join->used_tables; + /* + Embedding table depends on tables used + in embedded on expressions. + */ + table->embedding->on_expr_dep_tables|= table->on_expr->used_tables(); + } + else + table->dep_tables&= ~table->table->map; + } + + if (prev_table) + { + /* The order of tables is reverse: prev_table follows table */ + if (prev_table->straight) + prev_table->dep_tables|= used_tables; + if (prev_table->on_expr) + { + prev_table->dep_tables|= table->on_expr_dep_tables; + table_map prev_used_tables= prev_table->nested_join ? + prev_table->nested_join->used_tables : + prev_table->table->map; + /* + If on expression contains only references to inner tables + we still make the inner tables dependent on the outer tables. + It would be enough to set dependency only on one outer table + for them. Yet this is really a rare case. + */ + if (!(prev_table->on_expr->used_tables() & ~prev_used_tables)) + prev_table->dep_tables|= used_tables; + } + } + prev_table= table; + } + + /* Flatten nested joins that can be flattened. */ + TABLE_LIST *right_neighbor= NULL; + bool fix_name_res= FALSE; + li.rewind(); + while ((table= li++)) + { + nested_join= table->nested_join; + if (nested_join && !table->on_expr) + { + TABLE_LIST *tbl; + List_iterator it(nested_join->join_list); + while ((tbl= it++)) + { + tbl->embedding= table->embedding; + tbl->join_list= table->join_list; + } + li.replace(nested_join->join_list); + /* Need to update the name resolution table chain when flattening joins */ + fix_name_res= TRUE; + table= *li.ref(); + } + if (fix_name_res) + table->next_name_resolution_table= right_neighbor ? + right_neighbor->first_leaf_for_name_resolution() : + NULL; + right_neighbor= table; + } + DBUG_RETURN(conds); +} + + +/** + Assign each nested join structure a bit in nested_join_map. + + Assign each nested join structure (except "confluent" ones - those that + embed only one element) a bit in nested_join_map. + + @param join Join being processed + @param join_list List of tables + @param first_unused Number of first unused bit in nested_join_map before the + call + + @note + This function is called after simplify_joins(), when there are no + redundant nested joins, #non_confluent_nested_joins <= #tables_in_join so + we will not run out of bits in nested_join_map. + + @return + First unused bit in nested_join_map after the call. +*/ + +static uint build_bitmap_for_nested_joins(List *join_list, + uint first_unused) +{ + List_iterator li(*join_list); + TABLE_LIST *table; + DBUG_ENTER("build_bitmap_for_nested_joins"); + while ((table= li++)) + { + NESTED_JOIN *nested_join; + if ((nested_join= table->nested_join)) + { + /* + It is guaranteed by simplify_joins() function that a nested join + that has only one child represents a single table VIEW (and the child + is an underlying table). We don't assign bits to such nested join + structures because + 1. it is redundant (a "sequence" of one table cannot be interleaved + with anything) + 2. we could run out bits in nested_join_map otherwise. + */ + if (nested_join->join_list.elements != 1) + { + nested_join->nj_map= (nested_join_map) 1 << first_unused++; + first_unused= build_bitmap_for_nested_joins(&nested_join->join_list, + first_unused); + } + } + } + DBUG_RETURN(first_unused); +} + + +/** + Set NESTED_JOIN::counter=0 in all nested joins in passed list. + + Recursively set NESTED_JOIN::counter=0 for all nested joins contained in + the passed join_list. + + @param join_list List of nested joins to process. It may also contain base + tables which will be ignored. +*/ + +static void reset_nj_counters(List *join_list) +{ + List_iterator li(*join_list); + TABLE_LIST *table; + DBUG_ENTER("reset_nj_counters"); + while ((table= li++)) + { + NESTED_JOIN *nested_join; + if ((nested_join= table->nested_join)) + { + nested_join->counter= 0; + reset_nj_counters(&nested_join->join_list); + } + } + DBUG_VOID_RETURN; +} + + +/** + Check interleaving with an inner tables of an outer join for + extension table. + + Check if table next_tab can be added to current partial join order, and + if yes, record that it has been added. + + The function assumes that both current partial join order and its + extension with next_tab are valid wrt table dependencies. + + @verbatim + IMPLEMENTATION + LIMITATIONS ON JOIN ORDER + The nested [outer] joins executioner algorithm imposes these limitations + on join order: + 1. "Outer tables first" - any "outer" table must be before any + corresponding "inner" table. + 2. "No interleaving" - tables inside a nested join must form a continuous + sequence in join order (i.e. the sequence must not be interrupted by + tables that are outside of this nested join). + + #1 is checked elsewhere, this function checks #2 provided that #1 has + been already checked. + + WHY NEED NON-INTERLEAVING + Consider an example: + + select * from t0 join t1 left join (t2 join t3) on cond1 + + The join order "t1 t2 t0 t3" is invalid: + + table t0 is outside of the nested join, so WHERE condition for t0 is + attached directly to t0 (without triggers, and it may be used to access + t0). Applying WHERE(t0) to (t2,t0,t3) record is invalid as we may miss + combinations of (t1, t2, t3) that satisfy condition cond1, and produce a + null-complemented (t1, t2.NULLs, t3.NULLs) row, which should not have + been produced. + + If table t0 is not between t2 and t3, the problem doesn't exist: + If t0 is located after (t2,t3), WHERE(t0) is applied after nested join + processing has finished. + If t0 is located before (t2,t3), predicates like WHERE_cond(t0, t2) are + wrapped into condition triggers, which takes care of correct nested + join processing. + + HOW IT IS IMPLEMENTED + The limitations on join order can be rephrased as follows: for valid + join order one must be able to: + 1. write down the used tables in the join order on one line. + 2. for each nested join, put one '(' and one ')' on the said line + 3. write "LEFT JOIN" and "ON (...)" where appropriate + 4. get a query equivalent to the query we're trying to execute. + + Calls to check_interleaving_with_nj() are equivalent to writing the + above described line from left to right. + A single check_interleaving_with_nj(A,B) call is equivalent to writing + table B and appropriate brackets on condition that table A and + appropriate brackets is the last what was written. Graphically the + transition is as follows: + + +---- current position + | + ... last_tab ))) | ( next_tab ) )..) | ... + X Y Z | + +- need to move to this + position. + + Notes about the position: + The caller guarantees that there is no more then one X-bracket by + checking "!(remaining_tables & s->dependent)" before calling this + function. X-bracket may have a pair in Y-bracket. + + When "writing" we store/update this auxilary info about the current + position: + 1. join->cur_embedding_map - bitmap of pairs of brackets (aka nested + joins) we've opened but didn't close. + 2. {each NESTED_JOIN structure not simplified away}->counter - number + of this nested join's children that have already been added to to + the partial join order. + @endverbatim + + @param next_tab Table we're going to extend the current partial join with + + @retval + FALSE Join order extended, nested joins info about current join + order (see NOTE section) updated. + @retval + TRUE Requested join order extension not allowed. +*/ + +static bool check_interleaving_with_nj(JOIN_TAB *next_tab) +{ + TABLE_LIST *next_emb= next_tab->table->pos_in_table_list->embedding; + JOIN *join= next_tab->join; + + if (join->cur_embedding_map & ~next_tab->embedding_map) + { + /* + next_tab is outside of the "pair of brackets" we're currently in. + Cannot add it. + */ + return TRUE; + } + + /* + Do update counters for "pairs of brackets" that we've left (marked as + X,Y,Z in the above picture) + */ + for (;next_emb; next_emb= next_emb->embedding) + { + next_emb->nested_join->counter++; + if (next_emb->nested_join->counter == 1) + { + /* + next_emb is the first table inside a nested join we've "entered". In + the picture above, we're looking at the 'X' bracket. Don't exit yet as + X bracket might have Y pair bracket. + */ + join->cur_embedding_map |= next_emb->nested_join->nj_map; + } + + if (next_emb->nested_join->join_list.elements != + next_emb->nested_join->counter) + break; + + /* + We're currently at Y or Z-bracket as depicted in the above picture. + Mark that we've left it and continue walking up the brackets hierarchy. + */ + join->cur_embedding_map &= ~next_emb->nested_join->nj_map; + } + return FALSE; +} + + +/** + Nested joins perspective: Remove the last table from the join order. + + Remove the last table from the partial join order and update the nested + joins counters and join->cur_embedding_map. It is ok to call this + function for the first table in join order (for which + check_interleaving_with_nj has not been called) + + @param last join table to remove, it is assumed to be the last in current + partial join order. +*/ + +static void restore_prev_nj_state(JOIN_TAB *last) +{ + TABLE_LIST *last_emb= last->table->pos_in_table_list->embedding; + JOIN *join= last->join; + while (last_emb) + { + if (!(--last_emb->nested_join->counter)) + join->cur_embedding_map&= ~last_emb->nested_join->nj_map; + else if (last_emb->nested_join->join_list.elements-1 == + last_emb->nested_join->counter) + join->cur_embedding_map|= last_emb->nested_join->nj_map; + else + break; + last_emb= last_emb->embedding; + } +} + + +static COND * +optimize_cond(JOIN *join, COND *conds, List *join_list, + Item::cond_result *cond_value) +{ + THD *thd= join->thd; + DBUG_ENTER("optimize_cond"); + + if (!conds) + *cond_value= Item::COND_TRUE; + else + { + /* + Build all multiple equality predicates and eliminate equality + predicates that can be inferred from these multiple equalities. + For each reference of a field included into a multiple equality + that occurs in a function set a pointer to the multiple equality + predicate. Substitute a constant instead of this field if the + multiple equality contains a constant. + */ + DBUG_EXECUTE("where", print_where(conds, "original", QT_ORDINARY);); + conds= build_equal_items(join->thd, conds, NULL, join_list, + &join->cond_equal); + DBUG_EXECUTE("where",print_where(conds,"after equal_items", QT_ORDINARY);); + + /* change field = field to field = const for each found field = const */ + propagate_cond_constants(thd, (I_List *) 0, conds, conds); + /* + Remove all instances of item == item + Remove all and-levels where CONST item != CONST item + */ + DBUG_EXECUTE("where",print_where(conds,"after const change", QT_ORDINARY);); + conds= remove_eq_conds(thd, conds, cond_value) ; + DBUG_EXECUTE("info",print_where(conds,"after remove", QT_ORDINARY);); + } + DBUG_RETURN(conds); +} + + +/** + Remove const and eq items. + + @return + Return new item, or NULL if no condition @n + cond_value is set to according: + - COND_OK : query is possible (field = constant) + - COND_TRUE : always true ( 1 = 1 ) + - COND_FALSE : always false ( 1 = 2 ) +*/ + +COND * +remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value) +{ + if (cond->type() == Item::COND_ITEM) + { + bool and_level= ((Item_cond*) cond)->functype() + == Item_func::COND_AND_FUNC; + List_iterator li(*((Item_cond*) cond)->argument_list()); + Item::cond_result tmp_cond_value; + bool should_fix_fields=0; + + *cond_value=Item::COND_UNDEF; + Item *item; + while ((item=li++)) + { + Item *new_item=remove_eq_conds(thd, item, &tmp_cond_value); + if (!new_item) + li.remove(); + else if (item != new_item) + { + VOID(li.replace(new_item)); + should_fix_fields=1; + } + if (*cond_value == Item::COND_UNDEF) + *cond_value=tmp_cond_value; + switch (tmp_cond_value) { + case Item::COND_OK: // Not TRUE or FALSE + if (and_level || *cond_value == Item::COND_FALSE) + *cond_value=tmp_cond_value; + break; + case Item::COND_FALSE: + if (and_level) + { + *cond_value=tmp_cond_value; + return (COND*) 0; // Always false + } + break; + case Item::COND_TRUE: + if (!and_level) + { + *cond_value= tmp_cond_value; + return (COND*) 0; // Always true + } + break; + case Item::COND_UNDEF: // Impossible + break; /* purecov: deadcode */ + } + } + if (should_fix_fields) + cond->update_used_tables(); + + if (!((Item_cond*) cond)->argument_list()->elements || + *cond_value != Item::COND_OK) + return (COND*) 0; + if (((Item_cond*) cond)->argument_list()->elements == 1) + { // Remove list + item= ((Item_cond*) cond)->argument_list()->head(); + ((Item_cond*) cond)->argument_list()->empty(); + return item; + } + } + else if (cond->type() == Item::FUNC_ITEM && + ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC) + { + /* + Handles this special case for some ODBC applications: + The are requesting the row that was just updated with a auto_increment + value with this construct: + + SELECT * from table_name where auto_increment_column IS NULL + This will be changed to: + SELECT * from table_name where auto_increment_column = LAST_INSERT_ID + */ + + Item_func_isnull *func=(Item_func_isnull*) cond; + Item **args= func->arguments(); + if (args[0]->type() == Item::FIELD_ITEM) + { + Field *field=((Item_field*) args[0])->field; + if (field->flags & AUTO_INCREMENT_FLAG && !field->table->maybe_null && + (thd->options & OPTION_AUTO_IS_NULL) && + (thd->first_successful_insert_id_in_prev_stmt > 0 && + thd->substitute_null_with_insert_id)) + { +#ifdef HAVE_QUERY_CACHE + query_cache_abort(&thd->net); +#endif + COND *new_cond; + if ((new_cond= new Item_func_eq(args[0], + new Item_int("last_insert_id()", + thd->read_first_successful_insert_id_in_prev_stmt(), + MY_INT64_NUM_DECIMAL_DIGITS)))) + { + cond=new_cond; + /* + Item_func_eq can't be fixed after creation so we do not check + cond->fixed, also it do not need tables so we use 0 as second + argument. + */ + cond->fix_fields(thd, &cond); + } + /* + IS NULL should be mapped to LAST_INSERT_ID only for first row, so + clear for next row + */ + thd->substitute_null_with_insert_id= FALSE; + } + /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */ + else if (((field->type() == MYSQL_TYPE_DATE) || + (field->type() == MYSQL_TYPE_DATETIME)) && + (field->flags & NOT_NULL_FLAG) && + !field->table->maybe_null) + { + COND *new_cond; + if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2)))) + { + cond=new_cond; + /* + Item_func_eq can't be fixed after creation so we do not check + cond->fixed, also it do not need tables so we use 0 as second + argument. + */ + cond->fix_fields(thd, &cond); + } + } + } + if (cond->const_item()) + { + *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE; + return (COND*) 0; + } + } + else if (cond->const_item()) + { + *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE; + return (COND*) 0; + } + else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK) + { // boolan compare function + Item *left_item= ((Item_func*) cond)->arguments()[0]; + Item *right_item= ((Item_func*) cond)->arguments()[1]; + if (left_item->eq(right_item,1)) + { + if (!left_item->maybe_null || + ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC) + return (COND*) 0; // Compare of identical items + } + } + *cond_value=Item::COND_OK; + return cond; // Point at next and level +} + +/* + Check if equality can be used in removing components of GROUP BY/DISTINCT + + SYNOPSIS + test_if_equality_guarantees_uniqueness() + l the left comparison argument (a field if any) + r the right comparison argument (a const of any) + + DESCRIPTION + Checks if an equality predicate can be used to take away + DISTINCT/GROUP BY because it is known to be true for exactly one + distinct value (e.g. == ). + Arguments must be of the same type because e.g. + = may match more than 1 distinct value from + the column. + We must take into consideration and the optimization done for various + string constants when compared to dates etc (see Item_int_with_ref) as + well as the collation of the arguments. + + RETURN VALUE + TRUE can be used + FALSE cannot be used +*/ +static bool +test_if_equality_guarantees_uniqueness(Item *l, Item *r) +{ + return r->const_item() && + /* elements must be compared as dates */ + (Arg_comparator::can_compare_as_dates(l, r, 0) || + /* or of the same result type */ + (r->result_type() == l->result_type() && + /* and must have the same collation if compared as strings */ + (l->result_type() != STRING_RESULT || + l->collation.collation == r->collation.collation))); +} + +/** + Return TRUE if the item is a const value in all the WHERE clause. +*/ + +static bool +const_expression_in_where(COND *cond, Item *comp_item, Item **const_item) +{ + if (cond->type() == Item::COND_ITEM) + { + bool and_level= (((Item_cond*) cond)->functype() + == Item_func::COND_AND_FUNC); + List_iterator_fast li(*((Item_cond*) cond)->argument_list()); + Item *item; + while ((item=li++)) + { + bool res=const_expression_in_where(item, comp_item, const_item); + if (res) // Is a const value + { + if (and_level) + return 1; + } + else if (!and_level) + return 0; + } + return and_level ? 0 : 1; + } + else if (cond->eq_cmp_result() != Item::COND_OK) + { // boolan compare function + Item_func* func= (Item_func*) cond; + if (func->functype() != Item_func::EQUAL_FUNC && + func->functype() != Item_func::EQ_FUNC) + return 0; + Item *left_item= ((Item_func*) cond)->arguments()[0]; + Item *right_item= ((Item_func*) cond)->arguments()[1]; + if (left_item->eq(comp_item,1)) + { + if (test_if_equality_guarantees_uniqueness (left_item, right_item)) + { + if (*const_item) + return right_item->eq(*const_item, 1); + *const_item=right_item; + return 1; + } + } + else if (right_item->eq(comp_item,1)) + { + if (test_if_equality_guarantees_uniqueness (right_item, left_item)) + { + if (*const_item) + return left_item->eq(*const_item, 1); + *const_item=left_item; + return 1; + } + } + } + return 0; +} + +/**************************************************************************** + Create internal temporary table +****************************************************************************/ + +/** + Create field for temporary table from given field. + + @param thd Thread handler + @param org_field field from which new field will be created + @param name New field name + @param table Temporary table + @param item !=NULL if item->result_field should point to new field. + This is relevant for how fill_record() is going to work: + If item != NULL then fill_record() will update + the record in the original table. + If item == NULL then fill_record() will update + the temporary table + @param convert_blob_length If >0 create a varstring(convert_blob_length) + field instead of blob. + + @retval + NULL on error + @retval + new_created field +*/ + +Field *create_tmp_field_from_field(THD *thd, Field *org_field, + const char *name, TABLE *table, + Item_field *item, uint convert_blob_length) +{ + Field *new_field; + + /* + Make sure that the blob fits into a Field_varstring which has + 2-byte lenght. + */ + if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE && + (org_field->flags & BLOB_FLAG)) + new_field= new Field_varstring(convert_blob_length, + org_field->maybe_null(), + org_field->field_name, table->s, + org_field->charset()); + else + new_field= org_field->new_field(thd->mem_root, table, + table == org_field->table); + if (new_field) + { + new_field->init(table); + new_field->orig_table= org_field->orig_table; + if (item) + item->result_field= new_field; + else + new_field->field_name= name; + new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG); + if (org_field->maybe_null() || (item && item->maybe_null)) + new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join + if (org_field->type() == MYSQL_TYPE_VAR_STRING || + org_field->type() == MYSQL_TYPE_VARCHAR) + table->s->db_create_options|= HA_OPTION_PACK_RECORD; + else if (org_field->type() == FIELD_TYPE_DOUBLE) + ((Field_double *) new_field)->not_fixed= TRUE; + } + return new_field; +} + +/** + Create field for temporary table using type of given item. + + @param thd Thread handler + @param item Item to create a field for + @param table Temporary table + @param copy_func If set and item is a function, store copy of + item in this array + @param modify_item 1 if item->result_field should point to new + item. This is relevent for how fill_record() + is going to work: + If modify_item is 1 then fill_record() will + update the record in the original table. + If modify_item is 0 then fill_record() will + update the temporary table + @param convert_blob_length If >0 create a varstring(convert_blob_length) + field instead of blob. + + @retval + 0 on error + @retval + new_created field +*/ + +static Field *create_tmp_field_from_item(THD *thd, Item *item, TABLE *table, + Item ***copy_func, bool modify_item, + uint convert_blob_length) +{ + bool maybe_null= item->maybe_null; + Field *new_field; + LINT_INIT(new_field); + + switch (item->result_type()) { + case REAL_RESULT: + new_field= new Field_double(item->max_length, maybe_null, + item->name, item->decimals, TRUE); + break; + case INT_RESULT: + /* + Select an integer type with the minimal fit precision. + MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign. + Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into + Field_long : make them Field_longlong. + */ + if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1)) + new_field=new Field_longlong(item->max_length, maybe_null, + item->name, item->unsigned_flag); + else + new_field=new Field_long(item->max_length, maybe_null, + item->name, item->unsigned_flag); + break; + case STRING_RESULT: + DBUG_ASSERT(item->collation.collation); + + enum enum_field_types type; + /* + DATE/TIME and GEOMETRY fields have STRING_RESULT result type. + To preserve type they needed to be handled separately. + */ + if ((type= item->field_type()) == MYSQL_TYPE_DATETIME || + type == MYSQL_TYPE_TIME || type == MYSQL_TYPE_DATE || + type == MYSQL_TYPE_NEWDATE || + type == MYSQL_TYPE_TIMESTAMP || type == MYSQL_TYPE_GEOMETRY) + new_field= item->tmp_table_field_from_field_type(table, 1); + /* + Make sure that the blob fits into a Field_varstring which has + 2-byte lenght. + */ + else if (item->max_length/item->collation.collation->mbmaxlen > 255 && + convert_blob_length <= Field_varstring::MAX_SIZE && + convert_blob_length) + new_field= new Field_varstring(convert_blob_length, maybe_null, + item->name, table->s, + item->collation.collation); + else + new_field= item->make_string_field(table, thd); //@InfiniDB + new_field->set_derivation(item->collation.derivation); + break; + case DECIMAL_RESULT: + new_field= Field_new_decimal::new_decimal_field(item); + break; + case ROW_RESULT: + default: + // This case should never be choosen + DBUG_ASSERT(0); + new_field= 0; + break; + } + if (new_field) + new_field->init(table); + + if (copy_func && item->is_result_field()) + *((*copy_func)++) = item; // Save for copy_funcs + if (modify_item) + item->set_result_field(new_field); + if (item->type() == Item::NULL_ITEM) + new_field->is_created_from_null_item= TRUE; + return new_field; +} + + +/** + Create field for information schema table. + + @param thd Thread handler + @param table Temporary table + @param item Item to create a field for + + @retval + 0 on error + @retval + new_created field +*/ + +Field *create_tmp_field_for_schema(THD *thd, Item *item, TABLE *table) +{ + if (item->field_type() == MYSQL_TYPE_VARCHAR) + { + Field *field; + if (item->max_length > MAX_FIELD_VARCHARLENGTH) + field= new Field_blob(item->max_length, item->maybe_null, + item->name, item->collation.collation); + else + field= new Field_varstring(item->max_length, item->maybe_null, + item->name, + table->s, item->collation.collation); + if (field) + field->init(table); + return field; + } + return item->tmp_table_field_from_field_type(table, 0); +} + + +/** + Create field for temporary table. + + @param thd Thread handler + @param table Temporary table + @param item Item to create a field for + @param type Type of item (normally item->type) + @param copy_func If set and item is a function, store copy of item + in this array + @param from_field if field will be created using other field as example, + pointer example field will be written here + @param default_field If field has a default value field, store it here + @param group 1 if we are going to do a relative group by on result + @param modify_item 1 if item->result_field should point to new item. + This is relevent for how fill_record() is going to + work: + If modify_item is 1 then fill_record() will update + the record in the original table. + If modify_item is 0 then fill_record() will update + the temporary table + @param convert_blob_length If >0 create a varstring(convert_blob_length) + field instead of blob. + + @retval + 0 on error + @retval + new_created field +*/ + +Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type, + Item ***copy_func, Field **from_field, + Field **default_field, + bool group, bool modify_item, + bool table_cant_handle_bit_fields, + bool make_copy_field, + uint convert_blob_length) +{ + Field *result; + Item::Type orig_type= type; + Item *orig_item= 0; + + if (type != Item::FIELD_ITEM && + item->real_item()->type() == Item::FIELD_ITEM) + { + orig_item= item; + item= item->real_item(); + type= Item::FIELD_ITEM; + } + + switch (type) { + case Item::SUM_FUNC_ITEM: + { + Item_sum *item_sum=(Item_sum*) item; + result= item_sum->create_tmp_field(group, table, convert_blob_length); + if (!result) + thd->fatal_error(); + return result; + } + case Item::FIELD_ITEM: + case Item::DEFAULT_VALUE_ITEM: + { + Item_field *field= (Item_field*) item; + bool orig_modify= modify_item; + if (orig_type == Item::REF_ITEM) + modify_item= 0; + /* + If item have to be able to store NULLs but underlaid field can't do it, + create_tmp_field_from_field() can't be used for tmp field creation. + */ + if (field->maybe_null && !field->field->maybe_null()) + { + result= create_tmp_field_from_item(thd, item, table, NULL, + modify_item, convert_blob_length); + *from_field= field->field; + if (result && modify_item) + field->result_field= result; + } + else if (table_cant_handle_bit_fields && field->field->type() == + MYSQL_TYPE_BIT) + { + *from_field= field->field; + result= create_tmp_field_from_item(thd, item, table, copy_func, + modify_item, convert_blob_length); + if (result && modify_item) + field->result_field= result; + } + else + result= create_tmp_field_from_field(thd, (*from_field= field->field), + orig_item ? orig_item->name : + item->name, + table, + modify_item ? field : + NULL, + convert_blob_length); + if (orig_type == Item::REF_ITEM && orig_modify) + ((Item_ref*)orig_item)->set_result_field(result); + if (field->field->eq_def(result)) + *default_field= field->field; + return result; + } + /* Fall through */ + case Item::FUNC_ITEM: + if (((Item_func *) item)->functype() == Item_func::FUNC_SP) + { + Item_func_sp *item_func_sp= (Item_func_sp *) item; + Field *sp_result_field= item_func_sp->get_sp_result_field(); + + if (make_copy_field) + { + DBUG_ASSERT(item_func_sp->result_field); + *from_field= item_func_sp->result_field; + } + else + { + *((*copy_func)++)= item; + } + + Field *result_field= + create_tmp_field_from_field(thd, + sp_result_field, + item_func_sp->name, + table, + NULL, + convert_blob_length); + + if (modify_item) + item->set_result_field(result_field); + + return result_field; + } + + /* Fall through */ + case Item::COND_ITEM: + case Item::FIELD_AVG_ITEM: + case Item::FIELD_STD_ITEM: + case Item::SUBSELECT_ITEM: + /* The following can only happen with 'CREATE TABLE ... SELECT' */ + case Item::PROC_ITEM: + case Item::INT_ITEM: + case Item::REAL_ITEM: + case Item::DECIMAL_ITEM: + case Item::STRING_ITEM: + case Item::REF_ITEM: + case Item::NULL_ITEM: + case Item::VARBIN_ITEM: + if (make_copy_field) + { + DBUG_ASSERT(((Item_result_field*)item)->result_field); + *from_field= ((Item_result_field*)item)->result_field; + } + return create_tmp_field_from_item(thd, item, table, + (make_copy_field ? 0 : copy_func), + modify_item, convert_blob_length); + case Item::TYPE_HOLDER: + result= ((Item_type_holder *)item)->make_field_by_type(table, thd); //@infinidb pass in thd + result->set_derivation(item->collation.derivation); + return result; + default: // Dosen't have to be stored + return 0; + } +} + +/* + Set up column usage bitmaps for a temporary table + + IMPLEMENTATION + For temporary tables, we need one bitmap with all columns set and + a tmp_set bitmap to be used by things like filesort. +*/ + +void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps) +{ + uint field_count= table->s->fields; + bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count, + FALSE); + bitmap_init(&table->tmp_set, + (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)), + field_count, FALSE); + /* write_set and all_set are copies of read_set */ + table->def_write_set= table->def_read_set; + table->s->all_set= table->def_read_set; + bitmap_set_all(&table->s->all_set); + table->default_column_bitmaps(); +} + + +/** + Create a temp table according to a field list. + + Given field pointers are changed to point at tmp_table for + send_fields. The table object is self contained: it's + allocated in its own memory root, as well as Field objects + created for table columns. + This function will replace Item_sum items in 'fields' list with + corresponding Item_field items, pointing at the fields in the + temporary table, unless this was prohibited by TRUE + value of argument save_sum_fields. The Item_field objects + are created in THD memory root. + + @param thd thread handle + @param param a description used as input to create the table + @param fields list of items that will be used to define + column types of the table (also see NOTES) + @param group TODO document + @param distinct should table rows be distinct + @param save_sum_fields see NOTES + @param select_options + @param rows_limit + @param table_alias possible name of the temporary table that can + be used for name resolving; can be "". +*/ + +#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128 +#define AVG_STRING_LENGTH_TO_PACK_ROWS 64 +#define RATIO_TO_PACK_ROWS 2 +#define MIN_STRING_LENGTH_TO_PACK_ROWS 10 + +TABLE * +create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List &fields, + ORDER *group, bool distinct, bool save_sum_fields, + ulonglong select_options, ha_rows rows_limit, + char *table_alias) +{ + MEM_ROOT *mem_root_save, own_root; + TABLE *table; + TABLE_SHARE *share; + uint i,field_count,null_count,null_pack_length; + uint copy_func_count= param->func_count; + uint hidden_null_count, hidden_null_pack_length, hidden_field_count; + uint blob_count,group_null_items, string_count; + uint temp_pool_slot=MY_BIT_NONE; + uint fieldnr= 0; + ulong reclength, string_total_length; + bool using_unique_constraint= 0; + bool use_packed_rows= 0; + bool not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS); + char *tmpname,path[FN_REFLEN]; + uchar *pos, *group_buff, *bitmaps; + uchar *null_flags; + Field **reg_field, **from_field, **default_field; + uint *blob_field; + Copy_field *copy=0; + KEY *keyinfo; + KEY_PART_INFO *key_part_info; + Item **copy_func; + MI_COLUMNDEF *recinfo; + uint total_uneven_bit_length= 0; + bool force_copy_fields= param->force_copy_fields; + /* Treat sum functions as normal ones when loose index scan is used. */ + save_sum_fields|= param->precomputed_group_by; + DBUG_ENTER("create_tmp_table"); + DBUG_PRINT("enter", + ("distinct: %d save_sum_fields: %d rows_limit: %lu group: %d", + (int) distinct, (int) save_sum_fields, + (ulong) rows_limit,test(group))); + + status_var_increment(thd->status_var.created_tmp_tables); + + if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES)) + temp_pool_slot = bitmap_lock_set_next(&temp_pool); + + if (temp_pool_slot != MY_BIT_NONE) // we got a slot + sprintf(path, "%s_%lx_%i", tmp_file_prefix, + current_pid, temp_pool_slot); + else + { + /* if we run out of slots or we are not using tempool */ + sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid, + thd->thread_id, thd->tmp_table++); + } + + /* + No need to change table name to lower case as we are only creating + MyISAM or HEAP tables here + */ + fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME); + + + if (group) + { + if (!param->quick_group) + group=0; // Can't use group key + else for (ORDER *tmp=group ; tmp ; tmp=tmp->next) + { + (*tmp->item)->marker=4; // Store null in key + if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB) + using_unique_constraint=1; + } + if (param->group_length >= MAX_BLOB_WIDTH) + using_unique_constraint=1; + if (group) + distinct=0; // Can't use distinct + } + + field_count=param->field_count+param->func_count+param->sum_func_count; + hidden_field_count=param->hidden_field_count; + + /* + When loose index scan is employed as access method, it already + computes all groups and the result of all aggregate functions. We + make space for the items of the aggregate function in the list of + functions TMP_TABLE_PARAM::items_to_copy, so that the values of + these items are stored in the temporary table. + */ + if (param->precomputed_group_by) + copy_func_count+= param->sum_func_count; + + init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0); + + if (!multi_alloc_root(&own_root, + &table, sizeof(*table), + &share, sizeof(*share), + ®_field, sizeof(Field*) * (field_count+1), + &default_field, sizeof(Field*) * (field_count), + &blob_field, sizeof(uint)*(field_count+1), + &from_field, sizeof(Field*)*field_count, + ©_func, sizeof(*copy_func)*(copy_func_count+1), + ¶m->keyinfo, sizeof(*param->keyinfo), + &key_part_info, + sizeof(*key_part_info)*(param->group_parts+1), + ¶m->start_recinfo, + sizeof(*param->recinfo)*(field_count*2+4), + &tmpname, (uint) strlen(path)+1, + &group_buff, (group && ! using_unique_constraint ? + param->group_length : 0), + &bitmaps, bitmap_buffer_size(field_count)*2, + NullS)) + { + if (temp_pool_slot != MY_BIT_NONE) + bitmap_lock_clear_bit(&temp_pool, temp_pool_slot); + DBUG_RETURN(NULL); /* purecov: inspected */ + } + /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */ + if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count])) + { + if (temp_pool_slot != MY_BIT_NONE) + bitmap_lock_clear_bit(&temp_pool, temp_pool_slot); + free_root(&own_root, MYF(0)); /* purecov: inspected */ + DBUG_RETURN(NULL); /* purecov: inspected */ + } + param->items_to_copy= copy_func; + strmov(tmpname,path); + /* make table according to fields */ + + bzero((char*) table,sizeof(*table)); + bzero((char*) reg_field,sizeof(Field*)*(field_count+1)); + bzero((char*) default_field, sizeof(Field*) * (field_count)); + bzero((char*) from_field,sizeof(Field*)*field_count); + + table->mem_root= own_root; + mem_root_save= thd->mem_root; + thd->mem_root= &table->mem_root; + + table->field=reg_field; + table->alias= table_alias; + table->reginfo.lock_type=TL_WRITE; /* Will be updated */ + table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE; + table->map=1; + table->temp_pool_slot = temp_pool_slot; + table->copy_blobs= 1; + table->in_use= thd; + table->quick_keys.init(); + table->covering_keys.init(); + table->merge_keys.init(); + table->keys_in_use_for_query.init(); + + table->s= share; + init_tmp_table_share(thd, share, "", 0, tmpname, tmpname); + share->blob_field= blob_field; + share->blob_ptr_size= portable_sizeof_char_ptr; + share->db_low_byte_first=1; // True for HEAP and MyISAM + share->table_charset= param->table_charset; + share->primary_key= MAX_KEY; // Indicate no primary key + share->keys_for_keyread.init(); + share->keys_in_use.init(); + + /* Calculate which type of fields we will store in the temporary table */ + + reclength= string_total_length= 0; + blob_count= string_count= null_count= hidden_null_count= group_null_items= 0; + param->using_indirect_summary_function=0; + + List_iterator_fast li(fields); + Item *item; + Field **tmp_from_field=from_field; + while ((item=li++)) + { + Item::Type type=item->type(); + if (not_all_columns) + { + if (item->with_sum_func && type != Item::SUM_FUNC_ITEM) + { + if (item->used_tables() & OUTER_REF_TABLE_BIT) + item->update_used_tables(); + if (type == Item::SUBSELECT_ITEM || + (item->used_tables() & ~OUTER_REF_TABLE_BIT)) + { + /* + Mark that the we have ignored an item that refers to a summary + function. We need to know this if someone is going to use + DISTINCT on the result. + */ + param->using_indirect_summary_function=1; + continue; + } + } + if (item->const_item() && (int) hidden_field_count <= 0) + continue; // We don't have to store this + } + if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields) + { /* Can't calc group yet */ + Item_sum *sum_item= (Item_sum *) item; + sum_item->result_field=0; + for (i=0 ; i < sum_item->get_arg_count() ; i++) + { + Item *arg= sum_item->get_arg(i); + if (!arg->const_item()) + { + Field *new_field= + create_tmp_field(thd, table, arg, arg->type(), ©_func, + tmp_from_field, &default_field[fieldnr], + group != 0,not_all_columns, + distinct, 0, + param->convert_blob_length); + if (!new_field) + goto err; // Should be OOM + tmp_from_field++; + reclength+=new_field->pack_length(); + if (new_field->flags & BLOB_FLAG) + { + *blob_field++= fieldnr; + blob_count++; + } + if (new_field->type() == MYSQL_TYPE_BIT) + total_uneven_bit_length+= new_field->field_length & 7; + *(reg_field++)= new_field; + if (new_field->real_type() == MYSQL_TYPE_STRING || + new_field->real_type() == MYSQL_TYPE_VARCHAR) + { + string_count++; + string_total_length+= new_field->pack_length(); + } + thd->mem_root= mem_root_save; + arg= sum_item->set_arg(i, thd, new Item_field(new_field)); + thd->mem_root= &table->mem_root; + if (!(new_field->flags & NOT_NULL_FLAG)) + { + null_count++; + /* + new_field->maybe_null() is still false, it will be + changed below. But we have to setup Item_field correctly + */ + arg->maybe_null=1; + } + new_field->field_index= fieldnr++; + } + } + } + else + { + /* + The last parameter to create_tmp_field() is a bit tricky: + + We need to set it to 0 in union, to get fill_record() to modify the + temporary table. + We need to set it to 1 on multi-table-update and in select to + write rows to the temporary table. + We here distinguish between UNION and multi-table-updates by the fact + that in the later case group is set to the row pointer. + + The test for item->marker == 4 is ensure we don't create a group-by + key over a bit field as heap tables can't handle that. + */ + Field *new_field= (param->schema_table) ? + create_tmp_field_for_schema(thd, item, table) : + create_tmp_field(thd, table, item, type, ©_func, + tmp_from_field, &default_field[fieldnr], + group != 0, + !force_copy_fields && + (not_all_columns || group !=0), + item->marker == 4, force_copy_fields, + param->convert_blob_length); + + if (!new_field) + { + if (thd->is_fatal_error) + goto err; // Got OOM + continue; // Some kindf of const item + } + if (type == Item::SUM_FUNC_ITEM) + ((Item_sum *) item)->result_field= new_field; + tmp_from_field++; + reclength+=new_field->pack_length(); + if (!(new_field->flags & NOT_NULL_FLAG)) + null_count++; + if (new_field->type() == MYSQL_TYPE_BIT) + total_uneven_bit_length+= new_field->field_length & 7; + if (new_field->flags & BLOB_FLAG) + { + *blob_field++= fieldnr; + blob_count++; + } + if (item->marker == 4 && item->maybe_null) + { + group_null_items++; + new_field->flags|= GROUP_FLAG; + } + new_field->field_index= fieldnr++; + *(reg_field++)= new_field; + } + if (!--hidden_field_count) + { + /* + This was the last hidden field; Remember how many hidden fields could + have null + */ + hidden_null_count=null_count; + /* + We need to update hidden_field_count as we may have stored group + functions with constant arguments + */ + param->hidden_field_count= fieldnr; + null_count= 0; + } + } + DBUG_ASSERT(fieldnr == (uint) (reg_field - table->field)); + DBUG_ASSERT(field_count >= (uint) (reg_field - table->field)); + field_count= fieldnr; + *reg_field= 0; + *blob_field= 0; // End marker + share->fields= field_count; + + /* If result table is small; use a heap */ + /* future: storage engine selection can be made dynamic? */ + if (blob_count || using_unique_constraint || + (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == + OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM)) + { + share->db_plugin= ha_lock_engine(0, myisam_hton); + table->file= get_new_handler(share, &table->mem_root, + share->db_type()); + if (group && + (param->group_parts > table->file->max_key_parts() || + param->group_length > table->file->max_key_length())) + using_unique_constraint=1; + } + else + { + share->db_plugin= ha_lock_engine(0, heap_hton); + table->file= get_new_handler(share, &table->mem_root, + share->db_type()); + } + if (!table->file) + goto err; + + + if (!using_unique_constraint) + reclength+= group_null_items; // null flag is stored separately + + share->blob_fields= blob_count; + if (blob_count == 0) + { + /* We need to ensure that first byte is not 0 for the delete link */ + if (param->hidden_field_count) + hidden_null_count++; + else + null_count++; + } + hidden_null_pack_length=(hidden_null_count+7)/8; + null_pack_length= (hidden_null_pack_length + + (null_count + total_uneven_bit_length + 7) / 8); + reclength+=null_pack_length; + if (!reclength) + reclength=1; // Dummy select + /* Use packed rows if there is blobs or a lot of space to gain */ + if (blob_count || + (string_total_length >= STRING_TOTAL_LENGTH_TO_PACK_ROWS && + (reclength / string_total_length <= RATIO_TO_PACK_ROWS || + string_total_length / string_count >= AVG_STRING_LENGTH_TO_PACK_ROWS))) + use_packed_rows= 1; + + share->reclength= reclength; + { + uint alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1); + share->rec_buff_length= alloc_length; + if (!(table->record[0]= (uchar*) + alloc_root(&table->mem_root, alloc_length*3))) + goto err; + table->record[1]= table->record[0]+alloc_length; + share->default_values= table->record[1]+alloc_length; + } + copy_func[0]=0; // End marker + param->func_count= copy_func - param->items_to_copy; + + setup_tmp_table_column_bitmaps(table, bitmaps); + + recinfo=param->start_recinfo; + null_flags=(uchar*) table->record[0]; + pos=table->record[0]+ null_pack_length; + if (null_pack_length) + { + bzero((uchar*) recinfo,sizeof(*recinfo)); + recinfo->type=FIELD_NORMAL; + recinfo->length=null_pack_length; + recinfo++; + bfill(null_flags,null_pack_length,255); // Set null fields + + table->null_flags= (uchar*) table->record[0]; + share->null_fields= null_count+ hidden_null_count; + share->null_bytes= null_pack_length; + } + null_count= (blob_count == 0) ? 1 : 0; + hidden_field_count=param->hidden_field_count; + for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++) + { + Field *field= *reg_field; + uint length; + bzero((uchar*) recinfo,sizeof(*recinfo)); + + if (!(field->flags & NOT_NULL_FLAG)) + { + if (field->flags & GROUP_FLAG && !using_unique_constraint) + { + /* + We have to reserve one byte here for NULL bits, + as this is updated by 'end_update()' + */ + *pos++=0; // Null is stored here + recinfo->length=1; + recinfo->type=FIELD_NORMAL; + recinfo++; + bzero((uchar*) recinfo,sizeof(*recinfo)); + } + else + { + recinfo->null_bit= 1 << (null_count & 7); + recinfo->null_pos= null_count/8; + } + field->move_field(pos,null_flags+null_count/8, + 1 << (null_count & 7)); + null_count++; + } + else + field->move_field(pos,(uchar*) 0,0); + if (field->type() == MYSQL_TYPE_BIT) + { + /* We have to reserve place for extra bits among null bits */ + ((Field_bit*) field)->set_bit_ptr(null_flags + null_count / 8, + null_count & 7); + null_count+= (field->field_length & 7); + } + field->reset(); + + /* + Test if there is a default field value. The test for ->ptr is to skip + 'offset' fields generated by initalize_tables + */ + if (default_field[i] && default_field[i]->ptr) + { + /* + default_field[i] is set only in the cases when 'field' can + inherit the default value that is defined for the field referred + by the Item_field object from which 'field' has been created. + */ + my_ptrdiff_t diff; + Field *orig_field= default_field[i]; + /* Get the value from default_values */ + diff= (my_ptrdiff_t) (orig_field->table->s->default_values- + orig_field->table->record[0]); + orig_field->move_field_offset(diff); // Points now at default_values + if (orig_field->is_real_null()) + field->set_null(); + else + { + field->set_notnull(); + memcpy(field->ptr, orig_field->ptr, field->pack_length()); + } + orig_field->move_field_offset(-diff); // Back to record[0] + } + + if (from_field[i]) + { /* Not a table Item */ + copy->set(field,from_field[i],save_sum_fields); + copy++; + } + length=field->pack_length(); + pos+= length; + + /* Make entry for create table */ + recinfo->length=length; + if (field->flags & BLOB_FLAG) + recinfo->type= (int) FIELD_BLOB; + else if (use_packed_rows && + field->real_type() == MYSQL_TYPE_STRING && + length >= MIN_STRING_LENGTH_TO_PACK_ROWS) + recinfo->type=FIELD_SKIP_ENDSPACE; + else + recinfo->type=FIELD_NORMAL; + if (!--hidden_field_count) + null_count=(null_count+7) & ~7; // move to next byte + + // fix table name in field entry + field->table_name= &table->alias; + } + + param->copy_field_end=copy; + param->recinfo=recinfo; + store_record(table,s->default_values); // Make empty default record + + if (thd->variables.tmp_table_size == ~ (ulonglong) 0) // No limit + share->max_rows= ~(ha_rows) 0; + else + share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ? + min(thd->variables.tmp_table_size, + thd->variables.max_heap_table_size) : + thd->variables.tmp_table_size) / + share->reclength); + set_if_bigger(share->max_rows,1); // For dummy start options + /* + Push the LIMIT clause to the temporary table creation, so that we + materialize only up to 'rows_limit' records instead of all result records. + */ + set_if_smaller(share->max_rows, rows_limit); + param->end_write_records= rows_limit; + + keyinfo= param->keyinfo; + + if (group) + { + DBUG_PRINT("info",("Creating group key in temporary table")); + table->group=group; /* Table is grouped by key */ + param->group_buff=group_buff; + share->keys=1; + share->uniques= test(using_unique_constraint); + table->key_info=keyinfo; + keyinfo->key_part=key_part_info; + keyinfo->flags=HA_NOSAME; + keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts; + keyinfo->key_length=0; + keyinfo->rec_per_key=0; + keyinfo->algorithm= HA_KEY_ALG_UNDEF; + keyinfo->name= (char*) "group_key"; + ORDER *cur_group= group; + for (; cur_group ; cur_group= cur_group->next, key_part_info++) + { + Field *field=(*cur_group->item)->get_tmp_table_field(); + bool maybe_null=(*cur_group->item)->maybe_null; + key_part_info->null_bit=0; + key_part_info->field= field; + key_part_info->offset= field->offset(table->record[0]); + key_part_info->length= (uint16) field->key_length(); + key_part_info->type= (uint8) field->key_type(); + key_part_info->key_type = + ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT || + (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 || + (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ? + 0 : FIELDFLAG_BINARY; + if (!using_unique_constraint) + { + cur_group->buff=(char*) group_buff; + if (!(cur_group->field= field->new_key_field(thd->mem_root,table, + group_buff + + test(maybe_null), + field->null_ptr, + field->null_bit))) + goto err; /* purecov: inspected */ + if (maybe_null) + { + /* + To be able to group on NULL, we reserved place in group_buff + for the NULL flag just before the column. (see above). + The field data is after this flag. + The NULL flag is updated in 'end_update()' and 'end_write()' + */ + keyinfo->flags|= HA_NULL_ARE_EQUAL; // def. that NULL == NULL + key_part_info->null_bit=field->null_bit; + key_part_info->null_offset= (uint) (field->null_ptr - + (uchar*) table->record[0]); + cur_group->buff++; // Pointer to field data + group_buff++; // Skipp null flag + } + /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */ + key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL; + group_buff+= cur_group->field->pack_length(); + } + keyinfo->key_length+= key_part_info->length; + } + } + + if (distinct && field_count != param->hidden_field_count) + { + /* + Create an unique key or an unique constraint over all columns + that should be in the result. In the temporary table, there are + 'param->hidden_field_count' extra columns, whose null bits are stored + in the first 'hidden_null_pack_length' bytes of the row. + */ + DBUG_PRINT("info",("hidden_field_count: %d", param->hidden_field_count)); + + null_pack_length-=hidden_null_pack_length; + keyinfo->key_parts= ((field_count-param->hidden_field_count)+ + test(null_pack_length)); + table->distinct= 1; + share->keys= 1; + if (blob_count) + { + using_unique_constraint=1; + share->uniques= 1; + } + if (!(key_part_info= (KEY_PART_INFO*) + alloc_root(&table->mem_root, + keyinfo->key_parts * sizeof(KEY_PART_INFO)))) + goto err; + bzero((void*) key_part_info, keyinfo->key_parts * sizeof(KEY_PART_INFO)); + table->key_info=keyinfo; + keyinfo->key_part=key_part_info; + keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL; + keyinfo->key_length=(uint16) reclength; + keyinfo->name= (char*) "distinct_key"; + keyinfo->algorithm= HA_KEY_ALG_UNDEF; + keyinfo->rec_per_key=0; + if (null_pack_length) + { + key_part_info->null_bit=0; + key_part_info->offset=hidden_null_pack_length; + key_part_info->length=null_pack_length; + key_part_info->field= new Field_string(table->record[0], + (uint32) key_part_info->length, + (uchar*) 0, + (uint) 0, + Field::NONE, + NullS, &my_charset_bin); + if (!key_part_info->field) + goto err; + key_part_info->field->init(table); + key_part_info->key_type=FIELDFLAG_BINARY; + key_part_info->type= HA_KEYTYPE_BINARY; + key_part_info++; + } + /* Create a distinct key over the columns we are going to return */ + for (i=param->hidden_field_count, reg_field=table->field + i ; + i < field_count; + i++, reg_field++, key_part_info++) + { + key_part_info->null_bit=0; + key_part_info->field= *reg_field; + key_part_info->offset= (*reg_field)->offset(table->record[0]); + key_part_info->length= (uint16) (*reg_field)->pack_length(); + key_part_info->type= (uint8) (*reg_field)->key_type(); + key_part_info->key_type = + ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT || + (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 || + (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ? + 0 : FIELDFLAG_BINARY; + } + } + + if (thd->is_fatal_error) // If end of memory + goto err; /* purecov: inspected */ + share->db_record_offset= 1; + if (share->db_type() == myisam_hton) + { + if (create_myisam_tmp_table(table,param,select_options)) + goto err; + } + if (open_tmp_table(table)) + goto err; + + thd->mem_root= mem_root_save; + + DBUG_RETURN(table); + +err: + thd->mem_root= mem_root_save; + free_tmp_table(thd,table); /* purecov: inspected */ + if (temp_pool_slot != MY_BIT_NONE) + bitmap_lock_clear_bit(&temp_pool, temp_pool_slot); + DBUG_RETURN(NULL); /* purecov: inspected */ +} + + +/****************************************************************************/ + +/** + Create a reduced TABLE object with properly set up Field list from a + list of field definitions. + + The created table doesn't have a table handler associated with + it, has no keys, no group/distinct, no copy_funcs array. + The sole purpose of this TABLE object is to use the power of Field + class to read/write data to/from table->record[0]. Then one can store + the record in any container (RB tree, hash, etc). + The table is created in THD mem_root, so are the table's fields. + Consequently, if you don't BLOB fields, you don't need to free it. + + @param thd connection handle + @param field_list list of column definitions + + @return + 0 if out of memory, TABLE object in case of success +*/ + +TABLE *create_virtual_tmp_table(THD *thd, List &field_list) +{ + uint field_count= field_list.elements; + uint blob_count= 0; + Field **field; + Create_field *cdef; /* column definition */ + uint record_length= 0; + uint null_count= 0; /* number of columns which may be null */ + uint null_pack_length; /* NULL representation array length */ + uint *blob_field; + uchar *bitmaps; + TABLE *table; + TABLE_SHARE *share; + + if (!multi_alloc_root(thd->mem_root, + &table, sizeof(*table), + &share, sizeof(*share), + &field, (field_count + 1) * sizeof(Field*), + &blob_field, (field_count+1) *sizeof(uint), + &bitmaps, bitmap_buffer_size(field_count)*2, + NullS)) + return 0; + + bzero(table, sizeof(*table)); + bzero(share, sizeof(*share)); + table->field= field; + table->s= share; + share->blob_field= blob_field; + share->fields= field_count; + share->blob_ptr_size= portable_sizeof_char_ptr; + setup_tmp_table_column_bitmaps(table, bitmaps); + + /* Create all fields and calculate the total length of record */ + List_iterator_fast it(field_list); + while ((cdef= it++)) + { + *field= make_field(share, 0, cdef->length, + (uchar*) (f_maybe_null(cdef->pack_flag) ? "" : 0), + f_maybe_null(cdef->pack_flag) ? 1 : 0, + cdef->pack_flag, cdef->sql_type, cdef->charset, + cdef->geom_type, cdef->unireg_check, + cdef->interval, cdef->field_name); + if (!*field) + goto error; + (*field)->init(table); + record_length+= (*field)->pack_length(); + if (! ((*field)->flags & NOT_NULL_FLAG)) + null_count++; + + if ((*field)->flags & BLOB_FLAG) + share->blob_field[blob_count++]= (uint) (field - table->field); + + field++; + } + *field= NULL; /* mark the end of the list */ + share->blob_field[blob_count]= 0; /* mark the end of the list */ + share->blob_fields= blob_count; + + null_pack_length= (null_count + 7)/8; + share->reclength= record_length + null_pack_length; + share->rec_buff_length= ALIGN_SIZE(share->reclength + 1); + table->record[0]= (uchar*) thd->alloc(share->rec_buff_length); + if (!table->record[0]) + goto error; + + if (null_pack_length) + { + table->null_flags= (uchar*) table->record[0]; + share->null_fields= null_count; + share->null_bytes= null_pack_length; + } + + table->in_use= thd; /* field->reset() may access table->in_use */ + { + /* Set up field pointers */ + uchar *null_pos= table->record[0]; + uchar *field_pos= null_pos + share->null_bytes; + uint null_bit= 1; + + for (field= table->field; *field; ++field) + { + Field *cur_field= *field; + if ((cur_field->flags & NOT_NULL_FLAG)) + cur_field->move_field(field_pos); + else + { + cur_field->move_field(field_pos, (uchar*) null_pos, null_bit); + null_bit<<= 1; + if (null_bit == (1 << 8)) + { + ++null_pos; + null_bit= 1; + } + } + cur_field->reset(); + + field_pos+= cur_field->pack_length(); + } + } + return table; +error: + for (field= table->field; *field; ++field) + delete *field; /* just invokes field destructor */ + return 0; +} + + +static bool open_tmp_table(TABLE *table) +{ + int error; + if ((error=table->file->ha_open(table, table->s->table_name.str,O_RDWR, + HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE))) + { + table->file->print_error(error,MYF(0)); /* purecov: inspected */ + table->db_stat=0; + return(1); + } + (void) table->file->extra(HA_EXTRA_QUICK); /* Faster */ + return(0); +} + + +static bool create_myisam_tmp_table(TABLE *table,TMP_TABLE_PARAM *param, + ulonglong options) +{ + int error; + MI_KEYDEF keydef; + MI_UNIQUEDEF uniquedef; + KEY *keyinfo=param->keyinfo; + TABLE_SHARE *share= table->s; + DBUG_ENTER("create_myisam_tmp_table"); + + if (share->keys) + { // Get keys for ni_create + bool using_unique_constraint=0; + HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&table->mem_root, + sizeof(*seg) * keyinfo->key_parts); + if (!seg) + goto err; + + bzero(seg, sizeof(*seg) * keyinfo->key_parts); + if (keyinfo->key_length >= table->file->max_key_length() || + keyinfo->key_parts > table->file->max_key_parts() || + share->uniques) + { + /* Can't create a key; Make a unique constraint instead of a key */ + share->keys= 0; + share->uniques= 1; + using_unique_constraint=1; + bzero((char*) &uniquedef,sizeof(uniquedef)); + uniquedef.keysegs=keyinfo->key_parts; + uniquedef.seg=seg; + uniquedef.null_are_equal=1; + + /* Create extra column for hash value */ + bzero((uchar*) param->recinfo,sizeof(*param->recinfo)); + param->recinfo->type= FIELD_CHECK; + param->recinfo->length=MI_UNIQUE_HASH_LENGTH; + param->recinfo++; + share->reclength+=MI_UNIQUE_HASH_LENGTH; + } + else + { + /* Create an unique key */ + bzero((char*) &keydef,sizeof(keydef)); + keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY; + keydef.keysegs= keyinfo->key_parts; + keydef.seg= seg; + } + for (uint i=0; i < keyinfo->key_parts ; i++,seg++) + { + Field *field=keyinfo->key_part[i].field; + seg->flag= 0; + seg->language= field->charset()->number; + seg->length= keyinfo->key_part[i].length; + seg->start= keyinfo->key_part[i].offset; + if (field->flags & BLOB_FLAG) + { + seg->type= + ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ? + HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2); + seg->bit_start= (uint8)(field->pack_length() - share->blob_ptr_size); + seg->flag= HA_BLOB_PART; + seg->length=0; // Whole blob in unique constraint + } + else + { + seg->type= keyinfo->key_part[i].type; + /* Tell handler if it can do suffic space compression */ + if (field->real_type() == MYSQL_TYPE_STRING && + keyinfo->key_part[i].length > 4) + seg->flag|= HA_SPACE_PACK; + } + if (!(field->flags & NOT_NULL_FLAG)) + { + seg->null_bit= field->null_bit; + seg->null_pos= (uint) (field->null_ptr - (uchar*) table->record[0]); + /* + We are using a GROUP BY on something that contains NULL + In this case we have to tell MyISAM that two NULL should + on INSERT be regarded at the same value + */ + if (!using_unique_constraint) + keydef.flag|= HA_NULL_ARE_EQUAL; + } + } + } + MI_CREATE_INFO create_info; + bzero((char*) &create_info,sizeof(create_info)); + + if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == + OPTION_BIG_TABLES) + create_info.data_file_length= ~(ulonglong) 0; + + if ((error=mi_create(share->table_name.str, share->keys, &keydef, + (uint) (param->recinfo-param->start_recinfo), + param->start_recinfo, + share->uniques, &uniquedef, + &create_info, + HA_CREATE_TMP_TABLE))) + { + table->file->print_error(error,MYF(0)); /* purecov: inspected */ + table->db_stat=0; + goto err; + } + status_var_increment(table->in_use->status_var.created_tmp_disk_tables); + share->db_record_offset= 1; + DBUG_RETURN(0); + err: + DBUG_RETURN(1); +} + + +void +free_tmp_table(THD *thd, TABLE *entry) +{ + MEM_ROOT own_root= entry->mem_root; + const char *save_proc_info; + DBUG_ENTER("free_tmp_table"); + DBUG_PRINT("enter",("table: %s",entry->alias)); + + save_proc_info=thd->proc_info; + thd_proc_info(thd, "removing tmp table"); + + // Release latches since this can take a long time + ha_release_temporary_latches(thd); + + if (entry->file) + { + if (entry->db_stat) + entry->file->ha_drop_table(entry->s->table_name.str); + else + entry->file->ha_delete_table(entry->s->table_name.str); + delete entry->file; + } + + /* free blobs */ + for (Field **ptr=entry->field ; *ptr ; ptr++) + (*ptr)->free(); + free_io_cache(entry); + + if (entry->temp_pool_slot != MY_BIT_NONE) + bitmap_lock_clear_bit(&temp_pool, entry->temp_pool_slot); + + plugin_unlock(0, entry->s->db_plugin); + + free_root(&own_root, MYF(0)); /* the table is allocated in its own root */ + thd_proc_info(thd, save_proc_info); + + DBUG_VOID_RETURN; +} + +/** + If a HEAP table gets full, create a MyISAM table and copy all rows + to this. +*/ + +bool create_myisam_from_heap(THD *thd, TABLE *table, TMP_TABLE_PARAM *param, + int error, bool ignore_last_dupp_key_error) +{ + TABLE new_table; + TABLE_SHARE share; + const char *save_proc_info; + int write_err; + DBUG_ENTER("create_myisam_from_heap"); + + if (table->s->db_type() != heap_hton || + error != HA_ERR_RECORD_FILE_FULL) + { + /* + We don't want this error to be converted to a warning, e.g. in case of + INSERT IGNORE ... SELECT. + */ + thd->fatal_error(); + table->file->print_error(error,MYF(0)); + DBUG_RETURN(1); + } + + // Release latches since this can take a long time + ha_release_temporary_latches(thd); + + new_table= *table; + share= *table->s; + new_table.s= &share; + new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton); + if (!(new_table.file= get_new_handler(&share, &new_table.mem_root, + new_table.s->db_type()))) + DBUG_RETURN(1); // End of memory + + save_proc_info=thd->proc_info; + thd_proc_info(thd, "converting HEAP to MyISAM"); + + if (create_myisam_tmp_table(&new_table, param, + thd->lex->select_lex.options | thd->options)) + goto err2; + if (open_tmp_table(&new_table)) + goto err1; + if (table->file->indexes_are_disabled()) + new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL); + table->file->ha_index_or_rnd_end(); + table->file->ha_rnd_init(1); + if (table->no_rows) + { + new_table.file->extra(HA_EXTRA_NO_ROWS); + new_table.no_rows=1; + } + +#ifdef TO_BE_DONE_LATER_IN_4_1 + /* + To use start_bulk_insert() (which is new in 4.1) we need to find + all places where a corresponding end_bulk_insert() should be put. + */ + table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */ + new_table.file->ha_start_bulk_insert(table->file->stats.records); +#else + /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */ + new_table.file->extra(HA_EXTRA_WRITE_CACHE); +#endif + + /* + copy all old rows from heap table to MyISAM table + This is the only code that uses record[1] to read/write but this + is safe as this is a temporary MyISAM table without timestamp/autoincrement + or partitioning. + */ + while (!table->file->rnd_next(new_table.record[1])) + { + write_err= new_table.file->ha_write_row(new_table.record[1]); + DBUG_EXECUTE_IF("raise_error", write_err= HA_ERR_FOUND_DUPP_KEY ;); + if (write_err) + goto err; + } + /* copy row that filled HEAP table */ + if ((write_err=new_table.file->ha_write_row(table->record[0]))) + { + if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) || + !ignore_last_dupp_key_error) + goto err; + } + + /* remove heap table and change to use myisam table */ + (void) table->file->ha_rnd_end(); + (void) table->file->close(); // This deletes the table ! + delete table->file; + table->file=0; + plugin_unlock(0, table->s->db_plugin); + share.db_plugin= my_plugin_lock(0, &share.db_plugin); + new_table.s= table->s; // Keep old share + *table= new_table; + *table->s= share; + + table->file->change_table_ptr(table, table->s); + table->use_all_columns(); + if (save_proc_info) + thd_proc_info(thd, (!strcmp(save_proc_info,"Copying to tmp table") ? + "Copying to tmp table on disk" : save_proc_info)); + DBUG_RETURN(0); + + err: + DBUG_PRINT("error",("Got error: %d",write_err)); + table->file->print_error(write_err, MYF(0)); + (void) table->file->ha_rnd_end(); + (void) new_table.file->close(); + err1: + new_table.file->ha_delete_table(new_table.s->table_name.str); + err2: + delete new_table.file; + thd_proc_info(thd, save_proc_info); + table->mem_root= new_table.mem_root; + DBUG_RETURN(1); +} + + +/** + @details + Rows produced by a join sweep may end up in a temporary table or be sent + to a client. Setup the function of the nested loop join algorithm which + handles final fully constructed and matched records. + + @param join join to setup the function for. + + @return + end_select function to use. This function can't fail. +*/ + +Next_select_func setup_end_select_func(JOIN *join) +{ + TABLE *table= join->tmp_table; + TMP_TABLE_PARAM *tmp_tbl= &join->tmp_table_param; + Next_select_func end_select; + + /* Set up select_end */ + if (table) + { + if (table->group && tmp_tbl->sum_func_count && + !tmp_tbl->precomputed_group_by) + { + if (table->s->keys) + { + DBUG_PRINT("info",("Using end_update")); + end_select=end_update; + } + else + { + DBUG_PRINT("info",("Using end_unique_update")); + end_select=end_unique_update; + } + } + else if (join->sort_and_group && !tmp_tbl->precomputed_group_by) + { + DBUG_PRINT("info",("Using end_write_group")); + end_select=end_write_group; + } + else + { + DBUG_PRINT("info",("Using end_write")); + end_select=end_write; + if (tmp_tbl->precomputed_group_by) + { + /* + A preceding call to create_tmp_table in the case when loose + index scan is used guarantees that + TMP_TABLE_PARAM::items_to_copy has enough space for the group + by functions. It is OK here to use memcpy since we copy + Item_sum pointers into an array of Item pointers. + */ + memcpy(tmp_tbl->items_to_copy + tmp_tbl->func_count, + join->sum_funcs, + sizeof(Item*)*tmp_tbl->sum_func_count); + tmp_tbl->items_to_copy[tmp_tbl->func_count+tmp_tbl->sum_func_count]= 0; + } + } + } + else + { + if ((join->sort_and_group || + (join->procedure && join->procedure->flags & PROC_GROUP)) && + !tmp_tbl->precomputed_group_by) + end_select= end_send_group; + else + end_select= end_send; + } + return end_select; +} + + +/** + Make a join of all tables and write it on socket or to table. + + @retval + 0 if ok + @retval + 1 if error is sent + @retval + -1 if error should be sent +*/ + +static int +do_select(JOIN *join,List *fields,TABLE *table,Procedure *procedure) +{ + int rc= 0; + enum_nested_loop_state error= NESTED_LOOP_OK; + JOIN_TAB *join_tab= NULL; + DBUG_ENTER("do_select"); + + join->procedure=procedure; + join->tmp_table= table; /* Save for easy recursion */ + join->fields= fields; + + if (table) + { + VOID(table->file->extra(HA_EXTRA_WRITE_CACHE)); + empty_record(table); + if (table->group && join->tmp_table_param.sum_func_count && + table->s->keys && !table->file->inited) + table->file->ha_index_init(0, 0); + } + /* Set up select_end */ + Next_select_func end_select= setup_end_select_func(join); + if (join->tables) + { + join->join_tab[join->tables-1].next_select= end_select; + + join_tab=join->join_tab+join->const_tables; + } + join->send_records=0; + if (join->tables == join->const_tables) + { + /* + HAVING will be checked after processing aggregate functions, + But WHERE should checkd here (we alredy have read tables) + */ + if (!join->conds || join->conds->val_int()) + { + error= (*end_select)(join, 0, 0); + if (error == NESTED_LOOP_OK || error == NESTED_LOOP_QUERY_LIMIT) + error= (*end_select)(join, 0, 1); + + /* + If we don't go through evaluate_join_record(), do the counting + here. join->send_records is increased on success in end_send(), + so we don't touch it here. + */ + join->examined_rows++; + join->thd->row_count++; + DBUG_ASSERT(join->examined_rows <= 1); + } + else if (join->send_row_on_empty_set()) + { + List *columns_list= (procedure ? &join->procedure_fields_list : + fields); + rc= join->result->send_data(*columns_list); + } + } + else + { + DBUG_ASSERT(join->tables); + error= sub_select(join,join_tab,0); + if (error == NESTED_LOOP_OK || error == NESTED_LOOP_NO_MORE_ROWS) + error= sub_select(join,join_tab,1); + if (error == NESTED_LOOP_QUERY_LIMIT) + error= NESTED_LOOP_OK; /* select_limit used */ + } + if (error == NESTED_LOOP_NO_MORE_ROWS) + error= NESTED_LOOP_OK; + + if (error == NESTED_LOOP_OK) + { + /* + Sic: this branch works even if rc != 0, e.g. when + send_data above returns an error. + */ + if (!table) // If sending data to client + { + /* + The following will unlock all cursors if the command wasn't an + update command + */ + join->join_free(); // Unlock all cursors + if (join->result->send_eof()) + rc= 1; // Don't send error + } + DBUG_PRINT("info",("%ld records output", (long) join->send_records)); + } + else + rc= -1; + if (table) + { + int tmp, new_errno= 0; + if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE))) + { + DBUG_PRINT("error",("extra(HA_EXTRA_NO_CACHE) failed")); + new_errno= tmp; + } + if ((tmp=table->file->ha_index_or_rnd_end())) + { + DBUG_PRINT("error",("ha_index_or_rnd_end() failed")); + new_errno= tmp; + } + if (new_errno) + table->file->print_error(new_errno,MYF(0)); + } +#ifndef DBUG_OFF + if (rc) + { + DBUG_PRINT("error",("Error: do_select() failed")); + } +#endif + DBUG_RETURN(join->thd->is_error() ? -1 : rc); +} + + +enum_nested_loop_state +sub_select_cache(JOIN *join,JOIN_TAB *join_tab,bool end_of_records) +{ + enum_nested_loop_state rc; + + if (end_of_records) + { + rc= flush_cached_records(join,join_tab,FALSE); + if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS) + rc= sub_select(join,join_tab,end_of_records); + return rc; + } + if (join->thd->killed) // If aborted by user + { + join->thd->send_kill_message(); + return NESTED_LOOP_KILLED; /* purecov: inspected */ + } + if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0) + { + if (!store_record_in_cache(&join_tab->cache)) + return NESTED_LOOP_OK; // There is more room in cache + return flush_cached_records(join,join_tab,FALSE); + } + rc= flush_cached_records(join, join_tab, TRUE); + if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS) + rc= sub_select(join, join_tab, end_of_records); + return rc; +} + +/** + Retrieve records ends with a given beginning from the result of a join. + + For a given partial join record consisting of records from the tables + preceding the table join_tab in the execution plan, the function + retrieves all matching full records from the result set and + send them to the result set stream. + + @note + The function effectively implements the final (n-k) nested loops + of nested loops join algorithm, where k is the ordinal number of + the join_tab table and n is the total number of tables in the join query. + It performs nested loops joins with all conjunctive predicates from + the where condition pushed as low to the tables as possible. + E.g. for the query + @code + SELECT * FROM t1,t2,t3 + WHERE t1.a=t2.a AND t2.b=t3.b AND t1.a BETWEEN 5 AND 9 + @endcode + the predicate (t1.a BETWEEN 5 AND 9) will be pushed to table t1, + given the selected plan prescribes to nest retrievals of the + joined tables in the following order: t1,t2,t3. + A pushed down predicate are attached to the table which it pushed to, + at the field join_tab->select_cond. + When executing a nested loop of level k the function runs through + the rows of 'join_tab' and for each row checks the pushed condition + attached to the table. + If it is false the function moves to the next row of the + table. If the condition is true the function recursively executes (n-k-1) + remaining embedded nested loops. + The situation becomes more complicated if outer joins are involved in + the execution plan. In this case the pushed down predicates can be + checked only at certain conditions. + Suppose for the query + @code + SELECT * FROM t1 LEFT JOIN (t2,t3) ON t3.a=t1.a + WHERE t1>2 AND (t2.b>5 OR t2.b IS NULL) + @endcode + the optimizer has chosen a plan with the table order t1,t2,t3. + The predicate P1=t1>2 will be pushed down to the table t1, while the + predicate P2=(t2.b>5 OR t2.b IS NULL) will be attached to the table + t2. But the second predicate can not be unconditionally tested right + after a row from t2 has been read. This can be done only after the + first row with t3.a=t1.a has been encountered. + Thus, the second predicate P2 is supplied with a guarded value that are + stored in the field 'found' of the first inner table for the outer join + (table t2). When the first row with t3.a=t1.a for the current row + of table t1 appears, the value becomes true. For now on the predicate + is evaluated immediately after the row of table t2 has been read. + When the first row with t3.a=t1.a has been encountered all + conditions attached to the inner tables t2,t3 must be evaluated. + Only when all of them are true the row is sent to the output stream. + If not, the function returns to the lowest nest level that has a false + attached condition. + The predicates from on expressions are also pushed down. If in the + the above example the on expression were (t3.a=t1.a AND t2.a=t1.a), + then t1.a=t2.a would be pushed down to table t2, and without any + guard. + If after the run through all rows of table t2, the first inner table + for the outer join operation, it turns out that no matches are + found for the current row of t1, then current row from table t1 + is complemented by nulls for t2 and t3. Then the pushed down predicates + are checked for the composed row almost in the same way as it had + been done for the first row with a match. The only difference is + the predicates from on expressions are not checked. + + @par + @b IMPLEMENTATION + @par + The function forms output rows for a current partial join of k + tables tables recursively. + For each partial join record ending with a certain row from + join_tab it calls sub_select that builds all possible matching + tails from the result set. + To be able check predicates conditionally items of the class + Item_func_trig_cond are employed. + An object of this class is constructed from an item of class COND + and a pointer to a guarding boolean variable. + When the value of the guard variable is true the value of the object + is the same as the value of the predicate, otherwise it's just returns + true. + To carry out a return to a nested loop level of join table t the pointer + to t is remembered in the field 'return_tab' of the join structure. + Consider the following query: + @code + SELECT * FROM t1, + LEFT JOIN + (t2, t3 LEFT JOIN (t4,t5) ON t5.a=t3.a) + ON t4.a=t2.a + WHERE (t2.b=5 OR t2.b IS NULL) AND (t4.b=2 OR t4.b IS NULL) + @endcode + Suppose the chosen execution plan dictates the order t1,t2,t3,t4,t5 + and suppose for a given joined rows from tables t1,t2,t3 there are + no rows in the result set yet. + When first row from t5 that satisfies the on condition + t5.a=t3.a is found, the pushed down predicate t4.b=2 OR t4.b IS NULL + becomes 'activated', as well the predicate t4.a=t2.a. But + the predicate (t2.b=5 OR t2.b IS NULL) can not be checked until + t4.a=t2.a becomes true. + In order not to re-evaluate the predicates that were already evaluated + as attached pushed down predicates, a pointer to the the first + most inner unmatched table is maintained in join_tab->first_unmatched. + Thus, when the first row from t5 with t5.a=t3.a is found + this pointer for t5 is changed from t4 to t2. + + @par + @b STRUCTURE @b NOTES + @par + join_tab->first_unmatched points always backwards to the first inner + table of the embedding nested join, if any. + + @param join pointer to the structure providing all context info for + the query + @param join_tab the first next table of the execution plan to be retrieved + @param end_records true when we need to perform final steps of retrival + + @return + return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS. +*/ + +enum_nested_loop_state +sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records) +{ + join_tab->table->null_row=0; + if (end_of_records) + return (*join_tab->next_select)(join,join_tab+1,end_of_records); + + int error; + enum_nested_loop_state rc; + READ_RECORD *info= &join_tab->read_record; + + if (join->resume_nested_loop) + { + /* If not the last table, plunge down the nested loop */ + if (join_tab < join->join_tab + join->tables - 1) + rc= (*join_tab->next_select)(join, join_tab + 1, 0); + else + { + join->resume_nested_loop= FALSE; + rc= NESTED_LOOP_OK; + } + } + else + { + join->return_tab= join_tab; + + if (join_tab->last_inner) + { + /* join_tab is the first inner table for an outer join operation. */ + + /* Set initial state of guard variables for this table.*/ + join_tab->found=0; + join_tab->not_null_compl= 1; + + /* Set first_unmatched for the last inner table of this group */ + join_tab->last_inner->first_unmatched= join_tab; + } + join->thd->row_count= 0; + + error= (*join_tab->read_first_record)(join_tab); + rc= evaluate_join_record(join, join_tab, error); + } + + while (rc == NESTED_LOOP_OK) + { + error= info->read_record(info); + rc= evaluate_join_record(join, join_tab, error); + } + + if (rc == NESTED_LOOP_NO_MORE_ROWS && + join_tab->last_inner && !join_tab->found) + rc= evaluate_null_complemented_join_record(join, join_tab); + + if (rc == NESTED_LOOP_NO_MORE_ROWS) + rc= NESTED_LOOP_OK; + return rc; +} + + +/** + Process one record of the nested loop join. + + This function will evaluate parts of WHERE/ON clauses that are + applicable to the partial record on hand and in case of success + submit this record to the next level of the nested loop. +*/ + +static enum_nested_loop_state +evaluate_join_record(JOIN *join, JOIN_TAB *join_tab, + int error) +{ + bool not_used_in_distinct=join_tab->not_used_in_distinct; + ha_rows found_records=join->found_records; + COND *select_cond= join_tab->select_cond; + + if (error > 0 || (join->thd->is_error())) // Fatal error + return NESTED_LOOP_ERROR; + if (error < 0) + return NESTED_LOOP_NO_MORE_ROWS; + if (join->thd->killed) // Aborted by user + { + join->thd->send_kill_message(); + return NESTED_LOOP_KILLED; /* purecov: inspected */ + } + DBUG_PRINT("info", ("select cond 0x%lx", (ulong)select_cond)); + if (!select_cond || select_cond->val_int()) + { + /* + There is no select condition or the attached pushed down + condition is true => a match is found. + */ + bool found= 1; + while (join_tab->first_unmatched && found) + { + /* + The while condition is always false if join_tab is not + the last inner join table of an outer join operation. + */ + JOIN_TAB *first_unmatched= join_tab->first_unmatched; + /* + Mark that a match for current outer table is found. + This activates push down conditional predicates attached + to the all inner tables of the outer join. + */ + first_unmatched->found= 1; + for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++) + { + if (tab->table->reginfo.not_exists_optimize) + return NESTED_LOOP_NO_MORE_ROWS; + /* Check all predicates that has just been activated. */ + /* + Actually all predicates non-guarded by first_unmatched->found + will be re-evaluated again. It could be fixed, but, probably, + it's not worth doing now. + */ + if (tab->select_cond && !tab->select_cond->val_int()) + { + /* The condition attached to table tab is false */ + if (tab == join_tab) + found= 0; + else + { + /* + Set a return point if rejected predicate is attached + not to the last table of the current nest level. + */ + join->return_tab= tab; + return NESTED_LOOP_OK; + } + } + } + /* + Check whether join_tab is not the last inner table + for another embedding outer join. + */ + if ((first_unmatched= first_unmatched->first_upper) && + first_unmatched->last_inner != join_tab) + first_unmatched= 0; + join_tab->first_unmatched= first_unmatched; + } + + /* + It was not just a return to lower loop level when one + of the newly activated predicates is evaluated as false + (See above join->return_tab= tab). + */ + join->examined_rows++; + join->thd->row_count++; + DBUG_PRINT("counts", ("join->examined_rows++: %lu", + (ulong) join->examined_rows)); + + if (found) + { + enum enum_nested_loop_state rc; + /* A match from join_tab is found for the current partial join. */ + rc= (*join_tab->next_select)(join, join_tab+1, 0); + if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS) + return rc; + if (join->return_tab < join_tab) + return NESTED_LOOP_OK; + /* + Test if this was a SELECT DISTINCT query on a table that + was not in the field list; In this case we can abort if + we found a row, as no new rows can be added to the result. + */ + if (not_used_in_distinct && found_records != join->found_records) + return NESTED_LOOP_NO_MORE_ROWS; + } + else + join_tab->read_record.file->unlock_row(); + } + else + { + /* + The condition pushed down to the table join_tab rejects all rows + with the beginning coinciding with the current partial join. + */ + join->examined_rows++; + join->thd->row_count++; + join_tab->read_record.file->unlock_row(); + } + return NESTED_LOOP_OK; +} + + +/** + + @details + Construct a NULL complimented partial join record and feed it to the next + level of the nested loop. This function is used in case we have + an OUTER join and no matching record was found. +*/ + +static enum_nested_loop_state +evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab) +{ + /* + The table join_tab is the first inner table of a outer join operation + and no matches has been found for the current outer row. + */ + JOIN_TAB *last_inner_tab= join_tab->last_inner; + /* Cache variables for faster loop */ + COND *select_cond; + for ( ; join_tab <= last_inner_tab ; join_tab++) + { + /* Change the the values of guard predicate variables. */ + join_tab->found= 1; + join_tab->not_null_compl= 0; + /* The outer row is complemented by nulls for each inner tables */ + restore_record(join_tab->table,s->default_values); // Make empty record + mark_as_null_row(join_tab->table); // For group by without error + select_cond= join_tab->select_cond; + /* Check all attached conditions for inner table rows. */ + if (select_cond && !select_cond->val_int()) + return NESTED_LOOP_OK; + } + join_tab--; + /* + The row complemented by nulls might be the first row + of embedding outer joins. + If so, perform the same actions as in the code + for the first regular outer join row above. + */ + for ( ; ; ) + { + JOIN_TAB *first_unmatched= join_tab->first_unmatched; + if ((first_unmatched= first_unmatched->first_upper) && + first_unmatched->last_inner != join_tab) + first_unmatched= 0; + join_tab->first_unmatched= first_unmatched; + if (!first_unmatched) + break; + first_unmatched->found= 1; + for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++) + { + if (tab->select_cond && !tab->select_cond->val_int()) + { + join->return_tab= tab; + return NESTED_LOOP_OK; + } + } + } + /* + The row complemented by nulls satisfies all conditions + attached to inner tables. + Send the row complemented by nulls to be joined with the + remaining tables. + */ + return (*join_tab->next_select)(join, join_tab+1, 0); +} + + +static enum_nested_loop_state +flush_cached_records(JOIN *join,JOIN_TAB *join_tab,bool skip_last) +{ + enum_nested_loop_state rc= NESTED_LOOP_OK; + int error; + READ_RECORD *info; + + join_tab->table->null_row= 0; + if (!join_tab->cache.records) + return NESTED_LOOP_OK; /* Nothing to do */ + if (skip_last) + (void) store_record_in_cache(&join_tab->cache); // Must save this for later + if (join_tab->use_quick == 2) + { + if (join_tab->select->quick) + { /* Used quick select last. reset it */ + delete join_tab->select->quick; + join_tab->select->quick=0; + } + } + /* read through all records */ + if ((error=join_init_read_record(join_tab))) + { + reset_cache_write(&join_tab->cache); + return error < 0 ? NESTED_LOOP_NO_MORE_ROWS: NESTED_LOOP_ERROR; + } + + for (JOIN_TAB *tmp=join->join_tab; tmp != join_tab ; tmp++) + { + tmp->status=tmp->table->status; + tmp->table->status=0; + } + + info= &join_tab->read_record; + do + { + if (join->thd->killed) + { + join->thd->send_kill_message(); + return NESTED_LOOP_KILLED; // Aborted by user /* purecov: inspected */ + } + SQL_SELECT *select=join_tab->select; + if (rc == NESTED_LOOP_OK && + (!join_tab->cache.select || !join_tab->cache.select->skip_record())) + { + uint i; + reset_cache_read(&join_tab->cache); + for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;) + { + read_cached_record(join_tab); + if (!select || !select->skip_record()) + { + rc= (join_tab->next_select)(join,join_tab+1,0); + if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS) + { + reset_cache_write(&join_tab->cache); + return rc; + } + } + } + } + } while (!(error=info->read_record(info))); + + if (skip_last) + read_cached_record(join_tab); // Restore current record + reset_cache_write(&join_tab->cache); + if (error > 0) // Fatal error + return NESTED_LOOP_ERROR; /* purecov: inspected */ + for (JOIN_TAB *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++) + tmp2->table->status=tmp2->status; + return NESTED_LOOP_OK; +} + + +/***************************************************************************** + The different ways to read a record + Returns -1 if row was not found, 0 if row was found and 1 on errors +*****************************************************************************/ + +/** Help function when we get some an error from the table handler. */ + +int report_error(TABLE *table, int error) +{ + if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND) + { + table->status= STATUS_GARBAGE; + return -1; // key not found; ok + } + /* + Locking reads can legally return also these errors, do not + print them to the .err log + */ + if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT) + sql_print_error("Got error %d when reading table '%s'", + error, table->s->path.str); + table->file->print_error(error,MYF(0)); + return 1; +} + + +int safe_index_read(JOIN_TAB *tab) +{ + int error; + TABLE *table= tab->table; + if ((error=table->file->index_read_map(table->record[0], + tab->ref.key_buff, + make_prev_keypart_map(tab->ref.key_parts), + HA_READ_KEY_EXACT))) + return report_error(table, error); + return 0; +} + + +static int +join_read_const_table(JOIN_TAB *tab, POSITION *pos) +{ + int error; + DBUG_ENTER("join_read_const_table"); + TABLE *table=tab->table; + table->const_table=1; + table->null_row=0; + table->status=STATUS_NO_RECORD; + + if (tab->type == JT_SYSTEM) + { + if ((error=join_read_system(tab))) + { // Info for DESCRIBE + tab->info="const row not found"; + /* Mark for EXPLAIN that the row was not found */ + pos->records_read=0.0; + pos->ref_depend_map= 0; + if (!table->maybe_null || error > 0) + DBUG_RETURN(error); + } + } + else + { + if (!table->key_read && table->covering_keys.is_set(tab->ref.key) && + !table->no_keyread && + (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + tab->index= tab->ref.key; + } + error=join_read_const(tab); + if (table->key_read) + { + table->key_read=0; + table->file->extra(HA_EXTRA_NO_KEYREAD); + } + if (error) + { + tab->info="unique row not found"; + /* Mark for EXPLAIN that the row was not found */ + pos->records_read=0.0; + pos->ref_depend_map= 0; + if (!table->maybe_null || error > 0) + DBUG_RETURN(error); + } + } + if (*tab->on_expr_ref && !table->null_row) + { + if ((table->null_row= test((*tab->on_expr_ref)->val_int() == 0))) + mark_as_null_row(table); + } + if (!table->null_row) + table->maybe_null=0; + + /* Check appearance of new constant items in Item_equal objects */ + JOIN *join= tab->join; + if (join->conds) + update_const_equal_items(join->conds, tab); + TABLE_LIST *tbl; + for (tbl= join->select_lex->leaf_tables; tbl; tbl= tbl->next_leaf) + { + TABLE_LIST *embedded; + TABLE_LIST *embedding= tbl; + do + { + embedded= embedding; + if (embedded->on_expr) + update_const_equal_items(embedded->on_expr, tab); + embedding= embedded->embedding; + } + while (embedding && + embedding->nested_join->join_list.head() == embedded); + } + + DBUG_RETURN(0); +} + + +static int +join_read_system(JOIN_TAB *tab) +{ + TABLE *table= tab->table; + int error; + if (table->status & STATUS_GARBAGE) // If first read + { + if ((error=table->file->read_first_row(table->record[0], + table->s->primary_key))) + { + if (error != HA_ERR_END_OF_FILE) + return report_error(table, error); + mark_as_null_row(tab->table); + empty_record(table); // Make empty record + return -1; + } + store_record(table,record[1]); + } + else if (!table->status) // Only happens with left join + restore_record(table,record[1]); // restore old record + table->null_row=0; + return table->status ? -1 : 0; +} + + +/** + Read a table when there is at most one matching row. + + @param tab Table to read + + @retval + 0 Row was found + @retval + -1 Row was not found + @retval + 1 Got an error (other than row not found) during read +*/ + +static int +join_read_const(JOIN_TAB *tab) +{ + int error; + TABLE *table= tab->table; + if (table->status & STATUS_GARBAGE) // If first read + { + table->status= 0; + if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref)) + error=HA_ERR_KEY_NOT_FOUND; + else + { + error=table->file->index_read_idx_map(table->record[0],tab->ref.key, + (uchar*) tab->ref.key_buff, + make_prev_keypart_map(tab->ref.key_parts), + HA_READ_KEY_EXACT); + } + if (error) + { + table->status= STATUS_NOT_FOUND; + mark_as_null_row(tab->table); + empty_record(table); + if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) + return report_error(table, error); + return -1; + } + store_record(table,record[1]); + } + else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join + { + table->status=0; + restore_record(table,record[1]); // restore old record + } + table->null_row=0; + return table->status ? -1 : 0; +} + + +static int +join_read_key(JOIN_TAB *tab) +{ + int error; + TABLE *table= tab->table; + + if (!table->file->inited) + { + table->file->ha_index_init(tab->ref.key, tab->sorted); + } + if (cmp_buffer_with_ref(tab) || + (table->status & (STATUS_GARBAGE | STATUS_NO_PARENT | STATUS_NULL_ROW))) + { + if (tab->ref.key_err) + { + table->status=STATUS_NOT_FOUND; + return -1; + } + error=table->file->index_read_map(table->record[0], + tab->ref.key_buff, + make_prev_keypart_map(tab->ref.key_parts), + HA_READ_KEY_EXACT); + if (error && error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) + return report_error(table, error); + } + table->null_row=0; + return table->status ? -1 : 0; +} + + +/* + ref access method implementation: "read_first" function + + SYNOPSIS + join_read_always_key() + tab JOIN_TAB of the accessed table + + DESCRIPTION + This is "read_fist" function for the "ref" access method. + + The functon must leave the index initialized when it returns. + ref_or_null access implementation depends on that. + + RETURN + 0 - Ok + -1 - Row not found + 1 - Error +*/ + +static int +join_read_always_key(JOIN_TAB *tab) +{ + int error; + TABLE *table= tab->table; + + /* Initialize the index first */ + if (!table->file->inited) + table->file->ha_index_init(tab->ref.key, tab->sorted); + + /* Perform "Late NULLs Filtering" (see internals manual for explanations) */ + for (uint i= 0 ; i < tab->ref.key_parts ; i++) + { + if ((tab->ref.null_rejecting & 1 << i) && tab->ref.items[i]->is_null()) + return -1; + } + + if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref)) + return -1; + if ((error=table->file->index_read_map(table->record[0], + tab->ref.key_buff, + make_prev_keypart_map(tab->ref.key_parts), + HA_READ_KEY_EXACT))) + { + if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) + return report_error(table, error); + return -1; /* purecov: inspected */ + } + return 0; +} + + +/** + This function is used when optimizing away ORDER BY in + SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC. +*/ + +static int +join_read_last_key(JOIN_TAB *tab) +{ + int error; + TABLE *table= tab->table; + + if (!table->file->inited) + table->file->ha_index_init(tab->ref.key, tab->sorted); + if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref)) + return -1; + if ((error=table->file->index_read_last_map(table->record[0], + tab->ref.key_buff, + make_prev_keypart_map(tab->ref.key_parts)))) + { + if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) + return report_error(table, error); + return -1; /* purecov: inspected */ + } + return 0; +} + + + /* ARGSUSED */ +static int +join_no_more_records(READ_RECORD *info __attribute__((unused))) +{ + return -1; +} + + +static int +join_read_next_same(READ_RECORD *info) +{ + int error; + TABLE *table= info->table; + JOIN_TAB *tab=table->reginfo.join_tab; + + if ((error=table->file->index_next_same(table->record[0], + tab->ref.key_buff, + tab->ref.key_length))) + { + if (error != HA_ERR_END_OF_FILE) + return report_error(table, error); + table->status= STATUS_GARBAGE; + return -1; + } + return 0; +} + + +static int +join_read_prev_same(READ_RECORD *info) +{ + int error; + TABLE *table= info->table; + JOIN_TAB *tab=table->reginfo.join_tab; + + if ((error=table->file->index_prev(table->record[0]))) + return report_error(table, error); + if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key, + tab->ref.key_length)) + { + table->status=STATUS_NOT_FOUND; + error= -1; + } + return error; +} + + +static int +join_init_quick_read_record(JOIN_TAB *tab) +{ + if (test_if_quick_select(tab) == -1) + return -1; /* No possible records */ + return join_init_read_record(tab); +} + + +int rr_sequential(READ_RECORD *info); +int init_read_record_seq(JOIN_TAB *tab) +{ + tab->read_record.read_record= rr_sequential; + if (tab->read_record.file->ha_rnd_init(1)) + return 1; + return (*tab->read_record.read_record)(&tab->read_record); +} + +static int +test_if_quick_select(JOIN_TAB *tab) +{ + delete tab->select->quick; + tab->select->quick=0; + return tab->select->test_quick_select(tab->join->thd, tab->keys, + (table_map) 0, HA_POS_ERROR, 0); +} + + +static int +join_init_read_record(JOIN_TAB *tab) +{ + if (tab->select && tab->select->quick && tab->select->quick->reset()) + return 1; + init_read_record(&tab->read_record, tab->join->thd, tab->table, + tab->select,1,1, FALSE); + return (*tab->read_record.read_record)(&tab->read_record); +} + + +static int +join_read_first(JOIN_TAB *tab) +{ + int error; + TABLE *table=tab->table; + if (!table->key_read && table->covering_keys.is_set(tab->index) && + !table->no_keyread) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + tab->table->status=0; + tab->read_record.read_record=join_read_next; + tab->read_record.table=table; + tab->read_record.file=table->file; + tab->read_record.index=tab->index; + tab->read_record.record=table->record[0]; + if (!table->file->inited) + table->file->ha_index_init(tab->index, tab->sorted); + if ((error=tab->table->file->index_first(tab->table->record[0]))) + { + if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) + report_error(table, error); + return -1; + } + return 0; +} + + +static int +join_read_next(READ_RECORD *info) +{ + int error; + if ((error=info->file->index_next(info->record))) + return report_error(info->table, error); + return 0; +} + + +static int +join_read_last(JOIN_TAB *tab) +{ + TABLE *table=tab->table; + int error; + if (!table->key_read && table->covering_keys.is_set(tab->index) && + !table->no_keyread) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + tab->table->status=0; + tab->read_record.read_record=join_read_prev; + tab->read_record.table=table; + tab->read_record.file=table->file; + tab->read_record.index=tab->index; + tab->read_record.record=table->record[0]; + if (!table->file->inited) + table->file->ha_index_init(tab->index, 1); + if ((error= tab->table->file->index_last(tab->table->record[0]))) + return report_error(table, error); + return 0; +} + + +static int +join_read_prev(READ_RECORD *info) +{ + int error; + if ((error= info->file->index_prev(info->record))) + return report_error(info->table, error); + return 0; +} + + +static int +join_ft_read_first(JOIN_TAB *tab) +{ + int error; + TABLE *table= tab->table; + + if (!table->file->inited) + table->file->ha_index_init(tab->ref.key, 1); +#if NOT_USED_YET + /* as ft-key doesn't use store_key's, see also FT_SELECT::init() */ + if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref)) + return -1; +#endif + table->file->ft_init(); + + if ((error= table->file->ft_read(table->record[0]))) + return report_error(table, error); + return 0; +} + +static int +join_ft_read_next(READ_RECORD *info) +{ + int error; + if ((error= info->file->ft_read(info->table->record[0]))) + return report_error(info->table, error); + return 0; +} + + +/** + Reading of key with key reference and one part that may be NULL. +*/ + +int +join_read_always_key_or_null(JOIN_TAB *tab) +{ + int res; + + /* First read according to key which is NOT NULL */ + *tab->ref.null_ref_key= 0; // Clear null byte + if ((res= join_read_always_key(tab)) >= 0) + return res; + + /* Then read key with null value */ + *tab->ref.null_ref_key= 1; // Set null byte + return safe_index_read(tab); +} + + +int +join_read_next_same_or_null(READ_RECORD *info) +{ + int error; + if ((error= join_read_next_same(info)) >= 0) + return error; + JOIN_TAB *tab= info->table->reginfo.join_tab; + + /* Test if we have already done a read after null key */ + if (*tab->ref.null_ref_key) + return -1; // All keys read + *tab->ref.null_ref_key= 1; // Set null byte + return safe_index_read(tab); // then read null keys +} + + +/***************************************************************************** + DESCRIPTION + Functions that end one nested loop iteration. Different functions + are used to support GROUP BY clause and to redirect records + to a table (e.g. in case of SELECT into a temporary table) or to the + network client. + + RETURN VALUES + NESTED_LOOP_OK - the record has been successfully handled + NESTED_LOOP_ERROR - a fatal error (like table corruption) + was detected + NESTED_LOOP_KILLED - thread shutdown was requested while processing + the record + NESTED_LOOP_QUERY_LIMIT - the record has been successfully handled; + additionally, the nested loop produced the + number of rows specified in the LIMIT clause + for the query + NESTED_LOOP_CURSOR_LIMIT - the record has been successfully handled; + additionally, there is a cursor and the nested + loop algorithm produced the number of rows + that is specified for current cursor fetch + operation. + All return values except NESTED_LOOP_OK abort the nested loop. +*****************************************************************************/ + +/* ARGSUSED */ +static enum_nested_loop_state +end_send(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), + bool end_of_records) +{ + DBUG_ENTER("end_send"); + if (!end_of_records) + { + int error; + if (join->having && join->having->val_int() == 0) + DBUG_RETURN(NESTED_LOOP_OK); // Didn't match having + error=0; + if (join->procedure) + error=join->procedure->send_row(join->procedure_fields_list); + else if (join->do_send_rows) + error=join->result->send_data(*join->fields); + if (error) + DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */ + if (++join->send_records >= join->unit->select_limit_cnt && + join->do_send_rows) + { + if (join->select_options & OPTION_FOUND_ROWS) + { + JOIN_TAB *jt=join->join_tab; + if ((join->tables == 1) && !join->tmp_table && !join->sort_and_group + && !join->send_group_parts && !join->having && !jt->select_cond && + !(jt->select && jt->select->quick) && + (jt->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && + (jt->ref.key < 0)) + { + /* Join over all rows in table; Return number of found rows */ + TABLE *table=jt->table; + + join->select_options ^= OPTION_FOUND_ROWS; + if (table->sort.record_pointers || + (table->sort.io_cache && my_b_inited(table->sort.io_cache))) + { + /* Using filesort */ + join->send_records= table->sort.found_records; + } + else + { + table->file->info(HA_STATUS_VARIABLE); + join->send_records= table->file->stats.records; + } + } + else + { + join->do_send_rows= 0; + if (join->unit->fake_select_lex) + join->unit->fake_select_lex->select_limit= 0; + DBUG_RETURN(NESTED_LOOP_OK); + } + } + DBUG_RETURN(NESTED_LOOP_QUERY_LIMIT); // Abort nicely + } + else if (join->send_records >= join->fetch_limit) + { + /* + There is a server side cursor and all rows for + this fetch request are sent. + */ + DBUG_RETURN(NESTED_LOOP_CURSOR_LIMIT); + } + } + else + { + if (join->procedure && join->procedure->end_of_records()) + DBUG_RETURN(NESTED_LOOP_ERROR); + } + DBUG_RETURN(NESTED_LOOP_OK); +} + + + /* ARGSUSED */ +static enum_nested_loop_state +end_send_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), + bool end_of_records) +{ + int idx= -1; + enum_nested_loop_state ok_code= NESTED_LOOP_OK; + DBUG_ENTER("end_send_group"); + + if (!join->first_record || end_of_records || + (idx=test_if_group_changed(join->group_fields)) >= 0) + { + if (join->first_record || + (end_of_records && !join->group && !join->group_optimized_away)) + { + if (join->procedure) + join->procedure->end_group(); + if (idx < (int) join->send_group_parts) + { + int error=0; + if (join->procedure) + { + if (join->having && join->having->val_int() == 0) + error= -1; // Didn't satisfy having + else + { + if (join->do_send_rows) + error=join->procedure->send_row(*join->fields) ? 1 : 0; + join->send_records++; + } + if (end_of_records && join->procedure->end_of_records()) + error= 1; // Fatal error + } + else + { + if (!join->first_record) + { + List_iterator_fast it(*join->fields); + Item *item; + /* No matching rows for group function */ + join->clear(); + + while ((item= it++)) + item->no_rows_in_result(); + } + if (join->having && join->having->val_int() == 0) + error= -1; // Didn't satisfy having + else + { + if (join->do_send_rows) + error=join->result->send_data(*join->fields) ? 1 : 0; + join->send_records++; + } + if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0) + { + if (join->rollup_send_data((uint) (idx+1))) + error= 1; + } + } + if (error > 0) + DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */ + if (end_of_records) + DBUG_RETURN(NESTED_LOOP_OK); + if (join->send_records >= join->unit->select_limit_cnt && + join->do_send_rows) + { + if (!(join->select_options & OPTION_FOUND_ROWS)) + DBUG_RETURN(NESTED_LOOP_QUERY_LIMIT); // Abort nicely + join->do_send_rows=0; + join->unit->select_limit_cnt = HA_POS_ERROR; + } + else if (join->send_records >= join->fetch_limit) + { + /* + There is a server side cursor and all rows + for this fetch request are sent. + */ + /* + Preventing code duplication. When finished with the group reset + the group functions and copy_fields. We fall through. bug #11904 + */ + ok_code= NESTED_LOOP_CURSOR_LIMIT; + } + } + } + else + { + if (end_of_records) + DBUG_RETURN(NESTED_LOOP_OK); + join->first_record=1; + VOID(test_if_group_changed(join->group_fields)); + } + if (idx < (int) join->send_group_parts) + { + /* + This branch is executed also for cursors which have finished their + fetch limit - the reason for ok_code. + */ + copy_fields(&join->tmp_table_param); + if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1])) + DBUG_RETURN(NESTED_LOOP_ERROR); + if (join->procedure) + join->procedure->add(); + DBUG_RETURN(ok_code); + } + } + if (update_sum_func(join->sum_funcs)) + DBUG_RETURN(NESTED_LOOP_ERROR); + if (join->procedure) + join->procedure->add(); + DBUG_RETURN(NESTED_LOOP_OK); +} + + + /* ARGSUSED */ +static enum_nested_loop_state +end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), + bool end_of_records) +{ + TABLE *table=join->tmp_table; + DBUG_ENTER("end_write"); + + if (join->thd->killed) // Aborted by user + { + join->thd->send_kill_message(); + DBUG_RETURN(NESTED_LOOP_KILLED); /* purecov: inspected */ + } + if (!end_of_records) + { + copy_fields(&join->tmp_table_param); + copy_funcs(join->tmp_table_param.items_to_copy); +#ifdef TO_BE_DELETED + if (!table->uniques) // If not unique handling + { + /* Copy null values from group to row */ + ORDER *group; + for (group=table->group ; group ; group=group->next) + { + Item *item= *group->item; + if (item->maybe_null) + { + Field *field=item->get_tmp_table_field(); + field->ptr[-1]= (uchar) (field->is_null() ? 1 : 0); + } + } + } +#endif + if (!join->having || join->having->val_int()) + { + int error; + join->found_records++; + if ((error=table->file->ha_write_row(table->record[0]))) + { + if (!table->file->is_fatal_error(error, HA_CHECK_DUP)) + goto end; + if (create_myisam_from_heap(join->thd, table, &join->tmp_table_param, + error,1)) + DBUG_RETURN(NESTED_LOOP_ERROR); // Not a table_is_full error + table->s->uniques=0; // To ensure rows are the same + } + if (++join->send_records >= join->tmp_table_param.end_write_records && + join->do_send_rows) + { + if (!(join->select_options & OPTION_FOUND_ROWS)) + DBUG_RETURN(NESTED_LOOP_QUERY_LIMIT); + join->do_send_rows=0; + join->unit->select_limit_cnt = HA_POS_ERROR; + DBUG_RETURN(NESTED_LOOP_OK); + } + } + } +end: + DBUG_RETURN(NESTED_LOOP_OK); +} + +/* ARGSUSED */ +/** Group by searching after group record and updating it if possible. */ + +static enum_nested_loop_state +end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), + bool end_of_records) +{ + TABLE *table=join->tmp_table; + ORDER *group; + int error; + DBUG_ENTER("end_update"); + + if (end_of_records) + DBUG_RETURN(NESTED_LOOP_OK); + if (join->thd->killed) // Aborted by user + { + join->thd->send_kill_message(); + DBUG_RETURN(NESTED_LOOP_KILLED); /* purecov: inspected */ + } + + join->found_records++; + copy_fields(&join->tmp_table_param); // Groups are copied twice. + /* Make a key of group index */ + for (group=table->group ; group ; group=group->next) + { + Item *item= *group->item; + item->save_org_in_field(group->field); + /* Store in the used key if the field was 0 */ + if (item->maybe_null) + group->buff[-1]= (char) group->field->is_null(); + } + if (!table->file->index_read_map(table->record[1], + join->tmp_table_param.group_buff, + HA_WHOLE_KEY, + HA_READ_KEY_EXACT)) + { /* Update old record */ + restore_record(table,record[1]); + update_tmptable_sum_func(join->sum_funcs,table); + if ((error=table->file->ha_update_row(table->record[1], + table->record[0]))) + { + table->file->print_error(error,MYF(0)); /* purecov: inspected */ + DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */ + } + DBUG_RETURN(NESTED_LOOP_OK); + } + + /* + Copy null bits from group key to table + We can't copy all data as the key may have different format + as the row data (for example as with VARCHAR keys) + */ + KEY_PART_INFO *key_part; + for (group=table->group,key_part=table->key_info[0].key_part; + group ; + group=group->next,key_part++) + { + if (key_part->null_bit) + memcpy(table->record[0]+key_part->offset, group->buff, 1); + } + init_tmptable_sum_functions(join->sum_funcs); + copy_funcs(join->tmp_table_param.items_to_copy); + if ((error=table->file->ha_write_row(table->record[0]))) + { + if (create_myisam_from_heap(join->thd, table, &join->tmp_table_param, + error, 0)) + DBUG_RETURN(NESTED_LOOP_ERROR); // Not a table_is_full error + /* Change method to update rows */ + table->file->ha_index_init(0, 0); + join->join_tab[join->tables-1].next_select=end_unique_update; + } + join->send_records++; + DBUG_RETURN(NESTED_LOOP_OK); +} + + +/** Like end_update, but this is done with unique constraints instead of keys. */ + +static enum_nested_loop_state +end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), + bool end_of_records) +{ + TABLE *table=join->tmp_table; + int error; + DBUG_ENTER("end_unique_update"); + + if (end_of_records) + DBUG_RETURN(NESTED_LOOP_OK); + if (join->thd->killed) // Aborted by user + { + join->thd->send_kill_message(); + DBUG_RETURN(NESTED_LOOP_KILLED); /* purecov: inspected */ + } + + init_tmptable_sum_functions(join->sum_funcs); + copy_fields(&join->tmp_table_param); // Groups are copied twice. + copy_funcs(join->tmp_table_param.items_to_copy); + + if (!(error=table->file->ha_write_row(table->record[0]))) + join->send_records++; // New group + else + { + if ((int) table->file->get_dup_key(error) < 0) + { + table->file->print_error(error,MYF(0)); /* purecov: inspected */ + DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */ + } + if (table->file->rnd_pos(table->record[1],table->file->dup_ref)) + { + table->file->print_error(error,MYF(0)); /* purecov: inspected */ + DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */ + } + restore_record(table,record[1]); + update_tmptable_sum_func(join->sum_funcs,table); + if ((error=table->file->ha_update_row(table->record[1], + table->record[0]))) + { + table->file->print_error(error,MYF(0)); /* purecov: inspected */ + DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */ + } + } + DBUG_RETURN(NESTED_LOOP_OK); +} + + + /* ARGSUSED */ +static enum_nested_loop_state +end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), + bool end_of_records) +{ + TABLE *table=join->tmp_table; + int idx= -1; + DBUG_ENTER("end_write_group"); + + if (join->thd->killed) + { // Aborted by user + join->thd->send_kill_message(); + DBUG_RETURN(NESTED_LOOP_KILLED); /* purecov: inspected */ + } + if (!join->first_record || end_of_records || + (idx=test_if_group_changed(join->group_fields)) >= 0) + { + if (join->first_record || (end_of_records && !join->group)) + { + if (join->procedure) + join->procedure->end_group(); + int send_group_parts= join->send_group_parts; + if (idx < send_group_parts) + { + if (!join->first_record) + { + /* No matching rows for group function */ + join->clear(); + } + copy_sum_funcs(join->sum_funcs, + join->sum_funcs_end[send_group_parts]); + if (!join->having || join->having->val_int()) + { + int error= table->file->ha_write_row(table->record[0]); + if (error && create_myisam_from_heap(join->thd, table, + &join->tmp_table_param, + error, 0)) + DBUG_RETURN(NESTED_LOOP_ERROR); + } + if (join->rollup.state != ROLLUP::STATE_NONE) + { + if (join->rollup_write_data((uint) (idx+1), table)) + DBUG_RETURN(NESTED_LOOP_ERROR); + } + if (end_of_records) + DBUG_RETURN(NESTED_LOOP_OK); + } + } + else + { + if (end_of_records) + DBUG_RETURN(NESTED_LOOP_OK); + join->first_record=1; + VOID(test_if_group_changed(join->group_fields)); + } + if (idx < (int) join->send_group_parts) + { + copy_fields(&join->tmp_table_param); + copy_funcs(join->tmp_table_param.items_to_copy); + if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1])) + DBUG_RETURN(NESTED_LOOP_ERROR); + if (join->procedure) + join->procedure->add(); + DBUG_RETURN(NESTED_LOOP_OK); + } + } + if (update_sum_func(join->sum_funcs)) + DBUG_RETURN(NESTED_LOOP_ERROR); + if (join->procedure) + join->procedure->add(); + DBUG_RETURN(NESTED_LOOP_OK); +} + + +/***************************************************************************** + Remove calculation with tables that aren't yet read. Remove also tests + against fields that are read through key where the table is not a + outer join table. + We can't remove tests that are made against columns which are stored + in sorted order. +*****************************************************************************/ + +/** + @return + 1 if right_item is used removable reference key on left_item +*/ + +static bool test_if_ref(Item_field *left_item,Item *right_item) +{ + Field *field=left_item->field; + // No need to change const test. We also have to keep tests on LEFT JOIN + if (!field->table->const_table && !field->table->maybe_null) + { + Item *ref_item=part_of_refkey(field->table,field); + if (ref_item && ref_item->eq(right_item,1)) + { + right_item= right_item->real_item(); + if (right_item->type() == Item::FIELD_ITEM) + return (field->eq_def(((Item_field *) right_item)->field)); + /* remove equalities injected by IN->EXISTS transformation */ + else if (right_item->type() == Item::CACHE_ITEM) + return ((Item_cache *)right_item)->eq_def (field); + if (right_item->const_item() && !(right_item->is_null())) + { + /* + We can remove binary fields and numerical fields except float, + as float comparison isn't 100 % secure + We have to keep normal strings to be able to check for end spaces + */ + if (field->binary() && + field->real_type() != MYSQL_TYPE_STRING && + field->real_type() != MYSQL_TYPE_VARCHAR && + (field->type() != MYSQL_TYPE_FLOAT || field->decimals() == 0)) + { + return !store_val_in_field(field, right_item, CHECK_FIELD_WARN); + } + } + } + } + return 0; // keep test +} + + +static COND * +make_cond_for_table(COND *cond, table_map tables, table_map used_table) +{ + if (used_table && !(cond->used_tables() & used_table)) + return (COND*) 0; // Already checked + if (cond->type() == Item::COND_ITEM) + { + if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) + { + /* Create new top level AND item */ + Item_cond_and *new_cond=new Item_cond_and; + if (!new_cond) + return (COND*) 0; // OOM /* purecov: inspected */ + List_iterator li(*((Item_cond*) cond)->argument_list()); + Item *item; + while ((item=li++)) + { + Item *fix=make_cond_for_table(item,tables,used_table); + if (fix) + new_cond->argument_list()->push_back(fix); + } + switch (new_cond->argument_list()->elements) { + case 0: + return (COND*) 0; // Always true + case 1: + return new_cond->argument_list()->head(); + default: + /* + Item_cond_and do not need fix_fields for execution, its parameters + are fixed or do not need fix_fields, too + */ + new_cond->quick_fix_field(); + new_cond->used_tables_cache= + ((Item_cond_and*) cond)->used_tables_cache & + tables; + return new_cond; + } + } + else + { // Or list + Item_cond_or *new_cond=new Item_cond_or; + if (!new_cond) + return (COND*) 0; // OOM /* purecov: inspected */ + List_iterator li(*((Item_cond*) cond)->argument_list()); + Item *item; + while ((item=li++)) + { + Item *fix=make_cond_for_table(item,tables,0L); + if (!fix) + return (COND*) 0; // Always true + new_cond->argument_list()->push_back(fix); + } + /* + Item_cond_and do not need fix_fields for execution, its parameters + are fixed or do not need fix_fields, too + */ + new_cond->quick_fix_field(); + new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache; + new_cond->top_level_item(); + return new_cond; + } + } + + /* + Because the following test takes a while and it can be done + table_count times, we mark each item that we have examined with the result + of the test + */ + + if (cond->marker == 3 || (cond->used_tables() & ~tables)) + return (COND*) 0; // Can't check this yet + if (cond->marker == 2 || cond->eq_cmp_result() == Item::COND_OK) + return cond; // Not boolean op + + if (((Item_func*) cond)->functype() == Item_func::EQ_FUNC) + { + Item *left_item= ((Item_func*) cond)->arguments()[0]; + Item *right_item= ((Item_func*) cond)->arguments()[1]; + if (left_item->type() == Item::FIELD_ITEM && + test_if_ref((Item_field*) left_item,right_item)) + { + cond->marker=3; // Checked when read + return (COND*) 0; + } + if (right_item->type() == Item::FIELD_ITEM && + test_if_ref((Item_field*) right_item,left_item)) + { + cond->marker=3; // Checked when read + return (COND*) 0; + } + } + cond->marker=2; + return cond; +} + +static Item * +part_of_refkey(TABLE *table,Field *field) +{ + if (!table->reginfo.join_tab) + return (Item*) 0; // field from outer non-select (UPDATE,...) + + uint ref_parts=table->reginfo.join_tab->ref.key_parts; + if (ref_parts) + { + KEY_PART_INFO *key_part= + table->key_info[table->reginfo.join_tab->ref.key].key_part; + + for (uint part=0 ; part < ref_parts ; part++,key_part++) + if (field->eq(key_part->field) && + !(key_part->key_part_flag & (HA_PART_KEY_SEG | HA_NULL_PART))) + return table->reginfo.join_tab->ref.items[part]; + } + return (Item*) 0; +} + + +/** + Test if one can use the key to resolve ORDER BY. + + @param order Sort order + @param table Table to sort + @param idx Index to check + @param used_key_parts Return value for used key parts. + + + @note + used_key_parts is set to correct key parts used if return value != 0 + (On other cases, used_key_part may be changed) + Note that the value may actually be greater than the number of index + key parts. This can happen for storage engines that have the primary + key parts as a suffix for every secondary key. + + @retval + 1 key is ok. + @retval + 0 Key can't be used + @retval + -1 Reverse key can be used +*/ + +static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx, + uint *used_key_parts) +{ + KEY_PART_INFO *key_part,*key_part_end; + key_part=table->key_info[idx].key_part; + key_part_end=key_part+table->key_info[idx].key_parts; + key_part_map const_key_parts=table->const_key_parts[idx]; + int reverse=0; + my_bool on_primary_key= FALSE; + DBUG_ENTER("test_if_order_by_key"); + + for (; order ; order=order->next, const_key_parts>>=1) + { + Field *field=((Item_field*) (*order->item)->real_item())->field; + int flag; + + /* + Skip key parts that are constants in the WHERE clause. + These are already skipped in the ORDER BY by const_expression_in_where() + */ + for (; const_key_parts & 1 ; const_key_parts>>= 1) + key_part++; + + if (key_part == key_part_end) + { + /* + We are at the end of the key. Check if the engine has the primary + key as a suffix to the secondary keys. If it has continue to check + the primary key as a suffix. + */ + if (!on_primary_key && + (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) && + table->s->primary_key != MAX_KEY) + { + on_primary_key= TRUE; + key_part= table->key_info[table->s->primary_key].key_part; + key_part_end=key_part+table->key_info[table->s->primary_key].key_parts; + const_key_parts=table->const_key_parts[table->s->primary_key]; + + for (; const_key_parts & 1 ; const_key_parts>>= 1) + key_part++; + /* + The primary and secondary key parts were all const (i.e. there's + one row). The sorting doesn't matter. + */ + if (key_part == key_part_end && reverse == 0) + { + *used_key_parts= 0; + DBUG_RETURN(1); + } + } + else + DBUG_RETURN(0); + } + + if (key_part->field != field) + DBUG_RETURN(0); + + /* set flag to 1 if we can use read-next on key, else to -1 */ + flag= ((order->asc == !(key_part->key_part_flag & HA_REVERSE_SORT)) ? + 1 : -1); + if (reverse && flag != reverse) + DBUG_RETURN(0); + reverse=flag; // Remember if reverse + key_part++; + } + if (on_primary_key) + { + uint used_key_parts_secondary= table->key_info[idx].key_parts; + uint used_key_parts_pk= + (uint) (key_part - table->key_info[table->s->primary_key].key_part); + *used_key_parts= used_key_parts_pk + used_key_parts_secondary; + + if (reverse == -1 && + (!(table->file->index_flags(idx, used_key_parts_secondary - 1, 1) & + HA_READ_PREV) || + !(table->file->index_flags(table->s->primary_key, + used_key_parts_pk - 1, 1) & HA_READ_PREV))) + reverse= 0; // Index can't be used + } + else + { + *used_key_parts= (uint) (key_part - table->key_info[idx].key_part); + if (reverse == -1 && + !(table->file->index_flags(idx, *used_key_parts-1, 1) & HA_READ_PREV)) + reverse= 0; // Index can't be used + } + DBUG_RETURN(reverse); +} + + +uint find_shortest_key(TABLE *table, const key_map *usable_keys) +{ + uint min_length= (uint) ~0; + uint best= MAX_KEY; + if (!usable_keys->is_clear_all()) + { + for (uint nr=0; nr < table->s->keys ; nr++) + { + if (usable_keys->is_set(nr)) + { + if (table->key_info[nr].key_length < min_length) + { + min_length=table->key_info[nr].key_length; + best=nr; + } + } + } + } + return best; +} + +/** + Test if a second key is the subkey of the first one. + + @param key_part First key parts + @param ref_key_part Second key parts + @param ref_key_part_end Last+1 part of the second key + + @note + Second key MUST be shorter than the first one. + + @retval + 1 is a subkey + @retval + 0 no sub key +*/ + +inline bool +is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part, + KEY_PART_INFO *ref_key_part_end) +{ + for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++) + if (!key_part->field->eq(ref_key_part->field)) + return 0; + return 1; +} + +/** + Test if we can use one of the 'usable_keys' instead of 'ref' key + for sorting. + + @param ref Number of key, used for WHERE clause + @param usable_keys Keys for testing + + @return + - MAX_KEY If we can't use other key + - the number of found key Otherwise +*/ + +static uint +test_if_subkey(ORDER *order, TABLE *table, uint ref, uint ref_key_parts, + const key_map *usable_keys) +{ + uint nr; + uint min_length= (uint) ~0; + uint best= MAX_KEY; + uint not_used; + KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part; + KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts; + + for (nr= 0 ; nr < table->s->keys ; nr++) + { + if (usable_keys->is_set(nr) && + table->key_info[nr].key_length < min_length && + table->key_info[nr].key_parts >= ref_key_parts && + is_subkey(table->key_info[nr].key_part, ref_key_part, + ref_key_part_end) && + test_if_order_by_key(order, table, nr, ¬_used)) + { + min_length= table->key_info[nr].key_length; + best= nr; + } + } + return best; +} + + +/** + Check if GROUP BY/DISTINCT can be optimized away because the set is + already known to be distinct. + + Used in removing the GROUP BY/DISTINCT of the following types of + statements: + @code + SELECT [DISTINCT] ... FROM + [GROUP BY ,...] + @endcode + + If (a,b,c is distinct) + then ,{whatever} is also distinct + + This function checks if all the key parts of any of the unique keys + of the table are referenced by a list : either the select list + through find_field_in_item_list or GROUP BY list through + find_field_in_order_list. + If the above holds and the key parts cannot contain NULLs then we + can safely remove the GROUP BY/DISTINCT, + as no result set can be more distinct than an unique key. + + @param table The table to operate on. + @param find_func function to iterate over the list and search + for a field + + @retval + 1 found + @retval + 0 not found. +*/ + +static bool +list_contains_unique_index(TABLE *table, + bool (*find_func) (Field *, void *), void *data) +{ + for (uint keynr= 0; keynr < table->s->keys; keynr++) + { + if (keynr == table->s->primary_key || + (table->key_info[keynr].flags & HA_NOSAME)) + { + KEY *keyinfo= table->key_info + keynr; + KEY_PART_INFO *key_part, *key_part_end; + + for (key_part=keyinfo->key_part, + key_part_end=key_part+ keyinfo->key_parts; + key_part < key_part_end; + key_part++) + { + if (key_part->field->maybe_null() || + !find_func(key_part->field, data)) + break; + } + if (key_part == key_part_end) + return 1; + } + } + return 0; +} + + +/** + Helper function for list_contains_unique_index. + Find a field reference in a list of ORDER structures. + Finds a direct reference of the Field in the list. + + @param field The field to search for. + @param data ORDER *.The list to search in + + @retval + 1 found + @retval + 0 not found. +*/ + +static bool +find_field_in_order_list (Field *field, void *data) +{ + ORDER *group= (ORDER *) data; + bool part_found= 0; + for (ORDER *tmp_group= group; tmp_group; tmp_group=tmp_group->next) + { + Item *item= (*tmp_group->item)->real_item(); + if (item->type() == Item::FIELD_ITEM && + ((Item_field*) item)->field->eq(field)) + { + part_found= 1; + break; + } + } + return part_found; +} + + +/** + Helper function for list_contains_unique_index. + Find a field reference in a dynamic list of Items. + Finds a direct reference of the Field in the list. + + @param[in] field The field to search for. + @param[in] data List *.The list to search in + + @retval + 1 found + @retval + 0 not found. +*/ + +static bool +find_field_in_item_list (Field *field, void *data) +{ + List *fields= (List *) data; + bool part_found= 0; + List_iterator li(*fields); + Item *item; + + while ((item= li++)) + { + if (item->type() == Item::FIELD_ITEM && + ((Item_field*) item)->field->eq(field)) + { + part_found= 1; + break; + } + } + return part_found; +} + + +/** + Test if we can skip the ORDER BY by using an index. + + If we can use an index, the JOIN_TAB / tab->select struct + is changed to use the index. + + The index must cover all fields in , or it will not be considered. + + @param no_changes No changes will be made to the query plan. + + @todo + - sergeyp: Results of all index merge selects actually are ordered + by clustered PK values. + + @retval + 0 We have to use filesort to do the sorting + @retval + 1 We can use an index. +*/ + +static bool +test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit, + bool no_changes, key_map *map) +{ + int ref_key; + uint ref_key_parts; + int order_direction; + uint used_key_parts; + TABLE *table=tab->table; + SQL_SELECT *select=tab->select; + key_map usable_keys; + QUICK_SELECT_I *save_quick= 0; + DBUG_ENTER("test_if_skip_sort_order"); + LINT_INIT(ref_key_parts); + + /* + Keys disabled by ALTER TABLE ... DISABLE KEYS should have already + been taken into account. + */ + usable_keys= *map; + + for (ORDER *tmp_order=order; tmp_order ; tmp_order=tmp_order->next) + { + Item *item= (*tmp_order->item)->real_item(); + if (item->type() != Item::FIELD_ITEM) + { + usable_keys.clear_all(); + DBUG_RETURN(0); + } + usable_keys.intersect(((Item_field*) item)->field->part_of_sortkey); + if (usable_keys.is_clear_all()) + DBUG_RETURN(0); // No usable keys + } + + ref_key= -1; + /* Test if constant range in WHERE */ + if (tab->ref.key >= 0 && tab->ref.key_parts) + { + ref_key= tab->ref.key; + ref_key_parts= tab->ref.key_parts; + if (tab->type == JT_REF_OR_NULL || tab->type == JT_FT) + DBUG_RETURN(0); + } + else if (select && select->quick) // Range found by opt_range + { + int quick_type= select->quick->get_type(); + save_quick= select->quick; + /* + assume results are not ordered when index merge is used + TODO: sergeyp: Results of all index merge selects actually are ordered + by clustered PK values. + */ + + if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE || + quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || + quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) + DBUG_RETURN(0); + ref_key= select->quick->index; + ref_key_parts= select->quick->used_key_parts; + } + + if (ref_key >= 0) + { + /* + We come here when there is a REF key. + */ + if (!usable_keys.is_set(ref_key)) + { + /* + We come here when ref_key is not among usable_keys + */ + uint new_ref_key; + /* + If using index only read, only consider other possible index only + keys + */ + if (table->covering_keys.is_set(ref_key)) + usable_keys.intersect(table->covering_keys); + if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts, + &usable_keys)) < MAX_KEY) + { + /* Found key that can be used to retrieve data in sorted order */ + if (tab->ref.key >= 0) + { + /* + We'll use ref access method on key new_ref_key. In general case + the index search tuple for new_ref_key will be different (e.g. + when one index is defined as (part1, part2, ...) and another as + (part1, part2(N), ...) and the WHERE clause contains + "part1 = const1 AND part2=const2". + So we build tab->ref from scratch here. + */ + KEYUSE *keyuse= tab->keyuse; + while (keyuse->key != new_ref_key && keyuse->table == tab->table) + keyuse++; + if (create_ref_for_key(tab->join, tab, keyuse, + tab->join->const_table_map)) + DBUG_RETURN(0); + } + else + { + /* + The range optimizer constructed QUICK_RANGE for ref_key, and + we want to use instead new_ref_key as the index. We can't + just change the index of the quick select, because this may + result in an incosistent QUICK_SELECT object. Below we + create a new QUICK_SELECT from scratch so that all its + parameres are set correctly by the range optimizer. + */ + key_map new_ref_key_map; + new_ref_key_map.clear_all(); // Force the creation of quick select + new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key. + + if (select->test_quick_select(tab->join->thd, new_ref_key_map, 0, + (tab->join->select_options & + OPTION_FOUND_ROWS) ? + HA_POS_ERROR : + tab->join->unit->select_limit_cnt,0) <= + 0) + DBUG_RETURN(0); + } + ref_key= new_ref_key; + } + } + /* Check if we get the rows in requested sorted order by using the key */ + if (usable_keys.is_set(ref_key) && + (order_direction= test_if_order_by_key(order,table,ref_key, + &used_key_parts))) + goto check_reverse_order; + } + { + /* + Check whether there is an index compatible with the given order + usage of which is cheaper than usage of the ref_key index (ref_key>=0) + or a table scan. + It may be the case if ORDER/GROUP BY is used with LIMIT. + */ + uint nr; + key_map keys; + uint best_key_parts= 0; + int best_key_direction= 0; + ha_rows best_records= 0; + double read_time; + int best_key= -1; + bool is_best_covering= FALSE; + double fanout= 1; + JOIN *join= tab->join; + uint tablenr= tab - join->join_tab; + ha_rows table_records= table->file->stats.records; + bool group= join->group && order == join->group_list; + ha_rows ref_key_quick_rows= HA_POS_ERROR; + + /* + If not used with LIMIT, only use keys if the whole query can be + resolved with a key; This is because filesort() is usually faster than + retrieving all rows through an index. + */ + if (select_limit >= table_records) + { + /* + filesort() and join cache are usually faster than reading in + index order and not using join cache + */ + if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1) + DBUG_RETURN(0); + keys= *table->file->keys_to_use_for_scanning(); + keys.merge(table->covering_keys); + + /* + We are adding here also the index specified in FORCE INDEX clause, + if any. + This is to allow users to use index in ORDER BY. + */ + if (table->force_index) + keys.merge(group ? table->keys_in_use_for_group_by : + table->keys_in_use_for_order_by); + keys.intersect(usable_keys); + } + else + keys= usable_keys; + + if (ref_key >= 0 && table->covering_keys.is_set(ref_key)) + ref_key_quick_rows= table->quick_rows[ref_key]; + + read_time= join->best_positions[tablenr].read_time; + for (uint i= tablenr+1; i < join->tables; i++) + fanout*= join->best_positions[i].records_read; // fanout is always >= 1 + + for (nr=0; nr < table->s->keys ; nr++) + { + int direction; + + if (keys.is_set(nr) && + (direction= test_if_order_by_key(order, table, nr, &used_key_parts))) + { + /* + At this point we are sure that ref_key is a non-ordering + key (where "ordering key" is a key that will return rows + in the order required by ORDER BY). + */ + DBUG_ASSERT (ref_key != (int) nr); + + bool is_covering= table->covering_keys.is_set(nr) || + (nr == table->s->primary_key && + table->file->primary_key_is_clustered()); + + /* + Don't use an index scan with ORDER BY without limit. + For GROUP BY without limit always use index scan + if there is a suitable index. + Why we hold to this asymmetry hardly can be explained + rationally. It's easy to demonstrate that using + temporary table + filesort could be cheaper for grouping + queries too. + */ + if (is_covering || + select_limit != HA_POS_ERROR || + (ref_key < 0 && (group || table->force_index))) + { + double rec_per_key; + double index_scan_time; + KEY *keyinfo= tab->table->key_info+nr; + if (select_limit == HA_POS_ERROR) + select_limit= table_records; + if (group) + { + rec_per_key= used_key_parts ? keyinfo->rec_per_key[used_key_parts-1] + : 1; + set_if_bigger(rec_per_key, 1); + /* + With a grouping query each group containing on average + rec_per_key records produces only one row that will + be included into the result set. + */ + if (select_limit > table_records/rec_per_key) + select_limit= table_records; + else + select_limit= (ha_rows) (select_limit*rec_per_key); + } + /* + If tab=tk is not the last joined table tn then to get first + L records from the result set we can expect to retrieve + only L/fanout(tk,tn) where fanout(tk,tn) says how many + rows in the record set on average will match each row tk. + Usually our estimates for fanouts are too pessimistic. + So the estimate for L/fanout(tk,tn) will be too optimistic + and as result we'll choose an index scan when using ref/range + access + filesort will be cheaper. + */ + select_limit= (ha_rows) (select_limit < fanout ? + 1 : select_limit/fanout); + /* + We assume that each of the tested indexes is not correlated + with ref_key. Thus, to select first N records we have to scan + N/selectivity(ref_key) index entries. + selectivity(ref_key) = #scanned_records/#table_records = + table->quick_condition_rows/table_records. + In any case we can't select more than #table_records. + N/(table->quick_condition_rows/table_records) > table_records + <=> N > table->quick_condition_rows. + */ + if (select_limit > table->quick_condition_rows) + select_limit= table_records; + else + select_limit= (ha_rows) (select_limit * + (double) table_records / + table->quick_condition_rows); + rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1]; + set_if_bigger(rec_per_key, 1); + /* + Here we take into account the fact that rows are + accessed in sequences rec_per_key records in each. + Rows in such a sequence are supposed to be ordered + by rowid/primary key. When reading the data + in a sequence we'll touch not more pages than the + table file contains. + TODO. Use the formula for a disk sweep sequential access + to calculate the cost of accessing data rows for one + index entry. + */ + index_scan_time= select_limit/rec_per_key * + min(rec_per_key, table->file->scan_time()); + if ((ref_key < 0 && is_covering) || + (ref_key < 0 && (group || table->force_index)) || + index_scan_time < read_time) + { + ha_rows quick_records= table_records; + if ((is_best_covering && !is_covering) || + (is_covering && ref_key_quick_rows < select_limit)) + continue; + if (table->quick_keys.is_set(nr)) + quick_records= table->quick_rows[nr]; + if (best_key < 0 || + (select_limit <= min(quick_records,best_records) ? + keyinfo->key_parts < best_key_parts : + quick_records < best_records)) + { + best_key= nr; + best_key_parts= keyinfo->key_parts; + best_records= quick_records; + is_best_covering= is_covering; + best_key_direction= direction; + } + } + } + } + } + if (best_key >= 0) + { + bool quick_created= FALSE; + if (table->quick_keys.is_set(best_key) && best_key != ref_key) + { + key_map map; + map.clear_all(); // Force the creation of quick select + map.set_bit(best_key); // only best_key. + quick_created= + select->test_quick_select(join->thd, map, 0, + join->select_options & OPTION_FOUND_ROWS ? + HA_POS_ERROR : + join->unit->select_limit_cnt, + 0) > 0; + } + if (!no_changes) + { + /* + If ref_key used index tree reading only ('Using index' in EXPLAIN), + and best_key doesn't, then revert the decision. + */ + if (!table->covering_keys.is_set(best_key) && table->key_read) + { + table->key_read= 0; + table->file->extra(HA_EXTRA_NO_KEYREAD); + } + if (!quick_created) + { + tab->index= best_key; + tab->read_first_record= best_key_direction > 0 ? + join_read_first:join_read_last; + tab->type=JT_NEXT; // Read with index_first(), index_next() + if (select && select->quick) + { + delete select->quick; + select->quick= 0; + } + if (table->covering_keys.is_set(best_key)) + { + table->key_read=1; + table->file->extra(HA_EXTRA_KEYREAD); + } + table->file->ha_index_or_rnd_end(); + if (join->select_options & SELECT_DESCRIBE) + { + tab->ref.key= -1; + tab->ref.key_parts= 0; + if (select_limit < table_records) + tab->limit= select_limit; + } + } + else if (tab->type != JT_ALL) + { + /* + We're about to use a quick access to the table. + We need to change the access method so as the quick access + method is actually used. + */ + DBUG_ASSERT(tab->select->quick); + tab->type=JT_ALL; + tab->use_quick=1; + tab->ref.key= -1; + tab->ref.key_parts=0; // Don't use ref key. + tab->read_first_record= join_init_read_record; + if (tab->is_using_loose_index_scan()) + join->tmp_table_param.precomputed_group_by= TRUE; + /* + TODO: update the number of records in join->best_positions[tablenr] + */ + } + } + used_key_parts= best_key_parts; + order_direction= best_key_direction; + } + else + DBUG_RETURN(0); + } + +check_reverse_order: + if (order_direction == -1) // If ORDER BY ... DESC + { + if (select && select->quick) + { + /* + Don't reverse the sort order, if it's already done. + (In some cases test_if_order_by_key() can be called multiple times + */ + if (!select->quick->reverse_sorted()) + { + QUICK_SELECT_DESC *tmp; + int quick_type= select->quick->get_type(); + if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE || + quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT || + quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || + quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX) + { + tab->limit= 0; + select->quick= save_quick; + DBUG_RETURN(0); // Use filesort + } + + /* ORDER BY range_key DESC */ + tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick), + used_key_parts); + if (!tmp || tmp->error) + { + delete tmp; + select->quick= save_quick; + tab->limit= 0; + DBUG_RETURN(0); // Reverse sort not supported + } + select->quick=tmp; + } + } + else if (tab->type != JT_NEXT && + tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts) + { + /* + SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC + + Use a traversal function that starts by reading the last row + with key part (A) and then traverse the index backwards. + */ + tab->read_first_record= join_read_last_key; + tab->read_record.read_record= join_read_prev_same; + } + } + else if (select && select->quick) + select->quick->sorted= 1; + DBUG_RETURN(1); +} + + +/* + If not selecting by given key, create an index how records should be read + + SYNOPSIS + create_sort_index() + thd Thread handler + tab Table to sort (in join structure) + order How table should be sorted + filesort_limit Max number of rows that needs to be sorted + select_limit Max number of rows in final output + Used to decide if we should use index or not + is_order_by true if we are sorting on ORDER BY, false if GROUP BY + Used to decide if we should use index or not + + + IMPLEMENTATION + - If there is an index that can be used, 'tab' is modified to use + this index. + - If no index, create with filesort() an index file that can be used to + retrieve rows in order (should be done with 'read_record'). + The sorted data is stored in tab->table and will be freed when calling + free_io_cache(tab->table). + + RETURN VALUES + 0 ok + -1 Some fatal error + 1 No records +*/ + +static int +create_sort_index(THD *thd, JOIN *join, ORDER *order, + ha_rows filesort_limit, ha_rows select_limit, + bool is_order_by) +{ + uint length= 0; + ha_rows examined_rows; + TABLE *table; + SQL_SELECT *select; + JOIN_TAB *tab; + DBUG_ENTER("create_sort_index"); + + if (join->tables == join->const_tables) + DBUG_RETURN(0); // One row, no need to sort + tab= join->join_tab + join->const_tables; + table= tab->table; + select= tab->select; + + /* + When there is SQL_BIG_RESULT do not sort using index for GROUP BY, + and thus force sorting on disk unless a group min-max optimization + is going to be used as it is applied now only for one table queries + with covering indexes. + */ + if ((order != join->group_list || + !(join->select_options & SELECT_BIG_RESULT) || + (select && select->quick && + select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)) && + test_if_skip_sort_order(tab,order,select_limit,0, + is_order_by ? &table->keys_in_use_for_order_by : + &table->keys_in_use_for_group_by)) + DBUG_RETURN(0); + for (ORDER *ord= join->order; ord; ord= ord->next) + length++; + if (!(join->sortorder= + make_unireg_sortorder(order, &length, join->sortorder))) + goto err; /* purecov: inspected */ + + table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), + MYF(MY_WME | MY_ZEROFILL)); + table->status=0; // May be wrong if quick_select + + // If table has a range, move it to select + if (select && !select->quick && tab->ref.key >= 0) + { + if (tab->quick) + { + select->quick=tab->quick; + tab->quick=0; + /* + We can only use 'Only index' if quick key is same as ref_key + and in index_merge 'Only index' cannot be used + */ + if (table->key_read && ((uint) tab->ref.key != select->quick->index)) + { + table->key_read=0; + table->file->extra(HA_EXTRA_NO_KEYREAD); + } + } + else + { + /* + We have a ref on a const; Change this to a range that filesort + can use. + For impossible ranges (like when doing a lookup on NULL on a NOT NULL + field, quick will contain an empty record set. + */ + if (!(select->quick= (tab->type == JT_FT ? + new FT_SELECT(thd, table, tab->ref.key) : + get_quick_select_for_ref(thd, table, &tab->ref, + tab->found_records)))) + goto err; + } + } + + /* Fill schema tables with data before filesort if it's necessary */ + if ((join->select_lex->options & OPTION_SCHEMA_TABLE) && + get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX)) + goto err; + + if (table->s->tmp_table) + table->file->info(HA_STATUS_VARIABLE); // Get record count + table->sort.found_records=filesort(thd, table,join->sortorder, length, + select, filesort_limit, 0, + &examined_rows); + tab->records= table->sort.found_records; // For SQL_CALC_ROWS + if (select) + { + /* + We need to preserve tablesort's output resultset here, because + QUICK_INDEX_MERGE_SELECT::~QUICK_INDEX_MERGE_SELECT (called by + SQL_SELECT::cleanup()) may free it assuming it's the result of the quick + select operation that we no longer need. Note that all the other parts of + this data structure are cleaned up when + QUICK_INDEX_MERGE_SELECT::get_next encounters end of data, so the next + SQL_SELECT::cleanup() call changes sort.io_cache alone. + */ + IO_CACHE *tablesort_result_cache; + + tablesort_result_cache= table->sort.io_cache; + table->sort.io_cache= NULL; + + select->cleanup(); // filesort did select + tab->select= 0; + table->quick_keys.clear_all(); // as far as we cleanup select->quick + table->sort.io_cache= tablesort_result_cache; + } + tab->select_cond=0; + tab->last_inner= 0; + tab->first_unmatched= 0; + tab->type=JT_ALL; // Read with normal read_record + tab->read_first_record= join_init_read_record; + tab->join->examined_rows+=examined_rows; + if (table->key_read) // Restore if we used indexes + { + table->key_read=0; + table->file->extra(HA_EXTRA_NO_KEYREAD); + } + DBUG_RETURN(table->sort.found_records == HA_POS_ERROR); +err: + DBUG_RETURN(-1); +} + +#ifdef NOT_YET +/** + Add the HAVING criteria to table->select. +*/ + +static bool fix_having(JOIN *join, Item **having) +{ + (*having)->update_used_tables(); // Some tables may have been const + JOIN_TAB *table=&join->join_tab[join->const_tables]; + table_map used_tables= join->const_table_map | table->table->map; + + DBUG_EXECUTE("where",print_where(*having,"having", QT_ORDINARY);); + Item* sort_table_cond=make_cond_for_table(*having,used_tables,used_tables); + if (sort_table_cond) + { + if (!table->select) + if (!(table->select=new SQL_SELECT)) + return 1; + if (!table->select->cond) + table->select->cond=sort_table_cond; + else // This should never happen + if (!(table->select->cond= new Item_cond_and(table->select->cond, + sort_table_cond)) || + table->select->cond->fix_fields(join->thd, &table->select->cond)) + return 1; + table->select_cond=table->select->cond; + table->select_cond->top_level_item(); + DBUG_EXECUTE("where",print_where(table->select_cond, + "select and having", + QT_ORDINARY);); + *having=make_cond_for_table(*having,~ (table_map) 0,~used_tables); + DBUG_EXECUTE("where", + print_where(*having,"having after make_cond", QT_ORDINARY);); + } + return 0; +} +#endif + + +/***************************************************************************** + Remove duplicates from tmp table + This should be recoded to add a unique index to the table and remove + duplicates + Table is a locked single thread table + fields is the number of fields to check (from the end) +*****************************************************************************/ + +static bool compare_record(TABLE *table, Field **ptr) +{ + for (; *ptr ; ptr++) + { + if ((*ptr)->cmp_offset(table->s->rec_buff_length)) + return 1; + } + return 0; +} + +static bool copy_blobs(Field **ptr) +{ + for (; *ptr ; ptr++) + { + if ((*ptr)->flags & BLOB_FLAG) + if (((Field_blob *) (*ptr))->copy()) + return 1; // Error + } + return 0; +} + +static void free_blobs(Field **ptr) +{ + for (; *ptr ; ptr++) + { + if ((*ptr)->flags & BLOB_FLAG) + ((Field_blob *) (*ptr))->free(); + } +} + + +static int +remove_duplicates(JOIN *join, TABLE *entry,List &fields, Item *having) +{ + int error; + ulong reclength,offset; + uint field_count; + THD *thd= join->thd; + DBUG_ENTER("remove_duplicates"); + + entry->reginfo.lock_type=TL_WRITE; + + /* Calculate how many saved fields there is in list */ + field_count=0; + List_iterator it(fields); + Item *item; + while ((item=it++)) + { + if (item->get_tmp_table_field() && ! item->const_item()) + field_count++; + } + + if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having) + { // only const items with no OPTION_FOUND_ROWS + join->unit->select_limit_cnt= 1; // Only send first row + DBUG_RETURN(0); + } + Field **first_field=entry->field+entry->s->fields - field_count; + offset= (field_count ? + entry->field[entry->s->fields - field_count]-> + offset(entry->record[0]) : 0); + reclength=entry->s->reclength-offset; + + free_io_cache(entry); // Safety + entry->file->info(HA_STATUS_VARIABLE); + if (entry->s->db_type() == heap_hton || + (!entry->s->blob_fields && + ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records < + thd->variables.sortbuff_size))) + error=remove_dup_with_hash_index(join->thd, entry, + field_count, first_field, + reclength, having); + else + error=remove_dup_with_compare(join->thd, entry, first_field, offset, + having); + + free_blobs(first_field); + DBUG_RETURN(error); +} + + +static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field, + ulong offset, Item *having) +{ + handler *file=table->file; + char *org_record,*new_record; + uchar *record; + int error; + ulong reclength= table->s->reclength-offset; + DBUG_ENTER("remove_dup_with_compare"); + + org_record=(char*) (record=table->record[0])+offset; + new_record=(char*) table->record[1]+offset; + + file->ha_rnd_init(1); + error=file->rnd_next(record); + for (;;) + { + if (thd->killed) + { + thd->send_kill_message(); + error=0; + goto err; + } + if (error) + { + if (error == HA_ERR_RECORD_DELETED) + continue; + if (error == HA_ERR_END_OF_FILE) + break; + goto err; + } + if (having && !having->val_int()) + { + if ((error=file->ha_delete_row(record))) + goto err; + error=file->rnd_next(record); + continue; + } + if (copy_blobs(first_field)) + { + my_message(ER_OUTOFMEMORY, ER(ER_OUTOFMEMORY), MYF(0)); + error=0; + goto err; + } + memcpy(new_record,org_record,reclength); + + /* Read through rest of file and mark duplicated rows deleted */ + bool found=0; + for (;;) + { + if ((error=file->rnd_next(record))) + { + if (error == HA_ERR_RECORD_DELETED) + continue; + if (error == HA_ERR_END_OF_FILE) + break; + goto err; + } + if (compare_record(table, first_field) == 0) + { + if ((error=file->ha_delete_row(record))) + goto err; + } + else if (!found) + { + found=1; + file->position(record); // Remember position + } + } + if (!found) + break; // End of file + /* Restart search on next row */ + error=file->restart_rnd_next(record,file->ref); + } + + file->extra(HA_EXTRA_NO_CACHE); + DBUG_RETURN(0); +err: + file->extra(HA_EXTRA_NO_CACHE); + if (error) + file->print_error(error,MYF(0)); + DBUG_RETURN(1); +} + + +/** + Generate a hash index for each row to quickly find duplicate rows. + + @note + Note that this will not work on tables with blobs! +*/ + +static int remove_dup_with_hash_index(THD *thd, TABLE *table, + uint field_count, + Field **first_field, + ulong key_length, + Item *having) +{ + uchar *key_buffer, *key_pos, *record=table->record[0]; + int error; + handler *file= table->file; + ulong extra_length= ALIGN_SIZE(key_length)-key_length; + uint *field_lengths,*field_length; + HASH hash; + DBUG_ENTER("remove_dup_with_hash_index"); + + if (!my_multi_malloc(MYF(MY_WME), + &key_buffer, + (uint) ((key_length + extra_length) * + (long) file->stats.records), + &field_lengths, + (uint) (field_count*sizeof(*field_lengths)), + NullS)) + DBUG_RETURN(1); + + { + Field **ptr; + ulong total_length= 0; + for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++) + { + uint length= (*ptr)->sort_length(); + (*field_length++)= length; + total_length+= length; + } + DBUG_PRINT("info",("field_count: %u key_length: %lu total_length: %lu", + field_count, key_length, total_length)); + DBUG_ASSERT(total_length <= key_length); + key_length= total_length; + extra_length= ALIGN_SIZE(key_length)-key_length; + } + + if (hash_init(&hash, &my_charset_bin, (uint) file->stats.records, 0, + key_length, (hash_get_key) 0, 0, 0)) + { + my_free((char*) key_buffer,MYF(0)); + DBUG_RETURN(1); + } + + file->ha_rnd_init(1); + key_pos=key_buffer; + for (;;) + { + uchar *org_key_pos; + if (thd->killed) + { + thd->send_kill_message(); + error=0; + goto err; + } + if ((error=file->rnd_next(record))) + { + if (error == HA_ERR_RECORD_DELETED) + continue; + if (error == HA_ERR_END_OF_FILE) + break; + goto err; + } + if (having && !having->val_int()) + { + if ((error=file->ha_delete_row(record))) + goto err; + continue; + } + + /* copy fields to key buffer */ + org_key_pos= key_pos; + field_length=field_lengths; + for (Field **ptr= first_field ; *ptr ; ptr++) + { + (*ptr)->sort_string(key_pos,*field_length); + key_pos+= *field_length++; + } + /* Check if it exists before */ + if (hash_search(&hash, org_key_pos, key_length)) + { + /* Duplicated found ; Remove the row */ + if ((error=file->ha_delete_row(record))) + goto err; + } + else + (void) my_hash_insert(&hash, org_key_pos); + key_pos+=extra_length; + } + my_free((char*) key_buffer,MYF(0)); + hash_free(&hash); + file->extra(HA_EXTRA_NO_CACHE); + (void) file->ha_rnd_end(); + DBUG_RETURN(0); + +err: + my_free((char*) key_buffer,MYF(0)); + hash_free(&hash); + file->extra(HA_EXTRA_NO_CACHE); + (void) file->ha_rnd_end(); + if (error) + file->print_error(error,MYF(0)); + DBUG_RETURN(1); +} + + +SORT_FIELD *make_unireg_sortorder(ORDER *order, uint *length, + SORT_FIELD *sortorder) +{ + uint count; + SORT_FIELD *sort,*pos; + DBUG_ENTER("make_unireg_sortorder"); + + count=0; + for (ORDER *tmp = order; tmp; tmp=tmp->next) + count++; + if (!sortorder) + sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) * + (max(count, *length) + 1)); + pos= sort= sortorder; + + if (!pos) + return 0; + + for (;order;order=order->next,pos++) + { + Item *item= order->item[0]->real_item(); + pos->field= 0; pos->item= 0; + if (item->type() == Item::FIELD_ITEM) + pos->field= ((Item_field*) item)->field; + else if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item()) + pos->field= ((Item_sum*) item)->get_tmp_table_field(); + else if (item->type() == Item::COPY_STR_ITEM) + { // Blob patch + pos->item= ((Item_copy*) item)->get_item(); + } + else + pos->item= *order->item; + pos->reverse=! order->asc; + } + *length=count; + DBUG_RETURN(sort); +} + + +/***************************************************************************** + Fill join cache with packed records + Records are stored in tab->cache.buffer and last record in + last record is stored with pointers to blobs to support very big + records +******************************************************************************/ + +static int +join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count) +{ + reg1 uint i; + uint length, blobs; + size_t size; + CACHE_FIELD *copy,**blob_ptr; + JOIN_CACHE *cache; + JOIN_TAB *join_tab; + DBUG_ENTER("join_init_cache"); + + cache= &tables[table_count].cache; + cache->fields=blobs=0; + + join_tab=tables; + for (i=0 ; i < table_count ; i++,join_tab++) + { + if (!join_tab->used_fieldlength) /* Not calced yet */ + calc_used_field_length(thd, join_tab); + cache->fields+=join_tab->used_fields; + blobs+=join_tab->used_blobs; + } + if (!(cache->field=(CACHE_FIELD*) + sql_alloc(sizeof(CACHE_FIELD)*(cache->fields+table_count*2)+(blobs+1)* + + sizeof(CACHE_FIELD*)))) + { + my_free((uchar*) cache->buff,MYF(0)); /* purecov: inspected */ + cache->buff=0; /* purecov: inspected */ + DBUG_RETURN(1); /* purecov: inspected */ + } + copy=cache->field; + blob_ptr=cache->blob_ptr=(CACHE_FIELD**) + (cache->field+cache->fields+table_count*2); + + length=0; + for (i=0 ; i < table_count ; i++) + { + bool have_bit_fields= FALSE; + uint null_fields=0,used_fields; + Field **f_ptr,*field; + MY_BITMAP *read_set= tables[i].table->read_set; + for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ; + used_fields ; + f_ptr++) + { + field= *f_ptr; + if (bitmap_is_set(read_set, field->field_index)) + { + used_fields--; + length+=field->fill_cache_field(copy); + if (copy->blob_field) + (*blob_ptr++)=copy; + if (field->real_maybe_null()) + null_fields++; + if (field->type() == MYSQL_TYPE_BIT && + ((Field_bit*)field)->bit_len) + have_bit_fields= TRUE; + copy++; + } + } + /* Copy null bits from table */ + if (null_fields || have_bit_fields) + { /* must copy null bits */ + copy->str= tables[i].table->null_flags; + copy->length= tables[i].table->s->null_bytes; + copy->strip=0; + copy->blob_field=0; + length+=copy->length; + copy++; + cache->fields++; + } + /* If outer join table, copy null_row flag */ + if (tables[i].table->maybe_null) + { + copy->str= (uchar*) &tables[i].table->null_row; + copy->length=sizeof(tables[i].table->null_row); + copy->strip=0; + copy->blob_field=0; + length+=copy->length; + copy++; + cache->fields++; + } + } + + cache->length=length+blobs*sizeof(char*); + cache->blobs=blobs; + *blob_ptr=0; /* End sequentel */ + size=max(thd->variables.join_buff_size, cache->length); + if (!(cache->buff=(uchar*) my_malloc(size,MYF(0)))) + DBUG_RETURN(1); /* Don't use cache */ /* purecov: inspected */ + cache->end=cache->buff+size; + reset_cache_write(cache); + DBUG_RETURN(0); +} + + +static ulong +used_blob_length(CACHE_FIELD **ptr) +{ + uint length,blob_length; + for (length=0 ; *ptr ; ptr++) + { + (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length(); + length+=blob_length; + (*ptr)->blob_field->get_ptr(&(*ptr)->str); + } + return length; +} + + +static bool +store_record_in_cache(JOIN_CACHE *cache) +{ + uint length; + uchar *pos; + CACHE_FIELD *copy,*end_field; + bool last_record; + + pos=cache->pos; + end_field=cache->field+cache->fields; + + length=cache->length; + if (cache->blobs) + length+=used_blob_length(cache->blob_ptr); + if ((last_record= (length + cache->length > (size_t) (cache->end - pos)))) + cache->ptr_record=cache->records; + + /* + There is room in cache. Put record there + */ + cache->records++; + for (copy=cache->field ; copy < end_field; copy++) + { + if (copy->blob_field) + { + if (last_record) + { + copy->blob_field->get_image(pos, copy->length+sizeof(char*), + copy->blob_field->charset()); + pos+=copy->length+sizeof(char*); + } + else + { + copy->blob_field->get_image(pos, copy->length, // blob length + copy->blob_field->charset()); + memcpy(pos+copy->length,copy->str,copy->blob_length); // Blob data + pos+=copy->length+copy->blob_length; + } + } + else + { + if (copy->strip) + { + uchar *str,*end; + for (str=copy->str,end= str+copy->length; + end > str && end[-1] == ' ' ; + end--) ; + length=(uint) (end-str); + memcpy(pos+2, str, length); + int2store(pos, length); + pos+= length+2; + } + else + { + memcpy(pos,copy->str,copy->length); + pos+=copy->length; + } + } + } + cache->pos=pos; + return last_record || (size_t) (cache->end - pos) < cache->length; +} + + +static void +reset_cache_read(JOIN_CACHE *cache) +{ + cache->record_nr=0; + cache->pos=cache->buff; +} + + +static void reset_cache_write(JOIN_CACHE *cache) +{ + reset_cache_read(cache); + cache->records= 0; + cache->ptr_record= (uint) ~0; +} + + +static void +read_cached_record(JOIN_TAB *tab) +{ + uchar *pos; + uint length; + bool last_record; + CACHE_FIELD *copy,*end_field; + + last_record=tab->cache.record_nr++ == tab->cache.ptr_record; + pos=tab->cache.pos; + + for (copy=tab->cache.field,end_field=copy+tab->cache.fields ; + copy < end_field; + copy++) + { + if (copy->blob_field) + { + if (last_record) + { + copy->blob_field->set_image(pos, copy->length+sizeof(char*), + copy->blob_field->charset()); + pos+=copy->length+sizeof(char*); + } + else + { + copy->blob_field->set_ptr(pos, pos+copy->length); + pos+=copy->length+copy->blob_field->get_length(); + } + } + else + { + if (copy->strip) + { + length= uint2korr(pos); + memcpy(copy->str, pos+2, length); + memset(copy->str+length, ' ', copy->length-length); + pos+= 2 + length; + } + else + { + memcpy(copy->str,pos,copy->length); + pos+=copy->length; + } + } + } + tab->cache.pos=pos; + return; +} + + +static bool +cmp_buffer_with_ref(JOIN_TAB *tab) +{ + bool diff; + if (!(diff=tab->ref.key_err)) + { + memcpy(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length); + } + if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, tab->table, + &tab->ref)) || + diff) + return 1; + return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length) + != 0; +} + + +bool +cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref) +{ + enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields; + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set); + bool result= 0; + + for (store_key **copy=ref->key_copy ; *copy ; copy++) + { + if ((*copy)->copy() & 1) + { + result= 1; + break; + } + } + thd->count_cuted_fields= save_count_cuted_fields; + dbug_tmp_restore_column_map(table->write_set, old_map); + return result; +} + + +/***************************************************************************** + Group and order functions +*****************************************************************************/ + +/** + Resolve an ORDER BY or GROUP BY column reference. + + Given a column reference (represented by 'order') from a GROUP BY or ORDER + BY clause, find the actual column it represents. If the column being + resolved is from the GROUP BY clause, the procedure searches the SELECT + list 'fields' and the columns in the FROM list 'tables'. If 'order' is from + the ORDER BY clause, only the SELECT list is being searched. + + If 'order' is resolved to an Item, then order->item is set to the found + Item. If there is no item for the found column (that is, it was resolved + into a table field), order->item is 'fixed' and is added to all_fields and + ref_pointer_array. + + ref_pointer_array and all_fields are updated. + + @param[in] thd Pointer to current thread structure + @param[in,out] ref_pointer_array All select, group and order by fields + @param[in] tables List of tables to search in (usually + FROM clause) + @param[in] order Column reference to be resolved + @param[in] fields List of fields to search in (usually + SELECT list) + @param[in,out] all_fields All select, group and order by fields + @param[in] is_group_field True if order is a GROUP field, false if + ORDER by field + + @retval + FALSE if OK + @retval + TRUE if error occurred +*/ + +static bool +find_order_in_list(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables, + ORDER *order, List &fields, List &all_fields, + bool is_group_field) +{ + Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */ + Item::Type order_item_type; + Item **select_item; /* The corresponding item from the SELECT clause. */ + Field *from_field; /* The corresponding field from the FROM clause. */ + uint counter; + enum_resolution_type resolution; + + /* + Local SP variables may be int but are expressions, not positions. + (And they can't be used before fix_fields is called for them). + */ + if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item()) + { /* Order by position */ + uint count= (uint) order_item->val_int(); + if (!count || count > fields.elements) + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), + order_item->full_name(), thd->where); + return TRUE; + } + order->item= ref_pointer_array + count - 1; + order->in_field_list= 1; + order->counter= count; + order->counter_used= 1; + return FALSE; + } + /* Lookup the current GROUP/ORDER field in the SELECT clause. */ + select_item= find_item_in_list(order_item, fields, &counter, + REPORT_EXCEPT_NOT_FOUND, &resolution); + if (!select_item) + return TRUE; /* The item is not unique, or some other error occured. */ + + + /* Check whether the resolved field is not ambiguos. */ + if (select_item != not_found_item) + { + Item *view_ref= NULL; + /* + If we have found field not by its alias in select list but by its + original field name, we should additionaly check if we have conflict + for this name (in case if we would perform lookup in all tables). + */ + if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed && + order_item->fix_fields(thd, order->item)) + return TRUE; + + /* Lookup the current GROUP field in the FROM clause. */ + order_item_type= order_item->type(); + from_field= (Field*) not_found_field; + if ((is_group_field && + order_item_type == Item::FIELD_ITEM) || + order_item_type == Item::REF_ITEM) + { + from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables, + NULL, &view_ref, IGNORE_ERRORS, TRUE, + FALSE); + if (!from_field) + from_field= (Field*) not_found_field; + } + + if (from_field == not_found_field || + (from_field != view_ref_found ? + /* it is field of base table => check that fields are same */ + ((*select_item)->type() == Item::FIELD_ITEM && + ((Item_field*) (*select_item))->field->eq(from_field)) : + /* + in is field of view table => check that references on translation + table are same + */ + ((*select_item)->type() == Item::REF_ITEM && + view_ref->type() == Item::REF_ITEM && + ((Item_ref *) (*select_item))->ref == + ((Item_ref *) view_ref)->ref))) + { + /* + If there is no such field in the FROM clause, or it is the same field + as the one found in the SELECT clause, then use the Item created for + the SELECT field. As a result if there was a derived field that + 'shadowed' a table field with the same name, the table field will be + chosen over the derived field. + */ + order->item= ref_pointer_array + counter; + order->in_field_list=1; + return FALSE; + } + else + { + /* + There is a field with the same name in the FROM clause. This + is the field that will be chosen. In this case we issue a + warning so the user knows that the field from the FROM clause + overshadows the column reference from the SELECT list. + */ + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR, + ER(ER_NON_UNIQ_ERROR), + ((Item_ident*) order_item)->field_name, + current_thd->where); + } + } + + order->in_field_list=0; + /* + The call to order_item->fix_fields() means that here we resolve + 'order_item' to a column from a table in the list 'tables', or to + a column in some outer query. Exactly because of the second case + we come to this point even if (select_item == not_found_item), + inspite of that fix_fields() calls find_item_in_list() one more + time. + + We check order_item->fixed because Item_func_group_concat can put + arguments for which fix_fields already was called. + */ + if (!order_item->fixed && + (order_item->fix_fields(thd, order->item) || + (order_item= *order->item)->check_cols(1) || + thd->is_fatal_error)) + return TRUE; /* Wrong field. */ + + uint el= all_fields.elements; + all_fields.push_front(order_item); /* Add new field to field list. */ + ref_pointer_array[el]= order_item; + order->item= ref_pointer_array + el; + return FALSE; +} + + +/** + Change order to point at item in select list. + + If item isn't a number and doesn't exits in the select list, add it the + the field list. +*/ + +int setup_order(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables, + List &fields, List &all_fields, ORDER *order) +{ + thd->where="order clause"; + for (; order; order=order->next) + { + if (find_order_in_list(thd, ref_pointer_array, tables, order, fields, + all_fields, FALSE)) + return 1; + } + return 0; +} + + +/** + Intitialize the GROUP BY list. + + @param thd Thread handler + @param ref_pointer_array We store references to all fields that was + not in 'fields' here. + @param fields All fields in the select part. Any item in + 'order' that is part of these list is replaced + by a pointer to this fields. + @param all_fields Total list of all unique fields used by the + select. All items in 'order' that was not part + of fields will be added first to this list. + @param order The fields we should do GROUP BY on. + @param hidden_group_fields Pointer to flag that is set to 1 if we added + any fields to all_fields. + + @todo + change ER_WRONG_FIELD_WITH_GROUP to more detailed + ER_NON_GROUPING_FIELD_USED + + @retval + 0 ok + @retval + 1 error (probably out of memory) +*/ + +int +setup_group(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables, + List &fields, List &all_fields, ORDER *order, + bool *hidden_group_fields) +{ + *hidden_group_fields=0; + ORDER *ord; + + if (!order) + return 0; /* Everything is ok */ + + uint org_fields=all_fields.elements; + + thd->where="group statement"; + for (ord= order; ord; ord= ord->next) + { + if (find_order_in_list(thd, ref_pointer_array, tables, ord, fields, + all_fields, TRUE)) + return 1; + (*ord->item)->marker= UNDEF_POS; /* Mark found */ + if ((*ord->item)->with_sum_func) + { + my_error(ER_WRONG_GROUP_FIELD, MYF(0), (*ord->item)->full_name()); + return 1; + } + } + if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) + { + /* + Don't allow one to use fields that is not used in GROUP BY + For each select a list of field references that aren't under an + aggregate function is created. Each field in this list keeps the + position of the select list expression which it belongs to. + + First we check an expression from the select list against the GROUP BY + list. If it's found there then it's ok. It's also ok if this expression + is a constant or an aggregate function. Otherwise we scan the list + of non-aggregated fields and if we'll find at least one field reference + that belongs to this expression and doesn't occur in the GROUP BY list + we throw an error. If there are no fields in the created list for a + select list expression this means that all fields in it are used under + aggregate functions. + */ + Item *item; + Item_field *field; + int cur_pos_in_select_list= 0; + List_iterator li(fields); + List_iterator naf_it(thd->lex->current_select->non_agg_fields); + + field= naf_it++; + while (field && (item=li++)) + { + if (item->type() != Item::SUM_FUNC_ITEM && item->marker >= 0 && + !item->const_item() && + !(item->real_item()->type() == Item::FIELD_ITEM && + item->used_tables() & OUTER_REF_TABLE_BIT)) + { + while (field) + { + /* Skip fields from previous expressions. */ + if (field->marker < cur_pos_in_select_list) + goto next_field; + /* Found a field from the next expression. */ + if (field->marker > cur_pos_in_select_list) + break; + /* + Check whether the field occur in the GROUP BY list. + Throw the error later if the field isn't found. + */ + for (ord= order; ord; ord= ord->next) + if ((*ord->item)->eq((Item*)field, 0)) + goto next_field; + /* + TODO: change ER_WRONG_FIELD_WITH_GROUP to more detailed + ER_NON_GROUPING_FIELD_USED + */ + my_error(ER_WRONG_FIELD_WITH_GROUP, MYF(0), field->full_name()); + return 1; +next_field: + field= naf_it++; + } + } + cur_pos_in_select_list++; + } + } + if (org_fields != all_fields.elements) + *hidden_group_fields=1; // group fields is not used + return 0; +} + +/** + Add fields with aren't used at start of field list. + + @return + FALSE if ok +*/ + +static bool +setup_new_fields(THD *thd, List &fields, + List &all_fields, ORDER *new_field) +{ + Item **item; + uint counter; + enum_resolution_type not_used; + DBUG_ENTER("setup_new_fields"); + + thd->mark_used_columns= MARK_COLUMNS_READ; // Not really needed, but... + for (; new_field ; new_field= new_field->next) + { + if ((item= find_item_in_list(*new_field->item, fields, &counter, + IGNORE_ERRORS, ¬_used))) + new_field->item=item; /* Change to shared Item */ + else + { + thd->where="procedure list"; + if ((*new_field->item)->fix_fields(thd, new_field->item)) + DBUG_RETURN(1); /* purecov: inspected */ + all_fields.push_front(*new_field->item); + new_field->item=all_fields.head_ref(); + } + } + DBUG_RETURN(0); +} + +/** + Create a group by that consist of all non const fields. + + Try to use the fields in the order given by 'order' to allow one to + optimize away 'order by'. +*/ + +static ORDER * +create_distinct_group(THD *thd, Item **ref_pointer_array, + ORDER *order_list, List &fields, + List &all_fields, + bool *all_order_by_fields_used) +{ + List_iterator li(fields); + Item *item, **orig_ref_pointer_array= ref_pointer_array; + ORDER *order,*group,**prev; + + *all_order_by_fields_used= 1; + while ((item=li++)) + item->marker=0; /* Marker that field is not used */ + + prev= &group; group=0; + for (order=order_list ; order; order=order->next) + { + if (order->in_field_list) + { + ORDER *ord=(ORDER*) thd->memdup((char*) order,sizeof(ORDER)); + if (!ord) + return 0; + *prev=ord; + prev= &ord->next; + (*ord->item)->marker=1; + } + else + *all_order_by_fields_used= 0; + } + + li.rewind(); + while ((item=li++)) + { + if (!item->const_item() && !item->with_sum_func && !item->marker) + { + /* + Don't put duplicate columns from the SELECT list into the + GROUP BY list. + */ + ORDER *ord_iter; + for (ord_iter= group; ord_iter; ord_iter= ord_iter->next) + if ((*ord_iter->item)->eq(item, 1)) + goto next_item; + + ORDER *ord=(ORDER*) thd->calloc(sizeof(ORDER)); + if (!ord) + return 0; + + if (item->type() == Item::FIELD_ITEM && + item->field_type() == MYSQL_TYPE_BIT) + { + /* + Because HEAP tables can't index BIT fields we need to use an + additional hidden field for grouping because later it will be + converted to a LONG field. Original field will remain of the + BIT type and will be returned to a client. + */ + Item_field *new_item= new Item_field(thd, (Item_field*)item); + int el= all_fields.elements; + orig_ref_pointer_array[el]= new_item; + all_fields.push_front(new_item); + ord->item= orig_ref_pointer_array + el; + } + else + { + /* + We have here only field_list (not all_field_list), so we can use + simple indexing of ref_pointer_array (order in the array and in the + list are same) + */ + ord->item= ref_pointer_array; + } + ord->asc=1; + *prev=ord; + prev= &ord->next; + } +next_item: + ref_pointer_array++; + } + *prev=0; + return group; +} + + +/** + Update join with count of the different type of fields. +*/ + +void +count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, + List &fields, bool reset_with_sum_func) +{ + List_iterator li(fields); + Item *field; + + param->field_count=param->sum_func_count=param->func_count= + param->hidden_field_count=0; + param->quick_group=1; + while ((field=li++)) + { + Item::Type real_type= field->real_item()->type(); + if (real_type == Item::FIELD_ITEM) + param->field_count++; + else if (real_type == Item::SUM_FUNC_ITEM) + { + if (! field->const_item()) + { + Item_sum *sum_item=(Item_sum*) field->real_item(); + if (!sum_item->depended_from() || + sum_item->depended_from() == select_lex) + { + if (!sum_item->quick_group) + param->quick_group=0; // UDF SUM function + param->sum_func_count++; + + for (uint i=0 ; i < sum_item->get_arg_count() ; i++) + { + if (sum_item->get_arg(i)->real_item()->type() == Item::FIELD_ITEM) + param->field_count++; + else + param->func_count++; + } + } + param->func_count++; + } + } + else + { + param->func_count++; + if (reset_with_sum_func) + field->with_sum_func=0; + } + } +} + + +/** + Return 1 if second is a subpart of first argument. + + If first parts has different direction, change it to second part + (group is sorted like order) +*/ + +static bool +test_if_subpart(ORDER *a,ORDER *b) +{ + for (; a && b; a=a->next,b=b->next) + { + if ((*a->item)->eq(*b->item,1)) + a->asc=b->asc; + else + return 0; + } + return test(!b); +} + +/** + Return table number if there is only one table in sort order + and group and order is compatible, else return 0. +*/ + +static TABLE * +get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables) +{ + table_map map= (table_map) 0; + DBUG_ENTER("get_sort_by_table"); + + if (!a) + a=b; // Only one need to be given + else if (!b) + b=a; + + for (; a && b; a=a->next,b=b->next) + { + if (!(*a->item)->eq(*b->item,1)) + DBUG_RETURN(0); + map|=a->item[0]->used_tables(); + } + if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))) + DBUG_RETURN(0); + + for (; !(map & tables->table->map); tables= tables->next_leaf) ; + if (map != tables->table->map) + DBUG_RETURN(0); // More than one table + DBUG_PRINT("exit",("sort by table: %d",tables->table->tablenr)); + DBUG_RETURN(tables->table); +} + + +/** + calc how big buffer we need for comparing group entries. +*/ + +static void +calc_group_buffer(JOIN *join,ORDER *group) +{ + uint key_length=0, parts=0, null_parts=0; + + if (group) + join->group= 1; + for (; group ; group=group->next) + { + Item *group_item= *group->item; + Field *field= group_item->get_tmp_table_field(); + if (field) + { + enum_field_types type; + if ((type= field->type()) == MYSQL_TYPE_BLOB) + key_length+=MAX_BLOB_WIDTH; // Can't be used as a key + else if (type == MYSQL_TYPE_VARCHAR || type == MYSQL_TYPE_VAR_STRING) + key_length+= field->field_length + HA_KEY_BLOB_LENGTH; + else if (type == MYSQL_TYPE_BIT) + { + /* Bit is usually stored as a longlong key for group fields */ + key_length+= 8; // Big enough + } + else + key_length+= field->pack_length(); + } + else + { + switch (group_item->result_type()) { + case REAL_RESULT: + key_length+= sizeof(double); + break; + case INT_RESULT: + key_length+= sizeof(longlong); + break; + case DECIMAL_RESULT: + key_length+= my_decimal_get_binary_size(group_item->max_length - + (group_item->decimals ? 1 : 0), + group_item->decimals); + break; + case STRING_RESULT: + { + enum enum_field_types type= group_item->field_type(); + /* + As items represented as DATE/TIME fields in the group buffer + have STRING_RESULT result type, we increase the length + by 8 as maximum pack length of such fields. + */ + if (type == MYSQL_TYPE_TIME || + type == MYSQL_TYPE_DATE || + type == MYSQL_TYPE_DATETIME || + type == MYSQL_TYPE_TIMESTAMP) + { + key_length+= 8; + } + else + { + /* + Group strings are taken as varstrings and require an length field. + A field is not yet created by create_tmp_field() + and the sizes should match up. + */ + key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH; + } + break; + } + default: + /* This case should never be choosen */ + DBUG_ASSERT(0); + my_error(ER_OUT_OF_RESOURCES, MYF(0)); + join->thd->fatal_error(); + } + } + parts++; + if (group_item->maybe_null) + null_parts++; + } + join->tmp_table_param.group_length=key_length+null_parts; + join->tmp_table_param.group_parts=parts; + join->tmp_table_param.group_null_parts=null_parts; +} + + +/** + allocate group fields or take prepared (cached). + + @param main_join join of current select + @param curr_join current join (join of current select or temporary copy + of it) + + @retval + 0 ok + @retval + 1 failed +*/ + +static bool +make_group_fields(JOIN *main_join, JOIN *curr_join) +{ + if (main_join->group_fields_cache.elements) + { + curr_join->group_fields= main_join->group_fields_cache; + curr_join->sort_and_group= 1; + } + else + { + if (alloc_group_fields(curr_join, curr_join->group_list)) + return (1); + main_join->group_fields_cache= curr_join->group_fields; + } + return (0); +} + + +/** + Get a list of buffers for saveing last group. + + Groups are saved in reverse order for easyer check loop. +*/ + +static bool +alloc_group_fields(JOIN *join,ORDER *group) +{ + if (group) + { + for (; group ; group=group->next) + { + Cached_item *tmp=new_Cached_item(join->thd, *group->item); + if (!tmp || join->group_fields.push_front(tmp)) + return TRUE; + } + } + join->sort_and_group=1; /* Mark for do_select */ + return FALSE; +} + + +static int +test_if_group_changed(List &list) +{ + DBUG_ENTER("test_if_group_changed"); + List_iterator li(list); + int idx= -1,i; + Cached_item *buff; + + for (i=(int) list.elements-1 ; (buff=li++) ; i--) + { + if (buff->cmp()) + idx=i; + } + DBUG_PRINT("info", ("idx: %d", idx)); + DBUG_RETURN(idx); +} + + +/** + Setup copy_fields to save fields at start of new group. + + Setup copy_fields to save fields at start of new group + + Only FIELD_ITEM:s and FUNC_ITEM:s needs to be saved between groups. + Change old item_field to use a new field with points at saved fieldvalue + This function is only called before use of send_fields. + + @param thd THD pointer + @param param temporary table parameters + @param ref_pointer_array array of pointers to top elements of filed list + @param res_selected_fields new list of items of select item list + @param res_all_fields new list of all items + @param elements number of elements in select item list + @param all_fields all fields list + + @todo + In most cases this result will be sent to the user. + This should be changed to use copy_int or copy_real depending + on how the value is to be used: In some cases this may be an + argument in a group function, like: IF(ISNULL(col),0,COUNT(*)) + + @retval + 0 ok + @retval + !=0 error +*/ + +bool +setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param, + Item **ref_pointer_array, + List &res_selected_fields, List &res_all_fields, + uint elements, List &all_fields) +{ + Item *pos; + List_iterator_fast li(all_fields); + Copy_field *copy= NULL; + IF_DBUG(Copy_field *copy_start); + res_selected_fields.empty(); + res_all_fields.empty(); + List_iterator_fast itr(res_all_fields); + List extra_funcs; + uint i, border= all_fields.elements - elements; + DBUG_ENTER("setup_copy_fields"); + + if (param->field_count && + !(copy=param->copy_field= new Copy_field[param->field_count])) + goto err2; + + param->copy_funcs.empty(); + IF_DBUG(copy_start= copy); + for (i= 0; (pos= li++); i++) + { + Field *field; + uchar *tmp; + Item *real_pos= pos->real_item(); + /* + Aggregate functions can be substituted for fields (by e.g. temp tables). + We need to filter those substituted fields out. + */ + if (real_pos->type() == Item::FIELD_ITEM && + !(real_pos != pos && + ((Item_ref *)pos)->ref_type() == Item_ref::AGGREGATE_REF)) + { + Item_field *item; + if (!(item= new Item_field(thd, ((Item_field*) real_pos)))) + goto err; + if (pos->type() == Item::REF_ITEM) + { + /* preserve the names of the ref when dereferncing */ + Item_ref *ref= (Item_ref *) pos; + item->db_name= ref->db_name; + item->table_name= ref->table_name; + item->name= ref->name; + } + pos= item; + if (item->field->flags & BLOB_FLAG) + { + if (!(pos= Item_copy::create(pos))) + goto err; + /* + Item_copy_string::copy for function can call + Item_copy_string::val_int for blob via Item_ref. + But if Item_copy_string::copy for blob isn't called before, + it's value will be wrong + so let's insert Item_copy_string for blobs in the beginning of + copy_funcs + (to see full test case look at having.test, BUG #4358) + */ + if (param->copy_funcs.push_front(pos)) + goto err; + } + else + { + /* + set up save buffer and change result_field to point at + saved value + */ + field= item->field; + item->result_field=field->new_field(thd->mem_root,field->table, 1); + /* + We need to allocate one extra byte for null handling and + another extra byte to not get warnings from purify in + Field_string::val_int + */ + if (!(tmp= (uchar*) sql_alloc(field->pack_length()+2))) + goto err; + if (copy) + { + DBUG_ASSERT (param->field_count > (uint) (copy - copy_start)); + copy->set(tmp, item->result_field); + item->result_field->move_field(copy->to_ptr,copy->to_null_ptr,1); +#ifdef HAVE_purify + copy->to_ptr[copy->from_length]= 0; +#endif + copy++; + } + } + } + else if ((real_pos->type() == Item::FUNC_ITEM || + real_pos->type() == Item::SUBSELECT_ITEM || + real_pos->type() == Item::CACHE_ITEM || + real_pos->type() == Item::COND_ITEM) && + !real_pos->with_sum_func) + { // Save for send fields + pos= real_pos; + /* TODO: + In most cases this result will be sent to the user. + This should be changed to use copy_int or copy_real depending + on how the value is to be used: In some cases this may be an + argument in a group function, like: IF(ISNULL(col),0,COUNT(*)) + */ + if (!(pos= Item_copy::create(pos))) + goto err; + if (i < border) // HAVING, ORDER and GROUP BY + { + if (extra_funcs.push_back(pos)) + goto err; + } + else if (param->copy_funcs.push_back(pos)) + goto err; + } + res_all_fields.push_back(pos); + ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]= + pos; + } + param->copy_field_end= copy; + + for (i= 0; i < border; i++) + itr++; + itr.sublist(res_selected_fields, elements); + /* + Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any + reference used in these will resolve to a item that is already calculated + */ + param->copy_funcs.concat(&extra_funcs); + + DBUG_RETURN(0); + + err: + if (copy) + delete [] param->copy_field; // This is never 0 + param->copy_field=0; +err2: + DBUG_RETURN(TRUE); +} + + +/** + Make a copy of all simple SELECT'ed items. + + This is done at the start of a new group so that we can retrieve + these later when the group changes. +*/ + +void +copy_fields(TMP_TABLE_PARAM *param) +{ + Copy_field *ptr=param->copy_field; + Copy_field *end=param->copy_field_end; + + for (; ptr != end; ptr++) + (*ptr->do_copy)(ptr); + + List_iterator_fast it(param->copy_funcs); + Item_copy *item; + while ((item = (Item_copy*) it++)) + item->copy(); +} + + +/** + Make an array of pointers to sum_functions to speed up + sum_func calculation. + + @retval + 0 ok + @retval + 1 Error +*/ + +bool JOIN::alloc_func_list() +{ + uint func_count, group_parts; + DBUG_ENTER("alloc_func_list"); + + func_count= tmp_table_param.sum_func_count; + /* + If we are using rollup, we need a copy of the summary functions for + each level + */ + if (rollup.state != ROLLUP::STATE_NONE) + func_count*= (send_group_parts+1); + + group_parts= send_group_parts; + /* + If distinct, reserve memory for possible + disctinct->group_by optimization + */ + if (select_distinct) + { + group_parts+= fields_list.elements; + /* + If the ORDER clause is specified then it's possible that + it also will be optimized, so reserve space for it too + */ + if (order) + { + ORDER *ord; + for (ord= order; ord; ord= ord->next) + group_parts++; + } + } + + /* This must use calloc() as rollup_make_fields depends on this */ + sum_funcs= (Item_sum**) thd->calloc(sizeof(Item_sum**) * (func_count+1) + + sizeof(Item_sum***) * (group_parts+1)); + sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1); + DBUG_RETURN(sum_funcs == 0); +} + + +/** + Initialize 'sum_funcs' array with all Item_sum objects. + + @param field_list All items + @param send_fields Items in select list + @param before_group_by Set to 1 if this is called before GROUP BY handling + @param recompute Set to TRUE if sum_funcs must be recomputed + + @retval + 0 ok + @retval + 1 error +*/ + +bool JOIN::make_sum_func_list(List &field_list, List &send_fields, + bool before_group_by, bool recompute) +{ + List_iterator_fast it(field_list); + Item_sum **func; + Item *item; + DBUG_ENTER("make_sum_func_list"); + + if (*sum_funcs && !recompute) + DBUG_RETURN(FALSE); /* We have already initialized sum_funcs. */ + + func= sum_funcs; + while ((item=it++)) + { + if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() && + (!((Item_sum*) item)->depended_from() || + ((Item_sum *)item)->depended_from() == select_lex)) + *func++= (Item_sum*) item; + } + if (before_group_by && rollup.state == ROLLUP::STATE_INITED) + { + rollup.state= ROLLUP::STATE_READY; + if (rollup_make_fields(field_list, send_fields, &func)) + DBUG_RETURN(TRUE); // Should never happen + } + else if (rollup.state == ROLLUP::STATE_NONE) + { + for (uint i=0 ; i <= send_group_parts ;i++) + sum_funcs_end[i]= func; + } + else if (rollup.state == ROLLUP::STATE_READY) + DBUG_RETURN(FALSE); // Don't put end marker + *func=0; // End marker + DBUG_RETURN(FALSE); +} + + +/** + Change all funcs and sum_funcs to fields in tmp table, and create + new list of all items. + + @param thd THD pointer + @param ref_pointer_array array of pointers to top elements of filed list + @param res_selected_fields new list of items of select item list + @param res_all_fields new list of all items + @param elements number of elements in select item list + @param all_fields all fields list + + @retval + 0 ok + @retval + !=0 error +*/ + +static bool +change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array, + List &res_selected_fields, + List &res_all_fields, + uint elements, List &all_fields) +{ + List_iterator_fast it(all_fields); + Item *item_field,*item; + DBUG_ENTER("change_to_use_tmp_fields"); + + res_selected_fields.empty(); + res_all_fields.empty(); + + uint i, border= all_fields.elements - elements; + for (i= 0; (item= it++); i++) + { + Field *field; + + if ((item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) || + (item->type() == Item::FUNC_ITEM && + ((Item_func*)item)->functype() == Item_func::SUSERVAR_FUNC)) + item_field= item; + else + { + if (item->type() == Item::FIELD_ITEM) + { + item_field= item->get_tmp_table_item(thd); + } + else if ((field= item->get_tmp_table_field())) + { + if (item->type() == Item::SUM_FUNC_ITEM && field->table->group) + item_field= ((Item_sum*) item)->result_item(field); + else + item_field= (Item*) new Item_field(field); + if (!item_field) + DBUG_RETURN(TRUE); // Fatal error + + if (item->real_item()->type() != Item::FIELD_ITEM) + field->orig_table= 0; + item_field->name= item->name; + if (item->type() == Item::REF_ITEM) + { + Item_field *ifield= (Item_field *) item_field; + Item_ref *iref= (Item_ref *) item; + ifield->table_name= iref->table_name; + ifield->db_name= iref->db_name; + } +#ifndef DBUG_OFF + if (!item_field->name) + { + char buff[256]; + String str(buff,sizeof(buff),&my_charset_bin); + str.length(0); + item->print(&str, QT_ORDINARY); + item_field->name= sql_strmake(str.ptr(),str.length()); + } +#endif + } + else + item_field= item; + } + res_all_fields.push_back(item_field); + ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]= + item_field; + } + + List_iterator_fast itr(res_all_fields); + for (i= 0; i < border; i++) + itr++; + itr.sublist(res_selected_fields, elements); + DBUG_RETURN(FALSE); +} + + +/** + Change all sum_func refs to fields to point at fields in tmp table. + Change all funcs to be fields in tmp table. + + @param thd THD pointer + @param ref_pointer_array array of pointers to top elements of filed list + @param res_selected_fields new list of items of select item list + @param res_all_fields new list of all items + @param elements number of elements in select item list + @param all_fields all fields list + + @retval + 0 ok + @retval + 1 error +*/ + +static bool +change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array, + List &res_selected_fields, + List &res_all_fields, uint elements, + List &all_fields) +{ + List_iterator_fast it(all_fields); + Item *item, *new_item; + res_selected_fields.empty(); + res_all_fields.empty(); + + uint i, border= all_fields.elements - elements; + for (i= 0; (item= it++); i++) + { + res_all_fields.push_back(new_item= item->get_tmp_table_item(thd)); + ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]= + new_item; + } + + List_iterator_fast itr(res_all_fields); + for (i= 0; i < border; i++) + itr++; + itr.sublist(res_selected_fields, elements); + + return thd->is_fatal_error; +} + + + +/****************************************************************************** + Code for calculating functions +******************************************************************************/ + + +/** + Call ::setup for all sum functions. + + @param thd thread handler + @param func_ptr sum function list + + @retval + FALSE ok + @retval + TRUE error +*/ + +static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr) +{ + Item_sum *func; + DBUG_ENTER("setup_sum_funcs"); + while ((func= *(func_ptr++))) + { + if (func->setup(thd)) + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + + +static void +init_tmptable_sum_functions(Item_sum **func_ptr) +{ + Item_sum *func; + while ((func= *(func_ptr++))) + func->reset_field(); +} + + +/** Update record 0 in tmp_table from record 1. */ + +static void +update_tmptable_sum_func(Item_sum **func_ptr, + TABLE *tmp_table __attribute__((unused))) +{ + Item_sum *func; + while ((func= *(func_ptr++))) + func->update_field(); +} + + +/** Copy result of sum functions to record in tmp_table. */ + +static void +copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr) +{ + for (; func_ptr != end_ptr ; func_ptr++) + (void) (*func_ptr)->save_in_result_field(1); + return; +} + + +static bool +init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr) +{ + for (; func_ptr != end_ptr ;func_ptr++) + { + if ((*func_ptr)->reset()) + return 1; + } + /* If rollup, calculate the upper sum levels */ + for ( ; *func_ptr ; func_ptr++) + { + if ((*func_ptr)->add()) + return 1; + } + return 0; +} + + +static bool +update_sum_func(Item_sum **func_ptr) +{ + Item_sum *func; + for (; (func= (Item_sum*) *func_ptr) ; func_ptr++) + if (func->add()) + return 1; + return 0; +} + +/** Copy result of functions to record in tmp_table. */ + +void +copy_funcs(Item **func_ptr) +{ + Item *func; + for (; (func = *func_ptr) ; func_ptr++) + func->save_in_result_field(1); +} + + +/** + Create a condition for a const reference and add this to the + currenct select for the table. +*/ + +static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab) +{ + DBUG_ENTER("add_ref_to_table_cond"); + if (!join_tab->ref.key_parts) + DBUG_RETURN(FALSE); + + Item_cond_and *cond=new Item_cond_and(); + TABLE *table=join_tab->table; + int error; + if (!cond) + DBUG_RETURN(TRUE); + + for (uint i=0 ; i < join_tab->ref.key_parts ; i++) + { + Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i]. + fieldnr-1]; + Item *value=join_tab->ref.items[i]; + cond->add(new Item_func_equal(new Item_field(field), value)); + } + if (thd->is_fatal_error) + DBUG_RETURN(TRUE); + + if (!cond->fixed) + cond->fix_fields(thd, (Item**)&cond); + if (join_tab->select) + { + error=(int) cond->add(join_tab->select->cond); + join_tab->select_cond=join_tab->select->cond=cond; + } + else if ((join_tab->select= make_select(join_tab->table, 0, 0, cond, 0, + &error))) + join_tab->select_cond=cond; + + DBUG_RETURN(error ? TRUE : FALSE); +} + + +/** + Free joins of subselect of this select. + + @param thd THD pointer + @param select pointer to st_select_lex which subselects joins we will free +*/ + +void free_underlaid_joins(THD *thd, SELECT_LEX *select) +{ + for (SELECT_LEX_UNIT *unit= select->first_inner_unit(); + unit; + unit= unit->next_unit()) + unit->cleanup(); +} + +/**************************************************************************** + ROLLUP handling +****************************************************************************/ + +/** + Replace occurences of group by fields in an expression by ref items. + + The function replaces occurrences of group by fields in expr + by ref objects for these fields unless they are under aggregate + functions. + The function also corrects value of the the maybe_null attribute + for the items of all subexpressions containing group by fields. + + @b EXAMPLES + @code + SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP + SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP + @endcode + + @b IMPLEMENTATION + + The function recursively traverses the tree of the expr expression, + looks for occurrences of the group by fields that are not under + aggregate functions and replaces them for the corresponding ref items. + + @note + This substitution is needed GROUP BY queries with ROLLUP if + SELECT list contains expressions over group by attributes. + + @param thd reference to the context + @param expr expression to make replacement + @param group_list list of references to group by items + @param changed out: returns 1 if item contains a replaced field item + + @todo + - TODO: Some functions are not null-preserving. For those functions + updating of the maybe_null attribute is an overkill. + + @retval + 0 if ok + @retval + 1 on error +*/ + +static bool change_group_ref(THD *thd, Item_func *expr, ORDER *group_list, + bool *changed) +{ + if (expr->arg_count) + { + Name_resolution_context *context= &thd->lex->current_select->context; + Item **arg,**arg_end; + bool arg_changed= FALSE; + for (arg= expr->arguments(), + arg_end= expr->arguments()+expr->arg_count; + arg != arg_end; arg++) + { + Item *item= *arg; + if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM) + { + ORDER *group_tmp; + for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next) + { + if (item->eq(*group_tmp->item,0)) + { + Item *new_item; + if (!(new_item= new Item_ref(context, group_tmp->item, 0, + item->name))) + return 1; // fatal_error is set + thd->change_item_tree(arg, new_item); + arg_changed= TRUE; + } + } + } + else if (item->type() == Item::FUNC_ITEM) + { + if (change_group_ref(thd, (Item_func *) item, group_list, &arg_changed)) + return 1; + } + } + if (arg_changed) + { + expr->maybe_null= 1; + *changed= TRUE; + } + } + return 0; +} + + +/** Allocate memory needed for other rollup functions. */ + +bool JOIN::rollup_init() +{ + uint i,j; + Item **ref_array; + + tmp_table_param.quick_group= 0; // Can't create groups in tmp table + rollup.state= ROLLUP::STATE_INITED; + + /* + Create pointers to the different sum function groups + These are updated by rollup_make_fields() + */ + tmp_table_param.group_parts= send_group_parts; + + if (!(rollup.null_items= (Item_null_result**) thd->alloc((sizeof(Item*) + + sizeof(Item**) + + sizeof(List) + + ref_pointer_array_size) + * send_group_parts ))) + return 1; + + rollup.fields= (List*) (rollup.null_items + send_group_parts); + rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts); + ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts); + + /* + Prepare space for field list for the different levels + These will be filled up in rollup_make_fields() + */ + for (i= 0 ; i < send_group_parts ; i++) + { + rollup.null_items[i]= new (thd->mem_root) Item_null_result(); + List *rollup_fields= &rollup.fields[i]; + rollup_fields->empty(); + rollup.ref_pointer_arrays[i]= ref_array; + ref_array+= all_fields.elements; + } + for (i= 0 ; i < send_group_parts; i++) + { + for (j=0 ; j < fields_list.elements ; j++) + rollup.fields[i].push_back(rollup.null_items[i]); + } + List_iterator it(all_fields); + Item *item; + while ((item= it++)) + { + ORDER *group_tmp; + bool found_in_group= 0; + + for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next) + { + if (*group_tmp->item == item) + { + item->maybe_null= 1; + found_in_group= 1; + if (item->const_item()) + { + /* + For ROLLUP queries each constant item referenced in GROUP BY list + is wrapped up into an Item_func object yielding the same value + as the constant item. The objects of the wrapper class are never + considered as constant items and besides they inherit all + properties of the Item_result_field class. + This wrapping allows us to ensure writing constant items + into temporary tables whenever the result of the ROLLUP + operation has to be written into a temporary table, e.g. when + ROLLUP is used together with DISTINCT in the SELECT list. + Usually when creating temporary tables for a intermidiate + result we do not include fields for constant expressions. + */ + Item* new_item= new Item_func_rollup_const(item); + if (!new_item) + return 1; + new_item->fix_fields(thd, (Item **) 0); + thd->change_item_tree(it.ref(), new_item); + for (ORDER *tmp= group_tmp; tmp; tmp= tmp->next) + { + if (*tmp->item == item) + thd->change_item_tree(tmp->item, new_item); + } + } + } + } + if (item->type() == Item::FUNC_ITEM && !found_in_group) + { + bool changed= FALSE; + if (change_group_ref(thd, (Item_func *) item, group_list, &changed)) + return 1; + /* + We have to prevent creation of a field in a temporary table for + an expression that contains GROUP BY attributes. + Marking the expression item as 'with_sum_func' will ensure this. + */ + if (changed) + item->with_sum_func= 1; + } + } + return 0; +} + + +/** + Fill up rollup structures with pointers to fields to use. + + Creates copies of item_sum items for each sum level. + + @param fields_arg List of all fields (hidden and real ones) + @param sel_fields Pointer to selected fields + @param func Store here a pointer to all fields + + @retval + 0 if ok; + In this case func is pointing to next not used element. + @retval + 1 on error +*/ + +bool JOIN::rollup_make_fields(List &fields_arg, List &sel_fields, + Item_sum ***func) +{ + List_iterator_fast it(fields_arg); + Item *first_field= sel_fields.head(); + uint level; + + /* + Create field lists for the different levels + + The idea here is to have a separate field list for each rollup level to + avoid all runtime checks of which columns should be NULL. + + The list is stored in reverse order to get sum function in such an order + in func that it makes it easy to reset them with init_sum_functions() + + Assuming: SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP + + rollup.fields[0] will contain list where a,b,c is NULL + rollup.fields[1] will contain list where b,c is NULL + ... + rollup.ref_pointer_array[#] points to fields for rollup.fields[#] + ... + sum_funcs_end[0] points to all sum functions + sum_funcs_end[1] points to all sum functions, except grand totals + ... + */ + + for (level=0 ; level < send_group_parts ; level++) + { + uint i; + uint pos= send_group_parts - level -1; + bool real_fields= 0; + Item *item; + List_iterator new_it(rollup.fields[pos]); + Item **ref_array_start= rollup.ref_pointer_arrays[pos]; + ORDER *start_group; + + /* Point to first hidden field */ + Item **ref_array= ref_array_start + fields_arg.elements-1; + + /* Remember where the sum functions ends for the previous level */ + sum_funcs_end[pos+1]= *func; + + /* Find the start of the group for this level */ + for (i= 0, start_group= group_list ; + i++ < pos ; + start_group= start_group->next) + ; + + it.rewind(); + while ((item= it++)) + { + if (item == first_field) + { + real_fields= 1; // End of hidden fields + ref_array= ref_array_start; + } + + if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() && + (!((Item_sum*) item)->depended_from() || + ((Item_sum *)item)->depended_from() == select_lex)) + + { + /* + This is a top level summary function that must be replaced with + a sum function that is reset for this level. + + NOTE: This code creates an object which is not that nice in a + sub select. Fortunately it's not common to have rollup in + sub selects. + */ + item= item->copy_or_same(thd); + ((Item_sum*) item)->make_unique(); + *(*func)= (Item_sum*) item; + (*func)++; + } + else + { + /* Check if this is something that is part of this group by */ + ORDER *group_tmp; + for (group_tmp= start_group, i= pos ; + group_tmp ; group_tmp= group_tmp->next, i++) + { + if (*group_tmp->item == item) + { + /* + This is an element that is used by the GROUP BY and should be + set to NULL in this level + */ + Item_null_result *null_item= new (thd->mem_root) Item_null_result(); + if (!null_item) + return 1; + item->maybe_null= 1; // Value will be null sometimes + null_item->result_field= item->get_tmp_table_field(); + item= null_item; + break; + } + } + } + *ref_array= item; + if (real_fields) + { + (void) new_it++; // Point to next item + new_it.replace(item); // Replace previous + ref_array++; + } + else + ref_array--; + } + } + sum_funcs_end[0]= *func; // Point to last function + return 0; +} + +/** + Send all rollup levels higher than the current one to the client. + + @b SAMPLE + @code + SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP + @endcode + + @param idx Level we are on: + - 0 = Total sum level + - 1 = First group changed (a) + - 2 = Second group changed (a,b) + + @retval + 0 ok + @retval + 1 If send_data_failed() +*/ + +int JOIN::rollup_send_data(uint idx) +{ + uint i; + for (i= send_group_parts ; i-- > idx ; ) + { + /* Get reference pointers to sum functions in place */ + memcpy((char*) ref_pointer_array, + (char*) rollup.ref_pointer_arrays[i], + ref_pointer_array_size); + if ((!having || having->val_int())) + { + if (send_records < unit->select_limit_cnt && do_send_rows && + result->send_data(rollup.fields[i])) + return 1; + send_records++; + } + } + /* Restore ref_pointer_array */ + set_items_ref_array(current_ref_pointer_array); + return 0; +} + +/** + Write all rollup levels higher than the current one to a temp table. + + @b SAMPLE + @code + SELECT a, b, SUM(c) FROM t1 GROUP BY a,b WITH ROLLUP + @endcode + + @param idx Level we are on: + - 0 = Total sum level + - 1 = First group changed (a) + - 2 = Second group changed (a,b) + @param table reference to temp table + + @retval + 0 ok + @retval + 1 if write_data_failed() +*/ + +int JOIN::rollup_write_data(uint idx, TABLE *table_arg) +{ + uint i; + for (i= send_group_parts ; i-- > idx ; ) + { + /* Get reference pointers to sum functions in place */ + memcpy((char*) ref_pointer_array, + (char*) rollup.ref_pointer_arrays[i], + ref_pointer_array_size); + if ((!having || having->val_int())) + { + int write_error; + Item *item; + List_iterator_fast it(rollup.fields[i]); + while ((item= it++)) + { + if (item->type() == Item::NULL_ITEM && item->is_result_field()) + item->save_in_result_field(1); + } + copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]); + if ((write_error= table_arg->file->ha_write_row(table_arg->record[0]))) + { + if (create_myisam_from_heap(thd, table_arg, &tmp_table_param, + write_error, 0)) + return 1; + } + } + } + /* Restore ref_pointer_array */ + set_items_ref_array(current_ref_pointer_array); + return 0; +} + +/** + clear results if there are not rows found for group + (end_send_group/end_write_group) +*/ + +void JOIN::clear() +{ + clear_tables(this); + copy_fields(&tmp_table_param); + + if (sum_funcs) + { + Item_sum *func, **func_ptr= sum_funcs; + while ((func= *(func_ptr++))) + func->clear(); + } +} + +/** + EXPLAIN handling. + + Send a description about what how the select will be done to stdout. +*/ + +static void select_describe(JOIN *join, bool need_tmp_table, bool need_order, + bool distinct,const char *message) +{ + List field_list; + List item_list; + THD *thd=join->thd; + select_result *result=join->result; + Item *item_null= new Item_null(); + CHARSET_INFO *cs= system_charset_info; + int quick_type; + DBUG_ENTER("select_describe"); + DBUG_PRINT("info", ("Select 0x%lx, type %s, message %s", + (ulong)join->select_lex, join->select_lex->type, + message ? message : "NULL")); + /* Don't log this into the slow query log */ + thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED); + join->unit->offset_limit_cnt= 0; + + /* + NOTE: the number/types of items pushed into item_list must be in sync with + EXPLAIN column types as they're "defined" in THD::send_explain_fields() + */ + if (message) + { + item_list.push_back(new Item_int((int32) + join->select_lex->select_number)); + item_list.push_back(new Item_string(join->select_lex->type, + strlen(join->select_lex->type), cs)); + for (uint i=0 ; i < 7; i++) + item_list.push_back(item_null); + if (join->thd->lex->describe & DESCRIBE_PARTITIONS) + item_list.push_back(item_null); + if (join->thd->lex->describe & DESCRIBE_EXTENDED) + item_list.push_back(item_null); + + item_list.push_back(new Item_string(message,strlen(message),cs)); + if (result->send_data(item_list)) + join->error= 1; + } + else if (join->select_lex == join->unit->fake_select_lex) + { + /* + here we assume that the query will return at least two rows, so we + show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong + and no filesort will be actually done, but executing all selects in + the UNION to provide precise EXPLAIN information will hardly be + appreciated :) + */ + char table_name_buffer[NAME_LEN]; + item_list.empty(); + /* id */ + item_list.push_back(new Item_null); + /* select_type */ + item_list.push_back(new Item_string(join->select_lex->type, + strlen(join->select_lex->type), + cs)); + /* table */ + { + SELECT_LEX *sl= join->unit->first_select(); + uint len= 6, lastop= 0; + memcpy(table_name_buffer, STRING_WITH_LEN("next_select()) + { + len+= lastop; + lastop= my_snprintf(table_name_buffer + len, NAME_LEN - len, + "%u,", sl->select_number); + } + if (sl || len + lastop >= NAME_LEN) + { + memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1); + len+= 4; + } + else + { + len+= lastop; + table_name_buffer[len - 1]= '>'; // change ',' to '>' + } + item_list.push_back(new Item_string(table_name_buffer, len, cs)); + } + /* partitions */ + if (join->thd->lex->describe & DESCRIBE_PARTITIONS) + item_list.push_back(item_null); + /* type */ + item_list.push_back(new Item_string(join_type_str[JT_ALL], + strlen(join_type_str[JT_ALL]), + cs)); + /* possible_keys */ + item_list.push_back(item_null); + /* key*/ + item_list.push_back(item_null); + /* key_len */ + item_list.push_back(item_null); + /* ref */ + item_list.push_back(item_null); + /* in_rows */ + if (join->thd->lex->describe & DESCRIBE_EXTENDED) + item_list.push_back(item_null); + /* rows */ + item_list.push_back(item_null); + /* extra */ + if (join->unit->global_parameters->order_list.first) + item_list.push_back(new Item_string("Using filesort", + 14, cs)); + else + item_list.push_back(new Item_string("", 0, cs)); + + if (result->send_data(item_list)) + join->error= 1; + } + else + { + table_map used_tables=0; + for (uint i=0 ; i < join->tables ; i++) + { + JOIN_TAB *tab=join->join_tab+i; + TABLE *table=tab->table; + TABLE_LIST *table_list= tab->table->pos_in_table_list; + char buff[512]; + char buff1[512], buff2[512], buff3[512]; + char keylen_str_buf[64]; + String extra(buff, sizeof(buff),cs); + char table_name_buffer[NAME_LEN]; + String tmp1(buff1,sizeof(buff1),cs); + String tmp2(buff2,sizeof(buff2),cs); + String tmp3(buff3,sizeof(buff3),cs); + extra.length(0); + tmp1.length(0); + tmp2.length(0); + tmp3.length(0); + + quick_type= -1; + item_list.empty(); + /* id */ + item_list.push_back(new Item_uint((uint32) + join->select_lex->select_number)); + /* select_type */ + item_list.push_back(new Item_string(join->select_lex->type, + strlen(join->select_lex->type), + cs)); + if (tab->type == JT_ALL && tab->select && tab->select->quick) + { + quick_type= tab->select->quick->get_type(); + if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) || + (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) || + (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION)) + tab->type = JT_INDEX_MERGE; + else + tab->type = JT_RANGE; + } + /* table */ + if (table->derived_select_number) + { + /* Derived table name generation */ + int len= my_snprintf(table_name_buffer, sizeof(table_name_buffer)-1, + "", + table->derived_select_number); + item_list.push_back(new Item_string(table_name_buffer, len, cs)); + } + else + { + TABLE_LIST *real_table= table->pos_in_table_list; + item_list.push_back(new Item_string(real_table->alias, + strlen(real_table->alias), + cs)); + } + /* "partitions" column */ + if (join->thd->lex->describe & DESCRIBE_PARTITIONS) + { +#ifdef WITH_PARTITION_STORAGE_ENGINE + partition_info *part_info; + if (!table->derived_select_number && + (part_info= table->part_info)) + { + Item_string *item_str= new Item_string(cs); + make_used_partitions_str(part_info, &item_str->str_value); + item_list.push_back(item_str); + } + else + item_list.push_back(item_null); +#else + /* just produce empty column if partitioning is not compiled in */ + item_list.push_back(item_null); +#endif + } + /* "type" column */ + item_list.push_back(new Item_string(join_type_str[tab->type], + strlen(join_type_str[tab->type]), + cs)); + /* Build "possible_keys" value and add it to item_list */ + if (!tab->keys.is_clear_all()) + { + uint j; + for (j=0 ; j < table->s->keys ; j++) + { + if (tab->keys.is_set(j)) + { + if (tmp1.length()) + tmp1.append(','); + tmp1.append(table->key_info[j].name, + strlen(table->key_info[j].name), + system_charset_info); + } + } + } + if (tmp1.length()) + item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs)); + else + item_list.push_back(item_null); + + /* Build "key", "key_len", and "ref" values and add them to item_list */ + if (tab->ref.key_parts) + { + KEY *key_info=table->key_info+ tab->ref.key; + register uint length; + item_list.push_back(new Item_string(key_info->name, + strlen(key_info->name), + system_charset_info)); + length= longlong2str(tab->ref.key_length, keylen_str_buf, 10) - + keylen_str_buf; + item_list.push_back(new Item_string(keylen_str_buf, length, + system_charset_info)); + for (store_key **ref=tab->ref.key_copy ; *ref ; ref++) + { + if (tmp2.length()) + tmp2.append(','); + tmp2.append((*ref)->name(), strlen((*ref)->name()), + system_charset_info); + } + item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs)); + } + else if (tab->type == JT_NEXT) + { + KEY *key_info=table->key_info+ tab->index; + register uint length; + item_list.push_back(new Item_string(key_info->name, + strlen(key_info->name),cs)); + length= longlong2str(key_info->key_length, keylen_str_buf, 10) - + keylen_str_buf; + item_list.push_back(new Item_string(keylen_str_buf, + length, + system_charset_info)); + item_list.push_back(item_null); + } + else if (tab->select && tab->select->quick) + { + tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3); + item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs)); + item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs)); + item_list.push_back(item_null); + } + else + { + if (table_list->schema_table && + table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE) + { + const char *tmp_buff; + int f_idx; + if (table_list->has_db_lookup_value) + { + f_idx= table_list->schema_table->idx_field1; + tmp_buff= table_list->schema_table->fields_info[f_idx].field_name; + tmp2.append(tmp_buff, strlen(tmp_buff), cs); + } + if (table_list->has_table_lookup_value) + { + if (table_list->has_db_lookup_value) + tmp2.append(','); + f_idx= table_list->schema_table->idx_field2; + tmp_buff= table_list->schema_table->fields_info[f_idx].field_name; + tmp2.append(tmp_buff, strlen(tmp_buff), cs); + } + if (tmp2.length()) + item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs)); + else + item_list.push_back(item_null); + } + else + item_list.push_back(item_null); + item_list.push_back(item_null); + item_list.push_back(item_null); + } + + /* Add "rows" field to item_list. */ + if (table_list->schema_table) + { + /* in_rows */ + if (join->thd->lex->describe & DESCRIBE_EXTENDED) + item_list.push_back(item_null); + /* rows */ + item_list.push_back(item_null); + } + else + { + ha_rows examined_rows; + if (tab->select && tab->select->quick) + examined_rows= tab->select->quick->records; + else if (tab->type == JT_NEXT || tab->type == JT_ALL) + examined_rows= tab->limit ? tab->limit : tab->table->file->records(); + else + examined_rows=(ha_rows)join->best_positions[i].records_read; + + item_list.push_back(new Item_int((longlong) (ulonglong) examined_rows, + MY_INT64_NUM_DECIMAL_DIGITS)); + + /* Add "filtered" field to item_list. */ + if (join->thd->lex->describe & DESCRIBE_EXTENDED) + { + float f= 0.0; + if (examined_rows) + f= (float) (100.0 * join->best_positions[i].records_read / + examined_rows); + item_list.push_back(new Item_float(f, 2)); + } + } + + /* Build "Extra" field and add it to item_list. */ + my_bool key_read=table->key_read; + if ((tab->type == JT_NEXT || tab->type == JT_CONST) && + table->covering_keys.is_set(tab->index)) + key_read=1; + if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT && + !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row) + key_read=1; + + if (tab->info) + item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs)); + else if (tab->packed_info & TAB_INFO_HAVE_VALUE) + { + if (tab->packed_info & TAB_INFO_USING_INDEX) + extra.append(STRING_WITH_LEN("; Using index")); + if (tab->packed_info & TAB_INFO_USING_WHERE) + extra.append(STRING_WITH_LEN("; Using where")); + if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL) + extra.append(STRING_WITH_LEN("; Full scan on NULL key")); + /* Skip initial "; "*/ + const char *str= extra.ptr(); + uint32 len= extra.length(); + if (len) + { + str += 2; + len -= 2; + } + item_list.push_back(new Item_string(str, len, cs)); + } + else + { + if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || + quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT || + quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) + { + extra.append(STRING_WITH_LEN("; Using ")); + tab->select->quick->add_info_string(&extra); + } + if (tab->select) + { + if (tab->use_quick == 2) + { + /* 4 bits per 1 hex digit + terminating '\0' */ + char buf[MAX_KEY / 4 + 1]; + extra.append(STRING_WITH_LEN("; Range checked for each " + "record (index map: 0x")); + extra.append(tab->keys.print(buf)); + extra.append(')'); + } + else if (tab->select->cond) + { + const COND *pushed_cond= tab->table->file->pushed_cond; + + if (thd->variables.engine_condition_pushdown && pushed_cond) + { + extra.append(STRING_WITH_LEN("; Using where with pushed " + "condition")); + if (thd->lex->describe & DESCRIBE_EXTENDED) + { + extra.append(STRING_WITH_LEN(": ")); + ((COND *)pushed_cond)->print(&extra, QT_ORDINARY); + } + } + else + extra.append(STRING_WITH_LEN("; Using where")); + } + } + if (table_list->schema_table && + table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE) + { + if (!table_list->table_open_method) + extra.append(STRING_WITH_LEN("; Skip_open_table")); + else if (table_list->table_open_method == OPEN_FRM_ONLY) + extra.append(STRING_WITH_LEN("; Open_frm_only")); + else + extra.append(STRING_WITH_LEN("; Open_full_table")); + if (table_list->has_db_lookup_value && + table_list->has_table_lookup_value) + extra.append(STRING_WITH_LEN("; Scanned 0 databases")); + else if (table_list->has_db_lookup_value || + table_list->has_table_lookup_value) + extra.append(STRING_WITH_LEN("; Scanned 1 database")); + else + extra.append(STRING_WITH_LEN("; Scanned all databases")); + } + if (key_read) + { + if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX) + extra.append(STRING_WITH_LEN("; Using index for group-by")); + else + extra.append(STRING_WITH_LEN("; Using index")); + } + if (table->reginfo.not_exists_optimize) + extra.append(STRING_WITH_LEN("; Not exists")); + if (need_tmp_table) + { + need_tmp_table=0; + extra.append(STRING_WITH_LEN("; Using temporary")); + } + if (need_order) + { + need_order=0; + extra.append(STRING_WITH_LEN("; Using filesort")); + } + if (distinct & test_all_bits(used_tables,thd->used_tables)) + extra.append(STRING_WITH_LEN("; Distinct")); + + for (uint part= 0; part < tab->ref.key_parts; part++) + { + if (tab->ref.cond_guards[part]) + { + extra.append(STRING_WITH_LEN("; Full scan on NULL key")); + break; + } + } + if (i > 0 && tab[-1].next_select == sub_select_cache) + extra.append(STRING_WITH_LEN("; Using join buffer")); + + /* Skip initial "; "*/ + const char *str= extra.ptr(); + uint32 len= extra.length(); + if (len) + { + str += 2; + len -= 2; + } + item_list.push_back(new Item_string(str, len, cs)); + } + // For next iteration + used_tables|=table->map; + if (result->send_data(item_list)) + join->error= 1; + } + } + for (SELECT_LEX_UNIT *unit= join->select_lex->first_inner_unit(); + unit; + unit= unit->next_unit()) + { + if (mysql_explain_union(thd, unit, result)) + DBUG_VOID_RETURN; + } + DBUG_VOID_RETURN; +} + + +bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result) +{ + DBUG_ENTER("mysql_explain_union"); + bool res= 0; + SELECT_LEX *first= unit->first_select(); + + for (SELECT_LEX *sl= first; + sl; + sl= sl->next_select()) + { + // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only + uint8 uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN); + sl->type= (((&thd->lex->select_lex)==sl)? + (sl->first_inner_unit() || sl->next_select() ? + "PRIMARY" : "SIMPLE"): + ((sl == first)? + ((sl->linkage == DERIVED_TABLE_TYPE) ? + "DERIVED": + ((uncacheable & UNCACHEABLE_DEPENDENT) ? + "DEPENDENT SUBQUERY": + (uncacheable?"UNCACHEABLE SUBQUERY": + "SUBQUERY"))): + ((uncacheable & UNCACHEABLE_DEPENDENT) ? + "DEPENDENT UNION": + uncacheable?"UNCACHEABLE UNION": + "UNION"))); + sl->options|= SELECT_DESCRIBE; + } + if (unit->is_union()) + { + unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization + unit->fake_select_lex->type= "UNION RESULT"; + unit->fake_select_lex->options|= SELECT_DESCRIBE; + if (!(res= unit->prepare(thd, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE))) + res= unit->exec(); + res|= unit->cleanup(); + } + else + { + thd->lex->current_select= first; + unit->set_limit(unit->global_parameters); + res= mysql_select(thd, &first->ref_pointer_array, + (TABLE_LIST*) first->table_list.first, + first->with_wild, first->item_list, + first->where, + first->order_list.elements + + first->group_list.elements, + (ORDER*) first->order_list.first, + (ORDER*) first->group_list.first, + first->having, + (ORDER*) thd->lex->proc_list.first, + first->options | thd->options | SELECT_DESCRIBE, + result, unit, first); + } + DBUG_RETURN(res || thd->is_error()); +} + + +/** + Print joins from the FROM clause. + + @param thd thread handler + @param str string where table should be printed + @param tables list of tables in join + @query_type type of the query is being generated +*/ + +static void print_join(THD *thd, + String *str, + List *tables, + enum_query_type query_type) +{ + /* List is reversed => we should reverse it before using */ + List_iterator_fast ti(*tables); + TABLE_LIST **table= (TABLE_LIST **)thd->alloc(sizeof(TABLE_LIST*) * + tables->elements); + if (table == 0) + return; // out of memory + + for (TABLE_LIST **t= table + (tables->elements - 1); t >= table; t--) + *t= ti++; + + DBUG_ASSERT(tables->elements >= 1); + (*table)->print(thd, str, query_type); + + TABLE_LIST **end= table + tables->elements; + for (TABLE_LIST **tbl= table + 1; tbl < end; tbl++) + { + TABLE_LIST *curr= *tbl; + if (curr->outer_join) + { + /* MySQL converts right to left joins */ + str->append(STRING_WITH_LEN(" left join ")); + } + else if (curr->straight) + str->append(STRING_WITH_LEN(" straight_join ")); + else + str->append(STRING_WITH_LEN(" join ")); + curr->print(thd, str, query_type); + if (curr->on_expr) + { + str->append(STRING_WITH_LEN(" on(")); + curr->on_expr->print(str, query_type); + str->append(')'); + } + } +} + + +/** + @brief Print an index hint + + @details Prints out the USE|FORCE|IGNORE index hint. + + @param thd the current thread + @param[out] str appends the index hint here + @param hint what the hint is (as string : "USE INDEX"| + "FORCE INDEX"|"IGNORE INDEX") + @param hint_length the length of the string in 'hint' + @param indexes a list of index names for the hint +*/ + +void +Index_hint::print(THD *thd, String *str) +{ + switch (type) + { + case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break; + case INDEX_HINT_USE: str->append(STRING_WITH_LEN("USE INDEX")); break; + case INDEX_HINT_FORCE: str->append(STRING_WITH_LEN("FORCE INDEX")); break; + } + str->append (STRING_WITH_LEN(" (")); + if (key_name.length) + { + if (thd && !my_strnncoll(system_charset_info, + (const uchar *)key_name.str, key_name.length, + (const uchar *)primary_key_name, + strlen(primary_key_name))) + str->append(primary_key_name); + else + append_identifier(thd, str, key_name.str, key_name.length); + } + str->append(')'); +} + + +/** + Print table as it should be in join list. + + @param str string where table should be printed +*/ + +void TABLE_LIST::print(THD *thd, String *str, enum_query_type query_type) +{ + if (nested_join) + { + str->append('('); + print_join(thd, str, &nested_join->join_list, query_type); + str->append(')'); + } + else + { + const char *cmp_name; // Name to compare with alias + if (view_name.str) + { + // A view + + if (!(belong_to_view && + belong_to_view->compact_view_format)) + { + append_identifier(thd, str, view_db.str, view_db.length); + str->append('.'); + } + append_identifier(thd, str, view_name.str, view_name.length); + cmp_name= view_name.str; + } + else if (derived) + { + // A derived table + str->append('('); + derived->print(str, query_type); + str->append(')'); + cmp_name= ""; // Force printing of alias + } + else + { + // A normal table + + if (!(belong_to_view && + belong_to_view->compact_view_format)) + { + append_identifier(thd, str, db, db_length); + str->append('.'); + } + if (schema_table) + { + append_identifier(thd, str, schema_table_name, + strlen(schema_table_name)); + cmp_name= schema_table_name; + } + else + { + append_identifier(thd, str, table_name, table_name_length); + cmp_name= table_name; + } + } + if (my_strcasecmp(table_alias_charset, cmp_name, alias)) + { + char t_alias_buff[MAX_ALIAS_NAME]; + const char *t_alias= alias; + + str->append(' '); + if (lower_case_table_names== 1) + { + if (alias && alias[0]) + { + strmov(t_alias_buff, alias); + my_casedn_str(files_charset_info, t_alias_buff); + t_alias= t_alias_buff; + } + } + + append_identifier(thd, str, t_alias, strlen(t_alias)); + } + + if (index_hints) + { + List_iterator it(*index_hints); + Index_hint *hint; + + while ((hint= it++)) + { + str->append (STRING_WITH_LEN(" ")); + hint->print (thd, str); + } + } + } +} + + +void st_select_lex::print(THD *thd, String *str, enum_query_type query_type) +{ + /* QQ: thd may not be set for sub queries, but this should be fixed */ + if (!thd) + thd= current_thd; + + str->append(STRING_WITH_LEN("select ")); + + /* First add options */ + if (options & SELECT_STRAIGHT_JOIN) + str->append(STRING_WITH_LEN("straight_join ")); + if ((thd->lex->lock_option == TL_READ_HIGH_PRIORITY) && + (this == &thd->lex->select_lex)) + str->append(STRING_WITH_LEN("high_priority ")); + if (options & SELECT_DISTINCT) + str->append(STRING_WITH_LEN("distinct ")); + if (options & SELECT_SMALL_RESULT) + str->append(STRING_WITH_LEN("sql_small_result ")); + if (options & SELECT_BIG_RESULT) + str->append(STRING_WITH_LEN("sql_big_result ")); + if (options & OPTION_BUFFER_RESULT) + str->append(STRING_WITH_LEN("sql_buffer_result ")); + if (options & OPTION_FOUND_ROWS) + str->append(STRING_WITH_LEN("sql_calc_found_rows ")); + switch (sql_cache) + { + case SQL_NO_CACHE: + str->append(STRING_WITH_LEN("sql_no_cache ")); + break; + case SQL_CACHE: + str->append(STRING_WITH_LEN("sql_cache ")); + break; + case SQL_CACHE_UNSPECIFIED: + break; + default: + DBUG_ASSERT(0); + } + + //Item List + bool first= 1; + List_iterator_fast it(item_list); + Item *item; + while ((item= it++)) + { + if (first) + first= 0; + else + str->append(','); + item->print_item_w_name(str, query_type); + } + + /* + from clause + TODO: support USING/FORCE/IGNORE index + */ + //printf("before from: %s\n\n", str->ptr()); + + if (table_list.elements) + { + str->append(STRING_WITH_LEN(" from ")); + /* go through join tree */ + print_join(thd, str, &top_join_list, query_type); + } + else if (where) + { + /* + "SELECT 1 FROM DUAL WHERE 2" should not be printed as + "SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not. + */ + str->append(STRING_WITH_LEN(" from DUAL ")); + } + + // InfiniDB skip WHERE clause and after. the print functions are + // Called just for post process vtable creation. + if (query_type == QT_INFINIDB_NO_QUOTE || query_type == QT_INFINIDB_DERIVED) + return; + // Where + //printf("before where: %s\n\n", str->ptr()); + Item *cur_where= where; + if (join) + cur_where= join->conds; + if (cur_where || cond_value != Item::COND_UNDEF) + { + str->append(STRING_WITH_LEN(" where ")); + if (cur_where) + cur_where->print(str, query_type); + else + str->append(cond_value != Item::COND_FALSE ? "1" : "0"); + } + //printf("after where: %s\n\n", str->ptr()); + + // group by & olap + if (group_list.elements) + { + str->append(STRING_WITH_LEN(" group by ")); + print_order(str, (ORDER *) group_list.first, query_type); + switch (olap) + { + case CUBE_TYPE: + str->append(STRING_WITH_LEN(" with cube")); + break; + case ROLLUP_TYPE: + str->append(STRING_WITH_LEN(" with rollup")); + break; + default: + ; //satisfy compiler + } + } + + // having + Item *cur_having= having; + if (join) + cur_having= join->having; + + if (cur_having || having_value != Item::COND_UNDEF) + { + str->append(STRING_WITH_LEN(" having ")); + if (cur_having) + cur_having->print(str, query_type); + else + str->append(having_value != Item::COND_FALSE ? "1" : "0"); + } + + if (order_list.elements) + { + str->append(STRING_WITH_LEN(" order by ")); + print_order(str, (ORDER *) order_list.first, query_type); + } + + // limit + print_limit(thd, str, query_type); + + // PROCEDURE unsupported here +} + + +/** + change select_result object of JOIN. + + @param res new select_result object + + @retval + FALSE OK + @retval + TRUE error +*/ + +bool JOIN::change_result(select_result *res) +{ + DBUG_ENTER("JOIN::change_result"); + result= res; + if (!procedure && (result->prepare(fields_list, select_lex->master_unit()) || + result->prepare2())) + { + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + +/** + @} (end of group Query_Optimizer) +*/ diff --git a/dbcon/mysql/sql_table.cc b/dbcon/mysql/sql_table.cc new file mode 100644 index 00000000..e13c8609 --- /dev/null +++ b/dbcon/mysql/sql_table.cc @@ -0,0 +1,7979 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* drop and alter of tables */ + +#include "mysql_priv.h" +#include +#include +#include +#include "sp_head.h" +#include "sql_trigger.h" +#include "sql_show.h" + +#ifdef __WIN__ +#include +#endif + +int creating_table= 0; // How many mysql_create_table are running + +const char *primary_key_name="PRIMARY"; + +static bool check_if_keyname_exists(const char *name,KEY *start, KEY *end); +static char *make_unique_key_name(const char *field_name,KEY *start,KEY *end); +static int copy_data_between_tables(TABLE *from,TABLE *to, + List &create, bool ignore, + uint order_num, ORDER *order, + ha_rows *copied,ha_rows *deleted, + enum enum_enable_or_disable keys_onoff, + bool error_if_not_empty); + +static bool prepare_blob_field(THD *thd, Create_field *sql_field); +static bool check_engine(THD *, const char *, HA_CREATE_INFO *); +static int +mysql_prepare_create_table(THD *thd, HA_CREATE_INFO *create_info, + Alter_info *alter_info, + bool tmp_table, + uint *db_options, + handler *file, KEY **key_info_buffer, + uint *key_count, int select_field_count); +static bool +mysql_prepare_alter_table(THD *thd, TABLE *table, + HA_CREATE_INFO *create_info, + Alter_info *alter_info); + +#ifndef DBUG_OFF + +/* Wait until we get a 'mysql_kill' signal */ + +static void wait_for_kill_signal(THD *thd) +{ + while (thd->killed == 0) + sleep(1); + // Reset signal and continue as if nothing happend + thd->killed= THD::NOT_KILLED; +} +#endif + + +/** + @brief Helper function for explain_filename +*/ +static char* add_identifier(char *to_p, const char * end_p, + const char* name, uint name_len, bool add_quotes) +{ + uint res; + uint errors; + const char *conv_name; + char tmp_name[FN_REFLEN]; + char conv_string[FN_REFLEN]; + + DBUG_ENTER("add_identifier"); + if (!name[name_len]) + conv_name= name; + else + { + strnmov(tmp_name, name, name_len); + tmp_name[name_len]= 0; + conv_name= tmp_name; + } + res= strconvert(&my_charset_filename, conv_name, system_charset_info, + conv_string, FN_REFLEN, &errors); + if (!res || errors) + { + DBUG_PRINT("error", ("strconvert of '%s' failed with %u (errors: %u)", conv_name, res, errors)); + conv_name= name; + } + else + { + DBUG_PRINT("info", ("conv '%s' -> '%s'", conv_name, conv_string)); + conv_name= conv_string; + } + + if (add_quotes && (end_p - to_p > 2)) + { + *(to_p++)= '`'; + while (*conv_name && (end_p - to_p - 1) > 0) + { + uint length= my_mbcharlen(system_charset_info, *conv_name); + if (!length) + length= 1; + if (length == 1 && *conv_name == '`') + { + if ((end_p - to_p) < 3) + break; + *(to_p++)= '`'; + *(to_p++)= *(conv_name++); + } + else if (((long) length) < (end_p - to_p)) + { + to_p= strnmov(to_p, conv_name, length); + conv_name+= length; + } + else + break; /* string already filled */ + } + to_p= strnmov(to_p, "`", end_p - to_p); + } + else + to_p= strnmov(to_p, conv_name, end_p - to_p); + DBUG_RETURN(to_p); +} + + +/** + @brief Explain a path name by split it to database, table etc. + + @details Break down the path name to its logic parts + (database, table, partition, subpartition). + filename_to_tablename cannot be used on partitions, due to the #P# part. + There can be up to 6 '#', #P# for partition, #SP# for subpartition + and #TMP# or #REN# for temporary or renamed partitions. + This should be used when something should be presented to a user in a + diagnostic, error etc. when it would be useful to know what a particular + file [and directory] means. Such as SHOW ENGINE STATUS, error messages etc. + + @param from Path name in my_charset_filename + Null terminated in my_charset_filename, normalized + to use '/' as directory separation character. + @param to Explained name in system_charset_info + @param to_length Size of to buffer + @param explain_mode Requested output format. + EXPLAIN_ALL_VERBOSE -> + [Database `db`, ]Table `tbl`[,[ Temporary| Renamed] + Partition `p` [, Subpartition `sp`]] + EXPLAIN_PARTITIONS_VERBOSE -> `db`.`tbl` + [[ Temporary| Renamed] Partition `p` + [, Subpartition `sp`]] + EXPLAIN_PARTITIONS_AS_COMMENT -> `db`.`tbl` |* + [,[ Temporary| Renamed] Partition `p` + [, Subpartition `sp`]] *| + (| is really a /, and it is all in one line) + EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING -> + same as above but no quotes are added. + + @retval Length of returned string +*/ + +uint explain_filename(const char *from, + char *to, + uint to_length, + enum_explain_filename_mode explain_mode) +{ + uint res= 0; + char *to_p= to; + char *end_p= to_p + to_length; + const char *db_name= NULL; + int db_name_len= 0; + const char *table_name; + int table_name_len= 0; + const char *part_name= NULL; + int part_name_len= 0; + const char *subpart_name= NULL; + int subpart_name_len= 0; + enum enum_file_name_type {NORMAL, TEMP, RENAMED} name_type= NORMAL; + const char *tmp_p; + DBUG_ENTER("explain_filename"); + DBUG_PRINT("enter", ("from '%s'", from)); + tmp_p= from; + table_name= from; + /* + If '/' then take last directory part as database. + '/' is the directory separator, not FN_LIB_CHAR + */ + while ((tmp_p= strchr(tmp_p, '/'))) + { + db_name= table_name; + /* calculate the length */ + db_name_len= tmp_p - db_name; + tmp_p++; + table_name= tmp_p; + } + tmp_p= table_name; + while (!res && (tmp_p= strchr(tmp_p, '#'))) + { + tmp_p++; + switch (tmp_p[0]) { + case 'P': + case 'p': + if (tmp_p[1] == '#') + part_name= tmp_p + 2; + else + res= 1; + tmp_p+= 2; + break; + case 'S': + case 's': + if ((tmp_p[1] == 'P' || tmp_p[1] == 'p') && tmp_p[2] == '#') + { + part_name_len= tmp_p - part_name - 1; + subpart_name= tmp_p + 3; + } + else + res= 2; + tmp_p+= 3; + break; + case 'T': + case 't': + if ((tmp_p[1] == 'M' || tmp_p[1] == 'm') && + (tmp_p[2] == 'P' || tmp_p[2] == 'p') && + tmp_p[3] == '#' && !tmp_p[4]) + name_type= TEMP; + else + res= 3; + tmp_p+= 4; + break; + case 'R': + case 'r': + if ((tmp_p[1] == 'E' || tmp_p[1] == 'e') && + (tmp_p[2] == 'N' || tmp_p[2] == 'n') && + tmp_p[3] == '#' && !tmp_p[4]) + name_type= RENAMED; + else + res= 4; + tmp_p+= 4; + break; + default: + res= 5; + } + } + if (res) + { + /* Better to give something back if we fail parsing, than nothing at all */ + DBUG_PRINT("info", ("Error in explain_filename: %u", res)); + sql_print_warning("Invalid (old?) table or database name '%s'", from); + DBUG_RETURN(my_snprintf(to, to_length, + "", + res, from)); + } + if (part_name) + { + table_name_len= part_name - table_name - 3; + if (subpart_name) + subpart_name_len= strlen(subpart_name); + else + part_name_len= strlen(part_name); + if (name_type != NORMAL) + { + if (subpart_name) + subpart_name_len-= 5; + else + part_name_len-= 5; + } + } + else + table_name_len= strlen(table_name); + if (db_name) + { + if (explain_mode == EXPLAIN_ALL_VERBOSE) + { + to_p= strnmov(to_p, ER(ER_DATABASE_NAME), end_p - to_p); + *(to_p++)= ' '; + to_p= add_identifier(to_p, end_p, db_name, db_name_len, 1); + to_p= strnmov(to_p, ", ", end_p - to_p); + } + else + { + to_p= add_identifier(to_p, end_p, db_name, db_name_len, + (explain_mode != + EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING)); + to_p= strnmov(to_p, ".", end_p - to_p); + } + } + if (explain_mode == EXPLAIN_ALL_VERBOSE) + { + to_p= strnmov(to_p, ER(ER_TABLE_NAME), end_p - to_p); + *(to_p++)= ' '; + to_p= add_identifier(to_p, end_p, table_name, table_name_len, 1); + } + else + to_p= add_identifier(to_p, end_p, table_name, table_name_len, + (explain_mode != + EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING)); + if (part_name) + { + if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT || + explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING) + to_p= strnmov(to_p, " /* ", end_p - to_p); + else if (explain_mode == EXPLAIN_PARTITIONS_VERBOSE) + to_p= strnmov(to_p, " ", end_p - to_p); + else + to_p= strnmov(to_p, ", ", end_p - to_p); + if (name_type != NORMAL) + { + if (name_type == TEMP) + to_p= strnmov(to_p, ER(ER_TEMPORARY_NAME), end_p - to_p); + else + to_p= strnmov(to_p, ER(ER_RENAMED_NAME), end_p - to_p); + to_p= strnmov(to_p, " ", end_p - to_p); + } + to_p= strnmov(to_p, ER(ER_PARTITION_NAME), end_p - to_p); + *(to_p++)= ' '; + to_p= add_identifier(to_p, end_p, part_name, part_name_len, + (explain_mode != + EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING)); + if (subpart_name) + { + to_p= strnmov(to_p, ", ", end_p - to_p); + to_p= strnmov(to_p, ER(ER_SUBPARTITION_NAME), end_p - to_p); + *(to_p++)= ' '; + to_p= add_identifier(to_p, end_p, subpart_name, subpart_name_len, + (explain_mode != + EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING)); + } + if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT || + explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING) + to_p= strnmov(to_p, " */", end_p - to_p); + } + DBUG_PRINT("exit", ("to '%s'", to)); + DBUG_RETURN(to_p - to); +} + + +/* + Translate a file name to a table name (WL #1324). + + SYNOPSIS + filename_to_tablename() + from The file name in my_charset_filename. + to OUT The table name in system_charset_info. + to_length The size of the table name buffer. + + RETURN + Table name length. +*/ + +uint filename_to_tablename(const char *from, char *to, uint to_length) +{ + uint errors; + size_t res; + DBUG_ENTER("filename_to_tablename"); + DBUG_PRINT("enter", ("from '%s'", from)); + + if (!memcmp(from, tmp_file_prefix, tmp_file_prefix_length)) + { + /* Temporary table name. */ + res= (strnmov(to, from, to_length) - to); + } + else + { + res= strconvert(&my_charset_filename, from, + system_charset_info, to, to_length, &errors); + if (errors) // Old 5.0 name + { + res= (strxnmov(to, to_length, MYSQL50_TABLE_NAME_PREFIX, from, NullS) - + to); + sql_print_error("Invalid (old?) table or database name '%s'", from); + /* + TODO: add a stored procedure for fix table and database names, + and mention its name in error log. + */ + } + } + + DBUG_PRINT("exit", ("to '%s'", to)); + DBUG_RETURN(res); +} + + +/** + Check if given string begins with "#mysql50#" prefix, cut it if so. + + @param from string to check and cut + @param to[out] buffer for result string + @param to_length its size + + @retval + 0 no prefix found + @retval + non-0 result string length +*/ + +uint check_n_cut_mysql50_prefix(const char *from, char *to, uint to_length) +{ + if (from[0] == '#' && + !strncmp(from, MYSQL50_TABLE_NAME_PREFIX, + MYSQL50_TABLE_NAME_PREFIX_LENGTH)) + return (uint) (strmake(to, from + MYSQL50_TABLE_NAME_PREFIX_LENGTH, + to_length - 1) - to); + return 0; +} + + +/* + Translate a table name to a file name (WL #1324). + + SYNOPSIS + tablename_to_filename() + from The table name in system_charset_info. + to OUT The file name in my_charset_filename. + to_length The size of the file name buffer. + + RETURN + File name length. +*/ + +uint tablename_to_filename(const char *from, char *to, uint to_length) +{ + uint errors, length; + DBUG_ENTER("tablename_to_filename"); + DBUG_PRINT("enter", ("from '%s'", from)); + + if ((length= check_n_cut_mysql50_prefix(from, to, to_length))) + DBUG_RETURN(length); + length= strconvert(system_charset_info, from, + &my_charset_filename, to, to_length, &errors); + if (check_if_legal_tablename(to) && + length + 4 < to_length) + { + memcpy(to + length, "@@@", 4); + length+= 3; + } + DBUG_PRINT("exit", ("to '%s'", to)); + DBUG_RETURN(length); +} + + +/* + Creates path to a file: mysql_data_dir/db/table.ext + + SYNOPSIS + build_table_filename() + buff Where to write result in my_charset_filename. + This may be the same as table_name. + bufflen buff size + db Database name in system_charset_info. + table_name Table name in system_charset_info. + ext File extension. + flags FN_FROM_IS_TMP or FN_TO_IS_TMP or FN_IS_TMP + table_name is temporary, do not change. + + NOTES + + Uses database and table name, and extension to create + a file name in mysql_data_dir. Database and table + names are converted from system_charset_info into "fscs". + Unless flags indicate a temporary table name. + 'db' is always converted. + 'ext' is not converted. + + The conversion suppression is required for ALTER TABLE. This + statement creates intermediate tables. These are regular + (non-temporary) tables with a temporary name. Their path names must + be derivable from the table name. So we cannot use + build_tmptable_filename() for them. + + RETURN + path length +*/ + +uint build_table_filename(char *buff, size_t bufflen, const char *db, + const char *table_name, const char *ext, uint flags) +{ + char dbbuff[FN_REFLEN]; + char tbbuff[FN_REFLEN]; + DBUG_ENTER("build_table_filename"); + DBUG_PRINT("enter", ("db: '%s' table_name: '%s' ext: '%s' flags: %x", + db, table_name, ext, flags)); + + if (flags & FN_IS_TMP) // FN_FROM_IS_TMP | FN_TO_IS_TMP + strnmov(tbbuff, table_name, sizeof(tbbuff)); + else + VOID(tablename_to_filename(table_name, tbbuff, sizeof(tbbuff))); + + VOID(tablename_to_filename(db, dbbuff, sizeof(dbbuff))); + + char *end = buff + bufflen; + /* Don't add FN_ROOTDIR if mysql_data_home already includes it */ + char *pos = strnmov(buff, mysql_data_home, bufflen); + size_t rootdir_len= strlen(FN_ROOTDIR); + if (pos - rootdir_len >= buff && + memcmp(pos - rootdir_len, FN_ROOTDIR, rootdir_len) != 0) + pos= strnmov(pos, FN_ROOTDIR, end - pos); + pos= strxnmov(pos, end - pos, dbbuff, FN_ROOTDIR, NullS); +#ifdef USE_SYMDIR + unpack_dirname(buff, buff); + pos= strend(buff); +#endif + pos= strxnmov(pos, end - pos, tbbuff, ext, NullS); + + DBUG_PRINT("exit", ("buff: '%s'", buff)); + DBUG_RETURN(pos - buff); +} + + +/* + Creates path to a file: mysql_tmpdir/#sql1234_12_1.ext + + SYNOPSIS + build_tmptable_filename() + thd The thread handle. + buff Where to write result in my_charset_filename. + bufflen buff size + + NOTES + + Uses current_pid, thread_id, and tmp_table counter to create + a file name in mysql_tmpdir. + + RETURN + path length +*/ + +uint build_tmptable_filename(THD* thd, char *buff, size_t bufflen) +{ + DBUG_ENTER("build_tmptable_filename"); + + char *p= strnmov(buff, mysql_tmpdir, bufflen); + my_snprintf(p, bufflen - (p - buff), "/%s%lx_%lx_%x%s", + tmp_file_prefix, current_pid, + thd->thread_id, thd->tmp_table++, reg_ext); + + if (lower_case_table_names) + { + /* Convert all except tmpdir to lower case */ + my_casedn_str(files_charset_info, p); + } + + size_t length= unpack_filename(buff, buff); + DBUG_PRINT("exit", ("buff: '%s'", buff)); + DBUG_RETURN(length); +} + +/* +-------------------------------------------------------------------------- + + MODULE: DDL log + ----------------- + + This module is used to ensure that we can recover from crashes that occur + in the middle of a meta-data operation in MySQL. E.g. DROP TABLE t1, t2; + We need to ensure that both t1 and t2 are dropped and not only t1 and + also that each table drop is entirely done and not "half-baked". + + To support this we create log entries for each meta-data statement in the + ddl log while we are executing. These entries are dropped when the + operation is completed. + + At recovery those entries that were not completed will be executed. + + There is only one ddl log in the system and it is protected by a mutex + and there is a global struct that contains information about its current + state. + + History: + First version written in 2006 by Mikael Ronstrom +-------------------------------------------------------------------------- +*/ + + +struct st_global_ddl_log +{ + /* + We need to adjust buffer size to be able to handle downgrades/upgrades + where IO_SIZE has changed. We'll set the buffer size such that we can + handle that the buffer size was upto 4 times bigger in the version + that wrote the DDL log. + */ + char file_entry_buf[4*IO_SIZE]; + char file_name_str[FN_REFLEN]; + char *file_name; + DDL_LOG_MEMORY_ENTRY *first_free; + DDL_LOG_MEMORY_ENTRY *first_used; + uint num_entries; + File file_id; + uint name_len; + uint io_size; + bool inited; + bool do_release; + bool recovery_phase; + st_global_ddl_log() : inited(false), do_release(false) {} +}; + +st_global_ddl_log global_ddl_log; + +pthread_mutex_t LOCK_gdl; + +#define DDL_LOG_ENTRY_TYPE_POS 0 +#define DDL_LOG_ACTION_TYPE_POS 1 +#define DDL_LOG_PHASE_POS 2 +#define DDL_LOG_NEXT_ENTRY_POS 4 +#define DDL_LOG_NAME_POS 8 + +#define DDL_LOG_NUM_ENTRY_POS 0 +#define DDL_LOG_NAME_LEN_POS 4 +#define DDL_LOG_IO_SIZE_POS 8 + +/* + Read one entry from ddl log file + SYNOPSIS + read_ddl_log_file_entry() + entry_no Entry number to read + RETURN VALUES + TRUE Error + FALSE Success +*/ + +static bool read_ddl_log_file_entry(uint entry_no) +{ + bool error= FALSE; + File file_id= global_ddl_log.file_id; + uchar *file_entry_buf= (uchar*)global_ddl_log.file_entry_buf; + uint io_size= global_ddl_log.io_size; + DBUG_ENTER("read_ddl_log_file_entry"); + + if (my_pread(file_id, file_entry_buf, io_size, io_size * entry_no, + MYF(MY_WME)) != io_size) + error= TRUE; + DBUG_RETURN(error); +} + + +/* + Write one entry from ddl log file + SYNOPSIS + write_ddl_log_file_entry() + entry_no Entry number to read + RETURN VALUES + TRUE Error + FALSE Success +*/ + +static bool write_ddl_log_file_entry(uint entry_no) +{ + bool error= FALSE; + File file_id= global_ddl_log.file_id; + char *file_entry_buf= (char*)global_ddl_log.file_entry_buf; + DBUG_ENTER("write_ddl_log_file_entry"); + + if (my_pwrite(file_id, (uchar*)file_entry_buf, + IO_SIZE, IO_SIZE * entry_no, MYF(MY_WME)) != IO_SIZE) + error= TRUE; + DBUG_RETURN(error); +} + + +/* + Write ddl log header + SYNOPSIS + write_ddl_log_header() + RETURN VALUES + TRUE Error + FALSE Success +*/ + +static bool write_ddl_log_header() +{ + uint16 const_var; + bool error= FALSE; + DBUG_ENTER("write_ddl_log_header"); + + int4store(&global_ddl_log.file_entry_buf[DDL_LOG_NUM_ENTRY_POS], + global_ddl_log.num_entries); + const_var= FN_LEN; + int4store(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_LEN_POS], + (ulong) const_var); + const_var= IO_SIZE; + int4store(&global_ddl_log.file_entry_buf[DDL_LOG_IO_SIZE_POS], + (ulong) const_var); + if (write_ddl_log_file_entry(0UL)) + { + sql_print_error("Error writing ddl log header"); + DBUG_RETURN(TRUE); + } + VOID(sync_ddl_log()); + DBUG_RETURN(error); +} + + +/* + Create ddl log file name + SYNOPSIS + create_ddl_log_file_name() + file_name Filename setup + RETURN VALUES + NONE +*/ + +static inline void create_ddl_log_file_name(char *file_name) +{ + strxmov(file_name, mysql_data_home, "/", "ddl_log.log", NullS); +} + + +/* + Read header of ddl log file + SYNOPSIS + read_ddl_log_header() + RETURN VALUES + > 0 Last entry in ddl log + 0 No entries in ddl log + DESCRIPTION + When we read the ddl log header we get information about maximum sizes + of names in the ddl log and we also get information about the number + of entries in the ddl log. +*/ + +static uint read_ddl_log_header() +{ + char *file_entry_buf= (char*)global_ddl_log.file_entry_buf; + char file_name[FN_REFLEN]; + uint entry_no; + bool successful_open= FALSE; + DBUG_ENTER("read_ddl_log_header"); + + create_ddl_log_file_name(file_name); + if ((global_ddl_log.file_id= my_open(file_name, + O_RDWR | O_BINARY, MYF(0))) >= 0) + { + if (read_ddl_log_file_entry(0UL)) + { + /* Write message into error log */ + sql_print_error("Failed to read ddl log file in recovery"); + } + else + successful_open= TRUE; + } + entry_no= uint4korr(&file_entry_buf[DDL_LOG_NUM_ENTRY_POS]); + global_ddl_log.name_len= uint4korr(&file_entry_buf[DDL_LOG_NAME_LEN_POS]); + if (successful_open) + { + global_ddl_log.io_size= uint4korr(&file_entry_buf[DDL_LOG_IO_SIZE_POS]); + DBUG_ASSERT(global_ddl_log.io_size <= + sizeof(global_ddl_log.file_entry_buf)); + } + else + { + entry_no= 0; + } + global_ddl_log.first_free= NULL; + global_ddl_log.first_used= NULL; + global_ddl_log.num_entries= 0; + VOID(pthread_mutex_init(&LOCK_gdl, MY_MUTEX_INIT_FAST)); + global_ddl_log.do_release= true; + DBUG_RETURN(entry_no); +} + + +/* + Read a ddl log entry + SYNOPSIS + read_ddl_log_entry() + read_entry Number of entry to read + out:entry_info Information from entry + RETURN VALUES + TRUE Error + FALSE Success + DESCRIPTION + Read a specified entry in the ddl log +*/ + +bool read_ddl_log_entry(uint read_entry, DDL_LOG_ENTRY *ddl_log_entry) +{ + char *file_entry_buf= (char*)&global_ddl_log.file_entry_buf; + uint inx; + uchar single_char; + DBUG_ENTER("read_ddl_log_entry"); + + if (read_ddl_log_file_entry(read_entry)) + { + DBUG_RETURN(TRUE); + } + ddl_log_entry->entry_pos= read_entry; + single_char= file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]; + ddl_log_entry->entry_type= (enum ddl_log_entry_code)single_char; + single_char= file_entry_buf[DDL_LOG_ACTION_TYPE_POS]; + ddl_log_entry->action_type= (enum ddl_log_action_code)single_char; + ddl_log_entry->phase= file_entry_buf[DDL_LOG_PHASE_POS]; + ddl_log_entry->next_entry= uint4korr(&file_entry_buf[DDL_LOG_NEXT_ENTRY_POS]); + ddl_log_entry->name= &file_entry_buf[DDL_LOG_NAME_POS]; + inx= DDL_LOG_NAME_POS + global_ddl_log.name_len; + ddl_log_entry->from_name= &file_entry_buf[inx]; + inx+= global_ddl_log.name_len; + ddl_log_entry->handler_name= &file_entry_buf[inx]; + DBUG_RETURN(FALSE); +} + + +/* + Initialise ddl log + SYNOPSIS + init_ddl_log() + + DESCRIPTION + Write the header of the ddl log file and length of names. Also set + number of entries to zero. + + RETURN VALUES + TRUE Error + FALSE Success +*/ + +static bool init_ddl_log() +{ + char file_name[FN_REFLEN]; + DBUG_ENTER("init_ddl_log"); + + if (global_ddl_log.inited) + goto end; + + global_ddl_log.io_size= IO_SIZE; + create_ddl_log_file_name(file_name); + if ((global_ddl_log.file_id= my_create(file_name, + CREATE_MODE, + O_RDWR | O_TRUNC | O_BINARY, + MYF(MY_WME))) < 0) + { + /* Couldn't create ddl log file, this is serious error */ + sql_print_error("Failed to open ddl log file"); + DBUG_RETURN(TRUE); + } + global_ddl_log.inited= TRUE; + if (write_ddl_log_header()) + { + VOID(my_close(global_ddl_log.file_id, MYF(MY_WME))); + global_ddl_log.inited= FALSE; + DBUG_RETURN(TRUE); + } + +end: + DBUG_RETURN(FALSE); +} + + +/* + Execute one action in a ddl log entry + SYNOPSIS + execute_ddl_log_action() + ddl_log_entry Information in action entry to execute + RETURN VALUES + TRUE Error + FALSE Success +*/ + +static int execute_ddl_log_action(THD *thd, DDL_LOG_ENTRY *ddl_log_entry) +{ + bool frm_action= FALSE; + LEX_STRING handler_name; + handler *file= NULL; + MEM_ROOT mem_root; + int error= TRUE; + char to_path[FN_REFLEN]; + char from_path[FN_REFLEN]; +#ifdef WITH_PARTITION_STORAGE_ENGINE + char *par_ext= (char*)".par"; +#endif + handlerton *hton; + DBUG_ENTER("execute_ddl_log_action"); + + if (ddl_log_entry->entry_type == DDL_IGNORE_LOG_ENTRY_CODE) + { + DBUG_RETURN(FALSE); + } + handler_name.str= (char*)ddl_log_entry->handler_name; + handler_name.length= strlen(ddl_log_entry->handler_name); + init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + if (!strcmp(ddl_log_entry->handler_name, reg_ext)) + frm_action= TRUE; + else + { + plugin_ref plugin= ha_resolve_by_name(thd, &handler_name); + if (!plugin) + { + my_error(ER_ILLEGAL_HA, MYF(0), ddl_log_entry->handler_name); + goto error; + } + hton= plugin_data(plugin, handlerton*); + file= get_new_handler((TABLE_SHARE*)0, &mem_root, hton); + if (!file) + { + mem_alloc_error(sizeof(handler)); + goto error; + } + } + switch (ddl_log_entry->action_type) + { + case DDL_LOG_REPLACE_ACTION: + case DDL_LOG_DELETE_ACTION: + { + if (ddl_log_entry->phase == 0) + { + if (frm_action) + { + strxmov(to_path, ddl_log_entry->name, reg_ext, NullS); + if ((error= my_delete(to_path, MYF(MY_WME)))) + { + if (my_errno != ENOENT) + break; + } +#ifdef WITH_PARTITION_STORAGE_ENGINE + strxmov(to_path, ddl_log_entry->name, par_ext, NullS); + VOID(my_delete(to_path, MYF(MY_WME))); +#endif + } + else + { + if ((error= file->ha_delete_table(ddl_log_entry->name))) + { + if (error != ENOENT && error != HA_ERR_NO_SUCH_TABLE) + break; + } + } + if ((deactivate_ddl_log_entry(ddl_log_entry->entry_pos))) + break; + VOID(sync_ddl_log()); + error= FALSE; + if (ddl_log_entry->action_type == DDL_LOG_DELETE_ACTION) + break; + } + DBUG_ASSERT(ddl_log_entry->action_type == DDL_LOG_REPLACE_ACTION); + /* + Fall through and perform the rename action of the replace + action. We have already indicated the success of the delete + action in the log entry by stepping up the phase. + */ + } + case DDL_LOG_RENAME_ACTION: + { + error= TRUE; + if (frm_action) + { + strxmov(to_path, ddl_log_entry->name, reg_ext, NullS); + strxmov(from_path, ddl_log_entry->from_name, reg_ext, NullS); + if (my_rename(from_path, to_path, MYF(MY_WME))) + break; +#ifdef WITH_PARTITION_STORAGE_ENGINE + strxmov(to_path, ddl_log_entry->name, par_ext, NullS); + strxmov(from_path, ddl_log_entry->from_name, par_ext, NullS); + VOID(my_rename(from_path, to_path, MYF(MY_WME))); +#endif + } + else + { + if (file->ha_rename_table(ddl_log_entry->from_name, + ddl_log_entry->name)) + break; + } + if ((deactivate_ddl_log_entry(ddl_log_entry->entry_pos))) + break; + VOID(sync_ddl_log()); + error= FALSE; + break; + } + default: + DBUG_ASSERT(0); + break; + } + delete file; +error: + free_root(&mem_root, MYF(0)); + DBUG_RETURN(error); +} + + +/* + Get a free entry in the ddl log + SYNOPSIS + get_free_ddl_log_entry() + out:active_entry A ddl log memory entry returned + RETURN VALUES + TRUE Error + FALSE Success +*/ + +static bool get_free_ddl_log_entry(DDL_LOG_MEMORY_ENTRY **active_entry, + bool *write_header) +{ + DDL_LOG_MEMORY_ENTRY *used_entry; + DDL_LOG_MEMORY_ENTRY *first_used= global_ddl_log.first_used; + DBUG_ENTER("get_free_ddl_log_entry"); + + if (global_ddl_log.first_free == NULL) + { + if (!(used_entry= (DDL_LOG_MEMORY_ENTRY*)my_malloc( + sizeof(DDL_LOG_MEMORY_ENTRY), MYF(MY_WME)))) + { + sql_print_error("Failed to allocate memory for ddl log free list"); + DBUG_RETURN(TRUE); + } + global_ddl_log.num_entries++; + used_entry->entry_pos= global_ddl_log.num_entries; + *write_header= TRUE; + } + else + { + used_entry= global_ddl_log.first_free; + global_ddl_log.first_free= used_entry->next_log_entry; + *write_header= FALSE; + } + /* + Move from free list to used list + */ + used_entry->next_log_entry= first_used; + used_entry->prev_log_entry= NULL; + global_ddl_log.first_used= used_entry; + if (first_used) + first_used->prev_log_entry= used_entry; + + *active_entry= used_entry; + DBUG_RETURN(FALSE); +} + + +/* + External interface methods for the DDL log Module + --------------------------------------------------- +*/ + +/* + SYNOPSIS + write_ddl_log_entry() + ddl_log_entry Information about log entry + out:entry_written Entry information written into + + RETURN VALUES + TRUE Error + FALSE Success + + DESCRIPTION + A careful write of the ddl log is performed to ensure that we can + handle crashes occurring during CREATE and ALTER TABLE processing. +*/ + +bool write_ddl_log_entry(DDL_LOG_ENTRY *ddl_log_entry, + DDL_LOG_MEMORY_ENTRY **active_entry) +{ + bool error, write_header; + DBUG_ENTER("write_ddl_log_entry"); + + if (init_ddl_log()) + { + DBUG_RETURN(TRUE); + } + global_ddl_log.file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= + (char)DDL_LOG_ENTRY_CODE; + global_ddl_log.file_entry_buf[DDL_LOG_ACTION_TYPE_POS]= + (char)ddl_log_entry->action_type; + global_ddl_log.file_entry_buf[DDL_LOG_PHASE_POS]= 0; + int4store(&global_ddl_log.file_entry_buf[DDL_LOG_NEXT_ENTRY_POS], + ddl_log_entry->next_entry); + DBUG_ASSERT(strlen(ddl_log_entry->name) < FN_LEN); + strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS], + ddl_log_entry->name, FN_LEN - 1); + if (ddl_log_entry->action_type == DDL_LOG_RENAME_ACTION || + ddl_log_entry->action_type == DDL_LOG_REPLACE_ACTION) + { + DBUG_ASSERT(strlen(ddl_log_entry->from_name) < FN_LEN); + strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + FN_LEN], + ddl_log_entry->from_name, FN_LEN - 1); + } + else + global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + FN_LEN]= 0; + DBUG_ASSERT(strlen(ddl_log_entry->handler_name) < FN_LEN); + strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + (2*FN_LEN)], + ddl_log_entry->handler_name, FN_LEN - 1); + if (get_free_ddl_log_entry(active_entry, &write_header)) + { + DBUG_RETURN(TRUE); + } + error= FALSE; + if (write_ddl_log_file_entry((*active_entry)->entry_pos)) + { + error= TRUE; + sql_print_error("Failed to write entry_no = %u", + (*active_entry)->entry_pos); + } + if (write_header && !error) + { + VOID(sync_ddl_log()); + if (write_ddl_log_header()) + error= TRUE; + } + if (error) + release_ddl_log_memory_entry(*active_entry); + DBUG_RETURN(error); +} + + +/* + Write final entry in the ddl log + SYNOPSIS + write_execute_ddl_log_entry() + first_entry First entry in linked list of entries + to execute, if 0 = NULL it means that + the entry is removed and the entries + are put into the free list. + complete Flag indicating we are simply writing + info about that entry has been completed + in:out:active_entry Entry to execute, 0 = NULL if the entry + is written first time and needs to be + returned. In this case the entry written + is returned in this parameter + RETURN VALUES + TRUE Error + FALSE Success + + DESCRIPTION + This is the last write in the ddl log. The previous log entries have + already been written but not yet synched to disk. + We write a couple of log entries that describes action to perform. + This entries are set-up in a linked list, however only when a first + execute entry is put as the first entry these will be executed. + This routine writes this first +*/ + +bool write_execute_ddl_log_entry(uint first_entry, + bool complete, + DDL_LOG_MEMORY_ENTRY **active_entry) +{ + bool write_header= FALSE; + char *file_entry_buf= (char*)global_ddl_log.file_entry_buf; + DBUG_ENTER("write_execute_ddl_log_entry"); + + if (init_ddl_log()) + { + DBUG_RETURN(TRUE); + } + if (!complete) + { + /* + We haven't synched the log entries yet, we synch them now before + writing the execute entry. If complete is true we haven't written + any log entries before, we are only here to write the execute + entry to indicate it is done. + */ + VOID(sync_ddl_log()); + file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= (char)DDL_LOG_EXECUTE_CODE; + } + else + file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= (char)DDL_IGNORE_LOG_ENTRY_CODE; + file_entry_buf[DDL_LOG_ACTION_TYPE_POS]= 0; /* Ignored for execute entries */ + file_entry_buf[DDL_LOG_PHASE_POS]= 0; + int4store(&file_entry_buf[DDL_LOG_NEXT_ENTRY_POS], first_entry); + file_entry_buf[DDL_LOG_NAME_POS]= 0; + file_entry_buf[DDL_LOG_NAME_POS + FN_LEN]= 0; + file_entry_buf[DDL_LOG_NAME_POS + 2*FN_LEN]= 0; + if (!(*active_entry)) + { + if (get_free_ddl_log_entry(active_entry, &write_header)) + { + DBUG_RETURN(TRUE); + } + } + if (write_ddl_log_file_entry((*active_entry)->entry_pos)) + { + sql_print_error("Error writing execute entry in ddl log"); + release_ddl_log_memory_entry(*active_entry); + DBUG_RETURN(TRUE); + } + VOID(sync_ddl_log()); + if (write_header) + { + if (write_ddl_log_header()) + { + release_ddl_log_memory_entry(*active_entry); + DBUG_RETURN(TRUE); + } + } + DBUG_RETURN(FALSE); +} + + +/* + For complex rename operations we need to deactivate individual entries. + SYNOPSIS + deactivate_ddl_log_entry() + entry_no Entry position of record to change + RETURN VALUES + TRUE Error + FALSE Success + DESCRIPTION + During replace operations where we start with an existing table called + t1 and a replacement table called t1#temp or something else and where + we want to delete t1 and rename t1#temp to t1 this is not possible to + do in a safe manner unless the ddl log is informed of the phases in + the change. + + Delete actions are 1-phase actions that can be ignored immediately after + being executed. + Rename actions from x to y is also a 1-phase action since there is no + interaction with any other handlers named x and y. + Replace action where drop y and x -> y happens needs to be a two-phase + action. Thus the first phase will drop y and the second phase will + rename x -> y. +*/ + +bool deactivate_ddl_log_entry(uint entry_no) +{ + char *file_entry_buf= (char*)global_ddl_log.file_entry_buf; + DBUG_ENTER("deactivate_ddl_log_entry"); + + if (!read_ddl_log_file_entry(entry_no)) + { + if (file_entry_buf[DDL_LOG_ENTRY_TYPE_POS] == DDL_LOG_ENTRY_CODE) + { + if (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_DELETE_ACTION || + file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_RENAME_ACTION || + (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_REPLACE_ACTION && + file_entry_buf[DDL_LOG_PHASE_POS] == 1)) + file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= DDL_IGNORE_LOG_ENTRY_CODE; + else if (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_REPLACE_ACTION) + { + DBUG_ASSERT(file_entry_buf[DDL_LOG_PHASE_POS] == 0); + file_entry_buf[DDL_LOG_PHASE_POS]= 1; + } + else + { + DBUG_ASSERT(0); + } + if (write_ddl_log_file_entry(entry_no)) + { + sql_print_error("Error in deactivating log entry. Position = %u", + entry_no); + DBUG_RETURN(TRUE); + } + } + } + else + { + sql_print_error("Failed in reading entry before deactivating it"); + DBUG_RETURN(TRUE); + } + DBUG_RETURN(FALSE); +} + + +/* + Sync ddl log file + SYNOPSIS + sync_ddl_log() + RETURN VALUES + TRUE Error + FALSE Success +*/ + +bool sync_ddl_log() +{ + bool error= FALSE; + DBUG_ENTER("sync_ddl_log"); + + if ((!global_ddl_log.recovery_phase) && + init_ddl_log()) + { + DBUG_RETURN(TRUE); + } + if (my_sync(global_ddl_log.file_id, MYF(0))) + { + /* Write to error log */ + sql_print_error("Failed to sync ddl log"); + error= TRUE; + } + DBUG_RETURN(error); +} + + +/* + Release a log memory entry + SYNOPSIS + release_ddl_log_memory_entry() + log_memory_entry Log memory entry to release + RETURN VALUES + NONE +*/ + +void release_ddl_log_memory_entry(DDL_LOG_MEMORY_ENTRY *log_entry) +{ + DDL_LOG_MEMORY_ENTRY *first_free= global_ddl_log.first_free; + DDL_LOG_MEMORY_ENTRY *next_log_entry= log_entry->next_log_entry; + DDL_LOG_MEMORY_ENTRY *prev_log_entry= log_entry->prev_log_entry; + DBUG_ENTER("release_ddl_log_memory_entry"); + + global_ddl_log.first_free= log_entry; + log_entry->next_log_entry= first_free; + + if (prev_log_entry) + prev_log_entry->next_log_entry= next_log_entry; + else + global_ddl_log.first_used= next_log_entry; + if (next_log_entry) + next_log_entry->prev_log_entry= prev_log_entry; + DBUG_VOID_RETURN; +} + + +/* + Execute one entry in the ddl log. Executing an entry means executing + a linked list of actions. + SYNOPSIS + execute_ddl_log_entry() + first_entry Reference to first action in entry + RETURN VALUES + TRUE Error + FALSE Success +*/ + +bool execute_ddl_log_entry(THD *thd, uint first_entry) +{ + DDL_LOG_ENTRY ddl_log_entry; + uint read_entry= first_entry; + DBUG_ENTER("execute_ddl_log_entry"); + + pthread_mutex_lock(&LOCK_gdl); + do + { + if (read_ddl_log_entry(read_entry, &ddl_log_entry)) + { + /* Write to error log and continue with next log entry */ + sql_print_error("Failed to read entry = %u from ddl log", + read_entry); + break; + } + DBUG_ASSERT(ddl_log_entry.entry_type == DDL_LOG_ENTRY_CODE || + ddl_log_entry.entry_type == DDL_IGNORE_LOG_ENTRY_CODE); + + if (execute_ddl_log_action(thd, &ddl_log_entry)) + { + /* Write to error log and continue with next log entry */ + sql_print_error("Failed to execute action for entry = %u from ddl log", + read_entry); + break; + } + read_entry= ddl_log_entry.next_entry; + } while (read_entry); + pthread_mutex_unlock(&LOCK_gdl); + DBUG_RETURN(FALSE); +} + + +/* + Close the ddl log + SYNOPSIS + close_ddl_log() + RETURN VALUES + NONE +*/ + +static void close_ddl_log() +{ + DBUG_ENTER("close_ddl_log"); + if (global_ddl_log.file_id >= 0) + { + VOID(my_close(global_ddl_log.file_id, MYF(MY_WME))); + global_ddl_log.file_id= (File) -1; + } + DBUG_VOID_RETURN; +} + + +/* + Execute the ddl log at recovery of MySQL Server + SYNOPSIS + execute_ddl_log_recovery() + RETURN VALUES + NONE +*/ + +void execute_ddl_log_recovery() +{ + uint num_entries, i; + THD *thd; + DDL_LOG_ENTRY ddl_log_entry; + char file_name[FN_REFLEN]; + DBUG_ENTER("execute_ddl_log_recovery"); + + /* + Initialise global_ddl_log struct + */ + bzero(global_ddl_log.file_entry_buf, sizeof(global_ddl_log.file_entry_buf)); + global_ddl_log.inited= FALSE; + global_ddl_log.recovery_phase= TRUE; + global_ddl_log.io_size= IO_SIZE; + global_ddl_log.file_id= (File) -1; + + /* + To be able to run this from boot, we allocate a temporary THD + */ + if (!(thd=new THD)) + DBUG_VOID_RETURN; + thd->thread_stack= (char*) &thd; + thd->store_globals(); + + num_entries= read_ddl_log_header(); + for (i= 1; i < num_entries + 1; i++) + { + if (read_ddl_log_entry(i, &ddl_log_entry)) + { + sql_print_error("Failed to read entry no = %u from ddl log", + i); + continue; + } + if (ddl_log_entry.entry_type == DDL_LOG_EXECUTE_CODE) + { + if (execute_ddl_log_entry(thd, ddl_log_entry.next_entry)) + { + /* Real unpleasant scenario but we continue anyways. */ + continue; + } + } + } + close_ddl_log(); + create_ddl_log_file_name(file_name); + VOID(my_delete(file_name, MYF(0))); + global_ddl_log.recovery_phase= FALSE; + delete thd; + /* Remember that we don't have a THD */ + my_pthread_setspecific_ptr(THR_THD, 0); + DBUG_VOID_RETURN; +} + + +/* + Release all memory allocated to the ddl log + SYNOPSIS + release_ddl_log() + RETURN VALUES + NONE +*/ + +void release_ddl_log() +{ + DDL_LOG_MEMORY_ENTRY *free_list= global_ddl_log.first_free; + DDL_LOG_MEMORY_ENTRY *used_list= global_ddl_log.first_used; + DBUG_ENTER("release_ddl_log"); + + if (!global_ddl_log.do_release) + DBUG_VOID_RETURN; + + pthread_mutex_lock(&LOCK_gdl); + while (used_list) + { + DDL_LOG_MEMORY_ENTRY *tmp= used_list->next_log_entry; + my_free(used_list, MYF(0)); + used_list= tmp; + } + while (free_list) + { + DDL_LOG_MEMORY_ENTRY *tmp= free_list->next_log_entry; + my_free(free_list, MYF(0)); + free_list= tmp; + } + close_ddl_log(); + global_ddl_log.inited= 0; + pthread_mutex_unlock(&LOCK_gdl); + VOID(pthread_mutex_destroy(&LOCK_gdl)); + global_ddl_log.do_release= false; + DBUG_VOID_RETURN; +} + + +/* +--------------------------------------------------------------------------- + + END MODULE DDL log + -------------------- + +--------------------------------------------------------------------------- +*/ + + +/** + @brief construct a temporary shadow file name. + + @details Make a shadow file name used by ALTER TABLE to construct the + modified table (with keeping the original). The modified table is then + moved back as original table. The name must start with the temp file + prefix so it gets filtered out by table files listing routines. + + @param[out] buff buffer to receive the constructed name + @param bufflen size of buff + @param lpt alter table data structure + + @retval path length +*/ + +uint build_table_shadow_filename(char *buff, size_t bufflen, + ALTER_PARTITION_PARAM_TYPE *lpt) +{ + char tmp_name[FN_REFLEN]; + my_snprintf (tmp_name, sizeof (tmp_name), "%s-%s", tmp_file_prefix, + lpt->table_name); + return build_table_filename(buff, bufflen, lpt->db, tmp_name, "", FN_IS_TMP); +} + + +/* + SYNOPSIS + mysql_write_frm() + lpt Struct carrying many parameters needed for this + method + flags Flags as defined below + WFRM_INITIAL_WRITE If set we need to prepare table before + creating the frm file + WFRM_INSTALL_SHADOW If set we should install the new frm + WFRM_KEEP_SHARE If set we know that the share is to be + retained and thus we should ensure share + object is correct, if not set we don't + set the new partition syntax string since + we know the share object is destroyed. + WFRM_PACK_FRM If set we should pack the frm file and delete + the frm file + + RETURN VALUES + TRUE Error + FALSE Success + + DESCRIPTION + A support method that creates a new frm file and in this process it + regenerates the partition data. It works fine also for non-partitioned + tables since it only handles partitioned data if it exists. +*/ + +bool mysql_write_frm(ALTER_PARTITION_PARAM_TYPE *lpt, uint flags) +{ + /* + Prepare table to prepare for writing a new frm file where the + partitions in add/drop state have temporarily changed their state + We set tmp_table to avoid get errors on naming of primary key index. + */ + int error= 0; + char path[FN_REFLEN+1]; + char shadow_path[FN_REFLEN+1]; + char shadow_frm_name[FN_REFLEN+1]; + char frm_name[FN_REFLEN+1]; +#ifdef WITH_PARTITION_STORAGE_ENGINE + char *part_syntax_buf; + uint syntax_len; +#endif + DBUG_ENTER("mysql_write_frm"); + + /* + Build shadow frm file name + */ + build_table_shadow_filename(shadow_path, sizeof(shadow_path) - 1, lpt); + strxmov(shadow_frm_name, shadow_path, reg_ext, NullS); + if (flags & WFRM_WRITE_SHADOW) + { + if (mysql_prepare_create_table(lpt->thd, lpt->create_info, + lpt->alter_info, + /*tmp_table*/ 1, + &lpt->db_options, + lpt->table->file, + &lpt->key_info_buffer, + &lpt->key_count, + /*select_field_count*/ 0)) + { + DBUG_RETURN(TRUE); + } +#ifdef WITH_PARTITION_STORAGE_ENGINE + { + partition_info *part_info= lpt->table->part_info; + if (part_info) + { + if (!(part_syntax_buf= generate_partition_syntax(part_info, + &syntax_len, + TRUE, TRUE))) + { + DBUG_RETURN(TRUE); + } + part_info->part_info_string= part_syntax_buf; + part_info->part_info_len= syntax_len; + } + } +#endif + /* Write shadow frm file */ + lpt->create_info->table_options= lpt->db_options; + if ((mysql_create_frm(lpt->thd, shadow_frm_name, lpt->db, + lpt->table_name, lpt->create_info, + lpt->alter_info->create_list, lpt->key_count, + lpt->key_info_buffer, lpt->table->file)) || + lpt->table->file->ha_create_handler_files(shadow_path, NULL, + CHF_CREATE_FLAG, + lpt->create_info)) + { + my_delete(shadow_frm_name, MYF(0)); + error= 1; + goto end; + } + } + if (flags & WFRM_PACK_FRM) + { + /* + We need to pack the frm file and after packing it we delete the + frm file to ensure it doesn't get used. This is only used for + handlers that have the main version of the frm file stored in the + handler. + */ + uchar *data; + size_t length; + if (readfrm(shadow_path, &data, &length) || + packfrm(data, length, &lpt->pack_frm_data, &lpt->pack_frm_len)) + { + my_free(data, MYF(MY_ALLOW_ZERO_PTR)); + my_free(lpt->pack_frm_data, MYF(MY_ALLOW_ZERO_PTR)); + mem_alloc_error(length); + error= 1; + goto end; + } + error= my_delete(shadow_frm_name, MYF(MY_WME)); + } + if (flags & WFRM_INSTALL_SHADOW) + { +#ifdef WITH_PARTITION_STORAGE_ENGINE + partition_info *part_info= lpt->part_info; +#endif + /* + Build frm file name + */ + build_table_filename(path, sizeof(path) - 1, lpt->db, + lpt->table_name, "", 0); + strxmov(frm_name, path, reg_ext, NullS); + /* + When we are changing to use new frm file we need to ensure that we + don't collide with another thread in process to open the frm file. + We start by deleting the .frm file and possible .par file. Then we + write to the DDL log that we have completed the delete phase by + increasing the phase of the log entry. Next step is to rename the + new .frm file and the new .par file to the real name. After + completing this we write a new phase to the log entry that will + deactivate it. + */ + VOID(pthread_mutex_lock(&LOCK_open)); + if (my_delete(frm_name, MYF(MY_WME)) || +#ifdef WITH_PARTITION_STORAGE_ENGINE + lpt->table->file->ha_create_handler_files(path, shadow_path, + CHF_DELETE_FLAG, NULL) || + deactivate_ddl_log_entry(part_info->frm_log_entry->entry_pos) || + (sync_ddl_log(), FALSE) || +#endif +#ifdef WITH_PARTITION_STORAGE_ENGINE + my_rename(shadow_frm_name, frm_name, MYF(MY_WME)) || + lpt->table->file->ha_create_handler_files(path, shadow_path, + CHF_RENAME_FLAG, NULL)) +#else + my_rename(shadow_frm_name, frm_name, MYF(MY_WME))) +#endif + { + error= 1; + goto err; + } +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (part_info && (flags & WFRM_KEEP_SHARE)) + { + TABLE_SHARE *share= lpt->table->s; + char *tmp_part_syntax_str; + if (!(part_syntax_buf= generate_partition_syntax(part_info, + &syntax_len, + TRUE, TRUE))) + { + error= 1; + goto err; + } + if (share->partition_info_buffer_size < syntax_len + 1) + { + share->partition_info_buffer_size= syntax_len+1; + if (!(tmp_part_syntax_str= (char*) strmake_root(&share->mem_root, + part_syntax_buf, + syntax_len))) + { + error= 1; + goto err; + } + share->partition_info= tmp_part_syntax_str; + } + else + memcpy((char*) share->partition_info, part_syntax_buf, syntax_len + 1); + share->partition_info_len= part_info->part_info_len= syntax_len; + part_info->part_info_string= part_syntax_buf; + } +#endif + +err: + VOID(pthread_mutex_unlock(&LOCK_open)); +#ifdef WITH_PARTITION_STORAGE_ENGINE + deactivate_ddl_log_entry(part_info->frm_log_entry->entry_pos); + part_info->frm_log_entry= NULL; + VOID(sync_ddl_log()); +#endif + } + +end: + DBUG_RETURN(error); +} + + +/* + SYNOPSIS + write_bin_log() + thd Thread object + clear_error is clear_error to be called + query Query to log + query_length Length of query + + RETURN VALUES + NONE + + DESCRIPTION + Write the binlog if open, routine used in multiple places in this + file +*/ + +void write_bin_log(THD *thd, bool clear_error, + char const *query, ulong query_length) +{ + if (mysql_bin_log.is_open()) + { + int errcode= 0; + if (clear_error) + thd->clear_error(); + else + errcode= query_error_code(thd, TRUE); + thd->binlog_query(THD::STMT_QUERY_TYPE, + query, query_length, FALSE, FALSE, errcode); + } +} + + +/* + delete (drop) tables. + + SYNOPSIS + mysql_rm_table() + thd Thread handle + tables List of tables to delete + if_exists If 1, don't give error if one table doesn't exists + + NOTES + Will delete all tables that can be deleted and give a compact error + messages for tables that could not be deleted. + If a table is in use, we will wait for all users to free the table + before dropping it + + Wait if global_read_lock (FLUSH TABLES WITH READ LOCK) is set. + + RETURN + FALSE OK. In this case ok packet is sent to user + TRUE Error + +*/ + +bool mysql_rm_table(THD *thd,TABLE_LIST *tables, my_bool if_exists, + my_bool drop_temporary) +{ + bool error= FALSE, need_start_waiters= FALSE; + DBUG_ENTER("mysql_rm_table"); + + /* mark for close and remove all cached entries */ + + if (!drop_temporary) + { + if ((error= wait_if_global_read_lock(thd, 0, 1))) + { + my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->table_name); + DBUG_RETURN(TRUE); + } + else + need_start_waiters= TRUE; + } + + /* + Acquire LOCK_open after wait_if_global_read_lock(). If we would hold + LOCK_open during wait_if_global_read_lock(), other threads could not + close their tables. This would make a pretty deadlock. + */ + error= mysql_rm_table_part2(thd, tables, if_exists, drop_temporary, 0, 0); + + if (need_start_waiters) + start_waiting_global_read_lock(thd); + + if (error) + DBUG_RETURN(TRUE); + my_ok(thd); + DBUG_RETURN(FALSE); +} + +/* + Execute the drop of a normal or temporary table + + SYNOPSIS + mysql_rm_table_part2() + thd Thread handler + tables Tables to drop + if_exists If set, don't give an error if table doesn't exists. + In this case we give an warning of level 'NOTE' + drop_temporary Only drop temporary tables + drop_view Allow to delete VIEW .frm + dont_log_query Don't write query to log files. This will also not + generate warnings if the handler files doesn't exists + + TODO: + When logging to the binary log, we should log + tmp_tables and transactional tables as separate statements if we + are in a transaction; This is needed to get these tables into the + cached binary log that is only written on COMMIT. + + The current code only writes DROP statements that only uses temporary + tables to the cache binary log. This should be ok on most cases, but + not all. + + RETURN + 0 ok + 1 Error + -1 Thread was killed +*/ + +int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, + bool drop_temporary, bool drop_view, + bool dont_log_query) +{ + TABLE_LIST *table; + char path[FN_REFLEN + 1], *alias; + uint path_length; + String wrong_tables; + int error= 0; + int non_temp_tables_count= 0; + bool some_tables_deleted=0, tmp_table_deleted=0, foreign_key_error=0; + String built_query; + String built_tmp_query; + DBUG_ENTER("mysql_rm_table_part2"); + + LINT_INIT(alias); + LINT_INIT(path_length); + + if (thd->current_stmt_binlog_row_based && !dont_log_query) + { + built_query.set_charset(system_charset_info); + if (if_exists) + built_query.append("DROP TABLE IF EXISTS "); + else + built_query.append("DROP TABLE "); + } + + mysql_ha_rm_tables(thd, tables, FALSE); + + pthread_mutex_lock(&LOCK_open); + + /* + If we have the table in the definition cache, we don't have to check the + .frm file to find if the table is a normal table (not view) and what + engine to use. + */ + + for (table= tables; table; table= table->next_local) + { + TABLE_SHARE *share; + table->db_type= NULL; + if ((share= get_cached_table_share(table->db, table->table_name))) + table->db_type= share->db_type(); + + /* Disable drop of enabled log tables */ + if (share && (share->table_category == TABLE_CATEGORY_PERFORMANCE) && + check_if_log_table(table->db_length, table->db, + table->table_name_length, table->table_name, 1)) + { + my_error(ER_BAD_LOG_STATEMENT, MYF(0), "DROP"); + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(1); + } + } + + if (!drop_temporary && lock_table_names_exclusively(thd, tables)) + { + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(1); + } + + /* Don't give warnings for not found errors, as we already generate notes */ + thd->no_warnings_for_error= 1; + + for (table= tables; table; table= table->next_local) + { + char *db=table->db; + handlerton *table_type; + enum legacy_db_type frm_db_type; + + DBUG_PRINT("table", ("table_l: '%s'.'%s' table: 0x%lx s: 0x%lx", + table->db, table->table_name, (long) table->table, + table->table ? (long) table->table->s : (long) -1)); + + error= drop_temporary_table(thd, table); + + switch (error) { + case 0: + // removed temporary table + tmp_table_deleted= 1; + if (thd->variables.binlog_format == BINLOG_FORMAT_MIXED && + thd->current_stmt_binlog_row_based) + { + if (built_tmp_query.is_empty()) + { + built_tmp_query.set_charset(system_charset_info); + built_tmp_query.append("DROP TEMPORARY TABLE IF EXISTS "); + } + + built_tmp_query.append("`"); + if (thd->db == NULL || strcmp(db,thd->db) != 0) + { + built_tmp_query.append(db); + built_tmp_query.append("`.`"); + } + built_tmp_query.append(table->table_name); + built_tmp_query.append("`,"); + } + + continue; + case -1: + DBUG_ASSERT(thd->in_sub_stmt); + error= 1; + goto err_with_placeholders; + default: + // temporary table not found + error= 0; + } + + /* + If row-based replication is used and the table is not a + temporary table, we add the table name to the drop statement + being built. The string always end in a comma and the comma + will be chopped off before being written to the binary log. + */ + if (thd->current_stmt_binlog_row_based && !dont_log_query) + { + non_temp_tables_count++; + /* + Don't write the database name if it is the current one (or if + thd->db is NULL). + */ + built_query.append("`"); + if (thd->db == NULL || strcmp(db,thd->db) != 0) + { + built_query.append(db); + built_query.append("`.`"); + } + + built_query.append(table->table_name); + built_query.append("`,"); + } + + table_type= table->db_type; + if (!drop_temporary) + { + TABLE *locked_table; + abort_locked_tables(thd, db, table->table_name); + remove_table_from_cache(thd, db, table->table_name, + RTFC_WAIT_OTHER_THREAD_FLAG | + RTFC_CHECK_KILLED_FLAG); + /* + If the table was used in lock tables, remember it so that + unlock_table_names can free it + */ + if ((locked_table= drop_locked_tables(thd, db, table->table_name))) + table->table= locked_table; + + if (thd->killed) + { + error= -1; + goto err_with_placeholders; + } + alias= (lower_case_table_names == 2) ? table->alias : table->table_name; + /* remove .frm file and engine files */ + path_length= build_table_filename(path, sizeof(path) - 1, db, alias, + reg_ext, + table->internal_tmp_table ? + FN_IS_TMP : 0); + } + if (drop_temporary || + ((table_type == NULL && + access(path, F_OK) && + ha_create_table_from_engine(thd, db, alias)) || + (!drop_view && + mysql_frm_type(thd, path, &frm_db_type) != FRMTYPE_TABLE))) + { + // Table was not found on disk and table can't be created from engine + if (if_exists) + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR), + table->table_name); + else + error= 1; + } + else + { + char *end; + if (table_type == NULL) + { + mysql_frm_type(thd, path, &frm_db_type); + table_type= ha_resolve_by_legacy_type(thd, frm_db_type); + } + // Remove extension for delete + *(end= path + path_length - reg_ext_length)= '\0'; + error= ha_delete_table(thd, table_type, path, db, table->table_name, + !dont_log_query); + if ((error == ENOENT || error == HA_ERR_NO_SUCH_TABLE) && + (if_exists || table_type == NULL)) + { + error= 0; + thd->clear_error(); + } + if (error == HA_ERR_ROW_IS_REFERENCED) + { + /* the table is referenced by a foreign key constraint */ + foreign_key_error=1; + } + if (!error || error == ENOENT || error == HA_ERR_NO_SUCH_TABLE) + { + int new_error; + /* Delete the table definition file */ + strmov(end,reg_ext); + if (!(new_error=my_delete(path,MYF(MY_WME)))) + { + some_tables_deleted=1; + new_error= Table_triggers_list::drop_all_triggers(thd, db, + table->table_name); + } + error|= new_error; + } + } + if (error) + { + if (wrong_tables.length()) + wrong_tables.append(','); + wrong_tables.append(String(table->table_name,system_charset_info)); + } + DBUG_PRINT("table", ("table: 0x%lx s: 0x%lx", (long) table->table, + table->table ? (long) table->table->s : (long) -1)); + } + /* + It's safe to unlock LOCK_open: we have an exclusive lock + on the table name. + */ + pthread_mutex_unlock(&LOCK_open); + thd->thread_specific_used|= tmp_table_deleted; + error= 0; + if (wrong_tables.length()) + { + if (!foreign_key_error) + my_printf_error(ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR), MYF(0), + wrong_tables.c_ptr()); + else + my_message(ER_ROW_IS_REFERENCED, ER(ER_ROW_IS_REFERENCED), MYF(0)); + error= 1; + } + + if (some_tables_deleted || tmp_table_deleted || !error) + { + query_cache_invalidate3(thd, tables, 0); + if (!dont_log_query) + { + if (!thd->current_stmt_binlog_row_based || + (non_temp_tables_count > 0 && !tmp_table_deleted)) + { + /* + In this case, we are either using statement-based + replication or using row-based replication but have only + deleted one or more non-temporary tables (and no temporary + tables). In this case, we can write the original query into + the binary log. + */ + write_bin_log(thd, !error, thd->query, thd->query_length); + } + else if (thd->current_stmt_binlog_row_based && + tmp_table_deleted) + { + if (non_temp_tables_count > 0) + { + /* + In this case we have deleted both temporary and + non-temporary tables, so: + - since we have deleted a non-temporary table we have to + binlog the statement, but + - since we have deleted a temporary table we cannot binlog + the statement (since the table may have not been created on the + slave - check "if" branch below, this might cause the slave to + stop). + + Instead, we write a built statement, only containing the + non-temporary tables, to the binary log + */ + built_query.chop(); // Chop of the last comma + built_query.append(" /* generated by server */"); + write_bin_log(thd, !error, built_query.ptr(), built_query.length()); + } + + /* + One needs to always log any temporary table drop, if: + 1. thread logging format is mixed mode; AND + 2. current statement logging format is set to row. + */ + if (thd->variables.binlog_format == BINLOG_FORMAT_MIXED) + { + /* + In this case we have deleted some temporary tables but we are using + row based logging for the statement. However, thread uses mixed mode + format, thence we need to log the dropping as we cannot tell for + sure whether the create was logged as statement previously or not, ie, + before switching to row mode. + */ + built_tmp_query.chop(); // Chop of the last comma + built_tmp_query.append(" /* generated by server */"); + write_bin_log(thd, !error, built_tmp_query.ptr(), built_tmp_query.length()); + } + } + + /* + The remaining cases are: + - no tables were deleted and + - only temporary tables were deleted and row-based + replication is used. + In both these cases, nothing should be written to the binary + log. + */ + } + } + pthread_mutex_lock(&LOCK_open); +err_with_placeholders: + unlock_table_names(thd, tables, (TABLE_LIST*) 0); + pthread_mutex_unlock(&LOCK_open); + thd->no_warnings_for_error= 0; + DBUG_RETURN(error); +} + + +/* + Quickly remove a table. + + SYNOPSIS + quick_rm_table() + base The handlerton handle. + db The database name. + table_name The table name. + flags flags for build_table_filename(). + + RETURN + 0 OK + != 0 Error +*/ + +bool quick_rm_table(handlerton *base,const char *db, + const char *table_name, uint flags) +{ + char path[FN_REFLEN + 1]; + bool error= 0; + DBUG_ENTER("quick_rm_table"); + + uint path_length= build_table_filename(path, sizeof(path) - 1, + db, table_name, reg_ext, flags); + if (my_delete(path,MYF(0))) + error= 1; /* purecov: inspected */ + path[path_length - reg_ext_length]= '\0'; // Remove reg_ext + if (!(flags & FRM_ONLY)) + error|= ha_delete_table(current_thd, base, path, db, table_name, 0); + DBUG_RETURN(error); +} + +/* + Sort keys in the following order: + - PRIMARY KEY + - UNIQUE keys where all column are NOT NULL + - UNIQUE keys that don't contain partial segments + - Other UNIQUE keys + - Normal keys + - Fulltext keys + + This will make checking for duplicated keys faster and ensure that + PRIMARY keys are prioritized. +*/ + +static int sort_keys(KEY *a, KEY *b) +{ + ulong a_flags= a->flags, b_flags= b->flags; + + if (a_flags & HA_NOSAME) + { + if (!(b_flags & HA_NOSAME)) + return -1; + if ((a_flags ^ b_flags) & (HA_NULL_PART_KEY | HA_END_SPACE_KEY)) + { + /* Sort NOT NULL keys before other keys */ + return (a_flags & (HA_NULL_PART_KEY | HA_END_SPACE_KEY)) ? 1 : -1; + } + if (a->name == primary_key_name) + return -1; + if (b->name == primary_key_name) + return 1; + /* Sort keys don't containing partial segments before others */ + if ((a_flags ^ b_flags) & HA_KEY_HAS_PART_KEY_SEG) + return (a_flags & HA_KEY_HAS_PART_KEY_SEG) ? 1 : -1; + } + else if (b_flags & HA_NOSAME) + return 1; // Prefer b + + if ((a_flags ^ b_flags) & HA_FULLTEXT) + { + return (a_flags & HA_FULLTEXT) ? 1 : -1; + } + /* + Prefer original key order. usable_key_parts contains here + the original key position. + */ + return ((a->usable_key_parts < b->usable_key_parts) ? -1 : + (a->usable_key_parts > b->usable_key_parts) ? 1 : + 0); +} + +/* + Check TYPELIB (set or enum) for duplicates + + SYNOPSIS + check_duplicates_in_interval() + set_or_name "SET" or "ENUM" string for warning message + name name of the checked column + typelib list of values for the column + dup_val_count returns count of duplicate elements + + DESCRIPTION + This function prints an warning for each value in list + which has some duplicates on its right + + RETURN VALUES + 0 ok + 1 Error +*/ + +bool check_duplicates_in_interval(const char *set_or_name, + const char *name, TYPELIB *typelib, + CHARSET_INFO *cs, unsigned int *dup_val_count) +{ + TYPELIB tmp= *typelib; + const char **cur_value= typelib->type_names; + unsigned int *cur_length= typelib->type_lengths; + *dup_val_count= 0; + + for ( ; tmp.count > 1; cur_value++, cur_length++) + { + tmp.type_names++; + tmp.type_lengths++; + tmp.count--; + if (find_type2(&tmp, (const char*)*cur_value, *cur_length, cs)) + { + if ((current_thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES))) + { + my_error(ER_DUPLICATED_VALUE_IN_TYPE, MYF(0), + name,*cur_value,set_or_name); + return 1; + } + push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_DUPLICATED_VALUE_IN_TYPE, + ER(ER_DUPLICATED_VALUE_IN_TYPE), + name,*cur_value,set_or_name); + (*dup_val_count)++; + } + } + return 0; +} + + +/* + Check TYPELIB (set or enum) max and total lengths + + SYNOPSIS + calculate_interval_lengths() + cs charset+collation pair of the interval + typelib list of values for the column + max_length length of the longest item + tot_length sum of the item lengths + + DESCRIPTION + After this function call: + - ENUM uses max_length + - SET uses tot_length. + + RETURN VALUES + void +*/ +void calculate_interval_lengths(CHARSET_INFO *cs, TYPELIB *interval, + uint32 *max_length, uint32 *tot_length) +{ + const char **pos; + uint *len; + *max_length= *tot_length= 0; + for (pos= interval->type_names, len= interval->type_lengths; + *pos ; pos++, len++) + { + size_t length= cs->cset->numchars(cs, *pos, *pos + *len); + *tot_length+= length; + set_if_bigger(*max_length, (uint32)length); + } +} + + +/* + Prepare a create_table instance for packing + + SYNOPSIS + prepare_create_field() + sql_field field to prepare for packing + blob_columns count for BLOBs + timestamps count for timestamps + table_flags table flags + + DESCRIPTION + This function prepares a Create_field instance. + Fields such as pack_flag are valid after this call. + + RETURN VALUES + 0 ok + 1 Error +*/ + +int prepare_create_field(Create_field *sql_field, + uint *blob_columns, + int *timestamps, int *timestamps_with_niladic, + longlong table_flags) +{ + unsigned int dup_val_count; + DBUG_ENTER("prepare_field"); + + /* + This code came from mysql_prepare_create_table. + Indent preserved to make patching easier + */ + DBUG_ASSERT(sql_field->charset); + + switch (sql_field->sql_type) { + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_LONG_BLOB: + sql_field->pack_flag=FIELDFLAG_BLOB | + pack_length_to_packflag(sql_field->pack_length - + portable_sizeof_char_ptr); + if (sql_field->charset->state & MY_CS_BINSORT) + sql_field->pack_flag|=FIELDFLAG_BINARY; + sql_field->length=8; // Unireg field length + sql_field->unireg_check=Field::BLOB_FIELD; + (*blob_columns)++; + break; + case MYSQL_TYPE_GEOMETRY: +#ifdef HAVE_SPATIAL + if (!(table_flags & HA_CAN_GEOMETRY)) + { + my_printf_error(ER_CHECK_NOT_IMPLEMENTED, ER(ER_CHECK_NOT_IMPLEMENTED), + MYF(0), "GEOMETRY"); + DBUG_RETURN(1); + } + sql_field->pack_flag=FIELDFLAG_GEOM | + pack_length_to_packflag(sql_field->pack_length - + portable_sizeof_char_ptr); + if (sql_field->charset->state & MY_CS_BINSORT) + sql_field->pack_flag|=FIELDFLAG_BINARY; + sql_field->length=8; // Unireg field length + sql_field->unireg_check=Field::BLOB_FIELD; + (*blob_columns)++; + break; +#else + my_printf_error(ER_FEATURE_DISABLED,ER(ER_FEATURE_DISABLED), MYF(0), + sym_group_geom.name, sym_group_geom.needed_define); + DBUG_RETURN(1); +#endif /*HAVE_SPATIAL*/ + case MYSQL_TYPE_VARCHAR: +#ifndef QQ_ALL_HANDLERS_SUPPORT_VARCHAR + if (table_flags & HA_NO_VARCHAR) + { + /* convert VARCHAR to CHAR because handler is not yet up to date */ + sql_field->sql_type= MYSQL_TYPE_VAR_STRING; + sql_field->pack_length= calc_pack_length(sql_field->sql_type, + (uint) sql_field->length); + if ((sql_field->length / sql_field->charset->mbmaxlen) > + MAX_FIELD_CHARLENGTH) + { + my_printf_error(ER_TOO_BIG_FIELDLENGTH, ER(ER_TOO_BIG_FIELDLENGTH), + MYF(0), sql_field->field_name, MAX_FIELD_CHARLENGTH); + DBUG_RETURN(1); + } + } +#endif + /* fall through */ + case MYSQL_TYPE_STRING: + sql_field->pack_flag=0; + if (sql_field->charset->state & MY_CS_BINSORT) + sql_field->pack_flag|=FIELDFLAG_BINARY; + break; + case MYSQL_TYPE_ENUM: + sql_field->pack_flag=pack_length_to_packflag(sql_field->pack_length) | + FIELDFLAG_INTERVAL; + if (sql_field->charset->state & MY_CS_BINSORT) + sql_field->pack_flag|=FIELDFLAG_BINARY; + sql_field->unireg_check=Field::INTERVAL_FIELD; + if (check_duplicates_in_interval("ENUM",sql_field->field_name, + sql_field->interval, + sql_field->charset, &dup_val_count)) + DBUG_RETURN(1); + break; + case MYSQL_TYPE_SET: + sql_field->pack_flag=pack_length_to_packflag(sql_field->pack_length) | + FIELDFLAG_BITFIELD; + if (sql_field->charset->state & MY_CS_BINSORT) + sql_field->pack_flag|=FIELDFLAG_BINARY; + sql_field->unireg_check=Field::BIT_FIELD; + if (check_duplicates_in_interval("SET",sql_field->field_name, + sql_field->interval, + sql_field->charset, &dup_val_count)) + DBUG_RETURN(1); + /* Check that count of unique members is not more then 64 */ + if (sql_field->interval->count - dup_val_count > sizeof(longlong)*8) + { + my_error(ER_TOO_BIG_SET, MYF(0), sql_field->field_name); + DBUG_RETURN(1); + } + break; + case MYSQL_TYPE_DATE: // Rest of string types + case MYSQL_TYPE_NEWDATE: + case MYSQL_TYPE_TIME: + case MYSQL_TYPE_DATETIME: + case MYSQL_TYPE_NULL: + sql_field->pack_flag=f_settype((uint) sql_field->sql_type); + break; + case MYSQL_TYPE_BIT: + /* + We have sql_field->pack_flag already set here, see + mysql_prepare_create_table(). + */ + break; + case MYSQL_TYPE_NEWDECIMAL: + sql_field->pack_flag=(FIELDFLAG_NUMBER | + (sql_field->flags & UNSIGNED_FLAG ? 0 : + FIELDFLAG_DECIMAL) | + (sql_field->flags & ZEROFILL_FLAG ? + FIELDFLAG_ZEROFILL : 0) | + (sql_field->decimals << FIELDFLAG_DEC_SHIFT)); + break; + case MYSQL_TYPE_TIMESTAMP: + /* We should replace old TIMESTAMP fields with their newer analogs */ + if (sql_field->unireg_check == Field::TIMESTAMP_OLD_FIELD) + { + if (!*timestamps) + { + sql_field->unireg_check= Field::TIMESTAMP_DNUN_FIELD; + (*timestamps_with_niladic)++; + } + else + sql_field->unireg_check= Field::NONE; + } + else if (sql_field->unireg_check != Field::NONE) + (*timestamps_with_niladic)++; + + (*timestamps)++; + /* fall-through */ + default: + sql_field->pack_flag=(FIELDFLAG_NUMBER | + (sql_field->flags & UNSIGNED_FLAG ? 0 : + FIELDFLAG_DECIMAL) | + (sql_field->flags & ZEROFILL_FLAG ? + FIELDFLAG_ZEROFILL : 0) | + f_settype((uint) sql_field->sql_type) | + (sql_field->decimals << FIELDFLAG_DEC_SHIFT)); + break; + } + if (!(sql_field->flags & NOT_NULL_FLAG)) + sql_field->pack_flag|= FIELDFLAG_MAYBE_NULL; + if (sql_field->flags & NO_DEFAULT_VALUE_FLAG) + sql_field->pack_flag|= FIELDFLAG_NO_DEFAULT; + DBUG_RETURN(0); +} + +/* + Preparation for table creation + + SYNOPSIS + mysql_prepare_create_table() + thd Thread object. + create_info Create information (like MAX_ROWS). + alter_info List of columns and indexes to create + tmp_table If a temporary table is to be created. + db_options INOUT Table options (like HA_OPTION_PACK_RECORD). + file The handler for the new table. + key_info_buffer OUT An array of KEY structs for the indexes. + key_count OUT The number of elements in the array. + select_field_count The number of fields coming from a select table. + + DESCRIPTION + Prepares the table and key structures for table creation. + + NOTES + sets create_info->varchar if the table has a varchar + + RETURN VALUES + FALSE OK + TRUE error +*/ + +static int +mysql_prepare_create_table(THD *thd, HA_CREATE_INFO *create_info, + Alter_info *alter_info, + bool tmp_table, + uint *db_options, + handler *file, KEY **key_info_buffer, + uint *key_count, int select_field_count) +{ + const char *key_name; + Create_field *sql_field,*dup_field; + uint field,null_fields,blob_columns,max_key_length; + ulong record_offset= 0; + KEY *key_info; + KEY_PART_INFO *key_part_info; + int timestamps= 0, timestamps_with_niladic= 0; + int field_no,dup_no; + int select_field_pos,auto_increment=0; + List_iterator it(alter_info->create_list); + List_iterator it2(alter_info->create_list); + uint total_uneven_bit_length= 0; + DBUG_ENTER("mysql_prepare_create_table"); + + select_field_pos= alter_info->create_list.elements - select_field_count; + null_fields=blob_columns=0; + create_info->varchar= 0; + max_key_length= file->max_key_length(); + + for (field_no=0; (sql_field=it++) ; field_no++) + { + CHARSET_INFO *save_cs; + + /* + Initialize length from its original value (number of characters), + which was set in the parser. This is necessary if we're + executing a prepared statement for the second time. + */ + sql_field->length= sql_field->char_length; + if (!sql_field->charset) + sql_field->charset= create_info->default_table_charset; + /* + table_charset is set in ALTER TABLE if we want change character set + for all varchar/char columns. + But the table charset must not affect the BLOB fields, so don't + allow to change my_charset_bin to somethig else. + */ + if (create_info->table_charset && sql_field->charset != &my_charset_bin) + sql_field->charset= create_info->table_charset; + + save_cs= sql_field->charset; + if ((sql_field->flags & BINCMP_FLAG) && + !(sql_field->charset= get_charset_by_csname(sql_field->charset->csname, + MY_CS_BINSORT,MYF(0)))) + { + char tmp[64]; + strmake(strmake(tmp, save_cs->csname, sizeof(tmp)-4), + STRING_WITH_LEN("_bin")); + my_error(ER_UNKNOWN_COLLATION, MYF(0), tmp); + DBUG_RETURN(TRUE); + } + + /* + Convert the default value from client character + set into the column character set if necessary. + */ + if (sql_field->def && + save_cs != sql_field->def->collation.collation && + (sql_field->sql_type == MYSQL_TYPE_VAR_STRING || + sql_field->sql_type == MYSQL_TYPE_STRING || + sql_field->sql_type == MYSQL_TYPE_SET || + sql_field->sql_type == MYSQL_TYPE_ENUM)) + { + /* + Starting from 5.1 we work here with a copy of Create_field + created by the caller, not with the instance that was + originally created during parsing. It's OK to create + a temporary item and initialize with it a member of the + copy -- this item will be thrown away along with the copy + at the end of execution, and thus not introduce a dangling + pointer in the parsed tree of a prepared statement or a + stored procedure statement. + */ + sql_field->def= sql_field->def->safe_charset_converter(save_cs); + + if (sql_field->def == NULL) + { + /* Could not convert */ + my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + } + + if (sql_field->sql_type == MYSQL_TYPE_SET || + sql_field->sql_type == MYSQL_TYPE_ENUM) + { + uint32 dummy; + CHARSET_INFO *cs= sql_field->charset; + TYPELIB *interval= sql_field->interval; + + /* + Create typelib from interval_list, and if necessary + convert strings from client character set to the + column character set. + */ + if (!interval) + { + /* + Create the typelib in runtime memory - we will free the + occupied memory at the same time when we free this + sql_field -- at the end of execution. + */ + interval= sql_field->interval= typelib(thd->mem_root, + sql_field->interval_list); + List_iterator int_it(sql_field->interval_list); + String conv, *tmp; + char comma_buf[2]; + int comma_length= cs->cset->wc_mb(cs, ',', (uchar*) comma_buf, + (uchar*) comma_buf + + sizeof(comma_buf)); + DBUG_ASSERT(comma_length > 0); + for (uint i= 0; (tmp= int_it++); i++) + { + size_t lengthsp; + if (String::needs_conversion(tmp->length(), tmp->charset(), + cs, &dummy)) + { + uint cnv_errs; + conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), cs, &cnv_errs); + interval->type_names[i]= strmake_root(thd->mem_root, conv.ptr(), + conv.length()); + interval->type_lengths[i]= conv.length(); + } + + // Strip trailing spaces. + lengthsp= cs->cset->lengthsp(cs, interval->type_names[i], + interval->type_lengths[i]); + interval->type_lengths[i]= lengthsp; + ((uchar *)interval->type_names[i])[lengthsp]= '\0'; + if (sql_field->sql_type == MYSQL_TYPE_SET) + { + if (cs->coll->instr(cs, interval->type_names[i], + interval->type_lengths[i], + comma_buf, comma_length, NULL, 0)) + { + my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "set", tmp->ptr()); + DBUG_RETURN(TRUE); + } + } + } + sql_field->interval_list.empty(); // Don't need interval_list anymore + } + + if (sql_field->sql_type == MYSQL_TYPE_SET) + { + uint32 field_length; + if (sql_field->def != NULL) + { + char *not_used; + uint not_used2; + bool not_found= 0; + String str, *def= sql_field->def->val_str(&str); + if (def == NULL) /* SQL "NULL" maps to NULL */ + { + if ((sql_field->flags & NOT_NULL_FLAG) != 0) + { + my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + + /* else, NULL is an allowed value */ + (void) find_set(interval, NULL, 0, + cs, ¬_used, ¬_used2, ¬_found); + } + else /* not NULL */ + { + (void) find_set(interval, def->ptr(), def->length(), + cs, ¬_used, ¬_used2, ¬_found); + } + + if (not_found) + { + my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + } + calculate_interval_lengths(cs, interval, &dummy, &field_length); + sql_field->length= field_length + (interval->count - 1); + } + else /* MYSQL_TYPE_ENUM */ + { + uint32 field_length; + DBUG_ASSERT(sql_field->sql_type == MYSQL_TYPE_ENUM); + if (sql_field->def != NULL) + { + String str, *def= sql_field->def->val_str(&str); + if (def == NULL) /* SQL "NULL" maps to NULL */ + { + if ((sql_field->flags & NOT_NULL_FLAG) != 0) + { + my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + + /* else, the defaults yield the correct length for NULLs. */ + } + else /* not NULL */ + { + def->length(cs->cset->lengthsp(cs, def->ptr(), def->length())); + if (find_type2(interval, def->ptr(), def->length(), cs) == 0) /* not found */ + { + my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + } + } + calculate_interval_lengths(cs, interval, &field_length, &dummy); + sql_field->length= field_length; + } + set_if_smaller(sql_field->length, MAX_FIELD_WIDTH-1); + } + + if (sql_field->sql_type == MYSQL_TYPE_BIT) + { + sql_field->pack_flag= FIELDFLAG_NUMBER; + if (file->ha_table_flags() & HA_CAN_BIT_FIELD) + total_uneven_bit_length+= sql_field->length & 7; + else + sql_field->pack_flag|= FIELDFLAG_TREAT_BIT_AS_CHAR; + } + + sql_field->create_length_to_internal_length(); + if (prepare_blob_field(thd, sql_field)) + DBUG_RETURN(TRUE); + + if (!(sql_field->flags & NOT_NULL_FLAG)) + null_fields++; + + // @bug 2097. Trim trailing spaces for vtable + if (thd->infinidb_vtable.vtable_state != THD::INFINIDB_DISABLE_VTABLE) + { + char* tmp = (char*)sql_field->field_name; + + for (int i = strlen(tmp)-1; i >=0; i--) + { + if (tmp[i] == ' ') + { + tmp[i] = 0; + } + else + break; + } + } + // @bug 3708. Skip the column name checking for vtable creation. + else if (check_column_name(sql_field->field_name)) + { + my_error(ER_WRONG_COLUMN_NAME, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + + /* Check if we have used the same field name before */ + for (dup_no=0; (dup_field=it2++) != sql_field; dup_no++) + { + if (my_strcasecmp(system_charset_info, + sql_field->field_name, + dup_field->field_name) == 0) + { + // @bug 1928. Ignore duplicate field name error for now. Adjust the field name in get_plan and redo phase 1. + if (thd->infinidb_vtable.vtable_state == THD::INFINIDB_CREATE_VTABLE || + thd->infinidb_vtable.vtable_state == THD::INFINIDB_ALTER_VTABLE || + thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_PHASE1 || + thd->infinidb_vtable.vtable_state == THD::INFINIDB_REDO_QUERY) // @bug 3952. non-IDB table redo query + { + //thd->infinidb_vtable.duplicate_field_name = true; + break; + } + /* + If this was a CREATE ... SELECT statement, accept a field + redefinition if we are changing a field in the SELECT part + */ + if (field_no < select_field_pos || dup_no >= select_field_pos) + { + my_error(ER_DUP_FIELDNAME, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + else + { + /* Field redefined */ + sql_field->def= dup_field->def; + sql_field->sql_type= dup_field->sql_type; + sql_field->charset= (dup_field->charset ? + dup_field->charset : + create_info->default_table_charset); + sql_field->length= dup_field->char_length; + sql_field->pack_length= dup_field->pack_length; + sql_field->key_length= dup_field->key_length; + sql_field->decimals= dup_field->decimals; + sql_field->create_length_to_internal_length(); + sql_field->unireg_check= dup_field->unireg_check; + /* + We're making one field from two, the result field will have + dup_field->flags as flags. If we've incremented null_fields + because of sql_field->flags, decrement it back. + */ + if (!(sql_field->flags & NOT_NULL_FLAG)) + null_fields--; + sql_field->flags= dup_field->flags; + sql_field->interval= dup_field->interval; + it2.remove(); // Remove first (create) definition + select_field_pos--; + break; + } + } + } + + /* Don't pack rows in old tables if the user has requested this */ + if ((sql_field->flags & BLOB_FLAG) || + (sql_field->sql_type == MYSQL_TYPE_VARCHAR && + create_info->row_type != ROW_TYPE_FIXED)) + (*db_options)|= HA_OPTION_PACK_RECORD; + it2.rewind(); + } + + /* record_offset will be increased with 'length-of-null-bits' later */ + record_offset= 0; + null_fields+= total_uneven_bit_length; + + it.rewind(); + while ((sql_field=it++)) + { + DBUG_ASSERT(sql_field->charset != 0); + + if (prepare_create_field(sql_field, &blob_columns, + ×tamps, ×tamps_with_niladic, + file->ha_table_flags())) + DBUG_RETURN(TRUE); + if (sql_field->sql_type == MYSQL_TYPE_VARCHAR) + create_info->varchar= TRUE; + sql_field->offset= record_offset; + if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER) + auto_increment++; + record_offset+= sql_field->pack_length; + } + if (timestamps_with_niladic > 1) + { + my_message(ER_TOO_MUCH_AUTO_TIMESTAMP_COLS, + ER(ER_TOO_MUCH_AUTO_TIMESTAMP_COLS), MYF(0)); + DBUG_RETURN(TRUE); + } + if (auto_increment > 1) + { + my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0)); + DBUG_RETURN(TRUE); + } + if (auto_increment && + (file->ha_table_flags() & HA_NO_AUTO_INCREMENT)) + { + my_message(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT, + ER(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT), MYF(0)); + DBUG_RETURN(TRUE); + } + + if (blob_columns && (file->ha_table_flags() & HA_NO_BLOBS)) + { + my_message(ER_TABLE_CANT_HANDLE_BLOB, ER(ER_TABLE_CANT_HANDLE_BLOB), + MYF(0)); + DBUG_RETURN(TRUE); + } + + /* Create keys */ + + List_iterator key_iterator(alter_info->key_list); + List_iterator key_iterator2(alter_info->key_list); + uint key_parts=0, fk_key_count=0; + bool primary_key=0,unique_key=0; + Key *key, *key2; + uint tmp, key_number; + /* special marker for keys to be ignored */ + static char ignore_key[1]; + + /* Calculate number of key segements */ + *key_count= 0; + + while ((key=key_iterator++)) + { + DBUG_PRINT("info", ("key name: '%s' type: %d", key->name ? key->name : + "(none)" , key->type)); + LEX_STRING key_name_str; + if (key->type == Key::FOREIGN_KEY) + { + fk_key_count++; + Foreign_key *fk_key= (Foreign_key*) key; + if (fk_key->ref_columns.elements && + fk_key->ref_columns.elements != fk_key->columns.elements) + { + my_error(ER_WRONG_FK_DEF, MYF(0), + (fk_key->name ? fk_key->name : "foreign key without name"), + ER(ER_KEY_REF_DO_NOT_MATCH_TABLE_REF)); + DBUG_RETURN(TRUE); + } + continue; + } + (*key_count)++; + tmp=file->max_key_parts(); + if (key->columns.elements > tmp) + { + my_error(ER_TOO_MANY_KEY_PARTS,MYF(0),tmp); + DBUG_RETURN(TRUE); + } + key_name_str.str= (char*) key->name; + key_name_str.length= key->name ? strlen(key->name) : 0; + if (check_string_char_length(&key_name_str, "", NAME_CHAR_LEN, + system_charset_info, 1)) + { + my_error(ER_TOO_LONG_IDENT, MYF(0), key->name); + DBUG_RETURN(TRUE); + } + key_iterator2.rewind (); + if (key->type != Key::FOREIGN_KEY) + { + while ((key2 = key_iterator2++) != key) + { + /* + foreign_key_prefix(key, key2) returns 0 if key or key2, or both, is + 'generated', and a generated key is a prefix of the other key. + Then we do not need the generated shorter key. + */ + if ((key2->type != Key::FOREIGN_KEY && + key2->name != ignore_key && + !foreign_key_prefix(key, key2))) + { + /* TODO: issue warning message */ + /* mark that the generated key should be ignored */ + if (!key2->generated || + (key->generated && key->columns.elements < + key2->columns.elements)) + key->name= ignore_key; + else + { + key2->name= ignore_key; + key_parts-= key2->columns.elements; + (*key_count)--; + } + break; + } + } + } + if (key->name != ignore_key) + key_parts+=key->columns.elements; + else + (*key_count)--; + if (key->name && !tmp_table && (key->type != Key::PRIMARY) && + !my_strcasecmp(system_charset_info,key->name,primary_key_name)) + { + my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name); + DBUG_RETURN(TRUE); + } + } + tmp=file->max_keys(); + if (*key_count > tmp) + { + my_error(ER_TOO_MANY_KEYS,MYF(0),tmp); + DBUG_RETURN(TRUE); + } + + (*key_info_buffer)= key_info= (KEY*) sql_calloc(sizeof(KEY) * (*key_count)); + key_part_info=(KEY_PART_INFO*) sql_calloc(sizeof(KEY_PART_INFO)*key_parts); + if (!*key_info_buffer || ! key_part_info) + DBUG_RETURN(TRUE); // Out of memory + + key_iterator.rewind(); + key_number=0; + for (; (key=key_iterator++) ; key_number++) + { + uint key_length=0; + Key_part_spec *column; + + if (key->name == ignore_key) + { + /* ignore redundant keys */ + do + key=key_iterator++; + while (key && key->name == ignore_key); + if (!key) + break; + } + + switch (key->type) { + case Key::MULTIPLE: + key_info->flags= 0; + break; + case Key::FULLTEXT: + key_info->flags= HA_FULLTEXT; + if ((key_info->parser_name= &key->key_create_info.parser_name)->str) + key_info->flags|= HA_USES_PARSER; + else + key_info->parser_name= 0; + break; + case Key::SPATIAL: +#ifdef HAVE_SPATIAL + key_info->flags= HA_SPATIAL; + break; +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + sym_group_geom.name, sym_group_geom.needed_define); + DBUG_RETURN(TRUE); +#endif + case Key::FOREIGN_KEY: + key_number--; // Skip this key + continue; + default: + key_info->flags = HA_NOSAME; + break; + } + if (key->generated) + key_info->flags|= HA_GENERATED_KEY; + + key_info->key_parts=(uint8) key->columns.elements; + key_info->key_part=key_part_info; + key_info->usable_key_parts= key_number; + key_info->algorithm= key->key_create_info.algorithm; + + if (key->type == Key::FULLTEXT) + { + if (!(file->ha_table_flags() & HA_CAN_FULLTEXT)) + { + my_message(ER_TABLE_CANT_HANDLE_FT, ER(ER_TABLE_CANT_HANDLE_FT), + MYF(0)); + DBUG_RETURN(TRUE); + } + } + /* + Make SPATIAL to be RTREE by default + SPATIAL only on BLOB or at least BINARY, this + actually should be replaced by special GEOM type + in near future when new frm file is ready + checking for proper key parts number: + */ + + /* TODO: Add proper checks if handler supports key_type and algorithm */ + if (key_info->flags & HA_SPATIAL) + { + if (!(file->ha_table_flags() & HA_CAN_RTREEKEYS)) + { + my_message(ER_TABLE_CANT_HANDLE_SPKEYS, ER(ER_TABLE_CANT_HANDLE_SPKEYS), + MYF(0)); + DBUG_RETURN(TRUE); + } + if (key_info->key_parts != 1) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "SPATIAL INDEX"); + DBUG_RETURN(TRUE); + } + } + else if (key_info->algorithm == HA_KEY_ALG_RTREE) + { +#ifdef HAVE_RTREE_KEYS + if ((key_info->key_parts & 1) == 1) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "RTREE INDEX"); + DBUG_RETURN(TRUE); + } + /* TODO: To be deleted */ + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "RTREE INDEX"); + DBUG_RETURN(TRUE); +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + sym_group_rtree.name, sym_group_rtree.needed_define); + DBUG_RETURN(TRUE); +#endif + } + + /* Take block size from key part or table part */ + /* + TODO: Add warning if block size changes. We can't do it here, as + this may depend on the size of the key + */ + key_info->block_size= (key->key_create_info.block_size ? + key->key_create_info.block_size : + create_info->key_block_size); + + if (key_info->block_size) + key_info->flags|= HA_USES_BLOCK_SIZE; + + List_iterator cols(key->columns), cols2(key->columns); + CHARSET_INFO *ft_key_charset=0; // for FULLTEXT + for (uint column_nr=0 ; (column=cols++) ; column_nr++) + { + uint length; + Key_part_spec *dup_column; + + it.rewind(); + field=0; + while ((sql_field=it++) && + my_strcasecmp(system_charset_info, + column->field_name, + sql_field->field_name)) + field++; + if (!sql_field) + { + my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name); + DBUG_RETURN(TRUE); + } + while ((dup_column= cols2++) != column) + { + if (!my_strcasecmp(system_charset_info, + column->field_name, dup_column->field_name)) + { + my_printf_error(ER_DUP_FIELDNAME, + ER(ER_DUP_FIELDNAME),MYF(0), + column->field_name); + DBUG_RETURN(TRUE); + } + } + cols2.rewind(); + if (key->type == Key::FULLTEXT) + { + if ((sql_field->sql_type != MYSQL_TYPE_STRING && + sql_field->sql_type != MYSQL_TYPE_VARCHAR && + !f_is_blob(sql_field->pack_flag)) || + sql_field->charset == &my_charset_bin || + sql_field->charset->mbminlen > 1 || // ucs2 doesn't work yet + (ft_key_charset && sql_field->charset != ft_key_charset)) + { + my_error(ER_BAD_FT_COLUMN, MYF(0), column->field_name); + DBUG_RETURN(-1); + } + ft_key_charset=sql_field->charset; + /* + for fulltext keys keyseg length is 1 for blobs (it's ignored in ft + code anyway, and 0 (set to column width later) for char's. it has + to be correct col width for char's, as char data are not prefixed + with length (unlike blobs, where ft code takes data length from a + data prefix, ignoring column->length). + */ + column->length=test(f_is_blob(sql_field->pack_flag)); + } + else + { + column->length*= sql_field->charset->mbmaxlen; + + if (key->type == Key::SPATIAL && column->length) + { + my_error(ER_WRONG_SUB_KEY, MYF(0)); + DBUG_RETURN(TRUE); + } + + if (f_is_blob(sql_field->pack_flag) || + (f_is_geom(sql_field->pack_flag) && key->type != Key::SPATIAL)) + { + if (!(file->ha_table_flags() & HA_CAN_INDEX_BLOBS)) + { + my_error(ER_BLOB_USED_AS_KEY, MYF(0), column->field_name); + DBUG_RETURN(TRUE); + } + if (f_is_geom(sql_field->pack_flag) && sql_field->geom_type == + Field::GEOM_POINT) + column->length= 25; + if (!column->length) + { + my_error(ER_BLOB_KEY_WITHOUT_LENGTH, MYF(0), column->field_name); + DBUG_RETURN(TRUE); + } + } +#ifdef HAVE_SPATIAL + if (key->type == Key::SPATIAL) + { + if (!column->length) + { + /* + 4 is: (Xmin,Xmax,Ymin,Ymax), this is for 2D case + Lately we'll extend this code to support more dimensions + */ + column->length= 4*sizeof(double); + } + } +#endif + if (!(sql_field->flags & NOT_NULL_FLAG)) + { + if (key->type == Key::PRIMARY) + { + /* Implicitly set primary key fields to NOT NULL for ISO conf. */ + sql_field->flags|= NOT_NULL_FLAG; + sql_field->pack_flag&= ~FIELDFLAG_MAYBE_NULL; + null_fields--; + } + else + { + key_info->flags|= HA_NULL_PART_KEY; + if (!(file->ha_table_flags() & HA_NULL_IN_KEY)) + { + my_error(ER_NULL_COLUMN_IN_INDEX, MYF(0), column->field_name); + DBUG_RETURN(TRUE); + } + if (key->type == Key::SPATIAL) + { + my_message(ER_SPATIAL_CANT_HAVE_NULL, + ER(ER_SPATIAL_CANT_HAVE_NULL), MYF(0)); + DBUG_RETURN(TRUE); + } + } + } + if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER) + { + if (column_nr == 0 || (file->ha_table_flags() & HA_AUTO_PART_KEY)) + auto_increment--; // Field is used + } + } + + key_part_info->fieldnr= field; + key_part_info->offset= (uint16) sql_field->offset; + key_part_info->key_type=sql_field->pack_flag; + length= sql_field->key_length; + + if (column->length) + { + if (f_is_blob(sql_field->pack_flag)) + { + if ((length=column->length) > max_key_length || + length > file->max_key_part_length()) + { + length=min(max_key_length, file->max_key_part_length()); + if (key->type == Key::MULTIPLE) + { + /* not a critical problem */ + char warn_buff[MYSQL_ERRMSG_SIZE]; + my_snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_KEY), + length); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TOO_LONG_KEY, warn_buff); + /* Align key length to multibyte char boundary */ + length-= length % sql_field->charset->mbmaxlen; + } + else + { + my_error(ER_TOO_LONG_KEY,MYF(0),length); + DBUG_RETURN(TRUE); + } + } + } + else if (!f_is_geom(sql_field->pack_flag) && + (column->length > length || + !Field::type_can_have_key_part (sql_field->sql_type) || + ((f_is_packed(sql_field->pack_flag) || + ((file->ha_table_flags() & HA_NO_PREFIX_CHAR_KEYS) && + (key_info->flags & HA_NOSAME))) && + column->length != length))) + { + my_message(ER_WRONG_SUB_KEY, ER(ER_WRONG_SUB_KEY), MYF(0)); + DBUG_RETURN(TRUE); + } + else if (!(file->ha_table_flags() & HA_NO_PREFIX_CHAR_KEYS)) + length=column->length; + } + else if (length == 0) + { + my_error(ER_WRONG_KEY_COLUMN, MYF(0), column->field_name); + DBUG_RETURN(TRUE); + } + if (length > file->max_key_part_length() && key->type != Key::FULLTEXT) + { + length= file->max_key_part_length(); + if (key->type == Key::MULTIPLE) + { + /* not a critical problem */ + char warn_buff[MYSQL_ERRMSG_SIZE]; + my_snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_KEY), + length); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_TOO_LONG_KEY, warn_buff); + /* Align key length to multibyte char boundary */ + length-= length % sql_field->charset->mbmaxlen; + } + else + { + my_error(ER_TOO_LONG_KEY,MYF(0),length); + DBUG_RETURN(TRUE); + } + } + key_part_info->length=(uint16) length; + /* Use packed keys for long strings on the first column */ + if (!((*db_options) & HA_OPTION_NO_PACK_KEYS) && + (length >= KEY_DEFAULT_PACK_LENGTH && + (sql_field->sql_type == MYSQL_TYPE_STRING || + sql_field->sql_type == MYSQL_TYPE_VARCHAR || + sql_field->pack_flag & FIELDFLAG_BLOB))) + { + if ((column_nr == 0 && (sql_field->pack_flag & FIELDFLAG_BLOB)) || + sql_field->sql_type == MYSQL_TYPE_VARCHAR) + key_info->flags|= HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; + else + key_info->flags|= HA_PACK_KEY; + } + /* Check if the key segment is partial, set the key flag accordingly */ + if (length != sql_field->key_length) + key_info->flags|= HA_KEY_HAS_PART_KEY_SEG; + + key_length+=length; + key_part_info++; + + /* Create the key name based on the first column (if not given) */ + if (column_nr == 0) + { + if (key->type == Key::PRIMARY) + { + if (primary_key) + { + my_message(ER_MULTIPLE_PRI_KEY, ER(ER_MULTIPLE_PRI_KEY), + MYF(0)); + DBUG_RETURN(TRUE); + } + key_name=primary_key_name; + primary_key=1; + } + else if (!(key_name = key->name)) + key_name=make_unique_key_name(sql_field->field_name, + *key_info_buffer, key_info); + if (check_if_keyname_exists(key_name, *key_info_buffer, key_info)) + { + my_error(ER_DUP_KEYNAME, MYF(0), key_name); + DBUG_RETURN(TRUE); + } + key_info->name=(char*) key_name; + } + } + if (!key_info->name || check_column_name(key_info->name)) + { + my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key_info->name); + DBUG_RETURN(TRUE); + } + if (!(key_info->flags & HA_NULL_PART_KEY)) + unique_key=1; + key_info->key_length=(uint16) key_length; + if (key_length > max_key_length && key->type != Key::FULLTEXT) + { + my_error(ER_TOO_LONG_KEY,MYF(0),max_key_length); + DBUG_RETURN(TRUE); + } + key_info++; + } + if (!unique_key && !primary_key && + (file->ha_table_flags() & HA_REQUIRE_PRIMARY_KEY)) + { + my_message(ER_REQUIRES_PRIMARY_KEY, ER(ER_REQUIRES_PRIMARY_KEY), MYF(0)); + DBUG_RETURN(TRUE); + } + if (auto_increment > 0) + { + my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0)); + DBUG_RETURN(TRUE); + } + /* Sort keys in optimized order */ + my_qsort((uchar*) *key_info_buffer, *key_count, sizeof(KEY), + (qsort_cmp) sort_keys); + create_info->null_bits= null_fields; + + /* Check fields. */ + it.rewind(); + while ((sql_field=it++)) + { + Field::utype type= (Field::utype) MTYP_TYPENR(sql_field->unireg_check); + + if (thd->variables.sql_mode & MODE_NO_ZERO_DATE && + !sql_field->def && + sql_field->sql_type == MYSQL_TYPE_TIMESTAMP && + (sql_field->flags & NOT_NULL_FLAG) && + (type == Field::NONE || type == Field::TIMESTAMP_UN_FIELD)) + { + /* + An error should be reported if: + - NO_ZERO_DATE SQL mode is active; + - there is no explicit DEFAULT clause (default column value); + - this is a TIMESTAMP column; + - the column is not NULL; + - this is not the DEFAULT CURRENT_TIMESTAMP column. + + In other words, an error should be reported if + - NO_ZERO_DATE SQL mode is active; + - the column definition is equivalent to + 'column_name TIMESTAMP DEFAULT 0'. + */ + + my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); + DBUG_RETURN(TRUE); + } + } + + DBUG_RETURN(FALSE); +} + + +/* + Set table default charset, if not set + + SYNOPSIS + set_table_default_charset() + create_info Table create information + + DESCRIPTION + If the table character set was not given explicitely, + let's fetch the database default character set and + apply it to the table. +*/ + +static void set_table_default_charset(THD *thd, + HA_CREATE_INFO *create_info, char *db) +{ + /* + If the table character set was not given explicitly, + let's fetch the database default character set and + apply it to the table. + */ + if (!create_info->default_table_charset) + { + HA_CREATE_INFO db_info; + + load_db_opt_by_name(thd, db, &db_info); + + create_info->default_table_charset= db_info.default_table_charset; + } +} + + +/* + Extend long VARCHAR fields to blob & prepare field if it's a blob + + SYNOPSIS + prepare_blob_field() + sql_field Field to check + + RETURN + 0 ok + 1 Error (sql_field can't be converted to blob) + In this case the error is given +*/ + +static bool prepare_blob_field(THD *thd, Create_field *sql_field) +{ + DBUG_ENTER("prepare_blob_field"); + + if (sql_field->length > MAX_FIELD_VARCHARLENGTH && + !(sql_field->flags & BLOB_FLAG)) + { + /* Convert long VARCHAR columns to TEXT or BLOB */ + char warn_buff[MYSQL_ERRMSG_SIZE]; + + if (sql_field->def || (thd->variables.sql_mode & (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES))) + { + my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name, + MAX_FIELD_VARCHARLENGTH / sql_field->charset->mbmaxlen); + DBUG_RETURN(1); + } + sql_field->sql_type= MYSQL_TYPE_BLOB; + sql_field->flags|= BLOB_FLAG; + my_snprintf(warn_buff, sizeof(warn_buff), ER(ER_AUTO_CONVERT), sql_field->field_name, + (sql_field->charset == &my_charset_bin) ? "VARBINARY" : "VARCHAR", + (sql_field->charset == &my_charset_bin) ? "BLOB" : "TEXT"); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, ER_AUTO_CONVERT, + warn_buff); + } + + if ((sql_field->flags & BLOB_FLAG) && sql_field->length) + { + if (sql_field->sql_type == FIELD_TYPE_BLOB || + sql_field->sql_type == FIELD_TYPE_TINY_BLOB || + sql_field->sql_type == FIELD_TYPE_MEDIUM_BLOB) + { + /* The user has given a length to the blob column */ + sql_field->sql_type= get_blob_type_from_length(sql_field->length); + sql_field->pack_length= calc_pack_length(sql_field->sql_type, 0); + } + sql_field->length= 0; + } + DBUG_RETURN(0); +} + + +/* + Preparation of Create_field for SP function return values. + Based on code used in the inner loop of mysql_prepare_create_table() + above. + + SYNOPSIS + sp_prepare_create_field() + thd Thread object + sql_field Field to prepare + + DESCRIPTION + Prepares the field structures for field creation. + +*/ + +void sp_prepare_create_field(THD *thd, Create_field *sql_field) +{ + if (sql_field->sql_type == MYSQL_TYPE_SET || + sql_field->sql_type == MYSQL_TYPE_ENUM) + { + uint32 field_length, dummy; + if (sql_field->sql_type == MYSQL_TYPE_SET) + { + calculate_interval_lengths(sql_field->charset, + sql_field->interval, &dummy, + &field_length); + sql_field->length= field_length + + (sql_field->interval->count - 1); + } + else /* MYSQL_TYPE_ENUM */ + { + calculate_interval_lengths(sql_field->charset, + sql_field->interval, + &field_length, &dummy); + sql_field->length= field_length; + } + set_if_smaller(sql_field->length, MAX_FIELD_WIDTH-1); + } + + if (sql_field->sql_type == MYSQL_TYPE_BIT) + { + sql_field->pack_flag= FIELDFLAG_NUMBER | + FIELDFLAG_TREAT_BIT_AS_CHAR; + } + sql_field->create_length_to_internal_length(); + DBUG_ASSERT(sql_field->def == 0); + /* Can't go wrong as sql_field->def is not defined */ + (void) prepare_blob_field(thd, sql_field); +} + + +/* + Write CREATE TABLE binlog + + SYNOPSIS + write_create_table_bin_log() + thd Thread object + create_info Create information + internal_tmp_table Set to 1 if this is an internal temporary table + + DESCRIPTION + This function only is called in mysql_create_table_no_lock and + mysql_create_table + + RETURN VALUES + NONE + */ +static inline void write_create_table_bin_log(THD *thd, + const HA_CREATE_INFO *create_info, + bool internal_tmp_table) +{ + /* + Don't write statement if: + - It is an internal temporary table, + - Row-based logging is used and it we are creating a temporary table, or + - The binary log is not open. + Otherwise, the statement shall be binlogged. + */ + if (!internal_tmp_table && + (!thd->current_stmt_binlog_row_based || + (thd->current_stmt_binlog_row_based && + !(create_info->options & HA_LEX_CREATE_TMP_TABLE)))) + write_bin_log(thd, TRUE, thd->query, thd->query_length); +} + + +/* + Create a table + + SYNOPSIS + mysql_create_table_no_lock() + thd Thread object + db Database + table_name Table name + create_info Create information (like MAX_ROWS) + fields List of fields to create + keys List of keys to create + internal_tmp_table Set to 1 if this is an internal temporary table + (From ALTER TABLE) + select_field_count + + DESCRIPTION + If one creates a temporary table, this is automatically opened + + Note that this function assumes that caller already have taken + name-lock on table being created or used some other way to ensure + that concurrent operations won't intervene. mysql_create_table() + is a wrapper that can be used for this. + + no_log is needed for the case of CREATE ... SELECT, + as the logging will be done later in sql_insert.cc + select_field_count is also used for CREATE ... SELECT, + and must be zero for standard create of table. + + RETURN VALUES + FALSE OK + TRUE error +*/ + +bool mysql_create_table_no_lock(THD *thd, + const char *db, const char *table_name, + HA_CREATE_INFO *create_info, + Alter_info *alter_info, + bool internal_tmp_table, + uint select_field_count) +{ + char path[FN_REFLEN + 1]; + uint path_length; + const char *alias; + uint db_options, key_count; + KEY *key_info_buffer; + handler *file; + bool error= TRUE; + DBUG_ENTER("mysql_create_table_no_lock"); + DBUG_PRINT("enter", ("db: '%s' table: '%s' tmp: %d", + db, table_name, internal_tmp_table)); + + + /* Check for duplicate fields and check type of table to create */ + if (!alter_info->create_list.elements) + { + my_message(ER_TABLE_MUST_HAVE_COLUMNS, ER(ER_TABLE_MUST_HAVE_COLUMNS), + MYF(0)); + DBUG_RETURN(TRUE); + } + if (check_engine(thd, table_name, create_info)) + DBUG_RETURN(TRUE); + db_options= create_info->table_options; + if (create_info->row_type == ROW_TYPE_DYNAMIC) + db_options|=HA_OPTION_PACK_RECORD; + alias= table_case_name(create_info, table_name); + if (!(file= get_new_handler((TABLE_SHARE*) 0, thd->mem_root, + create_info->db_type))) + { + mem_alloc_error(sizeof(handler)); + DBUG_RETURN(TRUE); + } +#ifdef WITH_PARTITION_STORAGE_ENGINE + partition_info *part_info= thd->work_part_info; + + if (!part_info && create_info->db_type->partition_flags && + (create_info->db_type->partition_flags() & HA_USE_AUTO_PARTITION)) + { + /* + Table is not defined as a partitioned table but the engine handles + all tables as partitioned. The handler will set up the partition info + object with the default settings. + */ + thd->work_part_info= part_info= new partition_info(); + if (!part_info) + { + mem_alloc_error(sizeof(partition_info)); + DBUG_RETURN(TRUE); + } + file->set_auto_partitions(part_info); + part_info->default_engine_type= create_info->db_type; + part_info->is_auto_partitioned= TRUE; + } + if (part_info) + { + /* + The table has been specified as a partitioned table. + If this is part of an ALTER TABLE the handler will be the partition + handler but we need to specify the default handler to use for + partitions also in the call to check_partition_info. We transport + this information in the default_db_type variable, it is either + DB_TYPE_DEFAULT or the engine set in the ALTER TABLE command. + + Check that we don't use foreign keys in the table since it won't + work even with InnoDB beneath it. + */ + List_iterator key_iterator(alter_info->key_list); + Key *key; + handlerton *part_engine_type= create_info->db_type; + char *part_syntax_buf; + uint syntax_len; + handlerton *engine_type; + if (create_info->options & HA_LEX_CREATE_TMP_TABLE) + { + my_error(ER_PARTITION_NO_TEMPORARY, MYF(0)); + goto err; + } + while ((key= key_iterator++)) + { + if (key->type == Key::FOREIGN_KEY && + !part_info->is_auto_partitioned) + { + my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0)); + goto err; + } + } + if ((part_engine_type == partition_hton) && + part_info->default_engine_type) + { + /* + This only happens at ALTER TABLE. + default_engine_type was assigned from the engine set in the ALTER + TABLE command. + */ + ; + } + else + { + if (create_info->used_fields & HA_CREATE_USED_ENGINE) + { + part_info->default_engine_type= create_info->db_type; + } + else + { + if (part_info->default_engine_type == NULL) + { + part_info->default_engine_type= ha_checktype(thd, + DB_TYPE_DEFAULT, 0, 0); + } + } + } + DBUG_PRINT("info", ("db_type = %s create_info->db_type = %s", + ha_resolve_storage_engine_name(part_info->default_engine_type), + ha_resolve_storage_engine_name(create_info->db_type))); + if (part_info->check_partition_info(thd, &engine_type, file, + create_info, TRUE)) + goto err; + part_info->default_engine_type= engine_type; + + /* + We reverse the partitioning parser and generate a standard format + for syntax stored in frm file. + */ + if (!(part_syntax_buf= generate_partition_syntax(part_info, + &syntax_len, + TRUE, TRUE))) + goto err; + part_info->part_info_string= part_syntax_buf; + part_info->part_info_len= syntax_len; + if ((!(engine_type->partition_flags && + engine_type->partition_flags() & HA_CAN_PARTITION)) || + create_info->db_type == partition_hton) + { + /* + The handler assigned to the table cannot handle partitioning. + Assign the partition handler as the handler of the table. + */ + DBUG_PRINT("info", ("db_type: %s", + ha_resolve_storage_engine_name(create_info->db_type))); + delete file; + create_info->db_type= partition_hton; + if (!(file= get_ha_partition(part_info))) + { + DBUG_RETURN(TRUE); + } + /* + If we have default number of partitions or subpartitions we + might require to set-up the part_info object such that it + creates a proper .par file. The current part_info object is + only used to create the frm-file and .par-file. + */ + if (part_info->use_default_no_partitions && + part_info->no_parts && + (int)part_info->no_parts != + file->get_default_no_partitions(create_info)) + { + uint i; + List_iterator part_it(part_info->partitions); + part_it++; + DBUG_ASSERT(thd->lex->sql_command != SQLCOM_CREATE_TABLE); + for (i= 1; i < part_info->partitions.elements; i++) + (part_it++)->part_state= PART_TO_BE_DROPPED; + } + else if (part_info->is_sub_partitioned() && + part_info->use_default_no_subpartitions && + part_info->no_subparts && + (int)part_info->no_subparts != + file->get_default_no_partitions(create_info)) + { + DBUG_ASSERT(thd->lex->sql_command != SQLCOM_CREATE_TABLE); + part_info->no_subparts= file->get_default_no_partitions(create_info); + } + } + else if (create_info->db_type != engine_type) + { + /* + We come here when we don't use a partitioned handler. + Since we use a partitioned table it must be "native partitioned". + We have switched engine from defaults, most likely only specified + engines in partition clauses. + */ + delete file; + if (!(file= get_new_handler((TABLE_SHARE*) 0, thd->mem_root, + engine_type))) + { + mem_alloc_error(sizeof(handler)); + DBUG_RETURN(TRUE); + } + } + } +#endif + + set_table_default_charset(thd, create_info, (char*) db); + + if (mysql_prepare_create_table(thd, create_info, alter_info, + internal_tmp_table, + &db_options, file, + &key_info_buffer, &key_count, + select_field_count)) + goto err; + + /* Check if table exists */ + if (create_info->options & HA_LEX_CREATE_TMP_TABLE) + { + path_length= build_tmptable_filename(thd, path, sizeof(path)); + create_info->table_options|=HA_CREATE_DELAY_KEY_WRITE; + } + else + { + path_length= build_table_filename(path, sizeof(path) - 1, db, alias, reg_ext, + internal_tmp_table ? FN_IS_TMP : 0); + } + + /* Check if table already exists */ + if ((create_info->options & HA_LEX_CREATE_TMP_TABLE) && + find_temporary_table(thd, db, table_name)) + { + if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS) + { + create_info->table_existed= 1; // Mark that table existed + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR), + alias); + error= 0; + write_create_table_bin_log(thd, create_info, internal_tmp_table); + goto err; + } + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alias); + goto err; + } + + VOID(pthread_mutex_lock(&LOCK_open)); + if (!internal_tmp_table && !(create_info->options & HA_LEX_CREATE_TMP_TABLE)) + { + if (!access(path,F_OK)) + { + if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS) + goto warn; + my_error(ER_TABLE_EXISTS_ERROR,MYF(0),table_name); + goto unlock_and_end; + } + /* + We don't assert here, but check the result, because the table could be + in the table definition cache and in the same time the .frm could be + missing from the disk, in case of manual intervention which deletes + the .frm file. The user has to use FLUSH TABLES; to clear the cache. + Then she could create the table. This case is pretty obscure and + therefore we don't introduce a new error message only for it. + */ + if (get_cached_table_share(db, alias)) + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), table_name); + goto unlock_and_end; + } + } + + /* + Check that table with given name does not already + exist in any storage engine. In such a case it should + be discovered and the error ER_TABLE_EXISTS_ERROR be returned + unless user specified CREATE TABLE IF EXISTS + The LOCK_open mutex has been locked to make sure no + one else is attempting to discover the table. Since + it's not on disk as a frm file, no one could be using it! + */ + if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) + { + bool create_if_not_exists = + create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS; + int retcode = ha_table_exists_in_engine(thd, db, table_name); + DBUG_PRINT("info", ("exists_in_engine: %u",retcode)); + switch (retcode) + { + case HA_ERR_NO_SUCH_TABLE: + /* Normal case, no table exists. we can go and create it */ + break; + case HA_ERR_TABLE_EXIST: + DBUG_PRINT("info", ("Table existed in handler")); + + if (create_if_not_exists) + goto warn; + my_error(ER_TABLE_EXISTS_ERROR,MYF(0),table_name); + goto unlock_and_end; + break; + default: + DBUG_PRINT("info", ("error: %u from storage engine", retcode)); + my_error(retcode, MYF(0),table_name); + goto unlock_and_end; + } + } + + thd_proc_info(thd, "creating table"); + create_info->table_existed= 0; // Mark that table is created + +#ifdef HAVE_READLINK + if (test_if_data_home_dir(create_info->data_file_name)) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "DATA DIRECTORY"); + goto unlock_and_end; + } + if (test_if_data_home_dir(create_info->index_file_name)) + { + my_error(ER_WRONG_ARGUMENTS, MYF(0), "INDEX DIRECTORY"); + goto unlock_and_end; + } + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (check_partition_dirs(thd->lex->part_info)) + { + goto unlock_and_end; + } +#endif /* WITH_PARTITION_STORAGE_ENGINE */ + + if (!my_use_symdir || (thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE)) +#endif /* HAVE_READLINK */ + { + if (create_info->data_file_name) + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED), + "DATA DIRECTORY"); + if (create_info->index_file_name) + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, + WARN_OPTION_IGNORED, ER(WARN_OPTION_IGNORED), + "INDEX DIRECTORY"); + create_info->data_file_name= create_info->index_file_name= 0; + } + create_info->table_options=db_options; + + path[path_length - reg_ext_length]= '\0'; // Remove .frm extension + if (rea_create_table(thd, path, db, table_name, + create_info, alter_info->create_list, + key_count, key_info_buffer, file)) + goto unlock_and_end; + + if (create_info->options & HA_LEX_CREATE_TMP_TABLE) + { + /* Open table and put in temporary table list */ + if (!(open_temporary_table(thd, path, db, table_name, 1))) + { + (void) rm_temporary_table(create_info->db_type, path); + goto unlock_and_end; + } + thd->thread_specific_used= TRUE; + } + + write_create_table_bin_log(thd, create_info, internal_tmp_table); + error= FALSE; +unlock_and_end: + VOID(pthread_mutex_unlock(&LOCK_open)); + +err: + thd_proc_info(thd, "After create"); + delete file; + DBUG_RETURN(error); + +warn: + error= FALSE; + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR), + alias); + create_info->table_existed= 1; // Mark that table existed + write_create_table_bin_log(thd, create_info, internal_tmp_table); + goto unlock_and_end; +} + + +/* + Database and name-locking aware wrapper for mysql_create_table_no_lock(), +*/ + +bool mysql_create_table(THD *thd, const char *db, const char *table_name, + HA_CREATE_INFO *create_info, + Alter_info *alter_info, + bool internal_tmp_table, + uint select_field_count) +{ + TABLE *name_lock= 0; + bool result; + DBUG_ENTER("mysql_create_table"); + + /* Wait for any database locks */ + pthread_mutex_lock(&LOCK_lock_db); + while (!thd->killed && + hash_search(&lock_db_cache,(uchar*) db, strlen(db))) + { + wait_for_condition(thd, &LOCK_lock_db, &COND_refresh); + pthread_mutex_lock(&LOCK_lock_db); + } + + if (thd->killed) + { + pthread_mutex_unlock(&LOCK_lock_db); + DBUG_RETURN(TRUE); + } + creating_table++; + pthread_mutex_unlock(&LOCK_lock_db); + + if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) + { + if (lock_table_name_if_not_cached(thd, db, table_name, &name_lock)) + { + result= TRUE; + goto unlock; + } + if (!name_lock) + { + if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR), + table_name); + create_info->table_existed= 1; + result= FALSE; + write_create_table_bin_log(thd, create_info, internal_tmp_table); + } + else + { + my_error(ER_TABLE_EXISTS_ERROR,MYF(0),table_name); + result= TRUE; + } + goto unlock; + } + } + + result= mysql_create_table_no_lock(thd, db, table_name, create_info, + alter_info, + internal_tmp_table, + select_field_count); + +unlock: + if (name_lock) + { + pthread_mutex_lock(&LOCK_open); + unlink_open_table(thd, name_lock, FALSE); + pthread_mutex_unlock(&LOCK_open); + } + pthread_mutex_lock(&LOCK_lock_db); + if (!--creating_table && creating_database) + pthread_cond_signal(&COND_refresh); + pthread_mutex_unlock(&LOCK_lock_db); + DBUG_RETURN(result); +} + + +/* +** Give the key name after the first field with an optional '_#' after +**/ + +static bool +check_if_keyname_exists(const char *name, KEY *start, KEY *end) +{ + for (KEY *key=start ; key != end ; key++) + if (!my_strcasecmp(system_charset_info,name,key->name)) + return 1; + return 0; +} + + +static char * +make_unique_key_name(const char *field_name,KEY *start,KEY *end) +{ + char buff[MAX_FIELD_NAME],*buff_end; + + if (!check_if_keyname_exists(field_name,start,end) && + my_strcasecmp(system_charset_info,field_name,primary_key_name)) + return (char*) field_name; // Use fieldname + buff_end=strmake(buff,field_name, sizeof(buff)-4); + + /* + Only 3 chars + '\0' left, so need to limit to 2 digit + This is ok as we can't have more than 100 keys anyway + */ + for (uint i=2 ; i< 100; i++) + { + *buff_end= '_'; + int10_to_str(i, buff_end+1, 10); + if (!check_if_keyname_exists(buff,start,end)) + return sql_strdup(buff); + } + return (char*) "not_specified"; // Should never happen +} + + +/**************************************************************************** +** Alter a table definition +****************************************************************************/ + + +/* + Rename a table. + + SYNOPSIS + mysql_rename_table() + base The handlerton handle. + old_db The old database name. + old_name The old table name. + new_db The new database name. + new_name The new table name. + flags flags for build_table_filename(). + FN_FROM_IS_TMP old_name is temporary. + FN_TO_IS_TMP new_name is temporary. + NO_FRM_RENAME Don't rename the FRM file + but only the table in the storage engine. + + RETURN + FALSE OK + TRUE Error +*/ + +bool +mysql_rename_table(handlerton *base, const char *old_db, + const char *old_name, const char *new_db, + const char *new_name, uint flags) +{ + THD *thd= current_thd; + char from[FN_REFLEN + 1], to[FN_REFLEN + 1], + lc_from[FN_REFLEN + 1], lc_to[FN_REFLEN + 1]; + char *from_base= from, *to_base= to; + char tmp_name[NAME_LEN+1]; + handler *file; + int error=0; + DBUG_ENTER("mysql_rename_table"); + DBUG_PRINT("enter", ("old: '%s'.'%s' new: '%s'.'%s'", + old_db, old_name, new_db, new_name)); + + file= (base == NULL ? 0 : + get_new_handler((TABLE_SHARE*) 0, thd->mem_root, base)); + + build_table_filename(from, sizeof(from) - 1, old_db, old_name, "", + flags & FN_FROM_IS_TMP); + build_table_filename(to, sizeof(to) - 1, new_db, new_name, "", + flags & FN_TO_IS_TMP); + + /* + If lower_case_table_names == 2 (case-preserving but case-insensitive + file system) and the storage is not HA_FILE_BASED, we need to provide + a lowercase file name, but we leave the .frm in mixed case. + */ + if (lower_case_table_names == 2 && file && + !(file->ha_table_flags() & HA_FILE_BASED)) + { + strmov(tmp_name, old_name); + my_casedn_str(files_charset_info, tmp_name); + build_table_filename(lc_from, sizeof(lc_from) - 1, old_db, tmp_name, "", + flags & FN_FROM_IS_TMP); + from_base= lc_from; + + strmov(tmp_name, new_name); + my_casedn_str(files_charset_info, tmp_name); + build_table_filename(lc_to, sizeof(lc_to) - 1, new_db, tmp_name, "", + flags & FN_TO_IS_TMP); + to_base= lc_to; + } + + if (!file || !(error=file->ha_rename_table(from_base, to_base))) + { + if (!(flags & NO_FRM_RENAME) && rename_file_ext(from,to,reg_ext)) + { + error=my_errno; + /* Restore old file name */ + if (file) + file->ha_rename_table(to_base, from_base); + } + } + delete file; + if (error == HA_ERR_WRONG_COMMAND) + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "ALTER TABLE"); + else if (error) + my_error(ER_ERROR_ON_RENAME, MYF(0), from, to, error); + DBUG_RETURN(error != 0); +} + + +/* + Force all other threads to stop using the table + + SYNOPSIS + wait_while_table_is_used() + thd Thread handler + table Table to remove from cache + function HA_EXTRA_PREPARE_FOR_DROP if table is to be deleted + HA_EXTRA_FORCE_REOPEN if table is not be used + HA_EXTRA_PREPARE_FOR_RENAME if table is to be renamed + NOTES + When returning, the table will be unusable for other threads until + the table is closed. + + PREREQUISITES + Lock on LOCK_open + Win32 clients must also have a WRITE LOCK on the table ! +*/ + +void wait_while_table_is_used(THD *thd, TABLE *table, + enum ha_extra_function function) +{ + DBUG_ENTER("wait_while_table_is_used"); + DBUG_PRINT("enter", ("table: '%s' share: 0x%lx db_stat: %u version: %lu", + table->s->table_name.str, (ulong) table->s, + table->db_stat, table->s->version)); + + safe_mutex_assert_owner(&LOCK_open); + + VOID(table->file->extra(function)); + /* Mark all tables that are in use as 'old' */ + mysql_lock_abort(thd, table, TRUE); /* end threads waiting on lock */ + + /* Wait until all there are no other threads that has this table open */ + remove_table_from_cache(thd, table->s->db.str, + table->s->table_name.str, + RTFC_WAIT_OTHER_THREAD_FLAG); + DBUG_VOID_RETURN; +} + +/* + Close a cached table + + SYNOPSIS + close_cached_table() + thd Thread handler + table Table to remove from cache + + NOTES + Function ends by signaling threads waiting for the table to try to + reopen the table. + + PREREQUISITES + Lock on LOCK_open + Win32 clients must also have a WRITE LOCK on the table ! +*/ + +void close_cached_table(THD *thd, TABLE *table) +{ + DBUG_ENTER("close_cached_table"); + + wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN); + /* Close lock if this is not got with LOCK TABLES */ + if (thd->lock) + { + mysql_unlock_tables(thd, thd->lock); + thd->lock=0; // Start locked threads + } + /* Close all copies of 'table'. This also frees all LOCK TABLES lock */ + unlink_open_table(thd, table, TRUE); + + /* When lock on LOCK_open is freed other threads can continue */ + broadcast_refresh(); + DBUG_VOID_RETURN; +} + +static int send_check_errmsg(THD *thd, TABLE_LIST* table, + const char* operator_name, const char* errmsg) + +{ + Protocol *protocol= thd->protocol; + protocol->prepare_for_resend(); + protocol->store(table->alias, system_charset_info); + protocol->store((char*) operator_name, system_charset_info); + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + protocol->store(errmsg, system_charset_info); + thd->clear_error(); + if (protocol->write()) + return -1; + return 1; +} + + +static int prepare_for_restore(THD* thd, TABLE_LIST* table, + HA_CHECK_OPT *check_opt) +{ + DBUG_ENTER("prepare_for_restore"); + + if (table->table) // do not overwrite existing tables on restore + { + DBUG_RETURN(send_check_errmsg(thd, table, "restore", + "table exists, will not overwrite on restore" + )); + } + else + { + char* backup_dir= thd->lex->backup_dir; + char src_path[FN_REFLEN], dst_path[FN_REFLEN + 1], uname[FN_REFLEN]; + char* table_name= table->table_name; + char* db= table->db; + + VOID(tablename_to_filename(table->table_name, uname, sizeof(uname) - 1)); + + if (fn_format_relative_to_data_home(src_path, uname, backup_dir, reg_ext)) + DBUG_RETURN(-1); // protect buffer overflow + + build_table_filename(dst_path, sizeof(dst_path) - 1, + db, table_name, reg_ext, 0); + + if (lock_and_wait_for_table_name(thd,table)) + DBUG_RETURN(-1); + + if (my_copy(src_path, dst_path, MYF(MY_WME))) + { + pthread_mutex_lock(&LOCK_open); + unlock_table_name(thd, table); + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(send_check_errmsg(thd, table, "restore", + "Failed copying .frm file")); + } + if (mysql_truncate(thd, table, 1)) + { + pthread_mutex_lock(&LOCK_open); + unlock_table_name(thd, table); + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(send_check_errmsg(thd, table, "restore", + "Failed generating table from .frm file")); + } + } + + /* + Now we should be able to open the partially restored table + to finish the restore in the handler later on + */ + pthread_mutex_lock(&LOCK_open); + if (reopen_name_locked_table(thd, table, TRUE)) + { + unlock_table_name(thd, table); + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(send_check_errmsg(thd, table, "restore", + "Failed to open partially restored table")); + } + /* A MERGE table must not come here. */ + DBUG_ASSERT(!table->table || !table->table->child_l); + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(0); +} + + +static int prepare_for_repair(THD *thd, TABLE_LIST *table_list, + HA_CHECK_OPT *check_opt) +{ + int error= 0; + TABLE tmp_table, *table; + TABLE_SHARE *share; + char from[FN_REFLEN],tmp[FN_REFLEN+32]; + const char **ext; + MY_STAT stat_info; + DBUG_ENTER("prepare_for_repair"); + + if (!(check_opt->sql_flags & TT_USEFRM)) + DBUG_RETURN(0); + + if (!(table= table_list->table)) /* if open_ltable failed */ + { + char key[MAX_DBKEY_LENGTH]; + uint key_length; + + key_length= create_table_def_key(thd, key, table_list, 0); + pthread_mutex_lock(&LOCK_open); + if (!(share= (get_table_share(thd, table_list, key, key_length, 0, + &error)))) + { + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(0); // Can't open frm file + } + + if (open_table_from_share(thd, share, "", 0, 0, 0, &tmp_table, FALSE)) + { + release_table_share(share, RELEASE_NORMAL); + pthread_mutex_unlock(&LOCK_open); + DBUG_RETURN(0); // Out of memory + } + table= &tmp_table; + pthread_mutex_unlock(&LOCK_open); + } + + /* A MERGE table must not come here. */ + DBUG_ASSERT(!table->child_l); + + /* + REPAIR TABLE ... USE_FRM for temporary tables makes little sense. + */ + if (table->s->tmp_table) + { + error= send_check_errmsg(thd, table_list, "repair", + "Cannot repair temporary table from .frm file"); + goto end; + } + + /* + User gave us USE_FRM which means that the header in the index file is + trashed. + In this case we will try to fix the table the following way: + - Rename the data file to a temporary name + - Truncate the table + - Replace the new data file with the old one + - Run a normal repair using the new index file and the old data file + */ + + if (table->s->frm_version != FRM_VER_TRUE_VARCHAR) + { + error= send_check_errmsg(thd, table_list, "repair", + "Failed repairing incompatible .frm file"); + goto end; + } + + /* + Check if this is a table type that stores index and data separately, + like ISAM or MyISAM. We assume fixed order of engine file name + extentions array. First element of engine file name extentions array + is meta/index file extention. Second element - data file extention. + */ + ext= table->file->bas_ext(); + if (!ext[0] || !ext[1]) + goto end; // No data file + + // Name of data file + strxmov(from, table->s->normalized_path.str, ext[1], NullS); + if (!my_stat(from, &stat_info, MYF(0))) + goto end; // Can't use USE_FRM flag + + my_snprintf(tmp, sizeof(tmp), "%s-%lx_%lx", + from, current_pid, thd->thread_id); + + /* If we could open the table, close it */ + if (table_list->table) + { + pthread_mutex_lock(&LOCK_open); + close_cached_table(thd, table); + pthread_mutex_unlock(&LOCK_open); + } + if (lock_and_wait_for_table_name(thd,table_list)) + { + error= -1; + goto end; + } + if (my_rename(from, tmp, MYF(MY_WME))) + { + pthread_mutex_lock(&LOCK_open); + unlock_table_name(thd, table_list); + pthread_mutex_unlock(&LOCK_open); + error= send_check_errmsg(thd, table_list, "repair", + "Failed renaming data file"); + goto end; + } + if (mysql_truncate(thd, table_list, 1)) + { + pthread_mutex_lock(&LOCK_open); + unlock_table_name(thd, table_list); + pthread_mutex_unlock(&LOCK_open); + error= send_check_errmsg(thd, table_list, "repair", + "Failed generating table from .frm file"); + goto end; + } + if (my_rename(tmp, from, MYF(MY_WME))) + { + pthread_mutex_lock(&LOCK_open); + unlock_table_name(thd, table_list); + pthread_mutex_unlock(&LOCK_open); + error= send_check_errmsg(thd, table_list, "repair", + "Failed restoring .MYD file"); + goto end; + } + + /* + Now we should be able to open the partially repaired table + to finish the repair in the handler later on. + */ + pthread_mutex_lock(&LOCK_open); + if (reopen_name_locked_table(thd, table_list, TRUE)) + { + unlock_table_name(thd, table_list); + pthread_mutex_unlock(&LOCK_open); + error= send_check_errmsg(thd, table_list, "repair", + "Failed to open partially repaired table"); + goto end; + } + pthread_mutex_unlock(&LOCK_open); + +end: + if (table == &tmp_table) + { + pthread_mutex_lock(&LOCK_open); + closefrm(table, 1); // Free allocated memory + pthread_mutex_unlock(&LOCK_open); + } + DBUG_RETURN(error); +} + + + +/* + RETURN VALUES + FALSE Message sent to net (admin operation went ok) + TRUE Message should be sent by caller + (admin operation or network communication failed) +*/ +static bool mysql_admin_table(THD* thd, TABLE_LIST* tables, + HA_CHECK_OPT* check_opt, + const char *operator_name, + thr_lock_type lock_type, + bool open_for_modify, + bool no_warnings_for_error, + uint extra_open_options, + int (*prepare_func)(THD *, TABLE_LIST *, + HA_CHECK_OPT *), + int (handler::*operator_func)(THD *, + HA_CHECK_OPT *), + int (view_operator_func)(THD *, TABLE_LIST*)) +{ + TABLE_LIST *table; + SELECT_LEX *select= &thd->lex->select_lex; + List field_list; + Item *item; + Protocol *protocol= thd->protocol; + LEX *lex= thd->lex; + int result_code; + DBUG_ENTER("mysql_admin_table"); + + if (end_active_trans(thd)) + DBUG_RETURN(1); + field_list.push_back(item = new Item_empty_string("Table", NAME_CHAR_LEN*2)); + item->maybe_null = 1; + field_list.push_back(item = new Item_empty_string("Op", 10)); + item->maybe_null = 1; + field_list.push_back(item = new Item_empty_string("Msg_type", 10)); + item->maybe_null = 1; + field_list.push_back(item = new Item_empty_string("Msg_text", 255)); + item->maybe_null = 1; + if (protocol->send_fields(&field_list, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) + DBUG_RETURN(TRUE); + + mysql_ha_rm_tables(thd, tables, FALSE); + + for (table= tables; table; table= table->next_local) + { + char table_name[NAME_LEN*2+2]; + char* db = table->db; + bool fatal_error=0; + + DBUG_PRINT("admin", ("table: '%s'.'%s'", table->db, table->table_name)); + DBUG_PRINT("admin", ("extra_open_options: %u", extra_open_options)); + strxmov(table_name, db, ".", table->table_name, NullS); + thd->open_options|= extra_open_options; + table->lock_type= lock_type; + /* open only one table from local list of command */ + { + TABLE_LIST *save_next_global, *save_next_local; + save_next_global= table->next_global; + table->next_global= 0; + save_next_local= table->next_local; + table->next_local= 0; + select->table_list.first= (uchar*)table; + /* + Time zone tables and SP tables can be add to lex->query_tables list, + so it have to be prepared. + TODO: Investigate if we can put extra tables into argument instead of + using lex->query_tables + */ + lex->query_tables= table; + lex->query_tables_last= &table->next_global; + lex->query_tables_own_last= 0; + thd->no_warnings_for_error= no_warnings_for_error; + if (view_operator_func == NULL) + table->required_type=FRMTYPE_TABLE; + + open_and_lock_tables(thd, table); + thd->no_warnings_for_error= 0; + table->next_global= save_next_global; + table->next_local= save_next_local; + thd->open_options&= ~extra_open_options; +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (table->table) + { + /* + Set up which partitions that should be processed + if ALTER TABLE t ANALYZE/CHECK/OPTIMIZE/REPAIR PARTITION .. + */ + Alter_info *alter_info= &lex->alter_info; + + if (alter_info->flags & ALTER_ADMIN_PARTITION) + { + if (!table->table->part_info) + { + my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0)); + DBUG_RETURN(TRUE); + } + uint no_parts_found; + uint no_parts_opt= alter_info->partition_names.elements; + no_parts_found= set_part_state(alter_info, table->table->part_info, + PART_CHANGED); + if (no_parts_found != no_parts_opt && + (!(alter_info->flags & ALTER_ALL_PARTITION))) + { + char buff[FN_REFLEN + MYSQL_ERRMSG_SIZE]; + size_t length; + DBUG_PRINT("admin", ("sending non existent partition error")); + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store(operator_name, system_charset_info); + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + length= my_snprintf(buff, sizeof(buff), + ER(ER_DROP_PARTITION_NON_EXISTENT), + table_name); + protocol->store(buff, length, system_charset_info); + if(protocol->write()) + goto err; + my_eof(thd); + goto err; + } + } + } +#endif + } + DBUG_PRINT("admin", ("table: 0x%lx", (long) table->table)); + + if (prepare_func) + { + DBUG_PRINT("admin", ("calling prepare_func")); + switch ((*prepare_func)(thd, table, check_opt)) { + case 1: // error, message written to net + ha_autocommit_or_rollback(thd, 1); + end_trans(thd, ROLLBACK); + close_thread_tables(thd); + DBUG_PRINT("admin", ("simple error, admin next table")); + continue; + case -1: // error, message could be written to net + /* purecov: begin inspected */ + DBUG_PRINT("admin", ("severe error, stop")); + goto err; + /* purecov: end */ + default: // should be 0 otherwise + DBUG_PRINT("admin", ("prepare_func succeeded")); + ; + } + } + + /* + CHECK TABLE command is only command where VIEW allowed here and this + command use only temporary teble method for VIEWs resolving => there + can't be VIEW tree substitition of join view => if opening table + succeed then table->table will have real TABLE pointer as value (in + case of join view substitution table->table can be 0, but here it is + impossible) + */ + if (!table->table) + { + DBUG_PRINT("admin", ("open table failed")); + if (!thd->warn_list.elements) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_CHECK_NO_SUCH_TABLE, ER(ER_CHECK_NO_SUCH_TABLE)); + /* if it was a view will check md5 sum */ + if (table->view && + view_checksum(thd, table) == HA_ADMIN_WRONG_CHECKSUM) + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + ER_VIEW_CHECKSUM, ER(ER_VIEW_CHECKSUM)); + if (thd->main_da.is_error() && + (thd->main_da.sql_errno() == ER_NO_SUCH_TABLE || + thd->main_da.sql_errno() == ER_FILE_NOT_FOUND)) + /* A missing table is just issued as a failed command */ + result_code= HA_ADMIN_FAILED; + else + /* Default failure code is corrupt table */ + result_code= HA_ADMIN_CORRUPT; + goto send_result; + } + + if (table->view) + { + DBUG_PRINT("admin", ("calling view_operator_func")); + result_code= (*view_operator_func)(thd, table); + goto send_result; + } + + if (table->schema_table) + { + result_code= HA_ADMIN_NOT_IMPLEMENTED; + goto send_result; + } + + if ((table->table->db_stat & HA_READ_ONLY) && open_for_modify) + { + /* purecov: begin inspected */ + char buff[FN_REFLEN + MYSQL_ERRMSG_SIZE]; + size_t length; + DBUG_PRINT("admin", ("sending error message")); + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store(operator_name, system_charset_info); + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + length= my_snprintf(buff, sizeof(buff), ER(ER_OPEN_AS_READONLY), + table_name); + protocol->store(buff, length, system_charset_info); + ha_autocommit_or_rollback(thd, 0); + end_trans(thd, COMMIT); + close_thread_tables(thd); + lex->reset_query_tables_list(FALSE); + table->table=0; // For query cache + if (protocol->write()) + goto err; + thd->main_da.reset_diagnostics_area(); + continue; + /* purecov: end */ + } + + /* Close all instances of the table to allow repair to rename files */ + if (lock_type == TL_WRITE && table->table->s->version) + { + DBUG_PRINT("admin", ("removing table from cache")); + pthread_mutex_lock(&LOCK_open); + const char *old_message=thd->enter_cond(&COND_refresh, &LOCK_open, + "Waiting to get writelock"); + mysql_lock_abort(thd,table->table, TRUE); + remove_table_from_cache(thd, table->table->s->db.str, + table->table->s->table_name.str, + RTFC_WAIT_OTHER_THREAD_FLAG | + RTFC_CHECK_KILLED_FLAG); + thd->exit_cond(old_message); + DBUG_EXECUTE_IF("wait_in_mysql_admin_table", wait_for_kill_signal(thd);); + if (thd->killed) + goto err; + /* Flush entries in the query cache involving this table. */ + query_cache_invalidate3(thd, table->table, 0); + open_for_modify= 0; + } + + if (table->table->s->crashed && operator_func == &handler::ha_check) + { + /* purecov: begin inspected */ + DBUG_PRINT("admin", ("sending crashed warning")); + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store(operator_name, system_charset_info); + protocol->store(STRING_WITH_LEN("warning"), system_charset_info); + protocol->store(STRING_WITH_LEN("Table is marked as crashed"), + system_charset_info); + if (protocol->write()) + goto err; + /* purecov: end */ + } + + if (operator_func == &handler::ha_repair && + !(check_opt->sql_flags & TT_USEFRM)) + { + if ((table->table->file->check_old_types() == HA_ADMIN_NEEDS_ALTER) || + (table->table->file->ha_check_for_upgrade(check_opt) == + HA_ADMIN_NEEDS_ALTER)) + { + DBUG_PRINT("admin", ("recreating table")); + ha_autocommit_or_rollback(thd, 1); + close_thread_tables(thd); + tmp_disable_binlog(thd); // binlogging is done by caller if wanted + result_code= mysql_recreate_table(thd, table); + reenable_binlog(thd); + /* + mysql_recreate_table() can push OK or ERROR. + Clear 'OK' status. If there is an error, keep it: + we will store the error message in a result set row + and then clear. + */ + if (thd->main_da.is_ok()) + thd->main_da.reset_diagnostics_area(); + goto send_result; + } + } + + DBUG_PRINT("admin", ("calling operator_func '%s'", operator_name)); + result_code = (table->table->file->*operator_func)(thd, check_opt); + DBUG_PRINT("admin", ("operator_func returned: %d", result_code)); + +send_result: + + lex->cleanup_after_one_table_open(); + thd->clear_error(); // these errors shouldn't get client + { + List_iterator_fast it(thd->warn_list); + MYSQL_ERROR *err; + while ((err= it++)) + { + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store((char*) operator_name, system_charset_info); + protocol->store(warning_level_names[err->level].str, + warning_level_names[err->level].length, + system_charset_info); + protocol->store(err->msg, system_charset_info); + if (protocol->write()) + goto err; + } + mysql_reset_errors(thd, true); + } + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store(operator_name, system_charset_info); + +send_result_message: + + DBUG_PRINT("info", ("result_code: %d", result_code)); + switch (result_code) { + case HA_ADMIN_NOT_IMPLEMENTED: + { + char buf[MYSQL_ERRMSG_SIZE]; + size_t length=my_snprintf(buf, sizeof(buf), + ER(ER_CHECK_NOT_IMPLEMENTED), operator_name); + protocol->store(STRING_WITH_LEN("note"), system_charset_info); + protocol->store(buf, length, system_charset_info); + } + break; + + case HA_ADMIN_NOT_BASE_TABLE: + { + char buf[MYSQL_ERRMSG_SIZE]; + size_t length= my_snprintf(buf, sizeof(buf), + ER(ER_BAD_TABLE_ERROR), table_name); + protocol->store(STRING_WITH_LEN("note"), system_charset_info); + protocol->store(buf, length, system_charset_info); + } + break; + + case HA_ADMIN_OK: + protocol->store(STRING_WITH_LEN("status"), system_charset_info); + protocol->store(STRING_WITH_LEN("OK"), system_charset_info); + break; + + case HA_ADMIN_FAILED: + protocol->store(STRING_WITH_LEN("status"), system_charset_info); + protocol->store(STRING_WITH_LEN("Operation failed"), + system_charset_info); + break; + + case HA_ADMIN_REJECT: + protocol->store(STRING_WITH_LEN("status"), system_charset_info); + protocol->store(STRING_WITH_LEN("Operation need committed state"), + system_charset_info); + open_for_modify= FALSE; + break; + + case HA_ADMIN_ALREADY_DONE: + protocol->store(STRING_WITH_LEN("status"), system_charset_info); + protocol->store(STRING_WITH_LEN("Table is already up to date"), + system_charset_info); + break; + + case HA_ADMIN_CORRUPT: + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + protocol->store(STRING_WITH_LEN("Corrupt"), system_charset_info); + fatal_error=1; + break; + + case HA_ADMIN_INVALID: + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + protocol->store(STRING_WITH_LEN("Invalid argument"), + system_charset_info); + break; + + case HA_ADMIN_TRY_ALTER: + { + /* + This is currently used only by InnoDB. ha_innobase::optimize() answers + "try with alter", so here we close the table, do an ALTER TABLE, + reopen the table and do ha_innobase::analyze() on it. + We have to end the row, so analyze could return more rows. + */ + protocol->store(STRING_WITH_LEN("note"), system_charset_info); + protocol->store(STRING_WITH_LEN( + "Table does not support optimize, doing recreate + analyze instead"), + system_charset_info); + if (protocol->write()) + goto err; + ha_autocommit_or_rollback(thd, 0); + close_thread_tables(thd); + DBUG_PRINT("info", ("HA_ADMIN_TRY_ALTER, trying analyze...")); + TABLE_LIST *save_next_local= table->next_local, + *save_next_global= table->next_global; + table->next_local= table->next_global= 0; + tmp_disable_binlog(thd); // binlogging is done by caller if wanted + result_code= mysql_recreate_table(thd, table); + reenable_binlog(thd); + /* + mysql_recreate_table() can push OK or ERROR. + Clear 'OK' status. If there is an error, keep it: + we will store the error message in a result set row + and then clear. + */ + if (thd->main_da.is_ok()) + thd->main_da.reset_diagnostics_area(); + ha_autocommit_or_rollback(thd, 0); + close_thread_tables(thd); + if (!result_code) // recreation went ok + { + if ((table->table= open_ltable(thd, table, lock_type, 0)) && + ((result_code= table->table->file->ha_analyze(thd, check_opt)) > 0)) + result_code= 0; // analyze went ok + } + /* Start a new row for the final status row */ + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store(operator_name, system_charset_info); + if (result_code) // either mysql_recreate_table or analyze failed + { + DBUG_ASSERT(thd->is_error()); + if (thd->is_error()) + { + const char *err_msg= thd->main_da.message(); + if (!thd->vio_ok()) + { + sql_print_error("%s", err_msg); + } + else + { + /* Hijack the row already in-progress. */ + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + protocol->store(err_msg, system_charset_info); + if (protocol->write()) + goto err; + /* Start off another row for HA_ADMIN_FAILED */ + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + protocol->store(operator_name, system_charset_info); + } + thd->clear_error(); + } + } + result_code= result_code ? HA_ADMIN_FAILED : HA_ADMIN_OK; + table->next_local= save_next_local; + table->next_global= save_next_global; + goto send_result_message; + } + case HA_ADMIN_WRONG_CHECKSUM: + { + protocol->store(STRING_WITH_LEN("note"), system_charset_info); + protocol->store(ER(ER_VIEW_CHECKSUM), strlen(ER(ER_VIEW_CHECKSUM)), + system_charset_info); + break; + } + + case HA_ADMIN_NEEDS_UPGRADE: + case HA_ADMIN_NEEDS_ALTER: + { + char buf[MYSQL_ERRMSG_SIZE]; + size_t length; + + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + length=my_snprintf(buf, sizeof(buf), ER(ER_TABLE_NEEDS_UPGRADE), + table->table_name); + protocol->store(buf, length, system_charset_info); + fatal_error=1; + break; + } + + default: // Probably HA_ADMIN_INTERNAL_ERROR + { + char buf[MYSQL_ERRMSG_SIZE]; + size_t length=my_snprintf(buf, sizeof(buf), + "Unknown - internal error %d during operation", + result_code); + protocol->store(STRING_WITH_LEN("error"), system_charset_info); + protocol->store(buf, length, system_charset_info); + fatal_error=1; + break; + } + } + if (table->table) + { + if (fatal_error) + table->table->s->version=0; // Force close of table + else if (open_for_modify) + { + if (table->table->s->tmp_table) + table->table->file->info(HA_STATUS_CONST); + else + { + pthread_mutex_lock(&LOCK_open); + remove_table_from_cache(thd, table->table->s->db.str, + table->table->s->table_name.str, RTFC_NO_FLAG); + pthread_mutex_unlock(&LOCK_open); + } + /* May be something modified consequently we have to invalidate cache */ + query_cache_invalidate3(thd, table->table, 0); + } + } + ha_autocommit_or_rollback(thd, 0); + end_trans(thd, COMMIT); + close_thread_tables(thd); + table->table=0; // For query cache + if (protocol->write()) + goto err; + } + + my_eof(thd); + DBUG_RETURN(FALSE); + +err: + ha_autocommit_or_rollback(thd, 1); + end_trans(thd, ROLLBACK); + close_thread_tables(thd); // Shouldn't be needed + if (table) + table->table=0; + DBUG_RETURN(TRUE); +} + + +bool mysql_backup_table(THD* thd, TABLE_LIST* table_list) +{ + DBUG_ENTER("mysql_backup_table"); + WARN_DEPRECATED(thd, "6.0", "BACKUP TABLE", + "MySQL Administrator (mysqldump, mysql)"); + DBUG_RETURN(mysql_admin_table(thd, table_list, 0, + "backup", TL_READ, 0, 0, 0, 0, + &handler::ha_backup, 0)); +} + + +bool mysql_restore_table(THD* thd, TABLE_LIST* table_list) +{ + DBUG_ENTER("mysql_restore_table"); + WARN_DEPRECATED(thd, "6.0", "RESTORE TABLE", + "MySQL Administrator (mysqldump, mysql)"); + DBUG_RETURN(mysql_admin_table(thd, table_list, 0, + "restore", TL_WRITE, 1, 1, 0, + &prepare_for_restore, + &handler::ha_restore, 0)); +} + + +bool mysql_repair_table(THD* thd, TABLE_LIST* tables, HA_CHECK_OPT* check_opt) +{ + DBUG_ENTER("mysql_repair_table"); + DBUG_RETURN(mysql_admin_table(thd, tables, check_opt, + "repair", TL_WRITE, 1, + test(check_opt->sql_flags & TT_USEFRM), + HA_OPEN_FOR_REPAIR, + &prepare_for_repair, + &handler::ha_repair, 0)); +} + + +bool mysql_optimize_table(THD* thd, TABLE_LIST* tables, HA_CHECK_OPT* check_opt) +{ + DBUG_ENTER("mysql_optimize_table"); + DBUG_RETURN(mysql_admin_table(thd, tables, check_opt, + "optimize", TL_WRITE, 1,0,0,0, + &handler::ha_optimize, 0)); +} + + +/* + Assigned specified indexes for a table into key cache + + SYNOPSIS + mysql_assign_to_keycache() + thd Thread object + tables Table list (one table only) + + RETURN VALUES + FALSE ok + TRUE error +*/ + +bool mysql_assign_to_keycache(THD* thd, TABLE_LIST* tables, + LEX_STRING *key_cache_name) +{ + HA_CHECK_OPT check_opt; + KEY_CACHE *key_cache; + DBUG_ENTER("mysql_assign_to_keycache"); + + check_opt.init(); + pthread_mutex_lock(&LOCK_global_system_variables); + if (!(key_cache= get_key_cache(key_cache_name))) + { + pthread_mutex_unlock(&LOCK_global_system_variables); + my_error(ER_UNKNOWN_KEY_CACHE, MYF(0), key_cache_name->str); + DBUG_RETURN(TRUE); + } + pthread_mutex_unlock(&LOCK_global_system_variables); + check_opt.key_cache= key_cache; + DBUG_RETURN(mysql_admin_table(thd, tables, &check_opt, + "assign_to_keycache", TL_READ_NO_INSERT, 0, 0, + 0, 0, &handler::assign_to_keycache, 0)); +} + + +/* + Reassign all tables assigned to a key cache to another key cache + + SYNOPSIS + reassign_keycache_tables() + thd Thread object + src_cache Reference to the key cache to clean up + dest_cache New key cache + + NOTES + This is called when one sets a key cache size to zero, in which + case we have to move the tables associated to this key cache to + the "default" one. + + One has to ensure that one never calls this function while + some other thread is changing the key cache. This is assured by + the caller setting src_cache->in_init before calling this function. + + We don't delete the old key cache as there may still be pointers pointing + to it for a while after this function returns. + + RETURN VALUES + 0 ok +*/ + +int reassign_keycache_tables(THD *thd, KEY_CACHE *src_cache, + KEY_CACHE *dst_cache) +{ + DBUG_ENTER("reassign_keycache_tables"); + + DBUG_ASSERT(src_cache != dst_cache); + DBUG_ASSERT(src_cache->in_init); + src_cache->param_buff_size= 0; // Free key cache + ha_resize_key_cache(src_cache); + ha_change_key_cache(src_cache, dst_cache); + DBUG_RETURN(0); +} + + +/* + Preload specified indexes for a table into key cache + + SYNOPSIS + mysql_preload_keys() + thd Thread object + tables Table list (one table only) + + RETURN VALUES + FALSE ok + TRUE error +*/ + +bool mysql_preload_keys(THD* thd, TABLE_LIST* tables) +{ + DBUG_ENTER("mysql_preload_keys"); + /* + We cannot allow concurrent inserts. The storage engine reads + directly from the index file, bypassing the cache. It could read + outdated information if parallel inserts into cache blocks happen. + */ + DBUG_RETURN(mysql_admin_table(thd, tables, 0, + "preload_keys", TL_READ_NO_INSERT, 0, 0, 0, 0, + &handler::preload_keys, 0)); +} + + + +/** + @brief Create frm file based on I_S table + + @param[in] thd thread handler + @param[in] schema_table I_S table + @param[in] dst_path path where frm should be created + @param[in] create_info Create info + + @return Operation status + @retval 0 success + @retval 1 error +*/ + + +bool mysql_create_like_schema_frm(THD* thd, TABLE_LIST* schema_table, + char *dst_path, HA_CREATE_INFO *create_info) +{ + HA_CREATE_INFO local_create_info; + Alter_info alter_info; + bool tmp_table= (create_info->options & HA_LEX_CREATE_TMP_TABLE); + uint keys= schema_table->table->s->keys; + uint db_options= 0; + DBUG_ENTER("mysql_create_like_schema_frm"); + + bzero((char*) &local_create_info, sizeof(local_create_info)); + local_create_info.db_type= schema_table->table->s->db_type(); + local_create_info.row_type= schema_table->table->s->row_type; + local_create_info.default_table_charset=default_charset_info; + alter_info.flags= (ALTER_CHANGE_COLUMN | ALTER_RECREATE); + schema_table->table->use_all_columns(); + if (mysql_prepare_alter_table(thd, schema_table->table, + &local_create_info, &alter_info)) + DBUG_RETURN(1); + if (mysql_prepare_create_table(thd, &local_create_info, &alter_info, + tmp_table, &db_options, + schema_table->table->file, + &schema_table->table->s->key_info, &keys, 0)) + DBUG_RETURN(1); + local_create_info.max_rows= 0; + if (mysql_create_frm(thd, dst_path, NullS, NullS, + &local_create_info, alter_info.create_list, + keys, schema_table->table->s->key_info, + schema_table->table->file)) + DBUG_RETURN(1); + DBUG_RETURN(0); +} + + +/* + Create a table identical to the specified table + + SYNOPSIS + mysql_create_like_table() + thd Thread object + table Table list element for target table + src_table Table list element for source table + create_info Create info + + RETURN VALUES + FALSE OK + TRUE error +*/ + +bool mysql_create_like_table(THD* thd, TABLE_LIST* table, TABLE_LIST* src_table, + HA_CREATE_INFO *create_info) +{ + TABLE *name_lock= 0; + char src_path[FN_REFLEN], dst_path[FN_REFLEN + 1]; + uint dst_path_length; + char *db= table->db; + char *table_name= table->table_name; + int err; + bool res= TRUE; + uint not_used; +#ifdef WITH_PARTITION_STORAGE_ENGINE + char tmp_path[FN_REFLEN]; +#endif + char ts_name[FN_LEN + 1]; + DBUG_ENTER("mysql_create_like_table"); + + + /* + By opening source table we guarantee that it exists and no concurrent + DDL operation will mess with it. Later we also take an exclusive + name-lock on target table name, which makes copying of .frm file, + call to ha_create_table() and binlogging atomic against concurrent DML + and DDL operations on target table. Thus by holding both these "locks" + we ensure that our statement is properly isolated from all concurrent + operations which matter. + */ + if (open_tables(thd, &src_table, ¬_used, 0)) + DBUG_RETURN(TRUE); + + /* + For bug#25875, Newly created table through CREATE TABLE .. LIKE + has no ndb_dd attributes; + Add something to get possible tablespace info from src table, + it can get valid tablespace name only for disk-base ndb table + */ + if ((src_table->table->file->get_tablespace_name(thd, ts_name, FN_LEN))) + { + create_info->tablespace= ts_name; + create_info->storage_media= HA_SM_DISK; + } + + strxmov(src_path, src_table->table->s->path.str, reg_ext, NullS); + + DBUG_EXECUTE_IF("sleep_create_like_before_check_if_exists", my_sleep(6000000);); + + /* + Check that destination tables does not exist. Note that its name + was already checked when it was added to the table list. + */ + if (create_info->options & HA_LEX_CREATE_TMP_TABLE) + { + if (find_temporary_table(thd, db, table_name)) + goto table_exists; + dst_path_length= build_tmptable_filename(thd, dst_path, sizeof(dst_path)); + create_info->table_options|= HA_CREATE_DELAY_KEY_WRITE; + } + else + { + if (lock_table_name_if_not_cached(thd, db, table_name, &name_lock)) + goto err; + if (!name_lock) + goto table_exists; + dst_path_length= build_table_filename(dst_path, sizeof(dst_path) - 1, + db, table_name, reg_ext, 0); + if (!access(dst_path, F_OK)) + goto table_exists; + } + + DBUG_EXECUTE_IF("sleep_create_like_before_copy", my_sleep(6000000);); + + /* + Create a new table by copying from source table + + Altough exclusive name-lock on target table protects us from concurrent + DML and DDL operations on it we still want to wrap .FRM creation and call + to ha_create_table() in critical section protected by LOCK_open in order + to provide minimal atomicity against operations which disregard name-locks, + like I_S implementation, for example. This is a temporary and should not + be copied. Instead we should fix our code to always honor name-locks. + + Also some engines (e.g. NDB cluster) require that LOCK_open should be held + during the call to ha_create_table(). See bug #28614 for more info. + */ + VOID(pthread_mutex_lock(&LOCK_open)); + if (src_table->schema_table) + { + if (mysql_create_like_schema_frm(thd, src_table, dst_path, create_info)) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + goto err; + } + } + else if (my_copy(src_path, dst_path, MYF(MY_DONT_OVERWRITE_FILE))) + { + if (my_errno == ENOENT) + my_error(ER_BAD_DB_ERROR,MYF(0),db); + else + my_error(ER_CANT_CREATE_FILE,MYF(0),dst_path,my_errno); + VOID(pthread_mutex_unlock(&LOCK_open)); + goto err; + } + + /* + As mysql_truncate don't work on a new table at this stage of + creation, instead create the table directly (for both normal + and temporary tables). + */ +#ifdef WITH_PARTITION_STORAGE_ENGINE + /* + For partitioned tables we need to copy the .par file as well since + it is used in open_table_def to even be able to create a new handler. + There is no way to find out here if the original table is a + partitioned table so we copy the file and ignore any errors. + */ + fn_format(tmp_path, dst_path, reg_ext, ".par", MYF(MY_REPLACE_EXT)); + strmov(dst_path, tmp_path); + fn_format(tmp_path, src_path, reg_ext, ".par", MYF(MY_REPLACE_EXT)); + strmov(src_path, tmp_path); + my_copy(src_path, dst_path, MYF(MY_DONT_OVERWRITE_FILE)); +#endif + + DBUG_EXECUTE_IF("sleep_create_like_before_ha_create", my_sleep(6000000);); + + dst_path[dst_path_length - reg_ext_length]= '\0'; // Remove .frm + if (thd->variables.keep_files_on_create) + create_info->options|= HA_CREATE_KEEP_FILES; + err= ha_create_table(thd, dst_path, db, table_name, create_info, 1); + VOID(pthread_mutex_unlock(&LOCK_open)); + + if (create_info->options & HA_LEX_CREATE_TMP_TABLE) + { + if (err || !open_temporary_table(thd, dst_path, db, table_name, 1)) + { + (void) rm_temporary_table(create_info->db_type, + dst_path); /* purecov: inspected */ + goto err; /* purecov: inspected */ + } + thd->thread_specific_used= TRUE; + } + else if (err) + { + (void) quick_rm_table(create_info->db_type, db, + table_name, 0); /* purecov: inspected */ + goto err; /* purecov: inspected */ + } + +goto binlog; + +table_exists: + if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS) + { + char warn_buff[MYSQL_ERRMSG_SIZE]; + my_snprintf(warn_buff, sizeof(warn_buff), + ER(ER_TABLE_EXISTS_ERROR), table_name); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_TABLE_EXISTS_ERROR,warn_buff); + } + else + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), table_name); + goto err; + } + +binlog: + DBUG_EXECUTE_IF("sleep_create_like_before_binlogging", my_sleep(6000000);); + + /* + We have to write the query before we unlock the tables. + */ + if (thd->current_stmt_binlog_row_based) + { + /* + Since temporary tables are not replicated under row-based + replication, CREATE TABLE ... LIKE ... needs special + treatement. We have four cases to consider, according to the + following decision table: + + ==== ========= ========= ============================== + Case Target Source Write to binary log + ==== ========= ========= ============================== + 1 normal normal Original statement + 2 normal temporary Generated statement + 3 temporary normal Nothing + 4 temporary temporary Nothing + ==== ========= ========= ============================== + */ + if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) + { + if (src_table->table->s->tmp_table) // Case 2 + { + char buf[2048]; + String query(buf, sizeof(buf), system_charset_info); + query.length(0); // Have to zero it since constructor doesn't + + /* + Here we open the destination table, on which we already have + name-lock. This is needed for store_create_info() to work. + The table will be closed by unlink_open_table() at the end + of this function. + */ + table->table= name_lock; + VOID(pthread_mutex_lock(&LOCK_open)); + if (reopen_name_locked_table(thd, table, FALSE)) + { + VOID(pthread_mutex_unlock(&LOCK_open)); + goto err; + } + VOID(pthread_mutex_unlock(&LOCK_open)); + + IF_DBUG(int result=) + store_create_info(thd, table, &query, + create_info, FALSE /* show_database */); + + DBUG_ASSERT(result == 0); // store_create_info() always return 0 + write_bin_log(thd, TRUE, query.ptr(), query.length()); + } + else // Case 1 + write_bin_log(thd, TRUE, thd->query, thd->query_length); + } + /* + Case 3 and 4 does nothing under RBR + */ + } + else + write_bin_log(thd, TRUE, thd->query, thd->query_length); + + res= FALSE; + +err: + if (name_lock) + { + pthread_mutex_lock(&LOCK_open); + unlink_open_table(thd, name_lock, FALSE); + pthread_mutex_unlock(&LOCK_open); + } + DBUG_RETURN(res); +} + + +bool mysql_analyze_table(THD* thd, TABLE_LIST* tables, HA_CHECK_OPT* check_opt) +{ + thr_lock_type lock_type = TL_READ_NO_INSERT; + + DBUG_ENTER("mysql_analyze_table"); + DBUG_RETURN(mysql_admin_table(thd, tables, check_opt, + "analyze", lock_type, 1, 0, 0, 0, + &handler::ha_analyze, 0)); +} + + +bool mysql_check_table(THD* thd, TABLE_LIST* tables,HA_CHECK_OPT* check_opt) +{ + thr_lock_type lock_type = TL_READ_NO_INSERT; + + DBUG_ENTER("mysql_check_table"); + DBUG_RETURN(mysql_admin_table(thd, tables, check_opt, + "check", lock_type, + 0, 0, HA_OPEN_FOR_REPAIR, 0, + &handler::ha_check, &view_checksum)); +} + + +/* table_list should contain just one table */ +static int +mysql_discard_or_import_tablespace(THD *thd, + TABLE_LIST *table_list, + enum tablespace_op_type tablespace_op) +{ + TABLE *table; + my_bool discard; + int error; + DBUG_ENTER("mysql_discard_or_import_tablespace"); + + /* + Note that DISCARD/IMPORT TABLESPACE always is the only operation in an + ALTER TABLE + */ + + thd_proc_info(thd, "discard_or_import_tablespace"); + + discard= test(tablespace_op == DISCARD_TABLESPACE); + + /* + We set this flag so that ha_innobase::open and ::external_lock() do + not complain when we lock the table + */ + thd->tablespace_op= TRUE; + if (!(table=open_ltable(thd, table_list, TL_WRITE, 0))) + { + thd->tablespace_op=FALSE; + DBUG_RETURN(-1); + } + + error= table->file->ha_discard_or_import_tablespace(discard); + + thd_proc_info(thd, "end"); + + if (error) + goto err; + + /* + The 0 in the call below means 'not in a transaction', which means + immediate invalidation; that is probably what we wish here + */ + query_cache_invalidate3(thd, table_list, 0); + + /* The ALTER TABLE is always in its own transaction */ + error = ha_autocommit_or_rollback(thd, 0); + if (end_active_trans(thd)) + error=1; + if (error) + goto err; + write_bin_log(thd, FALSE, thd->query, thd->query_length); + +err: + ha_autocommit_or_rollback(thd, error); + thd->tablespace_op=FALSE; + + if (error == 0) + { + my_ok(thd); + DBUG_RETURN(0); + } + + table->file->print_error(error, MYF(0)); + + DBUG_RETURN(-1); +} + + +/* + SYNOPSIS + compare_tables() + table The original table. + alter_info Alter options, fields and keys for the new + table. + create_info Create options for the new table. + order_num Number of order list elements. + need_copy_table OUT Result of the comparison. Undefined if error. + Otherwise is one of: + ALTER_TABLE_METADATA_ONLY No copy needed + ALTER_TABLE_DATA_CHANGED Data changes, + copy needed + ALTER_TABLE_INDEX_CHANGED Index changes, + copy might be needed + key_info_buffer OUT An array of KEY structs for new indexes + index_drop_buffer OUT An array of offsets into table->key_info. + index_drop_count OUT The number of elements in the array. + index_add_buffer OUT An array of offsets into key_info_buffer. + index_add_count OUT The number of elements in the array. + candidate_key_count OUT The number of candidate keys in original table. + + DESCRIPTION + 'table' (first argument) contains information of the original + table, which includes all corresponding parts that the new + table has in arguments create_list, key_list and create_info. + + By comparing the changes between the original and new table + we can determine how much it has changed after ALTER TABLE + and whether we need to make a copy of the table, or just change + the .frm file. + + If there are no data changes, but index changes, 'index_drop_buffer' + and/or 'index_add_buffer' are populated with offsets into + table->key_info or key_info_buffer respectively for the indexes + that need to be dropped and/or (re-)created. + + RETURN VALUES + TRUE error + FALSE success +*/ + +static +bool +compare_tables(TABLE *table, + Alter_info *alter_info, + HA_CREATE_INFO *create_info, + uint order_num, + enum_alter_table_change_level *need_copy_table, + KEY **key_info_buffer, + uint **index_drop_buffer, uint *index_drop_count, + uint **index_add_buffer, uint *index_add_count, + uint *candidate_key_count) +{ + Field **f_ptr, *field; + uint changes= 0, tmp; + uint key_count; + List_iterator_fast new_field_it, tmp_new_field_it; + Create_field *new_field, *tmp_new_field; + KEY_PART_INFO *key_part; + KEY_PART_INFO *end; + THD *thd= table->in_use; + /* + Remember if the new definition has new VARCHAR column; + create_info->varchar will be reset in mysql_prepare_create_table. + */ + bool varchar= create_info->varchar; + bool not_nullable= true; + DBUG_ENTER("compare_tables"); + + /* + Create a copy of alter_info. + To compare the new and old table definitions, we need to "prepare" + the new definition - transform it from parser output to a format + that describes the final table layout (all column defaults are + initialized, duplicate columns are removed). This is done by + mysql_prepare_create_table. Unfortunately, + mysql_prepare_create_table performs its transformations + "in-place", that is, modifies the argument. Since we would + like to keep compare_tables() idempotent (not altering any + of the arguments) we create a copy of alter_info here and + pass it to mysql_prepare_create_table, then use the result + to evaluate possibility of fast ALTER TABLE, and then + destroy the copy. + */ + Alter_info tmp_alter_info(*alter_info, thd->mem_root); + uint db_options= 0; /* not used */ + /* Create the prepared information. */ + if (mysql_prepare_create_table(thd, create_info, + &tmp_alter_info, + (table->s->tmp_table != NO_TMP_TABLE), + &db_options, + table->file, key_info_buffer, + &key_count, 0)) + DBUG_RETURN(1); + /* Allocate result buffers. */ + if (! (*index_drop_buffer= + (uint*) thd->alloc(sizeof(uint) * table->s->keys)) || + ! (*index_add_buffer= + (uint*) thd->alloc(sizeof(uint) * tmp_alter_info.key_list.elements))) + DBUG_RETURN(1); + + /* + Some very basic checks. If number of fields changes, or the + handler, we need to run full ALTER TABLE. In the future + new fields can be added and old dropped without copy, but + not yet. + + Test also that engine was not given during ALTER TABLE, or + we are force to run regular alter table (copy). + E.g. ALTER TABLE tbl_name ENGINE=MyISAM. + + For the following ones we also want to run regular alter table: + ALTER TABLE tbl_name ORDER BY .. + ALTER TABLE tbl_name CONVERT TO CHARACTER SET .. + + At the moment we can't handle altering temporary tables without a copy. + We also test if OPTIMIZE TABLE was given and was mapped to alter table. + In that case we always do full copy. + + There was a bug prior to mysql-4.0.25. Number of null fields was + calculated incorrectly. As a result frm and data files gets out of + sync after fast alter table. There is no way to determine by which + mysql version (in 4.0 and 4.1 branches) table was created, thus we + disable fast alter table for all tables created by mysql versions + prior to 5.0 branch. + See BUG#6236. + */ + if (table->s->fields != alter_info->create_list.elements || + table->s->db_type() != create_info->db_type || + table->s->tmp_table || + create_info->used_fields & HA_CREATE_USED_ENGINE || + create_info->used_fields & HA_CREATE_USED_CHARSET || + create_info->used_fields & HA_CREATE_USED_DEFAULT_CHARSET || + (table->s->row_type != create_info->row_type) || + create_info->used_fields & HA_CREATE_USED_PACK_KEYS || + create_info->used_fields & HA_CREATE_USED_MAX_ROWS || + (alter_info->flags & (ALTER_RECREATE | ALTER_FOREIGN_KEY)) || + order_num || + !table->s->mysql_version || + (table->s->frm_version < FRM_VER_TRUE_VARCHAR && varchar)) + { + *need_copy_table= ALTER_TABLE_DATA_CHANGED; + DBUG_RETURN(0); + } + + /* + Use transformed info to evaluate possibility of fast ALTER TABLE + but use the preserved field to persist modifications. + */ + new_field_it.init(alter_info->create_list); + tmp_new_field_it.init(tmp_alter_info.create_list); + + /* + Go through fields and check if the original ones are compatible + with new table. + */ + for (f_ptr= table->field, new_field= new_field_it++, + tmp_new_field= tmp_new_field_it++; + (field= *f_ptr); + f_ptr++, new_field= new_field_it++, + tmp_new_field= tmp_new_field_it++) + { + /* Make sure we have at least the default charset in use. */ + if (!new_field->charset) + new_field->charset= create_info->default_table_charset; + + /* Check that NULL behavior is same for old and new fields */ + if ((tmp_new_field->flags & NOT_NULL_FLAG) != + (uint) (field->flags & NOT_NULL_FLAG)) + { + *need_copy_table= ALTER_TABLE_DATA_CHANGED; + DBUG_RETURN(0); + } + + /* Don't pack rows in old tables if the user has requested this. */ + if (create_info->row_type == ROW_TYPE_DYNAMIC || + (tmp_new_field->flags & BLOB_FLAG) || + (tmp_new_field->sql_type == MYSQL_TYPE_VARCHAR && + create_info->row_type != ROW_TYPE_FIXED)) + create_info->table_options|= HA_OPTION_PACK_RECORD; + + /* Check if field was renamed */ + field->flags&= ~FIELD_IS_RENAMED; + if (my_strcasecmp(system_charset_info, + field->field_name, + tmp_new_field->field_name)) + field->flags|= FIELD_IS_RENAMED; + + /* Evaluate changes bitmap and send to check_if_incompatible_data() */ + if (!(tmp= field->is_equal(tmp_new_field))) + { + *need_copy_table= ALTER_TABLE_DATA_CHANGED; + DBUG_RETURN(0); + } + // Clear indexed marker + field->flags&= ~FIELD_IN_ADD_INDEX; + changes|= tmp; + } + + /* + Go through keys and check if the original ones are compatible + with new table. + */ + KEY *table_key; + KEY *table_key_end= table->key_info + table->s->keys; + KEY *new_key; + KEY *new_key_end= *key_info_buffer + key_count; + + DBUG_PRINT("info", ("index count old: %d new: %d", + table->s->keys, key_count)); + /* + Step through all keys of the old table and search matching new keys. + */ + *index_drop_count= 0; + *index_add_count= 0; + *candidate_key_count= 0; + for (table_key= table->key_info; table_key < table_key_end; table_key++) + { + KEY_PART_INFO *table_part; + KEY_PART_INFO *table_part_end= table_key->key_part + table_key->key_parts; + KEY_PART_INFO *new_part; + + /* + Check if key is a candidate key, i.e. a unique index with no index + fields nullable, then key is either already primary key or could + be promoted to primary key if the original primary key is dropped. + Count all candidate keys. + */ + not_nullable= true; + for (table_part= table_key->key_part; + table_part < table_part_end; + table_part++) + { + not_nullable= not_nullable && (! table_part->field->maybe_null()); + } + if ((table_key->flags & HA_NOSAME) && not_nullable) + (*candidate_key_count)++; + + /* Search a new key with the same name. */ + for (new_key= *key_info_buffer; new_key < new_key_end; new_key++) + { + if (! strcmp(table_key->name, new_key->name)) + break; + } + if (new_key >= new_key_end) + { + /* Key not found. Add the offset of the key to the drop buffer. */ + (*index_drop_buffer)[(*index_drop_count)++]= table_key - table->key_info; + DBUG_PRINT("info", ("index dropped: '%s'", table_key->name)); + continue; + } + + /* Check that the key types are compatible between old and new tables. */ + if ((table_key->algorithm != new_key->algorithm) || + ((table_key->flags & HA_KEYFLAG_MASK) != + (new_key->flags & HA_KEYFLAG_MASK)) || + (table_key->key_parts != new_key->key_parts)) + goto index_changed; + + /* + Check that the key parts remain compatible between the old and + new tables. + */ + for (table_part= table_key->key_part, new_part= new_key->key_part; + table_part < table_part_end; + table_part++, new_part++) + { + /* + Key definition has changed if we are using a different field or + if the used key part length is different. We know that the fields + did not change. Comparing field numbers is sufficient. + */ + if ((table_part->length != new_part->length) || + (table_part->fieldnr - 1 != new_part->fieldnr)) + goto index_changed; + } + continue; + + index_changed: + /* Key modified. Add the offset of the key to both buffers. */ + (*index_drop_buffer)[(*index_drop_count)++]= table_key - table->key_info; + (*index_add_buffer)[(*index_add_count)++]= new_key - *key_info_buffer; + key_part= new_key->key_part; + end= key_part + new_key->key_parts; + for(; key_part != end; key_part++) + { + // Mark field to be part of new key + field= table->field[key_part->fieldnr]; + field->flags|= FIELD_IN_ADD_INDEX; + } + DBUG_PRINT("info", ("index changed: '%s'", table_key->name)); + } + /*end of for (; table_key < table_key_end;) */ + + /* + Step through all keys of the new table and find matching old keys. + */ + for (new_key= *key_info_buffer; new_key < new_key_end; new_key++) + { + /* Search an old key with the same name. */ + for (table_key= table->key_info; table_key < table_key_end; table_key++) + { + if (! strcmp(table_key->name, new_key->name)) + break; + } + if (table_key >= table_key_end) + { + /* Key not found. Add the offset of the key to the add buffer. */ + (*index_add_buffer)[(*index_add_count)++]= new_key - *key_info_buffer; + key_part= new_key->key_part; + end= key_part + new_key->key_parts; + for(; key_part != end; key_part++) + { + // Mark field to be part of new key + field= table->field[key_part->fieldnr]; + field->flags|= FIELD_IN_ADD_INDEX; + } + DBUG_PRINT("info", ("index added: '%s'", new_key->name)); + } + } + + /* Check if changes are compatible with current handler without a copy */ + if (table->file->check_if_incompatible_data(create_info, changes)) + { + *need_copy_table= ALTER_TABLE_DATA_CHANGED; + DBUG_RETURN(0); + } + + if (*index_drop_count || *index_add_count) + { + *need_copy_table= ALTER_TABLE_INDEX_CHANGED; + DBUG_RETURN(0); + } + + *need_copy_table= ALTER_TABLE_METADATA_ONLY; // Tables are compatible + DBUG_RETURN(0); +} + + +/* + Manages enabling/disabling of indexes for ALTER TABLE + + SYNOPSIS + alter_table_manage_keys() + table Target table + indexes_were_disabled Whether the indexes of the from table + were disabled + keys_onoff ENABLE | DISABLE | LEAVE_AS_IS + + RETURN VALUES + FALSE OK + TRUE Error +*/ + +static +bool alter_table_manage_keys(TABLE *table, int indexes_were_disabled, + enum enum_enable_or_disable keys_onoff) +{ + int error= 0; + DBUG_ENTER("alter_table_manage_keys"); + DBUG_PRINT("enter", ("table=%p were_disabled=%d on_off=%d", + table, indexes_were_disabled, keys_onoff)); + + switch (keys_onoff) { + case ENABLE: + error= table->file->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE); + break; + case LEAVE_AS_IS: + if (!indexes_were_disabled) + break; + /* fall-through: disabled indexes */ + case DISABLE: + error= table->file->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE); + } + + if (error == HA_ERR_WRONG_COMMAND) + { + push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA), + table->s->table_name.str); + error= 0; + } else if (error) + table->file->print_error(error, MYF(0)); + + DBUG_RETURN(error); +} + + +/** + Prepare column and key definitions for CREATE TABLE in ALTER TABLE. + + This function transforms parse output of ALTER TABLE - lists of + columns and keys to add, drop or modify into, essentially, + CREATE TABLE definition - a list of columns and keys of the new + table. While doing so, it also performs some (bug not all) + semantic checks. + + This function is invoked when we know that we're going to + perform ALTER TABLE via a temporary table -- i.e. fast ALTER TABLE + is not possible, perhaps because the ALTER statement contains + instructions that require change in table data, not only in + table definition or indexes. + + @param[in,out] thd thread handle. Used as a memory pool + and source of environment information. + @param[in] table the source table, open and locked + Used as an interface to the storage engine + to acquire additional information about + the original table. + @param[in,out] create_info A blob with CREATE/ALTER TABLE + parameters + @param[in,out] alter_info Another blob with ALTER/CREATE parameters. + Originally create_info was used only in + CREATE TABLE and alter_info only in ALTER TABLE. + But since ALTER might end-up doing CREATE, + this distinction is gone and we just carry + around two structures. + + @return + Fills various create_info members based on information retrieved + from the storage engine. + Sets create_info->varchar if the table has a VARCHAR column. + Prepares alter_info->create_list and alter_info->key_list with + columns and keys of the new table. + @retval TRUE error, out of memory or a semantical error in ALTER + TABLE instructions + @retval FALSE success +*/ + +static bool +mysql_prepare_alter_table(THD *thd, TABLE *table, + HA_CREATE_INFO *create_info, + Alter_info *alter_info) +{ + /* New column definitions are added here */ + List new_create_list; + /* New key definitions are added here */ + List new_key_list; + List_iterator drop_it(alter_info->drop_list); + List_iterator def_it(alter_info->create_list); + List_iterator alter_it(alter_info->alter_list); + List_iterator key_it(alter_info->key_list); + List_iterator find_it(new_create_list); + List_iterator field_it(new_create_list); + List key_parts; + uint db_create_options= (table->s->db_create_options + & ~(HA_OPTION_PACK_RECORD)); + uint used_fields= create_info->used_fields; + KEY *key_info=table->key_info; + bool rc= TRUE; + + DBUG_ENTER("mysql_prepare_alter_table"); + + create_info->varchar= FALSE; + /* Let new create options override the old ones */ + if (!(used_fields & HA_CREATE_USED_MIN_ROWS)) + create_info->min_rows= table->s->min_rows; + if (!(used_fields & HA_CREATE_USED_MAX_ROWS)) + create_info->max_rows= table->s->max_rows; + if (!(used_fields & HA_CREATE_USED_AVG_ROW_LENGTH)) + create_info->avg_row_length= table->s->avg_row_length; + if (!(used_fields & HA_CREATE_USED_DEFAULT_CHARSET)) + create_info->default_table_charset= table->s->table_charset; + if (!(used_fields & HA_CREATE_USED_AUTO) && table->found_next_number_field) + { + /* Table has an autoincrement, copy value to new table */ + table->file->info(HA_STATUS_AUTO); + create_info->auto_increment_value= table->file->stats.auto_increment_value; + } + if (!(used_fields & HA_CREATE_USED_KEY_BLOCK_SIZE)) + create_info->key_block_size= table->s->key_block_size; + + if (!create_info->tablespace && create_info->storage_media != HA_SM_MEMORY) + { + char *tablespace= static_cast(thd->alloc(FN_LEN + 1)); + /* + Regular alter table of disk stored table (no tablespace/storage change) + Copy tablespace name + */ + if (tablespace && + (table->file->get_tablespace_name(thd, tablespace, FN_LEN))) + create_info->tablespace= tablespace; + } + restore_record(table, s->default_values); // Empty record for DEFAULT + Create_field *def; + + /* + First collect all fields from table which isn't in drop_list + */ + Field **f_ptr,*field; + for (f_ptr=table->field ; (field= *f_ptr) ; f_ptr++) + { + if (field->type() == MYSQL_TYPE_STRING) + create_info->varchar= TRUE; + /* Check if field should be dropped */ + Alter_drop *drop; + drop_it.rewind(); + while ((drop=drop_it++)) + { + if (drop->type == Alter_drop::COLUMN && + !my_strcasecmp(system_charset_info,field->field_name, drop->name)) + { + /* Reset auto_increment value if it was dropped */ + if (MTYP_TYPENR(field->unireg_check) == Field::NEXT_NUMBER && + !(used_fields & HA_CREATE_USED_AUTO)) + { + create_info->auto_increment_value=0; + create_info->used_fields|=HA_CREATE_USED_AUTO; + } + break; + } + } + if (drop) + { + drop_it.remove(); + continue; + } + /* Check if field is changed */ + def_it.rewind(); + while ((def=def_it++)) + { + if (def->change && + !my_strcasecmp(system_charset_info,field->field_name, def->change)) + break; + } + if (def) + { // Field is changed + def->field=field; + if (!def->after) + { + new_create_list.push_back(def); + def_it.remove(); + } + } + else + { + /* + This field was not dropped and not changed, add it to the list + for the new table. + */ + def= new Create_field(field, field); + new_create_list.push_back(def); + alter_it.rewind(); // Change default if ALTER + Alter_column *alter; + while ((alter=alter_it++)) + { + if (!my_strcasecmp(system_charset_info,field->field_name, alter->name)) + break; + } + if (alter) + { + if (def->sql_type == MYSQL_TYPE_BLOB) + { + my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0), def->change); + goto err; + } + if ((def->def=alter->def)) // Use new default + def->flags&= ~NO_DEFAULT_VALUE_FLAG; + else + def->flags|= NO_DEFAULT_VALUE_FLAG; + alter_it.remove(); + } + } + } + def_it.rewind(); + while ((def=def_it++)) // Add new columns + { + if (def->change && ! def->field) + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change, table->s->table_name.str); + goto err; + } + /* + Check that the DATE/DATETIME not null field we are going to add is + either has a default value or the '0000-00-00' is allowed by the + set sql mode. + If the '0000-00-00' value isn't allowed then raise the error_if_not_empty + flag to allow ALTER TABLE only if the table to be altered is empty. + */ + if ((def->sql_type == MYSQL_TYPE_DATE || + def->sql_type == MYSQL_TYPE_NEWDATE || + def->sql_type == MYSQL_TYPE_DATETIME) && + !alter_info->datetime_field && + !(~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) && + thd->variables.sql_mode & MODE_NO_ZERO_DATE) + { + alter_info->datetime_field= def; + alter_info->error_if_not_empty= TRUE; + } + if (!def->after) + new_create_list.push_back(def); + else if (def->after == first_keyword) + new_create_list.push_front(def); + else + { + Create_field *find; + find_it.rewind(); + while ((find=find_it++)) // Add new columns + { + if (!my_strcasecmp(system_charset_info,def->after, find->field_name)) + break; + } + if (!find) + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after, table->s->table_name.str); + goto err; + } + find_it.after(def); // Put element after this + alter_info->change_level= ALTER_TABLE_DATA_CHANGED; + } + } + if (alter_info->alter_list.elements) + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), + alter_info->alter_list.head()->name, table->s->table_name.str); + goto err; + } + if (!new_create_list.elements) + { + my_message(ER_CANT_REMOVE_ALL_FIELDS, ER(ER_CANT_REMOVE_ALL_FIELDS), + MYF(0)); + goto err; + } + + /* + Collect all keys which isn't in drop list. Add only those + for which some fields exists. + */ + + for (uint i=0 ; i < table->s->keys ; i++,key_info++) + { + char *key_name= key_info->name; + Alter_drop *drop; + drop_it.rewind(); + while ((drop=drop_it++)) + { + if (drop->type == Alter_drop::KEY && + !my_strcasecmp(system_charset_info,key_name, drop->name)) + break; + } + if (drop) + { + drop_it.remove(); + continue; + } + + KEY_PART_INFO *key_part= key_info->key_part; + key_parts.empty(); + for (uint j=0 ; j < key_info->key_parts ; j++,key_part++) + { + if (!key_part->field) + continue; // Wrong field (from UNIREG) + const char *key_part_name=key_part->field->field_name; + Create_field *cfield; + field_it.rewind(); + while ((cfield=field_it++)) + { + if (cfield->change) + { + if (!my_strcasecmp(system_charset_info, key_part_name, + cfield->change)) + break; + } + else if (!my_strcasecmp(system_charset_info, + key_part_name, cfield->field_name)) + break; + } + if (!cfield) + continue; // Field is removed + uint key_part_length=key_part->length; + if (cfield->field) // Not new field + { + /* + If the field can't have only a part used in a key according to its + new type, or should not be used partially according to its + previous type, or the field length is less than the key part + length, unset the key part length. + + We also unset the key part length if it is the same as the + old field's length, so the whole new field will be used. + + BLOBs may have cfield->length == 0, which is why we test it before + checking whether cfield->length < key_part_length (in chars). + */ + if (!Field::type_can_have_key_part(cfield->field->type()) || + !Field::type_can_have_key_part(cfield->sql_type) || + /* spatial keys can't have sub-key length */ + (key_info->flags & HA_SPATIAL) || + (cfield->field->field_length == key_part_length && + !f_is_blob(key_part->key_type)) || + (cfield->length && (cfield->length < key_part_length / + key_part->field->charset()->mbmaxlen))) + key_part_length= 0; // Use whole field + } + key_part_length /= key_part->field->charset()->mbmaxlen; + key_parts.push_back(new Key_part_spec(cfield->field_name, + key_part_length)); + } + if (key_parts.elements) + { + KEY_CREATE_INFO key_create_info; + Key *key; + enum Key::Keytype key_type; + bzero((char*) &key_create_info, sizeof(key_create_info)); + + key_create_info.algorithm= key_info->algorithm; + if (key_info->flags & HA_USES_BLOCK_SIZE) + key_create_info.block_size= key_info->block_size; + if (key_info->flags & HA_USES_PARSER) + key_create_info.parser_name= *plugin_name(key_info->parser); + + if (key_info->flags & HA_SPATIAL) + key_type= Key::SPATIAL; + else if (key_info->flags & HA_NOSAME) + { + if (! my_strcasecmp(system_charset_info, key_name, primary_key_name)) + key_type= Key::PRIMARY; + else + key_type= Key::UNIQUE; + } + else if (key_info->flags & HA_FULLTEXT) + key_type= Key::FULLTEXT; + else + key_type= Key::MULTIPLE; + + key= new Key(key_type, key_name, + &key_create_info, + test(key_info->flags & HA_GENERATED_KEY), + key_parts); + new_key_list.push_back(key); + } + } + { + Key *key; + while ((key=key_it++)) // Add new keys + { + if (key->type != Key::FOREIGN_KEY) + new_key_list.push_back(key); + if (key->name && + !my_strcasecmp(system_charset_info,key->name,primary_key_name)) + { + my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name); + goto err; + } + } + } + + if (alter_info->drop_list.elements) + { + my_error(ER_CANT_DROP_FIELD_OR_KEY, MYF(0), + alter_info->drop_list.head()->name); + goto err; + } + if (alter_info->alter_list.elements) + { + my_error(ER_CANT_DROP_FIELD_OR_KEY, MYF(0), + alter_info->alter_list.head()->name); + goto err; + } + + if (!create_info->comment.str) + { + create_info->comment.str= table->s->comment.str; + create_info->comment.length= table->s->comment.length; + } + + table->file->update_create_info(create_info); + if ((create_info->table_options & + (HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS)) || + (used_fields & HA_CREATE_USED_PACK_KEYS)) + db_create_options&= ~(HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS); + if (create_info->table_options & + (HA_OPTION_CHECKSUM | HA_OPTION_NO_CHECKSUM)) + db_create_options&= ~(HA_OPTION_CHECKSUM | HA_OPTION_NO_CHECKSUM); + if (create_info->table_options & + (HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_NO_DELAY_KEY_WRITE)) + db_create_options&= ~(HA_OPTION_DELAY_KEY_WRITE | + HA_OPTION_NO_DELAY_KEY_WRITE); + create_info->table_options|= db_create_options; + + if (table->s->tmp_table) + create_info->options|=HA_LEX_CREATE_TMP_TABLE; + + rc= FALSE; + alter_info->create_list.swap(new_create_list); + alter_info->key_list.swap(new_key_list); +err: + DBUG_RETURN(rc); +} + + +/* + Alter table + + SYNOPSIS + mysql_alter_table() + thd Thread handle + new_db If there is a RENAME clause + new_name If there is a RENAME clause + create_info Information from the parsing phase about new + table properties. + table_list The table to change. + alter_info Lists of fields, keys to be changed, added + or dropped. + order_num How many ORDER BY fields has been specified. + order List of fields to ORDER BY. + ignore Whether we have ALTER IGNORE TABLE + + DESCRIPTION + This is a veery long function and is everything but the kitchen sink :) + It is used to alter a table and not only by ALTER TABLE but also + CREATE|DROP INDEX are mapped on this function. + + When the ALTER TABLE statement just does a RENAME or ENABLE|DISABLE KEYS, + or both, then this function short cuts its operation by renaming + the table and/or enabling/disabling the keys. In this case, the FRM is + not changed, directly by mysql_alter_table. However, if there is a + RENAME + change of a field, or an index, the short cut is not used. + See how `create_list` is used to generate the new FRM regarding the + structure of the fields. The same is done for the indices of the table. + + Important is the fact, that this function tries to do as little work as + possible, by finding out whether a intermediate table is needed to copy + data into and when finishing the altering to use it as the original table. + For this reason the function compare_tables() is called, which decides + based on all kind of data how similar are the new and the original + tables. + + RETURN VALUES + FALSE OK + TRUE Error +*/ + +bool mysql_alter_table(THD *thd,char *new_db, char *new_name, + HA_CREATE_INFO *create_info, + TABLE_LIST *table_list, + Alter_info *alter_info, + uint order_num, ORDER *order, bool ignore) +{ + TABLE *table, *new_table= 0, *name_lock= 0; + int error= 0; + char tmp_name[80],old_name[32],new_name_buff[FN_REFLEN + 1]; + char new_alias_buff[FN_REFLEN], *table_name, *db, *new_alias, *alias; + char index_file[FN_REFLEN], data_file[FN_REFLEN]; + char path[FN_REFLEN + 1]; + char reg_path[FN_REFLEN+1]; + ha_rows copied,deleted; + handlerton *old_db_type, *new_db_type, *save_old_db_type; + legacy_db_type table_type; + frm_type_enum frm_type; + enum_alter_table_change_level need_copy_table= ALTER_TABLE_METADATA_ONLY; +#ifdef WITH_PARTITION_STORAGE_ENGINE + uint fast_alter_partition= 0; + bool partition_changed= FALSE; +#endif + bool need_lock_for_indexes= TRUE; + KEY *key_info_buffer; + uint index_drop_count= 0; + uint *index_drop_buffer= NULL; + uint index_add_count= 0; + uint *index_add_buffer= NULL; + uint candidate_key_count= 0; + bool committed= 0; + bool no_pk; + DBUG_ENTER("mysql_alter_table"); + + /* + Check if we attempt to alter mysql.slow_log or + mysql.general_log table and return an error if + it is the case. + TODO: this design is obsolete and will be removed. + */ + if (table_list && table_list->db && table_list->table_name) + { + int table_kind= 0; + + table_kind= check_if_log_table(table_list->db_length, table_list->db, + table_list->table_name_length, + table_list->table_name, 0); + + if (table_kind) + { + /* Disable alter of enabled log tables */ + if (logger.is_log_table_enabled(table_kind)) + { + my_error(ER_BAD_LOG_STATEMENT, MYF(0), "ALTER"); + DBUG_RETURN(TRUE); + } + + /* Disable alter of log tables to unsupported engine */ + if ((create_info->used_fields & HA_CREATE_USED_ENGINE) && + (!create_info->db_type || /* unknown engine */ + !(create_info->db_type->flags & HTON_SUPPORT_LOG_TABLES))) + { + my_error(ER_UNSUPORTED_LOG_ENGINE, MYF(0)); + DBUG_RETURN(TRUE); + } + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (alter_info->flags & ALTER_PARTITION) + { + my_error(ER_WRONG_USAGE, MYF(0), "PARTITION", "log table"); + DBUG_RETURN(TRUE); + } +#endif + } + } + + /* + Assign variables table_name, new_name, db, new_db, path, reg_path + to simplify further comparisions: we want to see if it's a RENAME + later just by comparing the pointers, avoiding the need for strcmp. + */ + thd_proc_info(thd, "init"); + table_name=table_list->table_name; + alias= (lower_case_table_names == 2) ? table_list->alias : table_name; + db=table_list->db; + if (!new_db || !my_strcasecmp(table_alias_charset, new_db, db)) + new_db= db; + build_table_filename(reg_path, sizeof(reg_path) - 1, db, table_name, reg_ext, 0); + build_table_filename(path, sizeof(path) - 1, db, table_name, "", 0); + + mysql_ha_rm_tables(thd, table_list, FALSE); + + /* DISCARD/IMPORT TABLESPACE is always alone in an ALTER TABLE */ + if (alter_info->tablespace_op != NO_TABLESPACE_OP) + /* Conditionally writes to binlog. */ + DBUG_RETURN(mysql_discard_or_import_tablespace(thd,table_list, + alter_info->tablespace_op)); + strxnmov(new_name_buff, sizeof (new_name_buff) - 1, mysql_data_home, "/", db, + "/", table_name, reg_ext, NullS); + (void) unpack_filename(new_name_buff, new_name_buff); + /* + If this is just a rename of a view, short cut to the + following scenario: 1) lock LOCK_open 2) do a RENAME + 2) unlock LOCK_open. + This is a copy-paste added to make sure + ALTER (sic:) TABLE .. RENAME works for views. ALTER VIEW is handled + as an independent branch in mysql_execute_command. The need + for a copy-paste arose because the main code flow of ALTER TABLE + ... RENAME tries to use open_ltable, which does not work for views + (open_ltable was never modified to merge table lists of child tables + into the main table list, like open_tables does). + This code is wrong and will be removed, please do not copy. + */ + frm_type= mysql_frm_type(thd, new_name_buff, &table_type); + /* Rename a view */ + /* Sic: there is a race here */ + if (frm_type == FRMTYPE_VIEW && !(alter_info->flags & ~ALTER_RENAME)) + { + /* + The following branch handles "ALTER VIEW v1 /no arguments/;" + This feature is not documented one. + However, before "OPTIMIZE TABLE t1;" was implemented, + ALTER TABLE with no alter_specifications was used to force-rebuild + the table. That's why this grammar is allowed. That's why we ignore + it for views. So just do nothing in such a case. + */ + if (!new_name) + { + my_ok(thd); + DBUG_RETURN(FALSE); + } + + /* + Avoid problems with a rename on a table that we have locked or + if the user is trying to to do this in a transcation context + */ + + if (thd->locked_tables || thd->active_transaction()) + { + my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, + ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); + DBUG_RETURN(TRUE); + } + + if (wait_if_global_read_lock(thd,0,1)) + DBUG_RETURN(TRUE); + VOID(pthread_mutex_lock(&LOCK_open)); + if (lock_table_names(thd, table_list)) + { + error= 1; + goto view_err; + } + + if (!do_rename(thd, table_list, new_db, new_name, new_name, 1)) + { + if (mysql_bin_log.is_open()) + { + thd->clear_error(); + Query_log_event qinfo(thd, thd->query, thd->query_length, + 0, FALSE, 0); + mysql_bin_log.write(&qinfo); + } + my_ok(thd); + } + + unlock_table_names(thd, table_list, (TABLE_LIST*) 0); + +view_err: + pthread_mutex_unlock(&LOCK_open); + start_waiting_global_read_lock(thd); + DBUG_RETURN(error); + } + + if (!(table= open_n_lock_single_table(thd, table_list, TL_WRITE_ALLOW_READ))) + DBUG_RETURN(TRUE); + table->use_all_columns(); + + /* + Prohibit changing of the UNION list of a non-temporary MERGE table + under LOCK tables. It would be quite difficult to reuse a shrinked + set of tables from the old table or to open a new TABLE object for + an extended list and verify that they belong to locked tables. + */ + if (thd->locked_tables && + (create_info->used_fields & HA_CREATE_USED_UNION) && + (table->s->tmp_table == NO_TMP_TABLE)) + { + my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0)); + DBUG_RETURN(TRUE); + } + + /* Check that we are not trying to rename to an existing table */ + if (new_name) + { + DBUG_PRINT("info", ("new_db.new_name: '%s'.'%s'", new_db, new_name)); + strmov(new_name_buff,new_name); + strmov(new_alias= new_alias_buff, new_name); + if (lower_case_table_names) + { + if (lower_case_table_names != 2) + { + my_casedn_str(files_charset_info, new_name_buff); + new_alias= new_name; // Create lower case table name + } + my_casedn_str(files_charset_info, new_name); + } + if (new_db == db && + !my_strcasecmp(table_alias_charset, new_name_buff, table_name)) + { + /* + Source and destination table names are equal: make later check + easier. + */ + new_alias= new_name= table_name; + } + else + { + if (table->s->tmp_table != NO_TMP_TABLE) + { + if (find_temporary_table(thd,new_db,new_name_buff)) + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_name_buff); + DBUG_RETURN(TRUE); + } + } + else + { + if (lock_table_name_if_not_cached(thd, new_db, new_name, &name_lock)) + DBUG_RETURN(TRUE); + if (!name_lock) + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_alias); + DBUG_RETURN(TRUE); + } + + build_table_filename(new_name_buff, sizeof(new_name_buff) - 1, + new_db, new_name_buff, reg_ext, 0); + if (!access(new_name_buff, F_OK)) + { + /* Table will be closed in do_command() */ + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_alias); + goto err; + } + } + } + } + else + { + new_alias= (lower_case_table_names == 2) ? alias : table_name; + new_name= table_name; + } + + old_db_type= table->s->db_type(); + if (!create_info->db_type) + { +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (table->part_info && + create_info->used_fields & HA_CREATE_USED_ENGINE) + { + /* + This case happens when the user specified + ENGINE = x where x is a non-existing storage engine + We set create_info->db_type to default_engine_type + to ensure we don't change underlying engine type + due to a erroneously given engine name. + */ + create_info->db_type= table->part_info->default_engine_type; + } + else +#endif + create_info->db_type= old_db_type; + } + + if (check_engine(thd, new_name, create_info)) + goto err; + new_db_type= create_info->db_type; + + if ((new_db_type != old_db_type || + alter_info->flags & ALTER_PARTITION) && + !table->file->can_switch_engines()) + { + my_error(ER_ROW_IS_REFERENCED, MYF(0)); + goto err; + } + + if (create_info->row_type == ROW_TYPE_NOT_USED) + { + create_info->row_type= table->s->row_type; + create_info->used_fields |= HA_CREATE_USED_ROW_FORMAT; + } + + DBUG_PRINT("info", ("old type: %s new type: %s", + ha_resolve_storage_engine_name(old_db_type), + ha_resolve_storage_engine_name(new_db_type))); + if (ha_check_storage_engine_flag(old_db_type, HTON_ALTER_NOT_SUPPORTED) || + ha_check_storage_engine_flag(new_db_type, HTON_ALTER_NOT_SUPPORTED)) + { + DBUG_PRINT("info", ("doesn't support alter")); + my_error(ER_ILLEGAL_HA, MYF(0), table_name); + goto err; + } + + thd_proc_info(thd, "setup"); + if (!(alter_info->flags & ~(ALTER_RENAME | ALTER_KEYS_ONOFF)) && + !table->s->tmp_table) // no need to touch frm + { + switch (alter_info->keys_onoff) { + case LEAVE_AS_IS: + break; + case ENABLE: + /* + wait_while_table_is_used() ensures that table being altered is + opened only by this thread and that TABLE::TABLE_SHARE::version + of TABLE object corresponding to this table is 0. + The latter guarantees that no DML statement will open this table + until ALTER TABLE finishes (i.e. until close_thread_tables()) + while the fact that the table is still open gives us protection + from concurrent DDL statements. + */ + VOID(pthread_mutex_lock(&LOCK_open)); + wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_EXECUTE_IF("sleep_alter_enable_indexes", my_sleep(6000000);); + error= table->file->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE); + /* COND_refresh will be signaled in close_thread_tables() */ + break; + case DISABLE: + VOID(pthread_mutex_lock(&LOCK_open)); + wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN); + VOID(pthread_mutex_unlock(&LOCK_open)); + error=table->file->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE); + /* COND_refresh will be signaled in close_thread_tables() */ + break; + default: + DBUG_ASSERT(FALSE); + error= 0; + break; + } + if (error == HA_ERR_WRONG_COMMAND) + { + error= 0; + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA), + table->alias); + } + + VOID(pthread_mutex_lock(&LOCK_open)); + /* + Unlike to the above case close_cached_table() below will remove ALL + instances of TABLE from table cache (it will also remove table lock + held by this thread). So to make actual table renaming and writing + to binlog atomic we have to put them into the same critical section + protected by LOCK_open mutex. This also removes gap for races between + access() and mysql_rename_table() calls. + */ + + if (!error && (new_name != table_name || new_db != db)) + { + thd_proc_info(thd, "rename"); + /* + Then do a 'simple' rename of the table. First we need to close all + instances of 'source' table. + */ + close_cached_table(thd, table); + /* + Then, we want check once again that target table does not exist. + Actually the order of these two steps does not matter since + earlier we took name-lock on the target table, so we do them + in this particular order only to be consistent with 5.0, in which + we don't take this name-lock and where this order really matters. + TODO: Investigate if we need this access() check at all. + */ + if (!access(new_name_buff,F_OK)) + { + my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_name); + error= -1; + } + else + { + *fn_ext(new_name)=0; + if (mysql_rename_table(old_db_type,db,table_name,new_db,new_alias, 0)) + error= -1; + else if (Table_triggers_list::change_table_name(thd, db, table_name, + new_db, new_alias)) + { + VOID(mysql_rename_table(old_db_type, new_db, new_alias, db, + table_name, 0)); + error= -1; + } + } + } + + if (error == HA_ERR_WRONG_COMMAND) + { + error= 0; + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA), + table->alias); + } + + if (!error) + { + write_bin_log(thd, TRUE, thd->query, thd->query_length); + my_ok(thd); + } + else if (error > 0) + { + table->file->print_error(error, MYF(0)); + error= -1; + } + if (name_lock) + unlink_open_table(thd, name_lock, FALSE); + VOID(pthread_mutex_unlock(&LOCK_open)); + table_list->table= NULL; // For query cache + query_cache_invalidate3(thd, table_list, 0); + DBUG_RETURN(error); + } + + /* We have to do full alter table. */ + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (prep_alter_part_table(thd, table, alter_info, create_info, old_db_type, + &partition_changed, &fast_alter_partition)) + goto err; +#endif + /* + If the old table had partitions and we are doing ALTER TABLE ... + engine= , the new table must preserve the original + partitioning. That means that the new engine is still the + partitioning engine, not the engine specified in the parser. + This is discovered in prep_alter_part_table, which in such case + updates create_info->db_type. + Now we need to update the stack copy of create_info->db_type, + as otherwise we won't be able to correctly move the files of the + temporary table to the result table files. + */ + new_db_type= create_info->db_type; + + if (mysql_prepare_alter_table(thd, table, create_info, alter_info)) + goto err; + + need_copy_table= alter_info->change_level; + + set_table_default_charset(thd, create_info, db); + + if (thd->variables.old_alter_table + || (table->s->db_type() != create_info->db_type) +#ifdef WITH_PARTITION_STORAGE_ENGINE + || partition_changed +#endif + ) + need_copy_table= ALTER_TABLE_DATA_CHANGED; + else + { + enum_alter_table_change_level need_copy_table_res; + /* Check how much the tables differ. */ + if (compare_tables(table, alter_info, + create_info, order_num, + &need_copy_table_res, + &key_info_buffer, + &index_drop_buffer, &index_drop_count, + &index_add_buffer, &index_add_count, + &candidate_key_count)) + goto err; + + if (need_copy_table == ALTER_TABLE_METADATA_ONLY) + need_copy_table= need_copy_table_res; + } + + /* + If there are index changes only, try to do them online. "Index + changes only" means also that the handler for the table does not + change. The table is open and locked. The handler can be accessed. + */ + if (need_copy_table == ALTER_TABLE_INDEX_CHANGED) + { + int pk_changed= 0; + ulong alter_flags= 0; + ulong needed_online_flags= 0; + ulong needed_fast_flags= 0; + KEY *key; + uint *idx_p; + uint *idx_end_p; + + alter_flags= table->file->alter_table_flags(alter_info->flags); + DBUG_PRINT("info", ("alter_flags: %lu", alter_flags)); + /* Check dropped indexes. */ + for (idx_p= index_drop_buffer, idx_end_p= idx_p + index_drop_count; + idx_p < idx_end_p; + idx_p++) + { + key= table->key_info + *idx_p; + DBUG_PRINT("info", ("index dropped: '%s'", key->name)); + if (key->flags & HA_NOSAME) + { + /* + Unique key. Check for "PRIMARY". + or if dropping last unique key + */ + if ((uint) (key - table->key_info) == table->s->primary_key) + { + DBUG_PRINT("info", ("Dropping primary key")); + /* Primary key. */ + needed_online_flags|= HA_ONLINE_DROP_PK_INDEX; + needed_fast_flags|= HA_ONLINE_DROP_PK_INDEX_NO_WRITES; + pk_changed++; + candidate_key_count--; + } + else + { + KEY_PART_INFO *part_end= key->key_part + key->key_parts; + bool is_candidate_key= true; + + /* Non-primary unique key. */ + needed_online_flags|= HA_ONLINE_DROP_UNIQUE_INDEX; + needed_fast_flags|= HA_ONLINE_DROP_UNIQUE_INDEX_NO_WRITES; + + /* + Check if all fields in key are declared + NOT NULL and adjust candidate_key_count + */ + for (KEY_PART_INFO *key_part= key->key_part; + key_part < part_end; + key_part++) + is_candidate_key= + (is_candidate_key && + (! table->field[key_part->fieldnr-1]->maybe_null())); + if (is_candidate_key) + candidate_key_count--; + } + } + else + { + /* Non-unique key. */ + needed_online_flags|= HA_ONLINE_DROP_INDEX; + needed_fast_flags|= HA_ONLINE_DROP_INDEX_NO_WRITES; + } + } + no_pk= ((table->s->primary_key == MAX_KEY) || + (needed_online_flags & HA_ONLINE_DROP_PK_INDEX)); + /* Check added indexes. */ + for (idx_p= index_add_buffer, idx_end_p= idx_p + index_add_count; + idx_p < idx_end_p; + idx_p++) + { + key= key_info_buffer + *idx_p; + DBUG_PRINT("info", ("index added: '%s'", key->name)); + if (key->flags & HA_NOSAME) + { + /* Unique key */ + + KEY_PART_INFO *part_end= key->key_part + key->key_parts; + bool is_candidate_key= true; + + /* + Check if all fields in key are declared + NOT NULL + */ + for (KEY_PART_INFO *key_part= key->key_part; + key_part < part_end; + key_part++) + is_candidate_key= + (is_candidate_key && + (! table->field[key_part->fieldnr]->maybe_null())); + + /* + Check for "PRIMARY" + or if adding first unique key + defined on non-nullable fields + */ + + if ((!my_strcasecmp(system_charset_info, + key->name, primary_key_name)) || + (no_pk && candidate_key_count == 0 && is_candidate_key)) + { + DBUG_PRINT("info", ("Adding primary key")); + /* Primary key. */ + needed_online_flags|= HA_ONLINE_ADD_PK_INDEX; + needed_fast_flags|= HA_ONLINE_ADD_PK_INDEX_NO_WRITES; + pk_changed++; + no_pk= false; + } + else + { + /* Non-primary unique key. */ + needed_online_flags|= HA_ONLINE_ADD_UNIQUE_INDEX; + needed_fast_flags|= HA_ONLINE_ADD_UNIQUE_INDEX_NO_WRITES; + } + } + else + { + /* Non-unique key. */ + needed_online_flags|= HA_ONLINE_ADD_INDEX; + needed_fast_flags|= HA_ONLINE_ADD_INDEX_NO_WRITES; + } + } + + if ((candidate_key_count > 0) && + (needed_online_flags & HA_ONLINE_DROP_PK_INDEX)) + { + /* + Dropped primary key when there is some other unique + not null key that should be converted to primary key + */ + needed_online_flags|= HA_ONLINE_ADD_PK_INDEX; + needed_fast_flags|= HA_ONLINE_ADD_PK_INDEX_NO_WRITES; + pk_changed= 2; + } + + DBUG_PRINT("info", ("needed_online_flags: 0x%lx, needed_fast_flags: 0x%lx", + needed_online_flags, needed_fast_flags)); + /* + Online or fast add/drop index is possible only if + the primary key is not added and dropped in the same statement. + Otherwise we have to recreate the table. + need_copy_table is no-zero at this place. + */ + if ( pk_changed < 2 ) + { + if ((alter_flags & needed_online_flags) == needed_online_flags) + { + /* All required online flags are present. */ + need_copy_table= ALTER_TABLE_METADATA_ONLY; + need_lock_for_indexes= FALSE; + } + else if ((alter_flags & needed_fast_flags) == needed_fast_flags) + { + /* All required fast flags are present. */ + need_copy_table= ALTER_TABLE_METADATA_ONLY; + } + } + DBUG_PRINT("info", ("need_copy_table: %u need_lock: %d", + need_copy_table, need_lock_for_indexes)); + } + + /* + better have a negative test here, instead of positive, like + alter_info->flags & ALTER_ADD_COLUMN|ALTER_ADD_INDEX|... + so that ALTER TABLE won't break when somebody will add new flag + */ + if (need_copy_table == ALTER_TABLE_METADATA_ONLY) + create_info->frm_only= 1; + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (fast_alter_partition) + { + DBUG_ASSERT(!name_lock); + DBUG_RETURN(fast_alter_partition_table(thd, table, alter_info, + create_info, table_list, + db, table_name, + fast_alter_partition)); + } +#endif + + my_snprintf(tmp_name, sizeof(tmp_name), "%s-%lx_%lx", tmp_file_prefix, + current_pid, thd->thread_id); + /* Safety fix for innodb */ + if (lower_case_table_names) + my_casedn_str(files_charset_info, tmp_name); + + /* + Handling of symlinked tables: + If no rename: + Create new data file and index file on the same disk as the + old data and index files. + Copy data. + Rename new data file over old data file and new index file over + old index file. + Symlinks are not changed. + + If rename: + Create new data file and index file on the same disk as the + old data and index files. Create also symlinks to point at + the new tables. + Copy data. + At end, rename intermediate tables, and symlinks to intermediate + table, to final table name. + Remove old table and old symlinks + + If rename is made to another database: + Create new tables in new database. + Copy data. + Remove old table and symlinks. + */ + if (!strcmp(db, new_db)) // Ignore symlink if db changed + { + if (create_info->index_file_name) + { + /* Fix index_file_name to have 'tmp_name' as basename */ + strmov(index_file, tmp_name); + create_info->index_file_name=fn_same(index_file, + create_info->index_file_name, + 1); + } + if (create_info->data_file_name) + { + /* Fix data_file_name to have 'tmp_name' as basename */ + strmov(data_file, tmp_name); + create_info->data_file_name=fn_same(data_file, + create_info->data_file_name, + 1); + } + } + else + create_info->data_file_name=create_info->index_file_name=0; + + /* + Create a table with a temporary name. + With create_info->frm_only == 1 this creates a .frm file only. + We don't log the statement, it will be logged later. + */ + tmp_disable_binlog(thd); + error= mysql_create_table_no_lock(thd, new_db, tmp_name, + create_info, + alter_info, + 1, 0); + reenable_binlog(thd); + if (error) + goto err; + + /* Open the table if we need to copy the data. */ + DBUG_PRINT("info", ("need_copy_table: %u", need_copy_table)); + if (need_copy_table != ALTER_TABLE_METADATA_ONLY) + { + if (table->s->tmp_table) + { + TABLE_LIST tbl; + bzero((void*) &tbl, sizeof(tbl)); + tbl.db= new_db; + tbl.table_name= tbl.alias= tmp_name; + /* Table is in thd->temporary_tables */ + new_table= open_table(thd, &tbl, thd->mem_root, (bool*) 0, + MYSQL_LOCK_IGNORE_FLUSH); + } + else + { + char path[FN_REFLEN + 1]; + /* table is a normal table: Create temporary table in same directory */ + build_table_filename(path, sizeof(path) - 1, new_db, tmp_name, "", + FN_IS_TMP); + /* Open our intermediate table */ + new_table=open_temporary_table(thd, path, new_db, tmp_name,0); + } + if (!new_table) + goto err1; + /* + Note: In case of MERGE table, we do not attach children. We do not + copy data for MERGE tables. Only the children have data. + */ + } + + /* Copy the data if necessary. */ + thd->count_cuted_fields= CHECK_FIELD_WARN; // calc cuted fields + thd->cuted_fields=0L; + copied=deleted=0; + /* + We do not copy data for MERGE tables. Only the children have data. + MERGE tables have HA_NO_COPY_ON_ALTER set. + */ + if (new_table && !(new_table->file->ha_table_flags() & HA_NO_COPY_ON_ALTER)) + { + /* We don't want update TIMESTAMP fields during ALTER TABLE. */ + new_table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET; + new_table->next_number_field=new_table->found_next_number_field; + thd_proc_info(thd, "copy to tmp table"); + error= copy_data_between_tables(table, new_table, + alter_info->create_list, ignore, + order_num, order, &copied, &deleted, + alter_info->keys_onoff, + alter_info->error_if_not_empty); + } + else + { + VOID(pthread_mutex_lock(&LOCK_open)); + wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN); + VOID(pthread_mutex_unlock(&LOCK_open)); + thd_proc_info(thd, "manage keys"); + alter_table_manage_keys(table, table->file->indexes_are_disabled(), + alter_info->keys_onoff); + error= ha_autocommit_or_rollback(thd, 0); + if (end_active_trans(thd)) + error= 1; + } + thd->count_cuted_fields= CHECK_FIELD_IGNORE; + + /* If we did not need to copy, we might still need to add/drop indexes. */ + if (! new_table) + { + uint *key_numbers; + uint *keyno_p; + KEY *key_info; + KEY *key; + uint *idx_p; + uint *idx_end_p; + KEY_PART_INFO *key_part; + KEY_PART_INFO *part_end; + DBUG_PRINT("info", ("No new_table, checking add/drop index")); + + table->file->ha_prepare_for_alter(); + if (index_add_count) + { + /* The add_index() method takes an array of KEY structs. */ + key_info= (KEY*) thd->alloc(sizeof(KEY) * index_add_count); + key= key_info; + for (idx_p= index_add_buffer, idx_end_p= idx_p + index_add_count; + idx_p < idx_end_p; + idx_p++, key++) + { + /* Copy the KEY struct. */ + *key= key_info_buffer[*idx_p]; + /* Fix the key parts. */ + part_end= key->key_part + key->key_parts; + for (key_part= key->key_part; key_part < part_end; key_part++) + key_part->field= table->field[key_part->fieldnr]; + } + /* Add the indexes. */ + if ((error= table->file->add_index(table, key_info, index_add_count))) + { + /* + Exchange the key_info for the error message. If we exchange + key number by key name in the message later, we need correct info. + */ + KEY *save_key_info= table->key_info; + table->key_info= key_info; + table->file->print_error(error, MYF(0)); + table->key_info= save_key_info; + goto err1; + } + } + /*end of if (index_add_count)*/ + + if (index_drop_count) + { + /* The prepare_drop_index() method takes an array of key numbers. */ + key_numbers= (uint*) thd->alloc(sizeof(uint) * index_drop_count); + keyno_p= key_numbers; + /* Get the number of each key. */ + for (idx_p= index_drop_buffer, idx_end_p= idx_p + index_drop_count; + idx_p < idx_end_p; + idx_p++, keyno_p++) + *keyno_p= *idx_p; + /* + Tell the handler to prepare for drop indexes. + This re-numbers the indexes to get rid of gaps. + */ + if ((error= table->file->prepare_drop_index(table, key_numbers, + index_drop_count))) + { + table->file->print_error(error, MYF(0)); + goto err1; + } + + /* Tell the handler to finally drop the indexes. */ + if ((error= table->file->final_drop_index(table))) + { + table->file->print_error(error, MYF(0)); + goto err1; + } + } + /*end of if (index_drop_count)*/ + + /* + The final .frm file is already created as a temporary file + and will be renamed to the original table name later. + */ + + /* Need to commit before a table is unlocked (NDB requirement). */ + DBUG_PRINT("info", ("Committing before unlocking table")); + if (ha_autocommit_or_rollback(thd, 0) || end_active_trans(thd)) + goto err1; + committed= 1; + } + /*end of if (! new_table) for add/drop index*/ + + if (table->s->tmp_table != NO_TMP_TABLE) + { + /* We changed a temporary table */ + if (error) + goto err1; + /* Close lock if this is a transactional table */ + if (thd->lock) + { + mysql_unlock_tables(thd, thd->lock); + thd->lock=0; + } + /* Remove link to old table and rename the new one */ + close_temporary_table(thd, table, 1, 1); + /* Should pass the 'new_name' as we store table name in the cache */ + if (rename_temporary_table(thd, new_table, new_db, new_name)) + goto err1; + /* We don't replicate alter table statement on temporary tables */ + if (!thd->current_stmt_binlog_row_based) + write_bin_log(thd, TRUE, thd->query, thd->query_length); + goto end_temporary; + } + + if (new_table) + { + /* + Close the intermediate table that will be the new table. + Note that MERGE tables do not have their children attached here. + */ + intern_close_table(new_table); + my_free(new_table,MYF(0)); + } + VOID(pthread_mutex_lock(&LOCK_open)); + if (error) + { + VOID(quick_rm_table(new_db_type, new_db, tmp_name, FN_IS_TMP)); + VOID(pthread_mutex_unlock(&LOCK_open)); + goto err; + } + + /* + Data is copied. Now we: + 1) Wait until all other threads close old version of table. + 2) Close instances of table open by this thread and replace them + with exclusive name-locks. + 3) Rename the old table to a temp name, rename the new one to the + old name. + 4) If we are under LOCK TABLES and don't do ALTER TABLE ... RENAME + we reopen new version of table. + 5) Write statement to the binary log. + 6) If we are under LOCK TABLES and do ALTER TABLE ... RENAME we + remove name-locks from list of open tables and table cache. + 7) If we are not not under LOCK TABLES we rely on close_thread_tables() + call to remove name-locks from table cache and list of open table. + */ + + thd_proc_info(thd, "rename result table"); + my_snprintf(old_name, sizeof(old_name), "%s2-%lx-%lx", tmp_file_prefix, + current_pid, thd->thread_id); + if (lower_case_table_names) + my_casedn_str(files_charset_info, old_name); + + wait_while_table_is_used(thd, table, HA_EXTRA_PREPARE_FOR_RENAME); + close_data_files_and_morph_locks(thd, db, table_name); + + error=0; + save_old_db_type= old_db_type; + + /* + This leads to the storage engine (SE) not being notified for renames in + mysql_rename_table(), because we just juggle with the FRM and nothing + more. If we have an intermediate table, then we notify the SE that + it should become the actual table. Later, we will recycle the old table. + However, in case of ALTER TABLE RENAME there might be no intermediate + table. This is when the old and new tables are compatible, according to + compare_table(). Then, we need one additional call to + mysql_rename_table() with flag NO_FRM_RENAME, which does nothing else but + actual rename in the SE and the FRM is not touched. Note that, if the + table is renamed and the SE is also changed, then an intermediate table + is created and the additional call will not take place. + */ + if (need_copy_table == ALTER_TABLE_METADATA_ONLY) + { + DBUG_ASSERT(new_db_type == old_db_type); + /* This type cannot happen in regular ALTER. */ + new_db_type= old_db_type= NULL; + } + if (mysql_rename_table(old_db_type, db, table_name, db, old_name, + FN_TO_IS_TMP)) + { + error=1; + VOID(quick_rm_table(new_db_type, new_db, tmp_name, FN_IS_TMP)); + } + else if (mysql_rename_table(new_db_type, new_db, tmp_name, new_db, + new_alias, FN_FROM_IS_TMP) || + ((new_name != table_name || new_db != db) && // we also do rename + (need_copy_table != ALTER_TABLE_METADATA_ONLY || + mysql_rename_table(save_old_db_type, db, table_name, new_db, + new_alias, NO_FRM_RENAME)) && + Table_triggers_list::change_table_name(thd, db, table_name, + new_db, new_alias))) + { + /* Try to get everything back. */ + error=1; + VOID(quick_rm_table(new_db_type,new_db,new_alias, 0)); + VOID(quick_rm_table(new_db_type, new_db, tmp_name, FN_IS_TMP)); + VOID(mysql_rename_table(old_db_type, db, old_name, db, alias, + FN_FROM_IS_TMP)); + } + + if (error) + { + /* This shouldn't happen. But let us play it safe. */ + goto err_with_placeholders; + } + + if (need_copy_table == ALTER_TABLE_METADATA_ONLY) + { + /* + Now we have to inform handler that new .FRM file is in place. + To do this we need to obtain a handler object for it. + NO need to tamper with MERGE tables. The real open is done later. + */ + TABLE *t_table; + if (new_name != table_name || new_db != db) + { + table_list->alias= new_name; + table_list->table_name= new_name; + table_list->table_name_length= strlen(new_name); + table_list->db= new_db; + table_list->db_length= strlen(new_db); + table_list->table= name_lock; + if (reopen_name_locked_table(thd, table_list, FALSE)) + goto err_with_placeholders; + t_table= table_list->table; + } + else + { + if (reopen_table(table)) + goto err_with_placeholders; + t_table= table; + } + /* Tell the handler that a new frm file is in place. */ + if (t_table->file->ha_create_handler_files(path, NULL, CHF_INDEX_FLAG, + create_info)) + goto err_with_placeholders; + if (thd->locked_tables && new_name == table_name && new_db == db) + { + /* + We are going to reopen table down on the road, so we have to restore + state of the TABLE object which we used for obtaining of handler + object to make it suitable for reopening. + */ + DBUG_ASSERT(t_table == table); + table->open_placeholder= 1; + close_handle_and_leave_table_as_lock(table); + } + } + + VOID(quick_rm_table(old_db_type, db, old_name, FN_IS_TMP)); + + if (thd->locked_tables && new_name == table_name && new_db == db) + { + thd->in_lock_tables= 1; + error= reopen_tables(thd, 1, 1); + thd->in_lock_tables= 0; + if (error) + goto err_with_placeholders; + } + VOID(pthread_mutex_unlock(&LOCK_open)); + + thd_proc_info(thd, "end"); + + DBUG_EXECUTE_IF("sleep_alter_before_main_binlog", my_sleep(6000000);); + + ha_binlog_log_query(thd, create_info->db_type, LOGCOM_ALTER_TABLE, + thd->query, thd->query_length, + db, table_name); + + DBUG_ASSERT(!(mysql_bin_log.is_open() && + thd->current_stmt_binlog_row_based && + (create_info->options & HA_LEX_CREATE_TMP_TABLE))); + write_bin_log(thd, TRUE, thd->query, thd->query_length); + + if (ha_check_storage_engine_flag(old_db_type, HTON_FLUSH_AFTER_RENAME)) + { + /* + For the alter table to be properly flushed to the logs, we + have to open the new table. If not, we get a problem on server + shutdown. But we do not need to attach MERGE children. + */ + char path[FN_REFLEN]; + TABLE *t_table; + build_table_filename(path + 1, sizeof(path) - 1, new_db, table_name, "", 0); + t_table= open_temporary_table(thd, path, new_db, tmp_name, 0); + if (t_table) + { + intern_close_table(t_table); + my_free(t_table, MYF(0)); + } + else + sql_print_warning("Could not open table %s.%s after rename\n", + new_db,table_name); + ha_flush_logs(old_db_type); + } + table_list->table=0; // For query cache + query_cache_invalidate3(thd, table_list, 0); + + if (thd->locked_tables && (new_name != table_name || new_db != db)) + { + /* + If are we under LOCK TABLES and did ALTER TABLE with RENAME we need + to remove placeholders for the old table and for the target table + from the list of open tables and table cache. If we are not under + LOCK TABLES we can rely on close_thread_tables() doing this job. + */ + pthread_mutex_lock(&LOCK_open); + unlink_open_table(thd, table, FALSE); + unlink_open_table(thd, name_lock, FALSE); + pthread_mutex_unlock(&LOCK_open); + } + +end_temporary: + my_snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO), + (ulong) (copied + deleted), (ulong) deleted, + (ulong) thd->cuted_fields); + my_ok(thd, copied + deleted, 0L, tmp_name); + thd->some_tables_deleted=0; + DBUG_RETURN(FALSE); + +err1: + if (new_table) + { + /* close_temporary_table() frees the new_table pointer. */ + close_temporary_table(thd, new_table, 1, 1); + } + else + VOID(quick_rm_table(new_db_type, new_db, tmp_name, + create_info->frm_only + ? FN_IS_TMP | FRM_ONLY + : FN_IS_TMP)); + +err: + /* + No default value was provided for a DATE/DATETIME field, the + current sql_mode doesn't allow the '0000-00-00' value and + the table to be altered isn't empty. + Report error here. + */ + if (alter_info->error_if_not_empty && thd->row_count) + { + const char *f_val= 0; + enum enum_mysql_timestamp_type t_type= MYSQL_TIMESTAMP_DATE; + switch (alter_info->datetime_field->sql_type) + { + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_NEWDATE: + f_val= "0000-00-00"; + t_type= MYSQL_TIMESTAMP_DATE; + break; + case MYSQL_TYPE_DATETIME: + f_val= "0000-00-00 00:00:00"; + t_type= MYSQL_TIMESTAMP_DATETIME; + break; + default: + /* Shouldn't get here. */ + DBUG_ASSERT(0); + } + bool save_abort_on_warning= thd->abort_on_warning; + thd->abort_on_warning= TRUE; + make_truncated_value_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, + f_val, strlength(f_val), t_type, + alter_info->datetime_field->field_name); + thd->abort_on_warning= save_abort_on_warning; + } + if (name_lock) + { + pthread_mutex_lock(&LOCK_open); + unlink_open_table(thd, name_lock, FALSE); + pthread_mutex_unlock(&LOCK_open); + } + DBUG_RETURN(TRUE); + +err_with_placeholders: + /* + An error happened while we were holding exclusive name-lock on table + being altered. To be safe under LOCK TABLES we should remove placeholders + from list of open tables list and table cache. + */ + unlink_open_table(thd, table, FALSE); + if (name_lock) + unlink_open_table(thd, name_lock, FALSE); + VOID(pthread_mutex_unlock(&LOCK_open)); + DBUG_RETURN(TRUE); +} +/* mysql_alter_table */ + +static int +copy_data_between_tables(TABLE *from,TABLE *to, + List &create, + bool ignore, + uint order_num, ORDER *order, + ha_rows *copied, + ha_rows *deleted, + enum enum_enable_or_disable keys_onoff, + bool error_if_not_empty) +{ + int error; + Copy_field *copy,*copy_end; + ulong found_count,delete_count; + THD *thd= current_thd; + uint length= 0; + SORT_FIELD *sortorder; + READ_RECORD info; + TABLE_LIST tables; + List fields; + List all_fields; + ha_rows examined_rows; + bool auto_increment_field_copied= 0; + ulong save_sql_mode; + ulonglong prev_insert_id; + DBUG_ENTER("copy_data_between_tables"); + + /* + Turn off recovery logging since rollback of an alter table is to + delete the new table so there is no need to log the changes to it. + + This needs to be done before external_lock + */ + error= ha_enable_transaction(thd, FALSE); + if (error) + DBUG_RETURN(-1); + + if (!(copy= new Copy_field[to->s->fields])) + DBUG_RETURN(-1); /* purecov: inspected */ + + if (to->file->ha_external_lock(thd, F_WRLCK)) + DBUG_RETURN(-1); + + /* We need external lock before we can disable/enable keys */ + alter_table_manage_keys(to, from->file->indexes_are_disabled(), keys_onoff); + + /* We can abort alter table for any table type */ + thd->abort_on_warning= !ignore && test(thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES)); + + from->file->info(HA_STATUS_VARIABLE); + to->file->ha_start_bulk_insert(from->file->stats.records); + + save_sql_mode= thd->variables.sql_mode; + + List_iterator it(create); + Create_field *def; + copy_end=copy; + for (Field **ptr=to->field ; *ptr ; ptr++) + { + def=it++; + if (def->field) + { + if (*ptr == to->next_number_field) + { + auto_increment_field_copied= TRUE; + /* + If we are going to copy contents of one auto_increment column to + another auto_increment column it is sensible to preserve zeroes. + This condition also covers case when we are don't actually alter + auto_increment column. + */ + if (def->field == from->found_next_number_field) + thd->variables.sql_mode|= MODE_NO_AUTO_VALUE_ON_ZERO; + } + (copy_end++)->set(*ptr,def->field,0); + } + + } + + found_count=delete_count=0; + + if (order) + { + if (to->s->primary_key != MAX_KEY && to->file->primary_key_is_clustered()) + { + char warn_buff[MYSQL_ERRMSG_SIZE]; + my_snprintf(warn_buff, sizeof(warn_buff), + "ORDER BY ignored as there is a user-defined clustered index" + " in the table '%-.192s'", from->s->table_name.str); + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, + warn_buff); + } + else + { + from->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), + MYF(MY_FAE | MY_ZEROFILL)); + bzero((char *) &tables, sizeof(tables)); + tables.table= from; + tables.alias= tables.table_name= from->s->table_name.str; + tables.db= from->s->db.str; + error= 1; + + if (thd->lex->select_lex.setup_ref_array(thd, order_num) || + setup_order(thd, thd->lex->select_lex.ref_pointer_array, + &tables, fields, all_fields, order) || + !(sortorder= make_unireg_sortorder(order, &length, NULL)) || + (from->sort.found_records= filesort(thd, from, sortorder, length, + (SQL_SELECT *) 0, HA_POS_ERROR, + 1, &examined_rows)) == + HA_POS_ERROR) + goto err; + } + }; + + /* Tell handler that we have values for all columns in the to table */ + to->use_all_columns(); + init_read_record(&info, thd, from, (SQL_SELECT *) 0, 1, 1, FALSE); + if (ignore) + to->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + thd->row_count= 0; + restore_record(to, s->default_values); // Create empty record + while (!(error=info.read_record(&info))) + { + if (thd->killed) + { + thd->send_kill_message(); + error= 1; + break; + } + thd->row_count++; + /* Return error if source table isn't empty. */ + if (error_if_not_empty) + { + error= 1; + break; + } + if (to->next_number_field) + { + if (auto_increment_field_copied) + to->auto_increment_field_not_null= TRUE; + else + to->next_number_field->reset(); + } + + for (Copy_field *copy_ptr=copy ; copy_ptr != copy_end ; copy_ptr++) + { + copy_ptr->do_copy(copy_ptr); + } + prev_insert_id= to->file->next_insert_id; + error=to->file->ha_write_row(to->record[0]); + to->auto_increment_field_not_null= FALSE; + if (error) + { + if (!ignore || + to->file->is_fatal_error(error, HA_CHECK_DUP)) + { + if (!to->file->is_fatal_error(error, HA_CHECK_DUP)) + { + uint key_nr= to->file->get_dup_key(error); + if ((int) key_nr >= 0) + { + const char *err_msg= ER(ER_DUP_ENTRY_WITH_KEY_NAME); + if (key_nr == 0 && + (to->key_info[0].key_part[0].field->flags & + AUTO_INCREMENT_FLAG)) + err_msg= ER(ER_DUP_ENTRY_AUTOINCREMENT_CASE); + to->file->print_keydup_error(key_nr, err_msg); + break; + } + } + + to->file->print_error(error,MYF(0)); + break; + } + to->file->restore_auto_increment(prev_insert_id); + delete_count++; + } + else + found_count++; + } + end_read_record(&info); + free_io_cache(from); + delete [] copy; // This is never 0 + + if (to->file->ha_end_bulk_insert() && error <= 0) + { + to->file->print_error(my_errno,MYF(0)); + error=1; + } + to->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + + if (ha_enable_transaction(thd, TRUE)) + { + error= 1; + goto err; + } + + /* + Ensure that the new table is saved properly to disk so that we + can do a rename + */ + if (ha_autocommit_or_rollback(thd, 0)) + error=1; + if (end_active_trans(thd)) + error=1; + + err: + thd->variables.sql_mode= save_sql_mode; + thd->abort_on_warning= 0; + free_io_cache(from); + *copied= found_count; + *deleted=delete_count; + to->file->ha_release_auto_increment(); + if (to->file->ha_external_lock(thd,F_UNLCK)) + error=1; + DBUG_RETURN(error > 0 ? -1 : 0); +} + + +/* + Recreates tables by calling mysql_alter_table(). + + SYNOPSIS + mysql_recreate_table() + thd Thread handler + tables Tables to recreate + + RETURN + Like mysql_alter_table(). +*/ +bool mysql_recreate_table(THD *thd, TABLE_LIST *table_list) +{ + HA_CREATE_INFO create_info; + Alter_info alter_info; + + DBUG_ENTER("mysql_recreate_table"); + DBUG_ASSERT(!table_list->next_global); + /* + table_list->table has been closed and freed. Do not reference + uninitialized data. open_tables() could fail. + */ + table_list->table= NULL; + + bzero((char*) &create_info, sizeof(create_info)); + create_info.row_type=ROW_TYPE_NOT_USED; + create_info.default_table_charset=default_charset_info; + /* Force alter table to recreate table */ + alter_info.flags= (ALTER_CHANGE_COLUMN | ALTER_RECREATE); + DBUG_RETURN(mysql_alter_table(thd, NullS, NullS, &create_info, + table_list, &alter_info, 0, + (ORDER *) 0, 0)); +} + + +bool mysql_checksum_table(THD *thd, TABLE_LIST *tables, + HA_CHECK_OPT *check_opt) +{ + TABLE_LIST *table; + List field_list; + Item *item; + Protocol *protocol= thd->protocol; + DBUG_ENTER("mysql_checksum_table"); + + field_list.push_back(item = new Item_empty_string("Table", NAME_LEN*2)); + item->maybe_null= 1; + field_list.push_back(item= new Item_int("Checksum", (longlong) 1, + MY_INT64_NUM_DECIMAL_DIGITS)); + item->maybe_null= 1; + if (protocol->send_fields(&field_list, + Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) + DBUG_RETURN(TRUE); + + /* Open one table after the other to keep lock time as short as possible. */ + for (table= tables; table; table= table->next_local) + { + char table_name[NAME_LEN*2+2]; + TABLE *t; + + strxmov(table_name, table->db ,".", table->table_name, NullS); + + t= table->table= open_n_lock_single_table(thd, table, TL_READ); + thd->clear_error(); // these errors shouldn't get client + + protocol->prepare_for_resend(); + protocol->store(table_name, system_charset_info); + + if (!t) + { + /* Table didn't exist */ + protocol->store_null(); + thd->clear_error(); + } + else + { + if (t->file->ha_table_flags() & HA_HAS_CHECKSUM && + !(check_opt->flags & T_EXTEND)) + protocol->store((ulonglong)t->file->checksum()); + else if (!(t->file->ha_table_flags() & HA_HAS_CHECKSUM) && + (check_opt->flags & T_QUICK)) + protocol->store_null(); + else + { + /* calculating table's checksum */ + ha_checksum crc= 0; + uchar null_mask=256 - (1 << t->s->last_null_bit_pos); + + t->use_all_columns(); + + if (t->file->ha_rnd_init(1)) + protocol->store_null(); + else + { + for (;;) + { + if (thd->killed) + { + /* + we've been killed; let handler clean up, and remove the + partial current row from the recordset (embedded lib) + */ + t->file->ha_rnd_end(); + thd->protocol->remove_last_row(); + goto err; + } + ha_checksum row_crc= 0; + int error= t->file->rnd_next(t->record[0]); + if (unlikely(error)) + { + if (error == HA_ERR_RECORD_DELETED) + continue; + break; + } + if (t->s->null_bytes) + { + /* fix undefined null bits */ + t->record[0][t->s->null_bytes-1] |= null_mask; + if (!(t->s->db_create_options & HA_OPTION_PACK_RECORD)) + t->record[0][0] |= 1; + + row_crc= my_checksum(row_crc, t->record[0], t->s->null_bytes); + } + + for (uint i= 0; i < t->s->fields; i++ ) + { + Field *f= t->field[i]; + if ((f->type() == MYSQL_TYPE_BLOB) || + (f->type() == MYSQL_TYPE_VARCHAR)) + { + String tmp; + f->val_str(&tmp); + row_crc= my_checksum(row_crc, (uchar*) tmp.ptr(), tmp.length()); + } + else + row_crc= my_checksum(row_crc, f->ptr, + f->pack_length()); + } + + crc+= row_crc; + } + protocol->store((ulonglong)crc); + t->file->ha_rnd_end(); + } + } + thd->clear_error(); + close_thread_tables(thd); + table->table=0; // For query cache + } + if (protocol->write()) + goto err; + } + + my_eof(thd); + DBUG_RETURN(FALSE); + + err: + close_thread_tables(thd); // Shouldn't be needed + if (table) + table->table=0; + DBUG_RETURN(TRUE); +} + +static bool check_engine(THD *thd, const char *table_name, + HA_CREATE_INFO *create_info) +{ + handlerton **new_engine= &create_info->db_type; + handlerton *req_engine= *new_engine; + bool no_substitution= + test(thd->variables.sql_mode & MODE_NO_ENGINE_SUBSTITUTION); + if (!(*new_engine= ha_checktype(thd, ha_legacy_type(req_engine), + no_substitution, 1))) + return TRUE; + + if (req_engine && req_engine != *new_engine) + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_WARN_USING_OTHER_HANDLER, + ER(ER_WARN_USING_OTHER_HANDLER), + ha_resolve_storage_engine_name(*new_engine), + table_name); + } + if (create_info->options & HA_LEX_CREATE_TMP_TABLE && + ha_check_storage_engine_flag(*new_engine, HTON_TEMPORARY_NOT_SUPPORTED)) + { + if (create_info->used_fields & HA_CREATE_USED_ENGINE) + { + my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), + ha_resolve_storage_engine_name(*new_engine), "TEMPORARY"); + *new_engine= 0; + return TRUE; + } + *new_engine= myisam_hton; + } + return FALSE; +} diff --git a/dbcon/mysql/sql_update.cc b/dbcon/mysql/sql_update.cc new file mode 100644 index 00000000..d46d4cbe --- /dev/null +++ b/dbcon/mysql/sql_update.cc @@ -0,0 +1,2138 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* + Single table and multi table updates of tables. + Multi-table updates were introduced by Sinisa & Monty +*/ + +#include "mysql_priv.h" +#include "sql_select.h" +#include "sp_head.h" +#include "sql_trigger.h" + +/* Return 0 if row hasn't changed */ + +bool compare_record(TABLE *table) +{ + if (table->s->blob_fields + table->s->varchar_fields == 0) + return cmp_record(table,record[1]); + /* Compare null bits */ + if (memcmp(table->null_flags, + table->null_flags+table->s->rec_buff_length, + table->s->null_bytes)) + return TRUE; // Diff in NULL value + /* Compare updated fields */ + for (Field **ptr= table->field ; *ptr ; ptr++) + { + if (bitmap_is_set(table->write_set, (*ptr)->field_index) && + (*ptr)->cmp_binary_offset(table->s->rec_buff_length)) + return TRUE; + } + return FALSE; +} + + +/* + check that all fields are real fields + + SYNOPSIS + check_fields() + thd thread handler + items Items for check + + RETURN + TRUE Items can't be used in UPDATE + FALSE Items are OK +*/ + +static bool check_fields(THD *thd, List &items) +{ + List_iterator it(items); + Item *item; + Item_field *field; + + while ((item= it++)) + { + if (!(field= item->filed_for_view_update())) + { + /* item has name, because it comes from VIEW SELECT list */ + my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), item->name); + return TRUE; + } + /* + we make temporary copy of Item_field, to avoid influence of changing + result_field on Item_ref which refer on this field + */ + thd->change_item_tree(it.ref(), new Item_field(thd, field)); + } + return FALSE; +} + + +/** + Re-read record if more columns are needed for error message. + + If we got a duplicate key error, we want to write an error + message containing the value of the duplicate key. If we do not have + all fields of the key value in record[0], we need to re-read the + record with a proper read_set. + + @param[in] error error number + @param[in] table table +*/ + +static void prepare_record_for_error_message(int error, TABLE *table) +{ + Field **field_p; + Field *field; + uint keynr; + MY_BITMAP unique_map; /* Fields in offended unique. */ + my_bitmap_map unique_map_buf[bitmap_buffer_size(MAX_FIELDS)]; + DBUG_ENTER("prepare_record_for_error_message"); + + /* + Only duplicate key errors print the key value. + If storage engine does always read all columns, we have the value alraedy. + */ + if ((error != HA_ERR_FOUND_DUPP_KEY) || + !(table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ)) + DBUG_VOID_RETURN; + + /* + Get the number of the offended index. + We will see MAX_KEY if the engine cannot determine the affected index. + */ + if ((keynr= table->file->get_dup_key(error)) >= MAX_KEY) + DBUG_VOID_RETURN; + + /* Create unique_map with all fields used by that index. */ + bitmap_init(&unique_map, unique_map_buf, table->s->fields, FALSE); + table->mark_columns_used_by_index_no_reset(keynr, &unique_map); + + /* Subtract read_set and write_set. */ + bitmap_subtract(&unique_map, table->read_set); + bitmap_subtract(&unique_map, table->write_set); + + /* + If the unique index uses columns that are neither in read_set + nor in write_set, we must re-read the record. + Otherwise no need to do anything. + */ + if (bitmap_is_clear_all(&unique_map)) + DBUG_VOID_RETURN; + + /* Get identifier of last read record into table->file->ref. */ + table->file->position(table->record[0]); + /* Add all fields used by unique index to read_set. */ + bitmap_union(table->read_set, &unique_map); + /* Tell the engine about the new set. */ + table->file->column_bitmaps_signal(); + /* Read record that is identified by table->file->ref. */ + (void) table->file->rnd_pos(table->record[1], table->file->ref); + /* Copy the newly read columns into the new record. */ + for (field_p= table->field; (field= *field_p); field_p++) + if (bitmap_is_set(&unique_map, field->field_index)) + field->copy_from_tmp(table->s->rec_buff_length); + + DBUG_VOID_RETURN; +} + + +/* + Process usual UPDATE + + SYNOPSIS + mysql_update() + thd thread handler + fields fields for update + values values of fields for update + conds WHERE clause expression + order_num number of elemen in ORDER BY clause + order ORDER BY clause list + limit limit clause + handle_duplicates how to handle duplicates + + RETURN + 0 - OK + 2 - privilege check and openning table passed, but we need to convert to + multi-update because of view substitution + 1 - error +*/ +// @InfiniDB. Make conds argument reference to pointer so the optimization +// result can be passed in to the InfiniDB connector. +int mysql_update(THD *thd, + TABLE_LIST *table_list, + List &fields, + List &values, + COND *& conds, + uint order_num, ORDER *order, + ha_rows limit, + enum enum_duplicates handle_duplicates, bool ignore) +{ + bool using_limit= limit != HA_POS_ERROR; + bool safe_update= test(thd->options & OPTION_SAFE_UPDATES); + bool used_key_is_modified, transactional_table, will_batch; + bool can_compare_record; + int res; + int error, loc_error; + uint used_index= MAX_KEY, dup_key_found; + bool need_sort= TRUE; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + uint want_privilege; +#endif + uint table_count= 0; + ha_rows updated, found; + key_map old_covering_keys; + TABLE *table; + SQL_SELECT *select; + READ_RECORD info; + SELECT_LEX *select_lex= &thd->lex->select_lex; + bool need_reopen; + ulonglong id; + List all_fields; + THD::killed_state killed_status= THD::NOT_KILLED; + DBUG_ENTER("mysql_update"); + + for ( ; ; ) + { + if (open_tables(thd, &table_list, &table_count, 0)) + DBUG_RETURN(1); + + if (table_list->multitable_view) + { + DBUG_ASSERT(table_list->view != 0); + DBUG_PRINT("info", ("Switch to multi-update")); + /* pass counter value */ + thd->lex->table_count= table_count; + /* convert to multiupdate */ + DBUG_RETURN(2); + } + if (!lock_tables(thd, table_list, table_count, &need_reopen)) + break; + if (!need_reopen) + DBUG_RETURN(1); + close_tables_for_reopen(thd, &table_list); + } + + if (mysql_handle_derived(thd->lex, &mysql_derived_prepare) || + (thd->fill_derived_tables() && + mysql_handle_derived(thd->lex, &mysql_derived_filling))) + DBUG_RETURN(1); + + thd_proc_info(thd, "init"); + table= table_list->table; + + /* Calculate "table->covering_keys" based on the WHERE */ + table->covering_keys= table->s->keys_in_use; + table->quick_keys.clear_all(); + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* Force privilege re-checking for views after they have been opened. */ + want_privilege= (table_list->view ? UPDATE_ACL : + table_list->grant.want_privilege); +#endif + if (mysql_prepare_update(thd, table_list, &conds, order_num, order)) + DBUG_RETURN(1); + + old_covering_keys= table->covering_keys; // Keys used in WHERE + /* Check the fields we are going to modify */ +#ifndef NO_EMBEDDED_ACCESS_CHECKS + table_list->grant.want_privilege= table->grant.want_privilege= want_privilege; + table_list->register_want_access(want_privilege); +#endif + if (setup_fields_with_no_wrap(thd, 0, fields, MARK_COLUMNS_WRITE, 0, 0)) + DBUG_RETURN(1); /* purecov: inspected */ + if (table_list->view && check_fields(thd, fields)) + { + DBUG_RETURN(1); + } + if (!table_list->updatable || check_key_in_view(thd, table_list)) + { + my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "UPDATE"); + DBUG_RETURN(1); + } + if (table->timestamp_field) + { + // Don't set timestamp column if this is modified + if (bitmap_is_set(table->write_set, + table->timestamp_field->field_index)) + table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET; + else + { + if (table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_UPDATE || + table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH) + bitmap_set_bit(table->write_set, + table->timestamp_field->field_index); + } + } + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* Check values */ + table_list->grant.want_privilege= table->grant.want_privilege= + (SELECT_ACL & ~table->grant.privilege); +#endif + if (setup_fields(thd, 0, values, MARK_COLUMNS_READ, 0, 0)) + { + free_underlaid_joins(thd, select_lex); + DBUG_RETURN(1); /* purecov: inspected */ + } + + if (select_lex->inner_refs_list.elements && + fix_inner_refs(thd, all_fields, select_lex, select_lex->ref_pointer_array)) + DBUG_RETURN(1); + + if (conds) + { + Item::cond_result cond_value; + conds= remove_eq_conds(thd, conds, &cond_value); + if (cond_value == Item::COND_FALSE) + limit= 0; // Impossible WHERE + } + + /* + If a timestamp field settable on UPDATE is present then to avoid wrong + update force the table handler to retrieve write-only fields to be able + to compare records and detect data change. + */ + if (table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ && + table->timestamp_field && + (table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_UPDATE || + table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH)) + bitmap_union(table->read_set, table->write_set); + // Don't count on usage of 'only index' when calculating which key to use + table->covering_keys.clear_all(); + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (prune_partitions(thd, table, conds)) + { + free_underlaid_joins(thd, select_lex); + my_ok(thd); // No matching records + DBUG_RETURN(0); + } +#endif + /* Update the table->file->stats.records number */ + table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); + + select= make_select(table, 0, 0, conds, 0, &error); + if (error || !limit || + (select && select->check_quick(thd, safe_update, limit))) + { + delete select; + free_underlaid_joins(thd, select_lex); + /* + There was an error or the error was already sent by + the quick select evaluation. + TODO: Add error code output parameter to Item::val_xxx() methods. + Currently they rely on the user checking DA for + errors when unwinding the stack after calling Item::val_xxx(). + */ + if (error || thd->is_error()) + { + DBUG_RETURN(1); // Error in where + } + my_ok(thd); // No matching records + DBUG_RETURN(0); + } + if (!select && limit != HA_POS_ERROR) + { + if ((used_index= get_index_for_order(table, order, limit)) != MAX_KEY) + need_sort= FALSE; + } + /* If running in safe sql mode, don't allow updates without keys */ + if (table->quick_keys.is_clear_all()) + { + thd->server_status|=SERVER_QUERY_NO_INDEX_USED; + if (safe_update && !using_limit) + { + my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE, + ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0)); + goto err; + } + } + init_ftfuncs(thd, select_lex, 1); + + table->mark_columns_needed_for_update(); + + /* Check if we are modifying a key that we are used to search with */ + + if (select && select->quick) + { + used_index= select->quick->index; + used_key_is_modified= (!select->quick->unique_key_range() && + select->quick->is_keys_used(table->write_set)); + } + else + { + used_key_is_modified= 0; + if (used_index == MAX_KEY) // no index for sort order + used_index= table->file->key_used_on_scan; + if (used_index != MAX_KEY) + used_key_is_modified= is_key_used(table, used_index, table->write_set); + } + + +#ifdef WITH_PARTITION_STORAGE_ENGINE + if (used_key_is_modified || order || + partition_key_modified(table, table->write_set)) +#else + if (used_key_is_modified || order) +#endif + { + /* + We can't update table directly; We must first search after all + matching rows before updating the table! + */ + if (used_index < MAX_KEY && old_covering_keys.is_set(used_index)) + { + table->key_read=1; + table->mark_columns_used_by_index(used_index); + } + else + { + table->use_all_columns(); + } + + /* note: We avoid sorting avoid if we sort on the used index */ + if (order && (need_sort || used_key_is_modified)) + { + /* + Doing an ORDER BY; Let filesort find and sort the rows we are going + to update + NOTE: filesort will call table->prepare_for_position() + */ + uint length= 0; + SORT_FIELD *sortorder; + ha_rows examined_rows; + + table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE), + MYF(MY_FAE | MY_ZEROFILL)); + if (!(sortorder=make_unireg_sortorder(order, &length, NULL)) || + (table->sort.found_records= filesort(thd, table, sortorder, length, + select, limit, 1, + &examined_rows)) + == HA_POS_ERROR) + { + goto err; + } + /* + Filesort has already found and selected the rows we want to update, + so we don't need the where clause + */ + delete select; + select= 0; + } + else + { + /* + We are doing a search on a key that is updated. In this case + we go trough the matching rows, save a pointer to them and + update these in a separate loop based on the pointer. + */ + + IO_CACHE tempfile; + if (open_cached_file(&tempfile, mysql_tmpdir,TEMP_PREFIX, + DISK_BUFFER_SIZE, MYF(MY_WME))) + goto err; + + /* If quick select is used, initialize it before retrieving rows. */ + if (select && select->quick && select->quick->reset()) + goto err; + table->file->try_semi_consistent_read(1); + + /* + When we get here, we have one of the following options: + A. used_index == MAX_KEY + This means we should use full table scan, and start it with + init_read_record call + B. used_index != MAX_KEY + B.1 quick select is used, start the scan with init_read_record + B.2 quick select is not used, this is full index scan (with LIMIT) + Full index scan must be started with init_read_record_idx + */ + + if (used_index == MAX_KEY || (select && select->quick)) + init_read_record(&info, thd, table, select, 0, 1, FALSE); + else + init_read_record_idx(&info, thd, table, 1, used_index); + + thd_proc_info(thd, "Searching rows for update"); + ha_rows tmp_limit= limit; + + while (!(error=info.read_record(&info)) && !thd->killed) + { + if (!(select && select->skip_record())) + { + if (table->file->was_semi_consistent_read()) + continue; /* repeat the read of the same row if it still exists */ + + table->file->position(table->record[0]); + if (my_b_write(&tempfile,table->file->ref, + table->file->ref_length)) + { + error=1; /* purecov: inspected */ + break; /* purecov: inspected */ + } + if (!--limit && using_limit) + { + error= -1; + break; + } + } + else + table->file->unlock_row(); + } + if (thd->killed && !error) + error= 1; // Aborted + limit= tmp_limit; + table->file->try_semi_consistent_read(0); + end_read_record(&info); + + /* Change select to use tempfile */ + if (select) + { + delete select->quick; + if (select->free_cond) + delete select->cond; + select->quick=0; + select->cond=0; + } + else + { + select= new SQL_SELECT; + select->head=table; + } + if (reinit_io_cache(&tempfile,READ_CACHE,0L,0,0)) + error=1; /* purecov: inspected */ + select->file=tempfile; // Read row ptrs from this file + if (error >= 0) + goto err; + } + if (table->key_read) + table->restore_column_maps_after_mark_index(); + } + + if (ignore) + table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + + if (select && select->quick && select->quick->reset()) + goto err; + table->file->try_semi_consistent_read(1); + init_read_record(&info, thd, table, select, 0, 1, FALSE); + + updated= found= 0; + /* + Generate an error (in TRADITIONAL mode) or warning + when trying to set a NOT NULL field to NULL. + */ + thd->count_cuted_fields= CHECK_FIELD_WARN; + thd->cuted_fields=0L; + thd_proc_info(thd, "Updating"); + + transactional_table= table->file->has_transactions(); + thd->abort_on_warning= test(!ignore && + (thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES))); + if (table->triggers && + table->triggers->has_triggers(TRG_EVENT_UPDATE, + TRG_ACTION_AFTER)) + { + /* + The table has AFTER UPDATE triggers that might access to subject + table and therefore might need update to be done immediately. + So we turn-off the batching. + */ + (void) table->file->extra(HA_EXTRA_UPDATE_CANNOT_BATCH); + will_batch= FALSE; + } + else + will_batch= !table->file->start_bulk_update(); + + /* + Assure that we can use position() + if we need to create an error message. + */ + if (table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ) + table->prepare_for_position(); + + /* + We can use compare_record() to optimize away updates if + the table handler is returning all columns OR if + if all updated columns are read + */ + can_compare_record= (!(table->file->ha_table_flags() & + HA_PARTIAL_COLUMN_READ) || + bitmap_is_subset(table->write_set, table->read_set)); + + while (!(error=info.read_record(&info)) && !thd->killed) + { + if (!(select && select->skip_record())) + { + if (table->file->was_semi_consistent_read()) + continue; /* repeat the read of the same row if it still exists */ + + store_record(table,record[1]); + if (fill_record_n_invoke_before_triggers(thd, fields, values, 0, + table->triggers, + TRG_EVENT_UPDATE)) + break; /* purecov: inspected */ + + found++; + + if (!can_compare_record || compare_record(table)) + { + if ((res= table_list->view_check_option(thd, ignore)) != + VIEW_CHECK_OK) + { + found--; + if (res == VIEW_CHECK_SKIP) + continue; + else if (res == VIEW_CHECK_ERROR) + { + error= 1; + break; + } + } + if (will_batch) + { + /* + Typically a batched handler can execute the batched jobs when: + 1) When specifically told to do so + 2) When it is not a good idea to batch anymore + 3) When it is necessary to send batch for other reasons + (One such reason is when READ's must be performed) + + 1) is covered by exec_bulk_update calls. + 2) and 3) is handled by the bulk_update_row method. + + bulk_update_row can execute the updates including the one + defined in the bulk_update_row or not including the row + in the call. This is up to the handler implementation and can + vary from call to call. + + The dup_key_found reports the number of duplicate keys found + in those updates actually executed. It only reports those if + the extra call with HA_EXTRA_IGNORE_DUP_KEY have been issued. + If this hasn't been issued it returns an error code and can + ignore this number. Thus any handler that implements batching + for UPDATE IGNORE must also handle this extra call properly. + + If a duplicate key is found on the record included in this + call then it should be included in the count of dup_key_found + and error should be set to 0 (only if these errors are ignored). + */ + error= table->file->ha_bulk_update_row(table->record[1], + table->record[0], + &dup_key_found); + limit+= dup_key_found; + updated-= dup_key_found; + } + else + { + /* Non-batched update */ + error= table->file->ha_update_row(table->record[1], + table->record[0]); + } + if (!error || error == HA_ERR_RECORD_IS_THE_SAME) + { + if (error != HA_ERR_RECORD_IS_THE_SAME) + updated++; + else + error= 0; + } + else if (!ignore || + table->file->is_fatal_error(error, HA_CHECK_DUP_KEY)) + { + /* + If (ignore && error is ignorable) we don't have to + do anything; otherwise... + */ + if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY)) + thd->fatal_error(); /* Other handler errors are fatal */ + + prepare_record_for_error_message(error, table); + table->file->print_error(error,MYF(0)); + error= 1; + break; + } + } + + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_UPDATE, + TRG_ACTION_AFTER, TRUE)) + { + error= 1; + break; + } + + if (!--limit && using_limit) + { + /* + We have reached end-of-file in most common situations where no + batching has occurred and if batching was supposed to occur but + no updates were made and finally when the batch execution was + performed without error and without finding any duplicate keys. + If the batched updates were performed with errors we need to + check and if no error but duplicate key's found we need to + continue since those are not counted for in limit. + */ + if (will_batch && + ((error= table->file->exec_bulk_update(&dup_key_found)) || + dup_key_found)) + { + if (error) + { + /* purecov: begin inspected */ + /* + The handler should not report error of duplicate keys if they + are ignored. This is a requirement on batching handlers. + */ + prepare_record_for_error_message(error, table); + table->file->print_error(error,MYF(0)); + error= 1; + break; + /* purecov: end */ + } + /* + Either an error was found and we are ignoring errors or there + were duplicate keys found. In both cases we need to correct + the counters and continue the loop. + */ + limit= dup_key_found; //limit is 0 when we get here so need to + + updated-= dup_key_found; + } + else + { + error= -1; // Simulate end of file + break; + } + } + } + else + table->file->unlock_row(); + thd->row_count++; + if (thd->is_error()) + { + error= 1; + break; + } + } + table->auto_increment_field_not_null= FALSE; + dup_key_found= 0; + /* + Caching the killed status to pass as the arg to query event constuctor; + The cached value can not change whereas the killed status can + (externally) since this point and change of the latter won't affect + binlogging. + It's assumed that if an error was set in combination with an effective + killed status then the error is due to killing. + */ + killed_status= thd->killed; // get the status of the volatile + // simulated killing after the loop must be ineffective for binlogging + DBUG_EXECUTE_IF("simulate_kill_bug27571", + { + thd->killed= THD::KILL_QUERY; + };); + // @Infinidb bug2540. @bug4790. change only for InfiniDB table. + // @bug5117. Add isInfiniDBDML to make sure it's InfiniDB dml stmt. + if (thd->infinidb_vtable.isInfiniDBDML) + if (killed_status != THD::NOT_KILLED || thd->is_error()) + error= 1; + else + error= (killed_status == THD::NOT_KILLED)? error : 1; + + if (error && + will_batch && + (loc_error= table->file->exec_bulk_update(&dup_key_found))) + /* + An error has occurred when a batched update was performed and returned + an error indication. It cannot be an allowed duplicate key error since + we require the batching handler to treat this as a normal behavior. + + Otherwise we simply remove the number of duplicate keys records found + in the batched update. + */ + { + /* purecov: begin inspected */ + thd->fatal_error(); + prepare_record_for_error_message(loc_error, table); + table->file->print_error(loc_error,MYF(0)); + error= 1; + /* purecov: end */ + } + else + updated-= dup_key_found; + if (will_batch) + table->file->end_bulk_update(); + table->file->try_semi_consistent_read(0); + + if (!transactional_table && updated > 0) + thd->transaction.stmt.modified_non_trans_table= TRUE; + + end_read_record(&info); + delete select; + thd_proc_info(thd, "end"); + VOID(table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY)); + + /* + Invalidate the table in the query cache if something changed. + This must be before binlog writing and ha_autocommit_... + */ + if (updated) + { + query_cache_invalidate3(thd, table_list, 1); + } + + /* + error < 0 means really no error at all: we processed all rows until the + last one without error. error > 0 means an error (e.g. unique key + violation and no IGNORE or REPLACE). error == 0 is also an error (if + preparing the record or invoking before triggers fails). See + ha_autocommit_or_rollback(error>=0) and DBUG_RETURN(error>=0) below. + Sometimes we want to binlog even if we updated no rows, in case user used + it to be sure master and slave are in same state. + */ + if ((error < 0) || thd->transaction.stmt.modified_non_trans_table) + { + if (mysql_bin_log.is_open()) + { + int errcode= 0; + if (error < 0) + thd->clear_error(); + else + errcode= query_error_code(thd, killed_status == THD::NOT_KILLED); + + if (thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + transactional_table, FALSE, errcode)) + { + error=1; // Rollback update + } + } + if (thd->transaction.stmt.modified_non_trans_table) + thd->transaction.all.modified_non_trans_table= TRUE; + } + DBUG_ASSERT(transactional_table || !updated || thd->transaction.stmt.modified_non_trans_table); + free_underlaid_joins(thd, select_lex); + + /* If LAST_INSERT_ID(X) was used, report X */ + id= thd->arg_of_last_insert_id_function ? + thd->first_successful_insert_id_in_prev_stmt : 0; + + if (error < 0) + { + char buff[STRING_BUFFER_USUAL_SIZE]; + my_snprintf(buff, sizeof(buff), ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated, + (ulong) thd->cuted_fields); + //@Infinidb bug2936. not set row count to thd to push row count to the front. + // @bug4790. Only change for InfiniDB table. + // @bug5117. Add isInfiniDBDML to make sure it's InfiniDB dml stmt. + if (!(thd->infinidb_vtable.isInfiniDBDML)) + thd->row_count_func=(thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated; + my_ok(thd, (ulong) thd->row_count_func, id, buff); + DBUG_PRINT("info",("%ld records updated", (long) updated)); + } + thd->count_cuted_fields= CHECK_FIELD_IGNORE; /* calc cuted fields */ + thd->abort_on_warning= 0; + DBUG_RETURN((error >= 0 || thd->is_error()) ? 1 : 0); + +err: + delete select; + free_underlaid_joins(thd, select_lex); + if (table->key_read) + { + table->key_read=0; + table->file->extra(HA_EXTRA_NO_KEYREAD); + } + thd->abort_on_warning= 0; + DBUG_RETURN(1); +} + +/* + Prepare items in UPDATE statement + + SYNOPSIS + mysql_prepare_update() + thd - thread handler + table_list - global/local table list + conds - conditions + order_num - number of ORDER BY list entries + order - ORDER BY clause list + + RETURN VALUE + FALSE OK + TRUE error +*/ +bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list, + Item **conds, uint order_num, ORDER *order) +{ + Item *fake_conds= 0; +#ifndef NO_EMBEDDED_ACCESS_CHECKS + TABLE *table= table_list->table; +#endif + List all_fields; + SELECT_LEX *select_lex= &thd->lex->select_lex; + DBUG_ENTER("mysql_prepare_update"); + + /* + Statement-based replication of UPDATE ... LIMIT is not safe as order of + rows is not defined, so in mixed mode we go to row-based. + + Note that we may consider a statement as safe if ORDER BY primary_key + is present. However it may confuse users to see very similiar statements + replicated differently. + */ + if (thd->lex->current_select->select_limit) + { + thd->lex->set_stmt_unsafe(); + thd->set_current_stmt_binlog_row_based_if_mixed(); + } +#ifndef NO_EMBEDDED_ACCESS_CHECKS + table_list->grant.want_privilege= table->grant.want_privilege= + (SELECT_ACL & ~table->grant.privilege); + table_list->register_want_access(SELECT_ACL); +#endif + + thd->lex->allow_sum_func= 0; + + if (setup_tables_and_check_access(thd, &select_lex->context, + &select_lex->top_join_list, + table_list, + &select_lex->leaf_tables, + FALSE, UPDATE_ACL, SELECT_ACL) || + setup_conds(thd, table_list, select_lex->leaf_tables, conds) || + select_lex->setup_ref_array(thd, order_num) || + setup_order(thd, select_lex->ref_pointer_array, + table_list, all_fields, all_fields, order) || + setup_ftfuncs(select_lex)) + DBUG_RETURN(TRUE); + + /* Check that we are not using table that we are updating in a sub select */ + { + TABLE_LIST *duplicate; + if ((duplicate= unique_table(thd, table_list, table_list->next_global, 0))) + { + update_non_unique_table_error(table_list, "UPDATE", duplicate); + my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name); + DBUG_RETURN(TRUE); + } + } + select_lex->fix_prepare_information(thd, conds, &fake_conds); + DBUG_RETURN(FALSE); +} + + +/*************************************************************************** + Update multiple tables from join +***************************************************************************/ + +/* + Get table map for list of Item_field +*/ + +static table_map get_table_map(List *items) +{ + List_iterator_fast item_it(*items); + Item_field *item; + table_map map= 0; + + while ((item= (Item_field *) item_it++)) + map|= item->used_tables(); + DBUG_PRINT("info", ("table_map: 0x%08lx", (long) map)); + return map; +} + + +/* + make update specific preparation and checks after opening tables + + SYNOPSIS + mysql_multi_update_prepare() + thd thread handler + + RETURN + FALSE OK + TRUE Error +*/ + +int mysql_multi_update_prepare(THD *thd) +{ + LEX *lex= thd->lex; + TABLE_LIST *table_list= lex->query_tables; + TABLE_LIST *tl, *leaves; + List *fields= &lex->select_lex.item_list; + table_map tables_for_update; + bool update_view= 0; + /* + if this multi-update was converted from usual update, here is table + counter else junk will be assigned here, but then replaced with real + count in open_tables() + */ + uint table_count= lex->table_count; + const bool using_lock_tables= thd->locked_tables != 0; + bool original_multiupdate= (thd->lex->sql_command == SQLCOM_UPDATE_MULTI); + bool need_reopen= FALSE; + DBUG_ENTER("mysql_multi_update_prepare"); + + /* following need for prepared statements, to run next time multi-update */ + thd->lex->sql_command= SQLCOM_UPDATE_MULTI; + +reopen_tables: + + /* open tables and create derived ones, but do not lock and fill them */ + if (((original_multiupdate || need_reopen) && + open_tables(thd, &table_list, &table_count, 0)) || + mysql_handle_derived(lex, &mysql_derived_prepare)) + DBUG_RETURN(TRUE); + /* + setup_tables() need for VIEWs. JOIN::prepare() will call setup_tables() + second time, but this call will do nothing (there are check for second + call in setup_tables()). + */ + + if (setup_tables_and_check_access(thd, &lex->select_lex.context, + &lex->select_lex.top_join_list, + table_list, + &lex->select_lex.leaf_tables, FALSE, + UPDATE_ACL, SELECT_ACL)) + DBUG_RETURN(TRUE); + + if (setup_fields_with_no_wrap(thd, 0, *fields, MARK_COLUMNS_WRITE, 0, 0)) + DBUG_RETURN(TRUE); + + for (tl= table_list; tl ; tl= tl->next_local) + { + if (tl->view) + { + update_view= 1; + break; + } + } + + if (update_view && check_fields(thd, *fields)) + { + DBUG_RETURN(TRUE); + } + + thd->table_map_for_update= tables_for_update= get_table_map(fields); + + /* + Setup timestamp handling and locking mode + */ + leaves= lex->select_lex.leaf_tables; + for (tl= leaves; tl; tl= tl->next_leaf) + { + TABLE *table= tl->table; + /* Only set timestamp column if this is not modified */ + if (table->timestamp_field && + bitmap_is_set(table->write_set, + table->timestamp_field->field_index)) + table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET; + + /* if table will be updated then check that it is unique */ + if (table->map & tables_for_update) + { + if (!tl->updatable || check_key_in_view(thd, tl)) + { + my_error(ER_NON_UPDATABLE_TABLE, MYF(0), tl->alias, "UPDATE"); + DBUG_RETURN(TRUE); + } + + DBUG_PRINT("info",("setting table `%s` for update", tl->alias)); + /* + If table will be updated we should not downgrade lock for it and + leave it as is. + */ + } + else + { + DBUG_PRINT("info",("setting table `%s` for read-only", tl->alias)); + /* + If we are using the binary log, we need TL_READ_NO_INSERT to get + correct order of statements. Otherwise, we use a TL_READ lock to + improve performance. + */ + tl->lock_type= read_lock_type_for_table(thd, table); + tl->updating= 0; + /* Update TABLE::lock_type accordingly. */ + if (!tl->placeholder() && !using_lock_tables) + tl->table->reginfo.lock_type= tl->lock_type; + } + } + for (tl= table_list; tl; tl= tl->next_local) + { + /* Check access privileges for table */ + if (!tl->derived) + { + uint want_privilege= tl->updating ? UPDATE_ACL : SELECT_ACL; + if (check_access(thd, want_privilege, + tl->db, &tl->grant.privilege, 0, 0, + test(tl->schema_table)) || + check_grant(thd, want_privilege, tl, 0, 1, 0)) + DBUG_RETURN(TRUE); + } + } + + /* check single table update for view compound from several tables */ + for (tl= table_list; tl; tl= tl->next_local) + { + if (tl->effective_algorithm == VIEW_ALGORITHM_MERGE) + { + TABLE_LIST *for_update= 0; + if (tl->check_single_table(&for_update, tables_for_update, tl)) + { + my_error(ER_VIEW_MULTIUPDATE, MYF(0), + tl->view_db.str, tl->view_name.str); + DBUG_RETURN(-1); + } + } + } + + /* now lock and fill tables */ + if (!thd->stmt_arena->is_stmt_prepare() && + lock_tables(thd, table_list, table_count, &need_reopen)) + { + if (!need_reopen) + DBUG_RETURN(TRUE); + + DBUG_PRINT("info", ("lock_tables failed, reopening")); + + /* + We have to reopen tables since some of them were altered or dropped + during lock_tables() or something was done with their triggers. + Let us do some cleanups to be able do setup_table() and setup_fields() + once again. + */ + List_iterator_fast it(*fields); + Item *item; + while ((item= it++)) + item->cleanup(); + + /* We have to cleanup translation tables of views. */ + for (TABLE_LIST *tbl= table_list; tbl; tbl= tbl->next_global) + tbl->cleanup_items(); + + /* + To not to hog memory (as a result of the + unit->reinit_exec_mechanism() call below): + */ + lex->unit.cleanup(); + + for (SELECT_LEX *sl= lex->all_selects_list; + sl; + sl= sl->next_select_in_list()) + { + SELECT_LEX_UNIT *unit= sl->master_unit(); + unit->reinit_exec_mechanism(); // reset unit->prepared flags + /* + Reset 'clean' flag back to force normal execution of + unit->cleanup() in Prepared_statement::cleanup_stmt() + (call to lex->unit.cleanup() above sets this flag to TRUE). + */ + unit->unclean(); + } + + /* + Also we need to cleanup Natural_join_column::table_field items. + To not to traverse a join tree we will cleanup whole + thd->free_list (in PS execution mode that list may not contain + items from 'fields' list, so the cleanup above is necessary to. + */ + cleanup_items(thd->free_list); + + close_tables_for_reopen(thd, &table_list); + goto reopen_tables; + } + + /* + Check that we are not using table that we are updating, but we should + skip all tables of UPDATE SELECT itself + */ + lex->select_lex.exclude_from_table_unique_test= TRUE; + /* We only need SELECT privilege for columns in the values list */ + for (tl= leaves; tl; tl= tl->next_leaf) + { + TABLE *table= tl->table; + TABLE_LIST *tlist; + if (!(tlist= tl->top_table())->derived) + { + tlist->grant.want_privilege= + (SELECT_ACL & ~tlist->grant.privilege); + table->grant.want_privilege= (SELECT_ACL & ~table->grant.privilege); + } + DBUG_PRINT("info", ("table: %s want_privilege: %u", tl->alias, + (uint) table->grant.want_privilege)); + if (tl->lock_type != TL_READ && + tl->lock_type != TL_READ_NO_INSERT) + { + TABLE_LIST *duplicate; + if ((duplicate= unique_table(thd, tl, table_list, 0))) + { + update_non_unique_table_error(table_list, "UPDATE", duplicate); + DBUG_RETURN(TRUE); + } + } + } + /* + Set exclude_from_table_unique_test value back to FALSE. It is needed for + further check in multi_update::prepare whether to use record cache. + */ + lex->select_lex.exclude_from_table_unique_test= FALSE; + + if (thd->fill_derived_tables() && + mysql_handle_derived(lex, &mysql_derived_filling)) + DBUG_RETURN(TRUE); + + DBUG_RETURN (FALSE); +} + + +/* + Setup multi-update handling and call SELECT to do the join +*/ +// @InfiniDB. Make conds argument reference to pointer so the optimization +// result can be passed in to the InfiniDB connector. + +bool mysql_multi_update(THD *thd, + TABLE_LIST *table_list, + List *fields, + List *values, + COND *& conds, + ulonglong options, + enum enum_duplicates handle_duplicates, bool ignore, + SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex) +{ + multi_update *result; + bool res; + DBUG_ENTER("mysql_multi_update"); + + if (!(result= new multi_update(table_list, + thd->lex->select_lex.leaf_tables, + fields, values, + handle_duplicates, ignore))) + DBUG_RETURN(TRUE); + + thd->abort_on_warning= test(thd->variables.sql_mode & + (MODE_STRICT_TRANS_TABLES | + MODE_STRICT_ALL_TABLES)); + + List total_list; + res= mysql_select(thd, &select_lex->ref_pointer_array, + table_list, select_lex->with_wild, + total_list, + conds, 0, (ORDER *) NULL, (ORDER *)NULL, (Item *) NULL, + (ORDER *)NULL, + options | SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK | + OPTION_SETUP_TABLES_DONE, + result, unit, select_lex); + DBUG_PRINT("info",("res: %d report_error: %d", res, + (int) thd->is_error())); + res|= thd->is_error(); + if (unlikely(res)) + { + /* If we had a another error reported earlier then this will be ignored */ + result->send_error(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR)); + result->abort(); + } + delete result; + thd->abort_on_warning= 0; + DBUG_RETURN(FALSE); +} + + +multi_update::multi_update(TABLE_LIST *table_list, + TABLE_LIST *leaves_list, + List *field_list, List *value_list, + enum enum_duplicates handle_duplicates_arg, + bool ignore_arg) + :all_tables(table_list), leaves(leaves_list), update_tables(0), + tmp_tables(0), updated(0), found(0), fields(field_list), + values(value_list), table_count(0), copy_field(0), + handle_duplicates(handle_duplicates_arg), do_update(1), trans_safe(1), + transactional_tables(0), ignore(ignore_arg), error_handled(0) +{} + + +/* + Connect fields with tables and create list of tables that are updated +*/ + +int multi_update::prepare(List ¬_used_values, + SELECT_LEX_UNIT *lex_unit) +{ + TABLE_LIST *table_ref; + SQL_LIST update; + table_map tables_to_update; + Item_field *item; + List_iterator_fast field_it(*fields); + List_iterator_fast value_it(*values); + uint i, max_fields; + uint leaf_table_count= 0; + DBUG_ENTER("multi_update::prepare"); + + thd->count_cuted_fields= CHECK_FIELD_WARN; + thd->cuted_fields=0L; + thd_proc_info(thd, "updating main table"); + + tables_to_update= get_table_map(fields); + + if (!tables_to_update) + { + my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0)); + DBUG_RETURN(1); + } + + /* + We gather the set of columns read during evaluation of SET expression in + TABLE::tmp_set by pointing TABLE::read_set to it and then restore it after + setup_fields(). + */ + for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf) + { + TABLE *table= table_ref->table; + if (tables_to_update & table->map) + { + DBUG_ASSERT(table->read_set == &table->def_read_set); + table->read_set= &table->tmp_set; + bitmap_clear_all(table->read_set); + } + } + + /* + We have to check values after setup_tables to get covering_keys right in + reference tables + */ + + int error= setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0); + + for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf) + { + TABLE *table= table_ref->table; + if (tables_to_update & table->map) + { + table->read_set= &table->def_read_set; + bitmap_union(table->read_set, &table->tmp_set); + } + } + + if (error) + DBUG_RETURN(1); + + /* + Save tables beeing updated in update_tables + update_table->shared is position for table + Don't use key read on tables that are updated + */ + + update.empty(); + for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf) + { + /* TODO: add support of view of join support */ + TABLE *table=table_ref->table; + leaf_table_count++; + if (tables_to_update & table->map) + { + TABLE_LIST *tl= (TABLE_LIST*) thd->memdup((char*) table_ref, + sizeof(*tl)); + if (!tl) + DBUG_RETURN(1); + update.link_in_list((uchar*) tl, (uchar**) &tl->next_local); + tl->shared= table_count++; + table->no_keyread=1; + table->covering_keys.clear_all(); + table->pos_in_table_list= tl; + if (table->triggers && + table->triggers->has_triggers(TRG_EVENT_UPDATE, + TRG_ACTION_AFTER)) + { + /* + The table has AFTER UPDATE triggers that might access to subject + table and therefore might need update to be done immediately. + So we turn-off the batching. + */ + (void) table->file->extra(HA_EXTRA_UPDATE_CANNOT_BATCH); + } + } + } + + + table_count= update.elements; + update_tables= (TABLE_LIST*) update.first; + + tmp_tables = (TABLE**) thd->calloc(sizeof(TABLE *) * table_count); + tmp_table_param = (TMP_TABLE_PARAM*) thd->calloc(sizeof(TMP_TABLE_PARAM) * + table_count); + fields_for_table= (List_item **) thd->alloc(sizeof(List_item *) * + table_count); + values_for_table= (List_item **) thd->alloc(sizeof(List_item *) * + table_count); + if (thd->is_fatal_error) + DBUG_RETURN(1); + for (i=0 ; i < table_count ; i++) + { + fields_for_table[i]= new List_item; + values_for_table[i]= new List_item; + } + if (thd->is_fatal_error) + DBUG_RETURN(1); + + /* Split fields into fields_for_table[] and values_by_table[] */ + + while ((item= (Item_field *) field_it++)) + { + Item *value= value_it++; + uint offset= item->field->table->pos_in_table_list->shared; + fields_for_table[offset]->push_back(item); + values_for_table[offset]->push_back(value); + } + if (thd->is_fatal_error) + DBUG_RETURN(1); + + /* Allocate copy fields */ + max_fields=0; + for (i=0 ; i < table_count ; i++) + set_if_bigger(max_fields, fields_for_table[i]->elements + leaf_table_count); + copy_field= new Copy_field[max_fields]; + DBUG_RETURN(thd->is_fatal_error != 0); +} + + +/* + Check if table is safe to update on fly + + SYNOPSIS + safe_update_on_fly() + thd Thread handler + join_tab How table is used in join + all_tables List of tables + + NOTES + We can update the first table in join on the fly if we know that + a row in this table will never be read twice. This is true under + the following conditions: + + - No column is both written to and read in SET expressions. + + - We are doing a table scan and the data is in a separate file (MyISAM) or + if we don't update a clustered key. + + - We are doing a range scan and we don't update the scan key or + the primary key for a clustered table handler. + + - Table is not joined to itself. + + This function gets information about fields to be updated from + the TABLE::write_set bitmap. + + WARNING + This code is a bit dependent of how make_join_readinfo() works. + + The field table->tmp_set is used for keeping track of which fields are + read during evaluation of the SET expression. See multi_update::prepare. + + RETURN + 0 Not safe to update + 1 Safe to update +*/ + +static bool safe_update_on_fly(THD *thd, JOIN_TAB *join_tab, + TABLE_LIST *table_ref, TABLE_LIST *all_tables) +{ + TABLE *table= join_tab->table; + if (unique_table(thd, table_ref, all_tables, 0)) + return 0; + switch (join_tab->type) { + case JT_SYSTEM: + case JT_CONST: + case JT_EQ_REF: + return TRUE; // At most one matching row + case JT_REF: + case JT_REF_OR_NULL: + return !is_key_used(table, join_tab->ref.key, table->write_set); + case JT_ALL: + if (bitmap_is_overlapping(&table->tmp_set, table->write_set)) + return FALSE; + /* If range search on index */ + if (join_tab->quick) + return !join_tab->quick->is_keys_used(table->write_set); + /* If scanning in clustered key */ + if ((table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) && + table->s->primary_key < MAX_KEY) + return !is_key_used(table, table->s->primary_key, table->write_set); + return TRUE; + default: + break; // Avoid compler warning + } + return FALSE; + +} + + +/* + Initialize table for multi table + + IMPLEMENTATION + - Update first table in join on the fly, if possible + - Create temporary tables to store changed values for all other tables + that are updated (and main_table if the above doesn't hold). +*/ + +bool +multi_update::initialize_tables(JOIN *join) +{ + TABLE_LIST *table_ref; + DBUG_ENTER("initialize_tables"); + + if ((thd->options & OPTION_SAFE_UPDATES) && error_if_full_join(join)) + DBUG_RETURN(1); + main_table=join->join_tab->table; + table_to_update= 0; + + /* Any update has at least one pair (field, value) */ + DBUG_ASSERT(fields->elements); + /* + Only one table may be modified by UPDATE of an updatable view. + For an updatable view first_table_for_update indicates this + table. + For a regular multi-update it refers to some updated table. + */ + TABLE *first_table_for_update= ((Item_field *) fields->head())->field->table; + + /* Create a temporary table for keys to all tables, except main table */ + for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local) + { + TABLE *table=table_ref->table; + uint cnt= table_ref->shared; + List temp_fields; + ORDER group; + TMP_TABLE_PARAM *tmp_param; + + if (ignore) + table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); + if (table == main_table) // First table in join + { + if (safe_update_on_fly(thd, join->join_tab, table_ref, all_tables)) + { + table->mark_columns_needed_for_update(); + table_to_update= table; // Update table on the fly + continue; + } + } + table->mark_columns_needed_for_update(); + table->prepare_for_position(); + + /* + enable uncacheable flag if we update a view with check option + and check option has a subselect, otherwise, the check option + can be evaluated after the subselect was freed as independent + (See full_local in JOIN::join_free()). + */ + if (table_ref->check_option && !join->select_lex->uncacheable) + { + SELECT_LEX_UNIT *tmp_unit; + SELECT_LEX *sl; + for (tmp_unit= join->select_lex->first_inner_unit(); + tmp_unit; + tmp_unit= tmp_unit->next_unit()) + { + for (sl= tmp_unit->first_select(); sl; sl= sl->next_select()) + { + if (sl->master_unit()->item) + { + join->select_lex->uncacheable|= UNCACHEABLE_CHECKOPTION; + goto loop_end; + } + } + } + } +loop_end: + + if (table == first_table_for_update && table_ref->check_option) + { + table_map unupdated_tables= table_ref->check_option->used_tables() & + ~first_table_for_update->map; + for (TABLE_LIST *tbl_ref =leaves; + unupdated_tables && tbl_ref; + tbl_ref= tbl_ref->next_leaf) + { + if (unupdated_tables & tbl_ref->table->map) + unupdated_tables&= ~tbl_ref->table->map; + else + continue; + if (unupdated_check_opt_tables.push_back(tbl_ref->table)) + DBUG_RETURN(1); + } + } + + tmp_param= tmp_table_param+cnt; + + /* + Create a temporary table to store all fields that are changed for this + table. The first field in the temporary table is a pointer to the + original row so that we can find and update it. For the updatable + VIEW a few following fields are rowids of tables used in the CHECK + OPTION condition. + */ + + List_iterator_fast
tbl_it(unupdated_check_opt_tables); + TABLE *tbl= table; + do + { + Field_string *field= new Field_string(tbl->file->ref_length, 0, + tbl->alias, &my_charset_bin); + if (!field) + DBUG_RETURN(1); + field->init(tbl); + /* + The field will be converted to varstring when creating tmp table if + table to be updated was created by mysql 4.1. Deny this. + */ + field->can_alter_field_type= 0; + Item_field *ifield= new Item_field((Field *) field); + if (!ifield) + DBUG_RETURN(1); + ifield->maybe_null= 0; + if (temp_fields.push_back(ifield)) + DBUG_RETURN(1); + } while ((tbl= tbl_it++)); + + temp_fields.concat(fields_for_table[cnt]); + + /* Make an unique key over the first field to avoid duplicated updates */ + bzero((char*) &group, sizeof(group)); + group.asc= 1; + group.item= (Item**) temp_fields.head_ref(); + + tmp_param->quick_group=1; + tmp_param->field_count=temp_fields.elements; + tmp_param->group_parts=1; + tmp_param->group_length= table->file->ref_length; + if (!(tmp_tables[cnt]=create_tmp_table(thd, + tmp_param, + temp_fields, + (ORDER*) &group, 0, 0, + TMP_TABLE_ALL_COLUMNS, + HA_POS_ERROR, + (char *) ""))) + DBUG_RETURN(1); + tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE); + } + DBUG_RETURN(0); +} + + +multi_update::~multi_update() +{ + TABLE_LIST *table; + for (table= update_tables ; table; table= table->next_local) + { + table->table->no_keyread= table->table->no_cache= 0; + if (ignore) + table->table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); + } + + if (tmp_tables) + { + for (uint cnt = 0; cnt < table_count; cnt++) + { + if (tmp_tables[cnt]) + { + free_tmp_table(thd, tmp_tables[cnt]); + tmp_table_param[cnt].cleanup(); + } + } + } + if (copy_field) + delete [] copy_field; + thd->count_cuted_fields= CHECK_FIELD_IGNORE; // Restore this setting + DBUG_ASSERT(trans_safe || !updated || + thd->transaction.all.modified_non_trans_table); +} + + +bool multi_update::send_data(List ¬_used_values) +{ + TABLE_LIST *cur_table; + DBUG_ENTER("multi_update::send_data"); + + for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local) + { + TABLE *table= cur_table->table; + uint offset= cur_table->shared; + /* + Check if we are using outer join and we didn't find the row + or if we have already updated this row in the previous call to this + function. + + The same row may be presented here several times in a join of type + UPDATE t1 FROM t1,t2 SET t1.a=t2.a + + In this case we will do the update for the first found row combination. + The join algorithm guarantees that we will not find the a row in + t1 several times. + */ + if (table->status & (STATUS_NULL_ROW | STATUS_UPDATED)) + continue; + + /* + We can use compare_record() to optimize away updates if + the table handler is returning all columns OR if + if all updated columns are read + */ + if (table == table_to_update) + { + bool can_compare_record; + can_compare_record= (!(table->file->ha_table_flags() & + HA_PARTIAL_COLUMN_READ) || + bitmap_is_subset(table->write_set, + table->read_set)); + table->status|= STATUS_UPDATED; + store_record(table,record[1]); + if (fill_record_n_invoke_before_triggers(thd, *fields_for_table[offset], + *values_for_table[offset], 0, + table->triggers, + TRG_EVENT_UPDATE)) + DBUG_RETURN(1); + + found++; + if (!can_compare_record || compare_record(table)) + { + int error; + if ((error= cur_table->view_check_option(thd, ignore)) != + VIEW_CHECK_OK) + { + found--; + if (error == VIEW_CHECK_SKIP) + continue; + else if (error == VIEW_CHECK_ERROR) + DBUG_RETURN(1); + } + if (!updated++) + { + /* + Inform the main table that we are going to update the table even + while we may be scanning it. This will flush the read cache + if it's used. + */ + main_table->file->extra(HA_EXTRA_PREPARE_FOR_UPDATE); + } + if ((error=table->file->ha_update_row(table->record[1], + table->record[0])) && + error != HA_ERR_RECORD_IS_THE_SAME) + { + updated--; + if (!ignore || + table->file->is_fatal_error(error, HA_CHECK_DUP_KEY)) + { + /* + If (ignore && error == is ignorable) we don't have to + do anything; otherwise... + */ + if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY)) + thd->fatal_error(); /* Other handler errors are fatal */ + + prepare_record_for_error_message(error, table); + table->file->print_error(error,MYF(0)); + DBUG_RETURN(1); + } + } + else + { + if (error == HA_ERR_RECORD_IS_THE_SAME) + { + error= 0; + updated--; + } + /* non-transactional or transactional table got modified */ + /* either multi_update class' flag is raised in its branch */ + if (table->file->has_transactions()) + transactional_tables= 1; + else + { + trans_safe= 0; + thd->transaction.stmt.modified_non_trans_table= TRUE; + } + } + } + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_UPDATE, + TRG_ACTION_AFTER, TRUE)) + DBUG_RETURN(1); + } + else + { + int error; + TABLE *tmp_table= tmp_tables[offset]; + /* + For updatable VIEW store rowid of the updated table and + rowids of tables used in the CHECK OPTION condition. + */ + uint field_num= 0; + List_iterator_fast
tbl_it(unupdated_check_opt_tables); + TABLE *tbl= table; + do + { + tbl->file->position(tbl->record[0]); + memcpy((char*) tmp_table->field[field_num]->ptr, + (char*) tbl->file->ref, tbl->file->ref_length); + /* + For outer joins a rowid field may have no NOT_NULL_FLAG, + so we have to reset NULL bit for this field. + (set_notnull() resets NULL bit only if available). + */ + tmp_table->field[field_num]->set_notnull(); + field_num++; + } while ((tbl= tbl_it++)); + + /* Store regular updated fields in the row. */ + fill_record(thd, + tmp_table->field + 1 + unupdated_check_opt_tables.elements, + *values_for_table[offset], 1); + + /* Write row, ignoring duplicated updates to a row */ + error= tmp_table->file->ha_write_row(tmp_table->record[0]); + if (error != HA_ERR_FOUND_DUPP_KEY && error != HA_ERR_FOUND_DUPP_UNIQUE) + { + if (error && + create_myisam_from_heap(thd, tmp_table, + tmp_table_param + offset, error, 1)) + { + do_update= 0; + DBUG_RETURN(1); // Not a table_is_full error + } + found++; + } + } + } + DBUG_RETURN(0); +} + + +void multi_update::send_error(uint errcode,const char *err) +{ + /* First send error what ever it is ... */ + my_error(errcode, MYF(0), err); +} + + +void multi_update::abort() +{ + /* the error was handled or nothing deleted and no side effects return */ + if (error_handled || + (!thd->transaction.stmt.modified_non_trans_table && !updated)) + return; + + /* Something already updated so we have to invalidate cache */ + if (updated) + query_cache_invalidate3(thd, update_tables, 1); + /* + If all tables that has been updated are trans safe then just do rollback. + If not attempt to do remaining updates. + */ + + if (! trans_safe) + { + DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table); + if (do_update && table_count > 1) + { + /* Add warning here */ + /* + todo/fixme: do_update() is never called with the arg 1. + should it change the signature to become argless? + */ + VOID(do_updates()); + } + } + if (thd->transaction.stmt.modified_non_trans_table) + { + /* + The query has to binlog because there's a modified non-transactional table + either from the query's list or via a stored routine: bug#13270,23333 + */ + if (mysql_bin_log.is_open()) + { + /* + THD::killed status might not have been set ON at time of an error + got caught and if happens later the killed error is written + into repl event. + */ + int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); + thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + transactional_tables, FALSE, errcode); + } + thd->transaction.all.modified_non_trans_table= TRUE; + } + DBUG_ASSERT(trans_safe || !updated || thd->transaction.stmt.modified_non_trans_table); +} + + +int multi_update::do_updates() +{ + TABLE_LIST *cur_table; + int local_error= 0; + ha_rows org_updated; + TABLE *table, *tmp_table; + List_iterator_fast
check_opt_it(unupdated_check_opt_tables); + DBUG_ENTER("multi_update::do_updates"); + + do_update= 0; // Don't retry this function + if (!found) + DBUG_RETURN(0); + for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local) + { + bool can_compare_record; + uint offset= cur_table->shared; + + table = cur_table->table; + if (table == table_to_update) + continue; // Already updated + org_updated= updated; + tmp_table= tmp_tables[cur_table->shared]; + tmp_table->file->extra(HA_EXTRA_CACHE); // Change to read cache + (void) table->file->ha_rnd_init(0); + table->file->extra(HA_EXTRA_NO_CACHE); + + check_opt_it.rewind(); + while(TABLE *tbl= check_opt_it++) + { + if (tbl->file->ha_rnd_init(1)) + goto err; + tbl->file->extra(HA_EXTRA_CACHE); + } + + /* + Setup copy functions to copy fields from temporary table + */ + List_iterator_fast field_it(*fields_for_table[offset]); + Field **field= tmp_table->field + + 1 + unupdated_check_opt_tables.elements; // Skip row pointers + Copy_field *copy_field_ptr= copy_field, *copy_field_end; + for ( ; *field ; field++) + { + Item_field *item= (Item_field* ) field_it++; + (copy_field_ptr++)->set(item->field, *field, 0); + } + copy_field_end=copy_field_ptr; + + if ((local_error = tmp_table->file->ha_rnd_init(1))) + goto err; + + can_compare_record= (!(table->file->ha_table_flags() & + HA_PARTIAL_COLUMN_READ) || + bitmap_is_subset(table->write_set, + table->read_set)); + + for (;;) + { + if (thd->killed && trans_safe) + goto err; + if ((local_error=tmp_table->file->rnd_next(tmp_table->record[0]))) + { + if (local_error == HA_ERR_END_OF_FILE) + break; + if (local_error == HA_ERR_RECORD_DELETED) + continue; // May happen on dup key + goto err; + } + + /* call rnd_pos() using rowids from temporary table */ + check_opt_it.rewind(); + TABLE *tbl= table; + uint field_num= 0; + do + { + if((local_error= + tbl->file->rnd_pos(tbl->record[0], + (uchar *) tmp_table->field[field_num]->ptr))) + goto err; + field_num++; + } while((tbl= check_opt_it++)); + + table->status|= STATUS_UPDATED; + store_record(table,record[1]); + + /* Copy data from temporary table to current table */ + for (copy_field_ptr=copy_field; + copy_field_ptr != copy_field_end; + copy_field_ptr++) + (*copy_field_ptr->do_copy)(copy_field_ptr); + + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_UPDATE, + TRG_ACTION_BEFORE, TRUE)) + goto err2; + + if (!can_compare_record || compare_record(table)) + { + int error; + if ((error= cur_table->view_check_option(thd, ignore)) != + VIEW_CHECK_OK) + { + if (error == VIEW_CHECK_SKIP) + continue; + else if (error == VIEW_CHECK_ERROR) + goto err; + } + if ((local_error=table->file->ha_update_row(table->record[1], + table->record[0])) && + local_error != HA_ERR_RECORD_IS_THE_SAME) + { + if (!ignore || + table->file->is_fatal_error(local_error, HA_CHECK_DUP_KEY)) + goto err; + } + if (local_error != HA_ERR_RECORD_IS_THE_SAME) + updated++; + else + local_error= 0; + } + + if (table->triggers && + table->triggers->process_triggers(thd, TRG_EVENT_UPDATE, + TRG_ACTION_AFTER, TRUE)) + goto err2; + } + + if (updated != org_updated) + { + if (table->file->has_transactions()) + transactional_tables= 1; + else + { + trans_safe= 0; // Can't do safe rollback + thd->transaction.stmt.modified_non_trans_table= TRUE; + } + } + (void) table->file->ha_rnd_end(); + (void) tmp_table->file->ha_rnd_end(); + check_opt_it.rewind(); + while (TABLE *tbl= check_opt_it++) + tbl->file->ha_rnd_end(); + + } + DBUG_RETURN(0); + +err: + { + thd->fatal_error(); + prepare_record_for_error_message(local_error, table); + table->file->print_error(local_error,MYF(0)); + } + +err2: + (void) table->file->ha_rnd_end(); + (void) tmp_table->file->ha_rnd_end(); + check_opt_it.rewind(); + while (TABLE *tbl= check_opt_it++) + tbl->file->ha_rnd_end(); + + if (updated != org_updated) + { + if (table->file->has_transactions()) + transactional_tables= 1; + else + { + trans_safe= 0; + thd->transaction.stmt.modified_non_trans_table= TRUE; + } + } + DBUG_RETURN(1); +} + + +/* out: 1 if error, 0 if success */ + +bool multi_update::send_eof() +{ + char buff[STRING_BUFFER_USUAL_SIZE]; + ulonglong id; + THD::killed_state killed_status= THD::NOT_KILLED; + DBUG_ENTER("multi_update::send_eof"); + thd_proc_info(thd, "updating reference tables"); + + /* + Does updates for the last n - 1 tables, returns 0 if ok; + error takes into account killed status gained in do_updates() + */ + int local_error = (table_count) ? do_updates() : 0; + /* + if local_error is not set ON until after do_updates() then + later carried out killing should not affect binlogging. + */ + killed_status= (local_error == 0)? THD::NOT_KILLED : thd->killed; + thd_proc_info(thd, "end"); + + /* We must invalidate the query cache before binlog writing and + ha_autocommit_... */ + + if (updated) + { + query_cache_invalidate3(thd, update_tables, 1); + } + /* + Write the SQL statement to the binlog if we updated + rows and we succeeded or if we updated some non + transactional tables. + + The query has to binlog because there's a modified non-transactional table + either from the query's list or via a stored routine: bug#13270,23333 + */ + + DBUG_ASSERT(trans_safe || !updated || + thd->transaction.stmt.modified_non_trans_table); + if (local_error == 0 || thd->transaction.stmt.modified_non_trans_table) + { + if (mysql_bin_log.is_open()) + { + int errcode= 0; + if (local_error == 0) + thd->clear_error(); + else + errcode= query_error_code(thd, killed_status == THD::NOT_KILLED); + if (thd->binlog_query(THD::ROW_QUERY_TYPE, + thd->query, thd->query_length, + transactional_tables, FALSE, errcode)) + { + local_error= 1; // Rollback update + } + } + if (thd->transaction.stmt.modified_non_trans_table) + thd->transaction.all.modified_non_trans_table= TRUE; + } + if (local_error != 0) + error_handled= TRUE; // to force early leave from ::send_error() + + if (local_error > 0) // if the above log write did not fail ... + { + /* Safety: If we haven't got an error before (can happen in do_updates) */ + my_message(ER_UNKNOWN_ERROR, "An error occured in multi-table update", + MYF(0)); + DBUG_RETURN(TRUE); + } + + id= thd->arg_of_last_insert_id_function ? + thd->first_successful_insert_id_in_prev_stmt : 0; + my_snprintf(buff, sizeof(buff), ER(ER_UPDATE_INFO), + (ulong) found, (ulong) updated, (ulong) thd->cuted_fields); + //@Infinidb bug2936. not set row count on thd to push row count to the front + // @bug4790. only change for InfiniDB table + if (!(thd->infinidb_vtable.isInfiniDBDML)) + thd->row_count_func= (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated; + ::my_ok(thd, (ulong) thd->row_count_func, id, buff); + DBUG_RETURN(FALSE); +} diff --git a/dbcon/mysql/sql_yacc.yy b/dbcon/mysql/sql_yacc.yy new file mode 100644 index 00000000..4c8fa0db --- /dev/null +++ b/dbcon/mysql/sql_yacc.yy @@ -0,0 +1,13569 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* sql_yacc.yy */ + +/** + @defgroup Parser Parser + @{ +*/ + +%{ +/* thd is passed as an argument to yyparse(), and subsequently to yylex(). +** The type will be void*, so it must be cast to (THD*) when used. +** Use the YYTHD macro for this. +*/ +#define YYPARSE_PARAM yythd +#define YYLEX_PARAM yythd +#define YYTHD ((THD *)yythd) +#define YYLIP (& YYTHD->m_parser_state->m_lip) + +#define MYSQL_YACC +#define YYINITDEPTH 100 +#define YYMAXDEPTH 3200 /* Because of 64K stack */ +#define Lex (YYTHD->lex) +#define Select Lex->current_select +#include "mysql_priv.h" +#include "slave.h" +#include "lex_symbol.h" +#include "item_create.h" +#include "sp_head.h" +#include "sp_pcontext.h" +#include "sp_rcontext.h" +#include "sp.h" +#include "event_parse_data.h" +#include +#include + +/* this is to get the bison compilation windows warnings out */ +#ifdef _MSC_VER +/* warning C4065: switch statement contains 'default' but no 'case' labels */ +#pragma warning (disable : 4065) +#endif + +int yylex(void *yylval, void *yythd); + +const LEX_STRING null_lex_str= {0,0}; + +#define yyoverflow(A,B,C,D,E,F) \ + { \ + ulong val= *(F); \ + if (my_yyoverflow((B), (D), &val)) \ + { \ + yyerror((char*) (A)); \ + return 2; \ + } \ + else \ + { \ + *(F)= (YYSIZE_T)val; \ + } \ + } + +#define MYSQL_YYABORT \ + do \ + { \ + LEX::cleanup_lex_after_parse_error(YYTHD);\ + YYABORT; \ + } while (0) + +#define MYSQL_YYABORT_UNLESS(A) \ + if (!(A)) \ + { \ + my_parse_error(ER(ER_SYNTAX_ERROR));\ + MYSQL_YYABORT; \ + } + +/* + Work around for broken code generated by bison 1.875. + + The code generated by bison 1.875a and later, bison 2.1 and bison 2.2 is ok. + With bison 1.875 however, the generated code contains: +
+  yyerrlab1:
+  #if defined (__GNUC_MINOR__) && 2093 <= (__GNUC__ * 1000 + __GNUC_MINOR__)
+    __attribute__ ((__unused__))
+  #endif
+
+ This usage of __attribute__ is illegal, so we remove it. + See the following references for details: + http://lists.gnu.org/archive/html/bug-bison/2004-02/msg00014.html + http://gcc.gnu.org/bugzilla/show_bug.cgi?id=14273 +*/ + +#if defined (__GNUC_MINOR__) && 2093 <= (__GNUC__ * 1000 + __GNUC_MINOR__) +#undef __attribute__ +#define __attribute__(X) +#endif + + +#ifndef DBUG_OFF +#define YYDEBUG 1 +#else +#define YYDEBUG 0 +#endif + +/** + @brief Push an error message into MySQL error stack with line + and position information. + + This function provides semantic action implementers with a way + to push the famous "You have a syntax error near..." error + message into the error stack, which is normally produced only if + a parse error is discovered internally by the Bison generated + parser. +*/ + +void my_parse_error(const char *s) +{ + THD *thd= current_thd; + Lex_input_stream *lip= & thd->m_parser_state->m_lip; + + const char *yytext= lip->get_tok_start(); + /* Push an error into the error stack */ + my_printf_error(ER_PARSE_ERROR, ER(ER_PARSE_ERROR), MYF(0), s, + (yytext ? yytext : ""), + lip->yylineno); +} + +/** + @brief Bison callback to report a syntax/OOM error + + This function is invoked by the bison-generated parser + when a syntax error, a parse error or an out-of-memory + condition occurs. This function is not invoked when the + parser is requested to abort by semantic action code + by means of YYABORT or YYACCEPT macros. This is why these + macros should not be used (use MYSQL_YYABORT/MYSQL_YYACCEPT + instead). + + The parser will abort immediately after invoking this callback. + + This function is not for use in semantic actions and is internal to + the parser, as it performs some pre-return cleanup. + In semantic actions, please use my_parse_error or my_error to + push an error into the error stack and MYSQL_YYABORT + to abort from the parser. +*/ + +void MYSQLerror(const char *s) +{ + THD *thd= current_thd; + + /* + Restore the original LEX if it was replaced when parsing + a stored procedure. We must ensure that a parsing error + does not leave any side effects in the THD. + */ + LEX::cleanup_lex_after_parse_error(thd); + + /* "parse error" changed into "syntax error" between bison 1.75 and 1.875 */ + if (strcmp(s,"parse error") == 0 || strcmp(s,"syntax error") == 0) + s= ER(ER_SYNTAX_ERROR); + my_parse_error(s); +} + + +#ifndef DBUG_OFF +void turn_parser_debug_on() +{ + /* + MYSQLdebug is in sql/sql_yacc.cc, in bison generated code. + Turning this option on is **VERY** verbose, and should be + used when investigating a syntax error problem only. + + The syntax to run with bison traces is as follows : + - Starting a server manually : + mysqld --debug="d,parser_debug" ... + - Running a test : + mysql-test-run.pl --mysqld="--debug=d,parser_debug" ... + + The result will be in the process stderr (var/log/master.err) + */ + + extern int yydebug; + yydebug= 1; +} +#endif + +static bool is_native_function(THD *thd, const LEX_STRING *name) +{ + if (find_native_function_builder(thd, *name)) + return true; + + if (is_lex_native_function(name)) + return true; + + return false; +} + + +/** + Helper action for a case statement (entering the CASE). + This helper is used for both 'simple' and 'searched' cases. + This helper, with the other case_stmt_action_..., is executed when + the following SQL code is parsed: +
+CREATE PROCEDURE proc_19194_simple(i int)
+BEGIN
+  DECLARE str CHAR(10);
+
+  CASE i
+    WHEN 1 THEN SET str="1";
+    WHEN 2 THEN SET str="2";
+    WHEN 3 THEN SET str="3";
+    ELSE SET str="unknown";
+  END CASE;
+
+  SELECT str;
+END
+
+ The actions are used to generate the following code: +
+SHOW PROCEDURE CODE proc_19194_simple;
+Pos     Instruction
+0       set str@1 NULL
+1       set_case_expr (12) 0 i@0
+2       jump_if_not 5(12) (case_expr@0 = 1)
+3       set str@1 _latin1'1'
+4       jump 12
+5       jump_if_not 8(12) (case_expr@0 = 2)
+6       set str@1 _latin1'2'
+7       jump 12
+8       jump_if_not 11(12) (case_expr@0 = 3)
+9       set str@1 _latin1'3'
+10      jump 12
+11      set str@1 _latin1'unknown'
+12      stmt 0 "SELECT str"
+
+ + @param lex the parser lex context +*/ + +void case_stmt_action_case(LEX *lex) +{ + lex->sphead->new_cont_backpatch(NULL); + + /* + BACKPATCH: Creating target label for the jump to + "case_stmt_action_end_case" + (Instruction 12 in the example) + */ + + lex->spcont->push_label((char *)"", lex->sphead->instructions()); +} + +/** + Helper action for a case expression statement (the expr in 'CASE expr'). + This helper is used for 'searched' cases only. + @param lex the parser lex context + @param expr the parsed expression + @return 0 on success +*/ + +int case_stmt_action_expr(LEX *lex, Item* expr) +{ + sp_head *sp= lex->sphead; + sp_pcontext *parsing_ctx= lex->spcont; + int case_expr_id= parsing_ctx->register_case_expr(); + sp_instr_set_case_expr *i; + + if (parsing_ctx->push_case_expr_id(case_expr_id)) + return 1; + + i= new sp_instr_set_case_expr(sp->instructions(), + parsing_ctx, case_expr_id, expr, lex); + + sp->add_cont_backpatch(i); + return sp->add_instr(i); +} + +/** + Helper action for a case when condition. + This helper is used for both 'simple' and 'searched' cases. + @param lex the parser lex context + @param when the parsed expression for the WHEN clause + @param simple true for simple cases, false for searched cases +*/ + +int case_stmt_action_when(LEX *lex, Item *when, bool simple) +{ + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + uint ip= sp->instructions(); + sp_instr_jump_if_not *i; + Item_case_expr *var; + Item *expr; + + if (simple) + { + var= new Item_case_expr(ctx->get_current_case_expr_id()); + +#ifndef DBUG_OFF + if (var) + { + var->m_sp= sp; + } +#endif + + expr= new Item_func_eq(var, when); + i= new sp_instr_jump_if_not(ip, ctx, expr, lex); + } + else + i= new sp_instr_jump_if_not(ip, ctx, when, lex); + + /* + BACKPATCH: Registering forward jump from + "case_stmt_action_when" to "case_stmt_action_then" + (jump_if_not from instruction 2 to 5, 5 to 8 ... in the example) + */ + + return !test(i) || + sp->push_backpatch(i, ctx->push_label((char *)"", 0)) || + sp->add_cont_backpatch(i) || + sp->add_instr(i); +} + +/** + Helper action for a case then statements. + This helper is used for both 'simple' and 'searched' cases. + @param lex the parser lex context +*/ + +int case_stmt_action_then(LEX *lex) +{ + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + uint ip= sp->instructions(); + sp_instr_jump *i = new sp_instr_jump(ip, ctx); + if (!test(i) || sp->add_instr(i)) + return 1; + + /* + BACKPATCH: Resolving forward jump from + "case_stmt_action_when" to "case_stmt_action_then" + (jump_if_not from instruction 2 to 5, 5 to 8 ... in the example) + */ + + sp->backpatch(ctx->pop_label()); + + /* + BACKPATCH: Registering forward jump from + "case_stmt_action_then" to "case_stmt_action_end_case" + (jump from instruction 4 to 12, 7 to 12 ... in the example) + */ + + return sp->push_backpatch(i, ctx->last_label()); +} + +/** + Helper action for an end case. + This helper is used for both 'simple' and 'searched' cases. + @param lex the parser lex context + @param simple true for simple cases, false for searched cases +*/ + +void case_stmt_action_end_case(LEX *lex, bool simple) +{ + /* + BACKPATCH: Resolving forward jump from + "case_stmt_action_then" to "case_stmt_action_end_case" + (jump from instruction 4 to 12, 7 to 12 ... in the example) + */ + lex->sphead->backpatch(lex->spcont->pop_label()); + + if (simple) + lex->spcont->pop_case_expr_id(); + + lex->sphead->do_cont_backpatch(); +} + +/** + Helper to resolve the SQL:2003 Syntax exception 1) in . + See SQL:2003, Part 2, section 8.4 , Note 184, page 383. + This function returns the proper item for the SQL expression + left [NOT] IN ( expr ) + @param thd the current thread + @param left the in predicand + @param equal true for IN predicates, false for NOT IN predicates + @param expr first and only expression of the in value list + @return an expression representing the IN predicate. +*/ +Item* handle_sql2003_note184_exception(THD *thd, Item* left, bool equal, + Item *expr) +{ + /* + Relevant references for this issue: + - SQL:2003, Part 2, section 8.4 , page 383, + - SQL:2003, Part 2, section 7.2 , page 296, + - SQL:2003, Part 2, section 6.3 , page 174, + - SQL:2003, Part 2, section 7.15 , page 370, + - SQL:2003 Feature F561, "Full value expressions". + + The exception in SQL:2003 Note 184 means: + Item_singlerow_subselect, which corresponds to a , + should be re-interpreted as an Item_in_subselect, which corresponds + to a
when used inside an . + + Our reading of Note 184 is reccursive, so that all: + - IN (( )) + - IN ((( ))) + - IN '('^N ')'^N + - etc + should be interpreted as a
, no matter how deep in the + expression the is. + */ + + Item *result; + + DBUG_ENTER("handle_sql2003_note184_exception"); + + if (expr->type() == Item::SUBSELECT_ITEM) + { + Item_subselect *expr2 = (Item_subselect*) expr; + + if (expr2->substype() == Item_subselect::SINGLEROW_SUBS) + { + Item_singlerow_subselect *expr3 = (Item_singlerow_subselect*) expr2; + st_select_lex *subselect; + + /* + Implement the mandated change, by altering the semantic tree: + left IN Item_singlerow_subselect(subselect) + is modified to + left IN (subselect) + which is represented as + Item_in_subselect(left, subselect) + */ + subselect= expr3->invalidate_and_restore_select_lex(); + result= new (thd->mem_root) Item_in_subselect(left, subselect); + + if (! equal) + result = negate_expression(thd, result); + + DBUG_RETURN(result); + } + } + + if (equal) + result= new (thd->mem_root) Item_func_eq(left, expr); + else + result= new (thd->mem_root) Item_func_ne(left, expr); + + DBUG_RETURN(result); +} + +%} +%union { + int num; + ulong ulong_num; + ulonglong ulonglong_number; + longlong longlong_number; + LEX_STRING lex_str; + LEX_STRING *lex_str_ptr; + LEX_SYMBOL symbol; + Table_ident *table; + char *simple_string; + Item *item; + Item_num *item_num; + List *item_list; + List *string_list; + String *string; + Key_part_spec *key_part; + TABLE_LIST *table_list; + udf_func *udf; + LEX_USER *lex_user; + struct sys_var_with_base variable; + enum enum_var_type var_type; + Key::Keytype key_type; + enum ha_key_alg key_alg; + handlerton *db_type; + enum row_type row_type; + enum ha_rkey_function ha_rkey_mode; + enum enum_tx_isolation tx_isolation; + enum Cast_target cast_type; + enum Item_udftype udf_type; + CHARSET_INFO *charset; + thr_lock_type lock_type; + interval_type interval, interval_time_st; + timestamp_type date_time_type; + st_select_lex *select_lex; + chooser_compare_func_creator boolfunc2creator; + struct sp_cond_type *spcondtype; + struct { int vars, conds, hndlrs, curs; } spblock; + sp_name *spname; + struct st_lex *lex; + sp_head *sphead; + struct p_elem_val *p_elem_value; + enum index_hint_type index_hint; +} + +%{ +bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize); +%} + +%pure_parser /* We have threads */ +/* + Currently there are 169 shift/reduce conflicts. + We should not introduce new conflicts any more. +*/ +%expect 173 + +/* + Comments for TOKENS. + For each token, please include in the same line a comment that contains + the following tags: + SQL-2003-R : Reserved keyword as per SQL-2003 + SQL-2003-N : Non Reserved keyword as per SQL-2003 + SQL-1999-R : Reserved keyword as per SQL-1999 + SQL-1999-N : Non Reserved keyword as per SQL-1999 + MYSQL : MySQL extention (unspecified) + MYSQL-FUNC : MySQL extention, function + INTERNAL : Not a real token, lex optimization + OPERATOR : SQL operator + FUTURE-USE : Reserved for futur use + + This makes the code grep-able, and helps maintenance. +*/ + +%token ABORT_SYM /* INTERNAL (used in lex) */ +%token ACCESSIBLE_SYM +%token ACTION /* SQL-2003-N */ +%token ADD /* SQL-2003-R */ +%token ADDDATE_SYM /* MYSQL-FUNC */ +%token AFTER_SYM /* SQL-2003-N */ +%token AGAINST +%token AGGREGATE_SYM +%token ALGORITHM_SYM +%token ALL /* SQL-2003-R */ +%token ALTER /* SQL-2003-R */ +%token ANALYZE_SYM +%token AND_AND_SYM /* OPERATOR */ +%token AND_SYM /* SQL-2003-R */ +%token ANY_SYM /* SQL-2003-R */ +%token AS /* SQL-2003-R */ +%token ASC /* SQL-2003-N */ +%token ASCII_SYM /* MYSQL-FUNC */ +%token ASENSITIVE_SYM /* FUTURE-USE */ +%token AT_SYM /* SQL-2003-R */ +%token AUTHORS_SYM +%token AUTOEXTEND_SIZE_SYM +%token AUTO_INC +%token AVG_ROW_LENGTH +%token AVG_SYM /* SQL-2003-N */ +%token BACKUP_SYM +%token BEFORE_SYM /* SQL-2003-N */ +%token BEGIN_SYM /* SQL-2003-R */ +%token BETWEEN_SYM /* SQL-2003-R */ +%token BIGINT /* SQL-2003-R */ +%token BINARY /* SQL-2003-R */ +%token BINLOG_SYM +%token BIN_NUM +%token BIT_AND /* MYSQL-FUNC */ +%token BIT_OR /* MYSQL-FUNC */ +%token BIT_SYM /* MYSQL-FUNC */ +%token BIT_XOR /* MYSQL-FUNC */ +%token BLOB_SYM /* SQL-2003-R */ +%token BLOCK_SYM +%token BOOLEAN_SYM /* SQL-2003-R */ +%token BOOL_SYM +%token BOTH /* SQL-2003-R */ +%token BTREE_SYM +%token BY /* SQL-2003-R */ +%token BYTE_SYM +%token CACHE_SYM +%token CALL_SYM /* SQL-2003-R */ +%token CASCADE /* SQL-2003-N */ +%token CASCADED /* SQL-2003-R */ +%token CASE_SYM /* SQL-2003-R */ +%token CAST_SYM /* SQL-2003-R */ +%token CHAIN_SYM /* SQL-2003-N */ +%token CHANGE +%token CHANGED +%token CHARSET +%token CHAR_SYM /* SQL-2003-R */ +%token CHECKSUM_SYM +%token CHECK_SYM /* SQL-2003-R */ +%token CIPHER_SYM +%token CLIENT_SYM +%token CLOSE_SYM /* SQL-2003-R */ +%token COALESCE /* SQL-2003-N */ +%token CODE_SYM +%token COLLATE_SYM /* SQL-2003-R */ +%token COLLATION_SYM /* SQL-2003-N */ +%token COLUMNS +%token COLUMN_SYM /* SQL-2003-R */ +%token COMMENT_SYM +%token COMMITTED_SYM /* SQL-2003-N */ +%token COMMIT_SYM /* SQL-2003-R */ +%token COMPACT_SYM +%token COMPLETION_SYM +%token COMPRESSED_SYM +%token CONCURRENT +%token CONDITION_SYM /* SQL-2003-N */ +%token CONNECTION_SYM +%token CONSISTENT_SYM +%token CONSTRAINT /* SQL-2003-R */ +%token CONTAINS_SYM /* SQL-2003-N */ +%token CONTEXT_SYM +%token CONTINUE_SYM /* SQL-2003-R */ +%token CONTRIBUTORS_SYM +%token CONVERT_SYM /* SQL-2003-N */ +%token COUNT_SYM /* SQL-2003-N */ +%token CPU_SYM +%token CREATE /* SQL-2003-R */ +%token CROSS /* SQL-2003-R */ +%token CUBE_SYM /* SQL-2003-R */ +%token CURDATE /* MYSQL-FUNC */ +%token CURRENT_USER /* SQL-2003-R */ +%token CURSOR_SYM /* SQL-2003-R */ +%token CURTIME /* MYSQL-FUNC */ +%token DATABASE +%token DATABASES +%token DATAFILE_SYM +%token DATA_SYM /* SQL-2003-N */ +%token DATETIME +%token DATE_ADD_INTERVAL /* MYSQL-FUNC */ +%token DATE_SUB_INTERVAL /* MYSQL-FUNC */ +%token DATE_SYM /* SQL-2003-R */ +%token DAY_HOUR_SYM +%token DAY_MICROSECOND_SYM +%token DAY_MINUTE_SYM +%token DAY_SECOND_SYM +%token DAY_SYM /* SQL-2003-R */ +%token DEALLOCATE_SYM /* SQL-2003-R */ +%token DECIMAL_NUM +%token DECIMAL_SYM /* SQL-2003-R */ +%token DECLARE_SYM /* SQL-2003-R */ +%token DEFAULT /* SQL-2003-R */ +%token DEFINER_SYM +%token DELAYED_SYM +%token DELAY_KEY_WRITE_SYM +%token DELETE_SYM /* SQL-2003-R */ +%token DESC /* SQL-2003-N */ +%token DESCRIBE /* SQL-2003-R */ +%token DES_KEY_FILE +%token DETERMINISTIC_SYM /* SQL-2003-R */ +%token DIRECTORY_SYM +%token DISABLE_SYM +%token DISCARD +%token DISK_SYM +%token DISTINCT /* SQL-2003-R */ +%token DIV_SYM +%token DOUBLE_SYM /* SQL-2003-R */ +%token DO_SYM +%token DROP /* SQL-2003-R */ +%token DUAL_SYM +%token DUMPFILE +%token DUPLICATE_SYM +%token DYNAMIC_SYM /* SQL-2003-R */ +%token EACH_SYM /* SQL-2003-R */ +%token ELSE /* SQL-2003-R */ +%token ELSEIF_SYM +%token ENABLE_SYM +%token ENCLOSED +%token END /* SQL-2003-R */ +%token ENDS_SYM +%token END_OF_INPUT /* INTERNAL */ +%token ENGINES_SYM +%token ENGINE_SYM +%token ENUM +%token EQ /* OPERATOR */ +%token EQUAL_SYM /* OPERATOR */ +%token ERRORS +%token ESCAPED +%token ESCAPE_SYM /* SQL-2003-R */ +%token EVENTS_SYM +%token EVENT_SYM +%token EVERY_SYM /* SQL-2003-N */ +%token EXECUTE_SYM /* SQL-2003-R */ +%token EXISTS /* SQL-2003-R */ +%token EXIT_SYM +%token EXPANSION_SYM +%token EXTENDED_SYM +%token EXTENT_SIZE_SYM +%token EXTRACT_SYM /* SQL-2003-N */ +%token FALSE_SYM /* SQL-2003-R */ +%token FAST_SYM +%token FAULTS_SYM +%token FETCH_SYM /* SQL-2003-R */ +%token FILE_SYM +%token FIRST_SYM /* SQL-2003-N */ +%token FIXED_SYM +%token FLOAT_NUM +%token FLOAT_SYM /* SQL-2003-R */ +%token FLUSH_SYM +%token FORCE_SYM +%token FOREIGN /* SQL-2003-R */ +%token FOR_SYM /* SQL-2003-R */ +%token FOUND_SYM /* SQL-2003-R */ +%token FRAC_SECOND_SYM +%token FROM +%token FULL /* SQL-2003-R */ +%token FULLTEXT_SYM +%token FUNCTION_SYM /* SQL-2003-R */ +%token GE +%token GEOMETRYCOLLECTION +%token GEOMETRY_SYM +%token GET_FORMAT /* MYSQL-FUNC */ +%token GLOBAL_SYM /* SQL-2003-R */ +%token GRANT /* SQL-2003-R */ +%token GRANTS +%token GROUP_SYM /* SQL-2003-R */ +%token GROUP_CONCAT_SYM +%token GT_SYM /* OPERATOR */ +%token HANDLER_SYM +%token HASH_SYM +%token HAVING /* SQL-2003-R */ +%token HELP_SYM +%token HEX_NUM +%token HIGH_PRIORITY +%token HOST_SYM +%token HOSTS_SYM +%token HOUR_MICROSECOND_SYM +%token HOUR_MINUTE_SYM +%token HOUR_SECOND_SYM +%token HOUR_SYM /* SQL-2003-R */ +%token IDENT +%token IDENTIFIED_SYM +%token IDENT_QUOTED +%token IF +%token IGNORE_SYM +%token IMPORT +%token INDEXES +%token INDEX_SYM +%token INFILE +%token INITIAL_SIZE_SYM +%token INNER_SYM /* SQL-2003-R */ +%token INNOBASE_SYM +%token INOUT_SYM /* SQL-2003-R */ +%token INSENSITIVE_SYM /* SQL-2003-R */ +%token INSERT /* SQL-2003-R */ +%token INSERT_METHOD +%token INSTALL_SYM +%token INTERVAL_SYM /* SQL-2003-R */ +%token INTO /* SQL-2003-R */ +%token INT_SYM /* SQL-2003-R */ +%token INVOKER_SYM +%token IN_SYM /* SQL-2003-R */ +%token IO_SYM +%token IPC_SYM +%token IS /* SQL-2003-R */ +%token ISOLATION /* SQL-2003-R */ +%token ISSUER_SYM +%token ITERATE_SYM +%token JOIN_SYM /* SQL-2003-R */ +%token KEYS +%token KEY_BLOCK_SIZE +%token KEY_SYM /* SQL-2003-N */ +%token KILL_SYM +%token LANGUAGE_SYM /* SQL-2003-R */ +%token LAST_SYM /* SQL-2003-N */ +%token LE /* OPERATOR */ +%token LEADING /* SQL-2003-R */ +%token LEAVES +%token LEAVE_SYM +%token LEFT /* SQL-2003-R */ +%token LESS_SYM +%token LEVEL_SYM +%token LEX_HOSTNAME +%token LIKE /* SQL-2003-R */ +%token LIMIT +%token LINEAR_SYM +%token LINES +%token LINESTRING +%token LIST_SYM +%token LOAD +%token LOCAL_SYM /* SQL-2003-R */ +%token LOCATOR_SYM /* SQL-2003-N */ +%token LOCKS_SYM +%token LOCK_SYM +%token LOGFILE_SYM +%token LOGS_SYM +%token LONGBLOB +%token LONGTEXT +%token LONG_NUM +%token LONG_SYM +%token LOOP_SYM +%token LOW_PRIORITY +%token LT /* OPERATOR */ +%token MASTER_CONNECT_RETRY_SYM +%token MASTER_HOST_SYM +%token MASTER_LOG_FILE_SYM +%token MASTER_LOG_POS_SYM +%token MASTER_PASSWORD_SYM +%token MASTER_PORT_SYM +%token MASTER_SERVER_ID_SYM +%token MASTER_SSL_CAPATH_SYM +%token MASTER_SSL_CA_SYM +%token MASTER_SSL_CERT_SYM +%token MASTER_SSL_CIPHER_SYM +%token MASTER_SSL_KEY_SYM +%token MASTER_SSL_SYM +%token MASTER_SSL_VERIFY_SERVER_CERT_SYM +%token MASTER_SYM +%token MASTER_USER_SYM +%token MATCH /* SQL-2003-R */ +%token MAX_CONNECTIONS_PER_HOUR +%token MAX_QUERIES_PER_HOUR +%token MAX_ROWS +%token MAX_SIZE_SYM +%token MAX_SYM /* SQL-2003-N */ +%token MAX_UPDATES_PER_HOUR +%token MAX_USER_CONNECTIONS_SYM +%token MAX_VALUE_SYM /* SQL-2003-N */ +%token MEDIUMBLOB +%token MEDIUMINT +%token MEDIUMTEXT +%token MEDIUM_SYM +%token MEMORY_SYM +%token MERGE_SYM /* SQL-2003-R */ +%token MICROSECOND_SYM /* MYSQL-FUNC */ +%token MIGRATE_SYM +%token MINUTE_MICROSECOND_SYM +%token MINUTE_SECOND_SYM +%token MINUTE_SYM /* SQL-2003-R */ +%token MIN_ROWS +%token MIN_SYM /* SQL-2003-N */ +%token MODE_SYM +%token MODIFIES_SYM /* SQL-2003-R */ +%token MODIFY_SYM +%token MOD_SYM /* SQL-2003-N */ +%token MONTH_SYM /* SQL-2003-R */ +%token MULTILINESTRING +%token MULTIPOINT +%token MULTIPOLYGON +%token MUTEX_SYM +%token NAMES_SYM /* SQL-2003-N */ +%token NAME_SYM /* SQL-2003-N */ +%token NATIONAL_SYM /* SQL-2003-R */ +%token NATURAL /* SQL-2003-R */ +%token NCHAR_STRING +%token NCHAR_SYM /* SQL-2003-R */ +%token NDBCLUSTER_SYM +%token NE /* OPERATOR */ +%token NEG +%token NEW_SYM /* SQL-2003-R */ +%token NEXT_SYM /* SQL-2003-N */ +%token NODEGROUP_SYM +%token NONE_SYM /* SQL-2003-R */ +%token NOT2_SYM +%token NOT_SYM /* SQL-2003-R */ +%token NOW_SYM +%token NO_SYM /* SQL-2003-R */ +%token NO_WAIT_SYM +%token NO_WRITE_TO_BINLOG +%token NULL_SYM /* SQL-2003-R */ +%token NUM +%token NUMERIC_SYM /* SQL-2003-R */ +%token NVARCHAR_SYM +%token OFFSET_SYM +%token OLD_PASSWORD +%token ON /* SQL-2003-R */ +%token ONE_SHOT_SYM +%token ONE_SYM +%token OPEN_SYM /* SQL-2003-R */ +%token OPTIMIZE +%token OPTIONS_SYM +%token OPTION /* SQL-2003-N */ +%token OPTIONALLY +%token OR2_SYM +%token ORDER_SYM /* SQL-2003-R */ +%token OR_OR_SYM /* OPERATOR */ +%token OR_SYM /* SQL-2003-R */ +%token OUTER +%token OUTFILE +%token OUT_SYM /* SQL-2003-R */ +%token OWNER_SYM +%token PACK_KEYS_SYM +%token PAGE_SYM +%token PARAM_MARKER +%token PARSER_SYM +%token PARTIAL /* SQL-2003-N */ +%token PARTITIONING_SYM +%token PARTITIONS_SYM +%token PARTITION_SYM /* SQL-2003-R */ +%token PASSWORD +%token PHASE_SYM +%token PLUGINS_SYM +%token PLUGIN_SYM +%token POINT_SYM +%token POLYGON +%token PORT_SYM +%token POSITION_SYM /* SQL-2003-N */ +%token PRECISION /* SQL-2003-R */ +%token PREPARE_SYM /* SQL-2003-R */ +%token PRESERVE_SYM +%token PREV_SYM +%token PRIMARY_SYM /* SQL-2003-R */ +%token PRIVILEGES /* SQL-2003-N */ +%token PROCEDURE /* SQL-2003-R */ +%token PROCESS +%token PROCESSLIST_SYM +%token PROFILE_SYM +%token PROFILES_SYM +%token PURGE +%token QUARTER_SYM +%token QUERY_SYM +%token QUICK +%token RANGE_SYM /* SQL-2003-R */ +%token READS_SYM /* SQL-2003-R */ +%token READ_ONLY_SYM +%token READ_SYM /* SQL-2003-N */ +%token READ_WRITE_SYM +%token REAL /* SQL-2003-R */ +%token REBUILD_SYM +%token RECOVER_SYM +%token REDOFILE_SYM +%token REDO_BUFFER_SIZE_SYM +%token REDUNDANT_SYM +%token REFERENCES /* SQL-2003-R */ +%token REGEXP +%token RELAY_LOG_FILE_SYM +%token RELAY_LOG_POS_SYM +%token RELAY_THREAD +%token RELEASE_SYM /* SQL-2003-R */ +%token RELOAD +%token REMOVE_SYM +%token RENAME +%token REORGANIZE_SYM +%token REPAIR +%token REPEATABLE_SYM /* SQL-2003-N */ +%token REPEAT_SYM /* MYSQL-FUNC */ +%token REPLACE /* MYSQL-FUNC */ +%token REPLICATION +%token REQUIRE_SYM +%token RESET_SYM +%token RESOURCES +%token RESTORE_SYM +%token RESTRICT +%token RESUME_SYM +%token RETURNS_SYM /* SQL-2003-R */ +%token RETURN_SYM /* SQL-2003-R */ +%token REVOKE /* SQL-2003-R */ +%token RIGHT /* SQL-2003-R */ +%token ROLLBACK_SYM /* SQL-2003-R */ +%token ROLLUP_SYM /* SQL-2003-R */ +%token ROUTINE_SYM /* SQL-2003-N */ +%token ROWS_SYM /* SQL-2003-R */ +%token ROW_FORMAT_SYM +%token ROW_SYM /* SQL-2003-R */ +%token RTREE_SYM +%token SAVEPOINT_SYM /* SQL-2003-R */ +%token SCHEDULE_SYM +%token SECOND_MICROSECOND_SYM +%token SECOND_SYM /* SQL-2003-R */ +%token SECURITY_SYM /* SQL-2003-N */ +%token SELECT_SYM /* SQL-2003-R */ +%token SENSITIVE_SYM /* FUTURE-USE */ +%token SEPARATOR_SYM +%token SERIALIZABLE_SYM /* SQL-2003-N */ +%token SERIAL_SYM +%token SESSION_SYM /* SQL-2003-N */ +%token SERVER_SYM +%token SERVER_OPTIONS +%token SET /* SQL-2003-R */ +%token SET_VAR +%token SHARE_SYM +%token SHIFT_LEFT /* OPERATOR */ +%token SHIFT_RIGHT /* OPERATOR */ +%token SHOW +%token SHUTDOWN +%token SIGNED_SYM +%token SIMPLE_SYM /* SQL-2003-N */ +%token SLAVE +%token SMALLINT /* SQL-2003-R */ +%token SNAPSHOT_SYM +%token SOCKET_SYM +%token SONAME_SYM +%token SOUNDS_SYM +%token SOURCE_SYM +%token SPATIAL_SYM +%token SPECIFIC_SYM /* SQL-2003-R */ +%token SQLEXCEPTION_SYM /* SQL-2003-R */ +%token SQLSTATE_SYM /* SQL-2003-R */ +%token SQLWARNING_SYM /* SQL-2003-R */ +%token SQL_BIG_RESULT +%token SQL_BUFFER_RESULT +%token SQL_CACHE_SYM +%token SQL_CALC_FOUND_ROWS +%token SQL_NO_CACHE_SYM +%token INFINIDB_ORDERED_SYM +%token SQL_SMALL_RESULT +%token SQL_SYM /* SQL-2003-R */ +%token SQL_THREAD +%token SSL_SYM +%token STARTING +%token STARTS_SYM +%token START_SYM /* SQL-2003-R */ +%token STATUS_SYM +%token STDDEV_SAMP_SYM /* SQL-2003-N */ +%token STD_SYM +%token STOP_SYM +%token STORAGE_SYM +%token STRAIGHT_JOIN +%token STRING_SYM +%token SUBDATE_SYM +%token SUBJECT_SYM +%token SUBPARTITIONS_SYM +%token SUBPARTITION_SYM +%token SUBSTRING /* SQL-2003-N */ +%token SUM_SYM /* SQL-2003-N */ +%token SUPER_SYM +%token SUSPEND_SYM +%token SWAPS_SYM +%token SWITCHES_SYM +%token SYSDATE +%token TABLES +%token TABLESPACE +%token TABLE_REF_PRIORITY +%token TABLE_SYM /* SQL-2003-R */ +%token TABLE_CHECKSUM_SYM +%token TEMPORARY /* SQL-2003-N */ +%token TEMPTABLE_SYM +%token TERMINATED +%token TEXT_STRING +%token TEXT_SYM +%token THAN_SYM +%token THEN_SYM /* SQL-2003-R */ +%token TIMESTAMP /* SQL-2003-R */ +%token TIMESTAMP_ADD +%token TIMESTAMP_DIFF +%token TIME_SYM /* SQL-2003-R */ +%token TINYBLOB +%token TINYINT +%token TINYTEXT +%token TO_SYM /* SQL-2003-R */ +%token TRAILING /* SQL-2003-R */ +%token TRANSACTION_SYM +%token TRIGGERS_SYM +%token TRIGGER_SYM /* SQL-2003-R */ +%token TRIM /* SQL-2003-N */ +%token TRUE_SYM /* SQL-2003-R */ +%token TRUNCATE_SYM +%token TYPES_SYM +%token TYPE_SYM /* SQL-2003-N */ +%token UDF_RETURNS_SYM +%token ULONGLONG_NUM +%token UNCOMMITTED_SYM /* SQL-2003-N */ +%token UNDEFINED_SYM +%token UNDERSCORE_CHARSET +%token UNDOFILE_SYM +%token UNDO_BUFFER_SIZE_SYM +%token UNDO_SYM /* FUTURE-USE */ +%token UNICODE_SYM +%token UNINSTALL_SYM +%token UNION_SYM /* SQL-2003-R */ +%token UNIQUE_SYM +%token UNKNOWN_SYM /* SQL-2003-R */ +%token UNLOCK_SYM +%token UNSIGNED +%token UNTIL_SYM +%token UPDATE_SYM /* SQL-2003-R */ +%token UPGRADE_SYM +%token USAGE /* SQL-2003-N */ +%token USER /* SQL-2003-R */ +%token USE_FRM +%token USE_SYM +%token USING /* SQL-2003-R */ +%token UTC_DATE_SYM +%token UTC_TIMESTAMP_SYM +%token UTC_TIME_SYM +%token VALUES /* SQL-2003-R */ +%token VALUE_SYM /* SQL-2003-R */ +%token VARBINARY +%token VARCHAR /* SQL-2003-R */ +%token VARIABLES +%token VARIANCE_SYM +%token VARYING /* SQL-2003-R */ +%token VAR_SAMP_SYM +%token VIEW_SYM /* SQL-2003-N */ +%token WAIT_SYM +%token WARNINGS +%token WEEK_SYM +%token WHEN_SYM /* SQL-2003-R */ +%token WHERE /* SQL-2003-R */ +%token WHILE_SYM +%token WITH /* SQL-2003-R */ +%token WORK_SYM /* SQL-2003-N */ +%token WRAPPER_SYM +%token WRITE_SYM /* SQL-2003-N */ +%token X509_SYM +%token XA_SYM +%token XOR +%token YEAR_MONTH_SYM +%token YEAR_SYM /* SQL-2003-R */ +%token ZEROFILL + +%left JOIN_SYM INNER_SYM STRAIGHT_JOIN CROSS LEFT RIGHT +/* A dummy token to force the priority of table_ref production in a join. */ +%left TABLE_REF_PRIORITY +%left SET_VAR +%left OR_OR_SYM OR_SYM OR2_SYM +%left XOR +%left AND_SYM AND_AND_SYM +%left BETWEEN_SYM CASE_SYM WHEN_SYM THEN_SYM ELSE +%left EQ EQUAL_SYM GE GT_SYM LE LT NE IS LIKE REGEXP IN_SYM +%left '|' +%left '&' +%left SHIFT_LEFT SHIFT_RIGHT +%left '-' '+' +%left '*' '/' '%' DIV_SYM MOD_SYM +%left '^' +%left NEG '~' +%right NOT_SYM NOT2_SYM +%right BINARY COLLATE_SYM +%left INTERVAL_SYM + +%type + IDENT IDENT_QUOTED TEXT_STRING DECIMAL_NUM FLOAT_NUM NUM LONG_NUM HEX_NUM + LEX_HOSTNAME ULONGLONG_NUM field_ident select_alias ident ident_or_text + IDENT_sys TEXT_STRING_sys TEXT_STRING_literal + NCHAR_STRING opt_component key_cache_name + sp_opt_label BIN_NUM label_ident TEXT_STRING_filesystem ident_or_empty + +%type + opt_table_alias + +%type
+ table_ident table_ident_nodb references xid + +%type + remember_name remember_end opt_ident opt_db text_or_password + opt_constraint constraint + +%type + text_string opt_gconcat_separator + +%type + type int_type real_type order_dir lock_option + udf_type if_exists opt_local opt_table_options table_options + table_option opt_if_not_exists opt_no_write_to_binlog + delete_option opt_temporary all_or_any opt_distinct + opt_ignore_leaves fulltext_options spatial_type union_option + start_transaction_opts opt_chain opt_release + union_opt select_derived_init option_type2 + opt_natural_language_mode opt_query_expansion + opt_ev_status opt_ev_on_completion ev_on_completion opt_ev_comment + ev_alter_on_schedule_completion opt_ev_rename_to opt_ev_sql_stmt + +%type + ulong_num real_ulong_num merge_insert_types + +%type + ulonglong_num real_ulonglong_num size_number + +%type + part_bit_expr + +%type + replace_lock_option opt_low_priority insert_lock_option load_data_lock + +%type + literal text_literal insert_ident order_ident + simple_ident select_item2 expr opt_expr opt_else sum_expr in_sum_expr + variable variable_aux bool_pri + predicate bit_expr + table_wild simple_expr udf_expr + expr_or_default set_expr_or_default + param_marker geometry_function + signed_literal now_or_signed_literal opt_escape + sp_opt_default + simple_ident_nospvar simple_ident_q + field_or_var limit_option + part_func_expr + function_call_keyword + function_call_nonkeyword + function_call_generic + function_call_conflict + +%type + NUM_literal + +%type + expr_list opt_udf_expr_list udf_expr_list when_list + ident_list ident_list_arg opt_expr_list + +%type + option_type opt_var_type opt_var_ident_type + +%type + key_type opt_unique_or_fulltext constraint_key_type + +%type + btree_or_rtree + +%type + using_list + +%type + key_part + +%type + join_table_list join_table + table_factor table_ref esc_table_ref + select_derived derived_table_list + +%type date_time_type; +%type interval + +%type interval_time_st + +%type interval_time_stamp + +%type storage_engines known_storage_engines + +%type row_types + +%type isolation_types + +%type handler_rkey_mode + +%type cast_type + +%type keyword keyword_sp + +%type user grant_user + +%type + opt_collate + charset_name + charset_name_or_default + old_or_new_charset_name + old_or_new_charset_name_or_default + collation_name + collation_name_or_default + opt_load_data_charset + UNDERSCORE_CHARSET + +%type internal_variable_name + +%type subselect take_first_select + get_select_lex + +%type comp_op + +%type + query verb_clause create change select do drop insert replace insert2 + insert_values update delete truncate rename + show describe load alter optimize keycache preload flush + reset purge begin commit rollback savepoint release + slave master_def master_defs master_file_def slave_until_opts + repair restore backup analyze check start checksum + field_list field_list_item field_spec kill column_def key_def + keycache_list assign_to_keycache preload_list preload_keys + select_item_list select_item values_list no_braces + opt_limit_clause delete_limit_clause fields opt_values values + procedure_list procedure_list2 procedure_item + handler + opt_precision opt_ignore opt_column opt_restrict + grant revoke set lock unlock string_list field_options field_option + field_opt_list opt_binary table_lock_list table_lock + ref_list opt_on_delete opt_on_delete_list opt_on_delete_item use + opt_delete_options opt_delete_option varchar nchar nvarchar + opt_outer table_list table_name table_alias_ref_list table_alias_ref + opt_option opt_place + opt_attribute opt_attribute_list attribute column_list column_list_id + opt_column_list grant_privileges grant_ident grant_list grant_option + object_privilege object_privilege_list user_list rename_list + clear_privileges flush_options flush_option + equal optional_braces + opt_mi_check_type opt_to mi_check_types normal_join + table_to_table_list table_to_table opt_table_list opt_as + handler_rkey_function handler_read_or_scan + single_multi table_wild_list table_wild_one opt_wild + union_clause union_list + precision subselect_start opt_and charset + subselect_end select_var_list select_var_list_init help + field_length opt_field_length + opt_extended_describe + prepare prepare_src execute deallocate + statement sp_suid + sp_c_chistics sp_a_chistics sp_chistic sp_c_chistic xa + load_data opt_field_or_var_spec fields_or_vars opt_load_data_set_spec + view_replace_or_algorithm view_replace + view_algorithm view_or_trigger_or_sp_or_event + definer_tail no_definer_tail + view_suid view_tail view_list_opt view_list view_select + view_check_option trigger_tail sp_tail sf_tail udf_tail event_tail + install uninstall partition_entry binlog_base64_event + init_key_options key_options key_opts key_opt key_using_alg + server_def server_options_list server_option + definer_opt no_definer definer +END_OF_INPUT + +%type call sp_proc_stmts sp_proc_stmts1 sp_proc_stmt +%type sp_proc_stmt_statement sp_proc_stmt_return +%type sp_proc_stmt_if +%type sp_labeled_control sp_proc_stmt_unlabeled +%type sp_labeled_block sp_unlabeled_block +%type sp_proc_stmt_leave +%type sp_proc_stmt_iterate +%type sp_proc_stmt_open sp_proc_stmt_fetch sp_proc_stmt_close +%type case_stmt_specification simple_case_stmt searched_case_stmt + +%type sp_decl_idents sp_opt_inout sp_handler_type sp_hcond_list +%type sp_cond sp_hcond +%type sp_decls sp_decl +%type sp_cursor_stmt +%type sp_name +%type index_hint_type +%type index_hint_clause + +%type + '-' '+' '*' '/' '%' '(' ')' + ',' '!' '{' '}' '&' '|' AND_SYM OR_SYM OR_OR_SYM BETWEEN_SYM CASE_SYM + THEN_SYM WHEN_SYM DIV_SYM MOD_SYM OR2_SYM AND_AND_SYM +%% + +/* + Indentation of grammar rules: + +rule: <-- starts at col 1 + rule1a rule1b rule1c <-- starts at col 11 + { <-- starts at col 11 + code <-- starts at col 13, indentation is 2 spaces + } + | rule2a rule2b + { + code + } + ; <-- on a line by itself, starts at col 9 + + Also, please do not use any , but spaces. + Having a uniform indentation in this file helps + code reviews, patches, merges, and make maintenance easier. + Tip: grep [[:cntrl:]] sql_yacc.yy + Thanks. +*/ + +query: + END_OF_INPUT + { + THD *thd= YYTHD; + if (!thd->bootstrap && + (!(thd->lex->select_lex.options & OPTION_FOUND_COMMENT))) + { + my_message(ER_EMPTY_QUERY, ER(ER_EMPTY_QUERY), MYF(0)); + MYSQL_YYABORT; + } + thd->lex->sql_command= SQLCOM_EMPTY_QUERY; + YYLIP->found_semicolon= NULL; + } + | verb_clause + { + Lex_input_stream *lip = YYLIP; + + if ((YYTHD->client_capabilities & CLIENT_MULTI_QUERIES) && + ! lip->stmt_prepare_mode && + ! lip->eof()) + { + /* + We found a well formed query, and multi queries are allowed: + - force the parser to stop after the ';' + - mark the start of the next query for the next invocation + of the parser. + */ + lip->next_state= MY_LEX_END; + lip->found_semicolon= lip->get_ptr(); + } + else + { + /* Single query, terminated. */ + lip->found_semicolon= NULL; + } + } + ';' + opt_end_of_input + | verb_clause END_OF_INPUT + { + /* Single query, not terminated. */ + YYLIP->found_semicolon= NULL; + } + ; + +opt_end_of_input: + /* empty */ + | END_OF_INPUT + ; + +verb_clause: + statement + | begin + ; + +/* Verb clauses, except begin */ +statement: + alter + | analyze + | backup + | binlog_base64_event + | call + | change + | check + | checksum + | commit + | create + | deallocate + | delete + | describe + | do + | drop + | execute + | flush + | grant + | handler + | help + | insert + | install + | kill + | load + | lock + | optimize + | keycache + | partition_entry + | preload + | prepare + | purge + | release + | rename + | repair + | replace + | reset + | restore + | revoke + | rollback + | savepoint + | select + | set + | show + | slave + | start + | truncate + | uninstall + | unlock + | update + | use + | xa + ; + +deallocate: + deallocate_or_drop PREPARE_SYM ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->sql_command= SQLCOM_DEALLOCATE_PREPARE; + lex->prepared_stmt_name= $3; + } + ; + +deallocate_or_drop: + DEALLOCATE_SYM + | DROP + ; + +prepare: + PREPARE_SYM ident FROM prepare_src + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->sql_command= SQLCOM_PREPARE; + lex->prepared_stmt_name= $2; + } + ; + +prepare_src: + TEXT_STRING_sys + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->prepared_stmt_code= $1; + lex->prepared_stmt_code_is_varref= FALSE; + } + | '@' ident_or_text + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->prepared_stmt_code= $2; + lex->prepared_stmt_code_is_varref= TRUE; + } + ; + +execute: + EXECUTE_SYM ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->sql_command= SQLCOM_EXECUTE; + lex->prepared_stmt_name= $2; + } + execute_using + {} + ; + +execute_using: + /* nothing */ + | USING execute_var_list + ; + +execute_var_list: + execute_var_list ',' execute_var_ident + | execute_var_ident + ; + +execute_var_ident: + '@' ident_or_text + { + LEX *lex=Lex; + LEX_STRING *lexstr= (LEX_STRING*)sql_memdup(&$2, sizeof(LEX_STRING)); + if (!lexstr || lex->prepared_stmt_params.push_back(lexstr)) + MYSQL_YYABORT; + } + ; + +/* help */ + +help: + HELP_SYM + { + if (Lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "HELP"); + MYSQL_YYABORT; + } + } + ident_or_text + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_HELP; + lex->help_arg= $3.str; + } + ; + +/* change master */ + +change: + CHANGE MASTER_SYM TO_SYM + { + LEX *lex = Lex; + lex->sql_command = SQLCOM_CHANGE_MASTER; + bzero((char*) &lex->mi, sizeof(lex->mi)); + } + master_defs + {} + ; + +master_defs: + master_def + | master_defs ',' master_def + ; + +master_def: + MASTER_HOST_SYM EQ TEXT_STRING_sys + { + Lex->mi.host = $3.str; + } + | MASTER_USER_SYM EQ TEXT_STRING_sys + { + Lex->mi.user = $3.str; + } + | MASTER_PASSWORD_SYM EQ TEXT_STRING_sys + { + Lex->mi.password = $3.str; + } + | MASTER_PORT_SYM EQ ulong_num + { + Lex->mi.port = $3; + } + | MASTER_CONNECT_RETRY_SYM EQ ulong_num + { + Lex->mi.connect_retry = $3; + } + | MASTER_SSL_SYM EQ ulong_num + { + Lex->mi.ssl= $3 ? + LEX_MASTER_INFO::SSL_ENABLE : LEX_MASTER_INFO::SSL_DISABLE; + } + | MASTER_SSL_CA_SYM EQ TEXT_STRING_sys + { + Lex->mi.ssl_ca= $3.str; + } + | MASTER_SSL_CAPATH_SYM EQ TEXT_STRING_sys + { + Lex->mi.ssl_capath= $3.str; + } + | MASTER_SSL_CERT_SYM EQ TEXT_STRING_sys + { + Lex->mi.ssl_cert= $3.str; + } + | MASTER_SSL_CIPHER_SYM EQ TEXT_STRING_sys + { + Lex->mi.ssl_cipher= $3.str; + } + | MASTER_SSL_KEY_SYM EQ TEXT_STRING_sys + { + Lex->mi.ssl_key= $3.str; + } + | MASTER_SSL_VERIFY_SERVER_CERT_SYM EQ ulong_num + { + Lex->mi.ssl_verify_server_cert= $3 ? + LEX_MASTER_INFO::SSL_ENABLE : LEX_MASTER_INFO::SSL_DISABLE; + } + | master_file_def + ; + +master_file_def: + MASTER_LOG_FILE_SYM EQ TEXT_STRING_sys + { + Lex->mi.log_file_name = $3.str; + } + | MASTER_LOG_POS_SYM EQ ulonglong_num + { + Lex->mi.pos = $3; + /* + If the user specified a value < BIN_LOG_HEADER_SIZE, adjust it + instead of causing subsequent errors. + We need to do it in this file, because only there we know that + MASTER_LOG_POS has been explicitely specified. On the contrary + in change_master() (sql_repl.cc) we cannot distinguish between 0 + (MASTER_LOG_POS explicitely specified as 0) and 0 (unspecified), + whereas we want to distinguish (specified 0 means "read the binlog + from 0" (4 in fact), unspecified means "don't change the position + (keep the preceding value)"). + */ + Lex->mi.pos = max(BIN_LOG_HEADER_SIZE, Lex->mi.pos); + } + | RELAY_LOG_FILE_SYM EQ TEXT_STRING_sys + { + Lex->mi.relay_log_name = $3.str; + } + | RELAY_LOG_POS_SYM EQ ulong_num + { + Lex->mi.relay_log_pos = $3; + /* Adjust if < BIN_LOG_HEADER_SIZE (same comment as Lex->mi.pos) */ + Lex->mi.relay_log_pos = max(BIN_LOG_HEADER_SIZE, Lex->mi.relay_log_pos); + } + ; + +/* create a table */ + +create: + CREATE opt_table_options TABLE_SYM opt_if_not_exists table_ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->sql_command= SQLCOM_CREATE_TABLE; + if (!lex->select_lex.add_table_to_list(thd, $5, NULL, + TL_OPTION_UPDATING, + TL_WRITE)) + MYSQL_YYABORT; + lex->alter_info.reset(); + lex->col_list.empty(); + lex->change=NullS; + bzero((char*) &lex->create_info,sizeof(lex->create_info)); + lex->create_info.options=$2 | $4; + lex->create_info.db_type= ha_default_handlerton(thd); + lex->create_info.default_table_charset= NULL; + lex->name.str= 0; + lex->name.length= 0; + } + create2 + { + LEX *lex= YYTHD->lex; + lex->current_select= &lex->select_lex; + if (!lex->create_info.db_type) + { + lex->create_info.db_type= ha_default_handlerton(YYTHD); + push_warning_printf(YYTHD, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_USING_OTHER_HANDLER, + ER(ER_WARN_USING_OTHER_HANDLER), + ha_resolve_storage_engine_name(lex->create_info.db_type), + $5->table.str); + } + } + | CREATE opt_unique_or_fulltext INDEX_SYM ident key_alg ON + table_ident + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_CREATE_INDEX; + if (!lex->current_select->add_table_to_list(lex->thd, $7, + NULL, + TL_OPTION_UPDATING)) + MYSQL_YYABORT; + lex->alter_info.reset(); + lex->alter_info.flags= ALTER_ADD_INDEX; + lex->col_list.empty(); + lex->change=NullS; + } + '(' key_list ')' key_options + { + LEX *lex=Lex; + Key *key; + if ($2 != Key::FULLTEXT && lex->key_create_info.parser_name.str) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + key= new Key($2, $4.str, &lex->key_create_info, 0, + lex->col_list); + if (key == NULL) + MYSQL_YYABORT; + lex->alter_info.key_list.push_back(key); + lex->col_list.empty(); + } + | CREATE DATABASE opt_if_not_exists ident + { + Lex->create_info.default_table_charset= NULL; + Lex->create_info.used_fields= 0; + } + opt_create_database_options + { + LEX *lex=Lex; + lex->sql_command=SQLCOM_CREATE_DB; + lex->name= $4; + lex->create_info.options=$3; + } + | CREATE + { + Lex->create_view_mode= VIEW_CREATE_NEW; + Lex->create_view_algorithm= VIEW_ALGORITHM_UNDEFINED; + Lex->create_view_suid= TRUE; + } + view_or_trigger_or_sp_or_event + {} + | CREATE USER clear_privileges grant_list + { + Lex->sql_command = SQLCOM_CREATE_USER; + } + | CREATE LOGFILE_SYM GROUP_SYM logfile_group_info + { + Lex->alter_tablespace_info->ts_cmd_type= CREATE_LOGFILE_GROUP; + } + | CREATE TABLESPACE tablespace_info + { + Lex->alter_tablespace_info->ts_cmd_type= CREATE_TABLESPACE; + } + | CREATE server_def + { + Lex->sql_command= SQLCOM_CREATE_SERVER; + } + ; + +server_def: + SERVER_SYM + ident_or_text + FOREIGN DATA_SYM WRAPPER_SYM + ident_or_text + OPTIONS_SYM '(' server_options_list ')' + { + Lex->server_options.server_name= $2.str; + Lex->server_options.server_name_length= $2.length; + Lex->server_options.scheme= $6.str; + } + ; + +server_options_list: + server_option + | server_options_list ',' server_option + ; + +server_option: + USER TEXT_STRING_sys + { + Lex->server_options.username= $2.str; + } + | HOST_SYM TEXT_STRING_sys + { + Lex->server_options.host= $2.str; + } + | DATABASE TEXT_STRING_sys + { + Lex->server_options.db= $2.str; + } + | OWNER_SYM TEXT_STRING_sys + { + Lex->server_options.owner= $2.str; + } + | PASSWORD TEXT_STRING_sys + { + Lex->server_options.password= $2.str; + } + | SOCKET_SYM TEXT_STRING_sys + { + Lex->server_options.socket= $2.str; + } + | PORT_SYM ulong_num + { + Lex->server_options.port= $2; + } + ; + +event_tail: + remember_name EVENT_SYM opt_if_not_exists sp_name + { + THD *thd= YYTHD; + LEX *lex=Lex; + + lex->stmt_definition_begin= $1; + lex->create_info.options= $3; + if (!(lex->event_parse_data= Event_parse_data::new_instance(thd))) + MYSQL_YYABORT; + lex->event_parse_data->identifier= $4; + lex->event_parse_data->on_completion= + Event_parse_data::ON_COMPLETION_DROP; + + lex->sql_command= SQLCOM_CREATE_EVENT; + /* We need that for disallowing subqueries */ + } + ON SCHEDULE_SYM ev_schedule_time + opt_ev_on_completion + opt_ev_status + opt_ev_comment + DO_SYM ev_sql_stmt + { + /* + sql_command is set here because some rules in ev_sql_stmt + can overwrite it + */ + Lex->sql_command= SQLCOM_CREATE_EVENT; + } + ; + +ev_schedule_time: + EVERY_SYM expr interval + { + Lex->event_parse_data->item_expression= $2; + Lex->event_parse_data->interval= $3; + } + ev_starts + ev_ends + | AT_SYM expr + { + Lex->event_parse_data->item_execute_at= $2; + } + ; + +opt_ev_status: + /* empty */ { $$= 0; } + | ENABLE_SYM + { + Lex->event_parse_data->status= Event_parse_data::ENABLED; + $$= 1; + } + | DISABLE_SYM ON SLAVE + { + Lex->event_parse_data->status= Event_parse_data::SLAVESIDE_DISABLED; + $$= 1; + } + | DISABLE_SYM + { + Lex->event_parse_data->status= Event_parse_data::DISABLED; + $$= 1; + } + ; + +ev_starts: + /* empty */ + { + Item *item= new (YYTHD->mem_root) Item_func_now_local(); + if (item == NULL) + MYSQL_YYABORT; + Lex->event_parse_data->item_starts= item; + } + | STARTS_SYM expr + { + Lex->event_parse_data->item_starts= $2; + } + ; + +ev_ends: + /* empty */ + | ENDS_SYM expr + { + Lex->event_parse_data->item_ends= $2; + } + ; + +opt_ev_on_completion: + /* empty */ { $$= 0; } + | ev_on_completion + ; + +ev_on_completion: + ON COMPLETION_SYM PRESERVE_SYM + { + Lex->event_parse_data->on_completion= + Event_parse_data::ON_COMPLETION_PRESERVE; + $$= 1; + } + | ON COMPLETION_SYM NOT_SYM PRESERVE_SYM + { + Lex->event_parse_data->on_completion= + Event_parse_data::ON_COMPLETION_DROP; + $$= 1; + } + ; + +opt_ev_comment: + /* empty */ { $$= 0; } + | COMMENT_SYM TEXT_STRING_sys + { + Lex->comment= Lex->event_parse_data->comment= $2; + $$= 1; + } + ; + +ev_sql_stmt: + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + + /* + This stops the following : + - CREATE EVENT ... DO CREATE EVENT ...; + - ALTER EVENT ... DO CREATE EVENT ...; + - CREATE EVENT ... DO ALTER EVENT DO ....; + - CREATE PROCEDURE ... BEGIN CREATE EVENT ... END| + This allows: + - CREATE EVENT ... DO DROP EVENT yyy; + - CREATE EVENT ... DO ALTER EVENT yyy; + (the nested ALTER EVENT can have anything but DO clause) + - ALTER EVENT ... DO ALTER EVENT yyy; + (the nested ALTER EVENT can have anything but DO clause) + - ALTER EVENT ... DO DROP EVENT yyy; + - CREATE PROCEDURE ... BEGIN ALTER EVENT ... END| + (the nested ALTER EVENT can have anything but DO clause) + - CREATE PROCEDURE ... BEGIN DROP EVENT ... END| + */ + if (lex->sphead) + { + my_error(ER_EVENT_RECURSION_FORBIDDEN, MYF(0)); + MYSQL_YYABORT; + } + + if (!(lex->sphead= new sp_head())) + MYSQL_YYABORT; + + lex->sphead->reset_thd_mem_root(thd); + lex->sphead->init(lex); + lex->sphead->init_sp_name(thd, lex->event_parse_data->identifier); + + lex->sphead->m_type= TYPE_ENUM_PROCEDURE; + + bzero((char *)&lex->sp_chistics, sizeof(st_sp_chistics)); + lex->sphead->m_chistics= &lex->sp_chistics; + + lex->sphead->set_body_start(thd, lip->get_cpp_ptr()); + } + ev_sql_stmt_inner + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + + /* return back to the original memory root ASAP */ + lex->sphead->set_stmt_end(thd); + lex->sphead->restore_thd_mem_root(thd); + + lex->sp_chistics.suid= SP_IS_SUID; //always the definer! + + lex->event_parse_data->body_changed= TRUE; + } + ; + +ev_sql_stmt_inner: + sp_proc_stmt_statement + | sp_proc_stmt_return + | sp_proc_stmt_if + | case_stmt_specification + | sp_labeled_block + | sp_unlabeled_block + | sp_labeled_control + | sp_proc_stmt_unlabeled + | sp_proc_stmt_leave + | sp_proc_stmt_iterate + | sp_proc_stmt_open + | sp_proc_stmt_fetch + | sp_proc_stmt_close + ; + +clear_privileges: + /* Nothing */ + { + LEX *lex=Lex; + lex->users_list.empty(); + lex->columns.empty(); + lex->grant= lex->grant_tot_col= 0; + lex->all_privileges= 0; + lex->select_lex.db= 0; + lex->ssl_type= SSL_TYPE_NOT_SPECIFIED; + lex->ssl_cipher= lex->x509_subject= lex->x509_issuer= 0; + bzero((char *)&(lex->mqh),sizeof(lex->mqh)); + } + ; + +sp_name: + ident '.' ident + { + if (!$1.str || check_db_name(&$1)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), $1.str); + MYSQL_YYABORT; + } + if (check_routine_name(&$3)) + { + MYSQL_YYABORT; + } + $$= new sp_name($1, $3, true); + if ($$ == NULL) + MYSQL_YYABORT; + $$->init_qname(YYTHD); + } + | ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + LEX_STRING db; + if (check_routine_name(&$1)) + { + MYSQL_YYABORT; + } + if (lex->copy_db_to(&db.str, &db.length)) + MYSQL_YYABORT; + $$= new sp_name(db, $1, false); + if ($$ == NULL) + MYSQL_YYABORT; + $$->init_qname(thd); + } + ; + +sp_a_chistics: + /* Empty */ {} + | sp_a_chistics sp_chistic {} + ; + +sp_c_chistics: + /* Empty */ {} + | sp_c_chistics sp_c_chistic {} + ; + +/* Characteristics for both create and alter */ +sp_chistic: + COMMENT_SYM TEXT_STRING_sys + { Lex->sp_chistics.comment= $2; } + | LANGUAGE_SYM SQL_SYM + { /* Just parse it, we only have one language for now. */ } + | NO_SYM SQL_SYM + { Lex->sp_chistics.daccess= SP_NO_SQL; } + | CONTAINS_SYM SQL_SYM + { Lex->sp_chistics.daccess= SP_CONTAINS_SQL; } + | READS_SYM SQL_SYM DATA_SYM + { Lex->sp_chistics.daccess= SP_READS_SQL_DATA; } + | MODIFIES_SYM SQL_SYM DATA_SYM + { Lex->sp_chistics.daccess= SP_MODIFIES_SQL_DATA; } + | sp_suid + {} + ; + +/* Create characteristics */ +sp_c_chistic: + sp_chistic { } + | DETERMINISTIC_SYM { Lex->sp_chistics.detistic= TRUE; } + | not DETERMINISTIC_SYM { Lex->sp_chistics.detistic= FALSE; } + ; + +sp_suid: + SQL_SYM SECURITY_SYM DEFINER_SYM + { + Lex->sp_chistics.suid= SP_IS_SUID; + } + | SQL_SYM SECURITY_SYM INVOKER_SYM + { + Lex->sp_chistics.suid= SP_IS_NOT_SUID; + } + ; + +call: + CALL_SYM sp_name + { + LEX *lex = Lex; + + lex->sql_command= SQLCOM_CALL; + lex->spname= $2; + lex->value_list.empty(); + sp_add_used_routine(lex, YYTHD, $2, TYPE_ENUM_PROCEDURE); + } + opt_sp_cparam_list {} + ; + +/* CALL parameters */ +opt_sp_cparam_list: + /* Empty */ + | '(' opt_sp_cparams ')' + ; + +opt_sp_cparams: + /* Empty */ + | sp_cparams + ; + +sp_cparams: + sp_cparams ',' expr + { + Lex->value_list.push_back($3); + } + | expr + { + Lex->value_list.push_back($1); + } + ; + +/* Stored FUNCTION parameter declaration list */ +sp_fdparam_list: + /* Empty */ + | sp_fdparams + ; + +sp_fdparams: + sp_fdparams ',' sp_fdparam + | sp_fdparam + ; + +sp_init_param: + /* Empty */ + { + LEX *lex= Lex; + + lex->length= 0; + lex->dec= 0; + lex->type= 0; + + lex->default_value= 0; + lex->on_update_value= 0; + + lex->comment= null_lex_str; + lex->charset= NULL; + + lex->interval_list.empty(); + lex->uint_geom_type= 0; + } + ; + +sp_fdparam: + ident sp_init_param type + { + LEX *lex= Lex; + sp_pcontext *spc= lex->spcont; + + if (spc->find_variable(&$1, TRUE)) + { + my_error(ER_SP_DUP_PARAM, MYF(0), $1.str); + MYSQL_YYABORT; + } + sp_variable_t *spvar= spc->push_variable(&$1, + (enum enum_field_types)$3, + sp_param_in); + + if (lex->sphead->fill_field_definition(YYTHD, lex, + (enum enum_field_types) $3, + &spvar->field_def)) + { + MYSQL_YYABORT; + } + spvar->field_def.field_name= spvar->name.str; + spvar->field_def.pack_flag |= FIELDFLAG_MAYBE_NULL; + } + ; + +/* Stored PROCEDURE parameter declaration list */ +sp_pdparam_list: + /* Empty */ + | sp_pdparams + ; + +sp_pdparams: + sp_pdparams ',' sp_pdparam + | sp_pdparam + ; + +sp_pdparam: + sp_opt_inout sp_init_param ident type + { + LEX *lex= Lex; + sp_pcontext *spc= lex->spcont; + + if (spc->find_variable(&$3, TRUE)) + { + my_error(ER_SP_DUP_PARAM, MYF(0), $3.str); + MYSQL_YYABORT; + } + sp_variable_t *spvar= spc->push_variable(&$3, + (enum enum_field_types)$4, + (sp_param_mode_t)$1); + + if (lex->sphead->fill_field_definition(YYTHD, lex, + (enum enum_field_types) $4, + &spvar->field_def)) + { + MYSQL_YYABORT; + } + spvar->field_def.field_name= spvar->name.str; + spvar->field_def.pack_flag |= FIELDFLAG_MAYBE_NULL; + } + ; + +sp_opt_inout: + /* Empty */ { $$= sp_param_in; } + | IN_SYM { $$= sp_param_in; } + | OUT_SYM { $$= sp_param_out; } + | INOUT_SYM { $$= sp_param_inout; } + ; + +sp_proc_stmts: + /* Empty */ {} + | sp_proc_stmts sp_proc_stmt ';' + ; + +sp_proc_stmts1: + sp_proc_stmt ';' {} + | sp_proc_stmts1 sp_proc_stmt ';' + ; + +sp_decls: + /* Empty */ + { + $$.vars= $$.conds= $$.hndlrs= $$.curs= 0; + } + | sp_decls sp_decl ';' + { + /* We check for declarations out of (standard) order this way + because letting the grammar rules reflect it caused tricky + shift/reduce conflicts with the wrong result. (And we get + better error handling this way.) */ + if (($2.vars || $2.conds) && ($1.curs || $1.hndlrs)) + { /* Variable or condition following cursor or handler */ + my_message(ER_SP_VARCOND_AFTER_CURSHNDLR, + ER(ER_SP_VARCOND_AFTER_CURSHNDLR), MYF(0)); + MYSQL_YYABORT; + } + if ($2.curs && $1.hndlrs) + { /* Cursor following handler */ + my_message(ER_SP_CURSOR_AFTER_HANDLER, + ER(ER_SP_CURSOR_AFTER_HANDLER), MYF(0)); + MYSQL_YYABORT; + } + $$.vars= $1.vars + $2.vars; + $$.conds= $1.conds + $2.conds; + $$.hndlrs= $1.hndlrs + $2.hndlrs; + $$.curs= $1.curs + $2.curs; + } + ; + +sp_decl: + DECLARE_SYM sp_decl_idents + { + LEX *lex= Lex; + + lex->sphead->reset_lex(YYTHD); + lex->spcont->declare_var_boundary($2); + } + type + sp_opt_default + { + THD *thd= YYTHD; + LEX *lex= Lex; + sp_pcontext *pctx= lex->spcont; + uint num_vars= pctx->context_var_count(); + enum enum_field_types var_type= (enum enum_field_types) $4; + Item *dflt_value_item= $5; + + if (!dflt_value_item) + { + dflt_value_item= new (thd->mem_root) Item_null(); + if (dflt_value_item == NULL) + MYSQL_YYABORT; + /* QQ Set to the var_type with null_value? */ + } + + for (uint i = num_vars-$2 ; i < num_vars ; i++) + { + uint var_idx= pctx->var_context2runtime(i); + sp_variable_t *spvar= pctx->find_variable(var_idx); + + if (!spvar) + MYSQL_YYABORT; + + spvar->type= var_type; + spvar->dflt= dflt_value_item; + + if (lex->sphead->fill_field_definition(YYTHD, lex, var_type, + &spvar->field_def)) + { + MYSQL_YYABORT; + } + + spvar->field_def.field_name= spvar->name.str; + spvar->field_def.pack_flag |= FIELDFLAG_MAYBE_NULL; + + /* The last instruction is responsible for freeing LEX. */ + + sp_instr_set *is= new sp_instr_set(lex->sphead->instructions(), + pctx, + var_idx, + dflt_value_item, + var_type, + lex, + (i == num_vars - 1)); + if (is == NULL || + lex->sphead->add_instr(is)) + MYSQL_YYABORT; + } + + pctx->declare_var_boundary(0); + lex->sphead->restore_lex(YYTHD); + + $$.vars= $2; + $$.conds= $$.hndlrs= $$.curs= 0; + } + | DECLARE_SYM ident CONDITION_SYM FOR_SYM sp_cond + { + LEX *lex= Lex; + sp_pcontext *spc= lex->spcont; + + if (spc->find_cond(&$2, TRUE)) + { + my_error(ER_SP_DUP_COND, MYF(0), $2.str); + MYSQL_YYABORT; + } + if(YYTHD->lex->spcont->push_cond(&$2, $5)) + MYSQL_YYABORT; + $$.vars= $$.hndlrs= $$.curs= 0; + $$.conds= 1; + } + | DECLARE_SYM sp_handler_type HANDLER_SYM FOR_SYM + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + + lex->spcont= lex->spcont->push_context(LABEL_HANDLER_SCOPE); + + sp_pcontext *ctx= lex->spcont; + sp_instr_hpush_jump *i= + new sp_instr_hpush_jump(sp->instructions(), ctx, $2, + ctx->current_var_count()); + if (i == NULL || + sp->add_instr(i) || + sp->push_backpatch(i, ctx->push_label((char *)"", 0))) + MYSQL_YYABORT; + } + sp_hcond_list sp_proc_stmt + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + sp_label_t *hlab= lex->spcont->pop_label(); /* After this hdlr */ + sp_instr_hreturn *i; + + if ($2 == SP_HANDLER_CONTINUE) + { + i= new sp_instr_hreturn(sp->instructions(), ctx, + ctx->current_var_count()); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + else + { /* EXIT or UNDO handler, just jump to the end of the block */ + i= new sp_instr_hreturn(sp->instructions(), ctx, 0); + if (i == NULL || + sp->add_instr(i) || + sp->push_backpatch(i, lex->spcont->last_label())) /* Block end */ + MYSQL_YYABORT; + } + lex->sphead->backpatch(hlab); + + lex->spcont= ctx->pop_context(); + + $$.vars= $$.conds= $$.curs= 0; + $$.hndlrs= $6; + lex->spcont->add_handlers($6); + } + | DECLARE_SYM ident CURSOR_SYM FOR_SYM sp_cursor_stmt + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + uint offp; + sp_instr_cpush *i; + + if (ctx->find_cursor(&$2, &offp, TRUE)) + { + my_error(ER_SP_DUP_CURS, MYF(0), $2.str); + delete $5; + MYSQL_YYABORT; + } + i= new sp_instr_cpush(sp->instructions(), ctx, $5, + ctx->current_cursor_count()); + if (i == NULL || + sp->add_instr(i) || + ctx->push_cursor(&$2)) + MYSQL_YYABORT; + $$.vars= $$.conds= $$.hndlrs= 0; + $$.curs= 1; + } + ; + +sp_cursor_stmt: + { + Lex->sphead->reset_lex(YYTHD); + } + select + { + LEX *lex= Lex; + + DBUG_ASSERT(lex->sql_command == SQLCOM_SELECT); + + if (lex->result) + { + my_message(ER_SP_BAD_CURSOR_SELECT, ER(ER_SP_BAD_CURSOR_SELECT), + MYF(0)); + MYSQL_YYABORT; + } + lex->sp_lex_in_use= TRUE; + $$= lex; + lex->sphead->restore_lex(YYTHD); + } + ; + +sp_handler_type: + EXIT_SYM { $$= SP_HANDLER_EXIT; } + | CONTINUE_SYM { $$= SP_HANDLER_CONTINUE; } + /*| UNDO_SYM { QQ No yet } */ + ; + +sp_hcond_list: + sp_hcond_element + { $$= 1; } + | sp_hcond_list ',' sp_hcond_element + { $$+= 1; } + ; + +sp_hcond_element: + sp_hcond + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont->parent_context(); + + if (ctx->find_handler($1)) + { + my_message(ER_SP_DUP_HANDLER, ER(ER_SP_DUP_HANDLER), MYF(0)); + MYSQL_YYABORT; + } + else + { + sp_instr_hpush_jump *i= + (sp_instr_hpush_jump *)sp->last_instruction(); + + i->add_condition($1); + ctx->push_handler($1); + } + } + ; + +sp_cond: + ulong_num + { /* mysql errno */ + $$= (sp_cond_type_t *)YYTHD->alloc(sizeof(sp_cond_type_t)); + if ($$ == NULL) + MYSQL_YYABORT; + $$->type= sp_cond_type_t::number; + $$->mysqlerr= $1; + } + | SQLSTATE_SYM opt_value TEXT_STRING_literal + { /* SQLSTATE */ + if (!sp_cond_check(&$3)) + { + my_error(ER_SP_BAD_SQLSTATE, MYF(0), $3.str); + MYSQL_YYABORT; + } + $$= (sp_cond_type_t *)YYTHD->alloc(sizeof(sp_cond_type_t)); + if ($$ == NULL) + MYSQL_YYABORT; + $$->type= sp_cond_type_t::state; + memcpy($$->sqlstate, $3.str, 5); + $$->sqlstate[5]= '\0'; + } + ; + +opt_value: + /* Empty */ {} + | VALUE_SYM {} + ; + +sp_hcond: + sp_cond + { + $$= $1; + } + | ident /* CONDITION name */ + { + $$= Lex->spcont->find_cond(&$1); + if ($$ == NULL) + { + my_error(ER_SP_COND_MISMATCH, MYF(0), $1.str); + MYSQL_YYABORT; + } + } + | SQLWARNING_SYM /* SQLSTATEs 01??? */ + { + $$= (sp_cond_type_t *)YYTHD->alloc(sizeof(sp_cond_type_t)); + if ($$ == NULL) + MYSQL_YYABORT; + $$->type= sp_cond_type_t::warning; + } + | not FOUND_SYM /* SQLSTATEs 02??? */ + { + $$= (sp_cond_type_t *)YYTHD->alloc(sizeof(sp_cond_type_t)); + if ($$ == NULL) + MYSQL_YYABORT; + $$->type= sp_cond_type_t::notfound; + } + | SQLEXCEPTION_SYM /* All other SQLSTATEs */ + { + $$= (sp_cond_type_t *)YYTHD->alloc(sizeof(sp_cond_type_t)); + if ($$ == NULL) + MYSQL_YYABORT; + $$->type= sp_cond_type_t::exception; + } + ; + +sp_decl_idents: + ident + { + /* NOTE: field definition is filled in sp_decl section. */ + + LEX *lex= Lex; + sp_pcontext *spc= lex->spcont; + + if (spc->find_variable(&$1, TRUE)) + { + my_error(ER_SP_DUP_VAR, MYF(0), $1.str); + MYSQL_YYABORT; + } + spc->push_variable(&$1, (enum_field_types)0, sp_param_in); + $$= 1; + } + | sp_decl_idents ',' ident + { + /* NOTE: field definition is filled in sp_decl section. */ + + LEX *lex= Lex; + sp_pcontext *spc= lex->spcont; + + if (spc->find_variable(&$3, TRUE)) + { + my_error(ER_SP_DUP_VAR, MYF(0), $3.str); + MYSQL_YYABORT; + } + spc->push_variable(&$3, (enum_field_types)0, sp_param_in); + $$= $1 + 1; + } + ; + +sp_opt_default: + /* Empty */ { $$ = NULL; } + | DEFAULT expr { $$ = $2; } + ; + +sp_proc_stmt: + sp_proc_stmt_statement + | sp_proc_stmt_return + | sp_proc_stmt_if + | case_stmt_specification + | sp_labeled_block + | sp_unlabeled_block + | sp_labeled_control + | sp_proc_stmt_unlabeled + | sp_proc_stmt_leave + | sp_proc_stmt_iterate + | sp_proc_stmt_open + | sp_proc_stmt_fetch + | sp_proc_stmt_close + ; + +sp_proc_stmt_if: + IF + { Lex->sphead->new_cont_backpatch(NULL); } + sp_if END IF + { Lex->sphead->do_cont_backpatch(); } + ; + +sp_proc_stmt_statement: + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + + lex->sphead->reset_lex(thd); + lex->sphead->m_tmp_query= lip->get_tok_start(); + } + statement + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + sp_head *sp= lex->sphead; + + sp->m_flags|= sp_get_flags_for_command(lex); + if (lex->sql_command == SQLCOM_CHANGE_DB) + { /* "USE db" doesn't work in a procedure */ + my_error(ER_SP_BADSTATEMENT, MYF(0), "USE"); + MYSQL_YYABORT; + } + /* + Don't add an instruction for SET statements, since all + instructions for them were already added during processing + of "set" rule. + */ + DBUG_ASSERT(lex->sql_command != SQLCOM_SET_OPTION || + lex->var_list.is_empty()); + if (lex->sql_command != SQLCOM_SET_OPTION) + { + sp_instr_stmt *i=new sp_instr_stmt(sp->instructions(), + lex->spcont, lex); + if (i == NULL) + MYSQL_YYABORT; + + /* + Extract the query statement from the tokenizer. The + end is either lex->ptr, if there was no lookahead, + lex->tok_end otherwise. + */ + if (yychar == YYEMPTY) + i->m_query.length= lip->get_ptr() - sp->m_tmp_query; + else + i->m_query.length= lip->get_tok_end() - sp->m_tmp_query; + if (!(i->m_query.str= strmake_root(thd->mem_root, + sp->m_tmp_query, + i->m_query.length)) || + sp->add_instr(i)) + MYSQL_YYABORT; + } + sp->restore_lex(thd); + } + ; + +sp_proc_stmt_return: + RETURN_SYM + { Lex->sphead->reset_lex(YYTHD); } + expr + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + + if (sp->m_type != TYPE_ENUM_FUNCTION) + { + my_message(ER_SP_BADRETURN, ER(ER_SP_BADRETURN), MYF(0)); + MYSQL_YYABORT; + } + else + { + sp_instr_freturn *i; + + i= new sp_instr_freturn(sp->instructions(), lex->spcont, $3, + sp->m_return_field_def.sql_type, lex); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + sp->m_flags|= sp_head::HAS_RETURN; + } + sp->restore_lex(YYTHD); + } + ; + +sp_proc_stmt_unlabeled: + { /* Unlabeled controls get a secret label. */ + LEX *lex= Lex; + + lex->spcont->push_label((char *)"", lex->sphead->instructions()); + } + sp_unlabeled_control + { + LEX *lex= Lex; + + lex->sphead->backpatch(lex->spcont->pop_label()); + } + ; + +sp_proc_stmt_leave: + LEAVE_SYM label_ident + { + LEX *lex= Lex; + sp_head *sp = lex->sphead; + sp_pcontext *ctx= lex->spcont; + sp_label_t *lab= ctx->find_label($2.str); + + if (! lab) + { + my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "LEAVE", $2.str); + MYSQL_YYABORT; + } + else + { + sp_instr_jump *i; + uint ip= sp->instructions(); + uint n; + /* + When jumping to a BEGIN-END block end, the target jump + points to the block hpop/cpop cleanup instructions, + so we should exclude the block context here. + When jumping to something else (i.e., SP_LAB_ITER), + there are no hpop/cpop at the jump destination, + so we should include the block context here for cleanup. + */ + bool exclusive= (lab->type == SP_LAB_BEGIN); + + n= ctx->diff_handlers(lab->ctx, exclusive); + if (n) + { + sp_instr_hpop *hpop= new sp_instr_hpop(ip++, ctx, n); + if (hpop == NULL) + MYSQL_YYABORT; + sp->add_instr(hpop); + } + n= ctx->diff_cursors(lab->ctx, exclusive); + if (n) + { + sp_instr_cpop *cpop= new sp_instr_cpop(ip++, ctx, n); + if (cpop == NULL) + MYSQL_YYABORT; + sp->add_instr(cpop); + } + i= new sp_instr_jump(ip, ctx); + if (i == NULL) + MYSQL_YYABORT; + sp->push_backpatch(i, lab); /* Jumping forward */ + sp->add_instr(i); + } + } + ; + +sp_proc_stmt_iterate: + ITERATE_SYM label_ident + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + sp_label_t *lab= ctx->find_label($2.str); + + if (! lab || lab->type != SP_LAB_ITER) + { + my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "ITERATE", $2.str); + MYSQL_YYABORT; + } + else + { + sp_instr_jump *i; + uint ip= sp->instructions(); + uint n; + + n= ctx->diff_handlers(lab->ctx, FALSE); /* Inclusive the dest. */ + if (n) + { + sp_instr_hpop *hpop= new sp_instr_hpop(ip++, ctx, n); + if (hpop == NULL || + sp->add_instr(hpop)) + MYSQL_YYABORT; + } + n= ctx->diff_cursors(lab->ctx, FALSE); /* Inclusive the dest. */ + if (n) + { + sp_instr_cpop *cpop= new sp_instr_cpop(ip++, ctx, n); + if (cpop == NULL || + sp->add_instr(cpop)) + MYSQL_YYABORT; + } + i= new sp_instr_jump(ip, ctx, lab->ip); /* Jump back */ + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + } + ; + +sp_proc_stmt_open: + OPEN_SYM ident + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + uint offset; + sp_instr_copen *i; + + if (! lex->spcont->find_cursor(&$2, &offset)) + { + my_error(ER_SP_CURSOR_MISMATCH, MYF(0), $2.str); + MYSQL_YYABORT; + } + i= new sp_instr_copen(sp->instructions(), lex->spcont, offset); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + ; + +sp_proc_stmt_fetch: + FETCH_SYM sp_opt_fetch_noise ident INTO + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + uint offset; + sp_instr_cfetch *i; + + if (! lex->spcont->find_cursor(&$3, &offset)) + { + my_error(ER_SP_CURSOR_MISMATCH, MYF(0), $3.str); + MYSQL_YYABORT; + } + i= new sp_instr_cfetch(sp->instructions(), lex->spcont, offset); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + sp_fetch_list + {} + ; + +sp_proc_stmt_close: + CLOSE_SYM ident + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + uint offset; + sp_instr_cclose *i; + + if (! lex->spcont->find_cursor(&$2, &offset)) + { + my_error(ER_SP_CURSOR_MISMATCH, MYF(0), $2.str); + MYSQL_YYABORT; + } + i= new sp_instr_cclose(sp->instructions(), lex->spcont, offset); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + ; + +sp_opt_fetch_noise: + /* Empty */ + | NEXT_SYM FROM + | FROM + ; + +sp_fetch_list: + ident + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *spc= lex->spcont; + sp_variable_t *spv; + + if (!spc || !(spv = spc->find_variable(&$1))) + { + my_error(ER_SP_UNDECLARED_VAR, MYF(0), $1.str); + MYSQL_YYABORT; + } + else + { + /* An SP local variable */ + sp_instr_cfetch *i= (sp_instr_cfetch *)sp->last_instruction(); + + i->add_to_varlist(spv); + } + } + | sp_fetch_list ',' ident + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *spc= lex->spcont; + sp_variable_t *spv; + + if (!spc || !(spv = spc->find_variable(&$3))) + { + my_error(ER_SP_UNDECLARED_VAR, MYF(0), $3.str); + MYSQL_YYABORT; + } + else + { + /* An SP local variable */ + sp_instr_cfetch *i= (sp_instr_cfetch *)sp->last_instruction(); + + i->add_to_varlist(spv); + } + } + ; + +sp_if: + { Lex->sphead->reset_lex(YYTHD); } + expr THEN_SYM + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + uint ip= sp->instructions(); + sp_instr_jump_if_not *i = new sp_instr_jump_if_not(ip, ctx, + $2, lex); + if (i == NULL || + sp->push_backpatch(i, ctx->push_label((char *)"", 0)) || + sp->add_cont_backpatch(i) || + sp->add_instr(i)) + MYSQL_YYABORT; + sp->restore_lex(YYTHD); + } + sp_proc_stmts1 + { + sp_head *sp= Lex->sphead; + sp_pcontext *ctx= Lex->spcont; + uint ip= sp->instructions(); + sp_instr_jump *i = new sp_instr_jump(ip, ctx); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + sp->backpatch(ctx->pop_label()); + sp->push_backpatch(i, ctx->push_label((char *)"", 0)); + } + sp_elseifs + { + LEX *lex= Lex; + + lex->sphead->backpatch(lex->spcont->pop_label()); + } + ; + +sp_elseifs: + /* Empty */ + | ELSEIF_SYM sp_if + | ELSE sp_proc_stmts1 + ; + +case_stmt_specification: + simple_case_stmt + | searched_case_stmt + ; + +simple_case_stmt: + CASE_SYM + { + LEX *lex= Lex; + case_stmt_action_case(lex); + lex->sphead->reset_lex(YYTHD); /* For expr $3 */ + } + expr + { + LEX *lex= Lex; + if (case_stmt_action_expr(lex, $3)) + MYSQL_YYABORT; + + lex->sphead->restore_lex(YYTHD); /* For expr $3 */ + } + simple_when_clause_list + else_clause_opt + END + CASE_SYM + { + LEX *lex= Lex; + case_stmt_action_end_case(lex, true); + } + ; + +searched_case_stmt: + CASE_SYM + { + LEX *lex= Lex; + case_stmt_action_case(lex); + } + searched_when_clause_list + else_clause_opt + END + CASE_SYM + { + LEX *lex= Lex; + case_stmt_action_end_case(lex, false); + } + ; + +simple_when_clause_list: + simple_when_clause + | simple_when_clause_list simple_when_clause + ; + +searched_when_clause_list: + searched_when_clause + | searched_when_clause_list searched_when_clause + ; + +simple_when_clause: + WHEN_SYM + { + Lex->sphead->reset_lex(YYTHD); /* For expr $3 */ + } + expr + { + /* Simple case: = */ + + LEX *lex= Lex; + if (case_stmt_action_when(lex, $3, true)) + MYSQL_YYABORT; + lex->sphead->restore_lex(YYTHD); /* For expr $3 */ + } + THEN_SYM + sp_proc_stmts1 + { + LEX *lex= Lex; + if (case_stmt_action_then(lex)) + MYSQL_YYABORT; + } + ; + +searched_when_clause: + WHEN_SYM + { + Lex->sphead->reset_lex(YYTHD); /* For expr $3 */ + } + expr + { + LEX *lex= Lex; + if (case_stmt_action_when(lex, $3, false)) + MYSQL_YYABORT; + lex->sphead->restore_lex(YYTHD); /* For expr $3 */ + } + THEN_SYM + sp_proc_stmts1 + { + LEX *lex= Lex; + if (case_stmt_action_then(lex)) + MYSQL_YYABORT; + } + ; + +else_clause_opt: + /* empty */ + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + uint ip= sp->instructions(); + sp_instr_error *i= new sp_instr_error(ip, lex->spcont, + ER_SP_CASE_NOT_FOUND); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + | ELSE sp_proc_stmts1 + ; + +sp_labeled_control: + label_ident ':' + { + LEX *lex= Lex; + sp_pcontext *ctx= lex->spcont; + sp_label_t *lab= ctx->find_label($1.str); + + if (lab) + { + my_error(ER_SP_LABEL_REDEFINE, MYF(0), $1.str); + MYSQL_YYABORT; + } + else + { + lab= lex->spcont->push_label($1.str, + lex->sphead->instructions()); + lab->type= SP_LAB_ITER; + } + } + sp_unlabeled_control sp_opt_label + { + LEX *lex= Lex; + sp_label_t *lab= lex->spcont->pop_label(); + + if ($5.str) + { + if (my_strcasecmp(system_charset_info, $5.str, lab->name) != 0) + { + my_error(ER_SP_LABEL_MISMATCH, MYF(0), $5.str); + MYSQL_YYABORT; + } + } + lex->sphead->backpatch(lab); + } + ; + +sp_opt_label: + /* Empty */ { $$= null_lex_str; } + | label_ident { $$= $1; } + ; + +sp_labeled_block: + label_ident ':' + { + LEX *lex= Lex; + sp_pcontext *ctx= lex->spcont; + sp_label_t *lab= ctx->find_label($1.str); + + if (lab) + { + my_error(ER_SP_LABEL_REDEFINE, MYF(0), $1.str); + MYSQL_YYABORT; + } + + lab= lex->spcont->push_label($1.str, + lex->sphead->instructions()); + lab->type= SP_LAB_BEGIN; + } + sp_block_content sp_opt_label + { + LEX *lex= Lex; + sp_label_t *lab= lex->spcont->pop_label(); + + if ($5.str) + { + if (my_strcasecmp(system_charset_info, $5.str, lab->name) != 0) + { + my_error(ER_SP_LABEL_MISMATCH, MYF(0), $5.str); + MYSQL_YYABORT; + } + } + } + ; + +sp_unlabeled_block: + { /* Unlabeled blocks get a secret label. */ + LEX *lex= Lex; + uint ip= lex->sphead->instructions(); + sp_label_t *lab= lex->spcont->push_label((char *)"", ip); + lab->type= SP_LAB_BEGIN; + } + sp_block_content + { + LEX *lex= Lex; + lex->spcont->pop_label(); + } + ; + +sp_block_content: + BEGIN_SYM + { /* QQ This is just a dummy for grouping declarations and statements + together. No [[NOT] ATOMIC] yet, and we need to figure out how + make it coexist with the existing BEGIN COMMIT/ROLLBACK. */ + LEX *lex= Lex; + lex->spcont= lex->spcont->push_context(LABEL_DEFAULT_SCOPE); + } + sp_decls + sp_proc_stmts + END + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + sp_pcontext *ctx= lex->spcont; + sp_instr *i; + + sp->backpatch(ctx->last_label()); /* We always have a label */ + if ($3.hndlrs) + { + i= new sp_instr_hpop(sp->instructions(), ctx, $3.hndlrs); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + if ($3.curs) + { + i= new sp_instr_cpop(sp->instructions(), ctx, $3.curs); + if (i == NULL || + sp->add_instr(i)) + MYSQL_YYABORT; + } + lex->spcont= ctx->pop_context(); + } + ; + +sp_unlabeled_control: + LOOP_SYM + sp_proc_stmts1 END LOOP_SYM + { + LEX *lex= Lex; + uint ip= lex->sphead->instructions(); + sp_label_t *lab= lex->spcont->last_label(); /* Jumping back */ + sp_instr_jump *i = new sp_instr_jump(ip, lex->spcont, lab->ip); + if (i == NULL || + lex->sphead->add_instr(i)) + MYSQL_YYABORT; + } + | WHILE_SYM + { Lex->sphead->reset_lex(YYTHD); } + expr DO_SYM + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + uint ip= sp->instructions(); + sp_instr_jump_if_not *i = new sp_instr_jump_if_not(ip, lex->spcont, + $3, lex); + if (i == NULL || + /* Jumping forward */ + sp->push_backpatch(i, lex->spcont->last_label()) || + sp->new_cont_backpatch(i) || + sp->add_instr(i)) + MYSQL_YYABORT; + sp->restore_lex(YYTHD); + } + sp_proc_stmts1 END WHILE_SYM + { + LEX *lex= Lex; + uint ip= lex->sphead->instructions(); + sp_label_t *lab= lex->spcont->last_label(); /* Jumping back */ + sp_instr_jump *i = new sp_instr_jump(ip, lex->spcont, lab->ip); + if (i == NULL || + lex->sphead->add_instr(i)) + MYSQL_YYABORT; + lex->sphead->do_cont_backpatch(); + } + | REPEAT_SYM sp_proc_stmts1 UNTIL_SYM + { Lex->sphead->reset_lex(YYTHD); } + expr END REPEAT_SYM + { + LEX *lex= Lex; + uint ip= lex->sphead->instructions(); + sp_label_t *lab= lex->spcont->last_label(); /* Jumping back */ + sp_instr_jump_if_not *i = new sp_instr_jump_if_not(ip, lex->spcont, + $5, lab->ip, + lex); + if (i == NULL || + lex->sphead->add_instr(i)) + MYSQL_YYABORT; + lex->sphead->restore_lex(YYTHD); + /* We can shortcut the cont_backpatch here */ + i->m_cont_dest= ip+1; + } + ; + +trg_action_time: + BEFORE_SYM + { Lex->trg_chistics.action_time= TRG_ACTION_BEFORE; } + | AFTER_SYM + { Lex->trg_chistics.action_time= TRG_ACTION_AFTER; } + ; + +trg_event: + INSERT + { Lex->trg_chistics.event= TRG_EVENT_INSERT; } + | UPDATE_SYM + { Lex->trg_chistics.event= TRG_EVENT_UPDATE; } + | DELETE_SYM + { Lex->trg_chistics.event= TRG_EVENT_DELETE; } + ; +/* + This part of the parser contains common code for all TABLESPACE + commands. + CREATE TABLESPACE name ... + ALTER TABLESPACE name CHANGE DATAFILE ... + ALTER TABLESPACE name ADD DATAFILE ... + ALTER TABLESPACE name access_mode + CREATE LOGFILE GROUP_SYM name ... + ALTER LOGFILE GROUP_SYM name ADD UNDOFILE .. + ALTER LOGFILE GROUP_SYM name ADD REDOFILE .. + DROP TABLESPACE name + DROP LOGFILE GROUP_SYM name +*/ +change_tablespace_access: + tablespace_name + ts_access_mode + ; + +change_tablespace_info: + tablespace_name + CHANGE ts_datafile + change_ts_option_list + ; + +tablespace_info: + tablespace_name + ADD ts_datafile + opt_logfile_group_name + tablespace_option_list + ; + +opt_logfile_group_name: + /* empty */ {} + | USE_SYM LOGFILE_SYM GROUP_SYM ident + { + LEX *lex= Lex; + lex->alter_tablespace_info->logfile_group_name= $4.str; + } + ; + +alter_tablespace_info: + tablespace_name + ADD ts_datafile + alter_tablespace_option_list + { + Lex->alter_tablespace_info->ts_alter_tablespace_type= ALTER_TABLESPACE_ADD_FILE; + } + | tablespace_name + DROP ts_datafile + alter_tablespace_option_list + { + Lex->alter_tablespace_info->ts_alter_tablespace_type= ALTER_TABLESPACE_DROP_FILE; + } + ; + +logfile_group_info: + logfile_group_name + add_log_file + logfile_group_option_list + ; + +alter_logfile_group_info: + logfile_group_name + add_log_file + alter_logfile_group_option_list + ; + +add_log_file: + ADD lg_undofile + | ADD lg_redofile + ; + +change_ts_option_list: + /* empty */ {} + change_ts_options + ; + +change_ts_options: + change_ts_option + | change_ts_options change_ts_option + | change_ts_options ',' change_ts_option + ; + +change_ts_option: + opt_ts_initial_size + | opt_ts_autoextend_size + | opt_ts_max_size + ; + +tablespace_option_list: + tablespace_options + ; + +tablespace_options: + tablespace_option + | tablespace_options tablespace_option + | tablespace_options ',' tablespace_option + ; + +tablespace_option: + opt_ts_initial_size + | opt_ts_autoextend_size + | opt_ts_max_size + | opt_ts_extent_size + | opt_ts_nodegroup + | opt_ts_engine + | ts_wait + | opt_ts_comment + ; + +alter_tablespace_option_list: + alter_tablespace_options + ; + +alter_tablespace_options: + alter_tablespace_option + | alter_tablespace_options alter_tablespace_option + | alter_tablespace_options ',' alter_tablespace_option + ; + +alter_tablespace_option: + opt_ts_initial_size + | opt_ts_autoextend_size + | opt_ts_max_size + | opt_ts_engine + | ts_wait + ; + +logfile_group_option_list: + logfile_group_options + ; + +logfile_group_options: + logfile_group_option + | logfile_group_options logfile_group_option + | logfile_group_options ',' logfile_group_option + ; + +logfile_group_option: + opt_ts_initial_size + | opt_ts_undo_buffer_size + | opt_ts_redo_buffer_size + | opt_ts_nodegroup + | opt_ts_engine + | ts_wait + | opt_ts_comment + ; + +alter_logfile_group_option_list: + alter_logfile_group_options + ; + +alter_logfile_group_options: + alter_logfile_group_option + | alter_logfile_group_options alter_logfile_group_option + | alter_logfile_group_options ',' alter_logfile_group_option + ; + +alter_logfile_group_option: + opt_ts_initial_size + | opt_ts_engine + | ts_wait + ; + + +ts_datafile: + DATAFILE_SYM TEXT_STRING_sys + { + LEX *lex= Lex; + lex->alter_tablespace_info->data_file_name= $2.str; + } + ; + +lg_undofile: + UNDOFILE_SYM TEXT_STRING_sys + { + LEX *lex= Lex; + lex->alter_tablespace_info->undo_file_name= $2.str; + } + ; + +lg_redofile: + REDOFILE_SYM TEXT_STRING_sys + { + LEX *lex= Lex; + lex->alter_tablespace_info->redo_file_name= $2.str; + } + ; + +tablespace_name: + ident + { + LEX *lex= Lex; + lex->alter_tablespace_info= new st_alter_tablespace(); + if (lex->alter_tablespace_info == NULL) + MYSQL_YYABORT; + lex->alter_tablespace_info->tablespace_name= $1.str; + lex->sql_command= SQLCOM_ALTER_TABLESPACE; + } + ; + +logfile_group_name: + ident + { + LEX *lex= Lex; + lex->alter_tablespace_info= new st_alter_tablespace(); + if (lex->alter_tablespace_info == NULL) + MYSQL_YYABORT; + lex->alter_tablespace_info->logfile_group_name= $1.str; + lex->sql_command= SQLCOM_ALTER_TABLESPACE; + } + ; + +ts_access_mode: + READ_ONLY_SYM + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_access_mode= TS_READ_ONLY; + } + | READ_WRITE_SYM + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_access_mode= TS_READ_WRITE; + } + | NOT_SYM ACCESSIBLE_SYM + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_access_mode= TS_NOT_ACCESSIBLE; + } + ; + +opt_ts_initial_size: + INITIAL_SIZE_SYM opt_equal size_number + { + LEX *lex= Lex; + lex->alter_tablespace_info->initial_size= $3; + } + ; + +opt_ts_autoextend_size: + AUTOEXTEND_SIZE_SYM opt_equal size_number + { + LEX *lex= Lex; + lex->alter_tablespace_info->autoextend_size= $3; + } + ; + +opt_ts_max_size: + MAX_SIZE_SYM opt_equal size_number + { + LEX *lex= Lex; + lex->alter_tablespace_info->max_size= $3; + } + ; + +opt_ts_extent_size: + EXTENT_SIZE_SYM opt_equal size_number + { + LEX *lex= Lex; + lex->alter_tablespace_info->extent_size= $3; + } + ; + +opt_ts_undo_buffer_size: + UNDO_BUFFER_SIZE_SYM opt_equal size_number + { + LEX *lex= Lex; + lex->alter_tablespace_info->undo_buffer_size= $3; + } + ; + +opt_ts_redo_buffer_size: + REDO_BUFFER_SIZE_SYM opt_equal size_number + { + LEX *lex= Lex; + lex->alter_tablespace_info->redo_buffer_size= $3; + } + ; + +opt_ts_nodegroup: + NODEGROUP_SYM opt_equal real_ulong_num + { + LEX *lex= Lex; + if (lex->alter_tablespace_info->nodegroup_id != UNDEF_NODEGROUP) + { + my_error(ER_FILEGROUP_OPTION_ONLY_ONCE,MYF(0),"NODEGROUP"); + MYSQL_YYABORT; + } + lex->alter_tablespace_info->nodegroup_id= $3; + } + ; + +opt_ts_comment: + COMMENT_SYM opt_equal TEXT_STRING_sys + { + LEX *lex= Lex; + if (lex->alter_tablespace_info->ts_comment != NULL) + { + my_error(ER_FILEGROUP_OPTION_ONLY_ONCE,MYF(0),"COMMENT"); + MYSQL_YYABORT; + } + lex->alter_tablespace_info->ts_comment= $3.str; + } + ; + +opt_ts_engine: + opt_storage ENGINE_SYM opt_equal storage_engines + { + LEX *lex= Lex; + if (lex->alter_tablespace_info->storage_engine != NULL) + { + my_error(ER_FILEGROUP_OPTION_ONLY_ONCE,MYF(0), + "STORAGE ENGINE"); + MYSQL_YYABORT; + } + lex->alter_tablespace_info->storage_engine= $4; + } + ; + +opt_ts_wait: + /* empty */ + | ts_wait + ; + +ts_wait: + WAIT_SYM + { + LEX *lex= Lex; + lex->alter_tablespace_info->wait_until_completed= TRUE; + } + | NO_WAIT_SYM + { + LEX *lex= Lex; + if (!(lex->alter_tablespace_info->wait_until_completed)) + { + my_error(ER_FILEGROUP_OPTION_ONLY_ONCE,MYF(0),"NO_WAIT"); + MYSQL_YYABORT; + } + lex->alter_tablespace_info->wait_until_completed= FALSE; + } + ; + +size_number: + real_ulong_num { $$= $1;} + | IDENT + { + ulonglong number; + uint text_shift_number= 0; + longlong prefix_number; + char *start_ptr= $1.str; + uint str_len= $1.length; + char *end_ptr= start_ptr + str_len; + int error; + prefix_number= my_strtoll10(start_ptr, &end_ptr, &error); + if ((start_ptr + str_len - 1) == end_ptr) + { + switch (end_ptr[0]) + { + case 'g': + case 'G': + text_shift_number+=10; + case 'm': + case 'M': + text_shift_number+=10; + case 'k': + case 'K': + text_shift_number+=10; + break; + default: + { + my_error(ER_WRONG_SIZE_NUMBER, MYF(0)); + MYSQL_YYABORT; + } + } + if (prefix_number >> 31) + { + my_error(ER_SIZE_OVERFLOW_ERROR, MYF(0)); + MYSQL_YYABORT; + } + number= prefix_number << text_shift_number; + } + else + { + my_error(ER_WRONG_SIZE_NUMBER, MYF(0)); + MYSQL_YYABORT; + } + $$= number; + } + ; + +/* + End tablespace part +*/ + +create2: + '(' create2a {} + | opt_create_table_options + opt_partitioning + create3 {} + | LIKE table_ident + { + THD *thd= YYTHD; + TABLE_LIST *src_table; + LEX *lex= thd->lex; + + lex->create_info.options|= HA_LEX_CREATE_TABLE_LIKE; + src_table= lex->select_lex.add_table_to_list(thd, $2, NULL, 0, + TL_READ); + if (! src_table) + MYSQL_YYABORT; + /* CREATE TABLE ... LIKE is not allowed for views. */ + src_table->required_type= FRMTYPE_TABLE; + } + | '(' LIKE table_ident ')' + { + THD *thd= YYTHD; + TABLE_LIST *src_table; + LEX *lex= thd->lex; + + lex->create_info.options|= HA_LEX_CREATE_TABLE_LIKE; + src_table= lex->select_lex.add_table_to_list(thd, $3, NULL, 0, + TL_READ); + if (! src_table) + MYSQL_YYABORT; + /* CREATE TABLE ... LIKE is not allowed for views. */ + src_table->required_type= FRMTYPE_TABLE; + } + ; + +create2a: + field_list ')' opt_create_table_options + opt_partitioning + create3 {} + | opt_partitioning + create_select ')' + { Select->set_braces(1);} + union_opt {} + ; + +create3: + /* empty */ {} + | opt_duplicate opt_as create_select + { Select->set_braces(0);} + union_clause {} + | opt_duplicate opt_as '(' create_select ')' + { Select->set_braces(1);} + union_opt {} + ; + +/* + This part of the parser is about handling of the partition information. + + It's first version was written by Mikael Ronström with lots of answers to + questions provided by Antony Curtis. + + The partition grammar can be called from three places. + 1) CREATE TABLE ... PARTITION .. + 2) ALTER TABLE table_name PARTITION ... + 3) PARTITION ... + + The first place is called when a new table is created from a MySQL client. + The second place is called when a table is altered with the ALTER TABLE + command from a MySQL client. + The third place is called when opening an frm file and finding partition + info in the .frm file. It is necessary to avoid allowing PARTITION to be + an allowed entry point for SQL client queries. This is arranged by setting + some state variables before arriving here. + + To be able to handle errors we will only set error code in this code + and handle the error condition in the function calling the parser. This + is necessary to ensure we can also handle errors when calling the parser + from the openfrm function. +*/ +opt_partitioning: + /* empty */ {} + | partitioning + ; + +partitioning: + PARTITION_SYM + { +#ifdef WITH_PARTITION_STORAGE_ENGINE + LEX *lex= Lex; + LEX_STRING partition_name={C_STRING_WITH_LEN("partition")}; + if (!plugin_is_ready(&partition_name, MYSQL_STORAGE_ENGINE_PLUGIN)) + { + my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), + "--skip-partition"); + MYSQL_YYABORT; + } + lex->part_info= new partition_info(); + if (!lex->part_info) + { + mem_alloc_error(sizeof(partition_info)); + MYSQL_YYABORT; + } + if (lex->sql_command == SQLCOM_ALTER_TABLE) + { + lex->alter_info.flags|= ALTER_PARTITION; + } +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + "partitioning", "--with-partition"); + MYSQL_YYABORT; +#endif + + } + partition + ; + +partition_entry: + PARTITION_SYM + { + LEX *lex= Lex; + if (!lex->part_info) + { + my_parse_error(ER(ER_PARTITION_ENTRY_ERROR)); + MYSQL_YYABORT; + } + /* + We enter here when opening the frm file to translate + partition info string into part_info data structure. + */ + } + partition {} + ; + +partition: + BY part_type_def opt_no_parts opt_sub_part part_defs + ; + +part_type_def: + opt_linear KEY_SYM '(' part_field_list ')' + { + LEX *lex= Lex; + lex->part_info->list_of_part_fields= TRUE; + lex->part_info->part_type= HASH_PARTITION; + } + | opt_linear HASH_SYM + { Lex->part_info->part_type= HASH_PARTITION; } + part_func {} + | RANGE_SYM + { Lex->part_info->part_type= RANGE_PARTITION; } + part_func {} + | LIST_SYM + { Lex->part_info->part_type= LIST_PARTITION; } + part_func {} + ; + +opt_linear: + /* empty */ {} + | LINEAR_SYM + { Lex->part_info->linear_hash_ind= TRUE;} + ; + +part_field_list: + /* empty */ {} + | part_field_item_list {} + ; + +part_field_item_list: + part_field_item {} + | part_field_item_list ',' part_field_item {} + ; + +part_field_item: + ident + { + if (Lex->part_info->part_field_list.push_back($1.str)) + { + mem_alloc_error(1); + MYSQL_YYABORT; + } + } + ; + +part_func: + '(' remember_name part_func_expr remember_end ')' + { + LEX *lex= Lex; + uint expr_len= (uint)($4 - $2) - 1; + lex->part_info->list_of_part_fields= FALSE; + lex->part_info->part_expr= $3; + char *func_string= (char*) sql_memdup($2+1, expr_len); + if (func_string == NULL) + MYSQL_YYABORT; + lex->part_info->part_func_string= func_string; + lex->part_info->part_func_len= expr_len; + } + ; + +sub_part_func: + '(' remember_name part_func_expr remember_end ')' + { + LEX *lex= Lex; + uint expr_len= (uint)($4 - $2) - 1; + lex->part_info->list_of_subpart_fields= FALSE; + lex->part_info->subpart_expr= $3; + char *func_string= (char*) sql_memdup($2+1, expr_len); + if (func_string == NULL) + MYSQL_YYABORT; + lex->part_info->subpart_func_string= func_string; + lex->part_info->subpart_func_len= expr_len; + } + ; + + +opt_no_parts: + /* empty */ {} + | PARTITIONS_SYM real_ulong_num + { + uint no_parts= $2; + LEX *lex= Lex; + if (no_parts == 0) + { + my_error(ER_NO_PARTS_ERROR, MYF(0), "partitions"); + MYSQL_YYABORT; + } + + lex->part_info->no_parts= no_parts; + lex->part_info->use_default_no_partitions= FALSE; + } + ; + +opt_sub_part: + /* empty */ {} + | SUBPARTITION_SYM BY opt_linear HASH_SYM sub_part_func + { Lex->part_info->subpart_type= HASH_PARTITION; } + opt_no_subparts {} + | SUBPARTITION_SYM BY opt_linear KEY_SYM + '(' sub_part_field_list ')' + { + LEX *lex= Lex; + lex->part_info->subpart_type= HASH_PARTITION; + lex->part_info->list_of_subpart_fields= TRUE; + } + opt_no_subparts {} + ; + +sub_part_field_list: + sub_part_field_item {} + | sub_part_field_list ',' sub_part_field_item {} + ; + +sub_part_field_item: + ident + { + if (Lex->part_info->subpart_field_list.push_back($1.str)) + { + mem_alloc_error(1); + MYSQL_YYABORT; + } + } + ; + +part_func_expr: + bit_expr + { + LEX *lex= Lex; + bool not_corr_func; + not_corr_func= !lex->safe_to_cache_query; + lex->safe_to_cache_query= 1; + if (not_corr_func) + { + my_parse_error(ER(ER_CONST_EXPR_IN_PARTITION_FUNC_ERROR)); + MYSQL_YYABORT; + } + $$=$1; + } + ; + +opt_no_subparts: + /* empty */ {} + | SUBPARTITIONS_SYM real_ulong_num + { + uint no_parts= $2; + LEX *lex= Lex; + if (no_parts == 0) + { + my_error(ER_NO_PARTS_ERROR, MYF(0), "subpartitions"); + MYSQL_YYABORT; + } + lex->part_info->no_subparts= no_parts; + lex->part_info->use_default_no_subpartitions= FALSE; + } + ; + +part_defs: + /* empty */ + {} + | '(' part_def_list ')' + { + LEX *lex= Lex; + partition_info *part_info= lex->part_info; + uint count_curr_parts= part_info->partitions.elements; + if (part_info->no_parts != 0) + { + if (part_info->no_parts != + count_curr_parts) + { + my_parse_error(ER(ER_PARTITION_WRONG_NO_PART_ERROR)); + MYSQL_YYABORT; + } + } + else if (count_curr_parts > 0) + { + part_info->no_parts= count_curr_parts; + } + part_info->count_curr_subparts= 0; + } + ; + +part_def_list: + part_definition {} + | part_def_list ',' part_definition {} + ; + +part_definition: + PARTITION_SYM + { + LEX *lex= Lex; + partition_info *part_info= lex->part_info; + partition_element *p_elem= new partition_element(); + + if (!p_elem || part_info->partitions.push_back(p_elem)) + { + mem_alloc_error(sizeof(partition_element)); + MYSQL_YYABORT; + } + p_elem->part_state= PART_NORMAL; + part_info->curr_part_elem= p_elem; + part_info->current_partition= p_elem; + part_info->use_default_partitions= FALSE; + part_info->use_default_no_partitions= FALSE; + } + part_name + opt_part_values + opt_part_options + opt_sub_partition + {} + ; + +part_name: + ident + { + LEX *lex= Lex; + partition_info *part_info= lex->part_info; + partition_element *p_elem= part_info->curr_part_elem; + p_elem->partition_name= $1.str; + } + ; + +opt_part_values: + /* empty */ + { + LEX *lex= Lex; + if (! lex->is_partition_management()) + { + if (lex->part_info->part_type == RANGE_PARTITION) + { + my_error(ER_PARTITION_REQUIRES_VALUES_ERROR, MYF(0), + "RANGE", "LESS THAN"); + MYSQL_YYABORT; + } + if (lex->part_info->part_type == LIST_PARTITION) + { + my_error(ER_PARTITION_REQUIRES_VALUES_ERROR, MYF(0), + "LIST", "IN"); + MYSQL_YYABORT; + } + } + else + lex->part_info->part_type= HASH_PARTITION; + } + | VALUES LESS_SYM THAN_SYM part_func_max + { + LEX *lex= Lex; + if (! lex->is_partition_management()) + { + if (Lex->part_info->part_type != RANGE_PARTITION) + { + my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0), + "RANGE", "LESS THAN"); + MYSQL_YYABORT; + } + } + else + lex->part_info->part_type= RANGE_PARTITION; + } + | VALUES IN_SYM '(' part_list_func ')' + { + LEX *lex= Lex; + if (! lex->is_partition_management()) + { + if (Lex->part_info->part_type != LIST_PARTITION) + { + my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0), + "LIST", "IN"); + MYSQL_YYABORT; + } + } + else + lex->part_info->part_type= LIST_PARTITION; + } + ; + +part_func_max: + max_value_sym + { + LEX *lex= Lex; + if (lex->part_info->defined_max_value) + { + my_parse_error(ER(ER_PARTITION_MAXVALUE_ERROR)); + MYSQL_YYABORT; + } + lex->part_info->defined_max_value= TRUE; + lex->part_info->curr_part_elem->max_value= TRUE; + lex->part_info->curr_part_elem->range_value= LONGLONG_MAX; + } + | part_range_func + { + if (Lex->part_info->defined_max_value) + { + my_parse_error(ER(ER_PARTITION_MAXVALUE_ERROR)); + MYSQL_YYABORT; + } + if (Lex->part_info->curr_part_elem->has_null_value) + { + my_parse_error(ER(ER_NULL_IN_VALUES_LESS_THAN)); + MYSQL_YYABORT; + } + } + ; + +max_value_sym: + MAX_VALUE_SYM + | '(' MAX_VALUE_SYM ')' + ; + +part_range_func: + '(' part_bit_expr ')' + { + partition_info *part_info= Lex->part_info; + if (!($2->unsigned_flag)) + part_info->curr_part_elem->signed_flag= TRUE; + part_info->curr_part_elem->range_value= $2->value; + } + ; + +part_list_func: + part_list_item {} + | part_list_func ',' part_list_item {} + ; + +part_list_item: + part_bit_expr + { + part_elem_value *value_ptr= $1; + partition_info *part_info= Lex->part_info; + if (!value_ptr->unsigned_flag) + part_info->curr_part_elem->signed_flag= TRUE; + if (!value_ptr->null_value && + part_info->curr_part_elem-> + list_val_list.push_back(value_ptr)) + { + mem_alloc_error(sizeof(part_elem_value)); + MYSQL_YYABORT; + } + } + ; + +part_bit_expr: + bit_expr + { + Item *part_expr= $1; + THD *thd= YYTHD; + LEX *lex= thd->lex; + Name_resolution_context *context= &lex->current_select->context; + TABLE_LIST *save_list= context->table_list; + const char *save_where= thd->where; + + context->table_list= 0; + thd->where= "partition function"; + + part_elem_value *value_ptr= + (part_elem_value*)sql_alloc(sizeof(part_elem_value)); + if (!value_ptr) + { + mem_alloc_error(sizeof(part_elem_value)); + MYSQL_YYABORT; + } + if (part_expr->walk(&Item::check_partition_func_processor, 0, + NULL)) + { + my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0)); + MYSQL_YYABORT; + } + if (part_expr->fix_fields(YYTHD, (Item**)0) || + ((context->table_list= save_list), FALSE) || + (!part_expr->const_item()) || + (!lex->safe_to_cache_query)) + { + my_error(ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR, MYF(0)); + MYSQL_YYABORT; + } + thd->where= save_where; + value_ptr->value= part_expr->val_int(); + value_ptr->unsigned_flag= TRUE; + if (!part_expr->unsigned_flag && + value_ptr->value < 0) + value_ptr->unsigned_flag= FALSE; + if ((value_ptr->null_value= part_expr->null_value)) + { + if (Lex->part_info->curr_part_elem->has_null_value) + { + my_error(ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR, MYF(0)); + MYSQL_YYABORT; + } + Lex->part_info->curr_part_elem->has_null_value= TRUE; + } + else if (part_expr->result_type() != INT_RESULT) + { + my_parse_error(ER(ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR)); + MYSQL_YYABORT; + } + $$= value_ptr; + } + ; + +opt_sub_partition: + /* empty */ + { + if (Lex->part_info->no_subparts != 0 && + !Lex->part_info->use_default_subpartitions) + { + /* + We come here when we have defined subpartitions on the first + partition but not on all the subsequent partitions. + */ + my_parse_error(ER(ER_PARTITION_WRONG_NO_SUBPART_ERROR)); + MYSQL_YYABORT; + } + } + | '(' sub_part_list ')' + { + LEX *lex= Lex; + partition_info *part_info= lex->part_info; + if (part_info->no_subparts != 0) + { + if (part_info->no_subparts != + part_info->count_curr_subparts) + { + my_parse_error(ER(ER_PARTITION_WRONG_NO_SUBPART_ERROR)); + MYSQL_YYABORT; + } + } + else if (part_info->count_curr_subparts > 0) + { + if (part_info->partitions.elements > 1) + { + my_parse_error(ER(ER_PARTITION_WRONG_NO_SUBPART_ERROR)); + MYSQL_YYABORT; + } + part_info->no_subparts= part_info->count_curr_subparts; + } + part_info->count_curr_subparts= 0; + } + ; + +sub_part_list: + sub_part_definition {} + | sub_part_list ',' sub_part_definition {} + ; + +sub_part_definition: + SUBPARTITION_SYM + { + LEX *lex= Lex; + partition_info *part_info= lex->part_info; + partition_element *curr_part= part_info->current_partition; + partition_element *sub_p_elem= new partition_element(curr_part); + if (part_info->use_default_subpartitions && + part_info->partitions.elements >= 2) + { + /* + create table t1 (a int) + partition by list (a) subpartition by hash (a) + (partition p0 values in (1), + partition p1 values in (2) subpartition sp11); + causes use to arrive since we are on the second + partition, but still use_default_subpartitions + is set. When we come here we're processing at least + the second partition (the current partition processed + have already been put into the partitions list. + */ + my_parse_error(ER(ER_PARTITION_WRONG_NO_SUBPART_ERROR)); + MYSQL_YYABORT; + } + if (!sub_p_elem || + curr_part->subpartitions.push_back(sub_p_elem)) + { + mem_alloc_error(sizeof(partition_element)); + MYSQL_YYABORT; + } + part_info->curr_part_elem= sub_p_elem; + part_info->use_default_subpartitions= FALSE; + part_info->use_default_no_subpartitions= FALSE; + part_info->count_curr_subparts++; + } + sub_name opt_part_options {} + ; + +sub_name: + ident_or_text + { Lex->part_info->curr_part_elem->partition_name= $1.str; } + ; + +opt_part_options: + /* empty */ {} + | opt_part_option_list {} + ; + +opt_part_option_list: + opt_part_option_list opt_part_option {} + | opt_part_option {} + ; + +opt_part_option: + TABLESPACE opt_equal ident_or_text + { Lex->part_info->curr_part_elem->tablespace_name= $3.str; } + | opt_storage ENGINE_SYM opt_equal storage_engines + { + LEX *lex= Lex; + lex->part_info->curr_part_elem->engine_type= $4; + lex->part_info->default_engine_type= $4; + } + | NODEGROUP_SYM opt_equal real_ulong_num + { Lex->part_info->curr_part_elem->nodegroup_id= (uint16) $3; } + | MAX_ROWS opt_equal real_ulonglong_num + { Lex->part_info->curr_part_elem->part_max_rows= (ha_rows) $3; } + | MIN_ROWS opt_equal real_ulonglong_num + { Lex->part_info->curr_part_elem->part_min_rows= (ha_rows) $3; } + | DATA_SYM DIRECTORY_SYM opt_equal TEXT_STRING_sys + { Lex->part_info->curr_part_elem->data_file_name= $4.str; } + | INDEX_SYM DIRECTORY_SYM opt_equal TEXT_STRING_sys + { Lex->part_info->curr_part_elem->index_file_name= $4.str; } + | COMMENT_SYM opt_equal TEXT_STRING_sys + { Lex->part_info->curr_part_elem->part_comment= $3.str; } + ; + +/* + End of partition parser part +*/ + +create_select: + SELECT_SYM + { + LEX *lex=Lex; + lex->lock_option= TL_READ_DEFAULT; + if (lex->sql_command == SQLCOM_INSERT) + lex->sql_command= SQLCOM_INSERT_SELECT; + else if (lex->sql_command == SQLCOM_REPLACE) + lex->sql_command= SQLCOM_REPLACE_SELECT; + /* + The following work only with the local list, the global list + is created correctly in this case + */ + lex->current_select->table_list.save_and_clear(&lex->save_list); + mysql_init_select(lex); + lex->current_select->parsing_place= SELECT_LIST; + } + select_options select_item_list + { + Select->parsing_place= NO_MATTER; + } + opt_select_from + { + /* + The following work only with the local list, the global list + is created correctly in this case + */ + Lex->current_select->table_list.push_front(&Lex->save_list); + } + ; + +opt_as: + /* empty */ {} + | AS {} + ; + +opt_create_database_options: + /* empty */ {} + | create_database_options {} + ; + +create_database_options: + create_database_option {} + | create_database_options create_database_option {} + ; + +create_database_option: + default_collation {} + | default_charset {} + ; + +opt_table_options: + /* empty */ { $$= 0; } + | table_options { $$= $1;} + ; + +table_options: + table_option { $$=$1; } + | table_option table_options { $$= $1 | $2; } + ; + +table_option: + TEMPORARY { $$=HA_LEX_CREATE_TMP_TABLE; } + ; + +opt_if_not_exists: + /* empty */ { $$= 0; } + | IF not EXISTS { $$=HA_LEX_CREATE_IF_NOT_EXISTS; } + ; + +opt_create_table_options: + /* empty */ + | create_table_options + ; + +create_table_options_space_separated: + create_table_option + | create_table_option create_table_options_space_separated + ; + +create_table_options: + create_table_option + | create_table_option create_table_options + | create_table_option ',' create_table_options + ; + +create_table_option: + ENGINE_SYM opt_equal storage_engines + { + Lex->create_info.db_type= $3; + Lex->create_info.used_fields|= HA_CREATE_USED_ENGINE; + } + | TYPE_SYM opt_equal storage_engines + { + Lex->create_info.db_type= $3; + WARN_DEPRECATED(yythd, "6.0", "TYPE=storage_engine", + "'ENGINE=storage_engine'"); + Lex->create_info.used_fields|= HA_CREATE_USED_ENGINE; + } + | MAX_ROWS opt_equal ulonglong_num + { + Lex->create_info.max_rows= $3; + Lex->create_info.used_fields|= HA_CREATE_USED_MAX_ROWS; + } + | MIN_ROWS opt_equal ulonglong_num + { + Lex->create_info.min_rows= $3; + Lex->create_info.used_fields|= HA_CREATE_USED_MIN_ROWS; + } + | AVG_ROW_LENGTH opt_equal ulong_num + { + Lex->create_info.avg_row_length=$3; + Lex->create_info.used_fields|= HA_CREATE_USED_AVG_ROW_LENGTH; + } + | PASSWORD opt_equal TEXT_STRING_sys + { + Lex->create_info.password=$3.str; + Lex->create_info.used_fields|= HA_CREATE_USED_PASSWORD; + } + | COMMENT_SYM opt_equal TEXT_STRING_sys + { + Lex->create_info.comment=$3; + Lex->create_info.used_fields|= HA_CREATE_USED_COMMENT; + } + | AUTO_INC opt_equal ulonglong_num + { + Lex->create_info.auto_increment_value=$3; + Lex->create_info.used_fields|= HA_CREATE_USED_AUTO; + } + | PACK_KEYS_SYM opt_equal ulong_num + { + switch($3) { + case 0: + Lex->create_info.table_options|= HA_OPTION_NO_PACK_KEYS; + break; + case 1: + Lex->create_info.table_options|= HA_OPTION_PACK_KEYS; + break; + default: + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + Lex->create_info.used_fields|= HA_CREATE_USED_PACK_KEYS; + } + | PACK_KEYS_SYM opt_equal DEFAULT + { + Lex->create_info.table_options&= + ~(HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS); + Lex->create_info.used_fields|= HA_CREATE_USED_PACK_KEYS; + } + | CHECKSUM_SYM opt_equal ulong_num + { + Lex->create_info.table_options|= $3 ? HA_OPTION_CHECKSUM : HA_OPTION_NO_CHECKSUM; + Lex->create_info.used_fields|= HA_CREATE_USED_CHECKSUM; + } + | TABLE_CHECKSUM_SYM opt_equal ulong_num + { + Lex->create_info.table_options|= $3 ? HA_OPTION_CHECKSUM : HA_OPTION_NO_CHECKSUM; + Lex->create_info.used_fields|= HA_CREATE_USED_CHECKSUM; + } + | DELAY_KEY_WRITE_SYM opt_equal ulong_num + { + Lex->create_info.table_options|= $3 ? HA_OPTION_DELAY_KEY_WRITE : HA_OPTION_NO_DELAY_KEY_WRITE; + Lex->create_info.used_fields|= HA_CREATE_USED_DELAY_KEY_WRITE; + } + | ROW_FORMAT_SYM opt_equal row_types + { + Lex->create_info.row_type= $3; + Lex->create_info.used_fields|= HA_CREATE_USED_ROW_FORMAT; + } + | UNION_SYM opt_equal '(' opt_table_list ')' + { + /* Move the union list to the merge_list */ + LEX *lex=Lex; + TABLE_LIST *table_list= lex->select_lex.get_table_list(); + lex->create_info.merge_list= lex->select_lex.table_list; + lex->create_info.merge_list.elements--; + lex->create_info.merge_list.first= + (uchar*) (table_list->next_local); + lex->select_lex.table_list.elements=1; + lex->select_lex.table_list.next= + (uchar**) &(table_list->next_local); + table_list->next_local= 0; + lex->create_info.used_fields|= HA_CREATE_USED_UNION; + } + | default_charset + | default_collation + | INSERT_METHOD opt_equal merge_insert_types + { + Lex->create_info.merge_insert_method= $3; + Lex->create_info.used_fields|= HA_CREATE_USED_INSERT_METHOD; + } + | DATA_SYM DIRECTORY_SYM opt_equal TEXT_STRING_sys + { + Lex->create_info.data_file_name= $4.str; + Lex->create_info.used_fields|= HA_CREATE_USED_DATADIR; + } + | INDEX_SYM DIRECTORY_SYM opt_equal TEXT_STRING_sys + { + Lex->create_info.index_file_name= $4.str; + Lex->create_info.used_fields|= HA_CREATE_USED_INDEXDIR; + } + | TABLESPACE ident + {Lex->create_info.tablespace= $2.str;} + | STORAGE_SYM DISK_SYM + {Lex->create_info.storage_media= HA_SM_DISK;} + | STORAGE_SYM MEMORY_SYM + {Lex->create_info.storage_media= HA_SM_MEMORY;} + | CONNECTION_SYM opt_equal TEXT_STRING_sys + { + Lex->create_info.connect_string.str= $3.str; + Lex->create_info.connect_string.length= $3.length; + Lex->create_info.used_fields|= HA_CREATE_USED_CONNECTION; + } + | KEY_BLOCK_SIZE opt_equal ulong_num + { + Lex->create_info.used_fields|= HA_CREATE_USED_KEY_BLOCK_SIZE; + Lex->create_info.key_block_size= $3; + } + ; + +default_charset: + opt_default charset opt_equal charset_name_or_default + { + HA_CREATE_INFO *cinfo= &Lex->create_info; + if ((cinfo->used_fields & HA_CREATE_USED_DEFAULT_CHARSET) && + cinfo->default_table_charset && $4 && + !my_charset_same(cinfo->default_table_charset,$4)) + { + my_error(ER_CONFLICTING_DECLARATIONS, MYF(0), + "CHARACTER SET ", cinfo->default_table_charset->csname, + "CHARACTER SET ", $4->csname); + MYSQL_YYABORT; + } + Lex->create_info.default_table_charset= $4; + Lex->create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET; + } + ; + +default_collation: + opt_default COLLATE_SYM opt_equal collation_name_or_default + { + HA_CREATE_INFO *cinfo= &Lex->create_info; + if ((cinfo->used_fields & HA_CREATE_USED_DEFAULT_CHARSET) && + cinfo->default_table_charset && $4 && + !my_charset_same(cinfo->default_table_charset,$4)) + { + my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), + $4->name, cinfo->default_table_charset->csname); + MYSQL_YYABORT; + } + Lex->create_info.default_table_charset= $4; + Lex->create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET; + } + ; + +storage_engines: + ident_or_text + { + plugin_ref plugin= ha_resolve_by_name(YYTHD, &$1); + + if (plugin) + $$= plugin_data(plugin, handlerton*); + else + { + if (YYTHD->variables.sql_mode & MODE_NO_ENGINE_SUBSTITUTION) + { + my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), $1.str); + MYSQL_YYABORT; + } + $$= 0; + push_warning_printf(YYTHD, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_UNKNOWN_STORAGE_ENGINE, + ER(ER_UNKNOWN_STORAGE_ENGINE), + $1.str); + } + } + ; + +known_storage_engines: + ident_or_text + { + plugin_ref plugin; + if ((plugin= ha_resolve_by_name(YYTHD, &$1))) + $$= plugin_data(plugin, handlerton*); + else + { + my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), $1.str); + MYSQL_YYABORT; + } + } + ; + +row_types: + DEFAULT { $$= ROW_TYPE_DEFAULT; } + | FIXED_SYM { $$= ROW_TYPE_FIXED; } + | DYNAMIC_SYM { $$= ROW_TYPE_DYNAMIC; } + | COMPRESSED_SYM { $$= ROW_TYPE_COMPRESSED; } + | REDUNDANT_SYM { $$= ROW_TYPE_REDUNDANT; } + | COMPACT_SYM { $$= ROW_TYPE_COMPACT; } + ; + +merge_insert_types: + NO_SYM { $$= MERGE_INSERT_DISABLED; } + | FIRST_SYM { $$= MERGE_INSERT_TO_FIRST; } + | LAST_SYM { $$= MERGE_INSERT_TO_LAST; } + ; + +opt_select_from: + opt_limit_clause {} + | select_from select_lock_type + ; + +udf_type: + STRING_SYM {$$ = (int) STRING_RESULT; } + | REAL {$$ = (int) REAL_RESULT; } + | DECIMAL_SYM {$$ = (int) DECIMAL_RESULT; } + | INT_SYM {$$ = (int) INT_RESULT; } + ; + +field_list: + field_list_item + | field_list ',' field_list_item + ; + +field_list_item: + column_def + | key_def + ; + +column_def: + field_spec opt_check_constraint + | field_spec references + { + Lex->col_list.empty(); /* Alloced by sql_alloc */ + } + ; + +key_def: + key_type opt_ident key_alg '(' key_list ')' key_options + { + LEX *lex=Lex; + if ($1 != Key::FULLTEXT && lex->key_create_info.parser_name.str) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + Key *key= new Key($1, $2, &lex->key_create_info, 0, + lex->col_list); + if (key == NULL) + MYSQL_YYABORT; + lex->alter_info.key_list.push_back(key); + lex->col_list.empty(); /* Alloced by sql_alloc */ + } + | opt_constraint constraint_key_type opt_ident key_alg + '(' key_list ')' key_options + { + LEX *lex=Lex; + const char *key_name= $3 ? $3 : $1; + Key *key= new Key($2, key_name, &lex->key_create_info, 0, + lex->col_list); + if (key == NULL) + MYSQL_YYABORT; + lex->alter_info.key_list.push_back(key); + lex->col_list.empty(); /* Alloced by sql_alloc */ + } + | opt_constraint FOREIGN KEY_SYM opt_ident '(' key_list ')' references + { + LEX *lex=Lex; + const char *key_name= $1 ? $1 : $4; + const char *fkey_name = $4 ? $4 : key_name; + Key *key= new Foreign_key(fkey_name, lex->col_list, + $8, + lex->ref_list, + lex->fk_delete_opt, + lex->fk_update_opt, + lex->fk_match_option); + if (key == NULL) + MYSQL_YYABORT; + lex->alter_info.key_list.push_back(key); + key= new Key(Key::MULTIPLE, key_name, + &default_key_create_info, 1, + lex->col_list); + if (key == NULL) + MYSQL_YYABORT; + lex->alter_info.key_list.push_back(key); + lex->col_list.empty(); /* Alloced by sql_alloc */ + /* Only used for ALTER TABLE. Ignored otherwise. */ + lex->alter_info.flags|= ALTER_FOREIGN_KEY; + } + | constraint opt_check_constraint + { + Lex->col_list.empty(); /* Alloced by sql_alloc */ + } + | opt_constraint check_constraint + { + Lex->col_list.empty(); /* Alloced by sql_alloc */ + } + ; + +opt_check_constraint: + /* empty */ + | check_constraint + ; + +check_constraint: + CHECK_SYM expr + ; + +opt_constraint: + /* empty */ { $$=(char*) 0; } + | constraint { $$= $1; } + ; + +constraint: + CONSTRAINT opt_ident { $$=$2; } + ; + +field_spec: + field_ident + { + LEX *lex=Lex; + lex->length=lex->dec=0; + lex->type=0; + lex->default_value= lex->on_update_value= 0; + lex->comment=null_lex_str; + lex->charset=NULL; + } + type opt_attribute + { + LEX *lex=Lex; + if (add_field_to_list(lex->thd, &$1, (enum enum_field_types) $3, + lex->length,lex->dec,lex->type, + lex->default_value, lex->on_update_value, + &lex->comment, + lex->change,&lex->interval_list,lex->charset, + lex->uint_geom_type)) + MYSQL_YYABORT; + } + ; + +type: + int_type opt_field_length field_options { $$=$1; } + | real_type opt_precision field_options { $$=$1; } + | FLOAT_SYM float_options field_options { $$=MYSQL_TYPE_FLOAT; } + | BIT_SYM + { + Lex->length= (char*) "1"; + $$=MYSQL_TYPE_BIT; + } + | BIT_SYM field_length + { + $$=MYSQL_TYPE_BIT; + } + | BOOL_SYM + { + Lex->length= (char*) "1"; + $$=MYSQL_TYPE_TINY; + } + | BOOLEAN_SYM + { + Lex->length= (char*) "1"; + $$=MYSQL_TYPE_TINY; + } + | char field_length opt_binary + { + $$=MYSQL_TYPE_STRING; + } + | char opt_binary + { + Lex->length= (char*) "1"; + $$=MYSQL_TYPE_STRING; + } + | nchar field_length opt_bin_mod + { + $$=MYSQL_TYPE_STRING; + Lex->charset=national_charset_info; + } + | nchar opt_bin_mod + { + Lex->length= (char*) "1"; + $$=MYSQL_TYPE_STRING; + Lex->charset=national_charset_info; + } + | BINARY field_length + { + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_STRING; + } + | BINARY + { + Lex->length= (char*) "1"; + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_STRING; + } + | varchar field_length opt_binary + { + $$= MYSQL_TYPE_VARCHAR; + } + | nvarchar field_length opt_bin_mod + { + $$= MYSQL_TYPE_VARCHAR; + Lex->charset=national_charset_info; + } + | VARBINARY field_length + { + Lex->charset=&my_charset_bin; + $$= MYSQL_TYPE_VARCHAR; + } + | YEAR_SYM opt_field_length field_options + { $$=MYSQL_TYPE_YEAR; } + | DATE_SYM + { $$=MYSQL_TYPE_DATE; } + | TIME_SYM + { $$=MYSQL_TYPE_TIME; } + | TIMESTAMP opt_field_length + { + if (YYTHD->variables.sql_mode & MODE_MAXDB) + $$=MYSQL_TYPE_DATETIME; + else + { + /* + Unlike other types TIMESTAMP fields are NOT NULL by default. + */ + Lex->type|= NOT_NULL_FLAG; + $$=MYSQL_TYPE_TIMESTAMP; + } + } + | DATETIME + { $$=MYSQL_TYPE_DATETIME; } + | TINYBLOB + { + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_TINY_BLOB; + } + | BLOB_SYM opt_field_length + { + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_BLOB; + } + | spatial_type + { +#ifdef HAVE_SPATIAL + Lex->charset=&my_charset_bin; + Lex->uint_geom_type= (uint)$1; + $$=MYSQL_TYPE_GEOMETRY; +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + sym_group_geom.name, sym_group_geom.needed_define); + MYSQL_YYABORT; +#endif + } + | MEDIUMBLOB + { + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_MEDIUM_BLOB; + } + | LONGBLOB + { + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_LONG_BLOB; + } + | LONG_SYM VARBINARY + { + Lex->charset=&my_charset_bin; + $$=MYSQL_TYPE_MEDIUM_BLOB; + } + | LONG_SYM varchar opt_binary + { $$=MYSQL_TYPE_MEDIUM_BLOB; } + | TINYTEXT opt_binary + { $$=MYSQL_TYPE_TINY_BLOB; } + | TEXT_SYM opt_field_length opt_binary + { $$=MYSQL_TYPE_BLOB; } + | MEDIUMTEXT opt_binary + { $$=MYSQL_TYPE_MEDIUM_BLOB; } + | LONGTEXT opt_binary + { $$=MYSQL_TYPE_LONG_BLOB; } + | DECIMAL_SYM float_options field_options + { $$=MYSQL_TYPE_NEWDECIMAL;} + | NUMERIC_SYM float_options field_options + { $$=MYSQL_TYPE_NEWDECIMAL;} + | FIXED_SYM float_options field_options + { $$=MYSQL_TYPE_NEWDECIMAL;} + | ENUM + {Lex->interval_list.empty();} + '(' string_list ')' opt_binary + { $$=MYSQL_TYPE_ENUM; } + | SET + { Lex->interval_list.empty();} + '(' string_list ')' opt_binary + { $$=MYSQL_TYPE_SET; } + | LONG_SYM opt_binary + { $$=MYSQL_TYPE_MEDIUM_BLOB; } + | SERIAL_SYM + { + $$=MYSQL_TYPE_LONGLONG; + Lex->type|= (AUTO_INCREMENT_FLAG | NOT_NULL_FLAG | UNSIGNED_FLAG | + UNIQUE_FLAG); + } + ; + +spatial_type: + GEOMETRY_SYM { $$= Field::GEOM_GEOMETRY; } + | GEOMETRYCOLLECTION { $$= Field::GEOM_GEOMETRYCOLLECTION; } + | POINT_SYM + { + Lex->length= (char*)"25"; + $$= Field::GEOM_POINT; + } + | MULTIPOINT { $$= Field::GEOM_MULTIPOINT; } + | LINESTRING { $$= Field::GEOM_LINESTRING; } + | MULTILINESTRING { $$= Field::GEOM_MULTILINESTRING; } + | POLYGON { $$= Field::GEOM_POLYGON; } + | MULTIPOLYGON { $$= Field::GEOM_MULTIPOLYGON; } + ; + +char: + CHAR_SYM {} + ; + +nchar: + NCHAR_SYM {} + | NATIONAL_SYM CHAR_SYM {} + ; + +varchar: + char VARYING {} + | VARCHAR {} + ; + +nvarchar: + NATIONAL_SYM VARCHAR {} + | NVARCHAR_SYM {} + | NCHAR_SYM VARCHAR {} + | NATIONAL_SYM CHAR_SYM VARYING {} + | NCHAR_SYM VARYING {} + ; + +int_type: + INT_SYM { $$=MYSQL_TYPE_LONG; } + | TINYINT { $$=MYSQL_TYPE_TINY; } + | SMALLINT { $$=MYSQL_TYPE_SHORT; } + | MEDIUMINT { $$=MYSQL_TYPE_INT24; } + | BIGINT { $$=MYSQL_TYPE_LONGLONG; } + ; + +real_type: + REAL + { + $$= YYTHD->variables.sql_mode & MODE_REAL_AS_FLOAT ? + MYSQL_TYPE_FLOAT : MYSQL_TYPE_DOUBLE; + } + | DOUBLE_SYM + { $$=MYSQL_TYPE_DOUBLE; } + | DOUBLE_SYM PRECISION + { $$=MYSQL_TYPE_DOUBLE; } + ; + +float_options: + /* empty */ + { Lex->dec=Lex->length= (char*)0; } + | field_length + { Lex->dec= (char*)0; } + | precision + {} + ; + +precision: + '(' NUM ',' NUM ')' + { + LEX *lex=Lex; + lex->length=$2.str; + lex->dec=$4.str; + } + ; + +field_options: + /* empty */ {} + | field_opt_list {} + ; + +field_opt_list: + field_opt_list field_option {} + | field_option {} + ; + +field_option: + SIGNED_SYM {} + | UNSIGNED { Lex->type|= UNSIGNED_FLAG;} + | ZEROFILL { Lex->type|= UNSIGNED_FLAG | ZEROFILL_FLAG; } + ; + +field_length: + '(' LONG_NUM ')' { Lex->length= $2.str; } + | '(' ULONGLONG_NUM ')' { Lex->length= $2.str; } + | '(' DECIMAL_NUM ')' { Lex->length= $2.str; } + | '(' NUM ')' { Lex->length= $2.str; }; + +opt_field_length: + /* empty */ { Lex->length=(char*) 0; /* use default length */ } + | field_length { } + +opt_precision: + /* empty */ {} + | precision {} + ; + +opt_attribute: + /* empty */ {} + | opt_attribute_list {} + ; + +opt_attribute_list: + opt_attribute_list attribute {} + | attribute + ; + +attribute: + NULL_SYM { Lex->type&= ~ NOT_NULL_FLAG; } + | not NULL_SYM { Lex->type|= NOT_NULL_FLAG; } + | DEFAULT now_or_signed_literal { Lex->default_value=$2; } + | ON UPDATE_SYM NOW_SYM optional_braces + { + Item *item= new (YYTHD->mem_root) Item_func_now_local(); + if (item == NULL) + MYSQL_YYABORT; + Lex->on_update_value= item; + } + | AUTO_INC { Lex->type|= AUTO_INCREMENT_FLAG | NOT_NULL_FLAG; } + | SERIAL_SYM DEFAULT VALUE_SYM + { + LEX *lex=Lex; + lex->type|= AUTO_INCREMENT_FLAG | NOT_NULL_FLAG | UNIQUE_FLAG; + lex->alter_info.flags|= ALTER_ADD_INDEX; + } + | opt_primary KEY_SYM + { + LEX *lex=Lex; + lex->type|= PRI_KEY_FLAG | NOT_NULL_FLAG; + lex->alter_info.flags|= ALTER_ADD_INDEX; + } + | UNIQUE_SYM + { + LEX *lex=Lex; + lex->type|= UNIQUE_FLAG; + lex->alter_info.flags|= ALTER_ADD_INDEX; + } + | UNIQUE_SYM KEY_SYM + { + LEX *lex=Lex; + lex->type|= UNIQUE_KEY_FLAG; + lex->alter_info.flags|= ALTER_ADD_INDEX; + } + | COMMENT_SYM TEXT_STRING_sys { Lex->comment= $2; } + | COLLATE_SYM collation_name + { + if (Lex->charset && !my_charset_same(Lex->charset,$2)) + { + my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), + $2->name,Lex->charset->csname); + MYSQL_YYABORT; + } + else + { + Lex->charset=$2; + } + } + ; + +now_or_signed_literal: + NOW_SYM optional_braces + { + $$= new (YYTHD->mem_root) Item_func_now_local(); + if ($$ == NULL) + MYSQL_YYABORT; + } + | signed_literal + { $$=$1; } + ; + +charset: + CHAR_SYM SET {} + | CHARSET {} + ; + +charset_name: + ident_or_text + { + if (!($$=get_charset_by_csname($1.str,MY_CS_PRIMARY,MYF(0)))) + { + my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), $1.str); + MYSQL_YYABORT; + } + } + | BINARY { $$= &my_charset_bin; } + ; + +charset_name_or_default: + charset_name { $$=$1; } + | DEFAULT { $$=NULL; } + ; + +opt_load_data_charset: + /* Empty */ { $$= NULL; } + | charset charset_name_or_default { $$= $2; } + ; + +old_or_new_charset_name: + ident_or_text + { + if (!($$=get_charset_by_csname($1.str,MY_CS_PRIMARY,MYF(0))) && + !($$=get_old_charset_by_name($1.str))) + { + my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), $1.str); + MYSQL_YYABORT; + } + } + | BINARY { $$= &my_charset_bin; } + ; + +old_or_new_charset_name_or_default: + old_or_new_charset_name { $$=$1; } + | DEFAULT { $$=NULL; } + ; + +collation_name: + ident_or_text + { + if (!($$=get_charset_by_name($1.str,MYF(0)))) + { + my_error(ER_UNKNOWN_COLLATION, MYF(0), $1.str); + MYSQL_YYABORT; + } + } + ; + +opt_collate: + /* empty */ { $$=NULL; } + | COLLATE_SYM collation_name_or_default { $$=$2; } + ; + +collation_name_or_default: + collation_name { $$=$1; } + | DEFAULT { $$=NULL; } + ; + +opt_default: + /* empty */ {} + | DEFAULT {} + ; + +opt_binary: + /* empty */ { Lex->charset=NULL; } + | ASCII_SYM opt_bin_mod { Lex->charset=&my_charset_latin1; } + | BYTE_SYM { Lex->charset=&my_charset_bin; } + | UNICODE_SYM opt_bin_mod + { + if (!(Lex->charset=get_charset_by_csname("ucs2", + MY_CS_PRIMARY,MYF(0)))) + { + my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), "ucs2"); + MYSQL_YYABORT; + } + } + | charset charset_name opt_bin_mod { Lex->charset=$2; } + | BINARY opt_bin_charset { Lex->type|= BINCMP_FLAG; } + ; + +opt_bin_mod: + /* empty */ { } + | BINARY { Lex->type|= BINCMP_FLAG; } + ; + +opt_bin_charset: + /* empty */ { Lex->charset= NULL; } + | ASCII_SYM { Lex->charset=&my_charset_latin1; } + | UNICODE_SYM + { + if (!(Lex->charset=get_charset_by_csname("ucs2", + MY_CS_PRIMARY,MYF(0)))) + { + my_error(ER_UNKNOWN_CHARACTER_SET, MYF(0), "ucs2"); + MYSQL_YYABORT; + } + } + | charset charset_name { Lex->charset=$2; } + ; + +opt_primary: + /* empty */ + | PRIMARY_SYM + ; + +references: + REFERENCES table_ident + { + LEX *lex=Lex; + lex->fk_delete_opt= lex->fk_update_opt= lex->fk_match_option= 0; + lex->ref_list.empty(); + } + opt_ref_list + { + $$=$2; + } + ; + +opt_ref_list: + /* empty */ opt_on_delete {} + | '(' ref_list ')' opt_on_delete {} + ; + +ref_list: + ref_list ',' ident + { + Key_part_spec *key= new Key_part_spec($3.str); + if (key == NULL) + MYSQL_YYABORT; + Lex->ref_list.push_back(key); + } + | ident + { + Key_part_spec *key= new Key_part_spec($1.str); + if (key == NULL) + MYSQL_YYABORT; + Lex->ref_list.push_back(key); + } + ; + +opt_on_delete: + /* empty */ {} + | opt_on_delete_list {} + ; + +opt_on_delete_list: + opt_on_delete_list opt_on_delete_item {} + | opt_on_delete_item {} + ; + +opt_on_delete_item: + ON DELETE_SYM delete_option { Lex->fk_delete_opt= $3; } + | ON UPDATE_SYM delete_option { Lex->fk_update_opt= $3; } + | MATCH FULL { Lex->fk_match_option= Foreign_key::FK_MATCH_FULL; } + | MATCH PARTIAL { Lex->fk_match_option= Foreign_key::FK_MATCH_PARTIAL; } + | MATCH SIMPLE_SYM { Lex->fk_match_option= Foreign_key::FK_MATCH_SIMPLE; } + ; + +delete_option: + RESTRICT { $$= (int) Foreign_key::FK_OPTION_RESTRICT; } + | CASCADE { $$= (int) Foreign_key::FK_OPTION_CASCADE; } + | SET NULL_SYM { $$= (int) Foreign_key::FK_OPTION_SET_NULL; } + | NO_SYM ACTION { $$= (int) Foreign_key::FK_OPTION_NO_ACTION; } + | SET DEFAULT { $$= (int) Foreign_key::FK_OPTION_DEFAULT; } + ; + +key_type: + key_or_index { $$= Key::MULTIPLE; } + | FULLTEXT_SYM opt_key_or_index { $$= Key::FULLTEXT; } + | SPATIAL_SYM opt_key_or_index + { +#ifdef HAVE_SPATIAL + $$= Key::SPATIAL; +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + sym_group_geom.name, sym_group_geom.needed_define); + MYSQL_YYABORT; +#endif + } + ; + +constraint_key_type: + PRIMARY_SYM KEY_SYM { $$= Key::PRIMARY; } + | UNIQUE_SYM opt_key_or_index { $$= Key::UNIQUE; } + ; + +key_or_index: + KEY_SYM {} + | INDEX_SYM {} + ; + +opt_key_or_index: + /* empty */ {} + | key_or_index + ; + +keys_or_index: + KEYS {} + | INDEX_SYM {} + | INDEXES {} + ; + +opt_unique_or_fulltext: + /* empty */ { $$= Key::MULTIPLE; } + | UNIQUE_SYM { $$= Key::UNIQUE; } + | FULLTEXT_SYM { $$= Key::FULLTEXT;} + | SPATIAL_SYM + { +#ifdef HAVE_SPATIAL + $$= Key::SPATIAL; +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + sym_group_geom.name, sym_group_geom.needed_define); + MYSQL_YYABORT; +#endif + } + ; + +init_key_options: + { + Lex->key_create_info= default_key_create_info; + } + ; + +/* + For now, key_alg initializies lex->key_create_info. + In the future, when all key options are after key definition, + we can remove key_alg and move init_key_options to key_options +*/ + +key_alg: + init_key_options + | init_key_options key_using_alg + ; + +key_options: + /* empty */ {} + | key_opts + ; + +key_opts: + key_opt + | key_opts key_opt + ; + +key_using_alg: + USING btree_or_rtree { Lex->key_create_info.algorithm= $2; } + | TYPE_SYM btree_or_rtree { Lex->key_create_info.algorithm= $2; } + ; + +key_opt: + key_using_alg + | KEY_BLOCK_SIZE opt_equal ulong_num + { Lex->key_create_info.block_size= $3; } + | WITH PARSER_SYM IDENT_sys + { + if (plugin_is_ready(&$3, MYSQL_FTPARSER_PLUGIN)) + Lex->key_create_info.parser_name= $3; + else + { + my_error(ER_FUNCTION_NOT_DEFINED, MYF(0), $3.str); + MYSQL_YYABORT; + } + } + ; + +btree_or_rtree: + BTREE_SYM { $$= HA_KEY_ALG_BTREE; } + | RTREE_SYM { $$= HA_KEY_ALG_RTREE; } + | HASH_SYM { $$= HA_KEY_ALG_HASH; } + ; + +key_list: + key_list ',' key_part order_dir { Lex->col_list.push_back($3); } + | key_part order_dir { Lex->col_list.push_back($1); } + ; + +key_part: + ident + { + $$= new Key_part_spec($1.str); + if ($$ == NULL) + MYSQL_YYABORT; + } + | ident '(' NUM ')' + { + int key_part_len= atoi($3.str); + if (!key_part_len) + { + my_error(ER_KEY_PART_0, MYF(0), $1.str); + } + $$= new Key_part_spec($1.str,(uint) key_part_len); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +opt_ident: + /* empty */ { $$=(char*) 0; /* Default length */ } + | field_ident { $$=$1.str; } + ; + +opt_component: + /* empty */ { $$= null_lex_str; } + | '.' ident { $$= $2; } + ; + +string_list: + text_string { Lex->interval_list.push_back($1); } + | string_list ',' text_string { Lex->interval_list.push_back($3); }; + +/* +** Alter table +*/ + +alter: + ALTER opt_ignore TABLE_SYM table_ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->name.str= 0; + lex->name.length= 0; + lex->sql_command= SQLCOM_ALTER_TABLE; + lex->duplicates= DUP_ERROR; + if (!lex->select_lex.add_table_to_list(thd, $4, NULL, + TL_OPTION_UPDATING)) + MYSQL_YYABORT; + lex->alter_info.reset(); + lex->col_list.empty(); + lex->select_lex.init_order(); + lex->select_lex.db= + ((TABLE_LIST*) lex->select_lex.table_list.first)->db; + bzero((char*) &lex->create_info,sizeof(lex->create_info)); + lex->create_info.db_type= 0; + lex->create_info.default_table_charset= NULL; + lex->create_info.row_type= ROW_TYPE_NOT_USED; + lex->alter_info.reset(); + lex->no_write_to_binlog= 0; + lex->create_info.storage_media= HA_SM_DEFAULT; + } + alter_commands + {} + | ALTER DATABASE ident_or_empty + { + Lex->create_info.default_table_charset= NULL; + Lex->create_info.used_fields= 0; + } + create_database_options + { + LEX *lex=Lex; + lex->sql_command=SQLCOM_ALTER_DB; + lex->name= $3; + if (lex->name.str == NULL && + lex->copy_db_to(&lex->name.str, &lex->name.length)) + MYSQL_YYABORT; + } + | ALTER DATABASE ident UPGRADE_SYM DATA_SYM DIRECTORY_SYM NAME_SYM + { + LEX *lex= Lex; + if (lex->sphead) + { + my_error(ER_SP_NO_DROP_SP, MYF(0), "DATABASE"); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_ALTER_DB_UPGRADE; + lex->name= $3; + } + | ALTER PROCEDURE sp_name + { + LEX *lex= Lex; + + if (lex->sphead) + { + my_error(ER_SP_NO_DROP_SP, MYF(0), "PROCEDURE"); + MYSQL_YYABORT; + } + bzero((char *)&lex->sp_chistics, sizeof(st_sp_chistics)); + } + sp_a_chistics + { + LEX *lex=Lex; + + lex->sql_command= SQLCOM_ALTER_PROCEDURE; + lex->spname= $3; + } + | ALTER FUNCTION_SYM sp_name + { + LEX *lex= Lex; + + if (lex->sphead) + { + my_error(ER_SP_NO_DROP_SP, MYF(0), "FUNCTION"); + MYSQL_YYABORT; + } + bzero((char *)&lex->sp_chistics, sizeof(st_sp_chistics)); + } + sp_a_chistics + { + LEX *lex=Lex; + + lex->sql_command= SQLCOM_ALTER_FUNCTION; + lex->spname= $3; + } + | ALTER view_algorithm definer_opt + { + LEX *lex= Lex; + + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW"); + MYSQL_YYABORT; + } + lex->create_view_mode= VIEW_ALTER; + } + view_tail + {} + | ALTER definer_opt + /* + We have two separate rules for ALTER VIEW rather that + optional view_algorithm above, to resolve the ambiguity + with the ALTER EVENT below. + */ + { + LEX *lex= Lex; + + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW"); + MYSQL_YYABORT; + } + lex->create_view_algorithm= VIEW_ALGORITHM_UNDEFINED; + lex->create_view_mode= VIEW_ALTER; + } + view_tail + {} + | ALTER definer_opt EVENT_SYM sp_name + { + /* + It is safe to use Lex->spname because + ALTER EVENT xxx RENATE TO yyy DO ALTER EVENT RENAME TO + is not allowed. Lex->spname is used in the case of RENAME TO + If it had to be supported spname had to be added to + Event_parse_data. + */ + + if (!(Lex->event_parse_data= Event_parse_data::new_instance(YYTHD))) + MYSQL_YYABORT; + Lex->event_parse_data->identifier= $4; + + Lex->sql_command= SQLCOM_ALTER_EVENT; + } + ev_alter_on_schedule_completion + opt_ev_rename_to + opt_ev_status + opt_ev_comment + opt_ev_sql_stmt + { + if (!($6 || $7 || $8 || $9 || $10)) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + /* + sql_command is set here because some rules in ev_sql_stmt + can overwrite it + */ + Lex->sql_command= SQLCOM_ALTER_EVENT; + } + | ALTER TABLESPACE alter_tablespace_info + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_cmd_type= ALTER_TABLESPACE; + } + | ALTER LOGFILE_SYM GROUP_SYM alter_logfile_group_info + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_cmd_type= ALTER_LOGFILE_GROUP; + } + | ALTER TABLESPACE change_tablespace_info + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_cmd_type= CHANGE_FILE_TABLESPACE; + } + | ALTER TABLESPACE change_tablespace_access + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_cmd_type= ALTER_ACCESS_MODE_TABLESPACE; + } + | ALTER SERVER_SYM ident_or_text OPTIONS_SYM '(' server_options_list ')' + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_ALTER_SERVER; + lex->server_options.server_name= $3.str; + lex->server_options.server_name_length= $3.length; + } + ; + +ev_alter_on_schedule_completion: + /* empty */ { $$= 0;} + | ON SCHEDULE_SYM ev_schedule_time { $$= 1; } + | ev_on_completion { $$= 1; } + | ON SCHEDULE_SYM ev_schedule_time ev_on_completion { $$= 1; } + ; + +opt_ev_rename_to: + /* empty */ { $$= 0;} + | RENAME TO_SYM sp_name + { + /* + Use lex's spname to hold the new name. + The original name is in the Event_parse_data object + */ + Lex->spname= $3; + $$= 1; + } + ; + +opt_ev_sql_stmt: + /* empty*/ { $$= 0;} + | DO_SYM ev_sql_stmt { $$= 1; } + ; + +ident_or_empty: + /* empty */ { $$.str= 0; $$.length= 0; } + | ident { $$= $1; } + ; + +alter_commands: + /* empty */ + | DISCARD TABLESPACE { Lex->alter_info.tablespace_op= DISCARD_TABLESPACE; } + | IMPORT TABLESPACE { Lex->alter_info.tablespace_op= IMPORT_TABLESPACE; } + | alter_list + opt_partitioning + | alter_list + remove_partitioning + | remove_partitioning + | partitioning +/* + This part was added for release 5.1 by Mikael Ronström. + From here we insert a number of commands to manage the partitions of a + partitioned table such as adding partitions, dropping partitions, + reorganising partitions in various manners. In future releases the list + will be longer and also include moving partitions to a + new table and so forth. +*/ + | add_partition_rule + | DROP PARTITION_SYM alt_part_name_list + { + Lex->alter_info.flags|= ALTER_DROP_PARTITION; + } + | REBUILD_SYM PARTITION_SYM opt_no_write_to_binlog + all_or_alt_part_name_list + { + LEX *lex= Lex; + lex->alter_info.flags|= ALTER_REBUILD_PARTITION; + lex->no_write_to_binlog= $3; + } + | OPTIMIZE PARTITION_SYM opt_no_write_to_binlog + all_or_alt_part_name_list + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_OPTIMIZE; + lex->alter_info.flags|= ALTER_ADMIN_PARTITION; + lex->no_write_to_binlog= $3; + lex->check_opt.init(); + } + opt_no_write_to_binlog + | ANALYZE_SYM PARTITION_SYM opt_no_write_to_binlog + all_or_alt_part_name_list + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_ANALYZE; + lex->alter_info.flags|= ALTER_ADMIN_PARTITION; + lex->no_write_to_binlog= $3; + lex->check_opt.init(); + } + | CHECK_SYM PARTITION_SYM all_or_alt_part_name_list + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_CHECK; + lex->alter_info.flags|= ALTER_ADMIN_PARTITION; + lex->check_opt.init(); + } + opt_mi_check_type + | REPAIR PARTITION_SYM opt_no_write_to_binlog + all_or_alt_part_name_list + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_REPAIR; + lex->alter_info.flags|= ALTER_ADMIN_PARTITION; + lex->no_write_to_binlog= $3; + lex->check_opt.init(); + } + opt_mi_repair_type + | COALESCE PARTITION_SYM opt_no_write_to_binlog real_ulong_num + { + LEX *lex= Lex; + lex->alter_info.flags|= ALTER_COALESCE_PARTITION; + lex->no_write_to_binlog= $3; + lex->alter_info.no_parts= $4; + } + | reorg_partition_rule + ; + +remove_partitioning: + REMOVE_SYM PARTITIONING_SYM + { + Lex->alter_info.flags|= ALTER_REMOVE_PARTITIONING; + } + ; + +all_or_alt_part_name_list: + ALL + { + Lex->alter_info.flags|= ALTER_ALL_PARTITION; + } + | alt_part_name_list + ; + +add_partition_rule: + ADD PARTITION_SYM opt_no_write_to_binlog + { + LEX *lex= Lex; + lex->part_info= new partition_info(); + if (!lex->part_info) + { + mem_alloc_error(sizeof(partition_info)); + MYSQL_YYABORT; + } + lex->alter_info.flags|= ALTER_ADD_PARTITION; + lex->no_write_to_binlog= $3; + } + add_part_extra + {} + ; + +add_part_extra: + /* empty */ + | '(' part_def_list ')' + { + LEX *lex= Lex; + lex->part_info->no_parts= lex->part_info->partitions.elements; + } + | PARTITIONS_SYM real_ulong_num + { + LEX *lex= Lex; + lex->part_info->no_parts= $2; + } + ; + +reorg_partition_rule: + REORGANIZE_SYM PARTITION_SYM opt_no_write_to_binlog + { + LEX *lex= Lex; + lex->part_info= new partition_info(); + if (!lex->part_info) + { + mem_alloc_error(sizeof(partition_info)); + MYSQL_YYABORT; + } + lex->no_write_to_binlog= $3; + } + reorg_parts_rule + ; + +reorg_parts_rule: + /* empty */ + { + Lex->alter_info.flags|= ALTER_TABLE_REORG; + } + | alt_part_name_list + { + Lex->alter_info.flags|= ALTER_REORGANIZE_PARTITION; + } + INTO '(' part_def_list ')' + { + LEX *lex= Lex; + lex->part_info->no_parts= lex->part_info->partitions.elements; + } + ; + +alt_part_name_list: + alt_part_name_item {} + | alt_part_name_list ',' alt_part_name_item {} + ; + +alt_part_name_item: + ident + { + if (Lex->alter_info.partition_names.push_back($1.str)) + { + mem_alloc_error(1); + MYSQL_YYABORT; + } + } + ; + +/* + End of management of partition commands +*/ + +alter_list: + alter_list_item + | alter_list ',' alter_list_item + ; + +add_column: + ADD opt_column + { + LEX *lex=Lex; + lex->change=0; + lex->alter_info.flags|= ALTER_ADD_COLUMN; + } + ; + +alter_list_item: + add_column column_def opt_place { } + | ADD key_def + { + Lex->alter_info.flags|= ALTER_ADD_INDEX; + } + | add_column '(' field_list ')' + { + Lex->alter_info.flags|= ALTER_ADD_COLUMN | ALTER_ADD_INDEX; + } + | CHANGE opt_column field_ident + { + LEX *lex=Lex; + lex->change= $3.str; + lex->alter_info.flags|= ALTER_CHANGE_COLUMN; + } + field_spec opt_place + | MODIFY_SYM opt_column field_ident + { + LEX *lex=Lex; + lex->length=lex->dec=0; lex->type=0; + lex->default_value= lex->on_update_value= 0; + lex->comment=null_lex_str; + lex->charset= NULL; + lex->alter_info.flags|= ALTER_CHANGE_COLUMN; + } + type opt_attribute + { + LEX *lex=Lex; + if (add_field_to_list(lex->thd,&$3, + (enum enum_field_types) $5, + lex->length,lex->dec,lex->type, + lex->default_value, lex->on_update_value, + &lex->comment, + $3.str, &lex->interval_list, lex->charset, + lex->uint_geom_type)) + MYSQL_YYABORT; + } + opt_place + | DROP opt_column field_ident opt_restrict + { + LEX *lex=Lex; + Alter_drop *ad= new Alter_drop(Alter_drop::COLUMN, $3.str); + if (ad == NULL) + MYSQL_YYABORT; + lex->alter_info.drop_list.push_back(ad); + lex->alter_info.flags|= ALTER_DROP_COLUMN; + } + | DROP FOREIGN KEY_SYM opt_ident + { + Lex->alter_info.flags|= ALTER_DROP_INDEX | ALTER_FOREIGN_KEY; + } + | DROP PRIMARY_SYM KEY_SYM + { + LEX *lex=Lex; + Alter_drop *ad= new Alter_drop(Alter_drop::KEY, primary_key_name); + if (ad == NULL) + MYSQL_YYABORT; + lex->alter_info.drop_list.push_back(ad); + lex->alter_info.flags|= ALTER_DROP_INDEX; + } + | DROP key_or_index field_ident + { + LEX *lex=Lex; + Alter_drop *ad= new Alter_drop(Alter_drop::KEY, $3.str); + if (ad == NULL) + MYSQL_YYABORT; + lex->alter_info.drop_list.push_back(ad); + lex->alter_info.flags|= ALTER_DROP_INDEX; + } + | DISABLE_SYM KEYS + { + LEX *lex=Lex; + lex->alter_info.keys_onoff= DISABLE; + lex->alter_info.flags|= ALTER_KEYS_ONOFF; + } + | ENABLE_SYM KEYS + { + LEX *lex=Lex; + lex->alter_info.keys_onoff= ENABLE; + lex->alter_info.flags|= ALTER_KEYS_ONOFF; + } + | ALTER opt_column field_ident SET DEFAULT signed_literal + { + LEX *lex=Lex; + Alter_column *ac= new Alter_column($3.str,$6); + if (ac == NULL) + MYSQL_YYABORT; + lex->alter_info.alter_list.push_back(ac); + lex->alter_info.flags|= ALTER_CHANGE_COLUMN_DEFAULT; + } + | ALTER opt_column field_ident DROP DEFAULT + { + LEX *lex=Lex; + Alter_column *ac= new Alter_column($3.str, (Item*) 0); + if (ac == NULL) + MYSQL_YYABORT; + lex->alter_info.alter_list.push_back(ac); + lex->alter_info.flags|= ALTER_CHANGE_COLUMN_DEFAULT; + } + | RENAME opt_to table_ident + { + LEX *lex=Lex; + size_t dummy; + lex->select_lex.db=$3->db.str; + if (lex->select_lex.db == NULL && + lex->copy_db_to(&lex->select_lex.db, &dummy)) + { + MYSQL_YYABORT; + } + if (check_table_name($3->table.str,$3->table.length) || + ($3->db.str && check_db_name(&$3->db))) + { + my_error(ER_WRONG_TABLE_NAME, MYF(0), $3->table.str); + MYSQL_YYABORT; + } + lex->name= $3->table; + lex->alter_info.flags|= ALTER_RENAME; + } + | CONVERT_SYM TO_SYM charset charset_name_or_default opt_collate + { + if (!$4) + { + THD *thd= YYTHD; + $4= thd->variables.collation_database; + } + $5= $5 ? $5 : $4; + if (!my_charset_same($4,$5)) + { + my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), + $5->name, $4->csname); + MYSQL_YYABORT; + } + LEX *lex= Lex; + lex->create_info.table_charset= + lex->create_info.default_table_charset= $5; + lex->create_info.used_fields|= (HA_CREATE_USED_CHARSET | + HA_CREATE_USED_DEFAULT_CHARSET); + lex->alter_info.flags|= ALTER_CONVERT; + } + | create_table_options_space_separated + { + LEX *lex=Lex; + lex->alter_info.flags|= ALTER_OPTIONS; + } + | FORCE_SYM + { + Lex->alter_info.flags|= ALTER_FORCE; + } + | alter_order_clause + { + LEX *lex=Lex; + lex->alter_info.flags|= ALTER_ORDER; + } + ; + +opt_column: + /* empty */ {} + | COLUMN_SYM {} + ; + +opt_ignore: + /* empty */ { Lex->ignore= 0;} + | IGNORE_SYM { Lex->ignore= 1;} + ; + +opt_restrict: + /* empty */ { Lex->drop_mode= DROP_DEFAULT; } + | RESTRICT { Lex->drop_mode= DROP_RESTRICT; } + | CASCADE { Lex->drop_mode= DROP_CASCADE; } + ; + +opt_place: + /* empty */ {} + | AFTER_SYM ident { store_position_for_column($2.str); } + | FIRST_SYM { store_position_for_column(first_keyword); } + ; + +opt_to: + /* empty */ {} + | TO_SYM {} + | EQ {} + | AS {} + ; + +/* + SLAVE START and SLAVE STOP are deprecated. We keep them for compatibility. +*/ + +slave: + START_SYM SLAVE slave_thread_opts + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_SLAVE_START; + lex->type = 0; + /* We'll use mi structure for UNTIL options */ + bzero((char*) &lex->mi, sizeof(lex->mi)); + /* If you change this code don't forget to update SLAVE START too */ + } + slave_until + {} + | STOP_SYM SLAVE slave_thread_opts + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_SLAVE_STOP; + lex->type = 0; + /* If you change this code don't forget to update SLAVE STOP too */ + } + | SLAVE START_SYM slave_thread_opts + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_SLAVE_START; + lex->type = 0; + /* We'll use mi structure for UNTIL options */ + bzero((char*) &lex->mi, sizeof(lex->mi)); + } + slave_until + {} + | SLAVE STOP_SYM slave_thread_opts + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_SLAVE_STOP; + lex->type = 0; + } + ; + +start: + START_SYM TRANSACTION_SYM start_transaction_opts + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_BEGIN; + lex->start_transaction_opt= $3; + } + ; + +start_transaction_opts: + /*empty*/ { $$ = 0; } + | WITH CONSISTENT_SYM SNAPSHOT_SYM + { + $$= MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT; + } + ; + +slave_thread_opts: + { Lex->slave_thd_opt= 0; } + slave_thread_opt_list + {} + ; + +slave_thread_opt_list: + slave_thread_opt + | slave_thread_opt_list ',' slave_thread_opt + ; + +slave_thread_opt: + /*empty*/ {} + | SQL_THREAD { Lex->slave_thd_opt|=SLAVE_SQL; } + | RELAY_THREAD { Lex->slave_thd_opt|=SLAVE_IO; } + ; + +slave_until: + /*empty*/ {} + | UNTIL_SYM slave_until_opts + { + LEX *lex=Lex; + if (((lex->mi.log_file_name || lex->mi.pos) && + (lex->mi.relay_log_name || lex->mi.relay_log_pos)) || + !((lex->mi.log_file_name && lex->mi.pos) || + (lex->mi.relay_log_name && lex->mi.relay_log_pos))) + { + my_message(ER_BAD_SLAVE_UNTIL_COND, + ER(ER_BAD_SLAVE_UNTIL_COND), MYF(0)); + MYSQL_YYABORT; + } + } + ; + +slave_until_opts: + master_file_def + | slave_until_opts ',' master_file_def + ; + +restore: + RESTORE_SYM table_or_tables + { + Lex->sql_command = SQLCOM_RESTORE_TABLE; + } + table_list FROM TEXT_STRING_sys + { + Lex->backup_dir = $6.str; + } + ; + +backup: + BACKUP_SYM table_or_tables + { + Lex->sql_command = SQLCOM_BACKUP_TABLE; + } + table_list TO_SYM TEXT_STRING_sys + { + Lex->backup_dir = $6.str; + } + ; + +checksum: + CHECKSUM_SYM table_or_tables + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_CHECKSUM; + } + table_list opt_checksum_type + {} + ; + +opt_checksum_type: + /* nothing */ { Lex->check_opt.flags= 0; } + | QUICK { Lex->check_opt.flags= T_QUICK; } + | EXTENDED_SYM { Lex->check_opt.flags= T_EXTEND; } + ; + +repair: + REPAIR opt_no_write_to_binlog table_or_tables + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_REPAIR; + lex->no_write_to_binlog= $2; + lex->check_opt.init(); + lex->alter_info.reset(); + } + table_list opt_mi_repair_type + {} + ; + +opt_mi_repair_type: + /* empty */ { Lex->check_opt.flags = T_MEDIUM; } + | mi_repair_types {} + ; + +mi_repair_types: + mi_repair_type {} + | mi_repair_type mi_repair_types {} + ; + +mi_repair_type: + QUICK { Lex->check_opt.flags|= T_QUICK; } + | EXTENDED_SYM { Lex->check_opt.flags|= T_EXTEND; } + | USE_FRM { Lex->check_opt.sql_flags|= TT_USEFRM; } + ; + +analyze: + ANALYZE_SYM opt_no_write_to_binlog table_or_tables + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_ANALYZE; + lex->no_write_to_binlog= $2; + lex->check_opt.init(); + lex->alter_info.reset(); + } + table_list + {} + ; + +binlog_base64_event: + BINLOG_SYM TEXT_STRING_sys + { + Lex->sql_command = SQLCOM_BINLOG_BASE64_EVENT; + Lex->comment= $2; + } + ; + +check: + CHECK_SYM table_or_tables + { + LEX *lex=Lex; + + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "CHECK"); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_CHECK; + lex->check_opt.init(); + lex->alter_info.reset(); + } + table_list opt_mi_check_type + {} + ; + +opt_mi_check_type: + /* empty */ { Lex->check_opt.flags = T_MEDIUM; } + | mi_check_types {} + ; + +mi_check_types: + mi_check_type {} + | mi_check_type mi_check_types {} + ; + +mi_check_type: + QUICK { Lex->check_opt.flags|= T_QUICK; } + | FAST_SYM { Lex->check_opt.flags|= T_FAST; } + | MEDIUM_SYM { Lex->check_opt.flags|= T_MEDIUM; } + | EXTENDED_SYM { Lex->check_opt.flags|= T_EXTEND; } + | CHANGED { Lex->check_opt.flags|= T_CHECK_ONLY_CHANGED; } + | FOR_SYM UPGRADE_SYM { Lex->check_opt.sql_flags|= TT_FOR_UPGRADE; } + ; + +optimize: + OPTIMIZE opt_no_write_to_binlog table_or_tables + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_OPTIMIZE; + lex->no_write_to_binlog= $2; + lex->check_opt.init(); + lex->alter_info.reset(); + } + table_list + {} + ; + +opt_no_write_to_binlog: + /* empty */ { $$= 0; } + | NO_WRITE_TO_BINLOG { $$= 1; } + | LOCAL_SYM { $$= 1; } + ; + +rename: + RENAME table_or_tables + { + Lex->sql_command= SQLCOM_RENAME_TABLE; + } + table_to_table_list + {} + | RENAME USER clear_privileges rename_list + { + Lex->sql_command = SQLCOM_RENAME_USER; + } + ; + +rename_list: + user TO_SYM user + { + if (Lex->users_list.push_back($1) || Lex->users_list.push_back($3)) + MYSQL_YYABORT; + } + | rename_list ',' user TO_SYM user + { + if (Lex->users_list.push_back($3) || Lex->users_list.push_back($5)) + MYSQL_YYABORT; + } + ; + +table_to_table_list: + table_to_table + | table_to_table_list ',' table_to_table + ; + +table_to_table: + table_ident TO_SYM table_ident + { + LEX *lex=Lex; + SELECT_LEX *sl= lex->current_select; + if (!sl->add_table_to_list(lex->thd, $1,NULL,TL_OPTION_UPDATING, + TL_IGNORE) || + !sl->add_table_to_list(lex->thd, $3,NULL,TL_OPTION_UPDATING, + TL_IGNORE)) + MYSQL_YYABORT; + } + ; + +keycache: + CACHE_SYM INDEX_SYM keycache_list IN_SYM key_cache_name + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_ASSIGN_TO_KEYCACHE; + lex->ident= $5; + } + ; + +keycache_list: + assign_to_keycache + | keycache_list ',' assign_to_keycache + ; + +assign_to_keycache: + table_ident cache_keys_spec + { + if (!Select->add_table_to_list(YYTHD, $1, NULL, 0, TL_READ, + Select->pop_index_hints())) + MYSQL_YYABORT; + } + ; + +key_cache_name: + ident { $$= $1; } + | DEFAULT { $$ = default_key_cache_base; } + ; + +preload: + LOAD INDEX_SYM INTO CACHE_SYM + { + LEX *lex=Lex; + lex->sql_command=SQLCOM_PRELOAD_KEYS; + } + preload_list + {} + ; + +preload_list: + preload_keys + | preload_list ',' preload_keys + ; + +preload_keys: + table_ident cache_keys_spec opt_ignore_leaves + { + if (!Select->add_table_to_list(YYTHD, $1, NULL, $3, TL_READ, + Select->pop_index_hints())) + MYSQL_YYABORT; + } + ; + +cache_keys_spec: + { + Lex->select_lex.alloc_index_hints(YYTHD); + Select->set_index_hint_type(INDEX_HINT_USE, + global_system_variables.old_mode ? + INDEX_HINT_MASK_JOIN : + INDEX_HINT_MASK_ALL); + } + cache_key_list_or_empty + ; + +cache_key_list_or_empty: + /* empty */ { } + | key_or_index '(' opt_key_usage_list ')' + ; + +opt_ignore_leaves: + /* empty */ + { $$= 0; } + | IGNORE_SYM LEAVES { $$= TL_OPTION_IGNORE_LEAVES; } + ; + +/* + Select : retrieve data from table +*/ + + +select: + select_init + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SELECT; + } + ; + +/* Need select_init2 for subselects. */ +select_init: + SELECT_SYM select_init2 + | '(' select_paren ')' union_opt + ; + +select_paren: + SELECT_SYM select_part2 + { + LEX *lex= Lex; + SELECT_LEX * sel= lex->current_select; + if (sel->set_braces(1)) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if (sel->linkage == UNION_TYPE && + !sel->master_unit()->first_select()->braces && + sel->master_unit()->first_select()->linkage == + UNION_TYPE) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if (sel->linkage == UNION_TYPE && + sel->olap != UNSPECIFIED_OLAP_TYPE && + sel->master_unit()->fake_select_lex) + { + my_error(ER_WRONG_USAGE, MYF(0), + "CUBE/ROLLUP", "ORDER BY"); + MYSQL_YYABORT; + } + /* select in braces, can't contain global parameters */ + if (sel->master_unit()->fake_select_lex) + sel->master_unit()->global_parameters= + sel->master_unit()->fake_select_lex; + } + | '(' select_paren ')' + ; + +select_init2: + select_part2 + { + LEX *lex= Lex; + SELECT_LEX * sel= lex->current_select; + if (lex->current_select->set_braces(0)) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if (sel->linkage == UNION_TYPE && + sel->master_unit()->first_select()->braces) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + } + union_clause + ; + +select_part2: + { + LEX *lex= Lex; + SELECT_LEX *sel= lex->current_select; + if (sel->linkage != UNION_TYPE) + mysql_init_select(lex); + lex->current_select->parsing_place= SELECT_LIST; + } + select_options select_item_list + { + Select->parsing_place= NO_MATTER; + } + select_into select_lock_type + ; + +select_into: + opt_order_clause opt_limit_clause {} + | into + | select_from + | into select_from + | select_from into + ; + +select_from: + FROM join_table_list where_clause group_clause having_clause + opt_order_clause opt_limit_clause procedure_clause + { + Select->context.table_list= + Select->context.first_name_resolution_table= + (TABLE_LIST *) Select->table_list.first; + } + | FROM DUAL_SYM where_clause opt_limit_clause + /* oracle compatibility: oracle always requires FROM clause, + and DUAL is system table without fields. + Is "SELECT 1 FROM DUAL" any better than "SELECT 1" ? + Hmmm :) */ + ; + +select_options: + /* empty*/ + | select_option_list + { + if (Select->options & SELECT_DISTINCT && Select->options & SELECT_ALL) + { + my_error(ER_WRONG_USAGE, MYF(0), "ALL", "DISTINCT"); + MYSQL_YYABORT; + } + } + ; + +select_option_list: + select_option_list select_option + | select_option + ; + +select_option: + STRAIGHT_JOIN { Select->options|= SELECT_STRAIGHT_JOIN; } + | HIGH_PRIORITY + { + if (check_simple_select()) + MYSQL_YYABORT; + Lex->lock_option= TL_READ_HIGH_PRIORITY; + Lex->current_select->lock_option= TL_READ_HIGH_PRIORITY; + } + | DISTINCT { Select->options|= SELECT_DISTINCT; } + | SQL_SMALL_RESULT { Select->options|= SELECT_SMALL_RESULT; } + | SQL_BIG_RESULT { Select->options|= SELECT_BIG_RESULT; } + | SQL_BUFFER_RESULT + { + if (check_simple_select()) + MYSQL_YYABORT; + Select->options|= OPTION_BUFFER_RESULT; + } + | SQL_CALC_FOUND_ROWS + { + if (check_simple_select()) + MYSQL_YYABORT; + Select->options|= OPTION_FOUND_ROWS; + } + | SQL_NO_CACHE_SYM + { + Lex->safe_to_cache_query=0; + Lex->select_lex.options&= ~OPTION_TO_QUERY_CACHE; + Lex->select_lex.sql_cache= SELECT_LEX::SQL_NO_CACHE; + } + | INFINIDB_ORDERED_SYM + { + Lex->thd->infinidb_vtable.override_largeside_estimate=1; + } + | SQL_CACHE_SYM + { + /* + Honor this flag only if SQL_NO_CACHE wasn't specified AND + we are parsing the outermost SELECT in the query. + */ + if (Lex->select_lex.sql_cache != SELECT_LEX::SQL_NO_CACHE && + Lex->current_select == &Lex->select_lex) + { + Lex->safe_to_cache_query=1; + Lex->select_lex.options|= OPTION_TO_QUERY_CACHE; + Lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE; + } + } + | ALL { Select->options|= SELECT_ALL; } + ; + +select_lock_type: + /* empty */ + | FOR_SYM UPDATE_SYM + { + LEX *lex=Lex; + lex->current_select->set_lock_for_tables(TL_WRITE); + lex->current_select->lock_option= TL_WRITE; + lex->safe_to_cache_query=0; + lex->protect_against_global_read_lock= TRUE; + } + | LOCK_SYM IN_SYM SHARE_SYM MODE_SYM + { + LEX *lex=Lex; + lex->current_select-> + set_lock_for_tables(TL_READ_WITH_SHARED_LOCKS); + lex->current_select->lock_option= TL_READ_WITH_SHARED_LOCKS; + lex->safe_to_cache_query=0; + } + ; + +select_item_list: + select_item_list ',' select_item + | select_item + | '*' + { + THD *thd= YYTHD; + Item *item= new (thd->mem_root) + Item_field(&thd->lex->current_select->context, + NULL, NULL, "*"); + if (item == NULL) + MYSQL_YYABORT; + if (add_item_to_list(thd, item)) + MYSQL_YYABORT; + (thd->lex->current_select->with_wild)++; + } + ; + +select_item: + remember_name select_item2 remember_end select_alias + { + THD *thd= YYTHD; + DBUG_ASSERT($1 < $3); + + if (add_item_to_list(thd, $2)) + MYSQL_YYABORT; + if ($4.str) + { + if (Lex->sql_command == SQLCOM_CREATE_VIEW && + check_column_name($4.str)) + { + my_error(ER_WRONG_COLUMN_NAME, MYF(0), $4.str); + MYSQL_YYABORT; + } + $2->is_autogenerated_name= FALSE; + $2->set_name($4.str, $4.length, system_charset_info); + } + else if (!$2->name) + { + $2->set_name($1, (uint) ($3 - $1), thd->charset()); + } + } + ; + +remember_name: + { + $$= (char*) YYLIP->get_cpp_tok_start(); + } + ; + +remember_end: + { + $$= (char*) YYLIP->get_cpp_tok_end(); + } + ; + +select_item2: + table_wild { $$=$1; /* table.* */ } + | expr { $$=$1; } + ; + +select_alias: + /* empty */ { $$=null_lex_str;} + | AS ident { $$=$2; } + | AS TEXT_STRING_sys { $$=$2; } + | ident { $$=$1; } + | TEXT_STRING_sys { $$=$1; } + ; + +optional_braces: + /* empty */ {} + | '(' ')' {} + ; + +/* all possible expressions */ +expr: + expr or expr %prec OR_SYM + { + /* + Design notes: + Do not use a manually maintained stack like thd->lex->xxx_list, + but use the internal bison stack ($$, $1 and $3) instead. + Using the bison stack is: + - more robust to changes in the grammar, + - guaranteed to be in sync with the parser state, + - better for performances (no memory allocation). + */ + Item_cond_or *item1; + Item_cond_or *item3; + if (is_cond_or($1)) + { + item1= (Item_cond_or*) $1; + if (is_cond_or($3)) + { + item3= (Item_cond_or*) $3; + /* + (X1 OR X2) OR (Y1 OR Y2) ==> OR (X1, X2, Y1, Y2) + */ + item3->add_at_head(item1->argument_list()); + $$ = $3; + } + else + { + /* + (X1 OR X2) OR Y ==> OR (X1, X2, Y) + */ + item1->add($3); + $$ = $1; + } + } + else if (is_cond_or($3)) + { + item3= (Item_cond_or*) $3; + /* + X OR (Y1 OR Y2) ==> OR (X, Y1, Y2) + */ + item3->add_at_head($1); + $$ = $3; + } + else + { + /* X OR Y */ + $$ = new (YYTHD->mem_root) Item_cond_or($1, $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + } + | expr XOR expr %prec XOR + { + /* XOR is a proprietary extension */ + $$ = new (YYTHD->mem_root) Item_cond_xor($1, $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | expr and expr %prec AND_SYM + { + /* See comments in rule expr: expr or expr */ + Item_cond_and *item1; + Item_cond_and *item3; + if (is_cond_and($1)) + { + item1= (Item_cond_and*) $1; + if (is_cond_and($3)) + { + item3= (Item_cond_and*) $3; + /* + (X1 AND X2) AND (Y1 AND Y2) ==> AND (X1, X2, Y1, Y2) + */ + item3->add_at_head(item1->argument_list()); + $$ = $3; + } + else + { + /* + (X1 AND X2) AND Y ==> AND (X1, X2, Y) + */ + item1->add($3); + $$ = $1; + } + } + else if (is_cond_and($3)) + { + item3= (Item_cond_and*) $3; + /* + X AND (Y1 AND Y2) ==> AND (X, Y1, Y2) + */ + item3->add_at_head($1); + $$ = $3; + } + else + { + /* X AND Y */ + $$ = new (YYTHD->mem_root) Item_cond_and($1, $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + } + | NOT_SYM expr %prec NOT_SYM + { + $$= negate_expression(YYTHD, $2); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS TRUE_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_istrue($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS not TRUE_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isnottrue($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS FALSE_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isfalse($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS not FALSE_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isnotfalse($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS UNKNOWN_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isnull($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS not UNKNOWN_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isnotnull($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri + ; + +bool_pri: + bool_pri IS NULL_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isnull($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri IS not NULL_SYM %prec IS + { + $$= new (YYTHD->mem_root) Item_func_isnotnull($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri EQUAL_SYM predicate %prec EQUAL_SYM + { + $$= new (YYTHD->mem_root) Item_func_equal($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri comp_op predicate %prec EQ + { + $$= (*$2)(0)->create($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bool_pri comp_op all_or_any '(' subselect ')' %prec EQ + { + $$= all_any_subquery_creator($1, $2, $3, $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | predicate + ; + +predicate: + bit_expr IN_SYM '(' subselect ')' + { + $$= new (YYTHD->mem_root) Item_in_subselect($1, $4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr not IN_SYM '(' subselect ')' + { + THD *thd= YYTHD; + Item *item= new (thd->mem_root) Item_in_subselect($1, $5); + if (item == NULL) + MYSQL_YYABORT; + $$= negate_expression(thd, item); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr IN_SYM '(' expr ')' + { + $$= handle_sql2003_note184_exception(YYTHD, $1, true, $4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr IN_SYM '(' expr ',' expr_list ')' + { + $6->push_front($4); + $6->push_front($1); + $$= new (YYTHD->mem_root) Item_func_in(*$6); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr not IN_SYM '(' expr ')' + { + $$= handle_sql2003_note184_exception(YYTHD, $1, false, $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr not IN_SYM '(' expr ',' expr_list ')' + { + $7->push_front($5); + $7->push_front($1); + Item_func_in *item = new (YYTHD->mem_root) Item_func_in(*$7); + if (item == NULL) + MYSQL_YYABORT; + item->negate(); + $$= item; + } + | bit_expr BETWEEN_SYM bit_expr AND_SYM predicate + { + $$= new (YYTHD->mem_root) Item_func_between($1,$3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr not BETWEEN_SYM bit_expr AND_SYM predicate + { + Item_func_between *item; + item= new (YYTHD->mem_root) Item_func_between($1,$4,$6); + if (item == NULL) + MYSQL_YYABORT; + item->negate(); + $$= item; + } + | bit_expr SOUNDS_SYM LIKE bit_expr + { + Item *item1= new (YYTHD->mem_root) Item_func_soundex($1); + Item *item4= new (YYTHD->mem_root) Item_func_soundex($4); + if ((item1 == NULL) || (item4 == NULL)) + MYSQL_YYABORT; + $$= new (YYTHD->mem_root) Item_func_eq(item1, item4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr LIKE simple_expr opt_escape + { + $$= new (YYTHD->mem_root) Item_func_like($1,$3,$4,Lex->escape_used); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr not LIKE simple_expr opt_escape + { + Item *item= new (YYTHD->mem_root) Item_func_like($1,$4,$5, + Lex->escape_used); + if (item == NULL) + MYSQL_YYABORT; + $$= new (YYTHD->mem_root) Item_func_not(item); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr REGEXP bit_expr + { + $$= new (YYTHD->mem_root) Item_func_regex($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr not REGEXP bit_expr + { + Item *item= new (YYTHD->mem_root) Item_func_regex($1,$4); + if (item == NULL) + MYSQL_YYABORT; + $$= negate_expression(YYTHD, item); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr + ; + +bit_expr: + bit_expr '|' bit_expr %prec '|' + { + $$= new (YYTHD->mem_root) Item_func_bit_or($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '&' bit_expr %prec '&' + { + $$= new (YYTHD->mem_root) Item_func_bit_and($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr SHIFT_LEFT bit_expr %prec SHIFT_LEFT + { + $$= new (YYTHD->mem_root) Item_func_shift_left($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr SHIFT_RIGHT bit_expr %prec SHIFT_RIGHT + { + $$= new (YYTHD->mem_root) Item_func_shift_right($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '+' bit_expr %prec '+' + { + $$= new (YYTHD->mem_root) Item_func_plus($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '-' bit_expr %prec '-' + { + $$= new (YYTHD->mem_root) Item_func_minus($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '+' INTERVAL_SYM expr interval %prec '+' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($1,$4,$5,0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '-' INTERVAL_SYM expr interval %prec '-' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($1,$4,$5,1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '*' bit_expr %prec '*' + { + $$= new (YYTHD->mem_root) Item_func_mul($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '/' bit_expr %prec '/' + { + $$= new (YYTHD->mem_root) Item_func_div($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '%' bit_expr %prec '%' + { + $$= new (YYTHD->mem_root) Item_func_mod($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr DIV_SYM bit_expr %prec DIV_SYM + { + $$= new (YYTHD->mem_root) Item_func_int_div($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr MOD_SYM bit_expr %prec MOD_SYM + { + $$= new (YYTHD->mem_root) Item_func_mod($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | bit_expr '^' bit_expr + { + $$= new (YYTHD->mem_root) Item_func_bit_xor($1,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | simple_expr + ; + +or: + OR_SYM + | OR2_SYM + ; + +and: + AND_SYM + | AND_AND_SYM + ; + +not: + NOT_SYM + | NOT2_SYM + ; + +not2: + '!' + | NOT2_SYM + ; + +comp_op: + EQ { $$ = &comp_eq_creator; } + | GE { $$ = &comp_ge_creator; } + | GT_SYM { $$ = &comp_gt_creator; } + | LE { $$ = &comp_le_creator; } + | LT { $$ = &comp_lt_creator; } + | NE { $$ = &comp_ne_creator; } + ; + +all_or_any: + ALL { $$ = 1; } + | ANY_SYM { $$ = 0; } + ; + +simple_expr: + simple_ident + | function_call_keyword + | function_call_nonkeyword + | function_call_generic + | function_call_conflict + | simple_expr COLLATE_SYM ident_or_text %prec NEG + { + THD *thd= YYTHD; + Item *i1= new (thd->mem_root) Item_string($3.str, + $3.length, + thd->charset()); + if (i1 == NULL) + MYSQL_YYABORT; + $$= new (thd->mem_root) Item_func_set_collation($1, i1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | literal + | param_marker + | variable + | sum_expr + | simple_expr OR_OR_SYM simple_expr + { + $$= new (YYTHD->mem_root) Item_func_concat($1, $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | '+' simple_expr %prec NEG + { + $$= $2; + } + | '-' simple_expr %prec NEG + { + $$= new (YYTHD->mem_root) Item_func_neg($2); + if ($$ == NULL) + MYSQL_YYABORT; + } + | '~' simple_expr %prec NEG + { + $$= new (YYTHD->mem_root) Item_func_bit_neg($2); + if ($$ == NULL) + MYSQL_YYABORT; + } + | not2 simple_expr %prec NEG + { + $$= negate_expression(YYTHD, $2); + if ($$ == NULL) + MYSQL_YYABORT; + } + | '(' subselect ')' + { + $$= new (YYTHD->mem_root) Item_singlerow_subselect($2); + if ($$ == NULL) + MYSQL_YYABORT; + } + | '(' expr ')' + { $$= $2; } + | '(' expr ',' expr_list ')' + { + $4->push_front($2); + $$= new (YYTHD->mem_root) Item_row(*$4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | ROW_SYM '(' expr ',' expr_list ')' + { + $5->push_front($3); + $$= new (YYTHD->mem_root) Item_row(*$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | EXISTS '(' subselect ')' + { + $$= new (YYTHD->mem_root) Item_exists_subselect($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | '{' ident expr '}' + { $$= $3; } + | MATCH ident_list_arg AGAINST '(' bit_expr fulltext_options ')' + { + $2->push_front($5); + Item_func_match *i1= new (YYTHD->mem_root) Item_func_match(*$2, $6); + if (i1 == NULL) + MYSQL_YYABORT; + Select->add_ftfunc_to_list(i1); + $$= i1; + } + | BINARY simple_expr %prec NEG + { + $$= create_func_cast(YYTHD, $2, ITEM_CAST_CHAR, NULL, NULL, + &my_charset_bin); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CAST_SYM '(' expr AS cast_type ')' + { + LEX *lex= Lex; + $$= create_func_cast(YYTHD, $3, $5, lex->length, lex->dec, + lex->charset); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CASE_SYM opt_expr when_list opt_else END + { + $$= new (YYTHD->mem_root) Item_func_case(* $3, $2, $4 ); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CONVERT_SYM '(' expr ',' cast_type ')' + { + $$= create_func_cast(YYTHD, $3, $5, Lex->length, Lex->dec, + Lex->charset); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CONVERT_SYM '(' expr USING charset_name ')' + { + $$= new (YYTHD->mem_root) Item_func_conv_charset($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | DEFAULT '(' simple_ident ')' + { + if ($3->is_splocal()) + { + Item_splocal *il= static_cast($3); + + my_error(ER_WRONG_COLUMN_NAME, MYF(0), il->my_name()->str); + MYSQL_YYABORT; + } + $$= new (YYTHD->mem_root) Item_default_value(Lex->current_context(), + $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | VALUES '(' simple_ident_nospvar ')' + { + $$= new (YYTHD->mem_root) Item_insert_value(Lex->current_context(), + $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | INTERVAL_SYM expr interval '+' expr %prec INTERVAL_SYM + /* we cannot put interval before - */ + { + $$= new (YYTHD->mem_root) Item_date_add_interval($5,$2,$3,0); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +/* + Function call syntax using official SQL 2003 keywords. + Because the function name is an official token, + a dedicated grammar rule is needed in the parser. + There is no potential for conflicts +*/ +function_call_keyword: + CHAR_SYM '(' expr_list ')' + { + $$= new (YYTHD->mem_root) Item_func_char(*$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CHAR_SYM '(' expr_list USING charset_name ')' + { + $$= new (YYTHD->mem_root) Item_func_char(*$3, $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CURRENT_USER optional_braces + { + $$= new (YYTHD->mem_root) Item_func_current_user(Lex->current_context()); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->set_stmt_unsafe(); + Lex->safe_to_cache_query= 0; + } + | DATE_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_date_typecast($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | DAY_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_dayofmonth($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | HOUR_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_hour($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | INSERT '(' expr ',' expr ',' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_insert($3,$5,$7,$9); + if ($$ == NULL) + MYSQL_YYABORT; + } + | INTERVAL_SYM '(' expr ',' expr ')' %prec INTERVAL_SYM + { + THD *thd= YYTHD; + List *list= new (thd->mem_root) List; + if (list == NULL) + MYSQL_YYABORT; + list->push_front($5); + list->push_front($3); + Item_row *item= new (thd->mem_root) Item_row(*list); + if (item == NULL) + MYSQL_YYABORT; + $$= new (thd->mem_root) Item_func_interval(item); + if ($$ == NULL) + MYSQL_YYABORT; + } + | INTERVAL_SYM '(' expr ',' expr ',' expr_list ')' %prec INTERVAL_SYM + { + THD *thd= YYTHD; + $7->push_front($5); + $7->push_front($3); + Item_row *item= new (thd->mem_root) Item_row(*$7); + if (item == NULL) + MYSQL_YYABORT; + $$= new (thd->mem_root) Item_func_interval(item); + if ($$ == NULL) + MYSQL_YYABORT; + } + | LEFT '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_left($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MINUTE_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_minute($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MONTH_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_month($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | RIGHT '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_right($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SECOND_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_second($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TIME_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_time_typecast($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TIMESTAMP '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_datetime_typecast($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TIMESTAMP '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_add_time($3, $5, 1, 0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_trim($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' LEADING expr FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_ltrim($6,$4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' TRAILING expr FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_rtrim($6,$4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' BOTH expr FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_trim($6,$4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' LEADING FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_ltrim($5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' TRAILING FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_rtrim($5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' BOTH FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_trim($5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRIM '(' expr FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_trim($5,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | USER '(' ')' + { + $$= new (YYTHD->mem_root) Item_func_user(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->set_stmt_unsafe(); + Lex->safe_to_cache_query=0; + } + | YEAR_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_year($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +/* + Function calls using non reserved keywords, with special syntaxic forms. + Dedicated grammar rules are needed because of the syntax, + but also have the potential to cause incompatibilities with other + parts of the language. + MAINTAINER: + The only reasons a function should be added here are: + - for compatibility reasons with another SQL syntax (CURDATE), + - for typing reasons (GET_FORMAT) + Any other 'Syntaxic sugar' enhancements should be *STRONGLY* + discouraged. +*/ +function_call_nonkeyword: + ADDDATE_SYM '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($3, $5, + INTERVAL_DAY, 0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | ADDDATE_SYM '(' expr ',' INTERVAL_SYM expr interval ')' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($3, $6, $7, 0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CURDATE optional_braces + { + $$= new (YYTHD->mem_root) Item_func_curdate_local(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | CURTIME optional_braces + { + $$= new (YYTHD->mem_root) Item_func_curtime_local(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | CURTIME '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_curtime_local($3); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | DATE_ADD_INTERVAL '(' expr ',' INTERVAL_SYM expr interval ')' + %prec INTERVAL_SYM + { + $$= new (YYTHD->mem_root) Item_date_add_interval($3,$6,$7,0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | DATE_SUB_INTERVAL '(' expr ',' INTERVAL_SYM expr interval ')' + %prec INTERVAL_SYM + { + $$= new (YYTHD->mem_root) Item_date_add_interval($3,$6,$7,1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | EXTRACT_SYM '(' interval FROM expr ')' + { + $$=new (YYTHD->mem_root) Item_extract( $3, $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | GET_FORMAT '(' date_time_type ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_get_format($3, $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | NOW_SYM optional_braces + { + $$= new (YYTHD->mem_root) Item_func_now_local(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | NOW_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_now_local($3); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | POSITION_SYM '(' bit_expr IN_SYM expr ')' + { + $$ = new (YYTHD->mem_root) Item_func_locate($5,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUBDATE_SYM '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($3, $5, + INTERVAL_DAY, 1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUBDATE_SYM '(' expr ',' INTERVAL_SYM expr interval ')' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($3, $6, $7, 1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUBSTRING '(' expr ',' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_substr($3,$5,$7); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUBSTRING '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_substr($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUBSTRING '(' expr FROM expr FOR_SYM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_substr($3,$5,$7); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUBSTRING '(' expr FROM expr ')' + { + $$= new (YYTHD->mem_root) Item_func_substr($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SYSDATE optional_braces + { + if (global_system_variables.sysdate_is_now == 0) + $$= new (YYTHD->mem_root) Item_func_sysdate_local(); + else + $$= new (YYTHD->mem_root) Item_func_now_local(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | SYSDATE '(' expr ')' + { + if (global_system_variables.sysdate_is_now == 0) + $$= new (YYTHD->mem_root) Item_func_sysdate_local($3); + else + $$= new (YYTHD->mem_root) Item_func_now_local($3); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | TIMESTAMP_ADD '(' interval_time_stamp ',' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_date_add_interval($7,$5,$3,0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TIMESTAMP_DIFF '(' interval_time_stamp ',' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_timestamp_diff($5,$7,$3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | UTC_DATE_SYM optional_braces + { + $$= new (YYTHD->mem_root) Item_func_curdate_utc(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | UTC_TIME_SYM optional_braces + { + $$= new (YYTHD->mem_root) Item_func_curtime_utc(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | UTC_TIMESTAMP_SYM optional_braces + { + $$= new (YYTHD->mem_root) Item_func_now_utc(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + ; + +/* + Functions calls using a non reserved keyword, and using a regular syntax. + Because the non reserved keyword is used in another part of the grammar, + a dedicated rule is needed here. +*/ +function_call_conflict: + ASCII_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_ascii($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | CHARSET '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_charset($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | COALESCE '(' expr_list ')' + { + $$= new (YYTHD->mem_root) Item_func_coalesce(* $3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | COLLATION_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_collation($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | DATABASE '(' ')' + { + $$= new (YYTHD->mem_root) Item_func_database(); + if ($$ == NULL) + MYSQL_YYABORT; + Lex->safe_to_cache_query=0; + } + | IF '(' expr ',' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_if($3,$5,$7); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MICROSECOND_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_microsecond($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MOD_SYM '(' expr ',' expr ')' + { + $$ = new (YYTHD->mem_root) Item_func_mod($3, $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | OLD_PASSWORD '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_old_password($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | PASSWORD '(' expr ')' + { + THD *thd= YYTHD; + Item* i1; + if (thd->variables.old_passwords) + i1= new (thd->mem_root) Item_func_old_password($3); + else + i1= new (thd->mem_root) Item_func_password($3); + if (i1 == NULL) + MYSQL_YYABORT; + $$= i1; + } + | QUARTER_SYM '(' expr ')' + { + $$ = new (YYTHD->mem_root) Item_func_quarter($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | REPEAT_SYM '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_repeat($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | REPLACE '(' expr ',' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_replace($3,$5,$7); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRUNCATE_SYM '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_round($3,$5,1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | WEEK_SYM '(' expr ')' + { + THD *thd= YYTHD; + Item *i1= new (thd->mem_root) Item_int((char*) "0", + thd->variables.default_week_format, + 1); + if (i1 == NULL) + MYSQL_YYABORT; + $$= new (thd->mem_root) Item_func_week($3, i1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | WEEK_SYM '(' expr ',' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_week($3,$5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | geometry_function + { +#ifdef HAVE_SPATIAL + $$= $1; + /* $1 may be NULL, GEOM_NEW not tested for out of memory */ + if ($$ == NULL) + MYSQL_YYABORT; +#else + my_error(ER_FEATURE_DISABLED, MYF(0), + sym_group_geom.name, sym_group_geom.needed_define); + MYSQL_YYABORT; +#endif + } + ; + +geometry_function: + CONTAINS_SYM '(' expr ',' expr ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_rel($3, $5, + Item_func::SP_CONTAINS_FUNC)); + } + | GEOMETRYCOLLECTION '(' expr_list ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_collection(* $3, + Geometry::wkb_geometrycollection, + Geometry::wkb_point)); + } + | LINESTRING '(' expr_list ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_collection(* $3, + Geometry::wkb_linestring, + Geometry::wkb_point)); + } + | MULTILINESTRING '(' expr_list ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_collection(* $3, + Geometry::wkb_multilinestring, + Geometry::wkb_linestring)); + } + | MULTIPOINT '(' expr_list ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_collection(* $3, + Geometry::wkb_multipoint, + Geometry::wkb_point)); + } + | MULTIPOLYGON '(' expr_list ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_collection(* $3, + Geometry::wkb_multipolygon, + Geometry::wkb_polygon)); + } + | POINT_SYM '(' expr ',' expr ')' + { + $$= GEOM_NEW(YYTHD, Item_func_point($3,$5)); + } + | POLYGON '(' expr_list ')' + { + $$= GEOM_NEW(YYTHD, + Item_func_spatial_collection(* $3, + Geometry::wkb_polygon, + Geometry::wkb_linestring)); + } + ; + +/* + Regular function calls. + The function name is *not* a token, and therefore is guaranteed to not + introduce side effects to the language in general. + MAINTAINER: + All the new functions implemented for new features should fit into + this category. The place to implement the function itself is + in sql/item_create.cc +*/ +function_call_generic: + IDENT_sys '(' + { +#ifdef HAVE_DLOPEN + udf_func *udf= 0; + LEX *lex= Lex; + if (using_udf_functions && + (udf= find_udf($1.str, $1.length)) && + udf->type == UDFTYPE_AGGREGATE) + { + if (lex->current_select->inc_in_sum_expr()) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + } + /* Temporary placing the result of find_udf in $3 */ + $$= udf; +#endif + } + opt_udf_expr_list ')' + { + THD *thd= YYTHD; + Create_func *builder; + Item *item= NULL; + + /* + Implementation note: + names are resolved with the following order: + - MySQL native functions, + - User Defined Functions, + - Stored Functions (assuming the current database) + + This will be revised with WL#2128 (SQL PATH) + */ + builder= find_native_function_builder(thd, $1); + if (builder) + { + item= builder->create(thd, $1, $4); + } + else + { +#ifdef HAVE_DLOPEN + /* Retrieving the result of find_udf */ + udf_func *udf= $3; + + if (udf) + { + if (udf->type == UDFTYPE_AGGREGATE) + { + Select->in_sum_expr--; + } + + item= Create_udf_func::s_singleton.create(thd, udf, $4); + } + else +#endif + { + builder= find_qualified_function_builder(thd); + DBUG_ASSERT(builder); + item= builder->create(thd, $1, $4); + } + } + + if (! ($$= item)) + { + MYSQL_YYABORT; + } + } + | ident '.' ident '(' opt_expr_list ')' + { + THD *thd= YYTHD; + Create_qfunc *builder; + Item *item= NULL; + + /* + The following in practice calls: + Create_sp_func::create() + and builds a stored function. + + However, it's important to maintain the interface between the + parser and the implementation in item_create.cc clean, + since this will change with WL#2128 (SQL PATH): + - INFORMATION_SCHEMA.version() is the SQL 99 syntax for the native + function version(), + - MySQL.version() is the SQL 2003 syntax for the native function + version() (a vendor can specify any schema). + */ + + builder= find_qualified_function_builder(thd); + DBUG_ASSERT(builder); + item= builder->create(thd, $1, $3, true, $5); + + if (! ($$= item)) + { + MYSQL_YYABORT; + } + } + ; + +fulltext_options: + opt_natural_language_mode opt_query_expansion + { $$= $1 | $2; } + | IN_SYM BOOLEAN_SYM MODE_SYM + { $$= FT_BOOL; } + ; + +opt_natural_language_mode: + /* nothing */ { $$= FT_NL; } + | IN_SYM NATURAL LANGUAGE_SYM MODE_SYM { $$= FT_NL; } + ; + +opt_query_expansion: + /* nothing */ { $$= 0; } + | WITH QUERY_SYM EXPANSION_SYM { $$= FT_EXPAND; } + ; + +opt_udf_expr_list: + /* empty */ { $$= NULL; } + | udf_expr_list { $$= $1; } + ; + +udf_expr_list: + udf_expr + { + $$= new (YYTHD->mem_root) List; + if ($$ == NULL) + MYSQL_YYABORT; + $$->push_back($1); + } + | udf_expr_list ',' udf_expr + { + $1->push_back($3); + $$= $1; + } + ; + +udf_expr: + remember_name expr remember_end select_alias + { + /* + Use Item::name as a storage for the attribute value of user + defined function argument. It is safe to use Item::name + because the syntax will not allow having an explicit name here. + See WL#1017 re. udf attributes. + */ + if ($4.str) + { + $2->is_autogenerated_name= FALSE; + $2->set_name($4.str, $4.length, system_charset_info); + } + else + $2->set_name($1, (uint) ($3 - $1), YYTHD->charset()); + $$= $2; + } + ; + +sum_expr: + AVG_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_avg($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | AVG_SYM '(' DISTINCT in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_avg_distinct($4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | BIT_AND '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_and($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | BIT_OR '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_or($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | BIT_XOR '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_xor($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | COUNT_SYM '(' opt_all '*' ')' + { + Item *item= new (YYTHD->mem_root) Item_int((int32) 0L,1); + if (item == NULL) + MYSQL_YYABORT; + $$= new (YYTHD->mem_root) Item_sum_count(item); + if ($$ == NULL) + MYSQL_YYABORT; + } + | COUNT_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_count($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | COUNT_SYM '(' DISTINCT + { Select->in_sum_expr++; } + expr_list + { Select->in_sum_expr--; } + ')' + { + $$= new (YYTHD->mem_root) Item_sum_count_distinct(* $5); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MIN_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_min($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + /* + According to ANSI SQL, DISTINCT is allowed and has + no sense inside MIN and MAX grouping functions; so MIN|MAX(DISTINCT ...) + is processed like an ordinary MIN | MAX() + */ + | MIN_SYM '(' DISTINCT in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_min($4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MAX_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_max($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | MAX_SYM '(' DISTINCT in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_max($4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | STD_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_std($3, 0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | VARIANCE_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_variance($3, 0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | STDDEV_SAMP_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_std($3, 1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | VAR_SAMP_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_variance($3, 1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUM_SYM '(' in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_sum($3); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SUM_SYM '(' DISTINCT in_sum_expr ')' + { + $$= new (YYTHD->mem_root) Item_sum_sum_distinct($4); + if ($$ == NULL) + MYSQL_YYABORT; + } + | GROUP_CONCAT_SYM '(' opt_distinct + { Select->in_sum_expr++; } + expr_list opt_gorder_clause + opt_gconcat_separator + ')' + { + SELECT_LEX *sel= Select; + sel->in_sum_expr--; + $$= new (YYTHD->mem_root) + Item_func_group_concat(Lex->current_context(), $3, $5, + sel->gorder_list, $7); + if ($$ == NULL) + MYSQL_YYABORT; + $5->empty(); + } + ; + +variable: + '@' + { + if (! Lex->parsing_options.allows_variable) + { + my_error(ER_VIEW_SELECT_VARIABLE, MYF(0)); + MYSQL_YYABORT; + } + } + variable_aux + { + $$= $3; + } + ; + +variable_aux: + ident_or_text SET_VAR expr + { + Item_func_set_user_var *item; + $$= item= new (YYTHD->mem_root) Item_func_set_user_var($1, $3); + if ($$ == NULL) + MYSQL_YYABORT; + LEX *lex= Lex; + lex->uncacheable(UNCACHEABLE_RAND); + lex->set_var_list.push_back(item); + } + | ident_or_text + { + $$= new (YYTHD->mem_root) Item_func_get_user_var($1); + if ($$ == NULL) + MYSQL_YYABORT; + LEX *lex= Lex; + lex->uncacheable(UNCACHEABLE_RAND); + } + | '@' opt_var_ident_type ident_or_text opt_component + { + /* disallow "SELECT @@global.global.variable" */ + if ($3.str && $4.str && check_reserved_words(&$3)) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if (!($$= get_system_var(YYTHD, $2, $3, $4))) + MYSQL_YYABORT; + if (!((Item_func_get_system_var*) $$)->is_written_to_binlog()) + Lex->set_stmt_unsafe(); + } + ; + +opt_distinct: + /* empty */ { $$ = 0; } + | DISTINCT { $$ = 1; } + ; + +opt_gconcat_separator: + /* empty */ + { + $$= new (YYTHD->mem_root) String(",", 1, &my_charset_latin1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | SEPARATOR_SYM text_string { $$ = $2; } + ; + +opt_gorder_clause: + /* empty */ + { + Select->gorder_list = NULL; + } + | order_clause + { + SELECT_LEX *select= Select; + select->gorder_list= + (SQL_LIST*) sql_memdup((char*) &select->order_list, + sizeof(st_sql_list)); + if (select->gorder_list == NULL) + MYSQL_YYABORT; + select->order_list.empty(); + } + ; + +in_sum_expr: + opt_all + { + LEX *lex= Lex; + if (lex->current_select->inc_in_sum_expr()) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + } + expr + { + Select->in_sum_expr--; + $$= $3; + } + ; + +cast_type: + BINARY opt_field_length + { $$=ITEM_CAST_CHAR; Lex->charset= &my_charset_bin; Lex->dec= 0; } + | CHAR_SYM opt_field_length opt_binary + { $$=ITEM_CAST_CHAR; Lex->dec= 0; } + | NCHAR_SYM opt_field_length + { $$=ITEM_CAST_CHAR; Lex->charset= national_charset_info; Lex->dec=0; } + | SIGNED_SYM + { $$=ITEM_CAST_SIGNED_INT; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | SIGNED_SYM INT_SYM + { $$=ITEM_CAST_SIGNED_INT; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | UNSIGNED + { $$=ITEM_CAST_UNSIGNED_INT; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | UNSIGNED INT_SYM + { $$=ITEM_CAST_UNSIGNED_INT; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | DATE_SYM + { $$=ITEM_CAST_DATE; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | TIME_SYM + { $$=ITEM_CAST_TIME; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | DATETIME + { $$=ITEM_CAST_DATETIME; Lex->charset= NULL; Lex->dec=Lex->length= (char*)0; } + | DECIMAL_SYM float_options + { $$=ITEM_CAST_DECIMAL; Lex->charset= NULL; } + ; + +opt_expr_list: + /* empty */ { $$= NULL; } + | expr_list { $$= $1;} + ; + +expr_list: + expr + { + $$= new (YYTHD->mem_root) List; + if ($$ == NULL) + MYSQL_YYABORT; + $$->push_back($1); + } + | expr_list ',' expr + { + $1->push_back($3); + $$= $1; + } + ; + +ident_list_arg: + ident_list { $$= $1; } + | '(' ident_list ')' { $$= $2; } + ; + +ident_list: + simple_ident + { + $$= new (YYTHD->mem_root) List; + if ($$ == NULL) + MYSQL_YYABORT; + $$->push_back($1); + } + | ident_list ',' simple_ident + { + $1->push_back($3); + $$= $1; + } + ; + +opt_expr: + /* empty */ { $$= NULL; } + | expr { $$= $1; } + ; + +opt_else: + /* empty */ { $$= NULL; } + | ELSE expr { $$= $2; } + ; + +when_list: + WHEN_SYM expr THEN_SYM expr + { + $$= new List; + if ($$ == NULL) + MYSQL_YYABORT; + $$->push_back($2); + $$->push_back($4); + } + | when_list WHEN_SYM expr THEN_SYM expr + { + $1->push_back($3); + $1->push_back($5); + $$= $1; + } + ; + +/* Warning - may return NULL in case of incomplete SELECT */ +table_ref: + table_factor { $$=$1; } + | join_table + { + LEX *lex= Lex; + if (!($$= lex->current_select->nest_last_join(lex->thd))) + MYSQL_YYABORT; + } + ; + +join_table_list: + derived_table_list { MYSQL_YYABORT_UNLESS($$=$1); } + ; + +/* + The ODBC escape syntax for Outer Join is: '{' OJ join_table '}' + The parser does not define OJ as a token, any ident is accepted + instead in $2 (ident). Also, all productions from table_ref can + be escaped, not only join_table. Both syntax extensions are safe + and are ignored. +*/ +esc_table_ref: + table_ref { $$=$1; } + | '{' ident table_ref '}' { $$=$3; } + ; + +/* Warning - may return NULL in case of incomplete SELECT */ +derived_table_list: + esc_table_ref { $$=$1; } + | derived_table_list ',' esc_table_ref + { + MYSQL_YYABORT_UNLESS($1 && ($$=$3)); + } + ; + +/* + Notice that JOIN is a left-associative operation, and it must be parsed + as such, that is, the parser must process first the left join operand + then the right one. Such order of processing ensures that the parser + produces correct join trees which is essential for semantic analysis + and subsequent optimization phases. +*/ +join_table: + /* INNER JOIN variants */ + /* + Use %prec to evaluate production 'table_ref' before 'normal_join' + so that [INNER | CROSS] JOIN is properly nested as other + left-associative joins. + */ + table_ref normal_join table_ref %prec TABLE_REF_PRIORITY + { MYSQL_YYABORT_UNLESS($1 && ($$=$3)); } + | table_ref STRAIGHT_JOIN table_factor + { MYSQL_YYABORT_UNLESS($1 && ($$=$3)); $3->straight=1; } + | table_ref normal_join table_ref + ON + { + MYSQL_YYABORT_UNLESS($1 && $3); + /* Change the current name resolution context to a local context. */ + if (push_new_name_resolution_context(YYTHD, $1, $3)) + MYSQL_YYABORT; + Select->parsing_place= IN_ON; + } + expr + { + add_join_on($3,$6); + Lex->pop_context(); + Select->parsing_place= NO_MATTER; + } + | table_ref STRAIGHT_JOIN table_factor + ON + { + MYSQL_YYABORT_UNLESS($1 && $3); + /* Change the current name resolution context to a local context. */ + if (push_new_name_resolution_context(YYTHD, $1, $3)) + MYSQL_YYABORT; + Select->parsing_place= IN_ON; + } + expr + { + $3->straight=1; + add_join_on($3,$6); + Lex->pop_context(); + Select->parsing_place= NO_MATTER; + } + | table_ref normal_join table_ref + USING + { + MYSQL_YYABORT_UNLESS($1 && $3); + } + '(' using_list ')' + { add_join_natural($1,$3,$7,Select); $$=$3; } + | table_ref NATURAL JOIN_SYM table_factor + { + MYSQL_YYABORT_UNLESS($1 && ($$=$4)); + add_join_natural($1,$4,NULL,Select); + } + + /* LEFT JOIN variants */ + | table_ref LEFT opt_outer JOIN_SYM table_ref + ON + { + MYSQL_YYABORT_UNLESS($1 && $5); + /* Change the current name resolution context to a local context. */ + if (push_new_name_resolution_context(YYTHD, $1, $5)) + MYSQL_YYABORT; + Select->parsing_place= IN_ON; + } + expr + { + add_join_on($5,$8); + Lex->pop_context(); + $5->outer_join|=JOIN_TYPE_LEFT; + $$=$5; + Select->parsing_place= NO_MATTER; + } + | table_ref LEFT opt_outer JOIN_SYM table_factor + { + MYSQL_YYABORT_UNLESS($1 && $5); + } + USING '(' using_list ')' + { + add_join_natural($1,$5,$9,Select); + $5->outer_join|=JOIN_TYPE_LEFT; + $$=$5; + } + | table_ref NATURAL LEFT opt_outer JOIN_SYM table_factor + { + MYSQL_YYABORT_UNLESS($1 && $6); + add_join_natural($1,$6,NULL,Select); + $6->outer_join|=JOIN_TYPE_LEFT; + $$=$6; + } + + /* RIGHT JOIN variants */ + | table_ref RIGHT opt_outer JOIN_SYM table_ref + ON + { + MYSQL_YYABORT_UNLESS($1 && $5); + /* Change the current name resolution context to a local context. */ + if (push_new_name_resolution_context(YYTHD, $1, $5)) + MYSQL_YYABORT; + Select->parsing_place= IN_ON; + } + expr + { + LEX *lex= Lex; + if (!($$= lex->current_select->convert_right_join())) + MYSQL_YYABORT; + add_join_on($$, $8); + Lex->pop_context(); + Select->parsing_place= NO_MATTER; + } + | table_ref RIGHT opt_outer JOIN_SYM table_factor + { + MYSQL_YYABORT_UNLESS($1 && $5); + } + USING '(' using_list ')' + { + LEX *lex= Lex; + if (!($$= lex->current_select->convert_right_join())) + MYSQL_YYABORT; + add_join_natural($$,$5,$9,Select); + } + | table_ref NATURAL RIGHT opt_outer JOIN_SYM table_factor + { + MYSQL_YYABORT_UNLESS($1 && $6); + add_join_natural($6,$1,NULL,Select); + LEX *lex= Lex; + if (!($$= lex->current_select->convert_right_join())) + MYSQL_YYABORT; + } + ; + +normal_join: + JOIN_SYM {} + | INNER_SYM JOIN_SYM {} + | CROSS JOIN_SYM {} + ; + +/* Warning - may return NULL in case of incomplete SELECT */ +table_factor: + { + SELECT_LEX *sel= Select; + sel->table_join_options= 0; + } + table_ident opt_table_alias opt_key_definition + { + if (!($$= Select->add_table_to_list(YYTHD, $2, $3, + Select->get_table_join_options(), + Lex->lock_option, + Select->pop_index_hints()))) + MYSQL_YYABORT; + Select->add_joined_table($$); + } + | select_derived_init get_select_lex select_derived2 + { + LEX *lex= Lex; + SELECT_LEX *sel= lex->current_select; + if ($1) + { + if (sel->set_braces(1)) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + /* select in braces, can't contain global parameters */ + if (sel->master_unit()->fake_select_lex) + sel->master_unit()->global_parameters= + sel->master_unit()->fake_select_lex; + } + if ($2->init_nested_join(lex->thd)) + MYSQL_YYABORT; + $$= 0; + /* incomplete derived tables return NULL, we must be + nested in select_derived rule to be here. */ + } + | '(' get_select_lex select_derived union_opt ')' opt_table_alias + { + /* Use $2 instead of Lex->current_select as derived table will + alter value of Lex->current_select. */ + + if (!($3 || $6) && $2->embedding && + !$2->embedding->nested_join->join_list.elements) + { + /* we have a derived table ($3 == NULL) but no alias, + Since we are nested in further parentheses so we + can pass NULL to the outer level parentheses + Permits parsing of "((((select ...))) as xyz)" */ + $$= 0; + } + else if (!$3) + { + /* Handle case of derived table, alias may be NULL if there + are no outer parentheses, add_table_to_list() will throw + error in this case */ + LEX *lex=Lex; + SELECT_LEX *sel= lex->current_select; + SELECT_LEX_UNIT *unit= sel->master_unit(); + lex->current_select= sel= unit->outer_select(); + Table_ident *ti= new Table_ident(unit); + if (ti == NULL) + MYSQL_YYABORT; + if (!($$= sel->add_table_to_list(lex->thd, + ti, $6, 0, + TL_READ))) + + MYSQL_YYABORT; + sel->add_joined_table($$); + lex->pop_context(); + lex->nest_level--; + } + else if ($4 || $6) + { + /* simple nested joins cannot have aliases or unions */ + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + else + { + /* nested join: FROM (t1 JOIN t2 ...), + nest_level is the same as in the outer query */ + $$= $3; + } + } + ; + +/* handle contents of parentheses in join expression */ +select_derived: + get_select_lex + { + LEX *lex= Lex; + if ($1->init_nested_join(lex->thd)) + MYSQL_YYABORT; + } + derived_table_list + { + LEX *lex= Lex; + /* for normal joins, $3 != NULL and end_nested_join() != NULL, + for derived tables, both must equal NULL */ + + if (!($$= $1->end_nested_join(lex->thd)) && $3) + MYSQL_YYABORT; + if (!$3 && $$) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + } + ; + +select_derived2: + { + LEX *lex= Lex; + lex->derived_tables|= DERIVED_SUBQUERY; + if (!lex->expr_allows_subselect || + lex->sql_command == (int)SQLCOM_PURGE) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if (lex->current_select->linkage == GLOBAL_OPTIONS_TYPE || + mysql_new_select(lex, 1)) + MYSQL_YYABORT; + mysql_init_select(lex); + lex->current_select->linkage= DERIVED_TABLE_TYPE; + lex->current_select->parsing_place= SELECT_LIST; + } + select_options select_item_list + { + Select->parsing_place= NO_MATTER; + } + opt_select_from + ; + +get_select_lex: + /* Empty */ { $$= Select; } + ; + +select_derived_init: + SELECT_SYM + { + LEX *lex= Lex; + + if (! lex->parsing_options.allows_derived) + { + my_error(ER_VIEW_SELECT_DERIVED, MYF(0)); + MYSQL_YYABORT; + } + + SELECT_LEX *sel= lex->current_select; + TABLE_LIST *embedding; + if (!sel->embedding || sel->end_nested_join(lex->thd)) + { + /* we are not in parentheses */ + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + embedding= Select->embedding; + $$= embedding && + !embedding->nested_join->join_list.elements; + /* return true if we are deeply nested */ + } + ; + +opt_outer: + /* empty */ {} + | OUTER {} + ; + +index_hint_clause: + /* empty */ + { + $$= global_system_variables.old_mode ? + INDEX_HINT_MASK_JOIN : INDEX_HINT_MASK_ALL; + } + | FOR_SYM JOIN_SYM { $$= INDEX_HINT_MASK_JOIN; } + | FOR_SYM ORDER_SYM BY { $$= INDEX_HINT_MASK_ORDER; } + | FOR_SYM GROUP_SYM BY { $$= INDEX_HINT_MASK_GROUP; } + ; + +index_hint_type: + FORCE_SYM { $$= INDEX_HINT_FORCE; } + | IGNORE_SYM { $$= INDEX_HINT_IGNORE; } + ; + +index_hint_definition: + index_hint_type key_or_index index_hint_clause + { + Select->set_index_hint_type($1, $3); + } + '(' key_usage_list ')' + | USE_SYM key_or_index index_hint_clause + { + Select->set_index_hint_type(INDEX_HINT_USE, $3); + } + '(' opt_key_usage_list ')' + ; + +index_hints_list: + index_hint_definition + | index_hints_list index_hint_definition + ; + +opt_index_hints_list: + /* empty */ + | { Select->alloc_index_hints(YYTHD); } index_hints_list + ; + +opt_key_definition: + { Select->clear_index_hints(); } + opt_index_hints_list + ; + +opt_key_usage_list: + /* empty */ { Select->add_index_hint(YYTHD, NULL, 0); } + | key_usage_list {} + ; + +key_usage_element: + ident + { Select->add_index_hint(YYTHD, $1.str, $1.length); } + | PRIMARY_SYM + { Select->add_index_hint(YYTHD, (char *)"PRIMARY", 7); } + ; + +key_usage_list: + key_usage_element + | key_usage_list ',' key_usage_element + ; + +using_list: + ident + { + if (!($$= new List)) + MYSQL_YYABORT; + String *s= new (YYTHD->mem_root) String((const char *) $1.str, + $1.length, + system_charset_info); + if (s == NULL) + MYSQL_YYABORT; + $$->push_back(s); + } + | using_list ',' ident + { + String *s= new (YYTHD->mem_root) String((const char *) $3.str, + $3.length, + system_charset_info); + if (s == NULL) + MYSQL_YYABORT; + $1->push_back(s); + $$= $1; + } + ; + +interval: + interval_time_st {} + | DAY_HOUR_SYM { $$=INTERVAL_DAY_HOUR; } + | DAY_MICROSECOND_SYM { $$=INTERVAL_DAY_MICROSECOND; } + | DAY_MINUTE_SYM { $$=INTERVAL_DAY_MINUTE; } + | DAY_SECOND_SYM { $$=INTERVAL_DAY_SECOND; } + | HOUR_MICROSECOND_SYM { $$=INTERVAL_HOUR_MICROSECOND; } + | HOUR_MINUTE_SYM { $$=INTERVAL_HOUR_MINUTE; } + | HOUR_SECOND_SYM { $$=INTERVAL_HOUR_SECOND; } + | MINUTE_MICROSECOND_SYM { $$=INTERVAL_MINUTE_MICROSECOND; } + | MINUTE_SECOND_SYM { $$=INTERVAL_MINUTE_SECOND; } + | SECOND_MICROSECOND_SYM { $$=INTERVAL_SECOND_MICROSECOND; } + | YEAR_MONTH_SYM { $$=INTERVAL_YEAR_MONTH; } + ; + +interval_time_stamp: + interval_time_st {} + | FRAC_SECOND_SYM { + $$=INTERVAL_MICROSECOND; + /* + FRAC_SECOND was mistakenly implemented with + a wrong resolution. According to the ODBC + standard it should be nanoseconds, not + microseconds. Changing it to nanoseconds + in MySQL would mean making TIMESTAMPDIFF + and TIMESTAMPADD to return DECIMAL, since + the return value would be too big for BIGINT + Hence we just deprecate the incorrect + implementation without changing its + resolution. + */ + WARN_DEPRECATED(yythd, "6.2", "FRAC_SECOND", "MICROSECOND"); + } + ; + +interval_time_st: + DAY_SYM { $$=INTERVAL_DAY; } + | WEEK_SYM { $$=INTERVAL_WEEK; } + | HOUR_SYM { $$=INTERVAL_HOUR; } + | MINUTE_SYM { $$=INTERVAL_MINUTE; } + | MONTH_SYM { $$=INTERVAL_MONTH; } + | QUARTER_SYM { $$=INTERVAL_QUARTER; } + | SECOND_SYM { $$=INTERVAL_SECOND; } + | MICROSECOND_SYM { $$=INTERVAL_MICROSECOND; } + | YEAR_SYM { $$=INTERVAL_YEAR; } + ; + +date_time_type: + DATE_SYM {$$=MYSQL_TIMESTAMP_DATE;} + | TIME_SYM {$$=MYSQL_TIMESTAMP_TIME;} + | DATETIME {$$=MYSQL_TIMESTAMP_DATETIME;} + | TIMESTAMP {$$=MYSQL_TIMESTAMP_DATETIME;} + ; + +table_alias: + /* empty */ + | AS + | EQ + ; + +opt_table_alias: + /* empty */ { $$=0; } + | table_alias ident + { + $$= (LEX_STRING*) sql_memdup(&$2,sizeof(LEX_STRING)); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +opt_all: + /* empty */ + | ALL + ; + +where_clause: + /* empty */ { Select->where= 0; } + | WHERE + { + Select->parsing_place= IN_WHERE; + } + expr + { + SELECT_LEX *select= Select; + select->where= $3; + select->parsing_place= NO_MATTER; + if ($3) + $3->top_level_item(); + } + ; + +having_clause: + /* empty */ + | HAVING + { + Select->parsing_place= IN_HAVING; + } + expr + { + SELECT_LEX *sel= Select; + sel->having= $3; + sel->parsing_place= NO_MATTER; + if ($3) + $3->top_level_item(); + } + ; + +opt_escape: + ESCAPE_SYM simple_expr + { + Lex->escape_used= TRUE; + $$= $2; + } + | /* empty */ + { + THD *thd= YYTHD; + Lex->escape_used= FALSE; + $$= ((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) ? + new (thd->mem_root) Item_string("", 0, &my_charset_latin1) : + new (thd->mem_root) Item_string("\\", 1, &my_charset_latin1)); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +/* + group by statement in select +*/ + +group_clause: + /* empty */ + | GROUP_SYM BY group_list olap_opt + ; + +group_list: + group_list ',' order_ident order_dir + { if (add_group_to_list(YYTHD, $3,(bool) $4)) MYSQL_YYABORT; } + | order_ident order_dir + { if (add_group_to_list(YYTHD, $1,(bool) $2)) MYSQL_YYABORT; } + ; + +olap_opt: + /* empty */ {} + | WITH CUBE_SYM + { + LEX *lex=Lex; + if (lex->current_select->linkage == GLOBAL_OPTIONS_TYPE) + { + my_error(ER_WRONG_USAGE, MYF(0), "WITH CUBE", + "global union parameters"); + MYSQL_YYABORT; + } + lex->current_select->olap= CUBE_TYPE; + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "CUBE"); + MYSQL_YYABORT; /* To be deleted in 5.1 */ + } + | WITH ROLLUP_SYM + { + LEX *lex= Lex; + if (lex->current_select->linkage == GLOBAL_OPTIONS_TYPE) + { + my_error(ER_WRONG_USAGE, MYF(0), "WITH ROLLUP", + "global union parameters"); + MYSQL_YYABORT; + } + lex->current_select->olap= ROLLUP_TYPE; + } + ; + +/* + Order by statement in ALTER TABLE +*/ + +alter_order_clause: + ORDER_SYM BY alter_order_list + ; + +alter_order_list: + alter_order_list ',' alter_order_item + | alter_order_item + ; + +alter_order_item: + simple_ident_nospvar order_dir + { + THD *thd= YYTHD; + bool ascending= ($2 == 1) ? true : false; + if (add_order_to_list(thd, $1, ascending)) + MYSQL_YYABORT; + } + ; + +/* + Order by statement in select +*/ + +opt_order_clause: + /* empty */ + | order_clause + ; + +order_clause: + ORDER_SYM BY + { + LEX *lex=Lex; + SELECT_LEX *sel= lex->current_select; + SELECT_LEX_UNIT *unit= sel-> master_unit(); + if (sel->linkage != GLOBAL_OPTIONS_TYPE && + sel->olap != UNSPECIFIED_OLAP_TYPE && + (sel->linkage != UNION_TYPE || sel->braces)) + { + my_error(ER_WRONG_USAGE, MYF(0), + "CUBE/ROLLUP", "ORDER BY"); + MYSQL_YYABORT; + } + if (lex->sql_command != SQLCOM_ALTER_TABLE && !unit->fake_select_lex) + { + /* + A query of the of the form (SELECT ...) ORDER BY order_list is + executed in the same way as the query + SELECT ... ORDER BY order_list + unless the SELECT construct contains ORDER BY or LIMIT clauses. + Otherwise we create a fake SELECT_LEX if it has not been created + yet. + */ + SELECT_LEX *first_sl= unit->first_select(); + if (!unit->is_union() && + (first_sl->order_list.elements || + first_sl->select_limit) && + unit->add_fake_select_lex(lex->thd)) + MYSQL_YYABORT; + } + } + order_list + ; + +order_list: + order_list ',' order_ident order_dir + { if (add_order_to_list(YYTHD, $3,(bool) $4)) MYSQL_YYABORT; } + | order_ident order_dir + { if (add_order_to_list(YYTHD, $1,(bool) $2)) MYSQL_YYABORT; } + ; + +order_dir: + /* empty */ { $$ = 1; } + | ASC { $$ =1; } + | DESC { $$ =0; } + ; + +opt_limit_clause_init: + /* empty */ + { + LEX *lex= Lex; + SELECT_LEX *sel= lex->current_select; + sel->offset_limit= 0; + sel->select_limit= 0; + } + | limit_clause {} + ; + +opt_limit_clause: + /* empty */ {} + | limit_clause {} + ; + +limit_clause: + LIMIT limit_options {} + ; + +limit_options: + limit_option + { + SELECT_LEX *sel= Select; + sel->select_limit= $1; + sel->offset_limit= 0; + sel->explicit_limit= 1; + } + | limit_option ',' limit_option + { + SELECT_LEX *sel= Select; + sel->select_limit= $3; + sel->offset_limit= $1; + sel->explicit_limit= 1; + } + | limit_option OFFSET_SYM limit_option + { + SELECT_LEX *sel= Select; + sel->select_limit= $1; + sel->offset_limit= $3; + sel->explicit_limit= 1; + } + ; + +limit_option: + param_marker + { + ((Item_param *) $1)->limit_clause_param= TRUE; + } + | ULONGLONG_NUM + { + $$= new (YYTHD->mem_root) Item_uint($1.str, $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | LONG_NUM + { + $$= new (YYTHD->mem_root) Item_uint($1.str, $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | NUM + { + $$= new (YYTHD->mem_root) Item_uint($1.str, $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +delete_limit_clause: + /* empty */ + { + LEX *lex=Lex; + lex->current_select->select_limit= 0; + } + | LIMIT limit_option + { + SELECT_LEX *sel= Select; + sel->select_limit= $2; + sel->explicit_limit= 1; + } + ; + +ulong_num: + NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | HEX_NUM { $$= (ulong) strtol($1.str, (char**) 0, 16); } + | LONG_NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | ULONGLONG_NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | DECIMAL_NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | FLOAT_NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + ; + +real_ulong_num: + NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | HEX_NUM { $$= (ulong) strtol($1.str, (char**) 0, 16); } + | LONG_NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | ULONGLONG_NUM { int error; $$= (ulong) my_strtoll10($1.str, (char**) 0, &error); } + | dec_num_error { MYSQL_YYABORT; } + ; + +ulonglong_num: + NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | ULONGLONG_NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | LONG_NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | DECIMAL_NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | FLOAT_NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + ; + +real_ulonglong_num: + NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | ULONGLONG_NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | LONG_NUM { int error; $$= (ulonglong) my_strtoll10($1.str, (char**) 0, &error); } + | dec_num_error { MYSQL_YYABORT; } + ; + +dec_num_error: + dec_num + { my_parse_error(ER(ER_ONLY_INTEGERS_ALLOWED)); } + ; + +dec_num: + DECIMAL_NUM + | FLOAT_NUM + ; + +procedure_clause: + /* empty */ + | PROCEDURE ident /* Procedure name */ + { + LEX *lex=Lex; + + if (! lex->parsing_options.allows_select_procedure) + { + my_error(ER_VIEW_SELECT_CLAUSE, MYF(0), "PROCEDURE"); + MYSQL_YYABORT; + } + + if (&lex->select_lex != lex->current_select || + lex->select_lex.get_table_list()->derived) + { + my_error(ER_WRONG_USAGE, MYF(0), "PROCEDURE", "subquery"); + MYSQL_YYABORT; + } + lex->proc_list.elements=0; + lex->proc_list.first=0; + lex->proc_list.next= (uchar**) &lex->proc_list.first; + Item_field *item= new (YYTHD->mem_root) + Item_field(&lex->current_select->context, + NULL, NULL, $2.str); + if (item == NULL) + MYSQL_YYABORT; + if (add_proc_to_list(lex->thd, item)) + MYSQL_YYABORT; + Lex->uncacheable(UNCACHEABLE_SIDEEFFECT); + } + '(' procedure_list ')' + ; + +procedure_list: + /* empty */ {} + | procedure_list2 {} + ; + +procedure_list2: + procedure_list2 ',' procedure_item + | procedure_item + ; + +procedure_item: + remember_name expr remember_end + { + THD *thd= YYTHD; + + if (add_proc_to_list(thd, $2)) + MYSQL_YYABORT; + if (!$2->name) + $2->set_name($1, (uint) ($3 - $1), thd->charset()); + } + ; + +select_var_list_init: + { + LEX *lex=Lex; + if (!lex->describe && + (!(lex->result= new select_dumpvar(lex->nest_level)))) + MYSQL_YYABORT; + } + select_var_list + {} + ; + +select_var_list: + select_var_list ',' select_var_ident + | select_var_ident {} + ; + +select_var_ident: + '@' ident_or_text + { + LEX *lex=Lex; + if (lex->result) + { + my_var *var= new my_var($2,0,0,(enum_field_types)0); + if (var == NULL) + MYSQL_YYABORT; + ((select_dumpvar *)lex->result)->var_list.push_back(var); + } + else + { + /* + The parser won't create select_result instance only + if it's an EXPLAIN. + */ + DBUG_ASSERT(lex->describe); + } + } + | ident_or_text + { + LEX *lex=Lex; + sp_variable_t *t; + + if (!lex->spcont || !(t=lex->spcont->find_variable(&$1))) + { + my_error(ER_SP_UNDECLARED_VAR, MYF(0), $1.str); + MYSQL_YYABORT; + } + if (lex->result) + { + my_var *var= new my_var($1,1,t->offset,t->type); + if (var == NULL) + MYSQL_YYABORT; + ((select_dumpvar *)lex->result)->var_list.push_back(var); +#ifndef DBUG_OFF + var->sp= lex->sphead; +#endif + } + else + { + /* + The parser won't create select_result instance only + if it's an EXPLAIN. + */ + DBUG_ASSERT(lex->describe); + } + } + ; + +into: + INTO + { + if (! Lex->parsing_options.allows_select_into) + { + my_error(ER_VIEW_SELECT_CLAUSE, MYF(0), "INTO"); + MYSQL_YYABORT; + } + } + into_destination + ; + +into_destination: + OUTFILE TEXT_STRING_filesystem + { + LEX *lex= Lex; + lex->uncacheable(UNCACHEABLE_SIDEEFFECT); + if (!(lex->exchange= new sql_exchange($2.str, 0)) || + !(lex->result= new select_export(lex->exchange, lex->nest_level))) + MYSQL_YYABORT; + } + opt_load_data_charset + { Lex->exchange->cs= $4; } + opt_field_term opt_line_term + | DUMPFILE TEXT_STRING_filesystem + { + LEX *lex=Lex; + if (!lex->describe) + { + lex->uncacheable(UNCACHEABLE_SIDEEFFECT); + if (!(lex->exchange= new sql_exchange($2.str,1))) + MYSQL_YYABORT; + if (!(lex->result= new select_dump(lex->exchange, lex->nest_level))) + MYSQL_YYABORT; + } + } + | select_var_list_init + { + Lex->uncacheable(UNCACHEABLE_SIDEEFFECT); + } + ; + +/* + DO statement +*/ + +do: + DO_SYM + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_DO; + mysql_init_select(lex); + } + expr_list + { + Lex->insert_list= $3; + } + ; + +/* + Drop : delete tables or index or user +*/ + +drop: + DROP opt_temporary table_or_tables if_exists table_list opt_restrict + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_DROP_TABLE; + lex->drop_temporary= $2; + lex->drop_if_exists= $4; + } + | DROP INDEX_SYM ident ON table_ident {} + { + LEX *lex=Lex; + Alter_drop *ad= new Alter_drop(Alter_drop::KEY, $3.str); + if (ad == NULL) + MYSQL_YYABORT; + lex->sql_command= SQLCOM_DROP_INDEX; + lex->alter_info.reset(); + lex->alter_info.flags= ALTER_DROP_INDEX; + lex->alter_info.drop_list.push_back(ad); + if (!lex->current_select->add_table_to_list(lex->thd, $5, NULL, + TL_OPTION_UPDATING)) + MYSQL_YYABORT; + } + | DROP DATABASE if_exists ident + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_DROP_DB; + lex->drop_if_exists=$3; + lex->name= $4; + } + | DROP FUNCTION_SYM if_exists ident '.' ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + sp_name *spname; + if ($4.str && check_db_name(&$4)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), $4.str); + MYSQL_YYABORT; + } + if (lex->sphead) + { + my_error(ER_SP_NO_DROP_SP, MYF(0), "FUNCTION"); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_DROP_FUNCTION; + lex->drop_if_exists= $3; + spname= new sp_name($4, $6, true); + if (spname == NULL) + MYSQL_YYABORT; + spname->init_qname(thd); + lex->spname= spname; + } + | DROP FUNCTION_SYM if_exists ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + LEX_STRING db= {0, 0}; + sp_name *spname; + if (lex->sphead) + { + my_error(ER_SP_NO_DROP_SP, MYF(0), "FUNCTION"); + MYSQL_YYABORT; + } + if (thd->db && lex->copy_db_to(&db.str, &db.length)) + MYSQL_YYABORT; + lex->sql_command = SQLCOM_DROP_FUNCTION; + lex->drop_if_exists= $3; + spname= new sp_name(db, $4, false); + if (spname == NULL) + MYSQL_YYABORT; + spname->init_qname(thd); + lex->spname= spname; + } + | DROP PROCEDURE if_exists sp_name + { + LEX *lex=Lex; + if (lex->sphead) + { + my_error(ER_SP_NO_DROP_SP, MYF(0), "PROCEDURE"); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_DROP_PROCEDURE; + lex->drop_if_exists= $3; + lex->spname= $4; + } + | DROP USER clear_privileges user_list + { + Lex->sql_command = SQLCOM_DROP_USER; + } + | DROP VIEW_SYM if_exists table_list opt_restrict + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_DROP_VIEW; + lex->drop_if_exists= $3; + } + | DROP EVENT_SYM if_exists sp_name + { + Lex->drop_if_exists= $3; + Lex->spname= $4; + Lex->sql_command = SQLCOM_DROP_EVENT; + } + | DROP TRIGGER_SYM if_exists sp_name + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_DROP_TRIGGER; + lex->drop_if_exists= $3; + lex->spname= $4; + } + | DROP TABLESPACE tablespace_name opt_ts_engine opt_ts_wait + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_cmd_type= DROP_TABLESPACE; + } + | DROP LOGFILE_SYM GROUP_SYM logfile_group_name opt_ts_engine opt_ts_wait + { + LEX *lex= Lex; + lex->alter_tablespace_info->ts_cmd_type= DROP_LOGFILE_GROUP; + } + | DROP SERVER_SYM if_exists ident_or_text + { + Lex->sql_command = SQLCOM_DROP_SERVER; + Lex->drop_if_exists= $3; + Lex->server_options.server_name= $4.str; + Lex->server_options.server_name_length= $4.length; + } + ; + +table_list: + table_name + | table_list ',' table_name + ; + +table_name: + table_ident + { + if (!Select->add_table_to_list(YYTHD, $1, NULL, TL_OPTION_UPDATING)) + MYSQL_YYABORT; + } + ; + +table_alias_ref_list: + table_alias_ref + | table_alias_ref_list ',' table_alias_ref + ; + +table_alias_ref: + table_ident + { + if (!Select->add_table_to_list(YYTHD, $1, NULL, + TL_OPTION_UPDATING | TL_OPTION_ALIAS, + Lex->lock_option )) + MYSQL_YYABORT; + } + ; + +if_exists: + /* empty */ { $$= 0; } + | IF EXISTS { $$= 1; } + ; + +opt_temporary: + /* empty */ { $$= 0; } + | TEMPORARY { $$= 1; } + ; +/* +** Insert : add new data to table +*/ + +insert: + INSERT + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_INSERT; + lex->duplicates= DUP_ERROR; + mysql_init_select(lex); + /* for subselects */ + lex->lock_option= TL_READ_DEFAULT; + } + insert_lock_option + opt_ignore insert2 + { + Select->set_lock_for_tables($3); + Lex->current_select= &Lex->select_lex; + } + insert_field_spec opt_insert_update + {} + ; + +replace: + REPLACE + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_REPLACE; + lex->duplicates= DUP_REPLACE; + mysql_init_select(lex); + } + replace_lock_option insert2 + { + Select->set_lock_for_tables($3); + Lex->current_select= &Lex->select_lex; + } + insert_field_spec + {} + ; + +insert_lock_option: + /* empty */ + { +#ifdef HAVE_QUERY_CACHE + /* + If it is SP we do not allow insert optimisation whan result of + insert visible only after the table unlocking but everyone can + read table. + */ + $$= (Lex->sphead ? TL_WRITE_DEFAULT : TL_WRITE_CONCURRENT_INSERT); +#else + $$= TL_WRITE_CONCURRENT_INSERT; +#endif + } + | LOW_PRIORITY { $$= TL_WRITE_LOW_PRIORITY; } + | DELAYED_SYM { $$= TL_WRITE_DELAYED; } + | HIGH_PRIORITY { $$= TL_WRITE; } + ; + +replace_lock_option: + opt_low_priority { $$= $1; } + | DELAYED_SYM { $$= TL_WRITE_DELAYED; } + ; + +insert2: + INTO insert_table {} + | insert_table {} + ; + +insert_table: + table_name + { + LEX *lex=Lex; + lex->field_list.empty(); + lex->many_values.empty(); + lex->insert_list=0; + }; + +insert_field_spec: + insert_values {} + | '(' ')' insert_values {} + | '(' fields ')' insert_values {} + | SET + { + LEX *lex=Lex; + if (!(lex->insert_list = new List_item) || + lex->many_values.push_back(lex->insert_list)) + MYSQL_YYABORT; + } + ident_eq_list + ; + +fields: + fields ',' insert_ident { Lex->field_list.push_back($3); } + | insert_ident { Lex->field_list.push_back($1); } + ; + +insert_values: + VALUES values_list {} + | VALUE_SYM values_list {} + | create_select + { Select->set_braces(0);} + union_clause {} + | '(' create_select ')' + { Select->set_braces(1);} + union_opt {} + ; + +values_list: + values_list ',' no_braces + | no_braces + ; + +ident_eq_list: + ident_eq_list ',' ident_eq_value + | ident_eq_value + ; + +ident_eq_value: + simple_ident_nospvar equal expr_or_default + { + LEX *lex=Lex; + if (lex->field_list.push_back($1) || + lex->insert_list->push_back($3)) + MYSQL_YYABORT; + } + ; + +equal: + EQ {} + | SET_VAR {} + ; + +opt_equal: + /* empty */ {} + | equal {} + ; + +no_braces: + '(' + { + if (!(Lex->insert_list = new List_item)) + MYSQL_YYABORT; + } + opt_values ')' + { + LEX *lex=Lex; + if (lex->many_values.push_back(lex->insert_list)) + MYSQL_YYABORT; + } + ; + +opt_values: + /* empty */ {} + | values + ; + +values: + values ',' expr_or_default + { + if (Lex->insert_list->push_back($3)) + MYSQL_YYABORT; + } + | expr_or_default + { + if (Lex->insert_list->push_back($1)) + MYSQL_YYABORT; + } + ; + +expr_or_default: + expr { $$= $1;} + | DEFAULT + { + $$= new (YYTHD->mem_root) Item_default_value(Lex->current_context()); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +opt_insert_update: + /* empty */ + | ON DUPLICATE_SYM { Lex->duplicates= DUP_UPDATE; } + KEY_SYM UPDATE_SYM insert_update_list + ; + +/* Update rows in a table */ + +update: + UPDATE_SYM + { + LEX *lex= Lex; + mysql_init_select(lex); + lex->sql_command= SQLCOM_UPDATE; + lex->lock_option= TL_UNLOCK; /* Will be set later */ + lex->duplicates= DUP_ERROR; + } + opt_low_priority opt_ignore join_table_list + SET update_list + { + LEX *lex= Lex; + if (lex->select_lex.table_list.elements > 1) + lex->sql_command= SQLCOM_UPDATE_MULTI; + else if (lex->select_lex.get_table_list()->derived) + { + /* it is single table update and it is update of derived table */ + my_error(ER_NON_UPDATABLE_TABLE, MYF(0), + lex->select_lex.get_table_list()->alias, "UPDATE"); + MYSQL_YYABORT; + } + /* + In case of multi-update setting write lock for all tables may + be too pessimistic. We will decrease lock level if possible in + mysql_multi_update(). + */ + Select->set_lock_for_tables($3); + } + where_clause opt_order_clause delete_limit_clause {} + ; + +update_list: + update_list ',' update_elem + | update_elem + ; + +update_elem: + simple_ident_nospvar equal expr_or_default + { + if (add_item_to_list(YYTHD, $1) || add_value_to_list(YYTHD, $3)) + MYSQL_YYABORT; + } + ; + +insert_update_list: + insert_update_list ',' insert_update_elem + | insert_update_elem + ; + +insert_update_elem: + simple_ident_nospvar equal expr_or_default + { + LEX *lex= Lex; + if (lex->update_list.push_back($1) || + lex->value_list.push_back($3)) + MYSQL_YYABORT; + } + ; + +opt_low_priority: + /* empty */ { $$= TL_WRITE_DEFAULT; } + | LOW_PRIORITY { $$= TL_WRITE_LOW_PRIORITY; } + ; + +/* Delete rows from a table */ + +delete: + DELETE_SYM + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_DELETE; + mysql_init_select(lex); + lex->lock_option= TL_WRITE_DEFAULT; + lex->ignore= 0; + lex->select_lex.init_order(); + } + opt_delete_options single_multi {} + ; + +single_multi: + FROM table_ident + { + if (!Select->add_table_to_list(YYTHD, $2, NULL, TL_OPTION_UPDATING, + Lex->lock_option)) + MYSQL_YYABORT; + } + where_clause opt_order_clause + delete_limit_clause {} + | table_wild_list + { mysql_init_multi_delete(Lex); } + FROM join_table_list where_clause + { + if (multi_delete_set_locks_and_link_aux_tables(Lex)) + MYSQL_YYABORT; + } + | FROM table_alias_ref_list + { mysql_init_multi_delete(Lex); } + USING join_table_list where_clause + { + if (multi_delete_set_locks_and_link_aux_tables(Lex)) + MYSQL_YYABORT; + } + ; + +table_wild_list: + table_wild_one {} + | table_wild_list ',' table_wild_one {} + ; + +table_wild_one: + ident opt_wild opt_table_alias + { + Table_ident *ti= new Table_ident($1); + if (ti == NULL) + MYSQL_YYABORT; + if (!Select->add_table_to_list(YYTHD, + ti, + $3, + TL_OPTION_UPDATING | TL_OPTION_ALIAS, + Lex->lock_option)) + MYSQL_YYABORT; + } + | ident '.' ident opt_wild opt_table_alias + { + Table_ident *ti= new Table_ident(YYTHD, $1, $3, 0); + if (ti == NULL) + MYSQL_YYABORT; + if (!Select->add_table_to_list(YYTHD, + ti, + $5, + TL_OPTION_UPDATING | TL_OPTION_ALIAS, + Lex->lock_option)) + MYSQL_YYABORT; + } + ; + +opt_wild: + /* empty */ {} + | '.' '*' {} + ; + +opt_delete_options: + /* empty */ {} + | opt_delete_option opt_delete_options {} + ; + +opt_delete_option: + QUICK { Select->options|= OPTION_QUICK; } + | LOW_PRIORITY { Lex->lock_option= TL_WRITE_LOW_PRIORITY; } + | IGNORE_SYM { Lex->ignore= 1; } + ; + +truncate: + TRUNCATE_SYM opt_table_sym table_name + { + LEX* lex= Lex; + lex->sql_command= SQLCOM_TRUNCATE; + lex->select_lex.options= 0; + lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED; + lex->select_lex.init_order(); + } + ; + +opt_table_sym: + /* empty */ + | TABLE_SYM + ; + +opt_profile_defs: + /* empty */ + | profile_defs; + +profile_defs: + profile_def + | profile_defs ',' profile_def; + +profile_def: + CPU_SYM + { + Lex->profile_options|= PROFILE_CPU; + } + | MEMORY_SYM + { + Lex->profile_options|= PROFILE_MEMORY; + } + | BLOCK_SYM IO_SYM + { + Lex->profile_options|= PROFILE_BLOCK_IO; + } + | CONTEXT_SYM SWITCHES_SYM + { + Lex->profile_options|= PROFILE_CONTEXT; + } + | PAGE_SYM FAULTS_SYM + { + Lex->profile_options|= PROFILE_PAGE_FAULTS; + } + | IPC_SYM + { + Lex->profile_options|= PROFILE_IPC; + } + | SWAPS_SYM + { + Lex->profile_options|= PROFILE_SWAPS; + } + | SOURCE_SYM + { + Lex->profile_options|= PROFILE_SOURCE; + } + | ALL + { + Lex->profile_options|= PROFILE_ALL; + } + ; + +opt_profile_args: + /* empty */ + { + Lex->profile_query_id= 0; + } + | FOR_SYM QUERY_SYM NUM + { + Lex->profile_query_id= atoi($3.str); + } + ; + +/* Show things */ + +show: + SHOW + { + LEX *lex=Lex; + lex->wild=0; + lex->lock_option= TL_READ; + mysql_init_select(lex); + lex->current_select->parsing_place= SELECT_LIST; + bzero((char*) &lex->create_info,sizeof(lex->create_info)); + } + show_param + {} + ; + +show_param: + DATABASES wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_DATABASES; + if (prepare_schema_table(YYTHD, lex, 0, SCH_SCHEMATA)) + MYSQL_YYABORT; + } + | opt_full TABLES opt_db wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_TABLES; + lex->select_lex.db= $3; + if (prepare_schema_table(YYTHD, lex, 0, SCH_TABLE_NAMES)) + MYSQL_YYABORT; + } + | opt_full TRIGGERS_SYM opt_db wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_TRIGGERS; + lex->select_lex.db= $3; + if (prepare_schema_table(YYTHD, lex, 0, SCH_TRIGGERS)) + MYSQL_YYABORT; + } + | EVENTS_SYM opt_db wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_EVENTS; + lex->select_lex.db= $2; + if (prepare_schema_table(YYTHD, lex, 0, SCH_EVENTS)) + MYSQL_YYABORT; + } + | TABLE_SYM STATUS_SYM opt_db wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_TABLE_STATUS; + lex->select_lex.db= $3; + if (prepare_schema_table(YYTHD, lex, 0, SCH_TABLES)) + MYSQL_YYABORT; + } + | OPEN_SYM TABLES opt_db wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_OPEN_TABLES; + lex->select_lex.db= $3; + if (prepare_schema_table(YYTHD, lex, 0, SCH_OPEN_TABLES)) + MYSQL_YYABORT; + } + | opt_full PLUGIN_SYM + { + LEX *lex= Lex; + WARN_DEPRECATED(yythd, "6.0", "SHOW PLUGIN", "'SHOW PLUGINS'"); + lex->sql_command= SQLCOM_SHOW_PLUGINS; + if (prepare_schema_table(YYTHD, lex, 0, SCH_PLUGINS)) + MYSQL_YYABORT; + } + | PLUGINS_SYM + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_PLUGINS; + if (prepare_schema_table(YYTHD, lex, 0, SCH_PLUGINS)) + MYSQL_YYABORT; + } + | ENGINE_SYM known_storage_engines show_engine_param + { Lex->create_info.db_type= $2; } + | ENGINE_SYM ALL show_engine_param + { Lex->create_info.db_type= NULL; } + | opt_full COLUMNS from_or_in table_ident opt_db wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_FIELDS; + if ($5) + $4->change_db($5); + if (prepare_schema_table(YYTHD, lex, $4, SCH_COLUMNS)) + MYSQL_YYABORT; + } + | NEW_SYM MASTER_SYM FOR_SYM SLAVE + WITH MASTER_LOG_FILE_SYM EQ + TEXT_STRING_sys /* $8 */ + AND_SYM MASTER_LOG_POS_SYM EQ + ulonglong_num /* $12 */ + AND_SYM MASTER_SERVER_ID_SYM EQ + ulong_num /* $16 */ + { + Lex->sql_command = SQLCOM_SHOW_NEW_MASTER; + Lex->mi.log_file_name = $8.str; + Lex->mi.pos = $12; + Lex->mi.server_id = $16; + } + | master_or_binary LOGS_SYM + { + Lex->sql_command = SQLCOM_SHOW_BINLOGS; + } + | SLAVE HOSTS_SYM + { + Lex->sql_command = SQLCOM_SHOW_SLAVE_HOSTS; + } + | BINLOG_SYM EVENTS_SYM binlog_in binlog_from + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_BINLOG_EVENTS; + } opt_limit_clause_init + | keys_or_index from_or_in table_ident opt_db where_clause + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_KEYS; + if ($4) + $3->change_db($4); + if (prepare_schema_table(YYTHD, lex, $3, SCH_STATISTICS)) + MYSQL_YYABORT; + } + | COLUMN_SYM TYPES_SYM + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_COLUMN_TYPES; + } + | TABLE_SYM TYPES_SYM + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_STORAGE_ENGINES; + WARN_DEPRECATED(yythd, "6.0", "SHOW TABLE TYPES", "'SHOW [STORAGE] ENGINES'"); + if (prepare_schema_table(YYTHD, lex, 0, SCH_ENGINES)) + MYSQL_YYABORT; + } + | opt_storage ENGINES_SYM + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_STORAGE_ENGINES; + if (prepare_schema_table(YYTHD, lex, 0, SCH_ENGINES)) + MYSQL_YYABORT; + } + | AUTHORS_SYM + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_AUTHORS; + } + | CONTRIBUTORS_SYM + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_CONTRIBUTORS; + } + | PRIVILEGES + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_PRIVILEGES; + } + | COUNT_SYM '(' '*' ')' WARNINGS + { (void) create_select_for_variable("warning_count"); } + | COUNT_SYM '(' '*' ')' ERRORS + { (void) create_select_for_variable("error_count"); } + | WARNINGS opt_limit_clause_init + { Lex->sql_command = SQLCOM_SHOW_WARNS;} + | ERRORS opt_limit_clause_init + { Lex->sql_command = SQLCOM_SHOW_ERRORS;} + | PROFILES_SYM + { Lex->sql_command = SQLCOM_SHOW_PROFILES; } + | PROFILE_SYM opt_profile_defs opt_profile_args opt_limit_clause_init + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_PROFILE; + if (prepare_schema_table(YYTHD, lex, NULL, SCH_PROFILES) != 0) + YYABORT; + } + | opt_var_type STATUS_SYM wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_STATUS; + lex->option_type= $1; + if (prepare_schema_table(YYTHD, lex, 0, SCH_STATUS)) + MYSQL_YYABORT; + } + | INNOBASE_SYM STATUS_SYM + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_SHOW_ENGINE_STATUS; + if (!(lex->create_info.db_type= + ha_resolve_by_legacy_type(YYTHD, DB_TYPE_INNODB))) + { + my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), "InnoDB"); + MYSQL_YYABORT; + } + WARN_DEPRECATED(yythd, "6.0", "SHOW INNODB STATUS", "'SHOW ENGINE INNODB STATUS'"); + } + | MUTEX_SYM STATUS_SYM + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_SHOW_ENGINE_MUTEX; + if (!(lex->create_info.db_type= + ha_resolve_by_legacy_type(YYTHD, DB_TYPE_INNODB))) + { + my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), "InnoDB"); + MYSQL_YYABORT; + } + WARN_DEPRECATED(yythd, "6.0", "SHOW MUTEX STATUS", "'SHOW ENGINE INNODB MUTEX'"); + } + | opt_full PROCESSLIST_SYM + { Lex->sql_command= SQLCOM_SHOW_PROCESSLIST;} + | opt_var_type VARIABLES wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_VARIABLES; + lex->option_type= $1; + if (prepare_schema_table(YYTHD, lex, 0, SCH_VARIABLES)) + MYSQL_YYABORT; + } + | charset wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_CHARSETS; + if (prepare_schema_table(YYTHD, lex, 0, SCH_CHARSETS)) + MYSQL_YYABORT; + } + | COLLATION_SYM wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_COLLATIONS; + if (prepare_schema_table(YYTHD, lex, 0, SCH_COLLATIONS)) + MYSQL_YYABORT; + } + | GRANTS + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_GRANTS; + LEX_USER *curr_user; + if (!(curr_user= (LEX_USER*) lex->thd->alloc(sizeof(st_lex_user)))) + MYSQL_YYABORT; + bzero(curr_user, sizeof(st_lex_user)); + lex->grant_user= curr_user; + } + | GRANTS FOR_SYM user + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SHOW_GRANTS; + lex->grant_user=$3; + lex->grant_user->password=null_lex_str; + } + | CREATE DATABASE opt_if_not_exists ident + { + Lex->sql_command=SQLCOM_SHOW_CREATE_DB; + Lex->create_info.options=$3; + Lex->name= $4; + } + | CREATE TABLE_SYM table_ident + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_SHOW_CREATE; + if (!lex->select_lex.add_table_to_list(YYTHD, $3, NULL,0)) + MYSQL_YYABORT; + lex->only_view= 0; + lex->create_info.storage_media= HA_SM_DEFAULT; + } + | CREATE VIEW_SYM table_ident + { + LEX *lex= Lex; + lex->sql_command = SQLCOM_SHOW_CREATE; + if (!lex->select_lex.add_table_to_list(YYTHD, $3, NULL, 0)) + MYSQL_YYABORT; + lex->only_view= 1; + } + | MASTER_SYM STATUS_SYM + { + Lex->sql_command = SQLCOM_SHOW_MASTER_STAT; + } + | SLAVE STATUS_SYM + { + Lex->sql_command = SQLCOM_SHOW_SLAVE_STAT; + } + | CREATE PROCEDURE sp_name + { + LEX *lex= Lex; + + lex->sql_command = SQLCOM_SHOW_CREATE_PROC; + lex->spname= $3; + } + | CREATE FUNCTION_SYM sp_name + { + LEX *lex= Lex; + + lex->sql_command = SQLCOM_SHOW_CREATE_FUNC; + lex->spname= $3; + } + | CREATE TRIGGER_SYM sp_name + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_CREATE_TRIGGER; + lex->spname= $3; + } + | PROCEDURE STATUS_SYM wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_STATUS_PROC; + if (prepare_schema_table(YYTHD, lex, 0, SCH_PROCEDURES)) + MYSQL_YYABORT; + } + | FUNCTION_SYM STATUS_SYM wild_and_where + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_SHOW_STATUS_FUNC; + if (prepare_schema_table(YYTHD, lex, 0, SCH_PROCEDURES)) + MYSQL_YYABORT; + } + | PROCEDURE CODE_SYM sp_name + { +#ifdef DBUG_OFF + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; +#else + Lex->sql_command= SQLCOM_SHOW_PROC_CODE; + Lex->spname= $3; +#endif + } + | FUNCTION_SYM CODE_SYM sp_name + { +#ifdef DBUG_OFF + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; +#else + Lex->sql_command= SQLCOM_SHOW_FUNC_CODE; + Lex->spname= $3; +#endif + } + | CREATE EVENT_SYM sp_name + { + Lex->spname= $3; + Lex->sql_command = SQLCOM_SHOW_CREATE_EVENT; + } + ; + +show_engine_param: + STATUS_SYM + { Lex->sql_command= SQLCOM_SHOW_ENGINE_STATUS; } + | MUTEX_SYM + { Lex->sql_command= SQLCOM_SHOW_ENGINE_MUTEX; } + | LOGS_SYM + { Lex->sql_command= SQLCOM_SHOW_ENGINE_LOGS; } + ; + +master_or_binary: + MASTER_SYM + | BINARY + ; + +opt_storage: + /* empty */ + | STORAGE_SYM + ; + +opt_db: + /* empty */ { $$= 0; } + | from_or_in ident { $$= $2.str; } + ; + +opt_full: + /* empty */ { Lex->verbose=0; } + | FULL { Lex->verbose=1; } + ; + +from_or_in: + FROM + | IN_SYM + ; + +binlog_in: + /* empty */ { Lex->mi.log_file_name = 0; } + | IN_SYM TEXT_STRING_sys { Lex->mi.log_file_name = $2.str; } + ; + +binlog_from: + /* empty */ { Lex->mi.pos = 4; /* skip magic number */ } + | FROM ulonglong_num { Lex->mi.pos = $2; } + ; + +wild_and_where: + /* empty */ + | LIKE TEXT_STRING_sys + { + Lex->wild= new (YYTHD->mem_root) String($2.str, $2.length, + system_charset_info); + if (Lex->wild == NULL) + MYSQL_YYABORT; + } + | WHERE expr + { + Select->where= $2; + if ($2) + $2->top_level_item(); + } + ; + +/* A Oracle compatible synonym for show */ +describe: + describe_command table_ident + { + LEX *lex= Lex; + lex->lock_option= TL_READ; + mysql_init_select(lex); + lex->current_select->parsing_place= SELECT_LIST; + lex->sql_command= SQLCOM_SHOW_FIELDS; + lex->select_lex.db= 0; + lex->verbose= 0; + if (prepare_schema_table(YYTHD, lex, $2, SCH_COLUMNS)) + MYSQL_YYABORT; + } + opt_describe_column {} + | describe_command opt_extended_describe + { Lex->describe|= DESCRIBE_NORMAL; } + select + { + LEX *lex=Lex; + lex->select_lex.options|= SELECT_DESCRIBE; + } + ; + +describe_command: + DESC + | DESCRIBE + ; + +opt_extended_describe: + /* empty */ {} + | EXTENDED_SYM { Lex->describe|= DESCRIBE_EXTENDED; } + | PARTITIONS_SYM { Lex->describe|= DESCRIBE_PARTITIONS; } + ; + +opt_describe_column: + /* empty */ {} + | text_string { Lex->wild= $1; } + | ident + { + Lex->wild= new (YYTHD->mem_root) String((const char*) $1.str, + $1.length, + system_charset_info); + if (Lex->wild == NULL) + MYSQL_YYABORT; + } + ; + + +/* flush things */ + +flush: + FLUSH_SYM opt_no_write_to_binlog + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_FLUSH; + lex->type= 0; + lex->no_write_to_binlog= $2; + } + flush_options + {} + ; + +flush_options: + flush_options ',' flush_option + | flush_option + ; + +flush_option: + table_or_tables + { Lex->type|= REFRESH_TABLES; } + opt_table_list {} + | TABLES WITH READ_SYM LOCK_SYM + { Lex->type|= REFRESH_TABLES | REFRESH_READ_LOCK; } + | QUERY_SYM CACHE_SYM + { Lex->type|= REFRESH_QUERY_CACHE_FREE; } + | HOSTS_SYM + { Lex->type|= REFRESH_HOSTS; } + | PRIVILEGES + { Lex->type|= REFRESH_GRANT; } + | LOGS_SYM + { Lex->type|= REFRESH_LOG; } + | STATUS_SYM + { Lex->type|= REFRESH_STATUS; } + | SLAVE + { Lex->type|= REFRESH_SLAVE; } + | MASTER_SYM + { Lex->type|= REFRESH_MASTER; } + | DES_KEY_FILE + { Lex->type|= REFRESH_DES_KEY_FILE; } + | RESOURCES + { Lex->type|= REFRESH_USER_RESOURCES; } + ; + +opt_table_list: + /* empty */ {} + | table_list {} + ; + +reset: + RESET_SYM + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_RESET; lex->type=0; + } + reset_options + {} + ; + +reset_options: + reset_options ',' reset_option + | reset_option + ; + +reset_option: + SLAVE { Lex->type|= REFRESH_SLAVE; } + | MASTER_SYM { Lex->type|= REFRESH_MASTER; } + | QUERY_SYM CACHE_SYM { Lex->type|= REFRESH_QUERY_CACHE;} + ; + +purge: + PURGE + { + LEX *lex=Lex; + lex->type=0; + lex->sql_command = SQLCOM_PURGE; + } + purge_options + {} + ; + +purge_options: + master_or_binary LOGS_SYM purge_option + ; + +purge_option: + TO_SYM TEXT_STRING_sys + { + Lex->to_log = $2.str; + } + | BEFORE_SYM expr + { + LEX *lex= Lex; + lex->value_list.empty(); + lex->value_list.push_front($2); + lex->sql_command= SQLCOM_PURGE_BEFORE; + } + ; + +/* kill threads */ + +kill: + KILL_SYM kill_option expr + { + LEX *lex=Lex; + lex->value_list.empty(); + lex->value_list.push_front($3); + lex->sql_command= SQLCOM_KILL; + } + ; + +kill_option: + /* empty */ { Lex->type= 0; } + | CONNECTION_SYM { Lex->type= 0; } + | QUERY_SYM { Lex->type= ONLY_KILL_QUERY; } + ; + +/* change database */ + +use: + USE_SYM ident + { + LEX *lex=Lex; + lex->sql_command=SQLCOM_CHANGE_DB; + lex->select_lex.db= $2.str; + } + ; + +/* import, export of files */ + +load: + LOAD DATA_SYM + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "LOAD DATA"); + MYSQL_YYABORT; + } + lex->fname_start= lip->get_ptr(); + } + load_data + {} + | LOAD TABLE_SYM table_ident FROM MASTER_SYM + { + LEX *lex=Lex; + WARN_DEPRECATED(yythd, "6.0", "LOAD TABLE FROM MASTER", + "MySQL Administrator (mysqldump, mysql)"); + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "LOAD TABLE"); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_LOAD_MASTER_TABLE; + if (!Select->add_table_to_list(YYTHD, $3, NULL, TL_OPTION_UPDATING)) + MYSQL_YYABORT; + } + ; + +load_data: + load_data_lock opt_local INFILE TEXT_STRING_filesystem + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_LOAD; + lex->lock_option= $1; + lex->local_file= $2; + lex->duplicates= DUP_ERROR; + lex->ignore= 0; + if (!(lex->exchange= new sql_exchange($4.str, 0))) + MYSQL_YYABORT; + } + opt_duplicate INTO + { + Lex->fname_end= YYLIP->get_ptr(); + } + TABLE_SYM table_ident + { + LEX *lex=Lex; + if (!Select->add_table_to_list(YYTHD, $10, NULL, TL_OPTION_UPDATING, + lex->lock_option)) + MYSQL_YYABORT; + lex->field_list.empty(); + lex->update_list.empty(); + lex->value_list.empty(); + } + opt_load_data_charset + { Lex->exchange->cs= $12; } + opt_field_term opt_line_term opt_ignore_lines opt_field_or_var_spec + opt_load_data_set_spec + {} + | FROM MASTER_SYM + { + Lex->sql_command = SQLCOM_LOAD_MASTER_DATA; + WARN_DEPRECATED(yythd, "6.0", "LOAD DATA FROM MASTER", + "mysqldump or future " + "BACKUP/RESTORE DATABASE facility"); + } + ; + +opt_local: + /* empty */ { $$=0;} + | LOCAL_SYM { $$=1;} + ; + +load_data_lock: + /* empty */ { $$= TL_WRITE_DEFAULT; } + | CONCURRENT + { +#ifdef HAVE_QUERY_CACHE + /* + Ignore this option in SP to avoid problem with query cache + */ + if (Lex->sphead != 0) + $$= TL_WRITE_DEFAULT; + else +#endif + $$= TL_WRITE_CONCURRENT_INSERT; + } + | LOW_PRIORITY { $$= TL_WRITE_LOW_PRIORITY; } + ; + +opt_duplicate: + /* empty */ { Lex->duplicates=DUP_ERROR; } + | REPLACE { Lex->duplicates=DUP_REPLACE; } + | IGNORE_SYM { Lex->ignore= 1; } + ; + +opt_field_term: + /* empty */ + | COLUMNS field_term_list + ; + +field_term_list: + field_term_list field_term + | field_term + ; + +field_term: + TERMINATED BY text_string + { + DBUG_ASSERT(Lex->exchange != 0); + Lex->exchange->field_term= $3; + } + | OPTIONALLY ENCLOSED BY text_string + { + LEX *lex= Lex; + DBUG_ASSERT(lex->exchange != 0); + lex->exchange->enclosed= $4; + lex->exchange->opt_enclosed= 1; + } + | ENCLOSED BY text_string + { + DBUG_ASSERT(Lex->exchange != 0); + Lex->exchange->enclosed= $3; + } + | ESCAPED BY text_string + { + DBUG_ASSERT(Lex->exchange != 0); + Lex->exchange->escaped= $3; + } + ; + +opt_line_term: + /* empty */ + | LINES line_term_list + ; + +line_term_list: + line_term_list line_term + | line_term + ; + +line_term: + TERMINATED BY text_string + { + DBUG_ASSERT(Lex->exchange != 0); + Lex->exchange->line_term= $3; + } + | STARTING BY text_string + { + DBUG_ASSERT(Lex->exchange != 0); + Lex->exchange->line_start= $3; + } + ; + +opt_ignore_lines: + /* empty */ + | IGNORE_SYM NUM LINES + { + DBUG_ASSERT(Lex->exchange != 0); + Lex->exchange->skip_lines= atol($2.str); + } + ; + +opt_field_or_var_spec: + /* empty */ {} + | '(' fields_or_vars ')' {} + | '(' ')' {} + ; + +fields_or_vars: + fields_or_vars ',' field_or_var + { Lex->field_list.push_back($3); } + | field_or_var + { Lex->field_list.push_back($1); } + ; + +field_or_var: + simple_ident_nospvar {$$= $1;} + | '@' ident_or_text + { + $$= new (YYTHD->mem_root) Item_user_var_as_out_param($2); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +opt_load_data_set_spec: + /* empty */ {} + | SET insert_update_list {} + ; + +/* Common definitions */ + +text_literal: + TEXT_STRING + { + LEX_STRING tmp; + THD *thd= YYTHD; + CHARSET_INFO *cs_con= thd->variables.collation_connection; + CHARSET_INFO *cs_cli= thd->variables.character_set_client; + uint repertoire= thd->lex->text_string_is_7bit && + my_charset_is_ascii_based(cs_cli) ? + MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; + if (thd->charset_is_collation_connection || + (repertoire == MY_REPERTOIRE_ASCII && + my_charset_is_ascii_based(cs_con))) + tmp= $1; + else + { + if (thd->convert_string(&tmp, cs_con, $1.str, $1.length, cs_cli)) + MYSQL_YYABORT; + } + $$= new (thd->mem_root) Item_string(tmp.str, tmp.length, cs_con, + DERIVATION_COERCIBLE, + repertoire); + if ($$ == NULL) + MYSQL_YYABORT; + } + | NCHAR_STRING + { + uint repertoire= Lex->text_string_is_7bit ? + MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; + DBUG_ASSERT(my_charset_is_ascii_based(national_charset_info)); + $$= new (YYTHD->mem_root) Item_string($1.str, $1.length, + national_charset_info, + DERIVATION_COERCIBLE, + repertoire); + if ($$ == NULL) + MYSQL_YYABORT; + } + | UNDERSCORE_CHARSET TEXT_STRING + { + Item_string *str= new (YYTHD->mem_root) Item_string($2.str, + $2.length, $1); + if (str == NULL) + MYSQL_YYABORT; + str->set_repertoire_from_value(); + str->set_cs_specified(TRUE); + + $$= str; + } + | text_literal TEXT_STRING_literal + { + Item_string* item= (Item_string*) $1; + item->append($2.str, $2.length); + if (!(item->collation.repertoire & MY_REPERTOIRE_EXTENDED)) + { + /* + If the string has been pure ASCII so far, + check the new part. + */ + CHARSET_INFO *cs= YYTHD->variables.collation_connection; + item->collation.repertoire|= my_string_repertoire(cs, + $2.str, + $2.length); + } + } + ; + +text_string: + TEXT_STRING_literal + { + $$= new (YYTHD->mem_root) String($1.str, + $1.length, + YYTHD->variables.collation_connection); + if ($$ == NULL) + MYSQL_YYABORT; + } + | HEX_NUM + { + Item *tmp= new (YYTHD->mem_root) Item_hex_string($1.str, $1.length); + if (tmp == NULL) + MYSQL_YYABORT; + /* + it is OK only emulate fix_fields, because we need only + value of constant + */ + tmp->quick_fix_field(); + $$= tmp->val_str((String*) 0); + } + | BIN_NUM + { + Item *tmp= new (YYTHD->mem_root) Item_bin_string($1.str, $1.length); + if (tmp == NULL) + MYSQL_YYABORT; + /* + it is OK only emulate fix_fields, because we need only + value of constant + */ + tmp->quick_fix_field(); + $$= tmp->val_str((String*) 0); + } + ; + +param_marker: + PARAM_MARKER + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + Item_param *item; + if (! lex->parsing_options.allows_variable) + { + my_error(ER_VIEW_SELECT_VARIABLE, MYF(0)); + MYSQL_YYABORT; + } + item= new (thd->mem_root) Item_param((uint) (lip->get_tok_start() - thd->query)); + if (!($$= item) || lex->param_list.push_back(item)) + { + my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0)); + MYSQL_YYABORT; + } + } + ; + +signed_literal: + literal { $$ = $1; } + | '+' NUM_literal { $$ = $2; } + | '-' NUM_literal + { + $2->max_length++; + $$= $2->neg(); + } + ; + +literal: + text_literal { $$ = $1; } + | NUM_literal { $$ = $1; } + | NULL_SYM + { + $$ = new (YYTHD->mem_root) Item_null(); + if ($$ == NULL) + MYSQL_YYABORT; + YYLIP->next_state= MY_LEX_OPERATOR_OR_IDENT; + } + | FALSE_SYM + { + $$= new (YYTHD->mem_root) Item_int((char*) "FALSE",0,1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | TRUE_SYM + { + $$= new (YYTHD->mem_root) Item_int((char*) "TRUE",1,1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | HEX_NUM + { + $$ = new (YYTHD->mem_root) Item_hex_string($1.str, $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | BIN_NUM + { + $$= new (YYTHD->mem_root) Item_bin_string($1.str, $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | UNDERSCORE_CHARSET HEX_NUM + { + Item *tmp= new (YYTHD->mem_root) Item_hex_string($2.str, $2.length); + if (tmp == NULL) + MYSQL_YYABORT; + /* + it is OK only emulate fix_fieds, because we need only + value of constant + */ + tmp->quick_fix_field(); + String *str= tmp->val_str((String*) 0); + + Item_string *item_str; + item_str= new (YYTHD->mem_root) + Item_string(NULL, /* name will be set in select_item */ + str ? str->ptr() : "", + str ? str->length() : 0, + $1); + if (!item_str || + !item_str->check_well_formed_result(&item_str->str_value, TRUE)) + { + MYSQL_YYABORT; + } + + item_str->set_repertoire_from_value(); + item_str->set_cs_specified(TRUE); + + $$= item_str; + } + | UNDERSCORE_CHARSET BIN_NUM + { + Item *tmp= new (YYTHD->mem_root) Item_bin_string($2.str, $2.length); + if (tmp == NULL) + MYSQL_YYABORT; + /* + it is OK only emulate fix_fieds, because we need only + value of constant + */ + tmp->quick_fix_field(); + String *str= tmp->val_str((String*) 0); + + Item_string *item_str; + item_str= new (YYTHD->mem_root) + Item_string(NULL, /* name will be set in select_item */ + str ? str->ptr() : "", + str ? str->length() : 0, + $1); + if (!item_str || + !item_str->check_well_formed_result(&item_str->str_value, TRUE)) + { + MYSQL_YYABORT; + } + + item_str->set_cs_specified(TRUE); + + $$= item_str; + } + | DATE_SYM text_literal { $$ = $2; } + | TIME_SYM text_literal { $$ = $2; } + | TIMESTAMP text_literal { $$ = $2; } + ; + +NUM_literal: + NUM + { + int error; + $$= new (YYTHD->mem_root) + Item_int($1.str, + (longlong) my_strtoll10($1.str, NULL, &error), + $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | LONG_NUM + { + int error; + $$= new (YYTHD->mem_root) + Item_int($1.str, + (longlong) my_strtoll10($1.str, NULL, &error), + $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | ULONGLONG_NUM + { + $$= new (YYTHD->mem_root) Item_uint($1.str, $1.length); + if ($$ == NULL) + MYSQL_YYABORT; + } + | DECIMAL_NUM + { + $$= new (YYTHD->mem_root) Item_decimal($1.str, $1.length, + YYTHD->charset()); + if (($$ == NULL) || (YYTHD->is_error())) + { + MYSQL_YYABORT; + } + } + | FLOAT_NUM + { + $$= new (YYTHD->mem_root) Item_float($1.str, $1.length); + if (($$ == NULL) || (YYTHD->is_error())) + { + MYSQL_YYABORT; + } + } + ; + +/********************************************************************** +** Creating different items. +**********************************************************************/ + +insert_ident: + simple_ident_nospvar { $$=$1; } + | table_wild { $$=$1; } + ; + +table_wild: + ident '.' '*' + { + SELECT_LEX *sel= Select; + $$= new (YYTHD->mem_root) Item_field(Lex->current_context(), + NullS, $1.str, "*"); + if ($$ == NULL) + MYSQL_YYABORT; + sel->with_wild++; + } + | ident '.' ident '.' '*' + { + THD *thd= YYTHD; + SELECT_LEX *sel= Select; + const char* schema= thd->client_capabilities & CLIENT_NO_SCHEMA ? + NullS : $1.str; + $$= new (thd->mem_root) Item_field(Lex->current_context(), + schema, + $3.str,"*"); + if ($$ == NULL) + MYSQL_YYABORT; + sel->with_wild++; + } + ; + +order_ident: + expr { $$=$1; } + ; + +simple_ident: + ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + sp_variable_t *spv; + sp_pcontext *spc = lex->spcont; + if (spc && (spv = spc->find_variable(&$1))) + { + /* We're compiling a stored procedure and found a variable */ + if (! lex->parsing_options.allows_variable) + { + my_error(ER_VIEW_SELECT_VARIABLE, MYF(0)); + MYSQL_YYABORT; + } + + Item_splocal *splocal; + splocal= new (thd->mem_root) + Item_splocal($1, spv->offset, spv->type, + lip->get_tok_start_prev() - lex->sphead->m_tmp_query, + lip->get_tok_end() - lip->get_tok_start_prev()); + if (splocal == NULL) + MYSQL_YYABORT; +#ifndef DBUG_OFF + splocal->m_sp= lex->sphead; +#endif + $$= splocal; + lex->safe_to_cache_query=0; + } + else + { + SELECT_LEX *sel=Select; + if ((sel->parsing_place != IN_HAVING) || + (sel->get_in_sum_expr() > 0)) + { + $$= new (thd->mem_root) Item_field(Lex->current_context(), + NullS, NullS, $1.str); + } + else + { + $$= new (thd->mem_root) Item_ref(Lex->current_context(), + NullS, NullS, $1.str); + } + if ($$ == NULL) + MYSQL_YYABORT; + } + } + | simple_ident_q { $$= $1; } + ; + +simple_ident_nospvar: + ident + { + THD *thd= YYTHD; + SELECT_LEX *sel=Select; + if ((sel->parsing_place != IN_HAVING) || + (sel->get_in_sum_expr() > 0)) + { + $$= new (thd->mem_root) Item_field(Lex->current_context(), + NullS, NullS, $1.str); + } + else + { + $$= new (thd->mem_root) Item_ref(Lex->current_context(), + NullS, NullS, $1.str); + } + if ($$ == NULL) + MYSQL_YYABORT; + } + | simple_ident_q { $$= $1; } + ; + +simple_ident_q: + ident '.' ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + + /* + FIXME This will work ok in simple_ident_nospvar case because + we can't meet simple_ident_nospvar in trigger now. But it + should be changed in future. + */ + if (lex->sphead && lex->sphead->m_type == TYPE_ENUM_TRIGGER && + (!my_strcasecmp(system_charset_info, $1.str, "NEW") || + !my_strcasecmp(system_charset_info, $1.str, "OLD"))) + { + Item_trigger_field *trg_fld; + bool new_row= ($1.str[0]=='N' || $1.str[0]=='n'); + + if (lex->trg_chistics.event == TRG_EVENT_INSERT && + !new_row) + { + my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "OLD", "on INSERT"); + MYSQL_YYABORT; + } + + if (lex->trg_chistics.event == TRG_EVENT_DELETE && + new_row) + { + my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE"); + MYSQL_YYABORT; + } + + DBUG_ASSERT(!new_row || + (lex->trg_chistics.event == TRG_EVENT_INSERT || + lex->trg_chistics.event == TRG_EVENT_UPDATE)); + const bool read_only= + !(new_row && lex->trg_chistics.action_time == TRG_ACTION_BEFORE); + trg_fld= new (thd->mem_root) + Item_trigger_field(Lex->current_context(), + new_row ? + Item_trigger_field::NEW_ROW: + Item_trigger_field::OLD_ROW, + $3.str, + SELECT_ACL, + read_only); + if (trg_fld == NULL) + MYSQL_YYABORT; + + /* + Let us add this item to list of all Item_trigger_field objects + in trigger. + */ + lex->trg_table_fields.link_in_list((uchar*) trg_fld, + (uchar**) &trg_fld->next_trg_field); + + $$= trg_fld; + } + else + { + SELECT_LEX *sel= lex->current_select; + if (sel->no_table_names_allowed) + { + my_error(ER_TABLENAME_NOT_ALLOWED_HERE, + MYF(0), $1.str, thd->where); + } + if ((sel->parsing_place != IN_HAVING) || + (sel->get_in_sum_expr() > 0)) + { + $$= new (thd->mem_root) Item_field(Lex->current_context(), + NullS, $1.str, $3.str); + } + else + { + $$= new (thd->mem_root) Item_ref(Lex->current_context(), + NullS, $1.str, $3.str); + } + if ($$ == NULL) + MYSQL_YYABORT; + } + } + | '.' ident '.' ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + SELECT_LEX *sel= lex->current_select; + if (sel->no_table_names_allowed) + { + my_error(ER_TABLENAME_NOT_ALLOWED_HERE, + MYF(0), $2.str, thd->where); + } + if ((sel->parsing_place != IN_HAVING) || + (sel->get_in_sum_expr() > 0)) + { + $$= new (thd->mem_root) Item_field(Lex->current_context(), + NullS, $2.str, $4.str); + + } + else + { + $$= new (thd->mem_root) Item_ref(Lex->current_context(), + NullS, $2.str, $4.str); + } + if ($$ == NULL) + MYSQL_YYABORT; + } + | ident '.' ident '.' ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + SELECT_LEX *sel= lex->current_select; + const char* schema= (thd->client_capabilities & CLIENT_NO_SCHEMA ? + NullS : $1.str); + if (sel->no_table_names_allowed) + { + my_error(ER_TABLENAME_NOT_ALLOWED_HERE, + MYF(0), $3.str, thd->where); + } + if ((sel->parsing_place != IN_HAVING) || + (sel->get_in_sum_expr() > 0)) + { + $$= new (thd->mem_root) Item_field(Lex->current_context(), + schema, + $3.str, $5.str); + } + else + { + $$= new (thd->mem_root) Item_ref(Lex->current_context(), + schema, + $3.str, $5.str); + } + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +field_ident: + ident { $$=$1;} + | ident '.' ident '.' ident + { + TABLE_LIST *table= (TABLE_LIST*) Select->table_list.first; + if (my_strcasecmp(table_alias_charset, $1.str, table->db)) + { + my_error(ER_WRONG_DB_NAME, MYF(0), $1.str); + MYSQL_YYABORT; + } + if (my_strcasecmp(table_alias_charset, $3.str, + table->table_name)) + { + my_error(ER_WRONG_TABLE_NAME, MYF(0), $3.str); + MYSQL_YYABORT; + } + $$=$5; + } + | ident '.' ident + { + TABLE_LIST *table= (TABLE_LIST*) Select->table_list.first; + if (my_strcasecmp(table_alias_charset, $1.str, table->alias)) + { + my_error(ER_WRONG_TABLE_NAME, MYF(0), $1.str); + MYSQL_YYABORT; + } + $$=$3; + } + | '.' ident { $$=$2;} /* For Delphi */ + ; + +table_ident: + ident + { + $$= new Table_ident($1); + if ($$ == NULL) + MYSQL_YYABORT; + } + | ident '.' ident + { + $$= new Table_ident(YYTHD, $1,$3,0); + if ($$ == NULL) + MYSQL_YYABORT; + } + | '.' ident + { + /* For Delphi */ + $$= new Table_ident($2); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +table_ident_nodb: + ident + { + LEX_STRING db={(char*) any_db,3}; + $$= new Table_ident(YYTHD, db,$1,0); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +IDENT_sys: + IDENT { $$= $1; } + | IDENT_QUOTED + { + THD *thd= YYTHD; + + if (thd->charset_is_system_charset) + { + CHARSET_INFO *cs= system_charset_info; + int dummy_error; + uint wlen= cs->cset->well_formed_len(cs, $1.str, + $1.str+$1.length, + $1.length, &dummy_error); + if (wlen < $1.length) + { + my_error(ER_INVALID_CHARACTER_STRING, MYF(0), + cs->csname, $1.str + wlen); + MYSQL_YYABORT; + } + $$= $1; + } + else + { + if (thd->convert_string(&$$, system_charset_info, + $1.str, $1.length, thd->charset())) + MYSQL_YYABORT; + } + } + ; + +TEXT_STRING_sys: + TEXT_STRING + { + THD *thd= YYTHD; + + if (thd->charset_is_system_charset) + $$= $1; + else + { + if (thd->convert_string(&$$, system_charset_info, + $1.str, $1.length, thd->charset())) + MYSQL_YYABORT; + } + } + ; + +TEXT_STRING_literal: + TEXT_STRING + { + THD *thd= YYTHD; + + if (thd->charset_is_collation_connection) + $$= $1; + else + { + if (thd->convert_string(&$$, thd->variables.collation_connection, + $1.str, $1.length, thd->charset())) + MYSQL_YYABORT; + } + } + ; + +TEXT_STRING_filesystem: + TEXT_STRING + { + THD *thd= YYTHD; + + if (thd->charset_is_character_set_filesystem) + $$= $1; + else + { + if (thd->convert_string(&$$, + thd->variables.character_set_filesystem, + $1.str, $1.length, thd->charset())) + MYSQL_YYABORT; + } + } + ; + +ident: + IDENT_sys { $$=$1; } + | keyword + { + THD *thd= YYTHD; + $$.str= thd->strmake($1.str, $1.length); + if ($$.str == NULL) + MYSQL_YYABORT; + $$.length= $1.length; + } + ; + +label_ident: + IDENT_sys { $$=$1; } + | keyword_sp + { + THD *thd= YYTHD; + $$.str= thd->strmake($1.str, $1.length); + if ($$.str == NULL) + MYSQL_YYABORT; + $$.length= $1.length; + } + ; + +ident_or_text: + ident { $$=$1;} + | TEXT_STRING_sys { $$=$1;} + | LEX_HOSTNAME { $$=$1;} + ; + +user: + ident_or_text + { + THD *thd= YYTHD; + if (!($$=(LEX_USER*) thd->alloc(sizeof(st_lex_user)))) + MYSQL_YYABORT; + $$->user = $1; + $$->host.str= (char *) "%"; + $$->host.length= 1; + + if (check_string_char_length(&$$->user, ER(ER_USERNAME), + USERNAME_CHAR_LENGTH, + system_charset_info, 0)) + MYSQL_YYABORT; + } + | ident_or_text '@' ident_or_text + { + THD *thd= YYTHD; + if (!($$=(LEX_USER*) thd->alloc(sizeof(st_lex_user)))) + MYSQL_YYABORT; + $$->user = $1; $$->host=$3; + + if (check_string_char_length(&$$->user, ER(ER_USERNAME), + USERNAME_CHAR_LENGTH, + system_charset_info, 0) || + check_host_name(&$$->host)) + MYSQL_YYABORT; + } + | CURRENT_USER optional_braces + { + if (!($$=(LEX_USER*) YYTHD->alloc(sizeof(st_lex_user)))) + MYSQL_YYABORT; + /* + empty LEX_USER means current_user and + will be handled in the get_current_user() function + later + */ + bzero($$, sizeof(LEX_USER)); + } + ; + +/* Keyword that we allow for identifiers (except SP labels) */ +keyword: + keyword_sp {} + | ASCII_SYM {} + | BACKUP_SYM {} + | BEGIN_SYM {} + | BYTE_SYM {} + | CACHE_SYM {} + | CHARSET {} + | CHECKSUM_SYM {} + | CLOSE_SYM {} + | COMMENT_SYM {} + | COMMIT_SYM {} + | CONTAINS_SYM {} + | DEALLOCATE_SYM {} + | DO_SYM {} + | END {} + | EXECUTE_SYM {} + | FLUSH_SYM {} + | HANDLER_SYM {} + | HELP_SYM {} + | HOST_SYM {} + | INSTALL_SYM {} + | LANGUAGE_SYM {} + | NO_SYM {} + | OPEN_SYM {} + | OPTIONS_SYM {} + | OWNER_SYM {} + | PARSER_SYM {} + | PARTITION_SYM {} + | PORT_SYM {} + | PREPARE_SYM {} + | REMOVE_SYM {} + | REPAIR {} + | RESET_SYM {} + | RESTORE_SYM {} + | ROLLBACK_SYM {} + | SAVEPOINT_SYM {} + | SECURITY_SYM {} + | SERVER_SYM {} + | SIGNED_SYM {} + | SOCKET_SYM {} + | SLAVE {} + | SONAME_SYM {} + | START_SYM {} + | STOP_SYM {} + | TRUNCATE_SYM {} + | UNICODE_SYM {} + | UNINSTALL_SYM {} + | WRAPPER_SYM {} + | XA_SYM {} + | UPGRADE_SYM {} + ; + +/* + * Keywords that we allow for labels in SPs. + * Anything that's the beginning of a statement or characteristics + * must be in keyword above, otherwise we get (harmful) shift/reduce + * conflicts. + */ +keyword_sp: + ACTION {} + | ADDDATE_SYM {} + | AFTER_SYM {} + | AGAINST {} + | AGGREGATE_SYM {} + | ALGORITHM_SYM {} + | ANY_SYM {} + | AT_SYM {} + | AUTHORS_SYM {} + | AUTO_INC {} + | AUTOEXTEND_SIZE_SYM {} + | AVG_ROW_LENGTH {} + | AVG_SYM {} + | BINLOG_SYM {} + | BIT_SYM {} + | BLOCK_SYM {} + | BOOL_SYM {} + | BOOLEAN_SYM {} + | BTREE_SYM {} + | CASCADED {} + | CHAIN_SYM {} + | CHANGED {} + | CIPHER_SYM {} + | CLIENT_SYM {} + | COALESCE {} + | CODE_SYM {} + | COLLATION_SYM {} + | COLUMNS {} + | COMMITTED_SYM {} + | COMPACT_SYM {} + | COMPLETION_SYM {} + | COMPRESSED_SYM {} + | CONCURRENT {} + | CONNECTION_SYM {} + | CONSISTENT_SYM {} + | CONTEXT_SYM {} + | CONTRIBUTORS_SYM {} + | CPU_SYM {} + | CUBE_SYM {} + | DATA_SYM {} + | DATAFILE_SYM {} + | DATETIME {} + | DATE_SYM {} + | DAY_SYM {} + | DEFINER_SYM {} + | DELAY_KEY_WRITE_SYM {} + | DES_KEY_FILE {} + | DIRECTORY_SYM {} + | DISABLE_SYM {} + | DISCARD {} + | DISK_SYM {} + | DUMPFILE {} + | DUPLICATE_SYM {} + | DYNAMIC_SYM {} + | ENDS_SYM {} + | ENUM {} + | ENGINE_SYM {} + | ENGINES_SYM {} + | ERRORS {} + | ESCAPE_SYM {} + | EVENT_SYM {} + | EVENTS_SYM {} + | EVERY_SYM {} + | EXPANSION_SYM {} + | EXTENDED_SYM {} + | EXTENT_SIZE_SYM {} + | FAULTS_SYM {} + | FAST_SYM {} + | FOUND_SYM {} + | ENABLE_SYM {} + | FULL {} + | FILE_SYM {} + | FIRST_SYM {} + | FIXED_SYM {} + | FRAC_SECOND_SYM {} + | GEOMETRY_SYM {} + | GEOMETRYCOLLECTION {} + | GET_FORMAT {} + | GRANTS {} + | GLOBAL_SYM {} + | HASH_SYM {} + | HOSTS_SYM {} + | HOUR_SYM {} + | IDENTIFIED_SYM {} + | INVOKER_SYM {} + | IMPORT {} + | INDEXES {} + | INITIAL_SIZE_SYM {} + | IO_SYM {} + | IPC_SYM {} + | ISOLATION {} + | ISSUER_SYM {} + | INNOBASE_SYM {} + | INSERT_METHOD {} + | KEY_BLOCK_SIZE {} + | LAST_SYM {} + | LEAVES {} + | LESS_SYM {} + | LEVEL_SYM {} + | LINESTRING {} + | LIST_SYM {} + | LOCAL_SYM {} + | LOCKS_SYM {} + | LOGFILE_SYM {} + | LOGS_SYM {} + | MAX_ROWS {} + | MASTER_SYM {} + | MASTER_HOST_SYM {} + | MASTER_PORT_SYM {} + | MASTER_LOG_FILE_SYM {} + | MASTER_LOG_POS_SYM {} + | MASTER_USER_SYM {} + | MASTER_PASSWORD_SYM {} + | MASTER_SERVER_ID_SYM {} + | MASTER_CONNECT_RETRY_SYM {} + | MASTER_SSL_SYM {} + | MASTER_SSL_CA_SYM {} + | MASTER_SSL_CAPATH_SYM {} + | MASTER_SSL_CERT_SYM {} + | MASTER_SSL_CIPHER_SYM {} + | MASTER_SSL_KEY_SYM {} + | MAX_CONNECTIONS_PER_HOUR {} + | MAX_QUERIES_PER_HOUR {} + | MAX_SIZE_SYM {} + | MAX_UPDATES_PER_HOUR {} + | MAX_USER_CONNECTIONS_SYM {} + | MAX_VALUE_SYM {} + | MEDIUM_SYM {} + | MEMORY_SYM {} + | MERGE_SYM {} + | MICROSECOND_SYM {} + | MIGRATE_SYM {} + | MINUTE_SYM {} + | MIN_ROWS {} + | MODIFY_SYM {} + | MODE_SYM {} + | MONTH_SYM {} + | MULTILINESTRING {} + | MULTIPOINT {} + | MULTIPOLYGON {} + | MUTEX_SYM {} + | NAME_SYM {} + | NAMES_SYM {} + | NATIONAL_SYM {} + | NCHAR_SYM {} + | NDBCLUSTER_SYM {} + | NEXT_SYM {} + | NEW_SYM {} + | NO_WAIT_SYM {} + | NODEGROUP_SYM {} + | NONE_SYM {} + | NVARCHAR_SYM {} + | OFFSET_SYM {} + | OLD_PASSWORD {} + | ONE_SHOT_SYM {} + | ONE_SYM {} + | PACK_KEYS_SYM {} + | PAGE_SYM {} + | PARTIAL {} + | PARTITIONING_SYM {} + | PARTITIONS_SYM {} + | PASSWORD {} + | PHASE_SYM {} + | PLUGIN_SYM {} + | PLUGINS_SYM {} + | POINT_SYM {} + | POLYGON {} + | PRESERVE_SYM {} + | PREV_SYM {} + | PRIVILEGES {} + | PROCESS {} + | PROCESSLIST_SYM {} + | PROFILE_SYM {} + | PROFILES_SYM {} + | QUARTER_SYM {} + | QUERY_SYM {} + | QUICK {} + | READ_ONLY_SYM {} + | REBUILD_SYM {} + | RECOVER_SYM {} + | REDO_BUFFER_SIZE_SYM {} + | REDOFILE_SYM {} + | REDUNDANT_SYM {} + | RELAY_LOG_FILE_SYM {} + | RELAY_LOG_POS_SYM {} + | RELAY_THREAD {} + | RELOAD {} + | REORGANIZE_SYM {} + | REPEATABLE_SYM {} + | REPLICATION {} + | RESOURCES {} + | RESUME_SYM {} + | RETURNS_SYM {} + | ROLLUP_SYM {} + | ROUTINE_SYM {} + | ROWS_SYM {} + | ROW_FORMAT_SYM {} + | ROW_SYM {} + | RTREE_SYM {} + | SCHEDULE_SYM {} + | SECOND_SYM {} + | SERIAL_SYM {} + | SERIALIZABLE_SYM {} + | SESSION_SYM {} + | SIMPLE_SYM {} + | SHARE_SYM {} + | SHUTDOWN {} + | SNAPSHOT_SYM {} + | SOUNDS_SYM {} + | SOURCE_SYM {} + | SQL_CACHE_SYM {} + | SQL_BUFFER_RESULT {} + | SQL_NO_CACHE_SYM {} + | INFINIDB_ORDERED_SYM {} + | SQL_THREAD {} + | STARTS_SYM {} + | STATUS_SYM {} + | STORAGE_SYM {} + | STRING_SYM {} + | SUBDATE_SYM {} + | SUBJECT_SYM {} + | SUBPARTITION_SYM {} + | SUBPARTITIONS_SYM {} + | SUPER_SYM {} + | SUSPEND_SYM {} + | SWAPS_SYM {} + | SWITCHES_SYM {} + | TABLES {} + | TABLE_CHECKSUM_SYM {} + | TABLESPACE {} + | TEMPORARY {} + | TEMPTABLE_SYM {} + | TEXT_SYM {} + | THAN_SYM {} + | TRANSACTION_SYM {} + | TRIGGERS_SYM {} + | TIMESTAMP {} + | TIMESTAMP_ADD {} + | TIMESTAMP_DIFF {} + | TIME_SYM {} + | TYPES_SYM {} + | TYPE_SYM {} + | UDF_RETURNS_SYM {} + | FUNCTION_SYM {} + | UNCOMMITTED_SYM {} + | UNDEFINED_SYM {} + | UNDO_BUFFER_SIZE_SYM {} + | UNDOFILE_SYM {} + | UNKNOWN_SYM {} + | UNTIL_SYM {} + | USER {} + | USE_FRM {} + | VARIABLES {} + | VIEW_SYM {} + | VALUE_SYM {} + | WARNINGS {} + | WAIT_SYM {} + | WEEK_SYM {} + | WORK_SYM {} + | X509_SYM {} + | YEAR_SYM {} + ; + +/* Option functions */ + +set: + SET opt_option + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SET_OPTION; + mysql_init_select(lex); + lex->option_type=OPT_SESSION; + lex->var_list.empty(); + lex->one_shot_set= 0; + lex->autocommit= 0; + } + option_value_list + {} + ; + +opt_option: + /* empty */ {} + | OPTION {} + ; + +option_value_list: + option_type_value + | option_value_list ',' option_type_value + ; + +option_type_value: + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + + if (lex->sphead) + { + /* + If we are in SP we want have own LEX for each assignment. + This is mostly because it is hard for several sp_instr_set + and sp_instr_set_trigger instructions share one LEX. + (Well, it is theoretically possible but adds some extra + overhead on preparation for execution stage and IMO less + robust). + + QQ: May be we should simply prohibit group assignments in SP? + */ + lex->sphead->reset_lex(thd); + lex= thd->lex; + + /* Set new LEX as if we at start of set rule. */ + lex->sql_command= SQLCOM_SET_OPTION; + mysql_init_select(lex); + lex->option_type=OPT_SESSION; + lex->var_list.empty(); + lex->one_shot_set= 0; + lex->autocommit= 0; + lex->sphead->m_tmp_query= lip->get_tok_start(); + } + } + ext_option_value + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + + if (lex->sphead) + { + sp_head *sp= lex->sphead; + + if (!lex->var_list.is_empty()) + { + /* + We have assignment to user or system variable or + option setting, so we should construct sp_instr_stmt + for it. + */ + LEX_STRING qbuff; + sp_instr_stmt *i; + + if (!(i= new sp_instr_stmt(sp->instructions(), lex->spcont, + lex))) + MYSQL_YYABORT; + + /* + Extract the query statement from the tokenizer. The + end is either lip->ptr, if there was no lookahead, + lip->tok_end otherwise. + */ + if (yychar == YYEMPTY) + qbuff.length= lip->get_ptr() - sp->m_tmp_query; + else + qbuff.length= lip->get_tok_end() - sp->m_tmp_query; + + if (!(qbuff.str= (char*) alloc_root(thd->mem_root, + qbuff.length + 5))) + MYSQL_YYABORT; + + strmake(strmake(qbuff.str, "SET ", 4), sp->m_tmp_query, + qbuff.length); + qbuff.length+= 4; + i->m_query= qbuff; + if (sp->add_instr(i)) + MYSQL_YYABORT; + } + lex->sphead->restore_lex(thd); + } + } + ; + +option_type: + option_type2 {} + | GLOBAL_SYM { $$=OPT_GLOBAL; } + | LOCAL_SYM { $$=OPT_SESSION; } + | SESSION_SYM { $$=OPT_SESSION; } + ; + +option_type2: + /* empty */ { $$= OPT_DEFAULT; } + | ONE_SHOT_SYM { Lex->one_shot_set= 1; $$= OPT_SESSION; } + ; + +opt_var_type: + /* empty */ { $$=OPT_SESSION; } + | GLOBAL_SYM { $$=OPT_GLOBAL; } + | LOCAL_SYM { $$=OPT_SESSION; } + | SESSION_SYM { $$=OPT_SESSION; } + ; + +opt_var_ident_type: + /* empty */ { $$=OPT_DEFAULT; } + | GLOBAL_SYM '.' { $$=OPT_GLOBAL; } + | LOCAL_SYM '.' { $$=OPT_SESSION; } + | SESSION_SYM '.' { $$=OPT_SESSION; } + ; + +ext_option_value: + sys_option_value + | option_type2 option_value + ; + +sys_option_value: + option_type internal_variable_name equal set_expr_or_default + { + THD *thd= YYTHD; + LEX *lex=Lex; + + if ($2.var == trg_new_row_fake_var) + { + /* We are in trigger and assigning value to field of new row */ + Item *it; + Item_trigger_field *trg_fld; + sp_instr_set_trigger_field *sp_fld; + LINT_INIT(sp_fld); + if ($1) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if ($4) + it= $4; + else + { + /* QQ: Shouldn't this be field's default value ? */ + it= new Item_null(); + } + + DBUG_ASSERT(lex->trg_chistics.action_time == TRG_ACTION_BEFORE && + (lex->trg_chistics.event == TRG_EVENT_INSERT || + lex->trg_chistics.event == TRG_EVENT_UPDATE)); + + trg_fld= new (thd->mem_root) + Item_trigger_field(Lex->current_context(), + Item_trigger_field::NEW_ROW, + $2.base_name.str, + UPDATE_ACL, FALSE); + if (trg_fld == NULL) + MYSQL_YYABORT; + + sp_fld= new sp_instr_set_trigger_field(lex->sphead-> + instructions(), + lex->spcont, + trg_fld, + it, lex); + if (sp_fld == NULL) + MYSQL_YYABORT; + + /* + Let us add this item to list of all Item_trigger_field + objects in trigger. + */ + lex->trg_table_fields.link_in_list((uchar *)trg_fld, + (uchar **) &trg_fld-> + next_trg_field); + + if (lex->sphead->add_instr(sp_fld)) + MYSQL_YYABORT; + } + else if ($2.var) + { /* System variable */ + if ($1) + lex->option_type= $1; + set_var *var= new set_var(lex->option_type, $2.var, + &$2.base_name, $4); + if (var == NULL) + MYSQL_YYABORT; + lex->var_list.push_back(var); + } + else + { + /* An SP local variable */ + sp_pcontext *ctx= lex->spcont; + sp_variable_t *spv; + sp_instr_set *sp_set; + Item *it; + if ($1) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + + spv= ctx->find_variable(&$2.base_name); + + if ($4) + it= $4; + else if (spv->dflt) + it= spv->dflt; + else + { + it= new (thd->mem_root) Item_null(); + if (it == NULL) + MYSQL_YYABORT; + } + sp_set= new sp_instr_set(lex->sphead->instructions(), ctx, + spv->offset, it, spv->type, lex, TRUE); + if (sp_set == NULL || + lex->sphead->add_instr(sp_set)) + MYSQL_YYABORT; + } + } + | option_type TRANSACTION_SYM ISOLATION LEVEL_SYM isolation_types + { + THD *thd= YYTHD; + LEX *lex=Lex; + lex->option_type= $1; + Item *item= new (thd->mem_root) Item_int((int32) $5); + if (item == NULL) + MYSQL_YYABORT; + set_var *var= new set_var(lex->option_type, + find_sys_var(thd, "tx_isolation"), + &null_lex_str, + item); + if (var == NULL) + MYSQL_YYABORT; + lex->var_list.push_back(var); + } + ; + +option_value: + '@' ident_or_text equal expr + { + Item_func_set_user_var *item; + item= new (YYTHD->mem_root) Item_func_set_user_var($2, $4); + if (item == NULL) + MYSQL_YYABORT; + set_var_user *var= new set_var_user(item); + if (var == NULL) + MYSQL_YYABORT; + Lex->var_list.push_back(var); + } + | '@' '@' opt_var_ident_type internal_variable_name equal set_expr_or_default + { + LEX *lex=Lex; + set_var *var= new set_var($3, $4.var, &$4.base_name, $6); + if (var == NULL) + MYSQL_YYABORT; + lex->var_list.push_back(var); + } + | charset old_or_new_charset_name_or_default + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + CHARSET_INFO *cs2; + cs2= $2 ? $2: global_system_variables.character_set_client; + set_var_collation_client *var; + var= new set_var_collation_client(cs2, + thd->variables.collation_database, + cs2); + if (var == NULL) + MYSQL_YYABORT; + lex->var_list.push_back(var); + } + | NAMES_SYM equal expr + { + LEX *lex= Lex; + sp_pcontext *spc= lex->spcont; + LEX_STRING names; + + names.str= (char *)"names"; + names.length= 5; + if (spc && spc->find_variable(&names)) + my_error(ER_SP_BAD_VAR_SHADOW, MYF(0), names.str); + else + my_parse_error(ER(ER_SYNTAX_ERROR)); + + MYSQL_YYABORT; + } + | NAMES_SYM charset_name_or_default opt_collate + { + LEX *lex= Lex; + CHARSET_INFO *cs2; + CHARSET_INFO *cs3; + cs2= $2 ? $2 : global_system_variables.character_set_client; + cs3= $3 ? $3 : cs2; + if (!my_charset_same(cs2, cs3)) + { + my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), + cs3->name, cs2->csname); + MYSQL_YYABORT; + } + set_var_collation_client *var; + var= new set_var_collation_client(cs3, cs3, cs3); + if (var == NULL) + MYSQL_YYABORT; + lex->var_list.push_back(var); + } + | PASSWORD equal text_or_password + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + LEX_USER *user; + sp_pcontext *spc= lex->spcont; + LEX_STRING pw; + + pw.str= (char *)"password"; + pw.length= 8; + if (spc && spc->find_variable(&pw)) + { + my_error(ER_SP_BAD_VAR_SHADOW, MYF(0), pw.str); + MYSQL_YYABORT; + } + if (!(user=(LEX_USER*) thd->alloc(sizeof(LEX_USER)))) + MYSQL_YYABORT; + user->host=null_lex_str; + user->user.str=thd->security_ctx->priv_user; + set_var_password *var= new set_var_password(user, $3); + if (var == NULL) + MYSQL_YYABORT; + thd->lex->var_list.push_back(var); + thd->lex->autocommit= TRUE; + if (lex->sphead) + lex->sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT; + } + | PASSWORD FOR_SYM user equal text_or_password + { + set_var_password *var= new set_var_password($3,$5); + if (var == NULL) + MYSQL_YYABORT; + Lex->var_list.push_back(var); + Lex->autocommit= TRUE; + if (Lex->sphead) + Lex->sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT; + } + ; + +internal_variable_name: + ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + sp_pcontext *spc= lex->spcont; + sp_variable_t *spv; + + /* We have to lookup here since local vars can shadow sysvars */ + if (!spc || !(spv = spc->find_variable(&$1))) + { + /* Not an SP local variable */ + sys_var *tmp=find_sys_var(thd, $1.str, $1.length); + if (!tmp) + MYSQL_YYABORT; + $$.var= tmp; + $$.base_name= null_lex_str; + if (spc && tmp == &sys_autocommit) + { + /* + We don't allow setting AUTOCOMMIT from a stored function + or trigger. + */ + lex->sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT; + } + } + else + { + /* An SP local variable */ + $$.var= NULL; + $$.base_name= $1; + } + } + | ident '.' ident + { + LEX *lex= Lex; + if (check_reserved_words(&$1)) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + if (lex->sphead && lex->sphead->m_type == TYPE_ENUM_TRIGGER && + (!my_strcasecmp(system_charset_info, $1.str, "NEW") || + !my_strcasecmp(system_charset_info, $1.str, "OLD"))) + { + if ($1.str[0]=='O' || $1.str[0]=='o') + { + my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "OLD", ""); + MYSQL_YYABORT; + } + if (lex->trg_chistics.event == TRG_EVENT_DELETE) + { + my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), + "NEW", "on DELETE"); + MYSQL_YYABORT; + } + if (lex->trg_chistics.action_time == TRG_ACTION_AFTER) + { + my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "NEW", "after "); + MYSQL_YYABORT; + } + /* This special combination will denote field of NEW row */ + $$.var= trg_new_row_fake_var; + $$.base_name= $3; + } + else + { + sys_var *tmp=find_sys_var(YYTHD, $3.str, $3.length); + if (!tmp) + MYSQL_YYABORT; + if (!tmp->is_struct()) + my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), $3.str); + $$.var= tmp; + $$.base_name= $1; + } + } + | DEFAULT '.' ident + { + sys_var *tmp=find_sys_var(YYTHD, $3.str, $3.length); + if (!tmp) + MYSQL_YYABORT; + if (!tmp->is_struct()) + my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), $3.str); + $$.var= tmp; + $$.base_name.str= (char*) "default"; + $$.base_name.length= 7; + } + ; + +isolation_types: + READ_SYM UNCOMMITTED_SYM { $$= ISO_READ_UNCOMMITTED; } + | READ_SYM COMMITTED_SYM { $$= ISO_READ_COMMITTED; } + | REPEATABLE_SYM READ_SYM { $$= ISO_REPEATABLE_READ; } + | SERIALIZABLE_SYM { $$= ISO_SERIALIZABLE; } + ; + +text_or_password: + TEXT_STRING { $$=$1.str;} + | PASSWORD '(' TEXT_STRING ')' + { + $$= $3.length ? YYTHD->variables.old_passwords ? + Item_func_old_password::alloc(YYTHD, $3.str, $3.length) : + Item_func_password::alloc(YYTHD, $3.str, $3.length) : + $3.str; + if ($$ == NULL) + MYSQL_YYABORT; + } + | OLD_PASSWORD '(' TEXT_STRING ')' + { + $$= $3.length ? Item_func_old_password::alloc(YYTHD, $3.str, + $3.length) : + $3.str; + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + + +set_expr_or_default: + expr { $$=$1; } + | DEFAULT { $$=0; } + | ON + { + $$=new (YYTHD->mem_root) Item_string("ON", 2, system_charset_info); + if ($$ == NULL) + MYSQL_YYABORT; + } + | ALL + { + $$=new (YYTHD->mem_root) Item_string("ALL", 3, system_charset_info); + if ($$ == NULL) + MYSQL_YYABORT; + } + | BINARY + { + $$=new (YYTHD->mem_root) Item_string("binary", 6, system_charset_info); + if ($$ == NULL) + MYSQL_YYABORT; + } + ; + +/* Lock function */ + +lock: + LOCK_SYM table_or_tables + { + LEX *lex= Lex; + + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "LOCK"); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_LOCK_TABLES; + } + table_lock_list + {} + ; + +table_or_tables: + TABLE_SYM + | TABLES + ; + +table_lock_list: + table_lock + | table_lock_list ',' table_lock + ; + +table_lock: + table_ident opt_table_alias lock_option + { + thr_lock_type lock_type= (thr_lock_type) $3; + if (!Select->add_table_to_list(YYTHD, $1, $2, 0, lock_type)) + MYSQL_YYABORT; + /* If table is to be write locked, protect from a impending GRL. */ + if (lock_type >= TL_WRITE_ALLOW_WRITE) + Lex->protect_against_global_read_lock= TRUE; + } + ; + +lock_option: + READ_SYM { $$= TL_READ_NO_INSERT; } + | WRITE_SYM { $$= TL_WRITE_DEFAULT; } + | LOW_PRIORITY WRITE_SYM { $$= TL_WRITE_LOW_PRIORITY; } + | READ_SYM LOCAL_SYM { $$= TL_READ; } + ; + +unlock: + UNLOCK_SYM + { + LEX *lex= Lex; + + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "UNLOCK"); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_UNLOCK_TABLES; + } + table_or_tables + {} + ; + +/* +** Handler: direct access to ISAM functions +*/ + +handler: + HANDLER_SYM table_ident OPEN_SYM opt_table_alias + { + LEX *lex= Lex; + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "HANDLER"); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_HA_OPEN; + if (!lex->current_select->add_table_to_list(lex->thd, $2, $4, 0)) + MYSQL_YYABORT; + } + | HANDLER_SYM table_ident_nodb CLOSE_SYM + { + LEX *lex= Lex; + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "HANDLER"); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_HA_CLOSE; + if (!lex->current_select->add_table_to_list(lex->thd, $2, 0, 0)) + MYSQL_YYABORT; + } + | HANDLER_SYM table_ident_nodb READ_SYM + { + LEX *lex=Lex; + if (lex->sphead) + { + my_error(ER_SP_BADSTATEMENT, MYF(0), "HANDLER"); + MYSQL_YYABORT; + } + lex->expr_allows_subselect= FALSE; + lex->sql_command = SQLCOM_HA_READ; + lex->ha_rkey_mode= HA_READ_KEY_EXACT; /* Avoid purify warnings */ + Item *one= new (YYTHD->mem_root) Item_int((int32) 1); + if (one == NULL) + MYSQL_YYABORT; + lex->current_select->select_limit= one; + lex->current_select->offset_limit= 0; + if (!lex->current_select->add_table_to_list(lex->thd, $2, 0, 0)) + MYSQL_YYABORT; + } + handler_read_or_scan where_clause opt_limit_clause + { + Lex->expr_allows_subselect= TRUE; + } + ; + +handler_read_or_scan: + handler_scan_function { Lex->ident= null_lex_str; } + | ident handler_rkey_function { Lex->ident= $1; } + ; + +handler_scan_function: + FIRST_SYM { Lex->ha_read_mode = RFIRST; } + | NEXT_SYM { Lex->ha_read_mode = RNEXT; } + ; + +handler_rkey_function: + FIRST_SYM { Lex->ha_read_mode = RFIRST; } + | NEXT_SYM { Lex->ha_read_mode = RNEXT; } + | PREV_SYM { Lex->ha_read_mode = RPREV; } + | LAST_SYM { Lex->ha_read_mode = RLAST; } + | handler_rkey_mode + { + LEX *lex=Lex; + lex->ha_read_mode = RKEY; + lex->ha_rkey_mode=$1; + if (!(lex->insert_list = new List_item)) + MYSQL_YYABORT; + } + '(' values ')' + {} + ; + +handler_rkey_mode: + EQ { $$=HA_READ_KEY_EXACT; } + | GE { $$=HA_READ_KEY_OR_NEXT; } + | LE { $$=HA_READ_KEY_OR_PREV; } + | GT_SYM { $$=HA_READ_AFTER_KEY; } + | LT { $$=HA_READ_BEFORE_KEY; } + ; + +/* GRANT / REVOKE */ + +revoke: + REVOKE clear_privileges revoke_command + {} + ; + +revoke_command: + grant_privileges ON opt_table grant_ident FROM grant_list + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_REVOKE; + lex->type= 0; + } + | grant_privileges ON FUNCTION_SYM grant_ident FROM grant_list + { + LEX *lex= Lex; + if (lex->columns.elements) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_REVOKE; + lex->type= TYPE_ENUM_FUNCTION; + } + | grant_privileges ON PROCEDURE grant_ident FROM grant_list + { + LEX *lex= Lex; + if (lex->columns.elements) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_REVOKE; + lex->type= TYPE_ENUM_PROCEDURE; + } + | ALL opt_privileges ',' GRANT OPTION FROM grant_list + { + Lex->sql_command = SQLCOM_REVOKE_ALL; + } + ; + +grant: + GRANT clear_privileges grant_command + {} + ; + +grant_command: + grant_privileges ON opt_table grant_ident TO_SYM grant_list + require_clause grant_options + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_GRANT; + lex->type= 0; + } + | grant_privileges ON FUNCTION_SYM grant_ident TO_SYM grant_list + require_clause grant_options + { + LEX *lex= Lex; + if (lex->columns.elements) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_GRANT; + lex->type= TYPE_ENUM_FUNCTION; + } + | grant_privileges ON PROCEDURE grant_ident TO_SYM grant_list + require_clause grant_options + { + LEX *lex= Lex; + if (lex->columns.elements) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + lex->sql_command= SQLCOM_GRANT; + lex->type= TYPE_ENUM_PROCEDURE; + } + ; + +opt_table: + /* Empty */ + | TABLE_SYM + ; + +grant_privileges: + object_privilege_list {} + | ALL opt_privileges + { + Lex->all_privileges= 1; + Lex->grant= GLOBAL_ACLS; + } + ; + +opt_privileges: + /* empty */ + | PRIVILEGES + ; + +object_privilege_list: + object_privilege + | object_privilege_list ',' object_privilege + ; + +object_privilege: + SELECT_SYM + { Lex->which_columns = SELECT_ACL;} + opt_column_list {} + | INSERT + { Lex->which_columns = INSERT_ACL;} + opt_column_list {} + | UPDATE_SYM + { Lex->which_columns = UPDATE_ACL; } + opt_column_list {} + | REFERENCES + { Lex->which_columns = REFERENCES_ACL;} + opt_column_list {} + | DELETE_SYM { Lex->grant |= DELETE_ACL;} + | USAGE {} + | INDEX_SYM { Lex->grant |= INDEX_ACL;} + | ALTER { Lex->grant |= ALTER_ACL;} + | CREATE { Lex->grant |= CREATE_ACL;} + | DROP { Lex->grant |= DROP_ACL;} + | EXECUTE_SYM { Lex->grant |= EXECUTE_ACL;} + | RELOAD { Lex->grant |= RELOAD_ACL;} + | SHUTDOWN { Lex->grant |= SHUTDOWN_ACL;} + | PROCESS { Lex->grant |= PROCESS_ACL;} + | FILE_SYM { Lex->grant |= FILE_ACL;} + | GRANT OPTION { Lex->grant |= GRANT_ACL;} + | SHOW DATABASES { Lex->grant |= SHOW_DB_ACL;} + | SUPER_SYM { Lex->grant |= SUPER_ACL;} + | CREATE TEMPORARY TABLES { Lex->grant |= CREATE_TMP_ACL;} + | LOCK_SYM TABLES { Lex->grant |= LOCK_TABLES_ACL; } + | REPLICATION SLAVE { Lex->grant |= REPL_SLAVE_ACL; } + | REPLICATION CLIENT_SYM { Lex->grant |= REPL_CLIENT_ACL; } + | CREATE VIEW_SYM { Lex->grant |= CREATE_VIEW_ACL; } + | SHOW VIEW_SYM { Lex->grant |= SHOW_VIEW_ACL; } + | CREATE ROUTINE_SYM { Lex->grant |= CREATE_PROC_ACL; } + | ALTER ROUTINE_SYM { Lex->grant |= ALTER_PROC_ACL; } + | CREATE USER { Lex->grant |= CREATE_USER_ACL; } + | EVENT_SYM { Lex->grant |= EVENT_ACL;} + | TRIGGER_SYM { Lex->grant |= TRIGGER_ACL; } + ; + +opt_and: + /* empty */ {} + | AND_SYM {} + ; + +require_list: + require_list_element opt_and require_list + | require_list_element + ; + +require_list_element: + SUBJECT_SYM TEXT_STRING + { + LEX *lex=Lex; + if (lex->x509_subject) + { + my_error(ER_DUP_ARGUMENT, MYF(0), "SUBJECT"); + MYSQL_YYABORT; + } + lex->x509_subject=$2.str; + } + | ISSUER_SYM TEXT_STRING + { + LEX *lex=Lex; + if (lex->x509_issuer) + { + my_error(ER_DUP_ARGUMENT, MYF(0), "ISSUER"); + MYSQL_YYABORT; + } + lex->x509_issuer=$2.str; + } + | CIPHER_SYM TEXT_STRING + { + LEX *lex=Lex; + if (lex->ssl_cipher) + { + my_error(ER_DUP_ARGUMENT, MYF(0), "CIPHER"); + MYSQL_YYABORT; + } + lex->ssl_cipher=$2.str; + } + ; + +grant_ident: + '*' + { + LEX *lex= Lex; + size_t dummy; + if (lex->copy_db_to(&lex->current_select->db, &dummy)) + MYSQL_YYABORT; + if (lex->grant == GLOBAL_ACLS) + lex->grant = DB_ACLS & ~GRANT_ACL; + else if (lex->columns.elements) + { + my_message(ER_ILLEGAL_GRANT_FOR_TABLE, + ER(ER_ILLEGAL_GRANT_FOR_TABLE), MYF(0)); + MYSQL_YYABORT; + } + } + | ident '.' '*' + { + LEX *lex= Lex; + lex->current_select->db = $1.str; + if (lex->grant == GLOBAL_ACLS) + lex->grant = DB_ACLS & ~GRANT_ACL; + else if (lex->columns.elements) + { + my_message(ER_ILLEGAL_GRANT_FOR_TABLE, + ER(ER_ILLEGAL_GRANT_FOR_TABLE), MYF(0)); + MYSQL_YYABORT; + } + } + | '*' '.' '*' + { + LEX *lex= Lex; + lex->current_select->db = NULL; + if (lex->grant == GLOBAL_ACLS) + lex->grant= GLOBAL_ACLS & ~GRANT_ACL; + else if (lex->columns.elements) + { + my_message(ER_ILLEGAL_GRANT_FOR_TABLE, + ER(ER_ILLEGAL_GRANT_FOR_TABLE), MYF(0)); + MYSQL_YYABORT; + } + } + | table_ident + { + LEX *lex=Lex; + if (!lex->current_select->add_table_to_list(lex->thd, $1,NULL, + TL_OPTION_UPDATING)) + MYSQL_YYABORT; + if (lex->grant == GLOBAL_ACLS) + lex->grant = TABLE_ACLS & ~GRANT_ACL; + } + ; + +user_list: + user + { + if (Lex->users_list.push_back($1)) + MYSQL_YYABORT; + } + | user_list ',' user + { + if (Lex->users_list.push_back($3)) + MYSQL_YYABORT; + } + ; + +grant_list: + grant_user + { + if (Lex->users_list.push_back($1)) + MYSQL_YYABORT; + } + | grant_list ',' grant_user + { + if (Lex->users_list.push_back($3)) + MYSQL_YYABORT; + } + ; + +grant_user: + user IDENTIFIED_SYM BY TEXT_STRING + { + $$=$1; $1->password=$4; + if ($4.length) + { + if (YYTHD->variables.old_passwords) + { + char *buff= + (char *) YYTHD->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH_323+1); + if (buff == NULL) + MYSQL_YYABORT; + my_make_scrambled_password_323(buff, $4.str, $4.length); + $1->password.str= buff; + $1->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH_323; + } + else + { + char *buff= + (char *) YYTHD->alloc(SCRAMBLED_PASSWORD_CHAR_LENGTH+1); + if (buff == NULL) + MYSQL_YYABORT; + my_make_scrambled_password(buff, $4.str, $4.length); + $1->password.str= buff; + $1->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH; + } + } + } + | user IDENTIFIED_SYM BY PASSWORD TEXT_STRING + { $$= $1; $1->password= $5; } + | user + { $$= $1; $1->password= null_lex_str; } + ; + +opt_column_list: + /* empty */ + { + LEX *lex=Lex; + lex->grant |= lex->which_columns; + } + | '(' column_list ')' + ; + +column_list: + column_list ',' column_list_id + | column_list_id + ; + +column_list_id: + ident + { + String *new_str = new (YYTHD->mem_root) String((const char*) $1.str,$1.length,system_charset_info); + if (new_str == NULL) + MYSQL_YYABORT; + List_iterator iter(Lex->columns); + class LEX_COLUMN *point; + LEX *lex=Lex; + while ((point=iter++)) + { + if (!my_strcasecmp(system_charset_info, + point->column.ptr(), new_str->ptr())) + break; + } + lex->grant_tot_col|= lex->which_columns; + if (point) + point->rights |= lex->which_columns; + else + { + LEX_COLUMN *col= new LEX_COLUMN (*new_str,lex->which_columns); + if (col == NULL) + MYSQL_YYABORT; + lex->columns.push_back(col); + } + } + ; + +require_clause: + /* empty */ + | REQUIRE_SYM require_list + { + Lex->ssl_type=SSL_TYPE_SPECIFIED; + } + | REQUIRE_SYM SSL_SYM + { + Lex->ssl_type=SSL_TYPE_ANY; + } + | REQUIRE_SYM X509_SYM + { + Lex->ssl_type=SSL_TYPE_X509; + } + | REQUIRE_SYM NONE_SYM + { + Lex->ssl_type=SSL_TYPE_NONE; + } + ; + +grant_options: + /* empty */ {} + | WITH grant_option_list + ; + +grant_option_list: + grant_option_list grant_option {} + | grant_option {} + ; + +grant_option: + GRANT OPTION { Lex->grant |= GRANT_ACL;} + | MAX_QUERIES_PER_HOUR ulong_num + { + LEX *lex=Lex; + lex->mqh.questions=$2; + lex->mqh.specified_limits|= USER_RESOURCES::QUERIES_PER_HOUR; + } + | MAX_UPDATES_PER_HOUR ulong_num + { + LEX *lex=Lex; + lex->mqh.updates=$2; + lex->mqh.specified_limits|= USER_RESOURCES::UPDATES_PER_HOUR; + } + | MAX_CONNECTIONS_PER_HOUR ulong_num + { + LEX *lex=Lex; + lex->mqh.conn_per_hour= $2; + lex->mqh.specified_limits|= USER_RESOURCES::CONNECTIONS_PER_HOUR; + } + | MAX_USER_CONNECTIONS_SYM ulong_num + { + LEX *lex=Lex; + lex->mqh.user_conn= $2; + lex->mqh.specified_limits|= USER_RESOURCES::USER_CONNECTIONS; + } + ; + +begin: + BEGIN_SYM + { + LEX *lex=Lex; + lex->sql_command = SQLCOM_BEGIN; + lex->start_transaction_opt= 0; + } + opt_work {} + ; + +opt_work: + /* empty */ {} + | WORK_SYM {} + ; + +opt_chain: + /* empty */ + { $$= (YYTHD->variables.completion_type == 1); } + | AND_SYM NO_SYM CHAIN_SYM { $$=0; } + | AND_SYM CHAIN_SYM { $$=1; } + ; + +opt_release: + /* empty */ + { $$= (YYTHD->variables.completion_type == 2); } + | RELEASE_SYM { $$=1; } + | NO_SYM RELEASE_SYM { $$=0; } +; + +opt_savepoint: + /* empty */ {} + | SAVEPOINT_SYM {} + ; + +commit: + COMMIT_SYM opt_work opt_chain opt_release + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_COMMIT; + lex->tx_chain= $3; + lex->tx_release= $4; + } + ; + +rollback: + ROLLBACK_SYM opt_work opt_chain opt_release + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_ROLLBACK; + lex->tx_chain= $3; + lex->tx_release= $4; + } + | ROLLBACK_SYM opt_work + TO_SYM opt_savepoint ident + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_ROLLBACK_TO_SAVEPOINT; + lex->ident= $5; + } + ; + +savepoint: + SAVEPOINT_SYM ident + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_SAVEPOINT; + lex->ident= $2; + } + ; + +release: + RELEASE_SYM SAVEPOINT_SYM ident + { + LEX *lex=Lex; + lex->sql_command= SQLCOM_RELEASE_SAVEPOINT; + lex->ident= $3; + } + ; + +/* + UNIONS : glue selects together +*/ + + +union_clause: + /* empty */ {} + | union_list + ; + +union_list: + UNION_SYM union_option + { + LEX *lex=Lex; + if (lex->result && + (lex->result->get_nest_level() == -1 || + lex->result->get_nest_level() == lex->nest_level)) + { + /* + Only the last SELECT can have INTO unless the INTO and UNION + are at different nest levels. In version 5.1 and above, INTO + will onle be allowed at top level. + */ + my_error(ER_WRONG_USAGE, MYF(0), "UNION", "INTO"); + MYSQL_YYABORT; + } + if (lex->current_select->linkage == GLOBAL_OPTIONS_TYPE) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + /* This counter shouldn't be incremented for UNION parts */ + Lex->nest_level--; + if (mysql_new_select(lex, 0)) + MYSQL_YYABORT; + mysql_init_select(lex); + lex->current_select->linkage=UNION_TYPE; + if ($2) /* UNION DISTINCT - remember position */ + lex->current_select->master_unit()->union_distinct= + lex->current_select; + } + select_init + { + /* + Remove from the name resolution context stack the context of the + last select in the union. + */ + Lex->pop_context(); + } + ; + +union_opt: + /* Empty */ { $$= 0; } + | union_list { $$= 1; } + | union_order_or_limit { $$= 1; } + ; + +union_order_or_limit: + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + DBUG_ASSERT(lex->current_select->linkage != GLOBAL_OPTIONS_TYPE); + SELECT_LEX *sel= lex->current_select; + SELECT_LEX_UNIT *unit= sel->master_unit(); + SELECT_LEX *fake= unit->fake_select_lex; + if (fake) + { + unit->global_parameters= fake; + fake->no_table_names_allowed= 1; + lex->current_select= fake; + } + thd->where= "global ORDER clause"; + } + order_or_limit + { + THD *thd= YYTHD; + thd->lex->current_select->no_table_names_allowed= 0; + thd->where= ""; + } + ; + +order_or_limit: + order_clause opt_limit_clause_init + | limit_clause + ; + +union_option: + /* empty */ { $$=1; } + | DISTINCT { $$=1; } + | ALL { $$=0; } + ; + +take_first_select: /* empty */ + { + $$= Lex->current_select->master_unit()->first_select(); + }; + +subselect: + SELECT_SYM subselect_start select_init2 take_first_select + subselect_end + { + $$= $4; + } + | '(' subselect_start select_paren take_first_select + subselect_end ')' + { + $$= $4; + }; + +subselect_start: + { + LEX *lex=Lex; + if (!lex->expr_allows_subselect || + lex->sql_command == (int)SQLCOM_PURGE) + { + my_parse_error(ER(ER_SYNTAX_ERROR)); + MYSQL_YYABORT; + } + /* + we are making a "derived table" for the parenthesis + as we need to have a lex level to fit the union + after the parenthesis, e.g. + (SELECT .. ) UNION ... becomes + SELECT * FROM ((SELECT ...) UNION ...) + */ + if (mysql_new_select(Lex, 1)) + MYSQL_YYABORT; + } + ; + +subselect_end: + { + LEX *lex=Lex; + /* + Set the required lock level for the tables associated with the + current sub-select. This will overwrite previous lock options set + using st_select_lex::add_table_to_list in any of the following + rules: single_multi, table_wild_one, load_data, table_alias_ref, + table_factor. + The default lock level is TL_READ_DEFAULT but it can be modified + with query options specific for a certain (sub-)SELECT. + */ + lex->current_select-> + set_lock_for_tables(lex->current_select->lock_option); + + lex->pop_context(); + SELECT_LEX *child= lex->current_select; + lex->current_select = lex->current_select->return_after_parsing(); + lex->nest_level--; + lex->current_select->n_child_sum_items += child->n_sum_items; + /* + A subselect can add fields to an outer select. Reserve space for + them. + */ + lex->current_select->select_n_where_fields+= + child->select_n_where_fields; + } + ; + +/************************************************************************** + + CREATE VIEW | TRIGGER | PROCEDURE statements. + +**************************************************************************/ + +view_or_trigger_or_sp_or_event: + definer definer_tail + {} + | no_definer no_definer_tail + {} + | view_replace_or_algorithm definer_opt view_tail + {} + ; + +definer_tail: + view_tail + | trigger_tail + | sp_tail + | sf_tail + | event_tail + ; + +no_definer_tail: + view_tail + | trigger_tail + | sp_tail + | sf_tail + | udf_tail + | event_tail + ; + +/************************************************************************** + + DEFINER clause support. + +**************************************************************************/ + +definer_opt: + no_definer + | definer + ; + +no_definer: + /* empty */ + { + /* + We have to distinguish missing DEFINER-clause from case when + CURRENT_USER specified as definer explicitly in order to properly + handle CREATE TRIGGER statements which come to replication thread + from older master servers (i.e. to create non-suid trigger in this + case). + */ + YYTHD->lex->definer= 0; + } + ; + +definer: + DEFINER_SYM EQ user + { + YYTHD->lex->definer= get_current_user(YYTHD, $3); + } + ; + +/************************************************************************** + + CREATE VIEW statement parts. + +**************************************************************************/ + +view_replace_or_algorithm: + view_replace + {} + | view_replace view_algorithm + {} + | view_algorithm + {} + ; + +view_replace: + OR_SYM REPLACE + { Lex->create_view_mode= VIEW_CREATE_OR_REPLACE; } + ; + +view_algorithm: + ALGORITHM_SYM EQ UNDEFINED_SYM + { Lex->create_view_algorithm= VIEW_ALGORITHM_UNDEFINED; } + | ALGORITHM_SYM EQ MERGE_SYM + { Lex->create_view_algorithm= VIEW_ALGORITHM_MERGE; } + | ALGORITHM_SYM EQ TEMPTABLE_SYM + { Lex->create_view_algorithm= VIEW_ALGORITHM_TMPTABLE; } + ; + +view_suid: + /* empty */ + { Lex->create_view_suid= VIEW_SUID_DEFAULT; } + | SQL_SYM SECURITY_SYM DEFINER_SYM + { Lex->create_view_suid= VIEW_SUID_DEFINER; } + | SQL_SYM SECURITY_SYM INVOKER_SYM + { Lex->create_view_suid= VIEW_SUID_INVOKER; } + ; + +view_tail: + view_suid VIEW_SYM table_ident + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + lex->sql_command= SQLCOM_CREATE_VIEW; + /* first table in list is target VIEW name */ + if (!lex->select_lex.add_table_to_list(thd, $3, NULL, TL_OPTION_UPDATING)) + MYSQL_YYABORT; + } + view_list_opt AS view_select + ; + +view_list_opt: + /* empty */ + {} + | '(' view_list ')' + ; + +view_list: + ident + { + Lex->view_list.push_back((LEX_STRING*) + sql_memdup(&$1, sizeof(LEX_STRING))); + } + | view_list ',' ident + { + Lex->view_list.push_back((LEX_STRING*) + sql_memdup(&$3, sizeof(LEX_STRING))); + } + ; + +view_select: + { + LEX *lex= Lex; + lex->parsing_options.allows_variable= FALSE; + lex->parsing_options.allows_select_into= FALSE; + lex->parsing_options.allows_select_procedure= FALSE; + lex->parsing_options.allows_derived= FALSE; + lex->create_view_select.str= (char *) YYLIP->get_cpp_ptr(); + } + view_select_aux view_check_option + { + THD *thd= YYTHD; + LEX *lex= Lex; + uint len= YYLIP->get_cpp_ptr() - lex->create_view_select.str; + void *create_view_select= thd->memdup(lex->create_view_select.str, len); + lex->create_view_select.length= len; + lex->create_view_select.str= (char *) create_view_select; + trim_whitespace(thd->charset(), &lex->create_view_select); + lex->parsing_options.allows_variable= TRUE; + lex->parsing_options.allows_select_into= TRUE; + lex->parsing_options.allows_select_procedure= TRUE; + lex->parsing_options.allows_derived= TRUE; + } + ; + +view_select_aux: + SELECT_SYM select_init2 + | '(' select_paren ')' union_opt + ; + +view_check_option: + /* empty */ + { Lex->create_view_check= VIEW_CHECK_NONE; } + | WITH CHECK_SYM OPTION + { Lex->create_view_check= VIEW_CHECK_CASCADED; } + | WITH CASCADED CHECK_SYM OPTION + { Lex->create_view_check= VIEW_CHECK_CASCADED; } + | WITH LOCAL_SYM CHECK_SYM OPTION + { Lex->create_view_check= VIEW_CHECK_LOCAL; } + ; + +/************************************************************************** + + CREATE TRIGGER statement parts. + +**************************************************************************/ + +trigger_tail: + TRIGGER_SYM + remember_name + sp_name + trg_action_time + trg_event + ON + remember_name /* $7 */ + { /* $8 */ + Lex->raw_trg_on_table_name_begin= YYLIP->get_tok_start(); + } + table_ident /* $9 */ + FOR_SYM + remember_name /* $11 */ + { /* $12 */ + Lex->raw_trg_on_table_name_end= YYLIP->get_tok_start(); + } + EACH_SYM + ROW_SYM + { /* $15 */ + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + sp_head *sp; + + if (lex->sphead) + { + my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), "TRIGGER"); + MYSQL_YYABORT; + } + + if (!(sp= new sp_head())) + MYSQL_YYABORT; + sp->reset_thd_mem_root(thd); + sp->init(lex); + sp->m_type= TYPE_ENUM_TRIGGER; + sp->init_sp_name(thd, $3); + lex->stmt_definition_begin= $2; + lex->ident.str= $7; + lex->ident.length= $11 - $7; + + lex->sphead= sp; + lex->spname= $3; + + bzero((char *)&lex->sp_chistics, sizeof(st_sp_chistics)); + lex->sphead->m_chistics= &lex->sp_chistics; + lex->sphead->set_body_start(thd, lip->get_cpp_ptr()); + } + sp_proc_stmt /* $16 */ + { /* $17 */ + LEX *lex= Lex; + sp_head *sp= lex->sphead; + + lex->sql_command= SQLCOM_CREATE_TRIGGER; + sp->set_stmt_end(YYTHD); + sp->restore_thd_mem_root(YYTHD); + + if (sp->is_not_allowed_in_function("trigger")) + MYSQL_YYABORT; + + /* + We have to do it after parsing trigger body, because some of + sp_proc_stmt alternatives are not saving/restoring LEX, so + lex->query_tables can be wiped out. + */ + if (!lex->select_lex.add_table_to_list(YYTHD, $9, + (LEX_STRING*) 0, + TL_OPTION_UPDATING, + TL_IGNORE)) + MYSQL_YYABORT; + } + ; + +/************************************************************************** + + CREATE FUNCTION | PROCEDURE statements parts. + +**************************************************************************/ + +udf_tail: + AGGREGATE_SYM remember_name FUNCTION_SYM ident + RETURNS_SYM udf_type SONAME_SYM TEXT_STRING_sys + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + if (is_native_function(thd, & $4)) + { + my_error(ER_NATIVE_FCT_NAME_COLLISION, MYF(0), + $4.str); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_CREATE_FUNCTION; + lex->udf.type= UDFTYPE_AGGREGATE; + lex->stmt_definition_begin= $2; + lex->udf.name = $4; + lex->udf.returns=(Item_result) $6; + lex->udf.dl=$8.str; + } + | remember_name FUNCTION_SYM ident + RETURNS_SYM udf_type SONAME_SYM TEXT_STRING_sys + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + if (is_native_function(thd, & $3)) + { + my_error(ER_NATIVE_FCT_NAME_COLLISION, MYF(0), + $3.str); + MYSQL_YYABORT; + } + lex->sql_command = SQLCOM_CREATE_FUNCTION; + lex->udf.type= UDFTYPE_FUNCTION; + lex->stmt_definition_begin= $1; + lex->udf.name = $3; + lex->udf.returns=(Item_result) $5; + lex->udf.dl=$7.str; + } + ; + +sf_tail: + remember_name /* $1 */ + FUNCTION_SYM /* $2 */ + sp_name /* $3 */ + '(' /* $4 */ + { /* $5 */ + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + sp_head *sp; + const char* tmp_param_begin; + + lex->stmt_definition_begin= $1; + lex->spname= $3; + + if (lex->sphead) + { + my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), "FUNCTION"); + MYSQL_YYABORT; + } + /* Order is important here: new - reset - init */ + sp= new sp_head(); + if (sp == NULL) + MYSQL_YYABORT; + sp->reset_thd_mem_root(thd); + sp->init(lex); + sp->init_sp_name(thd, lex->spname); + + sp->m_type= TYPE_ENUM_FUNCTION; + lex->sphead= sp; + + tmp_param_begin= lip->get_cpp_tok_start(); + tmp_param_begin++; + lex->sphead->m_param_begin= tmp_param_begin; + } + sp_fdparam_list /* $6 */ + ')' /* $7 */ + { /* $8 */ + Lex->sphead->m_param_end= YYLIP->get_cpp_tok_start(); + } + RETURNS_SYM /* $9 */ + { /* $10 */ + LEX *lex= Lex; + lex->charset= NULL; + lex->length= lex->dec= NULL; + lex->interval_list.empty(); + lex->type= 0; + } + type /* $11 */ + { /* $12 */ + LEX *lex= Lex; + sp_head *sp= lex->sphead; + /* + This was disabled in 5.1.12. See bug #20701 + When collation support in SP is implemented, then this test + should be removed. + */ + if (($11 == MYSQL_TYPE_STRING || $11 == MYSQL_TYPE_VARCHAR) + && (lex->type & BINCMP_FLAG)) + { + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "return value collation"); + MYSQL_YYABORT; + } + + if (sp->fill_field_definition(YYTHD, lex, + (enum enum_field_types) $11, + &sp->m_return_field_def)) + MYSQL_YYABORT; + + bzero((char *)&lex->sp_chistics, sizeof(st_sp_chistics)); + } + sp_c_chistics /* $13 */ + { /* $14 */ + THD *thd= YYTHD; + LEX *lex= thd->lex; + Lex_input_stream *lip= YYLIP; + + lex->sphead->m_chistics= &lex->sp_chistics; + lex->sphead->set_body_start(thd, lip->get_cpp_tok_start()); + } + sp_proc_stmt /* $15 */ + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + sp_head *sp= lex->sphead; + + if (sp->is_not_allowed_in_function("function")) + MYSQL_YYABORT; + + lex->sql_command= SQLCOM_CREATE_SPFUNCTION; + sp->set_stmt_end(thd); + if (!(sp->m_flags & sp_head::HAS_RETURN)) + { + my_error(ER_SP_NORETURN, MYF(0), sp->m_qname.str); + MYSQL_YYABORT; + } + if (is_native_function(thd, & sp->m_name)) + { + /* + This warning will be printed when + [1] A client query is parsed, + [2] A stored function is loaded by db_load_routine. + Printing the warning for [2] is intentional, to cover the + following scenario: + - A user define a SF 'foo' using MySQL 5.N + - An application uses select foo(), and works. + - MySQL 5.{N+1} defines a new native function 'foo', as + part of a new feature. + - MySQL 5.{N+1} documentation is updated, and should mention + that there is a potential incompatible change in case of + existing stored function named 'foo'. + - The user deploys 5.{N+1}. At this point, 'select foo()' + means something different, and the user code is most likely + broken (it's only safe if the code is 'select db.foo()'). + With a warning printed when the SF is loaded (which has to occur + before the call), the warning will provide a hint explaining + the root cause of a later failure of 'select foo()'. + With no warning printed, the user code will fail with no + apparent reason. + Printing a warning each time db_load_routine is executed for + an ambiguous function is annoying, since that can happen a lot, + but in practice should not happen unless there *are* name + collisions. + If a collision exists, it should not be silenced but fixed. + */ + push_warning_printf(thd, + MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_NATIVE_FCT_NAME_COLLISION, + ER(ER_NATIVE_FCT_NAME_COLLISION), + sp->m_name.str); + } + sp->restore_thd_mem_root(thd); + } + ; + +sp_tail: + PROCEDURE remember_name sp_name + { + LEX *lex= Lex; + sp_head *sp; + + if (lex->sphead) + { + my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), "PROCEDURE"); + MYSQL_YYABORT; + } + + lex->stmt_definition_begin= $2; + + /* Order is important here: new - reset - init */ + sp= new sp_head(); + if (sp == NULL) + MYSQL_YYABORT; + sp->reset_thd_mem_root(YYTHD); + sp->init(lex); + sp->m_type= TYPE_ENUM_PROCEDURE; + sp->init_sp_name(YYTHD, $3); + + lex->sphead= sp; + } + '(' + { + const char* tmp_param_begin; + + tmp_param_begin= YYLIP->get_cpp_tok_start(); + tmp_param_begin++; + Lex->sphead->m_param_begin= tmp_param_begin; + } + sp_pdparam_list + ')' + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + + lex->sphead->m_param_end= YYLIP->get_cpp_tok_start(); + bzero((char *)&lex->sp_chistics, sizeof(st_sp_chistics)); + } + sp_c_chistics + { + THD *thd= YYTHD; + LEX *lex= thd->lex; + + lex->sphead->m_chistics= &lex->sp_chistics; + lex->sphead->set_body_start(thd, YYLIP->get_cpp_tok_start()); + } + sp_proc_stmt + { + LEX *lex= Lex; + sp_head *sp= lex->sphead; + + sp->set_stmt_end(YYTHD); + lex->sql_command= SQLCOM_CREATE_PROCEDURE; + sp->restore_thd_mem_root(YYTHD); + } + ; + +/*************************************************************************/ + +xa: + XA_SYM begin_or_start xid opt_join_or_resume + { + Lex->sql_command = SQLCOM_XA_START; + } + | XA_SYM END xid opt_suspend + { + Lex->sql_command = SQLCOM_XA_END; + } + | XA_SYM PREPARE_SYM xid + { + Lex->sql_command = SQLCOM_XA_PREPARE; + } + | XA_SYM COMMIT_SYM xid opt_one_phase + { + Lex->sql_command = SQLCOM_XA_COMMIT; + } + | XA_SYM ROLLBACK_SYM xid + { + Lex->sql_command = SQLCOM_XA_ROLLBACK; + } + | XA_SYM RECOVER_SYM + { + Lex->sql_command = SQLCOM_XA_RECOVER; + } + ; + +xid: + text_string + { + MYSQL_YYABORT_UNLESS($1->length() <= MAXGTRIDSIZE); + if (!(Lex->xid=(XID *)YYTHD->alloc(sizeof(XID)))) + MYSQL_YYABORT; + Lex->xid->set(1L, $1->ptr(), $1->length(), 0, 0); + } + | text_string ',' text_string + { + MYSQL_YYABORT_UNLESS($1->length() <= MAXGTRIDSIZE && $3->length() <= MAXBQUALSIZE); + if (!(Lex->xid=(XID *)YYTHD->alloc(sizeof(XID)))) + MYSQL_YYABORT; + Lex->xid->set(1L, $1->ptr(), $1->length(), $3->ptr(), $3->length()); + } + | text_string ',' text_string ',' ulong_num + { + MYSQL_YYABORT_UNLESS($1->length() <= MAXGTRIDSIZE && $3->length() <= MAXBQUALSIZE); + if (!(Lex->xid=(XID *)YYTHD->alloc(sizeof(XID)))) + MYSQL_YYABORT; + Lex->xid->set($5, $1->ptr(), $1->length(), $3->ptr(), $3->length()); + } + ; + +begin_or_start: + BEGIN_SYM {} + | START_SYM {} + ; + +opt_join_or_resume: + /* nothing */ { Lex->xa_opt=XA_NONE; } + | JOIN_SYM { Lex->xa_opt=XA_JOIN; } + | RESUME_SYM { Lex->xa_opt=XA_RESUME; } + ; + +opt_one_phase: + /* nothing */ { Lex->xa_opt=XA_NONE; } + | ONE_SYM PHASE_SYM { Lex->xa_opt=XA_ONE_PHASE; } + ; + +opt_suspend: + /* nothing */ + { Lex->xa_opt=XA_NONE; } + | SUSPEND_SYM + { Lex->xa_opt=XA_SUSPEND; } + opt_migrate + ; + +opt_migrate: + /* nothing */ {} + | FOR_SYM MIGRATE_SYM { Lex->xa_opt=XA_FOR_MIGRATE; } + ; + +install: + INSTALL_SYM PLUGIN_SYM ident SONAME_SYM TEXT_STRING_sys + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_INSTALL_PLUGIN; + lex->comment= $3; + lex->ident= $5; + } + ; + +uninstall: + UNINSTALL_SYM PLUGIN_SYM ident + { + LEX *lex= Lex; + lex->sql_command= SQLCOM_UNINSTALL_PLUGIN; + lex->comment= $3; + } + ; + +/** + @} (end of group Parser) +*/ diff --git a/dbcon/mysql/table.h b/dbcon/mysql/table.h new file mode 100644 index 00000000..5ed76844 --- /dev/null +++ b/dbcon/mysql/table.h @@ -0,0 +1,1742 @@ +/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + + +/* Structs that defines the TABLE */ + +class Item; /* Needed by ORDER */ +class Item_subselect; +class Item_field; +class GRANT_TABLE; +class st_select_lex_unit; +class st_select_lex; +class partition_info; +class COND_EQUAL; +class Security_context; + +/*************************************************************************/ + +/** + View_creation_ctx -- creation context of view objects. +*/ + +class View_creation_ctx : public Default_object_creation_ctx, + public Sql_alloc +{ +public: + static View_creation_ctx *create(THD *thd); + + static View_creation_ctx *create(THD *thd, + TABLE_LIST *view); + +private: + View_creation_ctx(THD *thd) + : Default_object_creation_ctx(thd) + { } +}; + +/*************************************************************************/ + +/* Order clause list element */ + +typedef struct st_order { + struct st_order *next; + Item **item; /* Point at item in select fields */ + Item *item_ptr; /* Storage for initial item */ + Item **item_copy; /* For SPs; the original item ptr */ + int counter; /* position in SELECT list, correct + only if counter_used is true*/ + bool asc; /* true if ascending */ + bool free_me; /* true if item isn't shared */ + bool in_field_list; /* true if in select field list */ + bool counter_used; /* parameter was counter of columns */ + Field *field; /* If tmp-table group */ + char *buff; /* If tmp-table group */ + table_map used, depend_map; +} ORDER; + +/** + @brief The current state of the privilege checking process for the current + user, SQL statement and SQL object. + + @details The privilege checking process is divided into phases depending on + the level of the privilege to be checked and the type of object to be + accessed. Due to the mentioned scattering of privilege checking + functionality, it is necessary to keep track of the state of the + process. This information is stored in privilege, want_privilege, and + orig_want_privilege. + + A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant + members are grant_table and version. + */ +typedef struct st_grant_info +{ + /** + @brief A copy of the privilege information regarding the current host, + database, object and user. + + @details The version of this copy is found in GRANT_INFO::version. + */ + GRANT_TABLE *grant_table; + /** + @brief Used for cache invalidation when caching privilege information. + + @details The privilege information is stored on disk, with dedicated + caches residing in memory: table-level and column-level privileges, + respectively, have their own dedicated caches. + + The GRANT_INFO works as a level 1 cache with this member updated to the + current value of the global variable @c grant_version (@c static variable + in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from + the level 2 cache. The level 2 cache is the @c column_priv_hash structure + (@c static variable in sql_acl.cc) + + @see grant_version + */ + uint version; + /** + @brief The set of privileges that the current user has fulfilled for a + certain host, database, and object. + + @details This field is continually updated throughout the access checking + process. In each step the "wanted privilege" is checked against the + fulfilled privileges. When/if the intersection of these sets is empty, + access is granted. + + The set is implemented as a bitmap, with the bits defined in sql_acl.h. + */ + ulong privilege; + /** + @brief the set of privileges that the current user needs to fulfil in + order to carry out the requested operation. + */ + ulong want_privilege; + /** + Stores the requested access acl of top level tables list. Is used to + check access rights to the underlying tables of a view. + */ + ulong orig_want_privilege; +} GRANT_INFO; + +enum tmp_table_type +{ + NO_TMP_TABLE, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE, + INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE +}; + +/** Event on which trigger is invoked. */ +enum trg_event_type +{ + TRG_EVENT_INSERT= 0, + TRG_EVENT_UPDATE= 1, + TRG_EVENT_DELETE= 2, + TRG_EVENT_MAX +}; + +enum frm_type_enum +{ + FRMTYPE_ERROR= 0, + FRMTYPE_TABLE, + FRMTYPE_VIEW +}; + +enum release_type { RELEASE_NORMAL, RELEASE_WAIT_FOR_DROP }; + +typedef struct st_filesort_info +{ + IO_CACHE *io_cache; /* If sorted through filesort */ + uchar **sort_keys; /* Buffer for sorting keys */ + uchar *buffpek; /* Buffer for buffpek structures */ + uint buffpek_len; /* Max number of buffpeks in the buffer */ + uchar *addon_buf; /* Pointer to a buffer if sorted with fields */ + size_t addon_length; /* Length of the buffer */ + struct st_sort_addon_field *addon_field; /* Pointer to the fields info */ + void (*unpack)(struct st_sort_addon_field *, uchar *); /* To unpack back */ + uchar *record_pointers; /* If sorted in memory */ + ha_rows found_records; /* How many records in sort */ +} FILESORT_INFO; + + +/* + Values in this enum are used to indicate how a tables TIMESTAMP field + should be treated. It can be set to the current timestamp on insert or + update or both. + WARNING: The values are used for bit operations. If you change the + enum, you must keep the bitwise relation of the values. For example: + (int) TIMESTAMP_AUTO_SET_ON_BOTH must be equal to + (int) TIMESTAMP_AUTO_SET_ON_INSERT | (int) TIMESTAMP_AUTO_SET_ON_UPDATE. + We use an enum here so that the debugger can display the value names. +*/ +enum timestamp_auto_set_type +{ + TIMESTAMP_NO_AUTO_SET= 0, TIMESTAMP_AUTO_SET_ON_INSERT= 1, + TIMESTAMP_AUTO_SET_ON_UPDATE= 2, TIMESTAMP_AUTO_SET_ON_BOTH= 3 +}; +#define clear_timestamp_auto_bits(_target_, _bits_) \ + (_target_)= (enum timestamp_auto_set_type)((int)(_target_) & ~(int)(_bits_)) + +class Field_timestamp; +class Field_blob; +class Table_triggers_list; + +/** + Category of table found in the table share. +*/ +enum enum_table_category +{ + /** + Unknown value. + */ + TABLE_UNKNOWN_CATEGORY=0, + + /** + Temporary table. + The table is visible only in the session. + Therefore, + - FLUSH TABLES WITH READ LOCK + - SET GLOBAL READ_ONLY = ON + do not apply to this table. + Note that LOCK TABLE t FOR READ/WRITE + can be used on temporary tables. + Temporary tables are not part of the table cache. + */ + TABLE_CATEGORY_TEMPORARY=1, + + /** + User table. + These tables do honor: + - LOCK TABLE t FOR READ/WRITE + - FLUSH TABLES WITH READ LOCK + - SET GLOBAL READ_ONLY = ON + User tables are cached in the table cache. + */ + TABLE_CATEGORY_USER=2, + + /** + System table, maintained by the server. + These tables do honor: + - LOCK TABLE t FOR READ/WRITE + - FLUSH TABLES WITH READ LOCK + - SET GLOBAL READ_ONLY = ON + Typically, writes to system tables are performed by + the server implementation, not explicitly be a user. + System tables are cached in the table cache. + */ + TABLE_CATEGORY_SYSTEM=3, + + /** + Information schema tables. + These tables are an interface provided by the system + to inspect the system metadata. + These tables do *not* honor: + - LOCK TABLE t FOR READ/WRITE + - FLUSH TABLES WITH READ LOCK + - SET GLOBAL READ_ONLY = ON + as there is no point in locking explicitely + an INFORMATION_SCHEMA table. + Nothing is directly written to information schema tables. + Note that this value is not used currently, + since information schema tables are not shared, + but implemented as session specific temporary tables. + */ + /* + TODO: Fixing the performance issues of I_S will lead + to I_S tables in the table cache, which should use + this table type. + */ + TABLE_CATEGORY_INFORMATION=4, + + /** + Performance schema tables. + These tables are an interface provided by the system + to inspect the system performance data. + These tables do *not* honor: + - LOCK TABLE t FOR READ/WRITE + - FLUSH TABLES WITH READ LOCK + - SET GLOBAL READ_ONLY = ON + as there is no point in locking explicitely + a PERFORMANCE_SCHEMA table. + An example of PERFORMANCE_SCHEMA tables are: + - mysql.slow_log + - mysql.general_log, + which *are* updated even when there is either + a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect. + User queries do not write directly to these tables + (there are exceptions for log tables). + The server implementation perform writes. + Performance tables are cached in the table cache. + */ + TABLE_CATEGORY_PERFORMANCE=5 +}; +typedef enum enum_table_category TABLE_CATEGORY; + +TABLE_CATEGORY get_table_category(const LEX_STRING *db, + const LEX_STRING *name); + +/* + This structure is shared between different table objects. There is one + instance of table share per one table in the database. +*/ + +typedef struct st_table_share +{ + st_table_share() {} /* Remove gcc warning */ + + /** Category of this table. */ + TABLE_CATEGORY table_category; + + /* hash of field names (contains pointers to elements of field array) */ + HASH name_hash; /* hash of field names */ + MEM_ROOT mem_root; + TYPELIB keynames; /* Pointers to keynames */ + TYPELIB fieldnames; /* Pointer to fieldnames */ + TYPELIB *intervals; /* pointer to interval info */ + pthread_mutex_t mutex; /* For locking the share */ + pthread_cond_t cond; /* To signal that share is ready */ + struct st_table_share *next, /* Link to unused shares */ + **prev; +#ifdef NOT_YET + struct st_table *open_tables; /* link to open tables */ +#endif + + /* The following is copied to each TABLE on OPEN */ + Field **field; + Field **found_next_number_field; + Field *timestamp_field; /* Used only during open */ + KEY *key_info; /* data of keys in database */ + uint *blob_field; /* Index to blobs in Field arrray*/ + + uchar *default_values; /* row with default values */ + LEX_STRING comment; /* Comment about table */ + CHARSET_INFO *table_charset; /* Default charset of string fields */ + + MY_BITMAP all_set; + /* + Key which is used for looking-up table in table cache and in the list + of thread's temporary tables. Has the form of: + "database_name\0table_name\0" + optional part for temporary tables. + + Note that all three 'table_cache_key', 'db' and 'table_name' members + must be set (and be non-zero) for tables in table cache. They also + should correspond to each other. + To ensure this one can use set_table_cache() methods. + */ + LEX_STRING table_cache_key; + LEX_STRING db; /* Pointer to db */ + LEX_STRING table_name; /* Table name (for open) */ + LEX_STRING path; /* Path to .frm file (from datadir) */ + LEX_STRING normalized_path; /* unpack_filename(path) */ + LEX_STRING connect_string; + + /* + Set of keys in use, implemented as a Bitmap. + Excludes keys disabled by ALTER TABLE ... DISABLE KEYS. + */ + key_map keys_in_use; + key_map keys_for_keyread; + ha_rows min_rows, max_rows; /* create information */ + ulong avg_row_length; /* create information */ + ulong raid_chunksize; + ulong version, mysql_version; + ulong timestamp_offset; /* Set to offset+1 of record */ + ulong reclength; /* Recordlength */ + + plugin_ref db_plugin; /* storage engine plugin */ + inline handlerton *db_type() const /* table_type for handler */ + { + // DBUG_ASSERT(db_plugin); + return db_plugin ? plugin_data(db_plugin, handlerton*) : NULL; + } + enum row_type row_type; /* How rows are stored */ + enum tmp_table_type tmp_table; + enum enum_ha_unused unused1; + enum enum_ha_unused unused2; + + uint ref_count; /* How many TABLE objects uses this */ + uint open_count; /* Number of tables in open list */ + uint blob_ptr_size; /* 4 or 8 */ + uint key_block_size; /* create key_block_size, if used */ + uint null_bytes, last_null_bit_pos; + uint fields; /* Number of fields */ + uint rec_buff_length; /* Size of table->record[] buffer */ + uint keys, key_parts; + uint max_key_length, max_unique_length, total_key_length; + uint uniques; /* Number of UNIQUE index */ + uint null_fields; /* number of null fields */ + uint blob_fields; /* number of blob fields */ + uint timestamp_field_offset; /* Field number for timestamp field */ + uint varchar_fields; /* number of varchar fields */ + uint db_create_options; /* Create options from database */ + uint db_options_in_use; /* Options in use */ + uint db_record_offset; /* if HA_REC_IN_SEQ */ + uint raid_type, raid_chunks; + uint rowid_field_offset; /* Field_nr +1 to rowid field */ + /* Index of auto-updated TIMESTAMP field in field array */ + uint primary_key; + uint next_number_index; /* autoincrement key number */ + uint next_number_key_offset; /* autoinc keypart offset in a key */ + uint next_number_keypart; /* autoinc keypart number in a key */ + uint error, open_errno, errarg; /* error from open_table_def() */ + uint column_bitmap_size; + uchar frm_version; + bool null_field_first; + bool system; /* Set if system table (one record) */ + bool crypted; /* If .frm file is crypted */ + bool db_low_byte_first; /* Portable row format */ + bool crashed; + bool is_view; + bool name_lock, replace_with_name_lock; + bool waiting_on_cond; /* Protection against free */ + ulong table_map_id; /* for row-based replication */ + ulonglong table_map_version; + + /* + Cache for row-based replication table share checks that does not + need to be repeated. Possible values are: -1 when cache value is + not calculated yet, 0 when table *shall not* be replicated, 1 when + table *may* be replicated. + */ + int cached_row_logging_check; + +#ifdef WITH_PARTITION_STORAGE_ENGINE + /** @todo: Move into *ha_data for partitioning */ + bool auto_partitioned; + const char *partition_info; + uint partition_info_len; + uint partition_info_buffer_size; + const char *part_state; + uint part_state_len; + handlerton *default_part_db_type; +#endif + + /** place to store storage engine specific data */ + void *ha_data; + + + /* + Set share's table cache key and update its db and table name appropriately. + + SYNOPSIS + set_table_cache_key() + key_buff Buffer with already built table cache key to be + referenced from share. + key_length Key length. + + NOTES + Since 'key_buff' buffer will be referenced from share it should has same + life-time as share itself. + This method automatically ensures that TABLE_SHARE::table_name/db have + appropriate values by using table cache key as their source. + */ + + void set_table_cache_key(char *key_buff, uint key_length) + { + table_cache_key.str= key_buff; + table_cache_key.length= key_length; + /* + Let us use the fact that the key is "db/0/table_name/0" + optional + part for temporary tables. + */ + db.str= table_cache_key.str; + db.length= strlen(db.str); + table_name.str= db.str + db.length + 1; + table_name.length= strlen(table_name.str); + } + + + /* + Set share's table cache key and update its db and table name appropriately. + + SYNOPSIS + set_table_cache_key() + key_buff Buffer to be used as storage for table cache key + (should be at least key_length bytes). + key Value for table cache key. + key_length Key length. + + NOTE + Since 'key_buff' buffer will be used as storage for table cache key + it should has same life-time as share itself. + */ + + void set_table_cache_key(char *key_buff, const char *key, uint key_length) + { + memcpy(key_buff, key, key_length); + set_table_cache_key(key_buff, key_length); + } + + inline bool honor_global_locks() + { + return ((table_category == TABLE_CATEGORY_USER) + || (table_category == TABLE_CATEGORY_SYSTEM)); + } + + inline bool require_write_privileges() + { + return (table_category == TABLE_CATEGORY_PERFORMANCE); + } + + inline ulong get_table_def_version() + { + return table_map_id; + } + + /** + Convert unrelated members of TABLE_SHARE to one enum + representing its type. + + @todo perhaps we need to have a member instead of a function. + */ + enum enum_table_ref_type get_table_ref_type() const + { + if (is_view) + return TABLE_REF_VIEW; + switch (tmp_table) { + case NO_TMP_TABLE: + return TABLE_REF_BASE_TABLE; + case SYSTEM_TMP_TABLE: + return TABLE_REF_I_S_TABLE; + default: + return TABLE_REF_TMP_TABLE; + } + } + /** + Return a table metadata version. + * for base tables, we return table_map_id. + It is assigned from a global counter incremented for each + new table loaded into the table definition cache (TDC). + * for temporary tables it's table_map_id again. But for + temporary tables table_map_id is assigned from + thd->query_id. The latter is assigned from a thread local + counter incremented for every new SQL statement. Since + temporary tables are thread-local, each temporary table + gets a unique id. + * for everything else (views, information schema tables), + the version id is zero. + + This choice of version id is a large compromise + to have a working prepared statement validation in 5.1. In + future version ids will be persistent, as described in WL#4180. + + Let's try to explain why and how this limited solution allows + to validate prepared statements. + + Firstly, sets (in mathematical sense) of version numbers + never intersect for different table types. Therefore, + version id of a temporary table is never compared with + a version id of a view, and vice versa. + + Secondly, for base tables, we know that each DDL flushes the + respective share from the TDC. This ensures that whenever + a table is altered or dropped and recreated, it gets a new + version id. + Unfortunately, since elements of the TDC are also flushed on + LRU basis, this choice of version ids leads to false positives. + E.g. when the TDC size is too small, we may have a SELECT + * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which + in turn will lead to a validation error and a subsequent + reprepare of all prepared statements. This is + considered acceptable, since as long as prepared statements are + automatically reprepared, spurious invalidation is only + a performance hit. Besides, no better simple solution exists. + + For temporary tables, using thd->query_id ensures that if + a temporary table was altered or recreated, a new version id is + assigned. This suits validation needs very well and will perhaps + never change. + + Metadata of information schema tables never changes. + Thus we can safely assume 0 for a good enough version id. + + Views are a special and tricky case. A view is always inlined + into the parse tree of a prepared statement at prepare. + Thus, when we execute a prepared statement, the parse tree + will not get modified even if the view is replaced with another + view. Therefore, we can safely choose 0 for version id of + views and effectively never invalidate a prepared statement + when a view definition is altered. Note, that this leads to + wrong binary log in statement-based replication, since we log + prepared statement execution in form Query_log_events + containing conventional statements. But since there is no + metadata locking for views, the very same problem exists for + conventional statements alone, as reported in Bug#25144. The only + difference between prepared and conventional execution is, + effectively, that for prepared statements the race condition + window is much wider. + In 6.0 we plan to support view metadata locking (WL#3726) and + extend table definition cache to cache views (WL#4298). + When this is done, views will be handled in the same fashion + as the base tables. + + Finally, by taking into account table type, we always + track that a change has taken place when a view is replaced + with a base table, a base table is replaced with a temporary + table and so on. + + @sa TABLE_LIST::is_table_ref_id_equal() + */ + ulong get_table_ref_version() const + { + return (tmp_table == SYSTEM_TMP_TABLE || is_view) ? 0 : table_map_id; + } + +} TABLE_SHARE; + + +extern ulong refresh_version; + +/* Information for one open table */ +enum index_hint_type +{ + INDEX_HINT_IGNORE, + INDEX_HINT_USE, + INDEX_HINT_FORCE +}; + +struct st_table { + st_table() {} /* Remove gcc warning */ + + TABLE_SHARE *s; + handler *file; +#ifdef NOT_YET + struct st_table *used_next, **used_prev; /* Link to used tables */ + struct st_table *open_next, **open_prev; /* Link to open tables */ +#endif + struct st_table *next, *prev; + + /* For the below MERGE related members see top comment in ha_myisammrg.cc */ + struct st_table *parent; /* Set in MERGE child. Ptr to parent */ + TABLE_LIST *child_l; /* Set in MERGE parent. List of children */ + TABLE_LIST **child_last_l; /* Set in MERGE parent. End of list */ + + THD *in_use; /* Which thread uses this */ + Field **field; /* Pointer to fields */ + + uchar *record[2]; /* Pointer to records */ + uchar *write_row_record; /* Used as optimisation in + THD::write_row */ + uchar *insert_values; /* used by INSERT ... UPDATE */ + /* + Map of keys that can be used to retrieve all data from this table + needed by the query without reading the row. + */ + key_map covering_keys; + key_map quick_keys, merge_keys; + /* + A set of keys that can be used in the query that references this + table. + + All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be + subtracted from this set upon instantiation. Thus for any TABLE t it holds + that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we + must not introduce any new keys here (see setup_tables). + + The set is implemented as a bitmap. + */ + key_map keys_in_use_for_query; + /* Map of keys that can be used to calculate GROUP BY without sorting */ + key_map keys_in_use_for_group_by; + /* Map of keys that can be used to calculate ORDER BY without sorting */ + key_map keys_in_use_for_order_by; + KEY *key_info; /* data of keys in database */ + + Field *next_number_field; /* Set if next_number is activated */ + Field *found_next_number_field; /* Set on open */ + Field_timestamp *timestamp_field; + + /* Table's triggers, 0 if there are no of them */ + Table_triggers_list *triggers; + TABLE_LIST *pos_in_table_list;/* Element referring to this table */ + ORDER *group; + const char *alias; /* alias or table name */ + uchar *null_flags; + my_bitmap_map *bitmap_init_value; + MY_BITMAP def_read_set, def_write_set, tmp_set; /* containers */ + MY_BITMAP *read_set, *write_set; /* Active column sets */ + /* + The ID of the query that opened and is using this table. Has different + meanings depending on the table type. + + Temporary tables: + + table->query_id is set to thd->query_id for the duration of a statement + and is reset to 0 once it is closed by the same statement. A non-zero + table->query_id means that a statement is using the table even if it's + not the current statement (table is in use by some outer statement). + + Non-temporary tables: + + Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id + for the duration of a statement and is reset to 0 once it is closed by + the same statement. A non-zero query_id is used to control which tables + in the list of pre-opened and locked tables are actually being used. + */ + query_id_t query_id; + + /* + For each key that has quick_keys.is_set(key) == TRUE: estimate of #records + and max #key parts that range access would use. + */ + ha_rows quick_rows[MAX_KEY]; + + /* Bitmaps of key parts that =const for the entire join. */ + key_part_map const_key_parts[MAX_KEY]; + + uint quick_key_parts[MAX_KEY]; + uint quick_n_ranges[MAX_KEY]; + + /* + Estimate of number of records that satisfy SARGable part of the table + condition, or table->file->records if no SARGable condition could be + constructed. + This value is used by join optimizer as an estimate of number of records + that will pass the table condition (condition that depends on fields of + this table and constants) + */ + ha_rows quick_condition_rows; + + /* + If this table has TIMESTAMP field with auto-set property (pointed by + timestamp_field member) then this variable indicates during which + operations (insert only/on update/in both cases) we should set this + field to current timestamp. If there are no such field in this table + or we should not automatically set its value during execution of current + statement then the variable contains TIMESTAMP_NO_AUTO_SET (i.e. 0). + + Value of this variable is set for each statement in open_table() and + if needed cleared later in statement processing code (see mysql_update() + as example). + */ + timestamp_auto_set_type timestamp_field_type; + table_map map; /* ID bit of table (1,2,4,8,16...) */ + + uint lock_position; /* Position in MYSQL_LOCK.table */ + uint lock_data_start; /* Start pos. in MYSQL_LOCK.locks */ + uint lock_count; /* Number of locks */ + uint tablenr,used_fields; + uint temp_pool_slot; /* Used by intern temp tables */ + uint status; /* What's in record[0] */ + uint db_stat; /* mode of file as in handler.h */ + /* number of select if it is derived table */ + uint derived_select_number; + int current_lock; /* Type of lock on table */ + my_bool copy_blobs; /* copy_blobs when storing */ + + /* + 0 or JOIN_TYPE_{LEFT|RIGHT}. Currently this is only compared to 0. + If maybe_null !=0, this table is inner w.r.t. some outer join operation, + and null_row may be true. + */ + uint maybe_null; + /* + If true, the current table row is considered to have all columns set to + NULL, including columns declared as "not null" (see maybe_null). + */ + my_bool null_row; + + /* + TODO: Each of the following flags take up 8 bits. They can just as easily + be put into one single unsigned long and instead of taking up 18 + bytes, it would take up 4. + */ + my_bool force_index; + my_bool distinct,const_table,no_rows; + + /** + If set, the optimizer has found that row retrieval should access index + tree only. + */ + my_bool key_read; + my_bool no_keyread; + /* + Placeholder for an open table which prevents other connections + from taking name-locks on this table. Typically used with + TABLE_SHARE::version member to take an exclusive name-lock on + this table name -- a name lock that not only prevents other + threads from opening the table, but also blocks other name + locks. This is achieved by: + - setting open_placeholder to 1 - this will block other name + locks, as wait_for_locked_table_name will be forced to wait, + see table_is_used for details. + - setting version to 0 - this will force other threads to close + the instance of this table and wait (this is the same approach + as used for usual name locks). + An exclusively name-locked table currently can have no handler + object associated with it (db_stat is always 0), but please do + not rely on that. + */ + my_bool open_placeholder; + my_bool locked_by_logger; + my_bool no_replicate; + my_bool locked_by_name; + my_bool fulltext_searched; + my_bool no_cache; + /* To signal that the table is associated with a HANDLER statement */ + my_bool open_by_handler; + /* + To indicate that a non-null value of the auto_increment field + was provided by the user or retrieved from the current record. + Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode. + */ + my_bool auto_increment_field_not_null; + my_bool insert_or_update; /* Can be used by the handler */ + my_bool alias_name_used; /* true if table_name is alias */ + my_bool get_fields_in_item_tree; /* Signal to fix_field */ + /* If MERGE children attached to parent. See top comment in ha_myisammrg.cc */ + my_bool children_attached; + + REGINFO reginfo; /* field connections */ + MEM_ROOT mem_root; + GRANT_INFO grant; + FILESORT_INFO sort; +#ifdef WITH_PARTITION_STORAGE_ENGINE + partition_info *part_info; /* Partition related information */ + bool no_partitions_used; /* If true, all partitions have been pruned away */ +#endif + + bool fill_item_list(List *item_list) const; + void reset_item_list(List *item_list) const; + void clear_column_bitmaps(void); + void prepare_for_position(void); + void mark_columns_used_by_index_no_reset(uint index, MY_BITMAP *map); + void mark_columns_used_by_index(uint index); + void restore_column_maps_after_mark_index(); + void mark_auto_increment_column(void); + void mark_columns_needed_for_update(void); + void mark_columns_needed_for_delete(void); + void mark_columns_needed_for_insert(void); + // @Infinidb if this is InfiniDB table. + inline bool isInfiniDB() + { +#if (defined(_MSC_VER) && defined(_DEBUG)) || defined(SAFE_MUTEX) + if (s && s->db_plugin && (strcmp((*s->db_plugin)->name.str, "InfiniDB") == 0)) +#else + if (s && s->db_plugin && (strcmp(s->db_plugin->name.str, "InfiniDB") == 0)) +#endif + return true; + return false; + } + inline void column_bitmaps_set(MY_BITMAP *read_set_arg, + MY_BITMAP *write_set_arg) + { + read_set= read_set_arg; + write_set= write_set_arg; + if (file) + file->column_bitmaps_signal(); + } + inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg, + MY_BITMAP *write_set_arg) + { + read_set= read_set_arg; + write_set= write_set_arg; + } + inline void use_all_columns() + { + column_bitmaps_set(&s->all_set, &s->all_set); + } + inline void default_column_bitmaps() + { + read_set= &def_read_set; + write_set= &def_write_set; + } + /* Is table open or should be treated as such by name-locking? */ + inline bool is_name_opened() { return db_stat || open_placeholder; } + /* + Is this instance of the table should be reopen or represents a name-lock? + */ + inline bool needs_reopen_or_name_lock() + { return s->version != refresh_version; } + bool is_children_attached(void); +}; + +enum enum_schema_table_state +{ + NOT_PROCESSED= 0, + PROCESSED_BY_CREATE_SORT_INDEX, + PROCESSED_BY_JOIN_EXEC +}; + +typedef struct st_foreign_key_info +{ + LEX_STRING *forein_id; + LEX_STRING *referenced_db; + LEX_STRING *referenced_table; + LEX_STRING *update_method; + LEX_STRING *delete_method; + LEX_STRING *referenced_key_name; + List foreign_fields; + List referenced_fields; +} FOREIGN_KEY_INFO; + +/* + Make sure that the order of schema_tables and enum_schema_tables are the same. +*/ + +enum enum_schema_tables +{ + SCH_CHARSETS= 0, + SCH_COLLATIONS, + SCH_COLLATION_CHARACTER_SET_APPLICABILITY, + SCH_COLUMNS, + SCH_COLUMN_PRIVILEGES, + SCH_ENGINES, + SCH_EVENTS, + SCH_FILES, + SCH_GLOBAL_STATUS, + SCH_GLOBAL_VARIABLES, + SCH_KEY_COLUMN_USAGE, + SCH_OPEN_TABLES, + SCH_PARTITIONS, + SCH_PLUGINS, + SCH_PROCESSLIST, + SCH_PROFILES, + SCH_REFERENTIAL_CONSTRAINTS, + SCH_PROCEDURES, + SCH_SCHEMATA, + SCH_SCHEMA_PRIVILEGES, + SCH_SESSION_STATUS, + SCH_SESSION_VARIABLES, + SCH_STATISTICS, + SCH_STATUS, + SCH_TABLES, + SCH_TABLE_CONSTRAINTS, + SCH_TABLE_NAMES, + SCH_TABLE_PRIVILEGES, + SCH_TRIGGERS, + SCH_USER_PRIVILEGES, + SCH_VARIABLES, + SCH_VIEWS +}; + + +#define MY_I_S_MAYBE_NULL 1 +#define MY_I_S_UNSIGNED 2 + + +#define SKIP_OPEN_TABLE 0 // do not open table +#define OPEN_FRM_ONLY 1 // open FRM file only +#define OPEN_FULL_TABLE 2 // open FRM,MYD, MYI files + +typedef struct st_field_info +{ + /** + This is used as column name. + */ + const char* field_name; + /** + For string-type columns, this is the maximum number of + characters. Otherwise, it is the 'display-length' for the column. + */ + uint field_length; + /** + This denotes data type for the column. For the most part, there seems to + be one entry in the enum for each SQL data type, although there seem to + be a number of additional entries in the enum. + */ + enum enum_field_types field_type; + int value; + /** + This is used to set column attributes. By default, columns are @c NOT + @c NULL and @c SIGNED, and you can deviate from the default + by setting the appopriate flags. You can use either one of the flags + @c MY_I_S_MAYBE_NULL and @cMY_I_S_UNSIGNED or + combine them using the bitwise or operator @c |. Both flags are + defined in table.h. + */ + uint field_flags; // Field atributes(maybe_null, signed, unsigned etc.) + const char* old_name; + /** + This should be one of @c SKIP_OPEN_TABLE, + @c OPEN_FRM_ONLY or @c OPEN_FULL_TABLE. + */ + uint open_method; +} ST_FIELD_INFO; + + +struct TABLE_LIST; +typedef class Item COND; + +typedef struct st_schema_table +{ + const char* table_name; + ST_FIELD_INFO *fields_info; + /* Create information_schema table */ + TABLE *(*create_table) (THD *thd, TABLE_LIST *table_list); + /* Fill table with data */ + int (*fill_table) (THD *thd, TABLE_LIST *tables, COND *cond); + /* Handle fileds for old SHOW */ + int (*old_format) (THD *thd, struct st_schema_table *schema_table); + int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table, + bool res, LEX_STRING *db_name, LEX_STRING *table_name); + int idx_field1, idx_field2; + bool hidden; + uint i_s_requested_object; /* the object we need to open(TABLE | VIEW) */ +} ST_SCHEMA_TABLE; + + +#define JOIN_TYPE_LEFT 1 +#define JOIN_TYPE_RIGHT 2 + +#define VIEW_ALGORITHM_UNDEFINED 0 +#define VIEW_ALGORITHM_TMPTABLE 1 +#define VIEW_ALGORITHM_MERGE 2 + +#define VIEW_SUID_INVOKER 0 +#define VIEW_SUID_DEFINER 1 +#define VIEW_SUID_DEFAULT 2 + +/* view WITH CHECK OPTION parameter options */ +#define VIEW_CHECK_NONE 0 +#define VIEW_CHECK_LOCAL 1 +#define VIEW_CHECK_CASCADED 2 + +/* result of view WITH CHECK OPTION parameter check */ +#define VIEW_CHECK_OK 0 +#define VIEW_CHECK_ERROR 1 +#define VIEW_CHECK_SKIP 2 + +/** The threshold size a blob field buffer before it is freed */ +#define MAX_TDC_BLOB_SIZE 65536 + +struct st_lex; +class select_union; +class TMP_TABLE_PARAM; + +Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref, + const char *name); + +struct Field_translator +{ + Item *item; + const char *name; +}; + + +/* + Column reference of a NATURAL/USING join. Since column references in + joins can be both from views and stored tables, may point to either a + Field (for tables), or a Field_translator (for views). +*/ + +class Natural_join_column: public Sql_alloc +{ +public: + Field_translator *view_field; /* Column reference of merge view. */ + Item_field *table_field; /* Column reference of table or temp view. */ + TABLE_LIST *table_ref; /* Original base table/view reference. */ + /* + True if a common join column of two NATURAL/USING join operands. Notice + that when we have a hierarchy of nested NATURAL/USING joins, a column can + be common at some level of nesting but it may not be common at higher + levels of nesting. Thus this flag may change depending on at which level + we are looking at some column. + */ + bool is_common; +public: + Natural_join_column(Field_translator *field_param, TABLE_LIST *tab); + Natural_join_column(Item_field *field_param, TABLE_LIST *tab); + const char *name(); + Item *create_item(THD *thd); + Field *field(); + const char *table_name(); + const char *db_name(); + GRANT_INFO *grant(); +}; + + +/* + Table reference in the FROM clause. + + These table references can be of several types that correspond to + different SQL elements. Below we list all types of TABLE_LISTs with + the necessary conditions to determine when a TABLE_LIST instance + belongs to a certain type. + + 1) table (TABLE_LIST::view == NULL) + - base table + (TABLE_LIST::derived == NULL) + - subquery - TABLE_LIST::table is a temp table + (TABLE_LIST::derived != NULL) + - information schema table + (TABLE_LIST::schema_table != NULL) + NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL + 2) view (TABLE_LIST::view != NULL) + - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE) + also (TABLE_LIST::field_translation != NULL) + - tmptable (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TMPTABLE) + also (TABLE_LIST::field_translation == NULL) + 3) nested table reference (TABLE_LIST::nested_join != NULL) + - table sequence - e.g. (t1, t2, t3) + TODO: how to distinguish from a JOIN? + - general JOIN + TODO: how to distinguish from a table sequence? + - NATURAL JOIN + (TABLE_LIST::natural_join != NULL) + - JOIN ... USING + (TABLE_LIST::join_using_fields != NULL) +*/ + +class Index_hint; +struct TABLE_LIST +{ + TABLE_LIST() {} /* Remove gcc warning */ + + /** + Prepare TABLE_LIST that consists of one table instance to use in + simple_open_and_lock_tables + */ + inline void init_one_table(const char *db_name_arg, + const char *table_name_arg, + enum thr_lock_type lock_type_arg) + { + bzero((char*) this, sizeof(*this)); + db= (char*) db_name_arg; + table_name= alias= (char*) table_name_arg; + lock_type= lock_type_arg; + } + + /* + List of tables local to a subquery (used by SQL_LIST). Considers + views as leaves (unlike 'next_leaf' below). Created at parse time + in st_select_lex::add_table_to_list() -> table_list.link_in_list(). + */ + TABLE_LIST *next_local; + /* link in a global list of all queries tables */ + TABLE_LIST *next_global, **prev_global; + char *db, *alias, *table_name, *schema_table_name; + char *option; /* Used by cache index */ + Item *on_expr; /* Used with outer join */ + /* + The structure of ON expression presented in the member above + can be changed during certain optimizations. This member + contains a snapshot of AND-OR structure of the ON expression + made after permanent transformations of the parse tree, and is + used to restore ON clause before every reexecution of a prepared + statement or stored procedure. + */ + Item *prep_on_expr; + COND_EQUAL *cond_equal; /* Used with outer join */ + /* + During parsing - left operand of NATURAL/USING join where 'this' is + the right operand. After parsing (this->natural_join == this) iff + 'this' represents a NATURAL or USING join operation. Thus after + parsing 'this' is a NATURAL/USING join iff (natural_join != NULL). + */ + TABLE_LIST *natural_join; + /* + True if 'this' represents a nested join that is a NATURAL JOIN. + For one of the operands of 'this', the member 'natural_join' points + to the other operand of 'this'. + */ + bool is_natural_join; + /* Field names in a USING clause for JOIN ... USING. */ + List *join_using_fields; + /* + Explicitly store the result columns of either a NATURAL/USING join or + an operand of such a join. + */ + List *join_columns; + /* TRUE if join_columns contains all columns of this table reference. */ + bool is_join_columns_complete; + + /* + List of nodes in a nested join tree, that should be considered as + leaves with respect to name resolution. The leaves are: views, + top-most nodes representing NATURAL/USING joins, subqueries, and + base tables. All of these TABLE_LIST instances contain a + materialized list of columns. The list is local to a subquery. + */ + TABLE_LIST *next_name_resolution_table; + /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */ + List *index_hints; + TABLE *table; /* opened table */ + uint table_id; /* table id (from binlog) for opened table */ + /* + select_result for derived table to pass it from table creation to table + filling procedure + */ + select_union *derived_result; + /* + Reference from aux_tables to local list entry of main select of + multi-delete statement: + delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b; + here it will be reference of first occurrence of t1 to second (as you + can see this lists can't be merged) + */ + TABLE_LIST *correspondent_table; + /** + @brief Normally, this field is non-null for anonymous derived tables only. + + @details This field is set to non-null for + + - Anonymous derived tables, In this case it points to the SELECT_LEX_UNIT + representing the derived table. E.g. for a query + + @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim + + For the @c TABLE_LIST representing the derived table @c b, @c derived + points to the SELECT_LEX_UNIT representing the result of the query within + parenteses. + + - Views. This is set for views with @verbatim ALGORITHM = TEMPTABLE + @endverbatim by mysql_make_view(). + + @note Inside views, a subquery in the @c FROM clause is not allowed. + @note Do not use this field to separate views/base tables/anonymous + derived tables. Use TABLE_LIST::is_anonymous_derived_table(). + */ + st_select_lex_unit *derived; /* SELECT_LEX_UNIT of derived table */ + ST_SCHEMA_TABLE *schema_table; /* Information_schema table */ + st_select_lex *schema_select_lex; + /* + True when the view field translation table is used to convert + schema table fields for backwards compatibility with SHOW command. + */ + bool schema_table_reformed; + TMP_TABLE_PARAM *schema_table_param; + /* link to select_lex where this table was used */ + st_select_lex *select_lex; + st_lex *view; /* link on VIEW lex for merging */ + Field_translator *field_translation; /* array of VIEW fields */ + /* pointer to element after last one in translation table above */ + Field_translator *field_translation_end; + /* + List (based on next_local) of underlying tables of this view. I.e. it + does not include the tables of subqueries used in the view. Is set only + for merged views. + */ + TABLE_LIST *merge_underlying_list; + /* + - 0 for base tables + - in case of the view it is the list of all (not only underlying + tables but also used in subquery ones) tables of the view. + */ + List *view_tables; + /* most upper view this table belongs to */ + TABLE_LIST *belong_to_view; + /* + The view directly referencing this table + (non-zero only for merged underlying tables of a view). + */ + TABLE_LIST *referencing_view; + /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */ + TABLE_LIST *parent_l; + /* + Security context (non-zero only for tables which belong + to view with SQL SECURITY DEFINER) + */ + Security_context *security_ctx; + /* + This view security context (non-zero only for views with + SQL SECURITY DEFINER) + */ + Security_context *view_sctx; + /* + List of all base tables local to a subquery including all view + tables. Unlike 'next_local', this in this list views are *not* + leaves. Created in setup_tables() -> make_leaves_list(). + */ + bool allowed_show; + TABLE_LIST *next_leaf; + Item *where; /* VIEW WHERE clause condition */ + Item *check_option; /* WITH CHECK OPTION condition */ + LEX_STRING select_stmt; /* text of (CREATE/SELECT) statement */ + LEX_STRING md5; /* md5 of query text */ + LEX_STRING source; /* source of CREATE VIEW */ + LEX_STRING view_db; /* saved view database */ + LEX_STRING view_name; /* saved view name */ + LEX_STRING timestamp; /* GMT time stamp of last operation */ + st_lex_user definer; /* definer of view */ + ulonglong file_version; /* version of file's field set */ + ulonglong updatable_view; /* VIEW can be updated */ + /** + @brief The declared algorithm, if this is a view. + @details One of + - VIEW_ALGORITHM_UNDEFINED + - VIEW_ALGORITHM_TMPTABLE + - VIEW_ALGORITHM_MERGE + @to do Replace with an enum + */ + ulonglong algorithm; + ulonglong view_suid; /* view is suid (TRUE dy default) */ + ulonglong with_check; /* WITH CHECK OPTION */ + /* + effective value of WITH CHECK OPTION (differ for temporary table + algorithm) + */ + uint8 effective_with_check; + /** + @brief The view algorithm that is actually used, if this is a view. + @details One of + - VIEW_ALGORITHM_UNDEFINED + - VIEW_ALGORITHM_TMPTABLE + - VIEW_ALGORITHM_MERGE + @to do Replace with an enum + */ + uint8 effective_algorithm; + GRANT_INFO grant; + /* data need by some engines in query cache*/ + ulonglong engine_data; + /* call back function for asking handler about caching in query cache */ + qc_engine_callback callback_func; + thr_lock_type lock_type; + uint outer_join; /* Which join type */ + uint shared; /* Used in multi-upd */ + size_t db_length; + size_t table_name_length; + bool updatable; /* VIEW/TABLE can be updated now */ + bool straight; /* optimize with prev table */ + bool updating; /* for replicate-do/ignore table */ + bool force_index; /* prefer index over table scan */ + bool ignore_leaves; /* preload only non-leaf nodes */ + table_map dep_tables; /* tables the table depends on */ + table_map on_expr_dep_tables; /* tables on expression depends on */ + struct st_nested_join *nested_join; /* if the element is a nested join */ + TABLE_LIST *embedding; /* nested join containing the table */ + List *join_list;/* join list the table belongs to */ + bool cacheable_table; /* stop PS caching */ + /* used in multi-upd/views privilege check */ + bool table_in_first_from_clause; + bool skip_temporary; /* this table shouldn't be temporary */ + /* TRUE if this merged view contain auto_increment field */ + bool contain_auto_increment; + bool multitable_view; /* TRUE iff this is multitable view */ + bool compact_view_format; /* Use compact format for SHOW CREATE VIEW */ + /* view where processed */ + bool where_processed; + /* TRUE <=> VIEW CHECK OPTION expression has been processed */ + bool check_option_processed; + /* FRMTYPE_ERROR if any type is acceptable */ + enum frm_type_enum required_type; + handlerton *db_type; /* table_type for handler */ + char timestamp_buffer[20]; /* buffer for timestamp (19+1) */ + /* + This TABLE_LIST object is just placeholder for prelocking, it will be + used for implicit LOCK TABLES only and won't be used in real statement. + */ + bool prelocking_placeholder; + /* + This TABLE_LIST object corresponds to the table to be created + so it is possible that it does not exist (used in CREATE TABLE + ... SELECT implementation). + */ + bool create; + bool internal_tmp_table; + + + /* View creation context. */ + + View_creation_ctx *view_creation_ctx; + + /* + Attributes to save/load view creation context in/from frm-file. + + Ther are required only to be able to use existing parser to load + view-definition file. As soon as the parser parsed the file, view + creation context is initialized and the attributes become redundant. + + These attributes MUST NOT be used for any purposes but the parsing. + */ + + LEX_STRING view_client_cs_name; + LEX_STRING view_connection_cl_name; + + /* + View definition (SELECT-statement) in the UTF-form. + */ + + LEX_STRING view_body_utf8; + + /* End of view definition context. */ + + /** + Indicates what triggers we need to pre-load for this TABLE_LIST + when opening an associated TABLE. This is filled after + the parsed tree is created. + */ + uint8 trg_event_map; + + uint i_s_requested_object; + bool has_db_lookup_value; + bool has_table_lookup_value; + uint table_open_method; + enum enum_schema_table_state schema_table_state; + void calc_md5(char *buffer); + void set_underlying_merge(); + int view_check_option(THD *thd, bool ignore_failure); + bool setup_underlying(THD *thd); + void cleanup_items(); + bool placeholder() + { + return derived || view || schema_table || (create && !table->db_stat) || + !table; + } + void print(THD *thd, String *str, enum_query_type query_type); + bool check_single_table(TABLE_LIST **table, table_map map, + TABLE_LIST *view); + bool set_insert_values(MEM_ROOT *mem_root); + void hide_view_error(THD *thd); + TABLE_LIST *find_underlying_table(TABLE *table); + TABLE_LIST *first_leaf_for_name_resolution(); + TABLE_LIST *last_leaf_for_name_resolution(); + bool is_leaf_for_name_resolution(); + inline TABLE_LIST *top_table() + { return belong_to_view ? belong_to_view : this; } + inline bool prepare_check_option(THD *thd) + { + bool res= FALSE; + if (effective_with_check) + res= prep_check_option(thd, effective_with_check); + return res; + } + inline bool prepare_where(THD *thd, Item **conds, + bool no_where_clause) + { + if (effective_algorithm == VIEW_ALGORITHM_MERGE) + return prep_where(thd, conds, no_where_clause); + return FALSE; + } + + void register_want_access(ulong want_access); + bool prepare_security(THD *thd); +#ifndef NO_EMBEDDED_ACCESS_CHECKS + Security_context *find_view_security_context(THD *thd); + bool prepare_view_securety_context(THD *thd); +#endif + /* + Cleanup for re-execution in a prepared statement or a stored + procedure. + */ + void reinit_before_use(THD *thd); + Item_subselect *containing_subselect(); + + /* + Compiles the tagged hints list and fills up st_table::keys_in_use_for_query, + st_table::keys_in_use_for_group_by, st_table::keys_in_use_for_order_by, + st_table::force_index and st_table::covering_keys. + */ + bool process_index_hints(TABLE *table); + + /* Access MERGE child def version. See top comment in ha_myisammrg.cc */ + inline ulong get_child_def_version() + { + return child_def_version; + } + inline void set_child_def_version(ulong version) + { + child_def_version= version; + } + inline void init_child_def_version() + { + child_def_version= ~0UL; + } + + /** + Compare the version of metadata from the previous execution + (if any) with values obtained from the current table + definition cache element. + + @sa check_and_update_table_version() + */ + inline + bool is_table_ref_id_equal(TABLE_SHARE *s) const + { + return (m_table_ref_type == s->get_table_ref_type() && + m_table_ref_version == s->get_table_ref_version()); + } + + /** + Record the value of metadata version of the corresponding + table definition cache element in this parse tree node. + + @sa check_and_update_table_version() + */ + inline + void set_table_ref_id(TABLE_SHARE *s) + { + m_table_ref_type= s->get_table_ref_type(); + m_table_ref_version= s->get_table_ref_version(); + } + + /** + @brief True if this TABLE_LIST represents an anonymous derived table, + i.e. the result of a subquery. + */ + bool is_anonymous_derived_table() const { return derived && !view; } + + /** + @brief Returns the name of the database that the referenced table belongs + to. + */ + char *get_db_name() { return view != NULL ? view_db.str : db; } + + /** + @brief Returns the name of the table that this TABLE_LIST represents. + + @details The unqualified table name or view name for a table or view, + respectively. + */ + char *get_table_name() { return view != NULL ? view_name.str : table_name; } + +private: + bool prep_check_option(THD *thd, uint8 check_opt_type); + bool prep_where(THD *thd, Item **conds, bool no_where_clause); + /* + Cleanup for re-execution in a prepared statement or a stored + procedure. + */ + + /* Remembered MERGE child def version. See top comment in ha_myisammrg.cc */ + ulong child_def_version; + /** See comments for set_metadata_id() */ + enum enum_table_ref_type m_table_ref_type; + /** See comments for set_metadata_id() */ + ulong m_table_ref_version; +}; + +class Item; + +/* + Iterator over the fields of a generic table reference. +*/ + +class Field_iterator: public Sql_alloc +{ +public: + Field_iterator() {} /* Remove gcc warning */ + virtual ~Field_iterator() {} + virtual void set(TABLE_LIST *)= 0; + virtual void next()= 0; + virtual bool end_of_fields()= 0; /* Return 1 at end of list */ + virtual const char *name()= 0; + virtual Item *create_item(THD *)= 0; + virtual Field *field()= 0; +}; + + +/* + Iterator over the fields of a base table, view with temporary + table, or subquery. +*/ + +class Field_iterator_table: public Field_iterator +{ + Field **ptr; +public: + Field_iterator_table() :ptr(0) {} + void set(TABLE_LIST *table) { ptr= table->table->field; } + void set_table(TABLE *table) { ptr= table->field; } + void next() { ptr++; } + bool end_of_fields() { return *ptr == 0; } + const char *name(); + Item *create_item(THD *thd); + Field *field() { return *ptr; } +}; + + +/* Iterator over the fields of a merge view. */ + +class Field_iterator_view: public Field_iterator +{ + Field_translator *ptr, *array_end; + TABLE_LIST *view; +public: + Field_iterator_view() :ptr(0), array_end(0) {} + void set(TABLE_LIST *table); + void next() { ptr++; } + bool end_of_fields() { return ptr == array_end; } + const char *name(); + Item *create_item(THD *thd); + Item **item_ptr() {return &ptr->item; } + Field *field() { return 0; } + inline Item *item() { return ptr->item; } + Field_translator *field_translator() { return ptr; } +}; + + +/* + Field_iterator interface to the list of materialized fields of a + NATURAL/USING join. +*/ + +class Field_iterator_natural_join: public Field_iterator +{ + List_iterator_fast column_ref_it; + Natural_join_column *cur_column_ref; +public: + Field_iterator_natural_join() :cur_column_ref(NULL) {} + ~Field_iterator_natural_join() {} + void set(TABLE_LIST *table); + void next(); + bool end_of_fields() { return !cur_column_ref; } + const char *name() { return cur_column_ref->name(); } + Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); } + Field *field() { return cur_column_ref->field(); } + Natural_join_column *column_ref() { return cur_column_ref; } +}; + + +/* + Generic iterator over the fields of an arbitrary table reference. + + DESCRIPTION + This class unifies the various ways of iterating over the columns + of a table reference depending on the type of SQL entity it + represents. If such an entity represents a nested table reference, + this iterator encapsulates the iteration over the columns of the + members of the table reference. + + IMPLEMENTATION + The implementation assumes that all underlying NATURAL/USING table + references already contain their result columns and are linked into + the list TABLE_LIST::next_name_resolution_table. +*/ + +class Field_iterator_table_ref: public Field_iterator +{ + TABLE_LIST *table_ref, *first_leaf, *last_leaf; + Field_iterator_table table_field_it; + Field_iterator_view view_field_it; + Field_iterator_natural_join natural_join_it; + Field_iterator *field_it; + void set_field_iterator(); +public: + Field_iterator_table_ref() :field_it(NULL) {} + void set(TABLE_LIST *table); + void next(); + bool end_of_fields() + { return (table_ref == last_leaf && field_it->end_of_fields()); } + const char *name() { return field_it->name(); } + const char *get_table_name(); + const char *get_db_name(); + GRANT_INFO *grant(); + Item *create_item(THD *thd) { return field_it->create_item(thd); } + Field *field() { return field_it->field(); } + Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref); + Natural_join_column *get_natural_column_ref(); +}; + + +typedef struct st_nested_join +{ + List join_list; /* list of elements in the nested join */ + table_map used_tables; /* bitmap of tables in the nested join */ + table_map not_null_tables; /* tables that rejects nulls */ + struct st_join_table *first_nested;/* the first nested table in the plan */ + /* + Used to count tables in the nested join in 2 isolated places: + 1. In make_outerjoin_info(). + 2. check_interleaving_with_nj/restore_prev_nj_state (these are called + by the join optimizer. + Before each use the counters are zeroed by reset_nj_counters. + */ + uint counter; + nested_join_map nj_map; /* Bit used to identify this nested join*/ +} NESTED_JOIN; + + +typedef struct st_changed_table_list +{ + struct st_changed_table_list *next; + char *key; + uint32 key_length; +} CHANGED_TABLE_LIST; + + +typedef struct st_open_table_list{ + struct st_open_table_list *next; + char *db,*table; + uint32 in_use,locked; +} OPEN_TABLE_LIST; + +typedef struct st_table_field_w_type +{ + LEX_STRING name; + LEX_STRING type; + LEX_STRING cset; +} TABLE_FIELD_W_TYPE; + + +my_bool +table_check_intact(TABLE *table, const uint table_f_count, + const TABLE_FIELD_W_TYPE *table_def); + +static inline my_bitmap_map *tmp_use_all_columns(TABLE *table, + MY_BITMAP *bitmap) +{ + my_bitmap_map *old= bitmap->bitmap; + bitmap->bitmap= table->s->all_set.bitmap; + return old; +} + + +static inline void tmp_restore_column_map(MY_BITMAP *bitmap, + my_bitmap_map *old) +{ + bitmap->bitmap= old; +} + +/* The following is only needed for debugging */ + +static inline my_bitmap_map *dbug_tmp_use_all_columns(TABLE *table, + MY_BITMAP *bitmap) +{ +#ifndef DBUG_OFF + return tmp_use_all_columns(table, bitmap); +#else + return 0; +#endif +} + +static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap, + my_bitmap_map *old) +{ +#ifndef DBUG_OFF + tmp_restore_column_map(bitmap, old); +#endif +} + + +/* + Variant of the above : handle both read and write sets. + Provide for the possiblity of the read set being the same as the write set +*/ +static inline void dbug_tmp_use_all_columns(TABLE *table, + my_bitmap_map **save, + MY_BITMAP *read_set, + MY_BITMAP *write_set) +{ +#ifndef DBUG_OFF + save[0]= read_set->bitmap; + save[1]= write_set->bitmap; + (void) tmp_use_all_columns(table, read_set); + (void) tmp_use_all_columns(table, write_set); +#endif +} + + +static inline void dbug_tmp_restore_column_maps(MY_BITMAP *read_set, + MY_BITMAP *write_set, + my_bitmap_map **old) +{ +#ifndef DBUG_OFF + tmp_restore_column_map(read_set, old[0]); + tmp_restore_column_map(write_set, old[1]); +#endif +} + + +size_t max_row_length(TABLE *table, const uchar *data); + diff --git a/dbcon/sm/Makefile.am b/dbcon/sm/Makefile.am new file mode 100644 index 00000000..6409bd26 --- /dev/null +++ b/dbcon/sm/Makefile.am @@ -0,0 +1,38 @@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + +AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) +AM_CFLAGS = $(idb_cflags) +AM_CXXFLAGS = $(idb_cxxflags) +AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) +lib_LTLIBRARIES = libsm.la +libsm_la_SOURCES = sm.cpp +include_HEADERS = sm.h + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: install-data-am + diff --git a/dbcon/sm/Makefile.in b/dbcon/sm/Makefile.in new file mode 100644 index 00000000..bb6e5ce2 --- /dev/null +++ b/dbcon/sm/Makefile.in @@ -0,0 +1,533 @@ +# Makefile.in generated by automake 1.9.6 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = dbcon/sm +DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" +libLTLIBRARIES_INSTALL = $(INSTALL) +LTLIBRARIES = $(lib_LTLIBRARIES) +libsm_la_LIBADD = +am_libsm_la_OBJECTS = sm.lo +libsm_la_OBJECTS = $(am_libsm_la_OBJECTS) +DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CXXFLAGS) $(CXXFLAGS) +CXXLD = $(CXX) +CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ + $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(libsm_la_SOURCES) +DIST_SOURCES = $(libsm_la_SOURCES) +includeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(include_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +ALLOCA = @ALLOCA@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POW_LIB = @POW_LIB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +YACC = @YACC@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +etcdir = @etcdir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +idb_brm_libs = @idb_brm_libs@ +idb_cflags = @idb_cflags@ +idb_common_includes = @idb_common_includes@ +idb_common_ldflags = @idb_common_ldflags@ +idb_common_libs = @idb_common_libs@ +idb_cppflags = @idb_cppflags@ +idb_cxxflags = @idb_cxxflags@ +idb_exec_libs = @idb_exec_libs@ +idb_ldflags = @idb_ldflags@ +idb_oam_libs = @idb_oam_libs@ +idb_write_libs = @idb_write_libs@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localdir = @localdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +march_flags = @march_flags@ +mibdir = @mibdir@ +mkdir_p = @mkdir_p@ +mysqldir = @mysqldir@ +netsnmp_libs = @netsnmp_libs@ +oldincludedir = @oldincludedir@ +postdir = @postdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedir = @sharedir@ +sharedstatedir = @sharedstatedir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +toolsdir = @toolsdir@ +AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) +AM_CFLAGS = $(idb_cflags) +AM_CXXFLAGS = $(idb_cxxflags) +AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) +lib_LTLIBRARIES = libsm.la +libsm_la_SOURCES = sm.cpp +include_HEADERS = sm.h +all: all-am + +.SUFFIXES: +.SUFFIXES: .cpp .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu dbcon/sm/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu dbcon/sm/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(mkdir_p) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + if test -f $$p; then \ + f=$(am__strip_dir) \ + echo " $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \ + else :; fi; \ + done + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @set -x; list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + p=$(am__strip_dir) \ + echo " $(LIBTOOL) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \ + $(LIBTOOL) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libsm.la: $(libsm_la_OBJECTS) $(libsm_la_DEPENDENCIES) + $(CXXLINK) -rpath $(libdir) $(libsm_la_LDFLAGS) $(libsm_la_OBJECTS) $(libsm_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sm.Plo@am__quote@ + +.cpp.o: +@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< + +.cpp.obj: +@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.cpp.lo: +@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(mkdir_p) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f=$(am__strip_dir) \ + echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'"; \ + $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; for p in $$list; do \ + f=$(am__strip_dir) \ + echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ + rm -f "$(DESTDIR)$(includedir)/$$f"; \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-includeHEADERS + +install-exec-am: install-libLTLIBRARIES + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-includeHEADERS uninstall-info-am \ + uninstall-libLTLIBRARIES + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-exec \ + install-exec-am install-includeHEADERS install-info \ + install-info-am install-libLTLIBRARIES install-man \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-includeHEADERS uninstall-info-am \ + uninstall-libLTLIBRARIES + + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: install-data-am +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/dbcon/sm/sm.cpp b/dbcon/sm/sm.cpp new file mode 100644 index 00000000..268a1d3d --- /dev/null +++ b/dbcon/sm/sm.cpp @@ -0,0 +1,555 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** + * $Id: sm.cpp 9262 2013-02-06 21:07:19Z zzhu $ + * + ***********************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#if __FreeBSD__ +typedef sig_t sighandler_t; +#endif +using namespace std; + +#include + +#include "calpontsystemcatalog.h" +using namespace execplan; + +#include "bytestream.h" +using namespace messageqcpp; + +#include "errorcodes.h" +using namespace logging; + +#include "querystats.h" +using namespace querystats; + +#include "sm.h" + +namespace { +using namespace sm; + +// @bug 159 fix. clean up routine when error happened +void cleanup(cpsm_conhdl_t* hndl) +{ + // remove system catalog instance for this statement. + CalpontSystemCatalog::removeCalpontSystemCatalog(hndl->sessionID); + hndl->queryState = NO_QUERY; + hndl->resultSet.erase(hndl->resultSet.begin(), hndl->resultSet.end()); +} + +} + +namespace sm +{ +#ifdef _MSC_VER + const std::string DEFAULT_SAVE_PATH = "C:\\Calpont\\tmp"; +#else + const std::string DEFAULT_SAVE_PATH = "/var/tmp"; +#endif + +status_t +tpl_open ( + tableid_t tableid, /* IN - Table id */ + void **tplhdl, /* OUT - Tuple handle */ + void *conn_hdl /* IN - connection handle */ +) +{ + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + DEBUG << "tpl_open: " << hndl << " tableid: " << tableid << endl; + + // @bug 649. No initialization here. take passed in reference + cpsm_tplh_t* ntplh = static_cast(*tplhdl); + + // if first time enter this function for a statement, set + // queryState to QUERY_IN_PRCOESS and get execution plan. + if (hndl->queryState == NO_QUERY) + { + hndl->queryState = QUERY_IN_PROCESS; + } + + try { + // @bug 626. check saveFlag, if SAVED, do not project + if (ntplh->saveFlag != SAVED) + { + // Request ExeMgr to start projecting table tableid + CalpontSystemCatalog::OID tableOID = static_cast(tableid); + ByteStream::quadbyte qb = static_cast(tableOID); + ByteStream bs; + bs << qb; + //hndl->exeMgr->write(bs); + hndl->write(bs); + } + } + catch (std::exception& ex) + { + DEBUG << "Exception caught in tpl_open: " << ex.what() << endl; + //hndl->queryState = NO_QUERY; + cleanup(hndl); + return CALPONT_INTERNAL_ERROR; + } + + ntplh->tableid = tableid; + char* tmp = (char*)alloca(sizeof(ntplh->tbName)); + strcpy(ntplh->tbName, tblid2name(tmp, ntplh->tableid, conn_hdl)); + + return STATUS_OK; +} + +status_t +tpl_scan_open ( + tableid_t tableid, /* IN - Table id of the table */ + tpl_fetch_hint_t fh, /* IN - Tuple fetch hint */ + sp_cpsm_tplsch_t& ntplsch, /* OUT - Tuple scan handle */ + void *conn_hdl /* IN - connection handle */ +) +{ + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + DEBUG << "tpl_scan_open: " << hndl << " tableid: " << tableid << endl; + + // @bug 649. No initialization here. take passed in reference + ntplsch->tableid = tableid; + char* tmp = (char*)alloca(sizeof(ntplsch->tbName)); + strcpy(ntplsch->tbName, tblid2name(tmp, ntplsch->tableid, conn_hdl)); + + ntplsch->rowsreturned = 0; + return STATUS_OK; +} + +status_t tpl_scan_fetch_getband(cpsm_conhdl_t* hndl, sp_cpsm_tplsch_t& ntplsch, int* killed) +{ + // @bug 649 check keybandmap first + map::iterator keyBandMapIter = hndl->keyBandMap.find(ntplsch->key); + + try { + if (keyBandMapIter != hndl->keyBandMap.end()) + { + ByteStream bs; + ostringstream oss; + oss << DEFAULT_SAVE_PATH << '/' << hndl->sessionID << '/' << ntplsch->key << '_' << ntplsch->bandID << ".band"; + ifstream bandFile (oss.str().c_str(), ios::in); + bandFile >> bs; + unlink (oss.str().c_str()); + + // not possible for vtable + ntplsch->deserializeTable(bs); + ntplsch->bandID++; + + // end of result set + if (ntplsch->bandID == keyBandMapIter->second) + { + hndl->keyBandMap.erase(keyBandMapIter); + return SQL_NOT_FOUND; + } + } + else + { + ByteStream bs; + // @bug 626. check saveFlag. If SAVING, read band from socket and save to disk + if (ntplsch->saveFlag == SAVING) + { + ByteStream bs; + // @bug 2244. Bypass ClientRotator::read() because if I/O error occurs, it tries + // to reestablish a connection with ExeMgr which ends up causing mysql + // session to hang. + bs = hndl->exeMgr->read(); + ostringstream oss; + oss << DEFAULT_SAVE_PATH << '/' << hndl->sessionID << '/' << ntplsch->tableid << '_' << ntplsch->bandsReturned << ".band"; + ofstream saveFile (oss.str().c_str(), ios::out); + saveFile << bs; + saveFile.close(); + ntplsch->bandsReturned++; + // not possible for vtable + ntplsch->deserializeTable(bs); + } + // if SAVED, read from saved file. not possible for vtable + else if (ntplsch->saveFlag == SAVED) + { + ostringstream oss; + oss << DEFAULT_SAVE_PATH << '/' << hndl->sessionID << '/' << ntplsch->tableid << '_' << ntplsch->bandsReturned << ".band"; + ifstream saveFile (oss.str().c_str(), ios::in); + saveFile >> bs; + saveFile.close(); + ntplsch->bandsReturned++; + ntplsch->deserializeTable(bs); + } + // most normal path. also the path for vtable + else + { + ntplsch->bs.restart(); + // @bug 2244. Bypass ClientRotator::read() because if I/O error occurs, it tries + // to reestablish a connection with ExeMgr which ends up causing mysql + // session to hang. + // @bug 3386. need to abort the query when user does ctrl+c + timespec t; + t.tv_sec = 5L; + t.tv_nsec = 0L; + if (killed && *killed) + return SQL_KILLED; + ntplsch->bs = hndl->exeMgr->read(); + + if (ntplsch->bs.length() != 0) + { + ntplsch->deserializeTable(ntplsch->bs); + if (ntplsch->rowGroup && ntplsch->rowGroup->getData() == NULL) + { + ntplsch->bs.restart(); + // @bug 2244. Bypass ClientRotator::read() because if I/O error occurs, it tries + // to reestablish a connection with ExeMgr which ends up causing mysql + // session to hang. + bool timeout = true; + while (timeout) + { + timeout = false; + ntplsch->bs = hndl->exeMgr->getClient()->read(&t, &timeout); + + if (killed && *killed) + return SQL_KILLED; + } + + if (ntplsch->bs.length() == 0) + { + hndl->curFetchTb = 0; + return logging::ERR_LOST_CONN_EXEMGR; + } + ntplsch->deserializeTable(ntplsch->bs); + } + + uint16_t error = ntplsch->getStatus(); + if (0 != error) + { + ntplsch->setErrMsg(); + return error; + } + } + else // @todo error handling + { + hndl->curFetchTb = 0; + if (ntplsch->saveFlag == NO_SAVE) + hndl->tidScanMap[ntplsch->tableid] = ntplsch; + ntplsch->errMsg = IDBErrorInfo::instance()->errorMsg(ERR_LOST_CONN_EXEMGR); + return logging::ERR_LOST_CONN_EXEMGR; + } + } + + // All done with this table. reset curFetchTb when finish SOCKET reading + if (ntplsch->getRowCount() == 0) + { + hndl->curFetchTb = 0; + if (ntplsch->saveFlag == NO_SAVE) + hndl->tidScanMap[ntplsch->tableid] = ntplsch; + return SQL_NOT_FOUND; + } + } + } catch (std::exception &e) + { + hndl->curFetchTb = 0; + if (ntplsch->saveFlag == NO_SAVE) + hndl->tidScanMap[ntplsch->tableid] = ntplsch; + ntplsch->errMsg = e.what(); + return logging::ERR_LOST_CONN_EXEMGR; + } + ntplsch->rowsreturned = 0; + return STATUS_OK; +} + +status_t +tpl_scan_fetch ( + sp_cpsm_tplsch_t& ntplsch, /* IN - Tuple scan handle */ + fldl_val_t* fld_vlist, /* OUT - Field values fetched */ + void* tid, /* OUT - Tuple id of the fetched tuple */ + void* conn_hdl, /* IN - connection handle */ + int* killed +) +{ + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + + // @770. force end of result set when this is not the first table to be fetched. + if (ntplsch->traceFlags & CalpontSelectExecutionPlan::TRACE_NO_ROWS2) + if (hndl->tidScanMap.size() >= 1) + return SQL_NOT_FOUND; + + // need another band + status_t status = STATUS_OK; + if (ntplsch->rowsreturned == ntplsch->getRowCount()) + status = tpl_scan_fetch_getband(hndl, ntplsch, killed); + + return status; +} + +status_t +tpl_scan_close ( + //void *tpl_scanhdl, /* IN - Tuple scan handle */ + sp_cpsm_tplsch_t& ntplsch, + void *conn_hdl /* IN - connection handle */ +) +{ + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + + DEBUG << "tpl_scan_close: " << hndl; + if (ntplsch) + DEBUG << " tableid: " << ntplsch->tableid << endl; + ntplsch.reset(); + + return STATUS_OK; +} + +void end_query(cpsm_conhdl_t* hndl) +{ + // remove system catalog instance for this statement. + // @bug 695. turn on system catalog session cache for FE + // CalpontSystemCatalog::removeCalpontSystemCatalog(hndl->sessionID); + hndl->queryState = NO_QUERY; + // reset at the end of query + hndl->curFetchTb = 0; + // @bug 626 clear up + hndl->tidMap.clear(); + hndl->tidScanMap.clear(); + hndl->keyBandMap.clear(); + // Tell ExeMgr we are done with this query + try { + ByteStream bs; + ByteStream::quadbyte qb = 0; + bs << qb; + hndl->write(bs); + } + catch(...) + { + throw; + } +} + +status_t +tpl_close ( + void *tplhdl, /* IN - Tuple handle */ + cpsm_conhdl_t **conn_hdl, /* IN - connection handle */ + QueryStats& stats /* IN&OUT - query stats */ +) +{ + cpsm_conhdl_t* hndl = static_cast(*conn_hdl); + + cpsm_tplh_t* ntplh = static_cast(tplhdl); + + DEBUG << "tpl_close: " << hndl; + if (ntplh) DEBUG << " tableid: " << ntplh->tableid; + DEBUG << endl; + + delete ntplh; + + // determine end of result set and end of statement execution + if (hndl->queryState == QUERY_IN_PROCESS) + { + // Get the query stats + ByteStream bs; + ByteStream::quadbyte qb = 3; + bs << qb; + //hndl->exeMgr->write(bs); + hndl->write(bs); + //keep reading until we get a string + //TODO: really need to fix this! Why is ExeMgr sending other stuff? + for (int tries = 0; tries < 10; tries++) + { + bs = hndl->exeMgr->read(); + if (bs.length() == 0) break; + try { + bs >> hndl->queryStats; + bs >> hndl->extendedStats; + bs >> hndl->miniStats; + stats.unserialize(bs); + stats.setEndTime(); + stats.insert(); + break; + } catch (IDBExcept&) + { + // @bug4732 + end_query(hndl); + throw; + } + catch (...) { + // querystats messed up. close connection. + // no need to throw for querystats protocol error, like for tablemode. + end_query(hndl); + sm_cleanup(hndl); + *conn_hdl = 0; + return STATUS_OK; + //throw runtime_error(string("tbl_close catch exception: ") + e.what()); + } + } + end_query(hndl); + } + return STATUS_OK; +} + +status_t +sm_init ( + const char *database, /*!< IN - Database name */ + const char *userid, /*!< IN - User ID to connect to the database */ + const char *passwd, /*!< IN - Authorization for the given user */ + + const char *dboptions, /*!< IN - Additional connection options */ + + void **conn_hdl /*!< OUT- connection handle */ +) +{ + // clear file content +#if IDB_SM_DEBUG + smlog.close(); + smlog.open("/tmp/sm.log"); +#endif + DEBUG << "sm_init: " << dboptions << endl; + cpsm_conhdl_t* hndl = new cpsm_conhdl_t(time(0), atoi(dboptions)); + cpsm_conhdl_t** chp = reinterpret_cast(conn_hdl); + *chp = hndl; + hndl->sessionID = atoi(dboptions); + + // profiling statistics + GET_PF_TIME(hndl->pf.login); + + return STATUS_OK; +} + +status_t +sm_cleanup ( + void *conn_hdl /*!< IN - Connection handle */ +) +{ + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + DEBUG << "sm_cleanup: " << hndl << endl; + +#if IDB_SM_DEBUG + DEBUG.close(); +#endif + delete hndl; + return STATUS_OK; +} + +int tbname2id(const char* schema, const char* table, void* conn_hdl) +{ + tblinfo_t ti; + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + hndl->schemaname = string(schema); + hndl->tablename = string(table); + hndl->requestType = NAME2ID; + get_tblinfo(&ti, conn_hdl); + return ti.id; +} + +char* tblid2name(char* workbuf, tableid_t tableid, void* conn_hdl) +{ + strcpy(workbuf, "unknown"); + + return workbuf; +} + +status_t +char_to_tid ( + short len, /* IN - Length of input buffer */ + const char *in_buf, /* IN - input buffer */ + void *tid, /* OUT - resultant Tuple id */ + void *conn_hdl /* IN - connection handle */ +) +{ + //cout << "char_to_tid" << endl; + cpsm_tid_t* ntid = static_cast(tid); + if (in_buf) + { + ntid->value = atoi(in_buf); + ntid->valid = true; + } + + return STATUS_OK; +} + +status_t get_tblinfo ( + tblinfo_t* info, /* OUT - pointer to table information */ + void* conn_hdl /* IN - connection handle */ +) +{ + // NOTE: this call and get_colinfo are not comply with dharma interface + // anymore. Dharma expects them to look up all the tables in the schema and return + // table info until the end (return SQL_NOT_FOUND). Current implementation only + // search for the table info given table and schema name. this works fine with Oracle. + // TODO: need a dharma version for ODBC solution. + cpsm_conhdl_t* hndl = static_cast(conn_hdl); + uint32_t sessionid = hndl->sessionID; + boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionid); + csc->sessionID(sessionid); + csc->identity(CalpontSystemCatalog::FE); + + if (hndl->requestType == ID2NAME) + { + // should not need this + return STATUS_OK; + } + else //(hndl->requestType == NAME2ID) + { + CalpontSystemCatalog::TableName tn; + tn.schema = hndl->schemaname; + tn.table = hndl->tablename; + CalpontSystemCatalog::ROPair rp = csc->tableRID(tn); + info->id = rp.objnum; + return STATUS_OK; + } +} + +// @bug 1054, 863 - SIGPIPE handler +bool sigFlag = false; +void sighandler(int sig_num) +{ + FILE* p; + char buf[1024]; + + if ((p = fopen("/tmp/f1.dat", "a")) != NULL) + { + snprintf(buf, 1024, "sighandler() hit with %d\n", sig_num); + fwrite(buf, 1, strlen(buf), p); + fclose(p); + } + sigFlag = true; + throw runtime_error("zerror"); +} + +void cpsm_conhdl_t::write(ByteStream bs) +{ +#ifdef _MSC_VER + exeMgr->write(bs); +#else + sighandler_t old_handler = signal(SIGPIPE, sighandler); + sigFlag = false; + exeMgr->write(bs); + signal(SIGPIPE, old_handler); + if (sigFlag) + throw runtime_error("Broken Pipe Error"); +#endif +} + +void cpsm_conhdl_t::connect(double timeout) +{ + exeMgr->connect(timeout); +} + +} + diff --git a/dbcon/sm/sm.h b/dbcon/sm/sm.h new file mode 100644 index 00000000..7033000c --- /dev/null +++ b/dbcon/sm/sm.h @@ -0,0 +1,328 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/*********************************************************************** + * $Id: sm.h 9262 2013-02-06 21:07:19Z zzhu $ + * + ***********************************************************************/ +/** @file */ + +#ifndef SM_H__ +#define SM_H__ + +#include +#include +#include +#include +#include +#include + +#include "calpontsystemcatalog.h" +#include "clientrotator.h" +#include "rowgroup.h" +#include "calpontselectexecutionplan.h" +#include "querystats.h" + +#define IDB_SM_DEBUG 0 +#define IDB_SM_PROFILE 0 + +#if defined(_MSC_VER) && defined(xxxDLLEXPORT) +#define EXPORT __declspec(dllexport) +#else +#define EXPORT +#endif + +#if IDB_SM_PROFILE +#include +#define GET_PF_TIME(n) {gettimeofday(&n, NULL);} +#else +#define GET_PF_TIME(n) {} +#endif + +namespace sm +{ +const int STATUS_OK=0; +const int SQL_NOT_FOUND=-1000; +const int SQL_KILLED=-1001; +const int CALPONT_INTERNAL_ERROR=-1007; + +const int MAX_IDLEN=32+1; + +#if IDB_SM_DEBUG +extern std::ofstream smlog; +#define DEBUG smlog +#else +#define DEBUG if (false) std::cerr +#endif +extern const std::string DEFAULT_SAVE_PATH; + +typedef enum +{ + TPL_FH_READ, /* Fetch for read */ + TPL_FH_WRITE /* Fetch for update */ +} tpl_fetch_hint_t; +typedef unsigned short field_t; +typedef int32_t typeid_t; +typedef unsigned char sm_boolean; +typedef struct { + typeid_t dt_data_type; /* Data type */ + sm_boolean dt_is_data_null;/* Is the value stored NULL */ + unsigned short dt_maxlen; /* Maximum length of data */ + unsigned short dt_data_len; /* Actual length of data - defined */ + /* for char and binary types. */ + short dt_width; /* Data type precision - Ignored */ + /* except for numeric types */ + short dt_scale; /* Scale for numeric types */ + void *dt_data; /* Pointer to store the data */ +} data_t; +typedef struct { + field_t fv_field; /* Field id in the table */ + field_t fv_tfield; /* Field id in the table if fv_field is */ + /* index field id. */ + unsigned short fv_maxlen; /* Maximum length of the field */ + data_t *fv_data; /* Data value in the field */ +} fv_item_t; +typedef struct { + short fv_nitems ;/* Number of field values in the list */ + fv_item_t *fv_item ; /* Pointer to an array of field values */ +} fldl_val_t; + +typedef uint64_t tableid_t; +typedef int32_t status_t; + +enum QueryState +{ + NO_QUERY = 0, + QUERY_IN_PROCESS +}; + +typedef struct Column { + Column():tableID(-1) {} + ~Column() {} + int tableID; + int colPos; + int dataType; + std::vector data; +} Column; + +typedef std::map ResultMap; + +struct Profiler +{ + struct timeval login; + struct timeval beforePlan; + struct timeval afterPlan; + struct timeval resultArrival; + struct timeval resultReady; + struct timeval endProcess; + long prePlan(){ + return (beforePlan.tv_sec-login.tv_sec) * 1000 + + (beforePlan.tv_usec - login.tv_usec)/1000; } + long buildPlan() { + return (afterPlan.tv_sec - beforePlan.tv_sec) * 1000 + + (afterPlan.tv_usec - beforePlan.tv_usec)/1000; } + long jobProcess() { + return (resultArrival.tv_sec - afterPlan.tv_sec) * 1000 + + (resultArrival.tv_usec - afterPlan.tv_usec)/1000; } + long buildResult() { + return (resultReady.tv_sec - resultArrival.tv_sec) * 1000 + + (resultReady.tv_usec - resultArrival.tv_usec)/1000; } + long tableFetch () { + return (endProcess.tv_sec - resultReady.tv_sec) * 1000 + + (endProcess.tv_usec - resultReady.tv_usec)/1000; } +}; + +/** @brief Calpont table scan handle */ +struct cpsm_tplsch_t +{ + cpsm_tplsch_t() : tableid(0), rowsreturned(0), rowGroup(0), traceFlags(0), bandID(0), saveFlag(0), bandsReturned(0), + ctp(0) {} + ~cpsm_tplsch_t() + { + delete rowGroup; + } + + char tbName[100]; + tableid_t tableid; + uint64_t rowsreturned; + rowgroup::RowGroup *rowGroup; + messageqcpp::ByteStream bs; // rowgroup bytestream. need to stay with the life span of rowgroup + uint32_t traceFlags; + // @bug 649 + int bandID; // the band that being read from the disk + int key; // unique key for the table's scan context + // @bug 626 + uint16_t saveFlag; + uint32_t bandsReturned; + std::vector ctp; + std::string errMsg; + void deserializeTable(messageqcpp::ByteStream& bs) + { + if (!rowGroup) + { + rowGroup = new rowgroup::RowGroup(); + rowGroup->deserialize(bs); + } + else + { + rowGroup->setData(const_cast(bs.buf())); + } + } + + uint16_t getStatus() + { + assert (rowGroup != 0); + return rowGroup->getStatus(); + } + + uint64_t getRowCount() + { + if (rowGroup) + return rowGroup->getRowCount(); + else + return 0; + } + + void setErrMsg() + { + if (rowGroup && getStatus()) + { + bs.advance(rowGroup->getDataSize()); + bs >> errMsg; + } + else + { + errMsg = "NOERROR"; + } + } +}; +typedef boost::shared_ptr sp_cpsm_tplsch_t; + +enum RequestType +{ + ID2NAME = 0, + NAME2ID +}; + +/** @brief Calpont connection handle structure */ +class cpsm_conhdl_t +{ +public: + cpsm_conhdl_t(time_t v, const uint32_t sid) : + value(v), sessionID(sid), queryState (NO_QUERY), + exeMgr( new execplan::ClientRotator(sid, "ExeMgr")), + tblinfo_idx(0), idxinfo_idx(0), curFetchTb (0) //, EXEMGR("ExeMgr") + { } + + +/** @brief connnect ExeMgr + * + * Try connecting to ExeMgr. If no connection, try ExeMgr1, + * ExeMgr2... until timeout lapses. Then throw exception. + */ + EXPORT void connect(double timeout=0.005); + EXPORT void write(messageqcpp::ByteStream bs); + + ~cpsm_conhdl_t() { + delete exeMgr; + } + EXPORT const std::string toString() const; + time_t value; + uint32_t sessionID; + short queryState; // 0 -- NO_QUERY; 1 -- QUERY_IN_PROCESS + execplan::ClientRotator* exeMgr; + ResultMap resultSet; + Profiler pf; + int tblinfo_idx; + int idxinfo_idx; + std::string schemaname; + std::string tablename; + int tboid; + short requestType; // 0 -- ID2NAME; 1 -- NAME2ID + boost::shared_ptr csc; + // @bug 649; @bug 626 + std::map tidMap; // tableid-tableStartCount map + std::map tidScanMap; + std::map keyBandMap; // key-savedBandCount map + int curFetchTb; // current fetching table key + std::string queryStats; + std::string extendedStats; + std::string miniStats; +private: +}; +std::ostream& operator<<(std::ostream& output, const cpsm_conhdl_t& rhs); + +// @bug 626 save table bands to avoid sending plan too many times +enum SavingFlag +{ + NO_SAVE = 0, + SAVING, + SAVED +}; + +/** @brief Calpont table handle */ +struct cpsm_tplh_t +{ + cpsm_tplh_t() : tableid(0), rowsintable(0), bandID(0), saveFlag(NO_SAVE), bandsInTable(0) {} + tableid_t tableid; + int rowsintable; + char tbName[100]; + // @bug 649 + int bandID; // the band that being read from the disk + int key; // unique key for the table's scan context + // @bug 626 + uint16_t saveFlag; + int bandsInTable; +}; + +struct cpsm_tid_t +{ + cpsm_tid_t() : valid(false), value(0) {} + bool valid; + int value; +}; + +typedef struct { + tableid_t id; + char table_name[MAX_IDLEN]; + char table_owner[MAX_IDLEN]; + sm_boolean read_only ; + sm_boolean ispublic ; +} tblinfo_t; + +extern status_t sm_init(const char*, const char*, const char*, const char*, void**); +extern status_t sm_cleanup(void*); + +extern status_t tpl_open(tableid_t, void**, void*); +extern status_t tpl_scan_open(tableid_t, tpl_fetch_hint_t, sp_cpsm_tplsch_t&, void*); +extern status_t tpl_scan_fetch(sp_cpsm_tplsch_t&, fldl_val_t*, void*, void*, int* = NULL); +extern status_t tpl_scan_close(sp_cpsm_tplsch_t&, void*); +extern status_t tpl_close(void*, cpsm_conhdl_t**, querystats::QueryStats& stats); + +extern int tbname2id(const char*, const char*, void*); +/** @brief Util function to map table id to table name */ +extern char* tblid2name(char* workbuf, tableid_t tableid, void* conn_hdl); + +extern status_t char_to_tid( short len, const char *in_buf, void *tid, void *conn_hdl); +extern status_t get_tblinfo ( tblinfo_t *info, void *conn_hdl); + +} + +#undef EXPORT + +#endif + diff --git a/dbcon/sm/tdriver.cpp b/dbcon/sm/tdriver.cpp new file mode 100644 index 00000000..cd6e802b --- /dev/null +++ b/dbcon/sm/tdriver.cpp @@ -0,0 +1,22 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +int main (int argc, char *argv[]) +{ + return 0; +} + diff --git a/ddlproc/DDLProc.rc b/ddlproc/DDLProc.rc deleted file mode 100644 index cb8b9395..00000000 --- a/ddlproc/DDLProc.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB DDL Processor" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "DDLProc" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "DDLProc.exe" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/ddlproc/DDLProc.vcxproj b/ddlproc/DDLProc.vcxproj deleted file mode 100644 index 395a05ff..00000000 --- a/ddlproc/DDLProc.vcxproj +++ /dev/null @@ -1,351 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {EE6E6244-93A6-4014-A947-EFCB779B87B6} - DDLProc - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DDL Processor" $(SolutionDir)..\..x64\Release\DDLProc.exe - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\winport;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DDL Processor" $(SolutionDir)..\..\x64\EnterpriseRelease\DDLProc.exe - - - - - - - - - - - - - - - - - {19142d9e-7660-445c-b85d-98e722dffea5} - - - {033c6cba-d984-483f-adc8-825be20a699d} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {2be469d2-d854-4480-bfe0-34de89c557b2} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {4bc37219-e09d-4133-98c4-cf0386657df6} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - - - - \ No newline at end of file diff --git a/ddlproc/DDLProc.vcxproj.filters b/ddlproc/DDLProc.vcxproj.filters deleted file mode 100644 index af17084d..00000000 --- a/ddlproc/DDLProc.vcxproj.filters +++ /dev/null @@ -1,41 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/ddlproc/Makefile.am b/ddlproc/Makefile.am index cc066dca..7f42dc0b 100644 --- a/ddlproc/Makefile.am +++ b/ddlproc/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 665 2012-04-04 18:19:21Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/ddlproc/Makefile.in b/ddlproc/Makefile.in index a62ee257..36e6abea 100644 --- a/ddlproc/Makefile.in +++ b/ddlproc/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 665 2012-04-04 18:19:21Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = DDLProc$(EXEEXT) subdir = ddlproc DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/ddlproc/ddlproc.cpp b/ddlproc/ddlproc.cpp index 3ea3b8a0..c738cede 100644 --- a/ddlproc/ddlproc.cpp +++ b/ddlproc/ddlproc.cpp @@ -57,7 +57,7 @@ using namespace execplan; #include "cacheutils.h" #include "we_clients.h" #include "dbrm.h" -#include "IDBPolicy.h" + #include "utils_utf8.h" @@ -87,6 +87,7 @@ namespace logging::Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); Dec->Setup(); + WriteEngine::WEClients::instance(WriteEngine::WEClients::DDLPROC)->Setup(); } } @@ -99,11 +100,6 @@ int main(int argc, char* argv[]) setupCwd(); WriteEngine::WriteEngineWrapper::init( WriteEngine::SUBSYSTEM_ID_DDLPROC ); -#ifdef _MSC_VER - // In windows, initializing the wrapper (A dll) does not set the static variables - // in the main program - idbdatafile::IDBPolicy::configIDBPolicy(); -#endif ResourceManager rm; Dec = DistributedEngineComm::instance(rm); diff --git a/ddlproc/ddlprocessor.cpp b/ddlproc/ddlprocessor.cpp index 7812b930..7090437a 100644 --- a/ddlproc/ddlprocessor.cpp +++ b/ddlproc/ddlprocessor.cpp @@ -36,7 +36,7 @@ using namespace std; #include "markpartitionprocessor.h" #include "restorepartitionprocessor.h" #include "droppartitionprocessor.h" -//#define SERIALIZE_DDL_DML_CPIMPORT 1 +#define SERIALIZE_DDL_DML_CPIMPORT 1 #include "cacheutils.h" #include "vss.h" @@ -54,11 +54,6 @@ using namespace execplan; using namespace logging; using namespace WriteEngine; -#include "querytele.h" -using namespace querytele; - -#include "oamcache.h" - namespace { typedef messageqcpp::ByteStream::quadbyte quadbyte; @@ -68,6 +63,18 @@ const quadbyte NO_PKNAME_AVAILABLE = 101; const std::string DDLProcName = "DDLProc"; +// primary key name supplied by Oracle. Oracle will issue +// two separate DDL statements for a create table with primary +// key DDL, with the 1st one being create index and the 2nd +// one being create table. This PK name will be stored here +// when creatindexprocessor gets the create index statement. This +// is to make sure Calpont use the same system primary key name as Oracle +typedef map PKNameMap; + +//FIXME: when DDL is parallelized again, access to this map needs to be protected by a lock! +PKNameMap pkNameMap; + +WriteEngine::WriteEngineWrapper writeEngine; void cleanPMSysCache() { @@ -83,7 +90,7 @@ struct PackageHandler DDLPackageProcessor::DDLResult result; result.result = DDLPackageProcessor::NO_ERROR; //boost::shared_ptr systemCatalogPtr; - + try { //cout << "DDLProc received package " << fPackageType << endl; @@ -93,66 +100,61 @@ struct PackageHandler { CreateTableStatement createTableStmt; createTableStmt.unserialize(fByteStream); - boost::shared_ptr systemCatalogPtr = - CalpontSystemCatalog::makeCalpontSystemCatalog(createTableStmt.fSessionID ); - boost::scoped_ptr processor(new CreateTableProcessor(fDbrm)); - processor->fTxnid.id = fTxnid.id; - processor->fTxnid.valid = true; + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(createTableStmt.fSessionID ); + CreateTableProcessor processor; + PKNameMap::iterator it = pkNameMap.find(createTableStmt.fSessionID); + if (it == pkNameMap.end()) + //throw (NO_PKNAME_AVAILABLE); + // TODO: should check if this createtablestmt has primary key + processor.PKName(""); + else + processor.PKName((*it).second); + processor.fTxnid.id = fTxnid.id; + processor.fTxnid.valid = true; //cout << "create table using txnid " << fTxnid.id << endl; - - QueryTeleStats qts; - qts.query_uuid = QueryTeleClient::genUUID(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = createTableStmt.fSessionID; - qts.query_type = "CREATE"; - qts.query = createTableStmt.fSql; - qts.system_name = fOamCache->getSystemName(); - qts.module_name = fOamCache->getModuleName(); - qts.schema_name = createTableStmt.schemaName(); - fQtc.postQueryTele(qts); - - result = processor->processPackage(createTableStmt); - + result = processor.processPackage(createTableStmt); + if (it != pkNameMap.end()) + pkNameMap.erase(it); systemCatalogPtr->removeCalpontSystemCatalog( createTableStmt.fSessionID ); systemCatalogPtr->removeCalpontSystemCatalog( createTableStmt.fSessionID | 0x80000000); - - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.end_time = QueryTeleClient::timeNowms(); - fQtc.postQueryTele(qts); } break; - +#if 0 + case ddlpackage::DDL_CREATE_INDEX: + { + CreateIndexStatement createIndexStmt; + createIndexStmt.unserialize(fByteStream); + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(createIndexStmt.fSessionID ); + CreateIndexProcessor processor; + processor.fTxnid.id = fTxnid.id; + processor.fTxnid..valid = true; + result = processor.processPackage(createIndexStmt); + pkNameMap.insert(PKNameMap::value_type(createIndexStmt.fSessionID, processor.PKName())); + systemCatalogPtr->removeCalpontSystemCatalog( createIndexStmt.fSessionID ); + systemCatalogPtr->removeCalpontSystemCatalog( createIndexStmt.fSessionID | 0x80000000); + } + break; +#endif case ddlpackage::DDL_ALTER_TABLE_STATEMENT: { AlterTableStatement alterTableStmt; alterTableStmt.unserialize(fByteStream); - boost::shared_ptr systemCatalogPtr = - CalpontSystemCatalog::makeCalpontSystemCatalog(alterTableStmt.fSessionID ); - boost::scoped_ptr processor(new AlterTableProcessor(fDbrm)); - processor->fTxnid.id = fTxnid.id; - processor->fTxnid.valid = true; - - QueryTeleStats qts; - qts.query_uuid = QueryTeleClient::genUUID(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = alterTableStmt.fSessionID; - qts.query_type = "ALTER"; - qts.query = alterTableStmt.fSql; - qts.system_name = fOamCache->getSystemName(); - qts.module_name = fOamCache->getModuleName(); - qts.schema_name = alterTableStmt.schemaName(); - fQtc.postQueryTele(qts); - - result = processor->processPackage(alterTableStmt); - + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(alterTableStmt.fSessionID ); + AlterTableProcessor processor; + processor.fTxnid.id = fTxnid.id; + processor.fTxnid.valid = true; + PKNameMap::iterator it = pkNameMap.find(alterTableStmt.fSessionID); + if (it == pkNameMap.end()) + //throw (NO_PKNAME_AVAILABLE); + // TODO: should check if this createtablestmt has primary key + processor.PKName(""); + else + processor.PKName((*it).second); + result = processor.processPackage(alterTableStmt); + if (it != pkNameMap.end()) + pkNameMap.erase(it); systemCatalogPtr->removeCalpontSystemCatalog( alterTableStmt.fSessionID ); systemCatalogPtr->removeCalpontSystemCatalog( alterTableStmt.fSessionID | 0x80000000); - - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.end_time = QueryTeleClient::timeNowms(); - fQtc.postQueryTele(qts); } break; @@ -160,78 +162,37 @@ struct PackageHandler { DropTableStatement dropTableStmt; dropTableStmt.unserialize(fByteStream); - boost::shared_ptr systemCatalogPtr = - CalpontSystemCatalog::makeCalpontSystemCatalog(dropTableStmt.fSessionID ); - boost::scoped_ptr processor(new DropTableProcessor(fDbrm)); - - processor->fTxnid.id = fTxnid.id; - processor->fTxnid.valid = true; - - QueryTeleStats qts; - qts.query_uuid = QueryTeleClient::genUUID(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = dropTableStmt.fSessionID; - qts.query_type = "DROP"; - qts.query = dropTableStmt.fSql; - qts.system_name = fOamCache->getSystemName(); - qts.module_name = fOamCache->getModuleName(); - qts.schema_name = dropTableStmt.schemaName(); - fQtc.postQueryTele(qts); - + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropTableStmt.fSessionID ); + boost::scoped_ptr processor(new DropTableProcessor()); + (processor->fTxnid).id = fTxnid.id; + (processor->fTxnid).valid = true; //cout << "Drop table using txnid " << fTxnid.id << endl; result = processor->processPackage(dropTableStmt); - systemCatalogPtr->removeCalpontSystemCatalog( dropTableStmt.fSessionID ); systemCatalogPtr->removeCalpontSystemCatalog( dropTableStmt.fSessionID | 0x80000000); - - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.end_time = QueryTeleClient::timeNowms(); - fQtc.postQueryTele(qts); } break; - case ddlpackage::DDL_TRUNC_TABLE_STATEMENT: { TruncTableStatement truncTableStmt; truncTableStmt.unserialize(fByteStream); boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(truncTableStmt.fSessionID); - boost::scoped_ptr processor(new TruncTableProcessor(fDbrm)); - - processor->fTxnid.id = fTxnid.id; - processor->fTxnid.valid = true; - - QueryTeleStats qts; - qts.query_uuid = QueryTeleClient::genUUID(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = truncTableStmt.fSessionID; - qts.query_type = "TRUNCATE"; - qts.query = truncTableStmt.fSql; - qts.system_name = fOamCache->getSystemName(); - qts.module_name = fOamCache->getModuleName(); - qts.schema_name = truncTableStmt.schemaName(); - fQtc.postQueryTele(qts); - + boost::scoped_ptr processor(new TruncTableProcessor()); + (processor->fTxnid).id = fTxnid.id; + (processor->fTxnid).valid = true; result = processor->processPackage(truncTableStmt); - systemCatalogPtr->removeCalpontSystemCatalog(truncTableStmt.fSessionID ); systemCatalogPtr->removeCalpontSystemCatalog(truncTableStmt.fSessionID | 0x80000000); - - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.end_time = QueryTeleClient::timeNowms(); - fQtc.postQueryTele(qts); } break; - case ddlpackage::DDL_MARK_PARTITION_STATEMENT: { MarkPartitionStatement markPartitionStmt; markPartitionStmt.unserialize(fByteStream); boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(markPartitionStmt.fSessionID); - boost::scoped_ptr processor(new MarkPartitionProcessor(fDbrm)); + boost::scoped_ptr processor(new MarkPartitionProcessor()); (processor->fTxnid).id = fTxnid.id; (processor->fTxnid).valid = true; result = processor->processPackage(markPartitionStmt); @@ -239,14 +200,13 @@ struct PackageHandler systemCatalogPtr->removeCalpontSystemCatalog(markPartitionStmt.fSessionID | 0x80000000); } break; - case ddlpackage::DDL_RESTORE_PARTITION_STATEMENT: { RestorePartitionStatement restorePartitionStmt; restorePartitionStmt.unserialize(fByteStream); boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(restorePartitionStmt.fSessionID); - boost::scoped_ptr processor(new RestorePartitionProcessor(fDbrm)); + boost::scoped_ptr processor(new RestorePartitionProcessor()); (processor->fTxnid).id = fTxnid.id; (processor->fTxnid).valid = true; result = processor->processPackage(restorePartitionStmt); @@ -254,14 +214,13 @@ struct PackageHandler systemCatalogPtr->removeCalpontSystemCatalog(restorePartitionStmt.fSessionID | 0x80000000); } break; - case ddlpackage::DDL_DROP_PARTITION_STATEMENT: { DropPartitionStatement dropPartitionStmt; dropPartitionStmt.unserialize(fByteStream); boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropPartitionStmt.fSessionID); - boost::scoped_ptr processor(new DropPartitionProcessor(fDbrm)); + boost::scoped_ptr processor(new DropPartitionProcessor()); (processor->fTxnid).id = fTxnid.id; (processor->fTxnid).valid = true; result = processor->processPackage(dropPartitionStmt); @@ -269,10 +228,21 @@ struct PackageHandler systemCatalogPtr->removeCalpontSystemCatalog(dropPartitionStmt.fSessionID | 0x80000000); } break; - +#if 0 + case ddlpackage::DDL_DROP_INDEX_STATEMENT: + { + DropIndexStatement dropIndexStmt; + dropIndexStmt.unserialize(fByteStream); + boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropIndexStmt.fSessionID ); + DropIndexProcessor processor; + result = processor.processPackage(dropIndexStmt); + systemCatalogPtr->CalpontSystemCatalog::makeCalpontSystemCatalog(dropIndexStmt.fSessionID ); + systemCatalogPtr->CalpontSystemCatalog::makeCalpontSystemCatalog(dropIndexStmt.fSessionID | 0x80000000); + } + break; +#endif default: - throw UNRECOGNIZED_PACKAGE_TYPE; - break; + throw(UNRECOGNIZED_PACKAGE_TYPE); } //@Bug 3427. No need to log user rror, just return the message to user. @@ -284,12 +254,12 @@ struct PackageHandler ml.logErrorMessage( result.message ); } - cleanPMSysCache(); + //cleanPMSysCache(); messageqcpp::ByteStream results; messageqcpp::ByteStream::byte status = result.result; results << status; results << result.message.msg(); - + fIos.write(results); fIos.close(); @@ -306,7 +276,7 @@ struct PackageHandler messageqcpp::ByteStream::byte status = DDLPackageProcessor::CREATE_ERROR; results << status; results << string(idbEx.what()); - + fIos.write(results); fIos.close(); @@ -321,17 +291,15 @@ struct PackageHandler messageqcpp::IOSocket fIos; messageqcpp::ByteStream fByteStream; messageqcpp::ByteStream::quadbyte fPackageType; - BRM::TxnID fTxnid; - BRM::DBRM* fDbrm; - QueryTeleClient fQtc; - oam::OamCache* fOamCache; + BRM::TxnID fTxnid; + + }; } namespace ddlprocessor { - DDLProcessor::DDLProcessor( int packageMaxThreads, int packageWorkQueueSize ) :fPackageMaxThreads(packageMaxThreads), fPackageWorkQueueSize(packageWorkQueueSize), fMqServer(DDLProcName) @@ -340,21 +308,10 @@ DDLProcessor::DDLProcessor( int packageMaxThreads, int packageWorkQueueSize ) fDdlPackagepool.setQueueSize(fPackageWorkQueueSize); csc = CalpontSystemCatalog::makeCalpontSystemCatalog(); csc->identity(CalpontSystemCatalog::EC); - string teleServerHost(config::Config::makeConfig()->getConfig("QueryTele", "Host")); - if (!teleServerHost.empty()) - { - int teleServerPort = config::Config::fromText(config::Config::makeConfig()->getConfig("QueryTele", "Port")); - if (teleServerPort > 0) - { - fQtc.serverParms(QueryTeleServerParms(teleServerHost, teleServerPort)); - } - } + fWEClient = WriteEngine::WEClients::instance(WriteEngine::WEClients::DDLPROC); + fPMCount = fWEClient->getPmCount(); } -DDLProcessor::~DDLProcessor() -{ - -} void DDLProcessor::process() { DBRM dbrm; @@ -362,22 +319,16 @@ void DDLProcessor::process() messageqcpp::ByteStream bs; PackageHandler handler; messageqcpp::ByteStream::quadbyte packageType; - bool concurrentSupport = true; - string concurrentTranStr = config::Config::makeConfig()->getConfig("SystemConfig", "ConcurrentTransactions"); - if ( concurrentTranStr.length() != 0 ) - { - if ((concurrentTranStr.compare("N") == 0) || (concurrentTranStr.compare("n") == 0)) - concurrentSupport = false; - } + cout << "DDLProc is ready..." << endl; - + try { for (;;) { ios = fMqServer.accept(); bs = ios.read(); - uint32_t sessionID; + u_int32_t sessionID; bs >> sessionID; bs >> packageType; @@ -427,13 +378,20 @@ void DDLProcessor::process() continue; } } - + +#ifdef SERIALIZE_DDL_DML_CPIMPORT + //Check if any other active transaction + bool bIsDbrmUp = true; + bool anyOtherActiveTransaction = true; + execplan::SessionManager sessionManager; + BRM::SIDTIDEntry blockingsid; +#endif //check whether the system is ready to process statement. if (dbrm.getSystemReady() < 1) { messageqcpp::ByteStream results; messageqcpp::ByteStream::byte status = DDLPackageProcessor::NOT_ACCEPTING_PACKAGES; - + results << status; string msg ("System is not ready yet. Please try again." ); @@ -443,252 +401,196 @@ void DDLProcessor::process() ios.close(); continue; } - - BRM::TxnID txnid; - int rc = 0; - if (!concurrentSupport) - { - //Check if any other active transaction - bool bIsDbrmUp = true; - bool anyOtherActiveTransaction = true; - execplan::SessionManager sessionManager; - BRM::SIDTIDEntry blockingsid; - int i = 0; - int waitPeriod = 10; - //@Bug 2487 Check transaction map every 1/10 second - - int sleepTime = 100; // sleep 100 milliseconds between checks - int numTries = 10; // try 10 times per second - - string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); - if ( waitPeriodStr.length() != 0 ) - waitPeriod = static_cast(config::Config::fromText(waitPeriodStr)); - - numTries = waitPeriod * 10; - struct timespec rm_ts; - - rm_ts.tv_sec = sleepTime/1000; - rm_ts.tv_nsec = sleepTime%1000 *1000000; - //cout << "starting i = " << i << endl; - //anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp ); - while (anyOtherActiveTransaction) - { - anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, - blockingsid ); - if (anyOtherActiveTransaction) - { - for ( ; i < numTries; i++ ) - { + int i = 0; + int waitPeriod = 10; + //@Bug 2487 Check transaction map every 1/10 second + + int sleepTime = 100; // sleep 100 milliseconds between checks + int numTries = 10; // try 10 times per second + +#ifdef SERIALIZE_DDL_DML_CPIMPORT + string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); + if ( waitPeriodStr.length() != 0 ) + waitPeriod = static_cast(config::Config::fromText(waitPeriodStr)); + + numTries = waitPeriod * 10; + struct timespec rm_ts; + + rm_ts.tv_sec = sleepTime/1000; + rm_ts.tv_nsec = sleepTime%1000 *1000000; + //cout << "starting i = " << i << endl; + BRM::TxnID txnid; + int rc = 0; + //anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp ); + while (anyOtherActiveTransaction) + { + anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, + blockingsid ); + if (anyOtherActiveTransaction) + { + for ( ; i < numTries; i++ ) + { #ifdef _MSC_VER - Sleep(rm_ts.tv_sec * 1000); + Sleep(rm_ts.tv_sec * 1000); #else - struct timespec abs_ts; - //cout << "session " << sessionID << " nanosleep on package type " << (int)packageType << endl; - do - { - abs_ts.tv_sec = rm_ts.tv_sec; - abs_ts.tv_nsec = rm_ts.tv_nsec; - } - while(nanosleep(&abs_ts,&rm_ts) < 0); + struct timespec abs_ts; + //cout << "session " << sessionID << " nanosleep on package type " << (int)packageType << endl; + do + { + abs_ts.tv_sec = rm_ts.tv_sec; + abs_ts.tv_nsec = rm_ts.tv_nsec; + } + while(nanosleep(&abs_ts,&rm_ts) < 0); #endif - anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, - blockingsid ); - if ( !anyOtherActiveTransaction ) - { - //cout << "Ready to process type " << (int)packageType << endl; - txnid = sessionManager.getTxnID(sessionID); - if ( !txnid.valid ) - { - txnid = sessionManager.newTxnID(sessionID, true, true); - if (txnid.valid) { - //cout << "Ready to process type " << (int)packageType << " with txnid " << txnid.id << endl; - anyOtherActiveTransaction = false; - break; - } - else - { - anyOtherActiveTransaction = true; - } - } - else - { - string errorMsg; - rc = commitTransaction(txnid.id, errorMsg); - if ( rc != 0) - throw std::runtime_error(errorMsg); + anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, + blockingsid ); + if ( !anyOtherActiveTransaction ) + { + //cout << "Ready to process type " << (int)packageType << endl; + txnid = sessionManager.getTxnID(sessionID); + if ( !txnid.valid ) + { + txnid = sessionManager.newTxnID(sessionID, true, true); + if (txnid.valid) { + //cout << "Ready to process type " << (int)packageType << " with txnid " << txnid.id << endl; + anyOtherActiveTransaction = false; + break; + } + else + { + anyOtherActiveTransaction = true; + } + } + else + { + string errorMsg; + rc = commitTransaction(txnid.id, errorMsg); + if ( rc != 0) + throw std::runtime_error(errorMsg); //need unlock the table. - std::vector tableLocks = dbrm.getAllTableLocks(); - bool lockReleased = true; - for (unsigned k = 0; k < tableLocks.size(); k++) - { - if (tableLocks[k].ownerTxnID == txnid.id) - { - lockReleased = dbrm.releaseTableLock(tableLocks[k].id); - if (!lockReleased) - { - ostringstream os; - os << "tablelock id " << tableLocks[k].id << " is not found"; - throw std::runtime_error(os.str()); - } - } - } - dbrm.committed(txnid); - txnid = dbrm.newTxnID(sessionID, true, true); - if (txnid.valid) { - //cout << "Ready to process type " << (int)packageType << " with txnid " << txnid.id << endl; - anyOtherActiveTransaction = false; - break; - } - else - { - anyOtherActiveTransaction = true; - } - } - } - } + std::vector tableLocks = dbrm.getAllTableLocks(); + bool lockReleased = true; + for (unsigned k = 0; k < tableLocks.size(); k++) + { + if (tableLocks[k].ownerTxnID == txnid.id) + { + lockReleased = dbrm.releaseTableLock(tableLocks[k].id); + if (!lockReleased) + { + ostringstream os; + os << "tablelock id " << tableLocks[k].id << " is not found"; + throw std::runtime_error(os.str()); + } + } + } + sessionManager.committed(txnid); + txnid = sessionManager.newTxnID(sessionID, true, true); + if (txnid.valid) { + //cout << "Ready to process type " << (int)packageType << " with txnid " << txnid.id << endl; + anyOtherActiveTransaction = false; + break; + } + else + { + anyOtherActiveTransaction = true; + } + } + } + } //cout << "ending i = " << i << endl; - } - else - { - //cout << "Ready to process type " << (int)packageType << endl; - txnid = sessionManager.getTxnID(sessionID); - if ( !txnid.valid ) - { - txnid = sessionManager.newTxnID(sessionID, true, true); - if (!txnid.valid) { - //cout << "cannot get txnid " << (int)packageType << " for session " << sessionID << endl; - anyOtherActiveTransaction = true; - } - else - { - anyOtherActiveTransaction = false; - } - } - else - { - string errorMsg; - rc = commitTransaction(txnid.id, errorMsg); - if ( rc != 0) - throw std::runtime_error(errorMsg); - //need unlock the table. - std::vector tableLocks = dbrm.getAllTableLocks(); - bool lockReleased = true; - for (unsigned k = 0; k < tableLocks.size(); k++) - { - if (tableLocks[k].ownerTxnID == txnid.id) - { - lockReleased = dbrm.releaseTableLock(tableLocks[k].id); - if (!lockReleased) - { - ostringstream os; - os << "tablelock id " << tableLocks[k].id << " is not found"; - throw std::runtime_error(os.str()); - } - } - } - sessionManager.committed(txnid); - txnid = sessionManager.newTxnID(sessionID, true, true); - if (!txnid.valid) { + } + else + { + //cout << "Ready to process type " << (int)packageType << endl; + txnid = sessionManager.getTxnID(sessionID); + if ( !txnid.valid ) + { + txnid = sessionManager.newTxnID(sessionID, true, true); + if (!txnid.valid) { + //cout << "cannot get txnid " << (int)packageType << " for session " << sessionID << endl; + anyOtherActiveTransaction = true; + } + else + { + anyOtherActiveTransaction = false; + } + } + else + { + string errorMsg; + rc = commitTransaction(txnid.id, errorMsg); + if ( rc != 0) + throw std::runtime_error(errorMsg); + //need unlock the table. + std::vector tableLocks = dbrm.getAllTableLocks(); + bool lockReleased = true; + for (unsigned k = 0; k < tableLocks.size(); k++) + { + if (tableLocks[k].ownerTxnID == txnid.id) + { + lockReleased = dbrm.releaseTableLock(tableLocks[k].id); + if (!lockReleased) + { + ostringstream os; + os << "tablelock id " << tableLocks[k].id << " is not found"; + throw std::runtime_error(os.str()); + } + } + } + sessionManager.committed(txnid); + txnid = sessionManager.newTxnID(sessionID, true, true); + if (!txnid.valid) { //cout << "cannot get txnid " << (int)packageType << " for session " << sessionID << endl; - anyOtherActiveTransaction = true; - } - else - { - anyOtherActiveTransaction = false; - } - } - } - - if ((anyOtherActiveTransaction) && (i >= numTries)) - { + anyOtherActiveTransaction = true; + } + else + { + anyOtherActiveTransaction = false; + } + } + } + + if ((anyOtherActiveTransaction) && (i >= numTries)) + { //cout << " Erroring out on package type " << (int)packageType << endl; - break; - } - } - - if ((anyOtherActiveTransaction) && (i >= numTries)) - { - messageqcpp::ByteStream results; - messageqcpp::ByteStream::byte status = DDLPackageProcessor::NOT_ACCEPTING_PACKAGES; - - results << status; - Message::Args args; - args.add(static_cast(blockingsid.sessionid)); - - results << IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args); - //@Bug 3854 Log to debug.log - LoggingID logid(15, 0, 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add(IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args)); - msg.format( args1 ); - logging::Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - - ios.write(results); - - ios.close(); - } - else - { - handler.fIos = ios; - handler.fByteStream = bs; - handler.fPackageType = packageType; - handler.fTxnid = txnid; - handler.fDbrm = &dbrm; - handler.fQtc = fQtc; - handler.fOamCache = oam::OamCache::makeOamCache(); - fDdlPackagepool.invoke(handler); - - } - } - else - { - txnid = dbrm.getTxnID(sessionID); - if ( !txnid.valid ) - { - txnid = dbrm.newTxnID(sessionID, true, true); - if (!txnid.valid) { - throw std::runtime_error( std::string("Unable to start a transaction. Check critical log.") ); - } - } - else - { - string errorMsg; - rc = commitTransaction(txnid.id, errorMsg); - if ( rc != 0) - throw std::runtime_error(errorMsg); - //need unlock the table. - std::vector tableLocks = dbrm.getAllTableLocks(); - bool lockReleased = true; - for (unsigned k = 0; k < tableLocks.size(); k++) - { - if (tableLocks[k].ownerTxnID == txnid.id) - { - lockReleased = dbrm.releaseTableLock(tableLocks[k].id); - if (!lockReleased) - { - ostringstream os; - os << "tablelock id " << tableLocks[k].id << " is not found"; - throw std::runtime_error(os.str()); - } - } - } - dbrm.committed(txnid); - txnid = dbrm.newTxnID(sessionID, true, true); - if (!txnid.valid) { - throw std::runtime_error( std::string("Unable to start a transaction. Check critical log.") ); - } - } - handler.fIos = ios; - handler.fByteStream = bs; - handler.fPackageType = packageType; - handler.fTxnid = txnid; - handler.fDbrm = &dbrm; - handler.fQtc = fQtc; - handler.fOamCache = oam::OamCache::makeOamCache(); - fDdlPackagepool.invoke(handler); - } + break; + } + } +#endif +#ifdef SERIALIZE_DDL_DML_CPIMPORT + if ((anyOtherActiveTransaction) && (i >= numTries)) + { + messageqcpp::ByteStream results; + messageqcpp::ByteStream::byte status = DDLPackageProcessor::NOT_ACCEPTING_PACKAGES; + + results << status; + Message::Args args; + args.add(static_cast(blockingsid.sessionid)); + + results << IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args); + //@Bug 3854 Log to debug.log + LoggingID logid(15, 0, 0); + logging::Message::Args args1; + logging::Message msg(1); + args1.add(IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args)); + msg.format( args1 ); + logging::Logger logger(logid.fSubsysID); + logger.logMessage(LOG_TYPE_DEBUG, msg, logid); + + ios.write(results); + + ios.close(); + } + else + { + handler.fIos = ios; + handler.fByteStream = bs; + handler.fPackageType = packageType; + handler.fTxnid = txnid; + fDdlPackagepool.invoke(handler); + + } +#endif } } catch (exception& ex) @@ -696,7 +598,7 @@ void DDLProcessor::process() cerr << ex.what() << endl; messageqcpp::ByteStream results; messageqcpp::ByteStream::byte status = DDLPackageProcessor::NOT_ACCEPTING_PACKAGES; - + results << status; results << ex.what(); ios.write(results); @@ -708,7 +610,7 @@ void DDLProcessor::process() cerr << "Caught unknown exception!" << endl; messageqcpp::ByteStream results; messageqcpp::ByteStream::byte status = DDLPackageProcessor::NOT_ACCEPTING_PACKAGES; - + results << status; results << "Caught unknown exception!"; ios.write(results); @@ -722,8 +624,6 @@ void DDLProcessor::process() int DDLProcessor::commitTransaction(uint32_t txnID, std::string & errorMsg) { - fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DDLPROC); - fPMCount = fWEClient->getPmCount(); ByteStream bytestream; DBRM dbrm; uint64_t uniqueId = dbrm.getUnique64(); @@ -731,7 +631,7 @@ int DDLProcessor::commitTransaction(uint32_t txnID, std::string & errorMsg) bytestream << (ByteStream::byte)WE_SVR_COMMIT_VERSION; bytestream << uniqueId; bytestream << txnID; - uint32_t msgRecived = 0; + uint msgRecived = 0; fWEClient->write_to_all(bytestream); boost::shared_ptr bsIn; bsIn.reset(new ByteStream()); @@ -745,10 +645,10 @@ int DDLProcessor::commitTransaction(uint32_t txnID, std::string & errorMsg) if ( bsIn->length() == 0 ) //read error { rc = 1; - errorMsg = "DDL cannot communicate with WES"; + errorMsg = "DDL cannot communicate with WES"; fWEClient->removeQueue(uniqueId); break; - } + } else { *bsIn >> tmp8; rc = tmp8; @@ -758,11 +658,9 @@ int DDLProcessor::commitTransaction(uint32_t txnID, std::string & errorMsg) break; } else - msgRecived++; + msgRecived++; } } - delete fWEClient; - fWEClient = 0; return rc; } } // namespace ddlprocessor diff --git a/ddlproc/ddlprocessor.h b/ddlproc/ddlprocessor.h index f822ad78..10c401b4 100644 --- a/ddlproc/ddlprocessor.h +++ b/ddlproc/ddlprocessor.h @@ -27,7 +27,6 @@ #include "ddlproc.h" #include "threadpool.h" #include "calpontsystemcatalog.h" -#include "querytele.h" namespace ddlprocessor { @@ -42,7 +41,7 @@ class DDLProcessor * @param packageWorkQueueSize the maximum number of ddl packages in the work queue */ DDLProcessor( int packageMaxThreads, int packageWorkQueueSize ); - ~DDLProcessor(); + /** @brief entry point for the DDLProcessor */ void process(); @@ -81,9 +80,8 @@ class DDLProcessor messageqcpp::MessageQueueServer fMqServer; boost::shared_ptr csc; - WriteEngine::WEClients* fWEClient; - uint32_t fPMCount; - querytele::QueryTeleClient fQtc; + WriteEngine::WEClients* fWEClient; + uint fPMCount; }; diff --git a/ddlproc/resource.h b/ddlproc/resource.h deleted file mode 100644 index 66f10d20..00000000 --- a/ddlproc/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by DDLProc.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/decomsvr/DecomSvr.rc b/decomsvr/DecomSvr.rc deleted file mode 100644 index 38e974fa..00000000 --- a/decomsvr/DecomSvr.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB V1 Decompression Server" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "DecomSvr" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "DecomSvr.exe" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/decomsvr/DecomSvr.vcxproj b/decomsvr/DecomSvr.vcxproj deleted file mode 100644 index 8e3bb55a..00000000 --- a/decomsvr/DecomSvr.vcxproj +++ /dev/null @@ -1,290 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {E7F6F8A8-9DDE-4FC4-8F80-25AB98922E6F} - DecomSvr - Win32Proj - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - true - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - true - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - false - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - false - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - false - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - false - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - - Level3 - EditAndContinue - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;%(AdditionalLibraryDirectories) - true - Console - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - - Level3 - ProgramDatabase - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - Console - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - Level3 - ProgramDatabase - 4996;4244;4267;%(DisableSpecificWarnings) - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;%(AdditionalLibraryDirectories) - true - Console - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - Level3 - ProgramDatabase - 4996;4244;4267;%(DisableSpecificWarnings) - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - Console - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB V1 Decompression Server" $(SolutionDir)..\..x64\Release\DecomSvr.exe - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - Level3 - ProgramDatabase - 4996;4244;4267;%(DisableSpecificWarnings) - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;%(AdditionalLibraryDirectories) - true - Console - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - Level3 - ProgramDatabase - 4996;4244;4267;%(DisableSpecificWarnings) - false - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - Console - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB V1 Decompression Server" $(SolutionDir)..\..\x64\EnterpriseRelease\DecomSvr.exe - - - - - - - - - - - - - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - - - - \ No newline at end of file diff --git a/decomsvr/DecomSvr.vcxproj.filters b/decomsvr/DecomSvr.vcxproj.filters deleted file mode 100644 index 3166cce9..00000000 --- a/decomsvr/DecomSvr.vcxproj.filters +++ /dev/null @@ -1,35 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/decomsvr/Makefile.am b/decomsvr/Makefile.am index d5436671..b2159a8b 100644 --- a/decomsvr/Makefile.am +++ b/decomsvr/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id$ ## Process this file with automake to produce Makefile.in @@ -25,7 +8,7 @@ AM_LDFLAGS = $(idb_ldflags) bin_PROGRAMS = DecomSvr DecomSvr_SOURCES = quicklz.c server.cpp DecomSvr_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -DecomSvr_LDFLAGS = $(idb_common_ldflags) -lboost_idb $(AM_LDFLAGS) -lpthread -lrt +DecomSvr_LDFLAGS = $(idb_common_ldflags) -lboost_idb $(AM_LDFLAGS) -lpthread test: diff --git a/decomsvr/Makefile.in b/decomsvr/Makefile.in index 2c7691d9..7f95ad43 100644 --- a/decomsvr/Makefile.in +++ b/decomsvr/Makefile.in @@ -14,23 +14,6 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id$ srcdir = @srcdir@ @@ -59,9 +42,8 @@ bin_PROGRAMS = DecomSvr$(EXEEXT) subdir = decomsvr DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -157,9 +139,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -201,7 +180,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -215,11 +193,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -236,7 +209,7 @@ AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) DecomSvr_SOURCES = quicklz.c server.cpp DecomSvr_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -DecomSvr_LDFLAGS = $(idb_common_ldflags) -lboost_idb $(AM_LDFLAGS) -lpthread -lrt +DecomSvr_LDFLAGS = $(idb_common_ldflags) -lboost_idb $(AM_LDFLAGS) -lpthread all: all-am .SUFFIXES: diff --git a/decomsvr/resource.h b/decomsvr/resource.h deleted file mode 100644 index bddfca70..00000000 --- a/decomsvr/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by DecomSvr.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/decomsvr/server.cpp b/decomsvr/server.cpp index cd7938eb..a2b12a2d 100644 --- a/decomsvr/server.cpp +++ b/decomsvr/server.cpp @@ -105,7 +105,7 @@ const uint8_t CHUNK_MAGIC1 = 0xff; const int SIG_OFFSET = 0; const int CHECKSUM_OFFSET = 1; const int LEN_OFFSET = 5; -const uint32_t HEADER_SIZE = 9; +const uint HEADER_SIZE = 9; const int ERR_OK = 0; const int ERR_CHECKSUM = -1; @@ -138,6 +138,15 @@ void log(const string &s) cerr << s << endl; } +struct CompressedDBFileHeader +{ + uint64_t fMagicNumber; + uint64_t fVersionNum; + uint64_t fCompressionType; + uint64_t fHeaderSize; + uint64_t fBlockCount; +}; + struct DecomMessage { DecomMessage() : isValid(false) { } @@ -280,9 +289,6 @@ void readn(int fd, void* buf, const size_t wanted) ssize_t rrc = -1; pollfd fds[1]; int en = 0; - int prc = 0; - ostringstream oss; - unsigned zerocount=0; fds[0].fd = fd; fds[0].events = POLLIN; @@ -290,22 +296,7 @@ void readn(int fd, void* buf, const size_t wanted) while (wanted > sofar) { fds[0].revents = 0; - errno = 0; - prc = poll(fds, 1, -1); - en = errno; - if (prc <= 0) - { - if (en == EAGAIN || en == EINTR || en == 512) - continue; - oss << "decomsvr::readn: poll() returned " << prc << " (" << strerror(en) << ")"; - idbassert_s(0, oss.str()); - } - //no data on fd - if ((fds[0].revents & POLLIN) == 0) - { - oss << "decomsvr::readn: revents for fd " << fds[0].fd << " was " << fds[0].revents; - idbassert_s(0, oss.str()); - } + poll(fds, 1, -1); errno = 0; rrc = read(fd, (p + sofar), needed); en = errno; @@ -313,24 +304,10 @@ void readn(int fd, void* buf, const size_t wanted) { if (en == EAGAIN || en == EINTR || en == 512) continue; - oss << "decomsvr::readn: read() returned " << rrc << " (" << strerror(en) << ")"; + ostringstream oss; + oss << "decomsrv: read() returned " << rrc << " (" << strerror(en) << ")"; idbassert_s(0, oss.str()); } - if (rrc == 0) - { - ostringstream os; - zerocount++; - if (zerocount >= 10) - { - os << "decomsvr::readn(): too many zero-length reads!"; - idbassert_s(0, oss.str()); - } - os << "decomsvr::readn(): zero-length read on fd " << fd; - log(os.str()); - sleep(1); - } - else - zerocount = 0; needed -= rrc; sofar += rrc; } @@ -653,30 +630,21 @@ void ThreadFunc::operator()() CloseHandle(h); cleaner.handle = INVALID_HANDLE_VALUE; #else - scoped_array in; - int fd=-1; - try - { - fd = open(cfifo.c_str(), O_RDONLY); - idbassert_s(fd >= 0, "when opening data fifo for input"); + int fd = open(cfifo.c_str(), O_RDONLY); + idbassert_s(fd >= 0, "when opening data fifo for input"); +// if (fd < 0) +// throw runtime_error("when opening data fifo for input"); - cleaner.fd = fd; + cleaner.fd = fd; - readn(fd, &ccount, 8); + readn(fd, &ccount, 8); - in.reset(new char[ccount]); + scoped_array in(new char[ccount]); - readn(fd, in.get(), ccount); + readn(fd, in.get(), ccount); - close(fd); - cleaner.fd = -1; - } - catch (std::exception& ) - { - //This is a protocol error and returning here will clean up resources on - //the stack unwind. - return; - } + close(fd); + cleaner.fd = -1; #endif #ifdef _MSC_VER h = CreateFile(ufifo.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); @@ -712,42 +680,39 @@ void ThreadFunc::operator()() CloseHandle(h); cleaner.handle = INVALID_HANDLE_VALUE; #else - scoped_array out; - try - { - fd = open(ufifo.c_str(), O_WRONLY); - idbassert_s(fd >= 0, "when opening data fifo for output"); - //if (fd < 0) - // throw runtime_error("when opening data fifo for output"); - - cleaner.fd = fd; - - uint64_t outlen = 512 * 1024 * 8; - unsigned int ol = outlen; + fd = open(ufifo.c_str(), O_WRONLY); + idbassert_s(fd >= 0, "when opening data fifo for output"); + //if (fd < 0) + // throw runtime_error("when opening data fifo for output"); - out.reset(new char[outlen]); + cleaner.fd = fd; - int crc = uncompressBlock(in.get(), ccount, reinterpret_cast(out.get()), ol); - if (crc != ERR_OK) - outlen = 0; - else - outlen = ol; + uint64_t outlen = 512 * 1024 * 8; + unsigned int ol = outlen; - rrc = writen(fd, &outlen, 8); - idbassert_s(rrc == 8, "when writing len to data fifo"); + scoped_array out(new char[outlen]); - rrc = writen(fd, out.get(), outlen); - idbassert_s(rrc == (ssize_t)outlen, "when writing data to data fifo"); + int crc = uncompressBlock(in.get(), ccount, reinterpret_cast(out.get()), ol); + if (crc != ERR_OK) + outlen = 0; + else + outlen = ol; - close(fd); - cleaner.fd = -1; - } - catch (std::exception& ) - { - //There was an error writing the uncompressed data back to PrimProc. Cleanup by - //unwinding the stack - return; - } + rrc = writen(fd, &outlen, 8); + idbassert_s(rrc == 8, "when writing len to data fifo"); + //if (rrc != 8) + //{ + // throw runtime_error("when writing len to data fifo"); + //} + rrc = writen(fd, out.get(), outlen); + idbassert_s(rrc == (ssize_t)outlen, "when writing data to data fifo"); + //if (rrc != (ssize_t)outlen) + //{ + // throw runtime_error("when writing data to data fifo"); + //} + + close(fd); + cleaner.fd = -1; #endif } diff --git a/dmlib/Makefile.am b/dmlib/Makefile.am new file mode 100644 index 00000000..bd6bca50 --- /dev/null +++ b/dmlib/Makefile.am @@ -0,0 +1,37 @@ +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +## Process this file with automake to produce Makefile.in + +AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) +AM_CFLAGS = $(idb_cflags) +AM_CXXFLAGS = $(idb_cxxflags) +AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) +lib_LTLIBRARIES = libdm.la +libdm_la_SOURCES = dm.c + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: + diff --git a/dmlib/dm.c b/dmlib/dm.c new file mode 100644 index 00000000..7cfb0313 --- /dev/null +++ b/dmlib/dm.c @@ -0,0 +1,256 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/** + * $Id: dm.c 414 2011-02-10 14:23:02Z rdempsey $ + * + * @file dm.c + * @author Robert King + * + * @brief Implementation file for the Disk Manager (dm) Library. + * + * This file contains the implementation for the following Disk Manager + * Library functions: + * + * - dmOid2FPath() + * - _doDir() + * - _doFile() + */ + +#include +#include + +#include "dm.h" + +#ifdef _MSC_VER +#define snprintf _snprintf +#endif + +#define STATIC static + +STATIC int _doDir(char* pBuffer, int blen, unsigned int val); //dmc-Branch +STATIC int _doFile(char* pBuffer, int blen, unsigned char val); + +/** @brief Converts an OID into a group if directories and a filename. +* +*/ +int dmFPath2Oid(dmFilePathArgs_t* pArgs, UINT32* OID) +{ + unsigned part; + + *OID = 0; + part = atoi(pArgs->pDirA); + if (part > 255) return -1; + *OID |= (part << 24); + part = atoi(pArgs->pDirB); + if (part > 255) return -1; + *OID |= (part << 16); + part = atoi(pArgs->pDirC); + if (part > 255) return -1; + *OID |= (part << 8); + part = atoi(&pArgs->pFName[4]); + if (part > 255) return -1; + *OID |= (part << 0); + return 0; +} + +/** @brief Converts an OID into a group if directories and a filename. +* +* This function takes a 32-bit Object ID (OID). If DLen is 0, then the +* OID is converted into 3 hierarchical directory names and a filename. +* If DLen is >0 then the OID is converted into 5 hierarchical directory +* names and a filename (using the partition and segment as additional +* input into the filepath. The actual location +* of the file is ////, or +* //////. The +* entry must be pre-pended by the calling application after calling +* this function. The value for is stored in the Calpont.xml +* configuration file. +* +* @param oid INPUT -- The Object Id. +* @param partition INPUT -- partition to be included in filepath. +* @param segment INPUT -- segment to be included in filepath. +* @param dmFilePathArgs* I/O -- Points to a buffer structure +* +* @return 0 if everything went OK. -1 if an error occured. Two +* kinds of errors are possible: +* +* - a null pointer was passed in +* - truncation occured. +* +* If a null buffer pointer is passed in, a return code +* of -1 will be returned FOR THAT BUFFER. +* +* Truncation can occur if the buffer length specified in +* dmFilePathArgs is too small. +* +* If a buffer's return code is not zero, the appropriate +* return code in dmfilePathArgs can be examined. If a +* buffer's return code is be less than zero, the +* corresponding buffer pointer was NULL. If it is greater +* or equal to the buffer's length argument, length is too small +*. +*/ +int dmOid2FPath(UINT32 oid, UINT32 partition, UINT32 segment, + dmFilePathArgs_t* pArgs) //dmc-Branch +{ + + pArgs->Arc = _doDir( + pArgs->pDirA, + pArgs->ALen, + (unsigned int)oid>>24); + + pArgs->Brc = _doDir( + pArgs->pDirB, + pArgs->BLen, + (unsigned int)(oid&0x00ff0000)>>16); + + pArgs->Crc = _doDir( + pArgs->pDirC, + pArgs->CLen, + (unsigned int)(oid&0x0000ff00)>>8); + +//dmc-Branch-Begin + // include partition and segment number in the file path if they are present + if (pArgs->DLen > 0) + { + pArgs->Drc = _doDir( + pArgs->pDirD, + pArgs->DLen, + (unsigned int)(oid&0x000000ff)); + + pArgs->Erc = _doDir( + pArgs->pDirE, + pArgs->ELen, + partition); + + pArgs->FNrc = _doFile( + pArgs->pFName, + pArgs->FNLen, + segment); + + if ( + (pArgs->Drc < 0) || + (pArgs->Erc < 0) + ) + return -1; + + if ( + (pArgs->Drc >= pArgs->ALen) || + (pArgs->Erc >= pArgs->ALen) + ) + return -1; + } + else + { + pArgs->FNrc = _doFile( + pArgs->pFName, + pArgs->FNLen, + (unsigned int)(oid&0x000000ff)); + } +//dmc-Branch-End + + if ( + (pArgs->Arc < 0) || + (pArgs->Brc < 0) || + (pArgs->Crc < 0) || + (pArgs->FNrc < 0) + ) + return -1; + + if ( + (pArgs->Arc >= pArgs->ALen) || + (pArgs->Brc >= pArgs->BLen) || + (pArgs->Crc >= pArgs->CLen) || + (pArgs->FNrc >= pArgs->FNLen) + ) + return -1; + else + return 0; +} + + + + +/** @brief Formats a directory name. + * + * This function takes a 8-bit value and converts it into a directory + * name. + * + * @param pBuffer OUPUT - A pointer to the output buffer. + * @param blen INPUT - The length of the output buffer, in bytes. + * @param val INPUT - value to be used in the formatted name. + * + * @return The number of characters in the output buffer is returned + * (not including the NULL terminator). -1 of the input buffer + * pointer is NULL. + * @note If the input pointer is invalid (points to unmapped memoty, + * for example,) this function can raise a segmentation violation + * or a bus error. + * + */ +STATIC int _doDir(char* pBuffer, int blen, unsigned int val) //dmc-Branch +{ + int rc; + + if (!pBuffer) + { + rc = -1; + + } else { + rc = snprintf(pBuffer, blen, "%03u.dir", val); //dmc-Branch + pBuffer[blen-1] = (char)0; + } + + return rc; +} + + + + +/** @brief Formats a file name. + * + * This function takes a 8-bit value and converts it into a file name. + * + * @param pBuffer OUPUT - A pointer to the output buffer. + * @param blen INPUT - The length of the output buffer, in bytes. + * @param val INPUT - value to be used in the formatted name. + * + * @return The number of characters in the output buffer is returned + * (not including the NULL terminator). -1 of the input buffer + * pointer is NULL. + * @note If the input pointer is invalid (points to unmapped memoty, + * for example,) this function can raise a segmentation violation + * or a bus error. + * + */ +STATIC int _doFile(char* pBuffer, int blen, unsigned char val) +{ + int rc; + + if (!pBuffer) + { + rc = -1; + + } else { + rc = snprintf(pBuffer, blen, "FILE%03d.cdf", val); + pBuffer[blen-1] = (char)0; + } + + return rc; +} + diff --git a/dmlib/dm.h b/dmlib/dm.h new file mode 100644 index 00000000..79be3786 --- /dev/null +++ b/dmlib/dm.h @@ -0,0 +1,101 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/** +* $Id: dm.h 407 2011-02-03 17:54:57Z rdempsey $ +* +* @file dm.h +* @author Robert King +* +* @brief Interface file for the Disk Manager (dm) Library. +* +* This file contains the interface specification for the Disk Manager +* Library. Additionally, any structures used by this interface are +* defined here as well. +* +* +*/ +#ifndef DM_H +#define DM_H + +#ifndef _MSC_VER +#include +#ifndef _BASETSD_H_ +typedef uint32_t UINT32; +#endif +#else +typedef unsigned __int32 UINT32; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief Contains directory and filename buffers. +* +* dmFilePathArgs_t contains buffers for reporting back the directories +* and filename that correspond to an Object ID (OID) +* +* Directories are organized in a 3-layer tree (used for version buffer files): +* +* /// +* +* OR in a 5-layer tree (used for all other db files besides version buffer): +* +* ///// +* +* @note All buffers must be pre-allocated by the calling routine. +* @note 5-layer directory structure includes partition and segment number. +*/ +typedef struct +{ + char* pDirA; /**< OUT -- DirA's buffer*/ + char* pDirB; /**< OUT -- DirB's buffer */ + char* pDirC; /**< OUT -- DirC's buffer */ + char* pDirD; /**< OUT -- DirD's buffer */ //dmc-Branch + char* pDirE; /**< OUT -- DirE's buffer */ //dmc-Branch + char* pFName; /**< OUT -- Filename buffer */ + int ALen; /**< IN -- Size in bytes of DirA's Buffer. */ + int BLen; /**< IN -- Size in bytes of DirB's Buffer. */ + int CLen; /**< IN -- Size in bytes of DirC's Buffer. */ + int DLen; /**< IN -- Size in bytes of DirD's Buffer. */ //dmc-Branch + int ELen; /**< IN -- Size in bytes of DirE's Buffer. */ //dmc-Branch + int FNLen; /**< IN -- Size in bytes of Filename's Buffer. */ + int Arc; /**< OUT -- result code for formatting DirA. */ + int Brc; /**< OUT -- result code for formatting DirB. */ + int Crc; /**< OUT -- result code for formatting DirC. */ + int Drc; /**< OUT -- result code for formatting DirD. */ //dmc-Branch + int Erc; /**< OUT -- result code for formatting DirE. */ //dmc-Branch + int FNrc; /**< OUT -- result code for formatting Filename. */ +} dmFilePathArgs_t; + +/** +* @brief fill in dmFilePathArgs_t struct for OID. +*/ +int dmOid2FPath(UINT32 oid, UINT32 partition, UINT32 segment, dmFilePathArgs_t* pArgs); //dmc-Branch + +/** +* @brief calculate OID given dmFilePathArgs_t struct. +*/ +int dmFPath2Oid(dmFilePathArgs_t* pArgs, UINT32* oid); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dmlib/tdriver.c b/dmlib/tdriver.c new file mode 100644 index 00000000..5f988e12 --- /dev/null +++ b/dmlib/tdriver.c @@ -0,0 +1,280 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// $Id: tdriver.c 414 2011-02-10 14:23:02Z rdempsey $ + +#include +#include +#include +#include + + +#include "dm.h" + +int main(int argc, char** argv) +{ + char aBuff[10]; + char bBuff[10]; + char cBuff[10]; + char fnBuff[16]; + + int rc; + + dmFilePathArgs_t args; + + args.pDirA = aBuff; + args.pDirB = bBuff; + args.pDirC = cBuff; + args.pFName = fnBuff; + + + //-------------------------------------------------------------------------- + // test 1 - test for correctness + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = sizeof(bBuff); + args.CLen = sizeof(cBuff); + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0xd5aa9687, &args); + assert(strcmp(args.pDirA, "213.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "170.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "150.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE135.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == 0); + + + //-------------------------------------------------------------------------- + // test 2 - test for short numbers -- zero-fill + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = sizeof(bBuff); + args.CLen = sizeof(cBuff); + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0x00010203, &args); + assert(strcmp(args.pDirA, "000.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "001.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "002.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE003.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == 0); + + + //-------------------------------------------------------------------------- + // test 3 - test for ZERO + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = sizeof(bBuff); + args.CLen = sizeof(cBuff); + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0x00000000, &args); + assert(strcmp(args.pDirA, "000.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "000.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "000.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE000.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == 0); + + + //-------------------------------------------------------------------------- + // test 4 - test for MAXINT + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = sizeof(bBuff); + args.CLen = sizeof(cBuff); + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0xffffffff, &args); + assert(strcmp(args.pDirA, "255.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "255.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "255.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE255.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == 0); + + + //-------------------------------------------------------------------------- + // test 5 - test for buffer too small + //-------------------------------------------------------------------------- + args.ALen = 6; + args.BLen = sizeof(bBuff); + args.CLen = sizeof(cBuff); + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0xffffffff, &args); + assert(strcmp(args.pDirA, "255.d") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "255.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "255.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE255.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == -1); + + + + //-------------------------------------------------------------------------- + // test 6 - test for buffer too small + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = 6; + args.CLen = sizeof(cBuff); + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0xffffffff, &args); + assert(strcmp(args.pDirA, "255.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "255.d") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "255.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE255.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == -1); + + + + //-------------------------------------------------------------------------- + // test 7 - test for buffer too small + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = sizeof(bBuff); + args.CLen = 6; + args.FNLen = sizeof(fnBuff); + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0xffffffff, &args); + assert(strcmp(args.pDirA, "255.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "255.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "255.d") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE255.cdf") == 0); + assert(args.FNrc == 11); + assert(rc == -1); + + + + //-------------------------------------------------------------------------- + // test 8 - test for buffer too small + //-------------------------------------------------------------------------- + args.ALen = sizeof(aBuff); + args.BLen = sizeof(bBuff); + args.CLen = sizeof(bBuff); + args.FNLen = 10; + + args.Arc = 0; + args.Brc = 0; + args.Crc = 0; + args.FNrc = 0; + + rc = dmOid2FPath((UINT32)0xffffffff, &args); + assert(strcmp(args.pDirA, "255.dir") == 0); + assert(args.Arc == 7); + assert(strcmp(args.pDirB, "255.dir") == 0); + assert(args.Brc == 7); + assert(strcmp(args.pDirC, "255.dir") == 0); + assert(args.Crc == 7); + assert(strcmp(args.pFName, "FILE255.c") == 0); + assert(args.FNrc == 11); + assert(rc == -1); + + UINT32 OID = 0; + strcpy(args.pDirA, "000.dir"); + strcpy(args.pDirB, "001.dir"); + strcpy(args.pDirC, "002.dir"); + args.Arc = args.Brc = args.Crc = 7; + strcpy(args.pFName, "FILE003.cdf"); + args.FNrc = 11; + rc = dmFPath2Oid(&args, &OID); + assert(rc == 0); + assert(OID == (UINT32)0x00010203); + + strcpy(args.pDirA, "255.dir"); + strcpy(args.pDirB, "255.dir"); + strcpy(args.pDirC, "255.dir"); + strcpy(args.pFName, "FILE255.cdf"); + rc = dmFPath2Oid(&args, &OID); + assert(rc == 0); + assert(OID == (UINT32)0xffffffff); + + strcpy(args.pDirA, "213.dir"); + strcpy(args.pDirB, "170.dir"); + strcpy(args.pDirC, "150.dir"); + strcpy(args.pFName, "FILE135.cdf"); + rc = dmFPath2Oid(&args, &OID); + assert(rc == 0); + assert(OID == (UINT32)0xd5aa9687); + + strcpy(args.pFName, "FILE999.cdf"); + rc = dmFPath2Oid(&args, &OID); + assert(rc != 0); + +exit(0); +} + diff --git a/dmlproc/DMLProc.rc b/dmlproc/DMLProc.rc deleted file mode 100644 index d240733d..00000000 --- a/dmlproc/DMLProc.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB DML Processor" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "DMLProc" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "DMLProc.exe" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/dmlproc/DMLProc.vcxproj b/dmlproc/DMLProc.vcxproj deleted file mode 100644 index c190f3fb..00000000 --- a/dmlproc/DMLProc.vcxproj +++ /dev/null @@ -1,370 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {10EFDC01-9720-45A3-9290-7C394B459CB0} - DMLProc - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dmlib;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\batchloader;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dmlib;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\batchloader;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dmlib;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\batchloader;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNING;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dmlib;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\batchloader;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNING;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DML Processor" $(SolutionDir)..\..x64\Release\DMLProc.exe - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dmlib;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\batchloader;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNING;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dmlib;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\batchloader;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNING;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB DML Processor" $(SolutionDir)..\..\x64\EnterpriseRelease\DMLProc.exe - - - - - - - - - - - - - - - - - - - - - {19142d9e-7660-445c-b85d-98e722dffea5} - - - {c78dd512-fca0-4b8a-a531-376e33c9fbb7} - - - {b9045bca-0955-4c5e-bca4-5ee516838119} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {35d6295b-4a83-4e6e-bab0-70adf19ae822} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {e95fecb8-1b06-41ff-8e1d-40b7e6841765} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {0bbaeacb-3336-4406-acfb-255669a3b9cf} - - - {3238cd73-8ffd-44a7-aa5f-815beef8f402} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {2be469d2-d854-4480-bfe0-34de89c557b2} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {4bc37219-e09d-4133-98c4-cf0386657df6} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - - - - \ No newline at end of file diff --git a/dmlproc/DMLProc.vcxproj.filters b/dmlproc/DMLProc.vcxproj.filters deleted file mode 100644 index 8bc8f87e..00000000 --- a/dmlproc/DMLProc.vcxproj.filters +++ /dev/null @@ -1,53 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/dmlproc/Makefile.am b/dmlproc/Makefile.am index 1fe1c266..717e0796 100644 --- a/dmlproc/Makefile.am +++ b/dmlproc/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 197 2009-04-03 17:41:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/dmlproc/Makefile.in b/dmlproc/Makefile.in index b6e09c9a..0c588bff 100644 --- a/dmlproc/Makefile.in +++ b/dmlproc/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 197 2009-04-03 17:41:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = DMLProc$(EXEEXT) subdir = dmlproc DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -149,9 +148,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -193,7 +189,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -207,11 +202,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/dmlproc/batchinsertprocessor.cpp b/dmlproc/batchinsertprocessor.cpp index 1cd2ea0c..485ce023 100644 --- a/dmlproc/batchinsertprocessor.cpp +++ b/dmlproc/batchinsertprocessor.cpp @@ -1,19 +1,19 @@ -/* Copyright (C) 2014 InfiniDB, Inc. +/* + Copyright (C) 2009-2012 Calpont Corporation. - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ // $Id: batchinsertprocessor.h 525 2010-01-19 23:18:05Z xlou $ // @@ -30,449 +30,565 @@ using namespace oam; #include "batchinsertprocessor.h" using namespace dmlprocessor; +#include "we_clients.h" #include "we_messages.h" using namespace WriteEngine; #include "dmlpackageprocessor.h" + +#include "dbrm.h" +using namespace BRM; + +#include "batchloader.h" using namespace batchloader; #include "calpontsystemcatalog.h" using namespace execplan; -#include "idberrorinfo.h" -#include "errorids.h" -using namespace logging; -#include "dbrm.h" -using namespace BRM; using namespace messageqcpp; boost::mutex mute; boost::condition_variable cond; boost::mutex fLock; - -namespace dmlprocessor +namespace { +using namespace dmlprocessor; +class BatchInsertThread { +public: + BatchInsertThread(execplan::CalpontSystemCatalog::SCN txnid, uint32_t tableOid) : fTxnid(txnid), fTableOid(tableOid) {} -BatchInsertProc::BatchInsertProc(bool isAutocommitOn, uint32_t tableOid, execplan::CalpontSystemCatalog::SCN txnId, BRM::DBRM* aDbrm) : -fTxnid(txnId), fIsAutocommitOn(isAutocommitOn), fTableOid(tableOid), fDbrm(aDbrm) -{ - fErrorCode = 0; - fErrMsg = ""; - fLastpkg = false; - fUniqueId = fDbrm->getUnique64(); - fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DMLPROC); - fWEClient->addQueue(fUniqueId); - fOamcache = OamCache::makeOamCache(); - std::vector moduleIds = fOamcache->getModuleIds(); - //cout << "moduleIds size is " << moduleIds.size() << endl; - for (unsigned i=0; i < moduleIds.size(); i++) - { - fPMs.push_back((uint32_t)moduleIds[i]); - //cout << "got module id " << (uint32_t)moduleIds[i] << endl; - //cout << "fPMs[0] is " << fPMs[0] << endl; - } - fBatchLoader = new BatchLoader(fTableOid, fTxnid, fPMs); - for (unsigned i=0; iremoveQueue(fUniqueId); - delete fWEClient; -} + fWEClient = WriteEngine::WEClients::instance(WriteEngine::WEClients::DMLPROC); + fBatchInsertProc = BatchInsertProc::makeBatchInsertProc(fTxnid, fTableOid); + OamCache * oamcache = OamCache::makeOamCache(); + std::vector moduleIds = oamcache->getModuleIds(); + //@Bug 4495 check PM status first + oam::Oam oam; + int rc = 0; +#if !defined(_MSC_VER) && !defined(SKIP_OAM_INIT) + for (unsigned i=0; i < moduleIds.size(); i++) + { + int opState = 0; + bool aDegraded = false; + ostringstream aOss; + aOss << "pm" << moduleIds[i]; + std::string aModName = aOss.str(); + try + { + oam.getModuleStatus(aModName, opState, aDegraded); + } + catch(std::exception& ex) + { + ostringstream oss; + oss << "Exception on getModuleStatus on module "; + oss << aModName; + oss << ": "; + oss << ex.what(); + rc = 1; + fBatchInsertProc->setError(rc, oss.str()); + } -uint64_t BatchInsertProc::grabTableLock(int32_t sessionId) -{ - uint32_t processID = ::getpid(); - int32_t txnId = fTxnid; - std::string processName("DMLProc batchinsert"); - int32_t tmpSessionId = sessionId; - uint32_t tableOid = fTableOid; - int i = 0; - try { - //cout << "In grabTableLock, fPMs[0] is "<< fPMs[0] << endl; - fTableLockid = fDbrm->getTableLock(fPMs, tableOid, &processName, &processID, &tmpSessionId, &txnId, BRM::LOADING ); - } - catch (std::exception&) - { - setError(dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR , IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - return 0; - } + if(opState == oam::ACTIVE ) + { + fPMs.push_back((uint)moduleIds[i]); + } + } +#else + for (unsigned i=0; i < moduleIds.size(); i++) + { + fPMs.push_back((uint)moduleIds[i]); + } +#endif + //Look up extent map to decide which dbroot to start + DBRM dbrm; + boost::scoped_ptr aBatchloader( new BatchLoader(fTableOid, fTxnid, fPMs) ); + uint firstPmId = 0; + bool startFromNextPM = false; + string errorMsg; + try { + rc = aBatchloader->selectFirstPM (firstPmId, startFromNextPM); + } + catch (std::exception& ex) + { + rc = 1; + fBatchInsertProc->setError(rc, ex.what()); + return; + } + if ( rc ==0 ) + { + if (startFromNextPM) + { + aBatchloader->prepareForSecondPM(); + firstPmId = aBatchloader->selectNextPM(); + } + if (firstPmId == 0) + { + aBatchloader->prepareForSecondPM(); + firstPmId = aBatchloader->selectNextPM(); + } + } - if ( fTableLockid == 0 ) - { - int waitPeriod = 10; - int sleepTime = 100; // sleep 100 milliseconds between checks - int numTries = 10; // try 10 times per second - string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); - if ( waitPeriodStr.length() != 0 ) - waitPeriod = static_cast(config::Config::fromText(waitPeriodStr)); - - numTries = waitPeriod * 10; - struct timespec rm_ts; - - rm_ts.tv_sec = sleepTime/1000; - rm_ts.tv_nsec = sleepTime%1000 *1000000; + if (firstPmId == 0) + { + rc = 1; + fBatchInsertProc->setError(rc, "Request cannot be sent to PM 0."); + return; + } + aBatchloader->prepareForSecondPM(); + uint64_t uniqueId = dbrm.getUnique64(); + fWEClient->addQueue(uniqueId); - for (; i < numTries; i++) + + ByteStream bs1; + bs1 << (ByteStream::byte) WE_SVR_BATCH_INSERT; + bs1 << uniqueId; + bs1 << (ByteStream::quadbyte) fTxnid; + ByteStream bs2; + fLastPkg = false; + bool isAutoCommitOn = true; + uint32_t tableOid; + boost::shared_ptr bsIn; + bsIn.reset(new ByteStream()); + ByteStream::byte tmp8; + ByteStream::quadbyte tmp32; + std::map pmState; + + for (unsigned i=0; i BulkSetHWMArgs; + std::vector hwmArgsAllPms; + fCurrentPMid = firstPmId; + try { + while (1) + { + boost::unique_lock lock(mute); + + while ((fBatchInsertProc->getInsertQueue()->size()) == 0) { - abs_ts.tv_sec = rm_ts.tv_sec; - abs_ts.tv_nsec = rm_ts.tv_nsec; + //cout << "batchinsertprocessor is waiting for work ... " << endl; + cond.wait(lock); } - while(nanosleep(&abs_ts,&rm_ts) < 0); -#endif - try + //send pkg to pm + + //cout << "Before loop, current queue size = " << fBatchInsertProc->getInsertQueue()->size() << endl; + unsigned int quesize = fBatchInsertProc->getInsertQueue()->size(); + for (unsigned i=0; i < quesize; i++) { - processID = ::getpid(); - txnId = fTxnid; - tmpSessionId = sessionId; - processName = "DMLProc batchinsert"; - fTableLockid = fDbrm->getTableLock(fPMs, tableOid, &processName, &processID, &tmpSessionId, &txnId, BRM::LOADING ); + //find the dbroot and the residing pm to sent the package to + //cout << "Inside loop, current queue size = " << fBatchInsertProc->getInsertQueue()->size() << " and i is " << i << endl; + bs2.reset(); + bs2 = bs1; + bs2 << (ByteStream::quadbyte) fCurrentPMid; //to keep track of PMs + bs2 += fBatchInsertProc->getPkg(fLastPkg, isAutoCommitOn, tableOid); + //cout << " getPkg fLastPkg is " << fLastPkg << endl; + //send to all dbroots + if (pmState[fCurrentPMid]) { + //cout << "current pm state for pm is true for pm " << fDbrootPm[fCurrentDbroot]<< endl; + fWEClient->write(bs2, fCurrentPMid); + //cout << "batchinsertprocessor sent pkg to pmnum " << fCurrentPMid << endl; + pmState[fCurrentPMid] = false; + fCurrentPMid = aBatchloader->selectNextPM(); + //cout << "fCurrentPMid changed to " << fCurrentPMid << endl; + //cout << "set pm state to false for pm " << fDbrootPm[fCurrentDbroot] << endl; + } + else { + //cout << "current pm state for pm is false for pm " << fCurrentPMid<< endl; + while (1) + { + //cout << "Read from WES for pm id " << (uint) tmp32 << endl; + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + fBatchInsertProc->setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); + //fWEClient->removeQueue(uniqueId); + break; + } + else { + *bsIn >> tmp8; + rc = tmp8; + *bsIn >> errorMsg; + *bsIn >> tmp32; + //cout << "got response from WES for pm id " << (uint) tmp32 << endl; + if (rc != 0) { + //cout << "Batch insert got error code:errormsg = " << (uint)tmp8<<":"<setError(rc, errorMsg); + pmState[tmp32] = true; + while(!fBatchInsertProc->getInsertQueue()->empty()) fBatchInsertProc->getInsertQueue()->pop(); + cond.notify_one(); + //fWEClient->removeQueue(uniqueId); + break; + } + } + pmState[tmp32] = true; + //cout << "set pm state to true for pm " << (uint) tmp32 << " and current PM id is " << fCurrentPMid << endl; + if (tmp32 == fCurrentPMid) + break; + } + if (rc != 0) + break; + //cout << "before batchinsertprocessor sent pkg to pm " << fCurrentPMid << endl; + fWEClient->write(bs2, fCurrentPMid); + //cout << "batchinsertprocessor sent pkg to pm " << fCurrentPMid << endl; + pmState[fCurrentPMid] = false; + fCurrentPMid = aBatchloader->selectNextPM(); + //cout << "fCurrentPMid changed to " << fCurrentPMid << endl; + } + //send to all PMs to set hwm if this is the last pkg + //cout << "fLastPkg is now " << fLastPkg << endl; + if (fLastPkg && (fBatchInsertProc->getInsertQueue()->size() == 0) ) + { + //receive message first + //check whether need to wait for message + uint meesageNotReceved = 0; + for (unsigned i=0; i 0) { + uint messageRcvd = 0; + while (1) + { + if (meesageNotReceved == messageRcvd) + break; + + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + fBatchInsertProc->setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); + //fWEClient->removeQueue(uniqueId); + messageRcvd++; + } + else { + *bsIn >> tmp8; + rc = tmp8; + *bsIn >> errorMsg; + *bsIn >> tmp32; + messageRcvd++; + //cout << "got response from WES for pm id " << (uint) tmp32 << endl; + if (rc == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) + { + fBatchInsertProc->setError(rc, errorMsg); + } + else if (rc != 0) { + //cout << "Batch insert got error code:errormsg = " << rc<<":"<setError(rc, errorMsg); + pmState[tmp32] = true; + //cout << "set pm state to true for pm " << (uint) tmp32 << endl; + //fWEClient->removeQueue(uniqueId); + break; + } + pmState[tmp32] = true; + //cout << "set pm state to true for pm " << (uint) tmp32 << endl; + } + } + } + //cout << "out of for loop and rc is " << rc<write_to_all(bs1); + //cout << "sent the last pkg" << endl; + uint msgRevd = 0; + while (1) + { + if (msgRevd == fWEClient->getPmCount()) + break; + + //cout << "Read last from WES bytestream" << endl; + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + fBatchInsertProc->setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); + //fWEClient->removeQueue(uniqueId); + break; + } + else { + *bsIn >> tmp8; + rc = tmp8; + *bsIn >> errorMsg; + msgRevd++; + if (!isAutoCommitOn) //collect Hwm + { + BulkSetHWMArgs setHWMArgs; + //cout << "received from WES bytestream length = " << bsIn->length() << endl; + deserializeInlineVector(*(bsIn.get()), setHWMArgs); + //cout << "get hwm info from WES size " << setHWMArgs.size() << endl; + hwmArgsAllPms.push_back(setHWMArgs); + } + if (rc == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) + { + fBatchInsertProc->setError(rc, errorMsg); + } + else if (rc != 0) { + //cout << "Batch insert lastpkg got error code:errormsg = " << (uint)tmp8<<":"<setError(rc, errorMsg); + //fWEClient->removeQueue(uniqueId); + break; + } + } + } + //cout << " received response for last batch" << endl; + if (!isAutoCommitOn) + { + //set hwm + std::vector allHwm; + BulkSetHWMArgs::const_iterator itor; + //cout << "total hwmArgsAllPms size " << hwmArgsAllPms.size() << endl; + for (unsigned i=0; i < fWEClient->getPmCount(); i++) + { + itor = hwmArgsAllPms[i].begin(); + while (itor != hwmArgsAllPms[i].end()) + { + allHwm.push_back(*itor); + //cout << "received hwm info: " << itor->oid << ":" << itor->hwm << endl; + itor++; + } + } + + if (allHwm.size() > 0) + { + //cout << "setting hwm allHwm size " << allHwm.size() << endl; + scoped_ptr dbrmp(new DBRM()); + rc = dbrmp->bulkSetHWM(allHwm, 0); + } + } + break; + + } } - catch (std::exception&) + + //@Bug 4419. need to recive all messages before returning to connector in error + if (rc != 0) { - setError(dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR , IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); - return 0; + //receive message first + //check whether need to wait for message + //cout << "error occured." << endl; + uint messagesNotReceived = 0; + for (unsigned i=0; i 0) + { + //cout << "Batchinsertprocessor erroring out and need to receive messages " << messagesNotReceived << endl; + while (1) + { + if (msgReceived == messagesNotReceived) + break; + + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + msgReceived++; + } + else { + *bsIn >> tmp8; + *bsIn >> errorMsg; + *bsIn >> tmp32; + msgReceived++; + } + } + } + //cout << "Batchinsertprocessor erroring out and received all messages " << endl; + bs1.reset(); + bs1 << (ByteStream::byte) WE_SVR_BATCH_INSERT_END; + bs1 << uniqueId; + bs1 << (ByteStream::quadbyte) fTxnid; + bs1 << (ByteStream::byte)isAutoCommitOn; + bs1 << tableOid; + bs1 << (ByteStream::byte) rc; + //cout << "sending the last pkg" << endl; + fWEClient->write_to_all(bs1); + //cout << "sent the last pkg" << endl; + msgReceived = 0; + while (1) + { + if (msgReceived == fWEClient->getPmCount()) + break; + + fWEClient->read(uniqueId, bsIn); + if ( bsIn->length() == 0 ) //read error + { + msgReceived++; + } + else { + *bsIn >> tmp8; + *bsIn >> errorMsg; + msgReceived++; + if (!isAutoCommitOn) //collect Hwm + { + BulkSetHWMArgs setHWMArgs; + //cout << "received from WES bytestream length = " << bsIn->length() << endl; + deserializeInlineVector(*(bsIn.get()), setHWMArgs); + //cout << "get hwm info from WES size " << setHWMArgs.size() << endl; + hwmArgsAllPms.push_back(setHWMArgs); + } + } + } + //cout << "received all response before error out " << endl; + if (!isAutoCommitOn) + { + //set hwm + std::vector allHwm; + BulkSetHWMArgs::const_iterator itor; + //cout << "total hwmArgsAllPms size " << hwmArgsAllPms.size() << endl; + for (unsigned i=0; i < fWEClient->getPmCount(); i++) + { + itor = hwmArgsAllPms[i].begin(); + while (itor != hwmArgsAllPms[i].end()) + { + allHwm.push_back(*itor); + //cout << "received hwm info: " << itor->oid << ":" << itor->hwm << endl; + itor++; + } + } + + if (allHwm.size() > 0) + { + //cout << "setting hwm allHwm size " << allHwm.size() << endl; + scoped_ptr dbrmp(new DBRM()); + rc = dbrmp->bulkSetHWM(allHwm, 0); + } + } + break; } - - if (fTableLockid > 0) - return fTableLockid; + //@Bug 4530. Need check queue size to prevent prematurally terminate the process. + if (fLastPkg && (fBatchInsertProc->getInsertQueue()->size() == 0) ) + break; + //Notify receive pkg + //cout << "notifying dmlprocessor" << endl; + cond.notify_one(); + } } - - if (i >= numTries) //error out + catch (std::exception& ex) { - logging::Message::Args args; - args.add(processName); - args.add((uint64_t)processID); - args.add(tmpSessionId); - setError(dmlpackageprocessor::DMLPackageProcessor::TABLE_LOCK_ERROR , IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); - return 0; + ostringstream oss; + oss << "Exception on communicating to WES "; + oss << ex.what(); + rc = 1; + fBatchInsertProc->setError(rc, oss.str()); + cout << oss.str() << endl; } + fWEClient->removeQueue(uniqueId); } - return fTableLockid; -} -BatchInsertProc::SP_PKG BatchInsertProc::getInsertQueue() -{ - mutex::scoped_lock lk(fLock); - return fInsertPkgQueue; -} -void BatchInsertProc::setLastPkg (bool lastPkg) -{ - fLastpkg = lastPkg; -} -void BatchInsertProc::addPkg(messageqcpp::ByteStream& insertBs) -{ - mutex::scoped_lock lk(fLock); - fInsertPkgQueue->push(insertBs); +private: + std::vector fPMs; + WriteEngine::WEClients* fWEClient; + std::vector fDbRoots; + std::map fDbrootPm; // key - dbroot. + BatchInsertProc* fBatchInsertProc; + uint fStartingDbroot; + uint fCurrentPMid; + execplan::CalpontSystemCatalog::SCN fTxnid; + bool fLastPkg; + uint32_t fTableOid; +}; } -messageqcpp::ByteStream BatchInsertProc::getPkg() -{ - messageqcpp::ByteStream bs; - mutex::scoped_lock lk(fLock); - bs = fInsertPkgQueue->front(); - fInsertPkgQueue->pop(); - return bs; -} - -void BatchInsertProc::buildPkg(messageqcpp::ByteStream& bs) +namespace dmlprocessor { - bs.reset(); - bs << (ByteStream::byte) WE_SVR_BATCH_INSERT; - bs << fUniqueId; - bs << (uint32_t) fTxnid; - bs << fCurrentPMid; //to keep track of PMs - bs += getPkg(); -} - -void BatchInsertProc::buildLastPkg(messageqcpp::ByteStream& bs) +/*static*/ +BatchInsertProc* BatchInsertProc::fInstance; +uint BatchInsertProc::fNumDBRoots; +uint32_t BatchInsertProc::fTableOid; +boost::thread* BatchInsertProc::fProcessorThread; +execplan::CalpontSystemCatalog::SCN BatchInsertProc::fTxnid; +int BatchInsertProc::fErrorCode; +std::string BatchInsertProc::fErrMsg; +BatchInsertProc * BatchInsertProc::makeBatchInsertProc(execplan::CalpontSystemCatalog::SCN txnid, uint32_t tableOid) { - bs.reset(); - bs << (ByteStream::byte) WE_SVR_BATCH_INSERT_END; - bs << fUniqueId; - bs << (ByteStream::quadbyte) fTxnid; - bs << (ByteStream::byte)fIsAutocommitOn; - bs << fTableOid; - bs << (ByteStream::byte) fErrorCode; + if (fInstance) + return fInstance; + + fInstance = new BatchInsertProc(); + joblist::ResourceManager rm; + fNumDBRoots = rm.getDBRootCount(); + fTxnid = txnid; + fTableOid = tableOid; + fErrorCode = 0; + fErrMsg = ""; + BatchInsertThread batchInsertThread(fTxnid, fTableOid); + fProcessorThread = new boost::thread(batchInsertThread); + return fInstance; } -void BatchInsertProc::sendFirstBatch() +void BatchInsertProc::removeBatchInsertProc(int & rc, string & errMsg) { - uint32_t firstPmId = 0; - int rc = 0; - try { - firstPmId = fBatchLoader->selectNextPM(); - } - catch (std::exception& ex) - { - rc = 1; - setError(rc, ex.what()); - return; - } - - if (firstPmId == 0) - { - rc = 1; - setError(rc, "Request cannot be sent to PM 0."); - return; - } - - fCurrentPMid = firstPmId; - messageqcpp::ByteStream bs; - buildPkg(bs); + fProcessorThread->join(); + delete fProcessorThread; + fProcessorThread = NULL; + rc = fErrorCode; + //cout << "fErrorCode is " << fErrorCode << endl; + errMsg = fErrMsg; - fWEClient->write(bs, fCurrentPMid); - //cout << "in sendFirstBatch: batchinsertprocessor sent pkg to pmnum " << fCurrentPMid << endl; - fPmState[fCurrentPMid] = false; + if (fInstance) + delete fInstance; + fInstance = 0; } -void BatchInsertProc::sendNextBatch() +BatchInsertProc::BatchInsertProc():fInsertPkgQueue(new pkg_type) { - int rc = 0; - try { - fCurrentPMid = fBatchLoader->selectNextPM(); - } - catch (std::exception& ex) - { - rc = 1; - setError(rc, ex.what()); - return; - } - messageqcpp::ByteStream bs; - buildPkg(bs); - string errorMsg; - //cout << "in sendNextBatch: fCurrentPMid changed to " << fCurrentPMid << " this = " << this << endl; - if (fPmState[fCurrentPMid]) { - //cout << "current pm state for pm is true for pm " << fCurrentPMid << " this = " << this<< endl; - fWEClient->write(bs, fCurrentPMid); - //cout << "batchinsertprocessor sent pkg to pmnum " << fCurrentPMid << endl; - fPmState[fCurrentPMid] = false; - //cout << "set pm state to false for pm " << fCurrentPMid << " this = " << this << endl; - } - else { - //cout << "current pm state for pm is false for pm " << fCurrentPMid<< endl; - while (1) - { - //cout << "Read from WES for pm id " << (uint32_t) tmp32 << endl; - bsIn.reset(new ByteStream()); - fWEClient->read(fUniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - errorMsg = "Lost connection to WES."; - setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); - break; - } - else { - *bsIn >> tmp8; - rc = tmp8; - *bsIn >> errorMsg; - *bsIn >> tmp32; - //cout << "got response from WES for pm id " << (uint32_t) tmp32 << endl; - if (rc != 0) { - //cout << "Batch insert got error code:errormsg = " << (uint32_t)tmp8<<":"<write(bs, fCurrentPMid); - //cout << "batchinsertprocessor sent pkg to pm " << fCurrentPMid << endl; - fPmState[fCurrentPMid] = false; - //cout << "set pm state to false for pm " << fCurrentPMid << " this = " << this << endl; - } - + } -void BatchInsertProc::sendlastBatch() +BatchInsertProc::~BatchInsertProc() { - messageqcpp::ByteStream bs; - buildLastPkg(bs); - try { - fWEClient->write_to_all(bs); - //cout << "sent the last pkg" << endl; - } - catch (std::exception& ex) - { - ostringstream oss; - oss << "Exception on communicating to WES "; - oss << ex.what(); - setError(1, oss.str()); - //cout << oss.str() << endl; - } } -void BatchInsertProc::receiveOutstandingMsg() -{ - //check how many message we need to receive - uint32_t messagesNotReceived = 0; - int rc = 0; - for (unsigned i=0; igetPmCount()) - break; - - //cout << "Read last from WES bytestream" << endl; - fWEClient->read(fUniqueId, bsIn); - if ( bsIn->length() == 0 ) //read error - { - errorMsg = "Lost connection to WES."; - setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); - msgRevd++; - if (!fIsAutocommitOn) - { - BulkSetHWMArgs setHWMArgs; - fHwmArgsAllPms.push_back(setHWMArgs); - } - } - else { - *bsIn >> tmp8; - rc = tmp8; - *bsIn >> errorMsg; - msgRevd++; - if (!fIsAutocommitOn) //collect Hwm - { - BulkSetHWMArgs setHWMArgs; - deserializeInlineVector(*(bsIn.get()), setHWMArgs); - fHwmArgsAllPms.push_back(setHWMArgs); - - } - if (rc == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) - { - setError(rc, errorMsg); - } - else if (rc != 0) { - //cout << "Batch insert lastpkg got error code:errormsg = " << (uint32_t)tmp8<<":"<getPmCount())) - setHwm(); - + return fNumDBRoots; } -void BatchInsertProc::collectHwm() +void BatchInsertProc::addPkg(messageqcpp::ByteStream& insertBs, bool lastpkg, bool isAutocommitOn, uint32_t tableOid) { - BulkSetHWMArgs setHWMArgs; - //cout << "received from WES bytestream length = " << bsIn->length() << endl; - deserializeInlineVector(*(bsIn.get()), setHWMArgs); - //cout << "get hwm info from WES size " << setHWMArgs.size() << endl; - fHwmArgsAllPms.push_back(setHWMArgs); + mutex::scoped_lock lk(fLock); + fInsertPkgQueue->push(insertBs); + fLastpkg = lastpkg; + //cout << "set fLastpkg to " << fLastpkg << endl; + fIsAutocommitOn = isAutocommitOn; } -void BatchInsertProc::setHwm() +messageqcpp::ByteStream BatchInsertProc::getPkg(bool & lastPkg, bool & isAutoCommitOn, uint32_t & tableOid) { - std::vector allHwm; - BulkSetHWMArgs::const_iterator itor; - //cout << "total hwmArgsAllPms size " << hwmArgsAllPms.size() << endl; - for (unsigned i=0; i < fWEClient->getPmCount(); i++) - { - itor = fHwmArgsAllPms[i].begin(); - while (itor != fHwmArgsAllPms[i].end()) - { - allHwm.push_back(*itor); - //cout << "received hwm info: " << itor->oid << ":" << itor->hwm << endl; - itor++; - } - } - - if (allHwm.size() > 0) - { - //cout << "setting hwm allHwm size " << allHwm.size() << endl; - int rc = fDbrm->bulkSetHWM(allHwm, 0); - if ( rc !=0 ) - { - string errorMsg; - BRM::errString(rc, errorMsg); - setError(rc, errorMsg); - } - } + messageqcpp::ByteStream bs; + mutex::scoped_lock lk(fLock); + bs = fInsertPkgQueue->front(); + fInsertPkgQueue->pop(); + lastPkg = fLastpkg; + //cout << "get fLastpkg is " << fLastpkg << endl; + isAutoCommitOn = fIsAutocommitOn; + tableOid = fTableOid; + return bs; } void BatchInsertProc::setError(int errorCode, std::string errMsg) diff --git a/dmlproc/batchinsertprocessor.h b/dmlproc/batchinsertprocessor.h index 8e5b8638..c4b10075 100644 --- a/dmlproc/batchinsertprocessor.h +++ b/dmlproc/batchinsertprocessor.h @@ -1,97 +1,74 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: batchinsertprocessor.h 525 2010-01-19 23:18:05Z xlou $ - -/** @file */ - -#ifndef BATCHINSERTPROCESSOR_H__ -#define BATCHINSERTPROCESSOR_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "insertdmlpackage.h" -#include "resourcemanager.h" -#include "bytestream.h" -#include "dbrm.h" -#include "batchloader.h" -#include "we_clients.h" -namespace dmlprocessor -{ -class BatchInsertProc -{ -public: - typedef std::queue pkg_type; - typedef boost::shared_ptr SP_PKG; - typedef std::vector BulkSetHWMArgs; - BatchInsertProc(bool isAutocommitOn, uint32_t tableOid, execplan::CalpontSystemCatalog::SCN txnId, BRM::DBRM* aDbrm); - BatchInsertProc(const BatchInsertProc& rhs); - ~BatchInsertProc(); - uint64_t grabTableLock(int32_t sessionId); - SP_PKG getInsertQueue (); - uint32_t getNumDBRoots(); - void setLastPkg (bool lastPkg); - void addPkg(messageqcpp::ByteStream & insertBs); - messageqcpp::ByteStream getPkg(); - void setError(int errorCode, std::string errMsg); - void getError(int & errorCode, std::string & errMsg); - int sendPkg(int pmId); - void buildPkg(messageqcpp::ByteStream& bs); - void buildLastPkg(messageqcpp::ByteStream& bs); - void sendFirstBatch(); - void sendNextBatch(); - void sendlastBatch(); - void collectHwm(); - void setHwm(); - void receiveAllMsg(); - void receiveOutstandingMsg(); -private: - SP_PKG fInsertPkgQueue; - boost::condition condvar; - execplan::CalpontSystemCatalog::SCN fTxnid; - int fErrorCode; - std::string fErrMsg; - bool fLastpkg; - bool fIsAutocommitOn; - uint32_t fTableOid; - uint64_t fUniqueId; - BRM::DBRM* fDbrm; - WriteEngine::WEClients* fWEClient; - oam::OamCache *fOamcache; - std::vector fPMs; //active PMs - batchloader::BatchLoader* fBatchLoader; - std::map fPmState; - uint32_t fCurrentPMid; - boost::shared_ptr bsIn; - messageqcpp::ByteStream::byte tmp8; - messageqcpp::ByteStream::quadbyte tmp32; - std::vector fHwmArgsAllPms; - uint64_t fTableLockid; - - -}; - -} // namespace dmlprocessor -#endif -// vim:ts=4 sw=4: +/* + Copyright (C) 2009-2012 Calpont Corporation. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// $Id: batchinsertprocessor.h 525 2010-01-19 23:18:05Z xlou $ +// +/** @file */ + +#ifndef BATCHINSERTPROCESSOR_H__ +#define BATCHINSERTPROCESSOR_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "insertdmlpackage.h" +#include "resourcemanager.h" +#include "bytestream.h" + +namespace dmlprocessor +{ +class BatchInsertProc +{ +public: + typedef std::queue pkg_type; + typedef boost::shared_ptr SP_PKG; + static BatchInsertProc* makeBatchInsertProc(execplan::CalpontSystemCatalog::SCN txnid, uint32_t tableOid); + static void removeBatchInsertProc(int & rc, std::string & errMsg); + ~BatchInsertProc(); + + SP_PKG getInsertQueue (); + uint getNumDBRoots(); + void addPkg(messageqcpp::ByteStream & insertBs, bool lastpkg = false, bool isAutocommitOn = true, uint32_t tableOid=0); + messageqcpp::ByteStream getPkg(bool & lastPkg, bool & isAutocommitOn, uint32_t &tableOid); + void setError(int errorCode, std::string errMsg); + void getError(int & errorCode, std::string & errMsg); +private: + /** Constuctors */ + explicit BatchInsertProc(); + explicit BatchInsertProc(const BatchInsertProc& rhs); + SP_PKG fInsertPkgQueue; + boost::condition condvar; + static BatchInsertProc* fInstance; + static uint fNumDBRoots; + static boost::thread* fProcessorThread; + static execplan::CalpontSystemCatalog::SCN fTxnid; + static int fErrorCode; + static std::string fErrMsg; + bool fLastpkg; + bool fIsAutocommitOn; + static uint32_t fTableOid; +}; + +} // namespace dmlprocessor +#endif +// vim:ts=4 sw=4: diff --git a/dmlproc/dmlproc.cpp b/dmlproc/dmlproc.cpp index 5942d6cc..c3df051c 100644 --- a/dmlproc/dmlproc.cpp +++ b/dmlproc/dmlproc.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlproc.cpp 1029 2013-07-31 19:17:42Z dhall $ +* $Id: dmlproc.cpp 1009 2013-07-08 20:10:44Z bpaul $ * * ***********************************************************************/ @@ -64,7 +64,6 @@ using namespace logging; using namespace oam; #include "writeengine.h" -#include "IDBPolicy.h" #undef READ //someone has polluted the namespace! #include "vss.h" @@ -101,7 +100,7 @@ void added_a_pm(int) Dec->Setup(); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - //WriteEngine::WEClients::instance(WriteEngine::WEClients::DMLPROC)->Setup(); + WriteEngine::WEClients::instance(WriteEngine::WEClients::DMLPROC)->Setup(); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); } @@ -125,7 +124,7 @@ class CleanUpThread }; // This function rolls back any active transactions in case of an abnormal shutdown. -void rollbackAll(DBRM* dbrm) +void rollbackAll() { Oam oam; try { @@ -146,40 +145,39 @@ void rollbackAll(DBRM* dbrm) boost::shared_array activeTxns; BRM::TxnID txnID; SessionManager sessionManager; + DBRM dbrm; int rc = 0; - rc = dbrm->isReadWrite(); + rc = dbrm.isReadWrite(); if (rc != 0 ) throw std::runtime_error("Rollback will be deferred due to DBRM is in read only state."); - dbrm->setSystemReady(false); + dbrm.setSystemReady(false); //DDL clean up thread thread_group tg; tg.create_thread(CleanUpThread()); std::vector tableLocks; - try - { - tableLocks = dbrm->getAllTableLocks(); + try { + tableLocks = dbrm.getAllTableLocks(); } catch (std::exception&) { throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); } - // If there are tables to rollback, set to ROLLBACK_INIT. - // This tells ProcMgr that we are rolling back and will be - // a while. A message to this effect should be printed. - if (tableLocks.size() > 0) - { - oam.processInitComplete("DMLProc", oam::ROLLBACK_INIT); - } - - uint64_t uniqueId = dbrm->getUnique64(); - RollbackTransactionProcessor rollbackProcessor(dbrm); + uint64_t uniqueId = dbrm.getUnique64(); + RollbackTransactionProcessor rollbackProcessor; std::string errorMsg; unsigned int i = 0; BRM::TxnID txnId; ostringstream oss; + // If there are tables to rollback, set to BUSY_INIT. + // This tells ProcMgr that we are rolling back and will be + // a while. A message to this effect should be printed. + if (tableLocks.size() > 0) + { + oam.processInitComplete("DMLProc", oam::BUSY_INIT); + } oss << "DMLProc will rollback " << tableLocks.size() << " tables."; //cout << oss.str() << endl; logging::Message::Args args5; @@ -202,8 +200,16 @@ void rollbackAll(DBRM* dbrm) args1.add(oss.str()); message2.format( args1 ); ml.logInfoMessage( message2 ); - dbrm->invalidateUncommittedExtentLBIDs(tableLocks[i].ownerTxnID); - uint32_t sessionid = 0; + vector lbidList; + dbrm.getUncommittedExtentLBIDs(static_cast(tableLocks[i].ownerTxnID), lbidList); + vector::const_iterator iter = lbidList.begin(); + vector::const_iterator end = lbidList.end(); + while (iter != end) + { + dbrm.setExtentMaxMin(*iter, numeric_limits::min(), numeric_limits::max(), -1); + ++iter; + } + u_int32_t sessionid = 0; txnId.id = tableLocks[i].ownerTxnID; txnId.valid = true; rc = rollbackProcessor.rollBackTransaction(uniqueId, txnId, sessionid, errorMsg); @@ -216,12 +222,8 @@ void rollbackAll(DBRM* dbrm) args3.add(oss.str()); message3.format( args3 ); ml.logInfoMessage( message3 ); - - //@Bug 5285 get the process name to see whether calling bulkrollback is necessary. - string::size_type namelen = tableLocks[i].ownerName.find_first_of(" "); - if (namelen != string::npos) { - rollbackProcessor.rollBackBatchAutoOnTransaction(uniqueId, txnId, sessionid, tableLocks[i].tableOID, errorMsg); - } + //@Bug 4524. In case it is batchinsert, call bulkrollback. + rollbackProcessor.rollBackBatchAutoOnTransaction(uniqueId, txnId, sessionid, tableLocks[i].tableOID, errorMsg); logging::logCommand(0, tableLocks[i].ownerTxnID, "ROLLBACK;"); //release table lock if not DDLProc if (tableLocks[i].ownerName == "DDLProc") @@ -229,7 +231,7 @@ void rollbackAll(DBRM* dbrm) bool lockReleased = true; try { - lockReleased = dbrm->releaseTableLock(tableLocks[i].id); + lockReleased = dbrm.releaseTableLock(tableLocks[i].id); } catch (std::exception&) { @@ -250,7 +252,7 @@ void rollbackAll(DBRM* dbrm) else { ostringstream oss; - oss << "DMLProc rolled back transaction " <setReadOnly(true); + rc = dbrm.setReadOnly(true); //Raise an alarm try { snmpmanager::SNMPManager alarmMgr; @@ -286,7 +288,7 @@ void rollbackAll(DBRM* dbrm) //Just release the table lock bool lockReleased = true; try { - lockReleased = dbrm->releaseTableLock(tableLocks[i].id); + lockReleased = dbrm.releaseTableLock(tableLocks[i].id); } catch (std::exception& ex) { @@ -347,9 +349,8 @@ void rollbackAll(DBRM* dbrm) // Clear out the session manager session list of sessions / transactions. //Take care of any transaction left from create table as there is no table lock information set txnList; - rc = dbrm->getCurrentTxnIDs(txnList); + rc = dbrm.getCurrentTxnIDs(txnList); if(txnList.size() > 0) { - oam.processInitComplete("DMLProc", oam::ROLLBACK_INIT); ostringstream oss; oss << "DMLProc will rollback " << txnList.size() << " transactions."; logging::Message::Args args2; @@ -359,10 +360,19 @@ void rollbackAll(DBRM* dbrm) ml.logInfoMessage( message2 ); set::const_iterator curTxnID; for(curTxnID = txnList.begin(); curTxnID != txnList.end(); ++curTxnID) { - dbrm->invalidateUncommittedExtentLBIDs(*curTxnID); + //@Bug 2299 check write engine error. + vector lbidList; + dbrm.getUncommittedExtentLBIDs(static_cast(*curTxnID), lbidList); + vector::const_iterator iter = lbidList.begin(); + vector::const_iterator end = lbidList.end(); + while (iter != end) + { + dbrm.setExtentMaxMin(*iter, numeric_limits::min()+1, numeric_limits::max()-1, -1); + ++iter; + } txnId.id = *curTxnID; txnId.valid = true; - uint32_t sessionid = 0; + u_int32_t sessionid = 0; ostringstream oss; oss << "DMLProc will roll back transaction " <<*curTxnID; logging::Message::Args args2; @@ -390,7 +400,7 @@ void rollbackAll(DBRM* dbrm) //@Bug 4524 still need to set readonly as transaction information is lost during system restart. ostringstream oss; oss << " problem with rollback transaction " << txnId.id << "and DBRM is setting to readonly and table lock is not released: " << errorMsg; - rc = dbrm->setReadOnly(true); + rc = dbrm.setReadOnly(true); //Raise an alarm try { snmpmanager::SNMPManager alarmMgr; @@ -434,7 +444,7 @@ void rollbackAll(DBRM* dbrm) // Clear out the DBRM. - dbrm->clear(); + dbrm.clear(); //Flush the cache cacheutils::flushPrimProcCache(); @@ -446,7 +456,7 @@ void rollbackAll(DBRM* dbrm) message1.format( args1 ); ml.logInfoMessage( message1 ); - dbrm->setSystemReady(true); + dbrm.setSystemReady(true); } void setupCwd() @@ -465,7 +475,7 @@ int main(int argc, char* argv[]) // get and set locale language string systemLang = "C"; - BRM::DBRM dbrm; + BRM::DBRM dbrm(true); Oam oam; //BUG 5362 systemLang = funcexp::utf8::idb_setlocale(); @@ -475,25 +485,20 @@ int main(int argc, char* argv[]) setupCwd(); WriteEngine::WriteEngineWrapper::init( WriteEngine::SUBSYSTEM_ID_DMLPROC ); -#ifdef _MSC_VER - // In windows, initializing the wrapper (A dll) does not set the static variables - // in the main program - idbdatafile::IDBPolicy::configIDBPolicy(); -#endif - - try - { - // At first we set to BUSY_INIT - oam.processInitComplete("DMLProc", oam::BUSY_INIT); - } - catch (...) - { + try + { + // At first we set to MAN_INIT, which tells ProcMgr that we + // are starting up. If rollbacks are needed, we'll the set to + // BUSY_INIT to indicate we are rolling back. + oam.processInitComplete("DMLProc", oam::MAN_INIT); + } + catch (...) + { } //@Bug 1627 - try - { - rollbackAll(&dbrm); // Rollback any + try { + rollbackAll(); // Rollback any } catch ( std::exception &e ) { @@ -520,8 +525,8 @@ int main(int argc, char* argv[]) } int temp; - int serverThreads = 10; - int serverQueueSize = 50; + int serverThreads = 100; + int serverQueueSize = 200; const string DMLProc("DMLProc"); temp = toInt(cf->getConfig(DMLProc, "ServerThreads")); @@ -533,37 +538,16 @@ int main(int argc, char* argv[]) serverQueueSize = temp; - bool rootUser = true; -#ifndef _MSC_VER - //check if root-user - int user; - user = getuid(); - if (user != 0) - rootUser = false; -#endif - //read and cleanup port before trying to use - try { - string port = cf->getConfig(DMLProc, "Port"); - string cmd = "fuser -k " + port + "/tcp >/dev/null 2>&1"; - if ( !rootUser) - cmd = "sudo fuser -k " + port + "/tcp >/dev/null 2>&1"; - - (void)::system(cmd.c_str()); - } - catch(...) - { - } - - DMLServer dmlserver(serverThreads, serverQueueSize,&dbrm); + DMLServer dmlserver(serverThreads, serverQueueSize); //set ACTIVE state try - { - oam.processInitComplete("DMLProc", ACTIVE); - } - catch (...) - { - } + { + oam.processInitComplete("DMLProc", ACTIVE); + } + catch (...) + { + } ResourceManager rm; Dec = DistributedEngineComm::instance(rm); diff --git a/dmlproc/dmlproc.h b/dmlproc/dmlproc.h index fa76dc70..0d7b2b4f 100644 --- a/dmlproc/dmlproc.h +++ b/dmlproc/dmlproc.h @@ -17,7 +17,7 @@ /****************************************************************************************** * -* $Id: dmlproc.h 927 2013-01-21 14:11:25Z rdempsey $ +* $Id: dmlproc.h 734 2012-04-04 18:19:16Z rdempsey $ * ******************************************************************************************/ /** diff --git a/dmlproc/dmlprocessor.cpp b/dmlproc/dmlprocessor.cpp index 597d5863..46266379 100644 --- a/dmlproc/dmlprocessor.cpp +++ b/dmlproc/dmlprocessor.cpp @@ -16,22 +16,19 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlprocessor.cpp 1024 2013-07-26 16:23:59Z chao $ +* $Id: dmlprocessor.cpp 1003 2013-06-26 15:04:55Z dcathey $ * * ***********************************************************************/ /** @file */ #include "configcpp.h" #include -#include -//#define SERIALIZE_DDL_DML_CPIMPORT 1 +#define SERIALIZE_DDL_DML_CPIMPORT 1 #include #include #include -#include using namespace boost; - #include "cacheutils.h" #include "vss.h" #include "dbrm.h" @@ -57,9 +54,6 @@ using namespace logging; using namespace oam; using namespace WriteEngine; -#include "querytele.h" -using namespace querytele; - extern boost::mutex mute; extern boost::condition_variable cond; @@ -72,13 +66,9 @@ namespace dmlprocessor { // Map to store the package handler objects so we can set flags during execution // for things like ctrl+c -DMLProcessor::PackageHandlerMap_t DMLProcessor::packageHandlerMap; +std::map DMLProcessor::packageHandlerMap; boost::mutex DMLProcessor::packageHandlerMapLock; -//Map to store the BatchInsertProc object -std::map DMLProcessor::batchinsertProcessorMap; -boost::mutex DMLProcessor::batchinsertProcessorMapLock; - //------------------------------------------------------------------------------ // A thread to periodically call dbrm to see if a user is // shutting down the system or has put the system into write @@ -91,17 +81,19 @@ boost::mutex DMLProcessor::batchinsertProcessorMapLock; // If FORCE is set, we can't rollback. struct CancellationThread { - CancellationThread(DBRM * aDbrm) : fDbrm(aDbrm) + CancellationThread() {} void operator()() { bool bDoingRollback = false; bool bRollback = false; bool bForce = false; + int iShutdown; ostringstream oss; + DBRM dbrm; std::vector tableLocks; BRM::TxnID txnId; - DMLProcessor::PackageHandlerMap_t::iterator phIter; + std::map::iterator phIter; uint32_t sessionID; int rc = 0; @@ -109,7 +101,7 @@ struct CancellationThread { usleep(1000000); // 1 seconds // Check to see if someone has ordered a shutdown or suspend with rollback. - (void)fDbrm->getSystemShutdownPending(bRollback, bForce); + iShutdown = dbrm.getSystemShutdownPending(bRollback, bForce); if (bDoingRollback && bRollback) { continue; @@ -118,9 +110,9 @@ struct CancellationThread bDoingRollback = false; if (bRollback) { - RollbackTransactionProcessor rollbackProcessor(fDbrm); + RollbackTransactionProcessor rollbackProcessor; SessionManager sessionManager; - uint64_t uniqueId = fDbrm->getUnique64(); + uint64_t uniqueId = dbrm.getUnique64(); std::string errorMsg; int activeTransCount = 0; int idleTransCount = 0; @@ -131,7 +123,7 @@ struct CancellationThread // Tell any active processors to stop working and return an error // The front end will respond with a ROLLBACK command. // Mark all active processors to rollback - boost::mutex::scoped_lock lk2(DMLProcessor::packageHandlerMapLock); + DMLProcessor::packageHandlerMapLock.lock(); for (phIter = DMLProcessor::packageHandlerMap.begin(); phIter != DMLProcessor::packageHandlerMap.end(); ++phIter) @@ -149,14 +141,14 @@ struct CancellationThread oss1 << "DMLProc is rolling back back " << activeTransCount << " active transactions."; DMLProcessor::log(oss1.str(), logging::LOG_TYPE_INFO); } - if (fDbrm->isReadWrite()) + if (dbrm.isReadWrite()) { continue; } // Check for any open DML transactions that don't currently have // a processor - tableLocks = fDbrm->getAllTableLocks(); + tableLocks = dbrm.getAllTableLocks(); if (tableLocks.size() > 0) { for (uint32_t i = 0; i < tableLocks.size(); ++i) @@ -179,7 +171,15 @@ struct CancellationThread rc = rollbackProcessor.rollBackTransaction(uniqueId, txnId, sessionID, errorMsg); if ( rc == 0 ) { - fDbrm->invalidateUncommittedExtentLBIDs(txnId.id); + vector lbidList; + dbrm.getUncommittedExtentLBIDs(static_cast(txnId.id), lbidList); + vector::const_iterator iter = lbidList.begin(); + vector::const_iterator end = lbidList.end(); + while (iter != end) + { + dbrm.setExtentMaxMin(*iter, numeric_limits::min(), numeric_limits::max(), -1); + ++iter; + } //@Bug 4524. In case it is batchinsert, call bulkrollback. rc = rollbackProcessor.rollBackBatchAutoOnTransaction(uniqueId, txnId, sessionID, tableLocks[i].tableOID, errorMsg); @@ -190,7 +190,7 @@ struct CancellationThread bool lockReleased = true; try { - lockReleased = fDbrm->releaseTableLock(tableLocks[i].id); + lockReleased = dbrm.releaseTableLock(tableLocks[i].id); TablelockData::removeTablelockData(sessionID); } catch (std::exception&) @@ -216,7 +216,7 @@ struct CancellationThread ostringstream oss; oss << " problem with bulk rollback of idle transaction " << tableLocks[i].ownerTxnID << "and DBRM is setting to readonly and table lock is not released: " << errorMsg; DMLProcessor::log(oss.str(), logging::LOG_TYPE_CRITICAL); - rc = fDbrm->setReadOnly(true); + rc = dbrm.setReadOnly(true); } } else @@ -224,12 +224,13 @@ struct CancellationThread ostringstream oss; oss << " problem with rollback of idle transaction " << tableLocks[i].ownerTxnID << "and DBRM is setting to readonly and table lock is not released: " << errorMsg; DMLProcessor::log(oss.str(), logging::LOG_TYPE_CRITICAL); - rc = fDbrm->setReadOnly(true); + rc = dbrm.setReadOnly(true); } } } } } + DMLProcessor::packageHandlerMapLock.unlock(); // If there are any abandonded transactions without locks // release them. @@ -269,33 +270,22 @@ struct CancellationThread } } } - DBRM* fDbrm; }; PackageHandler::PackageHandler(const messageqcpp::IOSocket& ios, boost::shared_ptr bs, - uint8_t packageType, + messageqcpp::ByteStream::quadbyte packageType, joblist::DistributedEngineComm *ec, uint64_t maxDeleteRows, uint32_t sessionID, - execplan::CalpontSystemCatalog::SCN txnId, - DBRM * aDbrm, - const QueryTeleClient& qtc) : - fIos(ios), - fByteStream(bs), - fPackageType(packageType), - fEC(ec), - fMaxDeleteRows(maxDeleteRows), - fSessionID(sessionID), - fTxnid(txnId), - fDbrm(aDbrm), - fQtc(qtc) + execplan::CalpontSystemCatalog::SCN txnId) : + fIos(ios), fPackageType(packageType), fEC(ec), fMaxDeleteRows(maxDeleteRows), fSessionID(sessionID), fTxnid(txnId) { + fByteStream = bs; } PackageHandler::~PackageHandler() { - //cout << "In destructor" << endl; } void PackageHandler::run() @@ -306,8 +296,6 @@ void PackageHandler::run() //cout << "PackageHandler handling "; std::string stmt; unsigned DMLLoggingId = 21; - oam::OamCache* oamCache = oam::OamCache::makeOamCache(); - try { @@ -321,99 +309,132 @@ void PackageHandler::run() //boost::shared_ptr insertBs (new messageqcpp::ByteStream); messageqcpp::ByteStream bsSave = *(fByteStream.get()); insertPkg.read(*(fByteStream.get())); - QueryTeleStats qts; - qts.query_uuid = QueryTeleClient::genUUID(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = fSessionID; - qts.query_type = "INSERT"; - qts.query = insertPkg.get_SQLStatement(); - qts.system_name = oamCache->getSystemName(); - qts.module_name = oamCache->getModuleName(); - qts.schema_name = insertPkg.get_SchemaName(); - fQtc.postQueryTele(qts); //cout << "This is batch insert " << insertPkg->get_isBatchInsert() << endl; + BatchInsertProc* batchInsertProcessor; if (insertPkg.get_isBatchInsert()) { //cout << "This is batch insert " << endl; //boost::shared_ptr insertBs (new messageqcpp::ByteStream(fByteStream)); - BatchInsertProc* batchProcessor = NULL; - { - boost::mutex::scoped_lock lk(DMLProcessor::batchinsertProcessorMapLock); - - std::map::iterator batchIter = DMLProcessor::batchinsertProcessorMap.find(fSessionID); - - if (batchIter == DMLProcessor::batchinsertProcessorMap.end()) - { - batchProcessor = new BatchInsertProc(insertPkg.get_isAutocommitOn(), insertPkg.getTableOid(), fTxnid, fDbrm); - DMLProcessor::batchinsertProcessorMap[fSessionID] = batchProcessor; - //cout << "batchProcessor is created " << batchProcessor << endl; - } - else - { - batchProcessor = batchIter->second; - //cout << "Found batchProcessor " << batchProcessor << endl; - } - } - if ( insertPkg.get_Logging() ) { LoggingID logid( DMLLoggingId, insertPkg.get_SessionID(), fTxnid); logging::Message::Args args1; logging::Message msg(1); args1.add("Start SQL statement: "); - ostringstream oss; - oss << insertPkg.get_SQLStatement() << "; |" << insertPkg.get_SchemaName() <<"|"; - args1.add(oss.str()); + args1.add(insertPkg.get_SQLStatement()); msg.format( args1 ); logging::Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); TablelockData * tablelockData = TablelockData::makeTablelockData(insertPkg.get_SessionID()); uint64_t tableLockId = tablelockData->getTablelockId(insertPkg.getTableOid()); - //cout << "Processing table oid " << insertPkg.getTableOid() << " for transaction "<< (int)fTxnid << endl; if (tableLockId == 0) { - //cout << "Grabing tablelock for batchProcessor " << batchProcessor << endl; - tableLockId = batchProcessor->grabTableLock(insertPkg.get_SessionID()); - if (tableLockId == 0) + //cout << "tablelock is not found in cache " << endl; + DBRM dbrm; + uint32_t processID = ::getpid(); + int32_t txnId = fTxnid; + std::string processName("DMLProc"); + int32_t sessionId = insertPkg.get_SessionID(); + uint32_t tableOid = insertPkg.getTableOid(); + int i = 0; + OamCache * oamcache = OamCache::makeOamCache(); + std::vector pmList = oamcache->getModuleIds(); + //cout << "PMList size is " << pmList.size() << endl; + std::vector pms; + for (unsigned i=0; i < pmList.size(); i++) { - BRM::TxnID brmTxnID; - brmTxnID.id = fTxnid; - brmTxnID.valid = true; - sessionManager.rolledback(brmTxnID); - string errMsg; - int rc = 0; - batchProcessor->getError(rc, errMsg); - result.result = DMLPackageProcessor::TABLE_LOCK_ERROR; - logging::Message::Args args; - logging::Message message(1); - args.add("Insert Failed: "); - args.add(errMsg); - args.add(""); - args.add(""); - message.format(args); - result.message = message; + pms.push_back((uint)pmList[i]); + } + + try { + tableLockId = dbrm.getTableLock(pms, tableOid, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + } + catch (std::exception&) + { + result.result = dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR; + result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); break; } + + if ( tableLockId == 0 ) + { + int waitPeriod = 10; + int sleepTime = 100; // sleep 100 milliseconds between checks + int numTries = 10; // try 10 times per second + string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); + if ( waitPeriodStr.length() != 0 ) + waitPeriod = static_cast(config::Config::fromText(waitPeriodStr)); + + numTries = waitPeriod * 10; + struct timespec rm_ts; + + rm_ts.tv_sec = sleepTime/1000; + rm_ts.tv_nsec = sleepTime%1000 *1000000; + + for (; i < numTries; i++) + { +#ifdef _MSC_VER + Sleep(rm_ts.tv_sec * 1000); +#else + struct timespec abs_ts; + do + { + abs_ts.tv_sec = rm_ts.tv_sec; + abs_ts.tv_nsec = rm_ts.tv_nsec; + } + while(nanosleep(&abs_ts,&rm_ts) < 0); +#endif + try + { + processID = ::getpid(); + txnId = fTxnid; + sessionId = insertPkg.get_SessionID();; + processName = "DMLProc"; + tableLockId = dbrm.getTableLock(pms, tableOid, &processName, &processID, &sessionId, &txnId, BRM::LOADING ); + } + catch (std::exception&) + { + result.result = dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR; + result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); + break; + } + + if (tableLockId > 0) + break; + } + + if (i >= numTries) //error out + { + result.result = dmlpackageprocessor::DMLPackageProcessor::TABLE_LOCK_ERROR; + logging::Message::Args args; + args.add(processName); + args.add((uint64_t)processID); + args.add(sessionId); + BRM::TxnID brmTxnID; + brmTxnID.id = txnId; + brmTxnID.valid = true; + sessionManager.rolledback(brmTxnID); + result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); + break; + } + } if (tableLockId > 0) - tablelockData->setTablelock(insertPkg.getTableOid(), tableLockId); - } + tablelockData->setTablelock(tableOid, tableLockId); + } + + if ((tableLockId == 0) || (result.result != dmlpackageprocessor::DMLPackageProcessor::NO_ERROR)) + break; } - if (insertPkg.get_Logending() && insertPkg.get_Logging()) //only one batch need to be processed. + if (insertPkg.get_Logending() && insertPkg.get_Logging()) { + batchInsertProcessor = BatchInsertProc::makeBatchInsertProc(fTxnid, insertPkg.getTableOid()); //cout << "dmlprocessor add last pkg" << endl; - //need to add error handling. - batchProcessor->addPkg(bsSave); - batchProcessor->sendFirstBatch(); - batchProcessor->receiveOutstandingMsg(); - //@Bug 5162. Get the correct error message before the last message. - string errMsg; + batchInsertProcessor->addPkg(bsSave, true, insertPkg.get_isAutocommitOn(), insertPkg.getTableOid()); + cond.notify_one(); int rc = 0; - batchProcessor->getError(rc, errMsg); - batchProcessor->sendlastBatch(); - batchProcessor->receiveAllMsg(); - + string errMsg; + BatchInsertProc::removeBatchInsertProc(rc, errMsg); if (rc == DMLPackageProcessor::IDBRANGE_WARNING) { result.result = dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING; @@ -425,20 +446,12 @@ void PackageHandler::run() logging::Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); logging::logDML(insertPkg.get_SessionID(), fTxnid, insertPkg.get_SQLStatement()+ ";", insertPkg.get_SchemaName()); - logging::Message::Args args; - logging::Message message(1); - args.add(errMsg); - args.add(""); - args.add(""); - message.format(args); - result.message = message; } else if ( rc != 0) { result.result = dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR; logging::Message::Args args; logging::Message message(1); - cout << "Got error in the end of one batchinsert." << endl; args.add("Insert Failed: "); args.add(errMsg); args.add(""); @@ -456,10 +469,6 @@ void PackageHandler::run() } else { - // if (!insertPkg.get_isAutocommitOn()) - // { - // batchProcessor->setHwm(); - // } LoggingID logid( DMLLoggingId, insertPkg.get_SessionID(), fTxnid); logging::Message::Args args1; logging::Message msg(1); @@ -469,35 +478,22 @@ void PackageHandler::run() logger.logMessage(LOG_TYPE_DEBUG, msg, logid); logging::logDML(insertPkg.get_SessionID(), fTxnid, insertPkg.get_SQLStatement()+ ";", insertPkg.get_SchemaName()); } - //remove the batch insert object - { - boost::mutex::scoped_lock lk(DMLProcessor::batchinsertProcessorMapLock); - - std::map::iterator batchIter = DMLProcessor::batchinsertProcessorMap.find(fSessionID); - if (batchIter != DMLProcessor::batchinsertProcessorMap.end()) - { - delete batchIter->second; - DMLProcessor::batchinsertProcessorMap.erase(fSessionID); - } - } } - else if (insertPkg.get_Logending()) //Last batch + else if (insertPkg.get_Logending()) { + batchInsertProcessor = BatchInsertProc::makeBatchInsertProc(fTxnid, insertPkg.getTableOid()); int rc = 0; string errMsg; - batchProcessor->getError(rc, errMsg); + batchInsertProcessor->getError(rc, errMsg); //cout <<"dmlprocessor received last pkg from mysql rc == " << rc << endl; - if (( rc == 0) || (rc == DMLPackageProcessor::IDBRANGE_WARNING)) + if ( rc == 0) { //cout << " rc = " << rc << endl; - batchProcessor->addPkg(bsSave); - batchProcessor->sendNextBatch(); - batchProcessor->receiveOutstandingMsg(); - //@Bug 5162. Get the correct error message before the last message. - batchProcessor->getError(rc, errMsg); - batchProcessor->sendlastBatch(); - batchProcessor->receiveAllMsg(); - + batchInsertProcessor->addPkg(bsSave, true, insertPkg.get_isAutocommitOn(), insertPkg.getTableOid()); + //cout << " added last pkg to queue" << endl; + cond.notify_one(); + //cout << "Going to remove batchinsertproc " << endl; + BatchInsertProc::removeBatchInsertProc(rc, errMsg); if (rc == DMLPackageProcessor::IDBRANGE_WARNING) { result.result = dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING; @@ -509,17 +505,9 @@ void PackageHandler::run() logging::Logger logger(logid.fSubsysID); logger.logMessage(LOG_TYPE_DEBUG, msg, logid); logging::logDML(insertPkg.get_SessionID(), fTxnid, insertPkg.get_SQLStatement()+ ";", insertPkg.get_SchemaName()); - logging::Message::Args args; - logging::Message message(1); - args.add(errMsg); - args.add(""); - args.add(""); - message.format(args); - result.message = message; } else if ( rc != 0) { - //cout << "Got error in the end of last batchinsert. error message is " << errMsg << endl; result.result = dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR; logging::Message::Args args; logging::Message message(1); @@ -551,14 +539,23 @@ void PackageHandler::run() } //cout << "finished batch insert" << endl; } + else if (rc == DMLPackageProcessor::IDBRANGE_WARNING) + { + BatchInsertProc::removeBatchInsertProc(rc, errMsg); + result.result = dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING; + LoggingID logid( DMLLoggingId, insertPkg.get_SessionID(), fTxnid); + logging::Message::Args args1; + logging::Message msg(1); + args1.add("End SQL statement with warnings"); + msg.format( args1 ); + logging::Logger logger(logid.fSubsysID); + logger.logMessage(LOG_TYPE_DEBUG, msg, logid); + logging::logDML(insertPkg.get_SessionID(), fTxnid, insertPkg.get_SQLStatement()+ ";", insertPkg.get_SchemaName()); + } else { - //error occured. Receive all outstanding messages nefore erroring out. - batchProcessor->receiveOutstandingMsg(); - batchProcessor->sendlastBatch(); //needs to flush files - batchProcessor->receiveAllMsg(); + BatchInsertProc::removeBatchInsertProc(rc, errMsg); result.result = dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR; - //cout << "Got error in the end of batchinsert2. error msg is " << errMsg<< endl; logging::Message::Args args; logging::Message message(1); args.add("Insert Failed: "); @@ -576,88 +573,44 @@ void PackageHandler::run() logger.logMessage(LOG_TYPE_DEBUG, msg, logid); logging::logDML(insertPkg.get_SessionID(), fTxnid, insertPkg.get_SQLStatement()+ ";", insertPkg.get_SchemaName()); } - //remove from map - { - boost::mutex::scoped_lock lk(DMLProcessor::batchinsertProcessorMapLock); - std::map::iterator batchIter = DMLProcessor::batchinsertProcessorMap.find(fSessionID); - if (batchIter != DMLProcessor::batchinsertProcessorMap.end()) - { - //cout << "Batchinsertprcessor is deleted. " << batchIter->second << endl; - delete batchIter->second; - DMLProcessor::batchinsertProcessorMap.erase(fSessionID); - } - } - } else { + batchInsertProcessor = BatchInsertProc::makeBatchInsertProc(fTxnid, insertPkg.getTableOid()); + boost::unique_lock lock(mute); + while (batchInsertProcessor->getInsertQueue()->size() >= batchInsertProcessor->getNumDBRoots() ) + { + cond.wait(lock); + } int rc = 0; string errMsg; - batchProcessor->getError(rc, errMsg); + batchInsertProcessor->getError(rc, errMsg); if (rc == DMLPackageProcessor::IDBRANGE_WARNING) { result.result = dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING; } else if ( rc !=0) { - result.result = dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR; - //@Bug - //cout << "Got error during batchinsert. with message " << errMsg << endl; + result.result = dmlpackageprocessor::DMLPackageProcessor::VB_OVERFLOW_ERROR; logging::Message::Args args; - logging::Message message(6); - args.add( errMsg ); - message.format( args ); + logging::Message message(1); + args.add(errMsg); + message.format(args); result.message = message; - batchProcessor->receiveOutstandingMsg(); - batchProcessor->sendlastBatch(); //needs to flush files - //cout << "Last batch is sent to WES." << endl; - batchProcessor->receiveAllMsg(); - LoggingID logid( DMLLoggingId, insertPkg.get_SessionID(), fTxnid); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("End SQL statement with error"); - msg.format( args1 ); - logging::Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - //remove from map - { - boost::mutex::scoped_lock lk(DMLProcessor::batchinsertProcessorMapLock); - std::map::iterator batchIter = DMLProcessor::batchinsertProcessorMap.find(fSessionID); - if (batchIter != DMLProcessor::batchinsertProcessorMap.end()) - { - //cout << "Batchinsertprcessor is deleted. " << batchIter->second << endl; - delete batchIter->second; - DMLProcessor::batchinsertProcessorMap.erase(fSessionID); - } - } break; } - batchProcessor->addPkg(bsSave); - batchProcessor->sendNextBatch(); + batchInsertProcessor->addPkg(bsSave, false, insertPkg.get_isAutocommitOn()); + cond.notify_one(); break; } } else { - //insertPkg.readTable(*(fByteStream.get())); insertPkg.set_TxnID(fTxnid); - fProcessor.reset(new dmlpackageprocessor::InsertPackageProcessor(fDbrm, insertPkg.get_SessionID())); + fProcessor.reset(new dmlpackageprocessor::InsertPackageProcessor); result = fProcessor->processPackage(insertPkg); } - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.max_mem_pct = result.stats.fMaxMemPct; - qts.num_files = result.stats.fNumFiles; - qts.phy_io = result.stats.fPhyIO; - qts.cache_io = result.stats.fCacheIO; - qts.msg_rcv_cnt = result.stats.fMsgRcvCnt; - qts.cp_blocks_skipped = result.stats.fCPBlocksSkipped; - qts.msg_bytes_in = result.stats.fMsgBytesIn; - qts.msg_bytes_out = result.stats.fMsgBytesOut; - qts.rows = result.stats.fRows; - qts.end_time = QueryTeleClient::timeNowms(); - qts.blocks_changed = result.stats.fBlocksChanged; - fQtc.postQueryTele(qts); } break; @@ -668,38 +621,14 @@ void PackageHandler::run() boost::scoped_ptr updatePkg(new dmlpackage::UpdateDMLPackage()); updatePkg->read(*(fByteStream.get())); updatePkg->set_TxnID(fTxnid); - QueryTeleStats qts; - qts.query_uuid = updatePkg->uuid(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = fSessionID; - qts.query_type = "UPDATE"; - qts.query = updatePkg->get_SQLStatement(); - qts.system_name = oamCache->getSystemName(); - qts.module_name = oamCache->getModuleName(); - qts.schema_name = updatePkg->get_SchemaName(); - fQtc.postQueryTele(qts); // process it //@Bug 1341. Don't remove calpontsystemcatalog from this //session to take advantage of cache. - fProcessor.reset(new dmlpackageprocessor::UpdatePackageProcessor(fDbrm, updatePkg->get_SessionID())); + fProcessor.reset(new dmlpackageprocessor::UpdatePackageProcessor()); fProcessor->setEngineComm(fEC); fProcessor->setRM( &frm); idbassert( fTxnid != 0); result = fProcessor->processPackage(*(updatePkg.get())) ; - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.max_mem_pct = result.stats.fMaxMemPct; - qts.num_files = result.stats.fNumFiles; - qts.phy_io = result.stats.fPhyIO; - qts.cache_io = result.stats.fCacheIO; - qts.msg_rcv_cnt = result.stats.fMsgRcvCnt; - qts.cp_blocks_skipped = result.stats.fCPBlocksSkipped; - qts.msg_bytes_in = result.stats.fMsgBytesIn; - qts.msg_bytes_out = result.stats.fMsgBytesOut; - qts.rows = result.stats.fRows; - qts.end_time = QueryTeleClient::timeNowms(); - qts.blocks_changed = result.stats.fBlocksChanged; - fQtc.postQueryTele(qts); } break; @@ -708,37 +637,13 @@ void PackageHandler::run() boost::scoped_ptr deletePkg(new dmlpackage::DeleteDMLPackage()); deletePkg->read(*(fByteStream.get())); deletePkg->set_TxnID(fTxnid); - QueryTeleStats qts; - qts.query_uuid = deletePkg->uuid(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.session_id = fSessionID; - qts.query_type = "DELETE"; - qts.query = deletePkg->get_SQLStatement(); - qts.system_name = oamCache->getSystemName(); - qts.module_name = oamCache->getModuleName(); - qts.schema_name = deletePkg->get_SchemaName(); - fQtc.postQueryTele(qts); // process it //@Bug 1341. Don't remove calpontsystemcatalog from this session to take advantage of cache. - fProcessor.reset(new dmlpackageprocessor::DeletePackageProcessor(fDbrm, deletePkg->get_SessionID())); + fProcessor.reset(new dmlpackageprocessor::DeletePackageProcessor()); fProcessor->setEngineComm(fEC); fProcessor->setRM( &frm); idbassert( fTxnid != 0); result = fProcessor->processPackage(*(deletePkg.get())) ; - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.max_mem_pct = result.stats.fMaxMemPct; - qts.num_files = result.stats.fNumFiles; - qts.phy_io = result.stats.fPhyIO; - qts.cache_io = result.stats.fCacheIO; - qts.msg_rcv_cnt = result.stats.fMsgRcvCnt; - qts.cp_blocks_skipped = result.stats.fCPBlocksSkipped; - qts.msg_bytes_in = result.stats.fMsgBytesIn; - qts.msg_bytes_out = result.stats.fMsgBytesOut; - qts.rows = result.stats.fRows; - qts.end_time = QueryTeleClient::timeNowms(); - qts.blocks_changed = result.stats.fBlocksChanged; - fQtc.postQueryTele(qts); } break; case dmlpackage::DML_COMMAND: @@ -747,23 +652,14 @@ void PackageHandler::run() //cout << "a COMMAND package" << endl; dmlpackage::CommandDMLPackage commandPkg; commandPkg.read(*(fByteStream.get())); + // process it + //@Bug 1341. Don't remove calpontsystemcatalog from this session to take advantage of cache. + fProcessor.reset(new dmlpackageprocessor::CommandPackageProcessor); stmt = commandPkg.get_DMLStatement(); boost::algorithm::to_upper(stmt); trim(stmt); - if (stmt == "CLEANUP") - { - execplan::CalpontSystemCatalog::removeCalpontSystemCatalog(commandPkg.get_SessionID()); - execplan::CalpontSystemCatalog::removeCalpontSystemCatalog(commandPkg.get_SessionID() | 0x80000000); - } - else - { - // process it - //@Bug 1341. Don't remove calpontsystemcatalog from this session to take advantage of cache. - fProcessor.reset(new dmlpackageprocessor::CommandPackageProcessor(fDbrm, commandPkg.get_SessionID())); - - //cout << "got command " << stmt << " for session " << commandPkg.get_SessionID() << endl; - result = fProcessor->processPackage(commandPkg); - } + //cout << "got command " << stmt << " for session " << commandPkg.get_SessionID() << endl; + result = fProcessor->processPackage(commandPkg); } break; } @@ -800,9 +696,8 @@ void PackageHandler::run() results << result.miniStats; result.stats.serialize(results); fIos.write(results); - //Bug 5226. dmlprocessor thread will close the socket to mysqld. - //if (stmt == "CLEANUP") - // fIos.close(); + if (stmt == "CLEANUP") + fIos.close(); } catch(...) { @@ -821,7 +716,7 @@ void PackageHandler::rollbackPending() fProcessor->setRollbackPending(true); ostringstream oss; - oss << "PackageHandler::rollbackPending: Processing DMLPackage."; + oss << "PackageHandler::rollbackPending: rocessing DMLPackage."; DMLProcessor::log(oss.str(), logging::LOG_TYPE_DEBUG); } @@ -833,8 +728,8 @@ void added_a_pm(int) dec->Setup(); } -DMLServer::DMLServer(int packageMaxThreads, int packageWorkQueueSize, DBRM* dbrm) : - fPackageMaxThreads(packageMaxThreads), fPackageWorkQueueSize(packageWorkQueueSize), fDbrm(dbrm) +DMLServer::DMLServer(int packageMaxThreads, int packageWorkQueueSize) : + fPackageMaxThreads(packageMaxThreads), fPackageWorkQueueSize(packageWorkQueueSize) { fMqServer.reset(new MessageQueueServer("DMLProc")); @@ -852,7 +747,7 @@ void DMLServer::start() // CancellationThread is for telling all active transactions // to quit working because the system is either going down // or going into write suspend mode - CancellationThread cancelObject(fDbrm); + CancellationThread cancelObject; boost::thread cancelThread(cancelObject); cout << "DMLProc is ready..." << endl; @@ -860,7 +755,7 @@ void DMLServer::start() { ios = fMqServer->accept(); ios.setSockID(nextID++); - fDmlPackagepool.invoke(DMLProcessor(ios, fDbrm)); + fDmlPackagepool.invoke(DMLProcessor(ios)); } cancelThread.join(); } @@ -869,45 +764,29 @@ void DMLServer::start() } } -DMLProcessor::DMLProcessor(messageqcpp::IOSocket ios, BRM::DBRM* aDbrm) : - fIos(ios), fDbrm(aDbrm) +DMLProcessor::DMLProcessor(messageqcpp::IOSocket ios) : + fIos(ios) { csc = CalpontSystemCatalog::makeCalpontSystemCatalog(); csc->identity(CalpontSystemCatalog::EC); - string teleServerHost(config::Config::makeConfig()->getConfig("QueryTele", "Host")); - if (!teleServerHost.empty()) - { - int teleServerPort = config::Config::fromText(config::Config::makeConfig()->getConfig("QueryTele", "Port")); - if (teleServerPort > 0) - { - fQtc.serverParms(QueryTeleServerParms(teleServerHost, teleServerPort)); - } - } } void DMLProcessor::operator()() { + DBRM dbrm; bool bIsDbrmUp = true; try { boost::shared_ptr bs1 (new messageqcpp::ByteStream()); //messageqcpp::ByteStream bs; - uint8_t packageType; + messageqcpp::ByteStream::byte packageType; ResourceManager rm; DistributedEngineComm* fEC = DistributedEngineComm::instance(rm); + boost::scoped_ptr fCM(NULL); uint64_t maxDeleteRows = rm.getDMLMaxDeleteRows(); - - bool concurrentSupport = true; - string concurrentTranStr = config::Config::makeConfig()->getConfig("SystemConfig", "ConcurrentTransactions"); - if ( concurrentTranStr.length() != 0 ) - { - if ((concurrentTranStr.compare("N") == 0) || (concurrentTranStr.compare("n") == 0)) - concurrentSupport = false; - } - #ifndef _MSC_VER struct sigaction ign; memset(&ign, 0, sizeof(ign)); @@ -915,7 +794,7 @@ void DMLProcessor::operator()() sigaction(SIGHUP, &ign, 0); #endif fEC->Open(); - + for (;;) { //cout << "DMLProc is waiting for a Calpont DML Package on " << fIos.getSockID() << endl; @@ -924,7 +803,7 @@ void DMLProcessor::operator()() bs1.reset(new messageqcpp::ByteStream(fIos.read())); //cout << "received from mysql socket " << fIos.getSockID() << endl; } - catch (std::exception&) + catch (runtime_error&) { //This is an I/O error from InetStreamSocket::read(), just close and move on... //cout << "runtime error during read on " << fIos.getSockID() << " " << ex.what() << endl; @@ -933,26 +812,22 @@ void DMLProcessor::operator()() catch (...) { //cout << "... error during read " << fIos.getSockID() << endl; - // all this throw does is cause this thread to silently go away. I doubt this is the right - // thing to do... throw; } - - if (!bs1 || bs1->length() == 0) + if (bs1->length() == 0) { //cout << "Read 0 bytes. Closing connection " << fIos.getSockID() << endl; fIos.close(); break; } - uint32_t sessionID; - *bs1 >> sessionID; - *bs1 >> packageType; -//cout << "DMLProc received pkg. sessionid:type = " << sessionID <<":"<<(int)packageType << endl; + *(bs1.get()) >> sessionID; + *(bs1.get()) >> packageType; + uint32_t stateFlags; messageqcpp::ByteStream::byte status=255; messageqcpp::ByteStream::octbyte rowCount = 0; - if (fDbrm->getSystemState(stateFlags) > 0) // > 0 implies succesful retrieval. It doesn't imply anything about the contents + if (dbrm.getSystemState(stateFlags) > 0) // > 0 implies succesful retrieval. It doesn't imply anything about the contents { messageqcpp::ByteStream results; const char* responseMsg=0; @@ -1011,34 +886,20 @@ void DMLProcessor::operator()() dmlpackage::InsertDMLPackage insertPkg; messageqcpp::ByteStream bsSave = *(bs1.get()); insertPkg.read(*(bs1.get())); - BatchInsertProc* batchInsertProcessor = NULL; + BatchInsertProc* batchInsertProcessor; if (insertPkg.get_isBatchInsert() && insertPkg.get_Logending()) { + // No need to send lastpkg msg "if" this is a single msg + // transaction (both get_Logging() and get_Logending() are true) + if (!insertPkg.get_Logging()) { - boost::mutex::scoped_lock lk(DMLProcessor::batchinsertProcessorMapLock); - std::map::iterator batchIter = DMLProcessor::batchinsertProcessorMap.find(sessionID); - - if (batchIter != DMLProcessor::batchinsertProcessorMap.end()) //The first batch, no need to do anything - { - - batchInsertProcessor = batchIter->second; - batchInsertProcessor->addPkg(bsSave); - - batchInsertProcessor->sendlastBatch(); - batchInsertProcessor->receiveAllMsg(); - - - if (!insertPkg.get_isAutocommitOn()) - { - batchInsertProcessor->setHwm(); - } - - batchIter = DMLProcessor::batchinsertProcessorMap.find(sessionID); - if (batchIter != DMLProcessor::batchinsertProcessorMap.end()) - { - DMLProcessor::batchinsertProcessorMap.erase(sessionID); - } - } + int rc; + string errMsg; + BRM::TxnID txnid = sessionManager.getTxnID(sessionID); + batchInsertProcessor = BatchInsertProc::makeBatchInsertProc(txnid.id, insertPkg.getTableOid()); + batchInsertProcessor->addPkg(bsSave, true); + cond.notify_one(); + BatchInsertProc::removeBatchInsertProc(rc, errMsg); // Causes a join. That is, we'll wait for BatchInsertProc to finish doing its thing. } } } @@ -1062,53 +923,58 @@ void DMLProcessor::operator()() // find our own sessionID in the map. // This mechanism may prove useful for other things, so the above // comment may change. + packageHandlerMapLock.lock(); + std::map::iterator phIter = packageHandlerMap.find(sessionID); + packageHandlerMapLock.unlock(); + if (phIter != packageHandlerMap.end()) { - boost::mutex::scoped_lock lk2(DMLProcessor::packageHandlerMapLock); - DMLProcessor::PackageHandlerMap_t::iterator phIter = packageHandlerMap.find(sessionID); - if (phIter != packageHandlerMap.end()) + if (packageType == dmlpackage::DML_COMMAND) { - if (packageType == dmlpackage::DML_COMMAND) + dmlpackage::CommandDMLPackage commandPkg; + commandPkg.read(*(bs1.get())); + std::string stmt = commandPkg.get_DMLStatement(); + boost::algorithm::to_upper(stmt); + trim(stmt); + if (stmt == "CTRL+C") { - dmlpackage::CommandDMLPackage commandPkg; - commandPkg.read(*(bs1.get())); - std::string stmt = commandPkg.get_DMLStatement(); - boost::algorithm::to_upper(stmt); - trim(stmt); - if (stmt == "CTRL+C") - { - phIter->second->rollbackPending(); - fIos.close(); - break; - } + phIter->second->rollbackPending(); + fIos.close(); + break; } - else - { - // If there's a PackageHandler already working for this - // sessionID, we have a problem. Reject this package - messageqcpp::ByteStream results; - ostringstream oss; - oss << "Received a DML command for session " << sessionID << + } + else + { + // If there's a PackageHandler already working for this + // sessionID, we have a problem. Reject this package + messageqcpp::ByteStream results; + ostringstream oss; + oss << "Received a DML command for session " << sessionID << " while still processing a command for the same sessionID"; - results << static_cast(DMLPackageProcessor::DEAD_LOCK_ERROR); - results << static_cast(0); // rowcount - logging::Message::Args args; - logging::Message message(2); - args.add(oss.str()); - message.format( args ); - logging::LoggingID lid(20); - logging::MessageLog ml(lid); - ml.logErrorMessage(message); - results << message.msg(); - fIos.write(results); - continue; - } + results << static_cast(DMLPackageProcessor::DEAD_LOCK_ERROR); + results << static_cast(0); // rowcount + logging::Message::Args args; + logging::Message message(2); + args.add(oss.str()); + message.format( args ); + logging::LoggingID lid(20); + logging::MessageLog ml(lid); + ml.logErrorMessage(message); + results << message.msg(); + fIos.write(results); + continue; } } + //cout << " got a "; switch (packageType) { case dmlpackage::DML_INSERT: //cout << "DML_INSERT"; + if (fCM.get() == NULL) + { + fCM.reset(new WriteEngine::ChunkManager()); + } + fCM->setIsInsert(true); break; case dmlpackage::DML_UPDATE: //cout << "DML_UPDATE"; @@ -1117,7 +983,20 @@ void DMLProcessor::operator()() //cout << "DML_DELETE"; break; case dmlpackage::DML_COMMAND: - //cout << "DML_COMMAND"; + //cout << "DML_COMMAND"; + //@Bug 3851. Delete the chunkmanager for insert. + if ( fCM.get() != NULL ) + { + std::map oids; + fCM->setIsInsert(false); + BRM::TxnID txnid = sessionManager.getTxnID(sessionID); + if (txnid.valid) + { + fCM->setTransId(txnid.id); + fCM->flushChunks(0, oids); + fCM.reset(); + } + } break; case dmlpackage::DML_INVALID_TYPE: //cout << "DML_INVALID_TYPE"; @@ -1128,196 +1007,159 @@ void DMLProcessor::operator()() } //cout << " package" << endl; +#ifdef SERIALIZE_DDL_DML_CPIMPORT + //Check if any other active transaction + bool anyOtherActiveTransaction = true; BRM::TxnID txnid; - if (!concurrentSupport) - { - //Check if any other active transaction - bool anyOtherActiveTransaction = true; - BRM::SIDTIDEntry blockingsid; + BRM::SIDTIDEntry blockingsid; - //For logout commit trigger - if ( packageType == dmlpackage::DML_COMMAND ) - { - anyOtherActiveTransaction = false; - } - int i = 0; - int waitPeriod = 10; - //@Bug 2487 Check transaction map every 1/10 second + //For logout commit trigger + if ( packageType == dmlpackage::DML_COMMAND ) + { + anyOtherActiveTransaction = false; + } +#endif + int i = 0; + int waitPeriod = 10; + //@Bug 2487 Check transaction map every 1/10 second - int sleepTime = 100; // sleep 100 milliseconds between checks - int numTries = 10; // try 10 times per second + int sleepTime = 100; // sleep 100 milliseconds between checks + int numTries = 10; // try 10 times per second - - string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); - if ( waitPeriodStr.length() != 0 ) - waitPeriod = static_cast(config::Config::fromText(waitPeriodStr)); +#ifdef SERIALIZE_DDL_DML_CPIMPORT + string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); + if ( waitPeriodStr.length() != 0 ) + waitPeriod = static_cast(config::Config::fromText(waitPeriodStr)); - numTries = waitPeriod * 10; - struct timespec rm_ts; - - rm_ts.tv_sec = sleepTime/1000; - rm_ts.tv_nsec = sleepTime%1000 *1000000; - //cout << "starting i = " << i << endl; - //txnid = sessionManager.getTxnID(sessionID); - while (anyOtherActiveTransaction) + numTries = waitPeriod * 10; + struct timespec rm_ts; + + rm_ts.tv_sec = sleepTime/1000; + rm_ts.tv_nsec = sleepTime%1000 *1000000; + //cout << "starting i = " << i << endl; + //txnid = sessionManager.getTxnID(sessionID); + while (anyOtherActiveTransaction) + { + anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, + blockingsid ); + //cout << "session " << sessionID << " with package type " << (int)packageType << " got anyOtherActiveTransaction " << anyOtherActiveTransaction << endl; + if (anyOtherActiveTransaction) { - anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, - blockingsid ); - //cout << "session " << sessionID << " with package type " << (int)packageType << " got anyOtherActiveTransaction " << anyOtherActiveTransaction << endl; - if (anyOtherActiveTransaction) + for ( ; i < numTries; i++ ) { - for ( ; i < numTries; i++ ) - { #ifdef _MSC_VER - Sleep(rm_ts.tv_sec * 1000); + Sleep(rm_ts.tv_sec * 1000); #else - struct timespec abs_ts; - //cout << "session " << sessionID << " nanosleep on package type " << (int)packageType << endl; - do - { - abs_ts.tv_sec = rm_ts.tv_sec; - abs_ts.tv_nsec = rm_ts.tv_nsec; - } - while(nanosleep(&abs_ts,&rm_ts) < 0); + struct timespec abs_ts; + //cout << "session " << sessionID << " nanosleep on package type " << (int)packageType << endl; + do + { + abs_ts.tv_sec = rm_ts.tv_sec; + abs_ts.tv_nsec = rm_ts.tv_nsec; + } + while(nanosleep(&abs_ts,&rm_ts) < 0); #endif - anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, - blockingsid ); - if ( !anyOtherActiveTransaction ) + anyOtherActiveTransaction = sessionManager.checkActiveTransaction( sessionID, bIsDbrmUp, + blockingsid ); + if ( !anyOtherActiveTransaction ) + { + txnid = sessionManager.getTxnID(sessionID); + //cout << "Ready to process type " << (int)packageType << " with txd " << txnid << endl; + if ( !txnid.valid ) { - txnid = sessionManager.getTxnID(sessionID); - //cout << "Ready to process type " << (int)packageType << " with txd " << txnid << endl; - if ( !txnid.valid ) - { - txnid = sessionManager.newTxnID(sessionID, true); - if (txnid.valid) { - //cout << "Ready to process type " << (int)packageType << " for session "<< sessionID << " with new txnid " << txnid.id << endl; - anyOtherActiveTransaction = false; - break; - } - else - { - anyOtherActiveTransaction = true; - } + txnid = sessionManager.newTxnID(sessionID, true); + if (txnid.valid) { + //cout << "Ready to process type " << (int)packageType << " for session "<< sessionID << " with new txnid " << txnid.id << endl; + anyOtherActiveTransaction = false; + break; } else { - anyOtherActiveTransaction = false; - //cout << "already have transaction to process type " << (int)packageType << " for session "<< sessionID <<" with existing txnid " << txnid.id << endl; - break; + anyOtherActiveTransaction = true; } } - } - //cout << "ending i = " << i << endl; - } - else - { - //cout << "Ready to process type " << (int)packageType << endl; - txnid = sessionManager.getTxnID(sessionID); - if ( !txnid.valid ) - { - txnid = sessionManager.newTxnID(sessionID, true); - if (txnid.valid) { - //cout << "later Ready to process type " << (int)packageType << " for session "<< sessionID << " with new txnid " << txnid.id << endl; - anyOtherActiveTransaction = false; - } else { - anyOtherActiveTransaction = true; - //cout << "Cannot get txnid for process type " << (int)packageType << " for session "<< sessionID << endl; + anyOtherActiveTransaction = false; + //cout << "already have transaction to process type " << (int)packageType << " for session "<< sessionID <<" with existing txnid " << txnid.id << endl; + break; } } - else - { - anyOtherActiveTransaction = false; - //cout << "already have transaction to process type " << (int)packageType << " for session "<< sessionID <<" with txnid " << txnid.id << endl; - break; - } } - - if ((anyOtherActiveTransaction) && (i >= numTries)) - { - //cout << " Erroring out on package type " << (int)packageType << " for session " << sessionID << endl; - break; - } - } - - if (anyOtherActiveTransaction && (i >= numTries)) - { - //cout << " again Erroring out on package type " << (int)packageType << endl; - messageqcpp::ByteStream results; - //@Bug 2681 set error code for active transaction - status = DMLPackageProcessor::ACTIVE_TRANSACTION_ERROR; - rowCount = 0; - results << status; - results << rowCount; - Message::Args args; - args.add(static_cast(blockingsid.sessionid)); - results << IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args); - //@Bug 3854 Log to debug.log - LoggingID logid(20, 0, 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add(IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args)); - msg.format( args1 ); - logging::Logger logger(logid.fSubsysID); - logger.logMessage(LOG_TYPE_DEBUG, msg, logid); - - fIos.write(results); + //cout << "ending i = " << i << endl; } else { - //cout << "starting processing package type " << (int) packageType << " for session " << sessionID << " with id " << txnid.id << endl; - boost::shared_ptr php(new PackageHandler(fIos, bs1, packageType, fEC, - maxDeleteRows, sessionID, txnid.id, fDbrm, fQtc)); - // We put the packageHandler into a map so that if we receive a - // message to affect the previous command, we can find it. - boost::mutex::scoped_lock lk2(DMLProcessor::packageHandlerMapLock, defer_lock); - - lk2.lock(); - packageHandlerMap[sessionID] = php; - lk2.unlock(); - - php->run(); // Operates in this thread. - - lk2.lock(); - packageHandlerMap.erase(sessionID); - lk2.unlock(); - } - } - else - { - if (packageType != dmlpackage::DML_COMMAND) - { + //cout << "Ready to process type " << (int)packageType << endl; txnid = sessionManager.getTxnID(sessionID); if ( !txnid.valid ) { txnid = sessionManager.newTxnID(sessionID, true); - if (!txnid.valid) { - throw std::runtime_error( std::string("Unable to start a transaction. Check critical log.") ); + if (txnid.valid) { + //cout << "later Ready to process type " << (int)packageType << " for session "<< sessionID << " with new txnid " << txnid.id << endl; + anyOtherActiveTransaction = false; } + else + { + anyOtherActiveTransaction = true; + //cout << "Cannot get txnid for process type " << (int)packageType << " for session "<< sessionID << endl; + } + } + else + { + anyOtherActiveTransaction = false; + //cout << "already have transaction to process type " << (int)packageType << " for session "<< sessionID <<" with txnid " << txnid.id << endl; + break; } } - else + + if ((anyOtherActiveTransaction) && (i >= numTries)) { - txnid = sessionManager.getTxnID(sessionID); + //cout << " Erroring out on package type " << (int)packageType << " for session " << sessionID << endl; + break; } - - boost::shared_ptr php(new PackageHandler(fIos, bs1, packageType, fEC, - maxDeleteRows, sessionID, txnid.id, fDbrm, fQtc)); + } +#endif + +#ifdef SERIALIZE_DDL_DML_CPIMPORT + if (anyOtherActiveTransaction && (i >= numTries)) + { + //cout << " again Erroring out on package type " << (int)packageType << endl; + messageqcpp::ByteStream results; + //@Bug 2681 set error code for active transaction + status = DMLPackageProcessor::ACTIVE_TRANSACTION_ERROR; + rowCount = 0; + results << status; + results << rowCount; + Message::Args args; + args.add(static_cast(blockingsid.sessionid)); + results << IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args); + //@Bug 3854 Log to debug.log + LoggingID logid(20, 0, 0); + logging::Message::Args args1; + logging::Message msg(1); + args1.add(IDBErrorInfo::instance()->errorMsg(ERR_ACTIVE_TRANSACTION, args)); + msg.format( args1 ); + logging::Logger logger(logid.fSubsysID); + logger.logMessage(LOG_TYPE_DEBUG, msg, logid); + + fIos.write(results); + } + else + { + //cout << "starting processing package type " << (int) packageType << " for session " << sessionID << " with id " << txnid.id << endl; + PackageHandler ph(fIos, bs1, packageType, fEC, maxDeleteRows, sessionID, txnid.id); // We put the packageHandler into a map so that if we receive a // message to affect the previous command, we can find it. - boost::mutex::scoped_lock lk2(DMLProcessor::packageHandlerMapLock, defer_lock); - - lk2.lock(); - packageHandlerMap[sessionID] = php; - lk2.unlock(); - - php->run(); // Operates in this thread. - - lk2.lock(); + packageHandlerMapLock.lock(); + packageHandlerMap[sessionID] = &ph; + packageHandlerMapLock.unlock(); + ph.run(); // Operates in this thread. + packageHandlerMapLock.lock(); packageHandlerMap.erase(sessionID); - lk2.unlock(); + packageHandlerMapLock.unlock(); } +#endif } } catch (std::exception& ex) @@ -1337,7 +1179,7 @@ void DMLProcessor::operator()() } } -void RollbackTransactionProcessor::processBulkRollback (BRM::TableLockInfo lockInfo, BRM::DBRM * dbrm, uint64_t uniqueId, +void RollbackTransactionProcessor::processBulkRollback (BRM::TableLockInfo lockInfo, BRM::DBRM & dbrm, uint64_t uniqueId, OamCache::dbRootPMMap_t& dbRootPMMap, bool & lockReleased) { // Take over ownership of stale lock. @@ -1349,7 +1191,7 @@ void RollbackTransactionProcessor::processBulkRollback (BRM::TableLockInfo lockI bool ownerChanged = true; lockReleased = true; try { - ownerChanged = dbrm->changeOwner(lockInfo.id, processName, processID, sessionID, txnid); + ownerChanged = dbrm.changeOwner(lockInfo.id, processName, processID, sessionID, txnid); } catch (std::exception&) { @@ -1371,7 +1213,7 @@ void RollbackTransactionProcessor::processBulkRollback (BRM::TableLockInfo lockI //find the PMs need to send the message to std::set pmSet; int pmId; - for (uint32_t i=0; ichangeState( lockInfo.id, BRM::CLEANUP ); + dbrm.changeState( lockInfo.id, BRM::CLEANUP ); } // end of (lockInfo.state == BRM::LOADING) //delete meta data backup rollback files @@ -1444,7 +1286,7 @@ void RollbackTransactionProcessor::processBulkRollback (BRM::TableLockInfo lockI // Wait for "all" the responses, and accumulate any/all errors unsigned int pmMsgCnt = 0; //@Bug 4517 Release tablelock when it is in CLEANUP state - uint32_t rcCleanup = 0; + uint rcCleanup = 0; std::string fileDeleteErrMsg; while (pmMsgCnt < pmSet.size()) { @@ -1474,7 +1316,7 @@ void RollbackTransactionProcessor::processBulkRollback (BRM::TableLockInfo lockI } // end of while loop to process all responses to rollback cleanup fWEClient->removeQueue(uniqueId); // We ignore return release flag from releaseTableLock(). - dbrm->releaseTableLock( lockInfo.id ); + dbrm.releaseTableLock( lockInfo.id ); if (rcCleanup != 0) throw std::runtime_error(fileDeleteErrMsg); @@ -1511,3 +1353,4 @@ void DMLProcessor::log(const std::string& msg, logging::LOG_TYPE level) } //namespace dmlprocessor // vim:ts=4 sw=4: + diff --git a/dmlproc/dmlprocessor.h b/dmlproc/dmlprocessor.h index b3344323..0b247589 100644 --- a/dmlproc/dmlprocessor.h +++ b/dmlproc/dmlprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlprocessor.h 955 2013-03-20 19:37:27Z rdempsey $ +* $Id: dmlprocessor.h 863 2012-10-02 21:30:34Z dhall $ * * ***********************************************************************/ @@ -42,8 +42,7 @@ #include "dmlpackageprocessor.h" #include "calpontsystemcatalog.h" #include "dmlpackageprocessor.h" -#include "batchinsertprocessor.h" -#include "querytele.h" +//#include "iosocket.h" namespace dmlprocessor { @@ -53,7 +52,7 @@ namespace dmlprocessor class DMLServer { public: - DMLServer(int packageMaxThreads, int packageWorkQueueSize, BRM::DBRM * aDbrm); + DMLServer(int packageMaxThreads, int packageWorkQueueSize); ~DMLServer() { } @@ -93,7 +92,6 @@ class DMLServer int fPackageWorkQueueSize; /** @brief max number of packages waiting in the work queue */ boost::scoped_ptr fMqServer; - BRM::DBRM* fDbrm; }; /** @brief Thread to process a single dml package. @@ -102,10 +100,8 @@ class DMLServer class PackageHandler { public: - PackageHandler(const messageqcpp::IOSocket& ios, boost::shared_ptr bs, - uint8_t packageType, joblist::DistributedEngineComm *ec, uint64_t maxDeleteRows, - uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnId, BRM::DBRM * aDbrm, - const querytele::QueryTeleClient& qtc); + PackageHandler(const messageqcpp::IOSocket& ios, boost::shared_ptr bs, messageqcpp::ByteStream::quadbyte packageType, + joblist::DistributedEngineComm *ec, uint64_t maxDeleteRows, uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnId); ~PackageHandler(); void run(); @@ -123,8 +119,6 @@ class PackageHandler uint32_t fSessionID; execplan::CalpontSystemCatalog::SCN fTxnid; execplan::SessionManager sessionManager; - BRM::DBRM *fDbrm; - querytele::QueryTeleClient fQtc; }; /** @brief processes dml packages as they arrive @@ -137,7 +131,7 @@ class DMLProcessor * @param packageMaxThreads the maximum number of threads to process dml packages * @param packageWorkQueueSize the maximum number of dml packages in the work queue */ - DMLProcessor(messageqcpp::IOSocket ios, BRM::DBRM* aDbrm); + DMLProcessor(messageqcpp::IOSocket ios); /** @brief entry point for the DMLProcessor */ @@ -146,30 +140,21 @@ class DMLProcessor static void log(const std::string& msg, logging::LOG_TYPE level); private: messageqcpp::IOSocket fIos; - execplan::SessionManager sessionManager; boost::shared_ptr csc; - BRM::DBRM* fDbrm; - querytele::QueryTeleClient fQtc; // A map to hold pointers to all active PackageProcessors - typedef std::map > PackageHandlerMap_t; - static PackageHandlerMap_t packageHandlerMap; + static std::map packageHandlerMap; static boost::mutex packageHandlerMapLock; - // A map to hold pointers to all BatchInsertProc object - static std::map batchinsertProcessorMap; - static boost::mutex batchinsertProcessorMapLock; - friend struct CancellationThread; - friend class PackageHandler; }; class RollbackTransactionProcessor : public dmlpackageprocessor::DMLPackageProcessor { public: - RollbackTransactionProcessor(BRM::DBRM* aDbrm) : DMLPackageProcessor(aDbrm, 1) {} + RollbackTransactionProcessor() : DMLPackageProcessor() {} /** @brief process an Rollback transactions * * @param cpackage the UpdateDMLPackage to process @@ -181,7 +166,7 @@ class RollbackTransactionProcessor : public dmlpackageprocessor::DMLPackageProce return result; } - void processBulkRollback (BRM::TableLockInfo lockInfo, BRM::DBRM * dbrm, uint64_t uniqueId, + void processBulkRollback (BRM::TableLockInfo lockInfo, BRM::DBRM & dbrm, uint64_t uniqueId, oam::OamCache::dbRootPMMap_t& dbRootPMMap, bool & lockReleased); protected: diff --git a/dmlproc/dmlresultbuffer.cpp b/dmlproc/dmlresultbuffer.cpp index 3426304d..5dfcbd14 100644 --- a/dmlproc/dmlresultbuffer.cpp +++ b/dmlproc/dmlresultbuffer.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlresultbuffer.cpp 927 2013-01-21 14:11:25Z rdempsey $ +* $Id: dmlresultbuffer.cpp 734 2012-04-04 18:19:16Z rdempsey $ * * ***********************************************************************/ diff --git a/dmlproc/dmlresultbuffer.h b/dmlproc/dmlresultbuffer.h index 5abccf03..a5634344 100644 --- a/dmlproc/dmlresultbuffer.h +++ b/dmlproc/dmlresultbuffer.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: dmlresultbuffer.h 927 2013-01-21 14:11:25Z rdempsey $ +* $Id: dmlresultbuffer.h 734 2012-04-04 18:19:16Z rdempsey $ * * ***********************************************************************/ diff --git a/dmlproc/resource.h b/dmlproc/resource.h deleted file mode 100644 index c198facf..00000000 --- a/dmlproc/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by DMLProc.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/exemgr/ExeMgr.rc b/exemgr/ExeMgr.rc deleted file mode 100644 index 02d4d681..00000000 --- a/exemgr/ExeMgr.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB Execution Manager" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "ExeMgr" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "ExeMgr.exe" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/exemgr/ExeMgr.vcxproj b/exemgr/ExeMgr.vcxproj deleted file mode 100644 index ac92cf5a..00000000 --- a/exemgr/ExeMgr.vcxproj +++ /dev/null @@ -1,357 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {1CE8E777-042F-48E2-B146-2B411E14F765} - ExeMgr - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\querytele - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - iphlpapi.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\querytele - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - - - - - - - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;$(SolutionDir)../../mysql\libmysql\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\querytele - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - $(SolutionDir)..\..\signit "InfiniDB Execution Manager" \InfiniDB\Release\ExeMgr.exe - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\querytele - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB Execution Manager" $(SolutionDir)..\..x64\Release\ExeMgr.exe - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\querytele - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - $(SolutionDir)..\..\signit "InfiniDB Execution Manager" \InfiniDB\Release\ExeMgr.exe - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\querytele - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;4800;%(DisableSpecificWarnings) - false - - - iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;$(SolutionDir)../../mysql\libmysql\Release;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB Execution Manager" $(SolutionDir)..\..\x64\EnterpriseRelease\ExeMgr.exe - - - - - - - - - - - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {0bbaeacb-3336-4406-acfb-255669a3b9cf} - - - {3238cd73-8ffd-44a7-aa5f-815beef8f402} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - - - - \ No newline at end of file diff --git a/exemgr/ExeMgr.vcxproj.filters b/exemgr/ExeMgr.vcxproj.filters deleted file mode 100644 index f9ec4090..00000000 --- a/exemgr/ExeMgr.vcxproj.filters +++ /dev/null @@ -1,44 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/exemgr/Makefile.am b/exemgr/Makefile.am index 234dc3c8..8258fa84 100644 --- a/exemgr/Makefile.am +++ b/exemgr/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 808 2012-04-04 18:19:10Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -23,7 +23,7 @@ AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) bin_PROGRAMS = ExeMgr -ExeMgr_SOURCES = main.cpp activestatementcounter.cpp femsghandler.cpp +ExeMgr_SOURCES = main.cpp procstat.cpp activestatementcounter.cpp femsghandler.cpp ExeMgr_LDFLAGS = $(idb_common_ldflags) $(idb_exec_libs) -lcacheutils -lthreadpool $(AM_LDFLAGS) test: diff --git a/exemgr/Makefile.in b/exemgr/Makefile.in index 3103730a..d062cb1d 100644 --- a/exemgr/Makefile.in +++ b/exemgr/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 808 2012-04-04 18:19:10Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = ExeMgr$(EXEEXT) subdir = exemgr DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -70,8 +69,8 @@ CONFIG_CLEAN_FILES = am__installdirs = "$(DESTDIR)$(bindir)" binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) PROGRAMS = $(bin_PROGRAMS) -am_ExeMgr_OBJECTS = main.$(OBJEXT) activestatementcounter.$(OBJEXT) \ - femsghandler.$(OBJEXT) +am_ExeMgr_OBJECTS = main.$(OBJEXT) procstat.$(OBJEXT) \ + activestatementcounter.$(OBJEXT) femsghandler.$(OBJEXT) ExeMgr_OBJECTS = $(am_ExeMgr_OBJECTS) ExeMgr_LDADD = $(LDADD) DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) @@ -149,9 +148,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -193,7 +189,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -207,11 +202,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -226,7 +216,7 @@ AM_CPPFLAGS = $(idb_common_includes) $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) -ExeMgr_SOURCES = main.cpp activestatementcounter.cpp femsghandler.cpp +ExeMgr_SOURCES = main.cpp procstat.cpp activestatementcounter.cpp femsghandler.cpp ExeMgr_LDFLAGS = $(idb_common_ldflags) $(idb_exec_libs) -lcacheutils -lthreadpool $(AM_LDFLAGS) all: all-am @@ -302,6 +292,7 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/activestatementcounter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/femsghandler.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/procstat.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ diff --git a/exemgr/activestatementcounter.cpp b/exemgr/activestatementcounter.cpp index c8a28126..219d7fa9 100644 --- a/exemgr/activestatementcounter.cpp +++ b/exemgr/activestatementcounter.cpp @@ -15,15 +15,26 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: activestatementcounter.cpp 940 2013-01-21 14:11:31Z rdempsey $ +// $Id: activestatementcounter.cpp 894 2012-11-02 21:17:14Z pleblanc $ // -#include +//#define NDEBUG +#include +#include using namespace std; #include +#include +#include using namespace boost; +#include "vss.h" +#include "dbrm.h" +#include "brmtypes.h" +using namespace BRM; + +#include "cacheutils.h" + #include "activestatementcounter.h" void ActiveStatementCounter::incr(bool& counted) @@ -35,12 +46,9 @@ void ActiveStatementCounter::incr(bool& counted) mutex::scoped_lock lk(fMutex); if (upperLimit > 0) while (fStatementCount >= upperLimit) - { - fStatementsWaiting++; condvar.wait(lk); - --fStatementsWaiting; - } fStatementCount++; +// cout << "incr: fStatementCount=" << fStatementCount << endl; } void ActiveStatementCounter::decr(bool& counted) @@ -50,11 +58,37 @@ void ActiveStatementCounter::decr(bool& counted) counted = false; mutex::scoped_lock lk(fMutex); + //assert(fStatementCount > 0); if (fStatementCount == 0) return; --fStatementCount; +// cout << "decr: fStatementCount=" << fStatementCount << endl; condvar.notify_one(); + /* This doesn't take into account EC-mode syscat queries. Need to think + about whether it's actually beneficial or not. If it must happen, + the right place to do it is in PrimProc. */ +#if 0 + if (fStatementCount == 0) + { + if (!fVss.isEmpty()) + { + scoped_ptr dbrmp(new DBRM()); + int len; + shared_array entries = dbrmp->SIDTIDMap(len); + if (len == 0) + { + BlockList_t blist; + dbrmp->getUnlockedLBIDs(&blist); + if (!blist.empty()) + { + cacheutils::flushPrimProcBlocks(blist); + dbrmp->clear(); + } + } + } + } +#endif } // vim:ts=4 sw=4: diff --git a/exemgr/activestatementcounter.h b/exemgr/activestatementcounter.h index ebc314d3..e1563b4d 100644 --- a/exemgr/activestatementcounter.h +++ b/exemgr/activestatementcounter.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: activestatementcounter.h 940 2013-01-21 14:11:31Z rdempsey $ +// $Id: activestatementcounter.h 808 2012-04-04 18:19:10Z rdempsey $ // /** @file */ @@ -32,26 +32,19 @@ class ActiveStatementCounter { public: - ActiveStatementCounter(uint32_t limit) : - fStatementCount(0), - upperLimit(limit), - fStatementsWaiting(0) - {} - + ActiveStatementCounter(uint limit) : fStatementCount(0), upperLimit(limit) {} virtual ~ActiveStatementCounter() {} void incr(bool& counted); void decr(bool& counted); uint32_t cur() const { return fStatementCount; } - uint32_t waiting() const { return fStatementsWaiting; } private: ActiveStatementCounter(const ActiveStatementCounter& rhs); ActiveStatementCounter& operator=(const ActiveStatementCounter& rhs); uint32_t fStatementCount; - uint32_t upperLimit; - uint32_t fStatementsWaiting; + uint upperLimit; boost::mutex fMutex; boost::condition condvar; BRM::VSS fVss; diff --git a/exemgr/main.cpp b/exemgr/main.cpp index 3ab982e1..25002cd0 100644 --- a/exemgr/main.cpp +++ b/exemgr/main.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /********************************************************************** -* $Id: main.cpp 1000 2013-07-24 21:05:51Z pleblanc $ +* $Id: main.cpp 992 2013-07-08 20:08:38Z bpaul $ * * ***********************************************************************/ @@ -25,17 +25,17 @@ * * This is the ?main? program for dealing with execution plans and * result sets. It sits in a loop waiting for CalpontExecutionPlan - * from the FEP. It then passes the CalpontExecutionPlan to the + * from the FEP. It then passes the CalpontExecutionPlan to the * JobListFactory from which a JobList is obtained. This is passed - * to to the Query Manager running in the real-time portion of the - * EC. The ExecutionPlanManager waits until the Query Manager - * returns a result set for the job list. These results are passed - * into the CalpontResultFactory, which outputs a CalpontResultSet. - * The ExecutionPlanManager passes the CalpontResultSet into the - * VendorResultFactory which produces a result set tailored to the - * specific DBMS front end in use. The ExecutionPlanManager then + * to to the Query Manager running in the real-time portion of the + * EC. The ExecutionPlanManager waits until the Query Manager + * returns a result set for the job list. These results are passed + * into the CalpontResultFactory, which outputs a CalpontResultSet. + * The ExecutionPlanManager passes the CalpontResultSet into the + * VendorResultFactory which produces a result set tailored to the + * specific DBMS front end in use. The ExecutionPlanManager then * sends the VendorResultSet back to the Calpont Database Connector - * on the Front-End Processor where it is returned to the DBMS + * on the Front-End Processor where it is returned to the DBMS * front-end. */ #include @@ -54,12 +54,10 @@ //#define NDEBUG #include #include -#include using namespace std; #include #include -#include using namespace boost; #include "configcpp.h" @@ -68,6 +66,8 @@ using namespace config; #include "iosocket.h" #include "bytestream.h" using namespace messageqcpp; +#include "threadpool.h" +using namespace threadpool; #include "calpontselectexecutionplan.h" #include "calpontsystemcatalog.h" #include "simplecolumn.h" @@ -83,18 +83,17 @@ using namespace oam; #include "sqllogger.h" #include "idberrorinfo.h" using namespace logging; +#include "procstat.h" +using namespace procstat; #include "querystats.h" using namespace querystats; -#include "MonitorProcMem.h" -#include "querytele.h" -using namespace querytele; -#include "oamcache.h" + +#include #include "activestatementcounter.h" #include "femsghandler.h" #include "utils_utf8.h" -#include "boost/filesystem.hpp" namespace { @@ -122,8 +121,8 @@ mutex sessionMemMapMutex; //...The FrontEnd may establish more than 1 connection (which results in // more than 1 ExeMgr thread) per session. These threads will share -// the same CalpontSystemCatalog object for that session. Here, we -// define a map to track how many threads are sharing each session, so +// the same CalpontSystemCatalog object for that session. Here, we de- +// fine a map to track how many threads are sharing each session, so // that we know when we can safely delete a CalpontSystemCatalog object // shared by multiple threads per session. typedef map ThreadCntPerSessionMap_t; @@ -135,8 +134,6 @@ ActiveStatementCounter *statementsRunningCount; DistributedEngineComm *ec; -ResourceManager rm(true); - int toInt(const string& val) { if (val.length() == 0) return -1; @@ -216,39 +213,13 @@ const string prettyPrintMiniInfo(const string& in) return oss.str(); } -const string timeNow() +struct SessionThread { - time_t outputTime = time(0); - struct tm ltm; - char buf[32]; //ctime(3) says at least 26 - size_t len = 0; -#ifdef _MSC_VER - asctime_s(buf, 32, localtime_r(&outputTime, <m)); -#else - asctime_r(localtime_r(&outputTime, <m), buf); -#endif - len = strlen(buf); - if (len > 0) --len; - if (buf[len] == '\n') buf[len] = 0; - return buf; -} - -QueryTeleServerParms gTeleServerParms; - -class SessionThread -{ -public: - SessionThread(const IOSocket& ios, DistributedEngineComm* ec, ResourceManager& rm) : fIos(ios), fEc(ec), fRm(rm), - fStatsRetrieved(false), - fTeleClient(gTeleServerParms), - fOamCachePtr(oam::OamCache::makeOamCache()) - { - } - -private: + fStatsRetrieved(false) + { } IOSocket fIos; DistributedEngineComm *fEc; @@ -258,10 +229,6 @@ class SessionThread // Variables used to store return stats bool fStatsRetrieved; - QueryTeleClient fTeleClient; - - oam::OamCache* fOamCachePtr; //this ptr is copyable... - //...Reinitialize stats for start of a new query void initStats ( uint32_t sessionId, string& sqlText ) { @@ -269,6 +236,7 @@ class SessionThread fStats.reset(); fStats.setStartTime(); + //fStats.rm(&fRm); fStats.fSessionID = sessionId; fStats.fQuery = sqlText; fStatsRetrieved = false; @@ -300,6 +268,7 @@ class SessionThread { if ( sessionId < 0x80000000 ) { + // cout << "Deleting pct for session " << sessionId << endl; mutex::scoped_lock lk(sessionMemMapMutex); SessionMemMap_t::iterator mapIter = sessionMemMap.find( sessionId ); @@ -311,16 +280,15 @@ class SessionThread } //...Get and log query stats to specified output stream - const string formatQueryStats ( + void getAndLogQueryStats ( SJLP& jl, // joblist associated with query + ostream& os, // output stream to log output to const string& label, // header label to print in front of log output bool includeNewLine,//include line breaks in query stats string bool vtableModeOn, bool wantExtendedStats, uint64_t rowsReturned) { - ostringstream os; - // Get stats if not already acquired for current query if ( !fStatsRetrieved ) { @@ -361,8 +329,6 @@ class SessionThread "; MsgBytesIn-" << roundBytes(fStats.fMsgBytesIn) << "; MsgBytesOut-" << roundBytes(fStats.fMsgBytesOut) << "; Mode-" << queryMode; - - return os.str(); } //...Increment the number of threads using the specified sessionId @@ -403,6 +369,8 @@ class SessionThread } } +private: + //...Init sessionMemMap entry for specified session to 0 memory %. //...SessionId >= 0x80000000 is system catalog query we can ignore. static void initMaxMemPct ( uint32_t sessionId ) @@ -438,7 +406,7 @@ class SessionThread if (up) roundedValue++; - + ostringstream oss; oss << roundedValue << units[i]; return oss.str(); @@ -475,7 +443,7 @@ class SessionThread } } } - + void buildSysCache(const CalpontSelectExecutionPlan& csep, boost::shared_ptr csc) { const CalpontSelectExecutionPlan::ColumnMap& colMap = csep.columnMap(); @@ -529,7 +497,7 @@ class SessionThread bs = fIos.read(); if (bs.length() == 0) { - if (gDebug > 1 || (gDebug && !csep.isInternal())) + if (gDebug > 1 || (gDebug && (csep.sessionID()&0x80000000)==0)) cout << "### Got a close(1) for session id " << csep.sessionID() << endl; // connection closed by client fIos.close(); @@ -555,17 +523,6 @@ class SessionThread // now wait for the CSEP... bs = fIos.read(); } - else if (qb == 5) //somebody wants stats - { - bs.restart(); - qb = statementsRunningCount->cur(); - bs << qb; - qb = statementsRunningCount->waiting(); - bs << qb; - fIos.write(bs); - fIos.close(); - break; - } else { if (gDebug) @@ -576,37 +533,26 @@ class SessionThread } new_plan: csep.unserialize(bs); - - QueryTeleStats qts; - if ( !csep.isInternal() && - (csep.queryType() == "SELECT" || csep.queryType() == "INSERT_SELECT") ) - { - qts.query_uuid = csep.uuid(); - qts.msg_type = QueryTeleStats::QT_START; - qts.start_time = QueryTeleClient::timeNowms(); - qts.query = csep.data(); - qts.session_id = csep.sessionID(); - qts.query_type = csep.queryType(); - qts.system_name = fOamCachePtr->getSystemName(); - qts.module_name = fOamCachePtr->getModuleName(); - qts.local_query = csep.localQuery(); - qts.schema_name = csep.schemaName(); - fTeleClient.postQueryTele(qts); - } - - if (gDebug > 1 || (gDebug && !csep.isInternal())) + + // check limit clause and determin if ExeMgr needs to stop sending before finish + // @bug5176. Do limit only for select. + bool hasLimit = (csep.queryType() == "SELECT") && + (!csep.hasOrderBy()) && (csep.limitNum() != (uint64_t (-1))); + uint64_t requestRowCount = csep.limitStart() + csep.limitNum(); + + if (gDebug > 1 || (gDebug && (csep.sessionID()&0x80000000)==0)) cout << "### For session id " << csep.sessionID() << ", got a CSEP" << endl; setRMParms(csep.rmParms()); // @bug 1021. try to get schema cache for a come in query. // skip system catalog queries. - if (!csep.isInternal()) + if ((csep.sessionID()&0x80000000)==0) { boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(csep.sessionID()); buildSysCache(csep, csc); } - + // As soon as we have a session id for this thread, update the // thread count per session; only do this once per thread. // Mask 0x80000000 is for associate user query and csc query @@ -616,6 +562,7 @@ class SessionThread incSessionThreadCnt = false; } +// bool needEndMsg = false; bool needDbProfEndStatementMsg = false; Message::Args args; string sqlText = csep.data(); @@ -629,13 +576,24 @@ class SessionThread initStats( csep.sessionID(), sqlText ); fStats.fQueryType = csep.queryType(); +// @bug 1775 Use SQLLogger instead +// if (!sqlText.empty()) +// { +// if (!selfJoin) +// { +// args.add(sqlText); +// msgLog.logMessage(LOG_TYPE_DEBUG, logStartSql, args, li); +// } +// needEndMsg = true; +// } + // Log start and end statement if tracing is enabled. Keep in // mind the trace flag won't be set for system catalog queries. if (csep.traceOn()) { args.reset(); args.add((int)csep.statementID()); - args.add((int)csep.verID().currentScn); + args.add((int)csep.verID()); args.add(sqlText); msgLog.logMessage(LOG_TYPE_DEBUG, logDbProfStartStatement, @@ -643,15 +601,20 @@ class SessionThread li); needDbProfEndStatementMsg = true; } - + //Don't log subsequent self joins after first. if (selfJoin) sqlText = ""; + SQLLogger sqlLog(sqlText, li); - ostringstream oss; - oss << sqlText << "; |" << csep.schemaName() <<"|"; - SQLLogger sqlLog(oss.str(), li); + // Initialize stats for this query, including + // init sessionMemMap entry for this session to 0 memory %. + // We will need this later for traceOn() or if we receive a + // table request with qb=3 (see below). This is also recorded + // as query start time. +// initStats( csep.sessionID() ); + // Run the query, get the minimum RID list for each table statementsRunningCount->incr(stmtCounted); if (tryTuples) @@ -665,7 +628,7 @@ class SessionThread &csep, fRm, true, true); // assign query stats jl->queryStats(fStats); - + ByteStream tbs; if ((jl->status()) == 0 && (jl->putEngineComm(fEc) == 0)) @@ -673,6 +636,7 @@ class SessionThread usingTuples = true; //Tell the FE that we're sending tuples back, not TableBands +// tflg = 4; tbs << tflg; fIos.write(tbs); emsgBs.reset(); @@ -712,7 +676,7 @@ class SessionThread "response; "; throw runtime_error( errMsg.str() ); } - + if (!usingTuples) { if (gDebug) @@ -741,7 +705,7 @@ class SessionThread } - jl->doQuery(); + jl->doQuery(); // throw runtime_error("ExeMgr: Query failed to run!"); CalpontSystemCatalog::OID tableOID; bool swallowRows = false; @@ -755,7 +719,7 @@ class SessionThread bs = fIos.read(); if (bs.length() == 0) { - if (gDebug > 1 || (gDebug && !csep.isInternal())) + if (gDebug > 1 || (gDebug && (csep.sessionID()&0x80000000)==0)) cout << "### Got a close(2) for session id " << csep.sessionID() << endl; break; } @@ -779,7 +743,7 @@ class SessionThread try // @bug2244: try/catch around fIos.write() calls responding to qb command { bs >> qb; - if (gDebug > 1 || (gDebug && !csep.isInternal())) + if (gDebug > 1 || (gDebug && (csep.sessionID()&0x80000000)==0)) cout << "### For session id " << csep.sessionID() << ", got a command = " << qb << endl; if (qb == 0) { @@ -801,7 +765,7 @@ class SessionThread DeliveredTableMap::iterator iter = tm.begin(); if (iter == tm.end()) { - if (gDebug > 1 || (gDebug && !csep.isInternal())) + if (gDebug > 1 || (gDebug && (csep.sessionID()&0x80000000)==0)) cout << "### For session id " << csep.sessionID() << ", returning end flag" << endl; bs.restart(); bs << (ByteStream::byte)1; @@ -812,11 +776,12 @@ class SessionThread } else if (qb == 3) //special option-UM wants job stats string { - string statsString; + ostringstream statsString; //Log stats string to be sent back to front end - statsString = formatQueryStats( + getAndLogQueryStats( jl, + statsString, "Query Stats", false, !(csep.traceFlags() & CalpontSelectExecutionPlan::TRACE_TUPLE_OFF), @@ -825,7 +790,7 @@ class SessionThread ); bs.restart(); - bs << statsString; + bs << statsString.str(); if ((csep.traceFlags() & CalpontSelectExecutionPlan::TRACE_LOG) != 0) { bs << jl->extendedInfo(); @@ -837,10 +802,11 @@ class SessionThread bs << empty; bs << empty; } - + // send stats to connector for inserting to the querystats table fStats.serialize(bs); fIos.write(bs); + continue; } // for table mode handling @@ -874,6 +840,8 @@ class SessionThread if (swallowRows) tm.erase(tableOID); + // uint64_t totalRowCount = 0; + FEMsgHandler msgHandler(jl, &fIos); if (tableOID == 100) msgHandler.start(); @@ -881,14 +849,14 @@ class SessionThread //...Loop serializing table bands projected for the tableOID for (;;) { - uint32_t rowCount; + uint rowCount; rowCount = jl->projectTable(tableOID, bs); msgHandler.stop(); if (jl->status()) { IDBErrorInfo* errInfo = IDBErrorInfo::instance(); - + if (jl->errMsg().length() != 0) bs << jl->errMsg(); else @@ -924,7 +892,8 @@ class SessionThread if (tableOID == 100 && msgHandler.aborted()) { /* TODO: modularize the cleanup code, as well as * the rest of this fcn */ - + //cout << "saw the abort signal\n"; + decThreadCntPerSession( csep.sessionID() | 0x80000000 ); statementsRunningCount->decr(stmtCounted); fIos.close(); @@ -948,7 +917,13 @@ class SessionThread } totalRowCount += rowCount; totalBytesSent += bs.length(); - + + // send stats if finish fetching for limit query + if (hasLimit && totalRowCount >= requestRowCount) + { + break; + } + if (rowCount == 0) { msgHandler.stop(); @@ -972,20 +947,23 @@ class SessionThread if (needDbProfEndStatementMsg) { - string ss; + time_t outputTime; + outputTime = time(NULL); ostringstream prefix; prefix << "ses:" << csep.sessionID() << " Query Totals"; //Log stats string to standard out - ss = formatQueryStats( + getAndLogQueryStats( jl, + cout, prefix.str(), true, !(csep.traceFlags() & CalpontSelectExecutionPlan::TRACE_TUPLE_OFF), (csep.traceFlags() & CalpontSelectExecutionPlan::TRACE_LOG), totalRowCount); //@Bug 1306. Added timing info for real time tracking. - cout << ss << " at " << timeNow() << endl; + struct tm ltm; + cout << " at " << asctime(localtime_r(&outputTime, <m)) << endl; // log query status to debug log file args.reset(); @@ -1022,12 +1000,18 @@ class SessionThread // delete sessionMemMap entry for this session's memory % use deleteMaxMemPct( csep.sessionID() ); - string endtime(timeNow()); +// if (needEndMsg) +// msgLog.logMessage(LOG_TYPE_DEBUG, logEndSql, Message::Args(), li); + if ((csep.traceFlags() & flagsWantOutput) && (csep.sessionID() < 0x80000000)) { + //@Bug 1306. Added timing info for real time tracking. + time_t outputTime; + outputTime = time(NULL); + struct tm ltm; cout << "For session " << csep.sessionID() << ": " << totalBytesSent << - " bytes sent back at " << endtime << endl; + " bytes sent back at " << asctime(localtime_r(&outputTime, <m)) << endl; // @bug 663 - Implemented caltraceon(16) to replace the // $FIFO_SINK compiler definition in pColStep. @@ -1052,36 +1036,11 @@ class SessionThread } statementsRunningCount->decr(stmtCounted); - - if ( !csep.isInternal() && - (csep.queryType() == "SELECT" || csep.queryType() == "INSERT_SELECT") ) - { - qts.msg_type = QueryTeleStats::QT_SUMMARY; - qts.max_mem_pct = fStats.fMaxMemPct; - qts.num_files = fStats.fNumFiles; - qts.phy_io = fStats.fPhyIO; - qts.cache_io = fStats.fCacheIO; - qts.msg_rcv_cnt = fStats.fMsgRcvCnt; - qts.cp_blocks_skipped = fStats.fCPBlocksSkipped; - qts.msg_bytes_in = fStats.fMsgBytesIn; - qts.msg_bytes_out = fStats.fMsgBytesOut; - qts.rows = totalRowCount; - qts.end_time = QueryTeleClient::timeNowms(); - qts.session_id = csep.sessionID(); - qts.query_type = csep.queryType(); - qts.query = csep.data(); - qts.system_name = fOamCachePtr->getSystemName(); - qts.module_name = fOamCachePtr->getModuleName(); - qts.local_query = csep.localQuery(); - fTeleClient.postQueryTele(qts); - } - } jl.reset(); // Release CSC object (for sessionID) that was added by makeJobList() // Mask 0x80000000 is for associate user query and csc query decThreadCntPerSession( csep.sessionID() | 0x80000000 ); - } catch (std::exception& ex) { @@ -1108,190 +1067,210 @@ class SessionThread } }; - -class RssMonFcn : public utils::MonitorProcMem +void pause_(unsigned secs) { -public: - RssMonFcn(size_t maxPct, int pauseSeconds) : - MonitorProcMem(maxPct, 0, 21, pauseSeconds) {} - - /*virtual*/ - void operator()() const - { - for (;;) - { - size_t rssMb = rss(); - size_t pct = rssMb * 100 / fMemTotal; - - if (pct > fMaxPct) - { - if (fMaxPct >= 95) - { - cerr << "Too much memory allocated!" << endl; - Message::Args args; - args.add((int)pct); - args.add((int)fMaxPct); - msgLog.logMessage(LOG_TYPE_CRITICAL, logRssTooBig, args, LoggingID(16)); - exit(1); - } - if (statementsRunningCount->cur() == 0) - { - cerr << "Too much memory allocated!" << endl; - Message::Args args; - args.add((int)pct); - args.add((int)fMaxPct); - msgLog.logMessage(LOG_TYPE_WARNING, logRssTooBig, args, LoggingID(16)); - exit(1); - } - cerr << "Too much memory allocated, but stmts running" << endl; - } - - // Update sessionMemMap entries lower than current mem % use - mutex::scoped_lock lk(sessionMemMapMutex); - for ( SessionMemMap_t::iterator mapIter = sessionMemMap.begin(); - mapIter != sessionMemMap.end(); - ++mapIter ) - { - if ( pct > mapIter->second ) - { - mapIter->second = pct; - } - } - lk.unlock(); - - pause_(); - } - } -}; + struct timespec req; + struct timespec rem; -void exit_(int) -{ - exit(0); -} + req.tv_sec = secs; + req.tv_nsec = 0; -void added_a_pm(int) -{ - logging::LoggingID logid(21, 0, 0); - logging::Message::Args args1; - logging::Message msg(1); - args1.add("exeMgr caught SIGHUP. Resetting connections"); - msg.format( args1 ); - cout << msg.msg().c_str() << endl; - logging::Logger logger(logid.fSubsysID); - logger.logMessage(logging::LOG_TYPE_DEBUG, msg, logid); - if (ec) { - //set BUSY_INIT state while processing the add pm configuration change - Oam oam; - try - { - oam.processInitComplete("ExeMgr", oam::BUSY_INIT); - } - catch (...) - {} - - ec->Setup(); - - //set ACTIVE state - try - { - oam.processInitComplete("ExeMgr"); - } - catch (...) - {} - } -} + rem.tv_sec = 0; + rem.tv_nsec = 0; -void printTotalUmMemory(int sig) -{ - int64_t num = rm.availableMemory(); - cout << "Total UM memory available: " << num << endl; -} - -void setupSignalHandlers() -{ #ifdef _MSC_VER - signal(SIGSEGV, exit_); - signal(SIGINT, exit_); - signal(SIGTERM, exit_); + Sleep(req.tv_sec * 1000); #else - struct sigaction ign; +again: + if (nanosleep(&req, &rem) != 0) + if (rem.tv_sec > 0 || rem.tv_nsec > 0) + { + req = rem; + goto again; + } +#endif +} + + boost::thread* rssMonThd; + + struct RssMonFcn + { + public: + RssMonFcn(size_t maxPct, int pauseSeconds) : + fPs(getpid()), + fMaxPct(maxPct), + fPauseSeconds(pauseSeconds) + { } + + void operator()() const + { + const size_t mt = ProcStat::memTotal(); + for (;;) + { + size_t rss = fPs.rss(); + size_t pct = rss * 100 / mt; - memset(&ign, 0, sizeof(ign)); - ign.sa_handler = SIG_IGN; + if (pct > fMaxPct) + { + if (fMaxPct >= 95) + { + cerr << "Too much memory allocated!" << endl; + Message::Args args; + args.add((int)pct); + args.add((int)fMaxPct); + msgLog.logMessage(LOG_TYPE_CRITICAL, logRssTooBig, args, LoggingID(16)); + exit(1); + } + if (statementsRunningCount->cur() == 0) + { + cerr << "Too much memory allocated!" << endl; + Message::Args args; + args.add((int)pct); + args.add((int)fMaxPct); + msgLog.logMessage(LOG_TYPE_WARNING, logRssTooBig, args, LoggingID(16)); + exit(1); + } + cerr << "Too much memory allocated, but stmts running" << endl; + } - sigaction(SIGPIPE, &ign, 0); + // Update sessionMemMap entries lower than current mem % use + mutex::scoped_lock lk(sessionMemMapMutex); + for ( SessionMemMap_t::iterator mapIter = sessionMemMap.begin(); + mapIter != sessionMemMap.end(); + ++mapIter ) + { + if ( pct > mapIter->second ) + { + //cout << "Updating session " << mapIter->first + // << " percentage to " << pct << endl; + mapIter->second = pct; + } + } + lk.unlock(); - memset(&ign, 0, sizeof(ign)); - ign.sa_handler = added_a_pm; - sigaction(SIGHUP, &ign, 0); - ign.sa_handler = printTotalUmMemory; - sigaction(SIGUSR1, &ign, 0); -#endif -} + pause_(fPauseSeconds); + } + } -void setupCwd(ResourceManager& rm) -{ - string workdir = rm.getScWorkingDir(); - (void)chdir(workdir.c_str()); - if (access(".", W_OK) != 0) - (void)chdir("/tmp"); -} + private: + //RssMonFcn(const RssMonFcn& rhs); + //RssMonFcn& operator=(const RssMonFcn& rhs); -void startRssMon(size_t maxPct, int pauseSeconds) -{ - new boost::thread(RssMonFcn(maxPct, pauseSeconds)); -} + ProcStat fPs; + size_t fMaxPct; + int fPauseSeconds; // @bug 825 - Made interval to poll memory configurable. +}; -int setupResources() -{ + void exit_(int) + { + ec->destroyMulticastSender(); + exit(0); + } + + void added_a_pm(int) + { + logging::LoggingID logid(21, 0, 0); + logging::Message::Args args1; + logging::Message msg(1); + args1.add("exeMgr caught SIGHUP. Resetting connections"); + msg.format( args1 ); + cout << msg.msg().c_str() << endl; + logging::Logger logger(logid.fSubsysID); + logger.logMessage(logging::LOG_TYPE_DEBUG, msg, logid); + if (ec) { + //set BUSY_INIT state while processing the add pm configuration change + Oam oam; + try + { + oam.processInitComplete("ExeMgr", oam::BUSY_INIT); + } + catch (...) + {} + + ec->Setup(); + + //set ACTIVE state + try + { + oam.processInitComplete("ExeMgr"); + } + catch (...) + {} + } + } + + void setupSignalHandlers() + { #ifdef _MSC_VER - //FIXME: + signal(SIGSEGV, exit_); + signal(SIGINT, exit_); + signal(SIGTERM, exit_); #else - struct rlimit rlim; + struct sigaction ign; + + memset(&ign, 0, sizeof(ign)); + ign.sa_handler = SIG_IGN; - if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { - return -1; - } + sigaction(SIGPIPE, &ign, 0); - rlim.rlim_cur = rlim.rlim_max = 65536; - if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { - return -2; - } + // @bug5030 comment out the following signal hanlder to avoid + // deadlock when thread being interrupted by signal. - if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { - return -3; - } + //memset(&ign, 0, sizeof(ign)); + //ign.sa_handler = exit_; - if (rlim.rlim_cur != 65536) { - return -4; - } + //sigaction(SIGUSR1, &ign, 0); + //signal(SIGSEGV, exit_); + //signal(SIGINT, exit_); + //signal(SIGTERM, exit_); + + memset(&ign, 0, sizeof(ign)); + ign.sa_handler = added_a_pm; + sigaction(SIGHUP, &ign, 0); #endif - return 0; -} + } -} + void setupCwd(ResourceManager& rm) + { + string workdir = rm.getScWorkingDir(); + (void)chdir(workdir.c_str()); + if (access(".", W_OK) != 0) + (void)chdir("/tmp"); + } -void cleanTempDir() -{ - config::Config *config = config::Config::makeConfig(); - string allowDJS = config->getConfig("HashJoin", "AllowDiskBasedJoin"); - string tmpPrefix = config->getConfig("HashJoin", "TempFilePath"); + void startRssMon(size_t maxPct, int pauseSeconds) + { + rssMonThd = new boost::thread(RssMonFcn(maxPct, pauseSeconds)); + } - if (allowDJS == "N" || allowDJS == "n") - return; + int setupResources() + { +#ifdef _MSC_VER + //FIXME: +#else + struct rlimit rlim; - if (tmpPrefix.empty()) - tmpPrefix = "/tmp/infinidb"; + if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { + return -1; + } - tmpPrefix += "/"; + rlim.rlim_cur = rlim.rlim_max = 65536; + if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { + return -2; + } - assert(tmpPrefix != "/"); + if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { + return -3; + } - /* This is quite scary as ExeMgr usually runs as root */ - boost::filesystem::remove_all(tmpPrefix); - boost::filesystem::create_directories(tmpPrefix); -} + if (rlim.rlim_cur != 65536) { + return -4; + } +#endif + return 0; + } +} int main(int argc, char* argv[]) { @@ -1340,11 +1319,24 @@ int main(int argc, char* argv[]) #endif setupSignalHandlers(); setupResources(); - + ResourceManager rm(true); setupCwd(rm); - - cleanTempDir(); - +#ifndef _MSC_VER + //TODO: huge kludge to get Q/A going + { + string tdp = rm.getScTempDiskPath(); + ostringstream rmcmd; + rmcmd << "/usr/bin/find " << tdp << " -name LDL-\\* 2>/dev/null | /usr/bin/xargs /bin/rm -f >/dev/null 2>&1"; + (void)system(rmcmd.str().c_str()); + // @bug 1041. remove stranded tuple dl. + rmcmd.str(""); + rmcmd << "/usr/bin/find " << tdp << " -name Tuple-\\* 2>/dev/null | /usr/bin/xargs /bin/rm -f >/dev/null 2>&1"; + (void)system(rmcmd.str().c_str()); + rmcmd.str(""); + rmcmd << "/usr/bin/find " << tdp << " -name FIFO-\\* 2>/dev/null | /usr/bin/xargs /bin/rm -f >/dev/null 2>&1"; + (void)system(rmcmd.str().c_str()); + } +#endif MsgMap msgMap; msgMap[logDefaultMsg] = Message(logDefaultMsg); msgMap[logDbProfStartStatement] = Message(logDbProfStartStatement); @@ -1356,7 +1348,7 @@ int main(int argc, char* argv[]) msgMap[logExeMgrExcpt] = Message(logExeMgrExcpt); msgLog.msgMap(msgMap); - ec = DistributedEngineComm::instance(rm, true); + ec = DistributedEngineComm::instance(rm); ec->Open(); bool tellUser = true; @@ -1401,16 +1393,16 @@ int main(int argc, char* argv[]) setpriority(PRIO_PROCESS, 0, priority); #endif - string teleServerHost(rm.getConfig()->getConfig("QueryTele", "Host")); - if (!teleServerHost.empty()) - { - int teleServerPort = toInt(rm.getConfig()->getConfig("QueryTele", "Port")); - if (teleServerPort > 0) - { - gTeleServerParms.host = teleServerHost; - gTeleServerParms.port = teleServerPort; - } - } + ThreadPool tp(serverThreads, serverQueueSize); + +// // bug 934. Let ExeMgr continue, even if BucketReuseManger cannot startup successfully +// try +// { +// BucketReuseManager::instance()->startup(rm); +// } +// catch (...) +// { +// } cout << "Starting ExeMgr: st = " << serverThreads << ", sq = " << serverQueueSize << ", qs = " << rm.getEmExecQueueSize() << ", mx = " << maxPct << ", cf = " << @@ -1428,11 +1420,23 @@ int main(int argc, char* argv[]) } } + // init mysql client if cross engine support is configured + try + { + joblist::init_mysqlcl_idb(); + } + catch (...) + { + } + +// exQueueCount = 0; + for (;;) { IOSocket ios; ios = mqs->accept(); boost::thread thd(SessionThread(ios, ec, rm)); +// tp.invoke(SessionThread(ios, ec, rm)); } return 0; diff --git a/exemgr/procstat.cpp b/exemgr/procstat.cpp new file mode 100644 index 00000000..841734f0 --- /dev/null +++ b/exemgr/procstat.cpp @@ -0,0 +1,128 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// $Id: procstat.cpp 808 2012-04-04 18:19:10Z rdempsey $ + +#ifdef _MSC_VER +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#include +#endif +#include +#include +#include +#include +#include +using namespace std; + +#include "procstat.h" + +namespace procstat +{ + +size_t ProcStat::rss() const +{ + uint64_t rss; +#if defined(_MSC_VER) + HANDLE hProcess; + PROCESS_MEMORY_COUNTERS pmc; + hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | + PROCESS_VM_READ, + FALSE, fPid ); + if (NULL == hProcess) + return 0; + + if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) + rss = pmc.WorkingSetSize; + else + rss = 0; + + CloseHandle( hProcess ); + +#elif defined(__FreeBSD__) + ostringstream cmd; + cmd << "ps -a -o rss -p " << getpid() << " | tail +2"; + FILE* cmdPipe; + char input[80]; + cmdPipe = popen(cmd.str().c_str(), "r"); + input[0] = '\0'; + fgets(input, 80, cmdPipe); + input[79] = '\0'; + pclose(cmdPipe); + rss = atoi(input) * 1024LL; +#else + ostringstream pstat; + pstat << "/proc/" << fPid << "/statm"; + ifstream in(pstat.str().c_str()); + size_t x; + + in >> x; + in >> rss; + + //rss is now in pages, convert to MB + rss *= fPagesize; +#endif + rss /= (1024ULL * 1024ULL); + return static_cast(rss); +} + + +/*static*/ +size_t ProcStat::memTotal() +{ + size_t memTot; +#if defined(_MSC_VER) + MEMORYSTATUSEX memStat; + memStat.dwLength = sizeof(memStat); + if (GlobalMemoryStatusEx(&memStat) == 0) + //FIXME: Assume 2GB? + memTot = 2 * 1024 * 1024; + else + { +#ifndef _WIN64 + memStat.ullTotalPhys = std::min(memStat.ullTotalVirtual, memStat.ullTotalPhys); +#endif + //We now have the total phys mem in bytes + memTot = memStat.ullTotalPhys / 1024; + } +#elif defined(__FreeBSD__) + string cmd("sysctl -a | awk '/realmem/ {print int(($2+1023)/1024);}'"); + FILE* cmdPipe; + char input[80]; + cmdPipe = popen(cmd.c_str(), "r"); + input[0] = '\0'; + fgets(input, 80, cmdPipe); + input[79] = '\0'; + pclose(cmdPipe); + memTot = atoi(input); +#else + ifstream in("/proc/meminfo"); + string x; + + in >> x; + in >> memTot; +#endif + + //memTot is now in KB, convert to MB + memTot /= 1024; + return memTot; +} + +} + diff --git a/exemgr/procstat.h b/exemgr/procstat.h new file mode 100644 index 00000000..5ba5faed --- /dev/null +++ b/exemgr/procstat.h @@ -0,0 +1,64 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +// $Id: procstat.h 808 2012-04-04 18:19:10Z rdempsey $ + +/** @file */ + +#ifndef PROCSTAT_H__ +#define PROCSTAT_H__ + +#include +#include + +namespace procstat +{ + +/** A class to monitor a process's status + * + */ +class ProcStat +{ +public: + /** ctor + * + */ + explicit ProcStat(pid_t pid) : fPid(pid), fPagesize(getpagesize()) { } + + /** return the current process RSS size in MB + * + */ + size_t rss() const; + + /** return the system RAM size in MB + * + */ + static size_t memTotal(); + +private: + //defaults okay + //ProcStat(const ProcStat& rhs); + //ProcStat& operator=(const ProcStat& rhs); + + pid_t fPid; + int fPagesize; +}; + +} + +#endif + diff --git a/exemgr/resource.h b/exemgr/resource.h deleted file mode 100644 index 3e43cf67..00000000 --- a/exemgr/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by ExeMgr.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/m4/compilerflags.m4 b/m4/compilerflags.m4 deleted file mode 100644 index dcee6991..00000000 --- a/m4/compilerflags.m4 +++ /dev/null @@ -1,15 +0,0 @@ -dnl @synopsis CXX_FLAGS_CHECK [compiler flags] -dnl @summary check whether compiler supports given flags or not -AC_DEFUN([CXX_FLAG_CHECK], -[dnl - AC_MSG_CHECKING([if $CXX supports $1]) - ac_saved_cxxflags="$CXXFLAGS" - CXXFLAGS="-Werror $1" - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], - [AC_MSG_RESULT([yes]) - cxx_extra_flags="$cxx_extra_flags $1"], - [AC_MSG_RESULT([no])] - ) - CXXFLAGS="$ac_saved_cxxflags" -]) - diff --git a/make_rpms b/make_rpms new file mode 100755 index 00000000..57ce74e7 --- /dev/null +++ b/make_rpms @@ -0,0 +1,140 @@ +#! /bin/bash +# +# $Id$ +# + +if [ ! -f ./build/releasenum ]; then + echo "I could not find the file 'releasesum' in the ./build directory: I can't continue!" 1>&2 + echo "Maybe you're not in the right directory?" 1>&2 + exit 1 +fi + +. ./build/releasenum + +prefix="`awk '/^prefix = / {print $3}' ./Makefile 2>/dev/null`" +if [ "x$prefix" = x ]; then + echo "I could not determine the prefix from ./Makefile: I can't continue!" 1>&2 + echo "Maybe you're not in the right directory?" 1>&2 + exit 1 +fi + +if [ ! -d "$prefix/Calpont" ]; then + echo "$prefix/Calpont doesn't seem to be a directory: I can't continue!" 1>&2 + echo "Maybe you're not in the right directory?" 1>&2 + exit 1 +fi + +buildroot=$HOME/rpm/BUILD/calpont-$version-$release + +mkdir -p $buildroot/Calpont +pushd "$prefix/Calpont" > /dev/null +tar -cf - . | tar -C $buildroot/Calpont -xf - +popd >/dev/null + +#clean up some files from buildroot +rm -f $buildroot/Calpont/bin/emulator +rm -f $buildroot/Calpont/etc/Doxyfile +rm -rf $buildroot/Calpont/include +for file in $buildroot/Calpont/lib/*; do + if [ -h $file ]; then + rm -f $file + fi +done +rm -f $buildroot/Calpont/lib/libdbbc.a + +#temporarily clean up these BRM thingies +for file in dbrm script-fcns; do + rm -f $buildroot/Calpont/bin/$file +done + +#clean up these bulkload scripts +for file in bulkload.sh cleanup.sh dbbuilder.sh dbload.sh cleanup.pl; do + rm -f $buildroot/Calpont/bin/$file +done + +rm -rf $buildroot/Calpont/mysql/mysql-test +rm -rf $buildroot/Calpont/mysql/sql-bench +rm -rf $buildroot/Calpont/mysql/include + +rm -rf $buildroot/Calpont/man + +rm -rf $buildroot/Calpont/share/snmp/snmpconf-data +rm -f $buildroot/Calpont/share/snmp/mib2c.*.conf + +rm -f $buildroot/Calpont/etc/snmpd.* +rm -f $buildroot/Calpont/etc/snmptrapd.* +rm -f $buildroot/Calpont/local/snmpdx.* + +rm -rf $buildroot/Calpont/share + +rm -f $buildroot/Calpont/lib/*.a +rm -f $buildroot/Calpont/lib/*.la + +for plugin in ha_archive ha_blackhole ha_example ha_federated ha_innodb ha_innodb_plugin; do + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.a + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.la + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.so + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.so.0 +done +rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/ha_example.so.0.0.0 + +for lib in libdbug libheap libmyisam libmyisammrg libmysqlclient libmysqlclient_r libmystrings libmysys libvio; do + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.a + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.la + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.so + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.so.16 +done + +rm -rf $buildroot/Calpont/mysql/share/aclocal +rm -rf $buildroot/Calpont/mysql/share/man + +mkdir -p ~/rpm/BUILD ~/rpm/RPMS ~/rpm/SRPMS ~/rpm/SPECS ~/rpm/tmp + +if [ ! -f $HOME/.rpmmacros ]; then +cat > $HOME/.rpmmacros <> $HOME/.rpmmacros <&2 @@ -32,3 +32,57 @@ if [ ! -f "$prefix/lib/libnetsnmp.so.5.2.1" ]; then make install fi +#cleanup + +for file in \ +encode_keychange \ +fixproc \ +ipf-mod.pl \ +mib2c \ +mib2c-update \ +net-snmp-config \ +snmpbulkget \ +snmpbulkwalk \ +snmpcheck \ +snmpconf \ +snmpdelta \ +snmpdf \ +snmpget \ +snmpgetnext \ +snmpinform \ +snmpnetstat \ +snmpset \ +snmpstatus \ +snmptable \ +snmptest \ +snmptranslate \ +snmptrap \ +snmpusm \ +snmpvacm \ +snmpwalk \ +tkmib \ +traptoemail +do + rm -f ${prefix}/bin/$file +done + +for lib in \ +libnetsnmp \ +libnetsnmpagent \ +libnetsnmphelpers \ +libnetsnmpmibs \ +libnetsnmptrapd +do + rm -f ${prefix}/lib/${lib}.a + rm -f ${prefix}/lib/${lib}.la +done + +for file in \ +snmpd \ +snmptrapd +do + rm -f ${prefix}/sbin/$file +done + +rm -rf ${prefix}/man/* + diff --git a/net-snmp/net-snmp-5.2.1.2/agent/helpers/row_merge.c b/net-snmp/net-snmp-5.2.1.2/agent/helpers/row_merge.c index 512af402..f2e5541e 100644 --- a/net-snmp/net-snmp-5.2.1.2/agent/helpers/row_merge.c +++ b/net-snmp/net-snmp-5.2.1.2/agent/helpers/row_merge.c @@ -1,4 +1,3 @@ -#include #include #if HAVE_STRING_H @@ -35,7 +34,7 @@ netsnmp_get_row_merge_handler(int prefix_len) ret = netsnmp_create_handler("row_merge", netsnmp_row_merge_helper_handler); if (ret) { - ret->myvoid = (void *)(ptrdiff_t)prefix_len; + ret->myvoid = (void *) prefix_len; } return ret; } @@ -72,7 +71,7 @@ netsnmp_row_merge_helper_handler(netsnmp_mib_handler *handler, * Use the prefix length as supplied during registration, rather * than trying to second-guess what the MIB implementer wanted. */ - int SKIP_OID = (int)(ptrdiff_t)handler->myvoid; + int SKIP_OID = (int)handler->myvoid; DEBUGMSGTL(("helper:row_merge", "Got request (%d)\n", SKIP_OID)); DEBUGMSGOID(("helper:row_merge", reginfo->rootoid, reginfo->rootoid_len)); diff --git a/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/agent/nsDebug.c b/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/agent/nsDebug.c index cbee3cae..5cc47116 100644 --- a/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/agent/nsDebug.c +++ b/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/agent/nsDebug.c @@ -1,4 +1,3 @@ -#include #include #include #include @@ -291,7 +290,7 @@ get_first_debug_entry(void **loop_context, void **data_context, snmp_set_var_value(index, dbg_tokens[i].token_name, strlen(dbg_tokens[i].token_name)); - *loop_context = (void*)(ptrdiff_t)i; + *loop_context = (void*)i; *data_context = (void*)&dbg_tokens[i]; return index; } @@ -301,7 +300,7 @@ get_next_debug_entry(void **loop_context, void **data_context, netsnmp_variable_list *index, netsnmp_iterator_info *data) { - int i = (int)(ptrdiff_t)*loop_context; + int i = (int)*loop_context; for (i++; inext, &tmp); } @@ -397,7 +397,7 @@ _access_interface_entry_save_name(const char *name, oid index) if(NULL == name) return; - tmp = se_find_value_in_slist("interfaces", (char*)name); + tmp = se_find_value_in_slist("interfaces", name); if (tmp == SE_DNE) { se_add_pair_to_slist("interfaces", strdup(name), index); DEBUGMSGTL(("access:interface:ifIndex", "saved ifIndex %d for %s\n", diff --git a/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/tcp-mib/data_access/Makefile b/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/tcp-mib/data_access/Makefile deleted file mode 100644 index 3067611c..00000000 --- a/net-snmp/net-snmp-5.2.1.2/agent/mibgroup/tcp-mib/data_access/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -top_srcdir := ../../../.. - -CC := gcc -CFLAGS := -g -DNETSNMP_TCPCONN_TEST \ - -I$(top_srcdir)/agent/mibgroup/ip-mib/data_access \ - -I$(top_srcdir)/include \ - -I$(top_srcdir)/agent/mibgroup - -OBJS = tcpConn_common.o tcpConn_linux.o - -NETSNMPDIR=$(top_srcdir) -NETSNMPCONFIG=$(NETSNMPDIR)/net-snmp-config -NETSNMPBASELIBS := $(shell $(NETSNMPCONFIG) --base-agent-libs) -NETSNMPEXTLIBS := $(shell $(NETSNMPCONFIG) --external-agent-libs) -NETSNMPLIBDIRS := $(shell $(NETSNMPCONFIG) --build-lib-dirs $(NETSNMPDIR)) -NETSNMPLIBDEPS := $(shell $(NETSNMPCONFIG) --build-lib-deps $(NETSNMPDIR)) -LIB_DEPS=$(NETSNMPLIBDEPS) -LIBS=$(NETSNMPLIBDIRS) -Wl,-Bstatic $(NETSNMPBASELIBS) -Wl,-Bdynamic $(NETSNMPEXTLIBS) - -TARGET := tcpConn_test - -test: $(OBJS) - $(CC) $(CFLAGS) $(OBJS) -o $(TARGET) $(LIBS) - -clean: - rm $(OBJS) $(TARGET) diff --git a/net-snmp/net-snmp-5.2.1.2/dist/Makefile b/net-snmp/net-snmp-5.2.1.2/dist/Makefile deleted file mode 100644 index 498d0569..00000000 --- a/net-snmp/net-snmp-5.2.1.2/dist/Makefile +++ /dev/null @@ -1,133 +0,0 @@ -# ====================================================================== -# $Source: /cvsroot/net-snmp/net-snmp/dist/Makefile,v $ -# $Revision: 1.8.2.4.2.2 $ -# $Date: 2005/06/30 16:30:12 $ -# $Author: hardaker $ -# $Name: Ext-5-2-1-2 $ -# $State: Exp $ -# ====================================================================== - -# Makefile for generating rpm package files (.rpm) for net-snmp. - -# GNU 'make'-specific features are used in this makefile. -# Other makes may or may not work with it. -# See http://www.gnu.org/manual/make/index.html for details. - -SHELL = /bin/sh - -# Define the RPM package name -NAME = net-snmp - -# Define the default RPM release number. Set by VersionMunge.pl -VERSION = 5.1.2 - -VERSION_TAG=`echo Ext-$(VERSION) | sed 's/\./-/g;'` - -WITH_PERL=1 -EMBED_PERL=0 - -# Define the RPM architecture, i.e., 'noarch', 'i386', 'i686', etc. -ARCH = `uname -m` - -# Directory structure expected by 'rpm' program -RPM_BASE := $(PWD)/rpm - -RPM_TREE := \ - $(RPM_BASE)/BUILD \ - $(RPM_BASE)/RPMS \ - $(RPM_BASE)/SOURCES \ - $(RPM_BASE)/SPECS \ - $(RPM_BASE)/SRPMS - -.PHONY: all clean rpm_files binary_rpm source_rpm all_rpm - -all: all_rpm_files - -# Delete all generated files. -clean: - rm -rf $(RPM_BASE) - -# -------------------------------------------------------------------- -# Macros and rules for updating net-snmp-x.x.x.tar.gz. -# 'rpm' expects a compressed archive (.tar.gz) of the source directory -# to exist (in the rpm/SOURCES directory) before it is run. -# -------------------------------------------------------------------- -CVSROOT = :pserver:anonymous@cvs.net-snmp.sourceforge.net:/cvsroot/net-snmp - -PKG_VER := $(NAME)-$(VERSION) - -GZIP_TAR := $(RPM_BASE)/SOURCES/$(PKG_VER).tar.gz - -gzip_tar: $(GZIP_TAR) - -$(GZIP_TAR): - @echo "Creating a compressed archive of the package's source files..." - (cd $(RPM_BASE)/SOURCES; \ - cvs -d$(CVSROOT) login; \ - cvs -z3 -d$(CVSROOT) export -r$(VERSION_TAG) $(NAME); \ - mv $(NAME) $(PKG_VER); \ - tar cf $(PKG_VER).tar $(PKG_VER); \ - gzip $(PKG_VER).tar) - @echo "A compressed archive of the package's source-file tree has been created." - -# -------------------------------------------------------------------- -# Macros and rules for updating the binary and source RPM package files. -# -------------------------------------------------------------------- -# Redefine '%_topdir' to allow an RPM package file to be built anywhere, -# instead of in the /usr/src/redhat directory tree. -# -# Don't want 'rpmbuild' to strip your executable programs? -# Then add this line: -# --define='_os_install_post /usr/lib/rpm/brp-compress' \ -# to the RPM_OPTS macro definition. This will eliminate the -# stripping of binaries, but still retain the compression of -# manual pages. -# -ifeq ($(WITH_PERL),1) -PERLOPTS = --with perl_modules -endif -ifeq ($(EMBED_PERL),1) -PERLOPTS += --with embedded_perl -endif - -RPM_OPTS := \ - --define='_topdir $(PWD)/rpm' \ - --define='_includedir /usr/include/net-snmp' \ - --target $(ARCH) $(PERLOPTS) - -SPEC_FILE := $(NAME).spec -RPM_SPEC := $(RPM_BASE)/SPECS/$(SPEC_FILE) - -BINARY_RPM := $(RPM_BASE)/RPMS/$(ARCH)/$(PKG_VER)-$(RELEASE).$(ARCH).rpm -SOURCE_RPM := $(RPM_BASE)/SRPMS/$(PKG_VER)-$(RELEASE).src.rpm - -rpm_files: $(GZIP_TAR) all_rpm_files -binary_rpm: $(BINARY_RPM) -source_rpm: $(SOURCE_RPM) -rpm_tree: $(RPM_TREE) - -all_rpm_files: $(RPM_TREE) $(RPM_SPEC) - (cd $(RPM_BASE)/SPECS; \ - rpmbuild -ba $(RPM_OPTS) $(SPEC_FILE)) - -$(BINARY_RPM): $(RPM_TREE) $(RPM_SPEC) - (cd $(RPM_BASE)/SPECS; \ - rpmbuild -bb $(RPM_OPTS) $(SPEC_FILE)) - -$(SOURCE_RPM): $(RPM_TREE) $(RPM_SPEC) - (cd $(RPM_BASE)/SPECS; \ - rpmbuild -bs $(RPM_OPTS) $(SPEC_FILE)) - -$(RPM_SPEC): $(RPM_BASE)/SPECS $(SPEC_FILE) - cp $(SPEC_FILE) $@ - -$(RPM_TREE): - mkdir -p $@ - -$(SPEC_FILE): - @echo "ERROR: missing '$(SPEC_FILE)' in the current directory" - @exit 1 - -FORCE: - -# === End of Makefile === # diff --git a/net-snmp/net-snmp-5.2.1.2/include/net-snmp/library/snmp_logging.h b/net-snmp/net-snmp-5.2.1.2/include/net-snmp/library/snmp_logging.h index 634c846a..fcf1512d 100644 --- a/net-snmp/net-snmp-5.2.1.2/include/net-snmp/library/snmp_logging.h +++ b/net-snmp/net-snmp-5.2.1.2/include/net-snmp/library/snmp_logging.h @@ -81,7 +81,7 @@ extern "C" { int snmp_log_options(char *optarg, int argc, char *const *argv); void snmp_log_options_usage(const char *lead, FILE *outf); - const char *snmp_log_syslogname(const char *syslogname); + char *snmp_log_syslogname(char *syslogname); typedef struct netsnmp_log_handler_s netsnmp_log_handler; typedef int (NetsnmpLogHandler)(netsnmp_log_handler*, int, const char *); diff --git a/net-snmp/net-snmp-5.2.1.2/snmplib/md5.c b/net-snmp/net-snmp-5.2.1.2/snmplib/md5.c index abe5b50f..0336f05d 100644 --- a/net-snmp/net-snmp-5.2.1.2/snmplib/md5.c +++ b/net-snmp/net-snmp-5.2.1.2/snmplib/md5.c @@ -465,7 +465,6 @@ MDsign(u_char * data, size_t len, u_char * mac, size_t maclen, goto update_end; i = len; -#if 0 if (((unsigned int) data) % sizeof(long) != 0) { /* * this relies on the ability to use integer math and thus we @@ -476,9 +475,6 @@ MDsign(u_char * data, size_t len, u_char * mac, size_t maclen, } else { cp = data; } -#else - cp = data; -#endif while (i >= 64) { rc = MDupdate(&MD, cp, 64 * 8); diff --git a/net-snmp/net-snmp-5.2.1.2/snmplib/snmp_logging.c b/net-snmp/net-snmp-5.2.1.2/snmplib/snmp_logging.c index 0c1073e5..384ba89d 100644 --- a/net-snmp/net-snmp-5.2.1.2/snmplib/snmp_logging.c +++ b/net-snmp/net-snmp-5.2.1.2/snmplib/snmp_logging.c @@ -374,7 +374,7 @@ snmp_log_options(char *optarg, int argc, char *const *argv) if (facility == -1) return -1; logh->pri_max = pri_max; logh->token = strdup(snmp_log_syslogname(0)); - logh->magic = (void *)(ptrdiff_t)facility; + logh->magic = (void *)facility; snmp_enable_syslog_ident(snmp_log_syslogname(0), facility); } break; @@ -409,8 +409,8 @@ snmp_log_options(char *optarg, int argc, char *const *argv) return 0; } -const char * -snmp_log_syslogname(const char *pstr) +char * +snmp_log_syslogname(char *pstr) { if (pstr) strncpy (syslogname, pstr, sizeof(syslogname)); @@ -982,7 +982,7 @@ log_handler_syslog( netsnmp_log_handler* logh, int pri, const char *string) */ if (!(logh->imagic)) { const char *ident = logh->token; - int facility = (int)(ptrdiff_t)logh->magic; + int facility = (int)logh->magic; if (!ident) ident = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_APPTYPE); diff --git a/oam/Makefile.am b/oam/Makefile.am index e0e92cfc..2de83d44 100644 --- a/oam/Makefile.am +++ b/oam/Makefile.am @@ -1,23 +1,23 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ -SUBDIRS = etc post oamcpp install_scripts cloud +SUBDIRS = etc post oamcpp replaytxnlog install_scripts test: diff --git a/oam/Makefile.in b/oam/Makefile.in index dcf8a0c0..1f19b9e4 100644 --- a/oam/Makefile.in +++ b/oam/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ srcdir = @srcdir@ @@ -57,9 +57,8 @@ host_triplet = @host@ subdir = oam DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -209,7 +199,7 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ -SUBDIRS = etc post oamcpp install_scripts cloud +SUBDIRS = etc post oamcpp replaytxnlog install_scripts all: all-recursive .SUFFIXES: diff --git a/oam/cloud/IDBInstanceCmds.sh b/oam/cloud/IDBInstanceCmds.sh index 33757da8..5ed2a9ab 100644 --- a/oam/cloud/IDBInstanceCmds.sh +++ b/oam/cloud/IDBInstanceCmds.sh @@ -8,7 +8,7 @@ prefix=/usr/local #check command if [ "$1" = "" ]; then - echo "Enter Command Name: {launchInstance|getInstance|getZone|getPrivateIP|getKey|getAMI|getType|terminateInstance|startInstance|assignElasticIP|deassignElasticIP|getProfile|stopInstance|getGroup} + echo "Enter Command Name: {launchInstance|getInstance|getZone|getPrivateIP|getType|getKey|getAMI|getType|terminateInstance|startInstance|assignElasticIP|deassignElasticIP|getProfile|stopInstance} }" exit 1 fi @@ -23,19 +23,14 @@ fi if [ "$1" = "launchInstance" ]; then if [ "$2" = "" ]; then - IPaddress="unassigned" - else - IPaddress="$2" - fi - if [ "$3" = "" ]; then instanceType="unassigned" else - instanceType="$3" + instanceType="$2" fi - if [ "$4" = "" ]; then + if [ "$3" = "" ]; then group="unassigned" else - group="$4" + group="$3" fi fi @@ -83,7 +78,7 @@ if [ "$1" = "deassignElasticIP" ]; then echo "Enter Elastic IP Address" exit 1 else - IPAddress="$2"getType + IPAddress="$2" fi fi @@ -113,7 +108,6 @@ export JAVA_HOME=$java x509Cert=`$prefix/Calpont/bin/getConfig Installation AmazonX509Certificate` x509PriKey=`$prefix/Calpont/bin/getConfig Installation AmazonX509PrivateKey` Region=`$prefix/Calpont/bin/getConfig Installation AmazonRegion` -subnet=`$prefix/Calpont/bin/getConfig Installation AmazonSubNetID` if test ! -f $x509Cert ; then echo "FAILED: missing x509Cert : $x509Cert" @@ -128,13 +122,6 @@ fi #default instance to null instance="" -describeInstanceFile="/tmp/describeInstance.txt" -touch $describeInstanceFile - -describeInstance() { - ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region > $describeInstanceFile 2>&1 -} - getInstance() { if [ "$instance" != "" ]; then echo $instance @@ -145,14 +132,7 @@ getInstance() { localIP=`ifconfig eth0 | grep "inet addr:" | awk '{print substr($2,6,20)}'` #get local Instance ID -# instance=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - - instance=`cat $describeInstanceFile | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - if [ "$instance" == "" ]; then - describeInstance - fi - instance=`cat $describeInstanceFile | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - + instance=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` echo $instance return } @@ -167,14 +147,7 @@ getInstancePrivate() { localIP=`ifconfig eth0 | grep "inet addr:" | awk '{print substr($2,6,20)}'` #get local Instance ID -# instance=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - - instance=`cat $describeInstanceFile | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - if [ "$instance" == "" ]; then - describeInstance - fi - instance=`cat $describeInstanceFile | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - + instance=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $localIP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` return } @@ -187,24 +160,7 @@ getZone() { #get local Instance ID getInstancePrivate >/dev/null 2>&1 #get zone - if [ "$subnet" == "unassigned" ]; then -# zone=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $11}'` - - zone=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $11}'` - if [ "$zone" == "" ]; then - describeInstance - fi - zone=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $11}'` - - else -# zone=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $10}'` - - zone=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $10}'` - if [ "$zone" == "" ]; then - describeInstance - fi - zone=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $10}'` - fi + zone=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $11}'` $prefix/Calpont/bin/setConfig Installation AmazonZone $zone fi @@ -214,48 +170,31 @@ getZone() { getPrivateIP() { #get instance info -# ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region $instanceName > /tmp/instanceInfo_$instanceName 2>&1 - - grep -B1 -A4 -m 1 $instanceName $describeInstanceFile > /tmp/instanceInfo_$instanceName 2>&1 - if [ `cat /tmp/instanceInfo_$instanceName | wc -c` -eq 0 ]; then - describeInstance - fi - grep -B1 -A4 -m 1 $instanceName $describeInstanceFile > /tmp/instanceInfo_$instanceName 2>&1 - + ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region $instanceName > /tmp/instanceInfo_$instanceName 2>&1 + #check if running or terminated cat /tmp/instanceInfo_$instanceName | grep running > /tmp/instanceStatus_$instanceName if [ `cat /tmp/instanceStatus_$instanceName | wc -c` -eq 0 ]; then # not running - cat /tmp/instanceInfo_$instanceName | grep pending > /tmp/instanceStatus_$instanceName + cat /tmp/instanceInfo_$instanceName | grep terminated > /tmp/instanceStatus_$instanceName if [ `cat /tmp/instanceStatus_$instanceName | wc -c` -ne 0 ]; then - describeInstance - echo "stopped" + echo "terminated" exit 1 else - cat /tmp/instanceInfo_$instanceName | grep terminated > /tmp/instanceStatus_$instanceName + cat /tmp/instanceInfo_$instanceName | grep shutting-down > /tmp/instanceStatus_$instanceName if [ `cat /tmp/instanceStatus_$instanceName | wc -c` -ne 0 ]; then echo "terminated" exit 1 else - cat /tmp/instanceInfo_$instanceName | grep shutting-down > /tmp/instanceStatus_$instanceName - if [ `cat /tmp/instanceStatus_$instanceName | wc -c` -ne 0 ]; then - echo "terminated" - exit 1 - else - echo "stopped" - exit 1 - fi + echo "stopped" + exit 1 fi fi fi #running, get priviate IP Address - if [ "$subnet" == "unassigned" ]; then - IpAddr=`head -n 2 /tmp/instanceInfo_$instanceName | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $15}'` - else - IpAddr=`head -n 2 /tmp/instanceInfo_$instanceName | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $13}'` - fi - + IpAddr=`cat /tmp/instanceInfo_$instanceName | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $15}'` + echo $IpAddr exit 0 } @@ -264,25 +203,7 @@ getType() { #get local Instance ID getInstancePrivate >/dev/null 2>&1 #get Type - if [ "$subnet" == "unassigned" ]; then -# instanceType=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $9}'` - - instanceType=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $9}'` - if [ "$instanceType" == "" ]; then - describeInstance - fi - instanceType=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $9}'` - - else -# instanceType=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $8}'` - - instanceType=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $8}'` - if [ "$instanceType" == "" ]; then - describeInstance - fi - instanceType=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $8}'` - - fi + instanceType=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $9}'` echo $instanceType return @@ -292,25 +213,7 @@ getKey() { #get local Instance ID getInstancePrivate >/dev/null 2>&1 #get Key - if [ "$subnet" == "unassigned" ]; then -# key=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $7}'` - - key=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $7}'` - if [ "$key" == "" ]; then - describeInstance - fi - key=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $7}'` - - else -# key=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $6}'` - - key=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $6}'` - if [ "$key" == "" ]; then - describeInstance - fi - key=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $6}'` - - fi + key=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $7}'` echo $key return @@ -320,13 +223,7 @@ getAMI() { #get local Instance ID getInstancePrivate >/dev/null 2>&1 #get AMI -# ami=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $3}'` - - ami=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $3}'` - if [ "$ami" == "" ]; then - describeInstance - fi - ami=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $3}'` + ami=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $3}'` echo $ami return @@ -336,24 +233,7 @@ getGroup() { #get local Instance ID getInstancePrivate >/dev/null 2>&1 #get group - if [ "$subnet" == "unassigned" ]; then -# group=`ec2-describe-instances -C $x509Cert -K $x509PriKey $instance --region $Region | grep -m 1 RESERVATION | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $4}'` - - group=`grep -B1 -A4 -m 1 $instance $describeInstanceFile | grep -m 1 RESERVATION | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $4}'` - if [ "$group" == "" ]; then - describeInstance - fi - group=`grep -B1 -A4 -m 1 $instance $describeInstanceFile | grep -m 1 RESERVATION | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $4}'` - - else -# group=`ec2-describe-instances -C $x509Cert -K $x509PriKey $instance --region $Region | grep -m 1 GROUP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - - group=`grep -B1 -A4 -m 1 $instance $describeInstanceFile | grep -m 1 GROUP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - if [ "$group" == "" ]; then - describeInstance - fi - group=`grep -B1 -A4 -m 1 $instance $describeInstanceFile | grep -m 1 GROUP | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - fi + group=`ec2-describe-instances -C $x509Cert -K $x509PriKey $instance --region $Region | grep -m 1 RESERVATION | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $4}'` echo $group return @@ -363,25 +243,7 @@ getProfile() { #get local Instance ID getInstancePrivate >/dev/null 2>&1 #get Type - if [ "$subnet" == "unassigned" ]; then -# instanceProfile=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $23}'` - - instanceProfile=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $23}'` - if [ "$instanceProfile" == "" ]; then - describeInstance - fi - instanceProfile=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $23}'` - - else -# instanceProfile=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $21}'` - - instanceProfile=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $21}'` - if [ "$instanceProfile" == "" ]; then - describeInstance - fi - instanceProfile=`cat $describeInstanceFile | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $21}'` - - fi + instanceProfile=`ec2-describe-instances -C $x509Cert -K $x509PriKey --region $Region | grep -m 1 $instance | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $23}'` echo $instanceProfile return @@ -405,43 +267,10 @@ launchInstance() { #get AMI Profile getProfile >/dev/null 2>&1 - if [ "$subnet" == "unassigned" ]; then - #NOT VPC - if [ "$instanceProfile" = "" ] || [ "$instanceProfile" = "default" ]; then - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone --region $Region $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - else - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone -p $instanceProfile --region $Region $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - fi - else # VPC - if [ "$instanceProfile" = "" ] || [ "$instanceProfile" = "default" ]; then - if [ "$group" != "default" ]; then - if [ "$IPaddress" = "autoassign" ]; then - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone --region $Region -s $subnet $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - else - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone --region $Region -s $subnet --private-ip-address $IPaddress $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - fi - else - if [ "$IPaddress" = "autoassign" ]; then - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -t $instanceType -z $zone --region $Region -s $subnet $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - else - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -t $instanceType -z $zone --region $Region -s $subnet --private-ip-address $IPaddress $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - fi - fi - else - if [ "$group" != "default" ]; then - if [ "$IPaddress" = "autoassign" ]; then - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone -p $instanceProfile --region $Region -s $subnet $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - else - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone -p $instanceProfile --region $Region -s $subnet --private-ip-address $IPaddress $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - fi - else - if [ "$IPaddress" = "autoassign" ]; then - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -t $instanceType -z $zone -p $instanceProfile --region $Region -s $subnet $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - else - newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -t $instanceType -z $zone -p $instanceProfile --region $Region -s $subnet --private-ip-address $IPaddress $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` - fi - fi - fi + if [ "$instanceProfile" = "" ]; then + newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone --region $Region $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` + else + newInstance=`ec2-run-instances -C $x509Cert -K $x509PriKey -k $key -g $group -t $instanceType -z $zone -p $instanceProfile --region $Region $ami | grep -m 1 INSTANCE | awk '{gsub(/^[ \t]+|[ \t]+$/,"");print $2}'` fi echo $newInstance return @@ -543,11 +372,8 @@ case "$1" in getProfile) getProfile ;; - getGroup) - getGroup - ;; *) - echo $"Usage: $0 {launchInstance|getInstance|getZone|getPrivateIP|getType|getKey|getAMI|getType|terminateInstance|startInstance|assignElasticIP|deassignElasticIP|getProfile|stopInstance|getGroup}" + echo $"Usage: $0 {launchInstance|getInstance|getZone|getPrivateIP|getType|getKey|getAMI|getType|terminateInstance|startInstance|assignElasticIP|deassignElasticIP|getProfile|stopInstance}" exit 1 esac diff --git a/oam/cloud/Makefile.am b/oam/cloud/Makefile.am deleted file mode 100644 index e5568cd3..00000000 --- a/oam/cloud/Makefile.am +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -bin_SCRIPTS = IDBInstanceCmds.sh IDBVolumeCmds.sh - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/oam/cloud/Makefile.in b/oam/cloud/Makefile.in deleted file mode 100644 index 9f1111e2..00000000 --- a/oam/cloud/Makefile.in +++ /dev/null @@ -1,400 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -subdir = oam/cloud -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binSCRIPT_INSTALL = $(INSTALL_SCRIPT) -SCRIPTS = $(bin_SCRIPTS) -SOURCES = -DIST_SOURCES = -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -bin_SCRIPTS = IDBInstanceCmds.sh IDBVolumeCmds.sh -all: all-am - -.SUFFIXES: -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oam/cloud/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oam/cloud/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binSCRIPTS: $(bin_SCRIPTS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_SCRIPTS)'; for p in $$list; do \ - if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ - if test -f $$d$$p; then \ - f=`echo "$$p" | sed 's|^.*/||;$(transform)'`; \ - echo " $(binSCRIPT_INSTALL) '$$d$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(binSCRIPT_INSTALL) "$$d$$p" "$(DESTDIR)$(bindir)/$$f"; \ - else :; fi; \ - done - -uninstall-binSCRIPTS: - @$(NORMAL_UNINSTALL) - @list='$(bin_SCRIPTS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's|^.*/||;$(transform)'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: -tags: TAGS -TAGS: - -ctags: CTAGS -CTAGS: - - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(SCRIPTS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -f Makefile -distclean-am: clean-am distclean-generic distclean-libtool - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binSCRIPTS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-generic mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binSCRIPTS uninstall-info-am - -.PHONY: all all-am check check-am clean clean-generic clean-libtool \ - distclean distclean-generic distclean-libtool distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binSCRIPTS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ - uninstall uninstall-am uninstall-binSCRIPTS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oam/etc/AlarmConfig.xml b/oam/etc/AlarmConfig.xml index 9a08916d..54dc5a3b 100644 --- a/oam/etc/AlarmConfig.xml +++ b/oam/etc/AlarmConfig.xml @@ -1,5 +1,5 @@ - + 1 @@ -282,10 +282,10 @@ 32 - Unassigned - Unassigned - 0 - 0 + EE_LICENSE_EXPIRED + Enterprise License has Expired, Contact Calpont Customer Support. + 1 + 100 0 0 @@ -316,13 +316,4 @@ 0 0 - - 36 - INVALID_LOCALE - An Error was reported on setting system locale. - 1 - 100 - 0 - 0 - diff --git a/oam/etc/Calpont.xml b/oam/etc/Calpont.xml old mode 100755 new mode 100644 index d082b5c5..732cb054 --- a/oam/etc/Calpont.xml +++ b/oam/etc/Calpont.xml @@ -1,268 +1,61 @@ - - - 0.0.0.0 + 127.0.0.1 8601 - unassigned - - 0.0.0.0 - 8602 - - - 0.0.0.0 - 8603 - - - 0.0.0.0 - 8604 - - - 0.0.0.0 - 8605 - - - - - 127.0.0.1 - 8800 - - - 0.0.0.0 - 8800 - - - 0.0.0.0 - 8800 - - - 0.0.0.0 - 8800 - - - 0.0.0.0 - 8622 - - - 0.0.0.0 - 8622 - - - 0.0.0.0 - 8622 - - - 0.0.0.0 - 8630 - - 0.0.0.0 + 127.0.0.1 8612 - 0.0.0.0 + 127.0.0.1 8614 + + 127.0.0.1 + 8630 + 10000 1 - 8 128 - 10K + + 10K 0 13 512 - 512 + 512 1 0 - y - - - - y + n - 0.0.0.0 + 127.0.0.1 8620 - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - - - 0.0.0.0 - 8620 - C calpont-1 pm1 - unassigned - unassigned - 1 + 10 3 - 30 // 2.5 minutes - - 1 $INSTALLDIR/data1 $INSTALLDIR/data1/systemFiles/dbrm/BRM_saves - $INSTALLDIR/data1/systemFiles/dbrm/tablelocks - 20 - 100000 - 90 - 80 - 70 + $INSTALLDIR/data1/systemFiles/dbrm/tablelocks + 20 + 100000 /tmp /tmp 10 - 0.0.0.0 - 128M - 10 + 128M + 10 /tmp/infinidb_tmp_files $INSTALLDIR - 10 - 120 - restartSystem - n - 95 - OFF - - /tmp/rdwrscratch dm @@ -272,60 +65,60 @@ 0.0.0.0 unassigned ENABLED - 0 - 0 - 0 - 0 + 90 + 80 + 70 + 60 90 80 70 90 - 0 - 0 + 80 + 70 90 80 70 / - unassigned - unassigned + 0 + 0 um User Module - SIMPLEX - 1 + LOADSHARE + 0 0.0.0.0 unassigned ENABLED - 0 - 0 - 0 - 0 + 90 + 80 + 70 + 60 90 80 70 90 - 0 - 0 + 80 + 70 90 80 70 / - unassigned - unassigned + 0 + 0 pm Performance Module SIMPLEX 1 - 0.0.0.0 - unassigned + 127.0.0.1 + localhost ENABLED - 0 - 0 - 0 - 0 + 90 + 80 + 70 + 60 90 80 70 - 90 + 0 0 0 90 @@ -343,86 +136,38 @@ 1000 + $INSTALLDIR/data1/systemFiles/dbrm/CalpontShm $INSTALLDIR/data1/systemFiles/dbrm/SMTxnID + + $INSTALLDIR/data1/systemFiles/dbrm/CalpontSessionMonitorShm + 10 + - 1GB - $INSTALLDIR/data1/systemFiles/dbrm/oidbitmap - 3000 $INSTALLDIR/data/bulk - $INSTALLDIR/data1/systemFiles/bulkRollback + $INSTALLDIR/data/bulk/rollback 98 - 1 1 - 0.0.0.0 + 127.0.0.1 8616 - - 0.0.0.0 + 127.0.0.1 8700 - unassigned + pm1 - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - 0.0.0.0 - 8700 - unassigned - - - - - 1 + 66 + 0 0 65536 @@ -432,83 +177,36 @@ n - n - n + y 2 - n - n internal - internal - rpm - unassigned - unassigned - unassigned - unassigned - unassigned - us-east-1 - unassigned - unassigned - unassigned - y - unassigned - unassigned - unassigned - unassigned - unassigned - n - 0 - unassigned - unassigned - n - 0 - unassigned - n - unassigned - unassigned - 3306 - - 4 + 4 2 0x0 128 - 128K + 128K 128 - 64M - 50% - 10% + 64M + 8G 100 - N - - $INSTALLDIR/tmp - Y 16K 32 - 1 - - - 20 + 1 + 1 + + - 1M - 1M - 512 + 1M + 1M + 512 @@ -521,18 +219,4 @@ unassigned - - N - - - N - - - Y - - - 127.0.0.1 - 0 - - diff --git a/oam/etc/Calpont.xml.singleserver b/oam/etc/Calpont.xml.singleserver index f8459608..098df13c 100644 --- a/oam/etc/Calpont.xml.singleserver +++ b/oam/etc/Calpont.xml.singleserver @@ -4,7 +4,6 @@ 127.0.0.1 8601 - pm1 0.0.0.0 @@ -82,7 +81,6 @@ - 95 127.0.0.1 @@ -244,12 +242,6 @@ 120 restartSystem n - 95 - OFF - - /tmp/rdwrscratch dm @@ -277,7 +269,7 @@ unassigned um User Module - SIMPLEX + LOADSHARE 0 0.0.0.0 unassigned @@ -415,7 +407,7 @@ - 50 + 66 1 0 @@ -430,33 +422,24 @@ y y 2 - n - n internal internal unassigned unassigned - unassigned + n rpm y unassigned unassigned us-east-1 unassigned - unassigned - unassigned unassigned unassigned unassigned unassigned unassigned + n n - 0 - unassigned - unassigned - n - unassigned - unassigned 128 64M - 25% - 10% + 8G 100 - N - - $INSTALLDIR/tmp - Y 16K @@ -512,17 +488,4 @@ unassigned - - N - - - N - - - Y - - - 127.0.0.1 - 0 - diff --git a/oam/etc/ConsoleCmds.xml b/oam/etc/ConsoleCmds.xml index 7c672569..0ac01f14 100644 --- a/oam/etc/ConsoleCmds.xml +++ b/oam/etc/ConsoleCmds.xml @@ -97,17 +97,17 @@ addDbroot - Add DBRoot Disk storage to the InfiniDB System + Add DBRoot Disk storage to the Calpont InfiniDB System Required: Number of DBRoots to be added removeDbroot - Remove DBRoot Disk storage from the InfiniDB System + Remove DBRoot Disk storage from the Calpont InfiniDB System Required: List of Dbroot IDs to be removed stopSystem - Stops the processing of the InfiniDB System + Stops the processing of the Calpont InfiniDB System It will leave the Modules powered on and the Operating Systems enable This command might be used for Software Maintenance reasons Optional: GRACEFUL/FORCEFUL is the mode the process will be taken down. Default is FORCEFUL @@ -115,21 +115,21 @@ shutdownSystem - Shuts down the InfiniDB System - This command stops the processing of applications on all Modules within the InfiniDB System + Shuts down the Calpont InfiniDB System + This command stops the processing of applications on all Modules within the Calpont InfiniDB System It should be using when performing an upgrade Optional: GRACEFUL/FORCEFUL is the mode the process will be taken down. Default is FORCEFUL Optional: ACK_YES/ACK_NO is Acknowledgment response or not. Default is ACK_YES startSystem - Starts a stopped or shutdown InfiniDB System + Starts a stopped or shutdown Calpont InfiniDB System If system is shutdown, then a server root password should be entered if a ssh key is not defined Optional: Server-root-password restartSystem - Restarts a stopped or shutdown InfiniDB System + Restarts a stopped or shutdown Calpont InfiniDB System If system is shutdown, then a server root password should be entered if a ssh key is not defined Optional: GRACEFUL/FORCEFUL is the mode the process will be taken down. Default is FORCEFUL Optional: ACK_YES/ACK_NO is Acknowledgment response or not. Default is ACK_YES @@ -138,13 +138,13 @@ getSystemStatus Get System and Modules Status - Get Status of the InfiniDB System and the modules within the InfiniDB Appliance + Get Status of the Calpont InfiniDB System and the modules within the Calpont InfiniDB Appliance None getProcessStatus - Get InfiniDB Process Statuses - Get Status of the InfiniDB Processes witin the InfiniDB System + Get Calpont InfiniDB Process Statuses + Get Status of the Calpont InfiniDB Processes witin the Calpont InfiniDB System None @@ -195,7 +195,7 @@ getStorageStatus Get System Storage Status - Get Status of the InfiniDB DBRoot Storages within the InfiniDB Appliance + Get Status of the Calpont InfiniDB DBRoot Storages within the Calpont InfiniDB Appliance Only Valid for External Configured disk None @@ -214,20 +214,16 @@ suspendDatabaseWrites - Suspend performing writes to the InfiniDB Database + Suspend performing writes to the Calpont InfiniDB Database None resumeDatabaseWrites - Resume performing writes to the InfiniDB Database + Resume performing writes to the Calpont InfiniDB Database None - unassignDbrootPmConfig - Unassign DBroots from a Performance Module - This command could be used before a DBRoot is removed - Required: List of Dbroot IDs to be unassigned - Required: Performance Module Name + AVAILABLE assignDbrootPmConfig @@ -304,14 +300,14 @@ getCalpontSoftwareInfo - Get the InfiniDB RPM detailed information + Get the Calpont InfiniDB RPM detailed information None addModule - Add a Module within the InfiniDB System + Add a Module within the Calpont InfiniDB System This command is used to configure a Module to the Configuration - Database within the InfiniDB System. It will also install the + Database within the Calpont InfiniDB System. It will also install the Calpont InfiniDB Packages and setup the module to make it ready to be restored Required: Module-type or Module-name being added Required: Number-of-Modules being added when Module-type is specified @@ -320,16 +316,14 @@ removeModule - Remove a Module within the InfiniDB System + Remove a Module within the Calpont InfiniDB System This command is used to unconfigure a Module from the Configuration - Database within the InfiniDB System + Database within the Calpont InfiniDB System Required: Module-type or Module-name being removed Required: Number-of-Modules being remove when Module-type is specified - getModuleHostNames - Get a list of Module host names (NIC 1 only) - Optional: um or pm + AVAILABLE AVAILABLE @@ -412,16 +406,16 @@ alterSystem-disableModule - Disable a Module and Alter the InfiniDB System + Disable a Module and Alter the Calpont InfiniDB System This command is used to place a Module in an disable state - and restart the associated processes the InfiniDB System. + and restart the associated processes the Calpont InfiniDB System. Required: Module-name(s) being placed disable alterSystem-enableModule - Enable a Module and Alter the InfiniDB System + Enable a Module and Alter the Calpont InfiniDB System This command is used to place a Module in an enable state - and restart the associated processes the InfiniDB System. + and restart the associated processes the Calpont InfiniDB System. Required: Module-name(s) being placed enable diff --git a/oam/etc/Makefile.am b/oam/etc/Makefile.am index 98f3f45a..eedfe6c7 100644 --- a/oam/etc/Makefile.am +++ b/oam/etc/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. dist_sysconf_DATA = AlarmConfig.xml Calpont.xml ProcessConfig.xml ConsoleCmds.xml Calpont.xml.singleserver ProcessConfig.xml.singleserver diff --git a/oam/etc/Makefile.in b/oam/etc/Makefile.in index 89b8e362..ddd03201 100644 --- a/oam/etc/Makefile.in +++ b/oam/etc/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -57,9 +57,8 @@ subdir = oam/etc DIST_COMMON = $(dist_sysconf_DATA) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/oam/etc/ProcessConfig.xml b/oam/etc/ProcessConfig.xml index 118a852f..ca0b1a54 100644 --- a/oam/etc/ProcessConfig.xml +++ b/oam/etc/ProcessConfig.xml @@ -1,5 +1,5 @@ - + ProcessMonitor @@ -102,7 +102,7 @@ DecomSvr pm - /$INSTALLDIR/bin/DecomSvr + $INSTALLDIR/bin/DecomSvr 2 15 @@ -140,9 +140,9 @@ off - DDLProc + DMLProc um - $INSTALLDIR/bin/DDLProc + $INSTALLDIR/bin/DMLProc 2 50 WriteEngineServer @@ -150,22 +150,20 @@ DBRMWorkerNode * ExeMgr - * + um* SIMPLEX off - DMLProc + DDLProc um - $INSTALLDIR/bin/DMLProc + $INSTALLDIR/bin/DDLProc 2 51 WriteEngineServer pm* DBRMWorkerNode * - DDLProc - @ SIMPLEX off diff --git a/oam/etc/ProcessConfig.xml.singleserver b/oam/etc/ProcessConfig.xml.singleserver index ec46cb75..43a4867d 100644 --- a/oam/etc/ProcessConfig.xml.singleserver +++ b/oam/etc/ProcessConfig.xml.singleserver @@ -27,16 +27,16 @@ /usr/local/Calpont/sbin/snmptrapd /usr/local/Calpont/sbin/snmptrapd -M - /usr/local/Calpont/share/snmp/mibs - -m - /usr/local/Calpont/share/snmp/mibs/CALPONT-MIB.txt - -c - /usr/local/Calpont/etc/snmptrapd.conf - -C - -Lf - /var/log/Calpont/snmptrapd.log - -p - /var/run/snmptrapd.pid + /usr/local/Calpont/share/snmp/mibs + -m + /usr/local/Calpont/share/snmp/mibs/CALPONT-MIB.txt + -c + /usr/local/Calpont/etc/snmptrapd.conf + -C + -Lf + /var/log/Calpont/snmptrapd.log + -p + /var/run/snmptrapd.pid 1 3 ProcessManager @@ -140,9 +140,9 @@ off - DDLProc + DMLProc um - $INSTALLDIR/bin/DDLProc + /usr/local/Calpont/bin/DMLProc 2 50 WriteEngineServer @@ -150,33 +150,33 @@ DBRMWorkerNode * ExeMgr - um* + pm* + DDLProc + pm* SIMPLEX off - DMLProc + DDLProc um - $INSTALLDIR/bin/DMLProc + /usr/local/Calpont/bin/DDLProc 2 51 WriteEngineServer pm* DBRMWorkerNode * - DDLProc - @ SIMPLEX off mysqld pm - /usr/local/Calpont/mysql/libexe/mysqld + /usr/local/Calpont/mysql/libexec/mysqld 0 100 LOADSHARE off - + diff --git a/oam/install_scripts/Makefile.am b/oam/install_scripts/Makefile.am index 65792ab6..36f3b96e 100644 --- a/oam/install_scripts/Makefile.am +++ b/oam/install_scripts/Makefile.am @@ -1,29 +1,26 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -bin_SCRIPTS = post-install pre-uninstall remote_command.sh \ -calpontLogRotate transactionLog transactionLogArchiver.sh system_installer.sh \ -module_installer.sh patch_installer.sh xm_installer.sh startupTests.sh \ -director_installer.sh user_installer.sh performance_installer.sh \ -remote_scp_get.sh calpontAlias run.sh upgrade-infinidb.sh \ -post-mysql-install post-mysqld-install binary_installer.sh \ -os_check.sh infinidb calpontSyslog calpontSyslog-ng syslogSetup.sh \ -remote_scp_put.sh calpontUninstall.sh infinidb.def \ -remotessh.exp rsync.sh remote_command_verify.sh +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +bin_SCRIPTS = post-install pre-uninstall \ +calpontLogRotate transactionLog transactionLogArchiver.sh \ +startupTests.sh upgrade-infinidb.sh \ +infinidb install-infinidb.sh calpontAlias run.sh \ +post-mysql-install post-mysqld-install os_check.sh \ +calpontSyslog calpontSyslog-ng syslogSetup.sh infinidb.def dist_local_DATA = module diff --git a/oam/install_scripts/Makefile.in b/oam/install_scripts/Makefile.in index 1f07e08b..5311f658 100644 --- a/oam/install_scripts/Makefile.in +++ b/oam/install_scripts/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. srcdir = @srcdir@ @@ -58,9 +58,8 @@ subdir = oam/install_scripts DIST_COMMON = $(dist_local_DATA) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -139,9 +138,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -183,7 +179,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -197,11 +192,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -212,15 +202,12 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ -bin_SCRIPTS = post-install pre-uninstall remote_command.sh \ -calpontLogRotate transactionLog transactionLogArchiver.sh system_installer.sh \ -module_installer.sh patch_installer.sh xm_installer.sh startupTests.sh \ -director_installer.sh user_installer.sh performance_installer.sh \ -remote_scp_get.sh calpontAlias run.sh upgrade-infinidb.sh \ -post-mysql-install post-mysqld-install binary_installer.sh \ -os_check.sh infinidb calpontSyslog calpontSyslog-ng syslogSetup.sh \ -remote_scp_put.sh calpontUninstall.sh infinidb.def \ -remotessh.exp rsync.sh remote_command_verify.sh +bin_SCRIPTS = post-install pre-uninstall \ +calpontLogRotate transactionLog transactionLogArchiver.sh \ +startupTests.sh upgrade-infinidb.sh \ +infinidb install-infinidb.sh calpontAlias run.sh \ +post-mysql-install post-mysqld-install os_check.sh \ +calpontSyslog calpontSyslog-ng syslogSetup.sh infinidb.def dist_local_DATA = module all: all-am diff --git a/oam/install_scripts/binary_installer.sh b/oam/install_scripts/binary_installer.sh index 6aa4fe1a..d875fe04 100644 --- a/oam/install_scripts/binary_installer.sh +++ b/oam/install_scripts/binary_installer.sh @@ -22,17 +22,16 @@ set MODULETYPE [lindex $argv 4] set INSTALLTYPE [lindex $argv 5] set PKGTYPE "binary" set SERVERTYPE [lindex $argv 6] -set MYSQLPORT [lindex $argv 7] -set DEBUG [lindex $argv 8] +set DEBUG [lindex $argv 7] set INSTALLDIR "/usr/local/Calpont" -set IDIR [lindex $argv 9] +set IDIR [lindex $argv 8] if { $IDIR != "" } { set INSTALLDIR $IDIR } set env(INFINIDB_INSTALL_DIR) $INSTALLDIR set PREFIX [file dirname $INSTALLDIR] set USERNAME $env(USER) -set UNM [lindex $argv 10] +set UNM [lindex $argv 9] if { $UNM != "" } { set USERNAME $UNM } @@ -53,27 +52,27 @@ if { $INSTALLTYPE == "initial" || $INSTALLTYPE == "uninstall" } { send_user "Uninstall Calpont Package " send " \n" send date\n - send "ssh $USERNAME@$SERVER 'rm -f /etc/init.d/infinidb /etc/init.d/mysql-Calpont $INSTALLDIR/releasenum >/dev/null 2>&1'\n" + send "ssh $USERNAME@$SERVER 'test -x $INSTALLDIR/bin/pre-uninstall && $INSTALLDIR/bin/pre-uninstall --installdir=$INSTALLDIR; rm -f /etc/init.d/infinidb /etc/init.d/mysql-Calpont $INSTALLDIR/releasenum >/dev/null 2>&1'\n" set timeout 20 expect { - "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1} - "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1} - "authenticity" { send "yes\n" + -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1} + -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1} + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } - "Calpont uninstall completed" { send_user "DONE" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "Calpont uninstall completed" { send_user "DONE" } abort } set timeout 30 expect { - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Calpont uninstall completed" { send_user "DONE" } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Calpont uninstall completed" { send_user "DONE" } abort } send_user "\n" } @@ -90,21 +89,21 @@ send date\n send "scp $CALPONTPKG $USERNAME@$SERVER:$CALPONTPKG\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 120 expect { - "100%" { send_user "DONE" } - "scp:" { send_user "ERROR\n" ; + -re "100%" { send_user "DONE" } abort + -re "scp:" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } timeout { send_user "ERROR: Timeout\n" ; exit 1 } } send_user "\n" @@ -119,18 +118,18 @@ send date\n send "ssh $USERNAME@$SERVER 'tar -C $PREFIX --exclude db -zxf $CALPONTPKG;cat $INSTALLDIR/releasenum'\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 120 expect { - "release=" { send_user "DONE" } - "No such file" { send_user "ERROR: Binary Install Failed, binary/releasenum not found\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "release=" { send_user "DONE" } abort + -re "No such file" { send_user "ERROR: Binary Install Failed, binary/releasenum not found\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } timeout { send_user "ERROR: Timeout\n" ; exit 1 } } #sleep to give time for cat Calpont/releasenum to complete @@ -143,19 +142,19 @@ send date\n send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-install --installdir=$INSTALLDIR'\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 60 # check return expect { - "InfiniDB syslog logging not working" { send_user "ERROR: InfiniDB System logging not setup\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } - "postConfigure" { send_user "DONE" } + -re "InfiniDB syslog logging not working" { send_user "ERROR: InfiniDB System logging not setup\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "postConfigure" { send_user "DONE" } abort } send_user "\n" sleep 10 @@ -170,17 +169,17 @@ if { $INSTALLTYPE == "initial"} { send "scp $INSTALLDIR/etc/* $USERNAME@$SERVER:$INSTALLDIR/etc\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 30 expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "#|$" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" # @@ -192,17 +191,17 @@ if { $INSTALLTYPE == "initial"} { send "scp -r $INSTALLDIR/local/etc $USERNAME@$SERVER:$INSTALLDIR/local\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 60 expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "#|$" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" # @@ -214,17 +213,17 @@ if { $INSTALLTYPE == "initial"} { send "scp $INSTALLDIR/local/etc/$MODULE/* $USERNAME@$SERVER:$INSTALLDIR/local\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} } set timeout 60 expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "#|$" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" # @@ -233,26 +232,25 @@ if { $INSTALLTYPE == "initial"} { send_user "Run Module Installer " send " \n" send date\n - send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/module_installer.sh --module=$MODULETYPE --port=$MYSQLPORT --installdir=$INSTALLDIR $MODULETYPE'\n" + send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/module_installer.sh --installdir=$INSTALLDIR $MODULETYPE'\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 60 expect { - "!!!Module" { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "FAILED" { send_user "ERROR: missing module file\n" ; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } - "No such file" { send_user "ERROR: File Not Found\n" ; exit 1 } + -re "!!!Module" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "FAILED" { send_user "ERROR: missing module file\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" sleep 10 - if { $MODULETYPE == "um" || $SERVERTYPE == "2" || $SERVERTYPE == "pmwithum" } { + if { $MODULETYPE == "um" || $SERVERTYPE == "2" } { # # run mysql setup scripts # @@ -262,41 +260,41 @@ if { $INSTALLTYPE == "initial"} { send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-mysqld-install --installdir=$INSTALLDIR'\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 60 expect { - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit 1 } - "FAILED" { send_user "ERROR: Daemon failed to run"; + -re "FAILED" { send_user "ERROR: Daemon failed to run"; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } - + # send " \n" send date\n send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-mysql-install --installdir=$INSTALLDIR'\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 60 expect { - "Shutting down mysql." { send_user "DONE" } - timeout { send_user "DONE" } - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "Shutting down mysql." { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit 1 } - "FAILED" { send_user "ERROR: Daemon failed to run"; + -re "FAILED" { send_user "ERROR: Daemon failed to run"; exit 1 } - "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" } @@ -311,20 +309,21 @@ send date\n send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/syslogSetup.sh check'\n" set timeout 10 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } set timeout 30 expect { - "Logging working" { send_user "DONE" } - timeout { send_user "DONE" } - "not working" { send_user "WARNING: InfiniDB system logging functionality not working" } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "Logging working" { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "not working" { send_user "WARNING: InfiniDB system logging functionality not working" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" +# send_user "\nInstallation Successfully Completed on '$MODULE'\n" exit 0 diff --git a/oam/install_scripts/calpontAlias b/oam/install_scripts/calpontAlias index b19fcb96..510306a5 100644 --- a/oam/install_scripts/calpontAlias +++ b/oam/install_scripts/calpontAlias @@ -1,13 +1,6 @@ -# InfiniDB Alias Commands +#! /bin/bash +# +# $Id: calpontAlias.os 2265 2011-03-03 16:41:47Z dhill $ # alias idbmysql='/usr/local/Calpont/mysql/bin/mysql --defaults-file=/usr/local/Calpont/mysql/my.cnf -u root' -alias cc=/usr/local/Calpont/bin/calpontConsole -alias cmconsole=/usr/local/Calpont/bin/calpontConsole -alias home='cd /usr/local/Calpont/' -alias log='cd /var/log/Calpont/' -alias core='cd /var/log/Calpont/corefiles' -alias tmsg='tail -f /var/log/messages' -alias tdebug='tail -f /var/log/Calpont/debug.log' -alias tinfo='tail -f /var/log/Calpont/info.log' -alias dbrm='cd /usr/local/Calpont/data1/systemFiles/dbrm' -alias module='cat /usr/local/Calpont/local/module' + diff --git a/oam/install_scripts/calpontInstall.sh b/oam/install_scripts/calpontInstall.sh index 57e80c5d..851f0445 100755 --- a/oam/install_scripts/calpontInstall.sh +++ b/oam/install_scripts/calpontInstall.sh @@ -72,7 +72,7 @@ log_user $DEBUG set timeout 2 send "$INSTALLDIR/bin/infinidb status\n" expect { - "is running" { puts "InfiniDB is running, can't run calpontInstall.sh while InfiniDB is running. Exiting..\n"; + -re "is running" { puts "InfiniDB is running, can't run calpontInstall.sh while InfiniDB is running. Exiting..\n"; exit 1 } } @@ -93,9 +93,9 @@ set timeout 2 set INSTALL 2 send "$INSTALLDIR/bin/getConfig DBRM_Controller NumWorkers\n" expect { - 1 { set INSTALL 1 + -re 1 { set INSTALL 1 set PASSWORD "dummy" - set RPMVERSION "rpm" } + set RPMVERSION "rpm" } abort } @@ -107,34 +107,32 @@ send_user "\n" if { $INSTALL == "2" } { if { $PACKAGE == "rpm" } { - set CALPONTPACKAGE1 /root/infinidb-libs-$RPMVERSION*.rpm - set CALPONTPACKAGE2 /root/infinidb-platform-$RPMVERSION*.rpm - set CALPONTPACKAGE3 /root/infinidb-enterprise-$RPMVERSION*.rpm - set CONNECTORPACKAGE1 /root/infinidb-mysql-$RPMVERSION*.rpm - set CONNECTORPACKAGE2 /root/infinidb-storage-engine-$RPMVERSION*.rpm - send_user "Installing InfiniDB Packages: $CALPONTPACKAGE1, $CALPONTPACKAGE2, $CALPONTPACKAGE3, $CONNECTORPACKAGE1, $CONNECTORPACKAGE2\n\n" + set CALPONTPACKAGE /root/calpont-$RPMVERSION*.rpm + set CONNECTORPACKAGE1 /root/calpont-mysql-$RPMVERSION*.rpm + set CONNECTORPACKAGE2 /root/calpont-mysqld-$RPMVERSION*.rpm + send_user "Installing InfiniDB Packages: $CALPONTPACKAGE, $CONNECTORPACKAGE1, $CONNECTORPACKAGE2\n\n" set EEPKG "rpm" - } elseif { $PACKAGE == "deb" } { - set CALPONTPACKAGE1 /root/infinidb-libs_$RPMVERSION*.deb - set CALPONTPACKAGE2 /root/infinidb-platform_$RPMVERSION*.deb - set CALPONTPACKAGE3 /root/infinidb-enterprise_$RPMVERSION*.deb - set CONNECTORPACKAGE1 /root/infinidb-mysql_$RPMVERSION*.deb - set CONNECTORPACKAGE2 /root/infinidb-storage-engine_$RPMVERSION*.deb - send_user "Installing InfiniDB Packages: $CALPONTPACKAGE1, $CALPONTPACKAGE2, $CALPONTPACKAGE3, $CONNECTORPACKAGE1, $CONNECTORPACKAGE2\n\n" - set EEPKG "deb" - } elseif { $PACKAGE == "binary" } { - set CALPONTPACKAGE /root/infinidb-ent-$RPMVERSION*bin.tar.gz - set CONNECTORPACKAGE1 "nopkg" - set CONNECTORPACKAGE2 "nopkg" - send_user "Installing InfiniDB Package: $CALPONTPACKAGE\n\n" - set EEPKG "binary" - } else { - puts "please enter Valid Package Type, enter ./calpontInstaller.sh -h for additional info"; exit 1 + } else { + if { $PACKAGE == "deb" } { + set CALPONTPACKAGE /root/calpont_$RPMVERSION*.deb + set CONNECTORPACKAGE1 /root/calpont-mysql_$RPMVERSION*.deb + set CONNECTORPACKAGE2 /root/calpont-mysqld_$RPMVERSION*.deb + send_user "Installing InfiniDB Packages: $CALPONTPACKAGE, $CONNECTORPACKAGE1, $CONNECTORPACKAGE2\n\n" + set EEPKG "deb" + } else { + if { $PACKAGE == "binary" } { + set CALPONTPACKAGE /root/calpont-infinidb-ent-$RPMVERSION*bin.tar.gz + set CONNECTORPACKAGE1 "nopkg" + set CONNECTORPACKAGE2 "nopkg" + send_user "Installing InfiniDB Package: $CALPONTPACKAGE\n\n" + set EEPKG "binary" + } else { + puts "please enter Valid Package Type, enter ./calpontInstaller.sh -h for additional info"; exit 1 + } + } } } else { - set CALPONTPACKAGE1 "dummy.rpm" - set CALPONTPACKAGE2 "dummy.rpm" - set CALPONTPACKAGE3 "dummy.rpm" + set CALPONTPACKAGE "dummy.rpm" set CONNECTORPACKAGE1 "dummy.rpm" set CONNECTORPACKAGE2 "dummy.rpm" set EEPKG "rpm" @@ -144,7 +142,7 @@ send_user "Performing InfiniDB System Install, please wait...\n" send "$INSTALLDIR/bin/setConfig -d Installation EEPackageType $EEPKG\n" expect { - -re {[$#] } { } + -re "# " { } abort } send_user "\n" @@ -152,16 +150,14 @@ set timeout 600 # # Run installer # -send "$INSTALLDIR/bin/installer $CALPONTPACKAGE1 $CALPONTPACKAGE2 $CALPONTPACKAGE3 $CONNECTORPACKAGE1 $CONNECTORPACKAGE2 initial $PASSWORD n $NODEPS $MYSQLPASSWORD $DEBUG\n" +send "$INSTALLDIR/bin/installer $CALPONTPACKAGE $CONNECTORPACKAGE1 $CONNECTORPACKAGE2 initial $PASSWORD n $NODEPS $MYSQLPASSWORD $DEBUG\n" expect { - "InfiniDB Install Successfully Completed" { } - "ERROR" { send_user "FAILED: error returned from installer, execute with debug mode on to determine error\n" ; exit 1 } - "Enter MySQL password" { send_user "FAILED: a MySQL password is set\n" ; exit 1 } + -re "InfiniDB Install Successfully Completed" { } abort + -re "ERROR" { send_user "FAILED: error returned from installer, execute with debug mode on to determine error\n" ; exit 1 } + -re "Enter MySQL password" { send_user "FAILED: a MySQL password is set\n" ; exit 1 } timeout { send_user "FAILED: Timeout while running installer, execute with debug mode on to determine error\n" ; exit 1 } } send_user "\nCalpont Package System Install Completed\n\n" exit 0 -# vim:ts=4 sw=4: - diff --git a/oam/install_scripts/calpontLogRotate b/oam/install_scripts/calpontLogRotate index 48dec838..b6ae207c 100644 --- a/oam/install_scripts/calpontLogRotate +++ b/oam/install_scripts/calpontLogRotate @@ -25,11 +25,17 @@ copy olddir /usr/local/Calpont/etc/ } +/var/log/Calpont/prat/pslog { + missingok + rotate 7 + daily + copytruncate +} /usr/local/Calpont/mysql/db/*.err { missingok rotate 7 daily dateext copytruncate - olddir /usr/local/Calpont/mysql/db + olddir /usr/local/Calpont/mysql/db/archive } diff --git a/oam/install_scripts/calpontSyslog b/oam/install_scripts/calpontSyslog index 8bc56eb3..6b8937b6 100644 --- a/oam/install_scripts/calpontSyslog +++ b/oam/install_scripts/calpontSyslog @@ -1,7 +1,7 @@ # Calpont Database Platform Logging -local1.=crit -/var/log/Calpont/crit.log -local1.=err -/var/log/Calpont/err.log -local1.=warning -/var/log/Calpont/warning.log -local1.=info -/var/log/Calpont/info.log -local1.=debug -/var/log/Calpont/debug.log -local2.=crit -/var/log/Calpont/data/data_mods.log +local1.=crit /var/log/Calpont/crit.log +local1.=err /var/log/Calpont/err.log +local1.=warning /var/log/Calpont/warning.log +local1.=info /var/log/Calpont/info.log +local1.=debug /var/log/Calpont/debug.log +local2.=crit /var/log/Calpont/data/data_mods.log diff --git a/oam/install_scripts/calpontUninstall.sh b/oam/install_scripts/calpontUninstall.sh index e13bdf8a..9ffcedc4 100755 --- a/oam/install_scripts/calpontUninstall.sh +++ b/oam/install_scripts/calpontUninstall.sh @@ -11,11 +11,9 @@ set USERNAME $env(USER) set PASSWORD " " set DEBUG 0 -set INFINIDBRPM1 "infinidb-libs" -set INFINIDBRPM2 "infinidb-platform" -set INFINIDBRPM3 "infinidb-enterprise" -set CONNECTORRPM1 "infinidb-mysql" -set CONNECTORRPM2 "infinidb-storage-engine" +set CALPONTRPM "calpont" +set CONNECTORRPM1 "calpont-mysql" +set CONNECTORRPM2 "calpont-mysqld" spawn -noecho /bin/bash @@ -57,15 +55,15 @@ set timeout 2 set INSTALL 2 send "$INFINIDB_INSTALL_DIR/bin/getConfig DBRM_Controller NumWorkers\n" expect { - 1 { set INSTALL 1 } + -re 1 { set INSTALL 1 } abort } set PACKAGE "rpm" send "$INFINIDB_INSTALL_DIR/bin/getConfig Installation EEPackageType\n" expect { - rpm { set PACKAGE rpm } - deb { set PACKAGE deb } - binary { set PACKAGE binary } + -re rpm { set PACKAGE rpm } abort + -re deb { set PACKAGE deb } abort + -re binary { set PACKAGE binary } abort } set timeout 60 @@ -78,10 +76,10 @@ send_user "\nPerforming InfiniDB System Uninstall\n\n" # shutdownSystem # send_user "Shutdown InfiniDB System " -expect -re {[$#] } +expect -re "# " send "$INFINIDB_INSTALL_DIR/bin/calpontConsole shutdownsystem y\n" expect { - "shutdownSystem " { send_user "DONE" } + -re "shutdownSystem " { send_user "DONE" } abort } send_user "\n" @@ -92,10 +90,10 @@ if { $INSTALL == "2"} { # Run installer # send_user "Run System Uninstaller " - send "$INFINIDB_INSTALL_DIR/bin/installer $INFINIDBRPM1 $INFINIDBRPM2 $INFINIDBRPM3 $CONNECTORRPM1 $CONNECTORRPM2 uninstall $PASSWORD n --nodeps dummymysqlpw $DEBUG\n" + send "$INFINIDB_INSTALL_DIR/bin/installer $CALPONTRPM $CONNECTORRPM1 $CONNECTORRPM2 uninstall $PASSWORD n --nodeps dummymysqlpw $DEBUG\n" expect { - "uninstall request successful" { send_user "DONE" } - "ERROR" { send_user "FAILED" ; exit -1 } + -re "uninstall request successful" { send_user "DONE" } abort + -re "ERROR" { send_user "FAILED" ; exit -1 } } send_user "\n" } @@ -103,7 +101,7 @@ if { $INSTALL == "2"} { if { $PACKAGE == "binary" } { send "$INFINIDB_INSTALL_DIR/bin/pre-uninstall\n" expect { - -re {[$#] } { } + -re "# " { } abort } send_user "\n" diff --git a/oam/install_scripts/dbhealth.sh b/oam/install_scripts/dbhealth.sh new file mode 100644 index 00000000..089c9d99 --- /dev/null +++ b/oam/install_scripts/dbhealth.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# +# $Id$ +# +# generic InfiniDB Health Test script. +# +# Notes: This script can be run at varies times t check the system DB health state +# + +if [ -z "$INFINIDB_INSTALL_DIR" ]; then + INFINIDB_INSTALL_DIR=/usr/local/Calpont +fi + +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR + +pwprompt=" " +for arg in "$@"; do + if [ `expr -- "$arg" : '--installdir='` -eq 13 ]; then + installdir="`echo $arg | awk -F= '{print $2}'`" + elif [ `expr -- "$arg" : '--password='` -eq 11 ]; then + password="`echo $arg | awk -F= '{print $2}'`" + pwprompt="--password=$password" + fi +done + +test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/functions + +$INFINIDB_INSTALL_DIR/mysql/bin/mysql \ + --defaults-file=$INFINIDB_INSTALL_DIR/mysql/my.cnf \ + --user=root $pwprompt \ + --execute="source $INFINIDB_INSTALL_DIR/bin/dbhealth.sql;" > /tmp/dbhealthTest.log 2>&1 + +grep OK /tmp/dbhealthTest.log > /tmp/error.check +if [ `cat /tmp/error.check | wc -c` -eq 0 ]; then + echo "System Health Test Failed, check /tmp/dbhealthTest.log" + rm -f /tmp/error.check + exit 1; +fi + +echo "OK" +echo "System Health Test Passed" + +rm -f /tmp/error.check + +exit 0 diff --git a/oam/install_scripts/dbhealth.sql b/oam/install_scripts/dbhealth.sql new file mode 100644 index 00000000..4663520c --- /dev/null +++ b/oam/install_scripts/dbhealth.sql @@ -0,0 +1,18 @@ +create database if not exists oamtest; +use oamtest + +-- Create a table with a tinyint. +create table if not exists tmp(c1 tinyint)engine=infinidb; + +-- Insert +insert into tmp values (1); + +-- Select +select * from tmp; + +-- Trucate and drop table +truncate table tmp; +drop table tmp; + +-- NEEDED for good status return +select "OK"; diff --git a/oam/install_scripts/director_installer.sh b/oam/install_scripts/director_installer.sh index 6ccb8c98..b35e668e 100755 --- a/oam/install_scripts/director_installer.sh +++ b/oam/install_scripts/director_installer.sh @@ -13,20 +13,18 @@ set timeout 10 set MODULE [lindex $argv 0] set SERVER [lindex $argv 1] set PASSWORD [lindex $argv 2] -set CALPONTRPM1 [lindex $argv 3] -set CALPONTRPM2 [lindex $argv 4] -set CALPONTRPM3 [lindex $argv 5] -set CALPONTMYSQLRPM [lindex $argv 6] -set CALPONTMYSQLDRPM [lindex $argv 7] -set INSTALLTYPE [lindex $argv 8] -set DEBUG [lindex $argv 9] +set CALPONTRPM [lindex $argv 3] +set CALPONTMYSQLRPM [lindex $argv 4] +set CALPONTMYSQLDRPM [lindex $argv 5] +set INSTALLTYPE [lindex $argv 6] +set DEBUG [lindex $argv 7] set INSTALLDIR "/usr/local/Calpont" -set IDIR [lindex $argv 10] +set IDIR [lindex $argv 8] if { $IDIR != "" } { set INSTALLDIR $IDIR } set USERNAME "root" -set UNM [lindex $argv 11] +set UNM [lindex $argv 9] if { $UNM != "" } { set USERNAME $UNM } @@ -36,274 +34,352 @@ spawn -noecho /bin/bash # if { $INSTALLTYPE == "initial" || $INSTALLTYPE == "uninstall" } { # - # erase InfiniDB MySQL storage engine package + # erase Calpont-MySql package # - send_user "Erase InfiniDB MySQL Storage Engine Package on Module " - expect -re {[$#] } - send "ssh $USERNAME@$SERVER 'rpm -e --nodeps --allmatches calpont-mysql >/dev/null 2>&1; rpm -e --nodeps --allmatches infinidb-storage-engine'\n" + send_user "Erase Calpont-Mysql Package on Module " + expect -re "# " + send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches calpont-mysql'\n" expect { - "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit } - "service not known" { send_user "FAILED: Invalid Host\n" ; exit } - "authenticity" { send "yes\n" + -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit } + -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit } + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort } } - "word: " { send "$PASSWORD\n" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "word: " { send "$PASSWORD\n" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } # password for ssh send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "uninstall completed" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "not installed" { send_user "INFO: Package not installed" } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "not installed" { send_user "INFO: Package not installed" } abort } send_user "\n" # - # erase InfiniDB MySQL package + # erase Calpont-MySqld package # - send_user "Erase InfiniDB MySQL Package on Module " - expect -re {[$#] } - send "ssh $USERNAME@$SERVER 'rpm -e --nodeps --allmatches calpont-mysqld >/dev/null 2>&1; rpm -e --nodeps --allmatches infinidb-mysql'\n" - expect "word: " + send_user "Erase Calpont-Mysqld Package on Module " + expect -re "# " + send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches calpont-mysqld'\n" + expect -re "word: " # password for ssh send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "uninstall completed" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "not installed" { send_user "INFO: Package not installed" } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "not installed" { send_user "INFO: Package not installed" } abort } send_user "\n" # - # erase InfiniDB packages + # erase Calpont package # - send_user "Erase InfiniDB Packages on Module " - expect -re {[$#] } - send "ssh $USERNAME@$SERVER 'rpm -e --nodeps --allmatches calpont >/dev/null 2>&1; rpm -e --nodeps --allmatches infinidb-enterprise >/dev/null 2>&1; rpm -e --nodeps --allmatches infinidb-libs infinidb-platform'\n" - expect "word: " + send_user "Erase Calpont Package on Module " + expect -re "# " + send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches calpont'\n" + expect -re "word: " # password for ssh send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "uninstall completed" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "not installed" { send_user "INFO: Package not installed" } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "not installed" { send_user "INFO: Package not installed" } abort } send_user "\n" } if { $INSTALLTYPE == "uninstall" } { exit 0 } # -# send the InfiniDB package +# send the Calpont package # -expect -re {[$#] } +expect -re "# " set timeout 20 -send_user "Copy New InfiniDB Package to Module " -send "ssh $USERNAME@$SERVER 'rm -f /root/infinidb-*.rpm'\n" -expect "word: " +send_user "Copy New Calpont Package to Module " +send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.rpm'\n" +expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - -re {[$#] } { } + -re "# " { } abort } -send "scp $CALPONTRPM1 $CALPONTRPM2 $CALPONTRPM3 $USERNAME@$SERVER:.\n" -expect "word: " +send "scp $CALPONTRPM $USERNAME@$SERVER:$CALPONTRPM\n" +expect -re "word: " # send the password send "$PASSWORD\n" # check return expect { - "100%" { send_user "DONE" } - "scp" { send_user "ERROR\n" ; + -re "100%" { send_user "DONE" } abort + -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } } send_user "\n" # -# send the InfiniDB MySQL sotrage engine package +# send the Calpont-mysql package # -send_user "Copy New InfiniDB MySQL Storage Engine Package to Module " +send_user "Copy New Calpont-MySql Package to Module " send "scp $CALPONTMYSQLRPM $USERNAME@$SERVER:$CALPONTMYSQLRPM\n" -expect "word: " +expect -re "word: " # send the password send "$PASSWORD\n" # check return expect { - "100%" { send_user "DONE" } - "scp" { send_user "ERROR\n" ; + -re "100%" { send_user "DONE" } abort + -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } } send_user "\n" # -# send the InfiniDB MySQL package +# send the Calpont-mysqld package # -send_user "Copy New InfiniDB MySQL Package to Module " +send_user "Copy New Calpont-MySqld Package to Module " send "scp $CALPONTMYSQLDRPM $USERNAME@$SERVER:$CALPONTMYSQLDRPM\n" -expect "word: " +expect -re "word: " # send the password send "$PASSWORD\n" # check return expect { - "100%" { send_user "DONE" } - "scp" { send_user "ERROR\n" ; + -re "100%" { send_user "DONE" } abort + -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } } # send_user "\n" -expect -re {[$#] } +expect -re "# " set timeout 60 if { $INSTALLTYPE == "initial"} { # # install package # - send_user "Install InfiniDB Packages on Module " - send "ssh $USERNAME@$SERVER 'rpm -ivh $CALPONTRPM1 $CALPONTRPM2 $CALPONTRPM3 $CALPONTMYSQLDRPM $CALPONTMYSQLRPM'\n" - expect "word: " + send_user "Install Calpont Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -ivh $CALPONTRPM'\n" + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - -re {[$#] } { send_user "DONE" } - "completed" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } send_user "\n" - expect -re {[$#] } + expect -re "# " + # + # install package + # + send_user "Install Calpont-MySqld Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -ivh $CALPONTMYSQLDRPM'\n" + expect -re "word: " + # password for ssh + send "$PASSWORD\n" + # check return + expect { + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + } + send_user "\n" + expect -re "# " + # + # install package + # + send_user "Install Calpont-MySql Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -ivh $CALPONTMYSQLRPM'\n" + expect -re "word: " + # password for ssh + send "$PASSWORD\n" + # check return + expect { + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + } + send_user "\n" + expect -re "# " set timeout 10 # # install package # - send_user "Running InfiniDB MySQL Setup Scripts on Module " + send_user "Running Calpont-MySql Setup Scripts on Module " send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-mysql-install'\n" - expect "word: " + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - "Shutting down MySQL." { send_user "DONE" } - timeout { send_user "DONE" } - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "Shutting down MySQL." { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit -1 } } send_user "\n" - expect -re {[$#] } + expect -re "# " # # install package # - send_user "Running InfiniDB MySQL Setup Scripts on Module " + send_user "Running Calpont-MySqld Setup Scripts on Module " send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-mysqld-install'\n" - expect "word: " + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - "Shutting down MySQL." { send_user "DONE" } - timeout { send_user "DONE" } - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "Shutting down MySQL." { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit -1 } } } else { # # upgrade package # - expect -re {[$#] } - send_user "Upgrade InfiniDB Packages on Module " - send "ssh $USERNAME@$SERVER ' rpm -Uvh --noscripts $CALPONTRPM1 $CALPONTRPM2 $CALPONTRPM3 $CALPONTMYSQLDRPM $CALPONTMYSQLRPM'\n" - expect "word: " + expect -re "# " + send_user "Upgrade Calpont Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -Uvh --noscripts $CALPONTRPM'\n" + expect -re "word: " + # password for ssh + send "$PASSWORD\n" + # check return + expect { + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit -1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + } + send_user "\n" + expect -re "# " + # + # upgrade package + # + send_user "Upgrade Calpont-MySqld Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -Uvh --noscripts $CALPONTMYSQLDRPM'\n" + expect -re "word: " + # password for ssh + send "$PASSWORD\n" + # check return + expect { + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit -1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + } + send_user "\n" + expect -re "# " + # + # upgrade package + # + send_user "Upgrade Calpont-MySql Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -Uvh --noscripts $CALPONTMYSQLRPM'\n" + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - -re {[$#] } { send_user "DONE" } - "completed" { send_user "DONE" } - "already installed" { send_user "INFO: Already Installed\n" ; exit -1 } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit -1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } send_user "\n" - expect -re {[$#] } + expect -re "# " set timeout 10 # # install package # - send_user "Running InfiniDB MySQL Setup Scripts on Module " + send_user "Running Calpont-MySql Setup Scripts on Module " send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-mysql-install'\n" - expect "word: " + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - "Shutting down MySQL." { send_user "DONE" } - timeout { send_user "DONE" } - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "Shutting down MySQL." { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit -1 } } send_user "\n" - expect -re {[$#] } + expect -re "# " # # install package # - send_user "Running InfiniDB MySQL Setup Scripts on Module " + send_user "Running Calpont-MySqld Setup Scripts on Module " send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/post-mysqld-install'\n" - expect "word: " + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - "Shutting down MySQL." { send_user "DONE" } - timeout { send_user "DONE" } - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "Shutting down MySQL." { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit -1 } } } send_user "\n" -expect -re {[$#] } +expect -re "# " set timeout 30 # if { $INSTALLTYPE == "initial"} { # - # copy over InfiniDB OS files + # copy over calpont OS files # - send_user "Copy InfiniDB OS files to Module " + send_user "Copy Calpont OS files to Module " send "scp $INSTALLDIR/local/etc/$MODULE/* $USERNAME@$SERVER:$INSTALLDIR/local/.\n" - expect "word: " + expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } send_user "\n" # - # copy over InfiniDB config file + # copy over calpont config file # - send_user "Copy InfiniDB Config file to Module " + send_user "Copy Calpont Config file to Module " send "scp $INSTALLDIR/etc/* $USERNAME@$SERVER:$INSTALLDIR/etc/.\n" - expect "word: " + expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } send_user "\n" # @@ -311,12 +387,12 @@ if { $INSTALLTYPE == "initial"} { # send_user "Copy Custom OS files to Module " send "scp -r $INSTALLDIR/local/etc $USERNAME@$SERVER:$INSTALLDIR/local/.\n" - expect "word: " + expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } send_user "\n" # @@ -324,13 +400,13 @@ if { $INSTALLTYPE == "initial"} { # send_user "Run Module Installer " send "ssh $USERNAME@$SERVER '$INSTALLDIR/bin/module_installer.sh'\n" - expect "word: " + expect -re "word: " # send the password send "$PASSWORD\n" expect { - "!!!Module" { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "FAILED" { send_user "ERROR: missing OS file\n" ; exit -1 } + -re "!!!Module" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "FAILED" { send_user "ERROR: missing OS file\n" ; exit -1 } } send_user "\n" } diff --git a/oam/install_scripts/displayJobGraph.sh b/oam/install_scripts/displayJobGraph.sh new file mode 100755 index 00000000..41830ad0 --- /dev/null +++ b/oam/install_scripts/displayJobGraph.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# +# $Id$ + +PATH=/usr/local/Calpont/bin:$PATH + +graphdir=$(getConfig SystemConfig WorkingDir) +if [ -z "$graphdir" ]; then + echo "Note: looking for graph files in default directory /tmp" + graphdir=/tmp +fi +if [ ! -d "$graphdir" ]; then + echo "Note: looking for graph files in default directory /tmp" + graphdir=/tmp +fi +cd "$graphdir" +if [ -z "$1" ]; then + filename=$(ls -1tr jobstep*.dot 2>&- | tail -1) +else + filename="$1" +fi +if [ -z "$filename" ]; then + echo "No graph file specified and none found in $graphdir" 1>&2 + exit 1 +fi + +dot -V >/dev/null 2>&1 +if [ $? -ne -0 ]; then + echo "'dot' command not found" 1>&2 + echo "This script requires the 'dot' command to convert jobfiles into PNG files" 1>&2 + echo "The 'graphviz' package is one possible source for the 'dot' command" 1>&2 + exit 1 +fi +outname=$(echo $filename | sed 's/\.dot$/.png/') +cnt=$(expr $outname : '.*\.png$') +if [ $cnt -eq 0 ]; then + outname=${outname}.png +fi +dot -Tpng -o$outname $filename + +eog --version >/dev/null 2>&1 +if [ $? -ne 0 ]; then + echo "Output PNG left in $graphdir/$outname" + exit 0 +fi +eog $outname + +# vim:ts=4 sw=4: diff --git a/oam/install_scripts/infinidb b/oam/install_scripts/infinidb index 9c63457c..56463bfd 100644 --- a/oam/install_scripts/infinidb +++ b/oam/install_scripts/infinidb @@ -1,16 +1,17 @@ #!/bin/bash # -# $Id: infinidb 3704 2013-08-07 03:33:20Z bwilkinson $ +# $Id: infinidb.os 2937 2012-05-30 18:17:09Z rdempsey $ +# # # infinidb Starts Calpont InfiniDB database platform # # # chkconfig: 2345 99 99 -# description: Calpont InfiniDB is a database platform that utilizes Mysql +# description: InfiniDB is a database platform that utilizes Mysql # ### BEGIN INIT INFO -# Provides: infinidb -# Required-Start: $local_fs $remote_fs $network $syslog $all +# Provides: $infinidb +# Required-Start: $local_fs $remote_fs $network $syslog # Required-Stop: $local_fs $remote_fs $network $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 @@ -20,8 +21,23 @@ # Source function library. if [ -f /etc/init.d/functions ]; then . /etc/init.d/functions +else +killproc() { + pkill $2 $1 +} fi +unset pathmunge +pathmunge () { + if ! echo $PATH | egrep -q "(^|:)$1($|:)" ; then + if [ "$2" = "after" ] ; then + PATH=$PATH:$1 + else + PATH=$1:$PATH + fi + fi +} + if [ -z "$INFINIDB_INSTALL_DIR" ]; then test -f /etc/default/infinidb && . /etc/default/infinidb fi @@ -30,151 +46,361 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR -InstallDir=$INFINIDB_INSTALL_DIR +CALPONT_HOME=$INFINIDB_INSTALL_DIR +export CALPONT_CONFIG_FILE=$CALPONT_HOME/etc/Calpont.xml +export CALPONT_LIB=$CALPONT_HOME/lib -if [ $InstallDir != "/usr/local/Calpont" ]; then - export PATH=$InstallDir/bin:$InstallDir/mysql/bin:/bin:/usr/bin - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$InstallDir/lib:$InstallDir/mysql/lib/mysql -fi +pathmunge $CALPONT_HOME/bin -#hadoop -plugin=`$INFINIDB_INSTALL_DIR/bin/getConfig SystemConfig DataFilePlugin` -if [ -n "$plugin" ]; then - setenv=`$InstallDir/bin/getConfig SystemConfig DataFileEnvFile` - . $InstallDir/bin/$setenv >/dev/null 2>&1 -fi +RETVAL=0 -if [ -e $InstallDir/lib/libjemalloc.so ]; then - export LD_PRELOAD=$InstallDir/lib/libjemalloc.so -elif [ -e $InstallDir/lib/libjemalloc.so.1 ]; then - export LD_PRELOAD=$InstallDir/lib/libjemalloc.so.1 -fi +# run dbbuilder if necessary +checkForSysCat() { + if [ `editem -o 1001 | wc -l` -eq 0 ]; then -test -f $InstallDir/post/functions && . $InstallDir/post/functions + echo -n "creating system catalog (be patient): " + dbbuilder 7 > /tmp/dbbuilder.log & -mt=`module_type` -mid=`module_id` + while [ -d /proc/$! ]; do + sleep 5 + echo -n "." + done -has_um=`$InstallDir/bin/getConfig SystemModuleConfig ModuleCount2` -if [ "x$has_um" = x ]; then - has_um=0 -fi + echo " done." + fi +} -user=$USER -if [ -z "$user" ]; then - user=root -fi +# run upgrade script +upgradeDB() { -checkInstallSetup() { - InitialInstallFlag=`$InstallDir/bin/getConfig -c $InstallDir/etc/Calpont.xml Installation InitialInstallFlag` - if [ $InitialInstallFlag != "y" ]; then - echo "Please run the postConfigure install script, check the Installation Guide" - echo "for additional details" - rm -f /var/lock/subsys/infinidb - exit 1 + echo "Validate InfiniDB System Catalog:" + + df=$CALPONT_HOME/mysql/my.cnf + + #check for password set + pwprompt=" " + password=" " + userprompt=" *** Enter MySQL password: " + while true ; do + $CALPONT_HOME/mysql/bin/mysql --defaults-file=$df --force --user=root $pwprompt -e status &>/tmp/idbmysql.log + + egrep -qs "ERROR 1045" /tmp/idbmysql.log + if [ $? -eq 0 ]; then + echo "" + stty_orig=`stty -g` + stty -echo + echo -n "$userprompt" + read -t 30 password + stty $stty_orig + echo " " + + if [ -z $password ]; then + echo " " + echo " Timeout: Continuing" + return + else + pwprompt="--password=$password" + userprompt=" *** Incorrect password, please re-enter MySQL password: " + fi + else + egrep -qs "InfiniDB" /tmp/idbmysql.log + if [ $? -ne 0 ]; then + echo "" + echo " ERROR: MySQL runtime error, exit..." + cat /tmp/idbmysql.log + exit 1 + else + rm -f /tmp/idbmysql.log + break + fi + fi + done + + status="ERROR" + if [ -x $CALPONT_HOME/bin/upgrade-infinidb.sh ]; then + status="`$CALPONT_HOME/bin/upgrade-infinidb.sh doupgrade --password=$password`" fi + if [ "$status" != "OK" ]; then + echo " ERROR: Database upgrade script failed" + exit 1 + fi + + echo " Validation Succesfully Completed" + } -[ -f $InstallDir/bin/ProcMon ] || exit 0 -start() { - if [ -f /var/lock/subsys/infinidb ]; then - echo "InfiniDB Database Platform already running" - exit 0 +# functionality test +funTest() { + #check logging functionality + echo -n " InfiniDB Logging check: " + logger -p local1.debug "Functional Test" + status=`grep -s "Functional Test" /var/log/Calpont/debug.log > /tmp/debug.check` + if [ `cat /tmp/debug.check | wc -c` -eq 0 ]; then + echo "ERROR: InfiniDB logging not functioning" + else + echo "DONE" fi - (mkdir -p /var/lock/subsys && touch /var/lock/subsys/infinidb) >/dev/null 2>&1 + #check stop process flag + echo -n " Platform Process check: " - if [ -x $InstallDir/bin/infinidb.pre-start ]; then - $InstallDir/bin/infinidb.pre-start - if [ $? -ne 0 ]; then - echo "Error running InfiniDB pre-start script, not starting InfiniDB" - rm -f /var/lock/subsys/infinidb + if [ -f /tmp/StopCalpont ]; then + echo "InfiniDB Platform is down" + return + fi + + #check Process statility from logs and ps command + PSCOUNT=1 + + DMLProcCnt=`ps ax -opid,comm | grep -c DMLProc | awk '{print $1}'` + DDLProcCnt=`ps ax -opid,comm | grep -c DDLProc | awk '{print $1}'` + ExeMgrCnt=`ps ax -opid,comm | grep -c ExeMgr | awk '{print $1}'` + PrimProcCnt=`ps ax -opid,comm | grep -c PrimProc | awk '{print $1}'` + controllernodeCnt=`ps ax -opid,comm | grep -c controllernode | awk '{print $1}'` + workernodeCnt=`ps ax -opid,comm | grep -c workernode | awk '{print $1}'` + + badProc="dummy" + if [ $DMLProcCnt -ne $PSCOUNT ]; then + badProc="DMLProc" + elif [ $DDLProcCnt -ne $PSCOUNT ]; then + badProc="DDLProc" + elif [ $ExeMgrCnt -ne $PSCOUNT ]; then + badProc="ExeMgr" + elif [ $PrimProcCnt -ne $PSCOUNT ]; then + badProc="PrimProc" + elif [ $controllernodeCnt -ne $PSCOUNT ]; then + badProc="controllernode" + elif [ $workernodeCnt -ne $PSCOUNT ]; then + badProc="workernode" + fi + + if [ $badProc != "dummy" ]; then + echo " ERROR: Problem with InfiniDB process $badProc, should be a single version running" + echo " " + echo "***Stopping InfiniDB to allow the process problem to be resolved." + echo " " + stop + exit 1 + fi + + DMLProcPID1=`ps ax -opid,comm | grep DMLProc | awk '{print $1}'` + DDLProcPID1=`ps ax -opid,comm | grep DDLProc | awk '{print $1}'` + ExeMgrPID1=`ps ax -opid,comm | grep ExeMgr | awk '{print $1}'` + PrimProcPID1=`ps ax -opid,comm | grep PrimProc | awk '{print $1}'` + controllernodePID1=`ps ax -opid,comm | grep controllernode | awk '{print $1}'` + workernodePID1=`ps ax -opid,comm | grep workernode | awk '{print $1}'` + + sleep 3 + DMLProcPID2=`ps ax -opid,comm | grep DMLProc | awk '{print $1}'` + DDLProcPID2=`ps ax -opid,comm | grep DDLProc | awk '{print $1}'` + ExeMgrPID2=`ps ax -opid,comm | grep ExeMgr | awk '{print $1}'` + PrimProcPID2=`ps ax -opid,comm | grep PrimProc | awk '{print $1}'` + controllernodePID2=`ps ax -opid,comm | grep controllernode | awk '{print $1}'` + workernodePID2=`ps ax -opid,comm | grep workernode | awk '{print $1}'` + + badProc="dummy" + if [ $DMLProcPID1 -ne $DMLProcPID2 ]; then + badProc="DMLProc" + elif [ $DDLProcPID1 -ne $DDLProcPID2 ]; then + badProc="DDLProc" + elif [ $ExeMgrPID1 -ne $ExeMgrPID2 ]; then + badProc="ExeMgr" + elif [ $PrimProcPID1 -ne $PrimProcPID2 ]; then + badProc="PrimProc" + elif [ $controllernodePID1 -ne $controllernodePID2 ]; then + badProc="controllernode" + elif [ $workernodePID1 -ne $workernodePID2 ]; then + badProc="workernode" + fi + + if [ $badProc != "dummy" ]; then + echo " ERROR: $badProc not Active" + + status=`tail -1 /var/log/Calpont/crit.log | grep "allocated too much memory" > /tmp/crit.check` + if [ `cat /tmp/crit.check | wc -c` -ne 0 ]; then + echo " There isn't enough available system memory for the InfiniDB Process." + echo " Check available/active memory and settings of /etc/sysctl.conf for memory limitations." + echo " Check /var/log/Calpont/*.log files for additional information." + echo " " + echo "***Stopping InfiniDB to allow the memory problem to be resolved." + echo " " + stop + exit 1 + else + echo " Check /var/log/Calpont/*.log files for additional information" + echo " " + echo "***Stopping InfiniDB to allow the process problem to be resolved." + echo " " + stop exit 1 fi + else + echo "DONE" fi - checkInstallSetup - CoreFileFlag=`$InstallDir/bin/getConfig -c $InstallDir/etc/Calpont.xml Installation CoreFileFlag` - if [ $CoreFileFlag = "y" ]; then - SUDO= - if [ -z "$NO_NONROOT_SUDO" -a "$user" != "root" ]; then - SUDO="sudo" + echo -n " MySQL Daemon check: " + test -x /etc/init.d/mysql-Calpont && /etc/init.d/mysql-Calpont status + + #check dbrm + echo -n " Database check: " + + $CALPONT_HOME/bin/dbrmctl status > /tmp/dbrmctl.status + status=`cat /tmp/dbrmctl.status | awk '{print $1}'` + if [ $status != "OK." ]; then + echo -n "ERROR: " + cat /tmp/dbrmctl.status + if [ $status != "DBRM is currently Read Only!" ]; then + echo " ***DDL/DML are disabled, can only perform queries" fi + echo " Check /var/log/Calpont/*.log files for additional information" + return + fi - #infinidb core files - $SUDO ulimit -c unlimited > /dev/null 2>&1 - $SUDO sysctl -q -w kernel.core_uses_pid=1 > /dev/null 2>&1 - $SUDO sysctl -q -w kernel.core_pattern=/var/log/Calpont/corefiles/core.%e.%p > /dev/null 2>&1 + $CALPONT_HOME/bin/editem -o 2001 > /tmp/editem.status 2>&1 + cnt=`cat /tmp/editem.status | wc -l` + if [ $cnt -eq 0 ]; then + echo "ERROR: NO system catalog data" + echo " Check /var/log/Calpont/*.log files for additional information" + echo " " + echo "***Stopping InfiniDB to allow the problem to be resolved." + echo "A clean re-install of InfiniDB might be required to correct." + stop + exit 1 fi - RETVAL=0 - echo "Starting InfiniDB Database Platform" - rm -f /tmp/StopCalpont - exec $InstallDir/bin/run.sh $InstallDir/bin/ProcMon > /dev/null 2>&1 & + #run save_brm to get a current file and run post-test + $CALPONT_HOME/bin/save_brm > /tmp/savebrm.status 2>&1 + $CALPONT_HOME/bin/startupTests.sh > /tmp/startupTests.status 2>&1 + status=`cat /tmp/startupTests.status | awk '{print $1}'` + if [ x$status != "xOK" ]; then + echo "ERROR: Check /var/log/Calpont/crit.log files for additional information" + echo " " + echo "***Stopping InfiniDB to allow the problem to be resolved." + stop + exit 1 + fi + + echo "DONE" +} + +checkInstallSetup() { + if [ ! -d $CALPONT_HOME/data1/systemFiles/dbrm ]; then + install-infinidb.sh + fi +} +killProcesses() { + killproc DMLProc -9 > /dev/null + killproc DDLProc -9 > /dev/null + killproc ExeMgr -9 > /dev/null + killproc WriteEngineServer -9 > /dev/null + # only first 15 chars can be used on debian + killproc WriteEngineServ -9 > /dev/null + killproc PrimProc -9 > /dev/null + killproc controllernode -9 > /dev/null + killproc workernode -9 > /dev/null +} + +start() { + checkInstallSetup + touch /tmp/StopCalpont + killProcesses + echo -n "Starting Calpont InfiniDB Database Platform: " + rm -f /tmp/StopCalpont + brm_prefix=$(cat $(getConfig SystemConfig DBRMRoot)_current 2>/dev/null) + if [ -n "$brm_prefix" ]; then + echo -n "." + load_brm $brm_prefix > /tmp/load_brm.log + sleep 5 + grep OK /tmp/load_brm.log >/dev/null 2>&1 + if [ $? -ne 0 ]; then + echo " " + echo "Error when loading BRM data. Check log file at /tmp/load_brm.log" + return 1 + fi + fi + echo -n "." + run.sh workernode DBRM_Worker1 fg >/dev/null 2>&1 & + sleep 1 + echo -n "." + run.sh controllernode fg >/dev/null 2>&1 & + sleep 1 + echo -n "." + run.sh PrimProc >/dev/null 2>&1 & + sleep 1 + echo -n "." + run.sh WriteEngineServer >/dev/null 2>&1 & + sleep 1 + echo -n "." + run.sh ExeMgr >/dev/null 2>&1 & + sleep 1 + echo -n "." + run.sh DDLProc >/dev/null 2>&1 & + sleep 1 + echo -n "." + run.sh DMLProc >/dev/null 2>&1 & + sleep 5 + echo " DONE" + checkForSysCat + RETVAL=0 + echo "Starting Calpont InfiniDB MySQL: " + test -x /etc/init.d/mysql-Calpont && /etc/init.d/mysql-Calpont start + sleep 2 + upgradeDB + [ $RETVAL -eq 0 ] && [ -d /var/lock/subsys ] && touch /var/lock/subsys/infinidb + echo "Perform Functionality test: " + funTest return $RETVAL } stop() { - echo "Shutting down InfiniDB Database Platform" + echo "Shutting down Calpont InfiniDB MySQL: " touch /tmp/StopCalpont - pkill -9 ProcMon - pkill -9 ProcMgr - pkill -9 snmptrapd + test -x /etc/init.d/mysql-Calpont && /etc/init.d/mysql-Calpont stop + echo "Shutting down Calpont InfiniDB Database Platform: " + killProcesses + reset_locks > /dev/null 2>&1 + save_brm > /dev/null 2>&1 sleep 1 - $InstallDir/bin/clearShm - RETVAL=$? - rm -f /var/lock/subsys/infinidb + RETVAL=0 + echo fuser -k 8604/tcp > /dev/null 2>&1 - test -f $InstallDir/mysql/mysql-Calpont || return $RETVAL - $InstallDir/mysql/mysql-Calpont stop > /dev/null 2>&1 - if [ -x $InstallDir/bin/infinidb.post-stop ]; then - $InstallDir/bin/infinidb.post-stop - fi + clearShm + [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/infinidb return $RETVAL } restart() { stop + sleep 10 start -} +} + status() { - isrunning=0 - if [ $EUID -eq 0 ]; then - if [ -f /var/lock/subsys/infinidb ]; then - isrunning=1 - fi - else - pgrep ProcMon >/dev/null 2>&1 - if [ $? -eq 0 ]; then - isrunning=1 - fi - fi - if [ $isrunning -ne 0 ]; then - echo "InfiniDB is running" - else - echo "InfiniDB is not running" - fi -} + RETVAL=0 + funTest + return $RETVAL +} + case "$1" in -start) - start + start) + start ;; -stop) - stop + stop) + stop ;; -restart) - restart + restart) + restart ;; -condrestart) - [ -f /var/lock/subsys/infinidb ] && restart || : + condrestart) + [ -f /var/lock/subsys/infinidb ] && restart || : ;; -status) - status + status) + status ;; -*) + *) echo $"Usage: $0 {start|stop|restart|condrestart|status}" exit 1 esac diff --git a/oam/install_scripts/infinidb.def b/oam/install_scripts/infinidb.def index 4ebfb201..e583b374 100644 --- a/oam/install_scripts/infinidb.def +++ b/oam/install_scripts/infinidb.def @@ -1,9 +1,8 @@ -#!/bin/bash # Copy this file to /etc/default and rename it to 'infinidb'. # Change this line to your InfiniDB installation directory INFINIDB_INSTALL_DIR=/usr/local/Calpont LD_LIBRARY_PATH=$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR -export LD_LIBRARY_PATH=$LD_LIBRARY_PATH +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x LD_LIBRARY_PATH=$LD_LIBRARY_PATH diff --git a/oam/install_scripts/install-infinidb.sh b/oam/install_scripts/install-infinidb.sh index d19d0090..1f1437b4 100755 --- a/oam/install_scripts/install-infinidb.sh +++ b/oam/install_scripts/install-infinidb.sh @@ -2,12 +2,311 @@ # # $Id: install-infinidb.sh 421 2007-04-05 15:46:55Z dhill $ # -# install-infinidb.sh dummy EE version +# install-infinidb.sh preconfigures a system before the Calpont Database Platform can run -echo " " 1>&2 -echo " This install-infinidb.sh script is only used to install the Community Edition." 1>&2 -echo " Please use the 'postConfigure' for installing the Enterprise Edition." 1>&2 -echo " Check the Calpont InfiniDB Installation Document for further details." 1>&2 +prefix=/usr/local +rpmmode=install -exit 1 +#check 64-bit OS compatiable +arch=`uname -m` +patcnt=`expr "$arch" : 'i.86'` +is64bitos=1 +if [ $patcnt -ne 0 ]; then + is64bitos=0 +fi +is64bitpkg=1 +file ${prefix}/Calpont/bin/PrimProc | grep '64-bit' >/dev/null 2>&1 +if [ $? -ne 0 ]; then + is64bitpkg=0 +fi +if [ $is64bitpkg -eq 1 -a $is64bitos -ne 1 ]; then + echo "ERROR: Incompatible version, package is intended for a x86_64 architecture" + echo "exiting...." + exit 1 +fi +#run post-install in case it hadn't been run already +${prefix}/Calpont/bin/post-install --prefix=$prefix --rpmmode=$rpmmode + +for arg in "$@"; do + if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then + prefix="`echo $arg | awk -F= '{print $2}'`" + elif [ `expr -- "$arg" : '--rpmmode='` -eq 10 ]; then + rpmmode="`echo $arg | awk -F= '{print $2}'`" + else + echo "ignoring unknown argument: $arg" 1>&2 + fi +done + +netstat -na | egrep -qs ':3306.*LISTEN' +if [ $? -eq 0 ]; then + egrep -qs '= 3306' ${prefix}/Calpont/mysql/my.cnf + if [ $? -eq 0 ]; then + echo " " + echo " There is already a version of mysqld running." + echo " If the InfiniDB mysqld is running then stop it and run install-infinidb.sh again." + echo " If another version of mysqld is running then either change the port number" + echo " of 3306 in ${prefix}/Calpont/mysql/my.cnf or stop the other mysqld" + echo " then run install-infinidb.sh again." + exit 1 + fi +fi + +#setup for a single server system +for file in Calpont.xml ProcessConfig.xml snmpd.conf snmptrapd.conf; do + rm -f ${prefix}/Calpont/etc/${file}.save + if [ -f ${prefix}/Calpont/etc/${file} ]; then + mv ${prefix}/Calpont/etc/${file} ${prefix}/Calpont/etc/${file}.save + fi + if [ -f ${prefix}/Calpont/etc/${file}.singleserver ]; then + cp ${prefix}/Calpont/etc/${file}.singleserver ${prefix}/Calpont/etc/${file} + fi +done + +#check 3rd party library check +echo " " +echo "DEPENDENCY LIBRARY CHECK" +echo " " +ldd ${prefix}/Calpont/bin/* | grep 'not found' | sort -u > /tmp/pkgcheck +if [ `cat /tmp/pkgcheck | wc -c` -ne 0 ]; then + cat /tmp/pkgcheck + echo " " + echo "Please install the libraries that are shown to be missing, then run install-infinidb.sh again" + rm -f /tmp/pkgcheck + exit 1 +fi + +rm -f /tmp/pkgcheck +echo "All libraries found" +echo " " + +#check disk space +echo "DISK SPACE CHECK" +echo "" +echo "Make sure there is enough local or mounted disk space for the" +echo "InfiniDB System Catalog and the planned test Database." +echo " " +df -h / +df -h ${prefix}/Calpont/data1 2>/dev/null | grep data1 +if [ $? -ne 0 ]; then + echo " " + echo "No '${prefix}/Calpont/data1' mounted disk found" + echo "Check the JumpStart Guide for information on how to setup a mounted disk" + echo "if you require additional disk space for the InfiniDB Database" +fi + +echo " " +echo "CONFIGURATION / DATA VALIDATION CHECK" +echo " " +echo "Validates Configuration and Data settings" +echo "" +if [ -f ${prefix}/Calpont/etc/Calpont.xml.rpmsave ]; then + rm -f ${prefix}/Calpont/etc/Calpont.xml.new + cp ${prefix}/Calpont/etc/Calpont.xml ${prefix}/Calpont/etc/Calpont.xml.new + + #check FilesPerColumnPartition and ExtentsPerSegmentFile + oldFilesPer=`${prefix}/Calpont/bin/getConfig -c ${prefix}/Calpont/etc/Calpont.xml.rpmsave ExtentMap FilesPerColumnPartition` + newFilesPer=`${prefix}/Calpont/bin/getConfig ExtentMap FilesPerColumnPartition` + + oldExtentsPer=`${prefix}/Calpont/bin/getConfig -c ${prefix}/Calpont/etc/Calpont.xml.rpmsave ExtentMap ExtentsPerSegmentFile` + newExtentsPer=`${prefix}/Calpont/bin/getConfig ExtentMap ExtentsPerSegmentFile` + + if [ $oldFilesPer -ne $newFilesPer ]; then + echo "" + echo "The Configuration Parameter of ExtentMap/FilesPerColumnPartition mis-compares" + echo "between the Calpont.xml file and the backed up version of Calpont.xml.rpmsave" + echo "Calpont.xml value = " $oldFilesPer ", Calpont.xml.rpmsave value = " $newFilesPer + echo "" + echo "InfiniDB will continue to use the previous value from Calpont.xml.rpmsave" + echo "Please refer to the JumpStart Guide for additional Information" + ${prefix}/Calpont/bin/setConfig ExtentMap FilesPerColumnPartition $oldFilesPer + fi + + if [ $oldExtentsPer -ne $newExtentsPer ]; then + echo "" + echo "The Configuration Parameter of ExtentMap/ExtentsPerSegmentFile mis-compares" + echo "between the Calpont.xml file and the backed up version of Calpont.xml.rpmsave" + echo "Calpont.xml value = " $oldExtentsPer ", Calpont.xml.rpmsave value = " $newExtentsPer + echo "" + echo "InfiniDB will continue to use the previous value from Calpont.xml.rpmsave" + echo "Please refer to the JumpStart Guide for additional Information" + ${prefix}/Calpont/bin/setConfig ExtentMap ExtentsPerSegmentFile $oldExtentsPer + fi + + #check NumBlocksPct and TotalUmMem + oldNumBlocksPct=`${prefix}/Calpont/bin/getConfig -c ${prefix}/Calpont/etc/Calpont.xml.rpmsave DBBC NumBlocksPct` + `${prefix}/Calpont/bin/setConfig DBBC NumBlocksPct $oldNumBlocksPct` + + oldTotalUmMem=`${prefix}/Calpont/bin/getConfig -c ${prefix}/Calpont/etc/Calpont.xml.rpmsave HashJoin TotalUmMemory` + `${prefix}/Calpont/bin/setConfig HashJoin TotalUmMemory $oldTotalUmMem` + + #check dbrm file location + dbrmrootPrev=`${prefix}/Calpont/bin/getConfig -c ${prefix}/Calpont/etc/Calpont.xml.rpmsave SystemConfig DBRMRoot` + dbrmroot=`${prefix}/Calpont/bin/getConfig SystemConfig DBRMRoot` + + dbrmrootPrevDir=${dbrmrootPrev//BRM_saves/} + dbrmrootDir=${dbrmroot//BRM_saves/} + + if [ $dbrmrootPrev != $dbrmroot ]; then + if [ -f $dbrmrootPrev"_current" ]; then + if [ -f $dbrmroot"_current" ]; then + echo "" + echo "DBRM Data File Directory Check" + echo "" + echo "**** IMPORTANT PLEASE READ ****************************************************" + echo "" + echo "DBRM data files were found in $dbrmrootPrevDir" + echo "and in new location $dbrmrootDir" + echo "" + echo "Make sure that the correct set of files are in the new location." + echo "Then rename the directory $dbrmrootPrevDir." + echo "If the files were copied from $dbrmrootPrevDir" + echo "you will need to edit the file BRM_saves_current to contain the current path of" + echo $dbrmrootDir + echo "" + echo "Please reference the Calpont InfiniDB JumpStart Guide for Upgrade Installs for " + echo "addition information, if needed." + echo "" + echo "*******************************************************************************" + else + echo "" + echo "DBRM Data File Directory Check" + echo "" + echo "DBRM data files moved from $dbrmrootPrev" + echo "to new location $dbrmrootDir." + echo "Old location $dbrmrootPrevDir renamed to /usr/local/Calpont/dbrm.old ." + /bin/cp -fp $dbrmrootPrevDir/* $dbrmrootDir/. + sed 's/dbrm/data1\/systemFiles\/dbrm/' $dbrmrootPrev"_current" > $dbrmroot"_current" + mv $dbrmrootPrevDir /usr/local/Calpont/dbrm.old + fi + fi + fi +else + memory=`${prefix}/Calpont/bin/idbmeminfo` + + if [ $memory -le 2000 ]; then + echo "A minumum of 2GB of memory is recommended, which this machine doesn't seem to have." + echo "We recommend using a machine with more memory." + echo "If you know you have more memory than shown, see the InfiniDB Tuning Guide for" + echo "instructions on how to configure InfiniDB's use of system memory." + value=256M + elif [ $memory -le 4000 ]; then + value=512M + elif [ $memory -le 8000 ]; then + value=1G + elif [ $memory -le 16000 ]; then + value=2G + elif [ $memory -le 32000 ]; then + value=4G + elif [ $memory -le 64000 ]; then + value=8G + else + value=16G + fi + + ${prefix}/Calpont/bin/setConfig HashJoin TotalUmMemory $value +fi + +NumBlocksPct=`${prefix}/Calpont/bin/getConfig DBBC NumBlocksPct` +TotalUmMemory=`${prefix}/Calpont/bin/getConfig HashJoin TotalUmMemory` + +echo "The Memory Configuration Setting are:" +echo " NumBlocksPct = $NumBlocksPct%" +echo " TotalUmMemory = $TotalUmMemory" + + +echo " " +echo "SETUP INFINIDB MYSQL" +echo " " + +${prefix}/Calpont/bin/post-mysqld-install --prefix=$prefix --rpmmode=$rpmmode + +#check for password set +#start in the same way that mysqld will be started normally. +/etc/init.d/mysql-Calpont start +sleep 2 + +df=${prefix}/Calpont/mysql/my.cnf +password=" " +userprompt=" *** Enter MySQL password: " +while true ; do + $prefix/Calpont/mysql/bin/mysql --defaults-file=$df --force --user=root $pwprompt -e status &>/tmp/idbmysql.log + + egrep -qs "ERROR 1045" /tmp/idbmysql.log + if [ $? -eq 0 ]; then + echo "" + stty_orig=`stty -g` + stty -echo + echo -n "$userprompt" + read password + stty $stty_orig + echo " " + pwprompt="--password=$password" + userprompt=" *** Incorrect password, please re-enter MySQL password: " + else + egrep -qs "InfiniDB" /tmp/idbmysql.log + if [ $? -ne 0 ]; then + echo "" + echo "ERROR: MySQL runtime error, exit..." + cat /tmp/idbmysql.log + exit 1 + else + /etc/init.d/mysql-Calpont stop + rm -f /tmp/idbmysql.log + break + fi + fi +done + +${prefix}/Calpont/bin/post-mysql-install --prefix=$prefix --rpmmode=$rpmmode --password=$password + +echo " " +echo "SETUP INFINIDB SYSTEM LOGGING" + +#setup syslog + +${prefix}/Calpont/bin/syslogSetup.sh install + +for file in snmpdx.conf; do + rm -f ${prefix}/Calpont/local/${file}.save + if [ -f ${prefix}/Calpont/local/${file} ]; then + mv ${prefix}/Calpont/local/${file} ${prefix}/Calpont/local/${file}.save + fi + if [ -f ${prefix}/Calpont/local/${file}.singleserver ]; then + cp ${prefix}/Calpont/local/${file}.singleserver ${prefix}/Calpont/local/${file} + fi +done + +#create the bulk-load dirs +mkdir -p ${prefix}/Calpont/data/bulk/data/import >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/log >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/job >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/rollback >/dev/null 2>&1 + +#setup the calpont service script +rm -f /etc/init.d/infinidb +cp ${prefix}/Calpont/bin/infinidb /etc/init.d +if [ -x /sbin/chkconfig ]; then + /sbin/chkconfig --add infinidb > /dev/null 2>&1 + /sbin/chkconfig infinidb on > /dev/null 2>&1 + echo "" + echo "InfiniDB is setup for autostart using 'chkconfig'" +elif [ -x /usr/sbin/update-rc.d ]; then + /usr/sbin/update-rc.d infinidb defaults > /dev/null 2>&1 + echo "" + echo "InfiniDB is setup for autostart using 'update-rc.d'" +else + echo "" + echo "Package 'chkconfig' or 'update-rc.d' not installed, contact your sysadmin if you want to setup to autostart InfiniDB" +fi + +#clean up some dirs that post-install created during the rpm install +rm -rf /mnt/parentOAM >/dev/null 2>&1 +# if /mnt/tmp is empty, assume that we created it and remove it +cnt=`/bin/ls -1 /mnt/tmp | wc -l` +if [ $cnt -eq 0 ]; then + rm -rf /mnt/tmp >/dev/null 2>&1 +fi + +echo " " +echo "InfiniDB Installation Completed" diff --git a/oam/install_scripts/master-rep-infinidb.sh b/oam/install_scripts/master-rep-infinidb.sh deleted file mode 100644 index 4efecc63..00000000 --- a/oam/install_scripts/master-rep-infinidb.sh +++ /dev/null @@ -1,109 +0,0 @@ -#!/bin/bash -# -# $Id$ -# -# generic InfiniDB Master Replication script. -# -# Notes: This script gets run by ProcMon during installs and upgrades: - -# check log for error -checkForError() { - grep ERROR /tmp/master-rep-status-$hostipaddr.log > /tmp/error.check - if [ `cat /tmp/error.check | wc -c` -ne 0 ]; then - echo "ERROR: check log file: /tmp/master-rep-status-$hostipaddr.log" - rm -f /tmp/error.check - exit 1; - fi - rm -f /tmp/error.check -} - -prefix=/usr/local -installdir=$prefix/Calpont -pwprompt= -for arg in "$@"; do - if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then - prefix="`echo $arg | awk -F= '{print $2}'`" - installdir=$prefix/Calpont - elif [ `expr -- "$arg" : '--password='` -eq 11 ]; then - password="`echo $arg | awk -F= '{print $2}'`" - pwprompt="--password=$password" - elif [ `expr -- "$arg" : '--installdir='` -eq 13 ]; then - installdir="`echo $arg | awk -F= '{print $2}'`" - prefix=`dirname $installdir` - elif [ `expr -- "$arg" : '--hostIP='` -eq 9 ]; then - hostipaddr="`echo $arg | awk -F= '{print $2}'`" - fi -done - -test -f $installdir/post/functions && . $installdir/post/functions - -repUser="idbrep" -password="Calpont1" - ->/tmp/master-rep-status-$hostipaddr.log - -# -# Create Replication User -# -echo "Create Replication User $repUser for node $hostipaddr" >>/tmp/master-rep-status-$hostipaddr.log -cat >/tmp/idb_master-rep.sql <>/tmp/master-rep-status-$hostipaddr.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/master-rep-status-$hostipaddr.log - -checkForError - -# -# Grant table access for created user -# -echo "Grant table access for $repUser for node $hostipaddr" >>/tmp/master-rep-status-$hostipaddr.log -cat >/tmp/idb_master-rep.sql <>/tmp/master-rep-status-$hostipaddr.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/master-rep-status-$hostipaddr.log - -checkForError - -# -# Run SHOW MASTER STATUS -# -echo "Run SHOW MASTER STATUS to node log" >>/tmp/master-rep-status-$hostipaddr.log -cat >/tmp/idb_master-rep.sql <>/tmp/master-rep-status-$hostipaddr.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/master-rep-status-$hostipaddr.log - -checkForError - -echo "Run SHOW MASTER STATUS to master status log /tmp/show-master-status.log" >>/tmp/master-rep-status-$hostipaddr.log -cat >/tmp/idb_master-rep.sql </tmp/show-master-status.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/show-master-status.log - - -#alls good, 'OK' for success -echo "OK" - diff --git a/oam/install_scripts/module_installer.sh b/oam/install_scripts/module_installer.sh index f435f415..27296a8f 100755 --- a/oam/install_scripts/module_installer.sh +++ b/oam/install_scripts/module_installer.sh @@ -37,24 +37,18 @@ for arg in "$@"; do elif [ $(expr -- "$arg" : '--quiet') -eq 7 ]; then quiet=1 ((shiftcnt++)) - elif [ $(expr -- "$arg" : '--port') -eq 6 ]; then - mysqlPort="$(echo $arg | awk -F= '{print $2}')" - ((shiftcnt++)) - elif [ $(expr -- "$arg" : '--module') -eq 8 ]; then - module="$(echo $arg | awk -F= '{print $2}')" - ((shiftcnt++)) fi done shift $shiftcnt if [ $installdir != "/usr/local/Calpont" ]; then - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql + export LD_LIBRARY_PATH=$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql fi export INFINIDB_INSTALL_DIR=$installdir cloud=`$INFINIDB_INSTALL_DIR/bin/getConfig Installation Cloud` -if [ $cloud = "amazon-ec2" ] || [ $cloud = "amazon-vpc" ]; then +if [ $cloud = "amazon" ]; then cp $INFINIDB_INSTALL_DIR/local/etc/*.pem /root/. > /dev/null 2>&1 if test -f $INFINIDB_INSTALL_DIR/local/fstab ; then @@ -71,8 +65,8 @@ test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/fun mid=`module_id` #if um, cloud, separate system type, external um storage, then setup mount -if [ $module = "um" ]; then - if [ $cloud = "amazon-ec2" ] || [ $cloud = "amazon-vpc" ]; then +if [ "$1" = "um" ]; then + if [ $cloud = "amazon" ]; then systemtype=`$INFINIDB_INSTALL_DIR/bin/getConfig Installation ServerTypeInstall` if [ $systemtype = "1" ]; then umstoragetype=`$INFINIDB_INSTALL_DIR/bin/getConfig Installation UMStorageType` @@ -88,7 +82,7 @@ if [ $module = "um" ]; then fi #if pm, create dbroot directories -if [ $module = "pm" ]; then +if [ "$1" = "pm" ]; then numdbroots=`$INFINIDB_INSTALL_DIR/bin/getConfig SystemConfig DBRootCount` for (( id=1; id<$numdbroots+1; id++ )); do mkdir -p $INFINIDB_INSTALL_DIR/data$id > /dev/null 2>&1 @@ -111,48 +105,6 @@ if [ $EUID -eq 0 -a -f $INFINIDB_INSTALL_DIR/local/rc.local.calpont ]; then fi fi -if [ $user != "root" ]; then - echo "Setup .bashrc on Module for non-root" - - eval userhome=~$user - bashFile=$userhome/.bashrc - touch ${bashFile} - - echo " " >> ${bashFile} - echo "export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR" >> ${bashFile} - echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql" >> ${bashFile} -fi - -plugin=`$INFINIDB_INSTALL_DIR/bin/getConfig SystemConfig DataFilePlugin` -if [ -n "$plugin" ]; then - echo "Setup .bashrc on Module for local-query" - - setenv=`$INFINIDB_INSTALL_DIR/bin/getConfig SystemConfig DataFileEnvFile` - - eval userhome=~$user - bashFile=$userhome/.bashrc - touch ${bashFile} - - echo " " >> ${bashFile} - echo ". $INFINIDB_INSTALL_DIR/bin/$setenv" >> ${bashFile} -fi - -# if mysqlrep is on and module has a my.cnf file, upgrade it - -MySQLRep=`$INFINIDB_INSTALL_DIR/bin/getConfig Installation MySQLRep` -if [ $MySQLRep = "y" ]; then - if test -f $INFINIDB_INSTALL_DIR/mysql/my.cnf ; then - echo "Run Upgrade on my.cnf on Module" - $INFINIDB_INSTALL_DIR/bin/mycnfUpgrade > /tmp/mycnfUpgrade.log 2>&1 - fi -fi - -if test -f $INFINIDB_INSTALL_DIR/mysql/my.cnf ; then - echo "Run Mysql Port update on my.cnf on Module" - $INFINIDB_INSTALL_DIR/bin/mycnfUpgrade $mysqlPort > /tmp/mycnfUpgrade_port.log 2>&1 -fi - - echo " " echo "!!!Module Installation Successfully Completed!!!" diff --git a/oam/install_scripts/myCnf-exclude-args.text b/oam/install_scripts/myCnf-exclude-args.text deleted file mode 100644 index aac98c73..00000000 --- a/oam/install_scripts/myCnf-exclude-args.text +++ /dev/null @@ -1,2 +0,0 @@ -# List of my.cnf arguments that should be ignored during upgrade install -# diff --git a/oam/install_scripts/myCnf-include-args.text b/oam/install_scripts/myCnf-include-args.text deleted file mode 100644 index 7472a4d4..00000000 --- a/oam/install_scripts/myCnf-include-args.text +++ /dev/null @@ -1,6 +0,0 @@ -# List of my.cnf arguments that should be checked and saved during upgrade install -# -infinidb_local_query -log-bin=mysql-bin -server-id -relay-log \ No newline at end of file diff --git a/oam/install_scripts/patch_installer.sh b/oam/install_scripts/patch_installer.sh index 8e21af3a..42b2006d 100755 --- a/oam/install_scripts/patch_installer.sh +++ b/oam/install_scripts/patch_installer.sh @@ -39,7 +39,7 @@ expect -re "word: " send "$PASSWORD\n" # check return expect { - -re "# " { send_user " DONE" } + -re "# " { send_user " DONE" } abort -re "Permission denied" { send_user " FAILED: Invalid password\n" } exit; -re "mv" { send_user " FAILED: copy filed\n" ; exit} } @@ -55,7 +55,7 @@ expect -re "word: " send "$PASSWORD\n" # check return expect { - -re "100%" { send_user " DONE" } + -re "100%" { send_user " DONE" } abort -re "scp" { send_user " FAILED\n" ; send_user "\n*** Installation Failed\n" ; exit } diff --git a/oam/install_scripts/performance_installer.sh b/oam/install_scripts/performance_installer.sh index e65a0638..56fd2057 100644 --- a/oam/install_scripts/performance_installer.sh +++ b/oam/install_scripts/performance_installer.sh @@ -14,22 +14,20 @@ set USERNAME root set MODULE [lindex $argv 0] set SERVER [lindex $argv 1] set PASSWORD [lindex $argv 2] -set CALPONTRPM1 [lindex $argv 3] -set CALPONTRPM2 [lindex $argv 4] -set CALPONTRPM3 [lindex $argv 5] -set CALPONTMYSQLRPM [lindex $argv 6] -set CALPONTMYSQLDRPM [lindex $argv 7] -set INSTALLTYPE [lindex $argv 8] -set PKGTYPE [lindex $argv 9] -set NODEPS [lindex $argv 10] -set DEBUG [lindex $argv 11] +set CALPONTRPM [lindex $argv 3] +set CALPONTMYSQLRPM [lindex $argv 4] +set CALPONTMYSQLDRPM [lindex $argv 5] +set INSTALLTYPE [lindex $argv 6] +set PKGTYPE [lindex $argv 7] +set NODEPS [lindex $argv 8] +set DEBUG [lindex $argv 9] set INSTALLDIR "/usr/local/Calpont" -set IDIR [lindex $argv 12] +set IDIR [lindex $argv 10] if { $IDIR != "" } { set INSTALLDIR $IDIR } set USERNAME "root" -set UNM [lindex $argv 13] +set UNM [lindex $argv 11] if { $UNM != "" } { set USERNAME $UNM } @@ -64,256 +62,242 @@ send_user " " send "ssh $USERNAME@$SERVER 'time'\n" set timeout 60 expect { - "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1 } - "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } - "authenticity" { send "yes\n" + -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1 } + -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - "sys" { set PASSWORD "ssh" } - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "sys" { set PASSWORD "ssh" } abort + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } timeout { send_user "ERROR: Timeout to host\n" ; exit 1 } } set timeout 30 expect { - -re {[$#] } { } - "sys" { } + -re "# " { } abort + -re "sys" { } abort } send_user "\n" -#BUG 5749 - SAS: didn't work on their system until I added the sleep 60 - -sleep 60 +sleep 5 if { $INSTALLTYPE == "initial" || $INSTALLTYPE == "uninstall" } { # # erase package # - send_user "Erase InfiniDB Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGERASE calpont >/dev/null 2>&1; $PKGERASE infinidb-enterprise >/dev/null 2>&1; $PKGERASE infinidb-libs infinidb-platform;$PKGERASE dummy'\n" + send_user "Erase calpont Package on Module " + send "ssh $USERNAME@$SERVER '$PKGERASE calpont'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - set timeout 120 + set timeout 30 expect { - "package dummy" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "removing" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "error: package" { send_user "INFO: Package not installed" } abort + -re "not installed" { send_user "INFO: Package not installed" } abort + -re "isn't installed" { send_user "INFO: Package not installed" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" } - if { $INSTALLTYPE == "uninstall" } { exit 0 } +#gives time for the rpmsave to be done +sleep 5 # # send the package # set timeout 30 -#expect -re {[$#] } -send_user "Copy New InfiniDB Package to Module " -send "ssh $USERNAME@$SERVER 'rm -f /root/infinidb-*.$PKGTYPE'\n" +expect -re "# " +send_user "Copy New calpont Package to Module " +send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.$PKGTYPE'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } expect { - -re {[$#] } { } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "# " { } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } set timeout 30 +expect -re "# " +send "scp $CALPONTRPM $USERNAME@$SERVER:$CALPONTRPM\n" +if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + } +} +set timeout 120 expect { - -re {[$#] } { } + -re "100%" { send_user "DONE" } abort + -re "directory" { send_user "ERROR\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } - -send "scp $CALPONTRPM1 $CALPONTRPM2 $CALPONTMYSQLRPM $CALPONTMYSQLDRPM $USERNAME@$SERVER:.;$PKGERASE dummy\n" +send_user "\n" +#sleep to make sure it's finished +sleep 5 +# +# send the package +# +send_user "Copy New calpont-mysql Package to Module " +send "scp $CALPONTMYSQLRPM $USERNAME@$SERVER:$CALPONTMYSQLRPM\n" if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + } } set timeout 120 expect { - "package dummy" { send_user "DONE" } - "directory" { send_user "ERROR\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "100%" { send_user "DONE" } abort + -re "directory" { send_user "ERROR\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" - #sleep to make sure it's finished sleep 5 -if { $CALPONTRPM3 != "dummy.rpm" } { - expect -re {[$#] } - send_user "Copy new InfiniDB Enterprise Packages to Module " - send "scp $CALPONTRPM3 $USERNAME@$SERVER:.\n" - if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } - } - set timeout 120 - expect { - "100%" { send_user "DONE" } - "directory" { send_user "ERROR\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - } - send_user "\n" +# +# send the package +# +send_user "Copy New calpont-mysqld Package to Module " +send "scp $CALPONTMYSQLDRPM $USERNAME@$SERVER:$CALPONTMYSQLDRPM\n" +if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + } } - +set timeout 120 +expect { + -re "100%" { send_user "DONE" } abort + -re "directory" { send_user "ERROR\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } +} +send_user "\n" #sleep to make sure it's finished sleep 5 - # if { $INSTALLTYPE == "initial"} { # # install package # - send_user "Install InfiniDB Packages on Module " - - send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTRPM1 $CALPONTRPM2;$PKGERASE dummy'\n" + send_user "Install calpont Package on Module " + send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTRPM'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - set timeout 180 + set timeout 60 expect { - "package dummy" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "needs" { send_user "ERROR: disk space issue\n" ; exit 1 } - "conflicts" { send_user "ERROR: File Conflict issue\n" ; exit 1 } - } - - if { $CALPONTRPM3 != "dummy.rpm" } { - expect -re {[$#] } - send_user "\n" - send_user "Install InfiniDB Enterprise Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTRPM3'\n" - if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } - } - set timeout 60 - expect { - "completed" { send_user "DONE" } - "Setting up" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "conflicts" { send_user "ERROR: File Conflict issue\n" ; exit 1 } - } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: file not found\n" ; exit 1 } } - } else { # # upgrade package # - send_user "Upgrade InfiniDB Packages on Module " - - send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTRPM1 $CALPONTRPM2;$PKGERASE dummy'\n" + send_user "Upgrade calpont Package on Module " + send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTRPM'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 60 expect { - "package dummy" { send_user "DONE" } - "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } - - if { $CALPONTRPM3 != "dummy.rpm" } { - send_user "\n" - send_user "Upgrade InfiniDB Enterprise Packages on Module " - - send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTRPM3'\n" - if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } - } - set timeout 60 - expect { - "completed" { send_user "DONE" } - "Setting up" { send_user "DONE" } - "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - } - } - } send_user "\n" -#sleep to make sure it's finished -sleep 5 set timeout 30 -#expect -re {[$#] } +expect -re "# " +#sleep to make sure rpm install has finsihed +sleep 10 if { $INSTALLTYPE == "initial"} { # - # copy over InfiniDB config file + # copy over calpont config file # - send_user "Copy InfiniDB Config file to Module " + send_user "Copy Calpont Config file to Module " send "scp $INSTALLDIR/etc/* $USERNAME@$SERVER:$INSTALLDIR/etc/.\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" #sleep to make sure it's finished @@ -326,36 +310,40 @@ if { $INSTALLTYPE == "initial"} { if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" #sleep to make sure it's finished sleep 5 # - # copy over InfiniDB OS files + # copy over calpont OS files # - send_user "Copy InfiniDB OS files to Module " + send_user "Copy Calpont OS files to Module " send "scp $INSTALLDIR/local/etc/$MODULE/* $USERNAME@$SERVER:$INSTALLDIR/local/.\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } # send_user "\n" @@ -365,21 +353,23 @@ if { $INSTALLTYPE == "initial"} { # Start module installer to setup Custom OS files # send_user "Run Module Installer " - send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/module_installer.sh --module=pm'\n" + send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/module_installer.sh pm'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "!!!Module" { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "FAILED" { send_user "ERROR: missing OS file\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No such file" { send_user "ERROR: File Not Found\n" ; exit 1 } + -re "!!!Module" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "FAILED" { send_user "ERROR: missing OS file\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: file not found\n" ; exit 1 } } send_user "\n" } @@ -388,7 +378,7 @@ if { $INSTALLTYPE == "initial"} { # check InfiniDB syslog functionality # set timeout 30 -#expect -re {[$#] } +expect -re "# " send_user "Check InfiniDB system logging functionality " send " \n" @@ -397,21 +387,23 @@ send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/syslogSetup.sh check'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "Logging working" { send_user "DONE" } + -re "Logging working" { send_user "DONE" } abort timeout { send_user "DONE" } - "not working" { send_user "WARNING: InfiniDB system logging functionality not working" } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "not working" { send_user "WARNING: InfiniDB system logging functionality not working" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: file not found\n" ; exit 1 } } send_user "\n" # send_user "\nInstallation Successfully Completed on '$MODULE'\n" exit 0 -# vim:ts=4 sw=4: diff --git a/oam/install_scripts/post-install b/oam/install_scripts/post-install old mode 100755 new mode 100644 index 693be89a..08abbab0 --- a/oam/install_scripts/post-install +++ b/oam/install_scripts/post-install @@ -1,50 +1,22 @@ #!/bin/bash # -# $Id: post-install 3705 2013-08-07 19:47:20Z dhill $ +# $Id: post-install 1886 2010-04-01 18:30:38Z dhill $ # # Post-install steps for calpont install prefix=/usr/local -installdir=$prefix/Calpont rpmmode=install -user=$USER -if [ -z "$user" ]; then - user=root -fi -quiet=0 for arg in "$@"; do if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then prefix="`echo $arg | awk -F= '{print $2}'`" - installdir=$prefix/Calpont elif [ `expr -- "$arg" : '--rpmmode='` -eq 10 ]; then rpmmode="`echo $arg | awk -F= '{print $2}'`" - elif [ `expr -- "$arg" : '--installdir='` -eq 13 ]; then - installdir="`echo $arg | awk -F= '{print $2}'`" - prefix=`dirname $installdir` - elif [ `expr -- "$arg" : '--user='` -eq 7 ]; then - user="`echo $arg | awk -F= '{print $2}'`" - elif [ `expr -- "$arg" : '--quiet'` -eq 7 ]; then - quiet=1 - elif [ `expr -- "$arg" : '--plugin='` -eq 9 ]; then - plugin="`echo $arg | awk -F= '{print $2}'`" else - echo "post-install: ignoring unknown argument: $arg" 1>&2 + echo "ignoring unknown argument: $arg" 1>&2 fi done -#remove ending '/' -case "$installdir" in -*/) - installdir=${installdir%/*} - ;; -esac - -if [ $installdir != "/usr/local/Calpont" ]; then - export INFINIDB_INSTALL_DIR=$installdir - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$installdir/lib -fi - #check 64-bit OS compatiable arch=`uname -m` patcnt=`expr "$arch" : 'i.86'` @@ -53,309 +25,82 @@ if [ $patcnt -ne 0 ]; then is64bitos=0 fi is64bitpkg=1 -file $installdir/bin/PrimProc | grep '64-bit' >/dev/null 2>&1 +file ${prefix}/Calpont/bin/PrimProc | grep '64-bit' >/dev/null 2>&1 if [ $? -ne 0 ]; then is64bitpkg=0 fi if [ $is64bitpkg -eq 1 -a $is64bitos -ne 1 ]; then - echo "ERROR: Incompatiable Version, package is intended for a x86_64 architecture" + echo "ERROR: Incompatible version, package is intended for a x86_64 architecture" echo "exiting...." exit 1 fi -if [ ! -f $installdir/etc/Calpont.xml ]; then - echo "$installdir/etc/Calpont.xml not found, exiting" +if [ ! -f ${prefix}/Calpont/etc/Calpont.xml ]; then + echo "${prefix}/Calpont/etc/Calpont.xml not found, exiting" exit 1 fi -cd $installdir/lib || exit 1 +cd ${prefix}/Calpont/lib || exit 1 for lib in *.so.1.0.0; do blib=`basename $lib .1.0.0` ln -sf $lib $blib + ln -sf $lib $blib.1 done -chown -h $user.$user *.so >/dev/null 2>&1 +chown -h root.root *.so if [ -f libnetsnmp.so.5.2.1 ]; then for lib in *.so.5.2.1; do blib=`basename $lib .5.2.1` ln -sf $lib $blib ln -sf $lib ${blib}.5 done - chown -h $user.$user *.so *.so.5 >/dev/null 2>&1 -fi -if [ -f libstdc++.so.6.0.14 ]; then - ln -sf libstdc++.so.6.0.14 libstdc++.so.6 - chown -h $user.$user libstdc++.so.6 >/dev/null 2>&1 + chown -h root.root *.so *.so.5 fi -ln -sf libjemalloc.so.3.3.0 libjemalloc.so -chown -h $user.$user libjemalloc.so >/dev/null 2>&1 - -# TODO-based on early experience with HDP it doesn't install bigtop -# so the code below will not correctly detect JAVA_HOME. Need to -# decide how to handle -# Autodetect JAVA_HOME if not defined -#if [ -e /usr/libexec/bigtop-detect-javahome ]; then -#. /usr/libexec/bigtop-detect-javahome -#elif [ -e /usr/lib/bigtop-utils/bigtop-detect-javahome ]; then -#. /usr/lib/bigtop-utils/bigtop-detect-javahome -#fi -#ln -sf $JAVA_HOME/jre/lib/amd64/server/libjvm.so -#chown -h $user.$user libjvm.so >/dev/null 2>&1 - cd / - -test -d /var/log/Calpont || mkdir /var/log/Calpont >/dev/null 2>&1 -test -d /var/log/Calpont/archive || mkdir /var/log/Calpont/archive >/dev/null 2>&1 -test -d /var/log/Calpont/corefiles || mkdir /var/log/Calpont/corefiles >/dev/null 2>&1 -test -d /var/log/Calpont/trace || mkdir /var/log/Calpont/trace >/dev/null 2>&1 +test -d /var/log/Calpont || mkdir /var/log/Calpont +test -d /var/log/Calpont/archive || mkdir /var/log/Calpont/archive +test -d /var/log/Calpont/corefiles || mkdir /var/log/Calpont/corefiles +test -d /var/log/Calpont/trace || mkdir /var/log/Calpont/trace # make sure trace dir is world-writable and sticky -chmod 1777 /var/log/Calpont/trace >/dev/null 2>&1 -test -d $installdir/data || mkdir $installdir/data -test -d $installdir/data1 || mkdir $installdir/data1 -test -d $installdir/data1/systemFiles || mkdir $installdir/data1/systemFiles -test -d $installdir/data1/systemFiles/dbrm || mkdir $installdir/data1/systemFiles/dbrm -test -d $installdir/data1/systemFiles/dataTransaction || mkdir $installdir/data1/systemFiles/dataTransaction -test -d $installdir/data1/systemFiles/dataTransaction/archive || mkdir $installdir/data1/systemFiles/dataTransaction/archive -chmod 1777 $installdir/data1 >/dev/null 2>&1 -chmod -R 1777 $installdir/data1/systemFiles >/dev/null 2>&1 -chmod 1777 $installdir/etc > /dev/null 2>&1 -test -d /var/log/Calpont/data || ln -sf $installdir/data1/systemFiles/dataTransaction /var/log/Calpont/data > /dev/null 2>&1 - -#create the bulk-load dirs -mkdir -p $installdir/data/bulk/data/import >/dev/null 2>&1 -mkdir -p $installdir/data/bulk/log >/dev/null 2>&1 -mkdir -p $installdir/data/bulk/job >/dev/null 2>&1 -mkdir -p $installdir/data/bulk/rollback >/dev/null 2>&1 -mkdir -p $installdir/data/bulk/tmpjob >/dev/null 2>&1 -rm -f $installdir/data/bulk/tmpjob/* >/dev/null 2>&1 +chmod 1777 /var/log/Calpont/trace +test -d ${prefix}/Calpont/data || mkdir ${prefix}/Calpont/data +test -d ${prefix}/Calpont/data1 || mkdir ${prefix}/Calpont/data1 +test -d ${prefix}/Calpont/data1/systemFiles || mkdir ${prefix}/Calpont/data1/systemFiles +test -d ${prefix}/Calpont/data1/systemFiles/dataTransaction || mkdir ${prefix}/Calpont/data1/systemFiles/dataTransaction +test -d ${prefix}/Calpont/data1/systemFiles/dataTransaction/archive || mkdir ${prefix}/Calpont/data1/systemFiles/dataTransaction/archive +test -d ${prefix}/Calpont/data1/systemFiles/dbrm || mkdir ${prefix}/Calpont/data1/systemFiles/dbrm +chmod -R 1777 ${prefix}/Calpont/data1/systemFiles/dbrm > /dev/null 2>&1 +chmod -R 1777 ${prefix}/Calpont/data1 > /dev/null 2>&1 +chmod -R 1777 ${prefix}/Calpont/etc > /dev/null 2>&1 +test -d /var/log/Calpont/data || ln -sf ${prefix}/Calpont/data1/systemFiles/dataTransaction /var/log/Calpont/data #create infinidb temp file directory -mkdir -p /tmp/infinidb_tmp_files >/dev/null 2>&1 +mkdir -p /tmp/infinidb_tmp_files + +#create the bulk-load dirs +mkdir -p ${prefix}/Calpont/data/bulk/data/import >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/log >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/job >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/rollback >/dev/null 2>&1 +mkdir -p ${prefix}/Calpont/data/bulk/tmpjob >/dev/null 2>&1 +rm -f ${prefix}/Calpont/data/bulk/tmpjob/* >/dev/null 2>&1 #setup core file directory and link mkdir /var/log/Calpont/corefiles > /dev/null 2>&1 -chmod 777 /var/log/Calpont/corefiles > /dev/null 2>&1 +chmod 777 /var/log/Calpont/corefiles #create mount directories mkdir /mnt/tmp > /dev/null 2>&1 mkdir /var/log/Calpont/data/archive > /dev/null 2>&1 -#remove this fstab back file if its left over from 2.x version -if test -f /etc/fstab.calpontSave ; then - rm -f /etc/fstab.calpontSave > /dev/null 2>&1 -fi - - # install Calpont Log Rotate File -test -d $installdir/mysql/db || mkdir -p $installdir/mysql/db -cp $installdir/bin/calpontLogRotate /etc/logrotate.d/calpont > /dev/null 2>&1 -rm -rf $installdir/mysql/db/infinidb_log_archive > /dev/null 2>&1 - -# delete Calpont shared memory segments -$installdir/bin/Calpont/bin/clearShm > /dev/null 2>&1 - -#setup the infinidb service script -rm -f /etc/init.d/infinidb >/dev/null 2>&1 -cp $installdir/bin/infinidb /etc/init.d >/dev/null 2>&1 -if [ -x /sbin/chkconfig ]; then - /sbin/chkconfig --add infinidb > /dev/null 2>&1 - /sbin/chkconfig infinidb on > /dev/null 2>&1 -elif [ -x /usr/sbin/update-rc.d ]; then - /usr/sbin/update-rc.d infinidb defaults 99 > /dev/null 2>&1 -else - echo "" - echo "Package 'chkconfig' or 'update-rc.d' not installed, contact your sysadmin if you want to setup to autostart for infinidb" -fi - -#setup InfiniDB system logging -if [ $user = "root" ]; then - $installdir/bin/syslogSetup.sh install > /tmp/syslog_install.log 2>&1 - chmod 777 /dev/shm -elif [ -z "$NO_NONROOT_SUDO" ]; then - sudo $installdir/bin/syslogSetup.sh --installdir=$installdir install > /tmp/syslog_install.log 2>&1 - sudo chown $user:$user $installdir/etc/Calpont.xml - sudo chmod 777 /var/log - sudo chmod -R 777 /var/log/Calpont - sudo chmod 777 /dev/shm - sudo rm -f /var/lock/subsys/mysql-Calpont - sudo rm -f /tmp/StopCalpont - - sed -i -e s@/usr/local/Calpont@$installdir@g $installdir/bin/infinidb.def - sudo cp $installdir/bin/infinidb.def /etc/default/infinidb -fi - -#check if InfiniDB system logging was setup -cat /tmp/syslog_install.log | grep 'No System Logging' >/dev/null 2>&1 -if [ $? -eq 0 ]; then - cat /tmp/syslog_install.log -fi - -#setup alias commands -eval userhome=~$user -bashFile=$userhome/.bashrc -touch ${bashFile} -if [ $installdir != "/usr/local/Calpont" ]; then - sed -i -e s@/usr/local/Calpont@$installdir@g $installdir/bin/calpontAlias -fi -egrep -qs 'Calpont Database Platform Alias Commands' ${bashFile} -rc1=$? -egrep -qs 'InfiniDB Alias Commands' ${bashFile} -rc2=$? -if [ $rc1 -ne 0 -a $rc2 -ne 0 ]; then - rm -f ${bashFile}.calpontSave - cp ${bashFile} ${bashFile}.calpontSave >/dev/null 2>&1 - cat $installdir/bin/calpontAlias >> ${bashFile} - echo " " >> ${bashFile} -fi - -#check and get amazon EC2 env variables -if [ -n "$EC2_HOME" ]; then - $installdir/bin/setConfig -d Installation EC2_HOME $EC2_HOME >/dev/null 2>&1 - - if [ -n "$EC2_HOME" ]; then - $installdir/bin/setConfig -d Installation JAVA_HOME $JAVA_HOME >/dev/null 2>&1 - fi - - $installdir/bin/setConfig -d Installation EC2_PATH $PATH:/home/ec2/bin:/opt/aws/bin >/dev/null 2>&1 -fi +cp ${prefix}/Calpont/bin/calpontLogRotate /etc/logrotate.d/calpont > /dev/null 2>&1 +cp ${prefix}/Calpont/bin/transactionLog /etc/cron.d/. +chmod 644 /etc/cron.d/transactionLog #log install message -test -f $installdir/post/functions && . $installdir/post/functions -LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$installdir/lib $installdir/bin/cplogger -i 19 "***** InfiniDB Installed *****" - -#setup hadoop -hadoop=`which hadoop 2>/dev/null` -if [ -z $hadoop ]; then - #not hadoop - check for non-root user - if [ $installdir != "/usr/local/Calpont" -a $quiet -eq 0 ]; then -cat < /tmp/hdfs-config-test.log 2>&1 - if [ $? -ne 0 ]; then - PASS=false - fi - else - PASS=false - fi - - if [ !PASS ]; then - #Failed, see what passes - . $installdir/bin/setenv-hdfs-20 - $installdir/bin/hdfsCheck $installdir/lib/hdfs-20.so > /tmp/hdfs-20-test.log 2>&1 - if [ $? -eq 0 ]; then - #Passed, save - DATAPLUGIN=$installdir/lib/hdfs-20.so - DATAENV=setenv-hdfs-20 - else - . $installdir/bin/setenv-hdfs-12 - $installdir/bin/hdfsCheck $installdir/lib/hdfs-12.so > /tmp/hdfs-12-test.log 2>&1 - if [ $? -eq 0 ]; then - #Passed, save - DATAPLUGIN=$installdir/lib/hdfs-12.so - DATAENV=setenv-hdfs-12 - else - DATAPLUGIN="unassigned" - DATAENV="unassigned" - fi - fi - - #set in config file - $installdir/bin/setConfig -d SystemConfig DataFilePlugin $DATAPLUGIN >/dev/null 2>&1 - $installdir/bin/setConfig -d SystemConfig DataFileEnvFile $DATAENV >/dev/null 2>&1 - - #hadoop test error - if [ $DATAENV == "unassigned" ]; then - #check for non-root user - if [ $installdir != "/usr/local/Calpont" -a $quiet -eq 0 ]; then -cat <&2 fi done -if [ $installdir != "/usr/local/Calpont" ]; then - export INFINIDB_INSTALL_DIR=$installdir - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql -fi - -if [ -f $installdir/lib/libcalmysql.so.1.0.0 ]; then - libcalmysql=$installdir/lib/libcalmysql.so.1.0.0 - libudfsdk=$installdir/lib/libudf_mysql.so.1.0.0 -elif [ -f $installdir/lib/libcalmysql.so.1 ]; then - libcalmysql=$installdir/lib/libcalmysql.so.1 - libudfsdk=$installdir/lib/libudf_mysql.so.1 +if [ -f ${prefix}/Calpont/lib/libcalmysql.so.1.0.0 ]; then + libcalmysql=${prefix}/Calpont/lib/libcalmysql.so.1.0.0 +elif [ -f ${prefix}/Calpont/lib/libcalmysql.so.1 ]; then + libcalmysql=${prefix}/Calpont/lib/libcalmysql.so.1 else libcalmysql= fi -if [ -d $installdir/mysql/lib/mysql/plugin -a -n "$libcalmysql" ]; then - cd $installdir/mysql/lib/mysql/plugin +if [ -d ${prefix}/Calpont/mysql/lib/mysql/plugin -a -n "$libcalmysql" ]; then + cd ${prefix}/Calpont/mysql/lib/mysql/plugin ln -sf $libcalmysql libcalmysql.so - ln -sf $libcalmysql libcalmysqlent.so - ln -sf $libudfsdk libudf_mysql.so fi - -if [ $installdir != "/usr/local/Calpont" ]; then - sed -i -e s@/usr/local/Calpont@$installdir@g $installdir/mysql/my.cnf -fi - -if [ -x $installdir/mysql/mysql-Calpont ]; then +if [ -x /etc/init.d/mysql-Calpont ]; then # Restart in the same way that mysqld will be started normally. - $installdir/mysql/mysql-Calpont start + /etc/init.d/mysql-Calpont start sleep 2 # Install various Calpont stuff... - $installdir/mysql/install_calpont_mysql.sh --password=$password --installdir=$installdir + ${prefix}/Calpont/mysql/install_calpont_mysql.sh --password=$password - $installdir/mysql/mysql-Calpont stop + /etc/init.d/mysql-Calpont stop fi exit 0 - diff --git a/oam/install_scripts/post-mysqld-install b/oam/install_scripts/post-mysqld-install index ad3df10c..f80544de 100755 --- a/oam/install_scripts/post-mysqld-install +++ b/oam/install_scripts/post-mysqld-install @@ -1,46 +1,34 @@ #!/bin/bash # -# $Id: post-mysqld-install 3661 2013-06-25 22:04:33Z dhill $ +# $Id: post-mysqld-install 1995 2010-07-02 13:59:21Z rdempsey $ # -# Post-install steps for infinidb-mysql install +# Post-install steps for calpont-mysqld install prefix=/usr/local -installdir=$prefix/Calpont rpmmode=install -user=mysql -if [ $EUID -ne 0 ]; then - user=$USER -fi - for arg in "$@"; do if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then prefix="`echo $arg | awk -F= '{print $2}'`" - installdir=$prefix/Calpont elif [ `expr -- "$arg" : '--rpmmode='` -eq 10 ]; then rpmmode="`echo $arg | awk -F= '{print $2}'`" - elif [ `expr -- "$arg" : '--installdir='` -eq 13 ]; then - installdir="`echo $arg | awk -F= '{print $2}'`" - prefix=`dirname $installdir` - elif [ `expr -- "$arg" : '--user='` -eq 7 ]; then - user="`echo $arg | awk -F= '{print $2}'`" else - echo "post-mysqld-install: ignoring unknown argument: $arg" 1>&2 + echo "ignoring unknown argument: $arg" 1>&2 fi done -cd $installdir/mysql/lib/mysql +cd ${prefix}/Calpont/mysql/lib/mysql for file in libmysqlclient libmysqlclient_r; do ln -sf $file.so.16.0.0 $file.so ln -sf $file.so.16.0.0 $file.so.16 done -cd $installdir/mysql/lib/mysql/plugin +cd ${prefix}/Calpont/mysql/lib/mysql/plugin for file in ha_archive ha_blackhole ha_federated ha_innodb ha_innodb_plugin; do ln -sf $file.so.0.0.0 $file.so ln -sf $file.so.0.0.0 $file.so.0 done ### taken from MySQL-server-5.1.30-0.glibc23.i386.rpm -mysql_datadir=$installdir/mysql/db +mysql_datadir=${prefix}/Calpont/mysql/db # Create data directory if needed if test ! -d $mysql_datadir; then mkdir -m 755 $mysql_datadir; fi @@ -49,53 +37,50 @@ if test ! -d $mysql_datadir/test; then mkdir $mysql_datadir/test; fi # Create a MySQL user and group. Do not report any problems if it already # exists. -groupadd -r $user 2> /dev/null || true -useradd -m -r -d $mysql_datadir -s /bin/bash -c "MySQL server" -g $user $user 2> /dev/null || true +groupadd -r mysql 2> /dev/null || true +useradd -m -r -d $mysql_datadir -s /bin/bash -c "MySQL server" -g mysql mysql 2> /dev/null || true # The user may already exist, make sure it has the proper group nevertheless (BUG#12823) -usermod -g $user $user 2> /dev/null || true +usermod -g mysql mysql 2> /dev/null || true # Change permissions so that the user that will run the MySQL daemon # owns all database files. -chown -R $user:$user $mysql_datadir +chown -R mysql:mysql $mysql_datadir # Initiate databases if needed -if [ $installdir != "/usr/local/Calpont" ]; then - sed -i -e s@/usr/local/Calpont@$installdir@g $installdir/mysql/my.cnf -fi - -# InfiniDB testing hook... -test -x /usr/local/bin/idb-testing-mysql-pre-start && /usr/local/bin/idb-testing-mysql-pre-start $installdir/mysql - ### Don't give the user the notes, we'll fix them ourselves... -$installdir/mysql/bin/mysql_install_db --rpm --user=$user --defaults-file=$installdir/mysql/my.cnf --basedir=$installdir/mysql >/dev/null +${prefix}/Calpont/mysql/bin/mysql_install_db --rpm --user=mysql --defaults-file=${prefix}/Calpont/mysql/my.cnf --basedir=${prefix}/Calpont/mysql >/dev/null # Change permissions again to fix any new files. -chown -R $user:$user $mysql_datadir +chown -R mysql:mysql $mysql_datadir # Fix permissions for the permission database so that only the user # can read them. chmod -R og-rw $mysql_datadir/mysql # Change permissions again to fix any new files. -chown -R $user.$user $installdir/mysql +chown -R mysql.mysql ${prefix}/Calpont/mysql + +test -e /etc/init.d/mysql-Calpont || cp ${prefix}/Calpont/mysql/mysql-Calpont /etc/init.d -test -e /etc/init.d/mysql-Calpont || cp $installdir/mysql/mysql-Calpont /etc/init.d >/dev/null 2>&1 +# Make MySQL start/shutdown automatically when the machine does it. +if [ -x /sbin/chkconfig ]; then + /sbin/chkconfig --add mysql-Calpont > /dev/null 2>&1 + /sbin/chkconfig mysql-Calpont on > /dev/null 2>&1 +elif [ -x /usr/sbin/update-rc.d ]; then + /usr/sbin/update-rc.d mysql-Calpont defaults > /dev/null 2>&1 +fi -if [ -f $installdir/lib/libcalmysql.so.1.0.0 ]; then - libcalmysql=$installdir/lib/libcalmysql.so.1.0.0 - libudfsdk=$installdir/lib/libudf_mysql.so.1.0.0 -elif [ -f $installdir/lib/libcalmysql.so.1 ]; then - libcalmysql=$installdir/lib/libcalmysql.so.1 - libudfsdk=$installdir/lib/libudf_mysql.so.1 +if [ -f ${prefix}/Calpont/lib/libcalmysql.so.1.0.0 ]; then + libcalmysql=${prefix}/Calpont/lib/libcalmysql.so.1.0.0 +elif [ -f ${prefix}/Calpont/lib/libcalmysql.so.1 ]; then + libcalmysql=${prefix}/Calpont/lib/libcalmysql.so.1 else libcalmysql= fi if [ -n "$libcalmysql" ]; then - cd $installdir/mysql/lib/mysql/plugin + cd ${prefix}/Calpont/mysql/lib/mysql/plugin ln -sf $libcalmysql libcalmysql.so - ln -sf $libcalmysql libcalmysqlent.so - ln -sf $libudfsdk libudf_mysql.so fi exit 0 diff --git a/oam/install_scripts/postInstall.sh b/oam/install_scripts/postInstall.sh index 11783a5e..2901fc43 100755 --- a/oam/install_scripts/postInstall.sh +++ b/oam/install_scripts/postInstall.sh @@ -78,8 +78,8 @@ send_user "Stop Calpont System " expect -re "# " send "$INSTALLDIR/bin/calpontConsole stopSystem INSTALL y\n" expect { - -re "# " { send_user "DONE" } - -re "**** stopSystem Failed" { send_user "INFO: System not running" } + -re "# " { send_user "DONE" } abort + -re "**** stopSystem Failed" { send_user "INFO: System not running" } abort } send_user "\n" # @@ -89,10 +89,10 @@ send_user "Erase Calpont Package on Module " expect -re "# " send "rpm -e --nodeps calpont\n" expect { - -re "# " { send_user "DONE" } - -re "uninstall completed" { send_user "DONE" } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort -re "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; exit -1 } - -re "not installed" { send_user "INFO: Package not installed" } + -re "not installed" { send_user "INFO: Package not installed" } abort } send_user "\n" @@ -103,7 +103,7 @@ set timeout 60 send_user "Install Calpont Package on Module " send "rpm -ivh $RPMPACKAGE\n" expect { - -re "completed" { send_user "DONE" } + -re "completed" { send_user "DONE" } abort -re "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } @@ -124,7 +124,7 @@ set timeout 380 send_user "Run System Installer " send "$INSTALLDIR/bin/installer $RPMPACKAGE initial $PASSWORD n 0\n" expect { - -re "reboot request successful" { } + -re "reboot request successful" { } abort -re "error" { send_user "FAILED" ; exit -1 } } diff --git a/oam/install_scripts/pre-uninstall b/oam/install_scripts/pre-uninstall index 9700c858..bdf10385 100755 --- a/oam/install_scripts/pre-uninstall +++ b/oam/install_scripts/pre-uninstall @@ -27,10 +27,11 @@ for arg in "$@"; do elif [ `expr -- "$arg" : '--quiet'` -eq 7 ]; then quiet=1 else - echo "post-uninstall: ignoring unknown argument: $arg" 1>&2 + echo "post-install: ignoring unknown argument: $arg" 1>&2 fi done + #stop services $installdir/bin/infinidb stop > /dev/null 2>&1 if test -f /etc/init.d/calpont-Mysql ; then @@ -52,13 +53,12 @@ fi if test -f /etc/rc.local.calpontSave ; then mv -f /etc/rc.local.calpontSave /etc/rc.local > /dev/null 2>&1 fi - + #remove log file directories #rm -rf /var/log/Calpont > /dev/null 2>&1 #rm -f $installdir/mysql/db/*.err > /dev/null 2>&1 rm -f /var/log/Calpont/activeAlarms > /dev/null 2>&1 rm -f /var/log/Calpont/*.log1 > /dev/null 2>&1 -rm -rf $installdir/mysql/db/infinidb_log_archive > /dev/null 2>&1 # remove Calpont Log Rotate File abd Transaction Log File rm -f /etc/logrotate.d/calpont > /dev/null 2>&1 @@ -84,21 +84,16 @@ rm -f /var/lock/subsys/infinidb rm -f /tmp/pkgcheck rm -f /tmp/upgrade-status.log.* rm -f /tmp/mount.log +rm -f /tmp/idb* rm -f $installdir/data/bulk/tmpjob/* >/dev/null 2>&1 rm -rf /tmp/infinidb_tmp_files rm -f $installdir/local/moveDbrootTransactionLog -#delete any old setenv files under home directory -if [ $user = "root" ]; then - rm -f /root/setenv-hdfs* -else - rm -f /home/$user/setenv-hdfs* -fi # delete core files -#rm -f /var/log/Calpont/corefiles/* > /dev/null 2>&1 +rm -f /var/log/Calpont/corefiles/* > /dev/null 2>&1 -#uninstall InfiniDB system logging +#un-setup InfiniDB system logging if [ -x $installdir/bin/syslogSetup.sh ]; then if [ $user = "root" ]; then $installdir/bin/syslogSetup.sh uninstall >/dev/null 2>&1 @@ -115,11 +110,9 @@ elif [ -x /usr/sbin/update-rc.d ]; then /usr/sbin/update-rc.d -f infinidb remove > /dev/null 2>&1 fi -if [ $quiet != 1 ]; then - #make copy of Calpont.xml - /bin/cp -f $installdir/etc/Calpont.xml $installdir/etc/Calpont.xml.rpmsave > /dev/null 2>&1 - /bin/cp -f $installdir/mysql/my.cnf $installdir/mysql/my.cnf.rpmsave > /dev/null 2>&1 -fi +#make copy of Calpont.xml +/bin/cp -f $installdir/etc/Calpont.xml $installdir/etc/Calpont.xml.rpmsave > /dev/null 2>&1 +/bin/cp -f $installdir/mysql/my.cnf $installdir/mysql/my.cnf.rpmsave > /dev/null 2>&1 #umount file systems if [ $user = "root" ]; then diff --git a/oam/install_scripts/remote_command.sh b/oam/install_scripts/remote_command.sh index 6878bcf2..798974c0 100755 --- a/oam/install_scripts/remote_command.sh +++ b/oam/install_scripts/remote_command.sh @@ -1,6 +1,6 @@ #!/usr/bin/expect # -# $Id: remote_command.sh 3495 2012-12-17 22:51:40Z dhill $ +# $Id: remote_command.sh 3496 2012-12-17 22:51:51Z dhill $ # # Remote command execution script to another server # Argument 1 - Remote Server Host Name or IP address @@ -8,32 +8,19 @@ # Argument 3 - Command # Argument 4 - debug flag # Argument 5 - Remote user name (optional) -# Argument 6 - Force a tty to be allocated (optional) -set stty_init {cols 512 -opost}; set timeout 30 set SERVER [lindex $argv 0] set PASSWORD [lindex $argv 1] set COMMAND [lindex $argv 2] set DEBUG [lindex $argv 3] - -if {[info exists env(USER)]} { - set USERNAME $env(USER) -} else { - set USERNAME "root" -} - +set USERNAME $env(USER) set UNM [lindex $argv 4] -if { $UNM != "" && $UNM != "-" } { +if { $UNM != "" } { set USERNAME "$UNM" } -set TTY "" -set TTYOPT [lindex $argv 5] -if { $TTYOPT != "" } { - set TTY "-t" -} log_user $DEBUG spawn -noecho /bin/bash -expect -re {[$#] } +expect -re "\[#$] " if { $PASSWORD == "ssh" } { set PASSWORD "" @@ -42,28 +29,28 @@ if { $PASSWORD == "ssh" } { # # send command # -send "ssh $TTY $USERNAME@$SERVER $COMMAND\n" +send "ssh $USERNAME@$SERVER $COMMAND\n" expect { - "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1} - "service not known" { send_user " FAILED: Invalid Host\n" ; exit 1} - "ssh: connect to host" { send_user " FAILED: Invalid Host\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "Connection closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "authenticity" { send "yes\n" + -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1} + -re "service not known" { send_user " FAILED: Invalid Host\n" ; exit 1} + -re "ssh: connect to host" { send_user " FAILED: Invalid Host\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - -re {[$#] } { exit 0 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + -re "\[#$] " { exit 0 } } expect { - -re {[$#] } { exit 0 } - "Permission denied" { send_user " FAILED: Invalid password\n" ; exit 1 } - "(y or n)" { send "y\n" - expect -re {[$#] } { exit 0 } + -re "\[#$] " { exit 0 } + -re "Permission denied" { send_user " FAILED: Invalid password\n" ; exit 1 } + -re "(y or n)" { send "y\n" + expect -re "\[#$] " { exit 0 } } } exit 0 diff --git a/oam/install_scripts/remote_command_verify.sh b/oam/install_scripts/remote_command_verify.sh deleted file mode 100755 index d7ceb520..00000000 --- a/oam/install_scripts/remote_command_verify.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/expect -# -# $Id: remote_commend.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - Remote Server Host Name or IP address -# Argument 2 - Remote Server root password -# Argument 3 - Command -# Argument 4 - Good Response -# Argument 5 - Bad Response -# Argument 6 - timeout -# Argument 7 - Debug flag -set timeout 30 -set SERVER [lindex $argv 0] -set USERNAME [lindex $argv 1] -set PASSWORD [lindex $argv 2] -set COMMAND [lindex $argv 3] -set GOOD_RESPONSE [lindex $argv 4] -set BAD_RESPONSE [lindex $argv 5] -set timeout [lindex $argv 6] -set DEBUG [lindex $argv 7] -log_user $DEBUG -spawn -noecho /bin/bash -expect -re {[$#] } -# -# send command -# -send "ssh $USERNAME@$SERVER '$COMMAND'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - timeout { send_user "TIMEOUT\n" ; exit 2 } - -re "word: " { send "$PASSWORD\n" } abort - } - } - timeout { send_user "TIMEOUT\n" ; exit 2 } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } - -re "Permission denied" { send_user "FAILED: Invalid Password\n" ; exit 1 } - -re "word: " { send "$PASSWORD\n" } abort - -re $GOOD_RESPONSE { send_user " " ; exit 0 } - -re $BAD_RESPONSE { send_user "FAILED\n" ; exit 1 } - -re "parser error" { send_user "FAILED: System Calpont.xml parse error\n" ; exit 1 } -} -expect { - timeout { send_user "FAILED-TIMEOUT\n" ; exit 1 } - -re $GOOD_RESPONSE { send_user " " ; exit 0 } - -re $BAD_RESPONSE { send_user "FAILED\n" ; exit 1 } - -re "No such file" { send_user "FAILED\n" ; exit 1 } - -re "parser error" { send_user "FAILED: System Calpont.xml parse error\n" ; exit 1 } -} - -exit 1 - diff --git a/oam/install_scripts/remote_installer.sh b/oam/install_scripts/remote_installer.sh index c701ab19..1e937e9f 100755 --- a/oam/install_scripts/remote_installer.sh +++ b/oam/install_scripts/remote_installer.sh @@ -31,9 +31,9 @@ expect -re "word: " send "$PASSWORD\n" # check return expect { - -re "uninstall completed" { send_user " DONE" } - -re "# " { send_user " DONE" } - -re "not installed" { send_user " FAILED: Package not installed" } + -re "uninstall completed" { send_user " DONE" } abort + -re "# " { send_user " DONE" } abort + -re "not installed" { send_user " FAILED: Package not installed" } abort -re "Failed dependencies" { send_user " FAILED: Failed dependencies\n" ; exit } -re "Permission denied" { send_user " FAILED: Invalid password\n" ; exit } } @@ -48,8 +48,8 @@ expect -re "word: " send "$PASSWORD\n" # check return expect { - -re "100%" { send_user " DONE" } - -re "# " { send_user " DONE" } + -re "100%" { send_user " DONE" } abort + -re "# " { send_user " DONE" } abort -re "scp" { send_user " FAILED\n" ; send_user "\n*** Installation Failed\n" ; exit } @@ -70,8 +70,8 @@ expect -re "word: " send "$PASSWORD\n" # check return expect { - -re "completed" { send_user " DONE" } - -re "# " { send_user " DONE" } + -re "completed" { send_user " DONE" } abort + -re "# " { send_user " DONE" } abort -re "Failed dependencies" { send_user " FAILED: Failed dependencies\n" ; send_user "\n*** Installation Failed\n" ; exit } @@ -91,7 +91,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user " DONE" } + -re "# " { send_user " DONE" } abort -re "Permission denied" { send_user " FAILED: Invalid password\n" ; exit } } # diff --git a/oam/install_scripts/remote_scp_get.sh b/oam/install_scripts/remote_scp_get.sh index 1524b15c..950e149a 100755 --- a/oam/install_scripts/remote_scp_get.sh +++ b/oam/install_scripts/remote_scp_get.sh @@ -22,30 +22,30 @@ if { $PASSWORD == "ssh" } { # # send command # -expect -re {[$#] } +expect -re "# " send "scp $USERNAME$SERVER:$FILE .\n" expect { - "authenticity" { send "yes\n" + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "Connection timed out" { send_user "FAILED: Connection timed out\n" ; exit 1 } - "lost connection" { send_user "FAILED: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "Connection timed out" { send_user "FAILED: Connection timed out\n" ; exit 1 } + -re "lost connection" { send_user "FAILED: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } expect { - "100%" { send_user "DONE\n" } - "scp:" { send_user "FAILED\n" ; exit 1 } - "Permission denied" { send_user "FAILED: Invalid password\n" ; exit 1 } - "No such file or directory" { send_user "FAILED: No such file or directory\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "100%" { send_user "DONE\n" } abort + -re "scp:" { send_user "FAILED\n" ; exit 1 } + -re "Permission denied" { send_user "FAILED: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } } #sleep to make sure it's finished sleep 5 diff --git a/oam/install_scripts/remote_scp_put.sh b/oam/install_scripts/remote_scp_put.sh index 1c7a8154..b105b532 100644 --- a/oam/install_scripts/remote_scp_put.sh +++ b/oam/install_scripts/remote_scp_put.sh @@ -27,8 +27,8 @@ send "scp $FILE $USERNAME$SERVER:$FILE\n" expect { -re "authenticity" { send "yes\n" expect { - -re "word: " { send "$PASSWORD\n" } - -re "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } @@ -36,12 +36,12 @@ expect { -re "Connection timed out" { send_user "FAILED: Connection timed out\n" ; exit 1 } -re "lost connection" { send_user "FAILED: Connection refused\n" ; exit 1 } -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - -re "word: " { send "$PASSWORD\n" } - -re "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort -re "WARNING:" { send "rm -f /root/.ssh/known_hosts" ; exit 1 } } expect { - -re "100%" { send_user "DONE\n" } + -re "100%" { send_user "DONE\n" } abort -re "scp:" { send_user "FAILED\n" ; exit 1 } -re "Permission denied" { send_user "FAILED: Invalid password\n" ; exit 1 } -re "No such file or directory" { send_user "FAILED: Invalid file\n" ; exit 1 } diff --git a/oam/install_scripts/rsync.sh b/oam/install_scripts/rsync.sh old mode 100755 new mode 100644 index 174bd0b8..447a5cec --- a/oam/install_scripts/rsync.sh +++ b/oam/install_scripts/rsync.sh @@ -21,12 +21,12 @@ if { $PASSWORD == "ssh" } { set PASSWORD "" } -set COMMAND "rsync -vopgr -e ssh --exclude=mysql/ --exclude=test/ --exclude=infinidb_vtable/ --exclude=infinidb_querystats/ --exclude=calpontsys/ --include=*/ --include=*/* --exclude=* $installdir/mysql/db/ $USERNAME$SERVER:/usr/local/Calpont/mysql/db/" +set COMMAND "rsync -vuopg -e ssh --delete --exclude=*err --exclude=*pid -r $installdir/mysql/db $USERNAME$SERVER:/usr/local/Calpont/mysql/" # # run command # -set timeout 60 +set timeout 600 send "$COMMAND\n" expect { -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit -1} @@ -34,20 +34,19 @@ expect { -re "ssh: connect to host" { send_user " FAILED: Invalid Host\n" ; exit -1 } -re "authenticity" { send "yes\n" expect { - -re "word: " { send "$PASSWORD\n" } - -re "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - -re "word: " { send "$PASSWORD\n" } - -re "passphrase" { send "$PASSWORD\n" } - -re "total size" { exit 0 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } expect { - -re "total size" { exit 0 } + -re "# " { exit 0 } -re "Permission denied" { send_user " FAILED: Invalid password\n" ; exit 1 } -re "(y or n)" { send "y\n" - expect -re "total size" { exit 0 } + expect -re "# " { exit 0 } } } -exit 0 +exit 0 \ No newline at end of file diff --git a/oam/install_scripts/slave-rep-infinidb.sh b/oam/install_scripts/slave-rep-infinidb.sh deleted file mode 100644 index c46cafea..00000000 --- a/oam/install_scripts/slave-rep-infinidb.sh +++ /dev/null @@ -1,124 +0,0 @@ -#!/bin/bash -# -# $Id$ -# -# generic InfiniDB Slave Replication script. -# -# Notes: This script gets run by ProcMon during installs and upgrades: - -# check log for error -checkForError() { - grep ERROR /tmp/slave-rep-status.log > /tmp/error.check - if [ `cat /tmp/error.check | wc -c` -ne 0 ]; then - echo "ERROR: check log file: /tmp/slave-rep-status.log" - rm -f /tmp/error.check - exit 1; - fi - rm -f /tmp/error.check -} - -prefix=/usr/local -installdir=$prefix/Calpont -pwprompt= -for arg in "$@"; do - if [ `expr -- "$arg" : '--prefix='` -eq 9 ]; then - prefix="`echo $arg | awk -F= '{print $2}'`" - installdir=$prefix/Calpont - elif [ `expr -- "$arg" : '--password='` -eq 11 ]; then - password="`echo $arg | awk -F= '{print $2}'`" - pwprompt="--password=$password" - elif [ `expr -- "$arg" : '--installdir='` -eq 13 ]; then - installdir="`echo $arg | awk -F= '{print $2}'`" - prefix=`dirname $installdir` - elif [ `expr -- "$arg" : '--masteripaddr='` -eq 15 ]; then - masteripaddr="`echo $arg | awk -F= '{print $2}'`" - elif [ `expr -- "$arg" : '--masterlogfile='` -eq 16 ]; then - masterlogfile="`echo $arg | awk -F= '{print $2}'`" - elif [ `expr -- "$arg" : '--masterlogpos='` -eq 15 ]; then - masterlogpos="`echo $arg | awk -F= '{print $2}'`" - elif [ `expr -- "$arg" : '--port='` -eq 7 ]; then - port="`echo $arg | awk -F= '{print $2}'`" - fi -done - -test -f $installdir/post/functions && . $installdir/post/functions - -repUser="idbrep" -password="Calpont1" - ->/tmp/slave-rep-status.log - -# -# Run stop slave command -# -echo "Run stop slave command" >>/tmp/slave-rep-status.log -cat >/tmp/idb_slave-rep.sql <>/tmp/slave-rep-status.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/slave-rep-status.log - -checkForError - -# -# Run Change Master Command -# -echo "Run Change Master Command" >>/tmp/slave-rep-status.log -cat >/tmp/idb_slave-rep.sql <>/tmp/slave-rep-status.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/slave-rep-status.log - -checkForError - -# -# Run start slave command -# -echo "Run start slave command" >>/tmp/slave-rep-status.log -cat >/tmp/idb_slave-rep.sql <>/tmp/slave-rep-status.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/slave-rep-status.log - -checkForError - -# -# Run SHOW SLAVE STATUS -# -echo "Run SHOW MASTER STATUS to node log" >>/tmp/slave-rep-status.log -cat >/tmp/idb_slave-rep.sql <>/tmp/slave-rep-status.log -$installdir/mysql/bin/mysql \ - --defaults-file=$installdir/mysql/my.cnf \ - --user=root $pwprompt \ - calpontsys >/tmp/slave-rep-status.log - -checkForError - -#alls good, 'OK' for success -echo "OK" - diff --git a/oam/install_scripts/startupTests.sh b/oam/install_scripts/startupTests.sh index 8f7e3787..3875b9df 100755 --- a/oam/install_scripts/startupTests.sh +++ b/oam/install_scripts/startupTests.sh @@ -13,7 +13,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/functions diff --git a/oam/install_scripts/syslogSetup.sh b/oam/install_scripts/syslogSetup.sh index 1ba4186f..b087845d 100644 --- a/oam/install_scripts/syslogSetup.sh +++ b/oam/install_scripts/syslogSetup.sh @@ -31,7 +31,7 @@ done if [ $installdir != "/usr/local/Calpont" ]; then export INFINIDB_INSTALL_DIR=$installdir - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFINIDB_INSTALL_DIR/lib + export LD_LIBRARY_PATH=$INFINIDB_INSTALL_DIR/lib fi calpontSyslogFile=$installdir/bin/calpontSyslog @@ -88,13 +88,13 @@ if [ "$daemon" = "syslog-ng" ]; then echo "" fi elif [ "$daemon" = "rsyslog" ]; then - if [ -f /etc/rsyslog.conf ]; then - cnt=`grep "/etc/rsyslog.d/" /etc/rsyslog.conf | wc -l` - if [ $cnt -gt 0 ]; then - syslog_conf=/etc/rsyslog.d/calpont.conf - else - syslog_conf=/etc/rsyslog.conf - fi + if [ -d /etc/rsyslog.d ]; then + syslog_conf=/etc/rsyslog.d/calpont.conf + echo "" + echo "System logging being used: rsyslog" + echo "" + elif [ -f /etc/rsyslog.conf ]; then + syslog_conf=/etc/rsyslog.conf echo "" echo "System logging being used: rsyslog" echo "" @@ -105,12 +105,6 @@ elif [ "$daemon" = "syslog" ]; then echo "" echo "System logging being used: syslog" echo "" - elif [ -d /etc/syslog-ng/syslog-ng.conf ]; then - syslog_conf=/etc/syslog-ng/syslog-ng.conf - calpontSyslogFile=$installdir/bin/calpontSyslog-ng - echo "" - echo "System logging being used: syslog-ng" - echo "" fi else echo "" diff --git a/oam/install_scripts/system_installer.sh b/oam/install_scripts/system_installer.sh index 241be291..fb7ad550 100755 --- a/oam/install_scripts/system_installer.sh +++ b/oam/install_scripts/system_installer.sh @@ -14,11 +14,9 @@ set USERNAME root set MODULE [lindex $argv 0] set SERVER [lindex $argv 1] set PASSWORD [lindex $argv 2] -set RPMPACKAGE1 [lindex $argv 3] -set RPMPACKAGE2 [lindex $argv 4] -set RPMPACKAGE3 [lindex $argv 5] -set INSTALLTYPE [lindex $argv 6] -set DEBUG [lindex $argv 7] +set RPMPACKAGE [lindex $argv 3] +set INSTALLTYPE [lindex $argv 4] +set DEBUG [lindex $argv 5] log_user $DEBUG spawn -noecho /bin/bash # @@ -26,28 +24,28 @@ if { $INSTALLTYPE == "initial" || $INSTALLTYPE == "uninstall" } { # # erase package # - send_user "Erase InfiniDB Packages on Module " - expect -re {[$#] } - send "ssh $USERNAME@$SERVER 'rpm -e --nodeps --allmatches calpont >/dev/null 2>&1; rpm -e --nodeps --allmatches infinidb-enterprise >/dev/null 2>&1; rpm -e --nodeps --allmatches infinidb-libs infinidb-platform'\n" + send_user "Erase Calpont Package on Module " + expect -re "# " + send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches calpont'\n" expect { - "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit } - "service not known" { send_user "FAILED: Invalid Host\n" ; exit } - "authenticity" { send "yes\n" + -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit } + -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit } + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort } } - "word: " { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort } # password for ssh send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "uninstall completed" { send_user "DONE" } - "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "error: package" { send_user "INFO: Package not installed" } - "not installed" { send_user "INFO: Package not installed" } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "error: package" { send_user "INFO: Package not installed" } abort + -re "not installed" { send_user "INFO: Package not installed" } abort } send_user "\n" } @@ -56,28 +54,28 @@ if { $INSTALLTYPE == "uninstall" } { exit 0 } # # send the package # -expect -re {[$#] } -send_user "Copy New InfiniDB Packages to Module " -send "ssh $USERNAME@$SERVER 'rm -f /root/infinidb-*.rpm'\n" -expect "word: " +expect -re "# " +send_user "Copy New Calpont Package to Module " +send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.rpm'\n" +expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - -re {[$#] } { } + -re "# " { } abort } -send "scp $RPMPACKAGE1 $RPMPACKAGE2 $RPMPACKAGE3 $USERNAME@$SERVER:.\n" -expect "word: " +send "scp $RPMPACKAGE $USERNAME@$SERVER:$RPMPACKAGE\n" +expect -re "word: " # send the password send "$PASSWORD\n" # check return expect { - "100%" { send_user "DONE" } - "scp" { send_user "ERROR\n" ; + -re "100%" { send_user "DONE" } abort + -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit -1 } } send_user "\n" # @@ -86,56 +84,56 @@ if { $INSTALLTYPE == "initial"} { # # install package # - send_user "Install InfiniDB Packages on Module " - send "ssh $USERNAME@$SERVER 'rpm -ivh $RPMPACKAGE1 $RPMPACKAGE2 $RPMPACKAGE3'\n" - expect "word: " + send_user "Install Calpont Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -ivh $RPMPACKAGE'\n" + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - -re {[$#] } { send_user "DONE" } - "completed" { send_user "DONE" } - "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } } else { # # upgrade package # - send_user "Upgrade InfiniDB Packages on Module " - send "ssh $USERNAME@$SERVER 'rpm -Uvh --noscripts $RPMPACKAGE1 $RPMPACKAGE2 $RPMPACKAGE3'\n" - expect "word: " + send_user "Upgrade Calpont Package on Module " + send "ssh $USERNAME@$SERVER ' rpm -Uvh --noscripts $RPMPACKAGE'\n" + expect -re "word: " # password for ssh send "$PASSWORD\n" # check return expect { - -re {[$#] } { send_user "DONE" } - "completed" { send_user "DONE" } - "already installed" { send_user "INFO: Already Installed\n" ; exit -1 } - "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit -1 } + -re "ERROR dependencies" { send_user "ERROR: ERROR dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } } -expect -re {[$#] } +expect -re "# " send_user "\n" set timeout 30 # if { $INSTALLTYPE == "initial"} { # - # copy over InfiniDB OS files + # copy over calpont OS files # - send_user "Copy InfiniDB OS files to Module " + send_user "Copy Calpont OS files to Module " send "scp /usr/local/Calpont/local/etc/$MODULE/* $USERNAME@$SERVER:/usr/local/Calpont/local/.\n" - expect "word: " + expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re {[$#] } { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } } # send_user "\n" @@ -145,13 +143,13 @@ if { $INSTALLTYPE == "initial"} { # send_user "Run Module Installer " send "ssh $USERNAME@$SERVER '/usr/local/Calpont/bin/module_installer.sh'\n" - expect "word: " + expect -re "word: " # send the password send "$PASSWORD\n" expect { - "!!!Module" { send_user "DONE" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } - "FAILED" { send_user "ERROR: missing OS file\n" ; exit -1 } + -re "!!!Module" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit -1 } + -re "FAILED" { send_user "ERROR: missing OS file\n" ; exit -1 } } send_user "\n" } diff --git a/oam/install_scripts/user_installer.sh b/oam/install_scripts/user_installer.sh index f6b71c62..5762eb4e 100644 --- a/oam/install_scripts/user_installer.sh +++ b/oam/install_scripts/user_installer.sh @@ -14,24 +14,21 @@ set USERNAME root set MODULE [lindex $argv 0] set SERVER [lindex $argv 1] set PASSWORD [lindex $argv 2] -set CALPONTRPM1 [lindex $argv 3] -set CALPONTRPM2 [lindex $argv 4] -set CALPONTRPM3 [lindex $argv 5] -set CALPONTMYSQLRPM [lindex $argv 6] -set CALPONTMYSQLDRPM [lindex $argv 7] -set INSTALLTYPE [lindex $argv 8] -set PKGTYPE [lindex $argv 9] -set NODEPS [lindex $argv 10] -set MYSQLPW [lindex $argv 11] -set MYSQLPORT [lindex $argv 12] -set DEBUG [lindex $argv 13] +set CALPONTRPM [lindex $argv 3] +set CALPONTMYSQLRPM [lindex $argv 4] +set CALPONTMYSQLDRPM [lindex $argv 5] +set INSTALLTYPE [lindex $argv 6] +set PKGTYPE [lindex $argv 7] +set NODEPS [lindex $argv 8] +set MYSQLPW [lindex $argv 9] +set DEBUG [lindex $argv 10] set INSTALLDIR "/usr/local/Calpont" -set IDIR [lindex $argv 14] +set IDIR [lindex $argv 11] if { $IDIR != "" } { set INSTALLDIR $IDIR } set USERNAME "root" -set UNM [lindex $argv 15] +set UNM [lindex $argv 12] if { $UNM != "" } { set USERNAME $UNM } @@ -68,255 +65,416 @@ send_user " " send "ssh $USERNAME@$SERVER 'time'\n" set timeout 60 expect { - "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1 } - "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } - "authenticity" { send "yes\n" + -re "Host key verification failed" { send_user "FAILED: Host key verification failed\n" ; exit 1 } + -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } + -re "authenticity" { send "yes\n" expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - "sys" { set PASSWORD "ssh" } - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + -re "sys" { set PASSWORD "ssh" } abort + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } timeout { send_user "ERROR: Timeout to host\n" ; exit 1 } } set timeout 30 expect { - -re {[$#] } { } - "sys" { } + -re "# " { } abort + -re "sys" { } abort } send_user "\n" -#BUG 5749 - SAS: didn't work on their system until I added the sleep 60 -sleep 60 +sleep 5 if { $INSTALLTYPE == "initial" || $INSTALLTYPE == "uninstall" } { # - # erase InfiniDB packages + # erase Calpont-mysql package + # + send_user "Erase calpont-mysql Package on Module " + send "ssh $USERNAME@$SERVER '$PKGERASE calpont-mysql'\n" + if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + } + } + set timeout 30 + expect { + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "removing" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "not installed" { send_user "INFO: Package not installed" } abort + -re "isn't installed" { send_user "INFO: Package not installed" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + } + send_user "\n" + # + # erase Calpont-mysqld package + # + send_user "Erase calpont-mysqld Package on Module " + set timeout 30 + expect -re "# " + send "ssh $USERNAME@$SERVER '$PKGERASE calpont-mysqld'\n" + if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + } + } + set timeout 30 + expect { + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "removing" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "not installed" { send_user "INFO: Package not installed" } abort + -re "isn't installed" { send_user "INFO: Package not installed" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + } + send_user "\n" + # + # erase Calpont package # - send_user "Erase InfiniDB Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGERASE calpont >/dev/null 2>&1; $PKGERASE calpont-mysql >/dev/null 2>&1; $PKGERASE calpont-mysqld >/dev/null 2>&1; $PKGERASE infinidb-enterprise >/dev/null 2>&1; $PKGERASE infinidb-libs infinidb-platform;$PKGERASE infinidb-storage-engine infinidb-mysql;$PKGERASE dummy'\n" + send_user "Erase calpont Package on Module " + set timeout 30 + expect -re "# " + send "ssh $USERNAME@$SERVER '$PKGERASE calpont'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - set timeout 120 + set timeout 30 expect { - "package dummy" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit 1 } - "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "uninstall completed" { send_user "DONE" } abort + -re "removing" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "not installed" { send_user "INFO: Package not installed" } abort + -re "isn't installed" { send_user "INFO: Package not installed" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" } - if { $INSTALLTYPE == "uninstall" } { exit 0 } # -# send the InfinIDB package +# send the Calpont package # set timeout 30 -#expect -re {[$#] } -send_user "Copy new InfiniDB Packages to Module " -send "ssh $USERNAME@$SERVER 'rm -f /root/infinidb-*.$PKGTYPE'\n" +expect -re "# " +send_user "Copy new calpont Package to Module " +#gives time for the rpmsave to be done +sleep 5 +send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.$PKGTYPE'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } } -expect { - -re {[$#] } { } - "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } -} set timeout 30 expect { - -re {[$#] } { } + -re "# " { } abort } - -send "scp $CALPONTRPM1 $CALPONTRPM2 $CALPONTMYSQLRPM $CALPONTMYSQLDRPM $USERNAME@$SERVER:.;$PKGERASE dummy\n" +send "scp $CALPONTRPM $USERNAME@$SERVER:$CALPONTRPM\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 120 expect { - "package dummy" { send_user "DONE" } - "directory" { send_user "ERROR\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "100%" { send_user "DONE" } abort + -re "directory" { send_user "ERROR\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" - #sleep to make sure it's finished sleep 5 -if { $CALPONTRPM3 != "dummy.rpm" } { - expect -re {[$#] } - send_user "Copy new InfiniDB Enterprise Packages to Module " - send "scp $CALPONTRPM3 $USERNAME@$SERVER:.\n" - if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } +# +# send the package +# +send_user "Copy new calpont-mysql Package to Module " +send "scp $CALPONTMYSQLRPM $USERNAME@$SERVER:$CALPONTMYSQLRPM\n" +if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } - set timeout 120 +} +set timeout 120 +expect { + -re "100%" { send_user "DONE" } abort + -re "directory" { send_user "ERROR\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } +} +send_user "\n" +#sleep to make sure it's finished +sleep 5 +# +# send the package +# +send_user "Copy new calpont-mysqld Package to Module " +send "scp $CALPONTMYSQLDRPM $USERNAME@$SERVER:$CALPONTMYSQLDRPM\n" +if { $PASSWORD != "ssh" } { + set timeout 30 expect { - "100%" { send_user "DONE" } - "directory" { send_user "ERROR\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } - send_user "\n" } - +set timeout 120 +expect { + -re "100%" { send_user "DONE" } abort + -re "directory" { send_user "ERROR\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "No such file or directory" { send_user "ERROR: Invalid package\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } +} +send_user "\n" #sleep to make sure it's finished sleep 5 # set timeout 30 -expect -re {[$#] } +expect -re "# " if { $INSTALLTYPE == "initial"} { # # install package # - send_user "Install InfinIDB Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTRPM1 $CALPONTRPM2 $CALPONTMYSQLDRPM $CALPONTMYSQLRPM;$PKGERASE dummy'\n" + send_user "Install calpont Package on Module " + send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTRPM'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - set timeout 180 + set timeout 60 expect { - "package dummy" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "needs" { send_user "ERROR: disk space issue\n" ; exit 1 } - "conflicts" { send_user "ERROR: File Conflict issue\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" - - if { $CALPONTRPM3 != "dummy.rpm" } { - expect -re {[$#] } - send_user "Install InfinIDB Enterprise Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTRPM3'\n" - if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } + set timeout 30 + expect -re "# " + # + # install package + # + send_user "Install calpont-mysqld Package on Module " + send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTMYSQLDRPM'\n" + if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } - set timeout 60 + } + set timeout 60 + expect { + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + } + send_user "\n" + set timeout 30 + expect -re "# " + # + # install package + # + send_user "Install calpont-mysql Package on Module " + send "ssh $USERNAME@$SERVER '$PKGINSTALL $CALPONTMYSQLRPM'\n" + if { $PASSWORD != "ssh" } { + set timeout 30 expect { - "completed" { send_user "DONE" } - "Setting up" { send_user "DONE" } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } - send_user "\n" } - + set timeout 60 + expect { + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + } + send_user "\n" set timeout 30 - #expect -re {[$#] } + expect -re "# " } else { # # upgrade package # - #expect -re {[$#] } - send_user "Upgrade InfinIDB Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTRPM1 $CALPONTRPM2 $CALPONTRPM3 $CALPONTMYSQLDRPM $CALPONTMYSQLRPM;$PKGERASE dummy'\n" + expect -re "# " + send_user "Upgrade calpont Package on Module " + send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTRPM'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } - set timeout 120 + set timeout 30 expect { - "package dummy" { send_user "DONE" } - "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" - - if { $CALPONTRPM3 != "dummy.rpm" } { - expect -re {[$#] } - send_user "Upgrade InfinIDB Enterprise Packages on Module " - send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTRPM3'\n" - if { $PASSWORD != "ssh" } { - set timeout 30 - expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } - } + set timeout 30 + expect -re "# " + # + # upgrade package + # + send_user "Upgrade calpont-mysqld Package on Module " + send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTMYSQLDRPM'\n" + if { $PASSWORD != "ssh" } { + set timeout 30 + expect { + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } + } + set timeout 60 + expect { + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + } + send_user "\n" + set timeout 30 + expect -re "# " + # + # upgrade package + # + send_user "Upgrade calpont-mysql Package on Module " + send "ssh $USERNAME@$SERVER '$PKGUPGRADE $CALPONTMYSQLRPM'\n" + if { $PASSWORD != "ssh" } { set timeout 30 expect { - "completed" { send_user "DONE" } - "Setting up" { send_user "DONE" } - "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } - "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; - send_user "\n*** Installation ERROR\n" ; - exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } - send_user "\n" } - + set timeout 60 + expect { + -re "completed" { send_user "DONE" } abort + -re "Setting up" { send_user "DONE" } abort + -re "already installed" { send_user "INFO: Already Installed\n" ; exit 1 } + -re "error: Failed dependencies" { send_user "ERROR: Failed dependencies\n" ; + send_user "\n*** Installation ERROR\n" ; + exit 1 } + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } + } + send_user "\n" set timeout 30 - expect -re {[$#] } + expect -re "# " } -#sleep to make sure it's finished -sleep 5 # +#sleep to make sure rpm install has finsihed +sleep 10 if { $INSTALLTYPE == "initial"} { # - # copy over InfiniDB config file + # copy over calpont config file # - send_user "Copy InfiniDB Config file to Module " + send_user "Copy Calpont Config file to Module " send "scp $INSTALLDIR/etc/* $USERNAME@$SERVER:$INSTALLDIR/etc/.\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "directory" { send_user "ERROR\n" ; + -re "directory" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - -re {[$#] } { send_user "DONE" } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" #sleep to make sure it's finished @@ -329,40 +487,46 @@ if { $INSTALLTYPE == "initial"} { if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "directory" { send_user "ERROR\n" ; + -re "directory" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - -re {[$#] } { send_user "DONE" } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" #sleep to make sure it's finished sleep 5 # - # copy over InfiniDB OS files + # copy over calpont OS files # - send_user "Copy InfiniDB OS files to Module " + send_user "Copy Calpont OS files to Module " send "scp $INSTALLDIR/local/etc/$MODULE/* $USERNAME@$SERVER:$INSTALLDIR/local/.\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "directory" { send_user "ERROR\n" ; + -re "directory" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit 1 } - -re {[$#] } { send_user "DONE" } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "# " { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" #sleep to make sure it's finished @@ -371,24 +535,26 @@ if { $INSTALLTYPE == "initial"} { # Start module installer to setup Custom OS files # send_user "Run Module Installer " - send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/module_installer.sh --module=um --port=$MYSQLPORT'\n" + send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/module_installer.sh um'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "!!!Module" { send_user "DONE" } - "FAILED" { send_user "ERROR: missing OS file\n" ; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - "No such file" { send_user "ERROR: File Not Found\n" ; exit 1 } + -re "!!!Module" { send_user "DONE" } abort + -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } + -re "FAILED" { send_user "ERROR: missing OS file\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" set timeout 30 - expect -re {[$#] } + expect -re "# " # # run mysql setup scripts # @@ -397,37 +563,43 @@ if { $INSTALLTYPE == "initial"} { if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 20 expect { - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "ERROR" { send_user "ERROR: Daemon failed to run"; + exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } set timeout 30 - expect -re {[$#] } + expect -re "# " # send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/post-mysql-install $MYSQLPW'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 60 expect { - "Shutting down mysql." { send_user "DONE" } - -re {[$#] } { send_user "DONE" } - timeout { send_user "DONE" } - "ERROR" { send_user "ERROR: Daemon failed to run"; + -re "Shutting down mysql." { send_user "DONE" } abort + -re "# " { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "ERROR" { send_user "ERROR: Daemon failed to run"; exit 1 } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" set timeout 30 - #expect -re {[$#] } + expect -re "# " } # @@ -441,20 +613,21 @@ send "ssh $USERNAME@$SERVER '$BASH $INSTALLDIR/bin/syslogSetup.sh check'\n" if { $PASSWORD != "ssh" } { set timeout 30 expect { - "word: " { send "$PASSWORD\n" } - "passphrase" { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort + -re "passphrase" { send "$PASSWORD\n" } abort } } set timeout 30 expect { - "Logging working" { send_user "DONE" } - timeout { send_user "DONE" } - "not working" { send_user "WARNING: InfiniDB system logging functionality not working" } - "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "Logging working" { send_user "DONE" } abort + timeout { send_user "DONE" } abort + -re "not working" { send_user "WARNING: InfiniDB system logging functionality not working" } abort + -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } + -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } + -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } } send_user "\n" send_user "\nInstallation Successfully Completed on '$MODULE'\n" exit 0 -# vim:ts=4 sw=4: diff --git a/oam/install_scripts/xm_installer.sh b/oam/install_scripts/xm_installer.sh index 63c90384..a8d7a7ac 100755 --- a/oam/install_scripts/xm_installer.sh +++ b/oam/install_scripts/xm_installer.sh @@ -1,6 +1,6 @@ #!/usr/bin/expect # -# $Id$ +# $Id: system_installer.sh 421 2007-04-05 15:46:55Z dhill $ # # Install custom OS files on External Module # Argument 1 - Remote Module Name @@ -29,13 +29,13 @@ expect { -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit } -re "authenticity" { send "yes\n" expect { - -re "word: " { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort } } - -re "word: " { send "$PASSWORD\n" } + -re "word: " { send "$PASSWORD\n" } abort } expect { - -re "tools " { send_user "DONE" } + -re "tools " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } -re "package calpont" { send_user "ERROR: Calpont RPM not installed on External Module\n" ; exit -1 } } @@ -50,7 +50,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user "DONE" } + -re "# " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } -re "mkdir: cannot" { send_user "DONE: already installed\n" send_user "\nInstallation Successfully Completed on '$MODULE'\n"; exit 0 } @@ -62,7 +62,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user "DONE" } + -re "# " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } -re "mkdir: cannot" { send_user "DONE: already installed\n" send_user "\nInstallation Successfully Completed on '$MODULE'\n"; exit 0 } @@ -77,7 +77,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "100%" { send_user "DONE" } + -re "100%" { send_user "DONE" } abort -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } @@ -92,7 +92,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "100%" { send_user "DONE" } + -re "100%" { send_user "DONE" } abort -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } @@ -107,7 +107,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "100%" { send_user "DONE" } + -re "100%" { send_user "DONE" } abort -re "scp" { send_user "ERROR\n" ; send_user "\n*** Installation ERROR\n" ; exit -1 } @@ -124,7 +124,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user "DONE" } + -re "# " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } } # @@ -137,7 +137,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user "DONE" } + -re "# " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } } # @@ -150,7 +150,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user "DONE" } + -re "# " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } } # @@ -163,7 +163,7 @@ expect -re "word: " # send the password send "$PASSWORD\n" expect { - -re "# " { send_user "DONE" } + -re "# " { send_user "DONE" } abort -re "Permission denied" { send_user "ERROR: Invalid password\n" ; exit -1 } } send_user "\n" diff --git a/oam/oamcpp/COPYING b/oam/oamcpp/COPYING deleted file mode 100644 index 5c21d012..00000000 --- a/oam/oamcpp/COPYING +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/oam/oamcpp/Makefile.am b/oam/oamcpp/Makefile.am index 3f4733f1..d4d91ee4 100644 --- a/oam/oamcpp/Makefile.am +++ b/oam/oamcpp/Makefile.am @@ -1,21 +1,21 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. -# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +# $Id$ ## Process this file with automake to produce Makefile.in AM_CPPFLAGS = $(idb_cppflags) diff --git a/oam/oamcpp/Makefile.in b/oam/oamcpp/Makefile.in index 5c2df870..dac64993 100644 --- a/oam/oamcpp/Makefile.in +++ b/oam/oamcpp/Makefile.in @@ -14,24 +14,24 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. -# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ +# $Id$ srcdir = @srcdir@ @@ -58,11 +58,10 @@ build_triplet = @build@ host_triplet = @host@ subdir = oam/oamcpp DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in COPYING + $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -158,9 +157,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -202,7 +198,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -216,11 +211,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/oam/oamcpp/liboamcpp.cpp b/oam/oamcpp/liboamcpp.cpp index dc2fd2bb..3455cb6b 100644 --- a/oam/oamcpp/liboamcpp.cpp +++ b/oam/oamcpp/liboamcpp.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #if defined(__linux__) #include #include @@ -38,12 +37,9 @@ #include #include #include -#include -#include #endif #include #include -#include #include "ddlpkg.h" #include "dmlpkg.h" @@ -57,8 +53,6 @@ #include "installdir.h" #include "dbrm.h" #include "sessionmanager.h" -#include "IDBPolicy.h" -#include "IDBDataFile.h" #if defined(__GNUC__) #include @@ -79,17 +73,18 @@ using namespace oam; using namespace logging; using namespace BRM; +namespace +{ +const string CalpontFile = "Calpont.xml"; +const string AlarmFile = "AlarmConfig.xml"; +const string ProcessFile = "ProcessConfig.xml"; +} + namespace oam { // flag to tell us ctrl-c was hit uint32_t ctrlc = 0; - // flag for using HDFS - // -1: non-hdfs - // 0: unknown - // 1: hdfs - int Oam::UseHdfs = 0; - //------------------------------------------------------------------------------ // Signal handler to catch Control-C signal to terminate the process // while waiting for a shutdown or suspend action @@ -122,23 +117,12 @@ namespace oam if (cf != 0 && *cf != 0) calpontfiledir = cf; - CalpontConfigFile = calpontfiledir + "/Calpont.xml"; + CalpontConfigFile = calpontfiledir + "/" + CalpontFile; - AlarmConfigFile = calpontfiledir + "/AlarmConfig.xml"; + AlarmConfigFile = calpontfiledir + "/" + AlarmFile; - ProcessConfigFile = calpontfiledir + "/ProcessConfig.xml"; - if (UseHdfs == 0) - { - try { - Config* sysConfig = Config::makeConfig(CalpontConfigFile.c_str()); - string tmp = sysConfig->getConfig("Installation", "DBRootStorageType"); - if (boost::iequals(tmp, "hdfs")) - UseHdfs = 1; - else - UseHdfs = -1; - } - catch(...) {} // defaulted to false - } + ProcessConfigFile = calpontfiledir + "/" + ProcessFile; + } Oam::~Oam() @@ -1367,10 +1351,6 @@ namespace oam void Oam::getSystemStatus(SystemStatus& systemstatus) { -#ifdef _MSC_VER - // TODO: Remove when we create OAM for Windows - return; -#endif ModuleStatus modulestatus; systemstatus.systemmodulestatus.modulestatus.clear(); ExtDeviceStatus extdevicestatus; @@ -1399,38 +1379,15 @@ namespace oam struct timespec ts = { 10, 0 }; processor.write(obs, &ts); } - catch (exception& e) - { - processor.shutdown(); - string error = e.what(); - writeLog("getSystemStatus: write exception: " + error, LOG_TYPE_ERROR); - exceptionControl("getSystemStatus", API_FAILURE); - } catch(...) { - processor.shutdown(); - writeLog("getSystemStatus: write exception: unknown", LOG_TYPE_ERROR); - exceptionControl("getSystemStatus", API_FAILURE); + exceptionControl("getSystemStatus", API_TIMEOUT); } - // wait 20 seconds for ACK from Process Monitor - try { - struct timespec ts = { 20, 0 }; - ibs = processor.read(&ts); - } - catch (exception& e) - { - processor.shutdown(); - string error = e.what(); - writeLog("getSystemStatus: read exception: " + error, LOG_TYPE_ERROR); - exceptionControl("getSystemStatus", API_FAILURE); - } - catch(...) - { - processor.shutdown(); - writeLog("getSystemStatus: read exception: unknown", LOG_TYPE_ERROR); - exceptionControl("getSystemStatus", API_FAILURE); - } + // wait 10 seconds for ACK from Process Monitor + struct timespec ts = { 20, 0 }; + + ibs = processor.read(&ts); if (ibs.length() > 0) { @@ -1498,19 +1455,12 @@ namespace oam } // timeout ocurred, shutdown connection processor.shutdown(); - writeLog("getSystemStatus: read 0 length", LOG_TYPE_ERROR); } - catch (exception& e) - { - string error = e.what(); - writeLog("getSystemStatus: MessageQueueClient exception: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - writeLog("getSystemStatus: MessageQueueClient exception: unknown", LOG_TYPE_ERROR); + catch(...) + { + exceptionControl("getSystemStatus", API_FAILURE); } - - exceptionControl("getSystemStatus", API_FAILURE); + exceptionControl("getSystemStatus", API_TIMEOUT); } /******************************************************************** @@ -2077,7 +2027,7 @@ namespace oam { MessageQueueClient processor(port); processor.syncProto(false); - ByteStream::quadbyte processNumber; + ByteStream::byte processNumber; ByteStream::byte state; ByteStream::quadbyte PID; std::string changeDate; @@ -2105,7 +2055,7 @@ namespace oam { ibs >> processNumber; - for( unsigned i=0 ; i < processNumber ; ++i) + for( int i=0 ; i < processNumber ; ++i) { ibs >> processName; ibs >> moduleName; @@ -2143,10 +2093,6 @@ namespace oam void Oam::getProcessStatus(const std::string process, const std::string module, ProcessStatus& processstatus) { -#ifdef _MSC_VER - // TODO: Remove when we create OAM for Windows - return; -#endif try { MessageQueueClient processor("ProcStatusControl"); @@ -2166,7 +2112,6 @@ namespace oam } catch(...) { - processor.shutdown(); exceptionControl("getProcessStatus", API_TIMEOUT); } @@ -2502,38 +2447,30 @@ namespace oam void Oam::getActiveAlarms(AlarmList& activeAlarm) { - // check if on Active OAM Parent - bool OAMParentModuleFlag; - oamModuleInfo_t st; - try { - st = getModuleInfo(); - OAMParentModuleFlag = boost::get<4>(st); + // check if on Active OAM Parent + bool OAMParentModuleFlag; + oamModuleInfo_t st; + try { + st = getModuleInfo(); + OAMParentModuleFlag = boost::get<4>(st); - if (OAMParentModuleFlag) { - //call getAlarm API directly - SNMPManager sm; - sm.getActiveAlarm(activeAlarm); - return; - } - } - catch (...) { - exceptionControl("getActiveAlarms", API_FAILURE); - } + if ( OAMParentModuleFlag ) { + //call getAlarm API directly + SNMPManager sm; + sm.getActiveAlarm(activeAlarm); + return; + } + } + catch (...) { + exceptionControl("getActiveAlarms", API_FAILURE); + } - int returnStatus = API_SUCCESS; - if (UseHdfs > 0) - { - // read from HDFS files - returnStatus = readHdfsActiveAlarms(activeAlarm); - } - else - { - // build and send msg - returnStatus = sendMsgToProcMgr3(GETACTIVEALARMDATA, activeAlarm, ""); - } + // build and send msg + int returnStatus = sendMsgToProcMgr3(GETACTIVEALARMDATA, activeAlarm, ""); if (returnStatus != API_SUCCESS) exceptionControl("getActiveAlarms", returnStatus); + } /******************************************************************** @@ -2544,26 +2481,27 @@ namespace oam void Oam::getAlarms(std::string date, AlarmList& alarmlist) { - // check if on Active OAM Parent - bool OAMParentModuleFlag; - oamModuleInfo_t st; - try { - st = getModuleInfo(); - OAMParentModuleFlag = boost::get<4>(st); + // check if on Active OAM Parent + bool OAMParentModuleFlag; + oamModuleInfo_t st; + try { + st = getModuleInfo(); + OAMParentModuleFlag = boost::get<4>(st); - if (OAMParentModuleFlag) { - //call getAlarm API directly - SNMPManager sm; - sm.getAlarm(date, alarmlist); - return; - } - } - catch (...) { - exceptionControl("getAlarms", API_FAILURE); - } + if ( OAMParentModuleFlag ) { + //call getAlarm API directly + SNMPManager sm; + sm.getAlarm(date, alarmlist); + return; + } + } + catch (...) { + exceptionControl("getActiveAlarms", API_FAILURE); + } // build and send msg int returnStatus = sendMsgToProcMgr3(GETALARMDATA, alarmlist, date); + if (returnStatus != API_SUCCESS) exceptionControl("getAlarms", returnStatus); } @@ -2574,48 +2512,43 @@ namespace oam * ********************************************************************/ - bool Oam::checkActiveAlarm(const int alarmid, const std::string moduleName, - const std::string deviceName) + bool Oam::checkActiveAlarm(const int alarmid, const std::string moduleName, const std::string deviceName) { AlarmList activeAlarm; - // check if on Active OAM Parent - bool OAMParentModuleFlag; - oamModuleInfo_t st; - try { - st = getModuleInfo(); - OAMParentModuleFlag = boost::get<4>(st); + // check if on Active OAM Parent + bool OAMParentModuleFlag; + oamModuleInfo_t st; + try { + st = getModuleInfo(); + OAMParentModuleFlag = boost::get<4>(st); - if (OAMParentModuleFlag) { - //call getAlarm API directly - SNMPManager sm; - sm.getActiveAlarm(activeAlarm); - } - else if (UseHdfs > 0) - { - // read from HDFS files - if (readHdfsActiveAlarms(activeAlarm) != API_SUCCESS) - return false; - } - else - { - // build and send msg - int returnStatus = sendMsgToProcMgr3(GETACTIVEALARMDATA, activeAlarm, ""); - if (returnStatus != API_SUCCESS) - return false; - } - } - catch (...) { - return false; - } + if ( OAMParentModuleFlag ) { + //call getAlarm API directly + SNMPManager sm; + sm.getActiveAlarm(activeAlarm); + } + else + { + // build and send msg + int returnStatus = sendMsgToProcMgr3(GETACTIVEALARMDATA, activeAlarm, ""); + + if (returnStatus != API_SUCCESS) + return false; + } + } + catch (...) { + return false; + } - for (AlarmList::iterator i = activeAlarm.begin(); i != activeAlarm.end(); ++i) + AlarmList::iterator i; + for (i = activeAlarm.begin(); i != activeAlarm.end(); ++i) { // check if matching ID if (alarmid != (i->second).getAlarmID() ) continue; - //check for moduleName of wildcard "*", if so return if alarm set on any module + //check for moduleName of wildcard "*", if so return if alarm set on any module if (deviceName.compare((i->second).getComponentID()) == 0 && moduleName == "*") return true; @@ -2624,7 +2557,7 @@ namespace oam if (deviceName.compare((i->second).getComponentID()) == 0 && moduleName.compare((i->second).getSname()) == 0) return true; - } + } return false; } @@ -2643,53 +2576,53 @@ namespace oam string localModuleType; int localModuleID; - // Get Module Name from module-file - string fileName = InstallDir + "/local/module"; - - ifstream oldFile (fileName.c_str()); + // Get Module Name from module-file + string fileName = InstallDir + "/local/module"; - char line[400]; - while (oldFile.getline(line, 400)) - { - localModule = line; - break; - } - oldFile.close(); - - if (localModule.empty() ) { - // not found - //system("touch /var/log/Calpont/test8"); - exceptionControl("getModuleInfo", API_FAILURE); - } + ifstream oldFile (fileName.c_str()); + + char line[400]; + while (oldFile.getline(line, 400)) + { + localModule = line; + break; + } + oldFile.close(); - localModuleType = localModule.substr(0,MAX_MODULE_TYPE_SIZE); - localModuleID = atoi(localModule.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); + if (localModule.empty() ) { + // not found + //system("touch /var/log/Calpont/test8"); + exceptionControl("getModuleInfo", API_FAILURE); + } - // Get Parent OAM Module name + localModuleType = localModule.substr(0,MAX_MODULE_TYPE_SIZE); + localModuleID = atoi(localModule.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - string ParentOAMModule = oam::UnassignedName; - string StandbyOAMModule = oam::UnassignedName; - bool parentOAMModuleFlag = false; + // Get Parent OAM Module name + + string ParentOAMModule = oam::UnassignedName; + string StandbyOAMModule = oam::UnassignedName; + bool parentOAMModuleFlag = false; bool standbyOAMModuleFlag = false; - int serverTypeInstall = 1; - - try { - Config* sysConfig = Config::makeConfig(CalpontConfigFile.c_str()); - string Section = "SystemConfig"; - ParentOAMModule = sysConfig->getConfig(Section, "ParentOAMModuleName"); - StandbyOAMModule = sysConfig->getConfig(Section, "StandbyOAMModuleName"); + int serverTypeInstall = 1; - if ( localModule == ParentOAMModule ) - parentOAMModuleFlag = true; + try { + Config* sysConfig = Config::makeConfig(CalpontConfigFile.c_str()); + string Section = "SystemConfig"; + ParentOAMModule = sysConfig->getConfig(Section, "ParentOAMModuleName"); + StandbyOAMModule = sysConfig->getConfig(Section, "StandbyOAMModuleName"); + + if ( localModule == ParentOAMModule ) + parentOAMModuleFlag = true; - if ( localModule == StandbyOAMModule ) - standbyOAMModuleFlag = true; + if ( localModule == StandbyOAMModule ) + standbyOAMModuleFlag = true; - // Get Server Type Install ID - - serverTypeInstall = atoi(sysConfig->getConfig("Installation", "ServerTypeInstall").c_str()); - } - catch (...) {} + // Get Server Type Install ID + + serverTypeInstall = atoi(sysConfig->getConfig("Installation", "ServerTypeInstall").c_str()); + } + catch (...) {} return boost::make_tuple(localModule, localModuleType, localModuleID, ParentOAMModule, parentOAMModuleFlag, serverTypeInstall, StandbyOAMModule, standbyOAMModuleFlag); } @@ -2771,14 +2704,12 @@ namespace oam catch(...) { //system("touch /var/log/Calpont/test6"); - processor.shutdown(); exceptionControl("getMyProcessStatus", API_INVALID_PARAMETER); } } catch(...) { //system("touch /var/log/Calpont/test7"); - processor.shutdown(); exceptionControl("getMyProcessStatus", API_INVALID_PARAMETER); } @@ -2952,8 +2883,21 @@ namespace oam // build and send msg int returnStatus = sendMsgToProcMgrWithStatus(STOPSYSTEM, "stopped", gracefulflag, ackflag); - if (returnStatus != API_SUCCESS) - exceptionControl("stopSystem", returnStatus); + //Wait for everything to settle down + sleep(10); + + switch (returnStatus) + { + case API_SUCCESS: + cout << endl << " Successful stop of System " << endl << endl; + break; + case API_CANCELLED: + cout << endl << " stop of System canceled" << endl << endl; + break; + default: + exceptionControl("stopSystem", returnStatus); + break; + } } /******************************************************************** @@ -3720,9 +3664,6 @@ namespace oam ******************************************************************************************/ int Oam::getLocalDBRMID(const std::string moduleName) { - string cmd = "touch " + CalpontConfigFile; - (void)system(cmd.c_str()); - string SECTION = "DBRM_Worker"; Config* sysConfig = Config::makeConfig(CalpontConfigFile.c_str()); @@ -3786,16 +3727,16 @@ namespace oam ******************************************************************************************/ string Oam::getIPAddress(string hostName) { - static uint32_t my_bind_addr; + static u_long my_bind_addr; struct hostent *ent; string IPAddr = ""; ent=gethostbyname(hostName.c_str()); if (ent != 0) { - my_bind_addr = (uint32_t) ((in_addr*)ent->h_addr_list[0])->s_addr; + my_bind_addr = (u_long) ((in_addr*)ent->h_addr_list[0])->s_addr; - uint8_t split[4]; - uint32_t ip = my_bind_addr; + u_int8_t split[4]; + u_int32_t ip = my_bind_addr; split[0] = (ip & 0xff000000) >> 24; split[1] = (ip & 0x00ff0000) >> 16; split[2] = (ip & 0x0000ff00) >> 8; @@ -4329,9 +4270,9 @@ namespace oam ByteStream::byte entries; string deviceName; - uint64_t totalBlocks; - uint64_t usedBlocks; - uint8_t diskUsage; + ByteStream::quadbyte totalBlocks; + ByteStream::quadbyte usedBlocks; + ByteStream::byte diskUsage; // setup message msg << (ByteStream::byte) GET_MODULE_DISK_USAGE; @@ -4391,8 +4332,6 @@ namespace oam ByteStream msg; ByteStream receivedMSG; ByteStream::byte entries; - ByteStream::byte retStatus; - try { Oam::getSystemConfig(systemmoduletypeconfig); @@ -4446,13 +4385,6 @@ namespace oam receivedMSG = servermonitor.read(&ts); if (receivedMSG.length() > 0) { - receivedMSG >> retStatus; - if ( retStatus != oam::API_SUCCESS ) { - // shutdown connection - servermonitor.shutdown(); - exceptionControl("getActiveSQLStatements", (int) retStatus); - } - receivedMSG >> entries; ActiveSqlStatement activeSqlStatement; for (int i = 0; i < entries; i++) @@ -4515,40 +4447,6 @@ namespace oam return false; } - - /******************************************************************** - * - * incrementIPAddress - Increment IP Address - * - ********************************************************************/ - std::string Oam::incrementIPAddress(const std::string ipAddress) - { - string newipAddress = ipAddress; - string::size_type pos = ipAddress.rfind(".",80); - if (pos != string::npos) { - string last = ipAddress.substr(pos+1,80); - int Ilast = atoi(last.c_str()); - Ilast++; - - if ( Ilast > 255 ) - { - writeLog("incrementIPAddress: new address invalid, larger than 255", LOG_TYPE_ERROR ); - exceptionControl("incrementIPAddress", API_FAILURE); - } - - last = itoa(Ilast); - newipAddress = ipAddress.substr(0,pos+1); - newipAddress = newipAddress + last; - } - else - { - writeLog("incrementIPAddress: passed address invalid: " + ipAddress, LOG_TYPE_ERROR ); - exceptionControl("incrementIPAddress", API_FAILURE); - } - - return newipAddress; - } - /******************************************************************** * * checkLogStatus - Check for a phrase in a log file and return status @@ -4575,58 +4473,6 @@ namespace oam return false; } - /******************************************************************** - * - * fixRSAkey - Fix RSA key - * - ********************************************************************/ - void Oam::fixRSAkey(std::string logFile) - { - ifstream file (logFile.c_str()); - - char line[400]; - string buf; - - while (file.getline(line, 400)) - { - buf = line; - - string::size_type pos = buf.find("Offending RSA key",0); - if (pos != string::npos) { - // line ID - pos = buf.find(":",0); - string lineID = buf.substr(pos+1,80); - //remove non alphanumber characters - for (size_t i = 0; i < lineID.length();) - { - if (!isdigit(lineID[i])) - lineID.erase(i, 1); - else - i++; - } - - //get user - string USER = "root"; - char* p= getenv("USER"); - if (p && *p) - USER = p; - - string userDir = USER; - if ( USER != "root") - userDir = "home/" + USER; - - string cmd = "sed '" + lineID + "d' /" + userDir + "/.ssh/known_hosts > /" + userDir + "/.ssh/known_hosts"; - cout << cmd << endl; - system(cmd.c_str()); - return; - } - - } - file.close(); - - return; - } - /******************************************************************** * * getWritablePM - Get PM with read-write mount @@ -4766,7 +4612,7 @@ namespace oam try { getSystemStatus(systemstatus); } - catch (exception& ) + catch (exception& ex) {} if (systemstatus.SystemOpState == oam::MAN_INIT || @@ -4800,7 +4646,7 @@ namespace oam sleep(10); // build and send msg to restart system - returnStatus = sendMsgToProcMgr(RESTARTSYSTEM, "", FORCEFUL, ACK_YES); + returnStatus = sendMsgToProcMgr(STARTSYSTEM, "", FORCEFUL, ACK_YES); if (returnStatus != API_SUCCESS) exceptionControl("startSystem", returnStatus); @@ -4950,7 +4796,7 @@ namespace oam // dbrootid not found, return with error exceptionControl("getDbrootPmConfig", API_INVALID_PARAMETER); } - catch (exception& ) + catch (exception& e) {} // dbrootid not found, return with error @@ -4970,7 +4816,7 @@ namespace oam pmid = itoa(PMid); return; } - catch (exception& ) + catch (exception& e) {} // dbrootid not found, return with error @@ -5065,7 +4911,7 @@ namespace oam { setSystemDBrootCount(); } - catch (exception& ) + catch (exception& e) { cout << endl << "**** setSystemDBrootCount Failed" << endl; exceptionControl("assignPmDbrootConfig", API_FAILURE); @@ -5141,7 +4987,7 @@ namespace oam exceptionControl("manualMovePmDbroot", API_FAILURE); } } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: getPmDbrootConfig api failure for pm" + residePMID , LOG_TYPE_ERROR ); cout << endl << "ERROR: getPmDbrootConfig api failure for pm" + residePMID << endl; @@ -5154,7 +5000,7 @@ namespace oam { getPmDbrootConfig(atoi(toPMID.c_str()), todbrootConfigList); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: getPmDbrootConfig api failure for pm" + toPMID , LOG_TYPE_ERROR ); cout << endl << "ERROR: getPmDbrootConfig api failure for pm" + toPMID << endl; @@ -5188,7 +5034,7 @@ namespace oam { mountDBRoot(dbroot1, false); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: dbroot failed to unmount", LOG_TYPE_ERROR ); cout << endl << "ERROR: umountDBRoot api failure" << endl; @@ -5207,7 +5053,7 @@ namespace oam { amazonReattach(toPM, dbroot1); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: amazonReattach api failure", LOG_TYPE_ERROR ); cout << endl << "ERROR: amazonReattach api failure" << endl; @@ -5254,7 +5100,7 @@ namespace oam { setPmDbrootConfig(atoi(residePMID.c_str()), residedbrootConfigList); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: setPmDbrootConfig api failure for pm" + residePMID , LOG_TYPE_ERROR ); cout << endl << "ERROR: setPmDbrootConfig api failure for pm" + residePMID << endl; @@ -5265,7 +5111,7 @@ namespace oam { setPmDbrootConfig(atoi(toPMID.c_str()), todbrootConfigList); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: setPmDbrootConfig api failure for pm" + toPMID , LOG_TYPE_ERROR ); cout << endl << "ERROR: setPmDbrootConfig api failure for pm" + toPMID << endl; @@ -5277,7 +5123,7 @@ namespace oam { mountDBRoot(dbrootlist); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: mountDBRoot api failure", LOG_TYPE_DEBUG ); cout << endl << "ERROR: mountDBRoot api failure" << endl; @@ -5318,7 +5164,7 @@ namespace oam GlusterConfig = "n"; } - if (DBRootStorageType == "internal" && GlusterConfig == "n") + if (DBRootStorageType != "external" && GlusterConfig == "n") return 1; // get current Module name @@ -5359,7 +5205,7 @@ namespace oam t = getStorageConfig(); moduledbrootlist = boost::get<2>(t); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: getStorageConfig failure", LOG_TYPE_ERROR ); exceptionControl("autoMovePmDbroot", API_FAILURE); @@ -5440,7 +5286,7 @@ namespace oam dbrootlist.push_back(itoa(dbrootID)); mountDBRoot(dbrootlist); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: mountDBRoot api failure", LOG_TYPE_DEBUG ); cout << endl << "ERROR: mountDBRoot api failure" << endl; @@ -5493,7 +5339,7 @@ namespace oam amazonReattach(localModuleName, dbrootlist, true); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: amazonReattach failure", LOG_TYPE_ERROR ); exceptionControl("autoMovePmDbroot", API_FAILURE); @@ -5519,7 +5365,7 @@ namespace oam exceptionControl("autoMovePmDbroot", API_INVALID_PARAMETER); } } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: glusterctl failure getting pm list for dbroot " + itoa(dbrootID), LOG_TYPE_ERROR ); exceptionControl("autoMovePmDbroot", API_INVALID_PARAMETER); @@ -5593,7 +5439,7 @@ namespace oam mountDBRoot(dbrootlist); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: mountDBRoot api failure", LOG_TYPE_DEBUG ); cout << endl << "ERROR: mountDBRoot api failure" << endl; @@ -5670,7 +5516,7 @@ namespace oam mountDBRoot(dbrootlist); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: mountDBRoot api failure", LOG_TYPE_DEBUG ); cout << endl << "ERROR: mountDBRoot api failure" << endl; @@ -5697,7 +5543,7 @@ namespace oam amazonReattach(toPM, dbrootlist, true); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: amazonReattach failure", LOG_TYPE_ERROR ); exceptionFailure = true; @@ -5849,8 +5695,7 @@ namespace oam exceptionControl("addDbroot", API_INVALID_PARAMETER); } - if ( (cloud == "amazon-ec2" || cloud == "amazon-vpc") && - DBRootStorageType == "external" ) + if (cloud == "amazon" && DBRootStorageType == "external" ) { if ( newSystemDBRootCount > MAX_DBROOT_AMAZON ) { @@ -5913,8 +5758,7 @@ namespace oam } //if amazon cloud with external volumes, create AWS volumes - if ( (cloud == "amazon-ec2" || cloud == "amazon-vpc") && - DBRootStorageType == "external" ) + if (cloud == "amazon" && DBRootStorageType == "external" ) { //get local instance name (pm1) string localInstance = getEC2LocalInstance(); @@ -6043,27 +5887,6 @@ namespace oam //get updated Calpont.xml distributed distributeConfigFile("system"); - // - //send message to Process Monitor to add new dbroot to shared memory - // - pt2 = dbrootlist.begin(); - for( ; pt2 != dbrootlist.end() ; pt2++) - { - try - { - ByteStream obs; - - obs << (ByteStream::byte) ADD_DBROOT; - obs << itoa(*pt2); - - sendStatusUpdate(obs, ADD_DBROOT); - } - catch(...) - { - exceptionControl("setSystemConfig", API_INVALID_PARAMETER); - } - } - return; } @@ -6282,7 +6105,7 @@ namespace oam { setSystemDBrootCount(); } - catch (exception& ) + catch (exception& e) { cout << endl << "**** setSystemDBrootCount Failed" << endl; exceptionControl("assignPmDbrootConfig", API_FAILURE); @@ -6293,7 +6116,7 @@ namespace oam { setFilesPerColumnPartition( oldSystemDbRootCount ); } - catch (exception& ) + catch (exception& e) { cout << endl << "**** setFilesPerColumnPartition Failed" << endl; exceptionControl("assignPmDbrootConfig", API_FAILURE); @@ -6369,7 +6192,7 @@ namespace oam { mountDBRoot(dbroot1, false); } - catch (exception& ) + catch (exception& e) { writeLog("ERROR: dbroot failed to unmount", LOG_TYPE_ERROR ); cout << endl << "ERROR: umountDBRoot api failure" << endl; @@ -6451,7 +6274,7 @@ namespace oam { setSystemDBrootCount(); } - catch (exception& ) + catch (exception& e) { cout << endl << "**** setSystemDBrootCount Failed" << endl; exceptionControl("unassignPmDbrootConfig", API_FAILURE); @@ -6462,7 +6285,7 @@ namespace oam { setFilesPerColumnPartition( oldSystemDbRootCount ); } - catch (exception& ) + catch (exception& e) { cout << endl << "**** setFilesPerColumnPartition Failed" << endl; exceptionControl("unassignPmDbrootConfig", API_FAILURE); @@ -6591,7 +6414,7 @@ namespace oam exceptionControl("removeDbroot", API_FAILURE); } } - catch (exception& ) + catch (exception& e) {} if (!isEmpty) @@ -6605,7 +6428,7 @@ namespace oam try { getDbrootPmConfig(dbrootID, pmid); } - catch (exception& ) + catch (exception& e) {} if ( pmid > 0 ) @@ -6617,7 +6440,7 @@ namespace oam try { unassignDbroot("pm" + itoa(pmid), pmdbrootlist); } - catch (exception& ) + catch (exception& e) { cout << endl << "**** unassignDbroot Failed" << endl; exceptionControl("removeDbroot", API_FAILURE); @@ -6646,27 +6469,6 @@ namespace oam //get updated Calpont.xml distributed distributeConfigFile("system"); - // - //send message to Process Monitor to add new dbroot to shared memory - // - pt = dbrootlist.begin(); - for( ; pt != dbrootlist.end() ; pt++) - { - try - { - ByteStream obs; - - obs << (ByteStream::byte) REMOVE_DBROOT; - obs << itoa(*pt); - - sendStatusUpdate(obs, REMOVE_DBROOT); - } - catch(...) - { - exceptionControl("setSystemConfig", API_INVALID_PARAMETER); - } - } - return; } @@ -6885,54 +6687,35 @@ namespace oam * ****************************************************************************/ - void Oam::actionMysqlCalpont(MYSQLCALPONT_ACTION action) + void Oam::actionMysqlCalpont(MYSQLCALPONT_ACTION action) { - // check system type to see if mysqld should be accessed on this module - int serverTypeInstall = oam::INSTALL_NORMAL; - string moduleType; + // check if mysql-Capont is installed + string mysqlscript = InstallDir + "/mysql/mysql-Calpont"; + if (access(mysqlscript.c_str(), X_OK) != 0) + exceptionControl("actionMysqlCalpont", API_FILE_OPEN_ERROR); + + string command; + + // get current Module name string moduleName; oamModuleInfo_t st; try { st = getModuleInfo(); - moduleType = boost::get<1>(st); - serverTypeInstall = boost::get<5>(st); moduleName = boost::get<0>(st); } - catch (...) {} - - //PMwithUM config - string PMwithUM = "n"; - try { - getSystemConfig( "PMwithUM", PMwithUM); - } - catch(...) { - PMwithUM = "n"; - } - - if ( ( serverTypeInstall == oam::INSTALL_NORMAL && moduleType == "um" ) || - ( serverTypeInstall == oam::INSTALL_NORMAL && moduleType == "pm" && PMwithUM == "y") || - ( serverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) ) - PMwithUM = PMwithUM; - else - return; - - // check if mysql-Capont is installed - string mysqlscript = InstallDir + "/mysql/mysql-Calpont"; - if (access(mysqlscript.c_str(), X_OK) != 0) - return; - - string command; + catch (...) + {} - switch(action) - { + switch(action) + { case MYSQL_START: { - command = "start > /tmp/actionMysqlCalpont.log 2>&1"; + command = "start > /dev/null 2>&1"; break; } case MYSQL_STOP: { - command = "stop > /tmp/actionMysqlCalpont.log 2>&1"; + command = "stop > /dev/null 2>&1"; //set process status try @@ -6946,17 +6729,17 @@ namespace oam } case MYSQL_RESTART: { - command = "restart > /tmp/actionMysqlCalpont.log 2>&1"; + command = "restart > /dev/null 2>&1"; break; } case MYSQL_RELOAD: { - command = "reload > /tmp/actionMysqlCalpont.log 2>&1"; + command = "reload > /dev/null 2>&1"; break; } case MYSQL_FORCE_RELOAD: { - command = "force-reload > /tmp/actionMysqlCalpont.log 2>&1"; + command = "force-reload > /dev/null 2>&1"; break; } case MYSQL_STATUS: @@ -6967,50 +6750,33 @@ namespace oam default: { - writeLog("***DEFAULT OPTION", LOG_TYPE_ERROR); - exceptionControl("actionMysqlCalpont", API_INVALID_PARAMETER); + exceptionControl("actionMysqlCalpont", API_INVALID_PARAMETER); } } string cmd = mysqlscript + " " + command; - system(cmd.c_str()); + int status = system(cmd.c_str()); + if (status != 0 && action != MYSQL_STATUS) + exceptionControl("actionMysqlCalpont", API_FAILURE); if (action == MYSQL_START || action == MYSQL_RESTART) { //get pid cmd = "cat " + InstallDir + "/mysql/db/*.pid > /tmp/mysql.pid"; system(cmd.c_str()); ifstream oldFile ("/tmp/mysql.pid"); - - //fail if file size 0 - oldFile.seekg(0, std::ios::end); - int size = oldFile.tellg(); - if ( size == 0 ) { - // mysql not started - writeLog("***FILE SIZE EQUALS ZERO", LOG_TYPE_ERROR); - exceptionControl("actionMysqlCalpont", API_FAILURE); - } - char line[400]; string pid; while (oldFile.getline(line, 400)) { pid = line; - string::size_type pos = pid.find("cat",0); - if (pos != string::npos) { - // mysql not started - writeLog("***FILE HAS CAT", LOG_TYPE_ERROR); - exceptionControl("actionMysqlCalpont", API_FAILURE); - } break; } oldFile.close(); - int PID = atoi(pid.c_str()); - //set process status try { - setProcessStatus("mysqld", moduleName, ACTIVE, PID); + setProcessStatus("mysqld", moduleName, ACTIVE, atoi(pid.c_str())); } catch(...) {} @@ -7089,12 +6855,15 @@ namespace oam setModuleStatus(moduleName, ACTIVE); } catch(...) - {} + { + exceptionControl("processInitFailure", API_FAILURE); + } } + } else { - if ( state == ACTIVE ) + if ( state != MAN_OFFLINE ) { //set process status try @@ -7120,7 +6889,9 @@ namespace oam setModuleStatus(moduleName, DEGRADED); } catch(...) - {} + { + exceptionControl("processInitFailure", API_FAILURE); + } } return; } @@ -7145,7 +6916,7 @@ namespace oam try { getSystemStatus(systemstatus); } - catch (exception& ) + catch (exception& ex) {} if (systemstatus.SystemOpState != oam::ACTIVE ) @@ -7339,7 +7110,7 @@ namespace oam // run script to get Instance status and IP Address string cmd = InstallDir + "/bin/IDBInstanceCmds.sh getInstance > /tmp/getInstanceInfo_" + name; int status = system(cmd.c_str()); - if (WEXITSTATUS(status) != 0 ) + if (status != 0 ) return "failed"; // get Instance Name @@ -7370,7 +7141,7 @@ namespace oam // run script to get Instance status and IP Address string cmd = InstallDir + "/bin/IDBInstanceCmds.sh getType > /tmp/getInstanceType_" + name; int status = system(cmd.c_str()); - if (WEXITSTATUS(status) != 0 ) + if (status != 0 ) return "failed"; // get Instance Name @@ -7396,12 +7167,12 @@ namespace oam * ****************************************************************************/ - std::string Oam::launchEC2Instance( const std::string name, const std::string IPAddress, const std::string type, const std::string group) + std::string Oam::launchEC2Instance( const std::string name, const std::string type, const std::string group) { // run script to get Instance status and IP Address - string cmd = InstallDir + "/bin/IDBInstanceCmds.sh launchInstance " + IPAddress + " " + type + " " + group + " > /tmp/getInstance_" + name; + string cmd = InstallDir + "/bin/IDBInstanceCmds.sh launchInstance " + type + " " + group + " > /tmp/getInstance_" + name; int status = system(cmd.c_str()); - if (WEXITSTATUS(status) != 0 ) + if (status != 0 ) return "failed"; if (checkLogStatus("/tmp/getInstance", "Required") ) @@ -7477,7 +7248,7 @@ namespace oam // run script to get Instance status and IP Address string cmd = InstallDir + "/bin/IDBInstanceCmds.sh startInstance " + instanceName + " > /tmp/startEC2Instance_" + instanceName; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) return false; return true; @@ -7496,7 +7267,7 @@ namespace oam // run script to get Instance status and IP Address string cmd = InstallDir + "/bin/IDBInstanceCmds.sh assignElasticIP " + instanceName + " " + IpAddress + " > /tmp/assignElasticIP_" + instanceName; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) exceptionControl("assignElasticIP", oam::API_FAILURE); return true; @@ -7515,7 +7286,7 @@ namespace oam // run script to get Instance status and IP Address string cmd = InstallDir + "/bin/IDBInstanceCmds.sh deassignElasticIP " + IpAddress + " > /tmp/deassignElasticIP_" + IpAddress; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) exceptionControl("deassignElasticIP", oam::API_FAILURE); return true; @@ -7534,7 +7305,7 @@ namespace oam // run script to get Volume Status string cmd = InstallDir + "/bin/IDBVolumeCmds.sh describe " + volumeName + " > /tmp/getVolumeStatus_" + volumeName; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) return "failed"; // get status @@ -7565,7 +7336,7 @@ namespace oam // run script to get Volume Status string cmd = InstallDir + "/bin/IDBVolumeCmds.sh create " + size + " > /tmp/createVolumeStatus_" + name; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) return "failed"; // get status @@ -7610,7 +7381,7 @@ namespace oam string cmd = InstallDir + "/bin/IDBVolumeCmds.sh attach " + volumeName + " " + instanceName + " " + deviceName + " > /tmp/attachVolumeStatus_" + volumeName; ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) == 0 ) + if (ret == 0 ) return true; //failing to attach, dettach and retry @@ -7636,7 +7407,7 @@ namespace oam // run script to attach Volume string cmd = InstallDir + "/bin/IDBVolumeCmds.sh detach " + volumeName + " > /tmp/detachVolumeStatus_" + volumeName; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) return false; return true; @@ -7655,7 +7426,7 @@ namespace oam // run script to delete Volume string cmd = InstallDir + "/bin/IDBVolumeCmds.sh delete " + volumeName + " > /tmp/deleteVolumeStatus_" + volumeName; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) return false; return true; @@ -7674,7 +7445,7 @@ namespace oam // run script to create a tag string cmd = InstallDir + "/bin/IDBVolumeCmds.sh createTag " + resourceName + " " + tagName + " " + tagValue + " > /tmp/createTagStatus_" + resourceName; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) != 0 ) + if (ret != 0 ) return false; return true; @@ -7814,7 +7585,7 @@ namespace oam int ret; ret = system(glustercmd.c_str()); - if ( WEXITSTATUS(ret) == 0 ) + if ( ret == 0 ) return 0; ret = checkGlusterLog("/tmp/gluster_status.log", errmsg); @@ -7829,7 +7600,7 @@ namespace oam glustercmd = glustercmd + " setddc " + copies + " > /tmp/gluster_setddc.log 2>&1"; int ret; ret = system(glustercmd.c_str()); - if ( WEXITSTATUS(ret) == 0 ) + if ( ret == 0 ) return 0; ret = checkGlusterLog("/tmp/gluster_setddc.log", errmsg); @@ -7847,7 +7618,7 @@ namespace oam int ret; ret = system(glustercmd.c_str()); writeLog("glusterctl return: GLUSTER_ASSIGN: dbroot = " + dbrootID + " pm = " + pmID, LOG_TYPE_DEBUG ); - if ( WEXITSTATUS(ret) == 0 ) + if ( ret == 0 ) return 0; ret = checkGlusterLog("/tmp/gluster_assign.log", errmsg); @@ -7890,6 +7661,8 @@ namespace oam writeLog("glusterctl: GLUSTER_WHOHAS: failure, retrying (restarting gluster) " + msg, LOG_TYPE_ERROR ); string cmd = "/etc/init.d/glusterd restart > /dev/null 2>&1"; + int user; + user = getuid(); if (user != 0) cmd = "sudo " + cmd; @@ -7911,7 +7684,7 @@ namespace oam glustercmd = glustercmd + " unassign " + dbrootID + " " + pmID + " > /tmp/gluster_unassign.log 2>&1"; int ret; ret = system(glustercmd.c_str()); - if ( WEXITSTATUS(ret) == 0 ) + if ( ret == 0 ) return 0; ret = checkGlusterLog("/tmp/gluster_unassign.log", errmsg); @@ -7931,7 +7704,7 @@ namespace oam int ret; //writeLog("glusterctl: cmd = " + glustercmd, LOG_TYPE_DEBUG ); ret = system(glustercmd.c_str()); - if ( WEXITSTATUS(ret) == 0 ) + if ( ret == 0 ) return 0; ret = checkGlusterLog("/tmp/gluster_add.log", errmsg); @@ -7946,57 +7719,6 @@ namespace oam return 0; } - /****************************************************************************************** - * @brief changeMyCnf - * - * purpose: change my.cnf - * - ******************************************************************************************/ - bool Oam::changeMyCnf( std::string paramater, std::string value ) - { - string mycnfFile = startup::StartUp::installDir() + "/mysql/my.cnf"; - ifstream file (mycnfFile.c_str()); - if (!file) { - cout << "File not found: " << mycnfFile << endl; - return false; - } - - vector lines; - char line[200]; - string buf; - while (file.getline(line, 200)) - { - buf = line; - // change port - if ( paramater == "port" ) - { - string::size_type pos = buf.find(paramater,0); - if ( pos == 0 ) { - string::size_type pos = buf.find("=",0); - if ( pos != string::npos ) - buf = "port = " + value; - } - } - - //output to temp file - lines.push_back(buf); - } - - file.close(); - unlink (mycnfFile.c_str()); - ofstream newFile (mycnfFile.c_str()); - - //create new file - int fd = open(mycnfFile.c_str(), O_RDWR|O_CREAT, 0666); - - copy(lines.begin(), lines.end(), ostream_iterator(newFile, "\n")); - newFile.close(); - - close(fd); - - return true; - } - /*************************************************************************** * PRIVATE FUNCTIONS @@ -8076,6 +7798,74 @@ namespace oam return 1; } + + /*************************************************************************** + * + * Function: copyDatabaseFiles + * + * Purpose: copy database files from src to dst + * + ****************************************************************************/ + void Oam::copyDatabaseFiles(std::string src, std::string dst) + { + std::vector dbFileNames; + std::string file_name; + fs::path sourceDir(src); + fs::directory_iterator iter(sourceDir); + fs::directory_iterator end_iter; + double total_bytes = 0; + for( ; iter != end_iter ; ++iter) + { + fs::path source = *iter; + if (!fs::is_directory(source) ) + { +#if BOOST_VERSION >= 105200 + file_name = source.filename().generic_string(); +#else + file_name = iter->leaf(); +#endif + if (file_name.find(".dat", file_name.length() - 4) != string::npos) + { + dbFileNames.push_back(file_name); + total_bytes += fs::file_size(source); + } + } + } + + // make sure there is enough disk space + double avail_bytes = getFreeSpace(dst); + if (avail_bytes < total_bytes) + { + char error[256]; + sprintf(error, "Insufficient Disk Space. Avail: %8.0f kb, Needed: %8.0f kb\n", avail_bytes/1024, total_bytes/1024); + throw std::runtime_error(error); + } + + boost::progress_display show_progress(dbFileNames.size()); + std::vector::iterator dbfiles_iter = dbFileNames.begin(); + for( ; dbfiles_iter != dbFileNames.end() ; ++dbfiles_iter) + { + file_name = *dbfiles_iter; + std::string sourceFile = src; + std::string destFile = dst; + + sourceFile += "/"; + sourceFile += file_name; + + destFile += "/"; + destFile += file_name; + + fs::path source = sourceFile; + fs::path destination = destFile; + if (fs::exists(destination)) + fs::remove(destination); + fs::copy_file( source, destination ); + + ++show_progress; + } + + } + /*************************************************************************** * * Function: exceptionControl @@ -8791,8 +8581,7 @@ namespace oam } catch(...) {} - if ( (cloud == "amazon-ec2" || cloud == "amazon-vpc") && - DBRootStorageType == "external" ) + if (cloud == "amazon" && DBRootStorageType == "external" ) { //get Instance Name for to-pm string toInstanceName = oam::UnassignedName; @@ -8935,7 +8724,7 @@ namespace oam ******************************************************************************************/ void Oam::writeLog(const string logContent, const LOG_TYPE logType) { - LoggingID lid(8); + LoggingID lid(17); MessageLog ml(lid); Message msg; Message::Args args; @@ -9041,55 +8830,6 @@ namespace oam // writeLog("Returning from wait with value " + itoa(ret), LOG_TYPE_INFO ); return ret; } - - int Oam::readHdfsActiveAlarms(AlarmList& alarmList) - { - int returnStatus = API_FAILURE; - Alarm alarm; - - // the alarm file will be pushed to all nodes every 10 seconds, retry 1 second - for (int i = 0; i < 10 && returnStatus != API_SUCCESS; i++) - { - try - { - ifstream activeAlarm(ACTIVE_ALARM_FILE.c_str(), ios::in); - if (!activeAlarm.is_open()) - { - // file may be temporary not available due to dpcp. - usleep(10000); - - activeAlarm.open(ACTIVE_ALARM_FILE.c_str(), ios::in); - if (!activeAlarm.is_open()) - { - // still cannot open, treat as no activeAlarms file. - returnStatus = API_SUCCESS; - continue; - } - } - - // read from opened file. - while (!activeAlarm.eof() && activeAlarm.good()) - { - activeAlarm >> alarm; - if (alarm.getAlarmID() != INVALID_ALARM_ID) - alarmList.insert (AlarmList::value_type(INVALID_ALARM_ID, alarm)); - } - activeAlarm.close(); - - returnStatus = API_SUCCESS; - } - catch (...) - { - } - - // wait a second and try again - if (returnStatus != API_SUCCESS) - usleep (100000); - } - - return returnStatus; - } - } //namespace oam diff --git a/oam/oamcpp/liboamcpp.h b/oam/oamcpp/liboamcpp.h index d4f539a3..4588ee44 100644 --- a/oam/oamcpp/liboamcpp.h +++ b/oam/oamcpp/liboamcpp.h @@ -23,6 +23,16 @@ #ifndef LIBOAMCPP_H #define LIBOAMCPP_H +//Major hack to get oam and brm to play nice. +#ifdef OAM_BRM_LEAN_AND_MEAN +#include +#include +#include +#include "bytestream.h" +#include "alarm.h" +#include "snmpmanager.h" +#include "messagequeue.h" +#else #include #include #include @@ -43,8 +53,12 @@ #include "boost/tuple/tuple.hpp" #include "snmpmanager.h" #include "dbrm.h" +#ifndef SKIP_SNMP +#include "license.h" +#endif #include "messagequeue.h" +#endif #if defined(_MSC_VER) && defined(xxxLIBOAM_DLLEXPORT) #define EXPORT __declspec(dllexport) @@ -269,39 +283,9 @@ namespace oam ENABLED, // 16 = Enabled mode INITIAL, // 17 = Initial mode STANDBY_INIT, // 18 = Standby init - BUSY_INIT, // 19 = Busy init - ROLLBACK_INIT, // 20 = Rollback during DML init - STATE_MAX // 21 = Max value + BUSY_INIT // 19 = Busy init }; - /** @brief String State - */ - const std::string oamState[] = - { - "MAN_OFFLINE", - "AUTO_OFFLINE", - "MAN_INIT", - "AUTO_INIT", - "ACTIVE", - "LEAVE_BLANK", - "HOT_STANDBY", - "FAILED", - "UP", - "DOWN", - "COLD_STANDBY", - "UNEQUIP", - "EQUIP", - "DEGRADED", - "MAN_DISABLED", - "AUTO_DISABLED", - "ENABLED", - "INITIAL", - "STANDBY_INIT", - "BUSY_INIT", - "ROLLBACK_INIT", - "PID_UPDATE" - "" - }; /** @brief Process and Hardware String States */ @@ -357,12 +341,12 @@ namespace oam */ const std::string LogFile[] = { - "local1.=crit -/var/log/Calpont/crit.log", - "local1.=err -/var/log/Calpont/err.log", - "local1.=warning -/var/log/Calpont/warning.log", - "local1.=info -/var/log/Calpont/info.log", - "local1.=debug -/var/log/Calpont/debug.log", - "local2.=crit -/var/log/Calpont/data/data_mods.log", + "local1.=crit /var/log/Calpont/crit.log", + "local1.=err /var/log/Calpont/err.log", + "local1.=warning /var/log/Calpont/warning.log", + "local1.=info /var/log/Calpont/info.log", + "local1.=debug /var/log/Calpont/debug.log", + "local2.=crit /var/log/Calpont/data/data_mods.log", "" }; @@ -430,7 +414,6 @@ namespace oam MODULE_SWITCH_ACTIVE, // 33 = PM Failover / Switchover ROLLBACK_FAILURE, // 34 = DB Rollback Failure GLUSTER_DISK_FAILURE, // 35 = Gluster Disk Copy Failure - INVALID_LOCALE, // 36 = Locale invalid MAX_ALARM_ID }; @@ -535,32 +518,29 @@ namespace oam PROCUPDATELOG, PROCGETCONFIGLOG, CHECKPOWERON, - PROCUPDATECONFIG, + PROCUPDATECONFIG, HEARTBEAT_REGISTER, HEARTBEAT_DEREGISTER, HEARTBEAT_SEND, - PROCBUILDSYSTEMTABLES, - LOCALHEARTBEAT, - RECONFIGURE, - PROCESSRESTART, - GETSOFTWAREINFO, - UPDATEEXPORTS, - UPDATEPARENTNFS, - OAMPARENTACTIVE, - UPDATECONFIGFILE, - GETDBRMDATA, - GETPARENTOAMMODULE, - OAMPARENTCOLD, - UPDATESNMPD, - GETALARMDATA, - GETACTIVEALARMDATA, - RUNUPGRADE, - PROCUNMOUNT, - PROCMOUNT, - PROCFSTABUPDATE, - MASTERREP, - SLAVEREP, - MASTERDIST + PROCBUILDSYSTEMTABLES, + LOCALHEARTBEAT, + RECONFIGURE, + PROCESSRESTART, + GETSOFTWAREINFO, + UPDATEEXPORTS, + UPDATEPARENTNFS, + OAMPARENTACTIVE, + UPDATECONFIGFILE, + GETDBRMDATA, + GETPARENTOAMMODULE, + OAMPARENTCOLD, + UPDATESNMPD, + GETALARMDATA, + GETACTIVEALARMDATA, + RUNUPGRADE, + PROCUNMOUNT, + PROCMOUNT, + PROCFSTABUPDATE }; @@ -621,9 +601,7 @@ namespace oam ADD_EXT_DEVICE, REMOVE_EXT_DEVICE, GET_SHARED_MEM, - SET_DBROOT_STATUS, - ADD_DBROOT, - REMOVE_DBROOT + SET_DBROOT_STATUS }; /** @brief System Software Package Structure @@ -1226,8 +1204,8 @@ namespace oam struct DiskUsage_s { std::string DeviceName; //!< Device Name - uint64_t TotalBlocks; //!< Total Blocks - uint64_t UsedBlocks; //!< Used Blocks + uint32_t TotalBlocks; //!< Total Blocks + uint32_t UsedBlocks; //!< Used Blocks uint16_t DiskUsage; //!< Disk Usage % }; typedef struct DiskUsage_s DiskUsage; @@ -1905,6 +1883,7 @@ namespace oam * Get's the Active Alarm list for the Calpont Database Appliance * @param activealarm Returned Active Alarm list Structure */ + EXPORT void getActiveAlarms(snmpmanager::AlarmList& activealarm); /** @brief Get Historical Alarms @@ -1913,6 +1892,7 @@ namespace oam * @param date date of alarms, "today" or date in YYYYMMDD * @param activealarm Returned Alarm list Structure */ + EXPORT void getAlarms(std::string date, snmpmanager::AlarmList& alarm); /** @brief check Active Alarm @@ -1924,13 +1904,6 @@ namespace oam */ EXPORT bool checkActiveAlarm(const int alarmid, const std::string moduleName, const std::string deviceName); - /** @brief Read Active Alarms in HDFS - * - * Read the Active Alarm list from the HDFS image of activeAlarms - * @param activealarm Returned Active Alarm list Structure - */ - EXPORT int readHdfsActiveAlarms(snmpmanager::AlarmList& activealarm); - /** @brief update Log * * Enable/Disable Logging with the system or on a specific Module at @@ -2149,135 +2122,124 @@ namespace oam */ EXPORT bool isValidIP(const std::string ipAddress); - /** @brief Increment IP Address - * - * Increment IP Address - */ - EXPORT std::string incrementIPAddress(const std::string ipAddress); - - /** - *@brief Check for a phrase in a log file and return status - */ - EXPORT bool checkLogStatus(std::string filename, std::string phase); - - /** - *@brief Fix RSA key - */ - EXPORT void fixRSAkey(std::string logFile); - - /** - *@brief Get PM with read-write mount - */ - EXPORT std::string getWritablePM(); - - /** - *@brief Get PM with read-write mount - */ - EXPORT std::string getHotStandbyPM(); - - /** - *@brief Get PM with read-write mount - */ - EXPORT void setHotStandbyPM(std::string moduleName); - - /** - *@brief Distribute Calpont Configure File - */ - EXPORT void distributeConfigFile(std::string name = "system", std::string file = "Calpont.xml"); - - /** - *@brief Switch Parent OAM Module - * Return true if we need to wait for systme restart - */ - EXPORT bool switchParentOAMModule(std::string moduleName, GRACEFUL_FLAG gracefulflag); - - /** - *@brief Get Storage Config Data - */ - EXPORT systemStorageInfo_t getStorageConfig(); - - /** - *@brief Get PM - DBRoot Config data - */ - EXPORT void getPmDbrootConfig(const int pmid, DBRootConfigList& dbrootconfiglist); - - /** - *@brief Get DBRoot - PM Config data - */ - EXPORT void getDbrootPmConfig(const int dbrootid, int& pmid); - - EXPORT void getDbrootPmConfig(const int dbrootid, std::string& pmid); - - /** - *@brief Get System DBRoot Config data - */ - EXPORT void getSystemDbrootConfig(DBRootConfigList& dbrootconfiglist); - - /** - *@brief Set PM - DBRoot Config data - */ - EXPORT void setPmDbrootConfig(const int pmid, DBRootConfigList& dbrootconfiglist); - - /** - *@brief Manual Move PM - DBRoot data - */ - EXPORT void manualMovePmDbroot(std::string residePM, std::string dbrootIDs, std::string toPM); - - /** - *@brief Auto Move PM - DBRoot data - */ - EXPORT bool autoMovePmDbroot(std::string residePM); - - /** - *@brief Auto Un-Move PM - DBRoot data - */ - EXPORT bool autoUnMovePmDbroot(std::string toPM); - - /** - *@brief add DBRoot - */ - EXPORT void addDbroot(const int dbrootNumber, DBRootConfigList& dbrootlist); - - /** - *@brief distribute Fstab Updates - */ - EXPORT void distributeFstabUpdates(std::string entry, std::string toPM = "system" ); - - /** - *@brief assign DBRoot - */ - EXPORT void assignDbroot(std::string toPM, DBRootConfigList& dbrootlist); - - /** - *@brief unassign DBRoot - */ - EXPORT void unassignDbroot(std::string residePM, DBRootConfigList& dbrootlist); - - /** - *@brief get unassigned DBRoot list - */ - EXPORT void getUnassignedDbroot(DBRootConfigList& dbrootlist); - - /** - *@brief remove DBRoot - */ - EXPORT void removeDbroot(DBRootConfigList& dbrootlist); - - /** - *@brief get AWS Device Name for DBRoot ID - */ - EXPORT std::string getAWSdeviceName( const int dbrootid); - - /** - *@brief set System DBRoot Count - */ - EXPORT void setSystemDBrootCount(); - - /** - *@brief set FilesPerColumnPartition based on value of old - * FilePerColumnPartition and old DbRootCount that is given - */ - EXPORT void setFilesPerColumnPartition( int oldDbRootCount ); + /** + *@brief Check for a phrase in a log file and return status + */ + EXPORT bool checkLogStatus(std::string filename, std::string phase); + + /** + *@brief Get PM with read-write mount + */ + EXPORT std::string getWritablePM(); + + /** + *@brief Get PM with read-write mount + */ + EXPORT std::string getHotStandbyPM(); + + /** + *@brief Get PM with read-write mount + */ + EXPORT void setHotStandbyPM(std::string moduleName); + + /** + *@brief Distribute Calpont Configure File + */ + EXPORT void distributeConfigFile(std::string name = "system", std::string file = "Calpont.xml"); + + /** + *@brief Switch Parent OAM Module + * Return true if we need to wait for systme restart + */ + EXPORT bool switchParentOAMModule(std::string moduleName, GRACEFUL_FLAG gracefulflag); + + /** + *@brief Get Storage Config Data + */ + EXPORT systemStorageInfo_t getStorageConfig(); + + /** + *@brief Get PM - DBRoot Config data + */ + EXPORT void getPmDbrootConfig(const int pmid, DBRootConfigList& dbrootconfiglist); + + /** + *@brief Get DBRoot - PM Config data + */ + EXPORT void getDbrootPmConfig(const int dbrootid, int& pmid); + + EXPORT void getDbrootPmConfig(const int dbrootid, std::string& pmid); + + /** + *@brief Get System DBRoot Config data + */ + EXPORT void getSystemDbrootConfig(DBRootConfigList& dbrootconfiglist); + + /** + *@brief Set PM - DBRoot Config data + */ + EXPORT void setPmDbrootConfig(const int pmid, DBRootConfigList& dbrootconfiglist); + + /** + *@brief Manual Move PM - DBRoot data + */ + EXPORT void manualMovePmDbroot(std::string residePM, std::string dbrootIDs, std::string toPM); + + /** + *@brief Auto Move PM - DBRoot data + */ + EXPORT bool autoMovePmDbroot(std::string residePM); + + /** + *@brief Auto Un-Move PM - DBRoot data + */ + EXPORT bool autoUnMovePmDbroot(std::string toPM); + + /** + *@brief add DBRoot + */ + EXPORT void addDbroot(const int dbrootNumber, DBRootConfigList& dbrootlist); + + /** + *@brief distribute Fstab Updates + */ + EXPORT void distributeFstabUpdates(std::string entry, std::string toPM = "system" ); + + /** + *@brief assign DBRoot + */ + EXPORT void assignDbroot(std::string toPM, DBRootConfigList& dbrootlist); + + /** + *@brief unassign DBRoot + */ + EXPORT void unassignDbroot(std::string residePM, DBRootConfigList& dbrootlist); + + /** + *@brief get unassigned DBRoot list + */ + EXPORT void getUnassignedDbroot(DBRootConfigList& dbrootlist); + + /** + *@brief remove DBRoot + */ + EXPORT void removeDbroot(DBRootConfigList& dbrootlist); + + /** + *@brief get AWS Device Name for DBRoot ID + */ + EXPORT std::string getAWSdeviceName( const int dbrootid); + + /** + *@brief set System DBRoot Count + */ + EXPORT void setSystemDBrootCount(); + + /** + *@brief set FilesPerColumnPartition based on value of old + * FilePerColumnPartition and old DbRootCount that is given + */ + EXPORT void setFilesPerColumnPartition( int oldDbRootCount ); /** @brief send Device Notification Msg */ @@ -2305,7 +2267,7 @@ namespace oam /** @brief launchEC2Instance */ - EXPORT std::string launchEC2Instance(const std::string name = "dummy", const std::string IPAddress = oam::UnassignedName, const std::string type = oam::UnassignedName, const std::string group = oam::UnassignedName); + EXPORT std::string launchEC2Instance(const std::string name = "dummy", const std::string type = oam::UnassignedName, const std::string group = oam::UnassignedName); /** @brief getEC2InstanceIpAddress */ @@ -2355,15 +2317,15 @@ namespace oam */ EXPORT bool createEC2tag(std::string resourceName, std::string tagName, std::string tagValue); - /** - *@brief take action on Syslog process - */ - EXPORT void syslogAction( std::string action); + /** + *@brief take action on Syslog process + */ + EXPORT void syslogAction( std::string action); - /** - *@brief call dbrm control - */ - EXPORT void dbrmctl(std::string command); + /** + *@brief call dbrm control + */ + EXPORT void dbrmctl(std::string command); /** @brief Wait for system to close transactions * @@ -2377,18 +2339,11 @@ namespace oam void amazonReattach(std::string toPM, dbrootList dbrootConfigList, bool attach = false); void mountDBRoot(dbrootList dbrootConfigList, bool mount = true); - /** - *@brief gluster control - */ - EXPORT int glusterctl(GLUSTER_COMMANDS command, std::string argument1, std::string& argument2, std::string& errmsg); + /** + *@brief gluster control + */ + EXPORT int glusterctl(GLUSTER_COMMANDS command, std::string argument1, std::string& argument2, std::string& errmsg); - /** - * @brief changeMyCnf - * - * purpose: change my.cnf - * - **/ - EXPORT bool changeMyCnf( std::string paramater, std::string value ); private: @@ -2396,8 +2351,11 @@ namespace oam */ int checkGlusterLog(std::string logFile, std::string& errmsg); + /** @brief copy database files from src to dst + */ + void copyDatabaseFiles(std::string src, std::string dst); - int sendMsgToProcMgr3(messageqcpp::ByteStream::byte requestType, snmpmanager::AlarmList& alarmlist, const std::string date); + int sendMsgToProcMgr3(messageqcpp::ByteStream::byte requestType, snmpmanager::AlarmList& alarmlist, const std::string date); /** @brief build and send request message to Process Manager */ @@ -2437,7 +2395,6 @@ namespace oam std::string AlarmConfigFile; std::string ProcessConfigFile; std::string InstallDir; - static int UseHdfs; }; // end of class diff --git a/oam/oamcpp/liboamcpp.rc b/oam/oamcpp/liboamcpp.rc deleted file mode 100644 index 00c76ea9..00000000 --- a/oam/oamcpp/liboamcpp.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB OAM API" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "liboamcpp" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "liboamcpp.dll" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/oam/oamcpp/liboamcpp.vcxproj b/oam/oamcpp/liboamcpp.vcxproj deleted file mode 100644 index 632df33e..00000000 --- a/oam/oamcpp/liboamcpp.vcxproj +++ /dev/null @@ -1,246 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {8F7C9B67-639C-468F-8C5A-EB5F2E944E64} - liboamcpp - - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\startup;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\startup;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\startup;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\startup;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\startup;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\startup;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/oam/oamcpp/liboamcpp.vcxproj.filters b/oam/oamcpp/liboamcpp.vcxproj.filters deleted file mode 100644 index b061535b..00000000 --- a/oam/oamcpp/liboamcpp.vcxproj.filters +++ /dev/null @@ -1,48 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/oam/oamcpp/oamcache.cpp b/oam/oamcpp/oamcache.cpp index a507fdfe..c40f0f50 100644 --- a/oam/oamcpp/oamcache.cpp +++ b/oam/oamcpp/oamcache.cpp @@ -32,7 +32,6 @@ using namespace boost; #include "liboamcpp.h" #include "exceptclasses.h" #include "configcpp.h" -#include "installdir.h" namespace { @@ -51,7 +50,7 @@ OamCache * OamCache::makeOamCache() return oamCache; } -OamCache::OamCache() : mtime(0), mLocalPMId(0) +OamCache::OamCache() : mtime(0) {} OamCache::~OamCache() @@ -77,7 +76,7 @@ void OamCache::checkReload() dbRootPMMap.reset(new map()); //cout << "reloading oamcache\n"; - for (uint32_t i = 0; i < dbroots.size(); i++) { + for (uint i = 0; i < dbroots.size(); i++) { oam.getDbrootPmConfig(dbroots[i], temp); //cout << " dbroot " << dbroots[i] << " -> PM " << temp << endl; (*dbRootPMMap)[dbroots[i]] = temp; @@ -85,7 +84,7 @@ void OamCache::checkReload() ModuleTypeConfig moduletypeconfig; std::set uniquePids; - oam.getSystemConfig("pm", moduletypeconfig); + oam.getSystemConfig("pm", moduletypeconfig); int moduleID = 0; for (unsigned i = 0; i < moduletypeconfig.ModuleCount; i++) { moduleID = atoi((moduletypeconfig.ModuleNetworkList[i]).DeviceName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); @@ -93,37 +92,26 @@ void OamCache::checkReload() } std::set::const_iterator it = uniquePids.begin(); moduleIds.clear(); - uint32_t i = 0; + uint i = 0; map pmToConnectionMap; -#ifdef _MSC_VER - moduleIds.push_back(*it); -#else - // Restore for Windows when we support multiple PMs while (it != uniquePids.end()) { -#if !defined(SKIP_OAM_INIT) - { - try { - int state = 0; bool degraded; - char num[80]; - - snprintf(num, 80, "%d", *it); - oam.getModuleStatus(string("pm") + num, state, degraded); - if (state == oam::ACTIVE) { - pmToConnectionMap[*it] = i++; - moduleIds.push_back(*it); + moduleIds.push_back(*it); + try { + int state = 0; bool degraded; + char num[80]; + + snprintf(num, 80, "%d", *it); + oam.getModuleStatus(string("pm") + num, state, degraded); + if (state == oam::ACTIVE) { + pmToConnectionMap[*it] = i++; //cout << "pm " << *it << " -> connection " << (i-1) << endl; - } } - catch (...) { /* doesn't get added to the connection map */ } } -#else - moduleIds.push_back(*it); -#endif + catch (...) { /* doesn't get added to the connection map */ } it++; - } -#endif + dbRootConnectionMap.reset(new map()); for (i = 0; i < dbroots.size(); i++) (*dbRootConnectionMap)[dbroots[i]] = pmToConnectionMap[(*dbRootPMMap)[dbroots[i]]]; @@ -146,7 +134,6 @@ void OamCache::checkReload() oamModuleInfo_t tm; tm = oam.getModuleInfo(); OAMParentModuleName = boost::get<3>(tm); - systemName = config->getConfig("SystemConfig", "SystemName"); } OamCache::dbRootPMMap_t OamCache::getDBRootToPMMap() @@ -173,7 +160,7 @@ OamCache::PMDbrootsMap_t OamCache::getPMToDbrootsMap() return pmDbrootsMap; } -uint32_t OamCache::getDBRootCount() +uint OamCache::getDBRootCount() { mutex::scoped_lock lk(cacheLock); @@ -204,67 +191,5 @@ std::string OamCache::getOAMParentModuleName() checkReload(); return OAMParentModuleName; } - -int OamCache::getLocalPMId() -{ - mutex::scoped_lock lk(cacheLock); - // This comes from the file $INSTALL/local/module, not from the xml. - // Thus, it's not refreshed during checkReload(). - if (mLocalPMId > 0) - { - return mLocalPMId; - } - - string localModule; - string moduleType; - string fileName = startup::StartUp::installDir() + "/local/module"; - ifstream moduleFile (fileName.c_str()); - char line[400]; - while (moduleFile.getline(line, 400)) - { - localModule = line; - break; - } - moduleFile.close(); - - if (localModule.empty() ) - { - mLocalPMId = 0; - return mLocalPMId; - } - - moduleType = localModule.substr(0,MAX_MODULE_TYPE_SIZE); - mLocalPMId = atoi(localModule.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - if (moduleType != "pm") - { - mLocalPMId = 0; - } - - return mLocalPMId; -} - -string OamCache::getSystemName() -{ - mutex::scoped_lock lk(cacheLock); - - checkReload(); - return systemName; -} - -string OamCache::getModuleName() -{ - mutex::scoped_lock lk(cacheLock); - - if (!moduleName.empty()) - return moduleName; - - string fileName = startup::StartUp::installDir() + "/local/module"; - ifstream moduleFile(fileName.c_str()); - getline(moduleFile, moduleName); - moduleFile.close(); - - return moduleName; -} - } /* namespace oam */ diff --git a/oam/oamcpp/oamcache.h b/oam/oamcpp/oamcache.h index af60450b..aa3e78f9 100644 --- a/oam/oamcpp/oamcache.h +++ b/oam/oamcpp/oamcache.h @@ -46,14 +46,11 @@ class OamCache { EXPORT dbRootPMMap_t getDBRootToPMMap(); EXPORT dbRootPMMap_t getDBRootToConnectionMap(); EXPORT PMDbrootsMap_t getPMToDbrootsMap(); - EXPORT uint32_t getDBRootCount(); + EXPORT uint getDBRootCount(); EXPORT DBRootConfigList& getDBRootNums(); EXPORT std::vector & getModuleIds(); EXPORT static OamCache * makeOamCache(); EXPORT std::string getOAMParentModuleName(); - EXPORT int getLocalPMId(); // return the PM id of this machine. - EXPORT std::string getSystemName(); - EXPORT std::string getModuleName(); private: OamCache(); @@ -63,14 +60,11 @@ class OamCache { dbRootPMMap_t dbRootPMMap; dbRootPMMap_t dbRootConnectionMap; PMDbrootsMap_t pmDbrootsMap; - uint32_t numDBRoots; + uint numDBRoots; time_t mtime; DBRootConfigList dbroots; std::vector moduleIds; std::string OAMParentModuleName; - int mLocalPMId; // The PM id running on this machine - std::string systemName; - std::string moduleName; }; } /* namespace */ diff --git a/oam/oamcpp/resource.h b/oam/oamcpp/resource.h deleted file mode 100644 index 48a18307..00000000 --- a/oam/oamcpp/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by liboamcpp.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/oam/post/Makefile.am b/oam/post/Makefile.am index a9311732..a27a5ba5 100644 --- a/oam/post/Makefile.am +++ b/oam/post/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. dist_post_SCRIPTS = functions \ test-001.sh \ diff --git a/oam/post/Makefile.in b/oam/post/Makefile.in index 2d58ea6d..340a828b 100644 --- a/oam/post/Makefile.in +++ b/oam/post/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -57,9 +57,8 @@ subdir = oam/post DIST_COMMON = $(dist_post_SCRIPTS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -130,9 +129,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -174,7 +170,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -188,11 +183,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/oam/post/functions b/oam/post/functions index ade49f60..12fa68a7 100755 --- a/oam/post/functions +++ b/oam/post/functions @@ -10,7 +10,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR PATH=$INFINIDB_INSTALL_DIR/bin:$PATH export PATH diff --git a/oam/post/test-001.sh b/oam/post/test-001.sh index 1ba6f9bd..c603fcdb 100755 --- a/oam/post/test-001.sh +++ b/oam/post/test-001.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# $Id: test-001.sh 3704 2013-08-07 03:33:20Z bwilkinson $ +# $Id: test-001.sh 2937 2012-05-30 18:17:09Z rdempsey $ if [ -z "$INFINIDB_INSTALL_DIR" ]; then test -f /etc/default/infinidb && . /etc/default/infinidb @@ -10,7 +10,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/functions @@ -52,13 +52,12 @@ catoids="$catoids 2001 2004" catoids="$catoids 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040" catoids="$catoids 2061 2064 2067 2070 2073 2076" -# TODO-this doesn't work with HDFS file system -#for oid in $catoids; do -# if [ ! -s `oid2file $oid` ]; then -# cplogger -c 50 $scrname "$tname" "could not find file for OID $oid" -# exit 1 -# fi -#done +for oid in $catoids; do + if [ ! -s `oid2file $oid` ]; then + cplogger -c 50 $scrname "$tname" "could not find file for OID $oid" + exit 1 + fi +done cplogger -i 52 $scrname "$tname" diff --git a/oam/post/test-002.sh b/oam/post/test-002.sh index 00c65a77..ebcbe7e0 100755 --- a/oam/post/test-002.sh +++ b/oam/post/test-002.sh @@ -10,7 +10,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/functions diff --git a/oam/post/test-003.sh b/oam/post/test-003.sh index 16258b6f..fa16715d 100755 --- a/oam/post/test-003.sh +++ b/oam/post/test-003.sh @@ -10,7 +10,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/functions diff --git a/oam/post/test-004.sh b/oam/post/test-004.sh index 0884cb5a..d3fdba78 100644 --- a/oam/post/test-004.sh +++ b/oam/post/test-004.sh @@ -14,7 +14,7 @@ if [ -z "$INFINIDB_INSTALL_DIR" ]; then INFINIDB_INSTALL_DIR=/usr/local/Calpont fi -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR +declare -x INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR test -f $INFINIDB_INSTALL_DIR/post/functions && . $INFINIDB_INSTALL_DIR/post/functions diff --git a/oam/replaytxnlog/Makefile.am b/oam/replaytxnlog/Makefile.am index 0dc0cb69..bd674a0a 100644 --- a/oam/replaytxnlog/Makefile.am +++ b/oam/replaytxnlog/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/oam/replaytxnlog/Makefile.in b/oam/replaytxnlog/Makefile.in new file mode 100644 index 00000000..6419be53 --- /dev/null +++ b/oam/replaytxnlog/Makefile.in @@ -0,0 +1,542 @@ +# Makefile.in generated by automake 1.9.6 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ + + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = oam/replaytxnlog +DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" +libLTLIBRARIES_INSTALL = $(INSTALL) +LTLIBRARIES = $(lib_LTLIBRARIES) +libreplaytxnlog_la_LIBADD = +am_libreplaytxnlog_la_OBJECTS = libreplaytxnlog_la-replaytxnlog.lo +libreplaytxnlog_la_OBJECTS = $(am_libreplaytxnlog_la_OBJECTS) +DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CXXFLAGS) $(CXXFLAGS) +CXXLD = $(CXX) +CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ + $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(libreplaytxnlog_la_SOURCES) +DIST_SOURCES = $(libreplaytxnlog_la_SOURCES) +includeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(include_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +ALLOCA = @ALLOCA@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POW_LIB = @POW_LIB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +YACC = @YACC@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +etcdir = @etcdir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +idb_brm_libs = @idb_brm_libs@ +idb_cflags = @idb_cflags@ +idb_common_includes = @idb_common_includes@ +idb_common_ldflags = @idb_common_ldflags@ +idb_common_libs = @idb_common_libs@ +idb_cppflags = @idb_cppflags@ +idb_cxxflags = @idb_cxxflags@ +idb_exec_libs = @idb_exec_libs@ +idb_ldflags = @idb_ldflags@ +idb_oam_libs = @idb_oam_libs@ +idb_write_libs = @idb_write_libs@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localdir = @localdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +march_flags = @march_flags@ +mibdir = @mibdir@ +mkdir_p = @mkdir_p@ +mysqldir = @mysqldir@ +netsnmp_libs = @netsnmp_libs@ +oldincludedir = @oldincludedir@ +postdir = @postdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedir = @sharedir@ +sharedstatedir = @sharedstatedir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +toolsdir = @toolsdir@ +AM_CPPFLAGS = $(idb_cppflags) +AM_CFLAGS = $(idb_cflags) +AM_CXXFLAGS = $(idb_cxxflags) +AM_LDFLAGS = $(idb_ldflags) +lib_LTLIBRARIES = libreplaytxnlog.la +libreplaytxnlog_la_SOURCES = replaytxnlog.cpp +libreplaytxnlog_la_LDFLAGS = -version-info 1:0:0 $(AM_LDFLAGS) +libreplaytxnlog_la_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +include_HEADERS = replaytxnlog.h +all: all-am + +.SUFFIXES: +.SUFFIXES: .cpp .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oam/replaytxnlog/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu oam/replaytxnlog/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(mkdir_p) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + if test -f $$p; then \ + f=$(am__strip_dir) \ + echo " $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \ + else :; fi; \ + done + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @set -x; list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + p=$(am__strip_dir) \ + echo " $(LIBTOOL) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \ + $(LIBTOOL) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libreplaytxnlog.la: $(libreplaytxnlog_la_OBJECTS) $(libreplaytxnlog_la_DEPENDENCIES) + $(CXXLINK) -rpath $(libdir) $(libreplaytxnlog_la_LDFLAGS) $(libreplaytxnlog_la_OBJECTS) $(libreplaytxnlog_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libreplaytxnlog_la-replaytxnlog.Plo@am__quote@ + +.cpp.o: +@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< + +.cpp.obj: +@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.cpp.lo: +@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< + +libreplaytxnlog_la-replaytxnlog.lo: replaytxnlog.cpp +@am__fastdepCXX_TRUE@ if $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libreplaytxnlog_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libreplaytxnlog_la-replaytxnlog.lo -MD -MP -MF "$(DEPDIR)/libreplaytxnlog_la-replaytxnlog.Tpo" -c -o libreplaytxnlog_la-replaytxnlog.lo `test -f 'replaytxnlog.cpp' || echo '$(srcdir)/'`replaytxnlog.cpp; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/libreplaytxnlog_la-replaytxnlog.Tpo" "$(DEPDIR)/libreplaytxnlog_la-replaytxnlog.Plo"; else rm -f "$(DEPDIR)/libreplaytxnlog_la-replaytxnlog.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='replaytxnlog.cpp' object='libreplaytxnlog_la-replaytxnlog.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libreplaytxnlog_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libreplaytxnlog_la-replaytxnlog.lo `test -f 'replaytxnlog.cpp' || echo '$(srcdir)/'`replaytxnlog.cpp + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(mkdir_p) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f=$(am__strip_dir) \ + echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'"; \ + $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; for p in $$list; do \ + f=$(am__strip_dir) \ + echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ + rm -f "$(DESTDIR)$(includedir)/$$f"; \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-includeHEADERS + +install-exec-am: install-libLTLIBRARIES + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-includeHEADERS uninstall-info-am \ + uninstall-libLTLIBRARIES + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-exec \ + install-exec-am install-includeHEADERS install-info \ + install-info-am install-libLTLIBRARIES install-man \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-includeHEADERS uninstall-info-am \ + uninstall-libLTLIBRARIES + + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: install-data-am +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/oam/replaytxnlog/replaytxnlog.cpp b/oam/replaytxnlog/replaytxnlog.cpp index 7327e5e3..c808e030 100644 --- a/oam/replaytxnlog/replaytxnlog.cpp +++ b/oam/replaytxnlog/replaytxnlog.cpp @@ -371,11 +371,7 @@ list ReplayTxnLog::getLogFileNames() { fs::path source = *iter; if (!fs::is_directory(source) ) { -#if BOOST_VERSION >= 105200 - fileName = source.filename().c_str(); -#else fileName = iter->leaf(); -#endif if(fileName.find(logFileName, 0) == 0) { fileName = archiveDir + "/" + fileName; dbFileNames.push_back(fileName); @@ -777,7 +773,7 @@ void ReplayTxnLog::process() { // Get the last version from issued before the backup. #ifdef LAST_TXN_AVAILABLE - fStartVersionID = mgr.verID().currentScn; + fStartVersionID = mgr.verID(); #else fStartVersionID = 0; #endif diff --git a/oamapps/Makefile.am b/oamapps/Makefile.am index 871eb592..115895ca 100644 --- a/oamapps/Makefile.am +++ b/oamapps/Makefile.am @@ -1,24 +1,23 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ -SUBDIRS = calpontConsole calpontDB postConfigure serverMonitor traphandler \ -sendtrap calpontSupport +SUBDIRS = replayTransactionLog test: diff --git a/oamapps/Makefile.in b/oamapps/Makefile.in index fd81b6d6..0994f145 100644 --- a/oamapps/Makefile.in +++ b/oamapps/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ srcdir = @srcdir@ @@ -57,9 +57,8 @@ host_triplet = @host@ subdir = oamapps DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -209,9 +199,7 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ -SUBDIRS = calpontConsole calpontDB postConfigure serverMonitor traphandler \ -sendtrap calpontSupport - +SUBDIRS = replayTransactionLog all: all-recursive .SUFFIXES: diff --git a/oamapps/calpont-console/Makefile.am b/oamapps/calpont-console/Makefile.am new file mode 100644 index 00000000..e6fb377e --- /dev/null +++ b/oamapps/calpont-console/Makefile.am @@ -0,0 +1,22 @@ +# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ +## Process this file with automake to produce Makefile.in + +AM_CPPFLAGS = $(idb_cppflags) +AM_CFLAGS = $(idb_cflags) +AM_CXXFLAGS = $(idb_cxxflags) +AM_LDFLAGS = $(idb_ldflags) +bin_PROGRAMS = calpontConsole +calpontConsole_SOURCES = calpontConsole.cpp +calpontConsole_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) +calpontConsole_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: install-data-am + diff --git a/oamapps/calpontConsole/calpontConsole.cpp b/oamapps/calpont-console/calpontConsole.cpp similarity index 81% rename from oamapps/calpontConsole/calpontConsole.cpp rename to oamapps/calpont-console/calpontConsole.cpp index dfe1887c..bfa534dc 100644 --- a/oamapps/calpontConsole/calpontConsole.cpp +++ b/oamapps/calpont-console/calpontConsole.cpp @@ -1,29 +1,9 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - - /****************************************************************************************** - * $Id: calpontConsole.cpp 3110 2013-06-20 18:09:12Z dhill $ + * $Id: calpontConsole.cpp 3120 2013-06-25 21:29:28Z dhill $ * ******************************************************************************************/ #include -#include -extern int h_errno; #include "calpontConsole.h" #include "boost/filesystem/operations.hpp" @@ -61,24 +41,24 @@ static void checkPromptThread(); bool waitForActive() { - Oam oam; - SystemStatus systemstatus; + Oam oam; + SystemStatus systemstatus; SystemProcessStatus systemprocessstatus; bool bfirst = true; - for (int i = 0 ; i < 1200 ; i ++) - { - sleep (3); - try - { - oam.getSystemStatus(systemstatus); - if (systemstatus.SystemOpState == ACTIVE) - { - return true; - } - if (systemstatus.SystemOpState == FAILED) - { - return false; + for ( int i = 0 ; i < 1200 ; i ++ ) + { + sleep (3); + try + { + oam.getSystemStatus(systemstatus); + if (systemstatus.SystemOpState == ACTIVE) + { + return true; + } + if (systemstatus.SystemOpState == FAILED) + { + return false; } if (systemstatus.SystemOpState == MAN_OFFLINE) { @@ -96,9 +76,9 @@ bool waitForActive() { if (systemprocessstatus.processstatus[i].ProcessName == "DMLProc") { - if (systemprocessstatus.processstatus[i].ProcessOpState == oam::ROLLBACK_INIT) + if (systemprocessstatus.processstatus[i].ProcessOpState == oam::BUSY_INIT) { - cout << endl << endl <<" System Not Ready, DMLProc is checking/processing rollback of abandoned transactions. Processing could take some time, please wait..." << flush; + cout << endl << " DMLProc is rolling back abandoned transactions. This could take some time." << flush; bfirst = false; } // At this point, we've found our DMLProc, so there's no need to spin the for loop @@ -106,56 +86,19 @@ bool waitForActive() break; } } - } - } - catch (...) - { - // At some point, we need to give up, ProcMgr just isn't going to respond. - if (i > 60) // 3 minutes - { - cout << "ProcMgr not responding while waiting for system to start"; - break; - } - } - } - - return false; -} - -bool waitForStop() -{ - Oam oam; - SystemStatus systemstatus; - SystemProcessStatus systemprocessstatus; - - for (int i = 0 ; i < 1200 ; i ++) - { - sleep (3); - try - { - oam.getSystemStatus(systemstatus); - if (systemstatus.SystemOpState == MAN_OFFLINE) - { - return true; - } - if (systemstatus.SystemOpState == FAILED) - { - return false; - } - cout << "." << flush; + } } - catch (...) - { + catch(...) + { // At some point, we need to give up, ProcMgr just isn't going to respond. if (i > 60) // 3 minutes { cout << "ProcMgr not responding while waiting for system to start"; break; } - } - } - - return false; + } + } + return false; } //------------------------------------------------------------------------------ @@ -226,10 +169,9 @@ int main(int argc, char *argv[]) exit(-1); } - //get parentModule Name + // get Local Module Name and Single Server Install Indicator parentOAMModule = getParentOAMModule(); - // get Local Module Name and Single Server Install Indicator oamModuleInfo_t st; try { st = oam.getModuleInfo(); @@ -296,6 +238,24 @@ int main(int argc, char *argv[]) cout << " Access Console from '" << parentOAMModule << "' if you need to make changes." << endl << endl; } + //check if license has expired + oam::LicenseKeyChecker keyChecker; + + bool keyGood = true; + try { + keyGood = keyChecker.isGood(); + } + catch(...) + { + keyGood = false; + } + + if (!keyGood) + { + cout << endl << "Your License trial period has expired, please contact Calpont Customer Support." << endl << endl; + exit (1); + } + // check for arguments passed in as a request if(argc > 1) @@ -494,8 +454,7 @@ int processCommand(string* arguments) GRACEFUL_FLAG gracefulTemp = GRACEFUL; ACK_FLAG ackTemp = ACK_YES; CC_SUSPEND_ANSWER suspendAnswer = CANCEL; - bool bNeedsConfirm = true; - string password; + // get command info from Command config file CmdID = -1; @@ -1454,10 +1413,6 @@ int processCommand(string* arguments) } catch(...) {} - string::size_type pos = cloud.find("amazon",0); - if (pos != string::npos) - cloud = "amazon"; - cout << endl << "System Storage Configuration" << endl << endl; cout << "Performance Module (DBRoot) Storage Type = " << boost::get<0>(t) << endl; @@ -1724,24 +1679,38 @@ int processCommand(string* arguments) case 15: // removeDbroot parameters: dbroot-list { - string GlusterConfig = "n"; - try { - oam.getSystemConfig( "GlusterConfig", GlusterConfig); - } - catch(...) - {} - - if (GlusterConfig == "y") { - cout << endl << "**** removeDbroot Not Supported on Data Redundancy Configured System" << endl; - break; - } - if ( localModule != parentOAMModule ) { // exit out since not on active module cout << endl << "**** removeDbroot Failed : Can only run command on Active OAM Parent Module (" << parentOAMModule << ")." << endl; break; } + //check the system status / service status and only allow command when System is MAN_OFFLINE + string cmd = startup::StartUp::installDir() + "/bin/infinidb status > /tmp/status.log"; + system(cmd.c_str()); + if (oam.checkLogStatus("/tmp/status.log", "InfiniDB is running") ) + { + SystemStatus systemstatus; + try { + oam.getSystemStatus(systemstatus); + + if (systemstatus.SystemOpState != oam::MAN_OFFLINE ) { + cout << endl << "**** removeDbroot Failed, System has to be in a MAN_OFFLINE state, stop system first" << endl; + break; + } + } + catch (exception& e) + { + cout << endl << "**** removeDbroot Failed : " << e.what() << endl; + break; + } + catch(...) + { + cout << endl << "**** removeDbroot Failed, Failed return from getSystemStatus API" << endl; + break; + } + } + if (arguments[1] == "") { // need atleast 1 arguments @@ -1749,50 +1718,19 @@ int processCommand(string* arguments) break; } - systemStorageInfo_t t; - try - { - t = oam.getStorageConfig(); - } - catch(...) {} - string dbrootIDs = arguments[1]; DBRootConfigList dbrootlist; - bool assign = false; boost::char_separator sep(", "); boost::tokenizer< boost::char_separator > tokens(dbrootIDs, sep); for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); it != tokens.end(); ++it) { - //check if dbroot is assigned to a pm - DeviceDBRootList moduledbrootlist = boost::get<2>(t); - - DeviceDBRootList::iterator pt = moduledbrootlist.begin(); - for( ; pt != moduledbrootlist.end() ; pt++) - { - DBRootConfigList::iterator pt1 = (*pt).dbrootConfigList.begin(); - for( ; pt1 != (*pt).dbrootConfigList.end() ; pt1++) - { - if ( atoi((*it).c_str()) == *pt1 ) { - cout << endl << "**** removeDbroot Failed, dbroot " << *it << " is assigned to a module, unassign first before removing" << endl; - assign = true; - break; - } - } - } - - if (assign) - break; - dbrootlist.push_back(atoi((*it).c_str())); } - if (assign) - break; - cout << endl; try @@ -1813,7 +1751,8 @@ int processCommand(string* arguments) { BRM::DBRM dbrm; bool bDBRMReady = dbrm.isDBRMReady(); - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); + bool bNeedsConfirm = true; if ( gracefulTemp == INSTALL ) { @@ -1821,266 +1760,205 @@ int processCommand(string* arguments) break; } + if (arguments[1] == "y") + { + bNeedsConfirm = false; + } + cout << endl << "This command stops the processing of applications on all Modules within the Calpont System" << endl; - try - { - if (gracefulTemp != GRACEFUL || - !bDBRMReady || - dbrm.isReadWrite()) - { - suspendAnswer = FORCE; - } - - if (suspendAnswer == CANCEL) // We don't have an answer from the command line or some other state. - { - // If there are bulkloads, ddl or dml happening, Ask what to do. - bool bIsDbrmUp = true; - execplan::SessionManager sessionManager; - BRM::SIDTIDEntry blockingsid; - std::vector tableLocks = dbrm.getAllTableLocks(); - bool bActiveTransactions = false; - if (!tableLocks.empty()) - { - oam.DisplayLockedTables(tableLocks, &dbrm); - bActiveTransactions = true; - } - if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) - { - cout << endl << "There are active transactions being processed" << endl; - bActiveTransactions = true; - } - - if (bActiveTransactions) - { - suspendAnswer = AskSuspendQuestion(CmdID); - // if (suspendAnswer == FORCE) - // { - // if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) - // { - // break; - // } - // } - bNeedsConfirm = false; - } - else - { - suspendAnswer = FORCE; - } - } - if (suspendAnswer == CANCEL) - { - // We're outa here. - break; - } - - if (bNeedsConfirm) - { - if (confirmPrompt("")) - break; - } - - switch (suspendAnswer) - { - case WAIT: - cout << endl << " Waiting for all transactions to complete" << flush; - dbrm.setSystemShutdownPending(true, false, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case ROLLBACK: - cout << endl << " Rollback of all transactions" << flush; - dbrm.setSystemShutdownPending(true, true, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case FORCE: - cout << endl << " System being stopped now..."; - if (bDBRMReady) - { - dbrm.setSystemShutdownPending(true, false, true); - } - break; - case CANCEL: - break; - } + if (gracefulTemp != GRACEFUL || + !bDBRMReady || + dbrm.isReadWrite()) + { + suspendAnswer = FORCE; + } - oam.stopSystem(gracefulTemp, ackTemp); + if (suspendAnswer == CANCEL) // We don't have an answer from the command line or some other state. + { + // If there are bulkloads, ddl or dml happening, Ask what to do. + bool bIsDbrmUp = true; + execplan::SessionManager sessionManager; + BRM::SIDTIDEntry blockingsid; + std::vector tableLocks = dbrm.getAllTableLocks(); + bool bActiveTransactions = false; + if (!tableLocks.empty()) + { + oam.DisplayLockedTables(tableLocks, &dbrm); + bActiveTransactions = true; + } + if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) + { + cout << endl << "There are active transactions being processed" << endl; + bActiveTransactions = true; + } - if ( waitForStop() ) - cout << endl << " Successful stop of System " << endl << endl; + if (bActiveTransactions) + { + suspendAnswer = AskSuspendQuestion(CmdID); +// if (suspendAnswer == FORCE) +// { +// if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) +// { +// break; +// } +// } + bNeedsConfirm = false; + } else - cout << endl << "**** stopSystem Failed : check log files" << endl; + { + suspendAnswer = FORCE; + } + } + if (suspendAnswer == CANCEL) + { + // We're outa here. + break; + } + + if (bNeedsConfirm) + { + if (confirmPrompt("")) + break; + } + + switch (suspendAnswer) + { + case WAIT: + cout << endl << " Waiting for all transactions to complete" << flush; + dbrm.setSystemShutdownPending(true, false, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case ROLLBACK: + cout << endl << " Rollback of all transactions" << flush; + dbrm.setSystemShutdownPending(true, true, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case FORCE: + cout << endl << " System being stopped now" << endl; + if (bDBRMReady) + { + dbrm.setSystemShutdownPending(true, false, true); + } + break; + case CANCEL: + break; + } + try + { + oam.stopSystem(gracefulTemp, ackTemp); checkForDisabledModules(); } catch (exception& e) { - string Failed = e.what(); - - if (Failed.find("Connection refused") != string::npos) - { - cout << endl << "**** stopSystem Failure : ProcessManager not Active" << endl; - cout << "Retry or Run 'shutdownSystem FORCEFUL' command" << endl << endl; - } - else - { - cout << endl << "**** stopSystem Failure : " << e.what() << endl; - cout << "Retry or Run 'shutdownSystem FORCEFUL' command" << endl << endl; - } + cout << endl << "**** stopSystem Failed : " << e.what() << endl; } } break; case 17: // shutdownSystem - parameters: graceful flag, Ack flag, suspendAnswer { - BRM::DBRM dbrm; - bool bDBRMReady = dbrm.isDBRMReady(); - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); - - cout << endl << "This command stops the processing of applications on all Modules within the Calpont System" << endl; - - try - { - if (gracefulTemp != GRACEFUL || - !bDBRMReady || - dbrm.isReadWrite()) - { - suspendAnswer = FORCE; - } - - if (suspendAnswer == CANCEL) // We don't have an answer from the command line. - { - // If there are bulkloads, ddl or dml happening, Ask what to do. - bool bIsDbrmUp = true; - execplan::SessionManager sessionManager; - BRM::SIDTIDEntry blockingsid; - std::vector tableLocks = dbrm.getAllTableLocks(); - bool bActiveTransactions = false; - if (!tableLocks.empty()) - { - oam.DisplayLockedTables(tableLocks, &dbrm); - bActiveTransactions = true; - } - if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) - { - cout << endl << "There are active transactions being processed" << endl; - bActiveTransactions = true; - } - - if (bActiveTransactions) - { - suspendAnswer = AskSuspendQuestion(CmdID); - bNeedsConfirm = false; - } - else - { - suspendAnswer = FORCE; - } - } - if (suspendAnswer == CANCEL) - { - // We're outa here. - break; - } - - if (bNeedsConfirm) - { - if (confirmPrompt("")) - break; - } - - switch (suspendAnswer) - { - case WAIT: - cout << endl << " Waiting for all transactions to complete" << flush; - dbrm.setSystemShutdownPending(true, false, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case ROLLBACK: - cout << endl << " Rollback of all transactions" << flush; - dbrm.setSystemShutdownPending(true, true, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case FORCE: - cout << endl << " System being shutdown now..."; - if (bDBRMReady) - { - dbrm.setSystemShutdownPending(true, false, true); - } - break; - case CANCEL: - break; - } - - // This won't return until the system is shutdown. It might take a while to finish what we're working on first. - - oam.stopSystem(gracefulTemp, ackTemp); - - if ( waitForStop() ) - cout << endl << " Successful stop of System " << endl << endl; - else - cout << endl << "**** stopSystem Failed : check log files" << endl; - - oam.shutdownSystem(gracefulTemp, ackTemp); + BRM::DBRM dbrm; + bool bDBRMReady = dbrm.isDBRMReady(); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); + bool bNeedsConfirm = true; - //hdfs / hadoop config - string DBRootStorageType; - try { - oam.getSystemConfig( "DBRootStorageType", DBRootStorageType); - } - catch(...) {} - - if ( DBRootStorageType == "hdfs") + if (arguments[1] == "y") { - string cmd = "pdsh -a '/" + startup::StartUp::installDir() + "/bin/infinidb stop' > /tmp/cc-stop.pdsh 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/cc-stop.pdsh", "exit") ) { - cout << endl << "ERROR: Stopping InfiniDB Service failure, check /tmp/cc-stop.pdsh. exit..." << endl; - } + bNeedsConfirm = false; } - } - catch (exception& e) - { - string Failed = e.what(); - - if ( gracefulTemp == FORCEFUL ) + cout << endl << "This command stops the processing of applications on all Modules within the Calpont System" << endl; + + if (gracefulTemp != GRACEFUL || + !bDBRMReady || + dbrm.isReadWrite()) { - string cmd = startup::StartUp::installDir() + "/bin/infinidb stop > /tmp/status.log"; - system(cmd.c_str()); - cout << endl << " Successful shutdown of System (stopped local infinidb service) " << endl << endl; + suspendAnswer = FORCE; } - - if (Failed.find("Connection refused") != string::npos) + + if (suspendAnswer == CANCEL) // We don't have an answer from the command line. { - cout << endl << "**** shutdownSystem Error : ProcessManager not Active, stopping infinidb service" << endl; - string cmd = startup::StartUp::installDir() + "/bin/infinidb stop > /tmp/status.log"; - system(cmd.c_str()); - cout << endl << " Successful stop of local infinidb service " << endl << endl; + // If there are bulkloads, ddl or dml happening, Ask what to do. + bool bIsDbrmUp = true; + execplan::SessionManager sessionManager; + BRM::SIDTIDEntry blockingsid; + std::vector tableLocks = dbrm.getAllTableLocks(); + bool bActiveTransactions = false; + if (!tableLocks.empty()) + { + oam.DisplayLockedTables(tableLocks, &dbrm); + bActiveTransactions = true; + } + if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) + { + cout << endl << "There are active transactions being processed" << endl; + bActiveTransactions = true; + } + + if (bActiveTransactions) + { + suspendAnswer = AskSuspendQuestion(CmdID); +// if (suspendAnswer == FORCE) +// { +// if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) +// { +// break; +// } +// } + bNeedsConfirm = false; + } + else + { + suspendAnswer = FORCE; + } } - else + if (suspendAnswer == CANCEL) { - cout << endl << "**** shutdownSystem Failure : " << e.what() << endl; - cout << "Retry using FORCEFUL option" << endl << endl; + // We're outa here. + break; } - - //hdfs / hadoop config - string DBRootStorageType; - try { - oam.getSystemConfig( "DBRootStorageType", DBRootStorageType); + + if (bNeedsConfirm) + { + if (confirmPrompt("")) + break; } - catch(...) {} - - if ( DBRootStorageType == "hdfs") + + switch (suspendAnswer) { - string cmd = "pdsh -a '" + startup::StartUp::installDir() + "/bin/infinidb stop' > /tmp/cc-stop.pdsh 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/cc-stop.pdsh", "exit") ) { - cout << endl << "ERROR: Stopping InfiniDB Service failure, check /tmp/cc-stop.pdsh. exit..." << endl; + case WAIT: + cout << endl << " Waiting for all transactions to complete" << flush; + dbrm.setSystemShutdownPending(true, false, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case ROLLBACK: + cout << endl << " Rollback of all transactions" << flush; + dbrm.setSystemShutdownPending(true, true, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case FORCE: + cout << endl << " System being shutdown now" << endl; + if (bDBRMReady) + { + dbrm.setSystemShutdownPending(true, false, true); + } + break; + case CANCEL: break; - } } - } - sleep(10); + try + { + // This won't return until the system is shutdown. It might take a while to finish what we're working on first. + oam.shutdownSystem(gracefulTemp, ackTemp); + } + catch (exception& e) + { + string cmd = startup::StartUp::installDir() + "/bin/infinidb stop > /tmp/status.log"; + system(cmd.c_str()); + cout << endl << " Successful shutdown of System " << endl << endl; + } } break; @@ -2109,6 +1987,7 @@ int processCommand(string* arguments) ModuleTypeConfig moduletypeconfig; ModuleConfig moduleconfig; systemmoduletypeconfig.moduletypeconfig.clear(); + string password; int systemModuleNumber = 0; try { @@ -2125,12 +2004,11 @@ int processCommand(string* arguments) } catch (exception& e) { - cout << endl << "**** startSystem Failed = " << e.what() << endl; + cout << endl << "**** getModuleConfig Failed = " << e.what() << endl; break; } - if ( systemModuleNumber > 1 ) - { + if ( systemModuleNumber > 1 ) { if (arguments[1] != "") password = arguments[1]; else @@ -2144,9 +2022,9 @@ int processCommand(string* arguments) string modulename; for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) { - for (pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); - ++pt) + for(pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); + pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); + ++pt) { modulename = (*pt).DeviceName; if ( (*pt).DisableState == oam::MANDISABLEDSTATE || @@ -2160,86 +2038,64 @@ int processCommand(string* arguments) cout.flush(); bool FAILED = false; - //hdfs / hadoop config - string DBRootStorageType; - try { - oam.getSystemConfig( "DBRootStorageType", DBRootStorageType); - } - catch(...) {} - - if ( DBRootStorageType == "hdfs") + for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) { - string cmd = "pdsh -a '" + startup::StartUp::installDir() + "/bin/infinidb restart' > /tmp/cc-restart.pdsh 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/cc-restart.pdsh", "exit") ) { - cout << endl << "ERROR: Restart InfiniDB Service failure, check /tmp/cc-restart.pdsh. exit..." << endl; + if( systemmoduletypeconfig.moduletypeconfig[i].ModuleType.empty() ) + // end of list break; - } - } - else - { - for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) + + int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; + if ( moduleCount == 0 ) + // skip if no modules + continue; + + for (pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); + pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end() ; + ++pt) { - if( systemmoduletypeconfig.moduletypeconfig[i].ModuleType.empty() ) - // end of list - break; - - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if ( moduleCount == 0 ) - // skip if no modules + modulename = (*pt).DeviceName; + + if ( (*pt).DisableState == oam::MANDISABLEDSTATE || + (*pt).DisableState == oam::AUTODISABLEDSTATE ) { continue; - - for (pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); - ++pt) - { - modulename = (*pt).DeviceName; - - if ( (*pt).DisableState == oam::MANDISABLEDSTATE || - (*pt).DisableState == oam::AUTODISABLEDSTATE ) - { - continue; + } + + if ( modulename == localModule ) { + cmd = startup::StartUp::installDir() + "/bin/infinidb restart >/dev/null 2>&1"; + int rtnCode = system(cmd.c_str()); + if (geteuid() == 0 && rtnCode != 0) { + cout << endl << "error with running 'infinidb restart' on local module " << endl; + cout << endl << "**** startSystem Failed" << endl; + break; } - - if ( modulename == localModule ) - { - cmd = startup::StartUp::installDir() + "/bin/infinidb restart > /tmp/start.log 2>&1"; - int rtnCode = system(cmd.c_str()); - if (geteuid() == 0 && WEXITSTATUS(rtnCode) != 0) - { - cout << endl << "error with running 'infinidb restart' on local module " << endl; - cout << endl << "**** startSystem Failed" << endl; - break; - } - - continue; + + continue; + } + + HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); + for( ; pt1 != (*pt).hostConfigList.end() ; pt1++) + { + //run remote command script + cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + (*pt1).IPAddr + " " + password + " '" + startup::StartUp::installDir() + "/bin/infinidb restart' 0"; + int rtnCode = system(cmd.c_str()); + if (rtnCode < 0) { + cout << endl << "error with running 'infinidb start' on module " + modulename << endl; + cout << endl << "**** startSystem Failed" << endl; + FAILED = true; + break; } - - HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); - for( ; pt1 != (*pt).hostConfigList.end() ; pt1++) + else { - //run remote command script - cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + (*pt1).IPAddr + " " + password + " '" + startup::StartUp::installDir() + "/bin/infinidb restart' 0"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) < 0) { - cout << endl << "error with running 'infinidb start' on module " + modulename << endl; + if (rtnCode > 0) { + cout << endl << "Invalid Password when running 'infinidb start' on module " + modulename << ", can retry by providing password as the second argument" << endl; cout << endl << "**** startSystem Failed" << endl; FAILED = true; break; } - else - { - if (rtnCode > 0) { - cout << endl << "Invalid Password when running 'infinidb start' on module " + modulename << ", can retry by providing password as the second argument" << endl; - cout << endl << "**** startSystem Failed" << endl; - FAILED = true; - break; - } - } } - if (FAILED) - break; } + if (FAILED) + break; } if (FAILED) break; @@ -2253,9 +2109,9 @@ int processCommand(string* arguments) //just kick off local server cout << " System being started, please wait..."; cout.flush(); - cmd = startup::StartUp::installDir() + "/bin/infinidb restart > /tmp/start.log 2>&1"; + cmd = startup::StartUp::installDir() + "/bin/infinidb restart >/dev/null 2>&1"; int rtnCode = system(cmd.c_str()); - if (geteuid() == 0 && WEXITSTATUS(rtnCode) != 0) { + if (geteuid() == 0 && rtnCode != 0) { cout << endl << "error with running 'infinidb restart' on local module " << endl; cout << endl << "**** startSystem Failed" << endl; break; @@ -2269,7 +2125,7 @@ int processCommand(string* arguments) } else { - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); try { @@ -2294,7 +2150,7 @@ int processCommand(string* arguments) case 19: // restartSystem - parameters: graceful flag, Ack flag { - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm, &password); + // restartSystem Command //don't restart if a disable module has a dbroot assigned to it if (!checkForDisabledModules()) { @@ -2302,8 +2158,6 @@ int processCommand(string* arguments) break; } - cout << endl << "This command stops and restarts the processing of applications on all Modules within the Calpont System" << endl; - // if infinidb service is down, then restart system by starting all of the infinidb services // this would be used after a shutdownSystem command // if infinidb service is up, send message to ProcMgr to restart system (which starts all processes) @@ -2311,11 +2165,6 @@ int processCommand(string* arguments) system(cmd.c_str()); if (!oam.checkLogStatus("/tmp/status.log", "InfiniDB is running") ) { - if (bNeedsConfirm) - { - if (confirmPrompt("")) // returns true if user wants to quit. - break; - } cout << endl << "restartSystem command, 'infinidb' service is down, sending command to" << endl; cout << "start the 'infinidb' service on all modules" << endl << endl; @@ -2323,6 +2172,7 @@ int processCommand(string* arguments) ModuleTypeConfig moduletypeconfig; ModuleConfig moduleconfig; systemmoduletypeconfig.moduletypeconfig.clear(); + string password; int systemModuleNumber = 0; try { @@ -2339,12 +2189,16 @@ int processCommand(string* arguments) } catch (exception& e) { - cout << endl << "**** restartSystem Failed = " << e.what() << endl; + cout << endl << "**** getModuleConfig Failed = " << e.what() << endl; break; } - if ( systemModuleNumber > 1 ) - { + if ( systemModuleNumber > 1 ) { + if (arguments[2] != "") + password = arguments[2]; + else + password = "ssh"; + // // perform start of InfiniDB of other servers in the system // @@ -2368,72 +2222,45 @@ int processCommand(string* arguments) cout.flush(); bool FAILED = false; - //hdfs / hadoop config - string DBRootStorageType; - try { - oam.getSystemConfig( "DBRootStorageType", DBRootStorageType); - } - catch(...) {} - - if ( DBRootStorageType == "hdfs") + for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) { - string cmd = "pdsh -a '" + startup::StartUp::installDir() + "/bin/infinidb restart' > /tmp/cc-restart.pdsh 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/cc-restart.pdsh", "exit") ) { - cout << endl << "ERROR: Restart InfiniDB Service failure, check /tmp/cc-restart.pdsh. exit..." << endl; + if( systemmoduletypeconfig.moduletypeconfig[i].ModuleType.empty() ) + // end of list break; - } - } - else - { - for (unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) + + int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; + if ( moduleCount == 0 ) + // skip if no modules + continue; + + for(pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end() ; + ++pt) { - if( systemmoduletypeconfig.moduletypeconfig[i].ModuleType.empty() ) - // end of list - break; - - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if ( moduleCount == 0 ) - // skip if no modules - continue; - - for(pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); - ++pt) + string modulename = (*pt).DeviceName; + if ( (*pt).DisableState == oam::MANDISABLEDSTATE || + (*pt).DisableState == oam::AUTODISABLEDSTATE ) { - string modulename = (*pt).DeviceName; - if ( (*pt).DisableState == oam::MANDISABLEDSTATE || - (*pt).DisableState == oam::AUTODISABLEDSTATE ) - continue; - - if ( modulename == localModule ) { - string cmd = startup::StartUp::installDir() + "/bin/infinidb restart > /tmp/start.log 2>&1"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { - cout << endl << "error with running 'infinidb start' on local module " << endl; - cout << endl << "**** startSystem Failed" << endl; - break; - } - - continue; + continue; + } + if ( modulename == localModule ) { + string cmd = startup::StartUp::installDir() + "/bin/infinidb start >/dev/null 2>&1"; + int rtnCode = system(cmd.c_str()); + if (rtnCode != 0) { + cout << endl << "error with running 'infinidb start' on local module " << endl; + cout << endl << "**** startSystem Failed" << endl; + break; } + + continue; } - string DBRootStorageType; - try - { - oam.getSystemConfig("DBRootStorageType", DBRootStorageType); - } - catch(...) {} - HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); for( ; pt1 != (*pt).hostConfigList.end() ; pt1++) { //run remote command script - cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + (*pt1).IPAddr + " " + password + " '" + startup::StartUp::installDir() + "/bin/infinidb restart' 0"; - + cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + (*pt1).IPAddr + " " + password + " '" + startup::StartUp::installDir() + "/bin/infinidb start' 0"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) < 0) { + if (rtnCode < 0) { cout << endl << "error with running 'infinidb start' on module " + modulename << endl; cout << endl << "**** startSystem Failed" << endl; FAILED = true; @@ -2464,9 +2291,9 @@ int processCommand(string* arguments) //just kick off local server cout << " System being restarted, please wait..."; cout.flush(); - string cmd = startup::StartUp::installDir() + "/bin/infinidb restart > /tmp/start.log 2>&1"; + string cmd = startup::StartUp::installDir() + "/bin/infinidb start > /tmp/status.log"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "error with running 'infinidb start' on local module " << endl; cout << endl << "**** restartSystem Failed" << endl; break; @@ -2482,85 +2309,93 @@ int processCommand(string* arguments) { BRM::DBRM dbrm; bool bDBRMReady = dbrm.isDBRMReady(); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); + bool bNeedsConfirm = true; - try - { - if (gracefulTemp != GRACEFUL || - !bDBRMReady || - dbrm.isReadWrite()) - { - suspendAnswer = FORCE; - } - - if (suspendAnswer == CANCEL) // We don't have an answer from the command line. - { - // If there are bulkloads, ddl or dml happening, Ask what to do. - bool bIsDbrmUp = true; - execplan::SessionManager sessionManager; - BRM::SIDTIDEntry blockingsid; - std::vector tableLocks = dbrm.getAllTableLocks(); - bool bActiveTransactions = false; - if (!tableLocks.empty()) - { - oam.DisplayLockedTables(tableLocks, &dbrm); - bActiveTransactions = true; - } - if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) - { - cout << endl << "There are active transactions being processed" << endl; - bActiveTransactions = true; - } - - if (bActiveTransactions) - { - suspendAnswer = AskSuspendQuestion(CmdID); - // if (suspendAnswer == FORCE) - // { - // if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) - // { - // break; - // } - // } - bNeedsConfirm = false; - } - else - { - suspendAnswer = FORCE; - } - } - if (suspendAnswer == CANCEL) - { - // We're outa here. - break; - } - if (bNeedsConfirm) - { - if (confirmPrompt("")) - break; - } - switch (suspendAnswer) - { - case WAIT: - cout << endl << " Waiting for all transactions to complete" << flush; - dbrm.setSystemShutdownPending(true, false, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case ROLLBACK: - cout << endl << " Rollback of all transactions" << flush; - dbrm.setSystemShutdownPending(true, true, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case FORCE: - cout << endl << " System being restarted now ..." << flush; - if (bDBRMReady) - { - dbrm.setSystemShutdownPending(true, false, true); - } - break; - case CANCEL: - break; - } + if (arguments[1] == "y") + { + bNeedsConfirm = false; + } + cout << endl << "This command stops and restarts the processing of applications on all Modules within the Calpont System" << endl; + + if (gracefulTemp != GRACEFUL || + !bDBRMReady || + dbrm.isReadWrite()) + { + suspendAnswer = FORCE; + } + + if (suspendAnswer == CANCEL) // We don't have an answer from the command line. + { + // If there are bulkloads, ddl or dml happening, Ask what to do. + bool bIsDbrmUp = true; + execplan::SessionManager sessionManager; + BRM::SIDTIDEntry blockingsid; + std::vector tableLocks = dbrm.getAllTableLocks(); + bool bActiveTransactions = false; + if (!tableLocks.empty()) + { + oam.DisplayLockedTables(tableLocks, &dbrm); + bActiveTransactions = true; + } + if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) + { + cout << endl << "There are active transactions being processed" << endl; + bActiveTransactions = true; + } + + if (bActiveTransactions) + { + suspendAnswer = AskSuspendQuestion(CmdID); +// if (suspendAnswer == FORCE) +// { +// if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) +// { +// break; +// } +// } + bNeedsConfirm = false; + } + else + { + suspendAnswer = FORCE; + } + } + if (suspendAnswer == CANCEL) + { + // We're outa here. + break; + } + if (bNeedsConfirm) + { + if (confirmPrompt("")) + break; + } + switch (suspendAnswer) + { + case WAIT: + cout << endl << " Waiting for all transactions to complete" << flush; + dbrm.setSystemShutdownPending(true, false, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case ROLLBACK: + cout << endl << " Rollback of all transactions" << flush; + dbrm.setSystemShutdownPending(true, true, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case FORCE: + cout << endl << " System being restarted now ..." << flush; + if (bDBRMReady) + { + dbrm.setSystemShutdownPending(true, false, true); + } + break; + case CANCEL: + break; + } + try + { int returnStatus = oam.restartSystem(gracefulTemp, ackTemp); switch (returnStatus) { @@ -2576,7 +2411,7 @@ int processCommand(string* arguments) default: cout << endl << "**** restartSystem Failed : Check system logs" << endl; break; - } + } } catch (exception& e) { @@ -2834,58 +2669,76 @@ int processCommand(string* arguments) BRM::DBRM dbrm; bool bDBRMReady = dbrm.isDBRMReady(); string module; + bool bConfirmAnswer = true; bool bUseHotStandby = true; - // First get the values for the standard arguments - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); - // Now check for arguments unique to this command. In this case, a valid - // module name. - for (int i = 1; i < ArgNum; i++) - { + suspendAnswer = CANCEL; + int i; + gracefulTemp = FORCEFUL; + // Command line Arguments can be "y", "Y", pmname, and suspendAnswer + // No check is made for mutually exclusive command line arguments. + for (i = 1; i < ArgNum; i++) + { + if (arguments[i] == "y" || arguments[i] == "Y" ) + bConfirmAnswer = false; + else + if (arguments[i] == "WAIT") + suspendAnswer = WAIT; + else +// if (arguments[i] == "ROLLBACK") +// suspendAnswer = ROLLBACK; +// else + if (arguments[i] == "FORCE") + suspendAnswer = FORCE; + else if (arguments[i].size() > 0) { if (oam.validateModule(arguments[i]) == API_SUCCESS) { module = arguments[i]; bUseHotStandby = false; + } + else + { + cout << endl << "**** switchParentOAMModule Failed : Unknown paramater " << arguments[i] << endl; break; } } } + if (i < ArgNum) + { + // We had an invalid parameter + break; + } //check if there are more than 1 pm modules to start with ModuleTypeConfig moduletypeconfig; oam.getSystemConfig("pm", moduletypeconfig); - if ( moduletypeconfig.ModuleCount < 2 ) - { + if ( moduletypeconfig.ModuleCount < 2 ) { cout << endl << "**** switchParentOAMModule Failed : Command only support on systems with Multiple Performance Modules" << endl; -// break; + break; } string DBRootStorageType; - try - { + try { oam.getSystemConfig("DBRootStorageType", DBRootStorageType); } catch(...) {} string GlusterConfig = "n"; - try - { + try { oam.getSystemConfig( "GlusterConfig", GlusterConfig); } catch(...) {} - if (DBRootStorageType == "internal" && GlusterConfig == "n") - { - cout << endl << "**** switchParentOAMModule Failed : DBRoot Storage type = internal/non-data-replication" << endl; + if (DBRootStorageType == "internal" && GlusterConfig == "n"){ + cout << endl << "**** switchParentOAMModule Failed : DBRoot Storage type = internal/non-data-replication" << endl; break; } if (bUseHotStandby) { oam.getSystemConfig("StandbyOAMModuleName", module); - if ( module.empty() || module == oam::UnassignedName ) - { + if ( module.empty() || module == oam::UnassignedName ) { cout << endl << "**** switchParentOAMModule Failed : There's no hot standby defined" << endl << " enter a Performance Module" << endl; break; } @@ -2895,8 +2748,7 @@ int processCommand(string* arguments) else { parentOAMModule = getParentOAMModule(); - if ( module == parentOAMModule ) - { + if ( module == parentOAMModule ) { cout << endl << "**** switchParentOAMModule Failed : " << module << " is already the Active Parent OAM Module" << endl; break; } @@ -2904,106 +2756,104 @@ int processCommand(string* arguments) cout << endl << "Switching to the Performance Module '" << module << "'" << endl; } - if (bNeedsConfirm) - { + if (bConfirmAnswer) { // confirm request if (confirmPrompt("This command switches the Active Parent OAM Module and should only be executed on an idle system.")) break; } - try - { - - if (!bDBRMReady || - dbrm.isReadWrite() != 0) - { - suspendAnswer = FORCE; - } + if (!bDBRMReady || + dbrm.isReadWrite() != 0) + { + suspendAnswer = FORCE; + } - if (suspendAnswer == CANCEL) // We don't have an answer from the command line. - { - // If there are bulkloads, ddl or dml happening, Ask what to do. - bool bIsDbrmUp = true; - execplan::SessionManager sessionManager; - BRM::SIDTIDEntry blockingsid; - std::vector tableLocks = dbrm.getAllTableLocks(); - bool bActiveTransactions = false; - if (!tableLocks.empty()) - { - oam.DisplayLockedTables(tableLocks, &dbrm); - bActiveTransactions = true; - } - if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) - { - cout << endl << "There are active transactions being processed" << endl; - bActiveTransactions = true; - } + if (suspendAnswer == CANCEL) // We don't have an answer from the command line. + { + // If there are bulkloads, ddl or dml happening, Ask what to do. + bool bIsDbrmUp = true; + execplan::SessionManager sessionManager; + BRM::SIDTIDEntry blockingsid; + std::vector tableLocks = dbrm.getAllTableLocks(); + bool bActiveTransactions = false; + if (!tableLocks.empty()) + { + oam.DisplayLockedTables(tableLocks, &dbrm); + bActiveTransactions = true; + } + if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) + { + cout << endl << "There are active transactions being processed" << endl; + bActiveTransactions = true; + } - if (bActiveTransactions) - { - suspendAnswer = AskSuspendQuestion(CmdID); - // if (suspendAnswer == FORCE) - // { - // if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) - // { - // break; - // } - // } - } - else - { - suspendAnswer = FORCE; - } - } - if (suspendAnswer == CANCEL) - { - // We're outa here. - break; - } - switch (suspendAnswer) - { - case WAIT: - cout << endl << " Waiting for all transactions to complete" << flush; - dbrm.setSystemShutdownPending(true, false, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case ROLLBACK: - cout << endl << " Rollback of all transactions" << flush; - dbrm.setSystemShutdownPending(true, true, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case FORCE: - cout << endl << " Active Parent OAM switching now" << endl; - if (bDBRMReady) - { - dbrm.setSystemShutdownPending(true, false, true); - } - break; - case CANCEL: - break; - } + if (bActiveTransactions) + { + suspendAnswer = AskSuspendQuestion(CmdID); +// if (suspendAnswer == FORCE) +// { +// if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) +// { +// break; +// } +// } + } + else + { + suspendAnswer = FORCE; + } + } + if (suspendAnswer == CANCEL) + { + // We're outa here. + break; + } + switch (suspendAnswer) + { + case WAIT: + cout << endl << " Waiting for all transactions to complete" << flush; + dbrm.setSystemShutdownPending(true, false, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case ROLLBACK: + cout << endl << " Rollback of all transactions" << flush; + dbrm.setSystemShutdownPending(true, true, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case FORCE: + cout << endl << " Active Parent OAM switching now" << endl; + if (bDBRMReady) + { + dbrm.setSystemShutdownPending(true, false, true); + } + break; + case CANCEL: + break; + } - if (oam.switchParentOAMModule(module, gracefulTemp)) - { - if (waitForActive()) { - // give time for new ProcMgr to go active - sleep (5); + try + { + if (oam.switchParentOAMModule(module, gracefulTemp)) + { + if ( waitForActive() ) { + // give time for new ProcMgr to go active + sleep (5); cout << endl << " Successful Switch Active Parent OAM Module" << endl << endl; - } + } else cout << endl << "**** Switch Active Parent OAM Module failed : check log files" << endl; - } + } else { - // give time for new ProcMgr to go active - sleep (5); + // give time for new ProcMgr to go active + sleep (5); cout << endl << " Successful Switch Active Parent OAM Module" << endl << endl; } } catch (exception& e) { cout << endl << "**** switchParentOAMModule Failed : " << e.what() << endl; - break; + break; } } break; @@ -3023,7 +2873,7 @@ int processCommand(string* arguments) if ( systemstatus.systemdbrootstatus.dbrootstatus.size() == 0 ) { - cout << " No External DBRoot Storage Configured" << endl; + cout << " No DBRoot Storage Configured" << endl; break; } @@ -3127,261 +2977,254 @@ int processCommand(string* arguments) case 31: // movePmDbrootConfig parameters: pm-reside dbroot-list pm-to { - if ( localModule != parentOAMModule ) { - // exit out since not on active module - cout << endl << "**** movePmDbrootConfig Failed : Can only run command on Active OAM Parent Module (" << parentOAMModule << ")." << endl; - break; - } - - //check the system status / service status and only allow command when System is MAN_OFFLINE - string cmd = startup::StartUp::installDir() + "/bin/infinidb status > /tmp/status.log"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/status.log", "InfiniDB is running") ) - { - SystemStatus systemstatus; - try { - oam.getSystemStatus(systemstatus); - - if (systemstatus.SystemOpState != oam::MAN_OFFLINE ) { - cout << endl << "**** movePmDbrootConfig Failed, System has to be in a MAN_OFFLINE state, stop system first" << endl; - break; - } - } - catch (exception& e) - { - cout << endl << "**** movePmDbrootConfig Failed : " << e.what() << endl; - break; - } - catch(...) - { - cout << endl << "**** movePmDbrootConfig Failed, Failed return from getSystemStatus API" << endl; + if ( localModule != parentOAMModule ) { + // exit out since not on active module + cout << endl << "**** movePmDbrootConfig Failed : Can only run command on Active OAM Parent Module (" << parentOAMModule << ")." << endl; break; } - } - - if (arguments[3] == "") - { - // need arguments - cout << endl << "**** movePmDbrootConfig Failed : Missing a required Parameter, enter 'help' for additional information" << endl; - break; - } - - string residePM = arguments[1]; - string dbrootIDs = arguments[2]; - string toPM = arguments[3]; - - string residePMID = residePM.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE);; - string toPMID = toPM.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE);; - - // check module status - try{ - bool degraded; - int opState; - oam.getModuleStatus(toPM, opState, degraded); - if (opState == oam::AUTO_DISABLED || - opState == oam::MAN_DISABLED) + //check the system status / service status and only allow command when System is MAN_OFFLINE + string cmd = startup::StartUp::installDir() + "/bin/infinidb status > /tmp/status.log"; + system(cmd.c_str()); + if (oam.checkLogStatus("/tmp/status.log", "InfiniDB is running") ) { - cout << "**** movePmDbrootConfig Failed: " << toPM << " is DISABLED." << endl; - cout << "Run alterSystem-EnableModule to enable module" << endl; - break; + SystemStatus systemstatus; + try { + oam.getSystemStatus(systemstatus); + + if (systemstatus.SystemOpState != oam::MAN_OFFLINE ) { + cout << endl << "**** movePmDbrootConfig Failed, System has to be in a MAN_OFFLINE state, stop system first" << endl; + break; + } + } + catch (exception& e) + { + cout << endl << "**** movePmDbrootConfig Failed : " << e.what() << endl; + break; + } + catch(...) + { + cout << endl << "**** movePmDbrootConfig Failed, Failed return from getSystemStatus API" << endl; + break; + } } - if (opState == oam::FAILED) - { - cout << "**** movePmDbrootConfig Failed: " << toPM << " is in a FAILED state." << endl; - break; - } - } - catch (exception& ex) - {} - - bool moveDBRoot1 = false; - bool found = false; - boost::char_separator sep(", "); - boost::tokenizer< boost::char_separator > tokens(dbrootIDs, sep); - for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); - it != tokens.end(); - ++it) - { - if (*it == "1" ) { - moveDBRoot1 = true; - break; - } + if (arguments[3] == "") + { + // need arguments + cout << endl << "**** movePmDbrootConfig Failed : Missing a required Parameter, enter 'help' for additional information" << endl; + break; + } - //if gluster, check if toPM is has a copy - string GlusterConfig; - try { - oam.getSystemConfig("GlusterConfig", GlusterConfig); + string residePM = arguments[1]; + string dbrootIDs = arguments[2]; + string toPM = arguments[3]; + + string residePMID = residePM.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE);; + string toPMID = toPM.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE);; + + // check module status + try{ + bool degraded; + int opState; + oam.getModuleStatus(toPM, opState, degraded); + + if (opState == oam::AUTO_DISABLED || + opState == oam::MAN_DISABLED) + { + cout << "**** movePmDbrootConfig Failed: " << toPM << " is DISABLED." << endl; + cout << "Run alterSystem-EnableModule to enable module" << endl; + break; + } } - catch(...) {} - - if ( GlusterConfig == "y" ) + catch (exception& ex) + {} + + bool moveDBRoot1 = false; + bool found = false; + boost::char_separator sep(", "); + boost::tokenizer< boost::char_separator > tokens(dbrootIDs, sep); + for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); + it != tokens.end(); + ++it) { - string pmList = ""; - try { - string errmsg; - oam.glusterctl(oam::GLUSTER_WHOHAS, *it, pmList, errmsg); + if (*it == "1" ) { + moveDBRoot1 = true; + break; } - catch (...) - {} - boost::char_separator sep(" "); - boost::tokenizer< boost::char_separator > tokens(pmList, sep); - for ( boost::tokenizer< boost::char_separator >::iterator it1 = tokens.begin(); - it1 != tokens.end(); - ++it1) + //if gluster, check if toPM is has a copy + string GlusterConfig; + try { + oam.getSystemConfig("GlusterConfig", GlusterConfig); + } + catch(...) {} + + if ( GlusterConfig == "y" ) { - if ( *it1 == toPMID ) + string pmList = ""; + try { + string errmsg; + oam.glusterctl(oam::GLUSTER_WHOHAS, *it, pmList, errmsg); + } + catch (...) + {} + + boost::char_separator sep(" "); + boost::tokenizer< boost::char_separator > tokens(pmList, sep); + for ( boost::tokenizer< boost::char_separator >::iterator it1 = tokens.begin(); + it1 != tokens.end(); + ++it1) { - found = true; + if ( *it1 == toPMID ) + { + found = true; + break; + } + } + + if (!found) + { + cout << endl << "**** movePmDbrootConfig Failed : Data Redundancy Configured, DBRoot #" << *it << " doesn't have a copy on " << toPM << endl; + cout << "Run getStorageConfig to get copy information" << endl << endl; break; } } + else + found = true; + } + + if (moveDBRoot1) { + cout << endl << "**** movePmDbrootConfig Failed : Can't move dbroot #1" << endl << endl; + break; + } + + if (!found) + { + break; + } - if (!found) - { - cout << endl << "**** movePmDbrootConfig Failed : Data Redundancy Configured, DBRoot #" << *it << " doesn't have a copy on " << toPM << endl; - cout << "Run getStorageConfig to get copy information" << endl << endl; - break; - } + + if (residePM.find("pm") == string::npos ) { + cout << endl << "**** movePmDbrootConfig Failed : Parmameter 1 is not a Performance Module name, enter 'help' for additional information" << endl; + break; } - else - found = true; - } - if (moveDBRoot1) { - cout << endl << "**** movePmDbrootConfig Failed : Can't move dbroot #1" << endl << endl; - break; - } + if (toPM.find("pm") == string::npos ) { + cout << endl << "**** movePmDbrootConfig Failed : Parmameter 3 is not a Performance Module name, enter 'help' for additional information" << endl; + break; + } - if (!found) - { - break; - } - + if (residePM == toPM ) { + cout << endl << "**** movePmDbrootConfig Failed : Reside and To Performance Modules are the same" << endl; + break; + } - if (residePM.find("pm") == string::npos ) { - cout << endl << "**** movePmDbrootConfig Failed : Parmameter 1 is not a Performance Module name, enter 'help' for additional information" << endl; - break; - } + //get dbroots ids for reside PM + DBRootConfigList residedbrootConfigList; + try + { + oam.getPmDbrootConfig(atoi(residePMID.c_str()), residedbrootConfigList); - if (toPM.find("pm") == string::npos ) { - cout << endl << "**** movePmDbrootConfig Failed : Parmameter 3 is not a Performance Module name, enter 'help' for additional information" << endl; - break; - } + cout << endl << "DBRoot IDs currently assigned to '" + residePM + "' = "; - if (residePM == toPM ) { - cout << endl << "**** movePmDbrootConfig Failed : Reside and To Performance Modules are the same" << endl; - break; - } + DBRootConfigList::iterator pt = residedbrootConfigList.begin(); + for( ; pt != residedbrootConfigList.end() ;) + { + cout << oam.itoa(*pt); + pt++; + if (pt != residedbrootConfigList.end()) + cout << ", "; + } + cout << endl; + } + catch (exception& e) + { + cout << endl << "**** getPmDbrootConfig Failed for '" << residePM << "' : " << e.what() << endl; + break; + } - //get dbroots ids for reside PM - DBRootConfigList residedbrootConfigList; + //get dbroots ids for reside PM + DBRootConfigList todbrootConfigList; + try + { + oam.getPmDbrootConfig(atoi(toPMID.c_str()), todbrootConfigList); - try - { - oam.getPmDbrootConfig(atoi(residePMID.c_str()), residedbrootConfigList); - - cout << endl << "DBRoot IDs currently assigned to '" + residePM + "' = "; + cout << "DBRoot IDs currently assigned to '" + toPM + "' = "; - DBRootConfigList::iterator pt = residedbrootConfigList.begin(); - for( ; pt != residedbrootConfigList.end() ;) - { - cout << oam.itoa(*pt); - pt++; - if (pt != residedbrootConfigList.end()) - cout << ", "; - } - cout << endl; - } - catch (exception& e) - { - cout << endl << "**** getPmDbrootConfig Failed for '" << residePM << "' : " << e.what() << endl; - break; - } - - //get dbroots ids for reside PM - DBRootConfigList todbrootConfigList; - try - { - oam.getPmDbrootConfig(atoi(toPMID.c_str()), todbrootConfigList); + DBRootConfigList::iterator pt = todbrootConfigList.begin(); + for( ; pt != todbrootConfigList.end() ;) + { + cout << oam.itoa(*pt); + pt++; + if (pt != todbrootConfigList.end()) + cout << ", "; + } + cout << endl; + } + catch (exception& e) + { + cout << endl << "**** getPmDbrootConfig Failed for '" << toPM << "' : " << e.what() << endl; + break; + } - cout << "DBRoot IDs currently assigned to '" + toPM + "' = "; + cout << endl << "DBroot IDs being moved, please wait..." << endl << endl; - DBRootConfigList::iterator pt = todbrootConfigList.begin(); - for( ; pt != todbrootConfigList.end() ;) + try { + oam.manualMovePmDbroot(residePM, dbrootIDs, toPM); + } + catch (...) { - cout << oam.itoa(*pt); - pt++; - if (pt != todbrootConfigList.end()) - cout << ", "; + cout << endl << "**** manualMovePmDbroot Failed : API Failure" << endl; + break; } - cout << endl; - } - catch (exception& e) - { - cout << endl << "**** getPmDbrootConfig Failed for '" << toPM << "' : " << e.what() << endl; - break; - } - cout << endl << "DBroot IDs being moved, please wait..." << endl << endl; - - try { - oam.manualMovePmDbroot(residePM, dbrootIDs, toPM); - } - catch (...) - { - cout << endl << "**** manualMovePmDbroot Failed : API Failure" << endl; - break; - } + //get dbroots ids for reside PM + try + { + residedbrootConfigList.clear(); + oam.getPmDbrootConfig(atoi(residePMID.c_str()), residedbrootConfigList); - //get dbroots ids for reside PM - try - { - residedbrootConfigList.clear(); - oam.getPmDbrootConfig(atoi(residePMID.c_str()), residedbrootConfigList); + cout << "DBRoot IDs newly assigned to '" + residePM + "' = "; - cout << "DBRoot IDs newly assigned to '" + residePM + "' = "; + DBRootConfigList::iterator pt = residedbrootConfigList.begin(); + for( ; pt != residedbrootConfigList.end() ;) + { + cout << oam.itoa(*pt); + pt++; + if (pt != residedbrootConfigList.end()) + cout << ", "; + } + cout << endl; + } + catch (exception& e) + { + cout << endl << "**** getPmDbrootConfig Failed for '" << toPM << "' : " << e.what() << endl; + break; + } - DBRootConfigList::iterator pt = residedbrootConfigList.begin(); - for( ; pt != residedbrootConfigList.end() ;) - { - cout << oam.itoa(*pt); - pt++; - if (pt != residedbrootConfigList.end()) - cout << ", "; - } - cout << endl; - } - catch (exception& e) - { - cout << endl << "**** getPmDbrootConfig Failed for '" << toPM << "' : " << e.what() << endl; - break; - } - - try - { - todbrootConfigList.clear(); - oam.getPmDbrootConfig(atoi(toPMID.c_str()), todbrootConfigList); + try + { + todbrootConfigList.clear(); + oam.getPmDbrootConfig(atoi(toPMID.c_str()), todbrootConfigList); - cout << "DBRoot IDs newly assigned to '" + toPM + "' = "; + cout << "DBRoot IDs newly assigned to '" + toPM + "' = "; - DBRootConfigList::iterator pt = todbrootConfigList.begin(); - for( ; pt != todbrootConfigList.end() ;) - { - cout << oam.itoa(*pt); - pt++; - if (pt != todbrootConfigList.end()) - cout << ", "; - } - cout << endl; - } - catch (exception& e) - { - cout << endl << "**** getPmDbrootConfig Failed for '" << toPM << "' : " << e.what() << endl; - break; - } + DBRootConfigList::iterator pt = todbrootConfigList.begin(); + for( ; pt != todbrootConfigList.end() ;) + { + cout << oam.itoa(*pt); + pt++; + if (pt != todbrootConfigList.end()) + cout << ", "; + } + cout << endl; + } + catch (exception& e) + { + cout << endl << "**** getPmDbrootConfig Failed for '" << toPM << "' : " << e.what() << endl; + break; + } } break; @@ -3389,92 +3232,96 @@ int processCommand(string* arguments) case 32: // suspendDatabaseWrites { BRM::DBRM dbrm; - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); - + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); + bool bNeedsConfirm = true; + if (arguments[1] == "y") + { + bNeedsConfirm = false; + } cout << endl << "This command suspends the DDL/DML writes to the Calpont Database" << endl; - try - { - if (!dbrm.isDBRMReady()) - { - cout << endl << " The Controller Node is not responding.\n The system can't be set into write suspend mode" << endl << flush; - break; - } - else - if (dbrm.isReadWrite() != 0) - { - suspendAnswer = FORCE; - } + if (!dbrm.isDBRMReady()) + { + cout << endl << " The Controller Node is not responding.\n The system can't be set into write suspend mode" << endl << flush; + break; + } + else + if (dbrm.isReadWrite() != 0) + { + suspendAnswer = FORCE; + } - // If there are bulkloads, ddl or dml happening, refuse the request - if (suspendAnswer == CANCEL) // We don't have an answer from the command line. - { - // If there are bulkloads, ddl or dml happening, Ask what to do. - bool bIsDbrmUp = true; - execplan::SessionManager sessionManager; - BRM::SIDTIDEntry blockingsid; - std::vector tableLocks = dbrm.getAllTableLocks(); - bool bActiveTransactions = false; - if (!tableLocks.empty()) - { - oam.DisplayLockedTables(tableLocks, &dbrm); - bActiveTransactions = true; - } - if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) - { - cout << endl << "There are active transactions being processed" << endl; - bActiveTransactions = true; - } + // If there are bulkloads, ddl or dml happening, refuse the request + if (suspendAnswer == CANCEL) // We don't have an answer from the command line. + { + // If there are bulkloads, ddl or dml happening, Ask what to do. + bool bIsDbrmUp = true; + execplan::SessionManager sessionManager; + BRM::SIDTIDEntry blockingsid; + std::vector tableLocks = dbrm.getAllTableLocks(); + bool bActiveTransactions = false; + if (!tableLocks.empty()) + { + oam.DisplayLockedTables(tableLocks, &dbrm); + bActiveTransactions = true; + } + if (sessionManager.checkActiveTransaction(0, bIsDbrmUp, blockingsid)) + { + cout << endl << "There are active transactions being processed" << endl; + bActiveTransactions = true; + } - if (bActiveTransactions) - { - suspendAnswer = AskSuspendQuestion(CmdID); - // if (suspendAnswer == FORCE) - // { - // if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) - // { - // break; - // } - // } - bNeedsConfirm = false; - } - else - { - suspendAnswer = FORCE; - } - } - if (suspendAnswer == CANCEL) - { - // We're outa here. - break; - } - if (bNeedsConfirm) - { - if (confirmPrompt("")) - break; - } - switch (suspendAnswer) - { - case WAIT: - cout << endl << " Waiting for all transactions to complete" << flush; - dbrm.setSystemSuspendPending(true, false); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case ROLLBACK: - cout << endl << " Rollback of all transactions" << flush; - dbrm.setSystemSuspendPending(true, true); - gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown - break; - case FORCE: - case CANCEL: - default: - gracefulTemp = FORCEFUL; - break; - } + if (bActiveTransactions) + { + suspendAnswer = AskSuspendQuestion(CmdID); +// if (suspendAnswer == FORCE) +// { +// if (confirmPrompt("Force may cause data problems and should only be used in extreme circumstances")) +// { +// break; +// } +// } + bNeedsConfirm = false; + } + else + { + suspendAnswer = FORCE; + } + } + if (suspendAnswer == CANCEL) + { + // We're outa here. + break; + } + if (bNeedsConfirm) + { + if (confirmPrompt("")) + break; + } + switch (suspendAnswer) + { + case WAIT: + cout << endl << " Waiting for all transactions to complete" << flush; + dbrm.setSystemSuspendPending(true, false); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case ROLLBACK: + cout << endl << " Rollback of all transactions" << flush; + dbrm.setSystemSuspendPending(true, true); + gracefulTemp = GRACEFUL_WAIT; // Causes procmgr to wait for all table locks to free and all transactions to finish before shutdown + break; + case FORCE: + case CANCEL: + default: + gracefulTemp = FORCEFUL; + break; + } - // stop writes to Calpont Database - oam.SuspendWrites(gracefulTemp, ackTemp); - } + // stop writes to Calpont Database + try + { + oam.SuspendWrites(gracefulTemp, ackTemp); + } catch (exception& e) { cout << endl << "**** stopDatabaseWrites Failed: " << e.what() << endl; @@ -3530,89 +3377,11 @@ int processCommand(string* arguments) cout << endl << "**** resumeDatabaseWrites Failed" << endl; break; } - break; - } - - case 34: // unassignDbrootPmConfig parameters: dbroot-list - { - if ( localModule != parentOAMModule ) { - // exit out since not on active module - cout << endl << "**** unassignDbrootPmConfig Failed : Can only run command on Active OAM Parent Module (" << parentOAMModule << ")." << endl; - break; - } - - //check the system status / service status and only allow command when System is MAN_OFFLINE - string cmd = startup::StartUp::installDir() + "/bin/infinidb status > /tmp/status.log"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/status.log", "InfiniDB is running") ) - { - SystemStatus systemstatus; - try { - oam.getSystemStatus(systemstatus); - - if (systemstatus.SystemOpState != oam::MAN_OFFLINE ) { - cout << endl << "**** unassignDbrootPmConfig Failed, System has to be in a MAN_OFFLINE state, stop system first" << endl; - break; - } - } - catch (exception& e) - { - cout << endl << "**** unassignDbrootPmConfig Failed : " << e.what() << endl; - break; - } - catch(...) - { - cout << endl << "**** unassignDbrootPmConfig Failed, Failed return from getSystemStatus API" << endl; - break; - } - } - else - { - cout << endl << "**** unassignDbrootPmConfig Failed, System is shutdown. Needs to be stopped" << endl; - break; - } - - if (arguments[2] == "") - { - // need atleast 2 arguments - cout << endl << "**** unassignDbrootPmConfig Failed : Missing a required Parameter, enter 'help' for additional information" << endl; - break; - } - - string dbrootIDs = arguments[1]; - string residePM = arguments[2]; - - if (arguments[2].find("pm") == string::npos ) { - cout << endl << "**** unassignDbrootPmConfig Failed : Parmameter 2 is not a Performance Module name, enter 'help' for additional information" << endl; - break; - } - - DBRootConfigList dbrootlist; - - boost::char_separator sep(", "); - boost::tokenizer< boost::char_separator > tokens(dbrootIDs, sep); - for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); - it != tokens.end(); - ++it) - { - dbrootlist.push_back(atoi((*it).c_str())); - } - - cout << endl; - - //get dbroots ids for reside PM - try - { - oam.unassignDbroot(residePM, dbrootlist); + break; + } - cout << endl << " Successfully Unassigned DBRoots " << endl << endl; - - } - catch (exception& e) - { - cout << endl << "**** Failed Unassign of DBRoots: " << e.what() << endl; - break; - } + case 34: // AVAILABLE + { } break; @@ -3649,11 +3418,6 @@ int processCommand(string* arguments) break; } } - else - { - cout << endl << "**** assignDbrootPmConfig Failed, System is shutdown. Needs to be stopped" << endl; - break; - } if (arguments[2] == "") { @@ -3670,29 +3434,6 @@ int processCommand(string* arguments) break; } - // check module status - try{ - bool degraded; - int opState; - oam.getModuleStatus(toPM, opState, degraded); - - if (opState == oam::AUTO_DISABLED || - opState == oam::MAN_DISABLED) - { - cout << "**** assignDbrootPmConfig Failed: " << toPM << " is DISABLED." << endl; - cout << "Run alterSystem-EnableModule to enable module" << endl; - break; - } - - if (opState == oam::FAILED) - { - cout << "**** assignDbrootPmConfig Failed: " << toPM << " is in a FAILED state." << endl; - break; - } - } - catch (exception& ex) - {} - DBRootConfigList dbrootlist; boost::char_separator sep(", "); @@ -3719,7 +3460,7 @@ int processCommand(string* arguments) if (DBRootStorageType == "external" ){ string GlusterConfig = "n"; - string cloud = oam::UnassignedName; + string cloud = "n"; try { oam.getSystemConfig("Cloud", cloud); oam.getSystemConfig( "GlusterConfig", GlusterConfig); @@ -3727,7 +3468,7 @@ int processCommand(string* arguments) catch(...) {} - if ( GlusterConfig == "n" && cloud == oam::UnassignedName) + if ( GlusterConfig == "n" && cloud != "amazon") cout << " REMINDER: Update the /etc/fstab on " << toPM << " to include these dbroot mounts" << endl << endl; break; @@ -4141,13 +3882,13 @@ int processCommand(string* arguments) case 43: // assignElasticIPAddress { //get cloud configuration data - string cloud = oam::UnassignedName; + string cloud = "n"; try{ oam.getSystemConfig("Cloud", cloud); } catch(...) {} - if ( cloud == oam::UnassignedName ) + if ( cloud != "amazon" ) { cout << endl << "**** assignElasticIPAddress Not Supported : For Amazon Systems only" << endl; break; @@ -4296,13 +4037,13 @@ int processCommand(string* arguments) case 44: // unassignElasticIPAddress { //get cloud configuration data - string cloud = oam::UnassignedName; + string cloud = "n"; try{ oam.getSystemConfig("Cloud", cloud); } catch(...) {} - if ( cloud == oam::UnassignedName ) + if ( cloud != "amazon" ) { cout << endl << "**** unassignElasticIPAddress Not Supported : For Amazon Systems only" << endl; break; @@ -4605,13 +4346,13 @@ int processCommand(string* arguments) } //get cloud configuration data - string cloud = oam::UnassignedName; + string cloud = "n"; try{ oam.getSystemConfig("Cloud", cloud); } catch(...) {} - if ( cloud == "amazon-ec2" || cloud == "amazon-vpc" ) + if ( cloud == "amazon" ) { cout << endl << "Amazon Instance Configuration" << endl << endl; @@ -4625,17 +4366,6 @@ int processCommand(string* arguments) cout << "UMInstanceType = " << UMInstanceType << endl; } catch(...) {} - - if ( cloud == "amazon-vpc" ) - { - string AmazonSubNetID = oam::UnassignedName; - try{ - oam.getSystemConfig("AmazonSubNetID", AmazonSubNetID); - - cout << "AmazonSubNetID = " << AmazonSubNetID << endl; - } - catch(...) {} - } } cout << endl; @@ -4711,7 +4441,7 @@ int processCommand(string* arguments) cout << endl; if ( rootUser) { - system("rpm -qi infinidb-platform > /tmp/calpont.txt 2>&1"); + system("rpm -qi calpont > /tmp/calpont.txt 2>&1"); if (oam.checkLogStatus("/tmp/calpont.txt", "Name")) system("cat /tmp/calpont.txt"); else { @@ -4762,15 +4492,13 @@ int processCommand(string* arguments) string GlusterConfig = "n"; int GlusterCopies; - string cloud = oam::UnassignedName; + string cloud = "n"; string GlusterStorageType; - string AmazonVPCNextPrivateIP; try { oam.getSystemConfig("GlusterConfig", GlusterConfig); oam.getSystemConfig("GlusterCopies", GlusterCopies); oam.getSystemConfig("Cloud", cloud); oam.getSystemConfig("GlusterStorageType", GlusterStorageType); - oam.getSystemConfig("AmazonVPCNextPrivateIP", AmazonVPCNextPrivateIP); } catch(...) {} @@ -4784,8 +4512,8 @@ int processCommand(string* arguments) string moduleName; int moduleCount; string password; - typedef std::vector inputNames; - inputNames inputnames; + typedef std::vector hostNames; + hostNames hostnames; typedef std::vector umStorageNames; umStorageNames umstoragenames; int hostArg; @@ -4794,7 +4522,7 @@ int processCommand(string* arguments) //check if module type or module name was entered if ( arguments[1].size() == 2 ) { //Module Type was entered - if (arguments[3] == "" && cloud == oam::UnassignedName) + if (arguments[3] == "" && cloud == "n") { // need at least arguments cout << endl << "**** addModule Failed : Missing a required Parameter, enter 'help' for additional information" << endl; @@ -4816,7 +4544,7 @@ int processCommand(string* arguments) else { //Module Name was entered - if (arguments[2] == "" && cloud == oam::UnassignedName) + if (arguments[2] == "" && cloud == "n") { // need at least arguments cout << endl << "**** addModule Failed : Missing a required Parameter, enter 'help' for additional information" << endl; @@ -4855,7 +4583,7 @@ int processCommand(string* arguments) } } - //check and parse input Hostname/VPC-IP Addresses + //check and parse Server Hostname if (arguments[hostArg] != "") { boost::char_separator sep(", "); boost::tokenizer< boost::char_separator > tokens(arguments[hostArg], sep); @@ -4863,63 +4591,22 @@ int processCommand(string* arguments) it != tokens.end(); ++it) { - inputnames.push_back(*it); + hostnames.push_back(*it); } } - if ( inputnames.size() < (unsigned) moduleCount ) { - if ( cloud == oam::UnassignedName ) + if ( hostnames.size() < (unsigned) moduleCount ) { + if ( cloud != "amazon" ) { cout << endl << "**** addModule Failed : Failed to Add Module, number of hostnames is less than Module Count" << endl; break; } else { - if ( cloud == "amazon-ec2" ) + cout << endl << "number of Instance-IDs (" << hostnames.size() << ") is less than Module Count (" << moduleCount << "), will launch new Instance(s)" << endl; + for ( int id = hostnames.size() ; id < moduleCount ; id++ ) { - cout << endl << "number of Instance-IDs (" << inputnames.size() << ") is less than Module Count (" << moduleCount << "), will launch new Instance(s)" << endl; - for ( int id = inputnames.size() ; id < moduleCount ; id++ ) - { - inputnames.push_back(oam::UnassignedName); - } - } - else - { // amazon-vpc - if ( inputnames.size() == 0 ) - { - if ( AmazonVPCNextPrivateIP == oam::UnassignedName) - { - cout << endl << "**** addModule Failed : Failed to Add Module, enter VPC Private IP Address" << endl; - break; - } - else - { - if ( AmazonVPCNextPrivateIP == "autoassign") - { - for ( int id = inputnames.size() ; id < moduleCount ; id++ ) - { - inputnames.push_back("autoassign"); - } - } - else - { - for ( int id = inputnames.size() ; id < moduleCount ; id++ ) - { - inputnames.push_back(AmazonVPCNextPrivateIP); - - try - { - AmazonVPCNextPrivateIP = oam.incrementIPAddress(AmazonVPCNextPrivateIP); - } - catch(...) - { - cout << endl << "ERROR: incrementIPAddress API error, check logs" << endl; - exit(1); - } - } - } - } - } + hostnames.push_back(oam::UnassignedName); } } } @@ -4953,13 +4640,13 @@ int processCommand(string* arguments) } } - if ( ((unsigned) nicNumber * moduleCount) != inputnames.size() && cloud == oam::UnassignedName ) { + if ( ((unsigned) nicNumber * moduleCount) != hostnames.size() && cloud == "n" ) { cout << endl << "**** addModule Failed : Failed to Add Module, invalid number of hostNames entered. Enter " + oam.itoa(nicNumber * moduleCount) + " hostname(s), which is the number of NICs times the number of modules" << endl; break; } int moduleID = 1; - inputNames::const_iterator listPT1 = inputnames.begin(); + hostNames::const_iterator listPT1 = hostnames.begin(); umStorageNames::const_iterator listPT2 = umstoragenames.begin(); for ( int i = 0 ; i < moduleCount ; i++ ) { @@ -5001,11 +4688,11 @@ int processCommand(string* arguments) for ( int j = 0 ; j < nicNumber ; j ++ ) { //get/check Server Hostnames IP address - string hostName; + string hostName = *listPT1; + //get Network IP Address string IPAddress; - if ( cloud == "amazon-ec2") + if ( cloud == "amazon") { - hostName = *listPT1; if ( hostName != oam::UnassignedName ) { IPAddress = oam.getEC2InstanceIpAddress(hostName); @@ -5019,42 +4706,13 @@ int processCommand(string* arguments) } else { - if ( cloud == "amazon-vpc") - { - if ( *listPT1 != "autoassign" ) - { - if ( oam.isValidIP(*listPT1) ) { - //ip address entered - hostName = oam::UnassignedName; - IPAddress = *listPT1; - } - else - { //instance id entered - hostName = *listPT1; - IPAddress = oam.getEC2InstanceIpAddress(hostName); - if (IPAddress == "stopped" || IPAddress == "terminated") { - cout << "ERROR: Instance " + hostName + " not running, please start and retry" << endl << endl; - return 1; - } - } - } - else - { - hostName = oam::UnassignedName; - IPAddress = "autoassign"; - } - } - else - { // non-amazon - hostName = *listPT1; - IPAddress = oam.getIPAddress(hostName); - if ( IPAddress.empty() ) { - // prompt for IP Address - string prompt = "IP Address of " + hostName + " not found, enter IP Address or enter 'abort'"; - IPAddress = dataPrompt(prompt); - if ( IPAddress == "abort" || !oam.isValidIP(IPAddress)) - return 1; - } + IPAddress = oam.getIPAddress(hostName); + if ( IPAddress.empty() ) { + // prompt for IP Address + string prompt = "IP Address of " + hostName + " not found, enter IP Address or enter 'abort'"; + IPAddress = dataPrompt(prompt); + if ( IPAddress == "abort" || !oam.isValidIP(IPAddress)) + return 1; } } @@ -5259,11 +4917,6 @@ int processCommand(string* arguments) cout << "addModule Command Successfully completed: Modules are Disabled, run alterSystem-enableModule command to enable them" << endl << endl; } - try { - oam.setSystemConfig("AmazonVPCNextPrivateIP", AmazonVPCNextPrivateIP); - } - catch(...) {} - } catch (exception& e) { @@ -5460,12 +5113,11 @@ int processCommand(string* arguments) oam.getModuleStatus((*pt).DeviceName, opState, degraded); if (opState == oam::MAN_OFFLINE || - opState == oam::MAN_DISABLED || - opState == oam::FAILED) + opState == oam::MAN_DISABLED) continue; else { - cout << "**** removeModule Failed : " << (*pt).DeviceName << " is not MAN_OFFLINE, DISABLED, or FAILED state."; + cout << "**** removeModule Failed : " << (*pt).DeviceName << " is not MAN_OFFLINE OR DISABLED."; quit = true; cout << endl; break; @@ -5504,84 +5156,12 @@ int processCommand(string* arguments) break; } - case 50: // getModuleHostNames + case 50: // AVAILABLE { - SystemModuleTypeConfig systemmoduletypeconfig; - ModuleTypeConfig moduletypeconfig; - ModuleConfig moduleconfig; - systemmoduletypeconfig.moduletypeconfig.clear(); - string returnValue; - string Argument; - - // get and all display Module HostNames (NIC 1) - // No other data will be displayed, only the hostnames. - // This feature is designed for use by other processes. - // It was specifically installed for the sqoop import feature (version 4.5) - // If arguments[1] == PM, display only PMs, UM, display only UMs, else all. - try - { - oam.getSystemConfig(systemmoduletypeconfig); - - for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - if( systemmoduletypeconfig.moduletypeconfig[i].ModuleType.empty() ) - // end of list - break; - - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if ( moduleCount == 0 ) - // skip if no modules - continue; - - string moduletype = systemmoduletypeconfig.moduletypeconfig[i].ModuleType; - if (arguments[1] == "pm" && moduletype != "pm") - continue; - if (arguments[1] == "um" && moduletype != "um") - continue; - - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end() ; pt++) - { - HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); - for( ; pt1 != (*pt).hostConfigList.end() ; pt1++) - { - // Only print for NIC 1 - if ((*pt1).NicID == 1) - { - // We need the name with domain and everything. - if ((*pt1).HostName == "localhost") - { - char hostName[128] = {0}; - gethostname(hostName, 128); - cout << hostName << endl; - } - else - { - struct hostent* hentName = gethostbyname((*pt1).HostName.c_str()); - if (hentName) - { - cout << hentName->h_name << endl; - } - else - { - cout << (*pt1).HostName.c_str() << endl; - } - } - } - } - } - } - } - catch (exception& e) - { - cout << endl << "**** getModuleHostNames Failed = " << e.what() << endl; - } - break; } case 51: // AVAILABLE { - break; } case 52: // getModuleCpuUsers @@ -6212,9 +5792,10 @@ int processCommand(string* arguments) { struct tm tmStartTime; char timeBuf[36]; + size_t timeSize; time_t startTime = activesqlstatements[i].starttime; localtime_r(&startTime, &tmStartTime); - (void)strftime(timeBuf, 36, "%b %d %H:%M:%S", &tmStartTime); + timeSize = strftime(timeBuf, 36, "%b %d %H:%M:%S", &tmStartTime); cout.setf(ios::left); cout.width(21); @@ -6294,103 +5875,84 @@ int processCommand(string* arguments) break; } - parentOAMModule = getParentOAMModule(); - if ( arguments[1] == parentOAMModule ) { - // exit out since you can't manually remove OAM Parent Module - cout << endl << "**** alterSystem-disableModule Failed : can't manually disable the Active OAM Parent Module." << endl; - break; - } - - string moduleType = arguments[1].substr(0,MAX_MODULE_TYPE_SIZE); + parentOAMModule = getParentOAMModule(); + if ( arguments[1] == parentOAMModule ) { + // exit out since you can't manually remove OAM Parent Module + cout << endl << "**** alterSystem-disableModule Failed : can't manually disable the Active OAM Parent Module." << endl; + break; + } - gracefulTemp = INSTALL; + string moduleType = arguments[1].substr(0,MAX_MODULE_TYPE_SIZE); - //display Primary UM Module - string PrimaryUMModuleName; - try { - oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); - } - catch(...) {} + gracefulTemp = INSTALL; - bool primUM = false; - if ( PrimaryUMModuleName == arguments[1] ) - { - cout << endl << "This command stops the processing of applications on the Primary User Module, which is where DDL/DML are performed"; - if (confirmPrompt("If there is another module that can be changed to a new Primary User Module, this will be done")) - break; - primUM = true; - } - else - { - // confirm request + // confirm request if ( arguments[2] != "y" ) { if (confirmPrompt("This command stops the processing of applications on a Module within the Calpont System")) break; } - } - //parse module names - DeviceNetworkConfig devicenetworkconfig; - DeviceNetworkList devicenetworklist; + //parse module names + DeviceNetworkConfig devicenetworkconfig; + DeviceNetworkList devicenetworklist; - boost::char_separator sep(", "); - boost::tokenizer< boost::char_separator > tokens(arguments[1], sep); - for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); - it != tokens.end(); - ++it) - { - devicenetworkconfig.DeviceName = *it; - devicenetworklist.push_back(devicenetworkconfig); - } + boost::char_separator sep(", "); + boost::tokenizer< boost::char_separator > tokens(arguments[1], sep); + for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); + it != tokens.end(); + ++it) + { + devicenetworkconfig.DeviceName = *it; + devicenetworklist.push_back(devicenetworkconfig); + } - DeviceNetworkList::iterator pt = devicenetworklist.begin(); - DeviceNetworkList::iterator endpt = devicenetworklist.end(); + DeviceNetworkList::iterator pt = devicenetworklist.begin(); + DeviceNetworkList::iterator endpt = devicenetworklist.end(); - bool quit = false; + bool quit = false; - // check for module status and if any dbroots still assigned - if ( moduleType == "pm" ) { - for( ; pt != endpt ; pt++) - { - // check for dbroots assigned - DBRootConfigList dbrootConfigList; - string moduleID = (*pt).DeviceName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE); - try { - oam.getPmDbrootConfig(atoi(moduleID.c_str()), dbrootConfigList); + // check for module status and if any dbroots still assigned + if ( moduleType == "pm" ) { + for( ; pt != endpt ; pt++) + { + // check for dbroots assigned + DBRootConfigList dbrootConfigList; + string moduleID = (*pt).DeviceName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE); + try { + oam.getPmDbrootConfig(atoi(moduleID.c_str()), dbrootConfigList); + } + catch(...) + {} + + if ( !dbrootConfigList.empty() ) { + cout << endl << "**** alterSystem-disableModule Failed : " << (*pt).DeviceName << " has dbroots still assigned and will not be disabled. Please run movePmDbrootConfig."; + quit = true; + cout << endl; + break; + } } - catch(...) - {} - if ( !dbrootConfigList.empty() ) { - cout << endl << "**** alterSystem-disableModule Failed : " << (*pt).DeviceName << " has dbroots still assigned and will not be disabled. Please run movePmDbrootConfig."; - quit = true; + if (quit) { cout << endl; break; } } - if (quit) { - cout << endl; + if ( devicenetworklist.empty() ) { + cout << endl << "quiting, no modules to remove." << endl << endl; break; } - } - - if ( devicenetworklist.empty() ) { - cout << endl << "quiting, no modules to remove." << endl << endl; - break; - } - - // stop module - try - { - cout << endl << " Stopping Modules" << endl; - oam.stopModule(devicenetworklist, gracefulTemp, ackTemp); - cout << " Successful stop of Modules " << endl; - } - catch (exception& e) - { - string Failed = e.what(); + // stop module + try + { + cout << endl << " Stopping Modules" << endl; + oam.stopModule(devicenetworklist, gracefulTemp, ackTemp); + cout << " Successful stop of Modules " << endl; + } + catch (exception& e) + { + string Failed = e.what(); if (Failed.find("Disabled") != string::npos) cout << endl << " Successful stop of Modules " << endl; else { @@ -6405,18 +5967,6 @@ int processCommand(string* arguments) cout << endl << " Disabling Modules" << endl; oam.disableModule(devicenetworklist); cout << " Successful disable of Modules " << endl; - - //display Primary UM Module - string PrimaryUMModuleName; - try { - oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); - } - catch(...) {} - - if ( primUM && - PrimaryUMModuleName != arguments[1] ) - cout << endl << " New Primary User Module = " << PrimaryUMModuleName << endl; - } catch (exception& e) { @@ -6550,7 +6100,6 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) GRACEFUL_FLAG gracefulTemp = GRACEFUL; ACK_FLAG ackTemp = ACK_YES; CC_SUSPEND_ANSWER suspendAnswer = WAIT; - bool bNeedsConfirm = true; switch( CommandID ) { @@ -6594,7 +6143,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) else { if ( arguments[3] != "y" ) { - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); // confirm request if (confirmPrompt("This command stops the processing of an application on a Module within the Calpont System")) break; @@ -6623,7 +6172,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) break; } - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); try { @@ -6646,7 +6195,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) break; } - getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer, bNeedsConfirm); + getFlags(arguments, gracefulTemp, ackTemp, suspendAnswer); // confirm request if (confirmPrompt("This command restarts the processing of an application on a Module within the Calpont System")) @@ -6723,11 +6272,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) { cout << endl << " System being stopped, please wait... " << endl; oam.stopSystem(GRACEFUL, ACK_YES); - - if ( waitForStop() ) - cout << endl << " Successful stop of System " << endl << endl; - else - cout << endl << "**** stopSystem Failed : check log files" << endl; + cout << endl << " Successful stop of System " << endl << endl; } catch (exception& e) { @@ -6781,7 +6326,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); string cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + (*pt1).IPAddr + " " + password + " reboot " ; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Failed with running remote_command.sh" << endl; FAILED = true; } @@ -6796,7 +6341,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) //reboot local module int rtnCode = system("reboot"); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Failed rebooting local module" << endl; else { @@ -6866,7 +6411,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) if (inputModuleName == localModule ) { //reboot local module int rtnCode = system("reboot"); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Failed rebooting local node" << endl; else { @@ -6885,7 +6430,7 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) //run remote command script string cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + ipAddr + " " + password + " reboot " ; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Failed with running remote_command.sh" << endl; else cout << endl << " Successful reboot request of Node " << modulename << endl; @@ -7267,46 +6812,29 @@ int ProcessSupportCommand(int CommandID, std::string arguments[]) * purpose: get and convert Graceful and Ack flags * ******************************************************************************************/ -void getFlags(const string* arguments, GRACEFUL_FLAG& gracefulTemp, ACK_FLAG& ackTemp, oam::CC_SUSPEND_ANSWER& suspendAnswer, bool& bNeedsConfirm, string* password) +void getFlags(const string* arguments, GRACEFUL_FLAG& gracefulTemp, ACK_FLAG& ackTemp, oam::CC_SUSPEND_ANSWER& suspendAnswer) { gracefulTemp = GRACEFUL; // default ackTemp = ACK_YES; // default suspendAnswer = CANCEL; - bNeedsConfirm = true; for( int i = 1; i < ArgNum; i++) { - if (strcasecmp(arguments[i].c_str(), "Y") == 0) - bNeedsConfirm = false; - else - if (strcasecmp(arguments[i].c_str(), "N") == 0) - bNeedsConfirm = true; - else - if (strcasecmp(arguments[i].c_str(), "GRACEFUL") == 0) + if (arguments[i] == "GRACEFUL") gracefulTemp = oam::GRACEFUL; - else - if (strcasecmp(arguments[i].c_str(), "FORCEFUL") == 0) + if (arguments[i] == "FORCEFUL") gracefulTemp = FORCEFUL; - else - if (strcasecmp(arguments[i].c_str(), "INSTALL") == 0) + if (arguments[i] == "INSTALL") gracefulTemp = INSTALL; - else - if (strcasecmp(arguments[i].c_str(), "ACK_YES") == 0 || strcasecmp(arguments[i].c_str(), "YES_ACK") == 0) + if (arguments[i] == "ACK_YES" || arguments[i] == "YES_ACK" ) ackTemp = ACK_YES; - else - if (strcasecmp(arguments[i].c_str(), "ACK_NO") == 0 || strcasecmp(arguments[i].c_str(), "NO_ACK") == 0) + if (arguments[i] == "ACK_NO" || arguments[i] == "NO_ACK" ) ackTemp = ACK_NO; - else - if (strcasecmp(arguments[i].c_str(), "WAIT") == 0) + if (arguments[i] == "WAIT") suspendAnswer = WAIT; - else - if (strcasecmp(arguments[i].c_str(), "ROLLBACK") == 0) + if (arguments[i] == "ROLLBACK") suspendAnswer = ROLLBACK; - else - if (strcasecmp(arguments[i].c_str(), "FORCE") == 0) + if (arguments[i] == "FORCE") suspendAnswer = FORCE; - else - if (password && arguments[i].length() > 0) - *password = arguments[i]; } } @@ -7339,10 +6867,10 @@ int confirmPrompt(std::string warningCommand) pcommand = 0; } - if (pcommand) { - free(pcommand); - pcommand = 0; - } + if (pcommand) { + free(pcommand); + pcommand = 0; + } // covert argument into lowercase transform (argument.begin(), argument.end(), argument.begin(), to_lower()); @@ -7547,7 +7075,7 @@ void printSystemStatus() printState(state, extraInfo); cout.width(24); string stime = systemstatus.StateChangeDate; - stime = stime.substr (0,24); + stime = stime.substr (0,24); cout << stime << endl << endl; for( unsigned int i = 0 ; i < systemstatus.systemmodulestatus.modulestatus.size(); i++) @@ -7585,62 +7113,10 @@ void printSystemStatus() } cout << endl; - if ( systemstatus.systemmodulestatus.modulestatus.size() > 1) { + if ( systemstatus.systemmodulestatus.modulestatus.size() > 1) // get and display Parent OAM Module - cout << "Active Parent OAM Performance Module is '" << getParentOAMModule() << "'" << endl; + cout << "Active Parent OAM Performance Module is '" << getParentOAMModule() << "'" << endl << endl; - //display Primary UM Module - string PrimaryUMModuleName; - try { - oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); - } - catch(...) {} - - if ( serverInstallType != oam::INSTALL_COMBINE_DM_UM_PM ) - { - ModuleTypeConfig moduletypeconfig; - try{ - oam.getSystemConfig("um", moduletypeconfig); - } - catch(...) - {} - - if ( moduletypeconfig.ModuleCount > 1 ) - { - if ( PrimaryUMModuleName != oam::UnassignedName ) - cout << "Primary Front-End MySQL Module is '" << PrimaryUMModuleName << "'" << endl; - } - } - else - { - if ( PrimaryUMModuleName != oam::UnassignedName ) - cout << "Primary Front-End MySQL Module is '" << PrimaryUMModuleName << "'" << endl; - } - } - - //display local Query / PMwithUM feature, if enabled - string PMwithUM; - try { - oam.getSystemConfig("PMwithUM", PMwithUM); - } - catch(...) {} - - if ( PMwithUM == "y" ) - cout << "Local Query Feature is enabled" << endl; - else - cout << endl; - - //display MySQL replication feature, if enabled - string MySQLRep; - try { - oam.getSystemConfig("MySQLRep", MySQLRep); - } - catch(...) {} - - if ( MySQLRep == "y" ) - cout << "MySQL Replication Feature is enabled" << endl << endl; - else - cout << endl; } catch (exception& e) { @@ -7881,7 +7357,7 @@ void printModuleDisk(ModuleDisk moduledisk) cout.width(31); cout << moduledisk.diskusage[i].DeviceName; cout.width(14); - cout << moduledisk.diskusage[i].TotalBlocks; + cout << oam.itoa(moduledisk.diskusage[i].TotalBlocks); cout.width(17); cout << moduledisk.diskusage[i].UsedBlocks; cout.width(2); @@ -8098,8 +7574,6 @@ bool checkForDisabledModules() if( moduleCount == 0) continue; - string moduleType = systemmoduletypeconfig.moduletypeconfig[i].ModuleType; - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++) { @@ -8118,9 +7592,6 @@ bool checkForDisabledModules() } cout << moduleName << " "; - if ( moduleType == "um" ) - continue; - //check if module has any dbroots assigned to it string PMID = moduleName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE);; DBRootConfigList dbrootConfigList; diff --git a/oamapps/calpontConsole/calpontConsole.h b/oamapps/calpont-console/calpontConsole.h similarity index 79% rename from oamapps/calpontConsole/calpontConsole.h rename to oamapps/calpont-console/calpontConsole.h index 71407d6d..ee4a9030 100644 --- a/oamapps/calpontConsole/calpontConsole.h +++ b/oamapps/calpont-console/calpontConsole.h @@ -1,22 +1,5 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** - * $Id: calpontConsole.h 3071 2013-04-04 18:45:53Z rdempsey $ + * $Id: calpontConsole.h 2641 2012-09-05 21:45:28Z dhill $ * ******************************************************************************************/ /** @@ -69,7 +52,7 @@ void writeLog(std::string command); */ const std::string ConsoleCmdsFile= "ConsoleCmds.xml"; -void getFlags(const std::string* arguments, oam::GRACEFUL_FLAG& gracefulTemp, oam::ACK_FLAG& ackTemp, oam::CC_SUSPEND_ANSWER& suspendAnswer, bool& bNeedsConfirm, std::string* password = NULL); +void getFlags(const std::string* arguments, oam::GRACEFUL_FLAG& gracefulTemp, oam::ACK_FLAG& ackTemp, oam::CC_SUSPEND_ANSWER& suspendAnswer); int confirmPrompt(std::string warningCommand); std::string dataPrompt(std::string promptCommand); int processCommand(std::string*); diff --git a/oamapps/calpont-console/tdriver.cpp b/oamapps/calpont-console/tdriver.cpp new file mode 100644 index 00000000..16935bd4 --- /dev/null +++ b/oamapps/calpont-console/tdriver.cpp @@ -0,0 +1,312 @@ +/*************************************************************************** +* $Id: tdriver.cpp 1834 2011-02-08 14:37:11Z rdempsey $ +* + * dhill@srvengcm1.calpont.com + * + * Purpose: Calpont Console tester + * + ***************************************************************************/ + +#include +#include +using namespace std; + +#include +using namespace boost; + +#include + +class GeneralCmdsTest : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE( GeneralCmdsTest ); + +CPPUNIT_TEST( test1 ); +CPPUNIT_TEST( test2 ); +CPPUNIT_TEST( test3 ); +CPPUNIT_TEST( test4 ); +CPPUNIT_TEST( test5 ); +CPPUNIT_TEST( test6 ); +CPPUNIT_TEST( test7 ); + +CPPUNIT_TEST_SUITE_END(); + +private: + +public: + void setUp() { + } + + void tearDown() { + } + + void test1() { + system("./calpontConsole help > tdriver.output"); + } + + void test2() { + system("./calpontConsole ? >> tdriver.output"); + } + + void test3() { + system("./calpontConsole help verbose >> tdriver.output"); + } + + void test4() { + system("./calpontConsole help getAlarmConfig >> tdriver.output"); + } + + void test5() { + system("./calpontConsole exit >> tdriver.output"); + } + + void test6() { + system("./calpontConsole quit >> tdriver.output"); + } + + void test7() { + system("./calpontConsole system ls -ltr >> tdriver.output"); + } +}; + +class AlarmConfigTest : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE( AlarmConfigTest ); + +CPPUNIT_TEST( test1 ); +CPPUNIT_TEST( test2 ); +CPPUNIT_TEST( test3 ); +CPPUNIT_TEST( test4 ); + +CPPUNIT_TEST_SUITE_END(); + +private: + +public: + void setUp() { + } + + void tearDown() { + } + + void test1() { + system("./calpontConsole getAlarmConfig >> tdriver.output"); + } + + void test2() { + system("./calpontConsole getAlarmConfig 1 >> tdriver.output"); + } + + void test3() { + system("./calpontConsole setAlarmConfig 1 Threshold 50 >> tdriver.output"); + } + + void test4() { + system("./calpontConsole getAlarmConfig 1 >> tdriver.output"); + } + +}; + +class ProcessConfigTest : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE( ProcessConfigTest ); + +CPPUNIT_TEST( test1 ); +CPPUNIT_TEST( test2 ); +CPPUNIT_TEST( test3 ); +CPPUNIT_TEST( test4 ); +CPPUNIT_TEST( test5 ); +CPPUNIT_TEST( test6 ); +CPPUNIT_TEST( test7 ); + +CPPUNIT_TEST_SUITE_END(); + +private: + +public: + void setUp() { + } + + void tearDown() { + } + + void test1() { + system("./calpontConsole getProcessConfig >> tdriver.output"); + } + + void test2() { + system("./calpontConsole getProcessConfig ProcessManager dm1 >> tdriver.output"); + } + + void test3() { + system("./calpontConsole getProcessConfig ProcessManager dm1 LaunchID >> tdriver.output"); + } + + void test4() { + system("./calpontConsole setProcessConfig ProcessManager dm1 LaunchID 1 >> tdriver.output"); + } + + void test5() { + system("./calpontConsole getProcessConfig ProcessManager dm1 LaunchID >> tdriver.output"); + } + + void test6() { + system("./calpontConsole setProcessConfig ProcessManager dm1 LaunchID 3 >> tdriver.output"); + } + + void test7() { + system("./calpontConsole getProcessConfig ProcessManager dm1 LaunchID >> tdriver.output"); + } + +}; + +class ServerConfigTest : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE( ServerConfigTest ); + +CPPUNIT_TEST( test1 ); +CPPUNIT_TEST( test2 ); +CPPUNIT_TEST( test3 ); +CPPUNIT_TEST( test4 ); +CPPUNIT_TEST( test5 ); +CPPUNIT_TEST( test6 ); +CPPUNIT_TEST( test7 ); + +CPPUNIT_TEST_SUITE_END(); + +private: + +public: + void setUp() { + } + + void tearDown() { + } + + void test1() { + system("./calpontConsole getModuleConfig >> tdriver.output"); + } + + void test2() { + system("./calpontConsole getModuleConfig dm1 >> tdriver.output"); + } + + void test3() { + system("./calpontConsole getModuleConfig dm1 ServerCPUCriticalThreshold >> tdriver.output"); + } + + void test4() { + system("./calpontConsole setModuleConfig dm1 ServerCPUCriticalThreshold 9999 >> tdriver.output"); + } + + void test5() { + system("./calpontConsole getModuleConfig dm1 ServerCPUCriticalThreshold >> tdriver.output"); + } + + void test6() { + system("./calpontConsole setModuleConfig dm1 ServerCPUCriticalThreshold 9000 >> tdriver.output"); + } + + void test7() { + system("./calpontConsole getModuleConfig dm1 ServerCPUCriticalThreshold >> tdriver.output"); + } + +}; + +class SystemConfigTest : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE( SystemConfigTest ); + +CPPUNIT_TEST( test1 ); +CPPUNIT_TEST( test2 ); +CPPUNIT_TEST( test3 ); +CPPUNIT_TEST( test4 ); + +CPPUNIT_TEST_SUITE_END(); + +private: + +public: + void setUp() { + } + + void tearDown() { + } + + void test1() { + system("./calpontConsole getSystemConfig >> tdriver.output"); + } + + void test2() { + system("./calpontConsole getSystemConfig SystemVersion >> tdriver.output"); + } + + void test3() { + system("./calpontConsole setSystemConfig SystemVersion 2.0.0.0 >> tdriver.output"); + } + + void test4() { + system("./calpontConsole getSystemConfig SystemVersion >> tdriver.output"); + } + +}; + +class SystemActionTest : public CppUnit::TestFixture { + +CPPUNIT_TEST_SUITE( SystemActionTest ); + +CPPUNIT_TEST( test1 ); // valid, but will fail command +CPPUNIT_TEST( test2 ); // valid, but will fail command +CPPUNIT_TEST( test3 ); // valid, but will fail command +CPPUNIT_TEST( test4 ); // valid, but will fail command + + +CPPUNIT_TEST_SUITE_END(); + +private: + +public: + void setUp() { + } + + void tearDown() { + } + + void test1() { + system("./calpontConsole stopSystem >> tdriver.output"); + } + + void test2() { + system("./calpontConsole shutdownSystem >> tdriver.output"); + } + + void test3() { + system("./calpontConsole startSystem >> tdriver.output"); + } + + void test4() { + system("./calpontConsole restartSystem >> tdriver.output"); + } + +}; + + +//CPPUNIT_TEST_SUITE_REGISTRATION( SystemActionTest ); +CPPUNIT_TEST_SUITE_REGISTRATION( SystemConfigTest ); +CPPUNIT_TEST_SUITE_REGISTRATION( ServerConfigTest ); +CPPUNIT_TEST_SUITE_REGISTRATION( ProcessConfigTest ); +CPPUNIT_TEST_SUITE_REGISTRATION( AlarmConfigTest ); +CPPUNIT_TEST_SUITE_REGISTRATION( GeneralCmdsTest ); + +#include +#include + +int main( int argc, char **argv) +{ + CppUnit::TextUi::TestRunner runner; + CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); + runner.addTest( registry.makeTest() ); + bool wasSuccessful = runner.run( "", false ); + return (wasSuccessful ? 0 : 1); +} + + diff --git a/oamapps/calpontConsole/Makefile.am b/oamapps/calpontConsole/Makefile.am deleted file mode 100644 index b93a3c53..00000000 --- a/oamapps/calpontConsole/Makefile.am +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = calpontConsole -calpontConsole_SOURCES = calpontConsole.cpp -calpontConsole_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -calpontConsole_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/oamapps/calpontConsole/Makefile.in b/oamapps/calpontConsole/Makefile.in deleted file mode 100644 index 9cb86a75..00000000 --- a/oamapps/calpontConsole/Makefile.in +++ /dev/null @@ -1,529 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = calpontConsole$(EXEEXT) -subdir = oamapps/calpontConsole -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_calpontConsole_OBJECTS = calpontConsole-calpontConsole.$(OBJEXT) -calpontConsole_OBJECTS = $(am_calpontConsole_OBJECTS) -calpontConsole_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(calpontConsole_SOURCES) -DIST_SOURCES = $(calpontConsole_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -calpontConsole_SOURCES = calpontConsole.cpp -calpontConsole_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -calpontConsole_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/calpontConsole/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/calpontConsole/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -calpontConsole$(EXEEXT): $(calpontConsole_OBJECTS) $(calpontConsole_DEPENDENCIES) - @rm -f calpontConsole$(EXEEXT) - $(CXXLINK) $(calpontConsole_LDFLAGS) $(calpontConsole_OBJECTS) $(calpontConsole_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/calpontConsole-calpontConsole.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -calpontConsole-calpontConsole.o: calpontConsole.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontConsole_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT calpontConsole-calpontConsole.o -MD -MP -MF "$(DEPDIR)/calpontConsole-calpontConsole.Tpo" -c -o calpontConsole-calpontConsole.o `test -f 'calpontConsole.cpp' || echo '$(srcdir)/'`calpontConsole.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/calpontConsole-calpontConsole.Tpo" "$(DEPDIR)/calpontConsole-calpontConsole.Po"; else rm -f "$(DEPDIR)/calpontConsole-calpontConsole.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='calpontConsole.cpp' object='calpontConsole-calpontConsole.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontConsole_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o calpontConsole-calpontConsole.o `test -f 'calpontConsole.cpp' || echo '$(srcdir)/'`calpontConsole.cpp - -calpontConsole-calpontConsole.obj: calpontConsole.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontConsole_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT calpontConsole-calpontConsole.obj -MD -MP -MF "$(DEPDIR)/calpontConsole-calpontConsole.Tpo" -c -o calpontConsole-calpontConsole.obj `if test -f 'calpontConsole.cpp'; then $(CYGPATH_W) 'calpontConsole.cpp'; else $(CYGPATH_W) '$(srcdir)/calpontConsole.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/calpontConsole-calpontConsole.Tpo" "$(DEPDIR)/calpontConsole-calpontConsole.Po"; else rm -f "$(DEPDIR)/calpontConsole-calpontConsole.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='calpontConsole.cpp' object='calpontConsole-calpontConsole.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontConsole_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o calpontConsole-calpontConsole.obj `if test -f 'calpontConsole.cpp'; then $(CYGPATH_W) 'calpontConsole.cpp'; else $(CYGPATH_W) '$(srcdir)/calpontConsole.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/calpontConsole/tdriver.cpp b/oamapps/calpontConsole/tdriver.cpp deleted file mode 100644 index 83bb44e3..00000000 --- a/oamapps/calpontConsole/tdriver.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/*************************************************************************** -* $Id: tdriver.cpp 3072 2013-04-04 19:04:45Z rdempsey $ -* - * dhill@srvengcm1.calpont.com - * - * Purpose: Calpont Console tester - * - ***************************************************************************/ - -#include -#include -using namespace std; - -#include -using namespace boost; - -#include - -class GeneralCmdsTest : public CppUnit::TestFixture { - -CPPUNIT_TEST_SUITE( GeneralCmdsTest ); - -CPPUNIT_TEST( test1 ); -CPPUNIT_TEST( test2 ); -CPPUNIT_TEST( test3 ); -CPPUNIT_TEST( test4 ); -CPPUNIT_TEST( test5 ); -CPPUNIT_TEST( test6 ); -CPPUNIT_TEST( test7 ); - -CPPUNIT_TEST_SUITE_END(); - -private: - -public: - void setUp() { - } - - void tearDown() { - } - - void test1() { - system("./calpontConsole help > tdriver.output"); - } - - void test2() { - system("./calpontConsole ? >> tdriver.output"); - } - - void test3() { - system("./calpontConsole help verbose >> tdriver.output"); - } - - void test4() { - system("./calpontConsole help getAlarmConfig >> tdriver.output"); - } - - void test5() { - system("./calpontConsole exit >> tdriver.output"); - } - - void test6() { - system("./calpontConsole quit >> tdriver.output"); - } - - void test7() { - system("./calpontConsole system ls -ltr >> tdriver.output"); - } -}; - -class AlarmConfigTest : public CppUnit::TestFixture { - -CPPUNIT_TEST_SUITE( AlarmConfigTest ); - -CPPUNIT_TEST( test1 ); -CPPUNIT_TEST( test2 ); -CPPUNIT_TEST( test3 ); -CPPUNIT_TEST( test4 ); - -CPPUNIT_TEST_SUITE_END(); - -private: - -public: - void setUp() { - } - - void tearDown() { - } - - void test1() { - system("./calpontConsole getAlarmConfig >> tdriver.output"); - } - - void test2() { - system("./calpontConsole getAlarmConfig 1 >> tdriver.output"); - } - - void test3() { - system("./calpontConsole setAlarmConfig 1 Threshold 50 >> tdriver.output"); - } - - void test4() { - system("./calpontConsole getAlarmConfig 1 >> tdriver.output"); - } - -}; - -class ProcessConfigTest : public CppUnit::TestFixture { - -CPPUNIT_TEST_SUITE( ProcessConfigTest ); - -CPPUNIT_TEST( test1 ); -CPPUNIT_TEST( test2 ); -CPPUNIT_TEST( test3 ); -CPPUNIT_TEST( test4 ); -CPPUNIT_TEST( test5 ); -CPPUNIT_TEST( test6 ); -CPPUNIT_TEST( test7 ); - -CPPUNIT_TEST_SUITE_END(); - -private: - -public: - void setUp() { - } - - void tearDown() { - } - - void test1() { - system("./calpontConsole getProcessConfig >> tdriver.output"); - } - - void test2() { - system("./calpontConsole getProcessConfig ProcessManager dm1 >> tdriver.output"); - } - - void test3() { - system("./calpontConsole getProcessConfig ProcessManager dm1 LaunchID >> tdriver.output"); - } - - void test4() { - system("./calpontConsole setProcessConfig ProcessManager dm1 LaunchID 1 >> tdriver.output"); - } - - void test5() { - system("./calpontConsole getProcessConfig ProcessManager dm1 LaunchID >> tdriver.output"); - } - - void test6() { - system("./calpontConsole setProcessConfig ProcessManager dm1 LaunchID 3 >> tdriver.output"); - } - - void test7() { - system("./calpontConsole getProcessConfig ProcessManager dm1 LaunchID >> tdriver.output"); - } - -}; - -class ServerConfigTest : public CppUnit::TestFixture { - -CPPUNIT_TEST_SUITE( ServerConfigTest ); - -CPPUNIT_TEST( test1 ); -CPPUNIT_TEST( test2 ); -CPPUNIT_TEST( test3 ); -CPPUNIT_TEST( test4 ); -CPPUNIT_TEST( test5 ); -CPPUNIT_TEST( test6 ); -CPPUNIT_TEST( test7 ); - -CPPUNIT_TEST_SUITE_END(); - -private: - -public: - void setUp() { - } - - void tearDown() { - } - - void test1() { - system("./calpontConsole getModuleConfig >> tdriver.output"); - } - - void test2() { - system("./calpontConsole getModuleConfig dm1 >> tdriver.output"); - } - - void test3() { - system("./calpontConsole getModuleConfig dm1 ServerCPUCriticalThreshold >> tdriver.output"); - } - - void test4() { - system("./calpontConsole setModuleConfig dm1 ServerCPUCriticalThreshold 9999 >> tdriver.output"); - } - - void test5() { - system("./calpontConsole getModuleConfig dm1 ServerCPUCriticalThreshold >> tdriver.output"); - } - - void test6() { - system("./calpontConsole setModuleConfig dm1 ServerCPUCriticalThreshold 9000 >> tdriver.output"); - } - - void test7() { - system("./calpontConsole getModuleConfig dm1 ServerCPUCriticalThreshold >> tdriver.output"); - } - -}; - -class SystemConfigTest : public CppUnit::TestFixture { - -CPPUNIT_TEST_SUITE( SystemConfigTest ); - -CPPUNIT_TEST( test1 ); -CPPUNIT_TEST( test2 ); -CPPUNIT_TEST( test3 ); -CPPUNIT_TEST( test4 ); - -CPPUNIT_TEST_SUITE_END(); - -private: - -public: - void setUp() { - } - - void tearDown() { - } - - void test1() { - system("./calpontConsole getSystemConfig >> tdriver.output"); - } - - void test2() { - system("./calpontConsole getSystemConfig SystemVersion >> tdriver.output"); - } - - void test3() { - system("./calpontConsole setSystemConfig SystemVersion 2.0.0.0 >> tdriver.output"); - } - - void test4() { - system("./calpontConsole getSystemConfig SystemVersion >> tdriver.output"); - } - -}; - -class SystemActionTest : public CppUnit::TestFixture { - -CPPUNIT_TEST_SUITE( SystemActionTest ); - -CPPUNIT_TEST( test1 ); // valid, but will fail command -CPPUNIT_TEST( test2 ); // valid, but will fail command -CPPUNIT_TEST( test3 ); // valid, but will fail command -CPPUNIT_TEST( test4 ); // valid, but will fail command - - -CPPUNIT_TEST_SUITE_END(); - -private: - -public: - void setUp() { - } - - void tearDown() { - } - - void test1() { - system("./calpontConsole stopSystem >> tdriver.output"); - } - - void test2() { - system("./calpontConsole shutdownSystem >> tdriver.output"); - } - - void test3() { - system("./calpontConsole startSystem >> tdriver.output"); - } - - void test4() { - system("./calpontConsole restartSystem >> tdriver.output"); - } - -}; - - -//CPPUNIT_TEST_SUITE_REGISTRATION( SystemActionTest ); -CPPUNIT_TEST_SUITE_REGISTRATION( SystemConfigTest ); -CPPUNIT_TEST_SUITE_REGISTRATION( ServerConfigTest ); -CPPUNIT_TEST_SUITE_REGISTRATION( ProcessConfigTest ); -CPPUNIT_TEST_SUITE_REGISTRATION( AlarmConfigTest ); -CPPUNIT_TEST_SUITE_REGISTRATION( GeneralCmdsTest ); - -#include -#include - -int main( int argc, char **argv) -{ - CppUnit::TextUi::TestRunner runner; - CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); - runner.addTest( registry.makeTest() ); - bool wasSuccessful = runner.run( "", false ); - return (wasSuccessful ? 0 : 1); -} - - diff --git a/oamapps/calpontDB/Makefile.am b/oamapps/calpontDB/Makefile.am index c0170e39..b779c743 100644 --- a/oamapps/calpontDB/Makefile.am +++ b/oamapps/calpontDB/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/oamapps/calpontDB/Makefile.in b/oamapps/calpontDB/Makefile.in deleted file mode 100644 index e0fdf65a..00000000 --- a/oamapps/calpontDB/Makefile.in +++ /dev/null @@ -1,529 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = calpontDBWrite$(EXEEXT) -subdir = oamapps/calpontDB -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_calpontDBWrite_OBJECTS = calpontDBWrite-calpontDB.$(OBJEXT) -calpontDBWrite_OBJECTS = $(am_calpontDBWrite_OBJECTS) -calpontDBWrite_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(calpontDBWrite_SOURCES) -DIST_SOURCES = $(calpontDBWrite_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -calpontDBWrite_SOURCES = calpontDB.cpp -calpontDBWrite_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -calpontDBWrite_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/calpontDB/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/calpontDB/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -calpontDBWrite$(EXEEXT): $(calpontDBWrite_OBJECTS) $(calpontDBWrite_DEPENDENCIES) - @rm -f calpontDBWrite$(EXEEXT) - $(CXXLINK) $(calpontDBWrite_LDFLAGS) $(calpontDBWrite_OBJECTS) $(calpontDBWrite_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/calpontDBWrite-calpontDB.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -calpontDBWrite-calpontDB.o: calpontDB.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontDBWrite_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT calpontDBWrite-calpontDB.o -MD -MP -MF "$(DEPDIR)/calpontDBWrite-calpontDB.Tpo" -c -o calpontDBWrite-calpontDB.o `test -f 'calpontDB.cpp' || echo '$(srcdir)/'`calpontDB.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/calpontDBWrite-calpontDB.Tpo" "$(DEPDIR)/calpontDBWrite-calpontDB.Po"; else rm -f "$(DEPDIR)/calpontDBWrite-calpontDB.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='calpontDB.cpp' object='calpontDBWrite-calpontDB.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontDBWrite_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o calpontDBWrite-calpontDB.o `test -f 'calpontDB.cpp' || echo '$(srcdir)/'`calpontDB.cpp - -calpontDBWrite-calpontDB.obj: calpontDB.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontDBWrite_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT calpontDBWrite-calpontDB.obj -MD -MP -MF "$(DEPDIR)/calpontDBWrite-calpontDB.Tpo" -c -o calpontDBWrite-calpontDB.obj `if test -f 'calpontDB.cpp'; then $(CYGPATH_W) 'calpontDB.cpp'; else $(CYGPATH_W) '$(srcdir)/calpontDB.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/calpontDBWrite-calpontDB.Tpo" "$(DEPDIR)/calpontDBWrite-calpontDB.Po"; else rm -f "$(DEPDIR)/calpontDBWrite-calpontDB.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='calpontDB.cpp' object='calpontDBWrite-calpontDB.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontDBWrite_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o calpontDBWrite-calpontDB.obj `if test -f 'calpontDB.cpp'; then $(CYGPATH_W) 'calpontDB.cpp'; else $(CYGPATH_W) '$(srcdir)/calpontDB.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/calpontDB/calpontDB.cpp b/oamapps/calpontDB/calpontDB.cpp index 1307f490..6ae529b2 100644 --- a/oamapps/calpontDB/calpontDB.cpp +++ b/oamapps/calpontDB/calpontDB.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** * $Id: calpontDB.cpp 419 2007-07-22 17:18:00Z dhill $ * diff --git a/oamapps/calpontSupport/Makefile.am b/oamapps/calpontSupport/Makefile.am deleted file mode 100644 index ee49911f..00000000 --- a/oamapps/calpontSupport/Makefile.am +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = calpontSupport -calpontSupport_SOURCES = calpontSupport.cpp -calpontSupport_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -calpontSupport_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) -dist_bin_SCRIPTS=\ - alarmReport.sh \ - bulklogReport.sh \ - configReport.sh \ - hadoopReport.sh \ - hardwareReport.sh \ - logReport.sh \ - resourceReport.sh \ - softwareReport.sh - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/oamapps/calpontSupport/Makefile.in b/oamapps/calpontSupport/Makefile.in deleted file mode 100644 index ddc1d484..00000000 --- a/oamapps/calpontSupport/Makefile.in +++ /dev/null @@ -1,564 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = calpontSupport$(EXEEXT) -subdir = oamapps/calpontSupport -DIST_COMMON = $(dist_bin_SCRIPTS) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_calpontSupport_OBJECTS = calpontSupport-calpontSupport.$(OBJEXT) -calpontSupport_OBJECTS = $(am_calpontSupport_OBJECTS) -calpontSupport_LDADD = $(LDADD) -dist_binSCRIPT_INSTALL = $(INSTALL_SCRIPT) -SCRIPTS = $(dist_bin_SCRIPTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(calpontSupport_SOURCES) -DIST_SOURCES = $(calpontSupport_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -calpontSupport_SOURCES = calpontSupport.cpp -calpontSupport_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -calpontSupport_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) -dist_bin_SCRIPTS = \ - alarmReport.sh \ - bulklogReport.sh \ - configReport.sh \ - hadoopReport.sh \ - hardwareReport.sh \ - logReport.sh \ - resourceReport.sh \ - softwareReport.sh - -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/calpontSupport/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/calpontSupport/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -calpontSupport$(EXEEXT): $(calpontSupport_OBJECTS) $(calpontSupport_DEPENDENCIES) - @rm -f calpontSupport$(EXEEXT) - $(CXXLINK) $(calpontSupport_LDFLAGS) $(calpontSupport_OBJECTS) $(calpontSupport_LDADD) $(LIBS) -install-dist_binSCRIPTS: $(dist_bin_SCRIPTS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(dist_bin_SCRIPTS)'; for p in $$list; do \ - if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ - if test -f $$d$$p; then \ - f=`echo "$$p" | sed 's|^.*/||;$(transform)'`; \ - echo " $(dist_binSCRIPT_INSTALL) '$$d$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(dist_binSCRIPT_INSTALL) "$$d$$p" "$(DESTDIR)$(bindir)/$$f"; \ - else :; fi; \ - done - -uninstall-dist_binSCRIPTS: - @$(NORMAL_UNINSTALL) - @list='$(dist_bin_SCRIPTS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's|^.*/||;$(transform)'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/calpontSupport-calpontSupport.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -calpontSupport-calpontSupport.o: calpontSupport.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontSupport_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT calpontSupport-calpontSupport.o -MD -MP -MF "$(DEPDIR)/calpontSupport-calpontSupport.Tpo" -c -o calpontSupport-calpontSupport.o `test -f 'calpontSupport.cpp' || echo '$(srcdir)/'`calpontSupport.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/calpontSupport-calpontSupport.Tpo" "$(DEPDIR)/calpontSupport-calpontSupport.Po"; else rm -f "$(DEPDIR)/calpontSupport-calpontSupport.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='calpontSupport.cpp' object='calpontSupport-calpontSupport.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontSupport_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o calpontSupport-calpontSupport.o `test -f 'calpontSupport.cpp' || echo '$(srcdir)/'`calpontSupport.cpp - -calpontSupport-calpontSupport.obj: calpontSupport.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontSupport_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT calpontSupport-calpontSupport.obj -MD -MP -MF "$(DEPDIR)/calpontSupport-calpontSupport.Tpo" -c -o calpontSupport-calpontSupport.obj `if test -f 'calpontSupport.cpp'; then $(CYGPATH_W) 'calpontSupport.cpp'; else $(CYGPATH_W) '$(srcdir)/calpontSupport.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/calpontSupport-calpontSupport.Tpo" "$(DEPDIR)/calpontSupport-calpontSupport.Po"; else rm -f "$(DEPDIR)/calpontSupport-calpontSupport.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='calpontSupport.cpp' object='calpontSupport-calpontSupport.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(calpontSupport_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o calpontSupport-calpontSupport.obj `if test -f 'calpontSupport.cpp'; then $(CYGPATH_W) 'calpontSupport.cpp'; else $(CYGPATH_W) '$(srcdir)/calpontSupport.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) $(SCRIPTS) -installdirs: - for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS install-dist_binSCRIPTS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-dist_binSCRIPTS \ - uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am \ - install-dist_binSCRIPTS install-exec install-exec-am \ - install-info install-info-am install-man install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ - tags uninstall uninstall-am uninstall-binPROGRAMS \ - uninstall-dist_binSCRIPTS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/calpontSupport/alarmReport.sh b/oamapps/calpontSupport/alarmReport.sh deleted file mode 100755 index 6d58f7b9..00000000 --- a/oamapps/calpontSupport/alarmReport.sh +++ /dev/null @@ -1,36 +0,0 @@ -#! /bin/sh -# -# $Id: logReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - SERVER=$1 -else - SERVER="localhost" -fi - -if [ $2 ] ; then - DATE=$2 -else - DATE=" " -fi - -rm -f /tmp/logReport.log - -{ -echo " " -echo "******************** Alarm Report for $SERVER ********************" -echo " " - -echo "-- Today's Alarms --" -echo " " -cat /var/log/Calpont/alarm.log 2>/dev/null - -if test -f /var/log/Calpont/archive/alarm.log-$DATE ; then - echo "-- Archived Alarms --" - echo " " - cat /var/log/Calpont/archive/alarm.log-$DATE 2>/dev/null -fi - -} > /tmp/logReport.log - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/analytics/create.sql b/oamapps/calpontSupport/analytics/create.sql deleted file mode 100644 index a7026bc6..00000000 --- a/oamapps/calpontSupport/analytics/create.sql +++ /dev/null @@ -1,26 +0,0 @@ -/* -Table for output from track.sh. - -Contains a row per process / snapshot. - -*/ - -drop table if exists processLog; - -create table processLog ( -snapshotid int, -dtm datetime, /* repeated for a snapshot */ -processPid int, -processUserName varchar(7), -processPriority int, -processNice int, -moduleSwapUsedK int, -moduleCachedUsedK int, -processVirt int, -processRes int, -processShr int, -processS char(8), -processCPUPct decimal(4,1), -processMemPct decimal(4,1), -processTime varchar(20), -processCommand varchar(20))engine=infinidb; diff --git a/oamapps/calpontSupport/analytics/track.sh b/oamapps/calpontSupport/analytics/track.sh deleted file mode 100755 index 6dc4dd67..00000000 --- a/oamapps/calpontSupport/analytics/track.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# -# Usage: -# track.sh - -# top output -#top - 12:45:49 up 21:58, 2 users, load average: 0.04, 0.10, 0.08 -#Tasks: 164 total, 1 running, 163 sleeping, 0 stopped, 0 zombie -#Cpu(s): 2.9%us, 2.4%sy, 10.3%ni, 76.2%id, 8.0%wa, 0.0%hi, 0.2%si, 0.0%st -#Mem: 16440336k total, 6129588k used, 10310748k free, 74336k buffers -#Swap: 2031608k total, 14848k used, 2016760k free, 511012k cached -# -# PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND - -# track.sh output -# SEQ DATE PID USER PR NI SWAP CACHE VIRT RES SHR S %CPU %MEM TIME+ COMMAND -# SWAP and CACHE are systemwise swap space: Swap: ... used ... cached - -i=0 -while [ true ] -do - let i++ - dt=`date '+%Y-%m-%d %H:%M:%S'` - top -b -n 1 | - egrep "Swap:|PrimProc|ExeMgr|DMLProc|DDLProc|cpimport|WriteEngineServ|controllernode|workernode|mysqld|DecomSvr" | - awk '{if(NR==1){s=$4; c=$8; next}}; {print s" "c" "$0}' | - awk -v i=$i -v dt="$dt" '{ - sub(/k/,"",$1); sub(/k/,"",$2); sub(/m/,"000",$7); sub(/m/,"000",$8); sub(/m/,"000",$9); - sub(/\.([0-9]+)g/, "&00000",$7); sub(/^[0-9]+g/, "&000000",$7); gsub(/[.|g]/, "",$7); - sub(/\.([0-9]+)g/, "&00000",$8); sub(/^[0-9]+g/, "&000000",$8); gsub(/[.|g]/, "",$8)} - {print i"|"dt"|"$3"|"$4"|"$5"|"$6"|"$1"|"$2"|"$7"|"$8"|"$9"|"$10"|"$11"|"$12"|"$13"|"$14"|"}' - if [ -f stop.txt ]; then - rm -f stop.txt - exit - fi - sleep 1 -done diff --git a/oamapps/calpontSupport/approximateRowCount.sh b/oamapps/calpontSupport/approximateRowCount.sh deleted file mode 100755 index 44bb6369..00000000 --- a/oamapps/calpontSupport/approximateRowCount.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash - -# -# Estimates the row count for a given table. Uses number of extents * 8M for the estimate. -# - -# -# Initialize variables. -# - -if [ -z "$MYSQLCMD" ]; then - INSTALLDIR="/usr/local/Calpont" - MYSQLCNF=$INSTALLDIR/mysql/my.cnf - MYSQLCMD="$INSTALLDIR/mysql/bin/mysql --defaults-file=$MYSQLCNF -u root" -fi - -# -# Validate that there are two parameters - schema and table. -# -if [ $# -ne 2 ]; then - echo "" - echo "Reports the approximate row count for the given table." - echo "" - echo "Parameters:" - echo " Schema" - echo " Table" -fi -db=$1 -table=$2 - -# -# Validate that the table exists. -# -sql="select count(*) from systable where \`schema\`='$db' and tablename='$table';" -count=`$MYSQLCMD calpontsys --skip-column-names -e "$sql;"` -if [ $count -le 0 ]; then - echo "" - echo "$db.$table does not exist in InfiniDB." - echo "" - exit 1 -fi - -# -# Grab the objectid and column width for a column in the table. -# -sql="select objectid from syscolumn where \`schema\`='$db' and tablename='$table' limit 1;" -objectid=`$MYSQLCMD calpontsys --skip-column-names -e "$sql"` -sql="select columnlength from syscolumn where objectid=$objectid;" -colWidth=`$MYSQLCMD calpontsys --skip-column-names -e "$sql"` - -# -# Use editem to count the extents. -# -extentCount=`/usr/local/Calpont/bin/editem -o $objectid | wc -l` -let extentCount-=2 # Take out the 2 extra rows for header and blank line at end. -let approximateRowCount=$extentCount*8192*1024; - -echo "" -echo "Approximate row count for $db.$table is $approximateRowCount." -echo "" - -exit 0 diff --git a/oamapps/calpontSupport/bulklogReport.sh b/oamapps/calpontSupport/bulklogReport.sh deleted file mode 100755 index 3510f11c..00000000 --- a/oamapps/calpontSupport/bulklogReport.sh +++ /dev/null @@ -1,38 +0,0 @@ -#! /bin/sh -# -# $Id: logReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "root" ]; then - SUDO=" " -else - SUDO="sudo" -fi - -$SUDO rm -f /tmp/${MODULE}_bulklogReport.txt - -{ - -if test -d $INSTALLDIR/data/bulk ; then - echo " " - echo "-- Check for Errors in Bulk Logs --" - echo " " - echo "################# egrep '(ERR|CRIT)' $INSTALLDIR/data/bulk/log/*.err #################" - echo " " - egrep '(ERR|CRIT)' $INSTALLDIR/data/bulk/log/*.err 2>/dev/null -fi - -} > /tmp/${MODULE}_bulklogReport.txt - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/calpontSupport.bat b/oamapps/calpontSupport/calpontSupport.bat deleted file mode 100644 index eb2a2a93..00000000 --- a/oamapps/calpontSupport/calpontSupport.bat +++ /dev/null @@ -1,227 +0,0 @@ -@echo off -pushd . -set help= -if "%1" == "-h" (set help=true) -if "%1" == "/h" (set help=true) -if "%1" == "--help" (set help=true) -if "%help%"=="true" ( - echo The InfiniDB Support Report creates a report that can be sent to InfiniDB - echo for help with field support. There are no options to this command. - set help= - exit /B 0 -) - -echo. -echo Running the InfiniDB Support Report, outputting to InfiniDBSupportReport.txt - -call :func > InfiniDBSupportReport.txt 2>&1 - -echo. -echo Report finished - -popd -exit /B 0 - -:ErrorExit - -echo. -echo Error - Failed to find InfiniDB Install Directory in Windows Registry, Exiting -popd -exit /B 1 - -:func - - setlocal - set key="HKLM\SOFTWARE\Calpont\InfiniDB" - set homeValue=InfiniDBHome - set configValue=ConfigFile - - for /f "tokens=3,*" %%a in ('reg query %key% /ve 2^>NUL ^| findstr REG_SZ') do ( - set InfiniDBInstall=%%b - ) - - if "%InfiniDBInstall%" == "" ( - for /f "tokens=2,*" %%a in ('reg query %key% /ve 2^>NUL ^| findstr REG_SZ') do ( - set InfiniDBInstall=%%b - ) - ) - - ::error out if can't locate Install Directory - if "%InfiniDBInstall%" == "" GOTO ErrorExit - -echo ####################################################################### -echo # # -echo # InfiniDB Support Report - %date% %time% -echo # # -echo ####################################################################### -echo. -echo. -echo ======================================================================= -echo = Software/Version Report = -echo ======================================================================= -echo. -echo. -echo -- InfiniDB Software Version -- -type %InfiniDBInstall%\etc\CalpontVersion.txt -echo. -echo -- mysql Software Version -- -mysql --user=root -e status -echo. -echo -- Windows Version -- -ver -echo. -echo. -echo ======================================================================= -echo = Status Report = -echo ======================================================================= -echo. -echo. -echo -- InfiniDB Process Status -- -echo. - -tasklist /FI "Imagename eq mysqld.exe" -tasklist /FI "Imagename eq controllernode.exe" -tasklist /FI "Imagename eq workernode.exe" -tasklist /FI "Imagename eq PrimProc.exe" -tasklist /FI "Imagename eq ExeMgr.exe" -tasklist /FI "Imagename eq DDLProc.exe" -tasklist /FI "Imagename eq DMLProc.exe" -tasklist /FI "Imagename eq WriteEngineServer.exe" - -echo. -echo. -echo ======================================================================= -echo = Configuration Report = -echo ======================================================================= -echo. -echo -- Windows InfiniDB Registry Values -- -echo. - - echo InfiniDBInstall = %InfiniDBInstall% - - for /f "tokens=2,*" %%a in ('reg query %key% /v %homeValue% 2^>NUL ^| findstr %homeValue%') do ( - set InfiniDBHome=%%b - ) - echo InfiniDBHome = %InfiniDBHome% - - for /f "tokens=2,*" %%a in ('reg query %key% /v %configValue% 2^>NUL ^| findstr %configValue%') do ( - set ConfigFile=%%b - ) - echo ConfigFile = %ConfigFile% -echo. -echo. -echo -- InfiniDB System Configuration Information -- -echo. -cd %InfiniDBInstall%\bin -for /f "delims=" %%a in ('getConfig.exe DBBC NumBlocksPct') do @echo NumBlocksPct = %%a -for /f "delims=" %%a in ('getConfig.exe HashJoin TotalUmMemory') do @echo TotalUmMemory = %%a -for /f "delims=" %%a in ('getConfig.exe VersionBuffer VersionBufferFileSize') do @echo VersionBufferFileSize = %%a -for /f "delims=" %%a in ('getConfig.exe ExtentMap FilesPerColumnPartition') do @echo FilesPerColumnPartition = %%a -for /f "delims=" %%a in ('getConfig.exe ExtentMap ExtentsPerSegmentFile') do @echo ExtentsPerSegmentFile = %%a -echo. -echo. -echo -- InfiniDB System Configuration File -- -echo. -type "%ConfigFile%" -echo. -echo. -echo -- System Process Status -- -echo. -tasklist /v -echo. -echo ======================================================================= -echo = Resource Usage Report = -echo ======================================================================= -echo. -echo -- System Information-- -echo. -systeminfo -echo. -echo -- IP Configuration Information -- -echo. -ipconfig -echo. -echo -- Disk BRM Data files -- -echo. -dir "%InfiniDBInstall%\dbrm\" -echo. -echo -- View Table Locks -- -echo. -cd %InfiniDBInstall%\bin\ -viewtablelock.exe -echo. -echo. -echo -- BRM Extent Map -- -echo. -cd %InfiniDBInstall%\bin\ -editem.exe -i -echo. -echo. -echo ======================================================================= -echo = Log Report = -echo ======================================================================= -echo. -echo -- InfiniDB Platform Logs -- -echo. -type "%InfiniDBInstall%\log\InfiniDBLog.txt" -echo. -echo. -echo -- InfiniDB MySQl log -- -echo. -type "%InfiniDBInstall%\mysqldb\*.err" -echo. -echo. -echo -- InfiniDB Bulk Load Logs -- -echo. -dir "%InfiniDBInstall%\bulk\data" -echo. -dir "%InfiniDBInstall%\bulk\log" -echo. -dir "%InfiniDBInstall%\bulk\job" -echo. -echo -- Check for Errors in Bulk Logs -- -echo. -cd "%InfiniDBInstall%\bulk\log" -findstr /spin /c:"error" * -findstr /spin /c:"failed" * -cd "%InfiniDBInstall%\bulk\job" -findstr /spin /c:"error" * -findstr /spin /c:"failed" * -echo. -echo ======================================================================= -echo = DBMS Report = -echo ======================================================================= -echo. -echo -- DBMS InfiniDB Mysql Version -- -echo. -mysql --user=root -e status -echo. -echo -- DBMS Mysql InfiniDB System Column -- -echo. -mysql --user=root -e "desc calpontsys.syscolumn" -echo. -echo -- DBMS Mysql InfiniDB System Table -- -echo. -mysql --user=root -e "desc calpontsys.systable" -echo. -echo -- DBMS Mysql InfiniDB System Table Data -- -echo. -mysql --user=root -e "select * from calpontsys.systable" -echo. -echo -- DBMS Mysql InfiniDB Databases -- -echo. -mysql --user=root -e "show databases" -echo. -echo -- DBMS Mysql InfiniDB variables -- -echo. -mysql --user=root -e "show variables" -echo. -echo -- DBMS Mysql InfiniDB config file -- -echo. -type "%InfiniDBInstall%\my.ini" -echo. -echo -- Active Queries -- - -::cd \InfiniDB\genii\oamapps\calpontSupport - - diff --git a/oamapps/calpontSupport/calpontSupport.cpp b/oamapps/calpontSupport/calpontSupport.cpp deleted file mode 100644 index 044b2fa2..00000000 --- a/oamapps/calpontSupport/calpontSupport.cpp +++ /dev/null @@ -1,1024 +0,0 @@ -/* Copyright (C) 2013 Calpont Corp. */ - - -/****************************************************************************************** -* $Id: calpontSupport.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "stdio.h" -#include "ctype.h" -#include -#include - -#include "liboamcpp.h" -#include "configcpp.h" -#include "installdir.h" - -using namespace std; -using namespace oam; -using namespace config; - -typedef struct Child_Module_struct -{ - std::string moduleName; - std::string moduleIP; - std::string hostName; -} ChildModule; - -typedef std::vector ChildModuleList; - -string currentDate; -string systemName; -string localModule; -string localModuleHostName; -ChildModuleList childmodulelist; -ChildModuleList parentmodulelist; -ChildModule childmodule; - -string rootPassword = ""; -string debug_flag = "0"; -string mysqlpw = " "; - -int runningThreads = 0; -pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; - -typedef boost::tuple threadInfo_t; - -bool LOCAL = false; - -void title(string outputFile = "calpontSupportReport.txt") -{ - string cmd = "echo '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' System " + systemName + "' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' calpontSupportReport script ran from Module " + localModule + " on " + currentDate + "' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' >> " + outputFile; - system(cmd.c_str()); -} - -void childReportThread(threadInfo_t& st) -{ - ChildModuleList::iterator& list = boost::get<0>(st); - string reportType = boost::get<1>(st); - - string remoteModuleName = (*list).moduleName; - string remoteModuleIP = (*list).moduleIP; - string remoteHostName = (*list).hostName; - - string installDir(startup::StartUp::installDir()); - - pthread_mutex_lock( &mutex1 ); - runningThreads++; -//cout << "++ " << runningThreads << endl; - pthread_mutex_unlock( &mutex1 ); - - string outputFile; - if (reportType == "log") - { - outputFile = remoteModuleName + "_" + reportType + "Report.tar.gz"; - } - else if (reportType == "hadoop") - { - outputFile = "hadoopReport.txt"; - } - else - { - outputFile = remoteModuleName + "_" + reportType + "Report.txt"; - - title(outputFile); - - string cmd = "echo '=======================================================================' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '= " + reportType + " report =' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '=======================================================================' >> " + outputFile; - system(cmd.c_str()); - } - - //run remote report script - if (reportType == "hadoop") - cout << "Get " + reportType + " report data" << endl; - else - cout << "Get " + reportType + " report data for " + remoteModuleName + " " << endl; - cout.flush(); - - string cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + rootPassword + " '" + - installDir + "/bin/" + reportType + "Report.sh " + remoteModuleName + " " + installDir + - "' " + debug_flag + " - forcetty"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { - cout << "Error with running remote_command.sh, exiting..." << endl; - } - cmd = installDir + "/bin/remote_scp_get.sh " + remoteModuleIP + " " + rootPassword + " /tmp/" + outputFile + " > /dev/null 2>&1"; - rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) - cout << "ERROR: failed to retrieve /tmp/" << outputFile << " from " + remoteHostName << endl; - pthread_mutex_lock( &mutex1 ); - runningThreads--; -//cout << "-- " << runningThreads << endl; - pthread_mutex_unlock( &mutex1 ); - - // exit thread - pthread_exit(0); -} - -void reportThread(string reporttype) -{ - string reportType = reporttype; - - string installDir(startup::StartUp::installDir()); - Oam oam; - - pthread_mutex_lock( &mutex1 ); - runningThreads++; -//cout << "++ " << runningThreads << endl; - pthread_mutex_unlock( &mutex1 ); - - string outputFile = localModule + "_" + reportType + "Report.txt"; - - // run on child servers and get report - if (!LOCAL) - { - ChildModuleList::iterator list1 = childmodulelist.begin(); - for (; list1 != childmodulelist.end() ; list1++) - { - threadInfo_t *st = new threadInfo_t; - *st = boost::make_tuple(list1, reportType); - - pthread_t childreportthread; - int status = pthread_create (&childreportthread, NULL, (void*(*)(void*)) &childReportThread, st); - - if ( status != 0 ) { - cout << "ERROR: childreportthread: pthread_create failed, return status = " + oam.itoa(status) << endl; - } - - sleep(1); - } - } - - // run report on local server - cout << "Get " + reportType + " report data for " + localModule << endl; - - if (reportType == "log") - { - string cmd = installDir + "/bin/logReport.sh " + localModule + " " + installDir; - system(cmd.c_str()); - - cmd = "mv -f /tmp/" + localModule + "_logReport.tar.gz ."; - system(cmd.c_str()); - - cmd = "tar -zcf " + localModule + "_mysqllogReport.tar.gz " + installDir + "/mysql/db/*.err* 2>/dev/null"; - system(cmd.c_str()); - - // run log config on local server - cout << "Get log config data for " + localModule << endl; - - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** Log Configuration ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# calpontConsole getLogConfig ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getLogConfig >> " + outputFile; - system(cmd.c_str()); - } - else - { - //get local report - title(outputFile); - - string cmd = "echo '=======================================================================' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '= " + reportType + " report =' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '=======================================================================' >> " + outputFile; - system(cmd.c_str()); - - cmd = installDir + "/bin/" + reportType + "Report.sh " + localModule + " " + installDir; - system(cmd.c_str()); - cmd = " mv -f /tmp/" + localModule + "_" + reportType + "Report.txt ."; - system(cmd.c_str()); - - if (reportType == "config" ) - { - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** System Network Configuration ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# calpontConsole getSystemNetworkConfig ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getSystemNetworkConfig >> " + outputFile; - system(cmd.c_str()); - - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** System Module Configure ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# calpontConsole getModuleTypeConfig ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getModuleTypeConfig >> " + outputFile; - system(cmd.c_str()); - - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** System Storage Configuration ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# calpontConsole getStorageConfig ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getStorageConfig >> " + outputFile; - system(cmd.c_str()); - - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** System Storage Status ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# calpontConsole getStorageStatus ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getStorageStatus >> " + outputFile; - system(cmd.c_str()); - - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** System Status ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# calpontConsole getSystemInfo ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getSystemInfo >> " + outputFile; - system(cmd.c_str()); - - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '******************** System Configuration File ********************' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo '################# cat /etc/Calpont.xml ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - cmd = "cat " + installDir + "/etc/Calpont.xml >> " + outputFile; - system(cmd.c_str()); - } - - if (reportType == "resource" ) - { - if (LOCAL) { - cmd = "echo '################# calpontConsole getModuleResourceUsage ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - string cmd = installDir + "/bin/calpontConsole getModuleResourceUsage " + localModule + " >> " + outputFile; - system(cmd.c_str()); - } - else - { - cmd = "echo '################# calpontConsole getSystemResourceUsage ################# ' >> " + outputFile; - system(cmd.c_str()); - cmd = "echo ' ' >> " + outputFile; - system(cmd.c_str()); - string cmd = installDir + "/bin/calpontConsole getSystemResourceUsage >> " + outputFile; - system(cmd.c_str()); - } - } - } - - // exit thread - pthread_mutex_lock( &mutex1 ); - runningThreads--; -//cout << "-- " << runningThreads << endl; - pthread_mutex_unlock( &mutex1 ); - - pthread_exit(0); -} - -int main(int argc, char *argv[]) -{ - Oam oam; - string installDir(startup::StartUp::installDir()); - - Config* sysConfig = Config::makeConfig(); - string SystemSection = "SystemConfig"; - string InstallSection = "Installation"; - - bool HARDWARE = false; - bool SOFTWARE = false; - bool CONFIG = false; - bool DBMS = false; - bool RESOURCE = false; - bool LOG = false; - bool BULKLOG = false; - bool HADOOP = false; - - //get current time and date - time_t now; - now = time(NULL); - struct tm tm; - localtime_r(&now, &tm); - char timestamp[200]; - strftime (timestamp, 200, "%m:%d:%y-%H:%M:%S", &tm); - currentDate = timestamp; - - char helpArg[3] = "-h"; - - // Get System Name - try{ - oam.getSystemConfig("SystemName", systemName); - } - catch(...) - { - systemName = "unassigned"; - } - - // get Local Module Name and Server Install Indicator - string singleServerInstall; - - oamModuleInfo_t st; - try { - st = oam.getModuleInfo(); - localModule = boost::get<0>(st); - } - catch (...) { - cout << endl << "**** Failed : Failed to read Local Module Name" << endl; - exit(-1); - } - - try{ - oam.getSystemConfig("SingleServerInstall", singleServerInstall); - } - catch(...) - { - singleServerInstall = "y"; - } - - if (argc == 1) { - argv[1] = &helpArg[0]; - argc = 2; - } - - string DataFilePlugin; - try{ - DataFilePlugin = sysConfig->getConfig(SystemSection, "DataFilePlugin"); - } - catch(...) - { - cout << "ERROR: Problem accessing InfiniDB configuration file" << endl; - exit(-1); - } - - for( int i = 1; i < argc; i++ ) - { - if( string("-h") == argv[i] ) { - cout << endl; - cout << "'calpontSupport' generates a Set of System Support Report Files in a tar file" << endl; - cout << "called calpontSupportReport.'system-name'.tar.gz in the local directory." << endl; - cout << "It should be run on the server with the DBRM front-end." << endl; - cout << "Check the Admin Guide for additional information." << endl; - cout << endl; - cout << "Usage: calpontSupport [-h][-a][-hw][-s][-c][-db][-r][-l][-bl][-lc][-p 'root-password'][-mp 'mysql-root-password'][-de]"; - // if hdfs set up print the hadoop option - if (!DataFilePlugin.empty()) - cout << "[-hd]"; - cout << endl; - cout << " -h help" << endl; - cout << " -a Output all Reports (excluding Bulk Logs Reports)" << endl; - cout << " -hw Output Hardware Reports only" << endl; - cout << " -s Output Software Reports only" << endl; - cout << " -c Output Configuration/Status Reports only" << endl; - cout << " -db Output DBMS Reports only" << endl; - cout << " -r Output Resource Reports only" << endl; - cout << " -l Output Calpont Log/Alarms Reports only" << endl; - cout << " -bl Output Calpont Bulk Log Reports only" << endl; - cout << " -lc Output Reports for Local Server only" << endl; - cout << " -p password (multi-server systems), root-password or 'ssh' to use 'ssh keys'" << endl; - cout << " -mp mysql root user password" << endl; - cout << " -de Debug Flag" << endl; - // if hdfs set up print the hadoop option - if (!DataFilePlugin.empty()) - cout << " -hd Output hadoop reports only" << endl; - - exit (0); - } - else - { - if( string("-a") == argv[i] ) { - HARDWARE = true; - SOFTWARE = true; - CONFIG = true; - DBMS = true; - RESOURCE = true; - LOG = true; - HADOOP = (DataFilePlugin.empty()? false : true); - } - else if( string("-hw") == argv[i] ) - HARDWARE = true; - else if( string("-s") == argv[i] ) - SOFTWARE = true; - else if( string("-c") == argv[i] ) - CONFIG = true; - else if( string("-db") == argv[i] ) - DBMS = true; - else if( string("-r") == argv[i] ) - RESOURCE = true; - else if( string("-l") == argv[i] ) - LOG = true; - else if( string("-bl") == argv[i] ) - BULKLOG = true; - else if( string("-lc") == argv[i] ) - LOCAL = true; - else if( string("-p") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing root password argument" << endl; - exit(-1); - } - rootPassword = argv[i]; - //add single quote for special characters - if ( rootPassword != "ssh" ) - { - rootPassword = "'" + rootPassword + "'"; - } - } - else if( string("-mp") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing mysql root user password argument" << endl; - exit(-1); - } - mysqlpw = argv[i]; - mysqlpw = "'" + mysqlpw + "'"; - } - else if( string("-de") == argv[i] ) - debug_flag = "1"; - else if ( string("-hd") == argv[i] ) - { - HADOOP = (DataFilePlugin.empty()? false : true); - } - else - { - cout << "Invalid Option of '" << argv[i] << "', run with '-h' for help" << endl; - exit (1); - } - } - } - - //default to -a if nothing is set - if ( !HARDWARE && !SOFTWARE && !CONFIG && !DBMS && !RESOURCE && !LOG && !BULKLOG && !HADOOP) - { - HARDWARE = true; - SOFTWARE = true; - CONFIG = true; - DBMS = true; - RESOURCE = true; - LOG = true; - HADOOP = (DataFilePlugin.empty()? false : true); - } - - //get Parent OAM Module Name and setup of it's Custom OS files - string PrimaryUMModuleName; - try{ - PrimaryUMModuleName = sysConfig->getConfig(SystemSection, "PrimaryUMModuleName"); - } - catch(...) - { - cout << "ERROR: Problem getting Parent OAM Module Name" << endl; - exit(-1); - } - - if ( PrimaryUMModuleName == "unassigned" ) - PrimaryUMModuleName = localModule; - - if ( (localModule != PrimaryUMModuleName) && DBMS ) - { - char* pcommand = 0; - char *p; - string argument = "n"; - - while(true) - { - cout << endl << "You selected to get the DBMS data." << endl; - cout << "You need to run the calpontSupport command on module '" << PrimaryUMModuleName << "' to get that information." << endl; - cout << "Or you can proceed on to get all data except the DBMS." << endl; - - pcommand = readline(" Do you want to proceed: (y or n) [n]: "); - - if (pcommand && *pcommand) { - p = strtok(pcommand," "); - argument = p; - free(pcommand); - pcommand = 0; - } - - if (pcommand) { - free(pcommand); - pcommand = 0; - } - - if( argument == "y") { - cout << endl; - break; - } - else if( argument == "n") - exit (1); - } - } - - //get number of worker-nodes, will tell us if a single server system - //get Parent OAM Module Name and setup of it's Custom OS files - try{ - string NumWorkers = sysConfig->getConfig("DBRM_Controller", "NumWorkers"); - if ( NumWorkers == "1" ) - singleServerInstall = "y"; - } - catch(...) - {} - - if ( singleServerInstall == "n" && !LOCAL) - if ( HARDWARE || SOFTWARE || CONFIG || RESOURCE || LOG || HADOOP ) - if ( rootPassword.empty() ) { - cout << "ERROR: Multi-Module System, Password Argument required or use '-lc' option, check help for more information" << endl; - exit(-1); - } - - //get Parent OAM Module Name and setup of it's Custom OS files - //string parentOAMModuleName; - ChildModule parentOAMModule; - try{ - parentOAMModule.moduleName = sysConfig->getConfig(SystemSection, "ParentOAMModuleName"); - } - catch(...) - { - cout << "ERROR: Problem getting Parent OAM Module Name" << endl; - exit(-1); - } - - //Get list of configured system modules - SystemModuleTypeConfig sysModuleTypeConfig; - - try{ - oam.getSystemConfig(sysModuleTypeConfig); - } - catch(...) - { - cout << "ERROR: Problem reading the Calpont System Configuration file" << endl; - exit(-1); - } - - string ModuleSection = "SystemModuleConfig"; - - for ( unsigned int i = 0 ; i < sysModuleTypeConfig.moduletypeconfig.size(); i++) - { - string moduleType = sysModuleTypeConfig.moduletypeconfig[i].ModuleType; - int moduleCount = sysModuleTypeConfig.moduletypeconfig[i].ModuleCount; - - if ( moduleCount == 0 ) - //no modules equipped for this Module Type, skip - continue; - - //get IP addresses and Host Names - DeviceNetworkList::iterator listPT = sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for( ; listPT != sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.end() ; listPT++) - { - string moduleName = (*listPT).DeviceName; - HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); - string moduleIPAddr = (*pt1).IPAddr; - string moduleHostName = (*pt1).HostName; - - if ( moduleName == localModule) { - localModuleHostName = moduleHostName; - } - - //save Child modules - if ( moduleName != localModule && moduleType != "xm") { - childmodule.moduleName = moduleName; - childmodule.moduleIP = moduleIPAddr; - childmodule.hostName = moduleHostName; - childmodulelist.push_back(childmodule); - } - - if (moduleName == parentOAMModule.moduleName) - { - parentOAMModule.moduleIP = moduleIPAddr; - parentOAMModule.hostName = moduleHostName; - parentOAMModule.moduleName = moduleName; - } - } - } //end of i for loop - - // create a clean Calpont Support Report - system("rm -f *_configReport.txt"); - system("rm -f *_dbmsReport.txt"); - system("rm -f *_hardwareReport.txt"); - system("rm -f *_logReport.txt"); - system("rm -f *_bulklogReport.txt"); - system("rm -f *_resourceReport.txt"); - system("rm -f *_softwareReport.txt"); - system("rm -f hadoopReport.txt"); - - // - // Software - // - - if ( SOFTWARE ) { - string reportType = "software"; - pthread_t reportthread; - int status = pthread_create (&reportthread, NULL, (void*(*)(void*)) &reportThread, &reportType); - - if ( status != 0 ) { - cout << "ERROR: reportthread: pthread_create failed, return status = " + oam.itoa(status); - } - - sleep(5); - } - - // - // Configuration - // - - if ( CONFIG ) { - string reportType = "config"; - pthread_t reportthread; - int status = pthread_create (&reportthread, NULL, (void*(*)(void*)) &reportThread, &reportType); - - if ( status != 0 ) { - cout << "ERROR: reportthread: pthread_create failed, return status = " + oam.itoa(status); - } - - sleep(5); - } - - // - // Alarms and Calpont Logs - // - - if ( LOG ) { - string reportType = "log"; - pthread_t reportthread; - int status = pthread_create (&reportthread, NULL, (void*(*)(void*)) &reportThread, &reportType); - - if ( status != 0 ) { - cout << "ERROR: reportthread: pthread_create failed, return status = " + oam.itoa(status); - } - - sleep(5); - } - - // - // Bulk Logs - // - - if ( BULKLOG ) { - string reportType = "bulklog"; - pthread_t reportthread; - int status = pthread_create (&reportthread, NULL, (void*(*)(void*)) &reportThread, &reportType); - - if ( status != 0 ) { - cout << "ERROR: reportthread: pthread_create failed, return status = " + oam.itoa(status); - } - - sleep(5); - } - - // - // Hardware - // - - if ( HARDWARE ) { - string reportType = "hardware"; - pthread_t reportthread; - int status = pthread_create (&reportthread, NULL, (void*(*)(void*)) &reportThread, &reportType); - - if ( status != 0 ) { - cout << "ERROR: reportthread: pthread_create failed, return status = " + oam.itoa(status); - } - - sleep(5); - } - - // - // Resources - // - - if ( RESOURCE ) { - string reportType = "resource"; - pthread_t reportthread; - int status = pthread_create (&reportthread, NULL, (void*(*)(void*)) &reportThread, &reportType); - - if ( status != 0 ) { - cout << "ERROR: reportthread: pthread_create failed, return status = " + oam.itoa(status); - } - - sleep(5); - } - - // - // DBMS - // - - if ( DBMS ) { - system("rm -f calpontSupportReport.txt;touch calpontSupportReport.txt"); - title(); - - system("echo '=======================================================================' >> calpontSupportReport.txt"); - system("echo '= DBMS Report =' >> calpontSupportReport.txt"); - system("echo '=======================================================================' >> calpontSupportReport.txt"); - - // run DBMS report on local server - cout << "Get dbms report data for " << localModule << endl; - - bool FAILED = false; - if ( localModule != PrimaryUMModuleName ) - { - cout << " FAILED: run calpontSupport on '" << PrimaryUMModuleName << "' to get the dbrm report" << endl; - FAILED = true; - } - else - { - // check if mysql is supported and get info - string calpontMysql = installDir + "/mysql/bin/mysql --defaults-file=" + installDir + "/mysql/my.cnf -u root "; - string cmd = calpontMysql + " -e 'status' > /tmp/idbmysql.log 2>&1"; - system(cmd.c_str()); - - //check for mysql password set - string pwprompt = " "; - - if (oam.checkLogStatus("/tmp/idbmysql.log", "ERROR 1045") ) { - cout << "NOTE: MySQL root user password is set" << endl; - //needs a password, was password entered on command line - if ( mysqlpw == " " ) - { //go check my.cnf - string file = installDir + "/mysql/my.cnf"; - ifstream oldFile (file.c_str()); - - vector lines; - char line[200]; - string buf; - while (oldFile.getline(line, 200)) - { - buf = line; - string::size_type pos = buf.find("password",0); - if (pos != string::npos) { - string::size_type pos1 = buf.find("=",0); - if (pos1 != string::npos) { - pos = buf.find("#",0); - if (pos == string::npos) { - //password arg in my.cnf, go get password - cout << "NOTE: Using password from my.cnf" << endl; - mysqlpw = buf.substr(pos1+1,80); - cout << mysqlpw << endl; - break; - } - } - } - } - - oldFile.close(); - - if ( mysqlpw == " " ) - { - cout << "NOTE: No password provide on command line or found uncommented in my.cnf" << endl; - cout << endl; - string prompt = " *** Enter MySQL password > "; - mysqlpw = getpass(prompt.c_str()); - } - } - - //check for mysql password set - pwprompt = "--password=" + mysqlpw; - - string cmd = calpontMysql + pwprompt + " -e 'status' > /tmp/idbmysql.log 2>&1"; - system(cmd.c_str()); - - if (oam.checkLogStatus("/tmp/idbmysql.log", "ERROR 1045") ) { - cout << "FAILED: Failed login using MySQL root user password '" << mysqlpw << "'" << endl; - FAILED = true; - } - } - - if (!FAILED) - { - // check if mysql is supported and get info - string calpontMysql = installDir + "/mysql/bin/mysql --defaults-file=" + installDir + "/mysql/my.cnf -u root " + pwprompt; - string cmd = calpontMysql + " -V > /dev/null 2>&1"; - int ret = system(cmd.c_str()); - if ( WEXITSTATUS(ret) == 0) { - // run DBMS report info - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS InfiniDB Mysql Version ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " -e status ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " -e 'status' >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql Calpont System Column ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " -e desc calpontsys.syscolumn ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " -e 'desc calpontsys.syscolumn;' >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql Calpont System Table ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " -e desc calpontsys.systable ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " -e 'desc calpontsys.systable;' >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql Calpont System Catalog Data ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " calpontsys < " + installDir + "/mysql/dumpcat_mysql.sql ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " calpontsys < " + installDir + "/mysql/dumpcat_mysql.sql >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql Calpont System Table Data ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " -e select * from calpontsys.systable ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " -e 'select * from calpontsys.systable;' >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql Calpont Usernames ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " -e show databases ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " -e 'show databases;' >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql InfiniDB variables ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# " + calpontMysql + " show variables ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = calpontMysql + " -e 'show variables;' >> calpontSupportReport.txt"; - system(cmd.c_str()); - } - } - } - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** Database Size Report ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - string cmd = "echo '################# /bin/databaseSizeReport ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = installDir + "/bin/databaseSizeReport >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** DBMS Mysql InfiniDB config file ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# cat /mysql/my.cnf ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "cat " + installDir + "/mysql/my.cnf 2>/dev/null >> calpontSupportReport.txt"; - system(cmd.c_str()); - - system("echo ' ' >> calpontSupportReport.txt"); - system("echo '******************** Active Queries ********************' >> calpontSupportReport.txt"); - system("echo ' ' >> calpontSupportReport.txt"); - cmd = "echo '################# calpontConsole getActiveSqlStatement ################# ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = "echo ' ' >> calpontSupportReport.txt"; - system(cmd.c_str()); - cmd = installDir + "/bin/calpontConsole getActiveSqlStatement >> calpontSupportReport.txt"; - system(cmd.c_str()); - - cmd = "cat calpontSupportReport.txt > " + localModule + "_dbmsReport.txt"; - system(cmd.c_str()); - } - - // - // HADOOP - // - - if (HADOOP) - { - if (LOCAL || childmodulelist.empty()) - { - cout << "Get hadoop report data" << endl; - string cmd = installDir + "/bin/hadoopReport.sh " + localModule + " " + installDir + "\n"; - cmd += " mv -f /tmp/hadoopReport.txt ."; - FILE* pipe = popen(cmd.c_str(), "r"); - if (!pipe) - { - cout << "Failed to get a pipe for hadoop health check commands" << endl; - exit(-1); - } - pclose(pipe); - } - else - { - // only get hadoop report from parentOAMModule, because it's consistant view. - parentmodulelist.push_back(parentOAMModule); - threadInfo_t *st = new threadInfo_t; - ChildModuleList::iterator iter = parentmodulelist.begin(); - *st = boost::make_tuple(iter, "hadoop"); - - pthread_t hdthread; - int status = pthread_create (&hdthread, NULL, (void*(*)(void*)) &childReportThread, st); - if ( status != 0 ) - { - cout << "ERROR: childreportthread: pthread_create failed, return status = " + oam.itoa(status) << endl; - } - } - } - - //wait for all threads to complete - sleep(5); - int wait = 0; - while (true) - { -//cout << "check " << runningThreads << endl; - if (runningThreads < 1) - break; - - sleep(2); - wait++; - // give it 60 minutes to complete - if ( wait >= 3600 * 5) - { - cout << "Timed out (60 minutes) waiting for Requests to complete" << endl; - } - } - - system("rm -f calpontSupportReport.txt"); - - system("unix2dos *Report.txt > /dev/null 2>&1"); - system("rm -rf calpontSupportReport;mkdir calpontSupportReport;mv *Report.txt calpontSupportReport/. > /dev/null 2>&1;mv *Report.tar.gz calpontSupportReport/. > /dev/null 2>&1"); - string cmd = "tar -zcf calpontSupportReport." + systemName + ".tar.gz calpontSupportReport/*"; - system(cmd.c_str()); - - - cout << endl << "Calpont Support Script Successfully completed, files located in calpontSupportReport." + systemName + ".tar.gz" << endl; -} diff --git a/oamapps/calpontSupport/configReport.sh b/oamapps/calpontSupport/configReport.sh deleted file mode 100755 index e517e027..00000000 --- a/oamapps/calpontSupport/configReport.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/bin/bash -# -# $Id: hardwareReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "root" ]; then - SUDO=" " -else - SUDO="sudo" -fi - -$SUDO rm -f /tmp/${MODULE}_configReport.txt - -{ -echo " " -echo "******************** Configuration/Status Report for ${MODULE} ********************" -echo " " - -if test -f /sbin/chkconfig ; then - echo "-- chkconfig configuration --" - echo " " - echo "################# /sbin/chkconfig --list | grep infinidb #################" - echo " " - $SUDO /sbin/chkconfig --list | grep infinidb 2>/dev/null - echo "################# /sbin/chkconfig --list | grep mysql-Calpont #################" - echo " " - $SUDO /sbin/chkconfig --list | grep mysql-Calpont 2>/dev/null -fi - -echo " " -echo "-- fstab Configuration --" -echo " " -echo "################# cat /etc/fstab #################" -echo " " -$SUDO cat /etc/fstab 2>/dev/null - -echo " " -echo "-- Server Processes --" -echo " " -echo "################# ps axu #################" -echo " " -$SUDO ps axu - -echo " " -echo "-- Server Processes with resource usage --" -echo " " -echo "################# top -b -n 1 #################" -echo " " -$SUDO top -b -n 1 - -} > /tmp/${MODULE}_configReport.txt - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/findStranded.sh b/oamapps/calpontSupport/findStranded.sh deleted file mode 100755 index 0f45e326..00000000 --- a/oamapps/calpontSupport/findStranded.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/sh - -# -# This script lists InfiniDBlpont data files that do not have associated extent map entries. -# -# NOTES: -# 1) Only looks in $INFINIDB_INSTALL_DIR/data* for the data files. -# 2) Only checks for an existing extent with a matching OID, doesn't validate that there is an -# existing extent for the exact segment. -# -# Close enough for hand grenades. - -if [ -z "$INFINIDB_INSTALL_DIR" ]; then - INFINIDB_INSTALL_DIR=/usr/local/Calpont -fi - -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR - -if [ $INFINIDB_INSTALL_DIR != "/usr/local/Calpont" ]; then - export PATH=$INFINIDB_INSTALL_DIR/bin:$INFINIDB_INSTALL_DIR/mysql/bin:/bin:/usr/bin - export LD_LIBRARY_PATH=$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql -fi - -cd $INFINIDB_INSTALL_DIR - -last=-1 -existsInExtentMap=0 -count=0 - -for i in $INFINIDB_INSTALL_DIR/data*/*/*/*/*/*/FILE*cdf; do - let count++ - oid=`$INFINIDB_INSTALL_DIR/bin/file2oid.pl $i` - if [ $last -ne $oid ]; then - last=$oid - existsInExtentMap=`$INFINIDB_INSTALL_DIR/bin/editem -o $oid | wc -l` - fi - if [ $existsInExtentMap -le 0 ]; then - echo "Missing oid $oid path $i" - fi -done diff --git a/oamapps/calpontSupport/getMinMax.sh b/oamapps/calpontSupport/getMinMax.sh deleted file mode 100755 index ad0b78e7..00000000 --- a/oamapps/calpontSupport/getMinMax.sh +++ /dev/null @@ -1,132 +0,0 @@ -#!/bin/bash - -# -# Reports the max value from the extent map for the given column. -# - -# -# Initialize variables. -# - -if [ -z "$MYSQLCMD" ]; then - INSTALLDIR="/usr/local/Calpont" - MYSQLCNF=$INSTALLDIR/mysql/my.cnf - MYSQLCMD="$INSTALLDIR/mysql/bin/mysql --defaults-file=$MYSQLCNF -u root" -fi - -# -# Validate that there are three parameters - schema and table and columnname. -# -if [ $# -ne 3 ]; then - echo "" - echo "Reports the max value for the given column." - echo "" - echo "Parameters:" - echo " Schema" - echo " Table" - echo " Column" - exit 1 -fi -db=$1 -table=$2 -column=$3 - -# -# Validate that the column exists. -# -sql="select count(*) from syscolumn where \`schema\`='$db' and tablename='$table' and columnname='$column';" -count=`$MYSQLCMD calpontsys --skip-column-names -e "$sql;"` -if [ $count -le 0 ]; then - echo "" - echo "$db.$table.$column does not exist in InfiniDB." - echo "" - exit 1 -fi - -# -# Validate that the column type is one that this script supports. -# Supported Types: -# 6 int -# 8 date -# 9 bigint -# 11 datetime -sql="select datatype from syscolumn where \`schema\`='$db' and tablename='$table' and columnname='$column';" -dataType=`$MYSQLCMD calpontsys --skip-column-names -e "$sql"` -if [ $dataType -ne 6 ] && [ $dataType -ne 8 ] && [ $dataType -ne 9 ] && [ $dataType -ne 11 ]; then - echo "" - echo "The column data type must be an int, bigint, date, or datetime." - echo "" - exit 1 -fi - -# -# Grab the objectid for the column. -# -sql="select objectid from syscolumn where \`schema\`='$db' and tablename='$table' and columnname='$column';" -objectid=`$MYSQLCMD calpontsys --skip-column-names -e "$sql"` - -# -# Set the editem specific parameter if the column is a date or datetime. -# -if [ $dataType -eq 8 ]; then - parm="-t" -elif [ $dataType -eq 11 ]; then - parm="-s" -fi - -# -# Use the editem utility to get the min and max value. -# -/usr/local/Calpont/bin/editem -o $objectid $parm | grep max | awk -v dataType=$dataType ' - BEGIN { - allValid=1; - foundValidExtent=0; - } - { - if(dataType == 11) { - state=substr($14, 1, length($14)-1); # Datetime has date and time as two fields. - thisMin=$6 " " substr($7, 1, length($7)-1); - thisMax=$9 " " substr($10, 1, length($10)-1); - } - else { - state=substr($12, 1, length($12)-1); - thisMin=substr($6, 1, length($6)-1); - thisMax=substr($8, 1, length($8)-1); - } - if(state == "valid") { - if(!foundValidExtent) { - min=thisMin; - max=thisMax; - foundValidExtent=1; - } - else { - if(thisMin < min) { - min=thisMin; - } - if(thisMax > max) { - max=thisMax; - } - } - } - else { - allValid=0; - } - } - END { - if(foundValidExtent == 1) { - print ""; - print "Min=" min; - print "Max=" max; - print ""; - if(allValid == 0) { - print "Not all extents had min and max values set. Answer is incomplete." - } - } - else { - print ""; - print "There were not any extents with valid min/max values. Unable to provide answer."; - print ""; - } - }' - -exit 0 diff --git a/oamapps/calpontSupport/hadoopReport.sh b/oamapps/calpontSupport/hadoopReport.sh deleted file mode 100755 index bbd8f0fc..00000000 --- a/oamapps/calpontSupport/hadoopReport.sh +++ /dev/null @@ -1,69 +0,0 @@ -#! /bin/sh -# - -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "hdfs" ]; then - SUDO=" " -else - SUDO="sudo -u hdfs" -fi - -sudo rm -f /tmp/hdfsReport.txt - -{ -echo -echo "****************************** HDFS REPORT ********************************" -echo -echo "-- Hadoop version --" -echo -echo "################# hadoop version #################" -echo -$SUDO hadoop version - -echo -echo "-- Data File Plugin --" -echo -echo "######### $INSTALLDIR/bin/getConfig SystemConfig DataFilePlugin ##########" -echo -sudo $INSTALLDIR/bin/getConfig SystemConfig DataFilePlugin - -echo -echo -echo "-- Hadoop Configuration File --" -echo -echo "################ core-site.xml ################" -echo -cat $HADOOP_CONF_DIR/core-site.xml - -echo -echo "################ hdfs-site.xml ################" -echo -cat $HADOOP_CONF_DIR/hdfs-site.xml - -echo -echo "-- Hadoop Health Check --" -echo -echo "################# hdfs dfsadmin -report #################" -echo -$SUDO hadoop dfsadmin -report 2>/dev/null - -echo -echo "-- HDFS check --" -echo -echo "################# hdfs fsck $INSTALLDIR #################" -echo -$SUDO hadoop fsck $INSTALLDIR 2>/dev/null -} > /tmp/hadoopReport.txt - -exit 0 diff --git a/oamapps/calpontSupport/hardwareReport.sh b/oamapps/calpontSupport/hardwareReport.sh deleted file mode 100755 index b39155f8..00000000 --- a/oamapps/calpontSupport/hardwareReport.sh +++ /dev/null @@ -1,101 +0,0 @@ -#! /bin/sh -# -# $Id: hardwareReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "root" ]; then - SUDO=" " -else - SUDO="sudo" -fi - -$SUDO rm -f /tmp/${MODULE}_hardwareReport.txt - -{ -echo " " -echo "******************** Hardware Report for ${MODULE} ********************" -echo " " - -echo "-- Server OS Version --" -echo " " -echo "################# cat /proc/version #################" -echo " " -$SUDO cat /proc/version 2>/dev/null -echo " " -echo "################# uname -a #################" -echo " " -uname -a -echo " " -echo "################# cat /etc/issue #################" -echo " " -cat /etc/issue 2>/dev/null -echo " " -echo "run os_check.sh" -echo " " -echo "################# /bin/os_check.sh #################" -echo " " -$INSTALLDIR/bin/os_check.sh 2>/dev/null - -echo " " -echo "-- Server Uptime --" -echo " " -echo "################# uptime #################" -echo " " -uptime - -echo " " -echo "-- Server cpu-info --" -echo " " -echo "################# cat /proc/cpuinfo #################" -echo " " -$SUDO cat /proc/cpuinfo 2>/dev/null - -echo " " -echo "-- Server memory-info --" -echo " " -echo "################# cat /proc/meminfo #################" -echo " " -$SUDO cat /proc/meminfo 2>/dev/null - -echo " " -echo "-- Server mounts --" -echo " " -echo "################# cat /proc/mounts #################" -echo " " -$SUDO cat /proc/mounts 2>/dev/null - -echo " " -echo "-- Server Disk Scheduler for Calpont Mounts --" -echo " " -for scsi_dev in `mount | awk '/mnt\/tmp/ {print $1}' | awk -F/ '{print $3}' | sed 's/[0-9]*$//'`; do - echo '/dev/'$scsi_dev ' scheduler setup is' - cat /sys/block/$scsi_dev/queue/scheduler 2>/dev/null -done -for scsi_dev in `mount | awk '/Calpont\/data/ {print $1}' | awk -F/ '{print $3}' | sed 's/[0-9]*$//'`; do - if [ $scsi_dev != "local" ] ; then - echo '/dev/'$scsi_dev ' scheduler setup is' - cat /sys/block/$scsi_dev/queue/scheduler 2>/dev/null - fi -done - -echo " " -echo "-- Server Ethernet Configuration --" -echo " " -echo "################# ifconfig -a #################" -echo " " -ifconfig -a 2>/dev/null - -} > /tmp/${MODULE}_hardwareReport.txt - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/logReport.sh b/oamapps/calpontSupport/logReport.sh deleted file mode 100755 index ac68a0b0..00000000 --- a/oamapps/calpontSupport/logReport.sh +++ /dev/null @@ -1,27 +0,0 @@ -#! /bin/sh -# -# $Id: logReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "root" ]; then - SUDO=" " -else - SUDO="sudo" -fi - -$SUDO rm -f /tmp/${MODULE}_logReport.tar.gz - -$SUDO tar -zcf /tmp/${MODULE}_logReport.tar.gz /var/log/Calpont > /dev/null 2>&1 - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/minMaxCheck.sh b/oamapps/calpontSupport/minMaxCheck.sh deleted file mode 100755 index b20eb189..00000000 --- a/oamapps/calpontSupport/minMaxCheck.sh +++ /dev/null @@ -1,170 +0,0 @@ -#!/bin/bash -# -# $Id: minMaxCheck.sh 1479 2011-07-20 09:53:32Z wweeks $ -# - -# -# This script resets the EM Min/Max values for the coluns defined in the cols array. -# -# Usage: -# ./minMax.sh -# runs against the columns defined in the cols array below. -# ./minMaxCheck.sh all -# run for all CP columns in the database (will take a long time against a large database). -# ./minMaxCheck.sh schemaname -# run for CP columns in tables in the schema. If your schema is named all, you'll get all columns. -# ./minMaxCheck.sh schemaname tablename -# run for CP columns against the given table. -# ./minMaxCheck.sh schemaname tablename columnname -# run against the given column. -# -# The script does the following: -# 1) Runs editem for the column. -# 2) Clears the min/max for the column with editem -c. -# 3) Counts the column so that the min/max get set again. -# 4) Runs editem for the column again. -# 5) Diffs the two editem runs and reports / saves the sdiff log files for the column if any of extents had the min/max changed. -# -# Notes: -# 1) An info.log entry will be logged at the end of the script if none of the columns checked had a bad extent map entry. -# Example: -# Mar 11 14:11:29 srvqaperf8 oamcpp[9872]: 29.091980 |0|0|0| I 08 CAL0000: min-max-monitor: okay -# 2) Two warning.log entries will be logged at the end of the script if one or min/max EM entries were corrected. -# Example: -# Mar 11 14:16:36 srvqaperf8 oamcpp[16364]: 36.231731 |0|0|0| W 08 CAL0000: min-max-monitor: some values were reset for oids 3004 3005 -# Mar 11 14:16:36 srvqaperf8 oamcpp[16365]: 36.263270 |0|0|0| W 08 CAL0000: min-max-monitor: log files are /tmp/idb_mm_mon.sdiff.*.15190 -# 3) The script outputs the results of the selects in #3 above as it's going through the columns and will echo a line when it finds a col that was corrected. -# Example: -# **** Extent map min/max changed on the scan. See results in /tmp/idb_mm_mon.sdiff.3039.15190 - - -# Define the cols array. Here's a sql statement that will list the date and datetime cols in the expected format. -# idbmysql calpontsys -e "select concat(objectid, ':', \`schema\`, '.', tablename, '.', columnname) from syscolumn where datatype in (8, 11) and tablename not like 'temp%';" > www.txt -# -# NOTE: The objectid will be looked up again when it's going through the columns in case the one in the array becomes stale. -# - -if [ -z "$MYSQLCMD" ]; then - MYSQLCMD="/usr/local/Calpont/mysql/bin/mysql --defaults-file=/usr/local/Calpont/mysql/my.cnf -u root" -fi - -if [ -z "$INSTALLDIR" ]; then - INSTALLDIR="/usr/local/Calpont" -fi - -if [ -z "$PGMPATH" ]; then - PGMPATH=$INSTALLDIR/bin -fi - -cols=( -1339664:tpch1.orders.o_orderdate -1339718:tpch1.lineitem.l_shipdate -1339719:tpch1.lineitem.l_commitdate -1339720:tpch1.lineitem.l_receiptdate -1339759:dml.orders.o_orderdate -1339813:dml.lineitem.l_shipdate -1339814:dml.lineitem.l_commitdate -1339815:dml.lineitem.l_receiptdate -) - -# -# If called with "all", run the script against all of the column types that use CP. -# -if [ $# -eq 1 ] && [ "$1" == "all" ]; then - $MYSQLCMD --execute="select concat(objectid, ':', \`schema\`, '.', tablename, '.', columnname) from syscolumn where datatype not in (4, 10, 13) and not (datatype = 2 and columnlength > 8) and not (datatype = 12 and columnlength > 7);" calpontsys --skip-column-names > /tmp/idb_mm_mon.cols - cols=( $( cat /tmp/idb_mm_mon.cols ) ) - rm -f /tmp/idb_mm_mon.cols - -# -# Else if one parm passed, run against the columns in the given schema. -# -elif [ $# -eq 1 ]; then - db=$1 - $MYSQLCMD --execute="select concat(objectid, ':', \`schema\`, '.', tablename, '.', columnname) from syscolumn where datatype not in (4, 10, 13) and not (datatype = 2 and columnlength > 8) and not (datatype = 12 and columnlength > 7) and \`schema\` = '$db';" calpontsys --skip-column-names > /tmp/idb_mm_mon.cols - cols=( $( cat /tmp/idb_mm_mon.cols ) ) - rm -f /tmp/idb_mm_mon.cols - -# -# Else if two parms passed, run the script against all the columns that use CP for that table. -# -elif [ $# -eq 2 ]; then - db=$1 - tbl=$2 - $MYSQLCMD --execute="select concat(objectid, ':', \`schema\`, '.', tablename, '.', columnname) from syscolumn where datatype not in (4, 10, 13) and not (datatype = 2 and columnlength > 8) and not (datatype = 12 and columnlength > 7) and \`schema\` = '$db' and tablename = '$tbl';" calpontsys --skip-column-names > /tmp/idb_mm_mon.cols - cols=( $( cat /tmp/idb_mm_mon.cols ) ) - rm -f /tmp/idb_mm_mon.cols - -# -# Else if three parms passed, run the script against the column. -# -elif [ $# -eq 3 ]; then - db=$1 - tbl=$2 - col=$3 - $MYSQLCMD --execute="select concat(objectid, ':', \`schema\`, '.', tablename, '.', columnname) from syscolumn where \`schema\` = '$db' and tablename = '$tbl' and columnname='$col';" calpontsys --skip-column-names > /tmp/idb_mm_mon.cols - cols=( $( cat /tmp/idb_mm_mon.cols ) ) - rm -f /tmp/idb_mm_mon.cols -fi - -i=0 -j=0 - -if [ ${#cols[@]} -le 0 ]; then - $PGMPATH/cplogger -w 0 "min-max-monitor: no qualifying columns" "$badoidlist" - echo "min-max-monitor: no qualifying columns" "$badoidlist" - exit 1 -fi - -badoidlist= -while [ $i -lt ${#cols[@]} ]; do - let row=$i+1 - echo "" - echo "Evaluating $row of ${#cols[@]} at `date`. Col is ${cols[$i]}." - eval $(echo ${cols[$i]} | awk -F: '{printf "oid=%d\ntcn=%s\n", $1, $2}') - eval $(echo $tcn | awk -F. '{printf "schema=%s\ntable=%s\ncolumn=%s\n", $1, $2, $3}') - - # - # Look up the oid if the cols array is being used to keep from having to continually update the array if tables are dropped and recreated. - # - if [ $# -eq 0 ]; then - $MYSQLCMD --execute="select concat(objectid, ':', \`schema\`, '.', tablename, '.', columnname) from syscolumn where \`schema\` = '$schema' and tablename='$table' and columnname='$column';" calpontsys --skip-column-names > /tmp/idb_mm_mon.cols - results=`wc -l /tmp/idb_mm_mon.cols | awk '{print $1}'` - if [ $results -eq 0 ]; then - oid=0 - else - oid=`cat /tmp/idb_mm_mon.cols` - fi - fi - - $PGMPATH/editem -o$oid | awk '{print $1, $6, $8, $12}' >/tmp/idb_mm_mon.$oid.1.$$ - $PGMPATH/editem -c$oid - $MYSQLCMD --execute="select count($column) from $table" $schema -vvv - $PGMPATH/editem -o$oid | awk '{print $1, $6, $8, $12}' >/tmp/idb_mm_mon.$oid.2.$$ - sdiff /tmp/idb_mm_mon.$oid.1.$$ /tmp/idb_mm_mon.$oid.2.$$ --suppress-common-lines | grep -n -v invalid > /tmp/idb_mm_mon.sdiff.$oid.$$ - count=`wc -l /tmp/idb_mm_mon.sdiff.$oid.$$ | awk '{print $1}'` - if [ $count -ne 0 ]; then - badoidlist="$badoidlist $oid" - ((j++)) - echo "**** Extent map min/max changed on the scan. See results in /tmp/idb_mm_mon.sdiff.$oid.$$" - else - rm -f /tmp/idb_mm_mon.sdiff.$oid.$$ - fi - rm -f /tmp/idb_mm_mon.$oid.*.$$ - ((i++)) -done -echo "" -if [ $j -eq 0 ]; then - $PGMPATH/cplogger -i 0 "min-max-monitor: okay" - echo "min-max-monitor: okay" - echo "" - exit 0 -else - $PGMPATH/cplogger -w 0 "min-max-monitor: some values were reset for oids" "$badoidlist" - $PGMPATH/cplogger -w 0 "min-max-monitor: log files are /tmp/idb_mm_mon.sdiff.*.$$" - echo "min-max-monitor: some values were reset for oids" "$badoidlist" - echo "min-max-monitor: log files are /tmp/idb_mm_mon.sdiff.*.$$" - echo "" - exit 1 -fi - - diff --git a/oamapps/calpontSupport/resourceReport.sh b/oamapps/calpontSupport/resourceReport.sh deleted file mode 100755 index 7728c89d..00000000 --- a/oamapps/calpontSupport/resourceReport.sh +++ /dev/null @@ -1,74 +0,0 @@ -#! /bin/sh -# -# $Id: resourceReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "root" ]; then - SUDO=" " -else - SUDO="sudo" -fi - -$SUDO rm -f /tmp/${MODULE}_resourceReport.txt - -{ -echo " " -echo "******************** Resource Usage Report for ${MODULE} ********************" -echo " " - -echo " " -echo "-- Shared Memory --" -echo " " -echo "################# ipcs -l #################" -echo " " -$SUDO ipcs -l - -echo "################# $INSTALLDIR/bin/clearShm -n #################" -echo " " -$INSTALLDIR/bin/clearShm -n - -echo " " -echo "-- Disk Usage --" -echo " " -echo "################# df -k #################" -echo " " -$SUDO df -k - -echo " " -echo "-- Disk BRM Data files --" -echo " " -ls -l $INSTALLDIR/data1/systemFiles/dbrm 2> /dev/null -ls -l $INSTALLDIR/dbrm 2> /dev/null - -echo "################# cat $INSTALLDIR/data1/systemFiles/dbrm/BRM_saves_current #################" -echo " " -cat $INSTALLDIR/data1/systemFiles/dbrm/BRM_saves_current 2> /dev/null - -echo " " -echo "-- View Table Locks --" -echo " " -echo "################# cat bin/viewtablelock #################" -echo " " -$INSTALLDIR/bin/viewtablelock 2> /dev/null - -echo " " -echo "-- BRM Extent Map --" -echo " " -echo "################# bin/editem -i #################" -echo " " -$INSTALLDIR/bin/editem -i 2>/dev/null - -} > /tmp/${MODULE}_resourceReport.txt - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/softwareReport.sh b/oamapps/calpontSupport/softwareReport.sh deleted file mode 100755 index f043552a..00000000 --- a/oamapps/calpontSupport/softwareReport.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/bin/bash -# -# $Id: hardwareReport.sh 421 2007-04-05 15:46:55Z dhill $ -# -if [ $1 ] ; then - MODULE=$1 -else - MODULE="pm1" -fi - -if [ $2 ] ; then - INSTALLDIR=$2 -else - INSTALLDIR="/usr/local/Calpont" -fi - -if [ $USER = "root" ]; then - SUDO=" " -else - SUDO="sudo" -fi - -$SUDO rm -f /tmp/${MODULE}_softwareReport.txt - -{ -echo " " -echo "******************** Software Report for ${MODULE} ********************" -echo " " - -echo " " -echo "-- Calpont Package Details --" -echo " " -echo "################# calpontConsole getcalpontsoftwareinfo #################" -echo " " -$INSTALLDIR/bin/calpontConsole getcalpontsoftwareinfo - -echo " " -echo "-- Calpont Release Number file --" -echo " " -echo "################# cat $INSTALLDIR/releasenum #################" -echo " " -cat $INSTALLDIR/releasenum - -echo " " -echo "-- Calpont Storage Configuration --" -echo " " -echo "################# calpontConsole getStorageConfig #################" -echo " " -$INSTALLDIR/bin/calpontConsole getStorageConfig - -} > /tmp/${MODULE}_softwareReport.txt - -exit 0 \ No newline at end of file diff --git a/oamapps/calpontSupport/sqlLogs.sh b/oamapps/calpontSupport/sqlLogs.sh deleted file mode 100755 index fc867dea..00000000 --- a/oamapps/calpontSupport/sqlLogs.sh +++ /dev/null @@ -1,225 +0,0 @@ -#!/bin/bash - -# -# Script that does analysis on SQL statements from an InfiniDB debug log. -# -DB=idb_idb_sqllogs -TABLE=statements - -if [ -z "$INFINIDB_INSTALL_DIR" ]; then - INFINIDB_INSTALL_DIR=/usr/local/Calpont -fi - -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR - -if [ $INFINIDB_INSTALL_DIR != "/usr/local/Calpont" ]; then - export PATH=$INFINIDB_INSTALL_DIR/bin:$INFINIDB_INSTALL_DIR/mysql/bin:/bin:/usr/bin - export LD_LIBRARY_PATH=$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql -fi - - -if [ -z "$MYSQLCMD" ]; then - MYSQLCMD="$INFINIDB_INSTALL_DIR/mysql/bin/mysql --defaults-file=$INFINIDB_INSTALL_DIR/mysql/my.cnf -u root" - export MYSQLCMD -fi - -main() -{ - if [ "$option" == "usage" ]; then - usage - exit - elif [ "$option" == "create" ]; then - if [ -f $logFile ]; then - create - else - echo "" - usage - echo "" - echo "*** $logFile not found. Pleae specify a valid debug log file.***" - echo "" - exit - fi - elif [ "$option" == "list" ]; then - list - elif [ "$option" == "listAll" ]; then - listAll - elif [ "$option" == "active" ]; then - listActive - elif [ "$option" == "activeAll" ]; then - listActiveAll - else - echo "" - usage - echo "*** $option is not a valid option. ***" - echo "" - exit - fi - -} - -usage () -{ - echo " - This script can be used to analyze select statements from an InfiniDB debug log. - - Usage: - - ./sqlLogs.sh create [debug log file name - default:debug.log] - Creates an $DB.$TABLE table with the select statements from the debug log. Must be run before other options can be used. - - ./sqlLogs.sh list - Lists the SQL statements and run times showing the following: - id - statement id in sequential order based on the start time - starttime - start time of the statement - endtime - end time of the statement - runtime - total run time of the statement - sessionid - the MySQL session id for the statement - sessionstatementid - the sequence of the statement within the session - - ./sqlLogs.sh listAll - Same as list with the addition of the SQL statement. - - ./sqlLogs.sh active timestamp - Example: ./sqlLogs.sh active 00:35:50.291408 - Lists the id, starttime, endtime, runtime, timeActive, sessionid, and sessionstatementid for the sql statements - that were active at the given timestamp. - - ./sqlLogs.sh activeAll timestamp - Same as listActive with the addition of the SQL statement. - " - -} - -create () -{ - echo "" - echo "Step 1 of 4. Building import file with Start SQL log entries." - grep "Start SQL" $logFile | grep -v syscolumn | grep -v systable | awk -F '|' '{print NR "|" substr($1,8,6) substr($1,length($1)-9,9) "|" $2 "|" $5}' | - sort -t '|' -n -k 3 -k 1 | - awk -F '|' ' - { - if(NR == 1) - { - prevSession=$3; - val=1; - } - else if(prevSession == $3) - val++; - else - { - val=1; - prevSession=$3; - } - print $0 "|" val "|" - }' | sort -t '|' -n -k 1 > /tmp/idbtmp.tbl - - echo "Step 2 of 4. Populating $DB.start table with Start SQL log entries." - sql=" - create database if not exists $DB; - use $DB; - drop table if exists start; - CREATE TABLE start ( - id int, - time char(20), - sessionid int, - statement varchar(8000), - sessionStatementId int - ) ENGINE=MyISAM ; - create index start_idx on start (sessionid, sessionStatementId); - load data infile '/tmp/idbtmp.tbl' into table start fields terminated by '|'; - " - $MYSQLCMD -e "$sql" - - echo "Step 3 of 4. Building import file with End SQL log entries." - grep "End SQL" $logFile | grep -v "2147483" | awk -F '|' '{print NR "|" substr($1,8,6) substr($1,length($1)-9,9) "|" $2}' | - sort -t '|' -n -k 3 -k 1 | - awk -F '|' ' - { - if(NR == 1) - { - prevSession=$3; - val=1; - } - else if(prevSession == $3) - val++; - else - { - val=1; - prevSession=$3; - } - print $0 "|" val "|" - }' | sort -t '|' -n -k 1 > /tmp/idbtmp.tbl - - echo "Step 4 of 4. Populating $DB.stop table with End SQL log entries." - sql=" - drop table if exists stop; - CREATE TABLE stop ( - id int, - time char(20), - sessionid int, - sessionStatementId int - ) ENGINE=MyISAM ; - create index stop_idx on stop (sessionid, sessionStatementId); - load data infile '/tmp/idbtmp.tbl' into table stop fields terminated by '|'; - " - $MYSQLCMD $DB -e "$sql;" - - echo "Step 5 of 5. Populating $DB.$TABLE table." - sql=" - drop table if exists $TABLE; - create table $TABLE as - (select - a.id id, a.time starttime, b.time endtime, substr(timediff(b.time, a.time), 1, 30) runTime, a.sessionid sessionId, a.sessionstatementid sessionStatementId, a.statement statement - from start a left join stop b - on a.sessionid = b.sessionid and a.sessionstatementid = b.sessionstatementid); - " - $MYSQLCMD $DB -e "$sql" - - echo "All done." - echo "" -} - -list() { - sql="select id, starttime, endtime, runtime, sessionid, sessionstatementid from statements;" - $MYSQLCMD $DB -vvv -e "$sql" -} - -listAll() -{ - sql="select id, starttime, endtime, runtime, sessionid, sessionstatementid, trim(statement) statement from statements;" - $MYSQLCMD $DB -vvv -e "$sql" -} - -listActive() -{ - dtm=$parm2 - sql=" - select id, starttime, endtime, runtime, timediff('$dtm', starttime) timeActive, sessionid, sessionstatementid from statements - where starttime <= '$dtm' and (endtime is null or endtime > '$dtm'); - " - $MYSQLCMD $DB -vvv -e "$sql" -} - -listActiveAll() -{ - dtm=$parm2 - sql=" - select id, starttime, endtime, runtime, timediff('$dtm', starttime) timeActive, sessionid, sessionstatementid, trim(statement) statement from statements - where starttime <= '$dtm' and (endtime is null or endtime > '$dtm'); - " - $MYSQLCMD $DB -vvv -e "$sql" -} - -if [ $# -lt 1 ]; then - usage - exit -else - option=$1 - parm2=$2 - logFile=debug.log - if [ $# -ge 2 ]; then - logFile=$2 - fi -fi - -main diff --git a/oamapps/hardwareMonitor/hardwareMonitor.cpp b/oamapps/hardwareMonitor/hardwareMonitor.cpp index 2ff78d7b..474f0a71 100644 --- a/oamapps/hardwareMonitor/hardwareMonitor.cpp +++ b/oamapps/hardwareMonitor/hardwareMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: hardwareMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/hardwareMonitor/hardwareMonitor.h b/oamapps/hardwareMonitor/hardwareMonitor.h index 69e05bfa..04834638 100644 --- a/oamapps/hardwareMonitor/hardwareMonitor.h +++ b/oamapps/hardwareMonitor/hardwareMonitor.h @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: hardwareMonitor.h 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/logUtils/Makefile.am b/oamapps/logUtils/Makefile.am new file mode 100644 index 00000000..9e5c5b8f --- /dev/null +++ b/oamapps/logUtils/Makefile.am @@ -0,0 +1,12 @@ +dist_bin_SCRIPTS = dbprof.pl + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: install-data-am + diff --git a/oamapps/logUtils/dbprof.pl b/oamapps/logUtils/dbprof.pl new file mode 100755 index 00000000..e4421c53 --- /dev/null +++ b/oamapps/logUtils/dbprof.pl @@ -0,0 +1,2066 @@ +#!/usr/bin/env perl +# +#------------------------------------------------------------------------------- +# +# $Id$ +# +# Copyright (C) 2009-2012 Calpont Corporation +# All rights reserved +# +#------------------------------------------------------------------------------- +# +# Purpose: +# This script takes a syslog file as input (from STDIN), and extracts +# and formats the information from message types 26-32 into a report +# (written to STDOUT). These message types contain the information +# necessary to report the elapsed time and block I/O counts for the +# job steps associated with each SQL statement found in the syslog. +# The resulting report thus provides profile information regarding +# the performance of the calpont database. +# +# The script parses these log messages, and collects the data into a set +# of hash tables. When all the job steps for a statement are completed, +# the script will calculate and report elapsed times, and I/O block counts +# (per object), for each of these steps. +# +# Usage: +# dbprof [-h] [-s sessionId] [-d] logfile +# -h displays this help message +# -s id of session to be extracted from syslog file +# -d enables debug mode +# logfile name of log file to be read +# +# Supported Message Types: +# +# Message Message Description and Format +# Type (as defined in MessageFile.txt +# ------- ------------------------------ +# 26 Start Transaction +# 27 End Transaction: xxx +# 28 Start Statement: Statement-999 Ver-999 SQL-yyy +# 29 End Statement: Statement-999 +# 30 Start Step: Statement-999 StepId-999 StepName-zzz +# 31 End Step: Statement-999 StepId-999 +# BlockedFifoIn-999 BlockedFifoOut-999 +# MsgBytesIn-999 MsgBytesOut-999 +# 32 I/O: Statement-999 StepId-999 ObjectId-999 +# PhyRead-999 CacheRead-999 CPBlks-999 +# 46 ProcessingTimesi: Statement-999 StepId-999 +# FirstRead-hh:mm:ss.xxxxxx LastRead-hh:mm:ss.xxxxxx +# FirstWrite-hh:mm:ss.xxxxxx LastWrite-hh:mm:ss.xxxxxx +# 47 Summary: Statement-999 MaxMemPct-99 TempFileCnt-999 +# TempFileSpace-999 PhysRead-999 CacheRead-999 +# MsgsRcvd-999 MsgBytesIn-999 MsgBytesOut-999 +# CPBlks-999 +# +# Where: +# 999 represents numeric field values. +# xxx in message 27 is "COMMIT" or "ROLLBACK". +# xxx in message 28 is the actual SQL statement. +# zzz in message 30 is a short descriptive title for the step. +# +# WARNING: +# This script is very dependent on the format and content of the syslog +# file, and more specifically, the messages being parsed. If any changes +# should be made to the format of the message body for the pertinent +# messages, or to some other part of the log entries (such as to the date +# format), then this script may be affected. +# +# TBD: +# As time allows, it would be helpful to add a utility that could be +# called, to convert the object id (from the syslog) to an object +# name. We could then display the object name in the report in addition +# to, or instead of, the object id. +# +#------------------------------------------------------------------------------- +use warnings; +use strict; + +use POSIX; +use Text::Wrap; +use Time::Local; + +#------------------------------------------------------------------------------- +# Global constants +#------------------------------------------------------------------------------- +my $LOG_MSG_NUM_START_TRANS = 26; # Start Transaction message type +my $LOG_MSG_NUM_END_TRANS = 27; # End Transaction message type +my $LOG_MSG_NUM_START_STATEMENT = 28; # Start Statement message type +my $LOG_MSG_NUM_END_STATEMENT = 29; # End Statement message type +my $LOG_MSG_NUM_START_STEP = 30; # Start Step message type +my $LOG_MSG_NUM_STOP_STEP = 31; # End Step message type +my $LOG_MSG_NUM_IO_COUNT = 32; # Object Read I/O message type +my $LOG_MSG_NUM_PROC_TIMES = 46; # Step Processing Times msg type +my $LOG_MSG_NUM_STATEMENT_SUM = 47; # Statement Summary message type +my $KEY_CONCATENATE_CHAR = "_"; # character used in concatenating + # host/session hash key string +my $SQL_LINE_LENGTH =120; # maximum SQL wrap line length +my $NUM_OBJECTS_TO_REPORT = 2; # number of objects to report per step +my $NUM_OBJECTS_TO_RPT_PER_LINE = 1; # number of objects to report per line +my $SESSION_ID_WILDCARD = -1; # indicates to include all session ids +my $EMPTY_STRING = "-"; # used to denote empty string + +my %MON_ALPHA_TO_NUM = (Jan => 0, + Feb => 1, + Mar => 2, + Apr => 3, + May => 4, + Jun => 5, + Jul => 6, + Aug => 7, + Sep => 8, + Oct => 9, + Nov =>10, + Dec =>11); + +#------------------------------------------------------------------------------- +# Global variable declarations +#------------------------------------------------------------------------------- +my $debugFlag = 0; # debug flag taken from command line +my $sessionToExtract = $SESSION_ID_WILDCARD; # id of session to be extracted +my $timeStampYear; # year used in time stamps, see + # getCurrentYear() +my $logFileName = ""; # name of log file to be read + +# Global variables used to store contents parsed from the latest syslog +# record. Went ahead and made these global to avoid having to pass around +# among several subroutines. +my $current_logRecord; # current log record read from +my $current_monAlpha; # current log month (3 char abbreviation) +my $current_mday; # current log month (from 0 to 11) +my $current_hh; # current log hour +my $current_mm; # current log minute +my $current_ss; # current log second +my $current_host; # current log hostname +my $current_subSysName; # current log subSystem name +my $current_pid; # current log pid +my $current_decSec; # current log decimal seconds +my $current_field6_1; # current log session +my $current_field6_2; # current log transaction +my $current_field6_3; # current log thread +my $current_severityLvl; # current log severity level +my $current_subSysId; # current log subSystem id +my $current_msgNum; # current log msg number (w/o CAL prefix) +my $current_msgBody; # current log message text body + +#------------------------------------------------------------------------------- +# Description of hash tables starting with %sessionHashTable. +# +# %sessionHashTable is a hash table of records, where each record carries +# the latest high level data for a host/session. The session records are +# defined as follows: +# +# sessionRecord = # Key is concatenated host and session strings +# { +# hostName # host server +# sessionId # session id +# transactionId # current transaction id +# statementId # current SQL statement id +# versionId # current DBRM version id +# sqlStatement # SQL statement associated with this statementId +# startTimeString # formatted version of startTime + startDecSec +# endTimeString # formatted version of endTime + endDecSec +# startDecSec # decimal seconds associated with startTime +# stepTable # table of current active job steps +# maxMemPct # peak memory usage for ExeMgr during this query +# totalTempFileCnt # number of temp files created during this query +# totalTempFileSpace # temp file disk space (in bytes) for this query +# totalPhysRead # total no. of physcal blk reads (from db) for this query +# totalCacheRead # total no. of cache blk reads (from db) for this query +# totalMsgsRcvd # total no. of msgs received from primproc for this query +# totalMsgBytesIn # total no. of bytes in incoming messages +# totalMsgBytesOut # total no. of bytes in outgoing messages +# totalCPBlks # total no. of blocks skipped due to casual partitioning +# } || +# || +# \/ +# where stepTable is a hash table that carries a list of step records +# pertaining to a list of job steps for a session. The stepTable records +# are defined as follows: +# +# stepTableRecord = # Key is stepId taken from syslog message +# { +# stepName # name or description of a step +# subSystem # name of subSystem performing the step (always ExeMgr) +# startTime # time when step started to execute (seconds) +# startDecSec # decimal seconds associated with startTime +# endTime # time when step completed execution (seconds) +# endDecSec # decimal seconds associated with endTime +# effStartTime # effective time when step starts processing input (secs) +# effStartDecSec # decimal seconds associated with effStartTime +# effEndTime # effective time when step stops processing output (secs) +# effEndDecSec # decimal seconds associated with effEndTime +# blockedFifoIn # number of FIFO read operations that blocked +# blockedFifoOut # number of FIFO write operations that blocked +# msgBytesIn # number of bytes in incoming messages +# msgBytesOut # number of bytes in outgoing messages +# isStepOpen # boolean flag indicating whether step is completed +# objectTable # table of objects related to this step +# } || +# || +# \/ +# where objectTable is a hash table carrying a list of object records +# pertaining to the objects relevant to a given step. The objectTable +# records are defined as follows: +# +# objectTableRecord =# Key is objectId taken from syslog message +# { +# physicalRead # number of blocks physically read from disk for this obj +# cacheRead # number of blocks logically read from cache for this obj +# cpBlks # number of blocks skipped due to casual partitioning +# } +# +#------------------------------------------------------------------------------- +my %sessionHashTable; + +#------------------------------------------------------------------------------- +# Print command line usage +# +# input arguments: none +# return value(s) : none +#------------------------------------------------------------------------------- +sub usage +{ + die "$0: [-h] [-s sessionId] [-d] logfile\n" . + " -h displays this help message\n" . + " -s id of session to be extracted from syslog file\n" . + " -d enables debug mode\n" . + " logFile name of log file to be read\n"; +} + +#------------------------------------------------------------------------------- +# Parse command line arguments +# +# input arguments: none +# return value(s) : none +#------------------------------------------------------------------------------- +sub parseCmdLineArgs +{ + my $argc = @ARGV; + + foreach (my $i=0; $i<$argc; $i+=1) + { + if ( $ARGV[$i] eq "-h" ) + { + usage(); + } + elsif ( $ARGV[$i] eq "-s" ) + { + $i+=1; + $sessionToExtract = $ARGV[$i]; + } + elsif ( $ARGV[$i] eq "-d" ) + { + $debugFlag = 1; + } + elsif ( ($i+1) == $argc ) + { + $logFileName = $ARGV[$i]; + } + } + + if ( $logFileName eq "" ) + { + print STDERR "\nname of log file must be provided on command line\n\n"; + usage(); + } + if ( $debugFlag == 1 ) + { + print STDERR "Running in debug mode...\n"; + } + if ( $sessionToExtract != $SESSION_ID_WILDCARD ) + { + print STDERR "Limiting report to sessionId ", $sessionToExtract, "\n"; + } +} + +#------------------------------------------------------------------------------- +# Determine current year so that we have a year to use in constructing +# time stamps. The year is not present in the input log file. +# We will assume it is the current year. It doesn't make that much +# difference what year we use, because we are only using it to create +# the time stamps we use in calculating elapsed times. But we'll use +# the current year to try to be correct. +# +# input arguments: none +# return value(s) : string representing current year +#------------------------------------------------------------------------------- +sub getCurrentYear +{ + my ($currSec, $currMin, $currHour, + $currMday,$currMon, $currYear, + $currWday,$currWyr, $currDst) = localtime(); + + return $currYear; +} + +#------------------------------------------------------------------------------- +# Create a time stamp (in seconds) using the date/time associated with the +# current log record. Decimal seconds field from the log record is incorporated +# into the time stamp. +# +# input arguments: none +# return value(s) : returns time stamp (in seconds) taken from the latest +# log record we have read. +#------------------------------------------------------------------------------- +sub createCurrentTimeStamp +{ + my $monNum = $MON_ALPHA_TO_NUM{$current_monAlpha}; + my $timeStamp = timelocal($current_ss, + $current_mm, + $current_hh, + $current_mday, + $monNum, + $timeStampYear); + + # If the decimal seconds field does not match the initial date/time stamp + # of the log record, we overwrite the seconds portion of the date/time stamp. + # Before doing that we first see if a minute wrap-around has occurred, in + # which case we first subtract 60 seconds before substituting the seconds + # from the decimal seconds field into the time stamp. + my ($wholeDecSec,$fracDecSec) = ($current_decSec =~ /([\d]+)\.([\d\D]+)/); + if ($current_ss != $wholeDecSec) + { + if (($current_ss < 5) && ($wholeDecSec > 55)) + { + $timeStamp = $timeStamp - 60; + } + $timeStamp = $timeStamp - $current_ss + $wholeDecSec; + } + + return $timeStamp; +} + +#------------------------------------------------------------------------------- +# Given a start date/time stamp and accompanying decimal seconds, and +# a second end date/time stamp and accompanying decimal seconds, this +# subroutine will return the difference between the 2 times. Subroutine +# assumes the decimal seconds is a string carrying 6 digits of precision, +# with leading zeros. +# +# input arguments: starting time (seconds), +# starting time (decimal seconds), +# end time (seconds), +# end time (decimal seconds) +# return value(s) : delta seconds and delta decimal seconds +#------------------------------------------------------------------------------- +sub deltaTwoTimes +{ + my ($startTime, $startDecSec, $endTime, $endDecSec) = @_; + + my $deltaTime = $endTime - $startTime; + my $deltaDecSec = $endDecSec - $startDecSec; + + if ($deltaDecSec < 0) + { + $deltaTime -= 1; + $deltaDecSec += 1000000; + } + + # + # Round off decimal seconds to 3 digits + # + my $deltaDecSecTruncated = int( $deltaDecSec / 1000 ); + my $deltaDecSecRounded = int( ($deltaDecSec + 500) / 1000); + if ( $deltaDecSecRounded == 1000 ) + { + $deltaDecSecRounded = 0; + $deltaTime += 1; + } + $deltaDecSec = $deltaDecSecRounded; + + return ($deltaTime, $deltaDecSec); +} + +#------------------------------------------------------------------------------- +# Format a time interval in seconds, into an equivalent time interval as +# an hh:mm:ss string. +# +# input arguments: time interval in seconds +# return value(s) : string formatted as "hh:mm:ss" +#------------------------------------------------------------------------------- +sub formatTimeInterval +{ + my ($timeInterval) = @_; + + my $hr = 0; + my $min = 0; + my $sec = 0; + + if ( $timeInterval > 0 ) + { + $hr = int ($timeInterval / 3600); + $timeInterval = $timeInterval - ($hr * 3600); + if ($timeInterval > 0) + { + $min = int ($timeInterval / 60); + $sec = $timeInterval - ($min * 60); + } + } + + return ( sprintf("%02d:%02d:%02d", $hr, $min, $sec) ); +} + +#------------------------------------------------------------------------------- +# Dump contents of our session hash table. +# +# input arguments: none +# return value(s) : none +#------------------------------------------------------------------------------- +sub dumpSessionHashTable +{ + my $sessionHashKey; + my $stepHashKey; + my $objectHashKey; + + print STDERR "Dump of Session Hash Table...\n"; + + # + # Loop through collection of sessions + # + for $sessionHashKey ( sort keys %sessionHashTable ) + { + if ( $sessionHashTable{$sessionHashKey}->{statementId} == -1 ) + { + print STDERR + "Host: " , $sessionHashTable{$sessionHashKey}->{hostName} , "; ", + "Session: " , $sessionHashTable{$sessionHashKey}->{sessionId}, "; ", + "\n" , + " No active statements for this host/session..." , + "\n"; + } + else + { + print STDERR + "Host: " , $sessionHashTable{$sessionHashKey}->{hostName} , "; ", + "Session: " , $sessionHashTable{$sessionHashKey}->{sessionId}, "; ", + "Transaction: " , $sessionHashTable{$sessionHashKey}->{transactionId}; + + print STDERR + "; StatementId: " , $sessionHashTable{$sessionHashKey}->{statementId}, + "; StartTime: " , $sessionHashTable{$sessionHashKey}->{startTimeString}, + "; StartDecSec: " , $sessionHashTable{$sessionHashKey}->{startDecSec}, + "\n"; + + print STDERR + "MaxMemPct: " , $sessionHashTable{$sessionHashKey}->{maxMemPct}, "; ", + "TotalTempFileCnt: ", + $sessionHashTable{$sessionHashKey}->{totalTempFileCnt}, "; ", + "TotalTempFileSpace: ", + $sessionHashTable{$sessionHashKey}->{totalTempFileSpace}, + "\n", + "TotalPhysRead: ", + $sessionHashTable{$sessionHashKey}->{totalPhysRead}, "; ", + "TotalCacheRead:", + $sessionHashTable{$sessionHashKey}->{totalCacheRead}, "; ", + "TotalCPBlocks:", + $sessionHashTable{$sessionHashKey}->{totalCPBlks}, "; ", + "TotalMsgsRcvd:", + $sessionHashTable{$sessionHashKey}->{totalMsgsRcvd}, + "\n"; + + my $stepHashTable = $sessionHashTable{$sessionHashKey}->{stepTable}; + print STDERR " Number of job steps: "; + print STDERR scalar( keys %$stepHashTable ); + print STDERR "\n"; + + # + # Loop through collection of steps for each session + # + for $stepHashKey ( sort { $a <=> $b } keys %$stepHashTable ) + { + my $jobStep = $stepHashTable->{$stepHashKey}; + my $formattedTime = asctime( localtime($jobStep->{startTime}) ); + chomp ( $formattedTime ); + print STDERR + " Id: " , $stepHashKey , + "; Name: " , $jobStep->{stepName} , + "; SubSystem: " , $jobStep->{subSystem} , + "; StartTime: " , $formattedTime , + "; StartDecSec: " , $jobStep->{startDecSec} , + "; IsStepOpen: " , $jobStep->{isStepOpen} , + "; BlockedFifoIn: " , $jobStep->{blockedFifoIn} , + "; BlockedFifoOut: ", $jobStep->{blockedFifoOut}, + "; MsgBytesIn: " , $jobStep->{msgBytesIn}, + "; MsgBytesOut: " , $jobStep->{msgBytesOut}, + "\n"; + + my $objectHashTable = $jobStep->{objectTable}; + print STDERR " Number of objects: "; + print STDERR scalar( keys %$objectHashTable ); + print STDERR "\n"; + + # + # Loop through collection of objects for each job step + # + for $objectHashKey ( keys %$objectHashTable ) + { + my $object = $objectHashTable->{$objectHashKey}; + print STDERR + " Id: " , $objectHashKey , + "; PhysicalRead: " , $object->{physicalRead} , + "; CacheRead: " , $object->{cacheRead} , + "; CPBlks: " , $object->{cpBlks} , + "\n"; + } + } + } + + print STDERR "\n"; + } +} + +#------------------------------------------------------------------------------- +# Print a SQL statement to STDOUT that is formatted or broken up into +# substrings, with each substring less than a given maximum line length +# ($SQL_LINE_LENGTH). +# +# input arguments: SQL statement +# return value(s) : none +#------------------------------------------------------------------------------- +sub printFormattedSql +{ + my ($sql) = @_; + + $Text::Wrap::columns = $SQL_LINE_LENGTH; + + print wrap ( " ", " ", ($sql) ); + print "\n"; +} + +#------------------------------------------------------------------------------- +# Print header info for the subsequent SQL statement in the output report. +# +# input arguments: $sessionRecord we are going to be writing out to report +# return value(s) : none +#------------------------------------------------------------------------------- +sub printStatementHeaders +{ + my ($sessionRecord) = @_; + + my $hostName = $sessionRecord->{hostName}; + my $sessionId = $sessionRecord->{sessionId}; + my $transactionId = $sessionRecord->{transactionId}; + my $sqlStatement = $sessionRecord->{sqlStatement}; + my $statementId = $sessionRecord->{statementId}; + my $startTimeString = $sessionRecord->{startTimeString}; + my $endTimeString = $sessionRecord->{endTimeString}; + my $versionId = $sessionRecord->{versionId}; + + # + # Record "Start Statement" to our output report + # + print "****************************************" , + "****************************************\n"; + print "Host: $hostName SessionID: $sessionId " , + "TransactionID: $transactionId" , + "\n\n"; + + printFormattedSql ( $sqlStatement ); + + print " \n" , + " StatementID: $statementId StartTime: $startTimeString " , + "EndTime: $endTimeString VersionID: $versionId\n" , + "\n\n"; + + # + # Print line 1 of column header + # + print " Step Step ", + "Start Elapsed ", + "Effective Effective Blocked Blocked ", + "Input Output "; + for (my $i=0; $i<$NUM_OBJECTS_TO_RPT_PER_LINE; $i++) + { + print " Object Physical Cache CasualPart"; + } + print "\n"; + + # + # Print line 2 of column header + # + print " ID Name ", + "Time Time ", + "Start Time Elapsed Time FifoIn FifoOut ", + "Msg KB Msg KB "; + for (my $i=0; $i<$NUM_OBJECTS_TO_RPT_PER_LINE; $i++) + { + print " ID Read Read Blocks "; + } + print "\n"; + + # + # Print line 3 of column header + # + print " ---- -------------------- ", + "--------------- ------------ ", + "------------ ------------ ------- ------- ", + "---------- ----------"; + for (my $i=0; $i<$NUM_OBJECTS_TO_RPT_PER_LINE; $i++) + { + print " ------ ---------- ---------- ----------"; + } + print "\n"; +} + +#------------------------------------------------------------------------------- +# Print trailer info for the recent SQL statement in the output report. +# +# input arguments: $sessionRecord we are writing out to report +# return value(s) : none +#------------------------------------------------------------------------------- +sub printStatementTrailers +{ + my ($sessionRecord) = @_; + + my $maxMemPct = $sessionRecord->{maxMemPct}; + my $totalTempFileCnt = $sessionRecord->{totalTempFileCnt}; + my $totalTempFileSpace = $sessionRecord->{totalTempFileSpace}; + my $totalPhysRead = $sessionRecord->{totalPhysRead}; + my $totalCacheRead = $sessionRecord->{totalCacheRead}; + my $totalMsgsRcvd = $sessionRecord->{totalMsgsRcvd}; + my $totalMsgBytesIn = $sessionRecord->{totalMsgBytesIn}; + my $totalMsgBytesOut = $sessionRecord->{totalMsgBytesOut}; + my $totalCPBlks = $sessionRecord->{totalCPBlks}; + + # round off to nearest MB for the purpose of the report + my $totalTempFileSpaceMB = 0; + my $totalMsgBytesInMB = 0; + my $totalMsgBytesOutMB = 0; + if ($totalTempFileSpace >= 500000) + { + $totalTempFileSpaceMB = int (($totalTempFileSpace+500000) / 1000000); + } + if ($totalMsgBytesIn >= 500000) + { + $totalMsgBytesInMB = int (($totalMsgBytesIn+500000) / 1000000); + } + if ($totalMsgBytesOut >= 500000) + { + $totalMsgBytesOutMB = int (($totalMsgBytesOut+500000) / 1000000); + } + + print " Max Memory Percentage Use for ExeMgr: $maxMemPct %\n"; + print " Totals for this query:\n", + " TotalTempFileCnt: " , $totalTempFileCnt, + "; TotalTempFileSpace: " , $totalTempFileSpaceMB, "MB\n", + " TotalPhysRead(blocks): " , $totalPhysRead, + "; TotalCacheRead(blocks): " , $totalCacheRead, + "; TotalCPBlks(blocks): " , $totalCPBlks, + "; TotalMsgsReceived: " , $totalMsgsRcvd, "\n", + " TotalMsgBytesIn: " , $totalMsgBytesInMB, "MB", + "; TotalMsgBytesOut: " , $totalMsgBytesOutMB, "MB", + "\n\n"; +} + +#------------------------------------------------------------------------------- +# Close and report the stats for all the job steps listed in the stepHashTable +# for the specified sessionRecord and corresponding statement. +# +# input arguments: $sessionRecord having %stepHashTable with steps to be closed +# return value(s) : 0 - no steps forced to end +# >0 - number of open steps that had to be closed +#------------------------------------------------------------------------------- +sub printAndEndAllSteps +{ + my ($sessionRecord) = @_; + + my $hostName = $sessionRecord->{hostName}; + my $sessionId = $sessionRecord->{sessionId}; + my $statementId = $sessionRecord->{statementId}; + my $stepHashTable = $sessionRecord->{stepTable}; + + my $stepHashKey; + my $stillOpenStepCount = 0; + my $stepCount = scalar( keys %$stepHashTable ); + + if ($sessionRecord->{sqlStatement} ne $EMPTY_STRING) + { + printStatementHeaders ($sessionRecord); + + if ( $stepCount > 0 ) + { + if ($debugFlag == 1) + { + print STDERR "At log record ", $., + ", $stepCount steps reported as complete for ", + "host-$hostName; session-$sessionId; " , + "statement-$statementId\n"; + } + + my $endTimeStamp = createCurrentTimeStamp(); + my ($endDecSec) = ($current_decSec =~ /\d+\.([\d\D]+)/); + + # + # Loop through the steps, sorted numerically by step id + # + for $stepHashKey ( sort { $a <=> $b } keys %$stepHashTable ) + { + my $jobStep = $stepHashTable->{$stepHashKey}; + + # + # Format the start times for the report + # + my $formattedTime = asctime( localtime($jobStep->{startTime}) ); + chomp ( $formattedTime ); + my ($formattedStartTimeOnly) = + ($formattedTime =~ /\w+\s+\d+\s+([\d:]+)/); + + my $effFormattedTime = asctime( localtime($jobStep->{effStartTime}) ); + chomp ( $effFormattedTime ); + my ($effFormattedStartTimeOnly) = + ($effFormattedTime =~ /\w+\s+\d+\s+([\d:]+)/); + + # + # Use EndStatement time for EndStep time, "if" we did not encounter an + # EndStep log record. + # + if ($jobStep->{endTime} == 0) + { + $jobStep->{endTime} = $endTimeStamp; + #jobStep->{endDecSec} = $endDecSec; + } + if ($jobStep->{effEndTime} == 0) + { + $jobStep->{effEndTime} = $endTimeStamp; + #jobStep->{effEndDecSec} = $endDecSec; + } + + # + # Calculate the elapsed times for this step + # + my ($elapsedTimeSec, $elapsedTimeDecSec) = + deltaTwoTimes( $jobStep->{startTime}, + $jobStep->{startDecSec}, + $jobStep->{endTime}, + $jobStep->{endDecSec} ); + my $formattedElapsedTime = formatTimeInterval ( $elapsedTimeSec ); + + my ($effElapsedTimeSec, $effElapsedTimeDecSec) = + deltaTwoTimes( $jobStep->{effStartTime}, + $jobStep->{effStartDecSec}, + $jobStep->{effEndTime}, + $jobStep->{effEndDecSec} ); + my $effFormattedElapsedTime = formatTimeInterval ( $effElapsedTimeSec ); + + # + # Add up the number of steps that are still open + # + if ($jobStep->{isStepOpen} == 1) + { + $stillOpenStepCount += 1; + } + + # round off msg byte counts to nearest KB for the purpose of the report + my $msgBytesInKB = 0; + my $msgBytesOutKB = 0; + if ($jobStep->{msgBytesIn} >= 500) + { + $msgBytesInKB = int (($jobStep->{msgBytesIn} +500) / 1000); + } + if ($jobStep->{msgBytesOut} >= 500) + { + $msgBytesOutKB = int (($jobStep->{msgBytesOut}+500) / 1000); + } + + # + # print the performance statistics for this step + # + printf " %04s %-20s %8s.%06d %8s.%03d %8s.%03d %8s.%03d" . + " %7d %7d %10d %10d", + $stepHashKey, + $jobStep->{stepName}, + $formattedStartTimeOnly, + $jobStep->{startDecSec}, + $formattedElapsedTime, + $elapsedTimeDecSec, + $effFormattedStartTimeOnly, + $jobStep->{effStartDecSec}, + $effFormattedElapsedTime, + $effElapsedTimeDecSec, + $jobStep->{blockedFifoIn}, + $jobStep->{blockedFifoOut}, + $msgBytesInKB, + $msgBytesOutKB; + + my $objectHashTable = $jobStep->{objectTable}; + my $objectHashKey; + my $objectCount = 0; + + # + # Loop through the collection of objects for this step + # + for $objectHashKey ( keys %$objectHashTable ) + { + # there should hopefully be no more than 2 objects involved in + # a step, so we think it is okay to only report the first 2. + # $NUM_OBJECTS_TO_REPORT can be changed if we decide we need + # and want to report on more than 2 objects. + if ($objectCount < $NUM_OBJECTS_TO_REPORT) + { + my $object = $objectHashTable->{$objectHashKey}; + + if ($objectCount > 0) + { + print "\n"; + printf " " . + " " . + " "; + } + printf " %6d %10d %10d %10d", + $objectHashKey, + $object->{physicalRead}, + $object->{cacheRead}, + $object->{cpBlks}; + } + else + { + last; # stop reporting after we reach $NUM_OBJECTS_TO_REPORT + } + + $objectCount += 1; + } + print "\n"; + + # + # Delete contents of the obj hash table by initializing to an empty list + # + %$objectHashTable = (); + } + + # + # Delete contents of the step hash table by initializing to an empty list + # + %$stepHashTable = (); + } + + # + # print a blank line after the last job step + # + print "\n"; + + # + # print statement summary totals + # + printStatementTrailers ($sessionRecord); + } + + return $stillOpenStepCount; +} + +#------------------------------------------------------------------------------- +# Create hash key for the session hash table. +# Key consists of the host name concatenated with the session id. +# +# input arguments: host string +# session string +# return value(s) : concatenated string to be used as session hash table key +#------------------------------------------------------------------------------- +sub createSessionHashTableKey +{ + my ($hostKey, $sessionKey) = @_; + my $sessionHashKey = $hostKey . $KEY_CONCATENATE_CHAR . $sessionKey; + + return $sessionHashKey; +} + +#------------------------------------------------------------------------------- +# Create and insert record to the session hash table. +# +# input arguments: none +# return value(s) : none +#------------------------------------------------------------------------------- +sub createSessionHashTableRecord +{ + # + # Create an entry in our sessionHashTable for this session/transaction; + # also create an empty stepHashTable for later use + # + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + my %stepHashTable; + my $sessionRecord = + { + hostName => $hostName, + sessionId => $sessionId, + transactionId => $transactionId, + statementId => -1, + versionId => -1, + sqlStatement => $EMPTY_STRING, + startTimeString => $EMPTY_STRING, + endTimeString => $EMPTY_STRING, + stepTable => \%stepHashTable, #add hash tbl ref to track job steps + maxMemPct => 0, + totalTempFileCnt => 0, + totalTempFileSpace => 0, + totalPhysRead => 0, + totalCacheRead => 0, + totalMsgsRcvd => 0, + totalMsgBytesIn => 0, + totalMsgBytesOut => 0, + totalCPBlks => 0 + + # The following sessionRecord fields are filled in later as we + # receive each Start Statement entry for this transaction. + # statementId + # versionId + # sqlStatement + # startTimeString + # endTimeString + # startDecSec + }; + + if ($debugFlag == 1) + { + print STDERR "At log record ", $., + ", Create session record for ", + "host-$hostName; session-$sessionId\n"; + } + + $sessionHashTable{$hashKey} = $sessionRecord; +} + +#------------------------------------------------------------------------------- +# Emulate an End Transaction log record so that we can start a new +# transaction. +# +# input arguments: none +# return value(s) : none +#------------------------------------------------------------------------------- +sub emulateEndTrans +{ + emulateEndStatement ( 1 ); +} + +#------------------------------------------------------------------------------- +# Emulate an End Statement log record so that we can start a new statement. +# +# input arguments: flag indicating whether to treat this as the end of a +# transaction as well. +# 0 - this is not the end of the transaction +# 1 - this is the end of the transaction +# return value(s) : none +#------------------------------------------------------------------------------- +sub emulateEndStatement +{ + my ($endOfTransaction) = @_; + + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + my $numberOfStepsClosed = printAndEndAllSteps ($sessionRecord); + if ( $numberOfStepsClosed > 0 ) + { + my $statementId = $sessionRecord->{statementId}; + warn ("WARNING: record #", $., ": ", + "Forced to close $numberOfStepsClosed step(s) without " , + "ever receiving an EndStep log message for host: $hostName, " , + "session: $sessionId, transaction: $transactionId, " , + "statement: $statementId\n"); + } + + # + # Set statementId to -1 to indicate that we don't currently have an active + # statement. + # Do the same to transactionId to denote the end of the transaction if + # applicable. + # + $sessionRecord->{statementId} = -1; + $sessionRecord->{versionId} = -1; + $sessionRecord->{sqlStatement} = $EMPTY_STRING; + $sessionRecord->{startTimeString} = $EMPTY_STRING; + $sessionRecord->{endTimeString} = $EMPTY_STRING; + + if ( $endOfTransaction == 1 ) + { + $sessionRecord->{transactionId} = -1; + } + } +} + +#------------------------------------------------------------------------------- +# Validate that the specified transaction ID and statement ID (from a log +# record) match those of the specified sessionRecord. +# +# input arguments: session record to be used in comparison +# transactionId of latest log record +# statementId of latest log record +# statement type label to use in error message +# return value(s) 0-ID's match; 1-One or both ID's do not match +#------------------------------------------------------------------------------- +sub validateTransactionAndStatement +{ + my ($sessionRecord, $transactionId, $statementId, $statementType) = @_; + + if ($sessionRecord->{transactionId} != $transactionId) + { + warn ("ERROR: record #", $., ": ", + "Transaction id ($transactionId) for a " , + "$statementType record does not match " , + "the current transactionId ($sessionRecord->{transactionId} " , + "for session $sessionRecord->{sessionId})\n"); + return 1; + } + + if ($sessionRecord->{statementId} != $statementId) + { + warn ("ERROR: record #", $., ": ", + "Statement id ($statementId) for a " , + "$statementType record does not match " , + "the current statementId ($sessionRecord->{statementId}) " , + "for session $sessionRecord->{sessionId})\n"); + return 1; + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process a Start Transaction log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processStartTrans +{ + # + # If for some reason, this session has an open transaction pending, we + # should close the transaction now, so that we can open a new transaction + # + emulateEndTrans (); + + # + # Create necessary sessionHashTable record to track this transaction. + # + createSessionHashTableRecord (); + + return 0; +} + +#------------------------------------------------------------------------------- +# Process an End Transaction log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processEndTrans +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + if ($sessionRecord->{transactionId} != $transactionId) + { + warn ("ERROR: record #", $., ": ", + "Transaction id ($transactionId) for an " , + "EndTransaction does not match " , + "the current transaction ($sessionRecord->{transactionId})\n"); + return 1; + } + + # + # If for some reason, this session has an open statement pending, we + # should close the statement now, so that we can end the transaction + # + emulateEndStatement ( 1 ); + } + else + { + # + # Received End Transaction for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received EndTransaction with transactionId $transactionId, " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process a Start Statement log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processStartStatement +{ + # + # If for some reason, this session has an open statement pending, we + # should close the statement now, so that we can open a new statement + # + emulateEndStatement ( 0 ); + + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + my $dateTimeString= $current_monAlpha . " " . + $current_mday . " " . + $current_hh . ":" . + $current_mm . ":" . + $current_ss . "(" . + $current_decSec . ")"; + + my $statementId; + my $versionId; + my $sqlStatement; + + # + # Parse the message body associated with this message + # + if ( (($statementId, + $versionId, + $sqlStatement) = + ($current_msgBody =~ /Statement-(\d+)\s+Ver-(\w+)\s+SQL-([\d\D]+)/)) != 3) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse statementId, versionId, and SQL\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + my $sessionRecord; + + # + # Save/track the current statement id and it's start time in our + # session entry + # + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + $sessionRecord = $sessionHashTable{$hashKey}; + + if ($sessionRecord->{transactionId} != $transactionId) + { + # + # If we should make Start and End Transaction log messages mandatory, + # then this would be an error condition, so we would error out like so: + # + # warn ("ERROR: record #", $., ": ", + # "Transaction id ($transactionId) for a " , + # "StartStatement does not match " , + # "the current transaction ($sessionRecord->{transactionId})\n"); + # return 1; + # + # But for now, Start and End Transaction are not necssary, so we just + # update the transaction id for this new statement, and continue. + # + $sessionRecord->{transactionId} = $transactionId; + } + } + else + { + # + # Received Start Statement for an unopened session, but since we are not + # requiring Start Transaction log entries, this is to be expected for the + # first statement in each session. Even if we were requiring Start Trans- + # action Statements this could still be a valid condition if we are read- + # ing a log file that starts in the middle of a session. In that case we + # still might want to post a warning like so, but we would still continue. + # + # if ($debugFlag == 1) + # { + # warn ("WARNING: record #", $., ": ", + # "Received StartStatement with statementId $statementId, " , + # "for a host and session ($hostName, $sessionId) that is not open", + # "\n"); + # } + + # + # Create necessary sessionHashTable record to track this transaction. + # + createSessionHashTableRecord (); + } + + $sessionRecord = $sessionHashTable{$hashKey}; + $sessionRecord->{statementId} = $statementId; + $sessionRecord->{versionId} = $versionId; + $sessionRecord->{sqlStatement} = $sqlStatement; + $sessionRecord->{startTimeString} = $dateTimeString; + ($sessionRecord->{startDecSec}) = ($current_decSec =~ /\d+\.([\d\D]+)/); + $sessionRecord->{maxMemPct} = 0; + $sessionRecord->{totalTempFileCnti} = 0; + $sessionRecord->{totalTempFileSpace} = 0; + $sessionRecord->{totalPhysRead} = 0; + $sessionRecord->{totalCacheRead} = 0; + $sessionRecord->{totalMsgsRcvd} = 0; + $sessionRecord->{totalMsgBytesIn} = 0; + $sessionRecord->{totalMsgBytesOut} = 0; + $sessionRecord->{totalCPBlks} = 0; + + if ($debugFlag == 1) + { + print STDERR "At log record ", $., + ", Open a new statement for processing for ", + "host-$hostName; session-$sessionId; " , + "statement-$statementId\n"; + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process an End Statement log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processEndStatement +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + my $dateTimeString= $current_monAlpha . " " . + $current_mday . " " . + $current_hh . ":" . + $current_mm . ":" . + $current_ss . "(" . + $current_decSec . ")"; + + my $statementId; + + # + # Parse the message body associated with this message + # + if ( (($statementId) = + ($current_msgBody =~ /Statement-(\d+)/)) != 1) + { + warn ("ERROR: record #", $., ": ", + " Unable to parse statementId\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + # + # Validate that the transaction and statement ID's match the ones for + # the currently applicable sessionRecord. + # + if (validateTransactionAndStatement ($sessionRecord, + $transactionId, + $statementId, + "EndStatement") != 0) + { + return 1; + } + + # + # Print all step information for this statement; and if for some reason, + # this session has any open steps pending, we report that as well. + # + $sessionRecord->{endTimeString} = $dateTimeString; + my $numberOfStepsClosed = printAndEndAllSteps ($sessionRecord); + if ( $numberOfStepsClosed > 0 ) + { + my $statementId = $sessionRecord->{statementId}; + warn ("WARNING: record #", $., ": ", + "Forced to close $numberOfStepsClosed step(s) without " , + "ever receiving an EndStep log message for host: $hostName, " , + "session: $sessionId, transaction: $transactionId, " , + "statement: $statementId\n"); + } + + # + # Set statementId to -1 to indicate that we don't currently have an active + # statement. + # + $sessionRecord->{statementId} = -1; + $sessionRecord->{versionId} = -1; + $sessionRecord->{sqlStatement} = $EMPTY_STRING; + $sessionRecord->{startTimeString} = $EMPTY_STRING; + $sessionRecord->{endTimeString} = $EMPTY_STRING; + } + else + { + # + # Received End Statement for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received EndStatement with statementId $statementId, " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process a Start Step log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processStartStep +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $statementId; + my $stepId; + my $stepName; + + # + # Parse the message body associated with this message + # + if ( (($statementId, + $stepId, + $stepName) = + ($current_msgBody =~ + /Statement-(\d+)\s+StepId-(\d+)\s+StepName-([\d\D]+)/)) != 3) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse statementId, stepId, and stepName\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + # + # Validate that the transaction and statement ID's match the ones for + # the currently applicable sessionRecord. + # + if (validateTransactionAndStatement ($sessionRecord, + $transactionId, + $statementId, + "StartStep") != 0) + { + return 1; + } + + # + # Add this step to the applicable session entry + # + my $stepHashTable = $sessionRecord->{stepTable}; + my ($startDecSec) = ($current_decSec =~ /\d+\.([\d\D]+)/); + my $startTimeStamp= createCurrentTimeStamp(); + + my %objectHashTable; + $stepHashTable->{$stepId} = + { + stepName => $stepName, + subSystem => $current_subSysName, + startTime => $startTimeStamp, + startDecSec => $startDecSec, + endTime => 0, + endDecSec => 0, + effStartTime => $startTimeStamp, + effStartDecSec => $startDecSec, + effEndTime => 0, + effEndDecSec => 0, + isStepOpen => 1, + blockedFifoIn => 0, + blockedFifoOut => 0, + msgBytesIn => 0, + msgBytesOut => 0, + objectTable => \%objectHashTable #add hash table ref for obj i/o counts + }; + } + else + { + # + # Received Start Step for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received StartStep with stepId $stepId, " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process an End Step log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processEndStep +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $statementId; + my $stepId; + my $blockedFifoIn; + my $blockedFifoOut; + my $msgBytesIn; + my $msgBytesOut; + + # + # Parse the message body associated with this message + # + if ( (($statementId, + $stepId, + $blockedFifoIn, + $blockedFifoOut, + $msgBytesIn, + $msgBytesOut) = + ($current_msgBody =~ + /Statement-(\d+)\s+StepId-(\d+)\s+BlockedFifoIn-(\d+)\s+BlockedFifoOut-(\d+)\s+MsgBytesIn-(\d+)\s+MsgBytesOut-(\d+)/)) != 6) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse statementId, stepId, blockedFifoIn, ", + "blockedFifoOut, msgBytesIn, and msgBytesOut\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + # + # Validate that the transaction and statement ID's match the ones for + # the currently applicable sessionRecord. + # + if (validateTransactionAndStatement ($sessionRecord, + $transactionId, + $statementId, + "EndStep") != 0) + { + return 1; + } + + my $stepHashTable = $sessionRecord->{stepTable}; + + # + # Find and close out this step + # + if ( exists($stepHashTable->{$stepId}) ) + { + my $jobStep = $stepHashTable->{$stepId}; + + my ($endDecSec) = ($current_decSec =~ /\d+\.([\d\D]+)/); + + $jobStep->{endTime} = createCurrentTimeStamp(); + $jobStep->{endDecSec} = $endDecSec; + $jobStep->{blockedFifoIn} = $blockedFifoIn; + $jobStep->{blockedFifoOut} = $blockedFifoOut; + $jobStep->{msgBytesIn} = $msgBytesIn; + $jobStep->{msgBytesOut} = $msgBytesOut; + + # + # If we did not encounter an End Processing time, then use the endStep + # time for the End Processing time. + # + if ($jobStep->{effEndTime} == 0) + { + $jobStep->{effEndTime} = $jobStep->{endTime}; + $jobStep->{effEndDecSec}= $jobStep->{endDecSec}; + } + $jobStep->{isStepOpen} = 0; + } + } + else + { + # + # Received End Step for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received EndStep with stepId $stepId, " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process a Processing Times log record, containing times that the step began +# reading/writing and finished reading/writing. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processProcessingTimes +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $statementId; + my $stepId; + my $firstRead_mon; + my $firstRead_day; + my $firstRead_yyyy; + my $firstRead_hh; + my $firstRead_min; + my $firstRead_ss; + my $firstRead_decSec; + my $lastRead_mon; + my $lastRead_day; + my $lastRead_yyyy; + my $lastRead_hh; + my $lastRead_min; + my $lastRead_ss; + my $lastRead_decSec; + my $firstWrite_mon; + my $firstWrite_day; + my $firstWrite_yyyy; + my $firstWrite_hh; + my $firstWrite_min; + my $firstWrite_ss; + my $firstWrite_decSec; + my $lastWrite_mon; + my $lastWrite_day; + my $lastWrite_yyyy; + my $lastWrite_hh; + my $lastWrite_min; + my $lastWrite_ss; + my $lastWrite_decSec; + + # + # Parse the message body associated with this message + # + if ( (($statementId, + $stepId, + $firstRead_mon, + $firstRead_day, + $firstRead_yyyy, + $firstRead_hh, + $firstRead_min, + $firstRead_ss, + $firstRead_decSec, + $lastRead_mon, + $lastRead_day, + $lastRead_yyyy, + $lastRead_hh, + $lastRead_min, + $lastRead_ss, + $lastRead_decSec, + $firstWrite_mon, + $firstWrite_day, + $firstWrite_yyyy, + $firstWrite_hh, + $firstWrite_min, + $firstWrite_ss, + $firstWrite_decSec, + $lastWrite_mon, + $lastWrite_day, + $lastWrite_yyyy, + $lastWrite_hh, + $lastWrite_min, + $lastWrite_ss, + $lastWrite_decSec) = + ($current_msgBody =~ + /Statement-(\d+)\s+StepId-(\d+)\s+FirstRead-(\d+)\/(\d+)\/(\d+)\|(\d+):(\d+):(\d+)\.(\d+)\s+LastRead-(\d+)\/(\d+)\/(\d+)\|(\d+):(\d+):(\d+)\.(\d+)\s+FirstWrite-(\d+)\/(\d+)\/(\d+)\|(\d+):(\d+):(\d+)\.(\d+)\s+LastWrite-(\d+)\/(\d+)\/(\d+)\|(\d+):(\d+):(\d+)\.(\d+)/)) != 30) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse statementId, ", + "stepId, firstRead, lastRead, firstWrite, and lastWrite\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + # + # Validate that the transaction and statement ID's match the ones for + # the currently applicable sessionRecord. + # + if (validateTransactionAndStatement ($sessionRecord, + $transactionId, + $statementId, + "ProcessingTimesStep") != 0) + { + return 1; + } + + my $stepHashTable = $sessionRecord->{stepTable}; + + # + # Find and set the effective start/end times for this step. + # In our report, we currently only log the first read and last write, + # and ignore the last read and first write. + # + if ( exists($stepHashTable->{$stepId}) ) + { + my $jobStep = $stepHashTable->{$stepId}; + + my ($effStartDecSec) = ($firstRead_decSec =~ /\d+\.([\d\D]+)/); + $jobStep->{effStartTime} = timelocal($firstRead_ss, + $firstRead_min, + $firstRead_hh, + $firstRead_day, + ($firstRead_mon-1), + ($firstRead_yyyy-1900)); + $jobStep->{effStartDecSec} = $firstRead_decSec; + + my ($effEndDecSec) = ($lastWrite_decSec =~ /\d+\.([\d\D]+)/); + $jobStep->{effEndTime} = timelocal($lastWrite_ss, + $lastWrite_min, + $lastWrite_hh, + $lastWrite_day, + ($lastWrite_mon-1), + ($lastWrite_yyyy-1900)); + $jobStep->{effEndDecSec} = $lastWrite_decSec; + } + } + else + { + # + # Received Start Processing Step for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received Start Processing Step for stepId $stepId, " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process an I/O log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processIOCount +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $statementId; + my $stepId; + my $objectId; + my $physicalRead; + my $cacheRead; + my $cpBlks; + + # + # Parse the message body associated with this message + # + if ( (($statementId, + $stepId, + $objectId, + $physicalRead, + $cacheRead, + $cpBlks) = + ($current_msgBody =~ + /I\/O:\s+Statement-(\d+)\s+StepId-(\d+)\s+ObjectId-(\d+)\s+PhysRead-(\d+)\s+CacheRead-(\d+)\s+CPBlks-(\d+)/)) != 6) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse statement, stepId, objectId, physRead, " , + "cacheRead, and cpBlks\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + # + # Validate that the transaction and statement ID's match the ones for + # the currently applicable sessionRecord. + # + if (validateTransactionAndStatement ($sessionRecord, + $transactionId, + $statementId, + "I/OCount") != 0) + { + return 1; + } + + my $stepHashTable = $sessionRecord->{stepTable}; + + # + # Find and update the object id list and the I/O counts for this step + # + if ( exists($stepHashTable->{$stepId}) ) + { + my $jobStep = $stepHashTable->{$stepId}; + my $objectHashTable = $jobStep->{objectTable}; + + # update or create an object entry for $objectId + if ( exists($objectHashTable->{$objectId}) ) + { + my $object = $objectHashTable->{$objectId}; + $object->{physicalRead} += $physicalRead; + $object->{cacheRead} += $cacheRead; + $object->{cpBlks} += $cpBlks; + } + else + { + $objectHashTable->{$objectId} = + { + physicalRead => $physicalRead, + cacheRead => $cacheRead, + cpBlks => $cpBlks + }; + my $object = $objectHashTable->{$objectId}; + } + } + } + else + { + # + # Received I/O counts for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received I/O count for stepId $stepId, " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process a Statement Summary log record. +# +# input arguments: none +# return value(s) : 0-success, 1-parsing error +#------------------------------------------------------------------------------- +sub processStatementSummary +{ + my $hostName = $current_host; + my $sessionId = $current_field6_1; + my $transactionId = $current_field6_2; + + my $statementId; + my $maxMemPct; + my $totalTempFileCnt; + my $totalTempFileSpace; + my $totalPhysRead; + my $totalCacheRead; + my $totalMsgsRcvd; + my $totalMsgBytesIn; + my $totalMsgBytesOut; + my $totalCPBlks; + + # + # Parse the message body associated with this message + # + if ( (($statementId, + $maxMemPct, + $totalTempFileCnt, + $totalTempFileSpace, + $totalPhysRead, + $totalCacheRead, + $totalMsgsRcvd, + $totalMsgBytesIn, + $totalMsgBytesOut, + $totalCPBlks) = + ($current_msgBody =~ + /Summary:\s+Statement-(\d+)\s+MaxMemPct-(\d+)\s+TempFileCnt-(\d+)\s+TempFileSpace-(\d+)\s+PhysRead-(\d+)\s+CacheRead-(\d+)\s+MsgsRcvd-(\d+)\s+MsgBytesIn-(\d+)\s+MsgBytesOut-(\d+)\s+CPBlks-(\d+)/)) != 10) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse statement, maxMemPct, tempFileCnt, tempFileSpace, ", + "physRead, cacheRead, msgsRcvd, msgBytesIn, and msgBytesOut\n"); + return 1; + } + + my $hashKey = createSessionHashTableKey ( $sessionId, $hostName ); + + if ( exists($sessionHashTable{$hashKey}) ) # find sessionHashTable entry + { + my $sessionRecord = $sessionHashTable{$hashKey}; + + # + # Validate that the transaction and statement ID's match the ones for + # the currently applicable sessionRecord. + # + if (validateTransactionAndStatement ($sessionRecord, + $transactionId, + $statementId, + "StatementSummary") != 0) + { + return 1; + } + + # + # Set the statement summary totals for this session record + # + $sessionRecord->{maxMemPct} = $maxMemPct; + $sessionRecord->{totalTempFileCnt} = $totalTempFileCnt; + $sessionRecord->{totalTempFileSpace} = $totalTempFileSpace; + $sessionRecord->{totalPhysRead} = $totalPhysRead; + $sessionRecord->{totalCacheRead} = $totalCacheRead; + $sessionRecord->{totalMsgsRcvd} = $totalMsgsRcvd; + $sessionRecord->{totalMsgBytesIn} = $totalMsgBytesIn; + $sessionRecord->{totalMsgBytesOut} = $totalMsgBytesOut; + $sessionRecord->{totalCPBlks} = $totalCPBlks; + } + else + { + # + # Received Statement Summary for an unopened session, but this could be + # valid if we read a log file that starts in the middle of a session; + # so we only post the warning if debug is enabled. + # + if ($debugFlag == 1) + { + warn ("WARNING: record #", $., ": ", + "Received Statement Summary " , + "for a host and session ($hostName, $sessionId) that is not open", + "\n"); + } + } + + return 0; +} + +#------------------------------------------------------------------------------- +# Process a log record. +# +# input arguments: none +# return value(s) : 0-success +# 1-parsing error +# 2-not a pertinent msg type +# 3-log record was filtered based on $sessionToExtract setting +#------------------------------------------------------------------------------- +sub processLogRecord +{ + my $returnStatus = 0; + + # + # Parse the log message + # + if ( (($current_monAlpha, + $current_mday, + $current_hh, + $current_mm, + $current_ss, + $current_host, + $current_subSysName, + $current_pid, + $current_decSec, + $current_field6_1, + $current_field6_2, + $current_field6_3, + $current_severityLvl, + $current_subSysId, + $current_msgNum, + $current_msgBody) = + ($current_logRecord =~ /(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\w+)\s+(\w+)\[(\d+)\]:\s+([\d\.]+)\s+\|(\d+)\|(\d+)\|(\d+)\|\s+(\w)\s+(\d+)\s+CAL(\d+):\s+([\d\D]+)/)) != 16) + { + warn ("ERROR: record #", $., ": ", + "Unable to parse header fields in record\n"); + return 1; + } + + if ( ( $sessionToExtract == $SESSION_ID_WILDCARD ) || + ( $current_field6_1 == $sessionToExtract ) ) + { + if ( ($current_msgNum == $LOG_MSG_NUM_START_TRANS) || + ($current_msgNum == $LOG_MSG_NUM_END_TRANS) || + ($current_msgNum == $LOG_MSG_NUM_START_STATEMENT) || + ($current_msgNum == $LOG_MSG_NUM_END_STATEMENT) || + ($current_msgNum == $LOG_MSG_NUM_START_STEP) || + ($current_msgNum == $LOG_MSG_NUM_STOP_STEP) || + ($current_msgNum == $LOG_MSG_NUM_IO_COUNT) || + ($current_msgNum == $LOG_MSG_NUM_PROC_TIMES) || + ($current_msgNum == $LOG_MSG_NUM_STATEMENT_SUM) ) + { + # + # For some serious verbose debugging, this block can be activated + # to dump the contents of each log message that we parse. + # + if ( $debugFlag == 1 ) + { + # print STDERR "Parsed performance log record contains:\n"; + # print STDERR " monAlpha : $current_monAlpha\n"; + # print STDERR " mday : $current_mday\n"; + # print STDERR " hh : $current_hh\n"; + # print STDERR " mm : $current_mm\n"; + # print STDERR " ss : $current_ss\n"; + # print STDERR " host : $current_host\n"; + # print STDERR " subSysName : $current_subSysName\n"; + # print STDERR " pid : $current_pid\n"; + # print STDERR " decSec : $current_decSec\n"; + # print STDERR " field6_1 : $current_field6_1\n"; + # print STDERR " field6_2 : $current_field6_2\n"; + # print STDERR " field6_3 : $current_field6_3\n"; + # print STDERR " severityLvl: $current_severityLvl\n"; + # print STDERR " subSysId : $current_subSysId\n"; + # print STDERR " msgNum : $current_msgNum\n"; + # print STDERR " msgBody : $current_msgBody\n"; + } + + # + # Branch to applicable processing subroutine based on message type + # + if ($current_msgNum == $LOG_MSG_NUM_START_TRANS) + { + $returnStatus = processStartTrans (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_END_TRANS) + { + $returnStatus = processEndTrans (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_START_STATEMENT) + { + $returnStatus = processStartStatement (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_END_STATEMENT) + { + $returnStatus = processEndStatement (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_START_STEP) + { + $returnStatus = processStartStep (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_STOP_STEP) + { + $returnStatus = processEndStep (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_IO_COUNT) + { + $returnStatus = processIOCount (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_PROC_TIMES) + { + $returnStatus = processProcessingTimes (); + } + elsif ($current_msgNum == $LOG_MSG_NUM_STATEMENT_SUM) + { + $returnStatus = processStatementSummary (); + } + else + { + $returnStatus = 2; + } + } + else + { + $returnStatus = 2; + } + } + else + { + $returnStatus = 3; + } + + return $returnStatus; +} + +#------------------------------------------------------------------------------- +# Main entry point for this script +#------------------------------------------------------------------------------- + +# +# Parse any command line arguments +# +parseCmdLineArgs (); + +# +# Set current year (see getCurrentYear() for explanation) +# +$timeStampYear = getCurrentYear (); + +# +# Reopen/reassign STDIN to the specified log file +# +if ( !open(STDIN, "<$logFileName") ) +{ + print STDERR "\nUnable to open log file $logFileName\n\n"; + usage(); +} + +# +# Loop through all the log records read from STDIN +# +while ($current_logRecord = ) +{ + chomp($current_logRecord); + + my $returnStatus = processLogRecord (); + if ( $returnStatus == 1 ) + { + warn ("ERROR: record #", $., ": ", + "Error processing log record $.: " , + "<$current_logRecord>\n"); + } + + # + # For some serious verbose debugging, this block can be activated + # to dump the contents of our hash table after each log record is + # successfully processed. + # + elsif ( $returnStatus == 0 ) + { + if ($debugFlag == 1) + { + # print STDERR "...Dumping hash table after record $.\n"; + # dumpSessionHashTable (); + } + } +} + +# +# Report any steps that are still pending as EOF is reached. +# This may or may not be what the user expected, so we report +# as a warning. +# +if ($debugFlag == 1) +{ + warn ("\n", + "WARNING: The following hash table dump shows any steps that ", + "are still pending when EOF was reached.\n"); + dumpSessionHashTable (); +} diff --git a/oamapps/postConfigure/Makefile.am b/oamapps/postConfigure/Makefile.am index ffb683a6..41e97068 100644 --- a/oamapps/postConfigure/Makefile.am +++ b/oamapps/postConfigure/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -22,7 +5,7 @@ AM_CPPFLAGS = $(idb_cppflags) AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) -lreadline -lncurses -bin_PROGRAMS = postConfigure installer patchInstaller amazonInstaller mycnfUpgrade +bin_PROGRAMS = postConfigure installer patchInstaller postConfigure_SOURCES = postConfigure.cpp helpers.cpp postConfigure_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) postConfigure_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) @@ -32,12 +15,6 @@ installer_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(i patchInstaller_SOURCES = patchInstaller.cpp patchInstaller_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) patchInstaller_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -amazonInstaller_SOURCES = amazonInstaller.cpp helpers.cpp -amazonInstaller_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -amazonInstaller_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -mycnfUpgrade_SOURCES = mycnfUpgrade.cpp -mycnfUpgrade_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -mycnfUpgrade_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) test: diff --git a/oamapps/postConfigure/Makefile.in b/oamapps/postConfigure/Makefile.in deleted file mode 100644 index 6a0959e5..00000000 --- a/oamapps/postConfigure/Makefile.in +++ /dev/null @@ -1,680 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = postConfigure$(EXEEXT) installer$(EXEEXT) \ - patchInstaller$(EXEEXT) amazonInstaller$(EXEEXT) \ - mycnfUpgrade$(EXEEXT) -subdir = oamapps/postConfigure -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_amazonInstaller_OBJECTS = \ - amazonInstaller-amazonInstaller.$(OBJEXT) \ - amazonInstaller-helpers.$(OBJEXT) -amazonInstaller_OBJECTS = $(am_amazonInstaller_OBJECTS) -amazonInstaller_LDADD = $(LDADD) -am_installer_OBJECTS = installer-installer.$(OBJEXT) \ - installer-helpers.$(OBJEXT) -installer_OBJECTS = $(am_installer_OBJECTS) -installer_LDADD = $(LDADD) -am_mycnfUpgrade_OBJECTS = mycnfUpgrade-mycnfUpgrade.$(OBJEXT) -mycnfUpgrade_OBJECTS = $(am_mycnfUpgrade_OBJECTS) -mycnfUpgrade_LDADD = $(LDADD) -am_patchInstaller_OBJECTS = patchInstaller-patchInstaller.$(OBJEXT) -patchInstaller_OBJECTS = $(am_patchInstaller_OBJECTS) -patchInstaller_LDADD = $(LDADD) -am_postConfigure_OBJECTS = postConfigure-postConfigure.$(OBJEXT) \ - postConfigure-helpers.$(OBJEXT) -postConfigure_OBJECTS = $(am_postConfigure_OBJECTS) -postConfigure_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(amazonInstaller_SOURCES) $(installer_SOURCES) \ - $(mycnfUpgrade_SOURCES) $(patchInstaller_SOURCES) \ - $(postConfigure_SOURCES) -DIST_SOURCES = $(amazonInstaller_SOURCES) $(installer_SOURCES) \ - $(mycnfUpgrade_SOURCES) $(patchInstaller_SOURCES) \ - $(postConfigure_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -lreadline -lncurses -postConfigure_SOURCES = postConfigure.cpp helpers.cpp -postConfigure_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -postConfigure_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) -installer_SOURCES = installer.cpp helpers.cpp -installer_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -installer_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -patchInstaller_SOURCES = patchInstaller.cpp -patchInstaller_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -patchInstaller_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -amazonInstaller_SOURCES = amazonInstaller.cpp helpers.cpp -amazonInstaller_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -amazonInstaller_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -mycnfUpgrade_SOURCES = mycnfUpgrade.cpp -mycnfUpgrade_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -mycnfUpgrade_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/postConfigure/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/postConfigure/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -amazonInstaller$(EXEEXT): $(amazonInstaller_OBJECTS) $(amazonInstaller_DEPENDENCIES) - @rm -f amazonInstaller$(EXEEXT) - $(CXXLINK) $(amazonInstaller_LDFLAGS) $(amazonInstaller_OBJECTS) $(amazonInstaller_LDADD) $(LIBS) -installer$(EXEEXT): $(installer_OBJECTS) $(installer_DEPENDENCIES) - @rm -f installer$(EXEEXT) - $(CXXLINK) $(installer_LDFLAGS) $(installer_OBJECTS) $(installer_LDADD) $(LIBS) -mycnfUpgrade$(EXEEXT): $(mycnfUpgrade_OBJECTS) $(mycnfUpgrade_DEPENDENCIES) - @rm -f mycnfUpgrade$(EXEEXT) - $(CXXLINK) $(mycnfUpgrade_LDFLAGS) $(mycnfUpgrade_OBJECTS) $(mycnfUpgrade_LDADD) $(LIBS) -patchInstaller$(EXEEXT): $(patchInstaller_OBJECTS) $(patchInstaller_DEPENDENCIES) - @rm -f patchInstaller$(EXEEXT) - $(CXXLINK) $(patchInstaller_LDFLAGS) $(patchInstaller_OBJECTS) $(patchInstaller_LDADD) $(LIBS) -postConfigure$(EXEEXT): $(postConfigure_OBJECTS) $(postConfigure_DEPENDENCIES) - @rm -f postConfigure$(EXEEXT) - $(CXXLINK) $(postConfigure_LDFLAGS) $(postConfigure_OBJECTS) $(postConfigure_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/amazonInstaller-amazonInstaller.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/amazonInstaller-helpers.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/installer-helpers.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/installer-installer.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/patchInstaller-patchInstaller.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/postConfigure-helpers.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/postConfigure-postConfigure.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -amazonInstaller-amazonInstaller.o: amazonInstaller.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT amazonInstaller-amazonInstaller.o -MD -MP -MF "$(DEPDIR)/amazonInstaller-amazonInstaller.Tpo" -c -o amazonInstaller-amazonInstaller.o `test -f 'amazonInstaller.cpp' || echo '$(srcdir)/'`amazonInstaller.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/amazonInstaller-amazonInstaller.Tpo" "$(DEPDIR)/amazonInstaller-amazonInstaller.Po"; else rm -f "$(DEPDIR)/amazonInstaller-amazonInstaller.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='amazonInstaller.cpp' object='amazonInstaller-amazonInstaller.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o amazonInstaller-amazonInstaller.o `test -f 'amazonInstaller.cpp' || echo '$(srcdir)/'`amazonInstaller.cpp - -amazonInstaller-amazonInstaller.obj: amazonInstaller.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT amazonInstaller-amazonInstaller.obj -MD -MP -MF "$(DEPDIR)/amazonInstaller-amazonInstaller.Tpo" -c -o amazonInstaller-amazonInstaller.obj `if test -f 'amazonInstaller.cpp'; then $(CYGPATH_W) 'amazonInstaller.cpp'; else $(CYGPATH_W) '$(srcdir)/amazonInstaller.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/amazonInstaller-amazonInstaller.Tpo" "$(DEPDIR)/amazonInstaller-amazonInstaller.Po"; else rm -f "$(DEPDIR)/amazonInstaller-amazonInstaller.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='amazonInstaller.cpp' object='amazonInstaller-amazonInstaller.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o amazonInstaller-amazonInstaller.obj `if test -f 'amazonInstaller.cpp'; then $(CYGPATH_W) 'amazonInstaller.cpp'; else $(CYGPATH_W) '$(srcdir)/amazonInstaller.cpp'; fi` - -amazonInstaller-helpers.o: helpers.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT amazonInstaller-helpers.o -MD -MP -MF "$(DEPDIR)/amazonInstaller-helpers.Tpo" -c -o amazonInstaller-helpers.o `test -f 'helpers.cpp' || echo '$(srcdir)/'`helpers.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/amazonInstaller-helpers.Tpo" "$(DEPDIR)/amazonInstaller-helpers.Po"; else rm -f "$(DEPDIR)/amazonInstaller-helpers.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='helpers.cpp' object='amazonInstaller-helpers.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o amazonInstaller-helpers.o `test -f 'helpers.cpp' || echo '$(srcdir)/'`helpers.cpp - -amazonInstaller-helpers.obj: helpers.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT amazonInstaller-helpers.obj -MD -MP -MF "$(DEPDIR)/amazonInstaller-helpers.Tpo" -c -o amazonInstaller-helpers.obj `if test -f 'helpers.cpp'; then $(CYGPATH_W) 'helpers.cpp'; else $(CYGPATH_W) '$(srcdir)/helpers.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/amazonInstaller-helpers.Tpo" "$(DEPDIR)/amazonInstaller-helpers.Po"; else rm -f "$(DEPDIR)/amazonInstaller-helpers.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='helpers.cpp' object='amazonInstaller-helpers.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(amazonInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o amazonInstaller-helpers.obj `if test -f 'helpers.cpp'; then $(CYGPATH_W) 'helpers.cpp'; else $(CYGPATH_W) '$(srcdir)/helpers.cpp'; fi` - -installer-installer.o: installer.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT installer-installer.o -MD -MP -MF "$(DEPDIR)/installer-installer.Tpo" -c -o installer-installer.o `test -f 'installer.cpp' || echo '$(srcdir)/'`installer.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/installer-installer.Tpo" "$(DEPDIR)/installer-installer.Po"; else rm -f "$(DEPDIR)/installer-installer.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='installer.cpp' object='installer-installer.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o installer-installer.o `test -f 'installer.cpp' || echo '$(srcdir)/'`installer.cpp - -installer-installer.obj: installer.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT installer-installer.obj -MD -MP -MF "$(DEPDIR)/installer-installer.Tpo" -c -o installer-installer.obj `if test -f 'installer.cpp'; then $(CYGPATH_W) 'installer.cpp'; else $(CYGPATH_W) '$(srcdir)/installer.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/installer-installer.Tpo" "$(DEPDIR)/installer-installer.Po"; else rm -f "$(DEPDIR)/installer-installer.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='installer.cpp' object='installer-installer.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o installer-installer.obj `if test -f 'installer.cpp'; then $(CYGPATH_W) 'installer.cpp'; else $(CYGPATH_W) '$(srcdir)/installer.cpp'; fi` - -installer-helpers.o: helpers.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT installer-helpers.o -MD -MP -MF "$(DEPDIR)/installer-helpers.Tpo" -c -o installer-helpers.o `test -f 'helpers.cpp' || echo '$(srcdir)/'`helpers.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/installer-helpers.Tpo" "$(DEPDIR)/installer-helpers.Po"; else rm -f "$(DEPDIR)/installer-helpers.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='helpers.cpp' object='installer-helpers.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o installer-helpers.o `test -f 'helpers.cpp' || echo '$(srcdir)/'`helpers.cpp - -installer-helpers.obj: helpers.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT installer-helpers.obj -MD -MP -MF "$(DEPDIR)/installer-helpers.Tpo" -c -o installer-helpers.obj `if test -f 'helpers.cpp'; then $(CYGPATH_W) 'helpers.cpp'; else $(CYGPATH_W) '$(srcdir)/helpers.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/installer-helpers.Tpo" "$(DEPDIR)/installer-helpers.Po"; else rm -f "$(DEPDIR)/installer-helpers.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='helpers.cpp' object='installer-helpers.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(installer_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o installer-helpers.obj `if test -f 'helpers.cpp'; then $(CYGPATH_W) 'helpers.cpp'; else $(CYGPATH_W) '$(srcdir)/helpers.cpp'; fi` - -mycnfUpgrade-mycnfUpgrade.o: mycnfUpgrade.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mycnfUpgrade_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT mycnfUpgrade-mycnfUpgrade.o -MD -MP -MF "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Tpo" -c -o mycnfUpgrade-mycnfUpgrade.o `test -f 'mycnfUpgrade.cpp' || echo '$(srcdir)/'`mycnfUpgrade.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Tpo" "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Po"; else rm -f "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='mycnfUpgrade.cpp' object='mycnfUpgrade-mycnfUpgrade.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mycnfUpgrade_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o mycnfUpgrade-mycnfUpgrade.o `test -f 'mycnfUpgrade.cpp' || echo '$(srcdir)/'`mycnfUpgrade.cpp - -mycnfUpgrade-mycnfUpgrade.obj: mycnfUpgrade.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mycnfUpgrade_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT mycnfUpgrade-mycnfUpgrade.obj -MD -MP -MF "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Tpo" -c -o mycnfUpgrade-mycnfUpgrade.obj `if test -f 'mycnfUpgrade.cpp'; then $(CYGPATH_W) 'mycnfUpgrade.cpp'; else $(CYGPATH_W) '$(srcdir)/mycnfUpgrade.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Tpo" "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Po"; else rm -f "$(DEPDIR)/mycnfUpgrade-mycnfUpgrade.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='mycnfUpgrade.cpp' object='mycnfUpgrade-mycnfUpgrade.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(mycnfUpgrade_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o mycnfUpgrade-mycnfUpgrade.obj `if test -f 'mycnfUpgrade.cpp'; then $(CYGPATH_W) 'mycnfUpgrade.cpp'; else $(CYGPATH_W) '$(srcdir)/mycnfUpgrade.cpp'; fi` - -patchInstaller-patchInstaller.o: patchInstaller.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(patchInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT patchInstaller-patchInstaller.o -MD -MP -MF "$(DEPDIR)/patchInstaller-patchInstaller.Tpo" -c -o patchInstaller-patchInstaller.o `test -f 'patchInstaller.cpp' || echo '$(srcdir)/'`patchInstaller.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/patchInstaller-patchInstaller.Tpo" "$(DEPDIR)/patchInstaller-patchInstaller.Po"; else rm -f "$(DEPDIR)/patchInstaller-patchInstaller.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='patchInstaller.cpp' object='patchInstaller-patchInstaller.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(patchInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o patchInstaller-patchInstaller.o `test -f 'patchInstaller.cpp' || echo '$(srcdir)/'`patchInstaller.cpp - -patchInstaller-patchInstaller.obj: patchInstaller.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(patchInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT patchInstaller-patchInstaller.obj -MD -MP -MF "$(DEPDIR)/patchInstaller-patchInstaller.Tpo" -c -o patchInstaller-patchInstaller.obj `if test -f 'patchInstaller.cpp'; then $(CYGPATH_W) 'patchInstaller.cpp'; else $(CYGPATH_W) '$(srcdir)/patchInstaller.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/patchInstaller-patchInstaller.Tpo" "$(DEPDIR)/patchInstaller-patchInstaller.Po"; else rm -f "$(DEPDIR)/patchInstaller-patchInstaller.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='patchInstaller.cpp' object='patchInstaller-patchInstaller.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(patchInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o patchInstaller-patchInstaller.obj `if test -f 'patchInstaller.cpp'; then $(CYGPATH_W) 'patchInstaller.cpp'; else $(CYGPATH_W) '$(srcdir)/patchInstaller.cpp'; fi` - -postConfigure-postConfigure.o: postConfigure.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT postConfigure-postConfigure.o -MD -MP -MF "$(DEPDIR)/postConfigure-postConfigure.Tpo" -c -o postConfigure-postConfigure.o `test -f 'postConfigure.cpp' || echo '$(srcdir)/'`postConfigure.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/postConfigure-postConfigure.Tpo" "$(DEPDIR)/postConfigure-postConfigure.Po"; else rm -f "$(DEPDIR)/postConfigure-postConfigure.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='postConfigure.cpp' object='postConfigure-postConfigure.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o postConfigure-postConfigure.o `test -f 'postConfigure.cpp' || echo '$(srcdir)/'`postConfigure.cpp - -postConfigure-postConfigure.obj: postConfigure.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT postConfigure-postConfigure.obj -MD -MP -MF "$(DEPDIR)/postConfigure-postConfigure.Tpo" -c -o postConfigure-postConfigure.obj `if test -f 'postConfigure.cpp'; then $(CYGPATH_W) 'postConfigure.cpp'; else $(CYGPATH_W) '$(srcdir)/postConfigure.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/postConfigure-postConfigure.Tpo" "$(DEPDIR)/postConfigure-postConfigure.Po"; else rm -f "$(DEPDIR)/postConfigure-postConfigure.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='postConfigure.cpp' object='postConfigure-postConfigure.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o postConfigure-postConfigure.obj `if test -f 'postConfigure.cpp'; then $(CYGPATH_W) 'postConfigure.cpp'; else $(CYGPATH_W) '$(srcdir)/postConfigure.cpp'; fi` - -postConfigure-helpers.o: helpers.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT postConfigure-helpers.o -MD -MP -MF "$(DEPDIR)/postConfigure-helpers.Tpo" -c -o postConfigure-helpers.o `test -f 'helpers.cpp' || echo '$(srcdir)/'`helpers.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/postConfigure-helpers.Tpo" "$(DEPDIR)/postConfigure-helpers.Po"; else rm -f "$(DEPDIR)/postConfigure-helpers.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='helpers.cpp' object='postConfigure-helpers.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o postConfigure-helpers.o `test -f 'helpers.cpp' || echo '$(srcdir)/'`helpers.cpp - -postConfigure-helpers.obj: helpers.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT postConfigure-helpers.obj -MD -MP -MF "$(DEPDIR)/postConfigure-helpers.Tpo" -c -o postConfigure-helpers.obj `if test -f 'helpers.cpp'; then $(CYGPATH_W) 'helpers.cpp'; else $(CYGPATH_W) '$(srcdir)/helpers.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/postConfigure-helpers.Tpo" "$(DEPDIR)/postConfigure-helpers.Po"; else rm -f "$(DEPDIR)/postConfigure-helpers.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='helpers.cpp' object='postConfigure-helpers.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(postConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o postConfigure-helpers.obj `if test -f 'helpers.cpp'; then $(CYGPATH_W) 'helpers.cpp'; else $(CYGPATH_W) '$(srcdir)/helpers.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/postConfigure/amazonConfig-1pm.xml b/oamapps/postConfigure/amazonConfig-1pm.xml deleted file mode 100644 index a04dd354..00000000 --- a/oamapps/postConfigure/amazonConfig-1pm.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - - calpont-1 - - - combined - - - - - - unassigned - - - - - - unassigned - - - - - - unassigned - - - - - - unassigned - - - - - unassigned - - - 0 - - - - unassigned - - - unassigned - - - unassigned - - - - y - - - - 10 - - - 1 - - - - unassigned - - - 1 - - - - y - - - 100 - - - 0.0.0.0 - - - unassigned - - - unassigned - - - Calpont1 - - - - - - y - - - us-east-1 - - - unassigned - - - unassigned - - diff --git a/oamapps/postConfigure/amazonConfig.xml b/oamapps/postConfigure/amazonConfig.xml index a8d3e198..caa72df5 100644 --- a/oamapps/postConfigure/amazonConfig.xml +++ b/oamapps/postConfigure/amazonConfig.xml @@ -9,30 +9,6 @@ separate - - - - - - unassigned - - - - - - unassigned - - - - - - unassigned - - - - - - unassigned @@ -60,6 +36,14 @@ 10 + + + + y + + + 10 + 2 @@ -80,7 +64,8 @@ 0.0.0.0 - + + unassigned @@ -89,6 +74,9 @@ Calpont1 + + unassigned + diff --git a/oamapps/postConfigure/amazonInstaller.cpp b/oamapps/postConfigure/amazonInstaller.cpp index 20463634..b1102618 100644 --- a/oamapps/postConfigure/amazonInstaller.cpp +++ b/oamapps/postConfigure/amazonInstaller.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** * $Id: amazonInstaller.cpp 64 2006-10-12 22:21:51Z dhill $ * @@ -78,22 +61,21 @@ typedef struct Volume_struct typedef std::vector VolumeList; -typedef struct ModuleIP_struct +typedef struct ElasticIP_struct { std::string IPaddress; std::string moduleName; -} ModuleIP; +} ElasticIP; -typedef std::vector ModuleIPList; +typedef std::vector ElasticIPList; -typedef std::vector PrivateIPList; string getIPAddress(string instance); void cleanupSystem(bool terminate = true); void setSystemName(); void snmpAppCheck(); void setRootPassword(); -void launchInstanceThread(ModuleIP moduleip); +void launchInstanceThread(string module); int launchInstanceCount = 0; void createVolumeThread(string module); int createVolumeCount = 0; @@ -121,11 +103,10 @@ VolumeList PMvolumelist; VolumeList UMvolumelist; string rootPassword = "Calpont1"; string AMIrootPassword = "Calpont1"; -ModuleIPList elasticiplist; -ModuleIPList moduleiplist; +ElasticIPList elasticiplist; -char* pcommand1 = 0; -string prompt1; +char* pcommand = 0; +string prompt; string NMSIPAddress = "0.0.0.0"; string systemName = "calpont-1"; string UserModuleInstanceType = oam::UnassignedName; @@ -140,13 +121,6 @@ string region = "us-east-1"; string autoTagging = "y"; string elasticIPs = oam::UnassignedName; string systemType = ""; -string subnetID = oam::UnassignedName; -string VPCStartPrivateIP = oam::UnassignedName; -string localQuery = "n"; -string MySQLRep = "n"; - -bool noPrompting; -string mysqlpw = " "; bool PMEBS = true; @@ -167,13 +141,14 @@ int main(int argc, char *argv[]) bool postConfigureDebug = false; string TotalUmMemory = oam::UnassignedName; string NumBlocksPct = oam::UnassignedName; + string LicenseKey = oam::UnassignedName; bool postConfigureCleanup = false; bool systemCleanup = false; bool systemStop = false; string existingPMInstances = oam::UnassignedName; string existingUMInstances = oam::UnassignedName; - string UMprivateIPS = oam::UnassignedName; - string PMprivateIPS = oam::UnassignedName; + string UserModuleAutoSync = "n"; + int UserModuleSyncTime = 10; string instanceType; string amazonConfigFile = "/root/amazonConfig.xml"; @@ -285,14 +260,14 @@ int main(int argc, char *argv[]) while(true) { string ready = "n"; if ( systemCleanup ) - prompt1 = "WARNING - You are about the delete '" + systemName + "' cluster. Are you sure you want to do this? [y,n] (n) > "; + prompt = "WARNING - You are about the delete '" + systemName + "' cluster. Are you sure you want to do this? [y,n] (n) > "; else - prompt1 = "WARNING - You are about the stop the instances on '" + systemName + "' cluster. Are you sure you want to do this? [y,n] (n) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) ready = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "WARNING - You are about the stop the instances on '" + systemName + "' cluster. Are you sure you want to do this? [y,n] (n) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) ready = pcommand; + free(pcommand); + pcommand = 0; if (ready == "n") exit(0); } @@ -482,12 +457,12 @@ int main(int argc, char *argv[]) while(true) { string ready = "y"; - prompt1 = "Are these files installed and ready to continue [y,n] (y) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) ready = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Are these files installed and ready to continue [y,n] (y) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) ready = pcommand; + free(pcommand); + pcommand = 0; if (ready == "n") { cout << endl << "Please Install these files and re-run amazonInstaller. exiting..." << endl; exit(0); @@ -512,12 +487,12 @@ int main(int argc, char *argv[]) while(true) { - prompt1 = "Enter name with directory of the X.509 Certificate file (" + x509Cert + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) x509Cert = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter name with directory of the X.509 Certificate file (" + x509Cert + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) x509Cert = pcommand; + free(pcommand); + pcommand = 0; } ifstream File (x509Cert.c_str()); if (!File) @@ -528,12 +503,12 @@ int main(int argc, char *argv[]) while(true) { - prompt1 = "Enter name with directory of the X.509 Private Key file (" + x509PriKey + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) x509PriKey = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter name with directory of the X.509 Private Key file (" + x509PriKey + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) x509PriKey = pcommand; + free(pcommand); + pcommand = 0; } ifstream File (x509PriKey.c_str()); if (!File) @@ -544,12 +519,12 @@ int main(int argc, char *argv[]) while(true) { - prompt1 = "Enter the Amazon Region you are running in (" + region + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) region = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter the Amazon Region you are running in (" + region + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) region = pcommand; + free(pcommand); + pcommand = 0; } break; } @@ -578,12 +553,12 @@ int main(int argc, char *argv[]) cout << endl << "===== Setup System Configuration =====" << endl << endl; //system Name - prompt1 = "Enter System Name (" + systemName + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) systemName = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter System Name (" + systemName + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) systemName = pcommand; + free(pcommand); + pcommand = 0; } cout << endl << "There are 2 options when configuring the System Module Type: separate and combined" << endl << endl; @@ -593,14 +568,14 @@ int main(int argc, char *argv[]) string serverTypeInstall = "2"; while(true) { - prompt1 = "Select the type of System Module Install [1=separate, 2=combined] (2) > "; - pcommand1 = readline(prompt1.c_str()); + prompt = "Select the type of System Module Install [1=separate, 2=combined] (2) > "; + pcommand = readline(prompt.c_str()); cout << endl; - if (pcommand1) + if (pcommand) { - if (strlen(pcommand1) > 0) serverTypeInstall = pcommand1; - free(pcommand1); - pcommand1 = 0; + if (strlen(pcommand) > 0) serverTypeInstall = pcommand; + free(pcommand); + pcommand = 0; } if ( serverTypeInstall != "1" && serverTypeInstall != "2" ) { @@ -625,12 +600,12 @@ int main(int argc, char *argv[]) while(true) { umNumber = 1; - prompt1 = "Enter number of User Modules [1,1024] (" + oam.itoa(umNumber) + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) umNumber = atoi(pcommand1); - free(pcommand1); - pcommand1 = 0; + prompt = "Enter number of User Modules [1,1024] (" + oam.itoa(umNumber) + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) umNumber = atoi(pcommand); + free(pcommand); + pcommand = 0; } if ( umNumber < 1 || umNumber > oam::MAX_MODULE ) { @@ -642,12 +617,12 @@ int main(int argc, char *argv[]) cout << endl; //get exist um imstance list - prompt1 = "Enter List of Existing User Modules Instances (id1,id2,id3) or hit enter for none > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) existingPMInstances = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter List of Existing User Modules Instances (id1,id2,id3) or hit enter for none > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) existingPMInstances = pcommand; + free(pcommand); + pcommand = 0; } instanceType = oam.getEC2LocalInstanceType(); @@ -662,12 +637,13 @@ int main(int argc, char *argv[]) //get UserModuleInstanceType while(true) { - prompt1 = "Enter User Module Instance Type or hit enter to default to current type (" + instanceType + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) UserModuleInstanceType = pcommand1; - free(pcommand1); - pcommand1 = 0; + UserModuleInstanceType = instanceType; + prompt = "Enter User Module Instance Type or hit enter to default to current type (" + instanceType + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) UserModuleInstanceType = pcommand; + free(pcommand); + pcommand = 0; } } @@ -675,28 +651,65 @@ int main(int argc, char *argv[]) //get UserModuleSecurityGroup while(true) { - prompt1 = "Enter User Module Security Group or hit enter to default to current Security Group > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) UserModuleSecurityGroup = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter User Module Security Group or hit enter to default to current Security Group > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) UserModuleSecurityGroup = pcommand; + free(pcommand); + pcommand = 0; } break; } cout << endl; + //get UM auto sync info + while(true) { + prompt = "We recommend enabling User Module Auto Syncing if using multiple User Modules, you want to enable? [y,n] (y) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) UserModuleAutoSync = pcommand; + free(pcommand); + pcommand = 0; + } + + if ( UserModuleAutoSync == "n" ) { + break; + } + + if ( UserModuleAutoSync == "y") { + while (true) + { + prompt = "Default sync time is 10 minutes, change if you like [1,1440] (10) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) UserModuleSyncTime = atoi(pcommand); + free(pcommand); + pcommand = 0; + } + + if ( UserModuleSyncTime < 1 || UserModuleSyncTime > 1441 ) { + cout << endl << "ERROR: Invalid Sync Time '" + oam.itoa(UserModuleSyncTime) + "', please re-enter" << endl << endl; + continue; + } + break; + } + + break; + } + + cout << "Invalid Entry, please enter 'y' for yes or 'n' for no" << endl; + } cout << endl; //get UMEBS volume info while(true) { string answer = "y"; - prompt1 = "We recommend using EBS Volumes for User Module storage, you want to use EBS Volume? [y,n] (y) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) answer = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "We recommend using EBS Volumes for User Module storage, you want to use EBS Volume? [y,n] (y) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) answer = pcommand; + free(pcommand); + pcommand = 0; } if ( answer == "n" ) { @@ -709,12 +722,12 @@ int main(int argc, char *argv[]) if ( answer == "y") { while (true) { - prompt1 = "Default Volume size is 10gbs, change if you like [1,1024] (100) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) UMvolumeSize = atoi(pcommand1); - free(pcommand1); - pcommand1 = 0; + prompt = "Default Volume size is 10gbs, change if you like [1,1024] (100) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) UMvolumeSize = atoi(pcommand); + free(pcommand); + pcommand = 0; } if ( UMvolumeSize < 1 || UMvolumeSize > 1024 ) { @@ -742,12 +755,12 @@ int main(int argc, char *argv[]) while(true) { pmNumber = 1; - prompt1 = "Enter number of Performance Modules [1,1024] (" + oam.itoa(pmNumber) + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) pmNumber = atoi(pcommand1); - free(pcommand1); - pcommand1 = 0; + prompt = "Enter number of Performance Modules [1,1024] (" + oam.itoa(pmNumber) + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) pmNumber = atoi(pcommand); + free(pcommand); + pcommand = 0; } if ( pmNumber < 1 || pmNumber > oam::MAX_MODULE ) { @@ -759,24 +772,24 @@ int main(int argc, char *argv[]) cout << endl; //get exist pm imstance list - prompt1 = "Enter List of Existing Performance Modules Instances (id1,id2,id3) or hit enter for none > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) existingPMInstances = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter List of Existing Performance Modules Instances (id1,id2,id3) or hit enter for none > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) existingPMInstances = pcommand; + free(pcommand); + pcommand = 0; } cout << endl; //get EBS Volume info while(true) { string answer = "y"; - prompt1 = "We recommend using EBS Volumes for Performance Module storage, you want to use EBS Volumes? [y,n] (y) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) answer = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "We recommend using EBS Volumes for Performance Module storage, you want to use EBS Volumes? [y,n] (y) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) answer = pcommand; + free(pcommand); + pcommand = 0; } if ( answer == "n" ) { @@ -790,12 +803,12 @@ int main(int argc, char *argv[]) while (true) { cout << "The default setting is 1 EBS Volume (dbroot) per Performance Module." << endl; - prompt1 = "How many EBS Volumes do you want to assign to each Performance Module (1) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) dbrootPer = atoi(pcommand1); - free(pcommand1); - pcommand1 = 0; + prompt = "How many EBS Volumes do you want to assign to each Performance Module (1) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) dbrootPer = atoi(pcommand); + free(pcommand); + pcommand = 0; } if ( dbrootPer > 0 ) @@ -806,12 +819,12 @@ int main(int argc, char *argv[]) while (true) { - prompt1 = "Default Volume size is 100gbs, change if you like [1,1024] (100) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) PMvolumeSize = atoi(pcommand1); - free(pcommand1); - pcommand1 = 0; + prompt = "Default Volume size is 100gbs, change if you like [1,1024] (100) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) PMvolumeSize = atoi(pcommand); + free(pcommand); + pcommand = 0; } if ( PMvolumeSize < 1 || PMvolumeSize > 1024 ) { @@ -829,12 +842,12 @@ int main(int argc, char *argv[]) cout << endl; //get Elasitic UP list - prompt1 = "Enter List of Elastic IPs with Assigned ModuleName (x.x.x.x,um1,y.y.y.y,pm1) or hit enter for none > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) elasticIPs = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter List of Elastic IPs with Assigned ModuleName (x.x.x.x,um1,y.y.y.y,pm1) or hit enter for none > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) elasticIPs = pcommand; + free(pcommand); + pcommand = 0; } cout << endl; @@ -842,12 +855,12 @@ int main(int argc, char *argv[]) //get auto tagging while(true) { string answer = "n"; - prompt1 = "Instance and Volume Name Auto tagging is enabled, do you want to disable it? [y,n] (n) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) answer = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Instance and Volume Name Auto tagging is enabled, do you want to disable it? [y,n] (n) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) answer = pcommand; + free(pcommand); + pcommand = 0; } if ( answer == "n" ) { @@ -865,24 +878,24 @@ int main(int argc, char *argv[]) cout << endl; //get TotalUmMemory - prompt1 = "Enter TotalUmMemory size or hit enter to default standard size > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) TotalUmMemory = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter TotalUmMemory size or hit enter to default standard size > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) TotalUmMemory = pcommand; + free(pcommand); + pcommand = 0; } cout << endl; //get NumBlocksPct while(true) { - prompt1 = "Enter NumBlocksPct size or hit enter to default standard size [1,100] > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) NumBlocksPct = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter NumBlocksPct size or hit enter to default standard size [1,100] > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) NumBlocksPct = pcommand; + free(pcommand); + pcommand = 0; } if ( ( atoi(NumBlocksPct.c_str()) < 0 || atoi(NumBlocksPct.c_str()) > 100) && NumBlocksPct != oam::UnassignedName) @@ -892,16 +905,25 @@ int main(int argc, char *argv[]) } cout << endl; + //get LicenseKey + prompt = "Enter License Key or hit enter to default to standard 30 days > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) LicenseKey = pcommand; + free(pcommand); + pcommand = 0; + } + //check snmp Apps disable option snmpAppCheck(); //get root password - prompt1 = "Enter Root-Password used to access the Instances or hit enter to default to 'Calpont1' > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) { - if (strlen(pcommand1) > 0) rootPassword = pcommand1; - free(pcommand1); - pcommand1 = 0; + prompt = "Enter Root-Password used to access the Instances or hit enter to default to 'Calpont1' > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) rootPassword = pcommand; + free(pcommand); + pcommand = 0; } cout << endl; @@ -954,8 +976,7 @@ int main(int argc, char *argv[]) cout << "Error: x509PrivateFile and x509CertificationFile are the same file name in the config file, exiting" << endl; exit (1); } - - //standard config parmeters + try { systemName = amazonConfig->getConfig("SystemConfig", "SystemName"); systemType = amazonConfig->getConfig("SystemConfig", "SystemType"); @@ -973,36 +994,16 @@ int main(int argc, char *argv[]) UserModuleSecurityGroup = amazonConfig->getConfig("SystemConfig", "UserModuleSecurityGroup"); TotalUmMemory = amazonConfig->getConfig("SystemConfig", "TotalUmMemory"); NumBlocksPct = amazonConfig->getConfig("SystemConfig", "NumBlocksPct"); + LicenseKey = amazonConfig->getConfig("SystemConfig", "LicenseKey"); existingPMInstances = amazonConfig->getConfig("SystemConfig", "PerformanceModuleInstances"); existingUMInstances = amazonConfig->getConfig("SystemConfig", "UserModuleInstances"); + UserModuleAutoSync = amazonConfig->getConfig("SystemConfig", "UserModuleAutoSync"); + UserModuleSyncTime = atoi(amazonConfig->getConfig("SystemConfig", "UserModuleSyncTime").c_str()); autoTagging = amazonConfig->getConfig("SystemConfig", "AutoTagging"); region = amazonConfig->getConfig("SystemConfig", "Region"); - subnetID = amazonConfig->getConfig("SystemConfig", "SubNetID"); - VPCStartPrivateIP = amazonConfig->getConfig("SystemConfig", "VPCStartPrivateIP"); - UMprivateIPS = amazonConfig->getConfig("SystemConfig", "UserModulePrivateIP"); - PMprivateIPS = amazonConfig->getConfig("SystemConfig", "PerformanceModulePrivateIP"); - } - catch(...) - {} - - //hidden config paremeters - try { - localQuery = amazonConfig->getConfig("SystemConfig", "LocalQuery"); } catch(...) {} - - if ( localQuery.empty() ) - localQuery = "n"; - - try { - MySQLRep = amazonConfig->getConfig("SystemConfig", "MySQLRep"); - } - catch(...) - {} - - if ( MySQLRep.empty() ) - MySQLRep = "n"; } // validate config paramaters @@ -1072,7 +1073,7 @@ int main(int argc, char *argv[]) it != tokens.end(); ++it) { - ModuleIP elasticip; + ElasticIP elasticip; elasticip.IPaddress = *it; ++it; elasticip.moduleName = *it; @@ -1113,163 +1114,11 @@ int main(int argc, char *argv[]) } } - //get Private IPs if VPC subNet configured - vector umprivateip; - vector pmprivateip; - if ( subnetID != oam::UnassignedName ) - { - //set subnetID - try { - sysConfig->setConfig(InstallSection, "AmazonSubNetID", subnetID); - } - catch(...) - {} - - if ( VPCStartPrivateIP == "autoassign" ) - { - for ( int um = 0 ; um < umNumber ; um++ ) - { - umprivateip.push_back("autoassign"); - } - - for ( int pm = 0 ; pm < pmNumber ; pm++ ) - { - pmprivateip.push_back("autoassign"); - } - - //set VPCNextPrivateIP - try { - sysConfig->setConfig(InstallSection, "AmazonVPCNextPrivateIP", "autoassign"); - } - catch(...) - {} - } - else - { - if ( VPCStartPrivateIP == oam::UnassignedName ) - { - if ( UMprivateIPS == oam::UnassignedName ) - { - cout << endl << "ERROR: Invalid UM Private IP Address List / VPCStartPrivateIP" << endl; - exit(1); - } - else - { - boost::char_separator sep(","); - boost::tokenizer< boost::char_separator > tokens(UMprivateIPS, sep); - for ( boost::tokenizer< boost::char_separator >::iterator it = tokens.begin(); - it != tokens.end(); - ++it) - { - if (!oam.isValidIP(*it)) - { - cout << endl << "ERROR: Invalid UM Private IP Address: " << *it << endl; - exit(1); - } - - umprivateip.push_back(*it); - } - - if ( umNumber != (int) umprivateip.size() ) - { - cout << endl << "ERROR: Number of UMs doesn't match number of UM Private IPs Provided" << endl; - exit(1); - } - } - - if ( PMprivateIPS == oam::UnassignedName ) - { - cout << endl << "ERROR: Invalid PM Private IP Address List / VPCStartPrivateIP" << endl; - exit(1); - } - else - { - boost::char_separator sep(","); - boost::tokenizer< boost::char_separator > tokens1(PMprivateIPS, sep); - for ( boost::tokenizer< boost::char_separator >::iterator it = tokens1.begin(); - it != tokens1.end(); - ++it) - { - if (!oam.isValidIP(*it)) - { - cout << endl << "ERROR: Invalid PM Private IP Address: " << *it << endl; - exit(1); - } - - pmprivateip.push_back(*it); - } - - if ( pmNumber != (int) pmprivateip.size() ) - { - cout << endl << "ERROR: Number of PMs doesn't match number of PM Private IPs Provided" << endl; - exit(1); - } - } - } - else - { - if (!oam.isValidIP(VPCStartPrivateIP)) - { - cout << endl << "ERROR: Invalid Starting VPC Private IP Address: " << VPCStartPrivateIP << endl; - exit(1); - } - - string VPCNextPrivateIP = VPCStartPrivateIP; - - for ( int um = 0 ; um < umNumber ; um++ ) - { - umprivateip.push_back(VPCNextPrivateIP); - - try - { - VPCNextPrivateIP = oam.incrementIPAddress(VPCNextPrivateIP); - } - catch(...) - { - cout << endl << "ERROR: incrementIPAddress API error, check logs" << endl; - exit(1); - } - } - - for ( int pm = 0 ; pm < pmNumber ; pm++ ) - { - pmprivateip.push_back(VPCNextPrivateIP); - - try - { - VPCNextPrivateIP = oam.incrementIPAddress(VPCNextPrivateIP); - } - catch(...) - { - cout << endl << "ERROR: incrementIPAddress API error, check logs" << endl; - exit(1); - } - } - - //set VPCNextPrivateIP - try { - sysConfig->setConfig(InstallSection, "AmazonVPCNextPrivateIP", VPCNextPrivateIP); - } - catch(...) - {} - } - } - } - - try { - sysConfig->write(); - } - catch(...) - { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; - exit(1); - } - //get local instance name (pm1) localInstance = oam.getEC2LocalInstance(); if ( localInstance == "failed" || localInstance.empty() || localInstance == "") { - cout << endl << "ERROR: Failed to get Instance ID, check configuration settings like region. exiting..." << endl; + cout << endl << "ERROR: Failed to get Instance ID, double check configuration setting. exiting..." << endl; exit (1); } @@ -1277,10 +1126,13 @@ int main(int argc, char *argv[]) if (instanceType.empty() || instanceType == "" || instanceType == "failed") { - cout << endl << "ERROR: Failed to get Instance ID, check configuration settings like region. exiting..." << endl; + cout << endl << "ERROR: Failed to get Instance Type, double check configuration setting. exiting..." << endl; exit (1); } + if ( UserModuleInstanceType == oam::UnassignedName ) + UserModuleInstanceType = instanceType; + cout << "===== Setting up system '" + systemName + "' based on these settings ===== " << endl << endl; SystemSoftware systemsoftware; @@ -1288,25 +1140,8 @@ int main(int argc, char *argv[]) cout << "InfiniDB Version = " << systemsoftware.Version << "-" << systemsoftware.Release << endl; cout << "System Type = " << systemType << endl; - - if ( subnetID != oam::UnassignedName ) { - cout << "SubNet ID = " << subnetID << endl; - if ( VPCStartPrivateIP == oam::UnassignedName ) - { - if ( systemType == "separate" ) - cout << "User Modules VPC Private IPs = " << UMprivateIPS << endl; - - cout << "Performance Modules VPC Private IPs = " << PMprivateIPS << endl; - } - else - cout << "Starting VPC Private IP = " << VPCStartPrivateIP << endl; - } - if ( systemType == "separate" ) { - if ( UserModuleInstanceType == oam::UnassignedName ) - cout << "Number of User Modules = " << umNumber << " (" + instanceType + ")" << endl; - else - cout << "Number of User Modules = " << umNumber << " (" + UserModuleInstanceType + ")" << endl; + cout << "Number of User Modules = " << umNumber << " (" + UserModuleInstanceType + ")" << endl; if ( UserModuleSecurityGroup != oam::UnassignedName ) cout << "User Modules Instances Security Group = " << UserModuleSecurityGroup << endl; if ( existingUMInstances != oam::UnassignedName ) @@ -1321,25 +1156,6 @@ int main(int argc, char *argv[]) if ( existingPMInstances != oam::UnassignedName ) cout << "Using Performance Modules Instances = " << existingPMInstances << endl; - if ( localQuery == "y" ) { - cout << "Local Query Feature = enabled" << endl; - if ( systemType == "combined" && localQuery == "y" ) { - cout << "NOTE: Local Query Feature is not valid on a 'combined' system, turning off feature" << endl; - localQuery == "n"; - } - else - { - if ( MySQLRep == "n" ) - { - cout << "NOTE: Local Query Feature is enabled and requires MySQL Replication, enabling MySQL Replication Feature" << endl; - MySQLRep = "y"; - } - } - } - - if ( MySQLRep == "y" ) - cout << "MySQL Replication Feature = enabled" << endl; - cout << "Number of DBRoots per Performance Modules = " << dbrootPer << endl; if ( systemType == "separate" ) { @@ -1356,7 +1172,7 @@ int main(int argc, char *argv[]) if ( elasticiplist.size() > 0 ) { - ModuleIPList::iterator list9 = elasticiplist.begin(); + ElasticIPList::iterator list9 = elasticiplist.begin(); for (; list9 != elasticiplist.end() ; list9++) { cout << "Elastic IP Address " << (*list9).IPaddress << " assigned to " << (*list9).moduleName << endl; @@ -1397,6 +1213,15 @@ int main(int argc, char *argv[]) } } + if ( LicenseKey != oam::UnassignedName ) { + cout << "LicenseKey = " << LicenseKey << endl; + try { + sysConfig->setConfig(SystemSection, "Flags", LicenseKey); + } + catch(...) + {} + } + if ( systemType == "separate" ) { try { sysConfig->setConfig(InstallSection, "UMSecurityGroup", UserModuleSecurityGroup); @@ -1480,6 +1305,26 @@ int main(int argc, char *argv[]) catch(...) {} + // set rsync paramaters + if ( UserModuleAutoSync == "y" || UserModuleAutoSync == "n" ) { + if ( UserModuleSyncTime < 1 ) { + cout << "Error: UserModuleSyncTime is invalid (enter a value greater than 0), exiting" << endl; + exit (1); + } + } + else + { + cout << "Error: UserModuleAutoSync is invalid (enter 'y' or 'n'), exiting" << endl; + exit (1); + } + + try { + sysConfig->setConfig(InstallSection, "UMAutoSync", UserModuleAutoSync); + sysConfig->setConfig(InstallSection, "UMSyncTime", oam.itoa(UserModuleSyncTime)); + } + catch(...) + {} + try { sysConfig->write(); } @@ -1610,29 +1455,17 @@ int main(int argc, char *argv[]) } //launch um Instances - std::vector::iterator umprivatelist = umprivateip.begin(); for ( ; um < umNumber+1 ; um ++ ) { string module = "um" + oam.itoa(um); - ModuleIP moduleip; - moduleip.moduleName = module; - - if ( umprivateip.size() == 0 ) - moduleip.IPaddress = oam::UnassignedName; - else - { - moduleip.IPaddress = *umprivatelist; - umprivatelist++; - } - while(true) { if ( launchInstanceCount < numCores ) { launchInstanceCount++; pthread_t launchinstancethread; - int status = pthread_create (&launchinstancethread, NULL, (void*(*)(void*)) &launchInstanceThread, &moduleip); + int status = pthread_create (&launchinstancethread, NULL, (void*(*)(void*)) &launchInstanceThread, &module); if ( status != 0 ) { cout << "launchInstanceThread failed for " + module << endl; @@ -1680,29 +1513,17 @@ int main(int argc, char *argv[]) } //launch pm Instances - std::vector::iterator pmprivatelist = pmprivateip.begin(); for ( ; pm < pmNumber+1 ; pm ++ ) { string module = "pm" + oam.itoa(pm); - ModuleIP moduleip; - moduleip.moduleName = module; - - if ( pmprivateip.size() == 0 ) - moduleip.IPaddress = oam::UnassignedName; - else - { - moduleip.IPaddress = *pmprivatelist; - pmprivatelist++; - } - while(true) { if ( launchInstanceCount < numCores ) { launchInstanceCount++; pthread_t launchinstancethread; - int status = pthread_create (&launchinstancethread, NULL, (void*(*)(void*)) &launchInstanceThread, &moduleip); + int status = pthread_create (&launchinstancethread, NULL, (void*(*)(void*)) &launchInstanceThread, &module); if ( status != 0 ) { cout << "launchInstanceThread failed for " + module << endl; @@ -1862,7 +1683,7 @@ int main(int argc, char *argv[]) } //install rpms - system("rpm -ivh /root/infinidb-mysql*rpm /root/infinidb-storage-engine*rpm"); + system("rpm -ivh /root/calpont-mysql*rpm"); cout << endl; } @@ -1880,12 +1701,8 @@ int main(int argc, char *argv[]) {} //set for amazon cloud - string cloud = "amazon-ec2"; - if ( subnetID != oam::UnassignedName ) - cloud = "amazon-vpc"; - try { - sysConfig->setConfig(InstallSection, "Cloud", cloud); + sysConfig->setConfig(InstallSection, "Cloud", "amazon"); } catch(...) {} @@ -1903,7 +1720,7 @@ int main(int argc, char *argv[]) } int id = 1; - ModuleIPList::iterator list9 = elasticiplist.begin(); + ElasticIPList::iterator list9 = elasticiplist.begin(); for (; list9 != elasticiplist.end() ; list9++) { string moduleName = (*list9).moduleName; @@ -2158,7 +1975,7 @@ int main(int argc, char *argv[]) system(cmd.c_str()); cmd = "cp " + installDir + "/etc/Calpont.xml " + installDir + "/etc/Calpont.xml.rpmsave"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Error copying Calpont.xml to Calpont.xml.rpmsave" << endl; cleanupSystem(); } @@ -2170,10 +1987,6 @@ int main(int argc, char *argv[]) string postConfigureCMD = installDir + "/bin/postConfigure -n -p " + rootPassword; if ( postConfigureDebug ) postConfigureCMD = postConfigureCMD + " -d"; - if ( localQuery == "y" ) - postConfigureCMD = postConfigureCMD + " -lq"; - if ( MySQLRep == "y" ) - postConfigureCMD = postConfigureCMD + " -rep"; cout << endl << " Running command: " << postConfigureCMD << endl; @@ -2181,7 +1994,7 @@ int main(int argc, char *argv[]) cout << "Outputting to log file " + postConfigureOutFile << ", please wait..." << endl; string cmd = postConfigureCMD + " > " + postConfigureOutFile; int ret = system(cmd.c_str()); - if (WEXITSTATUS(ret) == 0 ) + if (ret == 0 ) cout << "postConfigure Successfully Completed, system is ready to use" << endl << endl; else { cout << "ERROR : postConfigure install error, check " << postConfigureOutFile << endl << endl; @@ -2198,7 +2011,7 @@ int main(int argc, char *argv[]) else { int ret = system(postConfigureCMD.c_str()); - if (WEXITSTATUS(ret) == 0 ) + if (ret == 0 ) cout << "postConfigure Successfully Completed, system is ready to use" << endl << endl; else { cout << endl << "ERROR : postConfigure install failure" << endl << endl; @@ -2236,13 +2049,13 @@ void snmpAppCheck() cout << "This would be used to receive SNMP Traps from InfiniDB, like a Network Control Center" << endl; cout << "Default to 0.0.0.0 to not enable snmptrap forwarding" << endl << endl; - prompt1 = "Enter IP Address(es) of NMS Server (0.0.0.0) > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) + prompt = "Enter IP Address(es) of NMS Server (0.0.0.0) > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { - if (strlen(pcommand1) > 0) NMSIPAddress = pcommand1; - free(pcommand1); - pcommand1 = 0; + if (strlen(pcommand) > 0) NMSIPAddress = pcommand; + free(pcommand); + pcommand = 0; } return; @@ -2251,13 +2064,13 @@ void snmpAppCheck() void setSystemName() { - prompt1 = "Enter System Name (" + systemName + ") > "; - pcommand1 = readline(prompt1.c_str()); - if (pcommand1) + prompt = "Enter System Name (" + systemName + ") > "; + pcommand = readline(prompt.c_str()); + if (pcommand) { - if (strlen(pcommand1) > 0) systemName = pcommand1; - free(pcommand1); - pcommand1 = 0; + if (strlen(pcommand) > 0) systemName = pcommand; + free(pcommand); + pcommand = 0; } } @@ -2283,7 +2096,7 @@ void setRootPassword() string cmd = installDir + "/bin/remote_command.sh " + ipAddress + " " + AMIrootPassword + " '/root/updatePassword.sh " + rootPassword + "' > /dev/null 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "ERROR: failed update of root password on " + module << endl; cleanupSystem(); } @@ -2298,7 +2111,7 @@ void setRootPassword() if ( module == "pm1" ) { string cmd = "/root/updatePassword.sh " + rootPassword + " > /dev/null 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "ERROR: failed update root of password on " + module << endl; cleanupSystem(); } @@ -2315,20 +2128,19 @@ void setRootPassword() string cmd = installDir + "/bin/remote_command.sh " + ipAddress + " " + AMIrootPassword + " '/root/updatePassword.sh " + rootPassword + "' > /dev/null 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "ERROR: failed update root of password on " + module << endl; cleanupSystem(); } } } -void launchInstanceThread(ModuleIP moduleip) +void launchInstanceThread(string module) { Oam oam; - //get module info - string moduleName = moduleip.moduleName; - string IPAddress = moduleip.IPaddress; + //local copies + string moduleName = module; //due to bad instances getting launched causing scp failures //have retry login around fail scp command where a instance will be relaunched @@ -2340,9 +2152,9 @@ void launchInstanceThread(ModuleIP moduleip) string instanceName; if ( moduleName.find("um") == 0 ) - instanceName = oam.launchEC2Instance(moduleName, IPAddress, UserModuleInstanceType, UserModuleSecurityGroup); + instanceName = oam.launchEC2Instance(moduleName, UserModuleInstanceType, UserModuleSecurityGroup); else - instanceName = oam.launchEC2Instance(moduleName, IPAddress); + instanceName = oam.launchEC2Instance(moduleName); if ( instanceName == "failed" ) { cout << " *** Failed to Launch an Instance for " + moduleName << ", will retry up to 5 times" << endl; @@ -2377,7 +2189,7 @@ void launchInstanceThread(ModuleIP moduleip) string cmd = installDir + "/bin/remote_scp_put.sh " + ipAddress + " " + AMIrootPassword + " " + x509Cert + " > /tmp/scp.log_" + instanceName; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) { + if (rtnCode == 0) { pass = true; break; } @@ -2400,7 +2212,7 @@ void launchInstanceThread(ModuleIP moduleip) string cmd = installDir + "/bin/remote_scp_put.sh " + ipAddress + " " + AMIrootPassword + " " + x509PriKey + " > /tmp/scp.log_" + instanceName; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) { + if (rtnCode == 0) { pass = true; break; } @@ -2437,7 +2249,7 @@ void launchInstanceThread(ModuleIP moduleip) if ( elasticiplist.size() > 0 ) { - ModuleIPList::iterator list9 = elasticiplist.begin(); + ElasticIPList::iterator list9 = elasticiplist.begin(); for (; list9 != elasticiplist.end() ; list9++) { if ( moduleName == (*list9).moduleName ) @@ -2851,7 +2663,7 @@ void cleanupSystem(bool terminate) if ( systemType == "combined" ) { cout << "----- Combined System Type Uninstall Calpont-MySQL Packages -----" << endl << endl; - system("rpm -e infinidb-mysql infinidb-storage-engine"); + system("rpm -e calpont-mysql calpont-mysql"); } cout << endl << "Cleanup finished, exiting" << endl << endl; diff --git a/oamapps/postConfigure/helpers.cpp b/oamapps/postConfigure/helpers.cpp index eeec8d8b..b7010fbe 100644 --- a/oamapps/postConfigure/helpers.cpp +++ b/oamapps/postConfigure/helpers.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - #include #include #include @@ -35,46 +18,14 @@ using namespace oam; #include "helpers.h" -extern string mysqlpw; +string mysqlpw = " "; string pwprompt = " "; -string masterLogFile = oam::UnassignedName; -string masterLogPos = oam::UnassignedName; -string prompt; - -const char* pcommand = 0; - extern string installDir; -extern bool noPrompting; namespace installer { -const char* callReadline(string prompt) -{ - if ( !noPrompting ) - { - const char* ret = readline(prompt.c_str()); - if( ret == 0 ) - exit(1); - return ret; - } - else - { - cout << prompt << endl; - return ""; - } -} - -void callFree(const char* ) -{ - if ( !noPrompting ) - free((void*)pcommand); - pcommand = 0; -} - - - bool waitForActive() { Oam oam; @@ -107,6 +58,8 @@ void dbrmDirCheck() Config* sysConfig = Config::makeConfig(); Config* sysConfigPrev = Config::makeConfig(fname); + char* pcommand = 0; + string dbrmroot = ""; string dbrmrootPrev = ""; @@ -209,12 +162,11 @@ void dbrmDirCheck() while(true) { string answer = "n"; - prompt = "Enter 'y' when you are ready to continue > "; - pcommand = callReadline(prompt.c_str()); + pcommand = readline("Enter 'y' when you are ready to continue > "); if (pcommand) { if (strlen(pcommand) > 0) answer = pcommand; - callFree(pcommand); + free(pcommand); pcommand = 0; } if ( answer == "y" ) @@ -230,13 +182,13 @@ void dbrmDirCheck() return; } -void mysqlSetup(bool EM) +void mysqlSetup() { Oam oam; string cmd; cmd = installDir + "/bin/post-mysqld-install --installdir=" + installDir; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Error running post-mysqld-install" << endl; //check for password set @@ -258,15 +210,7 @@ void mysqlSetup(bool EM) system(cmd.c_str()); if (oam.checkLogStatus("/tmp/idbmysql.log", "ERROR 1045") ) { - if ( mysqlpw == " " ) { - if ( noPrompting || EM ) { - cout << " *** MySQL password required, enter on command line, exiting..." << endl; - exit(1); - } - - mysqlpw = getpass(prompt.c_str()); - } - + mysqlpw = getpass(prompt.c_str()); mysqlpw = "'" + mysqlpw + "'"; pwprompt = "--password=" + mysqlpw; prompt = " *** Password incorrect, please re-enter MySQL password > "; @@ -293,7 +237,7 @@ void mysqlSetup(bool EM) cmd = installDir + "/bin/post-mysql-install " + pwprompt + " --installdir=" + installDir; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Error running post-mysql-install" << endl; return; @@ -306,7 +250,7 @@ void mysqlSetup(bool EM) * * ******************************************************************************************/ -int sendUpgradeRequest(int IserverTypeInstall, bool pmwithum) +int sendUpgradeRequest(int IserverTypeInstall) { Oam oam; @@ -346,8 +290,7 @@ int sendUpgradeRequest(int IserverTypeInstall, bool pmwithum) string moduleType = systemmoduletypeconfig.moduletypeconfig[i].ModuleType; if ( moduleType == "um" || - ( moduleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) || - ( moduleType == "pm" && pmwithum ) ) { + ( moduleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) ) { DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++) @@ -357,159 +300,21 @@ int sendUpgradeRequest(int IserverTypeInstall, bool pmwithum) try { oam.getModuleStatus((*pt).DeviceName, opState, degraded); - if (opState == oam::ACTIVE || - opState == oam::DEGRADED) { + if (opState == oam::ACTIVE) { returnStatus = sendMsgProcMon( (*pt).DeviceName, msg, requestID, 30 ); - if ( returnStatus != API_SUCCESS) { - cout << "ERROR: Error return in running the InfiniDB Upgrade, check /tmp/upgrade*.logs on " << (*pt).DeviceName << endl; + if ( returnStatus != API_SUCCESS) return returnStatus; - } - } - } - catch (exception& ex) - {} - } - } - } - return returnStatus; -} - -/****************************************************************************************** -* @brief sendReplicationRequest -* -* purpose: send Upgrade Request Msg to all ACTIVE UMs -* -* -******************************************************************************************/ -int sendReplicationRequest(int IserverTypeInstall, std::string password, std::string port) -{ - Oam oam; - - SystemModuleTypeConfig systemmoduletypeconfig; - - try{ - oam.getSystemConfig(systemmoduletypeconfig); - } - catch (exception& ex) - {} - - //get Primary (Master) UM - string masterModule = oam::UnassignedName; - try { - oam.getSystemConfig("PrimaryUMModuleName", masterModule); - } - catch(...) { - masterModule = oam::UnassignedName; - } - - if ( masterModule == oam::UnassignedName ) - { - // use default setting - masterModule = "um1"; - if ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) - masterModule = "pm1"; - } - - int returnStatus = oam::API_SUCCESS; - - bool masterDone = false; - for( unsigned int i = 0; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - - string moduleType = systemmoduletypeconfig.moduletypeconfig[i].ModuleType; - - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); ) - { - // we want to do master first - if ( ( (*pt).DeviceName == masterModule && !masterDone ) || - ( (*pt).DeviceName != masterModule && masterDone ) ) - { - int opState; - bool degraded; - try { - oam.getModuleStatus((*pt).DeviceName, opState, degraded); - - if (opState == oam::ACTIVE || - opState == oam::DEGRADED) { - if ( (*pt).DeviceName == masterModule ) - { - // set for Master MySQL DB distrubution to slaves - ByteStream msg1; - ByteStream::byte requestID = oam::MASTERDIST; - msg1 << requestID; - msg1 << password; - msg1 << "all"; // dist to all slave modules - - returnStatus = sendMsgProcMon( (*pt).DeviceName, msg1, requestID, 600 ); - - if ( returnStatus != API_SUCCESS) { - cout << "ERROR: Error return in running the MySQL Master DB Distribute, check /tmp/master-dist.logs on " << masterModule << endl; - return returnStatus; - } - - // set for master repl request - ByteStream msg; - requestID = oam::MASTERREP; - msg << requestID; - msg << mysqlpw; - - returnStatus = sendMsgProcMon( (*pt).DeviceName, msg, requestID, 30 ); - - if ( returnStatus != API_SUCCESS) { - cout << "ERROR: Error return in running the MySQL Master replication, check /tmp/master-rep*.logs on " << masterModule << endl; - return returnStatus; - } - - masterDone = true; - pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - } - else - { // set for slave repl request - ByteStream msg; - ByteStream::byte requestID = oam::SLAVEREP; - msg << requestID; - msg << mysqlpw; - - if ( masterLogFile == oam::UnassignedName || - masterLogPos == oam::UnassignedName ) - return API_FAILURE; - - msg << masterLogFile; - msg << masterLogPos; - msg << port; - - returnStatus = sendMsgProcMon( (*pt).DeviceName, msg, requestID, 30 ); - - if ( returnStatus != API_SUCCESS) { - cout << "ERROR: Error return in running the MySQL Slave replication, check /tmp/slave-rep*.logs on " << (*pt).DeviceName << endl; - return returnStatus; - } - - pt++; - } - } - else - { - cout << "ERROR: Module not Active, replication not done on " << (*pt).DeviceName << endl; - pt++; } } catch (exception& ex) {} } - else - pt++; } } return returnStatus; } - /****************************************************************************************** * @brief sendMsgProcMon * @@ -570,17 +375,11 @@ int sendMsgProcMon( std::string module, ByteStream msg, int requestID, int timeo receivedMSG >> returnACK; receivedMSG >> returnRequestID; receivedMSG >> requestStatus; - - if ( requestID == oam::MASTERREP ) - { - receivedMSG >> masterLogFile; - receivedMSG >> masterLogPos; - } if ( returnACK == oam::ACK && returnRequestID == requestID) { // ACK for this request returnStatus = requestStatus; - break; + break; } } else @@ -605,6 +404,7 @@ int sendMsgProcMon( std::string module, ByteStream msg, int requestID, int timeo return returnStatus; } + void checkFilesPerPartion(int DBRootCount, Config* sysConfig) { // check 'files per parition' with number of dbroots @@ -655,215 +455,10 @@ void checkFilesPerPartion(int DBRootCount, Config* sysConfig) } } - return; -} - -void checkMysqlPort( std::string& mysqlPort, Config* sysConfig, bool EM ) -{ - Oam oam; - - while(true) - { - string cmd = "netstat -na | grep -e :" + mysqlPort + "[[:space:]] | grep LISTEN > /tmp/mysqlport"; - - system(cmd.c_str()); - string fileName = "/tmp/mysqlport"; - ifstream oldFile (fileName.c_str()); - if (oldFile) { - oldFile.seekg(0, std::ios::end); - int size = oldFile.tellg(); - if ( size != 0 ) { - if ( noPrompting || EM ) { - cout << endl << "The mysqld port of '" + mysqlPort + "' is already in-use" << endl; - cout << "For No-prompt install, use the command line argument of 'port' to enter a different number" << endl; - exit(1); - } - - cout << "The mysqld port of '" + mysqlPort + "' is already in-use" << endl; - - while(true) - { - prompt = "Enter a different port number > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) mysqlPort = pcommand; - callFree(pcommand); - pcommand = 0; - } - - if ( atoi(mysqlPort.c_str()) < 1000 || atoi(mysqlPort.c_str()) > 9999) - { - cout << " ERROR: Invalid MySQL Port ID supplied, must be between 1000-9999" << endl; - } - else - break; - } - } - else - { - cout << endl; - - try { - sysConfig->setConfig("Installation", "MySQLPort", mysqlPort); - } - catch(...) - {} - - if ( !writeConfig(sysConfig) ) { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; - exit(1); - } - - break; - } - } - else - break; - } - - // set mysql password - oam.changeMyCnf( "port", mysqlPort ); -} - -void checkSystemMySQLPort(std::string& mysqlPort, Config* sysConfig, std::string USER, std::string password, ChildModuleList childmodulelist, int IserverTypeInstall, bool pmwithum, bool EM) -{ - Oam oam; - - bool inUse = false; - - while(true) - { - string localnetstat = "netstat -na | grep -e :" + mysqlPort + "[[:space:]] | grep LISTEN > /tmp/mysqlport"; - string remotenetstat = "netstat -na | grep -e :" + mysqlPort + "[[:space:]] | grep LISTEN"; - - //first check local mysql, if needed - if ( ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) || - ( ( IserverTypeInstall != oam::INSTALL_COMBINE_DM_UM_PM ) && pmwithum ) ) - { - system(localnetstat.c_str()); - string fileName = "/tmp/mysqlport"; - ifstream oldFile (fileName.c_str()); - - if (oldFile) { - oldFile.seekg(0, std::ios::end); - int size = oldFile.tellg(); - if ( size != 0 ) { - if ( noPrompting || EM ) { - cout << endl << "The mysqld port of '" + mysqlPort + "' is already in-use" << endl; - cout << "For No-prompt install, use the command line argument of 'port' to enter a different number" << endl; - exit(1); - } - else - inUse = true; - } - } - } - - // if not inuse by local, go check remote servers - if ( !inUse ) - { - ChildModuleList::iterator list1 = childmodulelist.begin(); - for (; list1 != childmodulelist.end() ; list1++) - { - string remoteModuleName = (*list1).moduleName; - string remoteModuleIP = (*list1).moduleIP; - string remoteHostName = (*list1).hostName; - string remoteModuleType = remoteModuleName.substr(0,MAX_MODULE_TYPE_SIZE); - - if ( remoteModuleType == "um" || - (remoteModuleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM) || - (remoteModuleType == "pm" && pmwithum) ) - { - - string cmd = installDir + "/bin/remote_command_verify.sh " + remoteModuleIP + " " + " " + USER + " " + password + " '" + remotenetstat + "' tcp error 5 0 > /dev/null 2>&1"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) { - if ( noPrompting || EM ) { - cout << endl << "The mysqld port of '" + mysqlPort + "' is already in-use on " << remoteModuleName << endl; - cout << "For No-prompt install, use the command line argument of 'port' to enter a different number" << endl; - cout << "exiting..." << endl; - exit(1); - } - else - { - inUse = true; - break; - } - } - } - } - } - - if ( inUse ) - { - cout << endl << "The mysqld port of '" + mysqlPort + "' is already in-use" << endl; - - while(true) - { - prompt = "Enter a different port number > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) mysqlPort = pcommand; - callFree(pcommand); - pcommand = 0; - } - - if ( atoi(mysqlPort.c_str()) < 1000 || atoi(mysqlPort.c_str()) > 9999) - { - cout << " ERROR: Invalid MySQL Port ID supplied, must be between 1000-9999" << endl; - } - else - break; - } - - inUse = false; - } - else - { - cout << endl; - - try { - sysConfig->setConfig("Installation", "MySQLPort", mysqlPort); - } - catch(...) - {} - - if ( !writeConfig(sysConfig) ) { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; - exit(1); - } - - break; - } - } - - // set mysql password - oam.changeMyCnf( "port", mysqlPort ); return; } -/* - * writeConfig - */ -bool writeConfig( Config* sysConfig ) -{ - for ( int i = 0 ; i < 3 ; i++ ) - { - try { - sysConfig->write(); - return true; - } - catch(...) - {} - } - - return false; -} - - } diff --git a/oamapps/postConfigure/helpers.h b/oamapps/postConfigure/helpers.h index 8b1f717e..39a52403 100644 --- a/oamapps/postConfigure/helpers.h +++ b/oamapps/postConfigure/helpers.h @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - #ifndef HELPERS_H__ #define HELPERS_H__ @@ -23,32 +6,12 @@ using namespace messageqcpp; namespace installer { - -typedef struct Child_Module_struct -{ - std::string moduleName; - std::string moduleIP; - std::string hostName; -} ChildModule; - -typedef std::vector ChildModuleList; - extern bool waitForActive(); extern void dbrmDirCheck(); -extern void mysqlSetup(bool EM = false); +extern void mysqlSetup(); extern int sendMsgProcMon( std::string module, ByteStream msg, int requestID, int timeout ); -extern int sendUpgradeRequest(int IserverTypeInstall, bool pmwithum); -extern int sendReplicationRequest(int IserverTypeInstall, std::string password, std::string mysqlPort); +extern int sendUpgradeRequest(int IserverTypeInstall); extern void checkFilesPerPartion(int DBRootCount, Config* sysConfig); -extern void checkMysqlPort( string& mysqlPort, Config* sysConfig, bool EM = false); -extern bool writeConfig(Config* sysConfig); -extern void checkSystemMySQLPort(std::string& mysqlPort, Config* sysConfig, std::string USER, std::string password, ChildModuleList childmodulelist, int IserverTypeInstall, bool pmwithum, bool EM = false); -extern const char* callReadline(string prompt); -extern void callFree(const char* ); - - - - } #endif diff --git a/oamapps/postConfigure/installer.cpp b/oamapps/postConfigure/installer.cpp index 4f94f4e5..80530120 100644 --- a/oamapps/postConfigure/installer.cpp +++ b/oamapps/postConfigure/installer.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** * $Id: installer.cpp 64 2006-10-12 22:21:51Z dhill $ * @@ -71,13 +54,14 @@ bool makeBASH(); bool makeModuleFile(string moduleName, string parentOAMModuleName); bool updateProcessConfig(int serverTypeInstall); bool makeRClocal(string moduleName, int IserverTypeInstall); +bool createDbrootDirs(string DBRootStorageType); bool uncommentCalpontXml( string entry); +bool writeConfig(Config* sysConfig); extern string pwprompt; +extern string mysqlpw; string installDir; -bool noPrompting; -string mysqlpw = " "; int main(int argc, char *argv[]) { @@ -104,50 +88,36 @@ int main(int argc, char *argv[]) string DBRootStorageType; - if (argc < 12) + if (argc < 10) { cerr << "installer: ERROR: not enough arguments" << endl; exit(1); } - string calpont_rpm1 = argv[1]; - string calpont_rpm2 = argv[2]; - string calpont_rpm3 = argv[3]; - string mysql_rpm = argv[4]; - string mysqld_rpm = argv[5]; - string installType = argv[6]; - string password = argv[7]; - string reuseConfig = argv[8]; - nodeps = argv[9]; - mysqlpw = argv[10]; - installer_debug = argv[11]; - if (argc >= 13) - installDir = argv[12]; + string calpont_rpm = argv[1]; + string mysql_rpm = argv[2]; + string mysqld_rpm = argv[3]; + string installType = argv[4]; + string password = argv[5]; + string reuseConfig = argv[6]; + nodeps = argv[7]; + mysqlpw = argv[8]; + installer_debug = argv[9]; + if (argc >= 11) + installDir = argv[10]; else installDir = "/usr/local/Calpont"; - ofstream file("/dev/null"); - - //save cout stream buffer - streambuf* strm_buffer = cout.rdbuf(); - - // redirect cout to /dev/null - cout.rdbuf(file.rdbuf()); - - cout << calpont_rpm1 << endl; - cout << calpont_rpm2 << endl; - cout << calpont_rpm3 << endl; - cout << mysql_rpm << endl; - cout << mysqld_rpm << endl; - cout << installType << endl; - cout << password << endl; - cout << reuseConfig << endl; - cout << nodeps << endl; - cout << mysqlpw << endl; - cout << installer_debug << endl; - cout << installDir << endl; - - // restore cout stream buffer - cout.rdbuf (strm_buffer); +// cout << calpont_rpm << endl; +// cout << mysql_rpm << endl; +// cout << mysqld_rpm << endl; +// cout << installType << endl; +// cout << password << endl; +// cout << reuseConfig << endl; +// cout << nodeps << endl; +// cout << mysqlpw << endl; +// cout << installer_debug << endl; +// cout << installDir << endl; + sleep(1); if ( mysqlpw == "dummymysqlpw" ) mysqlpw = " "; @@ -209,22 +179,9 @@ int main(int argc, char *argv[]) // are we using settings from previous config file? if ( reuseConfig == "n" ) { try { - DBRootStorageType = sysConfig->getConfig(InstallSection, "DBRootStorageType"); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the InfiniDB System Configuration file" << endl; - return false; - } - - string numBlocksPct = "50"; - if ( DBRootStorageType == "hdfs") - numBlocksPct = "25"; + sysConfig->setConfig("DBBC", "NumBlocksPct", "50"); - try { - sysConfig->setConfig("DBBC", "NumBlocksPct", numBlocksPct); - - cout << endl << "NOTE: Setting 'NumBlocksPct' to " << numBlocksPct << "%" << endl; + cout << endl << "NOTE: Setting 'NumBlocksPct' to 50%" << endl; } catch(...) { @@ -258,26 +215,7 @@ int main(int argc, char *argv[]) else value = "16G"; - string percent = "25"; - if ( DBRootStorageType == "hdfs") - { - percent = "12"; - - if ( value == "512M") - value = "256M"; - else if ( value == "1G" ) - value = "512M"; - else if ( value == "2G" ) - value = "1G"; - else if ( value == "4G" ) - value = "2G"; - else if ( value == "8G") - value = "4G"; - else if ( value == "16G" ) - value = "8G"; - } - - cout << " Setting 'TotalUmMemory' to " << percent << "% of total memory (Combined Server Install maximum value is 16G). Value set to " << value << endl; + cout << " Setting 'TotalUmMemory' to 25% of total memory. Value set to " << value << endl; try { sysConfig->setConfig("HashJoin", "TotalUmMemory", value); @@ -609,9 +547,9 @@ int main(int argc, char *argv[]) temppwprompt = "none"; cout << endl << "----- Performing Uninstall on Module '" + remoteModuleName + "' -----" << endl << endl; - cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm1 + " " + calpont_rpm2 + " " + calpont_rpm3 + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + temppwprompt + " " + installer_debug; + cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + temppwprompt + " " + installer_debug; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR: returned from user_installer.sh" << endl; exit(1); } @@ -619,10 +557,10 @@ int main(int argc, char *argv[]) else { // do a binary package install cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + - password + " " + calpont_rpm1 + " " + remoteModuleType + " " + installType + " " + + password + " " + calpont_rpm + " " + remoteModuleType + " " + installType + " " + serverTypeInstall + " " + installer_debug + " " + installDir; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR: returned from binary_installer.sh" << endl; exit(1); } @@ -635,9 +573,9 @@ int main(int argc, char *argv[]) if ( packageType != "binary" ) { //run remote installer script cout << endl << "----- Performing Uninstall on Module '" + remoteModuleName + "' -----" << endl << endl; - cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm1 + " " + calpont_rpm2 + " " + calpont_rpm3 + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + installer_debug; + cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + installer_debug; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR returned from performance_installer.sh" << endl; exit(1); } @@ -645,10 +583,10 @@ int main(int argc, char *argv[]) else { // do a binary package install cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + - " " + password + " " + calpont_rpm1 + " " + remoteModuleType + " " + installType + " " + + " " + password + " " + calpont_rpm + " " + remoteModuleType + " " + installType + " " + serverTypeInstall + " " + installer_debug + " " + installDir; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR returned from binary_installer.sh" << endl; exit(1); } @@ -706,9 +644,9 @@ int main(int argc, char *argv[]) temppwprompt = "none"; cout << endl << "----- Performing Install on Module '" + remoteModuleName + "' -----" << endl << endl; - cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm1 + " " + calpont_rpm2 + " " + calpont_rpm3 + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + temppwprompt + " " + installer_debug; + cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + temppwprompt + " " + installer_debug; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR returned from user_installer.sh" << endl; exit(1); } @@ -716,10 +654,10 @@ int main(int argc, char *argv[]) else { // do a binary package install cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + - password + " " + calpont_rpm1 + " " + remoteModuleType + " " + installType + " " + + password + " " + calpont_rpm + " " + remoteModuleType + " " + installType + " " + serverTypeInstall + " " + installer_debug + " " + installDir; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR returned from binary_installer.sh" << endl; exit(1); } @@ -732,9 +670,9 @@ int main(int argc, char *argv[]) //run remote installer script if ( packageType != "binary" ) { cout << endl << "----- Performing Install on Module '" + remoteModuleName + "' -----" << endl << endl; - cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm1 + " " + calpont_rpm2 + " " + calpont_rpm3 + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + installer_debug; + cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpont_rpm + " " + mysql_rpm + " " + mysqld_rpm + " " + installType + " " + packageType + " " + nodeps + " " + installer_debug; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR returned from performance_installer.sh" << endl; exit(1); } @@ -742,10 +680,10 @@ int main(int argc, char *argv[]) else { // do a binary package install cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + - " " + password + " " + calpont_rpm1 + " " + remoteModuleType + " " + installType + + " " + password + " " + calpont_rpm + " " + remoteModuleType + " " + installType + " " + serverTypeInstall + " " + installer_debug + " " + installDir; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "ERROR returned from binary_installer.sh" << endl; exit(1); } @@ -783,7 +721,7 @@ int main(int argc, char *argv[]) //run remote command script cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '" + idbstartcmd + "' " + installer_debug; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "error with running remote_command.sh" << endl; } @@ -799,7 +737,7 @@ int main(int argc, char *argv[]) // // perform single-server install from auto-installer // - if ( calpont_rpm1 != "dummy.rpm" ) { + if ( calpont_rpm != "dummy.rpm" ) { //run the mysql / mysqld setup scripts cout << endl << "Running the InfiniDB MySQL setup scripts" << endl << endl; @@ -810,7 +748,7 @@ int main(int argc, char *argv[]) //start on local module int rtnCode = system(idbstartcmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Error starting InfiniDB local module" << endl; else cout << "Start InfiniDB request successful" << endl; @@ -857,8 +795,7 @@ int main(int argc, char *argv[]) cout.flush(); //send message to procmon's to run upgrade script - bool pmwithum = false; - int status = sendUpgradeRequest(IserverTypeInstall, pmwithum); + int status = sendUpgradeRequest(IserverTypeInstall); if ( status != 0 ) { cout << "ERROR: Error return in running the upgrade script, check /tmp/upgrade.log" << endl; @@ -1276,5 +1213,22 @@ bool uncommentCalpontXml( string entry) return true; } +/* + * writeConfig + */ +bool writeConfig( Config* sysConfig ) +{ + for ( int i = 0 ; i < 3 ; i++ ) + { + try { + sysConfig->write(); + return true; + } + catch(...) + {} + } + + return false; +} // vim:ts=4 sw=4: diff --git a/oamapps/postConfigure/mycnfUpgrade.cpp b/oamapps/postConfigure/mycnfUpgrade.cpp deleted file mode 100644 index 7237fc71..00000000 --- a/oamapps/postConfigure/mycnfUpgrade.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/****************************************************************************************** -* $Id: mycnfUpgrade.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "liboamcpp.h" -#include "installdir.h" - -using namespace std; -using namespace oam; - -int main(int argc, char *argv[]) -{ - Oam oam; - - //check for port argument - string mysqlPort; - if (argc > 1) { - mysqlPort = argv[1]; - - // set mysql password - oam.changeMyCnf( "port", mysqlPort ); - exit (0); - } - - //my.cnf file - string mycnfFile = startup::StartUp::installDir() + "/mysql/my.cnf"; - ifstream mycnffile (mycnfFile.c_str()); - if (!mycnffile) { - cerr << "mycnfUpgrade - my.cnf file not found: " << mycnfFile << endl; - exit (1); - } - - //my.cnf.rpmsave file - string mycnfsaveFile = startup::StartUp::installDir() + "/mysql/my.cnf.rpmsave"; - ifstream mycnfsavefile (mycnfsaveFile.c_str()); - if (!mycnfsavefile) { - cerr << "mycnfUpgrade - my.cnf.rpmsave file not found: " << mycnfsaveFile << endl; - exit (1); - } - - //include arguments file - string includeFile = startup::StartUp::installDir() + "/bin/myCnf-include-args.text"; - ifstream includefile (includeFile.c_str()); - if (!includefile) { - cerr << "mycnfUpgrade - my.cnf include argument file not found: " << includeFile << endl; - exit (1); - } - - //exclude arguments file - string excludeFile = startup::StartUp::installDir() + "/bin/myCnf-exclude-args.text"; - ifstream excludefile (excludeFile.c_str()); - if (!excludefile) { - cerr << "mycnfUpgrade - my.cnf exclude argument file not found: " << excludefile << endl; - exit (1); - } - - //go though include list - char line[200]; - string includeArg; - while (includefile.getline(line, 200)) - { - includeArg = line; - - //see if in my.cnf.rpmsave - ifstream mycnfsavefile (mycnfsaveFile.c_str()); - char line[200]; - string oldbuf; - while (mycnfsavefile.getline(line, 200)) - { - oldbuf = line; - string::size_type pos = oldbuf.find(includeArg,0); - if ( pos != string::npos ) { - //check if this is commented out - if ( line[0] != '#' ) - { - // no, find in my.cnf and replace - - ifstream mycnffile (mycnfFile.c_str()); - vector lines; - char line1[200]; - string newbuf; - while (mycnffile.getline(line1, 200)) - { - newbuf = line1; - string::size_type pos = newbuf.find(includeArg,0); - if ( pos != string::npos ) - newbuf = oldbuf; - - //output to temp file - lines.push_back(newbuf); - } - - //write out a new my.cnf - mycnffile.close(); - unlink (mycnfFile.c_str()); - ofstream newFile (mycnfFile.c_str()); - - //create new file - int fd = open(mycnfFile.c_str(), O_RDWR|O_CREAT, 0666); - - copy(lines.begin(), lines.end(), ostream_iterator(newFile, "\n")); - newFile.close(); - - close(fd); - } - - break; - } - } - } - - exit (0); -} -// vim:ts=4 sw=4: - diff --git a/oamapps/postConfigure/patchInstaller.cpp b/oamapps/postConfigure/patchInstaller.cpp index 37c1c56b..5c33f8bd 100644 --- a/oamapps/postConfigure/patchInstaller.cpp +++ b/oamapps/postConfigure/patchInstaller.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** * $Id: patchInstaller.cpp 64 2006-10-12 22:21:51Z dhill $ * diff --git a/oamapps/postConfigure/postConfigure.cpp b/oamapps/postConfigure/postConfigure.cpp index bb6e1077..91360d11 100644 --- a/oamapps/postConfigure/postConfigure.cpp +++ b/oamapps/postConfigure/postConfigure.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** * $Id: postConfigure.cpp 64 2006-10-12 22:21:51Z dhill $ * @@ -51,7 +34,6 @@ #include #include #include -#include #include #include @@ -71,6 +53,14 @@ using namespace snmpmanager; #include "helpers.h" using namespace installer; +typedef struct Child_Module_struct +{ + std::string moduleName; + std::string moduleIP; + std::string hostName; +} ChildModule; + +typedef std::vector ChildModuleList; typedef struct DBRoot_Module_struct { @@ -90,6 +80,8 @@ typedef struct Performance_Module_struct typedef std::vector PerformanceModuleList; + + void snmpAppCheck(); void offLineAppCheck(); bool setOSFiles(string parentOAMModuleName, int serverTypeInstall); @@ -102,6 +94,7 @@ bool makeModuleFile(string moduleName, string parentOAMModuleName); bool updateProcessConfig(int serverTypeInstall); bool uncommentCalpontXml( string entry); bool makeRClocal(string moduleType, string moduleName, int IserverTypeInstall); +bool writeConfig(Config* sysConfig); bool createDbrootDirs(string DBRootStorageType); bool pkgCheck(); bool storageSetup(string cloud); @@ -113,17 +106,17 @@ bool singleServerDBrootSetup(); bool copyFstab(string moduleName); bool copyX509files(); -void remoteInstallThread(void *); +void remoteInstallThread(string command); +int remoteInstallCount = 0; -string calpontPackage1; -string calpontPackage2; -string calpontPackage3; +string calpontPackage; string mysqlPackage; string mysqldPackage; +const char* pcommand = 0; + string parentOAMModuleName; int pmNumber = 0; -int umNumber = 0; string DBRootStorageLoc; string DBRootStorageType; @@ -136,6 +129,7 @@ Config* sysConfig = Config::makeConfig(); string SystemSection = "SystemConfig"; string InstallSection = "Installation"; string ModuleSection = "SystemModuleConfig"; +string prompt; string serverTypeInstall; int IserverTypeInstall; string parentOAMModuleIPAddr; @@ -148,40 +142,35 @@ string oldFileName; string x509Cert; string x509PriKey; string glusterCopies; -string glusterInstalled = "n"; -string hadoopInstalled = "n"; -string home; -string mysqlPort = oam::UnassignedName; +string glusterUsed = "n"; -bool noPrompting = false; +extern string pwprompt; +bool noPrompting; bool rootUser = true; string USER = "root"; -bool hdfs = false; -bool gluster = false; -bool pmwithum = false; -bool mysqlRep = false; -string MySQLRep = "n"; -string PMwithUM = "n"; -bool EM = false; - -string DataFileEnvFile; string installDir; -extern string pwprompt; -string mysqlpw = " "; - -extern const char* pcommand; -extern string prompt; +const char* callReadline(string prompt) +{ + if ( !noPrompting ) + return readline(prompt.c_str()); + else { + cout << prompt << endl; + return ""; + } +} -/* create thread argument struct for thr_func() */ -typedef struct _thread_data_t { - std::string command; -} thread_data_t; +void callFree(const char* ) +{ + if ( !noPrompting ) + free((void*)pcommand); + pcommand = 0; +} int main(int argc, char *argv[]) { - Oam oam; + Oam oam; string parentOAMModuleHostName; ChildModuleList childmodulelist; ChildModuleList niclist; @@ -194,16 +183,34 @@ int main(int argc, char *argv[]) bool startOfflinePrompt = false; noPrompting = false; string password; + string mysqlpw = " "; -// struct sysinfo myinfo; + struct sysinfo myinfo; // hidden options // -f for force use nodeps on rpm install // -o to prompt for process to start offline - // -em for Enterprise Manager + + //check if license has expired + oam::LicenseKeyChecker keyChecker; + + bool keyGood = true; + try { + keyGood = keyChecker.isGood(); + } + catch(...) + { + keyGood = false; + } + + if (!keyGood) + { + cout << endl << "Your License trial period has expired, please contact Calpont Customer Support." << endl; + exit (1); + } //default - installDir = installDir + ""; + installDir = "/usr/local/Calpont"; //see if we can determine our own location ostringstream oss; oss << "/proc/" << getpid() << "/exe"; @@ -240,8 +247,8 @@ int main(int argc, char *argv[]) if (p && *p) USER = p; - for( int i = 1; i < argc; i++ ) - { + for( int i = 1; i < argc; i++ ) + { if( string("-h") == argv[i] ) { cout << endl; cout << "This is the Calpont InfiniDB System Configuration and Installation tool." << endl; @@ -257,26 +264,21 @@ int main(int argc, char *argv[]) cout << " Enter one of the options within [], if available, or" << endl; cout << " Enter a new value" << endl << endl; cout << endl; - cout << "Usage: postConfigure [-h][-c][-n][-p][-mp][-s][-lq][-rep][-port]" << endl; + cout << "Usage: postConfigure [-h][-c][-n][-p][-mp][-s]" << endl; cout << " -h Help" << endl; cout << " -c Config File to use to extract configuration data, default is Calpont.xml.rpmsave" << endl; cout << " -n Install with no prompting" << endl; cout << " -p Password, used with no-prompting option" << endl; cout << " -mp MySQL Password, can be used with no-prompting option" << endl; cout << " -s Single Threaded Remote Install" << endl; - cout << " -lq Enable Local Query Feature" << endl; - cout << " -rep Enable MySQL Replication" << endl; - cout << " -port MySQL Port Address" << endl; exit (0); } - else if( string("-s") == argv[i] ) + else if( string("-s") == argv[i] ) thread_remote_installer = "0"; else if( string("-f") == argv[i] ) nodeps = "--nodeps"; else if( string("-o") == argv[i] ) startOfflinePrompt = true; - else if( string("-em") == argv[i] ) - EM = true; else if( string("-c") == argv[i] ) { i++; if (i >= argc ) { @@ -312,8 +314,6 @@ int main(int argc, char *argv[]) cout << " ERROR: Valid MySQL Password not provided" << endl; exit (1); } - if ( mysqlpw == "dummymysqlpw" ) - mysqlpw = " "; } else if( string("-n") == argv[i] ) noPrompting = true; @@ -329,33 +329,6 @@ int main(int argc, char *argv[]) exit (1); } } - else if( string("-lq") == argv[i] ) { - pmwithum = true; - PMwithUM = "y"; - } - else if( string("-rep") == argv[i] ) { - mysqlRep = true; - MySQLRep = "y"; - } - else if( string("-port") == argv[i] ) { - i++; - if (i >= argc ) { - cout << " ERROR: MySQL Port ID not supplied" << endl; - exit (1); - } - mysqlPort = argv[i]; - if ( atoi(mysqlPort.c_str()) < 1000 || atoi(mysqlPort.c_str()) > 9999) - { - cout << " ERROR: Invalid MySQL Port ID supplied, must be between 1000-9999" << endl; - exit (1); - } - } - else - { - cout << " ERROR: Invalid Argument = " << argv[i] << endl; - cout << " Usage: postConfigure [-h][-c][-n][-p][-mp][-s][-lq][-rep][-port]" << endl; - exit (1); - } } if (installDir[0] != '/') @@ -366,7 +339,7 @@ int main(int argc, char *argv[]) oldFileName = installDir + "/etc/Calpont.xml.rpmsave"; - home = "/root"; + string home = "/root"; if (!rootUser) { char* p= getenv("HOME"); if (p && *p) @@ -427,7 +400,7 @@ int main(int argc, char *argv[]) try { string InitialInstallFlag = sysConfig->getConfig(InstallSection, "InitialInstallFlag"); if ( InitialInstallFlag == "y" ) { - cmd = installDir + "/bin/pre-uninstall --quiet > /dev/null 2>&1"; + cmd = installDir + "/bin/pre-uninstall skipxml > /dev/null 2>&1"; system(cmd.c_str()); } } @@ -445,36 +418,6 @@ int main(int argc, char *argv[]) exit(1); } - //check mysql port changes - string MySQLPort; - try { - MySQLPort = sysConfig->getConfig(InstallSection, "MySQLPort"); - } - catch(...) - {} - - if ( mysqlPort == oam::UnassignedName ) - { - if ( MySQLPort.empty() || MySQLPort == "" ) { - mysqlPort = "3306"; - try { - sysConfig->setConfig(InstallSection, "MySQLPort", "3306"); - } - catch(...) - {} - } - else - mysqlPort = MySQLPort; - } - else - { // mysql port was providing on command line - try { - sysConfig->setConfig(InstallSection, "MySQLPort", mysqlPort); - } - catch(...) - {} - } - cout << endl; cout << "===== Setup System Server Type Configuration =====" << endl << endl; @@ -522,7 +465,7 @@ int main(int argc, char *argv[]) // within the same second which means the changes that are about to happen // when Calpont.xml gets overwritten will be ignored because of the Config // instance won't know to reload - sleep(2); + sleep(2); cmd = "rm -f " + installDir + "/etc/Calpont.xml.installSave > /dev/null 2>&1"; system(cmd.c_str()); @@ -544,10 +487,6 @@ int main(int argc, char *argv[]) exit(1); } - if (hdfs || !rootUser) - if( !updateBash() ) - cout << "updateBash error" << endl; - // setup storage if (!singleServerDBrootSetup()) { @@ -576,8 +515,6 @@ int main(int argc, char *argv[]) if (startOfflinePrompt) offLineAppCheck(); - checkMysqlPort(mysqlPort, sysConfig, EM); - if ( !writeConfig(sysConfig) ) { cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; exit(1); @@ -585,7 +522,7 @@ int main(int argc, char *argv[]) cout << endl << "===== Performing Configuration Setup and InfiniDB Startup =====" << endl; - cmd = installDir + "/bin/installer dummy.rpm dummy.rpm dummy.rpm dummy.rpm dummy.rpm initial dummy " + reuseConfig + " --nodeps ' ' 1 " + installDir; + cmd = installDir + "/bin/installer dummy.rpm dummy.rpm dummy.rpm initial dummy " + reuseConfig + " --nodeps ' ' 1 " + installDir; system(cmd.c_str()); exit(0); } @@ -624,45 +561,19 @@ int main(int argc, char *argv[]) // cout << endl; - string cloud = oam::UnassignedName; - string amazonSubNet = oam::UnassignedName; - bool amazonEC2 = false; - bool amazonVPC = false; - + string cloud; try { cloud = sysConfig->getConfig(InstallSection, "Cloud"); } catch(...) - { - cloud = oam::UnassignedName; - } + {} - string tcloud = "n"; - if (cloud == oam::UnassignedName) + string tcloud = cloud; + if (cloud.empty()) tcloud = "n"; else - { - if (cloud == "amazon-ec2") - { + if (cloud == "amazon") tcloud = "y"; - amazonEC2 = true; - } - else - { - if (cloud == "amazon-vpc") - { - tcloud = "y"; - amazonVPC = true; - - //get subnetID - try { - amazonSubNet = sysConfig->getConfig(InstallSection, "AmazonSubNetID"); - } - catch(...) - {} - } - } - } //cleanup/create local/etc directory cmd = "rm -rf " + installDir + "/local/etc > /dev/null 2>&1"; @@ -671,169 +582,98 @@ int main(int argc, char *argv[]) system(cmd.c_str()); while(true) { - prompt = "Installing on Amazon System (EC2 or VPC services) [y,n] (" + tcloud + ") > "; + prompt = "Installing on Amazon EC2 Instances [y,n] (" + tcloud + ") > "; pcommand = callReadline(prompt.c_str()); if (pcommand) { if (strlen(pcommand) > 0) tcloud = pcommand; callFree(pcommand); } - if (tcloud == "y") - { - if (!amazonEC2) - tcloud = "n"; + if (tcloud == "y") { + cloud = "amazon"; + cout << endl << "For Amazon EC2 Instance installs, these files will need to be installed on" << endl; + cout << "on the local instance:" << endl << endl; + cout << " 1. X.509 Certificate" << endl; + cout << " 2. X.509 Private Key" << endl << endl; - prompt = "Using EC2 services [y,n] (" + tcloud + ") > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) { - if (strlen(pcommand) > 0) tcloud = pcommand; - callFree(pcommand); - } - - if (tcloud == "n") - { - amazonEC2 = false; - cloud = oam::UnassignedName; - - if (amazonVPC) - tcloud = "y"; - - prompt = "Using VPC services [y,n] (" + tcloud + ") > "; + while(true) { + string ready = "y"; + prompt = "Are these files installed and ready to continue [y,n] (y) > "; pcommand = callReadline(prompt.c_str()); if (pcommand) { - if (strlen(pcommand) > 0) tcloud = pcommand; + if (strlen(pcommand) > 0) ready = pcommand; callFree(pcommand); + if (ready == "n") { + cout << endl << "Please Install these files and re-run postConfigure. exiting..." << endl; + exit(0); + } } - - if (tcloud == "n") - { - amazonVPC = false; - cloud = oam::UnassignedName; - } - else - { - amazonVPC = true; - cloud = "amazon-vpc"; - prompt = "Enter VPC SubNet ID (" + amazonSubNet + ") > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) { - if (strlen(pcommand) > 0) amazonSubNet = pcommand; - callFree(pcommand); - } + if ( ready == "y" ) + break; - //set subnetID - try { - sysConfig->setConfig(InstallSection, "AmazonSubNetID", amazonSubNet); - } - catch(...) - {} - } + cout << "Invalid Entry, please enter 'y' for yes or 'n' for no" << endl; } - else - { - amazonEC2 = true; - cloud = "amazon-ec2"; + + try { + x509Cert = sysConfig->getConfig(InstallSection, "AmazonX509Certificate"); + x509PriKey = sysConfig->getConfig(InstallSection, "AmazonX509PrivateKey"); } + catch(...) + {} + + cout << endl; - if ( amazonEC2 || amazonVPC ) + while(true) { - cout << endl << "For Amazon EC2/VPC Instance installs, these files will need to be installed on" << endl; - cout << "on the local instance:" << endl << endl; - cout << " 1. X.509 Certificate" << endl; - cout << " 2. X.509 Private Key" << endl << endl; - - while(true) { - string ready = "y"; - prompt = "Are these files installed and ready to continue [y,n] (y) > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) { - if (strlen(pcommand) > 0) ready = pcommand; - callFree(pcommand); - if (ready == "n") { - cout << endl << "Please Install these files and re-run postConfigure. exiting..." << endl; - exit(0); - } - } - - if ( ready == "y" ) - break; - - cout << "Invalid Entry, please enter 'y' for yes or 'n' for no" << endl; - if ( noPrompting ) - exit(1); - } - - try { - x509Cert = sysConfig->getConfig(InstallSection, "AmazonX509Certificate"); - x509PriKey = sysConfig->getConfig(InstallSection, "AmazonX509PrivateKey"); - } - catch(...) - {} - - cout << endl; - - while(true) - { - prompt = "Enter Name and directory of the X.509 Certificate (" + x509Cert + ") > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) { - if (strlen(pcommand) > 0) x509Cert = pcommand; - callFree(pcommand); - } - ifstream File (x509Cert.c_str()); - if (!File) { - cout << "Error: file not found, please re-enter" << endl; - if ( noPrompting ) - exit(1); - } - else - break; - } - - while(true) - { - prompt = "Enter Name and directory of the X.509 Private Key (" + x509PriKey + ") > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) { - if (strlen(pcommand) > 0) x509PriKey = pcommand; - callFree(pcommand); - } - ifstream File (x509PriKey.c_str()); - if (!File) - { - cout << "Error: file not found, please re-enter" << endl; - if ( noPrompting ) - exit(1); - } - else - break; + prompt = "Enter Name and directory of the X.509 Certificate (" + x509Cert + ") > "; + pcommand = callReadline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) x509Cert = pcommand; + callFree(pcommand); } - - try { - sysConfig->setConfig(InstallSection, "AmazonX509Certificate", x509Cert); - sysConfig->setConfig(InstallSection, "AmazonX509PrivateKey", x509PriKey); + ifstream File (x509Cert.c_str()); + if (!File) + cout << "Error: file not found, please re-enter" << endl; + else + break; + } + + while(true) + { + prompt = "Enter Name and directory of the X.509 Private Key (" + x509PriKey + ") > "; + pcommand = callReadline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) x509PriKey = pcommand; + callFree(pcommand); } - catch(...) - {} - - if( !copyX509files() ) - cout << "copyX509files error" << endl; - - break; + ifstream File (x509PriKey.c_str()); + if (!File) + cout << "Error: file not found, please re-enter" << endl; + else + break; } + + try { + sysConfig->setConfig(InstallSection, "AmazonX509Certificate", x509Cert); + sysConfig->setConfig(InstallSection, "AmazonX509PrivateKey", x509PriKey); + } + catch(...) + {} + + if( !copyX509files() ) + cout << "copyX509files error" << endl; + + break; } else { if (tcloud == "n" ) { - cloud = oam::UnassignedName; + cloud = "n"; break; } } - cout << "Invalid Entry, please enter 'y' for yes or 'n' for no" << endl; - if ( noPrompting ) - exit(1); } try { @@ -842,9 +682,6 @@ int main(int argc, char *argv[]) catch(...) {} - if ( cloud == "amazon-ec2" || cloud == "amazon-vpc" ) - cloud = "amazon"; - cout << endl << "===== Setup System Module Type Configuration =====" << endl << endl; cout << "There are 2 options when configuring the System Module Type: separate and combined" << endl << endl; @@ -897,54 +734,171 @@ int main(int argc, char *argv[]) cout << "Combined Server Installation will be performed." << endl; cout << "The Server will be configured as a Performance Module." << endl; cout << "All InfiniDB Processes will run on the Performance Modules." << endl; - - if ( pmwithum ) - { - cout << endl << "NOTE: Local Query Feature is not valid on a 'combined' system, feature turned off" << endl << endl; - pmwithum = false; - PMwithUM = "n"; - } - - try { - sysConfig->setConfig(InstallSection, "PMwithUM", "n"); - } - catch(...) - {} - + //module ProcessConfig.xml to setup all apps on the dm if( !updateProcessConfig(IserverTypeInstall) ) cout << "Update ProcessConfig.xml error" << endl; + // are we using settings from previous config file? + if ( reuseConfig == "n" ) { + if( !uncommentCalpontXml("NumBlocksPct") ) { + cout << "Update Calpont.xml NumBlocksPct Section" << endl; + exit(1); + } + + try { + sysConfig->setConfig("DBBC", "NumBlocksPct", "50"); + + cout << endl << "NOTE: Setting 'NumBlocksPct' to 50%" << endl; + } + catch(...) + { + cout << "ERROR: Problem setting NumBlocksPct in the InfiniDB System Configuration file" << endl; + exit(1); + } + + try{ + sysinfo(&myinfo); + } + catch (...) {} + + //get memory stats + long long total = myinfo.totalram / 1024 / 1000; + + // adjust max memory, 25% of total memory + string value; + + if ( total <= 2000 ) + value = "256M"; + else if ( total <= 4000 ) + value = "512M"; + else if ( total <= 8000 ) + value = "1G"; + else if ( total <= 16000 ) + value = "2G"; + else if ( total <= 32000 ) + value = "4G"; + else if ( total <= 64000 ) + value = "8G"; + else + value = "16G"; + + cout << " Setting 'TotalUmMemory' to 25% of total memory (Combined Server Install maximum value is 16G). Value set to " << value << endl; + + try { + sysConfig->setConfig("HashJoin", "TotalUmMemory", value); + } + catch(...) + { + cout << "ERROR: Problem setting TotalUmMemory in the InfiniDB System Configuration file" << endl; + exit(1); + } + + if ( !writeConfig(sysConfig) ) { + cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; + exit(1); + } + } + else + { + try { + string numBlocksPct = sysConfig->getConfig("DBBC", "NumBlocksPct"); + + cout << endl; + if ( numBlocksPct.empty() ) + cout << "NOTE: Using the default setting for 'NumBlocksPct' at 70%" << endl; + else + cout << "NOTE: Using previous configuration setting for 'NumBlocksPct' = " << numBlocksPct << "%" << endl; + + string totalUmMemory = sysConfig->getConfig("HashJoin", "TotalUmMemory"); + + + cout << " Using previous configuration setting for 'TotalUmMemory' = " << totalUmMemory << endl; + + } + catch(...) + { + cout << "ERROR: Problem reading NumBlocksPct/TotalUmMemory in the InfiniDB System Configuration file" << endl; + exit(1); + } + } break; } default: // normal, separate UM and PM { + // are we using settings from previous config file? + if ( reuseConfig == "n" ) { + cout << "NOTE: Using the default setting for 'NumBlocksPct' at 70%" << endl; + + try{ + sysinfo(&myinfo); + } + catch (...) {} + + //get memory stats + long long total = myinfo.totalram / 1024 / 1000; + + // adjust max memory, 50% of total memory + string value; + + if ( total <= 2000 ) + value = "512M"; + else if ( total <= 4000 ) + value = "1G"; + else if ( total <= 8000 ) + value = "2G"; + else if ( total <= 16000 ) + value = "4G"; + else if ( total <= 32000 ) + value = "8G"; + else if ( total <= 64000 ) + value = "16G"; + else + value = "32G"; + + cout << " Setting 'TotalUmMemory' to 50% of total memory (separate Server Install maximum value is 32G). Value set to " << value << endl; + + try { + sysConfig->setConfig("HashJoin", "TotalUmMemory", value); + } + catch(...) + { + cout << "ERROR: Problem setting TotalUmMemory in the InfiniDB System Configuration file" << endl; + exit(1); + } + + if ( !writeConfig(sysConfig) ) { + cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; + exit(1); + } + } + else + { + try { + string numBlocksPct = sysConfig->getConfig("DBBC", "NumBlocksPct"); + + if ( numBlocksPct.empty() ) + cout << "NOTE: Using the default setting for 'NumBlocksPct' at 70%" << endl; + else + cout << "NOTE: Using previous configuration setting for 'NumBlocksPct' = " << numBlocksPct << "%" << endl; + + string totalUmMemory = sysConfig->getConfig("HashJoin", "TotalUmMemory"); + + cout << " Using previous configuration setting for 'TotalUmMemory' = " << totalUmMemory << endl; + + } + catch(...) + { + cout << "ERROR: Problem reading NumBlocksPct/TotalUmMemory in the InfiniDB System Configuration file" << endl; + exit(1); + } + } break; } } break; } - //store local query flag - try { - sysConfig->setConfig(InstallSection, "PMwithUM", PMwithUM); - } - catch(...) - {} - - //local query needs mysql replication, make sure its enabled - if ( pmwithum ) - { - mysqlRep = true; - MySQLRep = "y"; - } - - if ( pmwithum ) - cout << "NOTE: Local Query Feature is enabled" << endl; - - if ( mysqlRep ) - cout << "NOTE: MySQL Replication Feature is enabled" << endl; - //Write out Updated System Configuration File try { sysConfig->setConfig(InstallSection, "InitialInstallFlag", "n"); @@ -959,8 +913,7 @@ int main(int argc, char *argv[]) cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; exit(1); } - - cout << endl; + setSystemName(); cout << endl; @@ -1062,170 +1015,6 @@ int main(int argc, char *argv[]) exit(1); } - if (hdfs || !rootUser) - if( !updateBash() ) - cout << "updateBash error" << endl; - - // - // setup memory paramater settings - // - - cout << endl << "===== Setup Memory Configuration =====" << endl << endl; - - switch ( IserverTypeInstall ) { - case (oam::INSTALL_COMBINE_DM_UM_PM): // combined #1 - dm/um/pm on a single server - { - // are we using settings from previous config file? - if ( reuseConfig == "n" ) { - if( !uncommentCalpontXml("NumBlocksPct") ) { - cout << "Update Calpont.xml NumBlocksPct Section" << endl; - exit(1); - } - - string numBlocksPct = "50"; - if (hdfs) - numBlocksPct = "25"; - - try { - sysConfig->setConfig("DBBC", "NumBlocksPct", numBlocksPct); - - cout << endl << "NOTE: Setting 'NumBlocksPct' to " << numBlocksPct << endl; - } - catch(...) - { - cout << "ERROR: Problem setting NumBlocksPct in the InfiniDB System Configuration file" << endl; - exit(1); - } - -// try{ -// sysinfo(&myinfo); -// } -// catch (...) {} - - //get memory stats -// long long total = myinfo.totalram / 1024 / 1000; - - string percent = "25%"; - - if (hdfs) { - percent = "12%"; - } - - cout << " Setting 'TotalUmMemory' to " << percent << " of total memory" << endl; - - try { - sysConfig->setConfig("HashJoin", "TotalUmMemory", percent); - } - catch(...) - { - cout << "ERROR: Problem setting TotalUmMemory in the InfiniDB System Configuration file" << endl; - exit(1); - } - - if ( !writeConfig(sysConfig) ) { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; - exit(1); - } - } - else - { - try { - string numBlocksPct = sysConfig->getConfig("DBBC", "NumBlocksPct"); - - cout << endl; - if ( numBlocksPct.empty() ) - cout << "NOTE: Using the default setting for 'NumBlocksPct' at 70%" << endl; - else - cout << "NOTE: Using previous configuration setting for 'NumBlocksPct' = " << numBlocksPct << "%" << endl; - - string totalUmMemory = sysConfig->getConfig("HashJoin", "TotalUmMemory"); - - cout << " Using previous configuration setting for 'TotalUmMemory' = " << totalUmMemory << endl; - } - catch(...) - { - cout << "ERROR: Problem reading NumBlocksPct/TotalUmMemory in the InfiniDB System Configuration file" << endl; - exit(1); - } - } - break; - } - default: // normal, separate UM and PM - { - // are we using settings from previous config file? - if ( reuseConfig == "n" ) { - - string numBlocksPct = "70"; - if (hdfs) { - numBlocksPct = "35"; - - try { - sysConfig->setConfig("DBBC", "NumBlocksPct", numBlocksPct); - - cout << "NOTE: Setting 'NumBlocksPct' to " << numBlocksPct << endl; - } - catch(...) - { - cout << "ERROR: Problem setting NumBlocksPct in the InfiniDB System Configuration file" << endl; - exit(1); - } - } - else - cout << "NOTE: Using the default setting for 'NumBlocksPct' at " << numBlocksPct << "%" << endl; - -// try{ -// sysinfo(&myinfo); -// } -// catch (...) {} - - //get memory stats -// long long total = myinfo.totalram / 1024 / 1000; - - string percent = "50%"; - if (hdfs) { - percent = "12%"; - } - - cout << " Setting 'TotalUmMemory' to " << percent << " of total memory" << endl; - - try { - sysConfig->setConfig("HashJoin", "TotalUmMemory", percent); - } - catch(...) - { - cout << "ERROR: Problem setting TotalUmMemory in the InfiniDB System Configuration file" << endl; - exit(1); - } - - if ( !writeConfig(sysConfig) ) { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; - exit(1); - } - } - else - { - try { - string numBlocksPct = sysConfig->getConfig("DBBC", "NumBlocksPct"); - - if ( numBlocksPct.empty() ) - cout << "NOTE: Using the default setting for 'NumBlocksPct' at 70%" << endl; - else - cout << "NOTE: Using previous configuration setting for 'NumBlocksPct' = " << numBlocksPct << "%" << endl; - - string totalUmMemory = sysConfig->getConfig("HashJoin", "TotalUmMemory"); - - cout << " Using previous configuration setting for 'TotalUmMemory' = " << totalUmMemory << endl; - } - catch(...) - { - cout << "ERROR: Problem reading NumBlocksPct/TotalUmMemory in the InfiniDB System Configuration file" << endl; - exit(1); - } - } - break; - } - } - //Write out Updated System Configuration File try { sysConfig->setConfig(InstallSection, "InitialInstallFlag", "y"); @@ -1352,9 +1141,6 @@ int main(int argc, char *argv[]) if ( moduleType == "pm" ) pmNumber = moduleCount; - if ( moduleType == "um" ) - umNumber = moduleCount; - int moduleID = 1; while(true) { prompt = "Enter Starting Module ID for " + moduleDesc + " [1," + oam.itoa(oam::MAX_MODULE-moduleCount+1) + "] (1) > "; @@ -1648,15 +1434,10 @@ int main(int argc, char *argv[]) else { if (cloud != "amazon") { - if ( moduleIPAddr == oam::UnassignedIpAddr ) - { - //get IP Address - string IPAddress = oam.getIPAddress( newModuleHostName); - if ( !IPAddress.empty() ) - newModuleIPAddr = IPAddress; - else - newModuleIPAddr = oam::UnassignedIpAddr; - } + //get IP Address + string IPAddress = oam.getIPAddress( newModuleHostName); + if ( !IPAddress.empty() ) + newModuleIPAddr = IPAddress; else newModuleIPAddr = moduleIPAddr; @@ -1701,10 +1482,10 @@ int main(int argc, char *argv[]) // run ping test to validate string cmdLine = "ping "; - string cmdOption = " -c 1 -w 5 >> /dev/null"; + string cmdOption = " -w 2 >> /dev/null"; string cmd = cmdLine + newModuleIPAddr + cmdOption; int rtnCode = system(cmd.c_str()); - if ( WEXITSTATUS(rtnCode) != 0 ) { + if ( rtnCode != 0 ) { //NIC failed to respond to ping string temp = "2"; while (true) @@ -1822,26 +1603,20 @@ int main(int argc, char *argv[]) sysConfig->setConfig(Section, "IPAddr", newModuleIPAddr); sysConfig->setConfig(Section, "Port", "8601"); - sysConfig->setConfig(Section, "Module", parentOAMModuleName); - + //set Performance Module's IP's to first NIC IP entered sysConfig->setConfig("DDLProc", "IPAddr", newModuleIPAddr); sysConfig->setConfig("DMLProc", "IPAddr", newModuleIPAddr); } - //set User Module's IP Addresses - if ( pmwithum ) { - string Section = "ExeMgr" + oam.itoa(moduleID+umNumber); - - sysConfig->setConfig(Section, "IPAddr", newModuleIPAddr); - sysConfig->setConfig(Section, "Port", "8601"); - sysConfig->setConfig(Section, "Module", parentOAMModuleName); - - } - //setup rc.local file in module tmp dir if( !makeRClocal(moduleType , newModuleName, IserverTypeInstall) ) cout << "makeRClocal error" << endl; + + //if cloud, copy fstab in module tmp dir + if ( cloud == "amazon" && moduleType == "pm") + if( !copyFstab(newModuleName) ) + cout << "copyFstab error" << endl; } else { @@ -1867,16 +1642,12 @@ int main(int argc, char *argv[]) if ( moduleType == "um" || ( moduleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) || ( moduleType == "um" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM ) || - ( moduleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_PM_UM ) || - ( moduleType == "pm" && pmwithum ) ) { - + ( moduleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_PM_UM ) ) { + string Section = "ExeMgr" + oam.itoa(moduleID); - if ( moduleType == "pm" && pmwithum ) - Section = "ExeMgr" + oam.itoa(moduleID+umNumber); sysConfig->setConfig(Section, "IPAddr", newModuleIPAddr); sysConfig->setConfig(Section, "Port", "8601"); - sysConfig->setConfig(Section, "Module", newModuleName); } //set Performance Module's IP's to first NIC IP entered @@ -2333,13 +2104,9 @@ int main(int argc, char *argv[]) } //set the PM Ports based on Number of PM modules equipped, if any equipped - int minPmPorts = 32; + int pmPorts = 32; sysConfig->setConfig("PrimitiveServers", "Count", oam.itoa(pmNumber)); - int pmPorts = pmNumber * (maxPMNicCount*2); - if ( pmPorts < minPmPorts ) - pmPorts = minPmPorts; - if ( pmNumber > 0 ) { const string PM = "PMS"; @@ -2370,7 +2137,6 @@ int main(int argc, char *argv[]) } if ( !IpAddr.empty() && IpAddr != oam::UnassignedIpAddr ) { sysConfig->setConfig(pmName, "IPAddr", IpAddr); - sysConfig->setConfig(pmName, "Port", "8620"); pmsID++; if ( pmsID > pmPorts ) break; @@ -2643,26 +2409,48 @@ int main(int argc, char *argv[]) //check if dbrm data resides in older directory path and inform user if it does dbrmDirCheck(); - if ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM && pmNumber == 1) { + if ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) { //run the mysql / mysqld setup scripts cout << endl << "===== Running the InfiniDB MySQL setup scripts =====" << endl << endl; - checkMysqlPort(mysqlPort, sysConfig, EM); + system("netstat -na | grep '3306 ' | grep LISTEN > /tmp/mysqlport"); + string fileName = "/tmp/mysqlport"; + ifstream oldFile (fileName.c_str()); + if (oldFile) { + oldFile.seekg(0, std::ios::end); + int size = oldFile.tellg(); + if ( size != 0 ) { + cout << "The mysqld default port of 3306 is already in-use by another mysqld" << endl; + cout << "Either change the port number of 3306 in " + installDir + "/mysql/my.cnf" << endl; + cout << "Or stop current mysqld version that is running" << endl; + + while(true) + { + string answer = "n"; + pcommand = callReadline("Enter 'y' when a change has been made and you are ready to continue > "); + if (pcommand) + { + if (strlen(pcommand) > 0) answer = pcommand; + callFree(pcommand); + } + if ( answer == "y" ) + break; + else + cout << "Invalid Entry, please enter 'y' for yes" << endl; + if ( noPrompting ) + exit(1); + } + } + } // call the mysql setup scripts - mysqlSetup(EM); + mysqlSetup(); sleep(5); } - int thread_id = 0; - - pthread_t thr[childmodulelist.size()]; - - /* create a thread_data_t argument array */ - thread_data_t thr_data[childmodulelist.size()]; - if ( IserverTypeInstall != oam::INSTALL_COMBINE_DM_UM_PM || pmNumber > 1 ) { + // // perform remote install of other servers in the system // @@ -2759,81 +2547,32 @@ int main(int argc, char *argv[]) //check if pkgs are located in $HOME directory if ( EEPackageType != "binary") { - string separator = "-"; + string seperator = "-"; if ( EEPackageType == "deb" ) - separator = "_"; - calpontPackage1 = "infinidb-libs" + separator + systemsoftware.Version + "-" + systemsoftware.Release; - calpontPackage2 = "infinidb-platform" + separator + systemsoftware.Version + "-" + systemsoftware.Release; - calpontPackage3 = "infinidb-enterprise" + separator + systemsoftware.Version + "-" + systemsoftware.Release; - mysqlPackage = "infinidb-storage-engine" + separator + systemsoftware.Version + "-" + systemsoftware.Release; - mysqldPackage = "infinidb-mysql" + separator + systemsoftware.Version + "-" + systemsoftware.Release; + seperator = "_"; + calpontPackage = "calpont" + seperator + systemsoftware.Version + "-" + systemsoftware.Release; + mysqlPackage = "calpont-mysql" + seperator + systemsoftware.Version + "-" + systemsoftware.Release; + mysqldPackage = "calpont-mysqld" + seperator + systemsoftware.Version + "-" + systemsoftware.Release; if( !pkgCheck() ) { exit(1); } else { - calpontPackage1 = home + "/" + calpontPackage1 + "*." + EEPackageType; - calpontPackage2 = home + "/" + calpontPackage2 + "*." + EEPackageType; - calpontPackage3 = home + "/" + calpontPackage3 + "*." + EEPackageType; + calpontPackage = home + "/" + calpontPackage + "*." + EEPackageType; mysqlPackage = home + "/" + mysqlPackage + "*." + EEPackageType; mysqldPackage = home + "/" + mysqldPackage + "*." + EEPackageType; } } else { - string fileName = installDir + "/bin/healthcheck"; - ifstream file (fileName.c_str()); - if (!file) // CE - calpontPackage1 = "infinidb-" + systemsoftware.Version + "-" + systemsoftware.Release; - else // EE - calpontPackage1 = "infinidb-ent-" + systemsoftware.Version + "-" + systemsoftware.Release; - calpontPackage2 = "dummy"; - calpontPackage3 = "dummy"; - mysqlPackage = calpontPackage1; - mysqldPackage = calpontPackage1; + calpontPackage = "calpont-infinidb-ent-" + systemsoftware.Version + "-" + systemsoftware.Release; + mysqlPackage = calpontPackage; + mysqldPackage = calpontPackage; if( !pkgCheck() ) exit(1); - calpontPackage1 = home + "/" + calpontPackage1 + "*.bin.tar.gz"; - calpontPackage2 = "dummy"; - calpontPackage3 = "dummy"; - } - - //If ent pkg is not there, mark it as such - { - glob_t gt; - memset(>, 0, sizeof(gt)); - if (glob(calpontPackage3.c_str(), 0, 0, >) != 0) - calpontPackage3 = "dummy.rpm"; - globfree(>); - } - - //if PM is running with UM functionality - // install UM packages and run mysql setup scripts - if ( pmwithum ) { - //run the mysql / mysqld setup scripts - - if ( EEPackageType != "binary") { - cout << endl << "===== Installing InfiniDB UM Packages and Running the InfiniDB MySQL setup scripts =====" << endl << endl; - string cmd = "rpm -Uv --force " + mysqlPackage + " " + mysqldPackage; - if ( EEPackageType == "deb" ) - cmd = "dpkg -i " + mysqlPackage + " " + mysqldPackage; - system(cmd.c_str()); - cout << endl; - } - } - else - { - // run my.cnf upgrade script - if ( reuseConfig == "y" && MySQLRep == "y" && - IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) - { - cmd = installDir + "/bin/mycnfUpgrade > /tmp/mycnfUpgrade.log 2>&1"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) - cout << "Error: Problem upgrade my.cnf, check /tmp/mycnfUpgrade.log" << endl; - } + calpontPackage = home + "/" + calpontPackage + "*.bin.tar.gz"; } cout << endl; @@ -2881,27 +2620,6 @@ int main(int argc, char *argv[]) password = "'" + password + "'"; } - checkSystemMySQLPort(mysqlPort, sysConfig, USER, password, childmodulelist, IserverTypeInstall, pmwithum, EM); - - if ( ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) || - ( (IserverTypeInstall != oam::INSTALL_COMBINE_DM_UM_PM) && pmwithum ) ) - { - cout << endl << "===== Running the InfiniDB MySQL setup scripts =====" << endl << endl; - - // run my.cnf upgrade script - if ( reuseConfig == "y" && MySQLRep == "y" ) - { - cmd = installDir + "/bin/mycnfUpgrade > /tmp/mycnfUpgrade.log 2>&1"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) - cout << "Error: Problem upgrade my.cnf, check /tmp/mycnfUpgrade.log" << endl; - } - - // call the mysql setup scripts - mysqlSetup(EM); - sleep(5); - } - ChildModuleList::iterator list1 = childmodulelist.begin(); for (; list1 != childmodulelist.end() ; list1++) { @@ -2919,8 +2637,7 @@ int main(int argc, char *argv[]) } if ( remoteModuleType == "um" || - (remoteModuleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM) || - (remoteModuleType == "pm" && pmwithum) ) + (remoteModuleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM) ) { cout << endl << "----- Performing Install on '" + remoteModuleName + " / " + remoteHostName + "' -----" << endl << endl; @@ -2931,38 +2648,36 @@ int main(int argc, char *argv[]) string temppwprompt = pwprompt; if ( pwprompt == " " ) temppwprompt = "none"; - - //check my.cnf port in-user on remote node -// checkRemoteMysqlPort(remoteModuleIP, remoteModuleName, USER, password, mysqlPort, sysConfig); - + //run remote installer script - cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage1 + " " + calpontPackage2 + " " + calpontPackage3 + " " + mysqlPackage + " " + mysqldPackage + " initial " + EEPackageType + " " + nodeps + " " + temppwprompt + " " + mysqlPort + " " + remote_installer_debug + " " + debug_logfile; + string cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + mysqlPackage + " " + mysqldPackage + " initial " + EEPackageType + " " + nodeps + " " + temppwprompt + " " + remote_installer_debug + " " + debug_logfile; if ( thread_remote_installer == "1" ) { - thr_data[thread_id].command = cmd; - - int status = pthread_create (&thr[thread_id], NULL, (void*(*)(void*)) &remoteInstallThread, &thr_data[thread_id]); + remoteInstallCount++; + pthread_t remoteinstallthread; + int status = pthread_create (&remoteinstallthread, NULL, (void*(*)(void*)) &remoteInstallThread, &cmd); if ( status != 0 ) { cout << "remoteInstallThread failed for " << remoteModuleName << ", exiting" << endl; exit (1); } - thread_id++; + + sleep(1); } else { int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from user_installer.sh" << endl; exit(1); } //check for mysql password on remote UM if ( pwprompt == " " ) { - cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '" + installDir + "/mysql/mysql-Calpont start'"; + cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '/etc/init.d/mysql-Calpont start'"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from mysql-Calpont start" << endl; exit(1); } @@ -2972,7 +2687,7 @@ int main(int argc, char *argv[]) { cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '" + installDir + "/mysql/bin/mysql --defaults-file=" + installDir + "/mysql/my.cnf -u root " + pwprompt + " -e status' 1 > /tmp/idbmysql.log 2>&1"; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from remote_command.sh" << endl; exit(1); } @@ -2982,14 +2697,12 @@ int main(int argc, char *argv[]) if ( prompt == " *** Enter MySQL password > " ) cout << endl << " MySQL password set on Module '" + remoteModuleName + "', Additional MySQL Install steps being performed" << endl << endl; - if ( mysqlpw == " " ) { - if ( noPrompting ) { - cout << " *** MySQL password required, enter on command line, exiting..." << endl; + if ( prompt == " *** Password incorrect, please re-enter MySQL password > " ) + if ( noPrompting ) exit(1); - } - + + if ( mysqlpw == " " ) mysqlpw = getpass(prompt.c_str()); - } mysqlpw = "'" + mysqlpw + "'"; pwprompt = "--password=" + mysqlpw; @@ -3006,9 +2719,9 @@ int main(int argc, char *argv[]) { cout << endl << "Additional MySQL Installation steps Successfully Completed on '" + remoteModuleName + "'" << endl << endl; - cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '" + installDir + "/mysql/mysql-Calpont stop'"; + cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '/etc/init.d/mysql-Calpont stop'"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from mysql-Calpont stop" << endl; exit(1); } @@ -3021,7 +2734,7 @@ int main(int argc, char *argv[]) //re-run post-mysqld-install with password cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + " '" + installDir + "/bin/post-mysql-install " + pwprompt + "'"; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from post-mysql-install" << endl; exit(1); } @@ -3030,22 +2743,15 @@ int main(int argc, char *argv[]) } else { // do a binary package install - string binservertype = serverTypeInstall; - if ( pmwithum ) - binservertype = "pmwithum"; - - //check my.cnf port in-user on remote node -// checkRemoteMysqlPort(remoteModuleIP, remoteModuleName, USER, password, mysqlPort, sysConfig); - cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + - remoteModuleIP + " " + password + " " + calpontPackage1 + " " + remoteModuleType + - " initial " + binservertype + " " + mysqlPort + " " + remote_installer_debug + + remoteModuleIP + " " + password + " " + calpontPackage + " " + remoteModuleType + + " initial " + serverTypeInstall + " " + remote_installer_debug + " " + installDir + " " + debug_logfile; if ( thread_remote_installer == "1" ) { - thr_data[thread_id].command = cmd; - - int status = pthread_create (&thr[thread_id], NULL, (void*(*)(void*)) &remoteInstallThread, &thr_data[thread_id]); + remoteInstallCount++; + pthread_t remoteinstallthread; + int status = pthread_create (&remoteinstallthread, NULL, (void*(*)(void*)) &remoteInstallThread, &cmd); if ( status != 0 ) { @@ -3053,12 +2759,12 @@ int main(int argc, char *argv[]) exit (1); } - thread_id++; + sleep(1); } else { int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from user_installer.sh" << endl; exit(1); } @@ -3067,8 +2773,7 @@ int main(int argc, char *argv[]) } else { - if ( (remoteModuleType == "pm" && IserverTypeInstall != oam::INSTALL_COMBINE_DM_UM_PM) || - (remoteModuleType == "pm" && !pmwithum ) ) + if (remoteModuleType == "pm" && IserverTypeInstall != oam::INSTALL_COMBINE_DM_UM_PM) { cout << endl << "----- Performing Install on '" + remoteModuleName + " / " + remoteHostName + "' -----" << endl << endl; @@ -3077,12 +2782,12 @@ int main(int argc, char *argv[]) if ( EEPackageType != "binary" ) { //run remote installer script - cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage1 + " " + calpontPackage2 + " " + calpontPackage3 + " " + mysqlPackage + " " + mysqldPackage + " initial " + EEPackageType + " " + nodeps + " " + remote_installer_debug + " " + debug_logfile; + cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + mysqlPackage + " " + mysqldPackage + " initial " + EEPackageType + " " + nodeps + " " + remote_installer_debug + " " + debug_logfile; if ( thread_remote_installer == "1" ) { - thr_data[thread_id].command = cmd; - - int status = pthread_create (&thr[thread_id], NULL, (void*(*)(void*)) &remoteInstallThread, &thr_data[thread_id]); + remoteInstallCount++; + pthread_t remoteinstallthread; + int status = pthread_create (&remoteinstallthread, NULL, (void*(*)(void*)) &remoteInstallThread, &cmd); if ( status != 0 ) { @@ -3090,12 +2795,12 @@ int main(int argc, char *argv[]) exit (1); } - thread_id++; + sleep(1); } else { int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from performance_installer.sh" << endl; exit(1); } @@ -3103,18 +2808,15 @@ int main(int argc, char *argv[]) } else { // do a binary package install - string binservertype = serverTypeInstall; - if ( pmwithum ) - binservertype = "pmwithum"; cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + - " " + password + " " + calpontPackage1 + " " + remoteModuleType + " initial " + - binservertype + " " + mysqlPort + " " + remote_installer_debug + " " + installDir + " " + + " " + password + " " + calpontPackage + " " + remoteModuleType + " initial " + + serverTypeInstall + " " + remote_installer_debug + " " + installDir + " " + debug_logfile; if ( thread_remote_installer == "1" ) { - thr_data[thread_id].command = cmd; - - int status = pthread_create (&thr[thread_id], NULL, (void*(*)(void*)) &remoteInstallThread, &thr_data[thread_id]); + remoteInstallCount++; + pthread_t remoteinstallthread; + int status = pthread_create (&remoteinstallthread, NULL, (void*(*)(void*)) &remoteInstallThread, &cmd); if ( status != 0 ) { @@ -3122,12 +2824,12 @@ int main(int argc, char *argv[]) exit (1); } - thread_id++; + sleep(1); } else { int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error returned from user_installer.sh" << endl; exit(1); } @@ -3136,32 +2838,44 @@ int main(int argc, char *argv[]) } } } + } + } - if ( thread_remote_installer == "1" ) { - - //wait until remove install Thread Count is at zero or hit timeout - cout << endl << "InfiniDB Package being installed, please wait ..."; - cout.flush(); - - /* block until all threads complete */ - for (thread_id = 0; thread_id < (int) childmodulelist.size(); ++thread_id) { - pthread_join(thr[thread_id], NULL); - } - - cout << " DONE" << endl; - } + if ( thread_remote_installer == "1" ) { + //wait until remove install Thread Count is at zero or hit timeout + cout << endl << "InfiniDB Package being installed, please wait ."; + cout.flush(); + + int wait = 0; + while (true) + { + if ( remoteInstallCount == 0 ) + break; + + cout << "."; + cout.flush(); + sleep(10); + wait++; + // give it 5 minutes to complete + if ( wait >= 60 ) + { + cout << "Timed out (5 minutes) waiting for Remote Nodes to be Installed, check logs" << endl; + exit (1); + } } + + cout << " DONE" << endl; } //configure data redundancy - string glusterconfig = installDir + "/bin/glusterconf"; + string glusterconfig = installDir + "/gluster/glusterconf"; - if (gluster && reuseConfig == "n" ) + if (glusterUsed == "y" && reuseConfig == "n" ) { cout << endl << "===== Configuring InfiniDB Data Redundancy Functionality =====" << endl << endl; int ret = system(glusterconfig.c_str()); - if ( WEXITSTATUS(ret) != 0 ) + if ( ret != 0 ) { cerr << endl << "There was an error in the Data Redundancy setup, exiting..." << endl; exit(1); @@ -3198,13 +2912,6 @@ int main(int argc, char *argv[]) } } - //store mysql rep enable flag - try { - sysConfig->setConfig(InstallSection, "MySQLRep", MySQLRep); - } - catch(...) - {} - if ( !writeConfig(sysConfig) ) { cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; exit(1); @@ -3226,7 +2933,7 @@ int main(int argc, char *argv[]) cmd = "sudo " + installDir + "/bin/syslogSetup.sh --installdir=" + installDir + " status > /dev/null 2>&1"; int ret = system(cmd.c_str()); - if ( WEXITSTATUS(ret) != 0) + if ( ret != 0) cerr << "WARNING: The InfiniDB system logging not correctly setup and working" << endl; else cout << "The InfiniDB system logging is setup and working on local server" << endl; @@ -3266,91 +2973,78 @@ int main(int argc, char *argv[]) if ( start == "y" ) { - if (hdfs) - { - cout << endl << "----- Starting InfiniDB Service on all Modules -----" << endl << endl; - string cmd = "pdsh -a '" + installDir + "/bin/infinidb restart' > /tmp/postConfigure.pdsh 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus("/tmp/postConfigure.pdsh", "exit") ) { - cout << endl << "ERROR: Starting InfiniDB Service failue, check /tmp/postConfigure.pdsh. exit..." << endl; - exit (1); - } - } - else - { - if ( password.empty() ) { - while(true) - { - char *pass1, *pass2; - - if ( noPrompting ) { - cout << "Enter your password, hit 'enter' to default to using a ssh key, or 'exit' > " << endl; - if ( password.empty() ) - password = "ssh"; - break; - } - - //check for command line option password - if ( !password.empty() ) - break; - - pass1=getpass("Enter your password, hit 'enter' to default to using a ssh key, or 'exit' > "); - if ( strcmp(pass1, "") == 0 ) { + if ( password.empty() ) { + while(true) + { + char *pass1, *pass2; + + if ( noPrompting ) { + cout << "Enter your password, hit 'enter' to default to using a ssh key, or 'exit' > " << endl; + if ( password.empty() ) password = "ssh"; - break; - } - - if ( strcmp(pass1, "exit") == 0 ) - exit(0); - string p1 = pass1; - pass2=getpass("Confirm password > "); - string p2 = pass2; - if ( p1 == p2 ) { - password = p2; - break; - } - else - cout << "Password mismatch, please re-enter" << endl; + break; } - - //add single quote for special characters - if ( password != "ssh" ) - { - password = "'" + password + "'"; + + //check for command line option password + if ( !password.empty() ) + break; + + pass1=getpass("Enter your password, hit 'enter' to default to using a ssh key, or 'exit' > "); + if ( strcmp(pass1, "") == 0 ) { + password = "ssh"; + break; + } + + if ( strcmp(pass1, "exit") == 0 ) + exit(0); + string p1 = pass1; + pass2=getpass("Confirm password > "); + string p2 = pass2; + if ( p1 == p2 ) { + password = p2; + break; } + else + cout << "Password mismatch, please re-enter" << endl; } - - ChildModuleList::iterator list1 = childmodulelist.begin(); - - for (; list1 != childmodulelist.end() ; list1++) + + //add single quote for special characters + if ( password != "ssh" ) { - string remoteModuleName = (*list1).moduleName; - string remoteModuleIP = (*list1).moduleIP; - string remoteHostName = (*list1).hostName; - - //run remote command script - cout << endl << "----- Starting InfiniDB on '" + remoteModuleName + "' -----" << endl << endl; - cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + - " '" + installDir + "/bin/infinidb restart' 0"; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) - cout << "Error with running remote_command.sh" << endl; - else - cout << "InfiniDB successfully started" << endl; + password = "'" + password + "'"; } + } + + ChildModuleList::iterator list1 = childmodulelist.begin(); + + for (; list1 != childmodulelist.end() ; list1++) + { + string remoteModuleName = (*list1).moduleName; + string remoteModuleIP = (*list1).moduleIP; + string remoteHostName = (*list1).hostName; - //start InfiniDB on local server - cout << endl << "----- Starting InfiniDB on local server -----" << endl << endl; - cmd = installDir + "/bin/infinidb restart > /dev/null 2>&1"; + //run remote command script + cout << endl << "----- Starting InfiniDB on '" + remoteModuleName + "' -----" << endl << endl; + cmd = installDir + "/bin/remote_command.sh " + remoteModuleIP + " " + password + + " '" + installDir + "/bin/infinidb restart' " + remote_installer_debug; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { - cout << "Error Starting InfiniDB local module" << endl; - cout << "Installation Failed, exiting" << endl; - exit (1); - } + if (rtnCode != 0) + cout << "Error with running remote_command.sh" << endl; else cout << "InfiniDB successfully started" << endl; } + + //start InfiniDB on local server + cout << endl << "----- Starting InfiniDB on local server -----" << endl << endl; + cmd = installDir + "/bin/infinidb start"; + int rtnCode = system(cmd.c_str()); + if (rtnCode != 0) { + cout << "Error Starting InfiniDB local module" << endl; + cout << "Installation Failed, exiting" << endl; + exit (1); + } + else + cout << "InfiniDB successfully started" << endl; } else { @@ -3386,9 +3080,9 @@ int main(int argc, char *argv[]) if ( start == "y" ) { //start InfiniDB on local server cout << endl << "----- Starting InfiniDB on local Server '" + parentOAMModuleName + "' -----" << endl << endl; - string cmd = installDir + "/bin/infinidb restart > /dev/null 2>&1"; + string cmd = installDir + "/bin/infinidb start"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Error Starting InfiniDB local module" << endl; cout << "Installation Failed, exiting" << endl; exit (1); @@ -3409,11 +3103,7 @@ int main(int argc, char *argv[]) if ( waitForActive() ) { cout << " DONE" << endl; - if (hdfs) - cmd = "bash -c '. " + installDir + "/bin/" + DataFileEnvFile + ";" + installDir + "/bin/dbbuilder 7 > /tmp/dbbuilder.log'"; - else - cmd = installDir + "/bin/dbbuilder 7 > /tmp/dbbuilder.log"; - + cmd = installDir + "/bin/dbbuilder 7 > /tmp/dbbuilder.log"; system(cmd.c_str()); if (oam.checkLogStatus("/tmp/dbbuilder.log", "System Catalog created") ) @@ -3422,13 +3112,14 @@ int main(int argc, char *argv[]) { if ( oam.checkLogStatus("/tmp/dbbuilder.log", "System catalog appears to exist") ) { - cout << endl << "Run MySQL Upgrade.. "; + cout << endl << "Run Upgrade Script.."; cout.flush(); //send message to procmon's to run upgrade script - int status = sendUpgradeRequest(IserverTypeInstall, pmwithum); + int status = sendUpgradeRequest(IserverTypeInstall); if ( status != 0 ) { + cout << "ERROR: Error return in running the upgrade script, check um's tmp/upgrade.log" << endl; cout << endl << "InfiniDB Install Failed" << endl << endl; exit(1); } @@ -3443,25 +3134,6 @@ int main(int argc, char *argv[]) } } - //set mysql replication, if wasn't setup before on system - if ( ( mysqlRep && pmwithum ) || - ( mysqlRep && (umNumber > 1) ) || - ( mysqlRep && (pmNumber > 1) && (IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM) ) ) - { - cout << endl << "Run MySQL Replication Setup.. "; - cout.flush(); - - //send message to procmon's to run upgrade script - int status = sendReplicationRequest(IserverTypeInstall, password, mysqlPort); - - if ( status != 0 ) { - cout << endl << " InfiniDB Install Failed" << endl << endl; - exit(1); - } - else - cout << " DONE" << endl; - } - cout << endl << "InfiniDB Install Successfully Completed, System is Active" << endl << endl; cout << "Enter the following command to define InfiniDB Alias Commands" << endl << endl; @@ -3603,62 +3275,35 @@ bool checkSaveConfigFile() { string cmd = "mv -f " + rpmFileName + " " + newFileName; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Error moving installed version of Calpont.xml" << endl; return false; } cmd = "cp " + oldFileName + " " + rpmFileName; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Error moving pkgsave file" << endl; return false; } cmd = "cd " + installDir + "/etc/;../bin/autoConfigure " + extentMapCheckOnly; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Error running autoConfigure" << endl; return false; } cmd = "mv -f " + newFileName + " " + rpmFileName; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << "Error moving pkgsave file" << endl; return false; } //check to see if updates were made - if ( sysConfig->getConfig("ExeMgr1", "IPAddr") != "0.0.0.0") { - //Calpont.xml is ready to go, get feature options - - if ( MySQLRep == "n" ) - { - try { - MySQLRep = sysConfig->getConfig(InstallSection, "MySQLRep"); - } - catch(...) - {} - - if ( MySQLRep == "y" ) - mysqlRep = true; - } - - if ( PMwithUM == "n" ) { - //get local query / PMwithUM feature flag - try { - PMwithUM = sysConfig->getConfig(InstallSection, "PMwithUM"); - } - catch(...) - {} - - if ( PMwithUM == "y" ) { - pmwithum = true; - } - } + if ( sysConfig->getConfig("ExeMgr1", "IPAddr") != "0.0.0.0") return true; - } sleep(1); } @@ -3721,7 +3366,7 @@ bool setOSFiles(string parentOAMModuleName, int serverTypeInstall) cmd = "sudo bash -c 'sudo cat " + installDir + "/local/etc/" + parentOAMModuleName + "/" + files[i] + ".calpont >> " + fileName + "'"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) + if (rtnCode != 0) cout << "Error Updating " + files[i] << endl; cmd = "rm -f " + installDir + "/local/ " + files[i] + "*.calpont > /dev/null 2>&1"; @@ -4059,14 +3704,14 @@ bool createDbrootDirs(string DBRootStorageType) // create system file directories cmd = "mkdir -p " + installDir + "/data1/systemFiles/dbrm > /dev/null 2>&1"; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error: failed to make mount dbrm dir" << endl; return false; } cmd = "mkdir -p " + installDir + "/data1/systemFiles/dataTransaction/archive > /dev/null 2>&1"; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { cout << endl << "Error: failed to make mount dataTransaction dir" << endl; return false; } @@ -4078,6 +3723,25 @@ bool createDbrootDirs(string DBRootStorageType) return true; } + +/* + * writeConfig + */ +bool writeConfig( Config* sysConfig ) +{ + for ( int i = 0 ; i < 3 ; i++ ) + { + try { + sysConfig->write(); + return true; + } + catch(...) + {} + } + + return false; +} + /* * pkgCheck */ @@ -4092,7 +3756,7 @@ bool pkgCheck() while(true) { - string cmd = "ls " + home + " | grep " + calpontPackage1 + " > /tmp/calpontpkgs"; + string cmd = "ls " + home + " | grep " + calpontPackage + " > /tmp/calpontpkgs"; system(cmd.c_str()); cmd = "ls " + home + " | grep " + mysqlPackage + " > /tmp/mysqlpkgs"; @@ -4101,7 +3765,7 @@ bool pkgCheck() cmd = "ls " + home + " | grep " + mysqldPackage + " > /tmp/mysqldpkgs"; system(cmd.c_str()); - string pkg = calpontPackage1; + string pkg = calpontPackage; string fileName = "/tmp/calpontpkgs"; ifstream oldFile (fileName.c_str()); if (oldFile) { @@ -4149,134 +3813,33 @@ bool pkgCheck() if (pcommand) { if (strcmp(pcommand, "exit") == 0) { - callFree(pcommand); - return false; - } - if (strlen(pcommand) == 0) - { - callFree(pcommand); - break; - } - callFree(pcommand); - cout << "Invalid entry, please re-enter" << endl; - if ( noPrompting ) - exit(1); - continue; - } - break; - } - } - - return true; -} - -bool storageSetup(string cloud) -{ - Oam oam; - - try { - DBRootStorageType = sysConfig->getConfig(InstallSection, "DBRootStorageType"); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the InfiniDB System Configuration file" << endl; - return false; - } - - if ( DBRootStorageType == "hdfs") - hdfs = true; - - if ( reuseConfig == "y" ) { - cout << "===== Storage Configuration = " + DBRootStorageType + " =====" << endl << endl; - - if (hdfs) - { - //default - DataFileEnvFile = "setenv-hdfs-20"; - try { - DataFileEnvFile = sysConfig->getConfig("SystemConfig", "DataFileEnvFile"); - } - catch(...) - { - DataFileEnvFile = "setenv-hdfs-20"; - } - - string DataFilePlugin = installDir + "/lib/hdfs-20.so"; - try { - DataFilePlugin = sysConfig->getConfig("SystemConfig", "DataFilePlugin"); - } - catch(...) - { - DataFilePlugin = installDir + "/lib/hdfs-20.so"; - } - - while(true) - { - cout << " Running HDFS Sanity Test (please wait): "; - cout.flush(); - string logdir("/var/log/Calpont"); - if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; - string hdfslog = logdir + "/hdfsCheck.log1"; - - string cmd = ". " + installDir + "/bin/" + DataFileEnvFile + ";" + installDir + "/bin/hdfsCheck " + DataFilePlugin + " > " + hdfslog + " 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus(hdfslog, "All HDFS checks passed!")) - { - cout << " PASSED" << endl; - - try { - sysConfig->setConfig("SystemConfig", "DataFilePlugin", DataFilePlugin); - } - catch(...) - { - cout << "ERROR: Problem setting DataFilePlugin in the InfiniDB System Configuration file" << endl; - return false; - } - - try { - sysConfig->setConfig("SystemConfig", "DataFileEnvFile", DataFileEnvFile); - } - catch(...) - { - cout << "ERROR: Problem setting DataFileEnvFile in the InfiniDB System Configuration file" << endl; - return false; - } - - if ( !writeConfig(sysConfig) ) { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; - return false; - } - - return true; - } - else - { - cout << " FAILED (Tested with Hadoop Datafile Plugin File (" + DataFilePlugin + "), please re-enter or enter 'exit' to Investigate)" << endl << endl; - - if ( noPrompting ) - exit(1); - - prompt = "Enter the Hadoop Datafile Plugin File (" + DataFilePlugin + ") > "; - pcommand = callReadline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) DataFilePlugin = pcommand; - callFree(pcommand); - } - - if ( DataFilePlugin == "exit" ) - exit (1); - - if ( DataFilePlugin != installDir + "/lib/hdfs-20.so" ) - DataFileEnvFile = "setenv-hdfs-12"; - else - DataFileEnvFile = "setenv-hdfs-20"; + callFree(pcommand); + return false; + } + if (strlen(pcommand) == 0) + { + callFree(pcommand); + break; } + callFree(pcommand); + cout << "Invalid entry, please re-enter" << endl; + if ( noPrompting ) + exit(1); + continue; } + break; } + } + + return true; +} +bool storageSetup(string cloud) +{ + if ( reuseConfig == "y" ) return true; - } + + Oam oam; cout << "===== Setup Storage Configuration =====" << endl << endl; @@ -4352,327 +3915,114 @@ bool storageSetup(string cloud) } } - //check if gluster is installed - if (rootUser) - system("which gluster > /tmp/gluster.log 2>&1"); - else - system("sudo which gluster > /tmp/gluster.log 2>&1"); - - ifstream in("/tmp/gluster.log"); - - in.seekg(0, std::ios::end); - int size = in.tellg(); - if ( size == 0 || oam.checkLogStatus("/tmp/gluster.log", "no gluster")) - // no gluster - size=0; - else - glusterInstalled = "y"; - - //check if hadoop is installed - system("which hadoop > /tmp/hadoop.log 2>&1"); - - ifstream in1("/tmp/hadoop.log"); - - in1.seekg(0, std::ios::end); - size = in1.tellg(); - if ( size == 0 || oam.checkLogStatus("/tmp/hadoop.log", "no hadoop")) - // no hadoop - size=0; - else - hadoopInstalled = "y"; - - // - // get Backend Data storage type - // - - // default to internal - storageType = "1"; - if ( DBRootStorageType == "external" ) - storageType = "2"; - if ( DBRootStorageType == "gluster" ) - storageType = "3"; - if ( DBRootStorageType == "hdfs" ) - storageType = "4"; - - cout << "----- Setup High Availability Data Storage Mount Configuration -----" << endl << endl; - - if ( glusterInstalled == "n" && hadoopInstalled == "n" ) - { - cout << "There are 2 options when configuring the storage: internal or external" << endl << endl; - prompt = "Select the type of Data Storage [1=internal, 2=external] (" + storageType + ") > "; - } - - if ( glusterInstalled == "y" && hadoopInstalled == "n" ) - { - cout << "There are 3 options when configuring the storage: internal, external, or gluster" << endl << endl; - prompt = "Select the type of Data Storage [1=internal, 2=external, 3=gluster] (" + storageType + ") > "; - } - - if ( glusterInstalled == "n" && hadoopInstalled == "y" ) - { - cout << "There are 3 options when configuring the storage: internal, external, or hdfs" << endl << endl; - prompt = "Select the type of Data Storage [1=internal, 2=external, 4=hdfs] (" + storageType + ") > "; - } - - if ( glusterInstalled == "y" && hadoopInstalled == "y" ) - { - cout << "There are 5 options when configuring the storage: internal, external, gluster, or hdfs" << endl << endl; - prompt = "Select the type of Data Storage [1=internal, 2=external, 3=gluster, 4=hdfs] (" + storageType + ") > "; - } - - cout << " 'internal' - This is specified when a local disk is used for the dbroot storage" << endl; - cout << " or the dbroot storage directories are manually mounted externally" << endl; - cout << " but no High Availability Support is required." << endl << endl; - cout << " 'external' - This is specified when the dbroot directories are externally mounted" << endl; - cout << " and High Availability Failover Support is required." << endl << endl; - - if ( glusterInstalled == "y" ) - { - cout << " 'gluster' - This is specified when glusterfs is installed and you want the dbroot" << endl; - cout << " directories to be controlled by glusterfs." << endl << endl; - } - - if ( hadoopInstalled == "y" ) - { - cout << " 'hdfs' - This is specified when hadoop is installed and you want the dbroot" << endl; - cout << " directories to be controlled by the Hadoop Distributed File System (HDFS)." << endl << endl; - } - - while(true) + string glusterconfig = installDir + "/gluster/glusterconf"; + if (access(glusterconfig.c_str(), X_OK) == 0 ) { - pcommand = callReadline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) storageType = pcommand; - callFree(pcommand); - } - - if ( glusterInstalled == "n" && hadoopInstalled == "n" ) - { - if ( storageType == "1" || storageType == "2") - break; - cout << endl << "Invalid Entry, please re-enter" << endl << endl; - if ( noPrompting ) - exit(1); - } - - if ( glusterInstalled == "y" && hadoopInstalled == "n" ) - { - if ( storageType == "1" || storageType == "2" || storageType == "3") - break; - cout << endl << "Invalid Entry, please re-enter" << endl << endl; - if ( noPrompting ) - exit(1); - } - - if ( glusterInstalled == "n" && hadoopInstalled == "y" ) + glusterUsed = "y"; + while(true) { - if ( storageType == "1" || storageType == "2" || storageType == "4") { - break; + prompt = "InfiniDB Data Redundancy Functionality Available, do you want to use it [y,n] (y) > "; + pcommand = callReadline(prompt.c_str()); + if (pcommand) { + if (strlen(pcommand) > 0) glusterUsed = pcommand; + callFree(pcommand); + if ( glusterUsed == "n" || glusterUsed == "y") { + break; + } + cout << "Invalid Option, please re-enter" << endl; + if ( noPrompting ) + exit(1); } - cout << endl << "Invalid Entry, please re-enter" << endl << endl; - if ( noPrompting ) - exit(1); - } - - if ( glusterInstalled == "y" && hadoopInstalled == "y" ) - { - if ( storageType == "1" || storageType == "2" || storageType == "3" || storageType == "4") + else break; - cout << endl << "Invalid Entry, please re-enter" << endl << endl; - if ( noPrompting ) - exit(1); - } - } - - switch ( atoi(storageType.c_str()) ) { - case (1): - { - DBRootStorageType = "internal"; - break; - } - case (2): - { - DBRootStorageType = "external"; - break; - } - case (3): - { - DBRootStorageType = "gluster"; - break; - } - case (4): - { - DBRootStorageType = "hdfs"; - break; - } - } - - //set DBRootStorageType - try { - sysConfig->setConfig(InstallSection, "DBRootStorageType", DBRootStorageType); - } - catch(...) - { - cout << "ERROR: Problem setting DBRootStorageType in the InfiniDB System Configuration file" << endl; - return false; - } - - if( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) - { - try { - sysConfig->setConfig(InstallSection, "UMStorageType", DBRootStorageType); - } - catch(...) - { - cout << "ERROR: Problem setting UMStorageType in the InfiniDB System Configuration file" << endl; - return false; } } - // if gluster - if ( storageType == "3" ) - { - gluster = true; - sysConfig->setConfig(InstallSection, "GlusterConfig", "y"); - sysConfig->setConfig("PrimitiveServers", "DirectIO", "n"); - } - else + if ( glusterUsed == "n" ) { - gluster = false; sysConfig->setConfig(InstallSection, "GlusterConfig", "n"); sysConfig->setConfig("PrimitiveServers", "DirectIO", "y"); - } - // if hadoop / hdfs - if ( storageType == "4" ) - { - hdfs = true; - string DataFilePlugin = installDir + "/lib/hdfs-20.so"; - try { - DataFilePlugin = sysConfig->getConfig("SystemConfig", "DataFilePlugin"); - } - catch(...) - { - DataFilePlugin = installDir + "/lib/hdfs-20.so"; - } - - if (DataFilePlugin.empty() || DataFilePlugin == "") - DataFilePlugin = installDir + "/lib/hdfs-20.so"; + // + // get Backend Data storage typ + // + + cout << endl << "----- Setup High Availability Data Storage Mount Configuration -----" << endl << endl; + + cout << "There are 2 options when configuring the storage: internal and external" << endl << endl; + cout << " 'internal' - This is specified when a local disk is used for the dbroot storage" << endl; + cout << " or the dbroot storage directories are manually mounted externally" << endl; + cout << " but no High Availability Support is required" << endl << endl; + cout << " 'external' - This is specified when the dbroot directories are externally mounted and" << endl; + cout << " High Availability Failover Support is required." << endl << endl; - DataFileEnvFile = "setenv-hdfs-20"; try { - DataFileEnvFile = sysConfig->getConfig("SystemConfig", "DataFileEnvFile"); + DBRootStorageType = sysConfig->getConfig(InstallSection, "DBRootStorageType"); } catch(...) { - DataFileEnvFile = "setenv-hdfs-20"; + cout << "ERROR: Problem getting DB Storage Data from the InfiniDB System Configuration file" << endl; + return false; } - - if (DataFileEnvFile.empty() || DataFileEnvFile == "") - DataFileEnvFile = "setenv-hdfs-20"; - - cout << endl; + while(true) { - prompt = "Enter the Hadoop Datafile Plugin File (" + DataFilePlugin + ") > "; + storageType = "1"; + if ( DBRootStorageType == "external" ) + storageType = "2"; + + prompt = "Select the type of Data Storage [1=internal, 2=external] (" + storageType + ") > "; pcommand = callReadline(prompt.c_str()); if (pcommand) { - if (strlen(pcommand) > 0) DataFilePlugin = pcommand; + if (strlen(pcommand) > 0) storageType = pcommand; callFree(pcommand); } - - if ( DataFilePlugin == "exit" ) - exit (1); - - if ( DataFilePlugin != installDir + "/lib/hdfs-20.so" ) - DataFileEnvFile = "setenv-hdfs-12"; - - ifstream File (DataFilePlugin.c_str()); - if (!File) - cout << "Error: Hadoop Datafile Plugin File (" + DataFilePlugin + ") doesn't exist, please re-enter" << endl; - else - { - cout << endl << " Running HDFS Sanity Test (please wait): "; - cout.flush(); - string logdir("/var/log/Calpont"); - if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; - string hdfslog = logdir + "/hdfsCheck.log1"; - - string cmd = installDir + "/bin/hdfsCheck " + DataFilePlugin + " > " + hdfslog + " 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus(hdfslog, "All HDFS checks passed!")) { - cout << " PASSED" << endl; - break; - } - else - { - cout << " FAILED (Tested with Hadoop Datafile Plugin File (" + DataFilePlugin + "), please re-enter or enter 'exit' to Investigate)" << endl<< endl; - } - } - } - - try { - sysConfig->setConfig("SystemConfig", "DataFilePlugin", DataFilePlugin); - } - catch(...) - { - cout << "ERROR: Problem setting DataFilePlugin in the InfiniDB System Configuration file" << endl; - return false; - } - - try { - sysConfig->setConfig("SystemConfig", "DataFileEnvFile", DataFileEnvFile); - } - catch(...) - { - cout << "ERROR: Problem setting DataFileEnvFile in the InfiniDB System Configuration file" << endl; - return false; + if ( storageType == "1" || storageType == "2") + break; + cout << endl << "Invalid Entry, please re-enter" << endl << endl; + if ( noPrompting ) + exit(1); } - + + if ( storageType == "1" ) + DBRootStorageType = "internal"; + else + DBRootStorageType = "external"; + try { - sysConfig->setConfig("SystemConfig", "DataFileLog", "OFF"); + sysConfig->setConfig(InstallSection, "DBRootStorageType", DBRootStorageType); } catch(...) { - cout << "ERROR: Problem setting DataFileLog in the InfiniDB System Configuration file" << endl; + cout << "ERROR: Problem setting DBRootStorageType in the InfiniDB System Configuration file" << endl; return false; } - - try { - sysConfig->setConfig("ExtentMap", "ExtentsPerSegmentFile", "1"); - } - catch(...) + + if( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) { - cout << "ERROR: Problem setting ExtentsPerSegmentFile in the InfiniDB System Configuration file" << endl; - return false; + try { + sysConfig->setConfig(InstallSection, "UMStorageType", DBRootStorageType); + } + catch(...) + { + cout << "ERROR: Problem setting UMStorageType in the InfiniDB System Configuration file" << endl; + return false; + } } } else { - hdfs = false; - - try { - sysConfig->setConfig("SystemConfig", "DataFilePlugin", ""); - } - catch(...) - { - cout << "ERROR: Problem setting DataFilePlugin in the InfiniDB System Configuration file" << endl; - return false; - } + sysConfig->setConfig(InstallSection, "GlusterConfig", "y"); + sysConfig->setConfig("PrimitiveServers", "DirectIO", "n"); + DBRootStorageType = "internal"; try { - sysConfig->setConfig("SystemConfig", "DataFileEnvFile", ""); + sysConfig->setConfig(InstallSection, "DBRootStorageType", DBRootStorageType); } catch(...) { - cout << "ERROR: Problem setting DataFileEnvFile in the InfiniDB System Configuration file" << endl; - return false; - } - - if ( !writeConfig(sysConfig) ) { - cout << "ERROR: Failed trying to update InfiniDB System Configuration file" << endl; + cout << "ERROR: Problem setting DBRootStorageType in the InfiniDB System Configuration file" << endl; return false; } } @@ -4821,6 +4171,8 @@ void snmpAppCheck() void setSystemName() { + cout << endl; + //setup System Name string systemName; try { @@ -4905,43 +4257,6 @@ bool makeModuleFile(string moduleName, string parentOAMModuleName) return true; } -/* - * Create a module file - */ -bool updateBash() -{ - string fileName = home + "/.bashrc"; - - ifstream newFile (fileName.c_str()); - - if (!rootUser) - { - string cmd = "echo export INFINIDB_INSTALL_DIR=" + installDir + " >> " + fileName; - system(cmd.c_str()); - - cmd = "echo export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFINIDB_INSTALL_DIR/lib:$INFINIDB_INSTALL_DIR/mysql/lib/mysql >> " + fileName; - system(cmd.c_str()); - } - - if ( hdfs ) - { - string cmd = "echo . " + installDir + "/bin/" + DataFileEnvFile + " >> " + fileName; - system(cmd.c_str()); - - if ( rootUser) - cmd = "su - hdfs -c 'hadoop fs -mkdir -p " + installDir + ";hadoop fs -chown root:root " + installDir + "' >/dev/null 2>&1"; - else - cmd = "sudo su - hdfs -c 'hadoop fs -mkdir -p " + installDir + ";hadoop fs -chown " + USER + ":" + USER + " " + installDir + "' >/dev/null 2>&1"; - - system(cmd.c_str()); - } - - newFile.close(); - - return true; - -} - void offLineAppCheck() { //check for system startup type, process offline or online option @@ -5208,20 +4523,20 @@ bool singleServerDBrootSetup() return true; } - -pthread_mutex_t THREAD_LOCK; -void remoteInstallThread(void *arg) + +void remoteInstallThread(string cmd) { - thread_data_t *data = (thread_data_t *)arg; + string command = cmd; - int rtnCode = system((data->command).c_str()); - if (WEXITSTATUS(rtnCode) != 0) { - pthread_mutex_lock(&THREAD_LOCK); + int rtnCode = system(command.c_str()); + if (rtnCode != 0) { cout << endl << "Failure with a remote module install, check install log files in /tmp" << endl; exit(1); } + remoteInstallCount--; + // exit thread pthread_exit(0); } diff --git a/oamapps/replayTransactionLog/Makefile.am b/oamapps/replayTransactionLog/Makefile.am index e894a953..f6a8e3a9 100644 --- a/oamapps/replayTransactionLog/Makefile.am +++ b/oamapps/replayTransactionLog/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/oamapps/replayTransactionLog/Makefile.in b/oamapps/replayTransactionLog/Makefile.in new file mode 100644 index 00000000..ca7ac67a --- /dev/null +++ b/oamapps/replayTransactionLog/Makefile.in @@ -0,0 +1,520 @@ +# Makefile.in generated by automake 1.9.6 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright (C) 2014 InfiniDB, Inc. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +bin_PROGRAMS = ReplayTransactionLog$(EXEEXT) +subdir = oamapps/replayTransactionLog +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +am__installdirs = "$(DESTDIR)$(bindir)" +binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +PROGRAMS = $(bin_PROGRAMS) +am_ReplayTransactionLog_OBJECTS = \ + ReplayTransactionLog-replaytransactionlog.$(OBJEXT) +ReplayTransactionLog_OBJECTS = $(am_ReplayTransactionLog_OBJECTS) +ReplayTransactionLog_LDADD = $(LDADD) +DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CXXFLAGS) $(CXXFLAGS) +CXXLD = $(CXX) +CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ + $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(ReplayTransactionLog_SOURCES) +DIST_SOURCES = $(ReplayTransactionLog_SOURCES) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +ALLOCA = @ALLOCA@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POW_LIB = @POW_LIB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +YACC = @YACC@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +etcdir = @etcdir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +idb_brm_libs = @idb_brm_libs@ +idb_cflags = @idb_cflags@ +idb_common_includes = @idb_common_includes@ +idb_common_ldflags = @idb_common_ldflags@ +idb_common_libs = @idb_common_libs@ +idb_cppflags = @idb_cppflags@ +idb_cxxflags = @idb_cxxflags@ +idb_exec_libs = @idb_exec_libs@ +idb_ldflags = @idb_ldflags@ +idb_oam_libs = @idb_oam_libs@ +idb_write_libs = @idb_write_libs@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localdir = @localdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +march_flags = @march_flags@ +mibdir = @mibdir@ +mkdir_p = @mkdir_p@ +mysqldir = @mysqldir@ +netsnmp_libs = @netsnmp_libs@ +oldincludedir = @oldincludedir@ +postdir = @postdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedir = @sharedir@ +sharedstatedir = @sharedstatedir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +toolsdir = @toolsdir@ +AM_CPPFLAGS = $(idb_cppflags) +AM_CFLAGS = $(idb_cflags) +AM_CXXFLAGS = $(idb_cxxflags) +AM_LDFLAGS = $(idb_ldflags) +ReplayTransactionLog_SOURCES = replaytransactionlog.cpp +ReplayTransactionLog_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +ReplayTransactionLog_LDFLAGS = @idb_common_ldflags@ @idb_exec_libs@ -lreplaytxnlog $(AM_LDFLAGS) +all: all-am + +.SUFFIXES: +.SUFFIXES: .cpp .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/replayTransactionLog/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu oamapps/replayTransactionLog/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-binPROGRAMS: $(bin_PROGRAMS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + if test -f $$p \ + || test -f $$p1 \ + ; then \ + f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ + $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ + else :; fi; \ + done + +uninstall-binPROGRAMS: + @$(NORMAL_UNINSTALL) + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ + rm -f "$(DESTDIR)$(bindir)/$$f"; \ + done + +clean-binPROGRAMS: + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f $$p $$f"; \ + rm -f $$p $$f ; \ + done +ReplayTransactionLog$(EXEEXT): $(ReplayTransactionLog_OBJECTS) $(ReplayTransactionLog_DEPENDENCIES) + @rm -f ReplayTransactionLog$(EXEEXT) + $(CXXLINK) $(ReplayTransactionLog_LDFLAGS) $(ReplayTransactionLog_OBJECTS) $(ReplayTransactionLog_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Po@am__quote@ + +.cpp.o: +@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< + +.cpp.obj: +@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.cpp.lo: +@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< + +ReplayTransactionLog-replaytransactionlog.o: replaytransactionlog.cpp +@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ReplayTransactionLog_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ReplayTransactionLog-replaytransactionlog.o -MD -MP -MF "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Tpo" -c -o ReplayTransactionLog-replaytransactionlog.o `test -f 'replaytransactionlog.cpp' || echo '$(srcdir)/'`replaytransactionlog.cpp; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Tpo" "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Po"; else rm -f "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='replaytransactionlog.cpp' object='ReplayTransactionLog-replaytransactionlog.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ReplayTransactionLog_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ReplayTransactionLog-replaytransactionlog.o `test -f 'replaytransactionlog.cpp' || echo '$(srcdir)/'`replaytransactionlog.cpp + +ReplayTransactionLog-replaytransactionlog.obj: replaytransactionlog.cpp +@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ReplayTransactionLog_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ReplayTransactionLog-replaytransactionlog.obj -MD -MP -MF "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Tpo" -c -o ReplayTransactionLog-replaytransactionlog.obj `if test -f 'replaytransactionlog.cpp'; then $(CYGPATH_W) 'replaytransactionlog.cpp'; else $(CYGPATH_W) '$(srcdir)/replaytransactionlog.cpp'; fi`; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Tpo" "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Po"; else rm -f "$(DEPDIR)/ReplayTransactionLog-replaytransactionlog.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='replaytransactionlog.cpp' object='ReplayTransactionLog-replaytransactionlog.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ReplayTransactionLog_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ReplayTransactionLog-replaytransactionlog.obj `if test -f 'replaytransactionlog.cpp'; then $(CYGPATH_W) 'replaytransactionlog.cpp'; else $(CYGPATH_W) '$(srcdir)/replaytransactionlog.cpp'; fi` + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) +installdirs: + for dir in "$(DESTDIR)$(bindir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: install-binPROGRAMS + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-binPROGRAMS uninstall-info-am + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ + clean-generic clean-libtool ctags distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-binPROGRAMS install-data install-data-am install-exec \ + install-exec-am install-info install-info-am install-man \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-binPROGRAMS uninstall-info-am + + +test: + +coverage: + +leakcheck: + +docs: + +bootstrap: install-data-am +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/oamapps/replayTransactionLog/tdriver.cpp b/oamapps/replayTransactionLog/tdriver.cpp index dd5e639e..d46854f5 100644 --- a/oamapps/replayTransactionLog/tdriver.cpp +++ b/oamapps/replayTransactionLog/tdriver.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * wweeks@calpont.com * * * @@ -25,6 +8,7 @@ using namespace std; #include #include #include +#include "sessionmonitor.h" #include "sessionmanager.h" #include diff --git a/oamapps/resourceMonitor/hardwareMonitor.cpp b/oamapps/resourceMonitor/hardwareMonitor.cpp index 542d6adc..785270a8 100644 --- a/oamapps/resourceMonitor/hardwareMonitor.cpp +++ b/oamapps/resourceMonitor/hardwareMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: hardwareMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/resourceMonitor/resourceMonitor.cpp b/oamapps/resourceMonitor/resourceMonitor.cpp index f680eefd..f6a14e7e 100644 --- a/oamapps/resourceMonitor/resourceMonitor.cpp +++ b/oamapps/resourceMonitor/resourceMonitor.cpp @@ -1,22 +1,5 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** - * $Id: resourceMonitor.cpp 3072 2013-04-04 19:04:45Z rdempsey $ + * $Id: resourceMonitor.cpp 1834 2011-02-08 14:37:11Z rdempsey $ * * Author: Zhixuan Zhu ***************************************************************************/ diff --git a/oamapps/resourceMonitor/tdriver.cpp b/oamapps/resourceMonitor/tdriver.cpp index 2b5bfe29..484ee4f3 100644 --- a/oamapps/resourceMonitor/tdriver.cpp +++ b/oamapps/resourceMonitor/tdriver.cpp @@ -1,21 +1,4 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/* $Id: tdriver.cpp 3072 2013-04-04 19:04:45Z rdempsey $ */ +/* $Id: tdriver.cpp 2 2006-08-30 13:29:53Z rdempsey $ */ #include #include diff --git a/oamapps/sendtrap/Makefile.am b/oamapps/sendtrap/Makefile.am deleted file mode 100644 index 1877d511..00000000 --- a/oamapps/sendtrap/Makefile.am +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id$ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = sendtrap -sendtrap_SOURCES = sendtrap.cpp -sendtrap_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -sendtrap_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ @idb_write_libs@ @netsnmp_libs@ $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/oamapps/sendtrap/Makefile.in b/oamapps/sendtrap/Makefile.in deleted file mode 100644 index 67f95e9a..00000000 --- a/oamapps/sendtrap/Makefile.in +++ /dev/null @@ -1,529 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id$ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = sendtrap$(EXEEXT) -subdir = oamapps/sendtrap -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_sendtrap_OBJECTS = sendtrap-sendtrap.$(OBJEXT) -sendtrap_OBJECTS = $(am_sendtrap_OBJECTS) -sendtrap_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(sendtrap_SOURCES) -DIST_SOURCES = $(sendtrap_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -sendtrap_SOURCES = sendtrap.cpp -sendtrap_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -sendtrap_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ @idb_write_libs@ @netsnmp_libs@ $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/sendtrap/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/sendtrap/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -sendtrap$(EXEEXT): $(sendtrap_OBJECTS) $(sendtrap_DEPENDENCIES) - @rm -f sendtrap$(EXEEXT) - $(CXXLINK) $(sendtrap_LDFLAGS) $(sendtrap_OBJECTS) $(sendtrap_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sendtrap-sendtrap.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -sendtrap-sendtrap.o: sendtrap.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sendtrap_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT sendtrap-sendtrap.o -MD -MP -MF "$(DEPDIR)/sendtrap-sendtrap.Tpo" -c -o sendtrap-sendtrap.o `test -f 'sendtrap.cpp' || echo '$(srcdir)/'`sendtrap.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/sendtrap-sendtrap.Tpo" "$(DEPDIR)/sendtrap-sendtrap.Po"; else rm -f "$(DEPDIR)/sendtrap-sendtrap.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='sendtrap.cpp' object='sendtrap-sendtrap.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sendtrap_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o sendtrap-sendtrap.o `test -f 'sendtrap.cpp' || echo '$(srcdir)/'`sendtrap.cpp - -sendtrap-sendtrap.obj: sendtrap.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sendtrap_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT sendtrap-sendtrap.obj -MD -MP -MF "$(DEPDIR)/sendtrap-sendtrap.Tpo" -c -o sendtrap-sendtrap.obj `if test -f 'sendtrap.cpp'; then $(CYGPATH_W) 'sendtrap.cpp'; else $(CYGPATH_W) '$(srcdir)/sendtrap.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/sendtrap-sendtrap.Tpo" "$(DEPDIR)/sendtrap-sendtrap.Po"; else rm -f "$(DEPDIR)/sendtrap-sendtrap.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='sendtrap.cpp' object='sendtrap-sendtrap.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sendtrap_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o sendtrap-sendtrap.obj `if test -f 'sendtrap.cpp'; then $(CYGPATH_W) 'sendtrap.cpp'; else $(CYGPATH_W) '$(srcdir)/sendtrap.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/sendtrap/sendtrap.cpp b/oamapps/sendtrap/sendtrap.cpp index f1e2afdb..784bd38d 100644 --- a/oamapps/sendtrap/sendtrap.cpp +++ b/oamapps/sendtrap/sendtrap.cpp @@ -128,9 +128,21 @@ int main(int argc, char **argv) size_t pid_oid_len = OID_LENGTH(PID_OID); const CALPONT_OID *tid_oid = TID_OID; size_t tid_oid_len = OID_LENGTH(TID_OID); - - string alarm_data = "CALALARM|" + oam.itoa(alarmID) + "|" + componentID + "|" + oam.itoa(state) + "|" + ModuleName + "|" + processName + "|" + oam.itoa(pid) + "|" + oam.itoa(tid); - + + // alarm_data + char alarm_data [100]; +// char* alarm_data; +// alarm_data = new char(100); + int pos; + pos = sprintf (alarm_data, "%s|", "CALALARM"); + pos += sprintf (alarm_data+pos, "%d|", alarmID); + pos += sprintf (alarm_data+pos, "%s|", componentID); + pos += sprintf (alarm_data+pos, "%d|", state); + pos += sprintf (alarm_data+pos, "%s|", ModuleName.c_str()); + pos += sprintf (alarm_data+pos, "%s|", processName.c_str()); + pos += sprintf (alarm_data+pos, "%d|", pid); + pos += sprintf (alarm_data+pos, "%d", tid); + netsnmp_variable_list *notification_vars = NULL; /* @@ -160,7 +172,7 @@ int main(int argc, char **argv) snmp_varlist_add_variable(¬ification_vars, calalarm_data_oid, calalarm_data_oid_len, ASN_OCTET_STR, - (u_char*)alarm_data.c_str(), alarm_data.length()); + (u_char*)alarm_data, strlen((char*)alarm_data)); snmp_varlist_add_variable(¬ification_vars, component_id_oid, component_id_oid_len, ASN_OCTET_STR, @@ -179,12 +191,12 @@ int main(int argc, char **argv) snmp_varlist_add_variable(¬ification_vars, sname_oid, sname_oid_len, ASN_OCTET_STR, - (u_char*)ModuleName.c_str(), ModuleName.length()); + (u_char*)&ModuleName, ModuleName.length()); snmp_varlist_add_variable(¬ification_vars, pname_oid, pname_oid_len, ASN_OCTET_STR, - (u_char*)processName.c_str(), processName.length()); + (u_char*)&processName, processName.length()); snmp_varlist_add_variable(¬ification_vars, pid_oid, pid_oid_len, diff --git a/oamapps/serverMonitor/Makefile.am b/oamapps/serverMonitor/Makefile.am index 63b4b67f..e41b821f 100644 --- a/oamapps/serverMonitor/Makefile.am +++ b/oamapps/serverMonitor/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/oamapps/serverMonitor/Makefile.in b/oamapps/serverMonitor/Makefile.in deleted file mode 100644 index 649329fe..00000000 --- a/oamapps/serverMonitor/Makefile.in +++ /dev/null @@ -1,660 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = ServerMonitor$(EXEEXT) -subdir = oamapps/serverMonitor -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_ServerMonitor_OBJECTS = ServerMonitor-main.$(OBJEXT) \ - ServerMonitor-serverMonitor.$(OBJEXT) \ - ServerMonitor-cpuMonitor.$(OBJEXT) \ - ServerMonitor-diskMonitor.$(OBJEXT) \ - ServerMonitor-memoryMonitor.$(OBJEXT) \ - ServerMonitor-procmonMonitor.$(OBJEXT) \ - ServerMonitor-msgProcessor.$(OBJEXT) \ - ServerMonitor-dbhealthMonitor.$(OBJEXT) \ - ServerMonitor-UMAutoSync.$(OBJEXT) -ServerMonitor_OBJECTS = $(am_ServerMonitor_OBJECTS) -ServerMonitor_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(ServerMonitor_SOURCES) -DIST_SOURCES = $(ServerMonitor_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -ServerMonitor_SOURCES = main.cpp serverMonitor.cpp cpuMonitor.cpp diskMonitor.cpp \ -memoryMonitor.cpp procmonMonitor.cpp msgProcessor.cpp dbhealthMonitor.cpp \ -UMAutoSync.cpp - -ServerMonitor_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -ServerMonitor_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/serverMonitor/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/serverMonitor/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -ServerMonitor$(EXEEXT): $(ServerMonitor_OBJECTS) $(ServerMonitor_DEPENDENCIES) - @rm -f ServerMonitor$(EXEEXT) - $(CXXLINK) $(ServerMonitor_LDFLAGS) $(ServerMonitor_OBJECTS) $(ServerMonitor_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-UMAutoSync.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-cpuMonitor.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-dbhealthMonitor.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-diskMonitor.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-main.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-memoryMonitor.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-msgProcessor.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-procmonMonitor.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ServerMonitor-serverMonitor.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -ServerMonitor-main.o: main.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-main.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-main.Tpo" -c -o ServerMonitor-main.o `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-main.Tpo" "$(DEPDIR)/ServerMonitor-main.Po"; else rm -f "$(DEPDIR)/ServerMonitor-main.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='ServerMonitor-main.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-main.o `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp - -ServerMonitor-main.obj: main.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-main.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-main.Tpo" -c -o ServerMonitor-main.obj `if test -f 'main.cpp'; then $(CYGPATH_W) 'main.cpp'; else $(CYGPATH_W) '$(srcdir)/main.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-main.Tpo" "$(DEPDIR)/ServerMonitor-main.Po"; else rm -f "$(DEPDIR)/ServerMonitor-main.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='ServerMonitor-main.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-main.obj `if test -f 'main.cpp'; then $(CYGPATH_W) 'main.cpp'; else $(CYGPATH_W) '$(srcdir)/main.cpp'; fi` - -ServerMonitor-serverMonitor.o: serverMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-serverMonitor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-serverMonitor.Tpo" -c -o ServerMonitor-serverMonitor.o `test -f 'serverMonitor.cpp' || echo '$(srcdir)/'`serverMonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-serverMonitor.Tpo" "$(DEPDIR)/ServerMonitor-serverMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-serverMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='serverMonitor.cpp' object='ServerMonitor-serverMonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-serverMonitor.o `test -f 'serverMonitor.cpp' || echo '$(srcdir)/'`serverMonitor.cpp - -ServerMonitor-serverMonitor.obj: serverMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-serverMonitor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-serverMonitor.Tpo" -c -o ServerMonitor-serverMonitor.obj `if test -f 'serverMonitor.cpp'; then $(CYGPATH_W) 'serverMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/serverMonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-serverMonitor.Tpo" "$(DEPDIR)/ServerMonitor-serverMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-serverMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='serverMonitor.cpp' object='ServerMonitor-serverMonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-serverMonitor.obj `if test -f 'serverMonitor.cpp'; then $(CYGPATH_W) 'serverMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/serverMonitor.cpp'; fi` - -ServerMonitor-cpuMonitor.o: cpuMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-cpuMonitor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-cpuMonitor.Tpo" -c -o ServerMonitor-cpuMonitor.o `test -f 'cpuMonitor.cpp' || echo '$(srcdir)/'`cpuMonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-cpuMonitor.Tpo" "$(DEPDIR)/ServerMonitor-cpuMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-cpuMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='cpuMonitor.cpp' object='ServerMonitor-cpuMonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-cpuMonitor.o `test -f 'cpuMonitor.cpp' || echo '$(srcdir)/'`cpuMonitor.cpp - -ServerMonitor-cpuMonitor.obj: cpuMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-cpuMonitor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-cpuMonitor.Tpo" -c -o ServerMonitor-cpuMonitor.obj `if test -f 'cpuMonitor.cpp'; then $(CYGPATH_W) 'cpuMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/cpuMonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-cpuMonitor.Tpo" "$(DEPDIR)/ServerMonitor-cpuMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-cpuMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='cpuMonitor.cpp' object='ServerMonitor-cpuMonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-cpuMonitor.obj `if test -f 'cpuMonitor.cpp'; then $(CYGPATH_W) 'cpuMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/cpuMonitor.cpp'; fi` - -ServerMonitor-diskMonitor.o: diskMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-diskMonitor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-diskMonitor.Tpo" -c -o ServerMonitor-diskMonitor.o `test -f 'diskMonitor.cpp' || echo '$(srcdir)/'`diskMonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-diskMonitor.Tpo" "$(DEPDIR)/ServerMonitor-diskMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-diskMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='diskMonitor.cpp' object='ServerMonitor-diskMonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-diskMonitor.o `test -f 'diskMonitor.cpp' || echo '$(srcdir)/'`diskMonitor.cpp - -ServerMonitor-diskMonitor.obj: diskMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-diskMonitor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-diskMonitor.Tpo" -c -o ServerMonitor-diskMonitor.obj `if test -f 'diskMonitor.cpp'; then $(CYGPATH_W) 'diskMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/diskMonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-diskMonitor.Tpo" "$(DEPDIR)/ServerMonitor-diskMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-diskMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='diskMonitor.cpp' object='ServerMonitor-diskMonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-diskMonitor.obj `if test -f 'diskMonitor.cpp'; then $(CYGPATH_W) 'diskMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/diskMonitor.cpp'; fi` - -ServerMonitor-memoryMonitor.o: memoryMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-memoryMonitor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-memoryMonitor.Tpo" -c -o ServerMonitor-memoryMonitor.o `test -f 'memoryMonitor.cpp' || echo '$(srcdir)/'`memoryMonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-memoryMonitor.Tpo" "$(DEPDIR)/ServerMonitor-memoryMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-memoryMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='memoryMonitor.cpp' object='ServerMonitor-memoryMonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-memoryMonitor.o `test -f 'memoryMonitor.cpp' || echo '$(srcdir)/'`memoryMonitor.cpp - -ServerMonitor-memoryMonitor.obj: memoryMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-memoryMonitor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-memoryMonitor.Tpo" -c -o ServerMonitor-memoryMonitor.obj `if test -f 'memoryMonitor.cpp'; then $(CYGPATH_W) 'memoryMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/memoryMonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-memoryMonitor.Tpo" "$(DEPDIR)/ServerMonitor-memoryMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-memoryMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='memoryMonitor.cpp' object='ServerMonitor-memoryMonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-memoryMonitor.obj `if test -f 'memoryMonitor.cpp'; then $(CYGPATH_W) 'memoryMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/memoryMonitor.cpp'; fi` - -ServerMonitor-procmonMonitor.o: procmonMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-procmonMonitor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-procmonMonitor.Tpo" -c -o ServerMonitor-procmonMonitor.o `test -f 'procmonMonitor.cpp' || echo '$(srcdir)/'`procmonMonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-procmonMonitor.Tpo" "$(DEPDIR)/ServerMonitor-procmonMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-procmonMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='procmonMonitor.cpp' object='ServerMonitor-procmonMonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-procmonMonitor.o `test -f 'procmonMonitor.cpp' || echo '$(srcdir)/'`procmonMonitor.cpp - -ServerMonitor-procmonMonitor.obj: procmonMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-procmonMonitor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-procmonMonitor.Tpo" -c -o ServerMonitor-procmonMonitor.obj `if test -f 'procmonMonitor.cpp'; then $(CYGPATH_W) 'procmonMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/procmonMonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-procmonMonitor.Tpo" "$(DEPDIR)/ServerMonitor-procmonMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-procmonMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='procmonMonitor.cpp' object='ServerMonitor-procmonMonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-procmonMonitor.obj `if test -f 'procmonMonitor.cpp'; then $(CYGPATH_W) 'procmonMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/procmonMonitor.cpp'; fi` - -ServerMonitor-msgProcessor.o: msgProcessor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-msgProcessor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-msgProcessor.Tpo" -c -o ServerMonitor-msgProcessor.o `test -f 'msgProcessor.cpp' || echo '$(srcdir)/'`msgProcessor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-msgProcessor.Tpo" "$(DEPDIR)/ServerMonitor-msgProcessor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-msgProcessor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='msgProcessor.cpp' object='ServerMonitor-msgProcessor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-msgProcessor.o `test -f 'msgProcessor.cpp' || echo '$(srcdir)/'`msgProcessor.cpp - -ServerMonitor-msgProcessor.obj: msgProcessor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-msgProcessor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-msgProcessor.Tpo" -c -o ServerMonitor-msgProcessor.obj `if test -f 'msgProcessor.cpp'; then $(CYGPATH_W) 'msgProcessor.cpp'; else $(CYGPATH_W) '$(srcdir)/msgProcessor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-msgProcessor.Tpo" "$(DEPDIR)/ServerMonitor-msgProcessor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-msgProcessor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='msgProcessor.cpp' object='ServerMonitor-msgProcessor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-msgProcessor.obj `if test -f 'msgProcessor.cpp'; then $(CYGPATH_W) 'msgProcessor.cpp'; else $(CYGPATH_W) '$(srcdir)/msgProcessor.cpp'; fi` - -ServerMonitor-dbhealthMonitor.o: dbhealthMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-dbhealthMonitor.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Tpo" -c -o ServerMonitor-dbhealthMonitor.o `test -f 'dbhealthMonitor.cpp' || echo '$(srcdir)/'`dbhealthMonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Tpo" "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='dbhealthMonitor.cpp' object='ServerMonitor-dbhealthMonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-dbhealthMonitor.o `test -f 'dbhealthMonitor.cpp' || echo '$(srcdir)/'`dbhealthMonitor.cpp - -ServerMonitor-dbhealthMonitor.obj: dbhealthMonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-dbhealthMonitor.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Tpo" -c -o ServerMonitor-dbhealthMonitor.obj `if test -f 'dbhealthMonitor.cpp'; then $(CYGPATH_W) 'dbhealthMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/dbhealthMonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Tpo" "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Po"; else rm -f "$(DEPDIR)/ServerMonitor-dbhealthMonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='dbhealthMonitor.cpp' object='ServerMonitor-dbhealthMonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-dbhealthMonitor.obj `if test -f 'dbhealthMonitor.cpp'; then $(CYGPATH_W) 'dbhealthMonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/dbhealthMonitor.cpp'; fi` - -ServerMonitor-UMAutoSync.o: UMAutoSync.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-UMAutoSync.o -MD -MP -MF "$(DEPDIR)/ServerMonitor-UMAutoSync.Tpo" -c -o ServerMonitor-UMAutoSync.o `test -f 'UMAutoSync.cpp' || echo '$(srcdir)/'`UMAutoSync.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-UMAutoSync.Tpo" "$(DEPDIR)/ServerMonitor-UMAutoSync.Po"; else rm -f "$(DEPDIR)/ServerMonitor-UMAutoSync.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='UMAutoSync.cpp' object='ServerMonitor-UMAutoSync.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-UMAutoSync.o `test -f 'UMAutoSync.cpp' || echo '$(srcdir)/'`UMAutoSync.cpp - -ServerMonitor-UMAutoSync.obj: UMAutoSync.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ServerMonitor-UMAutoSync.obj -MD -MP -MF "$(DEPDIR)/ServerMonitor-UMAutoSync.Tpo" -c -o ServerMonitor-UMAutoSync.obj `if test -f 'UMAutoSync.cpp'; then $(CYGPATH_W) 'UMAutoSync.cpp'; else $(CYGPATH_W) '$(srcdir)/UMAutoSync.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ServerMonitor-UMAutoSync.Tpo" "$(DEPDIR)/ServerMonitor-UMAutoSync.Po"; else rm -f "$(DEPDIR)/ServerMonitor-UMAutoSync.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='UMAutoSync.cpp' object='ServerMonitor-UMAutoSync.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ServerMonitor_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ServerMonitor-UMAutoSync.obj `if test -f 'UMAutoSync.cpp'; then $(CYGPATH_W) 'UMAutoSync.cpp'; else $(CYGPATH_W) '$(srcdir)/UMAutoSync.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/serverMonitor/UMAutoSync.cpp b/oamapps/serverMonitor/UMAutoSync.cpp index 78486313..d9765eea 100644 --- a/oamapps/serverMonitor/UMAutoSync.cpp +++ b/oamapps/serverMonitor/UMAutoSync.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: UMAutoSync.cpp 34 2006-09-29 21:13:54Z dhill $ * @@ -220,7 +203,7 @@ void rsync(std::string moduleName, std::string IPAddr, std::string rootPassword) string cmd = startup::StartUp::installDir() + "/bin/rsync.sh " + IPAddr + " " + rootPassword + " 1 > /tmp/rsync_" + moduleName + ".log"; int ret = system(cmd.c_str()); - if ( WEXITSTATUS(ret) == 0 ) + if ( ret == 0 ) { /* LoggingID lid(SERVER_MONITOR_LOG_ID); MessageLog ml(lid); diff --git a/oamapps/serverMonitor/cpuMonitor.cpp b/oamapps/serverMonitor/cpuMonitor.cpp index 3442e6c3..df8452cf 100644 --- a/oamapps/serverMonitor/cpuMonitor.cpp +++ b/oamapps/serverMonitor/cpuMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: cpuMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * @@ -113,10 +96,9 @@ void cpuMonitor() cpuMajor = moduleTypeConfig.ModuleCPUMajorThreshold; cpuMinor = moduleTypeConfig.ModuleCPUMinorThreshold; cpuMinorClear = moduleTypeConfig.ModuleCPUMinorClearThreshold; - } catch (...) + } catch (runtime_error e) { - sleep(5); - continue; + throw e; } if (RESOURCE_DEBUG) @@ -298,8 +280,8 @@ void cpuMonitor() pthread_mutex_unlock(&CPU_LOCK); - // sleep, 5 minutes - sleep(MONITOR_PERIOD*5); + // sleep + sleep(MONITOR_PERIOD); ++periodCounter; if ( periodCounter >= periodCount ) diff --git a/oamapps/serverMonitor/dbhealthMonitor.cpp b/oamapps/serverMonitor/dbhealthMonitor.cpp index 838e85af..8cac9acb 100644 --- a/oamapps/serverMonitor/dbhealthMonitor.cpp +++ b/oamapps/serverMonitor/dbhealthMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: dbhealthMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/serverMonitor/diskMonitor.cpp b/oamapps/serverMonitor/diskMonitor.cpp index c812f5f3..d13d6238 100644 --- a/oamapps/serverMonitor/diskMonitor.cpp +++ b/oamapps/serverMonitor/diskMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: diskMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * @@ -118,12 +101,12 @@ void diskMonitor() } } - string cloud = oam::UnassignedName; + string cloud = "n"; try { oam.getSystemConfig( "Cloud", cloud); } catch(...) { - cloud = oam::UnassignedName; + cloud = "n"; } //get Gluster Config setting @@ -490,7 +473,7 @@ void diskMonitor() fail = true; else { //second test for amazon, check volume status - if ( cloud != oam::UnassignedName ) { + if ( cloud == "amazon" ) { string volumeNameID = "PMVolumeName" + dbrootID; string volumeName = oam::UnassignedName; try { diff --git a/oamapps/serverMonitor/hardwareMonitor.cpp b/oamapps/serverMonitor/hardwareMonitor.cpp index 048506a5..275ff84e 100644 --- a/oamapps/serverMonitor/hardwareMonitor.cpp +++ b/oamapps/serverMonitor/hardwareMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: hardwareMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/serverMonitor/main.cpp b/oamapps/serverMonitor/main.cpp index 4b1e1d9a..f7527ec5 100644 --- a/oamapps/serverMonitor/main.cpp +++ b/oamapps/serverMonitor/main.cpp @@ -1,21 +1,11 @@ -/* Copyright (C) 2014 InfiniDB, Inc. +/*************************************************************************** + * $Id: main.cpp 34 2006-09-29 21:13:54Z dhill $ + * + * Copyright (C) 2009-2012 Calpont Corporationoration + * All rights reserved + * Author: David Hill + ***************************************************************************/ - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -#include "IDBPolicy.h" #include "serverMonitor.h" using namespace std; @@ -23,7 +13,6 @@ using namespace servermonitor; using namespace oam; using namespace logging; -extern int swapFlag; /***************************************************************************** * @brief main @@ -38,95 +27,37 @@ int main (int argc, char** argv) ServerMonitor serverMonitor; Oam oam; - //Launch Memory Monitor Thread and check if swap is in critical condition - pthread_t memoryMonitorThread; - pthread_create (&memoryMonitorThread, NULL, (void*(*)(void*)) &memoryMonitor, NULL); - - - // initialize IDBPolicy while waiting swap flag being set. - idbdatafile::IDBPolicy::configIDBPolicy(); - - // wait until swap flag is set. - while ( swapFlag == 0 ) - { - sleep(1); + try { + oam.processInitComplete("ServerMonitor"); + LoggingID lid(SERVER_MONITOR_LOG_ID); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("processInitComplete Successfully Called"); + msg.format(args); + ml.logInfoMessage(msg); } - - if ( swapFlag == 1 ) + catch (exception& ex) { - try { - oam.processInitFailure(); - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("processInitFailure Called"); - msg.format(args); - ml.logInfoMessage(msg); - sleep(5); - exit(1); - } - catch (exception& ex) - { - string error = ex.what(); - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("EXCEPTION ERROR on processInitComplete: "); - args.add(error); - msg.format(args); - ml.logErrorMessage(msg); - sleep(5); - exit(1); - } - catch(...) - { - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("EXCEPTION ERROR on processInitComplete: Caught unknown exception!"); - msg.format(args); - ml.logErrorMessage(msg); - sleep(5); - exit(1); - } + string error = ex.what(); + LoggingID lid(SERVER_MONITOR_LOG_ID); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("EXCEPTION ERROR on processInitComplete: "); + args.add(error); + msg.format(args); + ml.logErrorMessage(msg); } - else + catch(...) { - try { - oam.processInitComplete("ServerMonitor"); - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("processInitComplete Successfully Called"); - msg.format(args); - ml.logInfoMessage(msg); - } - catch (exception& ex) - { - string error = ex.what(); - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("EXCEPTION ERROR on processInitComplete: "); - args.add(error); - msg.format(args); - ml.logErrorMessage(msg); - } - catch(...) - { - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("EXCEPTION ERROR on processInitComplete: Caught unknown exception!"); - msg.format(args); - ml.logErrorMessage(msg); - } + LoggingID lid(SERVER_MONITOR_LOG_ID); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("EXCEPTION ERROR on processInitComplete: Caught unknown exception!"); + msg.format(args); + ml.logErrorMessage(msg); } //Ignore SIGPIPE signals @@ -272,6 +203,10 @@ int main (int argc, char** argv) pthread_t cpuMonitorThread; pthread_create (&cpuMonitorThread, NULL, (void*(*)(void*)) &cpuMonitor, NULL); + //Launch Memory Monitor Thread + pthread_t memoryMonitorThread; + pthread_create (&memoryMonitorThread, NULL, (void*(*)(void*)) &memoryMonitor, NULL); + //Launch Disk Monitor Thread pthread_t diskMonitorThread; pthread_create (&diskMonitorThread, NULL, (void*(*)(void*)) &diskMonitor, NULL); @@ -290,4 +225,3 @@ int main (int argc, char** argv) return 0; } - diff --git a/oamapps/serverMonitor/memoryMonitor.cpp b/oamapps/serverMonitor/memoryMonitor.cpp index 84c47124..542b7bdf 100644 --- a/oamapps/serverMonitor/memoryMonitor.cpp +++ b/oamapps/serverMonitor/memoryMonitor.cpp @@ -1,27 +1,9 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: memoryMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * * Author: Zhixuan Zhu ***************************************************************************/ -#include "cgroupconfigurator.h" #include "serverMonitor.h" using namespace std; @@ -33,7 +15,6 @@ using namespace servermonitor; unsigned long totalMem; ProcessMemoryList pml; -int swapFlag = 0; pthread_mutex_t MEMORY_LOCK; @@ -49,53 +30,80 @@ void memoryMonitor() int swapUsagePercent = 0; + struct sysinfo myinfo; + // set defaults - int memoryCritical = 90, - memoryMajor = 0, + int memoryCritical = 90, + memoryMajor = 0, memoryMinor = 0, - swapCritical = 90, - swapMajor = 80, + swapCritical = 90, + swapMajor = 80, swapMinor = 70; int day = 0; - //set monitoring period to 60 seconds - int monitorPeriod = MONITOR_PERIOD; - utils::CGroupConfigurator cg; + //set monitoring period to 10 seconds + int monitorPeriod = 10; while(true) { // Get MEMORY usage water mark from server configuration and compare ModuleTypeConfig moduleTypeConfig; Oam oam; - + try { oam.getSystemConfig (moduleTypeConfig); - memoryCritical = moduleTypeConfig.ModuleMemCriticalThreshold; - memoryMajor = moduleTypeConfig.ModuleMemMajorThreshold; + memoryCritical = moduleTypeConfig.ModuleMemCriticalThreshold; + memoryMajor = moduleTypeConfig.ModuleMemMajorThreshold; memoryMinor = moduleTypeConfig.ModuleMemMinorThreshold; - swapCritical = moduleTypeConfig.ModuleSwapCriticalThreshold; - swapMajor = moduleTypeConfig.ModuleSwapMajorThreshold; + swapCritical = moduleTypeConfig.ModuleSwapCriticalThreshold; + swapMajor = moduleTypeConfig.ModuleSwapMajorThreshold; swapMinor = moduleTypeConfig.ModuleSwapMinorThreshold; - } catch (...) + } catch (runtime_error e) + { + throw e; + } + + // get cache MEMORY stats + system("cat /proc/meminfo | grep Cached -m 1 | awk '{print $2}' > /tmp/cached"); + + ifstream oldFile ("/tmp/cached"); + + string strCache; + long long cache; + + char line[400]; + while (oldFile.getline(line, 400)) { - sleep(5); - continue; + strCache = line; + break; } + oldFile.close(); + + if (strCache.empty() ) + cache = 0; + else + cache = atol(strCache.c_str()) * 1024; + + try{ + sysinfo(&myinfo); + } + catch (...) {} //get memory stats - totalMem = cg.getTotalMemory(); - uint64_t freeMem = cg.getFreeMemory(); - uint64_t usedMem = totalMem - freeMem; + totalMem = myinfo.totalram ; + unsigned long freeMem = myinfo.freeram ; - //get swap stats - uint64_t totalSwap = cg.getTotalSwapSpace(); - uint64_t usedSwap = cg.getSwapInUse(); + // adjust for cache, which is available memory + unsigned long usedMem = totalMem - freeMem - cache; + //get swap stats + unsigned long totalSwap = myinfo.totalswap ; + unsigned long freeswap = myinfo.freeswap ; + unsigned long usedSwap = totalSwap - freeswap ; if ( totalSwap == 0 ) { swapUsagePercent = 0; - swapFlag = 2; //get current day, log warning only once a day time_t now; @@ -106,7 +114,7 @@ void memoryMonitor() if ( day != tm.tm_mday) { day = tm.tm_mday; - //Log this event + //Log this event LoggingID lid(SERVER_MONITOR_LOG_ID); MessageLog ml(lid); Message msg; @@ -123,7 +131,7 @@ void memoryMonitor() if ( totalMem == 0 ) { memoryUsagePercent = 0; - //Log this event + //Log this event LoggingID lid(SERVER_MONITOR_LOG_ID); MessageLog ml(lid); Message msg; @@ -137,7 +145,7 @@ void memoryMonitor() // check for Memory alarms if (memoryUsagePercent >= memoryCritical && memoryCritical > 0 ) { - if ( monitorPeriod == MONITOR_PERIOD ) { + if ( monitorPeriod == 10 ) { //first time called, log //adjust if over 100% if ( memoryUsagePercent > 100 ) @@ -163,7 +171,7 @@ void memoryMonitor() monitorPeriod = 1; } else if (memoryUsagePercent >= memoryMajor && memoryMajor > 0 ) { - monitorPeriod = MONITOR_PERIOD; + monitorPeriod = 10; LoggingID lid(SERVER_MONITOR_LOG_ID); MessageLog ml(lid); Message msg; @@ -175,7 +183,7 @@ void memoryMonitor() serverMonitor.sendResourceAlarm("Local-Memory", MEMORY_USAGE_MED, SET, memoryUsagePercent); } else if (memoryUsagePercent >= memoryMinor && memoryMinor > 0 ) { - monitorPeriod = MONITOR_PERIOD; + monitorPeriod = 10; LoggingID lid(SERVER_MONITOR_LOG_ID); MessageLog ml(lid); Message msg; @@ -187,7 +195,7 @@ void memoryMonitor() serverMonitor.sendResourceAlarm("Local-Memory", MEMORY_USAGE_LOW, SET, memoryUsagePercent); } else { - monitorPeriod = MONITOR_PERIOD; + monitorPeriod = 10; serverMonitor.checkMemoryAlarm("Local-Memory"); } @@ -220,7 +228,6 @@ void memoryMonitor() serverMonitor.checkSwapAction(); } else if (swapUsagePercent >= swapMinor && swapMinor > 0 ) { - swapFlag = 2; LoggingID lid(SERVER_MONITOR_LOG_ID); MessageLog ml(lid); Message msg; @@ -232,12 +239,9 @@ void memoryMonitor() serverMonitor.sendResourceAlarm("Swap", SWAP_USAGE_LOW, SET, swapUsagePercent); } else - { - swapFlag = 2; serverMonitor.checkSwapAlarm("Swap"); - } - // sleep, 1 minute + // sleep sleep(monitorPeriod); } // end of while loop @@ -358,27 +362,14 @@ void ServerMonitor::checkSwapAlarm(string alarmItem, ALARMS alarmID) void ServerMonitor::checkSwapAction() { Oam oam; - - if ( swapFlag == 0 ) { - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("Swap Space usage over Major threashold, startSystem failure"); - msg.format(args); - ml.logCriticalMessage(msg); - - swapFlag = 1; - sleep(5); - return; - } - - string swapAction = "restartSystem"; - + string swapAction = "stopSystem"; + try { oam.getSystemConfig ("SwapAction", swapAction); - } catch (...) - {} + } catch (runtime_error e) + { + throw e; + } if (swapAction == "none") return; diff --git a/oamapps/serverMonitor/msgProcessor.cpp b/oamapps/serverMonitor/msgProcessor.cpp index 0a6a6ae9..cff57513 100644 --- a/oamapps/serverMonitor/msgProcessor.cpp +++ b/oamapps/serverMonitor/msgProcessor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: msgProcessor.cpp 34 2006-09-29 21:13:54Z dhill $ * @@ -312,12 +295,9 @@ void msgProcessor() while(p != sdl.end()) { ackmsg << (*p).deviceName; - //ackmsg << (ByteStream::quadbyte) ((*p).totalBlocks / 1024) ; - //ackmsg << (ByteStream::quadbyte) ((*p).usedBlocks / 1024); - //ackmsg << (ByteStream::byte) (*p).usedPercent; - ackmsg << (uint64_t) ((*p).totalBlocks / 1024) ; - ackmsg << (uint64_t) ((*p).usedBlocks / 1024); - ackmsg << (uint8_t) (*p).usedPercent; + ackmsg << (ByteStream::quadbyte) ((*p).totalBlocks / 1024) ; + ackmsg << (ByteStream::quadbyte) ((*p).usedBlocks / 1024); + ackmsg << (ByteStream::byte) (*p).usedPercent; p++; } @@ -367,26 +347,11 @@ void msgProcessor() ifstream file (fileName.c_str()); if (!file) { - try { - LoggingID lid(SERVER_MONITOR_LOG_ID); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("File open error: "); - args.add(fileName); - msg.format(args); - ml.logErrorMessage(msg); - } - catch (...) - {} - - ackmsg << (ByteStream::byte) oam::API_FILE_OPEN_ERROR; + ackmsg << (ByteStream::byte) API_FILE_OPEN_ERROR; fIos.write(ackmsg); break; } - ackmsg << (ByteStream::byte) oam::API_SUCCESS; - // Read the file. Filter out anything we don't care about. Store // each SQL Start statement. When a SQL End statement is found, remove the // corresponding SQL statement from the collection. diff --git a/oamapps/serverMonitor/procmonMonitor.cpp b/oamapps/serverMonitor/procmonMonitor.cpp index 0ae09fb5..1e13dbfd 100644 --- a/oamapps/serverMonitor/procmonMonitor.cpp +++ b/oamapps/serverMonitor/procmonMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: procmonMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/serverMonitor/serverMonitor.cpp b/oamapps/serverMonitor/serverMonitor.cpp index ac61b764..da1f78b7 100644 --- a/oamapps/serverMonitor/serverMonitor.cpp +++ b/oamapps/serverMonitor/serverMonitor.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: serverMonitor.cpp 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/serverMonitor/serverMonitor.h b/oamapps/serverMonitor/serverMonitor.h index 87d11c99..43b5824e 100644 --- a/oamapps/serverMonitor/serverMonitor.h +++ b/oamapps/serverMonitor/serverMonitor.h @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * $Id: serverMonitor.h 34 2006-09-29 21:13:54Z dhill $ * diff --git a/oamapps/sessionWalker/Makefile.am b/oamapps/sessionWalker/Makefile.am index 941290c6..9092b24b 100644 --- a/oamapps/sessionWalker/Makefile.am +++ b/oamapps/sessionWalker/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/oamapps/sessionWalker/Makefile.in b/oamapps/sessionWalker/Makefile.in deleted file mode 100644 index 09a82436..00000000 --- a/oamapps/sessionWalker/Makefile.in +++ /dev/null @@ -1,529 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = sessionWalker$(EXEEXT) -subdir = oamapps/sessionWalker -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_sessionWalker_OBJECTS = sessionWalker-sessionwalker.$(OBJEXT) -sessionWalker_OBJECTS = $(am_sessionWalker_OBJECTS) -sessionWalker_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(sessionWalker_SOURCES) -DIST_SOURCES = $(sessionWalker_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -sessionWalker_SOURCES = sessionwalker.cpp -sessionWalker_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -sessionWalker_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ @idb_write_libs@ @netsnmp_libs@ $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/sessionWalker/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/sessionWalker/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -sessionWalker$(EXEEXT): $(sessionWalker_OBJECTS) $(sessionWalker_DEPENDENCIES) - @rm -f sessionWalker$(EXEEXT) - $(CXXLINK) $(sessionWalker_LDFLAGS) $(sessionWalker_OBJECTS) $(sessionWalker_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sessionWalker-sessionwalker.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -sessionWalker-sessionwalker.o: sessionwalker.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sessionWalker_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT sessionWalker-sessionwalker.o -MD -MP -MF "$(DEPDIR)/sessionWalker-sessionwalker.Tpo" -c -o sessionWalker-sessionwalker.o `test -f 'sessionwalker.cpp' || echo '$(srcdir)/'`sessionwalker.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/sessionWalker-sessionwalker.Tpo" "$(DEPDIR)/sessionWalker-sessionwalker.Po"; else rm -f "$(DEPDIR)/sessionWalker-sessionwalker.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='sessionwalker.cpp' object='sessionWalker-sessionwalker.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sessionWalker_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o sessionWalker-sessionwalker.o `test -f 'sessionwalker.cpp' || echo '$(srcdir)/'`sessionwalker.cpp - -sessionWalker-sessionwalker.obj: sessionwalker.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sessionWalker_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT sessionWalker-sessionwalker.obj -MD -MP -MF "$(DEPDIR)/sessionWalker-sessionwalker.Tpo" -c -o sessionWalker-sessionwalker.obj `if test -f 'sessionwalker.cpp'; then $(CYGPATH_W) 'sessionwalker.cpp'; else $(CYGPATH_W) '$(srcdir)/sessionwalker.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/sessionWalker-sessionwalker.Tpo" "$(DEPDIR)/sessionWalker-sessionwalker.Po"; else rm -f "$(DEPDIR)/sessionWalker-sessionwalker.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='sessionwalker.cpp' object='sessionWalker-sessionwalker.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(sessionWalker_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o sessionWalker-sessionwalker.obj `if test -f 'sessionwalker.cpp'; then $(CYGPATH_W) 'sessionwalker.cpp'; else $(CYGPATH_W) '$(srcdir)/sessionwalker.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/sessionWalker/sessionwalker.cpp b/oamapps/sessionWalker/sessionwalker.cpp index 5adc755a..77e9945c 100644 --- a/oamapps/sessionWalker/sessionwalker.cpp +++ b/oamapps/sessionWalker/sessionwalker.cpp @@ -1,22 +1,5 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** - * $Id: sessionwalker.cpp 3072 2013-04-04 19:04:45Z rdempsey $ + * $Id: sessionwalker.cpp 1834 2011-02-08 14:37:11Z rdempsey $ * * jrodriguez@calpont.com * * diff --git a/oamapps/sessionWalker/tdriver.cpp b/oamapps/sessionWalker/tdriver.cpp index 8563096a..eb64015d 100644 --- a/oamapps/sessionWalker/tdriver.cpp +++ b/oamapps/sessionWalker/tdriver.cpp @@ -1,20 +1,3 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** * jrodriguez@calpont.com * * * @@ -64,7 +47,7 @@ int createTxns(const int& start, const int& end) { verifyLen=manager->verifySize(); for (int idx = first; idxnewTxnID((uint32_t)idx+1000); + managerTxns[idx] = manager->newTxnID((u_int32_t)idx+1000); CPPUNIT_ASSERT(managerTxns[idx].id>0); CPPUNIT_ASSERT(managerTxns[idx].valid==true); verifyLen=manager->verifySize(); @@ -138,7 +121,7 @@ void MonitorTestPlan_1() { monitor->AgeLimit(sleepTime); toTxns.clear(); toTxns = monitor->timedOutTxns(); // get timed out txns - CPPUNIT_ASSERT(toTxns.size()==(uint32_t)txnCntIncr*idx); + CPPUNIT_ASSERT(toTxns.size()==(uint)txnCntIncr*idx); delete monitor; } diff --git a/oamapps/traphandler/Makefile.am b/oamapps/traphandler/Makefile.am index 82a9ac19..08063599 100644 --- a/oamapps/traphandler/Makefile.am +++ b/oamapps/traphandler/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/oamapps/traphandler/Makefile.in b/oamapps/traphandler/Makefile.in deleted file mode 100644 index 0493625f..00000000 --- a/oamapps/traphandler/Makefile.in +++ /dev/null @@ -1,529 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = trapHandler$(EXEEXT) -subdir = oamapps/traphandler -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_trapHandler_OBJECTS = trapHandler-trapHandler.$(OBJEXT) -trapHandler_OBJECTS = $(am_trapHandler_OBJECTS) -trapHandler_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(trapHandler_SOURCES) -DIST_SOURCES = $(trapHandler_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -trapHandler_SOURCES = trapHandler.cpp -trapHandler_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -trapHandler_LDFLAGS = $(idb_common_ldflags) $(idb_common_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu oamapps/traphandler/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu oamapps/traphandler/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -trapHandler$(EXEEXT): $(trapHandler_OBJECTS) $(trapHandler_DEPENDENCIES) - @rm -f trapHandler$(EXEEXT) - $(CXXLINK) $(trapHandler_LDFLAGS) $(trapHandler_OBJECTS) $(trapHandler_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/trapHandler-trapHandler.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -trapHandler-trapHandler.o: trapHandler.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(trapHandler_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT trapHandler-trapHandler.o -MD -MP -MF "$(DEPDIR)/trapHandler-trapHandler.Tpo" -c -o trapHandler-trapHandler.o `test -f 'trapHandler.cpp' || echo '$(srcdir)/'`trapHandler.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/trapHandler-trapHandler.Tpo" "$(DEPDIR)/trapHandler-trapHandler.Po"; else rm -f "$(DEPDIR)/trapHandler-trapHandler.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='trapHandler.cpp' object='trapHandler-trapHandler.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(trapHandler_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o trapHandler-trapHandler.o `test -f 'trapHandler.cpp' || echo '$(srcdir)/'`trapHandler.cpp - -trapHandler-trapHandler.obj: trapHandler.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(trapHandler_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT trapHandler-trapHandler.obj -MD -MP -MF "$(DEPDIR)/trapHandler-trapHandler.Tpo" -c -o trapHandler-trapHandler.obj `if test -f 'trapHandler.cpp'; then $(CYGPATH_W) 'trapHandler.cpp'; else $(CYGPATH_W) '$(srcdir)/trapHandler.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/trapHandler-trapHandler.Tpo" "$(DEPDIR)/trapHandler-trapHandler.Po"; else rm -f "$(DEPDIR)/trapHandler-trapHandler.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='trapHandler.cpp' object='trapHandler-trapHandler.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(trapHandler_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o trapHandler-trapHandler.obj `if test -f 'trapHandler.cpp'; then $(CYGPATH_W) 'trapHandler.cpp'; else $(CYGPATH_W) '$(srcdir)/trapHandler.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/oamapps/traphandler/tdriver.cpp b/oamapps/traphandler/tdriver.cpp index 5f1a16c6..8a273b24 100644 --- a/oamapps/traphandler/tdriver.cpp +++ b/oamapps/traphandler/tdriver.cpp @@ -1,21 +1,4 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/* $Id: tdriver.cpp 3072 2013-04-04 19:04:45Z rdempsey $ */ +/* $Id: tdriver.cpp 2 2006-08-30 13:29:53Z rdempsey $ */ #include #include diff --git a/oamapps/traphandler/trapHandler.cpp b/oamapps/traphandler/trapHandler.cpp index 2622998b..28794147 100644 --- a/oamapps/traphandler/trapHandler.cpp +++ b/oamapps/traphandler/trapHandler.cpp @@ -1,5 +1,5 @@ /****************************************************************************************** -* $Id: trapHandler.cpp 3151 2013-07-17 14:54:10Z rdempsey $ +* $Id: trapHandler.cpp 1969 2011-08-19 17:36:32Z dhill $ * * Author: Zhixuan Zhu ******************************************************************************************/ @@ -10,24 +10,17 @@ #include #include #include -using namespace std; - #include "snmpmanager.h" #include "alarm.h" -using namespace snmpmanager; #include "liboamcpp.h" -using namespace oam; #include "messagelog.h" #include "messageobj.h" #include "loggingid.h" -using namespace logging; - -#include "IDBDataFile.h" -#include "IDBPolicy.h" -using namespace idbdatafile; - -namespace { +using namespace std; +using namespace snmpmanager; +using namespace oam; +using namespace logging; /** * constants define @@ -38,232 +31,304 @@ const char* DELIM = "|"; const char* AGENT_TRAP = "agentTrap"; const unsigned int CTN_INTERVAL = 30*60; -/***************************************************************************************** -* @brief getNextToken -* -* purpose: Get next token in incoming Alarm Statement -* -*****************************************************************************************/ -char* getNextToken() -{ - char* token = strtok (NULL, DELIM); - if (token == NULL) - { - // TODO: call system log api to log the error - throw runtime_error (errMsg); - } - return token; -} - -/***************************************************************************************** -* @brief rewriteActiveLog -* -* purpose: Update Active Alarm file, called to remove Cleared alarm -* -*****************************************************************************************/ -void rewriteActiveLog (const AlarmList& alarmList) -{ - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("rewriteAlarmLog Called"); - msg.format(args); - ml.logDebugMessage(msg); - } +/** + * @brief get next token of alarm data from input stream + */ +char* getNextToken (); - // delete the old file - unlink (ACTIVE_ALARM_FILE.c_str()); - - // create new file - int fd = open(ACTIVE_ALARM_FILE.c_str(), O_RDWR|O_CREAT, 0666); - - // Aquire an exclusive lock - if (flock(fd,LOCK_EX) == -1) { - throw runtime_error ("Lock active alarm log file error"); - } +/** + * @brief set alarm data from alarm configuration file + */ +void configAlarm (Alarm &); - ofstream activeAlarmFile (ACTIVE_ALARM_FILE.c_str()); - - AlarmList::const_iterator i; - for (i = alarmList.begin(); i != alarmList.end(); ++i) - { - activeAlarmFile << i->second; - } +/** + * @brief process alarm + */ +void processAlarm (Alarm &); - activeAlarmFile.close(); +/** + * @brief log alarm to historical alarm file + */ +void logAlarm (const Alarm &, string fileName); - // Release lock - if (flock(fd,LOCK_UN)==-1) - { - throw runtime_error ("Release lock active alarm log file error"); - } - close(fd); -} +/** + * @brief rewrite active alarm file after removing alarm + */ +void rewriteActiveLog (AlarmList &); /***************************************************************************************** -* @brief logAlarm +* @brief main function * -* purpose: Log Alarm in Active Alarm or Historical Alarm file +* purpose: Parse incoming ALARM statement into calAlarm class * *****************************************************************************************/ -void logAlarm (const Alarm& calAlarm, const string& fileName) -{ - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("logAlarm Called"); - msg.format(args); - ml.logDebugMessage(msg); - } +int main (int argc, char *argv[]) { - int fd = open(fileName.c_str(), O_RDWR|O_CREAT, 0666); - ofstream AlarmFile (fileName.c_str(), ios::app); + if (argc != 2) + exit (0); + + Alarm calAlarm; - // Aquire an exclusive lock - if (flock(fd,LOCK_EX) == -1) { - throw runtime_error ("Lock file error: " + fileName); - } + char buf[100]; + char* alarmData; + char* token; + bool successFlag = false; - AlarmFile << calAlarm; - AlarmFile.close(); - - // Release lock - if (flock(fd,LOCK_UN)==-1) - { - throw runtime_error ("Release lock file error: " + fileName); + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("trapHandler Launched"); + msg.format(args); + ml.logDebugMessage(msg); } - close(fd); -} - -/***************************************************************************************** -* @brief processAlarm -* -* purpose: Process Alarm by updating Active Alarm and Historical Alarm files -* -*****************************************************************************************/ -void processAlarm(const Alarm& calAlarm) -{ - bool logActiveFlag = (calAlarm.getState() == CLEAR ? false: true); - bool logHistFlag = true; - if (calAlarm.getState() == CLEAR ) - logHistFlag = false; - - // get active alarms - AlarmList alarmList; - SNMPManager sm; - sm.getActiveAlarm (alarmList); - - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("processAlarm Called"); - msg.format(args); - ml.logDebugMessage(msg); - } - - AlarmList::iterator i; - for (i = alarmList.begin(); i != alarmList.end(); ++i) - { - // check if matching ID - if (calAlarm.getAlarmID() != (i->second).getAlarmID() ) { - continue; + // read alarm data + while (cin.getline(buf,100)) + { + // Alarm data + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("Alarm Data:"); + args.add(buf); + msg.format(args); + ml.logDebugMessage(msg); + } + // search for CALALARM + if ((alarmData = strstr(buf, "CALALARM")) == NULL) + continue; + + successFlag = true; + token = strtok (alarmData, DELIM); + + // alarmData format: CALALARM|alarmID|componentID|1(set)/0(clear)|server|process + // alarmID + try { + token = getNextToken(); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("getNextToken error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); } - // check if the same fault component on same server - if (calAlarm.getComponentID().compare((i->second).getComponentID()) == 0 && - calAlarm.getSname().compare((i->second).getSname()) == 0) - { - // for set alarm, don't log - if (calAlarm.getState() == SET ) - { - logActiveFlag = false; - logHistFlag = false; - break; - } - - // for clear alarm, remove the set by rewritting the file - else if (calAlarm.getState() == CLEAR ) - { - logActiveFlag = false; - logHistFlag = true; - //cout << "size before: " << alarmList.size(); - alarmList.erase (i); - //cout << " size after: " << alarmList.size() << endl; - try { - rewriteActiveLog (alarmList); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("rewriteActiveLog error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); - } - break; - } - } - } // end of for loop - - if (logActiveFlag) { + calAlarm.setAlarmID (atoi(token)); + + // componentID try { - logAlarm (calAlarm, ACTIVE_ALARM_FILE); - } catch (runtime_error& e) + token = getNextToken(); + } catch (runtime_error e) { if (::DEBUG) { LoggingID lid(11); MessageLog ml(lid); Message msg; Message::Args args; - args.add("logAlarm error:"); + args.add("getNextToken error:"); args.add(e.what()); msg.format(args); ml.logDebugMessage(msg); } exit(1); } - } - - if (logHistFlag) { - // log historical alarm + calAlarm.setComponentID (token); + + // state try { - logAlarm (calAlarm, ALARM_FILE); - } catch (runtime_error& e) + token = getNextToken(); + } catch (runtime_error e) { if (::DEBUG) { LoggingID lid(11); MessageLog ml(lid); Message msg; Message::Args args; - args.add("logAlarm error:"); + args.add("getNextToken error:"); args.add(e.what()); msg.format(args); ml.logDebugMessage(msg); } exit(1); } - } -} + calAlarm.setState (atoi(token)); + + // sname + try { + token = getNextToken(); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("getNextToken error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); + } + calAlarm.setSname (token); -/***************************************************************************************** -* @brief configAlarm + // pname + try { + token = getNextToken(); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("getNextToken error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); + } + calAlarm.setPname (token); + + // distinguish agent trap and process trap. + // agent trap set pid and tid 0. + if (strcmp (argv[1], AGENT_TRAP) == 0) + { + calAlarm.setPid (0); + calAlarm.setTid (0); + } + // process trap continues to get pid from alarm data + else + { + // pid + try { + token = getNextToken(); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("getNextToken error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); + } + calAlarm.setPid (atoi(token)); + + // tid + try { + token = getNextToken(); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("getNextToken error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); + } + calAlarm.setTid (atoi(token)); + } + + if (::DEBUG){ + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("Alarm Info:"); + args.add(calAlarm.getAlarmID()); + args.add(calAlarm.getComponentID()); + args.add(calAlarm.getState()); + msg.format(args); + ml.logDebugMessage(msg); + + cout << calAlarm.getAlarmID() << ":" + << calAlarm.getComponentID() << ":" + << calAlarm.getState() << endl; + } + // break while loop. ignore the other info carried by + // the trap. May need to retrieve more info in the future. + break; + } + + // not valid alarm data if no "CALALARM" found + if (!successFlag){ + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("Error: not valid alarm data if no 'CALALARM' found"); + msg.format(args); + ml.logDebugMessage(msg); + exit(1); + } + + // Get alarm configuration + try { + configAlarm (calAlarm); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("configAlarm error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); + } + + return 0; +} + +/***************************************************************************************** +* @brief getNextToken +* +* purpose: Get next token in incoming Alarm Statement +* +*****************************************************************************************/ +char* getNextToken() +{ + char* token = strtok (NULL, DELIM); + if (token == NULL) + { + // TODO: call system log api to log the error + throw runtime_error (errMsg); + } + return token; +} + +/***************************************************************************************** +* @brief configAlarm * * purpose: Get Config Data for Incoming alarm * *****************************************************************************************/ -void configAlarm (Alarm& calAlarm) +void configAlarm (Alarm &calAlarm) { int alarmID = calAlarm.getAlarmID(); Oam oam; @@ -326,7 +391,7 @@ void configAlarm (Alarm& calAlarm) return; } } - } catch (runtime_error& e) + } catch (runtime_error e) { if (::DEBUG) { LoggingID lid(11); @@ -338,254 +403,114 @@ void configAlarm (Alarm& calAlarm) msg.format(args); ml.logDebugMessage(msg); } - throw; + throw e; } // process alarm processAlarm (calAlarm); } -} //anon namespace - /***************************************************************************************** -* @brief main function +* @brief processAlarm * -* purpose: Parse incoming ALARM statement into calAlarm class +* purpose: Process Alarm by updating Active Alarm and Historical Alarm files * *****************************************************************************************/ -int main (int argc, char *argv[]) { - - if (argc != 2) - exit (0); - - Alarm calAlarm; - - char buf[100]; - char* alarmData; - char* token; - bool successFlag = false; - - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("trapHandler Launched"); - msg.format(args); - ml.logDebugMessage(msg); +void processAlarm (Alarm &calAlarm) +{ + bool logFlag = (calAlarm.getState() == CLEAR ? false: true); + + // get active alarms + AlarmList alarmList; + SNMPManager sm; + sm.getActiveAlarm (alarmList); + + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("processAlarm Called"); + msg.format(args); + ml.logDebugMessage(msg); } - - // read alarm data - while (cin.getline(buf,100)) - { - // Alarm data - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("Alarm Data:"); - args.add(buf); - msg.format(args); - ml.logDebugMessage(msg); - } - // search for CALALARM - if ((alarmData = strstr(buf, "CALALARM")) == NULL) - continue; - - successFlag = true; - token = strtok (alarmData, DELIM); - - // alarmData format: CALALARM|alarmID|componentID|1(set)/0(clear)|server|process - // alarmID - try { - token = getNextToken(); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("getNextToken error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); + + AlarmList::iterator i; + for (i = alarmList.begin(); i != alarmList.end(); ++i) + { + // check if matching ID + if (calAlarm.getAlarmID() != (i->second).getAlarmID() ) { + continue; } + // check if the same fault component on same server + if (calAlarm.getComponentID().compare((i->second).getComponentID()) == 0 && + calAlarm.getSname().compare((i->second).getSname()) == 0) + { + // for set alarm, don't log to active + if (calAlarm.getState() == SET ) + { + logFlag = false; + break; + } - calAlarm.setAlarmID (atoi(token)); - - // componentID - try { - token = getNextToken(); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("getNextToken error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); - } - calAlarm.setComponentID (token); - - // state - try { - token = getNextToken(); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("getNextToken error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); - } - calAlarm.setState (atoi(token)); - - // sname - try { - token = getNextToken(); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("getNextToken error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); - } - calAlarm.setSname (token); + // for clear alarm, remove the set by rewritting the file + else if (calAlarm.getState() == CLEAR ) + { + logFlag = false; + //cout << "size before: " << alarmList.size(); + alarmList.erase (i); + //cout << " size after: " << alarmList.size() << endl; + try { + rewriteActiveLog (alarmList); + } catch (runtime_error e) + { + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("rewriteActiveLog error:"); + args.add(e.what()); + msg.format(args); + ml.logDebugMessage(msg); + } + exit(1); + } + break; + } + } + } // end of for loop - // pname + if (logFlag) { try { - token = getNextToken(); - } catch (runtime_error& e) + logAlarm (calAlarm, ACTIVE_ALARM_FILE); + } catch (runtime_error e) { if (::DEBUG) { LoggingID lid(11); MessageLog ml(lid); Message msg; Message::Args args; - args.add("getNextToken error:"); + args.add("logAlarm error:"); args.add(e.what()); msg.format(args); ml.logDebugMessage(msg); } exit(1); } - calAlarm.setPname (token); - - // distinguish agent trap and process trap. - // agent trap set pid and tid 0. - if (strcmp (argv[1], AGENT_TRAP) == 0) - { - calAlarm.setPid (0); - calAlarm.setTid (0); - } - // process trap continues to get pid from alarm data - else - { - // pid - try { - token = getNextToken(); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("getNextToken error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); - } - calAlarm.setPid (atoi(token)); - - // tid - try { - token = getNextToken(); - } catch (runtime_error& e) - { - if (::DEBUG) { - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("getNextToken error:"); - args.add(e.what()); - msg.format(args); - ml.logDebugMessage(msg); - } - exit(1); - } - calAlarm.setTid (atoi(token)); - } - - if (::DEBUG){ - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("Alarm Info:"); - args.add(calAlarm.getAlarmID()); - args.add(calAlarm.getComponentID()); - args.add(calAlarm.getState()); - msg.format(args); - ml.logDebugMessage(msg); - - cout << calAlarm.getAlarmID() << ":" - << calAlarm.getComponentID() << ":" - << calAlarm.getState() << endl; - } - // break while loop. ignore the other info carried by - // the trap. May need to retrieve more info in the future. - break; } - - // not valid alarm data if no "CALALARM" found - if (!successFlag){ - LoggingID lid(11); - MessageLog ml(lid); - Message msg; - Message::Args args; - args.add("Error: not valid alarm data if no 'CALALARM' found"); - msg.format(args); - ml.logDebugMessage(msg); - exit(1); - } - - // Get alarm configuration + + // log historical alarm try { - configAlarm (calAlarm); - } catch (runtime_error& e) + logAlarm (calAlarm, ALARM_FILE); + } catch (runtime_error e) { if (::DEBUG) { LoggingID lid(11); MessageLog ml(lid); Message msg; Message::Args args; - args.add("configAlarm error:"); + args.add("logAlarm error:"); args.add(e.what()); msg.format(args); ml.logDebugMessage(msg); @@ -593,7 +518,89 @@ int main (int argc, char *argv[]) { exit(1); } - return 0; } -// vim:ts=4 sw=4: +/***************************************************************************************** +* @brief logAlarm +* +* purpose: Log Alarm in Active Alarm or Historical Alarm file +* +*****************************************************************************************/ +void logAlarm (const Alarm &calAlarm, string fileName) +{ + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("logAlarm Called"); + msg.format(args); + ml.logDebugMessage(msg); + } + + int fd = open(fileName.c_str(), O_RDWR|O_CREAT, 0666); + ofstream AlarmFile (fileName.c_str(), ios::app); + + // Aquire an exclusive lock + if (flock(fd,LOCK_EX) == -1) { + throw runtime_error ("Lock file error: " + fileName); + } + + AlarmFile << calAlarm; + AlarmFile.close(); + + // Release lock + if (flock(fd,LOCK_UN)==-1) + { + throw runtime_error ("Release lock file error: " + fileName); + } + + close(fd); +} + +/***************************************************************************************** +* @brief rewriteActiveLog +* +* purpose: Update Active Alarm file, called to remove Cleared alarm +* +*****************************************************************************************/ +void rewriteActiveLog (AlarmList &alarmList) +{ + if (::DEBUG) { + LoggingID lid(11); + MessageLog ml(lid); + Message msg; + Message::Args args; + args.add("rewriteAlarmLog Called"); + msg.format(args); + ml.logDebugMessage(msg); + } + + // delete the old file + unlink (ACTIVE_ALARM_FILE.c_str()); + + // create new file + int fd = open(ACTIVE_ALARM_FILE.c_str(), O_RDWR|O_CREAT, 0666); + + // Aquire an exclusive lock + if (flock(fd,LOCK_EX) == -1) { + throw runtime_error ("Lock active alarm log file error"); + } + + ofstream activeAlarmFile (ACTIVE_ALARM_FILE.c_str()); + + AlarmList::iterator i; + for (i = alarmList.begin(); i != alarmList.end(); ++i) + { + activeAlarmFile << i->second; + } + + activeAlarmFile.close(); + + // Release lock + if (flock(fd,LOCK_UN)==-1) + { + throw runtime_error ("Release lock active alarm log file error"); + } + close(fd); +} diff --git a/primitives/Makefile.am b/primitives/Makefile.am index 822d1ae1..a641cf2f 100644 --- a/primitives/Makefile.am +++ b/primitives/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. SUBDIRS = blockcache linux-port primproc diff --git a/primitives/Makefile.in b/primitives/Makefile.in index 80d46f1d..9d7cb1a3 100644 --- a/primitives/Makefile.in +++ b/primitives/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. srcdir = @srcdir@ top_srcdir = @top_srcdir@ VPATH = @srcdir@ @@ -55,9 +55,8 @@ host_triplet = @host@ subdir = primitives DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -134,9 +133,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -178,7 +174,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -192,11 +187,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/primitives/blockcache/Makefile.am b/primitives/blockcache/Makefile.am index 72fbda72..9767ae7f 100644 --- a/primitives/blockcache/Makefile.am +++ b/primitives/blockcache/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/primitives/blockcache/Makefile.in b/primitives/blockcache/Makefile.in index 034e945d..bf88f395 100644 --- a/primitives/blockcache/Makefile.in +++ b/primitives/blockcache/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ @@ -58,9 +58,8 @@ host_triplet = @host@ subdir = primitives/blockcache DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -153,9 +152,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -197,7 +193,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -211,11 +206,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/primitives/blockcache/bcTest.cpp b/primitives/blockcache/bcTest.cpp index c3a777e2..243fa1a9 100644 --- a/primitives/blockcache/bcTest.cpp +++ b/primitives/blockcache/bcTest.cpp @@ -79,8 +79,8 @@ void* thr_client(void* clientArgs) { uint64_t noOpCount=0; thr_wait_t* clientWait = (thr_wait_t*)clientArgs; struct timeval tv, tv2; - uint32_t randstate=0; - randstate = static_cast(tv.tv_usec); + uint randstate=0; + randstate = static_cast(tv.tv_usec); pthread_mutex_lock(&clientWait->fMutex); clientWait->predicate++; pthread_mutex_unlock(&clientWait->fMutex); @@ -91,10 +91,10 @@ void* thr_client(void* clientArgs) { FileBuffer* fbPtr=NULL; int ret=0; int idx=0; - uint32_t jdx=0; - uint32_t l=0; - uint32_t m=0; - uint32_t start=0, max=0, size=0; + uint jdx=0; + uint l=0; + uint m=0; + uint start=0, max=0, size=0; LBIDRange_v& r=range_thr[0]; for(idx=0; idxcacheSize) @@ -189,7 +189,7 @@ void ReadRange(const LBIDRange_v& v) int found=0; int notfound=0; int ret=0; - for(uint32_t i=0; icheck(lbid, ver, txn, flg, compType, wasBlockInCache); } /** * @brief verify all Disk Blocks for the LBID range are loaded into the Cache **/ - inline void check(const BRM::InlineLBIDRange& range, const BRM::QueryContext &ver, const BRM::VER_t txn, const int compType, + inline void check(const BRM::InlineLBIDRange& range, const BRM::VER_t ver, const BRM::VER_t txn, const int compType, uint32_t& rCount) { fBCCBrp->check(range, ver, txn, compType, rCount); } @@ -82,15 +82,21 @@ class blockCacheClient **/ inline const int read(const BRM::LBID_t& lbid, const BRM::VER_t& ver, void* bufferPtr) { return fBCCBrp->read(lbid, ver, bufferPtr); } + + /** + * @brief retrieve all disk Blocks in the LBIDRange range and insert them into fbList + **/ + inline const int read(const BRM::InlineLBIDRange& range, FileBufferList_t& fbList, const BRM::VER_t ver) { + return fBCCBrp->read(range, fbList, ver); } - inline const int getBlock(const BRM::LBID_t& lbid, const BRM::QueryContext &ver, const BRM::VER_t txn, const int compType, + inline const int getBlock(const BRM::LBID_t& lbid, const BRM::VER_t& ver, const BRM::VER_t txn, const int compType, void* bufferPtr, bool flg, bool &wasCached, bool *wasVersioned = NULL, bool insertIntoCache = true, bool readFromCache = true) { return fBCCBrp->getBlock(lbid, ver, txn, compType, bufferPtr, flg, wasCached, wasVersioned, insertIntoCache, readFromCache); } inline int getCachedBlocks(const BRM::LBID_t *lbids, const BRM::VER_t *vers, uint8_t **bufferPtrs, - bool *wasCached, uint32_t blockCount) + bool *wasCached, uint blockCount) { return fBCCBrp->getCachedBlocks(lbids, vers, bufferPtrs, wasCached, blockCount); } inline bool exists(BRM::LBID_t lbid, BRM::VER_t ver) { diff --git a/primitives/blockcache/blockrequestprocessor.cpp b/primitives/blockcache/blockrequestprocessor.cpp index e7f40a6f..7e4d0483 100644 --- a/primitives/blockcache/blockrequestprocessor.cpp +++ b/primitives/blockcache/blockrequestprocessor.cpp @@ -17,7 +17,7 @@ /*************************************************************************** * - * $Id: blockrequestprocessor.cpp 2055 2013-02-08 19:09:09Z pleblanc $ + * $Id: blockrequestprocessor.cpp 1965 2012-10-11 19:58:47Z xlou $ * * jrodriguez@calpont.com * * * @@ -37,16 +37,16 @@ using namespace std; namespace dbbc { BlockRequestProcessor::BlockRequestProcessor(uint32_t numBlcks, - int thrCount, - int blocksPerRead, - uint32_t deleteBlocks, - uint32_t blckSz) : - fbMgr(numBlcks, blckSz, deleteBlocks), - fIOMgr(fbMgr, fBRPRequestQueue, thrCount, blocksPerRead) + int thrCount, + int blocksPerRead, + uint32_t deleteBlocks, + uint32_t blckSz) : + fbMgr(numBlcks, blckSz, deleteBlocks), + fIOMgr(fbMgr, fBRPRequestQueue, thrCount, blocksPerRead) { //pthread_mutex_init(&check_mutex, NULL); config::Config* fConfig=config::Config::makeConfig(); - string val = fConfig->getConfig("DBBC", "BRPTracing"); + string val = fConfig->getConfig("DBBC", "BRPTracing"); int temp=0; #ifdef _MSC_VER int tid = GetCurrentThreadId(); @@ -54,9 +54,9 @@ BlockRequestProcessor::BlockRequestProcessor(uint32_t numBlcks, pthread_t tid = pthread_self(); #endif - if (val.length()>0) temp=static_cast(config::Config::fromText(val)); - - if (temp > 0) + if (val.length()>0) temp=static_cast(config::Config::fromText(val)); + + if (temp > 0) fTrace=true; else fTrace=false; @@ -83,10 +83,10 @@ BlockRequestProcessor::~BlockRequestProcessor() void BlockRequestProcessor::stop() { fBRPRequestQueue.stop(); - fIOMgr.stop(); + fIOMgr.stop(); } -int BlockRequestProcessor::check(const BRM::InlineLBIDRange& range, const BRM::QueryContext &ver, const BRM::VER_t txn, const int compType, uint32_t& lbidCount) { +int BlockRequestProcessor::check(const BRM::InlineLBIDRange& range, const BRM::VER_t ver, const BRM::VER_t txn, const int compType, uint32_t& lbidCount) { uint64_t maxLbid = range.start; // highest existent lbid uint64_t rangeLen = range.size; uint64_t idx; @@ -97,7 +97,7 @@ int BlockRequestProcessor::check(const BRM::InlineLBIDRange& range, const BRM::Q if (fTrace) clock_gettime(CLOCK_MONOTONIC, &start_tm); - for (idx = 0; fbMgr.exists(maxLbid, ver.currentScn) == true && idxerrorMsg(logging::ERR_BRM_LOOKUP), logging::ERR_BRM_LOOKUP); - else if (rqstBlk.RequestStatus() == fileRequest::FS_EINVAL) - throw logging::IDBExcept(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_O_DIRECT), - logging::ERR_O_DIRECT); - else if (rqstBlk.RequestStatus() == fileRequest::FS_ENOENT) - throw logging::IDBExcept( - logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_ENOENT), - logging::ERR_ENOENT); - else if (rqstBlk.RequestStatus() != fileRequest::SUCCESSFUL) + if (rqstBlk.RequestStatus() != fileRequest::SUCCESSFUL) { + if (rqstBlk.RequestStatus() == fileRequest::FS_EINVAL) + throw logging::IDBExcept(logging::IDBErrorInfo::instance()-> + errorMsg(logging::ERR_O_DIRECT), logging::ERR_O_DIRECT); + else if (rqstBlk.RequestStatus() == fileRequest::FS_ENOENT) + throw logging::IDBExcept(logging::IDBErrorInfo::instance()-> + errorMsg(logging::ERR_ENOENT), logging::ERR_ENOENT); + throw runtime_error(rqstBlk.RequestStatusStr()); + } lbidCount=rqstBlk.BlocksRead(); if (fTrace) { @@ -148,17 +147,17 @@ int BlockRequestProcessor::check(const BRM::InlineLBIDRange& range, const BRM::Q uint16_t segNum; uint32_t fbo; BRM::OID_t oid; - fdbrm.lookupLocal(maxLbid, ver.currentScn, false, oid, dbroot, partNum, segNum, fbo); + fdbrm.lookupLocal(maxLbid, ver, false, oid, dbroot, partNum, segNum, fbo); fLogFile - << oid << " " - << maxLbid << " " - << fbo << " " - << rangeLen << " " - << adjSz << " " - << rqstBlk.BlocksRead() << " " - << rqstBlk.BlocksLoaded() << " " - << right << fixed << ((double)(start_tm.tv_sec+(1.e-9*start_tm.tv_nsec))) - << endl; + << oid << " " + << maxLbid << " " + << fbo << " " + << rangeLen << " " + << adjSz << " " + << rqstBlk.BlocksRead() << " " + << rqstBlk.BlocksLoaded() << " " + << right << fixed << ((double)(start_tm.tv_sec+(1.e-9*start_tm.tv_nsec))) + << endl; } return rqstBlk.BlocksLoaded(); @@ -177,8 +176,8 @@ int BlockRequestProcessor::check(fileRequest& rqstBlk) { } // For future use. Not currently used. -int BlockRequestProcessor::check(BRM::LBID_t lbid, const BRM::QueryContext &ver, BRM::VER_t txn, bool flg, int compType, bool& wasBlockInCache) { - if (fbMgr.exists(lbid, ver.currentScn)==true) { +int BlockRequestProcessor::check(BRM::LBID_t lbid, BRM::VER_t ver, BRM::VER_t txn, bool flg, int compType, bool& wasBlockInCache) { + if (fbMgr.exists(lbid, ver)==true) { wasBlockInCache = true; return 0; } else { @@ -192,12 +191,31 @@ int BlockRequestProcessor::check(BRM::LBID_t lbid, const BRM::QueryContext &ver, } } -const int BlockRequestProcessor::getBlock(const BRM::LBID_t& lbid, const BRM::QueryContext &ver, BRM::VER_t txn, - int compType, void* bufferPtr, bool vbFlg, bool &wasCached, bool *versioned, bool insertIntoCache, - bool readFromCache) +const int BlockRequestProcessor::read(const BRM::InlineLBIDRange& range, FileBufferList_t& readList, const BRM::VER_t ver) +{ + int blksLoaded=0; + HashObject_t fb(0, 0, 0); + for(int idx=0; (uint64_t)idx USOID; namespace primitiveprocessor { extern Logger* mlp; extern int directIOFlag; -extern int noVB; +#ifdef _MSC_VER +extern CRITICAL_SECTION preadCSObject; +#else +//#define IDB_COMP_USE_CMP_SUFFIX +//#define IDB_COMP_POC_DEBUG +#ifdef IDB_COMP_POC_DEBUG +extern boost::mutex compDebugMutex; +#endif +#endif } +#include "rwlock_local.h" + +#include "iomanager.h" +#include "liboamcpp.h" + +#include "idbcompress.h" +using namespace compress; + #ifndef O_BINARY # define O_BINARY 0 #endif @@ -133,8 +136,8 @@ const uint32_t MAX_OPEN_FILES=16384; const uint32_t DECREASE_OPEN_FILES=4096; void timespec_sub(const struct timespec &tv1, - const struct timespec &tv2, - double &tm) + const struct timespec &tv2, + double &tm) { tm = (double)(tv2.tv_sec - tv1.tv_sec) + 1.e-9*(tv2.tv_nsec - tv1.tv_nsec); } @@ -152,50 +155,84 @@ class FdEntry { public: FdEntry() : oid(0), dbroot(0), partNum(0), segNum(0), - fp(0), c(0), inUse(0), compType(0) +#ifdef _MSC_VER + fd(INVALID_HANDLE_VALUE), +#else + fd(-1), +#endif + c(0), inUse(0), compType(0) { +#ifdef _MSC_VER + cmpMTime.QuadPart = 0; +#else cmpMTime = 0; +#endif } - FdEntry(const BRM::OID_t o, const uint16_t d, const uint32_t p, const uint16_t s, const int ct, IDBDataFile* f) : - oid(o), dbroot(d), partNum(p), segNum(s), fp(f), c(0), inUse(0), compType(0) + FdEntry(const BRM::OID_t o, const uint16_t d, const uint32_t p, const uint16_t s, const int ct, +#ifdef _MSC_VER + const HANDLE f +#else + const int f +#endif + ) : + oid(o), dbroot(d), partNum(p), segNum(s), fd(f), c(0), inUse(0), compType(0) { +#ifdef _MSC_VER + cmpMTime.QuadPart = 0; +#else cmpMTime = 0; +#endif if (oid >= 1000) compType = ct; } ~FdEntry() { - delete fp; - fp = 0; +#ifdef _MSC_VER + if (fd != INVALID_HANDLE_VALUE) + CloseHandle(fd); +#else + if (fd >= 0) + close(fd); +#endif } BRM::OID_t oid; uint16_t dbroot; uint32_t partNum; uint16_t segNum; - IDBDataFile* fp; +#ifdef _MSC_VER + HANDLE fd; +#else + int fd; +#endif uint32_t c; int inUse; CompChunkPtrList ptrList; int compType; - bool isCompressed() const { - return (oid >= 1000 && compType != 0); - } + bool isCompressed() const { return (oid >= 1000 && compType != 0); } +#ifdef _MSC_VER + ULARGE_INTEGER cmpMTime; +#else time_t cmpMTime; +#endif friend ostream& operator<<(ostream& out, const FdEntry& o) { out << " o: " << o.oid - << " f: " << o.fp - << " d: " << o.dbroot - << " p: " << o.partNum - << " s: " << o.segNum - << " c: " << o.c - << " t: " << o.compType - << " m: " << o.cmpMTime; + << " f: " << o.fd + << " d: " << o.dbroot + << " p: " << o.partNum + << " s: " << o.segNum + << " c: " << o.c + << " t: " << o.compType +#ifdef _MSC_VER + << " m: " << o.cmpMTime.QuadPart; +#else + << " m: " << o.cmpMTime; +#endif return out; } }; @@ -205,16 +242,16 @@ struct fdCacheMapLessThan bool operator()(const FdEntry& lhs, const FdEntry& rhs) const { if (lhs.oid < rhs.oid) - return true; + return true; if (lhs.oid==rhs.oid && lhs.dbroot < rhs.dbroot) - return true; + return true; if (lhs.oid==rhs.oid && lhs.dbroot==rhs.dbroot && lhs.partNum < rhs.partNum) - return true; + return true; if (lhs.oid==rhs.oid && lhs.dbroot==rhs.dbroot && lhs.partNum==rhs.partNum && lhs.segNum < rhs.segNum) - return true; + return true; return false; @@ -225,10 +262,10 @@ struct fdMapEqual { bool operator()(const FdEntry& lhs, const FdEntry& rhs) const { - return (lhs.oid == rhs.oid && - lhs.dbroot == rhs.dbroot && - lhs.partNum == rhs.partNum && - lhs.segNum == rhs.segNum); + return (lhs.oid == rhs.oid && + lhs.dbroot == rhs.dbroot && + lhs.partNum == rhs.partNum && + lhs.segNum == rhs.segNum); } }; @@ -240,7 +277,7 @@ struct FdCountEntry { FdCountEntry() {} FdCountEntry(const BRM::OID_t o, const uint16_t d, const uint32_t p, const uint16_t s, const uint32_t c, - const FdCacheType_t::iterator it) : oid(o), dbroot(d), partNum(p), segNum(s), cnt(c), fdit(it) {} + const FdCacheType_t::iterator it) : oid(o), dbroot(d), partNum(p), segNum(s), cnt(c), fdit(it) {} ~FdCountEntry() {} BRM::OID_t oid; @@ -253,10 +290,10 @@ struct FdCountEntry friend ostream& operator<<(ostream& out, const FdCountEntry& o) { out << " o: " << o.oid - << " d: " << o.dbroot - << " p: " << o.partNum - << " s: " << o.segNum - << " c: " << o.cnt; + << " d: " << o.dbroot + << " p: " << o.partNum + << " s: " << o.segNum + << " c: " << o.cnt; return out; } @@ -307,7 +344,7 @@ const vector > getDBRootList() { vector > ret; Config *config; - uint32_t dbrootCount, i; + uint dbrootCount, i; string stmp, devname, mountpoint; char devkey[80], mountkey[80]; @@ -339,20 +376,20 @@ const vector > getDBRootList() char* alignTo(const char* in, int av) { - ptrdiff_t inx = reinterpret_cast(in); - ptrdiff_t avx = static_cast(av); - if ((inx % avx) != 0) - { - inx &= ~(avx - 1); - inx += avx; - } - char* outx = reinterpret_cast(inx); - return outx; + ptrdiff_t inx = reinterpret_cast(in); + ptrdiff_t avx = static_cast(av); + if ((inx % avx) != 0) + { + inx &= ~(avx - 1); + inx += avx; + } + char* outx = reinterpret_cast(inx); + return outx; } void waitForRetry(long count) { - usleep(5000 * count); + usleep(5000 * count); return; } @@ -361,8 +398,8 @@ void waitForRetry(long count) int updateptrs(char* ptr, FdCacheType_t::iterator fdit, const IDBCompressInterface& decompressor) { ssize_t i; - uint32_t progress; - + struct stat statbuf; + ssize_t progress; // ptr is taken from buffer, already been checked: realbuff.get() == 0 if (ptr == 0) @@ -372,11 +409,32 @@ int updateptrs(char* ptr, FdCacheType_t::iterator fdit, const IDBCompressInterfa if (fdit->second.get() == 0) return -2; - IDBDataFile* fp = fdit->second->fp; - if (fp == INVALID_HANDLE_VALUE) +#ifdef _MSC_VER + HANDLE fd = fdit->second->fd; + if (fd == INVALID_HANDLE_VALUE) + { + Message::Args args; + args.add("updateptrs got invalid fd."); + primitiveprocessor::mlp->logInfoMessage(logging::M0006, args); + return -3; + } + + OVERLAPPED ovl; + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = 0; + ovl.OffsetHigh = 0; + DWORD bytesRead; + if (ReadFile(fd, ptr, 4096 * 3, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; + progress = i; +#else + int fd = fdit->second->fd; + if (fd < 0) { Message::Args args; - args.add("updateptrs got invalid fp."); + args.add("updateptrs got invalid fd."); primitiveprocessor::mlp->logInfoMessage(logging::M0006, args); return -3; } @@ -385,18 +443,29 @@ int updateptrs(char* ptr, FdCacheType_t::iterator fdit, const IDBCompressInterfa //FIXME: re-work all of this so we don't have to re-read the 3rd block. progress = 0; while (progress < 4096 * 3) { - i = fp->pread(&ptr[progress], progress, (4096 * 3) - progress); + i = pread(fd, &ptr[progress], (4096 * 3) - progress, progress); if (i <= 0) break; progress += i; } +#endif if (progress != 4096 * 3) return -4; // let it retry. Not likely, but ... +#ifdef _MSC_VER + //FIXME: + fdit->second->cmpMTime.QuadPart = 0; + FILETIME ft; + if (GetFileTime(fd, 0, 0, &ft)) + { + fdit->second->cmpMTime.LowPart = ft.dwLowDateTime; + fdit->second->cmpMTime.HighPart = ft.dwHighDateTime; + } +#else fdit->second->cmpMTime = 0; - time_t mtime = fp->mtime(); - if( mtime != (time_t) -1 ) - fdit->second->cmpMTime = mtime; + if (fstat(fd, &statbuf) == 0) + fdit->second->cmpMTime = statbuf.st_mtime; +#endif int gplRc = 0; gplRc = decompressor.getPtrList(&ptr[4096], 4096, fdit->second->ptrList); @@ -414,17 +483,27 @@ int updateptrs(char* ptr, FdCacheType_t::iterator fdit, const IDBCompressInterfa nextHdrBufPtr = alignTo(nextHdrBufsa.get(), 4096); +#ifdef _MSC_VER + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = 4096 * 2; + ovl.OffsetHigh = 0; + if (ReadFile(fd, &nextHdrBufPtr[0], numHdrs * 4096, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; + progress = i; +#else progress = 0; while (progress < numHdrs * 4096) { - i = fp->pread(&nextHdrBufPtr[progress], (4096 * 2) + progress, - (numHdrs * 4096) - progress); + i = pread(fd, &nextHdrBufPtr[progress], (numHdrs * 4096) - progress, + (4096 * 2) + progress); if (i <= 0) break; progress += i; } +#endif if (progress != numHdrs * 4096) return -8; - CompChunkPtrList nextPtrList; gplRc = decompressor.getPtrList(&nextHdrBufPtr[0], numHdrs * 4096, nextPtrList); if (gplRc != 0) @@ -444,7 +523,6 @@ void* thr_popper(ioManager *arg) { BRM::LBID_t lbid=0; BRM::OID_t oid=0; BRM::VER_t ver=0; - BRM::QueryContext qc; BRM::VER_t txn=0; int compType = 0; int blocksLoaded=0; @@ -454,6 +532,7 @@ void* thr_popper(ioManager *arg) { char fileName[WriteEngine::FILE_NAME_SIZE]; const uint64_t fileBlockSize = BLOCK_SIZE; bool flg=false; + bool inFlg=false; bool useCache; uint16_t dbroot=0; uint32_t partNum=0; @@ -462,11 +541,12 @@ void* thr_popper(ioManager *arg) { char* fileNamePtr=fileName; uint64_t longSeekOffset=0; int err; - uint32_t dlen = 0, acc, readSize, blocksThisRead, j; + uint dlen = 0, acc, readSize, blocksThisRead, j; uint32_t blocksRequested=0; ssize_t i; + uint32_t sz=0; char* alignedbuff=0; - boost::scoped_array realbuff; + boost::scoped_array realbuff; pthread_t threadId=0; ostringstream iomLogFileName; ofstream lFile; @@ -495,9 +575,13 @@ void* thr_popper(ioManager *arg) { } FdCacheType_t::iterator fdit; - IDBDataFile* fp = 0; - uint32_t maxCompSz = IDBCompressInterface::maxCompressedSize(iom->blocksPerRead * BLOCK_SIZE); - uint32_t readBufferSz = maxCompSz + pageSize; +#ifdef _MSC_VER + HANDLE fd = INVALID_HANDLE_VALUE; +#else + int fd = -1; +#endif + //usually iom->blocksPerRead = 512, so adding 87 is giving us 117% room for decomp expansion + uint32_t readBufferSz=((iom->blocksPerRead+87)*BLOCK_SIZE)+pageSize; realbuff.reset(new char[readBufferSz]); if (realbuff.get() == 0) { @@ -508,7 +592,7 @@ void* thr_popper(ioManager *arg) { alignedbuff = alignTo(realbuff.get(), 4096); if ((((ptrdiff_t)alignedbuff - (ptrdiff_t)realbuff.get()) >= (ptrdiff_t)pageSize) || - (((ptrdiff_t)alignedbuff % pageSize) != 0)) + (((ptrdiff_t)alignedbuff % pageSize) != 0)) throw runtime_error("aligned buffer size is not matching the page size."); uint8_t* uCmpBuf = 0; @@ -532,9 +616,10 @@ void* thr_popper(ioManager *arg) { if (iom->IOTrace()) clock_gettime(CLOCK_REALTIME, &rqst1); lbid = fr->Lbid(); - qc = fr->Ver(); + ver = fr->Ver(); txn = fr->Txn(); flg = fr->Flg(); + inFlg = fr->Flg(); compType = fr->CompType(); useCache = fr->useCache(); blocksLoaded=0; @@ -547,35 +632,35 @@ void* thr_popper(ioManager *arg) { segNum=0; offset=0; - // special case for getBlock. + int rc = 0; + + // special case for getBlock. iom->dbrm()->lockLBIDRange(lbid, blocksRequested); copyLocked = true; + //cout << "IOM: got request: start=" << lbid << " count=" << blocksRequested << " ver=" << ver << endl; + // special case for getBlock. if (blocksRequested==1) { - BRM::VER_t outVer; - iom->dbrm()->vssLookup((BRM::LBID_t) lbid, qc, txn, &outVer, &flg); - ver = outVer; + rc=iom->dbrm()->vssLookup((BRM::LBID_t)(lbid), ver, txn, flg); fr->versioned(flg); } - else { + else fr->versioned(false); - ver = qc.currentScn; - } err = iom->localLbidLookup(lbid, - ver, - flg, - oid, - dbroot, - partNum, - segNum, - offset); + ver, + flg, + oid, + dbroot, + partNum, + segNum, + offset); if (err == BRM::ERR_SNAPSHOT_TOO_OLD) { ostringstream errMsg; errMsg << "thr_popper: version " << ver << " of LBID " << lbid << - "is too old"; + "is too old"; iom->handleBlockReadError(fr, errMsg.str(), ©Locked); continue; } @@ -583,23 +668,29 @@ void* thr_popper(ioManager *arg) { { ostringstream errMsg; errMsg << "thr_popper: BRM lookup failure; lbid=" << - lbid << "; ver=" << ver << "; flg=" << (flg ? 1 : 0); + lbid << "; ver=" << ver << "; flg=" << (flg ? 1 : 0); iom->handleBlockReadError( fr, errMsg.str(), ©Locked, fileRequest::BRM_LOOKUP_ERROR); continue; } #ifdef IDB_COMP_POC_DEBUG - { - boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); - if (compType != 0) cout << boldStart; - cout << "fileRequest: " << *fr << endl; - if (compType != 0) cout << boldStop; - } +{ +boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); +if (compType != 0) cout << boldStart; +cout << "fileRequest: " << *fr << endl; +if (compType != 0) cout << boldStop; +} #endif const uint32_t extentSize = iom->getExtentRows(); - FdEntry fdKey(oid, dbroot, partNum, segNum, compType, NULL); + FdEntry fdKey(oid, dbroot, partNum, segNum, compType, +#ifdef _MSC_VER + INVALID_HANDLE_VALUE +#else + -1 +#endif + ); //cout << "Looking for " << fdKey << endl - // << "O: " << oid << " D: " << dbroot << " P: " << partNum << " S: " << segNum << endl; + // << "O: " << oid << " D: " << dbroot << " P: " << partNum << " S: " << segNum << endl; fdMapMutex.lock(); fdit = fdcache.find(fdKey); @@ -615,7 +706,7 @@ void* thr_popper(ioManager *arg) { primitiveprocessor::mlp->logMessage(logging::M0053, args, true); ostringstream errMsg; errMsg << "thr_popper: Error building filename for OID " << - oid << "; " << exc.what(); + oid << "; " << exc.what(); iom->handleBlockReadError( fr, errMsg.str(), ©Locked ); continue; } @@ -649,9 +740,9 @@ void* thr_popper(ioManager *arg) { if (iom->FDCacheTrace()) { iom->FDTraceFile() - << "Before flushing sz: " << fdcache.size() - << " delCount: " << iom->DecreaseOpenFilesCount() - << endl; + << "Before flushing sz: " << fdcache.size() + << " delCount: " << iom->DecreaseOpenFilesCount() + << endl; for (FdCacheType_t::iterator it = fdcache.begin(); it != fdcache.end(); it++) iom->FDTraceFile() << *(*it).second << endl; @@ -665,12 +756,18 @@ void* thr_popper(ioManager *arg) { uint32_t delCount=0; for(FdCacheCountType_t::reverse_iterator rit=fdCountSort.rbegin(); - rit != fdCountSort.rend() && - fdcache.size()>0 && - delCount < iom->DecreaseOpenFilesCount(); - rit++) + rit != fdCountSort.rend() && + fdcache.size()>0 && + delCount < iom->DecreaseOpenFilesCount(); + rit++) { - FdEntry oldfdKey(rit->oid, rit->dbroot, rit->partNum, rit->segNum, 0, NULL); + FdEntry oldfdKey(rit->oid, rit->dbroot, rit->partNum, rit->segNum, 0, +#ifdef _MSC_VER + INVALID_HANDLE_VALUE +#else + -1 +#endif + ); FdCacheType_t::iterator it = fdcache.find(oldfdKey); if (it!=fdcache.end()) { @@ -678,12 +775,12 @@ void* thr_popper(ioManager *arg) { { if (!rit->fdit->second->inUse) iom->FDTraceFile() - << "Removing dc: " << delCount << " sz: " << fdcache.size() - << *(*it).second << " u: " << rit->fdit->second->inUse << endl; + << "Removing dc: " << delCount << " sz: " << fdcache.size() + << *(*it).second << " u: " << rit->fdit->second->inUse << endl; else iom->FDTraceFile() - << "Skip Remove in use dc: " << delCount << " sz: " << fdcache.size() - << *(*it).second << " u: " << rit->fdit->second->inUse << endl; + << "Skip Remove in use dc: " << delCount << " sz: " << fdcache.size() + << *(*it).second << " u: " << rit->fdit->second->inUse << endl; } if (rit->fdit->second->inUse<=0) @@ -700,7 +797,7 @@ void* thr_popper(ioManager *arg) { for (FdCacheType_t::iterator it = fdcache.begin(); it != fdcache.end(); it++) { iom->FDTraceFile() - << *(*it).second << endl; + << *(*it).second << endl; } iom->FDTraceFile() << "==================" << endl << endl; } @@ -708,24 +805,27 @@ void* thr_popper(ioManager *arg) { fdCountSort.clear(); } // if (fdcache.size()... - } // if (oid > 3000) - - int opts = primitiveprocessor::directIOFlag ? IDBDataFile::USE_ODIRECT : 0; - fp = NULL; - uint32_t openRetries = 0; - int saveErrno; - while (fp == NULL && openRetries++ < 5) { - fp = IDBDataFile::open( - IDBPolicy::getType( fileNamePtr, IDBPolicy::PRIMPROC ), - fileNamePtr, - "r", - opts); - saveErrno = errno; - if (fp == NULL) - sleep(1); } - if( fp == NULL ) + +#if defined(EM_AS_A_TABLE_POC__) + if (oid == 1084) + fd = numeric_limits::max(); + else + fd = open(fileNamePtr, O_RDONLY|primitiveprocessor::directIOFlag|O_LARGEFILE|O_NOATIME); +#elif defined(_MSC_VER) + //FIXME: What does FILE_SHARE_DELETE do? + fd = CreateFile(fileNamePtr, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, 0, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_NO_BUFFERING, 0); +#else + fd = open(fileNamePtr, O_RDONLY|O_BINARY|O_LARGEFILE|O_NOATIME|primitiveprocessor::directIOFlag); +#endif +#ifdef _MSC_VER + if (fd == INVALID_HANDLE_VALUE) +#else + if (fd < 0) +#endif { + int saveErrno = errno; Message::Args args; fdit = fdcache.end(); fdMapMutex.unlock(); @@ -734,7 +834,7 @@ void* thr_popper(ioManager *arg) { primitiveprocessor::mlp->logMessage(logging::M0053, args, true); ostringstream errMsg; errMsg << "thr_popper: Error opening file for OID " << oid << "; " - << fileNamePtr << "; " << strerror(saveErrno); + << fileNamePtr << "; " << strerror(saveErrno); int errorCode = fileRequest::FAILED; if (saveErrno == EINVAL) errorCode = fileRequest::FS_EINVAL; @@ -744,7 +844,7 @@ void* thr_popper(ioManager *arg) { continue; } - fe.reset( new FdEntry(oid, dbroot, partNum, segNum, compType, fp) ); + fe.reset( new FdEntry(oid, dbroot, partNum, segNum, compType, fd) ); fe->inUse++; fdcache[fdKey] = fe; fdit = fdcache.find(fdKey); @@ -755,20 +855,16 @@ void* thr_popper(ioManager *arg) { if (fdit->second.get()) { fdit->second->c++; fdit->second->inUse++; - fp = fdit->second->fp; + fd = fdit->second->fd; } else { Message::Args args; - fdit = fdcache.end(); - fdMapMutex.unlock(); args.add(oid); ostringstream errMsg; errMsg << "Null FD cache entry. (dbroot, partNum, segNum, compType) = (" - << dbroot << ", " << partNum << ", " << segNum << ", " << compType << ")"; + << dbroot << ", " << partNum << ", " << segNum << ", " << compType << ")"; args.add(errMsg.str()); primitiveprocessor::mlp->logMessage(logging::M0053, args, true); - iom->handleBlockReadError( fr, errMsg.str(), ©Locked ); - continue; } } fdMapMutex.unlock(); @@ -784,18 +880,19 @@ void* thr_popper(ioManager *arg) { longSeekOffset=(uint64_t)offset * (uint64_t)fileBlockSize; lldiv_t cmpOffFact = lldiv(longSeekOffset, (4LL * 1024LL * 1024LL)); totalRqst++; + sz=0; uint32_t readCount=0; uint32_t bytesRead=0; uint32_t compressedBytesRead=0; // @Bug 3149. IOMTrace was not reporting bytesRead correctly for compressed columns. - uint32_t jend = blocksRequested/iom->blocksPerRead; + uint jend = blocksRequested/iom->blocksPerRead; if (iom->IOTrace()) clock_gettime(CLOCK_REALTIME, &tm); ostringstream errMsg; bool errorOccurred = false; string errorString; #ifdef IDB_COMP_POC_DEBUG - bool debugWrite=false; +bool debugWrite=false; #endif #ifdef EM_AS_A_TABLE_POC__ @@ -817,34 +914,164 @@ void* thr_popper(ioManager *arg) { acc = 0; while (acc < readSize) { #if defined(EM_AS_A_TABLE_POC__) - if (oid == 1084) + if (oid == 1084) + { + uint32_t h; + int32_t o = 0; + int32_t* ip; + ip = (int32_t*)(&alignedbuff[acc]); + for (o = 0; o < 2048; o++) + { + if (iom->dbrm()->getHWM(o+3000, h) == 0) + *ip++ = h; + else + *ip++ = numeric_limits::min() + 1; + } + i = BLOCK_SIZE; + } + else + i = pread(fd, &alignedbuff[acc], readSize - acc, longSeekOffset); + +#elif defined(_MSC_VER) + DWORD bytesRead; + OVERLAPPED ovl; + + if (fdit->second->isCompressed()) { - uint32_t h; - int32_t o = 0; - int32_t* ip; - ip = (int32_t*)(&alignedbuff[acc]); - for (o = 0; o < 2048; o++) +retryReadHeaders: + //hdrs may have been modified since we cached them in fdit->second... + ULARGE_INTEGER cur_mtime; + cur_mtime.QuadPart = numeric_limits::max(); + int updatePtrsRc = 0; + fdMapMutex.lock(); + //FIXME: + FILETIME ft; + if (GetFileTime(fd, 0, 0, &ft)) { - if (iom->dbrm()->getHWM(o+3000, h) == 0) - *ip++ = h; + cur_mtime.LowPart = ft.dwLowDateTime; + cur_mtime.HighPart = ft.dwHighDateTime; + } + if (decompRetryCount > 0 || retryReadHeadersCount > 0 || + cur_mtime.QuadPart > fdit->second->cmpMTime.QuadPart) + updatePtrsRc = updateptrs(&alignedbuff[0], fdit, decompressor); + fdMapMutex.unlock(); + + int idx = cmpOffFact.quot; + if (updatePtrsRc != 0 || idx >= (signed)fdit->second->ptrList.size()) + { + // Due to race condition, the header on disk may not upated yet. + // Log an info message and retry. + if (retryReadHeadersCount == 0) + { + Message::Args args; + args.add(oid); + ostringstream infoMsg; + iom->buildOidFileName(oid, dbroot, partNum, segNum, fileNamePtr); + infoMsg << "retry updateptrs for " << fileNamePtr + << ". rc=" << updatePtrsRc << ", idx=" + << idx << ", ptr.size=" << fdit->second->ptrList.size(); + infoMsg << " retryReadHeadersCount:" << retryReadHeadersCount + << " decompRetryCount:" << decompRetryCount; + args.add(infoMsg.str()); + primitiveprocessor::mlp->logInfoMessage(logging::M0061, args); + } + + if (++retryReadHeadersCount < 30) + { + fdit->second->cmpMTime.QuadPart = 0; + waitForRetry(retryReadHeadersCount); + goto retryReadHeaders; + } else - *ip++ = numeric_limits::min() + 1; + { + // still fail after all the retries. + errorOccurred = true; + errMsg << "Error update header ptr. rc=" << updatePtrsRc << ", idx=" + << idx << ", ptr.size=" << fdit->second->ptrList.size(); + errorString = errMsg.str(); + break; + } + } + + //FIXME: make sure alignedbuff can hold fdit->second->ptrList[idx].second bytes + if (fdit->second->ptrList[idx].second > (iom->blocksPerRead+87)*BLOCK_SIZE) + { + errorOccurred = true; + errMsg << "aligned buff too small. dataSize=" + << fdit->second->ptrList[idx].second + << ", buffSize=" << (iom->blocksPerRead+87)*BLOCK_SIZE; + errorString = errMsg.str(); + break; } - i = BLOCK_SIZE; + + //i = pread(fd, &alignedbuff[0], fdit->second->ptrList[idx].second, fdit->second->ptrList[idx].first); + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = static_cast(fdit->second->ptrList[idx].first); + ovl.OffsetHigh = static_cast(fdit->second->ptrList[idx].first>>32); + if (ReadFile(fd, &alignedbuff[0], fdit->second->ptrList[idx].second, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; + + // @bug3407, give it some retries if pread failed. + if (i != (ssize_t)fdit->second->ptrList[idx].second) + { + // log an info message + if (retryReadHeadersCount == 0) + { + Message::Args args; + args.add(oid); + ostringstream infoMsg; + iom->buildOidFileName(oid, dbroot, partNum, segNum, fileNamePtr); + infoMsg << " Read from " << fileNamePtr << " failed at chunk " << idx + << ". (offset, size, actuall read) = (" + << fdit->second->ptrList[idx].first << ", " + << fdit->second->ptrList[idx].second << ", " << i << ")"; + infoMsg << " retryReadHeadersCount:" << retryReadHeadersCount + << " decompRetryCount:" << decompRetryCount; + args.add(infoMsg.str()); + primitiveprocessor::mlp->logInfoMessage(logging::M0061, args); + } + + if (++retryReadHeadersCount < 30) + { + fdit->second->cmpMTime.QuadPart = 0; + waitForRetry(retryReadHeadersCount); + goto retryReadHeaders; + } + else + { + errorOccurred = true; + errMsg << "Error reading chunk " << idx; + errorString = errMsg.str(); + break; + } + } + + i = readSize; } else - i = pread(fd, &alignedbuff[acc], readSize - acc, longSeekOffset); + { + //i = pread(fd, &alignedbuff[acc], readSize - acc, longSeekOffset); + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = static_cast(longSeekOffset); + ovl.OffsetHigh = static_cast(longSeekOffset>>32); + if (ReadFile(fd, &alignedbuff[acc], readSize - acc, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; + } #else if (fdit->second->isCompressed()) { retryReadHeaders: //hdrs may have been modified since we cached them in fdit->second... + struct stat statbuf; time_t cur_mtime = numeric_limits::max(); int updatePtrsRc = 0; fdMapMutex.lock(); - time_t fp_mtime = fp->mtime(); - if( fp_mtime != (time_t) -1) - cur_mtime = fp_mtime; + if (fstat(fd, &statbuf) == 0) + cur_mtime = statbuf.st_mtime; if (decompRetryCount > 0 || retryReadHeadersCount > 0 || cur_mtime > fdit->second->cmpMTime) updatePtrsRc = updateptrs(&alignedbuff[0], fdit, decompressor); fdMapMutex.unlock(); @@ -861,8 +1088,8 @@ void* thr_popper(ioManager *arg) { ostringstream infoMsg; iom->buildOidFileName(oid, dbroot, partNum, segNum, fileNamePtr); infoMsg << "retry updateptrs for " << fileNamePtr - << ". rc=" << updatePtrsRc << ", idx=" - << idx << ", ptr.size=" << fdit->second->ptrList.size(); + << ". rc=" << updatePtrsRc << ", idx=" + << idx << ", ptr.size=" << fdit->second->ptrList.size(); args.add(infoMsg.str()); primitiveprocessor::mlp->logInfoMessage(logging::M0061, args); } @@ -878,30 +1105,30 @@ void* thr_popper(ioManager *arg) { // still fail after all the retries. errorOccurred = true; errMsg << "Error reading compression header. rc=" << updatePtrsRc << ", idx=" - << idx << ", ptr.size=" << fdit->second->ptrList.size(); + << idx << ", ptr.size=" << fdit->second->ptrList.size(); errorString = errMsg.str(); break; } } //FIXME: make sure alignedbuff can hold fdit->second->ptrList[idx].second bytes - if (fdit->second->ptrList[idx].second > maxCompSz) + if (fdit->second->ptrList[idx].second > (iom->blocksPerRead+87)*BLOCK_SIZE) { errorOccurred = true; errMsg << "aligned buff too small. dataSize=" - << fdit->second->ptrList[idx].second - << ", buffSize=" << maxCompSz; + << fdit->second->ptrList[idx].second + << ", buffSize=" << (iom->blocksPerRead+87)*BLOCK_SIZE; errorString = errMsg.str(); break; } - i = fp->pread(&alignedbuff[0], fdit->second->ptrList[idx].first, fdit->second->ptrList[idx].second ); + i = pread(fd, &alignedbuff[0], fdit->second->ptrList[idx].second, fdit->second->ptrList[idx].first); #ifdef IDB_COMP_POC_DEBUG - { - boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); - cout << boldStart << "pread1.1(" << fp << ", 0x" << hex << (ptrdiff_t)&alignedbuff[0] << dec << ", " << fdit->second->ptrList[idx].second << - ", " << fdit->second->ptrList[idx].first << ") = " << i << ' ' << cmpOffFact.quot << ' ' << cmpOffFact.rem << boldStop << endl; - } +{ +boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); +cout << boldStart << "pread1.1(" << fd << ", 0x" << hex << (ptrdiff_t)&alignedbuff[0] << dec << ", " << fdit->second->ptrList[idx].second << +", " << fdit->second->ptrList[idx].first << ") = " << i << ' ' << cmpOffFact.quot << ' ' << cmpOffFact.rem << boldStop << endl; +} #endif // @bug3407, give it some retries if pread failed. if (i != (ssize_t)fdit->second->ptrList[idx].second) @@ -914,9 +1141,9 @@ void* thr_popper(ioManager *arg) { ostringstream infoMsg; iom->buildOidFileName(oid, dbroot, partNum, segNum, fileNamePtr); infoMsg << " Read from " << fileNamePtr << " failed at chunk " << idx - << ". (offset, size, actuall read) = (" - << fdit->second->ptrList[idx].first << ", " - << fdit->second->ptrList[idx].second << ", " << i << ")"; + << ". (offset, size, actuall read) = (" + << fdit->second->ptrList[idx].first << ", " + << fdit->second->ptrList[idx].second << ", " << i << ")"; args.add(infoMsg.str()); primitiveprocessor::mlp->logInfoMessage(logging::M0061, args); } @@ -941,13 +1168,13 @@ void* thr_popper(ioManager *arg) { } else { - i = fp->pread(&alignedbuff[acc], longSeekOffset, readSize - acc); + i = pread(fd, &alignedbuff[acc], readSize - acc, longSeekOffset); #ifdef IDB_COMP_POC_DEBUG - { - boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); - cout << "pread1.2(" << fp << ", 0x" << hex << (ptrdiff_t)&alignedbuff[acc] << dec << ", " << (readSize - acc) << - ", " << longSeekOffset << ") = " << i << ' ' << cmpOffFact.quot << ' ' << cmpOffFact.rem << endl; - } +{ +boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); +cout << "pread1.2(" << fd << ", 0x" << hex << (ptrdiff_t)&alignedbuff[acc] << dec << ", " << (readSize - acc) << +", " << longSeekOffset << ") = " << i << ' ' << cmpOffFact.quot << ' ' << cmpOffFact.rem << endl; +} #endif } #endif @@ -969,8 +1196,8 @@ void* thr_popper(ioManager *arg) { errorString = strerror(errno); errorOccurred = true; errMsg << "thr_popper: Error reading file for OID " << oid << "; " - << " fp " << fp << "; offset " << longSeekOffset << "; fileName " - << fileNamePtr << "; " << errorString; + << " fd " << fd << "; offset " << longSeekOffset << "; fileName " + << fileNamePtr << "; " << errorString; break; // break from "while(acc..." loop } else if (i == 0) @@ -979,7 +1206,7 @@ void* thr_popper(ioManager *arg) { errorString = "early EOF"; errorOccurred = true; errMsg << "thr_popper: Early EOF reading file for OID " << - oid << "; " << fileNamePtr; + oid << "; " << fileNamePtr; break; // break from "while(acc..." loop } acc += i; @@ -1006,18 +1233,11 @@ void* thr_popper(ioManager *arg) { /* New bulk VSS lookup code */ { vector lbids; - vector versions; - vector isLocked; - for (i = 0; (uint32_t) i < blocksThisRead; i++) + vector vssData; + for (i = 0; (uint) i < blocksThisRead; i++) lbids.push_back((BRM::LBID_t) (lbid + i) + (j * iom->blocksPerRead)); - if (blocksRequested > 1 || !flg) // prefetch, or an unversioned single-block read - iom->dbrm()->bulkGetCurrentVersion(lbids, &versions, &isLocked); - else { // a single-block read that was versioned - versions.push_back(ver); - isLocked.push_back(false); - } - + rc = iom->dbrm()->bulkVSSLookup(lbids, ver, txn, &vssData); uint8_t *ptr = (uint8_t*)&alignedbuff[0]; if (blocksThisRead > 0 && fdit->second->isCompressed()) { @@ -1027,13 +1247,13 @@ void* thr_popper(ioManager *arg) { uint32_t blen = 4 * 1024 * 1024 + 4; #endif #ifdef IDB_COMP_POC_DEBUG - { - boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); - cout << "decompress(0x" << hex << (ptrdiff_t)&alignedbuff[0] << dec << ", " << fdit->second->ptrList[cmpOffFact.quot].second << ", 0x" << hex << (ptrdiff_t)uCmpBuf << dec << ", " << blen << ")" << endl; - } +{ + boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); + cout << "decompress(0x" << hex << (ptrdiff_t)&alignedbuff[0] << dec << ", " << fdit->second->ptrList[cmpOffFact.quot].second << ", 0x" << hex << (ptrdiff_t)uCmpBuf << dec << ", " << blen << ")" << endl; +} #endif int dcrc = decompressor.uncompressBlock(&alignedbuff[0], - fdit->second->ptrList[cmpOffFact.quot].second, uCmpBuf, blen); + fdit->second->ptrList[cmpOffFact.quot].second, uCmpBuf, blen); if (dcrc != 0) { @@ -1053,8 +1273,8 @@ void* thr_popper(ioManager *arg) { ostringstream infoMsg; iom->buildOidFileName(oid, dbroot, partNum, segNum, fileNamePtr); infoMsg << "decompress retry for " << fileNamePtr - << " decompRetry chunk " << cmpOffFact.quot - << " code=" << dcrc; + << " decompRetry chunk " << cmpOffFact.quot + << " code=" << dcrc; args.add(infoMsg.str()); primitiveprocessor::mlp->logInfoMessage(logging::M0061, args); } @@ -1085,51 +1305,56 @@ void* thr_popper(ioManager *arg) { ostringstream infoMsg; iom->buildOidFileName(oid, dbroot, partNum, segNum, fileNamePtr); infoMsg << "Successfully uncompress " << fileNamePtr << " chunk " - << cmpOffFact.quot << " @"; + << cmpOffFact.quot << " @"; if (retryReadHeadersCount > 0) - infoMsg << " HeaderRetry:" << retryReadHeadersCount; + infoMsg << " HeaderRetry:" << retryReadHeadersCount; if (decompRetryCount > 0) - infoMsg << " UncompressRetry:" << decompRetryCount; + infoMsg << " UncompressRetry:" << decompRetryCount; args.add(infoMsg.str()); primitiveprocessor::mlp->logInfoMessage(logging::M0006, args); } } - for (i = 0; useCache && (uint32_t) i < lbids.size(); i++) { - if (!isLocked[i]) { + for (i = 0; useCache && (uint) i < vssData.size(); i++) { + BRM::VSSData &vd = vssData[i]; + // if it was a prefetch and a block is marked versioned, don't cache + if ((blocksRequested > 1 && !vd.vbFlag) || blocksRequested == 1) { #ifdef IDB_COMP_POC_DEBUG - { - if (debugWrite) - { - boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); - cout << boldStart << "i = " << i << ", ptr = 0x" << hex << (ptrdiff_t)&ptr[i*BLOCK_SIZE] << dec << boldStop << endl; - cout << boldStart; +{ + if (debugWrite) + { + boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); + cout << boldStart << "i = " << i << ", ptr = 0x" << hex << (ptrdiff_t)&ptr[i*BLOCK_SIZE] << dec << boldStop << endl; + cout << boldStart; #if 0 - int32_t* i32p; - i32p = (int32_t*)&ptr[i*BLOCK_SIZE]; - for (int iy = 0; iy < 2; iy++) - { - for (int ix = 0; ix < 8; ix++, i32p++) - cout << *i32p << ' '; - cout << endl; - } + int32_t* i32p; + i32p = (int32_t*)&ptr[i*BLOCK_SIZE]; + for (int iy = 0; iy < 2; iy++) + { + for (int ix = 0; ix < 8; ix++, i32p++) + cout << *i32p << ' '; + cout << endl; + } #else - int64_t* i64p; - i64p = (int64_t*)&ptr[i*BLOCK_SIZE]; - for (int iy = 0; iy < 2; iy++) - { - for (int ix = 0; ix < 8; ix++, i64p++) - cout << *i64p << ' '; - cout << endl; - } + int64_t* i64p; + i64p = (int64_t*)&ptr[i*BLOCK_SIZE]; + for (int iy = 0; iy < 2; iy++) + { + for (int ix = 0; ix < 8; ix++, i64p++) + cout << *i64p << ' '; + cout << endl; + } #endif - cout << boldStop << endl; - } - } + cout << boldStop << endl; + } +} #endif - cacheInsertOps.push_back(CacheInsert_t(lbids[i], versions[i], (uint8_t *) - &alignedbuff[i*BLOCK_SIZE])); + cacheInsertOps.push_back(CacheInsert_t(lbids[i], vd.verID, (uint8_t *) + &alignedbuff[i*BLOCK_SIZE])); } +// else +// cout << "IOM: not inserting " << lbids[i] << "," << vd.verID << " vbflag=" << (int) +// vd.vbFlag << endl; } if (useCache) { blocksLoaded += fbm->bulkInsert(cacheInsertOps); @@ -1179,20 +1404,20 @@ void* thr_popper(ioManager *arg) { uint32_t reportBytesRead = (compressedBytesRead > 0) ? compressedBytesRead : bytesRead; lFile - << left << setw(5) << setfill(' ') << oid - << right << setw(5) << setfill(' ') << offset/extentSize << " " - << right << setw(11) << setfill(' ') << lbid << " " - << right << setw(9) << bytesRead/(readCount << 13) << " " - << right << setw(9) << blocksRequested << " " - << right << setw(10) << fixed << tm3 << " " - << right << fixed << ((double)(rqst1.tv_sec+(1.e-9*rqst1.tv_nsec))) << " " - << right << setw(10) << fixed << rqst3 << " " - << right << setw(10) << fixed << longSeekOffset << " " - << right << setw(10) << fixed << reportBytesRead << " " - << right << setw(3) << fixed << dbroot << " " - << right << setw(3) << fixed << partNum << " " - << right << setw(3) << fixed << segNum << " " - << endl; + << left << setw(5) << setfill(' ') << oid + << right << setw(5) << setfill(' ') << offset/extentSize << " " + << right << setw(11) << setfill(' ') << lbid << " " + << right << setw(9) << bytesRead/(readCount << 13) << " " + << right << setw(9) << blocksRequested << " " + << right << setw(10) << fixed << tm3 << " " + << right << fixed << ((double)(rqst1.tv_sec+(1.e-9*rqst1.tv_nsec))) << " " + << right << setw(10) << fixed << rqst3 << " " + << right << setw(10) << fixed << longSeekOffset << " " + << right << setw(10) << fixed << reportBytesRead << " " + << right << setw(3) << fixed << dbroot << " " + << right << setw(3) << fixed << partNum << " " + << right << setw(3) << fixed << segNum << " " + << endl; } } // for(;;) @@ -1226,29 +1451,15 @@ void dropFDCache() fdcache.clear(); localLock.write_unlock(); } -void purgeFDCache(std::vector& files) -{ - localLock.write_lock(); - - FdCacheType_t::iterator fdit; - for ( uint32_t i=0; i < files.size(); i++) - { - FdEntry fdKey(files[i].oid, files[i].dbRoot, files[i].partitionNum, files[i].segmentNum, files[i].compType, NULL); - fdit = fdcache.find(fdKey); - if (fdit!=fdcache.end()) - fdcache.erase(fdit); - } - localLock.write_unlock(); -} ioManager::ioManager(FileBufferMgr& fbm, - fileBlockRequestQueue& fbrq, - int thrCount, - int bsPerRead): - blocksPerRead(bsPerRead), - fIOMfbMgr(fbm), - fIOMRequestQueue(fbrq), - fFileOp(false) + fileBlockRequestQueue& fbrq, + int thrCount, + int bsPerRead): + blocksPerRead(bsPerRead), + fIOMfbMgr(fbm), + fIOMRequestQueue(fbrq), + fFileOp(false) { if (thrCount<=0) thrCount=1; @@ -1318,36 +1529,29 @@ const int ioManager::localLbidLookup(BRM::LBID_t lbid, uint16_t& segmentNum, uint32_t& fileBlockOffset) { - if (primitiveprocessor::noVB > 0) - vbFlag = false; - int rc = fdbrm.lookupLocal(lbid, - verid, - vbFlag, - oid, - dbRoot, - partitionNum, - segmentNum, - fileBlockOffset); + verid, + vbFlag, + oid, + dbRoot, + partitionNum, + segmentNum, + fileBlockOffset); return rc; } struct LambdaKludge { LambdaKludge(ioManager *i) : iom(i) { } - ~LambdaKludge() { - iom = NULL; - } + ~LambdaKludge() { iom = NULL; } ioManager *iom; - void operator()() { - thr_popper(iom); - } + void operator()() { thr_popper(iom); } }; void ioManager::createReaders() { int idx; - for (idx = 0; idx < fThreadCount; idx++) { + for (idx = 0; idx < fThreadCount; idx++){ try { fThreadArr.create_thread(LambdaKludge(this)); } @@ -1396,7 +1600,7 @@ fileRequest* ioManager::getNextRequest() { // Lastly, notifies waiting thread that fileRequest has been completed. //------------------------------------------------------------------------------ void ioManager::handleBlockReadError( fileRequest* fr, - const string& errMsg, bool *copyLocked, int errorCode ) { + const string& errMsg, bool *copyLocked, int errorCode ) { try { dbrm()->releaseLBIDRange(fr->Lbid(), fr->BlocksRequested()); *copyLocked = false; diff --git a/primitives/blockcache/iomanager.h b/primitives/blockcache/iomanager.h index c3d8b5f3..ca0c9772 100644 --- a/primitives/blockcache/iomanager.h +++ b/primitives/blockcache/iomanager.h @@ -17,7 +17,7 @@ #ifndef IOMANAGER_H #define IOMANAGER_H -// $Id: iomanager.h 2145 2013-08-09 22:38:19Z wweeks $ +// $Id: iomanager.h 2089 2013-05-06 17:56:34Z pleblanc $ // // C++ Interface: iomanager // @@ -79,7 +79,7 @@ class ioManager { const uint32_t getExtentRows() { return fdbrm.getExtentRows(); } - uint32_t blocksPerRead; + uint blocksPerRead; bool IOTrace() const { return fIOTrace;} @@ -96,9 +96,10 @@ class ioManager { BRM::DBRM* dbrm() { return &fdbrm;} + void dropFDCache(); #ifdef SHARED_NOTHING_DEMO_2 - uint32_t pmCount; + uint pmCount; #endif private: @@ -129,7 +130,7 @@ class ioManager { void setReadLock(); void releaseReadLock(); void dropFDCache(); -void purgeFDCache(std::vector& files); + } #endif diff --git a/primitives/blockcache/stats.cpp b/primitives/blockcache/stats.cpp index 8c1f892f..8df67f0f 100644 --- a/primitives/blockcache/stats.cpp +++ b/primitives/blockcache/stats.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: stats.cpp 2035 2013-01-21 14:12:19Z rdempsey $ +* $Id: stats.cpp 1855 2012-04-04 18:20:09Z rdempsey $ */ #include @@ -137,7 +137,7 @@ class TraceFile //Compiler defaults okay //TraceFile(const TraceFile& rhs); //TraceFile operator=(const TraceFile& rhs); - boost::shared_ptr oFile; + shared_ptr oFile; }; diff --git a/primitives/blockcache/stats.h b/primitives/blockcache/stats.h index 7f301780..fed249c1 100644 --- a/primitives/blockcache/stats.h +++ b/primitives/blockcache/stats.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: stats.h 2035 2013-01-21 14:12:19Z rdempsey $ +* $Id: stats.h 1855 2012-04-04 18:20:09Z rdempsey $ */ /** @file */ diff --git a/primitives/blockcache/tdriver.cpp b/primitives/blockcache/tdriver.cpp index e28d5777..8489e33b 100644 --- a/primitives/blockcache/tdriver.cpp +++ b/primitives/blockcache/tdriver.cpp @@ -78,8 +78,8 @@ void* thr_client(void* clientArgs) { uint64_t noOpCount=0; thr_wait_t* clientWait = (thr_wait_t*)clientArgs; struct timeval tv, tv2; - uint32_t randstate=0; - randstate = static_cast(tv.tv_usec); + uint randstate=0; + randstate = static_cast(tv.tv_usec); pthread_mutex_lock(&clientWait->fMutex); clientWait->predicate++; pthread_mutex_unlock(&clientWait->fMutex); @@ -155,7 +155,7 @@ void LoadRange(const LBIDRange_v& v, uint32_t& loadCount) blockCacheClient bc(BRP); uint32_t rCount=0; - for (uint32_t i =0; i rangesLoaded) ranges.pop_back(); #ifdef BLAH - for (uint32_t i =0; i @@ -43,21 +43,23 @@ using namespace logging; using namespace dbbc; using namespace primitives; using namespace primitiveprocessor; -using namespace execplan; namespace { +const long long MAX64=0x7fffffffffffffffLL; +const long long MIN64=0x8000000000000000LL; + inline uint64_t order_swap(uint64_t x) { - uint64_t ret = (x>>56) | - ((x<<40) & 0x00FF000000000000ULL) | - ((x<<24) & 0x0000FF0000000000ULL) | - ((x<<8) & 0x000000FF00000000ULL) | - ((x>>8) & 0x00000000FF000000ULL) | - ((x>>24) & 0x0000000000FF0000ULL) | - ((x>>40) & 0x000000000000FF00ULL) | - (x<<56); + uint64_t ret = (x>>56) | + ((x<<40) & 0x00FF000000000000ULL) | + ((x<<24) & 0x0000FF0000000000ULL) | + ((x<<8) & 0x000000FF00000000ULL) | + ((x>>8) & 0x00000000FF000000ULL) | + ((x>>24) & 0x0000000000FF0000ULL) | + ((x>>40) & 0x000000000000FF00ULL) | + (x<<56); return ret; } @@ -69,7 +71,7 @@ idb_regex_t placeholderRegex; template inline int compareBlock( const void * a, const void * b ) { - return ( (*(T*)a) - (*(T*)b) ); + return ( (*(T*)a) - (*(T*)b) ); } //this function is out-of-band, we don't need to inline it @@ -88,9 +90,9 @@ void logIt(int mid, int arg1, const string& arg2=string()) //FIXME: what are we trying to accomplish here? It looks like we just want to count // the chars in a string arg? -p_DataValue convertToPDataValue(const void* val, int W) +PrimitiveProcessor::p_DataValue convertToPDataValue(const void* val, int W) { - p_DataValue dv; + PrimitiveProcessor::p_DataValue dv; string str; if (8 == W) str = fixChar<8>(*reinterpret_cast(val)); @@ -106,23 +108,23 @@ template inline bool colCompare_(const T& val1, const T& val2, uint8_t COP) { switch(COP) { - case COMPARE_NIL: - return false; - case COMPARE_LT: - return val1 < val2; - case COMPARE_EQ: - return val1 == val2; - case COMPARE_LE: - return val1 <= val2; - case COMPARE_GT: - return val1 > val2; - case COMPARE_NE: - return val1 != val2; - case COMPARE_GE: - return val1 >= val2; - default: - logIt(34, COP, "colCompare"); - return false; // throw an exception here? + case COMPARE_NIL: + return false; + case COMPARE_LT: + return val1 < val2; + case COMPARE_EQ: + return val1 == val2; + case COMPARE_LE: + return val1 <= val2; + case COMPARE_GT: + return val1 > val2; + case COMPARE_NE: + return val1 != val2; + case COMPARE_GE: + return val1 >= val2; + default: + logIt(34, COP, "colCompare"); + return false; // throw an exception here? } } @@ -130,23 +132,23 @@ template inline bool colCompare_(const T& val1, const T& val2, uint8_t COP, uint8_t rf) { switch(COP) { - case COMPARE_NIL: - return false; - case COMPARE_LT: - return val1 < val2 || (val1 == val2 && (rf & 0x01)); - case COMPARE_LE: - return val1 < val2 || (val1 == val2 && rf ^ 0x80); - case COMPARE_EQ: - return val1 == val2 && rf == 0; - case COMPARE_NE: - return val1 != val2 || rf != 0; - case COMPARE_GE: - return val1 > val2 || (val1 == val2 && rf ^ 0x01); - case COMPARE_GT: - return val1 > val2 || (val1 == val2 && (rf & 0x80)); - default: - logIt(34, COP, "colCompare_l"); - return false; // throw an exception here? + case COMPARE_NIL: + return false; + case COMPARE_LT: + return val1 < val2 || (val1 == val2 && (rf & 0x01)); + case COMPARE_LE: + return val1 < val2 || (val1 == val2 && rf ^ 0x80); + case COMPARE_EQ: + return val1 == val2 && rf == 0; + case COMPARE_NE: + return val1 != val2 || rf != 0; + case COMPARE_GE: + return val1 > val2 || (val1 == val2 && rf ^ 0x01); + case COMPARE_GT: + return val1 > val2 || (val1 == val2 && (rf & 0x80)); + default: + logIt(34, COP, "colCompare_l"); + return false; // throw an exception here? } } @@ -166,33 +168,33 @@ bool isLike(const char *val, const idb_regex_t *regex) inline bool colStrCompare_(uint64_t val1, uint64_t val2, uint8_t COP, uint8_t rf, const idb_regex_t* regex) { switch(COP) { - case COMPARE_NIL: - return false; - case COMPARE_LT: - return val1 < val2 || (val1 == val2 && rf != 0); - case COMPARE_LE: - return val1 <= val2; - case COMPARE_EQ: - return val1 == val2 && rf == 0; - case COMPARE_NE: - return val1 != val2 || rf != 0; - case COMPARE_GE: - return val1 > val2 || (val1 == val2 && rf == 0); - case COMPARE_GT: - return val1 > val2; - case COMPARE_LIKE: - case COMPARE_NLIKE: { - /* LIKE comparisons are string comparisons so we reverse the order again. - Switching the order twice is probably as efficient as evaluating a guard. */ - char tmp[9]; - val1 = order_swap(val1); - memcpy(tmp, &val1, 8); - tmp[8] = '\0'; - return (COP & COMPARE_NOT ? !isLike(tmp, regex) : isLike(tmp, regex)); - } - default: - logIt(34, COP, "colCompare_l"); - return false; // throw an exception here? + case COMPARE_NIL: + return false; + case COMPARE_LT: + return val1 < val2 || (val1 == val2 && rf != 0); + case COMPARE_LE: + return val1 <= val2; + case COMPARE_EQ: + return val1 == val2 && rf == 0; + case COMPARE_NE: + return val1 != val2 || rf != 0; + case COMPARE_GE: + return val1 > val2 || (val1 == val2 && rf == 0); + case COMPARE_GT: + return val1 > val2; + case COMPARE_LIKE: + case COMPARE_NLIKE: { + /* LIKE comparisons are string comparisons so we reverse the order again. + Switching the order twice is probably as efficient as evaluating a guard. */ + char tmp[9]; + val1 = order_swap(val1); + memcpy(tmp, &val1, 8); + tmp[8] = '\0'; + return (COP & COMPARE_NOT ? !isLike(tmp, regex) : isLike(tmp, regex)); + } + default: + logIt(34, COP, "colCompare_l"); + return false; // throw an exception here? } } @@ -200,33 +202,33 @@ inline bool colStrCompare_(uint64_t val1, uint64_t val2, uint8_t COP, uint8_t rf inline bool colStrCompare_(uint64_t val1, uint64_t val2, uint8_t COP, const idb_regex_t* regex) { switch(COP) { - case COMPARE_NIL: - return false; - case COMPARE_LT: - return val1 < val2; - case COMPARE_LE: - return val1 <= val2; - case COMPARE_EQ: - return val1 == val2; - case COMPARE_NE: - return val1 != val2; - case COMPARE_GE: - return val1 >= val2; - case COMPARE_GT: - return val1 > val2; - case COMPARE_LIKE: - case COMPARE_NOT | COMPARE_LIKE: { - /* LIKE comparisons are string comparisons so we reverse the order again. - Switching the order twice is probably as efficient as evaluating a guard. */ - char tmp[9]; - val1 = order_swap(val1); - memcpy(tmp, &val1, 8); - tmp[8] = '\0'; - return (COP & COMPARE_NOT ? !isLike(tmp, regex) : isLike(tmp, regex)); - } - default: - logIt(34, COP, "colCompare"); - return false; // throw an exception here? + case COMPARE_NIL: + return false; + case COMPARE_LT: + return val1 < val2; + case COMPARE_LE: + return val1 <= val2; + case COMPARE_EQ: + return val1 == val2; + case COMPARE_NE: + return val1 != val2; + case COMPARE_GE: + return val1 >= val2; + case COMPARE_GT: + return val1 > val2; + case COMPARE_LIKE: + case COMPARE_NOT | COMPARE_LIKE: { + /* LIKE comparisons are string comparisons so we reverse the order again. + Switching the order twice is probably as efficient as evaluating a guard. */ + char tmp[9]; + val1 = order_swap(val1); + memcpy(tmp, &val1, 8); + tmp[8] = '\0'; + return (COP & COMPARE_NOT ? !isLike(tmp, regex) : isLike(tmp, regex)); + } + default: + logIt(34, COP, "colCompare"); + return false; // throw an exception here? } } #endif @@ -241,17 +243,14 @@ inline bool isEmptyVal<8>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: + case WriteEngine::DOUBLE: return (joblist::DOUBLEEMPTYROW == *val); - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - case CalpontSystemCatalog::VARBINARY: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: + case WriteEngine::VARBINARY: return (*val == joblist::CHAR8EMPTYROW); - case CalpontSystemCatalog::UBIGINT: - return (joblist::UBIGINTEMPTYROW == *val); default: break; } @@ -266,16 +265,13 @@ inline bool isEmptyVal<4>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: + case WriteEngine::FLOAT: return (joblist::FLOATEMPTYROW == *val); - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return (joblist::CHAR4EMPTYROW == *val); - case CalpontSystemCatalog::UINT: - return (joblist::UINTEMPTYROW == *val); default: break; } @@ -290,13 +286,11 @@ inline bool isEmptyVal<2>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return (joblist::CHAR2EMPTYROW == *val); - case CalpontSystemCatalog::USMALLINT: - return (joblist::USMALLINTEMPTYROW == *val); default: break; } @@ -311,13 +305,11 @@ inline bool isEmptyVal<1>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return (*val == joblist::CHAR1EMPTYROW); - case CalpontSystemCatalog::UTINYINT: - return (*val == joblist::UTINYINTEMPTYROW); default: break; } @@ -335,19 +327,16 @@ inline bool isNullVal<8>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::DOUBLE: - case CalpontSystemCatalog::UDOUBLE: + case WriteEngine::DOUBLE: return (joblist::DOUBLENULL == *val); - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: - case CalpontSystemCatalog::VARBINARY: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: + case WriteEngine::VARBINARY: //@bug 339 might be a token here //TODO: what's up with the second const here? return (*val == joblist::CHAR8NULL || 0xFFFFFFFFFFFFFFFELL == *val); - case CalpontSystemCatalog::UBIGINT: - return (joblist::UBIGINTNULL == *val); default: break; } @@ -362,17 +351,14 @@ inline bool isNullVal<4>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::FLOAT: - case CalpontSystemCatalog::UFLOAT: + case WriteEngine::FLOAT: return (joblist::FLOATNULL == *val); - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: return (joblist::CHAR4NULL == *val); - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return (joblist::DATENULL == *val); - case CalpontSystemCatalog::UINT: - return (joblist::UINTNULL == *val); default: break; } @@ -387,13 +373,11 @@ inline bool isNullVal<2>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return (joblist::CHAR2NULL == *val); - case CalpontSystemCatalog::USMALLINT: - return (joblist::USMALLINTNULL == *val); default: break; } @@ -408,13 +392,11 @@ inline bool isNullVal<1>(uint8_t type, const uint8_t* ival) switch (type) { - case CalpontSystemCatalog::CHAR: - case CalpontSystemCatalog::VARCHAR: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::DATETIME: + case WriteEngine::CHAR: + case WriteEngine::VARCHAR: + case WriteEngine::DATE: + case WriteEngine::DATETIME: return (*val == joblist::CHAR1NULL); - case CalpontSystemCatalog::UTINYINT: - return (joblist::UTINYINTNULL == *val); default: break; } @@ -423,17 +405,13 @@ inline bool isNullVal<1>(uint8_t type, const uint8_t* ival) } /* A generic isNullVal */ -inline bool isNullVal(uint32_t length, uint8_t type, const uint8_t *val8) +inline bool isNullVal(uint length, uint8_t type, const uint8_t *val8) { switch (length) { - case 8: - return isNullVal<8>(type, val8); - case 4: - return isNullVal<4>(type, val8); - case 2: - return isNullVal<2>(type, val8); - case 1: - return isNullVal<1>(type, val8); + case 8: return isNullVal<8>(type, val8); + case 4: return isNullVal<4>(type, val8); + case 2: return isNullVal<2>(type, val8); + case 1: return isNullVal<1>(type, val8); }; return false; } @@ -448,23 +426,18 @@ inline bool isMinMaxValid(const NewColRequestHeader *in) { else { switch (in->DataType) { - case CalpontSystemCatalog::CHAR: + case WriteEngine::CHAR: return (in->DataSize<9); - case CalpontSystemCatalog::VARCHAR: + case WriteEngine::VARCHAR: return (in->DataSize<8); - case CalpontSystemCatalog::TINYINT: - case CalpontSystemCatalog::SMALLINT: - case CalpontSystemCatalog::INT: - case CalpontSystemCatalog::DATE: - case CalpontSystemCatalog::BIGINT: - case CalpontSystemCatalog::DATETIME: - case CalpontSystemCatalog::UTINYINT: - case CalpontSystemCatalog::USMALLINT: - case CalpontSystemCatalog::UINT: - case CalpontSystemCatalog::UBIGINT: + case WriteEngine::TINYINT: + case WriteEngine::SMALLINT: + case WriteEngine::INT: + case WriteEngine::DATE: + case WriteEngine::BIGINT: + case WriteEngine::DATETIME: return true; - case CalpontSystemCatalog::DECIMAL: - case CalpontSystemCatalog::UDECIMAL: + case WriteEngine::DECIMAL: return (in->DataSize <= 8); default: return false; @@ -476,7 +449,7 @@ inline bool isMinMaxValid(const NewColRequestHeader *in) { template inline string fixChar(int64_t intval) { - char chval[W + 1]; + char chval[W + 1]; memcpy(chval, &intval, W); chval[W] = '\0'; @@ -490,22 +463,22 @@ inline bool colCompare(int64_t val1, int64_t val2, uint8_t COP, uint8_t rf, int if (COMPARE_NIL == COP) return false; //@bug 425 added isNull condition - else if ( !isNull && (type == CalpontSystemCatalog::FLOAT || type == CalpontSystemCatalog::DOUBLE)) { + else if ( !isNull && (type == WriteEngine::FLOAT || type == WriteEngine::DOUBLE)) { double dVal1, dVal2; - if (type == CalpontSystemCatalog::FLOAT) + if (type == WriteEngine::FLOAT) { - dVal1 = *((float *) &val1); - dVal2 = *((float *) &val2); + dVal1 = *((float *) &val1); + dVal2 = *((float *) &val2); } else { - dVal1 = *((double *) &val1); - dVal2 = *((double *) &val2); + dVal1 = *((double *) &val1); + dVal2 = *((double *) &val2); } return colCompare_(dVal1, dVal2, COP); } - else if ( (type == CalpontSystemCatalog::CHAR || type == CalpontSystemCatalog::VARCHAR) && !isNull ) + else if ( (type == WriteEngine::CHAR || type == WriteEngine::VARCHAR) && !isNull ) { if (!regex.used && !rf) return colCompare_(order_swap(val1), order_swap(val2), COP); @@ -523,25 +496,19 @@ inline bool colCompare(int64_t val1, int64_t val2, uint8_t COP, uint8_t rf, int } } -inline bool colCompareUnsigned(uint64_t val1, uint64_t val2, uint8_t COP, uint8_t rf, int type, uint8_t width, const idb_regex_t& regex, bool isNull=false) +template +inline void udf(UDFFcnPtr_t fp, void* out, const uint8_t* in) { -// cout << "comparing unsigned" << hex << val1 << " to " << val2 << endl; - - if (COMPARE_NIL == COP) return false; - - /* isNullVal should work on the normalized value on little endian machines */ - bool val2Null = isNullVal(width, type, (uint8_t *) &val2); - if (isNull == val2Null || (val2Null && COP == COMPARE_NE)) - return colCompare_(val1, val2, COP, rf); - else - return false; + int64_t* invp = (int64_t*)in; + int64_t outv = fp(*invp); + memcpy(out, &outv, N); } inline void store(const NewColRequestHeader *in, - NewColResultHeader *out, - unsigned outSize, - unsigned *written, - uint16_t rid, const uint8_t *block8) + NewColResultHeader *out, + unsigned outSize, + unsigned *written, + uint16_t rid, const uint8_t *block8) { uint8_t* out8 = reinterpret_cast(out); @@ -553,7 +520,7 @@ inline void store(const NewColRequestHeader *in, } #endif out->RidFlags |= (1 << (rid >> 10)); // set the (row/1024)'th bit - memcpy(&out8[*written], &rid, 2); + memcpy(&out8[*written], &rid, 2); *written += 2; } @@ -593,21 +560,22 @@ inline void store(const NewColRequestHeader *in, } template -inline uint64_t nextUnsignedColValue(int type, - const uint16_t *ridArray, - int NVALS, - int *index, - bool *done, - bool *isNull, - bool *isEmpty, - uint16_t *rid, - uint8_t OutputType, uint8_t *val8, unsigned itemsPerBlk) +inline int64_t nextColValue(int type, + const uint16_t *ridArray, + int NVALS, + int *index, + bool *done, + bool *isNull, + bool *isEmpty, + uint16_t *rid, + uint8_t OutputType, uint8_t *val8, unsigned itemsPerBlk) { + const uint8_t* vp = 0; if (ridArray == NULL) { while (static_cast(*index) < itemsPerBlk && - isEmptyVal(type, &val8[*index*W]) && - (OutputType & OT_RID)) + isEmptyVal(type, &val8[*index*W]) && + (OutputType & OT_RID)) { (*index)++; } @@ -624,7 +592,7 @@ inline uint64_t nextUnsignedColValue(int type, } else { while (*index < NVALS && - isEmptyVal(type, &val8[ridArray[*index] * W])) + isEmptyVal(type, &val8[ridArray[*index] * W])) { (*index)++; } @@ -639,80 +607,6 @@ inline uint64_t nextUnsignedColValue(int type, *isEmpty = isEmptyVal(type, vp); *rid = ridArray[(*index)++]; } - // at this point, nextRid is the index to return, and index is... - // if RIDs are not specified, nextRid + 1, - // if RIDs are specified, it's the next index in the rid array. - //Bug 838, tinyint null problem - switch (W) - { - case 1: - return reinterpret_cast (val8)[*rid]; - case 2: - return reinterpret_cast(val8)[*rid]; - case 4: - return reinterpret_cast(val8)[*rid]; - case 8: - return reinterpret_cast(val8)[*rid]; - default: - logIt(33, W); - -#ifdef PRIM_DEBUG - throw logic_error("PrimitiveProcessor::nextColValue() bad width"); -#endif - return -1; - } -} - -template -inline int64_t nextColValue(int type, - const uint16_t *ridArray, - int NVALS, - int *index, - bool *done, - bool *isNull, - bool *isEmpty, - uint16_t *rid, - uint8_t OutputType, uint8_t *val8, unsigned itemsPerBlk) -{ - const uint8_t* vp = 0; - if (ridArray == NULL) - { - while (static_cast(*index) < itemsPerBlk && - isEmptyVal(type, &val8[*index*W]) && - (OutputType & OT_RID)) - { - (*index)++; - } - - if (static_cast(*index) >= itemsPerBlk) { - *done = true; - return 0; - } - - vp = &val8[*index*W]; - *isNull = isNullVal(type, vp); - *isEmpty = isEmptyVal(type, vp); - *rid = (*index)++; - } - else - { - while (*index < NVALS && - isEmptyVal(type, &val8[ridArray[*index] * W])) - { - (*index)++; - } - - if (*index >= NVALS) - { - *done = true; - return 0; - } - - vp = &val8[ridArray[*index] * W]; - *isNull = isNullVal(type, vp); - *isEmpty = isEmptyVal(type, vp); - *rid = ridArray[(*index)++]; - } // at this point, nextRid is the index to return, and index is... // if RIDs are not specified, nextRid + 1, @@ -726,7 +620,7 @@ inline int64_t nextColValue(int type, return reinterpret_cast(val8)[*rid]; case 4: #if 0 - if (type == CalpontSystemCatalog::FLOAT) { + if (type == WriteEngine::FLOAT) { // convert the float to a 64-bit type, return that w/o conversion int32_t* val32 = reinterpret_cast(val8); double dTmp; @@ -736,7 +630,7 @@ inline int64_t nextColValue(int type, return reinterpret_cast(val8)[*rid]; } #else - return reinterpret_cast(val8)[*rid]; + return reinterpret_cast(val8)[*rid]; #endif case 8: return reinterpret_cast(val8)[*rid]; @@ -750,79 +644,43 @@ inline int64_t nextColValue(int type, } } - -// done should be init'd to false and -// index should be init'd to 0 on the first call -// done == true when there are no more elements to return. -inline uint64_t nextUnsignedColValueHelper(int type, - int width, - const uint16_t *ridArray, - int NVALS, - int *index, - bool *done, - bool *isNull, - bool *isEmpty, - uint16_t *rid, - uint8_t OutputType, uint8_t *val8, unsigned itemsPerBlk) -{ - switch (width) - { - case 8: - return nextUnsignedColValue<8>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); - case 4: - return nextUnsignedColValue<4>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); - case 2: - return nextUnsignedColValue<2>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); - case 1: - return nextUnsignedColValue<1>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); - default: - idbassert(0); - } - /*NOTREACHED*/ - return 0; -} - // done should be init'd to false and // index should be init'd to 0 on the first call // done == true when there are no more elements to return. inline int64_t nextColValueHelper(int type, - int width, - const uint16_t *ridArray, - int NVALS, - int *index, - bool *done, - bool *isNull, - bool *isEmpty, - uint16_t *rid, - uint8_t OutputType, uint8_t *val8, unsigned itemsPerBlk) + int width, + const uint16_t *ridArray, + int NVALS, + int *index, + bool *done, + bool *isNull, + bool *isEmpty, + uint16_t *rid, + uint8_t OutputType, uint8_t *val8, unsigned itemsPerBlk) { switch (width) { case 8: return nextColValue<8>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); + itemsPerBlk); case 4: return nextColValue<4>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); + itemsPerBlk); case 2: return nextColValue<2>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); + itemsPerBlk); case 1: return nextColValue<1>(type, ridArray, NVALS, index, done, isNull, isEmpty, rid, OutputType, val8, - itemsPerBlk); + itemsPerBlk); default: idbassert(0); } /*NOTREACHED*/ return 0; } -#if 0 + inline void p_Col_noprid(const NewColRequestHeader *in, NewColResultHeader *out, - unsigned outSize, unsigned *written, int* block) + unsigned outSize, unsigned *written, int* block) { int argIndex, argOffset; @@ -830,16 +688,16 @@ inline void p_Col_noprid(const NewColRequestHeader *in, NewColResultHeader *out, const ColArgs *args; const uint8_t *in8 = reinterpret_cast(in); int64_t argVal, colVal; - uint64_t uargVal, ucolVal; int8_t *val8 = reinterpret_cast(block); int16_t *val16 = reinterpret_cast(block); int32_t *val32 = reinterpret_cast(block); int64_t *val64 = reinterpret_cast(block); - uint8_t *uval8 = reinterpret_cast(block); - uint16_t *uval16 = reinterpret_cast(block); - uint32_t *uval32 = reinterpret_cast(block); - uint64_t *uval64 = reinterpret_cast(block); + + // No Min/Max returned since this is not a full scan. + out->ValidMinMax = false; + out->Min = 0; + out->Max = 0; placeholderRegex.used = false; @@ -847,83 +705,60 @@ inline void p_Col_noprid(const NewColRequestHeader *in, NewColResultHeader *out, for (argIndex = 0; argIndex < in->NVALS; argIndex++) { argOffset = sizeof(NewColRequestHeader) + (argIndex * (sizeof(ColArgs) + - sizeof(int16_t) + in->DataSize)); + sizeof(int16_t) + in->DataSize)); args = reinterpret_cast(&in8[argOffset]); rid = *reinterpret_cast(&in8[argOffset + sizeof(ColArgs) + - in->DataSize]); + in->DataSize]); - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - switch (in->DataSize) - { - case 1: - uargVal = *reinterpret_cast(args->val[0]); - ucolVal = uval8[rid]; - break; - case 2: - uargVal = *reinterpret_cast(args->val); - ucolVal = uval16[rid]; - break; - case 4: - uargVal = *reinterpret_cast(args->val); - ucolVal = uval32[rid]; - break; - case 8: - uargVal = *reinterpret_cast(args->val); - ucolVal = uval64[rid]; - break; - default: - logIt(33, in->DataSize); -#ifdef PRIM_DEBUG - throw logic_error("PrimitiveProcessor::p_Col_noprid(): bad width"); -#endif - return; - } + switch (in->DataSize) { + case 1: argVal = args->val[0]; colVal = val8[rid]; break; + case 2: argVal = *reinterpret_cast(args->val); + colVal = val16[rid]; + break; + case 4: +#if 0 + if (in->DataType == WriteEngine::FLOAT) { + double dTmp; - if (colCompare(ucolVal, uargVal, args->COP, args->rf, in->DataType, in->DataSize, placeholderRegex)) - store(in, out, outSize, written, rid, reinterpret_cast(block)); - } - else - { - switch (in->DataSize) - { - case 1: - argVal = args->val[0]; - colVal = val8[rid]; - break; - case 2: - argVal = *reinterpret_cast(args->val); - colVal = val16[rid]; - break; - case 4: + dTmp = (double) *((const float *) args->val); + argVal = *((int64_t *) &dTmp); + + dTmp = (double) *((float *) val32[rid]); + colVal = *((int64_t *) &dTmp); + } + else { argVal = *reinterpret_cast(args->val); colVal = val32[rid]; - break; - case 8: - argVal = *reinterpret_cast(args->val); - colVal = val64[rid]; - break; - default: - logIt(33, in->DataSize); + } +#else + argVal = *reinterpret_cast(args->val); + colVal = val32[rid]; +#endif + break; + case 8: argVal = *reinterpret_cast(args->val); + colVal = val64[rid]; + break; + default: + logIt(33, in->DataSize); #ifdef PRIM_DEBUG - throw logic_error("PrimitiveProcessor::p_Col_noprid(): bad width"); + throw logic_error("PrimitiveProcessor::p_Col_noprid(): bad width"); #endif - return; - } - - if (colCompare(colVal, argVal, args->COP, args->rf, in->DataType, in->DataSize, placeholderRegex)) - store(in, out, outSize, written, rid, reinterpret_cast(block)); + return; } + + if (colCompare(colVal, argVal, args->COP, args->rf, in->DataType, in->DataSize, placeholderRegex)) + store(in, out, outSize, written, rid, reinterpret_cast(block)); } } -#endif + template inline void p_Col_ridArray(NewColRequestHeader *in, - NewColResultHeader *out, - unsigned outSize, - unsigned *written, int* block, Stats* fStatsPtr, unsigned itemsPerBlk, - boost::shared_ptr parsedColumnFilter) + NewColResultHeader *out, + unsigned outSize, + unsigned *written, int* block, Stats* fStatsPtr, unsigned itemsPerBlk, + boost::shared_ptr parsedColumnFilter, + UDFFcnPtr_t fp) { uint16_t *ridArray=0; uint8_t *in8 = reinterpret_cast(in); @@ -933,7 +768,7 @@ inline void p_Col_ridArray(NewColRequestHeader *in, if (in->NVALS>0) ridArray = reinterpret_cast(&in8[sizeof(NewColRequestHeader) + - (in->NOPS * filterSize)]); + (in->NOPS * filterSize)]); if (ridArray && 1 == in->sort ) { @@ -948,28 +783,17 @@ inline void p_Col_ridArray(NewColRequestHeader *in, // Set boolean indicating whether to capture the min and max values. out->ValidMinMax = isMinMaxValid(in); - if (out->ValidMinMax) - { - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - out->Min = static_cast(numeric_limits::max()); - out->Max = 0; - } - else - { - out->Min = numeric_limits::max(); - out->Max = numeric_limits::min(); - } + if(out->ValidMinMax) { + out->Min = MAX64; + out->Max = MIN64; } - else - { + else { out->Min = 0; out->Max = 0; } const ColArgs *args=NULL; int64_t val=0; - uint64_t uval=0; int nextRidIndex=0, argIndex=0; bool done=false, cmp=false, isNull=false, isEmpty=false; uint16_t rid=0; @@ -978,222 +802,192 @@ inline void p_Col_ridArray(NewColRequestHeader *in, int64_t* std_argVals = (int64_t*)alloca(in->NOPS * sizeof(int64_t)); uint8_t* std_cops = (uint8_t*)alloca(in->NOPS * sizeof(uint8_t)); uint8_t* std_rfs = (uint8_t*)alloca(in->NOPS * sizeof(uint8_t)); - int64_t *argVals = NULL; - uint64_t *uargVals = NULL; - uint8_t *cops = NULL; - uint8_t *rfs = NULL; - + int64_t *argVals; + uint8_t *cops; + uint8_t *rfs; + scoped_array std_regex; - idb_regex_t* regex = NULL; + idb_regex_t* regex; uint8_t likeOps = 0; // no pre-parsed column filter is set, parse the filter in the message - if (parsedColumnFilter.get() == NULL) - { + if (parsedColumnFilter.get() == NULL) { + argVals = std_argVals; + cops = std_cops; + rfs = std_rfs; + std_regex.reset(new idb_regex_t[in->NOPS]); regex = &(std_regex[0]); - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) + for (argIndex = 0; argIndex < in->NOPS; argIndex++) { - uargVals = reinterpret_cast(std_argVals); - cops = std_cops; - rfs = std_rfs; - - for (argIndex = 0; argIndex < in->NOPS; argIndex++) - { - args = reinterpret_cast(&in8[sizeof(NewColRequestHeader) + - (argIndex * filterSize)]); - cops[argIndex] = args->COP; - rfs[argIndex] = args->rf; - - switch (W) - { - case 1: - uargVals[argIndex] = *reinterpret_cast(args->val); - break; - case 2: - uargVals[argIndex] = *reinterpret_cast(args->val); - break; - case 4: - uargVals[argIndex] = *reinterpret_cast(args->val); - break; - case 8: - uargVals[argIndex] = *reinterpret_cast(args->val); - break; - } - regex[argIndex].used = false; - } - } - else - { - argVals = std_argVals; - cops = std_cops; - rfs = std_rfs; - - for (argIndex = 0; argIndex < in->NOPS; argIndex++) - { - args = reinterpret_cast(&in8[sizeof(NewColRequestHeader) + - (argIndex * filterSize)]); - cops[argIndex] = args->COP; - rfs[argIndex] = args->rf; - - switch (W) - { - case 1: - argVals[argIndex] = args->val[0]; - break; - case 2: - argVals[argIndex] = *reinterpret_cast(args->val); - break; - case 4: + args = reinterpret_cast(&in8[sizeof(NewColRequestHeader) + + (argIndex * filterSize)]); + cops[argIndex] = args->COP; + rfs[argIndex] = args->rf; + + switch (W) { + case 1: argVals[argIndex] = args->val[0]; break; + case 2: argVals[argIndex] = *reinterpret_cast(args->val); break; + case 4: #if 0 - if (in->DataType == CalpontSystemCatalog::FLOAT) - { - double dTmp; + if (in->DataType == WriteEngine::FLOAT) { + double dTmp; - dTmp = (double) *((const float *) args->val); - argVals[argIndex] = *((int64_t *) &dTmp); - } - else - argVals[argIndex] = *reinterpret_cast(args->val); + dTmp = (double) *((const float *) args->val); + argVals[argIndex] = *((int64_t *) &dTmp); + } + else + argVals[argIndex] = *reinterpret_cast(args->val); #else argVals[argIndex] = *reinterpret_cast(args->val); #endif - break; - case 8: - argVals[argIndex] = *reinterpret_cast(args->val); - break; - } - if (COMPARE_LIKE & args->COP) + break; + case 8: argVals[argIndex] = *reinterpret_cast(args->val); break; + } + if (COMPARE_LIKE & args->COP) + { + PrimitiveProcessor::p_DataValue dv = convertToPDataValue(&argVals[argIndex], W); + int err = PrimitiveProcessor::convertToRegexp(®ex[argIndex], &dv); + if (err) { - p_DataValue dv = convertToPDataValue(&argVals[argIndex], W); - int err = PrimitiveProcessor::convertToRegexp(®ex[argIndex], &dv); - if (err) - { - throw runtime_error("PrimitiveProcessor::p_Col_ridarray(): Could not create regular expression for LIKE operator"); - } - ++likeOps; + throw runtime_error("PrimitiveProcessor::p_Col_ridarray(): Could not create regular expression for LIKE operator"); } - else - regex[argIndex].used = false; + ++likeOps; } + else + regex[argIndex].used = false; } } // we have a pre-parsed filter, and it's in the form of op and value arrays - else if (parsedColumnFilter->columnFilterMode == TWO_ARRAYS) - { + else if (parsedColumnFilter->columnFilterMode == TWO_ARRAYS) { argVals = parsedColumnFilter->prestored_argVals.get(); - uargVals = reinterpret_cast(parsedColumnFilter->prestored_argVals.get()); cops = parsedColumnFilter->prestored_cops.get(); rfs = parsedColumnFilter->prestored_rfs.get(); regex = parsedColumnFilter->prestored_regex.get(); likeOps = parsedColumnFilter->likeOps; - + } - // else we have a pre-parsed filter, and it's an unordered set for quick == comparisons - - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - uval = nextUnsignedColValue(in->DataType, ridArray, in->NVALS, &nextRidIndex, &done, &isNull, - &isEmpty, &rid, in->OutputType, reinterpret_cast(block), itemsPerBlk); - } - else - { - val = nextColValue(in->DataType, ridArray, in->NVALS, &nextRidIndex, &done, &isNull, - &isEmpty, &rid, in->OutputType, reinterpret_cast(block), itemsPerBlk); + // we have a pre-parsed filter, and it's an unordered set for quick == comparisons + else { + argVals = NULL; + cops = NULL; + rfs = NULL; + regex = NULL; } - while (!done) + val = nextColValue(in->DataType, ridArray, in->NVALS, &nextRidIndex, &done, &isNull, + &isEmpty, &rid, in->OutputType, reinterpret_cast(block), itemsPerBlk); + + if (fp) { - if (cops == NULL) // implies parsedColumnFilter && columnFilterMode == SET +#ifndef _MSC_VER + if ((void*)fp == (void*)::acos || + (void*)fp == (void*)::asin || + (void*)fp == (void*)::atan || + (void*)fp == (void*)::cos || + //(void*)fp == (void*):cotangent || + (void*)fp == (void*)::exp || + (void*)fp == (void*)::log || +#ifdef __linux__ + (void*)fp == (void*)::log2 || +#else + (void*)fp == (void*)::log || +#endif + (void*)fp == (void*)::log10 || + (void*)fp == (void*)::sin || + (void*)fp == (void*)::sqrt || + (void*)fp == (void*)::tan) { - /* bug 1920: ignore NULLs in the set and in the column data */ - if (!(isNull && in->BOP == BOP_AND)) + double (*dfp)(double) = (double (*)(double))fp; + switch (W) { - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - it = parsedColumnFilter->prestored_set->find(*reinterpret_cast(&uval)); - } - else - { - it = parsedColumnFilter->prestored_set->find(val); - } - if (in->BOP == BOP_OR) + case 4: { - // assume COP == COMPARE_EQ - if (it != parsedColumnFilter->prestored_set->end()) - { - store(in, out, outSize, written, rid, reinterpret_cast(block)); - } + float fout; + float* finp = (float*)&val; + int32_t* valp = (int32_t*)&fout; + fout = (float)dfp((double)(*finp)); + val = *valp; } - else if (in->BOP == BOP_AND) + break; + default: { - // assume COP == COMPARE_NE - if (it == parsedColumnFilter->prestored_set->end()) - { - store(in, out, outSize, written, rid, reinterpret_cast(block)); - } + double dout; + double* dinp = (double*)&val; + int64_t* valp = (int64_t*)&dout; + dout = dfp(*dinp); + val = *valp; } + break; } } else { - for (argIndex = 0; argIndex < in->NOPS; argIndex++) - { - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - cmp = colCompareUnsigned(uval, uargVals[argIndex], cops[argIndex], - rfs[argIndex], in->DataType, W, regex[argIndex], isNull); - } - else - { - cmp = colCompare(val, argVals[argIndex], cops[argIndex], - rfs[argIndex], in->DataType, W, regex[argIndex], isNull); + val = fp(val); + } +#else + //FIXME: ??? + val = 0; +#endif + } + + while (!done) { + if (cops == NULL) { // implies parsedColumnFilter && columnFilterMode == SET + + /* bug 1920: ignore NULLs in the set and in the column data */ + if (isNull && in->BOP == BOP_AND) + goto skipnulls; + it = parsedColumnFilter->prestored_set->find(val); + if (in->BOP == BOP_OR) { + // assume COP == COMPARE_EQ + if (it != parsedColumnFilter->prestored_set->end()) { + store(in, out, outSize, written, rid, reinterpret_cast(block)); } + } + else if (in->BOP == BOP_AND) { + // assume COP == COMPARE_NE + if (it == parsedColumnFilter->prestored_set->end()) + store(in, out, outSize, written, rid, reinterpret_cast(block)); + } +skipnulls: ; + } + else { + for (argIndex = 0; argIndex < in->NOPS; argIndex++) { - if (in->NOPS == 1) - { - if (cmp == true) - { + cmp = colCompare(val, argVals[argIndex], cops[argIndex], + rfs[argIndex], in->DataType, W, regex[argIndex], isNull); + + if (in->NOPS == 1) { + if (cmp == true) { store(in, out, outSize, written, rid, reinterpret_cast(block)); } break; } - else if (in->BOP == BOP_AND && cmp == false) - { + else if (in->BOP == BOP_AND && cmp == false) { break; } - else if (in->BOP == BOP_OR && cmp == true) - { + else if (in->BOP == BOP_OR && cmp == true) { store(in, out, outSize, written, rid, reinterpret_cast(block)); break; } } - if ((argIndex == in->NOPS && in->BOP == BOP_AND) || in->NOPS == 0) - { + if ((argIndex == in->NOPS && in->BOP == BOP_AND) || in->NOPS == 0) { store(in, out, outSize, written, rid, reinterpret_cast(block)); } } - + // Set the min and max if necessary. Ignore nulls. - if (out->ValidMinMax && !isNull && !isEmpty) - { + if (out->ValidMinMax && !isNull && !isEmpty) { - if ((in->DataType == CalpontSystemCatalog::CHAR || in->DataType == CalpontSystemCatalog::VARCHAR ) && 1 < W) + if ( (in->DataType == WriteEngine::CHAR || in->DataType == WriteEngine::VARCHAR ) && 1 < W) { if (colCompare(out->Min, val, COMPARE_GT, false, in->DataType, W, placeholderRegex)) out->Min = val; if (colCompare(out->Max, val, COMPARE_LT, false, in->DataType, W, placeholderRegex)) out->Max = val; } - else if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - if (static_cast(out->Min) > uval) - out->Min = static_cast(uval); - if (static_cast(out->Max) < uval) - out->Max = static_cast(uval);; - } else { if (out->Min > val) @@ -1203,18 +997,62 @@ inline void p_Col_ridArray(NewColRequestHeader *in, } } - if (isUnsigned((CalpontSystemCatalog::ColDataType)in->DataType)) - { - uval = nextUnsignedColValue(in->DataType, ridArray, in->NVALS, &nextRidIndex, &done, - &isNull, &isEmpty, &rid, in->OutputType, reinterpret_cast(block), - itemsPerBlk); - } - else + val = nextColValue(in->DataType, ridArray, in->NVALS, &nextRidIndex, &done, + &isNull, &isEmpty, &rid, in->OutputType, reinterpret_cast(block), + itemsPerBlk); + + if (fp) { - val = nextColValue(in->DataType, ridArray, in->NVALS, &nextRidIndex, &done, - &isNull, &isEmpty, &rid, in->OutputType, reinterpret_cast(block), - itemsPerBlk); +#ifndef _MSC_VER + if ((void*)fp == (void*)::acos || + (void*)fp == (void*)::asin || + (void*)fp == (void*)::atan || + (void*)fp == (void*)::cos || + //(void*)fp == (void*):cotangent || + (void*)fp == (void*)::exp || + (void*)fp == (void*)::log || +#ifdef __linux__ + (void*)fp == (void*)::log2 || +#else + (void*)fp == (void*)::log || +#endif + (void*)fp == (void*)::log10 || + (void*)fp == (void*)::sin || + (void*)fp == (void*)::sqrt || + (void*)fp == (void*)::tan) + { + double (*dfp)(double) = (double (*)(double))fp; + switch (W) + { + case 4: + { + float fout; + float* finp = (float*)&val; + int32_t* valp = (int32_t*)&fout; + fout = (float)dfp((double)(*finp)); + val = *valp; + } + break; + default: + { + double dout; + double* dinp = (double*)&val; + int64_t* valp = (int64_t*)&dout; + dout = dfp(*dinp); + val = *valp; + } + break; + } + } + else + { + val = fp(val); + } +#else + val = 0; +#endif } + } if (fStatsPtr) @@ -1231,7 +1069,7 @@ namespace primitives { void PrimitiveProcessor::p_Col(NewColRequestHeader *in, NewColResultHeader *out, - unsigned outSize, unsigned *written) + unsigned outSize, unsigned *written, UDFFcnPtr_t fp) { memcpy(out, in, sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); out->NVALS = 0; @@ -1255,10 +1093,10 @@ void PrimitiveProcessor::p_Col(NewColRequestHeader *in, NewColResultHeader *out, // short-circuit the actual block scan for testing if (out->LBID >= 802816) { - out->ValidMinMax = false; - out->Min = 0; - out->Max = 0; - return; + out->ValidMinMax = false; + out->Min = 0; + out->Max = 0; + return; } #endif @@ -1271,16 +1109,16 @@ void PrimitiveProcessor::p_Col(NewColRequestHeader *in, NewColResultHeader *out, switch (in->DataSize) { case 8: - p_Col_ridArray<8>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter); + p_Col_ridArray<8>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter, fp); break; case 4: - p_Col_ridArray<4>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter); + p_Col_ridArray<4>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter, fp); break; case 2: - p_Col_ridArray<2>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter); + p_Col_ridArray<2>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter, fp); break; case 1: - p_Col_ridArray<1>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter); + p_Col_ridArray<1>(in, out, outSize, written, block, fStatsPtr, itemsPerBlk, parsedColumnFilter, fp); break; default: idbassert(0); @@ -1294,12 +1132,193 @@ void PrimitiveProcessor::p_Col(NewColRequestHeader *in, NewColResultHeader *out, #endif } -boost::shared_ptr parseColumnFilter -(const uint8_t *filterString, uint32_t colWidth, uint32_t colType, uint32_t filterCount, - uint32_t BOP) +// This needs to be tested more then condensed. +void PrimitiveProcessor::do_sum8(NewColAggResultHeader *out, int64_t val) +{ + + if (out->SumSign == 0) { + if (val > 0) { + out->Sum += val; + if (out->Sum < 0) { + out->SumOverflow++; + out->Sum -= (static_cast(MAX64) + 1); + } + } + else { + out->Sum += val; + if (out->Sum < 0) { + if (out->SumOverflow > 0) { + out->SumOverflow--; + out->Sum += (static_cast(MAX64) + 1); + } + else { + out->SumSign = 1; + out->Sum = abs((int)out->Sum); + } + } + } + } + else { + if (val < 0) { + out->Sum -= val; + if (out->Sum < 0) { + out->SumOverflow++; + out->Sum -= (static_cast(MAX64) + 1); + } + } + else { + out->Sum -= val; + if (out->Sum < 0) { + if (out->SumOverflow > 0) { + out->SumOverflow--; + out->Sum += (static_cast(MAX64) + 1); + } + else { + out->SumSign = 0; + out->Sum = abs((int)out->Sum); + } + } + } + } +} + +void PrimitiveProcessor::p_ColAggregate(const NewColAggRequestHeader *in, + NewColAggResultHeader *out) +{ + const uint16_t *ridArray; + const u_int8_t *in8; + int ridIndex, argIndex; + uint16_t ridIndex2; + int64_t val; //, argVal=0; + bool done, cmp, isNull=true, isEmpty=true; + const ColArgs *args; + unsigned itemsPerBlk = 0; + + placeholderRegex.used = false; + + if (logicalBlockMode) + itemsPerBlk = BLOCK_SIZE; + else + itemsPerBlk = BLOCK_SIZE/in->DataSize; + + + memcpy(out, in, sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); + out->ism.Command = COL_AGG_RESULTS; + out->LBID = in->LBID; + out->Sum = 0; + out->SumOverflow = 0; + out->SumSign = 0; + out->Min = MAX64; + out->Max = MIN64; + out->NVALS = 0; + + in8 = reinterpret_cast(in); + const uint8_t filterSize = sizeof(uint8_t) + sizeof(uint8_t) + in->DataSize; + + if (in->NVALS == 0) + ridArray = NULL; + else + ridArray = reinterpret_cast(&in8[sizeof(NewColAggRequestHeader) + + (in->NOPS * filterSize)]); + + ridIndex = 0; + done = false; + + int64_t* argVals = (int64_t*)alloca(in->NOPS * sizeof(int64_t)); + uint8_t* cops = (uint8_t*)alloca(in->NOPS * sizeof(uint8_t)); + uint8_t* rfs = (uint8_t*)alloca(in->NOPS * sizeof(uint8_t)); + scoped_array regex(new idb_regex_t[in->NOPS]); + +//@bug 1828 Need to compile the like reg expressions first. + for (argIndex = 0; argIndex < in->NOPS; argIndex++) + { + args = reinterpret_cast(&in8[sizeof(NewColAggRequestHeader) + + (argIndex * filterSize)]); + cops[argIndex] = args->COP; + rfs[argIndex] = args->rf; + switch (in->DataSize) + { + case 1: argVals[argIndex] = args->val[0]; break; + case 2: argVals[argIndex] = *reinterpret_cast(args->val); break; + case 4: argVals[argIndex] = *reinterpret_cast(args->val); break; + case 8: argVals[argIndex] = *reinterpret_cast(args->val); break; + } + + if (COMPARE_LIKE & args->COP) + { + PrimitiveProcessor::p_DataValue dv = convertToPDataValue(&argVals[argIndex], in->DataSize); + int err = PrimitiveProcessor::convertToRegexp(®ex[argIndex], &dv); + if (err) + { + throw runtime_error("PrimitiveProcessor::p_colAggregate(): Could not create regular expression for LIKE operator"); + } + } + } + + + + for (val = nextColValueHelper(in->DataType, in->DataSize, ridArray, in->NVALS, &ridIndex, &done, &isNull, &isEmpty, &ridIndex2, in->OutputType, reinterpret_cast(block), itemsPerBlk); + !done; + val = nextColValueHelper(in->DataType, in->DataSize, ridArray, in->NVALS, &ridIndex, &done, &isNull, &isEmpty, &ridIndex2, in->OutputType, reinterpret_cast(block), itemsPerBlk)) { + + if (isNull) + continue; + + for (argIndex = 0; argIndex < in->NOPS; argIndex++) { + + cmp = colCompare(val, argVals[argIndex], cops[argIndex], rfs[argIndex], in->DataType, in->DataSize, regex[argIndex]); + // This check is here b/c BOP has no sensible value when NOPS=1, + // shouldn't base a decision on that. + if (in->NOPS == 1) { + if (cmp == true) + goto count; + else + break; + } + else if (in->BOP == BOP_AND && cmp == false) + break; + else if (in->BOP == BOP_OR && cmp == true) + goto count; + } + if ((argIndex == in->NOPS && in->BOP == BOP_AND) || in->NOPS == 0) { +count: + if (val != 0) + { + if (in->DataSize == 8) + do_sum8(out, val); + else + out->Sum += val; + } + + if (!isEmpty && !isNull) + { + if ( (in->DataType == WriteEngine::CHAR || in->DataType == WriteEngine::VARCHAR ) && 1 < in->DataSize ) + { + if (colCompare(out->Min, val, COMPARE_GT, false, in->DataType, in->DataSize, placeholderRegex)) + out->Min = val; + if (colCompare(out->Max, val, COMPARE_LT, false, in->DataType, in->DataSize, placeholderRegex)) + out->Max = val; + } + else + { + if (out->Min > val) + out->Min = val; + if (out->Max < val) + out->Max = val; + } + + } + out->NVALS++; + } + } +} + +boost::shared_ptr PrimitiveProcessor::parseColumnFilter + (const uint8_t *filterString, uint colWidth, uint colType, uint filterCount, + uint BOP) { boost::shared_ptr ret; - uint32_t argIndex; + uint argIndex; const ColArgs *args; bool convertToSet = true; @@ -1324,7 +1343,7 @@ boost::shared_ptr parseColumnFilter } */ - const uint8_t filterSize = sizeof(uint8_t) + sizeof(uint8_t) + colWidth; + const uint8_t filterSize = sizeof(uint8_t) + sizeof(uint8_t) + colWidth; /* Decide which structure to use. I think the only cases where we can use the set are when NOPS > 1, BOP is OR, and every COP is ==, @@ -1343,39 +1362,17 @@ boost::shared_ptr parseColumnFilter ret->prestored_cops[argIndex] = args->COP; ret->prestored_rfs[argIndex] = args->rf; if ((BOP == BOP_OR && args->COP != COMPARE_EQ) || - (BOP == BOP_AND && args->COP != COMPARE_NE) || - (args->COP == COMPARE_NIL)) + (BOP == BOP_AND && args->COP != COMPARE_NE) || + (args->COP == COMPARE_NIL)) convertToSet = false; - if (isUnsigned((CalpontSystemCatalog::ColDataType)colType)) - { - switch (colWidth) { - case 1: - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); - break; - case 2: - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); - break; - case 4: - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); - break; - case 8: - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); - break; - } - } - else - { - switch (colWidth) { - case 1: - ret->prestored_argVals[argIndex] = args->val[0]; - break; - case 2: - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); - break; + switch (colWidth) { + case 1: ret->prestored_argVals[argIndex] = args->val[0]; break; + case 2: ret->prestored_argVals[argIndex] = + *reinterpret_cast(args->val); break; case 4: #if 0 - if (colType == CalpontSystemCatalog::FLOAT) { + if (colType == WriteEngine::FLOAT) { double dTmp; dTmp = (double) *((const float *) args->val); @@ -1385,22 +1382,22 @@ boost::shared_ptr parseColumnFilter ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); #else - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); + ret->prestored_argVals[argIndex] = + *reinterpret_cast(args->val); #endif break; - case 8: - ret->prestored_argVals[argIndex] = *reinterpret_cast(args->val); + case 8: ret->prestored_argVals[argIndex] = + *reinterpret_cast(args->val); break; - } } // cout << "inserted* " << hex << ret->prestored_argVals[argIndex] << dec << // " COP = " << (int) ret->prestored_cops[argIndex] << endl; if (COMPARE_LIKE & args->COP) { - p_DataValue dv = convertToPDataValue(&ret->prestored_argVals[argIndex], colWidth); + PrimitiveProcessor::p_DataValue dv = convertToPDataValue(&ret->prestored_argVals[argIndex], colWidth); int err = PrimitiveProcessor::convertToRegexp(&ret->prestored_regex[argIndex], &dv); - if (err) + if (err) { throw runtime_error("PrimitiveProcessor::parseColumnFilter(): Could not create regular expression for LIKE operator"); } @@ -1424,6 +1421,11 @@ boost::shared_ptr parseColumnFilter return ret; } +void PrimitiveProcessor::setParsedColumnFilter(boost::shared_ptr pcf) +{ + parsedColumnFilter = pcf; +} + } // namespace primitives // vim:ts=4 sw=4: diff --git a/primitives/linux-port/dictionary.cpp b/primitives/linux-port/dictionary.cpp index 3e00634a..a7c3eda3 100644 --- a/primitives/linux-port/dictionary.cpp +++ b/primitives/linux-port/dictionary.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: dictionary.cpp 2122 2013-07-08 16:33:50Z bpaul $ + * $Id: dictionary.cpp 2124 2013-07-08 19:47:42Z bpaul $ */ #include @@ -91,27 +91,27 @@ void PrimitiveProcessor::p_TokenByScan(const TokenByScanRequestHeader *h, boost::shared_ptr eqFilter) { const DataValue *args; - const uint8_t *niceBlock; // block cast to a byte-indexed type - const uint8_t *niceInput; // h cast to a byte-indexed type - const uint16_t *offsets; + const u_int8_t *niceBlock; // block cast to a byte-indexed type + const u_int8_t *niceInput; // h cast to a byte-indexed type + const u_int16_t *offsets; int offsetIndex, argIndex, argsOffset; bool cmpResult=false; int tmp, i, err; const char *sig; - uint16_t siglen; + u_int16_t siglen; PrimToken *retTokens; DataValue *retDataValues; int rdvOffset; - uint8_t *niceRet; // ret cast to a byte-indexed type + u_int8_t *niceRet; // ret cast to a byte-indexed type boost::scoped_array regex; // set up pointers to fields within each structure // either retTokens or retDataValues will be used but not both. - niceRet = reinterpret_cast(ret); + niceRet = reinterpret_cast(ret); rdvOffset = sizeof(TokenByScanResultHeader); retTokens = reinterpret_cast(&niceRet[rdvOffset]); @@ -125,9 +125,9 @@ void PrimitiveProcessor::p_TokenByScan(const TokenByScanRequestHeader *h, ret->CacheIO = 0; ret->PhysicalIO = 0; - niceBlock = reinterpret_cast(block); - offsets = reinterpret_cast(&niceBlock[10]); - niceInput = reinterpret_cast(h); + niceBlock = reinterpret_cast(block); + offsets = reinterpret_cast(&niceBlock[10]); + niceInput = reinterpret_cast(h); // if LIKE is an operator, compile regexp's in advance. if ((h->NVALS > 0 && h->COP1 & COMPARE_LIKE) || @@ -380,9 +380,9 @@ void PrimitiveProcessor::nextSig(int NVALS, uint8_t outputFlags, bool oldGetSigBehavior, bool skipNulls) throw() { - const uint8_t* niceBlock = reinterpret_cast(block); - const uint16_t *offsets - = reinterpret_cast(&niceBlock[10]); + const u_int8_t* niceBlock = reinterpret_cast(block); + const u_int16_t *offsets + = reinterpret_cast(&niceBlock[10]); if (NVALS == 0) { if (offsets[dict_OffsetIndex + 1] == 0xffff) { @@ -427,7 +427,7 @@ void PrimitiveProcessor::nextSig(int NVALS, //@Bug 2534. Change the length check to 8000 if (ret->len < 0 || ret->len > 8001) { - ret->data = reinterpret_cast(signatureNotFound); + ret->data = reinterpret_cast(signatureNotFound); ret->len = strlen(reinterpret_cast(ret->data)); } else @@ -444,7 +444,7 @@ void PrimitiveProcessor::nextSig(int NVALS, ret->data = &niceBlock[tokens[dict_OffsetIndex].offset]; if (outputFlags & OT_TOKEN) { - //offsets = reinterpret_cast(&niceBlock[10]); + //offsets = reinterpret_cast(&niceBlock[10]); for (currentOffsetIndex = 1; offsets[currentOffsetIndex] != 0xffff; currentOffsetIndex++) if (tokens[dict_OffsetIndex].offset == offsets[currentOffsetIndex]) break; @@ -471,7 +471,7 @@ void PrimitiveProcessor::p_AggregateSignature(const AggregateSignatureRequestHea AggregateSignatureResultHeader *out, unsigned outSize, unsigned *written, bool utf8) { - uint8_t *niceOutput; // h cast to a byte-indexed type + u_int8_t *niceOutput; // h cast to a byte-indexed type int cmp; char cMin[BLOCK_SIZE], cMax[BLOCK_SIZE]; int cMinLen, cMaxLen; @@ -482,7 +482,7 @@ void PrimitiveProcessor::p_AggregateSignature(const AggregateSignatureRequestHea memcpy(out, in, sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); out->ism.Command = DICT_AGGREGATE_RESULTS; - niceOutput = reinterpret_cast(out); + niceOutput = reinterpret_cast(out); // The first sig is the min and the max. out->Count = 0; @@ -652,10 +652,10 @@ bool PrimitiveProcessor::isLike(const p_DataValue *dict, const idb_regex_t *rege } boost::shared_array -PrimitiveProcessor::makeLikeFilter (const DictFilterElement *filterString, uint32_t count) +PrimitiveProcessor::makeLikeFilter (const DictFilterElement *filterString, uint count) { boost::shared_array ret; - uint32_t filterIndex, filterOffset; + uint filterIndex, filterOffset; uint8_t *in8 = (uint8_t *) filterString; const DictFilterElement *filter; p_DataValue filterptr = {0, NULL}; @@ -681,7 +681,7 @@ void PrimitiveProcessor::p_Dictionary(const DictInput *in, vector *out, { PrimToken *outToken; const DictFilterElement *filter=0; - const uint8_t* in8; + const u_int8_t *block8, *in8; DataValue *outValue; p_DataValue min={0, NULL}, max={0, NULL}, sigptr={0, NULL}; int tmp, filterIndex, filterOffset; @@ -696,7 +696,8 @@ void PrimitiveProcessor::p_Dictionary(const DictInput *in, vector *out, const int SCALE_FACTOR = 2; out->resize(DEF_OUTSIZE); - in8 = reinterpret_cast(in); + block8 = reinterpret_cast(block); + in8 = reinterpret_cast(in); memcpy(&header, in, sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); header.ism.Command = DICT_RESULTS; @@ -810,7 +811,7 @@ void PrimitiveProcessor::p_Dictionary(const DictInput *in, vector *out, header.NVALS++; if (in->OutputType & OT_RID && in->InputFlags == 1) { // hack that indicates old GetSignature behavior const OldGetSigParams *oldParams; - uint64_t *outRid; + u_int64_t *outRid; oldParams = reinterpret_cast(in->tokens); uint32_t newlen = header.NBYTES + 8; if( newlen > out->size() ) diff --git a/primitives/linux-port/index.cpp b/primitives/linux-port/index.cpp index dd9b9292..6b436599 100644 --- a/primitives/linux-port/index.cpp +++ b/primitives/linux-port/index.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: index.cpp 2035 2013-01-21 14:12:19Z rdempsey $ + * $Id: index.cpp 1855 2012-04-04 18:20:09Z rdempsey $ * ****************************************************************************/ @@ -61,7 +61,7 @@ using namespace logging; #endif #define IDXWALK_INIT() \ - niceBlock = reinterpret_cast(block); \ + niceBlock = reinterpret_cast(block); \ blockOffset = (in->SubBlock * WriteEngine::SUBBLOCK_TOTAL_BYTES) + \ (in->SBEntry * 8); \ treePtr = reinterpret_cast(&niceBlock[blockOffset]); @@ -181,8 +181,8 @@ namespace primitives void PrimitiveProcessor::indexWalk_1(const IndexWalkHeader *in, vector *out) throw() { - uint16_t bitTest; - uint8_t *niceBlock; + u_int16_t bitTest; + u_int8_t *niceBlock; int blockOffset, bitTestGroupSize, i; WriteEngine::IdxBitTestEntry *treePtr; IndexWalkHeader *element; @@ -241,6 +241,7 @@ void PrimitiveProcessor::indexWalk_1(const IndexWalkHeader *in, // This is the general case where we're working within a bit test group else { GET_GROUP_SIZE(); + #ifdef VERBOSE cerr << " search string is 0x" << hex << in->SearchString[0] << dec << endl; #endif @@ -322,8 +323,8 @@ inline int PrimitiveProcessor::compare(int val1, int val2, uint8_t COP, void PrimitiveProcessor::indexWalk_2(const IndexWalkHeader *in, vector *out) throw() { - uint16_t bitTest1, bitTest2; - uint8_t *niceBlock; + u_int16_t bitTest1, bitTest2; + u_int8_t *niceBlock; int blockOffset, bitTestGroupSize, cmp[2], i; WriteEngine::IdxBitTestEntry *treePtr; IndexWalkHeader *element; @@ -519,8 +520,8 @@ skip3: ; void PrimitiveProcessor::indexWalk_many(const IndexWalkHeader *in, vector *out) throw() { - uint16_t bitTest; - uint8_t *niceBlock; + u_int16_t bitTest; + u_int8_t *niceBlock; int blockOffset, bitTestGroupSize, i; WriteEngine::IdxBitTestEntry *treePtr; IndexWalkHeader *element; @@ -766,7 +767,7 @@ void PrimitiveProcessor::indexWalk_many(const IndexWalkHeader *in, void PrimitiveProcessor::grabSubTree(const IndexWalkHeader *in, vector *out) throw() { - uint8_t *niceBlock; + u_int8_t *niceBlock; int blockOffset, bitTestGroupSize, i; WriteEngine::IdxBitTestEntry *treePtr; IndexWalkHeader *element; @@ -833,7 +834,7 @@ void PrimitiveProcessor::p_IdxWalk(const IndexWalkHeader *in, void PrimitiveProcessor::p_IdxList(const IndexListHeader *rqst, IndexListHeader *rslt, int mode) { - uint8_t *listPtr; + u_int8_t *listPtr; IndexListParam *linkList; IndexListEntry *listEntry, *rsltList, *sizeEntry=0; int listOfst, listType, ridCt, i, j, originalRidCt; @@ -849,7 +850,7 @@ void PrimitiveProcessor::p_IdxList(const IndexListHeader *rqst, rslt->ism.Command = INDEX_LIST_RESULTS; rslt->NVALS = 0; - listPtr = (uint8_t *)block; + listPtr = (u_int8_t *)block; linkList = (IndexListParam *)(rqst + 1); rsltList = (IndexListEntry *)(rslt + 1); @@ -879,7 +880,7 @@ void PrimitiveProcessor::p_IdxList(const IndexListHeader *rqst, ridCt = listEntry->value; originalRidCt = ridCt; #ifdef VERBOSE - uint64_t *tmp = (uint64_t *) &listEntry[1]; + u_int64_t *tmp = (u_int64_t *) &listEntry[1]; cerr << " ridCount=" << ridCt << " key value=0x" << hex << *tmp << dec << endl; #endif diff --git a/primitives/linux-port/primitiveprocessor.cpp b/primitives/linux-port/primitiveprocessor.cpp index 722fd563..8b1c856f 100644 --- a/primitives/linux-port/primitiveprocessor.cpp +++ b/primitives/linux-port/primitiveprocessor.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: primitiveprocessor.cpp 2035 2013-01-21 14:12:19Z rdempsey $ + * $Id: primitiveprocessor.cpp 1855 2012-04-04 18:20:09Z rdempsey $ * ****************************************************************************/ @@ -52,9 +52,9 @@ PrimitiveProcessor::~PrimitiveProcessor() } -void PrimitiveProcessor::setParsedColumnFilter(boost::shared_ptr pcf) +void PrimitiveProcessor::setBlockPtr(int *data) { - parsedColumnFilter = pcf; + block = data; } ParsedColumnFilter::ParsedColumnFilter() : columnFilterMode(STANDARD), likeOps(0) diff --git a/primitives/linux-port/primitiveprocessor.h b/primitives/linux-port/primitiveprocessor.h index 8553cecd..7dc4bd6f 100644 --- a/primitives/linux-port/primitiveprocessor.h +++ b/primitives/linux-port/primitiveprocessor.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************** - * $Id: primitiveprocessor.h 2035 2013-01-21 14:12:19Z rdempsey $ + * $Id: primitiveprocessor.h 1855 2012-04-04 18:20:09Z rdempsey $ * *****************************************************************************/ @@ -114,15 +114,6 @@ struct ParsedColumnFilter { ~ParsedColumnFilter(); }; -//@bug 1828 These need to be public so that column operations can use it for 'like' -struct p_DataValue { - int len; - const uint8_t *data; -}; - -boost::shared_ptr parseColumnFilter(const uint8_t *filterString, - uint32_t colWidth, uint32_t colType, uint32_t filterCount, uint32_t BOP); - /** @brief This class encapsulates the primitive processing functionality of the system. * * This class encapsulates the primitive processing functionality of the system. @@ -134,28 +125,25 @@ class PrimitiveProcessor virtual ~PrimitiveProcessor(); /** @brief Sets the block to operate on - * + * * The primitive processing functions operate on one block at a time. The caller * sets which block to operate on next with this function. */ - void setBlockPtr(int *data) - { - block = data; - } + void setBlockPtr(int *data); void setPMStatsPtr(dbbc::Stats* p) { - fStatsPtr=p; + fStatsPtr=p; } /** @brief The interface to Mark's NIOS primitive processing code. - * + * * The interface to Mark's NIOS primitive processing code. Instead of reading * and writing to a bus, it will read/write to buffers specified by inBuf * and outBuf. The primitives implemented this way are: * - p_Col and p_ColAggregate * - p_GetSignature - * + * * @param inBuf (in) The buffer containing a command to execute * @param inLength (in) The size of inBuf in 4-byte words * @param outBuf (in) The buffer to store the output in @@ -163,13 +151,13 @@ class PrimitiveProcessor * @param written (out) The number of bytes written to outBuf. * @note Throws logic_error if the output buffer is too small for the result. */ - void processBuffer(int *inBuf, unsigned inLength, int *outBuf, unsigned outLength, + void processBuffer(int *inBuf, unsigned inLength, int *outBuf, unsigned outLength, unsigned *written); - + /* Patrick */ /** @brief The p_TokenByScan primitive processor - * + * * The p_TokenByScan primitive processor. It relies on the caller setting * the block to operate on with setBlockPtr(). It assumes the continuation * pointer is not used. @@ -178,21 +166,21 @@ class PrimitiveProcessor * @param outSize (in) The size of the output buffer in bytes. * @note Throws logic_error if the output buffer is too small for the result. */ - void p_TokenByScan(const TokenByScanRequestHeader *t, + void p_TokenByScan(const TokenByScanRequestHeader *t, TokenByScanResultHeader *out, unsigned outSize,bool utf8, boost::shared_ptr eqFilter); /** @brief The p_IdxWalk primitive processor - * + * * The p_IdxWalk primitive processor. The caller must set the block to operate - * on with setBlockPtr(). This primitive can return intermediate results. + * on with setBlockPtr(). This primitive can return intermediate results. * All results returned will have an different LBID than the input. They can - * also be in varying states of completion. A result is final when + * also be in varying states of completion. A result is final when * Shift >= SSlen, otherwise it is intermediate and needs to be reissued with - * the specified LBID loaded. + * the specified LBID loaded. * @note If in->NVALS > 2, new vectors may be returned in the result set, which - * will have to be deleted by the caller. The test to use right now is - * ({element}->NVALS > 2 && {element}->State == 0). If that condition is true, + * will have to be deleted by the caller. The test to use right now is + * ({element}->NVALS > 2 && {element}->State == 0). If that condition is true, * delete the vector, otherwise don't. This kludginess is for efficiency's sake * and may go away for the sake of sanity later. * @note It is safe to delete any vector passed in after the call. @@ -202,14 +190,14 @@ class PrimitiveProcessor void p_IdxWalk(const IndexWalkHeader *in, std::vector *out) throw(); /** @brief The p_IdxList primitive processor. - * + * * The p_IdxList primitive processor. The caller must set the block to operate * on with setBlockPtr(). This primitive can return one intermediate result * for every call made. If there is an intermediate result returned, it will * be the first element, distinguished by its type field. If the * first element has a type == RID (3) , there is no intermediate result. If * the first element had a type == LLP_SUBBLK (4) or type == LLP_BLK (5), - * that element is the intermediate result. Its value field will be a pointer + * that element is the intermediate result. Its value field will be a pointer * to the next section of the list. * * @param rqst (in) The request header followed by NVALS IndexWalkParams @@ -220,26 +208,26 @@ class PrimitiveProcessor * be a pointer). 1 specifies new behavior (the last entry should be ignored). */ void p_IdxList(const IndexListHeader *rqst, IndexListHeader *rslt, int mode = 1); - + /** @brief The p_AggregateSignature primitive processor. - * + * * The p_AggregateSignature primitive processor. It operates on a dictionary * block and assumes the continuation pointer is not used. * @param in The input parameters * @param out A pointer to a buffer where the result will be written. * @param outSize The size of the output buffer in bytes. - * @param written (out parameter) A pointer to 1 int, which will contain the + * @param written (out parameter) A pointer to 1 int, which will contain the * number of bytes written to out. */ - void p_AggregateSignature(const AggregateSignatureRequestHeader *in, + void p_AggregateSignature(const AggregateSignatureRequestHeader *in, AggregateSignatureResultHeader *out, unsigned outSize, unsigned *written, bool utf8); /** @brief The p_Col primitive processor. - * + * * The p_Col primitive processor. It operates on a column block specified using setBlockPtr(). * @param in The buffer containing the command parameters. * The buffer should begin with a NewColRequestHeader structure, followed by - * an array of 'NOPS' defining the filter to apply (optional), + * an array of 'NOPS' defining the filter to apply (optional), * followed by an array of RIDs to apply the filter to (optional). * @param out The buffer that will contain the results. On return, it will start with * a NewColResultHeader, followed by the output type specified by in->OutputType. @@ -247,29 +235,29 @@ class PrimitiveProcessor * \li If OT_DATAVALUE, it will be an array of matching data values stored in the column * \li If OT_BOTH, it will be an array of pairs * @param outSize The size of the output buffer in bytes. - * @param written (out parameter) A pointer to 1 int, which will contain the + * @param written (out parameter) A pointer to 1 int, which will contain the * number of bytes written to out. * @note See PrimitiveMsg.h for the type definitions. */ - void p_Col(NewColRequestHeader *in, NewColResultHeader *out, unsigned outSize, - unsigned *written); + void p_Col(NewColRequestHeader *in, NewColResultHeader *out, unsigned outSize, + unsigned *written, primitiveprocessor::UDFFcnPtr_t fp=0); boost::shared_ptr parseColumnFilter(const uint8_t *filterString, - uint32_t colWidth, uint32_t colType, uint32_t filterCount, uint32_t BOP); + uint colWidth, uint colType, uint filterCount, uint BOP); void setParsedColumnFilter(boost::shared_ptr); /** @brief The p_ColAggregate primitive processor. - * - * The p_ColAggregate primitive processor. It operates on a column block + * + * The p_ColAggregate primitive processor. It operates on a column block * specified using setBlockPtr(). * @param in The buffer containing the command parameters. The buffer should begin * with a NewColAggRequestHeader, followed by an array of RIDs to generate * the data for (optional). - * @param out The buffer to put the result in. On return, it will contain a + * @param out The buffer to put the result in. On return, it will contain a * NewCollAggResultHeader. * @note See PrimitiveMsg.h for the type definitions. */ -// void p_ColAggregate(const NewColAggRequestHeader *in, NewColAggResultHeader *out); + void p_ColAggregate(const NewColAggRequestHeader *in, NewColAggResultHeader *out); void p_Dictionary(const DictInput *in, std::vector *out, bool utf8, bool skipNulls, boost::shared_ptr eqFilter, @@ -277,11 +265,16 @@ class PrimitiveProcessor inline void setLogicalBlockMode(bool b) { logicalBlockMode = b; } - + /* Patrick */ +//@bug 1828 These need to be public so that column operations can use it for 'like' + struct p_DataValue { + int len; + const u_int8_t *data; + }; static int convertToRegexp(idb_regex_t *regex, const p_DataValue *str); inline static bool isEscapedChar(char c); - boost::shared_array makeLikeFilter(const DictFilterElement *inputMsg, uint32_t count); + boost::shared_array makeLikeFilter(const DictFilterElement *inputMsg, uint count); void setLikeFilter(boost::shared_array filter) { parsedLikeFilter = filter; } private: @@ -301,8 +294,7 @@ class PrimitiveProcessor uint8_t outputFlags = 0, bool oldGetSigBehavior = false, bool skipNulls = false) throw(); bool isLike(const p_DataValue *dict, const idb_regex_t *arg) throw(); -// void do_sum8(NewColAggResultHeader *out, int64_t val); -// void do_unsignedsum8(NewColAggResultHeader *out, int64_t val); + void do_sum8(NewColAggResultHeader *out, int64_t val); uint64_t masks[11]; int dict_OffsetIndex, currentOffsetIndex; // used by p_dictionary diff --git a/primitives/linux-port/print_dictblock.cpp b/primitives/linux-port/print_dictblock.cpp index 05af5385..b2abafb4 100644 --- a/primitives/linux-port/print_dictblock.cpp +++ b/primitives/linux-port/print_dictblock.cpp @@ -45,15 +45,15 @@ void usage(char *name) void parseDictBlock(char *block) { - uint16_t *offsets; - uint16_t *freeBytes; + u_int16_t *offsets; + u_int16_t *freeBytes; u_int64_t *contPtr; int offsetIndex, size; char sig[BLOCK_SIZE+1]; - freeBytes = reinterpret_cast(&block[0]); + freeBytes = reinterpret_cast(&block[0]); contPtr = reinterpret_cast(&block[2]); - offsets = reinterpret_cast(&block[10]); + offsets = reinterpret_cast(&block[10]); cout << "Free Bytes: " << *freeBytes << endl; cout << "Continuation Pointer: 0x" << hex << *contPtr << dec << endl; diff --git a/primitives/linux-port/tdriver.cpp b/primitives/linux-port/tdriver.cpp index d322aefa..8f66070a 100644 --- a/primitives/linux-port/tdriver.cpp +++ b/primitives/linux-port/tdriver.cpp @@ -127,6 +127,22 @@ CPPUNIT_TEST(p_Col_neg_float_1); // negative double column test CPPUNIT_TEST(p_Col_neg_double_1); +// whole block tests +CPPUNIT_TEST(p_ColAggregate_1); +CPPUNIT_TEST(p_ColAggregate_2); +CPPUNIT_TEST(p_ColAggregate_3); +CPPUNIT_TEST(p_ColAggregate_4); + +// whole block tests with negative numbers +CPPUNIT_TEST(p_ColAggregate_5); + +// whole block test with sum overflow +CPPUNIT_TEST(p_ColAggregate_6); + +// whole block test with sum overflow and negative numbers +/* XXXPAT: We need new block data for this one b/c of the null values*/ +// CPPUNIT_TEST(p_ColAggregate_7); + // some ports of TokenByScan tests to validate similar & shared code CPPUNIT_TEST(p_Dictionary_1); CPPUNIT_TEST(p_Dictionary_2); @@ -172,7 +188,7 @@ void p_IdxWalk_1_eq_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -229,7 +245,7 @@ void p_IdxWalk_1_lt_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -296,7 +312,7 @@ void p_IdxWalk_1_lte_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -363,7 +379,7 @@ void p_IdxWalk_1_gt_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -430,7 +446,7 @@ void p_IdxWalk_1_gte_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -497,7 +513,7 @@ void p_IdxWalk_1_neq_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -564,7 +580,7 @@ void p_IdxWalk_1_eq_2() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -616,7 +632,7 @@ void p_IdxWalk_2_eq_or_1() char block[BLOCK_SIZE]; u_int64_t searchKey[2]; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -691,7 +707,7 @@ void p_IdxWalk_2_range_1() char block[BLOCK_SIZE]; u_int64_t searchKey[2]; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -766,7 +782,7 @@ void p_IdxWalk_2_range_2() char block[BLOCK_SIZE]; u_int64_t searchKey[2]; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -840,7 +856,7 @@ void p_IdxWalk_2_range_3() char block[BLOCK_SIZE]; u_int64_t searchKey[2]; int fd; - uint32_t err; + uint err; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -914,7 +930,7 @@ void p_IdxWalk_40_eq_or_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err, i; + uint err, i; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -989,7 +1005,7 @@ void p_IdxWalk_40_neq_and_1() char block[BLOCK_SIZE]; u_int64_t searchKey; int fd; - uint32_t err, i; + uint err, i; string filename("FILE_990.dat"); IndexWalkHeader *params; vector results; @@ -1063,14 +1079,14 @@ void p_AggregateSignature_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); AggregateSignatureRequestHeader *cmd; AggregateSignatureResultHeader *results; DataValue *dvPtr; char minmax[BLOCK_SIZE]; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1115,14 +1131,14 @@ void p_AggregateSignature_2() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); AggregateSignatureRequestHeader *cmd; AggregateSignatureResultHeader *results; DataValue *dvPtr; char minmax[BLOCK_SIZE]; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1182,13 +1198,13 @@ void p_AggregateSignature_2() void p_TokenByScan_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1230,13 +1246,13 @@ void p_TokenByScan_1() void p_TokenByScan_2() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1293,13 +1309,13 @@ void p_TokenByScan_2() void p_TokenByScan_3() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1345,13 +1361,13 @@ void p_TokenByScan_3() void p_TokenByScan_gt_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1400,13 +1416,13 @@ void p_TokenByScan_gt_1() void p_TokenByScan_gte_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1455,13 +1471,13 @@ void p_TokenByScan_gte_1() void p_TokenByScan_lt_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1510,13 +1526,13 @@ void p_TokenByScan_lt_1() void p_TokenByScan_lte_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1565,13 +1581,13 @@ void p_TokenByScan_lte_1() void p_TokenByScan_neq_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1620,13 +1636,13 @@ void p_TokenByScan_neq_1() void p_TokenByScan_range_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1684,13 +1700,13 @@ void p_TokenByScan_range_1() void p_TokenByScan_eq_6() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1767,13 +1783,13 @@ void p_TokenByScan_eq_6() void p_TokenByScan_neq_6() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1850,13 +1866,13 @@ void p_TokenByScan_neq_6() void p_TokenByScan_like_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE], tmp[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; int fd, argsOffset, i; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1908,14 +1924,14 @@ void p_TokenByScan_like_1() void p_TokenByScan_token_eq_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); TokenByScanRequestHeader *cmd; TokenByScanResultHeader *results; DataValue *args; PrimToken *result; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -1963,7 +1979,7 @@ void p_IdxList_1() // index list file is 10000 PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], input[BLOCK_SIZE], output[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], input[BLOCK_SIZE], output[BLOCK_SIZE]; string filename("FILE_991.dat"); IndexListHeader *hdr, *resultHdr; IndexListParam *params; @@ -1971,7 +1987,7 @@ void p_IdxList_1() vector bigResults; vector::iterator it; int fd; - uint32_t err, i; + uint err, i; bool continuationPtr; fd = open(filename.c_str(), O_RDONLY); @@ -2063,7 +2079,7 @@ void p_IdxList_2() // index list file is 10000 PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], input[BLOCK_SIZE], output[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], input[BLOCK_SIZE], output[BLOCK_SIZE]; string filename("FILE233.cdf"); IndexListHeader *hdr, *resultHdr; IndexListParam *params; @@ -2071,7 +2087,7 @@ void p_IdxList_2() vector bigResults; vector::iterator it; int fd; - uint32_t err, i; + uint err, i; bool continuationPtr; fd = open(filename.c_str(), O_RDONLY); @@ -2155,19 +2171,19 @@ void p_IdxList_2() for (i = 1, it = bigResults.begin(); it != bigResults.end(); it++, i++) { // cout << " " << i << ": type=" << (*it).type << " rid=" << (*it).value << endl; CPPUNIT_ASSERT((*it).type == RID); - CPPUNIT_ASSERT((*it).value == (uint32_t) i-1); + CPPUNIT_ASSERT((*it).value == (uint) i-1); } } void p_Col_1() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; - uint8_t *results; + u_int8_t *results; int fd; - uint32_t i, written; + uint i, written; string filename("col1block.cdf"); fd = open(filename.c_str(), O_RDONLY); @@ -2195,7 +2211,7 @@ void p_Col_1() out = reinterpret_cast(output); in->DataSize = 1; - in->DataType = CalpontSystemCatalog::CHAR; + in->DataType = WriteEngine::CHAR; in->OutputType = OT_DATAVALUE; in->NOPS = 0; in->NVALS = 0; @@ -2218,11 +2234,11 @@ void p_Col_1() void p_Col_2() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; - uint16_t *results; - uint32_t written, i; + u_int16_t *results; + uint written, i; int fd; string filename("col2block.cdf"); @@ -2251,7 +2267,7 @@ void p_Col_2() out = reinterpret_cast(output); in->DataSize = 2; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 0; in->NVALS = 0; @@ -2260,7 +2276,7 @@ void p_Col_2() pp.setBlockPtr((int*) block); pp.p_Col(in, out, 4*BLOCK_SIZE, &written); - results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); + results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); // cout << "NVALS = " << out->NVALS << endl; CPPUNIT_ASSERT(out->NVALS == 4096); for (i = 0; i < out->NVALS; i++) { @@ -2274,11 +2290,11 @@ void p_Col_2() void p_Col_3() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; - uint32_t *results; - uint32_t written, i; + u_int32_t *results; + uint written, i; int fd; string filename("col4block.cdf"); @@ -2307,7 +2323,7 @@ void p_Col_3() out = reinterpret_cast(output); in->DataSize = 4; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 0; in->NVALS = 0; @@ -2316,12 +2332,12 @@ void p_Col_3() pp.setBlockPtr((int*) block); pp.p_Col(in, out, 4*BLOCK_SIZE, &written); - results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); + results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); // cout << "NVALS = " << out->NVALS << endl; CPPUNIT_ASSERT(out->NVALS == 2048); for (i = 0; i < out->NVALS; i++) { // cout << i << ": " << hex << (int)results[i] << dec << endl; - CPPUNIT_ASSERT(results[i] == (uint32_t) i); + CPPUNIT_ASSERT(results[i] == (uint) i); } close(fd); @@ -2330,11 +2346,11 @@ void p_Col_3() void p_Col_4() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; u_int64_t *results; - uint32_t written, i; + uint written, i; int fd; string filename("col8block.cdf"); @@ -2363,7 +2379,7 @@ void p_Col_4() out = reinterpret_cast(output); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 0; in->NVALS = 0; @@ -2377,7 +2393,7 @@ void p_Col_4() CPPUNIT_ASSERT(out->NVALS == 1024); for (i = 0; i < out->NVALS; i++) { // cout << i << ": " << hex << (int)results[i] << dec << endl; - CPPUNIT_ASSERT(results[i] == (uint32_t) i); + CPPUNIT_ASSERT(results[i] == (uint) i); } close(fd); @@ -2386,12 +2402,12 @@ void p_Col_4() void p_Col_5() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; - uint8_t *results; - uint16_t *rids; - uint32_t written, i; + u_int8_t *results; + u_int16_t *rids; + uint written, i; int fd; string filename("col1block.cdf"); @@ -2418,10 +2434,10 @@ void p_Col_5() in = reinterpret_cast(input); out = reinterpret_cast(output); - rids = reinterpret_cast(&in[1]); + rids = reinterpret_cast(&in[1]); in->DataSize = 1; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 0; in->NVALS = 2; @@ -2432,7 +2448,7 @@ void p_Col_5() pp.setBlockPtr((int*) block); pp.p_Col(in, out, 4*BLOCK_SIZE, &written); - results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); + results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); // cout << "NVALS = " << out->NVALS << endl; CPPUNIT_ASSERT(out->NVALS == 2); for (i = 0; i < out->NVALS; i++) { @@ -2446,12 +2462,12 @@ void p_Col_5() void p_Col_6() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; - uint32_t *results; - uint32_t written, i; + u_int32_t *results; + uint written, i; int fd, tmp; string filename("col4block.cdf"); @@ -2481,7 +2497,7 @@ void p_Col_6() args = reinterpret_cast(&in[1]); in->DataSize = 4; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 2; in->BOP = BOP_AND; @@ -2500,12 +2516,12 @@ void p_Col_6() pp.setBlockPtr((int*) block); pp.p_Col(in, out, 4*BLOCK_SIZE, &written); - results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); + results = reinterpret_cast(&output[sizeof(NewColResultHeader)]); // cout << "NVALS = " << out->NVALS << endl; CPPUNIT_ASSERT(out->NVALS == 9); for (i = 0; i < out->NVALS; i++) { // cout << i << ": " << hex << (int)results[i] << dec << endl; - CPPUNIT_ASSERT(results[i] == 11 + (uint32_t)i); + CPPUNIT_ASSERT(results[i] == 11 + (uint)i); } close(fd); @@ -2514,12 +2530,12 @@ void p_Col_6() void p_Col_7() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; u_int64_t *results; - uint32_t written, i; + uint written, i; int fd; int64_t tmp; string filename("col8block.cdf"); @@ -2550,7 +2566,7 @@ void p_Col_7() args = reinterpret_cast(&input[sizeof(NewColRequestHeader)]); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 2; in->BOP = BOP_OR; @@ -2574,7 +2590,7 @@ void p_Col_7() CPPUNIT_ASSERT(out->NVALS == 33); for (i = 0; i < out->NVALS; i++) { // cout << i << ": " << hex << (int)results[i] << dec << endl; - CPPUNIT_ASSERT(results[i] == (uint32_t) (i < 10 ? i : i - 10 + 1001)); + CPPUNIT_ASSERT(results[i] == (uint) (i < 10 ? i : i - 10 + 1001)); } close(fd); @@ -2583,12 +2599,12 @@ void p_Col_7() void p_Col_8() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; u_int64_t *results; - uint32_t written, i; + uint written, i; int fd; int64_t tmp; string filename("col8block.cdf"); @@ -2619,7 +2635,7 @@ void p_Col_8() args = reinterpret_cast(&input[sizeof(NewColRequestHeader)]); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 2; in->BOP = BOP_OR; @@ -2645,7 +2661,7 @@ void p_Col_8() CPPUNIT_ASSERT(results[1] == 1000); // for (i = 0; i < out->NVALS; i++) { // cout << i << ": " << hex << (int)results[i] << dec << endl; -// CPPUNIT_ASSERT(results[i] == (uint32_t) (i < 10 ? i : i - 10 + 1001)); +// CPPUNIT_ASSERT(results[i] == (uint) (i < 10 ? i : i - 10 + 1001)); // } close(fd); @@ -2654,13 +2670,13 @@ void p_Col_8() void p_Col_9() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; - uint16_t *rids; + u_int16_t *rids; u_int64_t *results; - uint32_t written, i; + uint written, i; int fd; int64_t tmp; string filename("col8block.cdf"); @@ -2691,7 +2707,7 @@ void p_Col_9() args = reinterpret_cast(&input[sizeof(NewColRequestHeader)]); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_DATAVALUE; in->NOPS = 2; in->BOP = BOP_OR; @@ -2707,7 +2723,7 @@ void p_Col_9() tmp = 1000; memcpy(args->val, &tmp, in->DataSize); - rids = reinterpret_cast(&input[sizeof(NewColRequestHeader) + + rids = reinterpret_cast(&input[sizeof(NewColRequestHeader) + 2*(sizeof(ColArgs) + in->DataSize)]); rids[0] = 10; @@ -2722,21 +2738,585 @@ void p_Col_9() CPPUNIT_ASSERT(results[0] == 10); // for (i = 0; i < out->NVALS; i++) { // cout << i << ": " << hex << (int)results[i] << dec << endl; -// CPPUNIT_ASSERT(results[i] == (uint32_t) (i < 10 ? i : i - 10 + 1001)); +// CPPUNIT_ASSERT(results[i] == (uint) (i < 10 ? i : i - 10 + 1001)); // } close(fd); } +void p_ColAggregate_1() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd, sum; + uint8_t j; + string filename("col1block.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_1: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_1: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_1: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_1: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_1: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 1; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + for (sum = 0, i = 0, j = 0; i < 8192; i++, j++) + if (j != 0x81 && j != 0x80) + sum += (int8_t) j; + + CPPUNIT_ASSERT(out->Sum == sum); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == -126); + CPPUNIT_ASSERT(out->Max == 127); + CPPUNIT_ASSERT(out->NVALS == 8128); + + close(fd); +} + +void p_ColAggregate_2() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd, sum; + string filename("col2block.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_2: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_2: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_2: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_2: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_2: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 2; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + for (sum = 0, i = 0; i < 4096; i++) + sum += i; + + CPPUNIT_ASSERT(out->Sum == sum); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == 0); + CPPUNIT_ASSERT(out->Max == 4095); + CPPUNIT_ASSERT(out->NVALS == 4096); + + close(fd); +} + +void p_ColAggregate_3() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd, sum; + string filename("col4block.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_3: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_3: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_3: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_3: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_3: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 4; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << (int) out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + for (sum = 0, i = 0; i < 2048; i++) + sum += i; + + CPPUNIT_ASSERT(out->Sum == sum); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == 0); + CPPUNIT_ASSERT(out->Max == 2047); + CPPUNIT_ASSERT(out->NVALS == 2048); + + close(fd); +} + +void p_ColAggregate_4() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd, sum; + string filename("col8block.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_4: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_4: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_4: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_4: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_4: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 8; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << (int) out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + for (sum = 0, i = 0; i < 1024; i++) + sum += i; + + CPPUNIT_ASSERT(out->Sum == sum); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == 0); + CPPUNIT_ASSERT(out->Max == 1023); + CPPUNIT_ASSERT(out->NVALS == 1024); + + close(fd); +} + +void p_ColAggregate_5() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd; + string filename("col8block_neg.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_5: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_5: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_5: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_5: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_5: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 8; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << (int) out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + CPPUNIT_ASSERT(out->Sum == 512); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 1); + CPPUNIT_ASSERT(out->Min == -512); + CPPUNIT_ASSERT(out->Max == 511); + CPPUNIT_ASSERT(out->NVALS == 1024); + + close(fd); +} + +void p_ColAggregate_6() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd; + string filename("col8block_overflow.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_6: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_6: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_6: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_6: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_6: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 8; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << (int) out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + /* These numbers were verified using 'bc' */ + CPPUNIT_ASSERT(out->Sum == 9223372036854774784LL); + CPPUNIT_ASSERT(out->SumOverflow == 1023); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == 9223372036854775807LL); + CPPUNIT_ASSERT(out->Max == 9223372036854775807LL); + CPPUNIT_ASSERT(out->NVALS == 1024); + + close(fd); +} + +void p_ColAggregate_7() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd; + string filename("col8block_overflow_neg.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_7: skipping this test; needs the index list file " + << filename << endl; +// throw runtime_error("p_Col_1: file not found..."); + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_7: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_7: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_7: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_7: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 8; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << (int) out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + /* These numbers were verified using 'bc' */ +// CPPUNIT_ASSERT(out->Sum == 401); +// CPPUNIT_ASSERT(out->SumOverflow == 222); +// CPPUNIT_ASSERT(out->SumSign == 1); +// CPPUNIT_ASSERT(out->Min == -9223372036854775808LL); +// CPPUNIT_ASSERT(out->Max == 9223372036854775807LL); +// CPPUNIT_ASSERT(out->NVALS == 1024); + + close(fd); +} + +void p_ColAggregate_8() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i, j; + int fd, sum; + string filename("col1block.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_8: skipping this test; needs the index list file " + << filename << endl; + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_8: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_8: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_8: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_8: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 1; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + +/* + typedef struct + { + ISMPacketHeader ism; + PrimitiveHeader hdr; + Int64 LBID; + Int64 PBID; + Int8 DataSize; + Int8 DataType; + Int8 OutputType; + Int8 BOP; + Int8 ExtraNotUsed; + Int16 NOPS; + Int16 NVALS; + // this follows the header + // ColArgs ArgList[NOPS] (where the val field is DataSize bytes long) + // Int16 Rids[NVALS] (each rid is relative to the given block) + } NewColAggRequestHeader; +*/ + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + for (sum = 0, i = 0, j = 0; i < 8192; i++, j = i % 256) + if (j != 129) + sum += j; + + CPPUNIT_ASSERT(out->Sum == sum); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == 0); + CPPUNIT_ASSERT(out->Max == 255); + CPPUNIT_ASSERT(out->NVALS == 8160); + + close(fd); +} + +void p_ColAggregate_9() +{ + PrimitiveProcessor pp; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + NewColAggRequestHeader *in; + NewColAggResultHeader *out; + uint i; + int fd, sum; + string filename("col2block.cdf"); + + fd = open(filename.c_str(), O_RDONLY); + if (fd < 0) { + cerr << "p_ColAggregate_9: skipping this test; needs the index list file " + << filename << endl; + return; + } + + i = read(fd, block, BLOCK_SIZE); + if (i <= 0) { + cerr << "p_ColAggregate_9: Couldn't read the file " << filename << endl; + throw runtime_error("p_ColAggregate_9: Couldn't read the file"); + } + if (i != BLOCK_SIZE) { + cerr << "p_ColAggregate_9: could not read a whole block" << endl; + throw runtime_error("p_ColAggregate_9: could not read a whole block"); + } + + memset(input, 0, BLOCK_SIZE); + memset(output, 0, 4*BLOCK_SIZE); + + in = reinterpret_cast(input); + out = reinterpret_cast(output); + + in->DataSize = 2; + in->DataType = WriteEngine::INT; + in->NVALS = 0; + + pp.setBlockPtr((int*) block); + pp.p_ColAggregate(in, out); + +// cout << "Sum: " << out->Sum << endl; +// cout << "SumOverflow: " << out->SumOverflow << endl; +// cout << "SumSign: " << out->SumSign << endl; +// cout << "Min: " << out->Min << endl; +// cout << "Max: " << out->Max << endl; +// cout << "NVALS: " << out->NVALS << endl; + + for (sum = 0, i = 0; i < 4096; i++) + sum += i; + + CPPUNIT_ASSERT(out->Sum == sum); + CPPUNIT_ASSERT(out->SumOverflow == 0); + CPPUNIT_ASSERT(out->SumSign == 0); + CPPUNIT_ASSERT(out->Min == 0); + CPPUNIT_ASSERT(out->Max = 4096); + CPPUNIT_ASSERT(out->NVALS == 4096); + + close(fd); +} + void p_Col_10() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; int16_t *results; - uint32_t written, i; + uint written, i; int fd; int64_t tmp; string filename("col8block.cdf"); @@ -2767,7 +3347,7 @@ void p_Col_10() args = reinterpret_cast(&input[sizeof(NewColRequestHeader)]); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_RID; in->NOPS = 2; in->BOP = BOP_OR; @@ -2800,13 +3380,13 @@ void p_Col_10() void p_Col_11() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; int16_t *resultRid; int64_t *resultVal; - uint32_t written, i; + uint written, i; int fd; int64_t tmp; string filename("col8block.cdf"); @@ -2837,7 +3417,7 @@ void p_Col_11() args = reinterpret_cast(&input[sizeof(NewColRequestHeader)]); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_BOTH; in->NOPS = 2; in->BOP = BOP_OR; @@ -2874,12 +3454,12 @@ void p_Col_11() void p_Col_12() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; - uint8_t *results; - uint32_t written, i; + u_int8_t *results; + uint written, i; int fd; string filename("col1block.cdf"); @@ -2908,7 +3488,7 @@ void p_Col_12() out = reinterpret_cast(output); in->DataSize = 1; - in->DataType = CalpontSystemCatalog::CHAR; + in->DataType = WriteEngine::CHAR; in->OutputType = OT_DATAVALUE; in->BOP = BOP_AND; in->NOPS = 2; @@ -2944,12 +3524,12 @@ void p_Col_12() void p_Col_13() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; int16_t *results; - uint32_t written, i; + uint written, i; int fd; int32_t tmp; int16_t ridTmp; @@ -2981,7 +3561,7 @@ void p_Col_13() args = reinterpret_cast(&input[sizeof(NewColRequestHeader)]); in->DataSize = 4; - in->DataType = CalpontSystemCatalog::INT; + in->DataType = WriteEngine::INT; in->OutputType = OT_RID; in->NOPS = 3; in->BOP = BOP_OR; @@ -3030,12 +3610,12 @@ void p_Col_13() void p_Col_double_1() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; double *results; - uint32_t written, i; + uint written, i; int fd; string filename("col_double_block.cdf"); double tmp; @@ -3065,7 +3645,7 @@ void p_Col_double_1() out = reinterpret_cast(output); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::DOUBLE; + in->DataType = WriteEngine::DOUBLE; in->OutputType = OT_DATAVALUE; in->BOP = BOP_AND; in->NOPS = 2; @@ -3098,12 +3678,12 @@ void p_Col_double_1() void p_Col_float_1() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; float *resultVal; - uint32_t written, i; + uint written, i; int fd; string filename("col_float_block.cdf"); float tmp; @@ -3134,7 +3714,7 @@ void p_Col_float_1() out = reinterpret_cast(output); in->DataSize = 4; - in->DataType = CalpontSystemCatalog::FLOAT; + in->DataType = WriteEngine::FLOAT; in->OutputType = OT_BOTH; in->BOP = BOP_AND; in->NOPS = 2; @@ -3171,13 +3751,13 @@ void p_Col_float_1() void p_Col_neg_float_1() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; float *resultVal; int16_t *resultRid; - uint32_t written, i; + uint written, i; int fd; string filename("col_neg_float.cdf"); float tmp; @@ -3207,7 +3787,7 @@ void p_Col_neg_float_1() out = reinterpret_cast(output); in->DataSize = 4; - in->DataType = CalpontSystemCatalog::FLOAT; + in->DataType = WriteEngine::FLOAT; in->OutputType = OT_BOTH; in->BOP = BOP_AND; in->NOPS = 2; @@ -3245,12 +3825,12 @@ void p_Col_neg_float_1() void p_Col_neg_double_1() { PrimitiveProcessor pp; - uint8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; + u_int8_t input[BLOCK_SIZE], output[4*BLOCK_SIZE], block[BLOCK_SIZE]; NewColRequestHeader *in; NewColResultHeader *out; ColArgs *args; double *results; - uint32_t written, i; + uint written, i; int fd; string filename("col_neg_double.cdf"); double tmp; @@ -3280,7 +3860,7 @@ void p_Col_neg_double_1() out = reinterpret_cast(output); in->DataSize = 8; - in->DataType = CalpontSystemCatalog::DOUBLE; + in->DataType = WriteEngine::DOUBLE; in->OutputType = OT_DATAVALUE; in->BOP = BOP_AND; in->NOPS = 2; @@ -3313,14 +3893,14 @@ void p_Col_neg_double_1() void p_Dictionary_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -3365,14 +3945,14 @@ void p_Dictionary_1() void p_Dictionary_2() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -3426,14 +4006,14 @@ void p_Dictionary_2() void p_Dictionary_3() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -3482,14 +4062,14 @@ void p_Dictionary_3() void p_Dictionary_gt_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -3541,14 +4121,14 @@ void p_Dictionary_gt_1() void p_Dictionary_token_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; PrimToken *outToken; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -3604,14 +4184,14 @@ void p_Dictionary_token_1() void p_Dictionary_inputArg_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -3668,7 +4248,7 @@ void p_Dictionary_inputArg_1() void p_Dictionary_token_agg_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; @@ -3677,7 +4257,7 @@ void p_Dictionary_token_agg_1() DictAggregate *agg; DataValue *outValue; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -3746,7 +4326,7 @@ void p_Dictionary_token_agg_1() void p_Dictionary_inToken_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; @@ -3755,7 +4335,7 @@ void p_Dictionary_inToken_1() PrimToken *outToken; DataValue *outValue; int fd; - uint32_t err; + uint err; fd = open(filename.c_str(), O_RDONLY); if (fd < 0) { @@ -3834,7 +4414,7 @@ void p_Dictionary_inToken_1() void p_Dictionary_oldgetsig_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; @@ -3852,7 +4432,7 @@ void p_Dictionary_oldgetsig_1() } *oldResults; int fd, argsOffset; - uint32_t err; + uint err; // char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -3918,14 +4498,14 @@ void p_Dictionary_oldgetsig_1() void p_Dictionary_like_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -3981,14 +4561,14 @@ void p_Dictionary_like_1() void p_Dictionary_like_2() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4044,14 +4624,14 @@ void p_Dictionary_like_2() void p_Dictionary_like_3() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4103,14 +4683,14 @@ void p_Dictionary_like_3() void p_Dictionary_like_4() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4162,14 +4742,14 @@ void p_Dictionary_like_4() void p_Dictionary_like_5() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4225,14 +4805,14 @@ void p_Dictionary_like_5() void p_Dictionary_like_6() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4288,14 +4868,14 @@ void p_Dictionary_like_6() void p_Dictionary_like_7() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4348,14 +4928,14 @@ void p_Dictionary_like_7() void p_Dictionary_like_8() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; DataValue *outValue; int fd, argsOffset; - uint32_t err, i; + uint err, i; char tmp[BLOCK_SIZE]; fd = open(filename.c_str(), O_RDONLY); @@ -4411,13 +4991,13 @@ void p_Dictionary_like_8() void p_Dictionary_like_prefixbench_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; int fd; - uint32_t err; + uint err; uint64_t count; fd = open(filename.c_str(), O_RDONLY); @@ -4466,13 +5046,13 @@ void p_Dictionary_like_prefixbench_1() void p_Dictionary_like_substrbench_1() { PrimitiveProcessor pp; - uint8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; + u_int8_t block[BLOCK_SIZE], output[BLOCK_SIZE], input[BLOCK_SIZE]; string filename("dictblock.cdf"); DictInput *cmd; DictOutput *results; DictFilterElement *args; int fd; - uint32_t err; + uint err; uint64_t count; fd = open(filename.c_str(), O_RDONLY); diff --git a/primitives/primproc/Makefile.am b/primitives/primproc/Makefile.am index 885ac47b..44adec8e 100644 --- a/primitives/primproc/Makefile.am +++ b/primitives/primproc/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -32,11 +32,12 @@ PrimProc_SOURCES = primproc.cpp \ dictstep.cpp \ filtercommand.cpp \ logger.cpp \ + monitorprocmem.cpp \ passthrucommand.cpp \ primitiveserver.cpp \ - pseudocc.cpp \ rtscommand.cpp \ - umsocketselector.cpp + umsocketselector.cpp \ + udf.cpp PrimProc_CPPFLAGS = -I../blockcache -I../linux-port $(AM_CPPFLAGS) PrimProc_CXXFLAGS = $(march_flags) $(AM_CXXFLAGS) PrimProc_LDFLAGS = $(idb_common_ldflags) $(idb_write_libs) $(idb_common_libs) -lthreadpool -lcacheutils $(netsnmp_libs) $(AM_LDFLAGS) diff --git a/primitives/primproc/Makefile.in b/primitives/primproc/Makefile.in index 0e4d64d9..6ab369f2 100644 --- a/primitives/primproc/Makefile.in +++ b/primitives/primproc/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = PrimProc$(EXEEXT) subdir = primitives/primproc DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -75,10 +74,11 @@ am_PrimProc_OBJECTS = PrimProc-primproc.$(OBJEXT) \ PrimProc-bppseeder.$(OBJEXT) PrimProc-bppsendthread.$(OBJEXT) \ PrimProc-columncommand.$(OBJEXT) PrimProc-command.$(OBJEXT) \ PrimProc-dictstep.$(OBJEXT) PrimProc-filtercommand.$(OBJEXT) \ - PrimProc-logger.$(OBJEXT) PrimProc-passthrucommand.$(OBJEXT) \ - PrimProc-primitiveserver.$(OBJEXT) PrimProc-pseudocc.$(OBJEXT) \ + PrimProc-logger.$(OBJEXT) PrimProc-monitorprocmem.$(OBJEXT) \ + PrimProc-passthrucommand.$(OBJEXT) \ + PrimProc-primitiveserver.$(OBJEXT) \ PrimProc-rtscommand.$(OBJEXT) \ - PrimProc-umsocketselector.$(OBJEXT) + PrimProc-umsocketselector.$(OBJEXT) PrimProc-udf.$(OBJEXT) PrimProc_OBJECTS = $(am_PrimProc_OBJECTS) PrimProc_DEPENDENCIES = ../blockcache/libdbbc.a \ ../linux-port/libprocessor.a @@ -157,9 +157,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -201,7 +198,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -215,11 +211,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -243,11 +234,12 @@ PrimProc_SOURCES = primproc.cpp \ dictstep.cpp \ filtercommand.cpp \ logger.cpp \ + monitorprocmem.cpp \ passthrucommand.cpp \ primitiveserver.cpp \ - pseudocc.cpp \ rtscommand.cpp \ - umsocketselector.cpp + umsocketselector.cpp \ + udf.cpp PrimProc_CPPFLAGS = -I../blockcache -I../linux-port $(AM_CPPFLAGS) PrimProc_CXXFLAGS = $(march_flags) $(AM_CXXFLAGS) @@ -332,11 +324,12 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-dictstep.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-filtercommand.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-logger.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-monitorprocmem.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-passthrucommand.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-primitiveserver.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-primproc.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-pseudocc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-rtscommand.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-udf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/PrimProc-umsocketselector.Po@am__quote@ .cpp.o: @@ -486,6 +479,20 @@ PrimProc-logger.obj: logger.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-logger.obj `if test -f 'logger.cpp'; then $(CYGPATH_W) 'logger.cpp'; else $(CYGPATH_W) '$(srcdir)/logger.cpp'; fi` +PrimProc-monitorprocmem.o: monitorprocmem.cpp +@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-monitorprocmem.o -MD -MP -MF "$(DEPDIR)/PrimProc-monitorprocmem.Tpo" -c -o PrimProc-monitorprocmem.o `test -f 'monitorprocmem.cpp' || echo '$(srcdir)/'`monitorprocmem.cpp; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-monitorprocmem.Tpo" "$(DEPDIR)/PrimProc-monitorprocmem.Po"; else rm -f "$(DEPDIR)/PrimProc-monitorprocmem.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='monitorprocmem.cpp' object='PrimProc-monitorprocmem.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-monitorprocmem.o `test -f 'monitorprocmem.cpp' || echo '$(srcdir)/'`monitorprocmem.cpp + +PrimProc-monitorprocmem.obj: monitorprocmem.cpp +@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-monitorprocmem.obj -MD -MP -MF "$(DEPDIR)/PrimProc-monitorprocmem.Tpo" -c -o PrimProc-monitorprocmem.obj `if test -f 'monitorprocmem.cpp'; then $(CYGPATH_W) 'monitorprocmem.cpp'; else $(CYGPATH_W) '$(srcdir)/monitorprocmem.cpp'; fi`; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-monitorprocmem.Tpo" "$(DEPDIR)/PrimProc-monitorprocmem.Po"; else rm -f "$(DEPDIR)/PrimProc-monitorprocmem.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='monitorprocmem.cpp' object='PrimProc-monitorprocmem.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-monitorprocmem.obj `if test -f 'monitorprocmem.cpp'; then $(CYGPATH_W) 'monitorprocmem.cpp'; else $(CYGPATH_W) '$(srcdir)/monitorprocmem.cpp'; fi` + PrimProc-passthrucommand.o: passthrucommand.cpp @am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-passthrucommand.o -MD -MP -MF "$(DEPDIR)/PrimProc-passthrucommand.Tpo" -c -o PrimProc-passthrucommand.o `test -f 'passthrucommand.cpp' || echo '$(srcdir)/'`passthrucommand.cpp; \ @am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-passthrucommand.Tpo" "$(DEPDIR)/PrimProc-passthrucommand.Po"; else rm -f "$(DEPDIR)/PrimProc-passthrucommand.Tpo"; exit 1; fi @@ -514,20 +521,6 @@ PrimProc-primitiveserver.obj: primitiveserver.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-primitiveserver.obj `if test -f 'primitiveserver.cpp'; then $(CYGPATH_W) 'primitiveserver.cpp'; else $(CYGPATH_W) '$(srcdir)/primitiveserver.cpp'; fi` -PrimProc-pseudocc.o: pseudocc.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-pseudocc.o -MD -MP -MF "$(DEPDIR)/PrimProc-pseudocc.Tpo" -c -o PrimProc-pseudocc.o `test -f 'pseudocc.cpp' || echo '$(srcdir)/'`pseudocc.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-pseudocc.Tpo" "$(DEPDIR)/PrimProc-pseudocc.Po"; else rm -f "$(DEPDIR)/PrimProc-pseudocc.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='pseudocc.cpp' object='PrimProc-pseudocc.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-pseudocc.o `test -f 'pseudocc.cpp' || echo '$(srcdir)/'`pseudocc.cpp - -PrimProc-pseudocc.obj: pseudocc.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-pseudocc.obj -MD -MP -MF "$(DEPDIR)/PrimProc-pseudocc.Tpo" -c -o PrimProc-pseudocc.obj `if test -f 'pseudocc.cpp'; then $(CYGPATH_W) 'pseudocc.cpp'; else $(CYGPATH_W) '$(srcdir)/pseudocc.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-pseudocc.Tpo" "$(DEPDIR)/PrimProc-pseudocc.Po"; else rm -f "$(DEPDIR)/PrimProc-pseudocc.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='pseudocc.cpp' object='PrimProc-pseudocc.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-pseudocc.obj `if test -f 'pseudocc.cpp'; then $(CYGPATH_W) 'pseudocc.cpp'; else $(CYGPATH_W) '$(srcdir)/pseudocc.cpp'; fi` - PrimProc-rtscommand.o: rtscommand.cpp @am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-rtscommand.o -MD -MP -MF "$(DEPDIR)/PrimProc-rtscommand.Tpo" -c -o PrimProc-rtscommand.o `test -f 'rtscommand.cpp' || echo '$(srcdir)/'`rtscommand.cpp; \ @am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-rtscommand.Tpo" "$(DEPDIR)/PrimProc-rtscommand.Po"; else rm -f "$(DEPDIR)/PrimProc-rtscommand.Tpo"; exit 1; fi @@ -556,6 +549,20 @@ PrimProc-umsocketselector.obj: umsocketselector.cpp @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-umsocketselector.obj `if test -f 'umsocketselector.cpp'; then $(CYGPATH_W) 'umsocketselector.cpp'; else $(CYGPATH_W) '$(srcdir)/umsocketselector.cpp'; fi` +PrimProc-udf.o: udf.cpp +@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-udf.o -MD -MP -MF "$(DEPDIR)/PrimProc-udf.Tpo" -c -o PrimProc-udf.o `test -f 'udf.cpp' || echo '$(srcdir)/'`udf.cpp; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-udf.Tpo" "$(DEPDIR)/PrimProc-udf.Po"; else rm -f "$(DEPDIR)/PrimProc-udf.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='udf.cpp' object='PrimProc-udf.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-udf.o `test -f 'udf.cpp' || echo '$(srcdir)/'`udf.cpp + +PrimProc-udf.obj: udf.cpp +@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -MT PrimProc-udf.obj -MD -MP -MF "$(DEPDIR)/PrimProc-udf.Tpo" -c -o PrimProc-udf.obj `if test -f 'udf.cpp'; then $(CYGPATH_W) 'udf.cpp'; else $(CYGPATH_W) '$(srcdir)/udf.cpp'; fi`; \ +@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/PrimProc-udf.Tpo" "$(DEPDIR)/PrimProc-udf.Po"; else rm -f "$(DEPDIR)/PrimProc-udf.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='udf.cpp' object='PrimProc-udf.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(PrimProc_CPPFLAGS) $(CPPFLAGS) $(PrimProc_CXXFLAGS) $(CXXFLAGS) -c -o PrimProc-udf.obj `if test -f 'udf.cpp'; then $(CYGPATH_W) 'udf.cpp'; else $(CYGPATH_W) '$(srcdir)/udf.cpp'; fi` + mostlyclean-libtool: -rm -f *.lo diff --git a/primitives/primproc/PrimProc.rc b/primitives/primproc/PrimProc.rc deleted file mode 100644 index 54535710..00000000 --- a/primitives/primproc/PrimProc.rc +++ /dev/null @@ -1,102 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 4,6,0,0 - PRODUCTVERSION 4,6,0,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "InfiniDB, Inc." - VALUE "FileDescription", "InfiniDB Primitive Processor" - VALUE "FileVersion", "4.6.0-0" - VALUE "InternalName", "PrimProc" - VALUE "LegalCopyright", "Copyright (C) 2014" - VALUE "OriginalFilename", "PrimProc.exe" - VALUE "ProductName", "InfiniDB" - VALUE "ProductVersion", "4.6.0.0 Beta" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/primitives/primproc/PrimProc.vcxproj b/primitives/primproc/PrimProc.vcxproj deleted file mode 100644 index 2032f6a0..00000000 --- a/primitives/primproc/PrimProc.vcxproj +++ /dev/null @@ -1,447 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {C3CE5C6C-A4E2-4B6F-80C3-94E0609C654E} - PrimProc - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - del \InfiniDB\primproc\rowaggregation.h \InfiniDB\primproc\rowgroup.h >nul 2>&1 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\primitives\primproc;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\primitives\blockcache;$(SolutionDir)..\primitives\linux-port;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - rm -f \InfiniDB\primproc\rowaggregation.h \InfiniDB\primproc\rowgroup.h >nul 2>&1 - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\primitives\primproc;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\primitives\blockcache;$(SolutionDir)..\primitives\linux-port;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - true - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - Console - 2097152 - 0 - 2097152 - 0 - MachineX64 - - - - - del \InfiniDB\primproc\rowaggregation.h \InfiniDB\primproc\rowgroup.h >nul 2>&1 - - - Full - AnySuitable - true - Speed - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\primitives\primproc;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\primitives\blockcache;$(SolutionDir)..\primitives\linux-port;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - false - false - Level2 - ProgramDatabase - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - false - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - $(SolutionDir)..\..\signit "InfiniDB Primitive Processor" \InfiniDB\Release\PrimProc.exe - - - - - del \InfiniDB\primproc\rowaggregation.h \InfiniDB\primproc\rowgroup.h >nul 2>&1 - - - X64 - - - Full - AnySuitable - true - Speed - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\primitives\primproc;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\primitives\blockcache;$(SolutionDir)..\primitives\linux-port;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - false - false - Level2 - ProgramDatabase - - - false - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - Console - 2097152 - 2097152 - 1100 - true - true - UseLinkTimeCodeGeneration - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB Primitive Processor" $(SolutionDir)..\..x64\Release\PrimProc.exe - - - - - del \InfiniDB\primproc\rowaggregation.h \InfiniDB\primproc\rowgroup.h >nul 2>&1 - - - Full - AnySuitable - true - Speed - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\primitives\primproc;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\primitives\blockcache;$(SolutionDir)..\primitives\linux-port;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - false - false - Level2 - ProgramDatabase - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - $(SolutionDir)..\..\signit "InfiniDB Primitive Processor" \InfiniDB\Release\PrimProc.exe - - - - - rm -f \InfiniDB\primproc\rowaggregation.h \InfiniDB\primproc\rowgroup.h >nul 2>&1 - - - X64 - - - Full - AnySuitable - true - Speed - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\primitives\primproc;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\primitives\blockcache;$(SolutionDir)..\primitives\linux-port;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - false - true - Level2 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - Console - 2097152 - 2097152 - 1100 - true - true - UseLinkTimeCodeGeneration - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB Primitive Processor" $(SolutionDir)..\..\x64\EnterpriseRelease\PrimProc.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {fc0ba86e-2cc2-4ce8-ac62-16b662fe5b29} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {2be469d2-d854-4480-bfe0-34de89c557b2} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - - - - \ No newline at end of file diff --git a/primitives/primproc/PrimProc.vcxproj.filters b/primitives/primproc/PrimProc.vcxproj.filters deleted file mode 100644 index 3ce886e2..00000000 --- a/primitives/primproc/PrimProc.vcxproj.filters +++ /dev/null @@ -1,182 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/primitives/primproc/batchprimitiveprocessor.cpp b/primitives/primproc/batchprimitiveprocessor.cpp index d09c2cdc..49b51cbc 100644 --- a/primitives/primproc/batchprimitiveprocessor.cpp +++ b/primitives/primproc/batchprimitiveprocessor.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: batchprimitiveprocessor.cpp 2136 2013-07-24 21:04:30Z pleblanc $ +// $Id: batchprimitiveprocessor.cpp 2012 2012-12-10 21:08:03Z xlou $ // C++ Implementation: batchprimitiveprocessor // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -50,7 +50,7 @@ using namespace boost; #include "funcexpwrapper.h" #include "fixedallocator.h" #include "blockcacheclient.h" -#include "MonitorProcMem.h" +#include "monitorprocmem.h" #define MAX64 0x7fffffffffffffffLL #define MIN64 0x8000000000000000LL @@ -67,15 +67,15 @@ using namespace joblist; namespace primitiveprocessor { // these are config parms defined in primitiveserver.cpp, initialized by PrimProc main(). -extern uint32_t blocksReadAhead; -extern uint32_t dictBufferSize; -extern uint32_t defaultBufferSize; +extern uint blocksReadAhead; +extern uint dictBufferSize; +extern uint defaultBufferSize; extern int fCacheCount; -extern uint32_t connectionsPerUM; -extern int noVB; +extern uint connectionsPerUM; BatchPrimitiveProcessor::BatchPrimitiveProcessor() : ot(BPS_ELEMENT_TYPE), + versionNum(0), txnID(0), sessionID(0), stepID(0), @@ -106,16 +106,16 @@ BatchPrimitiveProcessor::BatchPrimitiveProcessor() : filtOnString(false), prefetchThreshold(0), hasDictStep(false), - sockIndex(0), - endOfJoinerRan(false) + sockIndex(0) { pp.setLogicalBlockMode(true); pp.setBlockPtr((int *) blockData); } BatchPrimitiveProcessor::BatchPrimitiveProcessor(ByteStream &b, double prefetch, - boost::shared_ptr bppst) : + boost::shared_ptr bppst) : ot(BPS_ELEMENT_TYPE), + versionNum(0), txnID(0), sessionID(0), stepID(0), @@ -146,8 +146,7 @@ BatchPrimitiveProcessor::BatchPrimitiveProcessor(ByteStream &b, double prefetch, filtOnString(false), prefetchThreshold(prefetch), hasDictStep(false), - sockIndex(0), - endOfJoinerRan(false) + sockIndex(0) { pp.setLogicalBlockMode(true); pp.setBlockPtr((int *) blockData); @@ -183,18 +182,19 @@ BatchPrimitiveProcessor::~BatchPrimitiveProcessor() void BatchPrimitiveProcessor::initBPP(ByteStream &bs) { - uint32_t i; + uint i; uint8_t tmp8; Command::CommandType type; bs.advance(sizeof(ISMPacketHeader)); // skip the header bs >> tmp8; ot = static_cast(tmp8); + bs >> versionNum; bs >> txnID; bs >> sessionID; bs >> stepID; bs >> uniqueID; - bs >> versionInfo; +// cerr << "init: sessionID=" << sessionID << " stepID=" << stepID << endl; bs >> tmp8; needStrValues = tmp8 & NEED_STR_VALUES; @@ -206,17 +206,16 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) hasRowGroup = tmp8 & HAS_ROWGROUP; getTupleJoinRowGroupData = tmp8 & JOIN_ROWGROUP_DATA; - // This used to signify that there was input row data from previous jobsteps, and - // it never quite worked right. No need to fix it or update it; all BPP's have started - // with a scan for years. Took it out. - assert(!hasRowGroup); - bs >> bop; bs >> forHJ; + if (hasRowGroup) { + bs >> valueColumn; + bs >> inputRG; + } + if (ot == ROW_GROUP) { bs >> outputRG; - //outputRG.setUseStringTable(true); bs >> tmp8; if (tmp8) { fe1.reset(new FuncExpWrapper()); @@ -240,12 +239,12 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) tJoiners.reset(new boost::shared_ptr[joinerCount]); _pools.reset(new boost::shared_ptr[joinerCount]); tlJoiners.reset(new boost::shared_ptr[joinerCount]); - tJoinerSizes.reset(new uint32_t[joinerCount]); - largeSideKeyColumns.reset(new uint32_t[joinerCount]); - tlLargeSideKeyColumns.reset(new vector[joinerCount]); + tJoinerSizes.reset(new uint[joinerCount]); + largeSideKeyColumns.reset(new uint[joinerCount]); + tlLargeSideKeyColumns.reset(new vector[joinerCount]); typelessJoin.reset(new bool[joinerCount]); - tlKeyLengths.reset(new uint32_t[joinerCount]); - storedKeyAllocators.reset(new PoolAllocator[joinerCount]); + tlKeyLengths.reset(new uint[joinerCount]); + storedKeyAllocators.reset(new FixedAllocator[joinerCount]); joinNullValues.reset(new uint64_t[joinerCount]); doMatchNulls.reset(new bool[joinerCount]); joinFEFilters.reset(new scoped_ptr[joinerCount]); @@ -254,7 +253,7 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) for (i = 0; i < joinerCount; i++) { doMatchNulls[i] = false; bs >> tJoinerSizes[i]; - //cout << "joiner size = " << tJoinerSizes[i] << endl; + //cout << "joiner size = " << tJoinerSizes[i] << endl; bs >> joinTypes[i]; bs >> tmp8; typelessJoin[i] = (bool) tmp8; @@ -268,15 +267,15 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) if (!typelessJoin[i]) { bs >> joinNullValues[i]; bs >> largeSideKeyColumns[i]; - //cout << "large side key is " << largeSideKeyColumns[i] << endl; + //cout << "large side key is " << largeSideKeyColumns[i] << endl; _pools[i].reset(new utils::SimplePool()); - utils::SimpleAllocator > alloc(_pools[i]); + utils::SimpleAllocator > alloc(_pools[i]); tJoiners[i].reset(new TJoiner(10, TupleJoiner::hasher(), equal_to(), alloc)); } else { - deserializeVector(bs, tlLargeSideKeyColumns[i]); + deserializeVector(bs, tlLargeSideKeyColumns[i]); bs >> tlKeyLengths[i]; - //storedKeyAllocators[i] = PoolAllocator(); + storedKeyAllocators[i] = FixedAllocator(tlKeyLengths[i], false, tJoinerSizes[i]); tlJoiners[i].reset(new TLJoiner(10, TupleJoiner::hasher())); } } @@ -288,29 +287,26 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) deserializeVector(bs, smallSideRGs); // cout << "deserialized " << smallSideRGs.size() << " small-side rowgroups\n"; idbassert(smallSideRGs.size() == joinerCount); - smallSideRowLengths.reset(new uint32_t[joinerCount]); - smallSideRowData.reset(new RGData[joinerCount]); - smallNullRowData.reset(new RGData[joinerCount]); - smallNullPointers.reset(new Row::Pointer[joinerCount]); + smallSideRowLengths.reset(new uint[joinerCount]); + smallSideRowData.reset(new shared_array[joinerCount]); + smallNullRowData.reset(new shared_array[joinerCount]); ssrdPos.reset(new uint64_t[joinerCount]); for (i = 0; i < joinerCount; i++) { - smallSideRowLengths[i] = smallSideRGs[i].getRowSize();; - smallSideRowData[i] = RGData(smallSideRGs[i], tJoinerSizes[i]); -// smallSideRowData[i].reset(new uint8_t[ -// smallSideRGs[i].getEmptySize() + -// (uint64_t) smallSideRowLengths[i] * tJoinerSizes[i]]); - smallSideRGs[i].setData(&smallSideRowData[i]); + smallSideRowLengths[i] = + smallSideRGs[i].getOffsets()[smallSideRGs[i].getColumnCount()]; + smallSideRowData[i].reset(new uint8_t[ + smallSideRGs[i].getEmptySize() + + (uint64_t) smallSideRowLengths[i] * tJoinerSizes[i]]); + smallSideRGs[i].setData(smallSideRowData[i].get()); smallSideRGs[i].resetRowGroup(0); + smallSideRGs[i].setRowCount(tJoinerSizes[i]); ssrdPos[i] = smallSideRGs[i].getEmptySize(); if (joinTypes[i] & (LARGEOUTER | SEMI | ANTI)) { Row smallRow; smallSideRGs[i].initRow(&smallRow); - smallNullRowData[i] = RGData(smallSideRGs[i], 1); - smallSideRGs[i].setData(&smallNullRowData[i]); - smallSideRGs[i].getRow(0, &smallRow); + smallNullRowData[i].reset(new uint8_t[smallRow.getSize()]); + smallRow.setData(smallNullRowData[i].get()); smallRow.initToNull(); - smallNullPointers[i] = smallRow.getPointer(); - smallSideRGs[i].setData(&smallSideRowData[i]); } } bs >> largeSideRG; @@ -330,11 +326,11 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) bs >> filterCount; filterSteps.resize(filterCount); - //cout << "deserializing " << filterCount << " filters\n"; +// cout << "deserializing " << filterCount << " filters\n"; hasScan = false; hasPassThru = false; for (i = 0; i < filterCount; ++i) { - //cout << "deserializing step " << i << endl; +// cout << "deserializing step " << i << endl; filterSteps[i] = SCommand(Command::makeCommand(bs, &type, filterSteps)); if (type == Command::COLUMN_COMMAND) { ColumnCommand *col = (ColumnCommand *) filterSteps[i].get(); @@ -352,10 +348,9 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) hasDictStep = true; } bs >> projectCount; - //cout << "deserializing " << projectCount << " projected columns\n\n"; +// cout << "deserializing " << projectCount << " projected columns\n\n"; projectSteps.resize(projectCount); for (i = 0; i < projectCount; ++i) { - //cout << "deserializing step " << i << endl; projectSteps[i] = SCommand(Command::makeCommand(bs, &type, projectSteps)); if (type == Command::PASS_THRU) hasPassThru = true; @@ -383,9 +378,9 @@ void BatchPrimitiveProcessor::initBPP(ByteStream &bs) * Refer to that fcn for message format info. */ void BatchPrimitiveProcessor::resetBPP(ByteStream &bs, const SP_UM_MUTEX& w, - const SP_UM_IOSOCK& s) + const SP_UM_IOSOCK& s) { - uint32_t i; + uint i; vector preloads; objLock.lock(); @@ -398,30 +393,40 @@ void BatchPrimitiveProcessor::resetBPP(ByteStream &bs, const SP_UM_MUTEX& w, bs.advance(sizeof(ISMPacketHeader) + 16); bs >> dbRoot; bs >> count; - bs >> ridCount; - - if (gotAbsRids) { - assert(0); - memcpy(absRids.get(), bs.buf(), ridCount << 3); - bs.advance(ridCount << 3); - /* TODO: this loop isn't always necessary or sensible */ - ridMap = 0; - baseRid = absRids[0] & 0xffffffffffffe000ULL; - for (uint32_t i = 0; i < ridCount; i++) { - relRids[i] = absRids[i] - baseRid; - ridMap |= 1 << (relRids[i] >> 10); - } + if (hasRowGroup) { + uint32_t rgSize; + + bs >> rgSize; + memcpy(inRowGroupData.get(), bs.buf(), rgSize); + bs.advance(rgSize); + + /* initializing the value & rid arrays happens in operator() */ } else { - bs >> ridMap; - bs >> baseRid; - memcpy(relRids, bs.buf(), ridCount << 1); - bs.advance(ridCount << 1); - } + bs >> ridCount; + + if (gotAbsRids) { + memcpy(absRids.get(), bs.buf(), ridCount << 3); + bs.advance(ridCount << 3); + /* TODO: this loop isn't always necessary or sensible */ + ridMap = 0; + baseRid = absRids[0] & 0xffffffffffffe000ULL; + for (uint i = 0; i < ridCount; i++) { + relRids[i] = absRids[i] & 0x1fff; + ridMap |= 1 << (relRids[i] >> 10); + } + } + else { + bs >> ridMap; + bs >> baseRid; + memcpy(relRids, bs.buf(), ridCount << 1); + bs.advance(ridCount << 1); + } - if (gotValues) { - memcpy(values, bs.buf(), ridCount << 3); - bs.advance(ridCount << 3); + if (gotValues) { + memcpy(values, bs.buf(), ridCount << 3); + bs.advance(ridCount << 3); + } } for (i = 0; i < filterCount; ++i) { filterSteps[i]->resetCommand(bs); @@ -436,6 +441,9 @@ void BatchPrimitiveProcessor::resetBPP(ByteStream &bs, const SP_UM_MUTEX& w, currentBlockOffset = 0; memset(relLBID.get(), 0, sizeof(uint64_t) * (projectCount + 1)); memset(asyncLoaded.get(), 0, sizeof(bool) * (projectCount + 1)); + + if (hasRowGroup) + initFromRowGroup(); buildVSSCache(count); #ifdef __FreeBSD__ @@ -445,7 +453,7 @@ void BatchPrimitiveProcessor::resetBPP(ByteStream &bs, const SP_UM_MUTEX& w, void BatchPrimitiveProcessor::addToJoiner(ByteStream &bs) { - uint32_t count, i, joinerNum, tlIndex, startPos; + uint32_t count, i, joinerNum, tlIndex; joblist::ElementType *et; TypelessData tlLargeKey; uint8_t nullFlag; @@ -462,7 +470,6 @@ void BatchPrimitiveProcessor::addToJoiner(ByteStream &bs) bs.advance(sizeof(ISMPacketHeader) + 3*sizeof(uint32_t)); bs >> count; - bs >> startPos; if (ot == ROW_GROUP) { bs >> joinerNum; idbassert(joinerNum < joinerCount); @@ -475,7 +482,7 @@ void BatchPrimitiveProcessor::addToJoiner(ByteStream &bs) tlLargeKey.deserialize(bs, storedKeyAllocators[joinerNum]); bs >> tlIndex; tlJoiners[joinerNum]->insert(pair(tlLargeKey, - tlIndex)); + tlIndex)); } else tJoinerSizes[joinerNum]--; @@ -492,31 +499,26 @@ void BatchPrimitiveProcessor::addToJoiner(ByteStream &bs) bs.advance(count * sizeof(JoinerElements)); if (getTupleJoinRowGroupData) { + Row r; // cout << "copying full row data for joiner " << joinerNum << endl; /* Need to update this assertion if there's a typeless join. search for nullFlag. */ // idbassert(ssrdPos[joinerNum] + (count * smallSideRowLengths[joinerNum]) <= // smallSideRGs[joinerNum].getEmptySize() + // (smallSideRowLengths[joinerNum] * tJoinerSizes[joinerNum])); + memcpy(&smallSideRowData[joinerNum][ssrdPos[joinerNum]], bs.buf(), + count * smallSideRowLengths[joinerNum]); - RowGroup &smallSide = smallSideRGs[joinerNum]; - RGData offTheWire; + ssrdPos[joinerNum] += count * smallSideRowLengths[joinerNum]; + bs.advance(count * smallSideRowLengths[joinerNum]); - // TODO: write an RGData fcn to let it interpret data within a ByteStream to avoid - // the extra copying. - offTheWire.deserialize(bs); - smallSide.setData(&smallSideRowData[joinerNum]); - smallSide.append(offTheWire, startPos); - - //ssrdPos[joinerNum] += count; - - /* This prints the row data - smallSideRGs[joinerNum].initRow(&r); - for (i = 0; i < (tJoinerSizes[joinerNum] * smallSideRowLengths[joinerNum]); i+=r.getSize()) { - r.setData(&smallSideRowData[joinerNum][i + smallSideRGs[joinerNum].getEmptySize()]); - cout << " got row: " << r.toString() << endl; - } - */ +/* This prints the row data + smallSideRGs[joinerNum].initRow(&r); + for (i = 0; i < (tJoinerSizes[joinerNum] * smallSideRowLengths[joinerNum]); i+=r.getSize()) { + r.setData(&smallSideRowData[joinerNum][i + smallSideRGs[joinerNum].getEmptySize()]); + cout << " got row: " << r.toString() << endl; + } +*/ } } else { @@ -531,46 +533,24 @@ void BatchPrimitiveProcessor::addToJoiner(ByteStream &bs) addToJoinerLock.unlock(); } -int BatchPrimitiveProcessor::endOfJoiner() +void BatchPrimitiveProcessor::endOfJoiner() { /* Wait for all joiner elements to be added */ - uint32_t i; + uint i; - boost::mutex::scoped_lock scoped(addToJoinerLock); - - if (endOfJoinerRan) - return 0; - - if (ot == ROW_GROUP) - for (i = 0; i < joinerCount; i++) { - if (!typelessJoin[i]) { - if ((tJoiners[i].get() == NULL || tJoiners[i]->size() != - tJoinerSizes[i])) - return -1; - } - else if ((tlJoiners[i].get() == NULL || tlJoiners[i]->size() != - tJoinerSizes[i])) - return -1; - } - else if (joiner.get() == NULL || joiner->size() != joinerSize) - return -1; - - endOfJoinerRan = true; - -#ifdef old_version addToJoinerLock.lock(); if (ot == ROW_GROUP) for (i = 0; i < joinerCount; i++) { if (!typelessJoin[i]) while ((tJoiners[i].get() == NULL || tJoiners[i]->size() != - tJoinerSizes[i])) { + tJoinerSizes[i])) { addToJoinerLock.unlock(); usleep(2000); addToJoinerLock.lock(); } else while ((tlJoiners[i].get() == NULL || tlJoiners[i]->size() != - tJoinerSizes[i])) { + tJoinerSizes[i])) { addToJoinerLock.unlock(); usleep(2000); addToJoinerLock.lock(); @@ -583,27 +563,29 @@ int BatchPrimitiveProcessor::endOfJoiner() addToJoinerLock.lock(); } addToJoinerLock.unlock(); -#endif - #ifndef __FreeBSD__ objLock.unlock(); #endif - return 0; } void BatchPrimitiveProcessor::initProcessor() { - uint32_t i, j; - - if (gotAbsRids || needStrValues || hasRowGroup) - absRids.reset(new uint64_t[LOGICAL_BLOCK_RIDS]); - if (needStrValues) - strValues.reset(new string[LOGICAL_BLOCK_RIDS]); + uint i, j; + + if (gotAbsRids || needStrValues || hasRowGroup) + absRids.reset(new uint64_t[LOGICAL_BLOCK_RIDS]); + if (needStrValues) + strValues.reset(new string[LOGICAL_BLOCK_RIDS]); + if (hasRowGroup) { + inRowGroupData.reset(new uint8_t[inputRG.getMaxDataSize()]); + inputRG.setData(inRowGroupData.get()); + } outMsgSize = defaultBufferSize; outputMsg.reset(new uint8_t[outMsgSize]); if (ot == ROW_GROUP) { // calculate the projection -> outputRG mapping projectionMap.reset(new int[projectCount]); + //bool reserved[outputRG.getColumnCount()]; bool* reserved = (bool*)alloca(outputRG.getColumnCount() * sizeof(bool)); for (i = 0; i < outputRG.getColumnCount(); i++) reserved[i] = false; @@ -636,7 +618,7 @@ void BatchPrimitiveProcessor::initProcessor() } } else { - for (uint32_t k = 0; k < tlLargeSideKeyColumns[j].size(); k++) { + for (uint k = 0; k < tlLargeSideKeyColumns[j].size(); k++) { if (projectionMap[i] == (int) tlLargeSideKeyColumns[j][k]) { keyColumnProj[i] = true; break; @@ -646,9 +628,9 @@ void BatchPrimitiveProcessor::initProcessor() } } if (hasJoinFEFilters) { - joinFERG->initRow(&joinFERow, true); - joinFERowData.reset(new uint8_t[joinFERow.getSize()]); + joinFERowData.reset(new uint8_t[joinFERG->getRowSize()]); joinFERow.setData(joinFERowData.get()); + joinFERG->initRow(&joinFERow); joinFEMappings.reset(new shared_array[joinerCount + 1]); for (i = 0; i < joinerCount; i++) joinFEMappings[i] = makeMapping(smallSideRGs[i], *joinFERG); @@ -662,6 +644,7 @@ void BatchPrimitiveProcessor::initProcessor() if (fe1) { fe1ToProjection = makeMapping(fe1Input, outputRG); projectForFE1.reset(new int[projectCount]); + //bool reserved[fe1Input.getColumnCount()]; bool* reserved = (bool*)alloca(fe1Input.getColumnCount() * sizeof(bool)); for (i = 0; i < fe1Input.getColumnCount(); i++) reserved[i] = false; @@ -685,13 +668,13 @@ void BatchPrimitiveProcessor::initProcessor() fe2Output.initRow(&fe2Out); } if (getTupleJoinRowGroupData) { - gjrgPlaceHolders.reset(new uint32_t[joinerCount]); + gjrgPlaceHolders.reset(new uint[joinerCount]); outputRG.initRow(&largeRow); joinedRG.initRow(&joinedRow); - joinedRG.initRow(&baseJRow, true); + joinedRG.initRow(&baseJRow); smallRows.reset(new Row[joinerCount]); for (i = 0; i < joinerCount; i++) - smallSideRGs[i].initRow(&smallRows[i], true); + smallSideRGs[i].initRow(&smallRows[i]); baseJRowMem.reset(new uint8_t[baseJRow.getSize()]); baseJRow.setData(baseJRowMem.get()); gjrgMappings.reset(new shared_array[joinerCount + 1]); @@ -701,26 +684,32 @@ void BatchPrimitiveProcessor::initProcessor() } } - // @bug 1051 - if (hasFilterStep) - { - for (uint64_t i = 0; i < 2; i++) - { - fFiltRidCount[i] = 0; - fFiltCmdRids[i].reset(new uint16_t[LOGICAL_BLOCK_RIDS]); - fFiltCmdValues[i].reset(new int64_t[LOGICAL_BLOCK_RIDS]); - if(filtOnString) fFiltStrValues[i].reset(new string[LOGICAL_BLOCK_RIDS]); - } + if (hasRowGroup && ot == ROW_GROUP) { + // calculate the in->out mapping + rgMap = makeMapping(inputRG, outputRG); + rgMap[valueColumn] = -1; } + // @bug 1051 + if (hasFilterStep) + { + for (uint64_t i = 0; i < 2; i++) + { + fFiltRidCount[i] = 0; + fFiltCmdRids[i].reset(new uint16_t[LOGICAL_BLOCK_RIDS]); + fFiltCmdValues[i].reset(new int64_t[LOGICAL_BLOCK_RIDS]); + if(filtOnString) fFiltStrValues[i].reset(new string[LOGICAL_BLOCK_RIDS]); + } + } + /* init the Commands */ if (filterCount > 0) { - for (i = 0; i < (uint32_t) filterCount - 1; ++i) { + for (i = 0; i < (uint) filterCount - 1; ++i) { // cout << "prepping filter " << i << endl; filterSteps[i]->setBatchPrimitiveProcessor(this); - if (filterSteps[i+1]->getCommandType() == Command::DICT_STEP) + if (filterSteps[i+1].get()->getCommandType() == Command::DICT_STEP) filterSteps[i]->prep(OT_BOTH, true); - else if (filterSteps[i]->filterFeeder() != Command::NOT_FEEDER) + else if (filterSteps[i].get()->filterFeeder() != Command::NOT_FEEDER) filterSteps[i]->prep(OT_BOTH, false); else filterSteps[i]->prep(OT_RID, false); @@ -732,10 +721,7 @@ void BatchPrimitiveProcessor::initProcessor() for (i = 0; i < projectCount; ++i) { // cout << "prepping projection " << i << endl; projectSteps[i]->setBatchPrimitiveProcessor(this); - if (noVB) - projectSteps[i]->prep(OT_BOTH, false); - else - projectSteps[i]->prep(OT_DATAVALUE, false); + projectSteps[i]->prep(OT_DATAVALUE, false); if (0 < filterCount ) { //if there is an rtscommand with a passThru, the passThru must make its own absRids //unless there is only one project step, then the last filter step can make absRids @@ -751,9 +737,8 @@ void BatchPrimitiveProcessor::initProcessor() if (fAggregator.get() != NULL) { - //fAggRowGroupData.reset(new uint8_t[fAggregateRG.getMaxDataSize()]); - fAggRowGroupData.reinit(fAggregateRG); - fAggregateRG.setData(&fAggRowGroupData); + fAggRowGroupData.reset(new uint8_t[fAggregateRG.getMaxDataSize()]); + fAggregateRG.setData(fAggRowGroupData.get()); if (doJoin) { fAggregator->setInputOutput(fe2 ? fe2Output : joinedRG, &fAggregateRG); fAggregator->setJoinRowGroups(&smallSideRGs, &largeSideRG); @@ -763,7 +748,7 @@ void BatchPrimitiveProcessor::initProcessor() } minVal = MAX64; maxVal = MIN64; - + // @bug 1269, initialize data used by execute() for async loading blocks // +1 for the scan filter step with no predicate, if any relLBID.reset(new uint64_t[projectCount + 1]); @@ -772,7 +757,7 @@ void BatchPrimitiveProcessor::initProcessor() void BatchPrimitiveProcessor::executeJoin() { - uint32_t newRowCount, i; + uint newRowCount, i; preJoinRidCount = ridCount; newRowCount = 0; @@ -789,7 +774,7 @@ void BatchPrimitiveProcessor::executeJoin() /* This version does a join on projected rows */ void BatchPrimitiveProcessor::executeTupleJoin() { - uint32_t newRowCount = 0, i, j; + uint newRowCount = 0, i, j; vector matches; uint64_t largeKey; TypelessData tlLargeKey; @@ -797,12 +782,13 @@ void BatchPrimitiveProcessor::executeTupleJoin() preJoinRidCount = ridCount; outputRG.getRow(0, &oldRow); outputRG.getRow(0, &newRow); - - //cout << "before join, RG has " << outputRG.getRowCount() << " BPP ridcount= " << ridCount << endl; + + //cout << "before join, RG has " << outputRG.getRowCount() << " BPP ridcount= " << ridCount << endl; + for (i = 0; i < ridCount && !sendThread->aborted(); i++, oldRow.nextRow()) { /* Decide whether this large-side row belongs in the output. The breaks * in the loop mean that it doesn't. - * + * * In English the logic is: * Reject the row if there's no match and it's not an anti or an outer join * or if there is a match and it's an anti join with no filter. @@ -811,7 +797,6 @@ void BatchPrimitiveProcessor::executeTupleJoin() * are NULL values to match against, but there is no filter, all rows can be eliminated. */ - //cout << "large side row: " << oldRow.toString() << endl; for (j = 0; j < joinerCount; j++) { bool found; if (UNLIKELY(joinTypes[j] & ANTI)) { @@ -821,15 +806,11 @@ void BatchPrimitiveProcessor::executeTupleJoin() break; } if (LIKELY(!typelessJoin[j])) { - //cout << "not typeless join\n"; bool isNull; - uint32_t colIndex = largeSideKeyColumns[j]; - if (oldRow.isUnsigned(colIndex)) - largeKey = oldRow.getUintField(colIndex); - else - largeKey = oldRow.getIntField(colIndex); + largeKey = oldRow.getIntField(largeSideKeyColumns[j]); found = (tJoiners[j]->find(largeKey) != tJoiners[j]->end()); - isNull = oldRow.isNullValue(colIndex); + isNull = oldRow.isNullValue(largeSideKeyColumns[j]); + /* These conditions define when the row is NOT in the result set: * - if the key is not in the small side, and the join isn't a large-outer or anti join * - if the key is NULL, and the join isn't anti- or large-outer @@ -837,21 +818,16 @@ void BatchPrimitiveProcessor::executeTupleJoin() */ if (((!found || isNull) && !(joinTypes[j] & (LARGEOUTER | ANTI))) || - ((joinTypes[j] & ANTI) && ((isNull && (joinTypes[j] & MATCHNULLS)) || (found && !isNull)))) { - //cout << " - not in the result set\n"; + ((joinTypes[j] & ANTI) && ((isNull && (joinTypes[j] & MATCHNULLS)) || (found && !isNull)))) break; - } - //else - // cout << " - in the result set\n"; } else { - //cout << " typeless join\n"; // the null values are not sent by UM in typeless case. null -> !found tlLargeKey = makeTypelessKey(oldRow, tlLargeSideKeyColumns[j], tlKeyLengths[j], - &tmpKeyAllocators[j]); + &tmpKeyAllocators[j]); found = tlJoiners[j]->find(tlLargeKey) != tlJoiners[j]->end(); if ((!found && !(joinTypes[j] & (LARGEOUTER | ANTI))) || - (joinTypes[j] & ANTI)) { + (joinTypes[j] & ANTI)) { /* Separated the ANTI join logic for readability. * @@ -861,7 +837,7 @@ void BatchPrimitiveProcessor::executeTupleJoin() break; else if (joinTypes[j] & MATCHNULLS) { bool hasNull = false; - for (uint32_t z = 0; z < tlLargeSideKeyColumns[j].size(); z++) + for (uint z = 0; z < tlLargeSideKeyColumns[j].size(); z++) if (oldRow.isNullValue(tlLargeSideKeyColumns[j][z])) { hasNull = true; break; @@ -870,7 +846,7 @@ void BatchPrimitiveProcessor::executeTupleJoin() break; else continue; // non-null keys not in the small side - // are in the result + // are in the result } else // signifies a not-exists query continue; @@ -881,7 +857,7 @@ void BatchPrimitiveProcessor::executeTupleJoin() } if (j == joinerCount) { for (j = 0; j < joinerCount; j++) { - uint32_t matchCount; + uint matchCount; /* The result is already known if... * -- anti-join with no fcnexp @@ -901,14 +877,13 @@ void BatchPrimitiveProcessor::executeTupleJoin() if (joinTypes[j] & WITHFCNEXP) { vector newMatches; applyMapping(joinFEMappings[joinerCount], oldRow, &joinFERow); - for (uint32_t k = 0; k < matchCount; k++) { - if (tSmallSideMatches[j][newRowCount][k] == (uint32_t) -1) - smallRows[j].setPointer(smallNullPointers[j]); + for (uint k = 0; k < matchCount; k++) { + if (tSmallSideMatches[j][newRowCount][k] == (uint) -1) + smallRows[j].setData(smallNullRowData[j].get()); else { - smallSideRGs[j].getRow(tSmallSideMatches[j][newRowCount][k], &smallRows[j]); - //uint64_t rowOffset = ((uint64_t) tSmallSideMatches[j][newRowCount][k]) * - // smallRows[j].getSize() + smallSideRGs[j].getEmptySize(); - //smallRows[j].setData(&smallSideRowData[j][rowOffset]); + uint64_t rowOffset = ((uint64_t) tSmallSideMatches[j][newRowCount][k]) * + smallRows[j].getSize() + smallSideRGs[j].getEmptySize(); + smallRows[j].setData(&smallSideRowData[j][rowOffset]); } applyMapping(joinFEMappings[j], smallRows[j], &joinFERow); if (joinFEFilters[j]->evaluate(&joinFERow)) { @@ -955,42 +930,195 @@ void BatchPrimitiveProcessor::executeTupleJoin() tSmallSideMatches[j][newRowCount].push_back(-1); matchCount = 1; } + +#if 0 + /* semi and anti joins with no filter or scalar restriction don't need + * the list of results. They are in the output regardless. + */ + if (!(joinTypes[j] & (SEMI | ANTI)) || (joinTypes[j] & (WITHFCNEXP | SCALAR)) || doMatchNulls[j]) + getJoinResults(oldRow, j, tSmallSideMatches[j][newRowCount]); + /* If the PM has to construct fully joined rows, push back a NULL row when + * there were no small-side matches, or when they are unnecessary (semi|anti). */ + if (getTupleJoinRowGroupData && (joinTypes[j] & (LARGEOUTER | SEMI | ANTI)) && + tSmallSideMatches[j][newRowCount].empty()) + tSmallSideMatches[j][newRowCount].push_back(-1); + + if ((joinTypes[j] & (WITHFCNEXP | SCALAR)) || doMatchNulls[j]) { + uint matchCount = tSmallSideMatches[j][newRowCount].size(); + /* If there's a join filter there is more work to decide whether the row + * belongs in the output. matchcount = the # of joined rows that pass. + * Note, WITHFCNEXP requires the "send small side data" flag to be set */ + if (joinTypes[j] & WITHFCNEXP) { + vector newMatches; + applyMapping(joinFEMappings[joinerCount], oldRow, &joinFERow); + for (uint k = 0; k < tSmallSideMatches[j][newRowCount].size(); k++) { + if (tSmallSideMatches[j][newRowCount][k] == (uint) -1) + smallRows[j].setData(smallNullRowData[j].get()); + else { + uint64_t rowOffset = + ((uint64_t) tSmallSideMatches[j][newRowCount][k]) * + smallRows[j].getSize() + smallSideRGs[j].getEmptySize(); + smallRows[j].setData(&smallSideRowData[j][rowOffset]); + } + applyMapping(joinFEMappings[j], smallRows[j], &joinFERow); + if (!joinFEFilters[j]->evaluate(&joinFERow)) + matchCount--; + else { + /* The first match includes it in a SEMI join result and excludes it from an ANTI join + * result. If it's SEMI & SCALAR however, it needs to continue. + */ + newMatches.push_back(tSmallSideMatches[j][newRowCount][k]); + if ((joinTypes[j] & ANTI) || ((joinTypes[j] & (SEMI | SCALAR)) == SEMI)) + break; + } + } + tSmallSideMatches[j][newRowCount].swap(newMatches); + } + if (matchCount == 0 && (joinTypes[j] & LARGEOUTER)) { + tSmallSideMatches[j][newRowCount].push_back(-1); + matchCount = 1; + } + + /* Scalar check */ + if ((joinTypes[j] & SCALAR) && matchCount > 1) + throw scalar_exception(); + + /* If anti-join, reverse the result */ + if (joinTypes[j] & ANTI) + matchCount = (matchCount ? 0 : 1); + + //if (matchCount == 0) { + // tSmallSideMatches[j][newRowCount].clear(); + // break; + //} + + if (joinTypes[j] & (SEMI | ANTI)) { + if (matchCount == 0 || !(joinTypes[j] & SCALAR)) + tSmallSideMatches[j][newRowCount].clear(); + if (matchCount == 0) + break; // not in the output + else if (!(joinTypes[j] & SCALAR) && getTupleJoinRowGroupData) // pair it with a NULL row for gjrg + tSmallSideMatches[j][newRowCount].push_back(-1); + } + + /* Catch-all clause. If there are no matches, not in the result. + * Join FE instance eliminated all matches. */ + //if (matchCount == 0) { + // tSmallSideMatches[j][newRowCount].clear(); + // break; + //} + + } + + +#endif } + + + + /* Finally, copy the row into the output */ if (j == joinerCount) { if (i != newRowCount) { values[newRowCount] = values[i]; relRids[newRowCount] = relRids[i]; - copyRow(oldRow, &newRow); - //cout << "joined row: " << newRow.toString() << endl; - //memcpy(newRow.getData(), oldRow.getData(), oldRow.getSize()); + memcpy(newRow.getData(), oldRow.getData(), oldRow.getSize()); } newRowCount++; newRow.nextRow(); } - //else - // cout << "j != joinerCount\n"; } } ridCount = newRowCount; outputRG.setRowCount(ridCount); - /* prints out the whole result set. - if (ridCount != 0) { - cout << "RG rowcount=" << outputRG.getRowCount() << " BPP ridcount=" << ridCount << endl; - for (i = 0; i < joinerCount; i++) { - for (j = 0; j < ridCount; j++) { - cout << "joiner " << i << " has " << tSmallSideMatches[i][j].size() << " entries" << endl; - cout << "row " << j << ":"; - for (uint32_t k = 0; k < tSmallSideMatches[i][j].size(); k++) - cout << " " << tSmallSideMatches[i][j][k]; - cout << endl; - } +/* prints out the whole result set. + if (ridCount != 0) { + cout << "RG rowcount=" << outputRG.getRowCount() << " BPP ridcount=" << ridCount << endl; + for (i = 0; i < joinerCount; i++) { + for (j = 0; j < ridCount; j++) { + cout << "joiner " << i << " has " << tSmallSideMatches[i][j].size() << " entries" << endl; + cout << "row " << j << ":"; + for (uint k = 0; k < tSmallSideMatches[i][j].size(); k++) + cout << " " << tSmallSideMatches[i][j][k]; cout << endl; } + cout << endl; } - */ + } +*/ +} + +#if 0 +This version processes rows between the filter and projection steps. We might have +a use for it later... +void BatchPrimitiveProcessor::executeTupleJoin() +{ + uint newRowCount, i, j; + unordered_multimap::iterator it; + pair::iterator, + unordered_multimap::iterator> range; + vector matches; + uint64_t largeKey; + +// cout << "doing tuple join ridcount = " << ridCount << "\n"; + preJoinRidCount = ridCount; + newRowCount = 0; + for (i = 0; i < joinerCount; i++) + tSmallSideMatches[i].clear(); + + for (i = 0; i < ridCount; i++) { + largeKey = values[i]; + cout << "largekey is " << largeKey << endl; + if (largeOuterJoin) { + relRids[newRowCount] = relRids[i]; + values[newRowCount++] = largeKey; + for (j = 0; j < joinerCount; j++) { + range = tJoiners[j]->equal_range(largeKey); + tSmallSideMatches[j].push_back(vector()); + for (; range.first != range.second; ++range.first) + tSmallSideMatches[j].back().push_back(range.first->second); + } + } + else { + for (j = 0; j < joinerCount; j++) + if (tJoiners[j]->find(largeKey) == tJoiners[j]->end()) + break; + if (j == joinerCount) { + relRids[newRowCount] = relRids[i]; + values[newRowCount++] = largeKey; + for (j = 0; j < joinerCount; j++) { + range = tJoiners[j]->equal_range(largeKey); + tSmallSideMatches[j].push_back(vector()); + for (; range.first != range.second; ++range.first) { + cout << "adding " << range.first->second << endl; + tSmallSideMatches[j].back().push_back(range.first->second); + } + } + } + } + } + ridCount = newRowCount; + cout << "done with tuple join, ridcount = " << ridCount << endl; +} +#endif + +/* This fcn takes into account that rows may have been filtered out. + If we can assume there are no filters this can be optimized. */ +void BatchPrimitiveProcessor::copyInputRGColumns() +{ + uint i; + Row ri, ro; + + inputRG.initRow(&ri); + outputRG.initRow(&ro); + + for (i = 0; i < ridCount; ++i) { + inputRG.getRow(relRids[i], &ri); + outputRG.getRow(i, &ro); + applyMapping(rgMap, ri, &ro); + } } #ifdef PRIMPROC_STOPWATCH @@ -999,412 +1127,410 @@ void BatchPrimitiveProcessor::execute(StopWatch *stopwatch) void BatchPrimitiveProcessor::execute() #endif { - uint32_t i, j; + uint i, j; try { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("BatchPrimitiveProcessor::execute first part"); +stopwatch->start("BatchPrimitiveProcessor::execute first part"); #endif - // if only one scan step which has no predicate, async load all columns - if (filterCount == 1 && hasScan) { - ColumnCommand* col = dynamic_cast(filterSteps[0].get()); - - if ((col != NULL) && (col->getFilterCount() == 0) && (col->getLBID() != 0)) { - // stored in last pos in relLBID[] and asyncLoaded[] - uint64_t p = projectCount; - asyncLoaded[p] = asyncLoaded[p] && (relLBID[p] % blocksReadAhead !=0); - relLBID[p] += col->getWidth(); - if (!asyncLoaded[p] && col->willPrefetch()) { - loadBlockAsync(col->getLBID(), - versionInfo, - txnID, - col->getCompType(), - &cachedIO, - &physIO, - LBIDTrace, - sessionID, - &counterLock, - &busyLoaderCount, - &vssCache); - asyncLoaded[p] = true; - } - asyncLoadProjectColumns(); + // if only one scan step which has no predicate, async load all columns + if (filterCount == 1 && hasScan) { + ColumnCommand* col = dynamic_cast(filterSteps[0].get()); + + if ((col != NULL) && (col->getFilterCount() == 0) && (col->getLBID() != 0)) { + // stored in last pos in relLBID[] and asyncLoaded[] + uint64_t p = projectCount; + asyncLoaded[p] = asyncLoaded[p] && (relLBID[p] % blocksReadAhead !=0); + relLBID[p] += col->getWidth(); + if (!asyncLoaded[p] && col->willPrefetch()) { + loadBlockAsync(col->getLBID(), + versionNum, + txnID, + col->getCompType(), + &cachedIO, + &physIO, + LBIDTrace, + sessionID, + &counterLock, + &busyLoaderCount, + &vssCache); + asyncLoaded[p] = true; } + asyncLoadProjectColumns(); } + } #ifdef PRIMPROC_STOPWATCH - stopwatch->stop("BatchPrimitiveProcessor::execute first part"); - stopwatch->start("BatchPrimitiveProcessor::execute second part"); +stopwatch->stop("BatchPrimitiveProcessor::execute first part"); +stopwatch->start("BatchPrimitiveProcessor::execute second part"); #endif - // filters use relrids and values for intermediate results. - if (bop == BOP_AND) - for (j = 0; j < filterCount; ++j) - { + // filters use relrids and values for intermediate results. + if (bop == BOP_AND) + for (j = 0; j < filterCount; ++j) + { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("- filterSteps[j]->execute()"); - filterSteps[j]->execute(); - stopwatch->stop("- filterSteps[j]->execute()"); + stopwatch->start("- filterSteps[j]->execute()"); + filterSteps[j]->execute(); + stopwatch->stop("- filterSteps[j]->execute()"); #else - filterSteps[j]->execute(); + filterSteps[j]->execute(); #endif + } + else { // BOP_OR + + /* XXXPAT: This is a hacky impl of OR logic. Each filter is configured to + be a scan operation on init. This code runs each independently and + unions their output ridlists using accumulator. At the end it turns + accumulator into a final ridlist for subsequent steps. + + If there's a join or a passthru command in the projection list, the + values array has to contain values from the last filter step. In that + case, the last filter step isn't part of the "OR" filter processing. + JLF has added it to prep those operations, not to be a filter. + + 7/7/09 update: the multiple-table join required relocating the join op. It's + no longer necessary to add the loader columncommand to the filter array. + */ + + bool accumulator[LOGICAL_BLOCK_RIDS]; +// uint realFilterCount = ((forHJ || hasPassThru) ? filterCount - 1 : filterCount); + uint realFilterCount = filterCount; + + for (i = 0; i < LOGICAL_BLOCK_RIDS; i++) + accumulator[i] = false; + + if (!hasScan) // there are input rids + for (i = 0; i < ridCount; i++) + accumulator[relRids[i]] = true; + ridCount = 0; + for (i = 0; i < realFilterCount; ++i) { + filterSteps[i]->execute(); + if (! filterSteps[i]->filterFeeder()) + { + for (j = 0; j < ridCount; j++) + accumulator[relRids[j]] = true; + ridCount = 0; } - else { // BOP_OR - - /* XXXPAT: This is a hacky impl of OR logic. Each filter is configured to - be a scan operation on init. This code runs each independently and - unions their output ridlists using accumulator. At the end it turns - accumulator into a final ridlist for subsequent steps. - - If there's a join or a passthru command in the projection list, the - values array has to contain values from the last filter step. In that - case, the last filter step isn't part of the "OR" filter processing. - JLF has added it to prep those operations, not to be a filter. - - 7/7/09 update: the multiple-table join required relocating the join op. It's - no longer necessary to add the loader columncommand to the filter array. - */ - - bool accumulator[LOGICAL_BLOCK_RIDS]; -// uint32_t realFilterCount = ((forHJ || hasPassThru) ? filterCount - 1 : filterCount); - uint32_t realFilterCount = filterCount; - - for (i = 0; i < LOGICAL_BLOCK_RIDS; i++) - accumulator[i] = false; - - if (!hasScan) // there are input rids - for (i = 0; i < ridCount; i++) - accumulator[relRids[i]] = true; - ridCount = 0; - for (i = 0; i < realFilterCount; ++i) { - filterSteps[i]->execute(); - if (! filterSteps[i]->filterFeeder()) - { - for (j = 0; j < ridCount; j++) - accumulator[relRids[j]] = true; - ridCount = 0; - } - } - for (ridMap = 0, i = 0; i < LOGICAL_BLOCK_RIDS; ++i) { - if (accumulator[i]) { - relRids[ridCount] = i; - ridMap |= 1 << (relRids[ridCount] >> 10); - ++ridCount; - } + } + for (ridMap = 0, i = 0; i < LOGICAL_BLOCK_RIDS; ++i) { + if (accumulator[i]) { + relRids[ridCount] = i; + ridMap |= 1 << (relRids[ridCount] >> 10); + ++ridCount; } } + } #ifdef PRIMPROC_STOPWATCH - stopwatch->stop("BatchPrimitiveProcessor::execute second part"); - stopwatch->start("BatchPrimitiveProcessor::execute third part"); +stopwatch->stop("BatchPrimitiveProcessor::execute second part"); +stopwatch->start("BatchPrimitiveProcessor::execute third part"); #endif - if (doJoin && ot != ROW_GROUP) - { + if (doJoin && ot != ROW_GROUP) + { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("- executeJoin"); - executeJoin(); - stopwatch->stop("- executeJoin"); + stopwatch->start("- executeJoin"); + executeJoin(); + stopwatch->stop("- executeJoin"); #else - executeJoin(); + executeJoin(); #endif - } + } - if (projectCount > 0 || ot == ROW_GROUP) - { + if (projectCount > 0 || ot == ROW_GROUP) + { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("- writeProjectionPreamble"); - writeProjectionPreamble(); - stopwatch->stop("- writeProjectionPreamble"); + stopwatch->start("- writeProjectionPreamble"); + writeProjectionPreamble(); + stopwatch->stop("- writeProjectionPreamble"); #else - writeProjectionPreamble(); + writeProjectionPreamble(); #endif - } + } - // async load blocks for project phase, if not alread loaded - if (ridCount > 0) - { + // async load blocks for project phase, if not alread loaded + if (ridCount > 0) + { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("- asyncLoadProjectColumns"); - asyncLoadProjectColumns(); - stopwatch->stop("- asyncLoadProjectColumns"); + stopwatch->start("- asyncLoadProjectColumns"); + asyncLoadProjectColumns(); + stopwatch->stop("- asyncLoadProjectColumns"); #else - asyncLoadProjectColumns(); + asyncLoadProjectColumns(); #endif - } + } #ifdef PRIMPROC_STOPWATCH - stopwatch->stop("BatchPrimitiveProcessor::execute third part"); - stopwatch->start("BatchPrimitiveProcessor::execute fourth part"); +stopwatch->stop("BatchPrimitiveProcessor::execute third part"); +stopwatch->start("BatchPrimitiveProcessor::execute fourth part"); #endif - // projection commands read relrids and write output directly to a rowgroup - // or the serialized bytestream - if (ot != ROW_GROUP) - for (j = 0; j < projectCount; ++j) - { - projectSteps[j]->project(); - } - else { - /* Function & Expression group 1 processing - - project for FE1 - - execute FE1 row by row - - if return value = true, map input row into the projection RG, adjust ridlist - */ + // projection commands read relrids and write output directly to a rowgroup + // or the serialized bytestream + if (ot != ROW_GROUP) + for (j = 0; j < projectCount; ++j) + { + projectSteps[j]->project(); + } + else { + /* Function & Expression group 1 processing + - project for FE1 + - execute FE1 row by row + - if return value = true, map input row into the projection RG, adjust ridlist + */ #ifdef PRIMPROC_STOPWATCH - stopwatch->start("- if(ot != ROW_GROUP) else"); + stopwatch->start("- if(ot != ROW_GROUP) else"); #endif - outputRG.resetRowGroup(baseRid); - if (fe1) { - uint32_t newRidCount = 0; - fe1Input.resetRowGroup(baseRid); - fe1Input.setRowCount(ridCount); - fe1Input.getRow(0, &fe1In); - outputRG.getRow(0, &fe1Out); - for (j = 0; j < projectCount; j++) - if (projectForFE1[j] != -1) - projectSteps[j]->projectIntoRowGroup(fe1Input, projectForFE1[j]); - for (j = 0; j < ridCount; j++, fe1In.nextRow()) - if (fe1->evaluate(&fe1In)) { - applyMapping(fe1ToProjection, fe1In, &fe1Out); - relRids[newRidCount] = relRids[j]; - values[newRidCount++] = values[j]; - fe1Out.nextRow(); - } - ridCount = newRidCount; - } - outputRG.setRowCount(ridCount); - if (sendRidsAtDelivery) { - Row r; - outputRG.initRow(&r); - outputRG.getRow(0, &r); - for (j = 0; j < ridCount; ++j) { - r.setRid(relRids[j]); - r.nextRow(); + outputRG.resetRowGroup(baseRid); + if (fe1) { + uint newRidCount = 0; + fe1Input.resetRowGroup(baseRid); + fe1Input.setRowCount(ridCount); + fe1Input.getRow(0, &fe1In); + outputRG.getRow(0, &fe1Out); + for (j = 0; j < projectCount; j++) + if (projectForFE1[j] != -1) + projectSteps[j]->projectIntoRowGroup(fe1Input, projectForFE1[j]); + for (j = 0; j < ridCount; j++, fe1In.nextRow()) + if (fe1->evaluate(&fe1In)) { + applyMapping(fe1ToProjection, fe1In, &fe1Out); + relRids[newRidCount] = relRids[j]; + values[newRidCount++] = values[j]; + fe1Out.nextRow(); } + ridCount = newRidCount; + } + outputRG.setRowCount(ridCount); + if (sendRidsAtDelivery) { + Row r; + outputRG.initRow(&r); + outputRG.getRow(0, &r); + for (j = 0; j < ridCount; ++j) { + r.setRid(relRids[j] + baseRid); + r.nextRow(); } + } - /* 7/7/09 PL: I Changed the projection alg to reduce block touches when there's - a join. The key columns get projected first, the join is executed to further - reduce the ridlist, then the rest of the columns get projected */ + /* 7/7/09 PL: I Changed the projection alg to reduce block touches when there's + a join. The key columns get projected first, the join is executed to further + reduce the ridlist, then the rest of the columns get projected */ - if (!doJoin) - { - for (j = 0; j < projectCount; ++j) { + if (!doJoin) + { + for (j = 0; j < projectCount; ++j) { // cout << "projectionMap[" << j << "] = " << projectionMap[j] << endl; - if (projectionMap[j] != -1) { + if (projectionMap[j] != -1) { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("-- projectIntoRowGroup"); - projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); - stopwatch->stop("-- projectIntoRowGroup"); + stopwatch->start("-- projectIntoRowGroup"); + projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); + stopwatch->stop("-- projectIntoRowGroup"); #else - projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); + projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); #endif - } -// else -// cout << " no target found for OID " << projectSteps[j]->getOID() << endl; } +// else +// cout << " no target found for OID " << projectSteps[j]->getOID() << endl; } - else { - /* project the key columns. If there's the filter IN the join, project everything. */ - for (j = 0; j < projectCount; j++) - if (keyColumnProj[j] || (hasJoinFEFilters && projectionMap[j] != -1)) - { + } + else { + /* project the key columns. If there's the filter IN the join, project everything. */ + for (j = 0; j < projectCount; j++) + if (keyColumnProj[j] || (hasJoinFEFilters && projectionMap[j] != -1)) + { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("-- projectIntoRowGroup"); - projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); - stopwatch->stop("-- projectIntoRowGroup"); + stopwatch->start("-- projectIntoRowGroup"); + projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); + stopwatch->stop("-- projectIntoRowGroup"); #else - projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); + projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); #endif - } + } #ifdef PRIMPROC_STOPWATCH - stopwatch->start("-- executeTupleJoin()"); - executeTupleJoin(); - stopwatch->stop("-- executeTupleJoin()"); + stopwatch->start("-- executeTupleJoin()"); + executeTupleJoin(); + stopwatch->stop("-- executeTupleJoin()"); #else - executeTupleJoin(); + executeTupleJoin(); #endif - /* project the non-key columns */ - for (j = 0; j < projectCount; ++j) + /* project the non-key columns */ + for (j = 0; j < projectCount; ++j) + { + if ((!keyColumnProj[j] && projectionMap[j] != -1) && !hasJoinFEFilters) { - if ((!keyColumnProj[j] && projectionMap[j] != -1) && !hasJoinFEFilters) - { #ifdef PRIMPROC_STOPWATCH - stopwatch->start("-- projectIntoRowGroup"); - projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); - stopwatch->stop("-- projectIntoRowGroup"); + stopwatch->start("-- projectIntoRowGroup"); + projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); + stopwatch->stop("-- projectIntoRowGroup"); #else - projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); + projectSteps[j]->projectIntoRowGroup(outputRG, projectionMap[j]); #endif - } } } + } - /* The RowGroup is fully joined at this point. - Add additional RowGroup processing here. - TODO: Try to clean up all of the switching */ - - if (doJoin && (fe2 || fAggregator)) { - bool moreRGs = true; - ByteStream preamble = *serialized; - initGJRG(); - while (moreRGs && !sendThread->aborted()) { - /* - generate 1 rowgroup (8192 rows max) of joined rows - if there's an FE2, run it - -pack results into a new rowgroup - -if there are < 8192 rows in the new RG, continue - if there's an agg, run it - send the result - */ - resetGJRG(); - moreRGs = generateJoinedRowGroup(baseJRow); - *serialized << (uint8_t) !moreRGs; - - if (fe2) { - /* functionize this -> processFE2()*/ - fe2Output.resetRowGroup(baseRid); - fe2Output.setDBRoot(dbRoot); - fe2Output.getRow(0, &fe2Out); - fe2Input->getRow(0, &fe2In); - for (j = 0; j < joinedRG.getRowCount(); j++, fe2In.nextRow()) - if (fe2->evaluate(&fe2In)) { - applyMapping(fe2Mapping, fe2In, &fe2Out); - fe2Out.setRid(fe2In.getRelRid()); - fe2Output.incRowCount(); - fe2Out.nextRow(); - } - } - RowGroup &nextRG = (fe2 ? fe2Output : joinedRG); - nextRG.setDBRoot(dbRoot); - if (fAggregator) { - fAggregator->addRowGroup(&nextRG); - - if ((currentBlockOffset+1) == count && moreRGs == false) { // @bug4507, 8k - fAggregator->loadResult(*serialized); // @bug4507, 8k - } // @bug4507, 8k - else if (utils::MonitorProcMem::isMemAvailable()) { // @bug4507, 8k - fAggregator->loadEmptySet(*serialized); // @bug4507, 8k - } // @bug4507, 8k - else { // @bug4507, 8k - fAggregator->loadResult(*serialized); // @bug4507, 8k - fAggregator->reset(); // @bug4507, 8k - } // @bug4507, 8k - } - else { - //cerr <<" * serialzing " << nextRG.toString() << endl; - nextRG.serializeRGData(*serialized); - } - /* send the msg & reinit the BS */ - if (moreRGs) { - sendResponse(); - serialized.reset(new ByteStream()); - *serialized = preamble; - } - } - if (hasSmallOuterJoin) { - *serialized << ridCount; - for (i = 0; i < joinerCount; i++) - for (j = 0; j < ridCount; ++j) - serializeInlineVector(*serialized, - tSmallSideMatches[i][j]); +// copy InputRGColumns does not behavior as expected, the valueColumn is not set +// disable for now. +// if (hasRowGroup) +// copyInputRGColumns(); + + /* The RowGroup is fully joined at this point. + Add additional RowGroup processing here. + TODO: Try to clean up all of the switching */ + + if (doJoin && (fe2 || fAggregator)) { + bool moreRGs = true; + ByteStream preamble = *serialized; + initGJRG(); + while (moreRGs && !sendThread->aborted()) { + /* + generate 1 rowgroup (8192 rows max) of joined rows + if there's an FE2, run it + -pack results into a new rowgroup + -if there are < 8192 rows in the new RG, continue + if there's an agg, run it + send the result + */ + resetGJRG(); + moreRGs = generateJoinedRowGroup(baseJRow); + *serialized << (uint8_t) !moreRGs; + + if (fe2) { + /* functionize this -> processFE2()*/ + fe2Output.resetRowGroup(baseRid); + fe2Output.setDBRoot(dbRoot); + fe2Output.getRow(0, &fe2Out); + fe2Input->getRow(0, &fe2In); + for (j = 0; j < joinedRG.getRowCount(); j++, fe2In.nextRow()) + if (fe2->evaluate(&fe2In)) { + applyMapping(fe2Mapping, fe2In, &fe2Out); + fe2Out.setRid(fe2In.getRid()); + fe2Output.incRowCount(); + fe2Out.nextRow(); + } } - } - - if (!doJoin && fe2) { - /* functionize this -> processFE2() */ - fe2Output.resetRowGroup(baseRid); - fe2Output.getRow(0, &fe2Out); - fe2Input->getRow(0, &fe2In); - //cerr << "input row: " << fe2In.toString() << endl; - for (j = 0; j < outputRG.getRowCount(); j++, fe2In.nextRow()) { - if (fe2->evaluate(&fe2In)) { - applyMapping(fe2Mapping, fe2In, &fe2Out); - //cerr << " passed. output row: " << fe2Out.toString() << endl; - fe2Out.setRid (fe2In.getRelRid()); - fe2Output.incRowCount(); - fe2Out.nextRow(); - } + RowGroup &nextRG = (fe2 ? fe2Output : joinedRG); + nextRG.setDBRoot(dbRoot); + if (fAggregator) { + fAggregator->addRowGroup(&nextRG); + + if ((currentBlockOffset+1) == count && moreRGs == false) { // @bug4507, 8k + fAggregator->loadResult(*serialized); // @bug4507, 8k + } // @bug4507, 8k + else if (MonitorProcMem::flushAggregationMem()) { // @bug4507, 8k + fAggregator->loadResult(*serialized); // @bug4507, 8k + fAggregator->reset(); // @bug4507, 8k + } // @bug4507, 8k + else { // @bug4507, 8k + fAggregator->loadEmptySet(*serialized); // @bug4507, 8k + } // @bug4507, 8k } - if (!fAggregator) { - *serialized << (uint8_t) 1; // the "count this msg" var - fe2Output.setDBRoot(dbRoot); - fe2Output.serializeRGData(*serialized); - //*serialized << fe2Output.getDataSize(); - //serialized->append(fe2Output.getData(), fe2Output.getDataSize()); + else { + *serialized << nextRG.getDataSize(); + serialized->append(nextRG.getData(), nextRG.getDataSize()); + } + /* send the msg & reinit the BS */ + if (moreRGs) { + sendResponse(); + serialized.reset(new ByteStream()); + *serialized = preamble; } } - if (!doJoin && fAggregator) { + if (hasSmallOuterJoin) { + *serialized << ridCount; + for (i = 0; i < joinerCount; i++) + for (j = 0; j < ridCount; ++j) + serializeInlineVector(*serialized, + tSmallSideMatches[i][j]); + } + } + + if (!doJoin && fe2) { + /* functionize this -> processFE2() */ + fe2Output.resetRowGroup(baseRid); + fe2Output.getRow(0, &fe2Out); + fe2Input->getRow(0, &fe2In); + for (j = 0; j < outputRG.getRowCount(); j++, fe2In.nextRow()) { + if (fe2->evaluate(&fe2In)) { + applyMapping(fe2Mapping, fe2In, &fe2Out); + fe2Out.setRid ( fe2In.getRid() ); + fe2Output.incRowCount(); + fe2Out.nextRow(); + } + } + if (!fAggregator) { *serialized << (uint8_t) 1; // the "count this msg" var - - RowGroup &toAggregate = (fe2 ? fe2Output : outputRG); - //toAggregate.convertToInlineDataInPlace(); - - if (fe2) - fe2Output.setDBRoot(dbRoot); - else - outputRG.setDBRoot(dbRoot); - fAggregator->addRowGroup(&toAggregate); - if ((currentBlockOffset+1) == count) { // @bug4507, 8k - fAggregator->loadResult(*serialized); // @bug4507, 8k - } // @bug4507, 8k - else if (utils::MonitorProcMem::isMemAvailable()) { // @bug4507, 8k - fAggregator->loadEmptySet(*serialized); // @bug4507, 8k - } // @bug4507, 8k - else { // @bug4507, 8k - fAggregator->loadResult(*serialized); // @bug4507, 8k - fAggregator->reset(); // @bug4507, 8k - } // @bug4507, 8k + fe2Output.setDBRoot(dbRoot); + *serialized << fe2Output.getDataSize(); + serialized->append(fe2Output.getData(), fe2Output.getDataSize()); } + } - if (!fAggregator && !fe2) { - *serialized << (uint8_t) 1; // the "count this msg" var + if (!doJoin && fAggregator) { + *serialized << (uint8_t) 1; // the "count this msg" var + + if (fe2) + fe2Output.setDBRoot(dbRoot); + else outputRG.setDBRoot(dbRoot); - //cerr << "serializing " << outputRG.toString() << endl; - outputRG.serializeRGData(*serialized); - //*serialized << outputRG.getDataSize(); - //serialized->append(outputRG.getData(), outputRG.getDataSize()); - if (doJoin) { - for (i = 0; i < joinerCount; i++) { - for (j = 0; j < ridCount; ++j) { - serializeInlineVector(*serialized, - tSmallSideMatches[i][j]); - } + fAggregator->addRowGroup(&(fe2 ? fe2Output : outputRG)); + if ((currentBlockOffset+1) == count) { // @bug4507, 8k + fAggregator->loadResult(*serialized); // @bug4507, 8k + } // @bug4507, 8k + else if (MonitorProcMem::flushAggregationMem()) { // @bug4507, 8k + fAggregator->loadResult(*serialized); // @bug4507, 8k + fAggregator->reset(); // @bug4507, 8k + } // @bug4507, 8k + else { // @bug4507, 8k + fAggregator->loadEmptySet(*serialized); // @bug4507, 8k + } // @bug4507, 8k + } + + if (!fAggregator && !fe2) { + *serialized << (uint8_t) 1; // the "count this msg" var + outputRG.setDBRoot(dbRoot); + *serialized << outputRG.getDataSize(); + serialized->append(outputRG.getData(), outputRG.getDataSize()); + if (doJoin) { + for (i = 0; i < joinerCount; i++) { + for (j = 0; j < ridCount; ++j) { + serializeInlineVector(*serialized, + tSmallSideMatches[i][j]); } } } + } - // clear small side match vector - if (doJoin) { - for (i = 0; i < joinerCount; i++) - for (j = 0; j < ridCount; ++j) - tSmallSideMatches[i][j].clear(); - } + // clear small side match vector + if (doJoin) { + for (i = 0; i < joinerCount; i++) + for (j = 0; j < ridCount; ++j) + tSmallSideMatches[i][j].clear(); + } #ifdef PRIMPROC_STOPWATCH - stopwatch->stop("- if(ot != ROW_GROUP) else"); + stopwatch->stop("- if(ot != ROW_GROUP) else"); #endif - } + } - if (projectCount > 0 || ot == ROW_GROUP) { - *serialized << cachedIO; - cachedIO = 0; - *serialized << physIO; - physIO = 0; - *serialized << touchedBlocks; - touchedBlocks = 0; -// cout << "sent physIO=" << physIO << " cachedIO=" << cachedIO << + if (projectCount > 0 || ot == ROW_GROUP) { + *serialized << cachedIO; + cachedIO = 0; + *serialized << physIO; + physIO = 0; + *serialized << touchedBlocks; + touchedBlocks = 0; +// cout << "sent physIO=" << physIO << " cachedIO=" << cachedIO << // " touchedBlocks=" << touchedBlocks << endl; - } + } #ifdef PRIMPROC_STOPWATCH - stopwatch->stop("BatchPrimitiveProcessor::execute fourth part"); +stopwatch->stop("BatchPrimitiveProcessor::execute fourth part"); #endif } @@ -1428,10 +1554,10 @@ void BatchPrimitiveProcessor::execute() { #if 0 - /* This block of code will flush the problematic OIDs from the + /* This block of code will flush the problematic OIDs from the * cache. It seems to have no effect on the problem, so it's commented * for now. - * + * * This is currently thrown only on syscat queries. If we find the problem * in user tables also, we should avoid dropping entire OIDs if possible. * @@ -1444,12 +1570,12 @@ void BatchPrimitiveProcessor::execute() try { vector oids; uint32_t oid; - for (uint32_t i = 0; i < filterCount; i++) { + for (uint i = 0; i < filterCount; i++) { oid = filterSteps[i]->getOID(); if (oid > 0) oids.push_back(oid); } - for (uint32_t i = 0; i < projectCount; i++) { + for (uint i = 0; i < projectCount; i++) { oid = projectSteps[i]->getOID(); if (oid > 0) oids.push_back(oid); @@ -1462,7 +1588,7 @@ void BatchPrimitiveProcessor::execute() for (int i = 0; i < oids.size(); i++) os << oids[i] << " "; logger.logMessage(os.str()); -#endif +#endif for (int i = 0; i < fCacheCount; i++) { dbbc::blockCacheClient bc(*BRPp[i]); // bc.flushCache(); @@ -1478,9 +1604,9 @@ void BatchPrimitiveProcessor::execute() } catch (IDBExcept& iex) { - ostringstream os; + ostringstream os; os << iex.what() << endl; - writeErrorMsg(os.str(), iex.errorCode(), true, false); + writeErrorMsg(os.str(), iex.errorCode(), true, false); } catch(const std::exception& ex) { @@ -1500,7 +1626,7 @@ void BatchPrimitiveProcessor::writeErrorMsg(const string& error, uint16_t errCod ISMPacketHeader ism; PrimitiveHeader ph; - // we don't need every field of these headers. Init'ing them anyway + // we don't need every field of these headers. Init'ing them anyway // makes memory checkers happy. memset(&ism, 0, sizeof(ISMPacketHeader)); memset(&ph, 0, sizeof(PrimitiveHeader)); @@ -1525,7 +1651,7 @@ void BatchPrimitiveProcessor::writeProjectionPreamble() ISMPacketHeader ism; PrimitiveHeader ph; - // we don't need every field of these headers. Init'ing them anyway + // we don't need every field of these headers. Init'ing them anyway // makes memory checkers happy. memset(&ism, 0, sizeof(ISMPacketHeader)); memset(&ph, 0, sizeof(PrimitiveHeader)); @@ -1581,12 +1707,12 @@ void BatchPrimitiveProcessor::serializeElementTypes() } } -void BatchPrimitiveProcessor::serializeStrings() +void BatchPrimitiveProcessor::serializeStrings() { - + *serialized << ridCount; serialized->append((uint8_t *) absRids.get(), ridCount << 3); - for (uint32_t i = 0; i < ridCount; ++i) + for (uint i = 0; i < ridCount; ++i) *serialized << strValues[i]; } @@ -1612,7 +1738,7 @@ void BatchPrimitiveProcessor::makeResponse() ISMPacketHeader ism; PrimitiveHeader ph; - // we don't need every field of these headers. Init'ing them anyway + // we don't need every field of these headers. Init'ing them anyway // makes memory checkers happy. memset(&ism, 0, sizeof(ISMPacketHeader)); memset(&ph, 0, sizeof(PrimitiveHeader)); @@ -1641,19 +1767,17 @@ void BatchPrimitiveProcessor::makeResponse() /* results */ /* Take the rid and value arrays, munge into OutputType ot */ switch (ot) { - case BPS_ELEMENT_TYPE: - serializeElementTypes(); - break; - case STRING_ELEMENT_TYPE: - serializeStrings(); - break; - default: - { - ostringstream oss; - oss << "BPP: makeResponse(): Bad output type: " << ot; - throw logic_error(oss.str()); - } - //throw logic_error("BPP: makeResponse(): Bad output type"); + case BPS_ELEMENT_TYPE: + serializeElementTypes(); break; + case STRING_ELEMENT_TYPE: + serializeStrings(); break; + default: +{ +ostringstream oss; +oss << "BPP: makeResponse(): Bad output type: " << ot; +throw logic_error(oss.str()); +} + //throw logic_error("BPP: makeResponse(): Bad output type"); } *serialized << cachedIO; @@ -1663,10 +1787,35 @@ void BatchPrimitiveProcessor::makeResponse() *serialized << touchedBlocks; touchedBlocks = 0; -// cout << "sent physIO=" << physIO << " cachedIO=" << cachedIO << +// cout << "sent physIO=" << physIO << " cachedIO=" << cachedIO << // " touchedBlocks=" << touchedBlocks << endl; } +void BatchPrimitiveProcessor::initFromRowGroup() +{ + Row r; + + ridCount = inputRG.getRowCount(); + ridMap = 0; + inputRG.initRow(&r); + + /* init rid arrays */ + inputRG.getRow(0, &r); + for (uint i = 0; i < ridCount; i++, r.nextRow()) { + absRids[i] = r.getRid(); + relRids[i] = r.getRid() & 0x1fff; + ridMap |= 1 << (relRids[i] >> 10); + } + baseRid = absRids[0] & 0xffffffffffffe000ULL; + + /* init values array */ + if (valueColumn != 0) { + inputRG.getRow(0, &r); + for (uint i = 0; i < ridCount; i++, r.nextRow()) + values[i] = r.getIntField(valueColumn); + } +} + int BatchPrimitiveProcessor::operator()() { if (currentBlockOffset == 0) { @@ -1741,24 +1890,7 @@ int BatchPrimitiveProcessor::operator()() sockIndex = (sockIndex + 1) % connectionsPerUM; nextLBID(); - - /* Base RIDs are now a combination of partition#, segment#, extent#, and block#. */ - uint32_t partNum; - uint16_t segNum; - uint8_t extentNum; - uint16_t blockNum; - rowgroup::getLocationFromRid(baseRid, &partNum, &segNum, &extentNum, &blockNum); - /* - cout << "baseRid=" << baseRid << " partNum=" << partNum << " segNum=" << segNum << - " extentNum=" << (int) extentNum - << " blockNum=" << blockNum << endl; - */ - blockNum++; - baseRid = rowgroup::convertToRid(partNum, segNum, extentNum, blockNum); - /* - cout << "-- baseRid=" << baseRid << " partNum=" << partNum << " extentNum=" << (int) extentNum - << " blockNum=" << blockNum << endl; - */ + baseRid += BLOCK_SIZE; } vssCache.clear(); @@ -1777,24 +1909,19 @@ int BatchPrimitiveProcessor::operator()() void BatchPrimitiveProcessor::allocLargeBuffers() { if (ot == ROW_GROUP && !outRowGroupData) { - //outputRG.setUseStringTable(true); - outRowGroupData.reset(new RGData(outputRG)); + outRowGroupData.reset(new uint8_t[outputRG.getMaxDataSize()]); outputRG.setData(outRowGroupData.get()); } if (fe1 && !fe1Data) { - //fe1Input.setUseStringTable(true); - fe1Data.reset(new RGData(fe1Input)); - //fe1Data.reset(new uint8_t[fe1Input.getMaxDataSize()]); + fe1Data.reset(new uint8_t[fe1Input.getMaxDataSize()]); fe1Input.setData(fe1Data.get()); } if (fe2 && !fe2Data) { - //fe2Output.setUseStringTable(true); - fe2Data.reset(new RGData(fe2Output)); + fe2Data.reset(new uint8_t[fe2Output.getMaxDataSize()]); fe2Output.setData(fe2Data.get()); } if (getTupleJoinRowGroupData && !joinedRGMem) { - //joinedRG.setUseStringTable(true); - joinedRGMem.reset(new RGData(joinedRG)); + joinedRGMem.reset(new uint8_t[joinedRG.getMaxDataSize()]); joinedRG.setData(joinedRGMem.get()); } } @@ -1802,19 +1929,19 @@ void BatchPrimitiveProcessor::allocLargeBuffers() void BatchPrimitiveProcessor::freeLargeBuffers() { /* Get rid of large buffers */ - if (ot == ROW_GROUP && outputRG.getMaxDataSizeWithStrings() > maxIdleBufferSize) + if (ot == ROW_GROUP && outputRG.getMaxDataSize() > maxIdleBufferSize) outRowGroupData.reset(); - if (fe1 && fe1Input.getMaxDataSizeWithStrings() > maxIdleBufferSize) + if (fe1 && fe1Input.getMaxDataSize() > maxIdleBufferSize) fe1Data.reset(); - if (fe2 && fe2Output.getMaxDataSizeWithStrings() > maxIdleBufferSize) + if (fe2 && fe2Output.getMaxDataSize() > maxIdleBufferSize) fe2Data.reset(); - if (getTupleJoinRowGroupData && joinedRG.getMaxDataSizeWithStrings() > maxIdleBufferSize) + if (getTupleJoinRowGroupData && joinedRG.getMaxDataSize() > maxIdleBufferSize) joinedRGMem.reset(); } void BatchPrimitiveProcessor::nextLBID() { - uint32_t i; + uint i; for (i = 0; i < filterCount; i++) filterSteps[i]->nextLBID(); @@ -1825,13 +1952,13 @@ void BatchPrimitiveProcessor::nextLBID() SBPP BatchPrimitiveProcessor::duplicate() { SBPP bpp; - uint32_t i; + uint i; // cout << "duplicating a bpp\n"; bpp.reset(new BatchPrimitiveProcessor()); bpp->ot = ot; - bpp->versionInfo = versionInfo; + bpp->versionNum = versionNum; bpp->txnID = txnID; bpp->sessionID = sessionID; bpp->stepID = stepID; @@ -1845,6 +1972,10 @@ SBPP BatchPrimitiveProcessor::duplicate() bpp->filtOnString = filtOnString; bpp->hasRowGroup = hasRowGroup; bpp->getTupleJoinRowGroupData = getTupleJoinRowGroupData; + if (hasRowGroup) { + bpp->valueColumn = valueColumn; + bpp->inputRG = inputRG; + } bpp->bop = bop; bpp->hasPassThru = hasPassThru; bpp->forHJ = forHJ; @@ -1895,7 +2026,6 @@ SBPP BatchPrimitiveProcessor::duplicate() bpp->smallSideRowLengths = smallSideRowLengths; bpp->smallSideRowData = smallSideRowData; bpp->smallNullRowData = smallNullRowData; - bpp->smallNullPointers = smallNullPointers; bpp->joinedRG = joinedRG; } } @@ -1920,7 +2050,7 @@ SBPP BatchPrimitiveProcessor::duplicate() { bpp->fAggregateRG = fAggregateRG; bpp->fAggregator.reset(new RowAggregation( - fAggregator->getGroupByCols(), fAggregator->getAggFunctions())); + fAggregator->getGroupByCols(), fAggregator->getAggFunctions())); } bpp->sendRidsAtDelivery = sendRidsAtDelivery; @@ -1935,14 +2065,13 @@ SBPP BatchPrimitiveProcessor::duplicate() return bpp; } -#if 0 bool BatchPrimitiveProcessor::operator==(const BatchPrimitiveProcessor &bpp) const { - uint32_t i; + uint i; if (ot != bpp.ot) return false; - if (versionInfo != bpp.versionInfo) + if (versionNum != bpp.versionNum) return false; if (txnID != bpp.txnID) return false; @@ -1967,9 +2096,9 @@ bool BatchPrimitiveProcessor::operator==(const BatchPrimitiveProcessor &bpp) con if (hasScan != bpp.hasScan) return false; if (hasFilterStep != bpp.hasFilterStep) - return false; + return false; if (filtOnString != bpp.filtOnString) - return false; + return false; if (doJoin != bpp.doJoin) return false; if (doJoin) @@ -1984,12 +2113,10 @@ bool BatchPrimitiveProcessor::operator==(const BatchPrimitiveProcessor &bpp) con return false; return true; } -#endif - void BatchPrimitiveProcessor::asyncLoadProjectColumns() { - // relLBID is the LBID related to the primMsg->LBID, + // relLBID is the LBID related to the primMsg->LBID, // it is used to keep the read ahead boundary for asyncLoads // 1. scan driven case: load blocks in # to (# + blocksReadAhead - 1) range, // where # is a multiple of ColScanReadAheadBlocks in Calpont.xml @@ -2002,58 +2129,60 @@ void BatchPrimitiveProcessor::asyncLoadProjectColumns() asyncLoaded[i] = asyncLoaded[i] && (relLBID[i] % blocksReadAhead !=0); relLBID[i] += col->getWidth(); if (!asyncLoaded[i] && col->willPrefetch()) { - loadBlockAsync(col->getLBID(), - versionInfo, - txnID, - col->getCompType(), - &cachedIO, - &physIO, - LBIDTrace, - sessionID, - &counterLock, - &busyLoaderCount, - &vssCache); + loadBlockAsync(col->getLBID(), + versionNum, + txnID, + col->getCompType(), + &cachedIO, + &physIO, + LBIDTrace, + sessionID, + &counterLock, + &busyLoaderCount, + &vssCache); asyncLoaded[i] = true; } } } } -bool BatchPrimitiveProcessor::generateJoinedRowGroup(rowgroup::Row &baseRow, const uint32_t depth) +bool BatchPrimitiveProcessor::generateJoinedRowGroup(rowgroup::Row &baseRow, const uint depth) { + uint64_t rowOffset; Row &smallRow = smallRows[depth]; const bool lowestLvl = (depth == joinerCount - 1); + const uint emptySize = smallSideRGs[depth].getEmptySize(); + const uint smallRowSize = smallRow.getSize(); + const shared_array &rowDataAtThisLvl = smallSideRowData[depth]; while (gjrgRowNumber < ridCount && - gjrgPlaceHolders[depth] < tSmallSideMatches[depth][gjrgRowNumber].size() && - !gjrgFull) { + gjrgPlaceHolders[depth] < tSmallSideMatches[depth][gjrgRowNumber].size() && + !gjrgFull) { const vector &results = tSmallSideMatches[depth][gjrgRowNumber]; - const uint32_t size = results.size(); + const uint size = results.size(); if (depth == 0) { outputRG.getRow(gjrgRowNumber, &largeRow); applyMapping(gjrgMappings[joinerCount], largeRow, &baseRow); - baseRow.setRid(largeRow.getRelRid()); + baseRow.setRid(largeRow.getRid()); } - //cout << "rowNum = " << gjrgRowNumber << " at depth " << depth << " size is " << size << endl; - for (uint32_t &i = gjrgPlaceHolders[depth]; i < size && !gjrgFull; i++) { - if (results[i] != (uint32_t) -1) { - smallSideRGs[depth].getRow(results[i], &smallRow); - //rowOffset = ((uint64_t) results[i]) * smallRowSize; - //smallRow.setData(&rowDataAtThisLvl.rowData[rowOffset] + emptySize); +// cout << "rowNum = " << gjrgRowNumber << " at depth " << depth << " size is " << size << endl; + for (uint &i = gjrgPlaceHolders[depth]; i < size && !gjrgFull; i++) { + if (results[i] != (uint) -1) { + rowOffset = ((uint64_t) results[i]) * smallRowSize; + smallRow.setData(&rowDataAtThisLvl[rowOffset] + emptySize); } - else - smallRow.setPointer(smallNullPointers[depth]); - - //cout << "small row: " << smallRow.toString() << endl; + else { + smallRow.setData(smallNullRowData[depth].get()); + } +// cout << "small row: " << smallRow.toString(p) << endl; applyMapping(gjrgMappings[depth], smallRow, &baseRow); if (!lowestLvl) generateJoinedRowGroup(baseRow, depth + 1); else { - copyRow(baseRow, &joinedRow); - //memcpy(joinedRow.getData(), baseRow.getData(), joinedRow.getSize()); - //cerr << "joined row " << joinedRG.getRowCount() << ": " << joinedRow.toString() << endl; + memcpy(joinedRow.getData(), baseRow.getData(), joinedRow.getSize()); + //cout << "joined row " << joinedRG.getRowCount() << ": " << joinedRow.toString() << endl; joinedRow.nextRow(); joinedRG.incRowCount(); if (joinedRG.getRowCount() == 8192) { @@ -2071,7 +2200,7 @@ bool BatchPrimitiveProcessor::generateJoinedRowGroup(rowgroup::Row &baseRow, con } } // if (depth == 0) -// cout << "gjrg returning " << (uint32_t) gjrgFull << endl; +// cout << "gjrg returning " << (uint) gjrgFull << endl; if (!gjrgFull) gjrgPlaceHolders[depth] = 0; return gjrgFull; @@ -2087,12 +2216,12 @@ void BatchPrimitiveProcessor::resetGJRG() void BatchPrimitiveProcessor::initGJRG() { - for (uint32_t z = 0; z < joinerCount; z++) + for (uint z = 0; z < joinerCount; z++) gjrgPlaceHolders[z] = 0; gjrgRowNumber = 0; } -inline void BatchPrimitiveProcessor::getJoinResults(const Row &r, uint32_t jIndex, vector& v) +inline void BatchPrimitiveProcessor::getJoinResults(const Row &r, uint jIndex, vector& v) { if (!typelessJoin[jIndex]) { if (r.isNullValue(largeSideKeyColumns[jIndex])) { @@ -2106,14 +2235,7 @@ inline void BatchPrimitiveProcessor::getJoinResults(const Row &r, uint32_t jInde else return; } - uint64_t largeKey; - uint32_t colIndex = largeSideKeyColumns[jIndex]; - if (r.isUnsigned(colIndex)) { - largeKey = r.getUintField(colIndex); - } - else { - largeKey = r.getIntField(colIndex); - } + uint64_t largeKey = r.getIntField(largeSideKeyColumns[jIndex]); pair range = tJoiners[jIndex]->equal_range(largeKey); for (; range.first != range.second; ++range.first) v.push_back(range.first->second); @@ -2127,7 +2249,7 @@ inline void BatchPrimitiveProcessor::getJoinResults(const Row &r, uint32_t jInde /* Bug 3524. Large-side NULL + ANTI join matches everything. */ if (joinTypes[jIndex] & ANTI) { bool hasNullValue = false; - for (uint32_t i = 0; i < tlLargeSideKeyColumns[jIndex].size(); i++) + for (uint i = 0; i < tlLargeSideKeyColumns[jIndex].size(); i++) if (r.isNullValue(tlLargeSideKeyColumns[jIndex][i])) { hasNullValue = true; break; @@ -2141,27 +2263,27 @@ inline void BatchPrimitiveProcessor::getJoinResults(const Row &r, uint32_t jInde } TypelessData largeKey = makeTypelessKey(r, tlLargeSideKeyColumns[jIndex], - tlKeyLengths[jIndex], &tmpKeyAllocators[jIndex]); + tlKeyLengths[jIndex], &tmpKeyAllocators[jIndex]); pair range = - tlJoiners[jIndex]->equal_range(largeKey); + tlJoiners[jIndex]->equal_range(largeKey); for (; range.first != range.second; ++range.first) v.push_back(range.first->second); } } -void BatchPrimitiveProcessor::buildVSSCache(uint32_t loopCount) +void BatchPrimitiveProcessor::buildVSSCache(uint loopCount) { vector lbidList; vector vssData; - uint32_t i; + uint i; int rc; - + for (i = 0; i < filterCount; i++) filterSteps[i]->getLBIDList(loopCount, &lbidList); for (i = 0; i < projectCount; i++) projectSteps[i]->getLBIDList(loopCount, &lbidList); - - rc = brm->bulkVSSLookup(lbidList, versionInfo, (int) txnID, &vssData); + + rc = brm->bulkVSSLookup(lbidList, (int) versionNum, (int) txnID, &vssData); if (rc == 0) for (i = 0; i < vssData.size(); i++) vssCache.insert(make_pair(lbidList[i], vssData[i])); diff --git a/primitives/primproc/batchprimitiveprocessor.h b/primitives/primproc/batchprimitiveprocessor.h index c7d8d815..fe840918 100644 --- a/primitives/primproc/batchprimitiveprocessor.h +++ b/primitives/primproc/batchprimitiveprocessor.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: batchprimitiveprocessor.h 2132 2013-07-17 20:06:10Z pleblanc $ +// $Id: batchprimitiveprocessor.h 1917 2012-08-01 15:58:55Z dhall $ // C++ Interface: batchprimitiveprocessor // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -65,7 +65,7 @@ namespace primitiveprocessor typedef boost::shared_ptr SBPP; -class scalar_exception : public std::exception { +class scalar_exception : public std::exception { const char * what() const throw() { return "Not a scalar subquery."; } }; @@ -90,23 +90,21 @@ class BatchPrimitiveProcessor void initBPP(messageqcpp::ByteStream &); void resetBPP(messageqcpp::ByteStream &, const SP_UM_MUTEX& wLock, const SP_UM_IOSOCK& outputSock); void addToJoiner(messageqcpp::ByteStream &); - int endOfJoiner(); + void endOfJoiner(); int operator()(); void setLBIDForScan(uint64_t rid); /* Duplicate() returns a deep copy of this object as it was init'd by initBPP. It's thread-safe wrt resetBPP. */ SBPP duplicate(); - - /* These need to be updated */ - //bool operator==(const BatchPrimitiveProcessor&) const; - //inline bool operator!=(const BatchPrimitiveProcessor& bpp) const - //{ - // return !(*this == bpp); - //} - - inline uint32_t getSessionID() { return sessionID; } - inline uint32_t getStepID() { return stepID; } + bool operator==(const BatchPrimitiveProcessor&) const; + inline bool operator!=(const BatchPrimitiveProcessor& bpp) const + { + return !(*this == bpp); + } + + inline uint getSessionID() { return sessionID; } + inline uint getStepID() { return stepID; } inline uint32_t getUniqueID() { return uniqueID; } inline bool busy() { return fBusy; } inline void busy(bool b) { fBusy = b; } @@ -119,10 +117,6 @@ class BatchPrimitiveProcessor void setError(const std::string& error, logging::ErrorCodeValues errorCode) {} - // these two functions are used by BPPV to create BPP instances - // on demand. TRY not to use unlock() for anything else. - void unlock() { objLock.unlock(); } - bool hasJoin() { return doJoin; } private: BatchPrimitiveProcessor(); BatchPrimitiveProcessor(const BatchPrimitiveProcessor &); @@ -150,10 +144,10 @@ class BatchPrimitiveProcessor BPSOutputType ot; - BRM::QueryContext versionInfo; - uint32_t txnID; - uint32_t sessionID; - uint32_t stepID; + uint versionNum; + uint txnID; + uint sessionID; + uint stepID; uint32_t uniqueID; // # of times to loop over the command arrays @@ -170,10 +164,10 @@ class BatchPrimitiveProcessor bool needStrValues; /* Common space for primitive data */ - static const uint32_t BUFFER_SIZE = 65536; + static const uint BUFFER_SIZE = 65536; uint8_t blockData[BLOCK_SIZE * 8]; boost::scoped_array outputMsg; - uint32_t outMsgSize; + uint outMsgSize; std::vector filterSteps; std::vector projectSteps; @@ -192,7 +186,7 @@ class BatchPrimitiveProcessor // IO counters boost::mutex counterLock; - uint32_t busyLoaderCount; + uint busyLoaderCount; uint32_t physIO, cachedIO, touchedBlocks; @@ -213,7 +207,7 @@ class BatchPrimitiveProcessor boost::mutex addToJoinerLock; void executeJoin(); -// uint32_t ridsIn, ridsOut; +// uint ridsIn, ridsOut; //@bug 1051 FilterStep on PM bool hasFilterStep; @@ -225,32 +219,35 @@ class BatchPrimitiveProcessor // query density threshold for prefetch & async loading double prefetchThreshold; - + /* RowGroup support */ - rowgroup::RowGroup outputRG; - boost::scoped_ptr outRowGroupData; + rowgroup::RowGroup inputRG, outputRG; + boost::scoped_array inRowGroupData, outRowGroupData; boost::shared_array rgMap; // maps input cols to output cols boost::shared_array projectionMap; // maps the projection steps to the output RG bool hasRowGroup; + uint32_t valueColumn; + void copyInputRGColumns(); + void initFromRowGroup(); /* Rowgroups + join */ typedef std::tr1::unordered_multimap, utils::SimpleAllocator > > TJoiner; - + typedef std::tr1::unordered_multimap TLJoiner; - bool generateJoinedRowGroup(rowgroup::Row &baseRow, const uint32_t depth = 0); + bool generateJoinedRowGroup(rowgroup::Row &baseRow, const uint depth = 0); /* generateJoinedRowGroup helper fcns & vars */ void initGJRG(); // called once after joining void resetGJRG(); // called after every rowgroup returned by generateJRG - boost::scoped_array gjrgPlaceHolders; - uint32_t gjrgRowNumber; + boost::scoped_array gjrgPlaceHolders; + uint gjrgRowNumber; bool gjrgFull; rowgroup::Row largeRow, joinedRow, baseJRow; boost::scoped_array baseJRowMem; - boost::scoped_ptr joinedRGMem; + boost::scoped_array joinedRGMem; boost::scoped_array smallRows; boost::shared_array > gjrgMappings; @@ -261,16 +258,15 @@ class BatchPrimitiveProcessor bool getTupleJoinRowGroupData; std::vector smallSideRGs; rowgroup::RowGroup largeSideRG; - boost::shared_array smallSideRowData; - boost::shared_array smallNullRowData; - boost::shared_array smallNullPointers; + boost::shared_array > smallSideRowData; + boost::shared_array > smallNullRowData; boost::shared_array ssrdPos; // this keeps track of position when building smallSideRowData - boost::shared_array smallSideRowLengths; + boost::shared_array smallSideRowLengths; boost::shared_array joinTypes; - uint32_t joinerCount; - boost::shared_array tJoinerSizes; + uint joinerCount; + boost::shared_array tJoinerSizes; // LSKC[i] = the column in outputRG joiner i uses as its key column - boost::shared_array largeSideKeyColumns; + boost::shared_array largeSideKeyColumns; // KCPP[i] = true means a joiner uses projection step i as a key column boost::shared_array keyColumnProj; rowgroup::Row oldRow, newRow; // used by executeTupleJoin() @@ -282,12 +278,12 @@ class BatchPrimitiveProcessor /* extra typeless join vars & fcns*/ boost::shared_array typelessJoin; - boost::shared_array > tlLargeSideKeyColumns; + boost::shared_array > tlLargeSideKeyColumns; boost::shared_array > tlJoiners; - boost::shared_array tlKeyLengths; - inline void getJoinResults(const rowgroup::Row &r, uint32_t jIndex, std::vector& v); + boost::shared_array tlKeyLengths; + inline void getJoinResults(const rowgroup::Row &r, uint jIndex, std::vector& v); // these allocators hold the memory for the keys stored in tlJoiners - boost::shared_array storedKeyAllocators; + boost::shared_array storedKeyAllocators; // these allocators hold the memory for the large side keys which are short-lived boost::scoped_array tmpKeyAllocators; @@ -295,8 +291,7 @@ class BatchPrimitiveProcessor rowgroup::RowGroup joinedRG; // if there's a join, the rows are formatted with this rowgroup::SP_ROWAGG_PM_t fAggregator; rowgroup::RowGroup fAggregateRG; - rowgroup::RGData fAggRowGroupData; - //boost::scoped_array fAggRowGroupData; + boost::scoped_array fAggRowGroupData; boost::shared_array > _pools; /* OR hacks */ @@ -308,8 +303,7 @@ class BatchPrimitiveProcessor rowgroup::RowGroup fe1Input, fe2Output, *fe2Input; // note, joinFERG is only for metadata, and is shared between BPPs boost::shared_ptr joinFERG; - boost::scoped_array joinFERowData; - boost::scoped_ptr fe1Data, fe2Data; // can probably make these RGDatas not pointers to RGDatas + boost::scoped_array fe1Data, fe2Data, joinFERowData; boost::shared_array projectForFE1; boost::shared_array fe1ToProjection, fe2Mapping; // RG mappings boost::scoped_array > joinFEMappings; @@ -318,20 +312,20 @@ class BatchPrimitiveProcessor bool hasDictStep; primitives::PrimitiveProcessor pp; - + /* VSS cache members */ VSSCache vssCache; - void buildVSSCache(uint32_t loopCount); - - /* To support limited DEC queues on the PM */ + void buildVSSCache(uint loopCount); + + /* To support limited DEC queues on the PM */ boost::shared_ptr sendThread; bool newConnection; // to support the load balancing code in sendThread - + /* To support reentrancy */ - uint32_t currentBlockOffset; + uint currentBlockOffset; boost::scoped_array relLBID; boost::scoped_array asyncLoaded; - + /* To support a smaller memory footprint when idle */ static const uint64_t maxIdleBufferSize = 16*1024*1024; // arbitrary void allocLargeBuffers(); @@ -341,9 +335,7 @@ class BatchPrimitiveProcessor int sockIndex; /* Shared nothing vars */ - uint32_t dbRoot; - - bool endOfJoinerRan; + uint dbRoot; friend class Command; friend class ColumnCommand; @@ -353,7 +345,6 @@ class BatchPrimitiveProcessor friend class FilterCommand; friend class ScaledFilterCmd; friend class StrFilterCmd; - friend class PseudoCC; }; } diff --git a/primitives/primproc/bpp.h b/primitives/primproc/bpp.h index a3a1c19b..548dd46f 100644 --- a/primitives/primproc/bpp.h +++ b/primitives/primproc/bpp.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: bpp.h 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: bpp.h 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Interface: bpp // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -41,5 +41,3 @@ #include "filtercommand.h" #include "passthrucommand.h" #include "rtscommand.h" -#include "pseudocc.h" - diff --git a/primitives/primproc/bppseeder.cpp b/primitives/primproc/bppseeder.cpp index c9abd146..d160b0cc 100644 --- a/primitives/primproc/bppseeder.cpp +++ b/primitives/primproc/bppseeder.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: bppseeder.cpp 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: bppseeder.cpp 1960 2012-09-27 17:35:56Z pleblanc $ // C++ Implementation: bppseeder // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -77,7 +77,7 @@ extern int fCacheCount; void timespec_sub(const struct timespec &tv1, const struct timespec &tv2, - double &tm) + double &tm) { tm = (double)(tv2.tv_sec - tv1.tv_sec) + 1.e-9*(tv2.tv_nsec - tv1.tv_nsec); } @@ -92,15 +92,12 @@ BPPSeeder::BPPSeeder(const SBS &b, firstRun(true) { uint8_t *buf = b->buf(); - uint32_t pos = sizeof(ISMPacketHeader); + uint pos = sizeof(ISMPacketHeader); sessionID = *((uint32_t *) &buf[pos]); pos += 4; stepID = *((uint32_t *) &buf[pos]); pos += 4; uniqueID = *((uint32_t *) &buf[pos]); pos +=4; _priority = *((uint32_t *) &buf[pos]); - - dieTime = boost::posix_time::second_clock::universal_time() + - boost::posix_time::seconds(100); } BPPSeeder::BPPSeeder(const BPPSeeder &b) @@ -126,6 +123,7 @@ int BPPSeeder::operator()() double tm3=0; bool ptLock=false; bool gotBPP = false; + const uint maxFailCount = 20000; // current 1ms pause in W-threadpool, this is 20s PTLogs_t* logFD=NULL; int ret = 0; pthread_t tid=0; @@ -149,53 +147,52 @@ int BPPSeeder::operator()() //if (!(sessionID & 0x80000000)) //cout << "got request for <" << sessionID <<", " << stepID << ">\n"; +retry: scoped.lock(); if (!bppv) { it = bppMap.find(uniqueID); if (it == bppMap.end()) { /* mitigate a small race between creation and use */ scoped.unlock(); - if (boost::posix_time::second_clock::universal_time() > dieTime) { + if (++failCount > maxFailCount) { #if 0 // for debugging #ifndef _MSC_VER boost::posix_time::ptime pt = boost::posix_time::microsec_clock::local_time(); if (sessionID & 0x80000000) - cout << "BPPSeeder couldn't find the sessionID/stepID pair. sessionID=" + cout << "BPPSeeder couldn't find the sessionID/stepID pair. sessionID=" << (int) (sessionID ^ 0x80000000) << " stepID=" << stepID << " (syscat)" << pt << endl; - else - cout << "BPPSeeder couldn't find the sessionID/stepID pair. sessionID=" + else + cout << "BPPSeeder couldn't find the sessionID/stepID pair. sessionID=" << sessionID << " stepID=" << stepID << pt << endl; #endif throw logic_error("BPPSeeder couldn't find the sessionID/stepID pair"); #endif return 0; } -// if (!isSysCat()) + if (!isSysCat()) return -1; -// else { // syscat queries aren't run by a threadpool, can't reschedule those jobs -// usleep(1000); -// goto retry; -// } + else { // syscat queries aren't run by a threadpool, can't reschedule those jobs + usleep(1000); + goto retry; + } } bppv = it->second; } - if (bppv->aborted()) - return 0; bpp = bppv->next(); scoped.unlock(); if (!bpp) { -// if (isSysCat()) { -// usleep(1000); -// goto retry; -// } + if (isSysCat()) { + usleep(1000); + goto retry; + } return -1; // all BPP instances are busy, make threadpool reschedule } gotBPP = true; bpp->resetBPP(*bs, writelock, sock); firstRun = false; } // firstRun - - + + if (fTrace) { PTLogsMap_t::iterator it; @@ -208,7 +205,7 @@ int BPPSeeder::operator()() // only lock map while inserted objects // once there is an object for each thread // there is not need to lock - if (gFDList.size()<(uint32_t)fPMThreads) { + if (gFDList.size()<(uint)fPMThreads) { gFDMutex.lock(); ptLock=true; } @@ -232,7 +229,7 @@ int BPPSeeder::operator()() } } else logFD =(*it).second.get(); - + if (ptLock) { gFDMutex.unlock(); ptLock=false; @@ -240,7 +237,7 @@ int BPPSeeder::operator()() clock_gettime(CLOCK_MONOTONIC, &tm); } // if (fTrace) - uint32_t retries = 0; + uint retries = 0; restart: try { ret = (*bpp)(); @@ -248,7 +245,7 @@ int BPPSeeder::operator()() catch (NeedToRestartJob &e) { ostringstream os; // experimentally the race can exist longer than 10s. "No way" should - // it take 10 minutes. If it does, the user will have to resubmit their + // it take 10 minutes. If it does, the user will have to resubmit their // query. // 9/27/12 - changed the timeout to 2 mins b/c people report the system @@ -276,12 +273,12 @@ int BPPSeeder::operator()() << left << setw(3) << logFD->thdId << right << fixed << ((double)(tm.tv_sec+(1.e-9*tm.tv_nsec))) << " " << right << fixed << tm3 << " " - << right << setw(6) << bpp->getSessionID() << " " - << right << setw(4) << bpp->getStepID() << " " - << right << setw(2) << bpp->FilterCount() << " " - << right << setw(2) << bpp->ProjectCount() << " " - << right << setw(9) << bpp->PhysIOCount() << " " - << right << setw(9) << bpp->CachedIOCount() << " " + << right << setw(6) << bpp->getSessionID() << " " + << right << setw(4) << bpp->getStepID() << " " + << right << setw(2) << bpp->FilterCount() << " " + << right << setw(2) << bpp->ProjectCount() << " " + << right << setw(9) << bpp->PhysIOCount() << " " + << right << setw(9) << bpp->CachedIOCount() << " " << right << setw(9) << bpp->BlocksTouchedCount() << endl; } // if (logFD... @@ -335,8 +332,8 @@ void BPPSeeder::sendErrorMsg(uint32_t id, uint16_t status, uint32_t step) ISMPacketHeader ism; PrimitiveHeader ph = {0}; - - ism.Status = status; + + ism.Status = status; ph.UniqueID = id; ph.StepID = step; ByteStream msg(sizeof(ISMPacketHeader) + sizeof(PrimitiveHeader)); @@ -350,7 +347,7 @@ void BPPSeeder::sendErrorMsg(uint32_t id, uint16_t status, uint32_t step) bool BPPSeeder::isSysCat() { const uint8_t *buf; - uint32_t sessionIDOffset = sizeof(ISMPacketHeader); + uint sessionIDOffset = sizeof(ISMPacketHeader); uint32_t sessionID; buf = bs->buf(); diff --git a/primitives/primproc/bppseeder.h b/primitives/primproc/bppseeder.h index b64f5521..1333f9f2 100644 --- a/primitives/primproc/bppseeder.h +++ b/primitives/primproc/bppseeder.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: bppseeder.h 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: bppseeder.h 1960 2012-09-27 17:35:56Z pleblanc $ // C++ Interface: bppseeder // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -53,7 +53,7 @@ class BPPSeeder : public threadpool::PriorityThreadPool::Functor { public: BPPSeeder(const messageqcpp::SBS &, - const SP_UM_MUTEX& wLock, + const SP_UM_MUTEX& wLock, const SP_UM_IOSOCK& ios, const int pmThreads, const bool trace=false); @@ -68,8 +68,8 @@ class BPPSeeder : public threadpool::PriorityThreadPool::Functor uint32_t getID(); - void priority(uint32_t p) { _priority = p; } - uint32_t priority() { return _priority; } + void priority(uint p) { _priority = p; } + uint priority() { return _priority; } private: BPPSeeder(); @@ -82,15 +82,14 @@ class BPPSeeder : public threadpool::PriorityThreadPool::Functor SP_UM_IOSOCK sock; int fPMThreads; bool fTrace; - + /* To support reentrancy */ uint32_t uniqueID, sessionID, stepID, failCount; boost::shared_ptr bpp; SBPPV bppv; bool firstRun; - boost::posix_time::ptime dieTime; - uint32_t _priority; + uint _priority; }; }; diff --git a/primitives/primproc/bppsendthread.cpp b/primitives/primproc/bppsendthread.cpp index 45e77e5f..f495d3f0 100644 --- a/primitives/primproc/bppsendthread.cpp +++ b/primitives/primproc/bppsendthread.cpp @@ -28,21 +28,26 @@ using namespace std; using namespace boost; -#include "atomicops.h" +#if defined(_MSC_VER) && !defined(_WIN64) +# ifndef InterlockedAdd +# define InterlockedAdd64 InterlockedAdd +# define InterlockedAdd(x, y) ((x) + (y)) +# endif +#endif namespace primitiveprocessor { -extern uint32_t connectionsPerUM; +extern uint connectionsPerUM; BPPSendThread::BPPSendThread() : die(false), gotException(false), mainThreadWaiting(false), sizeThreshold(100), msgsLeft(-1), waiting(false), sawAllConnections(false), fcEnabled(false), currentByteSize(0), maxByteSize(25000000) { runner = boost::thread(Runner_t(this)); -} - -BPPSendThread::BPPSendThread(uint32_t initMsgsLeft) : die(false), gotException(false), +} + +BPPSendThread::BPPSendThread(uint initMsgsLeft) : die(false), gotException(false), mainThreadWaiting(false), sizeThreshold(100), msgsLeft(initMsgsLeft), waiting(false), sawAllConnections(false), fcEnabled(false), currentByteSize(0), maxByteSize(25000000) { @@ -76,7 +81,11 @@ void BPPSendThread::sendResult(const Msg_t &msg, bool newConnection) mutex::scoped_lock sl(msgQueueLock); if (gotException) throw runtime_error(exceptionString); - (void)atomicops::atomicAdd(¤tByteSize, msg.msg->lengthWithHdrOverhead()); +#ifdef _MSC_VER + InterlockedAdd64(¤tByteSize, msg.msg->lengthWithHdrOverhead()); +#else + __sync_add_and_fetch(¤tByteSize, msg.msg->lengthWithHdrOverhead()); +#endif msgQueue.push(msg); if (!sawAllConnections && newConnection) { Connection_t ins(msg.sockLock, msg.sock); @@ -112,8 +121,12 @@ void BPPSendThread::sendResults(const vector &msgs, bool newConnection) } } } - for (uint32_t i = 0; i < msgs.size(); i++) { - (void)atomicops::atomicAdd(¤tByteSize, msgs[i].msg->lengthWithHdrOverhead()); + for (uint i = 0; i < msgs.size(); i++) { +#ifdef _MSC_VER + InterlockedAdd64(¤tByteSize, msgs[i].msg->lengthWithHdrOverhead()); +#else + __sync_add_and_fetch(¤tByteSize, msgs[i].msg->lengthWithHdrOverhead()); +#endif msgQueue.push(msgs[i]); } if (mainThreadWaiting) @@ -131,7 +144,11 @@ void BPPSendThread::sendMore(int num) msgsLeft = 0; } else - (void)atomicops::atomicAdd(&msgsLeft, num); +#ifdef _MSC_VER + InterlockedAdd(&msgsLeft, num); +#else + __sync_add_and_fetch(&msgsLeft, num); +#endif if (waiting) okToSend.notify_one(); } @@ -143,13 +160,13 @@ bool BPPSendThread::flowControlEnabled() void BPPSendThread::mainLoop() { - const uint32_t msgCap = 20; + const uint msgCap = 20; boost::scoped_array msg; - uint32_t msgCount = 0, i, msgsSent; + uint msgCount = 0, i, msgsSent; SP_UM_MUTEX lock; SP_UM_IOSOCK sock; bool doLoadBalancing = false; - + msg.reset(new Msg_t[msgCap]); while (!die) { @@ -160,7 +177,7 @@ void BPPSendThread::mainLoop() mainThreadWaiting = false; continue; } - + msgCount = (msgQueue.size() > msgCap ? msgCap : msgQueue.size()); for (i = 0; i < msgCount; i++) { msg[i] = msgQueue.front(); @@ -174,9 +191,9 @@ void BPPSendThread::mainLoop() msgsSent = 0; while (msgsSent < msgCount && !die) { uint64_t bsSize; - if (msgsLeft <= 0 && fcEnabled && !die) { + if (msgsLeft == 0 && fcEnabled && !die) { mutex::scoped_lock sl2(ackLock); - while (msgsLeft <= 0 && fcEnabled && !die) { + while (msgsLeft == 0 && fcEnabled && !die) { waiting = true; okToSend.wait(sl2); waiting = false; @@ -205,8 +222,15 @@ void BPPSendThread::mainLoop() gotException = true; return; } - (void)atomicops::atomicDec(&msgsLeft); - (void)atomicops::atomicSub(¤tByteSize, bsSize); +#ifdef _MSC_VER + InterlockedAdd(&msgsLeft, -1); + //FIXME: is bsSize always small enough to fit into a signed var? + int64_t sbsSize = static_cast(bsSize); + InterlockedAdd64(¤tByteSize, -sbsSize); +#else + __sync_sub_and_fetch(&msgsLeft, 1); + __sync_sub_and_fetch(¤tByteSize, bsSize); +#endif msg[msgsSent].msg.reset(); } } diff --git a/primitives/primproc/bppsendthread.h b/primitives/primproc/bppsendthread.h index 8ee715f2..e5c8f631 100644 --- a/primitives/primproc/bppsendthread.h +++ b/primitives/primproc/bppsendthread.h @@ -39,7 +39,7 @@ class BPPSendThread { public: BPPSendThread(); // starts unthrottled - BPPSendThread(uint32_t initMsgsLeft); // starts throttled + BPPSendThread(uint initMsgsLeft); // starts throttled virtual ~BPPSendThread(); struct Msg_t { @@ -83,8 +83,12 @@ class BPPSendThread { boost::condition queueNotEmpty; volatile bool die, gotException, mainThreadWaiting; std::string exceptionString; - uint32_t sizeThreshold; - volatile int32_t msgsLeft; + uint sizeThreshold; +#ifdef _MSC_VER + volatile LONG msgsLeft; +#else + volatile int msgsLeft; +#endif bool waiting; boost::mutex ackLock; boost::condition okToSend; @@ -106,7 +110,11 @@ class BPPSendThread { volatile bool fcEnabled; /* secondary queue size restriction based on byte size */ - volatile uint64_t currentByteSize; +#ifdef _MSC_VER + volatile LONG64 currentByteSize; +#else + uint64_t currentByteSize; +#endif uint64_t maxByteSize; }; diff --git a/primitives/primproc/columncommand.cpp b/primitives/primproc/columncommand.cpp index 8cad317b..d3ec0b88 100644 --- a/primitives/primproc/columncommand.cpp +++ b/primitives/primproc/columncommand.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: columncommand.cpp 2057 2013-02-13 17:00:10Z pleblanc $ +// $Id: columncommand.cpp 2058 2013-02-13 18:07:30Z pleblanc $ // C++ Implementation: columncommand // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -60,20 +60,53 @@ double cotangent(double in) return (1.0 / tan(in)); } +inline UDFFcnPtr_t ord2Fptr(uint8_t ord) +{ +#ifndef _MSC_VER + if (ord == 0) + return 0; + + if (ord == 255) return reinterpret_cast(::llabs); + if (ord == 254) return reinterpret_cast(::acos); + if (ord == 253) return reinterpret_cast(::asin); + if (ord == 252) return reinterpret_cast(::atan); + if (ord == 251) return reinterpret_cast(::cos); + if (ord == 250) return reinterpret_cast(cotangent); + if (ord == 249) return reinterpret_cast(::exp); + if (ord == 248) return reinterpret_cast(::log); +#ifdef __linux__ + if (ord == 247) return reinterpret_cast(::log2); +#else + if (ord == 247) return reinterpret_cast(::log); +#endif + if (ord == 246) return reinterpret_cast(::log10); + if (ord == 245) return reinterpret_cast(::sin); + if (ord == 244) return reinterpret_cast(::sqrt); + if (ord == 243) return reinterpret_cast(::tan); + + //we'd like to avoid having to lock the map, so we need to use const methods only + UDFFcnMap_t::const_iterator it = UDFFcnMap.find(ord); + if (it == UDFFcnMap.end()) + return 0; + + return it->second; +#else + return 0; +#endif +} } namespace primitiveprocessor { -extern int noVB; - ColumnCommand::ColumnCommand() : Command(COLUMN_COMMAND), blockCount(0), loadCount(0), - suppressFilter(false) -{ -} + suppressFilter(false), + fUdfFuncPtr(0) + { + } ColumnCommand::~ColumnCommand() { } @@ -107,7 +140,7 @@ void ColumnCommand::execute() _execute(); } -void ColumnCommand::execute(int64_t *vals) +void ColumnCommand::execute(int64_t *vals) { values = vals; _execute(); @@ -126,8 +159,8 @@ void ColumnCommand::makeScanMsg() primMsg->LBID = lbid; primMsg->RidFlags = 0xFF; -// cout << "scanning lbid " << lbid << " colwidth = " << primMsg->DataSize << -// " filterCount = " << filterCount << " outputType = " << +// cout << "scanning lbid " << lbid << " colwidth = " << primMsg->DataSize << +// " filterCount = " << filterCount << " outputType = " << // (int) primMsg->OutputType << endl; } @@ -141,39 +174,43 @@ void ColumnCommand::makeStepMsg() // cout << "lbid is " << lbid << endl; } -void ColumnCommand::loadData() +void ColumnCommand::issuePrimitive() { - uint32_t wasCached; + int i; + + bool wasVersioned; + uint wasCached; uint32_t blocksRead; + uint32_t resultSize; uint8_t _mask; uint64_t oidLastLbid=0; bool lastBlockReached=false; oidLastLbid = getLastLbid(); - uint32_t blocksToLoad = 0; + uint blocksToLoad = 0; BRM::LBID_t *lbids = (BRM::LBID_t *) alloca(8 * sizeof(BRM::LBID_t)); - uint8_t **blockPtrs = (uint8_t **) alloca(8 * sizeof(uint8_t *)); - int i; - + BRM::VER_t *vers = (BRM::VER_t *) alloca(8 * sizeof(BRM::VER_t)); + uint8_t **blockPtrs = (uint8_t **) alloca(8 * sizeof(uint8_t *)); _mask = mask; // primMsg->RidFlags = 0xff; // disables selective block loading //cout <<__FILE__ << "::issuePrimitive() o: " << getOID() << " l:" << primMsg->LBID << " ll: " << oidLastLbid << endl; - + for (i=0; i < colType.colWidth; ++i, _mask <<= shift) { if ((!lastBlockReached && _isScan) || (!_isScan && primMsg->RidFlags & _mask)) { lbids[blocksToLoad] = primMsg->LBID + i; + vers[blocksToLoad] = bpp->versionNum; blockPtrs[blocksToLoad] = &bpp->blockData[i * BLOCK_SIZE]; blocksToLoad++; loadCount++; } else if (lastBlockReached && _isScan) - { // fill remaining blocks with empty values when col scan + { // fill remaining blocks with empty values when col scan int blockLen = BLOCK_SIZE/colType.colWidth; - ByteStream::octbyte* oPtr=NULL; - ByteStream::quadbyte* qPtr=NULL; - ByteStream::byte* bPtr=NULL; - ByteStream::doublebyte* dPtr=NULL; + ByteStream::octbyte* oPtr=NULL; + ByteStream::quadbyte* qPtr=NULL; + ByteStream::byte* bPtr=NULL; + ByteStream::doublebyte* dPtr=NULL; if (colType.colWidth==1) bPtr = reinterpret_cast(&bpp->blockData[i*BLOCK_SIZE]); //@Bug 1812. Added two bytes column handling @@ -204,47 +241,39 @@ void ColumnCommand::loadData() oPtr[idx] = o; } } - + }// else if ( (primMsg->LBID+i)==oidLastLbid) lastBlockReached=true; blockCount++; } // for - + /* Do the load */ - wasCached = primitiveprocessor::loadBlocks(lbids, - bpp->versionInfo, - bpp->txnID, - colType.compressionType, - blockPtrs, - &blocksRead, - bpp->LBIDTrace, - bpp->sessionID, - blocksToLoad, - &wasVersioned, - willPrefetch(), - &bpp->vssCache); + wasCached = primitiveprocessor::loadBlocks(lbids, + vers, + bpp->txnID, + colType.compressionType, + blockPtrs, + &blocksRead, + bpp->LBIDTrace, + bpp->sessionID, + blocksToLoad, + &wasVersioned, + willPrefetch(), + &bpp->vssCache); bpp->cachedIO += wasCached; bpp->physIO += blocksRead; bpp->touchedBlocks += blocksToLoad; -} - -void ColumnCommand::issuePrimitive() -{ - uint32_t resultSize; - - loadData(); // cout << "issuing primitive for LBID " << primMsg->LBID << endl; if (!suppressFilter) bpp->pp.setParsedColumnFilter(parsedColumnFilter); else bpp->pp.setParsedColumnFilter(emptyFilter); - bpp->pp.p_Col(primMsg, outMsg, bpp->outMsgSize, (unsigned int*)&resultSize); + bpp->pp.p_Col(primMsg, outMsg, bpp->outMsgSize, (unsigned int*)&resultSize, fUdfFuncPtr); - /* Update CP data, the PseudoColumn code should always be !_isScan. Should be safe - to leave this here for now. */ + /* Update CP data */ if (_isScan) { bpp->validCPData = (outMsg->ValidMinMax && !wasVersioned); //if (wasVersioned && outMsg->ValidMinMax) @@ -266,45 +295,42 @@ void ColumnCommand::process_OT_BOTH() /* this is verbose and repetative to minimize the work per row */ switch(colType.colWidth) { - case 8: - for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { - if (makeAbsRids) - bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; - bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); - pos += 2; - values[i] = *((int64_t *) &bpp->outputMsg[pos]); - pos += 8; - } - break; - case 4: - for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { - if (makeAbsRids) - bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; - bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); - pos += 2; - values[i] = *((int32_t *) &bpp->outputMsg[pos]); - pos += 4; - } - break; - case 2: - for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { - if (makeAbsRids) - bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; - bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); - pos += 2; - values[i] = *((int16_t *) &bpp->outputMsg[pos]); - pos += 2; - } - break; - case 1: - for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { - if (makeAbsRids) - bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; - bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); - pos += 2; - values[i] = *((int8_t *) &bpp->outputMsg[pos++]); - } - break; + case 8: + for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { + if (makeAbsRids) + bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; + bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); + pos += 2; + values[i] = *((int64_t *) &bpp->outputMsg[pos]); pos += 8; + } + break; + case 4: + for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { + if (makeAbsRids) + bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; + bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); + pos += 2; + values[i] = *((int32_t *) &bpp->outputMsg[pos]); pos += 4; + } + break; + case 2: + for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { + if (makeAbsRids) + bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; + bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); + pos += 2; + values[i] = *((int16_t *) &bpp->outputMsg[pos]); pos += 2; + } + break; + case 1: + for (i = 0, pos = sizeof(NewColResultHeader); i < outMsg->NVALS; ++i) { + if (makeAbsRids) + bpp->absRids[i] = *((uint16_t *) &bpp->outputMsg[pos]) + bpp->baseRid; + bpp->relRids[i] = *((uint16_t *) &bpp->outputMsg[pos]); + pos += 2; + values[i] = *((int8_t *) &bpp->outputMsg[pos++]); + } + break; } } @@ -322,33 +348,33 @@ void ColumnCommand::process_OT_DATAVALUE() bpp->ridCount = outMsg->NVALS; // cout << "rid Count is " << bpp->ridCount << endl; switch(colType.colWidth) { - case 8: - { - memcpy(values, outMsg + 1, outMsg->NVALS << 3); -// cout << " CC: first value is " << values[0] << endl; - break; - } - case 4: - { - int32_t* arr32 = (int32_t *) (outMsg + 1); - for (uint64_t i = 0; i < outMsg->NVALS; ++i) - values[i] = arr32[i]; - break; - } - case 2: - { - int16_t* arr16 = (int16_t *) (outMsg + 1); - for (uint64_t i = 0; i < outMsg->NVALS; ++i) - values[i] = arr16[i]; - break; - } - case 1: - { - int8_t* arr8 = (int8_t *) (outMsg + 1); - for (uint64_t i = 0; i < outMsg->NVALS; ++i) - values[i] = arr8[i]; - break; - } + case 8: + { + memcpy(values, outMsg + 1, outMsg->NVALS << 3); +// cout << " CC: first value is " << values[0] << endl; + break; + } + case 4: + { + int32_t* arr32 = (int32_t *) (outMsg + 1); + for (uint64_t i = 0; i < outMsg->NVALS; ++i) + values[i] = arr32[i]; + break; + } + case 2: + { + int16_t* arr16 = (int16_t *) (outMsg + 1); + for (uint64_t i = 0; i < outMsg->NVALS; ++i) + values[i] = arr16[i]; + break; + } + case 1: + { + int8_t* arr8 = (int8_t *) (outMsg + 1); + for (uint64_t i = 0; i < outMsg->NVALS; ++i) + values[i] = arr8[i]; + break; + } } } @@ -361,18 +387,12 @@ void ColumnCommand::processResult() // idbassert(outMsg->NVALS == bpp->ridCount); switch (outMsg->OutputType) { - case OT_BOTH: - process_OT_BOTH(); - break; - case OT_RID: - process_OT_RID(); - break; - case OT_DATAVALUE: - process_OT_DATAVALUE(); - break; - default: - cout << "outputType = " << outMsg->OutputType << endl; - throw logic_error("ColumnCommand got a bad OutputType"); + case OT_BOTH: process_OT_BOTH(); break; + case OT_RID: process_OT_RID(); break; + case OT_DATAVALUE: process_OT_DATAVALUE(); break; + default: + cout << "outputType = " << outMsg->OutputType << endl; + throw logic_error("ColumnCommand got a bad OutputType"); } // check if feeding a filtercommand @@ -395,14 +415,14 @@ void ColumnCommand::createCommand(ByteStream &bs) { uint8_t tmp8; - bs.advance(1); + bs >> tmp8; // eat the Command bs >> tmp8; _isScan = tmp8; bs >> traceFlags; bs >> filterString; #if 0 cout << "filter string: "; - for (uint32_t i = 0; i < filterString.length(); ++i) + for (uint i = 0; i < filterString.length(); ++i) cout << (int) filterString.buf()[i] << " "; cout << endl; #endif @@ -416,21 +436,28 @@ void ColumnCommand::createCommand(ByteStream &bs) colType.compressionType = tmp8; bs >> BOP; bs >> filterCount; + bs >> tmp8; // UDF ordinal number + fUdfFuncPtr = ord2Fptr(tmp8); + if (tmp8 != 0 && fUdfFuncPtr == 0) { + Message::Args args; + args.add(tmp8); + mlp->logMessage(logging::M0069, args); + } deserializeInlineVector(bs, lastLbid); // cout << "lastLbid count=" << lastLbid.size() << endl; -// for (uint32_t i = 0; i < lastLbid.size(); i++) +// for (uint i = 0; i < lastLbid.size(); i++) // cout << " " << lastLbid[i]; //cout << "CreateCommand() o:" << getOID() << " lastLbid: " << lastLbid << endl; Command::createCommand(bs); - parsedColumnFilter = primitives::parseColumnFilter(filterString.buf(), colType.colWidth, - colType.colDataType, filterCount, BOP); + parsedColumnFilter = bpp->pp.parseColumnFilter(filterString.buf(), colType.colWidth, + colType.colDataType, filterCount, BOP); /* OR hack */ - emptyFilter = primitives::parseColumnFilter(filterString.buf(), colType.colWidth, - colType.colDataType, 0, BOP); + emptyFilter = bpp->pp.parseColumnFilter(filterString.buf(), colType.colWidth, + colType.colDataType, 0, BOP); /* XXXPAT: for debugging only */ // bs >> colType.columnOID; @@ -448,7 +475,7 @@ void ColumnCommand::prep(int8_t outputType, bool absRids) /* make the template NewColRequestHeader */ baseMsgLength = sizeof(NewColRequestHeader) + - (suppressFilter ? 0 : filterString.length()); + (suppressFilter ? 0 : filterString.length()); if (!inputMsg) inputMsg.reset(new uint8_t[baseMsgLength + (LOGICAL_BLOCK_RIDS * 2)]); @@ -458,27 +485,27 @@ void ColumnCommand::prep(int8_t outputType, bool absRids) primMsg->ism.Interleave = 0; primMsg->ism.Flags = 0; -// primMsg->ism.Flags = PrimitiveMsg::planFlagsToPrimFlags(traceFlags); +// primMsg->ism.Flags = PrimitiveMsg::planFlagsToPrimFlags(traceFlags); primMsg->ism.Command=COL_BY_SCAN; primMsg->ism.Size = sizeof(NewColRequestHeader) + (suppressFilter ? 0 : filterString.length()); primMsg->ism.Type = 2; primMsg->hdr.SessionID = bpp->sessionID; //primMsg->hdr.StatementID = 0; primMsg->hdr.TransactionID = bpp->txnID; - primMsg->hdr.VerID = bpp->versionInfo.currentScn; + primMsg->hdr.VerID = bpp->versionNum; primMsg->hdr.StepID = bpp->stepID; primMsg->DataSize = colType.colWidth; primMsg->DataType = colType.colDataType; primMsg->CompType = colType.compressionType; - primMsg->OutputType = outputType; + primMsg->OutputType = outputType; primMsg->BOP = BOP; primMsg->NOPS = (suppressFilter ? 0 : filterCount); primMsg->sort = 0; #if 0 - cout << "filter length is " << filterString.length() << endl; + cout << "filter length is " << filterString.length() << endl; cout << "appending filter string: "; - for (uint32_t i = 0; i < filterString.length(); ++i) + for (uint i = 0; i < filterString.length(); ++i) cout << (int) filterString.buf()[i] << " "; cout << endl; #endif @@ -489,25 +516,13 @@ void ColumnCommand::prep(int8_t outputType, bool absRids) switch (colType.colWidth) { - case 1: - shift = 8; - mask = 0xFF; - break; - case 2: - shift = 4; - mask = 0x0F; - break; - case 4: - shift = 2; - mask = 0x03; - break; - case 8: - shift = 1; - mask = 0x01; - break; - default: - cout << "CC: colWidth is " << colType.colWidth << endl; - throw logic_error("ColumnCommand: bad column width?"); + case 1: shift = 8; mask = 0xFF; break; + case 2: shift = 4; mask = 0x0F; break; + case 4: shift = 2; mask = 0x03; break; + case 8: shift = 1; mask = 0x01; break; + default: + cout << "CC: colWidth is " << colType.colWidth << endl; + throw logic_error("ColumnCommand: bad column width?"); } /* TODO: re-optimize with parameterized output RG */ @@ -531,7 +546,7 @@ void ColumnCommand::projectResult() uint16_t segNum; uint32_t fbo; brm.lookupLocal(lbid, 0, false, oid, l_dbroot, partNum, segNum, fbo); - + os << __FILE__ << " error on projection for oid " << oid << " lbid " << lbid; if (primMsg->NVALS != outMsg->NVALS ) os << ": input rids " << primMsg->NVALS; @@ -550,58 +565,16 @@ void ColumnCommand::projectResult() bpp->serialized->append((uint8_t *) (outMsg + 1), outMsg->NVALS * colType.colWidth); } -void ColumnCommand::removeRowsFromRowGroup(RowGroup &rg) -{ - uint32_t gapSize = colType.colWidth + 2; - uint8_t *msg8; - uint16_t rid; - Row oldRow, newRow; - uint32_t oldIdx, newIdx; - - rg.initRow(&oldRow); - rg.initRow(&newRow); - rg.getRow(0, &oldRow); - rg.getRow(0, &newRow); - msg8 = (uint8_t *) (outMsg + 1); - for (oldIdx = newIdx = 0; newIdx < outMsg->NVALS; newIdx++, msg8 += gapSize) { - rid = *((uint16_t *) msg8); - while (rid != bpp->relRids[oldIdx]) { - // need to find rid in relrids, and it is in there - oldIdx++; - oldRow.nextRow(); - } - if (oldIdx != newIdx) { - bpp->relRids[newIdx] = rid; - // we use a memcpy here instead of copyRow() to avoid expanding the string table; - memcpy(newRow.getData(), oldRow.getData(), newRow.getSize()); - } - oldIdx++; - oldRow.nextRow(); - newRow.nextRow(); - } - rg.setRowCount(outMsg->NVALS); // this gets rid of trailing rows, no need to set them to NULL - bpp->ridCount = outMsg->NVALS; - primMsg->NVALS = outMsg->NVALS; -} - -void ColumnCommand::projectResultRG(RowGroup &rg, uint32_t pos) +void ColumnCommand::projectResultRG(RowGroup &rg, uint pos) { - uint32_t i, offset, gapSize; - uint8_t *msg8 = (uint8_t *) (outMsg + 1); - if (noVB) { - // outMsg has rids in this case - msg8 += 2; - gapSize = colType.colWidth + 2; - } - else - gapSize = colType.colWidth; + uint i, offset; /* TODO: reoptimize these away */ rg.initRow(&r); offset = r.getOffset(pos); rowSize = r.getSize(); - if ((primMsg->NVALS != outMsg->NVALS || outMsg->NVALS != bpp->ridCount) && (!noVB || bpp->sessionID & 0x80000000)) + if (primMsg->NVALS != outMsg->NVALS || outMsg->NVALS != bpp->ridCount) { ostringstream os; BRM::DBRM brm; @@ -611,62 +584,66 @@ void ColumnCommand::projectResultRG(RowGroup &rg, uint32_t pos) uint16_t segNum; uint32_t fbo; brm.lookupLocal(lbid, 0, false, oid, dbroot, partNum, segNum, fbo); - + os << __FILE__ << " error on projectResultRG for oid " << oid << " lbid " << lbid; if (primMsg->NVALS != outMsg->NVALS ) os << ": input rids " << primMsg->NVALS; else os << ": ridcount " << bpp->ridCount; os << ", output rids " << outMsg->NVALS; - /* - BRM::VSSData entry; - if (bpp->vssCache.find(lbid) != bpp->vssCache.end()) { - entry = bpp->vssCache[lbid]; - if (entry.returnCode == 0) - os << " requested version " << entry.verID; - } - */ +/* + BRM::VSSData entry; + if (bpp->vssCache.find(lbid) != bpp->vssCache.end()) { + entry = bpp->vssCache[lbid]; + if (entry.returnCode == 0) + os << " requested version " << entry.verID; + } +*/ os << endl; if (bpp->sessionID & 0x80000000) throw NeedToRestartJob(os.str()); else throw PrimitiveColumnProjectResultExcept(os.str()); } - else if (primMsg->NVALS != outMsg->NVALS || outMsg->NVALS != bpp->ridCount) - removeRowsFromRowGroup(rg); idbassert(primMsg->NVALS == outMsg->NVALS); idbassert(outMsg->NVALS == bpp->ridCount); rg.getRow(0, &r); switch (colType.colWidth) { - case 1: { - for (i = 0; i < outMsg->NVALS; ++i, msg8 += gapSize) { - r.setUintField_offset<1>(*msg8, offset); - r.nextRow(rowSize); + case 1: { + uint8_t *val8 = (uint8_t *) (outMsg + 1); + for (i = 0; i < outMsg->NVALS; ++i) { + r.setUintField_offset<1>(val8[i], offset); + r.nextRow(rowSize); + } + break; } - break; - } - case 2: { - for (i = 0; i < outMsg->NVALS; ++i, msg8 += gapSize) { - r.setUintField_offset<2>(*((uint16_t *) msg8), offset); - r.nextRow(rowSize); + case 2: { + uint16_t *val16 = (uint16_t *) (outMsg + 1); + for (i = 0; i < outMsg->NVALS; ++i) { + r.setUintField_offset<2>(val16[i], offset); + r.nextRow(rowSize); + } + break; } - break; - } - case 4: { - for (i = 0; i < outMsg->NVALS; ++i, msg8 += gapSize) { - r.setUintField_offset<4>(*((uint32_t *) msg8), offset); - r.nextRow(rowSize); + case 4: { + uint32_t *val32 = (uint32_t *) (outMsg + 1); + for (i = 0; i < outMsg->NVALS; ++i) { +// if (OID > 3000) +// cout << "column primitive for oid " << OID << " inserting " << val32[i] << endl; + r.setUintField_offset<4>(val32[i], offset); + r.nextRow(rowSize); + } + break; } - break; - } - case 8: { - for (i = 0; i < outMsg->NVALS; ++i, msg8 += gapSize) { - r.setUintField_offset<8>(*((uint64_t *) msg8), offset); - r.nextRow(rowSize); + case 8: { + uint64_t *val64 = (uint64_t *) (outMsg + 1); + for (i = 0; i < outMsg->NVALS; ++i) { + r.setUintField_offset<8>(val64[i], offset); + r.nextRow(rowSize); + } + break; } - break; - } } } @@ -683,7 +660,7 @@ void ColumnCommand::project() projectResult(); } -void ColumnCommand::projectIntoRowGroup(RowGroup &rg, uint32_t pos) +void ColumnCommand::projectIntoRowGroup(RowGroup &rg, uint pos) { if (bpp->ridCount == 0) { blockCount += colType.colWidth; @@ -699,8 +676,13 @@ void ColumnCommand::nextLBID() lbid += colType.colWidth; } -void ColumnCommand::duplicate(ColumnCommand *cc) +SCommand ColumnCommand::duplicate() { + SCommand ret; + ColumnCommand *cc; + + ret.reset(new ColumnCommand()); + cc = (ColumnCommand *) ret.get(); cc->_isScan = _isScan; cc->traceFlags = traceFlags; cc->filterString = filterString; @@ -716,14 +698,6 @@ void ColumnCommand::duplicate(ColumnCommand *cc) cc->r = r; cc->rowSize = rowSize; cc->Command::duplicate(this); -} - -SCommand ColumnCommand::duplicate() -{ - SCommand ret; - - ret.reset(new ColumnCommand()); - duplicate((ColumnCommand *) ret.get()); return ret; } @@ -779,7 +753,7 @@ bool ColumnCommand::willPrefetch() //return false; return (blockCount == 0 || ((double)loadCount)/((double)blockCount) > - bpp->prefetchThreshold); + bpp->prefetchThreshold); } void ColumnCommand::disableFilters() @@ -804,86 +778,68 @@ void ColumnCommand::enableFilters() * RETURN: * emptyVal - the value of empty row ***********************************************************/ -const uint64_t ColumnCommand::getEmptyRowValue( const execplan::CalpontSystemCatalog::ColDataType dataType, const int width ) const -{ - uint64_t emptyVal = 0; - int offset; - - offset = ( dataType == execplan::CalpontSystemCatalog::VARCHAR )? -1 : 0; - switch ( dataType ) - { - case execplan::CalpontSystemCatalog::TINYINT : - emptyVal = joblist::TINYINTEMPTYROW; - break; - case execplan::CalpontSystemCatalog::SMALLINT: - emptyVal = joblist::SMALLINTEMPTYROW; - break; - case execplan::CalpontSystemCatalog::MEDINT : - case execplan::CalpontSystemCatalog::INT : - emptyVal = joblist::INTEMPTYROW; - break; - case execplan::CalpontSystemCatalog::BIGINT : - emptyVal = joblist::BIGINTEMPTYROW; - break; - - case execplan::CalpontSystemCatalog::UTINYINT : - emptyVal = joblist::UTINYINTEMPTYROW; - break; - case execplan::CalpontSystemCatalog::USMALLINT: - emptyVal = joblist::USMALLINTEMPTYROW; - break; - case execplan::CalpontSystemCatalog::UMEDINT : - case execplan::CalpontSystemCatalog::UINT : - emptyVal = joblist::UINTEMPTYROW; - break; - case execplan::CalpontSystemCatalog::UBIGINT : - emptyVal = joblist::UBIGINTEMPTYROW; - break; - - case execplan::CalpontSystemCatalog::FLOAT : - case execplan::CalpontSystemCatalog::UFLOAT : - emptyVal = joblist::FLOATEMPTYROW; - break; - case execplan::CalpontSystemCatalog::DOUBLE : - case execplan::CalpontSystemCatalog::UDOUBLE : - emptyVal = joblist::DOUBLEEMPTYROW; - break; - - case execplan::CalpontSystemCatalog::DECIMAL : - case execplan::CalpontSystemCatalog::UDECIMAL : - if ( width <= 1 ) - emptyVal = joblist::TINYINTEMPTYROW; - else if (width <= 2) - emptyVal = joblist::SMALLINTEMPTYROW; - else if ( width <= 4 ) - emptyVal = joblist::INTEMPTYROW; - else - emptyVal = joblist::BIGINTEMPTYROW; - break; - - case execplan::CalpontSystemCatalog::CHAR : - case execplan::CalpontSystemCatalog::VARCHAR : - case execplan::CalpontSystemCatalog::DATE : - case execplan::CalpontSystemCatalog::DATETIME : - case execplan::CalpontSystemCatalog::VARBINARY : - default: - emptyVal = joblist::CHAR1EMPTYROW; - if ( width == (2 + offset) ) - emptyVal = joblist::CHAR2EMPTYROW; - else if ( width >= (3 + offset) && width <= ( 4 + offset ) ) - emptyVal = joblist::CHAR4EMPTYROW; - else if ( width >= (5 + offset) ) - emptyVal = joblist::CHAR8EMPTYROW; - break; - } - - return emptyVal; -} - -void ColumnCommand::getLBIDList(uint32_t loopCount, vector *lbids) +const int64_t ColumnCommand::getEmptyRowValue( const execplan::CalpontSystemCatalog::ColDataType dataType, const int width ) const +{ + int64_t emptyVal = 0; + int offset; + + offset = ( dataType == execplan::CalpontSystemCatalog::VARCHAR )? -1 : 0; + switch( dataType ) { + case execplan::CalpontSystemCatalog::TINYINT : emptyVal = joblist::TINYINTEMPTYROW; break; + case execplan::CalpontSystemCatalog::SMALLINT: emptyVal = joblist::SMALLINTEMPTYROW; break; + case execplan::CalpontSystemCatalog::MEDINT : + case execplan::CalpontSystemCatalog::INT : + emptyVal = joblist::INTEMPTYROW; break; + case execplan::CalpontSystemCatalog::BIGINT : emptyVal = joblist::BIGINTEMPTYROW; break; + case execplan::CalpontSystemCatalog::FLOAT : emptyVal = joblist::FLOATEMPTYROW; break; + case execplan::CalpontSystemCatalog::DOUBLE : emptyVal = joblist::DOUBLEEMPTYROW; break; + case execplan::CalpontSystemCatalog::DECIMAL : +/* if( width <= 4 ) + emptyVal = joblist::SMALLINTEMPTYROW; + else + if( width <= 9 ) + emptyVal = joblist::INTEMPTYROW; + else + if( width <= 18 ) + emptyVal = joblist::BIGINTEMPTYROW; + else + emptyVal = joblist::CHAR8EMPTYROW; +*/ + // @bug 194 use the correct logic in handling empty value for decimal + if( width <= 1 ) + emptyVal = joblist::TINYINTEMPTYROW; + else if (width <= 2) + emptyVal = joblist::SMALLINTEMPTYROW; + else if( width <= 4 ) + emptyVal = joblist::INTEMPTYROW; + else + emptyVal = joblist::BIGINTEMPTYROW; + break; + case execplan::CalpontSystemCatalog::CHAR : + case execplan::CalpontSystemCatalog::VARCHAR : + case execplan::CalpontSystemCatalog::DATE : + case execplan::CalpontSystemCatalog::DATETIME : + case execplan::CalpontSystemCatalog::VARBINARY : + default: + emptyVal = joblist::CHAR1EMPTYROW; + if( width == (2 + offset) ) + emptyVal = joblist::CHAR2EMPTYROW; + else + if( width >= (3 + offset) && width <= ( 4 + offset ) ) + emptyVal = joblist::CHAR4EMPTYROW; + else + if( width >= (5 + offset) ) + emptyVal = joblist::CHAR8EMPTYROW; + break; + } + + return emptyVal; +} + +void ColumnCommand::getLBIDList(uint loopCount, vector *lbids) { int64_t firstLBID = lbid, lastLBID = firstLBID + (loopCount * colType.colWidth) - 1, i; - + for (i = firstLBID; i <= lastLBID; i++) lbids->push_back(i); } diff --git a/primitives/primproc/columncommand.h b/primitives/primproc/columncommand.h index e4672ba8..299d5208 100644 --- a/primitives/primproc/columncommand.h +++ b/primitives/primproc/columncommand.h @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: columncommand.h 2057 2013-02-13 17:00:10Z pleblanc $ +// $Id: columncommand.h 2058 2013-02-13 18:07:30Z pleblanc $ // C++ Interface: columncommand // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -54,18 +54,18 @@ class ColumnCommand : public Command void execute(int64_t *vals); //used by RTSCommand to redirect values void prep(int8_t outputType, bool makeAbsRids); void project(); - void projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t pos); + void projectIntoRowGroup(rowgroup::RowGroup &rg, uint pos); void nextLBID(); bool isScan() { return _isScan; } void createCommand(messageqcpp::ByteStream &); void resetCommand(messageqcpp::ByteStream &); void setMakeAbsRids(bool m) { makeAbsRids = m; } bool willPrefetch(); - const uint64_t getEmptyRowValue( const execplan::CalpontSystemCatalog::ColDataType dataType, const int width ) const; + const int64_t getEmptyRowValue( const execplan::CalpontSystemCatalog::ColDataType dataType, const int width ) const; const int64_t getLastLbid(); - void getLBIDList(uint32_t loopCount, std::vector *lbids); + void getLBIDList(uint loopCount, std::vector *lbids); - virtual SCommand duplicate(); + SCommand duplicate(); bool operator==(const ColumnCommand &) const; bool operator!=(const ColumnCommand &) const; @@ -76,14 +76,6 @@ class ColumnCommand : public Command int getCompType() const { return colType.compressionType; } -protected: - virtual void loadData(); - void duplicate(ColumnCommand *); - - // we only care about the width and type fields. - //On the PM the rest is uninitialized - execplan::CalpontSystemCatalog::ColType colType; - private: ColumnCommand(const ColumnCommand &); ColumnCommand& operator=(const ColumnCommand &); @@ -96,8 +88,7 @@ class ColumnCommand : public Command void process_OT_DATAVALUE(); void process_OT_ROWGROUP(); void projectResult(); - void projectResultRG(rowgroup::RowGroup &rg, uint32_t pos); - void removeRowsFromRowGroup(rowgroup::RowGroup &); + void projectResultRG(rowgroup::RowGroup &rg, uint pos); void makeScanMsg(); void makeStepMsg(); void setLBID(uint64_t rid); @@ -110,7 +101,7 @@ class ColumnCommand : public Command // the length of base prim msg, which is everything up to the // rid array for the pCol message - uint32_t baseMsgLength; + uint baseMsgLength; uint64_t lbid; uint32_t traceFlags; // probably move this to Command @@ -123,7 +114,11 @@ class ColumnCommand : public Command uint8_t mask, shift; // vars for the selective block loader // counters to decide whether to prefetch or not - uint32_t blockCount, loadCount; + uint blockCount, loadCount; + + // we only care about the width and type fields. + //On the PM the rest is uninitialized + execplan::CalpontSystemCatalog::ColType colType; boost::shared_ptr parsedColumnFilter; @@ -131,13 +126,12 @@ class ColumnCommand : public Command boost::shared_ptr emptyFilter; bool suppressFilter; + UDFFcnPtr_t fUdfFuncPtr; std::vector lastLbid; /* speculative optimizations for projectintorowgroup() */ rowgroup::Row r; - uint32_t rowSize; - - bool wasVersioned; + uint rowSize; friend class RTSCommand; }; diff --git a/primitives/primproc/command.cpp b/primitives/primproc/command.cpp index 6c057867..1fc45ac1 100644 --- a/primitives/primproc/command.cpp +++ b/primitives/primproc/command.cpp @@ -15,6 +15,19 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +// +// $Id: command.cpp 1855 2012-04-04 18:20:09Z rdempsey $ +// C++ Implementation: command +// +// Description: +// +// +// Author: Patrick LeBlanc , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// + #include #include "bpp.h" @@ -30,12 +43,10 @@ Command::Command(CommandType c) : cmdType(c), fFilterFeeder(NOT_FEEDER) { } Command::~Command() { }; -void Command::createCommand(ByteStream &bs) +void Command::createCommand(ByteStream &bs) { bs >> OID; bs >> tupleKey; - bs >> queryUuid; - bs >> stepUuid; } void Command::resetCommand(ByteStream &bs) { }; @@ -65,9 +76,6 @@ Command* Command::makeCommand(ByteStream &bs, CommandType *type, vectorbpp; @@ -146,8 +169,10 @@ void Command::duplicate(Command *c) fFilterFeeder = c->fFilterFeeder; OID = c->OID; tupleKey = c->tupleKey; - queryUuid = c->queryUuid; - stepUuid = c->stepUuid; } +void Command::getLBIDList(uint count, vector *out) +{ } + +}; diff --git a/primitives/primproc/command.h b/primitives/primproc/command.h index 580edb5d..0772e4c9 100644 --- a/primitives/primproc/command.h +++ b/primitives/primproc/command.h @@ -15,15 +15,26 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +// +// $Id: command.h 1855 2012-04-04 18:20:09Z rdempsey $ +// C++ Interface: command +// +// Description: +// +// +// Author: Patrick LeBlanc , (C) 2008 +// +// Copyright: See COPYING file that comes with this distribution +// +// + #ifndef COMMAND_H #define COMMAND_H -#include -#include - #include "serializeable.h" #include "bytestream.h" #include "rowgroup.h" +#include namespace primitiveprocessor { @@ -34,78 +45,76 @@ typedef boost::shared_ptr SCommand; class Command { -public: - enum CommandType { - NONE, - COLUMN_COMMAND, - DICT_STEP, - DICT_SCAN, - PASS_THRU, - RID_TO_STRING, - FILTER_COMMAND, - PSEUDOCOLUMN - }; - - static const uint8_t NOT_FEEDER = 0; - static const uint8_t FILT_FEEDER = 1; - static const uint8_t LEFT_FEEDER = 3; - static const uint8_t RIGHT_FEEDER = 5; - - Command(CommandType c); - virtual ~Command(); - - virtual void execute() = 0; - virtual void project() = 0; - virtual void projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t columnPosition) = 0; - virtual uint64_t getLBID() = 0; - virtual void getLBIDList(uint32_t loopCount, std::vector *out) {} // the default fcn returns 0 lbids - virtual void nextLBID() = 0; - virtual void createCommand(messageqcpp::ByteStream &); - virtual void resetCommand(messageqcpp::ByteStream &); - - /* Duplicate() makes a copy of this object as constructed by createCommand(). - It's thread-safe */ - virtual SCommand duplicate() = 0; - bool operator==(const Command &) const; - bool operator!=(const Command& c) const { return !(*this == c); } - - /* Put bootstrap code here (ie, build the template primitive msg) */ - virtual void prep(int8_t outputType, bool makeAbsRids) = 0; - virtual void setBatchPrimitiveProcessor(BatchPrimitiveProcessor *); - virtual void setMakeAbsRids(bool); - - CommandType getCommandType() const { return cmdType; } - - // if feeding a filtercommand - // note: a filtercommand itself can feed another filtercommand - uint8_t filterFeeder() { return fFilterFeeder; } - void filterFeeder(uint8_t f) { fFilterFeeder = f; } - virtual void copyRidsForFilterCmd(); - - static Command* makeCommand(messageqcpp::ByteStream&, CommandType*, std::vector&); - - uint32_t getOID() const { return OID; } - uint32_t getTupleKey() const { return tupleKey; } - - virtual int getCompType() const=0; - -protected: - BatchPrimitiveProcessor *bpp; - CommandType cmdType; - uint8_t fFilterFeeder; - uint32_t OID; - uint32_t tupleKey; - boost::uuids::uuid queryUuid; - boost::uuids::uuid stepUuid; - - void duplicate(Command *); - -private: - Command(); - Command(const Command &); +// #warning got Command definition + public: + enum CommandType { + NONE, + COLUMN_COMMAND, + DICT_STEP, + DICT_SCAN, + PASS_THRU, + RID_TO_STRING, + FILTER_COMMAND + }; + + static const uint8_t NOT_FEEDER = 0; + static const uint8_t FILT_FEEDER = 1; + static const uint8_t LEFT_FEEDER = 3; + static const uint8_t RIGHT_FEEDER = 5; + + Command(CommandType c); + virtual ~Command(); + + virtual void execute() = 0; + virtual void project() = 0; + virtual void projectIntoRowGroup(rowgroup::RowGroup &rg, uint columnPosition) = 0; + virtual uint64_t getLBID() = 0; + virtual void getLBIDList(uint loopCount, std::vector *out); // the default fcn returns 0 lbids + virtual void nextLBID() = 0; + virtual void createCommand(messageqcpp::ByteStream &); + virtual void resetCommand(messageqcpp::ByteStream &); + + /* Duplicate() makes a copy of this object as constructed by createCommand(). + It's thread-safe */ + virtual SCommand duplicate() = 0; + bool operator==(const Command &) const; + bool operator!=(const Command &) const; + + /* Put bootstrap code here (ie, build the template primitive msg) */ + virtual void prep(int8_t outputType, bool makeAbsRids) = 0; + virtual void setBatchPrimitiveProcessor(BatchPrimitiveProcessor *); + virtual void setMakeAbsRids(bool); + + CommandType getCommandType() const { return cmdType; } + + // if feeding a filtercommand + // note: a filtercommand itself can feed another filtercommand + uint8_t filterFeeder() { return fFilterFeeder; } + void filterFeeder(uint8_t f) { fFilterFeeder = f; } + virtual void copyRidsForFilterCmd(); + + static Command* makeCommand(messageqcpp::ByteStream&, CommandType*, std::vector&); + + uint32_t getOID() const; + uint32_t getTupleKey() const; + + virtual int getCompType() const=0; + + protected: + BatchPrimitiveProcessor *bpp; + CommandType cmdType; + uint8_t fFilterFeeder; + uint32_t OID; + uint32_t tupleKey; + + void duplicate(Command *); + + private: + Command(); + Command(const Command &); }; -} +}; #endif diff --git a/primitives/primproc/dictstep.cpp b/primitives/primproc/dictstep.cpp index 029fa25d..67cd7082 100644 --- a/primitives/primproc/dictstep.cpp +++ b/primitives/primproc/dictstep.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: dictstep.cpp 2110 2013-06-19 15:51:38Z bwilkinson $ +// $Id: dictstep.cpp 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Implementation: dictstep // -// Description: +// Description: // // // Author: Patrick LeBlanc , (C) 2008 @@ -42,11 +42,11 @@ using namespace rowgroup; namespace primitiveprocessor { -extern uint32_t dictBufferSize; +extern uint dictBufferSize; extern bool utf8; DictStep::DictStep() : Command(DICT_STEP), strValues(NULL), filterCount(0), - bufferSize(0) + bufferSize(0) { } @@ -73,7 +73,7 @@ void DictStep::createCommand(ByteStream &bs) { uint8_t tmp8; - bs.advance(1); + bs >> tmp8; // eat the command bs >> BOP; bs >> tmp8; compressionType = tmp8; @@ -86,7 +86,7 @@ void DictStep::createCommand(ByteStream &bs) eqFilter.reset(new primitives::DictEqualityFilter()); bs >> eqOp; //cout << "saw the eqfilter count=" << filterCount << endl; - for (uint32_t i = 0; i < filterCount; i++) { + for (uint i = 0; i < filterCount; i++) { bs >> strTmp; //cout << " " << strTmp << endl; eqFilter->insert(strTmp); @@ -98,7 +98,7 @@ void DictStep::createCommand(ByteStream &bs) #if 0 cout << "see " << filterCount << " filters\n"; DictFilterElement *filters = (DictFilterElement *) filterString.buf(); - for (uint32_t i = 0; i < filterCount; i++) { + for (uint i = 0; i < filterCount; i++) { cout << " COP=" << (int) filters->COP << endl; cout << " len=" << filters->len << endl; cout << " string=" << filters->data << endl; @@ -121,19 +121,19 @@ void DictStep::prep(int8_t outputType, bool makeAbsRids) primMsg->ism.Interleave = 0; primMsg->ism.Flags = 0; -// primMsg->ism.Flags = PrimitiveMsg::planFlagsToPrimFlags(traceFlags); +// primMsg->ism.Flags = PrimitiveMsg::planFlagsToPrimFlags(traceFlags); primMsg->ism.Command=DICT_SIGNATURE; primMsg->ism.Size = bufferSize; primMsg->ism.Type = 2; primMsg->hdr.SessionID = bpp->sessionID; //primMsg->hdr.StatementID = 0; primMsg->hdr.TransactionID = bpp->txnID; - primMsg->hdr.VerID = bpp->versionInfo.currentScn; + primMsg->hdr.VerID = bpp->versionNum; primMsg->hdr.StepID = bpp->stepID; primMsg->BOP = BOP; primMsg->InputFlags = 1; //TODO: Use the new p_Dict functionality primMsg->OutputType = (eqFilter || filterCount || fFilterFeeder != NOT_FEEDER - ? OT_RID : OT_RID | OT_DATAVALUE); + ? OT_RID : OT_RID | OT_DATAVALUE); primMsg->NOPS = (eqFilter ? 0 : filterCount); primMsg->NVALS = 0; @@ -146,16 +146,16 @@ void DictStep::issuePrimitive(bool isFilter) uint32_t blocksRead; if (!(primMsg->LBID & 0x8000000000000000LL)) { - //cout << "DS issuePrimitive lbid: " << (uint64_t)primMsg->LBID << endl; + //cout << "DS issuePrimitive lbid: " << (uint64_t)primMsg->LBID << endl; primitiveprocessor::loadBlock(primMsg->LBID, - bpp->versionInfo, - bpp->txnID, - compressionType, - bpp->blockData, - &wasCached, - &blocksRead, - bpp->LBIDTrace, - bpp->sessionID); + bpp->versionNum, + bpp->txnID, + compressionType, + bpp->blockData, + &wasCached, + &blocksRead, + bpp->LBIDTrace, + bpp->sessionID); if (wasCached) bpp->cachedIO++; bpp->physIO += blocksRead; @@ -167,7 +167,7 @@ void DictStep::issuePrimitive(bool isFilter) void DictStep::copyResultToTmpSpace(OrderedToken *ot) { - uint32_t i; + uint i; uint8_t *pos; uint16_t len; uint64_t rid64; @@ -180,17 +180,14 @@ void DictStep::copyResultToTmpSpace(OrderedToken *ot) pos = &result[sizeof(DictOutput)]; for (i = 0; i < header->NVALS; i++) { - rid64 = *((uint64_t *) pos); - pos += 8; + rid64 = *((uint64_t *) pos); pos += 8; rid16 = rid64 & 0x1fff; ot[rid16].inResult = true; tmpResultCounter++; if (primMsg->OutputType & OT_DATAVALUE) { - len = *((uint16_t *) pos); - pos += 2; - ot[rid16].str = string((char *) pos, len); - pos += len; + len = *((uint16_t *) pos); pos += 2; + ot[rid16].str = string((char *) pos, len); pos += len; if (rid64 & 0x8000000000000000LL) ot[rid16].str = joblist::CPNULLSTRMARK; } @@ -199,12 +196,12 @@ void DictStep::copyResultToTmpSpace(OrderedToken *ot) void DictStep::copyResultToFinalPosition(OrderedToken *ot) { - uint32_t i, resultPos = 0; + uint i, resultPos = 0; for (i = 0; i < inputRidCount; i++) { if (ot[i].inResult) { bpp->absRids[resultPos] = ot[i].rid; - bpp->relRids[resultPos] = ot[i].rid - bpp->baseRid; + bpp->relRids[resultPos] = ot[i].rid & 0x1fff; if (primMsg->OutputType & OT_DATAVALUE) (*strValues)[resultPos] = ot[i].str; resultPos++; @@ -214,7 +211,7 @@ void DictStep::copyResultToFinalPosition(OrderedToken *ot) void DictStep::processResult() { - uint32_t i; + uint i; uint8_t *pos; uint16_t len; DictOutput *header = (DictOutput *) &result[0]; @@ -225,18 +222,14 @@ void DictStep::processResult() for (i = 0; i < header->NVALS; i++, tmpResultCounter++) { if (primMsg->OutputType & OT_RID) { - bpp->absRids[tmpResultCounter] = *((uint64_t *) pos); - pos += 8; - //bpp->relRids[tmpResultCounter] = bpp->absRids[tmpResultCounter] & 0x1fff; - bpp->relRids[tmpResultCounter] = bpp->absRids[tmpResultCounter] - bpp->baseRid; + bpp->absRids[tmpResultCounter] = *((uint64_t *) pos); pos += 8; + bpp->relRids[tmpResultCounter] = bpp->absRids[tmpResultCounter] & 0x1fff; } if (primMsg->OutputType & OT_DATAVALUE) { - len = *((uint16_t *) pos); - pos += 2; - (*strValues)[tmpResultCounter] = string((char *) pos, len); - pos += len; + len = *((uint16_t *) pos); pos += 2; + (*strValues)[tmpResultCounter] = string((char *) pos, len); pos += len; } - //cout << " stored " << (*strValues)[tmpResultCounter] << endl; + //cout << " stored " << (*strValues)[tmpResultCounter] << endl; /* XXXPAT: disclaimer: this is how we do it in DictionaryStep; don't know if it's necessary or not yet */ if ((bpp->absRids[tmpResultCounter] & 0x8000000000000000LL) != 0) { @@ -247,9 +240,9 @@ void DictStep::processResult() } } -void DictStep::projectResult(string* strings) +void DictStep::projectResult(string *strings) { - uint32_t i; + uint i; uint8_t *pos; uint16_t len; DictOutput *header = (DictOutput *) &result[0]; @@ -259,42 +252,9 @@ void DictStep::projectResult(string* strings) pos = &result[sizeof(DictOutput)]; //cout << "projectResult() l: " << primMsg->LBID << " NVALS: " << header->NVALS << endl; for (i = 0; i < header->NVALS; i++) { - len = *((uint16_t *) pos); - pos += 2; + len = *((uint16_t *) pos); pos += 2; strings[tmpResultCounter++] = string((char *) pos, len); - //cout << "serialized length is " << len << " string is " << strings[tmpResultCounter-1] << " string length = " << - // strings[tmpResultCounter-1].length() << endl; - pos += len; - totalResultLength += len + 4; - } -} - -// bug4901 - -// This version of projectResult needs to stay in sync with -// the above. They are separate methods because the -// _projectToRG() method can deal with this optimized version -// where we only need to return the pointer and length. This -// is desirable because it avoids an unnecessary temporary -// string copy. The above version is still needed for the -// _project() method where it has to serialize the totalResultLength -// before starting to serialize strings. -void DictStep::projectResult(StringPtr *strings) -{ - uint32_t i; - uint8_t *pos; - uint16_t len; - DictOutput *header = (DictOutput *) &result[0]; - - if (header->NVALS == 0) return; - - pos = &result[sizeof(DictOutput)]; - //cout << "projectResult() l: " << primMsg->LBID << " NVALS: " << header->NVALS << endl; - for (i = 0; i < header->NVALS; i++) { - len = *((uint16_t *) pos); - pos += 2; - strings[tmpResultCounter++] = StringPtr(pos, len); - //cout << "serialized length is " << len << " string is " << strings[tmpResultCounter-1] << " string length = " << - // strings[tmpResultCounter-1].length() << endl; + //cout << "serialized length is " << len << " string is " << string((char *) pos, len) << endl; pos += len; totalResultLength += len + 4; } @@ -302,9 +262,9 @@ void DictStep::projectResult(StringPtr *strings) void DictStep::execute() { - if (fFilterFeeder == LEFT_FEEDER) + if (fFilterFeeder == LEFT_FEEDER) strValues = &(bpp->fFiltStrValues[0]); - else if (fFilterFeeder == RIGHT_FEEDER) + else if (fFilterFeeder == RIGHT_FEEDER) strValues = &(bpp->fFiltStrValues[1]); else strValues = &(bpp->strValues); @@ -344,13 +304,13 @@ void DictStep::_execute() while (i < bpp->ridCount && ((((int64_t) newRidList[i].token) >> 10) == l_lbid )) { if (UNLIKELY(l_lbid < 0)) pt[primMsg->NVALS].rid = - (fFilterFeeder == NOT_FEEDER ? newRidList[i].rid : i) + (fFilterFeeder == NOT_FEEDER ? newRidList[i].rid : i) | 0x8000000000000000LL; else pt[primMsg->NVALS].rid = - (fFilterFeeder == NOT_FEEDER ? newRidList[i].rid : i); + (fFilterFeeder == NOT_FEEDER ? newRidList[i].rid : i); pt[primMsg->NVALS].offsetIndex = newRidList[i].token & 0x3ff; - idbassert(pt[primMsg->NVALS].offsetIndex != 0); + idbassert(pt[primMsg->NVALS].offsetIndex != 0); primMsg->NVALS++; i++; } @@ -367,19 +327,19 @@ void DictStep::_execute() bpp->ridCount = tmpResultCounter; // check if feeding a filtercommand - if (fFilterFeeder != NOT_FEEDER) { - sort(&newRidList[0], &newRidList[inputRidCount], PosSorter()); - copyResultToFinalPosition(newRidList.get()); - copyRidsForFilterCmd(); - } - //cout << "DS: /_execute()\n"; + if (fFilterFeeder != NOT_FEEDER) { + sort(&newRidList[0], &newRidList[inputRidCount], PosSorter()); + copyResultToFinalPosition(newRidList.get()); + copyRidsForFilterCmd(); + } + //cout << "DS: /_execute()\n"; } /* This will do the same thing as execute() but put the result in bpp->serialized */ void DictStep::_project() { /* Need to loop over bpp->values, issuing a primitive for each LBID */ - uint32_t i; + uint i; int64_t l_lbid=0; OldGetSigParams *pt; string tmpStrings[LOGICAL_BLOCK_RIDS]; @@ -393,7 +353,7 @@ void DictStep::_project() newRidList[i].pos = i; } - //cout << "DS: _project()\n"; + //cout << "DS: _project()\n"; tmpResultCounter = 0; totalResultLength = 0; i = 0; @@ -420,22 +380,22 @@ void DictStep::_project() } idbassert(tmpResultCounter == bpp->ridCount); *bpp->serialized << totalResultLength; - //cout << "_project() total length = " << totalResultLength << endl; + //cout << "_project() total length = " << totalResultLength << endl; for (i = 0; i < tmpResultCounter; i++) { - //cout << "serializing " << tmpStrings[i] << endl; + //cout << "serializing " << tmpStrings[i] << endl; *bpp->serialized << tmpStrings[i]; } - //cout << "DS: /_project() l: " << l_lbid << endl; + //cout << "DS: /_project() l: " << l_lbid << endl; } -void DictStep::_projectToRG(RowGroup &rg, uint32_t col) +void DictStep::_projectToRG(RowGroup &rg, uint col) { /* Need to loop over bpp->values, issuing a primitive for each LBID */ - uint32_t i; + uint i; int64_t l_lbid=0; int64_t o_lbid=0; OldGetSigParams *pt; - StringPtr tmpStrings[LOGICAL_BLOCK_RIDS]; + string tmpStrings[LOGICAL_BLOCK_RIDS]; rowgroup::Row r; boost::scoped_array newRidList; @@ -448,12 +408,10 @@ void DictStep::_projectToRG(RowGroup &rg, uint32_t col) } sort(&newRidList[0], &newRidList[bpp->ridCount], TokenSorter()); - rg.initRow(&r); - uint32_t curResultCounter = 0; tmpResultCounter = 0; totalResultLength = 0; i = 0; - //cout << "DS: projectingToRG rids: " << bpp->ridCount << endl; + //cout << "DS: projectingToRG rids: " << bpp->ridCount << endl; while (i < bpp->ridCount) { l_lbid = ((int64_t) newRidList[i].token) >> 10; primMsg->LBID = l_lbid; @@ -463,7 +421,7 @@ void DictStep::_projectToRG(RowGroup &rg, uint32_t col) //@bug 972 //@bug 1821 while (iridCount && ((((int64_t)newRidList[i].token)>>10) == l_lbid || l_lbid == -1 - || ((((int64_t)newRidList[i].token)>>10) & 0x8000000000000000LL)) ) + || ((((int64_t)newRidList[i].token)>>10) & 0x8000000000000000LL)) ) { //@bug 1821 if (newRidList[i].token==0) @@ -497,7 +455,7 @@ void DictStep::_projectToRG(RowGroup &rg, uint32_t col) // pt++; i++; } - + if (((int64_t)primMsg->LBID)<0 && o_lbid>0) primMsg->LBID = o_lbid; @@ -505,30 +463,28 @@ void DictStep::_projectToRG(RowGroup &rg, uint32_t col) issuePrimitive(false); projectResult(tmpStrings); o_lbid=0; - //cout << "DS: project & issue l: " << (int64_t)primMsg->LBID << " NVALS: " << primMsg->NVALS << endl; - - // bug 4901 - move this inside the loop and call incrementally - // to save the unnecessary string copy - if (rg.getColTypes()[col] != execplan::CalpontSystemCatalog::VARBINARY) { - for (i = curResultCounter; i < tmpResultCounter; i++) { - rg.getRow(newRidList[i].pos, &r); - //cout << "serializing " << tmpStrings[i] << endl; - r.setStringField(tmpStrings[i].ptr, tmpStrings[i].len, col); - } - } - else { - for (i = curResultCounter; i < tmpResultCounter; i++) { - rg.getRow(newRidList[i].pos, &r); - r.setVarBinaryField(tmpStrings[i].ptr, tmpStrings[i].len, col); - } - } - curResultCounter = tmpResultCounter; + //cout << "DS: project & issue l: " << (int64_t)primMsg->LBID << " NVALS: " << primMsg->NVALS << endl; } - //cout << "_projectToRG() total length = " << totalResultLength << endl; + //cout << "_projectToRG() total length = " << totalResultLength << endl; idbassert(tmpResultCounter == bpp->ridCount); + rg.initRow(&r); +// rg.getRow(newRidList[0].pos, &r); + if (rg.getColTypes()[col] != execplan::CalpontSystemCatalog::VARBINARY) { + for (i = 0; i < tmpResultCounter; i++) { + rg.getRow(newRidList[i].pos, &r); + //cout << "serializing " << tmpStrings[i] << endl; + r.setStringField(tmpStrings[i], col); + } + } + else { + for (i = 0; i < tmpResultCounter; i++) { + rg.getRow(newRidList[i].pos, &r); + r.setVarBinaryField(tmpStrings[i], col); + } + } - //cout << "DS: /projectingToRG l: " << (int64_t)primMsg->LBID + //cout << "DS: /projectingToRG l: " << (int64_t)primMsg->LBID // << " len: " << tmpResultCounter // << endl; } @@ -545,13 +501,13 @@ void DictStep::project(int64_t *vals) _project(); } -void DictStep::projectIntoRowGroup(RowGroup &rg, uint32_t col) +void DictStep::projectIntoRowGroup(RowGroup &rg, uint col) { values = bpp->values; _projectToRG(rg, col); } -void DictStep::projectIntoRowGroup(RowGroup &rg, int64_t *vals, uint32_t col) +void DictStep::projectIntoRowGroup(RowGroup &rg, int64_t *vals, uint col) { values = vals; _projectToRG(rg, col); @@ -588,10 +544,10 @@ SCommand DictStep::duplicate() bool DictStep::operator==(const DictStep &ds) const { return ((BOP == ds.BOP) && - (fFilterFeeder == ds.fFilterFeeder) && - (compressionType == ds.compressionType) && - (filterString == ds.filterString) && - (filterCount == ds.filterCount)); + (fFilterFeeder == ds.fFilterFeeder) && + (compressionType == ds.compressionType) && + (filterString == ds.filterString) && + (filterCount == ds.filterCount)); } bool DictStep::operator!=(const DictStep &ds) const diff --git a/primitives/primproc/dictstep.h b/primitives/primproc/dictstep.h index de2a3fde..d5a585bf 100644 --- a/primitives/primproc/dictstep.h +++ b/primitives/primproc/dictstep.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ // -// $Id: dictstep.h 2110 2013-06-19 15:51:38Z bwilkinson $ +// $Id: dictstep.h 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Interface: dictstep // // Description: @@ -46,8 +46,8 @@ class DictStep : public Command void execute(); void project(); void project(int64_t *vals); //used by RTSCommand to redirect input - void projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t row); - void projectIntoRowGroup(rowgroup::RowGroup &rg, int64_t *vals, uint32_t col); + void projectIntoRowGroup(rowgroup::RowGroup &rg, uint row); + void projectIntoRowGroup(rowgroup::RowGroup &rg, int64_t *vals, uint col); uint64_t getLBID(); /* This doesn't do anything for this class... make it column-specific or not? */ @@ -69,21 +69,12 @@ class DictStep : public Command DictStep(const DictStep &); DictStep& operator=(const DictStep &); - struct StringPtr { - const uint8_t* ptr; - unsigned len; - - StringPtr() : ptr(NULL), len(0) {;} - StringPtr(const uint8_t* p, unsigned l) : ptr(p), len(l) {;} - }; - void _execute(); void issuePrimitive(bool isProjection); void processResult(); - void projectResult(std::string* tmpStrings); - void projectResult(StringPtr *tmpStrings); + void projectResult(std::string *tmpStrings); void _project(); - void _projectToRG(rowgroup::RowGroup &rg, uint32_t col); + void _projectToRG(rowgroup::RowGroup &rg, uint col); // struct used for scratch space struct OrderedToken { @@ -111,8 +102,8 @@ class DictStep : public Command // Worst case, 8192 tokens in the msg. Each is 10 bytes. */ boost::scoped_array inputMsg; - uint32_t tmpResultCounter; - uint32_t totalResultLength; + uint tmpResultCounter; + uint totalResultLength; DictInput *primMsg; std::vector result; diff --git a/primitives/primproc/filtercommand.cpp b/primitives/primproc/filtercommand.cpp index 91a89a23..86dfef52 100644 --- a/primitives/primproc/filtercommand.cpp +++ b/primitives/primproc/filtercommand.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: filtercommand.cpp 2035 2013-01-21 14:12:19Z rdempsey $ +* $Id: filtercommand.cpp 1855 2012-04-04 18:20:09Z rdempsey $ * * ***********************************************************************/ @@ -40,6 +40,93 @@ const uint32_t DCC = (ds << 16) | (cc << 8) | cc; const uint32_t CDC = (cc << 16) | (ds << 8) | cc; const uint32_t DCDC = (ds << 24) | (cc << 16) | (ds << 8) | cc; +inline bool isNull(int64_t val, const execplan::CalpontSystemCatalog::ColType& ct) +{ + bool ret = false; + + switch (ct.colDataType) + { + case execplan::CalpontSystemCatalog::TINYINT: + { + if ((int8_t) joblist::TINYINTNULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::CHAR: + { + int colWidth = ct.colWidth; + if (colWidth <= 8) + { + if ((colWidth == 1) && ((int8_t) joblist::CHAR1NULL == val)) ret = true ; + else if ((colWidth == 2) && ((int16_t) joblist::CHAR2NULL == val)) ret = true; + else if ((colWidth < 5) && ((int32_t) joblist::CHAR4NULL == val)) ret = true; + else if ((int64_t) joblist::CHAR8NULL == val) ret = true; + } + else + { + throw logic_error("Not a int column."); + } + break; + } + case execplan::CalpontSystemCatalog::SMALLINT: + { + if ((int16_t) joblist::SMALLINTNULL == val) ret = true; + break; + } + //TODO: does DECIMAL belong here? + case execplan::CalpontSystemCatalog::DECIMAL: + case execplan::CalpontSystemCatalog::DOUBLE: + { + if ((int64_t) joblist::DOUBLENULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::MEDINT: + case execplan::CalpontSystemCatalog::INT: + { + if ((int32_t) joblist::INTNULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::FLOAT: + { + if ((int32_t) joblist::FLOATNULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::DATE: + { + if ((int32_t) joblist::DATENULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::BIGINT: + { + if ((int64_t) joblist::BIGINTNULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::DATETIME: + { + if ((int64_t) joblist::DATETIMENULL == val) ret = true; + break; + } + case execplan::CalpontSystemCatalog::VARCHAR: + { + int colWidth = ct.colWidth; + if (colWidth <= 8) + { + if ((colWidth < 3) && ((int16_t) joblist::CHAR2NULL == val)) ret = true; + else if ((colWidth < 5) && ((int32_t) joblist::CHAR4NULL == val)) ret = true; + else if ((int64_t) joblist::CHAR8NULL == val) ret = true; + } + else + { + throw logic_error("Not a int column."); + } + break; + } + default: + break; + } + + return ret; +} + }; @@ -48,7 +135,9 @@ namespace primitiveprocessor Command* FilterCommand::makeFilterCommand(ByteStream& bs, vector& cmds) { - bs.advance(1); + // skip the command type byte -- filtercommand + bs.advance(1); + // find out the # of commands in the cmds vector, // vector::size() will not work, because cmds is resize() to filterCount uint64_t nc = 0; @@ -135,7 +224,7 @@ Command* FilterCommand::makeFilterCommand(ByteStream& bs, vector& cmds cmds[nc-1]->filterFeeder(RIGHT_FEEDER); ColumnCommand* cmd0 = dynamic_cast(cmds[nc-3].get()); ColumnCommand* cmd1 = dynamic_cast(cmds[nc-2].get()); - size_t cl = cmd0->getWidth(); // char[] column + size_t cl = cmd0->getWidth(); // char[] column sc->setCharLength(cl); sc->setCompareFunc(DCC); fc = sc; @@ -203,7 +292,7 @@ void FilterCommand::project() { } -void FilterCommand::projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t col) +void FilterCommand::projectIntoRowGroup(rowgroup::RowGroup &rg, uint col) { } @@ -248,7 +337,7 @@ void FilterCommand::doFilter() bpp->ridCount = 0; // rids in [0] is used for scan [1], so [1] is a subset of [0], and same order. - // -- see makeFilterCommand() above. + // -- see makeFilterCommand() above. for (uint64_t i = 0, j = 0; j < bpp->fFiltRidCount[1]; ) { if (bpp->fFiltCmdRids[0][i] != bpp->fFiltCmdRids[1][j]) @@ -277,8 +366,8 @@ void FilterCommand::doFilter() bool FilterCommand::compare(uint64_t i, uint64_t j) { - if (execplan::isNull(bpp->fFiltCmdValues[0][i], leftColType) || - execplan::isNull(bpp->fFiltCmdValues[1][j], rightColType)) + if (isNull(bpp->fFiltCmdValues[0][i], leftColType) || + isNull(bpp->fFiltCmdValues[1][j], rightColType)) return false; switch(fBOP) @@ -347,8 +436,8 @@ SCommand ScaledFilterCmd::duplicate() bool ScaledFilterCmd::compare(uint64_t i, uint64_t j) { - if (execplan::isNull(bpp->fFiltCmdValues[0][i], leftColType) || - execplan::isNull(bpp->fFiltCmdValues[1][j], rightColType)) + if (isNull(bpp->fFiltCmdValues[0][i], leftColType) || + isNull(bpp->fFiltCmdValues[1][j], rightColType)) return false; switch(fBOP) @@ -469,8 +558,8 @@ void StrFilterCmd::setCompareFunc(uint32_t columns) bool StrFilterCmd::compare_cc(uint64_t i, uint64_t j) { - if (execplan::isNull(bpp->fFiltCmdValues[0][i], leftColType) || - execplan::isNull(bpp->fFiltCmdValues[1][j], rightColType)) + if (isNull(bpp->fFiltCmdValues[0][i], leftColType) || + isNull(bpp->fFiltCmdValues[1][j], rightColType)) return false; switch(fBOP) @@ -535,7 +624,7 @@ bool StrFilterCmd::compare_ss(uint64_t i, uint64_t j) bool StrFilterCmd::compare_cs(uint64_t i, uint64_t j) { - if (execplan::isNull(bpp->fFiltCmdValues[0][i], leftColType) || + if (isNull(bpp->fFiltCmdValues[0][i], leftColType) || bpp->fFiltStrValues[1][j] == "" || bpp->fFiltStrValues[1][j] == joblist::CPNULLSTRMARK) return false; @@ -571,7 +660,7 @@ bool StrFilterCmd::compare_cs(uint64_t i, uint64_t j) bool StrFilterCmd::compare_sc(uint64_t i, uint64_t j) { if (bpp->fFiltStrValues[0][i] == "" || bpp->fFiltStrValues[0][i] == joblist::CPNULLSTRMARK || - execplan::isNull(bpp->fFiltCmdValues[1][j], rightColType)) + isNull(bpp->fFiltCmdValues[1][j], rightColType)) return false; int cmp = strncmp(bpp->fFiltStrValues[0][i].c_str(), diff --git a/primitives/primproc/filtercommand.h b/primitives/primproc/filtercommand.h index d2d2b102..f2f535bb 100644 --- a/primitives/primproc/filtercommand.h +++ b/primitives/primproc/filtercommand.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** -* $Id: filtercommand.h 2035 2013-01-21 14:12:19Z rdempsey $ +* $Id: filtercommand.h 1855 2012-04-04 18:20:09Z rdempsey $ * * ***********************************************************************/ @@ -49,7 +49,7 @@ class FilterCommand : public Command // virtuals from base class -- Command void execute(); void project(); - void projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t col); + void projectIntoRowGroup(rowgroup::RowGroup &rg, uint col); uint64_t getLBID(); void nextLBID(); void createCommand(messageqcpp::ByteStream&); diff --git a/primitives/primproc/logger.cpp b/primitives/primproc/logger.cpp index 9aaeee9d..40216375 100644 --- a/primitives/primproc/logger.cpp +++ b/primitives/primproc/logger.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* - * $Id: logger.cpp 2035 2013-01-21 14:12:19Z rdempsey $ + * $Id: logger.cpp 1855 2012-04-04 18:20:09Z rdempsey $ */ #include diff --git a/primitives/primproc/monitorprocmem.cpp b/primitives/primproc/monitorprocmem.cpp new file mode 100644 index 00000000..1131956e --- /dev/null +++ b/primitives/primproc/monitorprocmem.cpp @@ -0,0 +1,283 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: monitorprocmem.cpp 2012 2012-12-10 21:08:03Z xlou $ + * + *****************************************************************************/ + +#ifdef _MSC_VER +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#include +#endif +#include +#include +#include +#include +#include +using namespace std; + +#include "loggingid.h" +#include "messageids.h" +#include "pp_logger.h" + +#include "monitorprocmem.h" + +namespace primitiveprocessor +{ + +unsigned MonitorProcMem::fMemAvailPct = 0; +unsigned MonitorProcMem::fAggMemCheck = 0; + +//------------------------------------------------------------------------------ +// Thread entry point function, that drives a thread to periodically (every +// 15 seconds by default) monitor the memory usage for the process we are +// running in. If we exceed the memory percentage specified to the constructor, +// this thread will terminate the process by calling exit(). +//------------------------------------------------------------------------------ +void MonitorProcMem::operator()() const +{ + const unsigned logRssTooBig = logging::M0045; + const size_t mt = memTotal(); + + while (1) + { + if (fMaxPct > 0) + { + size_t rssMb = rss(); + size_t pct = rssMb * 100 / mt; + if (pct > fMaxPct) + { + cerr << "PrimProc: Too much memory allocated!" << endl; + logging::Message::Args args; + + fMsgLog->logMessage ( logRssTooBig, + logging::Message::Args(), + true ); + exit(1); + } + } + + fMemAvailPct = memAvailPct(); + + pause_(); + } +} + +//------------------------------------------------------------------------------ +// Returns the maximum memory available on the current host this process is +// running on. +//------------------------------------------------------------------------------ +size_t MonitorProcMem::memTotal() const +{ + size_t memTot; + +#if defined(_MSC_VER) + MEMORYSTATUSEX memStat; + memStat.dwLength = sizeof(memStat); + if (GlobalMemoryStatusEx(&memStat) == 0) + //FIXME: Assume 2GB? + memTot = 2 * 1024 * 1024; + else + { +#ifndef _WIN64 + memStat.ullTotalPhys = std::min(memStat.ullTotalVirtual, memStat.ullTotalPhys); +#endif + //We now have the total phys mem in bytes + memTot = memStat.ullTotalPhys / 1024; + } +#elif defined(__FreeBSD__) + string cmd("sysctl -a | awk '/realmem/ {print int(($2+1023)/1024);}'"); + FILE* cmdPipe; + char input[80]; + cmdPipe = popen(cmd.c_str(), "r"); + input[0] = '\0'; + fgets(input, 80, cmdPipe); + input[79] = '\0'; + pclose(cmdPipe); + memTot = atoi(input); +#else + ifstream in("/proc/meminfo"); + string x; + + in >> x; + in >> memTot; +#endif + + //memTot is now in KB, convert to MB + memTot /= 1024; + + return memTot; +} + +//------------------------------------------------------------------------------ +// Returns the RSS memory usage for the current process by reading the pid's +// statm file. +//------------------------------------------------------------------------------ +size_t MonitorProcMem::rss() const +{ + uint64_t rss; + +#if defined(_MSC_VER) + HANDLE hProcess; + PROCESS_MEMORY_COUNTERS pmc; + hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | + PROCESS_VM_READ, + FALSE, fPid ); + if (NULL == hProcess) + return 0; + + if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) + rss = pmc.WorkingSetSize; + else + rss = 0; + + CloseHandle( hProcess ); +#elif defined(__FreeBSD__) + ostringstream cmd; + cmd << "ps -a -o rss -p " << getpid() << " | tail +2"; + FILE* cmdPipe; + char input[80]; + cmdPipe = popen(cmd.str().c_str(), "r"); + input[0] = '\0'; + fgets(input, 80, cmdPipe); + input[79] = '\0'; + pclose(cmdPipe); + rss = atoi(input) * 1024LL; +#else + ostringstream pstat; + pstat << "/proc/" << fPid << "/statm"; + ifstream in(pstat.str().c_str()); + size_t x; + + in >> x; + in >> rss; + + //rss is now in pages, convert to MB + rss *= fPageSize; +#endif + rss /= (1024ULL * 1024ULL); + + return static_cast(rss); +} + +//------------------------------------------------------------------------------ +// Stays in "sleep" state till fSleepSec seconds have elapsed. +//------------------------------------------------------------------------------ +void MonitorProcMem::pause_( ) const +{ + struct timespec req; + struct timespec rem; + + req.tv_sec = fSleepSec; + req.tv_nsec = 0; + + rem.tv_sec = 0; + rem.tv_nsec = 0; + + while (1) + { +#ifdef _MSC_VER + Sleep(req.tv_sec * 1000); +#else + if (nanosleep(&req, &rem) != 0) + { + if (rem.tv_sec > 0 || rem.tv_nsec > 0) + { + req = rem; + continue; + } + } +#endif + break; + } +} + +//------------------------------------------------------------------------------ +// Returns the system free memory % +//------------------------------------------------------------------------------ +unsigned MonitorProcMem::memAvailPct() const +{ + uint64_t memTotal = 1; + uint64_t memFree = 0; + uint64_t buffers = 0; + uint64_t cached = 0; + +#if defined(_MSC_VER) + MEMORYSTATUSEX memStat; + memStat.dwLength = sizeof(memStat); + if (GlobalMemoryStatusEx(&memStat)) + { +#ifndef _WIN64 + memStat.ullTotalPhys = std::min(memStat.ullTotalVirtual, memStat.ullTotalPhys); +#endif + //We now have the total phys mem in bytes + memTotal = memStat.ullTotalPhys; + memFree = memStat.ullAvailPhys; +#ifndef _WIN64 + if (memFree > memTotal) + memFree = memTotal; +#endif + } +#elif defined(__FreeBSD__) + // FreeBSD is not supported, no optimization. + memFree = 0; +#else + ifstream in("/proc/meminfo"); + string x; + + in >> x; // MemTotal: + in >> memTotal; + in >> x; // kB + + in >> x; // MemFree: + in >> memFree; + in >> x; // kB + + in >> x; // Buffers: + in >> buffers; + in >> x; // kB + + in >> x; // Cached: + in >> cached; +#endif + + // % available for application + return ((100 * (memFree + buffers + cached)) / memTotal); +} + +//------------------------------------------------------------------------------ +// Returns the system used memory % +//------------------------------------------------------------------------------ +unsigned MonitorProcMem::memUsedPct() +{ + return (100 - fMemAvailPct); +} + +//------------------------------------------------------------------------------ +// Returns if need to flush aggregation memory +//------------------------------------------------------------------------------ +bool MonitorProcMem::flushAggregationMem() +{ + // used memory > aggregation memory check + return (fMemAvailPct + fAggMemCheck < 100); +} + +} // end of namespace diff --git a/primitives/primproc/monitorprocmem.h b/primitives/primproc/monitorprocmem.h new file mode 100644 index 00000000..b6b2a5e7 --- /dev/null +++ b/primitives/primproc/monitorprocmem.h @@ -0,0 +1,118 @@ +/* Copyright (C) 2014 InfiniDB, Inc. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; version 2 of + the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/****************************************************************************** + * $Id: monitorprocmem.h 2012 2012-12-10 21:08:03Z xlou $ + * + *****************************************************************************/ + +/** @file StagedDL datalist used to process data concurrently in stages. + * + */ + +#ifndef MONITORPROCMEM_H__ +#define MONITORPROCMEM_H__ + +#include +#include + +#include "pp_logger.h" + +namespace primitiveprocessor +{ + +/** @brief A class to monitor a process's memory usage. + * + * This class will monitor and terminate the process if + * this process exceeds the specified memory limit. + */ +class MonitorProcMem +{ + public: + /** @brief MonitorProcMem constructor + * + * @param maxPct (in) maximum allowable memory usage + * @param memChk (in) monitor total system physical memory usage + * @param msgLog (in) message logger to log msg to + * @param sec (in) number of seconds between memory checks + */ + explicit MonitorProcMem(size_t maxPct, + size_t memChk, + Logger* msgLog, + unsigned sec=1) : + fPid ( getpid() ), + fMaxPct ( maxPct ), + fSleepSec( sec ), + fMsgLog ( msgLog ), + fPageSize( getpagesize() ) { fAggMemCheck = memChk; } + + /** @brief Thread entry point + * + * Entry point for this thread that monitors memory usage. + */ + void operator()() const; + + /* return the % of total memory used + * + */ + static unsigned memUsedPct(); + + /* return if memory usage is above aggregation flush limit + * + */ + static bool flushAggregationMem(); + + + private: + //Defaults are okay + //MonitorProcMem (const MonitorProcMem& rhs); + //MonitorProcMem& operator=(const MonitorProcMem& rhs); + + /** return the current process RSS size in MB + * + */ + size_t rss() const; + + /* return the system RAM size in MB + * + */ + size_t memTotal() const; + + /* pause for fSleepSec seconds between memory usage checks + * + */ + void pause_() const; + + /* return the system % of free memory + * + */ + unsigned memAvailPct() const; + + pid_t fPid; // process pid + size_t fMaxPct; // max allowable % memory use + unsigned fSleepSec; // sleep interval in seconds + Logger* fMsgLog; // Logger used to record error msg + int fPageSize; // page size for this host (in bytes) + + // @bug4507, monitor % of total used system memory + static unsigned fMemAvailPct; + static unsigned fAggMemCheck; +}; + +} + +#endif diff --git a/primitives/primproc/passthrucommand.cpp b/primitives/primproc/passthrucommand.cpp index b4176127..8d1bb6ad 100644 --- a/primitives/primproc/passthrucommand.cpp +++ b/primitives/primproc/passthrucommand.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: passthrucommand.cpp 2093 2013-05-08 19:23:58Z pleblanc $ +// $Id: passthrucommand.cpp 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Implementation: passthrucommand // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -62,7 +62,7 @@ void PassThruCommand::execute() void PassThruCommand::project() { - uint32_t i; + uint i; *bpp->serialized << (uint32_t) (bpp->ridCount * colWidth); #if 0 @@ -92,15 +92,13 @@ void PassThruCommand::project() } } -void PassThruCommand::projectIntoRowGroup(RowGroup &rg, uint32_t col) +void PassThruCommand::projectIntoRowGroup(RowGroup &rg, uint col) { - uint32_t i; + uint i; + uint offset = r.getOffset(col); rg.initRow(&r); rg.getRow(0, &r); - uint32_t offset = r.getOffset(col); - rowSize = r.getSize(); - switch (colWidth) { case 1: for (i = 0; i < bpp->ridCount; i++) { @@ -118,6 +116,7 @@ void PassThruCommand::projectIntoRowGroup(RowGroup &rg, uint32_t col) break; case 4: for (i = 0; i < bpp->ridCount; i++) { +// cout << "PTC: " << bpp->values[i] << endl; r.setUintField_offset<4>(bpp->values[i], offset); r.nextRow(rowSize); } @@ -143,7 +142,7 @@ void PassThruCommand::nextLBID() void PassThruCommand::createCommand(ByteStream &bs) { - bs.advance(1); + bs.advance(1); bs >> colWidth; Command::createCommand(bs); } diff --git a/primitives/primproc/passthrucommand.h b/primitives/primproc/passthrucommand.h index 37e581ec..7d2011ed 100644 --- a/primitives/primproc/passthrucommand.h +++ b/primitives/primproc/passthrucommand.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ // -// $Id: passthrucommand.h 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: passthrucommand.h 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Interface: passthrucommand // // Description: @@ -45,7 +45,7 @@ class PassThruCommand : public Command void prep(int8_t outputType, bool makeAbsRids); void execute(); void project(); - void projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t col); + void projectIntoRowGroup(rowgroup::RowGroup &rg, uint col); uint64_t getLBID(); void nextLBID(); void createCommand(messageqcpp::ByteStream &); @@ -62,7 +62,7 @@ class PassThruCommand : public Command /* Minor optimization for projectIntoRowGroup() */ rowgroup::Row r; - uint32_t rowSize; + uint rowSize; }; } diff --git a/primitives/primproc/primitiveserver.cpp b/primitives/primproc/primitiveserver.cpp index 1d7462c3..4cb26961 100644 --- a/primitives/primproc/primitiveserver.cpp +++ b/primitives/primproc/primitiveserver.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: primitiveserver.cpp 2147 2013-08-14 20:44:44Z bwilkinson $ + * $Id: primitiveserver.cpp 2068 2013-03-28 21:03:39Z pleblanc $ * * ***********************************************************************/ @@ -32,6 +32,7 @@ #include #include #ifdef _MSC_VER +#include #include typedef int pthread_t; #else @@ -77,20 +78,16 @@ using namespace config; #include "pp_logger.h" using namespace primitives; +#include "multicast.h" +using namespace multicast; #include "errorcodes.h" #include "exceptclasses.h" #include "idbcompress.h" using namespace compress; -#include "IDBDataFile.h" -#include "IDBPolicy.h" -using namespace idbdatafile; - using namespace threadpool; -#include "atomicops.h" - #ifndef O_BINARY # define O_BINARY 0 #endif @@ -108,193 +105,218 @@ typedef tr1::unordered_set USOID; // make global for blockcache // -static const char* statsName = {"pm"}; -dbbc::Stats* gPMStatsPtr=0; +static const char* statsName ={"pm"}; +Stats* gPMStatsPtr=0; bool gPMProfOn=false; uint32_t gSession=0; #ifndef _MSC_VER -dbbc::Stats pmstats(statsName); +Stats pmstats(statsName); #endif -oam::OamCache *oamCache = oam::OamCache::makeOamCache(); - //FIXME: there is an anon ns burried later in between 2 named namespaces... namespace primitiveprocessor { -boost::shared_ptr OOBPool; +#ifdef _MSC_VER + extern CRITICAL_SECTION preadCSObject; +#else +//#define IDB_COMP_POC_DEBUG +#ifdef IDB_COMP_POC_DEBUG +extern boost::mutex compDebugMutex; +#endif +#endif -BlockRequestProcessor **BRPp; + BlockRequestProcessor **BRPp; #ifndef _MSC_VER -dbbc::Stats stats; + Stats stats; #endif -extern DebugLevel gDebugLevel; -BRM::DBRM* brm; -int fCacheCount; -bool fPMProfOn; -bool fLBIDTraceOn; - -/* params from the config file */ -uint32_t BPPCount; -uint32_t blocksReadAhead; -uint32_t defaultBufferSize; -uint32_t connectionsPerUM; -uint32_t highPriorityThreads; -uint32_t medPriorityThreads; -uint32_t lowPriorityThreads; -int directIOFlag = O_DIRECT; -int noVB = 0; - -const uint8_t fMaxColWidth(8); -BPPMap bppMap; -mutex bppLock; -mutex djLock; // djLock synchronizes destroy and joiner msgs, see bug 2619 -volatile int32_t asyncCounter; -const int asyncMax = 20; // current number of asynchronous loads - -extern bool utf8; - -struct preFetchCond { - //uint64_t lbid; - boost::condition cond; - unsigned waiters; - - preFetchCond(const uint64_t l) { - waiters = 0; - } + extern DebugLevel gDebugLevel; + BRM::DBRM* brm; + int fCacheCount; + bool fPMProfOn; + bool fLBIDTraceOn; + + /* params from the config file */ + uint BPPCount; + uint blocksReadAhead; + uint defaultBufferSize; + uint connectionsPerUM; + uint highPriorityThreads; + uint medPriorityThreads; + uint lowPriorityThreads; + int directIOFlag = O_DIRECT; + + const uint8_t fMaxColWidth(8); + BPPMap bppMap; + mutex bppLock; + mutex djLock; // djLock synchronizes destroy and joiner msgs, see bug 2619 +#ifdef _MSC_VER + volatile LONG asyncCounter; +#else + int asyncCounter; +#endif + const int asyncMax = 20; // current number of asynchronous loads - ~preFetchCond() { } -}; + extern bool utf8; -typedef preFetchCond preFetchBlock_t; -typedef std::tr1::unordered_map pfBlockMap_t; -typedef std::tr1::unordered_map::iterator pfBlockMapIter_t; + struct preFetchCond { + //uint64_t lbid; + boost::condition cond; + unsigned waiters; -pfBlockMap_t pfBlockMap; -boost::mutex pfbMutex; // = PTHREAD_MUTEX_INITIALIZER; + preFetchCond(const uint64_t l) { + //lbid=l; + //pthread_cond_init(&cond, NULL); + waiters = 0; + } -pfBlockMap_t pfExtentMap; -boost::mutex pfMutex; // = PTHREAD_MUTEX_INITIALIZER; + ~preFetchCond() {/*pthread_cond_destroy(&cond);*/} + }; -map > dictEqualityFilters; -mutex eqFilterMutex; + typedef preFetchCond preFetchBlock_t; + typedef std::tr1::unordered_map pfBlockMap_t; + typedef std::tr1::unordered_map::iterator pfBlockMapIter_t; -uint32_t cacheNum(uint64_t lbid) -{ - return ( lbid / brm->getExtentSize() ) % fCacheCount; -} + pfBlockMap_t pfBlockMap; + boost::mutex pfbMutex; // = PTHREAD_MUTEX_INITIALIZER; -void buildOidFileName(const BRM::OID_t oid, - const uint16_t dbRoot, - const uint16_t partNum, - const uint32_t segNum, - char* file_name) -{ - WriteEngine::FileOp fileOp(false); + pfBlockMap_t pfExtentMap; + boost::mutex pfMutex; // = PTHREAD_MUTEX_INITIALIZER; + + map > dictEqualityFilters; + mutex eqFilterMutex; - if (fileOp.getFileName(oid, file_name, dbRoot, partNum, segNum) != WriteEngine::NO_ERROR) + uint cacheNum(uint64_t lbid) { - file_name[0]=0; - throw std::runtime_error("fileOp.getFileName failed"); + return ( lbid / brm->getExtentSize() ) % fCacheCount; } - //cout << "Oid2Filename o: " << oid << " n: " << file_name << endl; -} + void buildOidFileName(const BRM::OID_t oid, + const uint16_t dbRoot, + const uint16_t partNum, + const uint32_t segNum, + char* file_name) + { + WriteEngine::FileOp fileOp(false); -void waitForRetry(long count) -{ - timespec ts; - ts.tv_sec = 5L*count/10L; - ts.tv_nsec = (5L*count%10L)*100000000L; + if (fileOp.getFileName(oid, file_name, dbRoot, partNum, segNum) != WriteEngine::NO_ERROR) + { + file_name[0]=0; + throw std::runtime_error("fileOp.getFileName failed"); + } + //cout << "Oid2Filename o: " << oid << " n: " << file_name << endl; + } + + + void waitForRetry(long count) + { + timespec ts; + ts.tv_sec = 5L*count/10L; + ts.tv_nsec = (5L*count%10L)*100000000L; #ifdef _MSC_VER - Sleep(ts.tv_sec * 1000 + ts.tv_nsec / 1000 / 1000); + Sleep(ts.tv_sec * 1000 + ts.tv_nsec / 1000 / 1000); #else - nanosleep(&ts, 0); + nanosleep(&ts, 0); #endif -} - - -void prefetchBlocks(const uint64_t lbid, - const int compType, - uint32_t* rCount) -{ - uint16_t dbRoot; - uint32_t partNum; - uint16_t segNum; - uint32_t hwm; - uint32_t fbo; - uint32_t lowfbo; - uint32_t highfbo; - BRM::OID_t oid; - pfBlockMap_t::const_iterator iter; - uint64_t lowlbid = (lbid/blocksReadAhead) * blocksReadAhead; - blockCacheClient bc(*BRPp[cacheNum(lbid)]); - BRM::InlineLBIDRange range; - int err; - - pfbMutex.lock(); - - iter = pfBlockMap.find(lowlbid); - if (iter!=pfBlockMap.end()) { - iter->second->waiters++; - iter->second->cond.wait(pfbMutex); - iter->second->waiters--; - pfbMutex.unlock(); - return; } - preFetchBlock_t* pfb = 0; - pfb = new preFetchBlock_t(lowlbid); - pfBlockMap[lowlbid]=pfb; - pfbMutex.unlock(); + void prefetchBlocks(const uint64_t lbid, + const uint32_t ver, + const uint32_t txn, + const int compType, + uint32_t* rCount) + { + uint16_t dbRoot; + uint32_t partNum; + uint16_t segNum; + uint32_t hwm; + uint32_t fbo; + uint32_t lowfbo; + uint32_t highfbo; + BRM::OID_t oid; + pfBlockMap_t::const_iterator iter; + uint64_t lowlbid = (lbid/blocksReadAhead) * blocksReadAhead; + blockCacheClient bc(*BRPp[cacheNum(lbid)]); + BRM::InlineLBIDRange range; + int err; - // loadBlock will catch a versioned block so vbflag can be set to false here - err = brm->lookupLocal(lbid, 0, false, oid, dbRoot, partNum, segNum, fbo); // need the oid - if (err < 0) { - cerr << "prefetchBlocks(): BRM lookupLocal failed! Expect more errors.\n"; - goto cleanup; - } + pfbMutex.lock(); //pthread_mutex_lock(&pfbMutex); - // We ignore extState that tells us whether the extent is - // an outOfService extent to be ignored. The filtering for - // outOfService extents is done elsewhere. - int extState; - err = brm->getLocalHWM(oid, partNum, segNum, hwm, extState); - if (err < 0) { - cerr << "prefetchBlock(): BRM getLocalHWM failed! Expect more errors.\n"; - goto cleanup; - } + iter = pfBlockMap.find(lowlbid); + if (iter!=pfBlockMap.end()) { + iter->second->waiters++; + iter->second->cond.wait(pfbMutex); //pthread_cond_wait(&(iter->second->cond), &pfbMutex); + iter->second->waiters--; + pfbMutex.unlock(); //pthread_mutex_unlock(&pfbMutex); + return; + } - lowfbo = fbo - (lbid - lowlbid); - highfbo = lowfbo + blocksReadAhead - 1; - range.start = lowlbid; - if (hwm < highfbo) - range.size = hwm - lowfbo + 1; - else - range.size = blocksReadAhead; + preFetchBlock_t* pfb = 0; + pfb = new preFetchBlock_t(lowlbid); - try { - if (range.size>blocksReadAhead) { - ostringstream os; - os << "Invalid Range from HWM for lbid " << lbid - << ", range size should be <= blocksReadAhead: HWM " << hwm - << ", dbroot " << dbRoot - << ", highfbo " << highfbo << ", lowfbo " << lowfbo - << ", blocksReadAhead " << blocksReadAhead - << ", range size " << (int) range.size << endl; - throw logging::InvalidRangeHWMExcept(os.str()); + pfBlockMap[lowlbid]=pfb; + pfbMutex.unlock(); //pthread_mutex_unlock(&pfbMutex); + + // loadBlock will catch a versioned block so vbflag can be set to false here + err = brm->lookupLocal(lbid, ver, false, oid, dbRoot, partNum, segNum, fbo); // need the oid + if (err < 0) { + cerr << "prefetchBlocks(): BRM lookupLocal failed! Expect more errors.\n"; + goto cleanup; + } + err = brm->getLocalHWM(oid, partNum, segNum, hwm); + if (err < 0) { + cerr << "prefetchBlock(): BRM getLocalHWM failed! Expect more errors.\n"; + goto cleanup; } - idbassert(range.size<=blocksReadAhead); + lowfbo = fbo - (lbid - lowlbid); + highfbo = lowfbo + blocksReadAhead - 1; + range.start = lowlbid; + if (hwm < highfbo) + range.size = hwm - lowfbo + 1; + else + range.size = blocksReadAhead; - bc.check(range, QueryContext(numeric_limits::max()), 0, compType, *rCount); - } - catch (...) - { - // Perform necessary cleanup before rethrowing the exception - pfb->cond.notify_all(); + try { + if (range.size>blocksReadAhead) { + ostringstream os; + os << "Invalid Range from HWM for lbid " << lbid + << ", range size should be <= blocksReadAhead: HWM " << hwm + << ", dbroot " << dbRoot + << ", highfbo " << highfbo << ", lowfbo " << lowfbo + << ", blocksReadAhead " << blocksReadAhead + << ", range size " << (int) range.size << endl; + throw logging::InvalidRangeHWMExcept(os.str()); + } + + idbassert(range.size<=blocksReadAhead); + + bc.check(range, numeric_limits::max(), 0, compType, *rCount); + } + catch (...) + { + // Perform necessary cleanup before rethrowing the exception + pfb->cond.notify_all(); //pthread_cond_broadcast(&(pfb->cond)); - pfbMutex.lock(); + pfbMutex.lock(); //pthread_mutex_lock(&(pfbMutex)); + while (pfb->waiters > 0) + { + pfbMutex.unlock(); + //handle race condition with other threads going into wait before the broadcast above + pfb->cond.notify_one(); + usleep(1); + pfbMutex.lock(); + } + if (pfBlockMap.erase(lowlbid) > 0) + delete pfb; + pfb=0; + pfbMutex.unlock(); //pthread_mutex_unlock(&pfbMutex); + throw; + } + cleanup: + pfb->cond.notify_all(); //pthread_cond_broadcast(&(pfb->cond)); + + pfbMutex.lock(); //pthread_mutex_lock(&(pfbMutex)); while (pfb->waiters > 0) { pfbMutex.unlock(); @@ -306,392 +328,451 @@ void prefetchBlocks(const uint64_t lbid, if (pfBlockMap.erase(lowlbid) > 0) delete pfb; pfb=0; - pfbMutex.unlock(); - throw; - } -cleanup: - pfb->cond.notify_all(); - - pfbMutex.lock(); - while (pfb->waiters > 0) + pfbMutex.unlock(); //pthread_mutex_unlock(&pfbMutex); + + } // prefetchBlocks() + + // returns the # that were cached. + uint loadBlocks ( + LBID_t *lbids, + VER_t *vers, + VER_t txn, + int compType, + uint8_t **bufferPtrs, + uint32_t *rCount, + bool LBIDTrace, + uint32_t sessionID, + uint blockCount, + bool *blocksWereVersioned, + bool doPrefetch, + VSSCache *vssCache) { - pfbMutex.unlock(); - //handle race condition with other threads going into wait before the broadcast above - pfb->cond.notify_one(); - usleep(1); - pfbMutex.lock(); - } - if (pfBlockMap.erase(lowlbid) > 0) - delete pfb; - pfb=0; - pfbMutex.unlock(); - -} // prefetchBlocks() - -// returns the # that were cached. -uint32_t loadBlocks ( - LBID_t *lbids, - QueryContext qc, - VER_t txn, - int compType, - uint8_t **bufferPtrs, - uint32_t *rCount, - bool LBIDTrace, - uint32_t sessionID, - uint32_t blockCount, - bool *blocksWereVersioned, - bool doPrefetch, - VSSCache *vssCache) -{ - blockCacheClient bc(*BRPp[cacheNum(lbids[0])]); - uint32_t blksRead=0; - VSSCache::iterator it; - uint32_t i, ret; - bool *vbFlags; - int *vssRCs; - bool *cacheThisBlock; - bool *wasCached; + blockCacheClient bc(*BRPp[cacheNum(lbids[0])]); + uint32_t blksRead=0; + VSSCache::iterator it; + uint i, ret; + bool *vbFlags; + int *vssRCs; + bool *cacheThisBlock; + bool *wasCached; - *blocksWereVersioned = false; + *blocksWereVersioned = false; #ifndef _MSC_VER - if (LBIDTrace) { - for (i = 0; i < blockCount; i++) { - - stats.touchedLBID(lbids[i], pthread_self(), sessionID); - } - } -#endif - VER_t *vers = (VER_t *) alloca(blockCount * sizeof(VER_t)); - vbFlags = (bool *) alloca(blockCount); - vssRCs = (int *) alloca(blockCount * sizeof(int)); - cacheThisBlock = (bool *) alloca(blockCount); - wasCached = (bool *) alloca(blockCount); - for (i = 0; i < blockCount; i++) { - if (vssCache) { - it = vssCache->find(lbids[i]); - if (it != vssCache->end()) { - VSSData &vd = it->second; - vers[i] = vd.verID; - vbFlags[i] = vd.vbFlag; - vssRCs[i] = vd.returnCode; - if (vssRCs[i] == ERR_SNAPSHOT_TOO_OLD) - throw runtime_error("Snapshot too old"); + if (LBIDTrace) { + for (i = 0; i < blockCount; i++) { + + stats.touchedLBID(lbids[i], pthread_self(), sessionID); } } - if (!vssCache || it == vssCache->end()) - vssRCs[i] = brm->vssLookup(lbids[i], qc, txn, &vers[i], &vbFlags[i]); - *blocksWereVersioned |= vbFlags[i]; - - // If the block is being modified by this txn, set the useCache flag to false - if (txn > 0 && vers[i] == txn && !vbFlags[i]) - cacheThisBlock[i] = false; - else - cacheThisBlock[i] = true; - } +#endif - /* - cout << " resolved ver #s: "; - for (uint32_t i = 0; i < blockCount; i++) - cout << " <" << vers[i] << ", " << (int) vbFlags[i] << ", " << (int) - cacheThisBlock[i] << ">"; - cout << endl; - */ + vbFlags = (bool *) alloca(blockCount); + vssRCs = (int *) alloca(blockCount * sizeof(int)); + cacheThisBlock = (bool *) alloca(blockCount); + wasCached = (bool *) alloca(blockCount); + for (i = 0; i < blockCount; i++) { + if (vssCache) { + it = vssCache->find(lbids[i]); + if (it != vssCache->end()) { + VSSData &vd = it->second; + vers[i] = vd.verID; + vbFlags[i] = vd.vbFlag; + vssRCs[i] = vd.returnCode; + if (vssRCs[i] == ERR_SNAPSHOT_TOO_OLD) + throw runtime_error("Snapshot too old"); + } + } + if (!vssCache || it == vssCache->end()) + vssRCs[i] = brm->vssLookup(lbids[i], vers[i], txn, vbFlags[i]); + *blocksWereVersioned |= vbFlags[i]; - ret = bc.getCachedBlocks(lbids, vers, bufferPtrs, wasCached, blockCount); + // If the block is being modified by this txn, set the useCache flag to false + if (txn > 0 && vers[i] == txn && !vbFlags[i]) + cacheThisBlock[i] = false; + else + cacheThisBlock[i] = true; + } - // Do we want to check any VB flags here? Initial thought: no, because we have - // no idea whether any other blocks in the prefetch range are versioned, - // what's the difference if one in the visible range is? - if (ret != blockCount && doPrefetch) { - prefetchBlocks(lbids[0], compType, &blksRead); + ret = bc.getCachedBlocks(lbids, vers, bufferPtrs, wasCached, blockCount); + + // Do we want to check any VB flags here? Initial thought: no, because we have + // no idea whether any other blocks in the prefetch range are versioned, + // what's the difference if one in the visible range is? + if (ret != blockCount && doPrefetch) { + prefetchBlocks(lbids[0], vers[0], 0, compType, &blksRead); #ifndef _MSC_VER - if (fPMProfOn) - pmstats.markEvent(lbids[0], (pthread_t)-1, sessionID, 'M'); + if (fPMProfOn) + pmstats.markEvent(lbids[0], (pthread_t)-1, sessionID, 'M'); #endif - /* After the prefetch they're all cached if they are in the same range, so - * prune the block list and try getCachedBlocks again first, then fall back - * to single-block IO requests if for some reason they aren't. */ - uint32_t l_blockCount = 0; - for (i = 0; i < blockCount; i++) { - if (!wasCached[i]) { - lbids[l_blockCount] = lbids[i]; - vers[l_blockCount] = vers[i]; - bufferPtrs[l_blockCount] = bufferPtrs[i]; - vbFlags[l_blockCount] = vbFlags[i]; - cacheThisBlock[l_blockCount] = cacheThisBlock[i]; - ++l_blockCount; + /* After the prefetch they're all cached if they are in the same range, so + * prune the block list and try getCachedBlocks again first, then fall back + * to single-block IO requests if for some reason they aren't. */ + uint l_blockCount = 0; + for (i = 0; i < blockCount; i++) { + if (!wasCached[i]) { + lbids[l_blockCount] = lbids[i]; + vers[l_blockCount] = vers[i]; + bufferPtrs[l_blockCount] = bufferPtrs[i]; + vbFlags[l_blockCount] = vbFlags[i]; + cacheThisBlock[l_blockCount] = cacheThisBlock[i]; + ++l_blockCount; + } } + ret += bc.getCachedBlocks(lbids, vers, bufferPtrs, wasCached, l_blockCount); + + if (ret != blockCount) + for (i = 0; i < l_blockCount; i++) + if (!wasCached[i]) { + bool ver; + bc.getBlock(lbids[i], vers[i], txn, compType, (void *) bufferPtrs[i], + vbFlags[i], wasCached[i], &ver, cacheThisBlock[i], false); + *blocksWereVersioned |= ver; + blksRead++; + } } - ret += bc.getCachedBlocks(lbids, vers, bufferPtrs, wasCached, l_blockCount); - - if (ret != blockCount) { - for (i = 0; i < l_blockCount; i++) + /* Some blocks weren't cached, prefetch is disabled -> issue single-block IO requests, + * skip checking the cache again. */ + else if (ret != blockCount) { + for (i = 0; i < blockCount; i++) { if (!wasCached[i]) { bool ver; - qc.currentScn = vers[i]; - bc.getBlock(lbids[i], qc, txn, compType, (void *) bufferPtrs[i], - vbFlags[i], wasCached[i], &ver, cacheThisBlock[i], false); + bc.getBlock(lbids[i], vers[i], txn, compType, (void *) bufferPtrs[i], vbFlags[i], + wasCached[i], &ver, cacheThisBlock[i], false); *blocksWereVersioned |= ver; blksRead++; } - } - } - /* Some blocks weren't cached, prefetch is disabled -> issue single-block IO requests, - * skip checking the cache again. */ - else if (ret != blockCount) { - for (i = 0; i < blockCount; i++) { - if (!wasCached[i]) { - bool ver; - - qc.currentScn = vers[i]; - bc.getBlock(lbids[i], qc, txn, compType, (void *) bufferPtrs[i], vbFlags[i], - wasCached[i], &ver, cacheThisBlock[i], false); - *blocksWereVersioned |= ver; - blksRead++; } } - } - if (rCount) - *rCount = blksRead; - //if (*verBlocks) - // cout << "loadBlock says there were versioned blocks\n"; - return ret; -} + if (rCount) + *rCount = blksRead; + //if (*verBlocks) + // cout << "loadBlock says there were versioned blocks\n"; + return ret; + } -void loadBlock ( - uint64_t lbid, - QueryContext v, - uint32_t t, - int compType, - void* bufferPtr, - bool* pWasBlockInCache, - uint32_t* rCount, - bool LBIDTrace, - uint32_t sessionID, - bool doPrefetch, - VSSCache *vssCache) -{ - bool flg = false; - BRM::OID_t oid; - BRM::VER_t txn = (BRM::VER_t)t; - uint16_t dbRoot=0; - uint32_t partitionNum=0; - uint16_t segmentNum=0; - int rc; - BRM::VER_t ver; - blockCacheClient bc(*BRPp[cacheNum(lbid)]); - char file_name[WriteEngine::FILE_NAME_SIZE]= {0}; - char* fileNamePtr = file_name; - uint32_t blksRead=0; - VSSCache::iterator it; + void loadBlock ( + u_int64_t lbid, + u_int32_t v, + u_int32_t t, + int compType, + void* bufferPtr, + bool* pWasBlockInCache, + uint32_t* rCount, + bool LBIDTrace, + uint32_t sessionID, + bool doPrefetch, + VSSCache *vssCache) + { + bool flg = false; + BRM::OID_t oid; + BRM::VER_t txn = (BRM::VER_t)t; + uint16_t dbRoot=0; + uint32_t partitionNum=0; + uint16_t segmentNum=0; + int rc; + BRM::VER_t ver = (BRM::VER_t)v; + blockCacheClient bc(*BRPp[cacheNum(lbid)]); + char file_name[WriteEngine::FILE_NAME_SIZE]={0}; + char* fileNamePtr = file_name; + uint32_t blksRead=0; + VSSCache::iterator it; #ifndef _MSC_VER - if (LBIDTrace) - stats.touchedLBID(lbid, pthread_self(), sessionID); + if (LBIDTrace) + stats.touchedLBID(lbid, pthread_self(), sessionID); #endif - if (vssCache) { - it = vssCache->find(lbid); - if (it != vssCache->end()) { - VSSData &vd = it->second; - ver = vd.verID; - flg = vd.vbFlag; - rc = vd.returnCode; + if (vssCache) { + it = vssCache->find(lbid); + if (it != vssCache->end()) { + VSSData &vd = it->second; + ver = vd.verID; + flg = vd.vbFlag; + rc = vd.returnCode; + } } - } - if (!vssCache || it == vssCache->end()) - rc = brm->vssLookup((BRM::LBID_t)lbid, v, txn, &ver, &flg); - - v.currentScn = ver; - //cout << "VSS l/u: l=" << lbid << " v=" << ver << " t=" << txn << " flg=" << flg << " rc: " << rc << endl; - - // if this block is locked by this session, don't cache it, just read it directly from disk - if (txn > 0 && ver == txn && !flg && !noVB) { - uint64_t offset; - uint32_t fbo; - boost::scoped_array newBufferSa; - boost::scoped_array cmpHdrBufSa; - boost::scoped_array cmpBufSa; - boost::scoped_array uCmpBufSa; - - - - ptrdiff_t alignedBuffer = 0; - void* readBufferPtr = NULL; - char* cmpHdrBuf = NULL; - char* cmpBuf = NULL; - unsigned char* uCmpBuf = NULL; - uint64_t cmpBufLen = 0; - int blockReadRetryCount = 0; - unsigned idx = 0; - int pageSize = getpagesize(); - IDBDataFile* fp = 0; - try { - rc = brm->lookupLocal((BRM::LBID_t)lbid, - ver, - flg, - oid, - dbRoot, - partitionNum, - segmentNum, - fbo); - - - // load the block - buildOidFileName(oid, dbRoot, partitionNum, segmentNum, fileNamePtr); - int opts = directIOFlag ? IDBDataFile::USE_ODIRECT : 0; - fp = IDBDataFile::open( - IDBPolicy::getType( fileNamePtr, IDBPolicy::PRIMPROC ), - fileNamePtr, - "r", - opts); - if( fp == NULL ) { - int errCode = errno; - SUMMARY_INFO2("open failed: ", fileNamePtr); - char errbuf[80]; - string errMsg; + if (!vssCache || it == vssCache->end()) + rc = brm->vssLookup((BRM::LBID_t)lbid, ver, txn, flg); + //cout << "VSS l/u: l=" << lbid << " v=" << ver << " t=" << txn << " flg=" << flg << " rc: " << rc << endl; + + // if this block is locked by this session, don't cache it, just read it directly from disk + if (txn > 0 && ver == txn && !flg) { + uint64_t offset; + uint32_t fbo; + boost::scoped_array newBufferSa; + boost::scoped_array cmpHdrBufSa; + boost::scoped_array cmpBufSa; + boost::scoped_array uCmpBufSa; + ptrdiff_t alignedBuffer = 0; + void* readBufferPtr = NULL; + char* cmpHdrBuf = NULL; + char* cmpBuf = NULL; + unsigned char* uCmpBuf = NULL; + uint64_t cmpBufLen = 0; + int blockReadRetryCount = 0; + unsigned idx = 0; + int pageSize = getpagesize(); +#ifdef _MSC_VER + HANDLE fdh; +#else + int fd = -1; +#endif + try { + rc = brm->lookupLocal((BRM::LBID_t)lbid, + ver, + flg, + oid, + dbRoot, + partitionNum, + segmentNum, + fbo); + + + // load the block + buildOidFileName(oid, dbRoot, partitionNum, segmentNum, fileNamePtr); +#ifdef _MSC_VER + fdh = CreateFile(fileNamePtr, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, 0, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_NO_BUFFERING, 0); +#else + fd = open(fileNamePtr, O_RDONLY|O_LARGEFILE|O_NOATIME|directIOFlag); +#endif +#ifdef _MSC_VER + if (fdh == INVALID_HANDLE_VALUE) { +#else + if ( fd < 0 ) { +#endif + int errCode = errno; + SUMMARY_INFO2("open failed: ", fileNamePtr); + char errbuf[80]; + string errMsg; #ifdef __linux__ //#if STRERROR_R_CHAR_P - const char* p; - if ((p = strerror_r(errCode, errbuf, 80)) != 0) - errMsg = p; + const char* p; + if ((p = strerror_r(errCode, errbuf, 80)) != 0) + errMsg = p; #else - int p; - if ((p = strerror_r(errCode, errbuf, 80)) == 0) - errMsg = errbuf; + int p; + if ((p = strerror_r(errCode, errbuf, 80)) == 0) + errMsg = errbuf; #endif #ifndef _MSC_VER - if (errCode == EINVAL) { - throw logging::IDBExcept(logging::IDBErrorInfo::instance()-> - errorMsg(logging::ERR_O_DIRECT), logging::ERR_O_DIRECT); - } + if (errCode == EINVAL) { + throw logging::IDBExcept(logging::IDBErrorInfo::instance()-> + errorMsg(logging::ERR_O_DIRECT), logging::ERR_O_DIRECT); + } #endif - string errStr(fileNamePtr); - errStr += ": open: "; - errStr += errMsg; - throw std::runtime_error(errStr); - } + string errStr(fileNamePtr); + errStr += ": open: "; + errStr += errMsg; + throw std::runtime_error(errStr); + } - // fd >= 0 must be true, otherwise above exception thrown. - offset = (uint64_t)fbo * (uint64_t)DATA_BLOCK_SIZE; - idx = offset / (4 * 1024 * 1024); + // fd >= 0 must be true, otherwise above exception thrown. + offset = (uint64_t)fbo * (uint64_t)DATA_BLOCK_SIZE; + idx = offset / (4 * 1024 * 1024); - errno = 0; - rc = 0; - int i = -1; + errno = 0; + rc = 0; + int i = -1; +#ifdef _MSC_VER + //needs to be atomic + //__int64 mrc; + DWORD bytesRead; + OVERLAPPED ovl; +#endif - if (compType == 0) - { - newBufferSa.reset(new uint8_t[DATA_BLOCK_SIZE + pageSize]); - alignedBuffer = (ptrdiff_t) newBufferSa.get(); - if ((alignedBuffer % pageSize) != 0) { - alignedBuffer &= ~((ptrdiff_t)pageSize - 1); - alignedBuffer += pageSize; - } - readBufferPtr = (void*) alignedBuffer; - i = fp->pread( readBufferPtr, offset, DATA_BLOCK_SIZE ); - memcpy(bufferPtr, readBufferPtr, i); + if (compType == 0) { +#ifdef _MSC_VER +#if 0 + //FIXME: why does ReadFile here always return EINVAL? + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = static_cast(offset); + ovl.OffsetHigh = static_cast(offset>>32); + if (ReadFile(fdh, bufferPtr, 8192, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; +#else + int xfd=open(fileNamePtr,O_RDONLY|O_BINARY); + idbassert(xfd>=0); + _lseeki64(xfd,offset,SEEK_SET); + i = _read(xfd,bufferPtr,8192); + close(xfd); +#endif // if 0 +#else // _MSC_VER + // linux only for O_DIRECT, using O_DIRECT to be consistent with iomanager. + newBufferSa.reset(new uint8_t[DATA_BLOCK_SIZE + pageSize]); + alignedBuffer = (ptrdiff_t) newBufferSa.get(); + if ((alignedBuffer % pageSize) != 0) { + alignedBuffer &= ~((ptrdiff_t)pageSize - 1); + alignedBuffer += pageSize; + } + readBufferPtr = (void*) alignedBuffer; + i = pread(fd, readBufferPtr, DATA_BLOCK_SIZE, offset); + memcpy(bufferPtr, readBufferPtr, i); #ifdef IDB_COMP_POC_DEBUG - { - boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); - cout << "pread2(" << fd << ", 0x" << hex << (ptrdiff_t)readBufferPtr << dec << ", " << DATA_BLOCK_SIZE << ", " << offset << ") = " << i << endl; - } +{ +boost::mutex::scoped_lock lk(primitiveprocessor::compDebugMutex); +cout << "pread2(" << fd << ", 0x" << hex << (ptrdiff_t)readBufferPtr << dec << ", " << DATA_BLOCK_SIZE << ", " << offset << ") = " << i << endl; +} #endif // IDB_COMP_POC_DEBUG - } // if (compType == 0) - else { // if (compType != 0) -// retry if file is out of sync -- compressed column file only. -blockReadRetry: +#endif // _MSC_VER + } // if (compType == 0) - uCmpBufSa.reset(new unsigned char[4 * 1024 * 1024 + 4]); - uCmpBuf = uCmpBufSa.get(); - cmpHdrBufSa.reset(new char[4096 * 3 + pageSize]); - alignedBuffer = (ptrdiff_t) cmpHdrBufSa.get(); - if ((alignedBuffer % pageSize) != 0) { - alignedBuffer &= ~((ptrdiff_t)pageSize - 1); - alignedBuffer += pageSize; - } - cmpHdrBuf = (char*) alignedBuffer; - - i = fp->pread( &cmpHdrBuf[0], 0, 4096 * 3); + else { // if (compType != 0) - CompChunkPtrList ptrList; - IDBCompressInterface decompressor; - int dcrc = 0; - if (i == 4096 * 3) { - uint64_t numHdrs = 0; // extra headers - dcrc = decompressor.getPtrList(&cmpHdrBuf[4096], 4096, ptrList); +#ifdef _MSC_VER +// retry if file is out of sync -- compressed column file only. +blockReadRetry: + uCmpBufSa.reset(new unsigned char[4 * 1024 * 1024 + 4]); + uCmpBuf = uCmpBufSa.get(); + cmpHdrBufSa.reset(new char[4096 * 3]); + cmpHdrBuf = cmpHdrBufSa.get(); + CompChunkPtrList ptrList; + ZeroMemory(&ovl, sizeof(ovl)); + if (ReadFile(fdh, &cmpHdrBuf[0], 4096*3, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; + IDBCompressInterface decompressor; + + uint64_t numHdrs = 0; + int dcrc = decompressor.getPtrList(&cmpHdrBuf[4096], 4096, ptrList); if (dcrc == 0 && ptrList.size() > 0) numHdrs = ptrList[0].first / 4096ULL - 2ULL; if (numHdrs > 0) { - boost::scoped_array nextHdrBufsa(new char[numHdrs * 4096 + pageSize]); - alignedBuffer = (ptrdiff_t) nextHdrBufsa.get(); - if ((alignedBuffer % pageSize) != 0) { - alignedBuffer &= ~((ptrdiff_t)pageSize - 1); - alignedBuffer += pageSize; - } - char* nextHdrBufPtr = (char*) alignedBuffer; - - i = fp->pread( &nextHdrBufPtr[0], 4096 * 2, numHdrs * 4096 ); - + boost::scoped_array nextHdrBufsa(new char[numHdrs * 4096]); + char* nextHdrBufPtr = nextHdrBufsa.get(); + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = static_cast(4096*2); + if (ReadFile(fdh, &nextHdrBufPtr[0], numHdrs*4096, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; CompChunkPtrList nextPtrList; dcrc = decompressor.getPtrList(&nextHdrBufPtr[0], numHdrs * 4096, nextPtrList); if (dcrc == 0) ptrList.insert(ptrList.end(), nextPtrList.begin(), nextPtrList.end()); } - } - if (dcrc != 0 || idx >= ptrList.size()) { - // Due to race condition, the header on disk may not upated yet. - // Log an info message and retry. - if (blockReadRetryCount == 0) { - logging::Message::Args args; - args.add(oid); - ostringstream infoMsg; - infoMsg << "retry read from " << fileNamePtr << ". dcrc=" << dcrc - << ", idx=" << idx << ", ptr.size=" << ptrList.size(); - args.add(infoMsg.str()); - mlp->logInfoMessage(logging::M0061, args); - } + if (i < 0 || dcrc != 0 || idx >= (signed)ptrList.size()) { + // Due to race condition, the header on disk may not upated yet. + // Log an info message and retry. + if (blockReadRetryCount == 0) { + logging::Message::Args args; + args.add(oid); + ostringstream infoMsg; + infoMsg << "retry read from " << fileNamePtr << ". dcrc=" << dcrc + << ", idx=" << idx << ", ptr.size=" << ptrList.size(); + args.add(infoMsg.str()); + mlp->logInfoMessage(logging::M0061, args); + } - if (++blockReadRetryCount < 30) { - waitForRetry(blockReadRetryCount); - goto blockReadRetry; + if (++blockReadRetryCount < 30) { + waitForRetry(blockReadRetryCount); + goto blockReadRetry; + } + else { + rc = -1001; + } } - else { - rc = -1004; + + if (rc == 0) { + unsigned cmpBlkOff = offset % (4 * 1024 * 1024); + uint64_t cmpBufOff = ptrList[idx].first; + uint64_t cmpBufSz = ptrList[idx].second; + if (cmpBufSa.get() == NULL || cmpBufLen < cmpBufSz) { + cmpBufSa.reset(new char[cmpBufSz]); + cmpBufLen = cmpBufSz; + cmpBuf = cmpBufSa.get(); + } + unsigned blen = 4 * 1024 * 1024; + ZeroMemory(&ovl, sizeof(ovl)); + ovl.Offset = static_cast(cmpBufOff); + ovl.OffsetHigh = static_cast(cmpBufOff>>32); + if (ReadFile(fdh, cmpBuf, cmpBufSz, &bytesRead, &ovl)) + i = bytesRead; + else + i = -1; + + dcrc = decompressor.uncompressBlock(cmpBuf, cmpBufSz, uCmpBuf, blen); + if (dcrc == 0) { + memcpy(bufferPtr, &uCmpBuf[cmpBlkOff], DATA_BLOCK_SIZE); + } + else { + // Due to race condition, the header on disk may not upated yet. + // Log an info message and retry. + if (blockReadRetryCount == 0) { + logging::Message::Args args; + args.add(oid); + ostringstream infoMsg; + infoMsg << "retry read from " << fileNamePtr << ". dcrc=" << dcrc + << ", idx=" << idx << ", ptr.size=" << ptrList.size(); + args.add(infoMsg.str()); + mlp->logInfoMessage(logging::M0061, args); + } + + if (++blockReadRetryCount < 30) { + waitForRetry(blockReadRetryCount); + goto blockReadRetry; + } + else { + rc = -1002; + } + } } } +#else +// retry if file is out of sync -- compressed column file only. +blockReadRetry: - if (rc == 0) { - unsigned cmpBlkOff = offset % (4 * 1024 * 1024); - uint64_t cmpBufOff = ptrList[idx].first; - uint64_t cmpBufSz = ptrList[idx].second; - if (cmpBufSa.get() == NULL || cmpBufLen < cmpBufSz) { - cmpBufSa.reset(new char[cmpBufSz + pageSize]); - cmpBufLen = cmpBufSz; - alignedBuffer = (ptrdiff_t) cmpBufSa.get(); - if ((alignedBuffer % pageSize) != 0) { - alignedBuffer &= ~((ptrdiff_t)pageSize - 1); - alignedBuffer += pageSize; - } - cmpBuf = (char*) alignedBuffer; + uCmpBufSa.reset(new unsigned char[4 * 1024 * 1024 + 4]); + uCmpBuf = uCmpBufSa.get(); + cmpHdrBufSa.reset(new char[4096 * 3 + pageSize]); + alignedBuffer = (ptrdiff_t) cmpHdrBufSa.get(); + if ((alignedBuffer % pageSize) != 0) { + alignedBuffer &= ~((ptrdiff_t)pageSize - 1); + alignedBuffer += pageSize; } - unsigned blen = 4 * 1024 * 1024; + cmpHdrBuf = (char*) alignedBuffer; + + i = pread(fd, &cmpHdrBuf[0], 4096 * 3, 0); + + CompChunkPtrList ptrList; + IDBCompressInterface decompressor; + int dcrc = 0; + if (i == 4096 * 3) { + uint64_t numHdrs = 0; // extra headers + dcrc = decompressor.getPtrList(&cmpHdrBuf[4096], 4096, ptrList); + if (dcrc == 0 && ptrList.size() > 0) + numHdrs = ptrList[0].first / 4096ULL - 2ULL; + + if (numHdrs > 0) { + boost::scoped_array nextHdrBufsa(new char[numHdrs * 4096 + pageSize]); + alignedBuffer = (ptrdiff_t) nextHdrBufsa.get(); + if ((alignedBuffer % pageSize) != 0) { + alignedBuffer &= ~((ptrdiff_t)pageSize - 1); + alignedBuffer += pageSize; + } + char* nextHdrBufPtr = (char*) alignedBuffer; - i = fp->pread( cmpBuf, cmpBufOff, cmpBufSz ); + i = pread(fd, &nextHdrBufPtr[0], numHdrs * 4096, 4096 * 2); - dcrc = decompressor.uncompressBlock(cmpBuf, cmpBufSz, uCmpBuf, blen); - if (dcrc == 0) { - memcpy(bufferPtr, &uCmpBuf[cmpBlkOff], DATA_BLOCK_SIZE); + CompChunkPtrList nextPtrList; + dcrc = decompressor.getPtrList(&nextHdrBufPtr[0], numHdrs * 4096, nextPtrList); + if (dcrc == 0) + ptrList.insert(ptrList.end(), nextPtrList.begin(), nextPtrList.end()); + } } - else { + + if (dcrc != 0 || idx >= ptrList.size()) { // Due to race condition, the header on disk may not upated yet. // Log an info message and retry. if (blockReadRetryCount == 0) { @@ -699,7 +780,7 @@ void loadBlock ( args.add(oid); ostringstream infoMsg; infoMsg << "retry read from " << fileNamePtr << ". dcrc=" << dcrc - << ", idx=" << idx << ", ptr.size=" << ptrList.size(); + << ", idx=" << idx << ", ptr.size=" << ptrList.size(); args.add(infoMsg.str()); mlp->logInfoMessage(logging::M0061, args); } @@ -709,219 +790,298 @@ void loadBlock ( goto blockReadRetry; } else { - rc = -1006; + rc = -1004; } } + + if (rc == 0) { + unsigned cmpBlkOff = offset % (4 * 1024 * 1024); + uint64_t cmpBufOff = ptrList[idx].first; + uint64_t cmpBufSz = ptrList[idx].second; + if (cmpBufSa.get() == NULL || cmpBufLen < cmpBufSz) { + cmpBufSa.reset(new char[cmpBufSz + pageSize]); + cmpBufLen = cmpBufSz; + alignedBuffer = (ptrdiff_t) cmpBufSa.get(); + if ((alignedBuffer % pageSize) != 0) { + alignedBuffer &= ~((ptrdiff_t)pageSize - 1); + alignedBuffer += pageSize; + } + cmpBuf = (char*) alignedBuffer; + } + unsigned blen = 4 * 1024 * 1024; + + i = pread(fd, cmpBuf, cmpBufSz, cmpBufOff); + + dcrc = decompressor.uncompressBlock(cmpBuf, cmpBufSz, uCmpBuf, blen); + if (dcrc == 0) { + memcpy(bufferPtr, &uCmpBuf[cmpBlkOff], DATA_BLOCK_SIZE); + } + else { + // Due to race condition, the header on disk may not upated yet. + // Log an info message and retry. + if (blockReadRetryCount == 0) { + logging::Message::Args args; + args.add(oid); + ostringstream infoMsg; + infoMsg << "retry read from " << fileNamePtr << ". dcrc=" << dcrc + << ", idx=" << idx << ", ptr.size=" << ptrList.size(); + args.add(infoMsg.str()); + mlp->logInfoMessage(logging::M0061, args); + } + + if (++blockReadRetryCount < 30) { + waitForRetry(blockReadRetryCount); + goto blockReadRetry; + } + else { + rc = -1006; + } + } + } + } +#endif + + if ( rc < 0 ) { + string msg("pread failed"); + ostringstream infoMsg; + infoMsg << +#ifndef _MSC_VER + " (fd:" << fd << +#endif + " rc:" << rc << ")"; + msg = msg + ", error:" + strerror(errno) + infoMsg.str(); + SUMMARY_INFO(msg); + //FIXME: free-up allocated memory! + throw std::runtime_error(msg); } } + catch (...) { +#ifdef _MSC_VER + CloseHandle(fdh); +#else + close(fd); +#endif + throw; + } - if ( rc < 0 ) { - string msg("pread failed"); +#ifdef _MSC_VER + CloseHandle(fdh); +#else + close(fd); +#endif + // log the retries + if (blockReadRetryCount > 0) { + logging::Message::Args args; + args.add(oid); ostringstream infoMsg; - infoMsg << " rc:" << rc << ")"; - msg = msg + ", error:" + strerror(errno) + infoMsg.str(); - SUMMARY_INFO(msg); - //FIXME: free-up allocated memory! - throw std::runtime_error(msg); + infoMsg << "Successfully uncompress " << fileNamePtr << " chunk " + << idx << " @" << " blockReadRetry:" << blockReadRetryCount; + args.add(infoMsg.str()); + mlp->logInfoMessage(logging::M0006, args); } + + if (pWasBlockInCache) + *pWasBlockInCache = false; + if (rCount) + *rCount = 1; + return; } - catch (...) { - delete fp; - fp = 0; - throw; + + FileBuffer* fbPtr=0; + bool wasBlockInCache=false; + + fbPtr = bc.getBlockPtr(lbid, ver, flg); + if (fbPtr) { + memcpy(bufferPtr, fbPtr->getData(), BLOCK_SIZE); + wasBlockInCache = true; } - delete fp; - fp = 0; - // log the retries - if (blockReadRetryCount > 0) { - logging::Message::Args args; - args.add(oid); - ostringstream infoMsg; - infoMsg << "Successfully uncompress " << fileNamePtr << " chunk " - << idx << " @" << " blockReadRetry:" << blockReadRetryCount; - args.add(infoMsg.str()); - mlp->logInfoMessage(logging::M0006, args); + if (doPrefetch && !wasBlockInCache && !flg) { + prefetchBlocks(lbid, ver, txn, compType, &blksRead); + +#ifndef _MSC_VER + if (fPMProfOn) + pmstats.markEvent(lbid, (pthread_t)-1, sessionID, 'M'); +#endif + bc.getBlock(lbid, ver, txn, compType, (uint8_t *) bufferPtr, flg, wasBlockInCache); + if (!wasBlockInCache) + blksRead++; + } + else if (!wasBlockInCache) { + bc.getBlock(lbid, ver, txn, compType, (uint8_t *) bufferPtr, flg, wasBlockInCache); + if (!wasBlockInCache) + blksRead++; } if (pWasBlockInCache) - *pWasBlockInCache = false; + *pWasBlockInCache = wasBlockInCache; if (rCount) - *rCount = 1; + *rCount = blksRead; - return; } - FileBuffer* fbPtr=0; - bool wasBlockInCache=false; - - fbPtr = bc.getBlockPtr(lbid, ver, flg); - if (fbPtr) { - memcpy(bufferPtr, fbPtr->getData(), BLOCK_SIZE); - wasBlockInCache = true; - } - - if (doPrefetch && !wasBlockInCache && !flg) { - prefetchBlocks(lbid, compType, &blksRead); + struct AsynchLoader { + AsynchLoader(uint64_t l, + uint32_t v, + uint32_t t, + int ct, + uint32_t *cCount, + uint32_t *rCount, + bool trace, + uint32_t sesID, + boost::mutex *m, + uint *loaderCount, + VSSCache *vCache) : + lbid(l), + ver(v), + txn(t), + compType(ct), + LBIDTrace(trace), + sessionID(sesID), + cacheCount(cCount), + readCount(rCount), + busyLoaders(loaderCount), + mutex(m), + vssCache(vCache) + { } + + void operator()() + { + bool cached=false; + uint32_t rCount=0; + char buf[BLOCK_SIZE]; -#ifndef _MSC_VER - if (fPMProfOn) - pmstats.markEvent(lbid, (pthread_t)-1, sessionID, 'M'); + //cout << "asynch started " << pthread_self() << " l: " << lbid << endl; + try { + loadBlock(lbid, ver, txn, compType, buf, &cached, &rCount, LBIDTrace, sessionID, true, vssCache); + } + catch (std::exception& ex) { + cerr << "AsynchLoader caught loadBlock exception: " << ex.what() << endl; + idbassert(asyncCounter > 0); +#ifdef _MSC_VER + InterlockedDecrement(&asyncCounter); +#else + __sync_add_and_fetch(&asyncCounter, -1); #endif - bc.getBlock(lbid, v, txn, compType, (uint8_t *) bufferPtr, flg, wasBlockInCache); - if (!wasBlockInCache) - blksRead++; - } - else if (!wasBlockInCache) { - bc.getBlock(lbid, v, txn, compType, (uint8_t *) bufferPtr, flg, wasBlockInCache); - if (!wasBlockInCache) - blksRead++; - } - - if (pWasBlockInCache) - *pWasBlockInCache = wasBlockInCache; - if (rCount) - *rCount = blksRead; - -} - -struct AsynchLoader { - AsynchLoader(uint64_t l, - const QueryContext &v, - uint32_t t, - int ct, - uint32_t *cCount, - uint32_t *rCount, - bool trace, - uint32_t sesID, - boost::mutex *m, - uint32_t *loaderCount, - VSSCache *vCache) : - lbid(l), - ver(v), - txn(t), - compType(ct), - LBIDTrace(trace), - sessionID(sesID), - cacheCount(cCount), - readCount(rCount), - busyLoaders(loaderCount), - mutex(m), - vssCache(vCache) - { } - - void operator()() - { - bool cached=false; - uint32_t rCount=0; - char buf[BLOCK_SIZE]; - - //cout << "asynch started " << pthread_self() << " l: " << lbid << endl; - try { - loadBlock(lbid, ver, txn, compType, buf, &cached, &rCount, LBIDTrace, sessionID, true, vssCache); - } - catch (std::exception& ex) { - cerr << "AsynchLoader caught loadBlock exception: " << ex.what() << endl; - idbassert(asyncCounter > 0); - (void)atomicops::atomicDec(&asyncCounter); - mutex->lock(); - --(*busyLoaders); - mutex->unlock(); - logging::Message::Args args; - args.add(string("PrimProc AsyncLoader caught error: ")); - args.add(ex.what()); - primitiveprocessor::mlp->logMessage(logging::M0000, args, false); - return; - } - catch (...) { - cerr << "AsynchLoader caught unknown exception: " << endl; - //FIXME Use a locked processor primitive? + mutex->lock(); //pthread_mutex_lock(mutex); + --(*busyLoaders); + mutex->unlock(); //pthread_mutex_unlock(mutex); + logging::Message::Args args; + args.add(string("PrimProc AsyncLoader caught error: ")); + args.add(ex.what()); + primitiveprocessor::mlp->logMessage(logging::M0000, args, false); + return; + } + catch (...) { + cerr << "AsynchLoader caught unknown exception: " << endl; + //FIXME Use a locked processor primitive? + idbassert(asyncCounter > 0); +#ifdef _MSC_VER + InterlockedDecrement(&asyncCounter); +#else + __sync_add_and_fetch(&asyncCounter, -1); +#endif + mutex->lock(); //pthread_mutex_lock(mutex); + --(*busyLoaders); + mutex->unlock(); //pthread_mutex_unlock(mutex); + logging::Message::Args args; + args.add(string("PrimProc AsyncLoader caught unknown error")); + primitiveprocessor::mlp->logMessage(logging::M0000, args, false); + return; + } idbassert(asyncCounter > 0); - (void)atomicops::atomicDec(&asyncCounter); - mutex->lock(); +#ifdef _MSC_VER + InterlockedDecrement(&asyncCounter); +#else + __sync_add_and_fetch(&asyncCounter, -1); +#endif + mutex->lock(); //pthread_mutex_lock(mutex); + if (cached) + (*cacheCount)++; + *readCount += rCount; --(*busyLoaders); - mutex->unlock(); - logging::Message::Args args; - args.add(string("PrimProc AsyncLoader caught unknown error")); - primitiveprocessor::mlp->logMessage(logging::M0000, args, false); - return; - } - idbassert(asyncCounter > 0); - (void)atomicops::atomicDec(&asyncCounter); - mutex->lock(); - if (cached) - (*cacheCount)++; - *readCount += rCount; - --(*busyLoaders); - mutex->unlock(); + mutex->unlock(); //pthread_mutex_unlock(mutex); // cerr << "done\n"; - } + } -private: - uint64_t lbid; - QueryContext ver; - uint32_t txn; - int compType; - uint8_t dataWidth; - bool LBIDTrace; - uint32_t sessionID; - uint32_t *cacheCount; - uint32_t *readCount; - uint32_t *busyLoaders; - boost::mutex *mutex; - VSSCache *vssCache; -}; + private: + uint64_t lbid; + uint32_t ver; + uint32_t txn; + int compType; + uint8_t dataWidth; + bool LBIDTrace; + uint32_t sessionID; + uint32_t *cacheCount; + uint32_t *readCount; + uint *busyLoaders; + boost::mutex *mutex; + VSSCache *vssCache; + }; -void loadBlockAsync(uint64_t lbid, - const QueryContext &c, - uint32_t txn, - int compType, - uint32_t *cCount, - uint32_t *rCount, - bool LBIDTrace, - uint32_t sessionID, - boost::mutex *m, - uint32_t *busyLoaders, - VSSCache *vssCache) -{ - blockCacheClient bc(*BRPp[cacheNum(lbid)]); - bool vbFlag; - BRM::VER_t ver; - VSSCache::iterator it; - - if (vssCache) { - it = vssCache->find(lbid); - if (it != vssCache->end()) { - //cout << "async: vss cache hit on " << lbid << endl; - VSSData &vd = it->second; - ver = vd.verID; - vbFlag = vd.vbFlag; + void loadBlockAsync(uint64_t lbid, + uint32_t v, + uint32_t txn, + int compType, + uint32_t *cCount, + uint32_t *rCount, + bool LBIDTrace, + uint32_t sessionID, + boost::mutex *m, + uint *busyLoaders, + VSSCache *vssCache) + { + blockCacheClient bc(*BRPp[cacheNum(lbid)]); + bool vbFlag; + int vssret; + BRM::VER_t ver = (BRM::VER_t) v; + VSSCache::iterator it; + + if (vssCache) { + it = vssCache->find(lbid); + if (it != vssCache->end()) { + //cout << "async: vss cache hit on " << lbid << endl; + VSSData &vd = it->second; + vssret = vd.returnCode; + ver = vd.verID; + vbFlag = vd.vbFlag; + } } - } - if (!vssCache || it == vssCache->end()) - brm->vssLookup((BRM::LBID_t) lbid, c, txn, &ver, &vbFlag); + if (!vssCache || it == vssCache->end()) + vssret = brm->vssLookup((BRM::LBID_t) lbid, ver, txn, vbFlag); + + if (bc.exists(lbid, ver)) + return; - if (bc.exists(lbid, ver)) - return; + /* a quick and easy stand-in for a threadpool for loaders */ +#ifdef _MSC_VER + if (_InterlockedOr(&asyncCounter, 0) >= asyncMax) + return; - /* a quick and easy stand-in for a threadpool for loaders */ - atomicops::atomicMb(); - if (asyncCounter >= asyncMax) - return; - (void)atomicops::atomicInc(&asyncCounter); + InterlockedIncrement(&asyncCounter); +#else + if (__sync_or_and_fetch(&asyncCounter, 0) >= asyncMax) + return; - mutex::scoped_lock sl(*m); - try { - boost::thread thd(AsynchLoader(lbid, c, txn, compType, cCount, rCount, - LBIDTrace, sessionID, m, busyLoaders, vssCache)); - (*busyLoaders)++; - } - catch (boost::thread_resource_error &e) { - cerr << "AsynchLoader: caught a thread resource error, need to lower asyncMax\n"; - idbassert(asyncCounter > 0); - (void)atomicops::atomicDec(&asyncCounter); + __sync_add_and_fetch(&asyncCounter, 1); +#endif + m->lock(); //pthread_mutex_lock(m); + try { + boost::thread thd(AsynchLoader(lbid, ver, txn, compType, cCount, rCount, + LBIDTrace, sessionID, m, busyLoaders, vssCache)); + (*busyLoaders)++; + } + catch (boost::thread_resource_error &e) { + cerr << "AsynchLoader: caught a thread resource error, need to lower asyncMax\n"; + idbassert(asyncCounter > 0); +#ifdef _MSC_VER + InterlockedDecrement(&asyncCounter); +#else + __sync_add_and_fetch(&asyncCounter, -1); +#endif + } + m->unlock(); //pthread_mutex_unlock(m); } -} } //namespace primitiveprocessor @@ -992,12 +1152,12 @@ class DictScanJob : public threadpool::PriorityThreadPool::Functor public: DictScanJob(SP_UM_IOSOCK ios, SBS bs, SP_UM_MUTEX writeLock); virtual ~DictScanJob(); - + void write(const ByteStream &); int operator()(); void catchHandler(const std::string& ex, uint32_t id, uint16_t code = logging::primitiveServerErr); void sendErrorMsg(uint32_t id, uint16_t code); - + private: SP_UM_IOSOCK fIos; SBS fByteStream; @@ -1006,7 +1166,7 @@ class DictScanJob : public threadpool::PriorityThreadPool::Functor }; DictScanJob::DictScanJob(SP_UM_IOSOCK ios, SBS bs, SP_UM_MUTEX writeLock) : - fIos(ios), fByteStream(bs), fWriteLock(writeLock) + fIos(ios), fByteStream(bs), fWriteLock(writeLock) { dieTime = posix_time::second_clock::universal_time() + posix_time::seconds(100); } @@ -1024,66 +1184,63 @@ void DictScanJob::write(const ByteStream& bs) int DictScanJob::operator()() { uint8_t data[DATA_BLOCK_SIZE]; - uint32_t output_buf_size = MAX_BUFFER_SIZE; + uint output_buf_size = MAX_BUFFER_SIZE; uint32_t session; - uint32_t uniqueId = 0; - bool wasBlockInCache=false; + uint32_t uniqueId; + bool wasBlockInCache; uint32_t blocksRead = 0; uint16_t runCount; - - boost::shared_ptr eqFilter; + shared_ptr eqFilter; ByteStream results(output_buf_size); - TokenByScanRequestHeader *cmd; + TokenByScanRequestHeader *cmd = (TokenByScanRequestHeader *) fByteStream->buf(); PrimitiveProcessor pproc(gDebugLevel); TokenByScanResultHeader *output; - QueryContext verInfo; try { #ifdef DCT_DEBUG DebugLevel oldDebugLevel = gDebugLevel; gDebugLevel = VERBOSE; #endif - fByteStream->advance(sizeof(TokenByScanRequestHeader)); - *fByteStream >> verInfo; - cmd = (TokenByScanRequestHeader *) fByteStream->buf(); - session = cmd->Hdr.SessionID; uniqueId = cmd->Hdr.UniqueID; runCount = cmd->Count; output = (TokenByScanResultHeader *) results.getInputPtr(); -#ifdef VALGRIND - memset(output, 0, sizeof(TokenByScanResultHeader)); -#endif /* Grab the equality filter if one is specified */ if (cmd->flags & HAS_EQ_FILTER) { - mutex::scoped_lock sl(eqFilterMutex); - map >::iterator it; - it = dictEqualityFilters.find(uniqueId); - if (it != dictEqualityFilters.end()) - eqFilter = it->second; - sl.unlock(); - if (!eqFilter) { - if (posix_time::second_clock::universal_time() < dieTime) { - fByteStream->rewind(); - return -1; // it's still being built, wait for it + while (!eqFilter) { + map >::iterator it; + mutex::scoped_lock sl(eqFilterMutex); + it = dictEqualityFilters.find(uniqueId); + if (it != dictEqualityFilters.end()) + eqFilter = it->second; + else { + sl.unlock(); + if (posix_time::second_clock::universal_time() > dieTime) + return 0; // timeout, might have been aborted + else { + if (session & 0x80000000) { // can't return on a syscat job in 3.6 + usleep(10000); + continue; + } + fByteStream->rewind(); + return -1; // still being built, reschedule + } } - else - return 0; // was probably aborted, go away... } } for (uint16_t i = 0; i < runCount; ++i) { loadBlock(cmd->LBID, - verInfo, - cmd->Hdr.TransactionID, - cmd->CompType, - data, - &wasBlockInCache, - &blocksRead, - fLBIDTraceOn, - session); + cmd->Hdr.VerID, + cmd->Hdr.TransactionID, + cmd->CompType, + data, + &wasBlockInCache, + &blocksRead, + fLBIDTraceOn, + session); pproc.setBlockPtr((int*) data); pproc.p_TokenByScan(cmd, output, output_buf_size, utf8, eqFilter); @@ -1107,7 +1264,7 @@ int DictScanJob::operator()() catchHandler(re.what(), uniqueId); } catch(...) { string msg("Unknown exception caught in DictScanJob."); - cerr << msg << endl; + cerr << msg << endl; catchHandler(msg, uniqueId); } return 0; @@ -1136,56 +1293,16 @@ void DictScanJob::sendErrorMsg(uint32_t id, uint16_t code) struct BPPHandler { - BPPHandler(PrimitiveServer* ps) : fPrimitiveServerPtr(ps) { } - - struct BPPHandlerFunctor : public PriorityThreadPool::Functor { - BPPHandlerFunctor(BPPHandler *r, SBS b) : rt(r), bs(b) - { - dieTime = posix_time::second_clock::universal_time() + posix_time::seconds(100); - } + BPPHandler(PrimitiveServer* ps) : fPrimitiveServerPtr(ps){ } + struct LastJoinerRunner { BPPHandler *rt; SBS bs; - posix_time::ptime dieTime; - }; - - struct LastJoiner : public BPPHandlerFunctor { - LastJoiner(BPPHandler *r, SBS b) : BPPHandlerFunctor(r, b) { } - int operator()() { - return rt->lastJoinerMsg(*bs, dieTime); - } - }; - - struct Create : public BPPHandlerFunctor { - Create(BPPHandler *r, SBS b) : BPPHandlerFunctor(r, b) { } - int operator()() { - rt->createBPP(*bs); - return 0; - } - }; - - struct Destroy : public BPPHandlerFunctor { - Destroy(BPPHandler *r, SBS b) : BPPHandlerFunctor(r, b) { } - int operator()() { - return rt->destroyBPP(*bs, dieTime); - } - }; - - struct AddJoiner : public BPPHandlerFunctor { - AddJoiner(BPPHandler *r, SBS b) : BPPHandlerFunctor(r, b) { } - int operator()() { - return rt->addJoinerToBPP(*bs, dieTime); - } + LastJoinerRunner(BPPHandler *r, SBS b) : rt(r), bs(b) { }; + void operator()() { rt->lastJoinerMsg(*bs); }; }; - struct Abort : public BPPHandlerFunctor { - Abort(BPPHandler *r, SBS b) : BPPHandlerFunctor(r, b) { } - int operator()() { - return rt->doAbort(*bs, dieTime); - } - }; - - int doAbort(ByteStream &bs, const posix_time::ptime &dieTime) + void doAbort(ByteStream &bs) { uint32_t key; BPPMap::iterator it; @@ -1194,135 +1311,118 @@ struct BPPHandler bs >> key; mutex::scoped_lock scoped(bppLock); it = bppMap.find(key); - if (it != bppMap.end()) { - it->second->abort(); - bppMap.erase(it); - } - else { - bs.rewind(); - if (posix_time::second_clock::universal_time() > dieTime) - return 0; - else - return -1; - } - scoped.unlock(); - fPrimitiveServerPtr->getProcessorThreadPool()->removeJobs(key); - OOBPool->removeJobs(key); - return 0; - } - - int doAck(ByteStream &bs) - { - uint32_t key; - int16_t msgCount; - SBPPV bpps; - const ISMPacketHeader *ism = (const ISMPacketHeader *) bs.buf(); - - key = ism->Interleave; - msgCount = (int16_t) ism->Size; - bs.advance(sizeof(ISMPacketHeader)); - - bpps = grabBPPs(key); - if (bpps) { - bpps->getSendThread()->sendMore(msgCount); - return 0; - } - else - return -1; + scoped.unlock(); + if (it != bppMap.end()) + it->second->abort(); + fPrimitiveServerPtr->getProcessorThreadPool()->removeJobs(key); } + void doAck(ByteStream &bs) + { + uint32_t key; + int16_t msgCount; + BPPMap::iterator it; + const ISMPacketHeader *ism = (const ISMPacketHeader *) bs.buf(); + + key = ism->Interleave; + msgCount = (int16_t) ism->Size; + bs.advance(sizeof(ISMPacketHeader)); + + mutex::scoped_lock scoped(bppLock); + it = bppMap.find(key); + scoped.unlock(); + if (it != bppMap.end()) + it->second->getSendThread()->sendMore(msgCount); + } + void createBPP(ByteStream &bs) { - uint32_t i; + uint i; uint32_t key, initMsgsLeft; SBPP bpp; SBPPV bppv; // make the new BPP object bppv.reset(new BPPV()); - bpp.reset(new BatchPrimitiveProcessor(bs, fPrimitiveServerPtr->prefetchThreshold(), - bppv->getSendThread())); - if (bs.length() > 0) + bpp.reset(new BatchPrimitiveProcessor(bs, fPrimitiveServerPtr->prefetchThreshold(), + bppv->getSendThread())); + if (bs.length() > 0) { bs >> initMsgsLeft; - else { + } + else{ initMsgsLeft = -1; } idbassert(bs.length() == 0); bppv->getSendThread()->sendMore(initMsgsLeft); bppv->add(bpp); - // this block of code creates some BPP instances up front for user queries, - // seems to get us slightly better query times - if ((bpp->getSessionID() & 0x80000000) == 0) { - for (i = 1; i < BPPCount/8; i++) { - SBPP dup = bpp->duplicate(); - - /* Uncomment these lines to verify duplicate(). == op might need updating */ -// if (*bpp != *dup) -// cerr << "createBPP: duplicate mismatch at index " << i << endl; -// idbassert(*bpp == *dup); - bppv->add(dup); - } + for (i = 1; i < BPPCount; i++) { + SBPP dup = bpp->duplicate(); + + /* Uncomment these lines to verify duplicate(). == op might need updating */ +// if (*bpp != *dup) +// cerr << "createBPP: duplicate mismatch at index " << i << endl; +// idbassert(*bpp == *dup); + bppv->add(dup); } + key = bpp->getUniqueID(); + //cout << "creating BPP key = " << key << endl; mutex::scoped_lock scoped(bppLock); bool newInsert; newInsert = bppMap.insert(pair(key, bppv)).second; - //cout << "creating BPP # " << key << endl; scoped.unlock(); if (!newInsert) { if (bpp->getSessionID() & 0x80000000) - cerr << "warning: createBPP() tried to clobber a BPP with duplicate sessionID & stepID. sessionID=" << - (int) (bpp->getSessionID() ^ 0x80000000) << " stepID=" << - bpp->getStepID()<< " (syscat)" << endl; + cerr << "warning: createBPP() tried to clobber a BPP with duplicate sessionID & stepID. sessionID=" << + (int) (bpp->getSessionID() ^ 0x80000000) << " stepID=" << + bpp->getStepID()<< " (syscat)" << endl; else cerr << "warning: createBPP() tried to clobber a BPP with duplicate sessionID & stepID. sessionID=" << - bpp->getSessionID() << " stepID=" << bpp->getStepID()<< endl; + bpp->getSessionID() << " stepID=" << bpp->getStepID()<< endl; } } - SBPPV grabBPPs(uint32_t uniqueID) + SBPPV grabBPPs(uint32_t uniqueID, bool fatal=true) { BPPMap::iterator it; - /* - uint32_t failCount = 0; - uint32_t maxFailCount = (fatal ? 500 : 5000); - */ + uint failCount = 0; + uint maxFailCount = (fatal ? 500 : 5000); SBPPV ret; mutex::scoped_lock scoped(bppLock); it = bppMap.find(uniqueID); if (it != bppMap.end()) - return it->second; - else - return SBPPV(); - /* - do - { - if (++failCount == maxFailCount) { - //cout << "grabBPPs couldn't find the BPPs for " << uniqueID << endl; - return ret; - //throw logic_error("grabBPPs couldn't find the unique ID"); - } - scoped.unlock(); - usleep(5000); - scoped.lock(); - it = bppMap.find(uniqueID); - } while (it == bppMap.end()); + { + ret = it->second; + return ret; + } - ret = it->second; + do + { + if (++failCount == maxFailCount) { + //cout << "grabBPPs couldn't find the BPPs for " << uniqueID << endl; return ret; - */ + //throw logic_error("grabBPPs couldn't find the unique ID"); + } + scoped.unlock(); + usleep(5000); + scoped.lock(); + it = bppMap.find(uniqueID); + } while (it == bppMap.end()); + + ret = it->second; + return ret; } - int addJoinerToBPP(ByteStream &bs, const posix_time::ptime &dieTime) + void addJoinerToBPP(ByteStream &bs) { SBPPV bppv; uint32_t uniqueID; const uint8_t *buf; /* call addToJoiner() on the first BPP */ - + buf = bs.buf(); /* the uniqueID is after the ISMPacketHeader, sessionID, and stepID */ uniqueID = *((const uint32_t *) &buf[sizeof(ISMPacketHeader) + 2*sizeof(uint32_t)]); @@ -1330,59 +1430,30 @@ struct BPPHandler if (bppv) { mutex::scoped_lock lk(djLock); bppv->get()[0]->addToJoiner(bs); - return 0; - } - else { - if (posix_time::second_clock::universal_time() > dieTime) - return 0; - else - return -1; } } - int lastJoinerMsg(ByteStream &bs, const posix_time::ptime &dieTime) + void lastJoinerMsg(ByteStream &bs) { SBPPV bppv; uint32_t uniqueID, i; const uint8_t *buf; - int err; /* call endOfJoiner() on the every BPP */ buf = bs.buf(); /* the uniqueID is after the ISMPacketHeader, sessionID, and stepID */ uniqueID = *((const uint32_t *) &buf[sizeof(ISMPacketHeader) + 2*sizeof(uint32_t)]); - - bppv = grabBPPs(uniqueID); - if (!bppv) { - //cout << "got a lastJoiner msg for an unknown obj " << uniqueID << endl; - if (posix_time::second_clock::universal_time() > dieTime) - return 0; - else - return -1; - } - + + bppv = grabBPPs(uniqueID, false); + if (!bppv) // they've already been destroyed + return; mutex::scoped_lock lk(djLock); - for (i = 0; i < bppv->get().size(); i++) { - err = bppv->get()[i]->endOfJoiner(); - if (err == -1) { - if (posix_time::second_clock::universal_time() > dieTime) - return 0; - else - return -1; - } - } - - /* Note: some of the duplicate/run/join sync was moved to the BPPV class to do - more intelligent scheduling. Once the join data is received, BPPV will - start letting jobs run and create more BPP instances on demand. */ - - atomicops::atomicMb(); // make sure the joinDataReceived assignment doesn't migrate upward... - bppv->joinDataReceived = true; - return 0; + for (i = 0; i < bppv->get().size(); i++) + bppv->get()[i]->endOfJoiner(); } - int destroyBPP(ByteStream &bs, const posix_time::ptime &dieTime) + void destroyBPP(ByteStream &bs) { uint32_t uniqueID, sessionID, stepID; BPPMap::iterator it; @@ -1391,35 +1462,25 @@ struct BPPHandler bs >> sessionID; bs >> stepID; bs >> uniqueID; - mutex::scoped_lock lk(djLock); mutex::scoped_lock scoped(bppLock); - + //cout << "destroying BPP # " << uniqueID << endl; it = bppMap.find(uniqueID); if (it != bppMap.end()) { it->second->abort(); bppMap.erase(it); } - else { - //cout << "got a destroy for an unknown obj " << uniqueID << endl; - bs.rewind(); - if (posix_time::second_clock::universal_time() > dieTime) - return 0; - else - return -1; - } + scoped.unlock(); // cout << " destroy: new size is " << bppMap.size() << endl; - /* - if (sessionID & 0x80000000) - cerr << "destroyed BPP instances for sessionID " << (int) - (sessionID ^ 0x80000000) << " stepID "<< stepID << " (syscat)\n"; - else - cerr << "destroyed BPP instances for sessionID " << sessionID << - " stepID "<< stepID << endl; - */ +/* + if (sessionID & 0x80000000) + cerr << "destroyed BPP instances for sessionID " << (int) + (sessionID ^ 0x80000000) << " stepID "<< stepID << " (syscat)\n"; + else + cerr << "destroyed BPP instances for sessionID " << sessionID << + " stepID "<< stepID << endl; +*/ fPrimitiveServerPtr->getProcessorThreadPool()->removeJobs(uniqueID); - OOBPool->removeJobs(uniqueID); - return 0; } void setBPPToError(uint32_t uniqueID, const string& error, logging::ErrorCodeValues errorCode) @@ -1429,116 +1490,15 @@ struct BPPHandler bppv = grabBPPs(uniqueID); if (!bppv) return; - for (uint32_t i = 0; i < bppv->get().size(); i++) + for (uint i = 0; i < bppv->get().size(); i++) bppv->get()[i]->setError(error, errorCode); if (bppv->get().empty() && !bppMap.empty() ) bppMap.begin()->second.get()->get()[0]->setError(error, errorCode); } - // Would be good to define the structure of these msgs somewhere... - inline uint32_t getUniqueID(SBS bs, uint8_t command) - { - uint8_t *buf; - - buf = bs->buf(); - switch (command) { - case BATCH_PRIMITIVE_ABORT: - return *((uint32_t *) &buf[sizeof(ISMPacketHeader)]); - case BATCH_PRIMITIVE_ACK: { - ISMPacketHeader *ism = (ISMPacketHeader *) buf; - return ism->Interleave; - } - case BATCH_PRIMITIVE_ADD_JOINER: - case BATCH_PRIMITIVE_END_JOINER: - case BATCH_PRIMITIVE_DESTROY: - return *((uint32_t *) &buf[sizeof(ISMPacketHeader) + 2*sizeof(uint32_t)]); - default: - return 0; - } - } - PrimitiveServer* fPrimitiveServerPtr; }; -class DictionaryOp : public PriorityThreadPool::Functor -{ -public: - DictionaryOp(SBS cmd) : bs(cmd) { - dieTime = posix_time::second_clock::universal_time() + posix_time::seconds(100); - } - virtual int execute() = 0; - int operator()() { - int ret; - ret = execute(); - if (ret != 0) { - bs->rewind(); - if (posix_time::second_clock::universal_time() > dieTime) - return 0; - } - return ret; - } -protected: - SBS bs; -private: - posix_time::ptime dieTime; -}; - -class CreateEqualityFilter : public DictionaryOp -{ -public: - CreateEqualityFilter(SBS cmd) : DictionaryOp(cmd) { } - int execute() { - createEqualityFilter(); - return 0; - } - -private: - void createEqualityFilter() - { - uint32_t uniqueID, count, i; - string str; - boost::shared_ptr filter(new DictEqualityFilter()); - - bs->advance(sizeof(ISMPacketHeader)); - *bs >> uniqueID; - *bs >> count; - for (i = 0; i < count; i++) { - *bs >> str; - filter->insert(str); - } - - mutex::scoped_lock sl(eqFilterMutex); - dictEqualityFilters[uniqueID] = filter; - } -}; - -class DestroyEqualityFilter : public DictionaryOp -{ -public: - DestroyEqualityFilter(SBS cmd) : DictionaryOp(cmd) { } - int execute() { - return destroyEqualityFilter(); - } - - int destroyEqualityFilter() - { - uint32_t uniqueID; - map >::iterator it; - - bs->advance(sizeof(ISMPacketHeader)); - *bs >> uniqueID; - - mutex::scoped_lock sl(eqFilterMutex); - it = dictEqualityFilters.find(uniqueID); - if (it != dictEqualityFilters.end()) { - dictEqualityFilters.erase(it); - return 0; - } - else - return -1; - } -}; - struct ReadThread { ReadThread(const string& serverName, IOSocket& ios, PrimitiveServer* ps) : @@ -1546,6 +1506,13 @@ struct ReadThread { } + struct LastJoinerRunner { + BPPHandler* rt; + SBS bs; + LastJoinerRunner(BPPHandler *r, SBS b) : rt(r), bs(b) { }; + void operator()() { rt->lastJoinerMsg(*bs); }; + }; + const ByteStream buildCacheOpResp(int32_t result) { const int msgsize = sizeof(ISMPacketHeader) + sizeof(int32_t); @@ -1567,8 +1534,7 @@ struct ReadThread { uint8_t *buf = bs.buf(); buf += sizeof(ISMPacketHeader); - uint32_t count = *((uint32_t *) buf); - buf += 4; + uint32_t count = *((uint32_t *) buf); buf += 4; uint32_t *oids = (uint32_t *) buf; for (int i = 0; i < fCacheCount; i++) { @@ -1614,25 +1580,12 @@ struct ReadThread ios->write(buildCacheOpResp(0)); } - void doCacheDropFDs(SP_UM_IOSOCK ios, ByteStream &bs) + void doCacheDropFDs(SP_UM_IOSOCK ios) { - std::vector files; - - bs.advance(sizeof(ISMPacketHeader)); dropFDCache(); ios->write(buildCacheOpResp(0)); } - void doCachePurgeFDs(SP_UM_IOSOCK ios, ByteStream &bs) - { - std::vector files; - - bs.advance(sizeof(ISMPacketHeader)); - deserializeInlineVector(bs, files); - purgeFDCache(files); - ios->write(buildCacheOpResp(0)); - } - //N.B. this fcn doesn't actually clean the VSS, but rather instructs PP to flush its // cache of specific LBID's void doCacheCleanVSSCmd(SP_UM_IOSOCK ios, const ByteStream& bs) @@ -1662,11 +1615,39 @@ struct ReadThread } ios->write(buildCacheOpResp(0)); } + + void createEqualityFilter(SBS bs) + { + uint32_t uniqueID, count, i; + string str; + boost::shared_ptr filter(new DictEqualityFilter()); + + bs->advance(sizeof(ISMPacketHeader)); + *bs >> uniqueID; + *bs >> count; + for (i = 0; i < count; i++) { + *bs >> str; + filter->insert(str); + } + + mutex::scoped_lock sl(eqFilterMutex); + dictEqualityFilters[uniqueID] = filter; + } + + void destroyEqualityFilter(SBS bs) + { + mutex::scoped_lock sl(eqFilterMutex); + uint32_t uniqueID; + + bs->advance(sizeof(ISMPacketHeader)); + *bs >> uniqueID; + dictEqualityFilters.erase(uniqueID); + } void operator()() { boost::shared_ptr procPoolPtr = - fPrimitiveServerPtr->getProcessorThreadPool(); + fPrimitiveServerPtr->getProcessorThreadPool(); SBS bs; UmSocketSelector* pUmSocketSelector = UmSocketSelector::instance(); @@ -1702,195 +1683,154 @@ struct ReadThread break; } try { - if (bs->length() != 0) { - idbassert(bs->length() >= sizeof(ISMPacketHeader)); - - const ISMPacketHeader* ismHdr = reinterpret_cast(bs->buf()); - - /* This switch is for the OOB commands */ - switch(ismHdr->Command) { - case CACHE_FLUSH_PARTITION: - doCacheFlushByPartition(outIos, *bs); - fIos.close(); - return; - case CACHE_FLUSH_BY_OID: - doCacheFlushByOID(outIos, *bs); - fIos.close(); - return; - case CACHE_FLUSH: - doCacheFlushCmd(outIos, *bs); - fIos.close(); - return; - case CACHE_CLEAN_VSS: - doCacheCleanVSSCmd(outIos, *bs); - fIos.close(); - return; - case FLUSH_ALL_VERSION: - doCacheFlushAllversion(outIos, *bs); - fIos.close(); - return; - case CACHE_DROP_FDS: - doCacheDropFDs(outIos, *bs); - fIos.close(); - return; - case CACHE_PURGE_FDS: - doCachePurgeFDs(outIos, *bs); - fIos.close(); - return; - default: - break; - } + if (bs->length() != 0) { + idbassert(bs->length() >= sizeof(ISMPacketHeader)); - switch(ismHdr->Command) { - case DICT_CREATE_EQUALITY_FILTER: { - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new CreateEqualityFilter(bs)); - OOBPool->addJob(job); - break; - } - case DICT_DESTROY_EQUALITY_FILTER: { - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new DestroyEqualityFilter(bs)); - OOBPool->addJob(job); - break; - } - case DICT_TOKEN_BY_SCAN_COMPARE: { - idbassert(bs->length() >= sizeof(TokenByScanRequestHeader)); - TokenByScanRequestHeader *hdr = (TokenByScanRequestHeader *) ismHdr; - if (bRotateDest) { - if (!pUmSocketSelector->nextIOSocket( - fIos, outIos, writeLock)) { - // If we ever fall into this part of the - // code we have a "bug" of some sort. - // See handleUmSockSelErr() for more info. - // We reset ios and mutex to defaults. - handleUmSockSelErr(string("default cmd")); - outIos = outIosDefault; - writeLock = writeLockDefault; - pUmSocketSelector->delConnection(fIos); - bRotateDest = false; - } + const ISMPacketHeader* ismHdr = reinterpret_cast(bs->buf()); + + /* This switch is for the OOB commands */ + switch(ismHdr->Command) { + case CACHE_FLUSH_PARTITION: + doCacheFlushByPartition(outIos, *bs); + fIos.close(); + return; + case CACHE_FLUSH_BY_OID: + doCacheFlushByOID(outIos, *bs); + fIos.close(); + return; + case CACHE_FLUSH: + doCacheFlushCmd(outIos, *bs); + fIos.close(); + return; + case CACHE_CLEAN_VSS: + doCacheCleanVSSCmd(outIos, *bs); + fIos.close(); + return; + case FLUSH_ALL_VERSION: + doCacheFlushAllversion(outIos, *bs); + fIos.close(); + return; + case CACHE_DROP_FDS: + doCacheDropFDs(outIos); + fIos.close(); + return; + default: + break; + } + + switch(ismHdr->Command) { + case DICT_CREATE_EQUALITY_FILTER: { + createEqualityFilter(bs); + break; + } + case DICT_DESTROY_EQUALITY_FILTER: { + destroyEqualityFilter(bs); + break; + } + case DICT_TOKEN_BY_SCAN_COMPARE: { + idbassert(bs->length() >= sizeof(TokenByScanRequestHeader)); + TokenByScanRequestHeader *hdr = (TokenByScanRequestHeader *) ismHdr; + if (bRotateDest) { + if (!pUmSocketSelector->nextIOSocket( + fIos, outIos, writeLock)) { + // If we ever fall into this part of the + // code we have a "bug" of some sort. + // See handleUmSockSelErr() for more info. + // We reset ios and mutex to defaults. + handleUmSockSelErr(string("default cmd")); + outIos = outIosDefault; + writeLock = writeLockDefault; + pUmSocketSelector->delConnection(fIos); + bRotateDest = false; } + } + if (hdr->flags & IS_SYSCAT) + boost::thread t(DictScanJob(outIos, bs, writeLock)); + else { PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new DictScanJob(outIos, - bs, writeLock)); - job.id = hdr->Hdr.UniqueID; + job.functor = shared_ptr(new DictScanJob(outIos, + bs, writeLock)); + job.id = hdr->Hdr.UniqueID;; job.weight = LOGICAL_BLOCK_RIDS; job.priority = hdr->Hdr.Priority; - if (hdr->flags & IS_SYSCAT) { - //boost::thread t(DictScanJob(outIos, bs, writeLock)); - // using already-existing threads may cut latency - // if it's changed back to running in an independent thread - // change the issyscat() checks in BPPSeeder as well - OOBPool->addJob(job); - } - else { - procPoolPtr->addJob(job); - } - break; + procPoolPtr->addJob(job); } - case BATCH_PRIMITIVE_RUN: { - if (bRotateDest) { - if (!pUmSocketSelector->nextIOSocket( - fIos, outIos, writeLock)) { - - // If we ever fall into this part of the - // code we have a "bug" of some sort. - // See handleUmSockSelErr() for more info. - // We reset ios and mutex to defaults. - handleUmSockSelErr(string("BPR cmd")); - outIos = outIosDefault; - writeLock = writeLockDefault; - pUmSocketSelector->delConnection(fIos); - bRotateDest = false; - } + break; + } + case BATCH_PRIMITIVE_RUN: { + if (bRotateDest) { + if (!pUmSocketSelector->nextIOSocket( + fIos, outIos, writeLock)) { + + // If we ever fall into this part of the + // code we have a "bug" of some sort. + // See handleUmSockSelErr() for more info. + // We reset ios and mutex to defaults. + handleUmSockSelErr(string("BPR cmd")); + outIos = outIosDefault; + writeLock = writeLockDefault; + pUmSocketSelector->delConnection(fIos); + bRotateDest = false; } - /* Decide whether this is a syscat call and run - right away instead of queueing */ - boost::shared_ptr bpps(new BPPSeeder(bs, writeLock, outIos, - fPrimitiveServerPtr->ProcessorThreads(), - fPrimitiveServerPtr->PTTrace())); + } + /* Decide whether this is a syscat call and run + right away instead of queueing */ + shared_ptr bpps(new BPPSeeder(bs, writeLock, outIos, + fPrimitiveServerPtr->ProcessorThreads(), + fPrimitiveServerPtr->PTTrace())); + if (bpps->isSysCat()) + boost::thread t(*bpps); + else { PriorityThreadPool::Job job; job.functor = bpps; job.id = bpps->getID(); job.weight = ismHdr->Size; job.priority = bpps->priority(); - if (bpps->isSysCat()) { - //boost::thread t(*bpps); - // using already-existing threads may cut latency - // if it's changed back to running in an independent thread - // change the issyscat() checks in BPPSeeder as well - OOBPool->addJob(job); - } - else { - procPoolPtr->addJob(job); - } - break; - } - case BATCH_PRIMITIVE_CREATE: { - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new BPPHandler::Create(&fBPPHandler, bs)); - OOBPool->addJob(job); - //fBPPHandler.createBPP(*bs); - break; - } - case BATCH_PRIMITIVE_ADD_JOINER: { - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new BPPHandler::AddJoiner(&fBPPHandler, bs)); - job.id = fBPPHandler.getUniqueID(bs, ismHdr->Command); - OOBPool->addJob(job); - //fBPPHandler.addJoinerToBPP(*bs); - break; - } - case BATCH_PRIMITIVE_END_JOINER: { - // lastJoinerMsg can block; must do this in a different thread - //OOBPool->invoke(BPPHandler::LastJoiner(&fBPPHandler, bs)); // needs a threadpool that can resched - //boost::thread tmp(BPPHandler::LastJoiner(&fBPPHandler, bs)); - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new BPPHandler::LastJoiner(&fBPPHandler, bs)); - job.id = fBPPHandler.getUniqueID(bs, ismHdr->Command); - OOBPool->addJob(job); - break; - } - case BATCH_PRIMITIVE_DESTROY: { - //OOBPool->invoke(BPPHandler::Destroy(&fBPPHandler, bs)); // needs a threadpool that can resched - //boost::thread tmp(BPPHandler::Destroy(&fBPPHandler, bs)); - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new BPPHandler::Destroy(&fBPPHandler, bs)); - job.id = fBPPHandler.getUniqueID(bs, ismHdr->Command); - OOBPool->addJob(job); - //fBPPHandler.destroyBPP(*bs); - break; - } - case BATCH_PRIMITIVE_ACK: { - fBPPHandler.doAck(*bs); - break; + procPoolPtr->addJob(job); } - case BATCH_PRIMITIVE_ABORT: { - //OBPool->invoke(BPPHandler::Abort(&fBPPHandler, bs)); - //fBPPHandler.doAbort(*bs); - PriorityThreadPool::Job job; - job.functor = boost::shared_ptr(new BPPHandler::Abort(&fBPPHandler, bs)); - job.id = fBPPHandler.getUniqueID(bs, ismHdr->Command); - OOBPool->addJob(job); - break; - } - default: { - std::ostringstream os; - Logger log; - os << "unknown primitive cmd: " << ismHdr->Command; - log.logMessage(os.str()); - break; - } - } // the switch stmt + break; } - else // bs.length() == 0 - { - if (bRotateDest) - pUmSocketSelector->delConnection(fIos); - fIos.close(); + case BATCH_PRIMITIVE_CREATE: { + fBPPHandler.createBPP(*bs); + break; + } + case BATCH_PRIMITIVE_ADD_JOINER: { + fBPPHandler.addJoinerToBPP(*bs); + break; + } + case BATCH_PRIMITIVE_END_JOINER: { + // lastJoinerMsg can block; must do this in a different thread + boost::thread t(BPPHandler::LastJoinerRunner(&fBPPHandler, bs)); + break; + } + case BATCH_PRIMITIVE_DESTROY: { + fBPPHandler.destroyBPP(*bs); + break; + } + case BATCH_PRIMITIVE_ACK: { + fBPPHandler.doAck(*bs); + break; + } + case BATCH_PRIMITIVE_ABORT: { + fBPPHandler.doAbort(*bs); + break; + } + default: { + std::ostringstream os; + Logger log; + os << "unknown primitive cmd: " << ismHdr->Command; + log.logMessage(os.str()); break; } + } // the switch stmt + } + else // bs.length() == 0 + { + if (bRotateDest) + pUmSocketSelector->delConnection(fIos); + fIos.close(); + break; + } } // the try- surrounding the if stmt catch (std::exception &e) { Logger logger; @@ -1909,7 +1849,7 @@ struct ReadThread { ostringstream oss; oss << "Unable to rotate through socket destinations (" << - cmd << ") for connection: " << fIos.toString(); + cmd << ") for connection: " << fIos.toString(); cerr << oss.str() << endl; logging::Message::Args args; args.add(oss.str()); @@ -1979,46 +1919,149 @@ struct ServerThread MessageQueueServer* mqServerPtr; }; + + +// Receives messages from Multicast PGM protocol +struct TransportReceiverThread +{ + PrimitiveServer* fPrimServer; +// MulticastReceiver fmcReceiver; + uint64_t fMaxBytes; + bool fMultiloop; + string fServerName; + BPPHandler fBPPHandler; + uint8_t fLastCommand; + uint32_t fLastUniqueId; + + TransportReceiverThread(uint64_t maxBytes, bool loop, const string& name, PrimitiveServer* ps) : + fPrimServer(ps), fMaxBytes(maxBytes), /*fmcReceiver*/fMultiloop(loop), fServerName(name), + fBPPHandler(ps), fLastCommand(0), fLastUniqueId(0) + { + SUMMARY_INFO("Starting multicast receiver"); + } + + void operator()() + { + MulticastReceiver fmcReceiver; + do + { + try + { + SBS byteStream = fmcReceiver.receive(); //blocks + processMessage(byteStream); + } + catch(const logging::MulticastException& ex) + { + logAndSendErrorMessage(ex.what()); +#ifdef ECONNRESET + if (ECONNRESET != ex.errorCode()) +#endif + return; + } + catch(const std::exception& ex) + { + logAndSendErrorMessage(ex.what()); + return; + } + catch(...) + { + logAndSendErrorMessage("Multicast caught unknown exception"); + return; + } + + } + while (true); + } + + void processMessage(const SBS& bs) + { + idbassert(bs->length() >= sizeof(ISMPacketHeader)); + + const ByteStream::byte* bytePtr = bs->buf(); + const ISMPacketHeader* ismHdr = reinterpret_cast(bytePtr); + fLastCommand = ismHdr->Command; + switch (ismHdr->Command) + { + case BATCH_PRIMITIVE_CREATE: + fLastUniqueId = *((const uint32_t *) &bytePtr[sizeof(ISMPacketHeader) + sizeof(uint8_t) + 4*sizeof(uint32_t)]); + + fBPPHandler.createBPP(*bs); + break; + case BATCH_PRIMITIVE_DESTROY: + fBPPHandler.destroyBPP(*bs); + break; + case BATCH_PRIMITIVE_ADD_JOINER: + fLastUniqueId = *((const uint32_t *) &bytePtr[sizeof(ISMPacketHeader) + 2*sizeof(uint32_t)]); + fBPPHandler.addJoinerToBPP(*bs); + break; + case BATCH_PRIMITIVE_END_JOINER: + { + // lastJoinerMsg blocks, this thread won't wait. + boost::thread t(BPPHandler::LastJoinerRunner(&fBPPHandler, bs)); + break; + } + default: + ostringstream oss; + oss << "Incorrect message type for Multicast "; + oss << ismHdr->Command; + logging::Message::Args args; + args.add(oss.str()); + mlp->logMessage(logging::M0070,args); + } + } + + void logAndSendErrorMessage(const string& msg) + { + logging::Message::Args args; + args.add(msg); + mlp->logMessage(logging::M0070,args, true); + if (BATCH_PRIMITIVE_ADD_JOINER == fLastCommand || BATCH_PRIMITIVE_CREATE == fLastCommand) + { + fBPPHandler.setBPPToError(fLastUniqueId, msg, logging::multicastErr); + } + } +}; + } // namespace anon namespace primitiveprocessor { PrimitiveServer::PrimitiveServer(int serverThreads, - int serverQueueSize, - int processorWeight, - int processorQueueSize, - bool rotatingDestination, - uint32_t BRPBlocks, - int BRPThreads, - int cacheCount, - int maxBlocksPerRead, - int readAheadBlocks, - uint32_t deleteBlocks, - bool ptTrace, - double prefetch, - uint64_t smallSide + int serverQueueSize, + int processorWeight, + int processorQueueSize, + bool rotatingDestination, + uint32_t BRPBlocks, + int BRPThreads, + int cacheCount, + int maxBlocksPerRead, + int readAheadBlocks, + uint32_t deleteBlocks, + bool ptTrace, + double prefetch, + bool multicast, + bool multicastloop, + uint64_t smallSide ): - fServerThreads(serverThreads), - fServerQueueSize(serverQueueSize), - fProcessorWeight(processorWeight), - fProcessorQueueSize(processorQueueSize), - fMaxBlocksPerRead(maxBlocksPerRead), - fReadAheadBlocks(readAheadBlocks), - fRotatingDestination(rotatingDestination), - fPTTrace(ptTrace), - fPrefetchThreshold(prefetch), - fPMSmallSide(smallSide) + fServerThreads(serverThreads), + fServerQueueSize(serverQueueSize), + fProcessorWeight(processorWeight), + fProcessorQueueSize(processorQueueSize), + fMaxBlocksPerRead(maxBlocksPerRead), + fReadAheadBlocks(readAheadBlocks), + fRotatingDestination(rotatingDestination), + fPTTrace(ptTrace), + fPrefetchThreshold(prefetch), + fMulticast(multicast), + fMulticastloop(multicastloop), + fPMSmallSide(smallSide) { fCacheCount=cacheCount; - fServerpool.setMaxThreads(fServerThreads); + fServerpool.setMaxThreads(fServerThreads + multicast); fServerpool.setQueueSize(fServerQueueSize); fProcessorPool.reset(new threadpool::PriorityThreadPool(fProcessorWeight, highPriorityThreads, - medPriorityThreads, lowPriorityThreads, 0)); - - // We're not using either the priority or the job-clustering features, just need a threadpool - // that can reschedule jobs, and an unlimited non-blocking queue - OOBPool.reset(new threadpool::PriorityThreadPool(1, 5, 0, 0, 1)); + medPriorityThreads, lowPriorityThreads)); asyncCounter = 0; @@ -2029,12 +2072,12 @@ PrimitiveServer::PrimitiveServer(int serverThreads, { for (int i = 0; i < fCacheCount; i++) BRPp[i] = new BlockRequestProcessor(BRPBlocks/fCacheCount, BRPThreads/fCacheCount, - fMaxBlocksPerRead, deleteBlocks/fCacheCount); + fMaxBlocksPerRead, deleteBlocks/fCacheCount); } catch (...) { cerr << "Unable to allocate " << BRPBlocks << " cache blocks. Adjust the DBBC config parameter " - "downward." << endl; + "downward." << endl; mlp->logMessage(logging::M0045, logging::Message::Args(), true); exit(1); } @@ -2055,6 +2098,27 @@ void PrimitiveServer::start() fServerpool.invoke(ServerThread(oss.str(), this)); } + if (fMulticast) + { + pause_(5); + try + { + fServerpool.invoke(TransportReceiverThread(fPMSmallSide, fMulticastloop, "PMS1", this)); + } + catch (const logging::MulticastException& mce) + { + string errormsg(" Error starting Multicast Receiver Thread. Turning Multicast off"); + cout << mce.what() << errormsg << endl; + logging::Message::Args args; + args.add(mce.what()); + args.add(errormsg); + mlp->logMessage(logging::M0070,args); + fMulticast = false; + } + } + // wait for things to settle down... +// pause_(5); + { Oam oam; try { @@ -2070,9 +2134,6 @@ void PrimitiveServer::start() BPPV::BPPV() { sendThread.reset(new BPPSendThread()); - v.reserve(BPPCount); - pos = 0; - joinDataReceived = false; } BPPV::~BPPV() @@ -2081,21 +2142,6 @@ BPPV::~BPPV() void BPPV::add(boost::shared_ptr a) { - /* Right now BPP initialization locks the object if there is a join to - prevent the instance from being used before the join data is received. - The init/join/run sync code is quite old and confusing at this point, - and this makes it a little worse by circumventing the original design. - Due for a rewrite. */ - - if (!unusedInstance) { - unusedInstance = a->duplicate(); - if (a->hasJoin()) { - joinDataReceived = false; - unusedInstance->unlock(); - } - else - joinDataReceived = true; - } v.push_back(a); } const vector > & BPPV::get() @@ -2106,50 +2152,16 @@ const vector > & BPPV::get() boost::shared_ptr BPPV::next() { - uint32_t size = v.size(); - uint32_t i; + std::vector >::iterator bpp = v.begin(); -#if 0 - // This block of code scans for the first available BPP instance, - // makes BPPSeeder reschedule it if none are available. Relies on BPP instance - // being preallocated. - for (i = 0; i < size; i++) { - uint32_t index = (i + pos) % size; - if (!(v[index]->busy())) { - pos = (index + 1) % size; - v[index]->busy(true); - return v[index]; + for (bpp = v.begin(); bpp != v.end(); bpp++) + if (!(*bpp)->busy()) { + (*bpp)->busy(true); + return *bpp; } - } + // They're all busy, make threadpool reschedule the job return boost::shared_ptr(); -#endif - - //This block of code creates BPP instances if/when they are needed - - // don't use a processor thread when it will just block, reschedule it instead - if (!joinDataReceived) - return boost::shared_ptr(); - - for (i = 0; i < size; i++) { - uint32_t index = (i+pos) % size; - if (!(v[index]->busy())) { - pos = (index + 1) % size; - v[index]->busy(true); - return v[index]; - } - } - - // honor the BPPCount limit, mostly for debugging purposes. - if (size >= BPPCount) - return boost::shared_ptr(); - - SBPP newone = unusedInstance->duplicate(); - if (newone->hasJoin()) - newone->unlock(); - newone->busy(true); - v.push_back(newone); - return newone; } void BPPV::abort() @@ -2157,11 +2169,6 @@ void BPPV::abort() sendThread->abort(); } -bool BPPV::aborted() -{ - return sendThread->aborted(); -} - #ifdef PRIMPROC_STOPWATCH map stopwatchMap; pthread_mutex_t stopwatchMapMutex; diff --git a/primitives/primproc/primitiveserver.h b/primitives/primproc/primitiveserver.h index 79880c70..82543e6c 100644 --- a/primitives/primproc/primitiveserver.h +++ b/primitives/primproc/primitiveserver.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: primitiveserver.h 2055 2013-02-08 19:09:09Z pleblanc $ + * $Id: primitiveserver.h 2026 2013-01-04 20:16:36Z pleblanc $ * * ***********************************************************************/ @@ -40,28 +40,23 @@ #include "blockrequestprocessor.h" #include "batchprimitiveprocessor.h" -#include "winport.h" //#define PRIMPROC_STOPWATCH #ifdef PRIMPROC_STOPWATCH #include "stopwatch.h" #endif -#include "oamcache.h" -extern oam::OamCache *oamCache; - namespace primitiveprocessor { - extern boost::shared_ptr OOBPool; extern dbbc::BlockRequestProcessor **BRPp; extern BRM::DBRM *brm; extern boost::mutex bppLock; - extern uint32_t highPriorityThreads, medPriorityThreads, lowPriorityThreads; + extern uint highPriorityThreads, medPriorityThreads, lowPriorityThreads; #ifdef PRIMPROC_STOPWATCH extern map stopwatchMap; extern pthread_mutex_t stopwatchMapMutex; extern bool stopwatchThreadCreated; - + extern void pause_(int seconds); extern void *autoFinishStopwatchThread(void *arg); #endif @@ -75,103 +70,98 @@ namespace primitiveprocessor const std::vector > & get(); inline boost::shared_ptr getSendThread() { return sendThread; } void abort(); - bool aborted(); - volatile bool joinDataReceived; private: std::vector > v; boost::shared_ptr sendThread; - - // the instance other instances are created from - boost::shared_ptr unusedInstance; - - // pos keeps the position of the last BPP returned by next(), - // next() will start searching at this pos on the next call. - uint32_t pos; }; typedef boost::shared_ptr SBPPV; typedef std::map BPPMap; extern BPPMap bppMap; - void prefetchBlocks(uint64_t lbid, uint32_t* rCount); + void prefetchBlocks(uint64_t lbid, uint32_t ver, uint32_t txn, uint32_t* rCount); void prefetchExtent(uint64_t lbid, uint32_t ver, uint32_t txn, uint32_t* rCount); - void loadBlock(uint64_t lbid, BRM::QueryContext q, uint32_t txn, int compType, void* bufferPtr, + void loadBlock(u_int64_t lbid, u_int32_t ver, u_int32_t txn, int compType, void* bufferPtr, bool* pWasBlockInCache, uint32_t* rCount=NULL, bool LBIDTrace = false, uint32_t sessionID = 0, bool doPrefetch=true, VSSCache *vssCache = NULL); - void loadBlockAsync(uint64_t lbid, const BRM::QueryContext &q, uint32_t txn, int CompType, + void loadBlockAsync(uint64_t lbid, uint32_t ver, uint32_t txn, int CompType, uint32_t *cCount, uint32_t *rCount, bool LBIDTrace, uint32_t sessionID, - boost::mutex *m, uint32_t *busyLoaders, VSSCache* vssCache=0); - uint32_t loadBlocks(BRM::LBID_t *lbids, BRM::QueryContext q, BRM::VER_t txn, int compType, + boost::mutex *m, uint *busyLoaders, VSSCache* vssCache=0); + uint loadBlocks(BRM::LBID_t *lbids, BRM::VER_t *vers, BRM::VER_t txn, int compType, uint8_t **bufferPtrs, uint32_t *rCount, bool LBIDTrace, uint32_t sessionID, - uint32_t blockCount, bool *wasVersioned, bool doPrefetch = true, VSSCache *vssCache = NULL); - uint32_t cacheNum(uint64_t lbid); + uint blockCount, bool *wasVersioned, bool doPrefetch = true, VSSCache *vssCache = NULL); + uint cacheNum(uint64_t lbid); void buildFileName(BRM::OID_t oid, char* fileName); - /** @brief process primitives as they arrive - */ - class PrimitiveServer - { - public: - /** @brief ctor - */ - PrimitiveServer(int serverThreads, + /** @brief process primitives as they arrive + */ + class PrimitiveServer + { + public: + /** @brief ctor + */ + PrimitiveServer(int serverThreads, int serverQueueSize, int processorWeight, int processorQueueSize, bool rotatingDestination, - uint32_t BRPBlocks=(1024 * 1024 * 2), - int BRPThreads=64, + uint32_t BRPBlocks=(1024 * 1024 * 2), + int BRPThreads=64, int cacheCount = 8, int maxBlocksPerRead = 128, int readAheadBlocks=256, uint32_t deleteBlocks = 0, bool ptTrace=false, double prefetchThreshold = 0, + bool multicast = false, + bool multicastloop = false, uint64_t pmSmallSide = 0); - /** @brief dtor - */ - ~PrimitiveServer(); + /** @brief dtor + */ + ~PrimitiveServer(); - /** @brief start the primitive server - * - */ - void start(); + /** @brief start the primitive server + * + */ + void start(); - /** @brief get a pointer the shared processor thread pool - */ - inline boost::shared_ptr getProcessorThreadPool() const { return fProcessorPool; } + /** @brief get a pointer the shared processor thread pool + */ + inline boost::shared_ptr getProcessorThreadPool() const { return fProcessorPool; } // int fCacheCount; const int ReadAheadBlocks() const {return fReadAheadBlocks;} bool rotatingDestination() const {return fRotatingDestination;} bool PTTrace() const {return fPTTrace;} double prefetchThreshold() const { return fPrefetchThreshold; } - uint32_t ProcessorThreads() const { return highPriorityThreads + medPriorityThreads + lowPriorityThreads; } - protected: - - private: - /** @brief the thread pool used to listen for - * incoming primitive commands - */ - threadpool::ThreadPool fServerpool; - - /** @brief the thread pool used to process - * primitive commands - */ - boost::shared_ptr fProcessorPool; - - int fServerThreads; - int fServerQueueSize; - int fProcessorWeight; - int fProcessorQueueSize; + uint ProcessorThreads() const { return highPriorityThreads + medPriorityThreads + lowPriorityThreads; } + protected: + + private: + /** @brief the thread pool used to listen for + * incoming primitive commands + */ + threadpool::ThreadPool fServerpool; + + /** @brief the thread pool used to process + * primitive commands + */ + boost::shared_ptr fProcessorPool; + + int fServerThreads; + int fServerQueueSize; + int fProcessorWeight; + int fProcessorQueueSize; int fMaxBlocksPerRead; int fReadAheadBlocks; bool fRotatingDestination; bool fPTTrace; double fPrefetchThreshold; + bool fMulticast; + bool fMulticastloop; uint64_t fPMSmallSide; - }; + }; } // namespace primitiveprocessor diff --git a/primitives/primproc/primproc.cpp b/primitives/primproc/primproc.cpp index d2f37b0c..e31b070a 100644 --- a/primitives/primproc/primproc.cpp +++ b/primitives/primproc/primproc.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: primproc.cpp 2147 2013-08-14 20:44:44Z bwilkinson $ + * $Id: primproc.cpp 2124 2013-07-08 19:47:42Z bpaul $ * * ***********************************************************************/ @@ -55,7 +55,7 @@ using namespace logging; #include "primproc.h" #include "primitiveserver.h" -#include "MonitorProcMem.h" +#include "monitorprocmem.h" #include "pp_logger.h" #include "umsocketselector.h" using namespace primitiveprocessor; @@ -65,35 +65,41 @@ using namespace oam; #include "utils_utf8.h" -#include "IDBPolicy.h" -using namespace idbdatafile; - -#include "cgroupconfigurator.h" - namespace primitiveprocessor { -extern uint32_t BPPCount; -extern uint32_t blocksReadAhead; -extern uint32_t defaultBufferSize; -extern uint32_t connectionsPerUM; -extern uint32_t highPriorityThreads; -extern uint32_t medPriorityThreads; -extern uint32_t lowPriorityThreads; +extern uint BPPCount; +extern uint blocksReadAhead; +extern uint defaultBufferSize; +extern uint connectionsPerUM; +extern uint highPriorityThreads; +extern uint medPriorityThreads; +extern uint lowPriorityThreads; extern int directIOFlag; -extern int noVB; DebugLevel gDebugLevel; Logger* mlp; +UDFFcnMap_t UDFFcnMap; string systemLang; bool utf8 = false; +#ifdef _MSC_VER +CRITICAL_SECTION preadCSObject; +#else +//#define IDB_COMP_POC_DEBUG +#ifdef IDB_COMP_POC_DEBUG +boost::mutex compDebugMutex; +#endif +#endif + bool isDebug( const DebugLevel level ) { - return level <= gDebugLevel; + return level <= gDebugLevel; } +extern void loadUDFs(); + } namespace @@ -101,29 +107,29 @@ namespace int toInt(const string& val) { - if (val.length() == 0) - return -1; - return static_cast(Config::fromText(val)); + if (val.length() == 0) + return -1; + return static_cast(Config::fromText(val)); } void setupSignalHandlers() { #ifndef _MSC_VER - signal(SIGHUP, SIG_IGN); + signal(SIGHUP, SIG_IGN); - struct sigaction ign; + struct sigaction ign; - memset(&ign, 0, sizeof(ign)); - ign.sa_handler = SIG_IGN; - sigaction(SIGPIPE, &ign, 0); + memset(&ign, 0, sizeof(ign)); + ign.sa_handler = SIG_IGN; + sigaction(SIGPIPE, &ign, 0); - memset(&ign, 0, sizeof(ign)); - ign.sa_handler = SIG_IGN; - sigaction(SIGUSR1, &ign, 0); + memset(&ign, 0, sizeof(ign)); + ign.sa_handler = SIG_IGN; + sigaction(SIGUSR1, &ign, 0); - memset(&ign, 0, sizeof(ign)); - ign.sa_handler = SIG_IGN; - sigaction(SIGUSR2, &ign, 0); + memset(&ign, 0, sizeof(ign)); + ign.sa_handler = SIG_IGN; + sigaction(SIGUSR2, &ign, 0); sigset_t sigset; sigemptyset(&sigset); @@ -131,42 +137,41 @@ void setupSignalHandlers() sigaddset(&sigset, SIGUSR1); sigaddset(&sigset, SIGUSR2); sigprocmask(SIG_BLOCK, &sigset, 0); - #endif } void setupCwd(Config* cf) { - string workdir = cf->getConfig("SystemConfig", "WorkingDir"); - if (workdir.length() == 0) - workdir = "."; - (void)chdir(workdir.c_str()); - if (access(".", W_OK) != 0) - (void)chdir("/tmp"); + string workdir = cf->getConfig("SystemConfig", "WorkingDir"); + if (workdir.length() == 0) + workdir = "."; + (void)chdir(workdir.c_str()); + if (access(".", W_OK) != 0) + (void)chdir("/tmp"); } int setupResources() { #ifndef _MSC_VER - struct rlimit rlim; - - if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { - return -1; - } - rlim.rlim_cur = rlim.rlim_max = 65536; - if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { - return -2; - } - - if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { - return -3; - } - - if (rlim.rlim_cur != 65536) { - return -4; - } + struct rlimit rlim; + + if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { + return -1; + } + rlim.rlim_cur = rlim.rlim_max = 65536; + if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { + return -2; + } + + if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { + return -3; + } + + if (rlim.rlim_cur != 65536) { + return -4; + } #endif - return 0; + return 0; } #ifdef QSIZE_DEBUG @@ -185,24 +190,24 @@ class QszMonThd { for (;;) { - uint32_t qd = fPsp->getProcessorThreadPool()->getWaiting(); - if (fQszLog) + uint qd = fPsp->getProcessorThreadPool()->getWaiting(); + if (fQszLog) { // Get a timestamp for output. struct tm tm; struct timeval tv; - + gettimeofday(&tv, 0); localtime_r(&tv.tv_sec, &tm); - + ostringstream oss; oss << setfill('0') - << setw(2) << tm.tm_hour << ':' - << setw(2) << tm.tm_min << ':' - << setw(2) << tm.tm_sec - << '.' - << setw(4) << tv.tv_usec/100 - ; + << setw(2) << tm.tm_hour << ':' + << setw(2) << tm.tm_min << ':' + << setw(2) << tm.tm_sec + << '.' + << setw(4) << tv.tv_usec/100 + ; *fQszLog << oss.str() << ' ' << qd << endl; } @@ -259,9 +264,10 @@ void* waitForSIGUSR1(void* p) BRPp[i]->formatLRUList(out); out << "###" << endl; } - } else if (rec_sig == SIGUSR2) + } else + if (rec_sig == SIGUSR2) { - // is reporting currently on? + // is reporting currently on? rpt_state = BRPp[0]->ReportingFrequency(); if (rpt_state>0) rpt_state=0; // turn reporting off @@ -277,15 +283,50 @@ void* waitForSIGUSR1(void* p) } #endif +int getNumCores() +{ +#ifdef _MSC_VER + SYSTEM_INFO siSysInfo; + GetSystemInfo(&siSysInfo); + return siSysInfo.dwNumberOfProcessors; +#else + ifstream cpuinfo("/proc/cpuinfo"); + + if (!cpuinfo.good()) + return -1; + + int nc = 0; + + regex re("Processor\\s*:\\s*[0-9]+", regex::normal|regex::icase); + + string line; + + getline(cpuinfo, line); + + unsigned i = 0; + while (i < 10000 && cpuinfo.good() && !cpuinfo.eof()) + { + if (regex_match(line, re)) + nc++; + + getline(cpuinfo, line); + + ++i; + } + + return nc; +#endif +} + } int main(int argc, char* argv[]) { // get and set locale language systemLang = funcexp::utf8::idb_setlocale(); - if ( systemLang != "en_US.UTF-8" && - systemLang.find("UTF") != string::npos ) - utf8 = true; + if ( systemLang != "en_US.UTF-8" && + systemLang.find("UTF") != string::npos ) + utf8 = true; Config* cf = Config::makeConfig(); @@ -325,12 +366,13 @@ int main(int argc, char* argv[]) uint64_t extentRows = 8*1024*1024; uint64_t MaxExtentSize = 0; double prefetchThreshold; + bool multicast = false; + bool multicastloop = false; uint64_t PMSmallSide = 67108864; BPPCount = 16; int numCores = -1; int configNumCores = -1; - uint32_t highPriorityPercentage, medPriorityPercentage, lowPriorityPercentage; - utils::CGroupConfigurator cg; + uint highPriorityPercentage, medPriorityPercentage, lowPriorityPercentage; gDebugLevel = primitiveprocessor::NONE; @@ -401,12 +443,11 @@ int main(int argc, char* argv[]) // responses to ExeMgr and vice versa, if we rotated socket dest. temp = toInt(cf->getConfig("Installation", "ServerTypeInstall")); if ((temp == oam::INSTALL_COMBINE_DM_UM_PM) || - (temp == oam::INSTALL_COMBINE_PM_UM)) + (temp == oam::INSTALL_COMBINE_PM_UM)) rotatingDestination = false; } - string strBlockPct = cf->getConfig(dbbc, "NumBlocksPct"); - temp = atoi(strBlockPct.c_str()); + temp = toInt(cf->getConfig(dbbc, "NumBlocksPct")); if (temp > 0) BRPBlocksPct = temp; @@ -427,8 +468,7 @@ int main(int argc, char* argv[]) #else // _SC_PHYS_PAGES is in 4KB units. Dividing by 200 converts to 8KB and gets ready to work in pct // _SC_PHYS_PAGES should always be >> 200 so we shouldn't see a total loss of precision - //BRPBlocks = sysconf(_SC_PHYS_PAGES) / 200 * BRPBlocksPct; - BRPBlocks = ((BRPBlocksPct/100.0) * (double) cg.getTotalMemory()) / 8192; + BRPBlocks = sysconf(_SC_PHYS_PAGES) / 200 * BRPBlocksPct; #endif #if 0 temp = toInt(cf->getConfig(dbbc, "NumThreads")); @@ -443,8 +483,8 @@ int main(int argc, char* argv[]) if (temp > 0) deleteBlocks = temp; - if ((uint32_t)(.01 * BRPBlocks) < deleteBlocks) - deleteBlocks = (uint32_t)(.01 * BRPBlocks); + if ((uint)(.01 * BRPBlocks) < deleteBlocks) + deleteBlocks = (uint)(.01 * BRPBlocks); temp = toInt(cf->getConfig(primitiveServers, "ColScanBufferSizeBlocks")); if (temp > (int) MaxReadAheadSz || temp < 1) @@ -459,7 +499,7 @@ int main(int argc, char* argv[]) { //make sure we've got an integral factor of extent size for (; (MaxExtentSize%temp)!=0; ++temp); - blocksReadAhead=temp; + blocksReadAhead=temp; } temp = toInt(cf->getConfig(primitiveServers, "PTTrace")); @@ -469,7 +509,7 @@ int main(int argc, char* argv[]) temp = toInt(cf->getConfig(primitiveServers, "PrefetchThreshold")); if (temp < 0 || temp > 100) prefetchThreshold = 0; - else + else prefetchThreshold = temp/100.0; int maxPct = 0; //disable by default @@ -478,14 +518,13 @@ int main(int argc, char* argv[]) maxPct = temp; // @bug4507, configurable pm aggregation AggregationMemoryCheck - // We could use this same mechanism for other growing buffers. int aggPct = 95; - temp = toInt(cf->getConfig("SystemConfig", "MemoryCheckPercent")); + temp = toInt(cf->getConfig(primitiveServers, "AggregationMemoryCheck")); if (temp >= 0) aggPct = temp; //...Start the thread to monitor our memory usage - new boost::thread(utils::MonitorProcMem(maxPct, aggPct, 28)); + new boost::thread(primitiveprocessor::MonitorProcMem(maxPct, aggPct, mlp)); // config file priority is 40..1 (highest..lowest) string sPriority = cf->getConfig(primitiveServers, "Priority"); @@ -515,6 +554,19 @@ int main(int argc, char* argv[]) rotatingDestination = false; } + strVal = cf->getConfig(primitiveServers, "Multicast"); + if ((strVal == "y") || (strVal == "Y")) + multicast = true; + if (multicast) + { + strVal = cf->getConfig(primitiveServers, "MulticastLoop"); + if ((strVal == "y") || (strVal == "Y")) + multicastloop = true; + uint64_t tmp = cf->uFromText(cf->getConfig("HashJoin", "PmMaxMemorySmallSide")); + if (tmp) + PMSmallSide = tmp; + } + //See if we want to override the calculated #cores temp = toInt(cf->getConfig(primitiveServers, "NumCores")); if (temp > 0) @@ -523,9 +575,8 @@ int main(int argc, char* argv[]) if (configNumCores <= 0) { //count the actual #cores - - numCores = cg.getNumCores(); - if (numCores == 0) + numCores = getNumCores(); + if (numCores <= 0) numCores = 8; } else @@ -542,20 +593,20 @@ int main(int argc, char* argv[]) // the default is ~10% low, 30% medium, 60% high, (where 2*cores = 100%) if (highPriorityPercentage == 0 && medPriorityPercentage == 0 && - lowPriorityPercentage == 0) { + lowPriorityPercentage == 0) { lowPriorityThreads = max(1, (2*numCores)/10); medPriorityThreads = max(1, (2*numCores)/3); highPriorityThreads = (2 * numCores) - lowPriorityThreads - medPriorityThreads; } else { - uint32_t totalThreads = (uint32_t) ((lowPriorityPercentage + medPriorityPercentage + - highPriorityPercentage) / 100.0 * (2*numCores)); + uint totalThreads = (uint) ((lowPriorityPercentage + medPriorityPercentage + + highPriorityPercentage) / 100.0 * (2*numCores)); if (totalThreads == 0) totalThreads = 1; - lowPriorityThreads = (uint32_t) (lowPriorityPercentage/100.0 * (2*numCores)); - medPriorityThreads = (uint32_t) (medPriorityPercentage/100.0 * (2*numCores)); + lowPriorityThreads = (uint) (lowPriorityPercentage/100.0 * (2*numCores)); + medPriorityThreads = (uint) (medPriorityPercentage/100.0 * (2*numCores)); highPriorityThreads = totalThreads - lowPriorityThreads - medPriorityThreads; } @@ -574,26 +625,24 @@ int main(int argc, char* argv[]) // @bug4598, switch for O_DIRECT to support gluster fs. // directIOFlag == O_DIRECT, by default strVal = cf->getConfig(primitiveServers, "DirectIO"); - if ((strVal == "n") || (strVal == "N")) + if ((strVal == "n") || (strVal == "N")) directIOFlag = 0; #endif - IDBPolicy::configIDBPolicy(); - - // no versionbuffer if using HDFS for performance reason - if (IDBPolicy::useHdfs()) - noVB = 1; - + loadUDFs(); +#ifdef _MSC_VER + InitializeCriticalSection(&preadCSObject); +#endif cout << "Starting PrimitiveServer: st = " << serverThreads << ", sq = " << serverQueueSize << - ", pw = " << processorWeight << ", pq = " << processorQueueSize << - ", nb = " << BRPBlocks << ", nt = " << BRPThreads << ", nc = " << cacheCount << - ", ra = " << blocksReadAhead << ", db = " << deleteBlocks << ", mb = " << maxBlocksPerRead << - ", rd = " << rotatingDestination << ", tr = " << PTTrace << - ", ss = " << PMSmallSide << ", bp = " << BPPCount << endl; + ", pw = " << processorWeight << ", pq = " << processorQueueSize << + ", nb = " << BRPBlocks << ", nt = " << BRPThreads << ", nc = " << cacheCount << + ", ra = " << blocksReadAhead << ", db = " << deleteBlocks << ", mb = " << maxBlocksPerRead << + ", rd = " << rotatingDestination << ", tr = " << PTTrace << ", mc = " << boolalpha << multicast << + ", ml = " << multicastloop << ", ss = " << PMSmallSide << ", bp = " << BPPCount << endl; PrimitiveServer server(serverThreads, serverQueueSize, processorWeight, processorQueueSize, - rotatingDestination, BRPBlocks, BRPThreads, cacheCount, maxBlocksPerRead, blocksReadAhead, - deleteBlocks, PTTrace, prefetchThreshold, PMSmallSide); + rotatingDestination, BRPBlocks, BRPThreads, cacheCount, maxBlocksPerRead, blocksReadAhead, + deleteBlocks, PTTrace, prefetchThreshold, multicast, multicastloop, PMSmallSide); #ifdef QSIZE_DEBUG thread* qszMonThd; diff --git a/primitives/primproc/primproc.h b/primitives/primproc/primproc.h index 52e31676..52df7854 100644 --- a/primitives/primproc/primproc.h +++ b/primitives/primproc/primproc.h @@ -17,7 +17,7 @@ /****************************************************************************************** * -* $Id: primproc.h 2035 2013-01-21 14:12:19Z rdempsey $ +* $Id: primproc.h 1855 2012-04-04 18:20:09Z rdempsey $ * ******************************************************************************************/ /** @@ -40,6 +40,10 @@ namespace primitiveprocessor { +typedef int64_t (*UDFFcnPtr_t)(int64_t); +typedef std::map UDFFcnMap_t; +extern UDFFcnMap_t UDFFcnMap; + #define SUMMARY_INFO( message ) \ if ( isDebug(SUMMARY) ) \ { \ diff --git a/primitives/primproc/pseudocc.cpp b/primitives/primproc/pseudocc.cpp deleted file mode 100644 index 4d76d0d3..00000000 --- a/primitives/primproc/pseudocc.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - - -#include "bpp.h" -#include "pseudocolumn.h" - -using namespace std; -using namespace execplan; - -namespace primitiveprocessor { - -PseudoCC::PseudoCC() : ColumnCommand() -{ -} - -PseudoCC::~PseudoCC() -{ -} - -SCommand PseudoCC::duplicate() -{ - SCommand ret; - PseudoCC *pseudo; - - pseudo = new PseudoCC(); - ret.reset(pseudo); - pseudo->function = function; - pseudo->valueFromUM = valueFromUM; - ColumnCommand::duplicate(pseudo); - return ret; -} - -void PseudoCC::createCommand(messageqcpp::ByteStream &bs) -{ - bs.advance(1); - bs >> function; - ColumnCommand::createCommand(bs); -} - -void PseudoCC::resetCommand(messageqcpp::ByteStream &bs) -{ - if (function == PSEUDO_EXTENTMAX || function == PSEUDO_EXTENTMIN || function == PSEUDO_EXTENTID) - bs >> valueFromUM; - ColumnCommand::resetCommand(bs); -} - -#ifdef __GNUC__ -// The "official" GCC version for InfiniDB is 4.5.3. This flag breaks at least 4.4.3 & 4.4.5, -// so just don't do it for anything younger than 4.5.0. -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -__attribute__((optimize("no-tree-vectorize"))) -#endif -#endif - -void PseudoCC::loadData() -{ - switch (function) { - case PSEUDO_PM: - switch(colType.colWidth) { - case 1: - loadPMNumber(); - break; - case 2: - loadPMNumber(); - break; - case 4: - loadPMNumber(); - break; - case 8: - loadPMNumber(); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - case PSEUDO_EXTENTRELATIVERID: - switch(colType.colWidth) { - case 1: - loadRIDs(); - break; - case 2: - loadRIDs(); - break; - case 4: - loadRIDs(); - break; - case 8: - loadRIDs(); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - case PSEUDO_SEGMENT: - switch(colType.colWidth) { - case 1: - loadSegmentNum(); - break; - case 2: - loadSegmentNum(); - break; - case 4: - loadSegmentNum(); - break; - case 8: - loadSegmentNum(); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - case PSEUDO_SEGMENTDIR: - switch(colType.colWidth) { - case 1: - loadPartitionNum(); - break; - case 2: - loadPartitionNum(); - break; - case 4: - loadPartitionNum(); - break; - case 8: - loadPartitionNum(); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - case PSEUDO_BLOCKID: - switch(colType.colWidth) { - case 1: - loadLBID(); - break; - case 2: - loadLBID(); - break; - case 4: - loadLBID(); - break; - case 8: - loadLBID(); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - case PSEUDO_DBROOT: - switch(colType.colWidth) { - case 1: - loadDBRootNum(); - break; - case 2: - loadDBRootNum(); - break; - case 4: - loadDBRootNum(); - break; - case 8: - loadDBRootNum(); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - /* cases where the value to use is sent from the UM */ - case PSEUDO_EXTENTMAX: - case PSEUDO_EXTENTMIN: - case PSEUDO_EXTENTID: - switch(colType.colWidth) { - case 1: - loadSingleValue(valueFromUM); - break; - case 2: - loadSingleValue(valueFromUM); - break; - case 4: - loadSingleValue(valueFromUM); - break; - case 8: - loadSingleValue(valueFromUM); - break; - default: - cout << "PC::loadData(): bad column width" << endl; - break; - } - break; - default: - cout << "PC::loadData(): bad function" << endl; - break; - } -} - -} diff --git a/primitives/primproc/pseudocc.h b/primitives/primproc/pseudocc.h deleted file mode 100644 index 27e1f475..00000000 --- a/primitives/primproc/pseudocc.h +++ /dev/null @@ -1,127 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - - -#ifndef PSEUDOCC_H -#define PSEUDOCC_H - -#include "columncommand.h" -#include "blocksize.h" - -namespace primitiveprocessor { - -class PseudoCC : public ColumnCommand -{ -public: - PseudoCC(); - virtual ~PseudoCC(); - - virtual SCommand duplicate(); - virtual void createCommand(messageqcpp::ByteStream &); - virtual void resetCommand(messageqcpp::ByteStream &); -protected: - virtual void loadData(); - -private: - - template void loadSingleValue(W val); - template void loadPMNumber(); - template void loadRIDs(); - template void loadSegmentNum(); - template void loadDBRootNum(); - template void loadPartitionNum(); - template void loadLBID(); - - uint32_t function; - uint64_t valueFromUM; -}; - - -template -#ifdef __GNUC__ -// The "official" GCC version for InfiniDB is 4.5.3. This flag breaks at least 4.4.3 & 4.4.5, -// so just don't do it for anything younger than 4.5.0. -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -__attribute__((optimize("no-tree-vectorize"))) -#endif -#endif -void PseudoCC::loadSingleValue(W val) -{ - W *bData = (W *) bpp->blockData; - for (uint32_t i = 0; i < BLOCK_SIZE; i++) - bData[i] = val; // this breaks when using tree-vectorization - //memcpy(&bData[i], &val, sizeof(W)); // this always works -} - -template -void PseudoCC::loadPMNumber() -{ - uint32_t pmNum = oamCache->getLocalPMId(); - loadSingleValue(pmNum); -} - -/* This returns extent-relative rids */ -template -void PseudoCC::loadRIDs() -{ - uint32_t i; - uint64_t baseRid = rowgroup::getExtentRelativeRid(bpp->baseRid); - W *bData = (W *) bpp->blockData; - for (i = 0; i < BLOCK_SIZE; i++) { - //W val = baseRid + i; - //memcpy(&bData[i], &val, sizeof(W)); - bData[i] = baseRid + i; // breaks with tree-vectorization - } -} - -template -void PseudoCC::loadSegmentNum() -{ - uint16_t segNum; - rowgroup::getLocationFromRid(bpp->baseRid, NULL, &segNum, NULL, NULL); - loadSingleValue(segNum); -} - -template -void PseudoCC::loadPartitionNum() -{ - uint32_t partNum; - rowgroup::getLocationFromRid(bpp->baseRid, &partNum, NULL, NULL, NULL); - loadSingleValue(partNum); -} - -template -void PseudoCC::loadDBRootNum() -{ - loadSingleValue(bpp->dbRoot); -} - -template -void PseudoCC::loadLBID() -{ - uint32_t i; - W *bData = (W *) bpp->blockData; - for (i = 0; i < BLOCK_SIZE; i++) { - //W val = ColumnCommand::getLBID() + (i * sizeof(W)) / BLOCK_SIZE; - //memcpy(&bData[i], &val, sizeof(W)); - bData[i] = ColumnCommand::getLBID() + (i * sizeof(W)) / BLOCK_SIZE; // breaks with tree-vectorization - } -} - -} - -#endif // PseudoCC_H diff --git a/primitives/primproc/resource.h b/primitives/primproc/resource.h deleted file mode 100644 index 5c5a9d03..00000000 --- a/primitives/primproc/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by PrimProc.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/primitives/primproc/rowaggregation.cpp b/primitives/primproc/rowaggregation.cpp new file mode 120000 index 00000000..ca602a15 --- /dev/null +++ b/primitives/primproc/rowaggregation.cpp @@ -0,0 +1 @@ +../../utils/rowgroup/rowaggregation.cpp \ No newline at end of file diff --git a/primitives/primproc/rowaggregation.h b/primitives/primproc/rowaggregation.h new file mode 120000 index 00000000..453e7462 --- /dev/null +++ b/primitives/primproc/rowaggregation.h @@ -0,0 +1 @@ +../../utils/rowgroup/rowaggregation.h \ No newline at end of file diff --git a/primitives/primproc/rowgroup.cpp b/primitives/primproc/rowgroup.cpp new file mode 120000 index 00000000..fc8147b9 --- /dev/null +++ b/primitives/primproc/rowgroup.cpp @@ -0,0 +1 @@ +../../utils/rowgroup/rowgroup.cpp \ No newline at end of file diff --git a/primitives/primproc/rowgroup.h b/primitives/primproc/rowgroup.h new file mode 120000 index 00000000..7ee1a7d5 --- /dev/null +++ b/primitives/primproc/rowgroup.h @@ -0,0 +1 @@ +../../utils/rowgroup/rowgroup.h \ No newline at end of file diff --git a/primitives/primproc/rtscommand.cpp b/primitives/primproc/rtscommand.cpp index 471f4c0b..f594d283 100644 --- a/primitives/primproc/rtscommand.cpp +++ b/primitives/primproc/rtscommand.cpp @@ -16,10 +16,10 @@ MA 02110-1301, USA. */ // -// $Id: rtscommand.cpp 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: rtscommand.cpp 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Implementation: rtscommand // -// Description: +// Description: // // // Author: Patrick , (C) 2008 @@ -56,7 +56,7 @@ void RTSCommand::execute() void RTSCommand::project() { - uint32_t i; + uint i; if (passThru) { // if (bpp->absRids.get() == NULL) @@ -72,19 +72,19 @@ void RTSCommand::project() } else { int64_t tmpValues[LOGICAL_BLOCK_RIDS]; - uint32_t old_rc = bpp->ridCount; + uint old_rc = bpp->ridCount; if (bpp->absRids.get() == NULL) bpp->absRids.reset(new uint64_t[LOGICAL_BLOCK_RIDS]); col.execute(tmpValues); - + if (old_rc != bpp->ridCount) { ostringstream os; os << __FILE__ << " (token column) error on projection for oid " << col.getOID() << " lbid " << col.getLBID(); os << ": input rids " << old_rc; os << ", output rids " << bpp->ridCount << endl; - if (bpp->sessionID & 0x80000000) + if (bpp->sessionID & 0x80000000) throw NeedToRestartJob(os.str()); else { throw PrimitiveColumnProjectResultExcept(os.str()); @@ -95,9 +95,9 @@ void RTSCommand::project() } } -void RTSCommand::projectIntoRowGroup(RowGroup &rg, uint32_t colNum) +void RTSCommand::projectIntoRowGroup(RowGroup &rg, uint colNum) { - uint32_t i; + uint i; if (passThru) { if (absNull) //@bug 1003. Always need to remake absRids @@ -110,7 +110,7 @@ void RTSCommand::projectIntoRowGroup(RowGroup &rg, uint32_t colNum) } else { int64_t tmpValues[LOGICAL_BLOCK_RIDS]; - uint32_t old_rc = bpp->ridCount; + uint old_rc = bpp->ridCount; if (bpp->absRids.get() == NULL) bpp->absRids.reset(new uint64_t[LOGICAL_BLOCK_RIDS]); @@ -125,7 +125,7 @@ void RTSCommand::projectIntoRowGroup(RowGroup &rg, uint32_t colNum) os << ", output rids " << bpp->ridCount << endl; if (bpp->sessionID & 0x80000000) throw NeedToRestartJob(os.str()); - else + else throw PrimitiveColumnProjectResultExcept(os.str()); } @@ -206,7 +206,7 @@ bool RTSCommand::operator!=(const RTSCommand &r) const return !(*this == r); } -void RTSCommand::getLBIDList(uint32_t loopCount, vector *lbids) +void RTSCommand::getLBIDList(uint loopCount, vector *lbids) { dict.getLBIDList(loopCount, lbids); if (!passThru) diff --git a/primitives/primproc/rtscommand.h b/primitives/primproc/rtscommand.h index 40abbead..d67415a1 100644 --- a/primitives/primproc/rtscommand.h +++ b/primitives/primproc/rtscommand.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ // -// $Id: rtscommand.h 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: rtscommand.h 1855 2012-04-04 18:20:09Z rdempsey $ // C++ Interface: rtscommand // // Description: @@ -45,7 +45,7 @@ class RTSCommand : public Command void execute(); void project(); - void projectIntoRowGroup(rowgroup::RowGroup &rg, uint32_t col); + void projectIntoRowGroup(rowgroup::RowGroup &rg, uint col); uint64_t getLBID(); void nextLBID(); void createCommand(messageqcpp::ByteStream &); @@ -60,7 +60,7 @@ class RTSCommand : public Command void prep(int8_t outputType, bool makeAbsRids); uint8_t isPassThru() { return passThru; } void setAbsNull(bool a = true) { absNull = a; } - void getLBIDList(uint32_t loopCount, std::vector *lbids); + void getLBIDList(uint loopCount, std::vector *lbids); //TODO: do we need to reference either col or dict? int getCompType() const { return dict.getCompType(); } diff --git a/primitives/primproc/tdriver.cpp b/primitives/primproc/tdriver.cpp index fd4c4ccc..7d0ecdb0 100644 --- a/primitives/primproc/tdriver.cpp +++ b/primitives/primproc/tdriver.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: tdriver.cpp 2035 2013-01-21 14:12:19Z rdempsey $ + * $Id: tdriver.cpp 1855 2012-04-04 18:20:09Z rdempsey $ * * ***********************************************************************/ diff --git a/primitives/primproc/udf.cpp b/primitives/primproc/udf.cpp index 0d75a481..5cf2252f 100644 --- a/primitives/primproc/udf.cpp +++ b/primitives/primproc/udf.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: udf.cpp 2035 2013-01-21 14:12:19Z rdempsey $ +// $Id: udf.cpp 1855 2012-04-04 18:20:09Z rdempsey $ #ifndef _MSC_VER #include diff --git a/primitives/primproc/umsocketselector.h b/primitives/primproc/umsocketselector.h index 40d5d942..cc9bf74c 100644 --- a/primitives/primproc/umsocketselector.h +++ b/primitives/primproc/umsocketselector.h @@ -38,7 +38,7 @@ #include #include #include -typedef uint32_t in_addr_t; +typedef boost::uint32_t in_addr_t; #else #include #endif diff --git a/primitives/udf/Makefile.sdk b/primitives/udf/Makefile.sdk new file mode 100644 index 00000000..5f3bc2bc --- /dev/null +++ b/primitives/udf/Makefile.sdk @@ -0,0 +1,35 @@ +#****************************************************************************************** +# $Id: Makefile.sdk 1589 2011-02-10 14:23:09Z rdempsey $ +# +#*****************************************************************************************/ +.PHONY: clean + +PROGRAM=libcaludf.so +VERSION=1.0.0 +LIBRARY=$(PROGRAM).$(VERSION) + +CPPFLAGS= +CXXFLAGS+=-Wall -fpic + +SRCS=caludf.cpp + +OBJS=$(SRCS:.cpp=.o) + +$(LIBRARY): $(OBJS) + $(LINK.cpp) -shared -o $(LIBRARY) $(OBJS) + rm -f $(PROGRAM) + ln -s $(LIBRARY) $(PROGRAM) + +clean: + rm -rf $(PROGRAM) $(LIBRARY) $(OBJS) \ + *~ *.o *.d* *-gcov* *.gcov \ + html config.tag + +%.d: %.cpp + @set -e; rm -f $@; \ + $(CC) -MM $(CPPFLAGS) $< > $@.$$$$; \ + sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ + rm -f $@.$$$$ + +-include $(SRCS:.cpp=.d) + diff --git a/primitives/udf/caludf.cpp b/primitives/udf/caludf.cpp new file mode 100644 index 00000000..b8c7565a --- /dev/null +++ b/primitives/udf/caludf.cpp @@ -0,0 +1,77 @@ +// $Id: caludf.cpp 866 2009-02-23 14:57:13Z rdempsey $ + +#include +#include +#include +using namespace std; + +#include "caludf.h" + +extern "C" +{ + +int64_t cpfunc1(int64_t in) +{ + int64_t out = in + 1; + return out; +} + +int64_t cpfunc2(int64_t in) +{ + int64_t out = 0; + union + { + Date d; + uint32_t i; + } u; + u.i = in; + u.d.year++; + out = u.i; + return out; +} + +int64_t cpfunc3(int64_t in) +{ + int64_t out = in * 2; + return out; +} + +int64_t cpfunc4(int64_t in) +{ + int64_t out = in * 3; + return out; +} + +int64_t cpfunc5(int64_t in) +{ + int64_t out = abs(in); + return out; +} + +int64_t cpfunc6(int64_t in) +{ + int64_t out = log(in); + return out; +} + +int64_t cpfunc7(int64_t in) +{ + int64_t out = exp(in); + return out; +} + +int64_t cpfunc8(int64_t in) +{ + int64_t out = -in; + return out; +} + +int64_t cpfunc9(int64_t in) +{ + int64_t out = 0; + return out; +} + +} +// vim:ts=4 sw=4: + diff --git a/primitives/udf/caludf.h b/primitives/udf/caludf.h new file mode 100644 index 00000000..22738aae --- /dev/null +++ b/primitives/udf/caludf.h @@ -0,0 +1,29 @@ +// $Id: caludf.h 866 2009-02-23 14:57:13Z rdempsey $ + +/** @file */ + +#ifndef CALUDF_H__ +#define CALUDF_H__ + +struct Date +{ + unsigned spare : 6; + unsigned day : 6; + unsigned month : 4; + unsigned year : 16; +}; + +struct DateTime +{ + unsigned msecond : 20; + unsigned second : 6; + unsigned minute : 6; + unsigned hour : 6; + unsigned day : 6; + unsigned month : 4; + unsigned year : 16; +}; + +#endif +// vim:ts=4 sw=4: + diff --git a/procmgr/Makefile.am b/procmgr/Makefile.am index 96d95722..cf0557a6 100644 --- a/procmgr/Makefile.am +++ b/procmgr/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -25,7 +8,7 @@ AM_LDFLAGS = $(idb_ldflags) bin_PROGRAMS = ProcMgr ProcMgr_SOURCES = main.cpp processmanager.cpp ProcMgr_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -ProcMgr_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lcacheutils $(AM_LDFLAGS) +ProcMgr_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) test: diff --git a/procmgr/Makefile.in b/procmgr/Makefile.in deleted file mode 100644 index 4bad5608..00000000 --- a/procmgr/Makefile.in +++ /dev/null @@ -1,545 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = .. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = ProcMgr$(EXEEXT) -subdir = procmgr -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_ProcMgr_OBJECTS = ProcMgr-main.$(OBJEXT) \ - ProcMgr-processmanager.$(OBJEXT) -ProcMgr_OBJECTS = $(am_ProcMgr_OBJECTS) -ProcMgr_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(ProcMgr_SOURCES) -DIST_SOURCES = $(ProcMgr_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -ProcMgr_SOURCES = main.cpp processmanager.cpp -ProcMgr_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -ProcMgr_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lcacheutils $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu procmgr/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu procmgr/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -ProcMgr$(EXEEXT): $(ProcMgr_OBJECTS) $(ProcMgr_DEPENDENCIES) - @rm -f ProcMgr$(EXEEXT) - $(CXXLINK) $(ProcMgr_LDFLAGS) $(ProcMgr_OBJECTS) $(ProcMgr_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ProcMgr-main.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ProcMgr-processmanager.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -ProcMgr-main.o: main.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMgr-main.o -MD -MP -MF "$(DEPDIR)/ProcMgr-main.Tpo" -c -o ProcMgr-main.o `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMgr-main.Tpo" "$(DEPDIR)/ProcMgr-main.Po"; else rm -f "$(DEPDIR)/ProcMgr-main.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='ProcMgr-main.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMgr-main.o `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp - -ProcMgr-main.obj: main.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMgr-main.obj -MD -MP -MF "$(DEPDIR)/ProcMgr-main.Tpo" -c -o ProcMgr-main.obj `if test -f 'main.cpp'; then $(CYGPATH_W) 'main.cpp'; else $(CYGPATH_W) '$(srcdir)/main.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMgr-main.Tpo" "$(DEPDIR)/ProcMgr-main.Po"; else rm -f "$(DEPDIR)/ProcMgr-main.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='ProcMgr-main.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMgr-main.obj `if test -f 'main.cpp'; then $(CYGPATH_W) 'main.cpp'; else $(CYGPATH_W) '$(srcdir)/main.cpp'; fi` - -ProcMgr-processmanager.o: processmanager.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMgr-processmanager.o -MD -MP -MF "$(DEPDIR)/ProcMgr-processmanager.Tpo" -c -o ProcMgr-processmanager.o `test -f 'processmanager.cpp' || echo '$(srcdir)/'`processmanager.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMgr-processmanager.Tpo" "$(DEPDIR)/ProcMgr-processmanager.Po"; else rm -f "$(DEPDIR)/ProcMgr-processmanager.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='processmanager.cpp' object='ProcMgr-processmanager.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMgr-processmanager.o `test -f 'processmanager.cpp' || echo '$(srcdir)/'`processmanager.cpp - -ProcMgr-processmanager.obj: processmanager.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMgr-processmanager.obj -MD -MP -MF "$(DEPDIR)/ProcMgr-processmanager.Tpo" -c -o ProcMgr-processmanager.obj `if test -f 'processmanager.cpp'; then $(CYGPATH_W) 'processmanager.cpp'; else $(CYGPATH_W) '$(srcdir)/processmanager.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMgr-processmanager.Tpo" "$(DEPDIR)/ProcMgr-processmanager.Po"; else rm -f "$(DEPDIR)/ProcMgr-processmanager.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='processmanager.cpp' object='ProcMgr-processmanager.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMgr_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMgr-processmanager.obj `if test -f 'processmanager.cpp'; then $(CYGPATH_W) 'processmanager.cpp'; else $(CYGPATH_W) '$(srcdir)/processmanager.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/procmgr/main.cpp b/procmgr/main.cpp index 0359fd33..8152fed0 100644 --- a/procmgr/main.cpp +++ b/procmgr/main.cpp @@ -1,30 +1,11 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /***************************************************************************************** -* $Id: main.cpp 2203 2013-07-08 16:50:51Z bpaul $ +* $Id: main.cpp 2205 2013-07-08 20:14:08Z bpaul $ * *****************************************************************************************/ #include -#include - #include "processmanager.h" #include "installdir.h" @@ -45,18 +26,11 @@ bool runCold = false; string systemName = "system"; string iface_name; string cloud; -bool amazon = false; string PMInstanceType; string UMInstanceType; string GlusterConfig = "n"; bool rootUser = true; string USER = "root"; -bool HDFS = false; -string localHostName; -string PMwithUM = "n"; - -// pushing the ACTIVE_ALARMS_FILE to all nodes every 10 seconds. -const int ACTIVE_ALARMS_PUSHING_INTERVAL = 10; typedef map moduleList; moduleList moduleInfoList; @@ -73,7 +47,6 @@ extern bool gOAMParentModuleFlag; static void messageThread(Configuration config); static void sigUser1Handler(int sig); static void startMgrProcessThread(); -static void hdfsActiveAlarmsPushingThread(); //static void pingDeviceThread(); //static void heartbeatProcessThread(); //static void heartbeatMsgThread(); @@ -105,6 +78,7 @@ int main(int argc, char **argv) if (p && *p) USER = p; + ProcessLog log; Configuration config; ProcessManager processManager(config, log); @@ -136,11 +110,10 @@ int main(int argc, char **argv) catch(...) {} //get amazon parameters - if ( cloud == "amazon-ec2" || cloud == "amazon-vpc" ) + if ( cloud == "amazon" ) { oam.getSystemConfig("PMInstanceType", PMInstanceType); oam.getSystemConfig("UMInstanceType", UMInstanceType); - amazon = true; } //get gluster config @@ -152,26 +125,33 @@ int main(int argc, char **argv) GlusterConfig = "n"; } - //hdfs / hadoop config - string DBRootStorageType; - try { - oam.getSystemConfig( "DBRootStorageType", DBRootStorageType); - } - catch(...) {} + // get system uptime and alarm if this is a restart after module outage + if ( gOAMParentModuleFlag ) { - if ( DBRootStorageType == "hdfs" ) - HDFS = true; + oam::LicenseKeyChecker keyChecker; - //PMwithUM config - try { - oam.getSystemConfig( "PMwithUM", PMwithUM); - } - catch(...) { - PMwithUM = "n"; - } + bool keyGood = true; + try { + keyGood = keyChecker.isGood(); + } + catch(...) + { + keyGood = false; + } - // get system uptime and alarm if this is a restart after module outage - if ( gOAMParentModuleFlag ) { + if (!keyGood) + { + //set alarm + aManager.sendAlarmReport(systemName.c_str(), EE_LICENSE_EXPIRED, SET); + log.writeLog(__LINE__, "Your trial period has expired.", LOG_TYPE_CRITICAL); + + //shutdown system, this might fail if a cpimport job is running + oam.shutdownSystem(GRACEFUL, ACK_YES); + // sleep until + sleep(100); + + exit (1); + } //clear alarm aManager.sendAlarmReport(systemName.c_str(), EE_LICENSE_EXPIRED, CLEAR); @@ -204,7 +184,6 @@ int main(int argc, char **argv) oam.getSystemConfig(config.moduleName(), moduleconfig); HostConfigList::iterator pt1 = moduleconfig.hostConfigList.begin(); string localIPaddr = (*pt1).IPAddr; - localHostName = (*pt1).HostName; struct ifaddrs *addrs, *iap; struct sockaddr_in *sa; @@ -272,7 +251,7 @@ int main(int argc, char **argv) { //running active after startup //Update DBRM section of Calpont.xml processManager.updateWorkerNodeconfig(); -// processManager.distributeConfigFile("system"); + processManager.distributeConfigFile("system"); pthread_t srvThread; int status = pthread_create (&srvThread, NULL, (void*(*)(void*)) &pingDeviceThread, NULL); @@ -280,14 +259,6 @@ int main(int argc, char **argv) if ( status != 0 ) log.writeLog(__LINE__, "pingDeviceThread: pthread_create failed, return status = " + oam.itoa(status), LOG_TYPE_ERROR); - // if HDFS, create a thread to push an image of activeAlarms to HDFS filesystem - if (HDFS) { - pthread_t hdfsAlarmThread; - int status = pthread_create(&hdfsAlarmThread, NULL, (void*(*)(void*)) &hdfsActiveAlarmsPushingThread, NULL); - if ( status != 0 ) - log.writeLog(__LINE__, "hdfsActiveAlarmsPushingThread pthread_create failed, return code = " + oam.itoa(status), LOG_TYPE_ERROR); - } - sleep(5); SystemStatus systemstatus; @@ -632,13 +603,9 @@ static void startMgrProcessThread() pthread_exit(0); } - //configure the PMS settings + //configure the PMS NIC #1 processManager.updatePMSconfig(); - if (HDFS) - //distribute config file - processManager.distributeConfigFile("system"); - //now wait until all procmons are up and validate rpms on each module int status = API_SUCCESS; int k = 0; @@ -667,29 +634,6 @@ static void startMgrProcessThread() (*pt).DisableState == oam::AUTODISABLEDSTATE ) continue; - int moduleOpState; - // check module state - try{ - bool degraded; - oam.getModuleStatus(moduleName, moduleOpState, degraded); - - // if up, set to MAN_INIT - if ( HDFS && - (moduleOpState == oam::UP) ) - { - processManager.setModuleState(moduleName, oam::MAN_INIT); - } - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); - } - // Is Module's ProcMon ACTIVE and module status has been updated int opState; try { @@ -718,24 +662,50 @@ static void startMgrProcessThread() continue; } - //ProcMon ACTIVE, validate the software release and version of that module - ByteStream msg; - ByteStream::byte requestID = GETSOFTWAREINFO; - msg << requestID; + // Is Module ACTIVE + try{ + bool degraded; + oam.getModuleStatus(moduleName, opState, degraded); - string moduleSoftwareInfo = processManager.sendMsgProcMon1( moduleName, msg, requestID ); - if ( moduleSoftwareInfo == "FAILED" ) - continue; + if (opState == oam::ACTIVE || + opState == oam::MAN_OFFLINE || + opState == oam::DOWN || + opState == oam::FAILED || + opState == oam::MAN_DISABLED || + opState == oam::AUTO_DISABLED) + //skip + continue; - if ( localSoftwareInfo != moduleSoftwareInfo ) { - // module not running on same Calpont Software build as this local Director - // alarm and fail the module - log.writeLog(__LINE__, "Software Info mismatch : " + moduleName + "/" + localSoftwareInfo + "/" + moduleSoftwareInfo, LOG_TYPE_ERROR); + //validate the software release and version of that module + ByteStream msg; + ByteStream::byte requestID = GETSOFTWAREINFO; + msg << requestID; + + string moduleSoftwareInfo = processManager.sendMsgProcMon1( moduleName, msg, requestID ); + if ( moduleSoftwareInfo == "FAILED" ) { + status = API_FAILURE; + break; + } - aManager.sendAlarmReport(moduleName.c_str(), INVALID_SW_VERSION, SET); - processManager.setModuleState(moduleName, oam::FAILED); - status = API_FAILURE; - break; + if ( localSoftwareInfo != moduleSoftwareInfo ) { + // module not running on same Calpont Software build as this local Director + // alarm and fail the module + log.writeLog(__LINE__, "Software Info mismatch : " + moduleName + "/" + localSoftwareInfo + "/" + moduleSoftwareInfo, LOG_TYPE_ERROR); + + aManager.sendAlarmReport(moduleName.c_str(), INVALID_SW_VERSION, SET); + processManager.setModuleState(moduleName, oam::FAILED); + status = API_FAILURE; + break; + } + } + catch (exception& ex) + { + string error = ex.what(); + log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": " + error, LOG_TYPE_ERROR); + } + catch(...) + { + log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); } } } @@ -764,13 +734,13 @@ static void startMgrProcessThread() processManager.setSystemState(oam::FAILED); // exit thread log.writeLog(__LINE__, "startMgrProcessThread Exit with a failure, not all ProcMons ACTIVE", LOG_TYPE_CRITICAL); - log.writeLog(__LINE__, "startMgrProcessThread Exit - failure", LOG_TYPE_DEBUG); - pthread_exit(0); + system("/etc/init.d/infinidb stop"); + exit(1); } else { //distribute config file -// processManager.distributeConfigFile("system"); + processManager.distributeConfigFile("system"); if ( systemStartupOffline == "n" && status == API_SUCCESS ) { oam::DeviceNetworkList devicenetworklist; @@ -929,6 +899,33 @@ void pingDeviceThread() while (true) { + //check if license has expired + oam::LicenseKeyChecker keyChecker; + + bool keyGood = true; + try { + keyGood = keyChecker.isGood(); + } + catch(...) + { + keyGood = false; + } + + if (!keyGood) + { + //set alarm + aManager.sendAlarmReport(systemName.c_str(), EE_LICENSE_EXPIRED, SET); + + log.writeLog(__LINE__, "Your trial period has expired.", LOG_TYPE_CRITICAL); + + //shutdown system, this might fail if a cpimport job is running + oam.shutdownSystem(GRACEFUL, ACK_YES); + // sleep until + sleep(100); + + exit (1); + } + //don't peform module test if system is MAN_OFFLINE or not getting status's while(true) { @@ -948,8 +945,8 @@ void pingDeviceThread() } // Module Heartbeat period and failure count - int ModuleHeartbeatPeriod; - int ModuleHeartbeatCount; + int ModuleHeartbeatPeriod; + int ModuleHeartbeatCount; try { oam.getSystemConfig("ModuleHeartbeatPeriod", ModuleHeartbeatPeriod); @@ -1079,7 +1076,6 @@ void pingDeviceThread() // perform ping test cmd = cmdLine + ipAddr + cmdOption; rtnCode = system(cmd.c_str()); - rtnCode = WEXITSTATUS(rtnCode); } else rtnCode = 0; @@ -1216,37 +1212,30 @@ void pingDeviceThread() { log.writeLog(__LINE__, "Module alive, bring it back online: " + moduleName, LOG_TYPE_DEBUG); - string PrimaryUMModuleName = config.moduleName(); - try { - oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); - } - catch(...) {} + // skip module check if DMLProc is BUSY_INIT (rollback) + SystemProcessStatus systemprocessstatus; + ProcessStatus processstatus; bool busy = false; - for ( int retry = 0 ; retry < 20 ; retry++ ) - { - busy = false; - ProcessStatus DMLprocessstatus; - try { - oam.getProcessStatus("DMLProc", PrimaryUMModuleName, DMLprocessstatus); - - if ( DMLprocessstatus.ProcessOpState == oam::BUSY_INIT) { + try { + oam.getProcessStatus(systemprocessstatus); + + for( unsigned int i = 0 ; i < systemprocessstatus.processstatus.size(); i++) + { + if ( systemprocessstatus.processstatus[i].ProcessName == "DMLProc" && + systemprocessstatus.processstatus[i].ProcessOpState == oam::BUSY_INIT) { log.writeLog(__LINE__, "DMLProc in BUSY_INIT, skip bringing module online " + moduleName, LOG_TYPE_DEBUG); busy = true; - sleep (5); - } - else break; + } } - catch(...) - {} } + catch(...) + {} if (busy) break; - processManager.setSystemState(oam::BUSY_INIT); - processManager.reinitProcessType("cpimport"); // halt the dbrm @@ -1264,12 +1253,8 @@ void pingDeviceThread() int status; // if pm, move dbroots back to pm - if ( ( moduleName.find("pm") == 0 && !amazon ) || - ( moduleName.find("pm") == 0 && amazon && downActiveOAMModule ) ) { - - //restart to get the versionbuffer files closed so it can be unmounted - processManager.restartProcessType("WriteEngineServer"); - + if ( ( moduleName.find("pm") == 0 && cloud != "amazon" ) || + ( moduleName.find("pm") == 0 && cloud == "amazon" && downActiveOAMModule ) ) { downActiveOAMModule = false; try { log.writeLog(__LINE__, "Call autoUnMovePmDbroot", LOG_TYPE_DEBUG); @@ -1305,7 +1290,6 @@ void pingDeviceThread() //clear count moduleInfoList[moduleName] = 0; - processManager.setSystemState(oam::ACTIVE); break; } } @@ -1338,13 +1322,13 @@ void pingDeviceThread() //clear count moduleInfoList[moduleName] = 0; - processManager.setSystemState(oam::ACTIVE); break; } } //restart module processes int retry = 0; + bool stopSuccess = false; int ModuleProcMonWaitCount = 30; try{ @@ -1422,39 +1406,39 @@ void pingDeviceThread() } // next, stopmodule to start up clean - status = processManager.stopModule(moduleName, oam::FORCEFUL, false); - if ( status == oam::API_SUCCESS ) { - string newStandbyModule = processManager.getStandbyModule(); - if ( !newStandbyModule.empty() && newStandbyModule != "NONE") { - processManager.setStandbyModule(newStandbyModule); +// if (!stopSuccess) +// { + status = processManager.stopModule(moduleName, oam::FORCEFUL, false); + if ( status == oam::API_SUCCESS ) { + stopSuccess = true; + string newStandbyModule = processManager.getStandbyModule(); + if ( !newStandbyModule.empty() && newStandbyModule != "NONE") { + processManager.setStandbyModule(newStandbyModule); + } + else + { + if ( newStandbyModule == "NONE") + if ( moduleName.substr(0,MAX_MODULE_TYPE_SIZE) == "pm" ) + processManager.setStandbyModule(moduleName); + } } - else - { - if ( newStandbyModule == "NONE") - if ( moduleName.substr(0,MAX_MODULE_TYPE_SIZE) == "pm" ) - processManager.setStandbyModule(moduleName); + else { + //stop failed, retry + log.writeLog(__LINE__, "stopModule, failed will retry: " + moduleName, LOG_TYPE_DEBUG); + sleep(5); + continue; } - } - else { - //stop failed, retry - log.writeLog(__LINE__, "stopModule, failed will retry: " + moduleName, LOG_TYPE_DEBUG); - sleep(5); - continue; - } - - //call dbrm control, need to resume before start so the getdbrmfiles halt doesn't hang - oam.dbrmctl("reload"); - log.writeLog(__LINE__, "'dbrmctl reload' done", LOG_TYPE_DEBUG); - - // resume the dbrm - oam.dbrmctl("resume"); - log.writeLog(__LINE__, "'dbrmctl resume' done", LOG_TYPE_DEBUG); +// } // next, startmodule status = processManager.startModule(moduleName, oam::FORCEFUL, oam::AUTO_OFFLINE); if ( status == oam::API_SUCCESS ) break; + if ( status != oam::API_MINOR_FAILURE ) + // do another stopModule + stopSuccess = false; + log.writeLog(__LINE__, "startModule, failed will retry: " + moduleName, LOG_TYPE_DEBUG); //sleep and retry all over again @@ -1474,6 +1458,14 @@ void pingDeviceThread() processManager.restartProcessType("mysql"); } + //call dbrm control + oam.dbrmctl("reload"); + log.writeLog(__LINE__, "'dbrmctl reload' done", LOG_TYPE_DEBUG); + + // resume the dbrm + oam.dbrmctl("resume"); + log.writeLog(__LINE__, "'dbrmctl resume' done", LOG_TYPE_DEBUG); + // if a PM module was started successfully, DMLProc/DDLProc if( moduleName.find("pm") == 0 ) { processManager.restartProcessType("DDLProc"); @@ -1485,14 +1477,6 @@ void pingDeviceThread() //clear count moduleInfoList[moduleName] = 0; - - //setup MySQL Replication for started modules - log.writeLog(__LINE__, "Setup MySQL Replication for module recovering from outage", LOG_TYPE_DEBUG); - DeviceNetworkList devicenetworklist; - DeviceNetworkConfig devicenetworkconfig; - devicenetworkconfig.DeviceName = moduleName; - devicenetworklist.push_back(devicenetworkconfig); - processManager.setMySQLReplication(devicenetworklist); } else { // module failed to restart, place back in disabled state @@ -1503,8 +1487,8 @@ void pingDeviceThread() aManager.sendAlarmReport(moduleName.c_str(), MODULE_DOWN_AUTO, SET); // if pm, move dbroots back to pm - if ( ( moduleName.find("pm") == 0 && !amazon ) || - ( moduleName.find("pm") == 0 && amazon && downActiveOAMModule ) ) { + if ( ( moduleName.find("pm") == 0 && cloud != "amazon" ) || + ( moduleName.find("pm") == 0 && cloud == "amazon" && downActiveOAMModule ) ) { //move dbroots to other modules try { log.writeLog(__LINE__, "Call autoMovePmDbroot", LOG_TYPE_DEBUG); @@ -1537,7 +1521,7 @@ void pingDeviceThread() log.writeLog(__LINE__, "Module failed to auto start: " + moduleName, LOG_TYPE_CRITICAL); - if ( amazon ) + if ( cloud == "amazon" ) processManager.setSystemState(oam::FAILED); else processManager.setSystemState(oam::ACTIVE); @@ -1580,9 +1564,9 @@ void pingDeviceThread() log.writeLog(__LINE__, "'dbrmctl halt' done", LOG_TYPE_DEBUG); processManager.setSystemState(oam::BUSY_INIT); - - string cmd = "/etc/init.d/glusterd restart > /dev/null 2>&1"; - system(cmd.c_str()); +// TEST CODE +string cmd = "/etc/init.d/glusterd restart > /dev/null 2>&1"; +system(cmd.c_str()); //send notification oam.sendDeviceNotification(moduleName, MODULE_DOWN); @@ -1604,7 +1588,7 @@ void pingDeviceThread() // state = running, then instance is rebooting, monitor for recovery // state = stopped, then try starting, if fail, remove/addmodule to launch new instance // state = terminate or nothing, remove/addmodule to launch new instance - if ( amazon ) { + if ( cloud == "amazon" ) { if ( moduleName.find("um") == 0 ) { @@ -1727,11 +1711,7 @@ void pingDeviceThread() HostConfig hostconfig; devicenetworkconfig.DeviceName = moduleName; - if (cloud == "amazon-vpc") - hostconfig.IPAddr = ipAddr; - else - hostconfig.IPAddr = oam::UnassignedName; - + hostconfig.IPAddr = oam::UnassignedName; hostconfig.HostName = oam::UnassignedName; hostconfig.NicID = 1; devicenetworkconfig.hostConfigList.push_back(hostconfig); @@ -1849,8 +1829,7 @@ void pingDeviceThread() //set recycle process processManager.recycleProcess(moduleName); - - sleep(2); + processManager.setSystemState(oam::ACTIVE); } } @@ -1891,7 +1870,6 @@ void pingDeviceThread() //set recycle process processManager.recycleProcess(moduleName); - sleep(2); processManager.setSystemState(oam::ACTIVE); //check if down module was Standby OAM, if so find another one @@ -2099,7 +2077,7 @@ void pingDeviceThread() cmd = cmdLine + ipAddr + cmdOption; rtnCode = system(cmd.c_str()); - switch (WEXITSTATUS(rtnCode)){ + switch (rtnCode){ case 0: //Switch Ack ping, Check whether alarm have been issued if (extDeviceInfoList[extDeviceName] >= ModuleHeartbeatCount) @@ -2158,8 +2136,7 @@ void pingDeviceThread() { bool degraded; oam.getModuleStatus(moduleName, opState, degraded); - if (opState == oam::ACTIVE || - opState == oam::DEGRADED || + if (opState == oam::ACTIVE || opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED ) continue; @@ -2186,8 +2163,10 @@ void pingDeviceThread() catch(...) {} ProcessStatus DMLprocessstatus; + ProcessStatus DDLprocessstatus; try { oam.getProcessStatus("DMLProc", PrimaryUMModuleName, DMLprocessstatus); + oam.getProcessStatus("DDLProc", PrimaryUMModuleName, DDLprocessstatus); } catch (exception& ex) { @@ -2199,7 +2178,8 @@ void pingDeviceThread() log.writeLog(__LINE__, "EXCEPTION ERROR on getProcessStatus: Caught unknown exception!", LOG_TYPE_ERROR); } - if (DMLprocessstatus.ProcessOpState == oam::ACTIVE) { + if (DMLprocessstatus.ProcessOpState == oam::ACTIVE && + DDLprocessstatus.ProcessOpState == oam::ACTIVE) { //set the system status if a change has occurred SystemStatus systemstatus; @@ -2240,39 +2220,6 @@ void pingDeviceThread() return; } -/****************************************************************************************** -* @brief hdfsActiveAlarmsPushingThread -* -* purpose: Push an image of ActiveAlarms to HDFS for non-OAMParentModule to view. -* -******************************************************************************************/ -static void hdfsActiveAlarmsPushingThread() -{ - boost::filesystem::path filePath(ACTIVE_ALARM_FILE); - boost::filesystem::path dirPath = filePath.parent_path(); - string dirName = boost::filesystem::canonical(dirPath).string(); - - if (boost::filesystem::exists("/etc/pdsh/machines")) - { - string cpCmd = "pdcp -a -x " + localHostName + " " + ACTIVE_ALARM_FILE + " " + dirName + - " > /dev/null 2>&1"; - string rmCmd = "pdsh -a -x " + localHostName + " rm -f " + ACTIVE_ALARM_FILE + - " > /dev/null 2>&1"; - while(1) - { - if (boost::filesystem::exists(filePath)) - system(cpCmd.c_str()); - else - system(rmCmd.c_str()); - - sleep(ACTIVE_ALARMS_PUSHING_INTERVAL); - } - } - - return; -} - - /***************************************************************************************** * @brief Processor Heartbeat Msg Thread * diff --git a/procmgr/processmanager.cpp b/procmgr/processmanager.cpp index 657ad220..4388247d 100644 --- a/procmgr/processmanager.cpp +++ b/procmgr/processmanager.cpp @@ -1,22 +1,5 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** -* $Id: processmanager.cpp 2216 2013-08-13 14:34:10Z dhill $ +* $Id: processmanager.cpp 2200 2013-07-01 21:50:36Z dhill $ * ******************************************************************************************/ @@ -42,7 +25,6 @@ pthread_mutex_t STATUS_LOCK; pthread_mutex_t THREAD_LOCK; extern string cloud; -extern bool amazon; extern bool runStandby; extern string iface_name; extern string PMInstanceType; @@ -50,9 +32,6 @@ extern string UMInstanceType; extern string GlusterConfig; extern bool rootUser; extern string USER; -extern bool HDFS; -extern string localHostName; -extern string PMwithUM; typedef map moduleList; extern moduleList moduleInfoList; @@ -63,7 +42,6 @@ oam::DeviceNetworkList startdevicenetworklist; int upgradethreadStatus = oam::API_SUCCESS; int startsystemthreadStatus = oam::API_SUCCESS; -int stopsystemthreadStatus = oam::API_SUCCESS; int startmodulethreadStatus = oam::API_SUCCESS; bool startsystemthreadStop = false; bool startsystemthreadRunning = false; @@ -71,10 +49,6 @@ string gdownActiveOAMModule; vector downModuleList; bool startFailOver = false; -string masterLogFile = oam::UnassignedName; -string masterLogPos = oam::UnassignedName; - - HeartBeatProcList hbproclist; namespace processmanager{ @@ -175,34 +149,19 @@ void ProcessLog::writeLog(const int lineNumber, const string logContent, const L switch(logType) { case LOG_TYPE_DEBUG: - try { - ml.logDebugMessage(msg); - } - catch(...) {} + ml.logDebugMessage(msg); break; case LOG_TYPE_INFO: - try { - ml.logInfoMessage(msg); - } - catch(...) {} + ml.logInfoMessage(msg); break; case LOG_TYPE_WARNING: - try { - ml.logWarningMessage(msg); - } - catch(...) {} + ml.logWarningMessage(msg); break; case LOG_TYPE_ERROR: - try { - ml.logErrorMessage(msg); - } - catch(...) {} + ml.logErrorMessage(msg); break; case LOG_TYPE_CRITICAL: - try { - ml.logCriticalMessage(msg); - } - catch(...) {} + ml.logCriticalMessage(msg); break; } return; @@ -312,6 +271,24 @@ void processMSG(messageqcpp::IOSocket* cfIos) pthread_t ThreadId; ThreadId = pthread_self(); + ProcessLog log; + Configuration config; + ProcessManager processManager(config, log); + + Oam oam; + ByteStream::byte msgType; + ByteStream::byte actionType; + string target; + ByteStream::byte graceful; + ByteStream::byte ackIndicator = 0; + ByteStream::byte manualFlag; + ByteStream ackMsg; + ByteStream::byte status = 0; + + SNMPManager aManager; + SystemModuleTypeConfig systemmoduletypeconfig; + SystemProcessConfig systemprocessconfig; + ByteStream msg; try{ @@ -329,28 +306,6 @@ void processMSG(messageqcpp::IOSocket* cfIos) pthread_exit(0); } - ByteStream::byte msgType; - msg >> msgType; - - Oam oam; - ProcessLog log; -// log.writeLog(__LINE__, "** processMSG msg type: " + oam.itoa(msgType), LOG_TYPE_DEBUG); - - Configuration config; - ProcessManager processManager(config, log); - - ByteStream::byte actionType; - string target; - ByteStream::byte graceful; - ByteStream::byte ackIndicator = 0; - ByteStream::byte manualFlag; - ByteStream ackMsg; - ByteStream::byte status = 0; - - SNMPManager aManager; - SystemModuleTypeConfig systemmoduletypeconfig; - SystemProcessConfig systemprocessconfig; - try{ oam.getSystemConfig(systemmoduletypeconfig); } @@ -364,6 +319,8 @@ void processMSG(messageqcpp::IOSocket* cfIos) log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: Caught unknown exception!", LOG_TYPE_ERROR); } + msg >> msgType; + switch (msgType) { case REQUEST: msg >> actionType; @@ -522,7 +479,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) status = API_SUCCESS; log.writeLog(__LINE__, "Shutdown Module Requested on " + moduleName, LOG_TYPE_INFO); - processManager.shutdownModule(moduleName, graceful, manualFlag, 0); + processManager.shutdownModule(moduleName, graceful, manualFlag); //check for SIMPLEX Processes on mate might need to be started processManager.checkSimplexModule(moduleName); @@ -617,10 +574,6 @@ void processMSG(messageqcpp::IOSocket* cfIos) log.writeLog(__LINE__, "'dbrmctl resume' done", LOG_TYPE_DEBUG); processManager.reinitProcessType("ExeMgr"); - - //setup MySQL Replication for started modules - log.writeLog(__LINE__, "Setup MySQL Replication for module being started", LOG_TYPE_DEBUG); - processManager.setMySQLReplication(startdevicenetworklist); } } else @@ -1027,37 +980,10 @@ void processMSG(messageqcpp::IOSocket* cfIos) {} //set system status - processManager.setSystemState(oam::MAN_INIT); - - if (HDFS) - { - oam::DeviceNetworkList devicenetworklist; - pthread_t stopsystemthread; - status = pthread_create (&stopsystemthread, NULL, (void*(*)(void*)) &stopSystemThread, &devicenetworklist); - - if ( status != 0 ) { - log.writeLog(__LINE__, "STOPSYSTEMS: pthread_create failed, return status = " + oam.itoa(status)); - status = API_FAILURE; - } - - if (status == 0 && ackIndicator) - { - ackMsg << (ByteStream::byte) oam::ACK; - ackMsg << actionType; - ackMsg << target; - ackMsg << (ByteStream::byte) status; - - try { - fIos.write(ackMsg); - } - catch(...) {} - - log.writeLog(__LINE__, "STOPSYSTEM: ACK back to sender"); - } - break; - } + processManager.setSystemState(oam::MAN_OFFLINE); //call to update module status and send notification message + //stop all of processes.. for( unsigned int i = 0 ;i < systemmoduletypeconfig.moduletypeconfig.size(); i++) { int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; @@ -1085,7 +1011,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) continue; - processManager.stopModule((*pt).DeviceName, STATUS_UPDATE, manualFlag, 0); + processManager.stopModule((*pt).DeviceName, STATUS_UPDATE, manualFlag); } } @@ -1126,114 +1052,72 @@ void processMSG(messageqcpp::IOSocket* cfIos) log.writeLog(__LINE__, "STOPSYSTEM: Request Stop Module on " + (*pt).DeviceName ); -// int retStatus = processManager.stopModule((*pt).DeviceName, graceful, manualFlag, 0); - processManager.stopModule((*pt).DeviceName, graceful, manualFlag, 0); + int retStatus = processManager.stopModule((*pt).DeviceName, graceful, manualFlag); -// log.writeLog(__LINE__, "STOPSYSTEM: ACK received from Process-Monitor, return status = " + oam.itoa(status)); -// if (retStatus != API_SUCCESS) -// status = retStatus; + log.writeLog(__LINE__, "STOPSYSTEM: ACK received from Process-Monitor, return status = " + oam.itoa(status)); + if (retStatus != API_SUCCESS) + status = retStatus; } } - //wait until all child modules are offline or A FAILURE HAS OCCURRED - bool failure = false; - bool stopped = true; - for ( int retry = 0 ; retry < 120 ; retry++ ) - { - sleep(1); - stopped = true; - for ( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if ( moduleCount == 0) - continue; - - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end() ; pt++) - { - string moduleName = (*pt).DeviceName; - - //skip OAM Parent module, do at the end - if ( moduleName == config.moduleName() ) - continue; +// if ( graceful == INSTALL ) { + //do stopmodule last since procmon will take down procmgr - int opState; - try - { - bool degraded; - oam.getModuleStatus(moduleName, opState, degraded); - if (opState == oam::FAILED) { - failure = true; - log.writeLog(__LINE__, "STOPSYSTEM: Failed, failure on module " + moduleName, LOG_TYPE_ERROR); - break; - } + //run save.brm script + processManager.saveBRM(); - if (opState == oam::MAN_OFFLINE || - opState == oam::MAN_DISABLED || - opState == oam::AUTO_DISABLED ) - continue; - stopped = false; - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on : " + error, LOG_TYPE_ERROR); - } - catch (...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); - } + log.writeLog(__LINE__, "Stop System Completed", LOG_TYPE_INFO); + + if (ackIndicator) + { + ackMsg.reset(); + ackMsg << (ByteStream::byte) oam::ACK; + ackMsg << actionType; + ackMsg << target; + ackMsg << (ByteStream::byte) API_SUCCESS; + try { + fIos.write(ackMsg); } - if ( failure ) - break; + catch(...) {} + + log.writeLog(__LINE__, "STOPMODULE: ACK back to sender"); } + + startsystemthreadStop = false; + + processManager.setSystemState(oam::MAN_OFFLINE); - if ( failure) - break; - if ( stopped ) - break; - } - - if ( failure ) + //now stop local module + processManager.stopModule(config.moduleName(), graceful, manualFlag ); +// } +#if 0 + else { - processManager.setSystemState(oam::FAILED); - } - else - { - if ( !stopped) - { - //timeout waiting for system to stop, error out - log.writeLog(__LINE__, "STOPSYSTEM: Failed, timeout waiting for module to stop", LOG_TYPE_ERROR); - processManager.setSystemState(oam::FAILED); - } - else - { - //now stop local module - processManager.stopModule(config.moduleName(), graceful, manualFlag ); + //now stop local module + processManager.stopModule(config.moduleName(), graceful, manualFlag ); - //run save.brm script - processManager.saveBRM(); + //run save.brm script + processManager.saveBRM(); - log.writeLog(__LINE__, "Stop System Completed Success", LOG_TYPE_INFO); + log.writeLog(__LINE__, "Stop System Completed", LOG_TYPE_INFO); + + if (ackIndicator) + { + ackMsg.reset(); + ackMsg << (ByteStream::byte) oam::ACK; + ackMsg << actionType; + ackMsg << target; + ackMsg << (ByteStream::byte) API_SUCCESS; + fIos.write(ackMsg); - processManager.setSystemState(oam::MAN_OFFLINE); + log.writeLog(__LINE__, "STOPMODULE: ACK back to sender"); } + + startsystemthreadStop = false; + + processManager.setSystemState(oam::MAN_OFFLINE); } - - if (ackIndicator) - { - ackMsg.reset(); - ackMsg << (ByteStream::byte) oam::ACK; - ackMsg << actionType; - ackMsg << target; - ackMsg << (ByteStream::byte) API_SUCCESS; - fIos.write(ackMsg); - - log.writeLog(__LINE__, "STOPMODULE: ACK back to sender"); - } - - startsystemthreadStop = false; - +#endif break; } case SHUTDOWNSYSTEM: @@ -1243,7 +1127,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) // GRACEFUL_WAIT means that we are shutting down, but waiting for // all transactions to finish or rollback as commanded. This is only set if // there are, in fact, transactions active (or cpimport). -/* if (graceful == GRACEFUL_WAIT) + if (graceful == GRACEFUL_WAIT) { ByteStream stillWorkingMsg; stillWorkingMsg << (ByteStream::byte) oam::ACK; @@ -1323,7 +1207,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) continue; - processManager.stopModule((*pt).DeviceName, STATUS_UPDATE, manualFlag, 0); + processManager.stopModule((*pt).DeviceName, STATUS_UPDATE, manualFlag); } } @@ -1332,87 +1216,45 @@ void processMSG(messageqcpp::IOSocket* cfIos) { processManager.stopProcessTypes(manualFlag); } -*/ - - int retStatus = oam::API_SUCCESS; - - if (HDFS) + int retStatus; + + for( unsigned int i = 0 ;i < systemmoduletypeconfig.moduletypeconfig.size(); i++) { - if (ackIndicator) + int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; + if( moduleCount == 0) + continue; + + DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); + for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++) { - ackMsg.reset(); - ackMsg << (ByteStream::byte) oam::ACK; - ackMsg << actionType; - ackMsg << target; - ackMsg << (ByteStream::byte) status; - try { - fIos.write(ackMsg); + //do local module last + if ( (*pt).DeviceName == config.moduleName() ) + { + continue; } - catch(...) {} - - log.writeLog(__LINE__, "SHUTDOWNSYSTEM: ACK back to sender, return status = " + oam.itoa(API_SUCCESS)); - } - - Config* sysConfig = Config::makeConfig(); - - // clear Standby OAM Module - sysConfig->setConfig("SystemConfig", "StandbyOAMModuleName", oam::UnassignedName); - sysConfig->setConfig("ProcStatusControlStandby", "IPAddr", oam::UnassignedIpAddr); - - //update Calpont Config table - try { - sysConfig->write(); - } - catch(...) - { - log.writeLog(__LINE__, "ERROR: sysConfig->write", LOG_TYPE_ERROR); - } - - //run save.brm script - processManager.saveBRM(); - - string cmd = "pdsh -a -x " + localHostName + " '" + startup::StartUp::installDir() + "/infinidb stop' > /dev/null 2>&1"; - system(cmd.c_str()); - break; - } - else - { - for( unsigned int i = 0 ;i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++) + int opState; + bool degraded; + try { + oam.getModuleStatus((*pt).DeviceName, opState, degraded); + } + catch (exception& ex) { - //do local module last - if ( (*pt).DeviceName == config.moduleName() ) - { - continue; - } - - int opState; - bool degraded; - try { - oam.getModuleStatus((*pt).DeviceName, opState, degraded); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + (*pt).DeviceName + ": " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + (*pt).DeviceName + ": Caught unknown exception!", LOG_TYPE_ERROR); - } - - if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) - continue; - - retStatus = processManager.shutdownModule((*pt).DeviceName, graceful, manualFlag, 0); + string error = ex.what(); + log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + (*pt).DeviceName + ": " + error, LOG_TYPE_ERROR); + } + catch(...) + { + log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + (*pt).DeviceName + ": Caught unknown exception!", LOG_TYPE_ERROR); } + + if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) + continue; + + retStatus = processManager.shutdownModule((*pt).DeviceName, graceful, manualFlag); + + if (retStatus != API_SUCCESS) + status = retStatus; } } @@ -1422,7 +1264,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) ackMsg << (ByteStream::byte) oam::ACK; ackMsg << actionType; ackMsg << target; - ackMsg << (ByteStream::byte) status; + ackMsg << (ByteStream::byte) API_SUCCESS; try { fIos.write(ackMsg); } @@ -1450,7 +1292,12 @@ void processMSG(messageqcpp::IOSocket* cfIos) processManager.saveBRM(); // now do local module - processManager.shutdownModule(config.moduleName(), graceful, manualFlag); + retStatus = processManager.shutdownModule(config.moduleName(), graceful, manualFlag); + + if (retStatus != API_SUCCESS) + status = retStatus; + + log.writeLog(__LINE__, "SHUTDOWNSYSTEM: ACK received from Process-Monitor, return status = " + oam.itoa(status)); break; } @@ -1506,8 +1353,10 @@ void processMSG(messageqcpp::IOSocket* cfIos) if (status == 0 && ackIndicator) { - pthread_join(startsystemthread, NULL); - status = stopsystemthreadStatus; + // BUG 4554 We don't need the join because calpont console is now looking for "Active" + // We need to return the ack right away to let console know we got the message. +// pthread_join(startsystemthread, NULL); +// status = startsystemthreadStatus; ackMsg << (ByteStream::byte) oam::ACK; ackMsg << actionType; @@ -1704,14 +1553,6 @@ void processMSG(messageqcpp::IOSocket* cfIos) // status = startsystemthreadStatus; } - // setup MySQL Replication after switchover command - if (graceful == FORCEFUL) - { - log.writeLog(__LINE__, "Setup MySQL Replication for restartSystem FORCE, used by switch-parent command", LOG_TYPE_DEBUG); - oam::DeviceNetworkList devicenetworklist; - processManager.setMySQLReplication(devicenetworklist); - } - log.writeLog(__LINE__, "RESTARTSYSTEM: Start System Request Completed", LOG_TYPE_INFO); } @@ -2539,7 +2380,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; string cmd = startup::StartUp::installDir() + "/bin/save_brm > " + logdir + "/save_brm.log1 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) + if (rtnCode == 0) { ackResponse = API_SUCCESS; } @@ -2829,18 +2670,7 @@ void processMSG(messageqcpp::IOSocket* cfIos) { log.writeLog(__LINE__, "MSG RECEIVED: Get DBRM Data Files"); - string moduleName; - - msg >> moduleName; - - oam.dbrmctl("halt"); - log.writeLog(__LINE__, "'dbrmctl halt' done", LOG_TYPE_DEBUG); - - int ret = processManager.getDBRMData(fIos, moduleName); - - oam.dbrmctl("resume"); - log.writeLog(__LINE__, "'dbrmctl resume' done", LOG_TYPE_DEBUG); - + int ret = processManager.getDBRMData(fIos); if ( ret == oam::API_SUCCESS ) log.writeLog(__LINE__, "Get DBRM Data Files Completed"); @@ -3046,7 +2876,7 @@ int ProcessManager::startModule(string target, messageqcpp::ByteStream::byte act * purpose: Stop all processes on the specified module * ******************************************************************************************/ -int ProcessManager::stopModule(string target, ByteStream::byte actionIndicator, bool manualFlag, int timeout) +int ProcessManager::stopModule(string target, ByteStream::byte actionIndicator, bool manualFlag) { Configuration config; ProcessManager processManager(config, log); @@ -3081,53 +2911,38 @@ int ProcessManager::stopModule(string target, ByteStream::byte actionIndicator, aManager.sendAlarmReport(target.c_str(), MODULE_DOWN_AUTO, SET); } } - else + + returnStatus = sendMsgProcMon( target, msg, requestID ); + + if ( returnStatus == API_SUCCESS) { - log.writeLog(__LINE__, target + " module is stopped by request.", LOG_TYPE_DEBUG); - + //Issue an alarm, log the event + log.writeLog(__LINE__, target + " module is successfully stopped.", LOG_TYPE_DEBUG); + if ( manualFlag ) { - setModuleState(target, oam::MAN_INIT); + setModuleState(target, oam::MAN_OFFLINE); + + //Issue an alarm + SNMPManager aManager; + aManager.sendAlarmReport(target.c_str(), MODULE_DOWN_MANUAL, SET); } else { - setModuleState(target, oam::AUTO_INIT); + setModuleState(target, oam::AUTO_OFFLINE); + + //Issue an alarm + SNMPManager aManager; + aManager.sendAlarmReport(target.c_str(), MODULE_DOWN_AUTO, SET); } } - - returnStatus = sendMsgProcMon( target, msg, requestID, timeout ); - - if ( actionIndicator != STATUS_UPDATE ) + else { - if ( returnStatus == API_SUCCESS) - { - //Issue an alarm, log the event - log.writeLog(__LINE__, target + " module is successfully stopped.", LOG_TYPE_DEBUG); - - if ( manualFlag ) { -// setModuleState(target, oam::MAN_OFFLINE); - - //Issue an alarm - SNMPManager aManager; - aManager.sendAlarmReport(target.c_str(), MODULE_DOWN_MANUAL, SET); - } - else - { -// setModuleState(target, oam::AUTO_OFFLINE); - - //Issue an alarm - SNMPManager aManager; - aManager.sendAlarmReport(target.c_str(), MODULE_DOWN_AUTO, SET); - } - } - else - { -// if ( manualFlag ) { -// setModuleState(target, oam::FAILED); -// } - - //log the event - log.writeLog(__LINE__, target + " module failed to stop!!", LOG_TYPE_WARNING); + if ( manualFlag ) { + setModuleState(target, oam::FAILED); } + + //log the event + log.writeLog(__LINE__, target + " module failed to stop!!", LOG_TYPE_WARNING); } return returnStatus; @@ -3139,7 +2954,7 @@ int ProcessManager::stopModule(string target, ByteStream::byte actionIndicator, * purpose: power off the specified module, * ******************************************************************************************/ -int ProcessManager::shutdownModule(string target, ByteStream::byte actionIndicator, bool manualFlag, int timeout) +int ProcessManager::shutdownModule(string target, ByteStream::byte actionIndicator, bool manualFlag) { ByteStream msg; ByteStream::byte requestID = SHUTDOWNMODULE; @@ -3147,7 +2962,7 @@ int ProcessManager::shutdownModule(string target, ByteStream::byte actionIndicat msg = buildRequestMessage(requestID, actionIndicator, processName, manualFlag); - int returnStatus = sendMsgProcMon( target, msg, requestID, timeout ); + int returnStatus = sendMsgProcMon( target, msg, requestID ); if ( returnStatus == API_SUCCESS) { @@ -3326,7 +3141,7 @@ void ProcessManager::recycleProcess(string module) string moduleType = module.substr(0,MAX_MODULE_TYPE_SIZE); - // if a UM module, send a restart on DMLProc/DDLProc to get started on another UM, if needed + // if a UM module send a restart on DMLProc/DDLProc to get started on another UM, if needed string PrimaryUMModuleName; try { oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); @@ -3504,14 +3319,14 @@ void ProcessManager::startMgrProcesses(std::string moduleName) * ******************************************************************************************/ int ProcessManager::stopProcess(string moduleName, string processName, - messageqcpp::ByteStream::byte actionIndicator, bool manualFlag, int timeout) + messageqcpp::ByteStream::byte actionIndicator, bool manualFlag) { ByteStream msg; ByteStream::byte requestID = STOP; msg = buildRequestMessage(requestID, actionIndicator, processName, manualFlag); - int returnStatus = sendMsgProcMon( moduleName, msg, requestID, timeout ); + int returnStatus = sendMsgProcMon( moduleName, msg, requestID ); if ( returnStatus == API_SUCCESS) //log the event @@ -3622,11 +3437,9 @@ void ProcessManager::setSystemState(uint16_t state) log.writeLog(__LINE__, "Set System State = " + oam.itoa(state), LOG_TYPE_DEBUG); - int setState = state; - // if system state = ACTIVE, make sure DMLProc is ACTIVE first + int setState = state; if( state == oam::ACTIVE ) { - setState = -1; // default to loal module string PrimaryUMModuleName = config.moduleName(); try { @@ -3635,11 +3448,13 @@ void ProcessManager::setSystemState(uint16_t state) catch(...) {} int retry = 0; - while (retry < 30) - { + while (retry < 30) + { ProcessStatus DMLprocessstatus; + ProcessStatus DDLprocessstatus; try { oam.getProcessStatus("DMLProc", PrimaryUMModuleName, DMLprocessstatus); + oam.getProcessStatus("DDLProc", PrimaryUMModuleName, DDLprocessstatus); } catch (exception& ex) { @@ -3651,54 +3466,57 @@ void ProcessManager::setSystemState(uint16_t state) log.writeLog(__LINE__, "EXCEPTION ERROR on getProcessStatus: Caught unknown exception!", LOG_TYPE_ERROR); } - if (DMLprocessstatus.ProcessOpState == oam::FAILED) { + if (DMLprocessstatus.ProcessOpState == oam::FAILED || + DDLprocessstatus.ProcessOpState == oam::FAILED) { setState = oam::FAILED; break; } - if (DMLprocessstatus.ProcessOpState == oam::ACTIVE) { + + if (DMLprocessstatus.ProcessOpState == oam::ACTIVE && + DDLprocessstatus.ProcessOpState == oam::ACTIVE) { setState = oam::ACTIVE; break; } + if ( setState != 0 ) + break; + sleep(2); retry++; } } - if ( setState != -1 ) + pthread_mutex_lock(&STATUS_LOCK); + try{ + oam.setSystemStatus(setState); + } + catch (exception& ex) { - pthread_mutex_lock(&STATUS_LOCK); - try{ - oam.setSystemStatus(setState); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on MessageQueueClient: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on MessageQueueClient: Caught unknown exception!", LOG_TYPE_ERROR); - } - pthread_mutex_unlock(&STATUS_LOCK); - - // Process Alarms - string system = "System"; - if( setState == oam::ACTIVE ) { - //clear alarms if set - if ( oam.checkActiveAlarm(SYSTEM_DOWN_AUTO, config.moduleName(), system) ) - aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_AUTO, CLEAR); - if ( oam.checkActiveAlarm(SYSTEM_DOWN_MANUAL, config.moduleName(), system) ) - aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_MANUAL, CLEAR); - } - else { - if( state == oam::MAN_OFFLINE ) - aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_MANUAL, SET); - else - if ( state == oam::AUTO_OFFLINE ) - aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_AUTO, SET); - } + string error = ex.what(); + log.writeLog(__LINE__, "EXCEPTION ERROR on MessageQueueClient: " + error, LOG_TYPE_ERROR); + } + catch(...) + { + log.writeLog(__LINE__, "EXCEPTION ERROR on MessageQueueClient: Caught unknown exception!", LOG_TYPE_ERROR); + } + pthread_mutex_unlock(&STATUS_LOCK); + + // Process Alarms + string system = "System"; + if( setState == oam::ACTIVE ) { + //clear alarms if set + if ( oam.checkActiveAlarm(SYSTEM_DOWN_AUTO, config.moduleName(), system) ) + aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_AUTO, CLEAR); + if ( oam.checkActiveAlarm(SYSTEM_DOWN_MANUAL, config.moduleName(), system) ) + aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_MANUAL, CLEAR); + } + else { + if( state == oam::MAN_OFFLINE ) + aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_MANUAL, SET); + else + if ( state == oam::AUTO_OFFLINE ) + aManager.sendAlarmReport(system.c_str(), SYSTEM_DOWN_AUTO, SET); } } @@ -3833,17 +3651,6 @@ void ProcessManager::setProcessStates(std::string moduleName, uint16_t state, st SystemProcessConfig systemprocessconfig; vector::iterator itor; - //PMwithUM config - string PMwithUM = "n"; - try { - oam.getSystemConfig( "PMwithUM", PMwithUM); - } - catch(...) { - PMwithUM = "n"; - } - - string moduleType = moduleName.substr(0,MAX_MODULE_TYPE_SIZE); - try{ oam.getProcessConfig(systemprocessconfig); } @@ -3857,7 +3664,7 @@ void ProcessManager::setProcessStates(std::string moduleName, uint16_t state, st log.writeLog(__LINE__, "EXCEPTION ERROR on getProcessConfig: Caught unknown exception!", LOG_TYPE_ERROR); } - string moduleTypeSet = moduleName.substr(0,MAX_MODULE_TYPE_SIZE); + string moduleType = moduleName.substr(0,MAX_MODULE_TYPE_SIZE); for (itor=systemprocessconfig.processconfig.begin(); itor != systemprocessconfig.processconfig.end(); ++itor) @@ -3891,32 +3698,6 @@ void ProcessManager::setProcessStates(std::string moduleName, uint16_t state, st setProcessState(moduleName, "mysqld", state, 0); } } - else - { //for for umwithpm apps, which is ExeMgr now - if ( moduleTypeSet == "pm" && PMwithUM == "y" ) - { - ProcessStatus processstatus; - try { - oam.getProcessStatus("ExeMgr", moduleName, processstatus); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getProcessStatus: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getProcessStatus: Caught unknown exception!", LOG_TYPE_ERROR); - } - - if (processstatus.ProcessOpState != oam::MAN_OFFLINE) { - setProcessState(moduleName, "ExeMgr", state, 0); - - if ( state == oam::AUTO_OFFLINE ) - setProcessState(moduleName, "mysqld", state, 0); - } - } - } } } @@ -4048,11 +3829,11 @@ int ProcessManager::stopProcessType( std::string processName, bool manualFlag ) { if ( systemprocessstatus.processstatus[i].ProcessName == processName) { // found one, request restart of it - processManager.stopProcess(systemprocessstatus.processstatus[i].Module, + int retStatus = processManager.stopProcess(systemprocessstatus.processstatus[i].Module, processName, GRACEFUL, - manualFlag, 0); -// log.writeLog(__LINE__, "stopProcessType: Start ACK received from Process-Monitor, return status = " + oam.itoa(retStatus), LOG_TYPE_DEBUG); + manualFlag); + log.writeLog(__LINE__, "stopProcessType: Start ACK received from Process-Monitor, return status = " + oam.itoa(retStatus), LOG_TYPE_DEBUG); } } } @@ -4136,15 +3917,6 @@ int ProcessManager::restartProcessType( std::string processName, bool manualFlag log.writeLog(__LINE__, "restartProcessType: Restart all " + processName, LOG_TYPE_DEBUG); - //PMwithUM config - string PMwithUM = "n"; - try { - oam.getSystemConfig( "PMwithUM", PMwithUM); - } - catch(...) { - PMwithUM = "n"; - } - // If mysql is the processName, then send to modules were ExeMgr is running try { @@ -4173,14 +3945,10 @@ int ProcessManager::restartProcessType( std::string processName, bool manualFlag if ( systemprocessstatus.processstatus[i].ProcessOpState == oam::BUSY_INIT ) continue; if ( (systemprocessstatus.processstatus[i].ProcessOpState == oam::ACTIVE) || - (systemprocessstatus.processstatus[i].ProcessOpState == oam::AUTO_OFFLINE) || (systemprocessstatus.processstatus[i].ProcessOpState == oam::COLD_STANDBY && !manualFlag) ) { if( processName.find("DDLProc") == 0 || processName.find("DMLProc") == 0 ) { - string procModuleType = systemprocessstatus.processstatus[i].Module.substr(0,MAX_MODULE_TYPE_SIZE); - if ( procModuleType == "pm" && PMwithUM == "y" ) - continue; - + try { oam.setSystemConfig("PrimaryUMModuleName", systemprocessstatus.processstatus[i].Module); @@ -4189,23 +3957,15 @@ int ProcessManager::restartProcessType( std::string processName, bool manualFlag //distribute config file processManager.distributeConfigFile("system"); sleep(1); - - //change master MySQL Replication setup, if DMLProc COLD_STANDBY is going ACTIVE - if ( systemprocessstatus.processstatus[i].ProcessOpState == oam::COLD_STANDBY && !manualFlag && processName.find("DMLProc") == 0 ) - { - log.writeLog(__LINE__, "Setup MySQL Replication for DMLProc COLD_STANDBY is going ACTIVE", LOG_TYPE_DEBUG); - oam::DeviceNetworkList devicenetworklist; - processManager.setMySQLReplication(devicenetworklist, systemprocessstatus.processstatus[i].Module); - } } catch(...) {} } // found one, request restart of it retStatus = processManager.restartProcess(systemprocessstatus.processstatus[i].Module, - processName, - FORCEFUL, - true); + processName, + FORCEFUL, + true); log.writeLog(__LINE__, "restartProcessType: Start ACK received from Process-Monitor, return status = " + oam.itoa(retStatus), LOG_TYPE_DEBUG); // if DDL or DMLProc, change IP Address @@ -4308,10 +4068,6 @@ int ProcessManager::reinitProcessType( std::string processName ) ******************************************************************************************/ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::string password, bool manualFlag) { - ProcessLog log; - Configuration config; - ProcessManager processManager(config, log); - SystemModuleTypeConfig systemmoduletypeconfig; ModuleTypeConfig moduletypeconfig; ModuleTypeConfig setmoduletypeconfig; @@ -4384,9 +4140,6 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str string calpontPackage; string mysqlPackage; string mysqldPackage; - string calpontPackage1; - string calpontPackage2; - string systemID; string packageType = "rpm"; @@ -4419,37 +4172,29 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str } if ( packageType != "binary") { - string separator = "-"; + string seperator = "-"; if ( packageType == "deb" ) - separator = "_"; - calpontPackage = homedir + "/infinidb-platform" + separator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; - mysqlPackage = homedir + "/infinidb-storage-engine" + separator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; - mysqldPackage = homedir + "/infinidb-mysql" + separator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; - calpontPackage1 = homedir + "/infinidb-libs" + separator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; - calpontPackage2 = homedir + "/infinidb-ent" + separator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; + seperator = "_"; + calpontPackage = homedir + "/calpont" + seperator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; + mysqlPackage = homedir + "/calpont-mysql" + seperator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; + mysqldPackage = homedir + "/calpont-mysqld" + seperator + systemsoftware.Version + "-" + systemsoftware.Release + "*." + packageType; } else { - calpontPackage = homedir + "/infinidb*" + systemsoftware.Version + "-" + systemsoftware.Release + "*.bin.tar.gz"; + calpontPackage = homedir + "/calpont-infinidb-ent-" + systemsoftware.Version + "-" + systemsoftware.Release + "*.bin.tar.gz"; mysqlPackage = calpontPackage; mysqldPackage = calpontPackage; } string cmd = "ls " + calpontPackage + " > /dev/null 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { log.writeLog(__LINE__, "addModule - ERROR: Package not found: " + calpontPackage, LOG_TYPE_ERROR); pthread_mutex_unlock(&THREAD_LOCK); return API_FILE_OPEN_ERROR; } log.writeLog(__LINE__, "addModule - Calpont Package found:" + calpontPackage, LOG_TYPE_DEBUG); - // check if infinidb-ent is there - cmd = "ls " + calpontPackage2 + " > /dev/null 2>&1"; - rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) - calpontPackage2 = "dummy.rpm"; - // // Verify Host IP and Password // @@ -4457,7 +4202,7 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str // This is the password that is set in a amazon AMI string amazonDefaultPassword = "Calpont1"; - if ( password == "ssh" && amazon ) + if ( password == "ssh" && cloud == "amazon" ) { // check if there is a root password stored string rpw = oam::UnassignedName; try @@ -4477,15 +4222,14 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str for( ; listPT != devicenetworklist.end() ; listPT++) { HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); - string newHostName = (*pt1).HostName; - if ( newHostName == oam::UnassignedName ) + string newIPAddr = (*pt1).IPAddr; + if ( newIPAddr == oam::UnassignedName ) continue; - string newIPAddr = (*pt1).IPAddr; string cmd = installDir + "/bin/remote_command.sh " + newIPAddr + " " + password + " ls"; log.writeLog(__LINE__, cmd, LOG_TYPE_DEBUG); int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { log.writeLog(__LINE__, "addModule - ERROR: Remote login test failed, Invalid IP / Password " + newIPAddr, LOG_TYPE_ERROR); pthread_mutex_unlock(&THREAD_LOCK); return API_FAILURE; @@ -4506,7 +4250,6 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str pthread_mutex_unlock(&THREAD_LOCK); return API_FAILURE; } - setmoduletypeconfig = moduletypeconfig; // update Module Type Count @@ -4529,8 +4272,7 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str string hostName = (*pt1).HostName; string IPAddr = (*pt1).IPAddr; //if cloud and unassigned, launch a new Instance - if ( ( cloud == "amazon-ec2" && hostName == oam::UnassignedName ) || - ( cloud == "amazon-vpc" && hostName == oam::UnassignedName ) ) + if ( cloud == "amazon" && hostName == oam::UnassignedName ) { string UMinstanceType; string UMSecurityGroup; @@ -4545,10 +4287,11 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str log.writeLog(__LINE__, "addModule - Launching a new Instance for: " + moduleName, LOG_TYPE_DEBUG); + if ( moduleType == "um" ) - hostName = oam.launchEC2Instance(moduleName, IPAddr, UMinstanceType, UMSecurityGroup); + hostName = oam.launchEC2Instance(moduleName, UMinstanceType, UMSecurityGroup); else - hostName = oam.launchEC2Instance(moduleName, IPAddr); + hostName = oam.launchEC2Instance(moduleName); if ( hostName == "failed" ) { log.writeLog(__LINE__, "addModule - Launch New Instance Failure", LOG_TYPE_ERROR); @@ -4572,18 +4315,9 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str sleep(10); continue; } - - string cmd = installDir + "/bin/remote_command.sh " + IPAddr + " " + amazonDefaultPassword + " 'ls' 1 > /tmp/login_test.log"; - system(cmd.c_str()); - if (!oam.checkLogStatus("/tmp/login_test.log", "README")) { - //check for RSA KEY ISSUE and fix - if (oam.checkLogStatus("/tmp/login_test.log", "Offending RSA key")) { - log.writeLog(__LINE__, "addModule - login failed, RSA key issue, try fixing: " + moduleName, LOG_TYPE_DEBUG); - string file = "/tmp/login_test.log"; - oam.fixRSAkey(file); - } - - log.writeLog(__LINE__, "addModule - login failed, retry login test: " + moduleName, LOG_TYPE_DEBUG); + string cmd = installDir + "/bin/remote_command.sh " + IPAddr + " " + amazonDefaultPassword + " 'ls' > /tmp/login_test.log"; + int rtnCode = system(cmd.c_str()); + if (rtnCode != 0) { sleep(10); continue; } @@ -4774,39 +4508,16 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str } if ( moduleType == "um" || - ( moduleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) || - ( moduleType == "pm" && PMwithUM == "y") ) { + ( moduleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) ) { listPT = devicenetworklist.begin(); for( ; listPT != devicenetworklist.end() ; listPT++) { int moduleID = atoi((*listPT).DeviceName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - int exemgrID = moduleID; - if ( PMwithUM == "y" ) - { // then go check for next available ID - exemgrID = 0; - for ( int id = 2 ; ; id++ ) - { - string Section = "ExeMgr" + oam.itoa(id); - string moduleName; - try { - Config* sysConfig = Config::makeConfig(); - moduleName = sysConfig->getConfig(Section, "Module"); - } - catch (...) {} - if ( moduleName.empty() ) - { - exemgrID = id; - break; - } - } - } - - Section = "ExeMgr" + oam.itoa(exemgrID); + Section = "ExeMgr" + oam.itoa(moduleID); HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); sysConfig->setConfig(Section, "IPAddr", (*pt1).IPAddr); sysConfig->setConfig(Section, "Port", "8601"); - sysConfig->setConfig(Section, "Module", (*listPT).DeviceName); } } @@ -4829,8 +4540,8 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str //setup dbroot entries if (moduleType == "pm" && manualFlag) { - const string MODULE_DBROOTID = "ModuleDBRootID"; - const string MODULE_DBROOT_COUNT = "ModuleDBRootCount"; + const string MODULE_DBROOTID = "ModuleDBRootID"; + const string MODULE_DBROOT_COUNT = "ModuleDBRootCount"; listPT = devicenetworklist.begin(); for( ; listPT != devicenetworklist.end() ; listPT++) @@ -4931,26 +4642,6 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str } } - //PMwithUM config - string PMwithUM = "n"; - try { - oam.getSystemConfig( "PMwithUM", PMwithUM); - } - catch(...) { - PMwithUM = "n"; - } - - //check mysql port changes - string MySQLPort; - try { - oam.getSystemConfig( "MySQLPort", MySQLPort); - } - catch(...) - {} - - if ( MySQLPort.empty() || MySQLPort == "" || MySQLPort == oam::UnassignedName ) - MySQLPort = "3306"; - //setup and push custom OS files listPT = devicenetworklist.begin(); for( ; listPT != devicenetworklist.end() ; listPT++) @@ -4966,7 +4657,7 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str string dir = installDir + "/local/etc/" + remoteModuleName; string cmd = "mkdir " + dir + " > /dev/null 2>&1"; - system(cmd.c_str()); + int rtnCode = system(cmd.c_str()); if ( remoteModuleType == "um" ) { cmd = "cp " + installDir + "/local/etc/um1/* " + dir + "/."; @@ -4996,11 +4687,11 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str } //set root password - if (amazon) { + if ( cloud == "amazon") { cmd = startup::StartUp::installDir() + "/bin/remote_command.sh " + remoteModuleIP + " " + amazonDefaultPassword + " '/root/updatePassword.sh " + password + "' > /tmp/password_change.log"; //log.writeLog(__LINE__, "addModule - cmd: " + cmd, LOG_TYPE_DEBUG); rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) + if (rtnCode == 0) log.writeLog(__LINE__, "addModule - update root password: " + remoteModuleName, LOG_TYPE_DEBUG); else log.writeLog(__LINE__, "addModule - ERROR: update root password: " + remoteModuleName, LOG_TYPE_DEBUG); @@ -5011,22 +4702,19 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str //run installer on remote module if ( remoteModuleType == "um" || - ( remoteModuleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) || - ( remoteModuleType == "pm" && PMwithUM == "y" ) ) { + ( remoteModuleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) ) { //run remote installer script if ( packageType != "binary" ) { log.writeLog(__LINE__, "addModule - user_installer run for " + remoteModuleName, LOG_TYPE_DEBUG); - - string cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + calpontPackage1 + " " + calpontPackage2 + " " + mysqlPackage + " " + mysqldPackage + " initial " + packageType + " --nodeps none " + MySQLPort + " 1 > /tmp/user_installer.log"; - + string cmd = installDir + "/bin/user_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + mysqlPackage + " " + mysqldPackage + " initial " + packageType + + " --nodeps none 1 > /tmp/user_installer.log"; log.writeLog(__LINE__, "addModule cmd: " + cmd, LOG_TYPE_DEBUG); rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { log.writeLog(__LINE__, "addModule - ERROR: user_installer.sh failed", LOG_TYPE_ERROR); pthread_mutex_unlock(&THREAD_LOCK); system(" cp /tmp/user_installer.log /tmp/user_installer.log.failed"); - processManager.setModuleState(remoteModuleName, oam::FAILED); return API_FAILURE; } } @@ -5034,18 +4722,14 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str { // do a binary package install log.writeLog(__LINE__, "addModule - binary_installer run for " + remoteModuleName, LOG_TYPE_DEBUG); - string binservertype = oam.itoa(config.ServerInstallType()); - if ( PMwithUM == "y" ) - binservertype = "pmwithum"; - string cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + remoteModuleType + " initial " + binservertype + " " + MySQLPort + " 1 " + binaryInstallDir + " > /tmp/binary_installer.log"; + string cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + remoteModuleType + " initial " + oam.itoa(config.ServerInstallType()) + " 1 " + binaryInstallDir + " > /tmp/binary_installer.log"; log.writeLog(__LINE__, "addModule - " + cmd, LOG_TYPE_DEBUG); rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { log.writeLog(__LINE__, "addModule - ERROR: binary_installer.sh failed", LOG_TYPE_ERROR); system(" cp /tmp/binary_installer.log /tmp/binary_installer.log.failed"); pthread_mutex_unlock(&THREAD_LOCK); - processManager.setModuleState(remoteModuleName, oam::FAILED); return API_FAILURE; } } @@ -5055,15 +4739,14 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str if ( remoteModuleType == "pm" ) { if ( packageType != "binary" ) { log.writeLog(__LINE__, "addModule - performance_installer run for " + remoteModuleName, LOG_TYPE_DEBUG); - string cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + calpontPackage1 + " " + calpontPackage2 + " " + mysqlPackage + " " + mysqldPackage + " initial " + packageType + " --nodeps 1 > /tmp/performance_installer.log"; + string cmd = installDir + "/bin/performance_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + mysqlPackage + " " + mysqldPackage + " initial " + packageType + " --nodeps 1 > /tmp/performance_installer.log"; log.writeLog(__LINE__, "addModule cmd: " + cmd, LOG_TYPE_DEBUG); rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { log.writeLog(__LINE__, "addModule - ERROR: performance_installer.sh failed", LOG_TYPE_ERROR); system(" cp /tmp/performance_installer.log /tmp/performance_installer.log.failed"); pthread_mutex_unlock(&THREAD_LOCK); - processManager.setModuleState(remoteModuleName, oam::FAILED); return API_FAILURE; } } @@ -5071,19 +4754,14 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str { // do a binary package install log.writeLog(__LINE__, "addModule - binary_installer run for " + remoteModuleName, LOG_TYPE_DEBUG); - string binservertype = oam.itoa(config.ServerInstallType()); - if ( PMwithUM == "y" ) - binservertype = "pmwithum"; - - string cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + remoteModuleType + " initial " + binservertype + " 1 " + binaryInstallDir + " > /tmp/binary_installer.log"; + string cmd = installDir + "/bin/binary_installer.sh " + remoteModuleName + " " + remoteModuleIP + " " + password + " " + calpontPackage + " " + remoteModuleType + " initial " + oam.itoa(config.ServerInstallType()) + " 1 " + binaryInstallDir + " > /tmp/binary_installer.log"; log.writeLog(__LINE__, "addModule - " + cmd, LOG_TYPE_DEBUG); rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 0) { + if (rtnCode != 0) { log.writeLog(__LINE__, "addModule - ERROR: binary_installer.sh failed", LOG_TYPE_ERROR); system(" cp /tmp/binary_installer.log /tmp/binary_installer.log.failed"); pthread_mutex_unlock(&THREAD_LOCK); - processManager.setModuleState(remoteModuleName, oam::FAILED); return API_FAILURE; } } @@ -5112,7 +4790,7 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str // add to monitor list moduleInfoList.insert(moduleList::value_type(remoteModuleName, 0)); - if (amazon) { + if ( cloud == "amazon") { //check and assign Elastic IP Address int AmazonElasticIPCount = 0; try{ @@ -5154,7 +4832,7 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str } //if amazon, delay to give time for ProcMon to start - if (amazon) { + if ( cloud == "amazon") { log.writeLog(__LINE__, "addModule - sleep 30 - give ProcMon time to start on new Instance", LOG_TYPE_DEBUG); sleep(30); } @@ -5162,10 +4840,6 @@ int ProcessManager::addModule(oam::DeviceNetworkList devicenetworklist, std::str //distribute config file distributeConfigFile("system"); - //add MySQL Replication slave - log.writeLog(__LINE__, "Setup MySQL Replication for new Modules being Added", LOG_TYPE_DEBUG); - processManager.setMySQLReplication(devicenetworklist, oam::UnassignedName, false, true, password ); - return API_SUCCESS; } @@ -5290,7 +4964,7 @@ int ProcessManager::removeModule(oam::DeviceNetworkList devicenetworklist, bool for ( ; pt1 != (*pt).hostConfigList.end() ; pt1++ ) { //if cloud, delete instance - if (amazon) + if ( cloud == "amazon" ) { log.writeLog(__LINE__, "removeModule - terminate instance: " + (*pt1).HostName, LOG_TYPE_DEBUG); oam.terminateEC2Instance( (*pt1).HostName ); @@ -5301,52 +4975,6 @@ int ProcessManager::removeModule(oam::DeviceNetworkList devicenetworklist, bool string tagValue = systemName + "-" + moduleName + "-terminated"; oam.createEC2tag( (*pt1).HostName, "Name", tagValue ); } - - //check if any volumes need to be deleted - if ( moduleType == "um" ) - { - string UMStorageType = "internal"; - { - try{ - oam.getSystemConfig("UMStorageType", UMStorageType); - } - catch(...) {} - } - - if ( UMStorageType == "external" ) - { //check if volume already assigned or need to create a new one - int moduleID = atoi(moduleName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - - string volumeNameID = "UMVolumeName" + oam.itoa(moduleID); - string volumeName = oam::UnassignedName; - string deviceNameID = "UMVolumeDeviceName" + oam.itoa(moduleID); - string deviceName = oam::UnassignedName; - try { - oam.getSystemConfig( volumeNameID, volumeName); - oam.getSystemConfig( deviceNameID, deviceName); - } - catch(...) - {} - - if ( !volumeName.empty() || volumeName != oam::UnassignedName ) { - log.writeLog(__LINE__, "removeModule - detach / remove volume: " + volumeName + "/" + deviceName, LOG_TYPE_DEBUG); - oam.detachEC2Volume( volumeName ); - - oam.deleteEC2Volume( volumeName ); - - try { - Config* sysConfig = Config::makeConfig(); - - sysConfig->setConfig("Installation", volumeNameID, oam::UnassignedName); - sysConfig->setConfig("Installation", deviceNameID, oam::UnassignedName); - - sysConfig->write(); - } - catch(...) - {} - } - } - } } clearNICAlarms((*pt1).HostName); @@ -5370,43 +4998,24 @@ int ProcessManager::removeModule(oam::DeviceNetworkList devicenetworklist, bool for( ; listPT != devicenetworklist.end() ; listPT++) { Section = (*listPT).DeviceName + "_ProcessMonitor"; - sysConfig->setConfig(Section, "IPAddr", oam::UnassignedName); + sysConfig->setConfig(Section, "IPAddr", oam::UnassignedIpAddr); Section = (*listPT).DeviceName + "_ServerMonitor"; - sysConfig->setConfig(Section, "IPAddr", oam::UnassignedName); + sysConfig->setConfig(Section, "IPAddr", oam::UnassignedIpAddr); } if ( moduleType == "um" || ( moduleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) || ( moduleType == "um" && config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM ) || - ( moduleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_PM_UM ) || - ( moduleType == "pm" && PMwithUM == "y" ) ) { + ( moduleType == "pm" && config.ServerInstallType() == oam::INSTALL_COMBINE_PM_UM ) ) { listPT = devicenetworklist.begin(); for( ; listPT != devicenetworklist.end() ; listPT++) { - // go find ExeMgr ID by moduleName - for ( int id = 1 ; ; id++ ) - { - string Section = "ExeMgr" + oam.itoa(id); - string moduleName; - try { - Config* sysConfig = Config::makeConfig(); - moduleName = sysConfig->getConfig(Section, "Module"); - - if ( moduleName == (*listPT).DeviceName ) - { // match - sysConfig->setConfig(Section, "IPAddr", oam::UnassignedName); - sysConfig->setConfig(Section, "Module", oam::UnassignedName); - - break; - } - } - catch (...) {} + int moduleID = atoi((*listPT).DeviceName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - if ( moduleName.empty() ) - break; - } + Section = "ExeMgr" + oam.itoa(moduleID); + sysConfig->setConfig(Section, "IPAddr", oam::UnassignedIpAddr); } } @@ -5925,12 +5534,6 @@ int ProcessManager::sendMsgProcMon( std::string module, ByteStream msg, int requ receivedMSG >> returnRequestID; receivedMSG >> requestStatus; - if ( requestID == oam::MASTERREP ) - { - receivedMSG >> masterLogFile; - receivedMSG >> masterLogPos; - } - if ( returnACK == oam::ACK && returnRequestID == requestID) { // ACK for this request returnStatus = requestStatus; @@ -6070,7 +5673,7 @@ void ProcessManager::saveBRM() string cmd = startup::StartUp::installDir() + "/bin/reset_locks > " + logdir + "/reset_locks.log1 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 1) { + if (rtnCode != 1) { log.writeLog(__LINE__, "Successfully ran reset_locks", LOG_TYPE_DEBUG); } else @@ -6080,7 +5683,7 @@ void ProcessManager::saveBRM() cmd = startup::StartUp::installDir() + "/bin/save_brm > " + logdir + "/save_brm.log1 2>&1"; rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) != 1) { + if (rtnCode != 1) { log.writeLog(__LINE__, "Successfully ran DBRM save_brm", LOG_TYPE_DEBUG); } else @@ -6169,7 +5772,7 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) if ( exitThread ) { pthread_detach (ThreadId); - pthread_exit(reinterpret_cast(static_cast(exitThreadStatus))); + pthread_exit((void*) exitThreadStatus); } if (systemstatus.SystemOpState == AUTO_OFFLINE) @@ -6179,7 +5782,6 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) //validate the dbroots assignments //make sure no 1 ID is assigned to 2 PMs - //and a dbroot not assigned to a DISABLED PM try { systemStorageInfo_t t; @@ -6194,11 +5796,15 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) string moduleID1 = oam.itoa((*pt1).DeviceID); string moduleName = "pm" + moduleID1; - // check DISABLED modules - int opState; - bool degraded; + // bypass DISABLED modules try{ + int opState; + bool degraded; oam.getModuleStatus(moduleName, opState, degraded); + + if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) + //skip + continue; } catch (exception& ex) { @@ -6213,21 +5819,6 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) continue; } - //check if disabled - if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) { - if ( (*pt1).dbrootConfigList.size() != 0 ) { - //issue log and Set the alarm - log.writeLog(__LINE__, "startSystemThread failed: Disabled Module '" + moduleName + "' has DBRoots assigned to it", LOG_TYPE_CRITICAL); - aManager.sendAlarmReport(config.moduleName().c_str(), STARTUP_DIAGNOTICS_FAILURE, SET); - startsystemthreadStatus = oam::API_FAILURE; - processManager.setSystemState(oam::FAILED); - pthread_detach (ThreadId); - pthread_exit((void*) oam::API_FAILURE); - } - - continue; - } - // if module has no dbroots assigned, fail startSystem if ( (*pt1).dbrootConfigList.size() == 0 ) { //issue log and Set the alarm @@ -6293,7 +5884,7 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) if ( exitThread ) { pthread_detach (ThreadId); - pthread_exit(reinterpret_cast(static_cast(exitThreadStatus))); + pthread_exit((void*) exitThreadStatus); } if (systemstatus.SystemOpState == AUTO_OFFLINE) @@ -6459,17 +6050,12 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) } pthread_t startmodulethread; - string name = moduleName; - int status = pthread_create (&startmodulethread, NULL, (void*(*)(void*)) &startModuleThread, &name); + int status = pthread_create (&startmodulethread, NULL, (void*(*)(void*)) &startModuleThread, &moduleName); if ( status != 0 ) log.writeLog(__LINE__, "startModuleThread: pthread_create failed, return status = " + oam.itoa(status), LOG_TYPE_ERROR); - if ( !HDFS ) - sleep(5); - else - //usleep(100000); - sleep(1); + sleep(5); } } } @@ -6579,13 +6165,13 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) status = oam::API_FAILURE; } - // Bug 4554: Wait until DMLProc is finished with rollback - if (status == oam::API_SUCCESS) - { - BRM::DBRM dbrm; - uint16_t rtn = 0; - bool bfirst = true; - SystemProcessStatus systemprocessstatus; + // Bug 4554: Wait until DMLProc is finished with rollback + if (status == oam::API_SUCCESS) + { + BRM::DBRM dbrm; + uint16_t rtn = 0; + bool bfirst = true; + SystemProcessStatus systemprocessstatus; string PrimaryUMModuleName; try { @@ -6605,12 +6191,14 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) pthread_exit(0); } - // waiting until dml are ACTIVE, then mark system ACTIVE - while (rtn == 0) - { + // waiting until ddl/dml are ACTIVE, then mark system ACTIVE + while (rtn == 0) + { ProcessStatus DMLprocessstatus; + ProcessStatus DDLprocessstatus; try { oam.getProcessStatus("DMLProc", PrimaryUMModuleName, DMLprocessstatus); + oam.getProcessStatus("DDLProc", PrimaryUMModuleName, DDLprocessstatus); } catch (exception& ex) { @@ -6630,20 +6218,21 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) } } - if (DMLprocessstatus.ProcessOpState == oam::ACTIVE) { - rtn = oam::ACTIVE; + if (DMLprocessstatus.ProcessOpState == oam::ACTIVE && + DDLprocessstatus.ProcessOpState == oam::ACTIVE) { + rtn = oam::ACTIVE; break; } if (DMLprocessstatus.ProcessOpState == oam::FAILED) { - rtn = oam::FAILED; + rtn = oam::FAILED; break; } // wait some more - sleep(2); - } - processManager.setSystemState(rtn); + sleep(2); + } + processManager.setSystemState(rtn); } // exit thread @@ -6662,10 +6251,6 @@ void startSystemThread(oam::DeviceNetworkList Devicenetworklist) *****************************************************************************************/ void startModuleThread(string module) { - - //store in a local variable - string moduleName = module; - ProcessLog log; Configuration config; ProcessManager processManager(config, log); @@ -6676,6 +6261,8 @@ void startModuleThread(string module) pthread_t ThreadId; ThreadId = pthread_self(); + //store in a local variable + string moduleName = module; if ( moduleName.empty() ){ log.writeLog(__LINE__, "startModuleThread received on invalid module name", LOG_TYPE_ERROR); pthread_detach (ThreadId); @@ -6707,7 +6294,7 @@ void startModuleThread(string module) if ( exitThread ) { pthread_detach (ThreadId); - pthread_exit(reinterpret_cast(static_cast(exitThreadStatus))); + pthread_exit((void*) exitThreadStatus); } // get module status @@ -6739,313 +6326,15 @@ void startModuleThread(string module) log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); } - if ( startsystemthreadStop) { - // set status and exit this thread - processManager.setModuleState(moduleName, oam::MAN_OFFLINE); - log.writeLog(__LINE__, "startModuleThread early exit on " + moduleName, LOG_TYPE_DEBUG); - pthread_detach (ThreadId); - pthread_exit(0); - } - - int retStatus = processManager.startModule(moduleName, oam::FORCEFUL, startType, true); - - log.writeLog(__LINE__, "ACK received from '" + moduleName + "' Process-Monitor, return status = " + oam.itoa(retStatus), LOG_TYPE_DEBUG); - - if (retStatus == API_SUCCESS) - break; - else - { - if (retStatus != API_MINOR_FAILURE) { - //major failure, set stopsystem flag and exit this thread - startmodulethreadStatus = retStatus; - startsystemthreadStop = true; - break; - } - } - } - - // exit thread - log.writeLog(__LINE__, "startModuleThread Exit on " + moduleName, LOG_TYPE_DEBUG); - pthread_detach (ThreadId); - pthread_exit(0); -} - - -/***************************************************************************************** -* @brief stopSystemThread -* -* purpose: Send Messages to Module Process Monitors to stop Processes -* -*****************************************************************************************/ -void stopSystemThread(oam::DeviceNetworkList Devicenetworklist) -{ - oam::DeviceNetworkList devicenetworklist = Devicenetworklist; - - ProcessLog log; - Configuration config; - ProcessManager processManager(config, log); - Oam oam; - SystemModuleTypeConfig systemmoduletypeconfig; - SNMPManager aManager; - int status = API_SUCCESS; - bool exitThread = false; - int exitThreadStatus = oam::API_SUCCESS; - - pthread_t ThreadId; - ThreadId = pthread_self(); - - log.writeLog(__LINE__, "stopSystemThread launched", LOG_TYPE_DEBUG); - - try{ - oam.getSystemConfig(systemmoduletypeconfig); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: " + error, LOG_TYPE_ERROR); - stopsystemthreadStatus = oam::API_FAILURE; - processManager.setSystemState(oam::FAILED); - exitThread = true; - exitThreadStatus = oam::API_FAILURE; - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: Caught unknown exception!", LOG_TYPE_ERROR); - stopsystemthreadStatus = oam::API_FAILURE; - processManager.setSystemState(oam::FAILED); - exitThread = true; - exitThreadStatus = oam::API_FAILURE; - } - - if ( devicenetworklist.size() != 0 ) { - // stop modules from devicenetworklist - DeviceNetworkList::iterator listPT = devicenetworklist.begin(); - - //launch start module threads, starting with local module - pthread_t stopmodulethread; - string moduleName = config.moduleName(); - int status = pthread_create (&stopmodulethread, NULL, (void*(*)(void*)) &stopModuleThread, &moduleName); - - if ( status != 0 ) - log.writeLog(__LINE__, "stopModuleThread: pthread_create failed, return status = " + oam.itoa(status), LOG_TYPE_ERROR); - - for( ; listPT != devicenetworklist.end() ; listPT++) - { - string moduleName = (*listPT).DeviceName; - - // bypass DISABLED modules - try{ - int opState; - bool degraded; - oam.getModuleStatus(moduleName, opState, degraded); - - if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) - //skip - continue; - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); - } - - pthread_t stopmodulethread; - int status = pthread_create (&stopmodulethread, NULL, (void*(*)(void*)) &stopModuleThread, &moduleName); - - if ( status != 0 ) - log.writeLog(__LINE__, "stopModuleThread: pthread_create failed, return status = " + oam.itoa(status), LOG_TYPE_ERROR); - - sleep(5); - } - } - else { - // stop all modules, like on a systemStart command - //launch stop module threads, stoping with local module - - for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++) - { - string moduleName = (*pt).DeviceName; - - // bypass DISABLED modules - try{ - int opState; - bool degraded; - oam.getModuleStatus(moduleName, opState, degraded); - - if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) - //skip - continue; - - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); - } - - pthread_t stopmodulethread; - string name = moduleName; - int status = pthread_create (&stopmodulethread, NULL, (void*(*)(void*)) &stopModuleThread, &name); - - if ( status != 0 ) - log.writeLog(__LINE__, "stopModuleThread: pthread_create failed, return status = " + oam.itoa(status), LOG_TYPE_ERROR); - - usleep(50000); - } - } - } - - // check status and process accordingly - int k = 0; - for( ; k < 1200 ; k++ ) - { - string moduleName; - status = API_SUCCESS; - for( unsigned int i = 0 ; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++) - { - moduleName = (*pt).DeviceName; - - // get module status - try{ - int opState; - bool degraded; - oam.getModuleStatus(moduleName, opState, degraded); - - if ( opState == oam::FAILED ) { - status = API_FAILURE; - break; - } - - if (opState == oam::MAN_DISABLED || - opState == oam::AUTO_DISABLED || - opState == oam::MAN_OFFLINE) - //skip - continue; - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": " + error, LOG_TYPE_ERROR); - continue; - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); - continue; - } - } - - if( status == API_FAILURE ) - break; - } - - //get out of loop if all modules stopped successfully - if( status == API_SUCCESS ) { - break; - } - else - { - //get out of loop if stop module failed - if( status == API_FAILURE ) { - //set system status - log.writeLog(__LINE__, "stopSystemThread: Module failed, Set System State to FAILED: " + moduleName , LOG_TYPE_CRITICAL); - processManager.setSystemState(oam::FAILED); - break; - } - } - sleep(5); - } - - if ( k == 1200 ) { - // system didn't Successfully restart - log.writeLog(__LINE__, "stopSystemThread: Modules failed to stop after 1200 tries, Set System State to FAILED" , LOG_TYPE_CRITICAL); - processManager.setSystemState(oam::FAILED); - status = oam::API_FAILURE; - } - else - { - processManager.setSystemState(oam::MAN_OFFLINE); - status = oam::API_SUCCESS; - } - - // exit thread - stopsystemthreadStatus = status; - log.writeLog(__LINE__, "stopSystemThread Exit", LOG_TYPE_DEBUG); - pthread_detach (ThreadId); - pthread_exit(0); -} - -/***************************************************************************************** -* @brief stopModuleThread -* -* purpose: Send Messages to Module Process Monitors to stop Processes -* -*****************************************************************************************/ -void stopModuleThread(string module) -{ - //store in a local variable - string moduleName = module; - - ProcessLog log; - Configuration config; - ProcessManager processManager(config, log); - Oam oam; - - pthread_t ThreadId; - ThreadId = pthread_self(); - - if ( moduleName.empty() ){ - log.writeLog(__LINE__, "stopModuleThread received on invalid module name", LOG_TYPE_ERROR); - pthread_detach (ThreadId); - pthread_exit(0); - } - - log.writeLog(__LINE__, "Stop Module " + moduleName, LOG_TYPE_DEBUG); - - while(true) - { - // get module status - try{ - int opState; - bool degraded; - oam.getModuleStatus(moduleName, opState, degraded); - - if (opState == oam::MAN_OFFLINE) - //quit - break; - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getModuleStatus on module " + moduleName + ": Caught unknown exception!", LOG_TYPE_ERROR); + if ( startsystemthreadStop) { + // set status and exit this thread + processManager.setModuleState(moduleName, oam::MAN_OFFLINE); + log.writeLog(__LINE__, "startModuleThread early exit on " + moduleName, LOG_TYPE_DEBUG); + pthread_detach (ThreadId); + pthread_exit(0); } - int retStatus = processManager.stopModule(moduleName, oam::GRACEFUL, true); + int retStatus = processManager.startModule(moduleName, oam::FORCEFUL, startType, true); log.writeLog(__LINE__, "ACK received from '" + moduleName + "' Process-Monitor, return status = " + oam.itoa(retStatus), LOG_TYPE_DEBUG); @@ -7055,13 +6344,15 @@ void stopModuleThread(string module) { if (retStatus != API_MINOR_FAILURE) { //major failure, set stopsystem flag and exit this thread + startmodulethreadStatus = retStatus; + startsystemthreadStop = true; break; } } } // exit thread - log.writeLog(__LINE__, "stopModuleThread Exit on " + moduleName, LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "startModuleThread Exit on " + moduleName, LOG_TYPE_DEBUG); pthread_detach (ThreadId); pthread_exit(0); } @@ -7121,8 +6412,7 @@ void ProcessManager::checkSimplexModule(std::string moduleName) bool degraded; oam.getModuleStatus((*pt).DeviceName, opState, degraded); - if (opState == oam::ACTIVE || - opState == oam::DEGRADED ) { + if (opState == oam::ACTIVE ) { //start COLD_STANDBY processes try { oam.getProcessConfig(systemprocessconfig); @@ -7149,22 +6439,7 @@ void ProcessManager::checkSimplexModule(std::string moduleName) log.writeLog(__LINE__, "EXCEPTION ERROR on getProcessStatus: Caught unknown exception!", LOG_TYPE_ERROR); continue; } - if ( state == oam::COLD_STANDBY ) { - //set Primary UM Module - if ( systemprocessconfig.processconfig[j].ProcessName == "DDLProc" ) { - oam.setSystemConfig("PrimaryUMModuleName", (*pt).DeviceName); - - //distribute config file - distributeConfigFile("system"); - sleep(2); - - //add MySQL Replication setup, if needed - log.writeLog(__LINE__, "Setup MySQL Replication for COLD_STANDBY DMLProc going ACTIVE", LOG_TYPE_DEBUG); - oam::DeviceNetworkList devicenetworklist; - processManager.setMySQLReplication(devicenetworklist, (*pt).DeviceName); - } - int status = processManager.startProcess((*pt).DeviceName, systemprocessconfig.processconfig[j].ProcessName, FORCEFUL); @@ -7172,8 +6447,9 @@ void ProcessManager::checkSimplexModule(std::string moduleName) log.writeLog(__LINE__, "checkSimplexModule: mate process started: " + (*pt).DeviceName + "/" + systemprocessconfig.processconfig[j].ProcessName, LOG_TYPE_DEBUG); //check to see if DDL/DML IPs need to be updated - if ( systemprocessconfig.processconfig[j].ProcessName == "DDLProc" ) + if ( (*pt).DeviceName.find("um") == 0 && systemprocessconfig.processconfig[j].ProcessName == "DDLProc" ) { setPMProcIPs((*pt).DeviceName); + } } else log.writeLog(__LINE__, "checkSimplexModule: mate process failed to start: " + (*pt).DeviceName + "/" + systemprocessconfig.processconfig[j].ProcessName, LOG_TYPE_DEBUG); @@ -7210,9 +6486,8 @@ void ProcessManager::checkSimplexModule(std::string moduleName) } } } + return; } - - return; } /****************************************************************************************** @@ -7224,7 +6499,7 @@ void ProcessManager::checkSimplexModule(std::string moduleName) int ProcessManager::updatePMSconfig( bool check ) { Oam oam; - int minPmPorts = 32; + int pmPorts = 32; vector IpAddrs; vector nicIDs; @@ -7339,10 +6614,6 @@ int ProcessManager::updatePMSconfig( bool check ) //update PM count if needed sysConfig1->setConfig("PrimitiveServers", "Count", oam.itoa(pmCount)); - int pmPorts = pmCount * (maxPMNicID*2); - if ( pmPorts < minPmPorts ) - pmPorts = minPmPorts; - const string PM = "PMS"; int nicID = 1; @@ -7821,10 +7092,11 @@ int ProcessManager::distributeConfigFile(std::string name, std::string file) Oam oam; int returnStatus = oam::API_SUCCESS; - log.writeLog(__LINE__, "distributeConfigFile called for " + name + " file = " + file, LOG_TYPE_DEBUG); + msg << requestID; + + string fileName = startup::StartUp::installDir() + "/etc/" + file; - string dirName = startup::StartUp::installDir() + "/etc/"; - string fileName = dirName + file; + msg << fileName; ifstream in (fileName.c_str()); if (!in) { @@ -7832,6 +7104,17 @@ int ProcessManager::distributeConfigFile(std::string name, std::string file) return oam::API_FAILURE; } +/* char line[1000]; + string buf; + string calpontFile; + + while (File.getline(line, 1000)) + { + buf = line; + calpontFile = calpontFile + buf + '\n'; + } +*/ + //skip any file of size 0 in.seekg(0, std::ios::end); int size = in.tellg(); @@ -7840,52 +7123,6 @@ int ProcessManager::distributeConfigFile(std::string name, std::string file) return oam::API_FAILURE; } - // distribute using hdfs call, make sure host names are in /etc/pdsh/machines - ifstream in1 ("/etc/pdsh/machines"); - if (in1) { - if ( HDFS ) - { - if ( name == "system" ) - { - string cmd = "pdcp -a -x " + localHostName + " " + fileName + " " + dirName; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) - { - log.writeLog(__LINE__, "distributeConfigFile using pdcp successful on " + fileName, LOG_TYPE_DEBUG); - return returnStatus; - } - else - { - log.writeLog(__LINE__, "distributeConfigFile using pdcp failed on " + fileName, LOG_TYPE_ERROR); - } - } - else - { - // get module hostname - ModuleConfig moduleconfig; - oam.getSystemConfig(name, moduleconfig); - HostConfigList::iterator pt1 = moduleconfig.hostConfigList.begin(); - string hostName = (*pt1).HostName; - - string cmd = "pdcp -w " + hostName + " " + fileName + " " + dirName; - int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) - { - log.writeLog(__LINE__, "distributeConfigFile using pdcp successful on " + fileName, LOG_TYPE_DEBUG); - return returnStatus; - } - else - { - log.writeLog(__LINE__, "distributeConfigFile using pdcp failed on " + fileName, LOG_TYPE_ERROR); - } - } - } - } - - //send via tcp messaging - msg << requestID; - msg << fileName; - in.seekg(0, std::ios::beg); in >> msg; @@ -7971,7 +7208,7 @@ int ProcessManager::distributeConfigFile(std::string name, std::string file) * purpose: get DBRM Data and send to requester * ******************************************************************************************/ -int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos, std::string moduleName) +int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos) { ByteStream msg; Oam oam; @@ -7983,10 +7220,10 @@ int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos, std::string moduleNa string DBRMroot; oam.getSystemConfig("DBRMRoot", DBRMroot); - string currentFileName = DBRMroot + "_current"; string journalFileName = DBRMroot + "_journal"; + string oidFile; oam.getSystemConfig("OIDBitmapFile", oidFile); @@ -8008,7 +7245,7 @@ int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos, std::string moduleNa } else { - log.writeLog(__LINE__, "getDBRMData: no DBRM current file found, must be initial install", LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "getDBRMData: no DBRM current file found, must be initial install", LOG_TYPE_ERROR); msg << "initial"; try { @@ -8037,7 +7274,7 @@ int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos, std::string moduleNa ifstream file (fileName.c_str()); if (!file) { - log.writeLog(__LINE__, "getDBRMData: no DBRM files found, must be initial install", LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "getDBRMData: no DBRM files found, must be initial install", LOG_TYPE_ERROR); msg << "initial"; try { @@ -8071,7 +7308,7 @@ int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos, std::string moduleNa file.close(); if ( dbrmFiles.size() < 1 ) { - log.writeLog(__LINE__, "getDBRMData: dbrmFiles size = 0, must be initial install", LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "getDBRMData: dbrmFiles size = 0, must be initial install", LOG_TYPE_ERROR); msg << "initial"; try { @@ -8224,7 +7461,6 @@ int ProcessManager::getDBRMData(messageqcpp::IOSocket fIos, std::string moduleNa return returnStatus; } - /****************************************************************************************** * @brief switchParentOAMModule * @@ -8338,28 +7574,13 @@ int ProcessManager::switchParentOAMModule(std::string newActiveModuleName) pthread_mutex_unlock(&THREAD_LOCK); if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) - { - //set DDL/DMLproc IPs to new module + //set DDL/DMLproc IPs to local module setPMProcIPs(newActiveModuleName); - //set Primary UM to new module - try { - oam.setSystemConfig("PrimaryUMModuleName", newActiveModuleName); - } - catch(...) {} - } - - log.writeLog(__LINE__, "Calpont.xml entries update to local IP address of " + newActiveIPaddr, LOG_TYPE_DEBUG); - //distribute config file - processManager.distributeConfigFile("system"); - sleep(1); - - //change master MySQL Replication setup - log.writeLog(__LINE__, "Setup MySQL Replication for new Parent Module during switch-over", LOG_TYPE_DEBUG); - oam::DeviceNetworkList devicenetworklist; - processManager.setMySQLReplication(devicenetworklist, newActiveModuleName); + distributeConfigFile("system"); + log.writeLog(__LINE__, "Calpont.xml entries update to local IP address of " + newActiveIPaddr, LOG_TYPE_DEBUG); } catch (exception& ex) { @@ -8421,24 +7642,6 @@ int ProcessManager::switchParentOAMModule(std::string newActiveModuleName) // clear alarm aManager.sendAlarmReport(newActiveModuleName.c_str(), MODULE_SWITCH_ACTIVE, CLEAR); - //DOING THIS JUST TO UPDATE THE TIMESTAMP OF THE CALPONT.XML FILE AS A WORK-AROUND FIX - //BECAUSE PROCMON ISN'T READING UPDATES FROM DISK ON HDFS SYSTEMS - - if (HDFS) - { - sleep(60); - Config* sysConfig = Config::makeConfig(); - try { - sysConfig->write(); - } - catch(...) - { - log.writeLog(__LINE__, "ERROR: sysConfig->write", LOG_TYPE_ERROR); - pthread_mutex_unlock(&THREAD_LOCK); - return API_FAILURE; - } - } - return returnStatus; } @@ -8572,11 +7775,31 @@ int ProcessManager::OAMParentModuleChange() break; } + oam::LicenseKeyChecker keyChecker; + + bool keyGood = true; + try { + keyGood = keyChecker.isGood(); + } + catch(...) + { + keyGood = false; + } + + if (!keyGood) + { + log.writeLog(__LINE__, "Your trial period has expired.", LOG_TYPE_CRITICAL); + //sleep until system gets stopped + while(true) { + sleep(100000); + } + } + // perform ping test of Active Parent Module string cmd = cmdLine + downOAMParentIPAddress + cmdOption; int rtnCode = system(cmd.c_str()); - switch (WEXITSTATUS(rtnCode)) { + switch (rtnCode) { case 0: { //Ack ping @@ -8671,7 +7894,7 @@ int ProcessManager::OAMParentModuleChange() string cmd = cmdLine + *pt2 + cmdOption; int rtnCode = system(cmd.c_str()); - switch (WEXITSTATUS(rtnCode)) { + switch (rtnCode) { case 0: { //Ack ping log.writeLog(__LINE__, *pt1 + " ping successful", LOG_TYPE_DEBUG); @@ -8797,7 +8020,7 @@ int ProcessManager::OAMParentModuleChange() {} //do amazon failover - if (amazon) + if ( cloud == "amazon" ) { log.writeLog(__LINE__, " ", LOG_TYPE_DEBUG); log.writeLog(__LINE__, "*** OAMParentModule outage, recover the Instance ***", LOG_TYPE_DEBUG); @@ -8962,16 +8185,10 @@ int ProcessManager::OAMParentModuleChange() return API_FAILURE; } - if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) { + if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) //set DDL/DMLproc IPs to local module setPMProcIPs(config.moduleName()); - try { - oam.setSystemConfig("PrimaryUMModuleName", config.moduleName()); - } - catch(...) {} - } - //send message to local Process Monitor for OAM Parent Activation ByteStream msg; ByteStream::byte requestID = OAMPARENTACTIVE; @@ -9155,25 +8372,19 @@ int ProcessManager::OAMParentModuleChange() //restart DDLProc/DMLProc to perform any rollbacks, if needed //dont rollback in amazon, wait until down pm recovers - if ( ( config.ServerInstallType() != oam::INSTALL_COMBINE_DM_UM_PM ) && - !amazon) { + if ( config.ServerInstallType() != oam::INSTALL_COMBINE_DM_UM_PM && + cloud != "amazon") { processManager.restartProcessType("DDLProc"); sleep(1); processManager.restartProcessType("DMLProc"); } - if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) - { - //change master MySQL Replication setup - log.writeLog(__LINE__, "Setup this node as MySQL Replication Master", LOG_TYPE_DEBUG); - oam::DeviceNetworkList devicenetworklist; - processManager.setMySQLReplication(devicenetworklist, config.moduleName(), true); - } + processManager.setSystemState(oam::ACTIVE); // clear alarm aManager.sendAlarmReport(config.moduleName().c_str(), MODULE_SWITCH_ACTIVE, CLEAR); - if (amazon) { + if ( cloud == "amazon") { //Set the down module instance state so it will be auto restarted processManager.setModuleState(downOAMParentName, oam::AUTO_OFFLINE); @@ -9297,23 +8508,23 @@ std::string ProcessManager::getStandbyModule() systemprocessstatus.processstatus[i].ProcessOpState == oam::MAN_OFFLINE && backupStandbyModule == "NONE" && newStandbyModule == "NONE" ) - { // Found a ProcessManager in a MAN_OFFLINE state, use if no COLD_STANDBY is found // and module is not disabled - int opState; - bool degraded; - try { - oam.getModuleStatus(systemprocessstatus.processstatus[i].Module, opState, degraded); - } - catch(...) - {} + { + int opState; + bool degraded; + try { + oam.getModuleStatus(systemprocessstatus.processstatus[i].Module, opState, degraded); + } + catch(...) + {} - if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) { - continue; + if (opState == oam::MAN_DISABLED || opState == oam::AUTO_DISABLED) { + continue; + } + else + backupStandbyModule = systemprocessstatus.processstatus[i].Module; } - else - backupStandbyModule = systemprocessstatus.processstatus[i].Module; - } } } catch (exception& ex) @@ -9575,7 +8786,7 @@ void sendUpgradeRequest() if ( exitThread ) { pthread_detach (ThreadId); - pthread_exit(reinterpret_cast(static_cast(exitThreadStatus))); + pthread_exit((void*) exitThreadStatus); } ByteStream msg; @@ -9604,8 +8815,7 @@ void sendUpgradeRequest() try { oam.getModuleStatus((*pt).DeviceName, opState, degraded); - if (opState == oam::ACTIVE || - opState == oam::DEGRADED) { + if (opState == oam::ACTIVE) { returnStatus = processManager.sendMsgProcMon( (*pt).DeviceName, msg, requestID, 30 ); upgradethreadStatus = returnStatus; @@ -9658,17 +8868,13 @@ void ProcessManager::stopProcessTypes(bool manualFlag) log.writeLog(__LINE__, "stopProcessTypes Called"); - //front-end first processManager.stopProcessType("mysql", manualFlag); processManager.stopProcessType("DMLProc", manualFlag); processManager.stopProcessType("DDLProc", manualFlag); - processManager.stopProcessType("ExeMgr", manualFlag); - //back-end - processManager.stopProcessType("WriteEngineServer", manualFlag); + processManager.stopProcessType("ExeMgr", manualFlag); processManager.stopProcessType("PrimProc", manualFlag); - //dbrm processManager.stopProcessType("DBRMControllerNode", manualFlag); processManager.stopProcessType("DBRMWorkerNode", manualFlag); @@ -9792,255 +8998,6 @@ void ProcessManager::flushInodeCache() #endif } -/****************************************************************************************** -* @brief setMySQLReplication -* -* purpose: setMySQLReplication -* -* -******************************************************************************************/ -int ProcessManager::setMySQLReplication(oam::DeviceNetworkList devicenetworklist, std::string masterModule, bool failover, bool distributeDB, std::string password) -{ - Oam oam; - - string MySQLRep = "n"; - try { - oam.getSystemConfig("MySQLRep", MySQLRep); - } - catch(...) { - MySQLRep = "n"; - } - - if ( MySQLRep == "n" ) - return oam::API_SUCCESS; - - //also skip if single-server, multi-node seperate with 1 UM, multi-node combo with 1 PM - - string SingleServerInstall = "n"; - try { - oam.getSystemConfig("SingleServerInstall", SingleServerInstall); - } - catch(...) { - SingleServerInstall = "n"; - } - - //single server check - if ( SingleServerInstall == "y" ) - return oam::API_SUCCESS; - - //combined system check - if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM && !failover ) { - try { - Config* sysConfig = Config::makeConfig(); - if ( sysConfig->getConfig("DBRM_Controller", "NumWorkers") == "1" ) - return oam::API_SUCCESS; - } - catch(...) - { - return oam::API_SUCCESS; - } - } - - //seperate system check - if ( config.ServerInstallType() != oam::INSTALL_COMBINE_DM_UM_PM ) { - ModuleTypeConfig moduletypeconfig; - try{ - oam.getSystemConfig("um", moduletypeconfig); - } - catch(...) - {} - - if ( moduletypeconfig.ModuleCount < 1 ) - return oam::API_SUCCESS; - } - - log.writeLog(__LINE__, "Setup MySQL Replication", LOG_TYPE_DEBUG); - - //get master info - if ( masterModule == oam::UnassignedName) - { - try { - oam.getSystemConfig("PrimaryUMModuleName", masterModule); - } - catch(...) { - masterModule = oam::UnassignedName; - } - - if ( masterModule == oam::UnassignedName ) - { - // use default setting - masterModule = "um1"; - if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) - masterModule = "pm1"; - } - } - - //send distubute DB - if ( distributeDB ) - { - if ( devicenetworklist.size() == 0 ) - { //dist to all slaves - ByteStream msg; - ByteStream::byte requestID = oam::MASTERDIST; - msg << requestID; - msg << password; - msg << "all"; - - log.writeLog(__LINE__, "Distribute Master DB, master module=" + masterModule, LOG_TYPE_DEBUG); - - int returnStatus = sendMsgProcMon( masterModule, msg, requestID, 60 ); - - if ( returnStatus != API_SUCCESS) { - log.writeLog(__LINE__, "setMySQLReplication: ERROR: Error getting MySQL Replication Master Information", LOG_TYPE_ERROR); - pthread_mutex_unlock(&THREAD_LOCK); - return API_FAILURE; - } - } - else - { - DeviceNetworkList::iterator listPT = devicenetworklist.begin(); - for( ; listPT != devicenetworklist.end() ; listPT++) - { - string remoteModuleName = (*listPT).DeviceName; - - //skip master - if ( remoteModuleName == masterModule ) - continue; - - ByteStream msg; - ByteStream::byte requestID = oam::MASTERDIST; - msg << requestID; - msg << password; - msg << remoteModuleName; - - log.writeLog(__LINE__, "Distribute Master DB, master module=" + masterModule, LOG_TYPE_DEBUG); - - int returnStatus = sendMsgProcMon( masterModule, msg, requestID, 60 ); - - if ( returnStatus != API_SUCCESS) { - log.writeLog(__LINE__, "setMySQLReplication: ERROR: Error getting MySQL Replication Master Information", LOG_TYPE_ERROR); - pthread_mutex_unlock(&THREAD_LOCK); - return API_FAILURE; - } - } - } - } - - //send setup master - ByteStream msg; - ByteStream::byte requestID = oam::MASTERREP; - msg << requestID; - string mysqlpw = " "; - msg << mysqlpw; - - log.writeLog(__LINE__, "Setup MySQL Replication, master module=" + masterModule, LOG_TYPE_DEBUG); - - int returnStatus = sendMsgProcMon( masterModule, msg, requestID, 30 ); - - if ( returnStatus != API_SUCCESS) { - log.writeLog(__LINE__, "setMySQLReplication: ERROR: Error getting MySQL Replication Master Information", LOG_TYPE_ERROR); - pthread_mutex_unlock(&THREAD_LOCK); - return API_FAILURE; - } - - // - // send msg to setup slave - // - - // check if a list was provide, if not, do all modules - if ( devicenetworklist.size() == 0 ) - { - SystemModuleTypeConfig systemmoduletypeconfig; - - try{ - oam.getSystemConfig(systemmoduletypeconfig); - } - catch (exception& ex) - {} - - for( unsigned int i = 0; i < systemmoduletypeconfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemmoduletypeconfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - - string moduleType = systemmoduletypeconfig.moduletypeconfig[i].ModuleType; - - DeviceNetworkList::iterator pt = systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for ( ; pt != systemmoduletypeconfig.moduletypeconfig[i].ModuleNetworkList.end(); pt++ ) - { - string remoteModuleName = (*pt).DeviceName; - - //skip master - if ( remoteModuleName == masterModule ) - continue; - - // don't do PMs unless PMwithUM flag is set - if ( config.ServerInstallType() != oam::INSTALL_COMBINE_DM_UM_PM ) { - string moduleType = remoteModuleName.substr(0,MAX_MODULE_TYPE_SIZE); - if ( moduleType == "pm" && PMwithUM == "n" ) - continue; - } - - ByteStream msg1; - ByteStream::byte requestID = oam::SLAVEREP; - msg1 << requestID; - msg1 << mysqlpw; - - if ( masterLogFile == oam::UnassignedName || - masterLogPos == oam::UnassignedName ) - return API_FAILURE; - - msg1 << masterLogFile; - msg1 << masterLogPos; - - log.writeLog(__LINE__, "Setup MySQL Replication, slave module=" + remoteModuleName, LOG_TYPE_DEBUG); - - returnStatus = sendMsgProcMon( remoteModuleName, msg1, requestID, 30 ); - - if ( returnStatus != API_SUCCESS) { - log.writeLog(__LINE__, "setMySQLReplication: ERROR: Error setting MySQL Replication Slave", LOG_TYPE_ERROR); - } - } - } - } - else - { - DeviceNetworkList::iterator listPT = devicenetworklist.begin(); - for( ; listPT != devicenetworklist.end() ; listPT++) - { - string remoteModuleName = (*listPT).DeviceName; - - //skip master - if ( remoteModuleName == masterModule ) - continue; - - ByteStream msg1; - ByteStream::byte requestID = oam::SLAVEREP; - msg1 << requestID; - msg1 << mysqlpw; - - if ( masterLogFile == oam::UnassignedName || - masterLogPos == oam::UnassignedName ) - { - log.writeLog(__LINE__, "setMySQLReplication: ERROR: Unassigned masterLogFile or masterLogPos", LOG_TYPE_ERROR); - return API_FAILURE; - } - - msg1 << masterLogFile; - msg1 << masterLogPos; - - returnStatus = sendMsgProcMon( remoteModuleName, msg1, requestID, 30 ); - - if ( returnStatus != API_SUCCESS) { - log.writeLog(__LINE__, "setMySQLReplication: ERROR: Error setting MySQL Replication Slave", LOG_TYPE_ERROR); - } - } - } - - return oam::API_SUCCESS; -} - } //end of namespace // vim:ts=4 sw=4: diff --git a/procmgr/processmanager.h b/procmgr/processmanager.h index ce2c3a72..61709554 100644 --- a/procmgr/processmanager.h +++ b/procmgr/processmanager.h @@ -1,22 +1,5 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /****************************************************************************************** -* $Id: processmanager.h 2163 2013-04-04 18:40:54Z rdempsey $ +* $Id: processmanager.h 2051 2012-11-29 21:09:31Z dhill $ * ******************************************************************************************/ @@ -71,12 +54,11 @@ void pingDeviceThread(); + namespace processmanager{ void startSystemThread(oam::DeviceNetworkList devicenetworklist); - void stopSystemThread(oam::DeviceNetworkList devicenetworklist); void startModuleThread(std::string moduleName); - void stopModuleThread(std::string moduleName); void processMSG(messageqcpp::IOSocket* fIos); void sendUpgradeRequest(); @@ -285,12 +267,12 @@ class ProcessManager /** *@brief Stop all processes on the specified module */ - int stopModule(std::string target, messageqcpp::ByteStream::byte actionIndicator, bool manualFlag, int timeout = 240 ); + int stopModule(std::string target, messageqcpp::ByteStream::byte actionIndicator, bool manualFlag); /** *@brief power off the specified module */ - int shutdownModule(std::string target, messageqcpp::ByteStream::byte actionIndicator, bool manualFlag, int timeout = 10 ); + int shutdownModule(std::string target, messageqcpp::ByteStream::byte actionIndicator, bool manualFlag); /** *@brief Disable a specified module @@ -322,7 +304,7 @@ class ProcessManager /** *@brief stop process on a specific module */ - int stopProcess(std::string moduleName, std::string processName, messageqcpp::ByteStream::byte actionIndicator, bool manualFlag, int timeout = 10); + int stopProcess(std::string moduleName, std::string processName, messageqcpp::ByteStream::byte actionIndicator, bool manualFlag); /** *@brief start process on a specific module @@ -493,7 +475,7 @@ class ProcessManager /** @brief get DBRM Data and send to requester */ - int getDBRMData(messageqcpp::IOSocket fIos, std::string moduleName); + int getDBRMData(messageqcpp::IOSocket fIos); /** @brief remount the dbroot disk */ @@ -530,10 +512,6 @@ class ProcessManager */ int updateFstab(std::string moduleName, std::string entry); - /** @brief Set MySQL Replication - */ - int setMySQLReplication(oam::DeviceNetworkList devicenetworklist, std::string masterModule = oam::UnassignedName, bool failover = false, bool distributeDB = false, std::string password = oam::UnassignedName); - private: diff --git a/procmon/Makefile.am b/procmon/Makefile.am index 238e3c28..20b774c2 100644 --- a/procmon/Makefile.am +++ b/procmon/Makefile.am @@ -1,20 +1,3 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/procmon/Makefile.in b/procmon/Makefile.in deleted file mode 100644 index c649b98e..00000000 --- a/procmon/Makefile.in +++ /dev/null @@ -1,545 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = .. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = ProcMon$(EXEEXT) -subdir = procmon -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_ProcMon_OBJECTS = ProcMon-main.$(OBJEXT) \ - ProcMon-processmonitor.$(OBJEXT) -ProcMon_OBJECTS = $(am_ProcMon_OBJECTS) -ProcMon_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(ProcMon_SOURCES) -DIST_SOURCES = $(ProcMon_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -ProcMon_SOURCES = main.cpp processmonitor.cpp -ProcMon_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -ProcMon_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lcacheutils $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu procmon/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu procmon/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -ProcMon$(EXEEXT): $(ProcMon_OBJECTS) $(ProcMon_DEPENDENCIES) - @rm -f ProcMon$(EXEEXT) - $(CXXLINK) $(ProcMon_LDFLAGS) $(ProcMon_OBJECTS) $(ProcMon_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ProcMon-main.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ProcMon-processmonitor.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -ProcMon-main.o: main.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMon-main.o -MD -MP -MF "$(DEPDIR)/ProcMon-main.Tpo" -c -o ProcMon-main.o `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMon-main.Tpo" "$(DEPDIR)/ProcMon-main.Po"; else rm -f "$(DEPDIR)/ProcMon-main.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='ProcMon-main.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMon-main.o `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp - -ProcMon-main.obj: main.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMon-main.obj -MD -MP -MF "$(DEPDIR)/ProcMon-main.Tpo" -c -o ProcMon-main.obj `if test -f 'main.cpp'; then $(CYGPATH_W) 'main.cpp'; else $(CYGPATH_W) '$(srcdir)/main.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMon-main.Tpo" "$(DEPDIR)/ProcMon-main.Po"; else rm -f "$(DEPDIR)/ProcMon-main.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='ProcMon-main.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMon-main.obj `if test -f 'main.cpp'; then $(CYGPATH_W) 'main.cpp'; else $(CYGPATH_W) '$(srcdir)/main.cpp'; fi` - -ProcMon-processmonitor.o: processmonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMon-processmonitor.o -MD -MP -MF "$(DEPDIR)/ProcMon-processmonitor.Tpo" -c -o ProcMon-processmonitor.o `test -f 'processmonitor.cpp' || echo '$(srcdir)/'`processmonitor.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMon-processmonitor.Tpo" "$(DEPDIR)/ProcMon-processmonitor.Po"; else rm -f "$(DEPDIR)/ProcMon-processmonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='processmonitor.cpp' object='ProcMon-processmonitor.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMon-processmonitor.o `test -f 'processmonitor.cpp' || echo '$(srcdir)/'`processmonitor.cpp - -ProcMon-processmonitor.obj: processmonitor.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT ProcMon-processmonitor.obj -MD -MP -MF "$(DEPDIR)/ProcMon-processmonitor.Tpo" -c -o ProcMon-processmonitor.obj `if test -f 'processmonitor.cpp'; then $(CYGPATH_W) 'processmonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/processmonitor.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/ProcMon-processmonitor.Tpo" "$(DEPDIR)/ProcMon-processmonitor.Po"; else rm -f "$(DEPDIR)/ProcMon-processmonitor.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='processmonitor.cpp' object='ProcMon-processmonitor.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(ProcMon_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o ProcMon-processmonitor.obj `if test -f 'processmonitor.cpp'; then $(CYGPATH_W) 'processmonitor.cpp'; else $(CYGPATH_W) '$(srcdir)/processmonitor.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/procmon/main.cpp b/procmon/main.cpp index ffb5fe2f..82a68297 100644 --- a/procmon/main.cpp +++ b/procmon/main.cpp @@ -1,19 +1,10 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ +/****************************************************************************************** +* $Id: main.cpp 1976 2013-02-08 16:50:01Z dhill $ +* +* Copyright (C) 2009-2012 Calpont Corporation +* +* All rights reserved +******************************************************************************************/ #include #include @@ -23,8 +14,6 @@ namespace bi=boost::interprocess; #include "processmonitor.h" #include "installdir.h" -#include "IDBPolicy.h" - using namespace std; using namespace messageqcpp; using namespace processmonitor; @@ -32,7 +21,6 @@ using namespace oam; using namespace logging; using namespace snmpmanager; using namespace config; -using namespace idbdatafile; //using namespace procheartbeat; @@ -47,7 +35,6 @@ string systemOAM; string dm_server; string cloud; string GlusterConfig = "n"; -bool HDFS = false; void updateShareMemory(processStatusList* aPtr); @@ -55,7 +42,6 @@ bool runStandby = false; bool processInitComplete = false; bool rootUser = true; string USER = "root"; -string PMwithUM = "n"; //extern std::string gOAMParentModuleName; extern bool gOAMParentModuleFlag; @@ -88,9 +74,6 @@ int main(int argc, char **argv) open("/dev/null", O_WRONLY); } - // setup environment for using HDFS. - idbdatafile::IDBPolicy::configIDBPolicy(); - Oam oam; MonitorLog log; MonitorConfig config; @@ -117,25 +100,18 @@ int main(int argc, char **argv) if (p && *p) USER = p; - // change permissions on /dev/shm - string cmd = "chmod 777 /dev/shm >/dev/null 2>&1"; - if ( !rootUser) - cmd = "sudo chmod 777 /dev/shm >/dev/null 2>&1"; - - system(cmd.c_str()); - - // get and set locale language + // get and set locale language string systemLang = "C"; try{ - oam.getSystemConfig("SystemLang", systemLang); - } - catch(...) - { + oam.getSystemConfig("SystemLang", systemLang); + } + catch(...) + { systemLang = "C"; } - setlocale(LC_ALL, systemLang.c_str()); + setlocale(LC_ALL, systemLang.c_str()); // if amazon cloud, check and update Instance IP Addresses and volumes try { @@ -143,7 +119,7 @@ int main(int argc, char **argv) } catch(...) {} - if ( cloud == "amazon-ec2" ) { + if ( cloud == "amazon" ) { if(!aMonitor.amazonIPCheck()) { string cmd = startup::StartUp::installDir() + "/bin/infinidb stop > /dev/null 2>&1"; system(cmd.c_str()); @@ -164,24 +140,6 @@ int main(int argc, char **argv) system("mount -a > /dev/null 2>&1"); } - //hdfs / hadoop config - string DBRootStorageType; - try { - oam.getSystemConfig( "DBRootStorageType", DBRootStorageType); - } - catch(...) {} - - if ( DBRootStorageType == "hdfs" ) - HDFS = true; - - //PMwithUM config - try { - oam.getSystemConfig( "PMwithUM", PMwithUM); - } - catch(...) { - PMwithUM = "n"; - } - //define entry if missing Config* sysConfig = Config::makeConfig(); if ( gOAMParentModuleFlag ) @@ -292,8 +250,8 @@ int main(int argc, char **argv) } // not active Parent, get updated Calpont.xml, retry in case ProcMgr isn't up yet - if ( !gOAMParentModuleFlag && !HDFS) - { + if ( !gOAMParentModuleFlag ) + { int count = 0; while(true) { @@ -332,17 +290,11 @@ int main(int argc, char **argv) try { bool degraded; oam.getModuleStatus(config.moduleName(), moduleStatus, degraded); - // if HDFS, wait until module state is MAN_INIT before continuing - if (HDFS) - { - if ( moduleStatus == oam::MAN_INIT) - break; - } break; } catch(...) { - log.writeLog(__LINE__, "wating for good return from getModuleStatus", LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "error return from getModuleStatus", LOG_TYPE_DEBUG); sleep (1); } } @@ -402,9 +354,35 @@ int main(int argc, char **argv) if ( ret != 0 ) log.writeLog(__LINE__, "pthread_create failed, return code = " + oam.itoa(ret), LOG_TYPE_ERROR); - sleep(6); // give the Status thread time to fully initialize + sleep(5); // give the Status thread time to fully initialize +/* if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) { + // start mysqld to make sure it's running + // need for addmodule command + try { + oam.actionMysqlCalpont(MYSQL_START); + } + catch(...) + {} + } +*/ } +/* else + { // um, start mysqld to make sure it's running + // need for reconfiguremodule command + try { + oam.actionMysqlCalpont(MYSQL_START); + } + catch(...) + {} + } +*/ + + // stop mysqld to make sure it's not running after reboot + try { + oam.actionMysqlCalpont(MYSQL_STOP); } + catch(...) + {} SystemStatus systemstatus; @@ -493,7 +471,7 @@ int main(int argc, char **argv) if ( procstat.ProcessOpState == oam::ACTIVE ) break; sleep(1); - log.writeLog(__LINE__, "Waiting for process-manager to go ACTIVE", LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "Waiting for process-manager to go ACTIVE", LOG_TYPE_ERROR); } catch (exception& ex) { @@ -553,13 +531,11 @@ int main(int argc, char **argv) systemprocessconfig.processconfig[i].LaunchID == 0 ) continue; - if ( (systemprocessconfig.processconfig[i].ModuleType == config.moduleType() ) || - ( systemprocessconfig.processconfig[i].ModuleType == "um" && - config.moduleType() == "pm" && PMwithUM == "y") || - ( systemprocessconfig.processconfig[i].ModuleType == "ChildExtOAMModule") || - ( systemprocessconfig.processconfig[i].ModuleType == "ChildOAMModule" ) || - ( systemprocessconfig.processconfig[i].ModuleType == "ParentOAMModule" && - config.moduleType() == OAMParentModuleType ) ) + if (systemprocessconfig.processconfig[i].ModuleType == config.moduleType() || + systemprocessconfig.processconfig[i].ModuleType == "ChildExtOAMModule" || + (systemprocessconfig.processconfig[i].ModuleType == "ChildOAMModule" ) || + (systemprocessconfig.processconfig[i].ModuleType == "ParentOAMModule" && + config.moduleType() == OAMParentModuleType ) ) { // If Process Monitor, update local state if ( systemprocessconfig.processconfig[i].ProcessName == "ProcessMonitor") @@ -579,17 +555,6 @@ int main(int argc, char **argv) } else { - if ( systemprocessconfig.processconfig[i].ModuleType == "um" && - config.moduleType() == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[i].ProcessName == "DMLProc" ) - continue; - - - if ( systemprocessconfig.processconfig[i].ModuleType == "um" && - config.moduleType() == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[i].ProcessName == "DDLProc" ) - continue; - // Get Last Known Process Status and PID int state = oam::AUTO_OFFLINE; int PID = 0; @@ -954,9 +919,11 @@ static void sigchldHandleThread() static void SIGCHLDHandler(int signal_number) { int status; + pid_t procID; - waitpid(-1, &status, WNOHANG); - + procID = waitpid(-1, &status, WNOHANG); +// procID = wait(&status); +// if (WIFEXITED (status)) return; } @@ -1041,9 +1008,7 @@ static void chldHandleThread(MonitorConfig config) //force restart the un-initted process log.writeLog(__LINE__, (*listPtr).ProcessName + "/" + oam.itoa((*listPtr).processID) + " failed to init in 20 seconds, force killing it so it can restart", LOG_TYPE_CRITICAL); - //skip killing 0 or 1 - if ( (*listPtr).processID > 1 ) - kill((*listPtr).processID, SIGKILL); + kill((*listPtr).processID, SIGKILL); break; } break; @@ -1088,21 +1053,6 @@ static void chldHandleThread(MonitorConfig config) log.writeLog(__LINE__, (*listPtr).ProcessName + " failed initialization", LOG_TYPE_WARNING); aMonitor.sendAlarm((*listPtr).ProcessName, PROCESS_INIT_FAILURE, SET); (*listPtr).state = state; - - //setModule status to failed - try{ - oam.setModuleStatus(config.moduleName(), oam::FAILED); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: Caught unknown exception!", LOG_TYPE_ERROR); - } - break; } @@ -1456,23 +1406,10 @@ static void statusControlThread() string processModuleType = systemprocessconfig.processconfig[j].ModuleType; if (processModuleType == systemModuleType - || ( processModuleType == "um" && - systemModuleType == "pm" && PMwithUM == "y") || processModuleType == "ChildExtOAMModule" || (processModuleType == "ChildOAMModule" ) || (processModuleType == "ParentOAMModule" && systemModuleType == OAMParentModuleType) ) { - if ( processModuleType == "um" && - systemModuleType == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[j].ProcessName == "DMLProc" ) - continue; - - - if ( processModuleType == "um" && - systemModuleType == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[j].ProcessName == "DDLProc" ) - continue; - processstatus procstat; procstat.ProcessName = systemprocessconfig.processconfig[j].ProcessName; procstat.ModuleName = (*pt).DeviceName; @@ -1880,7 +1817,7 @@ static void statusControlThread() //Initialize Shared memory if (memInit) { - // Init DBRoot Status Memory + // Init Ext Device Status Memory memset(fShmDbrootStatus, 0, DBROOTSTATshmsize); for ( int i=0; i < dbrootNumber ; ++i) { @@ -1902,6 +1839,9 @@ static void statusControlThread() // ModuleTypeConfig moduletypeconfig; + ByteStream msg; + IOSocket fIos; + //read and cleanup port before trying to use try { Config* sysConfig = Config::makeConfig(); @@ -1910,6 +1850,7 @@ static void statusControlThread() if ( !rootUser) cmd = "sudo fuser -k " + port + "/tcp >/dev/null 2>&1"; + system(cmd.c_str()); } catch(...) @@ -1918,16 +1859,11 @@ static void statusControlThread() log.writeLog(__LINE__, "statusControlThread Thread reading " + portName + " port", LOG_TYPE_DEBUG); - ByteStream msg; - IOSocket fIos; - MessageQueueServer* mqs=0; - - struct timespec ts = { 1, 0 }; - for (;;) { try { + MessageQueueServer* mqs; mqs = new MessageQueueServer(portName); mqs->syncProto(false); @@ -1940,9 +1876,6 @@ static void statusControlThread() mqs = new MessageQueueServer(portName); mqs->syncProto(false); log.writeLog(__LINE__, "statusControlThread Thread reading " + portName + " port", LOG_TYPE_DEBUG); - - processStatusList* aPtr = aMonitor.statusListPtr(); - updateShareMemory(aPtr); } if (runStandby && portName == "ProcStatusControl") { @@ -1953,6 +1886,7 @@ static void statusControlThread() log.writeLog(__LINE__, "statusControlThread Thread reading " + portName + " port", LOG_TYPE_DEBUG); } + struct timespec ts = { 1, 0 }; try { fIos = mqs->accept(&ts); @@ -2032,7 +1966,7 @@ static void statusControlThread() fIos.write(ackmsg); } - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set Process " + moduleName + "/" + processName + " State = " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set Process " + moduleName + "/" + processName + " State = " + oam.itoa(state), LOG_TYPE_DEBUG); processStatusList::iterator listPtr; processStatusList* aPtr = aMonitor.statusListPtr(); @@ -2050,7 +1984,7 @@ static void statusControlThread() if (listPtr == aPtr->end()) { // not in list - log.writeLog(__LINE__, "statusControl: SET_PROC_STATUS: Process not valid: " + moduleName + "/" + processName, LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: SET_PROC_STATUS: Process not valid: " + processName + " / " + moduleName, LOG_TYPE_DEBUG); break; } @@ -2105,38 +2039,18 @@ static void statusControlThread() // invalid state change ACTIVE TO MAN_INIT / AUTO_INIT if ( fShmProcessStatus[shmIndex].ProcessOpState == oam::ACTIVE ) { if ( state == oam::MAN_INIT || state == oam::AUTO_INIT ) { - log.writeLog(__LINE__, "statusControl: " + moduleName + "/" + processName + " Current State = ACTIVE, invalid update request to " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: Process " + processName + " of module " + moduleName + " Current State = ACTIVE, invalid update request to " + oam.itoa(state), LOG_TYPE_DEBUG); break; } } - if ( PID < 0 ) - PID = 0; - - log.writeLog(__LINE__, "statusControl: Set Process " + moduleName + "/" + processName + + " State = " + oamState[state] + " PID = " + oam.itoa(PID), LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: Set Process " + processName + " of module " + moduleName + " State = " + oam.itoa(state) + " PID = " + oam.itoa(PID), LOG_TYPE_DEBUG); //update table - if ( state < STATE_MAX ) - fShmProcessStatus[shmIndex].ProcessOpState = state; + fShmProcessStatus[shmIndex].ProcessOpState = state; if ( PID != 1 ) fShmProcessStatus[shmIndex].ProcessID = PID; memcpy(fShmProcessStatus[shmIndex].StateChangeDate, oam.getCurrentTime().c_str(), DATESIZE); - - //if DMLProc set to ACTIVE, set system state to ACTIVE - if ( processName == "DMLProc" && state == oam::ACTIVE ) - { - fShmSystemStatus[0].OpState = state; - memcpy(fShmSystemStatus[0].StateChangeDate, oam.getCurrentTime().c_str(), DATESIZE); - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set System State = " + oamState[state], LOG_TYPE_DEBUG); - } - - //if DMLProc set to BUSY_INIT, set system state to BUSY_INIT - if ( processName == "DMLProc" && state == oam::BUSY_INIT ) - { - fShmSystemStatus[0].OpState = state; - memcpy(fShmSystemStatus[0].StateChangeDate, oam.getCurrentTime().c_str(), DATESIZE); - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set System State = " + oamState[state], LOG_TYPE_DEBUG); - } } break; @@ -2152,7 +2066,7 @@ static void statusControlThread() processStatusList::iterator listPtr; processStatusList* aPtr = aMonitor.statusListPtr(); - ackmsg << (ByteStream::quadbyte) aPtr->size(); + ackmsg << (ByteStream::byte) aPtr->size(); for ( unsigned int i = 0 ; i < systemModuleTypeConfig.moduletypeconfig.size(); i++) { @@ -2331,7 +2245,7 @@ static void statusControlThread() msg >> state; fShmSystemStatus[0].OpState = state; memcpy(fShmSystemStatus[0].StateChangeDate, oam.getCurrentTime().c_str(), DATESIZE); - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set System State = " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set System State = " + oam.itoa(state), LOG_TYPE_DEBUG); if (!runStandby) { ByteStream ackmsg; @@ -2357,7 +2271,7 @@ static void statusControlThread() fIos.write(ackmsg); } - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set Module " + moduleName + " State = " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set Module " + moduleName + " State = " + oam.itoa(state), LOG_TYPE_DEBUG); //Handle Module RunType of ACTIVE_STANDBY string moduletype = moduleName.substr(0,MAX_MODULE_TYPE_SIZE); @@ -2528,7 +2442,7 @@ static void statusControlThread() fIos.write(ackmsg); } - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set Ext Device " + name + " State = " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set Ext Device " + name + " State = " + oam.itoa(state), LOG_TYPE_DEBUG); int i=0; for ( ; i < extDeviceNumber; ++i) @@ -2566,7 +2480,7 @@ static void statusControlThread() fIos.write(ackmsg); } - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set DBroot " + name + " State = " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set DBroot " + name + " State = " + oam.itoa(state), LOG_TYPE_DEBUG); if ( dbrootNumber == 0 ) { // no dbroots setup in shared memory, must be internal @@ -2610,7 +2524,7 @@ static void statusControlThread() fIos.write(ackmsg); } - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set NIC " + hostName + " State = " + oamState[state], LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Set NIC " + hostName + " State = " + oam.itoa(state), LOG_TYPE_DEBUG); int i=0; for ( ; i < NICNumber; ++i) @@ -2693,23 +2607,10 @@ static void statusControlThread() string processModuleType = systemprocessconfig.processconfig[j].ModuleType; if (processModuleType == moduleType - || ( processModuleType == "um" && - moduleType == "pm" && PMwithUM == "y") || processModuleType == "ChildExtOAMModule" || (processModuleType == "ChildOAMModule" ) || (processModuleType == "ParentOAMModule" && moduleType == OAMParentModuleType) ) { - if ( processModuleType == "um" && - moduleType == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[j].ProcessName == "DMLProc" ) - continue; - - - if ( processModuleType == "um" && - moduleType == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[j].ProcessName == "DDLProc" ) - continue; - processstatus procstat; procstat.ProcessName = systemprocessconfig.processconfig[j].ProcessName; procstat.ModuleName = (*pt).DeviceName; @@ -2856,9 +2757,9 @@ static void statusControlThread() msg >> device; - for ( int j=0 ; j < extDeviceNumber ; j++ ) + for ( int j=0 ; j < fmoduleNumber ; j++ ) { - memcpy(charName, fShmExtDeviceStatus[j].Name, NAMESIZE); + memcpy(charName, fShmSystemStatus[j].Name, NAMESIZE); shmName = charName; if ( device == shmName ) { for ( int k=j+1 ; k < extDeviceNumber ; k++) @@ -2882,65 +2783,6 @@ static void statusControlThread() } break; - case ADD_DBROOT: - { - ByteStream ackmsg; - string device; - - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Add DBRoot"); - - msg >> device; - - fShmDbrootStatus[dbrootNumber].OpState = oam::INITIAL; - memcpy(fShmDbrootStatus[dbrootNumber].Name, device.c_str(), NAMESIZE); - memcpy(fShmDbrootStatus[dbrootNumber].StateChangeDate, oam.getCurrentTime().c_str(), DATESIZE); - - dbrootNumber++; - - if (!runStandby) { - ackmsg << (ByteStream::byte) ADD_DBROOT; - fIos.write(ackmsg); - } - } - break; - - case REMOVE_DBROOT: - { - ByteStream ackmsg; - string device; - std::string shmName; - char charName[NAMESIZE]; - - log.writeLog(__LINE__, "statusControl: REQUEST RECEIVED: Remove DBRoot"); - - msg >> device; - - for ( int j=0 ; j < dbrootNumber ; j++ ) - { - memcpy(charName, fShmDbrootStatus[j].Name, NAMESIZE); - shmName = charName; - if ( device == shmName ) { - for ( int k=j+1 ; k < dbrootNumber ; k++) - { - string name = fShmDbrootStatus[k].Name; - int state = fShmDbrootStatus[k].OpState; - string changeDate = fShmDbrootStatus[k].StateChangeDate; - - memcpy(fShmDbrootStatus[j].Name, name.c_str(), NAMESIZE); - fShmDbrootStatus[j].OpState = state; - memcpy(fShmDbrootStatus[j].StateChangeDate, changeDate.c_str(), DATESIZE); - } - dbrootNumber--; - } - } - - if (!runStandby) { - ackmsg << (ByteStream::byte) REMOVE_DBROOT; - fIos.write(ackmsg); - } - } - break; - case GET_SHARED_MEM: { ByteStream ackmsg; @@ -2980,6 +2822,7 @@ static void statusControlThread() } // end of switch } + } catch (exception& ex) { @@ -3023,8 +2866,6 @@ static void statusControlThread() // takes 2 - 4 minites to free sockets, sleep and retry sleep(1); } - - delete mqs; } } diff --git a/procmon/processmonitor.cpp b/procmon/processmonitor.cpp index 29abb1c0..7d1626d8 100644 --- a/procmon/processmonitor.cpp +++ b/procmon/processmonitor.cpp @@ -1,29 +1,8 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** -* $Id: processmonitor.cpp 2044 2013-08-07 19:47:37Z dhill $ +* $Id: processmonitor.cpp 2024 2013-06-25 18:25:49Z dhill $ * ***************************************************************************/ -#include - -#include "IDBDataFile.h" -#include "IDBPolicy.h" #include "processmonitor.h" #include "installdir.h" #include "cacheutils.h" @@ -37,8 +16,6 @@ using namespace snmpmanager; using namespace logging; using namespace config; -using namespace idbdatafile; - extern string systemOAM; extern string dm_server; extern bool runStandby; @@ -48,8 +25,6 @@ extern string cloud; extern string GlusterConfig; extern bool rootUser; extern string USER; -extern bool HDFS; -extern string PMwithUM; //std::string gOAMParentModuleName; bool gOAMParentModuleFlag; @@ -574,17 +549,17 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO } pid_t processID = startProcess(processconfig.ModuleType, - processconfig.ProcessName, - processconfig.ProcessLocation, - processconfig.ProcessArgs, - processconfig.LaunchID, - processconfig.BootLaunch, - processconfig.RunType, - processconfig.DepProcessName, - processconfig.DepModuleName, - processconfig.LogFile, - initType, - actIndicator); + processconfig.ProcessName, + processconfig.ProcessLocation, + processconfig.ProcessArgs, + processconfig.LaunchID, + processconfig.BootLaunch, + processconfig.RunType, + processconfig.DepProcessName, + processconfig.DepModuleName, + processconfig.LogFile, + initType, + actIndicator); if ( processID > oam::API_MAX ) processID = oam::API_SUCCESS; requestStatus = processID; @@ -707,7 +682,7 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO { msg >> processName; msg >> manualFlag; - + int requestStatus = API_SUCCESS; log.writeLog(__LINE__, "MSG RECEIVED: Re-Init process request on: " + processName); if ( processName == "cpimport" ) @@ -725,10 +700,12 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if ((*listPtr).ProcessName == processName) { if ( (*listPtr).processID <= 1 ) { log.writeLog(__LINE__, "ERROR: process not active" , LOG_TYPE_DEBUG ); + requestStatus = API_SUCCESS; break; } reinitProcess((*listPtr).processID, (*listPtr).ProcessName, actIndicator); + requestStatus = API_SUCCESS; break; } } @@ -736,10 +713,16 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if (listPtr == aPtr->end()) { log.writeLog(__LINE__, "ERROR: No such process: " + processName, LOG_TYPE_ERROR ); + requestStatus = API_FAILURE; } } - log.writeLog(__LINE__, "PROCREINITPROCESS: completed, no ack to ProcMgr"); + ackMsg << (ByteStream::byte) ACK; + ackMsg << (ByteStream::byte) PROCREINITPROCESS; + ackMsg << (ByteStream::byte) requestStatus; + mq.write(ackMsg); + + log.writeLog(__LINE__, "PROCREINITPROCESS: ACK back to ProcMgr, return status = " + oam.itoa((int) requestStatus)); break; } case STOPALL: @@ -838,56 +821,8 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO //send down notification oam.sendDeviceNotification(config.moduleName(), MODULE_DOWN); - - //setModule status to offline - if ( manualFlag ) { - try{ - oam.setModuleStatus(config.moduleName(), oam::MAN_OFFLINE); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: Caught unknown exception!", LOG_TYPE_ERROR); - } - } - else - { - try{ - oam.setModuleStatus(config.moduleName(), oam::AUTO_OFFLINE); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: Caught unknown exception!", LOG_TYPE_ERROR); - } - } - } - else - { - //setModule status to failed - try{ - oam.setModuleStatus(config.moduleName(), oam::FAILED); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: Caught unknown exception!", LOG_TYPE_ERROR); - } } - if ( config.moduleType() == "pm" ) { //clearout auto move dbroots files string cmd = "rm -f " + startup::StartUp::installDir() + "/local/moveDbrootTransactionLog"; @@ -910,8 +845,8 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if ( actIndicator == oam::REMOVE ) { log.writeLog(__LINE__, "STOPALL: uninstall Calpont RPMs", LOG_TYPE_DEBUG); if ( config.moduleType() == "um" ) { - system("rpm -e infinidb-libs infinidb-platform infinidb-enterprise infinidb-storage-engine infinidb-mysql --nodeps"); - system("dpkg -P infinidb-libs infinidb-platform infinidb-enterprise infinidb-storage-engine infinidb-mysql"); + system("rpm -e calpont calpont-mysqld calpont-mysql --nodeps"); + system("dpkg -P calpont calpont-mysqld calpont-mysql"); } else // pm { @@ -925,8 +860,8 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO system(cmd.c_str()); sleep(1); - system("rpm -e infinidb-libs infinidb-platform infinidb-enterprise infinidb-storage-engine infinidb-mysql --nodeps"); - system("dpkg -P infinidb-libs infinidb-platform infinidb-enterprise infinidb-storage-engine infinidb-mysql"); + system("rpm -e calpont calpont-mysqld calpont-mysql --nodeps"); + system("dpkg -P calpont calpont-mysqld calpont-mysql"); } // should get here is packages get removed correctly string cmd = startup::StartUp::installDir() + "/bin/infinidb stop > /dev/null 2>&1"; @@ -942,37 +877,12 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO int requestStatus = oam::API_SUCCESS; log.writeLog(__LINE__, "MSG RECEIVED: Start All process request..."); - // change permissions on /dev/shm - string cmd = "chmod 777 /dev/shm >/dev/null 2>&1"; - if ( !rootUser) - cmd = "sudo chmod 777 /dev/shm >/dev/null 2>&1"; - - system(cmd.c_str()); - //start the mysql daemon try { oam.actionMysqlCalpont(MYSQL_START); } catch(...) - { // mysql didn't start, return with error - log.writeLog(__LINE__, "STARTALL: MySQL failed to start, start-module failure", LOG_TYPE_CRITICAL); - - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) STARTALL; - ackMsg << (ByteStream::byte) oam::API_FAILURE; - mq.write(ackMsg); - - try { - oam.setProcessStatus("mysqld", config.moduleName(), oam::FAILED, 0); - } - catch(...) - {} - - log.writeLog(__LINE__, "STARTALL: ACK back to ProcMgr, return status = " + oam.itoa((int) oam::API_FAILURE)); - - break; - - } + {} if( config.moduleType() == "pm" ) { @@ -996,27 +906,12 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO } } - //run HDFS startup test script to perform basic DB sanity testing - if ( HDFS ) { - if ( runHDFSTest() != oam::API_SUCCESS ) { - requestStatus = oam::API_FAILURE_DB_ERROR; - - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) STARTALL; - ackMsg << (ByteStream::byte) requestStatus; - mq.write(ackMsg); - - log.writeLog(__LINE__, "STARTALL: ACK back to ProcMgr, return status = " + oam.itoa((int) requestStatus)); - - break; - } - } - //Loop through all Process belong to this module processList::iterator listPtr; processList* aPtr = config.monitoredListPtr(); listPtr = aPtr->begin(); requestStatus = API_SUCCESS; + bool procmonProcessStart = false; //launched any processes controlled by ProcMon that aren't active for (; listPtr != aPtr->end(); ++listPtr) @@ -1024,14 +919,6 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if ( (*listPtr).BootLaunch != BOOT_LAUNCH) continue; - int opState; - bool degraded; - oam.getModuleStatus(config.moduleName(), opState, degraded); - if (opState == oam::FAILED) { - requestStatus = oam::API_FAILURE; - break; - } - //check the process current status & start the requested process if ((*listPtr).state == oam::MAN_OFFLINE || (*listPtr).state == oam::AUTO_OFFLINE || @@ -1063,6 +950,7 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if ( processID > oam::API_MAX ) { processID = oam::API_SUCCESS; + procmonProcessStart = true; } requestStatus = processID; @@ -1082,14 +970,6 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if ((*listPtr).BootLaunch != MGR_LAUNCH) continue; - int opState; - bool degraded; - oam.getModuleStatus(config.moduleName(), opState, degraded); - if (opState == oam::FAILED) { - requestStatus = oam::API_FAILURE; - break; - } - //check the process current status & start the requested process if ((*listPtr).state == oam::MAN_OFFLINE || (*listPtr).state == oam::AUTO_OFFLINE || @@ -1192,7 +1072,7 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO //Loop reversely thorugh the process list -/* processList* aPtr = config.monitoredListPtr(); + processList* aPtr = config.monitoredListPtr(); processList::reverse_iterator rPtr; uint16_t rtnCode; @@ -1224,7 +1104,7 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO } catch(...) {} -*/ + ackMsg << (ByteStream::byte) ACK; ackMsg << (ByteStream::byte) SHUTDOWNMODULE; ackMsg << (ByteStream::byte) API_SUCCESS; @@ -1382,22 +1262,21 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO } catch(...) {} - system("rpm -e infinidb-storage-engine infinidb-mysql"); - system("dpkg -P infinidb-storage-engine infinidb-mysql"); + system("rpm -e calpont-mysql calpont-mysqld"); + system("dpkg -P calpont-mysql calpont-mysqld"); log.writeLog(__LINE__, "RECONFIGURE: removed mysql rpms"); } // install mysql rpms if being reconfigured as a um if ( reconfigureModuleName.find("um") != string::npos ) { - system("rpm -ivh /root/infinidb-storage-engine-*rpm /root/infinidb-mysql-*rpm > /tmp/rpminstall"); - system("dpgk -i /root/infinidb-storage-engine-*deb /root/infinidb-mysql-*deb >> /tmp/rpminstall"); + system("rpm -ivh /root/calpont-mysql-*rpm /root/calpont-mysqld-*rpm > /tmp/rpminstall"); + system("dpgk -i /root/calpont-mysql-*deb /root/calpont-mysqld-*deb >> /tmp/rpminstall"); string cmd = startup::StartUp::installDir() + "/bin/post-mysqld-install >> /tmp/rpminstall"; system(cmd.c_str()); cmd = startup::StartUp::installDir() + "/bin/post-mysql-install >> /tmp/rpminstall"; system(cmd.c_str()); - cmd = startup::StartUp::installDir() + "/mysql/mysql-Calpont start > /tmp/mysqldstart"; - system(cmd.c_str()); + system("/etc/init.d/mysql-Calpont start > /tmp/mysqldstart"); ifstream file ("/tmp/mysqldstart"); if (!file) { @@ -1507,7 +1386,13 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO { log.writeLog(__LINE__, "MSG RECEIVED: Update Calpont Config file"); - (void)updateConfigFile(msg); + uint16_t rtnCode; + int requestStatus = API_SUCCESS; + + rtnCode = updateConfigFile(msg); + if (rtnCode) + // error in updating log + requestStatus = API_FAILURE; log.writeLog(__LINE__, "UPDATECONFIGFILE: Completed"); @@ -1655,7 +1540,6 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO { log.writeLog(__LINE__, "Unmount failed, device busy, dbroot: " + dbrootID, LOG_TYPE_ERROR); return_status = API_FAILURE; - system("mv -f /tmp/umount.txt /tmp/umount_failed.txt"); } } else @@ -1713,7 +1597,6 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO if (!oam.checkLogStatus("/tmp/mount.txt", "already")) { log.writeLog(__LINE__, "mount failed, dbroot: " + dbrootID, LOG_TYPE_ERROR); return_status = API_FAILURE; - system("mv -f /tmp/mount.txt /tmp/mount_failed.txt"); } } } @@ -1756,109 +1639,6 @@ void ProcessMonitor::processMessage(messageqcpp::ByteStream msg, messageqcpp::IO break; } - case MASTERREP: - { - log.writeLog(__LINE__, "MSG RECEIVED: Run Master Replication script "); - - string mysqlpw; - msg >> mysqlpw; - - string masterLogFile = oam::UnassignedName; - string masterLogPos = oam::UnassignedName; - - //change local my.cnf file - int ret = changeMyCnf("master"); - - if ( ret == oam::API_FAILURE ) - { - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) MASTERREP; - ackMsg << (ByteStream::byte) ret; - ackMsg << masterLogFile; - ackMsg << masterLogPos; - mq.write(ackMsg); - - log.writeLog(__LINE__, "MASTERREP: Error in changeMyCnf - ACK back to ProcMgr return status = " + oam.itoa((int) ret)); - break; - } - - // run Master Rep script - ret = runMasterRep(mysqlpw, masterLogFile, masterLogPos); - - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) MASTERREP; - ackMsg << (ByteStream::byte) ret; - ackMsg << masterLogFile; - ackMsg << masterLogPos; - mq.write(ackMsg); - - log.writeLog(__LINE__, "MASTERREP: ACK back to ProcMgr return status = " + oam.itoa((int) ret)); - - break; - } - - case SLAVEREP: - { - log.writeLog(__LINE__, "MSG RECEIVED: Run Slave Replication script "); - - string mysqlpw; - msg >> mysqlpw; - string masterLogFile; - msg >> masterLogFile; - string masterLogPos; - msg >> masterLogPos; - string port; - msg >> port; - - //change local my.cnf file - int ret = changeMyCnf("slave"); - - if ( ret == oam::API_FAILURE ) - { - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) SLAVEREP; - ackMsg << (ByteStream::byte) ret; - mq.write(ackMsg); - - log.writeLog(__LINE__, "SLAVEREP: Error in changeMyCnf - ACK back to ProcMgr return status = " + oam.itoa((int) ret)); - break; - } - - // run Slave Rep script - ret = runSlaveRep(mysqlpw, masterLogFile, masterLogPos, port); - - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) SLAVEREP; - ackMsg << (ByteStream::byte) ret; - mq.write(ackMsg); - - log.writeLog(__LINE__, "SLAVEREP: ACK back to ProcMgr return status = " + oam.itoa((int) ret)); - - break; - } - - case MASTERDIST: - { - log.writeLog(__LINE__, "MSG RECEIVED: Run Master DB Distribute command "); - - string password; - msg >> password; - string module; - msg >> module; - - // run Master Dist - int ret = runMasterDist(password, module); - - ackMsg << (ByteStream::byte) ACK; - ackMsg << (ByteStream::byte) MASTERDIST; - ackMsg << (ByteStream::byte) ret; - mq.write(ackMsg); - - log.writeLog(__LINE__, "MASTERDIST: runMasterRep - ACK back to ProcMgr return status = " + oam.itoa((int) ret)); - - break; - } - default: break; } //end of switch @@ -1965,7 +1745,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, launchID, newProcessID, FAILED, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process INIT state + //Update ProcessConfig.xml: Mark Process INIT state updateProcessInfo(processName, FAILED, newProcessID); return oam::API_FAILURE; @@ -2100,7 +1880,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, launchID, newProcessID, FAILED, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process INIT state + //Update ProcessConfig.xml: Mark Process INIT state updateProcessInfo(processName, FAILED, newProcessID); return oam::API_FAILURE; @@ -2174,7 +1954,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, try { int slavenodeID = oam.getLocalDBRMID(config.moduleName()); arg_list[i] = "DBRM_Worker" + oam.itoa(slavenodeID); - log.writeLog(__LINE__, "getLocalDBRMID Worker Node ID = " + oam.itoa(slavenodeID), LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "*** getLocalDBRMID Worker Node ID = " + oam.itoa(slavenodeID), LOG_TYPE_DEBUG); } catch(...) { @@ -2185,7 +1965,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, launchID, newProcessID, FAILED, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process INIT state + //Update ProcessConfig.xml: Mark Process INIT state updateProcessInfo(processName, FAILED, newProcessID); return oam::API_FAILURE; @@ -2203,11 +1983,11 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, argList[i] = NULL; //run load-brm script before brm processes started - if ( actIndicator != oam::GRACEFUL) { + if ( actIndicator != oam::GRACEFUL ) { if ( ( gOAMParentModuleFlag && processName == "DBRMControllerNode") || ( !gOAMParentModuleFlag && processName == "DBRMWorkerNode") ) { string DBRMDir; -// string tempDBRMDir = startup::StartUp::installDir() + "/data/dbrm"; + string tempDBRMDir = startup::StartUp::installDir() + "/data/dbrm"; // get DBRMroot config setting string DBRMroot; @@ -2226,7 +2006,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, launchID, newProcessID, FAILED, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process INIT state + //Update ProcessConfig.xml: Mark Process INIT state updateProcessInfo(processName, FAILED, newProcessID); return oam::API_FAILURE; @@ -2237,11 +2017,11 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, system(cmd.c_str()); // if Non Parent OAM Module, get the dbmr data from Parent OAM Module - if ( !gOAMParentModuleFlag && !HDFS ) { + if ( !gOAMParentModuleFlag ) { //create temp dbrm directory -// string cmd = "mkdir " + tempDBRMDir + " > /dev/null 2>&1"; -// system(cmd.c_str()); + string cmd = "mkdir " + tempDBRMDir + " > /dev/null 2>&1"; + system(cmd.c_str()); //setup softlink for editem on the 'um' or shared-nothing non active pm /* if( config.moduleType() == "um" || @@ -2254,7 +2034,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, } */ //change DBRMDir to temp DBRMDir -// DBRMDir = tempDBRMDir; + DBRMDir = tempDBRMDir; // remove all files for temp directory cmd = "rm -f " + DBRMDir + "/*"; @@ -2269,7 +2049,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, sendAlarm("DBRM", DBRM_LOAD_DATA_ERROR, CLEAR); // change DBRMroot to temp DBRMDir path -// DBRMroot = tempDBRMDir + "/BRM_saves"; + DBRMroot = tempDBRMDir + "/BRM_saves"; } // @@ -2278,24 +2058,19 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, string loadScript = "load_brm"; string fileName = DBRMroot + "_current"; - - ssize_t fileSize = IDBPolicy::size(fileName.c_str()); - boost::scoped_ptr oldFile(IDBDataFile::open( - IDBPolicy::getType(fileName.c_str(), - IDBPolicy::WRITEENG), - fileName.c_str(), "r", 0)); - if (oldFile && fileSize > 0) { - char line[200] = {0}; - oldFile->pread(line, 0, fileSize - 1); // skip the \n - line[fileSize] = '\0'; // not necessary, but be sure. + + ifstream oldFile (fileName.c_str()); + if (oldFile) { + char line[200]; + oldFile.getline(line, 200); string dbrmFile = line; -// if ( !gOAMParentModuleFlag ) { + if ( !gOAMParentModuleFlag ) { -// string::size_type pos = dbrmFile.find("/BRM_saves",0); -// if (pos != string::npos) -// dbrmFile = tempDBRMDir + dbrmFile.substr(pos,80);; -// } + string::size_type pos = dbrmFile.find("/BRM_saves",0); + if (pos != string::npos) + dbrmFile = tempDBRMDir + dbrmFile.substr(pos,80);; + } string logdir("/var/log/Calpont"); if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; @@ -2320,21 +2095,21 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, //record the process information into processList config.buildList(processModuleType, processName, processLocation, arg_list, - launchID, 0, FAILED, BootLaunch, RunType, + launchID, newProcessID, FAILED, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process FAILED state - updateProcessInfo(processName, FAILED, 0); + //Update ProcessConfig.xml: Mark Process INIT state + updateProcessInfo(processName, FAILED, newProcessID); return oam::API_FAILURE; } // now delete the dbrm data from local disk - if ( !gOAMParentModuleFlag && !HDFS ) { - string cmd = "rm -f " + DBRMDir + "/*"; - system(cmd.c_str()); - log.writeLog(__LINE__, "removed DBRM file with command: " + cmd, LOG_TYPE_DEBUG); - } +// if ( !gOAMParentModuleFlag) { +// string cmd = "rm -f " + tempDBRMDir + "/*"; +// system(cmd.c_str()); +// log.writeLog(__LINE__, "removed DBRM file with command: " + cmd, LOG_TYPE_DEBUG); +// } } else log.writeLog(__LINE__, "No DBRM files exist, must be a initial startup", LOG_TYPE_DEBUG); @@ -2422,7 +2197,8 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, } if (processLocation.find("snmp") != string::npos) - { // snmp app is special........... + { + // snmpd app is special........... // wait for up to 30 seconds for the pid file to be created //get snmp app pid which was stored when app was launched @@ -2453,13 +2229,12 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, log.writeLog(__LINE__, "FAILURE: no valid PID stored in " + pidFileLocation, LOG_TYPE_ERROR); return oam::API_MINOR_FAILURE; } - //record the process information into processList config.buildList(processModuleType, processName, processLocation, arg_list, launchID, newProcessID, oam::ACTIVE, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process oam::ACTIVE state + //Update ProcessConfig.xml: Mark Process oam::ACTIVE state updateProcessInfo(processName, oam::ACTIVE, newProcessID); } @@ -2472,8 +2247,8 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, launchID, newProcessID, initType, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Update PID - updateProcessInfo(processName, STATE_MAX, newProcessID); + //Update ProcessConfig.xml: Mark Process INIT state + updateProcessInfo(processName, initType, newProcessID); } log.writeLog(__LINE__, processName + " PID is " + oam.itoa(newProcessID), LOG_TYPE_DEBUG); @@ -2483,21 +2258,13 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, sendAlarm(processName, PROCESS_INIT_FAILURE, CLEAR); //give time to get status updates from process before starting next process - if ( processName == "DBRMWorkerNode" || processName == "ExeMgr" || processName == "DDLProc") + //only for certain process on single-server system + if ( processName == "DBRMWorkerNode" || processName == "ExeMgr" ) sleep(3); else - { if ( config.ServerInstallType() == oam::INSTALL_COMBINE_DM_UM_PM ) - { if ( processName == "PrimProc" || processName == "WriteEngineServer") sleep(3); - } - else - { - if ( (PMwithUM == "y") && processName == "PrimProc" ) - sleep(3); - } - } for (i=0; i < numAugs; i++) { @@ -2578,7 +2345,7 @@ pid_t ProcessMonitor::startProcess(string processModuleType, string processName, launchID, newProcessID, FAILED, BootLaunch, RunType, DepProcessName, DepModuleName, LogFile); - //Update Process Status: Mark Process INIT state + //Update ProcessConfig.xml: Mark Process INIT state updateProcessInfo(processName, FAILED, newProcessID); exit(oam::API_FAILURE); @@ -3384,24 +3151,11 @@ int ProcessMonitor::updateConfig() for( unsigned int i = 0 ; i < systemprocessconfig.processconfig.size(); i++) { if (systemprocessconfig.processconfig[i].ModuleType == systemModuleType - || ( systemprocessconfig.processconfig[i].ModuleType == "um" && - systemModuleType == "pm" && PMwithUM == "y" ) || systemprocessconfig.processconfig[i].ModuleType == "ChildExtOAMModule" || ( systemprocessconfig.processconfig[i].ModuleType == "ChildOAMModule" ) || (systemprocessconfig.processconfig[i].ModuleType == "ParentOAMModule" && systemModuleType == OAMParentModuleType) ) { - if ( systemprocessconfig.processconfig[i].ModuleType == "um" && - systemModuleType == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[i].ProcessName == "DMLProc" ) - continue; - - - if ( systemprocessconfig.processconfig[i].ModuleType == "um" && - systemModuleType == "pm" && PMwithUM == "y" && - systemprocessconfig.processconfig[i].ProcessName == "DDLProc" ) - continue; - ProcessStatus processstatus; try { //Get the process information @@ -3420,17 +3174,17 @@ int ProcessMonitor::updateConfig() } config.buildList(systemprocessconfig.processconfig[i].ModuleType, - systemprocessconfig.processconfig[i].ProcessName, - systemprocessconfig.processconfig[i].ProcessLocation, - systemprocessconfig.processconfig[i].ProcessArgs, - systemprocessconfig.processconfig[i].LaunchID, - processstatus.ProcessID, - processstatus.ProcessOpState, - systemprocessconfig.processconfig[i].BootLaunch, - systemprocessconfig.processconfig[i].RunType, - systemprocessconfig.processconfig[i].DepProcessName, - systemprocessconfig.processconfig[i].DepModuleName, - systemprocessconfig.processconfig[i].LogFile); + systemprocessconfig.processconfig[i].ProcessName, + systemprocessconfig.processconfig[i].ProcessLocation, + systemprocessconfig.processconfig[i].ProcessArgs, + systemprocessconfig.processconfig[i].LaunchID, + processstatus.ProcessID, + processstatus.ProcessOpState, + systemprocessconfig.processconfig[i].BootLaunch, + systemprocessconfig.processconfig[i].RunType, + systemprocessconfig.processconfig[i].DepProcessName, + systemprocessconfig.processconfig[i].DepModuleName, + systemprocessconfig.processconfig[i].LogFile); } } return API_SUCCESS; @@ -3451,7 +3205,8 @@ int ProcessMonitor::buildSystemTables() string fileName = DBdir + "/000.dir"; - if (!IDBPolicy::exists(fileName.c_str())) { + ifstream oldFile (fileName.c_str()); + if (!oldFile) { string logdir("/var/log/Calpont"); if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; string cmd = startup::StartUp::installDir() + "/bin/dbbuilder 7 > " + logdir + "/dbbuilder.log &"; @@ -3545,9 +3300,7 @@ int ProcessMonitor::checkSpecialProcessState( std::string processName, std::stri log.writeLog(__LINE__, "checkSpecialProcessState on : " + processName, LOG_TYPE_DEBUG); - if ( runType == SIMPLEX && PMwithUM == "y" && processModuleType == "um" && gOAMParentModuleFlag) - retStatus = oam::COLD_STANDBY; - else if ( runType == SIMPLEX && gOAMParentModuleFlag ) + if ( runType == SIMPLEX && gOAMParentModuleFlag ) retStatus = oam::MAN_INIT; else if ( runType == ACTIVE_STANDBY && processModuleType == "ParentOAMModule" && ( gOAMParentModuleFlag || !runStandby ) ) @@ -3556,8 +3309,6 @@ int ProcessMonitor::checkSpecialProcessState( std::string processName, std::stri retStatus = oam::STANDBY; else if ( runType == ACTIVE_STANDBY && processModuleType == "ParentOAMModule" ) retStatus = oam::COLD_STANDBY; - else if ( runType == SIMPLEX && processModuleType == "ParentOAMModule" && !gOAMParentModuleFlag) - retStatus = oam::COLD_STANDBY; else { //simplex on a non um1 or non-parent-pm @@ -3698,8 +3449,7 @@ int ProcessMonitor::createDataDirs(std::string cloud) log.writeLog(__LINE__, "createDataDirs called", LOG_TYPE_DEBUG); - if ( config.moduleType() == "um" && - ( cloud == "amazon-ec2" || cloud == "amazon-vpc") ) + if ( config.moduleType() == "um" && cloud == "amazon") { string UMStorageType; try { @@ -3754,7 +3504,7 @@ int ProcessMonitor::createDataDirs(std::string cloud) string cmd = "mkdir " + DBRootName + " > /dev/null 2>&1"; int rtnCode = system(cmd.c_str()); - if (WEXITSTATUS(rtnCode) == 0) + if (rtnCode == 0) log.writeLog(__LINE__, "Successful created directory " + DBRootName, LOG_TYPE_DEBUG); cmd = "chmod 1777 " + DBRootName + " > /dev/null 2>&1"; @@ -3769,9 +3519,8 @@ int ProcessMonitor::createDataDirs(std::string cloud) system(cmd.c_str()); } - if ( (cloud == "amazon-ec2" || cloud == "amazon-vpc") && - DBRootStorageType == "external" && - config.moduleID() == moduleID) + if (cloud == "amazon" && DBRootStorageType == "external" && + config.moduleID() == moduleID) { if(!amazonVolumeCheck(id)) { //Set the alarm @@ -3860,7 +3609,6 @@ int ProcessMonitor::getDBRMdata() int returnStatus = API_FAILURE; msg << (ByteStream::byte) GETDBRMDATA; - msg << config.moduleName(); try { @@ -3948,19 +3696,16 @@ int ProcessMonitor::getDBRMdata() journalFile = true; //change file name location to temp file local -// string::size_type pos1 = fileName.find("/dbrm",0); -// pos = fileName.find("data1",0); -// if (pos != string::npos) -// { -// string temp = fileName.substr(0,pos); -// string temp1 = temp + "data" + fileName.substr(pos1,80); -// fileName = temp1; -// } - - boost::scoped_ptr out(IDBDataFile::open( - IDBPolicy::getType(fileName.c_str(), - IDBPolicy::WRITEENG), - fileName.c_str(), "w", 0)); + string::size_type pos1 = fileName.find("/dbrm",0); + pos = fileName.find("data1",0); + if (pos != string::npos) + { + string temp = fileName.substr(0,pos); + string temp1 = temp + "data" + fileName.substr(pos1,80); + fileName = temp1; + } + + ofstream out(fileName.c_str()); // read file data try { @@ -3977,7 +3722,7 @@ int ProcessMonitor::getDBRMdata() } if (receivedMSG.length() > 0) { - out->write(receivedMSG.buf(), receivedMSG.length()); + out << receivedMSG; log.writeLog(__LINE__, fileName, LOG_TYPE_DEBUG); log.writeLog(__LINE__, oam.itoa(receivedMSG.length()), LOG_TYPE_DEBUG); } @@ -3991,7 +3736,7 @@ int ProcessMonitor::getDBRMdata() //create journal file if none come across if ( !journalFile) { - string cmd = "touch " + startup::StartUp::installDir() + "/data1/systemFiles/dbrm/BRM_saves_journal"; + string cmd = "touch " + startup::StartUp::installDir() + "/data/dbrm/BRM_saves_journal"; system(cmd.c_str()); } @@ -4213,6 +3958,7 @@ void ProcessMonitor::setTransactionLog(bool action) system("/etc/init.d/crond reload > /dev/null 2>&1"); } + /****************************************************************************************** * @brief runStartupTest * @@ -4242,28 +3988,14 @@ int ProcessMonitor::runStartupTest() system(cmd.c_str()); cmd = logdir + "/startupTests.log1"; - - bool fail = false; - if (oam.checkLogStatus(cmd, "OK")) { - log.writeLog(__LINE__, "startupTests passed", LOG_TYPE_DEBUG); - } - else - { - log.writeLog(__LINE__, "startupTests failed", LOG_TYPE_CRITICAL); - fail = true; - } - - if (!fail) - { - log.writeLog(__LINE__, "runStartupTest passed", LOG_TYPE_DEBUG); + log.writeLog(__LINE__, "Successfully ran startupTests", LOG_TYPE_DEBUG); //Clear the alarm sendAlarm(config.moduleName().c_str(), STARTUP_DIAGNOTICS_FAILURE, CLEAR); return oam::API_SUCCESS; } - else - { - log.writeLog(__LINE__, "ERROR: runStartupTest failed", LOG_TYPE_CRITICAL); + else { + log.writeLog(__LINE__, "ERROR: Failure returned from startupTests", LOG_TYPE_CRITICAL); //Set the alarm sendAlarm(config.moduleName().c_str(), STARTUP_DIAGNOTICS_FAILURE, SET); @@ -4285,105 +4017,87 @@ int ProcessMonitor::runStartupTest() } /****************************************************************************************** -* @brief runHDFSTest -* -* purpose: Runs HDFS sanity test +* @brief updateConfigFile * +* purpose: Update local Calpont Config File * ******************************************************************************************/ -int ProcessMonitor::runHDFSTest() +int ProcessMonitor::updateConfigFile(messageqcpp::ByteStream msg) { - //ProcMon log file - MonitorLog log; -// MonitorConfig config; -// ProcessMonitor aMonitor(config, log); - Oam oam; - bool fail = false; - - string logdir("/var/log/Calpont"); - if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; - string hdfslog = logdir + "/hdfsCheck.log1"; + string fileName; + string calpontFile; - //run hadoop test - string DataFilePlugin; - oam.getSystemConfig("DataFilePlugin", DataFilePlugin); + string installDir(startup::StartUp::installDir()); + string defaultCalpontConfigFile(installDir + "/etc/Calpont.xml"); + string defaultCalpontConfigFileTemp(installDir + "/etc/Calpont.xml.temp"); + string tmpCalpontConfigFileTemp(installDir + "/etc/Calpont.xml.temp1"); + string saveCalpontConfigFileTemp(installDir + "/etc/Calpont.xml.calpontSave"); - ifstream File (DataFilePlugin.c_str()); - if (!File) { - log.writeLog(__LINE__, "Error: Hadoop Datafile Plugin File (" + DataFilePlugin + ") doesn't exist", LOG_TYPE_CRITICAL); - fail = true; - } - else - { - // retry since infinidb can startup before hadoop is full up - int retry = 0; - for ( ; retry < 12 ; retry++ ) - { - string cmd = startup::StartUp::installDir() + "/bin/hdfsCheck " + DataFilePlugin + " > " + hdfslog + " 2>&1"; - system(cmd.c_str()); - if (oam.checkLogStatus(hdfslog, "All HDFS checks passed!")) { - log.writeLog(__LINE__, "hdfsCheck passed", LOG_TYPE_DEBUG); - break; - } - else - { - log.writeLog(__LINE__, "hdfsCheck Failed, wait and try again", LOG_TYPE_DEBUG); - sleep(10); - } - } + msg >> fileName; + ofstream out(fileName.c_str()); + out << msg; - if ( retry >= 12 ) - { - log.writeLog(__LINE__, "hdfsCheck Failed, check " + hdfslog, LOG_TYPE_CRITICAL); - fail = true; +/* if ( fileName == defaultCalpontConfigFile ) { + unlink (defaultCalpontConfigFileTemp.c_str()); + + ofstream newFile (defaultCalpontConfigFileTemp.c_str()); + + newFile.write (calpontFile.c_str(), calpontFile.size() ); + + newFile.close(); + + struct flock fl; + int fd; + + fl.l_type = F_WRLCK; // write lock + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + fl.l_pid = getpid(); + + fd = open(defaultCalpontConfigFile.c_str(), O_WRONLY); + + if (fcntl(fd, F_SETLKW, &fl) == -1) { + log.writeLog(__LINE__, "ERROR: Config::write: file lock error", LOG_TYPE_ERROR); + return oam::API_FAILURE; } - } - if (!fail) - { - //Clear the alarm - sendAlarm(config.moduleName().c_str(), STARTUP_DIAGNOTICS_FAILURE, CLEAR); - return oam::API_SUCCESS; + //save copy, copy temp file tp tmp then to Calpont.xml + //move to /tmp to get around a 'same file error' in mv command + string cmd = "rm -f " + saveCalpontConfigFileTemp; + system(cmd.c_str()); + cmd = "cp " + defaultCalpontConfigFile + " " + saveCalpontConfigFileTemp; + system(cmd.c_str()); + + cmd = "rm -f " + tmpCalpontConfigFileTemp; + system(cmd.c_str()); + cmd = "mv -f " + defaultCalpontConfigFileTemp + " " + tmpCalpontConfigFileTemp; + system(cmd.c_str()); + + cmd = "mv -f " + tmpCalpontConfigFileTemp + " " + defaultCalpontConfigFile; + system(cmd.c_str()); + + fl.l_type = F_UNLCK; //unlock + if (fcntl(fd, F_SETLK, &fl) == -1) + throw runtime_error("Config::write: file unlock error " + defaultCalpontConfigFile); + + close(fd); } else { - //Set the alarm - sendAlarm(config.moduleName().c_str(), STARTUP_DIAGNOTICS_FAILURE, SET); - - //setModule status to failed - try{ - oam.setModuleStatus(config.moduleName(), oam::FAILED); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on setModuleStatus: Caught unknown exception!", LOG_TYPE_ERROR); - } - - return oam::API_FAILURE; + //update a non Calpont.xml file + unlink (fileName.c_str()); + + ofstream newFile (fileName.c_str()); + + newFile.write (calpontFile.c_str(), calpontFile.size() ); + + newFile.close(); } -} - - -/****************************************************************************************** -* @brief updateConfigFile -* -* purpose: Update local Calpont Config File -* -******************************************************************************************/ -int ProcessMonitor::updateConfigFile(messageqcpp::ByteStream msg) -{ - Config* sysConfig = Config::makeConfig(); - sysConfig->writeConfigFile(msg); - +*/ return oam::API_SUCCESS; -} - +} /****************************************************************************************** * @brief sendMsgProcMon1 @@ -4475,6 +4189,23 @@ void ProcessMonitor::checkProcessFailover( std::string processName) { Oam oam; + //check if license has expired + oam::LicenseKeyChecker keyChecker; + + bool keyGood = true; + try { + keyGood = keyChecker.isGood(); + } + catch(...) + { + keyGood = false; + } + + if (!keyGood) + { + return; + } + //force failover on certain processes if ( processName == "DDLProc" || processName == "DMLProc" ) { @@ -4489,10 +4220,6 @@ void ProcessMonitor::checkProcessFailover( std::string processName) { if ( systemprocessstatus.processstatus[i].ProcessName == processName && systemprocessstatus.processstatus[i].Module != config.moduleName() ) { - //make sure it matches module type - string procModuleType = systemprocessstatus.processstatus[i].Module.substr(0,MAX_MODULE_TYPE_SIZE); - if ( config.moduleType() != procModuleType ) - continue; if ( systemprocessstatus.processstatus[i].ProcessOpState == oam::COLD_STANDBY || systemprocessstatus.processstatus[i].ProcessOpState == oam::AUTO_OFFLINE || systemprocessstatus.processstatus[i].ProcessOpState == oam::FAILED ) { @@ -4550,11 +4277,13 @@ int ProcessMonitor::runUpgrade(std::string mysqlpw) for ( int i = 0 ; i < 10 ; i++ ) { //run upgrade script + string logdir("/var/log/Calpont"); + if (access(logdir.c_str(), W_OK) != 0) logdir = "/tmp"; string cmd = startup::StartUp::installDir() + "/bin/upgrade-infinidb.sh doupgrade --password=" + - mysqlpw + " --installdir=" + startup::StartUp::installDir() + " > " + "/tmp/upgrade-infinidb.log 2>&1"; + mysqlpw + " --installdir=" + startup::StartUp::installDir() + " > " + logdir + "/upgrade-infinidb.log1 2>&1"; system(cmd.c_str()); - cmd = "/tmp/upgrade-infinidb.log"; + cmd = logdir + "/upgrade-infinidb.log1"; if (oam.checkLogStatus(cmd, "OK")) { log.writeLog(__LINE__, "upgrade-infinidb.sh: Successful return", LOG_TYPE_DEBUG); return oam::API_SUCCESS; @@ -4578,462 +4307,6 @@ int ProcessMonitor::runUpgrade(std::string mysqlpw) return oam::API_FAILURE; } - -/****************************************************************************************** -* @brief changeMyCnf -* -* purpose: Change my.cnf -* -******************************************************************************************/ -int ProcessMonitor::changeMyCnf(std::string type) -{ - Oam oam; - - log.writeLog(__LINE__, "changeMyCnf function called for " + type, LOG_TYPE_DEBUG); - - string mycnfFile = startup::StartUp::installDir() + "/mysql/my.cnf"; - ifstream file (mycnfFile.c_str()); - if (!file) { - log.writeLog(__LINE__, "changeMyCnf - my.cnf file not found: " + mycnfFile, LOG_TYPE_CRITICAL); - return oam::API_FAILURE; - } - - if ( type == "master" ) - { - // set master replication entries - vector lines; - char line[200]; - string buf; - while (file.getline(line, 200)) - { - buf = line; - string::size_type pos = buf.find("server-id =",0); - if ( pos != string::npos ) { - buf = "server-id = 1"; - } - - pos = buf.find("# log-bin=mysql-bin",0); - if ( pos != string::npos ) { - buf = "log-bin=mysql-bin"; - } - - pos = buf.find("infinidb_local_query=1",0); - if ( pos != string::npos && pos == 0) { - buf = "# infinidb_local_query=1"; - } - - //output to temp file - lines.push_back(buf); - } - - file.close(); - unlink (mycnfFile.c_str()); - ofstream newFile (mycnfFile.c_str()); - - //create new file - int fd = open(mycnfFile.c_str(), O_RDWR|O_CREAT, 0666); - - copy(lines.begin(), lines.end(), ostream_iterator(newFile, "\n")); - newFile.close(); - - close(fd); - } - - if ( type == "slave" ) - { - //get slave id based on ExeMgrx setup - string slaveID = "0"; - string slaveModuleName = config.moduleName(); - for ( int id = 1 ; ; id++ ) - { - string Section = "ExeMgr" + oam.itoa(id); - - string moduleName; - - try { - Config* sysConfig = Config::makeConfig(); - moduleName = sysConfig->getConfig(Section, "Module"); - - if ( moduleName == slaveModuleName ) - { - slaveID = oam.itoa(id); - - // if slave ID from above is 1, then it means this is a former Original master and use the ID of the current Master - if ( slaveID == "1" ) { - string PrimaryUMModuleName; - oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); - - for ( int mid = 1 ; ; mid++ ) - { - string Section = "ExeMgr" + oam.itoa(mid); - - string moduleName; - - try { - Config* sysConfig = Config::makeConfig(); - moduleName = sysConfig->getConfig(Section, "Module"); - - if ( moduleName == PrimaryUMModuleName ) - { - slaveID = oam.itoa(mid); - break; - } - } - catch (...) {} - } - } - break; - } - } - catch (...) {} - } - - if ( slaveID == "0" ) - { - log.writeLog(__LINE__, "changeMyCnf: ExeMgr for local module doesn't exist", LOG_TYPE_ERROR); - return oam::API_FAILURE; - } - - // get local host name - string HOSTNAME = "localhost"; - try - { - ModuleConfig moduleconfig; - oam.getSystemConfig(config.moduleName(), moduleconfig); - HostConfigList::iterator pt1 = moduleconfig.hostConfigList.begin(); - HOSTNAME = (*pt1).HostName; - } - catch(...) - {} - - char* p= getenv("HOSTNAME"); - if (p && *p) - HOSTNAME = p; - - // set slave replication entries - vector lines; - char line[200]; - string buf; - while (file.getline(line, 200)) - { - buf = line; - string::size_type pos = buf.find("server-id",0); - if ( pos != string::npos ) { - buf = "server-id = " + slaveID; - } - - pos = buf.find("#relay-log=HOSTNAME-relay-bin",0); - if ( pos != string::npos ) { - buf = "relay-log=" + HOSTNAME + "-relay-bin"; - } - - // set local query flag if on pm - if ( (PMwithUM == "y") && config.moduleType() == "pm" ) - { - pos = buf.find("# infinidb_local_query=1",0); - if ( pos != string::npos ) { - buf = "infinidb_local_query=1"; - } - } - else - { // disable, if needed - pos = buf.find("infinidb_local_query=1",0); - if ( pos != string::npos ) { - buf = "# infinidb_local_query=1"; - } - - } - - pos = buf.find("log-bin=mysql-bin",0); - if ( pos != string::npos && pos == 0 ) { - buf = "# log-bin=mysql-bin"; - } - - //output to temp file - lines.push_back(buf); - } - - file.close(); - unlink (mycnfFile.c_str()); - ofstream newFile (mycnfFile.c_str()); - - //create new file - int fd = open(mycnfFile.c_str(), O_RDWR|O_CREAT, 0666); - - copy(lines.begin(), lines.end(), ostream_iterator(newFile, "\n")); - newFile.close(); - - close(fd); - } - - // restart mysql - try { - oam.actionMysqlCalpont(MYSQL_RESTART); - } - catch(...) - {} - - return oam::API_SUCCESS; -} - -/****************************************************************************************** -* @brief runMasterRep -* -* purpose: run Master Replication script -* -******************************************************************************************/ -int ProcessMonitor::runMasterRep(std::string& mysqlpw, std::string& masterLogFile, std::string& masterLogPos) -{ - Oam oam; - - log.writeLog(__LINE__, "runMasterRep function called", LOG_TYPE_DEBUG); - - SystemModuleTypeConfig systemModuleTypeConfig; - try { - oam.getSystemConfig(systemModuleTypeConfig); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: Caught unknown exception!", LOG_TYPE_ERROR); - } - - // create user for each module by ip address - for ( unsigned int i = 0 ; i < systemModuleTypeConfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemModuleTypeConfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - - DeviceNetworkList::iterator pt = systemModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for( ; pt != systemModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.end() ; pt++) - { - string moduleName = (*pt).DeviceName; - - HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); - for ( ; pt1 != (*pt).hostConfigList.end() ; pt1++ ) - { - string ipAddr = (*pt1).IPAddr; - - string logFile = "/tmp/master-rep-infinidb-" + moduleName + ".log"; - string cmd = startup::StartUp::installDir() + "/bin/master-rep-infinidb.sh --password=" + - mysqlpw + " --installdir=" + startup::StartUp::installDir() + " --hostIP=" + ipAddr + " > " + logFile + " 2>&1"; - system(cmd.c_str()); - - if (oam.checkLogStatus(logFile, "OK")) - log.writeLog(__LINE__, "master-rep-infinidb.sh: Successful return for node " + moduleName, LOG_TYPE_DEBUG); - else - { - if (oam.checkLogStatus(logFile, "ERROR 1045") ) { - log.writeLog(__LINE__, "master-rep-infinidb.sh: Missing Password error, return success", LOG_TYPE_DEBUG); - return oam::API_SUCCESS; - } - else - { - log.writeLog(__LINE__, "master-rep-infinidb.sh: Error return, check log " + logFile, LOG_TYPE_ERROR); - return oam::API_FAILURE; - } - } - } - } - } - - // go parse out the MASTER_LOG_FILE and MASTER_LOG_POS - // this is what the output will look like - // - // SHOW MASTER STATUS - // File Position Binlog_Do_DB Binlog_Ignore_DB - // mysql-bin.000006 2921 - // - // in log - /tmp/show-master-status.log - - ifstream file ("/tmp/show-master-status.log"); - if (!file) { - log.writeLog(__LINE__, "runMasterRep - show master status log file doesn't exist - /tmp/show-master-status.log", LOG_TYPE_CRITICAL); - return oam::API_FAILURE; - } - else - { - char line[200]; - string buf; - while (file.getline(line, 200)) - { - buf = line; - string::size_type pos = buf.find("mysql-bin",0); - if ( pos != string::npos ) { - string::size_type pos1 = buf.find("\t",pos); - if ( pos1 != string::npos ) { - string masterlogfile = buf.substr(pos,pos1-pos); - - //strip trailing spaces - string::size_type lead = masterlogfile.find_first_of(" "); - masterLogFile = masterlogfile.substr( 0, lead); - - string masterlogpos = buf.substr(pos1,80); - - //strip off leading tab masterlogpos - lead=masterlogpos.find_first_not_of("\t"); - masterlogpos = masterlogpos.substr( lead, masterlogpos.length()-lead); - - //string trailing spaces - lead = masterlogpos.find_first_of(" "); - masterLogPos = masterlogpos.substr( 0, lead); - - log.writeLog(__LINE__, "runMasterRep: masterlogfile=" + masterLogFile + ", masterlogpos=" + masterLogPos, LOG_TYPE_DEBUG); - file.close(); - return oam::API_SUCCESS; - } - } - } - - file.close(); - } - - log.writeLog(__LINE__, "runMasterRep - 'mysql-bin not found in log file - /tmp/show-master-status.log", LOG_TYPE_CRITICAL); - return oam::API_FAILURE; -} - -/****************************************************************************************** -* @brief runSlaveRep -* -* purpose: run Slave Replication script -* -******************************************************************************************/ -int ProcessMonitor::runSlaveRep(std::string& mysqlpw, std::string& masterLogFile, std::string& masterLogPos, std::string& port) -{ - Oam oam; - - log.writeLog(__LINE__, "runSlaveRep function called", LOG_TYPE_DEBUG); - - // get master replicaion module IP Address - string PrimaryUMModuleName; - oam.getSystemConfig("PrimaryUMModuleName", PrimaryUMModuleName); - - string masterIPAddress; - try - { - ModuleConfig moduleconfig; - oam.getSystemConfig(PrimaryUMModuleName, moduleconfig); - HostConfigList::iterator pt1 = moduleconfig.hostConfigList.begin(); - masterIPAddress = (*pt1).IPAddr; - } - catch(...) - {} - - string cmd = startup::StartUp::installDir() + "/bin/slave-rep-infinidb.sh --password=" + - mysqlpw + " --installdir=" + startup::StartUp::installDir() + " --masteripaddr=" + masterIPAddress + " --masterlogfile=" + masterLogFile + " --masterlogpos=" + masterLogPos + + " --port=" + port + " > /tmp/slave-rep-infinidb.log 2>&1"; - system(cmd.c_str()); - - cmd = "/tmp/slave-rep-infinidb.log"; - if (oam.checkLogStatus(cmd, "OK")) { - log.writeLog(__LINE__, "slave-rep-infinidb.sh: Successful return", LOG_TYPE_DEBUG); - return oam::API_SUCCESS; - } - else { - if (oam.checkLogStatus(cmd, "ERROR 1045") ) { - log.writeLog(__LINE__, "slave-rep-infinidb.sh: Missing Password error, return success", LOG_TYPE_DEBUG); - return oam::API_SUCCESS; - } - - log.writeLog(__LINE__, "slave-rep-infinidb.sh: Error return, check log /tmp/slave-rep-infinidb.log", LOG_TYPE_ERROR); - return oam::API_FAILURE; - } - - return oam::API_FAILURE; -} - -/****************************************************************************************** -* @brief runMasterDist -* -* purpose: run Master DB Distribution -* -******************************************************************************************/ -int ProcessMonitor::runMasterDist(std::string& password, std::string& slaveModule) -{ - Oam oam; - - log.writeLog(__LINE__, "runMasterDist function called", LOG_TYPE_DEBUG); - - SystemModuleTypeConfig systemModuleTypeConfig; - try { - oam.getSystemConfig(systemModuleTypeConfig); - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: " + error, LOG_TYPE_ERROR); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getSystemConfig: Caught unknown exception!", LOG_TYPE_ERROR); - } - - if ( slaveModule == "all" ) - { - // Distrubuted MySQL Front-end DB to Slave Modules - for ( unsigned int i = 0 ; i < systemModuleTypeConfig.moduletypeconfig.size(); i++) - { - int moduleCount = systemModuleTypeConfig.moduletypeconfig[i].ModuleCount; - if( moduleCount == 0) - continue; - - string moduleType = systemModuleTypeConfig.moduletypeconfig[i].ModuleType; - - if ( (PMwithUM == "n") && (moduleType == "pm") && ( config.ServerInstallType() != oam::INSTALL_COMBINE_DM_UM_PM) ) - continue; - - DeviceNetworkList::iterator pt = systemModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for( ; pt != systemModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.end() ; pt++) - { - string moduleName = (*pt).DeviceName; - - //skip if local master mode - if ( moduleName == config.moduleName() ) - continue; - - HostConfigList::iterator pt1 = (*pt).hostConfigList.begin(); - for ( ; pt1 != (*pt).hostConfigList.end() ; pt1++ ) - { - string ipAddr = (*pt1).IPAddr; - - string cmd = startup::StartUp::installDir() + "/bin/rsync.sh " + ipAddr + " " + password + " 1 > /tmp/master-dist_" + moduleName + ".log"; - system(cmd.c_str()); - - string logFile = "/tmp/master-dist_" + moduleName + ".log"; - if (!oam.checkLogStatus(logFile, "FAILED")) - log.writeLog(__LINE__, "runMasterDist: Success rsync to module: " + moduleName, LOG_TYPE_DEBUG); - else - log.writeLog(__LINE__, "runMasterDist: Failure rsync to module: " + moduleName, LOG_TYPE_ERROR); - } - } - } - } - else - { - // get slave IP address - ModuleConfig moduleconfig; - oam.getSystemConfig(slaveModule, moduleconfig); - HostConfigList::iterator pt1 = moduleconfig.hostConfigList.begin(); - string ipAddr = (*pt1).IPAddr; - - string cmd = startup::StartUp::installDir() + "/bin/rsync.sh " + ipAddr + " " + password + " 1 > /tmp/master-dist_" + slaveModule + ".log"; - system(cmd.c_str()); - - string logFile = "/tmp/master-dist_" + slaveModule + ".log"; - if (!oam.checkLogStatus(logFile, "FAILED")) - log.writeLog(__LINE__, "runMasterDist: Success rsync to module: " + slaveModule, LOG_TYPE_DEBUG); - else - log.writeLog(__LINE__, "runMasterDist: Failure rsync to module: " + slaveModule, LOG_TYPE_ERROR); - } - - return oam::API_SUCCESS; -} - - /****************************************************************************************** * @brief amazonIPCheck * @@ -5047,9 +4320,6 @@ bool ProcessMonitor::amazonIPCheck() log.writeLog(__LINE__, "amazonIPCheck function called", LOG_TYPE_DEBUG); - // delete description file so it will create a new one - unlink("/tmp/describeInstance.txt"); - // // Get Module Info // @@ -5364,13 +4634,12 @@ void ProcessMonitor::unmountExtraDBroots() ModuleConfig moduleconfig; Oam oam; - string DBRootStorageType = "internal"; + string DBRootStorageType = "local"; try{ oam.getSystemConfig("DBRootStorageType", DBRootStorageType); - if ( DBRootStorageType == "hdfs" || - ( DBRootStorageType == "internal" && GlusterConfig == "n") ) + if ( DBRootStorageType == "internal" && GlusterConfig == "n") return; } catch(...) {} @@ -5454,53 +4723,46 @@ int ProcessMonitor::checkDataMount() log.writeLog(__LINE__, "checkDataMount called ", LOG_TYPE_DEBUG); - string DBRootStorageType = "internal"; + string DBRootStorageType = "local"; vector dbrootList; string installDir(startup::StartUp::installDir()); - for ( int retry = 0 ; retry < 10 ; retry++) + try { - try + systemStorageInfo_t t; + t = oam.getStorageConfig(); + + if ( boost::get<1>(t) == 0 ) { + log.writeLog(__LINE__, "No dbroots are configured in Calpont.xml file", LOG_TYPE_WARNING); + return API_INVALID_PARAMETER; + } + + DeviceDBRootList moduledbrootlist = boost::get<2>(t); + + DeviceDBRootList::iterator pt = moduledbrootlist.begin(); + for( ; pt != moduledbrootlist.end() ; pt++) { - systemStorageInfo_t t; - t = oam.getStorageConfig(); - - if ( boost::get<1>(t) == 0 ) { - log.writeLog(__LINE__, "getStorageConfig return: No dbroots are configured in Calpont.xml file", LOG_TYPE_WARNING); - return API_INVALID_PARAMETER; - } - - DeviceDBRootList moduledbrootlist = boost::get<2>(t); - - DeviceDBRootList::iterator pt = moduledbrootlist.begin(); - for( ; pt != moduledbrootlist.end() ; pt++) + int moduleID = (*pt).DeviceID; + + DBRootConfigList::iterator pt1 = (*pt).dbrootConfigList.begin(); + for( ; pt1 != (*pt).dbrootConfigList.end() ;pt1++) { - int moduleID = (*pt).DeviceID; - - DBRootConfigList::iterator pt1 = (*pt).dbrootConfigList.begin(); - for( ; pt1 != (*pt).dbrootConfigList.end() ;pt1++) + if (config.moduleID() == moduleID) { - if (config.moduleID() == moduleID) - { - dbrootList.push_back(oam.itoa(*pt1)); - } + dbrootList.push_back(oam.itoa(*pt1)); } } - - break; - } - catch (exception& ex) - { - string error = ex.what(); - log.writeLog(__LINE__, "EXCEPTION ERROR on getStorageConfig: " + error, LOG_TYPE_ERROR); - sleep (1); - } - catch(...) - { - log.writeLog(__LINE__, "EXCEPTION ERROR on getStorageConfig: Caught unknown exception!", LOG_TYPE_ERROR); - sleep (1); } } + catch (exception& ex) + { + string error = ex.what(); + log.writeLog(__LINE__, "EXCEPTION ERROR on getStorageConfig: " + error, LOG_TYPE_ERROR); + } + catch(...) + { + log.writeLog(__LINE__, "EXCEPTION ERROR on getStorageConfig: Caught unknown exception!", LOG_TYPE_ERROR); + } if ( dbrootList.size() == 0 ) { log.writeLog(__LINE__, "No dbroots are configured in Calpont.xml file", LOG_TYPE_WARNING); @@ -5535,10 +4797,12 @@ int ProcessMonitor::checkDataMount() log.writeLog(__LINE__, "Exception assigning gluster dbroot# " + dbrootID, LOG_TYPE_ERROR); } } + + //go unmount disk NOT assigned to this pm + unmountExtraDBroots(); } - if ( DBRootStorageType == "hdfs" || - (DBRootStorageType == "internal" && GlusterConfig == "n") ) { + if ( DBRootStorageType == "internal" && GlusterConfig == "n") { //create OAM-Test-Flag vector::iterator p = dbrootList.begin(); while ( p != dbrootList.end() ) @@ -5558,9 +4822,6 @@ int ProcessMonitor::checkDataMount() return API_SUCCESS; } - //go unmount disk NOT assigned to this pm - unmountExtraDBroots(); - //Flush the cache cacheutils::flushPrimProcCache(); cacheutils::dropPrimProcFdCache(); diff --git a/procmon/processmonitor.h b/procmon/processmonitor.h index 1641bd88..18e9f994 100644 --- a/procmon/processmonitor.h +++ b/procmon/processmonitor.h @@ -1,22 +1,5 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - /*************************************************************************** -* $Id: processmonitor.h 1993 2013-04-04 18:33:48Z rdempsey $ +* $Id: processmonitor.h 1918 2012-11-29 21:09:52Z dhill $ * ***************************************************************************/ @@ -462,11 +445,6 @@ class ProcessMonitor */ int runStartupTest(); - /** - *@brief Runs HDFS sanity test - */ - int runHDFSTest(); - /** *@brief Update Calpont Config File */ @@ -489,26 +467,6 @@ class ProcessMonitor */ int runUpgrade(std::string mysqlpw); - /** - *@brief change my.cnf - */ - int changeMyCnf(std::string type); - - /** - *@brief run Master Replication script - */ - int runMasterRep(std::string& mysqlpw, std::string& masterLogFile, std::string& masterLogPos); - - /** - *@brief run Master Distribution - */ - int runMasterDist(std::string& password, std::string& slaveModule); - - /** - *@brief run Slave Replication script - */ - int runSlaveRep(std::string& mysqlpw, std::string& masterLogFile, std::string& masterLogPos, std::string& port); - /** *@brief Amazon Instance and IP check */ diff --git a/rules.mak b/rules.mak index 65c3b912..ab4eb36e 100644 --- a/rules.mak +++ b/rules.mak @@ -26,20 +26,16 @@ INSTALL_MIB=$(INSTALL_ROOT)/share/snmp/mibs CALPONT_LIBRARY_PATH=$(EXPORT_ROOT)/lib CALPONT_INCLUDE_PATH=$(EXPORT_ROOT)/include -IDB_COMMON_LIBS=-lwindowfunction -ljoblist -lexecplan -ljoiner -lrowgroup -lfuncexp -ludfsdk \ --loamcpp -lsnmpmanager -ldataconvert -lbrm -lcacheutils -lmessageqcpp -lloggingcpp -lconfigcpp -lrwlock \ --lcommon -lcompress -lxml2 -lidbboot -lboost_idb -lmysqlcl_idb -lquerystats -lidbdatafile -lquerytele \ --lthrift -lpthread -lrt +IDB_COMMON_LIBS=-ljoblist -lexecplan -ljoiner -lrowgroup -lmulticast -lfuncexp -ludfsdk -loamcpp -lsnmpmanager \ +-ldataconvert -lbrm -lcacheutils -lmessageqcpp -lloggingcpp -lconfigcpp -lrwlock -lcommon -lcompress -lxml2 -lidbboot \ +-lboost_idb -lmysqlcl_idb -lquerystats IDB_WRITE_LIBS=-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lcompress -lcacheutils IDB_SNMP_LIBS=-lnetsnmpagent -lnetsnmp -lnetsnmpmibs -lnetsnmphelpers LDFLAGS=-Wl,--no-as-needed -#DEBUG_FLAGS=-ggdb3 -fno-tree-vectorize -DEBUG_FLAGS=-g0 -O3 -fno-strict-aliasing -fno-tree-vectorize - -#DEBUG_FLAGS+=-DVALGRIND -#DEBUG_FLAGS+=-DSKIP_OAM_INIT +#DEBUG_FLAGS=-ggdb3 +DEBUG_FLAGS=-g0 -O3 -fno-strict-aliasing ifeq (i686,$(shell uname -m)) DEBUG_FLAGS+=-march=pentium4 @@ -59,8 +55,7 @@ ifeq (4.5,$(shell test -x /usr/local/gcc45/bin/gcc && /usr/local/gcc45/bin/gcc - endif endif -#Use only the last, non-comment line from MyDebugFlags file -LOCAL_DEBUG_FLAGS=$(shell test -f $(TOP)/MyDebugFlags && awk '/^[^\#]/ {last=$$0}END{print last}' $(TOP)/MyDebugFlags) +LOCAL_DEBUG_FLAGS=$(shell test -f $(TOP)/MyDebugFlags && cat $(TOP)/MyDebugFlags) ifneq (,$(LOCAL_DEBUG_FLAGS)) DEBUG_FLAGS=$(LOCAL_DEBUG_FLAGS) endif diff --git a/snmpd/Makefile.am b/snmpd/Makefile.am index 5298888c..3694a51c 100644 --- a/snmpd/Makefile.am +++ b/snmpd/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ diff --git a/snmpd/Makefile.in b/snmpd/Makefile.in index 82aba42f..ba0bff26 100644 --- a/snmpd/Makefile.in +++ b/snmpd/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ srcdir = @srcdir@ @@ -57,9 +57,8 @@ host_triplet = @host@ subdir = snmpd DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/snmpd/etc/Makefile.am b/snmpd/etc/Makefile.am index 59193a68..79d58bfc 100644 --- a/snmpd/etc/Makefile.am +++ b/snmpd/etc/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. dist_sysconf_DATA = snmpd.conf snmptrapd.conf snmpd.conf.singleserver snmptrapd.conf.singleserver dist_mib_DATA = CALPONT-MIB.txt \ diff --git a/snmpd/etc/Makefile.in b/snmpd/etc/Makefile.in index 3b0b97d3..e421fe6d 100644 --- a/snmpd/etc/Makefile.in +++ b/snmpd/etc/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -57,9 +57,8 @@ subdir = snmpd/etc DIST_COMMON = $(dist_local_DATA) $(dist_mib_DATA) $(dist_sysconf_DATA) \ $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -139,9 +138,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -183,7 +179,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -197,11 +192,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/snmpd/snmpmanager/Makefile.am b/snmpd/snmpmanager/Makefile.am index 9d217a28..ca7c22a2 100644 --- a/snmpd/snmpmanager/Makefile.am +++ b/snmpd/snmpmanager/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/snmpd/snmpmanager/Makefile.in b/snmpd/snmpmanager/Makefile.in index a1968630..2ec5ab59 100644 --- a/snmpd/snmpmanager/Makefile.in +++ b/snmpd/snmpmanager/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 864 2009-04-02 19:22:49Z rdempsey $ @@ -60,9 +60,8 @@ subdir = snmpd/snmpmanager DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -158,9 +157,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -202,7 +198,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -216,11 +211,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/snmpd/snmpmanager/alarm.h b/snmpd/snmpmanager/alarm.h index 7d71a7a2..b6a4d13c 100644 --- a/snmpd/snmpmanager/alarm.h +++ b/snmpd/snmpmanager/alarm.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** -* $Id: alarm.h 781 2013-01-21 14:12:44Z rdempsey $ +* $Id: alarm.h 678 2012-04-04 18:20:46Z rdempsey $ * * Author: Zhixuan Zhu ******************************************************************************************/ diff --git a/snmpd/snmpmanager/snmpglobal.h b/snmpd/snmpmanager/snmpglobal.h index 2aae33d9..87acad5e 100644 --- a/snmpd/snmpmanager/snmpglobal.h +++ b/snmpd/snmpmanager/snmpglobal.h @@ -18,6 +18,12 @@ #ifndef SNMPGLOBAL_H #define SNMPGLOBAL_H +//Major hack to get oam and brm to play nice. +#ifdef OAM_BRM_LEAN_AND_MEAN +#include +#include +typedef u_long oid; +#else #ifdef __linux__ #include #include @@ -30,7 +36,8 @@ #include "net-snmp/net-snmp-includes.h" #include "net-snmp/agent/net-snmp-agent-includes.h" #else -typedef uint64_t oid; +typedef u_long oid; +#endif #endif namespace snmpmanager { diff --git a/snmpd/snmpmanager/snmpmanager.h b/snmpd/snmpmanager/snmpmanager.h index 14e2fc30..5bbaabc4 100644 --- a/snmpd/snmpmanager/snmpmanager.h +++ b/snmpd/snmpmanager/snmpmanager.h @@ -24,9 +24,15 @@ #ifndef SNMP_MANAGER_H #define SNMP_MANAGER_H +//Major hack to get oam and brm to play nice. +#ifdef OAM_BRM_LEAN_AND_MEAN #include #include #include "alarm.h" +#else +#include "alarm.h" +#include "messageobj.h" +#endif #if defined(_MSC_VER) && defined(xxxSNMPMANAGER_DLLEXPORT) #define EXPORT __declspec(dllexport) diff --git a/tools/Makefile.am b/tools/Makefile.am index 37c94fa9..e2a7fc0b 100644 --- a/tools/Makefile.am +++ b/tools/Makefile.am @@ -1,26 +1,25 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ SUBDIRS = dbbuilder editem dbloadxml \ getConfig cplogger \ - clearShm setConfig \ - configMgt viewtablelock cleartablelock ddlcleanup \ + clearShm setConfig viewtablelock cleartablelock ddlcleanup \ idbmeminfo test: diff --git a/tools/Makefile.in b/tools/Makefile.in index 48f176d0..10d6b7be 100644 --- a/tools/Makefile.in +++ b/tools/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 878 2009-04-03 20:34:32Z rdempsey $ srcdir = @srcdir@ @@ -57,9 +57,8 @@ host_triplet = @host@ subdir = tools DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -211,8 +201,7 @@ target_alias = @target_alias@ toolsdir = @toolsdir@ SUBDIRS = dbbuilder editem dbloadxml \ getConfig cplogger \ - clearShm setConfig \ - configMgt viewtablelock cleartablelock ddlcleanup \ + clearShm setConfig viewtablelock cleartablelock ddlcleanup \ idbmeminfo all: all-recursive diff --git a/tools/bincvt/li2bin.cpp b/tools/bincvt/li2bin.cpp deleted file mode 100644 index 901170d5..00000000 --- a/tools/bincvt/li2bin.cpp +++ /dev/null @@ -1,239 +0,0 @@ -#include -#ifdef _MSC_VER -#include -#include -#include -#else -#include -#endif -#include -#include -#include -//#define NDEBUG -#include -using namespace std; - -#include -#include -using namespace boost; - -#ifdef _MSC_VER -namespace -{ - inline long long atoll(const char* s) - { - return _strtoi64(s, 0, 10); - } - inline uint64_t strtoull(const char* s, char** a, int b) - { - return _strtoi64(s, a, b); - } -} -#endif - -//1|155190|7706|1|17|21168.23|0.04|0.02|N|O|1996-03-13|1996-02-12|1996-03-22|DELIVER IN PERSON|TRUCK|egular courts above the| - -#pragma pack(1) -struct lineitem_image -{ - int32_t l_orderkey; - int32_t l_partkey; - int32_t l_suppkey; //12 - int64_t l_linenumber; - int64_t l_quantity; - int64_t l_extendedprice; - int64_t l_discount; - int64_t l_tax; //40 - char l_returnflag; - char l_linestatus; //2 - int32_t l_shipdate; - int32_t l_commitdate; - int32_t l_receiptdate; //12 - char l_shipinstruct[25]; - char l_shipmode[10]; - char l_comment[44]; //79 -}; -BOOST_STATIC_ASSERT(sizeof(struct lineitem_image) == 145); - -// version of lineitem_image that treats some integer columns as unsigned ints. -// Decimal, date, and date/time columns are still treated as integer. -struct unsigned_lineitem_image -{ - uint32_t l_orderkey; - uint32_t l_partkey; - uint32_t l_suppkey; //12 - uint64_t l_linenumber; - int64_t l_quantity; - int64_t l_extendedprice; - int64_t l_discount; - int64_t l_tax; //40 - char l_returnflag; - char l_linestatus; //2 - int32_t l_shipdate; - int32_t l_commitdate; - int32_t l_receiptdate; //12 - char l_shipinstruct[25]; - char l_shipmode[10]; - char l_comment[44]; //79 -}; -BOOST_STATIC_ASSERT(sizeof(struct unsigned_lineitem_image) == 145); - -struct Date -{ - unsigned spare : 6; - unsigned day : 6; - unsigned month : 4; - unsigned year : 16; -}; -BOOST_STATIC_ASSERT(sizeof(struct Date) == 4); - -union date_image -{ - struct Date d; - int32_t i; -}; - -namespace -{ -typedef boost::tokenizer > tokenizer; - -int64_t idbbigdec2(const string& str) -{ - int64_t val=0; - string::size_type idx=string::npos; - string tmp(str); - idx = tmp.find('.'); - if (idx != string::npos) - tmp.erase(idx, 1); - else - tmp.append("00"); - val = atoll(tmp.c_str()); - return val; -} - -int32_t idbdate(const string& str) -{ - date_image di; - di.i = 0; - boost::char_separator sep("-"); - tokenizer tokens(str, sep); - tokenizer::iterator tok_iter = tokens.begin(); - - // Note that the spare bits must be set, instead of leaving them - // initialized to 0; to be compatible with internal date format. - if (distance(tok_iter, tokens.end()) == 3) - { - di.d.spare = 0x3E; - di.d.year = atoi(tok_iter->c_str()); ++tok_iter; - di.d.month = atoi(tok_iter->c_str()); ++tok_iter; - di.d.day = atoi(tok_iter->c_str()); ++tok_iter; - } - - return di.i; -} - -int parseinto(lineitem_image& img, const string& buf) -{ - memset(&img, 0, sizeof(img)); - - boost::char_separator sep("|"); - tokenizer tokens(buf, sep); - tokenizer::iterator tok_iter = tokens.begin(); - - if (distance(tok_iter, tokens.end()) < 16) - return -1; - - img.l_orderkey = atoi(tok_iter->c_str()); ++tok_iter; - img.l_partkey = atoi(tok_iter->c_str()); ++tok_iter; - img.l_suppkey = atoi(tok_iter->c_str()); ++tok_iter; - img.l_linenumber = atoll(tok_iter->c_str()); ++tok_iter; - img.l_quantity = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_extendedprice = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_discount = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_tax = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_returnflag = tok_iter->at(0); ++tok_iter; - img.l_linestatus = tok_iter->at(0); ++tok_iter; - img.l_shipdate = idbdate(tok_iter->c_str()); ++tok_iter; - img.l_commitdate = idbdate(tok_iter->c_str()); ++tok_iter; - img.l_receiptdate = idbdate(tok_iter->c_str()); ++tok_iter; - memcpy(&img.l_shipinstruct[0], tok_iter->c_str(), tok_iter->size()); ++tok_iter; - memcpy(&img.l_shipmode[0], tok_iter->c_str(), tok_iter->size()); ++tok_iter; - memcpy(&img.l_comment[0], tok_iter->c_str(), tok_iter->size()); ++tok_iter; - - return 0; -} - -int unsigned_parseinto(unsigned_lineitem_image& img, const string& buf) -{ - memset(&img, 0, sizeof(img)); - - boost::char_separator sep("|"); - tokenizer tokens(buf, sep); - tokenizer::iterator tok_iter = tokens.begin(); - - if (distance(tok_iter, tokens.end()) < 16) - return -1; - - img.l_orderkey = strtoul(tok_iter->c_str(),0,10); ++tok_iter; - img.l_partkey = strtoul(tok_iter->c_str(),0,10); ++tok_iter; - img.l_suppkey = strtoul(tok_iter->c_str(),0,10); ++tok_iter; - img.l_linenumber = strtoull(tok_iter->c_str(),0,10); ++tok_iter; - img.l_quantity = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_extendedprice = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_discount = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_tax = idbbigdec2(tok_iter->c_str()); ++tok_iter; - img.l_returnflag = tok_iter->at(0); ++tok_iter; - img.l_linestatus = tok_iter->at(0); ++tok_iter; - img.l_shipdate = idbdate(tok_iter->c_str()); ++tok_iter; - img.l_commitdate = idbdate(tok_iter->c_str()); ++tok_iter; - img.l_receiptdate = idbdate(tok_iter->c_str()); ++tok_iter; - memcpy(&img.l_shipinstruct[0], tok_iter->c_str(), tok_iter->size()); ++tok_iter; - memcpy(&img.l_shipmode[0], tok_iter->c_str(), tok_iter->size()); ++tok_iter; - memcpy(&img.l_comment[0], tok_iter->c_str(), tok_iter->size()); ++tok_iter; - - return 0; -} - -} - -int main(int argc, char** argv) -{ - if ((argc > 1) && (strcmp(argv[1],"-h") == 0)) - { - std::cerr << "li2bin [-u]" << std::endl; - std::cerr << " -u Create first 4 fields as unsigned integers" << std::endl; - return 0; - } - - string input; - -#ifdef _MSC_VER - _setmode(1, _O_BINARY); -#endif - - getline(cin, input); - if ((argc > 1) && (strcmp(argv[1],"-u") == 0)) - { - unsigned_lineitem_image i; - while (!cin.eof()) - { - if (unsigned_parseinto(i, input) == 0) - cout.write(reinterpret_cast(&i), sizeof(i)); - getline(cin, input); - } - } - else - { - lineitem_image i; - while (!cin.eof()) - { - if (parseinto(i, input) == 0) - cout.write(reinterpret_cast(&i), sizeof(i)); - getline(cin, input); - } - } - - return 0; -} -// vim:ts=4 sw=4: - diff --git a/tools/brmtest/Makefile.am b/tools/brmtest/Makefile.am deleted file mode 100644 index 922b5b06..00000000 --- a/tools/brmtest/Makefile.am +++ /dev/null @@ -1,23 +0,0 @@ -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = brmtest -brmtest_SOURCES = brmtest.cpp locks.cpp -brmtest_CPPFLAGS = -I@prefix@/Calpont/include -I/usr/include/libxml2 $(AM_CPPFLAGS) -brmtest_LDFLAGS = @idb_common_ldflags@ -lexecplan -ljoblist -lrowgroup -ldataconvert -lloggingcpp -l@boost_thread_lib@ -lbrm -lmessageqcpp -lrwlock -lconfigcpp -lxml2 -ljoiner \ --loamcpp -lsnmpmanager -l@boost_filesystem_lib@ -l@boost_date_time_lib@ @netsnmp_libs@ -lmulticast -lfuncexp $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/brmtest/brmtest.cpp b/tools/brmtest/brmtest.cpp deleted file mode 100644 index 88d87ee0..00000000 --- a/tools/brmtest/brmtest.cpp +++ /dev/null @@ -1,645 +0,0 @@ -/* -* $Id: brmtest.cpp 1739 2012-03-22 12:57:59Z pleblanc $ -*/ - -#include -#include -#include -#include -#include -using namespace std; - -#include -#include -#include - -#include "calpontsystemcatalog.h" -using namespace execplan; - -#include "extentmap.h" -#include "blockresolutionmanager.h" -using namespace BRM; - -#include "configcpp.h" -using namespace config; - -extern int query_locks(); -extern int reset_locks(); - -namespace { - -boost::shared_ptr Cat; - -void LBIDList(CalpontSystemCatalog::OID OID, ostringstream& cout_str) -{ - LBIDRange_v LBIDRanges; - - LBIDRange_v::size_type RangeCount; - ExtentMap em; - LBIDRange_v::size_type i; - LBIDRange LBIDR; - - cout_str << "HWM = " << em.getHWM(OID) << endl; - - em.lookup(OID, LBIDRanges); - RangeCount = LBIDRanges.size(); - idbassert(RangeCount < 1000); - - for (i = 0; i < RangeCount; i++) - { - LBIDR = LBIDRanges[i]; - cout_str << LBIDR.start << " - " << (LBIDR.start + LBIDR.size - 1) << " (" << LBIDR.size << ')'; - int64_t max=-1, min=-1; - int32_t seqNum=0; - em.getMaxMin(LBIDR.start, max, min, seqNum); - cout_str << " min: " << min << ", max: " << max << ", seqNum: " << seqNum << endl; - } - cout_str << endl; -} - -void doit(const CalpontSystemCatalog::TableColName& tcn, ostringstream& cout_str) -{ - CalpontSystemCatalog::OID OID; - try { - OID = Cat->columnRID(tcn).objnum; - } - catch (...) { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": OID not found" << endl; - return; - } - - if (OID > 0) - { - - CalpontSystemCatalog::OID ioid = Cat->lookupOID(tcn); - CalpontSystemCatalog::ColType CT = Cat->colType(ioid); - - CalpontSystemCatalog::DictOID DOID = CT.ddn; - - int DictOID = DOID.dictOID; - int ListOID = DOID.listOID; - int TreeOID = DOID.treeOID; - - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": OID = " << OID << endl; - try { - LBIDList(OID, cout_str); - } - catch (exception& ex) { - cerr << ex.what() << endl; - } - - if(DictOID > 0) - { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": DictOID = " << DictOID << endl; - - try { - LBIDList(DictOID, cout_str); - } - catch (exception& ex) { - cerr << ex.what() << endl; - } - } - if(ListOID > 0) - { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": DictListOID = " << ListOID << endl; - - try { - LBIDList(ListOID, cout_str); - } - catch (exception& ex) { - cerr << ex.what() << endl; - } - } - if(TreeOID > 0) - { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": DictTreeOID = " << TreeOID << endl; - - try { - LBIDList(TreeOID, cout_str); - } - catch (exception& ex) { - cerr << ex.what() << endl; - } - } - - CalpontSystemCatalog::IndexOID IOID = Cat->lookupIndexNbr(tcn); - if (IOID.objnum > 0) - { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": IndexOID = " << IOID.objnum << endl; - - try { - LBIDList(IOID.objnum, cout_str); - } - catch (exception& ex) { - cerr << ex.what() << endl; - } - } - if (IOID.listOID > 0) - { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": IndexLstOID = " << IOID.listOID << endl; - - try { - LBIDList(IOID.listOID, cout_str); - } - catch (exception& ex) { - cerr << ex.what() << endl; - } - } - } - else - { - cout_str << tcn.schema << '.' << tcn.table << '.' << tcn.column << ": OID was zero!" << endl; - } -} - -void usage(ostringstream& cout_str) -{ - cout_str << "usage: brmtest [-hrts] [-l LBID] [-c schema]" << endl; - cout_str << "\t-h display this help" << endl; - cout_str << "\t-r reset brm locks" << endl; - cout_str << "\t-l LBID display info about LBID" << endl; - cout_str << "\t-t dump TPC-H tables" << endl; - cout_str << "\t-s don't dump system catalog" << endl; - cout_str << "\t-c schema seach for TPC-H tables in schema" << endl; -} - -} - -int main(int argc, char** argv) -{ - int c; - - bool rflg = false; - bool lflg = false; - bool tflg = false; - bool sflg = true; - bool qflg = false; - - opterr = 0; - - uint64_t lbid = 0; - - ostringstream cout_str; - ostringstream cerr_str; - - string schema("tpch"); - - while ((c = getopt(argc, argv, "hrl:tsc:q")) != EOF) - switch (c) - { - case 'r': - rflg = true; - break; - case 'l': - lflg = true; - lbid = strtoul(optarg, 0, 0); - break; - case 'h': - usage(cout_str); - cerr << cout_str.str() << endl; - exit(0); - break; - case 't': - tflg = true; - break; - case 's': - sflg = false; - break; - case 'c': - schema = optarg; - break; - case 'q': - qflg = true; - break; - default: - usage(cout_str); - cerr << cout_str.str() << endl; - exit(1); - break; - } - - if (rflg) - { - reset_locks(); - return 0; - } - - if (query_locks() != 0) - { - cerr << "BRM is locked!" << endl; - return 1; - } - - if (lflg) - { - BlockResolutionManager brm; - uint16_t ver = 0; - BRM::OID_t oid; - uint32_t fbo; - int rc; - rc = brm.lookup(lbid, ver, false, oid, fbo); - idbassert(rc == 0); - if (qflg) - cout << oid << endl; - else - cout << "LBID " << lbid << " is part of OID " << oid << " at FBO " << fbo << endl; - return 0; - } - - //Now, close out all output so we don't get any debug from PG/RA - int fd; - ::close(2); - ::close(1); - //fd = open("./brmtest.out", O_WRONLY|O_CREAT|O_TRUNC, 0666); - fd = open("/dev/null", O_WRONLY); - idbassert(fd >= 0); - if (fd != 1) dup2(fd, 1); - //fd = open("./brmtest.err", O_WRONLY|O_CREAT|O_TRUNC, 0666); - fd = open("/dev/null", O_WRONLY); - idbassert(fd >= 0); - if (fd != 2) dup2(fd, 2); - - Cat = CalpontSystemCatalog::makeCalpontSystemCatalog(); - - fd = ::open("/dev/tty", O_WRONLY); - idbassert(fd >= 0); - - string status; - if (tflg) - { - const string region("region"); - const string nation("nation"); - const string customer("customer"); - const string orders("orders"); - const string supplier("supplier"); - const string partsupp("partsupp"); - const string lineitem("lineitem"); - const string part("part"); - - status = "Reading REGION...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, region, "r_regionkey"), cout_str); - doit(make_tcn(schema, region, "r_name"), cout_str); - doit(make_tcn(schema, region, "r_comment"), cout_str); - - status = "Reading NATION...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, nation, "n_nationkey"), cout_str); - doit(make_tcn(schema, nation, "n_name"), cout_str); - doit(make_tcn(schema, nation, "n_regionkey"), cout_str); - doit(make_tcn(schema, nation, "n_comment"), cout_str); - - status = "Reading CUSTOMER...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, customer, "c_custkey"), cout_str); - doit(make_tcn(schema, customer, "c_name"), cout_str); - doit(make_tcn(schema, customer, "c_address"), cout_str); - doit(make_tcn(schema, customer, "c_nationkey"), cout_str); - doit(make_tcn(schema, customer, "c_phone"), cout_str); - doit(make_tcn(schema, customer, "c_acctbal"), cout_str); - doit(make_tcn(schema, customer, "c_mktsegment"), cout_str); - doit(make_tcn(schema, customer, "c_comment"), cout_str); - - status = "Reading ORDERS...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, orders, "o_orderkey"), cout_str); - doit(make_tcn(schema, orders, "o_custkey"), cout_str); - doit(make_tcn(schema, orders, "o_orderstatus"), cout_str); - doit(make_tcn(schema, orders, "o_totalprice"), cout_str); - doit(make_tcn(schema, orders, "o_orderdate"), cout_str); - doit(make_tcn(schema, orders, "o_orderpriority"), cout_str); - doit(make_tcn(schema, orders, "o_clerk"), cout_str); - doit(make_tcn(schema, orders, "o_shippriority"), cout_str); - doit(make_tcn(schema, orders, "o_comment"), cout_str); - - status = "Reading PART...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, part, "p_partkey"), cout_str); - doit(make_tcn(schema, part, "p_name"), cout_str); - doit(make_tcn(schema, part, "p_mfgr"), cout_str); - doit(make_tcn(schema, part, "p_brand"), cout_str); - doit(make_tcn(schema, part, "p_type"), cout_str); - doit(make_tcn(schema, part, "p_size"), cout_str); - doit(make_tcn(schema, part, "p_container"), cout_str); - doit(make_tcn(schema, part, "p_retailprice"), cout_str); - doit(make_tcn(schema, part, "p_comment"), cout_str); - - status = "Reading SUPPLIER...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, supplier, "s_suppkey"), cout_str); - doit(make_tcn(schema, supplier, "s_name"), cout_str); - doit(make_tcn(schema, supplier, "s_address"), cout_str); - doit(make_tcn(schema, supplier, "s_nationkey"), cout_str); - doit(make_tcn(schema, supplier, "s_phone"), cout_str); - doit(make_tcn(schema, supplier, "s_acctbal"), cout_str); - doit(make_tcn(schema, supplier, "s_comment"), cout_str); - - status = "Reading PARTSUPP...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, partsupp, "ps_partkey"), cout_str); - doit(make_tcn(schema, partsupp, "ps_suppkey"), cout_str); - doit(make_tcn(schema, partsupp, "ps_availqty"), cout_str); - doit(make_tcn(schema, partsupp, "ps_supplycost"), cout_str); - doit(make_tcn(schema, partsupp, "ps_comment"), cout_str); - - status = "Reading LINEITEM...\n"; - ::write(fd, status.c_str(), status.length()); - - doit(make_tcn(schema, lineitem, "l_orderkey"), cout_str); - doit(make_tcn(schema, lineitem, "l_linenumber"), cout_str); - doit(make_tcn(schema, lineitem, "l_partkey"), cout_str); - doit(make_tcn(schema, lineitem, "l_suppkey"), cout_str); - doit(make_tcn(schema, lineitem, "l_quantity"), cout_str); - doit(make_tcn(schema, lineitem, "l_extendedprice"), cout_str); - doit(make_tcn(schema, lineitem, "l_discount"), cout_str); - doit(make_tcn(schema, lineitem, "l_tax"), cout_str); - doit(make_tcn(schema, lineitem, "l_returnflag"), cout_str); - doit(make_tcn(schema, lineitem, "l_linestatus"), cout_str); - doit(make_tcn(schema, lineitem, "l_shipdate"), cout_str); - doit(make_tcn(schema, lineitem, "l_commitdate"), cout_str); - doit(make_tcn(schema, lineitem, "l_receiptdate"), cout_str); - doit(make_tcn(schema, lineitem, "l_shipinstruct"), cout_str); - doit(make_tcn(schema, lineitem, "l_shipmode"), cout_str); - doit(make_tcn(schema, lineitem, "l_comment"), cout_str); - } - - if (sflg) - { - status = "Reading CALPONTSYS...\n\n"; - ::write(fd, status.c_str(), status.length()); - - schema = CALPONT_SCHEMA; - string table = SYSCOLUMN_TABLE; - doit(make_tcn(schema, table, SCHEMA_COL), cout_str); - doit(make_tcn(schema, table, TABLENAME_COL), cout_str); - doit(make_tcn(schema, table, COLNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, MULTICOLFLAG_COL), cout_str); - doit(make_tcn(schema, table, OBJECTID_COL), cout_str); - doit(make_tcn(schema, table, DICTOID_COL), cout_str); - doit(make_tcn(schema, table, LISTOBJID_COL), cout_str); - doit(make_tcn(schema, table, TREEOBJID_COL), cout_str); - doit(make_tcn(schema, table, DATATYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNTYPE_COL), cout_str); - doit(make_tcn(schema, table, COLUMNLEN_COL), cout_str); - doit(make_tcn(schema, table, COLUMNPOS_COL), cout_str); - ///doit(make_tcn(schema, table, CREATEDATE_COL), cout_str); - doit(make_tcn(schema, table, LASTUPDATE_COL), cout_str); - doit(make_tcn(schema, table, DEFAULTVAL_COL), cout_str); - doit(make_tcn(schema, table, NULLABLE_COL), cout_str); - doit(make_tcn(schema, table, SCALE_COL), cout_str); - doit(make_tcn(schema, table, PRECISION_COL), cout_str); - ///doit(make_tcn(schema, table, NUMNULLS_COL), cout_str); - ///doit(make_tcn(schema, table, NUMDISTINCTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MINVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MAXVAL_COL), cout_str); - ///doit(make_tcn(schema, table, DENSITY_COL), cout_str); - ///doit(make_tcn(schema, table, AVGRECORDLEN_COL), cout_str); - ///doit(make_tcn(schema, table, RECORDCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, LASTANYLDATE_COL), cout_str); - ///doit(make_tcn(schema, table, SAMPLESIZE_COL), cout_str); - ///doit(make_tcn(schema, table, PROPERTY_COL), cout_str); - doit(make_tcn(schema, table, AUTOINC_COL), cout_str); - ///doit(make_tcn(schema, table, DATANAME_COL), cout_str); - ///doit(make_tcn(schema, table, CATEGORY_COL), cout_str); - ///doit(make_tcn(schema, table, SIZE_COL), cout_str); - ///doit(make_tcn(schema, table, DESC_COL), cout_str); - ///doit(make_tcn(schema, table, INIT_COL), cout_str); - ///doit(make_tcn(schema, table, NEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNAME_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNUM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTPRIM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTSTATUS_COL), cout_str); - ///doit(make_tcn(schema, table, TREELEVEL_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, DISTINCTKEYS_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFBLOCKS_COL), cout_str); - ///doit(make_tcn(schema, table, AVGLEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, AVGDATABLOCK_COL), cout_str); - ///doit(make_tcn(schema, table, CLUSTERFACTOR_COL), cout_str); - - table = SYSTABLE_TABLE; - doit(make_tcn(schema, table, SCHEMA_COL), cout_str); - doit(make_tcn(schema, table, TABLENAME_COL), cout_str); - ///doit(make_tcn(schema, table, COLNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, MULTICOLFLAG_COL), cout_str); - doit(make_tcn(schema, table, OBJECTID_COL), cout_str); - ///doit(make_tcn(schema, table, DICTOID_COL), cout_str); - ///doit(make_tcn(schema, table, LISTOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, TREEOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, DATATYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNLEN_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNPOS_COL), cout_str); - doit(make_tcn(schema, table, CREATEDATE_COL), cout_str); - doit(make_tcn(schema, table, LASTUPDATE_COL), cout_str); - ///doit(make_tcn(schema, table, DEFAULTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, NULLABLE_COL), cout_str); - ///doit(make_tcn(schema, table, SCALE_COL), cout_str); - ///doit(make_tcn(schema, table, PRECISION_COL), cout_str); - ///doit(make_tcn(schema, table, NUMNULLS_COL), cout_str); - ///doit(make_tcn(schema, table, NUMDISTINCTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MINVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MAXVAL_COL), cout_str); - ///doit(make_tcn(schema, table, DENSITY_COL), cout_str); - ///doit(make_tcn(schema, table, AVGRECORDLEN_COL), cout_str); - ///doit(make_tcn(schema, table, RECORDCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, LASTANYLDATE_COL), cout_str); - ///doit(make_tcn(schema, table, SAMPLESIZE_COL), cout_str); - ///doit(make_tcn(schema, table, PROPERTY_COL), cout_str); - ///doit(make_tcn(schema, table, AUTOINC_COL), cout_str); - ///doit(make_tcn(schema, table, DATANAME_COL), cout_str); - ///doit(make_tcn(schema, table, CATEGORY_COL), cout_str); - ///doit(make_tcn(schema, table, SIZE_COL), cout_str); - ///doit(make_tcn(schema, table, DESC_COL), cout_str); - doit(make_tcn(schema, table, INIT_COL), cout_str); - doit(make_tcn(schema, table, NEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNAME_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNUM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTPRIM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTSTATUS_COL), cout_str); - ///doit(make_tcn(schema, table, TREELEVEL_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, DISTINCTKEYS_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFBLOCKS_COL), cout_str); - ///doit(make_tcn(schema, table, AVGLEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, AVGDATABLOCK_COL), cout_str); - ///doit(make_tcn(schema, table, CLUSTERFACTOR_COL), cout_str); - - table = SYSSCHEMA_TABLE; - ///doit(make_tcn(schema, table, SCHEMA_COL), cout_str); - ///doit(make_tcn(schema, table, TABLENAME_COL), cout_str); - ///doit(make_tcn(schema, table, COLNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, MULTICOLFLAG_COL), cout_str); - ///doit(make_tcn(schema, table, OBJECTID_COL), cout_str); - ///doit(make_tcn(schema, table, DICTOID_COL), cout_str); - ///doit(make_tcn(schema, table, LISTOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, TREEOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, DATATYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNLEN_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNPOS_COL), cout_str); - ///doit(make_tcn(schema, table, CREATEDATE_COL), cout_str); - ///doit(make_tcn(schema, table, LASTUPDATE_COL), cout_str); - ///doit(make_tcn(schema, table, DEFAULTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, NULLABLE_COL), cout_str); - ///doit(make_tcn(schema, table, SCALE_COL), cout_str); - ///doit(make_tcn(schema, table, PRECISION_COL), cout_str); - ///doit(make_tcn(schema, table, NUMNULLS_COL), cout_str); - ///doit(make_tcn(schema, table, NUMDISTINCTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MINVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MAXVAL_COL), cout_str); - ///doit(make_tcn(schema, table, DENSITY_COL), cout_str); - ///doit(make_tcn(schema, table, AVGRECORDLEN_COL), cout_str); - ///doit(make_tcn(schema, table, RECORDCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, LASTANYLDATE_COL), cout_str); - ///doit(make_tcn(schema, table, SAMPLESIZE_COL), cout_str); - ///doit(make_tcn(schema, table, PROPERTY_COL), cout_str); - ///doit(make_tcn(schema, table, AUTOINC_COL), cout_str); - ///doit(make_tcn(schema, table, DATANAME_COL), cout_str); - ///doit(make_tcn(schema, table, CATEGORY_COL), cout_str); - ///doit(make_tcn(schema, table, SIZE_COL), cout_str); - ///doit(make_tcn(schema, table, DESC_COL), cout_str); - ///doit(make_tcn(schema, table, INIT_COL), cout_str); - ///doit(make_tcn(schema, table, NEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNAME_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNUM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTPRIM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTSTATUS_COL), cout_str); - ///doit(make_tcn(schema, table, TREELEVEL_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, DISTINCTKEYS_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFBLOCKS_COL), cout_str); - ///doit(make_tcn(schema, table, AVGLEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, AVGDATABLOCK_COL), cout_str); - ///doit(make_tcn(schema, table, CLUSTERFACTOR_COL), cout_str); - - table = SYSINDEX_TABLE; - doit(make_tcn(schema, table, SCHEMA_COL), cout_str); - doit(make_tcn(schema, table, TABLENAME_COL), cout_str); - ///doit(make_tcn(schema, table, COLNAME_COL), cout_str); - doit(make_tcn(schema, table, INDEXNAME_COL), cout_str); - doit(make_tcn(schema, table, INDEXTYPE_COL), cout_str); - doit(make_tcn(schema, table, MULTICOLFLAG_COL), cout_str); - ///doit(make_tcn(schema, table, OBJECTID_COL), cout_str); - ///doit(make_tcn(schema, table, DICTOID_COL), cout_str); - doit(make_tcn(schema, table, LISTOBJID_COL), cout_str); - doit(make_tcn(schema, table, TREEOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, DATATYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNLEN_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNPOS_COL), cout_str); - doit(make_tcn(schema, table, CREATEDATE_COL), cout_str); - doit(make_tcn(schema, table, LASTUPDATE_COL), cout_str); - ///doit(make_tcn(schema, table, DEFAULTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, NULLABLE_COL), cout_str); - ///doit(make_tcn(schema, table, SCALE_COL), cout_str); - ///doit(make_tcn(schema, table, PRECISION_COL), cout_str); - ///doit(make_tcn(schema, table, NUMNULLS_COL), cout_str); - ///doit(make_tcn(schema, table, NUMDISTINCTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MINVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MAXVAL_COL), cout_str); - ///doit(make_tcn(schema, table, DENSITY_COL), cout_str); - ///doit(make_tcn(schema, table, AVGRECORDLEN_COL), cout_str); - doit(make_tcn(schema, table, RECORDCOUNT_COL), cout_str); - doit(make_tcn(schema, table, LASTANYLDATE_COL), cout_str); - doit(make_tcn(schema, table, SAMPLESIZE_COL), cout_str); - ///doit(make_tcn(schema, table, PROPERTY_COL), cout_str); - ///doit(make_tcn(schema, table, AUTOINC_COL), cout_str); - ///doit(make_tcn(schema, table, DATANAME_COL), cout_str); - ///doit(make_tcn(schema, table, CATEGORY_COL), cout_str); - ///doit(make_tcn(schema, table, SIZE_COL), cout_str); - ///doit(make_tcn(schema, table, DESC_COL), cout_str); - ///doit(make_tcn(schema, table, INIT_COL), cout_str); - ///doit(make_tcn(schema, table, NEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNAME_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNUM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTPRIM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTSTATUS_COL), cout_str); - doit(make_tcn(schema, table, TREELEVEL_COL), cout_str); - doit(make_tcn(schema, table, LEAFCOUNT_COL), cout_str); - doit(make_tcn(schema, table, DISTINCTKEYS_COL), cout_str); - doit(make_tcn(schema, table, LEAFBLOCKS_COL), cout_str); - doit(make_tcn(schema, table, AVGLEAFCOUNT_COL), cout_str); - doit(make_tcn(schema, table, AVGDATABLOCK_COL), cout_str); - doit(make_tcn(schema, table, CLUSTERFACTOR_COL), cout_str); - - table = SYSINDEXCOL_TABLE; - doit(make_tcn(schema, table, SCHEMA_COL), cout_str); - doit(make_tcn(schema, table, TABLENAME_COL), cout_str); - doit(make_tcn(schema, table, COLNAME_COL), cout_str); - doit(make_tcn(schema, table, INDEXNAME_COL), cout_str); - ///doit(make_tcn(schema, table, INDEXTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, MULTICOLFLAG_COL), cout_str); - ///doit(make_tcn(schema, table, OBJECTID_COL), cout_str); - ///doit(make_tcn(schema, table, DICTOID_COL), cout_str); - ///doit(make_tcn(schema, table, LISTOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, TREEOBJID_COL), cout_str); - ///doit(make_tcn(schema, table, DATATYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, COLUMNLEN_COL), cout_str); - doit(make_tcn(schema, table, COLUMNPOS_COL), cout_str); - ///doit(make_tcn(schema, table, CREATEDATE_COL), cout_str); - ///doit(make_tcn(schema, table, LASTUPDATE_COL), cout_str); - ///doit(make_tcn(schema, table, DEFAULTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, NULLABLE_COL), cout_str); - ///doit(make_tcn(schema, table, SCALE_COL), cout_str); - ///doit(make_tcn(schema, table, PRECISION_COL), cout_str); - ///doit(make_tcn(schema, table, NUMNULLS_COL), cout_str); - ///doit(make_tcn(schema, table, NUMDISTINCTVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MINVAL_COL), cout_str); - ///doit(make_tcn(schema, table, MAXVAL_COL), cout_str); - ///doit(make_tcn(schema, table, DENSITY_COL), cout_str); - ///doit(make_tcn(schema, table, AVGRECORDLEN_COL), cout_str); - ///doit(make_tcn(schema, table, RECORDCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, LASTANYLDATE_COL), cout_str); - ///doit(make_tcn(schema, table, SAMPLESIZE_COL), cout_str); - ///doit(make_tcn(schema, table, PROPERTY_COL), cout_str); - ///doit(make_tcn(schema, table, AUTOINC_COL), cout_str); - ///doit(make_tcn(schema, table, DATANAME_COL), cout_str); - ///doit(make_tcn(schema, table, CATEGORY_COL), cout_str); - ///doit(make_tcn(schema, table, SIZE_COL), cout_str); - ///doit(make_tcn(schema, table, DESC_COL), cout_str); - ///doit(make_tcn(schema, table, INIT_COL), cout_str); - ///doit(make_tcn(schema, table, NEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNAME_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTNUM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTYPE_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTPRIM_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTTEXT_COL), cout_str); - ///doit(make_tcn(schema, table, CONSTRAINTSTATUS_COL), cout_str); - ///doit(make_tcn(schema, table, TREELEVEL_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, DISTINCTKEYS_COL), cout_str); - ///doit(make_tcn(schema, table, LEAFBLOCKS_COL), cout_str); - ///doit(make_tcn(schema, table, AVGLEAFCOUNT_COL), cout_str); - ///doit(make_tcn(schema, table, AVGDATABLOCK_COL), cout_str); - ///doit(make_tcn(schema, table, CLUSTERFACTOR_COL), cout_str); - } - - cout_str << ends; - ::write(fd, cout_str.str().c_str(), cout_str.str().length()); - - return 0; -} - diff --git a/tools/brmtest/locks.cpp b/tools/brmtest/locks.cpp deleted file mode 100644 index 1b74c7d3..00000000 --- a/tools/brmtest/locks.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* -* $Id: locks.cpp 282 2007-10-28 02:18:55Z rdempsey $ -*/ - -#include -#include -using namespace std; - -#include "sessionmanager.h" -#include "calpontsystemcatalog.h" -using namespace execplan; - -#include "shmkeys.h" -#include "rwlock.h" -#include "mastersegmenttable.h" -using namespace BRM; - -int query_locks() -{ - ShmKeys keys; - RWLock *rwlock[MasterSegmentTable::nTables]; - int RWLockKeys[MasterSegmentTable::nTables]; - int i; - - RWLockKeys[0] = keys.KEYRANGE_EXTENTMAP_BASE; - RWLockKeys[1] = keys.KEYRANGE_EMFREELIST_BASE; - RWLockKeys[2] = keys.KEYRANGE_VBBM_BASE; - RWLockKeys[3] = keys.KEYRANGE_VSS_BASE; - RWLockKeys[4] = keys.KEYRANGE_CL_BASE; - - for (i = 0; i < MasterSegmentTable::nTables; i++) - rwlock[i] = new RWLock(RWLockKeys[i]); - - for (i = 0; i < MasterSegmentTable::nTables; i++) - if (rwlock[i]->getWriting() > 0 || - //rwlock[i]->getReading() > 0 || - rwlock[i]->getWritersWaiting() > 0 || - rwlock[i]->getReadersWaiting() > 0) - return 1; - - for (i = 0; i < MasterSegmentTable::nTables; i++) - delete rwlock[i]; - - return 0; -} - -int reset_locks() -{ - ShmKeys keys; - RWLock *rwlock[MasterSegmentTable::nTables]; - int RWLockKeys[MasterSegmentTable::nTables]; - int i; - SessionManager sm(true); - - RWLockKeys[0] = keys.KEYRANGE_EXTENTMAP_BASE; - RWLockKeys[1] = keys.KEYRANGE_EMFREELIST_BASE; - RWLockKeys[2] = keys.KEYRANGE_VBBM_BASE; - RWLockKeys[3] = keys.KEYRANGE_VSS_BASE; - RWLockKeys[4] = keys.KEYRANGE_CL_BASE; - - for (i = 0; i < MasterSegmentTable::nTables; i++) - rwlock[i] = new RWLock(RWLockKeys[i]); - - for (i = 0; i < MasterSegmentTable::nTables; i++) - rwlock[i]->reset(); - - for (i = 0; i < MasterSegmentTable::nTables; i++) - delete rwlock[i]; - - try { - sm.reset(); - } - catch (exception &e) { - cout << e.what() << endl; - return -1; - } - - return 0; -} - diff --git a/tools/cfread/Makefile.am b/tools/cfread/Makefile.am deleted file mode 100644 index 5419c427..00000000 --- a/tools/cfread/Makefile.am +++ /dev/null @@ -1,25 +0,0 @@ -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = cfread mtread -cfread_SOURCES = cfread.cpp -cfread_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -cfread_LDFLAGS = @idb_common_ldflags@ -lpthread -lwriteengine -lbrm -lrwlock -lmessageqcpp -ldl -lconfigcpp -lxml2 -lloggingcpp -lcacheutils -lboost_idb -lpthread -lrt $(AM_LDFLAGS) -mtread_SOURCES = mtread.cpp -mtread_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -mtread_LDFLAGS = @idb_common_ldflags@ -lpthread -lwriteengine -lbrm -lrwlock -lmessageqcpp -ldl -lconfigcpp -lxml2 -lloggingcpp -lcacheutils -lboost_idb -lpthread -lrt $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/cfread/cfread.cpp b/tools/cfread/cfread.cpp deleted file mode 100644 index a19b19c0..00000000 --- a/tools/cfread/cfread.cpp +++ /dev/null @@ -1,176 +0,0 @@ -// - -#include -#include -#include -#include -#define NDEBUG -#include -#include "writeengine.h" - -using namespace std; - -void timespec_sub(const struct timespec &tv1, - const struct timespec &tv2, - struct timespec &diff) -{ - if (tv2.tv_nsec < tv1.tv_nsec) { - diff.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; - diff.tv_nsec = tv1.tv_nsec - tv2.tv_nsec; - } - else { - diff.tv_sec = tv2.tv_sec - tv1.tv_sec; - diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; - } -} - -// TODO: -// add getopt for CLAs -// add threads for reading a file -// add threads for reading multiple files - -// main() -// -int main(int argc, char **argv) -{ - uint64_t acc=0; - uint64_t readBlocks=0; // read size ib blocks - uint64_t readSize=0; // read size ib bytes - uint64_t readBufferSz=0; - const uint64_t blockSize=8192; - char* alignedbuff=0; - boost::scoped_array realbuff; - const unsigned pageSize = 4096; //getpagesize(); - WriteEngine::FileOp fFileOp; - BRM::OID_t oid; - char fname[256]; - struct timespec tm; - struct timespec tm2; - struct timespec tm3; - struct timespec starttm; - struct timespec endtm; - struct timespec tottm; - bool odirect=true; - int fd = 0; - char response='Y'; - - if (argc <= 1) { - cerr << "usage: testread " << endl; - return -1; - } - - oid=atoi(argv[1]); - if (oid <=0) - exit(-1); - - if (argc >=2) { - readBlocks = atoi(argv[2]); - if (readBlocks <= 0) - readBlocks = 8; - } - - if (argc >=4) { - odirect=false; - } - - readSize=readBlocks*blockSize; - readBufferSz=readSize+pageSize; - - realbuff.reset(new char[readBufferSz]); - if (realbuff.get() == 0) { - cerr << "thr_popper: Can't allocate space for a whole extent in memory" << endl; - return 0; - } - - if (fFileOp.getFileName(oid, fname) != WriteEngine::NO_ERROR) { - fname[0]=0; - throw std::runtime_error("fileOp.getFileName failed"); - } - else { - cout << "Reading oid: " << oid << " od: " << odirect << " file: " << fname << endl; - } - -#if __LP64__ - alignedbuff=(char*)((((ptrdiff_t)realbuff.get() >> 12) << 12) + pageSize); -#else - alignedbuff=(char*)(((((ptrdiff_t)realbuff.get() >> 12) << 12) & 0xffffffff) + pageSize); -#endif - idbassert(((ptrdiff_t)alignedbuff - (ptrdiff_t)realbuff.get()) < (ptrdiff_t)pageSize); - idbassert(((ptrdiff_t)alignedbuff % pageSize) == 0); - - if (odirect) - fd=open(fname, O_RDONLY|O_DIRECT|O_LARGEFILE|O_NOATIME); - else - fd=open(fname, O_RDONLY|O_LARGEFILE|O_NOATIME); - - if (fd<0) { - cerr << "Open failed" << endl; - perror("open"); - throw runtime_error("Error opening file"); - } - - while (toupper(response) != 'N') { - uint64_t i=1; - uint64_t rCnt=0; - clock_gettime(CLOCK_REALTIME, &starttm); - while (i!=0) { - //clock_gettime(CLOCK_REALTIME, &tm); - i = pread(fd, alignedbuff, readSize, acc); - //clock_gettime(CLOCK_REALTIME, &tm2); - idbassert(i==0||i==readSize); - idbassert(i%pageSize==0); - idbassert(acc%pageSize==0); - if (i < 0 && errno == EINTR) { - timespec_sub(tm, tm2, tm3); - cout << "* " - << i << " " - << right << setw(2) << setfill(' ') << tm3.tv_sec << "." - << right << setw(9) << setfill('0') << tm3.tv_nsec - << endl; - continue; - } - else if (i < 0) { - timespec_sub(tm, tm2, tm3); - cout << "* i: " - << i << " sz: " << readSize << " acc: " << acc - << right << setw(2) << setfill(' ') << tm3.tv_sec << " " - << right << tm3.tv_nsec - << endl; - perror("pread"); - //make loop exit - i=0; - } - - acc += i; - if (i>0) - rCnt++; - - //timespec_sub(tm, tm2, tm3); - //cout - // << i << " " - // << right << setw(2) << setfill(' ') << tm3.tv_sec << " " - // << right << tm3.tv_nsec - // << endl; - - } // while(acc... - - clock_gettime(CLOCK_REALTIME, &endtm); - timespec_sub(starttm, endtm, tottm); - - cout << "Total reads: " << rCnt - << " sz: " << acc/(1024*1024) << "MB" - << " tm: " << tottm.tv_sec << "secs " - << tottm.tv_nsec << "ns" - << endl; - - cout << "Repeat the last scan[Y,N]?" << endl; - cin >> response; - acc=0; - - } // while response... - - close(fd); - return 0; - -} //main - diff --git a/tools/cfread/mtread.cpp b/tools/cfread/mtread.cpp deleted file mode 100644 index 9fbc2827..00000000 --- a/tools/cfread/mtread.cpp +++ /dev/null @@ -1,269 +0,0 @@ -// - -#include -#include -#include -#include -#include -#define NDEBUG -#include -#include "writeengine.h" - -using namespace std; - -void timespec_sub(const struct timespec &tv1, - const struct timespec &tv2, - struct timespec &diff) -{ - if (tv2.tv_nsec < tv1.tv_nsec) { - diff.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; - diff.tv_nsec = tv1.tv_nsec - tv2.tv_nsec; - } - else { - diff.tv_sec = tv2.tv_sec - tv1.tv_sec; - diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; - } -} - -// TODO: -// add threads for reading a file -// add threads for reading multiple files - -struct readThr -{ - public: - readThr(const int oid, const int rSize) - { - fblockSize=8192; - fpageSize=getpagesize(); - freadBlocks=rSize; - freadSize=rSize*fblockSize; // read size ib bytes - freadBufferSz=freadSize+fpageSize; - falignedbuff=0; - foid=oid; - facc=0; - memset(fname,0, sizeof(fname)); - memset((char*)&ftm, 0, sizeof(ftm)); - memset((char*)&ftm2, 0, sizeof(ftm2)); - memset((char*)&ftm3, 0, sizeof(ftm3)); - memset((char*)&fstarttm, 0, sizeof(fstarttm)); - memset((char*)&fendtm, 0, sizeof(fendtm)); - memset((char*)&ftottm, 0, sizeof(ftottm)); - fodirect=true; - fd = 0; - cout << "o: " << foid << " r: " << freadBlocks << " b: " << freadBufferSz << endl; - } - - void operator() () - { - - WriteEngine::FileOp fFileOp; - char frealbuff[freadBufferSz]; - memset(frealbuff, 0, freadBufferSz); - if (frealbuff==0) { - cerr << "thr_popper: Can't allocate space for a whole extent in memory" << endl; - return; - } - - if (fFileOp.getFileName(foid, fname) != WriteEngine::NO_ERROR) { - fname[0]=0; - throw std::runtime_error("fileOp.getFileName failed"); - } - else { - cout << "Reading oid: " << foid << " od: " << fodirect << " file: " << fname << endl; - } - -#if __LP64__ - falignedbuff=(char*)((((ptrdiff_t)frealbuff >> 12) << 12) + fpageSize); -#else - falignedbuff=(char*)(((((ptrdiff_t)frealbuff >> 12) << 12) & 0xffffffff) + fpageSize); -#endif - idbassert(((ptrdiff_t)falignedbuff - (ptrdiff_t)frealbuff) < (ptrdiff_t)fpageSize); - idbassert(((ptrdiff_t)falignedbuff % fpageSize) == 0); - - if (fodirect) - fd=open(fname, O_RDONLY|O_DIRECT|O_LARGEFILE|O_NOATIME); - else - fd=open(fname, O_RDONLY|O_LARGEFILE|O_NOATIME); - - if (fd<0) { - cerr << "Open failed" << endl; - perror("open"); - throw runtime_error("Error opening file"); - } - - uint64_t i=1; - uint64_t rCnt=0; - - clock_gettime(CLOCK_REALTIME, &fstarttm); - while (i>0) { - clock_gettime(CLOCK_REALTIME, &ftm); - i = pread(fd, falignedbuff, freadSize, facc); - clock_gettime(CLOCK_REALTIME, &ftm2); - - idbassert(i==0||i==freadSize); - idbassert(i%fpageSize==0); - idbassert(facc%fpageSize==0); - - if (i < 0 && errno == EINTR) - { - timespec_sub(ftm, ftm2, ftm3); - cout << "* " - << i << " " - << right << setw(2) << setfill(' ') << ftm3.tv_sec << "." - << right << setw(9) << setfill('0') << ftm3.tv_nsec - << endl; - continue; - } - else if (i < 0) - { - timespec_sub(ftm, ftm2, ftm3); - cout << "* i: " - << i << " sz: " << freadSize << " acc: " << facc - << right << setw(2) << setfill(' ') << ftm3.tv_sec << " " - << right << ftm3.tv_nsec - << endl; - perror("pread"); - } - - facc += i; - if (i>0) - rCnt++; - /** - timespec_sub(ftm, ftm2, ftm3); - cout - << rCnt << " " << facc/(1024*1024) - << right << setw(2) << setfill(' ') << ftm3.tv_sec << "." - << right << ftm3.tv_nsec << " i: " << i/(1024*1024) - << endl; - **/ - - } // while(acc... - - clock_gettime(CLOCK_REALTIME, &fendtm); - timespec_sub(fstarttm, fendtm, ftottm); - - cout << "Total reads: " << rCnt - << " sz: " << facc/(1024*1024) << "MB" - << " tm: " << ftottm.tv_sec << "secs " - << ftottm.tv_nsec << "ns" - << endl; - - facc=0; - close(fd); - } // operator() - - public: - uint64_t facc; - uint64_t freadBlocks; // read size ib blocks - uint64_t freadSize; // read size ib bytes - uint64_t freadBufferSz; - uint64_t fblockSize; - char* falignedbuff; - unsigned fpageSize ; - BRM::OID_t foid; - char fname[256]; - struct timespec ftm; - struct timespec ftm2; - struct timespec ftm3; - struct timespec fstarttm; - struct timespec fendtm; - struct timespec ftottm; - bool fodirect; - int fd; - -}; // struct readThr - -// -void usage() -{ - cerr << "usage: mtread -o -s " << endl; -} - -// main() -// -int main(int argc, char **argv) -{ - int ch=0; - int readBlocks=0; - BRM::OID_t oid=0; - std::vector oidList; - - enum CLA_ENUM { - OID=(int)0, - READSIZE - }; - - //longopt struct - //struct option { - //const char *name; - //int has_arg; - //int *flag; - //int val; - //}; - - static struct - option long_options[] = - { - //{const char *name, int has_arg, int *flag, int val}, - {"oid", required_argument, NULL, OID}, - {"rsize", required_argument, NULL, READSIZE}, - {0, 0, 0, 0} - }; - - if (argc <= 1) { - return -1; - } - - // process command line arguments - while( (ch = getopt_long_only(argc, argv, "o:s:", long_options, NULL)) != -1 ) - { - //pid_t pidId = getpid(); - switch (ch) { - - case OID: - case 'o': - oid=atoi(optarg); - oidList.push_back(oid); - cout << "oid: " << optarg << endl; - break; - - case READSIZE: - case 's': - readBlocks = atoi(optarg); - cout << "read size: " << optarg << endl; - if (readBlocks <= 0) - readBlocks = 1; - break; - - case '?': - default: - cout << "optarg " << optarg << endl; - usage(); - break; - - } // switch - - } // while... - - - uint32_t idx=0; - std::vector thrList; - - while(idx < oidList.size()) { - struct readThr rdr(oidList[idx++], readBlocks); - boost::thread* thr = new boost::thread(rdr); - thrList.push_back(thr); - } - - idx=0; - while(idxjoin(); - delete thr; - } - - thrList.clear(); - -} //main - diff --git a/tools/clearShm/Makefile.am b/tools/clearShm/Makefile.am index 599bf306..234aa0cb 100644 --- a/tools/clearShm/Makefile.am +++ b/tools/clearShm/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/clearShm/Makefile.in b/tools/clearShm/Makefile.in index c927f473..1a483edd 100644 --- a/tools/clearShm/Makefile.in +++ b/tools/clearShm/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = clearShm$(EXEEXT) subdir = tools/clearShm DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/clearShm/clearShm.vcxproj b/tools/clearShm/clearShm.vcxproj deleted file mode 100644 index c1c0a3d5..00000000 --- a/tools/clearShm/clearShm.vcxproj +++ /dev/null @@ -1,256 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {E369D45E-2933-4E72-AA1D-CA2A8E59BA5F} - clearShm - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - COMMUNITY_KEYRANGE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - %(AdditionalDependencies) - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - %(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - %(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - $(SolutionDir)..\..\boost_1_54_0;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - %(AdditionalDependencies) - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - %(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\utils\winport;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - false - - - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - %(AdditionalDependencies) - - - - - - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - - - - \ No newline at end of file diff --git a/tools/clearShm/clearShm.vcxproj.filters b/tools/clearShm/clearShm.vcxproj.filters deleted file mode 100644 index a5aaa3f2..00000000 --- a/tools/clearShm/clearShm.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/tools/clearShm/main.cpp b/tools/clearShm/main.cpp index fd64818e..8a0e6da1 100644 --- a/tools/clearShm/main.cpp +++ b/tools/clearShm/main.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: main.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +// $Id: main.cpp 2020 2012-11-09 21:18:22Z rdempsey $ #include "config.h" diff --git a/tools/cleartablelock/Makefile.am b/tools/cleartablelock/Makefile.am index 74ccd9b2..ea50d090 100644 --- a/tools/cleartablelock/Makefile.am +++ b/tools/cleartablelock/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -24,8 +24,8 @@ AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) bin_PROGRAMS = cleartablelock cleartablelock_SOURCES = cleartablelock.cpp cleartablelockthread.cpp -cleartablelock_CPPFLAGS = ${idb_common_includes} $(AM_CPPFLAGS) -cleartablelock_LDFLAGS = ${idb_common_ldflags} ${idb_write_libs} $(AM_LDFLAGS) +cleartablelock_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +cleartablelock_LDFLAGS = @idb_common_ldflags@ @idb_exec_libs@ -lwriteengine -lcacheutils $(AM_LDFLAGS) test: diff --git a/tools/cleartablelock/Makefile.in b/tools/cleartablelock/Makefile.in index 64c1366a..34053f56 100644 --- a/tools/cleartablelock/Makefile.in +++ b/tools/cleartablelock/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = cleartablelock$(EXEEXT) subdir = tools/cleartablelock DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -149,9 +148,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -193,7 +189,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -207,11 +202,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -227,8 +217,8 @@ AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) cleartablelock_SOURCES = cleartablelock.cpp cleartablelockthread.cpp -cleartablelock_CPPFLAGS = ${idb_common_includes} $(AM_CPPFLAGS) -cleartablelock_LDFLAGS = ${idb_common_ldflags} ${idb_write_libs} $(AM_LDFLAGS) +cleartablelock_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +cleartablelock_LDFLAGS = @idb_common_ldflags@ @idb_exec_libs@ -lwriteengine -lcacheutils $(AM_LDFLAGS) all: all-am .SUFFIXES: diff --git a/tools/cleartablelock/cleartablelock.cpp b/tools/cleartablelock/cleartablelock.cpp index ea38f0df..6bb1078d 100644 --- a/tools/cleartablelock/cleartablelock.cpp +++ b/tools/cleartablelock/cleartablelock.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: cleartablelock.cpp 2336 2013-06-25 19:11:36Z rdempsey $ +* $Id: cleartablelock.cpp 1872 2012-08-01 16:58:23Z dhall $ */ #include @@ -51,7 +51,8 @@ namespace { void usage() { std::cout << "Usage: cleartablelock lockID" << std::endl - << " -h to display this menu" << std::endl; + << " -h to display this menu" << std::endl + << " -d to enable debug" << std::endl; } //------------------------------------------------------------------------------ @@ -214,18 +215,18 @@ int createMsgQueClts( { errMsg.clear(); - std::string srvName; + std::ostringstream weServerName; try { // Send bulk rollback request to each specified PM. for (unsigned k=0; k(cl) ); } @@ -234,14 +235,14 @@ int createMsgQueClts( { std::ostringstream ossStatus; ossStatus << "Error creating connection to " << - srvName << ": " << ex.what(); + weServerName.str() << ex.what(); errMsg = ossStatus.str(); return 3; } catch (...) { std::ostringstream ossStatus; - ossStatus << "Error creating connection to " << srvName; + ossStatus << "Error creating connection to " << weServerName.str(); errMsg = ossStatus.str(); return 3; } @@ -348,7 +349,7 @@ int execBulkRollbackReq( { // Take over ownership of stale lock. std::string processName("clearTableLock"); - uint32_t processID = ::getpid(); + u_int32_t processID = ::getpid(); int32_t sessionID = -1; int32_t transID = -1; bool ownerChanged = brm->changeOwner( @@ -432,12 +433,16 @@ int main(int argc, char** argv) int c; bool clearLockOnly = false; bool rollbackOnly = false; + bool debugFlag = false; uint32_t tableOID = 0; - while ((c = getopt(argc, argv, "hlr:")) != EOF) + while ((c = getopt(argc, argv, "dhlr:")) != EOF) { switch (c) { + case 'd': + debugFlag = true; + break; case 'l': clearLockOnly = true; break; diff --git a/tools/cleartablelock/cleartablelock.vcxproj b/tools/cleartablelock/cleartablelock.vcxproj deleted file mode 100644 index bb876414..00000000 --- a/tools/cleartablelock/cleartablelock.vcxproj +++ /dev/null @@ -1,316 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {F1BFEF1B-41F8-437C-AA09-1F22D2F9ED13} - cleartablelock - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\server;$(SolutionDir)..\utils\compress;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - - - - \ No newline at end of file diff --git a/tools/cleartablelock/cleartablelock.vcxproj.filters b/tools/cleartablelock/cleartablelock.vcxproj.filters deleted file mode 100644 index 8d49470e..00000000 --- a/tools/cleartablelock/cleartablelock.vcxproj.filters +++ /dev/null @@ -1,30 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - - - Header Files - - - \ No newline at end of file diff --git a/tools/cleartablelock/cleartablelockthread.cpp b/tools/cleartablelock/cleartablelockthread.cpp index efa2bcd2..2293c346 100644 --- a/tools/cleartablelock/cleartablelockthread.cpp +++ b/tools/cleartablelock/cleartablelockthread.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** - * $Id: cleartablelockthread.cpp 2101 2013-01-21 14:12:52Z rdempsey $ + * $Id: cleartablelockthread.cpp 1739 2012-03-22 12:57:59Z pleblanc $ * ****************************************************************************/ #include "cleartablelockthread.h" diff --git a/tools/cleartablelock/cleartablelockthread.h b/tools/cleartablelock/cleartablelockthread.h index 80de00df..691c8bec 100644 --- a/tools/cleartablelock/cleartablelockthread.h +++ b/tools/cleartablelock/cleartablelockthread.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /******************************************************************************* -* $Id: cleartablelockthread.h 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: cleartablelockthread.h 1739 2012-03-22 12:57:59Z pleblanc $ * *******************************************************************************/ #ifndef ClearTableLockThread_H__ diff --git a/tools/configMgt/CalpontSystems.xml b/tools/configMgt/CalpontSystems.xml deleted file mode 100644 index bb3f304e..00000000 --- a/tools/configMgt/CalpontSystems.xml +++ /dev/null @@ -1,137 +0,0 @@ - - - - - 26 - qcald02 - qalpont! - qaftest6 - *.x86_64.rpm - root - qcald02a - qalpont! - qaftest3 - *.x86_64.rpm - root - qperfd01 - qalpont! - srvqaperf2 - *.x86_64.rpm - root - devint2 - Calpont1 - srvperf4 - *.x86_64.rpm - root - demo01 - Calpont1 - srvdemo2 - *.x86_64.rpm - root - devint1 - Calpont1 - srvperf7 - *.x86_64.rpm - root - devint3 - Calpont1 - srvperf3 - *.x86_64.rpm - root - qcald02b - Calpont1 - qaftest2 - *.x86_64.rpm - root - caldev01 - qalpont! - srvswdev10 - *.x86_64.rpm - root - caldev02 - Calpont1 - srvswdev11 - *.x86_64.rpm - root - srvitfep1 - Calpont1 - srvitfep1 - *.x86_64.rpm - root - daniel - qalpont! - srvdaniel - *.i686.rpm - root - qaftest2 - Calpont1 - qaftest2 - *.x86_64.rpm - root - srvswdev11 - Calpont1 - srvswdev11 - *.x86_64.rpm - root - ss1 - qalpont! - srvqaperf8 - *.x86_64.rpm - root - ss2 - qalpont! - srvalpha2 - *.x86_64.rpm - root - srvprodtest1 - qalpont! - srvprodtest1 - *.x86_64.rpm - root - qaftest4 - qalpont! - qaftest4 - *.x86_64.rpm - root - srvqawin1 - Calpont1 - srvqawin1 - *.x86_64.rpm - root - devsn1 - Calpont1 - srvdevsn2 - *.x86_64.rpm - root - devsn2 - Calpont1 - srvdevsn6 - *.x86_64.rpm - root - devsn3 - Calpont1 - srvdevsn8 - *.x86_64.rpm - root - demo02 - Calpont1 - srvdemo3 - *.x86_64.rpm - root - srvprodtest2 - qalpont! - srvprodtest2 - *.x86_64.rpm - root - alphad03 - Calpont1 - srvalpha3 - *x86_64.bin.tar.gz - infinidb - devsn4 - Calpont1 - srvdevsn11 - *.x86_64.rpm - root - - diff --git a/tools/configMgt/Makefile.am b/tools/configMgt/Makefile.am deleted file mode 100644 index 1746d374..00000000 --- a/tools/configMgt/Makefile.am +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 1929 2012-09-14 16:18:25Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = autoInstaller autoConfigure svnQuery - -autoInstaller_SOURCES = autoInstaller.cpp -autoInstaller_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -autoInstaller_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) - -autoConfigure_SOURCES = autoConfigure.cpp -autoConfigure_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -autoConfigure_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) - -svnQuery_SOURCES = svnQuery.cpp -svnQuery_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -svnQuery_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/configMgt/Makefile.in b/tools/configMgt/Makefile.in deleted file mode 100644 index a75fb494..00000000 --- a/tools/configMgt/Makefile.in +++ /dev/null @@ -1,580 +0,0 @@ -# Makefile.in generated by automake 1.9.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005 Free Software Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 1929 2012-09-14 16:18:25Z rdempsey $ - -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ -VPATH = @srcdir@ -pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -bin_PROGRAMS = autoInstaller$(EXEEXT) autoConfigure$(EXEEXT) \ - svnQuery$(EXEEXT) -subdir = tools/configMgt -DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = $(top_builddir)/config.h -CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(bindir)" -binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) -PROGRAMS = $(bin_PROGRAMS) -am_autoConfigure_OBJECTS = autoConfigure-autoConfigure.$(OBJEXT) -autoConfigure_OBJECTS = $(am_autoConfigure_OBJECTS) -autoConfigure_LDADD = $(LDADD) -am_autoInstaller_OBJECTS = autoInstaller-autoInstaller.$(OBJEXT) -autoInstaller_OBJECTS = $(am_autoInstaller_OBJECTS) -autoInstaller_LDADD = $(LDADD) -am_svnQuery_OBJECTS = svnQuery-svnQuery.$(OBJEXT) -svnQuery_OBJECTS = $(am_svnQuery_OBJECTS) -svnQuery_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) -depcomp = $(SHELL) $(top_srcdir)/depcomp -am__depfiles_maybe = depfiles -CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -LTCXXCOMPILE = $(LIBTOOL) --tag=CXX --mode=compile $(CXX) $(DEFS) \ - $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ - $(AM_CXXFLAGS) $(CXXFLAGS) -CXXLD = $(CXX) -CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ - $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ -SOURCES = $(autoConfigure_SOURCES) $(autoInstaller_SOURCES) \ - $(svnQuery_SOURCES) -DIST_SOURCES = $(autoConfigure_SOURCES) $(autoInstaller_SOURCES) \ - $(svnQuery_SOURCES) -ETAGS = etags -CTAGS = ctags -DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) -ACLOCAL = @ACLOCAL@ -ALLOCA = @ALLOCA@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -CC = @CC@ -CCDEPMODE = @CCDEPMODE@ -CFLAGS = @CFLAGS@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CXX = @CXX@ -CXXCPP = @CXXCPP@ -CXXDEPMODE = @CXXDEPMODE@ -CXXFLAGS = @CXXFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DEPDIR = @DEPDIR@ -ECHO = @ECHO@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -F77 = @F77@ -FFLAGS = @FFLAGS@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LDFLAGS = @LDFLAGS@ -LEX = @LEX@ -LEXLIB = @LEXLIB@ -LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAKEINFO = @MAKEINFO@ -OBJEXT = @OBJEXT@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -POW_LIB = @POW_LIB@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ -YACC = @YACC@ -ac_ct_AR = @ac_ct_AR@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_CXX = @ac_ct_CXX@ -ac_ct_F77 = @ac_ct_F77@ -ac_ct_RANLIB = @ac_ct_RANLIB@ -ac_ct_STRIP = @ac_ct_STRIP@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ -am__include = @am__include@ -am__leading_dot = @am__leading_dot@ -am__quote = @am__quote@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -datadir = @datadir@ -etcdir = @etcdir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -idb_brm_libs = @idb_brm_libs@ -idb_cflags = @idb_cflags@ -idb_common_includes = @idb_common_includes@ -idb_common_ldflags = @idb_common_ldflags@ -idb_common_libs = @idb_common_libs@ -idb_cppflags = @idb_cppflags@ -idb_cxxflags = @idb_cxxflags@ -idb_exec_libs = @idb_exec_libs@ -idb_ldflags = @idb_ldflags@ -idb_oam_libs = @idb_oam_libs@ -idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -localdir = @localdir@ -localstatedir = @localstatedir@ -mandir = @mandir@ -march_flags = @march_flags@ -mibdir = @mibdir@ -mkdir_p = @mkdir_p@ -mysqldir = @mysqldir@ -netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ -oldincludedir = @oldincludedir@ -postdir = @postdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -sbindir = @sbindir@ -sharedir = @sharedir@ -sharedstatedir = @sharedstatedir@ -sysconfdir = @sysconfdir@ -target_alias = @target_alias@ -toolsdir = @toolsdir@ -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -autoInstaller_SOURCES = autoInstaller.cpp -autoInstaller_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -autoInstaller_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) -lreadline -lncurses $(AM_LDFLAGS) -autoConfigure_SOURCES = autoConfigure.cpp -autoConfigure_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -autoConfigure_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -svnQuery_SOURCES = svnQuery.cpp -svnQuery_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -svnQuery_LDFLAGS = $(idb_common_ldflags) $(idb_brm_libs) $(idb_oam_libs) $(idb_exec_libs) $(AM_LDFLAGS) -all: all-am - -.SUFFIXES: -.SUFFIXES: .cpp .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu tools/configMgt/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu tools/configMgt/Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh - -$(top_srcdir)/configure: $(am__configure_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -install-binPROGRAMS: $(bin_PROGRAMS) - @$(NORMAL_INSTALL) - test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - || test -f $$p1 \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ - else :; fi; \ - done - -uninstall-binPROGRAMS: - @$(NORMAL_UNINSTALL) - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ - rm -f "$(DESTDIR)$(bindir)/$$f"; \ - done - -clean-binPROGRAMS: - @list='$(bin_PROGRAMS)'; for p in $$list; do \ - f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f $$p $$f"; \ - rm -f $$p $$f ; \ - done -autoConfigure$(EXEEXT): $(autoConfigure_OBJECTS) $(autoConfigure_DEPENDENCIES) - @rm -f autoConfigure$(EXEEXT) - $(CXXLINK) $(autoConfigure_LDFLAGS) $(autoConfigure_OBJECTS) $(autoConfigure_LDADD) $(LIBS) -autoInstaller$(EXEEXT): $(autoInstaller_OBJECTS) $(autoInstaller_DEPENDENCIES) - @rm -f autoInstaller$(EXEEXT) - $(CXXLINK) $(autoInstaller_LDFLAGS) $(autoInstaller_OBJECTS) $(autoInstaller_LDADD) $(LIBS) -svnQuery$(EXEEXT): $(svnQuery_OBJECTS) $(svnQuery_DEPENDENCIES) - @rm -f svnQuery$(EXEEXT) - $(CXXLINK) $(svnQuery_LDFLAGS) $(svnQuery_OBJECTS) $(svnQuery_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/autoConfigure-autoConfigure.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/autoInstaller-autoInstaller.Po@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/svnQuery-svnQuery.Po@am__quote@ - -.cpp.o: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< - -.cpp.obj: -@am__fastdepCXX_TRUE@ if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` - -.cpp.lo: -@am__fastdepCXX_TRUE@ if $(LTCXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< - -autoConfigure-autoConfigure.o: autoConfigure.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT autoConfigure-autoConfigure.o -MD -MP -MF "$(DEPDIR)/autoConfigure-autoConfigure.Tpo" -c -o autoConfigure-autoConfigure.o `test -f 'autoConfigure.cpp' || echo '$(srcdir)/'`autoConfigure.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/autoConfigure-autoConfigure.Tpo" "$(DEPDIR)/autoConfigure-autoConfigure.Po"; else rm -f "$(DEPDIR)/autoConfigure-autoConfigure.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='autoConfigure.cpp' object='autoConfigure-autoConfigure.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o autoConfigure-autoConfigure.o `test -f 'autoConfigure.cpp' || echo '$(srcdir)/'`autoConfigure.cpp - -autoConfigure-autoConfigure.obj: autoConfigure.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT autoConfigure-autoConfigure.obj -MD -MP -MF "$(DEPDIR)/autoConfigure-autoConfigure.Tpo" -c -o autoConfigure-autoConfigure.obj `if test -f 'autoConfigure.cpp'; then $(CYGPATH_W) 'autoConfigure.cpp'; else $(CYGPATH_W) '$(srcdir)/autoConfigure.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/autoConfigure-autoConfigure.Tpo" "$(DEPDIR)/autoConfigure-autoConfigure.Po"; else rm -f "$(DEPDIR)/autoConfigure-autoConfigure.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='autoConfigure.cpp' object='autoConfigure-autoConfigure.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoConfigure_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o autoConfigure-autoConfigure.obj `if test -f 'autoConfigure.cpp'; then $(CYGPATH_W) 'autoConfigure.cpp'; else $(CYGPATH_W) '$(srcdir)/autoConfigure.cpp'; fi` - -autoInstaller-autoInstaller.o: autoInstaller.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT autoInstaller-autoInstaller.o -MD -MP -MF "$(DEPDIR)/autoInstaller-autoInstaller.Tpo" -c -o autoInstaller-autoInstaller.o `test -f 'autoInstaller.cpp' || echo '$(srcdir)/'`autoInstaller.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/autoInstaller-autoInstaller.Tpo" "$(DEPDIR)/autoInstaller-autoInstaller.Po"; else rm -f "$(DEPDIR)/autoInstaller-autoInstaller.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='autoInstaller.cpp' object='autoInstaller-autoInstaller.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o autoInstaller-autoInstaller.o `test -f 'autoInstaller.cpp' || echo '$(srcdir)/'`autoInstaller.cpp - -autoInstaller-autoInstaller.obj: autoInstaller.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT autoInstaller-autoInstaller.obj -MD -MP -MF "$(DEPDIR)/autoInstaller-autoInstaller.Tpo" -c -o autoInstaller-autoInstaller.obj `if test -f 'autoInstaller.cpp'; then $(CYGPATH_W) 'autoInstaller.cpp'; else $(CYGPATH_W) '$(srcdir)/autoInstaller.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/autoInstaller-autoInstaller.Tpo" "$(DEPDIR)/autoInstaller-autoInstaller.Po"; else rm -f "$(DEPDIR)/autoInstaller-autoInstaller.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='autoInstaller.cpp' object='autoInstaller-autoInstaller.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(autoInstaller_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o autoInstaller-autoInstaller.obj `if test -f 'autoInstaller.cpp'; then $(CYGPATH_W) 'autoInstaller.cpp'; else $(CYGPATH_W) '$(srcdir)/autoInstaller.cpp'; fi` - -svnQuery-svnQuery.o: svnQuery.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(svnQuery_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT svnQuery-svnQuery.o -MD -MP -MF "$(DEPDIR)/svnQuery-svnQuery.Tpo" -c -o svnQuery-svnQuery.o `test -f 'svnQuery.cpp' || echo '$(srcdir)/'`svnQuery.cpp; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/svnQuery-svnQuery.Tpo" "$(DEPDIR)/svnQuery-svnQuery.Po"; else rm -f "$(DEPDIR)/svnQuery-svnQuery.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='svnQuery.cpp' object='svnQuery-svnQuery.o' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(svnQuery_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o svnQuery-svnQuery.o `test -f 'svnQuery.cpp' || echo '$(srcdir)/'`svnQuery.cpp - -svnQuery-svnQuery.obj: svnQuery.cpp -@am__fastdepCXX_TRUE@ if $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(svnQuery_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT svnQuery-svnQuery.obj -MD -MP -MF "$(DEPDIR)/svnQuery-svnQuery.Tpo" -c -o svnQuery-svnQuery.obj `if test -f 'svnQuery.cpp'; then $(CYGPATH_W) 'svnQuery.cpp'; else $(CYGPATH_W) '$(srcdir)/svnQuery.cpp'; fi`; \ -@am__fastdepCXX_TRUE@ then mv -f "$(DEPDIR)/svnQuery-svnQuery.Tpo" "$(DEPDIR)/svnQuery-svnQuery.Po"; else rm -f "$(DEPDIR)/svnQuery-svnQuery.Tpo"; exit 1; fi -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='svnQuery.cpp' object='svnQuery-svnQuery.obj' libtool=no @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(svnQuery_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o svnQuery-svnQuery.obj `if test -f 'svnQuery.cpp'; then $(CYGPATH_W) 'svnQuery.cpp'; else $(CYGPATH_W) '$(srcdir)/svnQuery.cpp'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ - if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ - if test -d $$d/$$file; then \ - if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ - fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ - else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ - || exit 1; \ - fi; \ - done -check-am: all-am -check: check-am -all-am: Makefile $(PROGRAMS) -installdirs: - for dir in "$(DESTDIR)$(bindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install -mostlyclean-generic: - -clean-generic: - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am - -clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am - -distclean: distclean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -info: info-am - -info-am: - -install-data-am: - -install-exec-am: install-binPROGRAMS - -install-info: install-info-am - -install-man: - -installcheck-am: - -maintainer-clean: maintainer-clean-am - -rm -rf ./$(DEPDIR) - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-binPROGRAMS uninstall-info-am - -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ - clean-generic clean-libtool ctags distclean distclean-compile \ - distclean-generic distclean-libtool distclean-tags distdir dvi \ - dvi-am html html-am info info-am install install-am \ - install-binPROGRAMS install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - maintainer-clean maintainer-clean-generic mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - pdf pdf-am ps ps-am tags uninstall uninstall-am \ - uninstall-binPROGRAMS uninstall-info-am - - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/tools/configMgt/README b/tools/configMgt/README deleted file mode 100644 index 1d908119..00000000 --- a/tools/configMgt/README +++ /dev/null @@ -1,43 +0,0 @@ - -This directory contains the Calpont Config Manager Build, Configure, and Install -scripts. - -User Command scripts: - -autoBuilder - Generate a RHEL5 or FC6 build based on latest genii code. - Execute './autoBuilder -h' for addition help. - -autoInstaller - Installs a Calpont system with a Calpont RPM. It can - install the latest build version or a specific released - versions. - Execute './autoInstaller -h' for addition help. - -autoReleaseNotes.sh - Generates bug reports for release notes - Execute './autoReleaseNotes.sh -h' for addition help. - -buildTester.sh - Installs a Calpont system with a New Latest Built or - Previously release Calpont RPM. If Latest Build is specified, - it will generate a new build based on the latest genii code. - If the build and install is successfully, it will perform a - set of Database Test. A report will be emailed. - Execute './buildTester -h' for addition help. - -configure - Interactively reads and Configures a local version of the - Calpont.xml file based on user inputs. - Usage ./configure - -Supported Command Scipts. These scripts are called by the User Command scripts: - -autoConfigure, parent_installer.sh, remote_command.sh, and remote_scp_get.sh - -Directories: - -systems - Contains directories of the systems with associated Calpont.xml - files for that system. - Also contains the CalpontSystem.xml file, which contains the - support systems that can be installed using the autoInstaller - command. - -RHEL5, FC6 - Would contain the build log files for a build failure using the - autoBuilder tool. - diff --git a/tools/configMgt/autoBuilder b/tools/configMgt/autoBuilder deleted file mode 100755 index 3e4d558e..00000000 --- a/tools/configMgt/autoBuilder +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/expect -# -# $Id: autoBuild.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - OS type: RHEL5 , RHEL5-1 or FC6 (default to RHEL5) -# Argument 2 - release (optional) -# Argument 3 - SVN branch or trunk -set USERNAME root -set PASSWORD Calpont1 -set OS RHEL5 -set RELEASE Latest -set SVN genii -set VERSION EE -log_user 0 - -spawn -noecho /bin/bash - -for {set i 0} {$i<[llength $argv]} {incr i} { - set arg($i) [lindex $argv $i] -} - -set i 0 -while true { - if { $i == [llength $argv] } { break } - if { $arg($i) == "-h" } { - send_user "\n" - send_user "'autoBuilder' generates a RHEL5 or FC6 rpm based on the Latest\n" - send_user "files checked into svn genii branch. The build takes 20 to 30 minutes.\n" - send_user "It will place the rpm in //calweb/shared/Iterations/Latest/\n" - send_user "and in //calweb/shared/Iterations/'release'/ when specified\n" - send_user "\n" - send_user "Usage: autoBuild -o 'OS' -r 'release' -s 'svn-branch'\n" - send_user " OS - RHEL5 (srvperf1 4.x build) or RHEL5-1 (srvnightly 4.x build)\n" - send_user " release - Calpont release number (defaults to Latest)\n" - send_user " svn-branch - SVN Branch name (defaults to genii)\n" - exit - } - if { $arg($i) == "-o" } { - incr i - set OS $arg($i) - } else { - if { $arg($i) == "-r" } { - incr i - set RELEASE $arg($i) - } else { - if { $arg($i) == "-s" } { - incr i - set SVN $arg($i) - } - } - } - incr i -} - -if { $OS == "RHEL5-1" } { - set SERVER srvnightly - set COMMAND "'/root/calpont-build $RELEASE $SVN'" -} else { - set SERVER srvperf1 - set COMMAND "'/root/infinidb-build $RELEASE $SVN'" -} - - -set timeout 4000 -# -# send command to build calpont rpms -# -#get current date -exec date >/tmp/datesync.tmp -exec cat /tmp/datesync.tmp -set newtime [exec cat /tmp/datesync.tmp] - -send_user "\nStart Time: $newtime\n" - -log_user 1 -send_user "\nRPM Package Build takes 60 minutes to complete, please wait...\n" -log_user 0 - -send "ssh $USERNAME@$SERVER $COMMAND\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort - -re "TIMEOUT" { send_user "Calpont RPM Build Failed, timeout\n" ; exit -1 } - timeout { send_user "Calpont RPM Build Failed, timeout\n" ; exit -1 } - -re "no rpm" { send_user "Calpont RPM Build Failed, check build log files\n" ; exit -1 } - -re "Build Successfully Completed" { log_user 1 - #get current date - exec date >/tmp/datesync.tmp - exec cat /tmp/datesync.tmp - set newtime [exec cat /tmp/datesync.tmp] - - file delete -force $RELEASE - send_user "\nCalpont RPM Build successfully completed $newtime\n"; exit 0 - } -} - -expect { - -re "TIMEOUT" { send_user "Calpont RPM Build Failed, timeout\n" ; exit -1 } - timeout { send_user "Calpont RPM Build Failed, timeout\n" ; exit -1 } - -re "no rpm" { send_user "Calpont RPM Build Failed, check build log files\n" ; exit -1 } - -re "Build Successfully Completed" { } abort -} - -log_user 1 - -#get current date -exec date >/tmp/datesync.tmp -exec cat /tmp/datesync.tmp -set newtime [exec cat /tmp/datesync.tmp] - -file delete -force $RELEASE -send_user "\nCalpont RPM Build successfully completed $newtime\n" -exit 0 diff --git a/tools/configMgt/autoConfigure.cpp b/tools/configMgt/autoConfigure.cpp deleted file mode 100644 index 46c03369..00000000 --- a/tools/configMgt/autoConfigure.cpp +++ /dev/null @@ -1,1811 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/****************************************************************************************** -* $Id: configure.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* List of files being updated by configure: -* Calpont/etc/Calpont.xml -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "stdio.h" -#include "ctype.h" -#include - -#include "liboamcpp.h" -#include "configcpp.h" - -using namespace std; -using namespace oam; -using namespace config; - -typedef struct Performance_Module_struct -{ - std::string moduleIP1; - std::string moduleIP2; - std::string moduleIP3; - std::string moduleIP4; -} PerformanceModule; - -typedef std::vector PerformanceModuleList; - -int main(int argc, char *argv[]) -{ - setenv("CALPONT_HOME", "./", 1); - - Oam oam; - string systemParentOAMModuleName; - string parentOAMModuleIPAddr; - PerformanceModuleList performancemodulelist; - int pmNumber = 0; - string prompt; - int DBRMworkernodeID = 0; - string remote_installer_debug = "0"; - Config* sysConfigOld; - Config* sysConfigNew; - string systemName; - bool extextMapCheckOnly = false; - - if (argc > 1) { - string arg1 = argv[1]; - if ( arg1 == "-e" ) - extextMapCheckOnly = true; - else - systemName = arg1; - } - else - systemName = oam::UnassignedName; - - try { - sysConfigOld = Config::makeConfig("./Calpont.xml"); // system version - sysConfigNew = Config::makeConfig("./Calpont.xml.new"); // released version - } - catch(...) - { - cout << "ERROR: Problem reading Calpont.xml files"; - exit(-1); - } - - string SystemSection = "SystemConfig"; - string InstallSection = "Installation"; - - //set install config flag - try { - sysConfigNew->setConfig(InstallSection, "InitialInstallFlag", "y"); - } - catch(...) - { - cout << "ERROR: Problem setting InitialInstallFlag from the Calpont System Configuration file" << endl; - exit(-1); - } - - //read cloud parameter to see if OLD is a 3.0+ or pre-3.0 build being installed - string cloud; - try { - cloud = sysConfigOld->getConfig(InstallSection, "Cloud"); - } - catch(...) - {} - - // build3 is for 3 and above 4 - bool OLDbuild3 = false; - if ( !cloud.empty() ) - OLDbuild3 = true; - - //read cloud parameter to see if NEW is a 3.0+ or pre-3.0 build being installed - try { - cloud = sysConfigNew->getConfig(InstallSection, "Cloud"); - } - catch(...) - {} - - // build3 is for 3 and above 4 - bool build3 = false; - if ( !cloud.empty() ) - build3 = true; - - // build 4.0 flag - string CoreFileFlag; - try { - CoreFileFlag = sysConfigNew->getConfig(InstallSection, "CoreFileFlag"); - } - catch(...) - {} - - bool build40 = false; - if ( !CoreFileFlag.empty() ) - build40 = true; - - //build 4.0.1 flag - string AmazonSubNetID; - try { - AmazonSubNetID = sysConfigNew->getConfig(InstallSection, "AmazonSubNetID"); - } - catch(...) - {} - - bool build401 = false; - if ( !AmazonSubNetID.empty() ) - build401 = true; - - //set install config flag - try { - sysConfigNew->setConfig(InstallSection, "InitialInstallFlag", "y"); - } - catch(...) - { - cout << "ERROR: Problem setting InitialInstallFlag from the Calpont System Configuration file" << endl; - exit(-1); - } - - - //check and update PMwithUM - try { - string PMwithUM = sysConfigOld->getConfig(InstallSection, "PMwithUM"); - - if ( !PMwithUM.empty() ) - { - try { - sysConfigNew->setConfig(InstallSection, "PMwithUM", PMwithUM); - } - catch(...) - { - cout << "ERROR: Problem setting PMwithUM in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - { - } - - //check and update PMwithUM - try { - string MySQLRep = sysConfigOld->getConfig(InstallSection, "MySQLRep"); - - if ( !MySQLRep.empty() ) - { - try { - sysConfigNew->setConfig(InstallSection, "MySQLRep", MySQLRep); - } - catch(...) - { - cout << "ERROR: Problem setting MySQLRep in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - { - } - - //set gluster flag if it exists - string GlusterConfig; - string GlusterCopies; - string GlusterStorageType; - try { - GlusterConfig = sysConfigOld->getConfig(InstallSection, "GlusterConfig"); - GlusterCopies = sysConfigOld->getConfig(InstallSection, "GlusterCopies"); - GlusterStorageType = sysConfigOld->getConfig(InstallSection, "GlusterStorageType"); - } - catch(...) - {} - if ( !GlusterConfig.empty() ) { - try { - sysConfigNew->setConfig(InstallSection, "GlusterConfig", GlusterConfig); - sysConfigNew->setConfig(InstallSection, "GlusterCopies", GlusterCopies); - sysConfigNew->setConfig(InstallSection, "GlusterStorageType", GlusterStorageType); - } - catch(...) - {} - } - - //check and make sure the ExtentMap variables don't get changed at install - string oldFilesPerColumnPartition; - string oldExtentsPerSegmentFile; - string newFilesPerColumnPartition; - string newExtentsPerSegmentFile; - try { - oldFilesPerColumnPartition = sysConfigOld->getConfig("ExtentMap", "FilesPerColumnPartition"); - oldExtentsPerSegmentFile = sysConfigOld->getConfig("ExtentMap", "ExtentsPerSegmentFile"); - - newFilesPerColumnPartition = sysConfigNew->getConfig("ExtentMap", "FilesPerColumnPartition"); - newExtentsPerSegmentFile = sysConfigNew->getConfig("ExtentMap", "ExtentsPerSegmentFile"); - - if ( oldFilesPerColumnPartition != newFilesPerColumnPartition ) - { - try { - sysConfigNew->setConfig("ExtentMap", "FilesPerColumnPartition", oldFilesPerColumnPartition); - } - catch(...) - { - cout << "ERROR: Problem setting FilesPerColumnPartition in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - if ( oldExtentsPerSegmentFile != newExtentsPerSegmentFile ) - { - try { - sysConfigNew->setConfig("ExtentMap", "ExtentsPerSegmentFile", oldExtentsPerSegmentFile); - } - catch(...) - { - cout << "ERROR: Problem setting ExtentsPerSegmentFile in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - { - } - - //check and update license key - try { - string key = sysConfigOld->getConfig("SystemConfig", "Flags"); - - if ( !key.empty() ) - { - try { - sysConfigNew->setConfig("SystemConfig", "Flags", key); - } - catch(...) - { - cout << "ERROR: Problem setting Flags in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - { - } - - sysConfigNew->write(); - - if ( extextMapCheckOnly ) - exit(0); - - systemParentOAMModuleName = "pm1"; - - //check if systemParentOAMModuleName (pm1) is configured, if not set to 'pm2' -// string IPaddr = sysConfigOld->getConfig("pm1_ProcessMonitor", "IPAddr"); -// if ( IPaddr == "0.0.0.0" ) -// systemParentOAMModuleName = "pm2"; - - //set Parent OAM Module Name - try{ - sysConfigNew->setConfig(SystemSection, "ParentOAMModuleName", systemParentOAMModuleName); - } - catch(...) - { - cout << "ERROR: Problem updating the Calpont System Configuration file" << endl; - exit(-1); - } - - //setup System Name - string oldSystemName; - try { - oldSystemName = sysConfigOld->getConfig(SystemSection, "SystemName"); - } - catch(...) - { } - - if ( !oldSystemName.empty() ) - systemName = oldSystemName; - - try { - sysConfigNew->setConfig(SystemSection, "SystemName", systemName); - } - catch(...) - { - cout << "ERROR: Problem setting SystemName from the Calpont System Configuration file" << endl; - exit(-1); - } - - //setup System Language - string systemLang = "C"; - try { - systemLang = sysConfigOld->getConfig(SystemSection, "SystemLang"); - } - catch(...) - { } - - try { - sysConfigNew->setConfig(SystemSection, "SystemLang", systemLang); - } - catch(...) - {} - - //setup HA IP Address - string HA_IPadd; - try { - HA_IPadd = sysConfigOld->getConfig("ProcMgr_HA", "IPAddr"); - } - catch(...) - { } - - if ( !HA_IPadd.empty() ) { - try { - sysConfigNew->setConfig("ProcMgr_HA", "IPAddr", HA_IPadd); - } - catch(...) - { - cout << "ERROR: Problem setting ProcMgr_HA from the Calpont System Configuration file" << endl; - exit(-1); - } - } - - //setup CMP IP Addresses - string CMP_IPadd; - string CMP_port; - for ( int id = 1 ;; id ++ ) - { - string cmpName = "CMP" + oam.itoa(id); - try { - CMP_IPadd = sysConfigOld->getConfig(cmpName, "IPAddr"); - } - catch(...) - { } - - if ( !CMP_IPadd.empty() ) { - try { - CMP_port = sysConfigOld->getConfig(cmpName, "Port"); - } - catch(...) - { } - - try { - sysConfigNew->setConfig(cmpName, "IPAddr", CMP_IPadd); - sysConfigNew->setConfig(cmpName, "Port", CMP_port); - } - catch(...) - { - cout << "ERROR: Problem setting CMP from the Calpont System Configuration file" << endl; - exit(-1); - } - } - else - break; - } - - //setup module and process monitor settings - string ModuleHeartbeatPeriod = "3"; - string ModuleHeartbeatCount = "1"; - string ProcessRestartCount = "3"; - string ProcessRestartPeriod = "1"; - string SwapAction = "restartSystem"; - string ActivePmFailoverDisabled = "n"; - - try { - ModuleHeartbeatPeriod = sysConfigOld->getConfig(SystemSection, "ModuleHeartbeatPeriod"); - ModuleHeartbeatCount = sysConfigOld->getConfig(SystemSection, "ModuleHeartbeatCount"); - ProcessRestartCount = sysConfigOld->getConfig(SystemSection, "ProcessRestartCount"); - ProcessRestartPeriod = sysConfigOld->getConfig(SystemSection, "ProcessRestartPeriod"); - SwapAction = sysConfigOld->getConfig(SystemSection, "SwapAction"); - ActivePmFailoverDisabled = sysConfigOld->getConfig(SystemSection, "ActivePmFailoverDisabled"); - } - catch(...) - { } - - try { - sysConfigNew->setConfig(SystemSection, "ModuleHeartbeatPeriod", ModuleHeartbeatPeriod); - sysConfigNew->setConfig(SystemSection, "ModuleHeartbeatCount", ModuleHeartbeatCount); - sysConfigNew->setConfig(SystemSection, "ProcessRestartCount", ProcessRestartCount); - sysConfigNew->setConfig(SystemSection, "ProcessRestartPeriod", ProcessRestartPeriod); - sysConfigNew->setConfig(SystemSection, "SwapAction", SwapAction); - sysConfigNew->setConfig(SystemSection, "ActivePmFailoverDisabled", ActivePmFailoverDisabled); - } - catch(...) - {} - - //save EEPackageType and EnableSNMP - string EEPackageType = "rpm"; - string EnableSNMP = "y"; - - try { - EEPackageType = sysConfigOld->getConfig(InstallSection, "EEPackageType"); - EnableSNMP = sysConfigOld->getConfig(InstallSection, "EnableSNMP"); - } - catch(...) - { } - - try { - sysConfigNew->setConfig(InstallSection, "EEPackageType", EEPackageType); - sysConfigNew->setConfig(InstallSection, "EnableSNMP", EnableSNMP); - } - catch(...) - { } - - if ( EEPackageType.empty() ) - EEPackageType = "rpm"; - - if ( EnableSNMP.empty() ) - EnableSNMP = "y"; - - try { - sysConfigNew->setConfig(InstallSection, "EEPackageType", EEPackageType); - sysConfigNew->setConfig(InstallSection, "EnableSNMP", EnableSNMP); - } - catch(...) - {} - - // make DBRM backwards compatiable for pre 1.0.0.157 load - string dbrmMainProc = "DBRM_Controller"; - string dbrmSubProc = "DBRM_Worker"; - string numSubProc = "NumWorkers"; - - //set system startup offline option to default 'n' - try { - sysConfigNew->setConfig(InstallSection, "SystemStartupOffline", "n"); - } - catch(...) - { - cout << "ERROR: Problem setting systemStartupOffline in the Calpont System Configuration file" << endl; - exit(-1); - } - - //CrossEngineSupport - string Host = ""; - string Port = "3306"; - string User = ""; - string Password = ""; - - try { - Host = sysConfigOld->getConfig("CrossEngineSupport", "Host"); - Port = sysConfigOld->getConfig("CrossEngineSupport", "Port"); - User = sysConfigOld->getConfig("CrossEngineSupport", "User"); - Password = sysConfigOld->getConfig("CrossEngineSupport", "Password"); - } - catch(...) - { - Host = ""; - Port = "3306"; - User = ""; - Password = ""; - } - - try { - sysConfigNew->setConfig("CrossEngineSupport", "Host", Host); - sysConfigNew->setConfig("CrossEngineSupport", "Port", Port); - sysConfigNew->setConfig("CrossEngineSupport", "User", User); - sysConfigNew->setConfig("CrossEngineSupport", "Password", Password); - } - catch(...) - {} - - //QueryStats and UserPriority - string QueryStats = "N"; - string UserPriority = "N"; - - try { - QueryStats = sysConfigOld->getConfig("QueryStats", "Enabled"); - UserPriority = sysConfigOld->getConfig("UserPriority", "Enabled"); - } - catch(...) - { - QueryStats = "N"; - UserPriority = "N"; - } - - try { - sysConfigNew->setConfig("QueryStats", "Enabled", QueryStats); - sysConfigNew->setConfig("UserPriority", "Enabled", UserPriority); - } - catch(...) - {} - - // @bug4598, DirectIO setting - string directIO = "y"; - try { - directIO = sysConfigOld->getConfig("PrimitiveServers", "DirectIO"); - } - catch(...) { - directIO = "y"; - } - - try { - sysConfigNew->setConfig("PrimitiveServers", "DirectIO", directIO); - } - catch(...) - {} - - // @bug4507, configurable pm aggregation AggregationMemoryCheck - string aggMemCheck; - try { - aggMemCheck = sysConfigOld->getConfig("PrimitiveServers", "AggregationMemoryCheck"); - - if ( !( aggMemCheck.empty() || aggMemCheck == "" ) ) { - sysConfigNew->setConfig("PrimitiveServers", "AggregationMemoryCheck", aggMemCheck); - } - } - catch(...) { - } - - //Priority Settings - string HighPriorityPercentage; - try { - HighPriorityPercentage = sysConfigOld->getConfig("PrimitiveServers", "HighPriorityPercentage"); - sysConfigNew->setConfig("PrimitiveServers", "HighPriorityPercentage", HighPriorityPercentage); - } - catch(...) {} - - string MediumPriorityPercentage; - try { - MediumPriorityPercentage = sysConfigOld->getConfig("PrimitiveServers", "MediumPriorityPercentage"); - sysConfigNew->setConfig("PrimitiveServers", "MediumPriorityPercentage", MediumPriorityPercentage); - } - catch(...) {} - - string LowPriorityPercentage; - try { - LowPriorityPercentage = sysConfigOld->getConfig("PrimitiveServers", "LowPriorityPercentage"); - sysConfigNew->setConfig("PrimitiveServers", "LowPriorityPercentage", LowPriorityPercentage); - } - catch(...) {} - - // default to single-server install type - string OserverTypeInstall = oam.itoa(oam::INSTALL_COMBINE_DM_UM_PM);; - string NserverTypeInstall; - string OSingleServerInstall = "y"; - int IserverTypeInstall; - - try { - OserverTypeInstall = sysConfigOld->getConfig(InstallSection, "ServerTypeInstall"); - OSingleServerInstall = sysConfigOld->getConfig(InstallSection, "SingleServerInstall"); - } - catch(...) - { - // default to Normal mult-server install type - OserverTypeInstall = oam.itoa(oam::INSTALL_COMBINE_DM_UM_PM); - OSingleServerInstall = "y"; - } - - // set Server Installation Type - try { - sysConfigNew->setConfig(InstallSection, "ServerTypeInstall", OserverTypeInstall); - sysConfigNew->setConfig(InstallSection, "SingleServerInstall", OSingleServerInstall); - } - catch(...) - {} - - NserverTypeInstall = OserverTypeInstall; - - IserverTypeInstall = atoi(NserverTypeInstall.c_str()); - - //set RotatingDestination - switch ( IserverTypeInstall ) { - case (oam::INSTALL_COMBINE_DM_UM_PM): // combined #1 - dm/um/pm on a single server - { - try { - sysConfigNew->setConfig("PrimitiveServers", "RotatingDestination", "n"); - } - catch(...) - { - cout << "ERROR: Problem setting RotatingDestination in the Calpont System Configuration file" << endl; - exit(-1); - } - - break; - } - } - - string parentOAMModuleType = systemParentOAMModuleName.substr(0,MAX_MODULE_TYPE_SIZE); - - // - // get Data storage Mount - // - - string DBRootStorageType; - - int DBRootCount; - string deviceName; - - try { - DBRootStorageType = sysConfigOld->getConfig(InstallSection, "DBRootStorageType"); - DBRootCount = strtol(sysConfigOld->getConfig(SystemSection, "DBRootCount").c_str(), 0, 0); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the Calpont System Configuration file" << endl; - exit(-1); - } - - // 2.2 to 3.x+ DBRootStorageTypeconversion - if ( DBRootStorageType == "local" ) - DBRootStorageType = "internal"; - - if ( DBRootStorageType == "storage" ) - DBRootStorageType = "external"; - - try { - sysConfigNew->setConfig(InstallSection, "DBRootStorageType", DBRootStorageType); - } - catch(...) - { - cout << "ERROR: Problem setting DBRootStorageType in the Calpont System Configuration file" << endl; - exit(-1); - } - - try { - sysConfigNew->setConfig(SystemSection, "DBRootCount", oam.itoa(DBRootCount)); - } - catch(...) - { - cout << "ERROR: Problem setting DBRoot Count in the Calpont System Configuration file" << endl; - exit(-1); - } - - // - //Update memory and cache settings - // - - string NumBlocksPct; - try { - NumBlocksPct = sysConfigOld->getConfig("DBBC", "NumBlocksPct"); - } - catch(...) - { } - - if ( ( NumBlocksPct.empty() || NumBlocksPct == "" ) && - IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) { - NumBlocksPct = "50"; - } - - if ( !( NumBlocksPct.empty() || NumBlocksPct == "" ) ) { - try { - sysConfigNew->setConfig("DBBC", "NumBlocksPct", NumBlocksPct); - } - catch(...) - {} - } - - string TotalUmMemory; - try { - TotalUmMemory = sysConfigOld->getConfig("HashJoin", "TotalUmMemory"); - } - catch(...) - { } - - try { - sysConfigNew->setConfig("HashJoin", "TotalUmMemory", TotalUmMemory); - } - catch(...) - {} - - string TotalPmUmMemory; - try { - TotalPmUmMemory = sysConfigOld->getConfig("HashJoin", "TotalPmUmMemory"); - } - catch(...) - { } - - try { - sysConfigNew->setConfig("HashJoin", "TotalPmUmMemory", TotalPmUmMemory); - } - catch(...) - {} - - string strNumThreads; - try { - strNumThreads = sysConfigOld->getConfig("DBBC", "NumThreads"); - } - catch(...) - { } - - if ( !( strNumThreads.empty() || strNumThreads == "" ) ) { - try { - sysConfigNew->setConfig("DBBC", "NumThreads", strNumThreads); - } - catch(...) - {} - } - - string MySQLPort = "3306"; - try { - MySQLPort = sysConfigOld->getConfig("Installation", "MySQLPort"); - } - catch(...) - { - MySQLPort = "3306"; - } - - try { - sysConfigNew->setConfig("Installation", "MySQLPort", MySQLPort); - } - catch(...) - {} - - sysConfigNew->write(); - - //Get list of configured system modules - SystemModuleTypeConfig sysModuleTypeConfig; - - try{ - oam.getSystemConfig(sysModuleTypeConfig); - } - catch(...) - { - cout << "ERROR: Problem reading the Calpont System Configuration file" << endl; - exit(-1); - } - - // - // Module Configuration - // - string ModuleSection = "SystemModuleConfig"; - unsigned int maxPMNicCount = 1; - - for ( unsigned int i = 0 ; i < sysModuleTypeConfig.moduletypeconfig.size(); i++) - { - string moduleType = sysModuleTypeConfig.moduletypeconfig[i].ModuleType; - string moduleDesc = sysModuleTypeConfig.moduletypeconfig[i].ModuleDesc; - int moduleCount = sysModuleTypeConfig.moduletypeconfig[i].ModuleCount; - - //verify and setup of modules count - switch ( IserverTypeInstall ) { - case (oam::INSTALL_COMBINE_DM_UM_PM): - { - if ( moduleType == "um" ) { - moduleCount = 0; - - try { - string ModuleCountParm = "ModuleCount" + oam.itoa(i+1); - sysConfigNew->setConfig(ModuleSection, ModuleCountParm, oam.itoa(moduleCount)); - continue; - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - else - { - try { - string ModuleCountParm = "ModuleCount" + oam.itoa(i+1); - sysConfigNew->setConfig(ModuleSection, ModuleCountParm, oam.itoa(moduleCount)); - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - break; - } - default: - { - try { - string ModuleCountParm = "ModuleCount" + oam.itoa(i+1); - sysConfigNew->setConfig(ModuleSection, ModuleCountParm, oam.itoa(moduleCount)); - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - break; - } - } - - if ( moduleCount == 0 ) - //no modules equipped for this Module Type, skip - continue; - - if ( moduleType == "pm" ) - pmNumber = moduleCount; - - //for 2.x to 3.x upgrade dbroot assignments - int dbrootNum = 0; - int systemDBRootCount = 0; - int dbrootCountPerModule = 0; - if ( moduleType == "pm" && !OLDbuild3) - { - dbrootNum = 1; - systemDBRootCount = DBRootCount; - if ( pmNumber > 0 ) - dbrootCountPerModule = DBRootCount / pmNumber; - if ( dbrootCountPerModule == 0 ) - dbrootCountPerModule = 1; - } - - //get Module Name IP addresses and Host Names - DeviceNetworkList::iterator listPT = sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for( ; listPT != sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.end() ; listPT++) - { - PerformanceModule performancemodule; - string moduleName = (*listPT).DeviceName; - int moduleID = atoi(moduleName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - - string moduleDisableState = (*listPT).DisableState; - if ( moduleDisableState.empty() || - moduleDisableState == oam::UnassignedName ) - moduleDisableState = oam::ENABLEDSTATE; - - if ( moduleDisableState == oam::AUTODISABLEDSTATE ) - moduleDisableState = oam::ENABLEDSTATE; - - //set Module Disable State - string moduleDisableStateParm = "ModuleDisableState" + oam.itoa(moduleID) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleDisableStateParm, moduleDisableState); - } - catch(...) - { - cout << "ERROR: Problem setting ModuleDisableState in the Calpont System Configuration file for " + moduleName << endl; - exit(-1); - } - - for( unsigned int nicID=1 ; nicID < MAX_NIC+1 ; nicID++ ) - { - string moduleIPAddr = oam::UnassignedIpAddr; - string moduleHostName = oam::UnassignedName; - - HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); - for( ; pt1 != (*listPT).hostConfigList.end() ; pt1++) - { - if ( moduleName == (*listPT).DeviceName && (*pt1).NicID == nicID) { - moduleIPAddr = (*pt1).IPAddr; - moduleHostName = (*pt1).HostName; - break; - } - } - - if (moduleHostName.empty() || (moduleHostName == oam::UnassignedName) ) - // exit out to next module ID - break; - - if (moduleIPAddr.empty()) - moduleIPAddr = oam::UnassignedIpAddr; - - string moduleNameDesc = moduleDesc + " #" + oam.itoa(moduleID); - - //set New Module Host Name - string moduleHostNameParm = "ModuleHostName" + oam.itoa(moduleID) + "-" + oam.itoa(nicID) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleHostNameParm, moduleHostName); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - - //set Module IP address - string moduleIPAddrNameParm = "ModuleIPAddr" + oam.itoa(moduleID) + "-" + oam.itoa(nicID) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleIPAddrNameParm, moduleIPAddr); - } - catch(...) - { - cout << "ERROR: Problem setting IP address in the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( moduleType == "pm" && moduleDisableState == oam::ENABLEDSTATE ) { - - switch(nicID) { - case 1: - performancemodule.moduleIP1 = moduleIPAddr; - break; - case 2: - performancemodule.moduleIP2 = moduleIPAddr; - break; - case 3: - performancemodule.moduleIP3 = moduleIPAddr; - break; - case 4: - performancemodule.moduleIP4 = moduleIPAddr; - break; - } - if ( maxPMNicCount < nicID ) - maxPMNicCount = nicID; - } - - if ( nicID > 1 ) - continue; - - //set port addresses - if ( moduleName == systemParentOAMModuleName ) { - parentOAMModuleIPAddr = moduleIPAddr; - - //exit out if parentOAMModuleIPAddr is NOT set, this means the System Calpont.xml isn't configured - if ( parentOAMModuleIPAddr == "0.0.0.0" ) { - cout << "ERROR: System Calpont.xml not configured" << endl; - exit(-1); - } - - //set Parent Processes Port IP Address - string parentProcessMonitor = systemParentOAMModuleName + "_ProcessMonitor"; - sysConfigNew->setConfig(parentProcessMonitor, "IPAddr", parentOAMModuleIPAddr); - sysConfigNew->setConfig(parentProcessMonitor, "Port", "8800"); - sysConfigNew->setConfig("ProcMgr", "IPAddr", parentOAMModuleIPAddr); - sysConfigNew->setConfig("ProcStatusControl", "IPAddr", parentOAMModuleIPAddr); - string parentServerMonitor = systemParentOAMModuleName + "_ServerMonitor"; - sysConfigNew->setConfig(parentServerMonitor, "IPAddr", parentOAMModuleIPAddr); - sysConfigNew->setConfig(parentServerMonitor, "Port", "8622"); - - if (build3) { - string portName = systemParentOAMModuleName + "_WriteEngineServer"; - sysConfigNew->setConfig(portName, "IPAddr", parentOAMModuleIPAddr); - sysConfigNew->setConfig(portName, "Port", "8630"); - } - else - { - sysConfigNew->setConfig("DDLProc", "IPAddr", parentOAMModuleIPAddr); - sysConfigNew->setConfig("DMLProc", "IPAddr", parentOAMModuleIPAddr); - } - - if ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) { - - //set User Module's IP Addresses - string Section = "ExeMgr" + oam.itoa(moduleID); - - sysConfigNew->setConfig(Section, "IPAddr", moduleIPAddr); - sysConfigNew->setConfig(Section, "Port", "8601"); - - //set Performance Module's IP's to first NIC IP entered - sysConfigNew->setConfig("DDLProc", "IPAddr", moduleIPAddr); - sysConfigNew->setConfig("DMLProc", "IPAddr", moduleIPAddr); - } - } - else - { - //set child Process Monitor Port IP Address - string portName = moduleName + "_ProcessMonitor"; - sysConfigNew->setConfig(portName, "IPAddr", moduleIPAddr); - sysConfigNew->setConfig(portName, "Port", "8800"); - - //set child Server Monitor Port IP Address - portName = moduleName + "_ServerMonitor"; - sysConfigNew->setConfig(portName, "IPAddr", moduleIPAddr); - sysConfigNew->setConfig(portName, "Port", "8622"); - - //set Performance Module WriteEngineServer Port IP Address - if ( moduleType == "pm" && build3) { - portName = moduleName + "_WriteEngineServer"; - sysConfigNew->setConfig(portName, "IPAddr", moduleIPAddr); - sysConfigNew->setConfig(portName, "Port", "8630"); - } - - //set User Module's IP Addresses - if ( moduleType == "um" || - ( moduleType == "pm" && IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) ) { - - string Section = "ExeMgr" + oam.itoa(moduleID); - - sysConfigNew->setConfig(Section, "IPAddr", moduleIPAddr); - sysConfigNew->setConfig(Section, "Port", "8601"); - } - } - - //set Performance Module's IP's to first NIC IP entered - if ( moduleName == "um1" && build3) { - sysConfigNew->setConfig("DDLProc", "IPAddr", moduleIPAddr); - sysConfigNew->setConfig("DMLProc", "IPAddr", moduleIPAddr); - } - - //setup DBRM processes - if ( moduleName == systemParentOAMModuleName ) - sysConfigNew->setConfig(dbrmMainProc, "IPAddr", moduleIPAddr); - - if ( moduleDisableState == oam::ENABLEDSTATE ) { - DBRMworkernodeID++; - string DBRMSection = dbrmSubProc + oam.itoa(DBRMworkernodeID); - sysConfigNew->setConfig(DBRMSection, "IPAddr", moduleIPAddr); - sysConfigNew->setConfig(DBRMSection, "Module", moduleName); - } - } //end of nicID loop - - //set dbroot assigments - DeviceDBRootList::iterator pt3 = sysModuleTypeConfig.moduletypeconfig[i].ModuleDBRootList.begin(); - - //this will be empty if upgrading from 2.2 - if ( sysModuleTypeConfig.moduletypeconfig[i].ModuleDBRootList.size() == 0 ) - { - if ( !OLDbuild3 && moduleType == "pm") - { - int dbrootCount = dbrootCountPerModule; - string moduleCountParm = "ModuleDBRootCount" + oam.itoa(moduleID) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleCountParm, oam.itoa(dbrootCount)); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - - int entry = 1; - for( ; entry < dbrootCountPerModule+1 ; entry++) - { - int dbrootid = dbrootNum; - if ( dbrootNum > systemDBRootCount ) - dbrootid = 0; - else - dbrootNum++; - - string moduleDBRootIDParm = "ModuleDBRootID" + oam.itoa(moduleID) + "-" + oam.itoa(entry) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleDBRootIDParm, oam.itoa(dbrootid)); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - } - else - { - for( ; pt3 != sysModuleTypeConfig.moduletypeconfig[i].ModuleDBRootList.end() ; pt3++) - { - if ( (*pt3).dbrootConfigList.size() > 0 ) - { - int moduleID = (*pt3).DeviceID; - - DBRootConfigList::iterator pt4 = (*pt3).dbrootConfigList.begin(); - - int dbrootCount = (*pt3).dbrootConfigList.size(); - string moduleCountParm = "ModuleDBRootCount" + oam.itoa(moduleID) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleCountParm, oam.itoa(dbrootCount)); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - - int entry = 1; - for( ; pt4 != (*pt3).dbrootConfigList.end() ; pt4++, entry++) - { - int dbrootid = *pt4; - - string moduleDBRootIDParm = "ModuleDBRootID" + oam.itoa(moduleID) + "-" + oam.itoa(entry) + "-" + oam.itoa(i+1); - try { - sysConfigNew->setConfig(ModuleSection, moduleDBRootIDParm, oam.itoa(dbrootid)); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - } - } - - if ( ( moduleType == "pm" && moduleDisableState == oam::ENABLEDSTATE ) || - ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) ) - performancemodulelist.push_back(performancemodule); - - } //end of module loop - - sysConfigNew->write(); - - } //end of i for loop - - if ( performancemodulelist.size() == 0 ) - { - cout << "ERROR: performancemodulelist is empty, exiting..." << endl; - exit(-1); - } - - //set dm count to 0 always - try { - sysConfigNew->setConfig(ModuleSection, "ModuleCount1", "0"); - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - - //setup DBRM Controller - sysConfigNew->setConfig(dbrmMainProc, numSubProc, oam.itoa(DBRMworkernodeID)); - - //setup PrimitiveServers parameters - try { - sysConfigNew->setConfig("PrimitiveServers", "ConnectionsPerPrimProc", oam.itoa(maxPMNicCount*2)); - } - catch(...) - { - cout << "ERROR: Problem setting ConnectionsPerPrimProc in the Calpont System Configuration file" << endl; - exit(-1); - } - - //set the PM Ports based on Number of PM modules equipped, if any equipped - int minPmPorts = 32; - sysConfigNew->setConfig("PrimitiveServers", "Count", oam.itoa(pmNumber)); - - int pmPorts = pmNumber * (maxPMNicCount*2); - if ( pmPorts < minPmPorts ) - pmPorts = minPmPorts; - - if ( pmNumber > 0 || - ( IserverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) ) - { - const string PM = "PMS"; - - for ( int pmsID = 1; pmsID < pmPorts+1 ; ) - { - for (unsigned int j = 1 ; j < maxPMNicCount+1 ; j++) - { - PerformanceModuleList::iterator list1 = performancemodulelist.begin(); - - for (; list1 != performancemodulelist.end() ; list1++) - { - string pmName = PM + oam.itoa(pmsID); - string IpAddr; - switch(j) { - case 1: - IpAddr = (*list1).moduleIP1; - break; - case 2: - IpAddr = (*list1).moduleIP2; - break; - case 3: - IpAddr = (*list1).moduleIP3; - break; - case 4: - IpAddr = (*list1).moduleIP4; - break; - } - if ( !IpAddr.empty() && IpAddr != oam::UnassignedIpAddr ) { - sysConfigNew->setConfig(pmName, "IPAddr", IpAddr); - pmsID++; - if ( pmsID > pmPorts ) - break; - } - } - if ( pmsID > pmPorts ) - break; - } - } - } - - sysConfigNew->write(); - - // - // Configure Ext Devices - // - SystemExtDeviceConfig systemextdeviceconfig; - - try{ - oam.getSystemConfig(systemextdeviceconfig); - } - catch(...) - { - cout << "ERROR: Problem reading the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( systemextdeviceconfig.Count > 0 ) { - - const string NAME = "Name"; - const string IPADDR = "IPAddr"; - const string DISABLE_STATE = "DisableState"; - - sysConfigNew->setConfig("SystemExtDeviceConfig", "Count", oam.itoa(systemextdeviceconfig.Count)); - - for ( unsigned int i = 0 ; i < systemextdeviceconfig.Count ; i++ ) - { - string name = NAME + oam.itoa(i+1); - string ipaddr = IPADDR + oam.itoa(i+1); - string disablestate = DISABLE_STATE + oam.itoa(i+1); - - sysConfigNew->setConfig("SystemExtDeviceConfig", name, systemextdeviceconfig.extdeviceconfig[i].Name); - sysConfigNew->setConfig("SystemExtDeviceConfig", ipaddr, systemextdeviceconfig.extdeviceconfig[i].IPAddr); - sysConfigNew->setConfig("SystemExtDeviceConfig", disablestate, systemextdeviceconfig.extdeviceconfig[i].DisableState); - } - } - - sysConfigNew->write(); - - // - // Configure NMS Addresses - // - - string NMSIPAddress; - try { - NMSIPAddress = sysConfigOld->getConfig(SystemSection, "NMSIPAddress"); - } - catch(...) - { - cout << "ERROR: Problem getting NMSIPAddress from Calpont System Configuration file" << endl; - exit(-1); - } - - try { - sysConfigNew->setConfig(SystemSection, "NMSIPAddress", NMSIPAddress); - } - catch(...) - { - cout << "ERROR: Problem setting NMSIPAddress in the Calpont System Configuration file" << endl; - exit(-1); - } - - // - // setup TransactionArchivePeriod - // - - string transactionArchivePeriod; - try { - transactionArchivePeriod = sysConfigOld->getConfig(SystemSection, "TransactionArchivePeriod"); - } - catch(...) - { - cout << "ERROR: Problem getting transactionArchivePeriod from Calpont System Configuration file" << endl; - exit(-1); - } - - try { - sysConfigNew->setConfig(SystemSection, "TransactionArchivePeriod", transactionArchivePeriod); - } - catch(...) - { - cout << "ERROR: Problem setting IP address in the Calpont System Configuration file" << endl; - exit(-1); - } - - // - // 3 and above configuration items - // - if (build3) { - //setup cloud parameters - string x509Cert; - string x509PriKey; - string UMStorageType; - string rpw; - string PMInstanceType; - string UMInstanceType; - string UMSecurityGroup; - string UMVolumeSize; - string PMVolumeSize; - string AmazonAutoTagging; - string AmazonRegion; - string AmazonZone; - string AmazonVPCNextPrivateIP; - - try { - cloud = sysConfigOld->getConfig(InstallSection, "Cloud"); - x509Cert = sysConfigOld->getConfig(InstallSection, "AmazonX509Certificate"); - x509PriKey = sysConfigOld->getConfig(InstallSection, "AmazonX509PrivateKey"); - UMStorageType = sysConfigOld->getConfig(InstallSection, "UMStorageType"); - rpw = sysConfigOld->getConfig(InstallSection, "rpw"); - PMInstanceType = sysConfigOld->getConfig(InstallSection, "PMInstanceType"); - UMInstanceType = sysConfigOld->getConfig(InstallSection, "UMInstanceType"); - UMSecurityGroup = sysConfigOld->getConfig(InstallSection, "UMSecurityGroup"); - UMVolumeSize = sysConfigOld->getConfig(InstallSection, "UMVolumeSize"); - PMVolumeSize = sysConfigOld->getConfig(InstallSection, "PMVolumeSize"); - AmazonAutoTagging = sysConfigOld->getConfig(InstallSection, "AmazonAutoTagging"); - AmazonRegion = sysConfigOld->getConfig(InstallSection, "AmazonRegion"); - AmazonZone = sysConfigOld->getConfig(InstallSection, "AmazonZone"); - AmazonVPCNextPrivateIP = sysConfigOld->getConfig(InstallSection, "AmazonVPCNextPrivateIP"); - AmazonSubNetID = sysConfigOld->getConfig(InstallSection, "AmazonSubNetID"); - } - catch(...) - { } - - //this is for 2.2 to 4.x builds - if ( UMStorageType.empty() || UMStorageType == "" ) - UMStorageType = "internal"; - - // 3.x upgrade - if (build3 && !build40 && !build401) - { - if ( cloud == "no" || cloud == oam::UnassignedName) - cloud = "n"; - if ( cloud == "amazon-ec2" || cloud == "amazon-vpc") - cloud = "amazon"; - } - - // 4.0 upgrade - if (build40 && !build401) - { - if ( cloud == "no" || cloud == "n" ) - cloud = oam::UnassignedName; - } - - // 4.0.1+ upgrade - if (build401) - { - if ( cloud == "no" || cloud == "n" ) - cloud = oam::UnassignedName; - if ( cloud == "amazon") - cloud = "amazon-ec2"; - if ( AmazonSubNetID.empty() ) - AmazonSubNetID = oam::UnassignedName; - if ( AmazonVPCNextPrivateIP.empty() ) - AmazonVPCNextPrivateIP = oam::UnassignedName; - - try { - sysConfigNew->setConfig(InstallSection, "AmazonSubNetID", AmazonSubNetID); - sysConfigNew->setConfig(InstallSection, "AmazonVPCNextPrivateIP", AmazonVPCNextPrivateIP); - } - catch(...) - { - // cout << "ERROR: Problem setting Cloud Parameters from the Calpont System Configuration file" << endl; - // exit(-1); - } - } - - try { - sysConfigNew->setConfig(InstallSection, "Cloud", cloud); - sysConfigNew->setConfig(InstallSection, "AmazonX509Certificate", x509Cert); - sysConfigNew->setConfig(InstallSection, "AmazonX509PrivateKey", x509PriKey); - sysConfigNew->setConfig(InstallSection, "UMStorageType", UMStorageType); - sysConfigNew->setConfig(InstallSection, "rpw", rpw); - sysConfigNew->setConfig(InstallSection, "PMInstanceType", PMInstanceType); - sysConfigNew->setConfig(InstallSection, "UMInstanceType", UMInstanceType); - sysConfigNew->setConfig(InstallSection, "UMSecurityGroup", UMSecurityGroup); - sysConfigNew->setConfig(InstallSection, "UMVolumeSize", UMVolumeSize); - sysConfigNew->setConfig(InstallSection, "PMVolumeSize", PMVolumeSize); - sysConfigNew->setConfig(InstallSection, "AmazonAutoTagging", AmazonAutoTagging); - sysConfigNew->setConfig(InstallSection, "AmazonRegion", AmazonRegion); - sysConfigNew->setConfig(InstallSection, "AmazonZone", AmazonZone); - } - catch(...) - { - // cout << "ERROR: Problem setting Cloud Parameters from the Calpont System Configuration file" << endl; - // exit(-1); - } - - - if ( cloud == "amazon-ec2" || cloud == "amazon-vpc") - cloud = "amazon"; - - //setup um storage - if ( cloud == "amazon" && UMStorageType == "external") { - - try - { - systemStorageInfo_t t; - t = oam.getStorageConfig(); - - ModuleTypeConfig moduletypeconfig; - oam.getSystemConfig("um", moduletypeconfig); - for ( int id = 1; id < moduletypeconfig.ModuleCount+1 ; id++) - { - string volumeNameID = "UMVolumeName" + oam.itoa(id); - string volumeName = oam::UnassignedName; - string deviceNameID = "UMVolumeDeviceName" + oam.itoa(id); - string deviceName = oam::UnassignedName; - try { - volumeName = sysConfigOld->getConfig(InstallSection, volumeNameID); - deviceName = sysConfigOld->getConfig(InstallSection, deviceNameID); - } - catch(...) - {} - - try { - sysConfigNew->setConfig(InstallSection, volumeNameID, volumeName); - sysConfigNew->setConfig(InstallSection, deviceNameID, deviceName); - } - catch(...) - {} - } - } - catch (exception& e) - { - cout << endl << "**** getStorageConfig Failed : " << e.what() << endl; - } - } - - //setup dbroot storage - try - { - DBRootConfigList dbrootConfigList; - oam.getSystemDbrootConfig(dbrootConfigList); - - DBRootConfigList::iterator pt = dbrootConfigList.begin(); - for( ; pt != dbrootConfigList.end() ; pt++) - { - int id = *pt; - string DBrootID = "DBRoot" + oam.itoa(id);; - string pathID = "/usr/local/Calpont/data" + oam.itoa(id); - - try { - sysConfigNew->setConfig(SystemSection, DBrootID, pathID); - } - catch(...) - { - cout << "ERROR: Problem setting DBRoot in the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( cloud == "amazon" && DBRootStorageType == "external") { - - string volumeNameID = "PMVolumeName" + oam.itoa(id); - string volumeName = oam::UnassignedName; - string deviceNameID = "PMVolumeDeviceName" + oam.itoa(id); - string deviceName = oam::UnassignedName; - try { - volumeName = sysConfigOld->getConfig(InstallSection, volumeNameID); - deviceName = sysConfigOld->getConfig(InstallSection, deviceNameID); - } - catch(...) - {} - - try { - sysConfigNew->setConfig(InstallSection, volumeNameID, volumeName); - sysConfigNew->setConfig(InstallSection, deviceNameID, deviceName); - } - catch(...) - {} - } - } - } - catch (exception& e) - { - cout << endl << "**** getSystemDbrootConfig Failed : " << e.what() << endl; - } - - //setup unassigned dbroots - try - { - DBRootConfigList dbrootConfigList; - oam.getUnassignedDbroot(dbrootConfigList); - - DBRootConfigList::iterator pt = dbrootConfigList.begin(); - for( ; pt != dbrootConfigList.end() ; pt++) - { - int id = *pt; - string DBrootID = "DBRoot" + oam.itoa(id);; - string pathID = "/usr/local/Calpont/data" + oam.itoa(id); - - try { - sysConfigNew->setConfig(SystemSection, DBrootID, pathID); - } - catch(...) - { - cout << "ERROR: Problem setting DBRoot in the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( cloud == "amazon" && DBRootStorageType == "external") { - - string volumeNameID = "VolumeName" + oam.itoa(id); - string volumeName = oam::UnassignedName; - string deviceNameID = "VolumeDeviceName" + oam.itoa(id); - string deviceName = oam::UnassignedName; - try { - volumeName = sysConfigOld->getConfig(InstallSection, volumeNameID); - deviceName = sysConfigOld->getConfig(InstallSection, deviceNameID); - } - catch(...) - {} - - try { - sysConfigNew->setConfig(InstallSection, volumeNameID, volumeName); - sysConfigNew->setConfig(InstallSection, deviceNameID, deviceName); - } - catch(...) - {} - - } - } - } - catch (exception& e) - { - cout << endl << "**** getUnassignedDbroot Failed : " << e.what() << endl; - } - } - else - { // pre 3.0 only - - string DBRootStorageLoc; - for( int i=1 ; i < DBRootCount+1 ; i++) - { - if ( DBRootStorageType != "local") { - - string DBRootStorageLocID = "DBRootStorageLoc" + oam.itoa(i); - try { - DBRootStorageLoc = sysConfigOld->getConfig(InstallSection, DBRootStorageLocID); - } - catch(...) - { - cout << "ERROR: Problem getting '" + DBRootStorageLocID + "' from the Calpont System Configuration file" << endl; - exit(-1); - } - - try { - sysConfigNew->setConfig(InstallSection, DBRootStorageLocID, DBRootStorageLoc); - } - catch(...) - { - cout << "ERROR: Problem setting '" + DBRootStorageLocID + "' in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - string DBrootID = "DBRoot" + oam.itoa(i); - string pathID = "/usr/local/Calpont/data" + oam.itoa(i); - - try { - sysConfigNew->setConfig(SystemSection, DBrootID, pathID); - } - catch(...) - { - cout << "ERROR: Problem setting DBRoot in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - - //do elastic IP configuration - int AmazonElasticIPCount = 0; - try { - AmazonElasticIPCount = atoi(sysConfigOld->getConfig(InstallSection, "AmazonElasticIPCount").c_str()); - - if (AmazonElasticIPCount > 0 ) - { - for ( int id = 1 ; id < AmazonElasticIPCount+1 ; id++ ) - { - string AmazonElasticModule = "AmazonElasticModule" + oam.itoa(id); - string ELmoduleName; - string AmazonElasticIPAddr = "AmazonElasticIPAddr" + oam.itoa(id); - string ELIPaddress; - - ELmoduleName = sysConfigOld->getConfig(InstallSection, AmazonElasticModule); - ELIPaddress = sysConfigOld->getConfig(InstallSection, AmazonElasticIPAddr); - - try { - sysConfigNew->setConfig(InstallSection, "AmazonElasticIPCount", oam.itoa(AmazonElasticIPCount)); - sysConfigNew->setConfig(InstallSection, AmazonElasticModule, ELmoduleName); - sysConfigNew->setConfig(InstallSection, AmazonElasticIPAddr, ELIPaddress); - } - catch(...) - {} - } - } - } - catch(...) - {} - - try{ - oam.getSystemConfig("AmazonElasticIPCount", AmazonElasticIPCount); - } - catch(...) { - AmazonElasticIPCount = 0; - } - - // ConcurrentTransactions - string ConcurrentTransactions; - try { - ConcurrentTransactions = sysConfigOld->getConfig(SystemSection, "ConcurrentTransactions"); - - if ( !ConcurrentTransactions.empty() ) - { - try { - sysConfigNew->setConfig(SystemSection, "ConcurrentTransactions", ConcurrentTransactions); - } - catch(...) - { - cout << "ERROR: Problem setting ConcurrentTransactions in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - // NetworkCompression Enabled - string NetworkCompression; - try { - NetworkCompression = sysConfigOld->getConfig("NetworkCompression", "Enabled"); - - if ( !NetworkCompression.empty() ) - { - try { - sysConfigNew->setConfig("NetworkCompression", "Enabled", NetworkCompression); - } - catch(...) - { - cout << "ERROR: Problem setting NetworkCompression in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - // CoreFile Flag - try { - CoreFileFlag = sysConfigOld->getConfig("Installation", "CoreFileFlag"); - - if ( !CoreFileFlag.empty() ) - { - try { - sysConfigNew->setConfig("Installation", "CoreFileFlag", CoreFileFlag); - } - catch(...) - { - cout << "ERROR: Problem setting CoreFileFlag in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - //hadoop - string DataFilePlugin; - try { - DataFilePlugin = sysConfigOld->getConfig(SystemSection, "DataFilePlugin"); - - if ( !DataFilePlugin.empty() ) - { - try { - sysConfigNew->setConfig(SystemSection, "DataFilePlugin", DataFilePlugin); - } - catch(...) - { - cout << "ERROR: Problem setting DataFilePlugin in the Calpont System Configuration file" << endl; - exit(-1); - } - - string DataFileEnvFile; - try { - DataFileEnvFile = sysConfigOld->getConfig(SystemSection, "DataFileEnvFile"); - - if ( !DataFileEnvFile.empty() ) - { - try { - sysConfigNew->setConfig(SystemSection, "DataFileEnvFile", DataFileEnvFile); - } - catch(...) - { - cout << "ERROR: Problem setting DataFileEnvFile in the Calpont System Configuration file" << endl; - exit(-1); - } - } - else - { - string::size_type pos = DataFilePlugin.find("hdfs-20.so",0); - if (pos != string::npos) - DataFileEnvFile = "setenv-hdfs-20"; - else - DataFileEnvFile = "setenv-hdfs-12"; - - try { - sysConfigNew->setConfig(SystemSection, "DataFileEnvFile", DataFileEnvFile); - } - catch(...) - { - cout << "ERROR: Problem setting DataFileEnvFile in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - string ExtentsPerSegmentFile; - try { - ExtentsPerSegmentFile = sysConfigOld->getConfig("ExtentMap", "ExtentsPerSegmentFile"); - - try { - sysConfigNew->setConfig("ExtentMap", "ExtentsPerSegmentFile", ExtentsPerSegmentFile); - } - catch(...) - { - cout << "ERROR: Problem setting ExtentsPerSegmentFile in the Calpont System Configuration file" << endl; - exit(-1); - } - } - catch(...) - {} - } - } - catch(...) - {} - - string DataFileLog; - try { - DataFileLog = sysConfigOld->getConfig(SystemSection, "DataFileLog"); - - if ( !DataFileLog.empty() ) - { - try { - sysConfigNew->setConfig(SystemSection, "DataFileLog", DataFileLog); - } - catch(...) - { - cout << "ERROR: Problem setting DataFileLog in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - - string AllowDiskBasedJoin; - string TempFilePath; - string TempFileCompression; - - try { - AllowDiskBasedJoin = sysConfigOld->getConfig("HashJoin", "AllowDiskBasedJoin"); - - if ( !AllowDiskBasedJoin.empty() ) - { - TempFilePath = sysConfigOld->getConfig("HashJoin", "TempFilePath"); - TempFileCompression = sysConfigOld->getConfig("HashJoin", "TempFileCompression"); - - try { - sysConfigNew->setConfig("HashJoin", "AllowDiskBasedJoin", AllowDiskBasedJoin); - sysConfigNew->setConfig("HashJoin", "TempFilePath", TempFilePath); - sysConfigNew->setConfig("HashJoin", "TempFileCompression", TempFileCompression); - } - catch(...) - { - cout << "ERROR: Problem setting AllowDiskBasedJoin in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - try { - Host = sysConfigOld->getConfig("QueryTele", "Host"); - - if ( !Host.empty() ) - { - Port = sysConfigOld->getConfig("QueryTele", "Port"); - - try { - sysConfigNew->setConfig("QueryTele", "Host", Host); - sysConfigNew->setConfig("QueryTele", "Port", Port); - } - catch(...) - { - cout << "ERROR: Problem setting QueryTele in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - catch(...) - {} - - - //Write out Updated System Configuration File - sysConfigNew->write(); -} diff --git a/tools/configMgt/autoInstaller.cpp b/tools/configMgt/autoInstaller.cpp deleted file mode 100644 index dfab7294..00000000 --- a/tools/configMgt/autoInstaller.cpp +++ /dev/null @@ -1,903 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/****************************************************************************************** -* $Id: autoInstaller.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* List of files being updated by configure: -* Calpont/etc/Calpont.xml -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include - -#include -#include - -#include "liboamcpp.h" -#include "configcpp.h" - -using namespace std; -using namespace oam; -using namespace config; - -int main(int argc, char *argv[]) -{ - Oam oam; - string systemName; - string systemPackage; - string systemUser = "root"; - string calpontPackage; - string mysqlRPM; - string mysqldRPM; - string installParentModuleHostName; - string installParentModuleIPAddr; - string debug_flag = "0"; - string uninstall_debug = " "; - string password; - string XMpassword = "dummypw"; - string configFile = "NULL"; - string release = "Latest"; - string installDir = "/usr/local"; - string MySQLpassword = "dummymysqlpw"; - string MySQLport= oam::UnassignedName; - string installPackageType = ""; - - char* pcommand = 0; - string prompt; - bool noprompt = false; - string CE = "0"; - - int forceVer = -1; - - Config* sysConfig = Config::makeConfig("./systems/CalpontSystems.xml"); - - //gethostname to determine where to get the packages - string SHARED = "//srvfrisco2/public"; - char hostname[128]; - gethostname(hostname, sizeof hostname); - string hostName = hostname; - string::size_type pos = hostName.find("srvnightly",0); - if (pos != string::npos) - SHARED = "//calweb/shared"; - - for( int i = 1; i < argc; i++ ) - { - if( string("-h") == argv[i] ) { - cout << endl; - cout << "'autoInstaller' installs the RPMs located in" << endl; - cout << SHARED << "/Iterations on the specified" << endl; - cout << "system. It will either install the latest rpm located in" << endl; - cout << "in the /Latest directory or the rpm associated with the" << endl; - cout << "release-number entered." << endl; - cout << endl; - cout << "The list of systems are located in '" << sysConfig->configFile() << "'" << endl; - cout << endl; - cout << "The 'Calpont.xml' used in the install will default to system" << endl; - cout << "configuration of the 'Calpont.xml' located on the system being" << endl; - cout << "or can be passed as an argument into 'quickInstaller'." << endl; - cout << endl; - cout << "Usage: autoInstaller -s system [-h][-ce][-r release][-c configFile][-n][-d][-p package-type][-m mysql-password][-port mysql-port]" << endl; - cout << " -s system-name" << endl; - cout << " -ce community-edition install" << endl; - cout << " -r release-number (optional, default to 'Latest')" << endl; - cout << " -c InfiniDB Config File located in system-name directory (optional, default to system configuration)" << endl; - cout << " -n No Prompt (Used for automated Installs)" << endl; - cout << " -m System MySQL Password, if set" << endl; - cout << " -port System MySQL Port, if set" << endl; - cout << " -d Debug Flag" << endl; - cout << " -p Install Package Type (rpm or binary), defaults to " << sysConfig->configFile() << " setting" << endl; - cout << " -3 Force a version 3 install, defaults to autodetect" << endl; - exit(0); - } - else if( string("-s") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing system argument" << endl; - exit(1); - } - systemName = argv[i]; - } - else if( string("-r") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing release argument" << endl; - exit(1); - } - release = argv[i]; - } - else if( string("-c") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing config file argument" << endl; - exit(1); - } - configFile = argv[i]; - string systemConfig = "systems/" + systemName + "/" + configFile; - ifstream oldFile (systemConfig.c_str()); - if (!oldFile) { - cout << "ERROR: Config file '" + systemConfig + "' not found" << endl; - exit(1); - } - } - else if( string("-ce") == argv[i] ) { - CE = "1"; - } - else if( string("-n") == argv[i] ) { - noprompt = true; - } - else if( string("-d") == argv[i] ) { - debug_flag = "1"; - uninstall_debug = "-d"; - } - else if( string("-m") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing mysql password argument" << endl; - exit(1); - } - MySQLpassword = argv[i]; - } - else if( string("-port") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing mysql port argument" << endl; - exit(1); - } - MySQLport = argv[i]; - } - else if( string("-p") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: package type argument" << endl; - exit(1); - } - installPackageType = argv[i]; - } - else if( string("-3") == argv[i] ) { - forceVer = 3; - } - else { - cout << "ERROR: Unknown option: " << argv[i] << endl; - exit(1); - } - } - - if (systemName.empty() ) { - cout << endl; - cout << "Usage: autoInstaller -s system [-h][-ce][-r release][-c configFile][-n][-d][-p package-type][-m mysql-password][-port mysql-port]" << endl; - exit(1); - } - - // get Parent OAM Module based on system name - int systemCount; - try { - systemCount = strtol(sysConfig->getConfig("NetworkConfig", "SystemCount").c_str(), 0, 0); - if ( systemCount == 0 ) { - cout << "ERROR: SystemCount in " << sysConfig->configFile() << " equal to 0, exiting" << endl; - cerr << "ERROR: SystemCount in " << sysConfig->configFile() << " equal to 0, exiting" << endl; - exit(1); - } - } - catch(...) - { - cout << "ERROR: Problem getting SystemCount from " << sysConfig->configFile() << ", exiting" << endl; - cerr << "ERROR: Problem getting SystemCount from " << sysConfig->configFile() << ", exiting" << endl; - exit(1); - } - - bool found = false; - for ( int i = 1 ; i <= systemCount ; i++) - { - string SystemName = "SystemName" + oam.itoa(i); - string oamParentModule = "OAMParentModule" + oam.itoa(i); - string SystemPackage = "SystemPackage" + oam.itoa(i); - string SystemPassword = "SystemPassword" + oam.itoa(i); - string SystemUser = "SystemUser" + oam.itoa(i); - - string tempSystem; - try { - tempSystem = sysConfig->getConfig("NetworkConfig", SystemName ); - } - catch(...) - { - cout << "ERROR: Problem getting SystemName from " << sysConfig->configFile() << ", exiting" << endl; - cerr << "ERROR: Problem getting SystemName from " << sysConfig->configFile() << ", exiting" << endl; - exit(1); - } - - if ( tempSystem == systemName ) { - try { - installParentModuleHostName = sysConfig->getConfig("NetworkConfig", oamParentModule ); - password = sysConfig->getConfig("NetworkConfig", SystemPassword ); - systemPackage = sysConfig->getConfig("NetworkConfig", SystemPackage ); - systemUser = sysConfig->getConfig("NetworkConfig", SystemUser ); - found = true; - break; - } - catch(...) - { - cout << "ERROR: Problem getting SystemName from " << sysConfig->configFile() << ", exiting" << endl; - cerr << "ERROR: Problem getting SystemName from " << sysConfig->configFile() << ", exiting" << endl; - exit(1); - } - } - } - - if ( !found ) { - cout << "ERROR: System Name '" + systemName + "' not in " << sysConfig->configFile() << ", exiting" << endl; - cerr << "ERROR: System Name '" + systemName + "' not in " << sysConfig->configFile() << ", exiting" << endl; - exit(1); - } - - //check if package type option is used - if ( !installPackageType.empty() ) - { - if ( installPackageType == "rpm" ) - systemPackage = "*.x86_64.rpm"; - else if ( installPackageType == "binary" ) - systemPackage = "*x86_64.bin.tar.gz"; - else - { - cout << "Invalid InfiniDB Package Type Arugument entered, use 'rpm' or 'binary' exiting" << endl; - cerr << "Invalid InfiniDB Package Type Arugument entered, use 'rpm' or 'binary' exiting" << endl; - exit(1); - } - } - - cout << endl << "*** Make sure nobody is sitting in a mounted directory, like data1 ***" << endl; - - if ( !noprompt ) { - while(true) - { - cout << endl; - - if ( systemPackage == "*.x86_64.rpm" ) - prompt = "Are you sure you want to install the '" + release + "' InfiniDB RPM on '" + systemName + "' ? (y,n,exit) > "; - else - prompt = "Are you sure you want to install the '" + release + "/packages' InfiniDB Binary Package on '" + systemName + "' ? (y,n,exit) > "; - - pcommand = readline(prompt.c_str()); - if (!pcommand) - exit(0); - - string confirm = pcommand; - free(pcommand); - pcommand = 0; - if ( confirm == "exit" ) - exit(0); - if ( confirm == "y" ) - break; - else - { - if ( confirm == "n" ) { - prompt = "Enter system (" + systemName + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - systemName = pcommand; - free(pcommand); - pcommand = 0; - } - else { - prompt = "Enter release (" + release + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - release = pcommand; - free(pcommand); - pcommand = 0; - } - } - } - } - } - } - - //get if root or no-root user install - if ( systemUser != "root" ) - installDir = "/home/" + systemUser; - - //remove all calpont packages from local /root/ directory, can interfere with install - if (geteuid() == 0) - system("rm -f /root/calpont-*rpm /root/infinidb-*rpm"); - - string systemDir = "systems/" + systemName + "/"; - - string cmd = "mkdir " + systemDir + " > /dev/null 2>&1"; - system(cmd.c_str()); - - //delete any packages and xml files - cmd = "rm -f " + systemDir + "* > /dev/null 2>&1"; - system(cmd.c_str()); - - int idbver = -1; - string currentPrefix; - string calpontPackagename; - string mysqlRPMname; - - //TODO: replace all the goofy file I/O with glob(3) or better yet just parse the output of samba 'dir' cmd - // and avoid all the wasted network I/O - if ( systemPackage == "*.x86_64.rpm" ) - { - //get rpm - string smbCmd = "cd " + systemDir + ";smbclient " + SHARED + " -Wcalpont -U" + oam::USERNAME + "%" + oam::PASSWORD + " -c 'cd Iterations/" + release + "/;prompt OFF;mget " + systemPackage + "' > /dev/null 2>&1"; - system(smbCmd.c_str()); - - if (forceVer > 0) - { - idbver = forceVer; - } - else - { - //try to guess the release, v4+ takes precedence - string sentinel = systemDir + "infinidb-libs-*.rpm"; - glob_t gt; - memset(>, 0, sizeof(gt)); - idbver = 3; - if (glob(sentinel.c_str(), 0, 0, >) == 0) - idbver = 4; - globfree(>); - } - //v4 really means 4+, it'll get fixed later... - currentPrefix = oam.itoa(idbver); - if (idbver >= 4) - { - calpontPackagename = "infinidb"; - mysqlRPMname = calpontPackagename + "-storage-engine"; - } - else - { - if (CE == "1") - { - cout << endl << "FAILED: Community-Edition install valid for 4.x builds and above" << endl; - cerr << endl << "FAILED: Community-Edition install valid for 4.x builds and above" << endl; - exit(1); - } - - calpontPackagename = "calpont"; - mysqlRPMname = calpontPackagename + "-mysql"; - } - - //check if package is there - cmd = "ls " + systemDir + mysqlRPMname + "* > /tmp/package.txt 2>&1"; - - int rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - { - cout << endl << "FAILED: InfiniDB Package(s) not found in " << release << " , exiting" << endl; - cerr << endl << "FAILED: InfiniDB Package(s) not found in " << release << " , exiting" << endl; - exit(1); - } - } - - ifstream file ("/tmp/package.txt"); - - char line[400]; - string buf; - - while (file.getline(line, 400)) - { - buf = line; - - string::size_type pos; - if (idbver >= 4) - { - pos = buf.find("infinidb-storage-engine-",0); - if (pos != string::npos) { - currentPrefix = buf.substr(pos+24,1); - break; - } - } - else - { - pos = buf.find("calpont-mysql-",0); - if (pos != string::npos) { - currentPrefix = buf.substr(pos+14,1); - break; - } - } - } - file.close(); - - calpontPackage = calpontPackagename + "-" + currentPrefix + systemPackage; - - cout << endl << "Using the InfiniDB Packages '" + systemPackage + "' from " + SHARED + "/Iterations/" + release + "/" << endl; - } - else //binary package - { - //this will pickup more than we want... - string smbCmd = "cd " + systemDir + ";smbclient " + SHARED + " -Wcalpont -U" + oam::USERNAME + "%" + oam::PASSWORD + " -c 'cd Iterations/" + release + "/packages;prompt OFF;mget *.x86_64.bin.tar.gz' > /dev/null 2>&1"; - system(smbCmd.c_str()); - - //TODO: consolodate this with above test... - if (forceVer > 0) - { - idbver = forceVer; - } - else - { - //try to guess the release, v4+ takes precedence - string sentinel = systemDir + "infinidb-ent-*.tar.gz"; - glob_t gt; - memset(>, 0, sizeof(gt)); - idbver = 3; - if (glob(sentinel.c_str(), 0, 0, >) == 0) - idbver = 4; - globfree(>); - } - //v4 really means 4+, it'll get fixed later... - currentPrefix = oam.itoa(idbver); - if (idbver >= 4) - { - calpontPackagename = "infinidb"; - mysqlRPMname = calpontPackagename + "-storage-engine"; - calpontPackage = "infinidb-ent-" + systemPackage; - } - else - { - calpontPackagename = "calpont"; - mysqlRPMname = calpontPackagename + "-mysql"; - calpontPackage = calpontPackagename + "-infinidb-ent-" + systemPackage; - } - - //check if package is there - cmd = "ls " + systemDir + calpontPackage + " > /tmp/package.txt 2>&1"; - - int rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - { - cout << endl << "FAILED: InfiniDB binary package not found in " << release << ", exiting" << endl; - cerr << endl << "FAILED: InfiniDB binary package not found in " << release << ", exiting" << endl; - exit(1); - } - } - - ifstream file ("/tmp/package.txt"); - - char line[400]; - string buf; - - while (file.getline(line, 400)) - { - buf = line; - - string::size_type pos; - if (idbver >= 4) - { - pos = buf.find("infinidb-ent-",0); - if (pos != string::npos) { - currentPrefix = buf.substr(pos+13,1); - break; - } - } - else - { - pos = buf.find("calpont-infinidb-ent-",0); - if (pos != string::npos) { - currentPrefix = buf.substr(pos+21,1); - break; - } - } - } - file.close(); - - cout << endl << "Using the InfiniDB Package '" + systemPackage + "' from " + SHARED + "/Iterations/" + release + "/packages" << endl; - - } - - mysqlRPM = mysqlRPMname + "-" + systemPackage; - if (idbver >= 4) - mysqldRPM = calpontPackagename + "-mysql-" + systemPackage; - else - mysqldRPM = calpontPackagename + "-mysqld-" + systemPackage; - - //TODO: we go to all the effort of downloading the packages above only to delete them here... - cmd = "rm -f " + systemDir + systemPackage + " > /dev/null 2>&1"; - system(cmd.c_str()); - - //get Network IP Address - installParentModuleIPAddr = oam.getIPAddress( installParentModuleHostName); - if ( installParentModuleIPAddr.empty() || installParentModuleIPAddr == "127.0.0.1" ) { - cout << "Invalid Host Name (No DNS IP found), exiting..." << endl; - cerr << "Invalid Host Name (No DNS IP found), exiting..." << endl; - exit(1); - } - - //check to see if system is up - string cmdLine = "ping "; - string cmdOption = " -w 5 >> /dev/null"; - - cmd = cmdLine + installParentModuleIPAddr + cmdOption; - int rtnCode = system(cmd.c_str()); - if ( rtnCode != 0 ) { - cout << " FAILED: failed ping test command installParentModuleIPAddr: " << installParentModuleIPAddr << ", exiting" << endl; - cerr << " FAILED: failed ping test command installParentModuleIPAddr: " << installParentModuleIPAddr << ", exiting" << endl; - exit(1); - } - - cout << endl; - -#if 0 -cout << "idbver = " << idbver << endl; -cout << "calpontPackagename = " << calpontPackagename << endl; -cout << "mysqlRPMname = " << mysqlRPMname << endl; -cout << "calpontPackage = " << calpontPackage << endl; -cout << "systemPackage = " << systemPackage << endl; -exit(0); -#endif - - //get release and system Calpont.xml and generate a new Calpont.xml file for installation - if ( configFile == "NULL" ) { - cout << "Get Release Calpont.xml " << flush; - - // get release Calpont.xml - string cmd = "cd " + systemDir + ";smbclient " + SHARED + " -Wcalpont -U" + oam::USERNAME + "%" + oam::PASSWORD + " -c 'cd Iterations/" + release + "/;prompt OFF;mget Calpont.xml' > /dev/null 2>&1"; - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << "FAILED: no Release Calpont.xml found for release '" + release + "', exiting" << endl; - cerr << "FAILED: no Release Calpont.xml found for release '" + release + "', exiting" << endl; - exit(1); - } - else - { - cmd = "cd " + systemDir + ";mv -f Calpont.xml Calpont.xml.new > /dev/null 2>&1"; - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << "FAILED: no Release Calpont.xml found for release '" + release + "', exiting" << endl; - cerr << "FAILED: no Release Calpont.xml found for release '" + release + "', exiting" << endl; - exit(1); - } - else - { - cout << "DONE" << endl; - - //get system Calpont.xml - cout << "Get System Calpont.xml " << flush; - for ( int retry = 0 ; retry < 5 ; retry++ ) - { - cmd = "./remote_scp_get.sh " + installParentModuleIPAddr + " " + password + " " + installDir + "/Calpont/etc/Calpont.xml " + systemUser + " " + debug_flag; - rtnCode = system(cmd.c_str()); - sleep(2); - if (rtnCode == 0) { - cmd = "mv Calpont.xml " + systemDir + "/."; - rtnCode = system(cmd.c_str()); - if ( rtnCode == 0 ) { - //Calpont.xml found - - //try to parse it - Config* sysConfigOld; - - ofstream file("/dev/null"); - - //save cout stream buffer - streambuf* strm_buffer = cerr.rdbuf(); - - try { - // redirect cout to /dev/null - cerr.rdbuf(file.rdbuf()); - - sysConfigOld = Config::makeConfig( systemDir + "/Calpont.xml"); - - // restore cout stream buffer - cerr.rdbuf (strm_buffer); - - //update release Calpont.xml with System Configuration info from system Calpont.xml - cout << "Run Calpont.xml autoConfigure " << flush; - cmd = "cd " + systemDir + ";../../autoConfigure"; - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << " FAILED, try Calpont.xml.rpmsave" << endl; - goto RPMSAVE; - } - else { - cout << "DONE" << endl; - configFile = "Calpont.xml.new"; - goto CONFIGDONE; - } - } - catch(...) - { -// cout << " FAILED to parse, try re-reading again" << endl; - // restore cout stream buffer - cerr.rdbuf (strm_buffer); - continue; - } - } - } - } - -RPMSAVE: - //try Calpont.xml.rpmsave - cout << "Get System Calpont.xml.rpmsave " << flush; - cmd = "./remote_scp_get.sh " + installParentModuleIPAddr + " " + password + " " + installDir + "/Calpont/etc/Calpont.xml.rpmsave " + systemUser + " " + debug_flag; - rtnCode = system(cmd.c_str()); - if (rtnCode == 0) { - cmd = "mv Calpont.xml.rpmsave " + systemDir + "/Calpont.xml"; - rtnCode = system(cmd.c_str()); - if ( rtnCode != 0 ) { - cout << "ERROR: No system Calpont.xml or Calpont.xml.rpmsave found, exiting" << endl; - cerr << "ERROR: No system Calpont.xml or Calpont.xml.rpmsave found, exiting" << endl; - exit(1); - } - } - - //update release Calpont.xml with System Configuration info from system Calpont.xml.rpmsave - cout << "Run Calpont.xml autoConfigure " << flush; - cmd = "cd " + systemDir + ";../../autoConfigure"; - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << " FAILED, exiting..." << endl; - cerr << " FAILED, exiting..." << endl; - exit(1); - } - else { - cout << "DONE" << endl; - configFile = "Calpont.xml.new"; - } - } - } - } - -CONFIGDONE: - - Config* sysConfigOld; - try { - sysConfigOld = Config::makeConfig( systemDir + "/Calpont.xml"); - } - catch(...) - { - cout << "ERROR: Problem reading Calpont.xml files, exiting" << endl; - cerr << "ERROR: Problem reading Calpont.xml files, exiting" << endl; - exit(1); - } - - //get Parent OAM Module Name of load being installed - string parentOAMModuleModuleName; - string parentOAMModuleIPAddr; - - try{ - parentOAMModuleModuleName = sysConfigOld->getConfig("SystemConfig", "ParentOAMModuleName"); - parentOAMModuleIPAddr = sysConfigOld->getConfig("ProcStatusControl", "IPAddr"); - } - catch(...) - { - cout << "ERROR: Problem updating the InfiniDB System Configuration file, exiting" << endl; - cerr << "ERROR: Problem updating the InfiniDB System Configuration file, exiting" << endl; - exit(1); - } - - if ( parentOAMModuleModuleName.empty() || parentOAMModuleIPAddr.empty() || - parentOAMModuleIPAddr == "127.0.0.1" || - parentOAMModuleIPAddr == "0.0.0.0" ) { - cout << " ERROR: ParentOAMModuleModuleName or ParentOAMModuleIPAddr are invalid in " << sysConfigOld->configFile() << ", exiting" << endl; - cerr << " ERROR: ParentOAMModuleModuleName or ParentOAMModuleIPAddr are invalid in " << sysConfigOld->configFile() << ", exiting" << endl; - exit(1); - } - - int serverTypeInstall; - try { - serverTypeInstall = atoi(sysConfigOld->getConfig("Installation", "ServerTypeInstall").c_str()); - } - catch(...) - { - cout << "ERROR: Problem reading serverTypeInstall from the InfiniDB System Configuration file, exiting" << endl; - cerr << "ERROR: Problem reading serverTypeInstall from the InfiniDB System Configuration file, exiting" << endl; - exit(1); - } - - bool HDFS = false; - string DBRootStorageType; - try { - DBRootStorageType = sysConfigOld->getConfig("Installation", "DBRootStorageType"); - } - catch(...) - { - cout << "ERROR: Problem reading DBRootStorageType from the InfiniDB System Configuration file, exiting" << endl; - cerr << "ERROR: Problem reading DBRootStorageType from the InfiniDB System Configuration file, exiting" << endl; - exit(1); - } - - string DataFileEnvFile = "setenv-hdfs-20"; - if ( DBRootStorageType == "hdfs" ) { - HDFS = true; - - try { - DataFileEnvFile = sysConfigOld->getConfig("Installation", "DataFileEnvFile"); - } - catch(...) - { - cout << "ERROR: Problem reading DataFileEnvFile from the InfiniDB System Configuration file, exiting" << endl; - cerr << "ERROR: Problem reading DataFileEnvFile from the InfiniDB System Configuration file, exiting" << endl; - exit(1); - } - } - - if ( serverTypeInstall != oam::INSTALL_COMBINE_DM_UM_PM && CE == "1") - { - cout << "Community-Edition only work on single-server systems, exiting" << endl; - cerr << "Community-Edition only work on single-server systems, exiting" << endl; - exit (0); - } - - pos = parentOAMModuleIPAddr.find("208",0); - if( pos != string::npos) { - string newIP = parentOAMModuleIPAddr.substr(0,pos) + "8" + parentOAMModuleIPAddr.substr(pos+3,80); - parentOAMModuleIPAddr = newIP; - } - - if ( parentOAMModuleIPAddr == "0.0.0.0" ) { - cout << "System Calpont.xml is un-configured, exiting" << endl; - cerr << "System Calpont.xml is un-configured, exiting" << endl; - exit (0); - } - - //set Version Key Flags - Config* sysConfigNew; - try { - sysConfigNew = Config::makeConfig( systemDir + "/" + configFile); - } - catch(...) - { - cout << "ERROR: Problem reading Calpont.xml files, exiting" << endl; - cerr << "ERROR: Problem reading Calpont.xml files, exiting" << endl; - exit(1); - } - - try{ - sysConfigNew->setConfig("SystemConfig", "Flags", "75635259"); - sysConfigNew->write(); - } - catch(...) - {} - - //set EE package Type to 'binary', if needed - if ( systemPackage == "*.x86_64.rpm" ) - { - try{ - sysConfigNew->setConfig("Installation", "EEPackageType", "rpm"); - sysConfigNew->write(); - } - catch(...) - {} - } - else - { - try{ - sysConfigNew->setConfig("Installation", "EEPackageType", "binary"); - sysConfigNew->write(); - } - catch(...) - {} - } - - cout << "Shutdown System " << flush; - - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + password + " '" + installDir + "/Calpont/bin/calpontConsole shutdownsystem Force y' 'Successful shutdown' Error 60 " + debug_flag; - rtnCode = system(cmd.c_str()); - if (rtnCode == 0) - cout << "DONE" << endl; - - // run calpontUninstaller script - cout << "Run calpontUninstall script " << flush; - - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + password + " '" + installDir + "/Calpont/bin/calpontUninstall.sh -d -p " + password + "' 'Uninstall Completed' FAILED 500 " + debug_flag; - rtnCode = system(cmd.c_str()); - if (rtnCode == 0) - cout << "DONE" << endl; - - // Copy the Packages and Configuration files down to Parent OAM Module - string installer; - if ( systemPackage != "*.x86_64.rpm" ) - { //do binary install - if (idbver >= 4) - installer = "parent_binary_installer.sh"; - else - installer = "parent_binary_installer_v3.sh"; - cmd = "cd " + systemDir + ";../../" + installer + " " + installParentModuleIPAddr + " " + - password + " " + systemPackage + " " + release + " " + configFile + " " + systemUser + " " + - installDir + " " + debug_flag; - } - else - { - if ( serverTypeInstall == oam::INSTALL_COMBINE_DM_UM_PM ) - { - if (idbver >= 4) - installer = "dm_parent_installer.sh"; - else - installer = "dm_parent_installer_v3.sh"; - cmd = "cd " + systemDir + ";../../" + installer + " " + installParentModuleIPAddr + " " + - password + " " + systemPackage + " " + release + " " + configFile + " " + systemUser + " " + CE + " " + debug_flag; - } - else - { - if (idbver >= 4) - installer = "pm_parent_installer.sh"; - else - installer = "pm_parent_installer_v3.sh"; - cmd = "cd " + systemDir + ";../../" + installer + " " + installParentModuleIPAddr + " " + - password + " " + systemPackage + " " + release + " " + configFile + " " + currentPrefix + " " + - systemUser + " " + debug_flag; - } - } - - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << endl << "Installation Failed, exiting" << endl; - cerr << endl << "Installation Failed, exiting" << endl; - exit(1); - } - - // - // Perform System Installing and launch - // - cout << "Install System " << flush; - if (idbver < 3) - { - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + " " + password + " '/usr/local/Calpont/bin/installer /root/" + calpontPackage + " /root/" + mysqlRPM + " /root/" + mysqldRPM + " initial " + password + " " + XMpassword + " --nodeps " + MySQLpassword + " 1' 'InfiniDB Install Successfully Completed' ERROR 1200 " + debug_flag; - } - else - { - if (HDFS) - { - if ( MySQLport == oam::UnassignedName ) - { - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + password + " '. " + installDir + "/Calpont/bin/" + DataFileEnvFile + ";" + installDir + "/Calpont/bin/postConfigure -i " + installDir + "/Calpont -n -mp " + MySQLpassword + " -p " + password + "' 'System is Active' Error 1200 " + debug_flag; - } - else - { - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + password + " '. " + installDir + "/Calpont/bin/" + DataFileEnvFile + ";" + installDir + "/Calpont/bin/postConfigure -i " + installDir + "/Calpont -n -mp " + MySQLpassword + " -p " + password + " -port " + MySQLport + "' 'System is Active' Error 1200 " + debug_flag; - } - } - else - { - if ( MySQLport == oam::UnassignedName ) - { - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + password + " '" + installDir + "/Calpont/bin/postConfigure -i " + installDir + "/Calpont -n -mp " + MySQLpassword + " -p " + password + "' 'System is Active' Error 1200 " + debug_flag; - } - else - { - cmd = "./remote_command.sh " + installParentModuleIPAddr + " " + systemUser + " " + password + " '" + installDir + "/Calpont/bin/postConfigure -i " + installDir + "/Calpont -n -mp " + MySQLpassword + " -p " + password + " -port " + MySQLport + "' 'System is Active' Error 1200 " + debug_flag; - string DataFileEnvFile = "setenv-hdfs-20"; - } - } - } - - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << "Installation Failed, exiting" << endl; - cerr << "Installation Failed, exiting" << endl; - exit(1); - } - else - cout << "DONE" << endl; - - //needs to be cerr so buildTester will see it.. - cout << endl << "Install Successfully completed" << endl; - cerr << endl << "Install Successfully completed" << endl; -} -// vim:ts=4 sw=4: - diff --git a/tools/configMgt/autoPackager b/tools/configMgt/autoPackager deleted file mode 100644 index a1682281..00000000 --- a/tools/configMgt/autoPackager +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/expect -# -# $Id: autoPackager.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -set USERNAME root -set PASSWORD Calpont1 -set RELEASE "" -set PKGSERVER srvdeb5 -set OLD "n" -log_user 0 - -spawn -noecho /bin/bash - -for {set i 0} {$i<[llength $argv]} {incr i} { - set arg($i) [lindex $argv $i] -} - -set i 0 -while true { - if { $i == [llength $argv] } { break } - if { $arg($i) == "-h" } { - send_user "\n" - send_user "'autoPackager' generates a packages based on the set of RPMs\n" - send_user "in the calweb/iterations branch.\n" - send_user "It will place the packages in //calweb/shared/Iterations/Latest/packages\n" - send_user "and in //calweb/shared/Iterations/'release'/packages when specified\n" - send_user "\n" - send_user "Usage: autoPackage -r 'release' -o\n" - send_user " release - Calpont release number\n" - send_user " -o - Build Old Calpont Packages\n" - exit - } - if { $arg($i) == "-r" } { - incr i - set RELEASE $arg($i) - } - if { $arg($i) == "-o" } { - set OLD "y" - } - incr i -} - -if { $RELEASE == "" } { - send_user "\nError: provide a release number with -r option\n" - exit 1 -} - -set PKGCOMMAND "'/root/autoOAM/buildCalpontPackages.sh $RELEASE'" -if { $OLD == "n"} { - set PKGCOMMAND "'/root/autoOAM/buildInfiniDBPackages.sh $RELEASE'" -} - -set timeout 3700 -# -# send command to build calpont rpms -# -#get current date -exec date >/tmp/datesync.tmp -exec cat /tmp/datesync.tmp -set newtime [exec cat /tmp/datesync.tmp] - -send_user "\nStart Time: $newtime\n" - -log_user 1 - -set timeout 900 -# -# send command to build calpont packages -# -if { $OLD == "n"} { - send_user "\nGenerating 4.x INFINIDB Packages takes 15 minutes to complete, please wait...\n" -} else { - send_user "\nGenerating 3.x CALPONT Packages takes 15 minutes to complete, please wait...\n" -} - -log_user 0 - -send "ssh $USERNAME@$PKGSERVER $PKGCOMMAND\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "Connection refused" { send_user "FAILED: Connection refused\n" ; exit -1 } - - -re "word: " { send "$PASSWORD\n" } abort -} -log_user 1 -expect { - -re "TIMEOUT" { send_user "Calpont Packages Build Failed, timeout" } abort - timeout { send_user "Calpont Packages Build Failed, timeout" } abort - -re "No such file" { send_user "$COMMAND file not found" } abort - -re "no rpm" { send_user "Calpont Packages Build Failed, check build log files" } abort - -re "Calpont Packages Build Successfully Completed" { send_user "Calpont Packages Successfully Completed" } abort -} - -#get current date -exec date >/tmp/datesync.tmp -exec cat /tmp/datesync.tmp -set newtime [exec cat /tmp/datesync.tmp] - -send_user " $newtime\n" - -file delete -force $RELEASE -send_user "\nBuild-Packaging successfully completed\n" -exit 0 diff --git a/tools/configMgt/autoReleaseNotes.sh b/tools/configMgt/autoReleaseNotes.sh deleted file mode 100755 index 07e3afe8..00000000 --- a/tools/configMgt/autoReleaseNotes.sh +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/expect -# -# $Id: autoReleaseNotes.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - release -# Argument 2 - date since last release (for BUG generation) in "2008-06-02 00:00:00" format -# Argument 3 - debug flag -set timeout 1800 -set SERVER srvengcm1 -set USERNAME root -set PASSWORD Calpont1 -set RELEASE [lindex $argv 0] -set DATE [lindex $argv 1] -set DEBUG [lindex $argv 2] -set COMMAND "'/home/bugzilla/resolve_bug_report $RELEASE $DATE'" - -#set SHARED "//cal6500/shared" -set SHARED "//calweb/shared" - -log_user $DEBUG -spawn -noecho /bin/bash -if { $RELEASE == "-h" } { - send_user "\n" - send_user "'autoReleaseNotes.sh' generates bug reports for release notes\n" - send_user "\n" - send_user "Usage: autoReleaseNotes.sh 'release' 'date'\n" - send_user " release - Calpont release number (optional)\n" - send_user " date - date since last build ('2008-06-02 00:00:00' format)\n" - exit -} -# -# send command -# -send "ssh $USERNAME@$SERVER $COMMAND\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "Generate Resolved Bug Report Successfully Completed" { send_user "Successfully completed BUG Report and placed on //cal6500/shared/Iterations/\n" } abort -} - -exec echo -e "\n##### Subsystem: build \n" > svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/build/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: dbcon \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/dbcon/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: dmlib \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/dmlib/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: exemgr \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/exemgr/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: oam \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/oam/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: oamapps \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/oamapps/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: primitives \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/primitives/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: procmgr \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/procmgr/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: procmon \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/procmon/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: snmpd \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/snmpd/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: tools \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/tools/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: utils \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/utils/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: versioning \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/versioning/trunk >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: writeengine \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/writeengine/trunk >> svn_release_notes.txt - -exec smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations;cd $RELEASE;put svn_release_notes.txt" - -send_user "Successfully completed SVN Reports and placed on //cal6500/shared/Iterations/\n" -exit \ No newline at end of file diff --git a/tools/configMgt/autoReleaseNotes_branch.sh b/tools/configMgt/autoReleaseNotes_branch.sh deleted file mode 100644 index f4f527d1..00000000 --- a/tools/configMgt/autoReleaseNotes_branch.sh +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/expect -# -# $Id: autoReleaseNotes.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - release -# Argument 2 - date since last release (for BUG generation) in "2008-06-02 00:00:00" format -# Argument 3 - debug flag -set timeout 1800 -set SERVER srvengcm1 -set USERNAME root -set PASSWORD Calpont1 -set RELEASE [lindex $argv 0] -set DATE [lindex $argv 1] -set BRANCH [lindex $argv 2] -set DEBUG [lindex $argv 3] -set COMMAND "'/home/bugzilla/resolve_bug_report $RELEASE $DATE'" - -#set SHARED "//cal6500/shared" -set SHARED "//calweb/shared" - -log_user $DEBUG -spawn -noecho /bin/bash -if { $RELEASE == "-h" } { - send_user "\n" - send_user "'autoReleaseNotes.sh' generates bug reports for release notes\n" - send_user "\n" - send_user "Usage: autoReleaseNotes.sh 'release' 'date' 'svn-branch'\n" - send_user " release - Calpont release number\n" - send_user " date - date since last build ('2008-06-02 00:00:00' format)\n" - send_user " svn-branch - svn branch\n" - exit -} - -if { $RELEASE == " " && $DATE != " " && $BRANCH != " "} {puts "enter 'release' 'date' 'svn-branch, enter -h for additional info"; exit -1} - -# -# send command -# -send "ssh $USERNAME@$SERVER $COMMAND\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "Generate Resolved Bug Report Successfully Completed" { send_user "Successfully completed BUG Report and placed on //cal6500/shared/Iterations/\n" } abort -} - -exec echo -e "\n##### Subsystem: build \n" > svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/build/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: dbcon \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/dbcon/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: ddlproc \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/ddlproc/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: dmlib \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/dmlib/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: dmlproc \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/dmlproc/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: exemgr \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/exemgr/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: oam \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/oam/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: oamapps \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/oamapps/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: primitives \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/primitives/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: procmgr \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/procmgr/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: procmon \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/procmon/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: snmpd \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/snmpd/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: tools \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/tools/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: utils \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/utils/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: versioning \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/versioning/branches/$BRANCH >> svn_release_notes.txt -exec echo -e "\n##### Subsystem: writeengine \n" >> svn_release_notes.txt -exec svn log -r "{$DATE}:HEAD" http://srvengcm1.calpont.com/svn/genii/writeengine/branches/$BRANCH >> svn_release_notes.txt - -exec smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations;cd $RELEASE;put svn_release_notes.txt" - -send_user "Successfully completed SVN Reports and placed on //cal6500/shared/Iterations/\n" -exit diff --git a/tools/configMgt/beetlejuice_installer.sh b/tools/configMgt/beetlejuice_installer.sh deleted file mode 100755 index 64c5e4d8..00000000 --- a/tools/configMgt/beetlejuice_installer.sh +++ /dev/null @@ -1,219 +0,0 @@ -#!/usr/bin/expect -# -# $Id: beetlejuice_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Beetlejuice Installer -# Argument 0 - Server IP address -# Argument 1 - Root Password -# Argument 2 - Debug flag 1 for on, 0 for off - -set timeout 30 -set USERNAME root -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set DEBUG [lindex $argv 4] -log_user $DEBUG -spawn -noecho /bin/bash -# -# get the package -# -send_user "Get Calpont Package " -send "rm -f $PACKAGE\n" -#expect -re "#" -send "smbclient //cal6500/shared -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found in //cal6500/shared/Iterations/$RELEASE/\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the DM package -# -expect -re "#" -send_user "Copy Calpont Package " -send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.rpm'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect -re "#" -send "scp $PACKAGE $USERNAME@$SERVER:/root/.\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send "rm -f $PACKAGE\n" -# -# backup custom os files -# -send_user "\n" -expect -re "#" -send_user "Backup Custom OS Files " -send "ssh $USERNAME@$SERVER 'rm -f /etc/*.calpont;cp /etc/inittab /etc/inittab.calpont;cp /etc/syslog.conf /etc/syslog.conf.calpont'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort - -re "cp" { send_user "FAILED" ; exit -1 } -} -send_user "\n" -# -# unmount disk -# -expect -re "#" -send_user "Unmount disk " -send "ssh $USERNAME@$SERVER 'umount -a'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort -} -send_user "\n" -# -# erase package -# -expect -re "#" -send_user "Erase Old Calpont-oracle Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps calpont-oracle'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "#" { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -send_user "Erase Old Calpont-Mysql Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps calpont-mysql'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "#" { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -send_user "Erase Old Calpont Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps calpont'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "#" { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -# -# install package -# -expect -re "#" -set timeout 120 -send_user "Install New Calpont Package " -send "ssh $USERNAME@$SERVER ' rpm -ivh /root/$PACKAGE'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -# -# Restore custom os files -# -set timeout 30 -expect -re "#" -send_user "Restore Custom OS Files " -send "ssh $USERNAME@$SERVER 'mv -f /etc/inittab.calpont /etc/inittab;mv -f /etc/syslog.conf.calpont /etc/syslog.conf'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort - -re "mv: cannot" { send_user "FAILED" ; exit -1 } -} -send_user "\n" -# -# mount disk -# -expect -re "#" -send_user "Mount disk " -send "ssh $USERNAME@$SERVER 'mount -a'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort -} -send_user "\n" -# -# restart syslog -# -expect -re "#" -send_user "Restart syslog service " -send "ssh $USERNAME@$SERVER 'service syslog restart'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "Starting kernel logger" { send_user "DONE" } abort - -re "service " { send_user "WARNING: service not available" } abort -} -send_user "\n" -# -# startup ProcMons -# -expect -re "#" -send_user "Startup ProcMon's " -send "ssh $USERNAME@$SERVER 'kill -HUP 1'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort -} -send_user "\n" -# -exit - diff --git a/tools/configMgt/beetlejuice_installer_3rpms.sh b/tools/configMgt/beetlejuice_installer_3rpms.sh deleted file mode 100755 index 42adf26f..00000000 --- a/tools/configMgt/beetlejuice_installer_3rpms.sh +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/expect -# -# $Id: beetlejuice_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Beetlejuice Installer -# Argument 0 - Server IP address -# Argument 1 - Root Password -# Argument 2 - Debug flag 1 for on, 0 for off - -set timeout 30 -set USERNAME root -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set SYSTEMRPM [lindex $argv 2] -set CALPONTRPMNAME [lindex $argv 3] -set CONNECTORRPM1NAME [lindex $argv 4] -set CONNECTORRPM2NAME [lindex $argv 5] -set RELEASE [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTRPM $CALPONTRPMNAME"-1"$SYSTEMRPM -set CONNECTORRPM1 $CONNECTORRPM1NAME"-1"$SYSTEMRPM -set CONNECTORRPM2 $CONNECTORRPM2NAME"-1"$SYSTEMRPM -#set SHARED "//cal6500/shared" -set SHARED "//calweb/shared" - -log_user $DEBUG - -spawn -noecho /bin/bash -# -# get the package -# -send_user "Get Calpont Packages " -send "rm -f $SYSTEMRPM\n" -#expect -re "#" -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $SYSTEMRPM'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $SYSTEMRPM not found in $SHARED/Iterations/$RELEASE/\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the DM Package -# -expect -re "#" -send_user "Copy Calpont Packages " -send "ssh $USERNAME@$SERVER 'rm -f /root/$SYSTEMRPM'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect -re "#" -send "scp $SYSTEMRPM $USERNAME@$SERVER:/root/.\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid Package\n" ; exit -1 } -} -send "rm -f $SYSTEMRPM\n" -# -# backup custom os files -# -send_user "\n" -expect -re "#" -send_user "Backup Custom OS Files " -send "ssh $USERNAME@$SERVER 'rm -f /etc/*.calpont;cp /etc/inittab /etc/inittab.calpont;cp /etc/syslog.conf /etc/syslog.conf.calpont'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort - -re "cp" { send_user "FAILED" ; exit -1 } -} -send_user "\n" -# -# unmount disk -# -expect -re "#" -send_user "Unmount disk " -send "ssh $USERNAME@$SERVER 'umount -a'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort -} -send_user "\n" -# -# erase Package -# -expect -re "#" -send_user "Erase Old $CONNECTORRPM1NAME Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps $CONNECTORRPM1NAME'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "#" { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -send_user "Erase Old $CONNECTORRPM2NAME Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps $CONNECTORRPM2NAME'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "#" { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -send_user "Erase Old $CALPONTRPMNAME Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps $CALPONTRPMNAME'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "#" { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -# -# install Package -# -expect -re "#" -set timeout 120 -send_user "Install New $CALPONTRPMNAME Package " -send "ssh $USERNAME@$SERVER ' rpm -ivh /root/$CALPONTRPM'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -send_user "Install New $CONNECTORRPM1NAME Package " -send "ssh $USERNAME@$SERVER ' rpm -ivh /root/$CONNECTORRPM1'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -expect -re "#" -send_user "Install New $CONNECTORRPM2NAME Package " -send "ssh $USERNAME@$SERVER ' rpm -ivh /root/$CONNECTORRPM2'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -# -# Restore custom os files -# -set timeout 30 -expect -re "#" -send_user "Restore Custom OS Files " -send "ssh $USERNAME@$SERVER 'mv -f /etc/inittab.calpont /etc/inittab;mv -f /etc/syslog.conf.calpont /etc/syslog.conf'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort - -re "mv: cannot" { send_user "FAILED" ; exit -1 } -} -send_user "\n" -# -# mount disk -# -expect -re "#" -send_user "Mount disk " -send "ssh $USERNAME@$SERVER 'mount -a'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort -} -send_user "\n" -# -# restart syslog -# -expect -re "#" -send_user "Restart syslog service " -send "ssh $USERNAME@$SERVER 'service syslog restart'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "Starting kernel logger" { send_user "DONE" } abort - -re "service " { send_user "WARNING: service not available" } abort -} -send_user "\n" -# -# startup ProcMons -# -expect -re "#" -send_user "Startup ProcMon's " -send "ssh $USERNAME@$SERVER 'kill -HUP 1'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "#" { send_user "DONE" } abort -} -send_user "\n" -# -exit - diff --git a/tools/configMgt/buildCalpontPackages.sh b/tools/configMgt/buildCalpontPackages.sh deleted file mode 100755 index 921576fa..00000000 --- a/tools/configMgt/buildCalpontPackages.sh +++ /dev/null @@ -1,48 +0,0 @@ -#! /bin/sh -# -# $1 - release number or 'Latest' (default 'Latest') -# -if [ "$1" = "" ] ; then - DIR=Latest - REL="3.6-0" -elif [ "$1" = "Latest" ] ; then - DIR=Latest - REL="3.6-0" -elif [ "$2" = "" ] ; then - DIR=$1 - REL=$1 -else - DIR=$1 - REL=$2 -fi -# -if [[ $REL != *-* ]] ; then - REL=$REL"-0" -fi -# -{ -cd /root/autoOAM/ -rpm -e infinidb-libs infinidb-platform infinidb-enterprise --nodeps -rpm -e infinidb-storage-engine infinidb-mysql --nodeps -rpm -e infinidb-mysql --nodeps -rm -rf /usr/local/Calpont -rm -rf calpont* -rm -f *gz -# -smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/$DIR;prompt OFF;mget *.rpm" -rpm -ivh calpont*.x86_64.rpm --nodeps -rpm -iq calpont >> /usr/local/Calpont/releasenum -cd /usr/local/ -tar -zcvf calpont-infinidb-ent-$REL.x86_64.bin.tar.gz Calpont -mv calpont-infinidb-ent-$REL.x86_64.bin.tar.gz /root/autoOAM/ -cd /root/autoOAM/ -alien -ck calpont*.x86_64.rpm -tar -zcvf calpont-infinidb-ent-$REL.x86_64.rpm.tar.gz *$REL*.rpm -tar -zcvf calpont-infinidb-ent-$REL.amd64.deb.tar.gz *$REL*.deb - -smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/$DIR;mkdir packages;cd packages;prompt OFF;del calpont-infinidb-ent*gz;mput *gz" -} > /root/autoOAM/buildCalpontPackages-$DIR.log 2>&1 -# -echo "Calpont Packages Build Successfully Completed" -exit 0 - diff --git a/tools/configMgt/buildDatdupPackages.sh b/tools/configMgt/buildDatdupPackages.sh deleted file mode 100755 index 3831232a..00000000 --- a/tools/configMgt/buildDatdupPackages.sh +++ /dev/null @@ -1,47 +0,0 @@ -#! /bin/sh -# -# $1 - release number or 'Latest' (default 'Latest') -if [ "$1" = "" ] ; then - DIR=Latest - REL="3.6-0" -elif [ "$1" = "Latest" ] ; then - DIR=Latest - REL="3.6-0" -elif [ "$2" = "" ] ; then - DIR=$1 - REL=$1 -else - DIR=$1 - REL=$2 -fi -# -if [[ $REL != *-* ]] ; then - REL=$REL"-0" -fi -# -{ -cd /root/autoOAM/ -rpm -e infinidb-libs infinidb-platform infinidb-enterprise --nodeps --allmatches -rpm -e infinidb-storage-engine infinidb-mysql --nodeps --allmatches -rpm -e infinidb-mysql --nodeps --allmatches -rpm -e infinidb-datdup --nodeps --allmatches -rm -rf /usr/local/Calpont -rm -rf infinidb* -rm -f *gz -# -smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/$DIR/packages;prompt OFF;mget infinidb-datdup*.rpm" -# -test -f infinidb-datdup*.rpm || echo "infinidb-datdup rpm" -test -f infinidb-datdup*.rpm || exit -1 -# -rpm -ivh infinidb-datdup*.x86_64.rpm --nodeps -cd /usr/local/ -tar -zcvf infinidb-datdup-$REL.x86_64.bin.tar.gz Calpont -mv infinidb-datdup-$REL.x86_64.bin.tar.gz /root/autoOAM/ -cd /root/autoOAM/ -smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/$DIR/packages;prompt OFF;del infinidb-datdup*gz;mput *gz" -} > /root/autoOAM/buildDatdupPackages-$DIR.log 2>&1 -# -echo "DatDup Package Build Successfully Completed" -exit 0 - diff --git a/tools/configMgt/buildTester.sh b/tools/configMgt/buildTester.sh deleted file mode 100755 index 5af5bf43..00000000 --- a/tools/configMgt/buildTester.sh +++ /dev/null @@ -1,475 +0,0 @@ -#!/usr/bin/expect -# -# $Id: buildTester.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Build, install, and test Calpont Builds -# -set EMAIL " " -set USERNAME root -set PASSWORD Calpont1 -set BUILD " " -set SVN genii -set RELEASE " " -set SYSTEM noSystem -set USER " " -set DEBUG "-k" -set TEST(0) " " -set SERVER srvswdev11 - -#set SHARED "//cal6500/shared" -set SHARED "//calweb/shared" - -spawn -noecho /bin/bash - -for {set i 0} {$i<[llength $argv]} {incr i} { - set arg($i) [lindex $argv $i] -} - -set i 0 -while true { - if { $i == [llength $argv] } { break } - if { $arg($i) == "-h" } { - send_user "\n" - send_user "'buildTester' executes a set of DVM test on a specifed system and\n" - send_user "send the results via email or outputs results to a log file.\n" - send_user "It has the option of installing a released\n" - send_user "build or generating a new build when release of 'Latest' is specified\n" - send_user "and installing that build on the specified system.\n" - send_user "\n" - send_user "Usage: buildTester -b 'build-type' -r 'release' -v 'svn-branch' -s 'system' -sv 'server' -u 'database-user' -p 'password' -d -e -t 'test-names'\n" - send_user " build-type - optional: RHEL5 or FC6\n" - send_user " release - Required when build-type is entered: Calpont release number or 'Latest'\n" - send_user " svn-branch - SVN Branch built againest, default to genii\n" - send_user " system - Target install/test system\n" - send_user " server - Target query server hostname\n" - send_user " database-user - Database User, i.e. tpch1\n" - send_user " password - system password, default to 'qcalpont!'\n" - send_user " -d - Debug mode, will output additional install and test data\n" - send_user " -e - email results\n" - send_user " test-names - Test name list seperated by spaces (sanity tpch)\n" - exit - } - if { $arg($i) == "-b" } { - incr i - set BUILD $arg($i) - } elseif { $arg($i) == "-r" } { - incr i - set RELEASE $arg($i) - } elseif { $arg($i) == "-s" } { - incr i - set SYSTEM $arg($i) - } elseif { $arg($i) == "-v" } { - incr i - set SVN $arg($i) - } elseif { $arg($i) == "-u" } { - incr i - set USER $arg($i) - } elseif { $arg($i) == "-p" } { - incr i - set PASSWORD $arg($i) - } elseif { $arg($i) == "-t" } { - incr i - if { $i == [llength $argv] } { - puts "no Test Name entered, enter ./buildTester.sh -h for additional info"; exit -1 - } - set TESTNUMBER 0 - while true { - set TEST($TESTNUMBER) $arg($i) - incr i - incr TESTNUMBER - if { $i == [llength $argv] } { - incr i -1 - break - } - } - } elseif { $arg($i) == "-e" } { - if { $SYSTEM == "qaftest2" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,dcathey@calpont.com,bpaul@calpont.com - } elseif { $SYSTEM == "qaftest2" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,dcathey@calpont.com,bpaul@calpont.com - } elseif { $SYSTEM == "caldev02" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,pleblanc@calpont.com,chao@calpont.com,xlou@calpont.com,dcathey@calpont.com - } elseif { $SYSTEM == "srvswdev11" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,pleblanc@calpont.com,chao@calpont.com,xlou@calpont.com,dcathey@calpont.com - } elseif { $SYSTEM == "devint2" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,pleblanc@calpont.com - } elseif { $SYSTEM == "devint3" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,pleblanc@calpont.com - } elseif { $SYSTEM == "ss2" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,pleblanc@calpont.com,chao@calpont.com,dcathey@calpont.com - } elseif { $SYSTEM == "ss2ImportSSB100" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,dcathey@calpont.com,pleblanc@calpont.com - } elseif { $SYSTEM == "demo01" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,pleblanc@calpont.com,chao@calpont.com - } elseif { $SYSTEM == "qperfd01" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,bpaul@calpont.com,dcathey@calpont.com,pleblanc@calpont.com - } elseif { $SYSTEM == "qperfd01" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,bpaul@calpont.com,dcathey@calpont.com - } elseif { $SYSTEM == "qcald02a" } { - set EMAIL dhill@calpont.com,wweeks@calpont.com,mroberts@calpont.com - } else { - set EMAIL dhill@calpont.com,wweeks@calpont.com - } - } elseif { $arg($i) == "-d" } { - set DEBUG " " - } elseif { $arg($i) == "-sv" } { - incr i - set SERVER $arg($i) - } - incr i -} - -if { $SYSTEM == "noSystem" } { - set SYSTEM $BUILD -} - -#cleanup -set RUN_LOG_FILE /tmp/$SYSTEM-$SVN.log -exec rm -f /tmp/test.log $RUN_LOG_FILE -# open log file -log_file $RUN_LOG_FILE - -#get current date -exec date >/tmp/datesync.tmp -exec cat /tmp/datesync.tmp -set newtime [exec cat /tmp/datesync.tmp] -# -send_user "\n\n#####################################################################################################\n" -send_user " Automated Build Tester Report $newtime\n" -send_user " BUILD=$BUILD RELEASE=$RELEASE SVN-BRANCH=$SVN SYSTEM=$SYSTEM\n" -send_user "\n#####################################################################################################\n\n" -# build request -log_user 1 -set timeout 30 -if { $BUILD != " " } { - set timeout 6060 - - send_user "******************* Generate Build $BUILD / $RELEASE ****************************\n\n" - - log_user 0 - send "./autoBuilder -o $BUILD -r $RELEASE -s $SVN\n" - log_user 1 - expect { - -re "Calpont RPM Build successfully completed" { } abort - -re "Build Failed" { send_user "\nBuild Failed\n" ; puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - } - #get current date - exec date >/tmp/datesync.tmp - exec cat /tmp/datesync.tmp - set newtime [exec cat /tmp/datesync.tmp] - - send_user "\nBuild successfully completed $newtime\n\n" -} -set timeout 30 -#expect -re "#" -if { $DEBUG == " " } { - log_user 1 -} else { - log_user 0 -} -if { $SYSTEM != $BUILD } { - set timeout 1500 - if { $RELEASE != " " } { - # install request - send_user "\n\n******************* Install Build $RELEASE on $SYSTEM *******************************\n\n" - send "./autoInstaller -s $SYSTEM -r $RELEASE -n -d\n" - expect { - -re "Install Successfully completed" { send_user "\nInstall successfully completed\n\n" } abort - -re "Installation Failed" { send_user "\nInstallation Failed\n\n" - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - timeout { send_user "\nInstallation Failed - Timeout error\n\n" - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - - } - } -} -#get install RPM info -#log_user 1 -#send_user "\n\n******************* Calpont RPM Install Information *******************************\n\n" -#exec ./remote_command_test.sh $SERVER $PASSWORD "rpm -iq calpont | grep Version -A 2" " " "No such file" 60 1 -#exec ./remote_command.sh $SERVER $PASSWORD 'rpm -iq calpont' tools not 30 1 -#expect { -# -re " " { abort } -# -re "FAILED" { -# puts "\nCalpont RPM not installed\n"; -# exec echo "Test Failed, Calpont RPM not installed" >> $RUN_LOG_FILE -# puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 -# } -#} -set timeout 30 - -if { $TEST(0) != " " } { - set timeout 600 - set t 0 - while true { - if { $t == $TESTNUMBER } { - break - } - set TESTCASE $TEST($t) - incr t - - #get current date - exec date >/tmp/datesync.tmp - exec cat /tmp/datesync.tmp - set newtime [exec cat /tmp/datesync.tmp] - - log_user 1 - send_user "\n\n******************* Run Test $TESTCASE start at $newtime **********************************\n\n" - #log_user 0 - - set TESTTYPE [exec expr substr $TESTCASE 1 5] - if { $TESTTYPE == "mysql" } { - set TESTCOMMAND [exec expr substr $TESTCASE 7 80] - } else { - # Oracle test case - set TESTCOMMAND [exec expr substr $TESTCASE 8 80] - } - - if { $TESTTYPE == "oracl" } { - if { [catch { open "/usr/local/lib/python2.4/site-packages/dvm_app/$USER\_$SYSTEM\_brefd01.cfg" "r"} handle ] } { - exec echo "\nTest Failed, DVM config file $USER\_$SYSTEM\_brefd01.cfg not found\n"; - exec echo "Test Failed, DVM config file $USER\_$SYSTEM\_brefd01.cfg not found" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 - } - - if { $TESTCOMMAND == "tpch" } { - exec su - oracle -c "python /usr/local/lib/python2.4/site-packages/dvm_app/dvm.py -c /usr/local/lib/python2.4/site-packages/dvm_app/$USER\\_$SYSTEM\_brefd01.cfg -e1 -sS -rB $DEBUG -l2 -t Perf_Tpch > /tmp/test.log " - expect { - -re "Traceback" { - exec echo "\nTest Failed, Database instance is down\n"; - exec echo "Test Failed, Database instance is down" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - -re "$" { if { [catch { open "/tmp/test.log" "r"} handle ] } { - exec echo "\nTest Failed, /tmp/test.log not found\n"; - exec echo "Test Failed, /tmp/test.log not found" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - } - } - exec cat /tmp/test.log >> $RUN_LOG_FILE - } else { - if { $TESTCOMMAND == "dml" } { - exec su - oracle -c "python /usr/local/lib/python2.4/site-packages/dvm_app/dvm.py -c /usr/local/lib/python2.4/site-packages/dvm_app/$USER\\_$SYSTEM\_brefd01.cfg -sS -rB -l2 -t Iter16_TableNameLengths $DEBUG > /tmp/test.log " - expect { - -re "Traceback" { - exec echo "\nTest Failed, Database instance is down\n"; - exec echo "Test Failed, Database instance is down" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - -re "$" { if { [catch { open "/tmp/test.log" "r"} handle ] } { - exec echo "\nTest Failed, /tmp/test.log not found\n"; - exec echo "Test Failed, /tmp/test.log not found" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - } - } - exec cat /tmp/test.log >> $RUN_LOG_FILE - - exec su - oracle -c "python /usr/local/lib/python2.4/site-packages/dvm_app/dvm.py -c /usr/local/lib/python2.4/site-packages/dvm_app/$USER\\_$SYSTEM\_brefd01.cfg -sS -rB -l2 -t Iter16_Datatypes_Ext $DEBUG > /tmp/test.log " - expect { - -re "Traceback" { - exec echo "\nTest Failed, Database instance is down\n"; - exec echo "Test Failed, Database instance is down" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - -re "$" { if { [catch { open "/tmp/test.log" "r"} handle ] } { - exec echo "\nTest Failed, /tmp/test.log not found\n"; - exec echo "Test Failed, /tmp/test.log not found" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - } - } - exec cat /tmp/test.log >> $RUN_LOG_FILE - } else { - # default to a test-command of a file name - exec su - oracle -c "python /usr/local/lib/python2.4/site-packages/dvm_app/dvm.py -c /usr/local/lib/python2.4/site-packages/dvm_app/$USER\\_$SYSTEM\_brefd01.cfg -e2 -sS -rT $DEBUG -t /home/qa/bldqry/$TESTCOMMAND.txt -q /home/qa/bldqry > /tmp/test.log " - expect { - -re "Traceback" { - exec echo "\nTest Failed, Database instance is down\n"; - exec echo "Test Failed, Database instance is down" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - -re "$" { if { [catch { open "/tmp/test.log" "r"} handle ] } { - exec echo "\nTest Failed, /tmp/test.log not found\n"; - exec echo "Test Failed, /tmp/test.log not found" >> $RUN_LOG_FILE - puts [exec mail -s "$SYSTEM/$SVN Automated Build Tester Results" $EMAIL < $RUN_LOG_FILE] ; exit -1 } - } - } - exec cat /tmp/test.log >> $RUN_LOG_FILE - } - } - } else { # run mysql test commands - if { $TESTTYPE == "mysql" } { - if { $TESTCOMMAND == "query" } { - set timeout 72000 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "./nightly/runQueryTestAll $SVN" "runQueryTestAll completed" "No such file" $timeout - expect { - -re "FAILED" { exec echo "\nFailed to run runQueryTestAll\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run runQueryTestAll\n" >> $RUN_LOG_FILE} abort; - -re " " { exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/nightly/srvswdev11/go.log" - exec cat go.log >> $RUN_LOG_FILE - exec rm -f go.log - } abort; - } - } elseif { $TESTCOMMAND == "querySSB" } { - set timeout 1200 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "./nightly/startQueryTesterSSB $SVN" "startQueryTester completed" "No such file" 1200 - expect { - -re " " { exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/queryTesterSSB.report" - exec cat queryTesterSSB.report >> $RUN_LOG_FILE - exec rm -f queryTesterSSB.report - } abort; - -re "FAILED" { exec echo "\nFailed to run queryTester\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run queryTester\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "concur" } { - set timeout 600 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "/root/nightly/startConcurTester 32" "Success" "Failed" 600 - expect { - -re " " { exec echo "Concurrance Test Passed\n\n" >> $RUN_LOG_FILE} abort; - -re "FAILED" { exec echo "\nConcurrance Test Failed\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nConcurrance Test Timeout\n" >> $RUN_LOG_FILE} abort; - timeout { exec echo "\nConcurrance Test Timeout\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "continueousConcur" } { - set timeout 30 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "/root/nightly/continueousConcurTester" "Started" "Failed" 30 - expect { - -re " " { exec echo "Continueous Concurrance Test Started \n\n" >> $RUN_LOG_FILE} abort; - -re "FAILED" { exec echo "\nContinueous Concurrance Test Failed\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nContinueous Concurrance Test Timeout\n" >> $RUN_LOG_FILE} abort; - timeout { exec echo "\nContinueous Concurrance Test Timeout\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "queryCalpontOnly" } { - set timeout 1200 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "./nightly/startQueryTesterCalpontOnly $SVN" "startQueryTester completed" "No such file" 1200 - expect { - -re " " { exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/queryTester_working_tpch1_calpontonly.report" - exec cat queryTester_working_tpch1_calpontonly.report >> $RUN_LOG_FILE - exec rm -f queryTester_working_tpch1_calpontonly.report} abort; - -re "FAILED" { exec echo "\nFailed to run queryTester\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run queryTester\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "DBimport" } { - set timeout 28800 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "./nightly/dbImport.sh $SVN" "dbImport completed" "No such file" $timeout - expect { - -re " " { exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/nightly/qaftest2/go.log" - exec cat go.log >> $RUN_LOG_FILE - exec rm -f go.log} abort; - -re "FAILED" { exec echo "\nFailed to run dbImport\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run dbImport\n" >> $RUN_LOG_FILE} abort; - } - } - if { $TESTCOMMAND == "ImportSSB100" } { - set timeout 28800 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "./nightly/importSSB100.sh $SVN" "importSSB100 completed" "No such file" $timeout - expect { - -re " " { - exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/nightly/srvalpha2/go.log" - exec cat go.log >> $RUN_LOG_FILE - exec rm -f go.log - } abort; - -re "FAILED" { - exec echo "\nFailed to run importSSB100\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run importSSB100\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "dml" } { - set timeout 60 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "./nightly/startQueryTesterDML $SVN" "startQueryTester completed" "No such file" 60 - expect { - -re "FAILED" { send_user "FAILED\n" - exec echo "\nFailed to run queryTesterDML\n" >> $RUN_LOG_FILE}; - -re "TIMEOUT" { send_user "TIMEOUT\n" - exec echo "\nTimeout on run queryTesterDML\n" >> $RUN_LOG_FILE}; - -re " " { send_user "PASSED\n" - exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/queryTesterDML.report" - exec cat queryTesterDML.report >> $RUN_LOG_FILE - exec rm -f queryTesterDML.report; - }; - send_user "NOTHING\n" - } - } elseif { $TESTCOMMAND == "timings" } { - set timeout 60 - log_user 1 - exec ./remote_command_test.sh $SERVER $PASSWORD "/root/nightly/updateQueries $SVN" "updateQueries completed" "No such file" 60 1 - set timeout 22000 - exec ./remote_command_test.sh $SERVER $PASSWORD "/root/nightly/startTimingsTester $SVN" "startTimingsTester completed" "error" 22000 1 - expect { - -re " " { - set REPORT demo - exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/nightly/$REPORT/go.log" - exec cat go.log >> $RUN_LOG_FILE} abort; - -re "FAILED" { exec echo "\nFailed to run timings\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run timings\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "perfTests" } { - set timeout 22000 - exec ./remote_command_test.sh $SERVER $PASSWORD "/root/nightly/startPerfTests $SVN" "startPerfTests completed" "error" 22000 1 - expect { - -re " " { - set REPORT perf - exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/nightly/$REPORT/go.log" - exec cat go.log >> $RUN_LOG_FILE} abort; - -re "FAILED" { echo "\nFailed to run timings\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run timings\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "dataWarehouse" } { - set timeout 5000000 - exec ./remote_command_test.sh $SERVER $PASSWORD "/root/nightly/startDataWarehouseTests $SVN" "startDataWarehouseTests completed" "error" 5000000 1 - expect { - -re " " { - set REPORT dataWarehouse - exec ./remote_scp_get.sh $SERVER $PASSWORD "/root/$SVN/mysql/queries/nightly/$REPORT/go.log" - exec cat go.log >> $RUN_LOG_FILE} abort; - -re "FAILED" { echo "\nFailed to run dataWarehouse\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on dataWarehouse\n" >> $RUN_LOG_FILE} abort; - } - } elseif { $TESTCOMMAND == "calbench" } { - set timeout 22000 - log_user 1 - exec ./remote_command.sh $SERVER $PASSWORD "/home/calbench/AutomatedCalBench.sh " "EndAutomatedCalBench" "No such file" 22000 1 - expect { - -re " " { exec echo "\n\nAutomatedCalBench.sh successfully started\n" >> $RUN_LOG_FILE} abort; - -re "FAILED" { exec echo "\nFailed to run AutomatedCalBench.sh\n" >> $RUN_LOG_FILE} abort; - -re "TIMEOUT" { exec echo "\nTimeout on run AutomatedCalBench.sh\n" >> $RUN_LOG_FILE} abort; - } - } - } else { - send_user "Test Failed, Testcase $TESTCASE not supported\n" - exec echo "Test Failed, Testcase $TESTCASE not supported" >> $RUN_LOG_FILE - } - } - #get current date - exec date >/tmp/datesync.tmp - exec cat /tmp/datesync.tmp - set newtime [exec cat /tmp/datesync.tmp] - exec echo "\n\n******************* Run Test $TESTCASE ended at $newtime **********************************\n\n" >> $RUN_LOG_FILE - sleep 10 - } -} -set timeout 30 - -#get current date -exec date >/tmp/datesync.tmp -exec cat /tmp/datesync.tmp -set newtime [exec cat /tmp/datesync.tmp] - -exec echo "\nBuild Test Successfully Completed $newtime\n\n" >> $RUN_LOG_FILE - -#send report -log_user 0 -if { $EMAIL != " " } { - puts [exec mail -s "$SYSTEM/$SVN Automated Build/Test Results" $EMAIL < $RUN_LOG_FILE] - send_user "email report sent\n" -} else { - log_user 1 - send_user "Report located here: $RUN_LOG_FILE\n" - exec cat $RUN_LOG_FILE -} - -send_user "\nBuild Test Completed\n" - -exit diff --git a/tools/configMgt/calpont-build b/tools/configMgt/calpont-build deleted file mode 100755 index 43bf25af..00000000 --- a/tools/configMgt/calpont-build +++ /dev/null @@ -1,102 +0,0 @@ -#! /bin/sh -# -# $Id: calpont-build 421 2007-14-15 15:46:55Z dhill $ -# -# build calpont rpm and install on call6500 -# $1 - release number or 'Latest' -# $2 - svn branch -# -if [ "$2" = "" ] ; then - echo "enter release and svn-branch arguments" - exit 0 -fi -# !!! set for OS type 32 or 64 bit !!! - -OS=x86_64 - -# -REL=$1 -DIR=$2 - -#remove mysqld before new one is built -#prevents old version from being packaged in new build -rm -f /usr/local/Calpont/mysql/libexec/* - -if [ $DIR = "genii" ] ; then - ./mysql-build-genii > mysql-build-genii.log & -else - ./mysql-build-branch $DIR > mysql-build-$DIR.log & -fi -# -HOME=/home/nightly/$DIR -rm -rf $HOME -rm -fr /home/nightly/rpm/ -# - -if [ $DIR = "genii" ] ; then - su - nightly -c "export CXXFLAGS='-O3 -fno-strict-aliasing ';mkdir $DIR;updateGenii.pl > ~/$DIR/updateGenii.log 2>&1;cd ~/$DIR;make clean;make > ~/$DIR/make.log 2>&1;make > ~/$DIR/make1.log 2>&1;./build/build_rpms > ~/$DIR/build_rpms.log 2>&1" -else - su - nightly -c "export CXXFLAGS='-O3 -fno-strict-aliasing ';mkdir $DIR;updateGenii.pl -b $DIR > ~/$DIR/updateGenii.log 2>&1;cd ~/$DIR;make clean;make > ~/$DIR/make.log 2>&1;make > ~/$DIR/make1.log 2>&1;./build/build_rpms > ~/$DIR/build_rpms.log 2>&1" -fi - -# -# generate rpm info text files - -if [ ! -f $HOME/build/releasenum ]; then - #default - version=3.0 -else - . $HOME/build/releasenum -fi - -cd /home/nightly/rpm/ > /dev/null 2>&1 -cd RPMS/$OS/ > /dev/null 2>&1 -test -f infinidb-platform-$version*.rpm || echo "no rpm" -test -f infinidb-platform-$version*.rpm || exit -1 -rpm -qi -p infinidb-platform-$version*.rpm > infinidb-platform-$OS-rpm-info.txt -echo " " >> infinidb-platform-$OS-rpm-info.txt -echo "MD5SUM" >> infinidb-platform-$OS-rpm-info.txt -md5sum infinidb-platform-$version*.rpm >> infinidb-platform-$OS-rpm-info.txt -echo " " >> infinidb-platform-$OS-rpm-info.txt -# -test -f infinidb-storage-engine-*.rpm || echo "no rpm" -test -f infinidb-storage-engine-*.rpm || exit -1 -rpm -qi -p infinidb-storage-engine-*.rpm > infinidb-storage-engine-$OS-rpm-info.txt -echo " " >> infinidb-storage-engine-$OS-rpm-info.txt -echo "MD5SUM" >> infinidb-storage-engine-$OS-rpm-info.txt -md5sum infinidb-storage-engine-*.rpm >> infinidb-storage-engine-$OS-rpm-info.txt -echo " " >> infinidb-storage-engine-$OS-rpm-info.txt -# -test -f infinidb-mysql-*.rpm || echo "no rpm" -test -f infinidb-mysql-*.rpm || exit -1 -rpm -qi -p infinidb-mysql-*.rpm > infinidb-mysql-$OS-rpm-info.txt -echo " " >> infinidb-mysql-$OS-rpm-info.txt -echo "MD5SUM" >> infinidb-mysql-$OS-rpm-info.txt -md5sum infinidb-mysql-*.rpm >> infinidb-mysql-$OS-rpm-info.txt -echo " " >> infinidb-mysql-$OS-rpm-info.txt -# -{ -if [ $REL != "Latest" ] ; then - # copy rpms to calweb - DATE=`date +%F` - cd /home/nightly/rpm/RPMS/$OS/ - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations;mkdir $REL;cd $REL;rm *.$OS.rpm;prompt OFF;mput *" - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/nightly;mkdir $REL-$DATE;cd $REL-$DATE;rm *.$OS.rpm;prompt OFF;mput *" - cd /home/nightly/$DIR/export/etc/ - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/$REL;rm Calpont.xml;prompt OFF;mput Calpont.xml" - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/nightly/$REL-$DATE;rm Calpont.xml;prompt OFF;mput Calpont.xml" - -else - # copy nightly on calweb - DATE=`date +%F` - cd /home/nightly/rpm/RPMS/$OS/ - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/Latest;rm *.$OS.rpm;prompt OFF;mput *" - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/nightly;mkdir genii-$DATE;cd genii-$DATE;prompt OFF;mput *" - cd /home/nightly/$DIR/export/etc/ - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/Latest;rm Calpont.xml;prompt OFF;mput Calpont.xml" - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/nightly/genii-$DATE;prompt OFF;mput Calpont.xml" -fi -} 2> /root/infinidb-build-$REL-$DIR.log -# -echo "Build Successfully Completed" -exit 0 diff --git a/tools/configMgt/configure.cpp b/tools/configMgt/configure.cpp deleted file mode 100644 index e857cfe8..00000000 --- a/tools/configMgt/configure.cpp +++ /dev/null @@ -1,1541 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/****************************************************************************************** -* $Id: configure.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* List of files being updated by configure: -* Calpont/etc/Calpont.xml -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "stdio.h" -#include "ctype.h" -#include - -#include -#include - -#include "liboamcpp.h" -#include "configcpp.h" - -using namespace std; -using namespace oam; -using namespace config; - -typedef std::vector Devices; - -typedef struct Performance_Module_struct -{ - std::string moduleIP1; - std::string moduleIP2; - std::string moduleIP3; - std::string moduleIP4; -} PerformanceModule; - -typedef std::vector PerformanceModuleList; - -int main(int argc, char *argv[]) -{ - - setenv("CALPONT_HOME", ".", 1); - - char* pcommand = 0; - string parentOAMModuleName; - string parentOAMModuleIPAddr; - PerformanceModuleList performancemodulelist; - int pmNumber = 0; - string prompt; - int DBRMworkernodeID = 0; - string parentOAMModuleHostName; - string password; - - string SystemSection = "SystemConfig"; - string InstallSection = "Installation"; - - cout << endl; - cout << "This is the Calpont System Configuration tool." << endl; - cout << "It will generate a Calpont System specific Calpont.xml file." << endl; - cout << "The file can then be used by the autoInstaller tool" << endl; - cout << endl; - - cout << "Instructions:" << endl << endl; - cout << " Press 'enter' to accept a default value in (), if available or" << endl; - cout << " Enter one of the options within [], if available, or" << endl; - cout << " Enter a new value" << endl << endl; - - //get system name - string systemName; - Config* netConfig = Config::makeConfig("./systems/CalpontSystems.xml"); - - - while(true) - { - prompt = "Enter Calpont system name > "; - pcommand = readline(prompt.c_str()); - if (pcommand) { - systemName = pcommand; - free(pcommand); - pcommand = 0; - - int systemCount; - try { - systemCount = strtol(netConfig->getConfig("NetworkConfig", "SystemCount").c_str(), 0, 0); - if ( systemCount == 0 ) { - cout << "ERROR: SystemCount in ./systems/CalpontSystems.xml equal to 0" << endl; - exit(-1); - } - } - catch(...) - { - cout << "ERROR: Problem getting SystemCount from ./systems/CalpontSystems.xml" << endl; - exit(-1); - } - - bool FOUND = false; - for ( int i = 1 ; i < systemCount+1 ; i++) - { - Oam oam; - string SystemName = "SystemName" + oam.itoa(i); - string oamParentModule = "OAMParentModule" + oam.itoa(i); - string SystemPassword = "SystemPassword" + oam.itoa(i); - - string tempSystem; - try { - tempSystem = netConfig->getConfig("NetworkConfig", SystemName ); - } - catch(...) - { - cout << "ERROR: Problem getting SystemName from ./systems/CalpontSystems.xml" << endl; - exit(-1); - } - - if ( tempSystem == systemName ) { - try { - parentOAMModuleHostName = netConfig->getConfig("NetworkConfig", oamParentModule ); - password = netConfig->getConfig("NetworkConfig", SystemPassword ); - - string cmd = "mkdir systems/" + systemName + " > /dev/null 2>&1" ; - system(cmd.c_str()); - - FOUND = true; - break; - } - catch(...) - { - cout << "ERROR: Problem getting SystemName from ./systems/CalpontSystems.xml" << endl; - exit(-1); - } - } - } - - if ( !FOUND ) { - cout << "ERROR: System Name '" + systemName + "' not in ./systems/CalpontSystems.xml" << endl; - continue; - } - - break; - } - cout << "Invalid System Name, please re-enter" << endl; - } - - //determine which Calpont.xml to use as a base - while(true) - { - cout << endl; - cout << "Enter the Calpont.xml file do you want to use as a based version" << endl; - cout << "Enter: 1 for System version (meaning copy from the system)" << endl; - cout << " 2 for Release version" << endl; - cout << " 3 for Calpont.xml version already located in the systems directory" << endl; - - int option; - prompt = "Enter (1,2,or 3) > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - continue; - else - { - option = atoi(pcommand); - free(pcommand); - pcommand = 0; - switch(option) { - case 1: //get system Calpont.xml - { - cout << "Copying from system, please wait... " << flush; - //get Network IP Address - Oam oam; - parentOAMModuleIPAddr = oam.getIPAddress( parentOAMModuleHostName); - if ( parentOAMModuleIPAddr.empty() ) { - cout << "Invalid Host Name (No DNS IP found), exiting..." << endl; - exit (-1); - } - - //check to see if system is up - string cmdLine = "ping "; - string cmdOption = " -w 1 >> /dev/null"; - - string cmd = cmdLine + parentOAMModuleIPAddr + cmdOption; - int rtnCode = system(cmd.c_str()); - if ( rtnCode != 0 ) { - cout << "System is down, exiting..." << endl; - exit (-1); - } - - cmd = "./remote_scp_get.sh " + parentOAMModuleIPAddr + " " + password + " /usr/local/Calpont/etc/Calpont.xml 0 "; - rtnCode = system(cmd.c_str()); - if (rtnCode == 0) { - cmd = "mv Calpont.xml systems/" + systemName + "/."; - rtnCode = system(cmd.c_str()); - if ( rtnCode != 0 ) { - cout << "ERROR: No system Calpont.xml found" << endl; - continue; - } - else - break; - } - break; - } - case 2: //get release Calpont.xml - { - string release; - while (true) - { - prompt = "Enter Calpont Release number > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - continue; - else - { - release = pcommand; - free(pcommand); - pcommand = 0; - if (release.empty()) continue; - string cmd = "cd systems/" + systemName + ";rm -f Calpont.xml;smbclient //cal6500/shared -Wcalpont -U" + oam::USERNAME + "%" + oam::PASSWORD + " -c 'cd Iterations/" + release + "/;prompt OFF;mget Calpont.xml' > /dev/null 2>&1"; - int rtnCode = system(cmd.c_str()); - if (rtnCode != 0) - cout << "FAILED: no Release Calpont.xml found for " + release << endl; - else - { - cmd = "cd systems/" + systemName + ";ls Calpont.xml > /dev/null 2>&1"; - rtnCode = system(cmd.c_str()); - if (rtnCode != 0) { - cout << "FAILED: no Release Calpont.xml found for " + release << endl; - continue; - } - else - break; - } - } - } - break; - } - case 3: //use Calpont.xml alyread in system directory - break; - - default: - continue; - } - break; - } - } - - cout << endl; - - string env = "systems/" + systemName; - - setenv("CALPONT_HOME", env.c_str() , 1); - Oam oam; - - Config* sysConfig = Config::makeConfig(env + "/Calpont.xml"); - - // make DBRM backwards compatiable for pre 1.0.0.157 load - string dbrmMainProc = "DBRM_Controller"; - string dbrmSubProc = "DBRM_Worker"; - string numSubProc = "NumWorkers"; - - try { - if ( (sysConfig->getConfig(dbrmMainProc, "IPAddr")).empty() ) { - dbrmMainProc = "DBRM_Master"; - dbrmSubProc = "DBRM_Slave"; - numSubProc = "NumSlaves"; - } - } - catch(...) - { - dbrmMainProc = "DBRM_Master"; - dbrmSubProc = "DBRM_Slave"; - numSubProc = "NumSlaves"; - } - - string singleServerInstall; - try { - singleServerInstall = sysConfig->getConfig(InstallSection, "SingleServerInstall"); - } - catch(...) - { - cout << "ERROR: Problem getting SingleServerInstall from the Calpont System Configuration file" << endl; - exit(-1); - } - - //get Parent OAM Module Name and setup of it's Custom OS files - try{ - parentOAMModuleName = sysConfig->getConfig(SystemSection, "ParentOAMModuleName"); - } - catch(...) - { - cout << "ERROR: Problem getting Parent OAM Module Name" << endl; - exit(-1); - } - - while(true) - { - prompt = "Single Server Installation? [y,n] (" + singleServerInstall + ") > "; - pcommand = readline(prompt.c_str()); - cout << endl; - if (pcommand) - { - if (strlen(pcommand) > 0) singleServerInstall = pcommand; - free(pcommand); - pcommand = 0; - } - - if ( singleServerInstall == "y" ) { - cout << "Single Server Installation will be performed. The Server will be assigned as a Director Module #1." << endl; - cout << "All Calpont Processes will run on this single server." << endl; - } - else - { - if ( singleServerInstall == "n" ) { - prompt = "Enter the OAM Parent Module Name or exit [mm1,dmx,exit] (" + parentOAMModuleName + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) { - if (strlen(pcommand) > 0) parentOAMModuleName = pcommand; - free(pcommand); - pcommand = 0; - if (parentOAMModuleName == "exit") - exit(0); - } - break; - } - else - cout << "Invalid Entry, please enter 'y' for yes or 'n' for no" << endl; - } - break; - } - - // set Single Server Installation Indicator - try { - sysConfig->setConfig(InstallSection, "SingleServerInstall", singleServerInstall); - } - catch(...) - { - cout << "ERROR: Problem setting DBRootStorageLoc in the Calpont System Configuration file" << endl; - exit(-1); - } - - //set Parent OAM Module Name - try{ - sysConfig->setConfig(SystemSection, "ParentOAMModuleName", parentOAMModuleName); - } - catch(...) - { - cout << "ERROR: Problem updating the Calpont System Configuration file" << endl; - exit(-1); - } - - string parentOAMModuleType = parentOAMModuleName.substr(0,MAX_MODULE_TYPE_SIZE); - int parentOAMModuleID = atoi(parentOAMModuleName.substr(MAX_MODULE_TYPE_SIZE,MAX_MODULE_ID_SIZE).c_str()); - - //Get list of configured system modules - SystemModuleTypeConfig sysModuleTypeConfig; - - try{ - oam.getSystemConfig(sysModuleTypeConfig); - } - catch(...) - { - cout << "ERROR: Problem reading the Calpont System Configuration file" << endl; - exit(-1); - } - - // - // get Data storage Mount - // - string DBRootStorageLoc; - string DBRootStorageType; - string UserStorageType; - string UserStorageLoc; - - string OAMStorageType; - string OAMStorageLoc; - - int DBRootCount; - string deviceName; - Devices devices; - - cout << endl << "===== Setup Data Storages Mount Configuration =====" << endl << endl; - - try { - DBRootStorageType = sysConfig->getConfig(InstallSection, "DBRootStorageType"); - DBRootCount = strtol(sysConfig->getConfig(SystemSection, "DBRootCount").c_str(), 0, 0); - OAMStorageType = sysConfig->getConfig(InstallSection, "OAMStorageType"); - OAMStorageLoc = sysConfig->getConfig(InstallSection, "OAMStorageLoc"); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the Calpont System Configuration file" << endl; - exit(-1); - } - - //setup dbroot storage - while(true) - { - prompt = "Enter Calpont Data Storage Mount Type [storage,local,nfs] (" + DBRootStorageType + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) DBRootStorageType = pcommand; - free(pcommand); - pcomand = 0; - } - if ( DBRootStorageType == "nfs" || DBRootStorageType == "storage" || DBRootStorageType == "local") - break; - cout << "Invalid Mount Type, please re-enter" << endl; - } - - try { - sysConfig->setConfig(InstallSection, "DBRootStorageType", DBRootStorageType); - } - catch(...) - { - cout << "ERROR: Problem setting DBRootStorageType in the Calpont System Configuration file" << endl; - exit(-1); - } - - while(true) - { - prompt = "Enter the Number of Calpont Data Storage (DBRoots) areas (" + oam.itoa(DBRootCount) + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) { - int newDBRootCount = DBRootCount; - if (strlen(pcommand) > 0) newDBRootCount = atoi(pcommand); - free(pcommand); - pcommand = 0; - if (newDBRootCount <= 0) { - cout << "ERROR: Invalid Number, please reenter" << endl; - continue; - } - - DBRootCount = newDBRootCount; - try { - sysConfig->setConfig(SystemSection, "DBRootCount", oam.itoa(DBRootCount)); - } - catch(...) - { - cout << "ERROR: Problem setting DBRoot Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - break; - } - - for( int i=1 ; i < DBRootCount+1 ; i++) - { - if ( DBRootStorageType != "local") { - - string DBRootStorageLocID = "DBRootStorageLoc" + oam.itoa(i); - try { - DBRootStorageLoc = sysConfig->getConfig(InstallSection, DBRootStorageLocID); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the Calpont System Configuration file" << endl; - exit(-1); - } - - prompt = "Enter Storage Location for DBRoot #" + oam.itoa(i) + " (" + DBRootStorageLoc + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) DBRootStorageLoc = pcommand; - free(pcommand); - pcommand = 0; - } - - devices.push_back(DBRootStorageLoc); - - try { - sysConfig->setConfig(InstallSection, DBRootStorageLocID, DBRootStorageLoc); - } - catch(...) - { - cout << "ERROR: Problem setting DBRootStorageLoc in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - string DBrootID = "DBRoot" + oam.itoa(i); - string pathID = "/usr/local/Calpont/data" + oam.itoa(i); - - try { - sysConfig->setConfig(SystemSection, DBrootID, pathID); - } - catch(...) - { - cout << "ERROR: Problem setting DBRoot in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - //setup OAM storage - cout << endl; - while(true) - { - prompt = "Enter OAM Data Storage Mount Type [storage,local] (" + OAMStorageType + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) OAMStorageType = pcommand; - free(pcommand); - pcommand = 0; - } - if ( OAMStorageType == "storage" || OAMStorageType == "local" ) - break; - cout << "Invalid Mount Location, please re-enter" << endl; - } - - try { - sysConfig->setConfig(InstallSection, "OAMStorageType", OAMStorageType); - } - catch(...) - { - cout << "ERROR: Problem setting OAMStorageType in the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( OAMStorageType == "storage") { - cout << endl; - prompt = "Enter Device Name for OAM Storage mounting (" + OAMStorageLoc + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) OAMStorageLoc = pcommand; - free(pcommand); - pcommand = 0; - } - - try { - sysConfig->setConfig(InstallSection, "OAMStorageLoc", OAMStorageLoc); - } - catch(...) - { - cout << "ERROR: Problem setting OAMStorageLoc in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - sysConfig->write(); - - // - // Module Configuration - // - cout << endl << "===== Setup the Module Configuration =====" << endl; - - string ModuleSection = "SystemModuleConfig"; - unsigned int maxPMNicCount = 1; - - for ( unsigned int i = 0 ; i < sysModuleTypeConfig.moduletypeconfig.size(); i++) - { - string moduleType = sysModuleTypeConfig.moduletypeconfig[i].ModuleType; - string moduleDesc = sysModuleTypeConfig.moduletypeconfig[i].ModuleDesc; - int moduleCount = sysModuleTypeConfig.moduletypeconfig[i].ModuleCount; - - //verify and setup of modules count - - if ( moduleType == "dm" && singleServerInstall == "y" ) { - - cout << endl << "----- " << moduleDesc << " Configuration -----" << endl << endl; - - moduleCount = 1; - pmNumber = 1; - try { - string ModuleCountParm = "ModuleCount" + oam.itoa(i+1); - sysConfig->setConfig(ModuleSection, ModuleCountParm, oam.itoa(moduleCount)); - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - else - { - if ( singleServerInstall == "y" ) { - moduleCount = 0; - try { - string ModuleCountParm = "ModuleCount" + oam.itoa(i+1); - sysConfig->setConfig(ModuleSection, ModuleCountParm, oam.itoa(moduleCount)); - continue; - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - cout << endl << "----- " << moduleDesc << " Configuration -----" << endl << endl; - - while(true) - { - prompt = "Enter number of " + moduleDesc + "s (" + oam.itoa(moduleCount) + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) { - //Update Count - string ModuleCountParm = "ModuleCount" + oam.itoa(i+1); - int newmoduleCount = moduleCount; - if (strlen(pcommand) > 0) newmoduleCount = atoi(pcommand); - free(pcommand); - pcommand = 0; - if (newmoduleCount <= 0) { - cout << "ERROR: Invalid Number, please reenter" << endl; - continue; - } - - try { - moduleCount = newmoduleCount; - sysConfig->setConfig(ModuleSection, ModuleCountParm, oam.itoa(moduleCount)); - } - catch(...) - { - cout << "ERROR: Problem setting Module Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - if ( parentOAMModuleType == moduleType && parentOAMModuleID > moduleCount ) { - cout << endl << "ERROR: Parent OAM Module is '" + parentOAMModuleName + "', so you have to have at least 1 of this Module Type" << endl << endl; - } - else - { - break; - } - } - } - - int listSize = sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.size(); - - if ( moduleCount == 0 ) { - //set unEquipped Module IP addresses to oam::UnassignedIpAddr - for ( int j = moduleCount ; j < listSize ; j ++ ) - { - for ( unsigned int k = 1 ; k < MAX_NIC+1 ; k++ ) - { - string ModuleIPAddr = "ModuleIPAddr" + oam.itoa(j+1) + "-" + oam.itoa(k) + "-" + oam.itoa(i+1); - if ( !(sysConfig->getConfig(ModuleSection, ModuleIPAddr).empty()) ) { - string ModuleHostName = "ModuleHostName" + oam.itoa(j+1) + "-" + oam.itoa(k) + "-" + oam.itoa(i+1); - - sysConfig->setConfig(ModuleSection, ModuleIPAddr, oam::UnassignedIpAddr); - sysConfig->setConfig(ModuleSection, ModuleHostName, oam::UnassignedName); - } - } - } - - //no modules equipped for this Module Type, skip - continue; - } - - if ( moduleType == "pm" ) - pmNumber = moduleCount; - - //Enter User Temp Storage location - if ( moduleType == "um" || singleServerInstall == "y" ) { - try { - UserStorageType = sysConfig->getConfig(InstallSection, "UserStorageType"); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( moduleType == "um" ) - cout << endl; - - //setup User Temp Storage - while(true) - { - string newUserStorageType = UserStorageType; - prompt = "Enter User Module Temp Data Storage Mount Type [storage,local] (" + UserStorageType + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) newUserStorageType = pcommand; - free(pcommand); - pcommand = 0; - } - - if ( newUserStorageType == "storage" || newUserStorageType == "local" ) { - UserStorageType = newUserStorageType; - break; - } - cout << "Invalid Mount Type, please re-enter" << endl; - } - - try { - sysConfig->setConfig(InstallSection, "UserStorageType", UserStorageType); - } - catch(...) - { - cout << "ERROR: Problem setting UserStorageType in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - int moduleID = 1; - while(true) { - prompt = "Enter Starting Module ID for " + moduleDesc + " (1) > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) moduleID = atoi(pcommand); - free(pcommand); - pcommand = 0; - } - - //valid if parent OAM module type and is consistent with parentOAMModuleName - if ( parentOAMModuleType == moduleType && - ( parentOAMModuleID < moduleID || parentOAMModuleID > moduleID + (moduleCount-1) ) ) { - cout << endl << "ERROR: Parent and Starting Module ID out of range, please re-enter" << endl << endl; - moduleID = 1; - } - else - break; - } - - //clear any Equipped Module IP addresses that aren't in current ID range - for ( int j = 0 ; j < listSize ; j++ ) - { - for ( unsigned int k = 1 ; k < MAX_NIC+1 ; k++) - { - string ModuleIPAddr = "ModuleIPAddr" + oam.itoa(j+1) + "-" + oam.itoa(k) + "-" + oam.itoa(i+1); - if ( !(sysConfig->getConfig(ModuleSection, ModuleIPAddr).empty()) ) { - if ( j+1 < moduleID || j+1 > moduleID + (moduleCount-1) ) { - string ModuleHostName = "ModuleHostName" + oam.itoa(j+1) + "-" + oam.itoa(k) + "-" + oam.itoa(i+1); - - sysConfig->setConfig(ModuleSection, ModuleIPAddr, oam::UnassignedIpAddr); - sysConfig->setConfig(ModuleSection, ModuleHostName, oam::UnassignedName); - } - } - } - } - - //get IP addresses and Host Names - for( int k=0 ; k < moduleCount ; k++, moduleID++ ) - { - PerformanceModule performancemodule; - string newModuleName = moduleType + oam.itoa(moduleID); - string moduleNameDesc = moduleDesc + " #" + oam.itoa(moduleID); - - cout << endl << "*** " << moduleNameDesc << " Configuration ***" << endl << endl; - - //Enter User Temp Storage location - if ( moduleType == "um" || singleServerInstall == "y" ) { - UserStorageLoc = oam::UnassignedName; - string USERSTORAGELOC = "UserStorageLoc" + oam.itoa(moduleID); - if ( UserStorageType == "storage") { - try { - UserStorageLoc = sysConfig->getConfig(InstallSection, USERSTORAGELOC); - } - catch(...) - { - cout << "ERROR: Problem getting DB Storage Data from the Calpont System Configuration file" << endl; - exit(-1); - } - - prompt = "Enter Device Name for User Module '" + newModuleName + "' Temp Storage (" + UserStorageLoc + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) UserStorageLoc = pcommand; - free(pcommand); - pcommand = 0; - } - - try { - sysConfig->setConfig(InstallSection, USERSTORAGELOC, UserStorageLoc); - } - catch(...) - { - cout << "ERROR: Problem setting UserStorageLoc in the Calpont System Configuration file" << endl; - exit(-1); - } - } - else - { - try { - sysConfig->setConfig(InstallSection, USERSTORAGELOC, oam::UnassignedName); - } - catch(...) - { - cout << "ERROR: Problem setting UserStorageLoc in the Calpont System Configuration file" << endl; - exit(-1); - } - } - } - - //setup HostName/IPAddress for each NIC - for( unsigned int nicID=1 ; nicID < MAX_NIC+1 ; nicID++ ) - { - string moduleHostName = oam::UnassignedName; - string moduleIPAddr = oam::UnassignedIpAddr; - - DeviceNetworkList::iterator listPT = sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.begin(); - for( ; listPT != sysModuleTypeConfig.moduletypeconfig[i].ModuleNetworkList.end() ; listPT++) - { - HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); - for( ; pt1 != (*listPT).hostConfigList.end() ; pt1++) - { - if ( newModuleName == (*listPT).DeviceName && (*pt1).NicID == nicID) { - moduleHostName = (*pt1).HostName; - moduleIPAddr = (*pt1).IPAddr; - break; - } - } - } - - bool moduleHostNameFound = true; - if (moduleHostName.empty()) { - moduleHostNameFound = false; - moduleHostName = oam::UnassignedName; - } - - if (moduleIPAddr.empty()) - moduleIPAddr = oam::UnassignedIpAddr; - - string newModuleIPAddr; - string newModuleHostName; - - while (true) - { - prompt = "Enter Nic Interface #" + oam.itoa(nicID) + " Host Name (" + moduleHostName + ") > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - newModuleHostName = moduleHostName; - else - { - if (strlen(pcommand) > 0) newModuleHostName = pcommand; - free(pcommand); - pcommand = 0; - } - - if ( newModuleHostName == oam::UnassignedName && !moduleHostNameFound && nicID == 1 ) - cout << "Invalid Entry, please enter at least 1 valid Host Name for Module" << endl; - else - break; - } - - if ( newModuleHostName == oam::UnassignedName && moduleHostNameFound ) - // exit out to next module ID - break; - - //set New Module Host Name - string moduleHostNameParm = "ModuleHostName" + oam.itoa(moduleID) + "-" + oam.itoa(nicID) + "-" + oam.itoa(i+1); - try { - sysConfig->setConfig(ModuleSection, moduleHostNameParm, newModuleHostName); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - - if ( newModuleHostName == oam::UnassignedName ) - newModuleIPAddr = oam::UnassignedIpAddr; - else - { - //get Network IP Address - string IPAddress = oam.getIPAddress( newModuleHostName); - if ( !IPAddress.empty() ) - newModuleIPAddr = IPAddress; - else - newModuleIPAddr = moduleIPAddr; - - //prompt for IP address - while (true) - { - prompt = "Enter Nic Interface #" + oam.itoa(nicID) + " IP Address of " + newModuleHostName + " (" + newModuleIPAddr + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) newModuleIPAddr = pcommand; - free(pcommand); - pcommand = 0; - } - if (oam.isValidIP(newModuleIPAddr)) - break; - else - cout << "Invalid IP Address format, xxx.xxx.xxx.xxx, please reenter" << endl; - } - } - - //set Module IP address - string moduleIPAddrNameParm = "ModuleIPAddr" + oam.itoa(moduleID) + "-" + oam.itoa(nicID) + "-" + oam.itoa(i+1); - try { - sysConfig->setConfig(ModuleSection, moduleIPAddrNameParm, newModuleIPAddr); - } - catch(...) - { - cout << "ERROR: Problem setting IP address in the Calpont System Configuration file" << endl; - exit(-1); - } - - if (moduleType == "pm" || ( moduleType == "dm" && singleServerInstall == "y" )) { - - switch(nicID) { - case 1: - performancemodule.moduleIP1 = newModuleIPAddr; - break; - case 2: - performancemodule.moduleIP2 = newModuleIPAddr; - break; - case 3: - performancemodule.moduleIP3 = newModuleIPAddr; - break; - case 4: - performancemodule.moduleIP4 = newModuleIPAddr; - break; - } - - if ( maxPMNicCount < nicID ) - maxPMNicCount = nicID; - } - - if ( nicID > 1 ) - continue; - - //set port addresses - if ( newModuleName == parentOAMModuleName ) { - parentOAMModuleIPAddr = newModuleIPAddr; - - //set Parent Processes Port IP Address - string parentProcessMonitor = parentOAMModuleName + "_ProcessMonitor"; - sysConfig->setConfig(parentProcessMonitor, "IPAddr", parentOAMModuleIPAddr); - sysConfig->setConfig(parentProcessMonitor, "Port", "8606"); - sysConfig->setConfig("ProcMgr", "IPAddr", parentOAMModuleIPAddr); - sysConfig->setConfig("ProcHeartbeatControl", "IPAddr", parentOAMModuleIPAddr); - sysConfig->setConfig("ProcStatusControl", "IPAddr", parentOAMModuleIPAddr); - string parentServerMonitor = parentOAMModuleName + "_ServerMonitor"; - sysConfig->setConfig(parentServerMonitor, "IPAddr", parentOAMModuleIPAddr); - - if ( singleServerInstall == "y" ) { - //set User Module's IP Addresses - string Section = "ExeMgr" + oam.itoa(moduleID); - - sysConfig->setConfig(Section, "IPAddr", newModuleIPAddr); - sysConfig->setConfig(Section, "Port", "8601"); - - //set Performance Module's IP's to first NIC IP entered - sysConfig->setConfig("DDLProc", "IPAddr", newModuleIPAddr); - sysConfig->setConfig("DMLProc", "IPAddr", newModuleIPAddr); - } - } - else - { - //set child Process Monitor Port IP Address - string portName = newModuleName + "_ProcessMonitor"; - sysConfig->setConfig(portName, "IPAddr", newModuleIPAddr); - sysConfig->setConfig(portName, "Port", "8606"); - - //set child Server Monitor Port IP Address - portName = newModuleName + "_ServerMonitor"; - sysConfig->setConfig(portName, "IPAddr", newModuleIPAddr); - sysConfig->setConfig(portName, "Port", "8622"); - - //set User Module's IP Addresses - if ( moduleType == "um" ) { - string Section = "ExeMgr" + oam.itoa(moduleID); - - sysConfig->setConfig(Section, "IPAddr", newModuleIPAddr); - sysConfig->setConfig(Section, "Port", "8601"); - } - - //set Performance Module's IP's to first NIC IP entered - if ( newModuleName == "pm1" ) { - sysConfig->setConfig("DDLProc", "IPAddr", newModuleIPAddr); - sysConfig->setConfig("DMLProc", "IPAddr", newModuleIPAddr); - } - } - - //setup DBRM processes - if ( newModuleName == "dm1" ) - sysConfig->setConfig(dbrmMainProc, "IPAddr", newModuleIPAddr); - - DBRMworkernodeID++; - string DBRMSection = dbrmSubProc + oam.itoa(DBRMworkernodeID); - sysConfig->setConfig(DBRMSection, "IPAddr", newModuleIPAddr); - sysConfig->setConfig(DBRMSection, "Module", newModuleName); - - } //end of nicID loop - - if (moduleType == "pm" || singleServerInstall == "y" ) - performancemodulelist.push_back(performancemodule); - - } //end of k (moduleCount) loop - - sysConfig->write(); - - } //end of i for loop - - //setup DBRM Controller - sysConfig->setConfig(dbrmMainProc, numSubProc, oam.itoa(DBRMworkernodeID)); - - //set ConnectionsPerPrimProc - try { - sysConfig->setConfig("PrimitiveServers", "ConnectionsPerPrimProc", oam.itoa(maxPMNicCount*2)); - } - catch(...) - { - cout << "ERROR: Problem setting ConnectionsPerPrimProc in the Calpont System Configuration file" << endl; - exit(-1); - } - - //set the PM Ports based on Number of PM modules equipped, if any equipped - int pmPorts = 32; - sysConfig->setConfig("PrimitiveServers", "Count", oam.itoa(pmNumber)); - - if ( pmNumber > 0 || singleServerInstall == "y" ) - { - const string PM = "PMS"; - - for ( int pmsID = 1; pmsID < pmPorts+1 ; ) - { - for (unsigned int j = 1 ; j < maxPMNicCount+1 ; j++) - { - PerformanceModuleList::iterator list1 = performancemodulelist.begin(); - - for (; list1 != performancemodulelist.end() ; list1++) - { - string pmName = PM + oam.itoa(pmsID); - string IpAddr; - switch(j) { - case 1: - IpAddr = (*list1).moduleIP1; - break; - case 2: - IpAddr = (*list1).moduleIP2; - break; - case 3: - IpAddr = (*list1).moduleIP3; - break; - case 4: - IpAddr = (*list1).moduleIP4; - break; - } - if ( !IpAddr.empty() && IpAddr != oam::UnassignedIpAddr ) { - sysConfig->setConfig(pmName, "IPAddr", IpAddr); - pmsID++; - if ( pmsID > pmPorts ) - break; - } - } - if ( pmsID > pmPorts ) - break; - } - } - } - - sysConfig->write(); - - // - // Configure switches - // - SystemSwitchTypeConfig sysSwitchTypeConfig; - - try{ - oam.getSystemConfig(sysSwitchTypeConfig); - } - catch(...) - { - cout << "ERROR: Problem reading the Calpont System Configuration file" << endl; - exit(-1); - } - - cout << endl << "===== Setup the Switch Configuration =====" << endl; - - string SwitchSection = "SystemSwitchConfig"; - - for ( unsigned int i = 0 ; i < sysSwitchTypeConfig.switchtypeconfig.size(); i++) - { - string switchType = sysSwitchTypeConfig.switchtypeconfig[i].SwitchType; - string switchDesc = sysSwitchTypeConfig.switchtypeconfig[i].SwitchDesc; - int switchCount = sysSwitchTypeConfig.switchtypeconfig[i].SwitchCount; - - //verify and setup of switches count - cout << endl << "----- " << switchDesc << " Configuration -----" << endl << endl; - - while(true) - { - prompt = "Enter number of " + switchDesc + "es (" + oam.itoa(switchCount) + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) { - //Update Count and continue with IP addresses - string SwitchCountParm = "SwitchCount" + oam.itoa(i+1); - int newswitchCount = switchCount; - if (strlen(pcommand) > 0) newswitchCount = atoi(pcommand); - free(pcommand); - pcommand = 0; - if (newswitchCount <= 0) { - cout << "ERROR: Invalid Number, please reenter" << endl; - continue; - } - - try { - switchCount = newswitchCount; - sysConfig->setConfig(SwitchSection, SwitchCountParm, oam.itoa(switchCount)); - break; - } - catch(...) - { - cout << "ERROR: Problem setting Switch Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - break; - } - - int listSize = sysSwitchTypeConfig.switchtypeconfig[i].SwitchNetworkList.size(); - - //set unEquipped Switch IP addresses to oam::UnassignedIpAddr - if ( switchCount < listSize ) - { - for ( int j = switchCount ; j < listSize ; j ++ ) - { - string SwitchIPAddr = "SwitchIPAddr" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - string SwitchHostName = "SwitchHostName" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - - sysConfig->setConfig(SwitchSection, SwitchIPAddr, oam::UnassignedIpAddr); - sysConfig->setConfig(SwitchSection, SwitchHostName, oam::UnassignedName); - } - } - - if ( switchCount == 0 ) - //no switches equipped for this Switch Type, skip - continue; - - //add new entried to Calpont System Config table for additional IP Addresses and Hostnames - for ( int j = listSize ; j < switchCount ; j ++ ) - { - string SwitchIPAddr = "SwitchIPAddr" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - string SwitchHostName = "SwitchHostName" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - - sysConfig->setConfig(SwitchSection, SwitchIPAddr, oam::UnassignedIpAddr); - sysConfig->setConfig(SwitchSection, SwitchHostName, oam::UnassignedName); - } - - //get IP addresses and Host Names - for( int k=0 ; k < switchCount ; k++ ) - { - int switchID = k+1; - string newSwitchName = switchType + oam.itoa(switchID); - string switchIPAddr = oam::UnassignedIpAddr; - string switchHostName = oam::UnassignedName; - string switchNameDesc = switchDesc + " #" + oam.itoa(switchID); - - cout << endl << "*** " << switchNameDesc << " Configuration ***" << endl << endl; - - DeviceNetworkList::iterator listPT = sysSwitchTypeConfig.switchtypeconfig[i].SwitchNetworkList.begin(); - for( ; listPT != sysSwitchTypeConfig.switchtypeconfig[i].SwitchNetworkList.end() ; listPT++) - { - if ( newSwitchName == (*listPT).DeviceName) { - HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); - for( ; pt1 != (*listPT).hostConfigList.end() ; pt1++) - { - switchIPAddr = (*pt1).IPAddr; - switchHostName = (*pt1).HostName; - break; - } - break; - } - } - - if (switchIPAddr.empty()) - switchIPAddr = oam::UnassignedIpAddr; - - if (switchHostName.empty()) - switchHostName = oam::UnassignedName; - - string newSwitchIPAddr; - string newSwitchHostName; - - prompt = "Enter Host Name (" + switchHostName + ") > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - newSwitchHostName = switchHostName; - else - { - if (strlen(pcommand) > 0 )newSwitchHostName = pcommand; - free(pcommand); - pcommand = 0; - - //set New Switch Host Name - string switchHostNameParm = "SwitchHostName" + oam.itoa(switchID) + "-" + oam.itoa(i+1); - try { - sysConfig->setConfig(SwitchSection, switchHostNameParm, newSwitchHostName); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - //get Network IP Address - string IPAddress = oam.getIPAddress( newSwitchHostName); - if ( !IPAddress.empty() ) { - newSwitchIPAddr = IPAddress; - - cout << "'" << newSwitchHostName << "' DNS IP Address is '" << newSwitchIPAddr << "'" << endl; - } - else - { //no DNS address found for Host Name - while (true) - { - prompt = "Enter IP Address of (" + switchIPAddr + ") > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - newSwitchIPAddr = switchIPAddr; - else - { - if (strlen(pcommand) > 0) newSwitchIPAddr = pcommand; - free(pcommand); - pcommand = 0; - } - if (oam.isValidIP(newSwitchIPAddr)) - break; - else - cout << "Invalid IP Address format, xxx.xxx.xxx.xxx, please reenter" << endl; - } - } - - //set New Switch IP address - string switchIPAddrNameParm = "SwitchIPAddr" + oam.itoa(switchID) + "-" + oam.itoa(i+1); - try { - sysConfig->setConfig(SwitchSection, switchIPAddrNameParm, newSwitchIPAddr); - } - catch(...) - { - cout << "ERROR: Problem setting IP address in the Calpont System Configuration file" << endl; - exit(-1); - } - } //end of k loop - } //end of i for loop - - sysConfig->write(); - - // - // Configure storages - // - SystemStorageTypeConfig sysStorageTypeConfig; - - try{ - oam.getSystemConfig(sysStorageTypeConfig); - } - catch(...) - { - cout << "ERROR: Problem reading the Calpont System Configuration file" << endl; - exit(-1); - } - - string StorageSection = "SystemStorageConfig"; - - cout << endl << "===== Setup the Storage Configuration =====" << endl; - - for ( unsigned int i = 0 ; i < sysStorageTypeConfig.storagetypeconfig.size(); i++) - { - string storageType = sysStorageTypeConfig.storagetypeconfig[i].StorageType; - string storageDesc = sysStorageTypeConfig.storagetypeconfig[i].StorageDesc; - int storageCount = sysStorageTypeConfig.storagetypeconfig[i].StorageCount; - - //verify and setup of storages count - cout << endl << "----- " << storageDesc << " Configuration -----" << endl << endl; - - while(true) - { - prompt = "Enter number of " + storageDesc + "s (" + oam.itoa(storageCount) + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) { - //Update Count and continue with IP addresses - string StorageCountParm = "StorageCount" + oam.itoa(i+1); - int newstorageCount = storageCount; - if (strlen(pcommand) > 0) newstorageCount = atoi(pcommand); - free(pcommand); - pcommand = 0; - if (newstorageCount <= 0) { - cout << "ERROR: Invalid Number, please reenter" << endl; - continue; - } - - try { - storageCount = newstorageCount; - sysConfig->setConfig(StorageSection, StorageCountParm, oam.itoa(storageCount)); - break; - } - catch(...) - { - cout << "ERROR: Problem setting Storage Count in the Calpont System Configuration file" << endl; - exit(-1); - } - } - break; - } - - int listSize = sysStorageTypeConfig.storagetypeconfig[i].StorageNetworkList.size(); - - //set unEquipped Storage IP addresses to oam::UnassignedIpAddr - if ( storageCount < listSize ) - { - for ( int j = storageCount ; j < listSize ; j ++ ) - { - string storageIPAddr = "StorageIPAddr" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - string StorageHostName = "StorageHostName" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - - sysConfig->setConfig(StorageSection, storageIPAddr, oam::UnassignedIpAddr); - sysConfig->setConfig(StorageSection, StorageHostName, oam::UnassignedName); - } - } - - if ( storageCount == 0 ) - //no storages equipped for this Storage Type, skip - continue; - - //add new entried to Calpont System Config table for additional IP Addresses and Hostnames - for ( int j = listSize ; j < storageCount ; j ++ ) - { - string storageIPAddr = "StorageIPAddr" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - string StorageHostName = "StorageHostName" + oam.itoa(j+1) + "-" + oam.itoa(i+1); - - sysConfig->setConfig(StorageSection, storageIPAddr, oam::UnassignedIpAddr); - sysConfig->setConfig(StorageSection, StorageHostName, oam::UnassignedName); - } - - - //get IP addresses and Host Names - for( int k=0 ; k < storageCount ; k++ ) - { - int storageID = k+1; - string newStorageName = storageType + oam.itoa(storageID); - string storageIPAddr = oam::UnassignedIpAddr; - string storageHostName = oam::UnassignedName; - string storageNameDesc = storageDesc + " #" + oam.itoa(storageID); - - cout << endl << "*** " << storageNameDesc << " Configuration ***" << endl << endl; - - DeviceNetworkList::iterator listPT = sysStorageTypeConfig.storagetypeconfig[i].StorageNetworkList.begin(); - for( ; listPT != sysStorageTypeConfig.storagetypeconfig[i].StorageNetworkList.end() ; listPT++) - { - if ( newStorageName == (*listPT).DeviceName) { - HostConfigList::iterator pt1 = (*listPT).hostConfigList.begin(); - for( ; pt1 != (*listPT).hostConfigList.end() ; pt1++) - { - storageIPAddr = (*pt1).IPAddr; - storageHostName = (*pt1).HostName; - break; - } - break; - } - } - - if (storageIPAddr.empty()) - storageIPAddr = oam::UnassignedIpAddr; - - if (storageHostName.empty()) - storageHostName = oam::UnassignedName; - - string newStorageIPAddr; - string newStorageHostName; - - prompt = "Enter Host Name (" + storageHostName + ") > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - newStorageHostName = storageHostName; - else - { - if (strlen(pcommand) > 0) newStorageHostName = pcommand; - free(pcommand); - pcommand = 0; - - //set New Storage Host Name - string storageHostNameParm = "StorageHostName" + oam.itoa(storageID) + "-" + oam.itoa(i+1); - try { - sysConfig->setConfig(StorageSection, storageHostNameParm, newStorageHostName); - } - catch(...) - { - cout << "ERROR: Problem setting Host Name in the Calpont System Configuration file" << endl; - exit(-1); - } - } - - //get Network IP Address - string IPAddress = oam.getIPAddress( newStorageHostName); - if ( !IPAddress.empty() ) { - newStorageIPAddr = IPAddress; - - cout << "'" << newStorageHostName << "' DNS IP Address is '" << newStorageIPAddr << "'" << endl; - } - else - { //no DNS address found for Host Name - while (true) - { - prompt = "Enter IP Address of (" + storageIPAddr + ") > "; - pcommand = readline(prompt.c_str()); - if (!pcommand) - newStorageIPAddr = storageIPAddr; - else - { - if (strlen(pcommand) > 0) newStorageIPAddr = pcommand; - free(pcommand); - pcommand = 0; - } - if (oam.isValidIP(newStorageIPAddr)) - break; - else - cout << "Invalid IP Address format, xxx.xxx.xxx.xxx, please reenter" << endl; - } - } - - //set New Storage IP address - string storageIPAddrNameParm = "StorageIPAddr" + oam.itoa(storageID) + "-" + oam.itoa(i+1); - try { - sysConfig->setConfig(StorageSection, storageIPAddrNameParm, newStorageIPAddr); - } - catch(...) - { - cout << "ERROR: Problem setting IP address in the Calpont System Configuration file" << endl; - exit(-1); - } - } //end of while loop - } //end of i for loop - - sysConfig->write(); - - // - // Configure NMS Addresses - // - - cout << endl << "===== Setup the External Network Management System (NMS) Server Configuration =====" << endl << endl; - - string NMSIPAddress; - try { - NMSIPAddress = sysConfig->getConfig(SystemSection, "NMSIPAddress"); - } - catch(...) - { - cout << "ERROR: Problem getting NMSIPAddress from Calpont System Configuration file" << endl; - exit(-1); - } - - prompt = "Enter IP Address(es) of NMS Server (" + NMSIPAddress + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) NMSIPAddress = pcommand; - free(pcommand); - pcommand = 0; - } - - try { - sysConfig->setConfig(SystemSection, "NMSIPAddress", NMSIPAddress); - } - catch(...) - { - cout << "ERROR: Problem setting NMSIPAddress in the Calpont System Configuration file" << endl; - exit(-1); - } - - - // - // setup TransactionArchivePeriod - // - - cout << endl << "===== Setup the Transaction Log Archive Time Period =====" << endl << endl; - - string transactionArchivePeriod; - try { - transactionArchivePeriod = sysConfig->getConfig(SystemSection, "TransactionArchivePeriod"); - } - catch(...) - { - cout << "ERROR: Problem getting transactionArchivePeriod from Calpont System Configuration file" << endl; - exit(-1); - } - - prompt = "Enter Transaction Archive Period in minutes (" + transactionArchivePeriod + ") > "; - pcommand = readline(prompt.c_str()); - if (pcommand) - { - if (strlen(pcommand) > 0) transactionArchivePeriod = pcommand; - free(pcommand); - pcommand = 0; - } - - try { - sysConfig->setConfig(SystemSection, "TransactionArchivePeriod", transactionArchivePeriod); - } - catch(...) - { - cout << "ERROR: Problem setting IP address in the Calpont System Configuration file" << endl; - exit(-1); - } - - // - //Update oidbitmap in Calpont.xml - // - - try { - sysConfig->setConfig("OIDManager", "OIDBitmapFile", "/mnt/OAM/dbrm/oidbitmap"); - } - catch(...) - { - cout << "ERROR: Problem setting OIDBitmapFile Calpont System Configuration file" << endl; - exit(-1); - } - - //Write out Updated System Configuration File - sysConfig->write(); - - cout << endl << "Configure is successfuly completed, Calpont.xml is located in systems/" + systemName << endl << endl; -} diff --git a/tools/configMgt/datdup-build b/tools/configMgt/datdup-build deleted file mode 100755 index 6825d923..00000000 --- a/tools/configMgt/datdup-build +++ /dev/null @@ -1,44 +0,0 @@ -#! /bin/sh -# -# $Id: calpont-build 421 2007-14-15 15:46:55Z dhill $ -# -# build calpont rpm and install on call6500 -# $1 - release number or 'Latest' -# $2 - svn branch -# -if [ "$2" = "" ] ; then - echo "enter release and svn-branch arguments" - exit 0 -fi -# !!! set for OS type 32 or 64 bit !!! - -OS=x86_64 - -# -REL=$1 -DIR=$2 - -HOME=/home/nightly/$DIR -rm -fr /home/nightly/rpm/* -# -su - nightly -c "cd $HOME;./build/build_rpms -g > ~/$DIR/build_datdup_rpm.log 2>&1" -# -test -d /home/nightly/rpm/RPMS || echo "no rpm, Build Failed" -test -d /home/nightly/rpm/RPMS || exit 1 -cd /home/nightly/rpm/RPMS/$OS/ -test -f calpont-datdup-$version*.rpm || echo "no rpm, Build Failed" -test -f calpont-datdup-$version*.rpm || exit 1 -{ -if [ $REL != "Latest" ] ; then - # copy rpms to calweb - cd /home/nightly/rpm/RPMS/$OS/ - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/$REL/packages;rm calpont-datdup*.$OS.rpm;prompt OFF;mput calpont-datdup*" -else - # copy nightly on calweb - cd /home/nightly/rpm/RPMS/$OS/ - smbclient //calweb/shared -Wcalpont -Uoamuser%Calpont1 -c "cd Iterations/Latest/packages;rm calpont-datdup*.$OS.rpm;prompt OFF;mput calpont-datdup*" -fi -} 2> /root/datdup-build-$REL-$DIR.log -# -echo "Build Successfully Completed" -exit 0 diff --git a/tools/configMgt/dm_parent_installer.sh b/tools/configMgt/dm_parent_installer.sh deleted file mode 100755 index c272bdf3..00000000 --- a/tools/configMgt/dm_parent_installer.sh +++ /dev/null @@ -1,197 +0,0 @@ -#!/usr/bin/expect -# -# $Id$ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set USERNAME [lindex $argv 5] -set CEFLAG [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTPACKAGE1 infinidb-libs-$PACKAGE -set CALPONTPACKAGE2 infinidb-platform-$PACKAGE -if { $CEFLAG == "1" } { - set CALPONTPACKAGE3 " " -} else { - set CALPONTPACKAGE3 infinidb-enterprise-$PACKAGE -} -set MYSQLPACKAGE infinidb-storage-engine-$PACKAGE -set MYSQLDPACKAGE infinidb-mysql-$PACKAGE -set INSTALLDIR "/usr/local" - -set SHARED "//calweb/shared" - -log_user $DEBUG -spawn -noecho /bin/bash -#send "rm -f $CALPONTPACKAGE1 $CALPONTPACKAGE2 $CALPONTPACKAGE3\n" -# -# delete and erase all old packages from Director Module -# -set timeout 10 -send "ssh $USERNAME@$SERVER 'rm -f /root/calpont-*.rpm /root/infinidb*.rpm'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } -} -expect { - -re {[$#] } { } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -# -# erase InfiniDB packages -# -set timeout 60 -send_user "Erase Old InfiniDB Packages " -send "ssh $USERNAME@$SERVER 'pkill -9 mysqld'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re {[$#] } { } -} -send "ssh $USERNAME@$SERVER 'rpm -e --nodeps \$(rpm -qa | grep '^calpont') >/dev/null 2>&1; rpm -e --nodeps \$(rpm -qa | grep '^infinidb-')'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { } - -re {[$#] } { } - -re "not installed" { } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -sleep 10 -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/Calpont/releasenum >/dev/null 2>&1; test -x $INSTALLDIR/Calpont/bin/pre-uninstall && $INSTALLDIR/Calpont/bin/pre-uninstall'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re {[$#] } { send_user "DONE" } - -re "uninstall completed" { send_user "DONE" } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -sleep 5 -# -# get the InfiniDB package -# -send_user "Get InfiniDB Packages " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } -} -send_user "\n" -# -# send the InfiniDB package -# -set timeout 120 -send_user "Copy InfiniDB Packages " -send "scp -q $PACKAGE $USERNAME@$SERVER:/root/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re {[$#] } { send_user "DONE" } - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -#send "rm -f $PACKAGE\n" -# -# install InfiniDB package -# -send_user "Install New InfiniDB Packages " -send "ssh $USERNAME@$SERVER ' rpm -iv --nodeps $CALPONTPACKAGE1 $CALPONTPACKAGE2 $CALPONTPACKAGE3 $MYSQLPACKAGE $MYSQLDPACKAGE'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { expect { - -re "completed" { expect { - -re "completed" { send_user "DONE" } - } - } - } - } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -set timeout 120 -expect -re {[$#] } -# -if { $CONFIGFILE != "NULL"} { - # - # copy over Calpont.xml file - # - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { } - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send_user "Copy InfiniDB Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml.rpmsave\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE"} - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - #do a dummy scp command - send "scp $CONFIGFILE $USERNAME@$SERVER:/tmp/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user " " } - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved InfiniDB Configuration File " - send "ssh $USERNAME@$SERVER 'cd /usr/local/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -# -exit - diff --git a/tools/configMgt/dm_parent_installer_v3.sh b/tools/configMgt/dm_parent_installer_v3.sh deleted file mode 100755 index f76d3fd4..00000000 --- a/tools/configMgt/dm_parent_installer_v3.sh +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/expect -# -# $Id: parent_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set USERNAME [lindex $argv 5] -set CEFLAG [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTPACKAGE calpont-$PACKAGE -set MYSQLPACKAGE calpont-mysql-$PACKAGE -set MYSQLDPACKAGE calpont-mysqld-$PACKAGE -set INSTALLDIR "/usr/local" - -#set SHARED "//cal6500/shared" -set SHARED "//calweb/shared" - -log_user $DEBUG -spawn -noecho /bin/bash -send "rm -f $CALPONTPACKAGE\n" -# -# delete and erase all old packages from Director Module -# -set timeout 10 -send "ssh $USERNAME@$SERVER 'rm -f /root/$CALPONTPACKAGE'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "#" { } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -# -# erase calpont packages -# -set timeout 60 -send_user "Erase Old Calpont Packages " -send "ssh $USERNAME@$SERVER 'pkill -9 mysqld'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { } abort -} -send "ssh $USERNAME@$SERVER 'rpm -e --nodeps \$(rpm -qa | grep '^calpont') >/dev/null 2>&1; rpm -e --nodeps \$(rpm -qa | grep '^infinidb-')'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { } abort - -re "# " { } abort - -re "not installed" { } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -sleep 10 -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/Calpont/releasenum >/dev/null 2>&1; test -x $INSTALLDIR/Calpont/bin/pre-uninstall && $INSTALLDIR/Calpont/bin/pre-uninstall'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { send_user "DONE" } abort - -re "uninstall completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -sleep 5 -# -# get the calpont package -# -send_user "Get Calpont Packages " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the calpont package -# -send_user "Copy Calpont Packages " -send "scp -q $PACKAGE $USERNAME@$SERVER:/root/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re "#" { send_user "DONE" } abort - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -#send "rm -f $PACKAGE\n" -# -# install calpont package -# -set timeout 120 -send_user "Install New Calpont Packages " -send "ssh $USERNAME@$SERVER ' rpm -iv --nodeps /root/$CALPONTPACKAGE'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { expect { - -re "completed" { expect { - -re "completed" { send_user "DONE" } abort - } - } - } - } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -set timeout 120 -expect -re "# " -# -if { $CONFIGFILE != "NULL"} { - # - # copy over Calpont.xml file - # - send_user "Copy Calpont Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml.rpmsave\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { } abort - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send "scp $CONFIGFILE $USERNAME@$SERVER:/tmp/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user " " } abort - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved Calpont Configuration File " - send "ssh $USERNAME@$SERVER 'cd /usr/local/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -# -exit - diff --git a/tools/configMgt/mysql-build-branch b/tools/configMgt/mysql-build-branch deleted file mode 100755 index afa79cd6..00000000 --- a/tools/configMgt/mysql-build-branch +++ /dev/null @@ -1,8 +0,0 @@ -#! /bin/sh -# -# $Id: mysql-build 421 2007-04-05 15:46:55Z dhill $ -# -# build calpont mysql - -su - mysql -c "scripts/build-branch $1" - diff --git a/tools/configMgt/mysql-build-genii b/tools/configMgt/mysql-build-genii deleted file mode 100755 index 4a3f21de..00000000 --- a/tools/configMgt/mysql-build-genii +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -# -# $Id: mysql-build 421 2007-04-05 15:46:55Z dhill $ -# -# build calpont mysql - -su - mysql -c scripts/build-genii - diff --git a/tools/configMgt/parent_binary_installer.sh b/tools/configMgt/parent_binary_installer.sh deleted file mode 100755 index 9253fea3..00000000 --- a/tools/configMgt/parent_binary_installer.sh +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/expect -# -# $Id: parent_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set USERNAME [lindex $argv 5] -set INSTALLDIR [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTPACKAGE infinidb-ent-*$PACKAGE - -set SHARED "//calweb/shared" - -set INSTALLDIRARG " " -set HOME "/root" -if { $USERNAME != "root" } { - set INSTALLDIRARG "--installdir=$INSTALLDIR/Calpont" - set HOME $INSTALLDIR -} - -log_user $DEBUG -spawn -noecho /bin/bash -send "rm -f $PACKAGE\n" -# -# delete binary package on Parent OAM Module -# -set timeout 30 -send_user "Remove Calpont Packages from System " -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/calpont*.gz;rm -f /root/calpont*.rpm;rm -f /root/calpont*.gz'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "DONE\n" -# -# get the calpont package -# -send_user "Get Calpont Packages " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/packages;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the calpont package -# -send_user "Copy Calpont Packages " -send "scp $PACKAGE $USERNAME@$SERVER:$HOME/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -# -# uninstall calpont package -# -send_user "Erase Old Calpont Package " -send "ssh $USERNAME@$SERVER 'pkill -9 mysqld'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { } abort -} -send "ssh $USERNAME@$SERVER 'rpm -e --nodeps \$(rpm -qa | grep '^calpont') >/dev/null 2>&1; rpm -e --nodeps \$(rpm -qa | grep '^infinidb-')'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { } abort - -re "# " { } abort - -re "not installed" { } abort - -re "Failed dependencies" { } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -sleep 10 -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/Calpont/releasenum >/dev/null 2>&1; test -x $INSTALLDIR/Calpont/bin/pre-uninstall && $INSTALLDIR/Calpont/bin/pre-uninstall $INSTALLDIRARG'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { send_user "DONE" } abort - -re "uninstall completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -sleep 5 -# -# install calpont package -# -set timeout 30 -send_user "Install New Calpont Package " -send "ssh $USERNAME@$SERVER 'tar -C $INSTALLDIR --exclude db -zxf $HOME/$CALPONTPACKAGE;cat $INSTALLDIR/Calpont/releasenum'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "release=" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "exiting now" { send_user "FAILED: Error in tar command\n" ; exit -1 } - -} -send_user "\n" -set timeout 30 -send "rm -f $PACKAGE\n" -# -send_user "Run post-install script " -send " \n" -send date\n -send "ssh $USERNAME@$SERVER '$INSTALLDIR/Calpont/bin/post-install $INSTALLDIRARG'\n" -set timeout 10 -expect { - -re "word: " { send "$PASSWORD\n" } abort - -re "passphrase" { send "$PASSWORD\n" } abort -} -set timeout 60 -# check return -expect { - -re "InfiniDB syslog logging not working" { send_user "ERROR: InfiniDB System logging not setup\n" ; exit 1 } - -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } - -re "postConfigure" { send_user "DONE" } abort - -re "# " { send_user "DONE" } abort -} -send_user "\n" -sleep 10 -# -if { $CONFIGFILE != "NULL"} { - # - # copy over Calpont.xml file - # - send_user "Copy Calpont Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:$INSTALLDIR/Calpont/etc/Calpont.xml.rpmsave\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send "scp $CONFIGFILE $USERNAME@$SERVER:$INSTALLDIR/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved Calpont Configuration File " - send "ssh $USERNAME@$SERVER 'cd $INSTALLDIR/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -# -exit - diff --git a/tools/configMgt/parent_binary_installer_v3.sh b/tools/configMgt/parent_binary_installer_v3.sh deleted file mode 100755 index 0b98656a..00000000 --- a/tools/configMgt/parent_binary_installer_v3.sh +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/expect -# -# $Id: parent_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set USERNAME [lindex $argv 5] -set INSTALLDIR [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTPACKAGE calpont-infinidb-ent-*$PACKAGE - -set SHARED "//calweb/shared" - -set INSTALLDIRARG " " -set HOME "/root" -if { $USERNAME != "root" } { - set INSTALLDIRARG "--installdir=$INSTALLDIR/Calpont" - set HOME $INSTALLDIR -} - -log_user $DEBUG -spawn -noecho /bin/bash -send "rm -f $PACKAGE\n" -# -# delete binary package on Parent OAM Module -# -set timeout 30 -send_user "Remove Calpont Packages from System " -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/calpont*.gz;rm -f /root/calpont*.rpm;rm -f /root/calpont*.gz'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "DONE\n" -# -# get the calpont package -# -send_user "Get Calpont Packages " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/packages;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the calpont package -# -send_user "Copy Calpont Packages " -send "scp $PACKAGE $USERNAME@$SERVER:$HOME/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -# -# uninstall calpont package -# -send_user "Erase Old Calpont Package " -send "ssh $USERNAME@$SERVER 'pkill -9 mysqld'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { } abort -} -send "ssh $USERNAME@$SERVER 'rpm -e --nodeps \$(rpm -qa | grep '^calpont') >/dev/null 2>&1; rpm -e --nodeps \$(rpm -qa | grep '^infinidb-')'\n"expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { } abort - -re "# " { } abort - -re "not installed" { } abort - -re "Failed dependencies" { } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -sleep 10 -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/Calpont/releasenum >/dev/null 2>&1; test -x $INSTALLDIR/Calpont/bin/pre-uninstall && $INSTALLDIR/Calpont/bin/pre-uninstall $INSTALLDIRARG'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { send_user "DONE" } abort - -re "uninstall completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -sleep 5 -# -# install calpont package -# -set timeout 30 -send_user "Install New Calpont Package " -send "ssh $USERNAME@$SERVER 'tar -C $INSTALLDIR --exclude db -zxf $HOME/$CALPONTPACKAGE;cat $INSTALLDIR/Calpont/releasenum'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "release=" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "exiting now" { send_user "FAILED: Error in tar command\n" ; exit -1 } - -} -send_user "\n" -set timeout 30 -send "rm -f $PACKAGE\n" -# -send_user "Run post-install script " -send " \n" -send date\n -send "ssh $USERNAME@$SERVER '$INSTALLDIR/Calpont/bin/post-install $INSTALLDIRARG'\n" -set timeout 10 -expect { - -re "word: " { send "$PASSWORD\n" } abort - -re "passphrase" { send "$PASSWORD\n" } abort -} -set timeout 60 -# check return -expect { - -re "InfiniDB syslog logging not working" { send_user "ERROR: InfiniDB System logging not setup\n" ; exit 1 } - -re "Permission denied, please try again" { send_user "ERROR: Invalid password\n" ; exit 1 } - -re "Read-only file system" { send_user "ERROR: local disk - Read-only file system\n" ; exit 1} - -re "Connection refused" { send_user "ERROR: Connection refused\n" ; exit 1 } - -re "closed" { send_user "ERROR: Connection closed\n" ; exit 1 } - -re "No route to host" { send_user "ERROR: No route to host\n" ; exit 1 } - -re "postConfigure" { send_user "DONE" } abort - -re "# " { send_user "DONE" } abort -} -send_user "\n" -sleep 10 -# -if { $CONFIGFILE != "NULL"} { - # - # copy over Calpont.xml file - # - send_user "Copy Calpont Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:$INSTALLDIR/Calpont/etc/Calpont.xml.rpmsave\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send "scp $CONFIGFILE $USERNAME@$SERVER:$INSTALLDIR/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved Calpont Configuration File " - send "ssh $USERNAME@$SERVER 'cd $INSTALLDIR/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -# -exit - diff --git a/tools/configMgt/parent_installer.sh b/tools/configMgt/parent_installer.sh deleted file mode 100755 index 469a5c2a..00000000 --- a/tools/configMgt/parent_installer.sh +++ /dev/null @@ -1,365 +0,0 @@ -#!/usr/bin/expect -# -# $Id: parent_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set timeout 40 -set USERNAME root -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set DEBUG [lindex $argv 5] -set CALPONTPACKAGE infinidb-platform-$PACKAGE -set CALPONTPACKAGE0 infinidb-0$PACKAGE -set CALPONTPACKAGE1 infinidb-1$PACKAGE -set ORACLEPACKAGE infinidb-oracle$PACKAGE -set MYSQLPACKAGE infinidb-storage-engine-$PACKAGE -set MYSQLDPACKAGE infinidb-mysql-$PACKAGE - -set SHARED "//calweb/shared" - -log_user $DEBUG -spawn -noecho /bin/bash -send "rm -f $PACKAGE,$CALPONTPACKAGE0,$CALPONTPACKAGE1,$ORACLEPACKAGE,$MYSQLPACKAGE,$MYSQLDPACKAGE\n" -# -# delete and erase all old packages from Director Module -# -send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.rpm'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "#" { } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -# -# erase calpont-oracle package -# -expect -re "# " -send_user "Erase Old Calpont-Oracle Connector Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches calpont-oracle'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "# " { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -# -# erase infinidb-mysql package -# -expect -re "# " -send_user "Erase Old Calpont-Mysqld Connector Package " -send "ssh $USERNAME@$SERVER 'pkill -9 mysqld'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { } abort -} -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches infinidb-mysql'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "# " { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -# -# erase infinidb-storage-engine package -# -expect -re "# " -send_user "Erase Old Calpont-Mysql Connector Package " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches infinidb-storage-engine'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "# " { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -send "rm -f $PACKAGE\n" -# -# erase calpont package -# -expect -re "# " -send_user "Erase Old Calpont Packages " -send "ssh $USERNAME@$SERVER ' rpm -e --nodeps --allmatches infinidb-libs infinidb-platform infinidb-enterprise'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { send_user "DONE" } abort - -re "# " { send_user "DONE" } abort - -re "not installed" { send_user "WARNING: Package not installed" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -# -# get the calpont package -# -expect -re "# " -send_user "Get Calpont Package " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $CALPONTPACKAGE0'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { - send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $CALPONTPACKAGE1'\n" - expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $CALPONTPACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort - } - } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the calpont package -# -send_user "Copy Calpont Package " -send "scp $CALPONTPACKAGE $USERNAME@$SERVER:/root/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -send "rm -f $PACKAGE\n" -# -# install calpont package -# -expect -re "# " -set timeout 120 -send_user "Install New Calpont Package " -send "ssh $USERNAME@$SERVER ' rpm -ivh /root/$CALPONTPACKAGE'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -set timeout 40 -expect -re "# " -send "rm -f $PACKAGE\n" -# -if { $CONFIGFILE != "NULL"} { - # - # copy over Calpont.xml file - # - send_user "Copy Calpont Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved Calpont Configuration File " - send "ssh $USERNAME@$SERVER 'cd /usr/local/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -# -# get the calpont-oracle package -# -set timeout 40 -expect -re "# " -send_user "Get Calpont-Oracle Connector Package " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $ORACLEPACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "WARNING: $ORACLEPACKAGE not found, skipping\n" } abort - -re "getting" { send_user "DONE\n" - # - # send the calpont-oracle package - # - expect -re "# " - send_user "Copy Calpont-Oracle Connector Package " - send "scp $ORACLEPACKAGE $USERNAME@$SERVER:/root/.\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - # - # install calpont-oracle package - # - send_user "\n" - expect -re "# " - set timeout 120 - send_user "Install Calpont-Oracle Connector Package " - send "ssh $USERNAME@$SERVER ' rpm -ivh /root/$ORACLEPACKAGE'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } - send_user "\n" - } -} -set timeout 40 -expect -re "# " -# -# get the calpont-mysql package -# -send_user "Get Calpont-Mysql Connector Package " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $MYSQLPACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "WARNING: $MYSQLPACKAGE not found, skipping\n" } abort - -re "getting" { send_user "DONE\n" - # - # send the calpont-mysql package - # - expect -re "# " - send_user "Copy Calpont-Mysql Connector Package " - send "scp $MYSQLPACKAGE $USERNAME@$SERVER:/root/.\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - # - # install calpont-mysql package - # - send_user "\n" - expect -re "# " - set timeout 120 - send_user "Install Calpont-Mysql Connector Package " - send "ssh $USERNAME@$SERVER ' rpm -ivh $MYSQLPACKAGE'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } - send_user "\n" - } -} -expect -re "# " -# -# get the infinidb-mysql package -# -send_user "Get Calpont-Mysqld Package " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $MYSQLDPACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "WARNING: $MYSQLDPACKAGE not found, skipping\n" } abort - -re "getting" { send_user "DONE\n" - # - # send the infinidb-mysql package - # - expect -re "# " - send_user "Copy Calpont-Mysqld Package " - send "scp $MYSQLDPACKAGE $USERNAME@$SERVER:.\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - # - # install infinidb-mysql-mysqld package - # - send_user "\n" - expect -re "# " - set timeout 120 - send_user "Install Calpont-Mysqld Package " - send "ssh $USERNAME@$SERVER ' rpm -ivh $MYSQLDPACKAGE'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } - send_user "\n" - } -} -# -exit - diff --git a/tools/configMgt/pm_parent_installer.sh b/tools/configMgt/pm_parent_installer.sh deleted file mode 100755 index 848480eb..00000000 --- a/tools/configMgt/pm_parent_installer.sh +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/expect -# -# $Id: parent_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set USERNAME root -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set PREFIX [lindex $argv 5] -set USERNAME [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTPACKAGE1 infinidb-libs-$PREFIX$PACKAGE -set CALPONTPACKAGE2 infinidb-platform-$PREFIX$PACKAGE -set CALPONTPACKAGE3 infinidb-enterprise-$PREFIX$PACKAGE -set MYSQLPACKAGE infinidb-storage-engine-$PACKAGE -set MYSQLDPACKAGE infinidb-mysql-$PACKAGE -set SHARED "//calweb/shared" -set INSTALLDIR "/usr/local" - -log_user $DEBUG -spawn -noecho /bin/bash -send "rm -f $PACKAGE\n" -# -# delete and erase all old packages from Parent OAM Module -# -set timeout 30 -send "ssh $USERNAME@$SERVER 'rm -f /root/calpont-*.rpm /root/infinidb*.rpm'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } -} -expect { - -re {[$#] } { } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -# -# get the InfiniDB package -# -expect -re {[$#] } -send_user "Get InfiniDB Packages " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } -} -send_user "\n" -# -# send the InfiniDB package -# -set timeout 120 -send_user "Copy InfiniDB Packages " -send "scp -q $PACKAGE $USERNAME@$SERVER:/root/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re {[$#] } { send_user "DONE" } - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -#send "rm -f $PACKAGE\n" -# -# erase InfiniDB package -# -set timeout 60 -expect -re {[$#] } -send_user "Erase Old InfiniDB Package " -send "ssh $USERNAME@$SERVER 'rpm -e --nodeps \$(rpm -qa | grep '^calpont') >/dev/null 2>&1; rpm -e --nodeps \$(rpm -qa | grep '^infinidb-')'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { } - -re {[$#] } { } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -sleep 10 -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/Calpont/releasenum >/dev/null 2>&1; test -x $INSTALLDIR/Calpont/bin/pre-uninstall && $INSTALLDIR/Calpont/bin/pre-uninstall'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re {[$#] } { send_user "DONE" } - -re "uninstall completed" { send_user "DONE" } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -sleep 5 -# -# install InfiniDB package -# -set timeout 160 -send_user "Install New InfiniDB Packages " -send "ssh $USERNAME@$SERVER ' rpm -ivh --nodeps $CALPONTPACKAGE1 $CALPONTPACKAGE2 $CALPONTPACKAGE3'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "File not found" { send_user "FAILED: File not found\n" ; exit -1 } -} -send_user "\n" -set timeout 120 -expect -re {[$#] } -send "rm -f $PACKAGE\n" -# -if { $CONFIGFILE != "NULL"} { - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { } - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - # - # copy over Calpont.xml file - # - send_user "Copy InfiniDB Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml.rpmsave\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE" } - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - #do a dummy scp command - send "scp $CONFIGFILE $USERNAME@$SERVER:/tmp/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user " " } - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved InfiniDB Configuration File " - send "ssh $USERNAME@$SERVER 'cd /usr/local/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -expect -re {[$#] } -# -exit - diff --git a/tools/configMgt/pm_parent_installer_v3.sh b/tools/configMgt/pm_parent_installer_v3.sh deleted file mode 100755 index f11a70aa..00000000 --- a/tools/configMgt/pm_parent_installer_v3.sh +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/expect -# -# $Id: parent_installer.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Parent OAM Installer, copy RPM's and custom OS files from postConfigure script -# Argument 0 - Parent OAM IP address -# Argument 1 - Root Password of Parent OAM Module -# Argument 2 - Calpont Config File -# Argument 3 - Debug flag 1 for on, 0 for off - -set USERNAME root -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set PACKAGE [lindex $argv 2] -set RELEASE [lindex $argv 3] -set CONFIGFILE [lindex $argv 4] -set PREFIX [lindex $argv 5] -set USERNAME [lindex $argv 6] -set DEBUG [lindex $argv 7] - -set CALPONTPACKAGE calpont-$PREFIX$PACKAGE -set MYSQLPACKAGE calpont-mysql-$PACKAGE -set MYSQLDPACKAGE calpont-mysqld-$PACKAGE -#set SHARED "//cal6500/shared" -set SHARED "//calweb/shared" -set INSTALLDIR "/usr/local" - -log_user $DEBUG -spawn -noecho /bin/bash -send "rm -f $PACKAGE\n" -# -# delete and erase all old packages from Parent OAM Module -# -set timeout 30 -send "ssh $USERNAME@$SERVER 'rm -f /root/calpont*.rpm /root/infinidb*.rpm'\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "#" { } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -# -# get the calpont package -# -expect -re "# " -send_user "Get Calpont Packages " -send "smbclient $SHARED -Wcalpont -Uoamuser%Calpont1 -c 'cd Iterations/$RELEASE/;prompt OFF;mget $PACKAGE'\n" -expect { - -re "NT_STATUS_NO_SUCH_FILE" { send_user "FAILED: $PACKAGE not found\n" ; exit -1 } - -re "getting" { send_user "DONE" } abort -} -send_user "\n" -# -# send the calpont package -# -send_user "Copy Calpont Packages " -send "scp -q $PACKAGE $USERNAME@$SERVER:/root/.\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -expect { - -re "#" { send_user "DONE" } abort - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -send_user "\n" -#send "rm -f $PACKAGE\n" -# -# erase calpont package -# -expect -re "# " -send_user "Erase Old Calpont Package " -send "ssh $USERNAME@$SERVER 'rpm -e --nodeps \$(rpm -qa | grep '^calpont') >/dev/null 2>&1; rpm -e --nodeps \$(rpm -qa | grep '^infinidb-')'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "uninstall completed" { } abort - -re "# " { } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -sleep 10 -send "ssh $USERNAME@$SERVER 'rm -f $INSTALLDIR/Calpont/releasenum >/dev/null 2>&1; test -x $INSTALLDIR/Calpont/bin/pre-uninstall && $INSTALLDIR/Calpont/bin/pre-uninstall'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "# " { send_user "DONE" } abort - -re "uninstall completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -sleep 5 -# -# install calpont package -# -set timeout 160 -send_user "Install New Calpont Package " -send "ssh $USERNAME@$SERVER ' rpm -ivh --nodeps /root/$CALPONTPACKAGE'\n" -expect -re "word: " -# password for ssh -send "$PASSWORD\n" -# check return -expect { - -re "completed" { send_user "DONE" } abort - -re "Failed dependencies" { send_user "FAILED: Failed dependencies\n" ; - send_user "\n*** Installation Failed\n" ; - exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } -} -send_user "\n" -set timeout 120 -expect -re "# " -send "rm -f $PACKAGE\n" -# -if { $CONFIGFILE != "NULL"} { - # - # copy over Calpont.xml file - # - send_user "Copy Calpont Configuration File " - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml.rpmsave\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { } abort - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send "scp $CONFIGFILE $USERNAME@$SERVER:/usr/local/Calpont/etc/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user "DONE" } abort - -re "scp" { send_user "FAILED: SCP failure\n" ; exit -1 } - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } - } - send "scp $CONFIGFILE $USERNAME@$SERVER:/tmp/Calpont.xml\n" - expect -re "word: " - # send the password - send "$PASSWORD\n" - expect { - -re "100%" { send_user " " } abort - } -} else { - # - # rename previous installed config file - # - send_user "Copy RPM-saved Calpont Configuration File " - send "ssh $USERNAME@$SERVER 'cd /usr/local/Calpont/etc/;mv -f Calpont.xml Calpont.xml.install;cp -v Calpont.xml.rpmsave Calpont.xml'\n" - expect -re "word: " - # password for ssh - send "$PASSWORD\n" - # check return - expect { - -re "Calpont.xml" { send_user "DONE" } abort - -re "Permission denied, please try again" { send_user "FAILED: Invalid password\n" ; exit -1 } - } -} -send_user "\n" -expect -re "# " -# -exit - diff --git a/tools/configMgt/recreateBranch.sh b/tools/configMgt/recreateBranch.sh deleted file mode 100755 index f00e9f24..00000000 --- a/tools/configMgt/recreateBranch.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/expect -# -# $Id: autoRecreateBranch.sh 421 2007-04-05 15:46:55Z dhill $ -# -set BRANCH [lindex $argv 0] -log_user 1 -spawn -noecho /bin/bash -if { $BRANCH == "-h" } { - send_user "\n" - send_user "'autoRecreateBranch.sh' deletes and recreates source from Branch on a \n" - send_user "development branch\n" - send_user "Usage: autoRecreateBranch.sh 'branch'\n" - send_user " branch - SVN branch name\n" - exit -} - -send_user "\n##### Subsystem: delete build \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/build/branches/$BRANCH -send_user "\n##### Subsystem: delete dbcon \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/dbcon/branches/$BRANCH -send_user "\n##### Subsystem: delete ddlproc \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/ddlproc/branches/$BRANCH -send_user "\n##### Subsystem: delete dmlproc \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/dmlproc/branches/$BRANCH -send_user "\n##### Subsystem: delete dmlib \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/dmlib/branches/$BRANCH -send_user "\n##### Subsystem: delete exemgr \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/exemgr/branches/$BRANCH -send_user "\n##### Subsystem: delete oam \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/oam/branches/$BRANCH -send_user "\n##### Subsystem: delete oamapps \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/oamapps/branches/$BRANCH -send_user "\n##### Subsystem: delete primitives \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/primitives/branches/$BRANCH -send_user "\n##### Subsystem: delete procmgr \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/procmgr/branches/$BRANCH -send_user "\n##### Subsystem: delete procmon \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/procmon/branches/$BRANCH -send_user "\n##### Subsystem: delete snmpd \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/snmpd/branches/$BRANCH -send_user "\n##### Subsystem: delete tools \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/tools/branches/$BRANCH -send_user "\n##### Subsystem: delete utils \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/utils/branches/$BRANCH -send_user "\n##### Subsystem: delete versioning \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/versioning/branches/$BRANCH -send_user "\n##### Subsystem: delete writeengine \n" -exec svn delete -m "deleting branch $BRANCH" http://srvengcm1.calpont.com/svn/genii/writeengine/branches/$BRANCH -send_user "\n##### Make branch $BRANCH \n" -exec ~/genii/build/makeBranch.pl $BRANCH - -send_user "Successfully recreated branch $BRANCH\n" -exit \ No newline at end of file diff --git a/tools/configMgt/remote_command.sh b/tools/configMgt/remote_command.sh deleted file mode 100755 index 80de5111..00000000 --- a/tools/configMgt/remote_command.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/expect -# -# $Id: remote_commend.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - Remote Server Host Name or IP address -# Argument 2 - Remote Server root password -# Argument 3 - Command -# Argument 4 - Good Response -# Argument 5 - Bad Response -# Argument 6 - timeout -# Argument 7 - Debug flag -set stty_init {cols 512 -opost}; -set timeout 30 -set SERVER [lindex $argv 0] -set USERNAME [lindex $argv 1] -set PASSWORD [lindex $argv 2] -set COMMAND [lindex $argv 3] -set GOOD_RESPONSE [lindex $argv 4] -set BAD_RESPONSE [lindex $argv 5] -set timeout [lindex $argv 6] -set DEBUG [lindex $argv 7] -log_user $DEBUG -spawn -noecho /bin/bash -expect -re {[$#] } -# -# send command -# -send "ssh $USERNAME@$SERVER $COMMAND\n" -expect { - -re "authenticity" { send "yes\n" - expect { - timeout { send_user "TIMEOUT\n" ; exit 2 } - -re "word: " { send "$PASSWORD\n" } abort - } - } - timeout { send_user "TIMEOUT\n" ; exit 2 } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit 1 } - -re "Permission denied" { send_user "FAILED: Invalid Password\n" ; exit 1 } - -re "word: " { send "$PASSWORD\n" } abort - -re $GOOD_RESPONSE { send_user " " ; exit 0 } - -re $BAD_RESPONSE { send_user "FAILED\n" ; exit 1 } -} -expect { -# -re $GOOD_RESPONSE exit - timeout { send_user "FAILED-TIMEOUT\n" ; exit 1 } - -re $GOOD_RESPONSE { send_user " " ; exit 0 } - -re $BAD_RESPONSE { send_user "FAILED\n" ; exit 1 } - -re "No such file" { send_user "FAILED\n" ; exit 1 } -} -exit 1 - diff --git a/tools/configMgt/remote_command_test.sh b/tools/configMgt/remote_command_test.sh deleted file mode 100755 index 281b0852..00000000 --- a/tools/configMgt/remote_command_test.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/expect -# -# $Id: remote_commend.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - Remote Server Host Name or IP address -# Argument 2 - Remote Server root password -# Argument 3 - Command -# Argument 4 - Good Response -# Argument 5 - Bad Response -# Argument 6 - timeout -# Argument 7 - Debug flag -set timeout 30 -set USERNAME root -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set COMMAND [lindex $argv 2] -set GOOD_RESPONSE [lindex $argv 3] -set BAD_RESPONSE [lindex $argv 4] -set timeout [lindex $argv 5] -set DEBUG [lindex $argv 6] -log_user $DEBUG -spawn -noecho /bin/bash -expect -re "# " -# -# send command -# -send "ssh $USERNAME@$SERVER $COMMAND\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit } - -re "Permission denied" { send_user "FAILED: Invalid Password\n" ; exit } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { -# -re $GOOD_RESPONSE exit - -re $GOOD_RESPONSE { send_user " " ; exit } - -re $BAD_RESPONSE { send_user "FAILED\n" ; exit } - timeout { send_user "TIMEOUT\n" ; exit } -} -send_user "UNKNOWN RESPONSE\n" -exit - diff --git a/tools/configMgt/remote_scp_get.sh b/tools/configMgt/remote_scp_get.sh deleted file mode 100755 index c8dfe3af..00000000 --- a/tools/configMgt/remote_scp_get.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/expect -# -# $Id: remote_commend.sh 421 2007-04-05 15:46:55Z dhill $ -# -# Remote command execution script to another server -# Argument 1 - Remote Server Host Name or IP address -# Argument 2 - Remote Server root password -# Argument 3 - Command -set timeout 30 -set SERVER [lindex $argv 0] -set PASSWORD [lindex $argv 1] -set FILE [lindex $argv 2] -set USERNAME [lindex $argv 3] -set DEBUG [lindex $argv 4] -log_user $DEBUG -spawn -noecho /bin/bash -# -# send command -# -expect -re {[$#] } -send "scp $USERNAME@$SERVER:$FILE .\n" -expect { - -re "authenticity" { send "yes\n" - expect { - -re "word: " { send "$PASSWORD\n" } abort - } - } - -re "service not known" { send_user "FAILED: Invalid Host\n" ; exit -1 } - -re "word: " { send "$PASSWORD\n" } abort -} -expect { - -re "100%" { send_user "DONE\n" } abort - -re "scp" { send_user "FAILED\n" ; exit -1 } - -re "Permission denied" { send_user "FAILED: Invalid password\n" ; exit -1 } - -re "No such file or directory" { send_user "FAILED: Invalid package\n" ; exit -1 } -} -exit - diff --git a/tools/configMgt/rpm_txt.sh b/tools/configMgt/rpm_txt.sh deleted file mode 100755 index 8988c32f..00000000 --- a/tools/configMgt/rpm_txt.sh +++ /dev/null @@ -1,32 +0,0 @@ -#! /bin/sh -# - -version=$1 -OS=x86_64 - -cd /home/nightly/rpm/ > /dev/null 2>&1 -cd RPMS/$OS/ > /dev/null 2>&1 -test -f infinidb-plafform-$version*.rpm || echo "no rpm" -test -f infinidb-plafform-$version*.rpm || exit -1 -rpm -qi -p infinidb-plafform-$version*.rpm > infinidb-plafform-$OS-rpm-info.txt -echo " " >> infinidb-plafform-$OS-rpm-info.txt -echo "MD5SUM" >> infinidb-plafform-$OS-rpm-info.txt -md5sum infinidb-plafform-$version*.rpm >> infinidb-plafform-$OS-rpm-info.txt -echo " " >> infinidb-plafform-$OS-rpm-info.txt -# -test -f infinidb-storage-engine-*.rpm || echo "no rpm" -test -f infinidb-storage-engine-*.rpm || exit -1 -rpm -qi -p infinidb-storage-engine-*.rpm > infinidb-storage-engine-$OS-rpm-info.txt -echo " " >> infinidb-storage-engine-$OS-rpm-info.txt -echo "MD5SUM" >> infinidb-storage-engine-$OS-rpm-info.txt -md5sum infinidb-storage-engine-*.rpm >> infinidb-storage-engine-$OS-rpm-info.txt -echo " " >> infinidb-storage-engine-$OS-rpm-info.txt -# -test -f infinidb-mysql-*.rpm || echo "no rpm" -test -f infinidb-mysql-*.rpm || exit -1 -rpm -qi -p infinidb-mysql-*.rpm > infinidb-mysql-$OS-rpm-info.txt -echo " " >> infinidb-mysql-$OS-rpm-info.txt -echo "MD5SUM" >> infinidb-mysql-$OS-rpm-info.txt -md5sum infinidb-mysql-*.rpm >> infinidb-mysql-$OS-rpm-info.txt -echo " " >> infinidb-mysql-$OS-rpm-info.txt -# diff --git a/tools/configMgt/stackReleaseChecker.cpp b/tools/configMgt/stackReleaseChecker.cpp deleted file mode 100644 index 5f9d3588..00000000 --- a/tools/configMgt/stackReleaseChecker.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/****************************************************************************************** -* $Id: stackReleaseChecker.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* List of files being updated by configure: -* Calpont/etc/Calpont.xml -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "stdio.h" -#include "ctype.h" -#include - -#include -#include - -#include "liboamcpp.h" -#include "configcpp.h" - -using namespace std; -using namespace oam; -using namespace config; - -int main(int argc, char *argv[]) -{ - Oam oam; - string systemUser = "root"; - string installParentModuleHostName; - string password; - string debug_flag = "1"; - string systemName = "all"; - bool VERBOSE = false; - - Config* sysConfig = Config::makeConfig("./systems/CalpontSystems.xml"); - - for( int i = 1; i < argc; i++ ) - { - if( string("-h") == argv[i] ) { - cout << endl; - cout << "'stackReleaseChecker' retrieves and prints the release installed on a stack." << endl; - cout << endl; - cout << "The list of systems are located in './systems/CalpontSystems.xml" << endl; - cout << endl; - cout << "Usage: stackReleaseChecker [-h][-s system][-v]" << endl; - cout << " -s system-name or leave blank for all systems" << endl; - cout << " -v verbose will give the version numbers" << endl; - exit (0); - } - else if( string("-s") == argv[i] ) { - i++; - if ( argc == i ) { - cout << "ERROR: missing system argument" << endl; - exit(-1); - } - systemName = argv[i]; - } - else if( string("-v") == argv[i] ) - VERBOSE = true; - } - - int systemCount; - try { - systemCount = strtol(sysConfig->getConfig("NetworkConfig", "SystemCount").c_str(), 0, 0); - if ( systemCount == 0 ) { - cout << "ERROR: SystemCount in ./systems/CalpontSystems.xml equal to 0" << endl; - exit(-1); - } - } - catch(...) - { - cout << "ERROR: Problem getting SystemCount from ./systems/CalpontSystems.xml" << endl; - exit(-1); - } - - bool FOUND = false; - for ( int i = 1 ; i < systemCount+1 ; i++) - { - string SystemName = "SystemName" + oam.itoa(i); - string oamParentModule = "OAMParentModule" + oam.itoa(i); - string SystemPassword = "SystemPassword" + oam.itoa(i); - string SystemUser = "SystemUser" + oam.itoa(i); - - string tempSystem; - try { - tempSystem = sysConfig->getConfig("NetworkConfig", SystemName ); - } - catch(...) - { - cout << "ERROR: Problem getting SystemName from ./systems/CalpontSystems.xml" << endl; - exit(-1); - } - - if ( tempSystem == systemName || systemName == "all") { - try { - installParentModuleHostName = sysConfig->getConfig("NetworkConfig", oamParentModule ); - password = sysConfig->getConfig("NetworkConfig", SystemPassword ); - systemUser = sysConfig->getConfig("NetworkConfig", SystemUser ); - FOUND = true; - } - catch(...) - { - cout << "ERROR: Problem getting SystemName from ./systems/CalpontSystems.xml" << endl; - exit(-1); - } - - if ( tempSystem == "unassigned") - continue; - - //get if root or no-root user install - string installDir = "/usr/local"; - if ( systemUser != "root" ) - installDir = "/home/" + systemUser; - - installDir = installDir + "/Calpont"; - - string cmd; - if (!VERBOSE) - cmd = "./remote_command.sh " + installParentModuleHostName + " " + systemUser + " " + password + " 'cat " + installDir + "/releasenum' 'release=' cat: 10 " + debug_flag; - else - cmd = "./remote_command.sh " + installParentModuleHostName + " " + systemUser + " " + password + " '" + installDir + "/bin/calpontConsole getcalpontsoftware' 'tools' Error 10 " + debug_flag; - - cout << "***** Calpont InfiniDB Package Release Information for stack '" << tempSystem << "' *****" << endl << endl; - - system(cmd.c_str()); - - cout << endl; - - cout << "***** Status of stack '" << tempSystem << "' *****" << endl << endl; - - cmd = "./remote_command.sh " + installParentModuleHostName + " " + systemUser + " " + password + " '" + installDir + "/bin/calpontConsole getsystems' dummy Error 10 " + debug_flag; - - system(cmd.c_str()); - - cout << endl << endl; - } - } - - if ( !FOUND ) { - cout << "ERROR: System Name '" + systemName + "' not in ./systems/CalpontSystems.xml" << endl; - exit(-1); - } -} diff --git a/tools/configMgt/svnQuery.cpp b/tools/configMgt/svnQuery.cpp deleted file mode 100644 index d8eb6510..00000000 --- a/tools/configMgt/svnQuery.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/****************************************************************************************** -* $Id: svnQuery.cpp 64 2006-10-12 22:21:51Z dhill $ -* -* -* -******************************************************************************************/ -/** - * @file - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "stdio.h" -#include "ctype.h" -#include -#include -#include -#include "liboamcpp.h" - -using namespace std; -using namespace oam; - -int main(int argc, char *argv[]) -{ - Oam oam; - vector queryDirectory; - vector queryID; - - // get latest set of svn queries -// system("rm -rf /root/genii/ > /dev/null 2>&1"); - system("updateGenii.pl > /dev/null 2>&1"); - - system("rm -rf /home/qa/bldqry/mysql/* > /dev/null 2>&1"); - - string cronFile = "/root/calpontBuildTest"; - unlink(cronFile.c_str()); - - // get query directory list - string topQueryfileName = "/tmp/topQuerydirs"; - string secondQueryfileName = "/tmp/secondQuerydirs"; - string queryfileName = "/home/qa/bldqry/mysql/querydirs"; - - string cmd = "ls /root/genii/mysql/queries/. > " + topQueryfileName; - system(cmd.c_str()); - - ifstream file (topQueryfileName.c_str()); - if (!file) { - cout << " Error: can't open " + topQueryfileName << endl; - exit (-1); - } - - char line[200]; - string topQueryDir; - while (file.getline(line, 200)) - { - topQueryDir = line; - if ( topQueryDir.find("queryTester",0) != string::npos || topQueryDir == "Makefile" ) - continue; - - // only do working queries for now - if ( topQueryDir.find("working",0) == string::npos) - continue; - - string cmd = "ls /root/genii/mysql/queries/" + topQueryDir + "/. > " + secondQueryfileName; - system(cmd.c_str()); - - ifstream file (secondQueryfileName.c_str()); - if (file) { - char line[200]; - string buf; - while (file.getline(line, 200)) - { - buf = line; - if ( buf.empty() ) - continue; - string tempdir = topQueryDir + "/" + buf; - queryDirectory.push_back(tempdir); - } - } - file.close(); - } - - file.close(); - - if ( queryDirectory.size() == 0 ) { - cout << endl << "Error: no query sub-directories located" << endl; - exit (-1); - } - - // get query list for each query directory - int test = 1; - std::vector::iterator pt1 = queryDirectory.begin(); - for( ; pt1 != queryDirectory.end() ; pt1++) - { - string directory = *pt1; - string::size_type pos = directory.find("/",0); - if (pos != string::npos) - { - string setName; - setName = directory.substr(0, pos); - setName = setName + "-"; - setName = setName + directory.substr(pos+1, 200); - - string cmd = "cd /home/qa/bldqry/mysql/;echo " + setName + ".sql > " + oam.itoa(test) + ".txt"; - system(cmd.c_str()); - queryID.push_back(oam.itoa(test)); - test++; - - cmd = "rm -f /home/qa/bldqry/mysql/" + setName + ".sql"; - system(cmd.c_str()); - - cmd = "cat /root/genii/mysql/queries/" + directory + "/*.sql >> /home/qa/bldqry/mysql/" + setName + ".sql"; - system(cmd.c_str()); - } - } - - // setup calpontBuildTest cron job with directories - string cronFileTemplate = "/root/calpontBuildTest.template"; - - ifstream cfile (cronFileTemplate.c_str()); - if (!cfile) { - cout << endl << "Error: " + cronFileTemplate + " not found" << endl; - exit (-1); - } - - vector lines; - string newLine; - string buf; - while (cfile.getline(line, 200)) - { - buf = line; - string::size_type pos = buf.find("buildTester",0); - if (pos != string::npos) - { - newLine = buf; - - pt1 = queryID.begin(); - for( ; pt1 != queryID.end() ; pt1++) - { - newLine.append(" mysql-"); - newLine.append(*pt1); - } - - newLine.append(" mysql-queryTester"); - - buf = newLine; - } - //output to temp file - lines.push_back(buf); - } - - cfile.close(); - - ofstream newFile (cronFile.c_str()); - - //create new file - int fd = open(cronFile.c_str(), O_RDWR|O_CREAT, 0777); - - copy(lines.begin(), lines.end(), ostream_iterator(newFile, "\n")); - newFile.close(); - close(fd); - - cmd = "chmod 777 " + cronFile; - system(cmd.c_str()); - - -} diff --git a/tools/cplogger/Makefile.am b/tools/cplogger/Makefile.am index 222ba7e8..20ef4763 100644 --- a/tools/cplogger/Makefile.am +++ b/tools/cplogger/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -24,8 +24,8 @@ AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) bin_PROGRAMS = cplogger cplogger_SOURCES = main.cpp -cplogger_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -cplogger_LDFLAGS = $(idb_common_ldflags) $(idb_exec_libs) $(idb_common_libs) $(AM_LDFLAGS) +cplogger_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +cplogger_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ $(AM_LDFLAGS) test: diff --git a/tools/cplogger/Makefile.in b/tools/cplogger/Makefile.in index e7f84e66..f5a7a87c 100644 --- a/tools/cplogger/Makefile.in +++ b/tools/cplogger/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = cplogger$(EXEEXT) subdir = tools/cplogger DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -226,8 +216,8 @@ AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) cplogger_SOURCES = main.cpp -cplogger_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -cplogger_LDFLAGS = $(idb_common_ldflags) $(idb_exec_libs) $(idb_common_libs) $(AM_LDFLAGS) +cplogger_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +cplogger_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ $(AM_LDFLAGS) all: all-am .SUFFIXES: diff --git a/tools/cplogger/cplogger.vcxproj b/tools/cplogger/cplogger.vcxproj deleted file mode 100644 index 460fbf46..00000000 --- a/tools/cplogger/cplogger.vcxproj +++ /dev/null @@ -1,257 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {6B8C806F-46F7-412F-9FB1-78DFA505597E} - cplogger - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - false - - - ws2_32.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - - - - \ No newline at end of file diff --git a/tools/cplogger/cplogger.vcxproj.filters b/tools/cplogger/cplogger.vcxproj.filters deleted file mode 100644 index a5aaa3f2..00000000 --- a/tools/cplogger/cplogger.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/tools/cplogger/main.cpp b/tools/cplogger/main.cpp index 8d698bc0..f86f3097 100644 --- a/tools/cplogger/main.cpp +++ b/tools/cplogger/main.cpp @@ -15,10 +15,9 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: main.cpp 2336 2013-06-25 19:11:36Z rdempsey $ -#include -#include +// $Id: main.cpp 1763 2012-04-04 18:20:36Z rdempsey $ #include +#include using namespace std; #include "messageobj.h" @@ -40,6 +39,7 @@ int main(int argc, char** argv) opterr = 0; bool cflg = true; bool wflg = false; + bool iflg = false; unsigned subsysID = 8; //oamcpp while ((c = getopt(argc, argv, "s:cwih")) != EOF) @@ -48,14 +48,17 @@ int main(int argc, char** argv) case 'c': cflg = true; wflg = false; + iflg = false; break; case 'w': cflg = false; wflg = true; + iflg = false; break; case 'i': cflg = false; wflg = false; + iflg = true; break; case 's': subsysID = strtoul(optarg, 0, 0); diff --git a/tools/dbbuilder/Makefile.am b/tools/dbbuilder/Makefile.am index b7699131..fabcf8df 100644 --- a/tools/dbbuilder/Makefile.am +++ b/tools/dbbuilder/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/dbbuilder/Makefile.in b/tools/dbbuilder/Makefile.in index 6c474618..07e812ff 100644 --- a/tools/dbbuilder/Makefile.in +++ b/tools/dbbuilder/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = dbbuilder$(EXEEXT) subdir = tools/dbbuilder DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/dbbuilder/dbbuilder.cpp b/tools/dbbuilder/dbbuilder.cpp index 20977518..9db4fa1a 100644 --- a/tools/dbbuilder/dbbuilder.cpp +++ b/tools/dbbuilder/dbbuilder.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /******************************************************************************* -* $Id: dbbuilder.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: dbbuilder.cpp 1798 2012-05-08 17:59:52Z rdempsey $ * *******************************************************************************/ #include @@ -25,18 +25,12 @@ #include using namespace std; -#include - #include "dbbuilder.h" #include "systemcatalog.h" #include "liboamcpp.h" -#include "configcpp.h" -#include "IDBPolicy.h" - using namespace oam; using namespace dmlpackageprocessor; using namespace dmlpackage; -using namespace idbdatafile; #include "objectidmanager.h" using namespace execplan; @@ -203,45 +197,6 @@ int main(int argc, char* argv[]) return 1; } - //@bug5554, make sure IDBPolicy matches the Calpont.xml config - try - { - string calpontConfigFile(startup::StartUp::installDir() + "/etc/Calpont.xml"); - config::Config* sysConfig = config::Config::makeConfig(calpontConfigFile.c_str()); - string tmp = sysConfig->getConfig("Installation", "DBRootStorageType"); - if (boost::iequals(tmp, "hdfs")) - { - // HDFS is configured - if (!IDBPolicy::useHdfs()) // error install plugin - throw runtime_error("HDFS is not enabled, installPlugin may have failed."); - - else if (!IDBFileSystem::getFs(IDBDataFile::HDFS).filesystemIsUp()) - throw runtime_error("HDFS FS is NULL, check env variables."); - } - } - catch(const exception& ex) - { - string cmd(string("echo 'FAILED: ") + ex.what() + "' > /tmp/dbbuilder.status"); - - if (canWrite) - (void)system(cmd.c_str()); - else - cerr << cmd << endl; - errorHandler(sysCatalogErr, "Build system catalog", ex.what(), false); - return 1; - } - catch(...) - { - string cmd = "echo 'FAILED: HDFS checking.' > /tmp/dbbuilder.status"; - - if (canWrite) - (void)system(cmd.c_str()); - else - cerr << cmd << endl; - errorHandler(sysCatalogErr, "Build system catalog", "HDFS check failed.", false); - return 1; - } - //create an initial oid bitmap file { ObjectIDManager oidm; diff --git a/tools/dbbuilder/dbbuilder.h b/tools/dbbuilder/dbbuilder.h index b0578ebf..926c0e5d 100644 --- a/tools/dbbuilder/dbbuilder.h +++ b/tools/dbbuilder/dbbuilder.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** -* $Id: dbbuilder.h 2122 2013-02-14 14:58:28Z chao $ +* $Id: dbbuilder.h 1763 2012-04-04 18:20:36Z rdempsey $ * ******************************************************************************************/ /** @@ -51,6 +51,7 @@ #include "updatedmlpackage.h" #include "commanddmlpackage.h" #include "dmlpackageprocessor.h" +#include "dmlpackageprocessorfactory.h" #include "insertpackageprocessor.h" #include "deletepackageprocessor.h" #include "commandpackageprocessor.h" diff --git a/tools/dbbuilder/dbbuilder.vcxproj b/tools/dbbuilder/dbbuilder.vcxproj deleted file mode 100644 index cdd73fa0..00000000 --- a/tools/dbbuilder/dbbuilder.vcxproj +++ /dev/null @@ -1,320 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {F767A00A-1063-4C0A-B8E3-A27E3F332724} - dbbuilder - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\utils\startup;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\utils\startup;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\utils\startup;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\utils\startup;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\utils\startup;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dbcon\dmlpackage;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\dbcon\dmlpackageproc;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\joiner;$(SolutionDir)..\utils\rowgroup;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\compress;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\utils\startup;$(SolutionDir)..\utils\querystats;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\utils\threadpool;$(SolutionDir)..\utils\querytele;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - - - - \ No newline at end of file diff --git a/tools/dbbuilder/dbbuilder.vcxproj.filters b/tools/dbbuilder/dbbuilder.vcxproj.filters deleted file mode 100644 index 1e38b2a5..00000000 --- a/tools/dbbuilder/dbbuilder.vcxproj.filters +++ /dev/null @@ -1,33 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/tools/dbbuilder/systemcatalog.cpp b/tools/dbbuilder/systemcatalog.cpp index d4640e48..98e874e0 100644 --- a/tools/dbbuilder/systemcatalog.cpp +++ b/tools/dbbuilder/systemcatalog.cpp @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: systemcatalog.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +// $Id: systemcatalog.cpp 1763 2012-04-04 18:20:36Z rdempsey $ #include #include @@ -29,9 +29,6 @@ using namespace execplan; #include "we_colopcompress.h" using namespace WriteEngine; -#include "resourcemanager.h" -using namespace joblist; - #include "dbbuilder.h" void SystemCatalog::build() @@ -64,122 +61,97 @@ void SystemCatalog::build() // Create SYSTABLE table //------------------------------------------------------------------------------ uint32_t dbRoot = 1; - int compressionType = 0; - uint32_t partition = 0; - uint16_t segment=0; - - ResourceManager rm; - std::map oids; - if( rm.useHdfs() ) - { - compressionType = 2; - oids[OID_SYSTABLE_TABLENAME] = OID_SYSTABLE_TABLENAME; - oids[DICTOID_SYSTABLE_TABLENAME] = DICTOID_SYSTABLE_TABLENAME; - oids[OID_SYSTABLE_SCHEMA] = OID_SYSTABLE_SCHEMA; - oids[DICTOID_SYSTABLE_SCHEMA] = DICTOID_SYSTABLE_SCHEMA; - oids[OID_SYSTABLE_OBJECTID] = OID_SYSTABLE_OBJECTID; - oids[OID_SYSTABLE_CREATEDATE] = OID_SYSTABLE_CREATEDATE; - oids[OID_SYSTABLE_LASTUPDATE] = OID_SYSTABLE_LASTUPDATE; - oids[OID_SYSTABLE_INIT] = OID_SYSTABLE_INIT; - oids[OID_SYSTABLE_NEXT] = OID_SYSTABLE_NEXT; - oids[OID_SYSTABLE_NUMOFROWS] = OID_SYSTABLE_NUMOFROWS; - oids[OID_SYSTABLE_AVGROWLEN] = OID_SYSTABLE_AVGROWLEN; - oids[OID_SYSTABLE_NUMOFBLOCKS] = OID_SYSTABLE_NUMOFBLOCKS; - oids[OID_SYSTABLE_AUTOINCREMENT] = OID_SYSTABLE_AUTOINCREMENT; - } - - fWriteEngine.setTransId(1); - fWriteEngine.setBulkFlag(true); + cout << "Creating SYSTABLE" << endl; cout << "---------------------------------------" << endl; // TableName msg << " Creating TableName column OID: "<< OID_SYSTABLE_TABLENAME; cout << msg.str() << endl; - rc = fWriteEngine.createColumn( txnID, OID_SYSTABLE_TABLENAME, CalpontSystemCatalog::VARCHAR, 40, dbRoot, partition, compressionType ); + rc = fWriteEngine.createColumn( txnID, OID_SYSTABLE_TABLENAME, WriteEngine::VARCHAR, 40, dbRoot ); if (rc) throw runtime_error(msg.str() + ec.errorString(rc)); msg.str(""); msg << " Creating TableName column dictionary"; //Dictionary files cout << msg.str() << endl; - rc = fWriteEngine.createDctnry(txnID, DICTOID_SYSTABLE_TABLENAME, 65, dbRoot, partition, segment, compressionType ); + rc = fWriteEngine.createDctnry(txnID, DICTOID_SYSTABLE_TABLENAME, 65, dbRoot); if (rc) throw runtime_error(msg.str() + ec.errorString(rc)); msg.str(""); // Schema msg << " Creating Schema column OID: "< dbRootCount) dbRoot = 1; -//flush data files - fWriteEngine.flushDataFiles(rc, 1, oids); // save brm msg.str(" BRMWrapper saving state "); diff --git a/tools/dbbuilder/systemcatalog.h b/tools/dbbuilder/systemcatalog.h index d1fbb4fd..c96f013f 100644 --- a/tools/dbbuilder/systemcatalog.h +++ b/tools/dbbuilder/systemcatalog.h @@ -15,7 +15,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -// $Id: systemcatalog.h 2101 2013-01-21 14:12:52Z rdempsey $ +// $Id: systemcatalog.h 1763 2012-04-04 18:20:36Z rdempsey $ /** * @file diff --git a/tools/dbbuilder/tpchpopulate.cpp b/tools/dbbuilder/tpchpopulate.cpp index e53c271f..548bd218 100644 --- a/tools/dbbuilder/tpchpopulate.cpp +++ b/tools/dbbuilder/tpchpopulate.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** -* $Id: tpchpopulate.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: tpchpopulate.cpp 1763 2012-04-04 18:20:36Z rdempsey $ * ******************************************************************************************/ diff --git a/tools/dbbuilder/tpchpopulate.h b/tools/dbbuilder/tpchpopulate.h index 6bc80a28..bae9aae5 100644 --- a/tools/dbbuilder/tpchpopulate.h +++ b/tools/dbbuilder/tpchpopulate.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** -* $Id: tpchpopulate.h 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: tpchpopulate.h 1763 2012-04-04 18:20:36Z rdempsey $ * ******************************************************************************************/ /** diff --git a/tools/dbbuilder/tpchschema.cpp b/tools/dbbuilder/tpchschema.cpp index 02cb3f6c..2aaca6f4 100644 --- a/tools/dbbuilder/tpchschema.cpp +++ b/tools/dbbuilder/tpchschema.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** -* $Id: tpchschema.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: tpchschema.cpp 1763 2012-04-04 18:20:36Z rdempsey $ * ******************************************************************************************/ #include diff --git a/tools/dbbuilder/tpchschema.h b/tools/dbbuilder/tpchschema.h index 3c47fb75..a5788396 100644 --- a/tools/dbbuilder/tpchschema.h +++ b/tools/dbbuilder/tpchschema.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /****************************************************************************************** -* $Id: tpchschema.h 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: tpchschema.h 1763 2012-04-04 18:20:36Z rdempsey $ * ******************************************************************************************/ /** diff --git a/tools/dbloadxml/Makefile.am b/tools/dbloadxml/Makefile.am index 5a50ff3c..4d69d4f6 100644 --- a/tools/dbloadxml/Makefile.am +++ b/tools/dbloadxml/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/dbloadxml/Makefile.in b/tools/dbloadxml/Makefile.in index da17944c..fa3cd148 100644 --- a/tools/dbloadxml/Makefile.in +++ b/tools/dbloadxml/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -60,9 +60,8 @@ bin_PROGRAMS = colxml$(EXEEXT) subdir = tools/dbloadxml DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -155,9 +154,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -199,7 +195,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -213,11 +208,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/dbloadxml/colxml.cpp b/tools/dbloadxml/colxml.cpp index 65a9ed1c..606ac9ea 100644 --- a/tools/dbloadxml/colxml.cpp +++ b/tools/dbloadxml/colxml.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /******************************************************************************* - * $Id: colxml.cpp 2237 2013-05-05 23:42:37Z dcathey $ + * $Id: colxml.cpp 1872 2012-08-01 16:58:23Z dhall $ * ******************************************************************************/ @@ -24,8 +24,6 @@ #include -#include - #include #include #include @@ -51,63 +49,9 @@ int main(int argc, char **argv) setlocale(LC_ALL, ""); WriteEngine::Config::initConfigCache(); // load Calpont.xml config settings - //Bug 6137 - std::string aBulkRoot = WriteEngine::Config::getBulkRoot(); - if (!aBulkRoot.empty()) - { - if (!boost::filesystem::exists(aBulkRoot.c_str())) - { - cout << "Creating directory : " << aBulkRoot < - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {635981B1-9353-4102-935B-177432EDC072} - colxml - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\xml;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\xml;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\xml;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\xml;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB Bulk Load Utility" $(SolutionDir)..\..x64\Release\colxml.exe - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\xml;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - $(SolutionDir)..\utils\winport;%(AdditionalIncludeDirectories) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\dmlib;$(SolutionDir)..\writeengine\xml;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - RequireAdministrator - false - true - true - MachineX64 - - - $(SolutionDir)..\..\signit "InfiniDB Bulk Load Utility" $(SolutionDir)..\..\x64\EnterpriseRelease\colxml.exe - - - - - - - - - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - - - - \ No newline at end of file diff --git a/tools/dbloadxml/colxml.vcxproj.filters b/tools/dbloadxml/colxml.vcxproj.filters deleted file mode 100644 index f2070de6..00000000 --- a/tools/dbloadxml/colxml.vcxproj.filters +++ /dev/null @@ -1,38 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/tools/dbloadxml/inputmgr.cpp b/tools/dbloadxml/inputmgr.cpp index 359db62d..a3f97feb 100644 --- a/tools/dbloadxml/inputmgr.cpp +++ b/tools/dbloadxml/inputmgr.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /******************************************************************************* -* $Id: inputmgr.cpp 2258 2013-05-08 17:33:40Z dcathey $ +* $Id: inputmgr.cpp 2011 2012-10-30 14:16:20Z dcathey $ * *******************************************************************************/ @@ -91,7 +91,7 @@ bool InputMgr::input(int argc, char **argv) std::vector l_tableList; int ch; - while( (ch=getopt(argc,argv,"b:d:s:j:l:e:n:p:t:u:r:c:w:x:hE:C:")) != EOF ) + while( (ch=getopt(argc,argv,"b:d:s:f:j:l:e:n:p:t:u:r:c:w:x:hE:C:")) != EOF ) { switch(ch) { @@ -259,14 +259,28 @@ std::ostream& operator<<(std::ostream& os, const InputMgr& m) i != m.fLoadNames.end(); ++i) os << *i << " "; + // Don't report the enclosedBy or escape characters if not enabled by user + bool bEnclosedByEnabled = false; for (InputMgr::ParmList::const_iterator i = m.fParms.begin(); i != m.fParms.end(); ++i) { - // Don't report the enclosedBy if not enabled by user - if ((i->first == XMLGenData::ENCLOSED_BY_CHAR) && - (i->second.length() < 1)) - continue; + if (i->first == XMLGenData::ENCLOSED_BY_CHAR) + { + if (i->second.length() > 0) + bEnclosedByEnabled = true; + break; + } + } + for (InputMgr::ParmList::const_iterator i = m.fParms.begin(); + i != m.fParms.end(); ++i) + { + if (!bEnclosedByEnabled) + { + if ((i->first == XMLGenData::ENCLOSED_BY_CHAR) || + (i->first == XMLGenData::ESCAPE_CHAR)) + continue; + } os << "\n\t" << i->first << "\t" << i->second; } diff --git a/tools/dbloadxml/inputmgr.h b/tools/dbloadxml/inputmgr.h index f007cbf3..ad347e05 100644 --- a/tools/dbloadxml/inputmgr.h +++ b/tools/dbloadxml/inputmgr.h @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /*********************************************************************** - * $Id: inputmgr.h 2101 2013-01-21 14:12:52Z rdempsey $ + * $Id: inputmgr.h 1763 2012-04-04 18:20:36Z rdempsey $ * ***********************************************************************/ /** @file */ diff --git a/tools/dbloadxml/resource.h b/tools/dbloadxml/resource.h deleted file mode 100644 index e6ada3dc..00000000 --- a/tools/dbloadxml/resource.h +++ /dev/null @@ -1,14 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by colxml.rc - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/tools/ddlcleanup/Makefile.am b/tools/ddlcleanup/Makefile.am index 9cf89990..9ca08e56 100644 --- a/tools/ddlcleanup/Makefile.am +++ b/tools/ddlcleanup/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/ddlcleanup/Makefile.in b/tools/ddlcleanup/Makefile.in index 292bb062..4a2223f1 100644 --- a/tools/ddlcleanup/Makefile.in +++ b/tools/ddlcleanup/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = ddlcleanup$(EXEEXT) subdir = tools/ddlcleanup DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/ddlcleanup/ddlcleanup.vcxproj b/tools/ddlcleanup/ddlcleanup.vcxproj deleted file mode 100644 index 8a8c1720..00000000 --- a/tools/ddlcleanup/ddlcleanup.vcxproj +++ /dev/null @@ -1,324 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {71C00ACF-619C-407D-8A69-995CD27F7809} - ddlcleanup - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;SKIP_IDB_COMPRESSION;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\ddlpackageproc;$(SolutionDir)..\dbcon\ddlpackage;$(SolutionDir)..\writeengine\wrapper;$(SolutionDir)..\writeengine\dictionary;$(SolutionDir)..\writeengine\index;$(SolutionDir)..\dmlib;$(SolutionDir)..\utils\cacheutils;$(SolutionDir)..\writeengine\client;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\utils\ddlcleanup;$(SolutionDir)..\utils\compress;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\funcexp;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - {19142d9e-7660-445c-b85d-98e722dffea5} - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {e95fecb8-1b06-41ff-8e1d-40b7e6841765} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - {4bc37219-e09d-4133-98c4-cf0386657df6} - - - {414a47eb-55e3-4251-99b0-95d86fe5580d} - - - - - - \ No newline at end of file diff --git a/tools/ddlcleanup/ddlcleanup.vcxproj.filters b/tools/ddlcleanup/ddlcleanup.vcxproj.filters deleted file mode 100644 index 8c6cfc79..00000000 --- a/tools/ddlcleanup/ddlcleanup.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/tools/ddldriver/Makefile.am b/tools/ddldriver/Makefile.am deleted file mode 100644 index 4f117a59..00000000 --- a/tools/ddldriver/Makefile.am +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = ddldriver -ddldriver_SOURCES = ddldriver.cpp -ddldriver_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -ddldriver_LDFLAGS = @idb_common_ldflags@ @idb_write_libs@ @idb_common_libs@ @netsnmp_libs@ $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/ddldriver/ddldriver.cpp b/tools/ddldriver/ddldriver.cpp deleted file mode 100644 index a87869ff..00000000 --- a/tools/ddldriver/ddldriver.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: ddldriver.cpp 2101 2013-01-21 14:12:52Z rdempsey $ - -#include -#include -#include -#include -#include -using namespace std; - -#include "ddlpkg.h" -#include "sqlparser.h" -using namespace ddlpackage; - -#include "bytestream.h" -#include "messagequeue.h" -using namespace messageqcpp; - -namespace -{ -void usage() -{ - cout << "usage: ddlriver [-h] schema sql_text" << endl; -} -const string toupper_(const string& in) -{ - string::const_iterator iter = in.begin(); - string::const_iterator end = in.end(); - ostringstream oss; - - while (iter != end) - { - oss << static_cast(toupper(*iter)); - ++iter; - } - - return oss.str(); -} -} - -int main(int argc, char** argv) -{ - int c; - - opterr = 0; - - while ((c = getopt(argc, argv, "h")) != EOF) - switch (c) - { - case 'h': - case '?': - default: - usage(); - return (c == 'h' ? 0 : 1); - break; - } - - if (argc - optind < 2) - { - usage(); - return 1; - } - - string owner(toupper_(argv[optind++])); - - SqlParser parser; - parser.setDefaultSchema(owner); - - string stmtStr(toupper_(argv[optind++])); - parser.Parse(stmtStr.c_str()); - - if (!parser.Good()) - { - cerr << "Failed to parse statement: " << stmtStr << endl; - return 1; - } - - const ParseTree &ptree = parser.GetParseTree(); - SqlStatement& stmt = *ptree.fList[0]; - - stmt.fSessionID = 1; - stmt.fSql = stmtStr; - stmt.fOwner = owner; - - ByteStream bytestream; - bytestream << stmt.fSessionID; - stmt.serialize(bytestream); - MessageQueueClient mq("DDLProc"); - ByteStream::byte b; - string errorMsg; - try - { - mq.write(bytestream); - bytestream = mq.read(); - bytestream >> b; - bytestream >> errorMsg; - } - catch (runtime_error& rex) - { - cerr << "runtime_error in engine: " << rex.what() << endl; - return 1; - } - catch (...) - { - cerr << "uknown error in engine" << endl; - return 1; - } - - if (b != 0) - { - cerr << "DDLProc error: " << errorMsg << endl; - return 1; - } - - return 0; -} - diff --git a/tools/dmldriver/Makefile.am b/tools/dmldriver/Makefile.am deleted file mode 100644 index 5f66bb34..00000000 --- a/tools/dmldriver/Makefile.am +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = dmldriver -dmldriver_SOURCES = dmldriver.cpp tpchrf2.cpp dmlif.cpp -dmldriver_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -dmldriver_LDFLAGS = @idb_common_ldflags@ @idb_write_libs@ @idb_common_libs@ @netsnmp_libs@ $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/dmldriver/dmldriver.cpp b/tools/dmldriver/dmldriver.cpp deleted file mode 100644 index d17b71d5..00000000 --- a/tools/dmldriver/dmldriver.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: dmldriver.cpp 2101 2013-01-21 14:12:52Z rdempsey $ - -//#define NDEBUG -#include -#include -#include -#include -#include -#include -#include -#include -using namespace std; - -#include -#include -using namespace boost; - -#include "tpchrf2.h" -#include "dmlif.h" - -namespace -{ -bool vflg; -bool dflg; - -void usage() -{ - cout << "usage: dmldriver [-vhd] [-c intvl] [-f file] [-s sid] [-t flgs] [-r file] [-p cnt] [sql_text]" << endl; - cout << " -c intvl \tcommit every intvl statements" << endl; - cout << " -f file \tread statements from file (max 15KB/stmt)" << endl; - cout << " -s sid \tset sid as session id" << endl; - cout << " -t flgs \tset trace flags" << endl; - cout << " -v \tdisplay affected row count(s)" << endl; - cout << " -d \tdisplay debug info" << endl; - cout << " -r file \tread orderkeys from file for TPC-H RF2" << endl; - cout << " -p cnt \tpack cnt orderkeys into each delete stmt (only w/ -r)" << endl; - cout << " -e schema\tset the schema name (only w/ -r)" << endl; - cout << " -h \tdisplay this help text" << endl; -} -} - -int main(int argc, char** argv) -{ - int c; - - opterr = 0; - - vflg = false; - dflg = false; - - bool fflg = false; - string infilename; - - int cIntvl = numeric_limits::max(); - - uint32_t sessionID = time(0) & 0x7fffffff; - - bool rflg = false; - - int packCnt = 1; - - uint32_t tflg = 0; - - string schema; - - while ((c = getopt(argc, argv, "e:t:s:c:f:r:p:vhd")) != EOF) - switch (c) - { - case 'v': - vflg = true; - break; - case 'd': - dflg = true; - break; - case 'f': - fflg = true; - infilename = optarg; - break; - case 'c': - cIntvl = static_cast(strtol(optarg, 0, 0)); - break; - case 's': - sessionID = static_cast(strtoul(optarg, 0, 0)); - break; - case 't': - tflg = static_cast(strtoul(optarg, 0, 0)); - break; - case 'r': - rflg = true; - infilename = optarg; - break; - case 'p': - packCnt = static_cast(strtol(optarg, 0, 0)); - break; - case 'e': - schema = optarg; - break; - case 'h': - case '?': - default: - usage(); - return (c == 'h' ? 0 : 1); - break; - } - - if (!fflg && !rflg && ((argc - optind) < 1)) - { - usage(); - return 1; - } - - if (fflg && rflg) - { - cout << "-f and -r are mutually exclusive!" << endl << endl; - usage(); - return 1; - } - - if (!schema.empty() && !rflg) - { - cout << "-e requires -r!" << endl << endl; - usage(); - return 1; - } - - string stmtStr; - if (!fflg && !rflg) - stmtStr = argv[optind++]; - - int rc = 0; - - dmlif::DMLIF dmlif(sessionID, tflg, dflg, vflg); - - if (fflg) - { - ifstream ifs(infilename.c_str()); - if (!ifs.good()) - { - cerr << "Error accessing file " << infilename << endl; - return 1; - } - const streamsize ilinelen = 15 * 1024; - scoped_array iline(new char[ilinelen]); - int cnt = 0; - for (;;) - { - ifs.getline(iline.get(), ilinelen); - if (ifs.eof()) - break; - rc = dmlif.sendOne(iline.get()); - if (rc != 0) - break; - cnt++; - if ((cnt % cIntvl) == 0) - dmlif.sendOne("COMMIT;"); - } - } - else if (rflg) - { - ifstream ifs(infilename.c_str()); - if (!ifs.good()) - { - cerr << "Error accessing file " << infilename << endl; - return 1; - } - if (schema.empty()) - schema = "tpch"; - tpch::RF2 rf2(schema, sessionID, tflg, cIntvl, packCnt, dflg, vflg); - rc = rf2.run(ifs); - } - else - { - rc = dmlif.sendOne(stmtStr); - } - - if (rc == 0) - dmlif.sendOne("COMMIT;"); - - return 0; -} - diff --git a/tools/dmldriver/dmlif.cpp b/tools/dmldriver/dmlif.cpp deleted file mode 100644 index a9094445..00000000 --- a/tools/dmldriver/dmlif.cpp +++ /dev/null @@ -1,333 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: dmlif.cpp 2101 2013-01-21 14:12:52Z rdempsey $ - -//#define NDEBUG -#include -#include -#include -using namespace std; - -#include -using namespace boost; - -#include "vendordmlstatement.h" -#include "calpontdmlpackage.h" -#include "calpontdmlfactory.h" -using namespace dmlpackage; - -#include "bytestream.h" -#include "messagequeue.h" -using namespace messageqcpp; - -#include "simplecolumn.h" -#include "calpontselectexecutionplan.h" -#include "sessionmanager.h" -#include "simplefilter.h" -#include "constantcolumn.h" -#include "constantfilter.h" -using namespace execplan; - -#include "brmtypes.h" - -#include "dmlif.h" -using namespace dmlif; - -namespace dmlif -{ - -DMLIF::DMLIF(uint32_t sessionid, uint32_t tflg, bool dflg, bool vflg) : - fSessionID(sessionid), fTflg(tflg), fDflg(dflg), fVflg(vflg), fOPt(0), fLPt(0) -{ - fMqp.reset(new MessageQueueClient("DMLProc")); -} - -DMLIF::~DMLIF() -{ -} - -int DMLIF::sendOne(const string& stmt) -{ - int rc; - - string tStmt(stmt); - if (*tStmt.rbegin() != ';') - tStmt += ";"; - - VendorDMLStatement dmlStmt(tStmt, fSessionID); - CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); - if (pDMLPackage == 0) - { - cerr << "Failed to parse statement: " << tStmt << endl; - return -1; - } - - string queryString = pDMLPackage->get_QueryString(); - if (fDflg) cout << "qs: >" << queryString << '<' << endl; - - string dmlStatement = pDMLPackage->get_DMLStatement(); - if (fDflg) cout << "DML: " << dmlStatement << endl; - bool isDML = true; - if (dmlStatement == "COMMIT" || dmlStatement == "ROLLBACK") - { - isDML = false; - } - - if (isDML) - { - char_separator sep(" "); - tokenizer > tok(queryString, sep); - tokenizer >::iterator iter = tok.begin(); - idbassert(iter != tok.end()); - string where = *iter; ++iter; - idbassert(iter != tok.end()); - string col1 = *iter; ++iter; - idbassert(iter != tok.end()); - string op = *iter; ++iter; - idbassert(iter != tok.end()); - string col2 = *iter; ++iter; - idbassert(iter == tok.end()); - if (fDflg) cout << "SQL: " << pDMLPackage->get_SQLStatement() << endl; - if (fDflg) cout << "hf: " << pDMLPackage->HasFilter() << endl; - DMLTable* tp = pDMLPackage->get_Table(); - if (fDflg) cout << "sn: " << tp->get_SchemaName() << " tn: " << tp->get_TableName() << endl; - if (fDflg) cout << "row count: " << tp->get_RowList().size() << endl; - SRCP srcp(new SimpleColumn(tp->get_SchemaName(), tp->get_TableName(), col1, fSessionID)); - CalpontSelectExecutionPlan::ColumnMap cm; - cm.insert(make_pair(col1, srcp)); - pDMLPackage->get_ExecutionPlan()->columnMap(cm); - CalpontSelectExecutionPlan::ReturnedColumnList rcl; - rcl.push_back(srcp); - pDMLPackage->get_ExecutionPlan()->returnedCols(rcl); - pDMLPackage->get_ExecutionPlan()->sessionID(fSessionID); - pDMLPackage->get_ExecutionPlan()->traceFlags(fTflg); - SessionManager sm; - BRM::TxnID txnid = sm.getTxnID(fSessionID); - if (!txnid.valid) - txnid = sm.newTxnID(fSessionID); - pDMLPackage->get_ExecutionPlan()->txnID(txnid.id); - pDMLPackage->get_ExecutionPlan()->verID(sm.verID()); - ParseTree* pt = new ParseTree(); - ReturnedColumn* rc1 = srcp->clone(); - ReturnedColumn* rc2 = new ConstantColumn(col2, ConstantColumn::NUM); - SOP sop(new Operator(op)); - SimpleFilter* sf = new SimpleFilter(sop, rc1, rc2); - pt->data(sf); - pDMLPackage->get_ExecutionPlan()->filters(pt); - if (fDflg) cout << "ep: " << *pDMLPackage->get_ExecutionPlan() << endl; - } - - ByteStream bytestream; - pDMLPackage->write(bytestream); - delete pDMLPackage; - ByteStream::octbyte rows; - - rc = DMLSend(bytestream, rows); - - if (isDML && fVflg) - cout << rows << " rows affected" << endl; - - return rc; -} - -int DMLIF::DMLSend(ByteStream& bytestream, ByteStream::octbyte& rows) -{ - ByteStream::byte b; - string errorMsg; - try - { - fMqp->connect(); - fMqp->write(bytestream); - bytestream = fMqp->read(); - fMqp->shutdown(); - if (fDflg) cout << "read " << bytestream.length() << " bytes from DMLProc" << endl; - bytestream >> b; - if (fDflg) cout << "b = " << (int)b << endl; - bytestream >> rows; - if (fDflg) cout << "rows = " << rows << endl; - bytestream >> errorMsg; - if (fDflg) cout << "errorMsg = " << errorMsg << endl; - } - catch (runtime_error& rex) - { - cerr << "runtime_error in engine: " << rex.what() << endl; - return -1; - } - catch (...) - { - cerr << "uknown error in engine" << endl; - return -1; - } - - if (b != 0) - { - cerr << "DMLProc error: " << errorMsg << endl; - return -1; - } - - return 0; -} - -void DMLIF::rf2Start(const string& sn) -{ - fSchema = sn; - fOFilterStr = ""; - fLFilterStr = ""; - fOPt = 0; - fLPt = 0; -} - -void DMLIF::rf2Add(int64_t okey) -{ - ostringstream oss; - oss << okey; - string okeyStr(oss.str()); - - if (fOFilterStr.empty()) - { - fOFilterStr = "o_orderkey=" + okeyStr; - ReturnedColumn* rc1 = new SimpleColumn(fSchema, "orders", "o_orderkey", fSessionID); - ReturnedColumn* rc2 = new ConstantColumn(okeyStr, ConstantColumn::NUM); - SOP sop(new Operator("=")); - ConstantFilter* cf = new ConstantFilter(sop, rc1, rc2); - sop.reset(new Operator("or")); - cf->op(sop); - fOPt = new ParseTree(cf); - } - else - { - fOFilterStr += " or o_orderkey=" + okeyStr; - ReturnedColumn* rc1 = new SimpleColumn(fSchema, "orders", "o_orderkey", fSessionID); - ReturnedColumn* rc2 = new ConstantColumn(okeyStr, ConstantColumn::NUM); - SOP sop(new Operator("=")); - ConstantFilter* cf = dynamic_cast(fOPt->data()); - cf->pushFilter(new SimpleFilter(sop, rc1, rc2)); - } - if (fLFilterStr.empty()) - { - fLFilterStr = "l_orderkey=" + okeyStr; - ReturnedColumn* rc1 = new SimpleColumn(fSchema, "lineitem", "l_orderkey", fSessionID); - ReturnedColumn* rc2 = new ConstantColumn(okeyStr, ConstantColumn::NUM); - SOP sop(new Operator("=")); - ConstantFilter* cf = new ConstantFilter(sop, rc1, rc2); - sop.reset(new Operator("or")); - cf->op(sop); - fLPt = new ParseTree(cf); - } - else - { - fLFilterStr += " or l_orderkey=" + okeyStr; - ReturnedColumn* rc1 = new SimpleColumn(fSchema, "lineitem", "l_orderkey", fSessionID); - ReturnedColumn* rc2 = new ConstantColumn(okeyStr, ConstantColumn::NUM); - SOP sop(new Operator("=")); - ConstantFilter* cf = dynamic_cast(fLPt->data()); - cf->pushFilter(new SimpleFilter(sop, rc1, rc2)); - } -} - -int DMLIF::rf2Send() -{ - if (fOFilterStr.empty()) - return -1; - - int rc = 0; - string dmlstr; - dmlstr = "delete from " + fSchema + ".orders where " + fOFilterStr + ';'; - if (fDflg) cout << dmlstr << endl; - - VendorDMLStatement dmlStmt(dmlstr, fSessionID); - CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); - if (pDMLPackage == 0) - { - cerr << "Failed to parse statement: " << dmlstr << endl; - return -1; - } - - SRCP srcp(new SimpleColumn(fSchema, "orders", "o_orderkey", fSessionID)); - CalpontSelectExecutionPlan::ColumnMap cm; - cm.insert(make_pair("o_orderkey", srcp)); - pDMLPackage->get_ExecutionPlan()->columnMap(cm); - CalpontSelectExecutionPlan::ReturnedColumnList rcl; - rcl.push_back(srcp); - pDMLPackage->get_ExecutionPlan()->returnedCols(rcl); - pDMLPackage->get_ExecutionPlan()->sessionID(fSessionID); - pDMLPackage->get_ExecutionPlan()->traceFlags(fTflg); - SessionManager sm; - BRM::TxnID txnid = sm.getTxnID(fSessionID); - if (!txnid.valid) - txnid = sm.newTxnID(fSessionID); - pDMLPackage->get_ExecutionPlan()->txnID(txnid.id); - pDMLPackage->get_ExecutionPlan()->verID(sm.verID()); - pDMLPackage->get_ExecutionPlan()->filters(fOPt); - if (fDflg) cout << "ep: " << *pDMLPackage->get_ExecutionPlan() << endl; - - ByteStream bytestream; - pDMLPackage->write(bytestream); - delete pDMLPackage; - pDMLPackage = 0; - ByteStream::octbyte rows = 0; - - rc = DMLSend(bytestream, rows); - - if (fVflg) - cout << rows << " rows affected" << endl; - - dmlstr = "delete from " + fSchema + ".lineitem where " + fLFilterStr + ';'; - if (fDflg) cout << dmlstr << endl; - - VendorDMLStatement dmlStmt1(dmlstr, fSessionID); - pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt1); - if (pDMLPackage == 0) - { - cerr << "Failed to parse statement: " << dmlstr << endl; - return -1; - } - - srcp.reset(new SimpleColumn(fSchema, "lineitem", "l_orderkey", fSessionID)); - cm.clear(); - cm.insert(make_pair("l_orderkey", srcp)); - pDMLPackage->get_ExecutionPlan()->columnMap(cm); - rcl.clear(); - rcl.push_back(srcp); - pDMLPackage->get_ExecutionPlan()->returnedCols(rcl); - pDMLPackage->get_ExecutionPlan()->sessionID(fSessionID); - pDMLPackage->get_ExecutionPlan()->traceFlags(fTflg); - txnid = sm.getTxnID(fSessionID); - if (!txnid.valid) - txnid = sm.newTxnID(fSessionID); - pDMLPackage->get_ExecutionPlan()->txnID(txnid.id); - pDMLPackage->get_ExecutionPlan()->verID(sm.verID()); - pDMLPackage->get_ExecutionPlan()->filters(fLPt); - if (fDflg) cout << "ep: " << *pDMLPackage->get_ExecutionPlan() << endl; - - bytestream.reset(); - pDMLPackage->write(bytestream); - delete pDMLPackage; - pDMLPackage = 0; - rows = 0; - - rc = DMLSend(bytestream, rows); - - if (fVflg) - cout << rows << " rows affected" << endl; - - return 0; -} - -} - diff --git a/tools/dmldriver/dmlif.h b/tools/dmldriver/dmlif.h deleted file mode 100644 index b5e0fa79..00000000 --- a/tools/dmldriver/dmlif.h +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: dmlif.h 2101 2013-01-21 14:12:52Z rdempsey $ - -#ifndef DMLIF_H__ -#define DMLIF_H__ - -#include -#include -#include - -#include "messagequeue.h" -#include "expressionparser.h" - -namespace dmlif -{ - -class DMLIF -{ -public: - DMLIF(uint32_t sessionid, uint32_t tflg=0, bool dflg=false, bool vflg=false); - ~DMLIF(); - - int sendOne(const std::string& stmt); - - void rf2Start(const std::string& sn); - void rf2Add(int64_t okey); - int rf2Send(); - -protected: - int DMLSend(messageqcpp::ByteStream& bytestream, messageqcpp::ByteStream::octbyte& rows); - -private: - //DMLIF(const DMLIF& rhs); - //DMLIF& operator=(const DMLIF& rhs); - - uint32_t fSessionID; - uint32_t fTflg; - bool fDflg; - bool fVflg; - - boost::scoped_ptr fMqp; - - std::string fSchema; - std::string fOFilterStr; - std::string fLFilterStr; - - execplan::ParseTree* fOPt; - execplan::ParseTree* fLPt; -}; - -} - -#endif - diff --git a/tools/dmldriver/tpchrf2.cpp b/tools/dmldriver/tpchrf2.cpp deleted file mode 100644 index 18c62fde..00000000 --- a/tools/dmldriver/tpchrf2.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: tpchrf2.cpp 2101 2013-01-21 14:12:52Z rdempsey $ - -#include -using namespace std; - -#include -#include -using namespace boost; - -#include "tpchrf2.h" -#include "dmlif.h" - -namespace tpch -{ - -RF2::RF2(const string& sn, uint32_t sid, uint32_t tflg, int c, int p, bool d, bool v) : - fSchema(sn), fSessionID(sid), fTflg(tflg), fIntvl(c), fPack(p), fDflg(d), fVflg(v) -{ -} - -RF2::~RF2() -{ -} - -int RF2::run(istream& in) -{ - const streamsize ilinelen = 1024; - scoped_array iline(new char[ilinelen]); - int cnt = 0; - dmlif::DMLIF dmlif(fSessionID, fTflg, fDflg, fVflg); - for (;;) - { - dmlif.rf2Start(fSchema); - for (int i = 0; i < fPack; i++) - { - in.getline(iline.get(), ilinelen); - if (in.eof()) - break; - typedef char_separator cs; - typedef tokenizer tk; - cs sep("|"); - tk tok(string(iline.get()), sep); - tk::iterator iter = tok.begin(); - idbassert(iter != tok.end()); - string keystr = *iter; ++iter; - //idbassert(iter == tok.end()); - int64_t okey = strtol(keystr.c_str(), 0, 0); - dmlif.rf2Add(okey); - } - dmlif.rf2Send(); - cnt++; - if ((cnt % fIntvl) == 0) - dmlif.sendOne("COMMIT;"); - if (in.eof()) - break; - } - dmlif.sendOne("COMMIT;"); - return 0; -} - -} diff --git a/tools/dmldriver/tpchrf2.h b/tools/dmldriver/tpchrf2.h deleted file mode 100644 index 74e6c3f0..00000000 --- a/tools/dmldriver/tpchrf2.h +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: tpchrf2.h 2101 2013-01-21 14:12:52Z rdempsey $ - -#ifndef TPCHRF2_H__ -#define TPCHRF2_H__ - -#include -#include -#include -#include -#include - -namespace tpch -{ - -class RF2 -{ -public: - RF2(const std::string& sn, uint32_t sid, uint32_t tflg=0, int c=std::numeric_limits::max(), - int p=1, bool d=false, bool v=false); - ~RF2(); - - int run(std::istream& in); - -private: - //RF2(const RF2& rhs); - //RF2& operator=(const RF2& rhs); - - std::string fSchema; - uint32_t fSessionID; - uint32_t fTflg; - int fIntvl; - int fPack; - bool fDflg; - bool fVflg; -}; - -} - -#endif diff --git a/tools/editem/Makefile.am b/tools/editem/Makefile.am index f07ed169..c226ab7c 100644 --- a/tools/editem/Makefile.am +++ b/tools/editem/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/editem/Makefile.in b/tools/editem/Makefile.in index 460b342f..0f31aeea 100644 --- a/tools/editem/Makefile.in +++ b/tools/editem/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = editem$(EXEEXT) subdir = tools/editem DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/editem/editem.cpp b/tools/editem/editem.cpp index 47dedaab..e363e281 100644 --- a/tools/editem/editem.cpp +++ b/tools/editem/editem.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: editem.cpp 2336 2013-06-25 19:11:36Z rdempsey $ +* $Id: editem.cpp 2092 2013-01-09 20:53:52Z rdempsey $ */ #include @@ -66,7 +66,6 @@ bool aflg = false; bool fflg = false; bool vflg = false; bool mflg = false; -bool uflg = false; struct SortExtentsByPartitionFirst { @@ -128,7 +127,6 @@ void usage(const string& pname) " -t \tdisplay min/max values as dates" << endl << " -s \tdisplay min/max values as timestamps" << endl << " -a \tdisplay min/max values as char strings" << endl << - " -u \tdisplay min/max values as unsigned integers" << endl << " -x \tcreate/extend one or more oids" << endl << " -e oid \tdelete oid" << endl << " -r oid \trollback or delete extents" << endl << @@ -180,13 +178,6 @@ const string fmt(int64_t v) { oss << v; } - else if (uflg) - { - if (static_cast(v) > numeric_limits::max() - 2) - oss << "notset"; - else - oss << static_cast(v); - } else { if (v == numeric_limits::max() || @@ -199,27 +190,6 @@ const string fmt(int64_t v) return oss.str(); } -//------------------------------------------------------------------------------ -// Check to see if the latest read operation from stdin was successful. -// Primarily used to validate the case where we have prompted the user for -// more than 1 parameter. Ex: we are validating that the user correctly -// formatted the input to enter 3 values separated by spaces (1 2 3) in- -// stead of accidentally separating with commas (1,2,3). -//------------------------------------------------------------------------------ -//@bug 4914: Validate that correct number of input parameters is given -bool isInputValid() -{ - if (cin.good()) - return true; - - cin.clear(); - cin.ignore( numeric_limits::max(),'\n'); - cout << endl << "Invalid input; try again, be sure to enter spaces " - "between input parameters." << endl << endl; - - return false; -} - //------------------------------------------------------------------------------ // Dump all the extents for the specified OID //------------------------------------------------------------------------------ @@ -253,7 +223,7 @@ int dumpone(OID_t oid, unsigned int sortOrder) end = entries.end(); while (iter != end) { - uint32_t lbidRangeSize = iter->range.size * 1024; + u_int32_t lbidRangeSize = iter->range.size * 1024; max = iter->partition.cprange.hi_val; min = iter->partition.cprange.lo_val; seqNum = iter->partition.cprange.sequenceNum; @@ -263,7 +233,19 @@ int dumpone(OID_t oid, unsigned int sortOrder) if ( iter->colWid > 0 ) { cout << "Col OID = " << oid << ", NumExtents = " << - entries.size() << ", width = " << iter->colWid << endl; + entries.size() << ", width = " << iter->colWid; + if (vflg) { + uint32_t partNum; + uint16_t segNum; + uint16_t dbRoot; + HWM_t hwm; + CHECK(emp->getLastLocalHWM( + oid,dbRoot,partNum,segNum,hwm)); + cout << "; LastLocalHWM: DBRoot-" << dbRoot << + ", part#-" << partNum << ", seg#-" << segNum << + ", HWM-" << hwm; + } + cout << endl; colWidth = iter->colWid; } else @@ -387,7 +369,7 @@ int clearAllCPData() cpInfo.min = numeric_limits::max(); cpInfo.seqNum = -1; - for (uint32_t i=0; i< ranges.size(); i++) { + for (uint i=0; i< ranges.size(); i++) { BRM::LBIDRange r=ranges.at(i); cpInfo.firstLbid = r.start; vCpInfo.push_back(cpInfo); @@ -434,7 +416,7 @@ int extendOids( ) uint32_t partNum; uint16_t segNum; OID_t oid; - uint32_t colWidth; + u_int32_t colWidth; char DictStoreOIDFlag; vector cols; @@ -449,12 +431,7 @@ int extendOids( ) cout << "Enter OID, DBRoot, and Partition#, and Segment# " "(separated by spaces): "; - while (1) - { - cin >> oid >> dbRoot >> partNum >> segNum; - if (isInputValid()) - break; - } + cin >> oid >> dbRoot >> partNum >> segNum; CHECK(emp->createDictStoreExtent ( oid, dbRoot, partNum, segNum, lbid, allocd)); @@ -472,49 +449,22 @@ int extendOids( ) { while (1) { - bool bFinished = false; - - while (1) - { - cout << "Enter OID and column width (separated by spaces); " - "0 OID represents end of list: "; - cin >> oid >> colWidth; - if (oid == 0) - { - bFinished = true; - break; - } - - if (isInputValid()) - break; - } - if (bFinished) - break; + cout << "Enter OID and column width (separated by spaces); " + "0 OID represents end of list: "; + cin >> oid >> colWidth; + if (oid == 0) break; CreateStripeColumnExtentsArgIn colArg; colArg.oid = oid; colArg.width = colWidth; - if (uflg) - { - colArg.colDataType = execplan::CalpontSystemCatalog::UBIGINT; - } - else - { - colArg.colDataType = execplan::CalpontSystemCatalog::BIGINT; - } cols.push_back( colArg ); } vector newExtents; - while (1) - { - cout << "Enter DBRoot and partition# (partition " - "only used for empty DBRoot): "; - cin >> dbRoot >> partNum; - if (isInputValid()) - break; - } + cout << "Enter DBRoot and partition# (partition " + "only used for empty DBRoot): "; + cin >> dbRoot >> partNum; CHECK(emp->createStripeColumnExtents(cols, dbRoot, partNum, segNum, newExtents)); @@ -553,29 +503,18 @@ int rollbackExtents(OID_t oid) if ((DictStoreOIDFlag == 'y') || (DictStoreOIDFlag == 'Y')) { - unsigned int hwmCount = 0; + unsigned int hwmCount; vector segNums; vector hwms; - while (1) - { - cout <<"Enter DBRoot#, part#, and the number of HWMs to be entered " - "(separated by spaces): "; - cin >> dbRoot >> partNum >> hwmCount; - if (isInputValid()) - break; - } + cout << "Enter DBRoot#, part#, and the number of HWMs to be entered " + "(separated by spaces): "; + cin >> dbRoot >> partNum >> hwmCount; for (unsigned int k=0; k> segNum >> hwm; - if (isInputValid()) - break; - } - + cout << "Enter seg# and HWM for a last extent " << + "(separated by spaces): "; + cin >> segNum >> hwm; hwms.push_back(hwm); segNums.push_back(segNum); } @@ -585,14 +524,9 @@ int rollbackExtents(OID_t oid) } else { - while (1) - { - cout << "Enter DBRoot#, part#, seg#, and HWM for the last extent " - "on that DBRoot (separated by spaces): "; - cin >> dbRoot >> partNum >> segNum >> hwm; - if (isInputValid()) - break; - } + cout << "Enter DBRoot#, part#, seg#, and HWM for the last extent " + "on that DBRoot (separated by spaces): "; + cin >> dbRoot >> partNum >> segNum >> hwm; CHECK(emp->rollbackColumnExtents_DBroot( oid, false, dbRoot, partNum, segNum, hwm )); @@ -635,15 +569,9 @@ int editHWM(OID_t oid) uint32_t partNum = 0; uint16_t segNum = 0; - while (1) - { - cout << "Enter Partition#, and Segment# (separated by spaces): "; - cin >> partNum >> segNum; - if (isInputValid()) - break; - } - int extState; - CHECK(emp->getLocalHWM(oid, partNum, segNum, oldHWM, extState)); + cout << "Enter Partition#, and Segment# (separated by spaces): "; + cin >> partNum >> segNum; + CHECK(emp->getLocalHWM(oid, partNum, segNum, oldHWM)); cout << "HWM for partition " << partNum << " and segment " << segNum << " is currently " << oldHWM << @@ -737,7 +665,7 @@ int main(int argc, char** argv) opterr = 0; - while ((c = getopt(argc, argv, "dzCc:o:tsxue:r:fvhw:lb:aimp:S:")) != EOF) + while ((c = getopt(argc, argv, "dzCc:o:tsxe:r:fvhw:lb:aimp:S:")) != EOF) switch (c) { case 'd': @@ -760,9 +688,6 @@ int main(int argc, char** argv) case 't': tflg = true; break; - case 'u': - uflg = true; - break; case 's': sflg = true; break; @@ -835,24 +760,18 @@ int main(int argc, char** argv) emp = new DBRM(); - if (!emp->isDBRMReady()) - { - cerr << endl << "Error! The DBRM is currently not responding!" << endl - << "editem can't continue" << endl << endl; - return 1; - } - MaxOID = -1; - if (localModuleType != "um") - { - ObjectIDManager oidm; - MaxOID = oidm.size(); - } - - if (emp->isReadWrite() != ERR_OK) - { - cerr << endl << "Warning! The DBRM is currently in Read-Only mode!" << endl - << "Updates will not propagate!" << endl << endl; - } + MaxOID = -1; + if (localModuleType != "um") + { + ObjectIDManager oidm; + MaxOID = oidm.size(); + } + + if (emp->isReadWrite() != ERR_OK) + { + cerr << endl << "Warning! The DBRM is currently in Read-Only mode!" << endl + << "Updates will not propagate!" << endl << endl; + } if (iflg) { @@ -870,9 +789,9 @@ int main(int argc, char** argv) return 1; } - if ((int)sflg + (int)tflg + (int)aflg + (int)uflg > 1) + if ((int)sflg + (int)tflg + (int)aflg > 1) { - cerr << "Only one of s/t/a/u can be specified." << endl; + cerr << "Only one of s/t/a can be specified." << endl; usage(pname); return 1; } diff --git a/tools/editem/editem.vcxproj b/tools/editem/editem.vcxproj deleted file mode 100644 index 9784c61c..00000000 --- a/tools/editem/editem.vcxproj +++ /dev/null @@ -1,312 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {E9417C0B-D839-46E2-A2A8-439E6087E873} - editem - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\dataconvert;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - - - - \ No newline at end of file diff --git a/tools/editem/editem.vcxproj.filters b/tools/editem/editem.vcxproj.filters deleted file mode 100644 index 4520f535..00000000 --- a/tools/editem/editem.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/tools/evalidx/Makefile.am b/tools/evalidx/Makefile.am deleted file mode 100644 index 0385ead0..00000000 --- a/tools/evalidx/Makefile.am +++ /dev/null @@ -1,25 +0,0 @@ -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = evalidx -evalidx_SOURCES = evalidx.cpp -evalidx_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -evalidx_LDFLAGS = @idb_common_ldflags@ -ldmlpackageproc -lexecplan -ljoblist -lrowgroup -lwriteengine -lbrm \ --ldataconvert -lcacheutils -ldmlpackage -lmessageqcpp -lloggingcpp -lconfigcpp -lrwlock -l@boost_thread_lib@ -lxml2 \ --ljoiner -loamcpp -lsnmpmanager -l@boost_filesystem_lib@ -l@boost_date_time_lib@ @netsnmp_libs@ -lmulticast -lfuncexp \ -$(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/evalidx/checkidx.py b/tools/evalidx/checkidx.py deleted file mode 100755 index ec43e45b..00000000 --- a/tools/evalidx/checkidx.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/python - -import os, sys, glob, shutil, xml.dom.minidom - -def find_paths(): - - """Find DBRoot and BulkRoot.""" - try: - config_file = os.environ['CALPONT_CONFIG_FILE'] - except KeyError: - try: - config_file = '/usr/local/Calpont/etc' - os.lstat(config_file) - except: - sys.exit('No config file available') - - - xmldoc = xml.dom.minidom.parse(config_file) - bulk_node = xmldoc.getElementsByTagName('BulkRoot')[0] - db_node = xmldoc.getElementsByTagName('DBRoot')[0] - - bulk_dir = bulk_node.childNodes[0].nodeValue - data_dir = db_node.childNodes[0].nodeValue - - return (bulk_dir, data_dir) - - -def validate_indexes(job_file): - index_files = [] - xmldoc = xml.dom.minidom.parse(job_file) - - for index_node in xmldoc.getElementsByTagName('Index'): - curTreeOid = index_node.getAttribute('iTreeOid') - curListOid = index_node.getAttribute('iListOid') - curMapOid = index_node.getAttribute('mapOid') - curIdxCmdArg = ' -t ' + curTreeOid + ' -l ' + curListOid + ' -v -c ' + curMapOid + ' -b 4' + ' > idxCol_' + curMapOid+'.out' -# print curIdxCmd -# exec_cmd( genii + '/tools/evalidx/evalidx', curIdxCmd ) - index_files.append( curIdxCmdArg ) - - return index_files - -def exec_cmd(cmd, args): - """Execute command using subprocess module or if that fails, - use os.system - """ - - try: - import subprocess - - try: - retcode = call(cmd + " "+args, shell=True) - if retcode < 0: - print >>sys.stderr, "Child was terminated by signal", -retcode - sys.exit(-1) - - else: - print >>sys.stderr, "Child returned", retcode - - except OSError, e: - - print >>sys.stderr, "Execution failed:", e - sys.exit(-1) - except: - res = os.system(cmd+' '+args) - if res: - sys.exit( res ) - - - -def main(): - """ - Validate indexes.. - """ - - if not os.access('.', os.W_OK): - os.chdir('/tmp') - print 'Changing to /tmp to have permission to write files' - - if len(os.getenv('LD_LIBRARY_PATH'))<5: - print 'Suspicous LD_LIBRARY_PATH: %s'%os.getenv('LD_LIBRARY_PATH') - - home = os.getenv('HOME') - genii = home+'/genii' - - (bulkroot, dbroot) = find_paths() - - if len(glob.glob(bulkroot+'/job/Job_300.xml')) == 0: - sys.exit("No Job_300.xml exist ") - - indexes = validate_indexes(bulkroot+'/job/Job_300.xml') - for idxCmdArg in indexes: - print idxCmdArg - exec_cmd( genii + '/tools/evalidx/evalidx', idxCmdArg ) - - -## the following line allows either interactive use or module import -if __name__=="__main__": main() diff --git a/tools/evalidx/evalidx.cpp b/tools/evalidx/evalidx.cpp deleted file mode 100644 index 46a28156..00000000 --- a/tools/evalidx/evalidx.cpp +++ /dev/null @@ -1,355 +0,0 @@ -/**************************************************************** - * $Id$ - * - ***************************************************************/ - -/** @file - * Validataion tool for index validation - * - * This tool is to validate the index tree and list structure. It starts - * from the index tree file, walk through the tree structure until it hits - * a leaf node, then locates the index list block based on the leaf pointer. - * It continues to get all the RIDs for that index key, and also goes to - * the column OID file to validate the column value with the index key. - */ - -#include -#include -#include -#include -#include -#include -using namespace std; - -#include - -#include "bytestream.h" -using namespace messageqcpp; - -#include "dmlpackageprocessor.h" -using namespace dmlpackageprocessor; - -#include "writeengine.h" -#include "we_indextree.h" -using namespace WriteEngine; - -#include "configcpp.h" -using namespace config; - -#include "dm.h" - -/** Debug macro */ -#define _DEBUG 0 -#if _DEBUG -#define DEBUG cout -#else -#define DEBUG if (0) cout -#endif - -namespace { - -const streamsize entrysize = sizeof(IdxBitTestEntry); -const streamsize subbloacksize = SUBBLOCK_TOTAL_BYTES; -const streamsize listHdrSize = sizeof(IdxRidListHdr); -uint32_t treeOID, listOID; -uint32_t colOID = 0; -uint32_t columnSize = 0; -ifstream indexTreeFile, indexListFile, columnFile; -bool vFlag = false; -bool nFlag = false; -int64_t keyNumber = 0; -FILE *pFile; -IndexList indexList; -u_int64_t keyvalue; -int totalRids = 0; - -void usage() -{ - cout << "evalidx [-h] -t OID -l OID [-v -c OID -b colSize -k keyvalue -n ]" << endl; - cout << "\t-h display this help" << endl; - cout << "\t-t OID index tree" << endl; - cout << "\t-l OID index list" << endl; - cout << "\t-v validate index value (need to go with -c and -b)" << endl; - cout << "\t-c OID column" << endl; - cout << "\t-b column size in number of byte (default = 4)" << endl; - cout << "\t-k keyvalue to return index list header for this key" << endl; - cout << "\t-n read RID from tree design" << endl; -} - -int oid2file(uint32_t oid, string& filename) -{ -//ITER17_Obsolete -// This code and this program is obsolete at this point since we are not -// currently supporting indexes. This function and it's use of getFileName -// needs to be changed, if we ever resurrect this program, since getFileName -// now normally requires the DBRoot, partition, and segment number in -// addition to the OID. -#if 0 - FileOp fileOp; - char file_name[WriteEngine::FILE_NAME_SIZE]; - if (fileOp.getFileName(oid, file_name) == WriteEngine::NO_ERROR) - { - filename = file_name; - return 0; - } - else - { - cerr << "WriteEngine::FileOp::getFileName() error!" << endl; - return -1; - } -#endif - return 0; -} - -int validateValue(WriteEngine::RID rid, int64_t key) -{ - int64_t byteoffset = rid * columnSize; - ByteStream::byte inbuf[columnSize]; - int64_t colVal = 0; - - columnFile.seekg(byteoffset, ios::beg); - columnFile.read(reinterpret_cast(inbuf), columnSize); - memcpy(&colVal, inbuf, columnSize); - if (key != colVal) - { - cerr << "rowid: " << rid << endl - << "index: " << key << endl - << "column: " << colVal << endl; - return 1; - } - return 0; -} - -void walkBlock (streamsize byteoffset) -{ - int64_t newByteoffset = 0; - int fbo; - int groupNo; - ByteStream::byte inbuf[entrysize]; - ByteStream::byte listHdr[listHdrSize]; - IdxBitTestEntry *entry; - IdxRidListHdr *hdrEntry; - IdxRidListHdrSize* hdrSize; - - // get group number - indexTreeFile.seekg(byteoffset, ios::beg); - indexTreeFile.read(reinterpret_cast(inbuf), entrysize); - if (indexTreeFile.eof()) return; - entry = (IdxBitTestEntry *) inbuf; - groupNo = entry->group; - - // continue to walk next stage if not leaf node for each entry in the group - for (int i = 0; i < 1 << groupNo; i++) - { - indexTreeFile.seekg(byteoffset, ios::beg); - indexTreeFile.read(reinterpret_cast(inbuf), entrysize); - if (indexTreeFile.eof()) return; - entry = (IdxBitTestEntry *) inbuf; - byteoffset += entrysize; - - DEBUG << ": fbo=" << (int)entry->fbo << - " sbid=" << entry->sbid << " sbentry=" << entry->entry << - " group=" << entry->group << " bittest=" << entry->bitTest << - " type=" << entry->type << endl; - - if (entry->type == WriteEngine::EMPTY_ENTRY || - entry->type == WriteEngine::EMPTY_LIST || - entry->type == WriteEngine::EMPTY_PTR) - continue; - - // convert lbid to real fob number - uint16_t dbRoot; - uint32_t partition; - uint16_t segment; - BRMWrapper::getInstance()->getFboOffset(entry->fbo, dbRoot, partition, segment, fbo); - newByteoffset = ((int64_t)fbo)*BLOCK_SIZE+entry->sbid*subbloacksize+entry->entry*entrysize; - - if (entry->type > 6) - { - cerr << "invalid type= " << entry->type << endl; - cerr << "fbo= " << fbo << " sbid= " << entry->sbid << " entry= " << entry->entry << endl; - throw runtime_error("invalid type of tree block"); - } - - // stop walking index tree if leaf node. go walk index list then - if (entry->type == LEAF_LIST) - { - keyNumber++; - IdxEmptyListEntry listPtr; - int size, rc; - CommBlock cbList; - - listPtr.fbo = entry->fbo; - listPtr.sbid = entry->sbid; - listPtr.entry = entry->entry; - - indexListFile.seekg(newByteoffset, ios::beg); - indexListFile.read(reinterpret_cast(listHdr), listHdrSize); - hdrEntry = reinterpret_cast(listHdr); - hdrSize = reinterpret_cast(listHdr); - DEBUG << "\nkey= " << hdrEntry->key - << " rowsize= " << hdrSize->size; - - // add feather for Jean. print out list header for a given key value - if (keyvalue == hdrEntry->key) - { - cerr << "fbo= " << listPtr.fbo - << " sbid= " << listPtr.sbid - << " entry= " << listPtr.entry - << " key : " << keyvalue << endl; - } - - cbList.file.oid = listOID; - cbList.file.pFile = pFile; - //WriteEngine::RID ridArray[MAX_BLOCK_ENTRY*10]; - int rSize = 0; - rSize = hdrSize->size; - WriteEngine::RID* ridArray = new WriteEngine::RID[rSize]; - size = 0; - if (!nFlag) - rc = indexList.getRIDArrayFromListHdr(cbList, hdrEntry->key, &listPtr, ridArray, size); - else - rc = indexList.getRIDArrayFromListHdrNarray(cbList, hdrEntry->key, &listPtr, ridArray, size, true); - totalRids = totalRids + size; - if (rc) - { - cerr << "Get RID array failed for index block: " << rc << endl; - cerr << "new byte offset= " << newByteoffset << endl; - cerr << "file good? " << indexListFile.good() << endl; - cerr << "fbo= " << listPtr.fbo - << " sbid= " << listPtr.sbid - << " entry= " << listPtr.entry << endl; - for (int64_t j = 0; j < size; j++) - cerr << " " << ridArray[j] << endl; - throw runtime_error("Get RID array failed"); - } - - if (hdrSize->size != static_cast(size)) - { - cerr << "row size not match with list header" << endl; - cerr << "fbo= " << listPtr.fbo - << " sbid= " << listPtr.sbid - << " entry= " << listPtr.entry << endl; - for (int64_t j = 0; j < size; j++) - cerr << " " << ridArray[j] << endl; - throw runtime_error("row size not match with list header"); - } - - for (int64_t j = 0; j < size; j++) - { - DEBUG << " " << ridArray[j] << endl; - - // validate column value with the index value - if (vFlag) - idbassert(validateValue(ridArray[j], hdrEntry->key) == 0); - } - delete [] ridArray; - } - else - walkBlock(newByteoffset); - } - -} - -} - -int main(int argc, char* argv[]) -{ - int c; - int i; - string filename; - - while ((c = getopt(argc, argv, "ntlhbcvk")) != EOF) - switch (c) - { - case 't': - treeOID = atoi(argv[optind]); - if (oid2file(treeOID, filename)) return 1; - DEBUG << "tree: " << filename << endl; - indexTreeFile.open(filename.c_str()); - break; - case 'l': - listOID = atoi(argv[optind]); - if (oid2file(listOID, filename)) return 1; - DEBUG << "list: " << filename << endl; - - indexListFile.open(filename.c_str()); - pFile = fopen(filename.c_str(), "rb"); - if (!pFile) - { - cerr << "Invalid OID " << listOID << " for index list" << endl; - exit(1); - } - break; - case 'v': - vFlag = true; - break; - case 'c': - colOID = atoi(argv[optind]); - if (oid2file(colOID, filename)) return 1; - DEBUG << "column: " << filename << endl; - columnFile.open(filename.c_str()); - break; - case 'b': - columnSize = atoi(argv[optind]); - break; - case 'k': - keyvalue = atoi(argv[optind]); - break; - case 'h': - usage(); - return 0; - break; - case 'n': - nFlag = true; - break; - default: - usage(); - return 1; - break; - } - - if ((argc - optind) < 1) - { - usage(); - return 1; - } - - if (argc < 5) - { - usage(); - return 1; - } - - if (vFlag && (colOID == 0 || columnSize == 0)) - { - cerr << "Please provide both -c and -b option if -v is indicated." << endl; - usage(); - return 1; - } - - if (vFlag && !columnFile.good()) - { - cerr << "Bad column OID" << endl; - return 1; - } - - if (!indexTreeFile.good() || !indexListFile.good()) - { - cerr << "Bad index OIDs" << endl; - return 1; - } - - - // walk through the index tree file - for (i = 0; i < 32; i++) - walkBlock (0 * BLOCK_SIZE + 1 * subbloacksize + i * entrysize); - - cout << "\n" << keyNumber << " index value validated!" << endl; - cout << "Total RIDs for this column=" << totalRids << endl; - indexListFile.close(); - indexTreeFile.close(); - fclose(pFile); - return 0; -} - diff --git a/tools/fixdate/fixdate.cpp b/tools/fixdate/fixdate.cpp deleted file mode 100644 index 3b48d068..00000000 --- a/tools/fixdate/fixdate.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/* -* $Id: fixdate.cpp 2101 2013-01-21 14:12:52Z rdempsey $ -* -*/ - -#include -#include -#include -#include -#include -#include -using namespace std; - -#include - -#include -#include -using namespace boost; - -#include "bytestream.h" -using namespace messageqcpp; - -#include "dmlpackageprocessor.h" -using namespace dmlpackageprocessor; - -namespace { - -const streamsize blkSz = 8192; - -void usage() -{ -} - -u_int64_t fixDate(ByteStream& bs, ostream& out) -{ - ByteStream fixed; - ByteStream::quadbyte o; - u_int64_t cnt = 0; -#if 0 - DMLPackageProcessor::Date minDate; - DMLPackageProcessor::Date maxDate; - minDate.year = 1992; - minDate.month = 1; - minDate.day = 2; - maxDate.year = 1998; - maxDate.month = 12; - maxDate.day = 25; - ByteStream::quadbyte mxd; - ByteStream::quadbyte mnd; - mxd = *(reinterpret_cast(&maxDate)); - mnd = *(reinterpret_cast(&minDate)); -#endif - DMLPackageProcessor::Date fixDate; - fixDate.spare = 0; - ByteStream::quadbyte f; - while (bs.length() > 0) - { - bs >> o; - if (o >= 0xfffffffe) - { - fixed << o; - continue; - } - f = o & 0xffff; - fixDate.year = f; - o >>= 16; - f = o & 0xf; - fixDate.month = f; - o >>= 4; - f = o & 0x3f; - fixDate.day = f; - //o >>= 6; - o = *(reinterpret_cast(&fixDate)); - fixed << o; -#if 0 - cout << DMLPackageProcessor::dateToString(o) << endl; - idbassert(o >= mnd && o <= mxd); - cnt++; -#endif - } - out << fixed; - return cnt; -} - -} - -int main(int argc, char* argv[]) -{ - int c; - - opterr = 0; - - while ((c = getopt(argc, argv, "h")) != EOF) - switch (c) - { - case 'h': - usage(); - return 0; - break; - default: - usage(); - return 1; - break; - } - - if ((argc - optind) < 1) - { - usage(); - return 1; - } - - ByteStream bs; - - ifstream ifs(argv[optind + 0]); - ByteStream::byte inbuf[blkSz]; - streampos fLen; - u_int64_t blkNo = 0; - - ifs.seekg(0, ios_base::end); - fLen = ifs.tellg(); - ifs.seekg(0, ios_base::beg); - - idbassert((fLen % blkSz) == 0); - u_int64_t numBlks = fLen / blkSz; - cout << numBlks << " blocks to fix..." << endl; - - ofstream ofs("fixdate.cdf"); - - cout << "pct done: " << setw(3); - - for(;;) - { - - ifs.read(reinterpret_cast(inbuf), blkSz); - if (ifs.eof()) break; - bs.load(inbuf, blkSz); - - fixDate(bs, ofs); - cout << "\b\b\b" << setw(3) << (u_int64_t)(blkNo * 100 / numBlks); - //cout << setw(3) << (u_int64_t)(blkNo * 100 / numBlks) << endl; - - blkNo++; - } - - cout << "\b\b\b" << setw(3) << 100 << endl; - //cout << setw(3) << 100 << endl; - - return 0; -} - diff --git a/tools/getConfig/Makefile.am b/tools/getConfig/Makefile.am index 4635adf2..c3b8aa7d 100644 --- a/tools/getConfig/Makefile.am +++ b/tools/getConfig/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in @@ -24,8 +24,8 @@ AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) bin_PROGRAMS = getConfig getConfig_SOURCES = main.cpp -getConfig_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -getConfig_LDFLAGS = $(idb_common_ldflags) $(idb_exec_libs) $(idb_common_libs) $(AM_LDFLAGS) +getConfig_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +getConfig_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ $(AM_LDFLAGS) test: diff --git a/tools/getConfig/Makefile.in b/tools/getConfig/Makefile.in index 207ff0cb..f564cf9f 100644 --- a/tools/getConfig/Makefile.in +++ b/tools/getConfig/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = getConfig$(EXEEXT) subdir = tools/getConfig DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -226,8 +216,8 @@ AM_CFLAGS = $(idb_cflags) AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = $(idb_ldflags) getConfig_SOURCES = main.cpp -getConfig_CPPFLAGS = $(idb_common_includes) $(AM_CPPFLAGS) -getConfig_LDFLAGS = $(idb_common_ldflags) $(idb_exec_libs) $(idb_common_libs) $(AM_LDFLAGS) +getConfig_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) +getConfig_LDFLAGS = @idb_common_ldflags@ @idb_common_libs@ $(AM_LDFLAGS) all: all-am .SUFFIXES: diff --git a/tools/getConfig/getConfig.vcxproj b/tools/getConfig/getConfig.vcxproj deleted file mode 100644 index f1320007..00000000 --- a/tools/getConfig/getConfig.vcxproj +++ /dev/null @@ -1,251 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {1F7BEFE7-87AC-4FB1-97E3-3472A578F0A3} - getConfig - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\loggingcpp;%(AdditionalIncludeDirectories) - MultiThreadedDLL - true - Level3 - ProgramDatabase - false - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - - - - \ No newline at end of file diff --git a/tools/getConfig/getConfig.vcxproj.filters b/tools/getConfig/getConfig.vcxproj.filters deleted file mode 100644 index a5aaa3f2..00000000 --- a/tools/getConfig/getConfig.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/tools/getConfig/main.cpp b/tools/getConfig/main.cpp index 3555a8bd..a4bcbb5a 100644 --- a/tools/getConfig/main.cpp +++ b/tools/getConfig/main.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /***************************************************************************** -* $Id: main.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: main.cpp 1927 2012-09-13 16:27:42Z rdempsey $ * *****************************************************************************/ #include @@ -24,11 +24,6 @@ #include using namespace std; -#include "logger.h" -#include "loggingid.h" -#include "messagelog.h" -#include -#include #include "configcpp.h" using namespace config; @@ -40,8 +35,6 @@ void usage(const string& pname) cout << "usage: " << pname << " [-vh] [-c config_file] section param" << endl << " Displays configuration variable param from section section." << endl << " -c config_file use config file config_file" << endl << - " -a display all configuration values" << endl << - " -i display all configuration values in .ini-file format (implies -a)" << endl << " -v display verbose information" << endl << " -h display this help text" << endl; } @@ -54,12 +47,10 @@ int main(int argc, char** argv) string pname(argv[0]); bool vflg = false; string configFile; - bool aflg = false; - bool iflg = false; opterr = 0; - while ((c = getopt(argc, argv, "c:vaih")) != EOF) + while ((c = getopt(argc, argv, "c:vh")) != EOF) switch (c) { case 'v': @@ -68,12 +59,6 @@ int main(int argc, char** argv) case 'c': configFile = optarg; break; - case 'a': - aflg = true; - break; - case 'i': - iflg = aflg = true; - break; case 'h': case '?': default: @@ -82,73 +67,25 @@ int main(int argc, char** argv) break; } - if (!aflg && ( (argc - optind) < 2 )) + if ((argc - optind) < 2) { usage(pname); return 1; } - try - { - openlog("getConfig", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER); - Config* cf; - if (configFile.length() > 0) - cf = Config::makeConfig(configFile); - else - cf = Config::makeConfig(); + Config* cf; + if (configFile.length() > 0) + cf = Config::makeConfig(configFile); + else + cf = Config::makeConfig(); - if (vflg) - { - cout << "Using config file: " << cf->configFile() << endl; - } + if (vflg) + { + cout << "Using config file: " << cf->configFile() << endl; + } - if (aflg) - { - vector secs; - vector parms; - secs = cf->enumConfig(); - vector::iterator siter; - vector::iterator send; - vector::iterator piter; - vector::iterator pend; - siter = secs.begin(); - send = secs.end(); - while (siter != send) - { - if (iflg) - cout << '[' << *siter << ']' << endl; - parms = cf->enumSection(*siter); - piter = parms.begin(); - pend = parms.end(); - while (piter != pend) - { - if (iflg) - cout << *piter << " = " << cf->getConfig(*siter, *piter) << endl; - else - cout << *siter << '.' << *piter << " = " << - cf->getConfig(*siter, *piter) << endl; - ++piter; - } - ++siter; - if (iflg) - cout << endl; - } - return 0; - } + cout << cf->getConfig(argv[optind + 0], argv[optind + 1]) << endl; - cout << cf->getConfig(argv[optind + 0], argv[optind + 1]) << endl; - closelog(); - } - catch(exception &e) - { - syslog(LOG_ERR, "Exception in getConfig for %s %s : %s", argv[optind + 0], argv[optind + 1], e.what()); - closelog(); - } - catch(...) - { - syslog(LOG_ERR, "Exception in getConfig for %s %s : Unknown exception", argv[optind + 0], argv[optind + 1]); - closelog(); - } return 0; } diff --git a/tools/hdfsCheck/hdfsCheck.cpp b/tools/hdfsCheck/hdfsCheck.cpp deleted file mode 100644 index c3af93e7..00000000 --- a/tools/hdfsCheck/hdfsCheck.cpp +++ /dev/null @@ -1,774 +0,0 @@ -/* - * foptest.cc - * - * Created on: Jul 17, 2012 - * Author: rtw - */ - -#include -#include -#ifndef _MSC_VER -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "IDBDataFile.h" -#include "IDBFileSystem.h" -#include "IDBPolicy.h" -using namespace idbdatafile; -using namespace std; - -size_t BLK_SIZE=2048; -const size_t MAX_BLK_SIZE=1048576; -size_t MAX_BLOCK=1024; - -int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) -{ - /* Perform the carry for the later subtraction by updating y. */ - if (x->tv_usec < y->tv_usec) { - int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; - y->tv_usec -= 1000000 * nsec; - y->tv_sec += nsec; - } - if (x->tv_usec - y->tv_usec > 1000000) { - int nsec = (y->tv_usec - x->tv_usec) / 1000000; - y->tv_usec += 1000000 * nsec; - y->tv_sec -= nsec; - } - /* Compute the time remaining to wait. - tv_usec is certainly positive. */ - result->tv_sec = x->tv_sec - y->tv_sec; - result->tv_usec = x->tv_usec - y->tv_usec; - - /* Return 1 if result is negative. */ - return x->tv_sec < y->tv_sec;} - -void usage() -{ - cerr << "usage: hdfsCheck [-b:n:t:r:] " << endl; - cerr << " Required Arguments" << endl; - cerr << " - path to the HDFS plugin to be loaded" << endl; - cerr << " Options" << endl; - cerr << " -b block size in bytes" << endl; - cerr << " -n number of blocks to write/read" << endl; - cerr << " -t how long to retry (in secs.) until we give up (default=30)" << endl; - cerr << " -r number of dbroot directories to check (default=0)" << endl; -} - -struct foptest_opts -{ - string pluginFile; - size_t blockSize; - int numBlocks; - int timeout; - int numDbRoots; - - foptest_opts() : - pluginFile(""), - blockSize(BLK_SIZE), - numBlocks(64), - timeout(30), - numDbRoots(0) - {;} -}; - -class TestRunner -{ -public: - TestRunner(int id, const foptest_opts& opts); - ~TestRunner(); - - bool runTest( IDBDataFile::Types filetype, unsigned open_opts ); - - const foptest_opts& runOpts() const { return m_opts; } - -private: - bool fillDefault(); - bool writeBlock(unsigned int blocknum, unsigned char* buf, unsigned char tag); - bool writeBlocks(unsigned int blocknum, unsigned char* buf, unsigned char tag, unsigned int count); - bool readBlock(unsigned int blocknum, unsigned char* buf, unsigned char tag); - bool readBlocks(unsigned int blocknum, unsigned char* buf, unsigned char tag, unsigned int count); - - bool readTest( IDBDataFile::Types filetype ); - bool openByModeStrTest(); - bool writeTest( IDBDataFile::Types filetype ); - bool rdwrTest( IDBDataFile::Types filetype ); - bool hdfsRdwrExhaustTest(); - bool openWF( bool reopen=false ); - bool openRF(); - - void reset(); - - enum LogLevel { - INFO, - ERROR - }; - void logMsg( LogLevel level, const string& msg ); - - string m_fname; - foptest_opts m_opts; - unsigned char m_defbuf[MAX_BLK_SIZE]; - IDBDataFile* m_file; - unsigned m_open_opts; - int m_id; -}; - -TestRunner::TestRunner(int id, const foptest_opts& opts) : - m_opts(opts), - m_file(NULL), - m_open_opts(0), - m_id(id) -{ - for( unsigned i = 0; i < BLK_SIZE; i++ ) - { - m_defbuf[i] = 0xfe; - } -} - -void TestRunner::reset() -{ - delete m_file; - m_file = 0; -} - -struct TestCleanup -{ - TestCleanup( IDBDataFile::Types type, const string& dir, const string& file ) : - m_fs( IDBFileSystem::getFs( type ) ), - m_dir(dir), - mm_file(file) {} - - ~TestCleanup() - { - if( m_fs.exists( mm_file.c_str() ) ) - m_fs.remove(mm_file.c_str()); - assert( !m_fs.exists( mm_file.c_str() ) ); - if( m_fs.exists( m_dir.c_str() ) ) - m_fs.remove(m_dir.c_str()); - assert( !m_fs.exists( m_dir.c_str() ) ); - } - - IDBFileSystem& m_fs; - string m_dir; - string mm_file; -}; - -bool TestRunner::runTest( IDBDataFile::Types filetype, unsigned open_opts ) -{ - m_open_opts = open_opts; - ostringstream infostr; - infostr << "Running test for file type " - << ( filetype == IDBDataFile::UNBUFFERED ? "Unbuffered" : - ( filetype == IDBDataFile::BUFFERED ? "Buffered" : "HDFS" ) ); - logMsg( INFO, infostr.str() ); - - IDBFileSystem& fs = IDBFileSystem::getFs( filetype ); - - // build the file name we are going to use - ostringstream oss; - // embed pid so that this is a new directory path - oss << "/tmp/idbdf-dir-" << getpid() << "-" << m_id; - string dir = oss.str(); - m_fname = dir + "/foobar"; - - // instantiate this here so that we always clean up files we created no matter - // where we exit the function from - boost::scoped_ptr cleanup( new TestCleanup( filetype, dir, m_fname ) ); - - logMsg( INFO, "Running writeTest" ); - bool returnval = true; - returnval = writeTest( filetype ); - - if( !returnval ) - { - return false; - } - - // going to check the size two different ways - once through the file and - // once through the file system. - unsigned fsize = m_file->size(); - if( fsize != m_opts.numBlocks * BLK_SIZE ) - { - ostringstream errstr; - errstr << "bad file size from file " << fsize << " != " << m_opts.numBlocks * BLK_SIZE << "!"; - logMsg( ERROR, errstr.str() ); - return false; - } - - // this deletes and closes the file - required to get accurate file size with - // buffered IO and in HDFS from the file system - reset(); - fsize = fs.size(m_fname.c_str()); - if( fsize != m_opts.numBlocks * BLK_SIZE ) - { - ostringstream errstr; - errstr << "bad file size from fs " << fsize << " != " << m_opts.numBlocks * BLK_SIZE << "!"; - logMsg( ERROR, errstr.str() ); - return false; - } - - if( returnval ) - { - logMsg( INFO, "Running readTest" ); - returnval = readTest( filetype ); - } - - if( returnval ) - { - logMsg( INFO, "Running rdwrTest" ); - returnval = rdwrTest( filetype ); - } - - if( returnval && filetype == IDBDataFile::HDFS ) - { - logMsg( INFO, "Running hdfsRdwrExhaustTest" ); - returnval = hdfsRdwrExhaustTest(); - } - - if( m_opts.numDbRoots > 0 ) - { - logMsg( INFO, "Checking dbroots" ); - for( int i = 0; i < m_opts.numDbRoots; ++i ) - { - ostringstream dbroot; - dbroot << "/usr/local/Calpont/data" << i+1; - if( !fs.exists(dbroot.str().c_str()) ) - { - ostringstream msg; - msg << "Could not locate dbroot directory " << dbroot.str(); - logMsg( ERROR, msg.str() ); - returnval = false; - } - } - } - - list dircontents; - assert( fs.listDirectory( dir.c_str(), dircontents ) == 0 ); - ostringstream ldstr; - ldstr << "Listed directory " << dir << ":"; - list::iterator iend = dircontents.end(); - for( list::iterator i = dircontents.begin(); i != iend; ++i ) - { - ldstr << (*i) << ","; - } - logMsg( INFO, ldstr.str() ); - assert( dircontents.size() == 1 ); - - // now check a bogus path and make sure it returns -1 - assert( fs.listDirectory( "/this-is-a-bogus-directory", dircontents ) == -1 ); - assert( fs.remove( "/this-is-a-bogus-directory" ) == 0 ); - assert( !fs.isDir( "/this-is-a-bogus-directory" )); - assert( !fs.isDir( m_fname.c_str() )); - - if( returnval ) - { - logMsg( INFO, "All tests passed!" ); - } - - reset(); - return returnval; -} - -bool TestRunner::readTest( IDBDataFile::Types filetype ) -{ - reset(); - m_file = IDBDataFile::open(filetype, m_fname.c_str(), "r", m_open_opts); - if( !m_file ) - { - ostringstream errstr; - errstr << "Unable to open " << m_fname << " for reading"; - logMsg( ERROR, errstr.str() ); - return false; - } - - // check the mtime method. - time_t now = time(0); - time_t mtime = m_file->mtime(); - assert( (now-mtime) <= 3 ); - - struct timeval starttime,endtime,timediff; - gettimeofday(&starttime,0x0); - - for( int i = 0; i < m_opts.numBlocks; ++i) - { - if( !readBlock(i, m_defbuf, i) ) - return false; - } - - gettimeofday(&endtime,0x0); - timeval_subtract(&timediff,&endtime,&starttime); - float secs = timediff.tv_sec + (timediff.tv_usec * 0.000001); - - ostringstream infostr; - infostr << "Read " << m_opts.numBlocks * BLK_SIZE << " bytes in " << secs << " secs, "; - infostr << "Throughput = " << setprecision(3) << ((m_opts.numBlocks * BLK_SIZE) / 1000000.0) / secs << "MB/sec"; - logMsg( INFO, infostr.str() ); - - return true; -} - -bool TestRunner::openByModeStrTest() -{ - // in this test we want to check the alternate open modes available for buffered i/o - // this test is only run if we are doing buffered I/O and expects it is run after the - // write test to guarantee the file is there - reset(); - m_file = IDBDataFile::open(IDBDataFile::BUFFERED, m_fname.c_str(), "r+b", m_open_opts); - if( !m_file ) - { - ostringstream errstr; - errstr << "Unable to open " << m_fname << " for read/write"; - logMsg( ERROR, errstr.str() ); - return false; - } - - // keep this fairly simple - read a block then write a block - - size_t readct = m_file->read(m_defbuf,BLK_SIZE); - if( readct != BLK_SIZE ) - { - ostringstream errstr; - errstr << "Only read " << readct << " bytes, expected 4"; - logMsg( ERROR, errstr.str() ); - return false; - } - if( m_defbuf[0] != (unsigned char) 0 ) - { - ostringstream errstr; - errstr << "Data error - expected " << 0 << ", read " << (int) m_defbuf[0]; - logMsg( ERROR, errstr.str() ); - return false; - } - - // we should be at block 1 - long filepos = m_file->tell(); - if( filepos != long(BLK_SIZE) ) - { - ostringstream errstr; - errstr << "File position not at correct block, " << filepos << " != " << BLK_SIZE; - logMsg( ERROR, errstr.str() ); - return false; - } - - m_defbuf[0] = 1; - size_t bytes_written = m_file->write(m_defbuf, BLK_SIZE); - if( bytes_written != BLK_SIZE ) - { - ostringstream errstr; - errstr << "Only wrote " << bytes_written << " bytes, expected 4"; - logMsg( ERROR, errstr.str() ); - return false; - } - - return true; -} - -bool TestRunner::writeTest( IDBDataFile::Types filetype ) -{ - reset(); - m_file = IDBDataFile::open(filetype, m_fname.c_str(), "w", m_open_opts); - if( !m_file ) - { - ostringstream errstr; - errstr << "Unable to open " << m_fname << " for writing"; - logMsg( ERROR, errstr.str() ); - return false; - } - - struct timeval starttime,endtime,timediff; - gettimeofday(&starttime,0x0); - - for( int i = 0; i < m_opts.numBlocks; ++i) - { - if( !writeBlock(i, m_defbuf, i) ) - return false; - } - - gettimeofday(&endtime,0x0); - timeval_subtract(&timediff,&endtime,&starttime); - float secs = timediff.tv_sec + (timediff.tv_usec * 0.000001); - - ostringstream infostr; - infostr << "Wrote " << m_opts.numBlocks * BLK_SIZE << " bytes in " << secs << " secs, "; - infostr << "Throughput = " << setprecision(3) << ((m_opts.numBlocks * BLK_SIZE) / 1000000.0) / secs << "MB/sec"; - logMsg( INFO, infostr.str() ); - - return true; -} - -bool TestRunner::rdwrTest( IDBDataFile::Types filetype ) -{ - reset(); - m_file = IDBDataFile::open(filetype, m_fname.c_str(), "r+", m_open_opts); - if( !m_file ) - { - ostringstream errstr; - errstr << "Unable to open " << m_fname << " for reading"; - logMsg( ERROR, errstr.str() ); - return false; - } - - struct drand48_data d48data; - srand48_r(0xdeadbeef, &d48data); - - // we will write to 5 random blocks and then come back and - // verify the contents and undo them - int blocks_to_touch = min( 5, m_opts.numBlocks); - vector touched; - for( int i = 0; i < blocks_to_touch; ++i ) - { - long int blk_num; - // we need to make sure all the blocks we touch are unique or - // the pattern used by this test won't work - bool found = false; - while(!found) - { - lrand48_r( &d48data, &blk_num); - blk_num = blk_num % m_opts.numBlocks; - vector::iterator pos = find( touched.begin(), touched.end(), blk_num ); - if( pos == touched.end()) - found = true; - } - - if( m_file->seek(blk_num * BLK_SIZE, SEEK_SET) ) - { - ostringstream errstr; - errstr << "failed to seek block " << blk_num; - logMsg( ERROR, errstr.str() ); - return false; - } - - unsigned char writeval = 0xb0; - size_t writect = m_file->write(&writeval,1); - if( writect != 1 ) - { - ostringstream errstr; - errstr << "Only wrote " << writect << " bytes, expected 1"; - logMsg( ERROR, errstr.str() ); - return false; - } - - touched.push_back(blk_num); - } - - m_file->flush(); - - for( int i = 0; i < (int) touched.size(); ++i ) - { - unsigned char readbuf; - size_t readct = m_file->pread(&readbuf,touched[i] * BLK_SIZE,1); - if( readct != 1 || readbuf != (unsigned char) 0xb0 ) - { - ostringstream errstr; - errstr << "Error reading expected value, readct=" << readct << " bytes, value" << (int) readbuf; - logMsg( ERROR, errstr.str() ); - return false; - } - - readbuf = touched[i]; - - if (m_file->seek(touched[i] * BLK_SIZE, SEEK_SET)) - { - ostringstream errstr; - errstr << "failed to seek to " << touched[i] * BLK_SIZE; - logMsg( ERROR, errstr.str() ); - return false; - } - - size_t writect = m_file->write(&readbuf,1); - if( writect != 1 ) - { - ostringstream errstr; - errstr << "Only wrote " << writect << " bytes, expected 1"; - logMsg( ERROR, errstr.str() ); - return false; - } - } - - return true; -} - -bool TestRunner::hdfsRdwrExhaustTest() -{ - // this is going to be a self-contained test that attempts to test - // all logic inherent in HdfsRdwr - - // choose a new filename that is specific to our thread - ostringstream oss; - // embed pid so that this is a new directory path - oss << "/tmp/hdfsrdwr-" << getpid() << "-" << m_id; - string newpath = oss.str(); - - // open a file with arbitrarily small buffer - IDBDataFile* file = IDBDataFile::open(IDBDataFile::HDFS, newpath.c_str(), "r+", 0, 8); - assert( file ); - - // check various empty file conditions - assert( file->size() == 0 ); - assert( file->tell() == 0 ); - assert( file->seek(-1, SEEK_CUR) == -1); - assert( file->seek(0, SEEK_SET) == 0); - unsigned char buf[4]; - assert( file->read(buf, 4) == 0); - - // write some data - buf[0] = 0xde; buf[1] = 0xad; buf[2] = 0xbe; buf[3] = 0xef; - assert( file->write(buf, 4) == 4); - assert( file->size() == 4 ); - assert( file->tell() == 4 ); - assert( file->truncate(-1) == -1 ); - - // now make file empty again - assert( file->truncate(0) == 0 ); - assert( file->size() == 0 ); - assert( file->seek(0, SEEK_SET) == 0); - assert( file->tell() == 0 ); - assert( file->read(buf, 4) == 0); - - // write data again, this time exactly up to allocated size - assert( file->write(buf, 4) == 4); - assert( file->write(buf, 4) == 4); - assert( file->size() == 8 ); - assert( file->tell() == 8 ); - - // truncate back to 4 - assert( file->truncate(4) == 0 ); - assert( file->size() == 4 ); - assert( file->seek(4, SEEK_SET) == 0); - assert( file->tell() == 4 ); - - // now trigger a buffer reallocation - assert( file->write(buf, 4) == 4); - assert( file->write(buf, 4) == 4); - assert( file->size() == 12 ); - - // now delete and close. - delete file; - - // check the file size through the file system - IDBFileSystem& fs = IDBFileSystem::getFs( IDBDataFile::HDFS ); - assert( fs.size( newpath.c_str() ) == 12); - - // open again - the file is bigger than the default buffer so it triggers alternate - // logic in the constructor - file = IDBDataFile::open(IDBDataFile::HDFS, newpath.c_str(), "r+", 0, 8); - assert( file ); - assert( file->size() == 12); - unsigned char newbuf[4]; - assert( file->pread(newbuf, 4, 4) == 4); - assert( newbuf[0] == 0xde && newbuf[1] == 0xad && newbuf[2] == 0xbe &&newbuf[3] == 0xef); - delete file; - - fs.remove(newpath.c_str()); - - return true; -} - -TestRunner::~TestRunner() -{ -} - -bool TestRunner::fillDefault() -{ - return true; -} - -bool TestRunner::writeBlock(unsigned int blocknum, unsigned char* buf, unsigned char tag) -{ - buf[0] = tag; - size_t rc = m_file->write(buf, BLK_SIZE); - - if (rc != BLK_SIZE) - { - ostringstream errstr; - errstr << "writeBlock failed for block " << blocknum << ", wrote " << rc << " bytes, expecting " << BLK_SIZE; - logMsg( ERROR, errstr.str() ); - return false; - } - - return true; -} - -bool TestRunner::writeBlocks(unsigned int blocknum, unsigned char* buf, unsigned char tag, unsigned int count) -{ - for (unsigned i = 0; i < count; ++i) - { - writeBlock(blocknum+i, buf, tag+i); - } - // should actually aggregate return values but using messages for now - return true; -} - -bool TestRunner::readBlock(unsigned int blocknum, unsigned char* buf, unsigned char tag) -{ - size_t rc = m_file->pread(buf,blocknum*BLK_SIZE,BLK_SIZE); - //cout << "DEBUG: read " << rc << " bytes at offset " << blocknum * BLK_SIZE << endl; - - if (rc != BLK_SIZE) - { - ostringstream errstr; - errstr << "readBlock failed for block " << blocknum << ", read " << rc << " bytes, expecting " << BLK_SIZE; - logMsg( ERROR, errstr.str() ); - return false; - } - else if (tag != buf[0]) - { - ostringstream errstr; - errstr << "read tag 0x" << setw(2) << hex << setfill('0') << (int) buf[0] << " at block " << dec - << blocknum << ", expected 0x" << (int) tag; - logMsg( ERROR, errstr.str() ); - return false; - } - - return true; -} - -bool TestRunner::readBlocks(unsigned int blocknum, unsigned char* buf, unsigned char tag, unsigned int count) -{ - for (unsigned i = 0; i < count; ++i) - { - readBlock(blocknum+i, buf, (unsigned char)(tag+i)); - } - // should actually aggregate return values but using messages for now - return true; -} - -void TestRunner::logMsg( LogLevel level, const string& msg ) -{ - cout << "Test-" << m_id << ":" << ((level == INFO) ? "INFO:" : "ERROR:") << msg << endl; -} - -void logSuccess() -{ - ::openlog("hdfsCheck", 0|LOG_PID, LOG_LOCAL1); - ::syslog(LOG_INFO, "All HDFS tests passed!"); - ::closelog(); -} - -void logFailure(const char* msg) -{ - ostringstream oss; - oss << "hdfsCheck failed: " << msg; - ::openlog("hdfsCheck", 0|LOG_PID, LOG_LOCAL1); - ::syslog(LOG_WARNING, oss.str().c_str()); - ::closelog(); -} - -int main(int argc, char** argv) -{ - foptest_opts opts; - - int c; - while ((c = getopt (argc, argv, "b:n:t:r:")) != -1) - switch (c) - { - case 'b': - opts.blockSize = atoi(optarg); - if( opts.blockSize > MAX_BLK_SIZE ) - { - opts.blockSize = MAX_BLK_SIZE; - cout << "WARNING: block size exceeds max, using " << opts.blockSize << endl; - } - else - { - cout << "INFO: using BLK_SIZE " << opts.blockSize << endl; - } - break; - case 'n': - opts.numBlocks = atoi(optarg); - cout << "INFO: will operate on " << opts.numBlocks << " blocks" << endl; - break; - case 't': - opts.timeout = atoi(optarg); - cout << "INFO: setting timeout to " << opts.timeout << " secs." << endl; - break; - case 'r': - opts.numDbRoots = atoi(optarg); - cout << "INFO: Will check " << opts.numDbRoots << " dbroot directories" << endl; - break; - default: - usage(); - logFailure("bad command-line option"); - return 1; - } - - if( optind != argc - 1 ) - { - usage(); - logFailure("missing hdfs-plugin argument"); - return 1; - } - opts.pluginFile = argv[optind]; - - try - { - // init the library with logging enabled - std::string hdfsRdwrScratch = "/tmp/rdwr_scratch"; - IDBPolicy::init( true, true, hdfsRdwrScratch, 2147483648 ); - - if( !IDBPolicy::installPlugin(opts.pluginFile) ) - { - cerr << "ERROR: HDFS plugin not installed " << opts.pluginFile << endl; - return -1; - } - } - catch (...) - { - logFailure("failure to initialize IDBPolicy and/or load HDFS plugin"); - return -1; - } - - struct timeval starttime,endtime,timediff; - gettimeofday(&starttime,0x0); - - bool done = false; - - while ( !done ) - { - // check to see if timeout has expired - TestRunner trun(0, opts); - try - { - if( trun.runTest( IDBDataFile::HDFS, 0 ) ) - { - done = true; - cout << "INFO: All HDFS checks passed!" << endl; - } - } - catch (...) - { - ; // treat an exception thrown as a failure - } - if( !done ) - { - gettimeofday(&endtime,0x0); - timeval_subtract(&timediff,&endtime,&starttime); - float secs = timediff.tv_sec + (timediff.tv_usec * 0.000001); - if( secs < opts.timeout ) - { - // wait 5 seconds before we try again - sleep(5); - } - else - { - cerr << "ERROR: timeout out after unsuccessful HDFS tests" << endl; - logFailure("One or more HDFS tests failed"); - return -1; - } - } - } - - // only way we get here is if everything passes - logSuccess(); - return 0; -} diff --git a/tools/idb_comp/main.cpp b/tools/idb_comp/main.cpp deleted file mode 100644 index e692c4b8..00000000 --- a/tools/idb_comp/main.cpp +++ /dev/null @@ -1,255 +0,0 @@ -#include -#include -#include -#include -#include -//#define NDEBUG -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -using namespace std; - -#include - -namespace -{ -size_t exp_buf_size; -unsigned vflg; - -const string lzo_rctos(int r) -{ - switch (r) - { - case LZO_E_INPUT_NOT_CONSUMED: - return "LZO_E_INPUT_NOT_CONSUMED"; - default: - break; - } - return "Unknown Error!"; -} - -void usage() -{ - cout << "usage: idb_comp [-e size][-h] file(s)" << endl - << "\t-e size size (in KB) of expansion buffer" << endl - << "\t-h display this help" << endl; -} - -int doit(const string& infile) -{ - int rc = 0; - int ifd = open(infile.c_str(), O_RDONLY|O_LARGEFILE|O_DIRECT); - - if (ifd < 0) - { - cerr << infile << ": open: " << strerror(errno) << endl; - return 1; - } - - struct stat istatbuf; - fstat(ifd, &istatbuf); - - string outname(infile); - - string::size_type ptr; - - ptr = outname.find_last_of('.'); - - if (ptr != string::npos) - outname.erase(ptr); - - ptr = outname.find_last_of('/'); - - if (ptr != string::npos) - outname.erase(0, ptr+1); - - outname = "./" + outname + ".cmp"; - - int ofd = open(outname.c_str(), O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE|O_DIRECT, 0644); - - if (ofd < 0) - { - cerr << outname << ": open: " << strerror(errno) << endl; - close(ifd); - return 1; - } - - lzo_init(); - - ssize_t nread = -1; - ssize_t nwritten = -1; - lzo_bytep ibuf; - lzo_bytep tibuf; - lzo_bytep cbuf; - lzo_bytep tcbuf; - lzo_bytep wkmem; - lzo_uint32 ibuf_len = 0; - lzo_uint cbuf_len = 0; - - ibuf_len = 512 * 1024 * 8; - tibuf = new lzo_byte[ibuf_len + 4095]; - if ((ptrdiff_t)tibuf & 0xfffULL) - ibuf = (lzo_bytep)((ptrdiff_t)tibuf & 0xfffffffffffff000ULL) + 4096; - else - ibuf = tibuf; - cbuf_len = 512 * 1024 * 8; - tcbuf = new lzo_byte[cbuf_len + 4095 + exp_buf_size * 1024]; - if ((ptrdiff_t)tcbuf & 0xfff) - cbuf = (lzo_bytep)((ptrdiff_t)tcbuf & 0xfffffffffffff000ULL) + 4096; - else - cbuf = tcbuf; - wkmem = new lzo_byte[LZO1X_1_15_MEM_COMPRESS]; - - int r = LZO_E_OK; - - const int TOTAL_HDR_LEN = 4096 * 2; - char* hdrbuf = new char[TOTAL_HDR_LEN + 4095]; - memset(hdrbuf, 0, TOTAL_HDR_LEN + 4095); - char* hdrbufp = 0; - if ((ptrdiff_t)hdrbuf & 0xfff) - hdrbufp = (char*)((ptrdiff_t)hdrbuf & 0xfffffffffffff000ULL) + 4096; - else - hdrbufp = hdrbuf; - - struct compHdr - { - uint64_t ptrs[512]; - }; - - idbassert(sizeof(compHdr) <= 4096); - - compHdr* hdrptr1 = (compHdr*)hdrbufp; - compHdr* hdrptr = hdrptr1 + 1; // advance to 2nd hdr to store compression ptrs - lseek(ofd, TOTAL_HDR_LEN, SEEK_SET); - - nread = read(ifd, ibuf, ibuf_len); - - int idx = 0; - off_t cmpoff = TOTAL_HDR_LEN; - while (nread > 0) - { - cbuf_len = 512 * 1024 * 8; - memset(cbuf, 0, cbuf_len); - r = lzo1x_1_15_compress(ibuf, nread, cbuf, &cbuf_len, wkmem); - if (r != LZO_E_OK) - { - cerr << "compression failed!: " << r << endl; - rc = 1; - goto out; - } - if (cbuf_len > (unsigned)nread) - { - cerr << "WARNING: expansion detected! (output grew by " << (cbuf_len - nread) << " bytes)" << endl; - idbassert((cbuf_len - nread) <= exp_buf_size * 1024); - } - if (cbuf_len & 0xfff) - cbuf_len = (cbuf_len & 0xfffffffffffff000ULL) + 4096; - //cbuf_len = 512 * 1024 * 8; - nwritten = write(ofd, cbuf, cbuf_len); - if (nwritten < 0 || (unsigned)nwritten != cbuf_len) - { - cerr << outname << ": write: " << strerror(errno) << " (" << nwritten << ')' << endl; - rc = 1; - goto out; - } - if (vflg > 0) - { - lzo_bytep tbuf; - lzo_uint tbuflen = 4 * 1024 * 1024 + 4; - boost::scoped_array tbuf_sa(new lzo_byte[tbuflen]); - tbuf = tbuf_sa.get(); - cout << "idx: " << idx << " off: " << cmpoff << " size: " << cbuf_len; - r = lzo1x_decompress(cbuf, cbuf_len, tbuf, &tbuflen, 0); - cout << " r: " << lzo_rctos(r) << " size: " << tbuflen << endl; - } - hdrptr->ptrs[idx] = cmpoff; - idx++; - cmpoff += cbuf_len; - - nread = read(ifd, ibuf, ibuf_len); - } - - if (nread < 0) - { - cerr << infile << ": read: " << strerror(errno) << endl; - rc = 1; - goto out; - } - - hdrptr->ptrs[idx] = cmpoff; - idbassert(idx <= 64); - - // Fill in meta-data information in first header - hdrptr1->ptrs[0] = 0xfdc119a384d0778eULL; - hdrptr1->ptrs[1] = 1; - hdrptr1->ptrs[2] = 1; - - nwritten = pwrite(ofd, hdrbufp, TOTAL_HDR_LEN, 0); - idbassert(nwritten == TOTAL_HDR_LEN); - -out: - delete [] wkmem; - delete [] tcbuf; - delete [] tibuf; - fsync(ofd); - struct stat ostatbuf; - fstat(ofd, &ostatbuf); - idbassert(ostatbuf.st_size == (signed)hdrptr->ptrs[idx]); - delete [] hdrbuf; - cout << infile << ": Input Size: " << istatbuf.st_size - << " Output size: " << ostatbuf.st_size - << " Compression: " << (100LL - (ostatbuf.st_size * 100LL / istatbuf.st_size)) << '%' << endl; - close(ofd); - close(ifd); - - return rc; -} - -} - -int main(int argc, char** argv) -{ - opterr = 0; - int c; - exp_buf_size = 128; - vflg = 0; - - while ((c = getopt(argc, argv, "e:vh")) != -1) - switch (c) - { - case 'e': - exp_buf_size = atoi(optarg); - break; - case 'v': - vflg++; - break; - case 'h': - default: - usage(); - return (c == 'h' ? 0 : 1); - break; - } - - if ((argc - optind) < 1) - { - usage(); - return 1; - } - - int rc = 0; - - for (int i = optind; i < argc; i++) - if (doit(argv[i])) - rc = 1; - - return rc; -} - diff --git a/tools/idbmeminfo/Makefile.am b/tools/idbmeminfo/Makefile.am index 9a4ae9d0..a9b188d1 100644 --- a/tools/idbmeminfo/Makefile.am +++ b/tools/idbmeminfo/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ ## Process this file with automake to produce Makefile.in diff --git a/tools/idbmeminfo/Makefile.in b/tools/idbmeminfo/Makefile.in index 329a175e..fdd85569 100644 --- a/tools/idbmeminfo/Makefile.in +++ b/tools/idbmeminfo/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ @@ -59,9 +59,8 @@ bin_PROGRAMS = idbmeminfo$(EXEEXT) subdir = tools/idbmeminfo DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/idbmeminfo/idbmeminfo.cpp b/tools/idbmeminfo/idbmeminfo.cpp index ef3429b3..7ce11217 100644 --- a/tools/idbmeminfo/idbmeminfo.cpp +++ b/tools/idbmeminfo/idbmeminfo.cpp @@ -132,23 +132,29 @@ int main(int argc, char** argv) { opterr = 0; int c; + bool mFlg = true; bool gFlg = false; bool tFlg = true; + bool fFlg = false; while ((c = getopt(argc, argv, "tfgmh")) != EOF) switch (c) { case 'm': + mFlg = true; gFlg = false; break; case 'g': + mFlg = false; gFlg = true; break; case 't': tFlg = true; + fFlg = false; break; case 'f': tFlg = false; + fFlg = true; break; case 'h': case '?': diff --git a/tools/notificationTester/client.cpp b/tools/notificationTester/client.cpp deleted file mode 100644 index 2a7aa25e..00000000 --- a/tools/notificationTester/client.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include -//#define NDEBUG -#include -using namespace std; - -#include "liboamcpp.h" -using namespace oam; - -int main(int argc, char** argv) -{ - Oam oam; - int rc; - - rc = oam.sendDeviceNotification("PM1", START_PM_MASTER_DOWN, "This is a test"); - - assert(rc == API_SUCCESS); - - return 0; -} - -// vim:ts=4 sw=4: diff --git a/tools/notificationTester/main.cpp b/tools/notificationTester/main.cpp deleted file mode 100644 index 070716a6..00000000 --- a/tools/notificationTester/main.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "liboamcpp.h" -#include "messagelog.h" -#include "messageobj.h" - -using namespace std; -using namespace oam; -using namespace messageqcpp; -using namespace config; - -#pragma pack(push,1) -struct NotifyMsgStruct -{ - uint32_t magic; - uint32_t msgno; - char node[8]; - uint32_t paylen; -}; -#pragma pack(pop) - -/***************************************************************************** -* @brief main -* -* purpose: Notification Receiver Test App -* -* -******************************************************************************/ - -int main (int argc, char** argv) -{ - ByteStream msg; - IOSocket fIos; - - string msgPort = "CMP1"; - - //check if configured - Config* sysConfig = Config::makeConfig(); - string ipaddr = sysConfig->getConfig(msgPort, "IPAddr"); - if (ipaddr.empty()) - { - cerr << "CMP1 not configured in Calpont.xml, example of what to add to Calpont.xml:" << endl; - cerr << "" << endl; - cerr << " 127.0.0.1" << endl; - cerr << " 8650" << endl; - cerr << "" << endl << endl; - cerr << "Exiting..." << endl; - return 1; - } - - //read and cleanup port before trying to use - string port; - try { - Config* sysConfig = Config::makeConfig(); - port = sysConfig->getConfig(msgPort, "Port"); - string cmd = "fuser -k " + port + "/tcp >/dev/null 2>&1"; - system(cmd.c_str()); - } - catch(...) - {} - - cout << endl << "Notification Receiver Tester Started" << endl << endl; - - //wait for notification messages - while(true) - { - try - { - int ls = -1; - ls = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); - if (ls < 0) throw runtime_error("socket create error"); - int rc = 0; - struct sockaddr_in serv_addr; - struct in_addr la; - ::inet_aton(ipaddr.c_str(), &la); - memset(&serv_addr, 0, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = la.s_addr; - serv_addr.sin_port = htons(atoi(port.c_str())); - rc = ::bind(ls, (sockaddr*)&serv_addr, sizeof(serv_addr)); - if (rc < 0) throw runtime_error("socket bind error"); - rc = ::listen(ls, 5); - if (rc < 0) throw runtime_error("socket listen error"); - int ds = -1; - for (;;) - { - try - { - ds = ::accept(ls, 0, 0); - if (ds < 0) throw runtime_error("socket accept error"); - char hbuf[sizeof(NotifyMsgStruct)]; - ssize_t bytesRead = 0; - ssize_t bytesNeeded = sizeof(NotifyMsgStruct); - while (bytesRead < bytesNeeded) - { - ssize_t thisRead = -1; - thisRead = ::read(ds, &hbuf[bytesRead], bytesNeeded); - if (thisRead < 0) throw runtime_error("socket read error"); - bytesRead += thisRead; - bytesNeeded -= thisRead; - } - NotifyMsgStruct* nmsp = (NotifyMsgStruct*)&hbuf[0]; - - if (bytesRead > 0) { - if ( nmsp->magic != oam::NOTIFICATIONKEY ) { - cout << "ERROR: Invalid Header Key received, tossing the msg" << endl; - cout << "headerKey received: " << nmsp->magic << endl; - continue; - } - - time_t now; - now = time(NULL); - struct tm tm; - localtime_r(&now, &tm); - char timestamp[200]; - strftime (timestamp, 200, "%H:%M:%S", &tm); - - cout << "Message Received: " << timestamp; - cout << " device: " << nmsp->node; - cout << " requestType ID: " << nmsp->msgno; - - if ( nmsp->paylen > 0 ) { - char* payLoad; - payLoad = (char*)alloca(nmsp->paylen); - bytesRead = 0; - bytesNeeded = nmsp->paylen; - while (bytesRead < bytesNeeded) - { - ssize_t thisRead = -1; - thisRead = ::read(ds, &payLoad[bytesRead], bytesNeeded); - if (thisRead < 0) throw runtime_error("socket read error"); - bytesRead += thisRead; - bytesNeeded -= thisRead; - } - cout << " payload: " << payLoad; - } - - switch (nmsp->msgno) { - case START_PM_MASTER_DOWN: - { - cout << " requestType: START_PM_MASTER_DOWN" << endl; - } - break; - - case START_PM_STANDBY_DOWN: - { - cout << " requestType: START_PM_STANDBY_DOWN" << endl; - } - break; - - case START_PM_COLD_DOWN: - { - cout << " requestType: START_PM_COLD_DOWN" << endl; - } - break; - - case START_UM_DOWN: - { - cout << " requestType: START_UM_DOWN" << endl; - } - break; - - case MODULE_DOWN: - { - cout << " requestType: MODULE_DOWN" << endl; - } - break; - - case START_STANDBY_TO_MASTER: - { - cout << " requestType: START_STANDBY_TO_MASTER" << endl; - } - break; - - case PM_MASTER_ACTIVE: - { - cout << " requestType: PM_MASTER_ACTIVE" << endl; - } - break; - - case PM_STANDBY_ACTIVE: - { - cout << " requestType: PM_STANDBY_ACTIVE" << endl; - } - break; - - case PM_COLD_ACTIVE: - { - cout << " requestType: PM_COLD_ACTIVE" << endl; - } - break; - - case UM_ACTIVE: - { - cout << " requestType: UM_ACTIVE" << endl; - } - break; - - case PM_MASTER_FAILED_DISABLED: - { - cout << " requestType: PM_MASTER_FAILED_DISABLED" << endl; - } - break; - - case DBROOT_DOWN: - { - cout << " requestType: DBROOT_DOWN" << endl; - } - break; - - case DBROOT_UP: - { - cout << " requestType: DBROOT_UP" << endl; - } - break; - - case DB_HEALTH_CHECK_FAILED: - { - cout << " requestType: DB_HEALTH_CHECK_FAILED" << endl; - } - break; - - case DBROOT_MOUNT_FAILURE: - { - cout << " requestType: DBROOT_MOUNT_FAILURE" << endl; - } - break; - - case MODULE_UP: - { - cout << " requestType: MODULE_UP" << endl; - } - break; - - default: - { - cout << " Invalid requestType: " << nmsp->msgno << endl; - } - break; - } - } - else - cout << "Message received of size 0" << endl; - - ::shutdown(ds, SHUT_RDWR); - ::close(ds); - } - catch(...) - { - cout << "accept/read exception received" << endl; - } - } - } - catch(...) - { - cout << "MessageQueueServer exception received" << endl; - } - } - - return 0; -} -// vim:ts=4 sw=4: - diff --git a/tools/pingproc/pingproc.cpp b/tools/pingproc/pingproc.cpp deleted file mode 100644 index fc90c310..00000000 --- a/tools/pingproc/pingproc.cpp +++ /dev/null @@ -1,2160 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: pingproc.cpp 2101 2013-01-21 14:12:52Z rdempsey $ -#include -#include -#include -#include -#include -#include -#include -using namespace std; - -#include -using namespace boost; - -#include "bytestream.h" -using namespace messageqcpp; - -#include "distributedenginecomm.h" -#include "primitivemsg.h" -#include "jobstep.h" -#include "batchprimitiveprocessor-jl.h" -using namespace joblist; - -#include "calpontsystemcatalog.h" -using namespace execplan; - -#include "brm.h" -using namespace BRM; - -// Global vars -bool debug; -bool thdFcnFailure; - -// -// TODO: Why is this namespace here? - -namespace -{ - -void timespec_sub(const struct timespec &tv1, - const struct timespec &tv2, - struct timespec &diff) -{ - if (tv2.tv_nsec < tv1.tv_nsec) { - diff.tv_sec = tv2.tv_sec - tv1.tv_sec - 1; - diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec + 1000000000; - } - else { - diff.tv_sec = tv2.tv_sec - tv1.tv_sec; - diff.tv_nsec = tv2.tv_nsec - tv1.tv_nsec; - } -} // timespec_sub - -// -// -class OidOperation { - -public: - - enum OpType_t { - SCAN=0, - BLOCK=1, - LOOPBACK=2, - NONE=3, - BATCHSCAN = 4, - BATCHSTEP = 5, - BATCHFILT = 6 - }; - - OidOperation(const OID_t oid, const OpType_t opType, const uint32_t sessionId=0); - ~OidOperation() {}; - - void addFilter(const int8_t COP, const int64_t value); - - const OID_t OID() const {return fOid;} - const OpType_t OpType() const {return fOpType;} - - const CalpontSystemCatalog::ColType& ColumnType() { return fColType;} - const uint32_t ColumnWidth() const { return fColType.colWidth;} - - const uint32_t FilterCount() const { return fFilterCount;} - const ByteStream& FilterString() { return fFilterList;} - const uint32_t SessionId() const { return fSessionId;} - const uint32_t DataType() const { return fColType.colDataType;} - const uint32_t BOP() const { return fBOP;} - void BOP(const uint32_t bop) { if (FilterCount()>=2) fBOP=bop;} - const uint32_t COP1() const { return fCOP1;} - void COP1(const uint32_t cop) { fCOP1=cop;} - const uint32_t COP2() const { return fCOP2;} - void COP2(const uint32_t cop) { fCOP2=cop;} - bool isIntegralDataType(); - void setLbidTraceOn(); - void setPMProfileOn(); - bool LbidTrace() {return fLbidTrace;} - bool PMProfile() {return fPMProfile;} - - void deSerializeFilter(int8_t& COP, int64_t& value); - -// private: - OidOperation(){}; - OID_t fOid; - - ByteStream fFilterList; - uint32_t fFilterCount; - OpType_t fOpType; - CalpontSystemCatalog::ColType fColType; - uint32_t fSessionId; - uint32_t fBOP; - uint32_t fCOP1; - uint32_t fCOP2; - bool fLbidTrace; - bool fPMProfile; -}; // class OidOperation - - -// -// -OidOperation::OidOperation(const OID_t oid, const OpType_t opType, const uint32_t sessionId) - :fOid(oid), fFilterList(), fFilterCount(0), fOpType(opType),fSessionId(sessionId), fBOP(BOP_NONE), fCOP1(COMPARE_NIL),fCOP2(COMPARE_NIL), fLbidTrace(false), fPMProfile(false) -{ - boost::shared_ptr cat = execplan::CalpontSystemCatalog::makeCalpontSystemCatalog(getpid()); - fColType = cat->colType(oid); - fFilterList.reset(); -} - -void OidOperation::setLbidTraceOn() -{ - fLbidTrace=true; -} - -void OidOperation::setPMProfileOn() -{ - fPMProfile=true; -} - -void OidOperation::addFilter(const int8_t COP, const int64_t value) -{ - - if (fFilterCount==2) - return; - - fFilterList << (uint8_t) COP; - // converts to a type of the appropriate width, then bitwise - // copies into the filter ByteStream - switch(ColumnWidth()) { - case 1: - int8_t tmp8; - tmp8 = value; - fFilterList << *((uint8_t *) &tmp8); - break; - case 2: - int16_t tmp16; - tmp16 = value; - fFilterList << *((uint16_t *) &tmp16); - break; - case 4: - int32_t tmp32; - tmp32 = value; - fFilterList << *((uint32_t *) &tmp32); - break; - case 8: - fFilterList << *((uint64_t *) &value); - break; - default: - ostringstream o; - - o << "addFilter: colType says OID " << - " has a width of " << ColumnWidth(); - throw runtime_error(o.str()); - } - fFilterCount++; -} - - -void OidOperation::deSerializeFilter(int8_t& COP, int64_t& value) -{ - - if (fFilterCount==0) - { - COP = COMPARE_NIL; - return; - } - - fFilterList >> *(uint8_t*) &COP; - - switch(ColumnWidth()) { - case 1: - int8_t tmp8; - tmp8 = value; - fFilterList >> *((uint8_t *) &tmp8); - value = tmp8; - break; - case 2: - int16_t tmp16; - fFilterList >> *((uint16_t *) &tmp16); - value = tmp16; - break; - case 4: - int32_t tmp32; - fFilterList >> *((uint32_t *) &tmp32); - value = tmp32; - break; - case 8: - fFilterList >> *((uint64_t *) &value); - break; - default: - ostringstream o; - - o << "deSerializeFilter: colType says OID " << - " has a width of " << ColumnWidth(); - throw runtime_error(o.str()); - } - fFilterCount--; -} - -typedef vector OperationList; - -// Only process these column types -// -bool OidOperation::isIntegralDataType() -{ - if (DataType()==CalpontSystemCatalog::BIT || - DataType()==CalpontSystemCatalog::TINYINT || - DataType()==CalpontSystemCatalog::SMALLINT || - DataType()==CalpontSystemCatalog::MEDINT || - DataType()==CalpontSystemCatalog::INT || - DataType()==CalpontSystemCatalog::DATE || - DataType()==CalpontSystemCatalog::BIGINT || - DataType()==CalpontSystemCatalog::DATETIME || - DataType()==CalpontSystemCatalog::UTINYINT || - DataType()==CalpontSystemCatalog::USMALLINT || - DataType()==CalpontSystemCatalog::UMEDINT || - DataType()==CalpontSystemCatalog::UINT || - DataType()==CalpontSystemCatalog::UBIGINT) - return true; - - if (DataType()==CalpontSystemCatalog::CHAR && 1 == fColType.colWidth) - return true; - - return false; -} - -const ByteStream formatLoopBackMsg(const uint32_t sessionId, uint32_t uniqueId) -{ - ByteStream primMsg; - ISMPacketHeader ism; - memset(&ism, 0, sizeof(ism)); - ism.Command=COL_LOOPBACK; - ism.Size=sizeof(ism) + sizeof(ColLoopback); - ism.Type=2; - primMsg.load((const uint8_t *) &ism, sizeof(ism)); - struct ColLoopback lb; - - memset(&lb, 0, sizeof(lb)); - - lb.Hdr.SessionID = sessionId; - lb.Hdr.StatementID = 0; - lb.Hdr.TransactionID = sessionId; - lb.Hdr.VerID = 0; - lb.Hdr.StepID = sessionId; - lb.Hdr.UniqueID = uniqueId; - primMsg.append((const uint8_t *) &lb, sizeof(lb)); - - return primMsg; -} // formatLoopBackMsg - -const ByteStream formatDictionaryMsg( - const uint64_t lbid, - ByteStream& ridList, - const uint16_t ridCount, - OidOperation& oidOp) -{ - ByteStream primMsg; - DictSignatureRequestHeader hdr; - ISMPacketHeader ism; - - ism.Flags=0; //planFlagsToPrimFlags(fTraceFlags); - ism.Command=DICT_SIGNATURE; - ism.Size=sizeof(DictSignatureRequestHeader) + ridList.length(); - ism.Type=2; - - hdr.Hdr.SessionID = oidOp.SessionId(); - hdr.Hdr.StatementID = 0; - hdr.Hdr.TransactionID = oidOp.SessionId(); - hdr.Hdr.VerID = 0; - hdr.Hdr.StepID = 0; - - hdr.LBID = lbid; - hdr.PBID = 0; - idbassert(ridCount <= 8000); - hdr.NVALS = ridCount; - - primMsg.load((const uint8_t *) &ism, sizeof(ism)); - primMsg.append((const uint8_t *) &hdr, sizeof(DictSignatureRequestHeader)); - primMsg += ridList; - - return primMsg; -} - - -const ByteStream formatColStepMsg( - const uint64_t lbid, - ByteStream& ridList, - const uint16_t ridCount, - OidOperation& oidOp, - uint32_t uniqueId) -{ - ByteStream primMsg; - NewColRequestHeader hdr; - - memset(&hdr, 0, sizeof(hdr)); - - hdr.ism.Reserve=0; - hdr.ism.Flags=0; - if (oidOp.LbidTrace()==true) - hdr.ism.Flags |= PF_LBID_TRACE; - if (oidOp.PMProfile()==true) - hdr.ism.Flags |= PF_PM_PROF; - hdr.ism.Command=COL_BY_SCAN; - hdr.ism.Size=sizeof(NewColRequestHeader) + oidOp.FilterString().length() + ridList.length(); - hdr.ism.Type=2; - - hdr.hdr.SessionID = oidOp.SessionId(); - hdr.hdr.StatementID = 0; - hdr.hdr.TransactionID = oidOp.SessionId(); - hdr.hdr.VerID = 0; - hdr.hdr.StepID = oidOp.SessionId(); - hdr.hdr.UniqueID = uniqueId; - - hdr.LBID = lbid; - idbassert(hdr.LBID > 0); - hdr.PBID = 0; - hdr.DataSize = oidOp.ColumnWidth(); - hdr.DataType = oidOp.DataType(); - hdr.OutputType = OT_BOTH; - hdr.BOP = BOP_NONE; -// hdr.InputFlags = 0; - hdr.NOPS = oidOp.FilterCount(); - hdr.NVALS = ridCount; - hdr.sort=0; - - primMsg.load((const uint8_t *) &hdr, sizeof(NewColRequestHeader)); - - if (oidOp.FilterCount()>0) - primMsg += oidOp.FilterString(); - - if (ridCount>0) - primMsg += ridList; - - return primMsg; - -} //formatColStepMsg - -const ByteStream formatDictionaryScanMsg(const uint64_t lbid, - const uint16_t count, - OidOperation& oidOp) -{ - ByteStream primMsg; - DictTokenByScanRequestHeader hdr; - - hdr.ism.Reserve = 0; - hdr.ism.Flags = 0; - hdr.ism.Command = DICT_TOKEN_BY_SCAN_COMPARE; - hdr.ism.Size = sizeof(DictTokenByScanRequestHeader) + - oidOp.FilterString().length(); - hdr.ism.Type = 2; - - hdr.Hdr.SessionID = oidOp.SessionId(); - hdr.Hdr.StatementID = 0; - hdr.Hdr.TransactionID = 0; - hdr.Hdr.VerID = 0; - hdr.Hdr.StepID = oidOp.SessionId(); - - hdr.LBID = lbid; - idbassert(hdr.LBID >= 0); - hdr.PBID = 0; - hdr.OutputType = OT_TOKEN; - hdr.BOP = oidOp.BOP(); - hdr.COP1 = oidOp.COP1(); - hdr.COP2 = oidOp.COP2(); - hdr.NVALS = oidOp.FilterCount(); - hdr.Count = count; - idbassert(hdr.Count > 0); - - primMsg.load((const uint8_t *) &hdr.ism, sizeof(ISMPacketHeader)); - primMsg.append((const uint8_t*) &hdr, sizeof(DictTokenByScanRequestHeader)); - primMsg += oidOp.FilterString(); - - return primMsg; -} - -const ByteStream formatColScanMsg(const uint64_t lbid, - const uint16_t count, - OidOperation& oidOp, - uint32_t uniqueId) -{ - ByteStream primMsg; - ISMPacketHeader ism; - ColByScanRangeRequestHeader fMsgHeader; - - memset(&fMsgHeader, 0, sizeof(fMsgHeader)); - memset(&ism, 0, sizeof(ism)); - - ism.Reserve=0; - ism.Flags=0; - if (oidOp.LbidTrace()==true) - ism.Flags |= PF_LBID_TRACE; - if (oidOp.PMProfile()==true) - ism.Flags |= PF_PM_PROF; - ism.Command=COL_BY_SCAN_RANGE; - ism.Size=sizeof(fMsgHeader) + sizeof(ism) + oidOp.FilterString().length(); - ism.Type=2; - - primMsg.load((const uint8_t *) &ism, sizeof(ism)); - - fMsgHeader.LBID = lbid; - idbassert(fMsgHeader.LBID >= 0); - fMsgHeader.PBID = 0; - fMsgHeader.DataSize = oidOp.ColumnWidth(); - fMsgHeader.DataType = oidOp.DataType(); - fMsgHeader.OutputType = OT_BOTH; - fMsgHeader.BOP = oidOp.BOP(); - fMsgHeader.NOPS = oidOp.FilterCount(); - fMsgHeader.NVALS = 0; - fMsgHeader.Count = count; //(hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - idbassert(fMsgHeader.Count > 0); - fMsgHeader.Hdr.SessionID = oidOp.SessionId(); - fMsgHeader.Hdr.StatementID = 0; - fMsgHeader.Hdr.TransactionID = oidOp.SessionId(); - fMsgHeader.Hdr.VerID = 0; - fMsgHeader.Hdr.StepID = oidOp.SessionId(); - fMsgHeader.Hdr.UniqueID = uniqueId; - - primMsg.append((const uint8_t *) &fMsgHeader, sizeof(fMsgHeader)); - - if (oidOp.FilterCount()>0) - primMsg+=oidOp.FilterString(); - - return primMsg; - -} //formatColScanMsg - - -// -void doBatchOp_scan(OidOperation& OidOp); -void doBatchOp_step(OidOperation& OidOp); -void doBatchOp_filt(OidOperation& OidOp); -void doBatchQueryOp(OperationList& OidOps); -void doColScan(OidOperation& OidOp); -void doColStep(OidOperation& OidOp); -void doDictScan(OidOperation& OidOp); -void doDictStep(OidOperation& OidOp); - -// receive the responses from PrimProc -// -struct ThdFcn -{ - void operator()() - { - uint64_t totalBytes=0; - try - { - ByteStream ibs; - if (debug) - cout << "Waiting on " << fNumMsgs << " messages." << endl; - for (uint32_t k=0; kread(uniqueID); -// cout << "got msg #" << k << endl; - if (debug) - if (k%10240==0) - cout - << "ThdFcn: read " << fSessionid - << " " << k << "/" << fNumMsgs << " " - << ibs.length() << "/" << totalBytes - << endl; - - if (ibs.length() == 0) - break; - - totalBytes+=ibs.length(); - } - } - catch (exception &e) - { - cerr << "read exception: " << e.what() << endl; - thdFcnFailure = true; - } - - if (debug) - cout << totalBytes << " bytes read in " - << fNumMsgs << " messages" << endl; - - } // void operator() - - uint32_t fSessionid; - uint32_t uniqueID; - DistributedEngineComm* fDec; - unsigned fNumMsgs; - -}; // struct ThdFcn - - -struct QryThdFcn -{ - void operator()() - { - uint64_t totalBytes=0; - int64_t min; - int64_t max; - uint64_t lbid; - uint32_t cachedIO; - uint32_t physIO; - uint32_t touchedBlocks; - bool validCPData; - try - { - ByteStream ibs; - ByteStream obs; - if (debug) - cout << "Waiting on " << fNumMsgs << " messages." << endl; - for (uint32_t k=0; kread(uniqueID); -// cout << "got msg #" << k << endl; - if (debug) - if (k%10240==0) - cout - << "QryThdFcn: read " << fSessionid - << " " << k << "/" << fNumMsgs << " " - << ibs.length() << "/" << totalBytes - << " rows: " << fRows << endl; - - if (ibs.length() == 0) - break; - - totalBytes+=ibs.length(); - fRows += fBpp.getTableBand (ibs, &obs, &validCPData, &lbid, &min, &max, &cachedIO, &physIO, &touchedBlocks ); - fBlockTouched += touchedBlocks; - } - } - catch (exception &e) - { - cerr << "read exception: " << e.what() << endl; - thdFcnFailure = true; - } - - if (debug) - cout << totalBytes << " bytes read in " - << fNumMsgs << " messages for " - << fRows << " rows and " << fBlockTouched << " blocks\n"; - - } // void operator() - - QryThdFcn(BatchPrimitiveProcessorJL& bpp, uint64_t& rows, uint32_t& blk): fBpp(bpp), fNumMsgs(0), fRows(rows), fBlockTouched(blk) {} - BatchPrimitiveProcessorJL& fBpp; - uint32_t fSessionid; - DistributedEngineComm* fDec; - unsigned fNumMsgs; - uint64_t& fRows; - uint32_t& fBlockTouched; - uint32_t uniqueID; - -}; // struct ThdFcn - - -struct BatchScanThr -{ - BatchScanThr(OidOperation& oidOp):fOidOp(oidOp){} - - void operator()() - { - doBatchOp_scan(fOidOp); - } // void operator() - - OidOperation& fOidOp; - -}; // struct BatchScanThr - -struct BatchStepThr -{ - BatchStepThr(OidOperation& oidOp):fOidOp(oidOp){} - - void operator()() - { - doBatchOp_step(fOidOp); - } // void operator() - - OidOperation& fOidOp; - -}; // struct BatchStepThr - -struct BatchFiltThr -{ - BatchFiltThr(OidOperation& oidOp):fOidOp(oidOp){} - - void operator()() - { - doBatchOp_filt(fOidOp); - } // void operator() - - OidOperation& fOidOp; - -}; // struct BatchFiltThr - -struct BatchQueryThr -{ - BatchQueryThr(OperationList& oidOps):fOidOps(oidOps){} - - void operator()() - { - doBatchQueryOp(fOidOps); - } // void operator() - - OperationList& fOidOps; - -}; // struct - - -struct ColStepThr -{ - ColStepThr(OidOperation& oidOp):fOidOp(oidOp){} - - void operator()() - { - doColStep(fOidOp); - } // void operator() - - OidOperation& fOidOp; - -}; // struct ColStepThr - -struct ColScanThr -{ - - ColScanThr(OidOperation& oidOp):fOidOp(oidOp){} - - void operator()() - { - doColScan(fOidOp); - } // void operator() - - OidOperation& fOidOp; - -}; // struct ColStepThr - -struct DictSigThr -{ -}; // DictSigThr - -struct DictScanThr -{ -}; // DictScanThr - -// doColScan -void doDictionaryScan(OidOperation& OidOp) { -} - - -// doColScan -void doColScan(OidOperation& OidOp) { - -if (debug) cout << "beginning doColScan\n"; - BRM::LBIDRange_v lbidRanges; - HWM_t hwm=0; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); - struct timespec ts1; - struct timespec ts2; - struct timespec diff; - uint32_t uniqueID; - - uint32_t sessionid = getpid(); - uint32_t totalBlks=0; -// dec->addSession(sessionid); -// dec->addStep(sessionid, sessionid); - DBRM dbrm; - - uniqueID = dbrm.getUnique32(); - dec->addQueue(uniqueID); - - int err = dbrm.lookup(OidOp.OID(), lbidRanges); - if (err) - throw runtime_error("doAColScan: BRM LBID range lookup failure (1)"); - - err = dbrm.getHWM(OidOp.OID(), hwm); - if (err) - throw runtime_error("doAColScan: BRM HWM lookup failure (3)"); - - LBIDRange_v::iterator it; - OID_t tmp; - uint32_t fbo; - - ThdFcn f1; - f1.fSessionid = sessionid; - f1.uniqueID = uniqueID; - f1.fDec = dec; - f1.fNumMsgs=0; - thdFcnFailure = false; - uint32_t rangeSize=0; - ByteStream obs; - - // calculate the expected number of messages - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) { - - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - cerr << "pColScanStep::sendPrimitiveMessages: dbrm.lookup failed for lbid " << lbid << endl; - abort(); - } - - if (hwm < fbo) - continue; - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - totalBlks+=rangeSize; - } // for - - f1.fNumMsgs=(totalBlks/OidOp.ColumnWidth()); - if (0 < totalBlks % OidOp.ColumnWidth()) ++f1.fNumMsgs; - - idbassert(f1.fNumMsgs); - if (debug) - cout - << "Scanning OID " << OidOp.OID() - << " " << f1.fNumMsgs << " msgs" << endl; - - thread t1(f1); - clock_gettime(CLOCK_REALTIME, &ts1); - // send the primitive requests - int rCount=0; - totalBlks=0; - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) { - - try { - - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - cerr << "doAColScan dbrm.lookup failed for lbid " << lbid << endl; - abort(); - } - - if (hwm < fbo) - continue; - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - obs = formatColScanMsg(lbid, rangeSize, OidOp, uniqueID); - if (obs.length() > 0) { - dec->write(obs); - rCount++; - if (debug) - cout << "colScan: " << rCount << "/" - << lbidRanges.size() << " sending " << obs.length() << " bytes " - << " lbid " << lbid << " sz " << rangeSize << endl; - } - } - catch(exception& e) - { - cerr << "catch " << e.what() << endl; - } - totalBlks+=rangeSize; - - } // for (lbidRanges ... - - t1.join(); - clock_gettime(CLOCK_REALTIME, &ts2); -// dec->removeSession(sessionid); - dec->removeQueue(uniqueID); - - timespec_sub(ts1, ts2, diff); - - cout << "ColScan stats OID: " << OidOp.OID() - << "\tFilter: " << (int) OidOp.FilterCount() - << "\tBlocks: " << (int) totalBlks - << "\tElapse: " << diff.tv_sec+(diff.tv_nsec/1000000000.0) << "s"; - - float rate = 0; - rate =totalBlks/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << " Blks/sec : " << rate << endl; - - if (thdFcnFailure) - cout << "There was a failure in the read thread." << endl; - cout << endl; - -} // doAScan - -// -void usage() -{ - cerr << - "PingProc operation [filter] [operation] [filter] [reporting]" << endl << - "PingProc -c -s -gt 0 -t -d " << endl << - "\t---- operation flags ----" << endl << - "\t--scan -s " << endl << - "\t--block -t " << endl << - "\t--BatchPrimitiveScan -B " << endl << - "\t--BatchPrimitiveStep -Z " << endl << - "\t--concurrent -c perform each operation in its own thread" << endl << - "\t--lbid-trace -lb set lbid trace flag in request" << endl << - "\t---- filter flags ----" << endl << - "\t--equal -eq equivalency test of values in a block>" << endl << - "\t--greater-than -gt - greater than (>) test of values in a block" << endl << - "\t--greater-than-equal -ge greater than or equal to (>=) test of values in a block" << endl << - "\t--less-than -lt less than (<) test of values in a block" << endl << - "\t--less-than-equal -le less than or equal to (<=) test of values in a block" << endl << - "\t--not-equal -ne not equal to (!=) test of values in a block" << endl << - "\t--bop <1 or 0> binary operator when 2 comparison filters are present" << endl << - "\t---- reporting flags ----" << endl << - "\t--debug -d turn debug output on>" << endl << - "\t--list -list -l print out all oids and their ranges" << endl << - "\t--loopback -p send count loopback requests" << endl << - "\t--query -q run batch query for all the oids (enter with -B or -Z)" << endl; - -} // usage() - -const int64_t getInt(string s) { - - if (s.length()<=0) - return -1; - - //if (atoll(s.data()) < 0) - // return -1; - - return atoll(s.data()); - -} //getInt - -// dictionary - void doDictionarySig(OidOperation& OidOp) { -} // doDictionarySig - -// col step -void doColStep(OidOperation& OidOp) { - - struct timespec ts1; - struct timespec ts2; - struct timespec diff; - DBRM dbrm; - BRM::LBIDRange_v lbidRanges; - HWM_t hwm=0; - LBIDRange_v::iterator it; - OID_t tmp; - uint32_t fbo; - uint32_t totalBlks=0; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); - ThdFcn f1; - -// dec->addSession(OidOp.SessionId()); -// dec->addStep(OidOp.SessionId(), OidOp.SessionId()); - uint32_t uniqueID = dbrm.getUnique32(); - dec->addQueue(uniqueID); - - f1.fSessionid = OidOp.SessionId(); - f1.uniqueID = uniqueID; - f1.fDec = dec; - f1.fNumMsgs = 0; - thdFcnFailure = false; - ByteStream ridlist; - uint16_t ridCount = 0; // BLOCK_SIZE/OidOp.ColumnWidth(); - - for (uint16_t i=0; i (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - totalBlks+=rangeSize; - } // for - - uint32_t colwidth = OidOp.ColumnWidth(); - f1.fNumMsgs = totalBlks /(colwidth); - if (0 < totalBlks % colwidth) ++f1.fNumMsgs; - - idbassert(f1.fNumMsgs); - thread t1(f1); - ByteStream obs; - totalBlks=0; - clock_gettime(CLOCK_REALTIME, &ts1); - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) { - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - if (debug) - cerr << "pColScanStep::sendPrimitiveMessages: dbrm.lookup failed for lbid " << lbid << endl; - abort(); - } - - if (hwm < fbo) - break; //continue; - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - for (unsigned i = 0; i < rangeSize; i++) - { - obs += formatColStepMsg(lbid+i, ridlist, ridCount, OidOp, uniqueID); - if (0 == (i + 1) % colwidth) - { - dec->write(obs); - if (debug && i+1 ==rangeSize) - cout << "colStep: " << i << "/" - << rangeSize << " " << obs.length() - << " lbid " << lbid + i << endl; - obs.restart(); - } - } - totalBlks+=rangeSize; - } // for - - if (obs.length()) - { - dec->write(obs); - if (debug) - cout << "colStep: last" << "/" - << rangeSize << " " << obs.length() << endl; - } - obs.reset(); - - t1.join(); //@bug 849 moved join here and changed output to be like pColScan. - clock_gettime(CLOCK_REALTIME, &ts2); - timespec_sub(ts1, ts2, diff); -// t1.join(); - cout << "ColStep stats OID: " << OidOp.OID() - << "\tFilter: " << (int) OidOp.FilterCount() - << "\tBlocks: " << (int) totalBlks - << "\tElapse: " << diff.tv_sec+(diff.tv_nsec/1000000000.0) << "s"; - - float rate = 0; - rate = totalBlks/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\tBlks/sec " << rate << endl; - - if (thdFcnFailure) - cerr << "There was a failure in the read thread." << endl; - - cout << endl; - -} // doColStep - -void doBatchOp_scan(OidOperation &OidOp) -{ - struct timespec ts1, ts2, diff; - JobStepAssociation injs, outjs; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); - ThdFcn f1; - boost::shared_ptr sysCat = execplan::CalpontSystemCatalog::makeCalpontSystemCatalog(getpid()); - - pColScanStep scan(injs, outjs, dec, sysCat, OidOp.fOid, OidOp.fOid, - OidOp.fSessionId, 0, OidOp.fSessionId, OidOp.fSessionId, OidOp.fSessionId, rm); - - int32_t filters = OidOp.FilterCount(); - while (OidOp.FilterCount()>0) - { - int8_t cop; - int64_t value; - OidOp.deSerializeFilter(cop, value); - scan.addFilter(cop, value); - } - - BatchPrimitiveProcessorJL bpp; - ByteStream bs; - DBRM dbrm; - BRM::LBIDRange_v lbidRanges; - HWM_t hwm=0; - LBIDRange_v::iterator it; - OID_t tmp; - uint32_t fbo; - - uint32_t uniqueID = dbrm.getUnique32(); - bpp.setUniqueID(uniqueID); - - bpp.setSessionID(OidOp.SessionId()); - bpp.setStepID(OidOp.SessionId()); - bpp.addFilterStep(scan); - - cout << "session number = " << OidOp.SessionId() << endl; -// dec->addSession(OidOp.SessionId()); -// dec->addStep(OidOp.SessionId(), OidOp.SessionId()); - dec->addQueue(uniqueID); - f1.fSessionid = OidOp.SessionId(); - f1.uniqueID = uniqueID; - f1.fDec = dec; - thdFcnFailure = false; - int err = dbrm.lookup(OidOp.OID(), lbidRanges); - if (err) { - cerr << "doAColScan: BRM LBID range lookup failure (1)\n"; - throw runtime_error("doAColScan: BRM LBID range lookup failure (1)"); - } - - err = dbrm.getHWM(OidOp.OID(), hwm); - if (err) { - cerr << "doAColScan: BRM HWM lookup failure (3)" << endl; - throw runtime_error("doAColScan: BRM HWM lookup failure (3)"); - } - f1.fNumMsgs = hwm/OidOp.fColType.colWidth + (hwm % OidOp.fColType.colWidth ? 1 : 0); - - thread t1(f1); - - bpp.createBPP(bs); - dec->write(bs); - bs.restart(); - - uint32_t rangeSize=0, totalBlks = 0; - clock_gettime(CLOCK_REALTIME, &ts1); -// cout << "BPP scaning\n"; - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) { - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - cerr << "pColScanStep::sendPrimitiveMessages: dbrm.lookup failed for lbid " << lbid << endl; - abort(); - } - - if (hwm < fbo) - continue; - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - bpp.setLBID(lbid); - bpp.setCount(rangeSize/OidOp.fColType.colWidth + (rangeSize % OidOp.fColType.colWidth ? 1 : 0)); - bpp.runBPP(bs); - dec->write(bs); -// cout << "sending the BPP\n"; - bpp.reset(); - bs.restart(); - totalBlks += rangeSize; - } - - t1.join(); - clock_gettime(CLOCK_REALTIME, &ts2); - timespec_sub(ts1, ts2, diff); - float rate = 0; - cout << "ColStep stats OID: " << OidOp.OID() - << " " <<(diff.tv_sec+(diff.tv_nsec/1000000000.0)) << "s" - << "\tFilters: " << filters - << "\tBlocks : " << (int) totalBlks; - - rate = totalBlks/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\tBlks/sec " << rate << endl; - - if (thdFcnFailure) - cerr << "There was a failure in the read thread." << endl; - - bpp.destroyBPP(bs); - dec->write(bs); - cout << endl; - -} - -void doBatchOp_filt(OidOperation &OidOp) -{ - struct timespec ts1, ts2, diff; - JobStepAssociation injs, outjs; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); - ThdFcn f1; - boost::shared_ptr sysCat = CalpontSystemCatalog::makeCalpontSystemCatalog(getpid()); - - ByteStream bs; - DBRM dbrm; - BRM::LBIDRange_v lbidRanges; - HWM_t hwm=0; - LBIDRange_v::iterator it; - OID_t tmp; - uint32_t fbo; - uint32_t uniqueID; - - BatchPrimitiveProcessorJL bpp; - uniqueID = dbrm.getUnique32(); - bpp.setUniqueID(uniqueID); - bpp.setSessionID(OidOp.SessionId()); - bpp.setStepID(OidOp.SessionId()); - - pColScanStep scan(injs, outjs, dec, sysCat, OidOp.fOid, OidOp.fOid, - OidOp.fSessionId, 0, OidOp.fSessionId, OidOp.fSessionId, OidOp.fSessionId, rm); - while (OidOp.FilterCount()>0) - { - int8_t cop; - int64_t value; - OidOp.deSerializeFilter(cop, value); - scan.addFilter(cop, value); - } - bpp.addFilterStep(scan); - - pColStep step(injs, outjs, dec, sysCat, OidOp.fOid + 1, OidOp.fOid + 1, - OidOp.fSessionId, 0, OidOp.fSessionId, OidOp.fSessionId, OidOp.fSessionId, rm); - while (OidOp.FilterCount()>0) - { - int8_t cop; - int64_t value; - OidOp.deSerializeFilter(cop, value); - step.addFilter(cop, value); - } - bpp.addFilterStep(step); - - execplan::CalpontSystemCatalog::ColType colType; - FilterStep filt(OidOp.fSessionId, OidOp.fSessionId, OidOp.fSessionId, colType); - filt.setBOP(OidOp.BOP()); - bpp.addFilterStep(filt); - - cout << "session number = " << OidOp.SessionId() << endl; -// dec->addSession(OidOp.SessionId()); -// dec->addStep(OidOp.SessionId(), OidOp.SessionId()); - dec->addQueue(uniqueID); - f1.fSessionid = OidOp.SessionId(); - f1.uniqueID = uniqueID; - f1.fDec = dec; - thdFcnFailure = false; - int err = dbrm.lookup(OidOp.OID(), lbidRanges); - if (err) { - cerr << "doBatchOp_filt: BRM LBID range lookup failure (1)\n"; - throw runtime_error("doAColScan: BRM LBID range lookup failure (1)"); - } - - err = dbrm.getHWM(OidOp.OID(), hwm); - if (err) { - cerr << "doBatchOp_filt: BRM HWM lookup failure (2)" << endl; - throw runtime_error("doBatchOp_filt: BRM HWM lookup failure (2)"); - } - f1.fNumMsgs = hwm/OidOp.fColType.colWidth + (hwm % OidOp.fColType.colWidth ? 1 : 0); - - thread t1(f1); - - bpp.createBPP(bs); - dec->write(bs); - bs.restart(); - - uint32_t rangeSize=0, totalBlks = 0; - clock_gettime(CLOCK_REALTIME, &ts1); -// cout << "BPP scaning\n"; - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) { - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - cerr << "doBatchOp_filt: dbrm.lookup failed for lbid (3)" << lbid << endl; - abort(); - } - - if (hwm < fbo) - continue; - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - bpp.setLBID(lbid); - bpp.setCount(rangeSize/OidOp.fColType.colWidth + (rangeSize % OidOp.fColType.colWidth ? 1 : 0)); - bpp.runBPP(bs); - dec->write(bs); -// cout << "sending the BPP\n"; - bpp.reset(); - bs.restart(); - totalBlks += rangeSize; - } - - t1.join(); - clock_gettime(CLOCK_REALTIME, &ts2); - timespec_sub(ts1, ts2, diff); - float rate = 0; - cout << "doBatchOp_filt stats OID: " << OidOp.OID() - << " " <<(diff.tv_sec+(diff.tv_nsec/1000000000.0)) << "s" - << "\tBlocks : " << (int) totalBlks; - - rate = totalBlks/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\tBlks/sec " << rate << endl; - - if (thdFcnFailure) - cerr << "There was a failure in the read thread." << endl; - - bpp.destroyBPP(bs); - dec->write(bs); - cout << endl; -} - - -void doBatchQueryOp(OperationList& OidOps) -{ - struct timespec ts1, ts2, diff; - - JobStepAssociation injs, outjs; - BatchPrimitiveProcessorJL bpp; - uint64_t rows = 0; - uint32_t blockTouched = 0; - DBRM dbrm; - - QryThdFcn f1(bpp, rows, blockTouched); - - OperationList::iterator filterOp = OidOps.begin(); - uint32_t sessionId = (*filterOp)->SessionId(); - uint32_t uniqueID = dbrm.getUnique32(); - bpp.setUniqueID(uniqueID); - bpp.setSessionID(sessionId); - bpp.setStepID(sessionId); - cout << "session number = " << sessionId << endl; - - - f1.fSessionid = sessionId; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); -// dec->addSession(sessionId); -// dec->addStep(sessionId, sessionId); - dec->addQueue(uniqueID); - - f1.fDec = dec; - f1.uniqueID = uniqueID; -// boost::shared_ptr sysCat = execplan::CalpontSystemCatalog::makeCalpontSystemCatalog(getpid()); - -//first column is made into the first scan filter step including filters - OID_t scanOid = (*filterOp)->fOid; - uint32_t scanWidth = (*filterOp)->ColumnWidth(); - uint32_t maxWidth = scanWidth; - - uint32_t pid = getpid(); - pColScanStep scan(injs, outjs, dec, execplan::CalpontSystemCatalog::makeCalpontSystemCatalog(pid), scanOid, scanOid, sessionId, 0, sessionId, sessionId, sessionId, rm); - - uint32_t filterCount = (*filterOp)->FilterCount(); - while ((*filterOp)->FilterCount()>0) - { - int8_t cop; - int64_t value; - (*filterOp)->deSerializeFilter(cop, value); - scan.addFilter(cop, value); - } - bpp.addFilterStep(scan); - -//Any other columns that are batch scans are added as filter steps, the rest as project steps. -//The last filter step is added as a passthru step into the project list. - - OperationList::iterator listend = OidOps.end(); - for(OperationList::iterator op = OidOps.begin() + 1; op != listend; ++op) - { - pColStep step(injs, outjs, dec, execplan::CalpontSystemCatalog::makeCalpontSystemCatalog(pid), (*op)->fOid, (*op)->fOid, sessionId, 0, sessionId, sessionId, sessionId, rm); - - if ((*op)->OpType()==OidOperation::BATCHSCAN) - { - filterCount += (*op)->FilterCount(); - while ((*op)->FilterCount()>0) - { - int8_t cop; - int64_t value; - (*op)->deSerializeFilter(cop, value); - step.addFilter(cop, value); - } - filterOp = op; - bpp.addFilterStep(step); - } - else - { - bpp.addProjectStep(step); - } - if ( (*op)->ColumnWidth() > maxWidth) - maxWidth = (*op)->ColumnWidth(); - } - - PassThruStep pass(injs, outjs, dec, (*filterOp)->ColumnType(), (*filterOp)->fOid, (*filterOp)->fOid, - sessionId, 0, sessionId, sessionId, sessionId, false, rm); - bpp.addProjectStep(pass); - - ByteStream bs; - BRM::LBIDRange_v lbidRanges; - HWM_t hwm=0; - LBIDRange_v::iterator it; - OID_t tmp; - uint32_t fbo; - - thdFcnFailure = false; - int err = dbrm.lookup(scanOid, lbidRanges); - if (err) { - cerr << "doQueryScan: BRM LBID range lookup failure (1)\n"; - throw runtime_error("doQueryScan: BRM LBID range lookup failure (1)"); - } - - err = dbrm.getHWM(scanOid, hwm); - if (err) { - cerr << "doQueryScan: BRM HWM lookup failure (3)" << endl; - throw runtime_error("doQueryScan: BRM HWM lookup failure (3)"); - } - f1.fNumMsgs = hwm/scanWidth + (hwm % scanWidth ? 1 : 0); - - thread t1(f1); - uint32_t cnt = dbrm.getExtentSize()/maxWidth; - - bpp.createBPP(bs); - dec->write(bs); - bs.restart(); - uint32_t rangeSize=0, totalBlks = 0; - clock_gettime(CLOCK_REALTIME, &ts1); -// cout << "BPP scaning\n"; - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) - { - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - cerr << "doBatchQuery dbrm.lookup failed for lbid " << lbid << endl; - abort(); - } - - if (hwm < fbo) - continue; - - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - uint32_t totallbid = rangeSize/scanWidth + (0 < rangeSize % scanWidth ? 1 : 0) ; - - while ( 0 < totallbid) - { - if (totallbid < cnt) cnt = totallbid; - bpp.setLBID(lbid); - bpp.setCount(cnt); - bpp.runBPP(bs); - dec->write(bs); -// cout << "sending the BPP with range cnt " << cnt << " lbid " << lbid << "\n"; - bpp.reset(); - bs.restart(); - lbid += cnt * scanWidth; - totallbid -= cnt; - } - - for (OperationList::iterator op = OidOps.begin(); op != OidOps.end(); ++op) - { - totalBlks += (uint32_t)(rangeSize * (double)( (double)(*op)->ColumnWidth()/scanWidth)); - } - } - - t1.join(); - clock_gettime(CLOCK_REALTIME, &ts2); - timespec_sub(ts1, ts2, diff); - - float rate = 0; - cout << "QueryScan stats - " << bpp.toString() - << "\tElapsed: " <<(diff.tv_sec+(diff.tv_nsec/1000000000.0)) << "s" - << "\tFilters: " << filterCount - << "\tBlocks : " << (int) totalBlks; - - rate = totalBlks/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\tBlks/sec " << rate << endl; - cout << "\tTouched Blocks: " << blockTouched; - rate = blockTouched/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\tTouched Blks/sec " << rate << endl; - - cout << "\tRows: " << rows; - rate = rows/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\t\tRows/sec " << fixed << setprecision(2) << rate << endl; - - - - if (thdFcnFailure) - cerr << "There was a failure in the read thread." << endl; - - bpp.destroyBPP(bs); - dec->write(bs); - cout << endl; -} - -void doBatchOp_step(OidOperation &OidOp) -{ - struct timespec ts1, ts2, diff; - DBRM dbrm; - BRM::LBIDRange_v lbidRanges; - HWM_t hwm=0; - LBIDRange_v::iterator it; - OID_t tmp; - uint32_t fbo; - uint32_t totalBlks=0; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); - ThdFcn f1; - JobStepAssociation injs, outjs; - - boost::shared_ptr sysCat = execplan::CalpontSystemCatalog::makeCalpontSystemCatalog(getpid()); - - pColStep step(injs, outjs, dec, sysCat, OidOp.fOid, OidOp.fOid, - OidOp.fSessionId, 0, OidOp.fSessionId, OidOp.fSessionId, OidOp.fSessionId, rm); - - int32_t filters = OidOp.FilterCount(); - while (OidOp.FilterCount()>0) - { - int8_t cop; - int64_t value; - OidOp.deSerializeFilter(cop, value); - step.addFilter(cop, value); - } - - BatchPrimitiveProcessorJL bpp; - ElementType et; - ByteStream obs; - uint32_t uniqueID = dbrm.getUnique32(); - bpp.setUniqueID(uniqueID); - bpp.setSessionID(OidOp.SessionId()); - bpp.setStepID(OidOp.SessionId()); - bpp.addFilterStep(step); - -// dec->addSession(OidOp.SessionId()); -// dec->addStep(OidOp.SessionId(), OidOp.SessionId()); - dec->addQueue(uniqueID); - f1.fSessionid = OidOp.SessionId(); - f1.uniqueID = uniqueID; - f1.fDec = dec; - f1.fNumMsgs = 0; - thdFcnFailure = false; - ByteStream ridlist; - uint16_t ridCount = 0; // BLOCK_SIZE/OidOp.ColumnWidth(); - - for (uint16_t i=0; iwrite(obs); - obs.restart(); - - clock_gettime(CLOCK_REALTIME, &ts1); - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) { - BRM::LBID_t lbid = (*it).start; - if (dbrm.lookup(lbid, 0, false, tmp, fbo)) - { - if (debug) - cerr << "pColScanStep::sendPrimitiveMessages: dbrm.lookup failed for lbid " << lbid << endl; - abort(); - } - - if (hwm < fbo) - continue; - - rangeSize = (hwm > (fbo + (*it).size - 1) ? (*it).size : hwm - fbo + 1); - for (unsigned i = 0; i < rangeSize; i++) - { - /* insert all rids for this LBID */ - for (uint32_t j = 0; j < BLOCK_SIZE/OidOp.fColType.colWidth; ++j) { - et.first = ((fbo+i) * BLOCK_SIZE/OidOp.fColType.colWidth) + j; - et.second = j; - bpp.addElementType(et); - } - /* If on a logical block boundary, send the primitive */ - if (i % OidOp.fColType.colWidth == (unsigned)OidOp.fColType.colWidth - 1) { -// cout << "serializing at extent offset " << i << endl; - bpp.runBPP(obs); - dec->write(obs); - bpp.reset(); - obs.restart(); - } - - if (debug && i+1==rangeSize) - cout - << "colStep: " << i+1 << "/" - << rangeSize << " " << obs.length() - << " lbid " << lbid+i << endl; - } - if (rangeSize % OidOp.fColType.colWidth) { -// cout << "serializing last msg\n"; - bpp.runBPP(obs); - dec->write(obs); - bpp.reset(); - obs.restart(); - } - totalBlks+=rangeSize; - } // for - - t1.join(); - clock_gettime(CLOCK_REALTIME, &ts2); - timespec_sub(ts1, ts2, diff); - float rate = 0; - cout << "ColStep stats OID: " << OidOp.OID() - << " " <<(diff.tv_sec+(diff.tv_nsec/1000000000.0)) << "s" - << "\tFilters: " << filters - << "\tBlocks : " << (int) totalBlks; - - rate = totalBlks/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\tBlks/sec " << rate << endl; - - if (thdFcnFailure) - cerr << "There was a failure in the read thread." << endl; - - bpp.destroyBPP(obs); - dec->write(obs); - - cout << endl; - -} - -// -// -void doListOp(const OID_t o=0) -{ - - DBRM dbrm; - BRM::LBIDRange_v lbidRanges; - LBIDRange_v::iterator it; - OID_t oid=3000; - HWM_t hwm=0; - - if (o!=0) { - int err = dbrm.lookup(o, lbidRanges); - if (err) - throw runtime_error("doAColScan: BRM LBID range lookup failure (1)"); - - err = dbrm.getHWM(o, hwm); - if (err) - throw runtime_error("doAColScan: BRM HWM lookup failure (3)"); - - cout << "Object ID: " << o << " HWM: " << hwm << endl; - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) - cout << "\tStart: " << (*it).start << " sz: " << (*it).size << endl; - } else { - for (; oid < 100000; oid++) { - - int err = dbrm.lookup(oid, lbidRanges); - if (lbidRanges.size()==0) - continue; - - if (err) - throw runtime_error("doAColScan: BRM LBID range lookup failure (1)"); - - err = dbrm.getHWM(oid, hwm); - if (err) - throw runtime_error("doAColScan: BRM HWM lookup failure (3)"); - - cout << "Object ID: " << oid << " HWM: " << hwm << endl; - for (it = lbidRanges.begin(); it != lbidRanges.end(); it++) - cout << "\tStart: " << (*it).start << " sz: " << (*it).size << endl; - hwm=0; - lbidRanges.clear(); - } // for (; oid... - } // else - -} // doListOp - -// -// do LoopBackOp - -void doLoopBack(const uint64_t loopcount) -{ - - ByteStream lbMsg; - struct timespec ts1; - struct timespec ts2; - struct timespec diff; - uint32_t sessionid = getpid(); - DBRM dbrm; - ResourceManager rm; - DistributedEngineComm* dec = DistributedEngineComm::instance(rm); - ThdFcn f1; - -// dec->addSession(sessionid); -// dec->addStep(sessionid, sessionid); - uint32_t uniqueID = dbrm.getUnique32(); - dec->addQueue(uniqueID); - f1.fSessionid = sessionid; - f1.uniqueID = uniqueID; - f1.fDec = dec; - f1.fNumMsgs = loopcount; - thdFcnFailure = false; - thread t1(f1); - lbMsg = formatLoopBackMsg(sessionid, uniqueID); - - cout << "Sending " << loopcount << " LOOPBACK requests" << endl; - clock_gettime(CLOCK_REALTIME, &ts1); - for (uint64_t i=0; i< loopcount; i++) - { - lbMsg = formatLoopBackMsg(sessionid, uniqueID); - dec->write(lbMsg); - } - clock_gettime(CLOCK_REALTIME, &ts2); - cout << loopcount << " LOOPBACK msgs sent" << endl; - - t1.join(); - timespec_sub(ts1, ts2, diff); - cout << "\ttotal runtime: " << (diff.tv_sec - +(diff.tv_nsec/1000000000.0)) << "s" << endl; - - float rate = 0; - rate = loopcount/(diff.tv_sec+(diff.tv_nsec/1000000000.0)); - cout << "\t" << rate << " rqsts/s" << endl; - dec->removeQueue(uniqueID); - -} //doLoopBack - -} //namespace - -/*--------------------------------------------------------------------------- -//Command line parameter definition -// -// -o -o -o . . . -// -s -// -t -// -d -// -eq -equal < == test of values in a block> -// -gt -greater-than < greater than (>) test of values in a block> -// -ge -greater-than-equal < greater than or equal to (>=) test of values in a block> -// -lt -less-than < less than (<) test of values in a block> -// -le -less-than-equal < less than or equal to (<=) test of values in a block> -// -ne -not-equal < not equal to (!=) test of values in a block> -// -bop <1 or 0> <1 AND 0 OR binary operator when 2 comparison filters are present> -// --list -list -l -// --loopback -loopback send loopback requests -// --concurrent run all jobs currently if set to true. defaults to false -// --lbid-trace -lb turn on lbid tracing -// --pm-profile -pmp turn on pm profiling ------------------------------------------------------------------------------*/ - - - -int main(int argc, char** argv) -{ - -int64_t eq_val=0; -int64_t gt_val=0; -int64_t ge_val=0; -int64_t lt_val=0; -int64_t le_val=0; -int64_t ne_val=0; -int64_t bop_val=0; -int64_t loopback_count=100000; -int64_t scanOid=0; -int64_t stepOid=0; -bool list=false; -//OID_t listOid=0; -string oidString; -vector oidv; -int ch=0; -bool concurrent_flag=false; -bool lbidtrace_flag=false; -bool pmprofile_flag=false; -bool query_flag=false; - - -enum CLA_ENUM { - OID=(int)0, - SCANOP=(int)1, - BLOCKOP=(int)2, - DEBUG=(int)3, - EQFILTER=(int)4, - GTFILTER=(int)5, - GEFILTER=(int)6, - LTFILTER=(int)7, - LEFILTER=(int)8, - NEFILTER=(int)9, - BOP=(int)10, - LISTOP=(int)11, - LOOPBACKOP=(int)12, - CONCURRENT=(int)13, - LBIDTRACE=(int)14, - PMPROFILE=(int)15, - INVALIDOP=(int)16, - BATCHSCANOP=(int)17, - BATCHSTEPOP=(int)18, - BATCHFILTOP=(int)19, - QUERYOP=(int)20 - -}; - -/** -// longopt struct -struct option { - const char *name; - int has_arg; - int *flag; - int val; -}; -**/ - -static struct -option long_options[] = -{ -// {const char *name, int has_arg, int *flag, int val}, - {"scan", required_argument, NULL, SCANOP }, - {"block", required_argument, NULL, BLOCKOP }, - {"debug", no_argument, NULL, DEBUG }, - {"equal", required_argument, NULL, EQFILTER }, - {"eq", required_argument, NULL, EQFILTER }, - {"greater-than", required_argument, NULL, GTFILTER }, - {"gt", required_argument, NULL, GTFILTER }, - {"greater-than-equal", required_argument, NULL, GEFILTER }, - {"ge", required_argument, NULL, GEFILTER }, - {"less-than", required_argument, NULL, LTFILTER }, - {"lt", required_argument, NULL, LTFILTER }, - {"less-than-equal", required_argument, NULL, LEFILTER }, - {"le", required_argument, NULL, LEFILTER }, - {"not-equal", required_argument, NULL, NEFILTER }, - {"ne", required_argument, NULL, NEFILTER }, - {"bop", optional_argument, NULL, BOP }, - {"list", no_argument, NULL, LISTOP }, - {"loopback", optional_argument, NULL, LOOPBACKOP }, - {"concurrent", no_argument, NULL, CONCURRENT }, - {"lbid-trace", no_argument, NULL, LBIDTRACE }, - {"lb", no_argument, NULL, LBIDTRACE }, - {"pm-prof", no_argument, NULL, PMPROFILE }, - {"pm-profile", no_argument, NULL, PMPROFILE }, - {"pmp", no_argument, NULL, PMPROFILE }, - {"batchscan", required_argument, NULL, BATCHSCANOP }, - {"batchstep", required_argument, NULL, BATCHSTEPOP }, - {"batchfilt", required_argument, NULL, BATCHFILTOP }, - {"queryop", no_argument, NULL, QUERYOP }, - {0, 0, 0, 0} -}; - -OidOperation* currOp=NULL; -OperationList OpList; - -if (argc <=1) { - usage(); -} - -// process command line arguments -while( (ch = getopt_long_only(argc, argv, "B:Z:F:ds:t:lcqp:", long_options, NULL)) != -1 ) -{ - - pid_t pidId = getpid(); - - switch (ch) { - - case SCANOP: - case 's': - if (optarg) - scanOid=getInt(optarg); - //cout << "OPT=" << ch << " ARG " << scanOid << endl; - currOp=NULL; - if (scanOid>0) - currOp = new OidOperation(scanOid, OidOperation::SCAN, pidId ); - else { - cout << "PingProc: scan missing or invalid OID parameter value" << endl; - break; - } - - if (currOp && currOp->isIntegralDataType()) - OpList.push_back(currOp); - else { - cout << "PingProc cannot process this ColumnType-oid: " << scanOid << endl; - delete currOp; - currOp=NULL; - } - break; - - case BATCHSCANOP: - case 'B': - if (optarg) - scanOid=getInt(optarg); - else - cout << "no optarg\n"; - cout << "OPT=" << ch << " ARG " << scanOid << endl; - currOp=NULL; - if (scanOid>0) - currOp = new OidOperation(scanOid, OidOperation::BATCHSCAN, pidId ); - else { - cout << "PingProc: batch scan missing or invalid OID parameter value" << endl; - break; - } - - if (currOp && currOp->isIntegralDataType()) - OpList.push_back(currOp); - else { - cout << "PingProc cannot process this ColumnType-oid: " << scanOid << endl; - delete currOp; - currOp=NULL; - } - break; - - case BATCHSTEPOP: - case 'Z': - if (optarg) - scanOid=getInt(optarg); - else - cout << "no optarg\n"; - cout << "OPT=" << ch << " ARG " << scanOid << endl; - currOp=NULL; - if (scanOid>0) - currOp = new OidOperation(scanOid, OidOperation::BATCHSTEP, pidId ); - else { - cout << "PingProc: batch step missing or invalid OID parameter value" << endl; - break; - } - - if (currOp && currOp->isIntegralDataType()) - OpList.push_back(currOp); - else { - cout << "PingProc cannot process this ColumnType-oid: " << scanOid << endl; - delete currOp; - currOp=NULL; - } - break; - - case BATCHFILTOP: - case 'F': - if (optarg) - scanOid=getInt(optarg); - else - cout << "no optarg\n"; - cout << "OPT=" << ch << " ARG " << scanOid << endl; - currOp=NULL; - if (scanOid>0) - currOp = new OidOperation(scanOid, OidOperation::BATCHFILT, pidId ); - else { - cout << "PingProc: batch filter missing or invalid OID parameter value" << endl; - break; - } - - if (currOp && currOp->isIntegralDataType()) - OpList.push_back(currOp); - else { - cout << "PingProc cannot process this ColumnType-oid: " << scanOid << endl; - delete currOp; - currOp=NULL; - } - break; - - case BLOCKOP: - case 't': - if (optarg) - stepOid=getInt(optarg); - //cout << "OPT=" << ch << " ARG " << stepOid << endl; - currOp=NULL; - if (stepOid>0) - currOp = new OidOperation(stepOid, OidOperation::BLOCK, pidId ); - else { - cout << "PingProc: step missing or invalid OID parameter value" << endl; - break; - } - - if (currOp && currOp->isIntegralDataType()) - OpList.push_back(currOp); - else { - cout << "PingProc cannot process this ColumnType-oid: " << stepOid << endl; - delete currOp; - currOp=NULL; - } - - break; - - case DEBUG: - case 'd': - //cout << "OPT=" << ch << endl; - debug=true; - break; - - case EQFILTER: - if (optarg) - eq_val=getInt(optarg); - else - eq_val=0; - cout << "OPT=" << ch << " ARG=" << eq_val << endl; - if (currOp) - currOp->addFilter(COMPARE_EQ, eq_val); - else - ; // TODO: error Processing - break; - - case GTFILTER: - if (optarg) - gt_val=getInt(optarg); - else - gt_val=0; - //cout << "OPT=" << ch << " ARG=" << gt_val << endl; - if (currOp) - currOp->addFilter(COMPARE_GT, gt_val); - break; - - case GEFILTER: - if (optarg) - ge_val=getInt(optarg); - else - ge_val=0; - //cout << "OPT=" << ch << " ARG=" << ge_val << endl; - if (currOp) - currOp->addFilter(COMPARE_GE, ge_val); - break; - - case LTFILTER: - if (optarg) - lt_val=getInt(optarg); - else - lt_val=0; - //cout << "OPT=" << ch << " ARG=" << lt_val << endl; - if (currOp) - currOp->addFilter(COMPARE_LT, lt_val); - break; - - case LEFILTER: - if (optarg) - le_val=getInt(optarg); - else - le_val=0; - //cout << "OPT=" << ch << " ARG=" << le_val << endl; - if (currOp) - currOp->addFilter(COMPARE_LE, le_val); - break; - - case NEFILTER: - case 'n': - if (optarg) - ne_val=getInt(optarg); - else - ne_val=0; - //cout << "OPT=" << ch << " ARG=" << ne_val << endl; - if (currOp) - currOp->addFilter(COMPARE_NE, ne_val); - break; - - case BOP: - case 'b': - if (optarg) - bop_val=getInt(optarg); - else - bop_val=1; // assume AND - //cout << "OPT=" << ch << " ARG=" << bop_val << endl; - if (currOp) - currOp->BOP(bop_val?BOP_AND:BOP_OR); - break; - - case LISTOP: - case 'l': - /** - if (optarg) - listOid=getInt(optarg); - else - listOid=0; - cout << "OPT=" << ch << " LISTOP " << listOid << endl; - **/ - list=true; - break; - - case LOOPBACKOP: - case 'p': - if (optarg) - loopback_count=getInt(optarg); - - //cout << "OPT=" << ch << " LOOPBACKOP " << loopback_count << endl; - currOp=NULL; - currOp = new OidOperation(0, OidOperation::LOOPBACK, pidId ); - OpList.push_back(currOp); - break; - - case 'c': - case CONCURRENT: - concurrent_flag=true; - //cout << "OPT=" << ch << " CONCURRENT " << concurrent_flag << endl; - break; - - case LBIDTRACE: - lbidtrace_flag=true; - //cout << "OPT=" << ch << " CONCURRENT " << concurrent_flag << endl; - if (currOp) - currOp->setLbidTraceOn(); - break; - - case PMPROFILE: - pmprofile_flag=true; - //cout << "OPT=" << ch << " CONCURRENT " << concurrent_flag << endl; - if (currOp) - currOp->setPMProfileOn(); - break; - case 'q': - case QUERYOP: - query_flag=true; -// cout << "OPT=" << ch << " QUERY FLAG " << query_flag << endl; - break; - - - case '?': - default: - cout << "optarg " << optarg << endl; - usage(); - - } - - if (list==true) - break; - -} // while - -// if list is requested, print the listing and exit -// -vector BatchScanThreads; -vector BatchStepThreads; -vector BatchFiltThreads; -vector ColScanThreads; -vector ColStepThreads; -vector DictScanThreads; -vector DictSigThreads; -vector thrArray; -if (query_flag) -{ - cout << "starting batch query thread\n"; - struct BatchQueryThr* qt = new struct BatchQueryThr(OpList); - thread* t1 = new thread(*qt); - if (concurrent_flag) - thrArray.push_back(t1); - else - t1->join(); -} -else -if (list) { - doListOp(); -} else { - - for (uint32_t i=0; iOpType()==OidOperation::LOOPBACK) { - doLoopBack(loopback_count); - } - - else if (OpList[i]->OpType()==OidOperation::SCAN) { - struct ColScanThr* cst = new struct ColScanThr(*OpList[i]); - ColScanThreads.push_back(cst); - thread* t1 = new thread(*cst); - if (concurrent_flag) - thrArray.push_back(t1); - else - { - t1->join(); - delete t1; - } - } - - else if (OpList[i]->OpType()==OidOperation::BLOCK) { - struct ColStepThr* cst = new struct ColStepThr(*OpList[i]); - ColStepThreads.push_back(cst); - thread* t1 = new thread(*cst); - if (concurrent_flag) - thrArray.push_back(t1); - else - { - t1->join(); - delete t1; - } - } - - else if (OpList[i]->OpType()==OidOperation::BATCHSCAN) { - cout << "starting batch scan thread\n"; - struct BatchScanThr* cst = new struct BatchScanThr(*OpList[i]); - BatchScanThreads.push_back(cst); - thread* t1 = new thread(*cst); - if (concurrent_flag) - thrArray.push_back(t1); - else - { - t1->join(); - delete t1; - } - } - - else if (OpList[i]->OpType()==OidOperation::BATCHSTEP) { - cout << "starting batch step thread\n"; - struct BatchStepThr* cst = new struct BatchStepThr(*OpList[i]); - BatchStepThreads.push_back(cst); - thread* t1 = new thread(*cst); - if (concurrent_flag) - thrArray.push_back(t1); - else - { - t1->join(); - delete t1; - } - } - - else if (OpList[i]->OpType()==OidOperation::BATCHFILT) { - cout << "starting batch filt thread\n"; - struct BatchFiltThr* cst = new struct BatchFiltThr(*OpList[i]); - BatchFiltThreads.push_back(cst); - thread* t1 = new thread(*cst); - if (concurrent_flag) - thrArray.push_back(t1); - else - { - t1->join(); - delete t1; - } - i += 2; - } - } // for - -} // else - - -// join threads to main -for (uint32_t i=0; ijoin(); - -// clean up -for(uint32_t i=0; i < OpList.size(); i++) - delete OpList[i]; -OpList.clear(); - -for(uint32_t i=0; i < BatchScanThreads.size(); i++) - delete BatchScanThreads[i]; -BatchScanThreads.clear(); - -for(uint32_t i=0; i < BatchStepThreads.size(); i++) - delete BatchStepThreads[i]; -BatchStepThreads.clear(); - -for(uint32_t i=0; i < BatchFiltThreads.size(); i++) - delete BatchFiltThreads[i]; -BatchFiltThreads.clear(); - -for(uint32_t i=0; i < ColScanThreads.size(); i++) - delete ColScanThreads[i]; -ColScanThreads.clear(); - -for(uint32_t i=0; i < ColStepThreads.size(); i++) - delete ColStepThreads[i]; -ColStepThreads.clear(); - -for(uint32_t i=0; i < DictScanThreads.size(); i++) - delete DictScanThreads[i]; -DictScanThreads.clear(); - -for(uint32_t i=0; i < DictSigThreads.size(); i++) - delete DictSigThreads[i]; -DictSigThreads.clear(); - -for (uint32_t i=0; i < thrArray.size(); i++) - delete thrArray[i]; -thrArray.clear(); - -} //main() - diff --git a/tools/qfe/Makefile.am b/tools/qfe/Makefile.am deleted file mode 100644 index 1c27bdf2..00000000 --- a/tools/qfe/Makefile.am +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id$ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -AM_YFLAGS = -d -p qfe -AM_LFLAGS = -i -Pqfe -olex.yy.c -bin_PROGRAMS = QFE -QFE_SOURCES = \ -cseputils.cpp \ -ddlstmts.cpp \ -parsequery.cpp \ -returnedrows.cpp \ -sendcsep.cpp \ -server.cpp \ -socketio.cpp \ -qfelexer.lpp \ -qfeparser.ypp -QFE_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -QFE_LDFLAGS = @idb_common_ldflags@ @idb_write_libs@ @idb_exec_libs@ $(AM_LDFLAGS) -BUILT_SOURCES = qfeparser.cpp qfelexer.cpp qfeparser.h - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/qfe/bison-win.cpp b/tools/qfe/bison-win.cpp deleted file mode 100644 index ecb5c34d..00000000 --- a/tools/qfe/bison-win.cpp +++ /dev/null @@ -1,2071 +0,0 @@ - -/* A Bison parser, made by GNU Bison 2.4.1. */ - -/* Skeleton implementation for Bison's Yacc-like parsers in C - - Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 - Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -/* C LALR(1) parser skeleton written by Richard Stallman, by - simplifying the original so-called "semantic" parser. */ - -/* All symbols defined below should begin with yy or YY, to avoid - infringing on user name space. This should be done even for local - variables, as they might otherwise be expanded by user macros. - There are some unavoidable exceptions within include files to - define necessary library symbols; they are noted "INFRINGES ON - USER NAME SPACE" below. */ - -/* Identify Bison output. */ -#define YYBISON 1 - -/* Bison version. */ -#define YYBISON_VERSION "2.4.1" - -/* Skeleton name. */ -#define YYSKELETON_NAME "yacc.c" - -/* Pure parsers. */ -#define YYPURE 0 - -/* Push parsers. */ -#define YYPUSH 0 - -/* Pull parsers. */ -#define YYPULL 1 - -/* Using locations. */ -#define YYLSP_NEEDED 0 - -/* Substitute the variable and function names. */ -#define yyparse qfeparse -#define yylex qfelex -#define yyerror qfeerror -#define yylval qfelval -#define yychar qfechar -#define yydebug qfedebug -#define yynerrs qfenerrs - - -/* Copy the first part of user declarations. */ - -/* Line 189 of yacc.c */ -#line 1 "qfeparser.ypp" - -#include -#include -#include -using namespace std; - -namespace qfe -{ -extern string DefaultSchema; -} - -int qfeerror(const char *s); -int qfelex(void); - -#include "calpontselectexecutionplan.h" -#include "simplecolumn.h" -#include "calpontsystemcatalog.h" -#include "aggregatecolumn.h" -execplan::CalpontSelectExecutionPlan* ParserCSEP; -boost::shared_ptr ParserCSC; -namespace execplan -{ -class ReturnedColumn; -} - -#include "cseputils.h" - - - -/* Line 189 of yacc.c */ -#line 111 "bison-win.cpp" - -/* Enabling traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif - -/* Enabling verbose error messages. */ -#ifdef YYERROR_VERBOSE -# undef YYERROR_VERBOSE -# define YYERROR_VERBOSE 1 -#else -# define YYERROR_VERBOSE 0 -#endif - -/* Enabling the token table. */ -#ifndef YYTOKEN_TABLE -# define YYTOKEN_TABLE 0 -#endif - - -/* Tokens. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - /* Put the tokens into the symbol table, so that GDB and other debuggers - know about them. */ - enum yytokentype { - CHAR_CONST = 258, - RELOP = 259, - LOGICOP = 260, - QFEP_SELECT = 261, - QFEP_FROM = 262, - QFEP_WHERE = 263, - GROUPBY = 264, - OBJNAME = 265, - INT_CONST = 266, - LIMIT = 267, - ORDERBY = 268, - ASC = 269, - DESC = 270, - AS = 271, - FUNC = 272 - }; -#endif - - - -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE -{ - -/* Line 214 of yacc.c */ -#line 31 "qfeparser.ypp" - - execplan::ReturnedColumn* rcp; - std::string* cp; - std::pair* cvp; - - - -/* Line 214 of yacc.c */ -#line 172 "bison-win.cpp" -} YYSTYPE; -# define YYSTYPE_IS_TRIVIAL 1 -# define yystype YYSTYPE /* obsolescent; will be withdrawn */ -# define YYSTYPE_IS_DECLARED 1 -#endif - - -/* Copy the second part of user declarations. */ - - -/* Line 264 of yacc.c */ -#line 184 "bison-win.cpp" - -#ifdef short -# undef short -#endif - -#ifdef YYTYPE_UINT8 -typedef YYTYPE_UINT8 yytype_uint8; -#else -typedef unsigned char yytype_uint8; -#endif - -#ifdef YYTYPE_INT8 -typedef YYTYPE_INT8 yytype_int8; -#elif (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -typedef signed char yytype_int8; -#else -typedef short int yytype_int8; -#endif - -#ifdef YYTYPE_UINT16 -typedef YYTYPE_UINT16 yytype_uint16; -#else -typedef unsigned short int yytype_uint16; -#endif - -#ifdef YYTYPE_INT16 -typedef YYTYPE_INT16 yytype_int16; -#else -typedef short int yytype_int16; -#endif - -#ifndef YYSIZE_T -# ifdef __SIZE_TYPE__ -# define YYSIZE_T __SIZE_TYPE__ -# elif defined size_t -# define YYSIZE_T size_t -# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -# include /* INFRINGES ON USER NAME SPACE */ -# define YYSIZE_T size_t -# else -# define YYSIZE_T unsigned int -# endif -#endif - -#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) - -#ifndef YY_ -# if YYENABLE_NLS -# if ENABLE_NLS -# include /* INFRINGES ON USER NAME SPACE */ -# define YY_(msgid) dgettext ("bison-runtime", msgid) -# endif -# endif -# ifndef YY_ -# define YY_(msgid) msgid -# endif -#endif - -/* Suppress unused-variable warnings by "using" E. */ -#if ! defined lint || defined __GNUC__ -# define YYUSE(e) ((void) (e)) -#else -# define YYUSE(e) /* empty */ -#endif - -/* Identity function, used to suppress warnings about constant conditions. */ -#ifndef lint -# define YYID(n) (n) -#else -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static int -YYID (int yyi) -#else -static int -YYID (yyi) - int yyi; -#endif -{ - return yyi; -} -#endif - -#if ! defined yyoverflow || YYERROR_VERBOSE - -/* The parser invokes alloca or malloc; define the necessary symbols. */ - -# ifdef YYSTACK_USE_ALLOCA -# if YYSTACK_USE_ALLOCA -# ifdef __GNUC__ -# define YYSTACK_ALLOC __builtin_alloca -# elif defined __BUILTIN_VA_ARG_INCR -# include /* INFRINGES ON USER NAME SPACE */ -# elif defined _AIX -# define YYSTACK_ALLOC __alloca -# elif defined _MSC_VER -# include /* INFRINGES ON USER NAME SPACE */ -# define alloca _alloca -# else -# define YYSTACK_ALLOC alloca -# if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -# include /* INFRINGES ON USER NAME SPACE */ -# ifndef _STDLIB_H -# define _STDLIB_H 1 -# endif -# endif -# endif -# endif -# endif - -# ifdef YYSTACK_ALLOC - /* Pacify GCC's `empty if-body' warning. */ -# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) -# ifndef YYSTACK_ALLOC_MAXIMUM - /* The OS might guarantee only one guard page at the bottom of the stack, - and a page size can be as small as 4096 bytes. So we cannot safely - invoke alloca (N) if N exceeds 4096. Use a slightly smaller number - to allow for a few compiler-allocated temporary stack slots. */ -# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ -# endif -# else -# define YYSTACK_ALLOC YYMALLOC -# define YYSTACK_FREE YYFREE -# ifndef YYSTACK_ALLOC_MAXIMUM -# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM -# endif -# if (defined __cplusplus && ! defined _STDLIB_H \ - && ! ((defined YYMALLOC || defined malloc) \ - && (defined YYFREE || defined free))) -# include /* INFRINGES ON USER NAME SPACE */ -# ifndef _STDLIB_H -# define _STDLIB_H 1 -# endif -# endif -# ifndef YYMALLOC -# define YYMALLOC malloc -# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# ifndef YYFREE -# define YYFREE free -# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -void free (void *); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# endif -#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - - -#if (! defined yyoverflow \ - && (! defined __cplusplus \ - || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) - -/* A type that is properly aligned for any stack member. */ -union yyalloc -{ - yytype_int16 yyss_alloc; - YYSTYPE yyvs_alloc; -}; - -/* The size of the maximum gap between one aligned stack and the next. */ -# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) - -/* The size of an array large to enough to hold all stacks, each with - N elements. */ -# define YYSTACK_BYTES(N) \ - ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ - + YYSTACK_GAP_MAXIMUM) - -/* Copy COUNT objects from FROM to TO. The source and destination do - not overlap. */ -# ifndef YYCOPY -# if defined __GNUC__ && 1 < __GNUC__ -# define YYCOPY(To, From, Count) \ - __builtin_memcpy (To, From, (Count) * sizeof (*(From))) -# else -# define YYCOPY(To, From, Count) \ - do \ - { \ - YYSIZE_T yyi; \ - for (yyi = 0; yyi < (Count); yyi++) \ - (To)[yyi] = (From)[yyi]; \ - } \ - while (YYID (0)) -# endif -# endif - -/* Relocate STACK from its old location to the new one. The - local variables YYSIZE and YYSTACKSIZE give the old and new number of - elements in the stack, and YYPTR gives the new location of the - stack. Advance YYPTR to a properly aligned location for the next - stack. */ -# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ - do \ - { \ - YYSIZE_T yynewbytes; \ - YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ - Stack = &yyptr->Stack_alloc; \ - yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ - yyptr += yynewbytes / sizeof (*yyptr); \ - } \ - while (YYID (0)) - -#endif - -/* YYFINAL -- State number of the termination state. */ -#define YYFINAL 12 -/* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 60 - -/* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 24 -/* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 22 -/* YYNRULES -- Number of rules. */ -#define YYNRULES 41 -/* YYNRULES -- Number of states. */ -#define YYNSTATES 67 - -/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ -#define YYUNDEFTOK 2 -#define YYMAXUTOK 272 - -#define YYTRANSLATE(YYX) \ - ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) - -/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ -static const yytype_uint8 yytranslate[] = -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 20, 21, 2, 2, 19, 2, 22, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 23, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17 -}; - -#if YYDEBUG -/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in - YYRHS. */ -static const yytype_uint8 yyprhs[] = -{ - 0, 0, 3, 13, 15, 19, 21, 23, 28, 31, - 32, 35, 38, 39, 41, 43, 45, 48, 49, 52, - 56, 62, 64, 68, 74, 76, 80, 82, 84, 85, - 88, 90, 94, 96, 98, 99, 103, 104, 106, 108, - 109, 112 -}; - -/* YYRHS -- A `-1'-separated list of the rules' RHS. */ -static const yytype_int8 yyrhs[] = -{ - 25, 0, -1, 6, 26, 7, 32, 35, 40, 43, - 45, 18, -1, 29, -1, 26, 19, 29, -1, 37, - -1, 28, -1, 17, 20, 27, 21, -1, 27, 30, - -1, -1, 31, 10, -1, 31, 3, -1, -1, 16, - -1, 34, -1, 37, -1, 33, 30, -1, -1, 8, - 36, -1, 37, 4, 39, -1, 36, 5, 37, 4, - 39, -1, 38, -1, 38, 22, 38, -1, 38, 22, - 38, 22, 38, -1, 10, -1, 23, 10, 23, -1, - 3, -1, 11, -1, -1, 9, 41, -1, 42, -1, - 41, 19, 42, -1, 37, -1, 11, -1, -1, 13, - 41, 44, -1, -1, 14, -1, 15, -1, -1, 12, - 11, -1, 12, 11, 19, 11, -1 -}; - -/* YYRLINE[YYN] -- source line where rule number YYN was defined. */ -static const yytype_uint16 yyrline[] = -{ - 0, 55, 55, 63, 69, 77, 87, 90, 98, 102, - 103, 108, 116, 117, 120, 124, 144, 147, 148, 151, - 163, 179, 190, 202, 217, 218, 224, 230, 238, 239, - 243, 244, 248, 249, 256, 257, 261, 262, 263, 267, - 268, 274 -}; -#endif - -#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE -/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. - First, the terminals, then, starting at YYNTOKENS, nonterminals. */ -static const char *const yytname[] = -{ - "$end", "error", "$undefined", "CHAR_CONST", "RELOP", "LOGICOP", - "QFEP_SELECT", "QFEP_FROM", "QFEP_WHERE", "GROUPBY", "OBJNAME", - "INT_CONST", "LIMIT", "ORDERBY", "ASC", "DESC", "AS", "FUNC", "';'", - "','", "'('", "')'", "'.'", "'`'", "$accept", "statement", - "select_column_list", "select_column_name", "func_col", - "aliased_column_name", "opt_alias", "opt_as", "table_spec", "table_name", - "aliased_table_name", "opt_where_clause", "filter_predicate_list", - "obj_name", "obj_name_aux", "constant", "opt_groupby_clause", - "groupby_items_list", "groupby_item", "opt_orderby_clause", - "opt_direction", "opt_limit_clause", 0 -}; -#endif - -# ifdef YYPRINT -/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to - token YYLEX-NUM. */ -static const yytype_uint16 yytoknum[] = -{ - 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, - 265, 266, 267, 268, 269, 270, 271, 272, 59, 44, - 40, 41, 46, 96 -}; -# endif - -/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ -static const yytype_uint8 yyr1[] = -{ - 0, 24, 25, 26, 26, 27, 27, 28, 29, 30, - 30, 30, 31, 31, 32, 33, 34, 35, 35, 36, - 36, 37, 37, 37, 38, 38, 39, 39, 40, 40, - 41, 41, 42, 42, 43, 43, 44, 44, 44, 45, - 45, 45 -}; - -/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ -static const yytype_uint8 yyr2[] = -{ - 0, 2, 9, 1, 3, 1, 1, 4, 2, 0, - 2, 2, 0, 1, 1, 1, 2, 0, 2, 3, - 5, 1, 3, 5, 1, 3, 1, 1, 0, 2, - 1, 3, 1, 1, 0, 3, 0, 1, 1, 0, - 2, 4 -}; - -/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state - STATE-NUM when YYTABLE doesn't specify something else to do. Zero - means the default is an error. */ -static const yytype_uint8 yydefact[] = -{ - 0, 0, 0, 24, 0, 0, 0, 9, 6, 3, - 5, 21, 1, 0, 0, 0, 0, 13, 8, 0, - 0, 0, 25, 17, 9, 14, 15, 4, 11, 10, - 22, 7, 0, 28, 16, 0, 18, 0, 0, 34, - 23, 0, 0, 33, 32, 29, 30, 0, 39, 0, - 26, 27, 19, 0, 36, 0, 0, 0, 31, 37, - 38, 35, 40, 2, 20, 0, 41 -}; - -/* YYDEFGOTO[NTERM-NUM]. */ -static const yytype_int8 yydefgoto[] = -{ - -1, 2, 6, 7, 8, 9, 18, 19, 23, 24, - 25, 33, 36, 10, 11, 52, 39, 45, 46, 48, - 61, 56 -}; - -/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing - STATE-NUM. */ -#define YYPACT_NINF -20 -static const yytype_int8 yypact[] = -{ - 8, -8, 4, -20, 5, 17, 3, 2, -20, -20, - -20, 9, -20, -8, 1, -2, -8, -20, -20, 10, - -2, 13, -20, 22, 2, -20, -20, -20, -20, -20, - 15, -20, -2, 26, -20, -2, 31, 35, -4, 27, - -20, -2, 0, -20, -20, 23, -20, -4, 29, 39, - -20, -20, -20, -4, 14, 33, 28, 0, -20, -20, - -20, -20, 30, -20, -20, 34, -20 -}; - -/* YYPGOTO[NTERM-NUM]. */ -static const yytype_int8 yypgoto[] = -{ - -20, -20, -20, 37, -20, 32, 36, -20, -20, -20, - -20, -20, -20, -15, -19, -10, -20, 6, -1, -20, - -20, -20 -}; - -/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If - positive, shift that token. If negative, reduce the rule which - number is the opposite. If zero, do what YYDEFACT says. - If YYTABLE_NINF, syntax error. */ -#define YYTABLE_NINF -13 -static const yytype_int8 yytable[] = -{ - 26, 30, 3, 50, 12, -12, 3, 43, 3, 4, - 15, 51, -12, 28, 1, 5, 40, 37, 17, 5, - 29, 5, 16, 44, 22, 13, 49, 14, 59, 60, - 32, 20, 44, 53, 31, 38, 41, 35, 44, 42, - 47, 55, 53, 57, 62, 66, 63, 64, 27, 65, - 21, 0, 58, 54, 0, 0, 0, 0, 0, 0, - 34 -}; - -static const yytype_int8 yycheck[] = -{ - 15, 20, 10, 3, 0, 3, 10, 11, 10, 17, - 7, 11, 10, 3, 6, 23, 35, 32, 16, 23, - 10, 23, 19, 38, 23, 20, 41, 10, 14, 15, - 8, 22, 47, 19, 21, 9, 5, 22, 53, 4, - 13, 12, 19, 4, 11, 11, 18, 57, 16, 19, - 13, -1, 53, 47, -1, -1, -1, -1, -1, -1, - 24 -}; - -/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing - symbol of state STATE-NUM. */ -static const yytype_uint8 yystos[] = -{ - 0, 6, 25, 10, 17, 23, 26, 27, 28, 29, - 37, 38, 0, 20, 10, 7, 19, 16, 30, 31, - 22, 27, 23, 32, 33, 34, 37, 29, 3, 10, - 38, 21, 8, 35, 30, 22, 36, 37, 9, 40, - 38, 5, 4, 11, 37, 41, 42, 13, 43, 37, - 3, 11, 39, 19, 41, 12, 45, 4, 42, 14, - 15, 44, 11, 18, 39, 19, 11 -}; - -#define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) -#define YYEMPTY (-2) -#define YYEOF 0 - -#define YYACCEPT goto yyacceptlab -#define YYABORT goto yyabortlab -#define YYERROR goto yyerrorlab - - -/* Like YYERROR except do call yyerror. This remains here temporarily - to ease the transition to the new meaning of YYERROR, for GCC. - Once GCC version 2 has supplanted version 1, this can go. */ - -#define YYFAIL goto yyerrlab - -#define YYRECOVERING() (!!yyerrstatus) - -#define YYBACKUP(Token, Value) \ -do \ - if (yychar == YYEMPTY && yylen == 1) \ - { \ - yychar = (Token); \ - yylval = (Value); \ - yytoken = YYTRANSLATE (yychar); \ - YYPOPSTACK (1); \ - goto yybackup; \ - } \ - else \ - { \ - yyerror (YY_("syntax error: cannot back up")); \ - YYERROR; \ - } \ -while (YYID (0)) - - -#define YYTERROR 1 -#define YYERRCODE 256 - - -/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. - If N is 0, then set CURRENT to the empty location which ends - the previous symbol: RHS[0] (always defined). */ - -#define YYRHSLOC(Rhs, K) ((Rhs)[K]) -#ifndef YYLLOC_DEFAULT -# define YYLLOC_DEFAULT(Current, Rhs, N) \ - do \ - if (YYID (N)) \ - { \ - (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ - (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ - (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ - (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ - } \ - else \ - { \ - (Current).first_line = (Current).last_line = \ - YYRHSLOC (Rhs, 0).last_line; \ - (Current).first_column = (Current).last_column = \ - YYRHSLOC (Rhs, 0).last_column; \ - } \ - while (YYID (0)) -#endif - - -/* YY_LOCATION_PRINT -- Print the location on the stream. - This macro was not mandated originally: define only if we know - we won't break user code: when these are the locations we know. */ - -#ifndef YY_LOCATION_PRINT -# if YYLTYPE_IS_TRIVIAL -# define YY_LOCATION_PRINT(File, Loc) \ - fprintf (File, "%d.%d-%d.%d", \ - (Loc).first_line, (Loc).first_column, \ - (Loc).last_line, (Loc).last_column) -# else -# define YY_LOCATION_PRINT(File, Loc) ((void) 0) -# endif -#endif - - -/* YYLEX -- calling `yylex' with the right arguments. */ - -#ifdef YYLEX_PARAM -# define YYLEX yylex (YYLEX_PARAM) -#else -# define YYLEX yylex () -#endif - -/* Enable debugging if requested. */ -#if YYDEBUG - -# ifndef YYFPRINTF -# include /* INFRINGES ON USER NAME SPACE */ -# define YYFPRINTF fprintf -# endif - -# define YYDPRINTF(Args) \ -do { \ - if (yydebug) \ - YYFPRINTF Args; \ -} while (YYID (0)) - -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ -do { \ - if (yydebug) \ - { \ - YYFPRINTF (stderr, "%s ", Title); \ - yy_symbol_print (stderr, \ - Type, Value); \ - YYFPRINTF (stderr, "\n"); \ - } \ -} while (YYID (0)) - - -/*--------------------------------. -| Print this symbol on YYOUTPUT. | -`--------------------------------*/ - -/*ARGSUSED*/ -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static void -yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -#else -static void -yy_symbol_value_print (yyoutput, yytype, yyvaluep) - FILE *yyoutput; - int yytype; - YYSTYPE const * const yyvaluep; -#endif -{ - if (!yyvaluep) - return; -# ifdef YYPRINT - if (yytype < YYNTOKENS) - YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); -# else - YYUSE (yyoutput); -# endif - switch (yytype) - { - default: - break; - } -} - - -/*--------------------------------. -| Print this symbol on YYOUTPUT. | -`--------------------------------*/ - -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static void -yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -#else -static void -yy_symbol_print (yyoutput, yytype, yyvaluep) - FILE *yyoutput; - int yytype; - YYSTYPE const * const yyvaluep; -#endif -{ - if (yytype < YYNTOKENS) - YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); - else - YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); - - yy_symbol_value_print (yyoutput, yytype, yyvaluep); - YYFPRINTF (yyoutput, ")"); -} - -/*------------------------------------------------------------------. -| yy_stack_print -- Print the state stack from its BOTTOM up to its | -| TOP (included). | -`------------------------------------------------------------------*/ - -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static void -yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) -#else -static void -yy_stack_print (yybottom, yytop) - yytype_int16 *yybottom; - yytype_int16 *yytop; -#endif -{ - YYFPRINTF (stderr, "Stack now"); - for (; yybottom <= yytop; yybottom++) - { - int yybot = *yybottom; - YYFPRINTF (stderr, " %d", yybot); - } - YYFPRINTF (stderr, "\n"); -} - -# define YY_STACK_PRINT(Bottom, Top) \ -do { \ - if (yydebug) \ - yy_stack_print ((Bottom), (Top)); \ -} while (YYID (0)) - - -/*------------------------------------------------. -| Report that the YYRULE is going to be reduced. | -`------------------------------------------------*/ - -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static void -yy_reduce_print (YYSTYPE *yyvsp, int yyrule) -#else -static void -yy_reduce_print (yyvsp, yyrule) - YYSTYPE *yyvsp; - int yyrule; -#endif -{ - int yynrhs = yyr2[yyrule]; - int yyi; - unsigned long int yylno = yyrline[yyrule]; - YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", - yyrule - 1, yylno); - /* The symbols being reduced. */ - for (yyi = 0; yyi < yynrhs; yyi++) - { - YYFPRINTF (stderr, " $%d = ", yyi + 1); - yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], - &(yyvsp[(yyi + 1) - (yynrhs)]) - ); - YYFPRINTF (stderr, "\n"); - } -} - -# define YY_REDUCE_PRINT(Rule) \ -do { \ - if (yydebug) \ - yy_reduce_print (yyvsp, Rule); \ -} while (YYID (0)) - -/* Nonzero means print parse trace. It is left uninitialized so that - multiple parsers can coexist. */ -int yydebug; -#else /* !YYDEBUG */ -# define YYDPRINTF(Args) -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) -# define YY_STACK_PRINT(Bottom, Top) -# define YY_REDUCE_PRINT(Rule) -#endif /* !YYDEBUG */ - - -/* YYINITDEPTH -- initial size of the parser's stacks. */ -#ifndef YYINITDEPTH -# define YYINITDEPTH 200 -#endif - -/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only - if the built-in stack extension method is used). - - Do not make this value too large; the results are undefined if - YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) - evaluated with infinite-precision integer arithmetic. */ - -#ifndef YYMAXDEPTH -# define YYMAXDEPTH 10000 -#endif - - - -#if YYERROR_VERBOSE - -# ifndef yystrlen -# if defined __GLIBC__ && defined _STRING_H -# define yystrlen strlen -# else -/* Return the length of YYSTR. */ -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static YYSIZE_T -yystrlen (const char *yystr) -#else -static YYSIZE_T -yystrlen (yystr) - const char *yystr; -#endif -{ - YYSIZE_T yylen; - for (yylen = 0; yystr[yylen]; yylen++) - continue; - return yylen; -} -# endif -# endif - -# ifndef yystpcpy -# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE -# define yystpcpy stpcpy -# else -/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in - YYDEST. */ -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static char * -yystpcpy (char *yydest, const char *yysrc) -#else -static char * -yystpcpy (yydest, yysrc) - char *yydest; - const char *yysrc; -#endif -{ - char *yyd = yydest; - const char *yys = yysrc; - - while ((*yyd++ = *yys++) != '\0') - continue; - - return yyd - 1; -} -# endif -# endif - -# ifndef yytnamerr -/* Copy to YYRES the contents of YYSTR after stripping away unnecessary - quotes and backslashes, so that it's suitable for yyerror. The - heuristic is that double-quoting is unnecessary unless the string - contains an apostrophe, a comma, or backslash (other than - backslash-backslash). YYSTR is taken from yytname. If YYRES is - null, do not copy; instead, return the length of what the result - would have been. */ -static YYSIZE_T -yytnamerr (char *yyres, const char *yystr) -{ - if (*yystr == '"') - { - YYSIZE_T yyn = 0; - char const *yyp = yystr; - - for (;;) - switch (*++yyp) - { - case '\'': - case ',': - goto do_not_strip_quotes; - - case '\\': - if (*++yyp != '\\') - goto do_not_strip_quotes; - /* Fall through. */ - default: - if (yyres) - yyres[yyn] = *yyp; - yyn++; - break; - - case '"': - if (yyres) - yyres[yyn] = '\0'; - return yyn; - } - do_not_strip_quotes: ; - } - - if (! yyres) - return yystrlen (yystr); - - return yystpcpy (yyres, yystr) - yyres; -} -# endif - -/* Copy into YYRESULT an error message about the unexpected token - YYCHAR while in state YYSTATE. Return the number of bytes copied, - including the terminating null byte. If YYRESULT is null, do not - copy anything; just return the number of bytes that would be - copied. As a special case, return 0 if an ordinary "syntax error" - message will do. Return YYSIZE_MAXIMUM if overflow occurs during - size calculation. */ -static YYSIZE_T -yysyntax_error (char *yyresult, int yystate, int yychar) -{ - int yyn = yypact[yystate]; - - if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) - return 0; - else - { - int yytype = YYTRANSLATE (yychar); - YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); - YYSIZE_T yysize = yysize0; - YYSIZE_T yysize1; - int yysize_overflow = 0; - enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; - char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; - int yyx; - -# if 0 - /* This is so xgettext sees the translatable formats that are - constructed on the fly. */ - YY_("syntax error, unexpected %s"); - YY_("syntax error, unexpected %s, expecting %s"); - YY_("syntax error, unexpected %s, expecting %s or %s"); - YY_("syntax error, unexpected %s, expecting %s or %s or %s"); - YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); -# endif - char *yyfmt; - char const *yyf; - static char const yyunexpected[] = "syntax error, unexpected %s"; - static char const yyexpecting[] = ", expecting %s"; - static char const yyor[] = " or %s"; - char yyformat[sizeof yyunexpected - + sizeof yyexpecting - 1 - + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) - * (sizeof yyor - 1))]; - char const *yyprefix = yyexpecting; - - /* Start YYX at -YYN if negative to avoid negative indexes in - YYCHECK. */ - int yyxbegin = yyn < 0 ? -yyn : 0; - - /* Stay within bounds of both yycheck and yytname. */ - int yychecklim = YYLAST - yyn + 1; - int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; - int yycount = 1; - - yyarg[0] = yytname[yytype]; - yyfmt = yystpcpy (yyformat, yyunexpected); - - for (yyx = yyxbegin; yyx < yyxend; ++yyx) - if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) - { - if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) - { - yycount = 1; - yysize = yysize0; - yyformat[sizeof yyunexpected - 1] = '\0'; - break; - } - yyarg[yycount++] = yytname[yyx]; - yysize1 = yysize + yytnamerr (0, yytname[yyx]); - yysize_overflow |= (yysize1 < yysize); - yysize = yysize1; - yyfmt = yystpcpy (yyfmt, yyprefix); - yyprefix = yyor; - } - - yyf = YY_(yyformat); - yysize1 = yysize + yystrlen (yyf); - yysize_overflow |= (yysize1 < yysize); - yysize = yysize1; - - if (yysize_overflow) - return YYSIZE_MAXIMUM; - - if (yyresult) - { - /* Avoid sprintf, as that infringes on the user's name space. - Don't have undefined behavior even if the translation - produced a string with the wrong number of "%s"s. */ - char *yyp = yyresult; - int yyi = 0; - while ((*yyp = *yyf) != '\0') - { - if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) - { - yyp += yytnamerr (yyp, yyarg[yyi++]); - yyf += 2; - } - else - { - yyp++; - yyf++; - } - } - } - return yysize; - } -} -#endif /* YYERROR_VERBOSE */ - - -/*-----------------------------------------------. -| Release the memory associated to this symbol. | -`-----------------------------------------------*/ - -/*ARGSUSED*/ -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -static void -yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) -#else -static void -yydestruct (yymsg, yytype, yyvaluep) - const char *yymsg; - int yytype; - YYSTYPE *yyvaluep; -#endif -{ - YYUSE (yyvaluep); - - if (!yymsg) - yymsg = "Deleting"; - YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); - - switch (yytype) - { - case 3: /* "CHAR_CONST" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1138 "bison-win.cpp" - break; - case 4: /* "RELOP" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1147 "bison-win.cpp" - break; - case 5: /* "LOGICOP" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1156 "bison-win.cpp" - break; - case 10: /* "OBJNAME" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1165 "bison-win.cpp" - break; - case 11: /* "INT_CONST" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1174 "bison-win.cpp" - break; - case 16: /* "AS" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1183 "bison-win.cpp" - break; - case 17: /* "FUNC" */ - -/* Line 1000 of yacc.c */ -#line 49 "qfeparser.ypp" - { delete (yyvaluep->cp); }; - -/* Line 1000 of yacc.c */ -#line 1192 "bison-win.cpp" - break; - case 27: /* "select_column_name" */ - -/* Line 1000 of yacc.c */ -#line 50 "qfeparser.ypp" - { delete (yyvaluep->rcp); }; - -/* Line 1000 of yacc.c */ -#line 1201 "bison-win.cpp" - break; - case 28: /* "func_col" */ - -/* Line 1000 of yacc.c */ -#line 50 "qfeparser.ypp" - { delete (yyvaluep->rcp); }; - -/* Line 1000 of yacc.c */ -#line 1210 "bison-win.cpp" - break; - case 29: /* "aliased_column_name" */ - -/* Line 1000 of yacc.c */ -#line 50 "qfeparser.ypp" - { delete (yyvaluep->rcp); }; - -/* Line 1000 of yacc.c */ -#line 1219 "bison-win.cpp" - break; - case 37: /* "obj_name" */ - -/* Line 1000 of yacc.c */ -#line 50 "qfeparser.ypp" - { delete (yyvaluep->rcp); }; - -/* Line 1000 of yacc.c */ -#line 1228 "bison-win.cpp" - break; - case 39: /* "constant" */ - -/* Line 1000 of yacc.c */ -#line 51 "qfeparser.ypp" - { delete (yyvaluep->cvp); }; - -/* Line 1000 of yacc.c */ -#line 1237 "bison-win.cpp" - break; - case 42: /* "groupby_item" */ - -/* Line 1000 of yacc.c */ -#line 50 "qfeparser.ypp" - { delete (yyvaluep->rcp); }; - -/* Line 1000 of yacc.c */ -#line 1246 "bison-win.cpp" - break; - - default: - break; - } -} - -/* Prevent warnings from -Wmissing-prototypes. */ -#ifdef YYPARSE_PARAM -#if defined __STDC__ || defined __cplusplus -int yyparse (void *YYPARSE_PARAM); -#else -int yyparse (); -#endif -#else /* ! YYPARSE_PARAM */ -#if defined __STDC__ || defined __cplusplus -int yyparse (void); -#else -int yyparse (); -#endif -#endif /* ! YYPARSE_PARAM */ - - -/* The lookahead symbol. */ -int yychar; - -/* The semantic value of the lookahead symbol. */ -YYSTYPE yylval; - -/* Number of syntax errors so far. */ -int yynerrs; - - - -/*-------------------------. -| yyparse or yypush_parse. | -`-------------------------*/ - -#ifdef YYPARSE_PARAM -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -int -yyparse (void *YYPARSE_PARAM) -#else -int -yyparse (YYPARSE_PARAM) - void *YYPARSE_PARAM; -#endif -#else /* ! YYPARSE_PARAM */ -#if (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) -int -yyparse (void) -#else -int -yyparse () - -#endif -#endif -{ - - - int yystate; - /* Number of tokens to shift before error messages enabled. */ - int yyerrstatus; - - /* The stacks and their tools: - `yyss': related to states. - `yyvs': related to semantic values. - - Refer to the stacks thru separate pointers, to allow yyoverflow - to reallocate them elsewhere. */ - - /* The state stack. */ - yytype_int16 yyssa[YYINITDEPTH]; - yytype_int16 *yyss; - yytype_int16 *yyssp; - - /* The semantic value stack. */ - YYSTYPE yyvsa[YYINITDEPTH]; - YYSTYPE *yyvs; - YYSTYPE *yyvsp; - - YYSIZE_T yystacksize; - - int yyn; - int yyresult; - /* Lookahead token as an internal (translated) token number. */ - int yytoken; - /* The variables used to return semantic value and location from the - action routines. */ - YYSTYPE yyval; - -#if YYERROR_VERBOSE - /* Buffer for error messages, and its allocated size. */ - char yymsgbuf[128]; - char *yymsg = yymsgbuf; - YYSIZE_T yymsg_alloc = sizeof yymsgbuf; -#endif - -#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) - - /* The number of symbols on the RHS of the reduced rule. - Keep to zero when no symbol should be popped. */ - int yylen = 0; - - yytoken = 0; - yyss = yyssa; - yyvs = yyvsa; - yystacksize = YYINITDEPTH; - - YYDPRINTF ((stderr, "Starting parse\n")); - - yystate = 0; - yyerrstatus = 0; - yynerrs = 0; - yychar = YYEMPTY; /* Cause a token to be read. */ - - /* Initialize stack pointers. - Waste one element of value and location stack - so that they stay on the same level as the state stack. - The wasted elements are never initialized. */ - yyssp = yyss; - yyvsp = yyvs; - - goto yysetstate; - -/*------------------------------------------------------------. -| yynewstate -- Push a new state, which is found in yystate. | -`------------------------------------------------------------*/ - yynewstate: - /* In all cases, when you get here, the value and location stacks - have just been pushed. So pushing a state here evens the stacks. */ - yyssp++; - - yysetstate: - *yyssp = yystate; - - if (yyss + yystacksize - 1 <= yyssp) - { - /* Get the current used size of the three stacks, in elements. */ - YYSIZE_T yysize = yyssp - yyss + 1; - -#ifdef yyoverflow - { - /* Give user a chance to reallocate the stack. Use copies of - these so that the &'s don't force the real ones into - memory. */ - YYSTYPE *yyvs1 = yyvs; - yytype_int16 *yyss1 = yyss; - - /* Each stack pointer address is followed by the size of the - data in use in that stack, in bytes. This used to be a - conditional around just the two extra args, but that might - be undefined if yyoverflow is a macro. */ - yyoverflow (YY_("memory exhausted"), - &yyss1, yysize * sizeof (*yyssp), - &yyvs1, yysize * sizeof (*yyvsp), - &yystacksize); - - yyss = yyss1; - yyvs = yyvs1; - } -#else /* no yyoverflow */ -# ifndef YYSTACK_RELOCATE - goto yyexhaustedlab; -# else - /* Extend the stack our own way. */ - if (YYMAXDEPTH <= yystacksize) - goto yyexhaustedlab; - yystacksize *= 2; - if (YYMAXDEPTH < yystacksize) - yystacksize = YYMAXDEPTH; - - { - yytype_int16 *yyss1 = yyss; - union yyalloc *yyptr = - (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); - if (! yyptr) - goto yyexhaustedlab; - YYSTACK_RELOCATE (yyss_alloc, yyss); - YYSTACK_RELOCATE (yyvs_alloc, yyvs); -# undef YYSTACK_RELOCATE - if (yyss1 != yyssa) - YYSTACK_FREE (yyss1); - } -# endif -#endif /* no yyoverflow */ - - yyssp = yyss + yysize - 1; - yyvsp = yyvs + yysize - 1; - - YYDPRINTF ((stderr, "Stack size increased to %lu\n", - (unsigned long int) yystacksize)); - - if (yyss + yystacksize - 1 <= yyssp) - YYABORT; - } - - YYDPRINTF ((stderr, "Entering state %d\n", yystate)); - - if (yystate == YYFINAL) - YYACCEPT; - - goto yybackup; - -/*-----------. -| yybackup. | -`-----------*/ -yybackup: - - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - - /* First try to decide what to do without reference to lookahead token. */ - yyn = yypact[yystate]; - if (yyn == YYPACT_NINF) - goto yydefault; - - /* Not known => get a lookahead token if don't already have one. */ - - /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token: ")); - yychar = YYLEX; - } - - if (yychar <= YYEOF) - { - yychar = yytoken = YYEOF; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); - } - - /* If the proper action on seeing token YYTOKEN is to reduce or to - detect an error, take that action. */ - yyn += yytoken; - if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) - goto yydefault; - yyn = yytable[yyn]; - if (yyn <= 0) - { - if (yyn == 0 || yyn == YYTABLE_NINF) - goto yyerrlab; - yyn = -yyn; - goto yyreduce; - } - - /* Count tokens shifted since error; after three, turn off error - status. */ - if (yyerrstatus) - yyerrstatus--; - - /* Shift the lookahead token. */ - YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); - - /* Discard the shifted token. */ - yychar = YYEMPTY; - - yystate = yyn; - *++yyvsp = yylval; - - goto yynewstate; - - -/*-----------------------------------------------------------. -| yydefault -- do the default action for the current state. | -`-----------------------------------------------------------*/ -yydefault: - yyn = yydefact[yystate]; - if (yyn == 0) - goto yyerrlab; - goto yyreduce; - - -/*-----------------------------. -| yyreduce -- Do a reduction. | -`-----------------------------*/ -yyreduce: - /* yyn is the number of a rule to reduce with. */ - yylen = yyr2[yyn]; - - /* If YYLEN is nonzero, implement the default value of the action: - `$$ = $1'. - - Otherwise, the following line sets YYVAL to garbage. - This behavior is undocumented and Bison - users should not rely upon it. Assigning to YYVAL - unconditionally makes the parser a bit smaller, and it avoids a - GCC warning that YYVAL may be used uninitialized. */ - yyval = yyvsp[1-yylen]; - - - YY_REDUCE_PRINT (yyn); - switch (yyn) - { - case 3: - -/* Line 1455 of yacc.c */ -#line 64 "qfeparser.ypp" - { - execplan::SRCP rcp((yyvsp[(1) - (1)].rcp)); - ParserCSEP->returnedCols().push_back(rcp); - (yyval.cp) = 0; - ;} - break; - - case 4: - -/* Line 1455 of yacc.c */ -#line 70 "qfeparser.ypp" - { - execplan::SRCP rcp((yyvsp[(3) - (3)].rcp)); - ParserCSEP->returnedCols().push_back(rcp); - (yyval.cp) = 0; - ;} - break; - - case 5: - -/* Line 1455 of yacc.c */ -#line 78 "qfeparser.ypp" - { - execplan::SimpleColumn* sc = dynamic_cast((yyvsp[(1) - (1)].rcp)); - if (sc->schemaName() == "infinidb_unknown" && !qfe::DefaultSchema.empty()) - sc->schemaName(qfe::DefaultSchema); - sc->setOID(); - sc->tableAlias(sc->tableName()); - sc->alias(execplan::make_tcn(sc->schemaName(), sc->tableName(), sc->columnName()).toString()); - (yyval.rcp) = (yyvsp[(1) - (1)].rcp); - ;} - break; - - case 7: - -/* Line 1455 of yacc.c */ -#line 91 "qfeparser.ypp" - { - execplan::AggregateColumn* ag = new execplan::AggregateColumn(execplan::AggregateColumn::agname2num(*((yyvsp[(1) - (4)].cp))), (yyvsp[(3) - (4)].rcp)); - delete (yyvsp[(1) - (4)].cp); - (yyval.rcp) = ag; - ;} - break; - - case 9: - -/* Line 1455 of yacc.c */ -#line 102 "qfeparser.ypp" - { (yyval.cp) = 0; ;} - break; - - case 10: - -/* Line 1455 of yacc.c */ -#line 104 "qfeparser.ypp" - { - delete (yyvsp[(2) - (2)].cp); - (yyval.cp) = (yyvsp[(1) - (2)].cp); - ;} - break; - - case 11: - -/* Line 1455 of yacc.c */ -#line 109 "qfeparser.ypp" - { - delete (yyvsp[(2) - (2)].cp); - (yyval.cp) = (yyvsp[(1) - (2)].cp); - ;} - break; - - case 12: - -/* Line 1455 of yacc.c */ -#line 116 "qfeparser.ypp" - { (yyval.cp) = 0; ;} - break; - - case 15: - -/* Line 1455 of yacc.c */ -#line 125 "qfeparser.ypp" - { - execplan::SimpleColumn* sc=0; - sc = dynamic_cast((yyvsp[(1) - (1)].rcp)); - execplan::CalpontSystemCatalog::TableAliasName tan; - tan.schema = sc->tableName(); - if (tan.schema == "infinidb_unknown" && !qfe::DefaultSchema.empty()) - tan.schema = qfe::DefaultSchema; - if (qfe::DefaultSchema.empty()) - qfe::DefaultSchema = tan.schema; - tan.table = sc->columnName(); - tan.alias = tan.table; - execplan::CalpontSelectExecutionPlan::TableList tl; - tl.push_back(tan); - ParserCSEP->tableList(tl); - delete sc; - (yyval.cp) = 0; - ;} - break; - - case 19: - -/* Line 1455 of yacc.c */ -#line 152 "qfeparser.ypp" - { - pair cval = *((yyvsp[(3) - (3)].cvp)); - delete (yyvsp[(3) - (3)].cvp); - execplan::SimpleColumn* sc=0; - sc = dynamic_cast((yyvsp[(1) - (3)].rcp)); - qfe::utils::updateParseTree(ParserCSC, ParserCSEP, - sc, *((yyvsp[(2) - (3)].cp)), cval); - delete sc; - delete (yyvsp[(2) - (3)].cp); - (yyval.cp) = 0; - ;} - break; - - case 20: - -/* Line 1455 of yacc.c */ -#line 164 "qfeparser.ypp" - { - //string logicop = *($2); - delete (yyvsp[(2) - (5)].cp); - pair cval = *((yyvsp[(5) - (5)].cvp)); - delete (yyvsp[(5) - (5)].cvp); - execplan::SimpleColumn* sc=0; - sc = dynamic_cast((yyvsp[(3) - (5)].rcp)); - qfe::utils::updateParseTree(ParserCSC, ParserCSEP, - sc, *((yyvsp[(4) - (5)].cp)), cval); - delete sc; - delete (yyvsp[(4) - (5)].cp); - (yyval.cp) = 0; - ;} - break; - - case 21: - -/* Line 1455 of yacc.c */ -#line 180 "qfeparser.ypp" - { - //This is possibly a table name, but we shove it into a SimpleColumn. We'll - // fix this in the table_spec production - execplan::SimpleColumn* sc = new execplan::SimpleColumn("infinidb_unknown", "infinidb_unknown", *((yyvsp[(1) - (1)].cp))); - sc->tableAlias("infinidb_unknown"); - sc->alias(execplan::make_tcn("infinidb_unknown", "infinidb_unknown", *((yyvsp[(1) - (1)].cp))).toString()); - //cerr << "inside parser: " << *sc << endl; - delete (yyvsp[(1) - (1)].cp); - (yyval.rcp) = sc; - ;} - break; - - case 22: - -/* Line 1455 of yacc.c */ -#line 191 "qfeparser.ypp" - { - //This is possibly a table name, but we shove it into a SimpleColumn. We'll - // fix this in the table_spec production - execplan::SimpleColumn* sc = new execplan::SimpleColumn("infinidb_unknown", *((yyvsp[(1) - (3)].cp)), *((yyvsp[(3) - (3)].cp))); - sc->tableAlias(*((yyvsp[(1) - (3)].cp))); - sc->alias(execplan::make_tcn("infinidb_unknown", *((yyvsp[(1) - (3)].cp)), *((yyvsp[(3) - (3)].cp))).toString()); - //cerr << "inside parser: " << *sc << endl; - delete (yyvsp[(1) - (3)].cp); - delete (yyvsp[(3) - (3)].cp); - (yyval.rcp) = sc; - ;} - break; - - case 23: - -/* Line 1455 of yacc.c */ -#line 203 "qfeparser.ypp" - { - if (qfe::DefaultSchema.empty()) - qfe::DefaultSchema = *((yyvsp[(1) - (5)].cp)); - execplan::SimpleColumn* sc = new execplan::SimpleColumn(*((yyvsp[(1) - (5)].cp)), *((yyvsp[(3) - (5)].cp)), *((yyvsp[(5) - (5)].cp))); - sc->tableAlias(*((yyvsp[(3) - (5)].cp))); - sc->alias(execplan::make_tcn(*((yyvsp[(1) - (5)].cp)), *((yyvsp[(3) - (5)].cp)), *((yyvsp[(5) - (5)].cp))).toString()); - //cerr << "inside parser: " << *sc << endl; - delete (yyvsp[(1) - (5)].cp); - delete (yyvsp[(3) - (5)].cp); - delete (yyvsp[(5) - (5)].cp); - (yyval.rcp) = sc; - ;} - break; - - case 25: - -/* Line 1455 of yacc.c */ -#line 219 "qfeparser.ypp" - { - (yyval.cp) = (yyvsp[(2) - (3)].cp); - ;} - break; - - case 26: - -/* Line 1455 of yacc.c */ -#line 225 "qfeparser.ypp" - { - pair* p = new pair(1, *((yyvsp[(1) - (1)].cp))); - delete (yyvsp[(1) - (1)].cp); - (yyval.cvp) = p; - ;} - break; - - case 27: - -/* Line 1455 of yacc.c */ -#line 231 "qfeparser.ypp" - { - pair* p = new pair(0, *((yyvsp[(1) - (1)].cp))); - delete (yyvsp[(1) - (1)].cp); - (yyval.cvp) = p; - ;} - break; - - case 29: - -/* Line 1455 of yacc.c */ -#line 240 "qfeparser.ypp" - { YYERROR; ;} - break; - - case 31: - -/* Line 1455 of yacc.c */ -#line 245 "qfeparser.ypp" - { delete (yyvsp[(3) - (3)].rcp); ;} - break; - - case 33: - -/* Line 1455 of yacc.c */ -#line 250 "qfeparser.ypp" - { - delete (yyvsp[(1) - (1)].cp); - (yyval.rcp) = 0; - ;} - break; - - case 35: - -/* Line 1455 of yacc.c */ -#line 258 "qfeparser.ypp" - { YYERROR; ;} - break; - - case 39: - -/* Line 1455 of yacc.c */ -#line 267 "qfeparser.ypp" - { (yyval.cp) = 0; ;} - break; - - case 40: - -/* Line 1455 of yacc.c */ -#line 269 "qfeparser.ypp" - { - delete (yyvsp[(2) - (2)].cp); - YYERROR; - (yyval.cp) = 0; - ;} - break; - - case 41: - -/* Line 1455 of yacc.c */ -#line 275 "qfeparser.ypp" - { - delete (yyvsp[(2) - (4)].cp); - delete (yyvsp[(4) - (4)].cp); - YYERROR; - (yyval.cp) = 0; - ;} - break; - - - -/* Line 1455 of yacc.c */ -#line 1835 "bison-win.cpp" - default: break; - } - YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); - - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - - *++yyvsp = yyval; - - /* Now `shift' the result of the reduction. Determine what state - that goes to, based on the state we popped back to and the rule - number reduced by. */ - - yyn = yyr1[yyn]; - - yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; - if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) - yystate = yytable[yystate]; - else - yystate = yydefgoto[yyn - YYNTOKENS]; - - goto yynewstate; - - -/*------------------------------------. -| yyerrlab -- here on detecting error | -`------------------------------------*/ -yyerrlab: - /* If not already recovering from an error, report this error. */ - if (!yyerrstatus) - { - ++yynerrs; -#if ! YYERROR_VERBOSE - yyerror (YY_("syntax error")); -#else - { - YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); - if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) - { - YYSIZE_T yyalloc = 2 * yysize; - if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) - yyalloc = YYSTACK_ALLOC_MAXIMUM; - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); - yymsg = (char *) YYSTACK_ALLOC (yyalloc); - if (yymsg) - yymsg_alloc = yyalloc; - else - { - yymsg = yymsgbuf; - yymsg_alloc = sizeof yymsgbuf; - } - } - - if (0 < yysize && yysize <= yymsg_alloc) - { - (void) yysyntax_error (yymsg, yystate, yychar); - yyerror (yymsg); - } - else - { - yyerror (YY_("syntax error")); - if (yysize != 0) - goto yyexhaustedlab; - } - } -#endif - } - - - - if (yyerrstatus == 3) - { - /* If just tried and failed to reuse lookahead token after an - error, discard it. */ - - if (yychar <= YYEOF) - { - /* Return failure if at end of input. */ - if (yychar == YYEOF) - YYABORT; - } - else - { - yydestruct ("Error: discarding", - yytoken, &yylval); - yychar = YYEMPTY; - } - } - - /* Else will try to reuse lookahead token after shifting the error - token. */ - goto yyerrlab1; - - -/*---------------------------------------------------. -| yyerrorlab -- error raised explicitly by YYERROR. | -`---------------------------------------------------*/ -yyerrorlab: - - /* Pacify compilers like GCC when the user code never invokes - YYERROR and the label yyerrorlab therefore never appears in user - code. */ - if (/*CONSTCOND*/ 0) - goto yyerrorlab; - - /* Do not reclaim the symbols of the rule which action triggered - this YYERROR. */ - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - yystate = *yyssp; - goto yyerrlab1; - - -/*-------------------------------------------------------------. -| yyerrlab1 -- common code for both syntax error and YYERROR. | -`-------------------------------------------------------------*/ -yyerrlab1: - yyerrstatus = 3; /* Each real token shifted decrements this. */ - - for (;;) - { - yyn = yypact[yystate]; - if (yyn != YYPACT_NINF) - { - yyn += YYTERROR; - if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) - { - yyn = yytable[yyn]; - if (0 < yyn) - break; - } - } - - /* Pop the current state because it cannot handle the error token. */ - if (yyssp == yyss) - YYABORT; - - - yydestruct ("Error: popping", - yystos[yystate], yyvsp); - YYPOPSTACK (1); - yystate = *yyssp; - YY_STACK_PRINT (yyss, yyssp); - } - - *++yyvsp = yylval; - - - /* Shift the error token. */ - YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); - - yystate = yyn; - goto yynewstate; - - -/*-------------------------------------. -| yyacceptlab -- YYACCEPT comes here. | -`-------------------------------------*/ -yyacceptlab: - yyresult = 0; - goto yyreturn; - -/*-----------------------------------. -| yyabortlab -- YYABORT comes here. | -`-----------------------------------*/ -yyabortlab: - yyresult = 1; - goto yyreturn; - -#if !defined(yyoverflow) || YYERROR_VERBOSE -/*-------------------------------------------------. -| yyexhaustedlab -- memory exhaustion comes here. | -`-------------------------------------------------*/ -yyexhaustedlab: - yyerror (YY_("memory exhausted")); - yyresult = 2; - /* Fall through. */ -#endif - -yyreturn: - if (yychar != YYEMPTY) - yydestruct ("Cleanup: discarding lookahead", - yytoken, &yylval); - /* Do not reclaim the symbols of the rule which action triggered - this YYABORT or YYACCEPT. */ - YYPOPSTACK (yylen); - YY_STACK_PRINT (yyss, yyssp); - while (yyssp != yyss) - { - yydestruct ("Cleanup: popping", - yystos[*yyssp], yyvsp); - YYPOPSTACK (1); - } -#ifndef yyoverflow - if (yyss != yyssa) - YYSTACK_FREE (yyss); -#endif -#if YYERROR_VERBOSE - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); -#endif - /* Make sure YYID is used. */ - return YYID (yyresult); -} - - - -/* Line 1675 of yacc.c */ -#line 283 "qfeparser.ypp" - - -int qfeerror(const string& s) -{ - extern int qfelineno; // defined and maintained in lex.c - extern char *qfetext; // defined and maintained in lex.c - - cerr << "ERROR: " << s << " at symbol \"" << qfetext; - cerr << "\" on line " << qfelineno << endl; - return -1; -} - -int qfeerror(const char *s) -{ - return qfeerror(string(s)); -} - -string* newstr(const char* cp) -{ - string* strp; - strp = new string(cp); - return strp; -} - - diff --git a/tools/qfe/bison-win.h b/tools/qfe/bison-win.h deleted file mode 100644 index 25565946..00000000 --- a/tools/qfe/bison-win.h +++ /dev/null @@ -1,85 +0,0 @@ - -/* A Bison parser, made by GNU Bison 2.4.1. */ - -/* Skeleton interface for Bison's Yacc-like parsers in C - - Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 - Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - - -/* Tokens. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - /* Put the tokens into the symbol table, so that GDB and other debuggers - know about them. */ - enum yytokentype { - CHAR_CONST = 258, - RELOP = 259, - LOGICOP = 260, - QFEP_SELECT = 261, - QFEP_FROM = 262, - QFEP_WHERE = 263, - GROUPBY = 264, - OBJNAME = 265, - INT_CONST = 266, - LIMIT = 267, - ORDERBY = 268, - ASC = 269, - DESC = 270, - AS = 271, - FUNC = 272 - }; -#endif - - - -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE -{ - -/* Line 1676 of yacc.c */ -#line 31 "qfeparser.ypp" - - execplan::ReturnedColumn* rcp; - std::string* cp; - std::pair* cvp; - - - -/* Line 1676 of yacc.c */ -#line 77 "bison-win.hpp" -} YYSTYPE; -# define YYSTYPE_IS_TRIVIAL 1 -# define yystype YYSTYPE /* obsolescent; will be withdrawn */ -# define YYSTYPE_IS_DECLARED 1 -#endif - -extern YYSTYPE qfelval; - - diff --git a/tools/qfe/cli.cpp b/tools/qfe/cli.cpp deleted file mode 100644 index 76944978..00000000 --- a/tools/qfe/cli.cpp +++ /dev/null @@ -1,172 +0,0 @@ -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#include -#include -#include -#include -#include -#else -#include -#include -#include -#include -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -using namespace std; - -#include "socktype.h" -#include "socketio.h" -using namespace qfe; - -namespace -{ -void usage() -{ - cout << "usage: cli [-h] [-s serverip] [-p port] [-c schema] " << endl; - cout << '\t' << "-s serverip connect to serverip instead of 127.0.0.1" << endl; - cout << '\t' << "-p port connect on port instead of 9198" << endl; - cout << '\t' << "-c schema use schema as default instead of tpch1" << endl; - cout << '\t' << "-h display this help" << endl; -} -} - -int main(int argc, char** argv) -{ - opterr = 0; - int c; - string serverip("127.0.0.1"); - string schema("tpch1"); - short PortNo = 9198; - while ((c = getopt(argc, argv, "s:c:p:h")) != -1) - switch (c) - { - case 's': - serverip = optarg; - break; - case 'c': - schema = optarg; - break; - case 'p': - PortNo = atoi(optarg); - if (PortNo == 0) - { - usage(); - return 1; - } - break; - case 'h': - case '?': - default: - usage(); - return 0; - break; - } - - if (argc - optind < 1) - { - usage(); - return 1; - } - - string query(argv[optind+0]); - - SockType fd = -1; - -#ifdef _MSC_VER - WSAData wsadata; - const WORD minVersion = MAKEWORD(2, 2); - if (WSAStartup(minVersion, &wsadata) != 0) - cerr << "networking startup error: " << IDBSysErrorStr(WSAGetLastError()) << endl; -#endif - fd = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); - if (fd < 0) - { -#ifdef _MSC_VER - cerr << "socket create error: " << IDBSysErrorStr(WSAGetLastError()) << endl; -#else - cerr << "socket create error: " << strerror(errno) << endl; -#endif - return 1; - } - - int rc = 0; - struct sockaddr_in serv_addr; - struct addrinfo hints; - struct addrinfo* res=0; - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = PF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - rc = getaddrinfo(serverip.c_str(), 0, &hints, &res); - if (rc != 0) - { - cerr << "Error resolving '" << serverip << "': " << gai_strerror(rc) << endl; - return 1; - } - sockaddr_in* sain=0; - sain = reinterpret_cast(res->ai_addr); - memset(&serv_addr, 0, sizeof(serv_addr)); - serv_addr.sin_family = PF_INET; - serv_addr.sin_addr = sain->sin_addr; - serv_addr.sin_port = htons(PortNo); - freeaddrinfo(res); - - rc = ::connect(fd, (sockaddr*)&serv_addr, sizeof(serv_addr)); - if (rc < 0) - { -#ifdef _MSC_VER - cerr << "socket connect error: " << IDBSysErrorStr(WSAGetLastError()) << endl; - WSACleanup(); -#else - cerr << "socket connect error: " << strerror(errno) << endl; -#endif - return 1; - } - - socketio::writeString(fd, schema); - socketio::writeString(fd, query); - - uint32_t flag=0; - string row; - row = socketio::readString(fd); - if (row != "OK") - { - cerr << "query failed: " << row << endl; - goto bailout; - } - - row = socketio::readString(fd); - while (!row.empty()) - { - cout << row << endl; - row = socketio::readString(fd); - } - - flag=0; - SockWriteFcn(fd, &flag, 4); -bailout: - ::shutdown(fd, SHUT_RDWR); -#ifdef _MSC_VER - ::closesocket(fd); - WSACleanup(); -#else - ::close(fd); -#endif - fd = -1; - - return 0; -} - diff --git a/tools/qfe/cseputils.cpp b/tools/qfe/cseputils.cpp deleted file mode 100644 index 67e22f42..00000000 --- a/tools/qfe/cseputils.cpp +++ /dev/null @@ -1,149 +0,0 @@ -#include -#include -using namespace std; - -#include "constantcolumn.h" -#include "simplefilter.h" -#include "calpontsystemcatalog.h" -#include "parsetree.h" -#include "simplecolumn.h" -#include "calpontselectexecutionplan.h" -using namespace execplan; - -#include "cseputils.h" - - -namespace qfe -{ -extern string DefaultSchema; - -namespace utils -{ - -ConstantColumn* createConstCol(const string& valstr) -{ - ConstantColumn* cc= new ConstantColumn(valstr); - cc->alias(valstr); - return cc; -} - -template -ConstantColumn* createConstCol(const string& valstr, T val) -{ - ConstantColumn* cc= new ConstantColumn(valstr, val); - cc->alias(valstr); - return cc; -} - -SimpleFilter* createSimpleFilter - ( - boost::shared_ptr& csc, - const CalpontSystemCatalog::TableColName& tcn, - const string& opstr, - ConstantColumn* cc - ) -{ - SimpleFilter* lsf = new SimpleFilter(); - - Operator* op = new Operator(); - op->data(opstr); - CalpontSystemCatalog::ColType ccct; - ccct = op->resultType(); - ccct.colDataType = cc->resultType().colDataType; - op->operationType(ccct); - - SOP sop(op); - lsf->op(sop); - - CalpontSystemCatalog::OID oid = csc->lookupOID(tcn); - CalpontSystemCatalog::ColType ct = csc->colType(oid); - - SimpleColumn* sc = new SimpleColumn(); - sc->schemaName(tcn.schema); - sc->tableName(tcn.table); - sc->tableAlias(tcn.table); - sc->columnName(tcn.column); - sc->oid(oid); - sc->resultType(ct); - sc->alias(tcn.toString()); - - lsf->lhs(sc); - lsf->rhs(cc); - - return lsf; -} - -void appendSimpleFilter - ( - ParseTree*& ptree, - SimpleFilter* filter - ) -{ - if( ptree->data() == 0 ) - { - // degenerate case, this filter goes at this node - ptree->data( filter ); - } - else if( ptree->right() == 0 && ptree->left() == 0 ) - { - // this will be the case when there is a single node in the tree - // that contains a filter. Here we want to make the root node an - // 'and' operator, push the existing down to the lhs and make a - // new node for the new filter - ParseTree* newLhs = new ParseTree( ptree->data() ); - ParseTree* newRhs = new ParseTree( filter ); - - Operator* op = new Operator(); - op->data("and"); - - ptree->data( op ); - ptree->left( newLhs ); - ptree->right( newRhs ); - } - else - { - // this will be the case once we have a tree with an 'and' at the - // root node, a filter in the lhs, and an arbitrary height tree - // with the same properties on the rhs. Because all operators - // are guaranteed to be and for now we simply insert a new rhs - // node and "push down" the existing tree - Operator* op = new Operator(); - op->data("and"); - - ParseTree* newRhs = new ParseTree( op ); - newRhs->left( new ParseTree( filter ) ); - newRhs->right( ptree->right() ); - ptree->right( newRhs ); - } -} - -void updateParseTree(boost::shared_ptr& csc, - execplan::CalpontSelectExecutionPlan*& csep, - execplan::SimpleColumn* sc, - const std::string& relop, pair cval) -{ - execplan::ConstantColumn* cc=0; - if (cval.first == 0) - cc = createConstCol(cval.second, static_cast(atoll(cval.second.c_str()))); - else - cc = createConstCol(cval.second); - if (sc->schemaName() == "infinidb_unknown" && !DefaultSchema.empty()) - sc->schemaName(DefaultSchema); - execplan::SimpleFilter* sf=0; - sf = createSimpleFilter(csc, - execplan::make_tcn(sc->schemaName(), sc->tableName(), sc->columnName()), - relop, cc); - execplan::ParseTree* ptp=0; - ptp = csep->filters(); - if (ptp == 0) - ptp = new execplan::ParseTree(); - appendSimpleFilter(ptp, sf); - csep->filters(ptp); -} - -//template instantiations -template ConstantColumn* createConstCol(const string& valstr, int64_t val); - -} //namespace qfe::utils -} //namespace qfe - diff --git a/tools/qfe/cseputils.h b/tools/qfe/cseputils.h deleted file mode 100644 index fa80ba0b..00000000 --- a/tools/qfe/cseputils.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef QFE_CSEPUTILS_H__ -#define QFE_CSEPUTILS_H__ - -#include - -namespace execplan -{ -class ConstantColumn; -class SimpleFilter; -class ParseTree; -class SimpleColumn; -} -#include "calpontsystemcatalog.h" - -namespace qfe -{ -namespace utils -{ -execplan::ConstantColumn* createConstCol(const std::string& valstr); - -template -execplan::ConstantColumn* createConstCol(const std::string& valstr, T val); - -execplan::SimpleFilter* createSimpleFilter - ( - boost::shared_ptr& csc, - const execplan::CalpontSystemCatalog::TableColName& tcn, - const std::string& opstr, - execplan::ConstantColumn* cc - ); - -void appendSimpleFilter - ( - execplan::ParseTree*& ptree, - execplan::SimpleFilter* filter - ); - -void updateParseTree(boost::shared_ptr&, - execplan::CalpontSelectExecutionPlan*&, - execplan::SimpleColumn*, - const std::string&, pair); - -} //namespace qfe::utils -} //namespace qfe -#endif - diff --git a/tools/qfe/ddlstmts.cpp b/tools/qfe/ddlstmts.cpp deleted file mode 100644 index b9b2b793..00000000 --- a/tools/qfe/ddlstmts.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -#include -#include -using namespace std; - -#include -using namespace boost; - -#include "ddlpkg.h" -#include "sqlparser.h" -using namespace ddlpackage; - -#include "bytestream.h" -#include "messagequeue.h" -using namespace messageqcpp; - -#include "ddlstmts.h" - -namespace qfe -{ -extern string DefaultSchema; -} - -namespace -{ -using namespace qfe; - -int processDDLStmt(const string& stmt, uint32_t sid) -{ - MessageQueueClient* mq=0; - SqlParser parser; - - parser.setDefaultSchema(DefaultSchema); - parser.Parse(stmt.c_str()); - if (parser.Good()) - { - const ddlpackage::ParseTree& ptree = parser.GetParseTree(); - SqlStatement &ddlstmt = *ptree.fList[0]; - ddlstmt.fSessionID = sid; - ddlstmt.fSql = stmt; - ddlstmt.fOwner = DefaultSchema; - ByteStream bytestream; - bytestream << ddlstmt.fSessionID; - ddlstmt.serialize(bytestream); - mq = new MessageQueueClient("DDLProc"); - scoped_ptr smq(mq); - ByteStream::byte b=0; - mq->write(bytestream); - bytestream = mq->read(); - bytestream >> b; - string emsg; - bytestream >> emsg; - if (b != 0) - throw runtime_error(emsg); - } - else - { - throw runtime_error("syntax error"); - } - - return 0; -} - -} - -namespace qfe -{ - -void processCreateStmt(const string& stmt, uint32_t sid) -{ - processDDLStmt(stmt, sid); -} - -void processDropStmt(const string& stmt, uint32_t sid) -{ - processDDLStmt(stmt, sid); -} - -} //namespace qfe - diff --git a/tools/qfe/ddlstmts.h b/tools/qfe/ddlstmts.h deleted file mode 100644 index c3f02a3e..00000000 --- a/tools/qfe/ddlstmts.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef QFE_DDLSTMTS_H__ -#define QFE_DDLSTMTS_H__ - -#include -#include - -namespace qfe -{ -void processCreateStmt(const std::string&, uint32_t); -void processDropStmt(const std::string&, uint32_t); -} - -#endif - diff --git a/tools/qfe/lex-win.cpp b/tools/qfe/lex-win.cpp deleted file mode 100644 index 4a2f9a23..00000000 --- a/tools/qfe/lex-win.cpp +++ /dev/null @@ -1,1760 +0,0 @@ -#define yy_create_buffer qfe_create_buffer -#define yy_delete_buffer qfe_delete_buffer -#define yy_scan_buffer qfe_scan_buffer -#define yy_scan_string qfe_scan_string -#define yy_scan_bytes qfe_scan_bytes -#define yy_flex_debug qfe_flex_debug -#define yy_init_buffer qfe_init_buffer -#define yy_flush_buffer qfe_flush_buffer -#define yy_load_buffer_state qfe_load_buffer_state -#define yy_switch_to_buffer qfe_switch_to_buffer -#define yyin qfein -#define yyleng qfeleng -#define yylex qfelex -#define yyout qfeout -#define yyrestart qferestart -#define yytext qfetext -#define yylineno qfelineno - -#line 20 "lex-win.cpp" -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include - - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ -#ifdef c_plusplus -#ifndef __cplusplus -#define __cplusplus -#endif -#endif - - -#ifdef __cplusplus - -#include -#include - -/* Use prototypes in function declarations. */ -#define YY_USE_PROTOS - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -#if __STDC__ - -#define YY_USE_PROTOS -#define YY_USE_CONST - -#endif /* __STDC__ */ -#endif /* ! __cplusplus */ - -#ifdef __TURBOC__ - #pragma warn -rch - #pragma warn -use -#include -#include -#define YY_USE_CONST -#define YY_USE_PROTOS -#endif - -#ifdef YY_USE_CONST -#define yyconst const -#else -#define yyconst -#endif - - -#ifdef YY_USE_PROTOS -#define YY_PROTO(proto) proto -#else -#define YY_PROTO(proto) () -#endif - -/* Returned upon end-of-file. */ -#define YY_NULL 0 - -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. - */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) - -/* Enter a start condition. This macro really ought to take a parameter, - * but we do it the disgusting crufty way forced on us by the ()-less - * definition of BEGIN. - */ -#define BEGIN yy_start = 1 + 2 * - -/* Translate the current start state into a value that can be later handed - * to BEGIN to return to the state. The YYSTATE alias is for lex - * compatibility. - */ -#define YY_START ((yy_start - 1) / 2) -#define YYSTATE YY_START - -/* Action number for EOF rule of a given start state. */ -#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - -/* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart( yyin ) - -#define YY_END_OF_BUFFER_CHAR 0 - -/* Size of default input buffer. */ -#define YY_BUF_SIZE 16384 - -typedef struct yy_buffer_state *YY_BUFFER_STATE; - -extern int yyleng; -extern FILE *yyin, *yyout; - -#define EOB_ACT_CONTINUE_SCAN 0 -#define EOB_ACT_END_OF_FILE 1 -#define EOB_ACT_LAST_MATCH 2 - -/* The funky do-while in the following #define is used to turn the definition - * int a single C statement (which needs a semi-colon terminator). This - * avoids problems with code like: - * - * if ( condition_holds ) - * yyless( 5 ); - * else - * do_something_else(); - * - * Prior to using the do-while the compiler would get upset at the - * "else" because it interpreted the "if" statement as being all - * done when it reached the ';' after the yyless() call. - */ - -/* Return all but the first 'n' matched characters back to the input stream. */ - -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - *yy_cp = yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } \ - while ( 0 ) - -#define unput(c) yyunput( c, yytext_ptr ) - -/* The following is because we cannot portably get our hands on size_t - * (without autoconf's help, which isn't available because we want - * flex-generated scanners to compile on their own). - */ -typedef unsigned int yy_size_t; - - -struct yy_buffer_state - { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - int yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; -#define YY_BUFFER_NEW 0 -#define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yyrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ -#define YY_BUFFER_EOF_PENDING 2 - }; - -static YY_BUFFER_STATE yy_current_buffer = 0; - -/* We provide macros for accessing buffer states in case in the - * future we want to put the buffer states in a more general - * "scanner state". - */ -#define YY_CURRENT_BUFFER yy_current_buffer - - -/* yy_hold_char holds the character lost when yytext is formed. */ -static char yy_hold_char; - -static int yy_n_chars; /* number of characters read into yy_ch_buf */ - - -int yyleng; - -/* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; -static int yy_init = 1; /* whether we need to initialize */ -static int yy_start = 0; /* start state number */ - -/* Flag which is used to allow yywrap()'s to do buffer switches - * instead of setting up a fresh yyin. A bit of a hack ... - */ -static int yy_did_buffer_switch_on_eof; - -void yyrestart YY_PROTO(( FILE *input_file )); - -void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); -void yy_load_buffer_state YY_PROTO(( void )); -YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); -void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); -void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); -void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); -#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) - -YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); -YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); -YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); - -static void *yy_flex_alloc YY_PROTO(( yy_size_t )); -static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); -static void yy_flex_free YY_PROTO(( void * )); - -#define yy_new_buffer yy_create_buffer - -#define yy_set_interactive(is_interactive) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_is_interactive = is_interactive; \ - } - -#define yy_set_bol(at_bol) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_at_bol = at_bol; \ - } - -#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) - - -#define YY_USES_REJECT - -#define yywrap() 1 -#define YY_SKIP_YYWRAP -typedef unsigned char YY_CHAR; -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; -typedef int yy_state_type; -extern int yylineno; -int yylineno = 1; -extern char *yytext; -#define yytext_ptr yytext - -static yy_state_type yy_get_previous_state YY_PROTO(( void )); -static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); -static int yy_get_next_buffer YY_PROTO(( void )); -static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); - -/* Done after the current pattern has been matched and before the - * corresponding action - sets up yytext. - */ -#define YY_DO_BEFORE_ACTION \ - yytext_ptr = yy_bp; \ - yyleng = (int) (yy_cp - yy_bp); \ - yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yy_c_buf_p = yy_cp; - -#define YY_NUM_RULES 30 -#define YY_END_OF_BUFFER 31 -static yyconst short int yy_acclist[125] = - { 0, - 27, 27, 18, 18, 31, 29, 30, 27, 29, 30, - 28, 30, 17, 29, 30, 29, 30, 20, 29, 30, - 23, 29, 30, 26, 29, 30, 21, 29, 30, 16, - 29, 30, 16, 29, 30, 16, 29, 30, 16, 29, - 30, 16, 29, 30, 16, 29, 30, 16, 29, 30, - 16, 29, 30, 16, 29, 30, 16, 29, 30, 18, - 30, 19, 30, 27, 20, 24, 25, 22, 16, 16, - 11, 16, 16, 16, 16, 16, 16, 16, 16, 6, - 16, 16, 16, 16, 18, 5, 16, 9, 16, 15, - 16, 16, 16, 16, 16, 14, 16, 13, 16, 16, - - 16, 12, 16, 16, 10, 16, 2, 16, 16, 16, - 16, 16, 16, 16, 7, 16, 16, 16, 3, 16, - 1, 16, 4, 8 - } ; - -static yyconst short int yy_accept[81] = - { 0, - 1, 2, 3, 4, 5, 6, 8, 11, 13, 16, - 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, - 48, 51, 54, 57, 60, 62, 64, 65, 66, 67, - 68, 69, 70, 71, 73, 74, 75, 76, 77, 78, - 79, 80, 82, 83, 84, 85, 86, 88, 90, 92, - 93, 94, 95, 96, 98, 100, 101, 102, 104, 105, - 107, 109, 110, 111, 112, 113, 114, 115, 117, 118, - 119, 121, 121, 121, 123, 123, 123, 124, 125, 125 - } ; - -static yyconst int yy_ec[256] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 4, 1, 1, 1, 1, 1, 1, 5, 1, - 1, 1, 6, 1, 6, 1, 1, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 1, 1, 8, - 9, 10, 1, 1, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 11, 11, 21, 22, 23, 24, 25, - 11, 26, 27, 28, 29, 30, 31, 32, 33, 11, - 1, 1, 1, 1, 11, 1, 12, 13, 14, 15, - - 16, 17, 18, 19, 20, 11, 11, 21, 22, 23, - 24, 25, 11, 26, 27, 28, 29, 30, 31, 32, - 33, 11, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1 - } ; - -static yyconst int yy_meta[34] = - { 0, - 1, 1, 1, 1, 2, 1, 3, 1, 1, 1, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3 - } ; - -static yyconst short int yy_base[83] = - { 0, - 0, 0, 92, 91, 95, 98, 32, 98, 98, 87, - 86, 28, 98, 83, 0, 12, 75, 64, 63, 68, - 28, 61, 25, 67, 0, 98, 41, 78, 98, 98, - 98, 0, 69, 69, 64, 54, 56, 55, 56, 45, - 53, 60, 53, 51, 56, 0, 0, 0, 0, 57, - 48, 40, 48, 0, 0, 51, 50, 0, 39, 0, - 0, 39, 35, 36, 47, 43, 49, 0, 48, 23, - 0, 37, 36, 0, 14, 13, 98, 98, 98, 54, - 41, 57 - } ; - -static yyconst short int yy_def[83] = - { 0, - 79, 1, 80, 80, 79, 79, 79, 79, 79, 79, - 79, 79, 79, 79, 81, 81, 81, 81, 81, 81, - 81, 81, 81, 81, 82, 79, 79, 79, 79, 79, - 79, 81, 81, 81, 81, 81, 81, 81, 81, 81, - 81, 81, 81, 81, 81, 82, 81, 81, 81, 81, - 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, - 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, - 81, 79, 79, 81, 79, 79, 79, 79, 0, 79, - 79, 79 - } ; - -static yyconst short int yy_nxt[132] = - { 0, - 6, 7, 8, 7, 9, 10, 11, 12, 13, 14, - 15, 16, 15, 15, 17, 15, 18, 19, 15, 15, - 20, 21, 15, 22, 15, 15, 23, 15, 15, 15, - 24, 15, 15, 27, 33, 27, 29, 30, 34, 40, - 43, 35, 27, 32, 27, 78, 77, 41, 76, 75, - 74, 73, 72, 44, 25, 25, 25, 46, 71, 46, - 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, - 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, - 50, 49, 48, 47, 28, 45, 42, 39, 38, 37, - 36, 31, 28, 28, 79, 26, 26, 5, 79, 79, - - 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, - 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, - 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, - 79 - } ; - -static yyconst short int yy_chk[132] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 7, 16, 7, 12, 12, 16, 21, - 23, 16, 27, 81, 27, 76, 75, 21, 73, 72, - 70, 69, 67, 23, 80, 80, 80, 82, 66, 82, - 65, 64, 63, 62, 59, 57, 56, 53, 52, 51, - 50, 45, 44, 43, 42, 41, 40, 39, 38, 37, - 36, 35, 34, 33, 28, 24, 22, 20, 19, 18, - 17, 14, 11, 10, 5, 4, 3, 79, 79, 79, - - 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, - 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, - 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, - 79 - } ; - -static yy_state_type yy_state_buf[YY_BUF_SIZE + 2], *yy_state_ptr; -static char *yy_full_match; -static int yy_lp; -#define REJECT \ -{ \ -*yy_cp = yy_hold_char; /* undo effects of setting up yytext */ \ -yy_cp = yy_full_match; /* restore poss. backed-over text */ \ -++yy_lp; \ -goto find_rule; \ -} -#define yymore() yymore_used_but_not_detected -#define YY_MORE_ADJ 0 -#define YY_RESTORE_YY_MORE_OFFSET -char *yytext; -#line 1 "qfelexer.lpp" -#define INITIAL 0 -#line 2 "qfelexer.lpp" -#include -#include -#include "returnedcolumn.h" -#ifndef _MSC_VER -#include "qfeparser.h" -#else -#include "bison-win.h" -#endif - -extern int qfeerror(const char *s); - -extern std::string* newstr(const char* cp); - -#define YY_NO_UNPUT 1 -#define CCONST 1 - -#line 481 "lex-win.cpp" - -/* Macros after this point can all be overridden by user definitions in - * section 1. - */ - -#ifndef YY_SKIP_YYWRAP -#ifdef __cplusplus -extern "C" int yywrap YY_PROTO(( void )); -#else -extern int yywrap YY_PROTO(( void )); -#endif -#endif - -#ifndef YY_NO_UNPUT -static void yyunput YY_PROTO(( int c, char *buf_ptr )); -#endif - -#ifndef yytext_ptr -static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen YY_PROTO(( yyconst char * )); -#endif - -#ifndef YY_NO_INPUT -#ifdef __cplusplus -static int yyinput YY_PROTO(( void )); -#else -static int input YY_PROTO(( void )); -#endif -#endif - -#if YY_STACK_USED -static int yy_start_stack_ptr = 0; -static int yy_start_stack_depth = 0; -static int *yy_start_stack = 0; -#ifndef YY_NO_PUSH_STATE -static void yy_push_state YY_PROTO(( int new_state )); -#endif -#ifndef YY_NO_POP_STATE -static void yy_pop_state YY_PROTO(( void )); -#endif -#ifndef YY_NO_TOP_STATE -static int yy_top_state YY_PROTO(( void )); -#endif - -#else -#define YY_NO_PUSH_STATE 1 -#define YY_NO_POP_STATE 1 -#define YY_NO_TOP_STATE 1 -#endif - -#ifdef YY_MALLOC_DECL -YY_MALLOC_DECL -#else -#if __STDC__ -#ifndef __cplusplus -#include -#endif -#else -/* Just try to get by without declaring the routines. This will fail - * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) - * or sizeof(void*) != sizeof(int). - */ -#endif -#endif - -/* Amount of stuff to slurp up with each read. */ -#ifndef YY_READ_BUF_SIZE -#define YY_READ_BUF_SIZE 8192 -#endif - -/* Copy whatever the last rule matched to the standard output. */ - -#ifndef ECHO -/* This used to be an fputs(), but since the string might contain NUL's, - * we now use fwrite(). - */ -#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) -#endif - -/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, - * is returned in "result". - */ -#ifndef YY_INPUT -#define YY_INPUT(buf,result,max_size) \ - if ( yy_current_buffer->yy_is_interactive ) \ - { \ - int c = '*', n; \ - for ( n = 0; n < max_size && \ - (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ - buf[n] = (char) c; \ - if ( c == '\n' ) \ - buf[n++] = (char) c; \ - if ( c == EOF && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - result = n; \ - } \ - else if ( ((result = fread( buf, 1, max_size, yyin )) == 0) \ - && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); -#endif - -/* No semi-colon after return; correct usage is to write "yyterminate();" - - * we don't want an extra ';' after the "return" because that will cause - * some compilers to complain about unreachable statements. - */ -#ifndef yyterminate -#define yyterminate() return YY_NULL -#endif - -/* Number of entries by which start-condition stack grows. */ -#ifndef YY_START_STACK_INCR -#define YY_START_STACK_INCR 25 -#endif - -/* Report a fatal error. */ -#ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) -#endif - -/* Default declaration of generated scanner - a define so the user can - * easily add parameters. - */ -#ifndef YY_DECL -#define YY_DECL int yylex YY_PROTO(( void )) -#endif - -/* Code executed at the beginning of each rule, after yytext and yyleng - * have been set up. - */ -#ifndef YY_USER_ACTION -#define YY_USER_ACTION -#endif - -/* Code executed at the end of each rule. */ -#ifndef YY_BREAK -#define YY_BREAK break; -#endif - -#define YY_RULE_SETUP \ - YY_USER_ACTION - -YY_DECL - { - register yy_state_type yy_current_state; - register char *yy_cp, *yy_bp; - register int yy_act; - -#line 28 "qfelexer.lpp" - - -#line 635 "lex-win.cpp" - - if ( yy_init ) - { - yy_init = 0; - -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if ( ! yy_start ) - yy_start = 1; /* first start state */ - - if ( ! yyin ) - yyin = stdin; - - if ( ! yyout ) - yyout = stdout; - - if ( ! yy_current_buffer ) - yy_current_buffer = - yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_load_buffer_state(); - } - - while ( 1 ) /* loops until end-of-file is reached */ - { - yy_cp = yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yy_start; - yy_state_ptr = yy_state_buf; - *yy_state_ptr++ = yy_current_state; -yy_match: - do - { - register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 80 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - *yy_state_ptr++ = yy_current_state; - ++yy_cp; - } - while ( yy_base[yy_current_state] != 98 ); - -yy_find_action: - yy_current_state = *--yy_state_ptr; - yy_lp = yy_accept[yy_current_state]; -find_rule: /* we branch to this label when backing up */ - for ( ; ; ) /* until we find what rule we matched */ - { - if ( yy_lp && yy_lp < yy_accept[yy_current_state + 1] ) - { - yy_act = yy_acclist[yy_lp]; - { - yy_full_match = yy_cp; - break; - } - } - --yy_cp; - yy_current_state = *--yy_state_ptr; - yy_lp = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - if ( yy_act != YY_END_OF_BUFFER ) - { - int yyl; - for ( yyl = 0; yyl < yyleng; ++yyl ) - if ( yytext[yyl] == '\n' ) - ++yylineno; - } - -do_action: /* This label is used only to access EOF actions. */ - - - switch ( yy_act ) - { /* beginning of action switch */ -case 1: -YY_RULE_SETUP -#line 30 "qfelexer.lpp" -{ return QFEP_SELECT; } - YY_BREAK -case 2: -YY_RULE_SETUP -#line 31 "qfelexer.lpp" -{ return QFEP_FROM; } - YY_BREAK -case 3: -YY_RULE_SETUP -#line 32 "qfelexer.lpp" -{ return QFEP_WHERE; } - YY_BREAK -case 4: -YY_RULE_SETUP -#line 33 "qfelexer.lpp" -{ return GROUPBY; } - YY_BREAK -case 5: -YY_RULE_SETUP -#line 34 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return LOGICOP; } - YY_BREAK -case 6: -YY_RULE_SETUP -#line 35 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return LOGICOP; } - YY_BREAK -case 7: -YY_RULE_SETUP -#line 36 "qfelexer.lpp" -{ return LIMIT; } - YY_BREAK -case 8: -YY_RULE_SETUP -#line 37 "qfelexer.lpp" -{ return ORDERBY; } - YY_BREAK -case 9: -YY_RULE_SETUP -#line 38 "qfelexer.lpp" -{ return ASC; } - YY_BREAK -case 10: -YY_RULE_SETUP -#line 39 "qfelexer.lpp" -{ return DESC; } - YY_BREAK -case 11: -YY_RULE_SETUP -#line 40 "qfelexer.lpp" -{ return AS; } - YY_BREAK -case 12: -YY_RULE_SETUP -#line 41 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return FUNC; } - YY_BREAK -case 13: -YY_RULE_SETUP -#line 42 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return FUNC; } - YY_BREAK -case 14: -YY_RULE_SETUP -#line 43 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return FUNC; } - YY_BREAK -case 15: -YY_RULE_SETUP -#line 44 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return FUNC; } - YY_BREAK -case 16: -YY_RULE_SETUP -#line 46 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return OBJNAME; } - YY_BREAK -case 17: -YY_RULE_SETUP -#line 48 "qfelexer.lpp" -{ BEGIN(CCONST); } - YY_BREAK -case 18: -YY_RULE_SETUP -#line 49 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return CHAR_CONST; } - YY_BREAK -case 19: -YY_RULE_SETUP -#line 50 "qfelexer.lpp" -{ BEGIN(INITIAL); } - YY_BREAK -case 20: -YY_RULE_SETUP -#line 52 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return INT_CONST; } - YY_BREAK -case 21: -YY_RULE_SETUP -#line 54 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return RELOP; } - YY_BREAK -case 22: -YY_RULE_SETUP -#line 55 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return RELOP; } - YY_BREAK -case 23: -YY_RULE_SETUP -#line 56 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return RELOP; } - YY_BREAK -case 24: -YY_RULE_SETUP -#line 57 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return RELOP; } - YY_BREAK -case 25: -YY_RULE_SETUP -#line 58 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return RELOP; } - YY_BREAK -case 26: -YY_RULE_SETUP -#line 59 "qfelexer.lpp" -{ qfelval.cp = newstr(qfetext); return RELOP; } - YY_BREAK -case 27: -YY_RULE_SETUP -#line 61 "qfelexer.lpp" -{} - YY_BREAK -case 28: -YY_RULE_SETUP -#line 62 "qfelexer.lpp" -{ qfelineno++; } - YY_BREAK -case 29: -YY_RULE_SETUP -#line 64 "qfelexer.lpp" -{ return qfetext[0]; } - YY_BREAK -case 30: -YY_RULE_SETUP -#line 66 "qfelexer.lpp" -ECHO; - YY_BREAK -#line 876 "lex-win.cpp" - case YY_STATE_EOF(INITIAL): - case YY_STATE_EOF(CCONST): - yyterminate(); - - case YY_END_OF_BUFFER: - { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) - { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yylex(). If so, then we have to assure - * consistency between yy_current_buffer and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yy_n_chars = yy_current_buffer->yy_n_chars; - yy_current_buffer->yy_input_file = yyin; - yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans( yy_current_state ); - - yy_bp = yytext_ptr + YY_MORE_ADJ; - - if ( yy_next_state ) - { - /* Consume the NUL. */ - yy_cp = ++yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else - { - yy_cp = yy_c_buf_p; - goto yy_find_action; - } - } - - else switch ( yy_get_next_buffer() ) - { - case EOB_ACT_END_OF_FILE: - { - yy_did_buffer_switch_on_eof = 0; - - if ( yywrap() ) - { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else - { - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = - yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yy_c_buf_p = - &yy_current_buffer->yy_ch_buf[yy_n_chars]; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR( - "fatal flex scanner internal error--no action found" ); - } /* end of action switch */ - } /* end of scanning one token */ - } /* end of yylex */ - - -/* yy_get_next_buffer - try to read in a new buffer - * - * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file - */ - -static int yy_get_next_buffer() - { - register char *dest = yy_current_buffer->yy_ch_buf; - register char *source = yytext_ptr; - register int number_to_move, i; - int ret_val; - - if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) - YY_FATAL_ERROR( - "fatal flex scanner internal error--end of buffer missed" ); - - if ( yy_current_buffer->yy_fill_buffer == 0 ) - { /* Don't try to fill the buffer, so this is an EOF. */ - if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) - { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else - { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; - - for ( i = 0; i < number_to_move; ++i ) - *(dest++) = *(source++); - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - yy_current_buffer->yy_n_chars = yy_n_chars = 0; - - else - { - int num_to_read = - yy_current_buffer->yy_buf_size - number_to_move - 1; - - while ( num_to_read <= 0 ) - { /* Not enough room in the buffer - grow it. */ -#ifdef YY_USES_REJECT - YY_FATAL_ERROR( -"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); -#else - - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = yy_current_buffer; - - int yy_c_buf_p_offset = - (int) (yy_c_buf_p - b->yy_ch_buf); - - if ( b->yy_is_our_buffer ) - { - int new_size = b->yy_buf_size * 2; - - if ( new_size <= 0 ) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; - - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yy_flex_realloc( (void *) b->yy_ch_buf, - b->yy_buf_size + 2 ); - } - else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; - - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( - "fatal error - scanner input buffer overflow" ); - - yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - - num_to_read = yy_current_buffer->yy_buf_size - - number_to_move - 1; -#endif - } - - if ( num_to_read > YY_READ_BUF_SIZE ) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), - yy_n_chars, num_to_read ); - - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - if ( yy_n_chars == 0 ) - { - if ( number_to_move == YY_MORE_ADJ ) - { - ret_val = EOB_ACT_END_OF_FILE; - yyrestart( yyin ); - } - - else - { - ret_val = EOB_ACT_LAST_MATCH; - yy_current_buffer->yy_buffer_status = - YY_BUFFER_EOF_PENDING; - } - } - - else - ret_val = EOB_ACT_CONTINUE_SCAN; - - yy_n_chars += number_to_move; - yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; - yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; - - yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; - - return ret_val; - } - - -/* yy_get_previous_state - get the state just before the EOB char was reached */ - -static yy_state_type yy_get_previous_state() - { - register yy_state_type yy_current_state; - register char *yy_cp; - - yy_current_state = yy_start; - yy_state_ptr = yy_state_buf; - *yy_state_ptr++ = yy_current_state; - - for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) - { - register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 80 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - *yy_state_ptr++ = yy_current_state; - } - - return yy_current_state; - } - - -/* yy_try_NUL_trans - try to make a transition on the NUL character - * - * synopsis - * next_state = yy_try_NUL_trans( current_state ); - */ - -#ifdef YY_USE_PROTOS -static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) -#else -static yy_state_type yy_try_NUL_trans( yy_current_state ) -yy_state_type yy_current_state; -#endif - { - register int yy_is_jam; - - register YY_CHAR yy_c = 1; - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 80 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 79); - if ( ! yy_is_jam ) - *yy_state_ptr++ = yy_current_state; - - return yy_is_jam ? 0 : yy_current_state; - } - - -#ifndef YY_NO_UNPUT -#ifdef YY_USE_PROTOS -static void yyunput( int c, register char *yy_bp ) -#else -static void yyunput( c, yy_bp ) -int c; -register char *yy_bp; -#endif - { - register char *yy_cp = yy_c_buf_p; - - /* undo effects of setting up yytext */ - *yy_cp = yy_hold_char; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - { /* need to shift things up to make room */ - /* +2 for EOB chars. */ - register int number_to_move = yy_n_chars + 2; - register char *dest = &yy_current_buffer->yy_ch_buf[ - yy_current_buffer->yy_buf_size + 2]; - register char *source = - &yy_current_buffer->yy_ch_buf[number_to_move]; - - while ( source > yy_current_buffer->yy_ch_buf ) - *--dest = *--source; - - yy_cp += (int) (dest - source); - yy_bp += (int) (dest - source); - yy_current_buffer->yy_n_chars = - yy_n_chars = yy_current_buffer->yy_buf_size; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - YY_FATAL_ERROR( "flex scanner push-back overflow" ); - } - - *--yy_cp = (char) c; - - if ( c == '\n' ) - --yylineno; - - yytext_ptr = yy_bp; - yy_hold_char = *yy_cp; - yy_c_buf_p = yy_cp; - } -#endif /* ifndef YY_NO_UNPUT */ - - -#ifdef __cplusplus -static int yyinput() -#else -static int input() -#endif - { - int c; - - *yy_c_buf_p = yy_hold_char; - - if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) - { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - /* This was really a NUL. */ - *yy_c_buf_p = '\0'; - - else - { /* need more input */ - int offset = yy_c_buf_p - yytext_ptr; - ++yy_c_buf_p; - - switch ( yy_get_next_buffer() ) - { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yyrestart( yyin ); - - /* fall through */ - - case EOB_ACT_END_OF_FILE: - { - if ( yywrap() ) - return EOF; - - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; -#ifdef __cplusplus - return yyinput(); -#else - return input(); -#endif - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = yytext_ptr + offset; - break; - } - } - } - - c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ - *yy_c_buf_p = '\0'; /* preserve yytext */ - yy_hold_char = *++yy_c_buf_p; - - if ( c == '\n' ) - ++yylineno; - - return c; - } - - -#ifdef YY_USE_PROTOS -void yyrestart( FILE *input_file ) -#else -void yyrestart( input_file ) -FILE *input_file; -#endif - { - if ( ! yy_current_buffer ) - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_init_buffer( yy_current_buffer, input_file ); - yy_load_buffer_state(); - } - - -#ifdef YY_USE_PROTOS -void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) -#else -void yy_switch_to_buffer( new_buffer ) -YY_BUFFER_STATE new_buffer; -#endif - { - if ( yy_current_buffer == new_buffer ) - return; - - if ( yy_current_buffer ) - { - /* Flush out information for old buffer. */ - *yy_c_buf_p = yy_hold_char; - yy_current_buffer->yy_buf_pos = yy_c_buf_p; - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - yy_current_buffer = new_buffer; - yy_load_buffer_state(); - - /* We don't actually know whether we did this switch during - * EOF (yywrap()) processing, but the only time this flag - * is looked at is after yywrap() is called, so it's safe - * to go ahead and always set it. - */ - yy_did_buffer_switch_on_eof = 1; - } - - -#ifdef YY_USE_PROTOS -void yy_load_buffer_state( void ) -#else -void yy_load_buffer_state() -#endif - { - yy_n_chars = yy_current_buffer->yy_n_chars; - yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; - yyin = yy_current_buffer->yy_input_file; - yy_hold_char = *yy_c_buf_p; - } - - -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) -#else -YY_BUFFER_STATE yy_create_buffer( file, size ) -FILE *file; -int size; -#endif - { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_buf_size = size; - - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_is_our_buffer = 1; - - yy_init_buffer( b, file ); - - return b; - } - - -#ifdef YY_USE_PROTOS -void yy_delete_buffer( YY_BUFFER_STATE b ) -#else -void yy_delete_buffer( b ) -YY_BUFFER_STATE b; -#endif - { - if ( ! b ) - return; - - if ( b == yy_current_buffer ) - yy_current_buffer = (YY_BUFFER_STATE) 0; - - if ( b->yy_is_our_buffer ) - yy_flex_free( (void *) b->yy_ch_buf ); - - yy_flex_free( (void *) b ); - } - - -#ifndef YY_ALWAYS_INTERACTIVE -#ifndef YY_NEVER_INTERACTIVE -extern int isatty YY_PROTO(( int )); -#endif -#endif - -#ifdef YY_USE_PROTOS -void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) -#else -void yy_init_buffer( b, file ) -YY_BUFFER_STATE b; -FILE *file; -#endif - - - { - yy_flush_buffer( b ); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; - -#if YY_ALWAYS_INTERACTIVE - b->yy_is_interactive = 1; -#else -#if YY_NEVER_INTERACTIVE - b->yy_is_interactive = 0; -#else - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; -#endif -#endif - } - - -#ifdef YY_USE_PROTOS -void yy_flush_buffer( YY_BUFFER_STATE b ) -#else -void yy_flush_buffer( b ) -YY_BUFFER_STATE b; -#endif - - { - if ( ! b ) - return; - - b->yy_n_chars = 0; - - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - - b->yy_buf_pos = &b->yy_ch_buf[0]; - - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; - - if ( b == yy_current_buffer ) - yy_load_buffer_state(); - } - - -#ifndef YY_NO_SCAN_BUFFER -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) -#else -YY_BUFFER_STATE yy_scan_buffer( base, size ) -char *base; -yy_size_t size; -#endif - { - YY_BUFFER_STATE b; - - if ( size < 2 || - base[size-2] != YY_END_OF_BUFFER_CHAR || - base[size-1] != YY_END_OF_BUFFER_CHAR ) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yy_switch_to_buffer( b ); - - return b; - } -#endif - - -#ifndef YY_NO_SCAN_STRING -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) -#else -YY_BUFFER_STATE yy_scan_string( yy_str ) -yyconst char *yy_str; -#endif - { - int len; - for ( len = 0; yy_str[len]; ++len ) - ; - - return yy_scan_bytes( yy_str, len ); - } -#endif - - -#ifndef YY_NO_SCAN_BYTES -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) -#else -YY_BUFFER_STATE yy_scan_bytes( bytes, len ) -yyconst char *bytes; -int len; -#endif - { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n; - int i; - - /* Get memory for full buffer, including space for trailing EOB's. */ - n = len + 2; - buf = (char *) yy_flex_alloc( n ); - if ( ! buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); - - for ( i = 0; i < len; ++i ) - buf[i] = bytes[i]; - - buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; - - b = yy_scan_buffer( buf, n ); - if ( ! b ) - YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); - - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; - - return b; - } -#endif - - -#ifndef YY_NO_PUSH_STATE -#ifdef YY_USE_PROTOS -static void yy_push_state( int new_state ) -#else -static void yy_push_state( new_state ) -int new_state; -#endif - { - if ( yy_start_stack_ptr >= yy_start_stack_depth ) - { - yy_size_t new_size; - - yy_start_stack_depth += YY_START_STACK_INCR; - new_size = yy_start_stack_depth * sizeof( int ); - - if ( ! yy_start_stack ) - yy_start_stack = (int *) yy_flex_alloc( new_size ); - - else - yy_start_stack = (int *) yy_flex_realloc( - (void *) yy_start_stack, new_size ); - - if ( ! yy_start_stack ) - YY_FATAL_ERROR( - "out of memory expanding start-condition stack" ); - } - - yy_start_stack[yy_start_stack_ptr++] = YY_START; - - BEGIN(new_state); - } -#endif - - -#ifndef YY_NO_POP_STATE -static void yy_pop_state() - { - if ( --yy_start_stack_ptr < 0 ) - YY_FATAL_ERROR( "start-condition stack underflow" ); - - BEGIN(yy_start_stack[yy_start_stack_ptr]); - } -#endif - - -#ifndef YY_NO_TOP_STATE -static int yy_top_state() - { - return yy_start_stack[yy_start_stack_ptr - 1]; - } -#endif - -#ifndef YY_EXIT_FAILURE -#define YY_EXIT_FAILURE 2 -#endif - -#ifdef YY_USE_PROTOS -static void yy_fatal_error( yyconst char msg[] ) -#else -static void yy_fatal_error( msg ) -char msg[]; -#endif - { - (void) fprintf( stderr, "%s\n", msg ); - exit( YY_EXIT_FAILURE ); - } - - - -/* Redefine yyless() so it works in section 3 code. */ - -#undef yyless -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - yytext[yyleng] = yy_hold_char; \ - yy_c_buf_p = yytext + n; \ - yy_hold_char = *yy_c_buf_p; \ - *yy_c_buf_p = '\0'; \ - yyleng = n; \ - } \ - while ( 0 ) - - -/* Internal utility routines. */ - -#ifndef yytext_ptr -#ifdef YY_USE_PROTOS -static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) -#else -static void yy_flex_strncpy( s1, s2, n ) -char *s1; -yyconst char *s2; -int n; -#endif - { - register int i; - for ( i = 0; i < n; ++i ) - s1[i] = s2[i]; - } -#endif - -#ifdef YY_NEED_STRLEN -#ifdef YY_USE_PROTOS -static int yy_flex_strlen( yyconst char *s ) -#else -static int yy_flex_strlen( s ) -yyconst char *s; -#endif - { - register int n; - for ( n = 0; s[n]; ++n ) - ; - - return n; - } -#endif - - -#ifdef YY_USE_PROTOS -static void *yy_flex_alloc( yy_size_t size ) -#else -static void *yy_flex_alloc( size ) -yy_size_t size; -#endif - { - return (void *) malloc( size ); - } - -#ifdef YY_USE_PROTOS -static void *yy_flex_realloc( void *ptr, yy_size_t size ) -#else -static void *yy_flex_realloc( ptr, size ) -void *ptr; -yy_size_t size; -#endif - { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *) realloc( (char *) ptr, size ); - } - -#ifdef YY_USE_PROTOS -static void yy_flex_free( void *ptr ) -#else -static void yy_flex_free( ptr ) -void *ptr; -#endif - { - free( ptr ); - } - -#if YY_MAIN -int main() - { - yylex(); - return 0; - } -#endif -#line 66 "qfelexer.lpp" diff --git a/tools/qfe/parsequery.cpp b/tools/qfe/parsequery.cpp deleted file mode 100644 index 4809ab15..00000000 --- a/tools/qfe/parsequery.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include -using namespace std; - -#include -#include -using namespace boost; - -#include "cseputils.h" -#include "parsequery.h" - -#include "calpontselectexecutionplan.h" -#include "simplecolumn.h" -#include "simplefilter.h" -#include "constantcolumn.h" -#include "calpontsystemcatalog.h" -#include "sessionmanager.h" -using namespace execplan; - -#include "brmtypes.h" -using namespace BRM; - -extern int qfeparse(); -extern int qfedebug; - -struct yy_buffer_state; -extern yy_buffer_state* qfe_scan_string(const char*); -extern void qfe_delete_buffer(yy_buffer_state*); -extern CalpontSelectExecutionPlan* ParserCSEP; -extern boost::shared_ptr ParserCSC; - -namespace -{ -mutex ParserMutex; -} //anon namespace - -namespace qfe -{ -extern string DefaultSchema; - -CalpontSelectExecutionPlan* parseQuery(const string& query, const uint32_t sid) -{ - //We're going to make parsing the query single-threaded for now. This makes it a lot - // easier to interface with the parser and doesn;t materially affect overall query - // performance (I think) - mutex::scoped_lock lk(ParserMutex); - - boost::shared_ptr csc = CalpontSystemCatalog::makeCalpontSystemCatalog(sid); - CalpontSelectExecutionPlan* csep=0; - csep = new CalpontSelectExecutionPlan(); - //we use an auto_ptr here with some trepidation. We only want auto delete on an execption. - //If the parseing and plan build succeed, we want the ptr to stay around. boost::scoped_ptr<> - //doesn't have an API to release ownership, so we use auto_ptr... - auto_ptr scsep(csep); - - yy_buffer_state* ybs=0; - ybs = qfe_scan_string(query.c_str()); - if (ybs != 0) - { - ParserCSEP = csep; - ParserCSC = csc; - if (qfeparse() != 0) - throw runtime_error("syntax error"); - qfe_delete_buffer(ybs); - } - else - throw runtime_error("Internal parser memory error"); - - csep->data(query); - - SessionManager sm; - TxnID txnID; - txnID = sm.getTxnID(sid); - if (!txnID.valid) - { - txnID.id = 0; - txnID.valid = true; - } - QueryContext verID; - verID = sm.verID(); - - csep->txnID(txnID.id); - csep->verID(verID); - csep->sessionID(sid); - - //cout << *csep << endl; - scsep.release(); - return csep; -} - -} - diff --git a/tools/qfe/parsequery.h b/tools/qfe/parsequery.h deleted file mode 100644 index afd64580..00000000 --- a/tools/qfe/parsequery.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef QFE_PARSEQUERY_H__ -#define QFE_PARSEQUERY_H__ - -#include -#include - -#include "calpontselectexecutionplan.h" - -namespace qfe -{ - -execplan::CalpontSelectExecutionPlan* parseQuery(const std::string&, uint32_t); - -} - -#endif diff --git a/tools/qfe/qfe-cli.py b/tools/qfe/qfe-cli.py deleted file mode 100755 index 70a5ea19..00000000 --- a/tools/qfe/qfe-cli.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/python -''' -Created on May 1, 2013 - -@author: rtw -''' - -import struct -import binascii -import socket -import sys - -QFE_HOST = 'localhost' -#QFE_HOST = 'winsvr2008r2.calpont.com' -QFE_SOCK = 9198 - -def do_query(query): - client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - client_socket.connect((QFE_HOST, QFE_SOCK)) - - defschem = "tpch1"; - lenstruct = struct.pack("I", len(defschem)) - client_socket.send(lenstruct) - client_socket.send(defschem) - - lenstruct = struct.pack("I", len(query)) - client_socket.send(lenstruct) - client_socket.send(query) - - rowlen = 1 - while rowlen: - rowlen = client_socket.recv(4) - if len(rowlen) < 4: - break - rowval = struct.unpack("I",rowlen)[0] - if rowval == 0: - lenstruct = struct.pack("I", 0); - client_socket.send(lenstruct) - break - row = client_socket.recv(rowval) - print row - - client_socket.close() - -if __name__ == '__main__': - if len(sys.argv) < 2: - query = raw_input ( "QFE-cli > " ) - else: - query = sys.argv[1] - - sys.exit(do_query(query)) diff --git a/tools/qfe/qfelexer.lpp b/tools/qfe/qfelexer.lpp deleted file mode 100644 index 853cec75..00000000 --- a/tools/qfe/qfelexer.lpp +++ /dev/null @@ -1,65 +0,0 @@ -%{ -#include -#include -#include "returnedcolumn.h" -#ifndef _MSC_VER -#include "qfeparser.h" -#else -#include "bison-win.h" -#endif - -extern int qfeerror(const char *s); - -extern std::string* newstr(const char* cp); - -%} - -%option noyywrap -%option yylineno -%option nounput - -%x CCONST - -digit [0-9] -int_const [+-]?{digit}+ -letter [a-zA-Z_] -objname {letter}({letter}|{digit})* - -%% - -"SELECT" { return QFEP_SELECT; } -"FROM" { return QFEP_FROM; } -"WHERE" { return QFEP_WHERE; } -"GROUP BY" { return GROUPBY; } -"AND" { qfelval.cp = newstr(qfetext); return LOGICOP; } -"OR" { qfelval.cp = newstr(qfetext); return LOGICOP; } -"LIMIT" { return LIMIT; } -"ORDER BY" { return ORDERBY; } -"ASC" { return ASC; } -"DESC" { return DESC; } -"AS" { return AS; } -"SUM" { qfelval.cp = newstr(qfetext); return FUNC; } -"MIN" { qfelval.cp = newstr(qfetext); return FUNC; } -"MAX" { qfelval.cp = newstr(qfetext); return FUNC; } -"AVG" { qfelval.cp = newstr(qfetext); return FUNC; } - -{objname} { qfelval.cp = newstr(qfetext); return OBJNAME; } - -"'" { BEGIN(CCONST); } -[^']* { qfelval.cp = newstr(qfetext); return CHAR_CONST; } -"'" { BEGIN(INITIAL); } - -{int_const} { qfelval.cp = newstr(qfetext); return INT_CONST; } - -">" { qfelval.cp = newstr(qfetext); return RELOP; } -">=" { qfelval.cp = newstr(qfetext); return RELOP; } -"<" { qfelval.cp = newstr(qfetext); return RELOP; } -"<=" { qfelval.cp = newstr(qfetext); return RELOP; } -"<>" { qfelval.cp = newstr(qfetext); return RELOP; } -"=" { qfelval.cp = newstr(qfetext); return RELOP; } - -[ \t]* {} -[\n] { qfelineno++; } - -. { return qfetext[0]; } - diff --git a/tools/qfe/qfeparser.ypp b/tools/qfe/qfeparser.ypp deleted file mode 100644 index 4bf75d59..00000000 --- a/tools/qfe/qfeparser.ypp +++ /dev/null @@ -1,306 +0,0 @@ -%{ -#include -#include -#include -using namespace std; - -namespace qfe -{ -extern string DefaultSchema; -} - -int qfeerror(const char *s); -int qfelex(void); - -#include "calpontselectexecutionplan.h" -#include "simplecolumn.h" -#include "calpontsystemcatalog.h" -#include "aggregatecolumn.h" -execplan::CalpontSelectExecutionPlan* ParserCSEP; -execplan::CalpontSystemCatalog* ParserCSC; -namespace execplan -{ -class ReturnedColumn; -} - -#include "cseputils.h" - -%} - -%union -{ - execplan::ReturnedColumn* rcp; - std::string* cp; - std::pair* cvp; -} - -//Some of these defines cause conflicts in calpontselectexecutionplan.h, so we prepend QFEP_ -%token CHAR_CONST RELOP LOGICOP QFEP_SELECT QFEP_FROM QFEP_WHERE GROUPBY OBJNAME INT_CONST LIMIT ORDERBY ASC -%token DESC AS FUNC - -%type select_column_list table_name filter_predicate_list obj_name_aux opt_alias opt_as -%type opt_limit_clause -%type OBJNAME CHAR_CONST INT_CONST RELOP LOGICOP FUNC AS - -%type aliased_column_name select_column_name obj_name func_col groupby_item - -%type constant - -%destructor { delete $$; } OBJNAME CHAR_CONST INT_CONST RELOP LOGICOP FUNC AS -%destructor { delete $$; } aliased_column_name select_column_name obj_name func_col groupby_item -%destructor { delete $$; } constant - -%% - -statement: QFEP_SELECT select_column_list - QFEP_FROM table_spec - opt_where_clause - opt_groupby_clause - opt_orderby_clause - opt_limit_clause ';' - ; - -select_column_list: aliased_column_name - { - execplan::SRCP rcp($1); - ParserCSEP->returnedCols().push_back(rcp); - $$ = 0; - } - | select_column_list ',' aliased_column_name - { - execplan::SRCP rcp($3); - ParserCSEP->returnedCols().push_back(rcp); - $$ = 0; - } - ; - -select_column_name: obj_name - { - execplan::SimpleColumn* sc = dynamic_cast($1); - if (sc->schemaName() == "infinidb_unknown" && !qfe::DefaultSchema.empty()) - sc->schemaName(qfe::DefaultSchema); - sc->setOID(); - sc->tableAlias(sc->tableName()); - sc->alias(execplan::make_tcn(sc->schemaName(), sc->tableName(), sc->columnName()).toString()); - $$ = $1; - } - | func_col - ; - -func_col: FUNC '(' select_column_name ')' - { - execplan::AggregateColumn* ag = new execplan::AggregateColumn(execplan::AggregateColumn::agname2num(*($1)), $3); - delete $1; - $$ = ag; - } - ; - -aliased_column_name: select_column_name opt_alias - ; - -opt_alias: /* empty */ - { $$ = 0; } - | opt_as OBJNAME - { - delete $2; - $$ = $1; - } - | opt_as CHAR_CONST - { - delete $2; - $$ = $1; - } - ; - -opt_as: /* empty */ - { $$ = 0; } - | AS - ; - -table_spec: aliased_table_name - ; - -/* this is too loose for a table name, but it's easier to parse */ -table_name: obj_name - { - execplan::SimpleColumn* sc=0; - sc = dynamic_cast($1); - execplan::CalpontSystemCatalog::TableAliasName tan; - tan.schema = sc->tableName(); - if (tan.schema == "infinidb_unknown" && !qfe::DefaultSchema.empty()) - tan.schema = qfe::DefaultSchema; - if (qfe::DefaultSchema.empty()) - qfe::DefaultSchema = tan.schema; - tan.table = sc->columnName(); - tan.alias = tan.table; - execplan::CalpontSelectExecutionPlan::TableList tl; - tl.push_back(tan); - ParserCSEP->tableList(tl); - delete sc; - $$ = 0; - } - ; - -aliased_table_name: table_name opt_alias - ; - -opt_where_clause: /* empty */ - | QFEP_WHERE filter_predicate_list - ; - -filter_predicate_list: obj_name RELOP constant - { - pair cval = *($3); - delete $3; - execplan::SimpleColumn* sc=0; - sc = dynamic_cast($1); - qfe::utils::updateParseTree(ParserCSC, ParserCSEP, - sc, *($2), cval); - delete sc; - delete $2; - $$ = 0; - } - | filter_predicate_list LOGICOP obj_name RELOP constant - { - //string logicop = *($2); - delete $2; - pair cval = *($5); - delete $5; - execplan::SimpleColumn* sc=0; - sc = dynamic_cast($3); - qfe::utils::updateParseTree(ParserCSC, ParserCSEP, - sc, *($4), cval); - delete sc; - delete $4; - $$ = 0; - } - ; - -obj_name: obj_name_aux - { - //This is possibly a table name, but we shove it into a SimpleColumn. We'll - // fix this in the table_spec production - execplan::SimpleColumn* sc = new execplan::SimpleColumn("infinidb_unknown", "infinidb_unknown", *($1)); - sc->tableAlias("infinidb_unknown"); - sc->alias(execplan::make_tcn("infinidb_unknown", "infinidb_unknown", *($1)).toString()); - //cerr << "inside parser: " << *sc << endl; - delete $1; - $$ = sc; - } - | obj_name_aux '.' obj_name_aux - { - //This is possibly a table name, but we shove it into a SimpleColumn. We'll - // fix this in the table_spec production - execplan::SimpleColumn* sc = new execplan::SimpleColumn("infinidb_unknown", *($1), *($3)); - sc->tableAlias(*($1)); - sc->alias(execplan::make_tcn("infinidb_unknown", *($1), *($3)).toString()); - //cerr << "inside parser: " << *sc << endl; - delete $1; - delete $3; - $$ = sc; - } - | obj_name_aux '.' obj_name_aux '.' obj_name_aux - { - if (qfe::DefaultSchema.empty()) - qfe::DefaultSchema = *($1); - execplan::SimpleColumn* sc = new execplan::SimpleColumn(*($1), *($3), *($5)); - sc->tableAlias(*($3)); - sc->alias(execplan::make_tcn(*($1), *($3), *($5)).toString()); - //cerr << "inside parser: " << *sc << endl; - delete $1; - delete $3; - delete $5; - $$ = sc; - } - ; - -obj_name_aux: OBJNAME - | '`' OBJNAME '`' - { - $$ = $2; - } - ; - -constant: CHAR_CONST - { - pair* p = new pair(1, *($1)); - delete $1; - $$ = p; - } - | INT_CONST - { - pair* p = new pair(0, *($1)); - delete $1; - $$ = p; - } - ; - -opt_groupby_clause: /* empty */ - | GROUPBY groupby_items_list - { YYERROR; } - ; - -groupby_items_list: groupby_item - | groupby_items_list ',' groupby_item - { delete $3; } - ; - -groupby_item: obj_name - | INT_CONST - { - delete $1; - $$ = 0; - } - ; - -opt_orderby_clause: /* empty */ - | ORDERBY groupby_items_list opt_direction - { YYERROR; } - ; - -opt_direction: /* empty */ - | ASC - | DESC - ; - -opt_limit_clause: /* empty */ - { $$ = 0; } - | LIMIT INT_CONST - { - delete $2; - YYERROR; - $$ = 0; - } - | LIMIT INT_CONST ',' INT_CONST - { - delete $2; - delete $4; - YYERROR; - $$ = 0; - } - ; - -%% - -int qfeerror(const string& s) -{ - extern int qfelineno; // defined and maintained in lex.c - extern char *qfetext; // defined and maintained in lex.c - - cerr << "ERROR: " << s << " at symbol \"" << qfetext; - cerr << "\" on line " << qfelineno << endl; - return -1; -} - -int qfeerror(const char *s) -{ - return qfeerror(string(s)); -} - -string* newstr(const char* cp) -{ - string* strp; - strp = new string(cp); - return strp; -} - diff --git a/tools/qfe/returnedrows.cpp b/tools/qfe/returnedrows.cpp deleted file mode 100644 index eb13a610..00000000 --- a/tools/qfe/returnedrows.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -#include -using namespace std; - -#include -#include -using namespace boost; - -#ifndef _MSC_VER -#include "config.h" -#endif - -#include "socktype.h" - -#include "exceptclasses.h" - -#include "socketio.h" - -#include "bytestream.h" -#include "messagequeue.h" -using namespace messageqcpp; - -#include "rowgroup.h" -using namespace rowgroup; - -namespace qfe -{ - -void processReturnedRows(MessageQueueClient* mqc, SockType fd) -{ - scoped_ptr cleaner(mqc); - SBS sbs; - sbs = mqc->read(); - //cerr << "got a bs of " << sbs->length() << " bytes" << endl; - - RowGroup rg; - rg.deserialize(*sbs); - - //cerr << "got a base rowgroup with rows of " << rg.getRowSize() << " bytes" << endl; - //cerr << rg.toString() << endl; - - ByteStream bs; - ByteStream::quadbyte tableOID=100; - bs.reset(); - bs << tableOID; - mqc->write(bs); - - sbs = mqc->read(); - //cerr << "got a bs of " << sbs->length() << " bytes" << endl; - RGData rgd; - rgd.deserialize(*sbs, true); - rg.setData(&rgd); - //cerr << "got a rowgroup with: " << rg.getRowCount() << " rows" << endl; - - socketio::writeString(fd, "OK"); - Row r; - while (rg.getRowCount() > 0) - { - rg.initRow(&r); - rg.getRow(0, &r); - string csv; - bs.reset(); - for (unsigned i = 0; i < rg.getRowCount(); i++) - { - csv = r.toCSV(); - bs << csv; - r.nextRow(); - } - //cerr << "writing " << bs.length() << " bytes back to client" << endl; - SockWriteFcn(fd, bs.buf(), bs.length()); - - bs.reset(); - bs << tableOID; - mqc->write(bs); - - sbs = mqc->read(); - //cerr << "got a bs of " << sbs->length() << " bytes" << endl; - rgd.deserialize(*sbs, true); - rg.setData(&rgd); - //cerr << "got a rowgroup with: " << rg.getRowCount() << " rows" << endl; - } - - tableOID=0; - bs.reset(); - bs << tableOID; - mqc->write(bs); - - //sync with the client on end-of-results - SockWriteFcn(fd, &tableOID, 4); - SockReadFcn(fd, &tableOID, 4); - -} - -} - diff --git a/tools/qfe/returnedrows.h b/tools/qfe/returnedrows.h deleted file mode 100644 index ce4a4e52..00000000 --- a/tools/qfe/returnedrows.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef QFE_RETURNEDROWS_H__ -#define QFE_RETURNEDROWS_H__ - -#include "socktype.h" -#include "messagequeue.h" - -namespace qfe -{ - -void processReturnedRows(messageqcpp::MessageQueueClient*, SockType); - -} - -#endif - diff --git a/tools/qfe/scanner.bat b/tools/qfe/scanner.bat deleted file mode 100644 index 31d4b79f..00000000 --- a/tools/qfe/scanner.bat +++ /dev/null @@ -1,6 +0,0 @@ -PATH=C:\PROGRA~2\GNUWIN32\BIN;%PATH% - -del bison-win.h >nul 2>&1 -bison -d -p qfe -o bison-win.cpp qfeparser.ypp -ren bison-win.hpp bison-win.h -flex -i -Pqfe -olex-win.cpp qfelexer.lpp diff --git a/tools/qfe/sendcsep.cpp b/tools/qfe/sendcsep.cpp deleted file mode 100644 index 118bf27f..00000000 --- a/tools/qfe/sendcsep.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include -#include -using namespace std; - -#include -using namespace boost; - -#include "calpontselectexecutionplan.h" -using namespace execplan; -#include "bytestream.h" -#include "messagequeue.h" -using namespace messageqcpp; - -namespace qfe -{ - -MessageQueueClient* sendCSEP(CalpontSelectExecutionPlan* csep) -{ - scoped_ptr cleaner(csep); - - ByteStream bs; - - MessageQueueClient* mqc=0; - - mqc = new MessageQueueClient("ExeMgr1"); - auto_ptr smqc(mqc); - - bs.reset(); - ByteStream::quadbyte wantTuples=4; - bs << wantTuples; - mqc->write(bs); - - bs.reset(); - csep->serialize(bs); - mqc->write(bs); - - SBS sbs; - sbs = mqc->read(); - *sbs >> wantTuples; - //cerr << "got flag: " << wantTuples << endl; - string msg; - sbs = mqc->read(); - *sbs >> msg; - //cerr << "got msg: " << msg << endl; - - if (wantTuples != 0) - throw runtime_error(msg); - - smqc.release(); - return mqc; -} - -} - diff --git a/tools/qfe/sendcsep.h b/tools/qfe/sendcsep.h deleted file mode 100644 index 47ba2848..00000000 --- a/tools/qfe/sendcsep.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef QFE_SENDCSEP_H__ -#define QFE_SENDCSEP_H__ - -#include "messagequeue.h" -#include "calpontselectexecutionplan.h" - -namespace qfe -{ - -//Takes ownership of the alloc'd ptr -//Returns an alloc'd mqc -messageqcpp::MessageQueueClient* sendCSEP(execplan::CalpontSelectExecutionPlan*); - -} - -#endif - diff --git a/tools/qfe/server.cpp b/tools/qfe/server.cpp deleted file mode 100644 index 3666adec..00000000 --- a/tools/qfe/server.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -/* - Protocol definition: -*/ - -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#include -#include -#include -#include -#include -#else -#include -#include -#include -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -using namespace std; - -#include -#include -#include -#include -#include -using namespace boost; - -#ifndef _MSC_VER -#include "config.h" -#endif - -#include "socktype.h" -#include "parsequery.h" -#include "sendcsep.h" -#include "returnedrows.h" -#include "socketio.h" -#include "ddlstmts.h" - -#include "exceptclasses.h" //brings in idbassert_s macro - -#include "messagequeue.h" -using namespace messageqcpp; - -#include "atomicops.h" - -namespace execplan -{ -class CalpontSelectExecutionPlan; -} - -#define SINGLE_THREADED - -namespace qfe -{ -string DefaultSchema; -} - -namespace -{ -using namespace qfe; - -enum StmtType -{ - UNKNOWN, - QUERY, - CREATE, - DROP, - SHOW, -}; - -volatile uint32_t SystemSID; - -void log(const string &s) -{ - cerr << s << endl; -} - -struct QueryMessage -{ - QueryMessage() : isValid(false) { } - ~QueryMessage() { } - - string toString() const; - - bool isValid; - string queryText; - string defaultSchema; -}; - -string QueryMessage::toString() const -{ - ostringstream oss; - oss << "valid: " << boolalpha << isValid << ", " << - "queryText: " << queryText << ", " << - "defaultSchema: " << defaultSchema; - return oss.str(); -} - -ostream& operator<<(ostream& os, const QueryMessage& rhs) -{ - os << rhs.toString(); - return os; -} - -class ThreadFunc -{ -public: - ThreadFunc(SockType fd) : fFd(fd) { } - ~ThreadFunc() { } - - void run(); - void operator()() { run(); } - -private: - ThreadFunc(const ThreadFunc& rhs); - ThreadFunc& operator=(const ThreadFunc& rhs); - - SockType fFd; -}; - -bool serverInit() -{ -#ifndef _MSC_VER - - setsid(); - - //Handle certain signals (we want these to return EINTR so we can throw) - //SIGPIPE - //I don't think we'll get any of these from init (except possibly HUP, but that's an indication - // of bad things anyway) - //SIGHUP? - //SIGUSR1? - //SIGUSR2? - //SIGPOLL? - struct sigaction sa; - memset(&sa, 0, sizeof(struct sigaction)); - sa.sa_handler = SIG_IGN; - sigaction(SIGPIPE, &sa, 0); - sigaction(SIGHUP, &sa, 0); - sigaction(SIGUSR1, &sa, 0); - sigaction(SIGUSR2, &sa, 0); -#ifndef __FreeBSD__ - sigaction(SIGPOLL, &sa, 0); -#endif -#if 0 - int fd; - close(2); - fd = open("/tmp/qfe.err",O_CREAT|O_TRUNC|O_WRONLY,0644); - if (fd >= 0 && fd != 2) - { - dup2(fd, 2); - close(fd); - } -#endif -#endif - return true; -} - -SockType initListenSock(short portNo) -{ - SockType listenSock=-1; -#ifdef _MSC_VER - WSAData wsadata; - const WORD minVersion = MAKEWORD(2, 2); - WSAStartup(minVersion, &wsadata); -#endif - listenSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); - idbassert_s(listenSock >= 0, string("socket create error: ") + strerror(errno)); - //if (listenSock < 0) throw runtime_error(string("socket create error: ") + strerror(errno)); -#ifndef _MSC_VER - int optval = 1; - setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&optval), sizeof(optval)); -#endif - int rc = 0; - struct sockaddr_in serv_addr; - memset(&serv_addr, 0, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = INADDR_ANY; - serv_addr.sin_port = htons(portNo); - const int MaxTries = 5 * 60 / 10; - int tries = 0; -again: - rc = ::bind(listenSock, (sockaddr*)&serv_addr, sizeof(serv_addr)); - if (rc < 0) - { -#ifdef _MSC_VER - int x = WSAGetLastError(); - if (x == WSAEADDRINUSE) -#else - if (errno == EADDRINUSE) -#endif - { - //cerr << "Addr in use..." << endl; - if (++tries >= MaxTries) - { - log("Waited too long for socket to bind...giving up"); - //cerr << "Waited too long for socket to bind...giving up" << endl; - exit(1); - } - sleep(10); - goto again; - } - idbassert_s(0, string("socket bind error: ") + strerror(errno)); - //throw runtime_error(string("socket bind error: ") + strerror(errno)); - } - rc = listen(listenSock, 16); - idbassert_s(rc >= 0, string("socket listen error") + strerror(errno)); - //if (rc < 0) throw runtime_error(string("socket listen error") + strerror(errno)); - - return listenSock; -} - -QueryMessage getNextMsg(SockType fd) -{ - QueryMessage msg; - - try { - msg.defaultSchema = socketio::readString(fd); - msg.queryText = socketio::readString(fd); - msg.isValid = true; - } catch (runtime_error& rex) { - cerr << "re reading ctl msg: " << rex.what() << endl; - msg.queryText = ""; - } catch (...) { - cerr << "ex reading ctl msg" << endl; - msg.queryText = ""; - } - - return msg; -} - -StmtType guessStatementType(const string& stmt) -{ - typedef boost::tokenizer > tokenizer; - char_separator sep; - tokenizer tokens(stmt, sep); - tokenizer::iterator tok_iter = tokens.begin(); - string first_word; - first_word = *tok_iter; - algorithm::to_lower(first_word); - - if (first_word == "select") - return QUERY; - if (first_word == "create") - return CREATE; - if (first_word == "drop") - return DROP; - if (first_word == "show") - return SHOW; - - return UNKNOWN; -} - -struct ScopedCleaner -{ - ScopedCleaner(SockType fd=-1) : fFd(fd) { } -#ifdef _MSC_VER - ~ScopedCleaner() { if (fFd >= 0) shutdown(fFd, SHUT_RDWR); closesocket(fFd); } -#else - ~ScopedCleaner() { if (fFd >= 0) shutdown(fFd, SHUT_RDWR); close(fFd); } - -#endif - SockType fFd; -}; - -void ThreadFunc::run() -{ - QueryMessage m; - execplan::CalpontSelectExecutionPlan* csep=0; - MessageQueueClient* msgqcl; - - ScopedCleaner cleaner(fFd); - - uint32_t sid = 1; - sid = atomicops::atomicInc(&SystemSID); - - try { - m = getNextMsg(fFd); - - if (m.isValid) - { - DefaultSchema = m.defaultSchema; - StmtType st = guessStatementType(m.queryText); - switch (st) - { - case QUERY: - csep = parseQuery(m.queryText, sid); - //sendCSEP takes ownership of the ptr from parseQuery - msgqcl = sendCSEP(csep); - //processReturnedRows takes ownership of the ptr from sendCSEP - processReturnedRows(msgqcl, fFd); - break; - case CREATE: - processCreateStmt(m.queryText, sid); - break; - case DROP: - processDropStmt(m.queryText, sid); - break; - case SHOW: - { - ostringstream oss; - oss << "select calpontsys.systable.tablename from calpontsys.systable where " - "calpontsys.systable.schema='" << m.defaultSchema << "';"; - csep = parseQuery(oss.str(), sid); - msgqcl = sendCSEP(csep); - processReturnedRows(msgqcl, fFd); - break; - } - default: - throw runtime_error("couldn't guess the statement type"); - break; - } - } - } catch (std::exception& ex) { - socketio::writeString(fFd, ex.what()); - throw; //in a multi-threaded server this will simply cause this thread to exit - } catch (...) { - socketio::writeString(fFd, "internal query processing error"); - throw; - } -} - -} - -int main(int argc, char** argv) -{ - int c; - SockType listenSock; - short portNo; - - portNo = 0; - char* p = getenv("IDB_QFE_PORT"); - if (p && *p) - portNo = atoi(p); - - if (portNo <= 0) - portNo = 9198; -#ifdef _MSC_VER - listenSock = INVALID_SOCKET; -#else - listenSock = -1; -#endif - opterr = 0; - - while ((c = getopt(argc, argv, "p:")) != -1) - switch (c) - { - case 'p': - portNo = atoi(optarg); - break; - case '?': - default: - break; - } - - if (!serverInit()) - { - log("Could not initialize the QFE Server!"); - cerr << "Could not initialize the QFE Server!" << endl; - return 1; - } - - listenSock = initListenSock(portNo); - - SystemSID = 0; - - for (;;) - { -#ifdef _MSC_VER - SOCKET querySock = INVALID_SOCKET; - querySock = accept(listenSock, 0, 0); - idbassert_s(querySock != INVALID_SOCKET, string("socket accept error: ") + strerror(errno)); -#if 0 - uint32_t sndbufsize; - int sndbufsizelen=4; - int rc; - rc = getsockopt(querySock, SOL_SOCKET, SO_SNDBUF, (char*)&sndbufsize, &sndbufsizelen); - if (rc != SOCKET_ERROR) - { - if (sndbufsizelen == 4) - { - cerr << "getsockopt(): current SO_SNDBUF = " << sndbufsize << endl; - sndbufsize = atoi(getenv("SO_SNDBUF")); - cerr << "setsockopt(): setting SO_SNDBUF = " << sndbufsize << endl; - rc = setsockopt(querySock, SOL_SOCKET, SO_SNDBUF, (const char*)&sndbufsize, sndbufsizelen); - if (rc != SOCKET_ERROR) - { - getsockopt(querySock, SOL_SOCKET, SO_SNDBUF, (char*)&sndbufsize, &sndbufsizelen); - cerr << "getsockopt(): new SO_SNDBUF = " << sndbufsize << endl; - } - else - { - cerr << "setsockopt(): " << WSAGetLastError() << endl; - } - } - else - { - cerr << "getsockopt(): expecting 4 bytes, got " << sndbufsizelen << endl; - } - } - else - { - cerr << "getsockopt(): " << WSAGetLastError() << endl; - } -#endif - uint32_t sndbufsize = 512 * 1024; - setsockopt(querySock, SOL_SOCKET, SO_SNDBUF, (const char*)&sndbufsize, 4); -#else - int querySock = -1; - querySock = accept(listenSock, 0, 0); - idbassert_s(querySock >= 0, string("socket accept error: ") + strerror(errno)); -#endif - - //ThreadFunc now owns querySock and is responsible for cleaning it up - ThreadFunc tf(querySock); - -#ifdef SINGLE_THREADED - try { - tf.run(); - } catch (std::exception& ex) { - cerr << "ThreadFunc run threw an exception: " << ex.what() << endl; - } catch (...) { - cerr << "ThreadFunc run threw an exception" << endl; - } -#else - thread t(tf); -#endif - } - - return 0; -} -// vim:ts=4 sw=4: - diff --git a/tools/qfe/socketio.cpp b/tools/qfe/socketio.cpp deleted file mode 100644 index 2c0736a6..00000000 --- a/tools/qfe/socketio.cpp +++ /dev/null @@ -1,202 +0,0 @@ -#include -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#include -#include -#include -#include -#include -#else -#include -#include -#include -#include -#endif -#include -#include -using namespace std; - -#include -using namespace boost; - -#ifndef _MSC_VER -#include "config.h" -#endif - -#include "exceptclasses.h" - -#include "socketio.h" - -namespace qfe -{ -namespace socketio -{ - -#ifndef _MSC_VER -void readn(int fd, void* buf, const size_t wanted) -{ - size_t needed = wanted; - size_t sofar = 0; - char* p = static_cast(buf); - ssize_t rrc = -1; - pollfd fds[1]; - int en = 0; - - fds[0].fd = fd; - fds[0].events = POLLIN; - - while (wanted > sofar) - { - fds[0].revents = 0; - poll(fds, 1, -1); - errno = 0; - rrc = read(fd, (p + sofar), needed); - en = errno; - if (rrc < 0) - { - if (en == EAGAIN || en == EINTR || en == 512) - continue; - ostringstream oss; - oss << "qfe: readn: read() returned " << rrc << " (" << strerror(en) << ")"; - idbassert_s(0, oss.str()); - } - needed -= rrc; - sofar += rrc; - } -} - -size_t writen(int fd, const void* data, const size_t nbytes) -{ - size_t nleft; - ssize_t nwritten; - const char* bufp = static_cast(data); - nleft = nbytes; - - while (nleft > 0) - { - // the O_NONBLOCK flag is not set, this is a blocking I/O. - if ((nwritten = ::write(fd, bufp, nleft)) < 0) - { - if (errno == EINTR) - nwritten = 0; - else { - // save the error no first - int e = errno; - string errorMsg = "qfe: writen: write() error: "; - scoped_array buf(new char[80]); -#if STRERROR_R_CHAR_P - const char* p; - if ((p = strerror_r(e, buf.get(), 80)) != 0) - errorMsg += p; -#else - int p; - if ((p = strerror_r(e, buf.get(), 80)) == 0) - errorMsg += buf.get(); -#endif - idbassert_s(0, errorMsg); - } - } - nleft -= nwritten; - bufp += nwritten; - } - - return nbytes; -} -#else -const size_t MAX_RECV_BYTES=64*1024; -void reads(SOCKET fd, void* buf, const size_t wanted) -{ - size_t needed = wanted; - size_t sofar = 0; - char* p = reinterpret_cast(buf); - ssize_t rrc = -1; - pollfd fds[1]; - int en = 0; - - fds[0].fd = fd; - fds[0].events = POLLIN; - - while (wanted > sofar) - { - fds[0].revents = 0; - poll(fds, 1, -1); - errno = 0; - //Windows recv() can only read so much at a time... - int thisrecv = static_cast(std::min(needed, MAX_RECV_BYTES)); - rrc = ::recv(fd, (p + sofar), thisrecv, 0); - en = errno; - if (rrc < 0) - { - if (en == EAGAIN || en == EINTR) - continue; - ostringstream oss; - oss << "qfe: reads: read() returned " << rrc << " (" << strerror(en) << ")"; - idbassert_s(0, oss.str()); - } - needed -= rrc; - sofar += rrc; - } -} -size_t writes(SOCKET fd, const void* data, const size_t nbytes) -{ - size_t nleft; - ssize_t nwritten; - const char* bufp = static_cast(data); - nleft = nbytes; - - while (nleft > 0) - { - int thissend = static_cast(std::min(nleft, MAX_RECV_BYTES)); - nwritten = ::send(fd, bufp, thissend, 0); - int en = errno; - if (nwritten == SOCKET_ERROR) - { - int wsaerrno = WSAGetLastError(); - if (en == EINTR) - nwritten = 0; - else { - ostringstream oss; - oss << "qfe: writes: send() returned " << nwritten << " (WSA: " << wsaerrno << ")"; - idbassert_s(0, oss.str()); - } - } - nleft -= nwritten; - bufp += nwritten; - } - - return nbytes; -} -#endif - -uint32_t readNumber32(SockType fd) -{ - uint32_t np; - SockReadFcn(fd, &np, 4); - return np; -} - -string readString(SockType fd) -{ - string s; - uint32_t len = readNumber32(fd); - if (len > 0) - { - scoped_array buf(new char[len+1]); - SockReadFcn(fd, buf.get(), len); - buf[len] = 0; - s = buf.get(); - } - return s; -} - -void writeString(SockType fd, const string& data) -{ - uint32_t len=data.length(); - SockWriteFcn(fd, &len, 4); - SockWriteFcn(fd, data.c_str(), len); -} - -} //namespace qfe::socketio -} //namespace qfe diff --git a/tools/qfe/socketio.h b/tools/qfe/socketio.h deleted file mode 100644 index b673ab46..00000000 --- a/tools/qfe/socketio.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef QFE_SOCKETIO_H__ -#define QFE_SOCKETIO_H__ - -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#else -#include -#endif -#include -#include - -#include "socktype.h" - -namespace qfe -{ -namespace socketio -{ - -#ifndef _MSC_VER -void readn(int fd, void* buf, const size_t wanted); -size_t writen(int fd, const void* data, const size_t nbytes); -#else -void reads(SOCKET fd, void* buf, const size_t wanted); -size_t writes(SOCKET fd, const void* buf, const size_t len); -#endif -uint32_t readNumber32(SockType); -std::string readString(SockType); -void writeString(SockType, const std::string&); - -} //namespace qfe::socketio -} //namespace qfe - -#endif - diff --git a/tools/qfe/socktype.h b/tools/qfe/socktype.h deleted file mode 100644 index ba832699..00000000 --- a/tools/qfe/socktype.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef QFE_SOCKTYPE_H__ -#define QFE_SOCKTYPE_H__ - -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#endif - -#ifdef _MSC_VER -typedef SOCKET SockType; -#define SockReadFcn qfe::socketio::reads -#define SockWriteFcn qfe::socketio::writes -#else -typedef int SockType; -#define SockReadFcn qfe::socketio::readn -#define SockWriteFcn qfe::socketio::writen -#endif - -#endif - diff --git a/tools/rebuildEM/main.cpp b/tools/rebuildEM/main.cpp deleted file mode 100644 index 815d65a7..00000000 --- a/tools/rebuildEM/main.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/***************************************************************************** -* $Id: main.cpp 1739 2012-03-22 12:57:59Z pleblanc $ -* -*****************************************************************************/ -#include -#include -//#define _XOPEN_SOURCE 500 -#include -#include -#include -#include -#include -#include -using namespace std; -using namespace boost; - -#include "configcpp.h" -using namespace config; - -#include "extentmap.h" -using namespace BRM; - -#include "calpontsystemcatalog.h" -#include "dm.h" - -namespace -{ - -unsigned vflg = 0; -bool dflg = false; -string DBRoot; -string pattern; -unsigned extentSize; -ExtentMap em; - -void usage(const string& pname) -{ - cout << "usage: " << pname << " [-vdh]" << endl << - " rebuilds the extent map from the contents of the database file system." << endl << - " -v display verbose progress information. More v's, more debug" << endl << - " -d display what would be done--don't do it" << endl << - " -h display this help text" << endl; -} - -OID_t pname2OID(const string& fpath) -{ - dmFilePathArgs_t args; - char aBuff[10]; - char bBuff[10]; - char cBuff[10]; - char fnBuff[16]; - int rc; - OID_t oid; - - args.pDirA = aBuff; - args.pDirB = bBuff; - args.pDirC = cBuff; - args.pFName = fnBuff; - args.ALen = sizeof(aBuff); - args.BLen = sizeof(bBuff); - args.CLen = sizeof(cBuff); - args.FNLen = sizeof(fnBuff); - args.Arc = 0; - args.Brc = 0; - args.Crc = 0; - args.FNrc = 0; - - typedef tokenizer > tokenizer; - char_separator sep("/"); - tokenizer tokens(fpath, sep); - tokenizer::iterator tok_iter = tokens.begin(); - tokenizer::iterator end = tokens.end(); - typedef stack pcomps_t; - pcomps_t pcomps; - while (tok_iter != end) - { - pcomps.push(*tok_iter); - ++tok_iter; - } - - idbassert(pcomps.size() >= 4); - - string pcomp; - pcomp = pcomps.top(); - pcomps.pop(); - idbassert(pcomp.size() < 16); - strcpy(args.pFName, pcomp.c_str()); - pcomp = pcomps.top(); - pcomps.pop(); - idbassert(pcomp.size() < 10); - strcpy(args.pDirC, pcomp.c_str()); - pcomp = pcomps.top(); - pcomps.pop(); - idbassert(pcomp.size() < 10); - strcpy(args.pDirB, pcomp.c_str()); - pcomp = pcomps.top(); - pcomps.pop(); - idbassert(pcomp.size() < 10); - strcpy(args.pDirA, pcomp.c_str()); - - rc = dmFPath2Oid(&args, (UINT32*)&oid); - if (rc != 0) - { - oid = 0; - } - - return oid; -} - -bool isCalpontDBFile(const string& fpath) -{ - return (fnmatch(pattern.c_str(), fpath.c_str(), 0) == 0); -} - -int walkDB(const char* fp, const struct stat* sb, int typeflag, struct FTW* ftwbuf) -{ - string fpath(fp); - unsigned numExtents; - unsigned numBlocks; - - if (typeflag != FTW_F) - { - return FTW_CONTINUE; - } - - if (!isCalpontDBFile(fpath)) - { - if (vflg > 2) - { - cout << "Skipping non-Calpont DB file " << fpath << endl; - } - return FTW_CONTINUE; - } - - if (vflg) - { - cout << "Processing file " << fpath << endl; - numBlocks = (sb->st_size + (BLOCK_SIZE - 1)) / BLOCK_SIZE; - numExtents = (numBlocks + (extentSize - 1)) / extentSize; - if (vflg > 1) - { - cout << "File is " << numExtents << " extent" << (numExtents > 1 ? "s" : "") << - ", " << numBlocks << " block" << (numBlocks > 1 ? "s" : "") << - ", " << sb->st_size << " bytes, "; - } - } - - OID_t oid; - oid = pname2OID(fpath); - - if (vflg > 1) - { - cout << "OID is " << oid << ", "; - } - - if (oid <= 10) - { - if (vflg) - { - cout << endl << "OID " << oid << " is probably a VBBF and is being skipped" << endl; - } - return FTW_CONTINUE; - } - - HWM_t hwm; -#ifdef DELETE_FIRST - try - { - hwm = em.getHWM(oid); - } - catch (exception& ex) - { - if (vflg) - { - cout << endl << "There was no HWM for OID " << oid << - ", it is probably a VBBF and is being skipped: " << ex.what() << endl; - } - return FTW_CONTINUE; - } - catch (...) - { - if (vflg) - { - cout << endl << "There was no HWM for OID " << oid << - ", it is probably a VBBF and is being skipped" << endl; - } - return FTW_CONTINUE; - } -#else - hwm = numBlocks - 1; -#endif - - if (vflg > 1) - { - cout << "HWM is " << hwm << endl; - } - -#ifdef DELETE_FIRST - if (vflg > 1) - { - cout << "Deleting OID " << oid << " from Extent Map" << endl; - } - - if (!dflg) - { - em.deleteOID(oid); - em.confirmChanges(); - } -#endif - - vector lbids; - int allocdsize = 0; - - if (vflg > 1) - { - cout << "Creating extent for " << numBlocks << " blocks for OID " << oid << endl; - } - - if (!dflg) - { - em.createExtent(numBlocks, oid, lbids, allocdsize); - em.confirmChanges(); - } - - if (vflg > 1) - { - cout << "Created " << allocdsize << " LBIDs for OID " << oid << endl; - if (vflg > 2) - { - vector::iterator iter = lbids.begin(); - vector::iterator end = lbids.end(); - cout << "First LBIDs from each extent are "; - while (iter != end) - { - cout << *iter << ", "; - ++iter; - } - cout << endl; - } - } - - if (vflg > 1) - { - cout << "Setting OID " << oid << " HWM to " << hwm << endl; - } - - if (!dflg) - { - em.setHWM(oid, hwm); - em.confirmChanges(); - } - - return FTW_CONTINUE; -} - -} - -int main(int argc, char** argv) -{ - int c; - string pname(argv[0]); - - opterr = 0; - - while ((c = getopt(argc, argv, "vdh")) != EOF) - switch (c) - { - case 'v': - vflg++; - break; - case 'd': - dflg = true; - break; - case 'h': - case '?': - default: - usage(pname); - return (c == 'h' ? 0 : 1); - break; - } - - const Config* cf = Config::makeConfig(); - DBRoot = cf->getConfig("SystemConfig", "DBRoot"); - pattern = DBRoot + "/[0-9][0-9][0-9].dir/[0-9][0-9][0-9].dir/[0-9][0-9][0-9].dir/FILE[0-9][0-9][0-9].cdf"; - - if (vflg) - { - cout << "Using DBRoot " << DBRoot << endl; - } - - if (access(DBRoot.c_str(), X_OK) != 0) - { - cerr << "Could not scan DBRoot " << DBRoot << '!' << endl; - return 1; - } - - ExtentMap em; - extentSize = em.getExtentSize(); - - if (vflg) - { - cout << "System extent size is " << extentSize << " blocks" << endl; - } - - if (nftw(DBRoot.c_str(), walkDB, 64, FTW_PHYS|FTW_ACTIONRETVAL) != 0) - { - cerr << "Error processing files in DBRoot " << DBRoot << '!' << endl; - return 1; - } - - return 0; -} - diff --git a/tools/reserveStacks/create.sql b/tools/reserveStacks/create.sql deleted file mode 100644 index f1851d0a..00000000 --- a/tools/reserveStacks/create.sql +++ /dev/null @@ -1,73 +0,0 @@ -/* -Creates the stacks table used to track availability / usage of our development stacks. -*/ - -create database if not exists stacks; -use stacks; - -drop table if exists stacks; -drop table if exists stacksLog; -drop table if exists users; - -CREATE TABLE `stacks` ( - `stack` varchar(20) DEFAULT NULL, - `status` varchar(20) DEFAULT NULL, - `user` varchar(20) DEFAULT NULL, - `checkedout` datetime DEFAULT NULL, - `userModule` varchar(20) DEFAULT NULL, - `notes` varchar(200) default null, - `version` char(8) -) ENGINE=MyISAM; - -insert into stacks values -('demo', 'Available', null, null, 'srvdemo1', '1 UM x 3 PMs', null), -('srvswdev11', 'Available', null, null, 'srvswdev11', '1 UM/PM', null), -('qaftest2', 'Available', null, null, 'qaftest2', '1 UM/PM', null), -('devint1', 'Available', null, null, 'srvperf7', '2 UM/PMs', null), -('devint2', 'Available', null, null, 'srvperf2', '1 UM x 3 PMs (Shared Nothing)', null), -('devint3', 'Available', null, null, 'srvperf3', '1 UM/PM (Shared Nothing)', null), -('devsn1', 'Available', null, null, 'srvdevsn1', '1 UM x 3 PMs (Shared Nothing)', null), -('devsn2', 'Available', null, null, 'srvdevsn5', '1 UM x 2 PMs (Shared Nothing)', null), -('devsn3', 'Available', null, null, 'srvdevsn8', '2 UM/PMs (Shared Nothing)', null), -('srvalpha2', 'Available', null, null, 'srvalpha2', '1 UM/PM', null), -('alphad03', 'Available', null, null, 'srvalpha4', '1 UM x 4 PMs', null), -('qperfd01', 'Available', null, null, 'qaftest7', '1 UM X 5 PMs', null), -('srvprodtest1', 'Available', null, null, 'srvprodtest1', '1 UM/PM',null, null); - -CREATE TABLE stacksLog ( - stack varchar(20), - user varchar(20), - checkedOut datetime, - checkedIn datetime, - source varchar(20) /* php or commandLine */ -) ENGINE=MyISAM; - -CREATE TABLE `users` ( - `user` varchar(20) DEFAULT NULL, - `mailOnCheckouts` tinyint(1) DEFAULT NULL, - `mailOnCheckins` tinyint(1) DEFAULT NULL -) ENGINE=MyISAM; - -insert into users values -('bpaul', false, false), -('chao', false, false), -('dcathey', false, false), -('dhill', false, false), -('pleblanc', false, false), -('rdempsey', false, false), -('wweeks', false, false), -('xlou', false, false), -('zzhu', false, false); - -create table testResults ( - test varchar(20), - stack varchar(20), - version varchar(10), - rel varchar(10), - start datetime, - stop datetime, - buildDtm varchar(30), - total int, - status varchar(8), - failedTests varchar(1000) -) engine=MyISAM; diff --git a/tools/reserveStacks/index.html b/tools/reserveStacks/index.html deleted file mode 100644 index 6ee9dd2c..00000000 --- a/tools/reserveStacks/index.html +++ /dev/null @@ -1,38 +0,0 @@ - - -Automated Nightly Testing Logs - - -

Automated Nightly Testing Logs

-Auto OAM Results
-Nightly Results
-
-2.2 Build Results
-3.0 Build Results
-3.5 Build Results
-3.6 Build Results
-Trunk (4.0) Build Results
-
-3.5 Nightly Regression Test - devint3
-3.5 Performance Test - demo
-3.5 Nightly Regression Test - demo
-3.5 Perf Stack Tests - qaftest7 (Mon, Wed, Fri, Sat night builds)
-
-3.6 Nightly Regression Test - devint2
-3.6 Regression Test - srvalpha2
-3.6 ssb100 Import Validation - srvalpha2
-3.6 Nightly Regression Test - qaftest2
-3.6 TPCH Import Test - qaftest2
-3.6 Windows Regression Test - srvbldwin1
-
-Trunk (4.0) Nightly Regression Test - srvswdev11
-Trunk (4.0) Nightly Regression Test - srvalpha4 (Cloudera)
-Trunk (4.0) Nightly Regression Test - devint1 (Cloudera)
-Trunk (4.0) ssb100 Import Validation - devint1 (Cloudera)
-Trunk (4.0) Perf Stack Tests - qaftest7 (Sun, Tue, Thu, Fri, Sat night builds)
-Trunk (4.0) Nightly Regression Test - qaftest7
-Trunk Performance Test - demo (Sat, Sun)
-Trunk TPCH Import Test - qaftest2
-Trunk (4.0) Windows Regression Test - srvbldwin1
- - diff --git a/tools/reserveStacks/procs.sql b/tools/reserveStacks/procs.sql deleted file mode 100644 index f6f8fefc..00000000 --- a/tools/reserveStacks/procs.sql +++ /dev/null @@ -1,184 +0,0 @@ -/* -Creates stored procedures used to track availability and usage of our development stacks. -*/ - -use stacks; - -drop procedure if exists list_stacks; -drop procedure if exists list_users; -drop procedure if exists reserve_stack; -drop procedure if exists reserve_stack2; -drop procedure if exists release_stack; -drop procedure if exists subscribe_checkins; -drop procedure if exists subscribe_checkouts; - -DELIMITER // - -/* Lists the stacks and their availability. */ -create procedure list_stacks() -begin - select stack as Stack, - userModule as 'User Module', - status as Status, - ifnull(user, '') User, - ifnull(checkedout, '') 'Checked Out', - ifnull(timediff(now(), checkedout), '') Time, - ifnull(notes, '') Notes, - version Version - from stacks - order by stack; -end // - -/* Lists the users. */ -create procedure list_users() -begin - select * from users order by 1; -end // - -create procedure reserve_stack(in inStack varchar(20), in inUser varchar(20)) -begin - call reserve_stack2(inStack, inUser, 'commandLine'); -end // - -/* Reserves the given stack on behalf of the given user. */ -create procedure reserve_stack2(in inStack varchar(20), in inUser varchar(20), in inSource varchar(20)) -begin - declare cnt int default 0; - declare err varchar(100) default ''; - - /* Validate the stack exists. */ - select count(*) into cnt from stacks where upper(stack) = upper(inStack); - if cnt <> 1 then - set err = concat(inStack, ' is not a valid stack.'); - end if; - - /* Validate that the stack is not already checked out unless the user is nightly in which case he gets it regardless of it */ - /* being checked out. */ - if lower(inUser) <> 'nightly' and err = '' then - select count(*) into cnt from stacks where status='Available' and upper(stack) = upper(inStack); - if cnt <> 1 then - set err = concat(inStack, ' is not available.'); - end if; - end if; - - /* Do the check out. */ - if err = '' then - - update stacks - set status='Checked Out', user=inUser, checkedout=now() - where upper(stack)=upper(inStack) and (status='Available' or lower(inUser)='nightly'); - - insert into stacksLog values (inStack, inUser, now(), null, inSource); - - end if; - - if err <> '' then - select err Status; - else - select concat(inStack, ' successfully checked out by ', inUser, '.') Status; - end if; -end // - -/* Releases the given stack. Requires the passed user to be the one holding the reservation. */ -create procedure release_stack(in inStack varchar(20), in inUser varchar(20)) -begin - declare cnt int default 0; - declare err varchar(100) default ''; - - /* Validate the stack exists. */ - select count(*) into cnt from stacks where upper(stack) = upper(inStack); - if cnt <> 1 then - set err = concat(inStack, ' is not a valid stack.'); - end if; - - /* Validate that the stack is checked out by the user. */ - if err = '' then - select count(*) into cnt - from stacks - where status='Checked Out' and upper(stack) = upper(inStack) and upper(user) = upper(inUser); - - if cnt <> 1 then - set err = concat(inStack, ' is not checked out by ', inUser, '.'); - end if; - end if; - - /* Update the row to release_stack the stack. */ - if err = '' then - update stacks - set status='Available', user=null, checkedout=null - where upper(stack)=upper(inStack); - - update stacksLog - set checkedIn=now() - where upper(stack) = upper(inStack) and checkedIn is null and upper(user) = upper(inUser); - end if; - - if err <> '' then - select err Status; - else - select concat(inStack, ' successfully released.') Status; - end if; -end // - -create procedure subscribe_checkins(in inUser varchar(20), in inSubscribe bool) -begin - declare cnt int default 0; - declare err varchar(100) default ''; - - /* Validate user. */ - select count(*) into cnt from users where upper(user)=upper(inUser); - if cnt <> 1 then - set err = concat(inUser, ' is not a valid user.'); - end if; - - if err = '' then - if inSubscribe then - update users - set mailOnCheckins = true - where upper(user) = upper(inUser); - else - update users - set mailOnCheckins = false - where upper(user) = upper(inUser); - end if; - end if; - - if err <> '' then - select err Status; - else - select concat(inUser, ' checkin mail setting successfully set.') Status; - end if; -end // - -create procedure subscribe_checkouts(in inUser varchar(20), in inSubscribe bool) -begin - declare cnt int default 0; - declare err varchar(100) default ''; - - /* Validate user. */ - select count(*) into cnt from users where upper(user)=upper(inUser); - if cnt < 1 then - set err = concat(inUser, ' is not a valid user.'); - end if; - - if err = '' then - if inSubscribe then - update users - set mailOnCheckouts = true - where upper(user) = upper(inUser); - else - update users - set mailOnCheckouts= false - where upper(user) = upper(inUser); - end if; - end if; - - if err <> '' then - select err Status; - else - select concat(inUser, ' checkout mail setting successfully set.') Status; - end if; -end // - -DELIMITER ; - diff --git a/tools/reserveStacks/results.php b/tools/reserveStacks/results.php deleted file mode 100644 index f6720ce2..00000000 --- a/tools/reserveStacks/results.php +++ /dev/null @@ -1,21 +0,0 @@ - -<?php echo $_GET["title"]; ?> - -\n"; -$file = fopen($_GET["logFile"], "r") or exit("Unable to open file!"); -//Output a line of the file until the end is reached -while(!feof($file)) -{ - $line = fgets($file); - if (!preg_match('/ Failed *= 0/', $line)) - $line = preg_replace('/ Failed/', ' Failed', $line); - $line = preg_replace('/ Passed/', ' Passed', $line); - $line = preg_replace('/ Yellow/', ' Yellow', $line); - echo $line; -} -fclose($file); -echo "\n"; -?> - - diff --git a/tools/reserveStacks/stack b/tools/reserveStacks/stack deleted file mode 100755 index 12d54ae0..00000000 --- a/tools/reserveStacks/stack +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash - -# BP 09/16/2011 13:43 -# This script will give user to -# list all the calpont stacks -# reserve a calpont stack -# release a calpont stack -# Help to use a test stack without stepping each other. -# - -DB=stacks - -usage() -{ - echo "Usage:" >&2 - echo " ${0##*/} list" >&2 - echo " ${0##*/} reserve stackname who" >&2 - echo " ${0##*/} release stackname who" >&2 -} - -cmd="$1" -argc=$# - -if [ -z "$cmd" -o "$cmd" = "-h" ]; then - usage - exit 1 -fi - -if [ $(expr 'list' : "$cmd") -gt 0 ]; then - cmd=list - INST=$2 -elif [ $(expr 'reserve' : "$cmd") -gt 2 ]; then - cmd=reserve - INST=$4 -elif [ $(expr 'release' : "$cmd") -gt 2 ]; then - cmd=release - INST=$4 -fi -if [ -z "$INSTALLDIR" ]; then - INSTALLDIR="/usr/local/Calpont" - if [ $INST ]; then - INSTALLDIR=$INST - fi - export INSTALLDIR -fi - -if [ -z "$MYSQLCMD" ]; then - if [ -d "$INSTALLDIR/mysql" ]; then - # Linux. - MYSQLCMD="$INSTALLDIR/mysql/bin/mysql -h 10.100.4.51 -u root --database=$DB" - else - # Windows. - MYSQLCMD="$INSTALLDIR/bin/mysql -h 10.100.4.51 -u root --database=$DB" - fi - export MYSQLCMD -fi - -good=0 - -if [ "$cmd" = "list" ]; then - sql="call list_stacks()" - $MYSQLCMD -e "$sql" - good=1 -fi - -if [ "$cmd" = "reserve" -a $argc -ge 3 ]; then - sql="call reserve_stack('$2', '$3')" - $MYSQLCMD -e "$sql" - good=1 -fi - -if [ "$cmd" = "release" -a $argc -ge 3 ]; then - sql="call release_stack('$2', '$3')" - $MYSQLCMD -e "$sql" - good=1 -fi - -if [ $good -eq 0 ]; then - usage - exit 1 -fi - diff --git a/tools/reserveStacks/stack.php b/tools/reserveStacks/stack.php deleted file mode 100644 index a4182411..00000000 --- a/tools/reserveStacks/stack.php +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - -User: " />  -
- - -"/> -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  StackUser ModuleStatusUserChecked OutTimeStack NotesVersion
                              
- - - diff --git a/tools/reserveStacks/stackReservationResult.php b/tools/reserveStacks/stackReservationResult.php deleted file mode 100644 index 15740411..00000000 --- a/tools/reserveStacks/stackReservationResult.php +++ /dev/null @@ -1,45 +0,0 @@ - - - - -'; - } - else { - echo ''; - } - echo $line; - echo '

'; - } -} -mysql_close(); -echo 'Return to Stacks'; -?> - - - - diff --git a/tools/sendPlan/Makefile.am b/tools/sendPlan/Makefile.am deleted file mode 100644 index 604e0f2e..00000000 --- a/tools/sendPlan/Makefile.am +++ /dev/null @@ -1,22 +0,0 @@ -# $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = sendPlan -sendPlan_SOURCES = sendplan.cpp -sendPlan_CPPFLAGS = @idb_common_includes@ $(AM_CPPFLAGS) -sendPlan_LDFLAGS = @idb_common_ldflags@ @idb_exec_libs@ $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/sendPlan/sendplan.cpp b/tools/sendPlan/sendplan.cpp deleted file mode 100644 index 2bada6e2..00000000 --- a/tools/sendPlan/sendplan.cpp +++ /dev/null @@ -1,378 +0,0 @@ -// $Id: sendplan.cpp 1739 2012-03-22 12:57:59Z pleblanc $ -#include -#include -#include -#include -#include -#include -using namespace std; - -#include "bytestream.h" -using namespace messageqcpp; - -#include "calpontselectexecutionplan.h" -#include "sessionmanager.h" -using namespace execplan; - -#include "calpontsystemcatalog.h" -using namespace execplan; - -#include "tableband.h" -#include "joblist.h" -#include "joblistfactory.h" -using namespace joblist; - -#include "configcpp.h" -#include "errorcodes.h" - -#include "rowgroup.h" -using namespace rowgroup; - -typedef CalpontSystemCatalog::OID OID; - -namespace -{ - -bool vflg; - -void usage() -{ - cout << "usage: sendPlan [-v|h|d|B] [-t lvl] [-s sid] plan_file ..." << endl; - cout << "-v verbose output" << endl; - cout << "-t lvl set trace level to lvl" << endl; - cout << "-s sid set session id to sid" << endl; - cout << "-d display the query, but don't run it" << endl; - cout << "-B Bob's personal preferred output format" << endl; - cout << "-h display this help" << endl; -} - -double tm_diff(const struct timeval* st, const struct timeval* et) -{ - double sd = (double)st->tv_sec + (double)st->tv_usec / 1000000.0; - double ed = (double)et->tv_sec + (double)et->tv_usec / 1000000.0; - - return (ed - sd); -} - -//...Extract the stats string to be printed and the runtime start time from -//...the full stats string we receive from ExeMgr. -void parseStatsString( - const string& fullStatsString, - string& printStatsString, - struct timeval& queryRunStartTime) -{ - string::size_type delimPos = fullStatsString.find ('|'); - printStatsString = fullStatsString.substr(0,delimPos); - - istringstream startTimeString( fullStatsString.substr(delimPos+1) ); - startTimeString >> queryRunStartTime.tv_sec >> queryRunStartTime.tv_usec; -} - -} - -int main(int argc, char** argv) -{ - vflg = false; - uint32_t tlvl = 0; - bool dflg = false; - int c; - int32_t sid = -1; - bool Bflg = false; - - opterr = 0; - - while ((c = getopt(argc, argv, "vt:ds:Bh")) != EOF) - switch (c) - { - case 't': - tlvl = static_cast(strtoul(optarg, 0, 0)); - break; - case 'v': - vflg = true; - break; - case 'd': - dflg = true; - break; - case 's': - sid = static_cast(strtol(optarg, 0, 0)); - break; - case 'B': - Bflg = true; - break; - case 'h': - case '?': - default: - usage(); - return (c == 'h' ? 0 : 1); - break; - } - - if (dflg) - vflg = true; - - if ((argc - optind) < 1) - { - usage(); - return 1; - } - - ifstream inputf; - ByteStream bs; - ByteStream dbs; - ByteStream eoq; - ByteStream tbs; - ByteStream statsStream; - ByteStream::quadbyte q = 0; - eoq << q; - uint32_t sessionid; - time_t t; - SJLP jl; - DeliveredTableMap tm; - DeliveredTableMap::iterator iter; - DeliveredTableMap::iterator end; - CalpontSelectExecutionPlan csep; - struct timeval start_time; - struct timeval end_time; - - MessageQueueClient* mqc = 0; - - if (!dflg) - mqc = new MessageQueueClient("ExeMgr1"); - - if (sid == -1) - { - time(&t); - sessionid = static_cast(t); - } - else - { - sessionid = static_cast(sid); - } - sessionid &= 0x7fffffff; - logging::ErrorCodes errorCodes; - for ( ; optind < argc; optind++) - { - - inputf.open(argv[optind]); - - if (!inputf.good()) - { - cerr << "error opening plan stream " << argv[optind] << endl; - return 1; - } - - bs.reset(); - inputf >> bs; - - inputf.close(); - - csep.unserialize(bs); - - csep.sessionID(sessionid); - SessionManager sm; - csep.verID(sm.verID()); - - csep.traceFlags(0); - ResourceManager rm; - jl = JobListFactory::makeJobList(&csep, rm); - csep.traceFlags(tlvl); - - if (vflg) - { - if (dflg) - cout << endl << "Query:" << endl; - else - { - cout << endl << "Session: " << sessionid << - ", Sending Query"; - if (Bflg) - cout << " (" << argv[optind] << ')'; - cout << ':' << endl; - } - - if (!Bflg) - cout << csep.data() << endl << endl; - } - - if (dflg) - continue; - - try - { - dbs.reset(); - csep.serialize(dbs); - - gettimeofday(&start_time, 0); - - //try tuples first, but expect the worst... - bool expectTuples = false; - ByteStream tbs; - ByteStream::quadbyte tqb = 4; - tbs << tqb; - mqc->write(tbs); - - //send the CSEP - mqc->write(dbs); - - //read the response to the tuple request - tbs = mqc->read(); - idbassert(tbs.length() == 4); - tbs >> tqb; - if (tqb == 4) - expectTuples = true; - - if (!expectTuples) - cout << "Using TableBand I/F" << endl; - else - cout << "Using tuple I/F" << endl; - - tm = jl->deliveredTables(); - - iter = tm.begin(); - end = tm.end(); - - OID toid; - uint64_t rowTot; - bool reported = false; - bool needRGCtor = true; - while (iter != end) - { - toid = iter->first; - q = static_cast(toid); - tbs.reset(); - tbs << q; - mqc->write(tbs); - - ByteStream tbbs; - TableBand tb; - RowGroup rg; - rowTot = 0; - uint16_t status = 0; - TableBand::VBA::size_type rc; -ofstream out; - for (;;) - { - tbbs = mqc->read(); -#if 0 -cout << tbbs.length() << endl; -out.open("bs1.dat"); -idbassert(out.good()); -out << tbbs; -out.close(); - tbbs = mqc->read(); -cout << tbbs.length() << endl; -out.open("bs2.dat"); -idbassert(out.good()); -out << tbbs; -out.close(); - tbbs = mqc->read(); -cout << tbbs.length() << endl; -out.open("bs3.dat"); -idbassert(out.good()); -out << tbbs; -out.close(); -#endif - if(tbbs.length()) - { - if (!expectTuples) - tb.unserialize(tbbs); - else - { - if (needRGCtor) - { - rg.deserialize(tbbs); - needRGCtor = false; - tbbs = mqc->read(); - } - rg.setData((uint8_t*)tbbs.buf()); - } - } - else - {//@bug 1346 - if (!status) - status = logging::makeJobListErr; - break; - } - if (!expectTuples) - { - rc = tb.getRowCount(); - status = tb.getStatus(); - } - else - { - rc = rg.getRowCount(); - status = rg.getStatus(); - if (rc == 0) status = 0; - } - if (rc == 0) - break; - rowTot += rc; - } - BatchPrimitive* step = dynamic_cast( iter->second.get() ); - if (vflg && step) - { - cout << "For table " << step->tableName(); - if (!Bflg) - cout << " " << toid; - cout << ": read " << rowTot << " rows" << endl; - } - if (status && !reported) - { - cout << "### Query failed: " << errorCodes.errorString(status) << " Check crit.log\n"; - reported = true; - } - if (!step && !reported) - { - cout << "### Query failed: Did not return project BatchPrimitive. Check crit.log\n"; - reported = true; - } - - ++iter; - } - - if (vflg) - { - gettimeofday(&end_time, 0); - cout << "Query time: " << fixed << setprecision(1) << tm_diff(&start_time, &end_time) << - " secs" << endl; - - //...Ask for query stats through special table id of 3 - const OID TABLE_ID_TO_GET_QUERY_STATS = 3; - if (!Bflg) - cout << "Retrieving stats..." << endl; - toid = TABLE_ID_TO_GET_QUERY_STATS; - q = static_cast(toid); - statsStream.reset(); - statsStream << q; - mqc->write(statsStream); - - ByteStream bs_statsString; - bs_statsString = mqc->read(); - string statsString; - bs_statsString >> statsString; - - string printStatsString; - struct timeval startRunTime; - parseStatsString (statsString, printStatsString, startRunTime); - cout << printStatsString << "; QuerySetupTime-" << - tm_diff(&start_time, &startRunTime) << "secs" << endl; - } - //...Close this query/session - mqc->write(eoq); - jl.reset(); - } - catch(const exception& ex) - { - cout << "### SendPlan caught an exception: " << ex.what() << endl; - } - } -// jl.reset(); - CalpontSystemCatalog::removeCalpontSystemCatalog( sessionid ); - config::Config::deleteInstanceMap(); - - delete mqc; - - return 0; -} -// vim:ts=4 sw=4: - diff --git a/tools/setConfig/Makefile.am b/tools/setConfig/Makefile.am index 3663dcf6..96347219 100644 --- a/tools/setConfig/Makefile.am +++ b/tools/setConfig/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/setConfig/Makefile.in b/tools/setConfig/Makefile.in index 5b1d537e..e456fe66 100644 --- a/tools/setConfig/Makefile.in +++ b/tools/setConfig/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -61,9 +61,8 @@ subdir = tools/setConfig DIST_COMMON = $(dist_bin_SCRIPTS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -152,9 +151,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -196,7 +192,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -210,11 +205,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/setConfig/configxml.sh b/tools/setConfig/configxml.sh index 7b56b5f3..8ec70dff 100755 --- a/tools/setConfig/configxml.sh +++ b/tools/setConfig/configxml.sh @@ -3,75 +3,59 @@ # configxml set/get an entry in Calpont.xml file # # - -if [ -z "$INFINIDB_INSTALL_DIR" ]; then - test -f /etc/default/infinidb && . /etc/default/infinidb -fi - -if [ -z "$INFINIDB_INSTALL_DIR" ]; then - INFINIDB_INSTALL_DIR=/usr/local/Calpont -fi - -export INFINIDB_INSTALL_DIR=$INFINIDB_INSTALL_DIR - -InstallDir=$INFINIDB_INSTALL_DIR - -if [ $InstallDir != "/usr/local/Calpont" ]; then - export PATH=$InstallDir/bin:$InstallDir/mysql/bin:/bin:/usr/bin - export LD_LIBRARY_PATH=$InstallDir/lib:$InstallDir/mysql/lib/mysql -fi - case "$1" in setconfig) - if [ $# -ne 4 ]; then - echo $"Usage: $0 setconfig section variable set-value" - exit 1 + if test ! $4 ; then + echo $"Usage: $0 setconfig section variable set-value" + exit 1 fi - oldvalue=$($InstallDir/bin/getConfig $2 $3) + calbin=/usr/local/Calpont/bin + + oldvalue=`$calbin/getConfig $2 $3` - #if [ -z $oldvalue ]; then - # echo "$2 / $3 not found in Calpont.xml" - # exit 1 - #fi + if [ -z $oldvalue ]; then + echo "$2 / $3 not found in Calpont.xml" + exit 1 + fi echo "Old value of $2 / $3 is $oldvalue" - calxml=$InstallDir/etc/Calpont.xml + calext=/usr/local/Calpont/etc/Calpont.xml - seconds=$(date +%s) - cp $calxml $calxml.$seconds + seconds=`date +%s` + cp $calext $calext.$seconds echo - echo "$calxml backed up to $calxml.$seconds" + echo $"$calext backed up to $calext.$seconds" echo - oldvalue=$($InstallDir/bin/getConfig $2 $3) + calbin=/usr/local/Calpont/bin + + oldvalue=`$calbin/getConfig $2 $3` echo "Old value of $2 / $3 is $oldvalue" - if ( [ $# -eq 4 ] && [ -z $4 ] ); then - $InstallDir/bin/setConfig $2 $3 "" - else - $InstallDir/bin/setConfig $2 $3 $4 - fi + $calbin/setConfig $2 $3 $4 - newvalue=$($InstallDir/bin/getConfig $2 $3) + newvalue=`$calbin/getConfig $2 $3` echo "$2 / $3 now set to $newvalue" ;; getconfig) if test ! $3 ; then - echo $"Usage: $0 getconfig section variable" - exit 1 + echo $"Usage: $0 getconfig section variable" + exit 1 fi - value=$($InstallDir/bin/getConfig $2 $3) + calbin=/usr/local/Calpont/bin + + value=`$calbin/getConfig $2 $3` if [ -z $value ]; then - echo "$2 / $3 not found in Calpont.xml" - exit 1 + echo "$2 / $3 not found in Calpont.xml" + exit 1 fi echo "Current value of $2 / $3 is $value" @@ -82,5 +66,3 @@ case "$1" in exit 1 esac -# vim:ts=4 sw=4: - diff --git a/tools/setConfig/setConfig.vcxproj b/tools/setConfig/setConfig.vcxproj deleted file mode 100644 index cc1aa5a3..00000000 --- a/tools/setConfig/setConfig.vcxproj +++ /dev/null @@ -1,314 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {13E96B71-0854-4EA5-A7ED-0950AE10C858} - setConfig - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - false - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\utils\idbdatafile;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4996;4244;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4996;4244;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4996;4244;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - true - false - 4996;4244;%(DisableSpecificWarnings) - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - UseLinkTimeCodeGeneration - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - - - - \ No newline at end of file diff --git a/tools/setConfig/setConfig.vcxproj.filters b/tools/setConfig/setConfig.vcxproj.filters deleted file mode 100644 index a5aaa3f2..00000000 --- a/tools/setConfig/setConfig.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/tools/snconvert/snconvert.pl b/tools/snconvert/snconvert.pl deleted file mode 100755 index f68aa2f6..00000000 --- a/tools/snconvert/snconvert.pl +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/perl -w -s - - -################################### -# Control parameters -################################### - -# location of the data files to process -$srcDir=""; -$srcFileName=""; - -if ( $#ARGV>-1 ) -{ - $srcDir = $ARGV[0]; - $srcFileName= $ARGV[1]; - print "\n\nCLA $srcDir $srcFileName\n\n"; -} -else -{ - $srcDir = "."; - $srcFileName = "FILE000.cdf"; -} - -# full path of the data file -$srcFile = $srcDir . $srcFileName; - -# name of the new file/extent file -$newFileName = $srcFileName . '_'; - -# get current directory -$currDir = `pwd`; -chomp $currDir; - -# number of file system files -$fsFileCnt=8; - -# once file data has been reorganized they will be moved -# to these locations. -@pmDest = ( - "root\@srvswdev2\:\/tmp", - "root\@srvswdev2\:\/tmp", - "root\@srvswdev2\:\/tmp", - "root\@srvswdev2\:\/tmp" -); - -# split column file into seperate extent files -@sysCmd = ("split", "-d", "-b", "8m", "$srcFile", "$newFileName"); -print "@sysCmd\n"; -print "Starting split . . . .\n"; -system(@sysCmd); -print "Split complete.\n"; - -# get names of extent files -@files = <$newFileName*>; - -$extentCnt = @files; -$i=0; - -# list of extent files to place into a file system file -@extList = (""); - -#list of file system files -@fsFiles = (""); - -#init file lists -while ( $i<$fsFileCnt ) -{ - $fsFiles[$i]="fsFile" . $i; - $extList[$i]=""; - $i++; -} - -# organize extents into files per file systems -#in this case there are 8 file systems -$i=0; -$j=0; -while ( $i<$extentCnt ) -{ - $j=0; - while ( $j<$fsFileCnt && $i<$extentCnt ) - { - $extList[$j] = $extList[$j] . " " . $files[$i]; - $i++; - $j++; - } -} - -$i=0; -while ( $i < $fsFileCnt ) -{ - print "List $i: $extList[$i]\n"; - $Cmd="cat $extList[$i] >> $fsFiles[$i]"; - print "concat $i: $Cmd\n"; - `$Cmd`; - $i++; -} - -# copy the file system files to the appropriate PM -# in this case there are 4 PMs -$pmCnt=4; -$i=0; -$j=0; -@pmFiles =(""); - -while ( $i<$fsFileCnt ) -{ - $j=0; - while ( $j < $pmCnt && $i < $fsFileCnt) - { -# $pmFiles[$j] = $pmFiles[$j] . " " . $fsFiles[$i++]; - $Cmd = "./remote_scp_put.sh $fsFiles[$i++] $pmDest[$j++] Calpont1"; - print "scp command: $Cmd\n"; - `$Cmd`; - } -} - -#$j=0; -#while ( $j < $pmCnt ) -#{ -# print "pmFileList $j : $pmFiles[$j]\n"; -# $j++; -#} -# -#$j=0; -#while ( $j < $pmCnt ) -#{ -# $Cmd = "scp $pmFiles[$j] $pmDest[$j]"; -# print "scp command: $Cmd\n"; -# system($Cmd); -# $j++; -#} - diff --git a/tools/updateGenii/listRepos.pl b/tools/updateGenii/listRepos.pl deleted file mode 100755 index 62954280..00000000 --- a/tools/updateGenii/listRepos.pl +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/perl -w -# -# $Id: listRepos.pl 192 2007-05-14 14:42:49Z rdempsey $ -# - -use File::Basename; - -$reporoot = '/Calpont/repos/genii/*'; - -$opt_a = 0; -if (defined($ENV{'QUERY_STRING'})) -{ - $opt_a = 1 if ($ENV{'QUERY_STRING'} eq "All"); -} - -sub findRepos -{ - my ($root) = @_; - - my @repolist = (); - - my @repodirs = glob($root); - - my $dir; - - for $dir (@repodirs) - { - $dir = basename($dir); - - if ($opt_a == 0) - { - next if ($dir eq "net-snmp"); - # deprecated projects - next if ($dir eq "altera"); - next if ($dir eq "diskmgr"); - next if ($dir eq "emulator"); - next if ($dir eq "message"); - next if ($dir eq "sqlengine"); - } - next if ($dir eq "demo"); - next if ($dir eq "doc"); - - push(@repolist, $dir); - } - - return @repolist; -} - -@repos = findRepos($reporoot); - -print 'content-type: text/plain', "\r\n"; -print "\r\n"; - -foreach $repo (@repos) -{ - print $repo, "\r\n"; -} - diff --git a/tools/updateGenii/test.dat b/tools/updateGenii/test.dat deleted file mode 100644 index 2690a2a0..00000000 --- a/tools/updateGenii/test.dat +++ /dev/null @@ -1,14 +0,0 @@ -A OID3046.dat -? brmtest/brmtest -? dumpcol/dumpcol -? fixdate/fixdate.cdf -? fixdate/f1.cdf -? fixdate/fixdate -? evalcol/evalcol -? editem/editem -? dbbuilder/dbbuilder -? oid2file/oid2file -M Makefile -G updateGenii -C updateGenii/updateGenii.pl -G updateGenii/listRepos.pl diff --git a/tools/updateGenii/updateGenii.pl b/tools/updateGenii/updateGenii.pl deleted file mode 100755 index 7766a162..00000000 --- a/tools/updateGenii/updateGenii.pl +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/perl -w -# -# $Id: updateGenii.pl 1265 2010-09-17 12:25:42Z rdempsey $ -# - -use Getopt::Std; - -sub usage -{ - my $msg = <<'EOD' -usage: updateGenii.pl [-h] [-b|-t branch/tag] [-r root] [-a] - -h Display this help - -b branch Update a branch wc - -t tag Update a tag wc - -r root Use root as the starting point rather than $HOME - -a Update wc for all svn projects, even deprecated ones -EOD -; - print "$msg\n"; -} - -sub findRepos -{ - my @repolist = (); - my $all = ''; - - $all = '?All' if ($opt_a); - - open(FH, 'curl -s http://srvengcm1.calpont.com/cgi-bin/listRepos.pl' . $all . ' |'); - while () - { - $_ =~ s/[\r\n]*$//; - push(@repolist, $_); - } - close(FH); - - return @repolist; -} - -if (!getopts('hab:r:t:')) -{ - usage(); - exit 1; -} - -if (defined($opt_h)) -{ - $opt_h = 1; - usage(); - exit 0; -} - -$opt_a = 1 if (defined($opt_a)); - -$prjroot = 'genii'; -$prjroot = $opt_r if (defined($opt_r)); -$prjroot = $opt_b if (defined($opt_b)); -$prjroot = $opt_t if (defined($opt_t)); - -if (!defined($opt_b) && !defined($opt_t) && $#ARGV >= 0) -{ - usage(); - exit 1; -} - -if (defined($opt_b) || defined($opt_t)) -{ - $cmd = 'svn list http://srvengcm1.calpont.com/svn/genii/dbcon/'; - if (defined($opt_b)) - { - $cmd = $cmd . 'branches'; - } - else - { - $cmd = $cmd . 'tags'; - } - $listcmd = $cmd; - $tmp = $prjroot; - $tmp =~ s/\./\\./g; - $cmd = $cmd . " 2>/dev/null | egrep '^" . $tmp . "/' | wc -l"; - $brcnt = `$cmd`; - if ($brcnt != 1) - { - print "branch/tag $prjroot not found. Choices are:\n"; - $listcmd = $listcmd . ' | sed s,/\$,,'; - system($listcmd); - exit 1; - } -} - -chdir $ENV{'HOME'} or die; - -$destDir = $prjroot; -if ((defined($opt_b) || defined($opt_t)) && defined($opt_r)) -{ - $destDir = $opt_r; -} -mkdir $destDir if (! -d $destDir); - -chdir $destDir or die; - -@repos = findRepos(); -@mergelines = (); -@conflictlines = (); - -foreach $repo (@repos) -{ - #print $repo, "\n"; next; - if (-d $repo . '/.svn') - { - print $repo, ": \n"; - chdir $repo or die; - open FH, 'svn update |'; - @svnlines = ; - close FH; - foreach $line (@svnlines) - { - print "$line"; - if ($line =~ /^C/) - { - push(@conflictlines, $repo . ": " . $line); - } - elsif ($line =~ /^G/) - { - push(@mergelines, $repo . ": " . $line); - } - } - - chdir '..' or die; - } - else - { - print $repo, ": \n"; - if (defined($opt_b)) - { - $svncmd = 'svn checkout http://srvengcm1.calpont.com/svn/genii/' . $repo . '/branches/' . - $prjroot . ' ' . $repo; - } - elsif (defined($opt_t)) - { - $svncmd = 'svn checkout http://srvengcm1.calpont.com/svn/genii/' . $repo . '/tags/' . - $prjroot . ' ' . $repo; - } - else - { - $svncmd = 'svn checkout http://srvengcm1.calpont.com/svn/genii/' . $repo . '/trunk/' . ' ' . - $repo; - } - system $svncmd; - } -} - -unlink 'merges.txt'; -unlink 'conflicts.txt'; - -if ($#mergelines >= 0) -{ - print "\n** Warning! merges:\n"; - foreach $merge (@mergelines) - { - print "$merge"; - } - open FH, ">merges.txt"; - print FH @mergelines; - close FH; - print "This information has been saved in merges.txt\n"; -} - -if ($#conflictlines >= 0) -{ - print "\n** Warning! conflicts:\n"; - foreach $conflict (@conflictlines) - { - print "$conflict"; - } - open FH, ">conflicts.txt"; - print FH @conflictlines; - close FH; - print "This information has been saved in conflicts.txt\n"; -} - -if (! -e 'Makefile') -{ - system './build/bootstrap'; -} - diff --git a/tools/valprint/valprint.cpp b/tools/valprint/valprint.cpp deleted file mode 100644 index 7425bfce..00000000 --- a/tools/valprint/valprint.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (C) 2014 InfiniDB, Inc. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301, USA. */ - -// $Id: valprint.cpp 2101 2013-01-21 14:12:52Z rdempsey $ - -#include -#include -using namespace std; - -#include "configcpp.h" -using namespace config; - -int main(int argc, char** argv) -{ - int c; - opterr = 0; - while ((c = getopt(argc, argv, "")) != EOF) - switch (c) - { - case '?': - default: - break; - } - - string s; - for (int i = optind; i < argc; i++) - { - s = argv[i]; - cout << s << " = " << Config::fromText(s) << endl; - } - - return 0; -} - diff --git a/tools/vbgen/Makefile.am b/tools/vbgen/Makefile.am deleted file mode 100644 index 211b9968..00000000 --- a/tools/vbgen/Makefile.am +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (C) 2014 InfiniDB, Inc. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id$ -## Process this file with automake to produce Makefile.in - -AM_CPPFLAGS = $(idb_cppflags) -AM_CFLAGS = $(idb_cflags) -AM_CXXFLAGS = $(idb_cxxflags) -AM_LDFLAGS = $(idb_ldflags) -bin_PROGRAMS = vbgen -vbgen_SOURCES = vbgen.cpp myrand.cpp -vbgen_CPPFLAGS = $(AM_CPPFLAGS) -vbgen_LDFLAGS = $(AM_LDFLAGS) - -test: - -coverage: - -leakcheck: - -docs: - -bootstrap: install-data-am - diff --git a/tools/vbgen/myrand.cpp b/tools/vbgen/myrand.cpp deleted file mode 100644 index 17f7b257..00000000 --- a/tools/vbgen/myrand.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "myrand.h" - -#include -#include -#include -#include -#include -using namespace std; - -namespace myrand -{ - -MyRand::MyRand(int min, int max) : - fMin(min), - fMax(max) -{ - if (fMax < fMin) throw range_error("max - -namespace myrand -{ -class MyRand -{ -public: - explicit MyRand(int min, int max); - ~MyRand() { } - - int generate() - { return (fMin + (int)((double)(fMax - fMin + 1) * (rand_r(&fSeed) / (RAND_MAX + 1.0)))); } - - int operator()() { return generate(); } - -protected: - -private: - //defaults okay (I guess) - //MyRand(const MyRand& rhs); - //MyRand& operator=(const MyRand& rhs); - - unsigned int fSeed; - int fMin; - int fMax; -}; -} - -#endif -// vim:ts=4 sw=4: - diff --git a/tools/vbgen/vbgen.cpp b/tools/vbgen/vbgen.cpp deleted file mode 100644 index 9c24b3ab..00000000 --- a/tools/vbgen/vbgen.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include -#include -#include -#include -using namespace std; - -#include "myrand.h" -using namespace myrand; - -namespace -{ -class PrintIt -{ -public: - PrintIt(ostream& os) : fOs(os) - { - fOs.fill('0'); - fOs.flags(ios::hex); - } - ~PrintIt() { } - - void operator()(const int i) const - { - unsigned u = static_cast(i & 0xff); - fOs << setw(2) << u; - } - -private: - //Defaults okay - //PrintIt(const PrintIt& rhs); - //PrintIt& operator=(const PrintIt& rhs); - - ostream& fOs; -}; -} - -int main(int argc, char** argv) -{ - int c; - unsigned long long numRows = 20000000; - - opterr = 0; - - while ((c = getopt(argc, argv, "r:h")) != -1) - switch (c) - { - case 'r': - numRows = strtoull(optarg, 0, 0); - break; - case 'h': - case '?': - default: - break; - } - - MyRand mrwidth(100, 800); - - for (unsigned long long i = 0; i < numRows; i++) - { - int w = mrwidth.generate(); - vector vi(w); - generate(vi.begin(), vi.end(), MyRand(0, 255)); - cout << "0|"; - for_each(vi.begin(), vi.end(), PrintIt(cout)); - cout << '|' << endl; - } - - return 0; -} - diff --git a/tools/viewtablelock/Makefile.am b/tools/viewtablelock/Makefile.am index ba14bc44..d8fc8277 100644 --- a/tools/viewtablelock/Makefile.am +++ b/tools/viewtablelock/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ ## Process this file with automake to produce Makefile.in diff --git a/tools/viewtablelock/Makefile.in b/tools/viewtablelock/Makefile.in index 6bb172ef..d5f02858 100644 --- a/tools/viewtablelock/Makefile.in +++ b/tools/viewtablelock/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id: Makefile.am 333 2009-04-03 20:35:04Z rdempsey $ @@ -59,9 +59,8 @@ bin_PROGRAMS = viewtablelock$(EXEEXT) subdir = tools/viewtablelock DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -148,9 +147,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -192,7 +188,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -206,11 +201,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ diff --git a/tools/viewtablelock/viewtablelock.cpp b/tools/viewtablelock/viewtablelock.cpp index d1ed466a..dc942fc0 100644 --- a/tools/viewtablelock/viewtablelock.cpp +++ b/tools/viewtablelock/viewtablelock.cpp @@ -16,7 +16,7 @@ MA 02110-1301, USA. */ /* -* $Id: viewtablelock.cpp 2101 2013-01-21 14:12:52Z rdempsey $ +* $Id: viewtablelock.cpp 1854 2012-07-09 18:11:39Z dcathey $ */ #include diff --git a/tools/viewtablelock/viewtablelock.vcxproj b/tools/viewtablelock/viewtablelock.vcxproj deleted file mode 100644 index 22fcf3bf..00000000 --- a/tools/viewtablelock/viewtablelock.vcxproj +++ /dev/null @@ -1,312 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {DC26E3DB-B3E6-469E-869D-3FA5FC026C20} - viewtablelock - - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - true - - - Application - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Debug;%(AdditionalLibraryDirectories) - true - MachineX86 - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Debug;$(SolutionDir)..\..\x64\Debug;%(AdditionalLibraryDirectories) - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4996;4244 - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4996;4244 - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;C:$(SolutionDir)..\..x64\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX64 - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4996;4244 - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0\lib32;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include\lib32;C:\InfiniDB\Release;%(AdditionalLibraryDirectories) - true - true - true - MachineX86 - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _SCL_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - false - 4996;4244 - - - ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies) - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\win32\Release;$(SolutionDir)..\..\x64\EnterpriseRelease;%(AdditionalLibraryDirectories) - false - true - true - MachineX64 - - - - - - - - {ffcce773-27fa-4f4d-9e28-2208be6348da} - - - {cba13ef7-eca1-42f4-8ce2-9e18e24dcde2} - - - {8f7c9b67-639c-468f-8c5a-eb5f2e944e64} - - - {b44be805-2019-4fcb-b213-45f1d7a73ccd} - - - {004899a2-3cab-4796-b030-34a20ac285c9} - - - {0b72a604-0755-4e2c-b74b-c93564847114} - - - {c543c9a1-b4e0-4bad-9fc2-2afeea952fc5} - - - {ab342a0e-604e-4bbc-b43e-08df3fa37f9b} - - - {9ae60d66-99f6-4ccb-902d-3814a12ae0a9} - - - {4c8231d7-7a87-4650-aa9c-d7650c1d03ee} - - - {07230df5-10e9-469e-8075-c0978c0460ad} - - - {226d1f60-1e33-401b-a333-d583af69b86e} - - - {599e3c29-63ba-4f25-aeae-bf413ad93312} - - - {054cfc82-a54e-4ea5-8ce7-1281d2ed9ece} - - - {5362725e-bb90-44a3-9d13-3de9b5041ad2} - - - {b62b74b4-4621-4cf2-ac06-fb84d9cca66f} - - - {021a7045-6334-478f-9a4c-79f8200b504a} - - - {4f0851d3-b782-4f12-b748-73efa2da586b} - - - {a13e870a-7a9e-4027-8e17-204398225361} - - - - - - \ No newline at end of file diff --git a/tools/viewtablelock/viewtablelock.vcxproj.filters b/tools/viewtablelock/viewtablelock.vcxproj.filters deleted file mode 100644 index 5516c1d2..00000000 --- a/tools/viewtablelock/viewtablelock.vcxproj.filters +++ /dev/null @@ -1,22 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - \ No newline at end of file diff --git a/utils/Makefile.am b/utils/Makefile.am index 73b8f140..352c805b 100644 --- a/utils/Makefile.am +++ b/utils/Makefile.am @@ -1,27 +1,23 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. - -# $Id: Makefile.am 4038 2013-08-07 14:02:48Z rdempsey $ - -SUBDIRS = boost_idb startup common configcpp loggingcpp messageqcpp \ - threadpool rwlock dataconvert joiner rowgroup cacheutils \ - funcexp udfsdk compress batchloader ddlcleanup \ - mysqlcl_idb querystats jemalloc windowfunction idbdatafile \ - idbhdfs winport thrift querytele +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +# $Id: Makefile.am 1310 2009-10-15 14:00:24Z rdempsey $ + +SUBDIRS = boost_idb startup common configcpp loggingcpp messageqcpp threadpool rwlock dataconvert joiner rowgroup cacheutils multicast funcexp compress batchloader ddlcleanup mysqlcl_idb querystats test: diff --git a/utils/Makefile.in b/utils/Makefile.in index 1120c05c..c584c80b 100644 --- a/utils/Makefile.in +++ b/utils/Makefile.in @@ -14,24 +14,24 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. -# $Id: Makefile.am 4038 2013-08-07 14:02:48Z rdempsey $ +# $Id: Makefile.am 1310 2009-10-15 14:00:24Z rdempsey $ srcdir = @srcdir@ top_srcdir = @top_srcdir@ VPATH = @srcdir@ @@ -57,9 +57,8 @@ host_triplet = @host@ subdir = utils DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -136,9 +135,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -180,7 +176,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -194,11 +189,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -209,12 +199,7 @@ sharedstatedir = @sharedstatedir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ toolsdir = @toolsdir@ -SUBDIRS = boost_idb startup common configcpp loggingcpp messageqcpp \ - threadpool rwlock dataconvert joiner rowgroup cacheutils \ - funcexp udfsdk compress batchloader ddlcleanup \ - mysqlcl_idb querystats jemalloc windowfunction idbdatafile \ - idbhdfs winport thrift querytele - +SUBDIRS = boost_idb startup common configcpp loggingcpp messageqcpp threadpool rwlock dataconvert joiner rowgroup cacheutils multicast funcexp compress batchloader ddlcleanup mysqlcl_idb querystats all: all-recursive .SUFFIXES: diff --git a/utils/autoconf/INSTALL b/utils/autoconf/INSTALL index 0f12f143..05699fc4 100644 --- a/utils/autoconf/INSTALL +++ b/utils/autoconf/INSTALL @@ -4,46 +4,49 @@ Installation Instructions Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005 Free Software Foundation, Inc. -Copyright (C) 2014 InfiniDB, Inc. +Copyright (C) 2009-2012 Calpont Corp. This file is free documentation; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. -InfiniDB, Inc. also gives unlimited permission to copy, distribute and +Calpont Corp. also gives unlimited permission to copy, distribute and modify it. -Basic Installation from source +Basic Installation from Source ============================== -**** InfiniDB source build instructions **** +**** Calpont infinidb source build instructions **** -Consult the generic installation instructions +Patch MySQL with Calpont extensions and get it built. +You need to determine the root directory for the MySQL installation. +A suggestion is $HOME. Now we can build MySQL/Calpont: + +./build_mysql.sh --prefix=$HOME + +Now we can build infinidb. Consult the generic installation instructions that follow for detailed information. The short version is: -cd $HOME -git clone http://github.com/infinidb/mysql -git clone http://github.com/infinidb/infinidb --- or -- -tar -zxf -cd mysql -./configure --prefix=$HOME -make -make install -cd ../infinidb ./configure --prefix=$HOME make make install -This will create a directory called Calpont in $HOME which conatins +This will create a directory called Calpont in $HOME which contains all the software you need. -Install the InfiniDB software into /usr/local (for example) by copying +Install the Calpont software into /usr/local (for example) by copying the entire Calpont directory tree there. +If you would like to do an RPM install, you can build RPM's with: +./make_rpms + After untaring the sofware or installing the RPM's, setup the software -to run (this script needs to run with root privileges). Check the Installation -Guide for addition details on using postConfigure: -/usr/local/Calpont/bin/postConfigure +to run (this script needs to run with root privileges): +/usr/local/Calpont/bin/install-infinidb.sh + +Start the database: +service infinidb start +or: +/usr/local/Calpont/bin/infinidb start Setup some aliases: . /usr/local/Calpont/bin/calpontAlias @@ -76,10 +79,8 @@ And check the import: calpontmysql calpont select * from caltest; - That's it. Enjoy. - These are generic installation instructions. The `configure' shell script attempts to guess correct values for diff --git a/utils/autoconf/Makefile.am b/utils/autoconf/Makefile.am index 055f5bb8..efdf8f0c 100644 --- a/utils/autoconf/Makefile.am +++ b/utils/autoconf/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ @@ -39,13 +39,12 @@ all-local: bootstrap $(MAKE) -C ddlpackage install; \ $(MAKE) -C ddlpackageproc install; \ $(MAKE) -C dmlpackage install; \ - $(MAKE) -C dmlpackageproc install + $(MAKE) -C dmlpackageproc install; \ + $(MAKE) -C sm install cd dbcon && $(MAKE) && $(MAKE) install cd exemgr && $(MAKE) && $(MAKE) install cd ddlproc && $(MAKE) && $(MAKE) install cd dmlproc && $(MAKE) && $(MAKE) install - cd procmon && $(MAKE) && $(MAKE) install - cd procmgr && $(MAKE) && $(MAKE) install cd oamapps && $(MAKE) && $(MAKE) install cd decomsvr && $(MAKE) && $(MAKE) install cd primitives && $(MAKE) && $(MAKE) install @@ -68,18 +67,24 @@ leakcheck: docs: bootstrap: - ./build/genVersion.sh --prefix=$(prefix) + ./build/genVersion.sh --prefix=@prefix@/Calpont for subdir in dbcon ddlproc dmlproc exemgr mysql net-snmp oam \ - oamapps decomsvr primitives procmgr procmon qa snmpd tools utils versioning \ + oamapps decomsvr primitives snmpd tools utils versioning \ writeengine ; do \ if test -f $$subdir/Makefile; then \ $(MAKE) BOOTSTRAP=1 -C $$subdir bootstrap || exit $$?; \ fi; \ done +install: install-data-am + $(INSTALL) -m0644 COPYING @prefix@/Calpont + $(INSTALL) -m0644 INSTALL @prefix@/Calpont + $(INSTALL) -m0644 README @prefix@/Calpont + $(INSTALL) -m0644 build/releasenum @prefix@/Calpont + clean: clean-am for subdir in dbcon ddlproc dmlproc exemgr mysql net-snmp oam \ - oamapps decomsvr primitives procmgr procmon qa snmpd tools utils versioning \ + oamapps decomsvr primitives snmpd tools utils versioning \ writeengine ; do \ if test -f $$subdir/Makefile; then \ $(MAKE) BOOTSTRAP=1 -C $$subdir clean || exit $$?; \ diff --git a/utils/autoconf/README b/utils/autoconf/README index 2aa1663a..5610d453 100644 --- a/utils/autoconf/README +++ b/utils/autoconf/README @@ -2,144 +2,39 @@ To build the software from source, consult the file INSTALL. Brief Install Instructions: -1. Install the 3 Calpont InfiniDB RPMs. -2. Install and start the software, run: /usr/local/Calpont/bin/postConfigure -3. Setup some aliases: . /usr/local/Calpont/bin/calpontAlias -4. Connect to MySQL: idbmysql -5. Try the test in step 12 below +1. Install the 3 Calpont infinidb RPMs or unpack the binary tar file into /usr/local. +2. Setup the software to run: /usr/local/Calpont/bin/install-infinidb.sh +3. Start the Database: service infinidb start + or /usr/local/Calpont/bin/infinidb start +4. Setup some aliases: . /usr/local/Calpont/bin/calpontAlias +5. Run the following upgrade script to create calponsys schema and upgrade the syscolumn table: /usr/local/Calpont/bin/upgrade-infinidb.sh +6. Connect to MySQL: idbmysql - -Detailed Installation Instructions: - -1. Download the package calpont-2.2.0-2.x86_64.rpm.tar.gz (RHEL5 64-BIT) - to the server where you are installing Calpont. - -2. Obtain root user access. - -3. Unpack the tarball, which will generate 4 RPMs. - - tar xvf calpont-2.2.0-2.x86_64.rpm.tar.gz - -4. Install the 3 RPMs in this order, the Calpont InfiniDB software will be installed in - /usr/local/Calpont. - - rpm -ivh infinidb-libs-2.2.0-2.x86_64.rpm - rpm -ivh infinidb-platform-2.2.0-2.x86_64.rpm - rpm -ivh infinidb-mysql-2.2.0-2.x86_64.rpm - rpm -ivh infinidb-storage-engine-2.2.0-2.x86_64.rpm - -5a.To configure and run on a single server system utilizing local disk storage, - run install script: - - /usr/local/Calpont/bin/postConfigure - -5b.To configure and run on a multi-server system and/or to utilize a SAN storage - system, follow the instructions in the Calpont InfiniDB Installation Guide. - - /usr/local/Calpont/bin/postConfigure - -6. Ports utilized by the Calpont InfiniDB Software - - The Calpont MySQL daemon utilizes port 3306. To use a different port, update - the 2 locations in the following file: - - /usr/local/Calpont/mysql/my.cnf - - port = 3306 - port = 3306 - - You must reserve the following ports to run the Calpont InfiniDB Software: - - 8600 - 8622, 8700, and 8800 - -7. Setup some aliases: -. /usr/local/Calpont/bin/calpontAlias - -8. To manually start and stop the Calpont InfiniDB Software as the root user run: - - cc startSystem - - To stop the Calpont Software, run: - - cc stopSystem - -9. To start/stop the Calpont InfiniDB Software during system boot/shutdown use the - chkconfig command - - /sbin/chkconfig --add infinidb - /sbin/chkconfig infinidb on - -10. After the Calpont InfiniDB Software has been started, use the following command to - connect to the Calpont OAM Console and watch for the System to go to the - ACTIVE status. The follow will repeatedly run the OAM command getsysteminfo - every 5 seconds. - - calpontOAMconsole getsysteminfo -r - - Here is an example display from a Single Server Install: - - System and Module statuses - - Component Status Last Status Change - ------------ ---------------------- ------------------------ - System ACTIVE Mon Apr 6 18:07:14 2009 - - Module dm1 ACTIVE Mon Apr 6 18:07:12 2009 - - Calpont Process statuses - - Process Module Status Last Status Change Process ID - ------------------ ------ ------------ ------------------------ ---------- - ProcessMonitor dm1 ACTIVE Mon Apr 6 18:06:41 2009 12753 - ProcessManager dm1 ACTIVE Mon Apr 6 18:06:46 2009 12954 - SNMPTrapDaemon dm1 ACTIVE Mon Apr 6 18:06:41 2009 12963 - SNMPAgent dm1 ACTIVE Mon Apr 6 18:06:50 2009 13565 - ServerMonitor dm1 ACTIVE Mon Apr 6 18:06:55 2009 13635 - DBRMWorkerNode dm1 ACTIVE Mon Apr 6 18:06:51 2009 13640 - DBRMControllerNode dm1 ACTIVE Mon Apr 6 18:06:52 2009 13645 - ExeMgr dm1 ACTIVE Mon Apr 6 18:07:05 2009 14578 - PrimProc dm1 ACTIVE Mon Apr 6 18:07:03 2009 13842 - DDLProc dm1 ACTIVE Mon Apr 6 18:07:10 2009 14936 - DMLProc dm1 ACTIVE Mon Apr 6 18:07:13 2009 15114 - - Active Alarm Counts: Critical = 0, Major = 0, Minor = 0, Warning = 0, Info = 0 - - Once the System status is ACTIVE, enter the following to exit back to the - UNIX prompt: - - CNTR - - Or to get back Calpont OAM Console Prompt,enter the following: - - CNTR - -11. Use the following command to access the Calpont InfiniDB MySQL console: - - idbmysql - - Example output: - - Welcome to the Mysql monitor. Commands end with ; or \g. - Your Mysql connection id is 1 - Server version: 5.1.26-Calpont-log Source distribution - - Type 'help;' or '\h' for help. Type '\c' to clear the buffer. - - mysql> - -12. Run the following upgrade script to create calponsys schema and upgrade the syscolumn table: /usr/local/Calpont/bin/upgrade-infinidb.sh - -13. As an example to get you started, try this: +7. As an example to get you started, try this: create database calpont; use calpont; create table caltest (col1 int, col2 int) engine=infinidb; show create table caltest; + set autocommit=0; insert into caltest values (1, 2); insert into caltest values (3, 4); commit; select * from caltest; -14. Consult the Admin Guide and Syntax Guide for additional information on how - to get started. +Note: +Examine the output of the show create table command carefully and +make sure the table is in fact a calpont table. + +If the table is MyISAM type: + +drop table caltest; +install plugin infinidb soname 'libcalmysql.so'; + +and retry the example. +To uninstall infinidb: + service infinidb stop + or /usr/local/Calpont/bin/infinidb stop + chkconfig --del infinidb + rm -rf /usr/local/Calpont diff --git a/utils/autoconf/build_mysql.sh b/utils/autoconf/build_mysql.sh new file mode 100755 index 00000000..99856788 --- /dev/null +++ b/utils/autoconf/build_mysql.sh @@ -0,0 +1,59 @@ +#!/bin/bash + +mysqldir=mysql-5.1.39 + +prefix=/usr/local +withdebug= +for arg in "$@"; do + if [ $(expr -- "$arg" : '--prefix=') -eq 9 ]; then + prefix="$(echo $arg | awk -F= '{print $2}')" + elif [ $(expr -- "$arg" : '--with-debug') -eq 12 ]; then + withdebug=--with-debug + else + echo "ignoring unknown argument: $arg" 1>&2 + fi +done + +if [ ! -d $mysqldir ]; then + echo "Didn't find required MySQL install directory: $mysqldir" 1>&2 + exit 1 +fi + +cd $mysqldir + +if [ ! -d ../dbcon/mysql ]; then + echo "Didn't find required MySQL patch source directory: ../dbcon/mysql" 1>&2 + exit 1 +fi + +for file in configure.in; do + cp ../dbcon/mysql/$file . +done + +pushd ../dbcon/mysql >/dev/null +filelist=$(ls -1 *.cc *.h *.yy | sed -e '/^ha_/d' -e '/^idb_/d') +popd >/dev/null +for file in $filelist; do + cp ../dbcon/mysql/$file sql +done +cp ../dbcon/mysql/include/*.h include +cp ../dbcon/mysql/mysys/*.h mysys + +autoreconf --force --install +./configure --prefix="$prefix/Calpont/mysql" $withdebug --without-libedit --with-readline --with-client-ldflags="-Wl,-rpath -Wl,/usr/local/Calpont/mysql/lib/mysql" + +make || exit 1 +make install + +cp ../dbcon/mysql/my.cnf $prefix/Calpont/mysql + +for dir in \ +docs \ +man \ +mysql-test \ +sql-bench +do + rm -rf $prefix/Calpont/mysql/$dir +done +rm -rf $prefix/Calpont/mysql/share/man + diff --git a/utils/autoconf/configure.ac b/utils/autoconf/configure.ac index ae2a6419..371b055f 100644 --- a/utils/autoconf/configure.ac +++ b/utils/autoconf/configure.ac @@ -3,7 +3,7 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) -AC_INIT(infinidb, 4.6.0, support@infinidb.co) +AC_INIT(Calpont, 1.0.0, support@calpont.com) ### we don't want the deault CXXFLAGS set by AC_INIT, but we do want to allow the user to set them SAVE_CXXFLAGS= if test -n "$CXXFLAGS"; then @@ -91,32 +91,8 @@ AC_FUNC_STRTOD AC_FUNC_UTIME_NULL AC_CHECK_FUNCS([alarm dup2 floor ftime ftruncate gethostbyname getpagesize gettimeofday inet_ntoa isascii localtime_r memchr memmove memset mkdir pow regcomp rmdir select setenv setlocale socket strcasecmp strchr strcspn strdup strerror strrchr strspn strstr strtol strtoul strtoull utime]) -AM_PATH_XML2([2.6.26]) -if test "x$XML_CPPFLAGS" = "x"; then - AC_MSG_ERROR([Could not find a usable libxml2 development environment!]) -fi - -AC_CHECK_HEADERS([zlib.h]) -if test "x$ac_cv_header_zlib_h" != "xyes"; then - AC_MSG_ERROR([Could not find a usable zlib development environment!]) -fi - -AC_CHECK_HEADERS([readline/readline.h]) -if test "x$ac_cv_header_readline_readline_h" != "xyes"; then - AC_MSG_ERROR([Could not find a usable readline development environment!]) -fi - -AC_CHECK_HEADERS([ncurses.h]) -if test "x$ac_cv_header_ncurses_h" != "xyes"; then - AC_MSG_ERROR([Could not find a usable ncurses development environment!]) -fi - -CXX_FLAG_CHECK([-Wno-unused-local-typedefs]) -CXX_FLAG_CHECK([-Wno-unused-result]) -CXX_FLAG_CHECK([-Wno-format]) - AC_MSG_CHECKING(whether to enable debugging) -AC_SUBST([idb_cppflags], [' ']) +AC_SUBST([idb_cppflags], ['-DSKIP_SNMP -DSKIP_UDF -DSKIP_IDB_COMPRESSION -DCOMMUNITY_KEYRANGE -DSKIP_VIEW -DSKIP_INSERT_SELECT -DSKIP_AUTOI -DSKIP_OAM_INIT']) AC_ARG_WITH([debug], AS_HELP_STRING([--with-debug],[include debugging symbols/no optimization])) if test "x$with_debug" = "xyes"; then @@ -124,12 +100,11 @@ if test "x$with_debug" = "xyes"; then AC_SUBST([idb_cflags],['-ggdb3 -Wall -DSAFE_MUTEX -DINFINIDB_DEBUG']) AC_MSG_RESULT(yes) else - AC_SUBST([idb_cxxflags],["-g0 -O3 -fno-strict-aliasing -Wall $cxx_extra_flags"]) + AC_SUBST([idb_cxxflags],['-g0 -O3 -fno-strict-aliasing -Wall']) AC_SUBST([idb_cflags],['-g0 -O3 -fno-strict-aliasing -Wall']) AC_MSG_RESULT(no) fi -AC_SUBST([idbinstall], ['${prefix}']) -AC_SUBST([idb_ldflags],['-Wl,--rpath -Wl,${idbinstall}/lib -Wl,--no-as-needed -Wl,--add-needed']) +AC_SUBST([idb_ldflags],['-Wl,--rpath -Wl,/usr/local/Calpont/lib -Wl,--no-as-needed -Wl,--add-needed']) AC_MSG_CHECKING(for CPU architecture) uname=`uname -m` @@ -138,34 +113,29 @@ AS_IF( [AC_SUBST([march_flags], [' '])] [AC_MSG_RESULT(x86_64)] ) -AC_SUBST([libdir], ['${idbinstall}/lib']) -AC_SUBST([bindir], ['${idbinstall}/bin']) -AC_SUBST([includedir], ['${idbinstall}/include']) -AC_SUBST([etcdir], ['${idbinstall}/etc']) -AC_SUBST([sysconfdir], ['${idbinstall}/etc']) -AC_SUBST([mandir], ['${idbinstall}/man']) -AC_SUBST([sbindir], ['${idbinstall}/sbin']) -AC_SUBST([sharedir], ['${idbinstall}/share']) -AC_SUBST([postdir], ['${idbinstall}/post']) -AC_SUBST([localdir], ['${idbinstall}/local']) -AC_SUBST([mysqldir], ['${idbinstall}/mysql']) -AC_SUBST([mibdir], ['${idbinstall}/share/snmp/mibs']) -AC_SUBST([netsnmpdir], ['${idbinstall}/include/net-snmp']) -AC_SUBST([netsnmpsysdir], ['${idbinstall}/include/net-snmp/system']) -AC_SUBST([netsnmpmachdir], ['${idbinstall}/include/net-snmp/machine']) -AC_SUBST([netsnmplibrdir], ['${idbinstall}/include/net-snmp/library']) -AC_SUBST([netsnmpagntdir], ['${idbinstall}/include/net-snmp/agent']) -AC_SUBST([toolsdir], ['${idbinstall}/tools']) - -AC_SUBST([netsnmp_libs], ['-lnetsnmpmibs -lnetsnmpagent -lnetsnmp -lnetsnmpmibs -lnetsnmphelpers']) +AC_SUBST([libdir], ['${prefix}/Calpont/lib']) +AC_SUBST([bindir], ['${prefix}/Calpont/bin']) +AC_SUBST([includedir], ['${prefix}/Calpont/include']) +AC_SUBST([etcdir], ['${prefix}/Calpont/etc']) +AC_SUBST([sysconfdir], ['${prefix}/Calpont/etc']) +AC_SUBST([mandir], ['${prefix}/Calpont/man']) +AC_SUBST([sbindir], ['${prefix}/Calpont/sbin']) +AC_SUBST([sharedir], ['${prefix}/Calpont/share']) +AC_SUBST([postdir], ['${prefix}/Calpont/post']) +AC_SUBST([localdir], ['${prefix}/Calpont/local']) +AC_SUBST([mysqldir], ['${prefix}/Calpont/mysql']) +AC_SUBST([toolsdir], ['${prefix}/Calpont/tools']) +AC_SUBST([mibdir], ['${prefix}/Calpont/share/snmp/mibs']) + +AC_SUBST([netsnmp_libs], [' ']) AC_SUBST([idb_common_libs], ['-lmessageqcpp -lloggingcpp -lconfigcpp -lidbboot -lboost_idb -lxml2 -lpthread -lrt']) AC_SUBST([idb_oam_libs], ['-loamcpp -lsnmpmanager ${netsnmp_libs}']) -AC_SUBST([idb_brm_libs], ['-lbrm -lidbdatafile -lcacheutils -lrwlock ${idb_oam_libs} ${idb_common_libs}']) -AC_SUBST([idb_exec_libs], ['-ljoblist -lexecplan -lwindowfunction -ljoiner -lrowgroup -lfuncexp -ludfsdk -ldataconvert -lcommon -lcompress -lmysqlcl_idb -lquerystats -lquerytele -lthrift -lthreadpool ${idb_brm_libs}']) -AC_SUBST([idb_write_libs], ['-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lidbdatafile -lcacheutils ${idb_exec_libs}']) -AC_SUBST([idb_common_includes], ['-I${idbinstall}/include -I/usr/local/include -I/usr/local/include/libxml2 -I/usr/include/libxml2']) -AC_SUBST([idb_common_ldflags], ['-L${idbinstall}/lib -L/usr/local/lib']) +AC_SUBST([idb_brm_libs], ['-lbrm -lrwlock -lcacheutils ${idb_oam_libs} ${idb_common_libs}']) +AC_SUBST([idb_exec_libs], ['-ljoblist -lexecplan -ljoiner -lrowgroup -lmulticast -lfuncexp -ldataconvert -lcommon -lmysqlcl_idb -lquerystats ${idb_brm_libs}']) +AC_SUBST([idb_write_libs], ['-lddlpackageproc -lddlpackage -ldmlpackageproc -ldmlpackage -lwriteengine -lwriteengineclient -lcacheutils ${idb_exec_libs}']) +AC_SUBST([idb_common_includes], ['-I${prefix}/Calpont/include -I/usr/local/include -I/usr/local/include/libxml2 -I/usr/include/libxml2']) +AC_SUBST([idb_common_ldflags], ['-L${prefix}/Calpont/lib -L/usr/local/lib']) AC_CONFIG_FILES([ Makefile @@ -182,23 +152,13 @@ AC_CONFIG_FILES([ utils/joiner/Makefile utils/rowgroup/Makefile utils/cacheutils/Makefile - utils/net-snmp/Makefile + utils/multicast/Makefile utils/funcexp/Makefile - utils/udfsdk/Makefile utils/compress/Makefile utils/ddlcleanup/Makefile utils/batchloader/Makefile utils/mysqlcl_idb/Makefile utils/querystats/Makefile - utils/jemalloc/Makefile - utils/windowfunction/Makefile - utils/idbdatafile/Makefile - utils/idbhdfs/Makefile - utils/idbhdfs/hdfs-12/Makefile - utils/idbhdfs/hdfs-20/Makefile - utils/winport/Makefile - utils/thrift/Makefile - utils/querytele/Makefile exemgr/Makefile ddlproc/Makefile dbcon/Makefile @@ -209,29 +169,21 @@ AC_CONFIG_FILES([ dbcon/execplan/Makefile dbcon/joblist/Makefile dbcon/mysql/Makefile + dbcon/sm/Makefile dmlproc/Makefile oam/Makefile oam/etc/Makefile oam/install_scripts/Makefile oam/oamcpp/Makefile oam/post/Makefile - oam/cloud/Makefile + oam/replaytxnlog/Makefile oamapps/Makefile - oamapps/calpontConsole/Makefile - oamapps/calpontDB/Makefile - oamapps/postConfigure/Makefile - oamapps/serverMonitor/Makefile - oamapps/sessionWalker/Makefile - oamapps/traphandler/Makefile - oamapps/sendtrap/Makefile - oamapps/calpontSupport/Makefile + oamapps/replayTransactionLog/Makefile primitives/Makefile primitives/blockcache/Makefile primitives/linux-port/Makefile primitives/primproc/Makefile decomsvr/Makefile - procmgr/Makefile - procmon/Makefile snmpd/Makefile snmpd/etc/Makefile snmpd/snmpmanager/Makefile @@ -243,7 +195,6 @@ AC_CONFIG_FILES([ tools/getConfig/Makefile tools/dbbuilder/Makefile tools/dbloadxml/Makefile - tools/configMgt/Makefile tools/viewtablelock/Makefile tools/cleartablelock/Makefile tools/ddlcleanup/Makefile @@ -260,7 +211,7 @@ AC_CONFIG_FILES([ writeengine/client/Makefile writeengine/splitter/Makefile writeengine/server/Makefile + writeengine/cpimport/Makefile writeengine/redistribute/Makefile - net-snmp/Makefile ]) AC_OUTPUT diff --git a/utils/autoconf/m4/compilerflags.m4 b/utils/autoconf/m4/compilerflags.m4 deleted file mode 100644 index dcee6991..00000000 --- a/utils/autoconf/m4/compilerflags.m4 +++ /dev/null @@ -1,15 +0,0 @@ -dnl @synopsis CXX_FLAGS_CHECK [compiler flags] -dnl @summary check whether compiler supports given flags or not -AC_DEFUN([CXX_FLAG_CHECK], -[dnl - AC_MSG_CHECKING([if $CXX supports $1]) - ac_saved_cxxflags="$CXXFLAGS" - CXXFLAGS="-Werror $1" - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([])], - [AC_MSG_RESULT([yes]) - cxx_extra_flags="$cxx_extra_flags $1"], - [AC_MSG_RESULT([no])] - ) - CXXFLAGS="$ac_saved_cxxflags" -]) - diff --git a/utils/autoconf/make_rpms b/utils/autoconf/make_rpms new file mode 100755 index 00000000..57ce74e7 --- /dev/null +++ b/utils/autoconf/make_rpms @@ -0,0 +1,140 @@ +#! /bin/bash +# +# $Id$ +# + +if [ ! -f ./build/releasenum ]; then + echo "I could not find the file 'releasesum' in the ./build directory: I can't continue!" 1>&2 + echo "Maybe you're not in the right directory?" 1>&2 + exit 1 +fi + +. ./build/releasenum + +prefix="`awk '/^prefix = / {print $3}' ./Makefile 2>/dev/null`" +if [ "x$prefix" = x ]; then + echo "I could not determine the prefix from ./Makefile: I can't continue!" 1>&2 + echo "Maybe you're not in the right directory?" 1>&2 + exit 1 +fi + +if [ ! -d "$prefix/Calpont" ]; then + echo "$prefix/Calpont doesn't seem to be a directory: I can't continue!" 1>&2 + echo "Maybe you're not in the right directory?" 1>&2 + exit 1 +fi + +buildroot=$HOME/rpm/BUILD/calpont-$version-$release + +mkdir -p $buildroot/Calpont +pushd "$prefix/Calpont" > /dev/null +tar -cf - . | tar -C $buildroot/Calpont -xf - +popd >/dev/null + +#clean up some files from buildroot +rm -f $buildroot/Calpont/bin/emulator +rm -f $buildroot/Calpont/etc/Doxyfile +rm -rf $buildroot/Calpont/include +for file in $buildroot/Calpont/lib/*; do + if [ -h $file ]; then + rm -f $file + fi +done +rm -f $buildroot/Calpont/lib/libdbbc.a + +#temporarily clean up these BRM thingies +for file in dbrm script-fcns; do + rm -f $buildroot/Calpont/bin/$file +done + +#clean up these bulkload scripts +for file in bulkload.sh cleanup.sh dbbuilder.sh dbload.sh cleanup.pl; do + rm -f $buildroot/Calpont/bin/$file +done + +rm -rf $buildroot/Calpont/mysql/mysql-test +rm -rf $buildroot/Calpont/mysql/sql-bench +rm -rf $buildroot/Calpont/mysql/include + +rm -rf $buildroot/Calpont/man + +rm -rf $buildroot/Calpont/share/snmp/snmpconf-data +rm -f $buildroot/Calpont/share/snmp/mib2c.*.conf + +rm -f $buildroot/Calpont/etc/snmpd.* +rm -f $buildroot/Calpont/etc/snmptrapd.* +rm -f $buildroot/Calpont/local/snmpdx.* + +rm -rf $buildroot/Calpont/share + +rm -f $buildroot/Calpont/lib/*.a +rm -f $buildroot/Calpont/lib/*.la + +for plugin in ha_archive ha_blackhole ha_example ha_federated ha_innodb ha_innodb_plugin; do + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.a + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.la + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.so + rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/${plugin}.so.0 +done +rm -f $buildroot/Calpont/mysql/lib/mysql/plugin/ha_example.so.0.0.0 + +for lib in libdbug libheap libmyisam libmyisammrg libmysqlclient libmysqlclient_r libmystrings libmysys libvio; do + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.a + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.la + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.so + rm -f $buildroot/Calpont/mysql/lib/mysql/${lib}.so.16 +done + +rm -rf $buildroot/Calpont/mysql/share/aclocal +rm -rf $buildroot/Calpont/mysql/share/man + +mkdir -p ~/rpm/BUILD ~/rpm/RPMS ~/rpm/SRPMS ~/rpm/SPECS ~/rpm/tmp + +if [ ! -f $HOME/.rpmmacros ]; then +cat > $HOME/.rpmmacros <> $HOME/.rpmmacros <& PMs ) + std::vector& PMs ) { fFirstPm=0; fNextIdx=0; @@ -56,7 +56,7 @@ BatchLoader::BatchLoader ( uint32_t tableOid, //cout << "fPMs size is " << fPMs.size() << endl; fPmDbrootMap.reset(new OamCache::PMDbrootsMap_t::element_type()); fDbrootPMmap.reset(new map()); - for (uint32_t i=0; i < fPMs.size(); i++) + for (uint i=0; i < fPMs.size(); i++) { iter = systemPmDbrootMap->find(fPMs[i]); if (iter != systemPmDbrootMap->end()) @@ -68,7 +68,7 @@ BatchLoader::BatchLoader ( uint32_t tableOid, //Build dbroot to PM map for (iter = fPmDbrootMap->begin(); iter != fPmDbrootMap->end(); iter++) { - for ( uint32_t i = 0; i < iter->second.size(); i++) + for ( uint i = 0; i < iter->second.size(); i++) { (*fDbrootPMmap)[iter->second[i]] = iter->first; } @@ -79,15 +79,14 @@ BatchLoader::BatchLoader ( uint32_t tableOid, /*Look up extent map to decide which dbroot to start 1. If newly created table, starts from the pm where the abbreviated extent created. 2. If the abbreviated extent has hwm > 0, and other PMs don't have any extent, start from next PM on the list. - 2.5If some DBRoots have extents and some don't the DBRoot with the fewest extents or blocks is chosen, - "unless" the partition 0, segment 0 extent is one of the HWM extents. In that case the partition 0, - segment 0 extent still takes precedence. 3. If all PMs have extents, count the number of extents under each dbroot, find the dbroot which has the least extents to start - 4. If all dbroots have same number of extents, starts from the dbroot which has least number of blocks + 4. If all dbroots have same number of extents, starts from the dbroot which has least number of blocks on the last partition. */ //------------------------------------------------------------------------------ -void BatchLoader::selectFirstPM ( uint32_t& PMId) +int BatchLoader::selectFirstPM ( uint& PMId, bool& startFromNextPM) { + startFromNextPM = false; + int rc = 0; boost::shared_ptr systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionId); //cout << "calling tableName for oid " << fTableOid << endl; CalpontSystemCatalog::TableName aTableName = systemCatalogPtr->tableName(fTableOid); @@ -99,7 +98,7 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) //Build distVec, start from the PM where the table is created. If not in the PM list, 0 will be used. uint16_t createdDbroot = 0; - int rc = 0; + std::vector allInfo (fPMs.size()); for (unsigned i = 0; i < fPMs.size(); i++) { @@ -112,32 +111,21 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) ostringstream oss; oss << "There is no extent information for table " << aTableName.table; throw std::runtime_error(oss.str()); + } - uint32_t numDbroot = fDbRoots.size(); - if (numDbroot == 0) - { - throw std::runtime_error("There are no dbroots found during selectFirstPM"); - } - uint64_t* rootExtents = (uint64_t*)alloca((numDbroot + 1) * sizeof(uint64_t)); //array of number extents for each dbroot + std::vector entries; + uint numDbroot = fDbRoots.size(); + int* rootExtents = (int*)alloca((numDbroot + 1) * sizeof(int)); //array of number extents for each dbroot for (unsigned i = 0; i < fDbRoots.size(); i++) { - uint64_t numExtents; - dbrmp->getExtentCount_dbroot((ridList[0].objnum), fDbRoots[i], - false, numExtents); - rootExtents[fDbRoots[i]] = numExtents; + dbrmp->getExtents_dbroot((ridList[0].objnum), entries, fDbRoots[i]); + rootExtents[fDbRoots[i]] = entries.size(); } bool startDBRootSet = false; - uint64_t* rootBlocks = (uint64_t*)alloca((numDbroot + 1) * sizeof(uint64_t)); //array of number of blocks for the last partition for each dbroot + int* rootBlocks = (int*)alloca((numDbroot + 1) * sizeof(int)); //array of number of blocks for the last partition for each dbroot //cout << "allInfo size is " << allInfo.size() << endl; - - //-------------------------------------------------------------------------- - // Load rootBlocks to carry total blocks for each DBRoot - // Set startDBRootSet if the partition 0 segment 0 extent is empty - // Set createdDbroot for the DBRoot that carries the partition 0 - // segment 0 extent (used to set the default PMId) - //-------------------------------------------------------------------------- for (unsigned i=0; i < allInfo.size(); i++) //All PMs { BRM::EmDbRootHWMInfo_v emDbRootHWMInfos = allInfo[i]; //one pm @@ -147,13 +135,8 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) if (emDbRootHWMInfos[j].totalBlocks == 0) { //cout << "totalBlocks is 0" << endl; continue; } - - //------------------------------------------------------------------ - // Ignore partition 0, segment 0 HWM extent if it is disabled - //------------------------------------------------------------------ - if ((emDbRootHWMInfos[j].partitionNum == 0) && - (emDbRootHWMInfos[j].segmentNum ==0) && - (emDbRootHWMInfos[j].status != BRM::EXTENTOUTOFSERVICE)) + + if ((emDbRootHWMInfos[j].partitionNum == 0) && (emDbRootHWMInfos[j].segmentNum ==0)) { if (emDbRootHWMInfos[j].localHWM == 0) { @@ -179,9 +162,6 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) break; } - //-------------------------------------------------------------------------- - // Set the default PMId to the PM with the partition 0 segment 0 extent - //-------------------------------------------------------------------------- PMId = 0; if ( createdDbroot != 0) { @@ -191,29 +171,17 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) if (iter != fDbrootPMmap->end()) PMId = iter->second; } - // This will build the batch distribution sequence //cout << "Building BatchDistSeqVector with PMId " << PMId << endl; buildBatchDistSeqVector(PMId); //cout << "startDBRootSet = " << startDBRootSet << endl; bool allEqual = true; - bool allOtherDbrootEmpty = true; - - //-------------------------------------------------------------------------- - // startDBRootSet == false - // We don't have an empty partition 0, segment 0 extent to load; - // so evaluate more selection criteria. - //-------------------------------------------------------------------------- if (!startDBRootSet) { + std::vector rootsExtentsBlocks; std::map::iterator iter; - - //---------------------------------------------------------------------- - // Load rootsExtentsBlocks to carry the number of extents and blocks - // for each DBRoot. - //---------------------------------------------------------------------- for (unsigned j=0; j < fPmDistSeq.size(); j++) { PMRootInfo aEntry; @@ -230,16 +198,12 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) } rootsExtentsBlocks.push_back(aEntry); } - //cout << "rootsExtentsBlocks size is " << rootsExtentsBlocks.size() << " and allOtherDbrootEmpty is " << allOtherDbrootEmpty<< endl; - - //---------------------------------------------------------------------- - // See if all other DBRoots other than the createdDbroot have 0 extents - //---------------------------------------------------------------------- + //cout << "rootsExtentsBlocks size is " << rootsExtentsBlocks.size() << endl; + bool allOtherDbrootEmpty = true; for (unsigned i=1; i < rootsExtentsBlocks.size(); i++) { if (!allOtherDbrootEmpty) break; - //cout << "createdDbroot is " << createdDbroot << endl; if (i != createdDbroot) { for ( unsigned j=0; j < rootsExtentsBlocks[i].rootInfo.size(); j++) @@ -255,32 +219,19 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) } } //cout << "allOtherDbrootEmpty is " << allOtherDbrootEmpty << endl; - - //---------------------------------------------------------------------- - // allOtherDbrootEmpty == true - // No DBRoots (other than the DBRoot having the partition 0, - // segment 0 extent) have extents - //---------------------------------------------------------------------- if (allOtherDbrootEmpty) { //find the next PM id on the list startDBRootSet = true; + startFromNextPM = true; buildBatchDistSeqVector(); allEqual = false; } - //---------------------------------------------------------------------- - // allOtherDbrootEmpty == false - // Some DBRoots (other than the DBRoot having the partition 0, - // segment 0 extent) have extents. More evaluation necessary. - //---------------------------------------------------------------------- else //find the dbroot which has the least extents to start { //cout << "finding least dbroot to start." << endl; - //------------------------------------------------------------------ - // Select PM with DBRoot having the fewest extents. - //------------------------------------------------------------------ - uint32_t tmpLeastExtents = rootsExtentsBlocks[0].rootInfo[0].numExtents; + uint tmpLeastExtents = rootsExtentsBlocks[0].rootInfo[0].numExtents; PMId = rootsExtentsBlocks[0].PMId; //@Bug 4809. for ( unsigned j=1; j < rootsExtentsBlocks[0].rootInfo.size(); j++) { @@ -290,7 +241,7 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) for (unsigned i=1; i < rootsExtentsBlocks.size(); i++) { - uint32_t leastExtents = rootsExtentsBlocks[i].rootInfo[0].numExtents; + uint leastExtents = rootsExtentsBlocks[i].rootInfo[0].numExtents; for ( unsigned j=0; j < rootsExtentsBlocks[i].rootInfo.size(); j++) { if (leastExtents > rootsExtentsBlocks[i].rootInfo[j].numExtents) @@ -308,15 +259,10 @@ void BatchLoader::selectFirstPM ( uint32_t& PMId) } //cout << "allEqual is " << allEqual << endl; - - //------------------------------------------------------------------ - // All DBRoots have the same number of extents. - // Select PM with DBRoot having the fewest number of blocks. - //------------------------------------------------------------------ - if (allEqual) //Find the dbroot which has least number of blocks + if (allEqual) //Find the dbroot which has least number of blocks on the last partition. { //cout << "All PMs have equal # of least extents" << endl; - uint32_t tmpBloks = rootsExtentsBlocks[0].rootInfo[0].numBlocks; + uint tmpBloks = rootsExtentsBlocks[0].rootInfo[0].numBlocks; PMId = rootsExtentsBlocks[0].PMId; //cout << "tmpBloks:PMId = " << tmpBloks <<":"<::iterator iter = fPmDbrootMap->begin(); - for (uint32_t i=0; i < fPMs.size(); i++) + for (uint i=0; i < fPMs.size(); i++) { iter = fPmDbrootMap->find(fPMs[i]); if ((iter != fPmDbrootMap->end()) && ((iter->second).begin()!=(iter->second).end())) @@ -404,15 +337,15 @@ void BatchLoader::buildBatchDistSeqVector() } int aTotDbRoots = 0; - for (uint32_t i=0; i aMax) { @@ -438,7 +371,7 @@ void BatchLoader::buildBatchDistSeqVector() */ //------------------------------------------------------------------------------ -void BatchLoader::buildBatchDistSeqVector(uint32_t StartPm) +void BatchLoader::buildBatchDistSeqVector(uint StartPm) { fPmDistSeq.clear(); BlIntVec aDbCntVec(fPMs.size()); @@ -447,7 +380,7 @@ void BatchLoader::buildBatchDistSeqVector(uint32_t StartPm) if((fPMs.size()==0)&&(StartPm!=0)) throw runtime_error("ERROR : PM list empty while Start != 0"); - //for (uint32_t i=0; iStartPm)&&(fPMs[i]<=aLast)) aPms.push_back(fPMs[i]); } // Add all the PMs with index less than "StartPm" - for(uint32_t i=0; i=aFirst)) aPms.push_back(fPMs[i]); } @@ -472,7 +405,7 @@ void BatchLoader::buildBatchDistSeqVector(uint32_t StartPm) std::map::iterator iter = fPmDbrootMap->begin(); - for (uint32_t i=0; i < aPms.size(); i++) + for (uint i=0; i < aPms.size(); i++) { iter = fPmDbrootMap->find(aPms[i]); if ((iter != fPmDbrootMap->end()) && ((iter->second).begin()!=(iter->second).end())) @@ -485,17 +418,17 @@ void BatchLoader::buildBatchDistSeqVector(uint32_t StartPm) } int aTotDbRoots = 0; - for (uint32_t i=0; ibuildBatchDistSeqVector(); + return fPmDistSeq; +} + +//------------------------------------------------------------------------------ + +uint BatchLoader::selectNextPM() +{ + if(0 == fPmDistSeq.size()) return 0; //Dist sequence not ready. if(fNextIdx >= fPmDistSeq.size()) fNextIdx=0; //reset it return fPmDistSeq[fNextIdx++]; } diff --git a/utils/batchloader/batchloader.h b/utils/batchloader/batchloader.h index efced70b..c2767d4a 100644 --- a/utils/batchloader/batchloader.h +++ b/utils/batchloader/batchloader.h @@ -48,15 +48,34 @@ class BatchLoader * @param sessionId cpimport use 0 as session id. * @param PMs vector Collection of PM ids. */ - BatchLoader ( uint32_t tableOid, execplan::CalpontSystemCatalog::SCN sessionId, std::vector& PMs); + BatchLoader ( uint32_t tableOid, execplan::CalpontSystemCatalog::SCN sessionId, std::vector& PMs); + /** @brief Select the first PM to send the first batch of rows. + * @param startFromNextPM - if true, don't use the PMId. Instead use the next one in the sorted dmList. + * @param PMId - The PM id to send the first batch of rows if startFromNextPM is false. + * @return Returns 0 if success, else returns error code. + */ + int selectFirstPM ( uint& PMId, bool& startFromNextPM); + + /** @brief build the batch distribution sequence in a vector + * return void + */ + void buildBatchDistSeqVector(); + + /** @brief build the batch distribution sequence in a vector + * return void + */ + void buildBatchDistSeqVector(uint StartPm); + /** @brief get the batch distribution sequence in a vector + * return the vector of PMId sequence, batches of data be distributed + */ + std::vector getBatchDistributionVector(); /** * @brief select the Next PM where batch data to be distributed. * return the PM where next batch to be send. * if an error occurs, 0 will be returned */ - uint32_t selectNextPM(); - + uint selectNextPM(); /** * @brief Move to previous Sequence in the array. * This can be used when we find that we cannot use the PM right now @@ -65,7 +84,6 @@ class BatchLoader * next time also. */ void reverseSequence(); - /* * @brief After calling selectFirstPM(), if we need to keep continuing to * the next PM in the list, we need to call this. If we just want to start @@ -77,49 +95,33 @@ class BatchLoader { /** @brief the dbroot */ - uint32_t DBRoot; + uint DBRoot; /** @brief the number of extents */ - uint64_t numExtents; + uint numExtents; /** @brief the number of blocks in the last partition */ - uint64_t numBlocks; + uint numBlocks; }; struct PMRootInfo { /** @brief the module id */ - uint32_t PMId; + uint PMId; /** @brief the dbroot info */ std::vector rootInfo; }; -private: - /** @brief Select the first PM to send the first batch of rows. - * @param startFromNextPM - if true, don't use the PMId. Instead use the next one in the sorted dmList. - * @param PMId - The PM id to send the first batch of rows if startFromNextPM is false. - * @return Returns 0 if success, else returns error code. - */ - void selectFirstPM ( uint32_t& PMId); - - /** @brief build the batch distribution sequence in a vector - * return void - */ - void buildBatchDistSeqVector(); - - /** @brief build the batch distribution sequence in a vector - * return void - */ - void buildBatchDistSeqVector(uint32_t StartPm); - typedef std::vector BlIntVec; +private: + typedef std::vector BlIntVec; BlIntVec fPMs; BlIntVec fDbRoots; BlIntVec fPmDistSeq; - uint32_t fNextIdx; - uint32_t fFirstPm; + uint fNextIdx; + uint fFirstPm; execplan::CalpontSystemCatalog::SCN fSessionId; uint32_t fTableOid; oam::OamCache::PMDbrootsMap_t fPmDbrootMap; diff --git a/utils/batchloader/libbatchloader.vcxproj b/utils/batchloader/libbatchloader.vcxproj deleted file mode 100644 index 7c7d03f5..00000000 --- a/utils/batchloader/libbatchloader.vcxproj +++ /dev/null @@ -1,209 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - EnterpriseRelease - Win32 - - - EnterpriseRelease - x64 - - - Release - Win32 - - - Release - x64 - - - - {35D6295B-4A83-4E6E-BAB0-70ADF19AE822} - libbatchloader - - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - true - - - StaticLibrary - v110 - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>11.0.50727.1 - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - $(SolutionDir)..\..\$(PlatformName)\$(ConfigurationName)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(PlatformName)\$(ConfigurationName)\ - - - $(SolutionDir)..\..\$(Platform)\$(Configuration)\ - $(SolutionDir)..\..\obj\$(ProjectName)\$(Platform)\$(Configuration)\ - - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - - - X64 - - - Disabled - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - SKIP_SNMP;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - ProgramDatabase - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - - - - - X64 - - - MaxSpeed - true - $(SolutionDir)..\..\boost_1_54_0;$(SolutionDir)..\..\libxml2-2.7.8\libxml2\include;$(SolutionDir)..\utils\winport;$(SolutionDir)..\oam\oamcpp;$(SolutionDir)..\utils\messageqcpp;$(SolutionDir)..\utils\configcpp;$(SolutionDir)..\utils\loggingcpp;$(SolutionDir)..\snmpd\snmpmanager;$(SolutionDir)..\versioning\BRM;$(SolutionDir)..\dbcon\execplan;$(SolutionDir)..\writeengine\shared;$(SolutionDir)..\utils\rwlock;$(SolutionDir)..\dbcon\joblist;$(SolutionDir)..\utils\common;$(SolutionDir)..\..\libiconv-1.14\libiconv\include;%(AdditionalIncludeDirectories) - _CRT_SECURE_NO_WARNINGS;SKIP_SNMP;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Level3 - ProgramDatabase - 4267;4244;4996;%(DisableSpecificWarnings) - false - - - - - - - - - - - - \ No newline at end of file diff --git a/utils/batchloader/libbatchloader.vcxproj.filters b/utils/batchloader/libbatchloader.vcxproj.filters deleted file mode 100644 index 0118ab45..00000000 --- a/utils/batchloader/libbatchloader.vcxproj.filters +++ /dev/null @@ -1,27 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - - - Header Files - - - \ No newline at end of file diff --git a/utils/boost_idb/Makefile.am b/utils/boost_idb/Makefile.am index 355bf875..7f52c23c 100644 --- a/utils/boost_idb/Makefile.am +++ b/utils/boost_idb/Makefile.am @@ -1,19 +1,19 @@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ ## Process this file with automake to produce Makefile.in @@ -25,38 +25,2827 @@ AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) lib_LTLIBRARIES = libboost_idb.la libboost_idb_la_SOURCES = \ - codecvt_error_category.cpp \ + c_regex_traits.cpp \ cpp_regex_traits.cpp \ cregex.cpp \ - c_regex_traits.cpp \ + date_generators.cpp \ error_code.cpp \ fileiter.cpp \ - future.cpp \ greg_month.cpp \ + greg_weekday.cpp \ + gregorian_types.cpp \ icu.cpp \ instances.cpp \ once.cpp \ operations.cpp \ path.cpp \ - path_traits.cpp \ portability.cpp \ posix_api.cpp \ + posix_time_types.cpp \ regex.cpp \ regex_debug.cpp \ regex_raw_buffer.cpp \ regex_traits_defaults.cpp \ static_mutex.cpp \ thread.cpp \ - tss_null.cpp \ - unique_path.cpp \ usinstances.cpp \ utf8_codecvt_facet.cpp \ w32_regex_traits.cpp \ wc_regex_traits.cpp \ wide_posix_api.cpp \ - windows_file_codecvt.cpp \ winstances.cpp include_HEADERS = +nobase_include_HEADERS = \ + boost/algorithm/minmax.hpp \ + boost/algorithm/minmax_element.hpp \ + boost/algorithm/string.hpp \ + boost/algorithm/string/case_conv.hpp \ + boost/algorithm/string/classification.hpp \ + boost/algorithm/string/compare.hpp \ + boost/algorithm/string/concept.hpp \ + boost/algorithm/string/config.hpp \ + boost/algorithm/string/constants.hpp \ + boost/algorithm/string/detail/case_conv.hpp \ + boost/algorithm/string/detail/classification.hpp \ + boost/algorithm/string/detail/find_format.hpp \ + boost/algorithm/string/detail/find_format_all.hpp \ + boost/algorithm/string/detail/find_format_store.hpp \ + boost/algorithm/string/detail/find_iterator.hpp \ + boost/algorithm/string/detail/finder.hpp \ + boost/algorithm/string/detail/finder_regex.hpp \ + boost/algorithm/string/detail/formatter.hpp \ + boost/algorithm/string/detail/formatter_regex.hpp \ + boost/algorithm/string/detail/predicate.hpp \ + boost/algorithm/string/detail/replace_storage.hpp \ + boost/algorithm/string/detail/sequence.hpp \ + boost/algorithm/string/detail/trim.hpp \ + boost/algorithm/string/detail/util.hpp \ + boost/algorithm/string/erase.hpp \ + boost/algorithm/string/find.hpp \ + boost/algorithm/string/find_format.hpp \ + boost/algorithm/string/find_iterator.hpp \ + boost/algorithm/string/finder.hpp \ + boost/algorithm/string/formatter.hpp \ + boost/algorithm/string/iter_find.hpp \ + boost/algorithm/string/join.hpp \ + boost/algorithm/string/predicate.hpp \ + boost/algorithm/string/predicate_facade.hpp \ + boost/algorithm/string/regex.hpp \ + boost/algorithm/string/regex_find_format.hpp \ + boost/algorithm/string/replace.hpp \ + boost/algorithm/string/sequence_traits.hpp \ + boost/algorithm/string/split.hpp \ + boost/algorithm/string/std/list_traits.hpp \ + boost/algorithm/string/std/rope_traits.hpp \ + boost/algorithm/string/std/slist_traits.hpp \ + boost/algorithm/string/std/string_traits.hpp \ + boost/algorithm/string/std_containers_traits.hpp \ + boost/algorithm/string/trim.hpp \ + boost/algorithm/string/yes_no_type.hpp \ + boost/algorithm/string_regex.hpp \ + boost/aligned_storage.hpp \ + boost/any.hpp \ + boost/array.hpp \ + boost/asio.hpp \ + boost/assert.hpp \ + boost/assign.hpp \ + boost/assign/list_inserter.hpp \ + boost/assign/ptr_list_inserter.hpp \ + boost/assign/list_of.hpp \ + boost/assign/assignment_exception.hpp \ + boost/assign/std.hpp \ + boost/assign/ptr_list_of.hpp \ + boost/assign/ptr_map_inserter.hpp \ + boost/assign/std/list.hpp \ + boost/assign/std/stack.hpp \ + boost/assign/std/set.hpp \ + boost/assign/std/slist.hpp \ + boost/assign/std/vector.hpp \ + boost/assign/std/map.hpp \ + boost/assign/std/deque.hpp \ + boost/assign/std/queue.hpp \ + boost/bimap.hpp \ + boost/bind.hpp \ + boost/bind/apply.hpp \ + boost/bind/arg.hpp \ + boost/bind/bind.hpp \ + boost/bind/bind_cc.hpp \ + boost/bind/bind_mf2_cc.hpp \ + boost/bind/bind_mf_cc.hpp \ + boost/bind/bind_template.hpp \ + boost/bind/make_adaptable.hpp \ + boost/bind/mem_fn.hpp \ + boost/bind/mem_fn_cc.hpp \ + boost/bind/mem_fn_template.hpp \ + boost/bind/mem_fn_vw.hpp \ + boost/bind/placeholders.hpp \ + boost/bind/protect.hpp \ + boost/bind/storage.hpp \ + boost/blank.hpp \ + boost/blank_fwd.hpp \ + boost/call_traits.hpp \ + boost/cast.hpp \ + boost/cerrno.hpp \ + boost/checked_delete.hpp \ + boost/circular_buffer.hpp \ + boost/circular_buffer_fwd.hpp \ + boost/compressed_pair.hpp \ + boost/concept/assert.hpp \ + boost/concept/detail/backward_compatibility.hpp \ + boost/concept/detail/borland.hpp \ + boost/concept/detail/concept_def.hpp \ + boost/concept/detail/concept_undef.hpp \ + boost/concept/detail/general.hpp \ + boost/concept/detail/has_constraints.hpp \ + boost/concept/detail/msvc.hpp \ + boost/concept/requires.hpp \ + boost/concept/usage.hpp \ + boost/concept_archetype.hpp \ + boost/concept_check.hpp \ + boost/config.hpp \ + boost/config/abi/borland_prefix.hpp \ + boost/config/abi/borland_suffix.hpp \ + boost/config/abi/msvc_prefix.hpp \ + boost/config/abi/msvc_suffix.hpp \ + boost/config/abi_prefix.hpp \ + boost/config/abi_suffix.hpp \ + boost/config/auto_link.hpp \ + boost/config/compiler/borland.hpp \ + boost/config/compiler/clang.hpp \ + boost/config/compiler/codegear.hpp \ + boost/config/compiler/comeau.hpp \ + boost/config/compiler/common_edg.hpp \ + boost/config/compiler/compaq_cxx.hpp \ + boost/config/compiler/digitalmars.hpp \ + boost/config/compiler/gcc.hpp \ + boost/config/compiler/gcc_xml.hpp \ + boost/config/compiler/greenhills.hpp \ + boost/config/compiler/hp_acc.hpp \ + boost/config/compiler/intel.hpp \ + boost/config/compiler/kai.hpp \ + boost/config/compiler/metrowerks.hpp \ + boost/config/compiler/mpw.hpp \ + boost/config/compiler/nvcc.hpp \ + boost/config/compiler/pgi.hpp \ + boost/config/compiler/sgi_mipspro.hpp \ + boost/config/compiler/sunpro_cc.hpp \ + boost/config/compiler/vacpp.hpp \ + boost/config/compiler/visualc.hpp \ + boost/config/no_tr1/cmath.hpp \ + boost/config/no_tr1/complex.hpp \ + boost/config/no_tr1/functional.hpp \ + boost/config/no_tr1/memory.hpp \ + boost/config/no_tr1/utility.hpp \ + boost/config/platform/aix.hpp \ + boost/config/platform/amigaos.hpp \ + boost/config/platform/beos.hpp \ + boost/config/platform/bsd.hpp \ + boost/config/platform/cygwin.hpp \ + boost/config/platform/hpux.hpp \ + boost/config/platform/irix.hpp \ + boost/config/platform/linux.hpp \ + boost/config/platform/macos.hpp \ + boost/config/platform/qnxnto.hpp \ + boost/config/platform/solaris.hpp \ + boost/config/platform/symbian.hpp \ + boost/config/platform/vms.hpp \ + boost/config/platform/vxworks.hpp \ + boost/config/platform/win32.hpp \ + boost/config/posix_features.hpp \ + boost/config/requires_threads.hpp \ + boost/config/select_compiler_config.hpp \ + boost/config/select_platform_config.hpp \ + boost/config/select_stdlib_config.hpp \ + boost/config/stdlib/dinkumware.hpp \ + boost/config/stdlib/libcomo.hpp \ + boost/config/stdlib/libstdcpp3.hpp \ + boost/config/stdlib/modena.hpp \ + boost/config/stdlib/msl.hpp \ + boost/config/stdlib/roguewave.hpp \ + boost/config/stdlib/sgi.hpp \ + boost/config/stdlib/stlport.hpp \ + boost/config/stdlib/vacpp.hpp \ + boost/config/suffix.hpp \ + boost/config/user.hpp \ + boost/config/warning_disable.hpp \ + boost/crc.hpp \ + boost/cregex.hpp \ + boost/cstdint.hpp \ + boost/cstdlib.hpp \ + boost/current_function.hpp \ + boost/date_time.hpp \ + boost/date_time/adjust_functors.hpp \ + boost/date_time/c_local_time_adjustor.hpp \ + boost/date_time/c_time.hpp \ + boost/date_time/compiler_config.hpp \ + boost/date_time/constrained_value.hpp \ + boost/date_time/date.hpp \ + boost/date_time/date_clock_device.hpp \ + boost/date_time/date_defs.hpp \ + boost/date_time/date_duration.hpp \ + boost/date_time/date_duration_types.hpp \ + boost/date_time/date_facet.hpp \ + boost/date_time/date_format_simple.hpp \ + boost/date_time/date_formatting.hpp \ + boost/date_time/date_formatting_limited.hpp \ + boost/date_time/date_formatting_locales.hpp \ + boost/date_time/date_generator_formatter.hpp \ + boost/date_time/date_generator_parser.hpp \ + boost/date_time/date_generators.hpp \ + boost/date_time/date_iterator.hpp \ + boost/date_time/date_names_put.hpp \ + boost/date_time/date_parsing.hpp \ + boost/date_time/dst_rules.hpp \ + boost/date_time/dst_transition_generators.hpp \ + boost/date_time/filetime_functions.hpp \ + boost/date_time/format_date_parser.hpp \ + boost/date_time/gregorian/conversion.hpp \ + boost/date_time/gregorian/formatters.hpp \ + boost/date_time/gregorian/formatters_limited.hpp \ + boost/date_time/gregorian/greg_calendar.hpp \ + boost/date_time/gregorian/greg_date.hpp \ + boost/date_time/gregorian/greg_day.hpp \ + boost/date_time/gregorian/greg_day_of_year.hpp \ + boost/date_time/gregorian/greg_duration.hpp \ + boost/date_time/gregorian/greg_duration_types.hpp \ + boost/date_time/gregorian/greg_facet.hpp \ + boost/date_time/gregorian/greg_month.hpp \ + boost/date_time/gregorian/greg_serialize.hpp \ + boost/date_time/gregorian/greg_weekday.hpp \ + boost/date_time/gregorian/greg_year.hpp \ + boost/date_time/gregorian/greg_ymd.hpp \ + boost/date_time/gregorian/gregorian.hpp \ + boost/date_time/gregorian/gregorian_io.hpp \ + boost/date_time/gregorian/gregorian_types.hpp \ + boost/date_time/gregorian/parsers.hpp \ + boost/date_time/gregorian_calendar.hpp \ + boost/date_time/gregorian_calendar.ipp \ + boost/date_time/int_adapter.hpp \ + boost/date_time/iso_format.hpp \ + boost/date_time/local_time/conversion.hpp \ + boost/date_time/local_time/custom_time_zone.hpp \ + boost/date_time/local_time/date_duration_operators.hpp \ + boost/date_time/local_time/dst_transition_day_rules.hpp \ + boost/date_time/local_time/local_date_time.hpp \ + boost/date_time/local_time/local_time.hpp \ + boost/date_time/local_time/local_time_io.hpp \ + boost/date_time/local_time/local_time_types.hpp \ + boost/date_time/local_time/posix_time_zone.hpp \ + boost/date_time/local_time/tz_database.hpp \ + boost/date_time/local_time_adjustor.hpp \ + boost/date_time/local_timezone_defs.hpp \ + boost/date_time/locale_config.hpp \ + boost/date_time/microsec_time_clock.hpp \ + boost/date_time/parse_format_base.hpp \ + boost/date_time/period.hpp \ + boost/date_time/period_formatter.hpp \ + boost/date_time/period_parser.hpp \ + boost/date_time/posix_time/conversion.hpp \ + boost/date_time/posix_time/date_duration_operators.hpp \ + boost/date_time/posix_time/posix_time.hpp \ + boost/date_time/posix_time/posix_time_config.hpp \ + boost/date_time/posix_time/posix_time_duration.hpp \ + boost/date_time/posix_time/posix_time_io.hpp \ + boost/date_time/posix_time/posix_time_legacy_io.hpp \ + boost/date_time/posix_time/posix_time_system.hpp \ + boost/date_time/posix_time/posix_time_types.hpp \ + boost/date_time/posix_time/ptime.hpp \ + boost/date_time/posix_time/time_formatters.hpp \ + boost/date_time/posix_time/time_formatters_limited.hpp \ + boost/date_time/posix_time/time_parsers.hpp \ + boost/date_time/posix_time/time_period.hpp \ + boost/date_time/posix_time/time_serialize.hpp \ + boost/date_time/special_defs.hpp \ + boost/date_time/special_values_formatter.hpp \ + boost/date_time/special_values_parser.hpp \ + boost/date_time/string_convert.hpp \ + boost/date_time/string_parse_tree.hpp \ + boost/date_time/strings_from_facet.hpp \ + boost/date_time/time.hpp \ + boost/date_time/time_clock.hpp \ + boost/date_time/time_defs.hpp \ + boost/date_time/time_duration.hpp \ + boost/date_time/time_facet.hpp \ + boost/date_time/time_formatting_streams.hpp \ + boost/date_time/time_iterator.hpp \ + boost/date_time/time_parsing.hpp \ + boost/date_time/time_resolution_traits.hpp \ + boost/date_time/time_system_counted.hpp \ + boost/date_time/time_system_split.hpp \ + boost/date_time/time_zone_base.hpp \ + boost/date_time/time_zone_names.hpp \ + boost/date_time/tz_db_base.hpp \ + boost/date_time/wrapping_int.hpp \ + boost/date_time/year_month_day.hpp \ + boost/detail/algorithm.hpp \ + boost/detail/allocator_utilities.hpp \ + boost/detail/atomic_count.hpp \ + boost/detail/binary_search.hpp \ + boost/detail/call_traits.hpp \ + boost/detail/catch_exceptions.hpp \ + boost/detail/compressed_pair.hpp \ + boost/detail/container_fwd.hpp \ + boost/detail/dynamic_bitset.hpp \ + boost/detail/endian.hpp \ + boost/detail/has_default_constructor.hpp \ + boost/detail/identifier.hpp \ + boost/detail/indirect_traits.hpp \ + boost/detail/interlocked.hpp \ + boost/detail/is_function_ref_tester.hpp \ + boost/detail/is_incrementable.hpp \ + boost/detail/is_xxx.hpp \ + boost/detail/iterator.hpp \ + boost/detail/lcast_precision.hpp \ + boost/detail/lightweight_mutex.hpp \ + boost/detail/lightweight_test.hpp \ + boost/detail/lightweight_thread.hpp \ + boost/detail/limits.hpp \ + boost/detail/named_template_params.hpp \ + boost/detail/no_exceptions_support.hpp \ + boost/detail/none_t.hpp \ + boost/detail/numeric_traits.hpp \ + boost/detail/ob_call_traits.hpp \ + boost/detail/ob_compressed_pair.hpp \ + boost/detail/quick_allocator.hpp \ + boost/detail/reference_content.hpp \ + boost/detail/scoped_enum_emulation.hpp \ + boost/detail/select_type.hpp \ + boost/detail/sp_typeinfo.hpp \ + boost/detail/templated_streams.hpp \ + boost/detail/utf8_codecvt_facet.hpp \ + boost/detail/workaround.hpp \ + boost/dynamic_bitset.hpp \ + boost/dynamic_bitset_fwd.hpp \ + boost/enable_shared_from_this.hpp \ + boost/exception.hpp \ + boost/exception/all.hpp \ + boost/exception/current_exception_cast.hpp \ + boost/exception/detail/attribute_noreturn.hpp \ + boost/exception/detail/error_info_impl.hpp \ + boost/exception/detail/exception_ptr.hpp \ + boost/exception/detail/is_output_streamable.hpp \ + boost/exception/detail/object_hex_dump.hpp \ + boost/exception/detail/type_info.hpp \ + boost/exception/diagnostic_information.hpp \ + boost/exception/enable_current_exception.hpp \ + boost/exception/enable_error_info.hpp \ + boost/exception/errinfo_api_function.hpp \ + boost/exception/errinfo_at_line.hpp \ + boost/exception/errinfo_errno.hpp \ + boost/exception/errinfo_file_handle.hpp \ + boost/exception/errinfo_file_name.hpp \ + boost/exception/errinfo_file_open_mode.hpp \ + boost/exception/errinfo_nested_exception.hpp \ + boost/exception/errinfo_type_info_name.hpp \ + boost/exception/error_info.hpp \ + boost/exception/exception.hpp \ + boost/exception/get_error_info.hpp \ + boost/exception/info.hpp \ + boost/exception/info_tuple.hpp \ + boost/exception/to_string.hpp \ + boost/exception/to_string_stub.hpp \ + boost/exception_ptr.hpp \ + boost/filesystem.hpp \ + boost/filesystem/config.hpp \ + boost/filesystem/convenience.hpp \ + boost/filesystem/exception.hpp \ + boost/filesystem/fstream.hpp \ + boost/filesystem/operations.hpp \ + boost/filesystem/path.hpp \ + boost/filesystem/v2/config.hpp \ + boost/filesystem/v2/convenience.hpp \ + boost/filesystem/v2/exception.hpp \ + boost/filesystem/v2/fstream.hpp \ + boost/filesystem/v2/operations.hpp \ + boost/filesystem/v2/path.hpp \ + boost/flyweight.hpp \ + boost/foreach.hpp \ + boost/foreach_fwd.hpp \ + boost/format.hpp \ + boost/format/alt_sstream.hpp \ + boost/format/alt_sstream_impl.hpp \ + boost/format/detail/compat_workarounds.hpp \ + boost/format/detail/config_macros.hpp \ + boost/format/detail/msvc_disambiguater.hpp \ + boost/format/detail/unset_macros.hpp \ + boost/format/detail/workarounds_gcc-2_95.hpp \ + boost/format/detail/workarounds_stlport.hpp \ + boost/format/exceptions.hpp \ + boost/format/feed_args.hpp \ + boost/format/format_class.hpp \ + boost/format/format_fwd.hpp \ + boost/format/format_implementation.hpp \ + boost/format/free_funcs.hpp \ + boost/format/group.hpp \ + boost/format/internals.hpp \ + boost/format/internals_fwd.hpp \ + boost/format/parsing.hpp \ + boost/function.hpp \ + boost/function/detail/function_iterate.hpp \ + boost/function/detail/maybe_include.hpp \ + boost/function/detail/prologue.hpp \ + boost/function/function0.hpp \ + boost/function/function1.hpp \ + boost/function/function10.hpp \ + boost/function/function2.hpp \ + boost/function/function3.hpp \ + boost/function/function4.hpp \ + boost/function/function5.hpp \ + boost/function/function6.hpp \ + boost/function/function7.hpp \ + boost/function/function8.hpp \ + boost/function/function9.hpp \ + boost/function/function_base.hpp \ + boost/function/function_fwd.hpp \ + boost/function/function_template.hpp \ + boost/function/function_typeof.hpp \ + boost/function_equal.hpp \ + boost/function_output_iterator.hpp \ + boost/functional.hpp \ + boost/functional/detail/container_fwd.hpp \ + boost/functional/factory.hpp \ + boost/functional/forward_adapter.hpp \ + boost/functional/hash.hpp \ + boost/functional/hash/detail/float_functions.hpp \ + boost/functional/hash/detail/hash_float.hpp \ + boost/functional/hash/detail/hash_float_generic.hpp \ + boost/functional/hash/detail/hash_float_x86.hpp \ + boost/functional/hash/detail/limits.hpp \ + boost/functional/hash/extensions.hpp \ + boost/functional/hash/hash.hpp \ + boost/functional/hash/hash_fwd.hpp \ + boost/functional/hash_fwd.hpp \ + boost/functional/lightweight_forward_adapter.hpp \ + boost/functional/value_factory.hpp \ + boost/generator_iterator.hpp \ + boost/get_pointer.hpp \ + boost/implicit_cast.hpp \ + boost/indirect_reference.hpp \ + boost/integer.hpp \ + boost/integer/integer_mask.hpp \ + boost/integer/static_log2.hpp \ + boost/integer/static_min_max.hpp \ + boost/integer_fwd.hpp \ + boost/integer_traits.hpp \ + boost/interprocess/allocators/adaptive_pool.hpp \ + boost/interprocess/allocators/allocator.hpp \ + boost/interprocess/allocators/cached_adaptive_pool.hpp \ + boost/interprocess/allocators/cached_node_allocator.hpp \ + boost/interprocess/allocators/detail/adaptive_node_pool.hpp \ + boost/interprocess/allocators/detail/allocator_common.hpp \ + boost/interprocess/allocators/detail/node_pool.hpp \ + boost/interprocess/allocators/detail/node_tools.hpp \ + boost/interprocess/allocators/node_allocator.hpp \ + boost/interprocess/allocators/private_adaptive_pool.hpp \ + boost/interprocess/allocators/private_node_allocator.hpp \ + boost/interprocess/anonymous_shared_memory.hpp \ + boost/interprocess/containers/allocation_type.hpp \ + boost/interprocess/containers/container/container_fwd.hpp \ + boost/interprocess/containers/container/deque.hpp \ + boost/interprocess/containers/container/detail/adaptive_node_pool_impl.hpp \ + boost/interprocess/containers/container/detail/advanced_insert_int.hpp \ + boost/interprocess/containers/container/detail/algorithms.hpp \ + boost/interprocess/containers/container/detail/allocation_type.hpp \ + boost/interprocess/containers/container/detail/config_begin.hpp \ + boost/interprocess/containers/container/detail/config_end.hpp \ + boost/interprocess/containers/container/detail/destroyers.hpp \ + boost/interprocess/containers/container/detail/flat_tree.hpp \ + boost/interprocess/containers/container/detail/iterators.hpp \ + boost/interprocess/containers/container/detail/math_functions.hpp \ + boost/interprocess/containers/container/detail/mpl.hpp \ + boost/interprocess/containers/container/detail/multiallocation_chain.hpp \ + boost/interprocess/containers/container/detail/node_alloc_holder.hpp \ + boost/interprocess/containers/container/detail/node_pool_impl.hpp \ + boost/interprocess/containers/container/detail/pair.hpp \ + boost/interprocess/containers/container/detail/pool_common.hpp \ + boost/interprocess/containers/container/detail/preprocessor.hpp \ + boost/interprocess/containers/container/detail/stored_ref.hpp \ + boost/interprocess/containers/container/detail/transform_iterator.hpp \ + boost/interprocess/containers/container/detail/tree.hpp \ + boost/interprocess/containers/container/detail/type_traits.hpp \ + boost/interprocess/containers/container/detail/utilities.hpp \ + boost/interprocess/containers/container/detail/value_init.hpp \ + boost/interprocess/containers/container/detail/variadic_templates_tools.hpp \ + boost/interprocess/containers/container/detail/version_type.hpp \ + boost/interprocess/containers/container/detail/workaround.hpp \ + boost/interprocess/containers/container/flat_map.hpp \ + boost/interprocess/containers/container/flat_set.hpp \ + boost/interprocess/containers/container/list.hpp \ + boost/interprocess/containers/container/map.hpp \ + boost/interprocess/containers/container/set.hpp \ + boost/interprocess/containers/container/slist.hpp \ + boost/interprocess/containers/container/stable_vector.hpp \ + boost/interprocess/containers/container/string.hpp \ + boost/interprocess/containers/container/vector.hpp \ + boost/interprocess/containers/containers_fwd.hpp \ + boost/interprocess/containers/deque.hpp \ + boost/interprocess/containers/flat_map.hpp \ + boost/interprocess/containers/flat_set.hpp \ + boost/interprocess/containers/list.hpp \ + boost/interprocess/containers/map.hpp \ + boost/interprocess/containers/pair.hpp \ + boost/interprocess/containers/set.hpp \ + boost/interprocess/containers/slist.hpp \ + boost/interprocess/containers/stable_vector.hpp \ + boost/interprocess/containers/string.hpp \ + boost/interprocess/containers/vector.hpp \ + boost/interprocess/containers/version_type.hpp \ + boost/interprocess/creation_tags.hpp \ + boost/interprocess/detail/atomic.hpp \ + boost/interprocess/detail/cast_tags.hpp \ + boost/interprocess/detail/config_begin.hpp \ + boost/interprocess/detail/config_end.hpp \ + boost/interprocess/detail/file_wrapper.hpp \ + boost/interprocess/detail/in_place_interface.hpp \ + boost/interprocess/detail/intermodule_singleton.hpp \ + boost/interprocess/detail/interprocess_tester.hpp \ + boost/interprocess/detail/intersegment_ptr.hpp \ + boost/interprocess/detail/managed_memory_impl.hpp \ + boost/interprocess/detail/managed_multi_shared_memory.hpp \ + boost/interprocess/detail/managed_open_or_create_impl.hpp \ + boost/interprocess/detail/math_functions.hpp \ + boost/interprocess/detail/min_max.hpp \ + boost/interprocess/detail/move.hpp \ + boost/interprocess/detail/mpl.hpp \ + boost/interprocess/detail/multi_segment_services.hpp \ + boost/interprocess/detail/named_proxy.hpp \ + boost/interprocess/detail/os_file_functions.hpp \ + boost/interprocess/detail/os_thread_functions.hpp \ + boost/interprocess/detail/pointer_type.hpp \ + boost/interprocess/detail/posix_time_types_wrk.hpp \ + boost/interprocess/detail/preprocessor.hpp \ + boost/interprocess/detail/ptime_wrk.hpp \ + boost/interprocess/detail/robust_emulation.hpp \ + boost/interprocess/detail/segment_manager_helper.hpp \ + boost/interprocess/detail/tmp_dir_helpers.hpp \ + boost/interprocess/detail/transform_iterator.hpp \ + boost/interprocess/detail/type_traits.hpp \ + boost/interprocess/detail/utilities.hpp \ + boost/interprocess/detail/variadic_templates_tools.hpp \ + boost/interprocess/detail/win32_api.hpp \ + boost/interprocess/detail/workaround.hpp \ + boost/interprocess/detail/xsi_shared_memory.hpp \ + boost/interprocess/detail/xsi_shared_memory_device.hpp \ + boost/interprocess/errors.hpp \ + boost/interprocess/exceptions.hpp \ + boost/interprocess/file_mapping.hpp \ + boost/interprocess/indexes/flat_map_index.hpp \ + boost/interprocess/indexes/iset_index.hpp \ + boost/interprocess/indexes/iunordered_set_index.hpp \ + boost/interprocess/indexes/map_index.hpp \ + boost/interprocess/indexes/null_index.hpp \ + boost/interprocess/indexes/unordered_map_index.hpp \ + boost/interprocess/interprocess_fwd.hpp \ + boost/interprocess/ipc/message_queue.hpp \ + boost/interprocess/managed_external_buffer.hpp \ + boost/interprocess/managed_heap_memory.hpp \ + boost/interprocess/managed_mapped_file.hpp \ + boost/interprocess/managed_shared_memory.hpp \ + boost/interprocess/managed_windows_shared_memory.hpp \ + boost/interprocess/mapped_region.hpp \ + boost/interprocess/mem_algo/detail/mem_algo_common.hpp \ + boost/interprocess/mem_algo/detail/multi_simple_seq_fit.hpp \ + boost/interprocess/mem_algo/detail/multi_simple_seq_fit_impl.hpp \ + boost/interprocess/mem_algo/detail/simple_seq_fit_impl.hpp \ + boost/interprocess/mem_algo/rbtree_best_fit.hpp \ + boost/interprocess/mem_algo/simple_seq_fit.hpp \ + boost/interprocess/offset_ptr.hpp \ + boost/interprocess/permissions.hpp \ + boost/interprocess/segment_manager.hpp \ + boost/interprocess/shared_memory_object.hpp \ + boost/interprocess/smart_ptr/deleter.hpp \ + boost/interprocess/smart_ptr/detail/bad_weak_ptr.hpp \ + boost/interprocess/smart_ptr/detail/shared_count.hpp \ + boost/interprocess/smart_ptr/detail/sp_counted_base.hpp \ + boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp \ + boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp \ + boost/interprocess/smart_ptr/enable_shared_from_this.hpp \ + boost/interprocess/smart_ptr/intrusive_ptr.hpp \ + boost/interprocess/smart_ptr/scoped_ptr.hpp \ + boost/interprocess/smart_ptr/shared_ptr.hpp \ + boost/interprocess/smart_ptr/unique_ptr.hpp \ + boost/interprocess/smart_ptr/weak_ptr.hpp \ + boost/interprocess/streams/bufferstream.hpp \ + boost/interprocess/streams/vectorstream.hpp \ + boost/interprocess/sync/emulation/interprocess_barrier.hpp \ + boost/interprocess/sync/emulation/interprocess_condition.hpp \ + boost/interprocess/sync/emulation/interprocess_semaphore.hpp \ + boost/interprocess/sync/emulation/mutex.hpp \ + boost/interprocess/sync/emulation/named_creation_functor.hpp \ + boost/interprocess/sync/emulation/recursive_mutex.hpp \ + boost/interprocess/sync/file_lock.hpp \ + boost/interprocess/sync/interprocess_barrier.hpp \ + boost/interprocess/sync/interprocess_condition.hpp \ + boost/interprocess/sync/interprocess_mutex.hpp \ + boost/interprocess/sync/interprocess_recursive_mutex.hpp \ + boost/interprocess/sync/interprocess_semaphore.hpp \ + boost/interprocess/sync/interprocess_upgradable_mutex.hpp \ + boost/interprocess/sync/lock_options.hpp \ + boost/interprocess/sync/mutex_family.hpp \ + boost/interprocess/sync/named_condition.hpp \ + boost/interprocess/sync/named_mutex.hpp \ + boost/interprocess/sync/named_recursive_mutex.hpp \ + boost/interprocess/sync/named_semaphore.hpp \ + boost/interprocess/sync/named_upgradable_mutex.hpp \ + boost/interprocess/sync/null_mutex.hpp \ + boost/interprocess/sync/posix/interprocess_barrier.hpp \ + boost/interprocess/sync/posix/interprocess_condition.hpp \ + boost/interprocess/sync/posix/interprocess_mutex.hpp \ + boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp \ + boost/interprocess/sync/posix/interprocess_semaphore.hpp \ + boost/interprocess/sync/posix/pthread_helpers.hpp \ + boost/interprocess/sync/posix/ptime_to_timespec.hpp \ + boost/interprocess/sync/posix/semaphore_wrapper.hpp \ + boost/interprocess/sync/scoped_lock.hpp \ + boost/interprocess/sync/sharable_lock.hpp \ + boost/interprocess/sync/upgradable_lock.hpp \ + boost/interprocess/sync/xsi/advanced_xsi_semaphore.hpp \ + boost/interprocess/sync/xsi/simple_xsi_semaphore.hpp \ + boost/interprocess/sync/xsi/xsi_named_mutex.hpp \ + boost/interprocess/windows_shared_memory.hpp \ + boost/intrusive_ptr.hpp \ + boost/io/ios_state.hpp \ + boost/io_fwd.hpp \ + boost/is_placeholder.hpp \ + boost/iterator.hpp \ + boost/iterator/counting_iterator.hpp \ + boost/iterator/detail/any_conversion_eater.hpp \ + boost/iterator/detail/config_def.hpp \ + boost/iterator/detail/config_undef.hpp \ + boost/iterator/detail/enable_if.hpp \ + boost/iterator/detail/facade_iterator_category.hpp \ + boost/iterator/detail/minimum_category.hpp \ + boost/iterator/filter_iterator.hpp \ + boost/iterator/indirect_iterator.hpp \ + boost/iterator/interoperable.hpp \ + boost/iterator/is_lvalue_iterator.hpp \ + boost/iterator/is_readable_iterator.hpp \ + boost/iterator/iterator_adaptor.hpp \ + boost/iterator/iterator_archetypes.hpp \ + boost/iterator/iterator_categories.hpp \ + boost/iterator/iterator_concepts.hpp \ + boost/iterator/iterator_facade.hpp \ + boost/iterator/iterator_traits.hpp \ + boost/iterator/new_iterator_tests.hpp \ + boost/iterator/permutation_iterator.hpp \ + boost/iterator/reverse_iterator.hpp \ + boost/iterator/transform_iterator.hpp \ + boost/iterator/zip_iterator.hpp \ + boost/iterator_adaptors.hpp \ + boost/last_value.hpp \ + boost/lexical_cast.hpp \ + boost/limits.hpp \ + boost/make_shared.hpp \ + boost/math_fwd.hpp \ + boost/mem_fn.hpp \ + boost/memory_order.hpp \ + boost/mpi.hpp \ + boost/mpl/O1_size.hpp \ + boost/mpl/O1_size_fwd.hpp \ + boost/mpl/accumulate.hpp \ + boost/mpl/advance.hpp \ + boost/mpl/advance_fwd.hpp \ + boost/mpl/alias.hpp \ + boost/mpl/always.hpp \ + boost/mpl/and.hpp \ + boost/mpl/apply.hpp \ + boost/mpl/apply_fwd.hpp \ + boost/mpl/apply_wrap.hpp \ + boost/mpl/arg.hpp \ + boost/mpl/arg_fwd.hpp \ + boost/mpl/arithmetic.hpp \ + boost/mpl/as_sequence.hpp \ + boost/mpl/assert.hpp \ + boost/mpl/at.hpp \ + boost/mpl/at_fwd.hpp \ + boost/mpl/aux_/O1_size_impl.hpp \ + boost/mpl/aux_/adl_barrier.hpp \ + boost/mpl/aux_/advance_backward.hpp \ + boost/mpl/aux_/advance_forward.hpp \ + boost/mpl/aux_/apply_1st.hpp \ + boost/mpl/aux_/arg_typedef.hpp \ + boost/mpl/aux_/arithmetic_op.hpp \ + boost/mpl/aux_/arity.hpp \ + boost/mpl/aux_/arity_spec.hpp \ + boost/mpl/aux_/at_impl.hpp \ + boost/mpl/aux_/back_impl.hpp \ + boost/mpl/aux_/basic_bind.hpp \ + boost/mpl/aux_/begin_end_impl.hpp \ + boost/mpl/aux_/clear_impl.hpp \ + boost/mpl/aux_/common_name_wknd.hpp \ + boost/mpl/aux_/comparison_op.hpp \ + boost/mpl/aux_/config/adl.hpp \ + boost/mpl/aux_/config/arrays.hpp \ + boost/mpl/aux_/config/bcc.hpp \ + boost/mpl/aux_/config/bind.hpp \ + boost/mpl/aux_/config/compiler.hpp \ + boost/mpl/aux_/config/ctps.hpp \ + boost/mpl/aux_/config/dependent_nttp.hpp \ + boost/mpl/aux_/config/dmc_ambiguous_ctps.hpp \ + boost/mpl/aux_/config/dtp.hpp \ + boost/mpl/aux_/config/eti.hpp \ + boost/mpl/aux_/config/forwarding.hpp \ + boost/mpl/aux_/config/gcc.hpp \ + boost/mpl/aux_/config/has_apply.hpp \ + boost/mpl/aux_/config/has_xxx.hpp \ + boost/mpl/aux_/config/integral.hpp \ + boost/mpl/aux_/config/intel.hpp \ + boost/mpl/aux_/config/lambda.hpp \ + boost/mpl/aux_/config/msvc.hpp \ + boost/mpl/aux_/config/msvc_typename.hpp \ + boost/mpl/aux_/config/nttp.hpp \ + boost/mpl/aux_/config/operators.hpp \ + boost/mpl/aux_/config/overload_resolution.hpp \ + boost/mpl/aux_/config/pp_counter.hpp \ + boost/mpl/aux_/config/preprocessor.hpp \ + boost/mpl/aux_/config/static_constant.hpp \ + boost/mpl/aux_/config/ttp.hpp \ + boost/mpl/aux_/config/typeof.hpp \ + boost/mpl/aux_/config/use_preprocessed.hpp \ + boost/mpl/aux_/config/workaround.hpp \ + boost/mpl/aux_/contains_impl.hpp \ + boost/mpl/aux_/count_args.hpp \ + boost/mpl/aux_/count_impl.hpp \ + boost/mpl/aux_/empty_impl.hpp \ + boost/mpl/aux_/erase_impl.hpp \ + boost/mpl/aux_/erase_key_impl.hpp \ + boost/mpl/aux_/filter_iter.hpp \ + boost/mpl/aux_/find_if_pred.hpp \ + boost/mpl/aux_/fold_impl.hpp \ + boost/mpl/aux_/fold_impl_body.hpp \ + boost/mpl/aux_/fold_op.hpp \ + boost/mpl/aux_/fold_pred.hpp \ + boost/mpl/aux_/front_impl.hpp \ + boost/mpl/aux_/full_lambda.hpp \ + boost/mpl/aux_/has_apply.hpp \ + boost/mpl/aux_/has_begin.hpp \ + boost/mpl/aux_/has_key_impl.hpp \ + boost/mpl/aux_/has_rebind.hpp \ + boost/mpl/aux_/has_size.hpp \ + boost/mpl/aux_/has_tag.hpp \ + boost/mpl/aux_/has_type.hpp \ + boost/mpl/aux_/include_preprocessed.hpp \ + boost/mpl/aux_/insert_impl.hpp \ + boost/mpl/aux_/insert_range_impl.hpp \ + boost/mpl/aux_/inserter_algorithm.hpp \ + boost/mpl/aux_/integral_wrapper.hpp \ + boost/mpl/aux_/is_msvc_eti_arg.hpp \ + boost/mpl/aux_/iter_apply.hpp \ + boost/mpl/aux_/iter_fold_if_impl.hpp \ + boost/mpl/aux_/iter_fold_impl.hpp \ + boost/mpl/aux_/iter_push_front.hpp \ + boost/mpl/aux_/joint_iter.hpp \ + boost/mpl/aux_/lambda_arity_param.hpp \ + boost/mpl/aux_/lambda_no_ctps.hpp \ + boost/mpl/aux_/lambda_spec.hpp \ + boost/mpl/aux_/lambda_support.hpp \ + boost/mpl/aux_/largest_int.hpp \ + boost/mpl/aux_/logical_op.hpp \ + boost/mpl/aux_/msvc_dtw.hpp \ + boost/mpl/aux_/msvc_eti_base.hpp \ + boost/mpl/aux_/msvc_is_class.hpp \ + boost/mpl/aux_/msvc_never_true.hpp \ + boost/mpl/aux_/msvc_type.hpp \ + boost/mpl/aux_/na.hpp \ + boost/mpl/aux_/na_assert.hpp \ + boost/mpl/aux_/na_fwd.hpp \ + boost/mpl/aux_/na_spec.hpp \ + boost/mpl/aux_/nested_type_wknd.hpp \ + boost/mpl/aux_/nttp_decl.hpp \ + boost/mpl/aux_/numeric_cast_utils.hpp \ + boost/mpl/aux_/numeric_op.hpp \ + boost/mpl/aux_/order_impl.hpp \ + boost/mpl/aux_/overload_names.hpp \ + boost/mpl/aux_/partition_op.hpp \ + boost/mpl/aux_/pop_back_impl.hpp \ + boost/mpl/aux_/pop_front_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/bcc/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/bcc/and.hpp \ + boost/mpl/aux_/preprocessed/bcc/apply.hpp \ + boost/mpl/aux_/preprocessed/bcc/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/bcc/arg.hpp \ + boost/mpl/aux_/preprocessed/bcc/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/bcc/bind.hpp \ + boost/mpl/aux_/preprocessed/bcc/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc/bitand.hpp \ + boost/mpl/aux_/preprocessed/bcc/bitor.hpp \ + boost/mpl/aux_/preprocessed/bcc/bitxor.hpp \ + boost/mpl/aux_/preprocessed/bcc/deque.hpp \ + boost/mpl/aux_/preprocessed/bcc/divides.hpp \ + boost/mpl/aux_/preprocessed/bcc/equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/bcc/greater.hpp \ + boost/mpl/aux_/preprocessed/bcc/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc/inherit.hpp \ + boost/mpl/aux_/preprocessed/bcc/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/bcc/less.hpp \ + boost/mpl/aux_/preprocessed/bcc/less_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc/list.hpp \ + boost/mpl/aux_/preprocessed/bcc/list_c.hpp \ + boost/mpl/aux_/preprocessed/bcc/map.hpp \ + boost/mpl/aux_/preprocessed/bcc/minus.hpp \ + boost/mpl/aux_/preprocessed/bcc/modulus.hpp \ + boost/mpl/aux_/preprocessed/bcc/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc/or.hpp \ + boost/mpl/aux_/preprocessed/bcc/placeholders.hpp \ + boost/mpl/aux_/preprocessed/bcc/plus.hpp \ + boost/mpl/aux_/preprocessed/bcc/quote.hpp \ + boost/mpl/aux_/preprocessed/bcc/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/set.hpp \ + boost/mpl/aux_/preprocessed/bcc/set_c.hpp \ + boost/mpl/aux_/preprocessed/bcc/shift_left.hpp \ + boost/mpl/aux_/preprocessed/bcc/shift_right.hpp \ + boost/mpl/aux_/preprocessed/bcc/template_arity.hpp \ + boost/mpl/aux_/preprocessed/bcc/times.hpp \ + boost/mpl/aux_/preprocessed/bcc/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/bcc/vector.hpp \ + boost/mpl/aux_/preprocessed/bcc/vector_c.hpp \ + boost/mpl/aux_/preprocessed/bcc551/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/bcc551/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/bcc551/and.hpp \ + boost/mpl/aux_/preprocessed/bcc551/apply.hpp \ + boost/mpl/aux_/preprocessed/bcc551/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc551/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/bcc551/arg.hpp \ + boost/mpl/aux_/preprocessed/bcc551/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bind.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bitand.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bitor.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bitxor.hpp \ + boost/mpl/aux_/preprocessed/bcc551/deque.hpp \ + boost/mpl/aux_/preprocessed/bcc551/divides.hpp \ + boost/mpl/aux_/preprocessed/bcc551/equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc551/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/bcc551/greater.hpp \ + boost/mpl/aux_/preprocessed/bcc551/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc551/inherit.hpp \ + boost/mpl/aux_/preprocessed/bcc551/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/bcc551/less.hpp \ + boost/mpl/aux_/preprocessed/bcc551/less_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc551/list.hpp \ + boost/mpl/aux_/preprocessed/bcc551/list_c.hpp \ + boost/mpl/aux_/preprocessed/bcc551/map.hpp \ + boost/mpl/aux_/preprocessed/bcc551/minus.hpp \ + boost/mpl/aux_/preprocessed/bcc551/modulus.hpp \ + boost/mpl/aux_/preprocessed/bcc551/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc551/or.hpp \ + boost/mpl/aux_/preprocessed/bcc551/placeholders.hpp \ + boost/mpl/aux_/preprocessed/bcc551/plus.hpp \ + boost/mpl/aux_/preprocessed/bcc551/quote.hpp \ + boost/mpl/aux_/preprocessed/bcc551/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/set.hpp \ + boost/mpl/aux_/preprocessed/bcc551/set_c.hpp \ + boost/mpl/aux_/preprocessed/bcc551/shift_left.hpp \ + boost/mpl/aux_/preprocessed/bcc551/shift_right.hpp \ + boost/mpl/aux_/preprocessed/bcc551/template_arity.hpp \ + boost/mpl/aux_/preprocessed/bcc551/times.hpp \ + boost/mpl/aux_/preprocessed/bcc551/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/bcc551/vector.hpp \ + boost/mpl/aux_/preprocessed/bcc551/vector_c.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/and.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/apply.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/arg.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bind.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bitand.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bitor.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bitxor.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/deque.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/divides.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/greater.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/inherit.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/less.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/less_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/list.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/list_c.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/map.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/minus.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/modulus.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/or.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/placeholders.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/plus.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/quote.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/set.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/set_c.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/shift_left.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/shift_right.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/template_arity.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/times.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/vector.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/vector_c.hpp \ + boost/mpl/aux_/preprocessed/dmc/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/dmc/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/dmc/and.hpp \ + boost/mpl/aux_/preprocessed/dmc/apply.hpp \ + boost/mpl/aux_/preprocessed/dmc/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/dmc/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/dmc/arg.hpp \ + boost/mpl/aux_/preprocessed/dmc/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/dmc/bind.hpp \ + boost/mpl/aux_/preprocessed/dmc/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/dmc/bitand.hpp \ + boost/mpl/aux_/preprocessed/dmc/bitor.hpp \ + boost/mpl/aux_/preprocessed/dmc/bitxor.hpp \ + boost/mpl/aux_/preprocessed/dmc/deque.hpp \ + boost/mpl/aux_/preprocessed/dmc/divides.hpp \ + boost/mpl/aux_/preprocessed/dmc/equal_to.hpp \ + boost/mpl/aux_/preprocessed/dmc/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/dmc/greater.hpp \ + boost/mpl/aux_/preprocessed/dmc/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/dmc/inherit.hpp \ + boost/mpl/aux_/preprocessed/dmc/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/dmc/less.hpp \ + boost/mpl/aux_/preprocessed/dmc/less_equal.hpp \ + boost/mpl/aux_/preprocessed/dmc/list.hpp \ + boost/mpl/aux_/preprocessed/dmc/list_c.hpp \ + boost/mpl/aux_/preprocessed/dmc/map.hpp \ + boost/mpl/aux_/preprocessed/dmc/minus.hpp \ + boost/mpl/aux_/preprocessed/dmc/modulus.hpp \ + boost/mpl/aux_/preprocessed/dmc/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/dmc/or.hpp \ + boost/mpl/aux_/preprocessed/dmc/placeholders.hpp \ + boost/mpl/aux_/preprocessed/dmc/plus.hpp \ + boost/mpl/aux_/preprocessed/dmc/quote.hpp \ + boost/mpl/aux_/preprocessed/dmc/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/set.hpp \ + boost/mpl/aux_/preprocessed/dmc/set_c.hpp \ + boost/mpl/aux_/preprocessed/dmc/shift_left.hpp \ + boost/mpl/aux_/preprocessed/dmc/shift_right.hpp \ + boost/mpl/aux_/preprocessed/dmc/template_arity.hpp \ + boost/mpl/aux_/preprocessed/dmc/times.hpp \ + boost/mpl/aux_/preprocessed/dmc/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/dmc/vector.hpp \ + boost/mpl/aux_/preprocessed/dmc/vector_c.hpp \ + boost/mpl/aux_/preprocessed/gcc/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/gcc/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/gcc/and.hpp \ + boost/mpl/aux_/preprocessed/gcc/apply.hpp \ + boost/mpl/aux_/preprocessed/gcc/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/gcc/arg.hpp \ + boost/mpl/aux_/preprocessed/gcc/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/gcc/bind.hpp \ + boost/mpl/aux_/preprocessed/gcc/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/gcc/bitand.hpp \ + boost/mpl/aux_/preprocessed/gcc/bitor.hpp \ + boost/mpl/aux_/preprocessed/gcc/bitxor.hpp \ + boost/mpl/aux_/preprocessed/gcc/deque.hpp \ + boost/mpl/aux_/preprocessed/gcc/divides.hpp \ + boost/mpl/aux_/preprocessed/gcc/equal_to.hpp \ + boost/mpl/aux_/preprocessed/gcc/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/gcc/greater.hpp \ + boost/mpl/aux_/preprocessed/gcc/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/gcc/inherit.hpp \ + boost/mpl/aux_/preprocessed/gcc/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/gcc/less.hpp \ + boost/mpl/aux_/preprocessed/gcc/less_equal.hpp \ + boost/mpl/aux_/preprocessed/gcc/list.hpp \ + boost/mpl/aux_/preprocessed/gcc/list_c.hpp \ + boost/mpl/aux_/preprocessed/gcc/map.hpp \ + boost/mpl/aux_/preprocessed/gcc/minus.hpp \ + boost/mpl/aux_/preprocessed/gcc/modulus.hpp \ + boost/mpl/aux_/preprocessed/gcc/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/gcc/or.hpp \ + boost/mpl/aux_/preprocessed/gcc/placeholders.hpp \ + boost/mpl/aux_/preprocessed/gcc/plus.hpp \ + boost/mpl/aux_/preprocessed/gcc/quote.hpp \ + boost/mpl/aux_/preprocessed/gcc/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/set.hpp \ + boost/mpl/aux_/preprocessed/gcc/set_c.hpp \ + boost/mpl/aux_/preprocessed/gcc/shift_left.hpp \ + boost/mpl/aux_/preprocessed/gcc/shift_right.hpp \ + boost/mpl/aux_/preprocessed/gcc/template_arity.hpp \ + boost/mpl/aux_/preprocessed/gcc/times.hpp \ + boost/mpl/aux_/preprocessed/gcc/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/gcc/vector.hpp \ + boost/mpl/aux_/preprocessed/gcc/vector_c.hpp \ + boost/mpl/aux_/preprocessed/msvc60/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/msvc60/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/msvc60/and.hpp \ + boost/mpl/aux_/preprocessed/msvc60/apply.hpp \ + boost/mpl/aux_/preprocessed/msvc60/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc60/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/msvc60/arg.hpp \ + boost/mpl/aux_/preprocessed/msvc60/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bind.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bitand.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bitor.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bitxor.hpp \ + boost/mpl/aux_/preprocessed/msvc60/deque.hpp \ + boost/mpl/aux_/preprocessed/msvc60/divides.hpp \ + boost/mpl/aux_/preprocessed/msvc60/equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc60/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/msvc60/greater.hpp \ + boost/mpl/aux_/preprocessed/msvc60/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc60/inherit.hpp \ + boost/mpl/aux_/preprocessed/msvc60/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/msvc60/less.hpp \ + boost/mpl/aux_/preprocessed/msvc60/less_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc60/list.hpp \ + boost/mpl/aux_/preprocessed/msvc60/list_c.hpp \ + boost/mpl/aux_/preprocessed/msvc60/map.hpp \ + boost/mpl/aux_/preprocessed/msvc60/minus.hpp \ + boost/mpl/aux_/preprocessed/msvc60/modulus.hpp \ + boost/mpl/aux_/preprocessed/msvc60/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc60/or.hpp \ + boost/mpl/aux_/preprocessed/msvc60/placeholders.hpp \ + boost/mpl/aux_/preprocessed/msvc60/plus.hpp \ + boost/mpl/aux_/preprocessed/msvc60/quote.hpp \ + boost/mpl/aux_/preprocessed/msvc60/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/set.hpp \ + boost/mpl/aux_/preprocessed/msvc60/set_c.hpp \ + boost/mpl/aux_/preprocessed/msvc60/shift_left.hpp \ + boost/mpl/aux_/preprocessed/msvc60/shift_right.hpp \ + boost/mpl/aux_/preprocessed/msvc60/template_arity.hpp \ + boost/mpl/aux_/preprocessed/msvc60/times.hpp \ + boost/mpl/aux_/preprocessed/msvc60/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/msvc60/vector.hpp \ + boost/mpl/aux_/preprocessed/msvc60/vector_c.hpp \ + boost/mpl/aux_/preprocessed/msvc70/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/msvc70/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/msvc70/and.hpp \ + boost/mpl/aux_/preprocessed/msvc70/apply.hpp \ + boost/mpl/aux_/preprocessed/msvc70/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc70/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/msvc70/arg.hpp \ + boost/mpl/aux_/preprocessed/msvc70/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bind.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bitand.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bitor.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bitxor.hpp \ + boost/mpl/aux_/preprocessed/msvc70/deque.hpp \ + boost/mpl/aux_/preprocessed/msvc70/divides.hpp \ + boost/mpl/aux_/preprocessed/msvc70/equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc70/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/msvc70/greater.hpp \ + boost/mpl/aux_/preprocessed/msvc70/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc70/inherit.hpp \ + boost/mpl/aux_/preprocessed/msvc70/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/msvc70/less.hpp \ + boost/mpl/aux_/preprocessed/msvc70/less_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc70/list.hpp \ + boost/mpl/aux_/preprocessed/msvc70/list_c.hpp \ + boost/mpl/aux_/preprocessed/msvc70/map.hpp \ + boost/mpl/aux_/preprocessed/msvc70/minus.hpp \ + boost/mpl/aux_/preprocessed/msvc70/modulus.hpp \ + boost/mpl/aux_/preprocessed/msvc70/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc70/or.hpp \ + boost/mpl/aux_/preprocessed/msvc70/placeholders.hpp \ + boost/mpl/aux_/preprocessed/msvc70/plus.hpp \ + boost/mpl/aux_/preprocessed/msvc70/quote.hpp \ + boost/mpl/aux_/preprocessed/msvc70/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/set.hpp \ + boost/mpl/aux_/preprocessed/msvc70/set_c.hpp \ + boost/mpl/aux_/preprocessed/msvc70/shift_left.hpp \ + boost/mpl/aux_/preprocessed/msvc70/shift_right.hpp \ + boost/mpl/aux_/preprocessed/msvc70/template_arity.hpp \ + boost/mpl/aux_/preprocessed/msvc70/times.hpp \ + boost/mpl/aux_/preprocessed/msvc70/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/msvc70/vector.hpp \ + boost/mpl/aux_/preprocessed/msvc70/vector_c.hpp \ + boost/mpl/aux_/preprocessed/mwcw/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/mwcw/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/mwcw/and.hpp \ + boost/mpl/aux_/preprocessed/mwcw/apply.hpp \ + boost/mpl/aux_/preprocessed/mwcw/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/mwcw/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/mwcw/arg.hpp \ + boost/mpl/aux_/preprocessed/mwcw/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bind.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bitand.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bitor.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bitxor.hpp \ + boost/mpl/aux_/preprocessed/mwcw/deque.hpp \ + boost/mpl/aux_/preprocessed/mwcw/divides.hpp \ + boost/mpl/aux_/preprocessed/mwcw/equal_to.hpp \ + boost/mpl/aux_/preprocessed/mwcw/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/mwcw/greater.hpp \ + boost/mpl/aux_/preprocessed/mwcw/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/mwcw/inherit.hpp \ + boost/mpl/aux_/preprocessed/mwcw/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/mwcw/less.hpp \ + boost/mpl/aux_/preprocessed/mwcw/less_equal.hpp \ + boost/mpl/aux_/preprocessed/mwcw/list.hpp \ + boost/mpl/aux_/preprocessed/mwcw/list_c.hpp \ + boost/mpl/aux_/preprocessed/mwcw/map.hpp \ + boost/mpl/aux_/preprocessed/mwcw/minus.hpp \ + boost/mpl/aux_/preprocessed/mwcw/modulus.hpp \ + boost/mpl/aux_/preprocessed/mwcw/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/mwcw/or.hpp \ + boost/mpl/aux_/preprocessed/mwcw/placeholders.hpp \ + boost/mpl/aux_/preprocessed/mwcw/plus.hpp \ + boost/mpl/aux_/preprocessed/mwcw/quote.hpp \ + boost/mpl/aux_/preprocessed/mwcw/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/set.hpp \ + boost/mpl/aux_/preprocessed/mwcw/set_c.hpp \ + boost/mpl/aux_/preprocessed/mwcw/shift_left.hpp \ + boost/mpl/aux_/preprocessed/mwcw/shift_right.hpp \ + boost/mpl/aux_/preprocessed/mwcw/template_arity.hpp \ + boost/mpl/aux_/preprocessed/mwcw/times.hpp \ + boost/mpl/aux_/preprocessed/mwcw/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/mwcw/vector.hpp \ + boost/mpl/aux_/preprocessed/mwcw/vector_c.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/and.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/apply.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/arg.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bind.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bitand.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bitor.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bitxor.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/deque.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/divides.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/greater.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/inherit.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/less.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/less_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/list.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/list_c.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/map.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/minus.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/modulus.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/or.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/placeholders.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/plus.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/quote.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/set.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/set_c.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/shift_left.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/shift_right.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/template_arity.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/times.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/vector.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/vector_c.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/and.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/apply.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/arg.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bind.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bitand.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bitor.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bitxor.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/deque.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/divides.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/greater.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/inherit.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/less.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/less_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/list.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/list_c.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/map.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/minus.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/modulus.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/or.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/placeholders.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/plus.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/quote.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/set.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/set_c.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/shift_left.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/shift_right.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/template_arity.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/times.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/vector.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/vector_c.hpp \ + boost/mpl/aux_/preprocessed/plain/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/plain/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/plain/and.hpp \ + boost/mpl/aux_/preprocessed/plain/apply.hpp \ + boost/mpl/aux_/preprocessed/plain/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/plain/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/plain/arg.hpp \ + boost/mpl/aux_/preprocessed/plain/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/plain/bind.hpp \ + boost/mpl/aux_/preprocessed/plain/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/plain/bitand.hpp \ + boost/mpl/aux_/preprocessed/plain/bitor.hpp \ + boost/mpl/aux_/preprocessed/plain/bitxor.hpp \ + boost/mpl/aux_/preprocessed/plain/deque.hpp \ + boost/mpl/aux_/preprocessed/plain/divides.hpp \ + boost/mpl/aux_/preprocessed/plain/equal_to.hpp \ + boost/mpl/aux_/preprocessed/plain/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/plain/greater.hpp \ + boost/mpl/aux_/preprocessed/plain/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/plain/inherit.hpp \ + boost/mpl/aux_/preprocessed/plain/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/plain/less.hpp \ + boost/mpl/aux_/preprocessed/plain/less_equal.hpp \ + boost/mpl/aux_/preprocessed/plain/list.hpp \ + boost/mpl/aux_/preprocessed/plain/list_c.hpp \ + boost/mpl/aux_/preprocessed/plain/map.hpp \ + boost/mpl/aux_/preprocessed/plain/minus.hpp \ + boost/mpl/aux_/preprocessed/plain/modulus.hpp \ + boost/mpl/aux_/preprocessed/plain/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/plain/or.hpp \ + boost/mpl/aux_/preprocessed/plain/placeholders.hpp \ + boost/mpl/aux_/preprocessed/plain/plus.hpp \ + boost/mpl/aux_/preprocessed/plain/quote.hpp \ + boost/mpl/aux_/preprocessed/plain/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/set.hpp \ + boost/mpl/aux_/preprocessed/plain/set_c.hpp \ + boost/mpl/aux_/preprocessed/plain/shift_left.hpp \ + boost/mpl/aux_/preprocessed/plain/shift_right.hpp \ + boost/mpl/aux_/preprocessed/plain/template_arity.hpp \ + boost/mpl/aux_/preprocessed/plain/times.hpp \ + boost/mpl/aux_/preprocessed/plain/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/plain/vector.hpp \ + boost/mpl/aux_/preprocessed/plain/vector_c.hpp \ + boost/mpl/aux_/preprocessor/add.hpp \ + boost/mpl/aux_/preprocessor/def_params_tail.hpp \ + boost/mpl/aux_/preprocessor/default_params.hpp \ + boost/mpl/aux_/preprocessor/enum.hpp \ + boost/mpl/aux_/preprocessor/ext_params.hpp \ + boost/mpl/aux_/preprocessor/filter_params.hpp \ + boost/mpl/aux_/preprocessor/is_seq.hpp \ + boost/mpl/aux_/preprocessor/params.hpp \ + boost/mpl/aux_/preprocessor/partial_spec_params.hpp \ + boost/mpl/aux_/preprocessor/range.hpp \ + boost/mpl/aux_/preprocessor/repeat.hpp \ + boost/mpl/aux_/preprocessor/sub.hpp \ + boost/mpl/aux_/preprocessor/token_equal.hpp \ + boost/mpl/aux_/preprocessor/tuple.hpp \ + boost/mpl/aux_/ptr_to_ref.hpp \ + boost/mpl/aux_/push_back_impl.hpp \ + boost/mpl/aux_/push_front_impl.hpp \ + boost/mpl/aux_/range_c/O1_size.hpp \ + boost/mpl/aux_/range_c/back.hpp \ + boost/mpl/aux_/range_c/empty.hpp \ + boost/mpl/aux_/range_c/front.hpp \ + boost/mpl/aux_/range_c/iterator.hpp \ + boost/mpl/aux_/range_c/size.hpp \ + boost/mpl/aux_/range_c/tag.hpp \ + boost/mpl/aux_/reverse_fold_impl.hpp \ + boost/mpl/aux_/reverse_fold_impl_body.hpp \ + boost/mpl/aux_/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/sequence_wrapper.hpp \ + boost/mpl/aux_/shift_op.hpp \ + boost/mpl/aux_/single_element_iter.hpp \ + boost/mpl/aux_/size_impl.hpp \ + boost/mpl/aux_/sort_impl.hpp \ + boost/mpl/aux_/static_cast.hpp \ + boost/mpl/aux_/template_arity.hpp \ + boost/mpl/aux_/template_arity_fwd.hpp \ + boost/mpl/aux_/test.hpp \ + boost/mpl/aux_/test/assert.hpp \ + boost/mpl/aux_/test/data.hpp \ + boost/mpl/aux_/test/test_case.hpp \ + boost/mpl/aux_/traits_lambda_spec.hpp \ + boost/mpl/aux_/transform_iter.hpp \ + boost/mpl/aux_/type_wrapper.hpp \ + boost/mpl/aux_/unwrap.hpp \ + boost/mpl/aux_/value_wknd.hpp \ + boost/mpl/aux_/yes_no.hpp \ + boost/mpl/back.hpp \ + boost/mpl/back_fwd.hpp \ + boost/mpl/back_inserter.hpp \ + boost/mpl/base.hpp \ + boost/mpl/begin.hpp \ + boost/mpl/begin_end.hpp \ + boost/mpl/begin_end_fwd.hpp \ + boost/mpl/bind.hpp \ + boost/mpl/bind_fwd.hpp \ + boost/mpl/bitand.hpp \ + boost/mpl/bitor.hpp \ + boost/mpl/bitwise.hpp \ + boost/mpl/bitxor.hpp \ + boost/mpl/bool.hpp \ + boost/mpl/bool_fwd.hpp \ + boost/mpl/char.hpp \ + boost/mpl/char_fwd.hpp \ + boost/mpl/clear.hpp \ + boost/mpl/clear_fwd.hpp \ + boost/mpl/comparison.hpp \ + boost/mpl/contains.hpp \ + boost/mpl/contains_fwd.hpp \ + boost/mpl/copy.hpp \ + boost/mpl/copy_if.hpp \ + boost/mpl/count.hpp \ + boost/mpl/count_fwd.hpp \ + boost/mpl/count_if.hpp \ + boost/mpl/deque.hpp \ + boost/mpl/deref.hpp \ + boost/mpl/distance.hpp \ + boost/mpl/distance_fwd.hpp \ + boost/mpl/divides.hpp \ + boost/mpl/empty.hpp \ + boost/mpl/empty_base.hpp \ + boost/mpl/empty_fwd.hpp \ + boost/mpl/empty_sequence.hpp \ + boost/mpl/end.hpp \ + boost/mpl/equal.hpp \ + boost/mpl/equal_to.hpp \ + boost/mpl/erase.hpp \ + boost/mpl/erase_fwd.hpp \ + boost/mpl/erase_key.hpp \ + boost/mpl/erase_key_fwd.hpp \ + boost/mpl/eval_if.hpp \ + boost/mpl/filter_view.hpp \ + boost/mpl/find.hpp \ + boost/mpl/find_if.hpp \ + boost/mpl/fold.hpp \ + boost/mpl/for_each.hpp \ + boost/mpl/front.hpp \ + boost/mpl/front_fwd.hpp \ + boost/mpl/front_inserter.hpp \ + boost/mpl/greater.hpp \ + boost/mpl/greater_equal.hpp \ + boost/mpl/has_key.hpp \ + boost/mpl/has_key_fwd.hpp \ + boost/mpl/has_xxx.hpp \ + boost/mpl/identity.hpp \ + boost/mpl/if.hpp \ + boost/mpl/index_if.hpp \ + boost/mpl/index_of.hpp \ + boost/mpl/inherit.hpp \ + boost/mpl/inherit_linearly.hpp \ + boost/mpl/insert.hpp \ + boost/mpl/insert_fwd.hpp \ + boost/mpl/insert_range.hpp \ + boost/mpl/insert_range_fwd.hpp \ + boost/mpl/inserter.hpp \ + boost/mpl/int.hpp \ + boost/mpl/int_fwd.hpp \ + boost/mpl/integral_c.hpp \ + boost/mpl/integral_c_fwd.hpp \ + boost/mpl/integral_c_tag.hpp \ + boost/mpl/is_placeholder.hpp \ + boost/mpl/is_sequence.hpp \ + boost/mpl/iter_fold.hpp \ + boost/mpl/iter_fold_if.hpp \ + boost/mpl/iterator_category.hpp \ + boost/mpl/iterator_range.hpp \ + boost/mpl/iterator_tags.hpp \ + boost/mpl/joint_view.hpp \ + boost/mpl/key_type.hpp \ + boost/mpl/key_type_fwd.hpp \ + boost/mpl/lambda.hpp \ + boost/mpl/lambda_fwd.hpp \ + boost/mpl/less.hpp \ + boost/mpl/less_equal.hpp \ + boost/mpl/limits/arity.hpp \ + boost/mpl/limits/list.hpp \ + boost/mpl/limits/map.hpp \ + boost/mpl/limits/set.hpp \ + boost/mpl/limits/string.hpp \ + boost/mpl/limits/unrolling.hpp \ + boost/mpl/limits/vector.hpp \ + boost/mpl/list.hpp \ + boost/mpl/list/aux_/O1_size.hpp \ + boost/mpl/list/aux_/begin_end.hpp \ + boost/mpl/list/aux_/clear.hpp \ + boost/mpl/list/aux_/empty.hpp \ + boost/mpl/list/aux_/front.hpp \ + boost/mpl/list/aux_/include_preprocessed.hpp \ + boost/mpl/list/aux_/item.hpp \ + boost/mpl/list/aux_/iterator.hpp \ + boost/mpl/list/aux_/numbered.hpp \ + boost/mpl/list/aux_/numbered_c.hpp \ + boost/mpl/list/aux_/pop_front.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list10.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list10_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list20.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list20_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list30.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list30_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list40.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list40_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list50.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list50_c.hpp \ + boost/mpl/list/aux_/push_back.hpp \ + boost/mpl/list/aux_/push_front.hpp \ + boost/mpl/list/aux_/size.hpp \ + boost/mpl/list/aux_/tag.hpp \ + boost/mpl/list/list0.hpp \ + boost/mpl/list/list0_c.hpp \ + boost/mpl/list/list10.hpp \ + boost/mpl/list/list10_c.hpp \ + boost/mpl/list/list20.hpp \ + boost/mpl/list/list20_c.hpp \ + boost/mpl/list/list30.hpp \ + boost/mpl/list/list30_c.hpp \ + boost/mpl/list/list40.hpp \ + boost/mpl/list/list40_c.hpp \ + boost/mpl/list/list50.hpp \ + boost/mpl/list/list50_c.hpp \ + boost/mpl/list_c.hpp \ + boost/mpl/logical.hpp \ + boost/mpl/long.hpp \ + boost/mpl/long_fwd.hpp \ + boost/mpl/lower_bound.hpp \ + boost/mpl/map.hpp \ + boost/mpl/map/aux_/at_impl.hpp \ + boost/mpl/map/aux_/begin_end_impl.hpp \ + boost/mpl/map/aux_/clear_impl.hpp \ + boost/mpl/map/aux_/contains_impl.hpp \ + boost/mpl/map/aux_/empty_impl.hpp \ + boost/mpl/map/aux_/erase_impl.hpp \ + boost/mpl/map/aux_/erase_key_impl.hpp \ + boost/mpl/map/aux_/has_key_impl.hpp \ + boost/mpl/map/aux_/include_preprocessed.hpp \ + boost/mpl/map/aux_/insert_impl.hpp \ + boost/mpl/map/aux_/item.hpp \ + boost/mpl/map/aux_/iterator.hpp \ + boost/mpl/map/aux_/key_type_impl.hpp \ + boost/mpl/map/aux_/map0.hpp \ + boost/mpl/map/aux_/numbered.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map10.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map20.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map30.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map40.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map50.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map10.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map20.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map30.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map40.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map50.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map10.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map20.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map30.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map40.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map50.hpp \ + boost/mpl/map/aux_/size_impl.hpp \ + boost/mpl/map/aux_/tag.hpp \ + boost/mpl/map/aux_/value_type_impl.hpp \ + boost/mpl/map/map0.hpp \ + boost/mpl/map/map10.hpp \ + boost/mpl/map/map20.hpp \ + boost/mpl/map/map30.hpp \ + boost/mpl/map/map40.hpp \ + boost/mpl/map/map50.hpp \ + boost/mpl/math/fixed_c.hpp \ + boost/mpl/math/is_even.hpp \ + boost/mpl/math/rational_c.hpp \ + boost/mpl/max.hpp \ + boost/mpl/max_element.hpp \ + boost/mpl/min.hpp \ + boost/mpl/min_element.hpp \ + boost/mpl/min_max.hpp \ + boost/mpl/minus.hpp \ + boost/mpl/modulus.hpp \ + boost/mpl/multiplies.hpp \ + boost/mpl/multiset/aux_/count_impl.hpp \ + boost/mpl/multiset/aux_/insert_impl.hpp \ + boost/mpl/multiset/aux_/item.hpp \ + boost/mpl/multiset/aux_/multiset0.hpp \ + boost/mpl/multiset/aux_/tag.hpp \ + boost/mpl/multiset/multiset0.hpp \ + boost/mpl/negate.hpp \ + boost/mpl/next.hpp \ + boost/mpl/next_prior.hpp \ + boost/mpl/not.hpp \ + boost/mpl/not_equal_to.hpp \ + boost/mpl/numeric_cast.hpp \ + boost/mpl/or.hpp \ + boost/mpl/order.hpp \ + boost/mpl/order_fwd.hpp \ + boost/mpl/pair.hpp \ + boost/mpl/pair_view.hpp \ + boost/mpl/partition.hpp \ + boost/mpl/placeholders.hpp \ + boost/mpl/plus.hpp \ + boost/mpl/pop_back.hpp \ + boost/mpl/pop_back_fwd.hpp \ + boost/mpl/pop_front.hpp \ + boost/mpl/pop_front_fwd.hpp \ + boost/mpl/print.hpp \ + boost/mpl/prior.hpp \ + boost/mpl/protect.hpp \ + boost/mpl/push_back.hpp \ + boost/mpl/push_back_fwd.hpp \ + boost/mpl/push_front.hpp \ + boost/mpl/push_front_fwd.hpp \ + boost/mpl/quote.hpp \ + boost/mpl/range_c.hpp \ + boost/mpl/remove.hpp \ + boost/mpl/remove_if.hpp \ + boost/mpl/replace.hpp \ + boost/mpl/replace_if.hpp \ + boost/mpl/reverse.hpp \ + boost/mpl/reverse_fold.hpp \ + boost/mpl/reverse_iter_fold.hpp \ + boost/mpl/same_as.hpp \ + boost/mpl/sequence_tag.hpp \ + boost/mpl/sequence_tag_fwd.hpp \ + boost/mpl/set.hpp \ + boost/mpl/set/aux_/at_impl.hpp \ + boost/mpl/set/aux_/begin_end_impl.hpp \ + boost/mpl/set/aux_/clear_impl.hpp \ + boost/mpl/set/aux_/empty_impl.hpp \ + boost/mpl/set/aux_/erase_impl.hpp \ + boost/mpl/set/aux_/erase_key_impl.hpp \ + boost/mpl/set/aux_/has_key_impl.hpp \ + boost/mpl/set/aux_/include_preprocessed.hpp \ + boost/mpl/set/aux_/insert_impl.hpp \ + boost/mpl/set/aux_/item.hpp \ + boost/mpl/set/aux_/iterator.hpp \ + boost/mpl/set/aux_/key_type_impl.hpp \ + boost/mpl/set/aux_/numbered.hpp \ + boost/mpl/set/aux_/numbered_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set10.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set10_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set20.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set20_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set30.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set30_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set40.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set40_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set50.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set50_c.hpp \ + boost/mpl/set/aux_/set0.hpp \ + boost/mpl/set/aux_/size_impl.hpp \ + boost/mpl/set/aux_/tag.hpp \ + boost/mpl/set/aux_/value_type_impl.hpp \ + boost/mpl/set/set0.hpp \ + boost/mpl/set/set0_c.hpp \ + boost/mpl/set/set10.hpp \ + boost/mpl/set/set10_c.hpp \ + boost/mpl/set/set20.hpp \ + boost/mpl/set/set20_c.hpp \ + boost/mpl/set/set30.hpp \ + boost/mpl/set/set30_c.hpp \ + boost/mpl/set/set40.hpp \ + boost/mpl/set/set40_c.hpp \ + boost/mpl/set/set50.hpp \ + boost/mpl/set/set50_c.hpp \ + boost/mpl/set_c.hpp \ + boost/mpl/shift_left.hpp \ + boost/mpl/shift_right.hpp \ + boost/mpl/single_view.hpp \ + boost/mpl/size.hpp \ + boost/mpl/size_fwd.hpp \ + boost/mpl/size_t.hpp \ + boost/mpl/size_t_fwd.hpp \ + boost/mpl/sizeof.hpp \ + boost/mpl/sort.hpp \ + boost/mpl/stable_partition.hpp \ + boost/mpl/string.hpp \ + boost/mpl/switch.hpp \ + boost/mpl/tag.hpp \ + boost/mpl/times.hpp \ + boost/mpl/transform.hpp \ + boost/mpl/transform_view.hpp \ + boost/mpl/unique.hpp \ + boost/mpl/unpack_args.hpp \ + boost/mpl/upper_bound.hpp \ + boost/mpl/value_type.hpp \ + boost/mpl/value_type_fwd.hpp \ + boost/mpl/vector.hpp \ + boost/mpl/vector/aux_/O1_size.hpp \ + boost/mpl/vector/aux_/at.hpp \ + boost/mpl/vector/aux_/back.hpp \ + boost/mpl/vector/aux_/begin_end.hpp \ + boost/mpl/vector/aux_/clear.hpp \ + boost/mpl/vector/aux_/empty.hpp \ + boost/mpl/vector/aux_/front.hpp \ + boost/mpl/vector/aux_/include_preprocessed.hpp \ + boost/mpl/vector/aux_/item.hpp \ + boost/mpl/vector/aux_/iterator.hpp \ + boost/mpl/vector/aux_/numbered.hpp \ + boost/mpl/vector/aux_/numbered_c.hpp \ + boost/mpl/vector/aux_/pop_back.hpp \ + boost/mpl/vector/aux_/pop_front.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector10.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector10_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector20.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector20_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector30.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector30_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector40.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector40_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector50.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector50_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector10.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector10_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector20.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector20_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector30.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector30_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector40.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector40_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector50.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector50_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector10.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector10_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector20.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector20_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector30.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector30_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector40.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector40_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector50.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector50_c.hpp \ + boost/mpl/vector/aux_/push_back.hpp \ + boost/mpl/vector/aux_/push_front.hpp \ + boost/mpl/vector/aux_/size.hpp \ + boost/mpl/vector/aux_/tag.hpp \ + boost/mpl/vector/aux_/vector0.hpp \ + boost/mpl/vector/vector0.hpp \ + boost/mpl/vector/vector0_c.hpp \ + boost/mpl/vector/vector10.hpp \ + boost/mpl/vector/vector10_c.hpp \ + boost/mpl/vector/vector20.hpp \ + boost/mpl/vector/vector20_c.hpp \ + boost/mpl/vector/vector30.hpp \ + boost/mpl/vector/vector30_c.hpp \ + boost/mpl/vector/vector40.hpp \ + boost/mpl/vector/vector40_c.hpp \ + boost/mpl/vector/vector50.hpp \ + boost/mpl/vector/vector50_c.hpp \ + boost/mpl/vector_c.hpp \ + boost/mpl/void.hpp \ + boost/mpl/void_fwd.hpp \ + boost/mpl/zip_view.hpp \ + boost/multi_array.hpp \ + boost/multi_index_container.hpp \ + boost/multi_index_container_fwd.hpp \ + boost/next_prior.hpp \ + boost/non_type.hpp \ + boost/noncopyable.hpp \ + boost/nondet_random.hpp \ + boost/none.hpp \ + boost/none_t.hpp \ + boost/operators.hpp \ + boost/optional.hpp \ + boost/optional/optional.hpp \ + boost/optional/optional_fwd.hpp \ + boost/optional/optional_io.hpp \ + boost/parameter.hpp \ + boost/pointee.hpp \ + boost/pointer_cast.hpp \ + boost/pointer_to_other.hpp \ + boost/preprocessor.hpp \ + boost/preprocessor/arithmetic.hpp \ + boost/preprocessor/arithmetic/add.hpp \ + boost/preprocessor/arithmetic/dec.hpp \ + boost/preprocessor/arithmetic/detail/div_base.hpp \ + boost/preprocessor/arithmetic/div.hpp \ + boost/preprocessor/arithmetic/inc.hpp \ + boost/preprocessor/arithmetic/mod.hpp \ + boost/preprocessor/arithmetic/mul.hpp \ + boost/preprocessor/arithmetic/sub.hpp \ + boost/preprocessor/array.hpp \ + boost/preprocessor/array/data.hpp \ + boost/preprocessor/array/elem.hpp \ + boost/preprocessor/array/insert.hpp \ + boost/preprocessor/array/pop_back.hpp \ + boost/preprocessor/array/pop_front.hpp \ + boost/preprocessor/array/push_back.hpp \ + boost/preprocessor/array/push_front.hpp \ + boost/preprocessor/array/remove.hpp \ + boost/preprocessor/array/replace.hpp \ + boost/preprocessor/array/reverse.hpp \ + boost/preprocessor/array/size.hpp \ + boost/preprocessor/assert_msg.hpp \ + boost/preprocessor/cat.hpp \ + boost/preprocessor/comma.hpp \ + boost/preprocessor/comma_if.hpp \ + boost/preprocessor/comparison.hpp \ + boost/preprocessor/comparison/equal.hpp \ + boost/preprocessor/comparison/greater.hpp \ + boost/preprocessor/comparison/greater_equal.hpp \ + boost/preprocessor/comparison/less.hpp \ + boost/preprocessor/comparison/less_equal.hpp \ + boost/preprocessor/comparison/not_equal.hpp \ + boost/preprocessor/config/config.hpp \ + boost/preprocessor/config/limits.hpp \ + boost/preprocessor/control.hpp \ + boost/preprocessor/control/deduce_d.hpp \ + boost/preprocessor/control/detail/dmc/while.hpp \ + boost/preprocessor/control/detail/edg/while.hpp \ + boost/preprocessor/control/detail/msvc/while.hpp \ + boost/preprocessor/control/detail/while.hpp \ + boost/preprocessor/control/expr_if.hpp \ + boost/preprocessor/control/expr_iif.hpp \ + boost/preprocessor/control/if.hpp \ + boost/preprocessor/control/iif.hpp \ + boost/preprocessor/control/while.hpp \ + boost/preprocessor/debug.hpp \ + boost/preprocessor/debug/assert.hpp \ + boost/preprocessor/debug/error.hpp \ + boost/preprocessor/debug/line.hpp \ + boost/preprocessor/dec.hpp \ + boost/preprocessor/detail/auto_rec.hpp \ + boost/preprocessor/detail/check.hpp \ + boost/preprocessor/detail/dmc/auto_rec.hpp \ + boost/preprocessor/detail/is_binary.hpp \ + boost/preprocessor/detail/is_nullary.hpp \ + boost/preprocessor/detail/is_unary.hpp \ + boost/preprocessor/detail/null.hpp \ + boost/preprocessor/detail/split.hpp \ + boost/preprocessor/empty.hpp \ + boost/preprocessor/enum.hpp \ + boost/preprocessor/enum_params.hpp \ + boost/preprocessor/enum_params_with_a_default.hpp \ + boost/preprocessor/enum_params_with_defaults.hpp \ + boost/preprocessor/enum_shifted.hpp \ + boost/preprocessor/enum_shifted_params.hpp \ + boost/preprocessor/expand.hpp \ + boost/preprocessor/expr_if.hpp \ + boost/preprocessor/facilities.hpp \ + boost/preprocessor/facilities/apply.hpp \ + boost/preprocessor/facilities/empty.hpp \ + boost/preprocessor/facilities/expand.hpp \ + boost/preprocessor/facilities/identity.hpp \ + boost/preprocessor/facilities/intercept.hpp \ + boost/preprocessor/facilities/is_1.hpp \ + boost/preprocessor/facilities/is_empty.hpp \ + boost/preprocessor/facilities/is_empty_or_1.hpp \ + boost/preprocessor/for.hpp \ + boost/preprocessor/identity.hpp \ + boost/preprocessor/if.hpp \ + boost/preprocessor/inc.hpp \ + boost/preprocessor/iterate.hpp \ + boost/preprocessor/iteration.hpp \ + boost/preprocessor/iteration/detail/bounds/lower1.hpp \ + boost/preprocessor/iteration/detail/bounds/lower2.hpp \ + boost/preprocessor/iteration/detail/bounds/lower3.hpp \ + boost/preprocessor/iteration/detail/bounds/lower4.hpp \ + boost/preprocessor/iteration/detail/bounds/lower5.hpp \ + boost/preprocessor/iteration/detail/bounds/upper1.hpp \ + boost/preprocessor/iteration/detail/bounds/upper2.hpp \ + boost/preprocessor/iteration/detail/bounds/upper3.hpp \ + boost/preprocessor/iteration/detail/bounds/upper4.hpp \ + boost/preprocessor/iteration/detail/bounds/upper5.hpp \ + boost/preprocessor/iteration/detail/finish.hpp \ + boost/preprocessor/iteration/detail/iter/forward1.hpp \ + boost/preprocessor/iteration/detail/iter/forward2.hpp \ + boost/preprocessor/iteration/detail/iter/forward3.hpp \ + boost/preprocessor/iteration/detail/iter/forward4.hpp \ + boost/preprocessor/iteration/detail/iter/forward5.hpp \ + boost/preprocessor/iteration/detail/iter/reverse1.hpp \ + boost/preprocessor/iteration/detail/iter/reverse2.hpp \ + boost/preprocessor/iteration/detail/iter/reverse3.hpp \ + boost/preprocessor/iteration/detail/iter/reverse4.hpp \ + boost/preprocessor/iteration/detail/iter/reverse5.hpp \ + boost/preprocessor/iteration/detail/local.hpp \ + boost/preprocessor/iteration/detail/rlocal.hpp \ + boost/preprocessor/iteration/detail/self.hpp \ + boost/preprocessor/iteration/detail/start.hpp \ + boost/preprocessor/iteration/iterate.hpp \ + boost/preprocessor/iteration/local.hpp \ + boost/preprocessor/iteration/self.hpp \ + boost/preprocessor/library.hpp \ + boost/preprocessor/limits.hpp \ + boost/preprocessor/list.hpp \ + boost/preprocessor/list/adt.hpp \ + boost/preprocessor/list/append.hpp \ + boost/preprocessor/list/at.hpp \ + boost/preprocessor/list/cat.hpp \ + boost/preprocessor/list/detail/dmc/fold_left.hpp \ + boost/preprocessor/list/detail/edg/fold_left.hpp \ + boost/preprocessor/list/detail/edg/fold_right.hpp \ + boost/preprocessor/list/detail/fold_left.hpp \ + boost/preprocessor/list/detail/fold_right.hpp \ + boost/preprocessor/list/enum.hpp \ + boost/preprocessor/list/filter.hpp \ + boost/preprocessor/list/first_n.hpp \ + boost/preprocessor/list/fold_left.hpp \ + boost/preprocessor/list/fold_right.hpp \ + boost/preprocessor/list/for_each.hpp \ + boost/preprocessor/list/for_each_i.hpp \ + boost/preprocessor/list/for_each_product.hpp \ + boost/preprocessor/list/rest_n.hpp \ + boost/preprocessor/list/reverse.hpp \ + boost/preprocessor/list/size.hpp \ + boost/preprocessor/list/to_tuple.hpp \ + boost/preprocessor/list/transform.hpp \ + boost/preprocessor/logical.hpp \ + boost/preprocessor/logical/and.hpp \ + boost/preprocessor/logical/bitand.hpp \ + boost/preprocessor/logical/bitnor.hpp \ + boost/preprocessor/logical/bitor.hpp \ + boost/preprocessor/logical/bitxor.hpp \ + boost/preprocessor/logical/bool.hpp \ + boost/preprocessor/logical/compl.hpp \ + boost/preprocessor/logical/nor.hpp \ + boost/preprocessor/logical/not.hpp \ + boost/preprocessor/logical/or.hpp \ + boost/preprocessor/logical/xor.hpp \ + boost/preprocessor/max.hpp \ + boost/preprocessor/min.hpp \ + boost/preprocessor/punctuation.hpp \ + boost/preprocessor/punctuation/comma.hpp \ + boost/preprocessor/punctuation/comma_if.hpp \ + boost/preprocessor/punctuation/paren.hpp \ + boost/preprocessor/punctuation/paren_if.hpp \ + boost/preprocessor/repeat.hpp \ + boost/preprocessor/repeat_2nd.hpp \ + boost/preprocessor/repeat_3rd.hpp \ + boost/preprocessor/repeat_from_to.hpp \ + boost/preprocessor/repeat_from_to_2nd.hpp \ + boost/preprocessor/repeat_from_to_3rd.hpp \ + boost/preprocessor/repetition.hpp \ + boost/preprocessor/repetition/deduce_r.hpp \ + boost/preprocessor/repetition/deduce_z.hpp \ + boost/preprocessor/repetition/detail/dmc/for.hpp \ + boost/preprocessor/repetition/detail/edg/for.hpp \ + boost/preprocessor/repetition/detail/for.hpp \ + boost/preprocessor/repetition/detail/msvc/for.hpp \ + boost/preprocessor/repetition/enum.hpp \ + boost/preprocessor/repetition/enum_binary_params.hpp \ + boost/preprocessor/repetition/enum_params.hpp \ + boost/preprocessor/repetition/enum_params_with_a_default.hpp \ + boost/preprocessor/repetition/enum_params_with_defaults.hpp \ + boost/preprocessor/repetition/enum_shifted.hpp \ + boost/preprocessor/repetition/enum_shifted_binary_params.hpp \ + boost/preprocessor/repetition/enum_shifted_params.hpp \ + boost/preprocessor/repetition/enum_trailing.hpp \ + boost/preprocessor/repetition/enum_trailing_binary_params.hpp \ + boost/preprocessor/repetition/enum_trailing_params.hpp \ + boost/preprocessor/repetition/for.hpp \ + boost/preprocessor/repetition/repeat.hpp \ + boost/preprocessor/repetition/repeat_from_to.hpp \ + boost/preprocessor/selection.hpp \ + boost/preprocessor/selection/max.hpp \ + boost/preprocessor/selection/min.hpp \ + boost/preprocessor/seq.hpp \ + boost/preprocessor/seq/cat.hpp \ + boost/preprocessor/seq/detail/split.hpp \ + boost/preprocessor/seq/elem.hpp \ + boost/preprocessor/seq/enum.hpp \ + boost/preprocessor/seq/filter.hpp \ + boost/preprocessor/seq/first_n.hpp \ + boost/preprocessor/seq/fold_left.hpp \ + boost/preprocessor/seq/fold_right.hpp \ + boost/preprocessor/seq/for_each.hpp \ + boost/preprocessor/seq/for_each_i.hpp \ + boost/preprocessor/seq/for_each_product.hpp \ + boost/preprocessor/seq/insert.hpp \ + boost/preprocessor/seq/pop_back.hpp \ + boost/preprocessor/seq/pop_front.hpp \ + boost/preprocessor/seq/push_back.hpp \ + boost/preprocessor/seq/push_front.hpp \ + boost/preprocessor/seq/remove.hpp \ + boost/preprocessor/seq/replace.hpp \ + boost/preprocessor/seq/rest_n.hpp \ + boost/preprocessor/seq/reverse.hpp \ + boost/preprocessor/seq/seq.hpp \ + boost/preprocessor/seq/size.hpp \ + boost/preprocessor/seq/subseq.hpp \ + boost/preprocessor/seq/to_array.hpp \ + boost/preprocessor/seq/to_tuple.hpp \ + boost/preprocessor/seq/transform.hpp \ + boost/preprocessor/slot.hpp \ + boost/preprocessor/slot/counter.hpp \ + boost/preprocessor/slot/detail/counter.hpp \ + boost/preprocessor/slot/detail/def.hpp \ + boost/preprocessor/slot/detail/shared.hpp \ + boost/preprocessor/slot/detail/slot1.hpp \ + boost/preprocessor/slot/detail/slot2.hpp \ + boost/preprocessor/slot/detail/slot3.hpp \ + boost/preprocessor/slot/detail/slot4.hpp \ + boost/preprocessor/slot/detail/slot5.hpp \ + boost/preprocessor/slot/slot.hpp \ + boost/preprocessor/stringize.hpp \ + boost/preprocessor/tuple.hpp \ + boost/preprocessor/tuple/eat.hpp \ + boost/preprocessor/tuple/elem.hpp \ + boost/preprocessor/tuple/rem.hpp \ + boost/preprocessor/tuple/reverse.hpp \ + boost/preprocessor/tuple/to_list.hpp \ + boost/preprocessor/tuple/to_seq.hpp \ + boost/preprocessor/while.hpp \ + boost/preprocessor/wstringize.hpp \ + boost/program_options.hpp \ + boost/progress.hpp \ + boost/ptr_container/clone_allocator.hpp \ + boost/ptr_container/detail/associative_ptr_container.hpp \ + boost/ptr_container/detail/default_deleter.hpp \ + boost/ptr_container/detail/is_convertible.hpp \ + boost/ptr_container/detail/map_iterator.hpp \ + boost/ptr_container/detail/meta_functions.hpp \ + boost/ptr_container/detail/move.hpp \ + boost/ptr_container/detail/reversible_ptr_container.hpp \ + boost/ptr_container/detail/scoped_deleter.hpp \ + boost/ptr_container/detail/serialize_ptr_map_adapter.hpp \ + boost/ptr_container/detail/serialize_reversible_cont.hpp \ + boost/ptr_container/detail/serialize_xml_names.hpp \ + boost/ptr_container/detail/static_move_ptr.hpp \ + boost/ptr_container/detail/throw_exception.hpp \ + boost/ptr_container/detail/void_ptr_iterator.hpp \ + boost/ptr_container/exception.hpp \ + boost/ptr_container/indirect_fun.hpp \ + boost/ptr_container/nullable.hpp \ + boost/ptr_container/ptr_array.hpp \ + boost/ptr_container/ptr_circular_buffer.hpp \ + boost/ptr_container/ptr_container.hpp \ + boost/ptr_container/ptr_deque.hpp \ + boost/ptr_container/ptr_inserter.hpp \ + boost/ptr_container/ptr_list.hpp \ + boost/ptr_container/ptr_map.hpp \ + boost/ptr_container/ptr_map_adapter.hpp \ + boost/ptr_container/ptr_sequence_adapter.hpp \ + boost/ptr_container/ptr_set.hpp \ + boost/ptr_container/ptr_set_adapter.hpp \ + boost/ptr_container/ptr_unordered_map.hpp \ + boost/ptr_container/ptr_unordered_set.hpp \ + boost/ptr_container/ptr_vector.hpp \ + boost/ptr_container/serialize_ptr_array.hpp \ + boost/ptr_container/serialize_ptr_circular_buffer.hpp \ + boost/ptr_container/serialize_ptr_container.hpp \ + boost/ptr_container/serialize_ptr_deque.hpp \ + boost/ptr_container/serialize_ptr_list.hpp \ + boost/ptr_container/serialize_ptr_map.hpp \ + boost/ptr_container/serialize_ptr_set.hpp \ + boost/ptr_container/serialize_ptr_unordered_map.hpp \ + boost/ptr_container/serialize_ptr_unordered_set.hpp \ + boost/ptr_container/serialize_ptr_vector.hpp \ + boost/python.hpp \ + boost/random.hpp \ + boost/range.hpp \ + boost/range/adaptors.hpp \ + boost/range/algorithm.hpp \ + boost/range/algorithm/adjacent_find.hpp \ + boost/range/algorithm/binary_search.hpp \ + boost/range/algorithm/copy.hpp \ + boost/range/algorithm/copy_backward.hpp \ + boost/range/algorithm/count.hpp \ + boost/range/algorithm/count_if.hpp \ + boost/range/algorithm/equal.hpp \ + boost/range/algorithm/equal_range.hpp \ + boost/range/algorithm/fill.hpp \ + boost/range/algorithm/fill_n.hpp \ + boost/range/algorithm/find.hpp \ + boost/range/algorithm/find_end.hpp \ + boost/range/algorithm/find_first_of.hpp \ + boost/range/algorithm/find_if.hpp \ + boost/range/algorithm/for_each.hpp \ + boost/range/algorithm/generate.hpp \ + boost/range/algorithm/heap_algorithm.hpp \ + boost/range/algorithm/inplace_merge.hpp \ + boost/range/algorithm/lexicographical_compare.hpp \ + boost/range/algorithm/lower_bound.hpp \ + boost/range/algorithm/max_element.hpp \ + boost/range/algorithm/merge.hpp \ + boost/range/algorithm/min_element.hpp \ + boost/range/algorithm/mismatch.hpp \ + boost/range/algorithm/nth_element.hpp \ + boost/range/algorithm/partial_sort.hpp \ + boost/range/algorithm/partial_sort_copy.hpp \ + boost/range/algorithm/partition.hpp \ + boost/range/algorithm/permutation.hpp \ + boost/range/algorithm/random_shuffle.hpp \ + boost/range/algorithm/remove.hpp \ + boost/range/algorithm/remove_copy.hpp \ + boost/range/algorithm/remove_copy_if.hpp \ + boost/range/algorithm/remove_if.hpp \ + boost/range/algorithm/replace.hpp \ + boost/range/algorithm/replace_copy.hpp \ + boost/range/algorithm/replace_copy_if.hpp \ + boost/range/algorithm/replace_if.hpp \ + boost/range/algorithm/reverse.hpp \ + boost/range/algorithm/reverse_copy.hpp \ + boost/range/algorithm/rotate.hpp \ + boost/range/algorithm/rotate_copy.hpp \ + boost/range/algorithm/search.hpp \ + boost/range/algorithm/search_n.hpp \ + boost/range/algorithm/set_algorithm.hpp \ + boost/range/algorithm/sort.hpp \ + boost/range/algorithm/stable_partition.hpp \ + boost/range/algorithm/stable_sort.hpp \ + boost/range/algorithm/swap_ranges.hpp \ + boost/range/algorithm/transform.hpp \ + boost/range/algorithm/unique.hpp \ + boost/range/algorithm/unique_copy.hpp \ + boost/range/algorithm/upper_bound.hpp \ + boost/range/algorithm_ext.hpp \ + boost/range/as_array.hpp \ + boost/range/as_literal.hpp \ + boost/range/atl.hpp \ + boost/range/begin.hpp \ + boost/range/category.hpp \ + boost/range/combine.hpp \ + boost/range/concepts.hpp \ + boost/range/config.hpp \ + boost/range/const_iterator.hpp \ + boost/range/const_reverse_iterator.hpp \ + boost/range/counting_range.hpp \ + boost/range/detail/as_literal.hpp \ + boost/range/detail/begin.hpp \ + boost/range/detail/collection_traits.hpp \ + boost/range/detail/collection_traits_detail.hpp \ + boost/range/detail/common.hpp \ + boost/range/detail/const_iterator.hpp \ + boost/range/detail/demote_iterator_traversal_tag.hpp \ + boost/range/detail/detail_str.hpp \ + boost/range/detail/difference_type.hpp \ + boost/range/detail/empty.hpp \ + boost/range/detail/end.hpp \ + boost/range/detail/extract_optional_type.hpp \ + boost/range/detail/implementation_help.hpp \ + boost/range/detail/iterator.hpp \ + boost/range/detail/join_iterator.hpp \ + boost/range/detail/microsoft.hpp \ + boost/range/detail/misc_concept.hpp \ + boost/range/detail/range_return.hpp \ + boost/range/detail/remove_extent.hpp \ + boost/range/detail/sfinae.hpp \ + boost/range/detail/size.hpp \ + boost/range/detail/size_type.hpp \ + boost/range/detail/sizer.hpp \ + boost/range/detail/str_types.hpp \ + boost/range/detail/value_type.hpp \ + boost/range/detail/vc6/end.hpp \ + boost/range/detail/vc6/size.hpp \ + boost/range/difference_type.hpp \ + boost/range/distance.hpp \ + boost/range/empty.hpp \ + boost/range/end.hpp \ + boost/range/functions.hpp \ + boost/range/irange.hpp \ + boost/range/istream_range.hpp \ + boost/range/iterator.hpp \ + boost/range/iterator_range.hpp \ + boost/range/iterator_range_core.hpp \ + boost/range/iterator_range_io.hpp \ + boost/range/join.hpp \ + boost/range/metafunctions.hpp \ + boost/range/mfc.hpp \ + boost/range/mutable_iterator.hpp \ + boost/range/numeric.hpp \ + boost/range/pointer.hpp \ + boost/range/rbegin.hpp \ + boost/range/reference.hpp \ + boost/range/rend.hpp \ + boost/range/result_iterator.hpp \ + boost/range/reverse_iterator.hpp \ + boost/range/reverse_result_iterator.hpp \ + boost/range/size.hpp \ + boost/range/size_type.hpp \ + boost/range/sub_range.hpp \ + boost/range/value_type.hpp \ + boost/rational.hpp \ + boost/ref.hpp \ + boost/regex.h \ + boost/regex.hpp \ + boost/regex/concepts.hpp \ + boost/regex/config.hpp \ + boost/regex/config/borland.hpp \ + boost/regex/config/cwchar.hpp \ + boost/regex/icu.hpp \ + boost/regex/mfc.hpp \ + boost/regex/pattern_except.hpp \ + boost/regex/pending/object_cache.hpp \ + boost/regex/pending/static_mutex.hpp \ + boost/regex/pending/unicode_iterator.hpp \ + boost/regex/regex_traits.hpp \ + boost/regex/user.hpp \ + boost/regex/v4/basic_regex.hpp \ + boost/regex/v4/basic_regex_creator.hpp \ + boost/regex/v4/basic_regex_parser.hpp \ + boost/regex/v4/c_regex_traits.hpp \ + boost/regex/v4/char_regex_traits.hpp \ + boost/regex/v4/cpp_regex_traits.hpp \ + boost/regex/v4/cregex.hpp \ + boost/regex/v4/error_type.hpp \ + boost/regex/v4/fileiter.hpp \ + boost/regex/v4/instances.hpp \ + boost/regex/v4/iterator_category.hpp \ + boost/regex/v4/iterator_traits.hpp \ + boost/regex/v4/match_flags.hpp \ + boost/regex/v4/match_results.hpp \ + boost/regex/v4/mem_block_cache.hpp \ + boost/regex/v4/perl_matcher.hpp \ + boost/regex/v4/perl_matcher_common.hpp \ + boost/regex/v4/perl_matcher_non_recursive.hpp \ + boost/regex/v4/perl_matcher_recursive.hpp \ + boost/regex/v4/primary_transform.hpp \ + boost/regex/v4/protected_call.hpp \ + boost/regex/v4/regbase.hpp \ + boost/regex/v4/regex.hpp \ + boost/regex/v4/regex_format.hpp \ + boost/regex/v4/regex_fwd.hpp \ + boost/regex/v4/regex_grep.hpp \ + boost/regex/v4/regex_iterator.hpp \ + boost/regex/v4/regex_match.hpp \ + boost/regex/v4/regex_merge.hpp \ + boost/regex/v4/regex_raw_buffer.hpp \ + boost/regex/v4/regex_replace.hpp \ + boost/regex/v4/regex_search.hpp \ + boost/regex/v4/regex_split.hpp \ + boost/regex/v4/regex_token_iterator.hpp \ + boost/regex/v4/regex_traits.hpp \ + boost/regex/v4/regex_traits_defaults.hpp \ + boost/regex/v4/regex_workaround.hpp \ + boost/regex/v4/states.hpp \ + boost/regex/v4/sub_match.hpp \ + boost/regex/v4/syntax_type.hpp \ + boost/regex/v4/u32regex_iterator.hpp \ + boost/regex/v4/u32regex_token_iterator.hpp \ + boost/regex/v4/w32_regex_traits.hpp \ + boost/regex_fwd.hpp \ + boost/scope_exit.hpp \ + boost/scoped_array.hpp \ + boost/scoped_ptr.hpp \ + boost/shared_array.hpp \ + boost/shared_container_iterator.hpp \ + boost/shared_ptr.hpp \ + boost/signal.hpp \ + boost/signals.hpp \ + boost/signals2.hpp \ + boost/smart_ptr.hpp \ + boost/smart_ptr/bad_weak_ptr.hpp \ + boost/smart_ptr/detail/atomic_count.hpp \ + boost/smart_ptr/detail/atomic_count_gcc.hpp \ + boost/smart_ptr/detail/atomic_count_gcc_x86.hpp \ + boost/smart_ptr/detail/atomic_count_pthreads.hpp \ + boost/smart_ptr/detail/atomic_count_solaris.hpp \ + boost/smart_ptr/detail/atomic_count_sync.hpp \ + boost/smart_ptr/detail/atomic_count_win32.hpp \ + boost/smart_ptr/detail/lightweight_mutex.hpp \ + boost/smart_ptr/detail/lwm_nop.hpp \ + boost/smart_ptr/detail/lwm_pthreads.hpp \ + boost/smart_ptr/detail/lwm_win32_cs.hpp \ + boost/smart_ptr/detail/operator_bool.hpp \ + boost/smart_ptr/detail/quick_allocator.hpp \ + boost/smart_ptr/detail/shared_array_nmt.hpp \ + boost/smart_ptr/detail/shared_count.hpp \ + boost/smart_ptr/detail/shared_ptr_nmt.hpp \ + boost/smart_ptr/detail/sp_convertible.hpp \ + boost/smart_ptr/detail/sp_counted_base.hpp \ + boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \ + boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \ + boost/smart_ptr/detail/sp_counted_base_cw_x86.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \ + boost/smart_ptr/detail/sp_counted_base_nt.hpp \ + boost/smart_ptr/detail/sp_counted_base_pt.hpp \ + boost/smart_ptr/detail/sp_counted_base_solaris.hpp \ + boost/smart_ptr/detail/sp_counted_base_spin.hpp \ + boost/smart_ptr/detail/sp_counted_base_sync.hpp \ + boost/smart_ptr/detail/sp_counted_base_w32.hpp \ + boost/smart_ptr/detail/sp_counted_impl.hpp \ + boost/smart_ptr/detail/sp_has_sync.hpp \ + boost/smart_ptr/detail/spinlock.hpp \ + boost/smart_ptr/detail/spinlock_gcc_arm.hpp \ + boost/smart_ptr/detail/spinlock_nt.hpp \ + boost/smart_ptr/detail/spinlock_pool.hpp \ + boost/smart_ptr/detail/spinlock_pt.hpp \ + boost/smart_ptr/detail/spinlock_sync.hpp \ + boost/smart_ptr/detail/spinlock_w32.hpp \ + boost/smart_ptr/detail/yield_k.hpp \ + boost/smart_ptr/enable_shared_from_this.hpp \ + boost/smart_ptr/enable_shared_from_this2.hpp \ + boost/smart_ptr/intrusive_ptr.hpp \ + boost/smart_ptr/make_shared.hpp \ + boost/smart_ptr/scoped_array.hpp \ + boost/smart_ptr/scoped_ptr.hpp \ + boost/smart_ptr/shared_array.hpp \ + boost/smart_ptr/shared_ptr.hpp \ + boost/smart_ptr/weak_ptr.hpp \ + boost/spirit.hpp \ + boost/static_assert.hpp \ + boost/strong_typedef.hpp \ + boost/swap.hpp \ + boost/system/api_config.hpp \ + boost/system/config.hpp \ + boost/system/cygwin_error.hpp \ + boost/system/error_code.hpp \ + boost/system/linux_error.hpp \ + boost/system/system_error.hpp \ + boost/system/windows_error.hpp \ + boost/thread.hpp \ + boost/thread/barrier.hpp \ + boost/thread/condition.hpp \ + boost/thread/condition_variable.hpp \ + boost/thread/detail/config.hpp \ + boost/thread/detail/force_cast.hpp \ + boost/thread/detail/move.hpp \ + boost/thread/detail/platform.hpp \ + boost/thread/detail/singleton.hpp \ + boost/thread/detail/thread.hpp \ + boost/thread/detail/thread_group.hpp \ + boost/thread/detail/thread_heap_alloc.hpp \ + boost/thread/detail/thread_interruption.hpp \ + boost/thread/detail/tss_hooks.hpp \ + boost/thread/exceptions.hpp \ + boost/thread/future.hpp \ + boost/thread/locks.hpp \ + boost/thread/mutex.hpp \ + boost/thread/once.hpp \ + boost/thread/pthread/condition_variable.hpp \ + boost/thread/pthread/condition_variable_fwd.hpp \ + boost/thread/pthread/mutex.hpp \ + boost/thread/pthread/once.hpp \ + boost/thread/pthread/pthread_mutex_scoped_lock.hpp \ + boost/thread/pthread/recursive_mutex.hpp \ + boost/thread/pthread/shared_mutex.hpp \ + boost/thread/pthread/thread_data.hpp \ + boost/thread/pthread/thread_heap_alloc.hpp \ + boost/thread/pthread/timespec.hpp \ + boost/thread/recursive_mutex.hpp \ + boost/thread/shared_mutex.hpp \ + boost/thread/thread.hpp \ + boost/thread/thread_time.hpp \ + boost/thread/tss.hpp \ + boost/thread/win32/basic_recursive_mutex.hpp \ + boost/thread/win32/basic_timed_mutex.hpp \ + boost/thread/win32/condition_variable.hpp \ + boost/thread/win32/interlocked_read.hpp \ + boost/thread/win32/mutex.hpp \ + boost/thread/win32/once.hpp \ + boost/thread/win32/recursive_mutex.hpp \ + boost/thread/win32/shared_mutex.hpp \ + boost/thread/win32/thread_data.hpp \ + boost/thread/win32/thread_heap_alloc.hpp \ + boost/thread/win32/thread_primitives.hpp \ + boost/thread/xtime.hpp \ + boost/throw_exception.hpp \ + boost/timer.hpp \ + boost/token_functions.hpp \ + boost/token_iterator.hpp \ + boost/tokenizer.hpp \ + boost/tuple/detail/tuple_basic.hpp \ + boost/tuple/detail/tuple_basic_no_partial_spec.hpp \ + boost/tuple/tuple.hpp \ + boost/tuple/tuple_comparison.hpp \ + boost/tuple/tuple_io.hpp \ + boost/type.hpp \ + boost/type_traits.hpp \ + boost/type_traits/add_const.hpp \ + boost/type_traits/add_cv.hpp \ + boost/type_traits/add_lvalue_reference.hpp \ + boost/type_traits/add_pointer.hpp \ + boost/type_traits/add_reference.hpp \ + boost/type_traits/add_rvalue_reference.hpp \ + boost/type_traits/add_volatile.hpp \ + boost/type_traits/aligned_storage.hpp \ + boost/type_traits/alignment_of.hpp \ + boost/type_traits/alignment_traits.hpp \ + boost/type_traits/arithmetic_traits.hpp \ + boost/type_traits/array_traits.hpp \ + boost/type_traits/broken_compiler_spec.hpp \ + boost/type_traits/common_type.hpp \ + boost/type_traits/composite_traits.hpp \ + boost/type_traits/conditional.hpp \ + boost/type_traits/config.hpp \ + boost/type_traits/conversion_traits.hpp \ + boost/type_traits/cv_traits.hpp \ + boost/type_traits/decay.hpp \ + boost/type_traits/detail/bool_trait_def.hpp \ + boost/type_traits/detail/bool_trait_undef.hpp \ + boost/type_traits/detail/common_type_imp.hpp \ + boost/type_traits/detail/cv_traits_impl.hpp \ + boost/type_traits/detail/false_result.hpp \ + boost/type_traits/detail/ice_and.hpp \ + boost/type_traits/detail/ice_eq.hpp \ + boost/type_traits/detail/ice_not.hpp \ + boost/type_traits/detail/ice_or.hpp \ + boost/type_traits/detail/is_function_ptr_helper.hpp \ + boost/type_traits/detail/is_function_ptr_tester.hpp \ + boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \ + boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \ + boost/type_traits/detail/size_t_trait_def.hpp \ + boost/type_traits/detail/size_t_trait_undef.hpp \ + boost/type_traits/detail/template_arity_spec.hpp \ + boost/type_traits/detail/type_trait_def.hpp \ + boost/type_traits/detail/type_trait_undef.hpp \ + boost/type_traits/detail/wrap.hpp \ + boost/type_traits/detail/yes_no_type.hpp \ + boost/type_traits/extent.hpp \ + boost/type_traits/floating_point_promotion.hpp \ + boost/type_traits/function_traits.hpp \ + boost/type_traits/has_new_operator.hpp \ + boost/type_traits/has_nothrow_assign.hpp \ + boost/type_traits/has_nothrow_constructor.hpp \ + boost/type_traits/has_nothrow_copy.hpp \ + boost/type_traits/has_nothrow_destructor.hpp \ + boost/type_traits/has_trivial_assign.hpp \ + boost/type_traits/has_trivial_constructor.hpp \ + boost/type_traits/has_trivial_copy.hpp \ + boost/type_traits/has_trivial_destructor.hpp \ + boost/type_traits/has_virtual_destructor.hpp \ + boost/type_traits/ice.hpp \ + boost/type_traits/integral_constant.hpp \ + boost/type_traits/integral_promotion.hpp \ + boost/type_traits/intrinsics.hpp \ + boost/type_traits/is_abstract.hpp \ + boost/type_traits/is_arithmetic.hpp \ + boost/type_traits/is_array.hpp \ + boost/type_traits/is_base_and_derived.hpp \ + boost/type_traits/is_base_of.hpp \ + boost/type_traits/is_base_of_tr1.hpp \ + boost/type_traits/is_class.hpp \ + boost/type_traits/is_complex.hpp \ + boost/type_traits/is_compound.hpp \ + boost/type_traits/is_const.hpp \ + boost/type_traits/is_convertible.hpp \ + boost/type_traits/is_empty.hpp \ + boost/type_traits/is_enum.hpp \ + boost/type_traits/is_float.hpp \ + boost/type_traits/is_floating_point.hpp \ + boost/type_traits/is_function.hpp \ + boost/type_traits/is_fundamental.hpp \ + boost/type_traits/is_integral.hpp \ + boost/type_traits/is_lvalue_reference.hpp \ + boost/type_traits/is_member_function_pointer.hpp \ + boost/type_traits/is_member_object_pointer.hpp \ + boost/type_traits/is_member_pointer.hpp \ + boost/type_traits/is_object.hpp \ + boost/type_traits/is_pod.hpp \ + boost/type_traits/is_pointer.hpp \ + boost/type_traits/is_polymorphic.hpp \ + boost/type_traits/is_reference.hpp \ + boost/type_traits/is_rvalue_reference.hpp \ + boost/type_traits/is_same.hpp \ + boost/type_traits/is_scalar.hpp \ + boost/type_traits/is_signed.hpp \ + boost/type_traits/is_stateless.hpp \ + boost/type_traits/is_union.hpp \ + boost/type_traits/is_unsigned.hpp \ + boost/type_traits/is_virtual_base_of.hpp \ + boost/type_traits/is_void.hpp \ + boost/type_traits/is_volatile.hpp \ + boost/type_traits/make_signed.hpp \ + boost/type_traits/make_unsigned.hpp \ + boost/type_traits/msvc/remove_all_extents.hpp \ + boost/type_traits/msvc/remove_bounds.hpp \ + boost/type_traits/msvc/remove_const.hpp \ + boost/type_traits/msvc/remove_cv.hpp \ + boost/type_traits/msvc/remove_extent.hpp \ + boost/type_traits/msvc/remove_pointer.hpp \ + boost/type_traits/msvc/remove_reference.hpp \ + boost/type_traits/msvc/remove_volatile.hpp \ + boost/type_traits/msvc/typeof.hpp \ + boost/type_traits/object_traits.hpp \ + boost/type_traits/promote.hpp \ + boost/type_traits/rank.hpp \ + boost/type_traits/reference_traits.hpp \ + boost/type_traits/remove_all_extents.hpp \ + boost/type_traits/remove_bounds.hpp \ + boost/type_traits/remove_const.hpp \ + boost/type_traits/remove_cv.hpp \ + boost/type_traits/remove_extent.hpp \ + boost/type_traits/remove_pointer.hpp \ + boost/type_traits/remove_reference.hpp \ + boost/type_traits/remove_volatile.hpp \ + boost/type_traits/same_traits.hpp \ + boost/type_traits/transform_traits.hpp \ + boost/type_traits/transform_traits_spec.hpp \ + boost/type_traits/type_with_alignment.hpp \ + boost/units/absolute.hpp \ + boost/units/base_dimension.hpp \ + boost/units/base_unit.hpp \ + boost/units/base_units/angle/arcminute.hpp \ + boost/units/base_units/angle/arcsecond.hpp \ + boost/units/base_units/angle/degree.hpp \ + boost/units/base_units/angle/gradian.hpp \ + boost/units/base_units/angle/radian.hpp \ + boost/units/base_units/angle/revolution.hpp \ + boost/units/base_units/angle/steradian.hpp \ + boost/units/base_units/astronomical/astronomical_unit.hpp \ + boost/units/base_units/astronomical/light_day.hpp \ + boost/units/base_units/astronomical/light_hour.hpp \ + boost/units/base_units/astronomical/light_minute.hpp \ + boost/units/base_units/astronomical/light_second.hpp \ + boost/units/base_units/astronomical/light_year.hpp \ + boost/units/base_units/astronomical/parsec.hpp \ + boost/units/base_units/cgs/biot.hpp \ + boost/units/base_units/cgs/centimeter.hpp \ + boost/units/base_units/cgs/gram.hpp \ + boost/units/base_units/imperial/conversions.hpp \ + boost/units/base_units/imperial/drachm.hpp \ + boost/units/base_units/imperial/fluid_ounce.hpp \ + boost/units/base_units/imperial/foot.hpp \ + boost/units/base_units/imperial/furlong.hpp \ + boost/units/base_units/imperial/gallon.hpp \ + boost/units/base_units/imperial/gill.hpp \ + boost/units/base_units/imperial/grain.hpp \ + boost/units/base_units/imperial/hundredweight.hpp \ + boost/units/base_units/imperial/inch.hpp \ + boost/units/base_units/imperial/league.hpp \ + boost/units/base_units/imperial/mile.hpp \ + boost/units/base_units/imperial/ounce.hpp \ + boost/units/base_units/imperial/pint.hpp \ + boost/units/base_units/imperial/pound.hpp \ + boost/units/base_units/imperial/quart.hpp \ + boost/units/base_units/imperial/quarter.hpp \ + boost/units/base_units/imperial/stone.hpp \ + boost/units/base_units/imperial/thou.hpp \ + boost/units/base_units/imperial/ton.hpp \ + boost/units/base_units/imperial/yard.hpp \ + boost/units/base_units/metric/angstrom.hpp \ + boost/units/base_units/metric/are.hpp \ + boost/units/base_units/metric/atmosphere.hpp \ + boost/units/base_units/metric/bar.hpp \ + boost/units/base_units/metric/barn.hpp \ + boost/units/base_units/metric/day.hpp \ + boost/units/base_units/metric/fermi.hpp \ + boost/units/base_units/metric/hectare.hpp \ + boost/units/base_units/metric/hour.hpp \ + boost/units/base_units/metric/knot.hpp \ + boost/units/base_units/metric/liter.hpp \ + boost/units/base_units/metric/micron.hpp \ + boost/units/base_units/metric/minute.hpp \ + boost/units/base_units/metric/mmHg.hpp \ + boost/units/base_units/metric/nautical_mile.hpp \ + boost/units/base_units/metric/ton.hpp \ + boost/units/base_units/metric/torr.hpp \ + boost/units/base_units/metric/year.hpp \ + boost/units/base_units/si/ampere.hpp \ + boost/units/base_units/si/candela.hpp \ + boost/units/base_units/si/kelvin.hpp \ + boost/units/base_units/si/kilogram.hpp \ + boost/units/base_units/si/meter.hpp \ + boost/units/base_units/si/mole.hpp \ + boost/units/base_units/si/second.hpp \ + boost/units/base_units/temperature/celsius.hpp \ + boost/units/base_units/temperature/conversions.hpp \ + boost/units/base_units/temperature/fahrenheit.hpp \ + boost/units/base_units/us/cup.hpp \ + boost/units/base_units/us/dram.hpp \ + boost/units/base_units/us/fluid_dram.hpp \ + boost/units/base_units/us/fluid_ounce.hpp \ + boost/units/base_units/us/foot.hpp \ + boost/units/base_units/us/gallon.hpp \ + boost/units/base_units/us/gill.hpp \ + boost/units/base_units/us/grain.hpp \ + boost/units/base_units/us/hundredweight.hpp \ + boost/units/base_units/us/inch.hpp \ + boost/units/base_units/us/mil.hpp \ + boost/units/base_units/us/mile.hpp \ + boost/units/base_units/us/minim.hpp \ + boost/units/base_units/us/ounce.hpp \ + boost/units/base_units/us/pint.hpp \ + boost/units/base_units/us/pound.hpp \ + boost/units/base_units/us/pound_force.hpp \ + boost/units/base_units/us/quart.hpp \ + boost/units/base_units/us/tablespoon.hpp \ + boost/units/base_units/us/teaspoon.hpp \ + boost/units/base_units/us/ton.hpp \ + boost/units/base_units/us/yard.hpp \ + boost/units/cmath.hpp \ + boost/units/config.hpp \ + boost/units/conversion.hpp \ + boost/units/derived_dimension.hpp \ + boost/units/detail/absolute_impl.hpp \ + boost/units/detail/cmath_impl.hpp \ + boost/units/detail/conversion_impl.hpp \ + boost/units/detail/dim_impl.hpp \ + boost/units/detail/dimension_impl.hpp \ + boost/units/detail/dimension_list.hpp \ + boost/units/detail/dimensionless_unit.hpp \ + boost/units/detail/heterogeneous_conversion.hpp \ + boost/units/detail/linear_algebra.hpp \ + boost/units/detail/one.hpp \ + boost/units/detail/ordinal.hpp \ + boost/units/detail/prevent_redefinition.hpp \ + boost/units/detail/push_front_if.hpp \ + boost/units/detail/push_front_or_add.hpp \ + boost/units/detail/sort.hpp \ + boost/units/detail/static_rational_power.hpp \ + boost/units/detail/unscale.hpp \ + boost/units/detail/utility.hpp \ + boost/units/dim.hpp \ + boost/units/dimension.hpp \ + boost/units/dimensionless_quantity.hpp \ + boost/units/dimensionless_type.hpp \ + boost/units/dimensionless_unit.hpp \ + boost/units/get_dimension.hpp \ + boost/units/get_system.hpp \ + boost/units/heterogeneous_system.hpp \ + boost/units/homogeneous_system.hpp \ + boost/units/io.hpp \ + boost/units/is_dim.hpp \ + boost/units/is_dimension_list.hpp \ + boost/units/is_dimensionless.hpp \ + boost/units/is_dimensionless_quantity.hpp \ + boost/units/is_dimensionless_unit.hpp \ + boost/units/is_quantity.hpp \ + boost/units/is_quantity_of_dimension.hpp \ + boost/units/is_quantity_of_system.hpp \ + boost/units/is_unit.hpp \ + boost/units/is_unit_of_dimension.hpp \ + boost/units/is_unit_of_system.hpp \ + boost/units/lambda.hpp \ + boost/units/limits.hpp \ + boost/units/make_scaled_unit.hpp \ + boost/units/make_system.hpp \ + boost/units/operators.hpp \ + boost/units/physical_dimensions.hpp \ + boost/units/physical_dimensions/absorbed_dose.hpp \ + boost/units/physical_dimensions/acceleration.hpp \ + boost/units/physical_dimensions/action.hpp \ + boost/units/physical_dimensions/activity.hpp \ + boost/units/physical_dimensions/amount.hpp \ + boost/units/physical_dimensions/angular_acceleration.hpp \ + boost/units/physical_dimensions/angular_momentum.hpp \ + boost/units/physical_dimensions/angular_velocity.hpp \ + boost/units/physical_dimensions/area.hpp \ + boost/units/physical_dimensions/capacitance.hpp \ + boost/units/physical_dimensions/conductance.hpp \ + boost/units/physical_dimensions/conductivity.hpp \ + boost/units/physical_dimensions/current.hpp \ + boost/units/physical_dimensions/dose_equivalent.hpp \ + boost/units/physical_dimensions/dynamic_viscosity.hpp \ + boost/units/physical_dimensions/electric_charge.hpp \ + boost/units/physical_dimensions/electric_potential.hpp \ + boost/units/physical_dimensions/energy.hpp \ + boost/units/physical_dimensions/energy_density.hpp \ + boost/units/physical_dimensions/force.hpp \ + boost/units/physical_dimensions/frequency.hpp \ + boost/units/physical_dimensions/heat_capacity.hpp \ + boost/units/physical_dimensions/illuminance.hpp \ + boost/units/physical_dimensions/impedance.hpp \ + boost/units/physical_dimensions/inductance.hpp \ + boost/units/physical_dimensions/kinematic_viscosity.hpp \ + boost/units/physical_dimensions/length.hpp \ + boost/units/physical_dimensions/luminance.hpp \ + boost/units/physical_dimensions/luminous_flux.hpp \ + boost/units/physical_dimensions/luminous_intensity.hpp \ + boost/units/physical_dimensions/magnetic_field_intensity.hpp \ + boost/units/physical_dimensions/magnetic_flux.hpp \ + boost/units/physical_dimensions/magnetic_flux_density.hpp \ + boost/units/physical_dimensions/mass.hpp \ + boost/units/physical_dimensions/mass_density.hpp \ + boost/units/physical_dimensions/molar_energy.hpp \ + boost/units/physical_dimensions/molar_heat_capacity.hpp \ + boost/units/physical_dimensions/moment_of_inertia.hpp \ + boost/units/physical_dimensions/momentum.hpp \ + boost/units/physical_dimensions/permeability.hpp \ + boost/units/physical_dimensions/permittivity.hpp \ + boost/units/physical_dimensions/plane_angle.hpp \ + boost/units/physical_dimensions/power.hpp \ + boost/units/physical_dimensions/pressure.hpp \ + boost/units/physical_dimensions/reluctance.hpp \ + boost/units/physical_dimensions/resistance.hpp \ + boost/units/physical_dimensions/resistivity.hpp \ + boost/units/physical_dimensions/solid_angle.hpp \ + boost/units/physical_dimensions/specific_energy.hpp \ + boost/units/physical_dimensions/specific_heat_capacity.hpp \ + boost/units/physical_dimensions/specific_volume.hpp \ + boost/units/physical_dimensions/stress.hpp \ + boost/units/physical_dimensions/surface_density.hpp \ + boost/units/physical_dimensions/surface_tension.hpp \ + boost/units/physical_dimensions/temperature.hpp \ + boost/units/physical_dimensions/thermal_conductivity.hpp \ + boost/units/physical_dimensions/time.hpp \ + boost/units/physical_dimensions/torque.hpp \ + boost/units/physical_dimensions/velocity.hpp \ + boost/units/physical_dimensions/volume.hpp \ + boost/units/physical_dimensions/wavenumber.hpp \ + boost/units/pow.hpp \ + boost/units/quantity.hpp \ + boost/units/reduce_unit.hpp \ + boost/units/scale.hpp \ + boost/units/scaled_base_unit.hpp \ + boost/units/static_constant.hpp \ + boost/units/static_rational.hpp \ + boost/units/systems/abstract.hpp \ + boost/units/systems/angle/degrees.hpp \ + boost/units/systems/angle/gradians.hpp \ + boost/units/systems/angle/revolutions.hpp \ + boost/units/systems/cgs.hpp \ + boost/units/systems/cgs/acceleration.hpp \ + boost/units/systems/cgs/area.hpp \ + boost/units/systems/cgs/base.hpp \ + boost/units/systems/cgs/current.hpp \ + boost/units/systems/cgs/dimensionless.hpp \ + boost/units/systems/cgs/dynamic_viscosity.hpp \ + boost/units/systems/cgs/energy.hpp \ + boost/units/systems/cgs/force.hpp \ + boost/units/systems/cgs/frequency.hpp \ + boost/units/systems/cgs/io.hpp \ + boost/units/systems/cgs/kinematic_viscosity.hpp \ + boost/units/systems/cgs/length.hpp \ + boost/units/systems/cgs/mass.hpp \ + boost/units/systems/cgs/mass_density.hpp \ + boost/units/systems/cgs/momentum.hpp \ + boost/units/systems/cgs/power.hpp \ + boost/units/systems/cgs/pressure.hpp \ + boost/units/systems/cgs/time.hpp \ + boost/units/systems/cgs/velocity.hpp \ + boost/units/systems/cgs/volume.hpp \ + boost/units/systems/cgs/wavenumber.hpp \ + boost/units/systems/detail/constants.hpp \ + boost/units/systems/si.hpp \ + boost/units/systems/si/absorbed_dose.hpp \ + boost/units/systems/si/acceleration.hpp \ + boost/units/systems/si/action.hpp \ + boost/units/systems/si/activity.hpp \ + boost/units/systems/si/amount.hpp \ + boost/units/systems/si/angular_acceleration.hpp \ + boost/units/systems/si/angular_momentum.hpp \ + boost/units/systems/si/angular_velocity.hpp \ + boost/units/systems/si/area.hpp \ + boost/units/systems/si/base.hpp \ + boost/units/systems/si/capacitance.hpp \ + boost/units/systems/si/catalytic_activity.hpp \ + boost/units/systems/si/codata/alpha_constants.hpp \ + boost/units/systems/si/codata/atomic-nuclear_constants.hpp \ + boost/units/systems/si/codata/deuteron_constants.hpp \ + boost/units/systems/si/codata/electromagnetic_constants.hpp \ + boost/units/systems/si/codata/electron_constants.hpp \ + boost/units/systems/si/codata/helion_constants.hpp \ + boost/units/systems/si/codata/muon_constants.hpp \ + boost/units/systems/si/codata/neutron_constants.hpp \ + boost/units/systems/si/codata/physico-chemical_constants.hpp \ + boost/units/systems/si/codata/proton_constants.hpp \ + boost/units/systems/si/codata/tau_constants.hpp \ + boost/units/systems/si/codata/triton_constants.hpp \ + boost/units/systems/si/codata/typedefs.hpp \ + boost/units/systems/si/codata/universal_constants.hpp \ + boost/units/systems/si/codata_constants.hpp \ + boost/units/systems/si/conductance.hpp \ + boost/units/systems/si/conductivity.hpp \ + boost/units/systems/si/current.hpp \ + boost/units/systems/si/dimensionless.hpp \ + boost/units/systems/si/dose_equivalent.hpp \ + boost/units/systems/si/dynamic_viscosity.hpp \ + boost/units/systems/si/electric_charge.hpp \ + boost/units/systems/si/electric_potential.hpp \ + boost/units/systems/si/energy.hpp \ + boost/units/systems/si/force.hpp \ + boost/units/systems/si/frequency.hpp \ + boost/units/systems/si/illuminance.hpp \ + boost/units/systems/si/impedance.hpp \ + boost/units/systems/si/inductance.hpp \ + boost/units/systems/si/io.hpp \ + boost/units/systems/si/kinematic_viscosity.hpp \ + boost/units/systems/si/length.hpp \ + boost/units/systems/si/luminous_flux.hpp \ + boost/units/systems/si/luminous_intensity.hpp \ + boost/units/systems/si/magnetic_field_intensity.hpp \ + boost/units/systems/si/magnetic_flux.hpp \ + boost/units/systems/si/magnetic_flux_density.hpp \ + boost/units/systems/si/mass.hpp \ + boost/units/systems/si/mass_density.hpp \ + boost/units/systems/si/moment_of_inertia.hpp \ + boost/units/systems/si/momentum.hpp \ + boost/units/systems/si/permeability.hpp \ + boost/units/systems/si/permittivity.hpp \ + boost/units/systems/si/plane_angle.hpp \ + boost/units/systems/si/power.hpp \ + boost/units/systems/si/prefixes.hpp \ + boost/units/systems/si/pressure.hpp \ + boost/units/systems/si/reluctance.hpp \ + boost/units/systems/si/resistance.hpp \ + boost/units/systems/si/resistivity.hpp \ + boost/units/systems/si/solid_angle.hpp \ + boost/units/systems/si/surface_density.hpp \ + boost/units/systems/si/surface_tension.hpp \ + boost/units/systems/si/temperature.hpp \ + boost/units/systems/si/time.hpp \ + boost/units/systems/si/torque.hpp \ + boost/units/systems/si/velocity.hpp \ + boost/units/systems/si/volume.hpp \ + boost/units/systems/si/wavenumber.hpp \ + boost/units/systems/temperature/celsius.hpp \ + boost/units/systems/temperature/fahrenheit.hpp \ + boost/units/unit.hpp \ + boost/units/units_fwd.hpp \ + boost/unordered_map.hpp \ + boost/unordered_set.hpp \ + boost/unordered/unordered_set.hpp \ + boost/unordered/unordered_set_fwd.hpp \ + boost/unordered/unordered_map_fwd.hpp \ + boost/unordered/detail/allocator_helpers.hpp \ + boost/unordered/detail/move.hpp \ + boost/unordered/detail/config.hpp \ + boost/unordered/detail/hash_table_impl.hpp \ + boost/unordered/detail/hash_table.hpp \ + boost/unordered/unordered_map.hpp \ + boost/utility.hpp \ + boost/utility/addressof.hpp \ + boost/utility/base_from_member.hpp \ + boost/utility/binary.hpp \ + boost/utility/compare_pointees.hpp \ + boost/utility/declval.hpp \ + boost/utility/detail/in_place_factory_prefix.hpp \ + boost/utility/detail/in_place_factory_suffix.hpp \ + boost/utility/detail/result_of_iterate.hpp \ + boost/utility/enable_if.hpp \ + boost/utility/in_place_factory.hpp \ + boost/utility/result_of.hpp \ + boost/utility/swap.hpp \ + boost/utility/typed_in_place_factory.hpp \ + boost/utility/value_init.hpp \ + boost/variant.hpp \ + boost/variant/variant.hpp \ + boost/variant/visitor_ptr.hpp \ + boost/variant/static_visitor.hpp \ + boost/variant/recursive_variant.hpp \ + boost/variant/get.hpp \ + boost/variant/variant_fwd.hpp \ + boost/variant/bad_visit.hpp \ + boost/variant/detail/substitute.hpp \ + boost/variant/detail/enable_recursive_fwd.hpp \ + boost/variant/detail/cast_storage.hpp \ + boost/variant/detail/make_variant_list.hpp \ + boost/variant/detail/backup_holder.hpp \ + boost/variant/detail/bool_trait_undef.hpp \ + boost/variant/detail/apply_visitor_unary.hpp \ + boost/variant/detail/generic_result_type.hpp \ + boost/variant/detail/variant_io.hpp \ + boost/variant/detail/substitute_fwd.hpp \ + boost/variant/detail/forced_return.hpp \ + boost/variant/detail/apply_visitor_binary.hpp \ + boost/variant/detail/move.hpp \ + boost/variant/detail/enable_recursive.hpp \ + boost/variant/detail/visitation_impl.hpp \ + boost/variant/detail/has_trivial_move.hpp \ + boost/variant/detail/config.hpp \ + boost/variant/detail/initializer.hpp \ + boost/variant/detail/bool_trait_def.hpp \ + boost/variant/detail/over_sequence.hpp \ + boost/variant/detail/has_nothrow_move.hpp \ + boost/variant/detail/apply_visitor_delayed.hpp \ + boost/variant/apply_visitor.hpp \ + boost/variant/recursive_wrapper.hpp \ + boost/variant/recursive_wrapper_fwd.hpp \ + boost/version.hpp \ + boost/visit_each.hpp \ + boost/wave.hpp \ + boost/weak_ptr.hpp test: @@ -68,6 +2857,3 @@ docs: bootstrap: install-data-am -install-data-hook: - cp -Rpf boost $(DESTDIR)$(includedir) - diff --git a/utils/boost_idb/Makefile.in b/utils/boost_idb/Makefile.in index a5540dca..594e1915 100644 --- a/utils/boost_idb/Makefile.in +++ b/utils/boost_idb/Makefile.in @@ -14,22 +14,22 @@ @SET_MAKE@ -# Copyright (C) 2014 InfiniDB, Inc. +# Copyright (C) 2014 InfiniDB, Inc. # -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; version 2 of -# the License. +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; version 2 of +# the License. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. # $Id$ @@ -57,12 +57,11 @@ POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = utils/boost_idb -DIST_COMMON = README $(include_HEADERS) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in +DIST_COMMON = README $(include_HEADERS) $(nobase_include_HEADERS) \ + $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/compilerflags.m4 \ - $(top_srcdir)/m4/functions.m4 $(top_srcdir)/m4/install.m4 \ - $(top_srcdir)/configure.ac +am__aclocal_m4_deps = $(top_srcdir)/m4/functions.m4 \ + $(top_srcdir)/m4/install.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d @@ -74,19 +73,20 @@ am__vpath_adj = case $$p in \ *) f=$$p;; \ esac; am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; -am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" \ + "$(DESTDIR)$(includedir)" libLTLIBRARIES_INSTALL = $(INSTALL) LTLIBRARIES = $(lib_LTLIBRARIES) libboost_idb_la_LIBADD = -am_libboost_idb_la_OBJECTS = codecvt_error_category.lo \ - cpp_regex_traits.lo cregex.lo c_regex_traits.lo error_code.lo \ - fileiter.lo future.lo greg_month.lo icu.lo instances.lo \ - once.lo operations.lo path.lo path_traits.lo portability.lo \ - posix_api.lo regex.lo regex_debug.lo regex_raw_buffer.lo \ - regex_traits_defaults.lo static_mutex.lo thread.lo tss_null.lo \ - unique_path.lo usinstances.lo utf8_codecvt_facet.lo \ +am_libboost_idb_la_OBJECTS = c_regex_traits.lo cpp_regex_traits.lo \ + cregex.lo date_generators.lo error_code.lo fileiter.lo \ + greg_month.lo greg_weekday.lo gregorian_types.lo icu.lo \ + instances.lo once.lo operations.lo path.lo portability.lo \ + posix_api.lo posix_time_types.lo regex.lo regex_debug.lo \ + regex_raw_buffer.lo regex_traits_defaults.lo static_mutex.lo \ + thread.lo usinstances.lo utf8_codecvt_facet.lo \ w32_regex_traits.lo wc_regex_traits.lo wide_posix_api.lo \ - windows_file_codecvt.lo winstances.lo + winstances.lo libboost_idb_la_OBJECTS = $(am_libboost_idb_la_OBJECTS) DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp @@ -102,7 +102,8 @@ CXXLINK = $(LIBTOOL) --tag=CXX --mode=link $(CXXLD) $(AM_CXXFLAGS) \ SOURCES = $(libboost_idb_la_SOURCES) DIST_SOURCES = $(libboost_idb_la_SOURCES) includeHEADERS_INSTALL = $(INSTALL_HEADER) -HEADERS = $(include_HEADERS) +nobase_includeHEADERS_INSTALL = $(install_sh_DATA) +HEADERS = $(include_HEADERS) $(nobase_include_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) @@ -165,9 +166,6 @@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ -XML2_CONFIG = @XML2_CONFIG@ -XML_CPPFLAGS = @XML_CPPFLAGS@ -XML_LIBS = @XML_LIBS@ YACC = @YACC@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ @@ -209,7 +207,6 @@ idb_exec_libs = @idb_exec_libs@ idb_ldflags = @idb_ldflags@ idb_oam_libs = @idb_oam_libs@ idb_write_libs = @idb_write_libs@ -idbinstall = @idbinstall@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ @@ -223,11 +220,6 @@ mibdir = @mibdir@ mkdir_p = @mkdir_p@ mysqldir = @mysqldir@ netsnmp_libs = @netsnmp_libs@ -netsnmpagntdir = @netsnmpagntdir@ -netsnmpdir = @netsnmpdir@ -netsnmplibrdir = @netsnmplibrdir@ -netsnmpmachdir = @netsnmpmachdir@ -netsnmpsysdir = @netsnmpsysdir@ oldincludedir = @oldincludedir@ postdir = @postdir@ prefix = @prefix@ @@ -244,39 +236,2829 @@ AM_CXXFLAGS = $(idb_cxxflags) AM_LDFLAGS = -version-info 1:0:0 $(idb_ldflags) lib_LTLIBRARIES = libboost_idb.la libboost_idb_la_SOURCES = \ - codecvt_error_category.cpp \ + c_regex_traits.cpp \ cpp_regex_traits.cpp \ cregex.cpp \ - c_regex_traits.cpp \ + date_generators.cpp \ error_code.cpp \ fileiter.cpp \ - future.cpp \ greg_month.cpp \ + greg_weekday.cpp \ + gregorian_types.cpp \ icu.cpp \ instances.cpp \ once.cpp \ operations.cpp \ path.cpp \ - path_traits.cpp \ portability.cpp \ posix_api.cpp \ + posix_time_types.cpp \ regex.cpp \ regex_debug.cpp \ regex_raw_buffer.cpp \ regex_traits_defaults.cpp \ static_mutex.cpp \ thread.cpp \ - tss_null.cpp \ - unique_path.cpp \ usinstances.cpp \ utf8_codecvt_facet.cpp \ w32_regex_traits.cpp \ wc_regex_traits.cpp \ wide_posix_api.cpp \ - windows_file_codecvt.cpp \ winstances.cpp include_HEADERS = +nobase_include_HEADERS = \ + boost/algorithm/minmax.hpp \ + boost/algorithm/minmax_element.hpp \ + boost/algorithm/string.hpp \ + boost/algorithm/string/case_conv.hpp \ + boost/algorithm/string/classification.hpp \ + boost/algorithm/string/compare.hpp \ + boost/algorithm/string/concept.hpp \ + boost/algorithm/string/config.hpp \ + boost/algorithm/string/constants.hpp \ + boost/algorithm/string/detail/case_conv.hpp \ + boost/algorithm/string/detail/classification.hpp \ + boost/algorithm/string/detail/find_format.hpp \ + boost/algorithm/string/detail/find_format_all.hpp \ + boost/algorithm/string/detail/find_format_store.hpp \ + boost/algorithm/string/detail/find_iterator.hpp \ + boost/algorithm/string/detail/finder.hpp \ + boost/algorithm/string/detail/finder_regex.hpp \ + boost/algorithm/string/detail/formatter.hpp \ + boost/algorithm/string/detail/formatter_regex.hpp \ + boost/algorithm/string/detail/predicate.hpp \ + boost/algorithm/string/detail/replace_storage.hpp \ + boost/algorithm/string/detail/sequence.hpp \ + boost/algorithm/string/detail/trim.hpp \ + boost/algorithm/string/detail/util.hpp \ + boost/algorithm/string/erase.hpp \ + boost/algorithm/string/find.hpp \ + boost/algorithm/string/find_format.hpp \ + boost/algorithm/string/find_iterator.hpp \ + boost/algorithm/string/finder.hpp \ + boost/algorithm/string/formatter.hpp \ + boost/algorithm/string/iter_find.hpp \ + boost/algorithm/string/join.hpp \ + boost/algorithm/string/predicate.hpp \ + boost/algorithm/string/predicate_facade.hpp \ + boost/algorithm/string/regex.hpp \ + boost/algorithm/string/regex_find_format.hpp \ + boost/algorithm/string/replace.hpp \ + boost/algorithm/string/sequence_traits.hpp \ + boost/algorithm/string/split.hpp \ + boost/algorithm/string/std/list_traits.hpp \ + boost/algorithm/string/std/rope_traits.hpp \ + boost/algorithm/string/std/slist_traits.hpp \ + boost/algorithm/string/std/string_traits.hpp \ + boost/algorithm/string/std_containers_traits.hpp \ + boost/algorithm/string/trim.hpp \ + boost/algorithm/string/yes_no_type.hpp \ + boost/algorithm/string_regex.hpp \ + boost/aligned_storage.hpp \ + boost/any.hpp \ + boost/array.hpp \ + boost/asio.hpp \ + boost/assert.hpp \ + boost/assign.hpp \ + boost/assign/list_inserter.hpp \ + boost/assign/ptr_list_inserter.hpp \ + boost/assign/list_of.hpp \ + boost/assign/assignment_exception.hpp \ + boost/assign/std.hpp \ + boost/assign/ptr_list_of.hpp \ + boost/assign/ptr_map_inserter.hpp \ + boost/assign/std/list.hpp \ + boost/assign/std/stack.hpp \ + boost/assign/std/set.hpp \ + boost/assign/std/slist.hpp \ + boost/assign/std/vector.hpp \ + boost/assign/std/map.hpp \ + boost/assign/std/deque.hpp \ + boost/assign/std/queue.hpp \ + boost/bimap.hpp \ + boost/bind.hpp \ + boost/bind/apply.hpp \ + boost/bind/arg.hpp \ + boost/bind/bind.hpp \ + boost/bind/bind_cc.hpp \ + boost/bind/bind_mf2_cc.hpp \ + boost/bind/bind_mf_cc.hpp \ + boost/bind/bind_template.hpp \ + boost/bind/make_adaptable.hpp \ + boost/bind/mem_fn.hpp \ + boost/bind/mem_fn_cc.hpp \ + boost/bind/mem_fn_template.hpp \ + boost/bind/mem_fn_vw.hpp \ + boost/bind/placeholders.hpp \ + boost/bind/protect.hpp \ + boost/bind/storage.hpp \ + boost/blank.hpp \ + boost/blank_fwd.hpp \ + boost/call_traits.hpp \ + boost/cast.hpp \ + boost/cerrno.hpp \ + boost/checked_delete.hpp \ + boost/circular_buffer.hpp \ + boost/circular_buffer_fwd.hpp \ + boost/compressed_pair.hpp \ + boost/concept/assert.hpp \ + boost/concept/detail/backward_compatibility.hpp \ + boost/concept/detail/borland.hpp \ + boost/concept/detail/concept_def.hpp \ + boost/concept/detail/concept_undef.hpp \ + boost/concept/detail/general.hpp \ + boost/concept/detail/has_constraints.hpp \ + boost/concept/detail/msvc.hpp \ + boost/concept/requires.hpp \ + boost/concept/usage.hpp \ + boost/concept_archetype.hpp \ + boost/concept_check.hpp \ + boost/config.hpp \ + boost/config/abi/borland_prefix.hpp \ + boost/config/abi/borland_suffix.hpp \ + boost/config/abi/msvc_prefix.hpp \ + boost/config/abi/msvc_suffix.hpp \ + boost/config/abi_prefix.hpp \ + boost/config/abi_suffix.hpp \ + boost/config/auto_link.hpp \ + boost/config/compiler/borland.hpp \ + boost/config/compiler/clang.hpp \ + boost/config/compiler/codegear.hpp \ + boost/config/compiler/comeau.hpp \ + boost/config/compiler/common_edg.hpp \ + boost/config/compiler/compaq_cxx.hpp \ + boost/config/compiler/digitalmars.hpp \ + boost/config/compiler/gcc.hpp \ + boost/config/compiler/gcc_xml.hpp \ + boost/config/compiler/greenhills.hpp \ + boost/config/compiler/hp_acc.hpp \ + boost/config/compiler/intel.hpp \ + boost/config/compiler/kai.hpp \ + boost/config/compiler/metrowerks.hpp \ + boost/config/compiler/mpw.hpp \ + boost/config/compiler/nvcc.hpp \ + boost/config/compiler/pgi.hpp \ + boost/config/compiler/sgi_mipspro.hpp \ + boost/config/compiler/sunpro_cc.hpp \ + boost/config/compiler/vacpp.hpp \ + boost/config/compiler/visualc.hpp \ + boost/config/no_tr1/cmath.hpp \ + boost/config/no_tr1/complex.hpp \ + boost/config/no_tr1/functional.hpp \ + boost/config/no_tr1/memory.hpp \ + boost/config/no_tr1/utility.hpp \ + boost/config/platform/aix.hpp \ + boost/config/platform/amigaos.hpp \ + boost/config/platform/beos.hpp \ + boost/config/platform/bsd.hpp \ + boost/config/platform/cygwin.hpp \ + boost/config/platform/hpux.hpp \ + boost/config/platform/irix.hpp \ + boost/config/platform/linux.hpp \ + boost/config/platform/macos.hpp \ + boost/config/platform/qnxnto.hpp \ + boost/config/platform/solaris.hpp \ + boost/config/platform/symbian.hpp \ + boost/config/platform/vms.hpp \ + boost/config/platform/vxworks.hpp \ + boost/config/platform/win32.hpp \ + boost/config/posix_features.hpp \ + boost/config/requires_threads.hpp \ + boost/config/select_compiler_config.hpp \ + boost/config/select_platform_config.hpp \ + boost/config/select_stdlib_config.hpp \ + boost/config/stdlib/dinkumware.hpp \ + boost/config/stdlib/libcomo.hpp \ + boost/config/stdlib/libstdcpp3.hpp \ + boost/config/stdlib/modena.hpp \ + boost/config/stdlib/msl.hpp \ + boost/config/stdlib/roguewave.hpp \ + boost/config/stdlib/sgi.hpp \ + boost/config/stdlib/stlport.hpp \ + boost/config/stdlib/vacpp.hpp \ + boost/config/suffix.hpp \ + boost/config/user.hpp \ + boost/config/warning_disable.hpp \ + boost/crc.hpp \ + boost/cregex.hpp \ + boost/cstdint.hpp \ + boost/cstdlib.hpp \ + boost/current_function.hpp \ + boost/date_time.hpp \ + boost/date_time/adjust_functors.hpp \ + boost/date_time/c_local_time_adjustor.hpp \ + boost/date_time/c_time.hpp \ + boost/date_time/compiler_config.hpp \ + boost/date_time/constrained_value.hpp \ + boost/date_time/date.hpp \ + boost/date_time/date_clock_device.hpp \ + boost/date_time/date_defs.hpp \ + boost/date_time/date_duration.hpp \ + boost/date_time/date_duration_types.hpp \ + boost/date_time/date_facet.hpp \ + boost/date_time/date_format_simple.hpp \ + boost/date_time/date_formatting.hpp \ + boost/date_time/date_formatting_limited.hpp \ + boost/date_time/date_formatting_locales.hpp \ + boost/date_time/date_generator_formatter.hpp \ + boost/date_time/date_generator_parser.hpp \ + boost/date_time/date_generators.hpp \ + boost/date_time/date_iterator.hpp \ + boost/date_time/date_names_put.hpp \ + boost/date_time/date_parsing.hpp \ + boost/date_time/dst_rules.hpp \ + boost/date_time/dst_transition_generators.hpp \ + boost/date_time/filetime_functions.hpp \ + boost/date_time/format_date_parser.hpp \ + boost/date_time/gregorian/conversion.hpp \ + boost/date_time/gregorian/formatters.hpp \ + boost/date_time/gregorian/formatters_limited.hpp \ + boost/date_time/gregorian/greg_calendar.hpp \ + boost/date_time/gregorian/greg_date.hpp \ + boost/date_time/gregorian/greg_day.hpp \ + boost/date_time/gregorian/greg_day_of_year.hpp \ + boost/date_time/gregorian/greg_duration.hpp \ + boost/date_time/gregorian/greg_duration_types.hpp \ + boost/date_time/gregorian/greg_facet.hpp \ + boost/date_time/gregorian/greg_month.hpp \ + boost/date_time/gregorian/greg_serialize.hpp \ + boost/date_time/gregorian/greg_weekday.hpp \ + boost/date_time/gregorian/greg_year.hpp \ + boost/date_time/gregorian/greg_ymd.hpp \ + boost/date_time/gregorian/gregorian.hpp \ + boost/date_time/gregorian/gregorian_io.hpp \ + boost/date_time/gregorian/gregorian_types.hpp \ + boost/date_time/gregorian/parsers.hpp \ + boost/date_time/gregorian_calendar.hpp \ + boost/date_time/gregorian_calendar.ipp \ + boost/date_time/int_adapter.hpp \ + boost/date_time/iso_format.hpp \ + boost/date_time/local_time/conversion.hpp \ + boost/date_time/local_time/custom_time_zone.hpp \ + boost/date_time/local_time/date_duration_operators.hpp \ + boost/date_time/local_time/dst_transition_day_rules.hpp \ + boost/date_time/local_time/local_date_time.hpp \ + boost/date_time/local_time/local_time.hpp \ + boost/date_time/local_time/local_time_io.hpp \ + boost/date_time/local_time/local_time_types.hpp \ + boost/date_time/local_time/posix_time_zone.hpp \ + boost/date_time/local_time/tz_database.hpp \ + boost/date_time/local_time_adjustor.hpp \ + boost/date_time/local_timezone_defs.hpp \ + boost/date_time/locale_config.hpp \ + boost/date_time/microsec_time_clock.hpp \ + boost/date_time/parse_format_base.hpp \ + boost/date_time/period.hpp \ + boost/date_time/period_formatter.hpp \ + boost/date_time/period_parser.hpp \ + boost/date_time/posix_time/conversion.hpp \ + boost/date_time/posix_time/date_duration_operators.hpp \ + boost/date_time/posix_time/posix_time.hpp \ + boost/date_time/posix_time/posix_time_config.hpp \ + boost/date_time/posix_time/posix_time_duration.hpp \ + boost/date_time/posix_time/posix_time_io.hpp \ + boost/date_time/posix_time/posix_time_legacy_io.hpp \ + boost/date_time/posix_time/posix_time_system.hpp \ + boost/date_time/posix_time/posix_time_types.hpp \ + boost/date_time/posix_time/ptime.hpp \ + boost/date_time/posix_time/time_formatters.hpp \ + boost/date_time/posix_time/time_formatters_limited.hpp \ + boost/date_time/posix_time/time_parsers.hpp \ + boost/date_time/posix_time/time_period.hpp \ + boost/date_time/posix_time/time_serialize.hpp \ + boost/date_time/special_defs.hpp \ + boost/date_time/special_values_formatter.hpp \ + boost/date_time/special_values_parser.hpp \ + boost/date_time/string_convert.hpp \ + boost/date_time/string_parse_tree.hpp \ + boost/date_time/strings_from_facet.hpp \ + boost/date_time/time.hpp \ + boost/date_time/time_clock.hpp \ + boost/date_time/time_defs.hpp \ + boost/date_time/time_duration.hpp \ + boost/date_time/time_facet.hpp \ + boost/date_time/time_formatting_streams.hpp \ + boost/date_time/time_iterator.hpp \ + boost/date_time/time_parsing.hpp \ + boost/date_time/time_resolution_traits.hpp \ + boost/date_time/time_system_counted.hpp \ + boost/date_time/time_system_split.hpp \ + boost/date_time/time_zone_base.hpp \ + boost/date_time/time_zone_names.hpp \ + boost/date_time/tz_db_base.hpp \ + boost/date_time/wrapping_int.hpp \ + boost/date_time/year_month_day.hpp \ + boost/detail/algorithm.hpp \ + boost/detail/allocator_utilities.hpp \ + boost/detail/atomic_count.hpp \ + boost/detail/binary_search.hpp \ + boost/detail/call_traits.hpp \ + boost/detail/catch_exceptions.hpp \ + boost/detail/compressed_pair.hpp \ + boost/detail/container_fwd.hpp \ + boost/detail/dynamic_bitset.hpp \ + boost/detail/endian.hpp \ + boost/detail/has_default_constructor.hpp \ + boost/detail/identifier.hpp \ + boost/detail/indirect_traits.hpp \ + boost/detail/interlocked.hpp \ + boost/detail/is_function_ref_tester.hpp \ + boost/detail/is_incrementable.hpp \ + boost/detail/is_xxx.hpp \ + boost/detail/iterator.hpp \ + boost/detail/lcast_precision.hpp \ + boost/detail/lightweight_mutex.hpp \ + boost/detail/lightweight_test.hpp \ + boost/detail/lightweight_thread.hpp \ + boost/detail/limits.hpp \ + boost/detail/named_template_params.hpp \ + boost/detail/no_exceptions_support.hpp \ + boost/detail/none_t.hpp \ + boost/detail/numeric_traits.hpp \ + boost/detail/ob_call_traits.hpp \ + boost/detail/ob_compressed_pair.hpp \ + boost/detail/quick_allocator.hpp \ + boost/detail/reference_content.hpp \ + boost/detail/scoped_enum_emulation.hpp \ + boost/detail/select_type.hpp \ + boost/detail/sp_typeinfo.hpp \ + boost/detail/templated_streams.hpp \ + boost/detail/utf8_codecvt_facet.hpp \ + boost/detail/workaround.hpp \ + boost/dynamic_bitset.hpp \ + boost/dynamic_bitset_fwd.hpp \ + boost/enable_shared_from_this.hpp \ + boost/exception.hpp \ + boost/exception/all.hpp \ + boost/exception/current_exception_cast.hpp \ + boost/exception/detail/attribute_noreturn.hpp \ + boost/exception/detail/error_info_impl.hpp \ + boost/exception/detail/exception_ptr.hpp \ + boost/exception/detail/is_output_streamable.hpp \ + boost/exception/detail/object_hex_dump.hpp \ + boost/exception/detail/type_info.hpp \ + boost/exception/diagnostic_information.hpp \ + boost/exception/enable_current_exception.hpp \ + boost/exception/enable_error_info.hpp \ + boost/exception/errinfo_api_function.hpp \ + boost/exception/errinfo_at_line.hpp \ + boost/exception/errinfo_errno.hpp \ + boost/exception/errinfo_file_handle.hpp \ + boost/exception/errinfo_file_name.hpp \ + boost/exception/errinfo_file_open_mode.hpp \ + boost/exception/errinfo_nested_exception.hpp \ + boost/exception/errinfo_type_info_name.hpp \ + boost/exception/error_info.hpp \ + boost/exception/exception.hpp \ + boost/exception/get_error_info.hpp \ + boost/exception/info.hpp \ + boost/exception/info_tuple.hpp \ + boost/exception/to_string.hpp \ + boost/exception/to_string_stub.hpp \ + boost/exception_ptr.hpp \ + boost/filesystem.hpp \ + boost/filesystem/config.hpp \ + boost/filesystem/convenience.hpp \ + boost/filesystem/exception.hpp \ + boost/filesystem/fstream.hpp \ + boost/filesystem/operations.hpp \ + boost/filesystem/path.hpp \ + boost/filesystem/v2/config.hpp \ + boost/filesystem/v2/convenience.hpp \ + boost/filesystem/v2/exception.hpp \ + boost/filesystem/v2/fstream.hpp \ + boost/filesystem/v2/operations.hpp \ + boost/filesystem/v2/path.hpp \ + boost/flyweight.hpp \ + boost/foreach.hpp \ + boost/foreach_fwd.hpp \ + boost/format.hpp \ + boost/format/alt_sstream.hpp \ + boost/format/alt_sstream_impl.hpp \ + boost/format/detail/compat_workarounds.hpp \ + boost/format/detail/config_macros.hpp \ + boost/format/detail/msvc_disambiguater.hpp \ + boost/format/detail/unset_macros.hpp \ + boost/format/detail/workarounds_gcc-2_95.hpp \ + boost/format/detail/workarounds_stlport.hpp \ + boost/format/exceptions.hpp \ + boost/format/feed_args.hpp \ + boost/format/format_class.hpp \ + boost/format/format_fwd.hpp \ + boost/format/format_implementation.hpp \ + boost/format/free_funcs.hpp \ + boost/format/group.hpp \ + boost/format/internals.hpp \ + boost/format/internals_fwd.hpp \ + boost/format/parsing.hpp \ + boost/function.hpp \ + boost/function/detail/function_iterate.hpp \ + boost/function/detail/maybe_include.hpp \ + boost/function/detail/prologue.hpp \ + boost/function/function0.hpp \ + boost/function/function1.hpp \ + boost/function/function10.hpp \ + boost/function/function2.hpp \ + boost/function/function3.hpp \ + boost/function/function4.hpp \ + boost/function/function5.hpp \ + boost/function/function6.hpp \ + boost/function/function7.hpp \ + boost/function/function8.hpp \ + boost/function/function9.hpp \ + boost/function/function_base.hpp \ + boost/function/function_fwd.hpp \ + boost/function/function_template.hpp \ + boost/function/function_typeof.hpp \ + boost/function_equal.hpp \ + boost/function_output_iterator.hpp \ + boost/functional.hpp \ + boost/functional/detail/container_fwd.hpp \ + boost/functional/factory.hpp \ + boost/functional/forward_adapter.hpp \ + boost/functional/hash.hpp \ + boost/functional/hash/detail/float_functions.hpp \ + boost/functional/hash/detail/hash_float.hpp \ + boost/functional/hash/detail/hash_float_generic.hpp \ + boost/functional/hash/detail/hash_float_x86.hpp \ + boost/functional/hash/detail/limits.hpp \ + boost/functional/hash/extensions.hpp \ + boost/functional/hash/hash.hpp \ + boost/functional/hash/hash_fwd.hpp \ + boost/functional/hash_fwd.hpp \ + boost/functional/lightweight_forward_adapter.hpp \ + boost/functional/value_factory.hpp \ + boost/generator_iterator.hpp \ + boost/get_pointer.hpp \ + boost/implicit_cast.hpp \ + boost/indirect_reference.hpp \ + boost/integer.hpp \ + boost/integer/integer_mask.hpp \ + boost/integer/static_log2.hpp \ + boost/integer/static_min_max.hpp \ + boost/integer_fwd.hpp \ + boost/integer_traits.hpp \ + boost/interprocess/allocators/adaptive_pool.hpp \ + boost/interprocess/allocators/allocator.hpp \ + boost/interprocess/allocators/cached_adaptive_pool.hpp \ + boost/interprocess/allocators/cached_node_allocator.hpp \ + boost/interprocess/allocators/detail/adaptive_node_pool.hpp \ + boost/interprocess/allocators/detail/allocator_common.hpp \ + boost/interprocess/allocators/detail/node_pool.hpp \ + boost/interprocess/allocators/detail/node_tools.hpp \ + boost/interprocess/allocators/node_allocator.hpp \ + boost/interprocess/allocators/private_adaptive_pool.hpp \ + boost/interprocess/allocators/private_node_allocator.hpp \ + boost/interprocess/anonymous_shared_memory.hpp \ + boost/interprocess/containers/allocation_type.hpp \ + boost/interprocess/containers/container/container_fwd.hpp \ + boost/interprocess/containers/container/deque.hpp \ + boost/interprocess/containers/container/detail/adaptive_node_pool_impl.hpp \ + boost/interprocess/containers/container/detail/advanced_insert_int.hpp \ + boost/interprocess/containers/container/detail/algorithms.hpp \ + boost/interprocess/containers/container/detail/allocation_type.hpp \ + boost/interprocess/containers/container/detail/config_begin.hpp \ + boost/interprocess/containers/container/detail/config_end.hpp \ + boost/interprocess/containers/container/detail/destroyers.hpp \ + boost/interprocess/containers/container/detail/flat_tree.hpp \ + boost/interprocess/containers/container/detail/iterators.hpp \ + boost/interprocess/containers/container/detail/math_functions.hpp \ + boost/interprocess/containers/container/detail/mpl.hpp \ + boost/interprocess/containers/container/detail/multiallocation_chain.hpp \ + boost/interprocess/containers/container/detail/node_alloc_holder.hpp \ + boost/interprocess/containers/container/detail/node_pool_impl.hpp \ + boost/interprocess/containers/container/detail/pair.hpp \ + boost/interprocess/containers/container/detail/pool_common.hpp \ + boost/interprocess/containers/container/detail/preprocessor.hpp \ + boost/interprocess/containers/container/detail/stored_ref.hpp \ + boost/interprocess/containers/container/detail/transform_iterator.hpp \ + boost/interprocess/containers/container/detail/tree.hpp \ + boost/interprocess/containers/container/detail/type_traits.hpp \ + boost/interprocess/containers/container/detail/utilities.hpp \ + boost/interprocess/containers/container/detail/value_init.hpp \ + boost/interprocess/containers/container/detail/variadic_templates_tools.hpp \ + boost/interprocess/containers/container/detail/version_type.hpp \ + boost/interprocess/containers/container/detail/workaround.hpp \ + boost/interprocess/containers/container/flat_map.hpp \ + boost/interprocess/containers/container/flat_set.hpp \ + boost/interprocess/containers/container/list.hpp \ + boost/interprocess/containers/container/map.hpp \ + boost/interprocess/containers/container/set.hpp \ + boost/interprocess/containers/container/slist.hpp \ + boost/interprocess/containers/container/stable_vector.hpp \ + boost/interprocess/containers/container/string.hpp \ + boost/interprocess/containers/container/vector.hpp \ + boost/interprocess/containers/containers_fwd.hpp \ + boost/interprocess/containers/deque.hpp \ + boost/interprocess/containers/flat_map.hpp \ + boost/interprocess/containers/flat_set.hpp \ + boost/interprocess/containers/list.hpp \ + boost/interprocess/containers/map.hpp \ + boost/interprocess/containers/pair.hpp \ + boost/interprocess/containers/set.hpp \ + boost/interprocess/containers/slist.hpp \ + boost/interprocess/containers/stable_vector.hpp \ + boost/interprocess/containers/string.hpp \ + boost/interprocess/containers/vector.hpp \ + boost/interprocess/containers/version_type.hpp \ + boost/interprocess/creation_tags.hpp \ + boost/interprocess/detail/atomic.hpp \ + boost/interprocess/detail/cast_tags.hpp \ + boost/interprocess/detail/config_begin.hpp \ + boost/interprocess/detail/config_end.hpp \ + boost/interprocess/detail/file_wrapper.hpp \ + boost/interprocess/detail/in_place_interface.hpp \ + boost/interprocess/detail/intermodule_singleton.hpp \ + boost/interprocess/detail/interprocess_tester.hpp \ + boost/interprocess/detail/intersegment_ptr.hpp \ + boost/interprocess/detail/managed_memory_impl.hpp \ + boost/interprocess/detail/managed_multi_shared_memory.hpp \ + boost/interprocess/detail/managed_open_or_create_impl.hpp \ + boost/interprocess/detail/math_functions.hpp \ + boost/interprocess/detail/min_max.hpp \ + boost/interprocess/detail/move.hpp \ + boost/interprocess/detail/mpl.hpp \ + boost/interprocess/detail/multi_segment_services.hpp \ + boost/interprocess/detail/named_proxy.hpp \ + boost/interprocess/detail/os_file_functions.hpp \ + boost/interprocess/detail/os_thread_functions.hpp \ + boost/interprocess/detail/pointer_type.hpp \ + boost/interprocess/detail/posix_time_types_wrk.hpp \ + boost/interprocess/detail/preprocessor.hpp \ + boost/interprocess/detail/ptime_wrk.hpp \ + boost/interprocess/detail/robust_emulation.hpp \ + boost/interprocess/detail/segment_manager_helper.hpp \ + boost/interprocess/detail/tmp_dir_helpers.hpp \ + boost/interprocess/detail/transform_iterator.hpp \ + boost/interprocess/detail/type_traits.hpp \ + boost/interprocess/detail/utilities.hpp \ + boost/interprocess/detail/variadic_templates_tools.hpp \ + boost/interprocess/detail/win32_api.hpp \ + boost/interprocess/detail/workaround.hpp \ + boost/interprocess/detail/xsi_shared_memory.hpp \ + boost/interprocess/detail/xsi_shared_memory_device.hpp \ + boost/interprocess/errors.hpp \ + boost/interprocess/exceptions.hpp \ + boost/interprocess/file_mapping.hpp \ + boost/interprocess/indexes/flat_map_index.hpp \ + boost/interprocess/indexes/iset_index.hpp \ + boost/interprocess/indexes/iunordered_set_index.hpp \ + boost/interprocess/indexes/map_index.hpp \ + boost/interprocess/indexes/null_index.hpp \ + boost/interprocess/indexes/unordered_map_index.hpp \ + boost/interprocess/interprocess_fwd.hpp \ + boost/interprocess/ipc/message_queue.hpp \ + boost/interprocess/managed_external_buffer.hpp \ + boost/interprocess/managed_heap_memory.hpp \ + boost/interprocess/managed_mapped_file.hpp \ + boost/interprocess/managed_shared_memory.hpp \ + boost/interprocess/managed_windows_shared_memory.hpp \ + boost/interprocess/mapped_region.hpp \ + boost/interprocess/mem_algo/detail/mem_algo_common.hpp \ + boost/interprocess/mem_algo/detail/multi_simple_seq_fit.hpp \ + boost/interprocess/mem_algo/detail/multi_simple_seq_fit_impl.hpp \ + boost/interprocess/mem_algo/detail/simple_seq_fit_impl.hpp \ + boost/interprocess/mem_algo/rbtree_best_fit.hpp \ + boost/interprocess/mem_algo/simple_seq_fit.hpp \ + boost/interprocess/offset_ptr.hpp \ + boost/interprocess/permissions.hpp \ + boost/interprocess/segment_manager.hpp \ + boost/interprocess/shared_memory_object.hpp \ + boost/interprocess/smart_ptr/deleter.hpp \ + boost/interprocess/smart_ptr/detail/bad_weak_ptr.hpp \ + boost/interprocess/smart_ptr/detail/shared_count.hpp \ + boost/interprocess/smart_ptr/detail/sp_counted_base.hpp \ + boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp \ + boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp \ + boost/interprocess/smart_ptr/enable_shared_from_this.hpp \ + boost/interprocess/smart_ptr/intrusive_ptr.hpp \ + boost/interprocess/smart_ptr/scoped_ptr.hpp \ + boost/interprocess/smart_ptr/shared_ptr.hpp \ + boost/interprocess/smart_ptr/unique_ptr.hpp \ + boost/interprocess/smart_ptr/weak_ptr.hpp \ + boost/interprocess/streams/bufferstream.hpp \ + boost/interprocess/streams/vectorstream.hpp \ + boost/interprocess/sync/emulation/interprocess_barrier.hpp \ + boost/interprocess/sync/emulation/interprocess_condition.hpp \ + boost/interprocess/sync/emulation/interprocess_semaphore.hpp \ + boost/interprocess/sync/emulation/mutex.hpp \ + boost/interprocess/sync/emulation/named_creation_functor.hpp \ + boost/interprocess/sync/emulation/recursive_mutex.hpp \ + boost/interprocess/sync/file_lock.hpp \ + boost/interprocess/sync/interprocess_barrier.hpp \ + boost/interprocess/sync/interprocess_condition.hpp \ + boost/interprocess/sync/interprocess_mutex.hpp \ + boost/interprocess/sync/interprocess_recursive_mutex.hpp \ + boost/interprocess/sync/interprocess_semaphore.hpp \ + boost/interprocess/sync/interprocess_upgradable_mutex.hpp \ + boost/interprocess/sync/lock_options.hpp \ + boost/interprocess/sync/mutex_family.hpp \ + boost/interprocess/sync/named_condition.hpp \ + boost/interprocess/sync/named_mutex.hpp \ + boost/interprocess/sync/named_recursive_mutex.hpp \ + boost/interprocess/sync/named_semaphore.hpp \ + boost/interprocess/sync/named_upgradable_mutex.hpp \ + boost/interprocess/sync/null_mutex.hpp \ + boost/interprocess/sync/posix/interprocess_barrier.hpp \ + boost/interprocess/sync/posix/interprocess_condition.hpp \ + boost/interprocess/sync/posix/interprocess_mutex.hpp \ + boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp \ + boost/interprocess/sync/posix/interprocess_semaphore.hpp \ + boost/interprocess/sync/posix/pthread_helpers.hpp \ + boost/interprocess/sync/posix/ptime_to_timespec.hpp \ + boost/interprocess/sync/posix/semaphore_wrapper.hpp \ + boost/interprocess/sync/scoped_lock.hpp \ + boost/interprocess/sync/sharable_lock.hpp \ + boost/interprocess/sync/upgradable_lock.hpp \ + boost/interprocess/sync/xsi/advanced_xsi_semaphore.hpp \ + boost/interprocess/sync/xsi/simple_xsi_semaphore.hpp \ + boost/interprocess/sync/xsi/xsi_named_mutex.hpp \ + boost/interprocess/windows_shared_memory.hpp \ + boost/intrusive_ptr.hpp \ + boost/io/ios_state.hpp \ + boost/io_fwd.hpp \ + boost/is_placeholder.hpp \ + boost/iterator.hpp \ + boost/iterator/counting_iterator.hpp \ + boost/iterator/detail/any_conversion_eater.hpp \ + boost/iterator/detail/config_def.hpp \ + boost/iterator/detail/config_undef.hpp \ + boost/iterator/detail/enable_if.hpp \ + boost/iterator/detail/facade_iterator_category.hpp \ + boost/iterator/detail/minimum_category.hpp \ + boost/iterator/filter_iterator.hpp \ + boost/iterator/indirect_iterator.hpp \ + boost/iterator/interoperable.hpp \ + boost/iterator/is_lvalue_iterator.hpp \ + boost/iterator/is_readable_iterator.hpp \ + boost/iterator/iterator_adaptor.hpp \ + boost/iterator/iterator_archetypes.hpp \ + boost/iterator/iterator_categories.hpp \ + boost/iterator/iterator_concepts.hpp \ + boost/iterator/iterator_facade.hpp \ + boost/iterator/iterator_traits.hpp \ + boost/iterator/new_iterator_tests.hpp \ + boost/iterator/permutation_iterator.hpp \ + boost/iterator/reverse_iterator.hpp \ + boost/iterator/transform_iterator.hpp \ + boost/iterator/zip_iterator.hpp \ + boost/iterator_adaptors.hpp \ + boost/last_value.hpp \ + boost/lexical_cast.hpp \ + boost/limits.hpp \ + boost/make_shared.hpp \ + boost/math_fwd.hpp \ + boost/mem_fn.hpp \ + boost/memory_order.hpp \ + boost/mpi.hpp \ + boost/mpl/O1_size.hpp \ + boost/mpl/O1_size_fwd.hpp \ + boost/mpl/accumulate.hpp \ + boost/mpl/advance.hpp \ + boost/mpl/advance_fwd.hpp \ + boost/mpl/alias.hpp \ + boost/mpl/always.hpp \ + boost/mpl/and.hpp \ + boost/mpl/apply.hpp \ + boost/mpl/apply_fwd.hpp \ + boost/mpl/apply_wrap.hpp \ + boost/mpl/arg.hpp \ + boost/mpl/arg_fwd.hpp \ + boost/mpl/arithmetic.hpp \ + boost/mpl/as_sequence.hpp \ + boost/mpl/assert.hpp \ + boost/mpl/at.hpp \ + boost/mpl/at_fwd.hpp \ + boost/mpl/aux_/O1_size_impl.hpp \ + boost/mpl/aux_/adl_barrier.hpp \ + boost/mpl/aux_/advance_backward.hpp \ + boost/mpl/aux_/advance_forward.hpp \ + boost/mpl/aux_/apply_1st.hpp \ + boost/mpl/aux_/arg_typedef.hpp \ + boost/mpl/aux_/arithmetic_op.hpp \ + boost/mpl/aux_/arity.hpp \ + boost/mpl/aux_/arity_spec.hpp \ + boost/mpl/aux_/at_impl.hpp \ + boost/mpl/aux_/back_impl.hpp \ + boost/mpl/aux_/basic_bind.hpp \ + boost/mpl/aux_/begin_end_impl.hpp \ + boost/mpl/aux_/clear_impl.hpp \ + boost/mpl/aux_/common_name_wknd.hpp \ + boost/mpl/aux_/comparison_op.hpp \ + boost/mpl/aux_/config/adl.hpp \ + boost/mpl/aux_/config/arrays.hpp \ + boost/mpl/aux_/config/bcc.hpp \ + boost/mpl/aux_/config/bind.hpp \ + boost/mpl/aux_/config/compiler.hpp \ + boost/mpl/aux_/config/ctps.hpp \ + boost/mpl/aux_/config/dependent_nttp.hpp \ + boost/mpl/aux_/config/dmc_ambiguous_ctps.hpp \ + boost/mpl/aux_/config/dtp.hpp \ + boost/mpl/aux_/config/eti.hpp \ + boost/mpl/aux_/config/forwarding.hpp \ + boost/mpl/aux_/config/gcc.hpp \ + boost/mpl/aux_/config/has_apply.hpp \ + boost/mpl/aux_/config/has_xxx.hpp \ + boost/mpl/aux_/config/integral.hpp \ + boost/mpl/aux_/config/intel.hpp \ + boost/mpl/aux_/config/lambda.hpp \ + boost/mpl/aux_/config/msvc.hpp \ + boost/mpl/aux_/config/msvc_typename.hpp \ + boost/mpl/aux_/config/nttp.hpp \ + boost/mpl/aux_/config/operators.hpp \ + boost/mpl/aux_/config/overload_resolution.hpp \ + boost/mpl/aux_/config/pp_counter.hpp \ + boost/mpl/aux_/config/preprocessor.hpp \ + boost/mpl/aux_/config/static_constant.hpp \ + boost/mpl/aux_/config/ttp.hpp \ + boost/mpl/aux_/config/typeof.hpp \ + boost/mpl/aux_/config/use_preprocessed.hpp \ + boost/mpl/aux_/config/workaround.hpp \ + boost/mpl/aux_/contains_impl.hpp \ + boost/mpl/aux_/count_args.hpp \ + boost/mpl/aux_/count_impl.hpp \ + boost/mpl/aux_/empty_impl.hpp \ + boost/mpl/aux_/erase_impl.hpp \ + boost/mpl/aux_/erase_key_impl.hpp \ + boost/mpl/aux_/filter_iter.hpp \ + boost/mpl/aux_/find_if_pred.hpp \ + boost/mpl/aux_/fold_impl.hpp \ + boost/mpl/aux_/fold_impl_body.hpp \ + boost/mpl/aux_/fold_op.hpp \ + boost/mpl/aux_/fold_pred.hpp \ + boost/mpl/aux_/front_impl.hpp \ + boost/mpl/aux_/full_lambda.hpp \ + boost/mpl/aux_/has_apply.hpp \ + boost/mpl/aux_/has_begin.hpp \ + boost/mpl/aux_/has_key_impl.hpp \ + boost/mpl/aux_/has_rebind.hpp \ + boost/mpl/aux_/has_size.hpp \ + boost/mpl/aux_/has_tag.hpp \ + boost/mpl/aux_/has_type.hpp \ + boost/mpl/aux_/include_preprocessed.hpp \ + boost/mpl/aux_/insert_impl.hpp \ + boost/mpl/aux_/insert_range_impl.hpp \ + boost/mpl/aux_/inserter_algorithm.hpp \ + boost/mpl/aux_/integral_wrapper.hpp \ + boost/mpl/aux_/is_msvc_eti_arg.hpp \ + boost/mpl/aux_/iter_apply.hpp \ + boost/mpl/aux_/iter_fold_if_impl.hpp \ + boost/mpl/aux_/iter_fold_impl.hpp \ + boost/mpl/aux_/iter_push_front.hpp \ + boost/mpl/aux_/joint_iter.hpp \ + boost/mpl/aux_/lambda_arity_param.hpp \ + boost/mpl/aux_/lambda_no_ctps.hpp \ + boost/mpl/aux_/lambda_spec.hpp \ + boost/mpl/aux_/lambda_support.hpp \ + boost/mpl/aux_/largest_int.hpp \ + boost/mpl/aux_/logical_op.hpp \ + boost/mpl/aux_/msvc_dtw.hpp \ + boost/mpl/aux_/msvc_eti_base.hpp \ + boost/mpl/aux_/msvc_is_class.hpp \ + boost/mpl/aux_/msvc_never_true.hpp \ + boost/mpl/aux_/msvc_type.hpp \ + boost/mpl/aux_/na.hpp \ + boost/mpl/aux_/na_assert.hpp \ + boost/mpl/aux_/na_fwd.hpp \ + boost/mpl/aux_/na_spec.hpp \ + boost/mpl/aux_/nested_type_wknd.hpp \ + boost/mpl/aux_/nttp_decl.hpp \ + boost/mpl/aux_/numeric_cast_utils.hpp \ + boost/mpl/aux_/numeric_op.hpp \ + boost/mpl/aux_/order_impl.hpp \ + boost/mpl/aux_/overload_names.hpp \ + boost/mpl/aux_/partition_op.hpp \ + boost/mpl/aux_/pop_back_impl.hpp \ + boost/mpl/aux_/pop_front_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/bcc/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/bcc/and.hpp \ + boost/mpl/aux_/preprocessed/bcc/apply.hpp \ + boost/mpl/aux_/preprocessed/bcc/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/bcc/arg.hpp \ + boost/mpl/aux_/preprocessed/bcc/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/bcc/bind.hpp \ + boost/mpl/aux_/preprocessed/bcc/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc/bitand.hpp \ + boost/mpl/aux_/preprocessed/bcc/bitor.hpp \ + boost/mpl/aux_/preprocessed/bcc/bitxor.hpp \ + boost/mpl/aux_/preprocessed/bcc/deque.hpp \ + boost/mpl/aux_/preprocessed/bcc/divides.hpp \ + boost/mpl/aux_/preprocessed/bcc/equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/bcc/greater.hpp \ + boost/mpl/aux_/preprocessed/bcc/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc/inherit.hpp \ + boost/mpl/aux_/preprocessed/bcc/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/bcc/less.hpp \ + boost/mpl/aux_/preprocessed/bcc/less_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc/list.hpp \ + boost/mpl/aux_/preprocessed/bcc/list_c.hpp \ + boost/mpl/aux_/preprocessed/bcc/map.hpp \ + boost/mpl/aux_/preprocessed/bcc/minus.hpp \ + boost/mpl/aux_/preprocessed/bcc/modulus.hpp \ + boost/mpl/aux_/preprocessed/bcc/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc/or.hpp \ + boost/mpl/aux_/preprocessed/bcc/placeholders.hpp \ + boost/mpl/aux_/preprocessed/bcc/plus.hpp \ + boost/mpl/aux_/preprocessed/bcc/quote.hpp \ + boost/mpl/aux_/preprocessed/bcc/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc/set.hpp \ + boost/mpl/aux_/preprocessed/bcc/set_c.hpp \ + boost/mpl/aux_/preprocessed/bcc/shift_left.hpp \ + boost/mpl/aux_/preprocessed/bcc/shift_right.hpp \ + boost/mpl/aux_/preprocessed/bcc/template_arity.hpp \ + boost/mpl/aux_/preprocessed/bcc/times.hpp \ + boost/mpl/aux_/preprocessed/bcc/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/bcc/vector.hpp \ + boost/mpl/aux_/preprocessed/bcc/vector_c.hpp \ + boost/mpl/aux_/preprocessed/bcc551/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/bcc551/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/bcc551/and.hpp \ + boost/mpl/aux_/preprocessed/bcc551/apply.hpp \ + boost/mpl/aux_/preprocessed/bcc551/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc551/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/bcc551/arg.hpp \ + boost/mpl/aux_/preprocessed/bcc551/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bind.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bitand.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bitor.hpp \ + boost/mpl/aux_/preprocessed/bcc551/bitxor.hpp \ + boost/mpl/aux_/preprocessed/bcc551/deque.hpp \ + boost/mpl/aux_/preprocessed/bcc551/divides.hpp \ + boost/mpl/aux_/preprocessed/bcc551/equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc551/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/bcc551/greater.hpp \ + boost/mpl/aux_/preprocessed/bcc551/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc551/inherit.hpp \ + boost/mpl/aux_/preprocessed/bcc551/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/bcc551/less.hpp \ + boost/mpl/aux_/preprocessed/bcc551/less_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc551/list.hpp \ + boost/mpl/aux_/preprocessed/bcc551/list_c.hpp \ + boost/mpl/aux_/preprocessed/bcc551/map.hpp \ + boost/mpl/aux_/preprocessed/bcc551/minus.hpp \ + boost/mpl/aux_/preprocessed/bcc551/modulus.hpp \ + boost/mpl/aux_/preprocessed/bcc551/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc551/or.hpp \ + boost/mpl/aux_/preprocessed/bcc551/placeholders.hpp \ + boost/mpl/aux_/preprocessed/bcc551/plus.hpp \ + boost/mpl/aux_/preprocessed/bcc551/quote.hpp \ + boost/mpl/aux_/preprocessed/bcc551/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc551/set.hpp \ + boost/mpl/aux_/preprocessed/bcc551/set_c.hpp \ + boost/mpl/aux_/preprocessed/bcc551/shift_left.hpp \ + boost/mpl/aux_/preprocessed/bcc551/shift_right.hpp \ + boost/mpl/aux_/preprocessed/bcc551/template_arity.hpp \ + boost/mpl/aux_/preprocessed/bcc551/times.hpp \ + boost/mpl/aux_/preprocessed/bcc551/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/bcc551/vector.hpp \ + boost/mpl/aux_/preprocessed/bcc551/vector_c.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/and.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/apply.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/arg.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bind.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bitand.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bitor.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/bitxor.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/deque.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/divides.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/greater.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/inherit.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/less.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/less_equal.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/list.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/list_c.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/map.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/minus.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/modulus.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/or.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/placeholders.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/plus.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/quote.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/set.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/set_c.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/shift_left.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/shift_right.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/template_arity.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/times.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/vector.hpp \ + boost/mpl/aux_/preprocessed/bcc_pre590/vector_c.hpp \ + boost/mpl/aux_/preprocessed/dmc/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/dmc/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/dmc/and.hpp \ + boost/mpl/aux_/preprocessed/dmc/apply.hpp \ + boost/mpl/aux_/preprocessed/dmc/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/dmc/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/dmc/arg.hpp \ + boost/mpl/aux_/preprocessed/dmc/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/dmc/bind.hpp \ + boost/mpl/aux_/preprocessed/dmc/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/dmc/bitand.hpp \ + boost/mpl/aux_/preprocessed/dmc/bitor.hpp \ + boost/mpl/aux_/preprocessed/dmc/bitxor.hpp \ + boost/mpl/aux_/preprocessed/dmc/deque.hpp \ + boost/mpl/aux_/preprocessed/dmc/divides.hpp \ + boost/mpl/aux_/preprocessed/dmc/equal_to.hpp \ + boost/mpl/aux_/preprocessed/dmc/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/dmc/greater.hpp \ + boost/mpl/aux_/preprocessed/dmc/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/dmc/inherit.hpp \ + boost/mpl/aux_/preprocessed/dmc/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/dmc/less.hpp \ + boost/mpl/aux_/preprocessed/dmc/less_equal.hpp \ + boost/mpl/aux_/preprocessed/dmc/list.hpp \ + boost/mpl/aux_/preprocessed/dmc/list_c.hpp \ + boost/mpl/aux_/preprocessed/dmc/map.hpp \ + boost/mpl/aux_/preprocessed/dmc/minus.hpp \ + boost/mpl/aux_/preprocessed/dmc/modulus.hpp \ + boost/mpl/aux_/preprocessed/dmc/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/dmc/or.hpp \ + boost/mpl/aux_/preprocessed/dmc/placeholders.hpp \ + boost/mpl/aux_/preprocessed/dmc/plus.hpp \ + boost/mpl/aux_/preprocessed/dmc/quote.hpp \ + boost/mpl/aux_/preprocessed/dmc/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/dmc/set.hpp \ + boost/mpl/aux_/preprocessed/dmc/set_c.hpp \ + boost/mpl/aux_/preprocessed/dmc/shift_left.hpp \ + boost/mpl/aux_/preprocessed/dmc/shift_right.hpp \ + boost/mpl/aux_/preprocessed/dmc/template_arity.hpp \ + boost/mpl/aux_/preprocessed/dmc/times.hpp \ + boost/mpl/aux_/preprocessed/dmc/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/dmc/vector.hpp \ + boost/mpl/aux_/preprocessed/dmc/vector_c.hpp \ + boost/mpl/aux_/preprocessed/gcc/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/gcc/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/gcc/and.hpp \ + boost/mpl/aux_/preprocessed/gcc/apply.hpp \ + boost/mpl/aux_/preprocessed/gcc/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/gcc/arg.hpp \ + boost/mpl/aux_/preprocessed/gcc/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/gcc/bind.hpp \ + boost/mpl/aux_/preprocessed/gcc/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/gcc/bitand.hpp \ + boost/mpl/aux_/preprocessed/gcc/bitor.hpp \ + boost/mpl/aux_/preprocessed/gcc/bitxor.hpp \ + boost/mpl/aux_/preprocessed/gcc/deque.hpp \ + boost/mpl/aux_/preprocessed/gcc/divides.hpp \ + boost/mpl/aux_/preprocessed/gcc/equal_to.hpp \ + boost/mpl/aux_/preprocessed/gcc/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/gcc/greater.hpp \ + boost/mpl/aux_/preprocessed/gcc/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/gcc/inherit.hpp \ + boost/mpl/aux_/preprocessed/gcc/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/gcc/less.hpp \ + boost/mpl/aux_/preprocessed/gcc/less_equal.hpp \ + boost/mpl/aux_/preprocessed/gcc/list.hpp \ + boost/mpl/aux_/preprocessed/gcc/list_c.hpp \ + boost/mpl/aux_/preprocessed/gcc/map.hpp \ + boost/mpl/aux_/preprocessed/gcc/minus.hpp \ + boost/mpl/aux_/preprocessed/gcc/modulus.hpp \ + boost/mpl/aux_/preprocessed/gcc/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/gcc/or.hpp \ + boost/mpl/aux_/preprocessed/gcc/placeholders.hpp \ + boost/mpl/aux_/preprocessed/gcc/plus.hpp \ + boost/mpl/aux_/preprocessed/gcc/quote.hpp \ + boost/mpl/aux_/preprocessed/gcc/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/gcc/set.hpp \ + boost/mpl/aux_/preprocessed/gcc/set_c.hpp \ + boost/mpl/aux_/preprocessed/gcc/shift_left.hpp \ + boost/mpl/aux_/preprocessed/gcc/shift_right.hpp \ + boost/mpl/aux_/preprocessed/gcc/template_arity.hpp \ + boost/mpl/aux_/preprocessed/gcc/times.hpp \ + boost/mpl/aux_/preprocessed/gcc/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/gcc/vector.hpp \ + boost/mpl/aux_/preprocessed/gcc/vector_c.hpp \ + boost/mpl/aux_/preprocessed/msvc60/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/msvc60/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/msvc60/and.hpp \ + boost/mpl/aux_/preprocessed/msvc60/apply.hpp \ + boost/mpl/aux_/preprocessed/msvc60/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc60/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/msvc60/arg.hpp \ + boost/mpl/aux_/preprocessed/msvc60/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bind.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bitand.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bitor.hpp \ + boost/mpl/aux_/preprocessed/msvc60/bitxor.hpp \ + boost/mpl/aux_/preprocessed/msvc60/deque.hpp \ + boost/mpl/aux_/preprocessed/msvc60/divides.hpp \ + boost/mpl/aux_/preprocessed/msvc60/equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc60/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/msvc60/greater.hpp \ + boost/mpl/aux_/preprocessed/msvc60/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc60/inherit.hpp \ + boost/mpl/aux_/preprocessed/msvc60/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/msvc60/less.hpp \ + boost/mpl/aux_/preprocessed/msvc60/less_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc60/list.hpp \ + boost/mpl/aux_/preprocessed/msvc60/list_c.hpp \ + boost/mpl/aux_/preprocessed/msvc60/map.hpp \ + boost/mpl/aux_/preprocessed/msvc60/minus.hpp \ + boost/mpl/aux_/preprocessed/msvc60/modulus.hpp \ + boost/mpl/aux_/preprocessed/msvc60/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc60/or.hpp \ + boost/mpl/aux_/preprocessed/msvc60/placeholders.hpp \ + boost/mpl/aux_/preprocessed/msvc60/plus.hpp \ + boost/mpl/aux_/preprocessed/msvc60/quote.hpp \ + boost/mpl/aux_/preprocessed/msvc60/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc60/set.hpp \ + boost/mpl/aux_/preprocessed/msvc60/set_c.hpp \ + boost/mpl/aux_/preprocessed/msvc60/shift_left.hpp \ + boost/mpl/aux_/preprocessed/msvc60/shift_right.hpp \ + boost/mpl/aux_/preprocessed/msvc60/template_arity.hpp \ + boost/mpl/aux_/preprocessed/msvc60/times.hpp \ + boost/mpl/aux_/preprocessed/msvc60/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/msvc60/vector.hpp \ + boost/mpl/aux_/preprocessed/msvc60/vector_c.hpp \ + boost/mpl/aux_/preprocessed/msvc70/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/msvc70/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/msvc70/and.hpp \ + boost/mpl/aux_/preprocessed/msvc70/apply.hpp \ + boost/mpl/aux_/preprocessed/msvc70/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc70/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/msvc70/arg.hpp \ + boost/mpl/aux_/preprocessed/msvc70/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bind.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bitand.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bitor.hpp \ + boost/mpl/aux_/preprocessed/msvc70/bitxor.hpp \ + boost/mpl/aux_/preprocessed/msvc70/deque.hpp \ + boost/mpl/aux_/preprocessed/msvc70/divides.hpp \ + boost/mpl/aux_/preprocessed/msvc70/equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc70/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/msvc70/greater.hpp \ + boost/mpl/aux_/preprocessed/msvc70/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc70/inherit.hpp \ + boost/mpl/aux_/preprocessed/msvc70/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/msvc70/less.hpp \ + boost/mpl/aux_/preprocessed/msvc70/less_equal.hpp \ + boost/mpl/aux_/preprocessed/msvc70/list.hpp \ + boost/mpl/aux_/preprocessed/msvc70/list_c.hpp \ + boost/mpl/aux_/preprocessed/msvc70/map.hpp \ + boost/mpl/aux_/preprocessed/msvc70/minus.hpp \ + boost/mpl/aux_/preprocessed/msvc70/modulus.hpp \ + boost/mpl/aux_/preprocessed/msvc70/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/msvc70/or.hpp \ + boost/mpl/aux_/preprocessed/msvc70/placeholders.hpp \ + boost/mpl/aux_/preprocessed/msvc70/plus.hpp \ + boost/mpl/aux_/preprocessed/msvc70/quote.hpp \ + boost/mpl/aux_/preprocessed/msvc70/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/msvc70/set.hpp \ + boost/mpl/aux_/preprocessed/msvc70/set_c.hpp \ + boost/mpl/aux_/preprocessed/msvc70/shift_left.hpp \ + boost/mpl/aux_/preprocessed/msvc70/shift_right.hpp \ + boost/mpl/aux_/preprocessed/msvc70/template_arity.hpp \ + boost/mpl/aux_/preprocessed/msvc70/times.hpp \ + boost/mpl/aux_/preprocessed/msvc70/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/msvc70/vector.hpp \ + boost/mpl/aux_/preprocessed/msvc70/vector_c.hpp \ + boost/mpl/aux_/preprocessed/mwcw/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/mwcw/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/mwcw/and.hpp \ + boost/mpl/aux_/preprocessed/mwcw/apply.hpp \ + boost/mpl/aux_/preprocessed/mwcw/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/mwcw/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/mwcw/arg.hpp \ + boost/mpl/aux_/preprocessed/mwcw/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bind.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bitand.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bitor.hpp \ + boost/mpl/aux_/preprocessed/mwcw/bitxor.hpp \ + boost/mpl/aux_/preprocessed/mwcw/deque.hpp \ + boost/mpl/aux_/preprocessed/mwcw/divides.hpp \ + boost/mpl/aux_/preprocessed/mwcw/equal_to.hpp \ + boost/mpl/aux_/preprocessed/mwcw/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/mwcw/greater.hpp \ + boost/mpl/aux_/preprocessed/mwcw/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/mwcw/inherit.hpp \ + boost/mpl/aux_/preprocessed/mwcw/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/mwcw/less.hpp \ + boost/mpl/aux_/preprocessed/mwcw/less_equal.hpp \ + boost/mpl/aux_/preprocessed/mwcw/list.hpp \ + boost/mpl/aux_/preprocessed/mwcw/list_c.hpp \ + boost/mpl/aux_/preprocessed/mwcw/map.hpp \ + boost/mpl/aux_/preprocessed/mwcw/minus.hpp \ + boost/mpl/aux_/preprocessed/mwcw/modulus.hpp \ + boost/mpl/aux_/preprocessed/mwcw/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/mwcw/or.hpp \ + boost/mpl/aux_/preprocessed/mwcw/placeholders.hpp \ + boost/mpl/aux_/preprocessed/mwcw/plus.hpp \ + boost/mpl/aux_/preprocessed/mwcw/quote.hpp \ + boost/mpl/aux_/preprocessed/mwcw/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/mwcw/set.hpp \ + boost/mpl/aux_/preprocessed/mwcw/set_c.hpp \ + boost/mpl/aux_/preprocessed/mwcw/shift_left.hpp \ + boost/mpl/aux_/preprocessed/mwcw/shift_right.hpp \ + boost/mpl/aux_/preprocessed/mwcw/template_arity.hpp \ + boost/mpl/aux_/preprocessed/mwcw/times.hpp \ + boost/mpl/aux_/preprocessed/mwcw/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/mwcw/vector.hpp \ + boost/mpl/aux_/preprocessed/mwcw/vector_c.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/and.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/apply.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/arg.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bind.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bitand.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bitor.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/bitxor.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/deque.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/divides.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/greater.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/inherit.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/less.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/less_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/list.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/list_c.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/map.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/minus.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/modulus.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/or.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/placeholders.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/plus.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/quote.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/set.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/set_c.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/shift_left.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/shift_right.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/template_arity.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/times.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/vector.hpp \ + boost/mpl/aux_/preprocessed/no_ctps/vector_c.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/and.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/apply.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/arg.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bind.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bitand.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bitor.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/bitxor.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/deque.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/divides.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/greater.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/inherit.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/less.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/less_equal.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/list.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/list_c.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/map.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/minus.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/modulus.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/or.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/placeholders.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/plus.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/quote.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/set.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/set_c.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/shift_left.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/shift_right.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/template_arity.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/times.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/vector.hpp \ + boost/mpl/aux_/preprocessed/no_ttp/vector_c.hpp \ + boost/mpl/aux_/preprocessed/plain/advance_backward.hpp \ + boost/mpl/aux_/preprocessed/plain/advance_forward.hpp \ + boost/mpl/aux_/preprocessed/plain/and.hpp \ + boost/mpl/aux_/preprocessed/plain/apply.hpp \ + boost/mpl/aux_/preprocessed/plain/apply_fwd.hpp \ + boost/mpl/aux_/preprocessed/plain/apply_wrap.hpp \ + boost/mpl/aux_/preprocessed/plain/arg.hpp \ + boost/mpl/aux_/preprocessed/plain/basic_bind.hpp \ + boost/mpl/aux_/preprocessed/plain/bind.hpp \ + boost/mpl/aux_/preprocessed/plain/bind_fwd.hpp \ + boost/mpl/aux_/preprocessed/plain/bitand.hpp \ + boost/mpl/aux_/preprocessed/plain/bitor.hpp \ + boost/mpl/aux_/preprocessed/plain/bitxor.hpp \ + boost/mpl/aux_/preprocessed/plain/deque.hpp \ + boost/mpl/aux_/preprocessed/plain/divides.hpp \ + boost/mpl/aux_/preprocessed/plain/equal_to.hpp \ + boost/mpl/aux_/preprocessed/plain/fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/full_lambda.hpp \ + boost/mpl/aux_/preprocessed/plain/greater.hpp \ + boost/mpl/aux_/preprocessed/plain/greater_equal.hpp \ + boost/mpl/aux_/preprocessed/plain/inherit.hpp \ + boost/mpl/aux_/preprocessed/plain/iter_fold_if_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/lambda_no_ctps.hpp \ + boost/mpl/aux_/preprocessed/plain/less.hpp \ + boost/mpl/aux_/preprocessed/plain/less_equal.hpp \ + boost/mpl/aux_/preprocessed/plain/list.hpp \ + boost/mpl/aux_/preprocessed/plain/list_c.hpp \ + boost/mpl/aux_/preprocessed/plain/map.hpp \ + boost/mpl/aux_/preprocessed/plain/minus.hpp \ + boost/mpl/aux_/preprocessed/plain/modulus.hpp \ + boost/mpl/aux_/preprocessed/plain/not_equal_to.hpp \ + boost/mpl/aux_/preprocessed/plain/or.hpp \ + boost/mpl/aux_/preprocessed/plain/placeholders.hpp \ + boost/mpl/aux_/preprocessed/plain/plus.hpp \ + boost/mpl/aux_/preprocessed/plain/quote.hpp \ + boost/mpl/aux_/preprocessed/plain/reverse_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/preprocessed/plain/set.hpp \ + boost/mpl/aux_/preprocessed/plain/set_c.hpp \ + boost/mpl/aux_/preprocessed/plain/shift_left.hpp \ + boost/mpl/aux_/preprocessed/plain/shift_right.hpp \ + boost/mpl/aux_/preprocessed/plain/template_arity.hpp \ + boost/mpl/aux_/preprocessed/plain/times.hpp \ + boost/mpl/aux_/preprocessed/plain/unpack_args.hpp \ + boost/mpl/aux_/preprocessed/plain/vector.hpp \ + boost/mpl/aux_/preprocessed/plain/vector_c.hpp \ + boost/mpl/aux_/preprocessor/add.hpp \ + boost/mpl/aux_/preprocessor/def_params_tail.hpp \ + boost/mpl/aux_/preprocessor/default_params.hpp \ + boost/mpl/aux_/preprocessor/enum.hpp \ + boost/mpl/aux_/preprocessor/ext_params.hpp \ + boost/mpl/aux_/preprocessor/filter_params.hpp \ + boost/mpl/aux_/preprocessor/is_seq.hpp \ + boost/mpl/aux_/preprocessor/params.hpp \ + boost/mpl/aux_/preprocessor/partial_spec_params.hpp \ + boost/mpl/aux_/preprocessor/range.hpp \ + boost/mpl/aux_/preprocessor/repeat.hpp \ + boost/mpl/aux_/preprocessor/sub.hpp \ + boost/mpl/aux_/preprocessor/token_equal.hpp \ + boost/mpl/aux_/preprocessor/tuple.hpp \ + boost/mpl/aux_/ptr_to_ref.hpp \ + boost/mpl/aux_/push_back_impl.hpp \ + boost/mpl/aux_/push_front_impl.hpp \ + boost/mpl/aux_/range_c/O1_size.hpp \ + boost/mpl/aux_/range_c/back.hpp \ + boost/mpl/aux_/range_c/empty.hpp \ + boost/mpl/aux_/range_c/front.hpp \ + boost/mpl/aux_/range_c/iterator.hpp \ + boost/mpl/aux_/range_c/size.hpp \ + boost/mpl/aux_/range_c/tag.hpp \ + boost/mpl/aux_/reverse_fold_impl.hpp \ + boost/mpl/aux_/reverse_fold_impl_body.hpp \ + boost/mpl/aux_/reverse_iter_fold_impl.hpp \ + boost/mpl/aux_/sequence_wrapper.hpp \ + boost/mpl/aux_/shift_op.hpp \ + boost/mpl/aux_/single_element_iter.hpp \ + boost/mpl/aux_/size_impl.hpp \ + boost/mpl/aux_/sort_impl.hpp \ + boost/mpl/aux_/static_cast.hpp \ + boost/mpl/aux_/template_arity.hpp \ + boost/mpl/aux_/template_arity_fwd.hpp \ + boost/mpl/aux_/test.hpp \ + boost/mpl/aux_/test/assert.hpp \ + boost/mpl/aux_/test/data.hpp \ + boost/mpl/aux_/test/test_case.hpp \ + boost/mpl/aux_/traits_lambda_spec.hpp \ + boost/mpl/aux_/transform_iter.hpp \ + boost/mpl/aux_/type_wrapper.hpp \ + boost/mpl/aux_/unwrap.hpp \ + boost/mpl/aux_/value_wknd.hpp \ + boost/mpl/aux_/yes_no.hpp \ + boost/mpl/back.hpp \ + boost/mpl/back_fwd.hpp \ + boost/mpl/back_inserter.hpp \ + boost/mpl/base.hpp \ + boost/mpl/begin.hpp \ + boost/mpl/begin_end.hpp \ + boost/mpl/begin_end_fwd.hpp \ + boost/mpl/bind.hpp \ + boost/mpl/bind_fwd.hpp \ + boost/mpl/bitand.hpp \ + boost/mpl/bitor.hpp \ + boost/mpl/bitwise.hpp \ + boost/mpl/bitxor.hpp \ + boost/mpl/bool.hpp \ + boost/mpl/bool_fwd.hpp \ + boost/mpl/char.hpp \ + boost/mpl/char_fwd.hpp \ + boost/mpl/clear.hpp \ + boost/mpl/clear_fwd.hpp \ + boost/mpl/comparison.hpp \ + boost/mpl/contains.hpp \ + boost/mpl/contains_fwd.hpp \ + boost/mpl/copy.hpp \ + boost/mpl/copy_if.hpp \ + boost/mpl/count.hpp \ + boost/mpl/count_fwd.hpp \ + boost/mpl/count_if.hpp \ + boost/mpl/deque.hpp \ + boost/mpl/deref.hpp \ + boost/mpl/distance.hpp \ + boost/mpl/distance_fwd.hpp \ + boost/mpl/divides.hpp \ + boost/mpl/empty.hpp \ + boost/mpl/empty_base.hpp \ + boost/mpl/empty_fwd.hpp \ + boost/mpl/empty_sequence.hpp \ + boost/mpl/end.hpp \ + boost/mpl/equal.hpp \ + boost/mpl/equal_to.hpp \ + boost/mpl/erase.hpp \ + boost/mpl/erase_fwd.hpp \ + boost/mpl/erase_key.hpp \ + boost/mpl/erase_key_fwd.hpp \ + boost/mpl/eval_if.hpp \ + boost/mpl/filter_view.hpp \ + boost/mpl/find.hpp \ + boost/mpl/find_if.hpp \ + boost/mpl/fold.hpp \ + boost/mpl/for_each.hpp \ + boost/mpl/front.hpp \ + boost/mpl/front_fwd.hpp \ + boost/mpl/front_inserter.hpp \ + boost/mpl/greater.hpp \ + boost/mpl/greater_equal.hpp \ + boost/mpl/has_key.hpp \ + boost/mpl/has_key_fwd.hpp \ + boost/mpl/has_xxx.hpp \ + boost/mpl/identity.hpp \ + boost/mpl/if.hpp \ + boost/mpl/index_if.hpp \ + boost/mpl/index_of.hpp \ + boost/mpl/inherit.hpp \ + boost/mpl/inherit_linearly.hpp \ + boost/mpl/insert.hpp \ + boost/mpl/insert_fwd.hpp \ + boost/mpl/insert_range.hpp \ + boost/mpl/insert_range_fwd.hpp \ + boost/mpl/inserter.hpp \ + boost/mpl/int.hpp \ + boost/mpl/int_fwd.hpp \ + boost/mpl/integral_c.hpp \ + boost/mpl/integral_c_fwd.hpp \ + boost/mpl/integral_c_tag.hpp \ + boost/mpl/is_placeholder.hpp \ + boost/mpl/is_sequence.hpp \ + boost/mpl/iter_fold.hpp \ + boost/mpl/iter_fold_if.hpp \ + boost/mpl/iterator_category.hpp \ + boost/mpl/iterator_range.hpp \ + boost/mpl/iterator_tags.hpp \ + boost/mpl/joint_view.hpp \ + boost/mpl/key_type.hpp \ + boost/mpl/key_type_fwd.hpp \ + boost/mpl/lambda.hpp \ + boost/mpl/lambda_fwd.hpp \ + boost/mpl/less.hpp \ + boost/mpl/less_equal.hpp \ + boost/mpl/limits/arity.hpp \ + boost/mpl/limits/list.hpp \ + boost/mpl/limits/map.hpp \ + boost/mpl/limits/set.hpp \ + boost/mpl/limits/string.hpp \ + boost/mpl/limits/unrolling.hpp \ + boost/mpl/limits/vector.hpp \ + boost/mpl/list.hpp \ + boost/mpl/list/aux_/O1_size.hpp \ + boost/mpl/list/aux_/begin_end.hpp \ + boost/mpl/list/aux_/clear.hpp \ + boost/mpl/list/aux_/empty.hpp \ + boost/mpl/list/aux_/front.hpp \ + boost/mpl/list/aux_/include_preprocessed.hpp \ + boost/mpl/list/aux_/item.hpp \ + boost/mpl/list/aux_/iterator.hpp \ + boost/mpl/list/aux_/numbered.hpp \ + boost/mpl/list/aux_/numbered_c.hpp \ + boost/mpl/list/aux_/pop_front.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list10.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list10_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list20.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list20_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list30.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list30_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list40.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list40_c.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list50.hpp \ + boost/mpl/list/aux_/preprocessed/plain/list50_c.hpp \ + boost/mpl/list/aux_/push_back.hpp \ + boost/mpl/list/aux_/push_front.hpp \ + boost/mpl/list/aux_/size.hpp \ + boost/mpl/list/aux_/tag.hpp \ + boost/mpl/list/list0.hpp \ + boost/mpl/list/list0_c.hpp \ + boost/mpl/list/list10.hpp \ + boost/mpl/list/list10_c.hpp \ + boost/mpl/list/list20.hpp \ + boost/mpl/list/list20_c.hpp \ + boost/mpl/list/list30.hpp \ + boost/mpl/list/list30_c.hpp \ + boost/mpl/list/list40.hpp \ + boost/mpl/list/list40_c.hpp \ + boost/mpl/list/list50.hpp \ + boost/mpl/list/list50_c.hpp \ + boost/mpl/list_c.hpp \ + boost/mpl/logical.hpp \ + boost/mpl/long.hpp \ + boost/mpl/long_fwd.hpp \ + boost/mpl/lower_bound.hpp \ + boost/mpl/map.hpp \ + boost/mpl/map/aux_/at_impl.hpp \ + boost/mpl/map/aux_/begin_end_impl.hpp \ + boost/mpl/map/aux_/clear_impl.hpp \ + boost/mpl/map/aux_/contains_impl.hpp \ + boost/mpl/map/aux_/empty_impl.hpp \ + boost/mpl/map/aux_/erase_impl.hpp \ + boost/mpl/map/aux_/erase_key_impl.hpp \ + boost/mpl/map/aux_/has_key_impl.hpp \ + boost/mpl/map/aux_/include_preprocessed.hpp \ + boost/mpl/map/aux_/insert_impl.hpp \ + boost/mpl/map/aux_/item.hpp \ + boost/mpl/map/aux_/iterator.hpp \ + boost/mpl/map/aux_/key_type_impl.hpp \ + boost/mpl/map/aux_/map0.hpp \ + boost/mpl/map/aux_/numbered.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map10.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map20.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map30.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map40.hpp \ + boost/mpl/map/aux_/preprocessed/no_ctps/map50.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map10.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map20.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map30.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map40.hpp \ + boost/mpl/map/aux_/preprocessed/plain/map50.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map10.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map20.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map30.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map40.hpp \ + boost/mpl/map/aux_/preprocessed/typeof_based/map50.hpp \ + boost/mpl/map/aux_/size_impl.hpp \ + boost/mpl/map/aux_/tag.hpp \ + boost/mpl/map/aux_/value_type_impl.hpp \ + boost/mpl/map/map0.hpp \ + boost/mpl/map/map10.hpp \ + boost/mpl/map/map20.hpp \ + boost/mpl/map/map30.hpp \ + boost/mpl/map/map40.hpp \ + boost/mpl/map/map50.hpp \ + boost/mpl/math/fixed_c.hpp \ + boost/mpl/math/is_even.hpp \ + boost/mpl/math/rational_c.hpp \ + boost/mpl/max.hpp \ + boost/mpl/max_element.hpp \ + boost/mpl/min.hpp \ + boost/mpl/min_element.hpp \ + boost/mpl/min_max.hpp \ + boost/mpl/minus.hpp \ + boost/mpl/modulus.hpp \ + boost/mpl/multiplies.hpp \ + boost/mpl/multiset/aux_/count_impl.hpp \ + boost/mpl/multiset/aux_/insert_impl.hpp \ + boost/mpl/multiset/aux_/item.hpp \ + boost/mpl/multiset/aux_/multiset0.hpp \ + boost/mpl/multiset/aux_/tag.hpp \ + boost/mpl/multiset/multiset0.hpp \ + boost/mpl/negate.hpp \ + boost/mpl/next.hpp \ + boost/mpl/next_prior.hpp \ + boost/mpl/not.hpp \ + boost/mpl/not_equal_to.hpp \ + boost/mpl/numeric_cast.hpp \ + boost/mpl/or.hpp \ + boost/mpl/order.hpp \ + boost/mpl/order_fwd.hpp \ + boost/mpl/pair.hpp \ + boost/mpl/pair_view.hpp \ + boost/mpl/partition.hpp \ + boost/mpl/placeholders.hpp \ + boost/mpl/plus.hpp \ + boost/mpl/pop_back.hpp \ + boost/mpl/pop_back_fwd.hpp \ + boost/mpl/pop_front.hpp \ + boost/mpl/pop_front_fwd.hpp \ + boost/mpl/print.hpp \ + boost/mpl/prior.hpp \ + boost/mpl/protect.hpp \ + boost/mpl/push_back.hpp \ + boost/mpl/push_back_fwd.hpp \ + boost/mpl/push_front.hpp \ + boost/mpl/push_front_fwd.hpp \ + boost/mpl/quote.hpp \ + boost/mpl/range_c.hpp \ + boost/mpl/remove.hpp \ + boost/mpl/remove_if.hpp \ + boost/mpl/replace.hpp \ + boost/mpl/replace_if.hpp \ + boost/mpl/reverse.hpp \ + boost/mpl/reverse_fold.hpp \ + boost/mpl/reverse_iter_fold.hpp \ + boost/mpl/same_as.hpp \ + boost/mpl/sequence_tag.hpp \ + boost/mpl/sequence_tag_fwd.hpp \ + boost/mpl/set.hpp \ + boost/mpl/set/aux_/at_impl.hpp \ + boost/mpl/set/aux_/begin_end_impl.hpp \ + boost/mpl/set/aux_/clear_impl.hpp \ + boost/mpl/set/aux_/empty_impl.hpp \ + boost/mpl/set/aux_/erase_impl.hpp \ + boost/mpl/set/aux_/erase_key_impl.hpp \ + boost/mpl/set/aux_/has_key_impl.hpp \ + boost/mpl/set/aux_/include_preprocessed.hpp \ + boost/mpl/set/aux_/insert_impl.hpp \ + boost/mpl/set/aux_/item.hpp \ + boost/mpl/set/aux_/iterator.hpp \ + boost/mpl/set/aux_/key_type_impl.hpp \ + boost/mpl/set/aux_/numbered.hpp \ + boost/mpl/set/aux_/numbered_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set10.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set10_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set20.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set20_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set30.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set30_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set40.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set40_c.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set50.hpp \ + boost/mpl/set/aux_/preprocessed/plain/set50_c.hpp \ + boost/mpl/set/aux_/set0.hpp \ + boost/mpl/set/aux_/size_impl.hpp \ + boost/mpl/set/aux_/tag.hpp \ + boost/mpl/set/aux_/value_type_impl.hpp \ + boost/mpl/set/set0.hpp \ + boost/mpl/set/set0_c.hpp \ + boost/mpl/set/set10.hpp \ + boost/mpl/set/set10_c.hpp \ + boost/mpl/set/set20.hpp \ + boost/mpl/set/set20_c.hpp \ + boost/mpl/set/set30.hpp \ + boost/mpl/set/set30_c.hpp \ + boost/mpl/set/set40.hpp \ + boost/mpl/set/set40_c.hpp \ + boost/mpl/set/set50.hpp \ + boost/mpl/set/set50_c.hpp \ + boost/mpl/set_c.hpp \ + boost/mpl/shift_left.hpp \ + boost/mpl/shift_right.hpp \ + boost/mpl/single_view.hpp \ + boost/mpl/size.hpp \ + boost/mpl/size_fwd.hpp \ + boost/mpl/size_t.hpp \ + boost/mpl/size_t_fwd.hpp \ + boost/mpl/sizeof.hpp \ + boost/mpl/sort.hpp \ + boost/mpl/stable_partition.hpp \ + boost/mpl/string.hpp \ + boost/mpl/switch.hpp \ + boost/mpl/tag.hpp \ + boost/mpl/times.hpp \ + boost/mpl/transform.hpp \ + boost/mpl/transform_view.hpp \ + boost/mpl/unique.hpp \ + boost/mpl/unpack_args.hpp \ + boost/mpl/upper_bound.hpp \ + boost/mpl/value_type.hpp \ + boost/mpl/value_type_fwd.hpp \ + boost/mpl/vector.hpp \ + boost/mpl/vector/aux_/O1_size.hpp \ + boost/mpl/vector/aux_/at.hpp \ + boost/mpl/vector/aux_/back.hpp \ + boost/mpl/vector/aux_/begin_end.hpp \ + boost/mpl/vector/aux_/clear.hpp \ + boost/mpl/vector/aux_/empty.hpp \ + boost/mpl/vector/aux_/front.hpp \ + boost/mpl/vector/aux_/include_preprocessed.hpp \ + boost/mpl/vector/aux_/item.hpp \ + boost/mpl/vector/aux_/iterator.hpp \ + boost/mpl/vector/aux_/numbered.hpp \ + boost/mpl/vector/aux_/numbered_c.hpp \ + boost/mpl/vector/aux_/pop_back.hpp \ + boost/mpl/vector/aux_/pop_front.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector10.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector10_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector20.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector20_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector30.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector30_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector40.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector40_c.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector50.hpp \ + boost/mpl/vector/aux_/preprocessed/no_ctps/vector50_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector10.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector10_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector20.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector20_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector30.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector30_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector40.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector40_c.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector50.hpp \ + boost/mpl/vector/aux_/preprocessed/plain/vector50_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector10.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector10_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector20.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector20_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector30.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector30_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector40.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector40_c.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector50.hpp \ + boost/mpl/vector/aux_/preprocessed/typeof_based/vector50_c.hpp \ + boost/mpl/vector/aux_/push_back.hpp \ + boost/mpl/vector/aux_/push_front.hpp \ + boost/mpl/vector/aux_/size.hpp \ + boost/mpl/vector/aux_/tag.hpp \ + boost/mpl/vector/aux_/vector0.hpp \ + boost/mpl/vector/vector0.hpp \ + boost/mpl/vector/vector0_c.hpp \ + boost/mpl/vector/vector10.hpp \ + boost/mpl/vector/vector10_c.hpp \ + boost/mpl/vector/vector20.hpp \ + boost/mpl/vector/vector20_c.hpp \ + boost/mpl/vector/vector30.hpp \ + boost/mpl/vector/vector30_c.hpp \ + boost/mpl/vector/vector40.hpp \ + boost/mpl/vector/vector40_c.hpp \ + boost/mpl/vector/vector50.hpp \ + boost/mpl/vector/vector50_c.hpp \ + boost/mpl/vector_c.hpp \ + boost/mpl/void.hpp \ + boost/mpl/void_fwd.hpp \ + boost/mpl/zip_view.hpp \ + boost/multi_array.hpp \ + boost/multi_index_container.hpp \ + boost/multi_index_container_fwd.hpp \ + boost/next_prior.hpp \ + boost/non_type.hpp \ + boost/noncopyable.hpp \ + boost/nondet_random.hpp \ + boost/none.hpp \ + boost/none_t.hpp \ + boost/operators.hpp \ + boost/optional.hpp \ + boost/optional/optional.hpp \ + boost/optional/optional_fwd.hpp \ + boost/optional/optional_io.hpp \ + boost/parameter.hpp \ + boost/pointee.hpp \ + boost/pointer_cast.hpp \ + boost/pointer_to_other.hpp \ + boost/preprocessor.hpp \ + boost/preprocessor/arithmetic.hpp \ + boost/preprocessor/arithmetic/add.hpp \ + boost/preprocessor/arithmetic/dec.hpp \ + boost/preprocessor/arithmetic/detail/div_base.hpp \ + boost/preprocessor/arithmetic/div.hpp \ + boost/preprocessor/arithmetic/inc.hpp \ + boost/preprocessor/arithmetic/mod.hpp \ + boost/preprocessor/arithmetic/mul.hpp \ + boost/preprocessor/arithmetic/sub.hpp \ + boost/preprocessor/array.hpp \ + boost/preprocessor/array/data.hpp \ + boost/preprocessor/array/elem.hpp \ + boost/preprocessor/array/insert.hpp \ + boost/preprocessor/array/pop_back.hpp \ + boost/preprocessor/array/pop_front.hpp \ + boost/preprocessor/array/push_back.hpp \ + boost/preprocessor/array/push_front.hpp \ + boost/preprocessor/array/remove.hpp \ + boost/preprocessor/array/replace.hpp \ + boost/preprocessor/array/reverse.hpp \ + boost/preprocessor/array/size.hpp \ + boost/preprocessor/assert_msg.hpp \ + boost/preprocessor/cat.hpp \ + boost/preprocessor/comma.hpp \ + boost/preprocessor/comma_if.hpp \ + boost/preprocessor/comparison.hpp \ + boost/preprocessor/comparison/equal.hpp \ + boost/preprocessor/comparison/greater.hpp \ + boost/preprocessor/comparison/greater_equal.hpp \ + boost/preprocessor/comparison/less.hpp \ + boost/preprocessor/comparison/less_equal.hpp \ + boost/preprocessor/comparison/not_equal.hpp \ + boost/preprocessor/config/config.hpp \ + boost/preprocessor/config/limits.hpp \ + boost/preprocessor/control.hpp \ + boost/preprocessor/control/deduce_d.hpp \ + boost/preprocessor/control/detail/dmc/while.hpp \ + boost/preprocessor/control/detail/edg/while.hpp \ + boost/preprocessor/control/detail/msvc/while.hpp \ + boost/preprocessor/control/detail/while.hpp \ + boost/preprocessor/control/expr_if.hpp \ + boost/preprocessor/control/expr_iif.hpp \ + boost/preprocessor/control/if.hpp \ + boost/preprocessor/control/iif.hpp \ + boost/preprocessor/control/while.hpp \ + boost/preprocessor/debug.hpp \ + boost/preprocessor/debug/assert.hpp \ + boost/preprocessor/debug/error.hpp \ + boost/preprocessor/debug/line.hpp \ + boost/preprocessor/dec.hpp \ + boost/preprocessor/detail/auto_rec.hpp \ + boost/preprocessor/detail/check.hpp \ + boost/preprocessor/detail/dmc/auto_rec.hpp \ + boost/preprocessor/detail/is_binary.hpp \ + boost/preprocessor/detail/is_nullary.hpp \ + boost/preprocessor/detail/is_unary.hpp \ + boost/preprocessor/detail/null.hpp \ + boost/preprocessor/detail/split.hpp \ + boost/preprocessor/empty.hpp \ + boost/preprocessor/enum.hpp \ + boost/preprocessor/enum_params.hpp \ + boost/preprocessor/enum_params_with_a_default.hpp \ + boost/preprocessor/enum_params_with_defaults.hpp \ + boost/preprocessor/enum_shifted.hpp \ + boost/preprocessor/enum_shifted_params.hpp \ + boost/preprocessor/expand.hpp \ + boost/preprocessor/expr_if.hpp \ + boost/preprocessor/facilities.hpp \ + boost/preprocessor/facilities/apply.hpp \ + boost/preprocessor/facilities/empty.hpp \ + boost/preprocessor/facilities/expand.hpp \ + boost/preprocessor/facilities/identity.hpp \ + boost/preprocessor/facilities/intercept.hpp \ + boost/preprocessor/facilities/is_1.hpp \ + boost/preprocessor/facilities/is_empty.hpp \ + boost/preprocessor/facilities/is_empty_or_1.hpp \ + boost/preprocessor/for.hpp \ + boost/preprocessor/identity.hpp \ + boost/preprocessor/if.hpp \ + boost/preprocessor/inc.hpp \ + boost/preprocessor/iterate.hpp \ + boost/preprocessor/iteration.hpp \ + boost/preprocessor/iteration/detail/bounds/lower1.hpp \ + boost/preprocessor/iteration/detail/bounds/lower2.hpp \ + boost/preprocessor/iteration/detail/bounds/lower3.hpp \ + boost/preprocessor/iteration/detail/bounds/lower4.hpp \ + boost/preprocessor/iteration/detail/bounds/lower5.hpp \ + boost/preprocessor/iteration/detail/bounds/upper1.hpp \ + boost/preprocessor/iteration/detail/bounds/upper2.hpp \ + boost/preprocessor/iteration/detail/bounds/upper3.hpp \ + boost/preprocessor/iteration/detail/bounds/upper4.hpp \ + boost/preprocessor/iteration/detail/bounds/upper5.hpp \ + boost/preprocessor/iteration/detail/finish.hpp \ + boost/preprocessor/iteration/detail/iter/forward1.hpp \ + boost/preprocessor/iteration/detail/iter/forward2.hpp \ + boost/preprocessor/iteration/detail/iter/forward3.hpp \ + boost/preprocessor/iteration/detail/iter/forward4.hpp \ + boost/preprocessor/iteration/detail/iter/forward5.hpp \ + boost/preprocessor/iteration/detail/iter/reverse1.hpp \ + boost/preprocessor/iteration/detail/iter/reverse2.hpp \ + boost/preprocessor/iteration/detail/iter/reverse3.hpp \ + boost/preprocessor/iteration/detail/iter/reverse4.hpp \ + boost/preprocessor/iteration/detail/iter/reverse5.hpp \ + boost/preprocessor/iteration/detail/local.hpp \ + boost/preprocessor/iteration/detail/rlocal.hpp \ + boost/preprocessor/iteration/detail/self.hpp \ + boost/preprocessor/iteration/detail/start.hpp \ + boost/preprocessor/iteration/iterate.hpp \ + boost/preprocessor/iteration/local.hpp \ + boost/preprocessor/iteration/self.hpp \ + boost/preprocessor/library.hpp \ + boost/preprocessor/limits.hpp \ + boost/preprocessor/list.hpp \ + boost/preprocessor/list/adt.hpp \ + boost/preprocessor/list/append.hpp \ + boost/preprocessor/list/at.hpp \ + boost/preprocessor/list/cat.hpp \ + boost/preprocessor/list/detail/dmc/fold_left.hpp \ + boost/preprocessor/list/detail/edg/fold_left.hpp \ + boost/preprocessor/list/detail/edg/fold_right.hpp \ + boost/preprocessor/list/detail/fold_left.hpp \ + boost/preprocessor/list/detail/fold_right.hpp \ + boost/preprocessor/list/enum.hpp \ + boost/preprocessor/list/filter.hpp \ + boost/preprocessor/list/first_n.hpp \ + boost/preprocessor/list/fold_left.hpp \ + boost/preprocessor/list/fold_right.hpp \ + boost/preprocessor/list/for_each.hpp \ + boost/preprocessor/list/for_each_i.hpp \ + boost/preprocessor/list/for_each_product.hpp \ + boost/preprocessor/list/rest_n.hpp \ + boost/preprocessor/list/reverse.hpp \ + boost/preprocessor/list/size.hpp \ + boost/preprocessor/list/to_tuple.hpp \ + boost/preprocessor/list/transform.hpp \ + boost/preprocessor/logical.hpp \ + boost/preprocessor/logical/and.hpp \ + boost/preprocessor/logical/bitand.hpp \ + boost/preprocessor/logical/bitnor.hpp \ + boost/preprocessor/logical/bitor.hpp \ + boost/preprocessor/logical/bitxor.hpp \ + boost/preprocessor/logical/bool.hpp \ + boost/preprocessor/logical/compl.hpp \ + boost/preprocessor/logical/nor.hpp \ + boost/preprocessor/logical/not.hpp \ + boost/preprocessor/logical/or.hpp \ + boost/preprocessor/logical/xor.hpp \ + boost/preprocessor/max.hpp \ + boost/preprocessor/min.hpp \ + boost/preprocessor/punctuation.hpp \ + boost/preprocessor/punctuation/comma.hpp \ + boost/preprocessor/punctuation/comma_if.hpp \ + boost/preprocessor/punctuation/paren.hpp \ + boost/preprocessor/punctuation/paren_if.hpp \ + boost/preprocessor/repeat.hpp \ + boost/preprocessor/repeat_2nd.hpp \ + boost/preprocessor/repeat_3rd.hpp \ + boost/preprocessor/repeat_from_to.hpp \ + boost/preprocessor/repeat_from_to_2nd.hpp \ + boost/preprocessor/repeat_from_to_3rd.hpp \ + boost/preprocessor/repetition.hpp \ + boost/preprocessor/repetition/deduce_r.hpp \ + boost/preprocessor/repetition/deduce_z.hpp \ + boost/preprocessor/repetition/detail/dmc/for.hpp \ + boost/preprocessor/repetition/detail/edg/for.hpp \ + boost/preprocessor/repetition/detail/for.hpp \ + boost/preprocessor/repetition/detail/msvc/for.hpp \ + boost/preprocessor/repetition/enum.hpp \ + boost/preprocessor/repetition/enum_binary_params.hpp \ + boost/preprocessor/repetition/enum_params.hpp \ + boost/preprocessor/repetition/enum_params_with_a_default.hpp \ + boost/preprocessor/repetition/enum_params_with_defaults.hpp \ + boost/preprocessor/repetition/enum_shifted.hpp \ + boost/preprocessor/repetition/enum_shifted_binary_params.hpp \ + boost/preprocessor/repetition/enum_shifted_params.hpp \ + boost/preprocessor/repetition/enum_trailing.hpp \ + boost/preprocessor/repetition/enum_trailing_binary_params.hpp \ + boost/preprocessor/repetition/enum_trailing_params.hpp \ + boost/preprocessor/repetition/for.hpp \ + boost/preprocessor/repetition/repeat.hpp \ + boost/preprocessor/repetition/repeat_from_to.hpp \ + boost/preprocessor/selection.hpp \ + boost/preprocessor/selection/max.hpp \ + boost/preprocessor/selection/min.hpp \ + boost/preprocessor/seq.hpp \ + boost/preprocessor/seq/cat.hpp \ + boost/preprocessor/seq/detail/split.hpp \ + boost/preprocessor/seq/elem.hpp \ + boost/preprocessor/seq/enum.hpp \ + boost/preprocessor/seq/filter.hpp \ + boost/preprocessor/seq/first_n.hpp \ + boost/preprocessor/seq/fold_left.hpp \ + boost/preprocessor/seq/fold_right.hpp \ + boost/preprocessor/seq/for_each.hpp \ + boost/preprocessor/seq/for_each_i.hpp \ + boost/preprocessor/seq/for_each_product.hpp \ + boost/preprocessor/seq/insert.hpp \ + boost/preprocessor/seq/pop_back.hpp \ + boost/preprocessor/seq/pop_front.hpp \ + boost/preprocessor/seq/push_back.hpp \ + boost/preprocessor/seq/push_front.hpp \ + boost/preprocessor/seq/remove.hpp \ + boost/preprocessor/seq/replace.hpp \ + boost/preprocessor/seq/rest_n.hpp \ + boost/preprocessor/seq/reverse.hpp \ + boost/preprocessor/seq/seq.hpp \ + boost/preprocessor/seq/size.hpp \ + boost/preprocessor/seq/subseq.hpp \ + boost/preprocessor/seq/to_array.hpp \ + boost/preprocessor/seq/to_tuple.hpp \ + boost/preprocessor/seq/transform.hpp \ + boost/preprocessor/slot.hpp \ + boost/preprocessor/slot/counter.hpp \ + boost/preprocessor/slot/detail/counter.hpp \ + boost/preprocessor/slot/detail/def.hpp \ + boost/preprocessor/slot/detail/shared.hpp \ + boost/preprocessor/slot/detail/slot1.hpp \ + boost/preprocessor/slot/detail/slot2.hpp \ + boost/preprocessor/slot/detail/slot3.hpp \ + boost/preprocessor/slot/detail/slot4.hpp \ + boost/preprocessor/slot/detail/slot5.hpp \ + boost/preprocessor/slot/slot.hpp \ + boost/preprocessor/stringize.hpp \ + boost/preprocessor/tuple.hpp \ + boost/preprocessor/tuple/eat.hpp \ + boost/preprocessor/tuple/elem.hpp \ + boost/preprocessor/tuple/rem.hpp \ + boost/preprocessor/tuple/reverse.hpp \ + boost/preprocessor/tuple/to_list.hpp \ + boost/preprocessor/tuple/to_seq.hpp \ + boost/preprocessor/while.hpp \ + boost/preprocessor/wstringize.hpp \ + boost/program_options.hpp \ + boost/progress.hpp \ + boost/ptr_container/clone_allocator.hpp \ + boost/ptr_container/detail/associative_ptr_container.hpp \ + boost/ptr_container/detail/default_deleter.hpp \ + boost/ptr_container/detail/is_convertible.hpp \ + boost/ptr_container/detail/map_iterator.hpp \ + boost/ptr_container/detail/meta_functions.hpp \ + boost/ptr_container/detail/move.hpp \ + boost/ptr_container/detail/reversible_ptr_container.hpp \ + boost/ptr_container/detail/scoped_deleter.hpp \ + boost/ptr_container/detail/serialize_ptr_map_adapter.hpp \ + boost/ptr_container/detail/serialize_reversible_cont.hpp \ + boost/ptr_container/detail/serialize_xml_names.hpp \ + boost/ptr_container/detail/static_move_ptr.hpp \ + boost/ptr_container/detail/throw_exception.hpp \ + boost/ptr_container/detail/void_ptr_iterator.hpp \ + boost/ptr_container/exception.hpp \ + boost/ptr_container/indirect_fun.hpp \ + boost/ptr_container/nullable.hpp \ + boost/ptr_container/ptr_array.hpp \ + boost/ptr_container/ptr_circular_buffer.hpp \ + boost/ptr_container/ptr_container.hpp \ + boost/ptr_container/ptr_deque.hpp \ + boost/ptr_container/ptr_inserter.hpp \ + boost/ptr_container/ptr_list.hpp \ + boost/ptr_container/ptr_map.hpp \ + boost/ptr_container/ptr_map_adapter.hpp \ + boost/ptr_container/ptr_sequence_adapter.hpp \ + boost/ptr_container/ptr_set.hpp \ + boost/ptr_container/ptr_set_adapter.hpp \ + boost/ptr_container/ptr_unordered_map.hpp \ + boost/ptr_container/ptr_unordered_set.hpp \ + boost/ptr_container/ptr_vector.hpp \ + boost/ptr_container/serialize_ptr_array.hpp \ + boost/ptr_container/serialize_ptr_circular_buffer.hpp \ + boost/ptr_container/serialize_ptr_container.hpp \ + boost/ptr_container/serialize_ptr_deque.hpp \ + boost/ptr_container/serialize_ptr_list.hpp \ + boost/ptr_container/serialize_ptr_map.hpp \ + boost/ptr_container/serialize_ptr_set.hpp \ + boost/ptr_container/serialize_ptr_unordered_map.hpp \ + boost/ptr_container/serialize_ptr_unordered_set.hpp \ + boost/ptr_container/serialize_ptr_vector.hpp \ + boost/python.hpp \ + boost/random.hpp \ + boost/range.hpp \ + boost/range/adaptors.hpp \ + boost/range/algorithm.hpp \ + boost/range/algorithm/adjacent_find.hpp \ + boost/range/algorithm/binary_search.hpp \ + boost/range/algorithm/copy.hpp \ + boost/range/algorithm/copy_backward.hpp \ + boost/range/algorithm/count.hpp \ + boost/range/algorithm/count_if.hpp \ + boost/range/algorithm/equal.hpp \ + boost/range/algorithm/equal_range.hpp \ + boost/range/algorithm/fill.hpp \ + boost/range/algorithm/fill_n.hpp \ + boost/range/algorithm/find.hpp \ + boost/range/algorithm/find_end.hpp \ + boost/range/algorithm/find_first_of.hpp \ + boost/range/algorithm/find_if.hpp \ + boost/range/algorithm/for_each.hpp \ + boost/range/algorithm/generate.hpp \ + boost/range/algorithm/heap_algorithm.hpp \ + boost/range/algorithm/inplace_merge.hpp \ + boost/range/algorithm/lexicographical_compare.hpp \ + boost/range/algorithm/lower_bound.hpp \ + boost/range/algorithm/max_element.hpp \ + boost/range/algorithm/merge.hpp \ + boost/range/algorithm/min_element.hpp \ + boost/range/algorithm/mismatch.hpp \ + boost/range/algorithm/nth_element.hpp \ + boost/range/algorithm/partial_sort.hpp \ + boost/range/algorithm/partial_sort_copy.hpp \ + boost/range/algorithm/partition.hpp \ + boost/range/algorithm/permutation.hpp \ + boost/range/algorithm/random_shuffle.hpp \ + boost/range/algorithm/remove.hpp \ + boost/range/algorithm/remove_copy.hpp \ + boost/range/algorithm/remove_copy_if.hpp \ + boost/range/algorithm/remove_if.hpp \ + boost/range/algorithm/replace.hpp \ + boost/range/algorithm/replace_copy.hpp \ + boost/range/algorithm/replace_copy_if.hpp \ + boost/range/algorithm/replace_if.hpp \ + boost/range/algorithm/reverse.hpp \ + boost/range/algorithm/reverse_copy.hpp \ + boost/range/algorithm/rotate.hpp \ + boost/range/algorithm/rotate_copy.hpp \ + boost/range/algorithm/search.hpp \ + boost/range/algorithm/search_n.hpp \ + boost/range/algorithm/set_algorithm.hpp \ + boost/range/algorithm/sort.hpp \ + boost/range/algorithm/stable_partition.hpp \ + boost/range/algorithm/stable_sort.hpp \ + boost/range/algorithm/swap_ranges.hpp \ + boost/range/algorithm/transform.hpp \ + boost/range/algorithm/unique.hpp \ + boost/range/algorithm/unique_copy.hpp \ + boost/range/algorithm/upper_bound.hpp \ + boost/range/algorithm_ext.hpp \ + boost/range/as_array.hpp \ + boost/range/as_literal.hpp \ + boost/range/atl.hpp \ + boost/range/begin.hpp \ + boost/range/category.hpp \ + boost/range/combine.hpp \ + boost/range/concepts.hpp \ + boost/range/config.hpp \ + boost/range/const_iterator.hpp \ + boost/range/const_reverse_iterator.hpp \ + boost/range/counting_range.hpp \ + boost/range/detail/as_literal.hpp \ + boost/range/detail/begin.hpp \ + boost/range/detail/collection_traits.hpp \ + boost/range/detail/collection_traits_detail.hpp \ + boost/range/detail/common.hpp \ + boost/range/detail/const_iterator.hpp \ + boost/range/detail/demote_iterator_traversal_tag.hpp \ + boost/range/detail/detail_str.hpp \ + boost/range/detail/difference_type.hpp \ + boost/range/detail/empty.hpp \ + boost/range/detail/end.hpp \ + boost/range/detail/extract_optional_type.hpp \ + boost/range/detail/implementation_help.hpp \ + boost/range/detail/iterator.hpp \ + boost/range/detail/join_iterator.hpp \ + boost/range/detail/microsoft.hpp \ + boost/range/detail/misc_concept.hpp \ + boost/range/detail/range_return.hpp \ + boost/range/detail/remove_extent.hpp \ + boost/range/detail/sfinae.hpp \ + boost/range/detail/size.hpp \ + boost/range/detail/size_type.hpp \ + boost/range/detail/sizer.hpp \ + boost/range/detail/str_types.hpp \ + boost/range/detail/value_type.hpp \ + boost/range/detail/vc6/end.hpp \ + boost/range/detail/vc6/size.hpp \ + boost/range/difference_type.hpp \ + boost/range/distance.hpp \ + boost/range/empty.hpp \ + boost/range/end.hpp \ + boost/range/functions.hpp \ + boost/range/irange.hpp \ + boost/range/istream_range.hpp \ + boost/range/iterator.hpp \ + boost/range/iterator_range.hpp \ + boost/range/iterator_range_core.hpp \ + boost/range/iterator_range_io.hpp \ + boost/range/join.hpp \ + boost/range/metafunctions.hpp \ + boost/range/mfc.hpp \ + boost/range/mutable_iterator.hpp \ + boost/range/numeric.hpp \ + boost/range/pointer.hpp \ + boost/range/rbegin.hpp \ + boost/range/reference.hpp \ + boost/range/rend.hpp \ + boost/range/result_iterator.hpp \ + boost/range/reverse_iterator.hpp \ + boost/range/reverse_result_iterator.hpp \ + boost/range/size.hpp \ + boost/range/size_type.hpp \ + boost/range/sub_range.hpp \ + boost/range/value_type.hpp \ + boost/rational.hpp \ + boost/ref.hpp \ + boost/regex.h \ + boost/regex.hpp \ + boost/regex/concepts.hpp \ + boost/regex/config.hpp \ + boost/regex/config/borland.hpp \ + boost/regex/config/cwchar.hpp \ + boost/regex/icu.hpp \ + boost/regex/mfc.hpp \ + boost/regex/pattern_except.hpp \ + boost/regex/pending/object_cache.hpp \ + boost/regex/pending/static_mutex.hpp \ + boost/regex/pending/unicode_iterator.hpp \ + boost/regex/regex_traits.hpp \ + boost/regex/user.hpp \ + boost/regex/v4/basic_regex.hpp \ + boost/regex/v4/basic_regex_creator.hpp \ + boost/regex/v4/basic_regex_parser.hpp \ + boost/regex/v4/c_regex_traits.hpp \ + boost/regex/v4/char_regex_traits.hpp \ + boost/regex/v4/cpp_regex_traits.hpp \ + boost/regex/v4/cregex.hpp \ + boost/regex/v4/error_type.hpp \ + boost/regex/v4/fileiter.hpp \ + boost/regex/v4/instances.hpp \ + boost/regex/v4/iterator_category.hpp \ + boost/regex/v4/iterator_traits.hpp \ + boost/regex/v4/match_flags.hpp \ + boost/regex/v4/match_results.hpp \ + boost/regex/v4/mem_block_cache.hpp \ + boost/regex/v4/perl_matcher.hpp \ + boost/regex/v4/perl_matcher_common.hpp \ + boost/regex/v4/perl_matcher_non_recursive.hpp \ + boost/regex/v4/perl_matcher_recursive.hpp \ + boost/regex/v4/primary_transform.hpp \ + boost/regex/v4/protected_call.hpp \ + boost/regex/v4/regbase.hpp \ + boost/regex/v4/regex.hpp \ + boost/regex/v4/regex_format.hpp \ + boost/regex/v4/regex_fwd.hpp \ + boost/regex/v4/regex_grep.hpp \ + boost/regex/v4/regex_iterator.hpp \ + boost/regex/v4/regex_match.hpp \ + boost/regex/v4/regex_merge.hpp \ + boost/regex/v4/regex_raw_buffer.hpp \ + boost/regex/v4/regex_replace.hpp \ + boost/regex/v4/regex_search.hpp \ + boost/regex/v4/regex_split.hpp \ + boost/regex/v4/regex_token_iterator.hpp \ + boost/regex/v4/regex_traits.hpp \ + boost/regex/v4/regex_traits_defaults.hpp \ + boost/regex/v4/regex_workaround.hpp \ + boost/regex/v4/states.hpp \ + boost/regex/v4/sub_match.hpp \ + boost/regex/v4/syntax_type.hpp \ + boost/regex/v4/u32regex_iterator.hpp \ + boost/regex/v4/u32regex_token_iterator.hpp \ + boost/regex/v4/w32_regex_traits.hpp \ + boost/regex_fwd.hpp \ + boost/scope_exit.hpp \ + boost/scoped_array.hpp \ + boost/scoped_ptr.hpp \ + boost/shared_array.hpp \ + boost/shared_container_iterator.hpp \ + boost/shared_ptr.hpp \ + boost/signal.hpp \ + boost/signals.hpp \ + boost/signals2.hpp \ + boost/smart_ptr.hpp \ + boost/smart_ptr/bad_weak_ptr.hpp \ + boost/smart_ptr/detail/atomic_count.hpp \ + boost/smart_ptr/detail/atomic_count_gcc.hpp \ + boost/smart_ptr/detail/atomic_count_gcc_x86.hpp \ + boost/smart_ptr/detail/atomic_count_pthreads.hpp \ + boost/smart_ptr/detail/atomic_count_solaris.hpp \ + boost/smart_ptr/detail/atomic_count_sync.hpp \ + boost/smart_ptr/detail/atomic_count_win32.hpp \ + boost/smart_ptr/detail/lightweight_mutex.hpp \ + boost/smart_ptr/detail/lwm_nop.hpp \ + boost/smart_ptr/detail/lwm_pthreads.hpp \ + boost/smart_ptr/detail/lwm_win32_cs.hpp \ + boost/smart_ptr/detail/operator_bool.hpp \ + boost/smart_ptr/detail/quick_allocator.hpp \ + boost/smart_ptr/detail/shared_array_nmt.hpp \ + boost/smart_ptr/detail/shared_count.hpp \ + boost/smart_ptr/detail/shared_ptr_nmt.hpp \ + boost/smart_ptr/detail/sp_convertible.hpp \ + boost/smart_ptr/detail/sp_counted_base.hpp \ + boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \ + boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \ + boost/smart_ptr/detail/sp_counted_base_cw_x86.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \ + boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \ + boost/smart_ptr/detail/sp_counted_base_nt.hpp \ + boost/smart_ptr/detail/sp_counted_base_pt.hpp \ + boost/smart_ptr/detail/sp_counted_base_solaris.hpp \ + boost/smart_ptr/detail/sp_counted_base_spin.hpp \ + boost/smart_ptr/detail/sp_counted_base_sync.hpp \ + boost/smart_ptr/detail/sp_counted_base_w32.hpp \ + boost/smart_ptr/detail/sp_counted_impl.hpp \ + boost/smart_ptr/detail/sp_has_sync.hpp \ + boost/smart_ptr/detail/spinlock.hpp \ + boost/smart_ptr/detail/spinlock_gcc_arm.hpp \ + boost/smart_ptr/detail/spinlock_nt.hpp \ + boost/smart_ptr/detail/spinlock_pool.hpp \ + boost/smart_ptr/detail/spinlock_pt.hpp \ + boost/smart_ptr/detail/spinlock_sync.hpp \ + boost/smart_ptr/detail/spinlock_w32.hpp \ + boost/smart_ptr/detail/yield_k.hpp \ + boost/smart_ptr/enable_shared_from_this.hpp \ + boost/smart_ptr/enable_shared_from_this2.hpp \ + boost/smart_ptr/intrusive_ptr.hpp \ + boost/smart_ptr/make_shared.hpp \ + boost/smart_ptr/scoped_array.hpp \ + boost/smart_ptr/scoped_ptr.hpp \ + boost/smart_ptr/shared_array.hpp \ + boost/smart_ptr/shared_ptr.hpp \ + boost/smart_ptr/weak_ptr.hpp \ + boost/spirit.hpp \ + boost/static_assert.hpp \ + boost/strong_typedef.hpp \ + boost/swap.hpp \ + boost/system/api_config.hpp \ + boost/system/config.hpp \ + boost/system/cygwin_error.hpp \ + boost/system/error_code.hpp \ + boost/system/linux_error.hpp \ + boost/system/system_error.hpp \ + boost/system/windows_error.hpp \ + boost/thread.hpp \ + boost/thread/barrier.hpp \ + boost/thread/condition.hpp \ + boost/thread/condition_variable.hpp \ + boost/thread/detail/config.hpp \ + boost/thread/detail/force_cast.hpp \ + boost/thread/detail/move.hpp \ + boost/thread/detail/platform.hpp \ + boost/thread/detail/singleton.hpp \ + boost/thread/detail/thread.hpp \ + boost/thread/detail/thread_group.hpp \ + boost/thread/detail/thread_heap_alloc.hpp \ + boost/thread/detail/thread_interruption.hpp \ + boost/thread/detail/tss_hooks.hpp \ + boost/thread/exceptions.hpp \ + boost/thread/future.hpp \ + boost/thread/locks.hpp \ + boost/thread/mutex.hpp \ + boost/thread/once.hpp \ + boost/thread/pthread/condition_variable.hpp \ + boost/thread/pthread/condition_variable_fwd.hpp \ + boost/thread/pthread/mutex.hpp \ + boost/thread/pthread/once.hpp \ + boost/thread/pthread/pthread_mutex_scoped_lock.hpp \ + boost/thread/pthread/recursive_mutex.hpp \ + boost/thread/pthread/shared_mutex.hpp \ + boost/thread/pthread/thread_data.hpp \ + boost/thread/pthread/thread_heap_alloc.hpp \ + boost/thread/pthread/timespec.hpp \ + boost/thread/recursive_mutex.hpp \ + boost/thread/shared_mutex.hpp \ + boost/thread/thread.hpp \ + boost/thread/thread_time.hpp \ + boost/thread/tss.hpp \ + boost/thread/win32/basic_recursive_mutex.hpp \ + boost/thread/win32/basic_timed_mutex.hpp \ + boost/thread/win32/condition_variable.hpp \ + boost/thread/win32/interlocked_read.hpp \ + boost/thread/win32/mutex.hpp \ + boost/thread/win32/once.hpp \ + boost/thread/win32/recursive_mutex.hpp \ + boost/thread/win32/shared_mutex.hpp \ + boost/thread/win32/thread_data.hpp \ + boost/thread/win32/thread_heap_alloc.hpp \ + boost/thread/win32/thread_primitives.hpp \ + boost/thread/xtime.hpp \ + boost/throw_exception.hpp \ + boost/timer.hpp \ + boost/token_functions.hpp \ + boost/token_iterator.hpp \ + boost/tokenizer.hpp \ + boost/tuple/detail/tuple_basic.hpp \ + boost/tuple/detail/tuple_basic_no_partial_spec.hpp \ + boost/tuple/tuple.hpp \ + boost/tuple/tuple_comparison.hpp \ + boost/tuple/tuple_io.hpp \ + boost/type.hpp \ + boost/type_traits.hpp \ + boost/type_traits/add_const.hpp \ + boost/type_traits/add_cv.hpp \ + boost/type_traits/add_lvalue_reference.hpp \ + boost/type_traits/add_pointer.hpp \ + boost/type_traits/add_reference.hpp \ + boost/type_traits/add_rvalue_reference.hpp \ + boost/type_traits/add_volatile.hpp \ + boost/type_traits/aligned_storage.hpp \ + boost/type_traits/alignment_of.hpp \ + boost/type_traits/alignment_traits.hpp \ + boost/type_traits/arithmetic_traits.hpp \ + boost/type_traits/array_traits.hpp \ + boost/type_traits/broken_compiler_spec.hpp \ + boost/type_traits/common_type.hpp \ + boost/type_traits/composite_traits.hpp \ + boost/type_traits/conditional.hpp \ + boost/type_traits/config.hpp \ + boost/type_traits/conversion_traits.hpp \ + boost/type_traits/cv_traits.hpp \ + boost/type_traits/decay.hpp \ + boost/type_traits/detail/bool_trait_def.hpp \ + boost/type_traits/detail/bool_trait_undef.hpp \ + boost/type_traits/detail/common_type_imp.hpp \ + boost/type_traits/detail/cv_traits_impl.hpp \ + boost/type_traits/detail/false_result.hpp \ + boost/type_traits/detail/ice_and.hpp \ + boost/type_traits/detail/ice_eq.hpp \ + boost/type_traits/detail/ice_not.hpp \ + boost/type_traits/detail/ice_or.hpp \ + boost/type_traits/detail/is_function_ptr_helper.hpp \ + boost/type_traits/detail/is_function_ptr_tester.hpp \ + boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \ + boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \ + boost/type_traits/detail/size_t_trait_def.hpp \ + boost/type_traits/detail/size_t_trait_undef.hpp \ + boost/type_traits/detail/template_arity_spec.hpp \ + boost/type_traits/detail/type_trait_def.hpp \ + boost/type_traits/detail/type_trait_undef.hpp \ + boost/type_traits/detail/wrap.hpp \ + boost/type_traits/detail/yes_no_type.hpp \ + boost/type_traits/extent.hpp \ + boost/type_traits/floating_point_promotion.hpp \ + boost/type_traits/function_traits.hpp \ + boost/type_traits/has_new_operator.hpp \ + boost/type_traits/has_nothrow_assign.hpp \ + boost/type_traits/has_nothrow_constructor.hpp \ + boost/type_traits/has_nothrow_copy.hpp \ + boost/type_traits/has_nothrow_destructor.hpp \ + boost/type_traits/has_trivial_assign.hpp \ + boost/type_traits/has_trivial_constructor.hpp \ + boost/type_traits/has_trivial_copy.hpp \ + boost/type_traits/has_trivial_destructor.hpp \ + boost/type_traits/has_virtual_destructor.hpp \ + boost/type_traits/ice.hpp \ + boost/type_traits/integral_constant.hpp \ + boost/type_traits/integral_promotion.hpp \ + boost/type_traits/intrinsics.hpp \ + boost/type_traits/is_abstract.hpp \ + boost/type_traits/is_arithmetic.hpp \ + boost/type_traits/is_array.hpp \ + boost/type_traits/is_base_and_derived.hpp \ + boost/type_traits/is_base_of.hpp \ + boost/type_traits/is_base_of_tr1.hpp \ + boost/type_traits/is_class.hpp \ + boost/type_traits/is_complex.hpp \ + boost/type_traits/is_compound.hpp \ + boost/type_traits/is_const.hpp \ + boost/type_traits/is_convertible.hpp \ + boost/type_traits/is_empty.hpp \ + boost/type_traits/is_enum.hpp \ + boost/type_traits/is_float.hpp \ + boost/type_traits/is_floating_point.hpp \ + boost/type_traits/is_function.hpp \ + boost/type_traits/is_fundamental.hpp \ + boost/type_traits/is_integral.hpp \ + boost/type_traits/is_lvalue_reference.hpp \ + boost/type_traits/is_member_function_pointer.hpp \ + boost/type_traits/is_member_object_pointer.hpp \ + boost/type_traits/is_member_pointer.hpp \ + boost/type_traits/is_object.hpp \ + boost/type_traits/is_pod.hpp \ + boost/type_traits/is_pointer.hpp \ + boost/type_traits/is_polymorphic.hpp \ + boost/type_traits/is_reference.hpp \ + boost/type_traits/is_rvalue_reference.hpp \ + boost/type_traits/is_same.hpp \ + boost/type_traits/is_scalar.hpp \ + boost/type_traits/is_signed.hpp \ + boost/type_traits/is_stateless.hpp \ + boost/type_traits/is_union.hpp \ + boost/type_traits/is_unsigned.hpp \ + boost/type_traits/is_virtual_base_of.hpp \ + boost/type_traits/is_void.hpp \ + boost/type_traits/is_volatile.hpp \ + boost/type_traits/make_signed.hpp \ + boost/type_traits/make_unsigned.hpp \ + boost/type_traits/msvc/remove_all_extents.hpp \ + boost/type_traits/msvc/remove_bounds.hpp \ + boost/type_traits/msvc/remove_const.hpp \ + boost/type_traits/msvc/remove_cv.hpp \ + boost/type_traits/msvc/remove_extent.hpp \ + boost/type_traits/msvc/remove_pointer.hpp \ + boost/type_traits/msvc/remove_reference.hpp \ + boost/type_traits/msvc/remove_volatile.hpp \ + boost/type_traits/msvc/typeof.hpp \ + boost/type_traits/object_traits.hpp \ + boost/type_traits/promote.hpp \ + boost/type_traits/rank.hpp \ + boost/type_traits/reference_traits.hpp \ + boost/type_traits/remove_all_extents.hpp \ + boost/type_traits/remove_bounds.hpp \ + boost/type_traits/remove_const.hpp \ + boost/type_traits/remove_cv.hpp \ + boost/type_traits/remove_extent.hpp \ + boost/type_traits/remove_pointer.hpp \ + boost/type_traits/remove_reference.hpp \ + boost/type_traits/remove_volatile.hpp \ + boost/type_traits/same_traits.hpp \ + boost/type_traits/transform_traits.hpp \ + boost/type_traits/transform_traits_spec.hpp \ + boost/type_traits/type_with_alignment.hpp \ + boost/units/absolute.hpp \ + boost/units/base_dimension.hpp \ + boost/units/base_unit.hpp \ + boost/units/base_units/angle/arcminute.hpp \ + boost/units/base_units/angle/arcsecond.hpp \ + boost/units/base_units/angle/degree.hpp \ + boost/units/base_units/angle/gradian.hpp \ + boost/units/base_units/angle/radian.hpp \ + boost/units/base_units/angle/revolution.hpp \ + boost/units/base_units/angle/steradian.hpp \ + boost/units/base_units/astronomical/astronomical_unit.hpp \ + boost/units/base_units/astronomical/light_day.hpp \ + boost/units/base_units/astronomical/light_hour.hpp \ + boost/units/base_units/astronomical/light_minute.hpp \ + boost/units/base_units/astronomical/light_second.hpp \ + boost/units/base_units/astronomical/light_year.hpp \ + boost/units/base_units/astronomical/parsec.hpp \ + boost/units/base_units/cgs/biot.hpp \ + boost/units/base_units/cgs/centimeter.hpp \ + boost/units/base_units/cgs/gram.hpp \ + boost/units/base_units/imperial/conversions.hpp \ + boost/units/base_units/imperial/drachm.hpp \ + boost/units/base_units/imperial/fluid_ounce.hpp \ + boost/units/base_units/imperial/foot.hpp \ + boost/units/base_units/imperial/furlong.hpp \ + boost/units/base_units/imperial/gallon.hpp \ + boost/units/base_units/imperial/gill.hpp \ + boost/units/base_units/imperial/grain.hpp \ + boost/units/base_units/imperial/hundredweight.hpp \ + boost/units/base_units/imperial/inch.hpp \ + boost/units/base_units/imperial/league.hpp \ + boost/units/base_units/imperial/mile.hpp \ + boost/units/base_units/imperial/ounce.hpp \ + boost/units/base_units/imperial/pint.hpp \ + boost/units/base_units/imperial/pound.hpp \ + boost/units/base_units/imperial/quart.hpp \ + boost/units/base_units/imperial/quarter.hpp \ + boost/units/base_units/imperial/stone.hpp \ + boost/units/base_units/imperial/thou.hpp \ + boost/units/base_units/imperial/ton.hpp \ + boost/units/base_units/imperial/yard.hpp \ + boost/units/base_units/metric/angstrom.hpp \ + boost/units/base_units/metric/are.hpp \ + boost/units/base_units/metric/atmosphere.hpp \ + boost/units/base_units/metric/bar.hpp \ + boost/units/base_units/metric/barn.hpp \ + boost/units/base_units/metric/day.hpp \ + boost/units/base_units/metric/fermi.hpp \ + boost/units/base_units/metric/hectare.hpp \ + boost/units/base_units/metric/hour.hpp \ + boost/units/base_units/metric/knot.hpp \ + boost/units/base_units/metric/liter.hpp \ + boost/units/base_units/metric/micron.hpp \ + boost/units/base_units/metric/minute.hpp \ + boost/units/base_units/metric/mmHg.hpp \ + boost/units/base_units/metric/nautical_mile.hpp \ + boost/units/base_units/metric/ton.hpp \ + boost/units/base_units/metric/torr.hpp \ + boost/units/base_units/metric/year.hpp \ + boost/units/base_units/si/ampere.hpp \ + boost/units/base_units/si/candela.hpp \ + boost/units/base_units/si/kelvin.hpp \ + boost/units/base_units/si/kilogram.hpp \ + boost/units/base_units/si/meter.hpp \ + boost/units/base_units/si/mole.hpp \ + boost/units/base_units/si/second.hpp \ + boost/units/base_units/temperature/celsius.hpp \ + boost/units/base_units/temperature/conversions.hpp \ + boost/units/base_units/temperature/fahrenheit.hpp \ + boost/units/base_units/us/cup.hpp \ + boost/units/base_units/us/dram.hpp \ + boost/units/base_units/us/fluid_dram.hpp \ + boost/units/base_units/us/fluid_ounce.hpp \ + boost/units/base_units/us/foot.hpp \ + boost/units/base_units/us/gallon.hpp \ + boost/units/base_units/us/gill.hpp \ + boost/units/base_units/us/grain.hpp \ + boost/units/base_units/us/hundredweight.hpp \ + boost/units/base_units/us/inch.hpp \ + boost/units/base_units/us/mil.hpp \ + boost/units/base_units/us/mile.hpp \ + boost/units/base_units/us/minim.hpp \ + boost/units/base_units/us/ounce.hpp \ + boost/units/base_units/us/pint.hpp \ + boost/units/base_units/us/pound.hpp \ + boost/units/base_units/us/pound_force.hpp \ + boost/units/base_units/us/quart.hpp \ + boost/units/base_units/us/tablespoon.hpp \ + boost/units/base_units/us/teaspoon.hpp \ + boost/units/base_units/us/ton.hpp \ + boost/units/base_units/us/yard.hpp \ + boost/units/cmath.hpp \ + boost/units/config.hpp \ + boost/units/conversion.hpp \ + boost/units/derived_dimension.hpp \ + boost/units/detail/absolute_impl.hpp \ + boost/units/detail/cmath_impl.hpp \ + boost/units/detail/conversion_impl.hpp \ + boost/units/detail/dim_impl.hpp \ + boost/units/detail/dimension_impl.hpp \ + boost/units/detail/dimension_list.hpp \ + boost/units/detail/dimensionless_unit.hpp \ + boost/units/detail/heterogeneous_conversion.hpp \ + boost/units/detail/linear_algebra.hpp \ + boost/units/detail/one.hpp \ + boost/units/detail/ordinal.hpp \ + boost/units/detail/prevent_redefinition.hpp \ + boost/units/detail/push_front_if.hpp \ + boost/units/detail/push_front_or_add.hpp \ + boost/units/detail/sort.hpp \ + boost/units/detail/static_rational_power.hpp \ + boost/units/detail/unscale.hpp \ + boost/units/detail/utility.hpp \ + boost/units/dim.hpp \ + boost/units/dimension.hpp \ + boost/units/dimensionless_quantity.hpp \ + boost/units/dimensionless_type.hpp \ + boost/units/dimensionless_unit.hpp \ + boost/units/get_dimension.hpp \ + boost/units/get_system.hpp \ + boost/units/heterogeneous_system.hpp \ + boost/units/homogeneous_system.hpp \ + boost/units/io.hpp \ + boost/units/is_dim.hpp \ + boost/units/is_dimension_list.hpp \ + boost/units/is_dimensionless.hpp \ + boost/units/is_dimensionless_quantity.hpp \ + boost/units/is_dimensionless_unit.hpp \ + boost/units/is_quantity.hpp \ + boost/units/is_quantity_of_dimension.hpp \ + boost/units/is_quantity_of_system.hpp \ + boost/units/is_unit.hpp \ + boost/units/is_unit_of_dimension.hpp \ + boost/units/is_unit_of_system.hpp \ + boost/units/lambda.hpp \ + boost/units/limits.hpp \ + boost/units/make_scaled_unit.hpp \ + boost/units/make_system.hpp \ + boost/units/operators.hpp \ + boost/units/physical_dimensions.hpp \ + boost/units/physical_dimensions/absorbed_dose.hpp \ + boost/units/physical_dimensions/acceleration.hpp \ + boost/units/physical_dimensions/action.hpp \ + boost/units/physical_dimensions/activity.hpp \ + boost/units/physical_dimensions/amount.hpp \ + boost/units/physical_dimensions/angular_acceleration.hpp \ + boost/units/physical_dimensions/angular_momentum.hpp \ + boost/units/physical_dimensions/angular_velocity.hpp \ + boost/units/physical_dimensions/area.hpp \ + boost/units/physical_dimensions/capacitance.hpp \ + boost/units/physical_dimensions/conductance.hpp \ + boost/units/physical_dimensions/conductivity.hpp \ + boost/units/physical_dimensions/current.hpp \ + boost/units/physical_dimensions/dose_equivalent.hpp \ + boost/units/physical_dimensions/dynamic_viscosity.hpp \ + boost/units/physical_dimensions/electric_charge.hpp \ + boost/units/physical_dimensions/electric_potential.hpp \ + boost/units/physical_dimensions/energy.hpp \ + boost/units/physical_dimensions/energy_density.hpp \ + boost/units/physical_dimensions/force.hpp \ + boost/units/physical_dimensions/frequency.hpp \ + boost/units/physical_dimensions/heat_capacity.hpp \ + boost/units/physical_dimensions/illuminance.hpp \ + boost/units/physical_dimensions/impedance.hpp \ + boost/units/physical_dimensions/inductance.hpp \ + boost/units/physical_dimensions/kinematic_viscosity.hpp \ + boost/units/physical_dimensions/length.hpp \ + boost/units/physical_dimensions/luminance.hpp \ + boost/units/physical_dimensions/luminous_flux.hpp \ + boost/units/physical_dimensions/luminous_intensity.hpp \ + boost/units/physical_dimensions/magnetic_field_intensity.hpp \ + boost/units/physical_dimensions/magnetic_flux.hpp \ + boost/units/physical_dimensions/magnetic_flux_density.hpp \ + boost/units/physical_dimensions/mass.hpp \ + boost/units/physical_dimensions/mass_density.hpp \ + boost/units/physical_dimensions/molar_energy.hpp \ + boost/units/physical_dimensions/molar_heat_capacity.hpp \ + boost/units/physical_dimensions/moment_of_inertia.hpp \ + boost/units/physical_dimensions/momentum.hpp \ + boost/units/physical_dimensions/permeability.hpp \ + boost/units/physical_dimensions/permittivity.hpp \ + boost/units/physical_dimensions/plane_angle.hpp \ + boost/units/physical_dimensions/power.hpp \ + boost/units/physical_dimensions/pressure.hpp \ + boost/units/physical_dimensions/reluctance.hpp \ + boost/units/physical_dimensions/resistance.hpp \ + boost/units/physical_dimensions/resistivity.hpp \ + boost/units/physical_dimensions/solid_angle.hpp \ + boost/units/physical_dimensions/specific_energy.hpp \ + boost/units/physical_dimensions/specific_heat_capacity.hpp \ + boost/units/physical_dimensions/specific_volume.hpp \ + boost/units/physical_dimensions/stress.hpp \ + boost/units/physical_dimensions/surface_density.hpp \ + boost/units/physical_dimensions/surface_tension.hpp \ + boost/units/physical_dimensions/temperature.hpp \ + boost/units/physical_dimensions/thermal_conductivity.hpp \ + boost/units/physical_dimensions/time.hpp \ + boost/units/physical_dimensions/torque.hpp \ + boost/units/physical_dimensions/velocity.hpp \ + boost/units/physical_dimensions/volume.hpp \ + boost/units/physical_dimensions/wavenumber.hpp \ + boost/units/pow.hpp \ + boost/units/quantity.hpp \ + boost/units/reduce_unit.hpp \ + boost/units/scale.hpp \ + boost/units/scaled_base_unit.hpp \ + boost/units/static_constant.hpp \ + boost/units/static_rational.hpp \ + boost/units/systems/abstract.hpp \ + boost/units/systems/angle/degrees.hpp \ + boost/units/systems/angle/gradians.hpp \ + boost/units/systems/angle/revolutions.hpp \ + boost/units/systems/cgs.hpp \ + boost/units/systems/cgs/acceleration.hpp \ + boost/units/systems/cgs/area.hpp \ + boost/units/systems/cgs/base.hpp \ + boost/units/systems/cgs/current.hpp \ + boost/units/systems/cgs/dimensionless.hpp \ + boost/units/systems/cgs/dynamic_viscosity.hpp \ + boost/units/systems/cgs/energy.hpp \ + boost/units/systems/cgs/force.hpp \ + boost/units/systems/cgs/frequency.hpp \ + boost/units/systems/cgs/io.hpp \ + boost/units/systems/cgs/kinematic_viscosity.hpp \ + boost/units/systems/cgs/length.hpp \ + boost/units/systems/cgs/mass.hpp \ + boost/units/systems/cgs/mass_density.hpp \ + boost/units/systems/cgs/momentum.hpp \ + boost/units/systems/cgs/power.hpp \ + boost/units/systems/cgs/pressure.hpp \ + boost/units/systems/cgs/time.hpp \ + boost/units/systems/cgs/velocity.hpp \ + boost/units/systems/cgs/volume.hpp \ + boost/units/systems/cgs/wavenumber.hpp \ + boost/units/systems/detail/constants.hpp \ + boost/units/systems/si.hpp \ + boost/units/systems/si/absorbed_dose.hpp \ + boost/units/systems/si/acceleration.hpp \ + boost/units/systems/si/action.hpp \ + boost/units/systems/si/activity.hpp \ + boost/units/systems/si/amount.hpp \ + boost/units/systems/si/angular_acceleration.hpp \ + boost/units/systems/si/angular_momentum.hpp \ + boost/units/systems/si/angular_velocity.hpp \ + boost/units/systems/si/area.hpp \ + boost/units/systems/si/base.hpp \ + boost/units/systems/si/capacitance.hpp \ + boost/units/systems/si/catalytic_activity.hpp \ + boost/units/systems/si/codata/alpha_constants.hpp \ + boost/units/systems/si/codata/atomic-nuclear_constants.hpp \ + boost/units/systems/si/codata/deuteron_constants.hpp \ + boost/units/systems/si/codata/electromagnetic_constants.hpp \ + boost/units/systems/si/codata/electron_constants.hpp \ + boost/units/systems/si/codata/helion_constants.hpp \ + boost/units/systems/si/codata/muon_constants.hpp \ + boost/units/systems/si/codata/neutron_constants.hpp \ + boost/units/systems/si/codata/physico-chemical_constants.hpp \ + boost/units/systems/si/codata/proton_constants.hpp \ + boost/units/systems/si/codata/tau_constants.hpp \ + boost/units/systems/si/codata/triton_constants.hpp \ + boost/units/systems/si/codata/typedefs.hpp \ + boost/units/systems/si/codata/universal_constants.hpp \ + boost/units/systems/si/codata_constants.hpp \ + boost/units/systems/si/conductance.hpp \ + boost/units/systems/si/conductivity.hpp \ + boost/units/systems/si/current.hpp \ + boost/units/systems/si/dimensionless.hpp \ + boost/units/systems/si/dose_equivalent.hpp \ + boost/units/systems/si/dynamic_viscosity.hpp \ + boost/units/systems/si/electric_charge.hpp \ + boost/units/systems/si/electric_potential.hpp \ + boost/units/systems/si/energy.hpp \ + boost/units/systems/si/force.hpp \ + boost/units/systems/si/frequency.hpp \ + boost/units/systems/si/illuminance.hpp \ + boost/units/systems/si/impedance.hpp \ + boost/units/systems/si/inductance.hpp \ + boost/units/systems/si/io.hpp \ + boost/units/systems/si/kinematic_viscosity.hpp \ + boost/units/systems/si/length.hpp \ + boost/units/systems/si/luminous_flux.hpp \ + boost/units/systems/si/luminous_intensity.hpp \ + boost/units/systems/si/magnetic_field_intensity.hpp \ + boost/units/systems/si/magnetic_flux.hpp \ + boost/units/systems/si/magnetic_flux_density.hpp \ + boost/units/systems/si/mass.hpp \ + boost/units/systems/si/mass_density.hpp \ + boost/units/systems/si/moment_of_inertia.hpp \ + boost/units/systems/si/momentum.hpp \ + boost/units/systems/si/permeability.hpp \ + boost/units/systems/si/permittivity.hpp \ + boost/units/systems/si/plane_angle.hpp \ + boost/units/systems/si/power.hpp \ + boost/units/systems/si/prefixes.hpp \ + boost/units/systems/si/pressure.hpp \ + boost/units/systems/si/reluctance.hpp \ + boost/units/systems/si/resistance.hpp \ + boost/units/systems/si/resistivity.hpp \ + boost/units/systems/si/solid_angle.hpp \ + boost/units/systems/si/surface_density.hpp \ + boost/units/systems/si/surface_tension.hpp \ + boost/units/systems/si/temperature.hpp \ + boost/units/systems/si/time.hpp \ + boost/units/systems/si/torque.hpp \ + boost/units/systems/si/velocity.hpp \ + boost/units/systems/si/volume.hpp \ + boost/units/systems/si/wavenumber.hpp \ + boost/units/systems/temperature/celsius.hpp \ + boost/units/systems/temperature/fahrenheit.hpp \ + boost/units/unit.hpp \ + boost/units/units_fwd.hpp \ + boost/unordered_map.hpp \ + boost/unordered_set.hpp \ + boost/unordered/unordered_set.hpp \ + boost/unordered/unordered_set_fwd.hpp \ + boost/unordered/unordered_map_fwd.hpp \ + boost/unordered/detail/allocator_helpers.hpp \ + boost/unordered/detail/move.hpp \ + boost/unordered/detail/config.hpp \ + boost/unordered/detail/hash_table_impl.hpp \ + boost/unordered/detail/hash_table.hpp \ + boost/unordered/unordered_map.hpp \ + boost/utility.hpp \ + boost/utility/addressof.hpp \ + boost/utility/base_from_member.hpp \ + boost/utility/binary.hpp \ + boost/utility/compare_pointees.hpp \ + boost/utility/declval.hpp \ + boost/utility/detail/in_place_factory_prefix.hpp \ + boost/utility/detail/in_place_factory_suffix.hpp \ + boost/utility/detail/result_of_iterate.hpp \ + boost/utility/enable_if.hpp \ + boost/utility/in_place_factory.hpp \ + boost/utility/result_of.hpp \ + boost/utility/swap.hpp \ + boost/utility/typed_in_place_factory.hpp \ + boost/utility/value_init.hpp \ + boost/variant.hpp \ + boost/variant/variant.hpp \ + boost/variant/visitor_ptr.hpp \ + boost/variant/static_visitor.hpp \ + boost/variant/recursive_variant.hpp \ + boost/variant/get.hpp \ + boost/variant/variant_fwd.hpp \ + boost/variant/bad_visit.hpp \ + boost/variant/detail/substitute.hpp \ + boost/variant/detail/enable_recursive_fwd.hpp \ + boost/variant/detail/cast_storage.hpp \ + boost/variant/detail/make_variant_list.hpp \ + boost/variant/detail/backup_holder.hpp \ + boost/variant/detail/bool_trait_undef.hpp \ + boost/variant/detail/apply_visitor_unary.hpp \ + boost/variant/detail/generic_result_type.hpp \ + boost/variant/detail/variant_io.hpp \ + boost/variant/detail/substitute_fwd.hpp \ + boost/variant/detail/forced_return.hpp \ + boost/variant/detail/apply_visitor_binary.hpp \ + boost/variant/detail/move.hpp \ + boost/variant/detail/enable_recursive.hpp \ + boost/variant/detail/visitation_impl.hpp \ + boost/variant/detail/has_trivial_move.hpp \ + boost/variant/detail/config.hpp \ + boost/variant/detail/initializer.hpp \ + boost/variant/detail/bool_trait_def.hpp \ + boost/variant/detail/over_sequence.hpp \ + boost/variant/detail/has_nothrow_move.hpp \ + boost/variant/detail/apply_visitor_delayed.hpp \ + boost/variant/apply_visitor.hpp \ + boost/variant/recursive_wrapper.hpp \ + boost/variant/recursive_wrapper_fwd.hpp \ + boost/version.hpp \ + boost/visit_each.hpp \ + boost/wave.hpp \ + boost/weak_ptr.hpp + all: all-am .SUFFIXES: @@ -347,35 +3129,33 @@ distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/c_regex_traits.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/codecvt_error_category.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cpp_regex_traits.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cregex.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/date_generators.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/error_code.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileiter.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/future.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/greg_month.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/greg_weekday.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gregorian_types.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/icu.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/instances.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/once.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/operations.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/path.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/path_traits.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/portability.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/posix_api.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/posix_time_types.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex_debug.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex_raw_buffer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex_traits_defaults.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/static_mutex.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/thread.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tss_null.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unique_path.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/usinstances.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/utf8_codecvt_facet.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/w32_regex_traits.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/wc_regex_traits.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/wide_posix_api.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/windows_file_codecvt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/winstances.Plo@am__quote@ .cpp.o: @@ -425,6 +3205,25 @@ uninstall-includeHEADERS: echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ rm -f "$(DESTDIR)$(includedir)/$$f"; \ done +install-nobase_includeHEADERS: $(nobase_include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(mkdir_p) "$(DESTDIR)$(includedir)" + @$(am__vpath_adj_setup) \ + list='$(nobase_include_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + $(am__vpath_adj) \ + echo " $(nobase_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'"; \ + $(nobase_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \ + done + +uninstall-nobase_includeHEADERS: + @$(NORMAL_UNINSTALL) + @$(am__vpath_adj_setup) \ + list='$(nobase_include_HEADERS)'; for p in $$list; do \ + $(am__vpath_adj) \ + echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ + rm -f "$(DESTDIR)$(includedir)/$$f"; \ + done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ @@ -475,6 +3274,7 @@ distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) + $(mkdir_p) $(distdir)/boost $(distdir)/boost/algorithm $(distdir)/boost/algorithm/string $(distdir)/boost/algorithm/string/detail $(distdir)/boost/algorithm/string/std $(distdir)/boost/assign $(distdir)/boost/assign/std $(distdir)/boost/bind $(distdir)/boost/concept $(distdir)/boost/concept/detail $(distdir)/boost/config $(distdir)/boost/config/abi $(distdir)/boost/config/compiler $(distdir)/boost/config/no_tr1 $(distdir)/boost/config/platform $(distdir)/boost/config/stdlib $(distdir)/boost/date_time $(distdir)/boost/date_time/gregorian $(distdir)/boost/date_time/local_time $(distdir)/boost/date_time/posix_time $(distdir)/boost/detail $(distdir)/boost/exception $(distdir)/boost/exception/detail $(distdir)/boost/filesystem $(distdir)/boost/filesystem/v2 $(distdir)/boost/format $(distdir)/boost/format/detail $(distdir)/boost/function $(distdir)/boost/function/detail $(distdir)/boost/functional $(distdir)/boost/functional/detail $(distdir)/boost/functional/hash $(distdir)/boost/functional/hash/detail $(distdir)/boost/integer $(distdir)/boost/interprocess $(distdir)/boost/interprocess/allocators $(distdir)/boost/interprocess/allocators/detail $(distdir)/boost/interprocess/containers $(distdir)/boost/interprocess/containers/container $(distdir)/boost/interprocess/containers/container/detail $(distdir)/boost/interprocess/detail $(distdir)/boost/interprocess/indexes $(distdir)/boost/interprocess/ipc $(distdir)/boost/interprocess/mem_algo $(distdir)/boost/interprocess/mem_algo/detail $(distdir)/boost/interprocess/smart_ptr $(distdir)/boost/interprocess/smart_ptr/detail $(distdir)/boost/interprocess/streams $(distdir)/boost/interprocess/sync $(distdir)/boost/interprocess/sync/emulation $(distdir)/boost/interprocess/sync/posix $(distdir)/boost/interprocess/sync/xsi $(distdir)/boost/io $(distdir)/boost/iterator $(distdir)/boost/iterator/detail $(distdir)/boost/mpl $(distdir)/boost/mpl/aux_ $(distdir)/boost/mpl/aux_/config $(distdir)/boost/mpl/aux_/preprocessed/bcc $(distdir)/boost/mpl/aux_/preprocessed/bcc551 $(distdir)/boost/mpl/aux_/preprocessed/bcc_pre590 $(distdir)/boost/mpl/aux_/preprocessed/dmc $(distdir)/boost/mpl/aux_/preprocessed/gcc $(distdir)/boost/mpl/aux_/preprocessed/msvc60 $(distdir)/boost/mpl/aux_/preprocessed/msvc70 $(distdir)/boost/mpl/aux_/preprocessed/mwcw $(distdir)/boost/mpl/aux_/preprocessed/no_ctps $(distdir)/boost/mpl/aux_/preprocessed/no_ttp $(distdir)/boost/mpl/aux_/preprocessed/plain $(distdir)/boost/mpl/aux_/preprocessor $(distdir)/boost/mpl/aux_/range_c $(distdir)/boost/mpl/aux_/test $(distdir)/boost/mpl/limits $(distdir)/boost/mpl/list $(distdir)/boost/mpl/list/aux_ $(distdir)/boost/mpl/list/aux_/preprocessed/plain $(distdir)/boost/mpl/map $(distdir)/boost/mpl/map/aux_ $(distdir)/boost/mpl/map/aux_/preprocessed/no_ctps $(distdir)/boost/mpl/map/aux_/preprocessed/plain $(distdir)/boost/mpl/map/aux_/preprocessed/typeof_based $(distdir)/boost/mpl/math $(distdir)/boost/mpl/multiset $(distdir)/boost/mpl/multiset/aux_ $(distdir)/boost/mpl/set $(distdir)/boost/mpl/set/aux_ $(distdir)/boost/mpl/set/aux_/preprocessed/plain $(distdir)/boost/mpl/vector $(distdir)/boost/mpl/vector/aux_ $(distdir)/boost/mpl/vector/aux_/preprocessed/no_ctps $(distdir)/boost/mpl/vector/aux_/preprocessed/plain $(distdir)/boost/mpl/vector/aux_/preprocessed/typeof_based $(distdir)/boost/optional $(distdir)/boost/preprocessor $(distdir)/boost/preprocessor/arithmetic $(distdir)/boost/preprocessor/arithmetic/detail $(distdir)/boost/preprocessor/array $(distdir)/boost/preprocessor/comparison $(distdir)/boost/preprocessor/config $(distdir)/boost/preprocessor/control $(distdir)/boost/preprocessor/control/detail $(distdir)/boost/preprocessor/control/detail/dmc $(distdir)/boost/preprocessor/control/detail/edg $(distdir)/boost/preprocessor/control/detail/msvc $(distdir)/boost/preprocessor/debug $(distdir)/boost/preprocessor/detail $(distdir)/boost/preprocessor/detail/dmc $(distdir)/boost/preprocessor/facilities $(distdir)/boost/preprocessor/iteration $(distdir)/boost/preprocessor/iteration/detail $(distdir)/boost/preprocessor/iteration/detail/bounds $(distdir)/boost/preprocessor/iteration/detail/iter $(distdir)/boost/preprocessor/list $(distdir)/boost/preprocessor/list/detail $(distdir)/boost/preprocessor/list/detail/dmc $(distdir)/boost/preprocessor/list/detail/edg $(distdir)/boost/preprocessor/logical $(distdir)/boost/preprocessor/punctuation $(distdir)/boost/preprocessor/repetition $(distdir)/boost/preprocessor/repetition/detail $(distdir)/boost/preprocessor/repetition/detail/dmc $(distdir)/boost/preprocessor/repetition/detail/edg $(distdir)/boost/preprocessor/repetition/detail/msvc $(distdir)/boost/preprocessor/selection $(distdir)/boost/preprocessor/seq $(distdir)/boost/preprocessor/seq/detail $(distdir)/boost/preprocessor/slot $(distdir)/boost/preprocessor/slot/detail $(distdir)/boost/preprocessor/tuple $(distdir)/boost/ptr_container $(distdir)/boost/ptr_container/detail $(distdir)/boost/range $(distdir)/boost/range/algorithm $(distdir)/boost/range/detail $(distdir)/boost/range/detail/vc6 $(distdir)/boost/regex $(distdir)/boost/regex/config $(distdir)/boost/regex/pending $(distdir)/boost/regex/v4 $(distdir)/boost/smart_ptr $(distdir)/boost/smart_ptr/detail $(distdir)/boost/system $(distdir)/boost/thread $(distdir)/boost/thread/detail $(distdir)/boost/thread/pthread $(distdir)/boost/thread/win32 $(distdir)/boost/tuple $(distdir)/boost/tuple/detail $(distdir)/boost/type_traits $(distdir)/boost/type_traits/detail $(distdir)/boost/type_traits/msvc $(distdir)/boost/units $(distdir)/boost/units/base_units/angle $(distdir)/boost/units/base_units/astronomical $(distdir)/boost/units/base_units/cgs $(distdir)/boost/units/base_units/imperial $(distdir)/boost/units/base_units/metric $(distdir)/boost/units/base_units/si $(distdir)/boost/units/base_units/temperature $(distdir)/boost/units/base_units/us $(distdir)/boost/units/detail $(distdir)/boost/units/physical_dimensions $(distdir)/boost/units/systems $(distdir)/boost/units/systems/angle $(distdir)/boost/units/systems/cgs $(distdir)/boost/units/systems/detail $(distdir)/boost/units/systems/si $(distdir)/boost/units/systems/si/codata $(distdir)/boost/units/systems/temperature $(distdir)/boost/unordered $(distdir)/boost/unordered/detail $(distdir)/boost/utility $(distdir)/boost/utility/detail $(distdir)/boost/variant $(distdir)/boost/variant/detail @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ list='$(DISTFILES)'; for file in $$list; do \ @@ -505,7 +3305,7 @@ check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) $(HEADERS) installdirs: - for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ + for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(mkdir_p) "$$dir"; \ done install: install-am @@ -553,9 +3353,7 @@ info: info-am info-am: -install-data-am: install-includeHEADERS - @$(NORMAL_INSTALL) - $(MAKE) $(AM_MAKEFLAGS) install-data-hook +install-data-am: install-includeHEADERS install-nobase_includeHEADERS install-exec-am: install-libLTLIBRARIES @@ -584,21 +3382,22 @@ ps: ps-am ps-am: uninstall-am: uninstall-includeHEADERS uninstall-info-am \ - uninstall-libLTLIBRARIES + uninstall-libLTLIBRARIES uninstall-nobase_includeHEADERS .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool ctags distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ - install install-am install-data install-data-am \ - install-data-hook install-exec install-exec-am \ - install-includeHEADERS install-info install-info-am \ - install-libLTLIBRARIES install-man install-strip installcheck \ + install install-am install-data install-data-am install-exec \ + install-exec-am install-includeHEADERS install-info \ + install-info-am install-libLTLIBRARIES install-man \ + install-nobase_includeHEADERS install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-includeHEADERS \ - uninstall-info-am uninstall-libLTLIBRARIES + uninstall-info-am uninstall-libLTLIBRARIES \ + uninstall-nobase_includeHEADERS test: @@ -610,9 +3409,6 @@ leakcheck: docs: bootstrap: install-data-am - -install-data-hook: - cp -Rpf boost $(DESTDIR)$(includedir) # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/utils/boost_idb/README b/utils/boost_idb/README index bba0cf6c..d5803885 100644 --- a/utils/boost_idb/README +++ b/utils/boost_idb/README @@ -1,11 +1,15 @@ -These files are verbatim copies from Boost 1.55.0. Only the files +These files are verbatim copies from Boost 1.39.0. Only the files pertinent to InfiniDB are included, however. This should be all of the thread, filesystem, regex and date_time libraries, as well as most of the header-only code. All of the code here retains its original copyright and is included only for the convenience of compiling InfiniDB without -having to locate and install a Boost 1.55.0 development package. +having to locate and install a Boost 1.39.0 development package. -See http://www.boost.org/ for a complete 1.55.0 source distribution. +See http://www.boost.org/ for a complete 1.39.0 source distribution. + +The interprocess library comes from 1.42.0. + +There are local changes to assert.hpp and interprocess/sync/posix/semaphore_wrapper.hpp diff --git a/utils/boost_idb/boost/algorithm/clamp.hpp b/utils/boost_idb/boost/algorithm/clamp.hpp deleted file mode 100644 index ae98d15d..00000000 --- a/utils/boost_idb/boost/algorithm/clamp.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - Revision history: - 27 June 2009 mtc First version - 23 Oct 2010 mtc Added predicate version - -*/ - -/// \file clamp.hpp -/// \brief Clamp algorithm -/// \author Marshall Clow -/// -/// Suggested by olafvdspek in https://svn.boost.org/trac/boost/ticket/3215 - -#ifndef BOOST_ALGORITHM_CLAMP_HPP -#define BOOST_ALGORITHM_CLAMP_HPP - -#include // For std::less -#include // For std::iterator_traits -#include - -#include -#include -#include // for identity -#include // for boost::disable_if - -namespace boost { namespace algorithm { - -/// \fn clamp ( T const& val, -/// typename boost::mpl::identity::type const& lo, -/// typename boost::mpl::identity::type const& hi, Pred p ) -/// \return the value "val" brought into the range [ lo, hi ] -/// using the comparison predicate p. -/// If p ( val, lo ) return lo. -/// If p ( hi, val ) return hi. -/// Otherwise, return the original value. -/// -/// \param val The value to be clamped -/// \param lo The lower bound of the range to be clamped to -/// \param hi The upper bound of the range to be clamped to -/// \param p A predicate to use to compare the values. -/// p ( a, b ) returns a boolean. -/// - template - T const & clamp ( T const& val, - typename boost::mpl::identity::type const & lo, - typename boost::mpl::identity::type const & hi, Pred p ) - { -// assert ( !p ( hi, lo )); // Can't assert p ( lo, hi ) b/c they might be equal - return p ( val, lo ) ? lo : p ( hi, val ) ? hi : val; - } - - -/// \fn clamp ( T const& val, -/// typename boost::mpl::identity::type const& lo, -/// typename boost::mpl::identity::type const& hi ) -/// \return the value "val" brought into the range [ lo, hi ]. -/// If the value is less than lo, return lo. -/// If the value is greater than "hi", return hi. -/// Otherwise, return the original value. -/// -/// \param val The value to be clamped -/// \param lo The lower bound of the range to be clamped to -/// \param hi The upper bound of the range to be clamped to -/// - template - T const& clamp ( const T& val, - typename boost::mpl::identity::type const & lo, - typename boost::mpl::identity::type const & hi ) - { - return (clamp) ( val, lo, hi, std::less()); - } - -/// \fn clamp_range ( InputIterator first, InputIterator last, OutputIterator out, -/// std::iterator_traits::value_type lo, -/// std::iterator_traits::value_type hi ) -/// \return clamp the sequence of values [first, last) into [ lo, hi ] -/// -/// \param first The start of the range of values -/// \param last One past the end of the range of input values -/// \param out An output iterator to write the clamped values into -/// \param lo The lower bound of the range to be clamped to -/// \param hi The upper bound of the range to be clamped to -/// - template - OutputIterator clamp_range ( InputIterator first, InputIterator last, OutputIterator out, - typename std::iterator_traits::value_type lo, - typename std::iterator_traits::value_type hi ) - { - // this could also be written with bind and std::transform - while ( first != last ) - *out++ = clamp ( *first++, lo, hi ); - return out; - } - -/// \fn clamp_range ( const Range &r, OutputIterator out, -/// typename std::iterator_traits::type>::value_type lo, -/// typename std::iterator_traits::type>::value_type hi ) -/// \return clamp the sequence of values [first, last) into [ lo, hi ] -/// -/// \param r The range of values to be clamped -/// \param out An output iterator to write the clamped values into -/// \param lo The lower bound of the range to be clamped to -/// \param hi The upper bound of the range to be clamped to -/// - template - typename boost::disable_if_c::value, OutputIterator>::type - clamp_range ( const Range &r, OutputIterator out, - typename std::iterator_traits::type>::value_type lo, - typename std::iterator_traits::type>::value_type hi ) - { - return clamp_range ( boost::begin ( r ), boost::end ( r ), out, lo, hi ); - } - - -/// \fn clamp_range ( InputIterator first, InputIterator last, OutputIterator out, -/// std::iterator_traits::value_type lo, -/// std::iterator_traits::value_type hi, Pred p ) -/// \return clamp the sequence of values [first, last) into [ lo, hi ] -/// using the comparison predicate p. -/// -/// \param first The start of the range of values -/// \param last One past the end of the range of input values -/// \param out An output iterator to write the clamped values into -/// \param lo The lower bound of the range to be clamped to -/// \param hi The upper bound of the range to be clamped to -/// \param p A predicate to use to compare the values. -/// p ( a, b ) returns a boolean. - -/// - template - OutputIterator clamp_range ( InputIterator first, InputIterator last, OutputIterator out, - typename std::iterator_traits::value_type lo, - typename std::iterator_traits::value_type hi, Pred p ) - { - // this could also be written with bind and std::transform - while ( first != last ) - *out++ = clamp ( *first++, lo, hi, p ); - return out; - } - -/// \fn clamp_range ( const Range &r, OutputIterator out, -/// typename std::iterator_traits::type>::value_type lo, -/// typename std::iterator_traits::type>::value_type hi, -/// Pred p ) -/// \return clamp the sequence of values [first, last) into [ lo, hi ] -/// using the comparison predicate p. -/// -/// \param r The range of values to be clamped -/// \param out An output iterator to write the clamped values into -/// \param lo The lower bound of the range to be clamped to -/// \param hi The upper bound of the range to be clamped to -/// \param p A predicate to use to compare the values. -/// p ( a, b ) returns a boolean. -// -// Disable this template if the first two parameters are the same type; -// In that case, the user will get the two iterator version. - template - typename boost::disable_if_c::value, OutputIterator>::type - clamp_range ( const Range &r, OutputIterator out, - typename std::iterator_traits::type>::value_type lo, - typename std::iterator_traits::type>::value_type hi, - Pred p ) - { - return clamp_range ( boost::begin ( r ), boost::end ( r ), out, lo, hi, p ); - } - - -}} - -#endif // BOOST_ALGORITHM_CLAMP_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/all_of.hpp b/utils/boost_idb/boost/algorithm/cxx11/all_of.hpp deleted file mode 100644 index b76cb3f0..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/all_of.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file all_of.hpp -/// \brief Test ranges to see if all elements match a value or predicate. -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_ALL_OF_HPP -#define BOOST_ALGORITHM_ALL_OF_HPP - -#include // for std::all_of, if available -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of all_of if it is available -using std::all_of; // Section 25.2.1 -#else -/// \fn all_of ( InputIterator first, InputIterator last, Predicate p ) -/// \return true if all elements in [first, last) satisfy the predicate 'p' -/// \note returns true on an empty range -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p A predicate for testing the elements of the sequence -/// -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -bool all_of ( InputIterator first, InputIterator last, Predicate p ) -{ - for ( ; first != last; ++first ) - if ( !p(*first)) - return false; - return true; -} -#endif - -/// \fn all_of ( const Range &r, Predicate p ) -/// \return true if all elements in the range satisfy the predicate 'p' -/// \note returns true on an empty range -/// -/// \param r The input range -/// \param p A predicate for testing the elements of the range -/// -template -bool all_of ( const Range &r, Predicate p ) -{ - return boost::algorithm::all_of ( boost::begin (r), boost::end (r), p ); -} - -/// \fn all_of_equal ( InputIterator first, InputIterator last, const T &val ) -/// \return true if all elements in [first, last) are equal to 'val' -/// \note returns true on an empty range -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param val A value to compare against -/// -template -bool all_of_equal ( InputIterator first, InputIterator last, const T &val ) -{ - for ( ; first != last; ++first ) - if ( val != *first ) - return false; - return true; -} - -/// \fn all_of_equal ( const Range &r, const T &val ) -/// \return true if all elements in the range are equal to 'val' -/// \note returns true on an empty range -/// -/// \param r The input range -/// \param val A value to compare against -/// -template -bool all_of_equal ( const Range &r, const T &val ) -{ - return boost::algorithm::all_of_equal ( boost::begin (r), boost::end (r), val ); -} - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_ALL_OF_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/any_of.hpp b/utils/boost_idb/boost/algorithm/cxx11/any_of.hpp deleted file mode 100644 index c3ab3ce5..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/any_of.hpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - For more information, see http://www.boost.org -*/ - -/// \file -/// \brief Test ranges to see if any elements match a value or predicate. -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_ANY_OF_HPP -#define BOOST_ALGORITHM_ANY_OF_HPP - -#include // for std::any_of, if available -#include -#include - -namespace boost { namespace algorithm { - -// Use the C++11 versions of any_of if it is available -#if __cplusplus >= 201103L -using std::any_of; // Section 25.2.2 -#else -/// \fn any_of ( InputIterator first, InputIterator last, Predicate p ) -/// \return true if any of the elements in [first, last) satisfy the predicate -/// \note returns false on an empty range -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p A predicate for testing the elements of the sequence -/// -template -bool any_of ( InputIterator first, InputIterator last, Predicate p ) -{ - for ( ; first != last; ++first ) - if ( p(*first)) - return true; - return false; -} -#endif - -/// \fn any_of ( const Range &r, Predicate p ) -/// \return true if any elements in the range satisfy the predicate 'p' -/// \note returns false on an empty range -/// -/// \param r The input range -/// \param p A predicate for testing the elements of the range -/// -template -bool any_of ( const Range &r, Predicate p ) -{ - return boost::algorithm::any_of (boost::begin (r), boost::end (r), p); -} - -/// \fn any_of_equal ( InputIterator first, InputIterator last, const V &val ) -/// \return true if any of the elements in [first, last) are equal to 'val' -/// \note returns false on an empty range -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param val A value to compare against -/// -template -bool any_of_equal ( InputIterator first, InputIterator last, const V &val ) -{ - for ( ; first != last; ++first ) - if ( val == *first ) - return true; - return false; -} - -/// \fn any_of_equal ( const Range &r, const V &val ) -/// \return true if any of the elements in the range are equal to 'val' -/// \note returns false on an empty range -/// -/// \param r The input range -/// \param val A value to compare against -/// -template -bool any_of_equal ( const Range &r, const V &val ) -{ - return boost::algorithm::any_of_equal (boost::begin (r), boost::end (r), val); -} - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_ANY_OF_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/copy_if.hpp b/utils/boost_idb/boost/algorithm/cxx11/copy_if.hpp deleted file mode 100644 index 88b79b50..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/copy_if.hpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file copy_if.hpp -/// \brief Copy a subset of a sequence to a new sequence -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_COPY_IF_HPP -#define BOOST_ALGORITHM_COPY_IF_HPP - -#include // for std::copy_if, if available -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of copy_if if it is available -using std::copy_if; // Section 25.3.1 -#else -/// \fn copy_if ( InputIterator first, InputIterator last, OutputIterator result, Predicate p ) -/// \brief Copies all the elements from the input range that satisfy the -/// predicate to the output range. -/// \return The updated output iterator -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param result An output iterator to write the results into -/// \param p A predicate for testing the elements of the range -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -OutputIterator copy_if ( InputIterator first, InputIterator last, OutputIterator result, Predicate p ) -{ - for ( ; first != last; ++first ) - if (p(*first)) - *result++ = *first; - return result; -} -#endif - -/// \fn copy_if ( const Range &r, OutputIterator result, Predicate p ) -/// \brief Copies all the elements from the input range that satisfy the -/// predicate to the output range. -/// \return The updated output iterator -/// -/// \param r The input range -/// \param result An output iterator to write the results into -/// \param p A predicate for testing the elements of the range -/// -template -OutputIterator copy_if ( const Range &r, OutputIterator result, Predicate p ) -{ - return boost::algorithm::copy_if (boost::begin (r), boost::end(r), result, p); -} - - -/// \fn copy_while ( InputIterator first, InputIterator last, OutputIterator result, Predicate p ) -/// \brief Copies all the elements at the start of the input range that -/// satisfy the predicate to the output range. -/// \return The updated input and output iterators -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param result An output iterator to write the results into -/// \param p A predicate for testing the elements of the range -/// -template -std::pair -copy_while ( InputIterator first, InputIterator last, OutputIterator result, Predicate p ) -{ - for ( ; first != last && p(*first); ++first ) - *result++ = *first; - return std::make_pair(first, result); -} - -/// \fn copy_while ( const Range &r, OutputIterator result, Predicate p ) -/// \brief Copies all the elements at the start of the input range that -/// satisfy the predicate to the output range. -/// \return The updated input and output iterators -/// -/// \param r The input range -/// \param result An output iterator to write the results into -/// \param p A predicate for testing the elements of the range -/// -template -std::pair::type, OutputIterator> -copy_while ( const Range &r, OutputIterator result, Predicate p ) -{ - return boost::algorithm::copy_while (boost::begin (r), boost::end(r), result, p); -} - - -/// \fn copy_until ( InputIterator first, InputIterator last, OutputIterator result, Predicate p ) -/// \brief Copies all the elements at the start of the input range that do not -/// satisfy the predicate to the output range. -/// \return The updated output iterator -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param result An output iterator to write the results into -/// \param p A predicate for testing the elements of the range -/// -template -std::pair -copy_until ( InputIterator first, InputIterator last, OutputIterator result, Predicate p ) -{ - for ( ; first != last && !p(*first); ++first ) - *result++ = *first; - return std::make_pair(first, result); -} - -/// \fn copy_until ( const Range &r, OutputIterator result, Predicate p ) -/// \brief Copies all the elements at the start of the input range that do not -/// satisfy the predicate to the output range. -/// \return The updated output iterator -/// -/// \param r The input range -/// \param result An output iterator to write the results into -/// \param p A predicate for testing the elements of the range -/// -template -std::pair::type, OutputIterator> -copy_until ( const Range &r, OutputIterator result, Predicate p ) -{ - return boost::algorithm::copy_until (boost::begin (r), boost::end(r), result, p); -} - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_COPY_IF_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/copy_n.hpp b/utils/boost_idb/boost/algorithm/cxx11/copy_n.hpp deleted file mode 100644 index 0ea53bd2..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/copy_n.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file copy_n.hpp -/// \brief Copy n items from one sequence to another -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_COPY_N_HPP -#define BOOST_ALGORITHM_COPY_N_HPP - -#include // for std::copy_n, if available - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of copy_n if it is available -using std::copy_n; // Section 25.3.1 -#else -/// \fn copy_n ( InputIterator first, Size n, OutputIterator result ) -/// \brief Copies exactly n (n > 0) elements from the range starting at first to -/// the range starting at result. -/// \return The updated output iterator -/// -/// \param first The start of the input sequence -/// \param n The number of elements to copy -/// \param result An output iterator to write the results into -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -OutputIterator copy_n ( InputIterator first, Size n, OutputIterator result ) -{ - for ( ; n > 0; --n, ++first, ++result ) - *result = *first; - return result; -} -#endif -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_COPY_IF_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/find_if_not.hpp b/utils/boost_idb/boost/algorithm/cxx11/find_if_not.hpp deleted file mode 100644 index 4beed000..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/find_if_not.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file find_if_not.hpp -/// \brief Find the first element in a sequence that does not satisfy a predicate. -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_FIND_IF_NOT_HPP -#define BOOST_ALGORITHM_FIND_IF_NOT_HPP - -#include // for std::find_if_not, if it exists - -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of find_if_not if it is available -using std::find_if_not; // Section 25.2.5 -#else -/// \fn find_if_not(InputIterator first, InputIterator last, Predicate p) -/// \brief Finds the first element in the sequence that does not satisfy the predicate. -/// \return The iterator pointing to the desired element. -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p A predicate for testing the elements of the range -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -InputIterator find_if_not ( InputIterator first, InputIterator last, Predicate p ) -{ - for ( ; first != last; ++first ) - if ( !p(*first)) - break; - return first; -} -#endif - -/// \fn find_if_not ( const Range &r, Predicate p ) -/// \brief Finds the first element in the sequence that does not satisfy the predicate. -/// \return The iterator pointing to the desired element. -/// -/// \param r The input range -/// \param p A predicate for testing the elements of the range -/// -template -typename boost::range_iterator::type find_if_not ( const Range &r, Predicate p ) -{ - return boost::algorithm::find_if_not (boost::begin (r), boost::end(r), p); -} - -}} -#endif // BOOST_ALGORITHM_FIND_IF_NOT_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/iota.hpp b/utils/boost_idb/boost/algorithm/cxx11/iota.hpp deleted file mode 100644 index b4f0dafa..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/iota.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file iota.hpp -/// \brief Generate an increasing series -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_IOTA_HPP -#define BOOST_ALGORITHM_IOTA_HPP - -#include - -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of iota if it is available -using std::iota; // Section 26.7.6 -#else -/// \fn iota ( ForwardIterator first, ForwardIterator last, T value ) -/// \brief Generates an increasing sequence of values, and stores them in [first, last) -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param value The initial value of the sequence to be generated -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -void iota ( ForwardIterator first, ForwardIterator last, T value ) -{ - for ( ; first != last; ++first, ++value ) - *first = value; -} -#endif - -/// \fn iota ( Range &r, T value ) -/// \brief Generates an increasing sequence of values, and stores them in the input Range. -/// -/// \param r The input range -/// \param value The initial value of the sequence to be generated -/// -template -void iota ( Range &r, T value ) -{ - boost::algorithm::iota (boost::begin(r), boost::end(r), value); -} - - -/// \fn iota_n ( OutputIterator out, T value, std::size_t n ) -/// \brief Generates an increasing sequence of values, and stores them in the input Range. -/// -/// \param out An output iterator to write the results into -/// \param value The initial value of the sequence to be generated -/// \param n The number of items to write -/// -template -OutputIterator iota_n ( OutputIterator out, T value, std::size_t n ) -{ - while ( n-- > 0 ) - *out++ = value++; - - return out; -} - -}} - -#endif // BOOST_ALGORITHM_IOTA_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/is_partitioned.hpp b/utils/boost_idb/boost/algorithm/cxx11/is_partitioned.hpp deleted file mode 100644 index e939e056..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/is_partitioned.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file is_partitioned.hpp -/// \brief Tell if a sequence is partitioned -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_IS_PARTITIONED_HPP -#define BOOST_ALGORITHM_IS_PARTITIONED_HPP - -#include // for std::is_partitioned, if available - -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of is_partitioned if it is available -using std::is_partitioned; // Section 25.3.13 -#else -/// \fn is_partitioned ( InputIterator first, InputIterator last, UnaryPredicate p ) -/// \brief Tests to see if a sequence is partitioned according to a predicate -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p The predicate to test the values with -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -bool is_partitioned ( InputIterator first, InputIterator last, UnaryPredicate p ) -{ -// Run through the part that satisfy the predicate - for ( ; first != last; ++first ) - if ( !p (*first)) - break; -// Now the part that does not satisfy the predicate - for ( ; first != last; ++first ) - if ( p (*first)) - return false; - return true; -} -#endif - -/// \fn is_partitioned ( const Range &r, UnaryPredicate p ) -/// \brief Generates an increasing sequence of values, and stores them in the input Range. -/// -/// \param r The input range -/// \param p The predicate to test the values with -/// -template -bool is_partitioned ( const Range &r, UnaryPredicate p ) -{ - return boost::algorithm::is_partitioned (boost::begin(r), boost::end(r), p); -} - - -}} - -#endif // BOOST_ALGORITHM_IS_PARTITIONED_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/is_permutation.hpp b/utils/boost_idb/boost/algorithm/cxx11/is_permutation.hpp deleted file mode 100644 index e1273f1d..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/is_permutation.hpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file is_permutation.hpp -/// \brief Is a sequence a permutation of another sequence -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_IS_PERMUTATION_HPP -#define BOOST_ALGORITHM_IS_PERMUTATION_HPP - -#include // for std::less, tie, mismatch and is_permutation (if available) -#include // for std::make_pair -#include // for std::equal_to -#include - -#include -#include -#include -#include -#include // for tie - -namespace boost { namespace algorithm { - -/// \cond DOXYGEN_HIDE -namespace detail { - template - struct value_predicate { - value_predicate ( Predicate p, Iterator it ) : p_ ( p ), it_ ( it ) {} - - template - bool operator () ( const T1 &t1 ) const { return p_ ( *it_, t1 ); } - private: - Predicate p_; - Iterator it_; - }; - -// Preconditions: -// 1. The sequences are the same length -// 2. Any common elements on the front have been removed (not necessary for correctness, just for performance) - template< class ForwardIterator1, class ForwardIterator2, class BinaryPredicate > - bool is_permutation_inner ( ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2, - BinaryPredicate p ) { - // for each unique value in the sequence [first1,last1), count how many times - // it occurs, and make sure it occurs the same number of times in [first2, last2) - for ( ForwardIterator1 iter = first1; iter != last1; ++iter ) { - value_predicate pred ( p, iter ); - - /* For each value we haven't seen yet... */ - if ( std::find_if ( first1, iter, pred ) == iter ) { - std::size_t dest_count = std::count_if ( first2, last2, pred ); - if ( dest_count == 0 || dest_count != (std::size_t) std::count_if ( iter, last1, pred )) - return false; - } - } - - return true; - } - - template< class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> - bool is_permutation_tag ( ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2, - BinaryPredicate p, - std::forward_iterator_tag, std::forward_iterator_tag ) { - - // Skip the common prefix (if any) - while ( first1 != last1 && first2 != last2 && p ( *first1, *first2 )) { - ++first1; - ++first2; - } - if ( first1 != last1 && first2 != last2 ) - return boost::algorithm::detail::is_permutation_inner ( first1, last1, first2, last2, - std::equal_to::value_type> ()); - return first1 == last1 && first2 == last2; - } - - template - bool is_permutation_tag ( RandomAccessIterator1 first1, RandomAccessIterator1 last1, - RandomAccessIterator2 first2, RandomAccessIterator2 last2, - BinaryPredicate p, - std::random_access_iterator_tag, std::random_access_iterator_tag ) { - // Cheap check - if ( std::distance ( first1, last1 ) != std::distance ( first2, last2 )) - return false; - // Skip the common prefix (if any) - while ( first1 != last1 && first2 != last2 && p ( *first1, *first2 )) { - ++first1; - ++first2; - } - - if ( first1 != last1 && first2 != last2 ) - return is_permutation_inner (first1, last1, first2, last2, p); - return first1 == last1 && first2 == last2; - } - -} -/// \endcond - -#if __cplusplus >= 201103L -// Use the C++11 versions of is_permutation if it is available -using std::is_permutation; // Section 25.2.12 -#else - -/// \fn is_permutation ( ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 first2, BinaryPredicate p ) -/// \brief Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2 -/// -/// \param first1 The start of the input sequence -/// \param last1 One past the end of the input sequence -/// \param first2 The start of the second sequence -/// \param p The predicate to compare elements with -/// -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template< class ForwardIterator1, class ForwardIterator2, class BinaryPredicate > -bool is_permutation ( ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, BinaryPredicate p ) -{ -// Skip the common prefix (if any) -// std::tie (first1, first2) = std::mismatch (first1, last1, first2, p); - std::pair eq = std::mismatch (first1, last1, first2, p); - first1 = eq.first; - first2 = eq.second; - if ( first1 != last1 ) { - // Create last2 - ForwardIterator2 last2 = first2; - std::advance ( last2, std::distance (first1, last1)); - return boost::algorithm::detail::is_permutation_inner ( first1, last1, first2, last2, p ); - } - - return true; -} - -/// \fn is_permutation ( ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 first2 ) -/// \brief Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2 -/// -/// \param first1 The start of the input sequence -/// \param last2 One past the end of the input sequence -/// \param first2 The start of the second sequence -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template< class ForwardIterator1, class ForwardIterator2 > -bool is_permutation ( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2 ) -{ -// How should I deal with the idea that ForwardIterator1::value_type -// and ForwardIterator2::value_type could be different? Define my own comparison predicate? -// Skip the common prefix (if any) - std::pair eq = std::mismatch (first1, last1, first2 ); - first1 = eq.first; - first2 = eq.second; - if ( first1 != last1 ) { - // Create last2 - ForwardIterator2 last2 = first2; - std::advance ( last2, std::distance (first1, last1)); - return boost::algorithm::detail::is_permutation_inner ( first1, last1, first2, last2, - std::equal_to::value_type> ()); - } - return true; -} - -#endif - -/// \fn is_permutation ( ForwardIterator1 first, ForwardIterator1 last, -/// ForwardIterator2 first2, ForwardIterator2 last2 ) -/// \brief Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2 -/// -/// \param first1 The start of the input sequence -/// \param last2 One past the end of the input sequence -/// \param first2 The start of the second sequence -/// \param last1 One past the end of the second sequence -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template< class ForwardIterator1, class ForwardIterator2 > -bool is_permutation ( ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2 ) -{ -// How should I deal with the idea that ForwardIterator1::value_type -// and ForwardIterator2::value_type could be different? Define my own comparison predicate? - return boost::algorithm::detail::is_permutation_tag ( - first1, last1, first2, last2, - std::equal_to::value_type> (), - typename std::iterator_traits::iterator_category (), - typename std::iterator_traits::iterator_category ()); -} - -/// \fn is_permutation ( ForwardIterator1 first, ForwardIterator1 last, -/// ForwardIterator2 first2, ForwardIterator2 last2, -/// BinaryPredicate p ) -/// \brief Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2 -/// -/// \param first1 The start of the input sequence -/// \param last1 One past the end of the input sequence -/// \param first2 The start of the second sequence -/// \param last2 One past the end of the second sequence -/// \param pred The predicate to compare elements with -/// -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template< class ForwardIterator1, class ForwardIterator2, class BinaryPredicate > -bool is_permutation ( ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2, - BinaryPredicate pred ) -{ - return boost::algorithm::detail::is_permutation_tag ( - first1, last1, first2, last2, pred, - typename std::iterator_traits::iterator_category (), - typename std::iterator_traits::iterator_category ()); -} - - - -/// \fn is_permutation ( const Range &r, ForwardIterator first2 ) -/// \brief Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2 -/// -/// \param r The input range -/// \param first2 The start of the second sequence -template -bool is_permutation ( const Range &r, ForwardIterator first2 ) -{ - return boost::algorithm::is_permutation (boost::begin (r), boost::end (r), first2 ); -} - -/// \fn is_permutation ( const Range &r, ForwardIterator first2, BinaryPredicate pred ) -/// \brief Tests to see if the sequence [first,last) is a permutation of the sequence starting at first2 -/// -/// \param r The input range -/// \param first2 The start of the second sequence -/// \param pred The predicate to compare elements with -/// -// Disable this template when the first two parameters are the same type -// That way the non-range version will be chosen. -template -typename boost::disable_if_c::value, bool>::type -is_permutation ( const Range &r, ForwardIterator first2, BinaryPredicate pred ) -{ - return boost::algorithm::is_permutation (boost::begin (r), boost::end (r), first2, pred ); -} - -}} - -#endif // BOOST_ALGORITHM_IS_PERMUTATION_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/is_sorted.hpp b/utils/boost_idb/boost/algorithm/cxx11/is_sorted.hpp deleted file mode 100644 index c9bc65fb..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/is_sorted.hpp +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright (c) 2010 Nuovation System Designs, LLC -// Grant Erickson -// -// Reworked somewhat by Marshall Clow; August 2010 -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/ for latest version. -// - -#ifndef BOOST_ALGORITHM_ORDERED_HPP -#define BOOST_ALGORITHM_ORDERED_HPP - -#include -#include -#include - -#include -#include - -#include -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of is_sorted/is_sorted_until if they are available -using std::is_sorted_until; // Section 25.4.1.5 -using std::is_sorted; // Section 25.4.1.5 -#else -/// \fn is_sorted_until ( ForwardIterator first, ForwardIterator last, Pred p ) -/// \return the point in the sequence [first, last) where the elements are unordered -/// (according to the comparison predicate 'p'). -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// \param p A binary predicate that returns true if two elements are ordered. -/// - template - ForwardIterator is_sorted_until ( ForwardIterator first, ForwardIterator last, Pred p ) - { - if ( first == last ) return last; // the empty sequence is ordered - ForwardIterator next = first; - while ( ++next != last ) - { - if ( p ( *next, *first )) - return next; - first = next; - } - return last; - } - -/// \fn is_sorted_until ( ForwardIterator first, ForwardIterator last ) -/// \return the point in the sequence [first, last) where the elements are unordered -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// - template - ForwardIterator is_sorted_until ( ForwardIterator first, ForwardIterator last ) - { - typedef typename std::iterator_traits::value_type value_type; - return boost::algorithm::is_sorted_until ( first, last, std::less()); - } - - -/// \fn is_sorted ( ForwardIterator first, ForwardIterator last, Pred p ) -/// \return whether or not the entire sequence is sorted -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// \param p A binary predicate that returns true if two elements are ordered. -/// - template - bool is_sorted ( ForwardIterator first, ForwardIterator last, Pred p ) - { - return boost::algorithm::is_sorted_until (first, last, p) == last; - } - -/// \fn is_sorted ( ForwardIterator first, ForwardIterator last ) -/// \return whether or not the entire sequence is sorted -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// - template - bool is_sorted ( ForwardIterator first, ForwardIterator last ) - { - return boost::algorithm::is_sorted_until (first, last) == last; - } -#endif - -/// -/// -- Range based versions of the C++11 functions -/// - -/// \fn is_sorted_until ( const R &range, Pred p ) -/// \return the point in the range R where the elements are unordered -/// (according to the comparison predicate 'p'). -/// -/// \param range The range to be tested. -/// \param p A binary predicate that returns true if two elements are ordered. -/// - template - typename boost::lazy_disable_if_c< - boost::is_same::value, - typename boost::range_iterator - >::type is_sorted_until ( const R &range, Pred p ) - { - return boost::algorithm::is_sorted_until ( boost::begin ( range ), boost::end ( range ), p ); - } - - -/// \fn is_sorted_until ( const R &range ) -/// \return the point in the range R where the elements are unordered -/// -/// \param range The range to be tested. -/// - template - typename boost::range_iterator::type is_sorted_until ( const R &range ) - { - return boost::algorithm::is_sorted_until ( boost::begin ( range ), boost::end ( range )); - } - -/// \fn is_sorted ( const R &range, Pred p ) -/// \return whether or not the entire range R is sorted -/// (according to the comparison predicate 'p'). -/// -/// \param range The range to be tested. -/// \param p A binary predicate that returns true if two elements are ordered. -/// - template - typename boost::lazy_disable_if_c< boost::is_same::value, boost::mpl::identity >::type - is_sorted ( const R &range, Pred p ) - { - return boost::algorithm::is_sorted ( boost::begin ( range ), boost::end ( range ), p ); - } - - -/// \fn is_sorted ( const R &range ) -/// \return whether or not the entire range R is sorted -/// -/// \param range The range to be tested. -/// - template - bool is_sorted ( const R &range ) - { - return boost::algorithm::is_sorted ( boost::begin ( range ), boost::end ( range )); - } - - -/// -/// -- Range based versions of the C++11 functions -/// - -/// \fn is_increasing ( ForwardIterator first, ForwardIterator last ) -/// \return true if the entire sequence is increasing; i.e, each item is greater than or -/// equal to the previous one. -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// -/// \note This function will return true for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_strictly_increasing instead. - template - bool is_increasing ( ForwardIterator first, ForwardIterator last ) - { - typedef typename std::iterator_traits::value_type value_type; - return boost::algorithm::is_sorted (first, last, std::less()); - } - - -/// \fn is_increasing ( const R &range ) -/// \return true if the entire sequence is increasing; i.e, each item is greater than or -/// equal to the previous one. -/// -/// \param range The range to be tested. -/// -/// \note This function will return true for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_strictly_increasing instead. - template - bool is_increasing ( const R &range ) - { - return is_increasing ( boost::begin ( range ), boost::end ( range )); - } - - - -/// \fn is_decreasing ( ForwardIterator first, ForwardIterator last ) -/// \return true if the entire sequence is decreasing; i.e, each item is less than -/// or equal to the previous one. -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// -/// \note This function will return true for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_strictly_decreasing instead. - template - bool is_decreasing ( ForwardIterator first, ForwardIterator last ) - { - typedef typename std::iterator_traits::value_type value_type; - return boost::algorithm::is_sorted (first, last, std::greater()); - } - -/// \fn is_decreasing ( const R &range ) -/// \return true if the entire sequence is decreasing; i.e, each item is less than -/// or equal to the previous one. -/// -/// \param range The range to be tested. -/// -/// \note This function will return true for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_strictly_decreasing instead. - template - bool is_decreasing ( const R &range ) - { - return is_decreasing ( boost::begin ( range ), boost::end ( range )); - } - - - -/// \fn is_strictly_increasing ( ForwardIterator first, ForwardIterator last ) -/// \return true if the entire sequence is strictly increasing; i.e, each item is greater -/// than the previous one -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// -/// \note This function will return false for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_increasing instead. - template - bool is_strictly_increasing ( ForwardIterator first, ForwardIterator last ) - { - typedef typename std::iterator_traits::value_type value_type; - return boost::algorithm::is_sorted (first, last, std::less_equal()); - } - -/// \fn is_strictly_increasing ( const R &range ) -/// \return true if the entire sequence is strictly increasing; i.e, each item is greater -/// than the previous one -/// -/// \param range The range to be tested. -/// -/// \note This function will return false for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_increasing instead. - template - bool is_strictly_increasing ( const R &range ) - { - return is_strictly_increasing ( boost::begin ( range ), boost::end ( range )); - } - - -/// \fn is_strictly_decreasing ( ForwardIterator first, ForwardIterator last ) -/// \return true if the entire sequence is strictly decreasing; i.e, each item is less than -/// the previous one -/// -/// \param first The start of the sequence to be tested. -/// \param last One past the end of the sequence -/// -/// \note This function will return false for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_decreasing instead. - template - bool is_strictly_decreasing ( ForwardIterator first, ForwardIterator last ) - { - typedef typename std::iterator_traits::value_type value_type; - return boost::algorithm::is_sorted (first, last, std::greater_equal()); - } - -/// \fn is_strictly_decreasing ( const R &range ) -/// \return true if the entire sequence is strictly decreasing; i.e, each item is less than -/// the previous one -/// -/// \param range The range to be tested. -/// -/// \note This function will return false for sequences that contain items that compare -/// equal. If that is not what you intended, you should use is_decreasing instead. - template - bool is_strictly_decreasing ( const R &range ) - { - return is_strictly_decreasing ( boost::begin ( range ), boost::end ( range )); - } - -}} // namespace boost - -#endif // BOOST_ALGORITHM_ORDERED_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/none_of.hpp b/utils/boost_idb/boost/algorithm/cxx11/none_of.hpp deleted file mode 100644 index feae9919..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/none_of.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file none_of.hpp -/// \brief Test ranges to see if no elements match a value or predicate. -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_NONE_OF_HPP -#define BOOST_ALGORITHM_NONE_OF_HPP - -#include // for std::none_of, if available -#include -#include - -namespace boost { namespace algorithm { - -// Use the C++11 versions of the none_of if it is available -#if __cplusplus >= 201103L -using std::none_of; // Section 25.2.3 -#else -/// \fn none_of ( InputIterator first, InputIterator last, Predicate p ) -/// \return true if none of the elements in [first, last) satisfy the predicate 'p' -/// \note returns true on an empty range -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p A predicate for testing the elements of the sequence -/// -template -bool none_of ( InputIterator first, InputIterator last, Predicate p ) -{ -for ( ; first != last; ++first ) - if ( p(*first)) - return false; - return true; -} -#endif - -/// \fn none_of ( const Range &r, Predicate p ) -/// \return true if none of the elements in the range satisfy the predicate 'p' -/// \note returns true on an empty range -/// -/// \param r The input range -/// \param p A predicate for testing the elements of the range -/// -template -bool none_of ( const Range &r, Predicate p ) -{ - return boost::algorithm::none_of (boost::begin (r), boost::end (r), p ); -} - -/// \fn none_of_equal ( InputIterator first, InputIterator last, const V &val ) -/// \return true if none of the elements in [first, last) are equal to 'val' -/// \note returns true on an empty range -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param val A value to compare against -/// -template -bool none_of_equal ( InputIterator first, InputIterator last, const V &val ) -{ - for ( ; first != last; ++first ) - if ( val == *first ) - return false; - return true; -} - -/// \fn none_of_equal ( const Range &r, const V &val ) -/// \return true if none of the elements in the range are equal to 'val' -/// \note returns true on an empty range -/// -/// \param r The input range -/// \param val A value to compare against -/// -template -bool none_of_equal ( const Range &r, const V & val ) -{ - return boost::algorithm::none_of_equal (boost::begin (r), boost::end (r), val); -} - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_NONE_OF_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/one_of.hpp b/utils/boost_idb/boost/algorithm/cxx11/one_of.hpp deleted file mode 100644 index b6e8c771..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/one_of.hpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file one_of.hpp -/// \brief Test ranges to see if only one element matches a value or predicate. -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_ONE_OF_HPP -#define BOOST_ALGORITHM_ONE_OF_HPP - -#include // for std::find and std::find_if -#include - -#include -#include - -namespace boost { namespace algorithm { - -/// \fn one_of ( InputIterator first, InputIterator last, Predicate p ) -/// \return true if the predicate 'p' is true for exactly one item in [first, last). -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p A predicate for testing the elements of the sequence -/// -template -bool one_of ( InputIterator first, InputIterator last, Predicate p ) -{ - InputIterator i = std::find_if (first, last, p); - if (i == last) - return false; // Didn't occur at all - return boost::algorithm::none_of (++i, last, p); -} - -/// \fn one_of ( const Range &r, Predicate p ) -/// \return true if the predicate 'p' is true for exactly one item in the range. -/// -/// \param r The input range -/// \param p A predicate for testing the elements of the range -/// -template -bool one_of ( const Range &r, Predicate p ) -{ - return boost::algorithm::one_of ( boost::begin (r), boost::end (r), p ); -} - - -/// \fn one_of_equal ( InputIterator first, InputIterator last, const V &val ) -/// \return true if the value 'val' exists only once in [first, last). -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param val A value to compare against -/// -template -bool one_of_equal ( InputIterator first, InputIterator last, const V &val ) -{ - InputIterator i = std::find (first, last, val); // find first occurrence of 'val' - if (i == last) - return false; // Didn't occur at all - return boost::algorithm::none_of_equal (++i, last, val); -} - -/// \fn one_of_equal ( const Range &r, const V &val ) -/// \return true if the value 'val' exists only once in the range. -/// -/// \param r The input range -/// \param val A value to compare against -/// -template -bool one_of_equal ( const Range &r, const V &val ) -{ - return boost::algorithm::one_of_equal ( boost::begin (r), boost::end (r), val ); -} - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_ALL_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/partition_copy.hpp b/utils/boost_idb/boost/algorithm/cxx11/partition_copy.hpp deleted file mode 100644 index 15c4dd68..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/partition_copy.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file partition_copy.hpp -/// \brief Copy a subset of a sequence to a new sequence -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_PARTITION_COPY_HPP -#define BOOST_ALGORITHM_PARTITION_COPY_HPP - -#include // for std::partition_copy, if available -#include // for make_pair - -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of partition_copy if it is available -using std::partition_copy; // Section 25.3.13 -#else -/// \fn partition_copy ( InputIterator first, InputIterator last, -/// OutputIterator1 out_true, OutputIterator2 out_false, UnaryPredicate p ) -/// \brief Copies the elements that satisfy the predicate p from the range [first, last) -/// to the range beginning at d_first_true, and -/// copies the elements that do not satisfy p to the range beginning at d_first_false. -/// -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param out_true An output iterator to write the elements that satisfy the predicate into -/// \param out_false An output iterator to write the elements that do not satisfy the predicate into -/// \param p A predicate for dividing the elements of the input sequence. -/// -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -std::pair -partition_copy ( InputIterator first, InputIterator last, - OutputIterator1 out_true, OutputIterator2 out_false, UnaryPredicate p ) -{ - for ( ; first != last; ++first ) - if ( p (*first)) - *out_true++ = *first; - else - *out_false++ = *first; - return std::pair ( out_true, out_false ); -} -#endif - -/// \fn partition_copy ( const Range &r, -/// OutputIterator1 out_true, OutputIterator2 out_false, UnaryPredicate p ) -/// -/// \param r The input range -/// \param out_true An output iterator to write the elements that satisfy the predicate into -/// \param out_false An output iterator to write the elements that do not satisfy the predicate into -/// \param p A predicate for dividing the elements of the input sequence. -/// -template -std::pair -partition_copy ( const Range &r, OutputIterator1 out_true, OutputIterator2 out_false, - UnaryPredicate p ) -{ - return boost::algorithm::partition_copy - (boost::begin(r), boost::end(r), out_true, out_false, p ); -} - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_PARTITION_COPY_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx11/partition_point.hpp b/utils/boost_idb/boost/algorithm/cxx11/partition_point.hpp deleted file mode 100644 index 36d8384b..00000000 --- a/utils/boost_idb/boost/algorithm/cxx11/partition_point.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file partition_point.hpp -/// \brief Find the partition point in a sequence -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_PARTITION_POINT_HPP -#define BOOST_ALGORITHM_PARTITION_POINT_HPP - -#include // for std::partition_point, if available - -#include -#include - -namespace boost { namespace algorithm { - -#if __cplusplus >= 201103L -// Use the C++11 versions of partition_point if it is available -using std::partition_point; // Section 25.3.13 -#else -/// \fn partition_point ( ForwardIterator first, ForwardIterator last, Predicate p ) -/// \brief Given a partitioned range, returns the partition point, i.e, the first element -/// that does not satisfy p -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param p The predicate to test the values with -/// \note This function is part of the C++2011 standard library. -/// We will use the standard one if it is available, -/// otherwise we have our own implementation. -template -ForwardIterator partition_point ( ForwardIterator first, ForwardIterator last, Predicate p ) -{ - std::size_t dist = std::distance ( first, last ); - while ( first != last ) { - std::size_t d2 = dist / 2; - ForwardIterator ret_val = first; - std::advance (ret_val, d2); - if (p (*ret_val)) { - first = ++ret_val; - dist -= d2 + 1; - } - else { - last = ret_val; - dist = d2; - } - } - return first; -} -#endif - -/// \fn partition_point ( Range &r, Predicate p ) -/// \brief Given a partitioned range, returns the partition point -/// -/// \param r The input range -/// \param p The predicate to test the values with -/// -template -typename boost::range_iterator partition_point ( Range &r, Predicate p ) -{ - return boost::algorithm::partition_point (boost::begin(r), boost::end(r), p); -} - - -}} - -#endif // BOOST_ALGORITHM_PARTITION_POINT_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx14/equal.hpp b/utils/boost_idb/boost/algorithm/cxx14/equal.hpp deleted file mode 100644 index cfc62d5f..00000000 --- a/utils/boost_idb/boost/algorithm/cxx14/equal.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file equal.hpp -/// \brief Test ranges to if they are equal -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_EQUAL_HPP -#define BOOST_ALGORITHM_EQUAL_HPP - -#include // for std::equal -#include // for std::equal_to - -namespace boost { namespace algorithm { - -namespace detail { - - template - struct eq : public std::binary_function { - bool operator () ( const T1& v1, const T2& v2 ) const { return v1 == v2 ;} - }; - - template - bool equal ( RandomAccessIterator1 first1, RandomAccessIterator1 last1, - RandomAccessIterator2 first2, RandomAccessIterator2 last2, BinaryPredicate pred, - std::random_access_iterator_tag, std::random_access_iterator_tag ) - { - // Random-access iterators let is check the sizes in constant time - if ( std::distance ( first1, last1 ) != std::distance ( first2, last2 )) - return false; - // If we know that the sequences are the same size, the original version is fine - return std::equal ( first1, last1, first2, pred ); - } - - template - bool equal ( InputIterator1 first1, InputIterator1 last1, - InputIterator2 first2, InputIterator2 last2, BinaryPredicate pred, - std::input_iterator_tag, std::input_iterator_tag ) - { - for (; first1 != last1 && first2 != last2; ++first1, ++first2 ) - if ( !pred(*first1, *first2 )) - return false; - - return first1 == last1 && first2 == last2; - } -} - -/// \fn equal ( InputIterator1 first1, InputIterator1 last1, -/// InputIterator2 first2, InputIterator2 last2, -/// BinaryPredicate pred ) -/// \return true if all elements in the two ranges are equal -/// -/// \param first1 The start of the first range. -/// \param last1 One past the end of the first range. -/// \param first2 The start of the second range. -/// \param last2 One past the end of the second range. -/// \param pred A predicate for comparing the elements of the ranges -template -bool equal ( InputIterator1 first1, InputIterator1 last1, - InputIterator2 first2, InputIterator2 last2, BinaryPredicate pred ) -{ - return boost::algorithm::detail::equal ( - first1, last1, first2, last2, pred, - typename std::iterator_traits::iterator_category (), - typename std::iterator_traits::iterator_category ()); -} - -/// \fn equal ( InputIterator1 first1, InputIterator1 last1, -/// InputIterator2 first2, InputIterator2 last2 ) -/// \return true if all elements in the two ranges are equal -/// -/// \param first1 The start of the first range. -/// \param last1 One past the end of the first range. -/// \param first2 The start of the second range. -/// \param last2 One past the end of the second range. -template -bool equal ( InputIterator1 first1, InputIterator1 last1, - InputIterator2 first2, InputIterator2 last2 ) -{ - return boost::algorithm::detail::equal ( - first1, last1, first2, last2, - boost::algorithm::detail::eq< - typename std::iterator_traits::value_type, - typename std::iterator_traits::value_type> (), - typename std::iterator_traits::iterator_category (), - typename std::iterator_traits::iterator_category ()); -} - -// There are already range-based versions of these. - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_EQUAL_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx14/is_permutation.hpp b/utils/boost_idb/boost/algorithm/cxx14/is_permutation.hpp deleted file mode 100644 index 779acef2..00000000 --- a/utils/boost_idb/boost/algorithm/cxx14/is_permutation.hpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - Copyright (c) Marshall Clow 2013 - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -*/ - -/// \file equal.hpp -/// \brief Determines if one -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_IS_PERMUTATION_HPP -#define BOOST_ALGORITHM_IS_PERMUTATION_HPP - -#include -#include // for std::equal_to - -namespace boost { namespace algorithm { - -namespace detail { - - template - struct is_perm_eq : public std::binary_function { - bool operator () ( const T1& v1, const T2& v2 ) const { return v1 == v2 ;} - }; - - - template - bool is_permutation ( RandomAccessIterator1 first1, RandomAccessIterator1 last1, - RandomAccessIterator2 first2, RandomAccessIterator2 last2, BinaryPredicate pred, - std::random_access_iterator_tag, std::random_access_iterator_tag ) - { - // Random-access iterators let is check the sizes in constant time - if ( std::distance ( first1, last1 ) != std::distance ( first2, last2 )) - return false; - // If we know that the sequences are the same size, the original version is fine - return std::is_permutation ( first1, last1, first2, pred ); - } - - - template - bool is_permutation ( - ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2, - BinaryPredicate pred, - std::forward_iterator_tag, std::forward_iterator_tag ) - { - - // Look for common prefix - for (; first1 != last1 && first2 != last2; ++first1, ++first2) - if (!pred(*first1, *first2)) - goto not_done; - // We've reached the end of one of the sequences without a mismatch. - return first1 == last1 && first2 == last2; - not_done: - - // Check and make sure that we have the same # of elements left - typedef typename std::iterator_traits::difference_type diff1_t; - diff1_t len1 = _VSTD::distance(first1, last1); - typedef typename std::iterator_traits::difference_type diff2_t; - diff2_t len2 = _VSTD::distance(first2, last2); - if (len1 != len2) - return false; - - // For each element in [f1, l1) see if there are the - // same number of equal elements in [f2, l2) - for ( ForwardIterator1 i = first1; i != last1; ++i ) - { - // Have we already counted this value? - ForwardIterator1 j; - for ( j = first1; j != i; ++j ) - if (pred(*j, *i)) - break; - if ( j == i ) // didn't find it... - { - // Count number of *i in [f2, l2) - diff1_t c2 = 0; - for ( ForwardIterator2 iter2 = first2; iter2 != last2; ++iter2 ) - if (pred(*i, *iter2)) - ++c2; - if (c2 == 0) - return false; - - // Count number of *i in [i, l1) - diff1_t c1 = 0; - for (_ForwardIterator1 iter1 = i; iter1 != last1; ++iter1 ) - if (pred(*i, *iter1)) - ++c1; - if (c1 != c2) - return false; - } - } - return true; - } - -} - - -template -bool is_permutation ( - ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2, - BinaryPredicate pred ) -{ - return boost::algorithm::detail::is_permutation ( - first1, last1, first2, last2, pred, - typename std::iterator_traits::iterator_category (), - typename std::iterator_traits::iterator_category ()); -} - -template -bool is_permutation ( ForwardIterator1 first1, ForwardIterator1 last1, - ForwardIterator2 first2, ForwardIterator2 last2 ) -{ - typedef typename iterator_traits<_ForwardIterator1>::value_type value1_t; - typedef typename iterator_traits<_ForwardIterator2>::value_type value2_t; - return boost::algorithm::detail::is_permutation ( - first1, last1, first2, last2, - boost::algorithm::detail::is_perm_eq< - typename std::iterator_traits::value_type, - typename std::iterator_traits::value_type> (), - typename std::iterator_traits::iterator_category (), - typename std::iterator_traits::iterator_category ()); -} - -// There are already range-based versions of these. - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_IS_PERMUTATION_HPP diff --git a/utils/boost_idb/boost/algorithm/cxx14/mismatch.hpp b/utils/boost_idb/boost/algorithm/cxx14/mismatch.hpp deleted file mode 100644 index 926ab194..00000000 --- a/utils/boost_idb/boost/algorithm/cxx14/mismatch.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) Marshall Clow 2008-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE10.txt or copy at http://www.boost.org/LICENSE10.txt) -*/ - -/// \file mismatch.hpp -/// \brief Find the first mismatched element in a sequence -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_MISMATCH_HPP -#define BOOST_ALGORITHM_MISMATCH_HPP - -#include // for std::mismatch -#include // for std::pair - -namespace boost { namespace algorithm { - -/// \fn mismatch ( InputIterator1 first1, InputIterator1 last1, -/// InputIterator2 first2, InputIterator2 last2, -/// BinaryPredicate pred ) -/// \return a pair of iterators pointing to the first elements in the sequence that do not match -/// -/// \param first1 The start of the first range. -/// \param last1 One past the end of the first range. -/// \param first2 The start of the second range. -/// \param last2 One past the end of the second range. -/// \param pred A predicate for comparing the elements of the ranges -template -std::pair mismatch ( - InputIterator1 first1, InputIterator1 last1, - InputIterator2 first2, InputIterator2 last2, - BinaryPredicate pred ) -{ - for (; first1 != last1 && first2 != last2; ++first1, ++first2) - if ( !pred ( *first1, *first2 )) - break; - return std::pair(first1, first2); -} - -/// \fn mismatch ( InputIterator1 first1, InputIterator1 last1, -/// InputIterator2 first2, InputIterator2 last2 ) -/// \return a pair of iterators pointing to the first elements in the sequence that do not match -/// -/// \param first1 The start of the first range. -/// \param last1 One past the end of the first range. -/// \param first2 The start of the second range. -/// \param last2 One past the end of the second range. -template -std::pair mismatch ( - InputIterator1 first1, InputIterator1 last1, - InputIterator2 first2, InputIterator2 last2 ) -{ - for (; first1 != last1 && first2 != last2; ++first1, ++first2) - if ( *first1 != *first2 ) - break; - return std::pair(first1, first2); -} - -// There are already range-based versions of these. - -}} // namespace boost and algorithm - -#endif // BOOST_ALGORITHM_MISMATCH_HPP diff --git a/utils/boost_idb/boost/algorithm/gather.hpp b/utils/boost_idb/boost/algorithm/gather.hpp deleted file mode 100644 index 944bc943..00000000 --- a/utils/boost_idb/boost/algorithm/gather.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - Copyright 2008 Adobe Systems Incorporated - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - Revision history: - January 2008 mtc Version for Adobe Source Library - January 2013 mtc Version for Boost.Algorithm - -*/ - -/**************************************************************************************************/ - -/*! -\author Marshall Clow -\date January 2008 -*/ - -#ifndef BOOST_ALGORITHM_GATHER_HPP -#define BOOST_ALGORITHM_GATHER_HPP - -#include // for std::stable_partition -#include - -#include // for boost::bind -#include // for boost::begin(range) -#include // for boost::end(range) - - -/**************************************************************************************************/ -/*! - \defgroup gather gather - \ingroup mutating_algorithm - - \c gather() takes a collection of elements defined by a pair of iterators and moves - the ones satisfying a predicate to them to a position (called the pivot) within - the sequence. The algorithm is stable. The result is a pair of iterators that - contains the items that satisfy the predicate. - - Given an sequence containing: -
-    0 1 2 3 4 5 6 7 8 9
-    
- - a call to gather ( arr, arr + 10, arr + 4, IsEven ()) will result in: - -
-    1 3 0 2 4 6 8 5 7 9
-        |---|-----|
-      first |  second
-          pivot
-    
- - - The problem is broken down into two basic steps, namely, moving the items before the pivot - and then moving the items from the pivot to the end. These "moves" are done with calls to - stable_partition. - - \par Storage Requirements: - - The algorithm uses stable_partition, which will attempt to allocate temporary memory, - but will work in-situ if there is none available. - - \par Time Complexity: - - If there is sufficient memory available, the run time is linear in N. - If there is not any memory available, then the run time is O(N log N). -*/ - -/**************************************************************************************************/ - -namespace boost { namespace algorithm { - -/**************************************************************************************************/ - -/*! - \ingroup gather - \brief iterator-based gather implementation -*/ - -template < - typename BidirectionalIterator, // Iter models BidirectionalIterator - typename Pred> // Pred models UnaryPredicate -std::pair gather - ( BidirectionalIterator first, BidirectionalIterator last, BidirectionalIterator pivot, Pred pred ) -{ -// The first call partitions everything up to (but not including) the pivot element, -// while the second call partitions the rest of the sequence. - return std::make_pair ( - std::stable_partition ( first, pivot, !boost::bind ( pred, _1 )), - std::stable_partition ( pivot, last, boost::bind ( pred, _1 ))); -} - -/**************************************************************************************************/ - -/*! - \ingroup gather - \brief range-based gather implementation -*/ - -template < - typename BidirectionalRange, // - typename Pred> // Pred models UnaryPredicate -std::pair< - typename boost::range_iterator::type, - typename boost::range_iterator::type> -gather ( - const BidirectionalRange &range, - typename boost::range_iterator::type pivot, - Pred pred ) -{ - return boost::algorithm::gather ( boost::begin ( range ), boost::end ( range ), pivot, pred ); -} - -/**************************************************************************************************/ - -}} // namespace - -/**************************************************************************************************/ - -#endif - diff --git a/utils/boost_idb/boost/algorithm/hex.hpp b/utils/boost_idb/boost/algorithm/hex.hpp deleted file mode 100644 index 2adb0be4..00000000 --- a/utils/boost_idb/boost/algorithm/hex.hpp +++ /dev/null @@ -1,261 +0,0 @@ -/* - Copyright (c) Marshall Clow 2011-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - Thanks to Nevin for his comments/help. -*/ - -/* - General problem - turn a sequence of integral types into a sequence of hexadecimal characters. - - and back. -*/ - -/// \file hex.hpp -/// \brief Convert sequence of integral types into a sequence of hexadecimal -/// characters and back. Based on the MySQL functions HEX and UNHEX -/// \author Marshall Clow - -#ifndef BOOST_ALGORITHM_HEXHPP -#define BOOST_ALGORITHM_HEXHPP - -#include // for std::iterator_traits -#include - -#include -#include -#include - -#include -#include - - -namespace boost { namespace algorithm { - -/*! - \struct hex_decode_error - \brief Base exception class for all hex decoding errors -*/ /*! - \struct non_hex_input - \brief Thrown when a non-hex value (0-9, A-F) encountered when decoding. - Contains the offending character -*/ /*! - \struct not_enough_input - \brief Thrown when the input sequence unexpectedly ends - -*/ -struct hex_decode_error : virtual boost::exception, virtual std::exception {}; -struct not_enough_input : virtual hex_decode_error {}; -struct non_hex_input : virtual hex_decode_error {}; -typedef boost::error_info bad_char; - -namespace detail { -/// \cond DOXYGEN_HIDE - - template - OutputIterator encode_one ( T val, OutputIterator out ) { - const std::size_t num_hex_digits = 2 * sizeof ( T ); - char res [ num_hex_digits ]; - char *p = res + num_hex_digits; - for ( std::size_t i = 0; i < num_hex_digits; ++i, val >>= 4 ) - *--p = "0123456789ABCDEF" [ val & 0x0F ]; - return std::copy ( res, res + num_hex_digits, out ); - } - - template - unsigned char hex_char_to_int ( T val ) { - char c = static_cast ( val ); - unsigned retval = 0; - if ( c >= '0' && c <= '9' ) retval = c - '0'; - else if ( c >= 'A' && c <= 'F' ) retval = c - 'A' + 10; - else if ( c >= 'a' && c <= 'f' ) retval = c - 'a' + 10; - else BOOST_THROW_EXCEPTION (non_hex_input() << bad_char (c)); - return retval; - } - -// My own iterator_traits class. -// It is here so that I can "reach inside" some kinds of output iterators -// and get the type to write. - template - struct hex_iterator_traits { - typedef typename std::iterator_traits::value_type value_type; - }; - - template - struct hex_iterator_traits< std::back_insert_iterator > { - typedef typename Container::value_type value_type; - }; - - template - struct hex_iterator_traits< std::front_insert_iterator > { - typedef typename Container::value_type value_type; - }; - - template - struct hex_iterator_traits< std::insert_iterator > { - typedef typename Container::value_type value_type; - }; - -// ostream_iterators have three template parameters. -// The first one is the output type, the second one is the character type of -// the underlying stream, the third is the character traits. -// We only care about the first one. - template - struct hex_iterator_traits< std::ostream_iterator > { - typedef T value_type; - }; - - template - bool iter_end ( Iterator current, Iterator last ) { return current == last; } - - template - bool ptr_end ( const T* ptr, const T* /*end*/ ) { return *ptr == '\0'; } - -// What can we assume here about the inputs? -// is std::iterator_traits::value_type always 'char' ? -// Could it be wchar_t, say? Does it matter? -// We are assuming ASCII for the values - but what about the storage? - template - typename boost::enable_if::value_type>, OutputIterator>::type - decode_one ( InputIterator &first, InputIterator last, OutputIterator out, EndPred pred ) { - typedef typename hex_iterator_traits::value_type T; - T res (0); - - // Need to make sure that we get can read that many chars here. - for ( std::size_t i = 0; i < 2 * sizeof ( T ); ++i, ++first ) { - if ( pred ( first, last )) - BOOST_THROW_EXCEPTION (not_enough_input ()); - res = ( 16 * res ) + hex_char_to_int (*first); - } - - *out = res; - return ++out; - } -/// \endcond - } - - -/// \fn hex ( InputIterator first, InputIterator last, OutputIterator out ) -/// \brief Converts a sequence of integral types into a hexadecimal sequence of characters. -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param out An output iterator to the results into -/// \return The updated output iterator -/// \note Based on the MySQL function of the same name -template -typename boost::enable_if::value_type>, OutputIterator>::type -hex ( InputIterator first, InputIterator last, OutputIterator out ) { - for ( ; first != last; ++first ) - out = detail::encode_one ( *first, out ); - return out; - } - - -/// \fn hex ( const T *ptr, OutputIterator out ) -/// \brief Converts a sequence of integral types into a hexadecimal sequence of characters. -/// -/// \param ptr A pointer to a 0-terminated sequence of data. -/// \param out An output iterator to the results into -/// \return The updated output iterator -/// \note Based on the MySQL function of the same name -template -typename boost::enable_if, OutputIterator>::type -hex ( const T *ptr, OutputIterator out ) { - while ( *ptr ) - out = detail::encode_one ( *ptr++, out ); - return out; - } - -/// \fn hex ( const Range &r, OutputIterator out ) -/// \brief Converts a sequence of integral types into a hexadecimal sequence of characters. -/// -/// \param r The input range -/// \param out An output iterator to the results into -/// \return The updated output iterator -/// \note Based on the MySQL function of the same name -template -typename boost::enable_if::value_type>, OutputIterator>::type -hex ( const Range &r, OutputIterator out ) { - return hex (boost::begin(r), boost::end(r), out); -} - - -/// \fn unhex ( InputIterator first, InputIterator last, OutputIterator out ) -/// \brief Converts a sequence of hexadecimal characters into a sequence of integers. -/// -/// \param first The start of the input sequence -/// \param last One past the end of the input sequence -/// \param out An output iterator to the results into -/// \return The updated output iterator -/// \note Based on the MySQL function of the same name -template -OutputIterator unhex ( InputIterator first, InputIterator last, OutputIterator out ) { - while ( first != last ) - out = detail::decode_one ( first, last, out, detail::iter_end ); - return out; - } - - -/// \fn unhex ( const T *ptr, OutputIterator out ) -/// \brief Converts a sequence of hexadecimal characters into a sequence of integers. -/// -/// \param ptr A pointer to a null-terminated input sequence. -/// \param out An output iterator to the results into -/// \return The updated output iterator -/// \note Based on the MySQL function of the same name -template -OutputIterator unhex ( const T *ptr, OutputIterator out ) { - typedef typename detail::hex_iterator_traits::value_type OutputType; -// If we run into the terminator while decoding, we will throw a -// malformed input exception. It would be nicer to throw a 'Not enough input' -// exception - but how much extra work would that require? - while ( *ptr ) - out = detail::decode_one ( ptr, (const T *) NULL, out, detail::ptr_end ); - return out; - } - - -/// \fn OutputIterator unhex ( const Range &r, OutputIterator out ) -/// \brief Converts a sequence of hexadecimal characters into a sequence of integers. -/// -/// \param r The input range -/// \param out An output iterator to the results into -/// \return The updated output iterator -/// \note Based on the MySQL function of the same name -template -OutputIterator unhex ( const Range &r, OutputIterator out ) { - return unhex (boost::begin(r), boost::end(r), out); - } - - -/// \fn String hex ( const String &input ) -/// \brief Converts a sequence of integral types into a hexadecimal sequence of characters. -/// -/// \param input A container to be converted -/// \return A container with the encoded text -template -String hex ( const String &input ) { - String output; - output.reserve (input.size () * (2 * sizeof (typename String::value_type))); - (void) hex (input, std::back_inserter (output)); - return output; - } - -/// \fn String unhex ( const String &input ) -/// \brief Converts a sequence of hexadecimal characters into a sequence of characters. -/// -/// \param input A container to be converted -/// \return A container with the decoded text -template -String unhex ( const String &input ) { - String output; - output.reserve (input.size () / (2 * sizeof (typename String::value_type))); - (void) unhex (input, std::back_inserter (output)); - return output; - } - -}} - -#endif // BOOST_ALGORITHM_HEXHPP diff --git a/utils/boost_idb/boost/algorithm/minmax_element.hpp b/utils/boost_idb/boost/algorithm/minmax_element.hpp index 752f6cbd..0d2efd8c 100644 --- a/utils/boost_idb/boost/algorithm/minmax_element.hpp +++ b/utils/boost_idb/boost/algorithm/minmax_element.hpp @@ -99,10 +99,8 @@ namespace boost { // if odd number of elements, treat last element if (first != last) { // odd number of elements - if (comp(first, min_result)) { - min_result = first; - potential_min_result = last; - } + if (comp(first, min_result)) + min_result = first, potential_min_result = last; else if (comp(max_result, first)) max_result = first; } diff --git a/utils/boost_idb/boost/algorithm/searching/boyer_moore.hpp b/utils/boost_idb/boost/algorithm/searching/boyer_moore.hpp deleted file mode 100644 index c5fe9fa2..00000000 --- a/utils/boost_idb/boost/algorithm/searching/boyer_moore.hpp +++ /dev/null @@ -1,268 +0,0 @@ -/* - Copyright (c) Marshall Clow 2010-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - For more information, see http://www.boost.org -*/ - -#ifndef BOOST_ALGORITHM_BOYER_MOORE_SEARCH_HPP -#define BOOST_ALGORITHM_BOYER_MOORE_SEARCH_HPP - -#include // for std::iterator_traits - -#include -#include - -#include -#include - -#include -#include - -#include -#include - -namespace boost { namespace algorithm { - -/* - A templated version of the boyer-moore searching algorithm. - -References: - http://www.cs.utexas.edu/users/moore/best-ideas/string-searching/ - http://www.cs.utexas.edu/~moore/publications/fstrpos.pdf - -Explanations: - http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm - http://www.movsd.com/bm.htm - http://www.cs.ucdavis.edu/~gusfield/cs224f09/bnotes.pdf - -The Boyer-Moore search algorithm uses two tables, a "bad character" table -to tell how far to skip ahead when it hits a character that is not in the pattern, -and a "good character" table to tell how far to skip ahead when it hits a -mismatch on a character that _is_ in the pattern. - -Requirements: - * Random access iterators - * The two iterator types (patIter and corpusIter) must - "point to" the same underlying type and be comparable. - * Additional requirements may be imposed but the skip table, such as: - ** Numeric type (array-based skip table) - ** Hashable type (map-based skip table) -*/ - - template > - class boyer_moore { - typedef typename std::iterator_traits::difference_type difference_type; - public: - boyer_moore ( patIter first, patIter last ) - : pat_first ( first ), pat_last ( last ), - k_pattern_length ( std::distance ( pat_first, pat_last )), - skip_ ( k_pattern_length, -1 ), - suffix_ ( k_pattern_length + 1 ) - { - this->build_skip_table ( first, last ); - this->build_suffix_table ( first, last ); - } - - ~boyer_moore () {} - - /// \fn operator ( corpusIter corpus_first, corpusIter corpus_last ) - /// \brief Searches the corpus for the pattern that was passed into the constructor - /// - /// \param corpus_first The start of the data to search (Random Access Iterator) - /// \param corpus_last One past the end of the data to search - /// - template - corpusIter operator () ( corpusIter corpus_first, corpusIter corpus_last ) const { - BOOST_STATIC_ASSERT (( boost::is_same< - typename std::iterator_traits::value_type, - typename std::iterator_traits::value_type>::value )); - - if ( corpus_first == corpus_last ) return corpus_last; // if nothing to search, we didn't find it! - if ( pat_first == pat_last ) return corpus_first; // empty pattern matches at start - - const difference_type k_corpus_length = std::distance ( corpus_first, corpus_last ); - // If the pattern is larger than the corpus, we can't find it! - if ( k_corpus_length < k_pattern_length ) - return corpus_last; - - // Do the search - return this->do_search ( corpus_first, corpus_last ); - } - - template - typename boost::range_iterator::type operator () ( Range &r ) const { - return (*this) (boost::begin(r), boost::end(r)); - } - - private: -/// \cond DOXYGEN_HIDE - patIter pat_first, pat_last; - const difference_type k_pattern_length; - typename traits::skip_table_t skip_; - std::vector suffix_; - - /// \fn operator ( corpusIter corpus_first, corpusIter corpus_last, Pred p ) - /// \brief Searches the corpus for the pattern that was passed into the constructor - /// - /// \param corpus_first The start of the data to search (Random Access Iterator) - /// \param corpus_last One past the end of the data to search - /// \param p A predicate used for the search comparisons. - /// - template - corpusIter do_search ( corpusIter corpus_first, corpusIter corpus_last ) const { - /* ---- Do the matching ---- */ - corpusIter curPos = corpus_first; - const corpusIter lastPos = corpus_last - k_pattern_length; - difference_type j, k, m; - - while ( curPos <= lastPos ) { - /* while ( std::distance ( curPos, corpus_last ) >= k_pattern_length ) { */ - // Do we match right where we are? - j = k_pattern_length; - while ( pat_first [j-1] == curPos [j-1] ) { - j--; - // We matched - we're done! - if ( j == 0 ) - return curPos; - } - - // Since we didn't match, figure out how far to skip forward - k = skip_ [ curPos [ j - 1 ]]; - m = j - k - 1; - if ( k < j && m > suffix_ [ j ] ) - curPos += m; - else - curPos += suffix_ [ j ]; - } - - return corpus_last; // We didn't find anything - } - - - void build_skip_table ( patIter first, patIter last ) { - for ( std::size_t i = 0; first != last; ++first, ++i ) - skip_.insert ( *first, i ); - } - - - template - void compute_bm_prefix ( Iter pat_first, Iter pat_last, Container &prefix ) { - const std::size_t count = std::distance ( pat_first, pat_last ); - BOOST_ASSERT ( count > 0 ); - BOOST_ASSERT ( prefix.size () == count ); - - prefix[0] = 0; - std::size_t k = 0; - for ( std::size_t i = 1; i < count; ++i ) { - BOOST_ASSERT ( k < count ); - while ( k > 0 && ( pat_first[k] != pat_first[i] )) { - BOOST_ASSERT ( k < count ); - k = prefix [ k - 1 ]; - } - - if ( pat_first[k] == pat_first[i] ) - k++; - prefix [ i ] = k; - } - } - - void build_suffix_table ( patIter pat_first, patIter pat_last ) { - const std::size_t count = (std::size_t) std::distance ( pat_first, pat_last ); - - if ( count > 0 ) { // empty pattern - std::vector::value_type> reversed(count); - (void) std::reverse_copy ( pat_first, pat_last, reversed.begin ()); - - std::vector prefix (count); - compute_bm_prefix ( pat_first, pat_last, prefix ); - - std::vector prefix_reversed (count); - compute_bm_prefix ( reversed.begin (), reversed.end (), prefix_reversed ); - - for ( std::size_t i = 0; i <= count; i++ ) - suffix_[i] = count - prefix [count-1]; - - for ( std::size_t i = 0; i < count; i++ ) { - const std::size_t j = count - prefix_reversed[i]; - const difference_type k = i - prefix_reversed[i] + 1; - - if (suffix_[j] > k) - suffix_[j] = k; - } - } - } -/// \endcond - }; - - -/* Two ranges as inputs gives us four possibilities; with 2,3,3,4 parameters - Use a bit of TMP to disambiguate the 3-argument templates */ - -/// \fn boyer_moore_search ( corpusIter corpus_first, corpusIter corpus_last, -/// patIter pat_first, patIter pat_last ) -/// \brief Searches the corpus for the pattern. -/// -/// \param corpus_first The start of the data to search (Random Access Iterator) -/// \param corpus_last One past the end of the data to search -/// \param pat_first The start of the pattern to search for (Random Access Iterator) -/// \param pat_last One past the end of the data to search for -/// - template - corpusIter boyer_moore_search ( - corpusIter corpus_first, corpusIter corpus_last, - patIter pat_first, patIter pat_last ) - { - boyer_moore bm ( pat_first, pat_last ); - return bm ( corpus_first, corpus_last ); - } - - template - corpusIter boyer_moore_search ( - corpusIter corpus_first, corpusIter corpus_last, const PatternRange &pattern ) - { - typedef typename boost::range_iterator::type pattern_iterator; - boyer_moore bm ( boost::begin(pattern), boost::end (pattern)); - return bm ( corpus_first, corpus_last ); - } - - template - typename boost::lazy_disable_if_c< - boost::is_same::value, typename boost::range_iterator > - ::type - boyer_moore_search ( CorpusRange &corpus, patIter pat_first, patIter pat_last ) - { - boyer_moore bm ( pat_first, pat_last ); - return bm (boost::begin (corpus), boost::end (corpus)); - } - - template - typename boost::range_iterator::type - boyer_moore_search ( CorpusRange &corpus, const PatternRange &pattern ) - { - typedef typename boost::range_iterator::type pattern_iterator; - boyer_moore bm ( boost::begin(pattern), boost::end (pattern)); - return bm (boost::begin (corpus), boost::end (corpus)); - } - - - // Creator functions -- take a pattern range, return an object - template - boost::algorithm::boyer_moore::type> - make_boyer_moore ( const Range &r ) { - return boost::algorithm::boyer_moore - ::type> (boost::begin(r), boost::end(r)); - } - - template - boost::algorithm::boyer_moore::type> - make_boyer_moore ( Range &r ) { - return boost::algorithm::boyer_moore - ::type> (boost::begin(r), boost::end(r)); - } - -}} - -#endif // BOOST_ALGORITHM_BOYER_MOORE_SEARCH_HPP diff --git a/utils/boost_idb/boost/algorithm/searching/boyer_moore_horspool.hpp b/utils/boost_idb/boost/algorithm/searching/boyer_moore_horspool.hpp deleted file mode 100644 index 758ded20..00000000 --- a/utils/boost_idb/boost/algorithm/searching/boyer_moore_horspool.hpp +++ /dev/null @@ -1,199 +0,0 @@ -/* - Copyright (c) Marshall Clow 2010-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - For more information, see http://www.boost.org -*/ - -#ifndef BOOST_ALGORITHM_BOYER_MOORE_HORSPOOOL_SEARCH_HPP -#define BOOST_ALGORITHM_BOYER_MOORE_HORSPOOOL_SEARCH_HPP - -#include // for std::iterator_traits - -#include -#include - -#include -#include - -#include -#include - -#include -#include - -// #define BOOST_ALGORITHM_BOYER_MOORE_HORSPOOL_DEBUG_HPP - -namespace boost { namespace algorithm { - -/* - A templated version of the boyer-moore-horspool searching algorithm. - - Requirements: - * Random access iterators - * The two iterator types (patIter and corpusIter) must - "point to" the same underlying type. - * Additional requirements may be imposed buy the skip table, such as: - ** Numeric type (array-based skip table) - ** Hashable type (map-based skip table) - -http://www-igm.univ-mlv.fr/%7Elecroq/string/node18.html - -*/ - - template > - class boyer_moore_horspool { - typedef typename std::iterator_traits::difference_type difference_type; - public: - boyer_moore_horspool ( patIter first, patIter last ) - : pat_first ( first ), pat_last ( last ), - k_pattern_length ( std::distance ( pat_first, pat_last )), - skip_ ( k_pattern_length, k_pattern_length ) { - - // Build the skip table - std::size_t i = 0; - if ( first != last ) // empty pattern? - for ( patIter iter = first; iter != last-1; ++iter, ++i ) - skip_.insert ( *iter, k_pattern_length - 1 - i ); -#ifdef BOOST_ALGORITHM_BOYER_MOORE_HORSPOOL_DEBUG_HPP - skip_.PrintSkipTable (); -#endif - } - - ~boyer_moore_horspool () {} - - /// \fn operator ( corpusIter corpus_first, corpusIter corpus_last, Pred p ) - /// \brief Searches the corpus for the pattern that was passed into the constructor - /// - /// \param corpus_first The start of the data to search (Random Access Iterator) - /// \param corpus_last One past the end of the data to search - /// \param p A predicate used for the search comparisons. - /// - template - corpusIter operator () ( corpusIter corpus_first, corpusIter corpus_last ) const { - BOOST_STATIC_ASSERT (( boost::is_same< - typename std::iterator_traits::value_type, - typename std::iterator_traits::value_type>::value )); - - if ( corpus_first == corpus_last ) return corpus_last; // if nothing to search, we didn't find it! - if ( pat_first == pat_last ) return corpus_first; // empty pattern matches at start - - const difference_type k_corpus_length = std::distance ( corpus_first, corpus_last ); - // If the pattern is larger than the corpus, we can't find it! - if ( k_corpus_length < k_pattern_length ) - return corpus_last; - - // Do the search - return this->do_search ( corpus_first, corpus_last ); - } - - template - typename boost::range_iterator::type operator () ( Range &r ) const { - return (*this) (boost::begin(r), boost::end(r)); - } - - private: -/// \cond DOXYGEN_HIDE - patIter pat_first, pat_last; - const difference_type k_pattern_length; - typename traits::skip_table_t skip_; - - /// \fn do_search ( corpusIter corpus_first, corpusIter corpus_last ) - /// \brief Searches the corpus for the pattern that was passed into the constructor - /// - /// \param corpus_first The start of the data to search (Random Access Iterator) - /// \param corpus_last One past the end of the data to search - /// \param k_corpus_length The length of the corpus to search - /// - template - corpusIter do_search ( corpusIter corpus_first, corpusIter corpus_last ) const { - corpusIter curPos = corpus_first; - const corpusIter lastPos = corpus_last - k_pattern_length; - while ( curPos <= lastPos ) { - // Do we match right where we are? - std::size_t j = k_pattern_length - 1; - while ( pat_first [j] == curPos [j] ) { - // We matched - we're done! - if ( j == 0 ) - return curPos; - j--; - } - - curPos += skip_ [ curPos [ k_pattern_length - 1 ]]; - } - - return corpus_last; - } -// \endcond - }; - -/* Two ranges as inputs gives us four possibilities; with 2,3,3,4 parameters - Use a bit of TMP to disambiguate the 3-argument templates */ - -/// \fn boyer_moore_horspool_search ( corpusIter corpus_first, corpusIter corpus_last, -/// patIter pat_first, patIter pat_last ) -/// \brief Searches the corpus for the pattern. -/// -/// \param corpus_first The start of the data to search (Random Access Iterator) -/// \param corpus_last One past the end of the data to search -/// \param pat_first The start of the pattern to search for (Random Access Iterator) -/// \param pat_last One past the end of the data to search for -/// - template - corpusIter boyer_moore_horspool_search ( - corpusIter corpus_first, corpusIter corpus_last, - patIter pat_first, patIter pat_last ) - { - boyer_moore_horspool bmh ( pat_first, pat_last ); - return bmh ( corpus_first, corpus_last ); - } - - template - corpusIter boyer_moore_horspool_search ( - corpusIter corpus_first, corpusIter corpus_last, const PatternRange &pattern ) - { - typedef typename boost::range_iterator::type pattern_iterator; - boyer_moore_horspool bmh ( boost::begin(pattern), boost::end (pattern)); - return bmh ( corpus_first, corpus_last ); - } - - template - typename boost::lazy_disable_if_c< - boost::is_same::value, typename boost::range_iterator > - ::type - boyer_moore_horspool_search ( CorpusRange &corpus, patIter pat_first, patIter pat_last ) - { - boyer_moore_horspool bmh ( pat_first, pat_last ); - return bm (boost::begin (corpus), boost::end (corpus)); - } - - template - typename boost::range_iterator::type - boyer_moore_horspool_search ( CorpusRange &corpus, const PatternRange &pattern ) - { - typedef typename boost::range_iterator::type pattern_iterator; - boyer_moore_horspool bmh ( boost::begin(pattern), boost::end (pattern)); - return bmh (boost::begin (corpus), boost::end (corpus)); - } - - - // Creator functions -- take a pattern range, return an object - template - boost::algorithm::boyer_moore_horspool::type> - make_boyer_moore_horspool ( const Range &r ) { - return boost::algorithm::boyer_moore_horspool - ::type> (boost::begin(r), boost::end(r)); - } - - template - boost::algorithm::boyer_moore_horspool::type> - make_boyer_moore_horspool ( Range &r ) { - return boost::algorithm::boyer_moore_horspool - ::type> (boost::begin(r), boost::end(r)); - } - -}} - -#endif // BOOST_ALGORITHM_BOYER_MOORE_HORSPOOOL_SEARCH_HPP diff --git a/utils/boost_idb/boost/algorithm/searching/detail/bm_traits.hpp b/utils/boost_idb/boost/algorithm/searching/detail/bm_traits.hpp deleted file mode 100644 index ea150c30..00000000 --- a/utils/boost_idb/boost/algorithm/searching/detail/bm_traits.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - Copyright (c) Marshall Clow 2010-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - For more information, see http://www.boost.org -*/ - -#ifndef BOOST_ALGORITHM_SEARCH_DETAIL_BM_TRAITS_HPP -#define BOOST_ALGORITHM_SEARCH_DETAIL_BM_TRAITS_HPP - -#include // for CHAR_BIT -#include -#include // for std::iterator_traits - -#include -#include -#include -#include - -#include -#include - -#include - -namespace boost { namespace algorithm { namespace detail { - -// -// Default implementations of the skip tables for B-M and B-M-H -// - template class skip_table; - -// General case for data searching other than bytes; use a map - template - class skip_table { - private: - typedef std::tr1::unordered_map skip_map; - const value_type k_default_value; - skip_map skip_; - - public: - skip_table ( std::size_t patSize, value_type default_value ) - : k_default_value ( default_value ), skip_ ( patSize ) {} - - void insert ( key_type key, value_type val ) { - skip_ [ key ] = val; // Would skip_.insert (val) be better here? - } - - value_type operator [] ( key_type key ) const { - typename skip_map::const_iterator it = skip_.find ( key ); - return it == skip_.end () ? k_default_value : it->second; - } - - void PrintSkipTable () const { - std::cout << "BM(H) Skip Table :" << std::endl; - for ( typename skip_map::const_iterator it = skip_.begin (); it != skip_.end (); ++it ) - if ( it->second != k_default_value ) - std::cout << " " << it->first << ": " << it->second << std::endl; - std::cout << std::endl; - } - }; - - -// Special case small numeric values; use an array - template - class skip_table { - private: - typedef typename boost::make_unsigned::type unsigned_key_type; - typedef boost::array skip_map; - skip_map skip_; - const value_type k_default_value; - public: - skip_table ( std::size_t patSize, value_type default_value ) : k_default_value ( default_value ) { - std::fill_n ( skip_.begin(), skip_.size(), default_value ); - } - - void insert ( key_type key, value_type val ) { - skip_ [ static_cast ( key ) ] = val; - } - - value_type operator [] ( key_type key ) const { - return skip_ [ static_cast ( key ) ]; - } - - void PrintSkipTable () const { - std::cout << "BM(H) Skip Table :" << std::endl; - for ( typename skip_map::const_iterator it = skip_.begin (); it != skip_.end (); ++it ) - if ( *it != k_default_value ) - std::cout << " " << std::distance (skip_.begin (), it) << ": " << *it << std::endl; - std::cout << std::endl; - } - }; - - template - struct BM_traits { - typedef typename std::iterator_traits::difference_type value_type; - typedef typename std::iterator_traits::value_type key_type; - typedef boost::algorithm::detail::skip_table::value && (sizeof(key_type)==1)> skip_table_t; - }; - -}}} // namespaces - -#endif // BOOST_ALGORITHM_SEARCH_DETAIL_BM_TRAITS_HPP diff --git a/utils/boost_idb/boost/algorithm/searching/detail/debugging.hpp b/utils/boost_idb/boost/algorithm/searching/detail/debugging.hpp deleted file mode 100644 index 3996e0f5..00000000 --- a/utils/boost_idb/boost/algorithm/searching/detail/debugging.hpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (c) Marshall Clow 2010-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - For more information, see http://www.boost.org -*/ - -#ifndef BOOST_ALGORITHM_SEARCH_DETAIL_DEBUG_HPP -#define BOOST_ALGORITHM_SEARCH_DETAIL_DEBUG_HPP - -#include -/// \cond DOXYGEN_HIDE - -namespace boost { namespace algorithm { namespace detail { - -// Debugging support - template - void PrintTable ( Iter first, Iter last ) { - std::cout << std::distance ( first, last ) << ": { "; - for ( Iter iter = first; iter != last; ++iter ) - std::cout << *iter << " "; - std::cout << "}" << std::endl; - } - -}}} -/// \endcond - -#endif // BOOST_ALGORITHM_SEARCH_DETAIL_DEBUG_HPP diff --git a/utils/boost_idb/boost/algorithm/searching/knuth_morris_pratt.hpp b/utils/boost_idb/boost/algorithm/searching/knuth_morris_pratt.hpp deleted file mode 100644 index aaeeb51c..00000000 --- a/utils/boost_idb/boost/algorithm/searching/knuth_morris_pratt.hpp +++ /dev/null @@ -1,258 +0,0 @@ -/* - Copyright (c) Marshall Clow 2010-2012. - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - For more information, see http://www.boost.org -*/ - -#ifndef BOOST_ALGORITHM_KNUTH_MORRIS_PRATT_SEARCH_HPP -#define BOOST_ALGORITHM_KNUTH_MORRIS_PRATT_SEARCH_HPP - -#include -#include // for std::iterator_traits - -#include -#include - -#include -#include - -#include -#include - -#include - -// #define BOOST_ALGORITHM_KNUTH_MORRIS_PRATT_DEBUG - -namespace boost { namespace algorithm { - -// #define NEW_KMP - -/* - A templated version of the Knuth-Morris-Pratt searching algorithm. - - Requirements: - * Random-access iterators - * The two iterator types (I1 and I2) must "point to" the same underlying type. - - http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm - http://www.inf.fh-flensburg.de/lang/algorithmen/pattern/kmpen.htm -*/ - - template - class knuth_morris_pratt { - typedef typename std::iterator_traits::difference_type difference_type; - public: - knuth_morris_pratt ( patIter first, patIter last ) - : pat_first ( first ), pat_last ( last ), - k_pattern_length ( std::distance ( pat_first, pat_last )), - skip_ ( k_pattern_length + 1 ) { -#ifdef NEW_KMP - preKmp ( pat_first, pat_last ); -#else - init_skip_table ( pat_first, pat_last ); -#endif -#ifdef BOOST_ALGORITHM_KNUTH_MORRIS_PRATT_DEBUG - detail::PrintTable ( skip_.begin (), skip_.end ()); -#endif - } - - ~knuth_morris_pratt () {} - - /// \fn operator ( corpusIter corpus_first, corpusIter corpus_last, Pred p ) - /// \brief Searches the corpus for the pattern that was passed into the constructor - /// - /// \param corpus_first The start of the data to search (Random Access Iterator) - /// \param corpus_last One past the end of the data to search - /// \param p A predicate used for the search comparisons. - /// - template - corpusIter operator () ( corpusIter corpus_first, corpusIter corpus_last ) const { - BOOST_STATIC_ASSERT (( boost::is_same< - typename std::iterator_traits::value_type, - typename std::iterator_traits::value_type>::value )); - if ( corpus_first == corpus_last ) return corpus_last; // if nothing to search, we didn't find it! - if ( pat_first == pat_last ) return corpus_first; // empty pattern matches at start - - const difference_type k_corpus_length = std::distance ( corpus_first, corpus_last ); - // If the pattern is larger than the corpus, we can't find it! - if ( k_corpus_length < k_pattern_length ) - return corpus_last; - - return do_search ( corpus_first, corpus_last, k_corpus_length ); - } - - template - typename boost::range_iterator::type operator () ( Range &r ) const { - return (*this) (boost::begin(r), boost::end(r)); - } - - private: -/// \cond DOXYGEN_HIDE - patIter pat_first, pat_last; - const difference_type k_pattern_length; - std::vector skip_; - - /// \fn operator ( corpusIter corpus_first, corpusIter corpus_last, Pred p ) - /// \brief Searches the corpus for the pattern that was passed into the constructor - /// - /// \param corpus_first The start of the data to search (Random Access Iterator) - /// \param corpus_last One past the end of the data to search - /// \param p A predicate used for the search comparisons. - /// - template - corpusIter do_search ( corpusIter corpus_first, corpusIter corpus_last, - difference_type k_corpus_length ) const { - difference_type match_start = 0; // position in the corpus that we're matching - -#ifdef NEW_KMP - int patternIdx = 0; - while ( match_start < k_corpus_length ) { - while ( patternIdx > -1 && pat_first[patternIdx] != corpus_first [match_start] ) - patternIdx = skip_ [patternIdx]; //<--- Shifting the pattern on mismatch - - patternIdx++; - match_start++; //<--- corpus is always increased by 1 - - if ( patternIdx >= (int) k_pattern_length ) - return corpus_first + match_start - patternIdx; - } - -#else -// At this point, we know: -// k_pattern_length <= k_corpus_length -// for all elements of skip, it holds -1 .. k_pattern_length -// -// In the loop, we have the following invariants -// idx is in the range 0 .. k_pattern_length -// match_start is in the range 0 .. k_corpus_length - k_pattern_length + 1 - - const difference_type last_match = k_corpus_length - k_pattern_length; - difference_type idx = 0; // position in the pattern we're comparing - - while ( match_start <= last_match ) { - while ( pat_first [ idx ] == corpus_first [ match_start + idx ] ) { - if ( ++idx == k_pattern_length ) - return corpus_first + match_start; - } - // Figure out where to start searching again - // assert ( idx - skip_ [ idx ] > 0 ); // we're always moving forward - match_start += idx - skip_ [ idx ]; - idx = skip_ [ idx ] >= 0 ? skip_ [ idx ] : 0; - // assert ( idx >= 0 && idx < k_pattern_length ); - } -#endif - - // We didn't find anything - return corpus_last; - } - - - void preKmp ( patIter first, patIter last ) { - const /*std::size_t*/ int count = std::distance ( first, last ); - - int i, j; - - i = 0; - j = skip_[0] = -1; - while (i < count) { - while (j > -1 && first[i] != first[j]) - j = skip_[j]; - i++; - j++; - if (first[i] == first[j]) - skip_[i] = skip_[j]; - else - skip_[i] = j; - } - } - - - void init_skip_table ( patIter first, patIter last ) { - const difference_type count = std::distance ( first, last ); - - int j; - skip_ [ 0 ] = -1; - for ( int i = 1; i <= count; ++i ) { - j = skip_ [ i - 1 ]; - while ( j >= 0 ) { - if ( first [ j ] == first [ i - 1 ] ) - break; - j = skip_ [ j ]; - } - skip_ [ i ] = j + 1; - } - } -// \endcond - }; - - -/* Two ranges as inputs gives us four possibilities; with 2,3,3,4 parameters - Use a bit of TMP to disambiguate the 3-argument templates */ - -/// \fn knuth_morris_pratt_search ( corpusIter corpus_first, corpusIter corpus_last, -/// patIter pat_first, patIter pat_last ) -/// \brief Searches the corpus for the pattern. -/// -/// \param corpus_first The start of the data to search (Random Access Iterator) -/// \param corpus_last One past the end of the data to search -/// \param pat_first The start of the pattern to search for (Random Access Iterator) -/// \param pat_last One past the end of the data to search for -/// - template - corpusIter knuth_morris_pratt_search ( - corpusIter corpus_first, corpusIter corpus_last, - patIter pat_first, patIter pat_last ) - { - knuth_morris_pratt kmp ( pat_first, pat_last ); - return kmp ( corpus_first, corpus_last ); - } - - template - corpusIter knuth_morris_pratt_search ( - corpusIter corpus_first, corpusIter corpus_last, const PatternRange &pattern ) - { - typedef typename boost::range_iterator::type pattern_iterator; - knuth_morris_pratt kmp ( boost::begin(pattern), boost::end (pattern)); - return kmp ( corpus_first, corpus_last ); - } - - template - typename boost::lazy_disable_if_c< - boost::is_same::value, typename boost::range_iterator > - ::type - knuth_morris_pratt_search ( CorpusRange &corpus, patIter pat_first, patIter pat_last ) - { - knuth_morris_pratt kmp ( pat_first, pat_last ); - return kmp (boost::begin (corpus), boost::end (corpus)); - } - - template - typename boost::range_iterator::type - knuth_morris_pratt_search ( CorpusRange &corpus, const PatternRange &pattern ) - { - typedef typename boost::range_iterator::type pattern_iterator; - knuth_morris_pratt kmp ( boost::begin(pattern), boost::end (pattern)); - return kmp (boost::begin (corpus), boost::end (corpus)); - } - - - // Creator functions -- take a pattern range, return an object - template - boost::algorithm::knuth_morris_pratt::type> - make_knuth_morris_pratt ( const Range &r ) { - return boost::algorithm::knuth_morris_pratt - ::type> (boost::begin(r), boost::end(r)); - } - - template - boost::algorithm::knuth_morris_pratt::type> - make_knuth_morris_pratt ( Range &r ) { - return boost::algorithm::knuth_morris_pratt - ::type> (boost::begin(r), boost::end(r)); - } -}} - -#endif // BOOST_ALGORITHM_KNUTH_MORRIS_PRATT_SEARCH_HPP diff --git a/utils/boost_idb/boost/algorithm/string/concept.hpp b/utils/boost_idb/boost/algorithm/string/concept.hpp index 17e83495..9876e98d 100644 --- a/utils/boost_idb/boost/algorithm/string/concept.hpp +++ b/utils/boost_idb/boost/algorithm/string/concept.hpp @@ -12,7 +12,7 @@ #define BOOST_STRING_CONCEPT_HPP #include -#include +#include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/detail/case_conv.hpp b/utils/boost_idb/boost/algorithm/string/detail/case_conv.hpp index 42621c74..5b0064fd 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/case_conv.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/case_conv.hpp @@ -15,8 +15,6 @@ #include #include -#include - namespace boost { namespace algorithm { namespace detail { @@ -39,7 +37,7 @@ namespace boost { CharT operator ()( CharT Ch ) const { #if defined(__BORLANDC__) && (__BORLANDC__ >= 0x560) && (__BORLANDC__ <= 0x564) && !defined(_USE_OLD_RW_STL) - return std::tolower( static_cast::type> ( Ch )); + return std::tolower( Ch); #else return std::tolower( Ch, *m_Loc ); #endif @@ -59,7 +57,7 @@ namespace boost { CharT operator ()( CharT Ch ) const { #if defined(__BORLANDC__) && (__BORLANDC__ >= 0x560) && (__BORLANDC__ <= 0x564) && !defined(_USE_OLD_RW_STL) - return std::toupper( static_cast::type> ( Ch )); + return std::toupper( Ch); #else return std::toupper( Ch, *m_Loc ); #endif diff --git a/utils/boost_idb/boost/algorithm/string/detail/classification.hpp b/utils/boost_idb/boost/algorithm/string/detail/classification.hpp index 704d9d20..fb439557 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/classification.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/classification.hpp @@ -126,7 +126,7 @@ namespace boost { } // Use fixed storage - ::std::memcpy(DestStorage, SrcStorage, sizeof(set_value_type)*m_Size); + ::memcpy(DestStorage, SrcStorage, sizeof(set_value_type)*m_Size); } // Destructor @@ -206,7 +206,7 @@ namespace boost { } // Copy the data - ::std::memcpy(DestStorage, SrcStorage, sizeof(set_value_type)*m_Size); + ::memcpy(DestStorage, SrcStorage, sizeof(set_value_type)*m_Size); return *this; } diff --git a/utils/boost_idb/boost/algorithm/string/detail/find_format.hpp b/utils/boost_idb/boost/algorithm/string/detail/find_format.hpp index b3987502..7f5f780b 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/find_format.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/find_format.hpp @@ -12,7 +12,7 @@ #define BOOST_STRING_FIND_FORMAT_DETAIL_HPP #include -#include +#include #include #include #include @@ -56,7 +56,7 @@ namespace boost { // Copy the beginning of the sequence Output = std::copy( ::boost::begin(Input), ::boost::begin(M), Output ); // Format find result - // Copy formatted result + // Copy formated result Output = std::copy( ::boost::begin(M.format_result()), ::boost::end(M.format_result()), Output ); // Copy the rest of the sequence Output = std::copy( M.end(), ::boost::end(Input), Output ); @@ -74,17 +74,17 @@ namespace boost { const InputT& Input, FormatterT Formatter, const FindResultT& FindResult ) - { + { if( ::boost::algorithm::detail::check_find_result(Input, FindResult) ) { - return ::boost::algorithm::detail::find_format_copy_impl2( - Output, - Input, - Formatter, - FindResult, - Formatter(FindResult) ); + return ::boost::algorithm::detail::find_format_copy_impl2( + Output, + Input, + Formatter, + FindResult, + Formatter(FindResult) ); } else { return std::copy( ::boost::begin(Input), ::boost::end(Input), Output ); - } + } } @@ -118,11 +118,11 @@ namespace boost { InputT Output; // Copy the beginning of the sequence - boost::algorithm::detail::insert( Output, ::boost::end(Output), ::boost::begin(Input), M.begin() ); - // Copy formatted result - boost::algorithm::detail::insert( Output, ::boost::end(Output), M.format_result() ); + insert( Output, ::boost::end(Output), ::boost::begin(Input), M.begin() ); + // Copy formated result + insert( Output, ::boost::end(Output), M.format_result() ); // Copy the rest of the sequence - boost::algorithm::detail::insert( Output, ::boost::end(Output), M.end(), ::boost::end(Input) ); + insert( Output, ::boost::end(Output), M.end(), ::boost::end(Input) ); return Output; } @@ -137,14 +137,14 @@ namespace boost { const FindResultT& FindResult) { if( ::boost::algorithm::detail::check_find_result(Input, FindResult) ) { - return ::boost::algorithm::detail::find_format_copy_impl2( - Input, - Formatter, - FindResult, - Formatter(FindResult) ); + return ::boost::algorithm::detail::find_format_copy_impl2( + Input, + Formatter, + FindResult, + Formatter(FindResult) ); } else { return Input; - } + } } // replace implementation ----------------------------------------------------// @@ -189,12 +189,12 @@ namespace boost { const FindResultT& FindResult) { if( ::boost::algorithm::detail::check_find_result(Input, FindResult) ) { - ::boost::algorithm::detail::find_format_impl2( - Input, - Formatter, - FindResult, - Formatter(FindResult) ); - } + ::boost::algorithm::detail::find_format_impl2( + Input, + Formatter, + FindResult, + Formatter(FindResult) ); + } } } // namespace detail diff --git a/utils/boost_idb/boost/algorithm/string/detail/find_format_all.hpp b/utils/boost_idb/boost/algorithm/string/detail/find_format_all.hpp index 52930c83..0f184a31 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/find_format_all.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/find_format_all.hpp @@ -12,7 +12,7 @@ #define BOOST_STRING_FIND_FORMAT_ALL_DETAIL_HPP #include -#include +#include #include #include #include @@ -58,7 +58,7 @@ namespace boost { { // Copy the beginning of the sequence Output = std::copy( LastMatch, M.begin(), Output ); - // Copy formatted result + // Copy formated result Output = std::copy( ::boost::begin(M.format_result()), ::boost::end(M.format_result()), Output ); // Proceed to the next match @@ -84,18 +84,18 @@ namespace boost { FinderT Finder, FormatterT Formatter, const FindResultT& FindResult ) - { + { if( ::boost::algorithm::detail::check_find_result(Input, FindResult) ) { - return ::boost::algorithm::detail::find_format_all_copy_impl2( - Output, - Input, - Finder, - Formatter, - FindResult, - Formatter(FindResult) ); + return ::boost::algorithm::detail::find_format_all_copy_impl2( + Output, + Input, + Finder, + Formatter, + FindResult, + Formatter(FindResult) ); } else { return std::copy( ::boost::begin(Input), ::boost::end(Input), Output ); - } + } } // find_format_all_copy implementation ----------------------------------------------// @@ -134,9 +134,9 @@ namespace boost { while( M ) { // Copy the beginning of the sequence - boost::algorithm::detail::insert( Output, ::boost::end(Output), LastMatch, M.begin() ); - // Copy formatted result - boost::algorithm::detail::insert( Output, ::boost::end(Output), M.format_result() ); + insert( Output, ::boost::end(Output), LastMatch, M.begin() ); + // Copy formated result + insert( Output, ::boost::end(Output), M.format_result() ); // Proceed to the next match LastMatch=M.end(); @@ -161,15 +161,15 @@ namespace boost { const FindResultT& FindResult) { if( ::boost::algorithm::detail::check_find_result(Input, FindResult) ) { - return ::boost::algorithm::detail::find_format_all_copy_impl2( - Input, - Finder, - Formatter, - FindResult, - Formatter(FindResult) ); + return ::boost::algorithm::detail::find_format_all_copy_impl2( + Input, + Finder, + Formatter, + FindResult, + Formatter(FindResult) ); } else { return Input; - } + } } // find_format_all implementation ------------------------------------------------// @@ -218,7 +218,7 @@ namespace boost { // Adjust search iterator SearchIt=M.end(); - // Copy formatted replace to the storage + // Copy formated replace to the storage ::boost::algorithm::detail::copy_to_storage( Storage, M.format_result() ); // Find range for a next match @@ -257,13 +257,13 @@ namespace boost { FindResultT FindResult) { if( ::boost::algorithm::detail::check_find_result(Input, FindResult) ) { - ::boost::algorithm::detail::find_format_all_impl2( - Input, - Finder, - Formatter, - FindResult, - Formatter(FindResult) ); - } + ::boost::algorithm::detail::find_format_all_impl2( + Input, + Finder, + Formatter, + FindResult, + Formatter(FindResult) ); + } } } // namespace detail diff --git a/utils/boost_idb/boost/algorithm/string/detail/find_format_store.hpp b/utils/boost_idb/boost/algorithm/string/detail/find_format_store.hpp index b9f4a88d..4872c5a9 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/find_format_store.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/find_format_store.hpp @@ -12,7 +12,7 @@ #define BOOST_STRING_FIND_FORMAT_STORE_DETAIL_HPP #include -#include +#include namespace boost { namespace algorithm { @@ -53,7 +53,7 @@ namespace boost { { iterator_range::operator=(FindResult); if( !this->empty() ) { - m_FormatResult=m_Formatter(FindResult); + m_FormatResult=m_Formatter(FindResult); } return *this; diff --git a/utils/boost_idb/boost/algorithm/string/detail/find_iterator.hpp b/utils/boost_idb/boost/algorithm/string/detail/find_iterator.hpp index 9b78a0f7..c76993a1 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/find_iterator.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/find_iterator.hpp @@ -12,7 +12,7 @@ #define BOOST_STRING_FIND_ITERATOR_DETAIL_HPP #include -#include +#include #include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/detail/finder.hpp b/utils/boost_idb/boost/algorithm/string/detail/finder.hpp index 209ce0b2..45bcb7d3 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/finder.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/finder.hpp @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include #include @@ -92,7 +92,7 @@ namespace boost { // find last functor -----------------------------------------------// - // find the last match a subsequence in the sequence ( functor ) + // find the last match a subseqeunce in the sequence ( functor ) /* Returns a pair marking the subsequence in the sequence. If the find fails, returns @@ -142,6 +142,7 @@ namespace boost { ForwardIteratorT End, std::forward_iterator_tag ) const { + typedef ForwardIteratorT input_iterator_type; typedef iterator_range result_type; first_finder_type first_finder( @@ -262,6 +263,7 @@ namespace boost { ForwardIteratorT End, unsigned int N) const { + typedef ForwardIteratorT input_iterator_type; typedef iterator_range result_type; // Sanity check @@ -296,6 +298,7 @@ namespace boost { ForwardIteratorT End, unsigned int N) const { + typedef ForwardIteratorT input_iterator_type; typedef iterator_range result_type; // Sanity check @@ -359,6 +362,7 @@ namespace boost { unsigned int N, std::random_access_iterator_tag ) { + typedef ForwardIteratorT input_iterator_type; typedef iterator_range result_type; if ( (End<=Begin) || ( static_cast(End-Begin) < N ) ) @@ -432,6 +436,7 @@ namespace boost { unsigned int N, std::random_access_iterator_tag ) { + typedef ForwardIteratorT input_iterator_type; typedef iterator_range result_type; if ( (End<=Begin) || ( static_cast(End-Begin) < N ) ) diff --git a/utils/boost_idb/boost/algorithm/string/detail/finder_regex.hpp b/utils/boost_idb/boost/algorithm/string/detail/finder_regex.hpp index 9cb01cfa..673d93a5 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/finder_regex.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/finder_regex.hpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include #include @@ -60,14 +60,14 @@ namespace boost { return *this; } - // Match result retrieval + // Match result retrival const match_results_type& match_results() const { return m_MatchResults; } private: - // Saved match result + // Saved matchresult match_results_type m_MatchResults; }; diff --git a/utils/boost_idb/boost/algorithm/string/detail/formatter.hpp b/utils/boost_idb/boost/algorithm/string/detail/formatter.hpp index c071822f..bd6a7802 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/formatter.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/formatter.hpp @@ -12,7 +12,7 @@ #define BOOST_STRING_FORMATTER_DETAIL_HPP -#include +#include #include #include #include @@ -87,31 +87,6 @@ namespace boost { } }; -// dissect format functor ----------------------------------------------------// - - // dissect format functor - template - struct dissect_formatF - { - public: - // Construction - dissect_formatF(FinderT Finder) : - m_Finder(Finder) {} - - // Operation - template - inline iterator_range< - BOOST_STRING_TYPENAME range_const_iterator::type> - operator()(const RangeT& Replace) const - { - return m_Finder(::boost::begin(Replace), ::boost::end(Replace)); - } - - private: - FinderT m_Finder; - }; - - } // namespace detail } // namespace algorithm } // namespace boost diff --git a/utils/boost_idb/boost/algorithm/string/detail/util.hpp b/utils/boost_idb/boost/algorithm/string/detail/util.hpp index cf4a8b1c..7e8471f7 100644 --- a/utils/boost_idb/boost/algorithm/string/detail/util.hpp +++ b/utils/boost_idb/boost/algorithm/string/detail/util.hpp @@ -13,7 +13,7 @@ #include #include -#include +#include namespace boost { namespace algorithm { diff --git a/utils/boost_idb/boost/algorithm/string/erase.hpp b/utils/boost_idb/boost/algorithm/string/erase.hpp index 68837909..e738b86f 100644 --- a/utils/boost_idb/boost/algorithm/string/erase.hpp +++ b/utils/boost_idb/boost/algorithm/string/erase.hpp @@ -13,7 +13,7 @@ #include -#include +#include #include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/find.hpp b/utils/boost_idb/boost/algorithm/string/find.hpp index f2c2926b..304646d0 100644 --- a/utils/boost_idb/boost/algorithm/string/find.hpp +++ b/utils/boost_idb/boost/algorithm/string/find.hpp @@ -13,7 +13,7 @@ #include -#include +#include #include #include #include @@ -86,7 +86,7 @@ namespace boost { //! Find first algorithm ( case insensitive ) /*! - Search for the first occurrence of the substring in the input. + Search for the first occurence of the substring in the input. Searching is case insensitive. \param Input A string which will be searched. @@ -228,13 +228,13 @@ namespace boost { //! Find head algorithm /*! Get the head of the input. Head is a prefix of the string of the - given size. If the input is shorter then required, whole input is considered + given size. If the input is shorter then required, whole input if considered to be the head. \param Input An input string \param N Length of the head For N>=0, at most N characters are extracted. - For N<0, at most size(Input)-|N| characters are extracted. + For N<0, size(Input)-|N| characters are extracted. \return An \c iterator_range delimiting the match. Returned iterator is either \c Range1T::iterator or @@ -258,13 +258,13 @@ namespace boost { //! Find tail algorithm /*! Get the tail of the input. Tail is a suffix of the string of the - given size. If the input is shorter then required, whole input is considered + given size. If the input is shorter then required, whole input if considered to be the tail. \param Input An input string \param N Length of the tail. For N>=0, at most N characters are extracted. - For N<0, at most size(Input)-|N| characters are extracted. + For N<0, size(Input)-|N| characters are extracted. \return An \c iterator_range delimiting the match. Returned iterator is either \c RangeT::iterator or @@ -293,7 +293,7 @@ namespace boost { If the "token compress mode" is enabled, adjacent tokens are considered to be one match. \param Input A input string. - \param Pred A unary predicate to identify a token + \param Pred An unary predicate to identify a token \param eCompress Enable/Disable compressing of adjacent tokens \return An \c iterator_range delimiting the match. diff --git a/utils/boost_idb/boost/algorithm/string/find_format.hpp b/utils/boost_idb/boost/algorithm/string/find_format.hpp index 0e84a4ee..ef037391 100644 --- a/utils/boost_idb/boost/algorithm/string/find_format.hpp +++ b/utils/boost_idb/boost/algorithm/string/find_format.hpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/find_iterator.hpp b/utils/boost_idb/boost/algorithm/string/find_iterator.hpp index 1502c7d9..72696c74 100644 --- a/utils/boost_idb/boost/algorithm/string/find_iterator.hpp +++ b/utils/boost_idb/boost/algorithm/string/find_iterator.hpp @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include #include @@ -259,11 +259,7 @@ namespace boost { m_End(End), m_bEof(false) { - // force the correct behavior for empty sequences and yield at least one token - if(Begin!=End) - { - increment(); - } + increment(); } //! Constructor /*! @@ -282,11 +278,7 @@ namespace boost { m_Next=::boost::begin(lit_col); m_End=::boost::end(lit_col); - // force the correct behavior for empty sequences and yield at least one token - if(m_Next!=m_End) - { - increment(); - } + increment(); } diff --git a/utils/boost_idb/boost/algorithm/string/finder.hpp b/utils/boost_idb/boost/algorithm/string/finder.hpp index 93f7ec30..4c7ac38b 100644 --- a/utils/boost_idb/boost/algorithm/string/finder.hpp +++ b/utils/boost_idb/boost/algorithm/string/finder.hpp @@ -13,7 +13,7 @@ #include -#include +#include #include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/formatter.hpp b/utils/boost_idb/boost/algorithm/string/formatter.hpp index de8681bc..50006df1 100644 --- a/utils/boost_idb/boost/algorithm/string/formatter.hpp +++ b/utils/boost_idb/boost/algorithm/string/formatter.hpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include @@ -36,10 +36,10 @@ namespace boost { //! Constant formatter /*! - Constructs a \c const_formatter. Const formatter always returns + Construct the \c const_formatter. Const formatter always returns the same value, regardless of the parameter. - \param Format A predefined value used as a result for formatting + \param Format A predefined value used as a result for formating \return An instance of the \c const_formatter object. */ template @@ -55,7 +55,7 @@ namespace boost { //! Identity formatter /*! - Constructs an \c identity_formatter. Identity formatter always returns + Construct the \c identity_formatter. Identity formatter always returns the parameter. \return An instance of the \c identity_formatter object. @@ -73,7 +73,7 @@ namespace boost { //! Empty formatter /*! - Constructs an \c empty_formatter. Empty formatter always returns an empty + Construct the \c empty_formatter. Empty formatter always returns an empty sequence. \param Input container used to select a correct value_type for the @@ -89,22 +89,6 @@ namespace boost { BOOST_STRING_TYPENAME range_value::type>(); } - //! Empty formatter - /*! - Constructs a \c dissect_formatter. Dissect formatter uses a specified finder - to extract a portion of the formatted sequence. The first finder's match is returned - as a result - - \param Finder a finder used to select a portion of the formatted sequence - \return An instance of the \c dissect_formatter object. - */ - template - inline detail::dissect_formatF< FinderT > - dissect_formatter(const FinderT& Finder) - { - return detail::dissect_formatF(Finder); - } - } // namespace algorithm @@ -112,7 +96,6 @@ namespace boost { using algorithm::const_formatter; using algorithm::identity_formatter; using algorithm::empty_formatter; - using algorithm::dissect_formatter; } // namespace boost diff --git a/utils/boost_idb/boost/algorithm/string/iter_find.hpp b/utils/boost_idb/boost/algorithm/string/iter_find.hpp index 10424abc..9e0245f1 100644 --- a/utils/boost_idb/boost/algorithm/string/iter_find.hpp +++ b/utils/boost_idb/boost/algorithm/string/iter_find.hpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include #include @@ -60,7 +60,7 @@ namespace boost { a match). \param Input A container which will be searched. \param Finder A Finder object used for searching - \return A reference to the result + \return A reference the result \note Prior content of the result will be overwritten. */ @@ -122,7 +122,7 @@ namespace boost { Each match is used as a separator of segments. These segments are then returned in the result. - \param Result A 'container container' to contain the result of search. + \param Result A 'container container' to container the result of search. Both outer and inner container must have constructor taking a pair of iterators as an argument. Typical type of the result is @@ -131,7 +131,7 @@ namespace boost { a match). \param Input A container which will be searched. \param Finder A finder object used for searching - \return A reference to the result + \return A reference the result \note Prior content of the result will be overwritten. */ diff --git a/utils/boost_idb/boost/algorithm/string/predicate.hpp b/utils/boost_idb/boost/algorithm/string/predicate.hpp index 0879829b..6642f427 100644 --- a/utils/boost_idb/boost/algorithm/string/predicate.hpp +++ b/utils/boost_idb/boost/algorithm/string/predicate.hpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/predicate_facade.hpp b/utils/boost_idb/boost/algorithm/string/predicate_facade.hpp index a9753fc2..c8319f7e 100644 --- a/utils/boost_idb/boost/algorithm/string/predicate_facade.hpp +++ b/utils/boost_idb/boost/algorithm/string/predicate_facade.hpp @@ -15,7 +15,7 @@ /* \file boost/algorith/string/predicate_facade.hpp - This file contains predicate_facade definition. This template class is used + This file containes predicate_facade definition. This template class is used to identify classification predicates, so they can be combined using composition operators. */ diff --git a/utils/boost_idb/boost/algorithm/string/regex.hpp b/utils/boost_idb/boost/algorithm/string/regex.hpp index a6c7c60a..0a4c38bd 100644 --- a/utils/boost_idb/boost/algorithm/string/regex.hpp +++ b/utils/boost_idb/boost/algorithm/string/regex.hpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/regex_find_format.hpp b/utils/boost_idb/boost/algorithm/string/regex_find_format.hpp index 409afc2b..f698004a 100644 --- a/utils/boost_idb/boost/algorithm/string/regex_find_format.hpp +++ b/utils/boost_idb/boost/algorithm/string/regex_find_format.hpp @@ -32,7 +32,7 @@ namespace boost { Construct the \c regex_finder. Finder uses the regex engine to search for a match. Result is given in \c regex_search_result. This is an extension - of the iterator_range. In addition it contains match results + of the iterator_range. In addition it containes match results from the \c regex_search algorithm. \param Rx A regular expression diff --git a/utils/boost_idb/boost/algorithm/string/replace.hpp b/utils/boost_idb/boost/algorithm/string/replace.hpp index 0c04e47e..f2d201f9 100644 --- a/utils/boost_idb/boost/algorithm/string/replace.hpp +++ b/utils/boost_idb/boost/algorithm/string/replace.hpp @@ -13,7 +13,7 @@ #include -#include +#include #include #include #include diff --git a/utils/boost_idb/boost/algorithm/string/trim.hpp b/utils/boost_idb/boost/algorithm/string/trim.hpp index e740d57d..eb408a35 100644 --- a/utils/boost_idb/boost/algorithm/string/trim.hpp +++ b/utils/boost_idb/boost/algorithm/string/trim.hpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include @@ -50,7 +50,7 @@ namespace boost { \param Output An output iterator to which the result will be copied \param Input An input range - \param IsSpace A unary predicate identifying spaces + \param IsSpace An unary predicate identifying spaces \return An output iterator pointing just after the last inserted character or a copy of the input @@ -118,7 +118,7 @@ namespace boost { The input sequence is modified in-place. \param Input An input sequence - \param IsSpace A unary predicate identifying spaces + \param IsSpace An unary predicate identifying spaces */ template inline void trim_left_if(SequenceT& Input, PredicateT IsSpace) @@ -158,7 +158,7 @@ namespace boost { \param Output An output iterator to which the result will be copied \param Input An input range - \param IsSpace A unary predicate identifying spaces + \param IsSpace An unary predicate identifying spaces \return An output iterator pointing just after the last inserted character or a copy of the input @@ -228,7 +228,7 @@ namespace boost { The input sequence is modified in-place. \param Input An input sequence - \param IsSpace A unary predicate identifying spaces + \param IsSpace An unary predicate identifying spaces */ template inline void trim_right_if(SequenceT& Input, PredicateT IsSpace) @@ -270,7 +270,7 @@ namespace boost { \param Output An output iterator to which the result will be copied \param Input An input range - \param IsSpace A unary predicate identifying spaces + \param IsSpace An unary predicate identifying spaces \return An output iterator pointing just after the last inserted character or a copy of the input @@ -352,7 +352,7 @@ namespace boost { The input sequence is modified in-place. \param Input An input sequence - \param IsSpace A unary predicate identifying spaces + \param IsSpace An unary predicate identifying spaces */ template inline void trim_if(SequenceT& Input, PredicateT IsSpace) diff --git a/utils/boost_idb/boost/algorithm/string/trim_all.hpp b/utils/boost_idb/boost/algorithm/string/trim_all.hpp deleted file mode 100644 index a616f7f3..00000000 --- a/utils/boost_idb/boost/algorithm/string/trim_all.hpp +++ /dev/null @@ -1,217 +0,0 @@ -// Boost string_algo library trim.hpp header file ---------------------------// - -// Copyright Pavol Droba 2002-2003. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/ for updates, documentation, and revision history. - -#ifndef BOOST_STRING_TRIM_ALL_HPP -#define BOOST_STRING_TRIM_ALL_HPP - -#include - -#include -#include -#include -#include -#include -#include - -/*! \file - Defines trim_all algorithms. - - Just like \c trim, \c trim_all removes all trailing and leading spaces from a - sequence (string). In addition, spaces in the middle of the sequence are truncated - to just one character. Space is recognized using given locales. - - \c trim_fill acts as trim_all, but the spaces in the middle are replaces with - a user-define sequence of character. - - Parametric (\c _if) variants use a predicate (functor) to select which characters - are to be trimmed.. - Functions take a selection predicate as a parameter, which is used to determine - whether a character is a space. Common predicates are provided in classification.hpp header. - -*/ - -namespace boost { - namespace algorithm { - - // multi line trim ----------------------------------------------- // - - //! Trim All - parametric - /*! - Remove all leading and trailing spaces from the input and - compress all other spaces to a single character. - The result is a trimmed copy of the input - - \param Input An input sequence - \param IsSpace A unary predicate identifying spaces - \return A trimmed copy of the input - */ - template - inline SequenceT trim_all_copy_if(const SequenceT& Input, PredicateT IsSpace) - { - return - ::boost::find_format_all_copy( - ::boost::trim_copy_if(Input, IsSpace), - ::boost::token_finder(IsSpace, ::boost::token_compress_on), - ::boost::dissect_formatter(::boost::head_finder(1))); - } - - - //! Trim All - /*! - Remove all leading and trailing spaces from the input and - compress all other spaces to a single character. - The input sequence is modified in-place. - - \param Input An input sequence - \param IsSpace A unary predicate identifying spaces - */ - template - inline void trim_all_if(SequenceT& Input, PredicateT IsSpace) - { - ::boost::trim_if(Input, IsSpace); - ::boost::find_format_all( - Input, - ::boost::token_finder(IsSpace, ::boost::token_compress_on), - ::boost::dissect_formatter(::boost::head_finder(1))); - } - - - //! Trim All - /*! - Remove all leading and trailing spaces from the input and - compress all other spaces to a single character. - The result is a trimmed copy of the input - - \param Input An input sequence - \param Loc A locale used for 'space' classification - \return A trimmed copy of the input - */ - template - inline SequenceT trim_all_copy(const SequenceT& Input, const std::locale& Loc =std::locale()) - { - return trim_all_copy_if(Input, ::boost::is_space(Loc)); - } - - - //! Trim All - /*! - Remove all leading and trailing spaces from the input and - compress all other spaces to a single character. - The input sequence is modified in-place. - - \param Input An input sequence - \param Loc A locale used for 'space' classification - \return A trimmed copy of the input - */ - template - inline void trim_all(SequenceT& Input, const std::locale& Loc =std::locale()) - { - trim_all_if(Input, ::boost::is_space(Loc)); - } - - - //! Trim Fill - parametric - /*! - Remove all leading and trailing spaces from the input and - replace all every block of consecutive spaces with a fill string - defined by user. - The result is a trimmed copy of the input - - \param Input An input sequence - \param Fill A string used to fill the inner spaces - \param IsSpace A unary predicate identifying spaces - \return A trimmed copy of the input - */ - template - inline SequenceT trim_fill_copy_if(const SequenceT& Input, const RangeT& Fill, PredicateT IsSpace) - { - return - ::boost::find_format_all_copy( - ::boost::trim_copy_if(Input, IsSpace), - ::boost::token_finder(IsSpace, ::boost::token_compress_on), - ::boost::const_formatter(::boost::as_literal(Fill))); - } - - - //! Trim Fill - /*! - Remove all leading and trailing spaces from the input and - replace all every block of consecutive spaces with a fill string - defined by user. - The input sequence is modified in-place. - - \param Input An input sequence - \param Fill A string used to fill the inner spaces - \param IsSpace A unary predicate identifying spaces - */ - template - inline void trim_fill_if(SequenceT& Input, const RangeT& Fill, PredicateT IsSpace) - { - ::boost::trim_if(Input, IsSpace); - ::boost::find_format_all( - Input, - ::boost::token_finder(IsSpace, ::boost::token_compress_on), - ::boost::const_formatter(::boost::as_literal(Fill))); - } - - - //! Trim Fill - /*! - Remove all leading and trailing spaces from the input and - replace all every block of consecutive spaces with a fill string - defined by user. - The result is a trimmed copy of the input - - \param Input An input sequence - \param Fill A string used to fill the inner spaces - \param Loc A locale used for 'space' classification - \return A trimmed copy of the input - */ - template - inline SequenceT trim_fill_copy(const SequenceT& Input, const RangeT& Fill, const std::locale& Loc =std::locale()) - { - return trim_fill_copy_if(Input, Fill, ::boost::is_space(Loc)); - } - - - //! Trim Fill - /*! - Remove all leading and trailing spaces from the input and - replace all every block of consecutive spaces with a fill string - defined by user. - The input sequence is modified in-place. - - \param Input An input sequence - \param Fill A string used to fill the inner spaces - \param Loc A locale used for 'space' classification - \return A trimmed copy of the input - */ - template - inline void trim_fill(SequenceT& Input, const RangeT& Fill, const std::locale& Loc =std::locale()) - { - trim_fill_if(Input, Fill, ::boost::is_space(Loc)); - } - - - } // namespace algorithm - - // pull names to the boost namespace - using algorithm::trim_all; - using algorithm::trim_all_if; - using algorithm::trim_all_copy; - using algorithm::trim_all_copy_if; - using algorithm::trim_fill; - using algorithm::trim_fill_if; - using algorithm::trim_fill_copy; - using algorithm::trim_fill_copy_if; - -} // namespace boost - -#endif // BOOST_STRING_TRIM_ALL_HPP diff --git a/utils/boost_idb/boost/algorithm/string_regex.hpp b/utils/boost_idb/boost/algorithm/string_regex.hpp index 791aa184..6fd8ad9f 100644 --- a/utils/boost_idb/boost/algorithm/string_regex.hpp +++ b/utils/boost_idb/boost/algorithm/string_regex.hpp @@ -13,7 +13,7 @@ /*! \file Cumulative include for string_algo library. - In addition to string.hpp contains also regex-related stuff. + In addtion to string.hpp contains also regex-related stuff. */ #include diff --git a/utils/boost_idb/boost/aligned_storage.hpp b/utils/boost_idb/boost/aligned_storage.hpp new file mode 100644 index 00000000..ce277ab7 --- /dev/null +++ b/utils/boost_idb/boost/aligned_storage.hpp @@ -0,0 +1,181 @@ +//----------------------------------------------------------------------------- +// boost aligned_storage.hpp header file +// See http://www.boost.org for updates, documentation, and revision history. +//----------------------------------------------------------------------------- +// +// Copyright (c) 2002-2003 +// Eric Friedman, Itay Maman +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_ALIGNED_STORAGE_HPP +#define BOOST_ALIGNED_STORAGE_HPP + +#include // for std::size_t + +#include "boost/config.hpp" +#include "boost/detail/workaround.hpp" +#include "boost/type_traits/alignment_of.hpp" +#include "boost/type_traits/type_with_alignment.hpp" +#include "boost/type_traits/is_pod.hpp" + +#include "boost/mpl/eval_if.hpp" +#include "boost/mpl/identity.hpp" + +#include "boost/type_traits/detail/bool_trait_def.hpp" + +namespace boost { + +namespace detail { namespace aligned_storage { + +BOOST_STATIC_CONSTANT( + std::size_t + , alignment_of_max_align = ::boost::alignment_of::value + ); + +// +// To be TR1 conforming this must be a POD type: +// +template < + std::size_t size_ + , std::size_t alignment_ +> +struct aligned_storage_imp +{ + union data_t + { + char buf[size_]; + + typename mpl::eval_if_c< + alignment_ == std::size_t(-1) + , mpl::identity + , type_with_alignment + >::type align_; + } data_; + void* address() const { return const_cast(this); } +}; + +template< std::size_t alignment_ > +struct aligned_storage_imp<0u,alignment_> +{ + /* intentionally empty */ + void* address() const { return 0; } +}; + +}} // namespace detail::aligned_storage + +template < + std::size_t size_ + , std::size_t alignment_ = std::size_t(-1) +> +class aligned_storage : +#ifndef __BORLANDC__ + private +#else + public +#endif + detail::aligned_storage::aligned_storage_imp +{ + +public: // constants + + typedef detail::aligned_storage::aligned_storage_imp type; + + BOOST_STATIC_CONSTANT( + std::size_t + , size = size_ + ); + BOOST_STATIC_CONSTANT( + std::size_t + , alignment = ( + alignment_ == std::size_t(-1) + ? ::boost::detail::aligned_storage::alignment_of_max_align + : alignment_ + ) + ); + +#if defined(__GNUC__) &&\ + (__GNUC__ > 3) ||\ + (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 ||\ + (__GNUC_MINOR__ == 2 && __GNUC_PATCHLEVEL__ >=3))) + +private: // noncopyable + + aligned_storage(const aligned_storage&); + aligned_storage& operator=(const aligned_storage&); + +#else // gcc less than 3.2.3 + +public: // _should_ be noncopyable, but GCC compiler emits error + + aligned_storage(const aligned_storage&); + aligned_storage& operator=(const aligned_storage&); + +#endif // gcc < 3.2.3 workaround + +public: // structors + + aligned_storage() + { + } + + ~aligned_storage() + { + } + +public: // accessors + + void* address() + { + return static_cast(this)->address(); + } + +#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300) + + const void* address() const + { + return static_cast(this)->address(); + } + +#else // MSVC6 + + const void* address() const; + +#endif // MSVC6 workaround + +}; + +#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) + +// MSVC6 seems not to like inline functions with const void* returns, so we +// declare the following here: + +template +const void* aligned_storage::address() const +{ + return const_cast< aligned_storage* >(this)->address(); +} + +#endif // MSVC6 workaround + +#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION +// +// Make sure that is_pod recognises aligned_storage<>::type +// as a POD (Note that aligned_storage<> itself is not a POD): +// +template +struct is_pod > + BOOST_TT_AUX_BOOL_C_BASE(true) +{ + BOOST_TT_AUX_BOOL_TRAIT_VALUE_DECL(true) +}; +#endif + + +} // namespace boost + +#include "boost/type_traits/detail/bool_trait_undef.hpp" + +#endif // BOOST_ALIGNED_STORAGE_HPP diff --git a/utils/boost_idb/boost/any.hpp b/utils/boost_idb/boost/any.hpp index 77139353..a8c654c3 100644 --- a/utils/boost_idb/boost/any.hpp +++ b/utils/boost_idb/boost/any.hpp @@ -3,31 +3,21 @@ #ifndef BOOST_ANY_INCLUDED #define BOOST_ANY_INCLUDED -#if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once -#endif - // what: variant type boost::any // who: contributed by Kevlin Henney, // with features contributed and bugs found by -// Antony Polukhin, Ed Brey, Mark Rodgers, -// Peter Dimov, and James Curran -// when: July 2001, April 2013 - May 2013 +// Ed Brey, Mark Rodgers, Peter Dimov, and James Curran +// when: July 2001 +// where: tested with BCC 5.5, MSVC 6.0, and g++ 2.95 #include #include #include "boost/config.hpp" #include -#include -#include #include -#include #include #include -#include -#include -#include // See boost/python/type_id.hpp // TODO: add BOOST_TYPEID_COMPARE_BY_NAME to config.hpp @@ -40,25 +30,20 @@ #include # endif -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 4172) // Mistakenly warns: returning address of local variable or temporary -#endif - namespace boost { class any { public: // structors - any() BOOST_NOEXCEPT + any() : content(0) { } template any(const ValueType & value) - : content(new holder::type>(value)) + : content(new holder(value)) { } @@ -67,39 +52,19 @@ namespace boost { } -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - // Move constructor - any(any&& other) BOOST_NOEXCEPT - : content(other.content) - { - other.content = 0; - } - - // Perfect forwarding of ValueType - template - any(ValueType&& value - , typename boost::disable_if >::type* = 0 // disable if value has type `any&` - , typename boost::disable_if >::type* = 0) // disable if value has type `const ValueType&&` - : content(new holder< typename decay::type >(static_cast(value))) - { - } -#endif - - ~any() BOOST_NOEXCEPT + ~any() { delete content; } public: // modifiers - any & swap(any & rhs) BOOST_NOEXCEPT + any & swap(any & rhs) { std::swap(content, rhs.content); return *this; } - -#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES template any & operator=(const ValueType & rhs) { @@ -108,48 +73,19 @@ namespace boost } any & operator=(any rhs) - { - any(rhs).swap(*this); - return *this; - } - -#else - any & operator=(const any& rhs) - { - any(rhs).swap(*this); - return *this; - } - - // move assignement - any & operator=(any&& rhs) BOOST_NOEXCEPT { rhs.swap(*this); - any().swap(rhs); return *this; } - // Perfect forwarding of ValueType - template - any & operator=(ValueType&& rhs) - { - any(static_cast(rhs)).swap(*this); - return *this; - } -#endif - public: // queries - bool empty() const BOOST_NOEXCEPT + bool empty() const { return !content; } - void clear() BOOST_NOEXCEPT - { - any().swap(*this); - } - - const std::type_info & type() const BOOST_NOEXCEPT + const std::type_info & type() const { return content ? content->type() : typeid(void); } @@ -170,7 +106,7 @@ namespace boost public: // queries - virtual const std::type_info & type() const BOOST_NOEXCEPT = 0; + virtual const std::type_info & type() const = 0; virtual placeholder * clone() const = 0; @@ -186,15 +122,9 @@ namespace boost { } -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - holder(ValueType&& value) - : held(static_cast< ValueType&& >(value)) - { - } -#endif public: // queries - virtual const std::type_info & type() const BOOST_NOEXCEPT + virtual const std::type_info & type() const { return typeid(ValueType); } @@ -217,10 +147,10 @@ namespace boost private: // representation template - friend ValueType * any_cast(any *) BOOST_NOEXCEPT; + friend ValueType * any_cast(any *); template - friend ValueType * unsafe_any_cast(any *) BOOST_NOEXCEPT; + friend ValueType * unsafe_any_cast(any *); #else @@ -231,16 +161,11 @@ namespace boost placeholder * content; }; - - inline void swap(any & lhs, any & rhs) BOOST_NOEXCEPT - { - lhs.swap(rhs); - } - class BOOST_SYMBOL_VISIBLE bad_any_cast : public std::bad_cast + class bad_any_cast : public std::bad_cast { public: - virtual const char * what() const BOOST_NOEXCEPT_OR_NOTHROW + virtual const char * what() const throw() { return "boost::bad_any_cast: " "failed conversion using boost::any_cast"; @@ -248,7 +173,7 @@ namespace boost }; template - ValueType * any_cast(any * operand) BOOST_NOEXCEPT + ValueType * any_cast(any * operand) { return operand && #ifdef BOOST_AUX_ANY_TYPE_ID_NAME @@ -261,7 +186,7 @@ namespace boost } template - inline const ValueType * any_cast(const any * operand) BOOST_NOEXCEPT + inline const ValueType * any_cast(const any * operand) { return any_cast(const_cast(operand)); } @@ -284,18 +209,7 @@ namespace boost nonref * result = any_cast(&operand); if(!result) boost::throw_exception(bad_any_cast()); - - // Attempt to avoid construction of a temporary object in cases when - // `ValueType` is not a reference. Example: - // `static_cast(*result);` - // which is equal to `std::string(*result);` - typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_< - boost::is_reference, - ValueType, - BOOST_DEDUCED_TYPENAME boost::add_reference::type - >::type ref_type; - - return static_cast(*result); + return *result; } template @@ -312,33 +226,19 @@ namespace boost return any_cast(const_cast(operand)); } -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - template - inline ValueType&& any_cast(any&& operand) - { - BOOST_STATIC_ASSERT_MSG( - boost::is_rvalue_reference::value - || boost::is_const< typename boost::remove_reference::type >::value, - "boost::any_cast shall not be used for getting nonconst references to temporary objects" - ); - return any_cast(operand); - } -#endif - - // Note: The "unsafe" versions of any_cast are not part of the // public interface and may be removed at any time. They are // required where we know what type is stored in the any and can't // use typeid() comparison, e.g., when our types may travel across // different shared libraries. template - inline ValueType * unsafe_any_cast(any * operand) BOOST_NOEXCEPT + inline ValueType * unsafe_any_cast(any * operand) { return &static_cast *>(operand->content)->held; } template - inline const ValueType * unsafe_any_cast(const any * operand) BOOST_NOEXCEPT + inline const ValueType * unsafe_any_cast(const any * operand) { return unsafe_any_cast(const_cast(operand)); } @@ -350,8 +250,4 @@ namespace boost // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) -#if defined(_MSC_VER) -#pragma warning(pop) -#endif - #endif diff --git a/utils/boost_idb/boost/array.hpp b/utils/boost_idb/boost/array.hpp index fa06fa9a..7df27714 100644 --- a/utils/boost_idb/boost/array.hpp +++ b/utils/boost_idb/boost/array.hpp @@ -13,8 +13,6 @@ * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * - * 14 Apr 2012 - (mtc) Added support for boost::hash - * 28 Dec 2010 - (mtc) Added cbegin and cend (and crbegin and crend) for C++Ox compatibility. * 10 Mar 2010 - (mtc) fill method added, matching resolution of the standard library working group. * See or Trac issue #3168 * Eventually, we should remove "assign" which is now a synonym for "fill" (Marshall Clow) @@ -47,7 +45,6 @@ // Handles broken standard libraries better than #include #include -#include #include // FIXES for broken compilers @@ -72,13 +69,10 @@ namespace boost { typedef std::ptrdiff_t difference_type; // iterator support - iterator begin() { return elems; } - const_iterator begin() const { return elems; } - const_iterator cbegin() const { return elems; } - - iterator end() { return elems+N; } - const_iterator end() const { return elems+N; } - const_iterator cend() const { return elems+N; } + iterator begin() { return elems; } + const_iterator begin() const { return elems; } + iterator end() { return elems+N; } + const_iterator end() const { return elems+N; } // reverse iterator support #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_MSVC_STD_ITERATOR) && !defined(BOOST_NO_STD_ITERATOR_TRAITS) @@ -105,28 +99,21 @@ namespace boost { const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { - return const_reverse_iterator(end()); - } - reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { - return const_reverse_iterator(begin()); - } // operator[] reference operator[](size_type i) { - BOOST_ASSERT_MSG( i < N, "out of range" ); + BOOST_ASSERT( i < N && "out of range" ); return elems[i]; } const_reference operator[](size_type i) const { - BOOST_ASSERT_MSG( i < N, "out of range" ); + BOOST_ASSERT( i < N && "out of range" ); return elems[i]; } @@ -213,13 +200,10 @@ namespace boost { typedef std::ptrdiff_t difference_type; // iterator support - iterator begin() { return iterator( reinterpret_cast< T * >( this ) ); } - const_iterator begin() const { return const_iterator( reinterpret_cast< const T * >( this ) ); } - const_iterator cbegin() const { return const_iterator( reinterpret_cast< const T * >( this ) ); } - - iterator end() { return begin(); } - const_iterator end() const { return begin(); } - const_iterator cend() const { return cbegin(); } + iterator begin() { return iterator( reinterpret_cast< T * >( this ) ); } + const_iterator begin() const { return const_iterator( reinterpret_cast< const T * >( this ) ); } + iterator end() { return begin(); } + const_iterator end() const { return begin(); } // reverse iterator support #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_MSVC_STD_ITERATOR) && !defined(BOOST_NO_STD_ITERATOR_TRAITS) @@ -246,17 +230,10 @@ namespace boost { const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { - return const_reverse_iterator(end()); - } - reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { - return const_reverse_iterator(begin()); - } // operator[] reference operator[](size_type /*i*/) @@ -324,7 +301,7 @@ namespace boost { static reference failed_rangecheck () { std::out_of_range e("attempt to access element of an empty array"); boost::throw_exception(e); -#if defined(BOOST_NO_EXCEPTIONS) || (!defined(BOOST_MSVC) && !defined(__PATHSCALE__)) +#if defined(BOOST_NO_EXCEPTIONS) || !defined(BOOST_MSVC) // // We need to return something here to keep // some compilers happy: however we will never @@ -369,34 +346,7 @@ namespace boost { x.swap(y); } -#if defined(__SUNPRO_CC) -// Trac ticket #4757; the Sun Solaris compiler can't handle -// syntax like 'T(&get_c_array(boost::array& arg))[N]' -// -// We can't just use this for all compilers, because the -// borland compilers can't handle this form. - namespace detail { - template struct c_array - { - typedef T type[N]; - }; - } - - // Specific for boost::array: simply returns its elems data member. - template - typename detail::c_array::type& get_c_array(boost::array& arg) - { - return arg.elems; - } - - // Specific for boost::array: simply returns its elems data member. - template - typename const detail::c_array::type& get_c_array(const boost::array& arg) - { - return arg.elems; - } -#else -// Specific for boost::array: simply returns its elems data member. + // Specific for boost::array: simply returns its elems data member. template T(&get_c_array(boost::array& arg))[N] { @@ -409,8 +359,7 @@ namespace boost { { return arg.elems; } -#endif - + #if 0 // Overload for std::array, assuming that std::array will have // explicit conversion functions as discussed at the WG21 meeting @@ -429,13 +378,6 @@ namespace boost { } #endif - - template - std::size_t hash_value(const array& arr) - { - return boost::hash_range(arr.begin(), arr.end()); - } - } /* namespace boost */ diff --git a/utils/boost_idb/boost/asio.hpp b/utils/boost_idb/boost/asio.hpp new file mode 100644 index 00000000..f94e0d65 --- /dev/null +++ b/utils/boost_idb/boost/asio.hpp @@ -0,0 +1,100 @@ +// +// asio.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See www.boost.org/libs/asio for documentation. +// + +#ifndef BOOST_ASIO_HPP +#define BOOST_ASIO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif // BOOST_ASIO_HPP diff --git a/utils/boost_idb/boost/assert.hpp b/utils/boost_idb/boost/assert.hpp index c2c469da..95430b5a 100644 --- a/utils/boost_idb/boost/assert.hpp +++ b/utils/boost_idb/boost/assert.hpp @@ -1,11 +1,8 @@ // // boost/assert.hpp - BOOST_ASSERT(expr) -// BOOST_ASSERT_MSG(expr, msg) -// BOOST_VERIFY(expr) // // Copyright (c) 2001, 2002 Peter Dimov and Multi Media Ltd. // Copyright (c) 2007 Peter Dimov -// Copyright (c) Beman Dawes 2011 // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at @@ -16,122 +13,40 @@ // See http://www.boost.org/libs/utility/assert.html for documentation. // -// -// Stop inspect complaining about use of 'assert': -// -// boostinspect:naassert_macro -// +#if __FreeBSD__ +#define IDB_BOOST_ENABLE_ASSERTS +#endif -//--------------------------------------------------------------------------------------// -// BOOST_ASSERT // -//--------------------------------------------------------------------------------------// +#if defined(IDB_BOOST_ENABLE_ASSERTS) +#undef BOOST_DISABLE_ASSERTS +#else +#define BOOST_DISABLE_ASSERTS 1 +#endif #undef BOOST_ASSERT -#ifndef IDB_ENABLE_BOOST_ASSERTS -#define BOOST_DISABLE_ASSERTS -#endif - #if defined(BOOST_DISABLE_ASSERTS) # define BOOST_ASSERT(expr) ((void)0) #elif defined(BOOST_ENABLE_ASSERT_HANDLER) -#include #include namespace boost { - void assertion_failed(char const * expr, - char const * function, char const * file, long line); // user defined + +void assertion_failed(char const * expr, char const * function, char const * file, long line); // user defined + } // namespace boost -#define BOOST_ASSERT(expr) (BOOST_LIKELY(!!(expr)) \ - ? ((void)0) \ - : ::boost::assertion_failed(#expr, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)) +#define BOOST_ASSERT(expr) ((expr)? ((void)0): ::boost::assertion_failed(#expr, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)) #else # include // .h to support old libraries w/o - effect is the same # define BOOST_ASSERT(expr) assert(expr) #endif -//--------------------------------------------------------------------------------------// -// BOOST_ASSERT_MSG // -//--------------------------------------------------------------------------------------// - -# undef BOOST_ASSERT_MSG - -#if defined(BOOST_DISABLE_ASSERTS) || defined(NDEBUG) - - #define BOOST_ASSERT_MSG(expr, msg) ((void)0) - -#elif defined(BOOST_ENABLE_ASSERT_HANDLER) - - #include - #include - - namespace boost - { - void assertion_failed_msg(char const * expr, char const * msg, - char const * function, char const * file, long line); // user defined - } // namespace boost - - #define BOOST_ASSERT_MSG(expr, msg) (BOOST_LIKELY(!!(expr)) \ - ? ((void)0) \ - : ::boost::assertion_failed_msg(#expr, msg, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)) - -#else - #ifndef BOOST_ASSERT_HPP - #define BOOST_ASSERT_HPP - #include - #include - #include - #include - - // IDE's like Visual Studio perform better if output goes to std::cout or - // some other stream, so allow user to configure output stream: - #ifndef BOOST_ASSERT_MSG_OSTREAM - # define BOOST_ASSERT_MSG_OSTREAM std::cerr - #endif - - namespace boost - { - namespace assertion - { - namespace detail - { - // Note: The template is needed to make the function non-inline and avoid linking errors - template< typename CharT > - BOOST_NOINLINE void assertion_failed_msg(CharT const * expr, char const * msg, char const * function, - char const * file, long line) - { - BOOST_ASSERT_MSG_OSTREAM - << "***** Internal Program Error - assertion (" << expr << ") failed in " - << function << ":\n" - << file << '(' << line << "): " << msg << std::endl; -#ifdef UNDER_CE - // The Windows CE CRT library does not have abort() so use exit(-1) instead. - std::exit(-1); -#else - std::abort(); -#endif - } - } // detail - } // assertion - } // detail - #endif - - #define BOOST_ASSERT_MSG(expr, msg) (BOOST_LIKELY(!!(expr)) \ - ? ((void)0) \ - : ::boost::assertion::detail::assertion_failed_msg(#expr, msg, \ - BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)) -#endif - -//--------------------------------------------------------------------------------------// -// BOOST_VERIFY // -//--------------------------------------------------------------------------------------// - #undef BOOST_VERIFY #if defined(BOOST_DISABLE_ASSERTS) || ( !defined(BOOST_ENABLE_ASSERT_HANDLER) && defined(NDEBUG) ) diff --git a/utils/boost_idb/boost/atomic.hpp b/utils/boost_idb/boost/atomic.hpp deleted file mode 100644 index cc28b1ab..00000000 --- a/utils/boost_idb/boost/atomic.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef BOOST_ATOMIC_HPP -#define BOOST_ATOMIC_HPP - -// Copyright (c) 2011 Helge Bahmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// This header includes all Boost.Atomic public headers - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -#endif diff --git a/utils/boost_idb/boost/atomic/atomic.hpp b/utils/boost_idb/boost/atomic/atomic.hpp deleted file mode 100644 index dd3c0146..00000000 --- a/utils/boost_idb/boost/atomic/atomic.hpp +++ /dev/null @@ -1,232 +0,0 @@ -#ifndef BOOST_ATOMIC_ATOMIC_HPP -#define BOOST_ATOMIC_ATOMIC_HPP - -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include - -#include - -#include -#include -#include -#include -#if defined(BOOST_MSVC) && BOOST_MSVC < 1400 -#include -#include -#endif - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { - -#ifndef BOOST_ATOMIC_CHAR_LOCK_FREE -#define BOOST_ATOMIC_CHAR_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_CHAR16_T_LOCK_FREE -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_CHAR32_T_LOCK_FREE -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_WCHAR_T_LOCK_FREE -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_SHORT_LOCK_FREE -#define BOOST_ATOMIC_SHORT_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_INT_LOCK_FREE -#define BOOST_ATOMIC_INT_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_LONG_LOCK_FREE -#define BOOST_ATOMIC_LONG_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_LLONG_LOCK_FREE -#define BOOST_ATOMIC_LLONG_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_INT128_LOCK_FREE -#define BOOST_ATOMIC_INT128_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_POINTER_LOCK_FREE -#define BOOST_ATOMIC_POINTER_LOCK_FREE 0 -#endif - -#define BOOST_ATOMIC_ADDRESS_LOCK_FREE BOOST_ATOMIC_POINTER_LOCK_FREE - -#ifndef BOOST_ATOMIC_BOOL_LOCK_FREE -#define BOOST_ATOMIC_BOOL_LOCK_FREE 0 -#endif - -#ifndef BOOST_ATOMIC_THREAD_FENCE -#define BOOST_ATOMIC_THREAD_FENCE 0 -inline void atomic_thread_fence(memory_order) -{ -} -#endif - -#ifndef BOOST_ATOMIC_SIGNAL_FENCE -#define BOOST_ATOMIC_SIGNAL_FENCE 0 -inline void atomic_signal_fence(memory_order order) -{ - atomic_thread_fence(order); -} -#endif - -template -class atomic : - public atomics::detail::base_atomic< - T, - typename atomics::detail::classify::type, - atomics::detail::storage_size_of::value, -#if !defined(BOOST_MSVC) || BOOST_MSVC >= 1400 - boost::is_signed::value -#else - // MSVC 2003 has problems instantiating is_signed on non-integral types - mpl::and_< boost::is_integral, boost::is_signed >::value -#endif - > -{ -private: - typedef T value_type; - typedef atomics::detail::base_atomic< - T, - typename atomics::detail::classify::type, - atomics::detail::storage_size_of::value, -#if !defined(BOOST_MSVC) || BOOST_MSVC >= 1400 - boost::is_signed::value -#else - // MSVC 2003 has problems instantiating is_signed on non-itegral types - mpl::and_< boost::is_integral, boost::is_signed >::value -#endif - > super; - typedef typename super::value_arg_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(atomic(void), BOOST_NOEXCEPT {}) - - // NOTE: The constructor is made explicit because gcc 4.7 complains that - // operator=(value_arg_type) is considered ambiguous with operator=(atomic const&) - // in assignment expressions, even though conversion to atomic<> is less preferred - // than conversion to value_arg_type. - explicit BOOST_CONSTEXPR atomic(value_arg_type v) BOOST_NOEXCEPT : super(v) {} - - value_type operator=(value_arg_type v) volatile BOOST_NOEXCEPT - { - this->store(v); - return v; - } - - operator value_type(void) volatile const BOOST_NOEXCEPT - { - return this->load(); - } - - BOOST_DELETED_FUNCTION(atomic(atomic const&)) - BOOST_DELETED_FUNCTION(atomic& operator=(atomic const&) volatile) -}; - -typedef atomic atomic_char; -typedef atomic atomic_uchar; -typedef atomic atomic_schar; -typedef atomic atomic_uint8_t; -typedef atomic atomic_int8_t; -typedef atomic atomic_ushort; -typedef atomic atomic_short; -typedef atomic atomic_uint16_t; -typedef atomic atomic_int16_t; -typedef atomic atomic_uint; -typedef atomic atomic_int; -typedef atomic atomic_uint32_t; -typedef atomic atomic_int32_t; -typedef atomic atomic_ulong; -typedef atomic atomic_long; -typedef atomic atomic_uint64_t; -typedef atomic atomic_int64_t; -#ifdef BOOST_HAS_LONG_LONG -typedef atomic atomic_ullong; -typedef atomic atomic_llong; -#endif -typedef atomic atomic_address; -typedef atomic atomic_bool; -typedef atomic atomic_wchar_t; -#if !defined(BOOST_NO_CXX11_CHAR16_T) -typedef atomic atomic_char16_t; -#endif -#if !defined(BOOST_NO_CXX11_CHAR32_T) -typedef atomic atomic_char32_t; -#endif - -typedef atomic atomic_int_least8_t; -typedef atomic atomic_uint_least8_t; -typedef atomic atomic_int_least16_t; -typedef atomic atomic_uint_least16_t; -typedef atomic atomic_int_least32_t; -typedef atomic atomic_uint_least32_t; -typedef atomic atomic_int_least64_t; -typedef atomic atomic_uint_least64_t; -typedef atomic atomic_int_fast8_t; -typedef atomic atomic_uint_fast8_t; -typedef atomic atomic_int_fast16_t; -typedef atomic atomic_uint_fast16_t; -typedef atomic atomic_int_fast32_t; -typedef atomic atomic_uint_fast32_t; -typedef atomic atomic_int_fast64_t; -typedef atomic atomic_uint_fast64_t; -typedef atomic atomic_intmax_t; -typedef atomic atomic_uintmax_t; - -typedef atomic atomic_size_t; -typedef atomic atomic_ptrdiff_t; - -#if defined(BOOST_HAS_INTPTR_T) -typedef atomic atomic_intptr_t; -typedef atomic atomic_uintptr_t; -#endif - -#ifndef BOOST_ATOMIC_FLAG_LOCK_FREE -#define BOOST_ATOMIC_FLAG_LOCK_FREE 0 -class atomic_flag -{ -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(false) {} - - bool - test_and_set(memory_order order = memory_order_seq_cst) BOOST_NOEXCEPT - { - return v_.exchange(true, order); - } - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v_.store(false, order); - } - - BOOST_DELETED_FUNCTION(atomic_flag(atomic_flag const&)) - BOOST_DELETED_FUNCTION(atomic_flag& operator=(atomic_flag const&)) - -private: - atomic v_; -}; -#endif - -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/base.hpp b/utils/boost_idb/boost/atomic/detail/base.hpp deleted file mode 100644 index eb105b9b..00000000 --- a/utils/boost_idb/boost/atomic/detail/base.hpp +++ /dev/null @@ -1,605 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_BASE_HPP -#define BOOST_ATOMIC_DETAIL_BASE_HPP - -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// Base class definition and fallback implementation. -// To be overridden (through partial specialization) by -// platform implementations. - -#include - -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -#define BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ - bool \ - compare_exchange_strong( \ - value_type & expected, \ - value_type desired, \ - memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT \ - { \ - return compare_exchange_strong(expected, desired, order, calculate_failure_order(order)); \ - } \ - \ - bool \ - compare_exchange_weak( \ - value_type & expected, \ - value_type desired, \ - memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT \ - { \ - return compare_exchange_weak(expected, desired, order, calculate_failure_order(order)); \ - } \ - -#define BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \ - value_type \ - operator++(int) volatile BOOST_NOEXCEPT \ - { \ - return fetch_add(1); \ - } \ - \ - value_type \ - operator++(void) volatile BOOST_NOEXCEPT \ - { \ - return fetch_add(1) + 1; \ - } \ - \ - value_type \ - operator--(int) volatile BOOST_NOEXCEPT \ - { \ - return fetch_sub(1); \ - } \ - \ - value_type \ - operator--(void) volatile BOOST_NOEXCEPT \ - { \ - return fetch_sub(1) - 1; \ - } \ - \ - value_type \ - operator+=(difference_type v) volatile BOOST_NOEXCEPT \ - { \ - return fetch_add(v) + v; \ - } \ - \ - value_type \ - operator-=(difference_type v) volatile BOOST_NOEXCEPT \ - { \ - return fetch_sub(v) - v; \ - } \ - -#define BOOST_ATOMIC_DECLARE_VOID_POINTER_ADDITIVE_OPERATORS \ - value_type \ - operator++(int) volatile BOOST_NOEXCEPT \ - { \ - return fetch_add(1); \ - } \ - \ - value_type \ - operator++(void) volatile BOOST_NOEXCEPT \ - { \ - return (char*)fetch_add(1) + 1; \ - } \ - \ - value_type \ - operator--(int) volatile BOOST_NOEXCEPT \ - { \ - return fetch_sub(1); \ - } \ - \ - value_type \ - operator--(void) volatile BOOST_NOEXCEPT \ - { \ - return (char*)fetch_sub(1) - 1; \ - } \ - \ - value_type \ - operator+=(difference_type v) volatile BOOST_NOEXCEPT \ - { \ - return (char*)fetch_add(v) + v; \ - } \ - \ - value_type \ - operator-=(difference_type v) volatile BOOST_NOEXCEPT \ - { \ - return (char*)fetch_sub(v) - v; \ - } \ - -#define BOOST_ATOMIC_DECLARE_BIT_OPERATORS \ - value_type \ - operator&=(difference_type v) volatile BOOST_NOEXCEPT \ - { \ - return fetch_and(v) & v; \ - } \ - \ - value_type \ - operator|=(difference_type v) volatile BOOST_NOEXCEPT \ - { \ - return fetch_or(v) | v; \ - } \ - \ - value_type \ - operator^=(difference_type v) volatile BOOST_NOEXCEPT\ - { \ - return fetch_xor(v) ^ v; \ - } \ - -#define BOOST_ATOMIC_DECLARE_POINTER_OPERATORS \ - BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ - BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \ - -#define BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS \ - BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ - BOOST_ATOMIC_DECLARE_VOID_POINTER_ADDITIVE_OPERATORS \ - -#define BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS \ - BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ - BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \ - BOOST_ATOMIC_DECLARE_BIT_OPERATORS \ - -namespace boost { -namespace atomics { -namespace detail { - -inline memory_order -calculate_failure_order(memory_order order) -{ - switch(order) - { - case memory_order_acq_rel: - return memory_order_acquire; - case memory_order_release: - return memory_order_relaxed; - default: - return order; - } -} - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef lockpool::scoped_lock guard_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(v) - {} - - void - store(value_type const& v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - char * storage = storage_ptr(); - guard_type guard(storage); - - memcpy(storage, &v, sizeof(value_type)); - } - - value_type - load(memory_order /*order*/ = memory_order_seq_cst) volatile const BOOST_NOEXCEPT - { - char * storage = storage_ptr(); - guard_type guard(storage); - - value_type v; - memcpy(&v, storage, sizeof(value_type)); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order /*success_order*/, - memory_order /*failure_order*/) volatile BOOST_NOEXCEPT - { - char * storage = storage_ptr(); - guard_type guard(storage); - - if (memcmp(storage, &expected, sizeof(value_type)) == 0) { - memcpy(storage, &desired, sizeof(value_type)); - return true; - } else { - memcpy(&expected, storage, sizeof(value_type)); - return false; - } - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - exchange(value_type const& v, memory_order /*order*/=memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - char * storage = storage_ptr(); - guard_type guard(storage); - - value_type tmp; - memcpy(&tmp, storage, sizeof(value_type)); - - memcpy(storage, &v, sizeof(value_type)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return false; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - char * storage_ptr() volatile const BOOST_NOEXCEPT - { - return const_cast(&reinterpret_cast(v_)); - } - - T v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef lockpool::scoped_lock guard_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - v_ = v; - } - - value_type - load(memory_order /*order*/ = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type v = const_cast(v_); - return v; - } - - value_type - exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ = v; - return old; - } - - bool - compare_exchange_strong(value_type & expected, value_type desired, - memory_order /*success_order*/, - memory_order /*failure_order*/) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - if (v_ == expected) { - v_ = desired; - return true; - } else { - expected = v_; - return false; - } - } - - bool - compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ += v; - return old; - } - - value_type - fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ -= v; - return old; - } - - value_type - fetch_and(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ &= v; - return old; - } - - value_type - fetch_or(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ |= v; - return old; - } - - value_type - fetch_xor(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ ^= v; - return old; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return false; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - typedef lockpool::scoped_lock guard_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - v_ = v; - } - - value_type - load(memory_order /*order*/ = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type v = const_cast(v_); - return v; - } - - value_type - exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ = v; - return old; - } - - bool - compare_exchange_strong(value_type & expected, value_type desired, - memory_order /*success_order*/, - memory_order /*failure_order*/) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - if (v_ == expected) { - v_ = desired; - return true; - } else { - expected = v_; - return false; - } - } - - bool - compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ += v; - return old; - } - - value_type fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ -= v; - return old; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return false; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void * value_type; - typedef lockpool::scoped_lock guard_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - v_ = v; - } - - value_type - load(memory_order /*order*/ = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type v = const_cast(v_); - return v; - } - - value_type - exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - v_ = v; - return old; - } - - bool - compare_exchange_strong(value_type & expected, value_type desired, - memory_order /*success_order*/, - memory_order /*failure_order*/) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - if (v_ == expected) { - v_ = desired; - return true; - } else { - expected = v_; - return false; - } - } - - bool - compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return false; - } - - value_type fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - char * cv = reinterpret_cast(old); - cv += v; - v_ = cv; - return old; - } - - value_type fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile - { - guard_type guard(const_cast(&v_)); - - value_type old = v_; - char * cv = reinterpret_cast(old); - cv -= v; - v_ = cv; - return old; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/cas128strong.hpp b/utils/boost_idb/boost/atomic/detail/cas128strong.hpp deleted file mode 100644 index 906c13e8..00000000 --- a/utils/boost_idb/boost/atomic/detail/cas128strong.hpp +++ /dev/null @@ -1,286 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_CAS128STRONG_HPP -#define BOOST_ATOMIC_DETAIL_CAS128STRONG_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann, Andrey Semashev - -// Build 128-bit atomic operation on integers/UDTs from platform_cmpxchg128_strong -// primitive. It is assumed that 128-bit loads/stores are not -// atomic, so they are implemented through platform_load128/platform_store128. - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -/* integral types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - platform_store128(v, &v_); - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = platform_load128(&v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg128_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* generic types */ - -#if defined(BOOST_HAS_INT128) - -typedef boost::uint128_type storage128_type; - -#else // defined(BOOST_HAS_INT128) - -struct BOOST_ALIGNMENT(16) storage128_type -{ - uint64_t data[2]; -}; - -inline bool operator== (storage128_type const& left, storage128_type const& right) -{ - return left.data[0] == right.data[0] && left.data[1] == right.data[1]; -} -inline bool operator!= (storage128_type const& left, storage128_type const& right) -{ - return !(left == right); -} - -#endif // defined(BOOST_HAS_INT128) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef storage128_type storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& value, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type value_s = 0; - memcpy(&value_s, &value, sizeof(value_type)); - platform_fence_before_store(order); - platform_store128(value_s, &v_); - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type value_s = platform_load128(&v_); - platform_fence_after_load(order); - value_type value; - memcpy(&value, &value_s, sizeof(value_type)); - return value; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - bool success = platform_cmpxchg128_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/cas32strong.hpp b/utils/boost_idb/boost/atomic/detail/cas32strong.hpp deleted file mode 100644 index 27e79839..00000000 --- a/utils/boost_idb/boost/atomic/detail/cas32strong.hpp +++ /dev/null @@ -1,939 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_CAS32STRONG_HPP -#define BOOST_ATOMIC_DETAIL_CAS32STRONG_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann - - -// Build 8-, 16- and 32-bit atomic operations from -// a platform_cmpxchg32_strong primitive. - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -/* integral types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef uint32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - storage_type expected_s = (storage_type) expected; - storage_type desired_s = (storage_type) desired; - - bool success = platform_cmpxchg32_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - expected = (value_type) expected_s; - } - - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef uint32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - storage_type expected_s = (storage_type) expected; - storage_type desired_s = (storage_type) desired; - - bool success = platform_cmpxchg32_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - expected = (value_type) expected_s; - } - - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg32_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* pointer types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef void * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg32_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, (char*)original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, (char*)original - v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg32_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* generic types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) ) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before_store(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) ) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) ) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) ) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - bool success = platform_cmpxchg32_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) ) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before_store(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) ) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - bool success = platform_cmpxchg32_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before_store(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - bool success = platform_cmpxchg32_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - is_lock_free(void) const volatile - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/cas32weak.hpp b/utils/boost_idb/boost/atomic/detail/cas32weak.hpp deleted file mode 100644 index d75215d8..00000000 --- a/utils/boost_idb/boost/atomic/detail/cas32weak.hpp +++ /dev/null @@ -1,1017 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_CAS32WEAK_HPP -#define BOOST_ATOMIC_DETAIL_CAS32WEAK_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann - - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -/* integral types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef uint32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - storage_type expected_s = (storage_type) expected; - storage_type desired_s = (storage_type) desired; - - bool success = platform_cmpxchg32(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - expected = (value_type) expected_s; - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef uint32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - storage_type expected_s = (storage_type) expected; - storage_type desired_s = (storage_type) desired; - - bool success = platform_cmpxchg32(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - expected = (value_type) expected_s; - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg32(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* pointer types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef void * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg32(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, (char*)original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, (char*)original - v, order, memory_order_relaxed)); - return original; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg32(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* generic types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before_store(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - - bool success = platform_cmpxchg32(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before_store(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - - bool success = platform_cmpxchg32(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before_store(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - - bool success = platform_cmpxchg32(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - while (true) - { - value_type tmp = expected; - if (compare_exchange_weak(tmp, desired, success_order, failure_order)) - return true; - if (tmp != expected) - { - expected = tmp; - return false; - } - } - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/cas64strong-ptr.hpp b/utils/boost_idb/boost/atomic/detail/cas64strong-ptr.hpp deleted file mode 100644 index 2f04112a..00000000 --- a/utils/boost_idb/boost/atomic/detail/cas64strong-ptr.hpp +++ /dev/null @@ -1,247 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_CAS64STRONG_PTR_HPP -#define BOOST_ATOMIC_DETAIL_CAS64STRONG_PTR_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann - -// Build 64-bit atomic operation on pointers from platform_cmpxchg64_strong -// primitive. It is assumed that 64-bit loads/stores are not -// atomic, so they are implemented through platform_load64/platform_store64. -// -// The reason for extracting pointer specializations to a separate header is -// that 64-bit CAS is available on some 32-bit platforms (notably, x86). -// On these platforms there is no need for 64-bit pointer specializations, -// since they will never be used. - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -/* pointer types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef void * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - platform_store64(v, &v_); - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = platform_load64(&v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg64_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, (char*)original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, (char*)original - v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - platform_store64(v, &v_); - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = platform_load64(&v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg64_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/cas64strong.hpp b/utils/boost_idb/boost/atomic/detail/cas64strong.hpp deleted file mode 100644 index c283f986..00000000 --- a/utils/boost_idb/boost/atomic/detail/cas64strong.hpp +++ /dev/null @@ -1,264 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_CAS64STRONG_HPP -#define BOOST_ATOMIC_DETAIL_CAS64STRONG_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann - -// Build 64-bit atomic operation on integers/UDTs from platform_cmpxchg64_strong -// primitive. It is assumed that 64-bit loads/stores are not -// atomic, so they are implemented through platform_load64/platform_store64. - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -/* integral types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before_store(order); - platform_store64(v, &v_); - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = platform_load64(&v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - - bool success = platform_cmpxchg64_strong(expected, desired, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - } - - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original + v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original - v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original & v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original | v, order, memory_order_relaxed)); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, original ^ v, order, memory_order_relaxed)); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* generic types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint64_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& value, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type value_s = 0; - memcpy(&value_s, &value, sizeof(value_type)); - platform_fence_before_store(order); - platform_store64(value_s, &v_); - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type value_s = platform_load64(&v_); - platform_fence_after_load(order); - value_type value; - memcpy(&value, &value_s, sizeof(value_type)); - return value; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original = load(memory_order_relaxed); - do { - } while (!compare_exchange_weak(original, v, order, memory_order_relaxed)); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - platform_fence_before(success_order); - bool success = platform_cmpxchg64_strong(expected_s, desired_s, &v_); - - if (success) { - platform_fence_after(success_order); - } else { - platform_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - } - - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/config.hpp b/utils/boost_idb/boost/atomic/detail/config.hpp deleted file mode 100644 index b1984e52..00000000 --- a/utils/boost_idb/boost/atomic/detail/config.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_CONFIG_HPP -#define BOOST_ATOMIC_DETAIL_CONFIG_HPP - -// Copyright (c) 2012 Hartmut Kaiser -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/gcc-alpha.hpp b/utils/boost_idb/boost/atomic/detail/gcc-alpha.hpp deleted file mode 100644 index 27754997..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-alpha.hpp +++ /dev/null @@ -1,368 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GCC_ALPHA_HPP -#define BOOST_ATOMIC_DETAIL_GCC_ALPHA_HPP - -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -/* - Refer to http://h71000.www7.hp.com/doc/82final/5601/5601pro_004.html - (HP OpenVMS systems documentation) and the alpha reference manual. - */ - -/* - NB: The most natural thing would be to write the increment/decrement - operators along the following lines: - - __asm__ __volatile__( - "1: ldl_l %0,%1 \n" - "addl %0,1,%0 \n" - "stl_c %0,%1 \n" - "beq %0,1b\n" - : "=&b" (tmp) - : "m" (value) - : "cc" - ); - - However according to the comments on the HP website and matching - comments in the Linux kernel sources this defies branch prediction, - as the cpu assumes that backward branches are always taken; so - instead copy the trick from the Linux kernel, introduce a forward - branch and back again. - - I have, however, had a hard time measuring the difference between - the two versions in microbenchmarks -- I am leaving it in nevertheless - as it apparently does not hurt either. -*/ - -namespace boost { -namespace atomics { -namespace detail { - -inline void fence_before(memory_order order) -{ - switch(order) { - case memory_order_consume: - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - __asm__ __volatile__ ("mb" ::: "memory"); - default:; - } -} - -inline void fence_after(memory_order order) -{ - switch(order) { - case memory_order_acquire: - case memory_order_acq_rel: - case memory_order_seq_cst: - __asm__ __volatile__ ("mb" ::: "memory"); - default:; - } -} - -template<> -inline void platform_atomic_thread_fence(memory_order order) -{ - switch(order) { - case memory_order_acquire: - case memory_order_consume: - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - __asm__ __volatile__ ("mb" ::: "memory"); - default:; - } -} - -template -class atomic_alpha_32 -{ -public: - typedef T integral_type; - BOOST_CONSTEXPR atomic_alpha_32(T v) BOOST_NOEXCEPT: i(v) {} - atomic_alpha_32() {} - T load(memory_order order=memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - T v=*reinterpret_cast(&i); - fence_after(order); - return v; - } - void store(T v, memory_order order=memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - fence_before(order); - *reinterpret_cast(&i)=(int)v; - } - bool compare_exchange_weak( - T &expected, - T desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - fence_before(success_order); - int current, success; - __asm__ __volatile__( - "1: ldl_l %2, %4\n" - "cmpeq %2, %0, %3\n" - "mov %2, %0\n" - "beq %3, 3f\n" - "stl_c %1, %4\n" - "2:\n" - - ".subsection 2\n" - "3: mov %3, %1\n" - "br 2b\n" - ".previous\n" - - : "+&r" (expected), "+&r" (desired), "=&r"(current), "=&r"(success) - : "m" (i) - : - ); - if (desired) fence_after(success_order); - else fence_after(failure_order); - return desired; - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT {return true;} -protected: - inline T fetch_add_var(T c, memory_order order) volatile BOOST_NOEXCEPT - { - fence_before(order); - T original, modified; - __asm__ __volatile__( - "1: ldl_l %0, %2\n" - "addl %0, %3, %1\n" - "stl_c %1, %2\n" - "beq %1, 2f\n" - - ".subsection 2\n" - "2: br 1b\n" - ".previous\n" - - : "=&r" (original), "=&r" (modified) - : "m" (i), "r" (c) - : - ); - fence_after(order); - return original; - } - inline T fetch_inc(memory_order order) volatile BOOST_NOEXCEPT - { - fence_before(order); - int original, modified; - __asm__ __volatile__( - "1: ldl_l %0, %2\n" - "addl %0, 1, %1\n" - "stl_c %1, %2\n" - "beq %1, 2f\n" - - ".subsection 2\n" - "2: br 1b\n" - ".previous\n" - - : "=&r" (original), "=&r" (modified) - : "m" (i) - : - ); - fence_after(order); - return original; - } - inline T fetch_dec(memory_order order) volatile BOOST_NOEXCEPT - { - fence_before(order); - int original, modified; - __asm__ __volatile__( - "1: ldl_l %0, %2\n" - "subl %0, 1, %1\n" - "stl_c %1, %2\n" - "beq %1, 2f\n" - - ".subsection 2\n" - "2: br 1b\n" - ".previous\n" - - : "=&r" (original), "=&r" (modified) - : "m" (i) - : - ); - fence_after(order); - return original; - } -private: - T i; -}; - -template -class atomic_alpha_64 -{ -public: - typedef T integral_type; - BOOST_CONSTEXPR atomic_alpha_64(T v) BOOST_NOEXCEPT: i(v) {} - atomic_alpha_64() {} - T load(memory_order order=memory_order_seq_cst) const volatile - { - T v=*reinterpret_cast(&i); - fence_after(order); - return v; - } - void store(T v, memory_order order=memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - fence_before(order); - *reinterpret_cast(&i)=v; - } - bool compare_exchange_weak( - T &expected, - T desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - fence_before(success_order); - int current, success; - __asm__ __volatile__( - "1: ldq_l %2, %4\n" - "cmpeq %2, %0, %3\n" - "mov %2, %0\n" - "beq %3, 3f\n" - "stq_c %1, %4\n" - "2:\n" - - ".subsection 2\n" - "3: mov %3, %1\n" - "br 2b\n" - ".previous\n" - - : "+&r" (expected), "+&r" (desired), "=&r"(current), "=&r"(success) - : "m" (i) - : - ); - if (desired) fence_after(success_order); - else fence_after(failure_order); - return desired; - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT {return true;} -protected: - inline T fetch_add_var(T c, memory_order order) volatile BOOST_NOEXCEPT - { - fence_before(order); - T original, modified; - __asm__ __volatile__( - "1: ldq_l %0, %2\n" - "addq %0, %3, %1\n" - "stq_c %1, %2\n" - "beq %1, 2f\n" - - ".subsection 2\n" - "2: br 1b\n" - ".previous\n" - - : "=&r" (original), "=&r" (modified) - : "m" (i), "r" (c) - : - ); - fence_after(order); - return original; - } - inline T fetch_inc(memory_order order) volatile BOOST_NOEXCEPT - { - fence_before(order); - T original, modified; - __asm__ __volatile__( - "1: ldq_l %0, %2\n" - "addq %0, 1, %1\n" - "stq_c %1, %2\n" - "beq %1, 2f\n" - - ".subsection 2\n" - "2: br 1b\n" - ".previous\n" - - : "=&r" (original), "=&r" (modified) - : "m" (i) - : - ); - fence_after(order); - return original; - } - inline T fetch_dec(memory_order order) volatile BOOST_NOEXCEPT - { - fence_before(order); - T original, modified; - __asm__ __volatile__( - "1: ldq_l %0, %2\n" - "subq %0, 1, %1\n" - "stq_c %1, %2\n" - "beq %1, 2f\n" - - ".subsection 2\n" - "2: br 1b\n" - ".previous\n" - - : "=&r" (original), "=&r" (modified) - : "m" (i) - : - ); - fence_after(order); - return original; - } -private: - T i; -}; - -template -class platform_atomic_integral : - public build_atomic_from_typical > > -{ -public: - typedef build_atomic_from_typical > > super; - BOOST_CONSTEXPR platform_atomic_integral(T v) BOOST_NOEXCEPT: super(v) {} - platform_atomic_integral(void) {} -}; - -template -class platform_atomic_integral : - public build_atomic_from_typical > > -{ -public: - typedef build_atomic_from_typical > > super; - BOOST_CONSTEXPR platform_atomic_integral(T v) BOOST_NOEXCEPT: super(v) {} - platform_atomic_integral(void) {} -}; - -template -class platform_atomic_integral : - public build_atomic_from_larger_type, T> -{ -public: - typedef build_atomic_from_larger_type, T> super; - BOOST_CONSTEXPR platform_atomic_integral(T v) BOOST_NOEXCEPT: super(v) {} - platform_atomic_integral(void) {} -}; - -template -class platform_atomic_integral : - public build_atomic_from_larger_type, T> -{ -public: - typedef build_atomic_from_larger_type, T> super; - BOOST_CONSTEXPR platform_atomic_integral(T v) BOOST_NOEXCEPT: super(v) {} - platform_atomic_integral(void) {} -}; - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/gcc-armv6plus.hpp b/utils/boost_idb/boost/atomic/detail/gcc-armv6plus.hpp deleted file mode 100644 index cccd1111..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-armv6plus.hpp +++ /dev/null @@ -1,255 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GCC_ARMV6PLUS_HPP -#define BOOST_ATOMIC_DETAIL_GCC_ARMV6PLUS_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2009 Phil Endecott -// Copyright (c) 2013 Tim Blechmann -// ARM Code by Phil Endecott, based on other architectures. - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -// From the ARM Architecture Reference Manual for architecture v6: -// -// LDREX{} , [] -// Specifies the destination register for the memory word addressed by -// Specifies the register containing the address. -// -// STREX{} , , [] -// Specifies the destination register for the returned status value. -// 0 if the operation updates memory -// 1 if the operation fails to update memory -// Specifies the register containing the word to be stored to memory. -// Specifies the register containing the address. -// Rd must not be the same register as Rm or Rn. -// -// ARM v7 is like ARM v6 plus: -// There are half-word and byte versions of the LDREX and STREX instructions, -// LDREXH, LDREXB, STREXH and STREXB. -// There are also double-word versions, LDREXD and STREXD. -// (Actually it looks like these are available from version 6k onwards.) -// FIXME these are not yet used; should be mostly a matter of copy-and-paste. -// I think you can supply an immediate offset to the address. -// -// A memory barrier is effected using a "co-processor 15" instruction, -// though a separate assembler mnemonic is available for it in v7. - -namespace boost { -namespace atomics { -namespace detail { - -// "Thumb 1" is a subset of the ARM instruction set that uses a 16-bit encoding. It -// doesn't include all instructions and in particular it doesn't include the co-processor -// instruction used for the memory barrier or the load-locked/store-conditional -// instructions. So, if we're compiling in "Thumb 1" mode, we need to wrap all of our -// asm blocks with code to temporarily change to ARM mode. -// -// You can only change between ARM and Thumb modes when branching using the bx instruction. -// bx takes an address specified in a register. The least significant bit of the address -// indicates the mode, so 1 is added to indicate that the destination code is Thumb. -// A temporary register is needed for the address and is passed as an argument to these -// macros. It must be one of the "low" registers accessible to Thumb code, specified -// using the "l" attribute in the asm statement. -// -// Architecture v7 introduces "Thumb 2", which does include (almost?) all of the ARM -// instruction set. So in v7 we don't need to change to ARM mode; we can write "universal -// assembler" which will assemble to Thumb 2 or ARM code as appropriate. The only thing -// we need to do to make this "universal" assembler mode work is to insert "IT" instructions -// to annotate the conditional instructions. These are ignored in other modes (e.g. v6), -// so they can always be present. - -#if defined(__thumb__) && !defined(__thumb2__) -#define BOOST_ATOMIC_ARM_ASM_START(TMPREG) "adr " #TMPREG ", 1f\n" "bx " #TMPREG "\n" ".arm\n" ".align 4\n" "1: " -#define BOOST_ATOMIC_ARM_ASM_END(TMPREG) "adr " #TMPREG ", 1f + 1\n" "bx " #TMPREG "\n" ".thumb\n" ".align 2\n" "1: " -#else -// The tmpreg is wasted in this case, which is non-optimal. -#define BOOST_ATOMIC_ARM_ASM_START(TMPREG) -#define BOOST_ATOMIC_ARM_ASM_END(TMPREG) -#endif - -#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7S__) -#define BOOST_ATOMIC_ARM_DMB "dmb\n" -#else -#define BOOST_ATOMIC_ARM_DMB "mcr\tp15, 0, r0, c7, c10, 5\n" -#endif - -inline void -arm_barrier(void) BOOST_NOEXCEPT -{ - int brtmp; - __asm__ __volatile__ - ( - BOOST_ATOMIC_ARM_ASM_START(%0) - BOOST_ATOMIC_ARM_DMB - BOOST_ATOMIC_ARM_ASM_END(%0) - : "=&l" (brtmp) :: "memory" - ); -} - -inline void -platform_fence_before(memory_order order) BOOST_NOEXCEPT -{ - switch(order) - { - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - arm_barrier(); - case memory_order_consume: - default:; - } -} - -inline void -platform_fence_after(memory_order order) BOOST_NOEXCEPT -{ - switch(order) - { - case memory_order_acquire: - case memory_order_acq_rel: - case memory_order_seq_cst: - arm_barrier(); - default:; - } -} - -inline void -platform_fence_before_store(memory_order order) BOOST_NOEXCEPT -{ - platform_fence_before(order); -} - -inline void -platform_fence_after_store(memory_order order) BOOST_NOEXCEPT -{ - if (order == memory_order_seq_cst) - arm_barrier(); -} - -inline void -platform_fence_after_load(memory_order order) BOOST_NOEXCEPT -{ - platform_fence_after(order); -} - -template -inline bool -platform_cmpxchg32(T & expected, T desired, volatile T * ptr) BOOST_NOEXCEPT -{ - int success; - int tmp; - __asm__ __volatile__ - ( - BOOST_ATOMIC_ARM_ASM_START(%2) - "mov %1, #0\n" // success = 0 - "ldrex %0, %3\n" // expected' = *(&i) - "teq %0, %4\n" // flags = expected'==expected - "ittt eq\n" - "strexeq %2, %5, %3\n" // if (flags.equal) *(&i) = desired, tmp = !OK - "teqeq %2, #0\n" // if (flags.equal) flags = tmp==0 - "moveq %1, #1\n" // if (flags.equal) success = 1 - BOOST_ATOMIC_ARM_ASM_END(%2) - : "=&r" (expected), // %0 - "=&r" (success), // %1 - "=&l" (tmp), // %2 - "+Q" (*ptr) // %3 - : "r" (expected), // %4 - "r" (desired) // %5 - : "cc" - ); - return success; -} - -} -} - -#define BOOST_ATOMIC_THREAD_FENCE 2 -inline void -atomic_thread_fence(memory_order order) -{ - switch(order) - { - case memory_order_acquire: - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - atomics::detail::arm_barrier(); - default:; - } -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -inline void -atomic_signal_fence(memory_order) -{ - __asm__ __volatile__ ("" ::: "memory"); -} - -class atomic_flag -{ -private: - uint32_t v_; - -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before_store(order); - const_cast(v_) = 0; - atomics::detail::platform_fence_after_store(order); - } - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before(order); - uint32_t expected = v_; - do { - if (expected == 1) - break; - } while (!atomics::detail::platform_cmpxchg32(expected, (uint32_t)1, &v_)); - atomics::detail::platform_fence_after(order); - return expected; - } - - BOOST_DELETED_FUNCTION(atomic_flag(const atomic_flag &)) - BOOST_DELETED_FUNCTION(atomic_flag& operator=(const atomic_flag &)) -}; - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -} - -#undef BOOST_ATOMIC_ARM_ASM_START -#undef BOOST_ATOMIC_ARM_ASM_END - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2 -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 -#define BOOST_ATOMIC_LLONG_LOCK_FREE 0 -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -#include - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/gcc-atomic.hpp b/utils/boost_idb/boost/atomic/detail/gcc-atomic.hpp deleted file mode 100644 index 5cd7f8f6..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-atomic.hpp +++ /dev/null @@ -1,1204 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GCC_ATOMIC_HPP -#define BOOST_ATOMIC_DETAIL_GCC_ATOMIC_HPP - -// Copyright (c) 2013 Andrey Semashev -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -#if (defined(__i386__) && defined(__SSE2__)) || defined(__x86_64__) -#define BOOST_ATOMIC_X86_PAUSE() __asm__ __volatile__ ("pause\n") -#endif - -#if defined(__i386__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) -#define BOOST_ATOMIC_X86_HAS_CMPXCHG8B 1 -#endif - -#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) -#define BOOST_ATOMIC_X86_HAS_CMPXCHG16B 1 -#endif - -BOOST_FORCEINLINE BOOST_CONSTEXPR int convert_memory_order_to_gcc(memory_order order) BOOST_NOEXCEPT -{ - return (order == memory_order_relaxed ? __ATOMIC_RELAXED : (order == memory_order_consume ? __ATOMIC_CONSUME : - (order == memory_order_acquire ? __ATOMIC_ACQUIRE : (order == memory_order_release ? __ATOMIC_RELEASE : - (order == memory_order_acq_rel ? __ATOMIC_ACQ_REL : __ATOMIC_SEQ_CST))))); -} - -} // namespace detail -} // namespace atomics - -#if __GCC_ATOMIC_BOOL_LOCK_FREE == 2 - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - bool v_; - -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(false) {} - - bool test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_test_and_set(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - void clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_clear((bool*)&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } -}; - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -#endif // __GCC_ATOMIC_BOOL_LOCK_FREE == 2 - -} // namespace boost - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#if __GCC_ATOMIC_CHAR_LOCK_FREE == 2 -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_CHAR16_T_LOCK_FREE == 2 -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_CHAR32_T_LOCK_FREE == 2 -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_WCHAR_T_LOCK_FREE == 2 -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_SHORT_LOCK_FREE == 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_INT_LOCK_FREE == 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_LONG_LOCK_FREE == 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_LLONG_LOCK_FREE == 2 -#define BOOST_ATOMIC_LLONG_LOCK_FREE 2 -#endif -#if defined(BOOST_ATOMIC_X86_HAS_CMPXCHG16B) && (defined(BOOST_HAS_INT128) || !defined(BOOST_NO_ALIGNMENT)) -#define BOOST_ATOMIC_INT128_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_POINTER_LOCK_FREE == 2 -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#endif -#if __GCC_ATOMIC_BOOL_LOCK_FREE == 2 -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 -#endif - -namespace boost { - -#define BOOST_ATOMIC_THREAD_FENCE 2 -BOOST_FORCEINLINE void atomic_thread_fence(memory_order order) -{ - __atomic_thread_fence(atomics::detail::convert_memory_order_to_gcc(order)); -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -BOOST_FORCEINLINE void atomic_signal_fence(memory_order order) -{ - __atomic_signal_fence(atomics::detail::convert_memory_order_to_gcc(order)); -} - -namespace atomics { -namespace detail { - -#if defined(BOOST_ATOMIC_CHAR_LOCK_FREE) && BOOST_ATOMIC_CHAR_LOCK_FREE > 0 - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_and(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_or(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_xor(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint8_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : - v_(reinterpret_cast(v)) - { - } - - void store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store(&v_, (storage_type*)&v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __atomic_load(&v_, (storage_type*)&v, atomics::detail::convert_memory_order_to_gcc(order)); - return v; - } - - value_type exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type r; - __atomic_exchange(&v_, (storage_type*)&v, (storage_type*)&r, atomics::detail::convert_memory_order_to_gcc(order)); - return r; - } - - bool compare_exchange_strong( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange(&v_, (storage_type*)&expected, (storage_type*)&desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange(&v_, (storage_type*)&expected, (storage_type*)&desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif // defined(BOOST_ATOMIC_CHAR_LOCK_FREE) && BOOST_ATOMIC_CHAR_LOCK_FREE > 0 - -#if defined(BOOST_ATOMIC_SHORT_LOCK_FREE) && BOOST_ATOMIC_SHORT_LOCK_FREE > 0 - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_and(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_or(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_xor(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint16_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : - v_(reinterpret_cast(v)) - { - } - - void store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store(&v_, (storage_type*)&v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __atomic_load(&v_, (storage_type*)&v, atomics::detail::convert_memory_order_to_gcc(order)); - return v; - } - - value_type exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type r; - __atomic_exchange(&v_, (storage_type*)&v, (storage_type*)&r, atomics::detail::convert_memory_order_to_gcc(order)); - return r; - } - - bool compare_exchange_strong( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange(&v_, (storage_type*)&expected, (storage_type*)&desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange(&v_, (storage_type*)&expected, (storage_type*)&desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif // defined(BOOST_ATOMIC_SHORT_LOCK_FREE) && BOOST_ATOMIC_SHORT_LOCK_FREE > 0 - -#if defined(BOOST_ATOMIC_INT_LOCK_FREE) && BOOST_ATOMIC_INT_LOCK_FREE > 0 - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_and(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_or(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_xor(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - __atomic_store_n(&v_, tmp, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - tmp = __atomic_exchange_n(&v_, tmp, atomics::detail::convert_memory_order_to_gcc(order)); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool compare_exchange_strong( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - const bool success = __atomic_compare_exchange_n(&v_, &expected_s, desired_s, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool compare_exchange_weak( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - const bool success = __atomic_compare_exchange_n(&v_, &expected_s, desired_s, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif // defined(BOOST_ATOMIC_INT_LOCK_FREE) && BOOST_ATOMIC_INT_LOCK_FREE > 0 - -#if defined(BOOST_ATOMIC_LLONG_LOCK_FREE) && BOOST_ATOMIC_LLONG_LOCK_FREE > 0 - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_and(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_or(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_xor(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint64_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - __atomic_store_n(&v_, tmp, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - tmp = __atomic_exchange_n(&v_, tmp, atomics::detail::convert_memory_order_to_gcc(order)); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool compare_exchange_strong( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - const bool success = __atomic_compare_exchange_n(&v_, &expected_s, desired_s, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool compare_exchange_weak( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - const bool success = __atomic_compare_exchange_n(&v_, &expected_s, desired_s, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif // defined(BOOST_ATOMIC_LLONG_LOCK_FREE) && BOOST_ATOMIC_LLONG_LOCK_FREE > 0 - -#if defined(BOOST_ATOMIC_INT128_LOCK_FREE) && BOOST_ATOMIC_INT128_LOCK_FREE > 0 - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_and(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_or(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_xor(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#if defined(BOOST_HAS_INT128) - -typedef boost::uint128_type storage128_type; - -#else // defined(BOOST_HAS_INT128) - -struct BOOST_ALIGNMENT(16) storage128_type -{ - uint64_t data[2]; -}; - -inline bool operator== (storage128_type const& left, storage128_type const& right) -{ - return left.data[0] == right.data[0] && left.data[1] == right.data[1]; -} -inline bool operator!= (storage128_type const& left, storage128_type const& right) -{ - return !(left == right); -} - -#endif // defined(BOOST_HAS_INT128) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef storage128_type storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - __atomic_store_n(&v_, tmp, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - tmp = __atomic_exchange_n(&v_, tmp, atomics::detail::convert_memory_order_to_gcc(order)); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool compare_exchange_strong( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - const bool success = __atomic_compare_exchange_n(&v_, &expected_s, desired_s, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool compare_exchange_weak( - value_type& expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - const bool success = __atomic_compare_exchange_n(&v_, &expected_s, desired_s, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif // defined(BOOST_ATOMIC_INT128_LOCK_FREE) && BOOST_ATOMIC_INT128_LOCK_FREE > 0 - - -/* pointers */ - -#if defined(BOOST_ATOMIC_POINTER_LOCK_FREE) && BOOST_ATOMIC_POINTER_LOCK_FREE > 0 - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T* value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v * sizeof(T), atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v * sizeof(T), atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef void* value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - __atomic_store_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - return __atomic_load_n(&v_, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_add(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_fetch_sub(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return __atomic_exchange_n(&v_, v, atomics::detail::convert_memory_order_to_gcc(order)); - } - - bool compare_exchange_strong( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, false, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool compare_exchange_weak( - value_type& expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return __atomic_compare_exchange_n(&v_, &expected, desired, true, - atomics::detail::convert_memory_order_to_gcc(success_order), - atomics::detail::convert_memory_order_to_gcc(failure_order)); - } - - bool is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return __atomic_is_lock_free(sizeof(v_), &v_); - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#endif // defined(BOOST_ATOMIC_POINTER_LOCK_FREE) && BOOST_ATOMIC_POINTER_LOCK_FREE > 0 - -} // namespace detail -} // namespace atomics -} // namespace boost - -#endif // !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#endif // BOOST_ATOMIC_DETAIL_GCC_ATOMIC_HPP diff --git a/utils/boost_idb/boost/atomic/detail/gcc-cas.hpp b/utils/boost_idb/boost/atomic/detail/gcc-cas.hpp deleted file mode 100644 index 25626bd5..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-cas.hpp +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2011 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// Use the gnu builtin __sync_val_compare_and_swap to build -// atomic operations for 32 bit and smaller. - -#ifndef BOOST_ATOMIC_DETAIL_GENERIC_CAS_HPP -#define BOOST_ATOMIC_DETAIL_GENERIC_CAS_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { - -#define BOOST_ATOMIC_THREAD_FENCE 2 -inline void -atomic_thread_fence(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - break; - case memory_order_release: - case memory_order_consume: - case memory_order_acquire: - case memory_order_acq_rel: - case memory_order_seq_cst: - __sync_synchronize(); - break; - } -} - -namespace atomics { -namespace detail { - -inline void -platform_fence_before(memory_order) -{ - /* empty, as compare_and_swap is synchronizing already */ -} - -inline void -platform_fence_after(memory_order) -{ - /* empty, as compare_and_swap is synchronizing already */ -} - -inline void -platform_fence_before_store(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_acquire: - case memory_order_consume: - break; - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - __sync_synchronize(); - break; - } -} - -inline void -platform_fence_after_store(memory_order order) -{ - if (order == memory_order_seq_cst) - __sync_synchronize(); -} - -inline void -platform_fence_after_load(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_release: - break; - case memory_order_consume: - case memory_order_acquire: - case memory_order_acq_rel: - case memory_order_seq_cst: - __sync_synchronize(); - break; - } -} - -template -inline bool -platform_cmpxchg32_strong(T & expected, T desired, volatile T * ptr) -{ - T found = __sync_val_compare_and_swap(ptr, expected, desired); - bool success = (found == expected); - expected = found; - return success; -} - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - uint32_t v_; -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before_store(order); - const_cast(v_) = 0; - atomics::detail::platform_fence_after_store(order); - } - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before(order); - uint32_t expected = v_; - do { - if (expected == 1) - break; - } while (!atomics::detail::platform_cmpxchg32(expected, (uint32_t)1, &v_)); - atomics::detail::platform_fence_after(order); - return expected; - } -}; - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -} -} -} - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE (sizeof(long) <= 4 ? 2 : 0) -#define BOOST_ATOMIC_LLONG_LOCK_FREE (sizeof(long long) <= 4 ? 2 : 0) -#define BOOST_ATOMIC_POINTER_LOCK_FREE (sizeof(void *) <= 4 ? 2 : 0) -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -#include - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/gcc-ppc.hpp b/utils/boost_idb/boost/atomic/detail/gcc-ppc.hpp deleted file mode 100644 index e6735dab..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-ppc.hpp +++ /dev/null @@ -1,2952 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GCC_PPC_HPP -#define BOOST_ATOMIC_DETAIL_GCC_PPC_HPP - -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -/* - Refer to: Motorola: "Programming Environments Manual for 32-Bit - Implementations of the PowerPC Architecture", Appendix E: - "Synchronization Programming Examples" for an explanation of what is - going on here (can be found on the web at various places by the - name "MPCFPE32B.pdf", Google is your friend...) - - Most of the atomic operations map to instructions in a relatively - straight-forward fashion, but "load"s may at first glance appear - a bit strange as they map to: - - lwz %rX, addr - cmpw %rX, %rX - bne- 1f - 1: - - That is, the CPU is forced to perform a branch that "formally" depends - on the value retrieved from memory. This scheme has an overhead of - about 1-2 clock cycles per load, but it allows to map "acquire" to - the "isync" instruction instead of "sync" uniformly and for all type - of atomic operations. Since "isync" has a cost of about 15 clock - cycles, while "sync" hast a cost of about 50 clock cycles, the small - penalty to atomic loads more than compensates for this. - - Byte- and halfword-sized atomic values are realized by encoding the - value to be represented into a word, performing sign/zero extension - as appropriate. This means that after add/sub operations the value - needs fixing up to accurately preserve the wrap-around semantic of - the smaller type. (Nothing special needs to be done for the bit-wise - and the "exchange type" operators as the compiler already sees to - it that values carried in registers are extended appropriately and - everything falls into place naturally). - - The register constraint "b" instructs gcc to use any register - except r0; this is sometimes required because the encoding for - r0 is used to signify "constant zero" in a number of instructions, - making r0 unusable in this place. For simplicity this constraint - is used everywhere since I am to lazy to look this up on a - per-instruction basis, and ppc has enough registers for this not - to pose a problem. -*/ - -namespace boost { -namespace atomics { -namespace detail { - -inline void -ppc_fence_before(memory_order order) -{ - switch(order) - { - case memory_order_release: - case memory_order_acq_rel: -#if defined(__powerpc64__) - __asm__ __volatile__ ("lwsync" ::: "memory"); - break; -#endif - case memory_order_seq_cst: - __asm__ __volatile__ ("sync" ::: "memory"); - default:; - } -} - -inline void -ppc_fence_after(memory_order order) -{ - switch(order) - { - case memory_order_acquire: - case memory_order_acq_rel: - case memory_order_seq_cst: - __asm__ __volatile__ ("isync"); - case memory_order_consume: - __asm__ __volatile__ ("" ::: "memory"); - default:; - } -} - -inline void -ppc_fence_after_store(memory_order order) -{ - switch(order) - { - case memory_order_seq_cst: - __asm__ __volatile__ ("sync"); - default:; - } -} - -} -} - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - uint32_t v_; -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::ppc_fence_before(order); - const_cast(v_) = 0; - atomics::detail::ppc_fence_after_store(order); - } - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - uint32_t original; - atomics::detail::ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (1) - : "cr0" - ); - atomics::detail::ppc_fence_after(order); - return original; - } -}; - -} /* namespace boost */ - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2 -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#if defined(__powerpc64__) -#define BOOST_ATOMIC_LLONG_LOCK_FREE 2 -#else -#define BOOST_ATOMIC_LLONG_LOCK_FREE 0 -#endif -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -/* Would like to move the slow-path of failed compare_exchange -(that clears the "success" bit) out-of-line. gcc can in -principle do that using ".subsection"/".previous", but Apple's -binutils seemingly does not understand that. Therefore wrap -the "clear" of the flag in a macro and let it remain -in-line for Apple -*/ - -#if !defined(__APPLE__) - -#define BOOST_ATOMIC_ASM_SLOWPATH_CLEAR \ - "9:\n" \ - ".subsection 2\n" \ - "2: addi %1,0,0\n" \ - "b 9b\n" \ - ".previous\n" \ - -#else - -#define BOOST_ATOMIC_ASM_SLOWPATH_CLEAR \ - "b 9f\n" \ - "2: addi %1,0,0\n" \ - "9:\n" \ - -#endif - -namespace boost { -namespace atomics { -namespace detail { - -/* integral types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef int32_t storage_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m"(v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=&r" (v) - : "m" (v_) - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "extsb %1, %1\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "extsb %1, %1\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "and %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "or %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "xor %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m"(v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=&r" (v) - : "m" (v_) - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "rlwinm %1, %1, 0, 0xff\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "rlwinm %1, %1, 0, 0xff\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "and %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "or %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "xor %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef int32_t storage_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m"(v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=&r" (v) - : "m" (v_) - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "extsh %1, %1\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "extsh %1, %1\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "and %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "or %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "xor %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m"(v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=&r" (v) - : "m" (v_) - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "rlwinm %1, %1, 0, 0xffff\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "rlwinm %1, %1, 0, 0xffff\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "and %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "or %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "xor %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - const_cast(v_) = v; - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - __asm__ __volatile__ ( - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "+b"(v) - : - : "cr0" - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "and %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "or %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "xor %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#if defined(__powerpc64__) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - const_cast(v_) = v; - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - __asm__ __volatile__ ( - "cmpd %0, %0\n" - "bne- 1f\n" - "1:\n" - : "+b"(v) - : - : "cr0" - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y1\n" - "stdcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "add %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "sub %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "and %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "or %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "xor %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#endif - -/* pointer types */ - -#if !defined(__powerpc64__) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void * value_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m" (v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(v) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m" (v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(v) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "add %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y2\n" - "sub %1,%0,%3\n" - "stwcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#else - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void * value_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "std %1, %0\n" - : "+m" (v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ ( - "ld %0, %1\n" - "cmpd %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(v) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y1\n" - "stdcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "add %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "sub %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - ppc_fence_before(order); - __asm__ ( - "std %1, %0\n" - : "+m" (v_) - : "r" (v) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v; - __asm__ ( - "ld %0, %1\n" - "cmpd %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(v) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type original; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y1\n" - "stdcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (v) - : "cr0" - ); - ppc_fence_after(order); - return original; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - int success; - ppc_fence_before(success_order); - __asm__( - "0: ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected), "=&b" (success), "+Z"(v_) - : "b" (expected), "b" (desired) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - return success; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "add %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - value_type original, tmp; - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y2\n" - "sub %1,%0,%3\n" - "stdcx. %1,%y2\n" - "bne- 1b\n" - : "=&b" (original), "=&b" (tmp), "+Z"(v_) - : "b" (v) - : "cc"); - ppc_fence_after(order); - return original; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#endif - -/* generic */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m" (v_) - : "r" (tmp) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(tmp) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0, original; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (tmp) - : "cr0" - ); - ppc_fence_after(order); - value_type res; - memcpy(&res, &original, sizeof(value_type)); - return res; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m" (v_) - : "r" (tmp) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(tmp) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0, original; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (tmp) - : "cr0" - ); - ppc_fence_after(order); - value_type res; - memcpy(&res, &original, sizeof(value_type)); - return res; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "stw %1, %0\n" - : "+m" (v_) - : "r" (tmp) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp; - __asm__ __volatile__ ( - "lwz %0, %1\n" - "cmpw %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(tmp) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0, original; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "1:\n" - "lwarx %0,%y1\n" - "stwcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (tmp) - : "cr0" - ); - ppc_fence_after(order); - value_type res; - memcpy(&res, &original, sizeof(value_type)); - return res; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "0: lwarx %0,%y2\n" - "cmpw %0, %3\n" - "bne- 2f\n" - "stwcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#if defined(__powerpc64__) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint64_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "std %1, %0\n" - : "+m" (v_) - : "r" (tmp) - ); - ppc_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp; - __asm__ __volatile__ ( - "ld %0, %1\n" - "cmpd %0, %0\n" - "bne- 1f\n" - "1:\n" - : "=r"(tmp) - : "m"(v_) - : "cr0" - ); - ppc_fence_after(order); - - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0, original; - memcpy(&tmp, &v, sizeof(value_type)); - ppc_fence_before(order); - __asm__ ( - "1:\n" - "ldarx %0,%y1\n" - "stdcx. %2,%y1\n" - "bne- 1b\n" - : "=&b" (original), "+Z"(v_) - : "b" (tmp) - : "cr0" - ); - ppc_fence_after(order); - value_type res; - memcpy(&res, &original, sizeof(value_type)); - return res; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s, desired_s; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 2f\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s, desired_s; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - - int success; - ppc_fence_before(success_order); - __asm__( - "0: ldarx %0,%y2\n" - "cmpd %0, %3\n" - "bne- 2f\n" - "stdcx. %4,%y2\n" - "bne- 0b\n" - "addi %1,0,1\n" - "1:" - - BOOST_ATOMIC_ASM_SLOWPATH_CLEAR - : "=&b" (expected_s), "=&b" (success), "+Z"(v_) - : "b" (expected_s), "b" (desired_s) - : "cr0" - ); - if (success) - ppc_fence_after(success_order); - else - ppc_fence_after(failure_order); - memcpy(&expected, &expected_s, sizeof(value_type)); - return success; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif - -} -} - -#define BOOST_ATOMIC_THREAD_FENCE 2 -inline void -atomic_thread_fence(memory_order order) -{ - switch(order) - { - case memory_order_acquire: - __asm__ __volatile__ ("isync" ::: "memory"); - break; - case memory_order_release: -#if defined(__powerpc64__) - __asm__ __volatile__ ("lwsync" ::: "memory"); - break; -#endif - case memory_order_acq_rel: - case memory_order_seq_cst: - __asm__ __volatile__ ("sync" ::: "memory"); - default:; - } -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -inline void -atomic_signal_fence(memory_order order) -{ - switch(order) - { - case memory_order_acquire: - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - __asm__ __volatile__ ("" ::: "memory"); - break; - default:; - } -} - -} - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/gcc-sparcv9.hpp b/utils/boost_idb/boost/atomic/detail/gcc-sparcv9.hpp deleted file mode 100644 index b3fc7e6a..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-sparcv9.hpp +++ /dev/null @@ -1,1333 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GCC_SPARC_HPP -#define BOOST_ATOMIC_DETAIL_GCC_SPARC_HPP - -// Copyright (c) 2010 Helge Bahmann -// Copyright (c) 2013 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -inline void -platform_fence_before(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_acquire: - case memory_order_consume: - break; - case memory_order_release: - case memory_order_acq_rel: - __asm__ __volatile__ ("membar #StoreStore | #LoadStore" ::: "memory"); - /* release */ - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("membar #Sync" ::: "memory"); - /* seq */ - break; - } -} - -inline void -platform_fence_after(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_release: - break; - case memory_order_acquire: - case memory_order_acq_rel: - __asm__ __volatile__ ("membar #LoadLoad | #LoadStore" ::: "memory"); - /* acquire */ - break; - case memory_order_consume: - /* consume */ - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("membar #Sync" ::: "memory"); - /* seq */ - break; - default:; - } -} - -inline void -platform_fence_after_store(memory_order order) -{ - switch(order) - { - case memory_order_seq_cst: - __asm__ __volatile__ ("membar #Sync" ::: "memory"); - default:; - } -} - - -inline void -platform_fence_after_load(memory_order order) -{ - platform_fence_after(order); -} - -} -} - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - uint32_t v_; -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before(order); - const_cast(v_) = 0; - atomics::detail::platform_fence_after_store(order); - } - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before(order); - uint32_t tmp = 1; - __asm__ ( - "cas [%1], %2, %0" - : "+r" (tmp) - : "r" (&v_), "r" (0) - : "memory" - ); - atomics::detail::platform_fence_after(order); - return tmp; - } -}; - -} /* namespace boost */ - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2 -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 -#define BOOST_ATOMIC_LLONG_LOCK_FREE 0 -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -namespace boost { - -#define BOOST_ATOMIC_THREAD_FENCE 2 -inline void -atomic_thread_fence(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - break; - case memory_order_release: - __asm__ __volatile__ ("membar #StoreStore | #LoadStore" ::: "memory"); - break; - case memory_order_acquire: - __asm__ __volatile__ ("membar #LoadLoad | #LoadStore" ::: "memory"); - break; - case memory_order_acq_rel: - __asm__ __volatile__ ("membar #LoadLoad | #LoadStore | #StoreStore" ::: "memory"); - break; - case memory_order_consume: - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("membar #Sync" ::: "memory"); - break; - default:; - } -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -inline void -atomic_signal_fence(memory_order) -{ - __asm__ __volatile__ ("" ::: "memory"); -} - -namespace atomics { -namespace detail { - -/* integral types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef int32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp - v, order, memory_order_relaxed)); - return tmp; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - storage_type desired_s = desired; - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" ((storage_type)expected) - : "memory" - ); - desired = desired_s; - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef uint32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp - v, order, memory_order_relaxed)); - return tmp; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - storage_type desired_s = desired; - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" ((storage_type)expected) - : "memory" - ); - desired = desired_s; - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef int32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp - v, order, memory_order_relaxed)); - return tmp; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - storage_type desired_s = desired; - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" ((storage_type)expected) - : "memory" - ); - desired = desired_s; - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - typedef uint32_t storage_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp - v, order, memory_order_relaxed)); - return tmp; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - storage_type desired_s = desired; - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" ((storage_type)expected) - : "memory" - ); - desired = desired_s; - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp - v, order, memory_order_relaxed)); - return tmp; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired) - : "r" (&v_), "r" (expected) - : "memory" - ); - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* pointer types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void * value_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired) - : "r" (&v_), "r" (expected) - : "memory" - ); - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - - bool compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, (char*)tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, (char*)tmp - v, order, memory_order_relaxed)); - return tmp; - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - const_cast(v_) = v; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - platform_fence_before(success_order); - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired) - : "r" (&v_), "r" (expected) - : "memory" - ); - bool success = (desired == expected); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = desired; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp + v, order, memory_order_relaxed)); - return tmp; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, tmp - v, order, memory_order_relaxed)); - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -/* generic types */ - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" (expected_s) - : "memory" - ); - bool success = (desired_s == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &desired_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" (expected_s) - : "memory" - ); - bool success = (desired_s == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &desired_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - platform_fence_after_store(order); - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - do {} while(!compare_exchange_weak(tmp, v, order, memory_order_relaxed)); - return tmp; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); - __asm__ ( - "cas [%1], %2, %0" - : "+r" (desired_s) - : "r" (&v_), "r" (expected_s) - : "memory" - ); - bool success = (desired_s == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &desired_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/gcc-x86.hpp b/utils/boost_idb/boost/atomic/detail/gcc-x86.hpp deleted file mode 100644 index 284478de..00000000 --- a/utils/boost_idb/boost/atomic/detail/gcc-x86.hpp +++ /dev/null @@ -1,2017 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GCC_X86_HPP -#define BOOST_ATOMIC_DETAIL_GCC_X86_HPP - -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2012 Tim Blechmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -#if defined(__x86_64__) || defined(__SSE2__) -# define BOOST_ATOMIC_X86_FENCE_INSTR "mfence\n" -#else -# define BOOST_ATOMIC_X86_FENCE_INSTR "lock ; addl $0, (%%esp)\n" -#endif - -#define BOOST_ATOMIC_X86_PAUSE() __asm__ __volatile__ ("pause\n") - -#if defined(__i386__) &&\ - (\ - defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) ||\ - defined(__i586__) || defined(__i686__) || defined(__pentium4__) || defined(__nocona__) || defined(__core2__) || defined(__corei7__) ||\ - defined(__k6__) || defined(__athlon__) || defined(__k8__) || defined(__amdfam10__) || defined(__bdver1__) || defined(__bdver2__) || defined(__bdver3__) || defined(__btver1__) || defined(__btver2__)\ - ) -#define BOOST_ATOMIC_X86_HAS_CMPXCHG8B 1 -#endif - -#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) -#define BOOST_ATOMIC_X86_HAS_CMPXCHG16B 1 -#endif - -inline void -platform_fence_before(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_acquire: - case memory_order_consume: - break; - case memory_order_release: - case memory_order_acq_rel: - __asm__ __volatile__ ("" ::: "memory"); - /* release */ - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("" ::: "memory"); - /* seq */ - break; - default:; - } -} - -inline void -platform_fence_after(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_release: - break; - case memory_order_acquire: - case memory_order_acq_rel: - __asm__ __volatile__ ("" ::: "memory"); - /* acquire */ - break; - case memory_order_consume: - /* consume */ - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("" ::: "memory"); - /* seq */ - break; - default:; - } -} - -inline void -platform_fence_after_load(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_release: - break; - case memory_order_acquire: - case memory_order_acq_rel: - __asm__ __volatile__ ("" ::: "memory"); - break; - case memory_order_consume: - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("" ::: "memory"); - break; - default:; - } -} - -inline void -platform_fence_before_store(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_acquire: - case memory_order_consume: - break; - case memory_order_release: - case memory_order_acq_rel: - __asm__ __volatile__ ("" ::: "memory"); - /* release */ - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("" ::: "memory"); - /* seq */ - break; - default:; - } -} - -inline void -platform_fence_after_store(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - case memory_order_release: - break; - case memory_order_acquire: - case memory_order_acq_rel: - __asm__ __volatile__ ("" ::: "memory"); - /* acquire */ - break; - case memory_order_consume: - /* consume */ - break; - case memory_order_seq_cst: - __asm__ __volatile__ ("" ::: "memory"); - /* seq */ - break; - default:; - } -} - -} -} - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - uint32_t v_; -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - uint32_t v = 1; - atomics::detail::platform_fence_before(order); - __asm__ __volatile__ ( - "xchgl %0, %1" - : "+r" (v), "+m" (v_) - ); - atomics::detail::platform_fence_after(order); - return v; - } - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order == memory_order_seq_cst) { - uint32_t v = 0; - __asm__ __volatile__ ( - "xchgl %0, %1" - : "+r" (v), "+m" (v_) - ); - } else { - atomics::detail::platform_fence_before(order); - v_ = 0; - } - } -}; - -} /* namespace boost */ - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2 -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 - -#if defined(__x86_64__) || defined(BOOST_ATOMIC_X86_HAS_CMPXCHG8B) -#define BOOST_ATOMIC_LLONG_LOCK_FREE 2 -#endif - -#if defined(BOOST_ATOMIC_X86_HAS_CMPXCHG16B) && (defined(BOOST_HAS_INT128) || !defined(BOOST_NO_ALIGNMENT)) -#define BOOST_ATOMIC_INT128_LOCK_FREE 2 -#endif - -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -namespace boost { - -#define BOOST_ATOMIC_THREAD_FENCE 2 -inline void -atomic_thread_fence(memory_order order) -{ - switch(order) - { - case memory_order_relaxed: - break; - case memory_order_release: - __asm__ __volatile__ ("" ::: "memory"); - break; - case memory_order_acquire: - __asm__ __volatile__ ("" ::: "memory"); - break; - case memory_order_acq_rel: - __asm__ __volatile__ ("" ::: "memory"); - break; - case memory_order_consume: - break; - case memory_order_seq_cst: - __asm__ __volatile__ (BOOST_ATOMIC_X86_FENCE_INSTR ::: "memory"); - break; - default:; - } -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -inline void -atomic_signal_fence(memory_order) -{ - __asm__ __volatile__ ("" ::: "memory"); -} - -namespace atomics { -namespace detail { - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddb %0, %1" - : "+q" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgb %0, %1" - : "+q" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgb %3, %1\n\t" - "sete %2" - : "+a" (previous), "+m" (v_), "=q" (success) - : "q" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddw %0, %1" - : "+q" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgw %0, %1" - : "+q" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgw %3, %1\n\t" - "sete %2" - : "+a" (previous), "+m" (v_), "=q" (success) - : "q" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddl %0, %1" - : "+r" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgl %0, %1" - : "+r" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgl %3, %1\n\t" - "sete %2" - : "+a,a" (previous), "+m,m" (v_), "=q,m" (success) - : "r,r" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#if defined(__x86_64__) -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddq %0, %1" - : "+r" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgq %0, %1" - : "+r" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgq %3, %1\n\t" - "sete %2" - : "+a,a" (previous), "+m,m" (v_), "=q,m" (success) - : "r,r" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - value_type tmp = load(memory_order_relaxed); - while (!compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed)) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#endif - -/* pointers */ - -// NOTE: x32 target is still regarded to as x86_64 and can only be detected by the size of pointers -#if !defined(__x86_64__) || (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void * value_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgl %0, %1" - : "+r" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool compare_exchange_strong(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgl %3, %1\n\t" - "sete %2" - : "+a,a" (previous), "+m,m" (v_), "=q,m" (success) - : "r,r" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddl %0, %1" - : "+r" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return reinterpret_cast(v); - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgl %0, %1" - : "+r" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgl %3, %1\n\t" - "sete %2" - : "+a,a" (previous), "+m,m" (v_), "=q,m" (success) - : "r,r" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddl %0, %1" - : "+r" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return reinterpret_cast(v); - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#else - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void * value_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgq %0, %1" - : "+r" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool compare_exchange_strong(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgq %3, %1\n\t" - "sete %2" - : "+a,a" (previous), "+m,m" (v_), "=q,m" (success) - : "r,r" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddq %0, %1" - : "+r" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return reinterpret_cast(v); - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T * value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgq %0, %1" - : "+r" (v), "+m" (v_) - ); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgq %3, %1\n\t" - "sete %2" - : "+a,a" (previous), "+m,m" (v_), "=q,m" (success) - : "r,r" (desired) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = previous; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - platform_fence_before(order); - __asm__ __volatile__ - ( - "lock ; xaddq %0, %1" - : "+r" (v), "+m" (v_) - : - : "cc" - ); - platform_fence_after(order); - return reinterpret_cast(v); - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -#endif - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint8_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : - v_(reinterpret_cast(v)) - { - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgb %0, %1" - : "+q" (tmp), "+m" (v_) - ); - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s, desired_s; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - storage_type previous_s = expected_s; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgb %3, %1\n\t" - "sete %2" - : "+a" (previous_s), "+m" (v_), "=q" (success) - : "q" (desired_s) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &previous_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint16_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : - v_(reinterpret_cast(v)) - { - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgw %0, %1" - : "+q" (tmp), "+m" (v_) - ); - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s, desired_s; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - storage_type previous_s = expected_s; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgw %3, %1\n\t" - "sete %2" - : "+a" (previous_s), "+m" (v_), "=q" (success) - : "q" (desired_s) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &previous_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgl %0, %1" - : "+q" (tmp), "+m" (v_) - ); - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - storage_type previous_s = expected_s; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgl %3, %1\n\t" - "sete %2" - : "+a,a" (previous_s), "+m,m" (v_), "=q,m" (success) - : "q,q" (desired_s) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &previous_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#if defined(__x86_64__) -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint64_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - __asm__ __volatile__ - ( - "xchgq %0, %1" - : "+q" (tmp), "+m" (v_) - ); - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - storage_type previous_s = expected_s; - platform_fence_before(success_order); - bool success; - __asm__ __volatile__ - ( - "lock ; cmpxchgq %3, %1\n\t" - "sete %2" - : "+a,a" (previous_s), "+m,m" (v_), "=q,m" (success) - : "q,q" (desired_s) - : "cc" - ); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &previous_s, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; -#endif - -#if !defined(__x86_64__) && defined(BOOST_ATOMIC_X86_HAS_CMPXCHG8B) - -template -inline bool -platform_cmpxchg64_strong(T & expected, T desired, volatile T * ptr) BOOST_NOEXCEPT -{ -#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 - const T oldval = __sync_val_compare_and_swap(ptr, expected, desired); - const bool result = (oldval == expected); - expected = oldval; - return result; -#else - uint32_t scratch; - /* Make sure ebx is saved and restored properly in case - this object is compiled as "position independent". Since - programmers on x86 tend to forget specifying -DPIC or - similar, always assume PIC. - - To make this work uniformly even in the non-PIC case, - setup register constraints such that ebx can not be - used by accident e.g. as base address for the variable - to be modified. Accessing "scratch" should always be okay, - as it can only be placed on the stack (and therefore - accessed through ebp or esp only). - - In theory, could push/pop ebx onto/off the stack, but movs - to a prepared stack slot turn out to be faster. */ - bool success; - __asm__ __volatile__ - ( - "movl %%ebx, %[scratch]\n\t" - "movl %[desired_lo], %%ebx\n\t" - "lock; cmpxchg8b %[dest]\n\t" - "movl %[scratch], %%ebx\n\t" - "sete %[success]" - : "+A,A,A,A,A,A" (expected), [dest] "+m,m,m,m,m,m" (*ptr), [scratch] "=m,m,m,m,m,m" (scratch), [success] "=q,m,q,m,q,m" (success) - : [desired_lo] "S,S,D,D,m,m" ((uint32_t)desired), "c,c,c,c,c,c" ((uint32_t)(desired >> 32)) - : "memory", "cc" - ); - return success; -#endif -} - -// Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 3A, 8.1.1. Guaranteed Atomic Operations: -// -// The Pentium processor (and newer processors since) guarantees that the following additional memory operations will always be carried out atomically: -// * Reading or writing a quadword aligned on a 64-bit boundary -// -// Luckily, the memory is almost always 8-byte aligned in our case because atomic<> uses 64 bit native types for storage and dynamic memory allocations -// have at least 8 byte alignment. The only unfortunate case is when atomic is placeod on the stack and it is not 8-byte aligned (like on 32 bit Windows). - -template -inline void -platform_store64(T value, volatile T * ptr) BOOST_NOEXCEPT -{ - if (((uint32_t)ptr & 0x00000007) == 0) - { -#if defined(__SSE2__) - __asm__ __volatile__ - ( - "movq %1, %%xmm4\n\t" - "movq %%xmm4, %0\n\t" - : "=m" (*ptr) - : "m" (value) - : "memory", "xmm4" - ); -#else - __asm__ __volatile__ - ( - "fildll %1\n\t" - "fistpll %0\n\t" - : "=m" (*ptr) - : "m" (value) - : "memory" - ); -#endif - } - else - { - uint32_t scratch; - __asm__ __volatile__ - ( - "movl %%ebx, %[scratch]\n\t" - "movl %[value_lo], %%ebx\n\t" - "movl 0(%[dest]), %%eax\n\t" - "movl 4(%[dest]), %%edx\n\t" - ".align 16\n\t" - "1: lock; cmpxchg8b 0(%[dest])\n\t" - "jne 1b\n\t" - "movl %[scratch], %%ebx" - : [scratch] "=m,m" (scratch) - : [value_lo] "a,a" ((uint32_t)value), "c,c" ((uint32_t)(value >> 32)), [dest] "D,S" (ptr) - : "memory", "cc", "edx" - ); - } -} - -template -inline T -platform_load64(const volatile T * ptr) BOOST_NOEXCEPT -{ - T value; - - if (((uint32_t)ptr & 0x00000007) == 0) - { -#if defined(__SSE2__) - __asm__ __volatile__ - ( - "movq %1, %%xmm4\n\t" - "movq %%xmm4, %0\n\t" - : "=m" (value) - : "m" (*ptr) - : "memory", "xmm4" - ); -#else - __asm__ __volatile__ - ( - "fildll %1\n\t" - "fistpll %0\n\t" - : "=m" (value) - : "m" (*ptr) - : "memory" - ); -#endif - } - else - { - // We don't care for comparison result here; the previous value will be stored into value anyway. - // Also we don't care for ebx and ecx values, they just have to be equal to eax and edx before cmpxchg8b. - __asm__ __volatile__ - ( - "movl %%ebx, %%eax\n\t" - "movl %%ecx, %%edx\n\t" - "lock; cmpxchg8b %[dest]" - : "=&A" (value) - : [dest] "m" (*ptr) - : "cc" - ); - } - - return value; -} - -#endif - -#if defined(BOOST_ATOMIC_INT128_LOCK_FREE) && BOOST_ATOMIC_INT128_LOCK_FREE > 0 - -template -inline bool -platform_cmpxchg128_strong(T& expected, T desired, volatile T* ptr) BOOST_NOEXCEPT -{ - uint64_t const* p_desired = (uint64_t const*)&desired; - bool success; - __asm__ __volatile__ - ( - "lock; cmpxchg16b %[dest]\n\t" - "sete %[success]" - : "+A,A" (expected), [dest] "+m,m" (*ptr), [success] "=q,m" (success) - : "b,b" (p_desired[0]), "c,c" (p_desired[1]) - : "memory", "cc" - ); - return success; -} - -template -inline void -platform_store128(T value, volatile T* ptr) BOOST_NOEXCEPT -{ - uint64_t const* p_value = (uint64_t const*)&value; - __asm__ __volatile__ - ( - "movq 0(%[dest]), %%rax\n\t" - "movq 8(%[dest]), %%rdx\n\t" - ".align 16\n\t" - "1: lock; cmpxchg16b 0(%[dest])\n\t" - "jne 1b" - : - : "b" (p_value[0]), "c" (p_value[1]), [dest] "r" (ptr) - : "memory", "cc", "rax", "rdx" - ); -} - -template -inline T -platform_load128(const volatile T* ptr) BOOST_NOEXCEPT -{ - T value; - - // We don't care for comparison result here; the previous value will be stored into value anyway. - // Also we don't care for rbx and rcx values, they just have to be equal to rax and rdx before cmpxchg16b. - __asm__ __volatile__ - ( - "movq %%rbx, %%rax\n\t" - "movq %%rcx, %%rdx\n\t" - "lock; cmpxchg16b %[dest]" - : "=&A" (value) - : [dest] "m" (*ptr) - : "cc" - ); - - return value; -} - -#endif // defined(BOOST_ATOMIC_INT128_LOCK_FREE) && BOOST_ATOMIC_INT128_LOCK_FREE > 0 - -} -} -} - -/* pull in 64-bit atomic type using cmpxchg8b above */ -#if !defined(__x86_64__) && defined(BOOST_ATOMIC_X86_HAS_CMPXCHG8B) -#include -#endif - -/* pull in 128-bit atomic type using cmpxchg16b above */ -#if defined(BOOST_ATOMIC_INT128_LOCK_FREE) && BOOST_ATOMIC_INT128_LOCK_FREE > 0 -#include -#endif - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/generic-cas.hpp b/utils/boost_idb/boost/atomic/detail/generic-cas.hpp deleted file mode 100644 index cf4a3d79..00000000 --- a/utils/boost_idb/boost/atomic/detail/generic-cas.hpp +++ /dev/null @@ -1,206 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_GENERIC_CAS_HPP -#define BOOST_ATOMIC_DETAIL_GENERIC_CAS_HPP - -// Copyright (c) 2009 Helge Bahmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -/* fallback implementation for various compilation targets; -this is *not* efficient, particularly because all operations -are fully fenced (full memory barriers before and after -each operation) */ - -#if defined(__GNUC__) - namespace boost { namespace atomics { namespace detail { - inline int32_t - fenced_compare_exchange_strong_32(volatile int32_t *ptr, int32_t expected, int32_t desired) - { - return __sync_val_compare_and_swap_4(ptr, expected, desired); - } - #define BOOST_ATOMIC_HAVE_CAS32 1 - - #if defined(__amd64__) || defined(__i686__) - inline int64_t - fenced_compare_exchange_strong_64(int64_t *ptr, int64_t expected, int64_t desired) - { - return __sync_val_compare_and_swap_8(ptr, expected, desired); - } - #define BOOST_ATOMIC_HAVE_CAS64 1 - #endif - }}} - -#elif defined(__ICL) || defined(_MSC_VER) - - #if defined(_MSC_VER) - #include - #include - #endif - - namespace boost { namespace atomics { namespace detail { - inline int32_t - fenced_compare_exchange_strong(int32_t *ptr, int32_t expected, int32_t desired) - { - return _InterlockedCompareExchange(reinterpret_cast(ptr), desired, expected); - } - #define BOOST_ATOMIC_HAVE_CAS32 1 - #if defined(_WIN64) - inline int64_t - fenced_compare_exchange_strong(int64_t *ptr, int64_t expected, int64_t desired) - { - return _InterlockedCompareExchange64(ptr, desired, expected); - } - #define BOOST_ATOMIC_HAVE_CAS64 1 - #endif - }}} - -#elif (defined(__ICC) || defined(__ECC)) - namespace boost { namespace atomics { namespace detail { - inline int32_t - fenced_compare_exchange_strong_32(int32_t *ptr, int32_t expected, int32_t desired) - { - return _InterlockedCompareExchange((void*)ptr, desired, expected); - } - #define BOOST_ATOMIC_HAVE_CAS32 1 - #if defined(__x86_64) - inline int64_t - fenced_compare_exchange_strong(int64_t *ptr, int64_t expected, int64_t desired) - { - return cas64(ptr, expected, desired); - } - #define BOOST_ATOMIC_HAVE_CAS64 1 - #elif defined(__ECC) //IA-64 version - inline int64_t - fenced_compare_exchange_strong(int64_t *ptr, int64_t expected, int64_t desired) - { - return _InterlockedCompareExchange64((void*)ptr, desired, expected); - } - #define BOOST_ATOMIC_HAVE_CAS64 1 - #endif - }}} - -#elif (defined(__SUNPRO_CC) && defined(__sparc)) - #include - namespace boost { namespace atomics { namespace detail { - inline int32_t - fenced_compare_exchange_strong_32(int32_t *ptr, int32_t expected, int32_t desired) - { - return atomic_cas_32((volatile unsigned int*)ptr, expected, desired); - } - #define BOOST_ATOMIC_HAVE_CAS32 1 - - /* FIXME: check for 64 bit mode */ - inline int64_t - fenced_compare_exchange_strong_64(int64_t *ptr, int64_t expected, int64_t desired) - { - return atomic_cas_64((volatile unsigned long long*)ptr, expected, desired); - } - #define BOOST_ATOMIC_HAVE_CAS64 1 - }}} -#endif - - -namespace boost { -namespace atomics { -namespace detail { - -#ifdef BOOST_ATOMIC_HAVE_CAS32 -template -class atomic_generic_cas32 -{ -private: - typedef atomic_generic_cas32 this_type; -public: - explicit atomic_generic_cas32(T v) : i((int32_t)v) {} - atomic_generic_cas32() {} - T load(memory_order order=memory_order_seq_cst) const volatile - { - T expected=(T)i; - do { } while(!const_cast(this)->compare_exchange_weak(expected, expected, order, memory_order_relaxed)); - return expected; - } - void store(T v, memory_order order=memory_order_seq_cst) volatile - { - exchange(v); - } - bool compare_exchange_strong( - T &expected, - T desired, - memory_order success_order, - memory_order failure_order) volatile - { - T found; - found=(T)fenced_compare_exchange_strong_32(&i, (int32_t)expected, (int32_t)desired); - bool success=(found==expected); - expected=found; - return success; - } - bool compare_exchange_weak( - T &expected, - T desired, - memory_order success_order, - memory_order failure_order) volatile - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - T exchange(T r, memory_order order=memory_order_seq_cst) volatile - { - T expected=(T)i; - do { } while(!compare_exchange_weak(expected, r, order, memory_order_relaxed)); - return expected; - } - - bool is_lock_free(void) const volatile {return true;} - typedef T integral_type; -private: - mutable int32_t i; -}; - -template -class platform_atomic_integral : - public build_atomic_from_exchange > -{ -public: - typedef build_atomic_from_exchange > super; - explicit platform_atomic_integral(T v) : super(v) {} - platform_atomic_integral(void) {} -}; - -template -class platform_atomic_integral : - public build_atomic_from_larger_type, T> -{ -public: - typedef build_atomic_from_larger_type, T> super; - - explicit platform_atomic_integral(T v) : super(v) {} - platform_atomic_integral(void) {} -}; - -template -class platform_atomic_integral : - public build_atomic_from_larger_type, T> -{ -public: - typedef build_atomic_from_larger_type, T> super; - - explicit platform_atomic_integral(T v) : super(v) {} - platform_atomic_integral(void) {} -}; -#endif - -} } } - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/interlocked.hpp b/utils/boost_idb/boost/atomic/detail/interlocked.hpp deleted file mode 100644 index ae8518df..00000000 --- a/utils/boost_idb/boost/atomic/detail/interlocked.hpp +++ /dev/null @@ -1,203 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_INTERLOCKED_HPP -#define BOOST_ATOMIC_DETAIL_INTERLOCKED_HPP - -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2012, 2013 Andrey Semashev -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -#if defined(_WIN32_WCE) || (defined(_MSC_VER) && _MSC_VER < 1400) - -#include - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(dest, exchange, compare) BOOST_INTERLOCKED_COMPARE_EXCHANGE((long*)(dest), exchange, compare) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE(dest, newval) BOOST_INTERLOCKED_EXCHANGE((long*)(dest), newval) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(dest, addend) BOOST_INTERLOCKED_EXCHANGE_ADD((long*)(dest), addend) -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) BOOST_INTERLOCKED_EXCHANGE_POINTER(dest, newval) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_INTERLOCKED_EXCHANGE_ADD((long*)(dest), byte_offset)) - -#elif defined(_MSC_VER) && _MSC_VER >= 1400 - -#include - -#pragma intrinsic(_InterlockedCompareExchange) -#pragma intrinsic(_InterlockedExchangeAdd) -#pragma intrinsic(_InterlockedExchange) -#pragma intrinsic(_InterlockedAnd) -#pragma intrinsic(_InterlockedOr) -#pragma intrinsic(_InterlockedXor) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(dest, exchange, compare) _InterlockedCompareExchange((long*)(dest), (long)(exchange), (long)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(dest, addend) _InterlockedExchangeAdd((long*)(dest), (long)(addend)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE(dest, newval) _InterlockedExchange((long*)(dest), (long)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_AND(dest, arg) _InterlockedAnd((long*)(dest), (long)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_OR(dest, arg) _InterlockedOr((long*)(dest), (long)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_XOR(dest, arg) _InterlockedXor((long*)(dest), (long)(arg)) - -#if (defined(_M_IX86) && _M_IX86 >= 500) || defined(_M_AMD64) || defined(_M_IA64) -#pragma intrinsic(_InterlockedCompareExchange64) -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64(dest, exchange, compare) _InterlockedCompareExchange64((__int64*)(dest), (__int64)(exchange), (__int64)(compare)) -#endif - -#if _MSC_VER >= 1600 - -// MSVC 2010 and later provide intrinsics for 8 and 16 bit integers. -// Note that for each bit count these macros must be either all defined or all not defined. -// Otherwise atomic<> operations will be implemented inconsistently. - -#pragma intrinsic(_InterlockedCompareExchange8) -#pragma intrinsic(_InterlockedExchangeAdd8) -#pragma intrinsic(_InterlockedExchange8) -#pragma intrinsic(_InterlockedAnd8) -#pragma intrinsic(_InterlockedOr8) -#pragma intrinsic(_InterlockedXor8) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8(dest, exchange, compare) _InterlockedCompareExchange8((char*)(dest), (char)(exchange), (char)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD8(dest, addend) _InterlockedExchangeAdd8((char*)(dest), (char)(addend)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE8(dest, newval) _InterlockedExchange8((char*)(dest), (char)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_AND8(dest, arg) _InterlockedAnd8((char*)(dest), (char)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_OR8(dest, arg) _InterlockedOr8((char*)(dest), (char)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_XOR8(dest, arg) _InterlockedXor8((char*)(dest), (char)(arg)) - -#pragma intrinsic(_InterlockedCompareExchange16) -#pragma intrinsic(_InterlockedExchangeAdd16) -#pragma intrinsic(_InterlockedExchange16) -#pragma intrinsic(_InterlockedAnd16) -#pragma intrinsic(_InterlockedOr16) -#pragma intrinsic(_InterlockedXor16) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16(dest, exchange, compare) _InterlockedCompareExchange16((short*)(dest), (short)(exchange), (short)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD16(dest, addend) _InterlockedExchangeAdd16((short*)(dest), (short)(addend)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE16(dest, newval) _InterlockedExchange16((short*)(dest), (short)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_AND16(dest, arg) _InterlockedAnd16((short*)(dest), (short)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_OR16(dest, arg) _InterlockedOr16((short*)(dest), (short)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_XOR16(dest, arg) _InterlockedXor16((short*)(dest), (short)(arg)) - -#endif // _MSC_VER >= 1600 - -#if defined(_M_AMD64) || defined(_M_IA64) - -#pragma intrinsic(_InterlockedExchangeAdd64) -#pragma intrinsic(_InterlockedExchange64) -#pragma intrinsic(_InterlockedAnd64) -#pragma intrinsic(_InterlockedOr64) -#pragma intrinsic(_InterlockedXor64) - -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64(dest, addend) _InterlockedExchangeAdd64((__int64*)(dest), (__int64)(addend)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE64(dest, newval) _InterlockedExchange64((__int64*)(dest), (__int64)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_AND64(dest, arg) _InterlockedAnd64((__int64*)(dest), (__int64)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_OR64(dest, arg) _InterlockedOr64((__int64*)(dest), (__int64)(arg)) -#define BOOST_ATOMIC_INTERLOCKED_XOR64(dest, arg) _InterlockedXor64((__int64*)(dest), (__int64)(arg)) - -#pragma intrinsic(_InterlockedCompareExchangePointer) -#pragma intrinsic(_InterlockedExchangePointer) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) _InterlockedCompareExchangePointer((void**)(dest), (void*)(exchange), (void*)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) _InterlockedExchangePointer((void**)(dest), (void*)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64((long*)(dest), byte_offset)) - -#else // defined(_M_AMD64) || defined(_M_IA64) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) ((void*)_InterlockedCompareExchange((long*)(dest), (long)(exchange), (long)(compare))) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) ((void*)_InterlockedExchange((long*)(dest), (long)(newval))) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD((long*)(dest), byte_offset)) - -#endif // defined(_M_AMD64) || defined(_M_IA64) - -#else // defined(_MSC_VER) && _MSC_VER >= 1400 - -#if defined(BOOST_USE_WINDOWS_H) - -#include - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(dest, exchange, compare) InterlockedCompareExchange((long*)(dest), (long)(exchange), (long)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE(dest, newval) InterlockedExchange((long*)(dest), (long)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(dest, addend) InterlockedExchangeAdd((long*)(dest), (long)(addend)) - -#if defined(_WIN64) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64(dest, exchange, compare) InterlockedCompareExchange64((__int64*)(dest), (__int64)(exchange), (__int64)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE64(dest, newval) InterlockedExchange64((__int64*)(dest), (__int64)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64(dest, addend) InterlockedExchangeAdd64((__int64*)(dest), (__int64)(addend)) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) InterlockedCompareExchangePointer((void**)(dest), (void*)(exchange), (void*)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) InterlockedExchangePointer((void**)(dest), (void*)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64(dest, byte_offset)) - -#else // defined(_WIN64) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) ((void*)BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(dest, exchange, compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE(dest, newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(dest, byte_offset)) - -#endif // defined(_WIN64) - -#else // defined(BOOST_USE_WINDOWS_H) - -#if defined(__MINGW64__) -#define BOOST_ATOMIC_INTERLOCKED_IMPORT -#else -#define BOOST_ATOMIC_INTERLOCKED_IMPORT __declspec(dllimport) -#endif - -namespace boost { -namespace atomics { -namespace detail { - -extern "C" { - -BOOST_ATOMIC_INTERLOCKED_IMPORT long __stdcall InterlockedCompareExchange(long volatile*, long, long); -BOOST_ATOMIC_INTERLOCKED_IMPORT long __stdcall InterlockedExchange(long volatile*, long); -BOOST_ATOMIC_INTERLOCKED_IMPORT long __stdcall InterlockedExchangeAdd(long volatile*, long); - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(dest, exchange, compare) boost::atomics::detail::InterlockedCompareExchange((long*)(dest), (long)(exchange), (long)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE(dest, newval) boost::atomics::detail::InterlockedExchange((long*)(dest), (long)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(dest, addend) boost::atomics::detail::InterlockedExchangeAdd((long*)(dest), (long)(addend)) - -#if defined(_WIN64) - -BOOST_ATOMIC_INTERLOCKED_IMPORT __int64 __stdcall InterlockedCompareExchange64(__int64 volatile*, __int64, __int64); -BOOST_ATOMIC_INTERLOCKED_IMPORT __int64 __stdcall InterlockedExchange64(__int64 volatile*, __int64); -BOOST_ATOMIC_INTERLOCKED_IMPORT __int64 __stdcall InterlockedExchangeAdd64(__int64 volatile*, __int64); - -BOOST_ATOMIC_INTERLOCKED_IMPORT void* __stdcall InterlockedCompareExchangePointer(void* volatile *, void*, void*); -BOOST_ATOMIC_INTERLOCKED_IMPORT void* __stdcall InterlockedExchangePointer(void* volatile *, void*); - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64(dest, exchange, compare) boost::atomics::detail::InterlockedCompareExchange64((__int64*)(dest), (__int64)(exchange), (__int64)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE64(dest, newval) boost::atomics::detail::InterlockedExchange64((__int64*)(dest), (__int64)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64(dest, addend) boost::atomics::detail::InterlockedExchangeAdd64((__int64*)(dest), (__int64)(addend)) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) boost::atomics::detail::InterlockedCompareExchangePointer((void**)(dest), (void*)(exchange), (void*)(compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) boost::atomics::detail::InterlockedExchangePointer((void**)(dest), (void*)(newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64(dest, byte_offset)) - -#else // defined(_WIN64) - -#define BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) ((void*)BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(dest, exchange, compare)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(dest, newval) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE(dest, newval)) -#define BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(dest, byte_offset) ((void*)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(dest, byte_offset)) - -#endif // defined(_WIN64) - -} // extern "C" - -} // namespace detail -} // namespace atomics -} // namespace boost - -#undef BOOST_ATOMIC_INTERLOCKED_IMPORT - -#endif // defined(BOOST_USE_WINDOWS_H) - -#endif // defined(_MSC_VER) - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/link.hpp b/utils/boost_idb/boost/atomic/detail/link.hpp deleted file mode 100644 index 25a4caf2..00000000 --- a/utils/boost_idb/boost/atomic/detail/link.hpp +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_LINK_HPP -#define BOOST_ATOMIC_DETAIL_LINK_HPP - -// Copyright (c) 2012 Hartmut Kaiser -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -/////////////////////////////////////////////////////////////////////////////// -// Set up dll import/export options -#if (defined(BOOST_ATOMIC_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)) && \ - !defined(BOOST_ATOMIC_STATIC_LINK) - -#if defined(BOOST_ATOMIC_SOURCE) -#define BOOST_ATOMIC_DECL BOOST_SYMBOL_EXPORT -#define BOOST_ATOMIC_BUILD_DLL -#else -#define BOOST_ATOMIC_DECL BOOST_SYMBOL_IMPORT -#endif - -#endif // building a shared library - -#ifndef BOOST_ATOMIC_DECL -#define BOOST_ATOMIC_DECL -#endif - -/////////////////////////////////////////////////////////////////////////////// -// Auto library naming -#if !defined(BOOST_ATOMIC_SOURCE) && !defined(BOOST_ALL_NO_LIB) && \ - !defined(BOOST_ATOMIC_NO_LIB) - -#define BOOST_LIB_NAME boost_atomic - -// tell the auto-link code to select a dll when required: -#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_ATOMIC_DYN_LINK) -#define BOOST_DYN_LINK -#endif - -#include - -#endif // auto-linking disabled - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/linux-arm.hpp b/utils/boost_idb/boost/atomic/detail/linux-arm.hpp deleted file mode 100644 index d39dcd0e..00000000 --- a/utils/boost_idb/boost/atomic/detail/linux-arm.hpp +++ /dev/null @@ -1,190 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_LINUX_ARM_HPP -#define BOOST_ATOMIC_DETAIL_LINUX_ARM_HPP - -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// Copyright (c) 2009, 2011 Helge Bahmann -// Copyright (c) 2009 Phil Endecott -// Copyright (c) 2013 Tim Blechmann -// Linux-specific code by Phil Endecott - -// Different ARM processors have different atomic instructions. In particular, -// architecture versions before v6 (which are still in widespread use, e.g. the -// Intel/Marvell XScale chips like the one in the NSLU2) have only atomic swap. -// On Linux the kernel provides some support that lets us abstract away from -// these differences: it provides emulated CAS and barrier functions at special -// addresses that are guaranteed not to be interrupted by the kernel. Using -// this facility is slightly slower than inline assembler would be, but much -// faster than a system call. -// -// While this emulated CAS is "strong" in the sense that it does not fail -// "spuriously" (i.e.: it never fails to perform the exchange when the value -// found equals the value expected), it does not return the found value on -// failure. To satisfy the atomic API, compare_exchange_{weak|strong} must -// return the found value on failure, and we have to manually load this value -// after the emulated CAS reports failure. This in turn introduces a race -// between the CAS failing (due to the "wrong" value being found) and subsequently -// loading (which might turn up the "right" value). From an application's -// point of view this looks like "spurious failure", and therefore the -// emulated CAS is only good enough to provide compare_exchange_weak -// semantics. - -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -inline void -arm_barrier(void) -{ - void (*kernel_dmb)(void) = (void (*)(void)) 0xffff0fa0; - kernel_dmb(); -} - -inline void -platform_fence_before(memory_order order) -{ - switch(order) { - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - arm_barrier(); - case memory_order_consume: - default:; - } -} - -inline void -platform_fence_after(memory_order order) -{ - switch(order) { - case memory_order_acquire: - case memory_order_acq_rel: - case memory_order_seq_cst: - arm_barrier(); - default:; - } -} - -inline void -platform_fence_before_store(memory_order order) -{ - platform_fence_before(order); -} - -inline void -platform_fence_after_store(memory_order order) -{ - if (order == memory_order_seq_cst) - arm_barrier(); -} - -inline void -platform_fence_after_load(memory_order order) -{ - platform_fence_after(order); -} - -template -inline bool -platform_cmpxchg32(T & expected, T desired, volatile T * ptr) -{ - typedef T (*kernel_cmpxchg32_t)(T oldval, T newval, volatile T * ptr); - - if (((kernel_cmpxchg32_t) 0xffff0fc0)(expected, desired, ptr) == 0) { - return true; - } else { - expected = *ptr; - return false; - } -} - -} -} - -#define BOOST_ATOMIC_THREAD_FENCE 2 -inline void -atomic_thread_fence(memory_order order) -{ - switch(order) { - case memory_order_acquire: - case memory_order_release: - case memory_order_acq_rel: - case memory_order_seq_cst: - atomics::detail::arm_barrier(); - default:; - } -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -inline void -atomic_signal_fence(memory_order) -{ - __asm__ __volatile__ ("" ::: "memory"); -} - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - uint32_t v_; -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before_store(order); - const_cast(v_) = 0; - atomics::detail::platform_fence_after_store(order); - } - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before(order); - uint32_t expected = v_; - do { - if (expected == 1) - break; - } while (!atomics::detail::platform_cmpxchg32(expected, (uint32_t)1, &v_)); - atomics::detail::platform_fence_after(order); - return expected; - } -}; - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -} - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR16_T_LOCK_FREE 2 -#define BOOST_ATOMIC_CHAR32_T_LOCK_FREE 2 -#define BOOST_ATOMIC_WCHAR_T_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 -#define BOOST_ATOMIC_LLONG_LOCK_FREE 0 -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -#include - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/lockpool.hpp b/utils/boost_idb/boost/atomic/detail/lockpool.hpp deleted file mode 100644 index 42464866..00000000 --- a/utils/boost_idb/boost/atomic/detail/lockpool.hpp +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_LOCKPOOL_HPP -#define BOOST_ATOMIC_DETAIL_LOCKPOOL_HPP - -// Copyright (c) 2011 Helge Bahmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#ifndef BOOST_ATOMIC_FLAG_LOCK_FREE -#include -#endif - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -#ifndef BOOST_ATOMIC_FLAG_LOCK_FREE - -class lockpool -{ -public: - typedef boost::detail::lightweight_mutex lock_type; - class scoped_lock : - public lock_type::scoped_lock - { - typedef lock_type::scoped_lock base_type; - - public: - explicit scoped_lock(const volatile void * addr) : base_type(get_lock_for(addr)) - { - } - - BOOST_DELETED_FUNCTION(scoped_lock(scoped_lock const&)) - BOOST_DELETED_FUNCTION(scoped_lock& operator=(scoped_lock const&)) - }; - -private: - static BOOST_ATOMIC_DECL lock_type& get_lock_for(const volatile void * addr); -}; - -#else - -class lockpool -{ -public: - typedef atomic_flag lock_type; - - class scoped_lock - { - private: - atomic_flag& flag_; - - public: - explicit - scoped_lock(const volatile void * addr) : flag_(get_lock_for(addr)) - { - for (; flag_.test_and_set(memory_order_acquire);) - { -#if defined(BOOST_ATOMIC_X86_PAUSE) - BOOST_ATOMIC_X86_PAUSE(); -#endif - } - } - - ~scoped_lock(void) - { - flag_.clear(memory_order_release); - } - - BOOST_DELETED_FUNCTION(scoped_lock(const scoped_lock &)) - BOOST_DELETED_FUNCTION(scoped_lock& operator=(const scoped_lock &)) - }; - -private: - static BOOST_ATOMIC_DECL lock_type& get_lock_for(const volatile void * addr); -}; - -#endif - -} -} -} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/platform.hpp b/utils/boost_idb/boost/atomic/detail/platform.hpp deleted file mode 100644 index 3dfb73d7..00000000 --- a/utils/boost_idb/boost/atomic/detail/platform.hpp +++ /dev/null @@ -1,71 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_PLATFORM_HPP -#define BOOST_ATOMIC_DETAIL_PLATFORM_HPP - -// Copyright (c) 2009 Helge Bahmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// Platform selection file - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -// Intel compiler does not support __atomic* intrinsics properly, although defines them (tested with 13.0.1 and 13.1.1 on Linux) -#if (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 407) && !defined(BOOST_INTEL_CXX_VERSION))\ - || (defined(BOOST_CLANG) && ((__clang_major__ * 100 + __clang_minor__) >= 302)) - - #include - -#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) - - #include - -#elif 0 && defined(__GNUC__) && defined(__alpha__) /* currently does not work correctly */ - - #include - #include - -#elif defined(__GNUC__) && (defined(__POWERPC__) || defined(__PPC__)) - - #include - -// This list of ARM architecture versions comes from Apple's arm/arch.h header. -// I don't know how complete it is. -#elif defined(__GNUC__) && (defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ - || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) \ - || defined(__ARM_ARCH_6K__) \ - || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ - || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ - || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7S__)) - - #include - -#elif defined(__linux__) && defined(__arm__) - - #include - -#elif defined(__GNUC__) && defined(__sparc_v9__) - - #include - -#elif defined(BOOST_WINDOWS) || defined(_WIN32_CE) - - #include - -#elif 0 && defined(__GNUC__) /* currently does not work correctly */ - - #include - #include - -#else - -#include - -#endif - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/type-classification.hpp b/utils/boost_idb/boost/atomic/detail/type-classification.hpp deleted file mode 100644 index 98bc3113..00000000 --- a/utils/boost_idb/boost/atomic/detail/type-classification.hpp +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_TYPE_CLASSIFICATION_HPP -#define BOOST_ATOMIC_DETAIL_TYPE_CLASSIFICATION_HPP - -// Copyright (c) 2011 Helge Bahmann -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace atomics { -namespace detail { - -template::value> -struct classify -{ - typedef void type; -}; - -template -struct classify {typedef int type;}; - -template -struct classify {typedef void* type;}; - -template -struct storage_size_of -{ - enum _ - { - size = sizeof(T), - value = (size == 3 ? 4 : (size >= 5 && size <= 7 ? 8 : (size >= 9 && size <= 15 ? 16 : size))) - }; -}; - -}}} - -#endif diff --git a/utils/boost_idb/boost/atomic/detail/windows.hpp b/utils/boost_idb/boost/atomic/detail/windows.hpp deleted file mode 100644 index a8dc4f84..00000000 --- a/utils/boost_idb/boost/atomic/detail/windows.hpp +++ /dev/null @@ -1,1669 +0,0 @@ -#ifndef BOOST_ATOMIC_DETAIL_WINDOWS_HPP -#define BOOST_ATOMIC_DETAIL_WINDOWS_HPP - -// Copyright (c) 2009 Helge Bahmann -// Copyright (c) 2012 Andrey Semashev -// Copyright (c) 2013 Tim Blechmann, Andrey Semashev -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -#ifdef _MSC_VER -#pragma warning(push) -// 'order' : unreferenced formal parameter -#pragma warning(disable: 4100) -#endif - -#if defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_IX86)) -extern "C" void _mm_pause(void); -#pragma intrinsic(_mm_pause) -#define BOOST_ATOMIC_X86_PAUSE() _mm_pause() -#else -#define BOOST_ATOMIC_X86_PAUSE() -#endif - -#if defined(_M_IX86) && _M_IX86 >= 500 -#define BOOST_ATOMIC_X86_HAS_CMPXCHG8B 1 -#endif - -// Define hardware barriers -#if defined(_MSC_VER) && (defined(_M_AMD64) || (defined(_M_IX86) && defined(_M_IX86_FP) && _M_IX86_FP >= 2)) -extern "C" void _mm_mfence(void); -#pragma intrinsic(_mm_mfence) -#endif - -// Define compiler barriers -#if defined(__INTEL_COMPILER) -#define BOOST_ATOMIC_COMPILER_BARRIER() __memory_barrier() -#elif defined(_MSC_VER) && _MSC_VER >= 1310 && !defined(_WIN32_WCE) -extern "C" void _ReadWriteBarrier(void); -#pragma intrinsic(_ReadWriteBarrier) -#define BOOST_ATOMIC_COMPILER_BARRIER() _ReadWriteBarrier() -#endif - -#ifndef BOOST_ATOMIC_COMPILER_BARRIER -#define BOOST_ATOMIC_COMPILER_BARRIER() -#endif - -namespace boost { -namespace atomics { -namespace detail { - -BOOST_FORCEINLINE void hardware_full_fence(void) -{ -#if defined(_MSC_VER) && (defined(_M_AMD64) || (defined(_M_IX86) && defined(_M_IX86_FP) && _M_IX86_FP >= 2)) - // Use mfence only if SSE2 is available - _mm_mfence(); -#else - long tmp; - BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&tmp, 0); -#endif -} - -BOOST_FORCEINLINE void -platform_fence_before(memory_order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); -} - -BOOST_FORCEINLINE void -platform_fence_after(memory_order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); -} - -BOOST_FORCEINLINE void -platform_fence_before_store(memory_order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); -} - -BOOST_FORCEINLINE void -platform_fence_after_store(memory_order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); -} - -BOOST_FORCEINLINE void -platform_fence_after_load(memory_order order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); - - // On x86 and x86_64 there is no need for a hardware barrier, - // even if seq_cst memory order is requested, because all - // seq_cst writes are implemented with lock-prefixed operations - // or xchg which has implied lock prefix. Therefore normal loads - // are already ordered with seq_cst stores on these architectures. - -#if !(defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_IX86))) - if (order == memory_order_seq_cst) - hardware_full_fence(); -#endif -} - -} // namespace detail -} // namespace atomics - -#define BOOST_ATOMIC_THREAD_FENCE 2 -BOOST_FORCEINLINE void -atomic_thread_fence(memory_order order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); - if (order == memory_order_seq_cst) - atomics::detail::hardware_full_fence(); -} - -#define BOOST_ATOMIC_SIGNAL_FENCE 2 -BOOST_FORCEINLINE void -atomic_signal_fence(memory_order) -{ - BOOST_ATOMIC_COMPILER_BARRIER(); -} - -#undef BOOST_ATOMIC_COMPILER_BARRIER - -class atomic_flag -{ -private: - atomic_flag(const atomic_flag &) /* = delete */ ; - atomic_flag & operator=(const atomic_flag &) /* = delete */ ; - uint32_t v_; -public: - BOOST_CONSTEXPR atomic_flag(void) BOOST_NOEXCEPT : v_(0) {} - - bool - test_and_set(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before(order); - const uint32_t old = (uint32_t)BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, 1); - atomics::detail::platform_fence_after(order); - return old != 0; - } - - void - clear(memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - atomics::detail::platform_fence_before_store(order); - BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, 0); - atomics::detail::platform_fence_after_store(order); - } -}; - -} // namespace boost - -#define BOOST_ATOMIC_FLAG_LOCK_FREE 2 - -#include - -#if !defined(BOOST_ATOMIC_FORCE_FALLBACK) - -#define BOOST_ATOMIC_CHAR_LOCK_FREE 2 -#define BOOST_ATOMIC_SHORT_LOCK_FREE 2 -#define BOOST_ATOMIC_INT_LOCK_FREE 2 -#define BOOST_ATOMIC_LONG_LOCK_FREE 2 -#if defined(BOOST_ATOMIC_X86_HAS_CMPXCHG8B) || defined(_M_AMD64) || defined(_M_IA64) -#define BOOST_ATOMIC_LLONG_LOCK_FREE 2 -#else -#define BOOST_ATOMIC_LLONG_LOCK_FREE 0 -#endif -#define BOOST_ATOMIC_POINTER_LOCK_FREE 2 -#define BOOST_ATOMIC_BOOL_LOCK_FREE 2 - -namespace boost { -namespace atomics { -namespace detail { - -#if defined(_MSC_VER) -#pragma warning(push) -// 'char' : forcing value to bool 'true' or 'false' (performance warning) -#pragma warning(disable: 4800) -#endif - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8 - typedef value_type storage_type; -#else - typedef uint32_t storage_type; -#endif - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT: v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - v_ = static_cast< storage_type >(v); - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = static_cast< value_type >(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); -#ifdef BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD8 - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD8(&v_, v)); -#else - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(&v_, v)); -#endif - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - typedef typename make_signed< value_type >::type signed_value_type; - return fetch_add(static_cast< value_type >(-static_cast< signed_value_type >(v)), order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); -#ifdef BOOST_ATOMIC_INTERLOCKED_EXCHANGE8 - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE8(&v_, v)); -#else - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, v)); -#endif - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8 - value_type oldval = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8(&v_, desired, previous)); -#else - value_type oldval = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&v_, desired, previous)); -#endif - bool success = (previous == oldval); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = oldval; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#ifdef BOOST_ATOMIC_INTERLOCKED_AND8 - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_AND8(&v_, v)); - platform_fence_after(order); - return v; -#elif defined(BOOST_ATOMIC_INTERLOCKED_AND) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_AND(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#ifdef BOOST_ATOMIC_INTERLOCKED_OR8 - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_OR8(&v_, v)); - platform_fence_after(order); - return v; -#elif defined(BOOST_ATOMIC_INTERLOCKED_OR) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_OR(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#ifdef BOOST_ATOMIC_INTERLOCKED_XOR8 - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_XOR8(&v_, v)); - platform_fence_after(order); - return v; -#elif defined(BOOST_ATOMIC_INTERLOCKED_XOR) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_XOR(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#if defined(_MSC_VER) -#pragma warning(pop) -#endif - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16 - typedef value_type storage_type; -#else - typedef uint32_t storage_type; -#endif - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT: v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - v_ = static_cast< storage_type >(v); - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = static_cast< value_type >(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); -#ifdef BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD16 - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD16(&v_, v)); -#else - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(&v_, v)); -#endif - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - typedef typename make_signed< value_type >::type signed_value_type; - return fetch_add(static_cast< value_type >(-static_cast< signed_value_type >(v)), order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); -#ifdef BOOST_ATOMIC_INTERLOCKED_EXCHANGE16 - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE16(&v_, v)); -#else - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, v)); -#endif - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16 - value_type oldval = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16(&v_, desired, previous)); -#else - value_type oldval = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&v_, desired, previous)); -#endif - bool success = (previous == oldval); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = oldval; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#ifdef BOOST_ATOMIC_INTERLOCKED_AND16 - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_AND16(&v_, v)); - platform_fence_after(order); - return v; -#elif defined(BOOST_ATOMIC_INTERLOCKED_AND) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_AND(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#ifdef BOOST_ATOMIC_INTERLOCKED_OR16 - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_OR16(&v_, v)); - platform_fence_after(order); - return v; -#elif defined(BOOST_ATOMIC_INTERLOCKED_OR) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_OR(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#ifdef BOOST_ATOMIC_INTERLOCKED_XOR16 - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_XOR16(&v_, v)); - platform_fence_after(order); - return v; -#elif defined(BOOST_ATOMIC_INTERLOCKED_XOR) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_XOR(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef value_type storage_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT: v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - v_ = static_cast< storage_type >(v); - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = static_cast< value_type >(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD(&v_, v)); - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - typedef typename make_signed< value_type >::type signed_value_type; - return fetch_add(static_cast< value_type >(-static_cast< signed_value_type >(v)), order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, v)); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - value_type oldval = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&v_, desired, previous)); - bool success = (previous == oldval); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = oldval; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#if defined(BOOST_ATOMIC_INTERLOCKED_AND) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_AND(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#if defined(BOOST_ATOMIC_INTERLOCKED_OR) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_OR(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for(; !compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#if defined(BOOST_ATOMIC_INTERLOCKED_XOR) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_XOR(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - bool - is_lock_free(void)const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -// MSVC 2012 fails to recognize sizeof(T) as a constant expression in template specializations -enum msvc_sizeof_pointer_workaround { sizeof_pointer = sizeof(void*) }; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef std::ptrdiff_t difference_type; - typedef void* value_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT: v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - v = (value_type)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(&v_, v); - platform_fence_after(order); - return v; - } - - bool compare_exchange_strong(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - value_type oldval = (value_type)BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(&v_, desired, previous); - bool success = (previous == oldval); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = oldval; - return success; - } - - bool compare_exchange_weak(value_type & expected, value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void)const volatile BOOST_NOEXCEPT - { - return true; - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - value_type res = (value_type)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(&v_, v); - platform_fence_after(order); - return res; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - BOOST_ATOMIC_DECLARE_VOID_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T* value_type; - typedef std::ptrdiff_t difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT: v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - const_cast(v_) = v; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - value_type v = const_cast(v_); - platform_fence_after_load(order); - return v; - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - v = (value_type)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_POINTER(&v_, v); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - value_type oldval = (value_type)BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE_POINTER(&v_, desired, previous); - bool success = (previous == oldval); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = oldval; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - v = v * sizeof(*v_); - platform_fence_before(order); - value_type res = (value_type)BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD_POINTER(&v_, v); - platform_fence_after(order); - return res; - } - - value_type - fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - return fetch_add(-v, order); - } - - bool - is_lock_free(void)const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_POINTER_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - value_type v_; -}; - - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8 - typedef uint8_t storage_type; -#else - typedef uint32_t storage_type; -#endif - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8 - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(reinterpret_cast< storage_type const& >(v)) - { - } -#else - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } -#endif - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); -#ifdef BOOST_ATOMIC_INTERLOCKED_EXCHANGE8 - tmp = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE8(&v_, tmp)); -#else - tmp = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, tmp)); -#endif - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8 - storage_type oldval = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE8(&v_, desired_s, expected_s)); -#else - storage_type oldval = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&v_, desired_s, expected_s)); -#endif - bool success = (oldval == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &oldval, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16 - typedef uint16_t storage_type; -#else - typedef uint32_t storage_type; -#endif - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16 - BOOST_CONSTEXPR explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(reinterpret_cast< storage_type const& >(v)) - { - } -#else - explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } -#endif - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); -#ifdef BOOST_ATOMIC_INTERLOCKED_EXCHANGE16 - tmp = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE16(&v_, tmp)); -#else - tmp = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, tmp)); -#endif - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); -#ifdef BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16 - storage_type oldval = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE16(&v_, desired_s, expected_s)); -#else - storage_type oldval = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&v_, desired_s, expected_s)); -#endif - bool success = (oldval == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &oldval, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void)const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint32_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - tmp = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE(&v_, tmp)); - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); - storage_type oldval = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE(&v_, desired_s, expected_s)); - bool success = (oldval == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &oldval, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void) const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#if defined(_M_AMD64) || defined(_M_IA64) - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef value_type storage_type; - typedef T difference_type; - -protected: - typedef value_type value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT: v_(v) {} - - void - store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - platform_fence_before(order); - v_ = static_cast< storage_type >(v); - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT - { - value_type v = static_cast< value_type >(v_); - platform_fence_after_load(order); - return v; - } - - value_type - fetch_add(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE_ADD64(&v_, v)); - platform_fence_after(order); - return v; - } - - value_type - fetch_sub(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - typedef typename make_signed< value_type >::type signed_value_type; - return fetch_add(static_cast< value_type >(-static_cast< signed_value_type >(v)), order); - } - - value_type - exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE64(&v_, v)); - platform_fence_after(order); - return v; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - value_type previous = expected; - platform_fence_before(success_order); - value_type oldval = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64(&v_, desired, previous)); - bool success = (previous == oldval); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - expected = oldval; - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - value_type - fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#if defined(BOOST_ATOMIC_INTERLOCKED_AND64) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_AND64(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp & v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#if defined(BOOST_ATOMIC_INTERLOCKED_OR64) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_OR64(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp | v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - value_type - fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { -#if defined(BOOST_ATOMIC_INTERLOCKED_XOR64) - platform_fence_before(order); - v = static_cast< value_type >(BOOST_ATOMIC_INTERLOCKED_XOR64(&v_, v)); - platform_fence_after(order); - return v; -#else - value_type tmp = load(memory_order_relaxed); - for (; !compare_exchange_weak(tmp, tmp ^ v, order, memory_order_relaxed);) - { - BOOST_ATOMIC_X86_PAUSE(); - } - return tmp; -#endif - } - - bool - is_lock_free(void)const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -template -class base_atomic -{ -private: - typedef base_atomic this_type; - typedef T value_type; - typedef uint64_t storage_type; - -protected: - typedef value_type const& value_arg_type; - -public: - BOOST_DEFAULTED_FUNCTION(base_atomic(void), {}) - explicit base_atomic(value_type const& v) : v_(0) - { - memcpy(&v_, &v, sizeof(value_type)); - } - - void - store(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - if (order != memory_order_seq_cst) { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - const_cast(v_) = tmp; - } else { - exchange(v, order); - } - } - - value_type - load(memory_order order = memory_order_seq_cst)const volatile BOOST_NOEXCEPT - { - storage_type tmp = const_cast(v_); - platform_fence_after_load(order); - value_type v; - memcpy(&v, &tmp, sizeof(value_type)); - return v; - } - - value_type - exchange(value_type const& v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT - { - storage_type tmp = 0; - memcpy(&tmp, &v, sizeof(value_type)); - platform_fence_before(order); - tmp = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_EXCHANGE64(&v_, tmp)); - platform_fence_after(order); - value_type res; - memcpy(&res, &tmp, sizeof(value_type)); - return res; - } - - bool - compare_exchange_strong( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - storage_type expected_s = 0, desired_s = 0; - memcpy(&expected_s, &expected, sizeof(value_type)); - memcpy(&desired_s, &desired, sizeof(value_type)); - platform_fence_before(success_order); - storage_type oldval = static_cast< storage_type >(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64(&v_, desired_s, expected_s)); - bool success = (oldval == expected_s); - if (success) - platform_fence_after(success_order); - else - platform_fence_after(failure_order); - memcpy(&expected, &oldval, sizeof(value_type)); - return success; - } - - bool - compare_exchange_weak( - value_type & expected, - value_type const& desired, - memory_order success_order, - memory_order failure_order) volatile BOOST_NOEXCEPT - { - return compare_exchange_strong(expected, desired, success_order, failure_order); - } - - bool - is_lock_free(void)const volatile BOOST_NOEXCEPT - { - return true; - } - - BOOST_ATOMIC_DECLARE_BASE_OPERATORS - - BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&)) - BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&)) - -private: - storage_type v_; -}; - -#elif defined(BOOST_ATOMIC_X86_HAS_CMPXCHG8B) - -template -inline bool -platform_cmpxchg64_strong(T & expected, T desired, volatile T * p) BOOST_NOEXCEPT -{ -#if defined(BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64) - const T oldval = BOOST_ATOMIC_INTERLOCKED_COMPARE_EXCHANGE64(p, desired, expected); - const bool result = (oldval == expected); - expected = oldval; - return result; -#else - bool result; - __asm - { - mov edi, p - mov esi, expected - mov ebx, dword ptr [desired] - mov ecx, dword ptr [desired + 4] - mov eax, dword ptr [esi] - mov edx, dword ptr [esi + 4] - lock cmpxchg8b qword ptr [edi] - mov dword ptr [esi], eax - mov dword ptr [esi + 4], edx - sete result - }; - return result; -#endif -} - -// Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 3A, 8.1.1. Guaranteed Atomic Operations: -// -// The Pentium processor (and newer processors since) guarantees that the following additional memory operations will always be carried out atomically: -// * Reading or writing a quadword aligned on a 64-bit boundary -// -// Luckily, the memory is almost always 8-byte aligned in our case because atomic<> uses 64 bit native types for storage and dynamic memory allocations -// have at least 8 byte alignment. The only unfortunate case is when atomic is placeod on the stack and it is not 8-byte aligned (like on 32 bit Windows). - -template -inline void -platform_store64(T value, volatile T * p) BOOST_NOEXCEPT -{ - if (((uint32_t)p & 0x00000007) == 0) - { -#if defined(_M_IX86_FP) && _M_IX86_FP >= 2 - __asm - { - mov edx, p - movq xmm4, value - movq qword ptr [edx], xmm4 - }; -#else - __asm - { - mov edx, p - fild value - fistp qword ptr [edx] - }; -#endif - } - else - { - __asm - { - mov edi, p - mov ebx, dword ptr [value] - mov ecx, dword ptr [value + 4] - mov eax, dword ptr [edi] - mov edx, dword ptr [edi + 4] - align 16 -again: - lock cmpxchg8b qword ptr [edi] - jne again - }; - } -} - -template -inline T -platform_load64(const volatile T * p) BOOST_NOEXCEPT -{ - T value; - - if (((uint32_t)p & 0x00000007) == 0) - { -#if defined(_M_IX86_FP) && _M_IX86_FP >= 2 - __asm - { - mov edx, p - movq xmm4, qword ptr [edx] - movq value, xmm4 - }; -#else - __asm - { - mov edx, p - fild qword ptr [edx] - fistp value - }; -#endif - } - else - { - // We don't care for comparison result here; the previous value will be stored into value anyway. - // Also we don't care for ebx and ecx values, they just have to be equal to eax and edx before cmpxchg8b. - __asm - { - mov edi, p - mov eax, ebx - mov edx, ecx - lock cmpxchg8b qword ptr [edi] - mov dword ptr [value], eax - mov dword ptr [value + 4], edx - }; - } - - return value; -} - -#endif - -} // namespace detail -} // namespace atomics -} // namespace boost - -/* pull in 64-bit atomic type using cmpxchg8b above */ -#if defined(BOOST_ATOMIC_X86_HAS_CMPXCHG8B) -#include -#endif - -#endif /* !defined(BOOST_ATOMIC_FORCE_FALLBACK) */ - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif diff --git a/utils/boost_idb/boost/bimap.hpp b/utils/boost_idb/boost/bimap.hpp new file mode 100644 index 00000000..51d726dd --- /dev/null +++ b/utils/boost_idb/boost/bimap.hpp @@ -0,0 +1,19 @@ +// Boost.Bimap +// +// Copyright (c) 2006-2007 Matias Capeletto +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// See www.boost.org/libs/bimap for documentation. + +// Convenience header + +#include + +namespace boost +{ + using ::boost::bimaps::bimap; +} + diff --git a/utils/boost_idb/boost/bind/bind.hpp b/utils/boost_idb/boost/bind/bind.hpp index fb670979..a63d2a02 100644 --- a/utils/boost_idb/boost/bind/bind.hpp +++ b/utils/boost_idb/boost/bind/bind.hpp @@ -1680,7 +1680,7 @@ template< class R, class T > struct add_cref< R (T::*) (), 1 > typedef void type; }; -#if !defined(__IBMCPP__) || __IBMCPP_FUNC_CV_TMPL_ARG_DEDUCTION +#if !( defined(__IBMCPP__) && BOOST_WORKAROUND( __IBMCPP__, BOOST_TESTED_AT(600) ) ) template< class R, class T > struct add_cref< R (T::*) () const, 1 > { diff --git a/utils/boost_idb/boost/blank.hpp b/utils/boost_idb/boost/blank.hpp new file mode 100644 index 00000000..d0fe5abc --- /dev/null +++ b/utils/boost_idb/boost/blank.hpp @@ -0,0 +1,106 @@ +//----------------------------------------------------------------------------- +// boost blank.hpp header file +// See http://www.boost.org for updates, documentation, and revision history. +//----------------------------------------------------------------------------- +// +// Copyright (c) 2003 +// Eric Friedman +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_BLANK_HPP +#define BOOST_BLANK_HPP + +#include "boost/blank_fwd.hpp" + +#if !defined(BOOST_NO_IOSTREAM) +#include // for std::basic_ostream forward declare +#include "boost/detail/templated_streams.hpp" +#endif // BOOST_NO_IOSTREAM + +#include "boost/mpl/bool.hpp" +#include "boost/type_traits/is_empty.hpp" +#include "boost/type_traits/is_pod.hpp" +#include "boost/type_traits/is_stateless.hpp" + +namespace boost { + +struct blank +{ +}; + +// type traits specializations +// + +template <> +struct is_pod< blank > + : mpl::true_ +{ +}; + +template <> +struct is_empty< blank > + : mpl::true_ +{ +}; + +template <> +struct is_stateless< blank > + : mpl::true_ +{ +}; + +// relational operators +// + +inline bool operator==(const blank&, const blank&) +{ + return true; +} + +inline bool operator<=(const blank&, const blank&) +{ + return true; +} + +inline bool operator>=(const blank&, const blank&) +{ + return true; +} + +inline bool operator!=(const blank&, const blank&) +{ + return false; +} + +inline bool operator<(const blank&, const blank&) +{ + return false; +} + +inline bool operator>(const blank&, const blank&) +{ + return false; +} + +// streaming support +// +#if !defined(BOOST_NO_IOSTREAM) + +BOOST_TEMPLATED_STREAM_TEMPLATE(E,T) +inline BOOST_TEMPLATED_STREAM(ostream, E,T)& operator<<( + BOOST_TEMPLATED_STREAM(ostream, E,T)& out + , const blank& + ) +{ + // (output nothing) + return out; +} + +#endif // BOOST_NO_IOSTREAM + +} // namespace boost + +#endif // BOOST_BLANK_HPP diff --git a/utils/boost_idb/boost/blank_fwd.hpp b/utils/boost_idb/boost/blank_fwd.hpp new file mode 100644 index 00000000..8bfe97c4 --- /dev/null +++ b/utils/boost_idb/boost/blank_fwd.hpp @@ -0,0 +1,22 @@ +//----------------------------------------------------------------------------- +// boost blank_fwd.hpp header file +// See http://www.boost.org for updates, documentation, and revision history. +//----------------------------------------------------------------------------- +// +// Copyright (c) 2003 +// Eric Friedman +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_BLANK_FWD_HPP +#define BOOST_BLANK_FWD_HPP + +namespace boost { + +struct blank; + +} // namespace boost + +#endif // BOOST_BLANK_FWD_HPP diff --git a/utils/boost_idb/boost/cast.hpp b/utils/boost_idb/boost/cast.hpp new file mode 100644 index 00000000..2615d183 --- /dev/null +++ b/utils/boost_idb/boost/cast.hpp @@ -0,0 +1,107 @@ +// boost cast.hpp header file ----------------------------------------------// + +// (C) Copyright Kevlin Henney and Dave Abrahams 1999. +// Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// See http://www.boost.org/libs/conversion for Documentation. + +// Revision History +// 23 JUn 05 numeric_cast removed and redirected to the new verion (Fernando Cacciola) +// 02 Apr 01 Removed BOOST_NO_LIMITS workarounds and included +// instead (the workaround did not +// actually compile when BOOST_NO_LIMITS was defined in +// any case, so we loose nothing). (John Maddock) +// 21 Jan 01 Undid a bug I introduced yesterday. numeric_cast<> never +// worked with stock GCC; trying to get it to do that broke +// vc-stlport. +// 20 Jan 01 Moved BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS to config.hpp. +// Removed unused BOOST_EXPLICIT_TARGET macro. Moved +// boost::detail::type to boost/type.hpp. Made it compile with +// stock gcc again (Dave Abrahams) +// 29 Nov 00 Remove nested namespace cast, cleanup spacing before Formal +// Review (Beman Dawes) +// 19 Oct 00 Fix numeric_cast for floating-point types (Dave Abrahams) +// 15 Jul 00 Suppress numeric_cast warnings for GCC, Borland and MSVC +// (Dave Abrahams) +// 30 Jun 00 More MSVC6 wordarounds. See comments below. (Dave Abrahams) +// 28 Jun 00 Removed implicit_cast<>. See comment below. (Beman Dawes) +// 27 Jun 00 More MSVC6 workarounds +// 15 Jun 00 Add workarounds for MSVC6 +// 2 Feb 00 Remove bad_numeric_cast ";" syntax error (Doncho Angelov) +// 26 Jan 00 Add missing throw() to bad_numeric_cast::what(0 (Adam Levar) +// 29 Dec 99 Change using declarations so usages in other namespaces work +// correctly (Dave Abrahams) +// 23 Sep 99 Change polymorphic_downcast assert to also detect M.I. errors +// as suggested Darin Adler and improved by Valentin Bonnard. +// 2 Sep 99 Remove controversial asserts, simplify, rename. +// 30 Aug 99 Move to cast.hpp, replace value_cast with numeric_cast, +// place in nested namespace. +// 3 Aug 99 Initial version + +#ifndef BOOST_CAST_HPP +#define BOOST_CAST_HPP + +# include +# include +# include +# include +# include +# include + +// It has been demonstrated numerous times that MSVC 6.0 fails silently at link +// time if you use a template function which has template parameters that don't +// appear in the function's argument list. +// +// TODO: Add this to config.hpp? +# if defined(BOOST_MSVC) && BOOST_MSVC < 1300 +# define BOOST_EXPLICIT_DEFAULT_TARGET , ::boost::type* = 0 +# else +# define BOOST_EXPLICIT_DEFAULT_TARGET +# endif + +namespace boost +{ +// See the documentation for descriptions of how to choose between +// static_cast<>, dynamic_cast<>, polymorphic_cast<> and polymorphic_downcast<> + +// polymorphic_cast --------------------------------------------------------// + + // Runtime checked polymorphic downcasts and crosscasts. + // Suggested in The C++ Programming Language, 3rd Ed, Bjarne Stroustrup, + // section 15.8 exercise 1, page 425. + + template + inline Target polymorphic_cast(Source* x BOOST_EXPLICIT_DEFAULT_TARGET) + { + Target tmp = dynamic_cast(x); + if ( tmp == 0 ) throw std::bad_cast(); + return tmp; + } + +// polymorphic_downcast ----------------------------------------------------// + + // BOOST_ASSERT() checked polymorphic downcast. Crosscasts prohibited. + + // WARNING: Because this cast uses BOOST_ASSERT(), it violates + // the One Definition Rule if used in multiple translation units + // where BOOST_DISABLE_ASSERTS, BOOST_ENABLE_ASSERT_HANDLER + // NDEBUG are defined inconsistently. + + // Contributed by Dave Abrahams + + template + inline Target polymorphic_downcast(Source* x BOOST_EXPLICIT_DEFAULT_TARGET) + { + BOOST_ASSERT( dynamic_cast(x) == x ); // detect logic error + return static_cast(x); + } + +# undef BOOST_EXPLICIT_DEFAULT_TARGET + +} // namespace boost + +# include + +#endif // BOOST_CAST_HPP diff --git a/utils/boost_idb/boost/chrono.hpp b/utils/boost_idb/boost/chrono.hpp deleted file mode 100644 index a3a35229..00000000 --- a/utils/boost_idb/boost/chrono.hpp +++ /dev/null @@ -1,20 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Vicente J. Botet Escriba 2010. -// Distributed under the Boost -// Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or -// copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/stm for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CHRONO_HPP -#define BOOST_CHRONO_HPP - -//----------------------------------------------------------------------------- -#include -//----------------------------------------------------------------------------- - -#endif // BOOST_CHRONO_HPP diff --git a/utils/boost_idb/boost/chrono/ceil.hpp b/utils/boost_idb/boost/chrono/ceil.hpp deleted file mode 100644 index 7fbf9ddc..00000000 --- a/utils/boost_idb/boost/chrono/ceil.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// boost/chrono/round.hpp ------------------------------------------------------------// - -// (C) Copyright Howard Hinnant -// Copyright 2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/libs/chrono for documentation. - -#ifndef BOOST_CHRONO_CEIL_HPP -#define BOOST_CHRONO_CEIL_HPP - -#include - -namespace boost -{ - namespace chrono - { - - /** - * rounds up - */ - template - To ceil(const duration& d) - { - To t = duration_cast(d); - if (t < d) - ++t; - return t; - } - - } // namespace chrono -} // namespace boost - -#endif diff --git a/utils/boost_idb/boost/chrono/chrono.hpp b/utils/boost_idb/boost/chrono/chrono.hpp deleted file mode 100644 index ebc29d8d..00000000 --- a/utils/boost_idb/boost/chrono/chrono.hpp +++ /dev/null @@ -1,15 +0,0 @@ -// chrono.hpp --------------------------------------------------------------// - -// Copyright 2009-2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#ifndef BOOST_CHRONO_CHRONO_HPP -#define BOOST_CHRONO_CHRONO_HPP - -#include -#include -#include - -#endif // BOOST_CHRONO_CHRONO_HPP diff --git a/utils/boost_idb/boost/chrono/chrono_io.hpp b/utils/boost_idb/boost/chrono/chrono_io.hpp deleted file mode 100644 index ebd18a3d..00000000 --- a/utils/boost_idb/boost/chrono/chrono_io.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// chrono_io -// -// (C) Copyright Howard Hinnant -// (C) Copyright 2010-2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o under lvm/libc++ to Boost - -#ifndef BOOST_CHRONO_CHRONO_IO_HPP -#define BOOST_CHRONO_CHRONO_IO_HPP - -#include - -//#if BOOST_CHRONO_VERSION == 2 -//#include -//#include -//#elif BOOST_CHRONO_VERSION == 1 -//#include -//#endif - -#if defined BOOST_CHRONO_DONT_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 -#include -#include -#else -#include -#endif - -#include - -#endif // BOOST_CHRONO_CHRONO_IO_HPP diff --git a/utils/boost_idb/boost/chrono/clock_string.hpp b/utils/boost_idb/boost/chrono/clock_string.hpp deleted file mode 100644 index af025f27..00000000 --- a/utils/boost_idb/boost/chrono/clock_string.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// -// (C) Copyright 2010-2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -#ifndef BOOST_CHRONO_CLOCK_STRING_HPP -#define BOOST_CHRONO_CLOCK_STRING_HPP - -#include - -namespace boost -{ - namespace chrono - { - - template - struct clock_string; - - } // chrono - -} // boost - -#endif // BOOST_CHRONO_CLOCK_STRING_HPP diff --git a/utils/boost_idb/boost/chrono/config.hpp b/utils/boost_idb/boost/chrono/config.hpp deleted file mode 100644 index 301b8775..00000000 --- a/utils/boost_idb/boost/chrono/config.hpp +++ /dev/null @@ -1,220 +0,0 @@ -// boost/chrono/config.hpp -------------------------------------------------// - -// Copyright Beman Dawes 2003, 2006, 2008 -// Copyright 2009-2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/libs/chrono for documentation. - -#ifndef BOOST_CHRONO_CONFIG_HPP -#define BOOST_CHRONO_CONFIG_HPP - -#include - -#if !defined BOOST_CHRONO_VERSION -#define BOOST_CHRONO_VERSION 1 -#else -#if BOOST_CHRONO_VERSION!=1 && BOOST_CHRONO_VERSION!=2 -#error "BOOST_CHRONO_VERSION must be 1 or 2" -#endif -#endif - -#if defined(BOOST_CHRONO_SOURCE) && !defined(BOOST_USE_WINDOWS_H) -#define BOOST_USE_WINDOWS_H -#endif - -#if ! defined BOOST_CHRONO_PROVIDES_DATE_IO_FOR_SYSTEM_CLOCK_TIME_POINT \ - && ! defined BOOST_CHRONO_DONT_PROVIDE_DATE_IO_FOR_SYSTEM_CLOCK_TIME_POINT - -# define BOOST_CHRONO_PROVIDES_DATE_IO_FOR_SYSTEM_CLOCK_TIME_POINT - -#endif - -// BOOST_CHRONO_POSIX_API, BOOST_CHRONO_MAC_API, or BOOST_CHRONO_WINDOWS_API -// can be defined by the user to specify which API should be used - -#if defined(BOOST_CHRONO_WINDOWS_API) -# warning Boost.Chrono will use the Windows API -#elif defined(BOOST_CHRONO_MAC_API) -# warning Boost.Chrono will use the Mac API -#elif defined(BOOST_CHRONO_POSIX_API) -# warning Boost.Chrono will use the POSIX API -#endif - -# if defined( BOOST_CHRONO_WINDOWS_API ) && defined( BOOST_CHRONO_POSIX_API ) -# error both BOOST_CHRONO_WINDOWS_API and BOOST_CHRONO_POSIX_API are defined -# elif defined( BOOST_CHRONO_WINDOWS_API ) && defined( BOOST_CHRONO_MAC_API ) -# error both BOOST_CHRONO_WINDOWS_API and BOOST_CHRONO_MAC_API are defined -# elif defined( BOOST_CHRONO_MAC_API ) && defined( BOOST_CHRONO_POSIX_API ) -# error both BOOST_CHRONO_MAC_API and BOOST_CHRONO_POSIX_API are defined -# elif !defined( BOOST_CHRONO_WINDOWS_API ) && !defined( BOOST_CHRONO_MAC_API ) && !defined( BOOST_CHRONO_POSIX_API ) -# if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) -# define BOOST_CHRONO_WINDOWS_API -# elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) -# define BOOST_CHRONO_MAC_API -# else -# define BOOST_CHRONO_POSIX_API -# endif -# endif - -# if defined( BOOST_CHRONO_WINDOWS_API ) -# ifndef UNDER_CE -# define BOOST_CHRONO_HAS_PROCESS_CLOCKS -# endif -# define BOOST_CHRONO_HAS_CLOCK_STEADY -# define BOOST_CHRONO_HAS_THREAD_CLOCK -# define BOOST_CHRONO_THREAD_CLOCK_IS_STEADY true -# endif - -# if defined( BOOST_CHRONO_MAC_API ) -# define BOOST_CHRONO_HAS_PROCESS_CLOCKS -# define BOOST_CHRONO_HAS_CLOCK_STEADY -# define BOOST_CHRONO_THREAD_CLOCK_IS_STEADY true -# endif - -# if defined( BOOST_CHRONO_POSIX_API ) -# define BOOST_CHRONO_HAS_PROCESS_CLOCKS -# include //to check for CLOCK_REALTIME and CLOCK_MONOTONIC and _POSIX_THREAD_CPUTIME -# if defined(CLOCK_MONOTONIC) -# define BOOST_CHRONO_HAS_CLOCK_STEADY -# endif -# if defined(_POSIX_THREAD_CPUTIME) && !defined(BOOST_DISABLE_THREADS) -# define BOOST_CHRONO_HAS_THREAD_CLOCK -# define BOOST_CHRONO_THREAD_CLOCK_IS_STEADY true -# endif -# if defined(CLOCK_THREAD_CPUTIME_ID) && !defined(BOOST_DISABLE_THREADS) -# define BOOST_CHRONO_HAS_THREAD_CLOCK -# define BOOST_CHRONO_THREAD_CLOCK_IS_STEADY true -# endif -# if defined(sun) || defined(__sun) -# undef BOOST_CHRONO_HAS_THREAD_CLOCK -# undef BOOST_CHRONO_THREAD_CLOCK_IS_STEADY -# endif -# if defined(__HP_aCC) && defined(__hpux) -# undef BOOST_CHRONO_HAS_THREAD_CLOCK -# undef BOOST_CHRONO_THREAD_CLOCK_IS_STEADY -# endif -# if defined(__VXWORKS__) -# undef BOOST_CHRONO_HAS_PROCESS_CLOCKS -# endif -# endif - -#if defined(BOOST_CHRONO_THREAD_DISABLED) && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) -#undef BOOST_CHRONO_HAS_THREAD_CLOCK -#undef BOOST_CHRONO_THREAD_CLOCK_IS_STEADY -#endif - -//#undef BOOST_CHRONO_HAS_PROCESS_CLOCKS - -// unicode support ------------------------------// - -#if defined(BOOST_NO_CXX11_UNICODE_LITERALS) || defined(BOOST_NO_CXX11_CHAR16_T) || defined(BOOST_NO_CXX11_CHAR32_T) -//~ #define BOOST_CHRONO_HAS_UNICODE_SUPPORT -#else -#define BOOST_CHRONO_HAS_UNICODE_SUPPORT 1 -#endif - -#if ! defined BOOST_NOEXCEPT -#if defined(BOOST_NO_CXX11_NOEXCEPT) -#define BOOST_NOEXCEPT -#else -#define BOOST_NOEXCEPT noexcept -#endif -#endif - -#if defined( BOOST_NO_CXX11_NUMERIC_LIMITS ) -#define BOOST_CHRONO_LIB_CONSTEXPR -#elif defined(_LIBCPP_VERSION) && !defined(_LIBCPP_CONSTEXPR) - #define BOOST_CHRONO_LIB_CONSTEXPR -#else - #define BOOST_CHRONO_LIB_CONSTEXPR BOOST_CONSTEXPR -#endif - -#if defined( BOOST_NO_CXX11_NUMERIC_LIMITS ) -# define BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW throw() -#else -#ifdef BOOST_NO_CXX11_NOEXCEPT -# define BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW throw() -#else -# define BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW noexcept -#endif -#endif - - -#if defined BOOST_CHRONO_PROVIDE_HYBRID_ERROR_HANDLING \ - && defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -#error "BOOST_CHRONO_PROVIDE_HYBRID_ERROR_HANDLING && BOOST_CHRONO_PROVIDE_HYBRID_ERROR_HANDLING defined" -#endif - -#if defined BOOST_CHRONO_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 \ - && defined BOOST_CHRONO_DONT_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 -#error "BOOST_CHRONO_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 && BOOST_CHRONO_DONT_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 defined" -#endif - -#if ! defined BOOST_CHRONO_PROVIDE_HYBRID_ERROR_HANDLING \ - && ! defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -#define BOOST_CHRONO_PROVIDE_HYBRID_ERROR_HANDLING -#endif - -#if (BOOST_CHRONO_VERSION == 2) -#if ! defined BOOST_CHRONO_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 \ - && ! defined BOOST_CHRONO_DONT_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 -#define BOOST_CHRONO_DONT_PROVIDES_DEPRECATED_IO_SINCE_V2_0_0 -#endif -#endif - -#ifdef BOOST_CHRONO_HEADER_ONLY -#define BOOST_CHRONO_INLINE inline -#define BOOST_CHRONO_STATIC inline -#define BOOST_CHRONO_DECL - -#else -#define BOOST_CHRONO_INLINE -#define BOOST_CHRONO_STATIC static - -// enable dynamic linking on Windows ---------------------------------------// - -// we need to import/export our code only if the user has specifically -// asked for it by defining either BOOST_ALL_DYN_LINK if they want all boost -// libraries to be dynamically linked, or BOOST_CHRONO_DYN_LINK -// if they want just this one to be dynamically liked: -#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_CHRONO_DYN_LINK) -// export if this is our own source, otherwise import: -#ifdef BOOST_CHRONO_SOURCE -# define BOOST_CHRONO_DECL BOOST_SYMBOL_EXPORT -#else -# define BOOST_CHRONO_DECL BOOST_SYMBOL_IMPORT -#endif // BOOST_CHRONO_SOURCE -#endif // DYN_LINK -// -// if BOOST_CHRONO_DECL isn't defined yet define it now: -#ifndef BOOST_CHRONO_DECL -#define BOOST_CHRONO_DECL -#endif - - - -// enable automatic library variant selection ------------------------------// - -#if !defined(BOOST_CHRONO_SOURCE) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_CHRONO_NO_LIB) -// -// Set the name of our library; this will get undef'ed by auto_link.hpp -// once it's done with it: -// -#define BOOST_LIB_NAME boost_chrono -// -// If we're importing code from a dll, then tell auto_link.hpp about it: -// -#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_CHRONO_DYN_LINK) -# define BOOST_DYN_LINK -#endif -// -// And include the header that does the work: -// -#include -#endif // auto-linking disabled -#endif // BOOST_CHRONO_HEADER_ONLY -#endif // BOOST_CHRONO_CONFIG_HPP - diff --git a/utils/boost_idb/boost/chrono/detail/inlined/chrono.hpp b/utils/boost_idb/boost/chrono/detail/inlined/chrono.hpp deleted file mode 100644 index 02788436..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/chrono.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// chrono.cpp --------------------------------------------------------------// - -// Copyright Beman Dawes 2008 -// Copyright Vicente J. Botet Escriba 2009 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#ifndef BOOST_CHRONO_DETAIL_INLINED_CHRONO_HPP -#define BOOST_CHRONO_DETAIL_INLINED_CHRONO_HPP - -#include -#include -#include -#include -#include - -//----------------------------------------------------------------------------// -// // -// Platform-specific Implementations // -// // -//----------------------------------------------------------------------------// - -//----------------------------------------------------------------------------// -// Windows // -//----------------------------------------------------------------------------// -#if defined(BOOST_CHRONO_WINDOWS_API) -#include - -//----------------------------------------------------------------------------// -// Mac // -//----------------------------------------------------------------------------// -#elif defined(BOOST_CHRONO_MAC_API) -#include - -//----------------------------------------------------------------------------// -// POSIX // -//----------------------------------------------------------------------------// -#elif defined(BOOST_CHRONO_POSIX_API) -#include - -#endif // POSIX - -#endif diff --git a/utils/boost_idb/boost/chrono/detail/inlined/mac/chrono.hpp b/utils/boost_idb/boost/chrono/detail/inlined/mac/chrono.hpp deleted file mode 100644 index bf20ae92..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/mac/chrono.hpp +++ /dev/null @@ -1,241 +0,0 @@ -// mac/chrono.cpp --------------------------------------------------------------// - -// Copyright Beman Dawes 2008 -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -//----------------------------------------------------------------------------// -// Mac // -//----------------------------------------------------------------------------// - -#include //for gettimeofday and timeval -#include // mach_absolute_time, mach_timebase_info_data_t - -namespace boost -{ -namespace chrono -{ - -// system_clock - -// gettimeofday is the most precise "system time" available on this platform. -// It returns the number of microseconds since New Years 1970 in a struct called timeval -// which has a field for seconds and a field for microseconds. -// Fill in the timeval and then convert that to the time_point -system_clock::time_point -system_clock::now() BOOST_NOEXCEPT -{ - timeval tv; - gettimeofday(&tv, 0); - return time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec)); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -system_clock::time_point -system_clock::now(system::error_code & ec) -{ - timeval tv; - gettimeofday(&tv, 0); - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec)); -} -#endif -// Take advantage of the fact that on this platform time_t is nothing but -// an integral count of seconds since New Years 1970 (same epoch as timeval). -// Just get the duration out of the time_point and truncate it to seconds. -time_t -system_clock::to_time_t(const time_point& t) BOOST_NOEXCEPT -{ - return time_t(duration_cast(t.time_since_epoch()).count()); -} - -// Just turn the time_t into a count of seconds and construct a time_point with it. -system_clock::time_point -system_clock::from_time_t(time_t t) BOOST_NOEXCEPT -{ - return system_clock::time_point(seconds(t)); -} - -namespace chrono_detail -{ - -// steady_clock - -// Note, in this implementation steady_clock and high_resolution_clock -// are the same clock. They are both based on mach_absolute_time(). -// mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of -// nanoseconds since the computer booted up. MachInfo.numer and MachInfo.denom -// are run time constants supplied by the OS. This clock has no relationship -// to the Gregorian calendar. It's main use is as a high resolution timer. - -// MachInfo.numer / MachInfo.denom is often 1 on the latest equipment. Specialize -// for that case as an optimization. -BOOST_CHRONO_STATIC -steady_clock::rep -steady_simplified() -{ - return mach_absolute_time(); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -BOOST_CHRONO_STATIC -steady_clock::rep -steady_simplified_ec(system::error_code & ec) -{ - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return mach_absolute_time(); -} -#endif - -BOOST_CHRONO_STATIC -double -compute_steady_factor(kern_return_t& err) -{ - mach_timebase_info_data_t MachInfo; - err = mach_timebase_info(&MachInfo); - if ( err != 0 ) { - return 0; - } - return static_cast(MachInfo.numer) / MachInfo.denom; -} - -BOOST_CHRONO_STATIC -steady_clock::rep -steady_full() -{ - static kern_return_t err; - static const double factor = chrono_detail::compute_steady_factor(err); - if (err != 0) - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - return static_cast(mach_absolute_time() * factor); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -BOOST_CHRONO_STATIC -steady_clock::rep -steady_full_ec(system::error_code & ec) -{ - static kern_return_t err; - static const double factor = chrono_detail::compute_steady_factor(err); - if (err != 0) - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - err, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::steady_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return steady_clock::rep(); - } - } - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return static_cast(mach_absolute_time() * factor); -} -#endif - -typedef steady_clock::rep (*FP)(); -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -typedef steady_clock::rep (*FP_ec)(system::error_code &); -#endif - -BOOST_CHRONO_STATIC -FP -init_steady_clock(kern_return_t & err) -{ - mach_timebase_info_data_t MachInfo; - err = mach_timebase_info(&MachInfo); - if ( err != 0 ) - { - return 0; - } - - if (MachInfo.numer == MachInfo.denom) - { - return &chrono_detail::steady_simplified; - } - return &chrono_detail::steady_full; -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -BOOST_CHRONO_STATIC -FP_ec -init_steady_clock_ec(kern_return_t & err) -{ - mach_timebase_info_data_t MachInfo; - err = mach_timebase_info(&MachInfo); - if ( err != 0 ) - { - return 0; - } - - if (MachInfo.numer == MachInfo.denom) - { - return &chrono_detail::steady_simplified_ec; - } - return &chrono_detail::steady_full_ec; -} -#endif -} - -steady_clock::time_point -steady_clock::now() BOOST_NOEXCEPT -{ - static kern_return_t err; - static chrono_detail::FP fp = chrono_detail::init_steady_clock(err); - if ( err != 0 ) - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - return time_point(duration(fp())); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -steady_clock::time_point -steady_clock::now(system::error_code & ec) -{ - static kern_return_t err; - static chrono_detail::FP_ec fp = chrono_detail::init_steady_clock_ec(err); - if ( err != 0 ) - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - err, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::steady_clock" )); - } - else - { - ec.assign( err, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(duration(fp(ec))); -} -#endif -} // namespace chrono -} // namespace boost diff --git a/utils/boost_idb/boost/chrono/detail/inlined/mac/process_cpu_clocks.hpp b/utils/boost_idb/boost/chrono/detail/inlined/mac/process_cpu_clocks.hpp deleted file mode 100644 index 48753bdf..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/mac/process_cpu_clocks.hpp +++ /dev/null @@ -1,331 +0,0 @@ -// boost process_cpu_clocks.cpp -----------------------------------------------------------// - -// Copyright Beman Dawes 1994, 2006, 2008 -// Copyright Vicente J. Botet Escriba 2009 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// - -#include -#include -#include - -#include //for gettimeofday and timeval -#include //for times -# include - -namespace boost -{ - namespace chrono - { - namespace chrono_detail - { - - inline long tick_factor() // multiplier to convert ticks - // to nanoseconds; -1 if unknown - { - static long factor = 0; - if (!factor) - { - if ((factor = ::sysconf(_SC_CLK_TCK)) <= 0) - factor = -1; - else - { - BOOST_ASSERT(factor <= 1000000000l); // doesn't handle large ticks - factor = 1000000000l / factor; // compute factor - if (!factor) - factor = -1; - } - } - return factor; - } - } - - - process_real_cpu_clock::time_point process_real_cpu_clock::now() BOOST_NOEXCEPT - { -#if 0 - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - return time_point(nanoseconds(c * factor)); - } else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); -#else - clock_t c = ::clock(); - if (c == clock_t(-1)) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - return time_point( - duration(c*(1000000000l/CLOCKS_PER_SEC)) - ); -#endif - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - process_real_cpu_clock::time_point process_real_cpu_clock::now(system::error_code & ec) - { - -#if 0 - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_real_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(nanoseconds(c * factor)); - } else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_real_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } - } -#else - clock_t c = ::clock(); - if (c == clock_t(-1)) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_real_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } - return time_point( - duration(c*(1000000000l/CLOCKS_PER_SEC)) - ); - -#endif - - } -#endif - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - process_user_cpu_clock::time_point process_user_cpu_clock::now(system::error_code & ec) - { - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_user_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(nanoseconds((tm.tms_utime + tm.tms_cutime) * factor)); - } else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_user_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } - } - } -#endif - - process_user_cpu_clock::time_point process_user_cpu_clock::now() BOOST_NOEXCEPT - { - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - return time_point(nanoseconds((tm.tms_utime + tm.tms_cutime) - * factor)); - } else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); - } - process_system_cpu_clock::time_point process_system_cpu_clock::now() BOOST_NOEXCEPT - { - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - return time_point(nanoseconds((tm.tms_stime + tm.tms_cstime) - * factor)); - } else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - process_system_cpu_clock::time_point process_system_cpu_clock::now(system::error_code & ec) - { - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_system_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(nanoseconds((tm.tms_stime + tm.tms_cstime) * factor)); - } else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_system_cpu_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } - } - } -#endif - - process_cpu_clock::time_point process_cpu_clock::now() BOOST_NOEXCEPT - { - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - time_point::rep - r(c * factor, (tm.tms_utime + tm.tms_cutime) * factor, (tm.tms_stime - + tm.tms_cstime) * factor); - return time_point(duration(r)); - } else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - process_cpu_clock::time_point process_cpu_clock::now(system::error_code & ec) - { - - tms tm; - clock_t c = ::times(&tm); - if (c == clock_t(-1)) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } else - { - long factor = chrono_detail::tick_factor(); - if (factor != -1) - { - time_point::rep - r(c * factor, (tm.tms_utime + tm.tms_cutime) * factor, (tm.tms_stime - + tm.tms_cstime) * factor); - return time_point(duration(r)); - } else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception(system::system_error(errno, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::process_clock")); - } else - { - ec.assign(errno, BOOST_CHRONO_SYSTEM_CATEGORY); - return time_point(); - } - } - } - - } -#endif - - } -} diff --git a/utils/boost_idb/boost/chrono/detail/inlined/mac/thread_clock.hpp b/utils/boost_idb/boost/chrono/detail/inlined/mac/thread_clock.hpp deleted file mode 100644 index dad806e4..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/mac/thread_clock.hpp +++ /dev/null @@ -1,15 +0,0 @@ -// boost thread_clock.cpp -----------------------------------------------------------// - -// Copyright Vicente J. Botet Escriba 2010 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// - -#include -#include -#include - diff --git a/utils/boost_idb/boost/chrono/detail/inlined/posix/chrono.hpp b/utils/boost_idb/boost/chrono/detail/inlined/posix/chrono.hpp deleted file mode 100644 index e35a7ce2..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/posix/chrono.hpp +++ /dev/null @@ -1,120 +0,0 @@ -// posix/chrono.cpp --------------------------------------------------------------// - -// Copyright Beman Dawes 2008 -// Copyright Vicente J. Botet Escriba 2009 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -//----------------------------------------------------------------------------// -// POSIX // -//----------------------------------------------------------------------------// - -#include // for clock_gettime - -namespace boost -{ -namespace chrono -{ - - system_clock::time_point system_clock::now() BOOST_NOEXCEPT - { - timespec ts; - if ( ::clock_gettime( CLOCK_REALTIME, &ts ) ) - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - - return time_point(duration( - static_cast( ts.tv_sec ) * 1000000000 + ts.tv_nsec)); - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - system_clock::time_point system_clock::now(system::error_code & ec) - { - timespec ts; - if ( ::clock_gettime( CLOCK_REALTIME, &ts ) ) - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::system_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(duration( - static_cast( ts.tv_sec ) * 1000000000 + ts.tv_nsec)); - } -#endif - - std::time_t system_clock::to_time_t(const system_clock::time_point& t) BOOST_NOEXCEPT - { - return static_cast( t.time_since_epoch().count() / 1000000000 ); - } - - system_clock::time_point system_clock::from_time_t(std::time_t t) BOOST_NOEXCEPT - { - return time_point(duration(static_cast(t) * 1000000000)); - } - -#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY - - steady_clock::time_point steady_clock::now() BOOST_NOEXCEPT - { - timespec ts; - if ( ::clock_gettime( CLOCK_MONOTONIC, &ts ) ) - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - - return time_point(duration( - static_cast( ts.tv_sec ) * 1000000000 + ts.tv_nsec)); - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - steady_clock::time_point steady_clock::now(system::error_code & ec) - { - timespec ts; - if ( ::clock_gettime( CLOCK_MONOTONIC, &ts ) ) - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::steady_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(duration( - static_cast( ts.tv_sec ) * 1000000000 + ts.tv_nsec)); - } -#endif -#endif - -} // namespace chrono -} // namespace boost - - diff --git a/utils/boost_idb/boost/chrono/detail/inlined/posix/process_cpu_clocks.hpp b/utils/boost_idb/boost/chrono/detail/inlined/posix/process_cpu_clocks.hpp deleted file mode 100644 index 5d5c4f48..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/posix/process_cpu_clocks.hpp +++ /dev/null @@ -1,353 +0,0 @@ -// boost process_cpu_clocks.cpp -----------------------------------------------------------// - -// Copyright Beman Dawes 1994, 2006, 2008 -// Copyright Vicente J. Botet Escriba 2009 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// - -#include -#include -#include - -#include -#include -#include // for clock_gettime - - -namespace boost { namespace chrono { -namespace chrono_detail -{ - inline long tick_factor() // multiplier to convert ticks - // to nanoseconds; -1 if unknown - { - static long factor = 0; - if ( !factor ) - { - if ( (factor = ::sysconf( _SC_CLK_TCK )) <= 0 ) - factor = -1; - else - { - BOOST_ASSERT( factor <= 1000000000l ); // doesn't handle large ticks - factor = 1000000000l / factor; // compute factor - if ( !factor ) factor = -1; - } - } - return factor; - } -} - -process_real_cpu_clock::time_point process_real_cpu_clock::now() BOOST_NOEXCEPT -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - return time_point( - nanoseconds(c*chrono_detail::tick_factor())); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_real_cpu_clock::time_point process_real_cpu_clock::now( - system::error_code & ec) -{ - - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_real_cpu_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point( - nanoseconds(c*chrono_detail::tick_factor())); - } - else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_real_cpu_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - } -} -#endif - -process_user_cpu_clock::time_point process_user_cpu_clock::now() BOOST_NOEXCEPT -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - return time_point( - nanoseconds((tm.tms_utime + tm.tms_cutime)*chrono_detail::tick_factor())); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_user_cpu_clock::time_point process_user_cpu_clock::now( - system::error_code & ec) -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_user_cpu_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point( - nanoseconds((tm.tms_utime + tm.tms_cutime)*chrono_detail::tick_factor())); - } - else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_user_cpu_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - } -} -#endif - -process_system_cpu_clock::time_point process_system_cpu_clock::now() BOOST_NOEXCEPT -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return time_point(); - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - return time_point( - nanoseconds((tm.tms_stime + tm.tms_cstime)*chrono_detail::tick_factor())); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return time_point(); - } - } -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_system_cpu_clock::time_point process_system_cpu_clock::now( - system::error_code & ec) -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_system_cpu_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point( - nanoseconds((tm.tms_stime + tm.tms_cstime)*chrono_detail::tick_factor())); - } - else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_system_cpu_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - } -} -#endif - -process_cpu_clock::time_point process_cpu_clock::now() BOOST_NOEXCEPT -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - time_point::rep r( - 1000*c*chrono_detail::tick_factor(), - 1000*(tm.tms_utime + tm.tms_cutime)*chrono_detail::tick_factor(), - 1000*(tm.tms_stime + tm.tms_cstime)*chrono_detail::tick_factor()); - return time_point(duration(r)); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - } - return time_point(); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_cpu_clock::time_point process_cpu_clock::now( - system::error_code & ec ) -{ - tms tm; - clock_t c = ::times( &tm ); - if ( c == clock_t(-1) ) // error - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - else - { - if ( chrono_detail::tick_factor() != -1 ) - { - time_point::rep r( - 1000*c*chrono_detail::tick_factor(), - 1000*(tm.tms_utime + tm.tms_cutime)*chrono_detail::tick_factor(), - 1000*(tm.tms_stime + tm.tms_cstime)*chrono_detail::tick_factor()); - return time_point(duration(r)); - } - else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - } - -} -#endif - -} } diff --git a/utils/boost_idb/boost/chrono/detail/inlined/posix/thread_clock.hpp b/utils/boost_idb/boost/chrono/detail/inlined/posix/thread_clock.hpp deleted file mode 100644 index a1012240..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/posix/thread_clock.hpp +++ /dev/null @@ -1,91 +0,0 @@ -// boost thread_clock.cpp -----------------------------------------------------------// - -// Copyright Beman Dawes 1994, 2006, 2008 -// Copyright Vicente J. Botet Escriba 2009-2011 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// - -#include -#include -#include - -#if !defined(__VXWORKS__) -# include -#endif -# include -# include - -namespace boost { namespace chrono { - - thread_clock::time_point thread_clock::now( ) BOOST_NOEXCEPT - { - struct timespec ts; -#if defined CLOCK_THREAD_CPUTIME_ID - // get the timespec associated to the thread clock - if ( ::clock_gettime( CLOCK_THREAD_CPUTIME_ID, &ts ) ) -#else - // get the current thread - pthread_t pth=pthread_self(); - // get the clock_id associated to the current thread - clockid_t clock_id; - pthread_getcpuclockid(pth, &clock_id); - // get the timespec associated to the thread clock - if ( ::clock_gettime( clock_id, &ts ) ) -#endif - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - - // transform to nanoseconds - return time_point(duration( - static_cast( ts.tv_sec ) * 1000000000 + ts.tv_nsec)); - - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - thread_clock::time_point thread_clock::now( system::error_code & ec ) - { - struct timespec ts; -#if defined CLOCK_THREAD_CPUTIME_ID - // get the timespec associated to the thread clock - if ( ::clock_gettime( CLOCK_THREAD_CPUTIME_ID, &ts ) ) -#else - // get the current thread - pthread_t pth=pthread_self(); - // get the clock_id associated to the current thread - clockid_t clock_id; - pthread_getcpuclockid(pth, &clock_id); - // get the timespec associated to the thread clock - if ( ::clock_gettime( clock_id, &ts ) ) -#endif - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::thread_clock" )); - } - else - { - ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - // transform to nanoseconds - return time_point(duration( - static_cast( ts.tv_sec ) * 1000000000 + ts.tv_nsec)); - - } -#endif -} } diff --git a/utils/boost_idb/boost/chrono/detail/inlined/process_cpu_clocks.hpp b/utils/boost_idb/boost/chrono/detail/inlined/process_cpu_clocks.hpp deleted file mode 100644 index d37f6754..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/process_cpu_clocks.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// boost process_cpu_clocks.cpp -----------------------------------------------------------// - -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// -#ifndef BOOST_CHRONO_DETAIL_INLINED_PROCESS_CPU_CLOCKS_HPP -#define BOOST_CHRONO_DETAIL_INLINED_PROCESS_CPU_CLOCKS_HPP - - -#include -#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS) - -#include -#include -#include -#include - -//----------------------------------------------------------------------------// -// Windows // -//----------------------------------------------------------------------------// -#if defined(BOOST_CHRONO_WINDOWS_API) -#include - -//----------------------------------------------------------------------------// -// Mac // -//----------------------------------------------------------------------------// -#elif defined(BOOST_CHRONO_MAC_API) -#include - -//----------------------------------------------------------------------------// -// POSIX // -//----------------------------------------------------------------------------// -#elif defined(BOOST_CHRONO_POSIX_API) -#include - -#endif // POSIX - -#endif - -#endif diff --git a/utils/boost_idb/boost/chrono/detail/inlined/thread_clock.hpp b/utils/boost_idb/boost/chrono/detail/inlined/thread_clock.hpp deleted file mode 100644 index 16d19ef4..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/thread_clock.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// boost thread_clock.cpp -----------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// -#ifndef BOOST_CHRONO_DETAIL_INLINED_THREAD_CLOCK_HPP -#define BOOST_CHRONO_DETAIL_INLINED_THREAD_CLOCK_HPP - -#include -#include -#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK) -#include -#include -#include -#include -#include - -//----------------------------------------------------------------------------// -// Windows // -//----------------------------------------------------------------------------// -#if defined(BOOST_CHRONO_WINDOWS_API) -#include - -//----------------------------------------------------------------------------// -// Mac // -//----------------------------------------------------------------------------// -#elif defined(BOOST_CHRONO_MAC_API) -#include - -//----------------------------------------------------------------------------// -// POSIX // -//----------------------------------------------------------------------------// -#elif defined(BOOST_CHRONO_POSIX_API) -#include - -#endif // POSIX - -#endif -#endif diff --git a/utils/boost_idb/boost/chrono/detail/inlined/win/chrono.hpp b/utils/boost_idb/boost/chrono/detail/inlined/win/chrono.hpp deleted file mode 100644 index fcb5b290..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/win/chrono.hpp +++ /dev/null @@ -1,139 +0,0 @@ -// win/chrono.cpp --------------------------------------------------------------// - -// Copyright Beman Dawes 2008 -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -//----------------------------------------------------------------------------// -// Windows // -//----------------------------------------------------------------------------// -#ifndef BOOST_CHRONO_DETAIL_INLINED_WIN_CHRONO_HPP -#define BOOST_CHRONO_DETAIL_INLINED_WIN_CHRONO_HPP - -#include -#include -#include - -namespace boost -{ -namespace chrono -{ -namespace chrono_detail -{ - - BOOST_CHRONO_INLINE double get_nanosecs_per_tic() BOOST_NOEXCEPT - { - boost::detail::winapi::LARGE_INTEGER_ freq; - if ( !boost::detail::winapi::QueryPerformanceFrequency( &freq ) ) - return 0.0L; - return double(1000000000.0L / freq.QuadPart); - } - -} - - steady_clock::time_point steady_clock::now() BOOST_NOEXCEPT - { - static double nanosecs_per_tic = chrono_detail::get_nanosecs_per_tic(); - - boost::detail::winapi::LARGE_INTEGER_ pcount; - if ( (nanosecs_per_tic <= 0.0L) || - (!boost::detail::winapi::QueryPerformanceCounter( &pcount )) ) - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return steady_clock::time_point(); - } - - return steady_clock::time_point(steady_clock::duration( - static_cast((nanosecs_per_tic) * pcount.QuadPart))); - } - - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - steady_clock::time_point steady_clock::now( system::error_code & ec ) - { - static double nanosecs_per_tic = chrono_detail::get_nanosecs_per_tic(); - - boost::detail::winapi::LARGE_INTEGER_ pcount; - if ( (nanosecs_per_tic <= 0.0L) - || (!boost::detail::winapi::QueryPerformanceCounter( &pcount )) ) - { - boost::detail::winapi::DWORD_ cause = - ((nanosecs_per_tic <= 0.0L) - ? ERROR_NOT_SUPPORTED - : boost::detail::winapi::GetLastError()); - if (BOOST_CHRONO_IS_THROWS(ec)) { - boost::throw_exception( - system::system_error( - cause, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::steady_clock" )); - } - else - { - ec.assign( cause, BOOST_CHRONO_SYSTEM_CATEGORY ); - return steady_clock::time_point(duration(0)); - } - } - - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(duration( - static_cast(nanosecs_per_tic * pcount.QuadPart))); - } -#endif - - BOOST_CHRONO_INLINE - system_clock::time_point system_clock::now() BOOST_NOEXCEPT - { - boost::detail::winapi::FILETIME_ ft; - boost::detail::winapi::GetSystemTimeAsFileTime( &ft ); // never fails - return system_clock::time_point( - system_clock::duration( - ((static_cast<__int64>( ft.dwHighDateTime ) << 32) | ft.dwLowDateTime) - -116444736000000000LL - ) - ); - } - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - BOOST_CHRONO_INLINE - system_clock::time_point system_clock::now( system::error_code & ec ) - { - boost::detail::winapi::FILETIME_ ft; - boost::detail::winapi::GetSystemTimeAsFileTime( &ft ); // never fails - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return system_clock::time_point( - system_clock::duration( - ((static_cast<__int64>( ft.dwHighDateTime ) << 32) | ft.dwLowDateTime) - -116444736000000000LL - )); - } -#endif - - BOOST_CHRONO_INLINE - std::time_t system_clock::to_time_t(const system_clock::time_point& t) BOOST_NOEXCEPT - { - __int64 temp = t.time_since_epoch().count(); - temp /= 10000000; - return static_cast( temp ); - } - - BOOST_CHRONO_INLINE - system_clock::time_point system_clock::from_time_t(std::time_t t) BOOST_NOEXCEPT - { - __int64 temp = t; - temp *= 10000000; - return time_point(duration(temp)); - } - -} // namespace chrono -} // namespace boost - -#endif diff --git a/utils/boost_idb/boost/chrono/detail/inlined/win/process_cpu_clocks.hpp b/utils/boost_idb/boost/chrono/detail/inlined/win/process_cpu_clocks.hpp deleted file mode 100644 index abfad67b..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/win/process_cpu_clocks.hpp +++ /dev/null @@ -1,276 +0,0 @@ -// boost process_timer.cpp -----------------------------------------------------------// - -// Copyright Beman Dawes 1994, 2006, 2008 -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// -#ifndef BOOST_CHRONO_DETAIL_INLINED_WIN_PROCESS_CLOCK_HPP -#define BOOST_CHRONO_DETAIL_INLINED_WIN_PROCESS_CLOCK_HPP - -#include -//#include -#include -#include -#include - -#include -#include -#include - -namespace boost -{ -namespace chrono -{ - -process_real_cpu_clock::time_point process_real_cpu_clock::now() BOOST_NOEXCEPT -{ - clock_t c = ::clock(); - if ( c == clock_t(-1) ) // error - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - } - typedef ratio_divide >::type R; - return time_point( - duration(static_cast(c)*R::num/R::den) - ); -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_real_cpu_clock::time_point process_real_cpu_clock::now( - system::error_code & ec) -{ - clock_t c = ::clock(); - if ( c == clock_t(-1) ) // error - { - boost::throw_exception( - system::system_error( - errno, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_real_cpu_clock" )); - } - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - typedef ratio_divide >::type R; - return time_point( - duration(static_cast(c)*R::num/R::den) - ); -} -#endif - -process_user_cpu_clock::time_point process_user_cpu_clock::now() BOOST_NOEXCEPT -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetProcessTimes( - boost::detail::winapi::GetCurrentProcess(), &creation, &exit, - &system_time, &user_time ) ) - { - return time_point(duration( - ((static_cast(user_time.dwHighDateTime) << 32) - | user_time.dwLowDateTime) * 100 - )); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return time_point(); - } - -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_user_cpu_clock::time_point process_user_cpu_clock::now( - system::error_code & ec) -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetProcessTimes( - boost::detail::winapi::GetCurrentProcess(), &creation, &exit, - &system_time, &user_time ) ) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(duration( - ((static_cast(user_time.dwHighDateTime) << 32) - | user_time.dwLowDateTime) * 100 - )); - } - else - { - boost::detail::winapi::DWORD_ cause = boost::detail::winapi::GetLastError(); - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - cause, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_user_cpu_clock" )); - } - else - { - ec.assign( cause, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - -} -#endif - -process_system_cpu_clock::time_point process_system_cpu_clock::now() BOOST_NOEXCEPT -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetProcessTimes( - boost::detail::winapi::GetCurrentProcess(), &creation, &exit, - &system_time, &user_time ) ) - { - return time_point(duration( - ((static_cast(system_time.dwHighDateTime) << 32) - | system_time.dwLowDateTime) * 100 - )); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return time_point(); - } - -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_system_cpu_clock::time_point process_system_cpu_clock::now( - system::error_code & ec) -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetProcessTimes( - boost::detail::winapi::GetCurrentProcess(), &creation, &exit, - &system_time, &user_time ) ) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(duration( - ((static_cast(system_time.dwHighDateTime) << 32) - | system_time.dwLowDateTime) * 100 - )); - } - else - { - boost::detail::winapi::DWORD_ cause = boost::detail::winapi::GetLastError(); - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - cause, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_system_cpu_clock" )); - } - else - { - ec.assign( cause, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - -} -#endif - -process_cpu_clock::time_point process_cpu_clock::now() BOOST_NOEXCEPT -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetProcessTimes( - boost::detail::winapi::GetCurrentProcess(), &creation, &exit, - &system_time, &user_time ) ) - { - time_point::rep r(process_real_cpu_clock::now().time_since_epoch().count() - , - ((static_cast(user_time.dwHighDateTime) << 32) - | user_time.dwLowDateTime - ) * 100, - ((static_cast(system_time.dwHighDateTime) << 32) - | system_time.dwLowDateTime - ) * 100 - ); - return time_point(duration(r)); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return time_point(); - } - -} - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -process_cpu_clock::time_point process_cpu_clock::now( - system::error_code & ec ) -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetProcessTimes( - boost::detail::winapi::GetCurrentProcess(), &creation, &exit, - &system_time, &user_time ) ) - { - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - time_point::rep r(process_real_cpu_clock::now().time_since_epoch().count() - , - ((static_cast(user_time.dwHighDateTime) << 32) - | user_time.dwLowDateTime - ) * 100, - ((static_cast(system_time.dwHighDateTime) << 32) - | system_time.dwLowDateTime - ) * 100 - ); - return time_point(duration(r)); - } - else - { - boost::detail::winapi::DWORD_ cause = boost::detail::winapi::GetLastError(); - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - cause, - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::process_cpu_clock" )); - } - else - { - ec.assign( cause, BOOST_CHRONO_SYSTEM_CATEGORY ); - return time_point(); - } - } - -} -#endif -} // namespace chrono -} // namespace boost - -#endif diff --git a/utils/boost_idb/boost/chrono/detail/inlined/win/thread_clock.hpp b/utils/boost_idb/boost/chrono/detail/inlined/win/thread_clock.hpp deleted file mode 100644 index e47c4814..00000000 --- a/utils/boost_idb/boost/chrono/detail/inlined/win/thread_clock.hpp +++ /dev/null @@ -1,102 +0,0 @@ -// boost thread_clock.cpp -----------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/chrono for documentation. - -//--------------------------------------------------------------------------------------// -#ifndef BOOST_CHRONO_DETAIL_INLINED_WIN_THREAD_CLOCK_HPP -#define BOOST_CHRONO_DETAIL_INLINED_WIN_THREAD_CLOCK_HPP - -#include -#include -#include - -#include -#include -#include - -namespace boost -{ -namespace chrono -{ - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING -thread_clock::time_point thread_clock::now( system::error_code & ec ) -{ - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetThreadTimes( - boost::detail::winapi::GetCurrentThread (), &creation, &exit, - &system_time, &user_time ) ) - { - duration user = duration( - ((static_cast(user_time.dwHighDateTime) << 32) - | user_time.dwLowDateTime) * 100 ); - - duration system = duration( - ((static_cast(system_time.dwHighDateTime) << 32) - | system_time.dwLowDateTime) * 100 ); - - if (!BOOST_CHRONO_IS_THROWS(ec)) - { - ec.clear(); - } - return time_point(system+user); - - } - else - { - if (BOOST_CHRONO_IS_THROWS(ec)) - { - boost::throw_exception( - system::system_error( - boost::detail::winapi::GetLastError(), - BOOST_CHRONO_SYSTEM_CATEGORY, - "chrono::thread_clock" )); - } - else - { - ec.assign( boost::detail::winapi::GetLastError(), BOOST_CHRONO_SYSTEM_CATEGORY ); - return thread_clock::time_point(duration(0)); - } - } -} -#endif - -thread_clock::time_point thread_clock::now() BOOST_NOEXCEPT -{ - - // note that Windows uses 100 nanosecond ticks for FILETIME - boost::detail::winapi::FILETIME_ creation, exit, user_time, system_time; - - if ( boost::detail::winapi::GetThreadTimes( - boost::detail::winapi::GetCurrentThread (), &creation, &exit, - &system_time, &user_time ) ) - { - duration user = duration( - ((static_cast(user_time.dwHighDateTime) << 32) - | user_time.dwLowDateTime) * 100 ); - - duration system = duration( - ((static_cast(system_time.dwHighDateTime) << 32) - | system_time.dwLowDateTime) * 100 ); - - return time_point(system+user); - } - else - { - BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); - return time_point(); - } - -} - -} // namespace chrono -} // namespace boost - -#endif diff --git a/utils/boost_idb/boost/chrono/detail/is_evenly_divisible_by.hpp b/utils/boost_idb/boost/chrono/detail/is_evenly_divisible_by.hpp deleted file mode 100644 index 960a208a..00000000 --- a/utils/boost_idb/boost/chrono/detail/is_evenly_divisible_by.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// is_evenly_divisible_by.hpp --------------------------------------------------------------// - -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#ifndef BOOST_CHRONO_DETAIL_IS_EVENLY_DIVISIBLE_BY_HPP -#define BOOST_CHRONO_DETAIL_IS_EVENLY_DIVISIBLE_BY_HPP - -#include - -#include -#include - -namespace boost { -namespace chrono { -namespace chrono_detail { - -// template -// struct is_evenly_divisible_by : public boost::mpl::bool_ < ratio_divide::type::den == 1 > -// {}; - template - struct is_evenly_divisible_by : public boost::ratio_detail::is_evenly_divisible_by - {}; - -} // namespace chrono_detail -} // namespace detail -} // namespace chrono - -#endif // BOOST_CHRONO_DETAIL_IS_EVENLY_DIVISIBLE_BY_HPP diff --git a/utils/boost_idb/boost/chrono/detail/no_warning/signed_unsigned_cmp.hpp b/utils/boost_idb/boost/chrono/detail/no_warning/signed_unsigned_cmp.hpp deleted file mode 100644 index 94936c8b..00000000 --- a/utils/boost_idb/boost/chrono/detail/no_warning/signed_unsigned_cmp.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// is_evenly_divisible_by.hpp --------------------------------------------------------------// - -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#ifndef BOOST_CHRONO_DETAIL_NO_WARNING_SIGNED_UNSIGNED_CMP_HPP -#define BOOST_CHRONO_DETAIL_NO_WARNING_SIGNED_UNSIGNED_CMP_HPP - -// -// We simply cannot include this header on gcc without getting copious warnings of the kind: -// -//../../../boost/chrono/detail/no_warning/signed_unsigned_cmp.hpp:37: warning: comparison between signed and unsigned integer expressions -// -// And yet there is no other reasonable implementation, so we declare this a system header -// to suppress these warnings. -// - -#if defined(__GNUC__) && (__GNUC__ >= 4) -#pragma GCC system_header -#elif defined __SUNPRO_CC -#pragma disable_warn -#elif defined _MSC_VER -#pragma warning(push, 1) -#endif - -namespace boost { -namespace chrono { -namespace detail { - - template - bool lt(T t, U u) - { - return t < u; - } - - template - bool gt(T t, U u) - { - return t > u; - } - -} // namespace detail -} // namespace detail -} // namespace chrono - -#if defined __SUNPRO_CC -#pragma enable_warn -#elif defined _MSC_VER -#pragma warning(pop) -#endif - -#endif // BOOST_CHRONO_DETAIL_NO_WARNING_SIGNED_UNSIGNED_CMP_HPP diff --git a/utils/boost_idb/boost/chrono/detail/scan_keyword.hpp b/utils/boost_idb/boost/chrono/detail/scan_keyword.hpp deleted file mode 100644 index 7c3ba6e2..00000000 --- a/utils/boost_idb/boost/chrono/detail/scan_keyword.hpp +++ /dev/null @@ -1,163 +0,0 @@ -// scan_keyword.hpp --------------------------------------------------------------// -//===----------------------------------------------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// Adaptation to Boost of the libcxx - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#ifndef BOOST_CHRONO_DETAIL_SCAN_KEYWORD_HPP -#define BOOST_CHRONO_DETAIL_SCAN_KEYWORD_HPP - -#include - -#include -#include -#include -#include -#include - -namespace boost { - using interprocess::unique_ptr; - -namespace chrono { -namespace chrono_detail { - -inline void free_aux(void* ptr) { free(ptr); } - -// scan_keyword -// Scans [b, e) until a match is found in the basic_strings range -// [kb, ke) or until it can be shown that there is no match in [kb, ke). -// b will be incremented (visibly), consuming CharT until a match is found -// or proved to not exist. A keyword may be "", in which will match anything. -// If one keyword is a prefix of another, and the next CharT in the input -// might match another keyword, the algorithm will attempt to find the longest -// matching keyword. If the longer matching keyword ends up not matching, then -// no keyword match is found. If no keyword match is found, ke is returned -// and failbit is set in err. -// Else an iterator pointing to the matching keyword is found. If more than -// one keyword matches, an iterator to the first matching keyword is returned. -// If on exit b == e, eofbit is set in err. -// Examples: -// Keywords: "a", "abb" -// If the input is "a", the first keyword matches and eofbit is set. -// If the input is "abc", no match is found and "ab" are consumed. - -template -ForwardIterator -scan_keyword(InputIterator& b, InputIterator e, - ForwardIterator kb, ForwardIterator ke, - std::ios_base::iostate& err - ) -{ - typedef typename std::iterator_traits::value_type CharT; - size_t nkw = std::distance(kb, ke); - const unsigned char doesnt_match = '\0'; - const unsigned char might_match = '\1'; - const unsigned char does_match = '\2'; - unsigned char statbuf[100]; - unsigned char* status = statbuf; - // Change free by free_aux to avoid - // Error: Could not find a match for boost::interprocess::unique_ptr::unique_ptr(int, extern "C" void(void*)) - unique_ptr stat_hold(0, free_aux); - if (nkw > sizeof(statbuf)) - { - status = (unsigned char*)malloc(nkw); - if (status == 0) - throw_exception(std::bad_alloc()); - stat_hold.reset(status); - } - size_t n_might_match = nkw; // At this point, any keyword might match - size_t n_does_match = 0; // but none of them definitely do - // Initialize all statuses to might_match, except for "" keywords are does_match - unsigned char* st = status; - for (ForwardIterator ky = kb; ky != ke; ++ky, ++st) - { - if (!ky->empty()) - *st = might_match; - else - { - *st = does_match; - --n_might_match; - ++n_does_match; - } - } - // While there might be a match, test keywords against the next CharT - for (size_t indx = 0; b != e && n_might_match > 0; ++indx) - { - // Peek at the next CharT but don't consume it - CharT c = *b; - bool consume = false; - // For each keyword which might match, see if the indx character is c - // If a match if found, consume c - // If a match is found, and that is the last character in the keyword, - // then that keyword matches. - // If the keyword doesn't match this character, then change the keyword - // to doesn't match - st = status; - for (ForwardIterator ky = kb; ky != ke; ++ky, ++st) - { - if (*st == might_match) - { - CharT kc = (*ky)[indx]; - if (c == kc) - { - consume = true; - if (ky->size() == indx+1) - { - *st = does_match; - --n_might_match; - ++n_does_match; - } - } - else - { - *st = doesnt_match; - --n_might_match; - } - } - } - // consume if we matched a character - if (consume) - { - ++b; - // If we consumed a character and there might be a matched keyword that - // was marked matched on a previous iteration, then such keywords - // which are now marked as not matching. - if (n_might_match + n_does_match > 1) - { - st = status; - for (ForwardIterator ky = kb; ky != ke; ++ky, ++st) - { - if (*st == does_match && ky->size() != indx+1) - { - *st = doesnt_match; - --n_does_match; - } - } - } - } - } - // We've exited the loop because we hit eof and/or we have no more "might matches". - if (b == e) - err |= std::ios_base::eofbit; - // Return the first matching result - for (st = status; kb != ke; ++kb, ++st) - if (*st == does_match) - break; - if (kb == ke) - err |= std::ios_base::failbit; - return kb; -} -} -} -} -#endif // BOOST_CHRONO_DETAIL_SCAN_KEYWORD_HPP diff --git a/utils/boost_idb/boost/chrono/detail/static_assert.hpp b/utils/boost_idb/boost/chrono/detail/static_assert.hpp deleted file mode 100644 index 86151947..00000000 --- a/utils/boost_idb/boost/chrono/detail/static_assert.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// static_assert.hpp --------------------------------------------------------------// - -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_CHRONO_DETAIL_STATIC_ASSERT_HPP -#define BOOST_CHRONO_DETAIL_STATIC_ASSERT_HPP - -#include - -#ifndef BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_CHRONO_STATIC_ASSERT(CND, MSG, TYPES) static_assert(CND,MSG) -#elif defined(BOOST_CHRONO_USES_STATIC_ASSERT) -#include -#define BOOST_CHRONO_STATIC_ASSERT(CND, MSG, TYPES) BOOST_STATIC_ASSERT(CND) -#elif defined(BOOST_CHRONO_USES_MPL_ASSERT) -#include -#include -#define BOOST_CHRONO_STATIC_ASSERT(CND, MSG, TYPES) \ - BOOST_MPL_ASSERT_MSG(boost::mpl::bool_< (CND) >::type::value, MSG, TYPES) -#else -//~ #elif defined(BOOST_CHRONO_USES_ARRAY_ASSERT) -#define BOOST_CHRONO_STATIC_ASSERT(CND, MSG, TYPES) static char BOOST_JOIN(boost_chrono_test_,__LINE__)[(CND)?1:-1] -//~ #define BOOST_CHRONO_STATIC_ASSERT(CND, MSG, TYPES) -#endif - -#endif // BOOST_CHRONO_DETAIL_STATIC_ASSERT_HPP diff --git a/utils/boost_idb/boost/chrono/detail/system.hpp b/utils/boost_idb/boost/chrono/detail/system.hpp deleted file mode 100644 index 0dcffe85..00000000 --- a/utils/boost_idb/boost/chrono/detail/system.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009-2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#ifndef BOOST_CHRONO_DETAIL_SYSTEM_HPP -#define BOOST_CHRONO_DETAIL_SYSTEM_HPP - -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - -#include -#include - -#if ((BOOST_VERSION / 100000) < 2) && ((BOOST_VERSION / 100 % 1000) < 44) -#define BOOST_CHRONO_SYSTEM_CATEGORY boost::system::system_category -#else -#define BOOST_CHRONO_SYSTEM_CATEGORY boost::system::system_category() -#endif - -#ifdef BOOST_SYSTEM_NO_DEPRECATED -#define BOOST_CHRONO_THROWS boost::throws() -#define BOOST_CHRONO_IS_THROWS(EC) (&EC==&boost::throws()) -#else -#define BOOST_CHRONO_THROWS boost::system::throws -#define BOOST_CHRONO_IS_THROWS(EC) (&EC==&boost::system::throws) -#endif - -#endif -#endif diff --git a/utils/boost_idb/boost/chrono/duration.hpp b/utils/boost_idb/boost/chrono/duration.hpp deleted file mode 100644 index 814adb0e..00000000 --- a/utils/boost_idb/boost/chrono/duration.hpp +++ /dev/null @@ -1,794 +0,0 @@ -// duration.hpp --------------------------------------------------------------// - -// Copyright 2008 Howard Hinnant -// Copyright 2008 Beman Dawes -// Copyright 2009-2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -/* - -This code was derived by Beman Dawes from Howard Hinnant's time2_demo prototype. -Many thanks to Howard for making his code available under the Boost license. -The original code was modified to conform to Boost conventions and to section -20.9 Time utilities [time] of the C++ committee's working paper N2798. -See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf. - -time2_demo contained this comment: - - Much thanks to Andrei Alexandrescu, - Walter Brown, - Peter Dimov, - Jeff Garland, - Terry Golubiewski, - Daniel Krugler, - Anthony Williams. -*/ - - -#ifndef BOOST_CHRONO_DURATION_HPP -#define BOOST_CHRONO_DURATION_HPP - -#include -#include - -#include -#include - - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#if !defined(BOOST_NO_CXX11_STATIC_ASSERT) || !defined(BOOST_CHRONO_USES_MPL_ASSERT) -#define BOOST_CHRONO_A_DURATION_REPRESENTATION_CAN_NOT_BE_A_DURATION "A duration representation can not be a duration" -#define BOOST_CHRONO_SECOND_TEMPLATE_PARAMETER_OF_DURATION_MUST_BE_A_STD_RATIO "Second template parameter of duration must be a boost::ratio" -#define BOOST_CHRONO_DURATION_PERIOD_MUST_BE_POSITIVE "duration period must be positive" -#define BOOST_CHRONO_SECOND_TEMPLATE_PARAMETER_OF_TIME_POINT_MUST_BE_A_BOOST_CHRONO_DURATION "Second template parameter of time_point must be a boost::chrono::duration" -#endif - -#ifndef BOOST_CHRONO_HEADER_ONLY -// this must occur after all of the includes and before any code appears: -#include // must be the last #include -#endif - -//----------------------------------------------------------------------------// -// // -// 20.9 Time utilities [time] // -// synopsis // -// // -//----------------------------------------------------------------------------// - -namespace boost { -namespace chrono { - - template > - class duration; - - namespace detail - { - template - struct is_duration - : boost::false_type {}; - - template - struct is_duration > - : boost::true_type {}; - - template ::value> - struct duration_divide_result - { - }; - - template ::type>::value)) - && ((boost::is_convertible::type>::value)) - ) - > - struct duration_divide_imp - { - }; - - template - struct duration_divide_imp, Rep2, true> - { - typedef duration::type, Period> type; - }; - - template - struct duration_divide_result, Rep2, false> - : duration_divide_imp, Rep2> - { - }; - -/// - template ::value> - struct duration_divide_result2 - { - }; - - template ::type>::value)) - && ((boost::is_convertible::type>::value)) - ) - > - struct duration_divide_imp2 - { - }; - - template - struct duration_divide_imp2, true> - { - //typedef typename common_type::type type; - typedef double type; - }; - - template - struct duration_divide_result2, false> - : duration_divide_imp2 > - { - }; - -/// - template ::value> - struct duration_modulo_result - { - }; - - template ::type>::value - //&& - boost::is_convertible::type>::value - ) - > - struct duration_modulo_imp - { - }; - - template - struct duration_modulo_imp, Rep2, true> - { - typedef duration::type, Period> type; - }; - - template - struct duration_modulo_result, Rep2, false> - : duration_modulo_imp, Rep2> - { - }; - -} // namespace detail -} // namespace chrono - - -// common_type trait specializations - -template -struct common_type, - chrono::duration >; - - -namespace chrono { - - // customization traits - template struct treat_as_floating_point; - template struct duration_values; - - // convenience typedefs - typedef duration nanoseconds; // at least 64 bits needed - typedef duration microseconds; // at least 55 bits needed - typedef duration milliseconds; // at least 45 bits needed - typedef duration seconds; // at least 35 bits needed - typedef duration > minutes; // at least 29 bits needed - typedef duration > hours; // at least 23 bits needed - -//----------------------------------------------------------------------------// -// duration helpers // -//----------------------------------------------------------------------------// - -namespace detail -{ - - // duration_cast - - // duration_cast is the heart of this whole prototype. It can convert any - // duration to any other. It is also (implicitly) used in converting - // time_points. The conversion is always exact if possible. And it is - // always as efficient as hand written code. If different representations - // are involved, care is taken to never require implicit conversions. - // Instead static_cast is used explicitly for every required conversion. - // If there are a mixture of integral and floating point representations, - // the use of common_type ensures that the most logical "intermediate" - // representation is used. - template - struct duration_cast_aux; - - // When the two periods are the same, all that is left to do is static_cast from - // the source representation to the target representation (which may be a no-op). - // This conversion is always exact as long as the static_cast from the source - // representation to the destination representation is exact. - template - struct duration_cast_aux - { - BOOST_CONSTEXPR ToDuration operator()(const FromDuration& fd) const - { - return ToDuration(static_cast(fd.count())); - } - }; - - // When the numerator of FromPeriod / ToPeriod is 1, then all we need to do is - // divide by the denominator of FromPeriod / ToPeriod. The common_type of - // the two representations is used for the intermediate computation before - // static_cast'ing to the destination. - // This conversion is generally not exact because of the division (but could be - // if you get lucky on the run time value of fd.count()). - template - struct duration_cast_aux - { - BOOST_CONSTEXPR ToDuration operator()(const FromDuration& fd) const - { - typedef typename common_type< - typename ToDuration::rep, - typename FromDuration::rep, - boost::intmax_t>::type C; - return ToDuration(static_cast( - static_cast(fd.count()) / static_cast(Period::den))); - } - }; - - // When the denominator of FromPeriod / ToPeriod is 1, then all we need to do is - // multiply by the numerator of FromPeriod / ToPeriod. The common_type of - // the two representations is used for the intermediate computation before - // static_cast'ing to the destination. - // This conversion is always exact as long as the static_cast's involved are exact. - template - struct duration_cast_aux - { - BOOST_CONSTEXPR ToDuration operator()(const FromDuration& fd) const - { - typedef typename common_type< - typename ToDuration::rep, - typename FromDuration::rep, - boost::intmax_t>::type C; - return ToDuration(static_cast( - static_cast(fd.count()) * static_cast(Period::num))); - } - }; - - // When neither the numerator or denominator of FromPeriod / ToPeriod is 1, then we need to - // multiply by the numerator and divide by the denominator of FromPeriod / ToPeriod. The - // common_type of the two representations is used for the intermediate computation before - // static_cast'ing to the destination. - // This conversion is generally not exact because of the division (but could be - // if you get lucky on the run time value of fd.count()). - template - struct duration_cast_aux - { - BOOST_CONSTEXPR ToDuration operator()(const FromDuration& fd) const - { - typedef typename common_type< - typename ToDuration::rep, - typename FromDuration::rep, - boost::intmax_t>::type C; - return ToDuration(static_cast( - static_cast(fd.count()) * static_cast(Period::num) - / static_cast(Period::den))); - } - }; - - template - struct duration_cast { - typedef typename ratio_divide::type Period; - typedef duration_cast_aux< - FromDuration, - ToDuration, - Period, - Period::num == 1, - Period::den == 1 - > Aux; - BOOST_CONSTEXPR ToDuration operator()(const FromDuration& fd) const - { - return Aux()(fd); - } - }; - -} // namespace detail - -//----------------------------------------------------------------------------// -// // -// 20.9.2 Time-related traits [time.traits] // -// // -//----------------------------------------------------------------------------// -//----------------------------------------------------------------------------// -// 20.9.2.1 treat_as_floating_point [time.traits.is_fp] // -// Probably should have been treat_as_floating_point. Editor notifed. // -//----------------------------------------------------------------------------// - - // Support bidirectional (non-exact) conversions for floating point rep types - // (or user defined rep types which specialize treat_as_floating_point). - template - struct treat_as_floating_point : boost::is_floating_point {}; - -//----------------------------------------------------------------------------// -// 20.9.2.2 duration_values [time.traits.duration_values] // -//----------------------------------------------------------------------------// - -namespace detail { - template ::value> - struct chrono_numeric_limits { - static BOOST_CHRONO_LIB_CONSTEXPR T lowest() BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW {return (std::numeric_limits::min) ();} - }; - - template - struct chrono_numeric_limits { - static BOOST_CHRONO_LIB_CONSTEXPR T lowest() BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW {return (std::numeric_limits::min) ();} - }; - - template <> - struct chrono_numeric_limits { - static BOOST_CHRONO_LIB_CONSTEXPR float lowest() BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW - { - return -(std::numeric_limits::max) (); - } - }; - - template <> - struct chrono_numeric_limits { - static BOOST_CHRONO_LIB_CONSTEXPR double lowest() BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW - { - return -(std::numeric_limits::max) (); - } - }; - - template <> - struct chrono_numeric_limits { - static BOOST_CHRONO_LIB_CONSTEXPR long double lowest() BOOST_CHRONO_LIB_NOEXCEPT_OR_THROW - { - return -(std::numeric_limits::max)(); - } - }; - - template - struct numeric_limits : chrono_numeric_limits::type> - {}; - -} -template -struct duration_values -{ - static BOOST_CONSTEXPR Rep zero() {return Rep(0);} - static BOOST_CHRONO_LIB_CONSTEXPR Rep max BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return (std::numeric_limits::max)(); - } - - static BOOST_CHRONO_LIB_CONSTEXPR Rep min BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return detail::numeric_limits::lowest(); - } -}; - -} // namespace chrono - -//----------------------------------------------------------------------------// -// 20.9.2.3 Specializations of common_type [time.traits.specializations] // -//----------------------------------------------------------------------------// - -template -struct common_type, - chrono::duration > -{ - typedef chrono::duration::type, - typename boost::ratio_gcd::type> type; -}; - - -//----------------------------------------------------------------------------// -// // -// 20.9.3 Class template duration [time.duration] // -// // -//----------------------------------------------------------------------------// - - -namespace chrono { - - template - class BOOST_SYMBOL_VISIBLE duration - { - //BOOST_CHRONO_STATIC_ASSERT(boost::is_integral::value, BOOST_CHRONO_A_DURATION_REPRESENTATION_MUST_BE_INTEGRAL, ()); - BOOST_CHRONO_STATIC_ASSERT(!boost::chrono::detail::is_duration::value, - BOOST_CHRONO_A_DURATION_REPRESENTATION_CAN_NOT_BE_A_DURATION, ()); - BOOST_CHRONO_STATIC_ASSERT(boost::ratio_detail::is_ratio::value, - BOOST_CHRONO_SECOND_TEMPLATE_PARAMETER_OF_DURATION_MUST_BE_A_STD_RATIO, ()); - BOOST_CHRONO_STATIC_ASSERT(Period::num>0, - BOOST_CHRONO_DURATION_PERIOD_MUST_BE_POSITIVE, ()); - public: - typedef Rep rep; - typedef Period period; - private: - rep rep_; - public: - - BOOST_FORCEINLINE BOOST_CONSTEXPR - duration() : rep_(duration_values::zero()) { } - template - BOOST_SYMBOL_VISIBLE BOOST_FORCEINLINE BOOST_CONSTEXPR - explicit duration(const Rep2& r - , typename boost::enable_if < - mpl::and_ < - boost::is_convertible, - mpl::or_ < - treat_as_floating_point, - mpl::and_ < - mpl::not_ < treat_as_floating_point >, - mpl::not_ < treat_as_floating_point > - > - > - > - >::type* = 0 - ) : rep_(r) { } - //~duration() {} //= default; -// BOOST_CONSTEXPR duration(const duration& rhs) : rep_(rhs.rep_) {} // = default; - duration& operator=(const duration& rhs) // = default; - { - if (&rhs != this) rep_= rhs.rep_; - return *this; - } - - // conversions - template - BOOST_FORCEINLINE BOOST_CONSTEXPR - duration(const duration& d - , typename boost::enable_if < - mpl::or_ < - treat_as_floating_point, - mpl::and_ < - chrono_detail::is_evenly_divisible_by, - mpl::not_ < treat_as_floating_point > - > - > - >::type* = 0 - ) - : rep_(chrono::detail::duration_cast, duration>()(d).count()) {} - - // observer - - BOOST_CONSTEXPR - rep count() const {return rep_;} - - // arithmetic - - BOOST_CONSTEXPR - duration operator+() const {return duration(rep_);;} - BOOST_CONSTEXPR - duration operator-() const {return duration(-rep_);} - duration& operator++() {++rep_; return *this;} - duration operator++(int) {return duration(rep_++);} - duration& operator--() {--rep_; return *this;} - duration operator--(int) {return duration(rep_--);} - - duration& operator+=(const duration& d) - { - rep_ += d.count(); return *this; - } - duration& operator-=(const duration& d) - { - rep_ -= d.count(); return *this; - } - - duration& operator*=(const rep& rhs) {rep_ *= rhs; return *this;} - duration& operator/=(const rep& rhs) {rep_ /= rhs; return *this;} - duration& operator%=(const rep& rhs) {rep_ %= rhs; return *this;} - duration& operator%=(const duration& rhs) - { - rep_ %= rhs.count(); return *this; - } - // 20.9.3.4 duration special values [time.duration.special] - - static BOOST_CONSTEXPR duration zero() - { - return duration(duration_values::zero()); - } - static BOOST_CHRONO_LIB_CONSTEXPR duration min BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return duration((duration_values::min)()); - } - static BOOST_CHRONO_LIB_CONSTEXPR duration max BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return duration((duration_values::max)()); - } - }; - -//----------------------------------------------------------------------------// -// 20.9.3.5 duration non-member arithmetic [time.duration.nonmember] // -//----------------------------------------------------------------------------// - - // Duration + - - template - inline BOOST_CONSTEXPR - typename common_type, duration >::type - operator+(const duration& lhs, - const duration& rhs) - { - typedef typename common_type, - duration >::type CD; - return CD(CD(lhs).count()+CD(rhs).count()); - } - - // Duration - - - template - inline BOOST_CONSTEXPR - typename common_type, duration >::type - operator-(const duration& lhs, - const duration& rhs) - { - typedef typename common_type, - duration >::type CD; - return CD(CD(lhs).count()-CD(rhs).count()); - } - - // Duration * - - template - inline BOOST_CONSTEXPR - typename boost::enable_if < - mpl::and_ < - boost::is_convertible::type>, - boost::is_convertible::type> - >, - duration::type, Period> - >::type - operator*(const duration& d, const Rep2& s) - { - typedef typename common_type::type CR; - typedef duration CD; - return CD(CD(d).count()*static_cast(s)); - } - - template - inline BOOST_CONSTEXPR - typename boost::enable_if < - mpl::and_ < - boost::is_convertible::type>, - boost::is_convertible::type> - >, - duration::type, Period> - >::type - operator*(const Rep1& s, const duration& d) - { - return d * s; - } - - // Duration / - - template - inline BOOST_CONSTEXPR - typename boost::disable_if , - typename boost::chrono::detail::duration_divide_result< - duration, Rep2>::type - >::type - operator/(const duration& d, const Rep2& s) - { - typedef typename common_type::type CR; - typedef duration CD; - - return CD(CD(d).count()/static_cast(s)); - } - - template - inline BOOST_CONSTEXPR - typename common_type::type - operator/(const duration& lhs, const duration& rhs) - { - typedef typename common_type, - duration >::type CD; - return CD(lhs).count() / CD(rhs).count(); - } - - #ifdef BOOST_CHRONO_EXTENSIONS - template - inline BOOST_CONSTEXPR - typename boost::disable_if , - typename boost::chrono::detail::duration_divide_result2< - Rep1, duration >::type - >::type - operator/(const Rep1& s, const duration& d) - { - typedef typename common_type::type CR; - typedef duration CD; - - return static_cast(s)/CD(d).count(); - } - #endif - // Duration % - - template - inline BOOST_CONSTEXPR - typename boost::disable_if , - typename boost::chrono::detail::duration_modulo_result< - duration, Rep2>::type - >::type - operator%(const duration& d, const Rep2& s) - { - typedef typename common_type::type CR; - typedef duration CD; - - return CD(CD(d).count()%static_cast(s)); - } - - template - inline BOOST_CONSTEXPR - typename common_type, duration >::type - operator%(const duration& lhs, - const duration& rhs) { - typedef typename common_type, - duration >::type CD; - - return CD(CD(lhs).count()%CD(rhs).count()); - } - - -//----------------------------------------------------------------------------// -// 20.9.3.6 duration comparisons [time.duration.comparisons] // -//----------------------------------------------------------------------------// - -namespace detail -{ - template - struct duration_eq - { - BOOST_CONSTEXPR bool operator()(const LhsDuration& lhs, const RhsDuration& rhs) const - { - typedef typename common_type::type CD; - return CD(lhs).count() == CD(rhs).count(); - } - }; - - template - struct duration_eq - { - BOOST_CONSTEXPR bool operator()(const LhsDuration& lhs, const LhsDuration& rhs) const - { - return lhs.count() == rhs.count(); - } - }; - - template - struct duration_lt - { - BOOST_CONSTEXPR bool operator()(const LhsDuration& lhs, const RhsDuration& rhs) const - { - typedef typename common_type::type CD; - return CD(lhs).count() < CD(rhs).count(); - } - }; - - template - struct duration_lt - { - BOOST_CONSTEXPR bool operator()(const LhsDuration& lhs, const LhsDuration& rhs) const - { - return lhs.count() < rhs.count(); - } - }; - -} // namespace detail - - // Duration == - - template - inline BOOST_CONSTEXPR - bool - operator==(const duration& lhs, - const duration& rhs) - { - return boost::chrono::detail::duration_eq< - duration, duration >()(lhs, rhs); - } - - // Duration != - - template - inline BOOST_CONSTEXPR - bool - operator!=(const duration& lhs, - const duration& rhs) - { - return !(lhs == rhs); - } - - // Duration < - - template - inline BOOST_CONSTEXPR - bool - operator< (const duration& lhs, - const duration& rhs) - { - return boost::chrono::detail::duration_lt< - duration, duration >()(lhs, rhs); - } - - // Duration > - - template - inline BOOST_CONSTEXPR - bool - operator> (const duration& lhs, - const duration& rhs) - { - return rhs < lhs; - } - - // Duration <= - - template - inline BOOST_CONSTEXPR - bool - operator<=(const duration& lhs, - const duration& rhs) - { - return !(rhs < lhs); - } - - // Duration >= - - template - inline BOOST_CONSTEXPR - bool - operator>=(const duration& lhs, - const duration& rhs) - { - return !(lhs < rhs); - } - -//----------------------------------------------------------------------------// -// 20.9.3.7 duration_cast [time.duration.cast] // -//----------------------------------------------------------------------------// - - // Compile-time select the most efficient algorithm for the conversion... - template - inline BOOST_CONSTEXPR - typename boost::enable_if < - boost::chrono::detail::is_duration, ToDuration>::type - duration_cast(const duration& fd) - { - return boost::chrono::detail::duration_cast< - duration, ToDuration>()(fd); - } - -} // namespace chrono -} // namespace boost - -#ifndef BOOST_CHRONO_HEADER_ONLY -// the suffix header occurs after all of our code: -#include // pops abi_prefix.hpp pragmas -#endif - -#endif // BOOST_CHRONO_DURATION_HPP diff --git a/utils/boost_idb/boost/chrono/floor.hpp b/utils/boost_idb/boost/chrono/floor.hpp deleted file mode 100644 index e133e49c..00000000 --- a/utils/boost_idb/boost/chrono/floor.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// boost/chrono/round.hpp ------------------------------------------------------------// - -// (C) Copyright Howard Hinnant -// Copyright 2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/libs/chrono for documentation. - -#ifndef BOOST_CHRONO_FLOOR_HPP -#define BOOST_CHRONO_FLOOR_HPP - -#include - -namespace boost -{ - namespace chrono - { - - /** - * rounds down - */ - template - To floor(const duration& d) - { - return duration_cast(d); - } - - - } // namespace chrono -} // namespace boost - -#endif diff --git a/utils/boost_idb/boost/chrono/include.hpp b/utils/boost_idb/boost/chrono/include.hpp deleted file mode 100644 index b58f76be..00000000 --- a/utils/boost_idb/boost/chrono/include.hpp +++ /dev/null @@ -1,23 +0,0 @@ - -// include -// -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o under lvm/libc++ to Boost - -#ifndef BOOST_CHRONO_INCLUDE_HPP -#define BOOST_CHRONO_INCLUDE_HPP - -#include -#include -#include -#include -#include -#include -#include - -#endif // BOOST_CHRONO_INCLUDE_HPP diff --git a/utils/boost_idb/boost/chrono/io/duration_get.hpp b/utils/boost_idb/boost/chrono/io/duration_get.hpp deleted file mode 100644 index 3b051e28..00000000 --- a/utils/boost_idb/boost/chrono/io/duration_get.hpp +++ /dev/null @@ -1,547 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -#ifndef BOOST_CHRONO_IO_DURATION_GET_HPP -#define BOOST_CHRONO_IO_DURATION_GET_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -/** - * Duration formatting facet for input. - */ -namespace boost -{ - namespace chrono - { - - namespace detail - { - template ::value> - struct duration_io_intermediate - { - typedef Rep type; - }; - - template - struct duration_io_intermediate - { - typedef typename mpl::if_c::value, long double, typename mpl::if_c< - is_signed::value, long long, unsigned long long>::type>::type type; - }; - - template - typename enable_if , bool>::type reduce(intermediate_type& r, - unsigned long long& den, std::ios_base::iostate& err) - { - typedef typename common_type::type common_type_t; - - // Reduce r * num / den - common_type_t t = math::gcd(common_type_t(r), common_type_t(den)); - r /= t; - den /= t; - if (den != 1) - { - // Conversion to Period is integral and not exact - err |= std::ios_base::failbit; - return false; - } - return true; - } - template - typename disable_if , bool>::type reduce(intermediate_type&, unsigned long long&, - std::ios_base::iostate&) - { - return true; - } - - } - - /** - * @c duration_get is used to parse a character sequence, extracting - * components of a duration into a class duration. - * Each get member parses a format as produced by a corresponding format specifier to time_put<>::put. - * If the sequence being parsed matches the correct format, the - * corresponding member of the class duration argument are set to the - * value used to produce the sequence; - * otherwise either an error is reported or unspecified values are assigned. - * In other words, user confirmation is required for reliable parsing of - * user-entered durations, but machine-generated formats can be parsed - * reliably. This allows parsers to be aggressive about interpreting user - * variations on standard formats. - * - * If the end iterator is reached during parsing of the get() member - * function, the member sets std::ios_base::eofbit in err. - */ - template > - class duration_get: public std::locale::facet - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string passed to member functions. - */ - typedef std::basic_string string_type; - /** - * Type of iterator used to scan the character buffer. - */ - typedef InputIterator iter_type; - - /** - * Construct a @c duration_get facet. - * @param refs - * @Effects Construct a @c duration_get facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - - explicit duration_get(size_t refs = 0) : - std::locale::facet(refs) - { - } - - /** - * @param s start input stream iterator - * @param end end input stream iterator - * @param ios a reference to a ios_base - * @param err the ios_base state - * @param d the duration - * @param pattern begin of the formatting pattern - * @param pat_end end of the formatting pattern - * - * Requires: [pattern,pat_end) shall be a valid range. - * - * Effects: The function starts by evaluating err = std::ios_base::goodbit. - * It then enters a loop, reading zero or more characters from s at - * each iteration. Unless otherwise specified below, the loop - * terminates when the first of the following conditions holds: - * - The expression pattern == pat_end evaluates to true. - * - The expression err == std::ios_base::goodbit evaluates to false. - * - The expression s == end evaluates to true, in which case the - * function evaluates err = std::ios_base::eofbit | std::ios_base::failbit. - * - The next element of pattern is equal to '%', followed by a conversion - * specifier character, format. - * If the number of elements in the range [pattern,pat_end) is not - * sufficient to unambiguously determine whether the conversion - * specification is complete and valid, the function evaluates - * err = std::ios_base::failbit. Otherwise, the function evaluates - * s = get_value(s, end, ios, err, r) when the conversion specification is 'v' and - * s = get_value(s, end, ios, err, rt) when the conversion specification is 'u'. - * If err == std::ios_base::goodbit holds after - * the evaluation of the expression, the function increments pattern to - * point just past the end of the conversion specification and continues - * looping. - * - The expression isspace(*pattern, ios.getloc()) evaluates to true, in - * which case the function first increments pattern until - * pattern == pat_end || !isspace(*pattern, ios.getloc()) evaluates to true, - * then advances s until s == end || !isspace(*s, ios.getloc()) is true, - * and finally resumes looping. - * - The next character read from s matches the element pointed to by - * pattern in a case-insensitive comparison, in which case the function - * evaluates ++pattern, ++s and continues looping. Otherwise, the function - * evaluates err = std::ios_base::failbit. - * - * Once r and rt are retrieved, - * Returns: s - */ - template - iter_type get(iter_type s, iter_type end, std::ios_base& ios, std::ios_base::iostate& err, - duration &d, const char_type *pattern, const char_type *pat_end) const - { - if (std::has_facet >(ios.getloc())) - { - duration_units const&facet = std::use_facet >(ios.getloc()); - return get(facet, s, end, ios, err, d, pattern, pat_end); - } - else - { - duration_units_default facet; - return get(facet, s, end, ios, err, d, pattern, pat_end); - } - } - - template - iter_type get(duration_units const&facet, iter_type s, iter_type end, std::ios_base& ios, - std::ios_base::iostate& err, duration &d, const char_type *pattern, const char_type *pat_end) const - { - - typedef typename detail::duration_io_intermediate::type intermediate_type; - intermediate_type r; - rt_ratio rt; - bool value_found = false, unit_found = false; - - const std::ctype& ct = std::use_facet >(ios.getloc()); - while (pattern != pat_end && err == std::ios_base::goodbit) - { - if (s == end) - { - err |= std::ios_base::eofbit; - break; - } - if (ct.narrow(*pattern, 0) == '%') - { - if (++pattern == pat_end) - { - err |= std::ios_base::failbit; - return s; - } - char cmd = ct.narrow(*pattern, 0); - switch (cmd) - { - case 'v': - { - if (value_found) - { - err |= std::ios_base::failbit; - return s; - } - value_found = true; - s = get_value(s, end, ios, err, r); - if (err & (std::ios_base::badbit | std::ios_base::failbit)) - { - return s; - } - break; - } - case 'u': - { - if (unit_found) - { - err |= std::ios_base::failbit; - return s; - } - unit_found = true; - s = get_unit(facet, s, end, ios, err, rt); - if (err & (std::ios_base::badbit | std::ios_base::failbit)) - { - return s; - } - break; - } - default: - BOOST_ASSERT(false && "Boost::Chrono internal error."); - break; - } - - ++pattern; - } - else if (ct.is(std::ctype_base::space, *pattern)) - { - for (++pattern; pattern != pat_end && ct.is(std::ctype_base::space, *pattern); ++pattern) - ; - for (; s != end && ct.is(std::ctype_base::space, *s); ++s) - ; - } - else if (ct.toupper(*s) == ct.toupper(*pattern)) - { - ++s; - ++pattern; - } - else - { - err |= std::ios_base::failbit; - return s; - } - - } - - unsigned long long num = rt.num; - unsigned long long den = rt.den; - - // r should be multiplied by (num/den) / Period - // Reduce (num/den) / Period to lowest terms - unsigned long long gcd_n1_n2 = math::gcd(num, Period::num); - unsigned long long gcd_d1_d2 = math::gcd(den, Period::den); - num /= gcd_n1_n2; - den /= gcd_d1_d2; - unsigned long long n2 = Period::num / gcd_n1_n2; - unsigned long long d2 = Period::den / gcd_d1_d2; - if (num > (std::numeric_limits::max)() / d2 || den - > (std::numeric_limits::max)() / n2) - { - // (num/den) / Period overflows - err |= std::ios_base::failbit; - return s; - } - num *= d2; - den *= n2; - - typedef typename common_type::type common_type_t; - - // num / den is now factor to multiply by r - if (!detail::reduce(r, den, err)) return s; - - if (chrono::detail::gt(r, ( (duration_values::max)() / num))) - { - // Conversion to Period overflowed - err |= std::ios_base::failbit; - return s; - } - common_type_t t = r * num; - t /= den; - if (t > 0) - { - Rep pt = t; - if ( (duration_values::max)() < pt) - { - // Conversion to Period overflowed - err |= std::ios_base::failbit; - return s; - } - } - // Success! Store it. - r = Rep(t); - d = duration (r); - - return s; - } - - /** - * - * @param s start input stream iterator - * @param end end input stream iterator - * @param ios a reference to a ios_base - * @param err the ios_base state - * @param d the duration - * Stores the duration pattern from the @c duration_unit facet in let say @c str. Last as if - * @code - * return get(s, end, ios, err, ios, d, str.data(), str.data() + str.size()); - * @codeend - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid name - */ - template - iter_type get(iter_type s, iter_type end, std::ios_base& ios, std::ios_base::iostate& err, - duration & d) const - { - if (std::has_facet >(ios.getloc())) - { - duration_units const&facet = std::use_facet >(ios.getloc()); - std::basic_string str = facet.get_pattern(); - return get(facet, s, end, ios, err, d, str.data(), str.data() + str.size()); - } - else - { - duration_units_default facet; - std::basic_string str = facet.get_pattern(); - return get(facet, s, end, ios, err, d, str.data(), str.data() + str.size()); - } - } - - /** - * - * @param s start input stream iterator - * @param end end input stream iterator - * @param ios a reference to a ios_base - * @param err the ios_base state - * @param r a reference to the duration representation. - * @Effects As if - * @code - * return std::use_facet >(ios.getloc()).get(s, end, ios, err, r); - * @endcode - * - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid name - */ - template - iter_type get_value(iter_type s, iter_type end, std::ios_base& ios, std::ios_base::iostate& err, Rep& r) const - { - return std::use_facet >(ios.getloc()).get(s, end, ios, err, r); - } - - /** - * - * @param s start input stream iterator - * @param e end input stream iterator - * @param ios a reference to a ios_base - * @param err the ios_base state - * @param rt a reference to the duration run-time ratio. - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid name - */ - iter_type get_unit(iter_type i, iter_type e, std::ios_base& is, std::ios_base::iostate& err, rt_ratio &rt) const - { - if (std::has_facet >(is.getloc())) - { - return get_unit(std::use_facet >(is.getloc()), i, e, is, err, rt); - } - else - { - duration_units_default facet; - return get_unit(facet, i, e, is, err, rt); - } - } - - - iter_type get_unit(duration_units const &facet, iter_type i, iter_type e, std::ios_base& is, - std::ios_base::iostate& err, rt_ratio &rt) const - { - - if (*i == '[') - { - // parse [N/D]s or [N/D]second or [N/D]seconds format - ++i; - i = std::use_facet >(is.getloc()).get(i, e, is, err, rt.num); - if ( (err & std::ios_base::failbit) != 0) - { - return i; - } - - if (i == e) - { - err |= std::ios_base::failbit; - return i; - } - CharT x = *i++; - if (x != '/') - { - err |= std::ios_base::failbit; - return i; - } - i = std::use_facet >(is.getloc()).get(i, e, is, err, rt.den); - if ( (err & std::ios_base::failbit) != 0) - { - return i; - } - if (i == e) - { - err |= std::ios_base::failbit; - return i; - } - if (*i != ']') - { - err |= std::ios_base::failbit; - return i; - } - ++i; - if (i == e) - { - err |= std::ios_base::failbit; - return i; - } - // parse s or second or seconds - return do_get_n_d_valid_unit(facet, i, e, is, err); - } - else - { - return do_get_valid_unit(facet, i, e, is, err, rt); - } - } - - /** - * Unique identifier for this type of facet. - */ - static std::locale::id id; - - /** - * @Effects Destroy the facet - */ - ~duration_get() - { - } - - protected: - - /** - * Extracts the run-time ratio associated to the duration when it is given in prefix form. - * - * This is an extension point of this facet so that we can take in account other periods that can have a useful - * translation in other contexts, as e.g. days and weeks. - * - * @param facet the duration_units facet - * @param i start input stream iterator. - * @param e end input stream iterator. - * @param ios a reference to a ios_base. - * @param err the ios_base state. - * @return @c s - */ - iter_type do_get_n_d_valid_unit(duration_units const &facet, iter_type i, iter_type e, - std::ios_base&, std::ios_base::iostate& err) const - { - // parse SI name, short or long - - const string_type* units = facet.get_n_d_valid_units_start(); - const string_type* units_end = facet.get_n_d_valid_units_end(); - - const string_type* k = chrono_detail::scan_keyword(i, e, units, units_end, - //~ std::use_facet >(loc), - err); - if (err & (std::ios_base::badbit | std::ios_base::failbit)) - { - return i; - } - if (!facet.match_n_d_valid_unit(k)) - { - err |= std::ios_base::failbit; - } - return i; - } - - /** - * Extracts the run-time ratio associated to the duration when it is given in prefix form. - * - * This is an extension point of this facet so that we can take in account other periods that can have a useful - * translation in other contexts, as e.g. days and weeks. - * - * @param facet the duration_units facet - * @param i start input stream iterator. - * @param e end input stream iterator. - * @param ios a reference to a ios_base. - * @param err the ios_base state. - * @param rt a reference to the duration run-time ratio. - * @Effects - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid name. - */ - iter_type do_get_valid_unit(duration_units const &facet, iter_type i, iter_type e, - std::ios_base&, std::ios_base::iostate& err, rt_ratio &rt) const - { - // parse SI name, short or long - - const string_type* units = facet.get_valid_units_start(); - const string_type* units_end = facet.get_valid_units_end(); - - err = std::ios_base::goodbit; - const string_type* k = chrono_detail::scan_keyword(i, e, units, units_end, - //~ std::use_facet >(loc), - err); - if (err & (std::ios_base::badbit | std::ios_base::failbit)) - { - return i; - } - if (!facet.match_valid_unit(k, rt)) - { - err |= std::ios_base::failbit; - } - return i; - } - }; - - /** - * Unique identifier for this type of facet. - */ - template - std::locale::id duration_get::id; - - } // chrono -} -// boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/duration_io.hpp b/utils/boost_idb/boost/chrono/io/duration_io.hpp deleted file mode 100644 index 438f7696..00000000 --- a/utils/boost_idb/boost/chrono/io/duration_io.hpp +++ /dev/null @@ -1,225 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o to Boost - -#ifndef BOOST_CHRONO_IO_DURATION_IO_HPP -#define BOOST_CHRONO_IO_DURATION_IO_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost -{ - namespace chrono - { - - /** - * duration parameterized manipulator. - */ - - class duration_fmt: public manip - { - duration_style style_; - public: - - /** - * explicit manipulator constructor from a @c duration_style - */ - explicit duration_fmt(duration_style style)BOOST_NOEXCEPT - : style_(style) - {} - - /** - * Change the duration_style ios state; - */ - void operator()(std::ios_base &ios) const - - { - set_duration_style(ios, style_); - } - }; - - /** - * duration_style i/o saver. - * - * See Boost.IO i/o state savers for a motivating compression. - */ - struct duration_style_io_saver - { - - //! the type of the state to restore - typedef std::ios_base state_type; - //! the type of aspect to save - typedef duration_style aspect_type; - - /** - * Explicit construction from an i/o stream. - * - * Store a reference to the i/o stream and the value of the associated @c duration_style. - */ - explicit duration_style_io_saver(state_type &s) : - s_save_(s) - { - a_save_ = get_duration_style(s_save_); - } - - /** - * Construction from an i/o stream and a @c duration_style to restore. - * - * Stores a reference to the i/o stream and the value @c duration_style to restore given as parameter. - */ - duration_style_io_saver(state_type &s, aspect_type new_value) : - s_save_(s), a_save_(new_value) - { - } - - /** - * Destructor. - * - * Restores the i/o stream with the duration_style to be restored. - */ - ~duration_style_io_saver() - { - this->restore(); - } - - /** - * Restores the i/o stream with the duration_style to be restored. - */ - void restore() - { - set_duration_style(s_save_, a_save_); - } - - private: - duration_style_io_saver& operator=(duration_style_io_saver const& rhs) ; - - state_type& s_save_; - aspect_type a_save_; - }; - - /** - * duration stream inserter - * @param os the output stream - * @param d to value to insert - * @return @c os - */ - template - std::basic_ostream& - operator<<(std::basic_ostream& os, const duration& d) - { - bool failed = false; - BOOST_TRY - { - std::ios_base::iostate err = std::ios_base::goodbit; - BOOST_TRY - { - typename std::basic_ostream::sentry opfx(os); - if (bool(opfx)) - { - if (!std::has_facet >(os.getloc())) - { - if (duration_put ().put(os, os, os.fill(), d) .failed()) - { - err = std::ios_base::badbit; - } - } - else if (std::use_facet >(os.getloc()) .put(os, os, os.fill(), d) .failed()) - { - err = std::ios_base::badbit; - } - os.width(0); - } - } - BOOST_CATCH(...) - { - bool flag = false; - BOOST_TRY - { - os.setstate(std::ios_base::failbit); - } - BOOST_CATCH (std::ios_base::failure ) - { - flag = true; - } - BOOST_CATCH_END - if (flag) throw; - } - BOOST_CATCH_END - if (err) os.setstate(err); - return os; - } - BOOST_CATCH(...) - { - failed = true; - } - BOOST_CATCH_END - if (failed) os.setstate(std::ios_base::failbit | std::ios_base::badbit); - return os; - } - - /** - * - * @param is the input stream - * @param d the duration - * @return @c is - */ - template - std::basic_istream& - operator>>(std::basic_istream& is, duration& d) - { - std::ios_base::iostate err = std::ios_base::goodbit; - - BOOST_TRY - { - typename std::basic_istream::sentry ipfx(is); - if (bool(ipfx)) - { - if (!std::has_facet >(is.getloc())) - { - duration_get ().get(is, std::istreambuf_iterator(), is, err, d); - } - else - { - std::use_facet >(is.getloc()) .get(is, std::istreambuf_iterator(), is, - err, d); - } - } - } - BOOST_CATCH (...) - { - bool flag = false; - BOOST_TRY - { - is.setstate(std::ios_base::failbit); - } - BOOST_CATCH (std::ios_base::failure ) - { - flag = true; - } - BOOST_CATCH_END - if (flag) { BOOST_RETHROW } - } - BOOST_CATCH_END - if (err) is.setstate(err); - return is; - } - - } // chrono - -} - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/duration_put.hpp b/utils/boost_idb/boost/chrono/io/duration_put.hpp deleted file mode 100644 index 7bd0cd7d..00000000 --- a/utils/boost_idb/boost/chrono/io/duration_put.hpp +++ /dev/null @@ -1,264 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -/** - * Duration formatting facet for output. - */ -#ifndef BOOST_CHRONO_IO_DURATION_PUT_HPP -#define BOOST_CHRONO_IO_DURATION_PUT_HPP - -#include -#include -#include -#include - -namespace boost -{ - namespace chrono - { - - /** - * @tparam ChatT a character type - * @tparam OutputIterator a model of @c OutputIterator - * - * The @c duration_put facet provides facilities for formatted output of duration values. - * The member function of @c duration_put take a duration and format it into character string representation. - * - */ - template > - class duration_put: public std::locale::facet - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string passed to member functions. - */ - typedef std::basic_string string_type; - /** - * Type of iterator used to write in the character buffer. - */ - typedef OutputIterator iter_type; - - /** - * Construct a duration_put facet. - * @param refs - * @Effects Construct a duration_put facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - explicit duration_put(size_t refs = 0) : - std::locale::facet(refs) - { - } - - /** - * - * @param s an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param d the duration - * @param pattern begin of the formatting pattern - * @param pat_end end of the formatting pattern - * - * @Effects Steps through the sequence from @c pattern to @c pat_end, - * identifying characters that are part of a pattern sequence. Each character - * that is not part of a pattern sequence is written to @c s immediately, and - * each pattern sequence, as it is identified, results in a call to - * @c put_value or @c put_unit; - * thus, pattern elements and other characters are interleaved in the output - * in the order in which they appear in the pattern. Pattern sequences are - * identified by converting each character @c c to a @c char value as if by - * @c ct.narrow(c,0), where @c ct is a reference to @c ctype obtained from - * @c ios.getloc(). The first character of each sequence is equal to @c '%', - * followed by a pattern specifier character @c spec, which can be @c 'v' for - * the duration value or @c 'u' for the duration unit. . - * For each valid pattern sequence identified, calls - * put_value(s, ios, fill, d) or put_unit(s, ios, fill, d). - * - * @Returns An iterator pointing immediately after the last character produced. - */ - template - iter_type put(iter_type s, std::ios_base& ios, char_type fill, duration const& d, const CharT* pattern, - const CharT* pat_end) const - { - if (std::has_facet >(ios.getloc())) - { - duration_units const&facet = std::use_facet >( - ios.getloc()); - return put(facet, s, ios, fill, d, pattern, pat_end); - } - else - { - duration_units_default facet; - return put(facet, s, ios, fill, d, pattern, pat_end); - } - } - - template - iter_type put(duration_units const& units_facet, iter_type s, std::ios_base& ios, char_type fill, - duration const& d, const CharT* pattern, const CharT* pat_end) const - { - - const std::ctype& ct = std::use_facet >(ios.getloc()); - for (; pattern != pat_end; ++pattern) - { - if (ct.narrow(*pattern, 0) == '%') - { - if (++pattern == pat_end) - { - *s++ = pattern[-1]; - break; - } - char fmt = ct.narrow(*pattern, 0); - switch (fmt) - { - case 'v': - { - s = put_value(s, ios, fill, d); - break; - } - case 'u': - { - s = put_unit(units_facet, s, ios, fill, d); - break; - } - default: - BOOST_ASSERT(false && "Boost::Chrono internal error."); - break; - } - } - else - *s++ = *pattern; - } - return s; - } - - /** - * - * @param s an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param d the duration - * @Effects imbue in @c ios the @c duration_units_default facet if not already present. - * Retrieves Stores the duration pattern from the @c duration_unit facet in let say @c str. Last as if - * @code - * return put(s, ios, d, str.data(), str.data() + str.size()); - * @endcode - * @Returns An iterator pointing immediately after the last character produced. - */ - template - iter_type put(iter_type s, std::ios_base& ios, char_type fill, duration const& d) const - { - if (std::has_facet >(ios.getloc())) - { - duration_units const&facet = std::use_facet >( - ios.getloc()); - std::basic_string str = facet.get_pattern(); - return put(facet, s, ios, fill, d, str.data(), str.data() + str.size()); - } - else - { - duration_units_default facet; - std::basic_string str = facet.get_pattern(); - return put(facet, s, ios, fill, d, str.data(), str.data() + str.size()); - } - } - - /** - * - * @param s an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param d the duration - * @Effects As if s=std::use_facet >(ios.getloc()).put(s, ios, fill, static_cast (d.count())). - * @Returns s, iterator pointing immediately after the last character produced. - */ - template - iter_type put_value(iter_type s, std::ios_base& ios, char_type fill, duration const& d) const - { - return std::use_facet >(ios.getloc()).put(s, ios, fill, - static_cast (d.count())); - } - - /** - * - * @param s an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param d the duration - * @Effects Let facet be the duration_units facet associated to ios. If the associated unit is named, - * as if - * @code - string_type str = facet.get_unit(get_duration_style(ios), d); - s=std::copy(str.begin(), str.end(), s); - * @endcode - * Otherwise, format the unit as "[Period::num/Period::den]" followed by the unit associated to [N/D] obtained using facet.get_n_d_unit(get_duration_style(ios), d) - * @Returns s, iterator pointing immediately after the last character produced. - */ - template - iter_type put_unit(iter_type s, std::ios_base& ios, char_type fill, duration const& d) const - { - if (std::has_facet >(ios.getloc())) - { - duration_units const&facet = std::use_facet >( - ios.getloc()); - return put_unit(facet, s, ios, fill, d); - } - else - { - duration_units_default facet; - return put_unit(facet, s, ios, fill, d); - } - } - - template - iter_type put_unit(duration_units const& facet, iter_type s, std::ios_base& ios, char_type fill, - duration const& d) const - { - if (facet.template is_named_unit()) { - string_type str = facet.get_unit(get_duration_style(ios), d); - s=std::copy(str.begin(), str.end(), s); - } else { - *s++ = CharT('['); - std::use_facet >(ios.getloc()).put(s, ios, fill, Period::num); - *s++ = CharT('/'); - std::use_facet >(ios.getloc()).put(s, ios, fill, Period::den); - *s++ = CharT(']'); - string_type str = facet.get_n_d_unit(get_duration_style(ios), d); - s=std::copy(str.begin(), str.end(), s); - } - return s; - } - - /** - * Unique identifier for this type of facet. - */ - static std::locale::id id; - - /** - * @Effects Destroy the facet - */ - ~duration_put() - { - } - - }; - - template - std::locale::id duration_put::id; - - } // chrono -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/duration_style.hpp b/utils/boost_idb/boost/chrono/io/duration_style.hpp deleted file mode 100644 index 65b76a90..00000000 --- a/utils/boost_idb/boost/chrono/io/duration_style.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o to Boost - -#ifndef BOOST_CHRONO_IO_DURATION_STYLE_HPP -#define BOOST_CHRONO_IO_DURATION_STYLE_HPP - -#include - -namespace boost -{ - namespace chrono - { - /** - * Scoped enumeration emulation stating whether the duration I/O style is long or short. - * prefix means duration::rep with whatever stream/locale settings are set for it followed by a long name representing the unit - * symbol means duration::rep with whatever stream/locale settings are set for it followed by a SI unit abbreviation - */ - BOOST_SCOPED_ENUM_DECLARE_BEGIN(duration_style) - { - prefix, symbol - } - BOOST_SCOPED_ENUM_DECLARE_END(duration_style) - - - } // chrono - -} - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/duration_units.hpp b/utils/boost_idb/boost/chrono/io/duration_units.hpp deleted file mode 100644 index 84faa819..00000000 --- a/utils/boost_idb/boost/chrono/io/duration_units.hpp +++ /dev/null @@ -1,1003 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -#ifndef BOOST_CHRONO_IO_DURATION_UNITS_HPP -#define BOOST_CHRONO_IO_DURATION_UNITS_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost -{ - namespace chrono - { - class rt_ratio - { - public: - template - rt_ratio(Period const&) : - num(Period::type::num), den(Period::type::den) - { - } - - rt_ratio(intmax_t n = 0, intmax_t d = 0) : - num(n), den(d) - { - } - - intmax_t num; - intmax_t den; - }; - - /** - * @c duration_units facet gives useful information about the duration units, - * as the number of plural forms, the plural form associated to a duration, - * the text associated to a plural form and a duration's period, - */ - template - class duration_units: public std::locale::facet - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string passed to member functions. - */ - typedef std::basic_string string_type; - - /** - * Unique identifier for this type of facet. - */ - static std::locale::id id; - - /** - * Construct a @c duration_units facet. - * @param refs - * @Effects Construct a @c duration_units facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - explicit duration_units(size_t refs = 0) : - std::locale::facet(refs) - { - } - - /** - * @return pointer to the start of valid [N/D] units. - */ - virtual const string_type* get_n_d_valid_units_start() const =0; - /** - * @effect calls the do_... - * @return pointer to the end of valid [N/D] units. - */ - virtual const string_type* get_n_d_valid_units_end() const=0; - - /** - * @return pointer to the start of valid units, symbol or prefix with its different plural forms. - */ - virtual const string_type* get_valid_units_start() const=0; - /** - * @return pointer to the end of valid units. - */ - virtual const string_type* get_valid_units_end() const=0; - - /** - * @param k the found pointer to the [N/D] unit. - * @return true if @c k matches a valid unit. - */ - virtual bool match_n_d_valid_unit(const string_type* k) const = 0; - /** - * @param k the found pointer to the unit. - * @Effects @c rt is set to the valid Period when the @c k matches a valid unit. - * @return true if @c k matches a valid unit. - */ - virtual bool match_valid_unit(const string_type* k, rt_ratio& rt) const = 0; - - /** - * @effect calls the do_... - * @return the pattern to be used by default. - */ - virtual string_type get_pattern() const=0; - - /** - * @effect calls the do_... - * @return the unit associated to this duration. - */ - template - string_type get_unit(duration_style style, duration const& d) const - { - return do_get_unit(style, rt_ratio(Period()), static_cast(d.count())); - } - /** - * @effect calls the do_... - * @return the [N/D] suffix unit associated to this duration. - */ - template - string_type get_n_d_unit(duration_style style, duration const& d) const - { - return do_get_n_d_unit(style, rt_ratio(Period()), static_cast(d.count())); - } - - /** - * @effect calls the do_... - * @return true if the unit associated to the given Period is named, false otherwise. - */ - template - bool is_named_unit() const - { - return do_is_named_unit(rt_ratio(Period())); - } - - - protected: - - /** - * @Effects Destroys the facet - */ - virtual ~duration_units() - { - } - /** - * @return the [N/D] suffix unit associated to this duration. - */ - virtual string_type do_get_n_d_unit(duration_style style, rt_ratio rt, intmax_t v) const = 0; - /** - * @return the unit associated to this duration. - */ - virtual string_type do_get_unit(duration_style style,rt_ratio rt, intmax_t v) const = 0; - /** - * @return true if the unit associated to the given Period is named, false otherwise. - */ - virtual bool do_is_named_unit(rt_ratio rt) const =0; - - }; - - template - std::locale::id duration_units::id; - - namespace detail - { - template - struct duration_units_default_holder - { - typedef std::basic_string string_type; - static string_type* n_d_valid_units_; - static string_type* valid_units_; - static bool initialized_; - }; - template - typename duration_units_default_holder::string_type* duration_units_default_holder::n_d_valid_units_=0; - template - typename duration_units_default_holder::string_type* duration_units_default_holder::valid_units_=0; - template - bool duration_units_default_holder::initialized_ = false; - } - - /** - * This class is used to define the strings for the default English - */ - template - class duration_units_default: public duration_units - { - protected: - static const std::size_t pfs_ = 2; - - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string passed to member functions. - */ - typedef std::basic_string string_type; - - /** - * Construct a @c duration_units_default facet. - * @param refs - * @Effects Construct a @c duration_units_default facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - explicit duration_units_default(size_t refs = 0) : - duration_units (refs) - { - } - - /** - * Destroys the facet. - */ - ~duration_units_default() - { - } - - public: - - /** - * @param k the found pointer to the [N/D] unit. - * @return true if @c k matches a valid unit. - */ - bool match_n_d_valid_unit(const string_type* k) const - { - std::size_t index = (k - get_n_d_valid_units_start()) / (pfs_ + 1); - switch (index) - { - case 0: - break; - default: - return false; - } - return true; - } - /** - * @param k the found pointer to the unit. - * @Effects @c rt is set to the valid Period when the @c k matches a valid unit. - * @return true if @c k matches a valid unit. - */ - bool match_valid_unit(const string_type* k, rt_ratio& rt) const - { - std::size_t index = (k - get_valid_units_start()) / (pfs_ + 1); - switch (index) - { - case 0: - rt = rt_ratio(atto()); - break; - case 1: - rt = rt_ratio(femto()); - break; - case 2: - rt = rt_ratio(pico()); - break; - case 3: - rt = rt_ratio(nano()); - break; - case 4: - rt = rt_ratio(micro()); - break; - case 5: - rt = rt_ratio(milli()); - break; - case 6: - rt = rt_ratio(centi()); - break; - case 7: - rt = rt_ratio(deci()); - break; - case 8: - rt = rt_ratio(deca()); - break; - case 9: - rt = rt_ratio(hecto()); - break; - case 10: - rt = rt_ratio(kilo()); - break; - case 11: - rt = rt_ratio(mega()); - break; - case 12: - rt = rt_ratio(giga()); - break; - case 13: - rt = rt_ratio(tera()); - break; - case 14: - rt = rt_ratio(peta()); - break; - case 15: - rt = rt_ratio(exa()); - break; - case 16: - rt = rt_ratio(ratio<1> ()); - break; - case 17: - rt = rt_ratio(ratio<60> ()); - break; - case 18: - rt = rt_ratio(ratio<3600> ()); - break; - default: - return false; - } - return true; - } - - /** - * @return pointer to the start of valid [N/D] units. - */ - virtual const string_type* get_n_d_valid_units_start()const - { - return detail::duration_units_default_holder::n_d_valid_units_; - } - /** - * @return pointer to the end of valid [N/D] units. - */ - virtual const string_type* get_n_d_valid_units_end()const - { - return detail::duration_units_default_holder::n_d_valid_units_ + (pfs_ + 1); - } - - /** - * @return pointer to the start of valid units. - */ - virtual const string_type* get_valid_units_start() const - { - return detail::duration_units_default_holder::valid_units_; - } - /** - * @return pointer to the end of valid units. - */ - virtual const string_type* get_valid_units_end() const - { - return detail::duration_units_default_holder::valid_units_ + 19 * (pfs_ + 1); - } - - string_type get_pattern() const - { - static const CharT t[] = - { '%', 'v', ' ', '%', 'u' }; - static const string_type pattern(t, t + sizeof (t) / sizeof (t[0])); - - return pattern; - } - - protected: - /** - * - * This facet names the units associated to the following periods: - * atto,femto,pico,nano,micro,milli,centi,deci,ratio<1>,deca,hecto,kilo,mega,giga,tera,peta,exa,ratio<60> and ratio<3600>. - * @return true if the unit associated to the given Period is named, false otherwise. - */ - bool do_is_named_unit(rt_ratio rt) const - { - if (rt.num==1) { - switch (rt.den) - { - case BOOST_RATIO_INTMAX_C(1): - case BOOST_RATIO_INTMAX_C(10): - case BOOST_RATIO_INTMAX_C(100): - case BOOST_RATIO_INTMAX_C(1000): - case BOOST_RATIO_INTMAX_C(1000000): - case BOOST_RATIO_INTMAX_C(1000000000): - case BOOST_RATIO_INTMAX_C(1000000000000): - case BOOST_RATIO_INTMAX_C(1000000000000000): - case BOOST_RATIO_INTMAX_C(1000000000000000000): - return true; - default: - return false; - } - } else if (rt.den==1) { - switch (rt.num) - { - case BOOST_RATIO_INTMAX_C(10): - case BOOST_RATIO_INTMAX_C(60): - case BOOST_RATIO_INTMAX_C(100): - case BOOST_RATIO_INTMAX_C(1000): - case BOOST_RATIO_INTMAX_C(3600): - case BOOST_RATIO_INTMAX_C(1000000): - case BOOST_RATIO_INTMAX_C(1000000000): - case BOOST_RATIO_INTMAX_C(1000000000000): - case BOOST_RATIO_INTMAX_C(1000000000000000): - case BOOST_RATIO_INTMAX_C(1000000000000000000): - return true; - default: - return false; - } - } - return false; - - } - - /** - * In English the suffix used after [N/D] is the one associated to the period ratio<1>. - * @return the [N/D] suffix unit associated to this duration. - */ - string_type do_get_n_d_unit(duration_style style, rt_ratio, intmax_t v) const - { - return do_get_unit(style, ratio<1>(), do_get_plural_form(v)); - } - - /** - * @return the unit associated to this duration if it is named, "" otherwise. - */ - string_type do_get_unit(duration_style style, rt_ratio rt, intmax_t v) const - { - if (rt.num==1) { - switch (rt.den) - { - case BOOST_RATIO_INTMAX_C(1): - return do_get_unit(style, ratio<1>(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(10): - return do_get_unit(style, deci(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(100): - return do_get_unit(style, centi(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000): - return do_get_unit(style, milli(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000): - return do_get_unit(style, micro(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000): - return do_get_unit(style, nano(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000000): - return do_get_unit(style, pico(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000000000): - return do_get_unit(style, femto(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000000000000): - return do_get_unit(style, atto(), do_get_plural_form(v)); - default: - ; - } - } else if (rt.den==1) { - switch (rt.num) - { - case BOOST_RATIO_INTMAX_C(10): - return do_get_unit(style, deca(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(60): - return do_get_unit(style, ratio<60>(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(100): - return do_get_unit(style, hecto(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000): - return do_get_unit(style, kilo(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(3600): - return do_get_unit(style, ratio<3600>(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000): - return do_get_unit(style, mega(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000): - return do_get_unit(style, giga(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000000): - return do_get_unit(style, tera(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000000000): - return do_get_unit(style, peta(), do_get_plural_form(v)); - case BOOST_RATIO_INTMAX_C(1000000000000000000): - return do_get_unit(style, exa(), do_get_plural_form(v)); - default: - ; - } - } - BOOST_ASSERT(false&&"ratio parameter can not be translated"); - //throw "exception"; - return string_type(); - } - - protected: - /** - * @return the number of associated plural forms this facet manages. - */ - virtual std::size_t do_get_plural_forms() const - { - return static_get_plural_forms(); - } - static std::size_t static_get_plural_forms() - { - return pfs_; - } - /** - * Gets the associated plural form. - * @param value the duration representation - * @return the plural form associated to the @c value parameter. In English there are 2 plural forms - * 0 singular (-1 or 1) - * 1 plural for all others - */ - virtual std::size_t do_get_plural_form(int_least64_t value) const - { - return static_get_plural_form(value); - } - static std::size_t static_get_plural_form(int_least64_t value) - { - return (value == -1 || value == 1) ? 0 : 1; - } - - /** - * @param style the duration style. - * @param period the period associated to the duration seconds. - * @param pf the requested plural form. - * @return if style is symbol returns "s", otherwise if pf is 0 return "second", if pf is 1 "seconds" - */ - virtual string_type do_get_unit(duration_style style, ratio<1> u, std::size_t pf) const - { - return static_get_unit(style,u,pf); - } - static string_type static_get_unit(duration_style style, ratio<1> , std::size_t pf) - { - static const CharT t[] = - { 's' }; - static const string_type symbol(t, t + sizeof (t) / sizeof (t[0])); - static const CharT u[] = - { 's', 'e', 'c', 'o', 'n', 'd' }; - static const string_type singular(u, u + sizeof (u) / sizeof (u[0])); - static const CharT v[] = - { 's', 'e', 'c', 'o', 'n', 'd', 's' }; - static const string_type plural(v, v + sizeof (v) / sizeof (v[0])); - - if (style == duration_style::symbol) - { - return symbol; - } - if (pf == 0) - { - return singular; - } - if (pf == 1) - { - return plural; - } - BOOST_ASSERT(false&&"style/pf parameters not valid"); - //throw "exception"; - return string_type(); - } - - /** - * @param style the duration style. - * @param period the period associated to the duration minutes. - * @param pf the requested plural form. - * @return if style is symbol returns "min", otherwise if pf is 0 return "minute", if pf is 1 "minutes" - */ - virtual string_type do_get_unit(duration_style style, ratio<60> u, std::size_t pf) const - { - return static_get_unit(style,u,pf); - } - static string_type static_get_unit(duration_style style, ratio<60> , std::size_t pf) - { - static const CharT t[] = - { 'm', 'i', 'n' }; - static const string_type symbol(t, t + sizeof (t) / sizeof (t[0])); - - static const CharT u[] = - { 'm', 'i', 'n', 'u', 't', 'e' }; - static const string_type singular(u, u + sizeof (u) / sizeof (u[0])); - static const CharT v[] = - { 'm', 'i', 'n', 'u', 't', 'e', 's' }; - static const string_type plural(v, v + sizeof (v) / sizeof (v[0])); - - if (style == duration_style::symbol) return symbol; - if (pf == 0) return singular; - if (pf == 1) return plural; - BOOST_ASSERT(false&&"style/pf parameters not valid"); - //throw "exception"; - return string_type(); - - } - - /** - * @param style the duration style. - * @param period the period associated to the duration hours. - * @param pf the requested plural form. - * @return if style is symbol returns "h", otherwise if pf is 0 return "hour", if pf is 1 "hours" - */ - virtual string_type do_get_unit(duration_style style, ratio<3600> u, std::size_t pf) const - { - return static_get_unit(style,u,pf); - } - static string_type static_get_unit(duration_style style, ratio<3600> , std::size_t pf) - { - static const CharT t[] = - { 'h' }; - static const string_type symbol(t, t + sizeof (t) / sizeof (t[0])); - static const CharT u[] = - { 'h', 'o', 'u', 'r' }; - static const string_type singular(u, u + sizeof (u) / sizeof (u[0])); - static const CharT v[] = - { 'h', 'o', 'u', 'r', 's' }; - static const string_type plural(v, v + sizeof (v) / sizeof (v[0])); - - if (style == duration_style::symbol) return symbol; - if (pf == 0) return singular; - if (pf == 1) return plural; - BOOST_ASSERT(false&&"style/pf parameters not valid"); - //throw "exception"; - return string_type(); - - } - /** - * @param style the duration style. - * @param u the period tag atto. - * @param pf the requested plural form. - * @return the concatenation of the prefix associated to @c period + the one associated to seconds. - */ - virtual string_type do_get_unit(duration_style style, atto u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, atto u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - /** - * @param style the duration style. - * @param u the period tag femto. - * @param pf the requested plural form. - * @return the concatenation of the prefix associated to period @c u + the one associated to seconds. - */ - virtual string_type do_get_unit(duration_style style, femto u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, femto u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - /** - * @param style the duration style. - * @param u the period tag femto. - * @param pf the requested plural form. - * @return the concatenation of the prefix associated to period @c u + the one associated to seconds. - */ - virtual string_type do_get_unit(duration_style style, pico u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, pico u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, nano u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, nano u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, micro u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, micro u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, milli u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, milli u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, centi u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, centi u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, deci u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, deci u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, deca u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, deca u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, hecto u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, hecto u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, kilo u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, kilo u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, mega u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, mega u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, giga u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, giga u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, tera u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, tera u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, peta u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, peta u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - virtual string_type do_get_unit(duration_style style, exa u, std::size_t pf) const - { - return do_get_ratio_prefix(style, u) + do_get_unit(style, ratio<1> (), pf); - } - static string_type static_get_unit(duration_style style, exa u, std::size_t pf) - { - return static_get_ratio_prefix(style, u) + static_get_unit(style, ratio<1> (), pf); - } - - protected: - - /** - * @param style the duration style. - * @param u the period tag atto. - * @return depending on the value of @c style return the ratio_string symbol or prefix. - */ - virtual string_type do_get_ratio_prefix(duration_style style, atto u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, atto) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, femto u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, femto) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, pico u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, pico) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, nano u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, nano) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, micro u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, micro) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, milli u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, milli) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, centi u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, centi) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, deci u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, deci) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, deca u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, deca) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, hecto u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, hecto) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, kilo u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, kilo) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, mega u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, mega) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, giga u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, giga) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, tera u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, tera) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, peta u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, peta) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - virtual string_type do_get_ratio_prefix(duration_style style, exa u) const - { - return static_get_ratio_prefix(style, u); - } - static string_type static_get_ratio_prefix(duration_style style, exa) - { - if (style == duration_style::symbol) return ratio_string::symbol(); - return ratio_string::prefix(); - } - - protected: - template - string_type* fill_units(string_type* it, Period) const - { - std::size_t pfs = do_get_plural_forms(); - for (std::size_t pf = 0; pf < pfs; ++pf) - { - *it++ = do_get_unit(duration_style::prefix, Period(), pf); - } - *it++ = do_get_unit(duration_style::symbol, Period(), 0); - return it; - } - public: - template - static string_type* static_fill_units(string_type* it, Period) - { - std::size_t pfs = static_get_plural_forms(); - for (std::size_t pf = 0; pf < pfs; ++pf) - { - *it++ = static_get_unit(duration_style::prefix, Period(), pf); - } - *it++ = static_get_unit(duration_style::symbol, Period(), 0); - return it; - } - static string_type* static_init_valid_units(string_type* it) - { - it = static_fill_units(it, atto()); - it = static_fill_units(it, femto()); - it = static_fill_units(it, pico()); - it = static_fill_units(it, nano()); - it = static_fill_units(it, micro()); - it = static_fill_units(it, milli()); - it = static_fill_units(it, centi()); - it = static_fill_units(it, deci()); - it = static_fill_units(it, deca()); - it = static_fill_units(it, hecto()); - it = static_fill_units(it, kilo()); - it = static_fill_units(it, mega()); - it = static_fill_units(it, giga()); - it = static_fill_units(it, tera()); - it = static_fill_units(it, peta()); - it = static_fill_units(it, exa()); - it = static_fill_units(it, ratio<1> ()); - it = static_fill_units(it, ratio<60> ()); - it = static_fill_units(it, ratio<3600> ()); - return it; - } - }; - - namespace detail - { - - template - struct duration_units_default_initializer_t - { - duration_units_default_initializer_t() - { - if (!duration_units_default_holder::initialized_) - { - typedef typename duration_units_default_holder::string_type string_type; - duration_units_default_holder::n_d_valid_units_ = new string_type[3]; - duration_units_default_holder::valid_units_ = new string_type[19 * 3]; - - string_type* it = duration_units_default_holder::n_d_valid_units_; - it = duration_units_default::static_fill_units(it, ratio<1> ()); - it = duration_units_default::static_init_valid_units(duration_units_default_holder::valid_units_); - - duration_units_default_holder::initialized_ = true; - } - } - ~duration_units_default_initializer_t() - { - if (duration_units_default_holder::initialized_) - { - delete[] duration_units_default_holder::n_d_valid_units_; - duration_units_default_holder::n_d_valid_units_ = 0; - delete[] duration_units_default_holder::valid_units_; - duration_units_default_holder::valid_units_ = 0; - duration_units_default_holder::initialized_ = false; - } - } - }; - namespace /**/ - { - duration_units_default_initializer_t duration_units_default_initializer; - duration_units_default_initializer_t wduration_units_default_initializer; - } // namespace - } - } // chrono - -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/ios_base_state.hpp b/utils/boost_idb/boost/chrono/io/ios_base_state.hpp deleted file mode 100644 index 6e320a56..00000000 --- a/utils/boost_idb/boost/chrono/io/ios_base_state.hpp +++ /dev/null @@ -1,151 +0,0 @@ -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o to Boost - -#ifndef BOOST_CHRONO_IO_IOS_BASE_STATE_HPP -#define BOOST_CHRONO_IO_IOS_BASE_STATE_HPP - -#include -#include -#include -#include -#include - -namespace boost -{ - namespace chrono - { - - class fmt_masks : public ios_flags - { - typedef ios_flags base_type; - fmt_masks& operator=(fmt_masks const& rhs) ; - - public: - fmt_masks(std::ios_base& ios): base_type(ios) {} - enum type - { - uses_symbol = 1 << 0, - uses_local = 1 << 1 - }; - - inline duration_style get_duration_style() - { - return (flags() & uses_symbol) ? duration_style::symbol : duration_style::prefix; - } - inline void set_duration_style(duration_style style) - { - if (style == duration_style::symbol) - setf(uses_symbol); - else - unsetf(uses_symbol); - } - - inline timezone get_timezone() - { - return (flags() & uses_local) ? timezone::local : timezone::utc; - } - inline void set_timezone(timezone tz) - { - if (tz == timezone::local) - setf(uses_local); - else - unsetf(uses_local); - } - }; - namespace detail - { - namespace /**/ { - xalloc_key_initializer fmt_masks_xalloc_key_initializer; - } // namespace - } // namespace detail - - inline duration_style get_duration_style(std::ios_base & ios) - { - return fmt_masks(ios).get_duration_style(); - } - inline void set_duration_style(std::ios_base& ios, duration_style style) - { - fmt_masks(ios).set_duration_style(style); - } - inline std::ios_base& symbol_format(std::ios_base& ios) - { - fmt_masks(ios).setf(fmt_masks::uses_symbol); - return ios; - } - inline std::ios_base& name_format(std::ios_base& ios) - { - fmt_masks(ios).unsetf(fmt_masks::uses_symbol); - return ios; - } - - inline timezone get_timezone(std::ios_base & ios) - { - return fmt_masks(ios).get_timezone(); - } - inline void set_timezone(std::ios_base& ios, timezone tz) - { - fmt_masks(ios).set_timezone(tz); - } - inline std::ios_base& local_timezone(std::ios_base& ios) - { - fmt_masks(ios).setf(fmt_masks::uses_local); - return ios; - } - - inline std::ios_base& utc_timezone(std::ios_base& ios) - { - fmt_masks(ios).unsetf(fmt_masks::uses_local); - return ios; - } - - namespace detail - { - - template - struct ios_base_data_aux - { - std::basic_string time_fmt; - std::basic_string duration_fmt; - public: - - ios_base_data_aux() : - time_fmt(""), - duration_fmt("") - { - } - }; - template - struct ios_base_data {}; - namespace /**/ { - xalloc_key_initializer > ios_base_data_aux_xalloc_key_initializer; - xalloc_key_initializer > wios_base_data_aux_xalloc_key_initializer; -#if BOOST_CHRONO_HAS_UNICODE_SUPPORT - xalloc_key_initializer > u16ios_base_data_aux_xalloc_key_initializer; - xalloc_key_initializer > u32ios_base_data_aux_xalloc_key_initializer; -#endif - } // namespace - } // namespace detail - - template - inline std::basic_string get_time_fmt(std::ios_base & ios) - { - ios_state_not_null_ptr, detail::ios_base_data_aux > ptr(ios); - return ptr->time_fmt; - } - template - inline void set_time_fmt(std::ios_base& ios, std::basic_string< - CharT> const& fmt) - { - ios_state_not_null_ptr, detail::ios_base_data_aux > ptr(ios); - ptr->time_fmt = fmt; - } - - } // chrono -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/time_point_get.hpp b/utils/boost_idb/boost/chrono/io/time_point_get.hpp deleted file mode 100644 index 5e4acd39..00000000 --- a/utils/boost_idb/boost/chrono/io/time_point_get.hpp +++ /dev/null @@ -1,330 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -#ifndef BOOST_CHRONO_IO_TIME_POINT_GET_HPP -#define BOOST_CHRONO_IO_TIME_POINT_GET_HPP - -#include -#include -#include -#include -#include -#include -#include - -/** - * Duration formatting facet for input. - */ -namespace boost -{ - namespace chrono - { - - template > - class time_point_get: public std::locale::facet - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of iterator used to scan the character buffer. - */ - typedef InputIterator iter_type; - - /** - * Construct a @c time_point_get facet. - * @param refs - * @Effects Construct a @c time_point_get facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - - explicit time_point_get(size_t refs = 0) : - std::locale::facet(refs) - { - } - - /** - * @param s start input stream iterator - * @param end end input stream iterator - * @param ios a reference to a ios_base - * @param err the ios_base state - * @param d the duration - * @param pattern begin of the formatting pattern - * @param pat_end end of the formatting pattern - * - * Requires: [pattern,pat_end) shall be a valid range. - * - * Effects: The function starts by evaluating err = std::ios_base::goodbit. - * It then enters a loop, reading zero or more characters from s at - * each iteration. Unless otherwise specified below, the loop - * terminates when the first of the following conditions holds: - * - The expression pattern == pat_end evaluates to true. - * - The expression err == std::ios_base::goodbit evaluates to false. - * - The expression s == end evaluates to true, in which case the - * function evaluates err = std::ios_base::eofbit | std::ios_base::failbit. - * - The next element of pattern is equal to '%', followed by a conversion - * specifier character, the functions @c get_duration or @c get_epoch are called depending on - * whether the format is @c 'd' or @c 'e'. - * If the number of elements in the range [pattern,pat_end) is not - * sufficient to unambiguously determine whether the conversion - * specification is complete and valid, the function evaluates - * err = std::ios_base::failbit. Otherwise, the function evaluates - * s = do_get(s, end, ios, err, d). If err == std::ios_base::goodbit holds after - * the evaluation of the expression, the function increments pattern to - * point just past the end of the conversion specification and continues - * looping. - * - The expression isspace(*pattern, ios.getloc()) evaluates to true, in - * which case the function first increments pattern until - * pattern == pat_end || !isspace(*pattern, ios.getloc()) evaluates to true, - * then advances s until s == end || !isspace(*s, ios.getloc()) is true, - * and finally resumes looping. - * - The next character read from s matches the element pointed to by - * pattern in a case-insensitive comparison, in which case the function - * evaluates ++pattern, ++s and continues looping. Otherwise, the function - * evaluates err = std::ios_base::failbit. - * - * Returns: s - */ - - template - iter_type get(iter_type i, iter_type e, std::ios_base& is, std::ios_base::iostate& err, - time_point &tp, const char_type *pattern, const char_type *pat_end) const - { - if (std::has_facet >(is.getloc())) - { - time_point_units const &facet = std::use_facet >(is.getloc()); - return get(facet, i, e, is, err, tp, pattern, pat_end); - } - else - { - time_point_units_default facet; - return get(facet, i, e, is, err, tp, pattern, pat_end); - } - } - - template - iter_type get(time_point_units const &facet, iter_type s, iter_type end, std::ios_base& ios, - std::ios_base::iostate& err, time_point &tp, const char_type *pattern, - const char_type *pat_end) const - { - - Duration d; - bool duration_found = false, epoch_found = false; - - const std::ctype& ct = std::use_facet >(ios.getloc()); - err = std::ios_base::goodbit; - while (pattern != pat_end && err == std::ios_base::goodbit) - { - if (s == end) - { - err |= std::ios_base::eofbit; - break; - } - if (ct.narrow(*pattern, 0) == '%') - { - if (++pattern == pat_end) - { - err |= std::ios_base::failbit; - return s; - } - char cmd = ct.narrow(*pattern, 0); - switch (cmd) - { - case 'd': - { - if (duration_found) - { - err |= std::ios_base::failbit; - return s; - } - duration_found = true; - s = get_duration(s, end, ios, err, d); - if (err & (std::ios_base::badbit | std::ios_base::failbit)) - { - return s; - } - break; - } - case 'e': - { - if (epoch_found) - { - err |= std::ios_base::failbit; - return s; - } - epoch_found = true; - s = get_epoch (facet, s, end, ios, err); - if (err & (std::ios_base::badbit | std::ios_base::failbit)) - { - return s; - } - break; - } - default: - BOOST_ASSERT(false && "Boost::Chrono internal error."); - break; - } - - ++pattern; - } - else if (ct.is(std::ctype_base::space, *pattern)) - { - for (++pattern; pattern != pat_end && ct.is(std::ctype_base::space, *pattern); ++pattern) - ; - for (; s != end && ct.is(std::ctype_base::space, *s); ++s) - ; - } - else if (ct.toupper(*s) == ct.toupper(*pattern)) - { - ++s; - ++pattern; - } - else - { - err |= std::ios_base::failbit; - } - } - - // Success! Store it. - tp = time_point (d); - return s; - } - - /** - * - * @param s an input stream iterator - * @param ios a reference to a ios_base - * @param d the duration - * Stores the duration pattern from the @c duration_unit facet in let say @c str. Last as if - * @code - * return get(s, end, ios, err, ios, d, str.data(), str.data() + str.size()); - * @codeend - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid name - */ - template - iter_type get(iter_type i, iter_type e, std::ios_base& is, std::ios_base::iostate& err, - time_point &tp) const - { - if (std::has_facet >(is.getloc())) - { - time_point_units const &facet = std::use_facet >(is.getloc()); - std::basic_string str = facet.get_pattern(); - return get(facet, i, e, is, err, tp, str.data(), str.data() + str.size()); - } - else - { - time_point_units_default facet; - std::basic_string str = facet.get_pattern(); - return get(facet, i, e, is, err, tp, str.data(), str.data() + str.size()); - } - } - - /** - * As if - * @code - * return facet.get(s, end, ios, err, d); - * @endcode - * where @c facet is either the @c duration_get facet associated to the @c ios or an instance of the default @c duration_get facet. - * - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid duration. - */ - template - iter_type get_duration(iter_type i, iter_type e, std::ios_base& is, std::ios_base::iostate& err, - duration& d) const - { - if (std::has_facet >(is.getloc())) - { - duration_get const &facet = std::use_facet >(is.getloc()); - return get_duration(facet, i, e, is, err, d); - } - else - { - duration_get facet; - return get_duration(facet, i, e, is, err, d); - } - } - - template - iter_type get_duration(duration_get const& facet, iter_type s, iter_type end, std::ios_base& ios, - std::ios_base::iostate& err, duration& d) const - { - return facet.get(s, end, ios, err, d); - } - - /** - * - * @Effects Let @c facet be the @c time_point_units facet associated to @c is or a new instance of the default @c time_point_units_default facet. - * Let @c epoch be the epoch string associated to the Clock using this facet. - * Scans @c i to match @c epoch or @c e is reached. - * - * If not match before the @c e is reached @c std::ios_base::failbit is set in @c err. - * If @c e is reached @c std::ios_base::failbit is set in @c err. - * - * @Returns An iterator pointing just beyond the last character that can be determined to be part of a valid epoch. - */ - template - iter_type get_epoch(iter_type i, iter_type e, std::ios_base& is, std::ios_base::iostate& err) const - { - if (std::has_facet >(is.getloc())) - { - time_point_units const &facet = std::use_facet >(is.getloc()); - return get_epoch(facet, i, e, is, err); - } - else - { - time_point_units_default facet; - return get_epoch(facet, i, e, is, err); - } - } - - template - iter_type get_epoch(time_point_units const &facet, iter_type i, iter_type e, std::ios_base&, - std::ios_base::iostate& err) const - { - const std::basic_string epoch = facet.template get_epoch (); - std::ptrdiff_t k = chrono_detail::scan_keyword(i, e, &epoch, &epoch + 1, - //~ std::use_facet >(ios.getloc()), - err) - &epoch; - if (k == 1) - { - err |= std::ios_base::failbit; - return i; - } - return i; - } - - /** - * Unique identifier for this type of facet. - */ - static std::locale::id id; - - /** - * @Effects Destroy the facet - */ - ~time_point_get() - { - } - }; - - /** - * Unique identifier for this type of facet. - */ - template - std::locale::id time_point_get::id; - - } // chrono -} -// boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/time_point_io.hpp b/utils/boost_idb/boost/chrono/io/time_point_io.hpp deleted file mode 100644 index f337131a..00000000 --- a/utils/boost_idb/boost/chrono/io/time_point_io.hpp +++ /dev/null @@ -1,1231 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2010-2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). - -//===-------------------------- locale ------------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is dual licensed under the MIT and the University of Illinois Open -// Source Licenses. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o to Boost and some functions from libc++/locale to emulate the missing time_get::get() - -#ifndef BOOST_CHRONO_IO_TIME_POINT_IO_HPP -#define BOOST_CHRONO_IO_TIME_POINT_IO_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define BOOST_CHRONO_INTERNAL_TIMEGM \ - ( defined BOOST_WINDOWS && ! defined(__CYGWIN__) ) \ - || ( (defined(sun) || defined(__sun)) && defined __GNUC__) \ - || (defined __IBMCPP__) - -#define BOOST_CHRONO_INTERNAL_GMTIME \ - (defined BOOST_WINDOWS && ! defined(__CYGWIN__)) \ - || ( (defined(sun) || defined(__sun)) && defined __GNUC__) \ - || (defined __IBMCPP__) - -#define BOOST_CHRONO_USES_INTERNAL_TIME_GET - -namespace boost -{ - namespace chrono - { - typedef double fractional_seconds; - namespace detail - { - - - template > - struct time_get - { - std::time_get const &that_; - time_get(std::time_get const& that) : that_(that) {} - - typedef std::time_get facet; - typedef typename facet::iter_type iter_type; - typedef typename facet::char_type char_type; - typedef std::basic_string string_type; - - static int - get_up_to_n_digits( - InputIterator& b, InputIterator e, - std::ios_base::iostate& err, - const std::ctype& ct, - int n) - { - // Precondition: n >= 1 - if (b == e) - { - err |= std::ios_base::eofbit | std::ios_base::failbit; - return 0; - } - // get first digit - CharT c = *b; - if (!ct.is(std::ctype_base::digit, c)) - { - err |= std::ios_base::failbit; - return 0; - } - int r = ct.narrow(c, 0) - '0'; - for (++b, --n; b != e && n > 0; ++b, --n) - { - // get next digit - c = *b; - if (!ct.is(std::ctype_base::digit, c)) - return r; - r = r * 10 + ct.narrow(c, 0) - '0'; - } - if (b == e) - err |= std::ios_base::eofbit; - return r; - } - - - void get_day( - int& d, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 2); - if (!(err & std::ios_base::failbit) && 1 <= t && t <= 31) - d = t; - else - err |= std::ios_base::failbit; - } - - void get_month( - int& m, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 2) - 1; - if (!(err & std::ios_base::failbit) && t <= 11) - m = t; - else - err |= std::ios_base::failbit; - } - - - void get_year4(int& y, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 4); - if (!(err & std::ios_base::failbit)) - y = t - 1900; - } - - void - get_hour(int& h, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 2); - if (!(err & std::ios_base::failbit) && t <= 23) - h = t; - else - err |= std::ios_base::failbit; - } - - void - get_minute(int& m, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 2); - if (!(err & std::ios_base::failbit) && t <= 59) - m = t; - else - err |= std::ios_base::failbit; - } - - void get_second(int& s, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 2); - if (!(err & std::ios_base::failbit) && t <= 60) - s = t; - else - err |= std::ios_base::failbit; - } - - void get_white_space(iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - for (; b != e && ct.is(std::ctype_base::space, *b); ++b) - ; - if (b == e) - err |= std::ios_base::eofbit; - } - - void get_12_hour(int& h, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 2); - if (!(err & std::ios_base::failbit) && 1 <= t && t <= 12) - h = t; - else - err |= std::ios_base::failbit; - } - - void get_percent(iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - if (b == e) - { - err |= std::ios_base::eofbit | std::ios_base::failbit; - return; - } - if (ct.narrow(*b, 0) != '%') - err |= std::ios_base::failbit; - else if(++b == e) - err |= std::ios_base::eofbit; - } - - void get_day_year_num(int& d, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 3); - if (!(err & std::ios_base::failbit) && t <= 365) - d = t; - else - err |= std::ios_base::failbit; - } - - void - get_weekday(int& w, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - int t = get_up_to_n_digits(b, e, err, ct, 1); - if (!(err & std::ios_base::failbit) && t <= 6) - w = t; - else - err |= std::ios_base::failbit; - } -#if 0 - - void - get_am_pm(int& h, - iter_type& b, iter_type e, - std::ios_base::iostate& err, - const std::ctype& ct) const - { - const string_type* ap = am_pm(); - if (ap[0].size() + ap[1].size() == 0) - { - err |= ios_base::failbit; - return; - } - ptrdiff_t i = detail::scan_keyword(b, e, ap, ap+2, ct, err, false) - ap; - if (i == 0 && h == 12) - h = 0; - else if (i == 1 && h < 12) - h += 12; - } - -#endif - - InputIterator get( - iter_type b, iter_type e, - std::ios_base& iob, - std::ios_base::iostate& err, - std::tm* tm, - char fmt, char) const - { - err = std::ios_base::goodbit; - const std::ctype& ct = std::use_facet >(iob.getloc()); - - switch (fmt) - { - case 'a': - case 'A': - { - std::tm tm2; - std::memset(&tm2, 0, sizeof(std::tm)); - that_.get_weekday(b, e, iob, err, &tm2); - //tm->tm_wday = tm2.tm_wday; - } - break; - case 'b': - case 'B': - case 'h': - { - std::tm tm2; - std::memset(&tm2, 0, sizeof(std::tm)); - that_.get_monthname(b, e, iob, err, &tm2); - //tm->tm_mon = tm2.tm_mon; - } - break; -// case 'c': -// { -// const string_type& fm = c(); -// b = get(b, e, iob, err, tm, fm.data(), fm.data() + fm.size()); -// } -// break; - case 'd': - case 'e': - get_day(tm->tm_mday, b, e, err, ct); - break; - case 'D': - { - const char_type fm[] = {'%', 'm', '/', '%', 'd', '/', '%', 'y'}; - b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0])); - } - break; - case 'F': - { - const char_type fm[] = {'%', 'Y', '-', '%', 'm', '-', '%', 'd'}; - b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0])); - } - break; - case 'H': - get_hour(tm->tm_hour, b, e, err, ct); - break; - case 'I': - get_12_hour(tm->tm_hour, b, e, err, ct); - break; - case 'j': - get_day_year_num(tm->tm_yday, b, e, err, ct); - break; - case 'm': - get_month(tm->tm_mon, b, e, err, ct); - break; - case 'M': - get_minute(tm->tm_min, b, e, err, ct); - break; - case 'n': - case 't': - get_white_space(b, e, err, ct); - break; -// case 'p': -// get_am_pm(tm->tm_hour, b, e, err, ct); -// break; - case 'r': - { - const char_type fm[] = {'%', 'I', ':', '%', 'M', ':', '%', 'S', ' ', '%', 'p'}; - b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0])); - } - break; - case 'R': - { - const char_type fm[] = {'%', 'H', ':', '%', 'M'}; - b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0])); - } - break; - case 'S': - get_second(tm->tm_sec, b, e, err, ct); - break; - case 'T': - { - const char_type fm[] = {'%', 'H', ':', '%', 'M', ':', '%', 'S'}; - b = get(b, e, iob, err, tm, fm, fm + sizeof(fm)/sizeof(fm[0])); - } - break; - case 'w': - { - get_weekday(tm->tm_wday, b, e, err, ct); - } - break; - case 'x': - return that_.get_date(b, e, iob, err, tm); -// case 'X': -// return that_.get_time(b, e, iob, err, tm); -// { -// const string_type& fm = X(); -// b = that_.get(b, e, iob, err, tm, fm.data(), fm.data() + fm.size()); -// } -// break; -// case 'y': -// get_year(tm->tm_year, b, e, err, ct); - break; - case 'Y': - get_year4(tm->tm_year, b, e, err, ct); - break; - case '%': - get_percent(b, e, err, ct); - break; - default: - err |= std::ios_base::failbit; - } - return b; - } - - - InputIterator get( - iter_type b, iter_type e, - std::ios_base& iob, - std::ios_base::iostate& err, std::tm* tm, - const char_type* fmtb, const char_type* fmte) const - { - const std::ctype& ct = std::use_facet >(iob.getloc()); - err = std::ios_base::goodbit; - while (fmtb != fmte && err == std::ios_base::goodbit) - { - if (b == e) - { - err = std::ios_base::failbit; - break; - } - if (ct.narrow(*fmtb, 0) == '%') - { - if (++fmtb == fmte) - { - err = std::ios_base::failbit; - break; - } - char cmd = ct.narrow(*fmtb, 0); - char opt = '\0'; - if (cmd == 'E' || cmd == '0') - { - if (++fmtb == fmte) - { - err = std::ios_base::failbit; - break; - } - opt = cmd; - cmd = ct.narrow(*fmtb, 0); - } - b = get(b, e, iob, err, tm, cmd, opt); - ++fmtb; - } - else if (ct.is(std::ctype_base::space, *fmtb)) - { - for (++fmtb; fmtb != fmte && ct.is(std::ctype_base::space, *fmtb); ++fmtb) - ; - for ( ; b != e && ct.is(std::ctype_base::space, *b); ++b) - ; - } - else if (ct.toupper(*b) == ct.toupper(*fmtb)) - { - ++b; - ++fmtb; - } - else - err = std::ios_base::failbit; - } - if (b == e) - err |= std::ios_base::eofbit; - return b; - } - - }; - - - template - class time_manip: public manip > - { - std::basic_string fmt_; - timezone tz_; - public: - - time_manip(timezone tz, std::basic_string fmt) - // todo move semantics - : - fmt_(fmt), tz_(tz) - { - } - - /** - * Change the timezone and time format ios state; - */ - void operator()(std::ios_base &ios) const - { - set_time_fmt (ios, fmt_); - set_timezone(ios, tz_); - } - }; - - class time_man: public manip - { - timezone tz_; - public: - - time_man(timezone tz) - // todo move semantics - : - tz_(tz) - { - } - - /** - * Change the timezone and time format ios state; - */ - void operator()(std::ios_base &ios) const - { - //set_time_fmt(ios, ""); - set_timezone(ios, tz_); - } - }; - - } - - template - inline detail::time_manip time_fmt(timezone tz, const CharT* fmt) - { - return detail::time_manip(tz, fmt); - } - - template - inline detail::time_manip time_fmt(timezone tz, std::basic_string fmt) - { - // todo move semantics - return detail::time_manip(tz, fmt); - } - - inline detail::time_man time_fmt(timezone f) - { - return detail::time_man(f); - } - - /** - * time_fmt_io_saver i/o saver. - * - * See Boost.IO i/o state savers for a motivating compression. - */ - template > - struct time_fmt_io_saver - { - - //! the type of the state to restore - typedef std::basic_ostream state_type; - //! the type of aspect to save - typedef std::basic_string aspect_type; - - /** - * Explicit construction from an i/o stream. - * - * Store a reference to the i/o stream and the value of the associated @c time format . - */ - explicit time_fmt_io_saver(state_type &s) : - s_save_(s), a_save_(get_time_fmt(s_save_)) - { - } - - /** - * Construction from an i/o stream and a @c time format to restore. - * - * Stores a reference to the i/o stream and the value @c new_value to restore given as parameter. - */ - time_fmt_io_saver(state_type &s, aspect_type new_value) : - s_save_(s), a_save_(new_value) - { - } - - /** - * Destructor. - * - * Restores the i/o stream with the format to be restored. - */ - ~time_fmt_io_saver() - { - this->restore(); - } - - /** - * Restores the i/o stream with the time format to be restored. - */ - void restore() - { - set_time_fmt(a_save_, a_save_); - } - private: - state_type& s_save_; - aspect_type a_save_; - }; - - /** - * timezone_io_saver i/o saver. - * - * See Boost.IO i/o state savers for a motivating compression. - */ - struct timezone_io_saver - { - - //! the type of the state to restore - typedef std::ios_base state_type; - //! the type of aspect to save - typedef timezone aspect_type; - - /** - * Explicit construction from an i/o stream. - * - * Store a reference to the i/o stream and the value of the associated @c timezone. - */ - explicit timezone_io_saver(state_type &s) : - s_save_(s), a_save_(get_timezone(s_save_)) - { - } - - /** - * Construction from an i/o stream and a @c timezone to restore. - * - * Stores a reference to the i/o stream and the value @c new_value to restore given as parameter. - */ - timezone_io_saver(state_type &s, aspect_type new_value) : - s_save_(s), a_save_(new_value) - { - } - - /** - * Destructor. - * - * Restores the i/o stream with the format to be restored. - */ - ~timezone_io_saver() - { - this->restore(); - } - - /** - * Restores the i/o stream with the timezone to be restored. - */ - void restore() - { - set_timezone(s_save_, a_save_); - } - private: - timezone_io_saver& operator=(timezone_io_saver const& rhs) ; - - state_type& s_save_; - aspect_type a_save_; - }; - - /** - * - * @param os - * @param tp - * @Effects Behaves as a formatted output function. After constructing a @c sentry object, if the @ sentry - * converts to true, calls to @c facet.put(os,os,os.fill(),tp) where @c facet is the @c time_point_put - * facet associated to @c os or a new created instance of the default @c time_point_put facet. - * @return @c os. - */ - template - std::basic_ostream& - operator<<(std::basic_ostream& os, const time_point& tp) - { - - bool failed = false; - BOOST_TRY - { - std::ios_base::iostate err = std::ios_base::goodbit; - BOOST_TRY - { - typename std::basic_ostream::sentry opfx(os); - if (bool(opfx)) - { - if (!std::has_facet >(os.getloc())) - { - if (time_point_put ().put(os, os, os.fill(), tp) .failed()) - { - err = std::ios_base::badbit; - } - } - else - { - if (std::use_facet >(os.getloc()) .put(os, os, os.fill(), tp).failed()) - { - err = std::ios_base::badbit; - } - } - os.width(0); - } - } - BOOST_CATCH (...) - { - bool flag = false; - BOOST_TRY - { - os.setstate(std::ios_base::failbit); - } - BOOST_CATCH (std::ios_base::failure ) - { - flag = true; - } - BOOST_CATCH_END - if (flag) throw; - } - BOOST_CATCH_END - if (err) os.setstate(err); - return os; - } - BOOST_CATCH (...) - { - failed = true; - } - BOOST_CATCH_END - if (failed) os.setstate(std::ios_base::failbit | std::ios_base::badbit); - return os; - } - - template - std::basic_istream& - operator>>(std::basic_istream& is, time_point& tp) - { - std::ios_base::iostate err = std::ios_base::goodbit; - - BOOST_TRY - { - typename std::basic_istream::sentry ipfx(is); - if (bool(ipfx)) - { - if (!std::has_facet >(is.getloc())) - { - time_point_get ().get(is, std::istreambuf_iterator(), is, err, tp); - } - else - { - std::use_facet >(is.getloc()).get(is, std::istreambuf_iterator(), is, - err, tp); - } - } - } - BOOST_CATCH (...) - { - bool flag = false; - BOOST_TRY - { - is.setstate(std::ios_base::failbit); - } - BOOST_CATCH (std::ios_base::failure ) - { - flag = true; - } - BOOST_CATCH_END - if (flag) throw; - } - BOOST_CATCH_END - if (err) is.setstate(err); - return is; - } - - - namespace detail - { - - inline int32_t is_leap(int32_t year) - { - if(year % 400 == 0) - return 1; - if(year % 100 == 0) - return 0; - if(year % 4 == 0) - return 1; - return 0; - } - inline int32_t days_from_0(int32_t year) - { - year--; - return 365 * year + (year / 400) - (year/100) + (year / 4); - } - inline int32_t days_from_1970(int32_t year) - { - static const int days_from_0_to_1970 = days_from_0(1970); - return days_from_0(year) - days_from_0_to_1970; - } - inline int32_t days_from_1jan(int32_t year,int32_t month,int32_t day) - { - static const int32_t days[2][12] = - { - { 0,31,59,90,120,151,181,212,243,273,304,334}, - { 0,31,60,91,121,152,182,213,244,274,305,335} - }; - - return days[is_leap(year)][month-1] + day - 1; - } - - inline time_t internal_timegm(std::tm const *t) - { - int year = t->tm_year + 1900; - int month = t->tm_mon; - if(month > 11) - { - year += month/12; - month %= 12; - } - else if(month < 0) - { - int years_diff = (-month + 11)/12; - year -= years_diff; - month+=12 * years_diff; - } - month++; - int day = t->tm_mday; - int day_of_year = days_from_1jan(year,month,day); - int days_since_epoch = days_from_1970(year) + day_of_year ; - - time_t seconds_in_day = 3600 * 24; - time_t result = seconds_in_day * days_since_epoch + 3600 * t->tm_hour + 60 * t->tm_min + t->tm_sec; - - return result; - } - - /** - * from_ymd could be made more efficient by using a table - * day_count_table indexed by the y%400. - * This table could contain the day_count - * by*365 + by/4 - by/100 + by/400 - * - * from_ymd = (by/400)*days_by_400_years+day_count_table[by%400] + - * days_in_year_before[is_leap_table[by%400]][m-1] + d; - */ - inline unsigned days_before_years(int32_t y) - { - return y * 365 + y / 4 - y / 100 + y / 400; - } - - // Returns year/month/day triple in civil calendar - // Preconditions: z is number of days since 1970-01-01 and is in the range: - // [numeric_limits::min(), numeric_limits::max()-719468]. - template - //constexpr - void - inline civil_from_days(Int z, Int& y, unsigned& m, unsigned& d) BOOST_NOEXCEPT - { - BOOST_STATIC_ASSERT_MSG(std::numeric_limits::digits >= 18, - "This algorithm has not been ported to a 16 bit unsigned integer"); - BOOST_STATIC_ASSERT_MSG(std::numeric_limits::digits >= 20, - "This algorithm has not been ported to a 16 bit signed integer"); - z += 719468; - const Int era = (z >= 0 ? z : z - 146096) / 146097; - const unsigned doe = static_cast(z - era * 146097); // [0, 146096] - const unsigned yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; // [0, 399] - y = static_cast(yoe) + era * 400; - const unsigned doy = doe - (365*yoe + yoe/4 - yoe/100); // [0, 365] - const unsigned mp = (5*doy + 2)/153; // [0, 11] - d = doy - (153*mp+2)/5 + 1; // [1, 31] - m = mp + (mp < 10 ? 3 : -9); // [1, 12] - y += (m <= 2); - --m; - } - inline std::tm * internal_gmtime(std::time_t const* t, std::tm *tm) - { - if (t==0) return 0; - if (tm==0) return 0; - -#if 0 - static const unsigned char - day_of_year_month[2][366] = - { - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, - - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 - - } }; - - static const int32_t days_in_year_before[2][13] = - { - { -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 }, - { -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 } - }; -#endif - - const time_t seconds_in_day = 3600 * 24; - int32_t days_since_epoch = static_cast(*t / seconds_in_day); - int32_t hms = static_cast(*t - seconds_in_day*days_since_epoch); - if (hms < 0) { - days_since_epoch-=1; - hms = seconds_in_day+hms; - } - -#if 0 - int32_t x = days_since_epoch; - int32_t y = static_cast (static_cast (x + 2) * 400 - / 146097); - const int32_t ym1 = y - 1; - int32_t doy = x - days_before_years(y); - const int32_t doy1 = x - days_before_years(ym1); - const int32_t N = std::numeric_limits::digits - 1; - const int32_t mask1 = doy >> N; // arithmetic rshift - not portable - but nearly universal - const int32_t mask0 = ~mask1; - doy = (doy & mask0) | (doy1 & mask1); - y = (y & mask0) | (ym1 & mask1); - //y -= 32767 + 2; - y += 70; - tm->tm_year=y; - const int32_t leap = is_leap(y); - tm->tm_mon = day_of_year_month[leap][doy]-1; - tm->tm_mday = doy - days_in_year_before[leap][tm->tm_mon] ; -#else - int32_t y; - unsigned m, d; - civil_from_days(days_since_epoch, y, m, d); - tm->tm_year=y-1900; tm->tm_mon=m; tm->tm_mday=d; -#endif - - tm->tm_hour = hms / 3600; - const int ms = hms % 3600; - tm->tm_min = ms / 60; - tm->tm_sec = ms % 60; - - tm->tm_isdst = -1; - (void)mktime(tm); - return tm; - } - - } // detail -#ifndef BOOST_CHRONO_NO_UTC_TIMEPOINT - -#if defined BOOST_CHRONO_PROVIDES_DATE_IO_FOR_SYSTEM_CLOCK_TIME_POINT - - template - std::basic_ostream& - operator<<(std::basic_ostream& os, const time_point& tp) - { - typename std::basic_ostream::sentry ok(os); - if (bool(ok)) - { - bool failed = false; - BOOST_TRY - { - const CharT* pb = 0; //nullptr; - const CharT* pe = pb; - std::basic_string fmt = get_time_fmt (os); - pb = fmt.data(); - pe = pb + fmt.size(); - - timezone tz = get_timezone(os); - std::locale loc = os.getloc(); - time_t t = system_clock::to_time_t(time_point_cast(tp)); - std::tm tm; - std::memset(&tm, 0, sizeof(std::tm)); - if (tz == timezone::local) - { -#if defined BOOST_WINDOWS && ! defined(__CYGWIN__) - std::tm *tmp = 0; - if ((tmp=localtime(&t)) == 0) - failed = true; - else - tm =*tmp; -#else - if (localtime_r(&t, &tm) == 0) failed = true; -#endif - } - else - { -#if BOOST_CHRONO_INTERNAL_GMTIME - if (detail::internal_gmtime(&t, &tm) == 0) failed = true; - -#elif defined BOOST_WINDOWS && ! defined(__CYGWIN__) - std::tm *tmp = 0; - if((tmp = gmtime(&t)) == 0) - failed = true; - else - tm = *tmp; -#else - if (gmtime_r(&t, &tm) == 0) failed = true; - tm.tm_isdst = -1; - (void)mktime(&tm); - -#endif - - } - if (!failed) - { - const std::time_put& tpf = std::use_facet >(loc); - if (pb == pe) - { - CharT pattern[] = - { '%', 'Y', '-', '%', 'm', '-', '%', 'd', ' ', '%', 'H', ':', '%', 'M', ':' }; - pb = pattern; - pe = pb + sizeof (pattern) / sizeof(CharT); - failed = tpf.put(os, os, os.fill(), &tm, pb, pe).failed(); - if (!failed) - { - duration d = tp - system_clock::from_time_t(t) + seconds(tm.tm_sec); - if (d.count() < 10) os << CharT('0'); - //if (! os.good()) { - // throw "exception"; - //} - std::ios::fmtflags flgs = os.flags(); - os.setf(std::ios::fixed, std::ios::floatfield); - //if (! os.good()) { - //throw "exception"; - //} - os.precision(9); - os << d.count(); - //if (! os.good()) { - //throw "exception"; - //} - os.flags(flgs); - if (tz == timezone::local) - { - CharT sub_pattern[] = - { ' ', '%', 'z' }; - pb = sub_pattern; - pe = pb + +sizeof (sub_pattern) / sizeof(CharT); - failed = tpf.put(os, os, os.fill(), &tm, pb, pe).failed(); - } - else - { - CharT sub_pattern[] = - { ' ', '+', '0', '0', '0', '0', 0 }; - os << sub_pattern; - } - } - } - else - { - failed = tpf.put(os, os, os.fill(), &tm, pb, pe).failed(); - } - } - } - BOOST_CATCH (...) - { - failed = true; - } - BOOST_CATCH_END - if (failed) - { - os.setstate(std::ios_base::failbit | std::ios_base::badbit); - } - } - return os; - } -#endif - - namespace detail - { - - template - minutes extract_z(InputIterator& b, InputIterator e, std::ios_base::iostate& err, const std::ctype& ct) - { - int min = 0; - if (b != e) - { - char cn = ct.narrow(*b, 0); - if (cn != '+' && cn != '-') - { - err |= std::ios_base::failbit; - return minutes(0); - } - int sn = cn == '-' ? -1 : 1; - int hr = 0; - for (int i = 0; i < 2; ++i) - { - if (++b == e) - { - err |= std::ios_base::eofbit | std::ios_base::failbit; - return minutes(0); - } - cn = ct.narrow(*b, 0); - if (! ('0' <= cn && cn <= '9')) - { - err |= std::ios_base::failbit; - return minutes(0); - } - hr = hr * 10 + cn - '0'; - } - for (int i = 0; i < 2; ++i) - { - if (++b == e) - { - err |= std::ios_base::eofbit | std::ios_base::failbit; - return minutes(0); - } - cn = ct.narrow(*b, 0); - if (! ('0' <= cn && cn <= '9')) - { - err |= std::ios_base::failbit; - return minutes(0); - } - min = min * 10 + cn - '0'; - } - if (++b == e) { - err |= std::ios_base::eofbit; - } - min += hr * 60; - min *= sn; - } - else - { - err |= std::ios_base::eofbit | std::ios_base::failbit; - } - return minutes(min); - } - - } // detail - -#if defined BOOST_CHRONO_PROVIDES_DATE_IO_FOR_SYSTEM_CLOCK_TIME_POINT - - template - std::basic_istream& - operator>>(std::basic_istream& is, time_point& tp) - { - typename std::basic_istream::sentry ok(is); - if (bool(ok)) - { - std::ios_base::iostate err = std::ios_base::goodbit; - BOOST_TRY - { - const CharT* pb = 0; //nullptr; - const CharT* pe = pb; - std::basic_string fmt = get_time_fmt (is); - pb = fmt.data(); - pe = pb + fmt.size(); - - timezone tz = get_timezone(is); - std::locale loc = is.getloc(); - const std::time_get& tg = std::use_facet >(loc); - const std::ctype& ct = std::use_facet >(loc); - tm tm; // {0} - std::memset(&tm, 0, sizeof(std::tm)); - - typedef std::istreambuf_iterator It; - if (pb == pe) - { - CharT pattern[] = - { '%', 'Y', '-', '%', 'm', '-', '%', 'd', ' ', '%', 'H', ':', '%', 'M', ':' }; - pb = pattern; - pe = pb + sizeof (pattern) / sizeof(CharT); - -#if defined BOOST_CHRONO_USES_INTERNAL_TIME_GET - const detail::time_get& dtg(tg); - dtg.get(is, 0, is, err, &tm, pb, pe); -#else - tg.get(is, 0, is, err, &tm, pb, pe); -#endif - if (err & std::ios_base::failbit) goto exit; - fractional_seconds sec; - CharT c = CharT(); - std::ios::fmtflags flgs = is.flags(); - is.setf(std::ios::fixed, std::ios::floatfield); - is.precision(9); - is >> sec; - is.flags(flgs); - if (is.fail()) - { - err |= std::ios_base::failbit; - goto exit; - } - It i(is); - It eof; - c = *i; - if (++i == eof || c != ' ') - { - err |= std::ios_base::failbit; - goto exit; - } - minutes min = detail::extract_z(i, eof, err, ct); - - if (err & std::ios_base::failbit) goto exit; - time_t t; - -#if BOOST_CHRONO_INTERNAL_TIMEGM - t = detail::internal_timegm(&tm); -#else - t = timegm(&tm); -#endif - tp = time_point_cast( - system_clock::from_time_t(t) - min + round (duration (sec)) - ); - } - else - { - const CharT z[2] = - { '%', 'z' }; - const CharT* fz = std::search(pb, pe, z, z + 2); -#if defined BOOST_CHRONO_USES_INTERNAL_TIME_GET - const detail::time_get& dtg(tg); - dtg.get(is, 0, is, err, &tm, pb, fz); -#else - tg.get(is, 0, is, err, &tm, pb, fz); -#endif - minutes minu(0); - if (fz != pe) - { - if (err != std::ios_base::goodbit) - { - err |= std::ios_base::failbit; - goto exit; - } - It i(is); - It eof; - minu = detail::extract_z(i, eof, err, ct); - if (err & std::ios_base::failbit) goto exit; - if (fz + 2 != pe) - { - if (err != std::ios_base::goodbit) - { - err |= std::ios_base::failbit; - goto exit; - } -#if defined BOOST_CHRONO_USES_INTERNAL_TIME_GET - const detail::time_get& dtg(tg); - dtg.get(is, 0, is, err, &tm, fz + 2, pe); -#else - tg.get(is, 0, is, err, &tm, fz + 2, pe); -#endif - if (err & std::ios_base::failbit) goto exit; - } - } - tm.tm_isdst = -1; - time_t t; - if (tz == timezone::utc || fz != pe) - { -#if BOOST_CHRONO_INTERNAL_TIMEGM - t = detail::internal_timegm(&tm); -#else - t = timegm(&tm); -#endif - } - else - { - t = mktime(&tm); - } - tp = time_point_cast( - system_clock::from_time_t(t) - minu - ); - } - } - BOOST_CATCH (...) - { - err |= std::ios_base::badbit | std::ios_base::failbit; - } - BOOST_CATCH_END - exit: is.setstate(err); - } - return is; - } - -#endif -#endif //UTC - } // chrono - -} - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/time_point_put.hpp b/utils/boost_idb/boost/chrono/io/time_point_put.hpp deleted file mode 100644 index 9c8c7cad..00000000 --- a/utils/boost_idb/boost/chrono/io/time_point_put.hpp +++ /dev/null @@ -1,261 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -/** - * Duration formatting facet for output. - */ -#ifndef BOOST_CHRONO_IO_TIME_POINT_PUT_HPP -#define BOOST_CHRONO_IO_TIME_POINT_PUT_HPP - -#include -#include -#include -#include -#include - -namespace boost -{ - namespace chrono - { - - /** - * @tparam ChatT a character type - * @tparam OutputIterator a model of @c OutputIterator - * - * The @c time_point_put facet provides facilities for formatted output of @c time_point values. - * The member function of @c time_point_put take a @c time_point and format it into character string representation. - * - */ - template > - class time_point_put: public std::locale::facet - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string passed to member functions. - */ - typedef std::basic_string string_type; - /** - * Type of iterator used to write in the character buffer. - */ - typedef OutputIterator iter_type; - - /** - * Construct a time_point_put facet. - * @param refs - * @Effects Construct a time_point_put facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - explicit time_point_put(size_t refs = 0) : - std::locale::facet(refs) - { - } - - /** - * @param i an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param tp the @c time_point - * @param pattern begin of the formatting pattern - * @param pat_end end of the formatting pattern - * - * @Effects Steps through the sequence from @c pattern to @c pat_end, - * identifying characters that are part of a pattern sequence. Each character - * that is not part of a pattern sequence is written to @c s immediately, and - * each pattern sequence, as it is identified, results in a call to - * @c put_duration or @c put_epoch; - * thus, pattern elements and other characters are interleaved in the output - * in the order in which they appear in the pattern. Pattern sequences are - * identified by converting each character @c c to a @c char value as if by - * @c ct.narrow(c,0), where @c ct is a reference to @c ctype obtained from - * @c ios.getloc(). The first character of each sequence is equal to @c '%', - * followed by a pattern specifier character @c spec, which can be @c 'd' for - * the duration value or @c 'e' for the epoch. - * For each valid pattern sequence identified, calls - * put_duration(s, ios, fill, tp.time_since_epoch()) or put_epoch(s, ios). - * - * @Returns An iterator pointing immediately after the last character produced. - */ - - template - iter_type put(iter_type i, std::ios_base& ios, char_type fill, time_point const& tp, const CharT* pattern, - const CharT* pat_end) const - { - if (std::has_facet >(ios.getloc())) - { - time_point_units const &facet = - std::use_facet >(ios.getloc()); - return put(facet, i, ios, fill, tp, pattern, pat_end); - } - else - { - time_point_units_default facet; - return put(facet, i, ios, fill, tp, pattern, pat_end); - } - } - - template - iter_type put(time_point_units const& units_facet, iter_type s, std::ios_base& ios, char_type fill, - time_point const& tp, const CharT* pattern, const CharT* pat_end) const - { - - const std::ctype& ct = std::use_facet >(ios.getloc()); - for (; pattern != pat_end; ++pattern) - { - if (ct.narrow(*pattern, 0) == '%') - { - if (++pattern == pat_end) - { - *s++ = pattern[-1]; - break; - } - char fmt = ct.narrow(*pattern, 0); - switch (fmt) - { - case 'd': - { - s = put_duration(s, ios, fill, tp.time_since_epoch()); - break; - } - case 'e': - { - s = put_epoch (units_facet, s, ios); - break; - } - default: - BOOST_ASSERT(false && "Boost::Chrono internal error."); - break; - } - } - else - *s++ = *pattern; - } - return s; - } - - /** - * @param i an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param tp the @c time_point - * @param pattern begin of the formatting pattern - * @param pat_end end of the formatting pattern - * - * @Effects Stores the time_point pattern from the @c time_point_unit facet in let say @c str. Last as if - * @code - * return put(s, ios, dill, tp, str.data(), str.data() + str.size()); - * @endcode - * @Returns An iterator pointing immediately after the last character produced. - */ - template - iter_type put(iter_type i, std::ios_base& ios, char_type fill, time_point const& tp) const - { - if (std::has_facet >(ios.getloc())) - { - time_point_units const &facet = - std::use_facet >(ios.getloc()); - std::basic_string str = facet.get_pattern(); - return put(facet, i, ios, fill, tp, str.data(), str.data() + str.size()); - } - else - { - time_point_units_default facet; - std::basic_string str = facet.get_pattern(); - return put(facet, i, ios, fill, tp, str.data(), str.data() + str.size()); - } - } - - /** - * @param i an output stream iterator - * @param ios a reference to a ios_base - * @param fill the character used as filler - * @param d the @c duration - * @Effects As if facet.put(s, ios, fill, d) where facet is the @c duration_put facet associated - * to the @c ios or a new instance of @c duration_put. - * @Returns An iterator pointing immediately after the last character produced. - */ - template - iter_type put_duration(iter_type i, std::ios_base& ios, char_type fill, duration const& d) const - { - if (std::has_facet >(ios.getloc())) - { - duration_put const &facet = std::use_facet >(ios.getloc()); - return facet.put(i, ios, fill, d); - } - else - { - duration_put facet; - return facet.put(i, ios, fill, d); - } - } - - /** - * - * @param i an output stream iterator - * @param ios a reference to a ios_base - * @Effects As if - * @code - * string_type str = facet.template get_epoch(); - * s=std::copy(str.begin(), str.end(), s); - * @endcode - * where facet is the @c time_point_units facet associated - * to the @c ios or a new instance of @c time_point_units_default. - * @Returns s, iterator pointing immediately after the last character produced. - */ - - template - iter_type put_epoch(iter_type i, std::ios_base& os) const - { - if (std::has_facet >(os.getloc())) - { - time_point_units const &facet = std::use_facet >(os.getloc()); - return put_epoch (facet, i, os); - } - else - { - time_point_units_default facet; - return put_epoch (facet, i, os); - } - } - - template - iter_type put_epoch(time_point_units const& facet, iter_type s, std::ios_base&) const - { - string_type str = facet.template get_epoch(); - s= std::copy(str.begin(), str.end(), s); - return s; - } - - /** - * Unique identifier for this type of facet. - */ - static std::locale::id id; - - /** - * @Effects Destroy the facet - */ - ~time_point_put() - { - } - - }; - - template - std::locale::id time_point_put::id; - - } // chrono -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/time_point_units.hpp b/utils/boost_idb/boost/chrono/io/time_point_units.hpp deleted file mode 100644 index 24284a76..00000000 --- a/utils/boost_idb/boost/chrono/io/time_point_units.hpp +++ /dev/null @@ -1,244 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// - -#ifndef BOOST_CHRONO_IO_TIME_POINT_UNITS_HPP -#define BOOST_CHRONO_IO_TIME_POINT_UNITS_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost -{ - namespace chrono - { - - /** - * @c time_point_units facet gives useful information about the time_point pattern, - * the text associated to a time_point's epoch, - */ - template - class time_point_units: public std::locale::facet - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string used by member functions. - */ - typedef std::basic_string string_type; - - /** - * Unique identifier for this type of facet. - */ - static std::locale::id id; - - /** - * Construct a @c time_point_units facet. - * @param refs - * @Effects Construct a @c time_point_units facet. - * If the @c refs argument is @c 0 then destruction of the object is - * delegated to the @c locale, or locales, containing it. This allows - * the user to ignore lifetime management issues. On the other had, - * if @c refs is @c 1 then the object must be explicitly deleted; - * the @c locale will not do so. In this case, the object can be - * maintained across the lifetime of multiple locales. - */ - explicit time_point_units(size_t refs = 0) : - std::locale::facet(refs) - { - } - - /** - * @return the pattern to be used by default. - */ - virtual string_type get_pattern() const =0; - - /** - * @return the epoch associated to the clock @c Clock calling @c do_get_epoch(Clock()) - */ - template - string_type get_epoch() const - { - return do_get_epoch(Clock()); - } - - protected: - /** - * Destroy the facet. - */ - virtual ~time_point_units() {} - - - /** - * - * @param c a dummy instance of @c system_clock. - * @return The epoch string associated to the @c system_clock. - */ - virtual string_type do_get_epoch(system_clock) const=0; - - /** - * - * @param c a dummy instance of @c steady_clock. - * @return The epoch string associated to the @c steady_clock. - */ - virtual string_type do_get_epoch(steady_clock) const=0; - -#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS) - /** - * - * @param c a dummy instance of @c process_real_cpu_clock. - * @return The epoch string associated to the @c process_real_cpu_clock. - */ - virtual string_type do_get_epoch(process_real_cpu_clock) const=0; - /** - * - * @param c a dummy instance of @c process_user_cpu_clock. - * @return The epoch string associated to the @c process_user_cpu_clock. - */ - virtual string_type do_get_epoch(process_user_cpu_clock) const=0; - /** - * - * @param c a dummy instance of @c process_system_cpu_clock. - * @return The epoch string associated to the @c process_system_cpu_clock. - */ - virtual string_type do_get_epoch(process_system_cpu_clock) const=0; - /** - * - * @param c a dummy instance of @c process_cpu_clock. - * @return The epoch string associated to the @c process_cpu_clock. - */ - virtual string_type do_get_epoch(process_cpu_clock) const=0; -#endif -#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK) - /** - * - * @param c a dummy instance of @c thread_clock. - * @return The epoch string associated to the @c thread_clock. - */ - virtual string_type do_get_epoch(thread_clock) const=0; -#endif - - }; - - template - std::locale::id time_point_units::id; - - - // This class is used to define the strings for the default English - template - class time_point_units_default: public time_point_units - { - public: - /** - * Type of character the facet is instantiated on. - */ - typedef CharT char_type; - /** - * Type of character string returned by member functions. - */ - typedef std::basic_string string_type; - - explicit time_point_units_default(size_t refs = 0) : - time_point_units (refs) - { - } - ~time_point_units_default() {} - - /** - * @return the default pattern "%d%e". - */ - string_type get_pattern() const - { - static const CharT t[] = - { '%', 'd', '%', 'e' }; - static const string_type pattern(t, t + sizeof (t) / sizeof (t[0])); - - return pattern; - } - - protected: - /** - * @param c a dummy instance of @c system_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(system_clock ) const - { - return clock_string::since(); - } - /** - * @param c a dummy instance of @c steady_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(steady_clock ) const - { - return clock_string::since(); - } - -#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS) - /** - * @param c a dummy instance of @c process_real_cpu_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(process_real_cpu_clock ) const - { - return clock_string::since(); - } - /** - * @param c a dummy instance of @c process_user_cpu_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(process_user_cpu_clock ) const - { - return clock_string::since(); - } - /** - * @param c a dummy instance of @c process_system_cpu_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(process_system_cpu_clock ) const - { - return clock_string::since(); - } - /** - * @param c a dummy instance of @c process_cpu_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(process_cpu_clock ) const - { - return clock_string::since(); - } - -#endif -#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK) - /** - * @param c a dummy instance of @c thread_clock. - * @return The epoch string returned by @c clock_string::since(). - */ - string_type do_get_epoch(thread_clock ) const - { - return clock_string::since(); - } -#endif - - }; - - - } // chrono - -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/timezone.hpp b/utils/boost_idb/boost/chrono/io/timezone.hpp deleted file mode 100644 index 67975da9..00000000 --- a/utils/boost_idb/boost/chrono/io/timezone.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// (C) Copyright Howard Hinnant -// (C) Copyright 2010-2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o to Boost - -#ifndef BOOST_CHRONO_IO_TIMEZONE_HPP -#define BOOST_CHRONO_IO_TIMEZONE_HPP -#include - -namespace boost -{ - namespace chrono - { - /** - * Scoped enumeration emulation stating whether the time_point for system_clock I/O is UTC or local. - */ - BOOST_SCOPED_ENUM_DECLARE_BEGIN(timezone) - { - utc, local - } - BOOST_SCOPED_ENUM_DECLARE_END(timezone) - - } // chrono -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/utility/ios_base_state_ptr.hpp b/utils/boost_idb/boost/chrono/io/utility/ios_base_state_ptr.hpp deleted file mode 100644 index 865b9872..00000000 --- a/utils/boost_idb/boost/chrono/io/utility/ios_base_state_ptr.hpp +++ /dev/null @@ -1,435 +0,0 @@ -// boost/chrono/utility/ios_base_pword_ptr.hpp ------------------------------------------------------------// - -// Copyright 2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/libs/chrono for documentation. - -#ifndef BOOST_CHRONO_UTILITY_IOS_BASE_STATE_PTR_HPP -#define BOOST_CHRONO_UTILITY_IOS_BASE_STATE_PTR_HPP - -#include -#include - -/** - * - - - */ -namespace boost -{ - namespace chrono - { - namespace detail - { - - /** - * xalloc key holder. - */ - template - struct xalloc_key_holder - { - static int value; //< the xalloc value associated to T. - static bool initialized; //< whether the value has been initialized or not. - }; - - template - int xalloc_key_holder::value = 0; - - template - bool xalloc_key_holder::initialized = false; - - } - - /** - * xalloc key initialiazer. - * - * Declare a static variable of this type to ensure that the xalloc_key_holder is initialized correctly. - */ - template - struct xalloc_key_initializer - { - xalloc_key_initializer() - { - if (!detail::xalloc_key_holder::initialized) - { - detail::xalloc_key_holder::value = std::ios_base::xalloc(); - detail::xalloc_key_holder::initialized = true; - } - } - }; - /** - * @c ios_state_ptr is a smart pointer to a ios_base specific state. - */ - template - class ios_state_ptr - { - ios_state_ptr& operator=(ios_state_ptr const& rhs) ; - - public: - /** - * The pointee type - */ - typedef T element_type; - /** - * Explicit constructor. - * @param ios the ios - * @Effects Constructs a @c ios_state_ptr by storing the associated @c ios. - */ - explicit ios_state_ptr(std::ios_base& ios) : - ios_(ios) - { - } - /** - * Nothing to do as xalloc index can not be removed. - */ - ~ios_state_ptr() - { - } - - /** - * @Effects Allocates the index if not already done. - * Registers the callback responsible of maintaining the state pointer coherency, if not already done. - * Retrieves the associated ios pointer - * @return the retrieved pointer statically casted to const. - */ - T const* get() const BOOST_NOEXCEPT - { - register_once(index(), ios_); - void* &pw = ios_.pword(index()); - if (pw == 0) - { - return 0; - } - return static_cast (pw); - } - /** - * @Effects Allocates the index if not already done. - * Registers the callback responsible of maintaining the state pointer coherency, if not already done. - * Retrieves the associated ios pointer - * @return the retrieved pointer. - */ - T * get() BOOST_NOEXCEPT - { - register_once(index(), ios_); - void* &pw = ios_.pword(index()); - if (pw == 0) - { - return 0; - } - return static_cast (pw); - } - /** - * @Effects as if @c return get(); - * @return the retrieved pointer. - */ - T * operator->()BOOST_NOEXCEPT - { - return get(); - } - /** - * @Effects as if @c return get(); - * @return the retrieved pointer. - */ - T const * operator->() const BOOST_NOEXCEPT - { - return get(); - } - - /** - * @Effects as if @c return *get(); - * @return a reference to the retrieved state. - * @Remark The behavior is undefined if @c get()==0. - */ - T & operator*() BOOST_NOEXCEPT - { - return *get(); - } - /** - * @Effects as if @c return *get(); - * @return a reference to the retrieved state. - * @Remark The behavior is undefined if @c get()==0. - */ - T const & operator *() const BOOST_NOEXCEPT - { - return *get(); - } - - /** - * @Effects reset the current pointer after storing in a temporary variable the pointer to the current state. - * @return the stored state pointer. - */ - T * release() BOOST_NOEXCEPT - { - T const* f = get(); - reset(); - return f; - } - - /** - * - * @param new_ptr the new pointer. - * @Effects deletes the current state and replace it with the new one. - */ - void reset(T* new_ptr = 0)BOOST_NOEXCEPT - { - register_once(index(), ios_); - void*& pw = ios_.pword(index()); - delete static_cast (pw); - pw = new_ptr; - } - -#if defined(BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS) - typedef T* (ios_state_ptr::*bool_type)(); - operator bool_type() const BOOST_NOEXCEPT - { - return (get()!=0)?&ios_state_ptr::release:0; - } - bool operator!() const BOOST_NOEXCEPT - { - return (get()==0)?&ios_state_ptr::release:0; - } -#else - /** - * Explicit conversion to bool. - */ - explicit operator bool() const BOOST_NOEXCEPT - { - return get()!=0; - } -#endif - - std::ios_base& getios()BOOST_NOEXCEPT - { - return ios_; - } - std::ios_base& getios() const BOOST_NOEXCEPT - { - return ios_; - } - /** - * Implicit conversion to the ios_base - */ - operator std::ios_base&() BOOST_NOEXCEPT - { - return ios_; - } - /** - * Implicit conversion to the ios_base const - */ - operator std::ios_base&() const BOOST_NOEXCEPT - { - return ios_; - } - private: - static inline bool is_registerd(std::ios_base& ios) - { - long iw = ios.iword(index()); - return (iw == 1); - } - static inline void set_registered(std::ios_base& ios) - { - long& iw = ios.iword(index()); - iw = 1; - } - static inline void callback(std::ios_base::event evt, std::ios_base& ios, int index) - { - switch (evt) - { - case std::ios_base::erase_event: - { - void*& pw = ios.pword(index); - if (pw != 0) - { - T* ptr = static_cast (pw); - delete ptr; - pw = 0; - } - break; - } - case std::ios_base::copyfmt_event: - { - void*& pw = ios.pword(index); - if (pw != 0) - { - pw = new T(*static_cast (pw)); - } - break; - } - default: - break; - } - } - - static inline int index() - { - return detail::xalloc_key_holder::value; - } - - static inline void register_once(int indx, std::ios_base& ios) - { - // needs a mask registered - if (!is_registerd(ios)) - { - set_registered(ios); - ios.register_callback(callback, indx); - } - } - - - protected: - std::ios_base& ios_; - //static detail::xalloc_key_initializer xalloc_key_initializer_; - - }; - //template - //detail::xalloc_key_initializer ios_state_ptr::xalloc_key_initializer_; - - - /** - * @c ios_state_not_null_ptr is a non null variant of @c ios_state_ptr. - * @tparm T - * @Requires @c T must be @c DefaultConstructible and @c HeapAllocatable - */ - template - class ios_state_not_null_ptr: public ios_state_ptr - { - typedef ios_state_ptr base_type; - public: - explicit ios_state_not_null_ptr(std::ios_base& ios) : - base_type(ios) - { - if (this->get() == 0) - { - this->base_type::reset(new T()); - } - } - ~ios_state_not_null_ptr() - { - } - - void reset(T* new_value) BOOST_NOEXCEPT - { - BOOST_ASSERT(new_value!=0); - this->base_type::reset(new_value); - } - - }; - - /** - * This class is useful to associate some flags to an std::ios_base. - */ - template - class ios_flags - { - public: - /** - * - * @param ios the associated std::ios_base. - * @Postcondition flags()==0 - */ - explicit ios_flags(std::ios_base& ios) : - ios_(ios) - { - } - ~ios_flags() - { - } - /** - * @Returns The format control information. - */ - long flags() const BOOST_NOEXCEPT - { - return value(); - } - - /** - * @param v the new bit mask. - * @Postcondition v == flags(). - * @Returns The previous value of @c flags(). - */ - long flags(long v)BOOST_NOEXCEPT - { - long tmp = flags(); - ref() = v; - return tmp; - } - - /** - * @param v the new value - * @Effects: Sets @c v in @c flags(). - * @Returns: The previous value of @c flags(). - */ - long setf(long v) - { - long tmp = value(); - ref() |= v; - return tmp; - } - - /** - * @param mask the bit mask to clear. - * @Effects: Clears @c mask in @c flags(). - */ - void unsetf(long mask) - { - ref() &= ~mask; - } - - /** - * - * @param v - * @param mask - * @Effects: Clears @c mask in @c flags(), sets v & mask in @c flags(). - * @Returns: The previous value of flags(). - */ - long setf(long v, long mask) - { - long tmp = value(); - unsetf(mask); - ref() |= v & mask; - return tmp; - } - - /** - * implicit conversion to the @c ios_base - */ - operator std::ios_base&()BOOST_NOEXCEPT - { - return ios_; - } - /** - * implicit conversion to the @c ios_base const - */ - operator std::ios_base const&() const BOOST_NOEXCEPT - { - return ios_; - } - private: - long value() const BOOST_NOEXCEPT - { - return ios_.iword(index()); - } - long& ref()BOOST_NOEXCEPT - { - return ios_.iword(index()); - } - static inline int index() - { - return detail::xalloc_key_holder::value; - } - ios_flags& operator=(ios_flags const& rhs) ; - - std::ios_base& ios_; - //static detail::xalloc_key_initializer xalloc_key_initializer_; - - }; - //template - //detail::xalloc_key_initializer ios_flags::xalloc_key_initializer_; - - } // namespace chrono -} // namespace boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/utility/manip_base.hpp b/utils/boost_idb/boost/chrono/io/utility/manip_base.hpp deleted file mode 100644 index f4a5f562..00000000 --- a/utils/boost_idb/boost/chrono/io/utility/manip_base.hpp +++ /dev/null @@ -1,101 +0,0 @@ -// boost/chrono/utility/manip_base.hpp ------------------------------------------------------------// - -// Copyright 2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/libs/chrono for documentation. - -#ifndef BOOST_CHRONO_UTILITY_MANIP_BASE_PTR_HPP -#define BOOST_CHRONO_UTILITY_MANIP_BASE_PTR_HPP - -#include - -/** - * - - */ - -namespace boost -{ - namespace chrono - { - - /** - * manip is a manipulator mixin class following the CRTP. - * @tparam Final the derived from manip and final type - * - * @Example - * @code - - class mendl: public manip - { - public: - explicit mendl(size_t how_many) : - count(how_many) {} - template - void operator()(out_stream &out) const - { - for (size_t line = 0; line < count; ++line) - { - out.put(out.widen('\n')); - } - out.flush(); - } - private: - size_t count; - }; - - * @codeend - */ - template - class manip - { - public: - /** - * - * @param ios the io stream or ios_base. - * @Effects calls to the manipulator final functor. - */ - //template - void operator()(std::ios_base &ios) const - { - (*static_cast (this))(ios); - } - }; - - /** - * @c manip stream inserter - * @param out the io stream or ios_base. - * @param op the manipulator instance. - * @Effects if @c out is good calls to the manipulator functor @op. - * @return @c out - */ - template - out_stream &operator<<(out_stream &out, const manip &op) - { - if (out.good()) - op(out); - return out; - } - - /** - * @c manip stream extractor - * @param in the io stream or ios_base. - * @param op the manipulator instance. - * @Effects if @c in is good calls to the manipulator functor @op. - * @return @c in - */ - template - in_stream &operator>>(in_stream &in, const manip &op) - { - if (in.good()) - op(in); - return in; - } - - } // namespace chrono -} // namespace boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io/utility/to_string.hpp b/utils/boost_idb/boost/chrono/io/utility/to_string.hpp deleted file mode 100644 index 4717ba6a..00000000 --- a/utils/boost_idb/boost/chrono/io/utility/to_string.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// boost/chrono/utility/to_string.hpp -// -// Copyright 2011 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). - -#ifndef BOOST_CHRONO_UTILITY_TO_STRING_HPP -#define BOOST_CHRONO_UTILITY_TO_STRING_HPP - -#include -#include -#include - -namespace boost -{ - namespace chrono - { - template - std::basic_string to_basic_string(T const&v) { - std::basic_stringstream sstr; - sstr << v; - return sstr.str(); - } - - template - std::string to_string(T const&v) { - return to_basic_string(v); - } -#ifndef BOOST_NO_STD_WSTRING - template - std::wstring to_wstring(T const&v) { - return to_basic_string(v); - } -#endif -#if BOOST_CHRONO_HAS_UNICODE_SUPPORT - template - std::basic_string to_u16string(T const&v) { - return to_basic_string(v); - } - template - std::basic_string to_u32string(T const&v) { - return to_basic_string(v); - } -#endif - } // chrono - -} // boost - -#endif // header diff --git a/utils/boost_idb/boost/chrono/io_v1/chrono_io.hpp b/utils/boost_idb/boost/chrono/io_v1/chrono_io.hpp deleted file mode 100644 index daabd492..00000000 --- a/utils/boost_idb/boost/chrono/io_v1/chrono_io.hpp +++ /dev/null @@ -1,637 +0,0 @@ - -// chrono_io -// -// (C) Copyright Howard Hinnant -// (C) Copyright 2010 Vicente J. Botet Escriba -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// This code was adapted by Vicente from Howard Hinnant's experimental work -// on chrono i/o under lvm/libc++ to Boost - -#ifndef BOOST_CHRONO_IO_V1_CHRONO_IO_HPP -#define BOOST_CHRONO_IO_V1_CHRONO_IO_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost -{ - -namespace chrono -{ - -template -class duration_punct - : public std::locale::facet -{ -public: - typedef std::basic_string string_type; - enum {use_long, use_short}; - -private: - bool use_short_; - string_type long_seconds_; - string_type long_minutes_; - string_type long_hours_; - string_type short_seconds_; - string_type short_minutes_; - string_type short_hours_; - - template - string_type short_name(Period) const - {return ::boost::ratio_string::short_name() + short_seconds_;} - - string_type short_name(ratio<1>) const {return short_seconds_;} - string_type short_name(ratio<60>) const {return short_minutes_;} - string_type short_name(ratio<3600>) const {return short_hours_;} - - template - string_type long_name(Period) const - {return ::boost::ratio_string::long_name() + long_seconds_;} - - string_type long_name(ratio<1>) const {return long_seconds_;} - string_type long_name(ratio<60>) const {return long_minutes_;} - string_type long_name(ratio<3600>) const {return long_hours_;} - - void init_C(); -public: - static std::locale::id id; - - explicit duration_punct(int use = use_long) - : use_short_(use==use_short) {init_C();} - - duration_punct(int use, - const string_type& long_seconds, const string_type& long_minutes, - const string_type& long_hours, const string_type& short_seconds, - const string_type& short_minutes, const string_type& short_hours); - - duration_punct(int use, const duration_punct& d); - - template - string_type short_name() const - {return short_name(typename Period::type());} - - template - string_type long_name() const - {return long_name(typename Period::type());} - - template - string_type plural() const - {return long_name(typename Period::type());} - - template - string_type singular() const - { - return string_type(long_name(typename Period::type()), 0, long_name(typename Period::type()).size()-1); - } - - template - string_type name() const - { - if (use_short_) return short_name(); - else { - return long_name(); - } - } - template - string_type name(D v) const - { - if (use_short_) return short_name(); - else - { - if (v==-1 || v==1) - return singular(); - else - return plural(); - } - } - - bool is_short_name() const {return use_short_;} - bool is_long_name() const {return !use_short_;} -}; - -template -std::locale::id -duration_punct::id; - -template -void -duration_punct::init_C() -{ - short_seconds_ = CharT('s'); - short_minutes_ = CharT('m'); - short_hours_ = CharT('h'); - const CharT s[] = {'s', 'e', 'c', 'o', 'n', 'd', 's'}; - const CharT m[] = {'m', 'i', 'n', 'u', 't', 'e', 's'}; - const CharT h[] = {'h', 'o', 'u', 'r', 's'}; - long_seconds_.assign(s, s + sizeof(s)/sizeof(s[0])); - long_minutes_.assign(m, m + sizeof(m)/sizeof(m[0])); - long_hours_.assign(h, h + sizeof(h)/sizeof(h[0])); -} - -template -duration_punct::duration_punct(int use, - const string_type& long_seconds, const string_type& long_minutes, - const string_type& long_hours, const string_type& short_seconds, - const string_type& short_minutes, const string_type& short_hours) - : use_short_(use==use_short), - long_seconds_(long_seconds), - long_minutes_(long_minutes), - long_hours_(long_hours), - short_seconds_(short_seconds), - short_minutes_(short_minutes), - short_hours_(short_hours) -{} - -template -duration_punct::duration_punct(int use, const duration_punct& d) - : use_short_(use==use_short), - long_seconds_(d.long_seconds_), - long_minutes_(d.long_minutes_), - long_hours_(d.long_hours_), - short_seconds_(d.short_seconds_), - short_minutes_(d.short_minutes_), - short_hours_(d.short_hours_) -{} - -template -std::basic_ostream& -duration_short(std::basic_ostream& os) -{ - typedef duration_punct Facet; - std::locale loc = os.getloc(); - if (std::has_facet(loc)) - { - const Facet& f = std::use_facet(loc); - if (f.is_long_name()) - os.imbue(std::locale(loc, new Facet(Facet::use_short, f))); - } - else - os.imbue(std::locale(loc, new Facet(Facet::use_short))); - return os; -} - -template -std::basic_ostream& -duration_long(std::basic_ostream& os) -{ - typedef duration_punct Facet; - std::locale loc = os.getloc(); - if (std::has_facet(loc)) - { - const Facet& f = std::use_facet(loc); - if (f.is_short_name()) - os.imbue(std::locale(loc, new Facet(Facet::use_long, f))); - } - return os; -} - -template -std::basic_ostream& -operator<<(std::basic_ostream& os, const duration& d) -{ - typedef duration_punct Facet; - std::locale loc = os.getloc(); - if (!std::has_facet(loc)) - os.imbue(std::locale(loc, new Facet)); - const Facet& f = std::use_facet(os.getloc()); - return os << d.count() << ' ' << f.template name(d.count()); -} - -namespace chrono_detail { -template ::value> -struct duration_io_intermediate -{ - typedef Rep type; -}; - -template -struct duration_io_intermediate -{ - typedef typename mpl::if_c - < - is_floating_point::value, - long double, - typename mpl::if_c - < - is_signed::value, - long long, - unsigned long long - >::type - >::type type; -}; - -template -typename enable_if, bool>::type -reduce(intermediate_type& r, unsigned long long& den, std::ios_base::iostate& err) -{ - typedef typename common_type::type common_type_t; - - // Reduce r * num / den - common_type_t t = math::gcd(common_type_t(r), common_type_t(den)); - r /= t; - den /= t; - if (den != 1) - { - // Conversion to Period is integral and not exact - err |= std::ios_base::failbit; - return false; - } - return true; -} -template -typename disable_if, bool>::type -reduce(intermediate_type& , unsigned long long& , std::ios_base::iostate& ) -{ - return true; -} - -} - -template -std::basic_istream& -operator>>(std::basic_istream& is, duration& d) -{ - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - typedef duration_punct Facet; - std::locale loc = is.getloc(); - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - if (!std::has_facet(loc)) { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.imbue(std::locale(loc, new Facet)); - } - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - loc = is.getloc(); - const Facet& f = std::use_facet(loc); - typedef typename chrono_detail::duration_io_intermediate::type intermediate_type; - intermediate_type r; - std::ios_base::iostate err = std::ios_base::goodbit; - // read value into r - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is >> r; - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - if (is.good()) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // now determine unit - typedef std::istreambuf_iterator in_iterator; - in_iterator i(is); - in_iterator e; - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - if (i != e && *i == ' ') // mandatory ' ' after value - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - ++i; - if (i != e) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // unit is num / den (yet to be determined) - unsigned long long num = 0; - unsigned long long den = 0; - if (*i == '[') - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // parse [N/D]s or [N/D]seconds format - ++i; - CharT x; - is >> num >> x >> den; - if (!is.good() || (x != '/')) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(is.failbit); - return is; - } - i = in_iterator(is); - if (*i != ']') - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(is.failbit); - return is; - } - ++i; - const std::basic_string units[] = - { - f.template singular >(), - f.template plural >(), - f.template short_name >() - }; - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - const std::basic_string* k = chrono_detail::scan_keyword(i, e, - units, units + sizeof(units)/sizeof(units[0]), - //~ std::use_facet >(loc), - err); - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(err); - switch ((k - units) / 3) - { - case 0: - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - break; - default: - is.setstate(err); - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - return is; - } - } - else - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // parse SI name, short or long - const std::basic_string units[] = - { - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular(), - f.template plural(), - f.template short_name(), - f.template singular >(), - f.template plural >(), - f.template short_name >(), - f.template singular >(), - f.template plural >(), - f.template short_name >(), - f.template singular >(), - f.template plural >(), - f.template short_name >() - }; - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - const std::basic_string* k = chrono_detail::scan_keyword(i, e, - units, units + sizeof(units)/sizeof(units[0]), - //~ std::use_facet >(loc), - err); - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - switch ((k - units) / 3) - { - case 0: - num = 1ULL; - den = 1000000000000000000ULL; - break; - case 1: - num = 1ULL; - den = 1000000000000000ULL; - break; - case 2: - num = 1ULL; - den = 1000000000000ULL; - break; - case 3: - num = 1ULL; - den = 1000000000ULL; - break; - case 4: - num = 1ULL; - den = 1000000ULL; - break; - case 5: - num = 1ULL; - den = 1000ULL; - break; - case 6: - num = 1ULL; - den = 100ULL; - break; - case 7: - num = 1ULL; - den = 10ULL; - break; - case 8: - num = 10ULL; - den = 1ULL; - break; - case 9: - num = 100ULL; - den = 1ULL; - break; - case 10: - num = 1000ULL; - den = 1ULL; - break; - case 11: - num = 1000000ULL; - den = 1ULL; - break; - case 12: - num = 1000000000ULL; - den = 1ULL; - break; - case 13: - num = 1000000000000ULL; - den = 1ULL; - break; - case 14: - num = 1000000000000000ULL; - den = 1ULL; - break; - case 15: - num = 1000000000000000000ULL; - den = 1ULL; - break; - case 16: - num = 1; - den = 1; - break; - case 17: - num = 60; - den = 1; - break; - case 18: - num = 3600; - den = 1; - break; - default: - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(err|is.failbit); - return is; - } - } - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // unit is num/den - // r should be multiplied by (num/den) / Period - // Reduce (num/den) / Period to lowest terms - unsigned long long gcd_n1_n2 = math::gcd(num, Period::num); - unsigned long long gcd_d1_d2 = math::gcd(den, Period::den); - num /= gcd_n1_n2; - den /= gcd_d1_d2; - unsigned long long n2 = Period::num / gcd_n1_n2; - unsigned long long d2 = Period::den / gcd_d1_d2; - if (num > (std::numeric_limits::max)() / d2 || - den > (std::numeric_limits::max)() / n2) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // (num/den) / Period overflows - is.setstate(err|is.failbit); - return is; - } - num *= d2; - den *= n2; - - typedef typename common_type::type common_type_t; - - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // num / den is now factor to multiply by r - if (!chrono_detail::reduce(r, den, err)) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(err|is.failbit); - return is; - } - - //if (r > ((duration_values::max)() / num)) - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - if (chrono::detail::gt(r,((duration_values::max)() / num))) - { - // Conversion to Period overflowed - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(err|is.failbit); - return is; - } - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - common_type_t t = r * num; - t /= den; - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - - if (t > 0) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - Rep pt = t; - if ( (duration_values::max)() < pt) - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // Conversion to Period overflowed - is.setstate(err|is.failbit); - return is; - } - } - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - // Success! Store it. - r = Rep(t); - d = duration(r); - is.setstate(err); - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - return is; - } - else { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - is.setstate(is.failbit | is.eofbit); - return is; - } - } - else - { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - if (i == e) - is.setstate(is.failbit|is.eofbit); - else - is.setstate(is.failbit); - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - return is; - } - } - else { - //std::cerr << __FILE__ << "[" << __LINE__ << "]"<< std::endl; - //is.setstate(is.failbit); - return is; - } -} - - -template -std::basic_ostream& -operator<<(std::basic_ostream& os, - const time_point& tp) -{ - return os << tp.time_since_epoch() << clock_string::since(); -} - -template -std::basic_istream& -operator>>(std::basic_istream& is, - time_point& tp) -{ - Duration d; - is >> d; - if (is.good()) - { - const std::basic_string units=clock_string::since(); - std::ios_base::iostate err = std::ios_base::goodbit; - typedef std::istreambuf_iterator in_iterator; - in_iterator i(is); - in_iterator e; - std::ptrdiff_t k = chrono_detail::scan_keyword(i, e, - &units, &units + 1, - //~ std::use_facet >(is.getloc()), - err) - &units; - is.setstate(err); - if (k == 1) - { - is.setstate(err | is.failbit); - // failed to read epoch string - return is; - } - tp = time_point(d); - } - else - is.setstate(is.failbit); - return is; -} -} // chrono - -} - -#endif // BOOST_CHRONO_CHRONO_IO_HPP diff --git a/utils/boost_idb/boost/chrono/process_cpu_clocks.hpp b/utils/boost_idb/boost/chrono/process_cpu_clocks.hpp deleted file mode 100644 index 486950da..00000000 --- a/utils/boost_idb/boost/chrono/process_cpu_clocks.hpp +++ /dev/null @@ -1,510 +0,0 @@ -// boost/chrono/process_cpu_clocks.hpp -----------------------------------------------------------// - -// Copyright 2009-2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/system for documentation. - -#ifndef BOOST_CHRONO_PROCESS_CPU_CLOCKS_HPP -#define BOOST_CHRONO_PROCESS_CPU_CLOCKS_HPP - -#include - - -#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS) - -#include -#include -#include -#include -#include -#include -#include - -#ifndef BOOST_CHRONO_HEADER_ONLY -#include // must be the last #include -#endif - -namespace boost { namespace chrono { - - class BOOST_CHRONO_DECL process_real_cpu_clock { - public: - typedef nanoseconds duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = true; - - static BOOST_CHRONO_INLINE time_point now() BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now(system::error_code & ec ); -#endif - }; - - class BOOST_CHRONO_DECL process_user_cpu_clock { - public: - typedef nanoseconds duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = true; - - static BOOST_CHRONO_INLINE time_point now() BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now(system::error_code & ec ); -#endif - }; - - class BOOST_CHRONO_DECL process_system_cpu_clock { - public: - typedef nanoseconds duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = true; - - static BOOST_CHRONO_INLINE time_point now() BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now(system::error_code & ec ); -#endif - }; - - template - struct process_times - : arithmetic, - multiplicative, Rep, - less_than_comparable > > > - { - //typedef process_real_cpu_clock::rep rep; - typedef Rep rep; - process_times() - : real(0) - , user(0) - , system(0){} - template - explicit process_times( - Rep2 r) - : real(r) - , user(r) - , system(r){} - template - explicit process_times( - process_times const& rhs) - : real(rhs.real) - , user(rhs.user) - , system(rhs.system){} - process_times( - rep r, - rep u, - rep s) - : real(r) - , user(u) - , system(s){} - - rep real; // real (i.e wall clock) time - rep user; // user cpu time - rep system; // system cpu time - - operator rep() const - { - return real; - } - template - bool operator==(process_times const& rhs) { - return (real==rhs.real && - user==rhs.user && - system==rhs.system); - } - - process_times& operator+=( - process_times const& rhs) - { - real+=rhs.real; - user+=rhs.user; - system+=rhs.system; - return *this; - } - process_times& operator-=( - process_times const& rhs) - { - real-=rhs.real; - user-=rhs.user; - system-=rhs.system; - return *this; - } - process_times& operator*=( - process_times const& rhs) - { - real*=rhs.real; - user*=rhs.user; - system*=rhs.system; - return *this; - } - process_times& operator*=(rep const& rhs) - { - real*=rhs; - user*=rhs; - system*=rhs; - return *this; - } - process_times& operator/=(process_times const& rhs) - { - real/=rhs.real; - user/=rhs.user; - system/=rhs.system; - return *this; - } - process_times& operator/=(rep const& rhs) - { - real/=rhs; - user/=rhs; - system/=rhs; - return *this; - } - bool operator<(process_times const & rhs) const - { - if (real < rhs.real) return true; - if (real > rhs.real) return false; - if (user < rhs.user) return true; - if (user > rhs.user) return false; - if (system < rhs.system) return true; - else return false; - } - - template - void print(std::basic_ostream& os) const - { - os << "{"<< real <<";"<< user <<";"<< system << "}"; - } - - template - void read(std::basic_istream& is) const - { - typedef std::istreambuf_iterator in_iterator; - in_iterator i(is); - in_iterator e; - if (i == e || *i != '{') // mandatory '{' - { - is.setstate(is.failbit | is.eofbit); - return; - } - CharT x,y,z; - is >> real >> x >> user >> y >> system >> z; - if (!is.good() || (x != ';')|| (y != ';')|| (z != '}')) - { - is.setstate(is.failbit); - } - } - }; -} -template -struct common_type< - chrono::process_times, - chrono::process_times -> -{ - typedef chrono::process_times::type> type; -}; - -template -struct common_type< - chrono::process_times, - Rep2 -> -{ - typedef chrono::process_times::type> type; -}; - -template -struct common_type< - Rep1, - chrono::process_times -> -{ - typedef chrono::process_times::type> type; -}; - - -namespace chrono -{ - template - inline BOOST_CONSTEXPR - bool - operator==(const duration, Period1>& lhs, - const duration, Period2>& rhs) - { - return boost::chrono::detail::duration_eq< - duration, Period1>, duration, Period2> >()(lhs, rhs); - } - - template - inline BOOST_CONSTEXPR - bool - operator==(const duration, Period1>& lhs, - const duration& rhs) - { - return boost::chrono::detail::duration_eq< - duration, duration >()(duration(lhs.count().real), rhs); - } - - template - inline BOOST_CONSTEXPR - bool - operator==(const duration& lhs, - const duration, Period2>& rhs) - { - return rhs == lhs; - } - - - // Duration < - - template - inline BOOST_CONSTEXPR - bool - operator< (const duration, Period1>& lhs, - const duration& rhs) - { - return boost::chrono::detail::duration_lt< - duration, duration >()(duration(lhs.count().real), rhs); - } - - template - inline BOOST_CONSTEXPR - bool - operator< (const duration& lhs, - const duration, Period2>& rhs) - { - return rhs < lhs; - } - - template - inline BOOST_CONSTEXPR - bool - operator< (const duration, Period1>& lhs, - const duration, Period2>& rhs) - { - return boost::chrono::detail::duration_lt< - duration, duration >()(lhs, rhs); - } - - - typedef process_times process_cpu_clock_times; - class BOOST_CHRONO_DECL process_cpu_clock - { - public: - - typedef process_cpu_clock_times times; - typedef boost::chrono::duration duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = true; - - static BOOST_CHRONO_INLINE time_point now() BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now(system::error_code & ec ); -#endif - }; - - template - std::basic_ostream& - operator<<(std::basic_ostream& os, - process_times const& rhs) - { - rhs.print(os); - return os; - } - - template - std::basic_istream& - operator>>(std::basic_istream& is, - process_times const& rhs) - { - rhs.read(is); - return is; - } - - template - struct duration_values > - { - typedef process_times Res; - public: - static Res zero() - { - return Res(); - } - static Res max BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return Res((std::numeric_limits::max)(), - (std::numeric_limits::max)(), - (std::numeric_limits::max)()); - } - static Res min BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return Res((std::numeric_limits::min)(), - (std::numeric_limits::min)(), - (std::numeric_limits::min)()); - } - }; - - template - struct clock_string - { - static std::basic_string name() - { - static const CharT - u[] = - { 'p', 'r', 'o', 'c', 'e', 's', 's', '_', 'r', 'e', 'a', 'l', '_', 'c', 'l', 'o', 'c', 'k' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - static std::basic_string since() - { - const CharT - u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 'p', 'r', 'o', 'c', 'e', 's', 's', ' ', 's', 't', 'a', 'r', 't', '-', 'u', 'p' }; - const std::basic_string str(u, u + sizeof(u) / sizeof(u[0])); - return str; - } - }; - - template - struct clock_string - { - static std::basic_string name() - { - static const CharT - u[] = - { 'p', 'r', 'o', 'c', 'e', 's', 's', '_', 'u', 's', 'e', 'r', '_', 'c', 'l', 'o', 'c', 'k' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - static std::basic_string since() - { - const CharT - u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 'p', 'r', 'o', 'c', 'e', 's', 's', ' ', 's', 't', 'a', 'r', 't', '-', 'u', 'p' }; - const std::basic_string str(u, u + sizeof(u) / sizeof(u[0])); - return str; - } - }; - - template - struct clock_string - { - static std::basic_string name() - { - static const CharT - u[] = - { 'p', 'r', 'o', 'c', 'e', 's', 's', '_', 's', 'y', 's', 't', 't', 'e', 'm', '_', 'c', 'l', 'o', 'c', 'k' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - static std::basic_string since() - { - const CharT - u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 'p', 'r', 'o', 'c', 'e', 's', 's', ' ', 's', 't', 'a', 'r', 't', '-', 'u', 'p' }; - const std::basic_string str(u, u + sizeof(u) / sizeof(u[0])); - return str; - } - }; - - template - struct clock_string - { - static std::basic_string name() - { - static const CharT u[] = - { 'p', 'r', 'o', 'c', 'e', 's', 's', '_', 'c', 'l', 'o', 'c', 'k' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - static std::basic_string since() - { - const CharT - u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 'p', 'r', 'o', 'c', 'e', 's', 's', ' ', 's', 't', 'a', 'r', 't', '-', 'u', 'p' }; - const std::basic_string str(u, u + sizeof(u) / sizeof(u[0])); - return str; - } - }; - -} // namespace chrono -} // namespace boost - -namespace std { - - template - struct numeric_limits > - { - typedef boost::chrono::process_times Res; - - public: - static const bool is_specialized = true; - static Res min BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return Res((std::numeric_limits::min)(), - (std::numeric_limits::min)(), - (std::numeric_limits::min)()); - } - static Res max BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return Res((std::numeric_limits::max)(), - (std::numeric_limits::max)(), - (std::numeric_limits::max)()); - } - static Res lowest() throw() - { - return (min)(); - } - static const int digits = std::numeric_limits::digits+ - std::numeric_limits::digits+ - std::numeric_limits::digits; - static const int digits10 = std::numeric_limits::digits10+ - std::numeric_limits::digits10+ - std::numeric_limits::digits10; - static const bool is_signed = Rep::is_signed; - static const bool is_integer = Rep::is_integer; - static const bool is_exact = Rep::is_exact; - static const int radix = 0; - //~ static Res epsilon() throw() { return 0; } - //~ static Res round_error() throw() { return 0; } - //~ static const int min_exponent = 0; - //~ static const int min_exponent10 = 0; - //~ static const int max_exponent = 0; - //~ static const int max_exponent10 = 0; - //~ static const bool has_infinity = false; - //~ static const bool has_quiet_NaN = false; - //~ static const bool has_signaling_NaN = false; - //~ static const float_denorm_style has_denorm = denorm_absent; - //~ static const bool has_denorm_loss = false; - //~ static Res infinity() throw() { return 0; } - //~ static Res quiet_NaN() throw() { return 0; } - //~ static Res signaling_NaN() throw() { return 0; } - //~ static Res denorm_min() throw() { return 0; } - //~ static const bool is_iec559 = false; - //~ static const bool is_bounded = true; - //~ static const bool is_modulo = false; - //~ static const bool traps = false; - //~ static const bool tinyness_before = false; - //~ static const float_round_style round_style = round_toward_zero; - - }; -} - -#ifndef BOOST_CHRONO_HEADER_ONLY -#include // pops abi_prefix.hpp pragmas -#else -#include -#endif -#endif - -#endif // BOOST_CHRONO_PROCESS_CPU_CLOCKS_HPP diff --git a/utils/boost_idb/boost/chrono/round.hpp b/utils/boost_idb/boost/chrono/round.hpp deleted file mode 100644 index 3d0619e6..00000000 --- a/utils/boost_idb/boost/chrono/round.hpp +++ /dev/null @@ -1,55 +0,0 @@ -// boost/chrono/round.hpp ------------------------------------------------------------// - -// (C) Copyright Howard Hinnant -// Copyright 2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org/libs/chrono for documentation. - -#ifndef BOOST_CHRONO_ROUND_HPP -#define BOOST_CHRONO_ROUND_HPP - -#include -#include -//#include - -namespace boost -{ - namespace chrono - { - - /** - * rounds to nearest, to even on tie - */ - template - To round(const duration& d) - { - To t0 = duration_cast(d); - To t1 = t0; - ++t1; -#if 0 - // Avoid the user of BOOST_AUTO to make the library portable to Sun, PGI, .. - BOOST_AUTO(diff0, d - t0); - BOOST_AUTO(diff1, t1 - d); -#else - typedef typename common_type >::type result_type; - result_type diff0 = d - t0; - result_type diff1 = t1 - d; -#endif - if (diff0 == diff1) - { - if (t0.count() & 1) - return t1; - return t0; - } - else if (diff0 < diff1) - return t0; - return t1; - } - - } // namespace chrono -} // namespace boost - -#endif diff --git a/utils/boost_idb/boost/chrono/system_clocks.hpp b/utils/boost_idb/boost/chrono/system_clocks.hpp deleted file mode 100644 index 5ba6a3b0..00000000 --- a/utils/boost_idb/boost/chrono/system_clocks.hpp +++ /dev/null @@ -1,233 +0,0 @@ -// boost/chrono/system_clocks.hpp --------------------------------------------------------------// - -// Copyright 2008 Howard Hinnant -// Copyright 2008 Beman Dawes -// Copyright 2009-2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -/* - -This code was derived by Beman Dawes from Howard Hinnant's time2_demo prototype. -Many thanks to Howard for making his code available under the Boost license. -The original code was modified to conform to Boost conventions and to section -20.9 Time utilities [time] of the C++ committee's working paper N2798. -See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf. - -time2_demo contained this comment: - - Much thanks to Andrei Alexandrescu, - Walter Brown, - Peter Dimov, - Jeff Garland, - Terry Golubiewski, - Daniel Krugler, - Anthony Williams. -*/ - -/* - -TODO: - - * Fully implement error handling, with test cases. - * Consider issues raised by Michael Marcin: - - > In the past I've seen QueryPerformanceCounter give incorrect results, - > especially with SpeedStep processors on laptops. This was many years ago and - > might have been fixed by service packs and drivers. - > - > Typically you check the results of QPC against GetTickCount to see if the - > results are reasonable. - > http://support.microsoft.com/kb/274323 - > - > I've also heard of problems with QueryPerformanceCounter in multi-processor - > systems. - > - > I know some people SetThreadAffinityMask to 1 for the current thread call - > their QueryPerformance* functions then restore SetThreadAffinityMask. This - > seems horrible to me because it forces your program to jump to another - > physical processor if it isn't already on cpu0 but they claim it worked well - > in practice because they called the timing functions infrequently. - > - > In the past I have chosen to use timeGetTime with timeBeginPeriod(1) for - > high resolution timers to avoid these issues. - -*/ - -#ifndef BOOST_CHRONO_SYSTEM_CLOCKS_HPP -#define BOOST_CHRONO_SYSTEM_CLOCKS_HPP - -#include -#include -#include -#include -#include - -#include - -# if defined( BOOST_CHRONO_POSIX_API ) -# if ! defined(CLOCK_REALTIME) && ! defined (__hpux__) -# error does not supply CLOCK_REALTIME -# endif -# endif - -#ifdef BOOST_CHRONO_WINDOWS_API -// The system_clock tick is 100 nanoseconds -# define BOOST_SYSTEM_CLOCK_DURATION boost::chrono::duration > -#else -# define BOOST_SYSTEM_CLOCK_DURATION boost::chrono::nanoseconds -#endif - -// this must occur after all of the includes and before any code appears: -#ifndef BOOST_CHRONO_HEADER_ONLY -#include // must be the last #include -#endif - - -//----------------------------------------------------------------------------// -// // -// 20.9 Time utilities [time] // -// synopsis // -// // -//----------------------------------------------------------------------------// - -namespace boost { -namespace chrono { - - // Clocks - class BOOST_CHRONO_DECL system_clock; -#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY - class BOOST_CHRONO_DECL steady_clock; -#endif - -#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY - typedef steady_clock high_resolution_clock; // as permitted by [time.clock.hires] -#else - typedef system_clock high_resolution_clock; // as permitted by [time.clock.hires] -#endif - -//----------------------------------------------------------------------------// -// // -// 20.9.5 Clocks [time.clock] // -// // -//----------------------------------------------------------------------------// - -// If you're porting, clocks are the system-specific (non-portable) part. -// You'll need to know how to get the current time and implement that under now(). -// You'll need to know what units (tick period) and representation makes the most -// sense for your clock and set those accordingly. -// If you know how to map this clock to time_t (perhaps your clock is std::time, which -// makes that trivial), then you can fill out system_clock's to_time_t() and from_time_t(). - -//----------------------------------------------------------------------------// -// 20.9.5.1 Class system_clock [time.clock.system] // -//----------------------------------------------------------------------------// - - class BOOST_CHRONO_DECL system_clock - { - public: - typedef BOOST_SYSTEM_CLOCK_DURATION duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = false; - - static BOOST_CHRONO_INLINE time_point now() BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now(system::error_code & ec); -#endif - - static BOOST_CHRONO_INLINE std::time_t to_time_t(const time_point& t) BOOST_NOEXCEPT; - static BOOST_CHRONO_INLINE time_point from_time_t(std::time_t t) BOOST_NOEXCEPT; - }; - -//----------------------------------------------------------------------------// -// 20.9.5.2 Class steady_clock [time.clock.steady] // -//----------------------------------------------------------------------------// - -// As permitted by [time.clock.steady] -// The class steady_clock is conditionally supported. - -#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY - class BOOST_CHRONO_DECL steady_clock - { - public: - typedef nanoseconds duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = true; - - static BOOST_CHRONO_INLINE time_point now() BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now(system::error_code & ec); -#endif - }; -#endif -//----------------------------------------------------------------------------// -// 20.9.5.3 Class high_resolution_clock [time.clock.hires] // -//----------------------------------------------------------------------------// - -// As permitted, steady_clock or system_clock is a typedef for high_resolution_clock. -// See synopsis. - - - template - struct clock_string - { - static std::basic_string name() - { - static const CharT u[] = - { 's', 'y', 's', 't', 'e', 'm', '_', 'c', 'l', 'o', 'c', 'k' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - static std::basic_string since() - { - static const CharT - u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 'J', 'a', 'n', ' ', '1', ',', ' ', '1', '9', '7', '0' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - }; - -#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY - - template - struct clock_string - { - static std::basic_string name() - { - static const CharT - u[] = - { 's', 't', 'e', 'a', 'd', 'y', '_', 'c', 'l', 'o', 'c', 'k' }; - static const std::basic_string str(u, u + sizeof(u) - / sizeof(u[0])); - return str; - } - static std::basic_string since() - { - const CharT u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 'b', 'o', 'o', 't' }; - const std::basic_string str(u, u + sizeof(u) / sizeof(u[0])); - return str; - } - }; - -#endif - -} // namespace chrono -} // namespace boost - -#ifndef BOOST_CHRONO_HEADER_ONLY -// the suffix header occurs after all of our code: -#include // pops abi_prefix.hpp pragmas -#else -#include -#endif - -#endif // BOOST_CHRONO_SYSTEM_CLOCKS_HPP diff --git a/utils/boost_idb/boost/chrono/thread_clock.hpp b/utils/boost_idb/boost/chrono/thread_clock.hpp deleted file mode 100644 index 207697b4..00000000 --- a/utils/boost_idb/boost/chrono/thread_clock.hpp +++ /dev/null @@ -1,75 +0,0 @@ -// boost/chrono/thread_clock.hpp -----------------------------------------------------------// - -// Copyright 2009-2011 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// See http://www.boost.org/libs/system for documentation. - -#include - -#ifndef BOOST_CHRONO_THREAD_CLOCK_HPP -#define BOOST_CHRONO_THREAD_CLOCK_HPP - -#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK) - -#include -#include -#include -#include -#include - -#ifndef BOOST_CHRONO_HEADER_ONLY -#include // must be the last #include -#endif - -namespace boost { namespace chrono { - -class BOOST_CHRONO_DECL thread_clock { -public: - typedef nanoseconds duration; - typedef duration::rep rep; - typedef duration::period period; - typedef chrono::time_point time_point; - BOOST_STATIC_CONSTEXPR bool is_steady = BOOST_CHRONO_THREAD_CLOCK_IS_STEADY; - - static BOOST_CHRONO_INLINE time_point now( ) BOOST_NOEXCEPT; -#if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING - static BOOST_CHRONO_INLINE time_point now( system::error_code & ec ); -#endif -}; - -template -struct clock_string -{ - static std::basic_string name() - { - static const CharT u[] = - { 't', 'h', 'r', 'e', 'a', 'd', '_', - 'c', 'l','o', 'c', 'k'}; - static const std::basic_string str(u, u + sizeof(u)/sizeof(u[0])); - return str; - } - static std::basic_string since() - { - const CharT u[] = - { ' ', 's', 'i', 'n', 'c', 'e', ' ', 't', 'h', 'r', 'e', 'a', 'd', ' ', 's', 't', 'a', 'r', 't', '-', 'u', 'p'}; - const std::basic_string str(u, u + sizeof(u)/sizeof(u[0])); - return str; - } -}; - -} // namespace chrono -} // namespace boost - - -#ifndef BOOST_CHRONO_HEADER_ONLY -#include // pops abi_prefix.hpp pragmas -#else -#include -#endif - -#endif - -#endif // BOOST_CHRONO_THREAD_CLOCK_HPP diff --git a/utils/boost_idb/boost/chrono/time_point.hpp b/utils/boost_idb/boost/chrono/time_point.hpp deleted file mode 100644 index 6449fac6..00000000 --- a/utils/boost_idb/boost/chrono/time_point.hpp +++ /dev/null @@ -1,380 +0,0 @@ -// duration.hpp --------------------------------------------------------------// - -// Copyright 2008 Howard Hinnant -// Copyright 2008 Beman Dawes -// Copyright 2009-2012 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -/* - -This code was derived by Beman Dawes from Howard Hinnant's time2_demo prototype. -Many thanks to Howard for making his code available under the Boost license. -The original code was modified to conform to Boost conventions and to section -20.9 Time utilities [time] of the C++ committee's working paper N2798. -See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf. - -time2_demo contained this comment: - - Much thanks to Andrei Alexandrescu, - Walter Brown, - Peter Dimov, - Jeff Garland, - Terry Golubiewski, - Daniel Krugler, - Anthony Williams. -*/ - - -#ifndef BOOST_CHRONO_TIME_POINT_HPP -#define BOOST_CHRONO_TIME_POINT_HPP - -#include -#include - -#ifndef BOOST_CHRONO_HEADER_ONLY -// this must occur after all of the includes and before any code appears: -#include // must be the last #include -#endif - -//----------------------------------------------------------------------------// -// // -// 20.9 Time utilities [time] // -// synopsis // -// // -//----------------------------------------------------------------------------// - -namespace boost { -namespace chrono { - - template - class time_point; - - -} // namespace chrono - - -// common_type trait specializations - -template - struct common_type, - chrono::time_point >; - - -//----------------------------------------------------------------------------// -// 20.9.2.3 Specializations of common_type [time.traits.specializations] // -//----------------------------------------------------------------------------// - - -template -struct common_type, - chrono::time_point > -{ - typedef chrono::time_point::type> type; -}; - - - -namespace chrono { - - // time_point arithmetic - template - inline BOOST_CONSTEXPR - time_point >::type> - operator+( - const time_point& lhs, - const duration& rhs); - template - inline BOOST_CONSTEXPR - time_point, Duration2>::type> - operator+( - const duration& lhs, - const time_point& rhs); - template - inline BOOST_CONSTEXPR - time_point >::type> - operator-( - const time_point& lhs, - const duration& rhs); - template - inline BOOST_CONSTEXPR - typename common_type::type - operator-( - const time_point& lhs, - const time_point& rhs); - - // time_point comparisons - template - inline BOOST_CONSTEXPR - bool operator==( - const time_point& lhs, - const time_point& rhs); - template - inline BOOST_CONSTEXPR - bool operator!=( - const time_point& lhs, - const time_point& rhs); - template - inline BOOST_CONSTEXPR - bool operator< ( - const time_point& lhs, - const time_point& rhs); - template - inline BOOST_CONSTEXPR - bool operator<=( - const time_point& lhs, - const time_point& rhs); - template - inline BOOST_CONSTEXPR - bool operator> ( - const time_point& lhs, - const time_point& rhs); - template - inline BOOST_CONSTEXPR - bool operator>=( - const time_point& lhs, - const time_point& rhs); - - // time_point_cast - template - inline BOOST_CONSTEXPR - time_point time_point_cast(const time_point& t); - -//----------------------------------------------------------------------------// -// // -// 20.9.4 Class template time_point [time.point] // -// // -//----------------------------------------------------------------------------// - - template - class time_point - { - BOOST_CHRONO_STATIC_ASSERT(boost::chrono::detail::is_duration::value, - BOOST_CHRONO_SECOND_TEMPLATE_PARAMETER_OF_TIME_POINT_MUST_BE_A_BOOST_CHRONO_DURATION, (Duration)); - public: - typedef Clock clock; - typedef Duration duration; - typedef typename duration::rep rep; - typedef typename duration::period period; - typedef Duration difference_type; - - private: - duration d_; - - public: - BOOST_FORCEINLINE BOOST_CONSTEXPR - time_point() : d_(duration::zero()) - {} - BOOST_FORCEINLINE BOOST_CONSTEXPR - explicit time_point(const duration& d) - : d_(d) - {} - - // conversions - template - BOOST_FORCEINLINE BOOST_CONSTEXPR - time_point(const time_point& t - , typename boost::enable_if - < - boost::is_convertible - >::type* = 0 - ) - : d_(t.time_since_epoch()) - { - } - // observer - - BOOST_CONSTEXPR - duration time_since_epoch() const - { - return d_; - } - - // arithmetic - -#ifdef BOOST_CHRONO_EXTENSIONS - BOOST_CONSTEXPR - time_point operator+() const {return *this;} - BOOST_CONSTEXPR - time_point operator-() const {return time_point(-d_);} - time_point& operator++() {++d_; return *this;} - time_point operator++(int) {return time_point(d_++);} - time_point& operator--() {--d_; return *this;} - time_point operator--(int) {return time_point(d_--);} - - time_point& operator+=(const rep& r) {d_ += duration(r); return *this;} - time_point& operator-=(const rep& r) {d_ -= duration(r); return *this;} - -#endif - - time_point& operator+=(const duration& d) {d_ += d; return *this;} - time_point& operator-=(const duration& d) {d_ -= d; return *this;} - - // special values - - static BOOST_CHRONO_LIB_CONSTEXPR time_point - min BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return time_point((duration::min)()); - } - static BOOST_CHRONO_LIB_CONSTEXPR time_point - max BOOST_PREVENT_MACRO_SUBSTITUTION () - { - return time_point((duration::max)()); - } - }; - -//----------------------------------------------------------------------------// -// 20.9.4.5 time_point non-member arithmetic [time.point.nonmember] // -//----------------------------------------------------------------------------// - - // time_point operator+(time_point x, duration y); - - template - inline BOOST_CONSTEXPR - time_point >::type> - operator+(const time_point& lhs, - const duration& rhs) - { - typedef typename common_type >::type CDuration; - typedef time_point< - Clock, - CDuration - > TimeResult; - return TimeResult(lhs.time_since_epoch() + CDuration(rhs)); - } - - // time_point operator+(duration x, time_point y); - - template - inline BOOST_CONSTEXPR - time_point, Duration2>::type> - operator+(const duration& lhs, - const time_point& rhs) - { - return rhs + lhs; - } - - // time_point operator-(time_point x, duration y); - - template - inline BOOST_CONSTEXPR - time_point >::type> - operator-(const time_point& lhs, - const duration& rhs) - { - return lhs + (-rhs); - } - - // duration operator-(time_point x, time_point y); - - template - inline BOOST_CONSTEXPR - typename common_type::type - operator-(const time_point& lhs, - const time_point& rhs) - { - return lhs.time_since_epoch() - rhs.time_since_epoch(); - } - -//----------------------------------------------------------------------------// -// 20.9.4.6 time_point comparisons [time.point.comparisons] // -//----------------------------------------------------------------------------// - - // time_point == - - template - inline BOOST_CONSTEXPR - bool - operator==(const time_point& lhs, - const time_point& rhs) - { - return lhs.time_since_epoch() == rhs.time_since_epoch(); - } - - // time_point != - - template - inline BOOST_CONSTEXPR - bool - operator!=(const time_point& lhs, - const time_point& rhs) - { - return !(lhs == rhs); - } - - // time_point < - - template - inline BOOST_CONSTEXPR - bool - operator<(const time_point& lhs, - const time_point& rhs) - { - return lhs.time_since_epoch() < rhs.time_since_epoch(); - } - - // time_point > - - template - inline BOOST_CONSTEXPR - bool - operator>(const time_point& lhs, - const time_point& rhs) - { - return rhs < lhs; - } - - // time_point <= - - template - inline BOOST_CONSTEXPR - bool - operator<=(const time_point& lhs, - const time_point& rhs) - { - return !(rhs < lhs); - } - - // time_point >= - - template - inline BOOST_CONSTEXPR - bool - operator>=(const time_point& lhs, - const time_point& rhs) - { - return !(lhs < rhs); - } - -//----------------------------------------------------------------------------// -// 20.9.4.7 time_point_cast [time.point.cast] // -//----------------------------------------------------------------------------// - - template - inline BOOST_CONSTEXPR - time_point - time_point_cast(const time_point& t) - { - return time_point( - duration_cast(t.time_since_epoch())); - } - -} // namespace chrono -} // namespace boost - -#ifndef BOOST_CHRONO_HEADER_ONLY -// the suffix header occurs after all of our code: -#include // pops abi_prefix.hpp pragmas -#endif - -#endif // BOOST_CHRONO_TIME_POINT_HPP diff --git a/utils/boost_idb/boost/chrono/typeof/boost/chrono/chrono.hpp b/utils/boost_idb/boost/chrono/typeof/boost/chrono/chrono.hpp deleted file mode 100644 index 0b0d2748..00000000 --- a/utils/boost_idb/boost/chrono/typeof/boost/chrono/chrono.hpp +++ /dev/null @@ -1,32 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Vicente J. Botet Escriba 20010. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or -// copy at http://www.boost.org/LICENSE_1_0.txt) -// -// Based on the unique_threader/unique_joiner design from of Kevlin Henney (n1883) -// -// See http://www.boost.org/libs/chrono for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CHRONO_TYPEOF_CHRONO_HPP -#define BOOST_CHRONO_TYPEOF_CHRONO_HPP - -#include -#include - -#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() - -BOOST_TYPEOF_REGISTER_TEMPLATE(boost::chrono::duration, (typename)(typename)) -BOOST_TYPEOF_REGISTER_TEMPLATE(boost::chrono::time_point, (typename)(typename)) -#if 0 -BOOST_TYPEOF_REGISTER_TYPE(boost::chrono::system_clock) -#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY -BOOST_TYPEOF_REGISTER_TYPE(boost::chrono::steady_clock) -#endif -BOOST_TYPEOF_REGISTER_TYPE(boost::chrono::high_resolution_clock) - -#endif -#endif diff --git a/utils/boost_idb/boost/chrono/typeof/boost/ratio.hpp b/utils/boost_idb/boost/chrono/typeof/boost/ratio.hpp deleted file mode 100644 index d61ce244..00000000 --- a/utils/boost_idb/boost/chrono/typeof/boost/ratio.hpp +++ /dev/null @@ -1,24 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Vicente J. Botet Escriba 20010. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or -// copy at http://www.boost.org/LICENSE_1_0.txt) -// -// Based on the unique_threader/unique_joiner design from of Kevlin Henney (n1883) -// -// See http://www.boost.org/libs/chrono for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CHRONO_TYPEOF_RATIO_HPP -#define BOOST_CHRONO_TYPEOF_RATIO_HPP - -#include -#include - -#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() - -BOOST_TYPEOF_REGISTER_TEMPLATE(boost::ratio, (boost::intmax_t)(boost::intmax_t)) - -#endif diff --git a/utils/boost_idb/boost/circular_buffer.hpp b/utils/boost_idb/boost/circular_buffer.hpp new file mode 100644 index 00000000..13cc94fe --- /dev/null +++ b/utils/boost_idb/boost/circular_buffer.hpp @@ -0,0 +1,74 @@ +// Circular buffer library header file. + +// Copyright (c) 2003-2008 Jan Gaspar + +// Use, modification, and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// See www.boost.org/libs/circular_buffer for documentation. + +#if !defined(BOOST_CIRCULAR_BUFFER_HPP) +#define BOOST_CIRCULAR_BUFFER_HPP + +#if defined(_MSC_VER) && _MSC_VER >= 1200 + #pragma once +#endif + +#include +#include + +// BOOST_CB_ENABLE_DEBUG: Debug support control. +#if defined(NDEBUG) || defined(BOOST_CB_DISABLE_DEBUG) + #define BOOST_CB_ENABLE_DEBUG 0 +#else + #define BOOST_CB_ENABLE_DEBUG 1 +#endif + +// BOOST_CB_ASSERT: Runtime assertion. +#if BOOST_CB_ENABLE_DEBUG + #include + #define BOOST_CB_ASSERT(Expr) BOOST_ASSERT(Expr) +#else + #define BOOST_CB_ASSERT(Expr) ((void)0) +#endif + +// BOOST_CB_STATIC_ASSERT: Compile time assertion. +#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) + #define BOOST_CB_STATIC_ASSERT(Expr) ((void)0) +#else + #include + #define BOOST_CB_STATIC_ASSERT(Expr) BOOST_STATIC_ASSERT(Expr) +#endif + +// BOOST_CB_IS_CONVERTIBLE: Check if Iterator::value_type is convertible to Type. +#if BOOST_WORKAROUND(__BORLANDC__, <= 0x0550) || BOOST_WORKAROUND(__MWERKS__, <= 0x2407) || \ + BOOST_WORKAROUND(BOOST_MSVC, < 1300) + #define BOOST_CB_IS_CONVERTIBLE(Iterator, Type) ((void)0) +#else + #include + #include + #define BOOST_CB_IS_CONVERTIBLE(Iterator, Type) \ + BOOST_CB_STATIC_ASSERT((is_convertible::value_type, Type>::value)) +#endif + +// BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS: +// Check if the STL provides templated iterator constructors for its containers. +#if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS) + #define BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS BOOST_CB_STATIC_ASSERT(false); +#else + #define BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS ((void)0); +#endif + +#include +#include +#include +#include + +#undef BOOST_CB_ASSERT_TEMPLATED_ITERATOR_CONSTRUCTORS +#undef BOOST_CB_IS_CONVERTIBLE +#undef BOOST_CB_STATIC_ASSERT +#undef BOOST_CB_ASSERT +#undef BOOST_CB_ENABLE_DEBUG + +#endif // #if !defined(BOOST_CIRCULAR_BUFFER_HPP) diff --git a/utils/boost_idb/boost/circular_buffer_fwd.hpp b/utils/boost_idb/boost/circular_buffer_fwd.hpp new file mode 100644 index 00000000..6fdb43e0 --- /dev/null +++ b/utils/boost_idb/boost/circular_buffer_fwd.hpp @@ -0,0 +1,43 @@ +// Forward declaration of the circular buffer and its adaptor. + +// Copyright (c) 2003-2008 Jan Gaspar + +// Use, modification, and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// See www.boost.org/libs/circular_buffer for documentation. + +#if !defined(BOOST_CIRCULAR_BUFFER_FWD_HPP) +#define BOOST_CIRCULAR_BUFFER_FWD_HPP + +#if defined(_MSC_VER) && _MSC_VER >= 1200 + #pragma once +#endif + +#include +#if !defined(BOOST_NO_STD_ALLOCATOR) + #include +#else + #include +#endif + +namespace boost { + +#if !defined(BOOST_NO_STD_ALLOCATOR) + #define BOOST_CB_DEFAULT_ALLOCATOR(T) std::allocator +#else + #define BOOST_CB_DEFAULT_ALLOCATOR(T) BOOST_DEDUCED_TYPENAME std::vector::allocator_type +#endif + +template +class circular_buffer; + +template +class circular_buffer_space_optimized; + +#undef BOOST_CB_DEFAULT_ALLOCATOR + +} // namespace boost + +#endif // #if !defined(BOOST_CIRCULAR_BUFFER_FWD_HPP) diff --git a/utils/boost_idb/boost/concept/detail/backward_compatibility.hpp b/utils/boost_idb/boost/concept/detail/backward_compatibility.hpp index 66d573ef..88d59215 100644 --- a/utils/boost_idb/boost/concept/detail/backward_compatibility.hpp +++ b/utils/boost_idb/boost/concept/detail/backward_compatibility.hpp @@ -8,7 +8,7 @@ namespace boost { namespace concepts {} -# if defined(BOOST_HAS_CONCEPTS) && !defined(BOOST_CONCEPT_NO_BACKWARD_KEYWORD) +# if !defined(BOOST_NO_CONCEPTS) && !defined(BOOST_CONCEPT_NO_BACKWARD_KEYWORD) namespace concept = concepts; # endif } // namespace boost::concept diff --git a/utils/boost_idb/boost/concept_check.hpp b/utils/boost_idb/boost/concept_check.hpp index bf5a2af7..58bd8b2b 100644 --- a/utils/boost_idb/boost/concept_check.hpp +++ b/utils/boost_idb/boost/concept_check.hpp @@ -38,14 +38,14 @@ namespace boost // // Backward compatibility // - + template inline void function_requires(Model* = 0) { BOOST_CONCEPT_ASSERT((Model)); - } + } template inline void ignore_unused_variable_warning(T const&) {} - + # define BOOST_CLASS_REQUIRE(type_var, ns, concept) \ BOOST_CONCEPT_ASSERT((ns::concept)) @@ -58,21 +58,20 @@ namespace boost # define BOOST_CLASS_REQUIRE4(tv1, tv2, tv3, tv4, ns, concept) \ BOOST_CONCEPT_ASSERT((ns::concept)) - + // // Begin concept definitions // BOOST_concept(Integer, (T)) { BOOST_CONCEPT_USAGE(Integer) - { + { x.error_type_must_be_an_integer_type(); } private: T x; }; - template <> struct Integer {}; template <> struct Integer {}; template <> struct Integer {}; template <> struct Integer {}; @@ -90,7 +89,7 @@ namespace boost # endif BOOST_concept(SignedInteger,(T)) { - BOOST_CONCEPT_USAGE(SignedInteger) { + BOOST_CONCEPT_USAGE(SignedInteger) { x.error_type_must_be_a_signed_integer_type(); } private: @@ -104,16 +103,16 @@ namespace boost template <> struct SignedInteger< ::boost::long_long_type> {}; # elif defined(BOOST_HAS_MS_INT64) template <> struct SignedInteger<__int64> {}; -# endif +# endif BOOST_concept(UnsignedInteger,(T)) { - BOOST_CONCEPT_USAGE(UnsignedInteger) { + BOOST_CONCEPT_USAGE(UnsignedInteger) { x.error_type_must_be_an_unsigned_integer_type(); } private: T x; }; - + template <> struct UnsignedInteger {}; template <> struct UnsignedInteger {}; template <> struct UnsignedInteger {}; @@ -139,24 +138,23 @@ namespace boost { BOOST_CONCEPT_USAGE(Assignable) { #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL - a = b; // require assignment operator + a = a; // require assignment operator #endif - const_constraints(b); + const_constraints(a); } private: - void const_constraints(const TT& x) { + void const_constraints(const TT& b) { #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL - a = x; // const required for argument to assignment + a = b; // const required for argument to assignment #else - ignore_unused_variable_warning(x); + ignore_unused_variable_warning(b); #endif } private: TT a; - TT b; }; - + BOOST_concept(CopyConstructible,(TT)) { BOOST_CONCEPT_USAGE(CopyConstructible) { @@ -184,23 +182,22 @@ namespace boost BOOST_concept(SGIAssignable,(TT)) { BOOST_CONCEPT_USAGE(SGIAssignable) { - TT c(a); + TT b(a); #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL - a = b; // require assignment operator + a = a; // require assignment operator #endif - const_constraints(b); - ignore_unused_variable_warning(c); + const_constraints(a); + ignore_unused_variable_warning(b); } private: - void const_constraints(const TT& x) { - TT c(x); + void const_constraints(const TT& b) { + TT c(b); #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL - a = x; // const required for argument to assignment + a = b; // const required for argument to assignment #endif ignore_unused_variable_warning(c); } TT a; - TT b; }; #if (defined _MSC_VER) # pragma warning( pop ) @@ -302,7 +299,7 @@ namespace boost BOOST_concept(Generator,(Func)(Return)) { BOOST_CONCEPT_USAGE(Generator) { test(is_void()); } - + private: void test(boost::mpl::false_) { @@ -315,22 +312,22 @@ namespace boost { f(); } - + Func f; }; BOOST_concept(UnaryFunction,(Func)(Return)(Arg)) { BOOST_CONCEPT_USAGE(UnaryFunction) { test(is_void()); } - + private: void test(boost::mpl::false_) { f(arg); // "priming the pump" this way keeps msvc6 happy (ICE) Return r = f(arg); - ignore_unused_variable_warning(r); + ignore_unused_variable_warning(r); } - + void test(boost::mpl::true_) { f(arg); @@ -359,21 +356,12 @@ namespace boost Return r = f(first, second); // require operator() (void)r; } - + void test(boost::mpl::true_) { f(first,second); } - -#if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ - && BOOST_WORKAROUND(__GNUC__, > 3))) - // Declare a dummy constructor to make gcc happy. - // It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type. - // (warning: non-static reference "const double& boost::BinaryFunction::arg" - // in class without a constructor [-Wuninitialized]) - BinaryFunction(); -#endif - + Func f; First first; Second second; @@ -385,15 +373,6 @@ namespace boost require_boolean_expr(f(arg)); // require operator() returning bool } private: -#if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ - && BOOST_WORKAROUND(__GNUC__, > 3))) - // Declare a dummy constructor to make gcc happy. - // It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type. - // (warning: non-static reference "const double& boost::UnaryPredicate::arg" - // in class without a constructor [-Wuninitialized]) - UnaryPredicate(); -#endif - Func f; Arg arg; }; @@ -404,14 +383,6 @@ namespace boost require_boolean_expr(f(a, b)); // require operator() returning bool } private: -#if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ - && BOOST_WORKAROUND(__GNUC__, > 3))) - // Declare a dummy constructor to make gcc happy. - // It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type. - // (warning: non-static reference "const double& boost::BinaryPredicate::arg" - // in class without a constructor [-Wuninitialized]) - BinaryPredicate(); -#endif Func f; First a; Second b; @@ -421,7 +392,7 @@ namespace boost BOOST_concept(Const_BinaryPredicate,(Func)(First)(Second)) : BinaryPredicate { - BOOST_CONCEPT_USAGE(Const_BinaryPredicate) { + BOOST_CONCEPT_USAGE(Const_BinaryPredicate) { const_constraints(f); } private: @@ -429,15 +400,6 @@ namespace boost // operator() must be a const member function require_boolean_expr(fun(a, b)); } -#if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ - && BOOST_WORKAROUND(__GNUC__, > 3))) - // Declare a dummy constructor to make gcc happy. - // It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type. - // (warning: non-static reference "const double& boost::Const_BinaryPredicate::arg" - // in class without a constructor [-Wuninitialized]) - Const_BinaryPredicate(); -#endif - Func f; First a; Second b; @@ -447,7 +409,7 @@ namespace boost : Generator { typedef typename Func::result_type result_type; - + BOOST_CONCEPT_USAGE(AdaptableGenerator) { BOOST_CONCEPT_ASSERT((Convertible)); @@ -478,7 +440,7 @@ namespace boost typedef typename Func::first_argument_type first_argument_type; typedef typename Func::second_argument_type second_argument_type; typedef typename Func::result_type result_type; - + ~AdaptableBinaryFunction() { BOOST_CONCEPT_ASSERT((Convertible)); @@ -516,7 +478,7 @@ namespace boost { BOOST_CONCEPT_ASSERT((SignedInteger)); BOOST_CONCEPT_ASSERT((Convertible)); - + TT j(i); (void)*i; // require dereference operator ++j; // require preincrement operator @@ -530,7 +492,7 @@ namespace boost : Assignable { BOOST_CONCEPT_USAGE(OutputIterator) { - + ++i; // require preincrement operator i++; // require postincrement operator *i++ = t; // require postincrement and assignment @@ -549,11 +511,11 @@ namespace boost BOOST_DEDUCED_TYPENAME ForwardIterator::iterator_category , std::forward_iterator_tag >)); - + typename InputIterator::reference r = *i; ignore_unused_variable_warning(r); } - + private: TT i; }; @@ -615,7 +577,7 @@ namespace boost n = i - j; // require difference operator (void)i[n]; // require element access operator } - + private: TT a, b; TT i, j; @@ -653,7 +615,7 @@ namespace boost BOOST_CONCEPT_ASSERT((InputIterator)); const_constraints(c); } - + private: void const_constraints(const C& cc) { i = cc.begin(); @@ -674,19 +636,19 @@ namespace boost typedef typename C::reference reference; typedef typename C::iterator iterator; typedef typename C::pointer pointer; - + BOOST_CONCEPT_USAGE(Mutable_Container) { BOOST_CONCEPT_ASSERT(( Assignable)); - + BOOST_CONCEPT_ASSERT((InputIterator)); - + i = c.begin(); i = c.end(); c.swap(c2); } - + private: iterator i; C c, c2; @@ -702,7 +664,7 @@ namespace boost typename ForwardContainer::const_iterator >)); } - }; + }; BOOST_concept(Mutable_ForwardContainer,(C)) : ForwardContainer @@ -715,7 +677,7 @@ namespace boost typename Mutable_ForwardContainer::iterator >)); } - }; + }; BOOST_concept(ReversibleContainer,(C)) : ForwardContainer @@ -729,9 +691,9 @@ namespace boost BOOST_CONCEPT_ASSERT(( BidirectionalIterator< typename ReversibleContainer::const_iterator>)); - + BOOST_CONCEPT_ASSERT((BidirectionalIterator)); - + const_constraints(c); } private: @@ -748,17 +710,17 @@ namespace boost , ReversibleContainer { typedef typename C::reverse_iterator reverse_iterator; - + BOOST_CONCEPT_USAGE(Mutable_ReversibleContainer) { typedef typename Mutable_ForwardContainer::iterator iterator; BOOST_CONCEPT_ASSERT((Mutable_BidirectionalIterator)); BOOST_CONCEPT_ASSERT((Mutable_BidirectionalIterator)); - + reverse_iterator i = c.rbegin(); i = c.rend(); } - private: + private: C c; }; @@ -774,7 +736,7 @@ namespace boost RandomAccessIterator< typename RandomAccessContainer::const_iterator >)); - + const_constraints(c); } private: @@ -783,7 +745,7 @@ namespace boost const_reference r = cc[n]; ignore_unused_variable_warning(r); } - + C c; size_type n; }; @@ -799,11 +761,11 @@ namespace boost { BOOST_CONCEPT_ASSERT((Mutable_RandomAccessIterator)); BOOST_CONCEPT_ASSERT((Mutable_RandomAccessIterator)); - + typename self::reference r = c[i]; ignore_unused_variable_warning(r); } - + private: typename Mutable_ReversibleContainer::size_type i; C c; @@ -819,7 +781,7 @@ namespace boost { BOOST_CONCEPT_USAGE(Sequence) { - S + S c(n), c2(n, t), c3(first, last); @@ -844,7 +806,7 @@ namespace boost typename Sequence::const_reference r = c.front(); ignore_unused_variable_warning(r); } - + typename S::value_type t; typename S::size_type n; typename S::value_type* first, *last; @@ -903,11 +865,11 @@ namespace boost c.erase(r.first, r.second); const_constraints(c); BOOST_CONCEPT_ASSERT((BinaryPredicate)); - + typedef typename AssociativeContainer::value_type value_type_; BOOST_CONCEPT_ASSERT((BinaryPredicate)); } - + // Redundant with the base concept, but it helps below. typedef typename C::const_iterator const_iterator; private: @@ -933,7 +895,7 @@ namespace boost BOOST_CONCEPT_USAGE(UniqueAssociativeContainer) { C c(first, last); - + pos_flag = c.insert(t); c.insert(first, last); @@ -951,7 +913,7 @@ namespace boost BOOST_CONCEPT_USAGE(MultipleAssociativeContainer) { C c(first, last); - + pos = c.insert(t); c.insert(first, last); @@ -994,7 +956,7 @@ namespace boost { BOOST_CONCEPT_USAGE(SortedAssociativeContainer) { - C + C c(kc), c2(first, last), c3(first, last, kc); @@ -1002,15 +964,15 @@ namespace boost p = c.upper_bound(k); p = c.lower_bound(k); r = c.equal_range(k); - + c.insert(p, t); - + ignore_unused_variable_warning(c); ignore_unused_variable_warning(c2); ignore_unused_variable_warning(c3); const_constraints(c); } - + void const_constraints(const C& c) { kc = c.key_comp(); @@ -1020,7 +982,7 @@ namespace boost cp = c.lower_bound(k); cr = c.equal_range(k); } - + private: typename C::key_compare kc; typename C::value_compare vc; @@ -1052,11 +1014,11 @@ namespace boost c.swap(c); } - void const_constraints(const C& cc) { - ci = cc.begin(); - ci = cc.end(); - n = cc.size(); - b = cc.empty(); + void const_constraints(const C& c) { + ci = c.begin(); + ci = c.end(); + n = c.size(); + b = c.empty(); } private: diff --git a/utils/boost_idb/boost/concept_check/borland.hpp b/utils/boost_idb/boost/concept_check/borland.hpp deleted file mode 100644 index 107926bb..00000000 --- a/utils/boost_idb/boost/concept_check/borland.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright David Abrahams 2006. Distributed under the Boost -// Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_CONCEPT_CHECK_BORLAND_DWA2006429_HPP -# define BOOST_CONCEPT_CHECK_BORLAND_DWA2006429_HPP - -namespace boost { - -template -struct concept_check; - -template -struct concept_check -{ - enum { instantiate = sizeof((((Model*)0)->~Model()), 3) }; -}; - -# define BOOST_CONCEPT_ASSERT( ModelInParens ) \ - enum { BOOST_PP_CAT(boost_concept_check,__LINE__) = \ - boost::concept_check::instantiate \ - } - -} // namespace boost::concept_checking - -#endif // BOOST_CONCEPT_CHECK_BORLAND_DWA2006429_HPP diff --git a/utils/boost_idb/boost/concept_check/general.hpp b/utils/boost_idb/boost/concept_check/general.hpp deleted file mode 100644 index cd09fb04..00000000 --- a/utils/boost_idb/boost/concept_check/general.hpp +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright David Abrahams 2006. Distributed under the Boost -// Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_CONCEPT_CHECK_MSVC_DWA2006429_HPP -# define BOOST_CONCEPT_CHECK_MSVC_DWA2006429_HPP - -# ifdef BOOST_OLD_CONCEPT_SUPPORT -# include -# include -# endif - - -// This implementation works on GCC and Comeau, but has actually been -// fairly carefully tuned to work on GCC versions starting with -// gcc-2.95.x. If you're trying to get an additional compiler to pass -// the tests you might consider breaking out a separate gcc.hpp and -// starting over on the general case. -namespace boost -{ - namespace concept_checking - { - template struct instantiate {}; - } - - template struct concept_check_; - - template - void concept_check_failed() - { - ((Model*)0)->~Model(); - } - - template - struct concept_check - { - concept_checking::instantiate > x; - enum { instantiate = 1 }; - }; - -# ifdef BOOST_OLD_CONCEPT_SUPPORT - - template - void constraint_check_failed() - { - ((Model*)0)->constraints(); - } - - template - struct constraint_check - { - concept_checking::instantiate > x; - enum { instantiate = 1 }; - }; - - template - struct concept_check_ - : mpl::if_c< - concept_checking::has_constraints::value - , constraint_check - , concept_check - >::type - {}; - -# else - - template - struct concept_check_ - : concept_check - {}; - -# endif - - // Usage, in class or function context: - // - // BOOST_CONCEPT_ASSERT((UnaryFunctionConcept)); -# define BOOST_CONCEPT_ASSERT( ModelInParens ) \ - enum { BOOST_PP_CAT(boost_concept_check,__LINE__) = \ - ::boost::concept_check_::instantiate \ - } -} - -#endif // BOOST_CONCEPT_CHECK_MSVC_DWA2006429_HPP diff --git a/utils/boost_idb/boost/concept_check/has_constraints.hpp b/utils/boost_idb/boost/concept_check/has_constraints.hpp deleted file mode 100644 index e19f664f..00000000 --- a/utils/boost_idb/boost/concept_check/has_constraints.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright David Abrahams 2006. Distributed under the Boost -// Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_CONCEPT_CHECK_HAS_CONSTRAINTS_DWA2006429_HPP -# define BOOST_CONCEPT_CHECK_HAS_CONSTRAINTS_DWA2006429_HPP - -namespace boost { namespace concept_checking { - -// Here we implement the "metafunction" that detects whether a -// constraints metafunction exists -typedef char yes; -typedef char (&no)[2]; - -template -struct wrap_constraints {}; - -template -inline yes has_constraints_(Model*, wrap_constraints* = 0); -inline no has_constraints_(...); - -template -struct has_constraints -{ - BOOST_STATIC_CONSTANT( - bool - , value = sizeof( concept_checking::has_constraints_((Model*)0) ) == 1 ); -}; - -}} // namespace boost::concept_checking - -#endif // BOOST_CONCEPT_CHECK_HAS_CONSTRAINTS_DWA2006429_HPP diff --git a/utils/boost_idb/boost/concept_check/msvc.hpp b/utils/boost_idb/boost/concept_check/msvc.hpp deleted file mode 100644 index 3968469a..00000000 --- a/utils/boost_idb/boost/concept_check/msvc.hpp +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright David Abrahams 2006. Distributed under the Boost -// Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_CONCEPT_CHECK_MSVC_DWA2006429_HPP -# define BOOST_CONCEPT_CHECK_MSVC_DWA2006429_HPP - -# ifdef BOOST_OLD_CONCEPT_SUPPORT -# include -# include -# endif - - -namespace boost -{ - namespace concept_checking - { - template - struct concept_check_ - { - virtual void failed(Model* x) - { - x->~Model(); - } - }; - } - -# ifdef BOOST_OLD_CONCEPT_SUPPORT - - namespace concept_checking - { - template - struct constraint_check - { - virtual void failed(Model* x) - { - x->constraints(); - } - }; - } - - template - struct concept_check - : mpl::if_c< - concept_checking::has_constraints::value - , concept_checking::constraint_check - , concept_checking::concept_check_ - >::type - {}; - -# else - - template - struct concept_check - : concept_checking::concept_check_ - {}; - -# endif - -# if BOOST_WORKAROUND(BOOST_MSVC, == 1310) - - // - // The iterator library sees some really strange errors unless we - // use partial specialization to extract the model type with - // msvc-7.1 - // - template - struct concept_check - : concept_check - { }; - -# define BOOST_CONCEPT_ASSERT( ModelInParens ) \ - enum { BOOST_PP_CAT(boost_concept_check,__LINE__) = \ - sizeof(::boost::concept_check) \ - } - -# else - - template - concept_check - concept_check_(void(*)(Model)); - -# define BOOST_CONCEPT_ASSERT( ModelInParens ) \ - enum { BOOST_PP_CAT(boost_concept_check,__LINE__) = \ - sizeof(::boost::concept_check_((void(*) ModelInParens)0)) \ - } - -# endif -} - -#endif // BOOST_CONCEPT_CHECK_MSVC_DWA2006429_HPP diff --git a/utils/boost_idb/boost/config.hpp b/utils/boost_idb/boost/config.hpp index 6ec3645c..055a2785 100644 --- a/utils/boost_idb/boost/config.hpp +++ b/utils/boost_idb/boost/config.hpp @@ -1,6 +1,6 @@ // Boost config.hpp configuration header file ------------------------------// -// (C) Copyright John Maddock 2002. +// (C) Copyright John Maddock 2002. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -36,7 +36,7 @@ #endif // if we don't have a std library config set, try and find one: -#if !defined(BOOST_STDLIB_CONFIG) && !defined(BOOST_NO_STDLIB_CONFIG) && !defined(BOOST_NO_CONFIG) && defined(__cplusplus) +#if !defined(BOOST_STDLIB_CONFIG) && !defined(BOOST_NO_STDLIB_CONFIG) && !defined(BOOST_NO_CONFIG) # include #endif // if we have a std library config, include it now: @@ -56,8 +56,15 @@ // get config suffix code: #include -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - #endif // BOOST_CONFIG_HPP + + + + + + + + + + + diff --git a/utils/boost_idb/boost/config/auto_link.hpp b/utils/boost_idb/boost/config/auto_link.hpp index 13cbad43..e562caff 100644 --- a/utils/boost_idb/boost/config/auto_link.hpp +++ b/utils/boost_idb/boost/config/auto_link.hpp @@ -60,14 +60,14 @@ BOOST_LIB_THREAD_OPT: "-mt" for multithread builds, otherwise nothing. BOOST_LIB_RT_OPT: A suffix that indicates the runtime library used, contains one or more of the following letters after - a hyphen: + a hiphen: s static runtime (dynamic if not present). g debug/diagnostic runtime (release if not present). y Python debug/diagnostic runtime (release if not present). d debug build (release if not present). - p STLport build. - n STLport build without its IOStreams. + g debug/diagnostic runtime (release if not present). + p STLPort Build. BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. @@ -114,74 +114,63 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. // select toolset if not defined already: // #ifndef BOOST_LIB_TOOLSET -# if defined(BOOST_MSVC) && (BOOST_MSVC < 1200) - // Note: no compilers before 1200 are supported -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1300) - -# ifdef UNDER_CE - // eVC4: -# define BOOST_LIB_TOOLSET "evc4" -# else - // vc6: -# define BOOST_LIB_TOOLSET "vc6" -# endif - -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1310) - - // vc7: -# define BOOST_LIB_TOOLSET "vc7" +// Note: no compilers before 1200 are supported +#if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1400) - - // vc71: -# define BOOST_LIB_TOOLSET "vc71" +# ifdef UNDER_CE + // vc6: +# define BOOST_LIB_TOOLSET "evc4" +# else + // vc6: +# define BOOST_LIB_TOOLSET "vc6" +# endif -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1500) +#elif defined(BOOST_MSVC) && (BOOST_MSVC == 1300) - // vc80: -# define BOOST_LIB_TOOLSET "vc80" + // vc7: +# define BOOST_LIB_TOOLSET "vc7" -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1600) +#elif defined(BOOST_MSVC) && (BOOST_MSVC == 1310) - // vc90: -# define BOOST_LIB_TOOLSET "vc90" + // vc71: +# define BOOST_LIB_TOOLSET "vc71" -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1700) +#elif defined(BOOST_MSVC) && (BOOST_MSVC == 1400) - // vc10: -# define BOOST_LIB_TOOLSET "vc100" + // vc80: +# define BOOST_LIB_TOOLSET "vc80" -# elif defined(BOOST_MSVC) && (BOOST_MSVC < 1800) +#elif defined(BOOST_MSVC) && (BOOST_MSVC == 1500) - // vc11: -# define BOOST_LIB_TOOLSET "vc110" + // vc90: +# define BOOST_LIB_TOOLSET "vc90" -# elif defined(BOOST_MSVC) +#elif defined(BOOST_MSVC) && (BOOST_MSVC >= 1600) - // vc12: -# define BOOST_LIB_TOOLSET "vc120" + // vc10: +# define BOOST_LIB_TOOLSET "vc100" -# elif defined(__BORLANDC__) +#elif defined(__BORLANDC__) - // CBuilder 6: -# define BOOST_LIB_TOOLSET "bcb" + // CBuilder 6: +# define BOOST_LIB_TOOLSET "bcb" -# elif defined(__ICL) +#elif defined(__ICL) - // Intel C++, no version number: -# define BOOST_LIB_TOOLSET "iw" + // Intel C++, no version number: +# define BOOST_LIB_TOOLSET "iw" -# elif defined(__MWERKS__) && (__MWERKS__ <= 0x31FF ) +#elif defined(__MWERKS__) && (__MWERKS__ <= 0x31FF ) - // Metrowerks CodeWarrior 8.x -# define BOOST_LIB_TOOLSET "cw8" + // Metrowerks CodeWarrior 8.x +# define BOOST_LIB_TOOLSET "cw8" -# elif defined(__MWERKS__) && (__MWERKS__ <= 0x32FF ) +#elif defined(__MWERKS__) && (__MWERKS__ <= 0x32FF ) - // Metrowerks CodeWarrior 9.x -# define BOOST_LIB_TOOLSET "cw9" + // Metrowerks CodeWarrior 9.x +# define BOOST_LIB_TOOLSET "cw9" -# endif +#endif #endif // BOOST_LIB_TOOLSET // @@ -207,11 +196,11 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. # elif defined(_DEBUG)\ && defined(BOOST_DEBUG_PYTHON) && defined(BOOST_LINKING_PYTHON) # define BOOST_LIB_RT_OPT "-gydp" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # elif defined(_DEBUG) # define BOOST_LIB_RT_OPT "-gdp" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # else # define BOOST_LIB_RT_OPT "-p" @@ -227,11 +216,11 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. # elif defined(_DEBUG)\ && defined(BOOST_DEBUG_PYTHON) && defined(BOOST_LINKING_PYTHON) # define BOOST_LIB_RT_OPT "-gydpn" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # elif defined(_DEBUG) # define BOOST_LIB_RT_OPT "-gdpn" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # else # define BOOST_LIB_RT_OPT "-pn" @@ -261,11 +250,11 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. # elif defined(_DEBUG)\ && defined(BOOST_DEBUG_PYTHON) && defined(BOOST_LINKING_PYTHON) # define BOOST_LIB_RT_OPT "-sgydp" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # elif defined(_DEBUG) # define BOOST_LIB_RT_OPT "-sgdp" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # else # define BOOST_LIB_RT_OPT "-sp" @@ -281,11 +270,11 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. # elif defined(_DEBUG)\ && defined(BOOST_DEBUG_PYTHON) && defined(BOOST_LINKING_PYTHON) # define BOOST_LIB_RT_OPT "-sgydpn" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # elif defined(_DEBUG) # define BOOST_LIB_RT_OPT "-sgdpn" -# pragma message("warning: STLport debug versions are built with /D_STLP_DEBUG=1") +# pragma message("warning: STLPort debug versions are built with /D_STLP_DEBUG=1") # error "Build options aren't compatible with pre-built libraries" # else # define BOOST_LIB_RT_OPT "-spn" @@ -318,7 +307,7 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. // sanity check: // #if defined(__STL_DEBUG) || defined(_STLP_DEBUG) -#error "Pre-built versions of the Boost libraries are not provided in STLport-debug form" +#error "Pre-built versions of the Boost libraries are not provided in STLPort-debug form" #endif # ifdef _RTLDLL @@ -375,7 +364,7 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. #ifdef BOOST_AUTO_LINK_TAGGED # pragma comment(lib, BOOST_LIB_PREFIX BOOST_STRINGIZE(BOOST_LIB_NAME) BOOST_LIB_THREAD_OPT BOOST_LIB_RT_OPT ".lib") # ifdef BOOST_LIB_DIAGNOSTIC -# pragma message ("Linking to lib file: " BOOST_LIB_PREFIX BOOST_STRINGIZE(BOOST_LIB_NAME) BOOST_LIB_THREAD_OPT BOOST_LIB_RT_OPT ".lib") +# pragma message ("Linking to lib file: " BOOST_LIB_PREFIX BOOST_STRINGIZE(BOOST_LIB_NAME) "-" BOOST_LIB_TOOLSET BOOST_LIB_THREAD_OPT BOOST_LIB_RT_OPT "-" BOOST_LIB_VERSION ".lib") # endif #elif defined(BOOST_AUTO_LINK_NOMANGLE) # pragma comment(lib, BOOST_STRINGIZE(BOOST_LIB_NAME) ".lib") @@ -425,5 +414,7 @@ BOOST_LIB_VERSION: The Boost version, in the form x_y, for Boost version x.y. #if defined(BOOST_DYN_LINK) # undef BOOST_DYN_LINK #endif - +#if defined(BOOST_AUTO_LINK_NOMANGLE) +# undef BOOST_AUTO_LINK_NOMANGLE +#endif diff --git a/utils/boost_idb/boost/config/compiler/borland.hpp b/utils/boost_idb/boost/config/compiler/borland.hpp index a8f5baae..a989fd63 100644 --- a/utils/boost_idb/boost/config/compiler/borland.hpp +++ b/utils/boost_idb/boost/config/compiler/borland.hpp @@ -47,7 +47,7 @@ # define BOOST_NO_OPERATORS_IN_NAMESPACE # endif // Variadic macros do not exist for C++ Builder versions 5 and below -#define BOOST_NO_CXX11_VARIADIC_MACROS +#define BOOST_NO_VARIADIC_MACROS # endif // Version 5.51 and below: @@ -56,13 +56,8 @@ # define BOOST_NO_CV_VOID_SPECIALIZATIONS # define BOOST_NO_DEDUCED_TYPENAME // workaround for missing WCHAR_MAX/WCHAR_MIN: -#ifdef __cplusplus #include #include -#else -#include -#include -#endif // __cplusplus #ifndef WCHAR_MAX # define WCHAR_MAX 0xffff #endif @@ -74,7 +69,7 @@ // Borland C++ Builder 6 and below: #if (__BORLANDC__ <= 0x564) -# if defined(NDEBUG) && defined(__cplusplus) +# ifdef NDEBUG // fix broken so that Boost.test works: # include # undef strcmp @@ -150,14 +145,14 @@ // C++0x Macros: // #if !defined( BOOST_CODEGEAR_0X_SUPPORT ) || (__BORLANDC__ < 0x610) -# define BOOST_NO_CXX11_CHAR16_T -# define BOOST_NO_CXX11_CHAR32_T -# define BOOST_NO_CXX11_DECLTYPE -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -# define BOOST_NO_CXX11_EXTERN_TEMPLATE -# define BOOST_NO_CXX11_RVALUE_REFERENCES -# define BOOST_NO_CXX11_SCOPED_ENUMS -# define BOOST_NO_CXX11_STATIC_ASSERT +# define BOOST_NO_CHAR16_T +# define BOOST_NO_CHAR32_T +# define BOOST_NO_DECLTYPE +# define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +# define BOOST_NO_EXTERN_TEMPLATE +# define BOOST_NO_RVALUE_REFERENCES +# define BOOST_NO_SCOPED_ENUMS +# define BOOST_NO_STATIC_ASSERT #else # define BOOST_HAS_ALIGNOF # define BOOST_HAS_CHAR16_T @@ -169,31 +164,23 @@ # define BOOST_HAS_STATIC_ASSERT #endif -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS // UTF-8 still not supported -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS // UTF-8 still not supported +#define BOOST_NO_VARIADIC_TEMPLATES #if __BORLANDC__ >= 0x590 # define BOOST_HAS_TR1_HASH @@ -246,7 +233,7 @@ // all versions support __declspec: // #if defined(__STRICT_ANSI__) -// config/platform/win32.hpp will define BOOST_SYMBOL_EXPORT, etc., unless already defined +// config/platform/win32.hpp will define BOOST_SYMBOL_EXPORT, etc., unless already defined # define BOOST_SYMBOL_EXPORT #endif // @@ -285,3 +272,6 @@ #define BOOST_NO_COMPLETE_VALUE_INITIALIZATION #define BOOST_COMPILER "Borland C++ version " BOOST_STRINGIZE(__BORLANDC__) + + + diff --git a/utils/boost_idb/boost/config/compiler/clang.hpp b/utils/boost_idb/boost/config/compiler/clang.hpp index b57e26c5..2ce67732 100644 --- a/utils/boost_idb/boost/config/compiler/clang.hpp +++ b/utils/boost_idb/boost/config/compiler/clang.hpp @@ -1,175 +1,58 @@ // (C) Copyright Douglas Gregor 2010 // -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. // Clang compiler setup. -#define BOOST_HAS_PRAGMA_ONCE - -#if !__has_feature(cxx_exceptions) && !defined(BOOST_NO_EXCEPTIONS) +#if __has_feature(cxx_exceptions) && !defined(BOOST_NO_EXCEPTIONS) +#else # define BOOST_NO_EXCEPTIONS #endif -#if !__has_feature(cxx_rtti) && !defined(BOOST_NO_RTTI) +#if __has_feature(cxx_rtti) +#else # define BOOST_NO_RTTI #endif -#if !__has_feature(cxx_rtti) && !defined(BOOST_NO_TYPEID) -# define BOOST_NO_TYPEID -#endif - -#if defined(__int64) && !defined(__GNUC__) +#if defined(__int64) # define BOOST_HAS_MS_INT64 #endif #define BOOST_HAS_NRVO -// Branch prediction hints -#if defined(__has_builtin) -#if __has_builtin(__builtin_expect) -#define BOOST_LIKELY(x) __builtin_expect(x, 1) -#define BOOST_UNLIKELY(x) __builtin_expect(x, 0) -#endif -#endif - -// Clang supports "long long" in all compilation modes. -#define BOOST_HAS_LONG_LONG - -// -// Dynamic shared object (DSO) and dynamic-link library (DLL) support -// -#if !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) -# define BOOST_SYMBOL_EXPORT __attribute__((__visibility__("default"))) -# define BOOST_SYMBOL_IMPORT -# define BOOST_SYMBOL_VISIBLE __attribute__((__visibility__("default"))) -#endif - -// -// The BOOST_FALLTHROUGH macro can be used to annotate implicit fall-through -// between switch labels. -// -#if __cplusplus >= 201103L && defined(__has_warning) -# if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") -# define BOOST_FALLTHROUGH [[clang::fallthrough]] -# endif -#endif - -#if !__has_feature(cxx_auto_type) -# define BOOST_NO_CXX11_AUTO_DECLARATIONS -# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#endif - -#if !(defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define BOOST_NO_CXX11_CHAR16_T -# define BOOST_NO_CXX11_CHAR32_T -#endif - -#if !__has_feature(cxx_constexpr) -# define BOOST_NO_CXX11_CONSTEXPR -#endif - -#if !__has_feature(cxx_decltype) -# define BOOST_NO_CXX11_DECLTYPE -#endif - -#if !__has_feature(cxx_decltype_incomplete_return_types) -# define BOOST_NO_CXX11_DECLTYPE_N3276 -#endif - -#if !__has_feature(cxx_defaulted_functions) -# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#endif - -#if !__has_feature(cxx_deleted_functions) -# define BOOST_NO_CXX11_DELETED_FUNCTIONS -#endif - -#if !__has_feature(cxx_explicit_conversions) -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#endif - -#if !__has_feature(cxx_default_function_template_args) -# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#endif - -#if !__has_feature(cxx_generalized_initializers) -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#endif - -#if !__has_feature(cxx_lambdas) -# define BOOST_NO_CXX11_LAMBDAS -#endif - -#if !__has_feature(cxx_local_type_template_args) -# define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#endif - -#if !__has_feature(cxx_noexcept) -# define BOOST_NO_CXX11_NOEXCEPT -#endif - -#if !__has_feature(cxx_nullptr) -# define BOOST_NO_CXX11_NULLPTR -#endif - -#if !__has_feature(cxx_range_for) -# define BOOST_NO_CXX11_RANGE_BASED_FOR -#endif - -#if !__has_feature(cxx_raw_string_literals) -# define BOOST_NO_CXX11_RAW_LITERALS -#endif - -#if !__has_feature(cxx_generalized_initializers) -# define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#endif - -#if !__has_feature(cxx_rvalue_references) -# define BOOST_NO_CXX11_RVALUE_REFERENCES -#endif - -#if !__has_feature(cxx_strong_enums) -# define BOOST_NO_CXX11_SCOPED_ENUMS -#endif - -#if !__has_feature(cxx_static_assert) -# define BOOST_NO_CXX11_STATIC_ASSERT -#endif - -#if !__has_feature(cxx_alias_templates) -# define BOOST_NO_CXX11_TEMPLATE_ALIASES -#endif - -#if !__has_feature(cxx_unicode_literals) -# define BOOST_NO_CXX11_UNICODE_LITERALS -#endif - -#if !__has_feature(cxx_variadic_templates) -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#endif - -#if !__has_feature(cxx_user_literals) -# define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#endif - -#if !(__has_feature(cxx_alignas) || __has_extension(cxx_alignas)) -# define BOOST_NO_CXX11_ALIGNAS -#endif - -#if !__has_feature(cxx_trailing_return) -# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#endif - -#if !__has_feature(cxx_inline_namespaces) -# define BOOST_NO_CXX11_INLINE_NAMESPACES -#endif - -// Clang always supports variadic macros -// Clang always supports extern templates +// NOTE: Clang's C++0x support is not worth detecting. However, it +// supports both extern templates and "long long" even in C++98/03 +// mode. +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS + +// HACK: Clang does support extern templates, but Boost's test for +// them is wrong. +#define BOOST_NO_EXTERN_TEMPLATE #ifndef BOOST_COMPILER # define BOOST_COMPILER "Clang version " __clang_version__ diff --git a/utils/boost_idb/boost/config/compiler/codegear.hpp b/utils/boost_idb/boost/config/compiler/codegear.hpp index 00e0bb94..f6dc4c02 100644 --- a/utils/boost_idb/boost/config/compiler/codegear.hpp +++ b/utils/boost_idb/boost/config/compiler/codegear.hpp @@ -60,7 +60,7 @@ // (Niels Dekker, LKEB, April 2010) # define BOOST_NO_COMPLETE_VALUE_INITIALIZATION -# if defined(NDEBUG) && defined(__cplusplus) +# ifdef NDEBUG // fix broken so that Boost.test works: # include # undef strcmp @@ -72,17 +72,11 @@ # endif #endif - -// Reportedly, #pragma once is supported since C++ Builder 2010 -#if (__CODEGEARC__ >= 0x620) -# define BOOST_HAS_PRAGMA_ONCE -#endif - // // C++0x macros: // #if (__CODEGEARC__ <= 0x620) -#define BOOST_NO_CXX11_STATIC_ASSERT +#define BOOST_NO_STATIC_ASSERT #else #define BOOST_HAS_STATIC_ASSERT #endif @@ -97,29 +91,23 @@ // #define BOOST_HAS_STATIC_ASSERT #define BOOST_HAS_STD_TYPE_TRAITS -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES // // TR1 macros: @@ -131,7 +119,7 @@ #define BOOST_HAS_MACRO_USE_FACET -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST +#define BOOST_NO_INITIALIZER_LISTS // On non-Win32 platforms let the platform config figure this out: #ifdef _WIN32 @@ -160,7 +148,7 @@ // all versions support __declspec: // #if defined(__STRICT_ANSI__) -// config/platform/win32.hpp will define BOOST_SYMBOL_EXPORT, etc., unless already defined +// config/platform/win32.hpp will define BOOST_SYMBOL_EXPORT, etc., unless already defined # define BOOST_SYMBOL_EXPORT #endif // diff --git a/utils/boost_idb/boost/config/compiler/common_edg.hpp b/utils/boost_idb/boost/config/compiler/common_edg.hpp index 70e7efa2..682c73af 100644 --- a/utils/boost_idb/boost/config/compiler/common_edg.hpp +++ b/utils/boost_idb/boost/config/compiler/common_edg.hpp @@ -1,10 +1,10 @@ -// (C) Copyright John Maddock 2001 - 2002. -// (C) Copyright Jens Maurer 2001. -// (C) Copyright David Abrahams 2002. -// (C) Copyright Aleksey Gurtovoy 2002. +// (C) Copyright John Maddock 2001 - 2002. +// (C) Copyright Jens Maurer 2001. +// (C) Copyright David Abrahams 2002. +// (C) Copyright Aleksey Gurtovoy 2002. // (C) Copyright Markus Schoepflin 2005. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -33,15 +33,15 @@ #if (__EDG_VERSION__ <= 244) && !defined(BOOST_NO_TEMPLATE_TEMPLATES) # define BOOST_NO_TEMPLATE_TEMPLATES -#endif +#endif #if (__EDG_VERSION__ < 300) && !defined(BOOST_NO_IS_ABSTRACT) # define BOOST_NO_IS_ABSTRACT -#endif +#endif #if (__EDG_VERSION__ <= 303) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL) # define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL -#endif +#endif // See also kai.hpp which checks a Kai-specific symbol for EH # if !defined(__KCC) && !defined(__EXCEPTIONS) && !defined(BOOST_NO_EXCEPTIONS) @@ -54,56 +54,41 @@ # define BOOST_NO_LONG_LONG # endif -// Not sure what version was the first to support #pragma once, but -// different EDG-based compilers (e.g. Intel) supported it for ages. -// Add a proper version check if it causes problems. -#define BOOST_HAS_PRAGMA_ONCE - // // C++0x features // // See above for BOOST_NO_LONG_LONG // #if (__EDG_VERSION__ < 310) -# define BOOST_NO_CXX11_EXTERN_TEMPLATE +# define BOOST_NO_EXTERN_TEMPLATE #endif -#if (__EDG_VERSION__ <= 310) +#if (__EDG_VERSION__ <= 310) || !defined(BOOST_STRICT_CONFIG) // No support for initializer lists -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#endif -#if (__EDG_VERSION__ < 400) -# define BOOST_NO_CXX11_VARIADIC_MACROS +# define BOOST_NO_INITIALIZER_LISTS #endif -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS #ifdef c_plusplus // EDG has "long long" in non-strict mode diff --git a/utils/boost_idb/boost/config/compiler/cray.hpp b/utils/boost_idb/boost/config/compiler/cray.hpp deleted file mode 100644 index 3ce29f01..00000000 --- a/utils/boost_idb/boost/config/compiler/cray.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// (C) Copyright John Maddock 2011. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for most recent version. - -// Greenhills C compiler setup: - -#define BOOST_COMPILER "Cray C version " BOOST_STRINGIZE(_RELEASE) - -#if _RELEASE < 7 -# error "Boost is not configured for Cray compilers prior to version 7, please try the configure script." -#endif - -// -// Check this is a recent EDG based compiler, otherwise we don't support it here: -// -#ifndef __EDG_VERSION__ -# error "Unsupported Cray compiler, please try running the configure script." -#endif - -#include "boost/config/compiler/common_edg.hpp" - -// -// Cray peculiarities, probably version 7 specific: -// -#undef BOOST_NO_CXX11_AUTO_DECLARATIONS -#undef BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_HAS_NRVO -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_TWO_PHASE_NAME_LOOKUP -#define BOOST_HAS_NRVO -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_SCOPED_ENUMS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_COMPLETE_VALUE_INITIALIZATION -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_ALIGNAS -//#define BOOST_BCB_PARTIAL_SPECIALIZATION_BUG -#define BOOST_MATH_DISABLE_STD_FPCLASSIFY -//#define BOOST_HAS_FPCLASSIFY - -#define BOOST_SP_USE_PTHREADS -#define BOOST_AC_USE_PTHREADS - diff --git a/utils/boost_idb/boost/config/compiler/digitalmars.hpp b/utils/boost_idb/boost/config/compiler/digitalmars.hpp index 7de6adb1..31c11bf0 100644 --- a/utils/boost_idb/boost/config/compiler/digitalmars.hpp +++ b/utils/boost_idb/boost/config/compiler/digitalmars.hpp @@ -1,8 +1,8 @@ // Copyright (C) Christof Meerwald 2003 // Copyright (C) Dan Watkins 2003 // -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Digital Mars C++ compiler setup: @@ -11,7 +11,15 @@ #define BOOST_HAS_LONG_LONG #define BOOST_HAS_PRAGMA_ONCE -#if !defined(BOOST_STRICT_CONFIG) +#if (__DMC__ <= 0x833) +#define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +#define BOOST_NO_TEMPLATE_TEMPLATES +#define BOOST_NEEDS_TOKEN_PASTING_OP_FOR_TOKENS_JUXTAPOSING +#define BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS +#define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +#endif +#if (__DMC__ <= 0x840) || !defined(BOOST_STRICT_CONFIG) +#define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS #define BOOST_NO_MEMBER_TEMPLATE_FRIENDS #define BOOST_NO_OPERATORS_IN_NAMESPACE #define BOOST_NO_UNREACHABLE_RETURN_DETECTION @@ -22,9 +30,11 @@ // // has macros: +#if (__DMC__ >= 0x840) #define BOOST_HAS_DIRENT_H #define BOOST_HAS_STDINT_H #define BOOST_HAS_WINTHREADS +#endif #if (__DMC__ >= 0x847) #define BOOST_HAS_EXPM1 @@ -34,9 +44,7 @@ // // Is this really the best way to detect whether the std lib is in namespace std? // -#ifdef __cplusplus #include -#endif #if !defined(__STL_IMPORT_VENDOR_CSTD) && !defined(_STLP_IMPORT_VENDOR_CSTD) # define BOOST_NO_STDC_NAMESPACE #endif @@ -50,38 +58,33 @@ // // C++0x features // -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#if (__DMC__ < 0x812) +#define BOOST_NO_VARIADIC_MACROS +#endif -#if (__DMC__ <= 0x840) +#if __DMC__ < 0x800 #error "Compiler not supported or configured - please reconfigure" #endif // diff --git a/utils/boost_idb/boost/config/compiler/gcc.hpp b/utils/boost_idb/boost/config/compiler/gcc.hpp index aa628e5a..eeaf9982 100644 --- a/utils/boost_idb/boost/config/compiler/gcc.hpp +++ b/utils/boost_idb/boost/config/compiler/gcc.hpp @@ -1,35 +1,67 @@ -// (C) Copyright John Maddock 2001 - 2003. -// (C) Copyright Darin Adler 2001 - 2002. -// (C) Copyright Jens Maurer 2001 - 2002. -// (C) Copyright Beman Dawes 2001 - 2003. -// (C) Copyright Douglas Gregor 2002. -// (C) Copyright David Abrahams 2002 - 2003. -// (C) Copyright Synge Todo 2003. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001 - 2002. +// (C) Copyright Jens Maurer 2001 - 2002. +// (C) Copyright Beman Dawes 2001 - 2003. +// (C) Copyright Douglas Gregor 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Synge Todo 2003. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. -// GNU C++ compiler setup. - -// -// Define BOOST_GCC so we know this is "real" GCC and not some pretender: -// -#if !defined(__CUDACC__) -#define BOOST_GCC (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -#endif - -#if __GNUC__ == 3 +// GNU C++ compiler setup: + +#if __GNUC__ < 3 +# if __GNUC_MINOR__ == 91 + // egcs 1.1 won't parse shared_ptr.hpp without this: +# define BOOST_NO_AUTO_PTR +# endif +# if __GNUC_MINOR__ < 95 + // + // Prior to gcc 2.95 member templates only partly + // work - define BOOST_MSVC6_MEMBER_TEMPLATES + // instead since inline member templates mostly work. + // +# define BOOST_NO_MEMBER_TEMPLATES +# if __GNUC_MINOR__ >= 9 +# define BOOST_MSVC6_MEMBER_TEMPLATES +# endif +# endif + +# if __GNUC_MINOR__ < 96 +# define BOOST_NO_SFINAE +# endif + +# if __GNUC_MINOR__ <= 97 +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# define BOOST_NO_OPERATORS_IN_NAMESPACE +# endif + +# define BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE +# define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +# define BOOST_NO_IS_ABSTRACT +# define BOOST_NO_EXTERN_TEMPLATE +// Variadic macros do not exist for gcc versions before 3.0 +# define BOOST_NO_VARIADIC_MACROS +#elif __GNUC__ == 3 # if defined (__PATHSCALE__) # define BOOST_NO_TWO_PHASE_NAME_LOOKUP # define BOOST_NO_IS_ABSTRACT # endif - + // + // gcc-3.x problems: + // + // Bug specific to gcc 3.1 and 3.2: + // +# if ((__GNUC_MINOR__ == 1) || (__GNUC_MINOR__ == 2)) +# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +# endif # if __GNUC_MINOR__ < 4 # define BOOST_NO_IS_ABSTRACT # endif -# define BOOST_NO_CXX11_EXTERN_TEMPLATE +# define BOOST_NO_EXTERN_TEMPLATE #endif #if __GNUC__ < 4 // @@ -41,11 +73,6 @@ # endif #endif -// GCC prior to 3.4 had #pragma once too but it didn't work well with filesystem links -#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -#define BOOST_HAS_PRAGMA_ONCE -#endif - #if __GNUC__ < 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ < 4 ) // Previous versions of GCC did not completely implement value-initialization: // GCC Bug 30111, "Value-initialization of POD base class doesn't initialize @@ -70,7 +97,7 @@ // #if !defined(__MINGW32__) && !defined(linux) && !defined(__linux) && !defined(__linux__) # define BOOST_HAS_THREADS -#endif +#endif // // gcc has "long long" @@ -80,30 +107,28 @@ // // gcc implements the named return value optimization since version 3.1 // +#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) #define BOOST_HAS_NRVO - -// Branch prediction hints -#define BOOST_LIKELY(x) __builtin_expect(x, 1) -#define BOOST_UNLIKELY(x) __builtin_expect(x, 0) +#endif // // Dynamic shared object (DSO) and dynamic-link library (DLL) support // #if __GNUC__ >= 4 # if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && !defined(__CYGWIN__) - // All Win32 development environments, including 64-bit Windows and MinGW, define + // All Win32 development environments, including 64-bit Windows and MinGW, define // _WIN32 or one of its variant spellings. Note that Cygwin is a POSIX environment, // so does not define _WIN32 or its variants. # define BOOST_HAS_DECLSPEC -# define BOOST_SYMBOL_EXPORT __attribute__((__dllexport__)) -# define BOOST_SYMBOL_IMPORT __attribute__((__dllimport__)) +# define BOOST_SYMBOL_EXPORT __attribute__((dllexport)) +# define BOOST_SYMBOL_IMPORT __attribute__((dllimport)) # else -# define BOOST_SYMBOL_EXPORT __attribute__((__visibility__("default"))) +# define BOOST_SYMBOL_EXPORT __attribute__((visibility("default"))) # define BOOST_SYMBOL_IMPORT # endif -# define BOOST_SYMBOL_VISIBLE __attribute__((__visibility__("default"))) +# define BOOST_SYMBOL_VISIBLE __attribute__((visibility("default"))) #else -// config/platform/win32.hpp will define BOOST_SYMBOL_EXPORT, etc., unless already defined +// config/platform/win32.hpp will define BOOST_SYMBOL_EXPORT, etc., unless already defined # define BOOST_SYMBOL_EXPORT #endif @@ -121,19 +146,11 @@ # endif #endif +// C++0x features not implemented in any GCC version // -// Recent GCC versions have __int128 when in 64-bit mode. -// -// We disable this if the compiler is really nvcc as it -// doesn't actually support __int128 as of CUDA_VERSION=5000 -// even though it defines __SIZEOF_INT128__. -// See https://svn.boost.org/trac/boost/ticket/8048 -// Only re-enable this for nvcc if you're absolutely sure -// of the circumstances under which it's supported: -// -#if defined(__SIZEOF_INT128__) && !defined(__CUDACC__) -# define BOOST_HAS_INT128 -#endif +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_NULLPTR +#define BOOST_NO_TEMPLATE_ALIASES // C++0x features in 4.3.n and later // @@ -146,92 +163,52 @@ # define BOOST_HAS_STATIC_ASSERT # define BOOST_HAS_VARIADIC_TMPL #else -# define BOOST_NO_CXX11_DECLTYPE -# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -# define BOOST_NO_CXX11_RVALUE_REFERENCES -# define BOOST_NO_CXX11_STATIC_ASSERT +# define BOOST_NO_DECLTYPE +# define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +# define BOOST_NO_RVALUE_REFERENCES +# define BOOST_NO_STATIC_ASSERT -// Variadic templates compiler: +// Variadic templates compiler: // http://www.generic-programming.org/~dgregor/cpp/variadic-templates.html -# if defined(__VARIADIC_TEMPLATES) || (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4) && defined(__GXX_EXPERIMENTAL_CXX0X__)) +# ifdef __VARIADIC_TEMPLATES # define BOOST_HAS_VARIADIC_TMPL # else -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES +# define BOOST_NO_VARIADIC_TEMPLATES # endif #endif // C++0x features in 4.4.n and later // #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 4) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_AUTO_DECLARATIONS -# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -# define BOOST_NO_CXX11_CHAR16_T -# define BOOST_NO_CXX11_CHAR32_T -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -# define BOOST_NO_CXX11_DELETED_FUNCTIONS -# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -# define BOOST_NO_CXX11_INLINE_NAMESPACES +# define BOOST_NO_AUTO_DECLARATIONS +# define BOOST_NO_AUTO_MULTIDECLARATIONS +# define BOOST_NO_CHAR16_T +# define BOOST_NO_CHAR32_T +# define BOOST_NO_DEFAULTED_FUNCTIONS +# define BOOST_NO_DELETED_FUNCTIONS +# define BOOST_NO_INITIALIZER_LISTS +# define BOOST_NO_SCOPED_ENUMS #endif -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5) +#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 4) # define BOOST_NO_SFINAE_EXPR #endif -// GCC 4.5 forbids declaration of defaulted functions in private or protected sections -#if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && (__GNUC__ == 4 && __GNUC_MINOR__ <= 5) -# define BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS -#endif - -// C++0x features in 4.5.0 and later -// -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -# define BOOST_NO_CXX11_LAMBDAS -# define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -# define BOOST_NO_CXX11_RAW_LITERALS -# define BOOST_NO_CXX11_UNICODE_LITERALS -#endif - -// C++0x features in 4.5.1 and later +// C++0x features in 4.4.1 and later // -#if (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__ < 40501) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -// scoped enums have a serious bug in 4.4.0, so define BOOST_NO_CXX11_SCOPED_ENUMS before 4.5.1 +#if (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__ < 40401) || !defined(__GXX_EXPERIMENTAL_CXX0X__) +// scoped enums have a serious bug in 4.4.0, so define BOOST_NO_SCOPED_ENUMS before 4.4.1 // See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38064 -# define BOOST_NO_CXX11_SCOPED_ENUMS -#endif - -// C++0x features in 4.6.n and later -// -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX +# define BOOST_NO_SCOPED_ENUMS #endif -// C++0x features in 4.7.n and later +// C++0x features in 4.5.n and later // -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_TEMPLATE_ALIASES -# define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#endif - -// C++0x features in 4.8.n and later -// -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_ALIGNAS -#endif - -// C++0x features in 4.8.1 and later -// -#if (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__ < 40801) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_DECLTYPE_N3276 -#endif - -#ifndef BOOST_COMPILER -# define BOOST_COMPILER "GNU C++ version " __VERSION__ +#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5) || !defined(__GXX_EXPERIMENTAL_CXX0X__) +# define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +# define BOOST_NO_LAMBDAS +# define BOOST_NO_RAW_LITERALS +# define BOOST_NO_UNICODE_LITERALS #endif // ConceptGCC compiler: @@ -239,16 +216,23 @@ #ifdef __GXX_CONCEPTS__ # define BOOST_HAS_CONCEPTS # define BOOST_COMPILER "ConceptGCC version " __VERSION__ +#else +# define BOOST_NO_CONCEPTS #endif +#ifndef BOOST_COMPILER +# define BOOST_COMPILER "GNU C++ version " __VERSION__ +#endif + +// // versions check: -// we don't know gcc prior to version 3.30: -#if (__GNUC__ < 3) || (__GNUC__ == 3 && (__GNUC_MINOR__ < 3)) +// we don't know gcc prior to version 2.90: +#if (__GNUC__ == 2) && (__GNUC_MINOR__ < 90) # error "Compiler not configured - please reconfigure" #endif // -// last known and checked version is 4.6 (Pre-release): -#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 6)) +// last known and checked version is 4.4 (Pre-release): +#if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 4)) # if defined(BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # else diff --git a/utils/boost_idb/boost/config/compiler/gcc_xml.hpp b/utils/boost_idb/boost/config/compiler/gcc_xml.hpp index d2e0c74f..a456463c 100644 --- a/utils/boost_idb/boost/config/compiler/gcc_xml.hpp +++ b/utils/boost_idb/boost/config/compiler/gcc_xml.hpp @@ -1,6 +1,6 @@ -// (C) Copyright John Maddock 2006. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2006. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -18,7 +18,7 @@ // #if !defined(__MINGW32__) && !defined(_MSC_VER) && !defined(linux) && !defined(__linux) && !defined(__linux__) # define BOOST_HAS_THREADS -#endif +#endif // // gcc has "long long" @@ -27,37 +27,29 @@ // C++0x features: // -# define BOOST_NO_CXX11_CONSTEXPR -# define BOOST_NO_CXX11_NULLPTR -# define BOOST_NO_CXX11_TEMPLATE_ALIASES -# define BOOST_NO_CXX11_DECLTYPE -# define BOOST_NO_CXX11_DECLTYPE_N3276 -# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -# define BOOST_NO_CXX11_RVALUE_REFERENCES -# define BOOST_NO_CXX11_STATIC_ASSERT -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES -# define BOOST_NO_CXX11_VARIADIC_MACROS -# define BOOST_NO_CXX11_AUTO_DECLARATIONS -# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -# define BOOST_NO_CXX11_CHAR16_T -# define BOOST_NO_CXX11_CHAR32_T -# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -# define BOOST_NO_CXX11_DELETED_FUNCTIONS -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_SCOPED_ENUMS +# define BOOST_NO_CONSTEXPR +# define BOOST_NO_NULLPTR +# define BOOST_NO_TEMPLATE_ALIASES +# define BOOST_NO_DECLTYPE +# define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +# define BOOST_NO_RVALUE_REFERENCES +# define BOOST_NO_STATIC_ASSERT +# define BOOST_NO_VARIADIC_TEMPLATES +# define BOOST_NO_VARIADIC_MACROS +# define BOOST_NO_AUTO_DECLARATIONS +# define BOOST_NO_AUTO_MULTIDECLARATIONS +# define BOOST_NO_CHAR16_T +# define BOOST_NO_CHAR32_T +# define BOOST_NO_DEFAULTED_FUNCTIONS +# define BOOST_NO_DELETED_FUNCTIONS +# define BOOST_NO_INITIALIZER_LISTS +# define BOOST_NO_SCOPED_ENUMS # define BOOST_NO_SFINAE_EXPR -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -# define BOOST_NO_CXX11_LAMBDAS -# define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -# define BOOST_NO_CXX11_RANGE_BASED_FOR -# define BOOST_NO_CXX11_RAW_LITERALS -# define BOOST_NO_CXX11_UNICODE_LITERALS -# define BOOST_NO_CXX11_NOEXCEPT -# define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -# define BOOST_NO_CXX11_USER_DEFINED_LITERALS -# define BOOST_NO_CXX11_ALIGNAS -# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -# define BOOST_NO_CXX11_INLINE_NAMESPACES +# define BOOST_NO_SCOPED_ENUMS +# define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +# define BOOST_NO_LAMBDAS +# define BOOST_NO_RAW_LITERALS +# define BOOST_NO_UNICODE_LITERALS #define BOOST_COMPILER "GCC-XML C++ version " __GCCXML__ diff --git a/utils/boost_idb/boost/config/compiler/hp_acc.hpp b/utils/boost_idb/boost/config/compiler/hp_acc.hpp index f08dca44..d0b672ec 100644 --- a/utils/boost_idb/boost/config/compiler/hp_acc.hpp +++ b/utils/boost_idb/boost/config/compiler/hp_acc.hpp @@ -1,11 +1,11 @@ -// (C) Copyright John Maddock 2001 - 2003. -// (C) Copyright Jens Maurer 2001 - 2003. -// (C) Copyright Aleksey Gurtovoy 2002. -// (C) Copyright David Abrahams 2002 - 2003. -// (C) Copyright Toon Knapen 2003. +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Jens Maurer 2001 - 2003. +// (C) Copyright Aleksey Gurtovoy 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Toon Knapen 2003. // (C) Copyright Boris Gubenko 2006 - 2007. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -43,7 +43,7 @@ # define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS # define BOOST_NO_IS_ABSTRACT # define BOOST_NO_MEMBER_TEMPLATE_FRIENDS -#endif +#endif // optional features rather than defects: #if (__HP_aCC >= 33900) @@ -92,44 +92,37 @@ // #if !defined(__EDG__) -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES - -/* +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES + +/* See https://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1443331 and https://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1443436 */ #if (__HP_aCC < 62500) || !defined(HP_CXX0x_SOURCE) - #define BOOST_NO_CXX11_VARIADIC_MACROS + #define BOOST_NO_VARIADIC_MACROS #endif #endif diff --git a/utils/boost_idb/boost/config/compiler/intel.hpp b/utils/boost_idb/boost/config/compiler/intel.hpp index 3f0eaa18..e7bc95ba 100644 --- a/utils/boost_idb/boost/config/compiler/intel.hpp +++ b/utils/boost_idb/boost/config/compiler/intel.hpp @@ -26,19 +26,7 @@ # define BOOST_INTEL_CXX_VERSION __ECC #endif -// Flags determined by comparing output of 'icpc -dM -E' with and without '-std=c++0x' -#if (!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && (__STDC_HOSTED__ && (BOOST_INTEL_CXX_VERSION <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__) || defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_INTEL_STDCXX0X -#endif -#if defined(_MSC_VER) && (_MSC_VER >= 1600) -# define BOOST_INTEL_STDCXX0X -#endif - -#ifdef BOOST_INTEL_STDCXX0X -#define BOOST_COMPILER "Intel C++ C++0x mode version " BOOST_STRINGIZE(BOOST_INTEL_CXX_VERSION) -#else #define BOOST_COMPILER "Intel C++ version " BOOST_STRINGIZE(BOOST_INTEL_CXX_VERSION) -#endif #define BOOST_INTEL BOOST_INTEL_CXX_VERSION #if defined(_WIN32) || defined(_WIN64) @@ -47,6 +35,11 @@ # define BOOST_INTEL_LINUX BOOST_INTEL #endif +#if (BOOST_INTEL_CXX_VERSION <= 500) && defined(_MSC_VER) +# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +# define BOOST_NO_TEMPLATE_TEMPLATES +#endif + #if (BOOST_INTEL_CXX_VERSION <= 600) # if defined(_MSC_VER) && (_MSC_VER <= 1300) // added check for <= VC 7 (Peter Dimov) @@ -106,7 +99,7 @@ # define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL # endif #endif -#if (defined(__GNUC__) && (__GNUC__ < 4)) || (defined(_WIN32) && (BOOST_INTEL_CXX_VERSION <= 1200)) || (BOOST_INTEL_CXX_VERSION <= 1200) +#if (defined(__GNUC__) && (__GNUC__ < 4)) || defined(_WIN32) || (BOOST_INTEL_CXX_VERSION <= 1110) // GCC or VC emulation: #define BOOST_NO_TWO_PHASE_NAME_LOOKUP #endif @@ -116,7 +109,6 @@ // in type_traits code among other things, getting this correct // for the Intel compiler is actually remarkably fragile and tricky: // -#ifdef __cplusplus #if defined(BOOST_NO_INTRINSIC_WCHAR_T) #include template< typename T > struct assert_no_intrinsic_wchar_t; @@ -130,9 +122,8 @@ template<> struct assert_intrinsic_wchar_t {}; // if you see an error here then define BOOST_NO_INTRINSIC_WCHAR_T on the command line: template<> struct assert_intrinsic_wchar_t {}; #endif -#endif -#if defined(_MSC_VER) && (_MSC_VER+0 >= 1000) +#if _MSC_VER+0 >= 1000 # if _MSC_VER >= 1200 # define BOOST_HAS_MS_INT64 # endif @@ -149,18 +140,10 @@ template<> struct assert_intrinsic_wchar_t {}; # define BOOST_HAS_NRVO #endif -// Branch prediction hints -// I'm not sure 8.0 was the first version to support these builtins, -// update the condition if the version is not accurate. (Andrey Semashev) -#if defined(__GNUC__) && BOOST_INTEL_CXX_VERSION >= 800 -#define BOOST_LIKELY(x) __builtin_expect(x, 1) -#define BOOST_UNLIKELY(x) __builtin_expect(x, 0) -#endif - // // versions check: -// we don't support Intel prior to version 6.0: -#if BOOST_INTEL_CXX_VERSION < 600 +// we don't support Intel prior to version 5.0: +#if BOOST_INTEL_CXX_VERSION < 500 # error "Compiler not supported or configured - please reconfigure" #endif @@ -176,15 +159,14 @@ template<> struct assert_intrinsic_wchar_t {}; // // An attempt to value-initialize a pointer-to-member may trigger an -// internal error on Intel <= 11.1 (last checked version), as was +// internal error on Intel <= 11.1 (last checked version), as was // reported by John Maddock, Intel support issue 589832, May 2010. // Moreover, according to test results from Huang-Vista-x86_32_intel, -// intel-vc9-win-11.1 may leave a non-POD array uninitialized, in some +// intel-vc9-win-11.1 may leave a non-POD array uninitialized, in some // cases when it should be value-initialized. // (Niels Dekker, LKEB, May 2010) -// Apparently Intel 12.1 (compiler version number 9999 !!) has the same issue (compiler regression). #if defined(__INTEL_COMPILER) -# if (__INTEL_COMPILER <= 1110) || (__INTEL_COMPILER == 9999) || (defined(_WIN32) && (__INTEL_COMPILER < 1500)) +# if __INTEL_COMPILER <= 1110 # define BOOST_NO_COMPLETE_VALUE_INITIALIZATION # endif #endif @@ -197,119 +179,10 @@ template<> struct assert_intrinsic_wchar_t {}; # define BOOST_SYMBOL_IMPORT # define BOOST_SYMBOL_VISIBLE __attribute__((visibility("default"))) #endif -// -// C++0x features -// - ICC added static_assert in 11.0 (first version with C++0x support) -// -#if defined(BOOST_INTEL_STDCXX0X) -# undef BOOST_NO_CXX11_STATIC_ASSERT -// -// These pass our test cases, but aren't officially supported according to: -// http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler/ -// -//# undef BOOST_NO_CXX11_LAMBDAS -//# undef BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -//# undef BOOST_NO_CXX11_DECLTYPE -//# undef BOOST_NO_CXX11_AUTO_DECLARATIONS -//# undef BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#endif - -#if defined(BOOST_INTEL_STDCXX0X) && (BOOST_INTEL_CXX_VERSION >= 1200) -//# undef BOOST_NO_CXX11_RVALUE_REFERENCES // Enabling this breaks Filesystem and Exception libraries -//# undef BOOST_NO_CXX11_SCOPED_ENUMS // doesn't really work!! -# undef BOOST_NO_CXX11_DELETED_FUNCTIONS -# undef BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -# undef BOOST_NO_CXX11_LAMBDAS -# undef BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -# undef BOOST_NO_CXX11_DECLTYPE -# undef BOOST_NO_CXX11_AUTO_DECLARATIONS -# undef BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -# undef BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#endif - -// icl Version 12.1.0.233 Build 20110811 and possibly some other builds -// had an incorrect __INTEL_COMPILER value of 9999. Intel say this has been fixed. -#if defined(BOOST_INTEL_STDCXX0X) && (BOOST_INTEL_CXX_VERSION > 1200) -# undef BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -# undef BOOST_NO_CXX11_NULLPTR -# undef BOOST_NO_CXX11_RVALUE_REFERENCES -# undef BOOST_NO_SFINAE_EXPR -# undef BOOST_NO_CXX11_TEMPLATE_ALIASES -# undef BOOST_NO_CXX11_VARIADIC_TEMPLATES - -// http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler/ -// continues to list scoped enum support as "Partial" -//# undef BOOST_NO_CXX11_SCOPED_ENUMS -#endif -#if defined(BOOST_INTEL_STDCXX0X) && (BOOST_INTEL_CXX_VERSION >= 1310) && !defined(_MSC_VER) -# undef BOOST_NO_CXX11_INLINE_NAMESPACES -# undef BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -// This one generates internal compiler errors in multiprecision, disabled for now: -//# undef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -// This one generates errors when used with conditional exception specifications, for example in multiprecision: -//# undef BOOST_NO_CXX11_NOEXCEPT -# undef BOOST_NO_CXX11_RANGE_BASED_FOR -# undef BOOST_NO_CXX11_SCOPED_ENUMS -# undef BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#endif -#if (BOOST_INTEL_CXX_VERSION >= 1310) -# undef BOOST_NO_SFINAE_EXPR -#endif -#if defined(BOOST_INTEL_STDCXX0X) && (BOOST_INTEL_CXX_VERSION >= 1400) && !defined(_MSC_VER) -# undef BOOST_NO_CXX11_UNICODE_LITERALS -# undef BOOST_NO_CXX11_RAW_LITERALS -// This one generates errors when used with conditional exception specifications, for example in multiprecision: -//# undef BOOST_NO_CXX11_NOEXCEPT -// This breaks multiprecision: -//# undef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -# undef BOOST_NO_CXX11_HDR_THREAD -# undef BOOST_NO_CXX11_CHAR32_T -# undef BOOST_NO_CXX11_CHAR16_T -#endif - -#if defined(BOOST_INTEL_STDCXX0X) && (BOOST_INTEL_CXX_VERSION <= 1310) -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#endif - -#if defined(BOOST_INTEL_STDCXX0X) && (BOOST_INTEL_CXX_VERSION == 1400) -// A regression in Intel's compiler means that seems to be broken in this release as well as : -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_TUPLE -#endif - -#if defined(_MSC_VER) && (_MSC_VER <= 1700) -// -// Although the Intel compiler is capable of supporting these, it appears not to in MSVC compatibility mode: -// -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES -# define BOOST_NO_CXX11_DELETED_FUNCTIONS -# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -# define BOOST_NO_CXX11_TEMPLATE_ALIASES -# if(BOOST_INTEL_CXX_VERSION < 1310) -# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -# endif -#endif - -#if (BOOST_INTEL_CXX_VERSION < 1200) -// -// fenv.h appears not to work with Intel prior to 12.0: -// -# define BOOST_NO_FENV_H -#endif - -#if defined(_MSC_VER) && (_MSC_VER >= 1600) -# define BOOST_HAS_STDINT_H -#endif - -#if defined(__LP64__) && defined(__GNUC__) && (BOOST_INTEL_CXX_VERSION >= 1310) -# define BOOST_HAS_INT128 -#endif // // last known and checked version: -#if (BOOST_INTEL_CXX_VERSION > 1310) +#if (BOOST_INTEL_CXX_VERSION > 1110) # if defined(BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # elif defined(_MSC_VER) diff --git a/utils/boost_idb/boost/config/compiler/metrowerks.hpp b/utils/boost_idb/boost/config/compiler/metrowerks.hpp index e1727860..21083b7a 100644 --- a/utils/boost_idb/boost/config/compiler/metrowerks.hpp +++ b/utils/boost_idb/boost/config/compiler/metrowerks.hpp @@ -1,11 +1,11 @@ -// (C) Copyright John Maddock 2001. -// (C) Copyright Darin Adler 2001. -// (C) Copyright Peter Dimov 2001. -// (C) Copyright David Abrahams 2001 - 2002. -// (C) Copyright Beman Dawes 2001 - 2003. -// (C) Copyright Stefan Slapeta 2004. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2001. +// (C) Copyright Darin Adler 2001. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright David Abrahams 2001 - 2002. +// (C) Copyright Beman Dawes 2001 - 2003. +// (C) Copyright Stefan Slapeta 2004. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -15,7 +15,7 @@ // locale support is disabled when linking with the dynamic runtime # ifdef _MSL_NO_LOCALE # define BOOST_NO_STD_LOCALE -# endif +# endif # if __MWERKS__ <= 0x2301 // 5.3 # define BOOST_NO_FUNCTION_TEMPLATE_ORDERING @@ -90,39 +90,31 @@ #if __MWERKS__ > 0x3206 && __option(rvalue_refs) # define BOOST_HAS_RVALUE_REFS #else -# define BOOST_NO_CXX11_RVALUE_REFERENCES +# define BOOST_NO_RVALUE_REFERENCES #endif -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_VARIADIC_MACROS -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS #define BOOST_COMPILER "Metrowerks CodeWarrior C++ version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) diff --git a/utils/boost_idb/boost/config/compiler/mpw.hpp b/utils/boost_idb/boost/config/compiler/mpw.hpp index 69104674..ae12f801 100644 --- a/utils/boost_idb/boost/config/compiler/mpw.hpp +++ b/utils/boost_idb/boost/config/compiler/mpw.hpp @@ -1,7 +1,7 @@ -// (C) Copyright John Maddock 2001 - 2002. -// (C) Copyright Aleksey Gurtovoy 2002. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2001 - 2002. +// (C) Copyright Aleksey Gurtovoy 2002. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -40,38 +40,30 @@ // // See boost\config\suffix.hpp for BOOST_NO_LONG_LONG // -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_VARIADIC_MACROS -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS // // versions check: diff --git a/utils/boost_idb/boost/config/compiler/nvcc.hpp b/utils/boost_idb/boost/config/compiler/nvcc.hpp index bbe81f6e..eaecf374 100644 --- a/utils/boost_idb/boost/config/compiler/nvcc.hpp +++ b/utils/boost_idb/boost/config/compiler/nvcc.hpp @@ -14,3 +14,74 @@ // NVIDIA Specific support // BOOST_GPU_ENABLED : Flag a function or a method as being enabled on the host and device #define BOOST_GPU_ENABLED __host__ __device__ + +// Boost support macro for NVCC +// NVCC Basically behaves like some flavor of MSVC6 + some specific quirks +#define BOOST_NO_INCLASS_MEMBER_INITIALIZATION +#define BOOST_MSVC6_MEMBER_TEMPLATES +#define BOOST_HAS_UNISTD_H +#define BOOST_HAS_STDINT_H +#define BOOST_HAS_SIGACTION +#define BOOST_HAS_SCHED_YIELD +#define BOOST_HAS_PTHREADS +#define BOOST_HAS_PTHREAD_YIELD +#define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE +#define BOOST_HAS_PARTIAL_STD_ALLOCATOR +#define BOOST_HAS_NRVO +#define BOOST_HAS_NL_TYPES_H +#define BOOST_HAS_NANOSLEEP +#define BOOST_HAS_LONG_LONG +#define BOOST_HAS_LOG1P +#define BOOST_HAS_GETTIMEOFDAY +#define BOOST_HAS_EXPM1 +#define BOOST_HAS_DIRENT_H +#define BOOST_HAS_CLOCK_GETTIME +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_STD_UNORDERED +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_SFINAE_EXPR +#define BOOST_NO_SCOPED_ENUMS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_NULLPTR +#define BOOST_NO_LAMBDAS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_MS_INT64_NUMERIC_LIMITS +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DECLTYPE +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CHAR16_T +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_0X_HDR_UNORDERED_SET +#define BOOST_NO_0X_HDR_UNORDERED_MAP +#define BOOST_NO_0X_HDR_TYPE_TRAITS +#define BOOST_NO_0X_HDR_TUPLE +#define BOOST_NO_0X_HDR_THREAD +#define BOOST_NO_0X_HDR_TYPEINDEX +#define BOOST_NO_0X_HDR_SYSTEM_ERROR +#define BOOST_NO_0X_HDR_REGEX +#define BOOST_NO_0X_HDR_RATIO +#define BOOST_NO_0X_HDR_RANDOM +#define BOOST_NO_0X_HDR_MUTEX +#define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +#define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +#define BOOST_NO_0X_HDR_INITIALIZER_LIST +#define BOOST_NO_0X_HDR_FUTURE +#define BOOST_NO_0X_HDR_FORWARD_LIST +#define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +#define BOOST_NO_0X_HDR_CONDITION_VARIABLE +#define BOOST_NO_0X_HDR_CONCEPTS +#define BOOST_NO_0X_HDR_CODECVT +#define BOOST_NO_0X_HDR_CHRONO +#define BOOST_NO_0X_HDR_ARRAY + diff --git a/utils/boost_idb/boost/config/compiler/pathscale.hpp b/utils/boost_idb/boost/config/compiler/pathscale.hpp deleted file mode 100644 index 567d83cc..00000000 --- a/utils/boost_idb/boost/config/compiler/pathscale.hpp +++ /dev/null @@ -1,83 +0,0 @@ -// (C) Copyright Bryce Lelbach 2011 - -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for most recent version. - -// PathScale EKOPath C++ Compiler - -#ifndef BOOST_COMPILER -# define BOOST_COMPILER "PathScale EKOPath C++ Compiler version " __PATHSCALE__ -#endif - -#if __PATHCC__ >= 4 -# define BOOST_MSVC6_MEMBER_TEMPLATES -# define BOOST_HAS_UNISTD_H -# define BOOST_HAS_STDINT_H -# define BOOST_HAS_SIGACTION -# define BOOST_HAS_SCHED_YIELD -# define BOOST_HAS_THREADS -# define BOOST_HAS_PTHREADS -# define BOOST_HAS_PTHREAD_YIELD -# define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE -# define BOOST_HAS_PARTIAL_STD_ALLOCATOR -# define BOOST_HAS_NRVO -# define BOOST_HAS_NL_TYPES_H -# define BOOST_HAS_NANOSLEEP -# define BOOST_HAS_LONG_LONG -# define BOOST_HAS_LOG1P -# define BOOST_HAS_GETTIMEOFDAY -# define BOOST_HAS_EXPM1 -# define BOOST_HAS_DIRENT_H -# define BOOST_HAS_CLOCK_GETTIME -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES -# define BOOST_NO_CXX11_UNICODE_LITERALS -# define BOOST_NO_CXX11_TEMPLATE_ALIASES -# define BOOST_NO_CXX11_STATIC_ASSERT -# define BOOST_NO_SFINAE_EXPR -# define BOOST_NO_CXX11_SCOPED_ENUMS -# define BOOST_NO_CXX11_RVALUE_REFERENCES -# define BOOST_NO_CXX11_RANGE_BASED_FOR -# define BOOST_NO_CXX11_RAW_LITERALS -# define BOOST_NO_CXX11_NULLPTR -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_NOEXCEPT -# define BOOST_NO_CXX11_LAMBDAS -# define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -# define BOOST_NO_MS_INT64_NUMERIC_LIMITS -# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -# define BOOST_NO_CXX11_DELETED_FUNCTIONS -# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -# define BOOST_NO_CXX11_DECLTYPE -# define BOOST_NO_CXX11_DECLTYPE_N3276 -# define BOOST_NO_CXX11_CONSTEXPR -# define BOOST_NO_COMPLETE_VALUE_INITIALIZATION -# define BOOST_NO_CXX11_CHAR32_T -# define BOOST_NO_CXX11_CHAR16_T -# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -# define BOOST_NO_CXX11_AUTO_DECLARATIONS -# define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_USER_DEFINED_LITERALS -# define BOOST_NO_CXX11_ALIGNAS -# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -# define BOOST_NO_CXX11_INLINE_NAMESPACES -#endif diff --git a/utils/boost_idb/boost/config/compiler/pgi.hpp b/utils/boost_idb/boost/config/compiler/pgi.hpp index d50cbef8..fb3a6c0b 100644 --- a/utils/boost_idb/boost/config/compiler/pgi.hpp +++ b/utils/boost_idb/boost/config/compiler/pgi.hpp @@ -1,6 +1,6 @@ // (C) Copyright Noel Belcourt 2007. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -8,7 +8,7 @@ // PGI C++ compiler setup: #define BOOST_COMPILER_VERSION __PGIC__##__PGIC_MINOR__ -#define BOOST_COMPILER "PGI compiler version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) +#define BOOST_COMPILER "PGI compiler version " BOOST_STRINGIZE(_COMPILER_VERSION) // // Threading support: @@ -16,34 +16,15 @@ // if no threading API is detected. // -#if __PGIC__ >= 11 +// PGI 10.x doesn't seem to define __PGIC__ -// options requested by configure --enable-test -#define BOOST_HAS_PTHREADS -#define BOOST_HAS_THREADS -#define BOOST_HAS_PTHREAD_YIELD -#define BOOST_HAS_NRVO -#define BOOST_HAS_LONG_LONG - -// options --enable-test wants undefined -#undef BOOST_NO_STDC_NAMESPACE -#undef BOOST_NO_EXCEPTION_STD_NAMESPACE -#undef BOOST_DEDUCED_TYPENAME - -#define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL -#define BOOST_NO_TWO_PHASE_NAME_LOOKUP -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_AUTO_DECLARATIONS - -#elif __PGIC__ >= 10 +// versions earlier than 10.x do define __PGIC__ +#if __PGIC__ >= 10 // options requested by configure --enable-test -#define BOOST_HAS_THREADS +#define BOOST_HAS_PTHREADS #define BOOST_HAS_NRVO #define BOOST_HAS_LONG_LONG -#if defined(linux) || defined(__linux) || defined(__linux__) -# define BOOST_HAS_STDINT_H -#endif // options --enable-test wants undefined #undef BOOST_NO_STDC_NAMESPACE @@ -52,11 +33,11 @@ #elif __PGIC__ >= 7 -#define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL +#define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL #define BOOST_NO_TWO_PHASE_NAME_LOOKUP #define BOOST_NO_SWPRINTF -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_AUTO_DECLARATIONS #else @@ -68,56 +49,28 @@ // // See boost\config\suffix.hpp for BOOST_NO_LONG_LONG // -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_NUMERIC_LIMITS -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_SWPRINTF -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_VARIADIC_MACROS -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX - -#define BOOST_NO_CXX11_HDR_UNORDERED_SET -#define BOOST_NO_CXX11_HDR_UNORDERED_MAP -#define BOOST_NO_CXX11_HDR_TYPEINDEX -#define BOOST_NO_CXX11_HDR_TYPE_TRAITS -#define BOOST_NO_CXX11_HDR_TUPLE -#define BOOST_NO_CXX11_HDR_THREAD -#define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -#define BOOST_NO_CXX11_HDR_REGEX -#define BOOST_NO_CXX11_HDR_RATIO -#define BOOST_NO_CXX11_HDR_RANDOM -#define BOOST_NO_CXX11_HDR_MUTEX -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_HDR_FUTURE -#define BOOST_NO_CXX11_HDR_FORWARD_LIST -#define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -#define BOOST_NO_CXX11_HDR_CODECVT -#define BOOST_NO_CXX11_HDR_CHRONO -#define BOOST_NO_CXX11_HDR_ARRAY -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS // // version check: diff --git a/utils/boost_idb/boost/config/compiler/sunpro_cc.hpp b/utils/boost_idb/boost/config/compiler/sunpro_cc.hpp index 486d5c43..85fa4625 100644 --- a/utils/boost_idb/boost/config/compiler/sunpro_cc.hpp +++ b/utils/boost_idb/boost/config/compiler/sunpro_cc.hpp @@ -1,10 +1,10 @@ -// (C) Copyright John Maddock 2001. -// (C) Copyright Jens Maurer 2001 - 2003. -// (C) Copyright Peter Dimov 2002. -// (C) Copyright Aleksey Gurtovoy 2002 - 2003. -// (C) Copyright David Abrahams 2002. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2001. +// (C) Copyright Jens Maurer 2001 - 2003. +// (C) Copyright Peter Dimov 2002. +// (C) Copyright Aleksey Gurtovoy 2002 - 2003. +// (C) Copyright David Abrahams 2002. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -34,7 +34,7 @@ # define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION # endif -# if (__SUNPRO_CC <= 0x530) +# if (__SUNPRO_CC <= 0x530) // Requesting debug info (-g) with Boost.Python results // in an internal compiler error for "static const" // initialized in-class. @@ -57,7 +57,7 @@ # define BOOST_NO_INTEGRAL_INT64_T # endif -# if (__SUNPRO_CC < 0x570) +# if (__SUNPRO_CC < 0x570) # define BOOST_NO_TEMPLATE_TEMPLATES // see http://lists.boost.org/MailArchives/boost/msg47184.php // and http://lists.boost.org/MailArchives/boost/msg47220.php @@ -65,7 +65,7 @@ # define BOOST_NO_SFINAE # define BOOST_NO_ARRAY_TYPE_SPECIALIZATIONS # endif -# if (__SUNPRO_CC <= 0x580) +# if (__SUNPRO_CC <= 0x580) # define BOOST_NO_IS_ABSTRACT # endif @@ -99,38 +99,30 @@ // # define BOOST_HAS_LONG_LONG -#define BOOST_NO_CXX11_AUTO_DECLARATIONS -#define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_RVALUE_REFERENCES -#define BOOST_NO_CXX11_SCOPED_ENUMS +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_STATIC_ASSERT -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#define BOOST_NO_CXX11_VARIADIC_MACROS -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS // // Version diff --git a/utils/boost_idb/boost/config/compiler/vacpp.hpp b/utils/boost_idb/boost/config/compiler/vacpp.hpp index 17c02f91..5ae9c285 100644 --- a/utils/boost_idb/boost/config/compiler/vacpp.hpp +++ b/utils/boost_idb/boost/config/compiler/vacpp.hpp @@ -1,10 +1,10 @@ -// (C) Copyright John Maddock 2001 - 2003. -// (C) Copyright Toon Knapen 2001 - 2003. -// (C) Copyright Lie-Quan Lee 2001. -// (C) Copyright Markus Schoepflin 2002 - 2003. -// (C) Copyright Beman Dawes 2002 - 2003. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Toon Knapen 2001 - 2003. +// (C) Copyright Lie-Quan Lee 2001. +// (C) Copyright Markus Schoepflin 2002 - 2003. +// (C) Copyright Beman Dawes 2002 - 2003. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. @@ -16,7 +16,7 @@ # define BOOST_NO_MEMBER_FUNCTION_SPECIALIZATIONS #endif -#if (__IBMCPP__ <= 502) +#if (__IBMCPP__ <= 502) // Actually the compiler supports inclass member initialization but it // requires a definition for the class member and it doesn't recognize // it as an integral constant expression when used as a template argument. @@ -27,12 +27,13 @@ #if (__IBMCPP__ <= 600) || !defined(BOOST_STRICT_CONFIG) # define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS +# define BOOST_NO_INITIALIZER_LISTS #endif #if (__IBMCPP__ <= 1110) -// XL C++ V11.1 and earlier versions may not always value-initialize -// a temporary object T(), when T is a non-POD aggregate class type. -// Michael Wong (IBM Canada Ltd) has confirmed this issue and gave it +// XL C++ V11.1 and earlier versions may not always value-initialize +// a temporary object T(), when T is a non-POD aggregate class type. +// Michael Wong (IBM Canada Ltd) has confirmed this issue and gave it // high priority. -- Niels Dekker (LKEB), May 2010. # define BOOST_NO_COMPLETE_VALUE_INITIALIZATION #endif @@ -53,79 +54,44 @@ #error "Compiler not supported or configured - please reconfigure" #endif // -// last known and checked version is 1210: -#if (__IBMCPP__ > 1210) +// last known and checked version is 600: +#if (__IBMCPP__ > 1010) # if defined(BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # endif #endif // Some versions of the compiler have issues with default arguments on partial specializations -#if __IBMCPP__ <= 1010 #define BOOST_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS -#endif // // C++0x features // // See boost\config\suffix.hpp for BOOST_NO_LONG_LONG // -#if ! __IBMCPP_AUTO_TYPEDEDUCTION -# define BOOST_NO_CXX11_AUTO_DECLARATIONS -# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -#endif -#if ! __IBMCPP_UTF_LITERAL__ -# define BOOST_NO_CXX11_CHAR16_T -# define BOOST_NO_CXX11_CHAR32_T -#endif -#if ! __IBMCPP_CONSTEXPR -# define BOOST_NO_CXX11_CONSTEXPR -#endif -#if ! __IBMCPP_DECLTYPE -# define BOOST_NO_CXX11_DECLTYPE -#else -# define BOOST_HAS_DECLTYPE -#endif -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -#define BOOST_NO_CXX11_DELETED_FUNCTIONS -#if ! __IBMCPP_EXPLICIT_CONVERSION_OPERATORS -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -#endif -#if ! __IBMCPP_EXTERN_TEMPLATE -# define BOOST_NO_CXX11_EXTERN_TEMPLATE -#endif -#if ! __IBMCPP_VARIADIC_TEMPLATES -// not enabled separately at this time -# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -#endif -#define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#define BOOST_NO_CXX11_LAMBDAS -#define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_NULLPTR -#define BOOST_NO_CXX11_RANGE_BASED_FOR -#define BOOST_NO_CXX11_RAW_LITERALS -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#if ! __IBMCPP_RVALUE_REFERENCES -# define BOOST_NO_CXX11_RVALUE_REFERENCES -#endif -#if ! __IBMCPP_SCOPED_ENUM -# define BOOST_NO_CXX11_SCOPED_ENUMS -#endif +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_EXTERN_TEMPLATE +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_NULLPTR +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#if ! __IBMCPP_STATIC_ASSERT -# define BOOST_NO_CXX11_STATIC_ASSERT -#endif -#define BOOST_NO_CXX11_TEMPLATE_ALIASES -#define BOOST_NO_CXX11_UNICODE_LITERALS -#if ! __IBMCPP_VARIADIC_TEMPLATES -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES -#endif -#if ! __C99_MACRO_WITH_VA_ARGS -# define BOOST_NO_CXX11_VARIADIC_MACROS -#endif -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -#define BOOST_NO_CXX11_INLINE_NAMESPACES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES +#define BOOST_NO_VARIADIC_MACROS + + + diff --git a/utils/boost_idb/boost/config/compiler/visualc.hpp b/utils/boost_idb/boost/config/compiler/visualc.hpp index 695fa943..6755287d 100644 --- a/utils/boost_idb/boost/config/compiler/visualc.hpp +++ b/utils/boost_idb/boost/config/compiler/visualc.hpp @@ -1,60 +1,88 @@ -// (C) Copyright John Maddock 2001 - 2003. -// (C) Copyright Darin Adler 2001 - 2002. -// (C) Copyright Peter Dimov 2001. -// (C) Copyright Aleksey Gurtovoy 2002. -// (C) Copyright David Abrahams 2002 - 2003. -// (C) Copyright Beman Dawes 2002 - 2003. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Darin Adler 2001 - 2002. +// (C) Copyright Peter Dimov 2001. +// (C) Copyright Aleksey Gurtovoy 2002. +// (C) Copyright David Abrahams 2002 - 2003. +// (C) Copyright Beman Dawes 2002 - 2003. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. -// + // Microsoft Visual C++ compiler setup: -// -// We need to be careful with the checks in this file, as contrary -// to popular belief there are versions with _MSC_VER with the final -// digit non-zero (mainly the MIPS cross compiler). -// -// So we either test _MSC_VER >= XXXX or else _MSC_VER < XXXX. -// No other comparisons (==, >, or <=) are safe. -// #define BOOST_MSVC _MSC_VER -// -// Helper macro BOOST_MSVC_FULL_VER for use in Boost code: -// #if _MSC_FULL_VER > 100000000 # define BOOST_MSVC_FULL_VER _MSC_FULL_VER #else # define BOOST_MSVC_FULL_VER (_MSC_FULL_VER * 10) #endif -// Attempt to suppress VC6 warnings about the length of decorated names (obsolete): +// turn off the warnings before we #include anything #pragma warning( disable : 4503 ) // warning: decorated name length exceeded -#define BOOST_HAS_PRAGMA_ONCE +#if _MSC_VER < 1300 // 1200 == VC++ 6.0, 1200-1202 == eVC++4 +# pragma warning( disable : 4786 ) // ident trunc to '255' chars in debug info +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +# define BOOST_NO_VOID_RETURNS +# define BOOST_NO_EXCEPTION_STD_NAMESPACE -// -// versions check: -// we don't support Visual C++ prior to version 7.1: -#if _MSC_VER < 1310 -# error "Compiler not supported or configured - please reconfigure" +# if BOOST_MSVC == 1202 +# define BOOST_NO_STD_TYPEINFO +# endif + + // disable min/max macro defines on vc6: + // #endif -#if _MSC_FULL_VER < 180020827 -# define BOOST_NO_FENV_H +#if (_MSC_VER <= 1300) // 1300 == VC++ 7.0 + +# if !defined(_MSC_EXTENSIONS) && !defined(BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS) // VC7 bug with /Za +# define BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS +# endif + +# define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS +# define BOOST_NO_INCLASS_MEMBER_INITIALIZATION +# define BOOST_NO_PRIVATE_IN_AGGREGATE +# define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP +# define BOOST_NO_INTEGRAL_INT64_T +# define BOOST_NO_DEDUCED_TYPENAME +# define BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE + +// VC++ 6/7 has member templates but they have numerous problems including +// cases of silent failure, so for safety we define: +# define BOOST_NO_MEMBER_TEMPLATES +// For VC++ experts wishing to attempt workarounds, we define: +# define BOOST_MSVC6_MEMBER_TEMPLATES + +# define BOOST_NO_MEMBER_TEMPLATE_FRIENDS +# define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION +# define BOOST_NO_CV_VOID_SPECIALIZATIONS +# define BOOST_NO_FUNCTION_TEMPLATE_ORDERING +# define BOOST_NO_USING_TEMPLATE +# define BOOST_NO_SWPRINTF +# define BOOST_NO_TEMPLATE_TEMPLATES +# define BOOST_NO_SFINAE +# define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS +# define BOOST_NO_IS_ABSTRACT +# define BOOST_NO_FUNCTION_TYPE_SPECIALIZATIONS +// TODO: what version is meant here? Have there really been any fixes in cl 12.01 (as e.g. shipped with eVC4)? +# if (_MSC_VER > 1200) +# define BOOST_NO_MEMBER_FUNCTION_SPECIALIZATIONS +# endif + #endif -#if _MSC_VER < 1400 +#if _MSC_VER < 1400 // although a conforming signature for swprint exists in VC7.1 // it appears not to actually work: # define BOOST_NO_SWPRINTF // Our extern template tests also fail for this compiler: -# define BOOST_NO_CXX11_EXTERN_TEMPLATE +# define BOOST_NO_EXTERN_TEMPLATE // Variadic macros do not exist for VC7.1 and lower -# define BOOST_NO_CXX11_VARIADIC_MACROS +# define BOOST_NO_VARIADIC_MACROS #endif #if defined(UNDER_CE) @@ -62,19 +90,24 @@ # define BOOST_NO_SWPRINTF #endif -#if _MSC_VER < 1500 // 140X == VC++ 8.0 +#if _MSC_VER <= 1400 // 1400 == VC++ 8.0 # define BOOST_NO_MEMBER_TEMPLATE_FRIENDS #endif -#if _MSC_VER < 1600 // 150X == VC++ 9.0 +#if _MSC_VER <= 1600 // 1600 == VC++ 10.0 +# define BOOST_NO_TWO_PHASE_NAME_LOOKUP +#endif + +#if _MSC_VER == 1500 // 1500 == VC++ 9.0 // A bug in VC9: # define BOOST_NO_ADL_BARRIER #endif -// MSVC (including the latest checked version) has not yet completely +#if (_MSC_VER <= 1600) +// MSVC (including the latest checked version) has not yet completely // implemented value-initialization, as is reported: -// "VC++ does not value-initialize members of derived classes without +// "VC++ does not value-initialize members of derived classes without // user-declared constructor", reported in 2009 by Sylvester Hesp: // https://connect.microsoft.com/VisualStudio/feedback/details/484295 // "Presence of copy constructor breaks member class initialization", @@ -85,33 +118,36 @@ // https://connect.microsoft.com/VisualStudio/feedback/details/100744 // See also: http://www.boost.org/libs/utility/value_init.htm#compiler_issues // (Niels Dekker, LKEB, May 2010) -# define BOOST_NO_COMPLETE_VALUE_INITIALIZATION +#define BOOST_NO_COMPLETE_VALUE_INITIALIZATION +#endif + +#if _MSC_VER <= 1500 || !defined(BOOST_STRICT_CONFIG) // 1500 == VC++ 9.0 +# define BOOST_NO_INITIALIZER_LISTS +#endif #ifndef _NATIVE_WCHAR_T_DEFINED # define BOOST_NO_INTRINSIC_WCHAR_T #endif #if defined(_WIN32_WCE) || defined(UNDER_CE) +# define BOOST_NO_THREADEX +# define BOOST_NO_GETSYSTEMTIMEASFILETIME # define BOOST_NO_SWPRINTF #endif -// we have ThreadEx or GetSystemTimeAsFileTime unless we're running WindowsCE -#if !defined(_WIN32_WCE) && !defined(UNDER_CE) -# define BOOST_HAS_THREADEX -# define BOOST_HAS_GETSYSTEMTIMEASFILETIME -#endif - -// -// check for exception handling support: +// +// check for exception handling support: #if !defined(_CPPUNWIND) && !defined(BOOST_NO_EXCEPTIONS) -# define BOOST_NO_EXCEPTIONS -#endif +# define BOOST_NO_EXCEPTIONS +#endif // // __int64 support: // -#define BOOST_HAS_MS_INT64 -#if defined(_MSC_EXTENSIONS) || (_MSC_VER >= 1400) +#if (_MSC_VER >= 1200) +# define BOOST_HAS_MS_INT64 +#endif +#if (_MSC_VER >= 1310) && (defined(_MSC_EXTENSIONS) || (_MSC_VER >= 1400)) # define BOOST_HAS_LONG_LONG #else # define BOOST_NO_LONG_LONG @@ -130,16 +166,6 @@ # define BOOST_NO_RTTI #endif -// -// TR1 features: -// -#if _MSC_VER >= 1700 -// # define BOOST_HAS_TR1_HASH // don't know if this is true yet. -// # define BOOST_HAS_TR1_TYPE_TRAITS // don't know if this is true yet. -# define BOOST_HAS_TR1_UNORDERED_MAP -# define BOOST_HAS_TR1_UNORDERED_SET -#endif - // // C++0x features // @@ -148,53 +174,34 @@ // C++ features supported by VC++ 10 (aka 2010) // #if _MSC_VER < 1600 -# define BOOST_NO_CXX11_AUTO_DECLARATIONS -# define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS -# define BOOST_NO_CXX11_LAMBDAS -# define BOOST_NO_CXX11_RVALUE_REFERENCES -# define BOOST_NO_CXX11_STATIC_ASSERT -# define BOOST_NO_CXX11_NULLPTR -# define BOOST_NO_CXX11_DECLTYPE +#define BOOST_NO_AUTO_DECLARATIONS +#define BOOST_NO_AUTO_MULTIDECLARATIONS +#define BOOST_NO_LAMBDAS +#define BOOST_NO_RVALUE_REFERENCES +#define BOOST_NO_STATIC_ASSERT +#define BOOST_NO_NULLPTR #endif // _MSC_VER < 1600 - #if _MSC_VER >= 1600 -# define BOOST_HAS_STDINT_H +#define BOOST_HAS_STDINT_H #endif -// C++11 features supported by VC++ 11 (aka 2012) -// -#if _MSC_VER < 1700 -# define BOOST_NO_CXX11_RANGE_BASED_FOR -# define BOOST_NO_CXX11_SCOPED_ENUMS -#endif // _MSC_VER < 1700 - -// C++11 features supported by VC++ 12 (aka 2013). -// -#if _MSC_FULL_VER < 180020827 -# define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS -# define BOOST_NO_CXX11_DELETED_FUNCTIONS -# define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS -# define BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS -# define BOOST_NO_CXX11_RAW_LITERALS -# define BOOST_NO_CXX11_TEMPLATE_ALIASES -# define BOOST_NO_CXX11_TRAILING_RESULT_TYPES -# define BOOST_NO_CXX11_VARIADIC_TEMPLATES -# define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX -#endif - -// C++11 features not supported by any versions -#define BOOST_NO_CXX11_CHAR16_T -#define BOOST_NO_CXX11_CHAR32_T -#define BOOST_NO_CXX11_CONSTEXPR -#define BOOST_NO_CXX11_DECLTYPE_N3276 -#define BOOST_NO_CXX11_NOEXCEPT -#define BOOST_NO_CXX11_UNICODE_LITERALS +// C++0x features not supported by any versions +#define BOOST_NO_CHAR16_T +#define BOOST_NO_CHAR32_T +#define BOOST_NO_CONCEPTS +#define BOOST_NO_CONSTEXPR +#define BOOST_NO_DEFAULTED_FUNCTIONS +#define BOOST_NO_DECLTYPE +#define BOOST_NO_DELETED_FUNCTIONS +#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS +#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS +#define BOOST_NO_INITIALIZER_LISTS +#define BOOST_NO_RAW_LITERALS +#define BOOST_NO_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR -#define BOOST_NO_TWO_PHASE_NAME_LOOKUP -#define BOOST_NO_CXX11_USER_DEFINED_LITERALS -#define BOOST_NO_CXX11_ALIGNAS -#define BOOST_NO_CXX11_INLINE_NAMESPACES - +#define BOOST_NO_TEMPLATE_ALIASES +#define BOOST_NO_UNICODE_LITERALS +#define BOOST_NO_VARIADIC_TEMPLATES // // prefix and suffix headers: // @@ -205,31 +212,23 @@ # define BOOST_ABI_SUFFIX "boost/config/abi/msvc_suffix.hpp" #endif -#ifndef BOOST_COMPILER // TODO: -// these things are mostly bogus. 1200 means version 12.0 of the compiler. The +// these things are mostly bogus. 1200 means version 12.0 of the compiler. The // artificial versions assigned to them only refer to the versions of some IDE // these compilers have been shipped with, and even that is not all of it. Some // were shipped with freely downloadable SDKs, others as crosscompilers in eVC. // IOW, you can't use these 'versions' in any sensible way. Sorry. # if defined(UNDER_CE) -# if _MSC_VER < 1400 - // Note: I'm not aware of any CE compiler with version 13xx -# if defined(BOOST_ASSERT_CONFIG) -# error "Unknown EVC++ compiler version - please run the configure tests and report the results" -# else -# pragma message("Unknown EVC++ compiler version - please run the configure tests and report the results") -# endif -# elif _MSC_VER < 1500 +# if _MSC_VER < 1200 + // Note: these are so far off, they are not really supported +# elif _MSC_VER < 1300 // eVC++ 4 comes with 1200-1202 +# define BOOST_COMPILER_VERSION evc4.0 +# elif _MSC_VER == 1400 # define BOOST_COMPILER_VERSION evc8 -# elif _MSC_VER < 1600 +# elif _MSC_VER == 1500 # define BOOST_COMPILER_VERSION evc9 -# elif _MSC_VER < 1700 +# elif _MSC_VER == 1600 # define BOOST_COMPILER_VERSION evc10 -# elif _MSC_VER < 1800 -# define BOOST_COMPILER_VERSION evc11 -# elif _MSC_VER < 1900 -# define BOOST_COMPILER_VERSION evc12 # else # if defined(BOOST_ASSERT_CONFIG) # error "Unknown EVC++ compiler version - please run the configure tests and report the results" @@ -238,36 +237,37 @@ # endif # endif # else -# if _MSC_VER < 1310 - // Note: Versions up to 7.0 aren't supported. +# if _MSC_VER < 1200 + // Note: these are so far off, they are not really supported # define BOOST_COMPILER_VERSION 5.0 # elif _MSC_VER < 1300 -# define BOOST_COMPILER_VERSION 6.0 -# elif _MSC_VER < 1310 +# define BOOST_COMPILER_VERSION 6.0 +# elif _MSC_VER == 1300 # define BOOST_COMPILER_VERSION 7.0 -# elif _MSC_VER < 1400 +# elif _MSC_VER == 1310 # define BOOST_COMPILER_VERSION 7.1 -# elif _MSC_VER < 1500 +# elif _MSC_VER == 1400 # define BOOST_COMPILER_VERSION 8.0 -# elif _MSC_VER < 1600 +# elif _MSC_VER == 1500 # define BOOST_COMPILER_VERSION 9.0 -# elif _MSC_VER < 1700 +# elif _MSC_VER == 1600 # define BOOST_COMPILER_VERSION 10.0 -# elif _MSC_VER < 1800 -# define BOOST_COMPILER_VERSION 11.0 -# elif _MSC_VER < 1900 -# define BOOST_COMPILER_VERSION 12.0 # else # define BOOST_COMPILER_VERSION _MSC_VER # endif # endif -# define BOOST_COMPILER "Microsoft Visual C++ version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) -#endif +#define BOOST_COMPILER "Microsoft Visual C++ version " BOOST_STRINGIZE(BOOST_COMPILER_VERSION) // -// last known and checked version is 18.00.20827.3 (VC12 RC, aka 2013 RC): -#if (_MSC_VER > 1800 && _MSC_FULL_VER > 180020827) +// versions check: +// we don't support Visual C++ prior to version 6: +#if _MSC_VER < 1200 +#error "Compiler not supported or configured - please reconfigure" +#endif +// +// last known and checked version is 1600 (VC10, aka 2010): +#if (_MSC_VER > 1600) # if defined(BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # else diff --git a/utils/boost_idb/boost/config/platform/cray.hpp b/utils/boost_idb/boost/config/platform/cray.hpp deleted file mode 100644 index 5c476e41..00000000 --- a/utils/boost_idb/boost/config/platform/cray.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// (C) Copyright John Maddock 2011. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - -// See http://www.boost.org for most recent version. - -// SGI Irix specific config options: - -#define BOOST_PLATFORM "Cray" - -// boilerplate code: -#define BOOST_HAS_UNISTD_H -#include - - - diff --git a/utils/boost_idb/boost/config/platform/cygwin.hpp b/utils/boost_idb/boost/config/platform/cygwin.hpp index b7ef572f..8e1bcb01 100644 --- a/utils/boost_idb/boost/config/platform/cygwin.hpp +++ b/utils/boost_idb/boost/config/platform/cygwin.hpp @@ -39,9 +39,6 @@ #define BOOST_HAS_STDINT_H #endif -/// Cygwin has no fenv.h -#define BOOST_NO_FENV_H - // boilerplate code: #include diff --git a/utils/boost_idb/boost/config/platform/linux.hpp b/utils/boost_idb/boost/config/platform/linux.hpp index a02aff78..51ae1334 100644 --- a/utils/boost_idb/boost/config/platform/linux.hpp +++ b/utils/boost_idb/boost/config/platform/linux.hpp @@ -11,11 +11,7 @@ #define BOOST_PLATFORM "linux" // make sure we have __GLIBC_PREREQ if available at all -#ifdef __cplusplus #include -#else -#include -#endif // // added to glibc 2.1.1 @@ -72,7 +68,6 @@ // boilerplate code: #define BOOST_HAS_UNISTD_H #include -#define BOOST_HAS_PTHREAD_YIELD #ifndef __GNUC__ // diff --git a/utils/boost_idb/boost/config/platform/macos.hpp b/utils/boost_idb/boost/config/platform/macos.hpp index 6d876b12..2780ef99 100644 --- a/utils/boost_idb/boost/config/platform/macos.hpp +++ b/utils/boost_idb/boost/config/platform/macos.hpp @@ -64,17 +64,16 @@ # if ( defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON ) || ( defined(TARGET_CARBON) && TARGET_CARBON ) # if !defined(BOOST_HAS_PTHREADS) -// MPTasks support is deprecated/removed from Boost: -//# define BOOST_HAS_MPTASKS +# define BOOST_HAS_MPTASKS # elif ( __dest_os == __mac_os_x ) // We are doing a Carbon/Mach-O/MSL build which has pthreads, but only the // gettimeofday and no posix. # define BOOST_HAS_GETTIMEOFDAY # endif -#ifdef BOOST_HAS_PTHREADS -# define BOOST_HAS_THREADS -#endif +// The MP task implementation of Boost Threads aims to replace MP-unsafe +// parts of the MSL, so we turn on threads unconditionally. +# define BOOST_HAS_THREADS // The remote call manager depends on this. # define BOOST_BIND_ENABLE_PASCAL diff --git a/utils/boost_idb/boost/config/platform/symbian.hpp b/utils/boost_idb/boost/config/platform/symbian.hpp index e02a7782..ad379431 100644 --- a/utils/boost_idb/boost/config/platform/symbian.hpp +++ b/utils/boost_idb/boost/config/platform/symbian.hpp @@ -18,11 +18,8 @@ // Open C / C++ plugin was introdused in this SDK, earlier versions don't have CRT / STL # define BOOST_S60_3rd_EDITION_FP2_OR_LATER_SDK // make sure we have __GLIBC_PREREQ if available at all -#ifdef __cplusplus -#include -#else -#include -#endif// boilerplate code: +# include +// boilerplate code: # define BOOST_HAS_UNISTD_H # include // S60 SDK defines _POSIX_VERSION as POSIX.1 diff --git a/utils/boost_idb/boost/config/platform/vxworks.hpp b/utils/boost_idb/boost/config/platform/vxworks.hpp index cdda0158..6ec5171e 100644 --- a/utils/boost_idb/boost/config/platform/vxworks.hpp +++ b/utils/boost_idb/boost/config/platform/vxworks.hpp @@ -1,369 +1,31 @@ -// (C) Copyright Dustin Spicuzza 2009. -// Adapted to vxWorks 6.9 by Peter Brockamp 2012. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file +// (C) Copyright Dustin Spicuzza 2009. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. -// Since WRS does not yet properly support boost under vxWorks -// and this file was badly outdated, but I was keen on using it, -// I patched boost myself to make things work. This has been tested -// and adapted by me for vxWorks 6.9 *only*, as I'm lacking access -// to earlier 6.X versions! The only thing I know for sure is that -// very old versions of vxWorks (namely everything below 6.x) are -// absolutely unable to use boost. This is mainly due to the completely -// outdated libraries and ancient compiler (GCC 2.96 or worse). Do -// not even think of getting this to work, a miserable failure will -// be guaranteed! -// Equally, this file has been tested for RTPs (Real Time Processes) -// only, not for DKMs (Downloadable Kernel Modules). These two types -// of executables differ largely in the available functionality of -// the C-library, STL, and so on. A DKM uses a library similar to those -// of vxWorks 5.X - with all its limitations and incompatibilities -// with respect to ANSI C++ and STL. So probably there might be problems -// with the usage of boost from DKMs. WRS or any voluteers are free to -// prove the opposite! +// vxWorks specific config options: -// ==================================================================== -// -// Some important information regarding the usage of POSIX semaphores: -// ------------------------------------------------------------------- -// -// VxWorks as a real time operating system handles threads somewhat -// different from what "normal" OSes do, regarding their scheduling! -// This could lead to a scenario called "priority inversion" when using -// semaphores, see http://en.wikipedia.org/wiki/Priority_inversion. -// -// Now, VxWorks POSIX-semaphores for DKM's default to the usage of -// priority inverting semaphores, which is fine. On the other hand, -// for RTP's it defaults to using non priority inverting semaphores, -// which could easily pose a serious problem for a real time process, -// i.e. deadlocks! To overcome this two possibilities do exist: -// -// a) Patch every piece of boost that uses semaphores to instanciate -// the proper type of semaphores. This is non-intrusive with respect -// to the OS and could relatively easy been done by giving all -// semaphores attributes deviating from the default (for in-depth -// information see the POSIX functions pthread_mutexattr_init() -// and pthread_mutexattr_setprotocol()). However this breaks all -// too easily, as with every new version some boost library could -// all in a sudden start using semaphores, resurrecting the very -// same, hard to locate problem over and over again! -// -// b) We could change the default properties for POSIX-semaphores -// that VxWorks uses for RTP's and this is being suggested here, -// as it will more or less seamlessly integrate with boost. I got -// the following information from WRS how to do this, compare -// Wind River TSR# 1209768: -// -// Instructions for changing the default properties of POSIX- -// semaphores for RTP's in VxWorks 6.9: -// - Edit the file /vxworks-6.9/target/usr/src/posix/pthreadLib.c -// in the root of your Workbench-installation. -// - Around line 917 there should be the definition of the default -// mutex attributes: -// -// LOCAL pthread_mutexattr_t defaultMutexAttr = -// { -// PTHREAD_INITIALIZED_OBJ, PTHREAD_PRIO_NONE, 0, -// PTHREAD_MUTEX_DEFAULT -// }; -// -// Here, replace PTHREAD_PRIO_NONE by PTHREAD_PRIO_INHERIT. -// - Around line 1236 there should be a definition for the function -// pthread_mutexattr_init(). A couple of lines below you should -// find a block of code like this: -// -// pAttr->mutexAttrStatus = PTHREAD_INITIALIZED_OBJ; -// pAttr->mutexAttrProtocol = PTHREAD_PRIO_NONE; -// pAttr->mutexAttrPrioceiling = 0; -// pAttr->mutexAttrType = PTHREAD_MUTEX_DEFAULT; -// -// Here again, replace PTHREAD_PRIO_NONE by PTHREAD_PRIO_INHERIT. -// - Finally, rebuild your VSB. This will create a new VxWorks kernel -// with the changed properties. That's it! Now, using boost should -// no longer cause any problems with task deadlocks! -// -// And here's another useful piece of information concerning VxWorks' -// POSIX-functionality in general: -// VxWorks is not a genuine POSIX-OS in itself, rather it is using a -// kind of compatibility layer (sort of a wrapper) to emulate the -// POSIX-functionality by using its own resources and functions. -// At the time a task (thread) calls it's first POSIX-function during -// runtime it is being transformed by the OS into a POSIX-thread. -// This transformation does include a call to malloc() to allocate the -// memory required for the housekeeping of POSIX-threads. In a high -// priority RTP this malloc() call may be highly undesirable, as its -// timing is more or less unpredictable (depending on what your actual -// heap looks like). You can circumvent this problem by calling the -// function thread_self() at a well defined point in the code of the -// task, e.g. shortly after the task spawns up. Thereby you are able -// to define the time when the task-transformation will take place and -// you could shift it to an uncritical point where a malloc() call is -// tolerable. So, if this could pose a problem for your code, remember -// to call thread_self() from the affected task at an early stage. -// -// ==================================================================== - -// Block out all versions before vxWorks 6.x, as these don't work: -// Include header with the vxWorks version information and query them -#include -#if !defined(_WRS_VXWORKS_MAJOR) || (_WRS_VXWORKS_MAJOR < 6) -# error "The vxWorks version you're using is so badly outdated,\ - it doesn't work at all with boost, sorry, no chance!" -#endif - -// Handle versions above 5.X but below 6.9 -#if (_WRS_VXWORKS_MAJOR == 6) && (_WRS_VXWORKS_MINOR < 9) -// TODO: Starting from what version does vxWorks work with boost? -// We can't reasonably insert a #warning "" as a user hint here, -// as this will show up with every file including some boost header, -// badly bugging the user... So for the time being we just leave it. -#endif - -// vxWorks specific config options: -// -------------------------------- #define BOOST_PLATFORM "vxWorks" -// Special behaviour for DKMs: -#ifdef _WRS_KERNEL - // DKMs do not have the -header, - // but apparently they do have an intrinsic wchar_t meanwhile! -# define BOOST_NO_CWCHAR +#define BOOST_NO_CWCHAR +#define BOOST_NO_INTRINSIC_WCHAR_T - // Lots of wide-functions and -headers are unavailable for DKMs as well: -# define BOOST_NO_CWCTYPE -# define BOOST_NO_SWPRINTF -# define BOOST_NO_STD_WSTRING -# define BOOST_NO_STD_WSTREAMBUF +#if defined(__GNUC__) && defined(__STRICT_ANSI__) +#define BOOST_NO_INT64_T #endif -// Generally available headers: #define BOOST_HAS_UNISTD_H -#define BOOST_HAS_STDINT_H -#define BOOST_HAS_DIRENT_H -#define BOOST_HAS_SLIST - -// vxWorks does not have installed an iconv-library by default, -// so unfortunately no Unicode support from scratch is available! -// Thus, instead it is suggested to switch to ICU, as this seems -// to be the most complete and portable option... -#define BOOST_LOCALE_WITH_ICU - -// Generally available functionality: -#define BOOST_HAS_THREADS -#define BOOST_HAS_NANOSLEEP -#define BOOST_HAS_GETTIMEOFDAY -#define BOOST_HAS_CLOCK_GETTIME -#define BOOST_HAS_MACRO_USE_FACET - -// Generally unavailable functionality, delivered by boost's test function: -//#define BOOST_NO_DEDUCED_TYPENAME // Commented this out, boost's test gives an errorneous result! -#define BOOST_NO_CXX11_EXTERN_TEMPLATE -#define BOOST_NO_CXX11_VARIADIC_MACROS - -// Generally available threading API's: -#define BOOST_HAS_PTHREADS -#define BOOST_HAS_SCHED_YIELD -#define BOOST_HAS_SIGACTION - -// Functionality available for RTPs only: -#ifdef __RTP__ -# define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE -# define BOOST_HAS_LOG1P -# define BOOST_HAS_EXPM1 -#endif -// Functionality available for DKMs only: -#ifdef _WRS_KERNEL - // Luckily, at the moment there seems to be none! -#endif +// these allow posix_features to work, since vxWorks doesn't +// define them itself +#define _POSIX_TIMERS 1 +#define _POSIX_THREADS 1 -// These #defines allow posix_features to work, since vxWorks doesn't -// #define them itself for DKMs (for RTPs on the contrary it does): -#ifdef _WRS_KERNEL -# ifndef _POSIX_TIMERS -# define _POSIX_TIMERS 1 -# endif -# ifndef _POSIX_THREADS -# define _POSIX_THREADS 1 -# endif -#endif - -// vxWorks doesn't work with asio serial ports: +// vxworks doesn't work with asio serial ports #define BOOST_ASIO_DISABLE_SERIAL_PORT -// TODO: The problem here seems to bee that vxWorks uses its own, very specific -// ways to handle serial ports, incompatible with POSIX or anything... -// Maybe a specific implementation would be possible, but until the -// straight need arises... This implementation would presumably consist -// of some vxWorks specific ioctl-calls, etc. Any voluteers? - -// vxWorks-around: #defines CLOCKS_PER_SEC as sysClkRateGet() but -// miserably fails to #include the required to make -// sysClkRateGet() available! So we manually include it here. -#ifdef __RTP__ -# include -# include -#endif - -// vxWorks-around: In the macros INT32_C(), UINT32_C(), INT64_C() and -// UINT64_C() are defined errorneously, yielding not a signed/ -// unsigned long/long long type, but a signed/unsigned int/long -// type. Eventually this leads to compile errors in ratio_fwd.hpp, -// when trying to define several constants which do not fit into a -// long type! We correct them here by redefining. -#include - -// Some macro-magic to do the job -#define VX_JOIN(X, Y) VX_DO_JOIN(X, Y) -#define VX_DO_JOIN(X, Y) VX_DO_JOIN2(X, Y) -#define VX_DO_JOIN2(X, Y) X##Y - -// Correctly setup the macros -#undef INT32_C -#undef UINT32_C -#undef INT64_C -#undef UINT64_C -#define INT32_C(x) VX_JOIN(x, L) -#define UINT32_C(x) VX_JOIN(x, UL) -#define INT64_C(x) VX_JOIN(x, LL) -#define UINT64_C(x) VX_JOIN(x, ULL) - -// #include Libraries required for the following function adaption -#include -#include -#include -// Use C-linkage for the following helper functions -extern "C" { - -// vxWorks-around: The required functions getrlimit() and getrlimit() are missing. -// But we have the similar functions getprlimit() and setprlimit(), -// which may serve the purpose. -// Problem: The vxWorks-documentation regarding these functions -// doesn't deserve its name! It isn't documented what the first two -// parameters idtype and id mean, so we must fall back to an educated -// guess - null, argh... :-/ - -// TODO: getprlimit() and setprlimit() do exist for RTPs only, for whatever reason. -// Thus for DKMs there would have to be another implementation. -#ifdef __RTP__ - inline int getrlimit(int resource, struct rlimit *rlp){ - return getprlimit(0, 0, resource, rlp); - } - - inline int setrlimit(int resource, const struct rlimit *rlp){ - return setprlimit(0, 0, resource, const_cast(rlp)); - } -#endif - -// vxWorks has ftruncate() only, so we do simulate truncate(): -inline int truncate(const char *p, off_t l){ - int fd = open(p, O_WRONLY); - if (fd == -1){ - errno = EACCES; - return -1; - } - if (ftruncate(fd, l) == -1){ - close(fd); - errno = EACCES; - return -1; - } - return close(fd); -} - -// Fake symlink handling by dummy functions: -inline int symlink(const char*, const char*){ - // vxWorks has no symlinks -> always return an error! - errno = EACCES; - return -1; -} - -inline ssize_t readlink(const char*, char*, size_t){ - // vxWorks has no symlinks -> always return an error! - errno = EACCES; - return -1; -} - -// vxWorks claims to implement gettimeofday in sys/time.h -// but nevertheless does not provide it! See -// https://support.windriver.com/olsPortal/faces/maintenance/techtipDetail_noHeader.jspx?docId=16442&contentId=WR_TECHTIP_006256 -// We implement a surrogate version here via clock_gettime: -inline int gettimeofday(struct timeval *tv, void * /*tzv*/) { - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - tv->tv_sec = ts.tv_sec; - tv->tv_usec = ts.tv_nsec / 1000; - return 0; -} - -// vxWorks does provide neither struct tms nor function times()! -// We implement an empty dummy-function, simply setting the user -// and system time to the half of thew actual system ticks-value -// and the child user and system time to 0. -// Rather ugly but at least it suppresses compiler errors... -// Unfortunately, this of course *does* have an severe impact on -// dependant libraries, actually this is chrono only! Here it will -// not be possible to correctly use user and system times! But -// as vxWorks is lacking the ability to calculate user and system -// process times there seems to be no other possible solution. -struct tms{ - clock_t tms_utime; // User CPU time - clock_t tms_stime; // System CPU time - clock_t tms_cutime; // User CPU time of terminated child processes - clock_t tms_cstime; // System CPU time of terminated child processes -}; - -inline clock_t times(struct tms *t){ - struct timespec ts; - clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts); - clock_t ticks(static_cast(static_cast(ts.tv_sec) * CLOCKS_PER_SEC + - static_cast(ts.tv_nsec) * CLOCKS_PER_SEC / 1000000.0)); - t->tms_utime = ticks/2U; - t->tms_stime = ticks/2U; - t->tms_cutime = 0; // vxWorks is lacking the concept of a child process! - t->tms_cstime = 0; // -> Set the wait times for childs to 0 - return ticks; -} - -} // extern "C" - -// Put the selfmade functions into the std-namespace, just in case -namespace std { -# ifdef __RTP__ - using ::getrlimit; - using ::setrlimit; -# endif - using ::truncate; - using ::symlink; - using ::readlink; - using ::times; - using ::gettimeofday; -} - -// Some more macro-magic: -// vxWorks-around: Some functions are not present or broken in vxWorks -// but may be patched to life via helper macros... - -// Include signal.h which might contain a typo to be corrected here -#include - -#define getpagesize() sysconf(_SC_PAGESIZE) // getpagesize is deprecated anyway! -#ifndef S_ISSOCK -# define S_ISSOCK(mode) ((mode & S_IFMT) == S_IFSOCK) // Is file a socket? -#endif -#define lstat(p, b) stat(p, b) // lstat() == stat(), as vxWorks has no symlinks! -#ifndef FPE_FLTINV -# define FPE_FLTINV (FPE_FLTSUB+1) // vxWorks has no FPE_FLTINV, so define one as a dummy -#endif -#if !defined(BUS_ADRALN) && defined(BUS_ADRALNR) -# define BUS_ADRALN BUS_ADRALNR // Correct a supposed typo in vxWorks' -#endif -//typedef int locale_t; // locale_t is a POSIX-extension, currently unpresent in vxWorks! - -// #include boilerplate code: +// boilerplate code: #include - -// vxWorks lies about XSI conformance, there is no nl_types.h: -#undef BOOST_HAS_NL_TYPES_H + diff --git a/utils/boost_idb/boost/config/platform/win32.hpp b/utils/boost_idb/boost/config/platform/win32.hpp index 6ab59f4e..f59c4ea7 100644 --- a/utils/boost_idb/boost/config/platform/win32.hpp +++ b/utils/boost_idb/boost/config/platform/win32.hpp @@ -31,20 +31,14 @@ # define BOOST_SYMBOL_IMPORT __declspec(dllimport) #endif + #if defined(__MINGW32__) && ((__MINGW32_MAJOR_VERSION > 2) || ((__MINGW32_MAJOR_VERSION == 2) && (__MINGW32_MINOR_VERSION >= 0))) # define BOOST_HAS_STDINT_H -# ifndef __STDC_LIMIT_MACROS -# define __STDC_LIMIT_MACROS -# endif +# define __STDC_LIMIT_MACROS # define BOOST_HAS_DIRENT_H # define BOOST_HAS_UNISTD_H #endif -#if defined(__MINGW32__) && (__GNUC__ >= 4) -# define BOOST_HAS_EXPM1 -# define BOOST_HAS_LOG1P -# define BOOST_HAS_GETTIMEOFDAY -#endif // // Win32 will normally be using native Win32 threads, // but there is a pthread library avaliable as an option, @@ -57,8 +51,6 @@ #ifdef _WIN32_WCE # define BOOST_NO_ANSI_APIS -#else -# define BOOST_HAS_GETSYSTEMTIMEASFILETIME #endif #ifndef BOOST_HAS_PTHREADS diff --git a/utils/boost_idb/boost/config/select_compiler_config.hpp b/utils/boost_idb/boost/config/select_compiler_config.hpp index 0eeb7ad3..f9b086ad 100644 --- a/utils/boost_idb/boost/config/select_compiler_config.hpp +++ b/utils/boost_idb/boost/config/select_compiler_config.hpp @@ -10,35 +10,46 @@ // See http://www.boost.org/ for most recent version. -// locate which compiler we are using and define -// BOOST_COMPILER_CONFIG as needed: -#if defined __CUDACC__ -// NVIDIA CUDA C++ compiler for GPU -# include "boost/config/compiler/nvcc.hpp" +// one identification macro for each of the +// compilers we support: + +# define BOOST_CXX_GCCXML 0 +# define BOOST_CXX_CLANG 0 +# define BOOST_CXX_COMO 0 +# define BOOST_CXX_DMC 0 +# define BOOST_CXX_INTEL 0 +# define BOOST_CXX_GNUC 0 +# define BOOST_CXX_KCC 0 +# define BOOST_CXX_SGI 0 +# define BOOST_CXX_TRU64 0 +# define BOOST_CXX_GHS 0 +# define BOOST_CXX_BORLAND 0 +# define BOOST_CXX_CW 0 +# define BOOST_CXX_SUNPRO 0 +# define BOOST_CXX_HPACC 0 +# define BOOST_CXX_MPW 0 +# define BOOST_CXX_IBMCPP 0 +# define BOOST_CXX_MSVC 0 +# define BOOST_CXX_PGI 0 +# define BOOST_CXX_NVCC 0 -#endif + +// locate which compiler we are using and define +// BOOST_COMPILER_CONFIG as needed: #if defined(__GCCXML__) // GCC-XML emulates other compilers, it has to appear first here! # define BOOST_COMPILER_CONFIG "boost/config/compiler/gcc_xml.hpp" -#elif defined(_CRAYC) -// EDG based Cray compiler: -# define BOOST_COMPILER_CONFIG "boost/config/compiler/cray.hpp" +#elif defined __CUDACC__ +// NVIDIA CUDA C++ compiler for GPU +# define BOOST_COMPILER_CONFIG "boost/config/compiler/nvcc.hpp" #elif defined __COMO__ // Comeau C++ # define BOOST_COMPILER_CONFIG "boost/config/compiler/comeau.hpp" -#elif defined(__PATHSCALE__) && (__PATHCC__ >= 4) -// PathScale EKOPath compiler (has to come before clang and gcc) -# define BOOST_COMPILER_CONFIG "boost/config/compiler/pathscale.hpp" - -#elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) -// Intel -# define BOOST_COMPILER_CONFIG "boost/config/compiler/intel.hpp" - #elif defined __clang__ // Clang C++ emulates GCC, so it has to appear early. # define BOOST_COMPILER_CONFIG "boost/config/compiler/clang.hpp" @@ -47,6 +58,10 @@ // Digital Mars C++ # define BOOST_COMPILER_CONFIG "boost/config/compiler/digitalmars.hpp" +#elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) +// Intel +# define BOOST_COMPILER_CONFIG "boost/config/compiler/intel.hpp" + # elif defined __GNUC__ // GNU C++: # define BOOST_COMPILER_CONFIG "boost/config/compiler/gcc.hpp" diff --git a/utils/boost_idb/boost/config/select_platform_config.hpp b/utils/boost_idb/boost/config/select_platform_config.hpp index 2af61d2d..bc1ffaf6 100644 --- a/utils/boost_idb/boost/config/select_platform_config.hpp +++ b/utils/boost_idb/boost/config/select_platform_config.hpp @@ -13,7 +13,7 @@ // in order to prevent macro expansion within the header // name (for example "linux" is a macro on linux systems). -#if (defined(linux) || defined(__linux) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)) && !defined(_CRAYC) +#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) // linux, also other platforms (Hurd etc) that use GLIBC, should these really have their own config headers though? # define BOOST_PLATFORM_CONFIG "boost/config/platform/linux.hpp" @@ -69,10 +69,6 @@ // Symbian: # define BOOST_PLATFORM_CONFIG "boost/config/platform/symbian.hpp" -#elif defined(_CRAYC) -// Cray: -# define BOOST_PLATFORM_CONFIG "boost/config/platform/cray.hpp" - #elif defined(__VMS) // VMS: # define BOOST_PLATFORM_CONFIG "boost/config/platform/vms.hpp" diff --git a/utils/boost_idb/boost/config/select_stdlib_config.hpp b/utils/boost_idb/boost/config/select_stdlib_config.hpp index 96ede002..2a1430ae 100644 --- a/utils/boost_idb/boost/config/select_stdlib_config.hpp +++ b/utils/boost_idb/boost/config/select_stdlib_config.hpp @@ -14,11 +14,7 @@ // First include to determine if some version of STLport is in use as the std lib // (do not rely on this header being included since users can short-circuit this header // if they know whose std lib they are using.) -#ifdef __cplusplus -# include -#else -# include -#endif +#include #if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) // STLPort library; this _must_ come first, otherwise since @@ -44,10 +40,6 @@ // Rogue Wave library: # define BOOST_STDLIB_CONFIG "boost/config/stdlib/roguewave.hpp" -#elif defined(_LIBCPP_VERSION) -// libc++ -# define BOOST_STDLIB_CONFIG "boost/config/stdlib/libcpp.hpp" - #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) // GNU libstdc++ 3 # define BOOST_STDLIB_CONFIG "boost/config/stdlib/libstdcpp3.hpp" diff --git a/utils/boost_idb/boost/config/stdlib/dinkumware.hpp b/utils/boost_idb/boost/config/stdlib/dinkumware.hpp index a8b68be7..e33fef12 100644 --- a/utils/boost_idb/boost/config/stdlib/dinkumware.hpp +++ b/utils/boost_idb/boost/config/stdlib/dinkumware.hpp @@ -87,53 +87,45 @@ #endif #include -#if ( (!_HAS_EXCEPTIONS && !defined(__ghs__)) || (!_HAS_NAMESPACE && defined(__ghs__)) ) && !defined(__TI_COMPILER_VERSION__) +#if !_HAS_EXCEPTIONS # define BOOST_NO_STD_TYPEINFO #endif // C++0x headers implemented in 520 (as shipped by Microsoft) // #if !defined(_CPPLIB_VER) || _CPPLIB_VER < 520 -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_FUNCTIONAL -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_SMART_PTR +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPEINDEX #endif -#if ((!defined(_HAS_TR1_IMPORTS) || (_HAS_TR1_IMPORTS+0 == 0)) && !defined(BOOST_NO_CXX11_HDR_TUPLE)) \ - && (!defined(_CPPLIB_VER) || _CPPLIB_VER < 610) -# define BOOST_NO_CXX11_HDR_TUPLE +#if !defined(_HAS_TR1_IMPORTS) && !defined(BOOST_NO_0X_HDR_TUPLE) +# define BOOST_NO_0X_HDR_TUPLE #endif -// C++0x headers implemented in 540 (as shipped by Microsoft) +// C++0x headers not yet implemented // -#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 540 -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -#endif - -// C++0x headers implemented in 610 (as shipped by Microsoft) -// -#if !defined(_CPPLIB_VER) || _CPPLIB_VER < 610 -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -#endif +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #ifdef _CPPLIB_VER # define BOOST_DINKUMWARE_STDLIB _CPPLIB_VER diff --git a/utils/boost_idb/boost/config/stdlib/libcomo.hpp b/utils/boost_idb/boost/config/stdlib/libcomo.hpp index 29490f1b..16a842ae 100644 --- a/utils/boost_idb/boost/config/stdlib/libcomo.hpp +++ b/utils/boost_idb/boost/config/stdlib/libcomo.hpp @@ -35,29 +35,30 @@ // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST // // Intrinsic type_traits support. diff --git a/utils/boost_idb/boost/config/stdlib/libcpp.hpp b/utils/boost_idb/boost/config/stdlib/libcpp.hpp deleted file mode 100644 index 3d574407..00000000 --- a/utils/boost_idb/boost/config/stdlib/libcpp.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// (C) Copyright Christopher Jefferson 2011. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for most recent version. - -// config for libc++ -// Might need more in here later. - -#if !defined(_LIBCPP_VERSION) -# include -# if !defined(_LIBCPP_VERSION) -# error "This is not libc++!" -# endif -#endif - -#define BOOST_STDLIB "libc++ version " BOOST_STRINGIZE(_LIBCPP_VERSION) - -#define BOOST_HAS_THREADS - -#ifdef _LIBCPP_HAS_NO_VARIADICS -# define BOOST_NO_CXX11_HDR_TUPLE -#endif - -// -// These appear to be unusable/incomplete so far: -// -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR - -// libc++ uses a non-standard messages_base -#define BOOST_NO_STD_MESSAGES - -// --- end --- diff --git a/utils/boost_idb/boost/config/stdlib/libstdcpp3.hpp b/utils/boost_idb/boost/config/stdlib/libstdcpp3.hpp index 976ab76b..01dd4907 100644 --- a/utils/boost_idb/boost/config/stdlib/libstdcpp3.hpp +++ b/utils/boost_idb/boost/config/stdlib/libstdcpp3.hpp @@ -9,8 +9,6 @@ // config for libstdc++ v3 // not much to go in here: -#define BOOST_GNU_STDLIB 1 - #ifdef __GLIBCXX__ #define BOOST_STDLIB "GNU libstdc++ version " BOOST_STRINGIZE(__GLIBCXX__) #else @@ -33,10 +31,7 @@ #ifdef __GLIBCXX__ // gcc 3.4 and greater: # if defined(_GLIBCXX_HAVE_GTHR_DEFAULT) \ - || defined(_GLIBCXX__PTHREADS) \ - || defined(_GLIBCXX_HAS_GTHREADS) \ - || defined(_WIN32) \ - || defined(_AIX) + || defined(_GLIBCXX__PTHREADS) // // If the std lib has thread support turned on, then turn it on in Boost // as well. We do this because some gcc-3.4 std lib headers define _REENTANT @@ -59,6 +54,7 @@ # define BOOST_HAS_THREADS #endif + #if !defined(_GLIBCPP_USE_LONG_LONG) \ && !defined(_GLIBCXX_USE_LONG_LONG)\ && defined(BOOST_HAS_LONG_LONG) @@ -67,16 +63,6 @@ # undef BOOST_HAS_LONG_LONG #endif -// Apple doesn't seem to reliably defined a *unix* macro -#if !defined(CYGWIN) && ( defined(__unix__) \ - || defined(__unix) \ - || defined(unix) \ - || defined(__APPLE__) \ - || defined(__APPLE) \ - || defined(APPLE)) -# include -#endif - #if defined(__GLIBCXX__) || (defined(__GLIBCPP__) && __GLIBCPP__>=20020514) // GCC >= 3.1.0 # define BOOST_STD_EXTENSION_NAMESPACE __gnu_cxx # define BOOST_HAS_SLIST @@ -106,61 +92,43 @@ // C++0x headers in GCC 4.3.0 and later // #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET #endif // C++0x headers in GCC 4.4.0 and later // #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 4) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_SMART_PTR -#else -# define BOOST_HAS_TR1_COMPLEX_INVERSE_TRIG -# define BOOST_HAS_TR1_COMPLEX_OVERLOADS -#endif - -#if (!defined(_GLIBCXX_HAS_GTHREADS) || !defined(_GLIBCXX_USE_C99_STDINT_TR1)) && (!defined(BOOST_NO_CXX11_HDR_CONDITION_VARIABLE) || !defined(BOOST_NO_CXX11_HDR_MUTEX)) -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_MUTEX +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD #endif // C++0x features in GCC 4.5.0 and later // #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_RANDOM -#endif - -// C++0x features in GCC 4.6.0 and later -// -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -# define BOOST_NO_CXX11_HDR_TYPEINDEX +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #endif -// C++0x features in GCC 4.7.0 and later -// -#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7) || !defined(__GXX_EXPERIMENTAL_CXX0X__) -// Note that although existed prior to 4.7, "stead_clock" is spelled "monotonic_clock" -// so 4.7.0 is the first truely conforming one. -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_ALLOCATOR -#endif -// C++0x headers not yet (fully!) implemented +// C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_TYPEINDEX // --- end --- diff --git a/utils/boost_idb/boost/config/stdlib/modena.hpp b/utils/boost_idb/boost/config/stdlib/modena.hpp index b483b6e0..147060d9 100644 --- a/utils/boost_idb/boost/config/stdlib/modena.hpp +++ b/utils/boost_idb/boost/config/stdlib/modena.hpp @@ -24,29 +24,30 @@ // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #define BOOST_STDLIB "Modena C++ standard library" diff --git a/utils/boost_idb/boost/config/stdlib/msl.hpp b/utils/boost_idb/boost/config/stdlib/msl.hpp index 4f9a2da6..8185e351 100644 --- a/utils/boost_idb/boost/config/stdlib/msl.hpp +++ b/utils/boost_idb/boost/config/stdlib/msl.hpp @@ -48,29 +48,30 @@ // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #define BOOST_STDLIB "Metrowerks Standard Library version " BOOST_STRINGIZE(__MSL_CPP__) diff --git a/utils/boost_idb/boost/config/stdlib/roguewave.hpp b/utils/boost_idb/boost/config/stdlib/roguewave.hpp index cb80f570..dcd0af84 100644 --- a/utils/boost_idb/boost/config/stdlib/roguewave.hpp +++ b/utils/boost_idb/boost/config/stdlib/roguewave.hpp @@ -10,8 +10,6 @@ // Rogue Wave std lib: -#define BOOST_RW_STDLIB 1 - #if !defined(__STD_RWCOMPILER_H__) && !defined(_RWSTD_VER) # include # if !defined(__STD_RWCOMPILER_H__) && !defined(_RWSTD_VER) @@ -154,33 +152,30 @@ # endif #endif -#if _RWSTD_VER < 0x05000000 -# define BOOST_NO_CXX11_HDR_ARRAY -#endif -// type_traits header is incomplete: -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -// // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST diff --git a/utils/boost_idb/boost/config/stdlib/sgi.hpp b/utils/boost_idb/boost/config/stdlib/sgi.hpp index ae9b6ad9..4d426473 100644 --- a/utils/boost_idb/boost/config/stdlib/sgi.hpp +++ b/utils/boost_idb/boost/config/stdlib/sgi.hpp @@ -40,17 +40,6 @@ # define BOOST_NO_STRINGSTREAM #endif -// Apple doesn't seem to reliably defined a *unix* macro -#if !defined(CYGWIN) && ( defined(__unix__) \ - || defined(__unix) \ - || defined(unix) \ - || defined(__APPLE__) \ - || defined(__APPLE) \ - || defined(APPLE)) -# include -#endif - - // // Assume no std::locale without own iostreams (this may be an // incorrect assumption in some cases): @@ -118,29 +107,30 @@ // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #define BOOST_STDLIB "SGI standard library" diff --git a/utils/boost_idb/boost/config/stdlib/stlport.hpp b/utils/boost_idb/boost/config/stdlib/stlport.hpp index bcc30b99..0e1c9b2b 100644 --- a/utils/boost_idb/boost/config/stdlib/stlport.hpp +++ b/utils/boost_idb/boost/config/stdlib/stlport.hpp @@ -16,16 +16,6 @@ # endif #endif -// Apple doesn't seem to reliably defined a *unix* macro -#if !defined(CYGWIN) && ( defined(__unix__) \ - || defined(__unix) \ - || defined(unix) \ - || defined(__APPLE__) \ - || defined(__APPLE) \ - || defined(APPLE)) -# include -#endif - // // __STL_STATIC_CONST_INIT_BUG implies BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS // for versions prior to 4.1(beta) @@ -71,6 +61,10 @@ # endif #endif +#if defined(_STLPORT_VERSION) && ((_STLPORT_VERSION < 0x500) || (_STLPORT_VERSION >= 0x520)) +# define BOOST_NO_STD_UNORDERED +#endif + #if defined(_STLPORT_VERSION) && (_STLPORT_VERSION >= 0x520) # define BOOST_HAS_TR1_UNORDERED_SET # define BOOST_HAS_TR1_UNORDERED_MAP @@ -208,29 +202,30 @@ namespace boost { using std::min; using std::max; } // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #define BOOST_STDLIB "STLPort standard library version " BOOST_STRINGIZE(__SGI_STL_PORT) diff --git a/utils/boost_idb/boost/config/stdlib/vacpp.hpp b/utils/boost_idb/boost/config/stdlib/vacpp.hpp index 9d169465..0fc092f0 100644 --- a/utils/boost_idb/boost/config/stdlib/vacpp.hpp +++ b/utils/boost_idb/boost/config/stdlib/vacpp.hpp @@ -12,41 +12,32 @@ #define BOOST_HAS_MACRO_USE_FACET #define BOOST_NO_STD_MESSAGES -// Apple doesn't seem to reliably defined a *unix* macro -#if !defined(CYGWIN) && ( defined(__unix__) \ - || defined(__unix) \ - || defined(unix) \ - || defined(__APPLE__) \ - || defined(__APPLE) \ - || defined(APPLE)) -# include -#endif - // C++0x headers not yet implemented // -# define BOOST_NO_CXX11_HDR_ARRAY -# define BOOST_NO_CXX11_HDR_CHRONO -# define BOOST_NO_CXX11_HDR_CODECVT -# define BOOST_NO_CXX11_HDR_CONDITION_VARIABLE -# define BOOST_NO_CXX11_HDR_FORWARD_LIST -# define BOOST_NO_CXX11_HDR_FUTURE -# define BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# define BOOST_NO_CXX11_HDR_MUTEX -# define BOOST_NO_CXX11_HDR_RANDOM -# define BOOST_NO_CXX11_HDR_RATIO -# define BOOST_NO_CXX11_HDR_REGEX -# define BOOST_NO_CXX11_HDR_SYSTEM_ERROR -# define BOOST_NO_CXX11_HDR_THREAD -# define BOOST_NO_CXX11_HDR_TUPLE -# define BOOST_NO_CXX11_HDR_TYPE_TRAITS -# define BOOST_NO_CXX11_HDR_TYPEINDEX -# define BOOST_NO_CXX11_HDR_UNORDERED_MAP -# define BOOST_NO_CXX11_HDR_UNORDERED_SET -# define BOOST_NO_CXX11_NUMERIC_LIMITS -# define BOOST_NO_CXX11_ALLOCATOR -# define BOOST_NO_CXX11_ATOMIC_SMART_PTR -# define BOOST_NO_CXX11_SMART_PTR -# define BOOST_NO_CXX11_HDR_FUNCTIONAL +# define BOOST_NO_0X_HDR_ARRAY +# define BOOST_NO_0X_HDR_CHRONO +# define BOOST_NO_0X_HDR_CODECVT +# define BOOST_NO_0X_HDR_CONCEPTS +# define BOOST_NO_0X_HDR_CONDITION_VARIABLE +# define BOOST_NO_0X_HDR_CONTAINER_CONCEPTS +# define BOOST_NO_0X_HDR_FORWARD_LIST +# define BOOST_NO_0X_HDR_FUTURE +# define BOOST_NO_0X_HDR_INITIALIZER_LIST +# define BOOST_NO_0X_HDR_ITERATOR_CONCEPTS +# define BOOST_NO_0X_HDR_MEMORY_CONCEPTS +# define BOOST_NO_0X_HDR_MUTEX +# define BOOST_NO_0X_HDR_RANDOM +# define BOOST_NO_0X_HDR_RATIO +# define BOOST_NO_0X_HDR_REGEX +# define BOOST_NO_0X_HDR_SYSTEM_ERROR +# define BOOST_NO_0X_HDR_THREAD +# define BOOST_NO_0X_HDR_TUPLE +# define BOOST_NO_0X_HDR_TYPE_TRAITS +# define BOOST_NO_0X_HDR_TYPEINDEX +# define BOOST_NO_STD_UNORDERED // deprecated; see following +# define BOOST_NO_0X_HDR_UNORDERED_MAP +# define BOOST_NO_0X_HDR_UNORDERED_SET +# define BOOST_NO_NUMERIC_LIMITS_LOWEST #define BOOST_STDLIB "Visual Age default standard library" diff --git a/utils/boost_idb/boost/config/suffix.hpp b/utils/boost_idb/boost/config/suffix.hpp index c55579ea..722758f9 100644 --- a/utils/boost_idb/boost/config/suffix.hpp +++ b/utils/boost_idb/boost/config/suffix.hpp @@ -1,10 +1,9 @@ // Boost config.hpp configuration header file ------------------------------// -// boostinspect:ndprecated_macros -- tell the inspect tool to ignore this file // Copyright (c) 2001-2003 John Maddock // Copyright (c) 2001 Darin Adler // Copyright (c) 2001 Peter Dimov -// Copyright (c) 2002 Bill Kempf +// Copyright (c) 2002 Bill Kempf // Copyright (c) 2002 Jens Maurer // Copyright (c) 2002-2003 David Abrahams // Copyright (c) 2003 Gennaro Prota @@ -104,6 +103,13 @@ # define BOOST_NO_LONG_LONG_NUMERIC_LIMITS #endif +// +// Normalize BOOST_NO_STATIC_ASSERT and (depricated) BOOST_HAS_STATIC_ASSERT: +// +#if !defined(BOOST_NO_STATIC_ASSERT) && !defined(BOOST_HAS_STATIC_ASSERT) +# define BOOST_HAS_STATIC_ASSERT +#endif + // // if there is no __int64 then there is no specialisation // for numeric_limits<__int64> either: @@ -146,7 +152,7 @@ # endif // -// Without partial specialization, partial +// Without partial specialization, partial // specialization with default args won't work either: // # if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ @@ -328,6 +334,21 @@ # define BOOST_HASH_MAP_HEADER #endif +// +// Set BOOST_NO_INITIALIZER_LISTS if there is no library support. +// + +#if defined(BOOST_NO_0X_HDR_INITIALIZER_LIST) && !defined(BOOST_NO_INITIALIZER_LISTS) +# define BOOST_NO_INITIALIZER_LISTS +#endif + +// +// Set BOOST_HAS_RVALUE_REFS when BOOST_NO_RVALUE_REFERENCES is not defined +// +#if !defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_HAS_RVALUE_REFS) +#define BOOST_HAS_RVALUE_REFS +#endif + // BOOST_HAS_ABI_HEADERS // This macro gets set if we have headers that fix the ABI, // and prevent ODR violations when linking to external libraries: @@ -348,7 +369,7 @@ // works as expected with standard conforming compilers. The resulting // double inclusion of is harmless. -# if defined(BOOST_NO_STDC_NAMESPACE) && defined(__cplusplus) +# ifdef BOOST_NO_STDC_NAMESPACE # include namespace std { using ::ptrdiff_t; using ::size_t; } # endif @@ -367,7 +388,7 @@ // BOOST_NO_STD_MIN_MAX workaround -----------------------------------------// -# if defined(BOOST_NO_STD_MIN_MAX) && defined(__cplusplus) +# ifdef BOOST_NO_STD_MIN_MAX namespace std { template @@ -478,7 +499,7 @@ namespace std { // but it's use may generate either warnings (with -ansi), or errors // (with -pedantic -ansi) unless it's use is prefixed by __extension__ // -#if defined(BOOST_HAS_LONG_LONG) && defined(__cplusplus) +#if defined(BOOST_HAS_LONG_LONG) namespace boost{ # ifdef __GNUC__ __extension__ typedef long long long_long_type; @@ -489,22 +510,71 @@ namespace boost{ # endif } #endif -// same again for __int128: -#if defined(BOOST_HAS_INT128) && defined(__cplusplus) -namespace boost{ -# ifdef __GNUC__ - __extension__ typedef __int128 int128_type; - __extension__ typedef unsigned __int128 uint128_type; -# else - typedef __int128 int128_type; - typedef unsigned __int128 uint128_type; -# endif -} -#endif // BOOST_[APPEND_]EXPLICIT_TEMPLATE_[NON_]TYPE macros --------------------------// +// +// Some compilers have problems with function templates whose template +// parameters don't appear in the function parameter list (basically +// they just link one instantiation of the template in the final +// executable). These macros provide a uniform way to cope with the +// problem with no effects on the calling syntax. + +// Example: +// +// #include +// #include +// #include +// +// template +// void f() { std::cout << n << ' '; } +// +// template +// void g() { std::cout << typeid(T).name() << ' '; } +// +// int main() { +// f<1>(); +// f<2>(); +// +// g(); +// g(); +// } +// +// With VC++ 6.0 the output is: +// +// 2 2 double double +// +// To fix it, write +// +// template +// void f(BOOST_EXPLICIT_TEMPLATE_NON_TYPE(int, n)) { ... } +// +// template +// void g(BOOST_EXPLICIT_TEMPLATE_TYPE(T)) { ... } +// + + +#if defined BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS + +# include "boost/type.hpp" +# include "boost/non_type.hpp" + +# define BOOST_EXPLICIT_TEMPLATE_TYPE(t) boost::type* = 0 +# define BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) boost::type* +# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v) boost::non_type* = 0 +# define BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) boost::non_type* + +# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(t) \ + , BOOST_EXPLICIT_TEMPLATE_TYPE(t) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) \ + , BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) \ + , BOOST_EXPLICIT_TEMPLATE_NON_TYPE(t, v) +# define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) \ + , BOOST_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) -// These macros are obsolete. Port away and remove. +#else + +// no workaround needed: expand to nothing # define BOOST_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_EXPLICIT_TEMPLATE_TYPE_SPEC(t) @@ -516,11 +586,14 @@ namespace boost{ # define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) + +#endif // defined BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS + // When BOOST_NO_STD_TYPEINFO is defined, we can just import // the global definition into std namespace: -#if defined(BOOST_NO_STD_TYPEINFO) && defined(__cplusplus) +#ifdef BOOST_NO_STD_TYPEINFO #include -namespace std{ using ::type_info; } +namespace std{ using ::typeinfo; } #endif // ---------------------------------------------------------------------------// @@ -568,374 +641,7 @@ namespace std{ using ::type_info; } // Set some default values GPU support // # ifndef BOOST_GPU_ENABLED -# define BOOST_GPU_ENABLED -# endif - -// BOOST_FORCEINLINE ---------------------------------------------// -// Macro to use in place of 'inline' to force a function to be inline -#if !defined(BOOST_FORCEINLINE) -# if defined(_MSC_VER) -# define BOOST_FORCEINLINE __forceinline -# elif defined(__GNUC__) && __GNUC__ > 3 - // Clang also defines __GNUC__ (as 4) -# define BOOST_FORCEINLINE inline __attribute__ ((__always_inline__)) -# else -# define BOOST_FORCEINLINE inline -# endif -#endif - -// BOOST_NOINLINE ---------------------------------------------// -// Macro to use in place of 'inline' to prevent a function to be inlined -#if !defined(BOOST_NOINLINE) -# if defined(_MSC_VER) -# define BOOST_NOINLINE __declspec(noinline) -# elif defined(__GNUC__) && __GNUC__ > 3 - // Clang also defines __GNUC__ (as 4) -# define BOOST_NOINLINE __attribute__ ((__noinline__)) -# else -# define BOOST_NOINLINE +# define BOOST_GPU_ENABLED # endif #endif -// Branch prediction hints -// These macros are intended to wrap conditional expressions that yield true or false -// -// if (BOOST_LIKELY(var == 10)) -// { -// // the most probable code here -// } -// -#if !defined(BOOST_LIKELY) -# define BOOST_LIKELY(x) x -#endif -#if !defined(BOOST_UNLIKELY) -# define BOOST_UNLIKELY(x) x -#endif - -// Type and data alignment specification -// -#if !defined(BOOST_NO_CXX11_ALIGNAS) -# define BOOST_ALIGNMENT(x) alignas(x) -#elif defined(_MSC_VER) -# define BOOST_ALIGNMENT(x) __declspec(align(x)) -#elif defined(__GNUC__) -# define BOOST_ALIGNMENT(x) __attribute__ ((__aligned__(x))) -#else -# define BOOST_NO_ALIGNMENT -# define BOOST_ALIGNMENT(x) -#endif - -// Defaulted and deleted function declaration helpers -// These macros are intended to be inside a class definition. -// BOOST_DEFAULTED_FUNCTION accepts the function declaration and its -// body, which will be used if the compiler doesn't support defaulted functions. -// BOOST_DELETED_FUNCTION only accepts the function declaration. It -// will expand to a private function declaration, if the compiler doesn't support -// deleted functions. Because of this it is recommended to use BOOST_DELETED_FUNCTION -// in the end of the class definition. -// -// class my_class -// { -// public: -// // Default-constructible -// BOOST_DEFAULTED_FUNCTION(my_class(), {}) -// // Copying prohibited -// BOOST_DELETED_FUNCTION(my_class(my_class const&)) -// BOOST_DELETED_FUNCTION(my_class& operator= (my_class const&)) -// }; -// -#if !(defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) || defined(BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS)) -# define BOOST_DEFAULTED_FUNCTION(fun, body) fun = default; -#else -# define BOOST_DEFAULTED_FUNCTION(fun, body) fun body -#endif - -#if !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS) -# define BOOST_DELETED_FUNCTION(fun) fun = delete; -#else -# define BOOST_DELETED_FUNCTION(fun) private: fun; -#endif - -// -// Set BOOST_NO_DECLTYPE_N3276 when BOOST_NO_DECLTYPE is defined -// -#if defined(BOOST_NO_CXX11_DECLTYPE) && !defined(BOOST_NO_CXX11_DECLTYPE_N3276) -#define BOOST_NO_CXX11_DECLTYPE_N3276 BOOST_NO_CXX11_DECLTYPE -#endif - -// -------------------- Deprecated macros for 1.50 --------------------------- -// These will go away in a future release - -// Use BOOST_NO_CXX11_HDR_UNORDERED_SET or BOOST_NO_CXX11_HDR_UNORDERED_MAP -// instead of BOOST_NO_STD_UNORDERED -#if defined(BOOST_NO_CXX11_HDR_UNORDERED_MAP) || defined (BOOST_NO_CXX11_HDR_UNORDERED_SET) -# ifndef BOOST_NO_CXX11_STD_UNORDERED -# define BOOST_NO_CXX11_STD_UNORDERED -# endif -#endif - -// Use BOOST_NO_CXX11_HDR_INITIALIZER_LIST instead of BOOST_NO_INITIALIZER_LISTS -#if defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) && !defined(BOOST_NO_INITIALIZER_LISTS) -# define BOOST_NO_INITIALIZER_LISTS -#endif - -// Use BOOST_NO_CXX11_HDR_ARRAY instead of BOOST_NO_0X_HDR_ARRAY -#if defined(BOOST_NO_CXX11_HDR_ARRAY) && !defined(BOOST_NO_0X_HDR_ARRAY) -# define BOOST_NO_0X_HDR_ARRAY -#endif -// Use BOOST_NO_CXX11_HDR_CHRONO instead of BOOST_NO_0X_HDR_CHRONO -#if defined(BOOST_NO_CXX11_HDR_CHRONO) && !defined(BOOST_NO_0X_HDR_CHRONO) -# define BOOST_NO_0X_HDR_CHRONO -#endif -// Use BOOST_NO_CXX11_HDR_CODECVT instead of BOOST_NO_0X_HDR_CODECVT -#if defined(BOOST_NO_CXX11_HDR_CODECVT) && !defined(BOOST_NO_0X_HDR_CODECVT) -# define BOOST_NO_0X_HDR_CODECVT -#endif -// Use BOOST_NO_CXX11_HDR_CONDITION_VARIABLE instead of BOOST_NO_0X_HDR_CONDITION_VARIABLE -#if defined(BOOST_NO_CXX11_HDR_CONDITION_VARIABLE) && !defined(BOOST_NO_0X_HDR_CONDITION_VARIABLE) -# define BOOST_NO_0X_HDR_CONDITION_VARIABLE -#endif -// Use BOOST_NO_CXX11_HDR_FORWARD_LIST instead of BOOST_NO_0X_HDR_FORWARD_LIST -#if defined(BOOST_NO_CXX11_HDR_FORWARD_LIST) && !defined(BOOST_NO_0X_HDR_FORWARD_LIST) -# define BOOST_NO_0X_HDR_FORWARD_LIST -#endif -// Use BOOST_NO_CXX11_HDR_FUTURE instead of BOOST_NO_0X_HDR_FUTURE -#if defined(BOOST_NO_CXX11_HDR_FUTURE) && !defined(BOOST_NO_0X_HDR_FUTURE) -# define BOOST_NO_0X_HDR_FUTURE -#endif - -// Use BOOST_NO_CXX11_HDR_INITIALIZER_LIST -// instead of BOOST_NO_0X_HDR_INITIALIZER_LIST or BOOST_NO_INITIALIZER_LISTS -#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST -# ifndef BOOST_NO_0X_HDR_INITIALIZER_LIST -# define BOOST_NO_0X_HDR_INITIALIZER_LIST -# endif -# ifndef BOOST_NO_INITIALIZER_LISTS -# define BOOST_NO_INITIALIZER_LISTS -# endif -#endif - -// Use BOOST_NO_CXX11_HDR_MUTEX instead of BOOST_NO_0X_HDR_MUTEX -#if defined(BOOST_NO_CXX11_HDR_MUTEX) && !defined(BOOST_NO_0X_HDR_MUTEX) -# define BOOST_NO_0X_HDR_MUTEX -#endif -// Use BOOST_NO_CXX11_HDR_RANDOM instead of BOOST_NO_0X_HDR_RANDOM -#if defined(BOOST_NO_CXX11_HDR_RANDOM) && !defined(BOOST_NO_0X_HDR_RANDOM) -# define BOOST_NO_0X_HDR_RANDOM -#endif -// Use BOOST_NO_CXX11_HDR_RATIO instead of BOOST_NO_0X_HDR_RATIO -#if defined(BOOST_NO_CXX11_HDR_RATIO) && !defined(BOOST_NO_0X_HDR_RATIO) -# define BOOST_NO_0X_HDR_RATIO -#endif -// Use BOOST_NO_CXX11_HDR_REGEX instead of BOOST_NO_0X_HDR_REGEX -#if defined(BOOST_NO_CXX11_HDR_REGEX) && !defined(BOOST_NO_0X_HDR_REGEX) -# define BOOST_NO_0X_HDR_REGEX -#endif -// Use BOOST_NO_CXX11_HDR_SYSTEM_ERROR instead of BOOST_NO_0X_HDR_SYSTEM_ERROR -#if defined(BOOST_NO_CXX11_HDR_SYSTEM_ERROR) && !defined(BOOST_NO_0X_HDR_SYSTEM_ERROR) -# define BOOST_NO_0X_HDR_SYSTEM_ERROR -#endif -// Use BOOST_NO_CXX11_HDR_THREAD instead of BOOST_NO_0X_HDR_THREAD -#if defined(BOOST_NO_CXX11_HDR_THREAD) && !defined(BOOST_NO_0X_HDR_THREAD) -# define BOOST_NO_0X_HDR_THREAD -#endif -// Use BOOST_NO_CXX11_HDR_TUPLE instead of BOOST_NO_0X_HDR_TUPLE -#if defined(BOOST_NO_CXX11_HDR_TUPLE) && !defined(BOOST_NO_0X_HDR_TUPLE) -# define BOOST_NO_0X_HDR_TUPLE -#endif -// Use BOOST_NO_CXX11_HDR_TYPE_TRAITS instead of BOOST_NO_0X_HDR_TYPE_TRAITS -#if defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) && !defined(BOOST_NO_0X_HDR_TYPE_TRAITS) -# define BOOST_NO_0X_HDR_TYPE_TRAITS -#endif -// Use BOOST_NO_CXX11_HDR_TYPEINDEX instead of BOOST_NO_0X_HDR_TYPEINDEX -#if defined(BOOST_NO_CXX11_HDR_TYPEINDEX) && !defined(BOOST_NO_0X_HDR_TYPEINDEX) -# define BOOST_NO_0X_HDR_TYPEINDEX -#endif -// Use BOOST_NO_CXX11_HDR_UNORDERED_MAP instead of BOOST_NO_0X_HDR_UNORDERED_MAP -#if defined(BOOST_NO_CXX11_HDR_UNORDERED_MAP) && !defined(BOOST_NO_0X_HDR_UNORDERED_MAP) -# define BOOST_NO_0X_HDR_UNORDERED_MAP -#endif -// Use BOOST_NO_CXX11_HDR_UNORDERED_SET instead of BOOST_NO_0X_HDR_UNORDERED_SET -#if defined(BOOST_NO_CXX11_HDR_UNORDERED_SET) && !defined(BOOST_NO_0X_HDR_UNORDERED_SET) -# define BOOST_NO_0X_HDR_UNORDERED_SET -#endif - -// ------------------ End of deprecated macros for 1.50 --------------------------- - -// -------------------- Deprecated macros for 1.51 --------------------------- -// These will go away in a future release - -// Use BOOST_NO_CXX11_AUTO_DECLARATIONS instead of BOOST_NO_AUTO_DECLARATIONS -#if defined(BOOST_NO_CXX11_AUTO_DECLARATIONS) && !defined(BOOST_NO_AUTO_DECLARATIONS) -# define BOOST_NO_AUTO_DECLARATIONS -#endif -// Use BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS instead of BOOST_NO_AUTO_MULTIDECLARATIONS -#if defined(BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS) && !defined(BOOST_NO_AUTO_MULTIDECLARATIONS) -# define BOOST_NO_AUTO_MULTIDECLARATIONS -#endif -// Use BOOST_NO_CXX11_CHAR16_T instead of BOOST_NO_CHAR16_T -#if defined(BOOST_NO_CXX11_CHAR16_T) && !defined(BOOST_NO_CHAR16_T) -# define BOOST_NO_CHAR16_T -#endif -// Use BOOST_NO_CXX11_CHAR32_T instead of BOOST_NO_CHAR32_T -#if defined(BOOST_NO_CXX11_CHAR32_T) && !defined(BOOST_NO_CHAR32_T) -# define BOOST_NO_CHAR32_T -#endif -// Use BOOST_NO_CXX11_TEMPLATE_ALIASES instead of BOOST_NO_TEMPLATE_ALIASES -#if defined(BOOST_NO_CXX11_TEMPLATE_ALIASES) && !defined(BOOST_NO_TEMPLATE_ALIASES) -# define BOOST_NO_TEMPLATE_ALIASES -#endif -// Use BOOST_NO_CXX11_CONSTEXPR instead of BOOST_NO_CONSTEXPR -#if defined(BOOST_NO_CXX11_CONSTEXPR) && !defined(BOOST_NO_CONSTEXPR) -# define BOOST_NO_CONSTEXPR -#endif -// Use BOOST_NO_CXX11_DECLTYPE_N3276 instead of BOOST_NO_DECLTYPE_N3276 -#if defined(BOOST_NO_CXX11_DECLTYPE_N3276) && !defined(BOOST_NO_DECLTYPE_N3276) -# define BOOST_NO_DECLTYPE_N3276 -#endif -// Use BOOST_NO_CXX11_DECLTYPE instead of BOOST_NO_DECLTYPE -#if defined(BOOST_NO_CXX11_DECLTYPE) && !defined(BOOST_NO_DECLTYPE) -# define BOOST_NO_DECLTYPE -#endif -// Use BOOST_NO_CXX11_DEFAULTED_FUNCTIONS instead of BOOST_NO_DEFAULTED_FUNCTIONS -#if defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BOOST_NO_DEFAULTED_FUNCTIONS) -# define BOOST_NO_DEFAULTED_FUNCTIONS -#endif -// Use BOOST_NO_CXX11_DELETED_FUNCTIONS instead of BOOST_NO_DELETED_FUNCTIONS -#if defined(BOOST_NO_CXX11_DELETED_FUNCTIONS) && !defined(BOOST_NO_DELETED_FUNCTIONS) -# define BOOST_NO_DELETED_FUNCTIONS -#endif -// Use BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS instead of BOOST_NO_EXPLICIT_CONVERSION_OPERATORS -#if defined(BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS) && !defined(BOOST_NO_EXPLICIT_CONVERSION_OPERATORS) -# define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS -#endif -// Use BOOST_NO_CXX11_EXTERN_TEMPLATE instead of BOOST_NO_EXTERN_TEMPLATE -#if defined(BOOST_NO_CXX11_EXTERN_TEMPLATE) && !defined(BOOST_NO_EXTERN_TEMPLATE) -# define BOOST_NO_EXTERN_TEMPLATE -#endif -// Use BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS instead of BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS -#if defined(BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS) && !defined(BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS) -# define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS -#endif -// Use BOOST_NO_CXX11_LAMBDAS instead of BOOST_NO_LAMBDAS -#if defined(BOOST_NO_CXX11_LAMBDAS) && !defined(BOOST_NO_LAMBDAS) -# define BOOST_NO_LAMBDAS -#endif -// Use BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS instead of BOOST_NO_LOCAL_CLASS_TEMPLATE_PARAMETERS -#if defined(BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS) && !defined(BOOST_NO_LOCAL_CLASS_TEMPLATE_PARAMETERS) -# define BOOST_NO_LOCAL_CLASS_TEMPLATE_PARAMETERS -#endif -// Use BOOST_NO_CXX11_NOEXCEPT instead of BOOST_NO_NOEXCEPT -#if defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_NOEXCEPT) -# define BOOST_NO_NOEXCEPT -#endif -// Use BOOST_NO_CXX11_NULLPTR instead of BOOST_NO_NULLPTR -#if defined(BOOST_NO_CXX11_NULLPTR) && !defined(BOOST_NO_NULLPTR) -# define BOOST_NO_NULLPTR -#endif -// Use BOOST_NO_CXX11_RAW_LITERALS instead of BOOST_NO_RAW_LITERALS -#if defined(BOOST_NO_CXX11_RAW_LITERALS) && !defined(BOOST_NO_RAW_LITERALS) -# define BOOST_NO_RAW_LITERALS -#endif -// Use BOOST_NO_CXX11_RVALUE_REFERENCES instead of BOOST_NO_RVALUE_REFERENCES -#if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_RVALUE_REFERENCES) -# define BOOST_NO_RVALUE_REFERENCES -#endif -// Use BOOST_NO_CXX11_SCOPED_ENUMS instead of BOOST_NO_SCOPED_ENUMS -#if defined(BOOST_NO_CXX11_SCOPED_ENUMS) && !defined(BOOST_NO_SCOPED_ENUMS) -# define BOOST_NO_SCOPED_ENUMS -#endif -// Use BOOST_NO_CXX11_STATIC_ASSERT instead of BOOST_NO_STATIC_ASSERT -#if defined(BOOST_NO_CXX11_STATIC_ASSERT) && !defined(BOOST_NO_STATIC_ASSERT) -# define BOOST_NO_STATIC_ASSERT -#endif -// Use BOOST_NO_CXX11_STD_UNORDERED instead of BOOST_NO_STD_UNORDERED -#if defined(BOOST_NO_CXX11_STD_UNORDERED) && !defined(BOOST_NO_STD_UNORDERED) -# define BOOST_NO_STD_UNORDERED -#endif -// Use BOOST_NO_CXX11_UNICODE_LITERALS instead of BOOST_NO_UNICODE_LITERALS -#if defined(BOOST_NO_CXX11_UNICODE_LITERALS) && !defined(BOOST_NO_UNICODE_LITERALS) -# define BOOST_NO_UNICODE_LITERALS -#endif -// Use BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX instead of BOOST_NO_UNIFIED_INITIALIZATION_SYNTAX -#if defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX) && !defined(BOOST_NO_UNIFIED_INITIALIZATION_SYNTAX) -# define BOOST_NO_UNIFIED_INITIALIZATION_SYNTAX -#endif -// Use BOOST_NO_CXX11_VARIADIC_TEMPLATES instead of BOOST_NO_VARIADIC_TEMPLATES -#if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_VARIADIC_TEMPLATES) -# define BOOST_NO_VARIADIC_TEMPLATES -#endif -// Use BOOST_NO_CXX11_VARIADIC_MACROS instead of BOOST_NO_VARIADIC_MACROS -#if defined(BOOST_NO_CXX11_VARIADIC_MACROS) && !defined(BOOST_NO_VARIADIC_MACROS) -# define BOOST_NO_VARIADIC_MACROS -#endif -// Use BOOST_NO_CXX11_NUMERIC_LIMITS instead of BOOST_NO_NUMERIC_LIMITS_LOWEST -#if defined(BOOST_NO_CXX11_NUMERIC_LIMITS) && !defined(BOOST_NO_NUMERIC_LIMITS_LOWEST) -# define BOOST_NO_NUMERIC_LIMITS_LOWEST -#endif -// ------------------ End of deprecated macros for 1.51 --------------------------- - - - -// -// Helper macros BOOST_NOEXCEPT, BOOST_NOEXCEPT_IF, BOOST_NOEXCEPT_EXPR -// These aid the transition to C++11 while still supporting C++03 compilers -// -#ifdef BOOST_NO_CXX11_NOEXCEPT -# define BOOST_NOEXCEPT -# define BOOST_NOEXCEPT_OR_NOTHROW throw() -# define BOOST_NOEXCEPT_IF(Predicate) -# define BOOST_NOEXCEPT_EXPR(Expression) false -#else -# define BOOST_NOEXCEPT noexcept -# define BOOST_NOEXCEPT_OR_NOTHROW noexcept -# define BOOST_NOEXCEPT_IF(Predicate) noexcept((Predicate)) -# define BOOST_NOEXCEPT_EXPR(Expression) noexcept((Expression)) -#endif -// -// Helper macro BOOST_FALLTHROUGH -// Fallback definition of BOOST_FALLTHROUGH macro used to mark intended -// fall-through between case labels in a switch statement. We use a definition -// that requires a semicolon after it to avoid at least one type of misuse even -// on unsupported compilers. -// -#ifndef BOOST_FALLTHROUGH -# define BOOST_FALLTHROUGH ((void)0) -#endif - -// -// constexpr workarounds -// -#if defined(BOOST_NO_CXX11_CONSTEXPR) -#define BOOST_CONSTEXPR -#define BOOST_CONSTEXPR_OR_CONST const -#else -#define BOOST_CONSTEXPR constexpr -#define BOOST_CONSTEXPR_OR_CONST constexpr -#endif - -#define BOOST_STATIC_CONSTEXPR static BOOST_CONSTEXPR_OR_CONST - -// -// Set BOOST_HAS_STATIC_ASSERT when BOOST_NO_CXX11_STATIC_ASSERT is not defined -// -#if !defined(BOOST_NO_CXX11_STATIC_ASSERT) && !defined(BOOST_HAS_STATIC_ASSERT) -# define BOOST_HAS_STATIC_ASSERT -#endif - -// -// Set BOOST_HAS_RVALUE_REFS when BOOST_NO_CXX11_RVALUE_REFERENCES is not defined -// -#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_HAS_RVALUE_REFS) -#define BOOST_HAS_RVALUE_REFS -#endif - -// -// Set BOOST_HAS_VARIADIC_TMPL when BOOST_NO_CXX11_VARIADIC_TEMPLATES is not defined -// -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_HAS_VARIADIC_TMPL) -#define BOOST_HAS_VARIADIC_TMPL -#endif - - -#endif diff --git a/utils/boost_idb/boost/config/warning_disable.hpp b/utils/boost_idb/boost/config/warning_disable.hpp index fea8e829..26ff1323 100644 --- a/utils/boost_idb/boost/config/warning_disable.hpp +++ b/utils/boost_idb/boost/config/warning_disable.hpp @@ -23,7 +23,7 @@ // Note that THIS HEADER MUST NOT INCLUDE ANY OTHER HEADERS: // not even std library ones! Doing so may turn the warning // off too late to be of any use. For example the VC++ C4996 -// warning can be emitted from if that header is included +// warning can be omitted from if that header is included // before or by this one :-( // diff --git a/utils/boost_idb/boost/container/allocator_traits.hpp b/utils/boost_idb/boost/container/allocator_traits.hpp deleted file mode 100644 index aa8194a4..00000000 --- a/utils/boost_idb/boost/container/allocator_traits.hpp +++ /dev/null @@ -1,405 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Pablo Halpern 2009. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_ALLOCATOR_ALLOCATOR_TRAITS_HPP -#define BOOST_CONTAINER_ALLOCATOR_ALLOCATOR_TRAITS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include //numeric_limits<>::max() -#include //placement new -#include //std::allocator - -#if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) -#include -#endif - -///@cond - -namespace boost { -namespace container { -namespace container_detail { - -//workaround needed for C++03 compilers with no construct() -//supporting rvalue references -template -struct is_std_allocator -{ static const bool value = false; }; - -template -struct is_std_allocator< std::allocator > -{ static const bool value = true; }; - -} //namespace container_detail { - -///@endcond - -//! The class template allocator_traits supplies a uniform interface to all allocator types. -//! This class is a C++03-compatible implementation of std::allocator_traits -template -struct allocator_traits -{ - //allocator_type - typedef Alloc allocator_type; - //value_type - typedef typename Alloc::value_type value_type; - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Alloc::pointer if such a type exists; otherwise, value_type* - //! - typedef unspecified pointer; - //! Alloc::const_pointer if such a type exists ; otherwise, pointer_traits::rebind::rebind. - //! - typedef see_documentation void_pointer; - //! Alloc::const_void_pointer if such a type exists ; otherwis e, pointer_traits::rebind::difference_type. - //! - typedef see_documentation difference_type; - //! Alloc::size_type if such a type exists ; otherwise, make_unsigned::type - //! - typedef see_documentation size_type; - //! Alloc::propagate_on_container_copy_assignment if such a type exists, otherwise an integral_constant - //! type with internal constant static member `value` == false. - typedef see_documentation propagate_on_container_copy_assignment; - //! Alloc::propagate_on_container_move_assignment if such a type exists, otherwise an integral_constant - //! type with internal constant static member `value` == false. - typedef see_documentation propagate_on_container_move_assignment; - //! Alloc::propagate_on_container_swap if such a type exists, otherwise an integral_constant - //! type with internal constant static member `value` == false. - typedef see_documentation propagate_on_container_swap; - //! Defines an allocator: Alloc::rebind::other if such a type exists; otherwise, Alloc - //! if Alloc is a class template instantiation of the form Alloc, where Args is zero or - //! more type arguments ; otherwise, the instantiation of rebind_alloc is ill-formed. - //! - //! In C++03 compilers `rebind_alloc` is a struct derived from an allocator - //! deduced by previously detailed rules. - template using rebind_alloc = see_documentation; - - //! In C++03 compilers `rebind_traits` is a struct derived from - //! `allocator_traits`, where `OtherAlloc` is - //! the allocator deduced by rules explained in `rebind_alloc`. - template using rebind_traits = allocator_traits >; - - //! Non-standard extension: Portable allocator rebind for C++03 and C++11 compilers. - //! `type` is an allocator related to Alloc deduced deduced by rules explained in `rebind_alloc`. - template - struct portable_rebind_alloc - { typedef see_documentation type; }; - #else - //pointer - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - pointer, value_type*) - pointer; - //const_pointer - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_EVAL_DEFAULT(boost::container::container_detail::, Alloc, - const_pointer, typename boost::intrusive::pointer_traits::template - rebind_pointer) - const_pointer; - //reference - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - reference, typename container_detail::unvoid::type&) - reference; - //const_reference - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - const_reference, const typename container_detail::unvoid::type&) - const_reference; - //void_pointer - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_EVAL_DEFAULT(boost::container::container_detail::, Alloc, - void_pointer, typename boost::intrusive::pointer_traits::template - rebind_pointer) - void_pointer; - //const_void_pointer - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_EVAL_DEFAULT(boost::container::container_detail::, Alloc, - const_void_pointer, typename boost::intrusive::pointer_traits::template - rebind_pointer) - const_void_pointer; - //difference_type - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - difference_type, std::ptrdiff_t) - difference_type; - //size_type - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - size_type, std::size_t) - size_type; - //propagate_on_container_copy_assignment - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - propagate_on_container_copy_assignment, boost::false_type) - propagate_on_container_copy_assignment; - //propagate_on_container_move_assignment - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - propagate_on_container_move_assignment, boost::false_type) - propagate_on_container_move_assignment; - //propagate_on_container_swap - typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, Alloc, - propagate_on_container_swap, boost::false_type) - propagate_on_container_swap; - - #if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES) - //C++11 - template using rebind_alloc = typename boost::intrusive::detail::type_rebinder::type; - template using rebind_traits = allocator_traits< rebind_alloc >; - #else // #if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES) - //Some workaround for C++03 or C++11 compilers with no template aliases - template - struct rebind_alloc : boost::intrusive::detail::type_rebinder::type - { - typedef typename boost::intrusive::detail::type_rebinder::type Base; - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - template - rebind_alloc(BOOST_FWD_REF(Args)... args) - : Base(boost::forward(args)...) - {} - #else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - rebind_alloc(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - : Base(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)) \ - {} \ - // - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - #endif // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - }; - - template - struct rebind_traits - : allocator_traits::type> - {}; - #endif // #if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES) - template - struct portable_rebind_alloc - { typedef typename boost::intrusive::detail::type_rebinder::type type; }; - #endif //BOOST_CONTAINER_DOXYGEN_INVOKED - - //! Returns: `a.allocate(n)` - //! - static pointer allocate(Alloc &a, size_type n) - { return a.allocate(n); } - - //! Returns: `a.deallocate(p, n)` - //! - //! Throws: Nothing - static void deallocate(Alloc &a, pointer p, size_type n) - { a.deallocate(p, n); } - - //! Effects: calls `a.allocate(n, p)` if that call is well-formed; - //! otherwise, invokes `a.allocate(n)` - static pointer allocate(Alloc &a, size_type n, const_void_pointer p) - { - const bool value = boost::container::container_detail:: - has_member_function_callable_with_allocate - ::value; - ::boost::integral_constant flag; - return allocator_traits::priv_allocate(flag, a, n, p); - } - - //! Effects: calls `a.destroy(p)` if that call is well-formed; - //! otherwise, invokes `p->~T()`. - template - static void destroy(Alloc &a, T*p) - { - typedef T* destroy_pointer; - const bool value = boost::container::container_detail:: - has_member_function_callable_with_destroy - ::value; - ::boost::integral_constant flag; - allocator_traits::priv_destroy(flag, a, p); - } - - //! Returns: `a.max_size()` if that expression is well-formed; otherwise, - //! `numeric_limits::max()`. - static size_type max_size(const Alloc &a) - { - const bool value = boost::container::container_detail:: - has_member_function_callable_with_max_size - ::value; - ::boost::integral_constant flag; - return allocator_traits::priv_max_size(flag, a); - } - - //! Returns: `a.select_on_container_copy_construction()` if that expression is well-formed; - //! otherwise, a. - static - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - typename container_detail::if_c - < boost::container::container_detail:: - has_member_function_callable_with_select_on_container_copy_construction - ::value - , Alloc - , const Alloc & - >::type - #else - Alloc - #endif - select_on_container_copy_construction(const Alloc &a) - { - const bool value = boost::container::container_detail:: - has_member_function_callable_with_select_on_container_copy_construction - ::value; - ::boost::integral_constant flag; - return allocator_traits::priv_select_on_container_copy_construction(flag, a); - } - - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: calls `a.construct(p, std::forward(args)...)` if that call is well-formed; - //! otherwise, invokes `::new (static_cast(p)) T(std::forward(args)...)` - template - static void construct(Alloc & a, T* p, BOOST_FWD_REF(Args)... args) - { - ::boost::integral_constant::value> flag; - allocator_traits::priv_construct(flag, a, p, ::boost::forward(args)...); - } - #endif - ///@cond - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - private: - static pointer priv_allocate(boost::true_type, Alloc &a, size_type n, const_void_pointer p) - { return a.allocate(n, p); } - - static pointer priv_allocate(boost::false_type, Alloc &a, size_type n, const_void_pointer) - { return allocator_traits::allocate(a, n); } - - template - static void priv_destroy(boost::true_type, Alloc &a, T* p) - { a.destroy(p); } - - template - static void priv_destroy(boost::false_type, Alloc &, T* p) - { p->~T(); (void)p; } - - static size_type priv_max_size(boost::true_type, const Alloc &a) - { return a.max_size(); } - - static size_type priv_max_size(boost::false_type, const Alloc &) - { return (std::numeric_limits::max)(); } - - static Alloc priv_select_on_container_copy_construction(boost::true_type, const Alloc &a) - { return a.select_on_container_copy_construction(); } - - static const Alloc &priv_select_on_container_copy_construction(boost::false_type, const Alloc &a) - { return a; } - - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - template - static void priv_construct(boost::false_type, Alloc &a, T *p, BOOST_FWD_REF(Args) ...args) - { - const bool value = boost::container::container_detail:: - has_member_function_callable_with_construct - < Alloc, T*, Args... >::value; - ::boost::integral_constant flag; - priv_construct_dispatch2(flag, a, p, ::boost::forward(args)...); - } - - template - static void priv_construct(boost::true_type, Alloc &a, T *p, BOOST_FWD_REF(Args) ...args) - { - priv_construct_dispatch2(boost::false_type(), a, p, ::boost::forward(args)...); - } - - template - static void priv_construct_dispatch2(boost::true_type, Alloc &a, T *p, BOOST_FWD_REF(Args) ...args) - { a.construct( p, ::boost::forward(args)...); } - - template - static void priv_construct_dispatch2(boost::false_type, Alloc &, T *p, BOOST_FWD_REF(Args) ...args) - { ::new((void*)p) T(::boost::forward(args)...); } - #else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - public: - #define BOOST_PP_LOCAL_MACRO(n) \ - template \ - static void construct(Alloc &a, T *p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - ::boost::integral_constant::value> flag; \ - allocator_traits::priv_construct(flag, a, p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - } \ - // - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - private: - #define BOOST_PP_LOCAL_MACRO(n) \ - template \ - static void priv_construct(boost::false_type, Alloc &a, T *p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST,_)) \ - { \ - const bool value = \ - boost::container::container_detail::has_member_function_callable_with_construct \ - < Alloc, T* BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_FWD_TYPE, _) >::value; \ - ::boost::integral_constant flag; \ - priv_construct_dispatch2(flag, a, p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - } \ - \ - template \ - static void priv_construct(boost::true_type, Alloc &a, T *p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST,_)) \ - { \ - priv_construct_dispatch2(boost::false_type(), a, p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - } \ - \ - template \ - static void priv_construct_dispatch2(boost::true_type, Alloc &a, T *p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST,_)) \ - { a.construct( p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); } \ - \ - template \ - static void priv_construct_dispatch2(boost::false_type, Alloc &, T *p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _) ) \ - { ::new((void*)p) T(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - // - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - #endif // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - template - static void priv_construct_dispatch2(boost::false_type, Alloc &, T *p, ::boost::container::default_init_t) - { ::new((void*)p) T; } - #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - ///@endcond -}; - -} //namespace container { -} //namespace boost { - -#include - -#endif // ! defined(BOOST_CONTAINER_ALLOCATOR_ALLOCATOR_TRAITS_HPP) diff --git a/utils/boost_idb/boost/container/container_fwd.hpp b/utils/boost_idb/boost/container/container_fwd.hpp deleted file mode 100644 index 271cc8b1..00000000 --- a/utils/boost_idb/boost/container/container_fwd.hpp +++ /dev/null @@ -1,182 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_CONTAINER_FWD_HPP -#define BOOST_CONTAINER_CONTAINER_FWD_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -////////////////////////////////////////////////////////////////////////////// -// Standard predeclarations -////////////////////////////////////////////////////////////////////////////// - -/// @cond - -namespace boost{ -namespace intrusive{ - //Create namespace to avoid compilation errors -}} - -namespace boost{ namespace container{ namespace container_detail{ - -namespace bi = boost::intrusive; - -}}} - -#include -#include -#include -#include -#include - -/// @endcond - -////////////////////////////////////////////////////////////////////////////// -// Containers -////////////////////////////////////////////////////////////////////////////// - -namespace boost { -namespace container { - -//vector class -template > -class vector; - -//vector class -template > -class stable_vector; - -//vector class -template > -class deque; - -//list class -template > -class list; - -//slist class -template > -class slist; - -//set class -template - ,class Allocator = std::allocator > -class set; - -//multiset class -template - ,class Allocator = std::allocator > -class multiset; - -//map class -template - ,class Allocator = std::allocator > > -class map; - -//multimap class -template - ,class Allocator = std::allocator > > -class multimap; - -//flat_set class -template - ,class Allocator = std::allocator > -class flat_set; - -//flat_multiset class -template - ,class Allocator = std::allocator > -class flat_multiset; - -//flat_map class -template - ,class Allocator = std::allocator > > -class flat_map; - -//flat_multimap class -template - ,class Allocator = std::allocator > > -class flat_multimap; - -//basic_string class -template - ,class Allocator = std::allocator > -class basic_string; - -//! Type used to tag that the input range is -//! guaranteed to be ordered -struct ordered_range_t -{}; - -//! Value used to tag that the input range is -//! guaranteed to be ordered -static const ordered_range_t ordered_range = ordered_range_t(); - -//! Type used to tag that the input range is -//! guaranteed to be ordered and unique -struct ordered_unique_range_t - : public ordered_range_t -{}; - -//! Value used to tag that the input range is -//! guaranteed to be ordered and unique -static const ordered_unique_range_t ordered_unique_range = ordered_unique_range_t(); - -//! Type used to tag that the input range is -//! guaranteed to be ordered and unique -struct default_init_t -{}; - -//! Value used to tag that the input range is -//! guaranteed to be ordered and unique -static const default_init_t default_init = default_init_t(); -/// @cond - -namespace detail_really_deep_namespace { - -//Otherwise, gcc issues a warning of previously defined -//anonymous_instance and unique_instance -struct dummy -{ - dummy() - { - (void)ordered_range; - (void)ordered_unique_range; - (void)default_init; - } -}; - -} //detail_really_deep_namespace { - -/// @endcond - -}} //namespace boost { namespace container { - -#endif //#ifndef BOOST_CONTAINER_CONTAINER_FWD_HPP diff --git a/utils/boost_idb/boost/container/deque.hpp b/utils/boost_idb/boost/container/deque.hpp deleted file mode 100644 index 136b4f62..00000000 --- a/utils/boost_idb/boost/container/deque.hpp +++ /dev/null @@ -1,1992 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DEQUE_HPP -#define BOOST_CONTAINER_DEQUE_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else -template -#endif -class deque; - -template -struct deque_value_traits -{ - typedef T value_type; - static const bool trivial_dctr = boost::has_trivial_destructor::value; - static const bool trivial_dctr_after_move = ::boost::has_trivial_destructor_after_move::value; - static const bool trivial_copy = has_trivial_copy::value; - static const bool nothrow_copy = has_nothrow_copy::value; - static const bool trivial_assign = has_trivial_assign::value; - //static const bool nothrow_assign = has_nothrow_assign::value; - static const bool nothrow_assign = false; -}; - -// Note: this function is simply a kludge to work around several compilers' -// bugs in handling constant expressions. -template -struct deque_buf_size -{ - static const std::size_t min_size = 512u; - static const std::size_t sizeof_t = sizeof(T); - static const std::size_t value = sizeof_t < min_size ? (min_size/sizeof_t) : std::size_t(1); -}; - -namespace container_detail { - -// Class invariants: -// For any nonsingular iterator i: -// i.node is the address of an element in the map array. The -// contents of i.node is a pointer to the beginning of a node. -// i.first == //(i.node) -// i.last == i.first + node_size -// i.cur is a pointer in the range [i.first, i.last). NOTE: -// the implication of this is that i.cur is always a dereferenceable -// pointer, even if i is a past-the-end iterator. -// Start and Finish are always nonsingular iterators. NOTE: this means -// that an empty deque must have one node, and that a deque -// with N elements, where N is the buffer size, must have two nodes. -// For every node other than start.node and finish.node, every element -// in the node is an initialized object. If start.node == finish.node, -// then [start.cur, finish.cur) are initialized objects, and -// the elements outside that range are uninitialized storage. Otherwise, -// [start.cur, start.last) and [finish.first, finish.cur) are initialized -// objects, and [start.first, start.cur) and [finish.cur, finish.last) -// are uninitialized storage. -// [map, map + map_size) is a valid, non-empty range. -// [start.node, finish.node] is a valid range contained within -// [map, map + map_size). -// Allocator pointer in the range [map, map + map_size) points to an allocated node -// if and only if the pointer is in the range [start.node, finish.node]. -template -class deque_iterator -{ - public: - typedef std::random_access_iterator_tag iterator_category; - typedef typename boost::intrusive::pointer_traits::element_type value_type; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename if_c - < IsConst - , typename boost::intrusive::pointer_traits::template - rebind_pointer::type - , Pointer - >::type pointer; - typedef typename if_c - < IsConst - , const value_type& - , value_type& - >::type reference; - - static std::size_t s_buffer_size() - { return deque_buf_size::value; } - - typedef Pointer val_alloc_ptr; - typedef typename boost::intrusive::pointer_traits:: - template rebind_pointer::type index_pointer; - - Pointer m_cur; - Pointer m_first; - Pointer m_last; - index_pointer m_node; - - public: - - Pointer get_cur() const { return m_cur; } - Pointer get_first() const { return m_first; } - Pointer get_last() const { return m_last; } - index_pointer get_node() const { return m_node; } - - deque_iterator(val_alloc_ptr x, index_pointer y) BOOST_CONTAINER_NOEXCEPT - : m_cur(x), m_first(*y), m_last(*y + s_buffer_size()), m_node(y) - {} - - deque_iterator() BOOST_CONTAINER_NOEXCEPT - : m_cur(), m_first(), m_last(), m_node() - {} - - deque_iterator(deque_iterator const& x) BOOST_CONTAINER_NOEXCEPT - : m_cur(x.get_cur()), m_first(x.get_first()), m_last(x.get_last()), m_node(x.get_node()) - {} - - deque_iterator(Pointer cur, Pointer first, Pointer last, index_pointer node) BOOST_CONTAINER_NOEXCEPT - : m_cur(cur), m_first(first), m_last(last), m_node(node) - {} - - deque_iterator unconst() const BOOST_CONTAINER_NOEXCEPT - { - return deque_iterator(this->get_cur(), this->get_first(), this->get_last(), this->get_node()); - } - - reference operator*() const BOOST_CONTAINER_NOEXCEPT - { return *this->m_cur; } - - pointer operator->() const BOOST_CONTAINER_NOEXCEPT - { return this->m_cur; } - - difference_type operator-(const deque_iterator& x) const BOOST_CONTAINER_NOEXCEPT - { - if(!this->m_cur && !x.m_cur){ - return 0; - } - return difference_type(this->s_buffer_size()) * (this->m_node - x.m_node - 1) + - (this->m_cur - this->m_first) + (x.m_last - x.m_cur); - } - - deque_iterator& operator++() BOOST_CONTAINER_NOEXCEPT - { - ++this->m_cur; - if (this->m_cur == this->m_last) { - this->priv_set_node(this->m_node + 1); - this->m_cur = this->m_first; - } - return *this; - } - - deque_iterator operator++(int) BOOST_CONTAINER_NOEXCEPT - { - deque_iterator tmp(*this); - ++*this; - return tmp; - } - - deque_iterator& operator--() BOOST_CONTAINER_NOEXCEPT - { - if (this->m_cur == this->m_first) { - this->priv_set_node(this->m_node - 1); - this->m_cur = this->m_last; - } - --this->m_cur; - return *this; - } - - deque_iterator operator--(int) BOOST_CONTAINER_NOEXCEPT - { - deque_iterator tmp(*this); - --*this; - return tmp; - } - - deque_iterator& operator+=(difference_type n) BOOST_CONTAINER_NOEXCEPT - { - difference_type offset = n + (this->m_cur - this->m_first); - if (offset >= 0 && offset < difference_type(this->s_buffer_size())) - this->m_cur += n; - else { - difference_type node_offset = - offset > 0 ? offset / difference_type(this->s_buffer_size()) - : -difference_type((-offset - 1) / this->s_buffer_size()) - 1; - this->priv_set_node(this->m_node + node_offset); - this->m_cur = this->m_first + - (offset - node_offset * difference_type(this->s_buffer_size())); - } - return *this; - } - - deque_iterator operator+(difference_type n) const BOOST_CONTAINER_NOEXCEPT - { deque_iterator tmp(*this); return tmp += n; } - - deque_iterator& operator-=(difference_type n) BOOST_CONTAINER_NOEXCEPT - { return *this += -n; } - - deque_iterator operator-(difference_type n) const BOOST_CONTAINER_NOEXCEPT - { deque_iterator tmp(*this); return tmp -= n; } - - reference operator[](difference_type n) const BOOST_CONTAINER_NOEXCEPT - { return *(*this + n); } - - friend bool operator==(const deque_iterator& l, const deque_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_cur == r.m_cur; } - - friend bool operator!=(const deque_iterator& l, const deque_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_cur != r.m_cur; } - - friend bool operator<(const deque_iterator& l, const deque_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return (l.m_node == r.m_node) ? (l.m_cur < r.m_cur) : (l.m_node < r.m_node); } - - friend bool operator>(const deque_iterator& l, const deque_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return r < l; } - - friend bool operator<=(const deque_iterator& l, const deque_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return !(r < l); } - - friend bool operator>=(const deque_iterator& l, const deque_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return !(l < r); } - - void priv_set_node(index_pointer new_node) BOOST_CONTAINER_NOEXCEPT - { - this->m_node = new_node; - this->m_first = *new_node; - this->m_last = this->m_first + this->s_buffer_size(); - } - - friend deque_iterator operator+(difference_type n, deque_iterator x) BOOST_CONTAINER_NOEXCEPT - { return x += n; } -}; - -} //namespace container_detail { - -// Deque base class. It has two purposes. First, its constructor -// and destructor allocate (but don't initialize) storage. This makes -// exception safety easier. -template -class deque_base -{ - BOOST_COPYABLE_AND_MOVABLE(deque_base) - public: - typedef allocator_traits val_alloc_traits_type; - typedef typename val_alloc_traits_type::value_type val_alloc_val; - typedef typename val_alloc_traits_type::pointer val_alloc_ptr; - typedef typename val_alloc_traits_type::const_pointer val_alloc_cptr; - typedef typename val_alloc_traits_type::reference val_alloc_ref; - typedef typename val_alloc_traits_type::const_reference val_alloc_cref; - typedef typename val_alloc_traits_type::difference_type val_alloc_diff; - typedef typename val_alloc_traits_type::size_type val_alloc_size; - typedef typename val_alloc_traits_type::template - portable_rebind_alloc::type ptr_alloc_t; - typedef allocator_traits ptr_alloc_traits_type; - typedef typename ptr_alloc_traits_type::value_type ptr_alloc_val; - typedef typename ptr_alloc_traits_type::pointer ptr_alloc_ptr; - typedef typename ptr_alloc_traits_type::const_pointer ptr_alloc_cptr; - typedef typename ptr_alloc_traits_type::reference ptr_alloc_ref; - typedef typename ptr_alloc_traits_type::const_reference ptr_alloc_cref; - typedef Allocator allocator_type; - typedef allocator_type stored_allocator_type; - typedef val_alloc_size size_type; - - protected: - - typedef deque_value_traits traits_t; - typedef ptr_alloc_t map_allocator_type; - - static size_type s_buffer_size() BOOST_CONTAINER_NOEXCEPT - { return deque_buf_size::value; } - - val_alloc_ptr priv_allocate_node() - { return this->alloc().allocate(s_buffer_size()); } - - void priv_deallocate_node(val_alloc_ptr p) BOOST_CONTAINER_NOEXCEPT - { this->alloc().deallocate(p, s_buffer_size()); } - - ptr_alloc_ptr priv_allocate_map(size_type n) - { return this->ptr_alloc().allocate(n); } - - void priv_deallocate_map(ptr_alloc_ptr p, size_type n) BOOST_CONTAINER_NOEXCEPT - { this->ptr_alloc().deallocate(p, n); } - - typedef container_detail::deque_iterator iterator; - typedef container_detail::deque_iterator const_iterator; - - deque_base(size_type num_elements, const allocator_type& a) - : members_(a) - { this->priv_initialize_map(num_elements); } - - explicit deque_base(const allocator_type& a) - : members_(a) - {} - - deque_base() - : members_() - {} - - explicit deque_base(BOOST_RV_REF(deque_base) x) - : members_( boost::move(x.ptr_alloc()) - , boost::move(x.alloc()) ) - {} - - ~deque_base() - { - if (this->members_.m_map) { - this->priv_destroy_nodes(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1); - this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); - } - } - - private: - deque_base(const deque_base&); - - protected: - - void swap_members(deque_base &x) BOOST_CONTAINER_NOEXCEPT - { - std::swap(this->members_.m_start, x.members_.m_start); - std::swap(this->members_.m_finish, x.members_.m_finish); - std::swap(this->members_.m_map, x.members_.m_map); - std::swap(this->members_.m_map_size, x.members_.m_map_size); - } - - void priv_initialize_map(size_type num_elements) - { -// if(num_elements){ - size_type num_nodes = num_elements / s_buffer_size() + 1; - - this->members_.m_map_size = container_detail::max_value((size_type) InitialMapSize, num_nodes + 2); - this->members_.m_map = this->priv_allocate_map(this->members_.m_map_size); - - ptr_alloc_ptr nstart = this->members_.m_map + (this->members_.m_map_size - num_nodes) / 2; - ptr_alloc_ptr nfinish = nstart + num_nodes; - - BOOST_TRY { - this->priv_create_nodes(nstart, nfinish); - } - BOOST_CATCH(...){ - this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); - this->members_.m_map = 0; - this->members_.m_map_size = 0; - BOOST_RETHROW - } - BOOST_CATCH_END - - this->members_.m_start.priv_set_node(nstart); - this->members_.m_finish.priv_set_node(nfinish - 1); - this->members_.m_start.m_cur = this->members_.m_start.m_first; - this->members_.m_finish.m_cur = this->members_.m_finish.m_first + - num_elements % s_buffer_size(); -// } - } - - void priv_create_nodes(ptr_alloc_ptr nstart, ptr_alloc_ptr nfinish) - { - ptr_alloc_ptr cur; - BOOST_TRY { - for (cur = nstart; cur < nfinish; ++cur) - *cur = this->priv_allocate_node(); - } - BOOST_CATCH(...){ - this->priv_destroy_nodes(nstart, cur); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - void priv_destroy_nodes(ptr_alloc_ptr nstart, ptr_alloc_ptr nfinish) BOOST_CONTAINER_NOEXCEPT - { - for (ptr_alloc_ptr n = nstart; n < nfinish; ++n) - this->priv_deallocate_node(*n); - } - - void priv_clear_map() BOOST_CONTAINER_NOEXCEPT - { - if (this->members_.m_map) { - this->priv_destroy_nodes(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1); - this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); - this->members_.m_map = 0; - this->members_.m_map_size = 0; - this->members_.m_start = iterator(); - this->members_.m_finish = this->members_.m_start; - } - } - - enum { InitialMapSize = 8 }; - - protected: - struct members_holder - : public ptr_alloc_t - , public allocator_type - { - members_holder() - : map_allocator_type(), allocator_type() - , m_map(0), m_map_size(0) - , m_start(), m_finish(m_start) - {} - - explicit members_holder(const allocator_type &a) - : map_allocator_type(a), allocator_type(a) - , m_map(0), m_map_size(0) - , m_start(), m_finish(m_start) - {} - - template - members_holder(BOOST_FWD_REF(PtrAllocConvertible) pa, BOOST_FWD_REF(ValAllocConvertible) va) - : map_allocator_type(boost::forward(pa)) - , allocator_type (boost::forward(va)) - , m_map(0), m_map_size(0) - , m_start(), m_finish(m_start) - {} - - ptr_alloc_ptr m_map; - val_alloc_size m_map_size; - iterator m_start; - iterator m_finish; - } members_; - - ptr_alloc_t &ptr_alloc() BOOST_CONTAINER_NOEXCEPT - { return members_; } - - const ptr_alloc_t &ptr_alloc() const BOOST_CONTAINER_NOEXCEPT - { return members_; } - - allocator_type &alloc() BOOST_CONTAINER_NOEXCEPT - { return members_; } - - const allocator_type &alloc() const BOOST_CONTAINER_NOEXCEPT - { return members_; } -}; -/// @endcond - -//! Deque class -//! -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else -template -#endif -class deque : protected deque_base -{ - /// @cond - private: - typedef deque_base Base; - /// @endcond - - public: - - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - - typedef T value_type; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef BOOST_CONTAINER_IMPDEF(allocator_type) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(typename Base::iterator) iterator; - typedef BOOST_CONTAINER_IMPDEF(typename Base::const_iterator) const_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - - /// @cond - - private: // Internal typedefs - BOOST_COPYABLE_AND_MOVABLE(deque) - typedef typename Base::ptr_alloc_ptr index_pointer; - static size_type s_buffer_size() - { return Base::s_buffer_size(); } - typedef allocator_traits allocator_traits_type; - - /// @endcond - - public: - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructors a deque. - //! - //! Throws: If allocator_type's default constructor throws. - //! - //! Complexity: Constant. - deque() - : Base() - {} - - //! Effects: Constructs a deque taking the allocator as parameter. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - explicit deque(const allocator_type& a) BOOST_CONTAINER_NOEXCEPT - : Base(a) - {} - - //! Effects: Constructs a deque that will use a copy of allocator a - //! and inserts n value initialized values. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - explicit deque(size_type n) - : Base(n, allocator_type()) - { - container_detail::insert_value_initialized_n_proxy proxy(this->alloc()); - proxy.uninitialized_copy_n_and_update(this->begin(), n); - //deque_base will deallocate in case of exception... - } - - //! Effects: Constructs a deque that will use a copy of allocator a - //! and inserts n default initialized values. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - //! - //! Note: Non-standard extension - deque(size_type n, default_init_t) - : Base(n, allocator_type()) - { - container_detail::insert_default_initialized_n_proxy proxy(this->alloc()); - proxy.uninitialized_copy_n_and_update(this->begin(), n); - //deque_base will deallocate in case of exception... - } - - //! Effects: Constructs a deque that will use a copy of allocator a - //! and inserts n copies of value. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - deque(size_type n, const value_type& value, - const allocator_type& a = allocator_type()) - : Base(n, a) - { this->priv_fill_initialize(value); } - - //! Effects: Constructs a deque that will use a copy of allocator a - //! and inserts a copy of the range [first, last) in the deque. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's constructor taking an dereferenced InIt throws. - //! - //! Complexity: Linear to the range [first, last). - template - deque(InIt first, InIt last, const allocator_type& a = allocator_type() - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - >::type * = 0 - #endif - ) - : Base(a) - { - typedef typename std::iterator_traits::iterator_category ItCat; - this->priv_range_initialize(first, last, ItCat()); - } - - //! Effects: Copy constructs a deque. - //! - //! Postcondition: x == *this. - //! - //! Complexity: Linear to the elements x contains. - deque(const deque& x) - : Base(allocator_traits_type::select_on_container_copy_construction(x.alloc())) - { - if(x.size()){ - this->priv_initialize_map(x.size()); - boost::container::uninitialized_copy_alloc - (this->alloc(), x.begin(), x.end(), this->members_.m_start); - } - } - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - deque(BOOST_RV_REF(deque) x) - : Base(boost::move(static_cast(x))) - { this->swap_members(x); } - - //! Effects: Copy constructs a vector using the specified allocator. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocation - //! throws or T's copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - deque(const deque& x, const allocator_type &a) - : Base(a) - { - if(x.size()){ - this->priv_initialize_map(x.size()); - boost::container::uninitialized_copy_alloc - (this->alloc(), x.begin(), x.end(), this->members_.m_start); - } - } - - //! Effects: Move constructor using the specified allocator. - //! Moves mx's resources to *this if a == allocator_type(). - //! Otherwise copies values from x to *this. - //! - //! Throws: If allocation or T's copy constructor throws. - //! - //! Complexity: Constant if a == mx.get_allocator(), linear otherwise. - deque(BOOST_RV_REF(deque) mx, const allocator_type &a) - : Base(a) - { - if(mx.alloc() == a){ - this->swap_members(mx); - } - else{ - if(mx.size()){ - this->priv_initialize_map(mx.size()); - boost::container::uninitialized_copy_alloc - (this->alloc(), mx.begin(), mx.end(), this->members_.m_start); - } - } - } - - //! Effects: Destroys the deque. All stored values are destroyed - //! and used memory is deallocated. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements. - ~deque() BOOST_CONTAINER_NOEXCEPT - { - this->priv_destroy_range(this->members_.m_start, this->members_.m_finish); - } - - //! Effects: Makes *this contain the same elements as x. - //! - //! Postcondition: this->size() == x.size(). *this contains a copy - //! of each of x's elements. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to the number of elements in x. - deque& operator= (BOOST_COPY_ASSIGN_REF(deque) x) - { - if (&x != this){ - allocator_type &this_alloc = this->alloc(); - const allocator_type &x_alloc = x.alloc(); - container_detail::bool_ flag; - if(flag && this_alloc != x_alloc){ - this->clear(); - this->shrink_to_fit(); - } - container_detail::assign_alloc(this->alloc(), x.alloc(), flag); - container_detail::assign_alloc(this->ptr_alloc(), x.ptr_alloc(), flag); - this->assign(x.cbegin(), x.cend()); - } - return *this; - } - - //! Effects: Move assignment. All mx's values are transferred to *this. - //! - //! Postcondition: x.empty(). *this contains a the elements x had - //! before the function. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Linear. - deque& operator= (BOOST_RV_REF(deque) x) - { - if (&x != this){ - allocator_type &this_alloc = this->alloc(); - allocator_type &x_alloc = x.alloc(); - //If allocators are equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy objects but retain memory in case x reuses it in the future - this->clear(); - this->swap_members(x); - //Move allocator if needed - container_detail::bool_ flag; - container_detail::move_alloc(this_alloc, x_alloc, flag); - container_detail::move_alloc(this->ptr_alloc(), x.ptr_alloc(), flag); - } - //If unequal allocators, then do a one by one move - else{ - this->assign( boost::make_move_iterator(x.begin()) - , boost::make_move_iterator(x.end())); - } - } - return *this; - } - - //! Effects: Assigns the n copies of val to *this. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - void assign(size_type n, const T& val) - { - typedef constant_iterator c_it; - this->assign(c_it(val, n), c_it()); - } - - //! Effects: Assigns the the range [first, last) to *this. - //! - //! Throws: If memory allocation throws or - //! T's constructor from dereferencing InIt throws. - //! - //! Complexity: Linear to n. - template - void assign(InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - iterator cur = this->begin(); - for ( ; first != last && cur != end(); ++cur, ++first){ - *cur = *first; - } - if (first == last){ - this->erase(cur, this->cend()); - } - else{ - this->insert(this->cend(), first, last); - } - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - void assign(FwdIt first, FwdIt last - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !container_detail::is_input_iterator::value - >::type * = 0 - ) - { - const size_type len = std::distance(first, last); - if (len > size()) { - FwdIt mid = first; - std::advance(mid, this->size()); - boost::container::copy(first, mid, begin()); - this->insert(this->cend(), mid, last); - } - else{ - this->erase(boost::container::copy(first, last, this->begin()), cend()); - } - } - #endif - - //! Effects: Returns a copy of the internal allocator. - //! - //! Throws: If allocator's copy constructor throws. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return Base::alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return Base::alloc(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return Base::alloc(); } - - //! Effects: Returns an iterator to the first element contained in the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_start; } - - //! Effects: Returns a const_iterator to the first element contained in the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_start; } - - //! Effects: Returns an iterator to the end of the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_finish; } - - //! Effects: Returns a const_iterator to the end of the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_finish; } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->members_.m_finish); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->members_.m_finish); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->members_.m_start); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->members_.m_start); } - - //! Effects: Returns a const_iterator to the first element contained in the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_start; } - - //! Effects: Returns a const_iterator to the end of the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_finish; } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->members_.m_finish); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->members_.m_start); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the deque contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_finish == this->members_.m_start; } - - //! Effects: Returns the number of the elements contained in the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_finish - this->members_.m_start; } - - //! Effects: Returns the largest possible size of the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return allocator_traits_type::max_size(this->alloc()); } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws, or T's constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size) - { - const size_type len = size(); - if (new_size < len) - this->priv_erase_last_n(len - new_size); - else{ - const size_type n = new_size - this->size(); - container_detail::insert_value_initialized_n_proxy proxy(this->alloc()); - priv_insert_back_aux_impl(n, proxy); - } - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are default initialized. - //! - //! Throws: If memory allocation throws, or T's constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - //! - //! Note: Non-standard extension - void resize(size_type new_size, default_init_t) - { - const size_type len = size(); - if (new_size < len) - this->priv_erase_last_n(len - new_size); - else{ - const size_type n = new_size - this->size(); - container_detail::insert_default_initialized_n_proxy proxy(this->alloc()); - priv_insert_back_aux_impl(n, proxy); - } - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are copy constructed from x. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size, const value_type& x) - { - const size_type len = size(); - if (new_size < len) - this->erase(this->members_.m_start + new_size, this->members_.m_finish); - else - this->insert(this->members_.m_finish, new_size - len, x); - } - - //! Effects: Tries to deallocate the excess of memory created - //! with previous allocations. The size of the deque is unchanged - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Constant. - void shrink_to_fit() - { - //This deque implementation already - //deallocates excess nodes when erasing - //so there is nothing to do except for - //empty deque - if(this->empty()){ - this->priv_clear_map(); - } - } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the first - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference front() BOOST_CONTAINER_NOEXCEPT - { return *this->members_.m_start; } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference front() const BOOST_CONTAINER_NOEXCEPT - { return *this->members_.m_start; } - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the last - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference back() BOOST_CONTAINER_NOEXCEPT - { return *(end()-1); } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the last - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference back() const BOOST_CONTAINER_NOEXCEPT - { return *(cend()-1); } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference operator[](size_type n) BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_start[difference_type(n)]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference operator[](size_type n) const BOOST_CONTAINER_NOEXCEPT - { return this->members_.m_start[difference_type(n)]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - reference at(size_type n) - { this->priv_range_check(n); return (*this)[n]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - const_reference at(size_type n) const - { this->priv_range_check(n); return (*this)[n]; } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the beginning of the deque. - //! - //! Throws: If memory allocation throws or the in-place constructor throws. - //! - //! Complexity: Amortized constant time - template - void emplace_front(Args&&... args) - { - if(this->priv_push_front_simple_available()){ - allocator_traits_type::construct - ( this->alloc() - , this->priv_push_front_simple_pos() - , boost::forward(args)...); - this->priv_push_front_simple_commit(); - } - else{ - typedef container_detail::insert_non_movable_emplace_proxy type; - this->priv_insert_front_aux_impl(1, type(this->alloc(), boost::forward(args)...)); - } - } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the end of the deque. - //! - //! Throws: If memory allocation throws or the in-place constructor throws. - //! - //! Complexity: Amortized constant time - template - void emplace_back(Args&&... args) - { - if(this->priv_push_back_simple_available()){ - allocator_traits_type::construct - ( this->alloc() - , this->priv_push_back_simple_pos() - , boost::forward(args)...); - this->priv_push_back_simple_commit(); - } - else{ - typedef container_detail::insert_non_movable_emplace_proxy type; - this->priv_insert_back_aux_impl(1, type(this->alloc(), boost::forward(args)...)); - } - } - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... before position - //! - //! Throws: If memory allocation throws or the in-place constructor throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - template - iterator emplace(const_iterator p, Args&&... args) - { - if(p == this->cbegin()){ - this->emplace_front(boost::forward(args)...); - return this->begin(); - } - else if(p == this->cend()){ - this->emplace_back(boost::forward(args)...); - return (this->end()-1); - } - else{ - typedef container_detail::insert_emplace_proxy type; - return this->priv_insert_aux_impl(p, 1, type(this->alloc(), boost::forward(args)...)); - } - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - //advanced_insert_int.hpp includes all necessary preprocessor machinery... - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, > ) \ - void emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - if(priv_push_front_simple_available()){ \ - allocator_traits_type::construct \ - ( this->alloc() \ - , this->priv_push_front_simple_pos() \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - priv_push_front_simple_commit(); \ - } \ - else{ \ - container_detail::BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, n) \ - proxy \ - (this->alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - priv_insert_front_aux_impl(1, proxy); \ - } \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - if(priv_push_back_simple_available()){ \ - allocator_traits_type::construct \ - ( this->alloc() \ - , this->priv_push_back_simple_pos() \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - priv_push_back_simple_commit(); \ - } \ - else{ \ - container_detail::BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, n) \ - proxy \ - (this->alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - priv_insert_back_aux_impl(1, proxy); \ - } \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(const_iterator p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - if(p == this->cbegin()){ \ - this->emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - return this->begin(); \ - } \ - else if(p == cend()){ \ - this->emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - return (this->end()-1); \ - } \ - else{ \ - container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ - proxy \ - (this->alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - return this->priv_insert_aux_impl(p, 1, proxy); \ - } \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the front of the deque. - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - void push_front(const T &x); - - //! Effects: Constructs a new element in the front of the deque - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - void push_front(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_front, T, void, priv_push_front) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the end of the deque. - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - void push_back(const T &x); - - //! Effects: Constructs a new element in the end of the deque - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - void push_back(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_back, T, void, priv_push_back) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a copy of x before position. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws or x's copy constructor throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - iterator insert(const_iterator position, const T &x); - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a new element before position with mx's resources. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - iterator insert(const_iterator position, T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, T, iterator, priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: pos must be a valid iterator of *this. - //! - //! Effects: Insert n copies of x before pos. - //! - //! Returns: an iterator to the first inserted element or pos if n is 0. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - iterator insert(const_iterator pos, size_type n, const value_type& x) - { - typedef constant_iterator c_it; - return this->insert(pos, c_it(x, n), c_it()); - } - - //! Requires: pos must be a valid iterator of *this. - //! - //! Effects: Insert a copy of the [first, last) range before pos. - //! - //! Returns: an iterator to the first inserted element or pos if first == last. - //! - //! Throws: If memory allocation throws, T's constructor from a - //! dereferenced InIt throws or T's copy constructor throws. - //! - //! Complexity: Linear to std::distance [first, last). - template - iterator insert(const_iterator pos, InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - size_type n = 0; - iterator it(pos.unconst()); - for(;first != last; ++first, ++n){ - it = this->emplace(it, *first); - ++it; - } - it -= n; - return it; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - iterator insert(const_iterator p, FwdIt first, FwdIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - container_detail::insert_range_proxy proxy(this->alloc(), first); - return priv_insert_aux_impl(p, (size_type)std::distance(first, last), proxy); - } - #endif - - //! Effects: Removes the first element from the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant time. - void pop_front() BOOST_CONTAINER_NOEXCEPT - { - if (this->members_.m_start.m_cur != this->members_.m_start.m_last - 1) { - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(this->members_.m_start.m_cur) - ); - ++this->members_.m_start.m_cur; - } - else - this->priv_pop_front_aux(); - } - - //! Effects: Removes the last element from the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant time. - void pop_back() BOOST_CONTAINER_NOEXCEPT - { - if (this->members_.m_finish.m_cur != this->members_.m_finish.m_first) { - --this->members_.m_finish.m_cur; - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(this->members_.m_finish.m_cur) - ); - } - else - this->priv_pop_back_aux(); - } - - //! Effects: Erases the element at position pos. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the elements between pos and the - //! last element (if pos is near the end) or the first element - //! if(pos is near the beginning). - //! Constant if pos is the first or the last element. - iterator erase(const_iterator pos) BOOST_CONTAINER_NOEXCEPT - { - iterator next = pos.unconst(); - ++next; - size_type index = pos - this->members_.m_start; - if (index < (this->size()/2)) { - boost::move_backward(this->begin(), pos.unconst(), next); - pop_front(); - } - else { - boost::move(next, this->end(), pos.unconst()); - pop_back(); - } - return this->members_.m_start + index; - } - - //! Effects: Erases the elements pointed by [first, last). - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the distance between first and - //! last plus the elements between pos and the - //! last element (if pos is near the end) or the first element - //! if(pos is near the beginning). - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { - if (first == this->members_.m_start && last == this->members_.m_finish) { - this->clear(); - return this->members_.m_finish; - } - else { - const size_type n = static_cast(last - first); - const size_type elems_before = static_cast(first - this->members_.m_start); - if (elems_before < (this->size() - n) - elems_before) { - boost::move_backward(begin(), first.unconst(), last.unconst()); - iterator new_start = this->members_.m_start + n; - if(!Base::traits_t::trivial_dctr_after_move) - this->priv_destroy_range(this->members_.m_start, new_start); - this->priv_destroy_nodes(this->members_.m_start.m_node, new_start.m_node); - this->members_.m_start = new_start; - } - else { - boost::move(last.unconst(), end(), first.unconst()); - iterator new_finish = this->members_.m_finish - n; - if(!Base::traits_t::trivial_dctr_after_move) - this->priv_destroy_range(new_finish, this->members_.m_finish); - this->priv_destroy_nodes(new_finish.m_node + 1, this->members_.m_finish.m_node + 1); - this->members_.m_finish = new_finish; - } - return this->members_.m_start + elems_before; - } - } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(deque &x) - { - this->swap_members(x); - container_detail::bool_ flag; - container_detail::swap_alloc(this->alloc(), x.alloc(), flag); - container_detail::swap_alloc(this->ptr_alloc(), x.ptr_alloc(), flag); - } - - //! Effects: Erases all the elements of the deque. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements in the deque. - void clear() BOOST_CONTAINER_NOEXCEPT - { - for (index_pointer node = this->members_.m_start.m_node + 1; - node < this->members_.m_finish.m_node; - ++node) { - this->priv_destroy_range(*node, *node + this->s_buffer_size()); - this->priv_deallocate_node(*node); - } - - if (this->members_.m_start.m_node != this->members_.m_finish.m_node) { - this->priv_destroy_range(this->members_.m_start.m_cur, this->members_.m_start.m_last); - this->priv_destroy_range(this->members_.m_finish.m_first, this->members_.m_finish.m_cur); - this->priv_deallocate_node(this->members_.m_finish.m_first); - } - else - this->priv_destroy_range(this->members_.m_start.m_cur, this->members_.m_finish.m_cur); - - this->members_.m_finish = this->members_.m_start; - } - - /// @cond - private: - - void priv_erase_last_n(size_type n) - { - if(n == this->size()) { - this->clear(); - } - else { - iterator new_finish = this->members_.m_finish - n; - if(!Base::traits_t::trivial_dctr_after_move) - this->priv_destroy_range(new_finish, this->members_.m_finish); - this->priv_destroy_nodes(new_finish.m_node + 1, this->members_.m_finish.m_node + 1); - this->members_.m_finish = new_finish; - } - } - - void priv_range_check(size_type n) const - { if (n >= this->size()) throw_out_of_range("deque::at out of range"); } - - template - iterator priv_insert(const_iterator position, BOOST_FWD_REF(U) x) - { - if (position == cbegin()){ - this->push_front(::boost::forward(x)); - return begin(); - } - else if (position == cend()){ - this->push_back(::boost::forward(x)); - return --end(); - } - else { - return priv_insert_aux_impl - (position, (size_type)1, container_detail::get_insert_value_proxy(this->alloc(), ::boost::forward(x))); - } - } - - template - void priv_push_front(BOOST_FWD_REF(U) x) - { - if(this->priv_push_front_simple_available()){ - allocator_traits_type::construct - ( this->alloc(), this->priv_push_front_simple_pos(), ::boost::forward(x)); - this->priv_push_front_simple_commit(); - } - else{ - priv_insert_aux_impl - (this->cbegin(), (size_type)1, container_detail::get_insert_value_proxy(this->alloc(), ::boost::forward(x))); - } - } - - template - void priv_push_back(BOOST_FWD_REF(U) x) - { - if(this->priv_push_back_simple_available()){ - allocator_traits_type::construct - ( this->alloc(), this->priv_push_back_simple_pos(), ::boost::forward(x)); - this->priv_push_back_simple_commit(); - } - else{ - priv_insert_aux_impl - (this->cend(), (size_type)1, container_detail::get_insert_value_proxy(this->alloc(), ::boost::forward(x))); - container_detail::insert_copy_proxy proxy(this->alloc(), x); - } - } - - bool priv_push_back_simple_available() const - { - return this->members_.m_map && - (this->members_.m_finish.m_cur != (this->members_.m_finish.m_last - 1)); - } - - T *priv_push_back_simple_pos() const - { - return container_detail::to_raw_pointer(this->members_.m_finish.m_cur); - } - - void priv_push_back_simple_commit() - { - ++this->members_.m_finish.m_cur; - } - - bool priv_push_front_simple_available() const - { - return this->members_.m_map && - (this->members_.m_start.m_cur != this->members_.m_start.m_first); - } - - T *priv_push_front_simple_pos() const - { return container_detail::to_raw_pointer(this->members_.m_start.m_cur) - 1; } - - void priv_push_front_simple_commit() - { --this->members_.m_start.m_cur; } - - void priv_destroy_range(iterator p, iterator p2) - { - for(;p != p2; ++p){ - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(&*p) - ); - } - } - - void priv_destroy_range(pointer p, pointer p2) - { - for(;p != p2; ++p){ - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(&*p) - ); - } - } - - template - iterator priv_insert_aux_impl(const_iterator p, size_type n, InsertProxy interf) - { - iterator pos(p.unconst()); - const size_type pos_n = p - this->cbegin(); - if(!this->members_.m_map){ - this->priv_initialize_map(0); - pos = this->begin(); - } - - const size_type elemsbefore = static_cast(pos - this->members_.m_start); - const size_type length = this->size(); - if (elemsbefore < length / 2) { - const iterator new_start = this->priv_reserve_elements_at_front(n); - const iterator old_start = this->members_.m_start; - if(!elemsbefore){ - interf.uninitialized_copy_n_and_update(new_start, n); - this->members_.m_start = new_start; - } - else{ - pos = this->members_.m_start + elemsbefore; - if (elemsbefore >= n) { - const iterator start_n = this->members_.m_start + n; - ::boost::container::uninitialized_move_alloc - (this->alloc(), this->members_.m_start, start_n, new_start); - this->members_.m_start = new_start; - boost::move(start_n, pos, old_start); - interf.copy_n_and_update(pos - n, n); - } - else { - const size_type mid_count = n - elemsbefore; - const iterator mid_start = old_start - mid_count; - interf.uninitialized_copy_n_and_update(mid_start, mid_count); - this->members_.m_start = mid_start; - ::boost::container::uninitialized_move_alloc - (this->alloc(), old_start, pos, new_start); - this->members_.m_start = new_start; - interf.copy_n_and_update(old_start, elemsbefore); - } - } - } - else { - const iterator new_finish = this->priv_reserve_elements_at_back(n); - const iterator old_finish = this->members_.m_finish; - const size_type elemsafter = length - elemsbefore; - if(!elemsafter){ - interf.uninitialized_copy_n_and_update(old_finish, n); - this->members_.m_finish = new_finish; - } - else{ - pos = old_finish - elemsafter; - if (elemsafter >= n) { - iterator finish_n = old_finish - difference_type(n); - ::boost::container::uninitialized_move_alloc - (this->alloc(), finish_n, old_finish, old_finish); - this->members_.m_finish = new_finish; - boost::move_backward(pos, finish_n, old_finish); - interf.copy_n_and_update(pos, n); - } - else { - const size_type raw_gap = n - elemsafter; - ::boost::container::uninitialized_move_alloc - (this->alloc(), pos, old_finish, old_finish + raw_gap); - BOOST_TRY{ - interf.copy_n_and_update(pos, elemsafter); - interf.uninitialized_copy_n_and_update(old_finish, raw_gap); - } - BOOST_CATCH(...){ - this->priv_destroy_range(old_finish, old_finish + elemsafter); - BOOST_RETHROW - } - BOOST_CATCH_END - this->members_.m_finish = new_finish; - } - } - } - return this->begin() + pos_n; - } - - template - iterator priv_insert_back_aux_impl(size_type n, InsertProxy interf) - { - if(!this->members_.m_map){ - this->priv_initialize_map(0); - } - - iterator new_finish = this->priv_reserve_elements_at_back(n); - iterator old_finish = this->members_.m_finish; - interf.uninitialized_copy_n_and_update(old_finish, n); - this->members_.m_finish = new_finish; - return iterator(this->members_.m_finish - n); - } - - template - iterator priv_insert_front_aux_impl(size_type n, InsertProxy interf) - { - if(!this->members_.m_map){ - this->priv_initialize_map(0); - } - - iterator new_start = this->priv_reserve_elements_at_front(n); - interf.uninitialized_copy_n_and_update(new_start, n); - this->members_.m_start = new_start; - return new_start; - } - - iterator priv_fill_insert(const_iterator pos, size_type n, const value_type& x) - { - typedef constant_iterator c_it; - return this->insert(pos, c_it(x, n), c_it()); - } - - // Precondition: this->members_.m_start and this->members_.m_finish have already been initialized, - // but none of the deque's elements have yet been constructed. - void priv_fill_initialize(const value_type& value) - { - index_pointer cur; - BOOST_TRY { - for (cur = this->members_.m_start.m_node; cur < this->members_.m_finish.m_node; ++cur){ - boost::container::uninitialized_fill_alloc - (this->alloc(), *cur, *cur + this->s_buffer_size(), value); - } - boost::container::uninitialized_fill_alloc - (this->alloc(), this->members_.m_finish.m_first, this->members_.m_finish.m_cur, value); - } - BOOST_CATCH(...){ - this->priv_destroy_range(this->members_.m_start, iterator(*cur, cur)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - template - void priv_range_initialize(InIt first, InIt last, std::input_iterator_tag) - { - this->priv_initialize_map(0); - BOOST_TRY { - for ( ; first != last; ++first) - this->emplace_back(*first); - } - BOOST_CATCH(...){ - this->clear(); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - template - void priv_range_initialize(FwdIt first, FwdIt last, std::forward_iterator_tag) - { - size_type n = 0; - n = std::distance(first, last); - this->priv_initialize_map(n); - - index_pointer cur_node; - BOOST_TRY { - for (cur_node = this->members_.m_start.m_node; - cur_node < this->members_.m_finish.m_node; - ++cur_node) { - FwdIt mid = first; - std::advance(mid, this->s_buffer_size()); - ::boost::container::uninitialized_copy_alloc(this->alloc(), first, mid, *cur_node); - first = mid; - } - ::boost::container::uninitialized_copy_alloc(this->alloc(), first, last, this->members_.m_finish.m_first); - } - BOOST_CATCH(...){ - this->priv_destroy_range(this->members_.m_start, iterator(*cur_node, cur_node)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - // Called only if this->members_.m_finish.m_cur == this->members_.m_finish.m_first. - void priv_pop_back_aux() BOOST_CONTAINER_NOEXCEPT - { - this->priv_deallocate_node(this->members_.m_finish.m_first); - this->members_.m_finish.priv_set_node(this->members_.m_finish.m_node - 1); - this->members_.m_finish.m_cur = this->members_.m_finish.m_last - 1; - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(this->members_.m_finish.m_cur) - ); - } - - // Called only if this->members_.m_start.m_cur == this->members_.m_start.m_last - 1. Note that - // if the deque has at least one element (a precondition for this member - // function), and if this->members_.m_start.m_cur == this->members_.m_start.m_last, then the deque - // must have at least two nodes. - void priv_pop_front_aux() BOOST_CONTAINER_NOEXCEPT - { - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(this->members_.m_start.m_cur) - ); - this->priv_deallocate_node(this->members_.m_start.m_first); - this->members_.m_start.priv_set_node(this->members_.m_start.m_node + 1); - this->members_.m_start.m_cur = this->members_.m_start.m_first; - } - - iterator priv_reserve_elements_at_front(size_type n) - { - size_type vacancies = this->members_.m_start.m_cur - this->members_.m_start.m_first; - if (n > vacancies){ - size_type new_elems = n-vacancies; - size_type new_nodes = (new_elems + this->s_buffer_size() - 1) / - this->s_buffer_size(); - size_type s = (size_type)(this->members_.m_start.m_node - this->members_.m_map); - if (new_nodes > s){ - this->priv_reallocate_map(new_nodes, true); - } - size_type i = 1; - BOOST_TRY { - for (; i <= new_nodes; ++i) - *(this->members_.m_start.m_node - i) = this->priv_allocate_node(); - } - BOOST_CATCH(...) { - for (size_type j = 1; j < i; ++j) - this->priv_deallocate_node(*(this->members_.m_start.m_node - j)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - return this->members_.m_start - difference_type(n); - } - - iterator priv_reserve_elements_at_back(size_type n) - { - size_type vacancies = (this->members_.m_finish.m_last - this->members_.m_finish.m_cur) - 1; - if (n > vacancies){ - size_type new_elems = n - vacancies; - size_type new_nodes = (new_elems + this->s_buffer_size() - 1)/s_buffer_size(); - size_type s = (size_type)(this->members_.m_map_size - (this->members_.m_finish.m_node - this->members_.m_map)); - if (new_nodes + 1 > s){ - this->priv_reallocate_map(new_nodes, false); - } - size_type i; - BOOST_TRY { - for (i = 1; i <= new_nodes; ++i) - *(this->members_.m_finish.m_node + i) = this->priv_allocate_node(); - } - BOOST_CATCH(...) { - for (size_type j = 1; j < i; ++j) - this->priv_deallocate_node(*(this->members_.m_finish.m_node + j)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - return this->members_.m_finish + difference_type(n); - } - - void priv_reallocate_map(size_type nodes_to_add, bool add_at_front) - { - size_type old_num_nodes = this->members_.m_finish.m_node - this->members_.m_start.m_node + 1; - size_type new_num_nodes = old_num_nodes + nodes_to_add; - - index_pointer new_nstart; - if (this->members_.m_map_size > 2 * new_num_nodes) { - new_nstart = this->members_.m_map + (this->members_.m_map_size - new_num_nodes) / 2 - + (add_at_front ? nodes_to_add : 0); - if (new_nstart < this->members_.m_start.m_node) - boost::move(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart); - else - boost::move_backward - (this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart + old_num_nodes); - } - else { - size_type new_map_size = - this->members_.m_map_size + container_detail::max_value(this->members_.m_map_size, nodes_to_add) + 2; - - index_pointer new_map = this->priv_allocate_map(new_map_size); - new_nstart = new_map + (new_map_size - new_num_nodes) / 2 - + (add_at_front ? nodes_to_add : 0); - boost::move(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart); - this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); - - this->members_.m_map = new_map; - this->members_.m_map_size = new_map_size; - } - - this->members_.m_start.priv_set_node(new_nstart); - this->members_.m_finish.priv_set_node(new_nstart + old_num_nodes - 1); - } - /// @endcond -}; - -// Nonmember functions. -template -inline bool operator==(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT -{ - return x.size() == y.size() && equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool operator<(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT -{ - return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); -} - -template -inline bool operator!=(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return !(x == y); } - -template -inline bool operator>(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return y < x; } - -template -inline bool operator>=(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return !(x < y); } - -template -inline bool operator<=(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return !(y < x); } - -template -inline void swap(deque& x, deque& y) -{ x.swap(y); } - -}} - -/// @cond - -namespace boost { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > - : public ::boost::has_trivial_destructor_after_move -{}; - -} - -/// @endcond - -#include - -#endif // #ifndef BOOST_CONTAINER_DEQUE_HPP diff --git a/utils/boost_idb/boost/container/detail/adaptive_node_pool_impl.hpp b/utils/boost_idb/boost/container/detail/adaptive_node_pool_impl.hpp deleted file mode 100644 index 4578ea81..00000000 --- a/utils/boost_idb/boost/container/detail/adaptive_node_pool_impl.hpp +++ /dev/null @@ -1,874 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP -#define BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -namespace adaptive_pool_flag { - -static const unsigned int none = 0u; -static const unsigned int align_only = 1u << 0u; -static const unsigned int size_ordered = 1u << 1u; -static const unsigned int address_ordered = 1u << 2u; - -} //namespace adaptive_pool_flag{ - -namespace container_detail { - -template -struct hdr_offset_holder_t -{ - hdr_offset_holder_t(size_type offset = 0) - : hdr_offset(offset) - {} - size_type hdr_offset; -}; - -template -struct less_func; - -template -struct less_func -{ - static bool less(SizeType, SizeType, const void *, const void *) - { return true; } -}; - -template -struct less_func -{ - static bool less(SizeType ls, SizeType rs, const void *, const void *) - { return ls < rs; } -}; - -template -struct less_func -{ - static bool less(SizeType, SizeType, const void *la, const void *ra) - { return &la < &ra; } -}; - -template -struct less_func -{ - static bool less(SizeType ls, SizeType rs, const void *la, const void *ra) - { return (ls < rs) || ((ls == rs) && (la < ra)); } -}; - -template -struct block_container_traits -{ - typedef typename bi::make_set_base_hook - < bi::void_pointer - , bi::optimize_size - , bi::link_mode >::type hook_t; - - template - struct container - { - typedef typename bi::make_multiset - , bi::size_type >::type type; - }; - - template - static void reinsert_was_used(Container &container, typename Container::reference v, bool) - { - typedef typename Container::const_iterator const_block_iterator; - const const_block_iterator this_block - (Container::s_iterator_to(const_cast(v))); - const_block_iterator next_block(this_block); - if(++next_block != container.cend()){ - if(this_block->free_nodes.size() > next_block->free_nodes.size()){ - container.erase(this_block); - container.insert(v); - } - } - } - - template - static void insert_was_empty(Container &container, typename Container::value_type &v, bool) - { - container.insert(v); - } - - template - static void erase_first(Container &container) - { - container.erase(container.cbegin()); - } - - template - static void erase_last(Container &container) - { - container.erase(--container.cend()); - } -}; - -template -struct block_container_traits -{ - typedef typename bi::make_list_base_hook - < bi::void_pointer - , bi::link_mode >::type hook_t; - - template - struct container - { - typedef typename bi::make_list - , bi::size_type, bi::constant_time_size >::type type; - }; - - template - static void reinsert_was_used(Container &container, typename Container::value_type &v, bool is_full) - { - if(is_full){ - container.erase(Container::s_iterator_to(v)); - container.push_back(v); - } - } - - template - static void insert_was_empty(Container &container, typename Container::value_type &v, bool is_full) - { - if(is_full){ - container.push_back(v); - } - else{ - container.push_front(v); - } - } - - template - static void erase_first(Container &container) - { - container.pop_front(); - } - - template - static void erase_last(Container &container) - { - container.pop_back(); - } -}; - -template -struct adaptive_pool_types -{ - typedef VoidPointer void_pointer; - static const bool ordered = (Flags & (adaptive_pool_flag::size_ordered | adaptive_pool_flag::address_ordered)) != 0; - typedef block_container_traits block_container_traits_t; - typedef typename block_container_traits_t::hook_t hook_t; - typedef hdr_offset_holder_t hdr_offset_holder; - static const unsigned int order_flags = Flags & (adaptive_pool_flag::size_ordered | adaptive_pool_flag::address_ordered); - typedef MultiallocationChain free_nodes_t; - - struct block_info_t - : public hdr_offset_holder, - public hook_t - { - //An intrusive list of free node from this block - free_nodes_t free_nodes; - friend bool operator <(const block_info_t &l, const block_info_t &r) - { - return less_func:: - less(l.free_nodes.size(), r.free_nodes.size(), &l , &r); - } - - friend bool operator ==(const block_info_t &l, const block_info_t &r) - { return &l == &r; } - }; - typedef typename block_container_traits_t:: template container::type block_container_t; -}; - -template -inline size_type calculate_alignment - ( size_type overhead_percent, size_type real_node_size - , size_type hdr_size, size_type hdr_offset_size, size_type payload_per_allocation) -{ - //to-do: handle real_node_size != node_size - const size_type divisor = overhead_percent*real_node_size; - const size_type dividend = hdr_offset_size*100; - size_type elements_per_subblock = (dividend - 1)/divisor + 1; - size_type candidate_power_of_2 = - upper_power_of_2(elements_per_subblock*real_node_size + hdr_offset_size); - bool overhead_satisfied = false; - //Now calculate the wors-case overhead for a subblock - const size_type max_subblock_overhead = hdr_size + payload_per_allocation; - while(!overhead_satisfied){ - elements_per_subblock = (candidate_power_of_2 - max_subblock_overhead)/real_node_size; - const size_type overhead_size = candidate_power_of_2 - elements_per_subblock*real_node_size; - if(overhead_size*100/candidate_power_of_2 < overhead_percent){ - overhead_satisfied = true; - } - else{ - candidate_power_of_2 <<= 1; - } - } - return candidate_power_of_2; -} - -template -inline void calculate_num_subblocks - (size_type alignment, size_type real_node_size, size_type elements_per_block - , size_type &num_subblocks, size_type &real_num_node, size_type overhead_percent - , size_type hdr_size, size_type hdr_offset_size, size_type payload_per_allocation) -{ - const size_type hdr_subblock_elements = (alignment - hdr_size - payload_per_allocation)/real_node_size; - size_type elements_per_subblock = (alignment - hdr_offset_size)/real_node_size; - size_type possible_num_subblock = (elements_per_block - 1)/elements_per_subblock + 1; - while(((possible_num_subblock-1)*elements_per_subblock + hdr_subblock_elements) < elements_per_block){ - ++possible_num_subblock; - } - elements_per_subblock = (alignment - hdr_offset_size)/real_node_size; - bool overhead_satisfied = false; - while(!overhead_satisfied){ - const size_type total_data = (elements_per_subblock*(possible_num_subblock-1) + hdr_subblock_elements)*real_node_size; - const size_type total_size = alignment*possible_num_subblock; - if((total_size - total_data)*100/total_size < overhead_percent){ - overhead_satisfied = true; - } - else{ - ++possible_num_subblock; - } - } - num_subblocks = possible_num_subblock; - real_num_node = (possible_num_subblock-1)*elements_per_subblock + hdr_subblock_elements; -} - -template -class private_adaptive_node_pool_impl -{ - //Non-copyable - private_adaptive_node_pool_impl(); - private_adaptive_node_pool_impl(const private_adaptive_node_pool_impl &); - private_adaptive_node_pool_impl &operator=(const private_adaptive_node_pool_impl &); - typedef private_adaptive_node_pool_impl this_type; - - typedef typename SegmentManagerBase::void_pointer void_pointer; - static const typename SegmentManagerBase:: - size_type PayloadPerAllocation = SegmentManagerBase::PayloadPerAllocation; - //Flags - //align_only - static const bool AlignOnly = (Flags & adaptive_pool_flag::align_only) != 0; - typedef bool_ IsAlignOnly; - typedef true_ AlignOnlyTrue; - typedef false_ AlignOnlyFalse; - //size_ordered - static const bool SizeOrdered = (Flags & adaptive_pool_flag::size_ordered) != 0; - typedef bool_ IsSizeOrdered; - typedef true_ SizeOrderedTrue; - typedef false_ SizeOrderedFalse; - //address_ordered - static const bool AddressOrdered = (Flags & adaptive_pool_flag::address_ordered) != 0; - typedef bool_ IsAddressOrdered; - typedef true_ AddressOrderedTrue; - typedef false_ AddressOrderedFalse; - - public: - typedef typename SegmentManagerBase::multiallocation_chain multiallocation_chain; - typedef typename SegmentManagerBase::size_type size_type; - - private: - typedef adaptive_pool_types - adaptive_pool_types_t; - typedef typename adaptive_pool_types_t::free_nodes_t free_nodes_t; - typedef typename adaptive_pool_types_t::block_info_t block_info_t; - typedef typename adaptive_pool_types_t::block_container_t block_container_t; - typedef typename adaptive_pool_types_t::block_container_traits_t block_container_traits_t; - typedef typename block_container_t::iterator block_iterator; - typedef typename block_container_t::const_iterator const_block_iterator; - typedef typename adaptive_pool_types_t::hdr_offset_holder hdr_offset_holder; - - static const size_type MaxAlign = alignment_of::value; - static const size_type HdrSize = ((sizeof(block_info_t)-1)/MaxAlign+1)*MaxAlign; - static const size_type HdrOffsetSize = ((sizeof(hdr_offset_holder)-1)/MaxAlign+1)*MaxAlign; - - public: - //!Segment manager typedef - typedef SegmentManagerBase segment_manager_base_type; - - //!Constructor from a segment manager. Never throws - private_adaptive_node_pool_impl - ( segment_manager_base_type *segment_mngr_base - , size_type node_size - , size_type nodes_per_block - , size_type max_free_blocks - , unsigned char overhead_percent - ) - : m_max_free_blocks(max_free_blocks) - , m_real_node_size(lcm(node_size, size_type(alignment_of::value))) - //Round the size to a power of two value. - //This is the total memory size (including payload) that we want to - //allocate from the general-purpose allocator - , m_real_block_alignment - (AlignOnly ? - upper_power_of_2(HdrSize + m_real_node_size*nodes_per_block) : - calculate_alignment( (size_type)overhead_percent, m_real_node_size - , HdrSize, HdrOffsetSize, PayloadPerAllocation)) - //This is the real number of nodes per block - , m_num_subblocks(0) - , m_real_num_node(AlignOnly ? (m_real_block_alignment - PayloadPerAllocation - HdrSize)/m_real_node_size : 0) - //General purpose allocator - , mp_segment_mngr_base(segment_mngr_base) - , m_block_container() - , m_totally_free_blocks(0) - { - if(!AlignOnly){ - calculate_num_subblocks - ( m_real_block_alignment - , m_real_node_size - , nodes_per_block - , m_num_subblocks - , m_real_num_node - , (size_type)overhead_percent - , HdrSize - , HdrOffsetSize - , PayloadPerAllocation); - } - } - - //!Destructor. Deallocates all allocated blocks. Never throws - ~private_adaptive_node_pool_impl() - { this->priv_clear(); } - - size_type get_real_num_node() const - { return m_real_num_node; } - - //!Returns the segment manager. Never throws - segment_manager_base_type* get_segment_manager_base()const - { return container_detail::to_raw_pointer(mp_segment_mngr_base); } - - //!Allocates array of count elements. Can throw - void *allocate_node() - { - this->priv_invariants(); - //If there are no free nodes we allocate a new block - if(!m_block_container.empty()){ - //We take the first free node the multiset can't be empty - free_nodes_t &free_nodes = m_block_container.begin()->free_nodes; - BOOST_ASSERT(!free_nodes.empty()); - const size_type free_nodes_count = free_nodes.size(); - void *first_node = container_detail::to_raw_pointer(free_nodes.pop_front()); - if(free_nodes.empty()){ - block_container_traits_t::erase_first(m_block_container); - } - m_totally_free_blocks -= static_cast(free_nodes_count == m_real_num_node); - this->priv_invariants(); - return first_node; - } - else{ - multiallocation_chain chain; - this->priv_append_from_new_blocks(1, chain, IsAlignOnly()); - return container_detail::to_raw_pointer(chain.pop_front()); - } - } - - //!Deallocates an array pointed by ptr. Never throws - void deallocate_node(void *pElem) - { - this->priv_invariants(); - block_info_t &block_info = *this->priv_block_from_node(pElem); - BOOST_ASSERT(block_info.free_nodes.size() < m_real_num_node); - - //We put the node at the beginning of the free node list - block_info.free_nodes.push_back(void_pointer(pElem)); - - //The loop reinserts all blocks except the last one - this->priv_reinsert_block(block_info, block_info.free_nodes.size() == 1); - this->priv_deallocate_free_blocks(m_max_free_blocks); - this->priv_invariants(); - } - - //!Allocates n nodes. - //!Can throw - void allocate_nodes(const size_type n, multiallocation_chain &chain) - { - size_type i = 0; - BOOST_TRY{ - this->priv_invariants(); - while(i != n){ - //If there are no free nodes we allocate all needed blocks - if (m_block_container.empty()){ - this->priv_append_from_new_blocks(n - i, chain, IsAlignOnly()); - BOOST_ASSERT(m_block_container.empty() || (++m_block_container.cbegin() == m_block_container.cend())); - BOOST_ASSERT(chain.size() == n); - break; - } - free_nodes_t &free_nodes = m_block_container.begin()->free_nodes; - const size_type free_nodes_count_before = free_nodes.size(); - m_totally_free_blocks -= static_cast(free_nodes_count_before == m_real_num_node); - const size_type num_left = n-i; - const size_type num_elems = (num_left < free_nodes_count_before) ? num_left : free_nodes_count_before; - typedef typename free_nodes_t::iterator free_nodes_iterator; - - if(num_left < free_nodes_count_before){ - const free_nodes_iterator it_bbeg(free_nodes.before_begin()); - free_nodes_iterator it_bend(it_bbeg); - for(size_type j = 0; j != num_elems; ++j){ - ++it_bend; - } - free_nodes_iterator it_end = it_bend; ++it_end; - free_nodes_iterator it_beg = it_bbeg; ++it_beg; - free_nodes.erase_after(it_bbeg, it_end, num_elems); - chain.incorporate_after(chain.last(), &*it_beg, &*it_bend, num_elems); - //chain.splice_after(chain.last(), free_nodes, it_bbeg, it_bend, num_elems); - BOOST_ASSERT(!free_nodes.empty()); - } - else{ - const free_nodes_iterator it_beg(free_nodes.begin()), it_bend(free_nodes.last()); - free_nodes.clear(); - chain.incorporate_after(chain.last(), &*it_beg, &*it_bend, num_elems); - block_container_traits_t::erase_first(m_block_container); - } - i += num_elems; - } - } - BOOST_CATCH(...){ - this->deallocate_nodes(chain); - BOOST_RETHROW - } - BOOST_CATCH_END - this->priv_invariants(); - } - - //!Deallocates a linked list of nodes. Never throws - void deallocate_nodes(multiallocation_chain &nodes) - { - this->priv_invariants(); - //To take advantage of node locality, wait until two - //nodes belong to different blocks. Only then reinsert - //the block of the first node in the block tree. - //Cache of the previous block - block_info_t *prev_block_info = 0; - - //If block was empty before this call, it's not already - //inserted in the block tree. - bool prev_block_was_empty = false; - typedef typename free_nodes_t::iterator free_nodes_iterator; - { - const free_nodes_iterator itbb(nodes.before_begin()), ite(nodes.end()); - free_nodes_iterator itf(nodes.begin()), itbf(itbb); - size_type splice_node_count = size_type(-1); - while(itf != ite){ - void *pElem = container_detail::to_raw_pointer(&*itf); - block_info_t &block_info = *this->priv_block_from_node(pElem); - BOOST_ASSERT(block_info.free_nodes.size() < m_real_num_node); - ++splice_node_count; - - //If block change is detected calculate the cached block position in the tree - if(&block_info != prev_block_info){ - if(prev_block_info){ //Make sure we skip the initial "dummy" cache - free_nodes_iterator it(itbb); ++it; - nodes.erase_after(itbb, itf, splice_node_count); - prev_block_info->free_nodes.incorporate_after(prev_block_info->free_nodes.last(), &*it, &*itbf, splice_node_count); - this->priv_reinsert_block(*prev_block_info, prev_block_was_empty); - splice_node_count = 0; - } - //Update cache with new data - prev_block_was_empty = block_info.free_nodes.empty(); - prev_block_info = &block_info; - } - itbf = itf; - ++itf; - } - } - if(prev_block_info){ - //The loop reinserts all blocks except the last one - const free_nodes_iterator itfirst(nodes.begin()), itlast(nodes.last()); - const size_type splice_node_count = nodes.size(); - nodes.clear(); - prev_block_info->free_nodes.incorporate_after(prev_block_info->free_nodes.last(), &*itfirst, &*itlast, splice_node_count); - this->priv_reinsert_block(*prev_block_info, prev_block_was_empty); - this->priv_invariants(); - this->priv_deallocate_free_blocks(m_max_free_blocks); - } - } - - void deallocate_free_blocks() - { this->priv_deallocate_free_blocks(0); } - - size_type num_free_nodes() - { - typedef typename block_container_t::const_iterator citerator; - size_type count = 0; - citerator it (m_block_container.begin()), itend(m_block_container.end()); - for(; it != itend; ++it){ - count += it->free_nodes.size(); - } - return count; - } - - void swap(private_adaptive_node_pool_impl &other) - { - BOOST_ASSERT(m_max_free_blocks == other.m_max_free_blocks); - BOOST_ASSERT(m_real_node_size == other.m_real_node_size); - BOOST_ASSERT(m_real_block_alignment == other.m_real_block_alignment); - BOOST_ASSERT(m_real_num_node == other.m_real_num_node); - std::swap(mp_segment_mngr_base, other.mp_segment_mngr_base); - std::swap(m_totally_free_blocks, other.m_totally_free_blocks); - m_block_container.swap(other.m_block_container); - } - - //Deprecated, use deallocate_free_blocks - void deallocate_free_chunks() - { this->priv_deallocate_free_blocks(0); } - - private: - - void priv_deallocate_free_blocks(size_type max_free_blocks) - { //Trampoline function to ease inlining - if(m_totally_free_blocks > max_free_blocks){ - this->priv_deallocate_free_blocks_impl(max_free_blocks); - } - } - - void priv_deallocate_free_blocks_impl(size_type max_free_blocks) - { - this->priv_invariants(); - //Now check if we've reached the free nodes limit - //and check if we have free blocks. If so, deallocate as much - //as we can to stay below the limit - multiallocation_chain chain; - { - const const_block_iterator itend = m_block_container.cend(); - const_block_iterator it = itend; - --it; - size_type totally_free_blocks = m_totally_free_blocks; - - for( ; totally_free_blocks > max_free_blocks; --totally_free_blocks){ - BOOST_ASSERT(it->free_nodes.size() == m_real_num_node); - void *addr = priv_first_subblock_from_block(const_cast(&*it)); - --it; - block_container_traits_t::erase_last(m_block_container); - chain.push_front(void_pointer(addr)); - } - BOOST_ASSERT((m_totally_free_blocks - max_free_blocks) == chain.size()); - m_totally_free_blocks = max_free_blocks; - } - this->mp_segment_mngr_base->deallocate_many(chain); - } - - void priv_reinsert_block(block_info_t &prev_block_info, const bool prev_block_was_empty) - { - //Cache the free nodes from the block - const size_type this_block_free_nodes = prev_block_info.free_nodes.size(); - const bool is_full = this_block_free_nodes == m_real_num_node; - - //Update free block count - m_totally_free_blocks += static_cast(is_full); - if(prev_block_was_empty){ - block_container_traits_t::insert_was_empty(m_block_container, prev_block_info, is_full); - } - else{ - block_container_traits_t::reinsert_was_used(m_block_container, prev_block_info, is_full); - } - } - - class block_destroyer; - friend class block_destroyer; - - class block_destroyer - { - public: - block_destroyer(const this_type *impl, multiallocation_chain &chain) - : mp_impl(impl), m_chain(chain) - {} - - void operator()(typename block_container_t::pointer to_deallocate) - { return this->do_destroy(to_deallocate, IsAlignOnly()); } - - private: - void do_destroy(typename block_container_t::pointer to_deallocate, AlignOnlyTrue) - { - BOOST_ASSERT(to_deallocate->free_nodes.size() == mp_impl->m_real_num_node); - m_chain.push_back(to_deallocate); - } - - void do_destroy(typename block_container_t::pointer to_deallocate, AlignOnlyFalse) - { - BOOST_ASSERT(to_deallocate->free_nodes.size() == mp_impl->m_real_num_node); - BOOST_ASSERT(0 == to_deallocate->hdr_offset); - hdr_offset_holder *hdr_off_holder = - mp_impl->priv_first_subblock_from_block(container_detail::to_raw_pointer(to_deallocate)); - m_chain.push_back(hdr_off_holder); - } - - const this_type *mp_impl; - multiallocation_chain &m_chain; - }; - - //This macro will activate invariant checking. Slow, but helpful for debugging the code. - //#define BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS - void priv_invariants() - #ifdef BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS - #undef BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS - { - const const_block_iterator itend(m_block_container.end()); - - { //We iterate through the block tree to free the memory - const_block_iterator it(m_block_container.begin()); - - if(it != itend){ - for(++it; it != itend; ++it){ - const_block_iterator prev(it); - --prev; - BOOST_ASSERT(*prev < *it); - (void)prev; (void)it; - } - } - } - { //Check that the total free nodes are correct - const_block_iterator it(m_block_container.cbegin()); - size_type total_free_nodes = 0; - for(; it != itend; ++it){ - total_free_nodes += it->free_nodes.size(); - } - BOOST_ASSERT(total_free_nodes >= m_totally_free_blocks*m_real_num_node); - } - { //Check that the total totally free blocks are correct - BOOST_ASSERT(m_block_container.size() >= m_totally_free_blocks); - const_block_iterator it = m_block_container.cend(); - size_type total_free_blocks = m_totally_free_blocks; - while(total_free_blocks--){ - BOOST_ASSERT((--it)->free_nodes.size() == m_real_num_node); - } - } - - if(!AlignOnly){ - //Check that header offsets are correct - const_block_iterator it = m_block_container.begin(); - for(; it != itend; ++it){ - hdr_offset_holder *hdr_off_holder = this->priv_first_subblock_from_block(const_cast(&*it)); - for(size_type i = 0, max = m_num_subblocks; i < max; ++i){ - const size_type offset = reinterpret_cast(const_cast(&*it)) - reinterpret_cast(hdr_off_holder); - BOOST_ASSERT(hdr_off_holder->hdr_offset == offset); - BOOST_ASSERT(0 == ((size_type)hdr_off_holder & (m_real_block_alignment - 1))); - BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1))); - hdr_off_holder = reinterpret_cast(reinterpret_cast(hdr_off_holder) + m_real_block_alignment); - } - } - } - } - #else - {} //empty - #endif - - //!Deallocates all used memory. Never throws - void priv_clear() - { - #ifndef NDEBUG - block_iterator it = m_block_container.begin(); - block_iterator itend = m_block_container.end(); - size_type n_free_nodes = 0; - for(; it != itend; ++it){ - //Check for memory leak - BOOST_ASSERT(it->free_nodes.size() == m_real_num_node); - ++n_free_nodes; - } - BOOST_ASSERT(n_free_nodes == m_totally_free_blocks); - #endif - //Check for memory leaks - this->priv_invariants(); - multiallocation_chain chain; - m_block_container.clear_and_dispose(block_destroyer(this, chain)); - this->mp_segment_mngr_base->deallocate_many(chain); - m_totally_free_blocks = 0; - } - - block_info_t *priv_block_from_node(void *node, AlignOnlyFalse) const - { - hdr_offset_holder *hdr_off_holder = - reinterpret_cast((std::size_t)node & size_type(~(m_real_block_alignment - 1))); - BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1))); - BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1))); - block_info_t *block = reinterpret_cast - (reinterpret_cast(hdr_off_holder) + hdr_off_holder->hdr_offset); - BOOST_ASSERT(block->hdr_offset == 0); - return block; - } - - block_info_t *priv_block_from_node(void *node, AlignOnlyTrue) const - { - return (block_info_t *)((std::size_t)node & std::size_t(~(m_real_block_alignment - 1))); - } - - block_info_t *priv_block_from_node(void *node) const - { return this->priv_block_from_node(node, IsAlignOnly()); } - - hdr_offset_holder *priv_first_subblock_from_block(block_info_t *block) const - { return this->priv_first_subblock_from_block(block, IsAlignOnly()); } - - hdr_offset_holder *priv_first_subblock_from_block(block_info_t *block, AlignOnlyFalse) const - { - hdr_offset_holder *const hdr_off_holder = reinterpret_cast - (reinterpret_cast(block) - (m_num_subblocks-1)*m_real_block_alignment); - BOOST_ASSERT(hdr_off_holder->hdr_offset == size_type(reinterpret_cast(block) - reinterpret_cast(hdr_off_holder))); - BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1))); - BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1))); - return hdr_off_holder; - } - - hdr_offset_holder *priv_first_subblock_from_block(block_info_t *block, AlignOnlyTrue) const - { - return reinterpret_cast(block); - } - - void priv_dispatch_block_chain_or_free - ( multiallocation_chain &chain, block_info_t &c_info, size_type num_node - , char *mem_address, size_type total_elements, bool insert_block_if_free) - { - BOOST_ASSERT(chain.size() <= total_elements); - //First add all possible nodes to the chain - const size_type left = total_elements - chain.size(); - const size_type max_chain = (num_node < left) ? num_node : left; - mem_address = static_cast(container_detail::to_raw_pointer - (chain.incorporate_after(chain.last(), void_pointer(mem_address), m_real_node_size, max_chain))); - //Now store remaining nodes in the free list - if(const size_type max_free = num_node - max_chain){ - free_nodes_t & free_nodes = c_info.free_nodes; - free_nodes.incorporate_after(free_nodes.last(), void_pointer(mem_address), m_real_node_size, max_free); - if(insert_block_if_free){ - m_block_container.push_front(c_info); - } - } - } - - //!Allocates a several blocks of nodes. Can throw - void priv_append_from_new_blocks(size_type min_elements, multiallocation_chain &chain, AlignOnlyTrue) - { - BOOST_ASSERT(m_block_container.empty()); - BOOST_ASSERT(min_elements > 0); - const size_type n = (min_elements - 1)/m_real_num_node + 1; - const size_type real_block_size = m_real_block_alignment - PayloadPerAllocation; - const size_type total_elements = chain.size() + min_elements; - for(size_type i = 0; i != n; ++i){ - //We allocate a new NodeBlock and put it the last - //element of the tree - char *mem_address = static_cast - (mp_segment_mngr_base->allocate_aligned(real_block_size, m_real_block_alignment)); - if(!mem_address){ - //In case of error, free memory deallocating all nodes (the new ones allocated - //in this function plus previously stored nodes in chain). - this->deallocate_nodes(chain); - throw_bad_alloc(); - } - block_info_t &c_info = *new(mem_address)block_info_t(); - mem_address += HdrSize; - if(i != (n-1)){ - chain.incorporate_after(chain.last(), void_pointer(mem_address), m_real_node_size, m_real_num_node); - } - else{ - this->priv_dispatch_block_chain_or_free(chain, c_info, m_real_num_node, mem_address, total_elements, true); - } - } - } - - void priv_append_from_new_blocks(size_type min_elements, multiallocation_chain &chain, AlignOnlyFalse) - { - BOOST_ASSERT(m_block_container.empty()); - BOOST_ASSERT(min_elements > 0); - const size_type n = (min_elements - 1)/m_real_num_node + 1; - const size_type real_block_size = m_real_block_alignment*m_num_subblocks - PayloadPerAllocation; - const size_type elements_per_subblock = (m_real_block_alignment - HdrOffsetSize)/m_real_node_size; - const size_type hdr_subblock_elements = (m_real_block_alignment - HdrSize - PayloadPerAllocation)/m_real_node_size; - const size_type total_elements = chain.size() + min_elements; - - for(size_type i = 0; i != n; ++i){ - //We allocate a new NodeBlock and put it the last - //element of the tree - char *mem_address = static_cast - (mp_segment_mngr_base->allocate_aligned(real_block_size, m_real_block_alignment)); - if(!mem_address){ - //In case of error, free memory deallocating all nodes (the new ones allocated - //in this function plus previously stored nodes in chain). - this->deallocate_nodes(chain); - throw_bad_alloc(); - } - //First initialize header information on the last subblock - char *hdr_addr = mem_address + m_real_block_alignment*(m_num_subblocks-1); - block_info_t &c_info = *new(hdr_addr)block_info_t(); - //Some structural checks - BOOST_ASSERT(static_cast(&static_cast(c_info).hdr_offset) == - static_cast(&c_info)); (void)c_info; - if(i != (n-1)){ - for( size_type subblock = 0, maxsubblock = m_num_subblocks - 1 - ; subblock < maxsubblock - ; ++subblock, mem_address += m_real_block_alignment){ - //Initialize header offset mark - new(mem_address) hdr_offset_holder(size_type(hdr_addr - mem_address)); - chain.incorporate_after - (chain.last(), void_pointer(mem_address + HdrOffsetSize), m_real_node_size, elements_per_subblock); - } - chain.incorporate_after(chain.last(), void_pointer(hdr_addr + HdrSize), m_real_node_size, hdr_subblock_elements); - } - else{ - for( size_type subblock = 0, maxsubblock = m_num_subblocks - 1 - ; subblock < maxsubblock - ; ++subblock, mem_address += m_real_block_alignment){ - //Initialize header offset mark - new(mem_address) hdr_offset_holder(size_type(hdr_addr - mem_address)); - this->priv_dispatch_block_chain_or_free - (chain, c_info, elements_per_subblock, mem_address + HdrOffsetSize, total_elements, false); - } - this->priv_dispatch_block_chain_or_free - (chain, c_info, hdr_subblock_elements, hdr_addr + HdrSize, total_elements, true); - } - } - } - - private: - typedef typename boost::intrusive::pointer_traits - ::template rebind_pointer::type segment_mngr_base_ptr_t; - const size_type m_max_free_blocks; - const size_type m_real_node_size; - //Round the size to a power of two value. - //This is the total memory size (including payload) that we want to - //allocate from the general-purpose allocator - const size_type m_real_block_alignment; - size_type m_num_subblocks; - //This is the real number of nodes per block - //const - size_type m_real_num_node; - segment_mngr_base_ptr_t mp_segment_mngr_base; //Segment manager - block_container_t m_block_container; //Intrusive block list - size_type m_totally_free_blocks; //Free blocks -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP diff --git a/utils/boost_idb/boost/container/detail/advanced_insert_int.hpp b/utils/boost_idb/boost/container/detail/advanced_insert_int.hpp deleted file mode 100644 index e42bcb31..00000000 --- a/utils/boost_idb/boost/container/detail/advanced_insert_int.hpp +++ /dev/null @@ -1,393 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP -#define BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include -#include -#include -#include -#include -#include //std::iterator_traits -#include -#include - -namespace boost { namespace container { namespace container_detail { - -template -struct move_insert_range_proxy -{ - typedef typename allocator_traits::size_type size_type; - typedef typename allocator_traits::value_type value_type; - - move_insert_range_proxy(A& a, FwdIt first) - : a_(a), first_(first) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) - { - this->first_ = ::boost::container::uninitialized_move_alloc_n_source - (this->a_, this->first_, n, p); - } - - void copy_n_and_update(Iterator p, size_type n) - { - this->first_ = ::boost::container::move_n_source(this->first_, n, p); - } - - A &a_; - FwdIt first_; -}; - - -template -struct insert_range_proxy -{ - typedef typename allocator_traits::size_type size_type; - typedef typename allocator_traits::value_type value_type; - - insert_range_proxy(A& a, FwdIt first) - : a_(a), first_(first) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) - { - this->first_ = ::boost::container::uninitialized_copy_alloc_n_source(this->a_, this->first_, n, p); - } - - void copy_n_and_update(Iterator p, size_type n) - { - this->first_ = ::boost::container::copy_n_source(this->first_, n, p); - } - - A &a_; - FwdIt first_; -}; - - -template -struct insert_n_copies_proxy -{ - typedef typename allocator_traits::size_type size_type; - typedef typename allocator_traits::value_type value_type; - - insert_n_copies_proxy(A& a, const value_type &v) - : a_(a), v_(v) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) const - { boost::container::uninitialized_fill_alloc_n(this->a_, v_, n, p); } - - void copy_n_and_update(Iterator p, size_type n) const - { std::fill_n(p, n, v_); } - - A &a_; - const value_type &v_; -}; - -template -struct insert_value_initialized_n_proxy -{ - typedef ::boost::container::allocator_traits alloc_traits; - typedef typename allocator_traits::size_type size_type; - typedef typename allocator_traits::value_type value_type; - - - explicit insert_value_initialized_n_proxy(A &a) - : a_(a) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) const - { boost::container::uninitialized_value_init_alloc_n(this->a_, n, p); } - - void copy_n_and_update(Iterator, size_type) const - { - BOOST_ASSERT(false); - } - - private: - A &a_; -}; - -template -struct insert_default_initialized_n_proxy -{ - typedef ::boost::container::allocator_traits alloc_traits; - typedef typename allocator_traits::size_type size_type; - typedef typename allocator_traits::value_type value_type; - - - explicit insert_default_initialized_n_proxy(A &a) - : a_(a) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) const - { boost::container::uninitialized_default_init_alloc_n(this->a_, n, p); } - - void copy_n_and_update(Iterator, size_type) const - { - BOOST_ASSERT(false); - } - - private: - A &a_; -}; - -template -struct insert_copy_proxy -{ - typedef boost::container::allocator_traits alloc_traits; - typedef typename alloc_traits::size_type size_type; - typedef typename alloc_traits::value_type value_type; - - insert_copy_proxy(A& a, const value_type &v) - : a_(a), v_(v) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) const - { - BOOST_ASSERT(n == 1); (void)n; - alloc_traits::construct( this->a_ - , container_detail::to_raw_pointer(&*p) - , v_ - ); - } - - void copy_n_and_update(Iterator p, size_type n) const - { - BOOST_ASSERT(n == 1); (void)n; - *p =v_; - } - - A &a_; - const value_type &v_; -}; - - -template -struct insert_move_proxy -{ - typedef boost::container::allocator_traits alloc_traits; - typedef typename alloc_traits::size_type size_type; - typedef typename alloc_traits::value_type value_type; - - insert_move_proxy(A& a, value_type &v) - : a_(a), v_(v) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) const - { - BOOST_ASSERT(n == 1); (void)n; - alloc_traits::construct( this->a_ - , container_detail::to_raw_pointer(&*p) - , ::boost::move(v_) - ); - } - - void copy_n_and_update(Iterator p, size_type n) const - { - BOOST_ASSERT(n == 1); (void)n; - *p = ::boost::move(v_); - } - - A &a_; - value_type &v_; -}; - -template -insert_move_proxy get_insert_value_proxy(A& a, BOOST_RV_REF(typename std::iterator_traits::value_type) v) -{ - return insert_move_proxy(a, v); -} - -template -insert_copy_proxy get_insert_value_proxy(A& a, const typename std::iterator_traits::value_type &v) -{ - return insert_copy_proxy(a, v); -} - -}}} //namespace boost { namespace container { namespace container_detail { - -#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - -#include -#include -#include -//#include //For debugging purposes - -namespace boost { -namespace container { -namespace container_detail { - -template -struct insert_non_movable_emplace_proxy -{ - typedef boost::container::allocator_traits alloc_traits; - typedef typename alloc_traits::size_type size_type; - typedef typename alloc_traits::value_type value_type; - - typedef typename build_number_seq::type index_tuple_t; - - explicit insert_non_movable_emplace_proxy(A &a, Args&&... args) - : a_(a), args_(args...) - {} - - void uninitialized_copy_n_and_update(Iterator p, size_type n) - { this->priv_uninitialized_copy_some_and_update(index_tuple_t(), p, n); } - - private: - template - void priv_uninitialized_copy_some_and_update(const index_tuple&, Iterator p, size_type n) - { - BOOST_ASSERT(n == 1); (void)n; - alloc_traits::construct( this->a_ - , container_detail::to_raw_pointer(&*p) - , ::boost::forward(get(this->args_))... - ); - } - - protected: - A &a_; - tuple args_; -}; - -template -struct insert_emplace_proxy - : public insert_non_movable_emplace_proxy -{ - typedef insert_non_movable_emplace_proxy base_t; - typedef boost::container::allocator_traits alloc_traits; - typedef typename base_t::value_type value_type; - typedef typename base_t::size_type size_type; - typedef typename base_t::index_tuple_t index_tuple_t; - - explicit insert_emplace_proxy(A &a, Args&&... args) - : base_t(a, ::boost::forward(args)...) - {} - - void copy_n_and_update(Iterator p, size_type n) - { this->priv_copy_some_and_update(index_tuple_t(), p, n); } - - private: - - template - void priv_copy_some_and_update(const index_tuple&, Iterator p, size_type n) - { - BOOST_ASSERT(n ==1); (void)n; - aligned_storage::value> v; - value_type *vp = static_cast(static_cast(&v)); - alloc_traits::construct(this->a_, vp, - ::boost::forward(get(this->args_))...); - BOOST_TRY{ - *p = ::boost::move(*vp); - } - BOOST_CATCH(...){ - alloc_traits::destroy(this->a_, vp); - BOOST_RETHROW - } - BOOST_CATCH_END - alloc_traits::destroy(this->a_, vp); - } -}; - -}}} //namespace boost { namespace container { namespace container_detail { - -#else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - -#include -#include - -namespace boost { -namespace container { -namespace container_detail { - -#define BOOST_PP_LOCAL_MACRO(N) \ -template \ -struct BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ -{ \ - typedef boost::container::allocator_traits alloc_traits; \ - typedef typename alloc_traits::size_type size_type; \ - typedef typename alloc_traits::value_type value_type; \ - \ - BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ - ( A &a BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_PARAM_LIST, _) ) \ - : a_(a) \ - BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_PARAM_INIT, _) \ - {} \ - \ - void uninitialized_copy_n_and_update(Iterator p, size_type n) \ - { \ - BOOST_ASSERT(n == 1); (void)n; \ - alloc_traits::construct \ - ( this->a_ \ - , container_detail::to_raw_pointer(&*p) \ - BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_MEMBER_FORWARD, _) \ - ); \ - } \ - \ - void copy_n_and_update(Iterator, size_type) \ - { BOOST_ASSERT(false); } \ - \ - protected: \ - A &a_; \ - BOOST_PP_REPEAT(N, BOOST_CONTAINER_PP_PARAM_DEFINE, _) \ -}; \ - \ -template \ -struct BOOST_PP_CAT(insert_emplace_proxy_arg, N) \ - : BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ - < A, Iterator BOOST_PP_ENUM_TRAILING_PARAMS(N, P) > \ -{ \ - typedef BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ - base_t; \ - typedef typename base_t::value_type value_type; \ - typedef typename base_t::size_type size_type; \ - typedef boost::container::allocator_traits alloc_traits; \ - \ - BOOST_PP_CAT(insert_emplace_proxy_arg, N) \ - ( A &a BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_PARAM_LIST, _) ) \ - : base_t(a BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ) \ - {} \ - \ - void copy_n_and_update(Iterator p, size_type n) \ - { \ - BOOST_ASSERT(n == 1); (void)n; \ - aligned_storage::value> v; \ - value_type *vp = static_cast(static_cast(&v)); \ - alloc_traits::construct(this->a_, vp \ - BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_MEMBER_FORWARD, _)); \ - BOOST_TRY{ \ - *p = ::boost::move(*vp); \ - } \ - BOOST_CATCH(...){ \ - alloc_traits::destroy(this->a_, vp); \ - BOOST_RETHROW \ - } \ - BOOST_CATCH_END \ - alloc_traits::destroy(this->a_, vp); \ - } \ -}; \ -//! -#define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) -#include BOOST_PP_LOCAL_ITERATE() - -}}} //namespace boost { namespace container { namespace container_detail { - -#endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - -#include - -#endif //#ifndef BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP diff --git a/utils/boost_idb/boost/container/detail/algorithms.hpp b/utils/boost_idb/boost/container/detail/algorithms.hpp deleted file mode 100644 index 7a4a8684..00000000 --- a/utils/boost_idb/boost/container/detail/algorithms.hpp +++ /dev/null @@ -1,90 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP -#define BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include - -#include -#include -#include - -#include -#include -#include - - -#include - -namespace boost { -namespace container { - -template -struct is_value_init_construct_iterator -{ - static const bool value = false; -}; - -template -struct is_value_init_construct_iterator > -{ - static const bool value = true; -}; - -template -struct is_emplace_iterator -{ - static const bool value = false; -}; - -template -struct is_emplace_iterator > -{ - static const bool value = true; -}; - -template -inline void construct_in_place(A &a, T* dest, InpIt source) -{ boost::container::allocator_traits::construct(a, dest, *source); } -//#endif - -template -inline void construct_in_place(A &a, T *dest, value_init_construct_iterator) -{ - boost::container::allocator_traits::construct(a, dest); -} - -template -inline void construct_in_place(A &a, T *dest, default_init_construct_iterator) -{ - boost::container::allocator_traits::construct(a, dest, default_init); -} - -template -inline void construct_in_place(A &a, T *dest, emplace_iterator ei) -{ - ei.construct_in_place(a, dest); -} - -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP - diff --git a/utils/boost_idb/boost/container/detail/allocator_version_traits.hpp b/utils/boost_idb/boost/container/detail/allocator_version_traits.hpp deleted file mode 100644 index 6df79da8..00000000 --- a/utils/boost_idb/boost/container/detail/allocator_version_traits.hpp +++ /dev/null @@ -1,167 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_ALLOCATOR_VERSION_TRAITS_HPP -#define BOOST_CONTAINER_DETAIL_ALLOCATOR_VERSION_TRAITS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include //allocator_traits -#include -#include //multiallocation_chain -#include //version_type -#include //allocation_type -#include //integral_constant -#include //pointer_traits -#include //pair -#include //BOOST_TRY - -namespace boost { -namespace container { -namespace container_detail { - -template::value> -struct allocator_version_traits -{ - typedef ::boost::container::container_detail::integral_constant - alloc_version; - - typedef typename Allocator::multiallocation_chain multiallocation_chain; - - typedef typename boost::container::allocator_traits::pointer pointer; - typedef typename boost::container::allocator_traits::size_type size_type; - - //Node allocation interface - static pointer allocate_one(Allocator &a) - { return a.allocate_one(); } - - static void deallocate_one(Allocator &a, const pointer &p) - { a.deallocate_one(p); } - - static void allocate_individual(Allocator &a, size_type n, multiallocation_chain &m) - { return a.allocate_individual(n, m); } - - static void deallocate_individual(Allocator &a, multiallocation_chain &holder) - { a.deallocate_individual(holder); } - - static std::pair - allocation_command(Allocator &a, allocation_type command, - size_type limit_size, size_type preferred_size, - size_type &received_size, const pointer &reuse) - { - return a.allocation_command - (command, limit_size, preferred_size, received_size, reuse); - } -}; - -template -struct allocator_version_traits -{ - typedef ::boost::container::container_detail::integral_constant - alloc_version; - - typedef typename boost::container::allocator_traits::pointer pointer; - typedef typename boost::container::allocator_traits::size_type size_type; - typedef typename boost::container::allocator_traits::value_type value_type; - - typedef typename boost::intrusive::pointer_traits:: - template rebind_pointer::type void_ptr; - typedef container_detail::basic_multiallocation_chain - multialloc_cached_counted; - typedef boost::container::container_detail:: - transform_multiallocation_chain - < multialloc_cached_counted, value_type> multiallocation_chain; - - //Node allocation interface - static pointer allocate_one(Allocator &a) - { return a.allocate(1); } - - static void deallocate_one(Allocator &a, const pointer &p) - { a.deallocate(p, 1); } - - static void deallocate_individual(Allocator &a, multiallocation_chain &holder) - { - size_type n = holder.size(); - typename multiallocation_chain::iterator it = holder.begin(); - while(n--){ - pointer p = boost::intrusive::pointer_traits::pointer_to(*it); - ++it; - a.deallocate(p, 1); - } - } - - struct allocate_individual_rollback - { - allocate_individual_rollback(Allocator &a, multiallocation_chain &chain) - : mr_a(a), mp_chain(&chain) - {} - - ~allocate_individual_rollback() - { - if(mp_chain) - allocator_version_traits::deallocate_individual(mr_a, *mp_chain); - } - - void release() - { - mp_chain = 0; - } - - Allocator &mr_a; - multiallocation_chain * mp_chain; - }; - - static void allocate_individual(Allocator &a, size_type n, multiallocation_chain &m) - { - allocate_individual_rollback rollback(a, m); - while(n--){ - m.push_front(a.allocate(1)); - } - rollback.release(); - } - - static std::pair - allocation_command(Allocator &a, allocation_type command, - size_type, size_type preferred_size, - size_type &received_size, const pointer &) - { - std::pair ret(pointer(), false); - if(!(command & allocate_new)){ - if(!(command & nothrow_allocation)){ - throw_logic_error("version 1 allocator without allocate_new flag"); - } - } - else{ - received_size = preferred_size; - BOOST_TRY{ - ret.first = a.allocate(received_size); - } - BOOST_CATCH(...){ - if(!(command & nothrow_allocation)){ - BOOST_RETHROW - } - } - BOOST_CATCH_END - } - return ret; - } -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif // ! defined(BOOST_CONTAINER_DETAIL_ALLOCATOR_VERSION_TRAITS_HPP) diff --git a/utils/boost_idb/boost/container/detail/config_begin.hpp b/utils/boost_idb/boost/container/detail/config_begin.hpp deleted file mode 100644 index 664f0927..00000000 --- a/utils/boost_idb/boost/container/detail/config_begin.hpp +++ /dev/null @@ -1,50 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_CONFIG_INCLUDED -#define BOOST_CONTAINER_CONTAINER_DETAIL_CONFIG_INCLUDED -#include - -#endif //BOOST_CONTAINER_CONTAINER_DETAIL_CONFIG_INCLUDED - -#ifdef BOOST_MSVC - #ifndef _CRT_SECURE_NO_DEPRECATE - #define BOOST_CONTAINER_DETAIL_CRT_SECURE_NO_DEPRECATE - #define _CRT_SECURE_NO_DEPRECATE - #endif - #pragma warning (push) - #pragma warning (disable : 4702) // unreachable code - #pragma warning (disable : 4706) // assignment within conditional expression - #pragma warning (disable : 4127) // conditional expression is constant - #pragma warning (disable : 4146) // unary minus operator applied to unsigned type, result still unsigned - #pragma warning (disable : 4284) // odd return type for operator-> - #pragma warning (disable : 4244) // possible loss of data - #pragma warning (disable : 4251) // "identifier" : class "type" needs to have dll-interface to be used by clients of class "type2" - #pragma warning (disable : 4267) // conversion from "X" to "Y", possible loss of data - #pragma warning (disable : 4275) // non DLL-interface classkey "identifier" used as base for DLL-interface classkey "identifier" - #pragma warning (disable : 4355) // "this" : used in base member initializer list - #pragma warning (disable : 4503) // "identifier" : decorated name length exceeded, name was truncated - #pragma warning (disable : 4511) // copy constructor could not be generated - #pragma warning (disable : 4512) // assignment operator could not be generated - #pragma warning (disable : 4514) // unreferenced inline removed - #pragma warning (disable : 4521) // Disable "multiple copy constructors specified" - #pragma warning (disable : 4522) // "class" : multiple assignment operators specified - #pragma warning (disable : 4675) // "method" should be declared "static" and have exactly one parameter - #pragma warning (disable : 4710) // function not inlined - #pragma warning (disable : 4711) // function selected for automatic inline expansion - #pragma warning (disable : 4786) // identifier truncated in debug info - #pragma warning (disable : 4996) // "function": was declared deprecated - #pragma warning (disable : 4197) // top-level volatile in cast is ignored - #pragma warning (disable : 4541) // 'typeid' used on polymorphic type 'boost::exception' - // with /GR-; unpredictable behavior may result - #pragma warning (disable : 4673) // throwing '' the following types will not be considered at the catch site - #pragma warning (disable : 4671) // the copy constructor is inaccessible - #pragma warning (disable : 4584) // X is already a base-class of Y - #pragma warning (disable : 4510) // default constructor could not be generated -#endif //BOOST_MSVC diff --git a/utils/boost_idb/boost/container/detail/config_end.hpp b/utils/boost_idb/boost/container/detail/config_end.hpp deleted file mode 100644 index 34513718..00000000 --- a/utils/boost_idb/boost/container/detail/config_end.hpp +++ /dev/null @@ -1,17 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#if defined BOOST_MSVC - #pragma warning (pop) - #ifdef BOOST_CONTAINER_DETAIL_CRT_SECURE_NO_DEPRECATE - #undef BOOST_CONTAINER_DETAIL_CRT_SECURE_NO_DEPRECATE - #undef _CRT_SECURE_NO_DEPRECATE - #endif -#endif - diff --git a/utils/boost_idb/boost/container/detail/destroyers.hpp b/utils/boost_idb/boost/container/detail/destroyers.hpp deleted file mode 100644 index fef8aa04..00000000 --- a/utils/boost_idb/boost/container/detail/destroyers.hpp +++ /dev/null @@ -1,376 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DESTROYERS_HPP -#define BOOST_CONTAINER_DESTROYERS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include -#include -#include -#include - -namespace boost { -namespace container { -namespace container_detail { - -//!A deleter for scoped_ptr that deallocates the memory -//!allocated for an object using a STL allocator. -template -struct scoped_deallocator -{ - typedef allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::pointer pointer; - typedef container_detail::integral_constant::value> alloc_version; - typedef container_detail::integral_constant allocator_v1; - typedef container_detail::integral_constant allocator_v2; - - private: - void priv_deallocate(allocator_v1) - { m_alloc.deallocate(m_ptr, 1); } - - void priv_deallocate(allocator_v2) - { m_alloc.deallocate_one(m_ptr); } - - BOOST_MOVABLE_BUT_NOT_COPYABLE(scoped_deallocator) - - public: - - pointer m_ptr; - A& m_alloc; - - scoped_deallocator(pointer p, A& a) - : m_ptr(p), m_alloc(a) - {} - - ~scoped_deallocator() - { if (m_ptr)priv_deallocate(alloc_version()); } - - scoped_deallocator(BOOST_RV_REF(scoped_deallocator) o) - : m_ptr(o.m_ptr), m_alloc(o.m_alloc) - { o.release(); } - - pointer get() const - { return m_ptr; } - - void set(const pointer &p) - { m_ptr = p; } - - void release() - { m_ptr = 0; } -}; - -template -struct null_scoped_deallocator -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::pointer pointer; - typedef typename AllocTraits::size_type size_type; - - null_scoped_deallocator(pointer, Allocator&, size_type) - {} - - void release() - {} - - pointer get() const - { return pointer(); } - - void set(const pointer &) - {} -}; - -//!A deleter for scoped_ptr that deallocates the memory -//!allocated for an array of objects using a STL allocator. -template -struct scoped_array_deallocator -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::pointer pointer; - typedef typename AllocTraits::size_type size_type; - - scoped_array_deallocator(pointer p, Allocator& a, size_type length) - : m_ptr(p), m_alloc(a), m_length(length) {} - - ~scoped_array_deallocator() - { if (m_ptr) m_alloc.deallocate(m_ptr, m_length); } - - void release() - { m_ptr = 0; } - - private: - pointer m_ptr; - Allocator& m_alloc; - size_type m_length; -}; - -template -struct null_scoped_array_deallocator -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::pointer pointer; - typedef typename AllocTraits::size_type size_type; - - null_scoped_array_deallocator(pointer, Allocator&, size_type) - {} - - void release() - {} -}; - -template -struct scoped_destroy_deallocator -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::pointer pointer; - typedef typename AllocTraits::size_type size_type; - typedef container_detail::integral_constant::value> alloc_version; - typedef container_detail::integral_constant allocator_v1; - typedef container_detail::integral_constant allocator_v2; - - scoped_destroy_deallocator(pointer p, Allocator& a) - : m_ptr(p), m_alloc(a) {} - - ~scoped_destroy_deallocator() - { - if(m_ptr){ - AllocTraits::destroy(m_alloc, container_detail::to_raw_pointer(m_ptr)); - priv_deallocate(m_ptr, alloc_version()); - } - } - - void release() - { m_ptr = 0; } - - private: - - void priv_deallocate(const pointer &p, allocator_v1) - { AllocTraits::deallocate(m_alloc, p, 1); } - - void priv_deallocate(const pointer &p, allocator_v2) - { m_alloc.deallocate_one(p); } - - pointer m_ptr; - Allocator& m_alloc; -}; - - -//!A deleter for scoped_ptr that destroys -//!an object using a STL allocator. -template -struct scoped_destructor_n -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::pointer pointer; - typedef typename AllocTraits::value_type value_type; - typedef typename AllocTraits::size_type size_type; - - scoped_destructor_n(pointer p, Allocator& a, size_type n) - : m_p(p), m_a(a), m_n(n) - {} - - void release() - { m_p = 0; } - - void increment_size(size_type inc) - { m_n += inc; } - - void increment_size_backwards(size_type inc) - { m_n += inc; m_p -= inc; } - - void shrink_forward(size_type inc) - { m_n -= inc; m_p += inc; } - - ~scoped_destructor_n() - { - if(!m_p) return; - value_type *raw_ptr = container_detail::to_raw_pointer(m_p); - while(m_n--){ - AllocTraits::destroy(m_a, raw_ptr); - } - } - - private: - pointer m_p; - Allocator & m_a; - size_type m_n; -}; - -//!A deleter for scoped_ptr that destroys -//!an object using a STL allocator. -template -struct null_scoped_destructor_n -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::pointer pointer; - typedef typename AllocTraits::size_type size_type; - - null_scoped_destructor_n(pointer, Allocator&, size_type) - {} - - void increment_size(size_type) - {} - - void increment_size_backwards(size_type) - {} - - void release() - {} -}; - -template -class scoped_destructor -{ - typedef boost::container::allocator_traits AllocTraits; - public: - typedef typename A::value_type value_type; - scoped_destructor(A &a, value_type *pv) - : pv_(pv), a_(a) - {} - - ~scoped_destructor() - { - if(pv_){ - AllocTraits::destroy(a_, pv_); - } - } - - void release() - { pv_ = 0; } - - - void set(value_type *ptr) { pv_ = ptr; } - - value_type *get() const { return pv_; } - - private: - value_type *pv_; - A &a_; -}; - - -template -class value_destructor -{ - typedef boost::container::allocator_traits AllocTraits; - public: - typedef typename A::value_type value_type; - value_destructor(A &a, value_type &rv) - : rv_(rv), a_(a) - {} - - ~value_destructor() - { - AllocTraits::destroy(a_, &rv_); - } - - private: - value_type &rv_; - A &a_; -}; - -template -class allocator_destroyer -{ - typedef boost::container::allocator_traits AllocTraits; - typedef typename AllocTraits::value_type value_type; - typedef typename AllocTraits::pointer pointer; - typedef container_detail::integral_constant::value> alloc_version; - typedef container_detail::integral_constant allocator_v1; - typedef container_detail::integral_constant allocator_v2; - - private: - Allocator & a_; - - private: - void priv_deallocate(const pointer &p, allocator_v1) - { AllocTraits::deallocate(a_,p, 1); } - - void priv_deallocate(const pointer &p, allocator_v2) - { a_.deallocate_one(p); } - - public: - allocator_destroyer(Allocator &a) - : a_(a) - {} - - void operator()(const pointer &p) - { - AllocTraits::destroy(a_, container_detail::to_raw_pointer(p)); - this->priv_deallocate(p, alloc_version()); - } -}; - -template -class allocator_destroyer_and_chain_builder -{ - typedef allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::value_type value_type; - typedef typename A::multiallocation_chain multiallocation_chain; - - A & a_; - multiallocation_chain &c_; - - public: - allocator_destroyer_and_chain_builder(A &a, multiallocation_chain &c) - : a_(a), c_(c) - {} - - void operator()(const typename A::pointer &p) - { - allocator_traits::destroy(a_, container_detail::to_raw_pointer(p)); - c_.push_back(p); - } -}; - -template -class allocator_multialloc_chain_node_deallocator -{ - typedef allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::value_type value_type; - typedef typename A::multiallocation_chain multiallocation_chain; - typedef allocator_destroyer_and_chain_builder chain_builder; - - A & a_; - multiallocation_chain c_; - - public: - allocator_multialloc_chain_node_deallocator(A &a) - : a_(a), c_() - {} - - chain_builder get_chain_builder() - { return chain_builder(a_, c_); } - - ~allocator_multialloc_chain_node_deallocator() - { - a_.deallocate_individual(c_); - } -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DESTROYERS_HPP diff --git a/utils/boost_idb/boost/container/detail/flat_tree.hpp b/utils/boost_idb/boost/container/detail/flat_tree.hpp deleted file mode 100644 index f214d191..00000000 --- a/utils/boost_idb/boost/container/detail/flat_tree.hpp +++ /dev/null @@ -1,1026 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -//////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_FLAT_TREE_HPP -#define BOOST_CONTAINER_FLAT_TREE_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include - -#include - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#ifdef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER -#include -#endif -#include - -namespace boost { - -namespace container { - -namespace container_detail { - -template -class flat_tree_value_compare - : private Compare -{ - typedef Value first_argument_type; - typedef Value second_argument_type; - typedef bool return_type; - public: - flat_tree_value_compare() - : Compare() - {} - - flat_tree_value_compare(const Compare &pred) - : Compare(pred) - {} - - bool operator()(const Value& lhs, const Value& rhs) const - { - KeyOfValue key_extract; - return Compare::operator()(key_extract(lhs), key_extract(rhs)); - } - - const Compare &get_comp() const - { return *this; } - - Compare &get_comp() - { return *this; } -}; - -template -struct get_flat_tree_iterators -{ - #ifdef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - typedef Pointer iterator; - typedef typename boost::intrusive:: - pointer_traits::element_type iterator_element_type; - typedef typename boost::intrusive:: - pointer_traits:: template - rebind_pointer::type const_iterator; - #else //BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - typedef typename container_detail:: - vec_iterator iterator; - typedef typename container_detail:: - vec_iterator const_iterator; - #endif //BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; -}; - -template -class flat_tree -{ - typedef boost::container::vector vector_t; - typedef A allocator_t; - - public: - typedef flat_tree_value_compare value_compare; - - private: - struct Data - //Inherit from value_compare to do EBO - : public value_compare - { - BOOST_COPYABLE_AND_MOVABLE(Data) - - public: - Data() - : value_compare(), m_vect() - {} - - explicit Data(const Data &d) - : value_compare(static_cast(d)), m_vect(d.m_vect) - {} - - Data(BOOST_RV_REF(Data) d) - : value_compare(boost::move(static_cast(d))), m_vect(boost::move(d.m_vect)) - {} - - Data(const Data &d, const A &a) - : value_compare(static_cast(d)), m_vect(d.m_vect, a) - {} - - Data(BOOST_RV_REF(Data) d, const A &a) - : value_compare(boost::move(static_cast(d))), m_vect(boost::move(d.m_vect), a) - {} - - explicit Data(const Compare &comp) - : value_compare(comp), m_vect() - {} - - Data(const Compare &comp, const allocator_t &alloc) - : value_compare(comp), m_vect(alloc) - {} - - explicit Data(const allocator_t &alloc) - : value_compare(), m_vect(alloc) - {} - - Data& operator=(BOOST_COPY_ASSIGN_REF(Data) d) - { - this->value_compare::operator=(d); - m_vect = d.m_vect; - return *this; - } - - Data& operator=(BOOST_RV_REF(Data) d) - { - this->value_compare::operator=(boost::move(static_cast(d))); - m_vect = boost::move(d.m_vect); - return *this; - } - - void swap(Data &d) - { - value_compare& mycomp = *this, & othercomp = d; - boost::container::swap_dispatch(mycomp, othercomp); - this->m_vect.swap(d.m_vect); - } - - vector_t m_vect; - }; - - Data m_data; - BOOST_COPYABLE_AND_MOVABLE(flat_tree) - - public: - - typedef typename vector_t::value_type value_type; - typedef typename vector_t::pointer pointer; - typedef typename vector_t::const_pointer const_pointer; - typedef typename vector_t::reference reference; - typedef typename vector_t::const_reference const_reference; - typedef Key key_type; - typedef Compare key_compare; - typedef typename vector_t::allocator_type allocator_type; - typedef typename vector_t::size_type size_type; - typedef typename vector_t::difference_type difference_type; - typedef typename vector_t::iterator iterator; - typedef typename vector_t::const_iterator const_iterator; - typedef typename vector_t::reverse_iterator reverse_iterator; - typedef typename vector_t::const_reverse_iterator const_reverse_iterator; - - //!Standard extension - typedef allocator_type stored_allocator_type; - - private: - typedef allocator_traits stored_allocator_traits; - - public: - flat_tree() - : m_data() - { } - - explicit flat_tree(const Compare& comp) - : m_data(comp) - { } - - flat_tree(const Compare& comp, const allocator_type& a) - : m_data(comp, a) - { } - - explicit flat_tree(const allocator_type& a) - : m_data(a) - { } - - flat_tree(const flat_tree& x) - : m_data(x.m_data) - { } - - flat_tree(BOOST_RV_REF(flat_tree) x) - : m_data(boost::move(x.m_data)) - { } - - flat_tree(const flat_tree& x, const allocator_type &a) - : m_data(x.m_data, a) - { } - - flat_tree(BOOST_RV_REF(flat_tree) x, const allocator_type &a) - : m_data(boost::move(x.m_data), a) - { } - - template - flat_tree( ordered_range_t, InputIterator first, InputIterator last - , const Compare& comp = Compare() - , const allocator_type& a = allocator_type()) - : m_data(comp, a) - { this->m_data.m_vect.insert(this->m_data.m_vect.end(), first, last); } - - template - flat_tree( bool unique_insertion - , InputIterator first, InputIterator last - , const Compare& comp = Compare() - , const allocator_type& a = allocator_type()) - : m_data(comp, a) - { - //Use cend() as hint to achieve linear time for - //ordered ranges as required by the standard - //for the constructor - //Call end() every iteration as reallocation might have invalidated iterators - if(unique_insertion){ - for ( ; first != last; ++first){ - this->insert_unique(this->cend(), *first); - } - } - else{ - for ( ; first != last; ++first){ - this->insert_equal(this->cend(), *first); - } - } - } - - ~flat_tree() - {} - - flat_tree& operator=(BOOST_COPY_ASSIGN_REF(flat_tree) x) - { m_data = x.m_data; return *this; } - - flat_tree& operator=(BOOST_RV_REF(flat_tree) mx) - { m_data = boost::move(mx.m_data); return *this; } - - public: - // accessors: - Compare key_comp() const - { return this->m_data.get_comp(); } - - allocator_type get_allocator() const - { return this->m_data.m_vect.get_allocator(); } - - const stored_allocator_type &get_stored_allocator() const - { return this->m_data.m_vect.get_stored_allocator(); } - - stored_allocator_type &get_stored_allocator() - { return this->m_data.m_vect.get_stored_allocator(); } - - iterator begin() - { return this->m_data.m_vect.begin(); } - - const_iterator begin() const - { return this->cbegin(); } - - const_iterator cbegin() const - { return this->m_data.m_vect.begin(); } - - iterator end() - { return this->m_data.m_vect.end(); } - - const_iterator end() const - { return this->cend(); } - - const_iterator cend() const - { return this->m_data.m_vect.end(); } - - reverse_iterator rbegin() - { return reverse_iterator(this->end()); } - - const_reverse_iterator rbegin() const - { return this->crbegin(); } - - const_reverse_iterator crbegin() const - { return const_reverse_iterator(this->cend()); } - - reverse_iterator rend() - { return reverse_iterator(this->begin()); } - - const_reverse_iterator rend() const - { return this->crend(); } - - const_reverse_iterator crend() const - { return const_reverse_iterator(this->cbegin()); } - - bool empty() const - { return this->m_data.m_vect.empty(); } - - size_type size() const - { return this->m_data.m_vect.size(); } - - size_type max_size() const - { return this->m_data.m_vect.max_size(); } - - void swap(flat_tree& other) - { this->m_data.swap(other.m_data); } - - public: - // insert/erase - std::pair insert_unique(const value_type& val) - { - std::pair ret; - insert_commit_data data; - ret.second = this->priv_insert_unique_prepare(val, data); - ret.first = ret.second ? this->priv_insert_commit(data, val) - : iterator(vector_iterator_get_ptr(data.position)); - return ret; - } - - std::pair insert_unique(BOOST_RV_REF(value_type) val) - { - std::pair ret; - insert_commit_data data; - ret.second = this->priv_insert_unique_prepare(val, data); - ret.first = ret.second ? this->priv_insert_commit(data, boost::move(val)) - : iterator(vector_iterator_get_ptr(data.position)); - return ret; - } - - iterator insert_equal(const value_type& val) - { - iterator i = this->upper_bound(KeyOfValue()(val)); - i = this->m_data.m_vect.insert(i, val); - return i; - } - - iterator insert_equal(BOOST_RV_REF(value_type) mval) - { - iterator i = this->upper_bound(KeyOfValue()(mval)); - i = this->m_data.m_vect.insert(i, boost::move(mval)); - return i; - } - - iterator insert_unique(const_iterator pos, const value_type& val) - { - std::pair ret; - insert_commit_data data; - return this->priv_insert_unique_prepare(pos, val, data) - ? this->priv_insert_commit(data, val) - : iterator(vector_iterator_get_ptr(data.position)); - } - - iterator insert_unique(const_iterator pos, BOOST_RV_REF(value_type) val) - { - std::pair ret; - insert_commit_data data; - return this->priv_insert_unique_prepare(pos, val, data) - ? this->priv_insert_commit(data, boost::move(val)) - : iterator(vector_iterator_get_ptr(data.position)); - } - - iterator insert_equal(const_iterator pos, const value_type& val) - { - insert_commit_data data; - this->priv_insert_equal_prepare(pos, val, data); - return this->priv_insert_commit(data, val); - } - - iterator insert_equal(const_iterator pos, BOOST_RV_REF(value_type) mval) - { - insert_commit_data data; - this->priv_insert_equal_prepare(pos, mval, data); - return this->priv_insert_commit(data, boost::move(mval)); - } - - template - void insert_unique(InIt first, InIt last) - { - for ( ; first != last; ++first){ - this->insert_unique(*first); - } - } - - template - void insert_equal(InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { this->priv_insert_equal_loop(first, last); } - - template - void insert_equal(InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - const size_type len = static_cast(std::distance(first, last)); - this->reserve(this->size()+len); - this->priv_insert_equal_loop(first, last); - } - - //Ordered - - template - void insert_equal(ordered_range_t, InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { this->priv_insert_equal_loop_ordered(first, last); } - - template - void insert_equal(ordered_range_t, FwdIt first, FwdIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_input_iterator::value && - container_detail::is_forward_iterator::value - >::type * = 0 - #endif - ) - { - const size_type len = static_cast(std::distance(first, last)); - this->reserve(this->size()+len); - this->priv_insert_equal_loop_ordered(first, last); - } - - template - void insert_equal(ordered_range_t, BidirIt first, BidirIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_input_iterator::value && - !container_detail::is_forward_iterator::value - >::type * = 0 - #endif - ) - { - size_type len = static_cast(std::distance(first, last)); - const size_type BurstSize = 16; - size_type positions[BurstSize]; - - //Prereserve all memory so that iterators are not invalidated - this->reserve(this->size()+len); - const const_iterator b(this->cbegin()); - const_iterator pos(b); - //Loop in burst sizes - while(len){ - const size_type burst = len < BurstSize ? len : BurstSize; - const const_iterator ce(this->cend()); - len -= burst; - for(size_type i = 0; i != burst; ++i){ - //Get the insertion position for each key - pos = const_cast(*this).priv_upper_bound(pos, ce, KeyOfValue()(*first)); - positions[i] = static_cast(pos - b); - ++first; - } - //Insert all in a single step in the precalculated positions - this->m_data.m_vect.insert_ordered_at(burst, positions + burst, first); - //Next search position updated - pos += burst; - } - } - - template - void insert_unique(ordered_unique_range_t, InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < container_detail::is_input_iterator::value || - container_detail::is_forward_iterator::value - >::type * = 0 - #endif - ) - { - const_iterator pos(this->cend()); - for ( ; first != last; ++first){ - pos = this->insert_unique(pos, *first); - ++pos; - } - } - - template - void insert_unique(ordered_unique_range_t, BidirIt first, BidirIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !(container_detail::is_input_iterator::value || - container_detail::is_forward_iterator::value) - >::type * = 0 - #endif - ) - { - size_type len = static_cast(std::distance(first, last)); - const size_type BurstSize = 16; - size_type positions[BurstSize]; - size_type skips[BurstSize]; - - //Prereserve all memory so that iterators are not invalidated - this->reserve(this->size()+len); - const const_iterator b(this->cbegin()); - const_iterator pos(b); - const value_compare &value_comp = this->m_data; - skips[0u] = 0u; - //Loop in burst sizes - while(len){ - const size_type burst = len < BurstSize ? len : BurstSize; - size_type unique_burst = 0u; - const const_iterator ce(this->cend()); - while(unique_burst < burst && len > 0){ - //Get the insertion position for each key - const value_type & val = *first++; - --len; - pos = const_cast(*this).priv_lower_bound(pos, ce, KeyOfValue()(val)); - //Check if already present - if(pos != ce && !value_comp(val, *pos)){ - if(unique_burst > 0){ - ++skips[unique_burst-1]; - } - continue; - } - - //If not present, calculate position - positions[unique_burst] = static_cast(pos - b); - skips[unique_burst++] = 0u; - } - if(unique_burst){ - //Insert all in a single step in the precalculated positions - this->m_data.m_vect.insert_ordered_at(unique_burst, positions + unique_burst, skips + unique_burst, first); - //Next search position updated - pos += unique_burst; - } - } - } - - #ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - template - std::pair emplace_unique(Args&&... args) - { - aligned_storage::value> v; - value_type &val = *static_cast(static_cast(&v)); - stored_allocator_type &a = this->get_stored_allocator(); - stored_allocator_traits::construct(a, &val, ::boost::forward(args)... ); - value_destructor d(a, val); - return this->insert_unique(::boost::move(val)); - } - - template - iterator emplace_hint_unique(const_iterator hint, Args&&... args) - { - aligned_storage::value> v; - value_type &val = *static_cast(static_cast(&v)); - stored_allocator_type &a = this->get_stored_allocator(); - stored_allocator_traits::construct(a, &val, ::boost::forward(args)... ); - value_destructor d(a, val); - return this->insert_unique(hint, ::boost::move(val)); - } - - template - iterator emplace_equal(Args&&... args) - { - aligned_storage::value> v; - value_type &val = *static_cast(static_cast(&v)); - stored_allocator_type &a = this->get_stored_allocator(); - stored_allocator_traits::construct(a, &val, ::boost::forward(args)... ); - value_destructor d(a, val); - return this->insert_equal(::boost::move(val)); - } - - template - iterator emplace_hint_equal(const_iterator hint, Args&&... args) - { - aligned_storage::value> v; - value_type &val = *static_cast(static_cast(&v)); - stored_allocator_type &a = this->get_stored_allocator(); - stored_allocator_traits::construct(a, &val, ::boost::forward(args)... ); - value_destructor d(a, val); - return this->insert_equal(hint, ::boost::move(val)); - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - std::pair \ - emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - aligned_storage::value> v; \ - value_type &val = *static_cast(static_cast(&v)); \ - stored_allocator_type &a = this->get_stored_allocator(); \ - stored_allocator_traits::construct(a, &val \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - value_destructor d(a, val); \ - return this->insert_unique(::boost::move(val)); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint_unique(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - aligned_storage::value> v; \ - value_type &val = *static_cast(static_cast(&v)); \ - stored_allocator_type &a = this->get_stored_allocator(); \ - stored_allocator_traits::construct(a, &val \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - value_destructor d(a, val); \ - return this->insert_unique(hint, ::boost::move(val)); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - aligned_storage::value> v; \ - value_type &val = *static_cast(static_cast(&v)); \ - stored_allocator_type &a = this->get_stored_allocator(); \ - stored_allocator_traits::construct(a, &val \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - value_destructor d(a, val); \ - return this->insert_equal(::boost::move(val)); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint_equal(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - aligned_storage::value> v; \ - value_type &val = *static_cast(static_cast(&v)); \ - stored_allocator_type &a = this->get_stored_allocator(); \ - stored_allocator_traits::construct(a, &val \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - value_destructor d(a, val); \ - return this->insert_equal(hint, ::boost::move(val)); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - iterator erase(const_iterator position) - { return this->m_data.m_vect.erase(position); } - - size_type erase(const key_type& k) - { - std::pair itp = this->equal_range(k); - size_type ret = static_cast(itp.second-itp.first); - if (ret){ - this->m_data.m_vect.erase(itp.first, itp.second); - } - return ret; - } - - iterator erase(const_iterator first, const_iterator last) - { return this->m_data.m_vect.erase(first, last); } - - void clear() - { this->m_data.m_vect.clear(); } - - //! Effects: Tries to deallocate the excess of memory created - // with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { this->m_data.m_vect.shrink_to_fit(); } - - // set operations: - iterator find(const key_type& k) - { - iterator i = this->lower_bound(k); - iterator end_it = this->end(); - if (i != end_it && this->m_data.get_comp()(k, KeyOfValue()(*i))){ - i = end_it; - } - return i; - } - - const_iterator find(const key_type& k) const - { - const_iterator i = this->lower_bound(k); - - const_iterator end_it = this->cend(); - if (i != end_it && this->m_data.get_comp()(k, KeyOfValue()(*i))){ - i = end_it; - } - return i; - } - - size_type count(const key_type& k) const - { - std::pair p = this->equal_range(k); - size_type n = p.second - p.first; - return n; - } - - iterator lower_bound(const key_type& k) - { return this->priv_lower_bound(this->begin(), this->end(), k); } - - const_iterator lower_bound(const key_type& k) const - { return this->priv_lower_bound(this->cbegin(), this->cend(), k); } - - iterator upper_bound(const key_type& k) - { return this->priv_upper_bound(this->begin(), this->end(), k); } - - const_iterator upper_bound(const key_type& k) const - { return this->priv_upper_bound(this->cbegin(), this->cend(), k); } - - std::pair equal_range(const key_type& k) - { return this->priv_equal_range(this->begin(), this->end(), k); } - - std::pair equal_range(const key_type& k) const - { return this->priv_equal_range(this->cbegin(), this->cend(), k); } - - size_type capacity() const - { return this->m_data.m_vect.capacity(); } - - void reserve(size_type cnt) - { this->m_data.m_vect.reserve(cnt); } - - private: - struct insert_commit_data - { - const_iterator position; - }; - - // insert/erase - void priv_insert_equal_prepare - (const_iterator pos, const value_type& val, insert_commit_data &data) - { - // N1780 - // To insert val at pos: - // if pos == end || val <= *pos - // if pos == begin || val >= *(pos-1) - // insert val before pos - // else - // insert val before upper_bound(val) - // else - // insert val before lower_bound(val) - const value_compare &value_comp = this->m_data; - - if(pos == this->cend() || !value_comp(*pos, val)){ - if (pos == this->cbegin() || !value_comp(val, pos[-1])){ - data.position = pos; - } - else{ - data.position = - this->priv_upper_bound(this->cbegin(), pos, KeyOfValue()(val)); - } - } - else{ - data.position = - this->priv_lower_bound(pos, this->cend(), KeyOfValue()(val)); - } - } - - bool priv_insert_unique_prepare - (const_iterator b, const_iterator e, const value_type& val, insert_commit_data &commit_data) - { - const value_compare &value_comp = this->m_data; - commit_data.position = this->priv_lower_bound(b, e, KeyOfValue()(val)); - return commit_data.position == e || value_comp(val, *commit_data.position); - } - - bool priv_insert_unique_prepare - (const value_type& val, insert_commit_data &commit_data) - { return this->priv_insert_unique_prepare(this->cbegin(), this->cend(), val, commit_data); } - - bool priv_insert_unique_prepare - (const_iterator pos, const value_type& val, insert_commit_data &commit_data) - { - //N1780. Props to Howard Hinnant! - //To insert val at pos: - //if pos == end || val <= *pos - // if pos == begin || val >= *(pos-1) - // insert val before pos - // else - // insert val before upper_bound(val) - //else if pos+1 == end || val <= *(pos+1) - // insert val after pos - //else - // insert val before lower_bound(val) - const value_compare &value_comp = this->m_data; - const const_iterator cend_it = this->cend(); - if(pos == cend_it || value_comp(val, *pos)){ //Check if val should go before end - const const_iterator cbeg = this->cbegin(); - commit_data.position = pos; - if(pos == cbeg){ //If container is empty then insert it in the beginning - return true; - } - const_iterator prev(pos); - --prev; - if(value_comp(*prev, val)){ //If previous element was less, then it should go between prev and pos - return true; - } - else if(!value_comp(val, *prev)){ //If previous was equal then insertion should fail - commit_data.position = prev; - return false; - } - else{ //Previous was bigger so insertion hint was pointless, dispatch to hintless insertion - //but reduce the search between beg and prev as prev is bigger than val - return this->priv_insert_unique_prepare(cbeg, prev, val, commit_data); - } - } - else{ - //The hint is before the insertion position, so insert it - //in the remaining range [pos, end) - return this->priv_insert_unique_prepare(pos, cend_it, val, commit_data); - } - } - - template - iterator priv_insert_commit - (insert_commit_data &commit_data, BOOST_FWD_REF(Convertible) convertible) - { - return this->m_data.m_vect.insert - ( commit_data.position - , boost::forward(convertible)); - } - - template - RanIt priv_lower_bound(RanIt first, RanIt last, - const key_type & key) const - { - const Compare &key_cmp = this->m_data.get_comp(); - KeyOfValue key_extract; - size_type len = static_cast(last - first); - RanIt middle; - - while (len) { - size_type half = len >> 1; - middle = first; - middle += half; - - if (key_cmp(key_extract(*middle), key)) { - ++middle; - first = middle; - len = len - half - 1; - } - else - len = half; - } - return first; - } - - - template - RanIt priv_upper_bound(RanIt first, RanIt last, - const key_type & key) const - { - const Compare &key_cmp = this->m_data.get_comp(); - KeyOfValue key_extract; - size_type len = static_cast(last - first); - RanIt middle; - - while (len) { - size_type half = len >> 1; - middle = first; - middle += half; - - if (key_cmp(key, key_extract(*middle))) { - len = half; - } - else{ - first = ++middle; - len = len - half - 1; - } - } - return first; - } - - template - std::pair - priv_equal_range(RanIt first, RanIt last, const key_type& key) const - { - const Compare &key_cmp = this->m_data.get_comp(); - KeyOfValue key_extract; - size_type len = static_cast(last - first); - RanIt middle; - - while (len) { - size_type half = len >> 1; - middle = first; - middle += half; - - if (key_cmp(key_extract(*middle), key)){ - first = middle; - ++first; - len = len - half - 1; - } - else if (key_cmp(key, key_extract(*middle))){ - len = half; - } - else { - //Middle is equal to key - last = first; - last += len; - first = this->priv_lower_bound(first, middle, key); - return std::pair (first, this->priv_upper_bound(++middle, last, key)); - } - } - return std::pair(first, first); - } - - template - void priv_insert_equal_loop(InIt first, InIt last) - { - for ( ; first != last; ++first){ - this->insert_equal(*first); - } - } - - template - void priv_insert_equal_loop_ordered(InIt first, InIt last) - { - const_iterator pos(this->cend()); - for ( ; first != last; ++first){ - //If ordered, then try hint version - //to achieve constant-time complexity per insertion - pos = this->insert_equal(pos, *first); - ++pos; - } - } -}; - -template -inline bool -operator==(const flat_tree& x, - const flat_tree& y) -{ - return x.size() == y.size() && - std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator<(const flat_tree& x, - const flat_tree& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), - y.begin(), y.end()); -} - -template -inline bool -operator!=(const flat_tree& x, - const flat_tree& y) - { return !(x == y); } - -template -inline bool -operator>(const flat_tree& x, - const flat_tree& y) - { return y < x; } - -template -inline bool -operator<=(const flat_tree& x, - const flat_tree& y) - { return !(y < x); } - -template -inline bool -operator>=(const flat_tree& x, - const flat_tree& y) - { return !(x < y); } - - -template -inline void -swap(flat_tree& x, - flat_tree& y) - { x.swap(y); } - -} //namespace container_detail { - -} //namespace container { -/* -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; -*/ -} //namespace boost { - -#include - -#endif // BOOST_CONTAINER_FLAT_TREE_HPP diff --git a/utils/boost_idb/boost/container/detail/function_detector.hpp b/utils/boost_idb/boost/container/detail/function_detector.hpp deleted file mode 100644 index 5a5f6fd7..00000000 --- a/utils/boost_idb/boost/container/detail/function_detector.hpp +++ /dev/null @@ -1,88 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -///////////////////////////////////////////////////////////////////////////// -// This code was modified from the code posted by Alexandre Courpron in his -// article "Interface Detection" in The Code Project: -// http://www.codeproject.com/KB/architecture/Detector.aspx -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2007 Alexandre Courpron -// -// Permission to use, copy, modify, redistribute and sell this software, -// provided that this copyright notice appears on all copies of the software. -/////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_FUNCTION_DETECTOR_HPP -#define BOOST_CONTAINER_DETAIL_FUNCTION_DETECTOR_HPP - -#include - -namespace boost { -namespace container { -namespace function_detector { - - typedef char NotFoundType; - struct StaticFunctionType { NotFoundType x [2]; }; - struct NonStaticFunctionType { NotFoundType x [3]; }; - - enum - { NotFound = 0, - StaticFunction = sizeof( StaticFunctionType ) - sizeof( NotFoundType ), - NonStaticFunction = sizeof( NonStaticFunctionType ) - sizeof( NotFoundType ) - }; - -} //namespace boost { -} //namespace container { -} //namespace function_detector { - -#define BOOST_CONTAINER_CREATE_FUNCTION_DETECTOR(Identifier, InstantiationKey) \ - namespace boost { \ - namespace container { \ - namespace function_detector { \ - template < class T, \ - class NonStaticType, \ - class NonStaticConstType, \ - class StaticType > \ - class DetectMember_##InstantiationKey_##Identifier { \ - template < NonStaticType > \ - struct TestNonStaticNonConst ; \ - \ - template < NonStaticConstType > \ - struct TestNonStaticConst ; \ - \ - template < StaticType > \ - struct TestStatic ; \ - \ - template \ - static NonStaticFunctionType Test( TestNonStaticNonConst<&U::Identifier>*, int ); \ - \ - template \ - static NonStaticFunctionType Test( TestNonStaticConst<&U::Identifier>*, int ); \ - \ - template \ - static StaticFunctionType Test( TestStatic<&U::Identifier>*, int ); \ - \ - template \ - static NotFoundType Test( ... ); \ - public : \ - static const int check = NotFound + (sizeof(Test(0, 0)) - sizeof(NotFoundType));\ - };\ -}}} //namespace boost::container::function_detector { - -#define BOOST_CONTAINER_DETECT_FUNCTION(Class, InstantiationKey, ReturnType, Identifier, Params) \ - ::boost::container::function_detector::DetectMember_##InstantiationKey_##Identifier< Class,\ - ReturnType (Class::*)Params,\ - ReturnType (Class::*)Params const,\ - ReturnType (*)Params \ - >::check - -#include - -#endif //@ifndef BOOST_CONTAINER_DETAIL_FUNCTION_DETECTOR_HPP diff --git a/utils/boost_idb/boost/container/detail/iterators.hpp b/utils/boost_idb/boost/container/detail/iterators.hpp deleted file mode 100644 index 5766a7c2..00000000 --- a/utils/boost_idb/boost/container/detail/iterators.hpp +++ /dev/null @@ -1,812 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// (C) Copyright Gennaro Prota 2003 - 2004. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_ITERATORS_HPP -#define BOOST_CONTAINER_DETAIL_ITERATORS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include -#include -#include -#include -#include - -#ifdef BOOST_CONTAINER_PERFECT_FORWARDING -#include -#else -#include -#endif - -#include - -namespace boost { -namespace container { - -template -class constant_iterator - : public std::iterator - -{ - typedef constant_iterator this_type; - - public: - explicit constant_iterator(const T &ref, Difference range_size) - : m_ptr(&ref), m_num(range_size){} - - //Constructors - constant_iterator() - : m_ptr(0), m_num(0){} - - constant_iterator& operator++() - { increment(); return *this; } - - constant_iterator operator++(int) - { - constant_iterator result (*this); - increment(); - return result; - } - - constant_iterator& operator--() - { decrement(); return *this; } - - constant_iterator operator--(int) - { - constant_iterator result (*this); - decrement(); - return result; - } - - friend bool operator== (const constant_iterator& i, const constant_iterator& i2) - { return i.equal(i2); } - - friend bool operator!= (const constant_iterator& i, const constant_iterator& i2) - { return !(i == i2); } - - friend bool operator< (const constant_iterator& i, const constant_iterator& i2) - { return i.less(i2); } - - friend bool operator> (const constant_iterator& i, const constant_iterator& i2) - { return i2 < i; } - - friend bool operator<= (const constant_iterator& i, const constant_iterator& i2) - { return !(i > i2); } - - friend bool operator>= (const constant_iterator& i, const constant_iterator& i2) - { return !(i < i2); } - - friend Difference operator- (const constant_iterator& i, const constant_iterator& i2) - { return i2.distance_to(i); } - - //Arithmetic - constant_iterator& operator+=(Difference off) - { this->advance(off); return *this; } - - constant_iterator operator+(Difference off) const - { - constant_iterator other(*this); - other.advance(off); - return other; - } - - friend constant_iterator operator+(Difference off, const constant_iterator& right) - { return right + off; } - - constant_iterator& operator-=(Difference off) - { this->advance(-off); return *this; } - - constant_iterator operator-(Difference off) const - { return *this + (-off); } - - const T& operator*() const - { return dereference(); } - - const T& operator[] (Difference ) const - { return dereference(); } - - const T* operator->() const - { return &(dereference()); } - - private: - const T * m_ptr; - Difference m_num; - - void increment() - { --m_num; } - - void decrement() - { ++m_num; } - - bool equal(const this_type &other) const - { return m_num == other.m_num; } - - bool less(const this_type &other) const - { return other.m_num < m_num; } - - const T & dereference() const - { return *m_ptr; } - - void advance(Difference n) - { m_num -= n; } - - Difference distance_to(const this_type &other)const - { return m_num - other.m_num; } -}; - -template -class value_init_construct_iterator - : public std::iterator - -{ - typedef value_init_construct_iterator this_type; - - public: - explicit value_init_construct_iterator(Difference range_size) - : m_num(range_size){} - - //Constructors - value_init_construct_iterator() - : m_num(0){} - - value_init_construct_iterator& operator++() - { increment(); return *this; } - - value_init_construct_iterator operator++(int) - { - value_init_construct_iterator result (*this); - increment(); - return result; - } - - value_init_construct_iterator& operator--() - { decrement(); return *this; } - - value_init_construct_iterator operator--(int) - { - value_init_construct_iterator result (*this); - decrement(); - return result; - } - - friend bool operator== (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return i.equal(i2); } - - friend bool operator!= (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return !(i == i2); } - - friend bool operator< (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return i.less(i2); } - - friend bool operator> (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return i2 < i; } - - friend bool operator<= (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return !(i > i2); } - - friend bool operator>= (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return !(i < i2); } - - friend Difference operator- (const value_init_construct_iterator& i, const value_init_construct_iterator& i2) - { return i2.distance_to(i); } - - //Arithmetic - value_init_construct_iterator& operator+=(Difference off) - { this->advance(off); return *this; } - - value_init_construct_iterator operator+(Difference off) const - { - value_init_construct_iterator other(*this); - other.advance(off); - return other; - } - - friend value_init_construct_iterator operator+(Difference off, const value_init_construct_iterator& right) - { return right + off; } - - value_init_construct_iterator& operator-=(Difference off) - { this->advance(-off); return *this; } - - value_init_construct_iterator operator-(Difference off) const - { return *this + (-off); } - - //This pseudo-iterator's dereference operations have no sense since value is not - //constructed until ::boost::container::construct_in_place is called. - //So comment them to catch bad uses - //const T& operator*() const; - //const T& operator[](difference_type) const; - //const T* operator->() const; - - private: - Difference m_num; - - void increment() - { --m_num; } - - void decrement() - { ++m_num; } - - bool equal(const this_type &other) const - { return m_num == other.m_num; } - - bool less(const this_type &other) const - { return other.m_num < m_num; } - - const T & dereference() const - { - static T dummy; - return dummy; - } - - void advance(Difference n) - { m_num -= n; } - - Difference distance_to(const this_type &other)const - { return m_num - other.m_num; } -}; - -template -class default_init_construct_iterator - : public std::iterator - -{ - typedef default_init_construct_iterator this_type; - - public: - explicit default_init_construct_iterator(Difference range_size) - : m_num(range_size){} - - //Constructors - default_init_construct_iterator() - : m_num(0){} - - default_init_construct_iterator& operator++() - { increment(); return *this; } - - default_init_construct_iterator operator++(int) - { - default_init_construct_iterator result (*this); - increment(); - return result; - } - - default_init_construct_iterator& operator--() - { decrement(); return *this; } - - default_init_construct_iterator operator--(int) - { - default_init_construct_iterator result (*this); - decrement(); - return result; - } - - friend bool operator== (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return i.equal(i2); } - - friend bool operator!= (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return !(i == i2); } - - friend bool operator< (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return i.less(i2); } - - friend bool operator> (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return i2 < i; } - - friend bool operator<= (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return !(i > i2); } - - friend bool operator>= (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return !(i < i2); } - - friend Difference operator- (const default_init_construct_iterator& i, const default_init_construct_iterator& i2) - { return i2.distance_to(i); } - - //Arithmetic - default_init_construct_iterator& operator+=(Difference off) - { this->advance(off); return *this; } - - default_init_construct_iterator operator+(Difference off) const - { - default_init_construct_iterator other(*this); - other.advance(off); - return other; - } - - friend default_init_construct_iterator operator+(Difference off, const default_init_construct_iterator& right) - { return right + off; } - - default_init_construct_iterator& operator-=(Difference off) - { this->advance(-off); return *this; } - - default_init_construct_iterator operator-(Difference off) const - { return *this + (-off); } - - //This pseudo-iterator's dereference operations have no sense since value is not - //constructed until ::boost::container::construct_in_place is called. - //So comment them to catch bad uses - //const T& operator*() const; - //const T& operator[](difference_type) const; - //const T* operator->() const; - - private: - Difference m_num; - - void increment() - { --m_num; } - - void decrement() - { ++m_num; } - - bool equal(const this_type &other) const - { return m_num == other.m_num; } - - bool less(const this_type &other) const - { return other.m_num < m_num; } - - const T & dereference() const - { - static T dummy; - return dummy; - } - - void advance(Difference n) - { m_num -= n; } - - Difference distance_to(const this_type &other)const - { return m_num - other.m_num; } -}; - - -template -class repeat_iterator - : public std::iterator - -{ - typedef repeat_iterator this_type; - public: - explicit repeat_iterator(T &ref, Difference range_size) - : m_ptr(&ref), m_num(range_size){} - - //Constructors - repeat_iterator() - : m_ptr(0), m_num(0){} - - this_type& operator++() - { increment(); return *this; } - - this_type operator++(int) - { - this_type result (*this); - increment(); - return result; - } - - this_type& operator--() - { increment(); return *this; } - - this_type operator--(int) - { - this_type result (*this); - increment(); - return result; - } - - friend bool operator== (const this_type& i, const this_type& i2) - { return i.equal(i2); } - - friend bool operator!= (const this_type& i, const this_type& i2) - { return !(i == i2); } - - friend bool operator< (const this_type& i, const this_type& i2) - { return i.less(i2); } - - friend bool operator> (const this_type& i, const this_type& i2) - { return i2 < i; } - - friend bool operator<= (const this_type& i, const this_type& i2) - { return !(i > i2); } - - friend bool operator>= (const this_type& i, const this_type& i2) - { return !(i < i2); } - - friend Difference operator- (const this_type& i, const this_type& i2) - { return i2.distance_to(i); } - - //Arithmetic - this_type& operator+=(Difference off) - { this->advance(off); return *this; } - - this_type operator+(Difference off) const - { - this_type other(*this); - other.advance(off); - return other; - } - - friend this_type operator+(Difference off, const this_type& right) - { return right + off; } - - this_type& operator-=(Difference off) - { this->advance(-off); return *this; } - - this_type operator-(Difference off) const - { return *this + (-off); } - - T& operator*() const - { return dereference(); } - - T& operator[] (Difference ) const - { return dereference(); } - - T *operator->() const - { return &(dereference()); } - - private: - T * m_ptr; - Difference m_num; - - void increment() - { --m_num; } - - void decrement() - { ++m_num; } - - bool equal(const this_type &other) const - { return m_num == other.m_num; } - - bool less(const this_type &other) const - { return other.m_num < m_num; } - - T & dereference() const - { return *m_ptr; } - - void advance(Difference n) - { m_num -= n; } - - Difference distance_to(const this_type &other)const - { return m_num - other.m_num; } -}; - -template -class emplace_iterator - : public std::iterator - -{ - typedef emplace_iterator this_type; - - public: - typedef Difference difference_type; - explicit emplace_iterator(EmplaceFunctor&e) - : m_num(1), m_pe(&e){} - - emplace_iterator() - : m_num(0), m_pe(0){} - - this_type& operator++() - { increment(); return *this; } - - this_type operator++(int) - { - this_type result (*this); - increment(); - return result; - } - - this_type& operator--() - { decrement(); return *this; } - - this_type operator--(int) - { - this_type result (*this); - decrement(); - return result; - } - - friend bool operator== (const this_type& i, const this_type& i2) - { return i.equal(i2); } - - friend bool operator!= (const this_type& i, const this_type& i2) - { return !(i == i2); } - - friend bool operator< (const this_type& i, const this_type& i2) - { return i.less(i2); } - - friend bool operator> (const this_type& i, const this_type& i2) - { return i2 < i; } - - friend bool operator<= (const this_type& i, const this_type& i2) - { return !(i > i2); } - - friend bool operator>= (const this_type& i, const this_type& i2) - { return !(i < i2); } - - friend difference_type operator- (const this_type& i, const this_type& i2) - { return i2.distance_to(i); } - - //Arithmetic - this_type& operator+=(difference_type off) - { this->advance(off); return *this; } - - this_type operator+(difference_type off) const - { - this_type other(*this); - other.advance(off); - return other; - } - - friend this_type operator+(difference_type off, const this_type& right) - { return right + off; } - - this_type& operator-=(difference_type off) - { this->advance(-off); return *this; } - - this_type operator-(difference_type off) const - { return *this + (-off); } - - //This pseudo-iterator's dereference operations have no sense since value is not - //constructed until ::boost::container::construct_in_place is called. - //So comment them to catch bad uses - //const T& operator*() const; - //const T& operator[](difference_type) const; - //const T* operator->() const; - - template - void construct_in_place(A &a, T* ptr) - { (*m_pe)(a, ptr); } - - private: - difference_type m_num; - EmplaceFunctor * m_pe; - - void increment() - { --m_num; } - - void decrement() - { ++m_num; } - - bool equal(const this_type &other) const - { return m_num == other.m_num; } - - bool less(const this_type &other) const - { return other.m_num < m_num; } - - const T & dereference() const - { - static T dummy; - return dummy; - } - - void advance(difference_type n) - { m_num -= n; } - - difference_type distance_to(const this_type &other)const - { return difference_type(m_num - other.m_num); } -}; - -#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - -template -struct emplace_functor -{ - typedef typename container_detail::build_number_seq::type index_tuple_t; - - emplace_functor(Args&&... args) - : args_(args...) - {} - - template - void operator()(A &a, T *ptr) - { emplace_functor::inplace_impl(a, ptr, index_tuple_t()); } - - template - void inplace_impl(A &a, T* ptr, const container_detail::index_tuple&) - { - allocator_traits::construct - (a, ptr, ::boost::forward(container_detail::get(args_))...); - } - - container_detail::tuple args_; -}; - -#else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - -#define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template <) \ - BOOST_PP_ENUM_PARAMS(n, class P) \ - BOOST_PP_EXPR_IF(n, >) \ - struct BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ - { \ - BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ - ( BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _) ) \ - BOOST_PP_EXPR_IF(n, :) BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_INIT, _){} \ - \ - template \ - void operator()(A &a, T *ptr) \ - { \ - allocator_traits::construct \ - (a, ptr BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_MEMBER_FORWARD, _) ); \ - } \ - BOOST_PP_REPEAT(n, BOOST_CONTAINER_PP_PARAM_DEFINE, _) \ - }; \ - //! -#define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) -#include BOOST_PP_LOCAL_ITERATE() - -#endif - -namespace container_detail { - -template -struct has_iterator_category -{ - template - static char test(int, typename X::iterator_category*); - - template - static int test(int, ...); - - static const bool value = (1 == sizeof(test(0, 0))); -}; - - -template::value > -struct is_input_iterator -{ - static const bool value = is_same::value; -}; - -template -struct is_input_iterator -{ - static const bool value = false; -}; - -template::value > -struct is_forward_iterator -{ - static const bool value = is_same::value; -}; - -template -struct is_forward_iterator -{ - static const bool value = false; -}; - -template::value > -struct is_bidirectional_iterator -{ - static const bool value = is_same::value; -}; - -template -struct is_bidirectional_iterator -{ - static const bool value = false; -}; - -template -struct iiterator_types -{ - typedef typename IIterator::value_type it_value_type; - typedef typename it_value_type::value_type value_type; - typedef typename std::iterator_traits::pointer it_pointer; - typedef typename std::iterator_traits::difference_type difference_type; - typedef typename ::boost::intrusive::pointer_traits:: - template rebind_pointer::type pointer; - typedef typename ::boost::intrusive::pointer_traits:: - template rebind_pointer::type const_pointer; - typedef typename ::boost::intrusive:: - pointer_traits::reference reference; - typedef typename ::boost::intrusive:: - pointer_traits::reference const_reference; - typedef typename IIterator::iterator_category iterator_category; -}; - -template -struct std_iterator -{ - typedef typename std::iterator - < typename iiterator_types::iterator_category - , typename iiterator_types::value_type - , typename iiterator_types::difference_type - , typename iiterator_types::const_pointer - , typename iiterator_types::const_reference> type; -}; - -template -struct std_iterator -{ - typedef typename std::iterator - < typename iiterator_types::iterator_category - , typename iiterator_types::value_type - , typename iiterator_types::difference_type - , typename iiterator_types::pointer - , typename iiterator_types::reference> type; -}; - -template -class iterator - : public std_iterator::type -{ - typedef typename std_iterator::type types_t; - - public: - typedef typename types_t::value_type value_type; - typedef typename types_t::pointer pointer; - typedef typename types_t::reference reference; - - iterator() - {} - - explicit iterator(IIterator iit) BOOST_CONTAINER_NOEXCEPT - : m_iit(iit) - {} - - iterator(iterator const& other) BOOST_CONTAINER_NOEXCEPT - : m_iit(other.get()) - {} - - iterator& operator++() BOOST_CONTAINER_NOEXCEPT - { ++this->m_iit; return *this; } - - iterator operator++(int) BOOST_CONTAINER_NOEXCEPT - { - iterator result (*this); - ++this->m_iit; - return result; - } - - iterator& operator--() BOOST_CONTAINER_NOEXCEPT - { - //If the iterator is not a bidirectional iterator, operator-- should not exist - BOOST_STATIC_ASSERT((is_bidirectional_iterator::value)); - --this->m_iit; return *this; - } - - iterator operator--(int) BOOST_CONTAINER_NOEXCEPT - { - iterator result (*this); - --this->m_iit; - return result; - } - - friend bool operator== (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_iit == r.m_iit; } - - friend bool operator!= (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return !(l == r); } - - reference operator*() const BOOST_CONTAINER_NOEXCEPT - { return (*this->m_iit).get_data(); } - - pointer operator->() const BOOST_CONTAINER_NOEXCEPT - { return ::boost::intrusive::pointer_traits::pointer_to(this->operator*()); } - - const IIterator &get() const BOOST_CONTAINER_NOEXCEPT - { return this->m_iit; } - - private: - IIterator m_iit; -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_ITERATORS_HPP diff --git a/utils/boost_idb/boost/container/detail/memory_util.hpp b/utils/boost_idb/boost/container/detail/memory_util.hpp deleted file mode 100644 index ed899548..00000000 --- a/utils/boost_idb/boost/container/detail/memory_util.hpp +++ /dev/null @@ -1,83 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP -#define BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include -#include - - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME allocate -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 2, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME destroy -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 3, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME max_size -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME select_on_container_copy_construction -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME construct -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS+1, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME swap -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, )) -#include BOOST_PP_ITERATE() - -namespace boost { -namespace container { -namespace container_detail { - - -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(pointer) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_pointer) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(reference) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_reference) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(void_pointer) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_void_pointer) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(size_type) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_copy_assignment) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_move_assignment) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_swap) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type) - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif // ! defined(BOOST_CONTAINER_ALLOCATOR_MEMORY_UTIL_HPP) diff --git a/utils/boost_idb/boost/container/detail/mpl.hpp b/utils/boost_idb/boost/container/detail/mpl.hpp deleted file mode 100644 index 08f3eae5..00000000 --- a/utils/boost_idb/boost/container/detail/mpl.hpp +++ /dev/null @@ -1,160 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP -#define BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include - -namespace boost { -namespace container { -namespace container_detail { - -template -struct integral_constant -{ - static const T value = val; - typedef integral_constant type; -}; - -template< bool C_ > -struct bool_ : integral_constant -{ - static const bool value = C_; - operator bool() const { return bool_::value; } -}; - -typedef bool_ true_; -typedef bool_ false_; - -typedef true_ true_type; -typedef false_ false_type; - -typedef char yes_type; -struct no_type -{ - char padding[8]; -}; - -template -struct enable_if_c { - typedef T type; -}; - -template -struct enable_if_c {}; - -template -struct enable_if : public enable_if_c {}; - -template -struct disable_if : public enable_if_c {}; - -template -struct disable_if_c : public enable_if_c {}; - -template -class is_convertible -{ - typedef char true_t; - class false_t { char dummy[2]; }; - static true_t dispatch(U); - static false_t dispatch(...); - static T trigger(); - public: - enum { value = sizeof(dispatch(trigger())) == sizeof(true_t) }; -}; - -template< - bool C - , typename T1 - , typename T2 - > -struct if_c -{ - typedef T1 type; -}; - -template< - typename T1 - , typename T2 - > -struct if_c -{ - typedef T2 type; -}; - -template< - typename T1 - , typename T2 - , typename T3 - > -struct if_ -{ - typedef typename if_c<0 != T1::value, T2, T3>::type type; -}; - - -template -struct select1st -// : public std::unary_function -{ - template - const typename Pair::first_type& operator()(const OtherPair& x) const - { return x.first; } - - const typename Pair::first_type& operator()(const typename Pair::first_type& x) const - { return x; } -}; - -// identity is an extension: it is not part of the standard. -template -struct identity -// : public std::unary_function -{ - typedef T type; - const T& operator()(const T& x) const - { return x; } -}; - -template -struct ls_zeros -{ - static const std::size_t value = (S & std::size_t(1)) ? 0 : (1u + ls_zeros<(S >> 1u)>::value); -}; - -template<> -struct ls_zeros<0> -{ - static const std::size_t value = 0; -}; - -template<> -struct ls_zeros<1> -{ - static const std::size_t value = 0; -}; - -template struct unvoid { typedef T type; }; -template <> struct unvoid { struct type { }; }; -template <> struct unvoid { struct type { }; }; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#endif //#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP - diff --git a/utils/boost_idb/boost/container/detail/multiallocation_chain.hpp b/utils/boost_idb/boost/container/detail/multiallocation_chain.hpp deleted file mode 100644 index bc9945ac..00000000 --- a/utils/boost_idb/boost/container/detail/multiallocation_chain.hpp +++ /dev/null @@ -1,286 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP -#define BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP - -#include "config_begin.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { -namespace container_detail { - -template -class basic_multiallocation_chain -{ - private: - typedef bi::slist_base_hook - ,bi::link_mode - > node; - - typedef typename boost::intrusive::pointer_traits - ::template rebind_pointer::type char_ptr; - typedef typename boost::intrusive:: - pointer_traits::difference_type difference_type; - - typedef bi::slist< node - , bi::linear - , bi::cache_last - , bi::size_type::type> - > slist_impl_t; - slist_impl_t slist_impl_; - - typedef typename boost::intrusive::pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename boost::intrusive:: - pointer_traits node_ptr_traits; - - static node & to_node(const VoidPointer &p) - { return *static_cast(static_cast(container_detail::to_raw_pointer(p))); } - - static VoidPointer from_node(node &n) - { return node_ptr_traits::pointer_to(n); } - - static node_ptr to_node_ptr(const VoidPointer &p) - { return node_ptr_traits::static_cast_from(p); } - - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_multiallocation_chain) - - public: - - typedef VoidPointer void_pointer; - typedef typename slist_impl_t::iterator iterator; - typedef typename slist_impl_t::size_type size_type; - - basic_multiallocation_chain() - : slist_impl_() - {} - - basic_multiallocation_chain(const void_pointer &b, const void_pointer &before_e, size_type n) - : slist_impl_(to_node_ptr(b), to_node_ptr(before_e), n) - {} - - basic_multiallocation_chain(BOOST_RV_REF(basic_multiallocation_chain) other) - : slist_impl_(::boost::move(other.slist_impl_)) - {} - - basic_multiallocation_chain& operator=(BOOST_RV_REF(basic_multiallocation_chain) other) - { - slist_impl_ = ::boost::move(other.slist_impl_); - return *this; - } - - bool empty() const - { return slist_impl_.empty(); } - - size_type size() const - { return slist_impl_.size(); } - - iterator before_begin() - { return slist_impl_.before_begin(); } - - iterator begin() - { return slist_impl_.begin(); } - - iterator end() - { return slist_impl_.end(); } - - iterator last() - { return slist_impl_.last(); } - - void clear() - { slist_impl_.clear(); } - - iterator insert_after(iterator it, void_pointer m) - { return slist_impl_.insert_after(it, to_node(m)); } - - void push_front(const void_pointer &m) - { return slist_impl_.push_front(to_node(m)); } - - void push_back(const void_pointer &m) - { return slist_impl_.push_back(to_node(m)); } - - void_pointer pop_front() - { - node & n = slist_impl_.front(); - void_pointer ret = from_node(n); - slist_impl_.pop_front(); - return ret; - } - - void splice_after(iterator after_this, basic_multiallocation_chain &x, iterator before_b, iterator before_e, size_type n) - { slist_impl_.splice_after(after_this, x.slist_impl_, before_b, before_e, n); } - - void splice_after(iterator after_this, basic_multiallocation_chain &x) - { slist_impl_.splice_after(after_this, x.slist_impl_); } - - void erase_after(iterator before_b, iterator e, size_type n) - { slist_impl_.erase_after(before_b, e, n); } - - void_pointer incorporate_after(iterator after_this, const void_pointer &b, size_type unit_bytes, size_type num_units) - { - typedef typename boost::intrusive::pointer_traits char_pointer_traits; - char_ptr elem = char_pointer_traits::static_cast_from(b); - if(num_units){ - char_ptr prev_elem = elem; - elem += unit_bytes; - for(size_type i = 0; i != num_units-1; ++i, elem += unit_bytes){ - ::new (container_detail::to_raw_pointer(prev_elem)) void_pointer(elem); - prev_elem = elem; - } - slist_impl_.incorporate_after(after_this, to_node_ptr(b), to_node_ptr(prev_elem), num_units); - } - return elem; - } - - void incorporate_after(iterator after_this, void_pointer b, void_pointer before_e, size_type n) - { slist_impl_.incorporate_after(after_this, to_node_ptr(b), to_node_ptr(before_e), n); } - - void swap(basic_multiallocation_chain &x) - { slist_impl_.swap(x.slist_impl_); } - - static iterator iterator_to(const void_pointer &p) - { return slist_impl_t::s_iterator_to(to_node(p)); } - - std::pair extract_data() - { - std::pair ret - (slist_impl_.begin().operator->() - ,slist_impl_.last().operator->()); - slist_impl_.clear(); - return ret; - } -}; - -template -struct cast_functor -{ - typedef typename container_detail::add_reference::type result_type; - template - result_type operator()(U &ptr) const - { return *static_cast(static_cast(&ptr)); } -}; - -template -class transform_multiallocation_chain - : public MultiallocationChain -{ - private: - BOOST_MOVABLE_BUT_NOT_COPYABLE(transform_multiallocation_chain) - //transform_multiallocation_chain(const transform_multiallocation_chain &); - //transform_multiallocation_chain & operator=(const transform_multiallocation_chain &); - - typedef typename MultiallocationChain::void_pointer void_pointer; - typedef typename boost::intrusive::pointer_traits - void_pointer_traits; - typedef typename void_pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive::pointer_traits - pointer_traits; - - static pointer cast(const void_pointer &p) - { return pointer_traits::static_cast_from(p); } - - public: - typedef transform_iterator - < typename MultiallocationChain::iterator - , container_detail::cast_functor > iterator; - typedef typename MultiallocationChain::size_type size_type; - - transform_multiallocation_chain() - : MultiallocationChain() - {} - - transform_multiallocation_chain(BOOST_RV_REF(transform_multiallocation_chain) other) - : MultiallocationChain(::boost::move(static_cast(other))) - {} - - transform_multiallocation_chain(BOOST_RV_REF(MultiallocationChain) other) - : MultiallocationChain(::boost::move(static_cast(other))) - {} - - transform_multiallocation_chain& operator=(BOOST_RV_REF(transform_multiallocation_chain) other) - { - return static_cast - (this->MultiallocationChain::operator=(::boost::move(static_cast(other)))); - } -/* - void push_front(const pointer &mem) - { holder_.push_front(mem); } - - void push_back(const pointer &mem) - { return holder_.push_back(mem); } - - void swap(transform_multiallocation_chain &other_chain) - { holder_.swap(other_chain.holder_); } - - void splice_after(iterator after_this, transform_multiallocation_chain &x, iterator before_b, iterator before_e, size_type n) - { holder_.splice_after(after_this.base(), x.holder_, before_b.base(), before_e.base(), n); } - - void incorporate_after(iterator after_this, pointer b, pointer before_e, size_type n) - { holder_.incorporate_after(after_this.base(), b, before_e, n); } -*/ - pointer pop_front() - { return cast(this->MultiallocationChain::pop_front()); } -/* - bool empty() const - { return holder_.empty(); } - - iterator before_begin() - { return iterator(holder_.before_begin()); } -*/ - iterator begin() - { return iterator(this->MultiallocationChain::begin()); } -/* - iterator end() - { return iterator(holder_.end()); } - - iterator last() - { return iterator(holder_.last()); } - - size_type size() const - { return holder_.size(); } - - void clear() - { holder_.clear(); } -*/ - iterator insert_after(iterator it, pointer m) - { return iterator(this->MultiallocationChain::insert_after(it.base(), m)); } - - static iterator iterator_to(const pointer &p) - { return iterator(MultiallocationChain::iterator_to(p)); } - - std::pair extract_data() - { - std::pair data(this->MultiallocationChain::extract_data()); - return std::pair(cast(data.first), cast(data.second)); - } -/* - MultiallocationChain &extract_multiallocation_chain() - { return holder_; }*/ -}; - -}}} - -// namespace container_detail { -// namespace container { -// namespace boost { - -#include - -#endif //BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP diff --git a/utils/boost_idb/boost/container/detail/node_alloc_holder.hpp b/utils/boost_idb/boost/container/detail/node_alloc_holder.hpp deleted file mode 100644 index d94c2e9f..00000000 --- a/utils/boost_idb/boost/container/detail/node_alloc_holder.hpp +++ /dev/null @@ -1,387 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_NODE_ALLOC_HPP_ -#define BOOST_CONTAINER_DETAIL_NODE_ALLOC_HPP_ - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef BOOST_CONTAINER_PERFECT_FORWARDING -#include -#endif - -#include -#include - - -namespace boost { -namespace container { -namespace container_detail { - -template -struct node_compare - : private ValueCompare -{ - typedef typename ValueCompare::key_type key_type; - typedef typename ValueCompare::value_type value_type; - typedef typename ValueCompare::key_of_value key_of_value; - - explicit node_compare(const ValueCompare &pred) - : ValueCompare(pred) - {} - - node_compare() - : ValueCompare() - {} - - ValueCompare &value_comp() - { return static_cast(*this); } - - ValueCompare &value_comp() const - { return static_cast(*this); } - - bool operator()(const Node &a, const Node &b) const - { return ValueCompare::operator()(a.get_data(), b.get_data()); } -}; - -template -struct node_alloc_holder -{ - typedef allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::value_type value_type; - typedef typename ICont::value_type Node; - typedef typename allocator_traits_type::template - portable_rebind_alloc::type NodeAlloc; - typedef allocator_traits node_allocator_traits_type; - typedef container_detail::allocator_version_traits node_allocator_version_traits_type; - typedef A ValAlloc; - typedef typename node_allocator_traits_type::pointer NodePtr; - typedef container_detail::scoped_deallocator Deallocator; - typedef typename node_allocator_traits_type::size_type size_type; - typedef typename node_allocator_traits_type::difference_type difference_type; - typedef container_detail::integral_constant allocator_v1; - typedef container_detail::integral_constant allocator_v2; - typedef container_detail::integral_constant::value> alloc_version; - typedef typename ICont::iterator icont_iterator; - typedef typename ICont::const_iterator icont_citerator; - typedef allocator_destroyer Destroyer; - typedef allocator_traits NodeAllocTraits; - typedef allocator_version_traits AllocVersionTraits; - - private: - BOOST_COPYABLE_AND_MOVABLE(node_alloc_holder) - - public: - - //Constructors for sequence containers - node_alloc_holder() - : members_() - {} - - explicit node_alloc_holder(const ValAlloc &a) - : members_(a) - {} - - explicit node_alloc_holder(const node_alloc_holder &x) - : members_(NodeAllocTraits::select_on_container_copy_construction(x.node_alloc())) - {} - - explicit node_alloc_holder(BOOST_RV_REF(node_alloc_holder) x) - : members_(boost::move(x.node_alloc())) - { this->icont().swap(x.icont()); } - - //Constructors for associative containers - explicit node_alloc_holder(const ValAlloc &a, const ValPred &c) - : members_(a, c) - {} - - explicit node_alloc_holder(const node_alloc_holder &x, const ValPred &c) - : members_(NodeAllocTraits::select_on_container_copy_construction(x.node_alloc()), c) - {} - - explicit node_alloc_holder(const ValPred &c) - : members_(c) - {} - - //helpers for move assignments - explicit node_alloc_holder(BOOST_RV_REF(node_alloc_holder) x, const ValPred &c) - : members_(boost::move(x.node_alloc()), c) - { this->icont().swap(x.icont()); } - - void copy_assign_alloc(const node_alloc_holder &x) - { - container_detail::bool_ flag; - container_detail::assign_alloc( static_cast(this->members_) - , static_cast(x.members_), flag); - } - - void move_assign_alloc( node_alloc_holder &x) - { - container_detail::bool_ flag; - container_detail::move_alloc( static_cast(this->members_) - , static_cast(x.members_), flag); - } - - ~node_alloc_holder() - { this->clear(alloc_version()); } - - size_type max_size() const - { return allocator_traits_type::max_size(this->node_alloc()); } - - NodePtr allocate_one() - { return AllocVersionTraits::allocate_one(this->node_alloc()); } - - void deallocate_one(const NodePtr &p) - { AllocVersionTraits::deallocate_one(this->node_alloc(), p); } - - #ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - template - NodePtr create_node(Args &&...args) - { - NodePtr p = this->allocate_one(); - Deallocator node_deallocator(p, this->node_alloc()); - allocator_traits::construct - ( this->node_alloc() - , container_detail::addressof(p->m_data), boost::forward(args)...); - node_deallocator.release(); - //This does not throw - typedef typename Node::hook_type hook_type; - ::new(static_cast(container_detail::to_raw_pointer(p))) hook_type; - return (p); - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - NodePtr create_node(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - NodePtr p = this->allocate_one(); \ - Deallocator node_deallocator(p, this->node_alloc()); \ - allocator_traits::construct \ - (this->node_alloc(), container_detail::addressof(p->m_data) \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - node_deallocator.release(); \ - typedef typename Node::hook_type hook_type; \ - ::new(static_cast(container_detail::to_raw_pointer(p))) hook_type; \ - return (p); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - template - NodePtr create_node_from_it(const It &it) - { - NodePtr p = this->allocate_one(); - Deallocator node_deallocator(p, this->node_alloc()); - ::boost::container::construct_in_place(this->node_alloc(), container_detail::addressof(p->m_data), it); - node_deallocator.release(); - //This does not throw - typedef typename Node::hook_type hook_type; - ::new(static_cast(container_detail::to_raw_pointer(p))) hook_type; - return (p); - } - - void destroy_node(const NodePtr &nodep) - { - allocator_traits::destroy(this->node_alloc(), container_detail::to_raw_pointer(nodep)); - this->deallocate_one(nodep); - } - - void swap(node_alloc_holder &x) - { - this->icont().swap(x.icont()); - container_detail::bool_ flag; - container_detail::swap_alloc(this->node_alloc(), x.node_alloc(), flag); - } - - template - void allocate_many_and_construct - (FwdIterator beg, difference_type n, Inserter inserter) - { - if(n){ - typedef typename node_allocator_version_traits_type::multiallocation_chain multiallocation_chain; - - //Try to allocate memory in a single block - typedef typename multiallocation_chain::iterator multialloc_iterator; - multiallocation_chain mem; - NodeAlloc &nalloc = this->node_alloc(); - node_allocator_version_traits_type::allocate_individual(nalloc, n, mem); - multialloc_iterator itbeg(mem.begin()), itlast(mem.last()); - mem.clear(); - Node *p = 0; - BOOST_TRY{ - Deallocator node_deallocator(NodePtr(), nalloc); - container_detail::scoped_destructor sdestructor(nalloc, 0); - while(n--){ - p = container_detail::to_raw_pointer(&*itbeg); - node_deallocator.set(p); - ++itbeg; - //This can throw - boost::container::construct_in_place(nalloc, container_detail::addressof(p->m_data), beg); - sdestructor.set(p); - ++beg; - //This does not throw - typedef typename Node::hook_type hook_type; - ::new(static_cast(p)) hook_type; - //This can throw in some containers (predicate might throw). - //(sdestructor will destruct the node and node_deallocator will deallocate it in case of exception) - inserter(*p); - sdestructor.set(0); - } - sdestructor.release(); - node_deallocator.release(); - } - BOOST_CATCH(...){ - mem.incorporate_after(mem.last(), &*itbeg, &*itlast, n); - node_allocator_version_traits_type::deallocate_individual(this->node_alloc(), mem); - BOOST_RETHROW - } - BOOST_CATCH_END - } - } - - void clear(allocator_v1) - { this->icont().clear_and_dispose(Destroyer(this->node_alloc())); } - - void clear(allocator_v2) - { - typename NodeAlloc::multiallocation_chain chain; - allocator_destroyer_and_chain_builder builder(this->node_alloc(), chain); - this->icont().clear_and_dispose(builder); - //BOOST_STATIC_ASSERT((::boost::has_move_emulation_enabled::value == true)); - if(!chain.empty()) - this->node_alloc().deallocate_individual(chain); - } - - icont_iterator erase_range(const icont_iterator &first, const icont_iterator &last, allocator_v1) - { return this->icont().erase_and_dispose(first, last, Destroyer(this->node_alloc())); } - - icont_iterator erase_range(const icont_iterator &first, const icont_iterator &last, allocator_v2) - { - typedef typename NodeAlloc::multiallocation_chain multiallocation_chain; - NodeAlloc & nalloc = this->node_alloc(); - multiallocation_chain chain; - allocator_destroyer_and_chain_builder chain_builder(nalloc, chain); - icont_iterator ret_it = this->icont().erase_and_dispose(first, last, chain_builder); - nalloc.deallocate_individual(chain); - return ret_it; - } - - template - size_type erase_key(const Key& k, const Comparator &comp, allocator_v1) - { return this->icont().erase_and_dispose(k, comp, Destroyer(this->node_alloc())); } - - template - size_type erase_key(const Key& k, const Comparator &comp, allocator_v2) - { - allocator_multialloc_chain_node_deallocator chain_holder(this->node_alloc()); - return this->icont().erase_and_dispose(k, comp, chain_holder.get_chain_builder()); - } - - protected: - struct cloner - { - cloner(node_alloc_holder &holder) - : m_holder(holder) - {} - - NodePtr operator()(const Node &other) const - { return m_holder.create_node(other.get_data()); } - - node_alloc_holder &m_holder; - }; - - struct members_holder - : public NodeAlloc - { - private: - members_holder(const members_holder&); - members_holder & operator=(const members_holder&); - - public: - members_holder() - : NodeAlloc(), m_icont() - {} - - template - explicit members_holder(BOOST_FWD_REF(ConvertibleToAlloc) c2alloc) - : NodeAlloc(boost::forward(c2alloc)) - , m_icont() - {} - - template - members_holder(BOOST_FWD_REF(ConvertibleToAlloc) c2alloc, const ValPred &c) - : NodeAlloc(boost::forward(c2alloc)) - , m_icont(typename ICont::value_compare(c)) - {} - - explicit members_holder(const ValPred &c) - : NodeAlloc() - , m_icont(typename ICont::value_compare(c)) - {} - - //The intrusive container - ICont m_icont; - }; - - ICont &non_const_icont() const - { return const_cast(this->members_.m_icont); } - - ICont &icont() - { return this->members_.m_icont; } - - const ICont &icont() const - { return this->members_.m_icont; } - - NodeAlloc &node_alloc() - { return static_cast(this->members_); } - - const NodeAlloc &node_alloc() const - { return static_cast(this->members_); } - - members_holder members_; -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif // BOOST_CONTAINER_DETAIL_NODE_ALLOC_HPP_ diff --git a/utils/boost_idb/boost/container/detail/pair.hpp b/utils/boost_idb/boost/container/detail/pair.hpp deleted file mode 100644 index bfe7978c..00000000 --- a/utils/boost_idb/boost/container/detail/pair.hpp +++ /dev/null @@ -1,354 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_PAIR_HPP -#define BOOST_CONTAINER_CONTAINER_DETAIL_PAIR_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include - -#include -#include -#include -#include - -#include //std::pair -#include //std::swap - -#include -#include - -#ifndef BOOST_CONTAINER_PERFECT_FORWARDING -#include -#endif - -namespace boost { -namespace container { -namespace container_detail { - -template -struct pair; - -template -struct is_pair -{ - static const bool value = false; -}; - -template -struct is_pair< pair > -{ - static const bool value = true; -}; - -template -struct is_pair< std::pair > -{ - static const bool value = true; -}; - -struct pair_nat; - -struct piecewise_construct_t { }; -static const piecewise_construct_t piecewise_construct = piecewise_construct_t(); - -/* -template -struct pair -{ - template pair(pair&& p); - template - pair(piecewise_construct_t, tuple first_args, - tuple second_args); - - template pair& operator=(const pair& p); - pair& operator=(pair&& p) noexcept(is_nothrow_move_assignable::value && - is_nothrow_move_assignable::value); - template pair& operator=(pair&& p); - - void swap(pair& p) noexcept(noexcept(swap(first, p.first)) && - noexcept(swap(second, p.second))); -}; - -template bool operator==(const pair&, const pair&); -template bool operator!=(const pair&, const pair&); -template bool operator< (const pair&, const pair&); -template bool operator> (const pair&, const pair&); -template bool operator>=(const pair&, const pair&); -template bool operator<=(const pair&, const pair&); -*/ - - -template -struct pair -{ - private: - BOOST_COPYABLE_AND_MOVABLE(pair) - - public: - typedef T1 first_type; - typedef T2 second_type; - - T1 first; - T2 second; - - //Default constructor - pair() - : first(), second() - {} - - //pair copy assignment - pair(const pair& x) - : first(x.first), second(x.second) - {} - - //pair move constructor - pair(BOOST_RV_REF(pair) p) - : first(::boost::move(p.first)), second(::boost::move(p.second)) - {} - - template - pair(const pair &p) - : first(p.first), second(p.second) - {} - - template - pair(BOOST_RV_REF_BEG pair BOOST_RV_REF_END p) - : first(::boost::move(p.first)), second(::boost::move(p.second)) - {} - - //pair from two values - pair(const T1 &t1, const T2 &t2) - : first(t1) - , second(t2) - {} - - template - pair(BOOST_FWD_REF(U) u, BOOST_FWD_REF(V) v) - : first(::boost::forward(u)) - , second(::boost::forward(v)) - {} - - //And now compatibility with std::pair - pair(const std::pair& x) - : first(x.first), second(x.second) - {} - - template - pair(const std::pair& p) - : first(p.first), second(p.second) - {} - - pair(BOOST_RV_REF_BEG std::pair BOOST_RV_REF_END p) - : first(::boost::move(p.first)), second(::boost::move(p.second)) - {} - - template - pair(BOOST_RV_REF_BEG std::pair BOOST_RV_REF_END p) - : first(::boost::move(p.first)), second(::boost::move(p.second)) - {} - - //piecewise_construct missing - //template pair(pair&& p); - //template - // pair(piecewise_construct_t, tuple first_args, - // tuple second_args); -/* - //Variadic versions - template - pair(BOOST_CONTAINER_PP_PARAM(U, u), typename container_detail::disable_if - < container_detail::is_pair< typename container_detail::remove_ref_const::type >, pair_nat>::type* = 0) - : first(::boost::forward(u)) - , second() - {} - - #ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - template - pair(U &&u, V &&v) - : first(::boost::forward(u)) - , second(::boost::forward(v), ::boost::forward(args)...) - {} - - #else - - #define BOOST_PP_LOCAL_MACRO(n) \ - template \ - pair(BOOST_CONTAINER_PP_PARAM(U, u) \ - ,BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - : first(::boost::forward(u)) \ - , second(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)) \ - {} \ - //! - #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - #endif -*/ - //pair copy assignment - pair& operator=(BOOST_COPY_ASSIGN_REF(pair) p) - { - first = p.first; - second = p.second; - return *this; - } - - //pair move assignment - pair& operator=(BOOST_RV_REF(pair) p) - { - first = ::boost::move(p.first); - second = ::boost::move(p.second); - return *this; - } - - template - typename ::boost::container::container_detail::enable_if_c - < !(::boost::container::container_detail::is_same::value && - ::boost::container::container_detail::is_same::value) - , pair &>::type - operator=(const pair&p) - { - first = p.first; - second = p.second; - return *this; - } - - template - typename ::boost::container::container_detail::enable_if_c - < !(::boost::container::container_detail::is_same::value && - ::boost::container::container_detail::is_same::value) - , pair &>::type - operator=(BOOST_RV_REF_BEG pair BOOST_RV_REF_END p) - { - first = ::boost::move(p.first); - second = ::boost::move(p.second); - return *this; - } - - //std::pair copy assignment - pair& operator=(const std::pair &p) - { - first = p.first; - second = p.second; - return *this; - } - - template - pair& operator=(const std::pair &p) - { - first = ::boost::move(p.first); - second = ::boost::move(p.second); - return *this; - } - - //std::pair move assignment - pair& operator=(BOOST_RV_REF_BEG std::pair BOOST_RV_REF_END p) - { - first = ::boost::move(p.first); - second = ::boost::move(p.second); - return *this; - } - - template - pair& operator=(BOOST_RV_REF_BEG std::pair BOOST_RV_REF_END p) - { - first = ::boost::move(p.first); - second = ::boost::move(p.second); - return *this; - } - - //swap - void swap(pair& p) - { - using std::swap; - swap(this->first, p.first); - swap(this->second, p.second); - } -}; - -template -inline bool operator==(const pair& x, const pair& y) -{ return static_cast(x.first == y.first && x.second == y.second); } - -template -inline bool operator< (const pair& x, const pair& y) -{ return static_cast(x.first < y.first || - (!(y.first < x.first) && x.second < y.second)); } - -template -inline bool operator!=(const pair& x, const pair& y) -{ return static_cast(!(x == y)); } - -template -inline bool operator> (const pair& x, const pair& y) -{ return y < x; } - -template -inline bool operator>=(const pair& x, const pair& y) -{ return static_cast(!(x < y)); } - -template -inline bool operator<=(const pair& x, const pair& y) -{ return static_cast(!(y < x)); } - -template -inline pair make_pair(T1 x, T2 y) -{ return pair(x, y); } - -template -inline void swap(pair& x, pair& y) -{ - swap(x.first, y.first); - swap(x.second, y.second); -} - -} //namespace container_detail { -} //namespace container { - - -//Without this specialization recursive flat_(multi)map instantiation fails -//because is_enum needs to instantiate the recursive pair, leading to a compilation error). -//This breaks the cycle clearly stating that pair is not an enum avoiding any instantiation. -template -struct is_enum; - -template -struct is_enum< ::boost::container::container_detail::pair > -{ - static const bool value = false; -}; - -//This specialization is needed to avoid instantiation of pair in -//is_class, and allow recursive maps. -template -struct is_class< ::boost::container::container_detail::pair > - : public ::boost::true_type -{}; - -#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES - -template -struct has_move_emulation_enabled< ::boost::container::container_detail::pair > - : ::boost::true_type -{}; - -#endif - - -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_PAIR_HPP diff --git a/utils/boost_idb/boost/container/detail/preprocessor.hpp b/utils/boost_idb/boost/container/detail/preprocessor.hpp deleted file mode 100644 index 41d1f553..00000000 --- a/utils/boost_idb/boost/container/detail/preprocessor.hpp +++ /dev/null @@ -1,232 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP -#define BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include - -#ifdef BOOST_CONTAINER_PERFECT_FORWARDING -//#error "This file is not needed when perfect forwarding is available" -#endif //BOOST_CONTAINER_PERFECT_FORWARDING - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS 10 - -//Note: -//We define template parameters as const references to -//be able to bind temporaries. After that we will un-const them. -//This cast is ugly but it is necessary until "perfect forwarding" -//is achieved in C++0x. Meanwhile, if we want to be able to -//bind rvalues with non-const references, we have to be ugly -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - #define BOOST_CONTAINER_PP_PARAM_LIST(z, n, data) \ - BOOST_PP_CAT(P, n) && BOOST_PP_CAT(p, n) \ - //! -#else - #define BOOST_CONTAINER_PP_PARAM_LIST(z, n, data) \ - const BOOST_PP_CAT(P, n) & BOOST_PP_CAT(p, n) \ - //! -#endif //#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - -#define BOOST_CONTAINER_PP_CONST_REF_PARAM_LIST_Q(z, n, Data) \ -const BOOST_PP_CAT(Q, n) & BOOST_PP_CAT(q, n) \ -//! - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - #define BOOST_CONTAINER_PP_PARAM(U, u) \ - U && u \ - //! -#else - #define BOOST_CONTAINER_PP_PARAM(U, u) \ - const U & u \ - //! -#endif //#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - - #define BOOST_CONTAINER_PP_PARAM_INIT(z, n, data) \ - BOOST_PP_CAT(m_p, n) (::boost::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) )) \ - //! - -#else //BOOST_NO_CXX11_RVALUE_REFERENCES - - #define BOOST_CONTAINER_PP_PARAM_INIT(z, n, data) \ - BOOST_PP_CAT(m_p, n) (const_cast(BOOST_PP_CAT(p, n))) \ - //! -#endif //#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - - #if defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - - namespace boost { - namespace container { - namespace container_detail { - template - struct ref_holder; - - template - struct ref_holder - { - explicit ref_holder(T &t) - : t_(t) - {} - T &t_; - T & get() { return t_; } - }; - - template - struct ref_holder - { - explicit ref_holder(const T &t) - : t_(t) - {} - const T &t_; - const T & get() { return t_; } - }; - - template - struct ref_holder - { - explicit ref_holder(const T &t) - : t_(t) - {} - const T &t_; - const T & get() { return t_; } - }; - - template - struct ref_holder - { - explicit ref_holder(T &&t) - : t_(t) - {} - T &t_; - T && get() { return ::boost::move(t_); } - }; - - template - struct ref_holder - { - explicit ref_holder(T &&t) - : t_(t) - {} - T &t_; - T && get() { return ::boost::move(t_); } - }; - - } //namespace container_detail { - } //namespace container { - } //namespace boost { - - #define BOOST_CONTAINER_PP_PARAM_DEFINE(z, n, data) \ - ::boost::container::container_detail::ref_holder BOOST_PP_CAT(m_p, n); \ - //! - - #else //BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG - - #define BOOST_CONTAINER_PP_PARAM_DEFINE(z, n, data) \ - BOOST_PP_CAT(P, n) && BOOST_PP_CAT(m_p, n); \ - //! - - #endif //defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - -#else //BOOST_NO_CXX11_RVALUE_REFERENCES - - #define BOOST_CONTAINER_PP_PARAM_DEFINE(z, n, data) \ - BOOST_PP_CAT(P, n) & BOOST_PP_CAT(m_p, n); \ - //! -#endif //#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - -#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - - #define BOOST_CONTAINER_PP_MEMBER_FORWARD(z, n, data) BOOST_PP_CAT(this->m_p, n).get() \ - //! - -#else //!defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - - #define BOOST_CONTAINER_PP_MEMBER_FORWARD(z, n, data) \ - ::boost::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(this->m_p, n) ) \ - //! - -#endif //!defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - -#define BOOST_CONTAINER_PP_PARAM_INC(z, n, data) \ - BOOST_PP_CAT(++this->m_p, n) \ -//! - -#define BOOST_CONTAINER_PP_IDENTITY(z, n, data) data - - -#define BOOST_CONTAINER_PP_PARAM_FORWARD(z, n, data) \ -::boost::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) ) \ -//! - -#define BOOST_CONTAINER_PP_DECLVAL(z, n, data) \ -::boost::move_detail::declval< BOOST_PP_CAT(P, n) >() \ -//! - -#define BOOST_CONTAINER_PP_MEMBER_IT_FORWARD(z, n, data) \ -BOOST_PP_CAT(*this->m_p, n) \ -//! - -#define BOOST_CONTAINER_PP_TEMPLATE_PARAM_VOID_DEFAULT(z, n, data) \ - BOOST_PP_CAT(class P, n) = void \ -//! - -#define BOOST_CONTAINER_PP_TEMPLATE_PARAM_WITH_DEFAULT(z, n, default_type) \ - BOOST_PP_CAT(class P, n) = default_type \ -//! - -#define BOOST_CONTAINER_PP_STATIC_PARAM_REF_DECLARE(z, n, data) \ - static BOOST_PP_CAT(P, n) & BOOST_PP_CAT(p, n); \ -//! - -#define BOOST_CONTAINER_PP_PARAM_PASS(z, n, data) \ - BOOST_PP_CAT(p, n) \ -//! - -#define BOOST_CONTAINER_PP_FWD_TYPE(z, n, data) \ - typename ::boost::move_detail::forward_type< BOOST_PP_CAT(P, n) >::type \ -//! - -#include - -//#else - -//#ifdef BOOST_CONTAINER_PERFECT_FORWARDING -//#error "This file is not needed when perfect forwarding is available" -//#endif //BOOST_CONTAINER_PERFECT_FORWARDING - -#endif //#ifndef BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP diff --git a/utils/boost_idb/boost/container/detail/transform_iterator.hpp b/utils/boost_idb/boost/container/detail/transform_iterator.hpp deleted file mode 100644 index c40ecc6b..00000000 --- a/utils/boost_idb/boost/container/detail/transform_iterator.hpp +++ /dev/null @@ -1,176 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// (C) Copyright Gennaro Prota 2003 - 2004. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATORS_HPP -#define BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATORS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include -#include -#include - -namespace boost { -namespace container { - -template -struct operator_arrow_proxy -{ - operator_arrow_proxy(const PseudoReference &px) - : m_value(px) - {} - - PseudoReference* operator->() const { return &m_value; } - // This function is needed for MWCW and BCC, which won't call operator-> - // again automatically per 13.3.1.2 para 8 -// operator T*() const { return &m_value; } - mutable PseudoReference m_value; -}; - -template -struct operator_arrow_proxy -{ - operator_arrow_proxy(T &px) - : m_value(px) - {} - - T* operator->() const { return const_cast(&m_value); } - // This function is needed for MWCW and BCC, which won't call operator-> - // again automatically per 13.3.1.2 para 8 -// operator T*() const { return &m_value; } - T &m_value; -}; - -template -class transform_iterator - : public UnaryFunction - , public std::iterator - < typename Iterator::iterator_category - , typename container_detail::remove_reference::type - , typename Iterator::difference_type - , operator_arrow_proxy - , typename UnaryFunction::result_type> -{ - public: - explicit transform_iterator(const Iterator &it, const UnaryFunction &f = UnaryFunction()) - : UnaryFunction(f), m_it(it) - {} - - explicit transform_iterator() - : UnaryFunction(), m_it() - {} - - //Constructors - transform_iterator& operator++() - { increment(); return *this; } - - transform_iterator operator++(int) - { - transform_iterator result (*this); - increment(); - return result; - } - - friend bool operator== (const transform_iterator& i, const transform_iterator& i2) - { return i.equal(i2); } - - friend bool operator!= (const transform_iterator& i, const transform_iterator& i2) - { return !(i == i2); } - -/* - friend bool operator> (const transform_iterator& i, const transform_iterator& i2) - { return i2 < i; } - - friend bool operator<= (const transform_iterator& i, const transform_iterator& i2) - { return !(i > i2); } - - friend bool operator>= (const transform_iterator& i, const transform_iterator& i2) - { return !(i < i2); } -*/ - friend typename Iterator::difference_type operator- (const transform_iterator& i, const transform_iterator& i2) - { return i2.distance_to(i); } - - //Arithmetic - transform_iterator& operator+=(typename Iterator::difference_type off) - { this->advance(off); return *this; } - - transform_iterator operator+(typename Iterator::difference_type off) const - { - transform_iterator other(*this); - other.advance(off); - return other; - } - - friend transform_iterator operator+(typename Iterator::difference_type off, const transform_iterator& right) - { return right + off; } - - transform_iterator& operator-=(typename Iterator::difference_type off) - { this->advance(-off); return *this; } - - transform_iterator operator-(typename Iterator::difference_type off) const - { return *this + (-off); } - - typename UnaryFunction::result_type operator*() const - { return dereference(); } - - operator_arrow_proxy - operator->() const - { return operator_arrow_proxy(dereference()); } - - Iterator & base() - { return m_it; } - - const Iterator & base() const - { return m_it; } - - private: - Iterator m_it; - - void increment() - { ++m_it; } - - void decrement() - { --m_it; } - - bool equal(const transform_iterator &other) const - { return m_it == other.m_it; } - - bool less(const transform_iterator &other) const - { return other.m_it < m_it; } - - typename UnaryFunction::result_type dereference() const - { return UnaryFunction::operator()(*m_it); } - - void advance(typename Iterator::difference_type n) - { std::advance(m_it, n); } - - typename Iterator::difference_type distance_to(const transform_iterator &other)const - { return std::distance(other.m_it, m_it); } -}; - -template -transform_iterator -make_transform_iterator(Iterator it, UnaryFunc fun) -{ - return transform_iterator(it, fun); -} - -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATORS_HPP diff --git a/utils/boost_idb/boost/container/detail/tree.hpp b/utils/boost_idb/boost/container/detail/tree.hpp deleted file mode 100644 index 7400a1a8..00000000 --- a/utils/boost_idb/boost/container/detail/tree.hpp +++ /dev/null @@ -1,1085 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_TREE_HPP -#define BOOST_CONTAINER_TREE_HPP - -#include "config_begin.hpp" -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifndef BOOST_CONTAINER_PERFECT_FORWARDING -#include -#endif - -#include //std::pair -#include -#include - -namespace boost { -namespace container { -namespace container_detail { - -template -struct tree_value_compare - : public KeyCompare -{ - typedef Value value_type; - typedef KeyCompare key_compare; - typedef KeyOfValue key_of_value; - typedef Key key_type; - - explicit tree_value_compare(const key_compare &kcomp) - : KeyCompare(kcomp) - {} - - tree_value_compare() - : KeyCompare() - {} - - const key_compare &key_comp() const - { return static_cast(*this); } - - key_compare &key_comp() - { return static_cast(*this); } - - template - struct is_key - { - static const bool value = is_same::value; - }; - - template - typename enable_if_c::value, const key_type &>::type - key_forward(const T &key) const - { return key; } - - template - typename enable_if_c::value, const key_type &>::type - key_forward(const T &key) const - { return KeyOfValue()(key); } - - template - bool operator()(const KeyType &key1, const KeyType2 &key2) const - { return key_compare::operator()(this->key_forward(key1), this->key_forward(key2)); } -}; - -template -struct rbtree_hook -{ - typedef typename container_detail::bi::make_set_base_hook - < container_detail::bi::void_pointer - , container_detail::bi::link_mode - , container_detail::bi::optimize_size - >::type type; -}; - -//This trait is used to type-pun std::pair because in C++03 -//compilers std::pair is useless for C++11 features -template -struct rbtree_internal_data_type -{ - typedef T type; -}; - -template -struct rbtree_internal_data_type< std::pair > -{ - typedef pair type; -}; - - -//The node to be store in the tree -template -struct rbtree_node - : public rbtree_hook::type -{ - private: - //BOOST_COPYABLE_AND_MOVABLE(rbtree_node) - rbtree_node(); - - public: - typedef typename rbtree_hook::type hook_type; - - typedef T value_type; - typedef typename rbtree_internal_data_type::type internal_type; - - typedef rbtree_node node_type; - - T &get_data() - { - T* ptr = reinterpret_cast(&this->m_data); - return *ptr; - } - - const T &get_data() const - { - const T* ptr = reinterpret_cast(&this->m_data); - return *ptr; - } - - internal_type m_data; - - template - void do_assign(const std::pair &p) - { - const_cast(m_data.first) = p.first; - m_data.second = p.second; - } - - template - void do_assign(const pair &p) - { - const_cast(m_data.first) = p.first; - m_data.second = p.second; - } - - template - void do_assign(const V &v) - { m_data = v; } - - template - void do_move_assign(std::pair &p) - { - const_cast(m_data.first) = ::boost::move(p.first); - m_data.second = ::boost::move(p.second); - } - - template - void do_move_assign(pair &p) - { - const_cast(m_data.first) = ::boost::move(p.first); - m_data.second = ::boost::move(p.second); - } - - template - void do_move_assign(V &v) - { m_data = ::boost::move(v); } -}; - -template -class insert_equal_end_hint_functor -{ - Icont &icont_; - - public: - insert_equal_end_hint_functor(Icont &icont) - : icont_(icont) - {} - - void operator()(Node &n) - { this->icont_.insert_equal(this->icont_.cend(), n); } -}; - -template -class push_back_functor -{ - Icont &icont_; - - public: - push_back_functor(Icont &icont) - : icont_(icont) - {} - - void operator()(Node &n) - { this->icont_.push_back(n); } -}; - -}//namespace container_detail { - -namespace container_detail { - -template -struct intrusive_rbtree_type -{ - typedef typename boost::container:: - allocator_traits::value_type value_type; - typedef typename boost::container:: - allocator_traits::void_pointer void_pointer; - typedef typename boost::container:: - allocator_traits::size_type size_type; - typedef typename container_detail::rbtree_node - node_type; - typedef node_compare node_compare_type; - typedef typename container_detail::bi::make_rbtree - - ,container_detail::bi::base_hook::type> - ,container_detail::bi::constant_time_size - ,container_detail::bi::size_type - >::type container_type; - typedef container_type type ; -}; - -} //namespace container_detail { - -namespace container_detail { - -template -class rbtree - : protected container_detail::node_alloc_holder - < A - , typename container_detail::intrusive_rbtree_type - - >::type - , tree_value_compare - > -{ - typedef tree_value_compare - ValComp; - typedef typename container_detail::intrusive_rbtree_type - < A, ValComp>::type Icont; - typedef container_detail::node_alloc_holder - AllocHolder; - typedef typename AllocHolder::NodePtr NodePtr; - typedef rbtree < Key, Value, KeyOfValue - , KeyCompare, A> ThisType; - typedef typename AllocHolder::NodeAlloc NodeAlloc; - typedef typename AllocHolder::ValAlloc ValAlloc; - typedef typename AllocHolder::Node Node; - typedef typename Icont::iterator iiterator; - typedef typename Icont::const_iterator iconst_iterator; - typedef container_detail::allocator_destroyer Destroyer; - typedef typename AllocHolder::allocator_v1 allocator_v1; - typedef typename AllocHolder::allocator_v2 allocator_v2; - typedef typename AllocHolder::alloc_version alloc_version; - - class RecyclingCloner; - friend class RecyclingCloner; - - class RecyclingCloner - { - public: - RecyclingCloner(AllocHolder &holder, Icont &irbtree) - : m_holder(holder), m_icont(irbtree) - {} - - NodePtr operator()(const Node &other) const - { - if(NodePtr p = m_icont.unlink_leftmost_without_rebalance()){ - //First recycle a node (this can't throw) - BOOST_TRY{ - //This can throw - p->do_assign(other.m_data); - return p; - } - BOOST_CATCH(...){ - //If there is an exception destroy the whole source - m_holder.destroy_node(p); - while((p = m_icont.unlink_leftmost_without_rebalance())){ - m_holder.destroy_node(p); - } - BOOST_RETHROW - } - BOOST_CATCH_END - } - else{ - return m_holder.create_node(other.m_data); - } - } - - AllocHolder &m_holder; - Icont &m_icont; - }; - - class RecyclingMoveCloner; - friend class RecyclingMoveCloner; - - class RecyclingMoveCloner - { - public: - RecyclingMoveCloner(AllocHolder &holder, Icont &irbtree) - : m_holder(holder), m_icont(irbtree) - {} - - NodePtr operator()(const Node &other) const - { - if(NodePtr p = m_icont.unlink_leftmost_without_rebalance()){ - //First recycle a node (this can't throw) - BOOST_TRY{ - //This can throw - p->do_move_assign(const_cast(other).m_data); - return p; - } - BOOST_CATCH(...){ - //If there is an exception destroy the whole source - m_holder.destroy_node(p); - while((p = m_icont.unlink_leftmost_without_rebalance())){ - m_holder.destroy_node(p); - } - BOOST_RETHROW - } - BOOST_CATCH_END - } - else{ - return m_holder.create_node(other.m_data); - } - } - - AllocHolder &m_holder; - Icont &m_icont; - }; - - BOOST_COPYABLE_AND_MOVABLE(rbtree) - - public: - - typedef Key key_type; - typedef Value value_type; - typedef A allocator_type; - typedef KeyCompare key_compare; - typedef ValComp value_compare; - typedef typename boost::container:: - allocator_traits::pointer pointer; - typedef typename boost::container:: - allocator_traits::const_pointer const_pointer; - typedef typename boost::container:: - allocator_traits::reference reference; - typedef typename boost::container:: - allocator_traits::const_reference const_reference; - typedef typename boost::container:: - allocator_traits::size_type size_type; - typedef typename boost::container:: - allocator_traits::difference_type difference_type; - typedef difference_type rbtree_difference_type; - typedef pointer rbtree_pointer; - typedef const_pointer rbtree_const_pointer; - typedef reference rbtree_reference; - typedef const_reference rbtree_const_reference; - typedef NodeAlloc stored_allocator_type; - - private: - - template - struct key_node_compare - : private KeyValueCompare - { - key_node_compare(const KeyValueCompare &comp) - : KeyValueCompare(comp) - {} - - template - struct is_node - { - static const bool value = is_same::value; - }; - - template - typename enable_if_c::value, const value_type &>::type - key_forward(const T &node) const - { return node.get_data(); } - - template - typename enable_if_c::value, const T &>::type - key_forward(const T &key) const - { return key; } - - template - bool operator()(const KeyType &key1, const KeyType2 &key2) const - { return KeyValueCompare::operator()(this->key_forward(key1), this->key_forward(key2)); } - }; - - typedef key_node_compare KeyNodeCompare; - - public: - typedef container_detail::iterator iterator; - typedef container_detail::iterator const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - rbtree() - : AllocHolder(ValComp(key_compare())) - {} - - explicit rbtree(const key_compare& comp, const allocator_type& a = allocator_type()) - : AllocHolder(a, ValComp(comp)) - {} - - explicit rbtree(const allocator_type& a) - : AllocHolder(a) - {} - - template - rbtree(bool unique_insertion, InputIterator first, InputIterator last, const key_compare& comp, - const allocator_type& a - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < container_detail::is_input_iterator::value - || container_detail::is_same::value - >::type * = 0 - #endif - ) - : AllocHolder(a, value_compare(comp)) - { - //Use cend() as hint to achieve linear time for - //ordered ranges as required by the standard - //for the constructor - const const_iterator end_it(this->cend()); - if(unique_insertion){ - for ( ; first != last; ++first){ - this->insert_unique(end_it, *first); - } - } - else{ - for ( ; first != last; ++first){ - this->insert_equal(end_it, *first); - } - } - } - - template - rbtree(bool unique_insertion, InputIterator first, InputIterator last, const key_compare& comp, - const allocator_type& a - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !(container_detail::is_input_iterator::value - || container_detail::is_same::value) - >::type * = 0 - #endif - ) - : AllocHolder(a, value_compare(comp)) - { - if(unique_insertion){ - //Use cend() as hint to achieve linear time for - //ordered ranges as required by the standard - //for the constructor - const const_iterator end_it(this->cend()); - for ( ; first != last; ++first){ - this->insert_unique(end_it, *first); - } - } - else{ - //Optimized allocation and construction - this->allocate_many_and_construct - ( first, std::distance(first, last) - , insert_equal_end_hint_functor(this->icont())); - } - } - - template - rbtree( ordered_range_t, InputIterator first, InputIterator last - , const key_compare& comp = key_compare(), const allocator_type& a = allocator_type() - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < container_detail::is_input_iterator::value - || container_detail::is_same::value - >::type * = 0 - #endif - ) - : AllocHolder(a, value_compare(comp)) - { - for ( ; first != last; ++first){ - this->push_back_impl(*first); - } - } - - template - rbtree( ordered_range_t, InputIterator first, InputIterator last - , const key_compare& comp = key_compare(), const allocator_type& a = allocator_type() - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !(container_detail::is_input_iterator::value - || container_detail::is_same::value) - >::type * = 0 - #endif - ) - : AllocHolder(a, value_compare(comp)) - { - //Optimized allocation and construction - this->allocate_many_and_construct - ( first, std::distance(first, last) - , container_detail::push_back_functor(this->icont())); - } - - rbtree(const rbtree& x) - : AllocHolder(x, x.value_comp()) - { - this->icont().clone_from - (x.icont(), typename AllocHolder::cloner(*this), Destroyer(this->node_alloc())); - } - - rbtree(BOOST_RV_REF(rbtree) x) - : AllocHolder(::boost::move(static_cast(x)), x.value_comp()) - {} - - rbtree(const rbtree& x, const allocator_type &a) - : AllocHolder(a, x.value_comp()) - { - this->icont().clone_from - (x.icont(), typename AllocHolder::cloner(*this), Destroyer(this->node_alloc())); - } - - rbtree(BOOST_RV_REF(rbtree) x, const allocator_type &a) - : AllocHolder(a, x.value_comp()) - { - if(this->node_alloc() == x.node_alloc()){ - this->icont().swap(x.icont()); - } - else{ - this->icont().clone_from - (x.icont(), typename AllocHolder::cloner(*this), Destroyer(this->node_alloc())); - } - } - - ~rbtree() - {} //AllocHolder clears the tree - - rbtree& operator=(BOOST_COPY_ASSIGN_REF(rbtree) x) - { - if (&x != this){ - NodeAlloc &this_alloc = this->get_stored_allocator(); - const NodeAlloc &x_alloc = x.get_stored_allocator(); - container_detail::bool_:: - propagate_on_container_copy_assignment::value> flag; - if(flag && this_alloc != x_alloc){ - this->clear(); - } - this->AllocHolder::copy_assign_alloc(x); - //Transfer all the nodes to a temporary tree - //If anything goes wrong, all the nodes will be destroyed - //automatically - Icont other_tree(::boost::move(this->icont())); - - //Now recreate the source tree reusing nodes stored by other_tree - this->icont().clone_from - (x.icont() - , RecyclingCloner(*this, other_tree) - , Destroyer(this->node_alloc())); - - //If there are remaining nodes, destroy them - NodePtr p; - while((p = other_tree.unlink_leftmost_without_rebalance())){ - AllocHolder::destroy_node(p); - } - } - return *this; - } - - rbtree& operator=(BOOST_RV_REF(rbtree) x) - { - if (&x != this){ - NodeAlloc &this_alloc = this->get_stored_allocator(); - const NodeAlloc &x_alloc = x.get_stored_allocator(); - //If allocators are equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy and swap pointers - this->clear(); - this->icont() = ::boost::move(x.icont()); - //Move allocator if needed - this->AllocHolder::move_assign_alloc(x); - } - //If unequal allocators, then do a one by one move - else{ - //Transfer all the nodes to a temporary tree - //If anything goes wrong, all the nodes will be destroyed - //automatically - Icont other_tree(::boost::move(this->icont())); - - //Now recreate the source tree reusing nodes stored by other_tree - this->icont().clone_from - (x.icont() - , RecyclingMoveCloner(*this, other_tree) - , Destroyer(this->node_alloc())); - - //If there are remaining nodes, destroy them - NodePtr p; - while((p = other_tree.unlink_leftmost_without_rebalance())){ - AllocHolder::destroy_node(p); - } - } - } - return *this; - } - - public: - // accessors: - value_compare value_comp() const - { return this->icont().value_comp().value_comp(); } - - key_compare key_comp() const - { return this->icont().value_comp().value_comp().key_comp(); } - - allocator_type get_allocator() const - { return allocator_type(this->node_alloc()); } - - const stored_allocator_type &get_stored_allocator() const - { return this->node_alloc(); } - - stored_allocator_type &get_stored_allocator() - { return this->node_alloc(); } - - iterator begin() - { return iterator(this->icont().begin()); } - - const_iterator begin() const - { return this->cbegin(); } - - iterator end() - { return iterator(this->icont().end()); } - - const_iterator end() const - { return this->cend(); } - - reverse_iterator rbegin() - { return reverse_iterator(end()); } - - const_reverse_iterator rbegin() const - { return this->crbegin(); } - - reverse_iterator rend() - { return reverse_iterator(begin()); } - - const_reverse_iterator rend() const - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const - { return const_iterator(this->non_const_icont().begin()); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const - { return const_iterator(this->non_const_icont().end()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const - { return const_reverse_iterator(cend()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const - { return const_reverse_iterator(cbegin()); } - - bool empty() const - { return !this->size(); } - - size_type size() const - { return this->icont().size(); } - - size_type max_size() const - { return AllocHolder::max_size(); } - - void swap(ThisType& x) - { AllocHolder::swap(x); } - - public: - - typedef typename Icont::insert_commit_data insert_commit_data; - - // insert/erase - std::pair insert_unique_check - (const key_type& key, insert_commit_data &data) - { - std::pair ret = - this->icont().insert_unique_check(key, KeyNodeCompare(value_comp()), data); - return std::pair(iterator(ret.first), ret.second); - } - - std::pair insert_unique_check - (const_iterator hint, const key_type& key, insert_commit_data &data) - { - std::pair ret = - this->icont().insert_unique_check(hint.get(), key, KeyNodeCompare(value_comp()), data); - return std::pair(iterator(ret.first), ret.second); - } - - iterator insert_unique_commit(const value_type& v, insert_commit_data &data) - { - NodePtr tmp = AllocHolder::create_node(v); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_unique_commit(*tmp, data)); - destroy_deallocator.release(); - return ret; - } - - template - iterator insert_unique_commit - (BOOST_FWD_REF(MovableConvertible) mv, insert_commit_data &data) - { - NodePtr tmp = AllocHolder::create_node(boost::forward(mv)); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_unique_commit(*tmp, data)); - destroy_deallocator.release(); - return ret; - } - - std::pair insert_unique(const value_type& v) - { - insert_commit_data data; - std::pair ret = - this->insert_unique_check(KeyOfValue()(v), data); - if(ret.second){ - ret.first = this->insert_unique_commit(v, data); - } - return ret; - } - - template - std::pair insert_unique(BOOST_FWD_REF(MovableConvertible) mv) - { - insert_commit_data data; - std::pair ret = - this->insert_unique_check(KeyOfValue()(mv), data); - if(ret.second){ - ret.first = this->insert_unique_commit(boost::forward(mv), data); - } - return ret; - } - - private: - - template - void push_back_impl(BOOST_FWD_REF(MovableConvertible) mv) - { - NodePtr tmp(AllocHolder::create_node(boost::forward(mv))); - //push_back has no-throw guarantee so avoid any deallocator/destroyer - this->icont().push_back(*tmp); - } - - std::pair emplace_unique_impl(NodePtr p) - { - value_type &v = p->get_data(); - insert_commit_data data; - scoped_destroy_deallocator destroy_deallocator(p, this->node_alloc()); - std::pair ret = - this->insert_unique_check(KeyOfValue()(v), data); - if(!ret.second){ - return ret; - } - //No throw insertion part, release rollback - destroy_deallocator.release(); - return std::pair - ( iterator(iiterator(this->icont().insert_unique_commit(*p, data))) - , true ); - } - - iterator emplace_unique_hint_impl(const_iterator hint, NodePtr p) - { - value_type &v = p->get_data(); - insert_commit_data data; - std::pair ret = - this->insert_unique_check(hint, KeyOfValue()(v), data); - if(!ret.second){ - Destroyer(this->node_alloc())(p); - return ret.first; - } - return iterator(iiterator(this->icont().insert_unique_commit(*p, data))); - } - - public: - - #ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - template - std::pair emplace_unique(Args&&... args) - { return this->emplace_unique_impl(AllocHolder::create_node(boost::forward(args)...)); } - - template - iterator emplace_hint_unique(const_iterator hint, Args&&... args) - { return this->emplace_unique_hint_impl(hint, AllocHolder::create_node(boost::forward(args)...)); } - - template - iterator emplace_equal(Args&&... args) - { - NodePtr tmp(AllocHolder::create_node(boost::forward(args)...)); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_equal(this->icont().end(), *tmp)); - destroy_deallocator.release(); - return ret; - } - - template - iterator emplace_hint_equal(const_iterator hint, Args&&... args) - { - NodePtr tmp(AllocHolder::create_node(boost::forward(args)...)); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_equal(hint.get(), *tmp)); - destroy_deallocator.release(); - return ret; - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - std::pair emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - return this->emplace_unique_impl \ - (AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint_unique(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - return this->emplace_unique_hint_impl \ - (hint, AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - NodePtr tmp(AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); \ - iterator ret(this->icont().insert_equal(this->icont().end(), *tmp)); \ - destroy_deallocator.release(); \ - return ret; \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint_equal(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - NodePtr tmp(AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); \ - iterator ret(this->icont().insert_equal(hint.get(), *tmp)); \ - destroy_deallocator.release(); \ - return ret; \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - iterator insert_unique(const_iterator hint, const value_type& v) - { - insert_commit_data data; - std::pair ret = - this->insert_unique_check(hint, KeyOfValue()(v), data); - if(!ret.second) - return ret.first; - return this->insert_unique_commit(v, data); - } - - template - iterator insert_unique(const_iterator hint, BOOST_FWD_REF(MovableConvertible) mv) - { - insert_commit_data data; - std::pair ret = - this->insert_unique_check(hint, KeyOfValue()(mv), data); - if(!ret.second) - return ret.first; - return this->insert_unique_commit(boost::forward(mv), data); - } - - template - void insert_unique(InputIterator first, InputIterator last) - { - for( ; first != last; ++first) - this->insert_unique(*first); - } - - iterator insert_equal(const value_type& v) - { - NodePtr tmp(AllocHolder::create_node(v)); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_equal(this->icont().end(), *tmp)); - destroy_deallocator.release(); - return ret; - } - - template - iterator insert_equal(BOOST_FWD_REF(MovableConvertible) mv) - { - NodePtr tmp(AllocHolder::create_node(boost::forward(mv))); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_equal(this->icont().end(), *tmp)); - destroy_deallocator.release(); - return ret; - } - - iterator insert_equal(const_iterator hint, const value_type& v) - { - NodePtr tmp(AllocHolder::create_node(v)); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_equal(hint.get(), *tmp)); - destroy_deallocator.release(); - return ret; - } - - template - iterator insert_equal(const_iterator hint, BOOST_FWD_REF(MovableConvertible) mv) - { - NodePtr tmp(AllocHolder::create_node(boost::forward(mv))); - scoped_destroy_deallocator destroy_deallocator(tmp, this->node_alloc()); - iterator ret(this->icont().insert_equal(hint.get(), *tmp)); - destroy_deallocator.release(); - return ret; - } - - template - void insert_equal(InputIterator first, InputIterator last) - { - for( ; first != last; ++first) - this->insert_equal(*first); - } - - iterator erase(const_iterator position) - { return iterator(this->icont().erase_and_dispose(position.get(), Destroyer(this->node_alloc()))); } - - size_type erase(const key_type& k) - { return AllocHolder::erase_key(k, KeyNodeCompare(value_comp()), alloc_version()); } - - iterator erase(const_iterator first, const_iterator last) - { return iterator(AllocHolder::erase_range(first.get(), last.get(), alloc_version())); } - - void clear() - { AllocHolder::clear(alloc_version()); } - - // set operations: - iterator find(const key_type& k) - { return iterator(this->icont().find(k, KeyNodeCompare(value_comp()))); } - - const_iterator find(const key_type& k) const - { return const_iterator(this->non_const_icont().find(k, KeyNodeCompare(value_comp()))); } - - size_type count(const key_type& k) const - { return size_type(this->icont().count(k, KeyNodeCompare(value_comp()))); } - - iterator lower_bound(const key_type& k) - { return iterator(this->icont().lower_bound(k, KeyNodeCompare(value_comp()))); } - - const_iterator lower_bound(const key_type& k) const - { return const_iterator(this->non_const_icont().lower_bound(k, KeyNodeCompare(value_comp()))); } - - iterator upper_bound(const key_type& k) - { return iterator(this->icont().upper_bound(k, KeyNodeCompare(value_comp()))); } - - const_iterator upper_bound(const key_type& k) const - { return const_iterator(this->non_const_icont().upper_bound(k, KeyNodeCompare(value_comp()))); } - - std::pair equal_range(const key_type& k) - { - std::pair ret = - this->icont().equal_range(k, KeyNodeCompare(value_comp())); - return std::pair(iterator(ret.first), iterator(ret.second)); - } - - std::pair equal_range(const key_type& k) const - { - std::pair ret = - this->non_const_icont().equal_range(k, KeyNodeCompare(value_comp())); - return std::pair - (const_iterator(ret.first), const_iterator(ret.second)); - } -}; - -template -inline bool -operator==(const rbtree& x, - const rbtree& y) -{ - return x.size() == y.size() && - std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator<(const rbtree& x, - const rbtree& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), - y.begin(), y.end()); -} - -template -inline bool -operator!=(const rbtree& x, - const rbtree& y) { - return !(x == y); -} - -template -inline bool -operator>(const rbtree& x, - const rbtree& y) { - return y < x; -} - -template -inline bool -operator<=(const rbtree& x, - const rbtree& y) { - return !(y < x); -} - -template -inline bool -operator>=(const rbtree& x, - const rbtree& y) { - return !(x < y); -} - - -template -inline void -swap(rbtree& x, - rbtree& y) -{ - x.swap(y); -} - -} //namespace container_detail { -} //namespace container { -/* -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move - > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; -*/ -} //namespace boost { - -#include - -#endif //BOOST_CONTAINER_TREE_HPP diff --git a/utils/boost_idb/boost/container/detail/type_traits.hpp b/utils/boost_idb/boost/container/detail/type_traits.hpp deleted file mode 100644 index 8dbd1826..00000000 --- a/utils/boost_idb/boost/container/detail/type_traits.hpp +++ /dev/null @@ -1,210 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// (C) Copyright John Maddock 2000. -// (C) Copyright Ion Gaztanaga 2005-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -// The alignment_of implementation comes from John Maddock's boost::alignment_of code -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_TYPE_TRAITS_HPP -#define BOOST_CONTAINER_CONTAINER_DETAIL_TYPE_TRAITS_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" - -#include - -namespace boost { -namespace container { -namespace container_detail { - -struct nat{}; - -template -struct LowPriorityConversion -{ - // Convertible from T with user-defined-conversion rank. - LowPriorityConversion(const U&) { } -}; - -//boost::alignment_of yields to 10K lines of preprocessed code, so we -//need an alternative -template struct alignment_of; - -template -struct alignment_of_hack -{ - char c; - T t; - alignment_of_hack(); -}; - -template -struct alignment_logic -{ - enum{ value = A < S ? A : S }; -}; - -template< typename T > -struct alignment_of -{ - enum{ value = alignment_logic - < sizeof(alignment_of_hack) - sizeof(T) - , sizeof(T)>::value }; -}; - -//This is not standard, but should work with all compilers -union max_align -{ - char char_; - short short_; - int int_; - long long_; - #ifdef BOOST_HAS_LONG_LONG - long long long_long_; - #endif - float float_; - double double_; - long double long_double_; - void * void_ptr_; -}; - -template -struct remove_reference -{ - typedef T type; -}; - -template -struct remove_reference -{ - typedef T type; -}; - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - -template -struct remove_reference -{ - typedef T type; -}; - -#else - -template -struct remove_reference< ::boost::rv > -{ - typedef T type; -}; - -#endif - -template -struct is_reference -{ - enum { value = false }; -}; - -template -struct is_reference -{ - enum { value = true }; -}; - -template -struct is_pointer -{ - enum { value = false }; -}; - -template -struct is_pointer -{ - enum { value = true }; -}; - -template -struct add_reference -{ - typedef T& type; -}; - -template -struct add_reference -{ - typedef T& type; -}; - -template<> -struct add_reference -{ - typedef nat &type; -}; - -template<> -struct add_reference -{ - typedef const nat &type; -}; - -template -struct add_const_reference -{ typedef const T &type; }; - -template -struct add_const_reference -{ typedef T& type; }; - -template -struct is_same -{ - typedef char yes_type; - struct no_type - { - char padding[8]; - }; - - template - static yes_type is_same_tester(V*, V*); - static no_type is_same_tester(...); - - static T *t; - static U *u; - - static const bool value = sizeof(yes_type) == sizeof(is_same_tester(t,u)); -}; - -template -struct remove_const -{ - typedef T type; -}; - -template -struct remove_const< const T> -{ - typedef T type; -}; - -template -struct remove_ref_const -{ - typedef typename remove_const< typename remove_reference::type >::type type; -}; - -} // namespace container_detail -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_TYPE_TRAITS_HPP diff --git a/utils/boost_idb/boost/container/detail/utilities.hpp b/utils/boost_idb/boost/container/detail/utilities.hpp deleted file mode 100644 index c42087c2..00000000 --- a/utils/boost_idb/boost/container/detail/utilities.hpp +++ /dev/null @@ -1,1180 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_UTILITIES_HPP -#define BOOST_CONTAINER_DETAIL_UTILITIES_HPP - -#include "config_begin.hpp" -#include "workaround.hpp" -#include -#include //for ::memcpy -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include //std::distance - -namespace boost { -namespace container { - -////////////////////////////////////////////////////////////////////////////// -// -// swap -// -////////////////////////////////////////////////////////////////////////////// - -namespace container_swap { - -template::value > -struct has_member_swap -{ - static const bool value = boost::container::container_detail:: - has_member_function_callable_with_swap::value; -}; - -template -struct has_member_swap -{ - static const bool value = false; -}; - -} //namespace container_swap { - -template inline -typename container_detail::enable_if_c - ::value, void>::type -swap_dispatch(T &left, T &right) //swap using member swap -{ - left.swap(right); // may throw -} - -template inline -typename container_detail::enable_if_c - ::value && boost::has_move_emulation_enabled::value, void>::type - swap_dispatch(T &left, T &right) -{ - T temp(boost::move(left)); // may throw - left = boost::move(right); // may throw - right = boost::move(temp); // may throw -} - -template inline -typename container_detail::enable_if_c - ::value && !boost::has_move_emulation_enabled::value, void>::type - swap_dispatch(T &left, T &right) -{ - using std::swap; - swap(left, right); // may throw -} - -namespace container_detail { - -template -inline T* addressof(T& obj) -{ - return static_cast( - static_cast( - const_cast( - &reinterpret_cast(obj) - ))); -} - -template -const T &max_value(const T &a, const T &b) -{ return a > b ? a : b; } - -template -const T &min_value(const T &a, const T &b) -{ return a < b ? a : b; } - -template -SizeType - get_next_capacity(const SizeType max_size - ,const SizeType capacity - ,const SizeType n) -{ -// if (n > max_size - capacity) -// throw std::length_error("get_next_capacity"); - - const SizeType m3 = max_size/3; - - if (capacity < m3) - return capacity + max_value(3*(capacity+1)/5, n); - - if (capacity < m3*2) - return capacity + max_value((capacity+1)/2, n); - - return max_size; -} - -template -inline T* to_raw_pointer(T* p) -{ return p; } - -template -inline typename Pointer::element_type* - to_raw_pointer(const Pointer &p) -{ return boost::container::container_detail::to_raw_pointer(p.operator->()); } - - -template -inline void swap_alloc(AllocatorType &, AllocatorType &, container_detail::false_type) - BOOST_CONTAINER_NOEXCEPT -{} - -template -inline void swap_alloc(AllocatorType &l, AllocatorType &r, container_detail::true_type) -{ boost::container::swap_dispatch(l, r); } - -template -inline void assign_alloc(AllocatorType &, const AllocatorType &, container_detail::false_type) - BOOST_CONTAINER_NOEXCEPT -{} - -template -inline void assign_alloc(AllocatorType &l, const AllocatorType &r, container_detail::true_type) -{ l = r; } - -template -inline void move_alloc(AllocatorType &, AllocatorType &, container_detail::false_type) - BOOST_CONTAINER_NOEXCEPT -{} - -template -inline void move_alloc(AllocatorType &l, AllocatorType &r, container_detail::true_type) -{ l = ::boost::move(r); } - -//Rounds "orig_size" by excess to round_to bytes -template -inline SizeType get_rounded_size(SizeType orig_size, SizeType round_to) -{ - return ((orig_size-1)/round_to+1)*round_to; -} - -template -struct ct_rounded_size -{ - enum { value = ((OrigSize-1)/RoundTo+1)*RoundTo }; -}; - -template -struct are_elements_contiguous -{ - static const bool value = false; -}; - -///////////////////////// -// raw pointers -///////////////////////// - -template -struct are_elements_contiguous -{ - static const bool value = true; -}; - -///////////////////////// -// predeclarations -///////////////////////// - -#ifndef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -template -class vector_iterator; - -template -class vector_const_iterator; - -#endif //BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -} //namespace container_detail { -} //namespace container { - -namespace interprocess { - -template -class offset_ptr; - -} //namespace interprocess { - -namespace container { - -namespace container_detail { - -///////////////////////// -//vector_[const_]iterator -///////////////////////// - -#ifndef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -template -struct are_elements_contiguous > -{ - static const bool value = true; -}; - -template -struct are_elements_contiguous > -{ - static const bool value = true; -}; - -#endif //BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -///////////////////////// -// offset_ptr -///////////////////////// - -template -struct are_elements_contiguous< ::boost::interprocess::offset_ptr > -{ - static const bool value = true; -}; - -template -struct are_contiguous_and_same -{ - static const bool is_same_io = - is_same< typename remove_const< typename ::std::iterator_traits::value_type >::type - , typename ::std::iterator_traits::value_type - >::value; - static const bool value = is_same_io && - are_elements_contiguous::value && - are_elements_contiguous::value; -}; - -template -struct is_memcpy_copy_assignable -{ - static const bool value = are_contiguous_and_same::value && - boost::has_trivial_assign< typename ::std::iterator_traits::value_type >::value; -}; - -template -struct is_memcpy_copy_constructible -{ - static const bool value = are_contiguous_and_same::value && - boost::has_trivial_copy< typename ::std::iterator_traits::value_type >::value; -}; - -template -struct enable_if_memcpy_copy_constructible - : public enable_if_c::value, R> -{}; - -template -struct disable_if_memcpy_copy_constructible - : public enable_if_c::value, R> -{}; - -template -struct enable_if_memcpy_copy_assignable - : public enable_if_c::value, R> -{}; - -template -struct disable_if_memcpy_copy_assignable - : public enable_if_c::value, R> -{}; - -template - // F models ForwardIterator -inline F memcpy(I f, I l, F r) BOOST_CONTAINER_NOEXCEPT -{ - typedef typename std::iterator_traits::value_type value_type; - typename std::iterator_traits::difference_type n = std::distance(f, l); - ::memcpy(container_detail::addressof(*r), container_detail::addressof(*f), sizeof(value_type)*n); - std::advance(r, n); - return r; -} - -template - // F models ForwardIterator -F memcpy_n(I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ - typedef typename std::iterator_traits::value_type value_type; - ::memcpy(container_detail::addressof(*r), container_detail::addressof(*f), sizeof(value_type)*n); - std::advance(r, n); - return r; -} - -template - // F models ForwardIterator -I memcpy_n_source(I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ - typedef typename std::iterator_traits::value_type value_type; - ::memcpy(container_detail::addressof(*r), container_detail::addressof(*f), sizeof(value_type)*n); - std::advance(f, n); - return f; -} - -template - // F models ForwardIterator -I memcpy_n_source_dest(I f, typename std::iterator_traits::difference_type n, F &r) BOOST_CONTAINER_NOEXCEPT -{ - typedef typename std::iterator_traits::value_type value_type; - ::memcpy(container_detail::addressof(*r), container_detail::addressof(*f), sizeof(value_type)*n); - std::advance(f, n); - std::advance(r, n); - return f; -} - - -} //namespace container_detail { - - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_move_alloc -// -////////////////////////////////////////////////////////////////////////////// - - -//! Effects: -//! \code -//! for (; f != l; ++r, ++f) -//! allocator_traits::construct(a, &*r, boost::move(*f)); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_constructible::type - uninitialized_move_alloc(A &a, I f, I l, F r) -{ - F back = r; - BOOST_TRY{ - while (f != l) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), boost::move(*f)); - ++f; ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_constructible::type - uninitialized_move_alloc(A &, I f, I l, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy(f, l, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_move_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r, boost::move(*f)); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_constructible::type - uninitialized_move_alloc_n(A &a, I f, typename std::iterator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), boost::move(*f)); - ++f; ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_constructible::type - uninitialized_move_alloc_n(A &, I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_move_alloc_n_source -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r, boost::move(*f)); -//! \endcode -//! -//! Returns: f (after incremented) -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_constructible::type - uninitialized_move_alloc_n_source(A &a, I f, typename std::iterator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), boost::move(*f)); - ++f; ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return f; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_constructible::type - uninitialized_move_alloc_n_source(A &, I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n_source(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_copy_alloc -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; f != l; ++r, ++f) -//! allocator_traits::construct(a, &*r, *f); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_constructible::type - uninitialized_copy_alloc(A &a, I f, I l, F r) -{ - F back = r; - BOOST_TRY{ - while (f != l) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), *f); - ++f; ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_constructible::type - uninitialized_copy_alloc(A &, I f, I l, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy(f, l, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_copy_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r, *f); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_constructible::type - uninitialized_copy_alloc_n(A &a, I f, typename std::iterator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), *f); - ++f; ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_constructible::type - uninitialized_copy_alloc_n(A &, I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_copy_alloc_n_source -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r, *f); -//! \endcode -//! -//! Returns: f (after incremented) -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_constructible::type - uninitialized_copy_alloc_n_source(A &a, I f, typename std::iterator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), *f); - ++f; ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return f; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_constructible::type - uninitialized_copy_alloc_n_source(A &, I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n_source(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_value_init_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline F uninitialized_value_init_alloc_n(A &a, typename allocator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r)); - ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_default_init_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline F uninitialized_default_init_alloc_n(A &a, typename allocator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), default_init); - ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_fill_alloc -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; f != l; ++r, ++f) -//! allocator_traits::construct(a, &*r, *f); -//! \endcode -//! -//! Returns: r -template - -inline void uninitialized_fill_alloc(A &a, F f, F l, const T &t) -{ - F back = f; - BOOST_TRY{ - while (f != l) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*f), t); - ++f; - } - } - BOOST_CATCH(...){ - for (; back != l; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END -} - - -////////////////////////////////////////////////////////////////////////////// -// -// uninitialized_fill_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -//! Effects: -//! \code -//! for (; n--; ++r, ++f) -//! allocator_traits::construct(a, &*r, v); -//! \endcode -//! -//! Returns: r -template - // F models ForwardIterator -inline F uninitialized_fill_alloc_n(A &a, const T &v, typename allocator_traits::difference_type n, F r) -{ - F back = r; - BOOST_TRY{ - while (n--) { - allocator_traits::construct(a, container_detail::to_raw_pointer(&*r), v); - ++r; - } - } - BOOST_CATCH(...){ - for (; back != r; ++back){ - allocator_traits::destroy(a, container_detail::to_raw_pointer(&*back)); - } - BOOST_RETHROW; - } - BOOST_CATCH_END - return r; -} - -////////////////////////////////////////////////////////////////////////////// -// -// copy -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - copy(I f, I l, F r) -{ - while (f != l) { - *r = *f; - ++f; ++r; - } - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - copy(I f, I l, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy(f, l, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// copy_n -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - copy_n(I f, typename std::iterator_traits::difference_type n, F r) -{ - while (n--) { - *r = *f; - ++f; ++r; - } - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - copy_n(I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// copy_n_source -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - copy_n_source(I f, typename std::iterator_traits::difference_type n, F r) -{ - while (n--) { - *r = *f; - ++f; ++r; - } - return f; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - copy_n_source(I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n_source(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// copy_n_source_dest -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - copy_n_source_dest(I f, typename std::iterator_traits::difference_type n, F &r) -{ - while (n--) { - *r = *f; - ++f; ++r; - } - return f; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - copy_n_source_dest(I f, typename std::iterator_traits::difference_type n, F &r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n_source_dest(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// move -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - move(I f, I l, F r) -{ - while (f != l) { - *r = ::boost::move(*f); - ++f; ++r; - } - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - move(I f, I l, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy(f, l, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// move_n -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - move_n(I f, typename std::iterator_traits::difference_type n, F r) -{ - while (n--) { - *r = ::boost::move(*f); - ++f; ++r; - } - return r; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - move_n(I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// move_n_source -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - move_n_source(I f, typename std::iterator_traits::difference_type n, F r) -{ - while (n--) { - *r = ::boost::move(*f); - ++f; ++r; - } - return f; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - move_n_source(I f, typename std::iterator_traits::difference_type n, F r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n_source(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// move_n_source_dest -// -////////////////////////////////////////////////////////////////////////////// - -template - // F models ForwardIterator -inline typename container_detail::disable_if_memcpy_copy_assignable::type - move_n_source_dest(I f, typename std::iterator_traits::difference_type n, F &r) -{ - while (n--) { - *r = ::boost::move(*f); - ++f; ++r; - } - return f; -} - -template - // F models ForwardIterator -inline typename container_detail::enable_if_memcpy_copy_assignable::type - move_n_source_dest(I f, typename std::iterator_traits::difference_type n, F &r) BOOST_CONTAINER_NOEXCEPT -{ return container_detail::memcpy_n_source_dest(f, n, r); } - -////////////////////////////////////////////////////////////////////////////// -// -// destroy_n -// -////////////////////////////////////////////////////////////////////////////// - -template - // I models InputIterator -inline void destroy_alloc_n(A &a, I f, typename std::iterator_traits::difference_type n - ,typename boost::container::container_detail::enable_if_c - < !boost::has_trivial_destructor::value_type>::value >::type* = 0) -{ - while(n--){ - allocator_traits::destroy(a, container_detail::addressof(*f++)); - } -} - -template - // I models InputIterator -inline void destroy_alloc_n(A &, I, typename std::iterator_traits::difference_type - ,typename boost::container::container_detail::enable_if_c - < boost::has_trivial_destructor::value_type>::value >::type* = 0) -{} - -////////////////////////////////////////////////////////////////////////////// -// -// deep_swap_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -template - -inline typename container_detail::disable_if_memcpy_copy_assignable::type - deep_swap_alloc_n( A &a, F short_range_f, typename allocator_traits::size_type n_i - , G large_range_f, typename allocator_traits::size_type n_j) -{ - typename allocator_traits::size_type n = 0; - for (; n != n_i ; ++short_range_f, ++large_range_f, ++n){ - boost::container::swap_dispatch(*short_range_f, *large_range_f); - } - boost::container::uninitialized_move_alloc_n(a, large_range_f, n_j - n_i, short_range_f); // may throw - boost::container::destroy_alloc_n(a, large_range_f, n_j - n_i); -} - -static const std::size_t DeepSwapAllocNMaxStorage = std::size_t(1) << std::size_t(11); //2K bytes - -template - -inline typename container_detail::enable_if_c - < container_detail::is_memcpy_copy_assignable::value && (MaxTmpBytes <= DeepSwapAllocNMaxStorage) && false - , void>::type - deep_swap_alloc_n( A &a, F short_range_f, typename allocator_traits::size_type n_i - , G large_range_f, typename allocator_traits::size_type n_j) -{ - typedef typename allocator_traits::value_type value_type; - typedef typename boost::aligned_storage - ::value>::type storage_type; - storage_type storage; - - const std::size_t n_i_bytes = sizeof(value_type)*n_i; - unsigned char *const large_ptr = static_cast(static_cast(container_detail::addressof(*large_range_f))); - unsigned char *const short_ptr = static_cast(static_cast(container_detail::addressof(*short_range_f))); - unsigned char *const stora_ptr = static_cast(static_cast(container_detail::addressof(storage))); - ::memcpy(stora_ptr, large_ptr, n_i_bytes); - ::memcpy(large_ptr, short_ptr, n_i_bytes); - ::memcpy(short_ptr, stora_ptr, n_i_bytes); - std::advance(large_range_f, n_i); - std::advance(short_range_f, n_i); - boost::container::uninitialized_move_alloc_n(a, large_range_f, n_j - n_i, short_range_f); // may throw - boost::container::destroy_alloc_n(a, large_range_f, n_j - n_i); -} - -template - -inline typename container_detail::enable_if_c - < container_detail::is_memcpy_copy_assignable::value && true//(MaxTmpBytes > DeepSwapAllocNMaxStorage) - , void>::type - deep_swap_alloc_n( A &a, F short_range_f, typename allocator_traits::size_type n_i - , G large_range_f, typename allocator_traits::size_type n_j) -{ - typedef typename allocator_traits::value_type value_type; - typedef typename boost::aligned_storage - ::value>::type storage_type; - storage_type storage; - const std::size_t sizeof_storage = sizeof(storage); - - std::size_t n_i_bytes = sizeof(value_type)*n_i; - char *large_ptr = static_cast(static_cast(container_detail::addressof(*large_range_f))); - char *short_ptr = static_cast(static_cast(container_detail::addressof(*short_range_f))); - char *stora_ptr = static_cast(static_cast(container_detail::addressof(storage))); - - std::size_t szt_times = n_i_bytes/sizeof_storage; - const std::size_t szt_rem = n_i_bytes%sizeof_storage; - - //Loop unrolling using Duff's device, as it seems it helps on some architectures - const std::size_t Unroll = 4; - std::size_t n = (szt_times + (Unroll-1))/Unroll; - const std::size_t branch_number = ((!szt_times)*Unroll) + (szt_times % Unroll); - switch(branch_number){ - case 4: - break; - case 0: do{ - ::memcpy(stora_ptr, large_ptr, sizeof_storage); - ::memcpy(large_ptr, short_ptr, sizeof_storage); - ::memcpy(short_ptr, stora_ptr, sizeof_storage); - large_ptr += sizeof_storage; - short_ptr += sizeof_storage; - BOOST_CONTAINER_FALLTHOUGH - case 3: - ::memcpy(stora_ptr, large_ptr, sizeof_storage); - ::memcpy(large_ptr, short_ptr, sizeof_storage); - ::memcpy(short_ptr, stora_ptr, sizeof_storage); - large_ptr += sizeof_storage; - short_ptr += sizeof_storage; - BOOST_CONTAINER_FALLTHOUGH - case 2: - ::memcpy(stora_ptr, large_ptr, sizeof_storage); - ::memcpy(large_ptr, short_ptr, sizeof_storage); - ::memcpy(short_ptr, stora_ptr, sizeof_storage); - large_ptr += sizeof_storage; - short_ptr += sizeof_storage; - BOOST_CONTAINER_FALLTHOUGH - case 1: - ::memcpy(stora_ptr, large_ptr, sizeof_storage); - ::memcpy(large_ptr, short_ptr, sizeof_storage); - ::memcpy(short_ptr, stora_ptr, sizeof_storage); - large_ptr += sizeof_storage; - short_ptr += sizeof_storage; - } while(--n); - } - ::memcpy(stora_ptr, large_ptr, szt_rem); - ::memcpy(large_ptr, short_ptr, szt_rem); - ::memcpy(short_ptr, stora_ptr, szt_rem); - std::advance(large_range_f, n_i); - std::advance(short_range_f, n_i); - boost::container::uninitialized_move_alloc_n(a, large_range_f, n_j - n_i, short_range_f); // may throw - boost::container::destroy_alloc_n(a, large_range_f, n_j - n_i); -} - - -////////////////////////////////////////////////////////////////////////////// -// -// copy_assign_range_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -template - -void copy_assign_range_alloc_n( A &a, I inp_start, typename allocator_traits::size_type n_i - , O out_start, typename allocator_traits::size_type n_o ) -{ - if (n_o < n_i){ - inp_start = boost::container::copy_n_source_dest(inp_start, n_o, out_start); // may throw - boost::container::uninitialized_copy_alloc_n(a, inp_start, n_i - n_o, out_start);// may throw - } - else{ - out_start = boost::container::copy_n(inp_start, n_i, out_start); // may throw - boost::container::destroy_alloc_n(a, out_start, n_o - n_i); - } -} - -////////////////////////////////////////////////////////////////////////////// -// -// move_assign_range_alloc_n -// -////////////////////////////////////////////////////////////////////////////// - -template - -void move_assign_range_alloc_n( A &a, I inp_start, typename allocator_traits::size_type n_i - , O out_start, typename allocator_traits::size_type n_o ) -{ - if (n_o < n_i){ - inp_start = boost::container::move_n_source_dest(inp_start, n_o, out_start); // may throw - boost::container::uninitialized_move_alloc_n(a, inp_start, n_i - n_o, out_start); // may throw - } - else{ - out_start = boost::container::move_n(inp_start, n_i, out_start); // may throw - boost::container::destroy_alloc_n(a, out_start, n_o - n_i); - } -} - -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_UTILITIES_HPP diff --git a/utils/boost_idb/boost/container/detail/value_init.hpp b/utils/boost_idb/boost/container/detail/value_init.hpp deleted file mode 100644 index afe5b15a..00000000 --- a/utils/boost_idb/boost/container/detail/value_init.hpp +++ /dev/null @@ -1,45 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP -#define BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include "config_begin.hpp" -#include - -namespace boost { -namespace container { -namespace container_detail { - -template -struct value_init -{ - value_init() - : m_t() - {} - - operator T &() { return m_t; } - - T m_t; -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP diff --git a/utils/boost_idb/boost/container/detail/version_type.hpp b/utils/boost_idb/boost/container/detail/version_type.hpp deleted file mode 100644 index e47ba26f..00000000 --- a/utils/boost_idb/boost/container/detail/version_type.hpp +++ /dev/null @@ -1,92 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// -// -// This code comes from N1953 document by Howard E. Hinnant -// -////////////////////////////////////////////////////////////////////////////// - - -#ifndef BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP -#define BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP - -#include "config_begin.hpp" - -#include -#include - -namespace boost{ -namespace container { -namespace container_detail { - -//using namespace boost; - -template -struct version_type - : public container_detail::integral_constant -{ - typedef T type; - - version_type(const version_type&); -}; - -namespace impl{ - -template , typename T::version>::value> -struct extract_version -{ - static const unsigned value = 1; -}; - -template -struct extract_version -{ - static const unsigned value = T::version::value; -}; - -template -struct has_version -{ - private: - struct two {char _[2];}; - template static two test(...); - template static char test(const typename U::version*); - public: - static const bool value = sizeof(test(0)) == 1; - void dummy(){} -}; - -template ::value> -struct version -{ - static const unsigned value = 1; -}; - -template -struct version -{ - static const unsigned value = extract_version::value; -}; - -} //namespace impl - -template -struct version - : public container_detail::integral_constant::value> -{ -}; - -} //namespace container_detail { -} //namespace container { -} //namespace boost{ - -#include "config_end.hpp" - -#endif //#define BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP diff --git a/utils/boost_idb/boost/container/detail/workaround.hpp b/utils/boost_idb/boost/container/detail/workaround.hpp deleted file mode 100644 index 49fe284b..00000000 --- a/utils/boost_idb/boost/container/detail/workaround.hpp +++ /dev/null @@ -1,50 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_DETAIL_WORKAROUND_HPP -#define BOOST_CONTAINER_DETAIL_WORKAROUND_HPP - -#include - -#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)\ - && !defined(BOOST_INTERPROCESS_DISABLE_VARIADIC_TMPL) - #define BOOST_CONTAINER_PERFECT_FORWARDING -#endif - -#if defined(BOOST_NO_CXX11_NOEXCEPT) - #if defined(BOOST_MSVC) - #define BOOST_CONTAINER_NOEXCEPT throw() - #else - #define BOOST_CONTAINER_NOEXCEPT - #endif - #define BOOST_CONTAINER_NOEXCEPT_IF(x) -#else - #define BOOST_CONTAINER_NOEXCEPT noexcept - #define BOOST_CONTAINER_NOEXCEPT_IF(x) noexcept(x) -#endif - -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && defined(__GXX_EXPERIMENTAL_CXX0X__)\ - && (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__ < 40700) - #define BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST -#endif - -#if !defined(BOOST_FALLTHOUGH) - #define BOOST_CONTAINER_FALLTHOUGH -#else - #define BOOST_CONTAINER_FALLTHOUGH BOOST_FALLTHOUGH; -#endif - -//Macros for documentation purposes. For code, expands to the argument -#define BOOST_CONTAINER_IMPDEF(TYPE) TYPE -#define BOOST_CONTAINER_SEEDOC(TYPE) TYPE - -#include - -#endif //#ifndef BOOST_CONTAINER_DETAIL_WORKAROUND_HPP diff --git a/utils/boost_idb/boost/container/flat_map.hpp b/utils/boost_idb/boost/container/flat_map.hpp deleted file mode 100644 index 8778de56..00000000 --- a/utils/boost_idb/boost/container/flat_map.hpp +++ /dev/null @@ -1,1705 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_FLAT_MAP_HPP -#define BOOST_CONTAINER_FLAT_MAP_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond -// Forward declarations of operators == and <, needed for friend declarations. -template -class flat_map; - -template -inline bool operator==(const flat_map& x, - const flat_map& y); - -template -inline bool operator<(const flat_map& x, - const flat_map& y); - -namespace container_detail{ - -template -static D &force(const S &s) -{ return *const_cast((reinterpret_cast(&s))); } - -template -static D force_copy(S s) -{ - D *vp = reinterpret_cast(&s); - return D(*vp); -} - -} //namespace container_detail{ - - -/// @endcond - -//! A flat_map is a kind of associative container that supports unique keys (contains at -//! most one of each key value) and provides for fast retrieval of values of another -//! type T based on the keys. The flat_map class supports random-access iterators. -//! -//! A flat_map satisfies all of the requirements of a container and of a reversible -//! container and of an associative container. A flat_map also provides -//! most operations described for unique keys. For a -//! flat_map the key_type is Key and the value_type is std::pair -//! (unlike std::map which value_type is std::pair<const Key, T>). -//! -//! Compare is the ordering function for Keys (e.g. std::less). -//! -//! Allocator is the allocator to allocate the value_types -//! (e.g. allocator< std::pair >). -//! -//! flat_map is similar to std::map but it's implemented like an ordered vector. -//! This means that inserting a new element into a flat_map invalidates -//! previous iterators and references -//! -//! Erasing an element invalidates iterators and references -//! pointing to elements that come after (their keys are bigger) the erased element. -//! -//! This container provides random-access iterators. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator< std::pair< Key, T> > > -#else -template -#endif -class flat_map -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(flat_map) - //This is the tree that we should store if pair was movable - typedef container_detail::flat_tree, - container_detail::select1st< std::pair >, - Compare, - Allocator> tree_t; - - //This is the real tree stored here. It's based on a movable pair - typedef container_detail::flat_tree, - container_detail::select1st >, - Compare, - typename allocator_traits::template portable_rebind_alloc - >::type> impl_tree_t; - impl_tree_t m_flat_tree; // flat tree representing flat_map - - typedef typename impl_tree_t::value_type impl_value_type; - typedef typename impl_tree_t::const_iterator impl_const_iterator; - typedef typename impl_tree_t::allocator_type impl_allocator_type; - typedef container_detail::flat_tree_value_compare - < Compare - , container_detail::select1st< std::pair > - , std::pair > value_compare_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::iterator iterator_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::const_iterator const_iterator_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::reverse_iterator reverse_iterator_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::const_reverse_iterator const_reverse_iterator_impl; - /// @endcond - - public: - - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Key key_type; - typedef T mapped_type; - typedef std::pair value_type; - typedef typename boost::container::allocator_traits::pointer pointer; - typedef typename boost::container::allocator_traits::const_pointer const_pointer; - typedef typename boost::container::allocator_traits::reference reference; - typedef typename boost::container::allocator_traits::const_reference const_reference; - typedef typename boost::container::allocator_traits::size_type size_type; - typedef typename boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef BOOST_CONTAINER_IMPDEF(Allocator) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(value_compare_impl) value_compare; - typedef Compare key_compare; - typedef BOOST_CONTAINER_IMPDEF(iterator_impl) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_iterator_impl) const_iterator; - typedef BOOST_CONTAINER_IMPDEF(reverse_iterator_impl) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(const_reverse_iterator_impl) const_reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(impl_value_type) movable_value_type; - - public: - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs an empty flat_map. - //! - //! Complexity: Constant. - flat_map() - : m_flat_tree() {} - - //! Effects: Constructs an empty flat_map using the specified - //! comparison object and allocator. - //! - //! Complexity: Constant. - explicit flat_map(const Compare& comp, const allocator_type& a = allocator_type()) - : m_flat_tree(comp, container_detail::force(a)) - {} - - //! Effects: Constructs an empty flat_map using the specified allocator. - //! - //! Complexity: Constant. - explicit flat_map(const allocator_type& a) - : m_flat_tree(container_detail::force(a)) - {} - - //! Effects: Constructs an empty flat_map using the specified comparison object and - //! allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - flat_map(InputIterator first, InputIterator last, const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(true, first, last, comp, container_detail::force(a)) - {} - - //! Effects: Constructs an empty flat_map using the specified comparison object and - //! allocator, and inserts elements from the ordered unique range [first ,last). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate and must be - //! unique values. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - flat_map( ordered_unique_range_t, InputIterator first, InputIterator last - , const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_flat_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a flat_map. - //! - //! Complexity: Linear in x.size(). - flat_map(const flat_map& x) - : m_flat_tree(x.m_flat_tree) {} - - //! Effects: Move constructs a flat_map. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - flat_map(BOOST_RV_REF(flat_map) x) - : m_flat_tree(boost::move(x.m_flat_tree)) - {} - - //! Effects: Copy constructs a flat_map using the specified allocator. - //! - //! Complexity: Linear in x.size(). - flat_map(const flat_map& x, const allocator_type &a) - : m_flat_tree(x.m_flat_tree, a) - {} - - //! Effects: Move constructs a flat_map using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if x.get_allocator() == a, linear otherwise. - flat_map(BOOST_RV_REF(flat_map) x, const allocator_type &a) - : m_flat_tree(boost::move(x.m_flat_tree), a) - {} - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - flat_map& operator=(BOOST_COPY_ASSIGN_REF(flat_map) x) - { m_flat_tree = x.m_flat_tree; return *this; } - - //! Effects: Move constructs a flat_map. - //! Constructs *this using x's resources. - //! - //! Complexity: Construct. - //! - //! Postcondition: x is emptied. - flat_map& operator=(BOOST_RV_REF(flat_map) mx) - { m_flat_tree = boost::move(mx.m_flat_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.get_allocator()); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force(m_flat_tree.get_stored_allocator()); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force(m_flat_tree.get_stored_allocator()); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.begin()); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.begin()); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.end()); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.end()); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rbegin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rbegin()); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rend()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rend()); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.cbegin()); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.cend()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.crbegin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.crend()); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.max_size(); } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.capacity(); } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws or T's copy constructor throws. - //! - //! Note: If capacity() is less than "cnt", iterators and references to - //! to values might be invalidated. - void reserve(size_type cnt) - { m_flat_tree.reserve(cnt); } - - //! Effects: Tries to deallocate the excess of memory created - // with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { m_flat_tree.shrink_to_fit(); } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: If there is no key equivalent to x in the flat_map, inserts - //! value_type(x, T()) into the flat_map. - //! - //! Returns: Allocator reference to the mapped_type corresponding to x in *this. - //! - //! Complexity: Logarithmic. - mapped_type &operator[](const key_type& k); - - //! Effects: If there is no key equivalent to x in the flat_map, inserts - //! value_type(move(x), T()) into the flat_map (the key is move-constructed) - //! - //! Returns: Allocator reference to the mapped_type corresponding to x in *this. - //! - //! Complexity: Logarithmic. - mapped_type &operator[](key_type &&k) ; - - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH( operator[] , key_type, mapped_type&, this->priv_subscript) - #endif - - //! Returns: Allocator reference to the element whose key is equivalent to x. - //! - //! Throws: An exception object of type out_of_range if no such element is present. - //! - //! Complexity: logarithmic. - T& at(const key_type& k) - { - iterator i = this->find(k); - if(i == this->end()){ - throw_out_of_range("flat_map::at key not found"); - } - return i->second; - } - - //! Returns: Allocator reference to the element whose key is equivalent to x. - //! - //! Throws: An exception object of type out_of_range if no such element is present. - //! - //! Complexity: logarithmic. - const T& at(const key_type& k) const - { - const_iterator i = this->find(k); - if(i == this->end()){ - throw_out_of_range("flat_map::at key not found"); - } - return i->second; - } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object x of type T constructed with - //! std::forward(args)... if and only if there is no element in the container - //! with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - std::pair emplace(Args&&... args) - { return container_detail::force_copy< std::pair >(m_flat_tree.emplace_unique(boost::forward(args)...)); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the container if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { - return container_detail::force_copy - (m_flat_tree.emplace_hint_unique( container_detail::force_copy(hint) - , boost::forward(args)...)); - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return container_detail::force_copy< std::pair > \ - (m_flat_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return container_detail::force_copy(m_flat_tree.emplace_hint_unique \ - (container_detail::force_copy(hint) \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - //! Effects: Inserts x if and only if there is no element in the container - //! with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - std::pair insert(const value_type& x) - { return container_detail::force_copy >( - m_flat_tree.insert_unique(container_detail::force(x))); } - - //! Effects: Inserts a new value_type move constructed from the pair if and - //! only if there is no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - std::pair insert(BOOST_RV_REF(value_type) x) - { return container_detail::force_copy >( - m_flat_tree.insert_unique(boost::move(container_detail::force(x)))); } - - //! Effects: Inserts a new value_type move constructed from the pair if and - //! only if there is no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - std::pair insert(BOOST_RV_REF(movable_value_type) x) - { - return container_detail::force_copy > - (m_flat_tree.insert_unique(boost::move(x))); - } - - //! Effects: Inserts a copy of x in the container if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, const value_type& x) - { - return container_detail::force_copy( - m_flat_tree.insert_unique( container_detail::force_copy(position) - , container_detail::force(x))); - } - - //! Effects: Inserts an element move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, BOOST_RV_REF(value_type) x) - { - return container_detail::force_copy - (m_flat_tree.insert_unique( container_detail::force_copy(position) - , boost::move(container_detail::force(x)))); - } - - //! Effects: Inserts an element move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, BOOST_RV_REF(movable_value_type) x) - { - return container_detail::force_copy( - m_flat_tree.insert_unique(container_detail::force_copy(position), boost::move(x))); - } - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) if and only - //! if there is no element with key equivalent to the key of that element. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: If an element is inserted it might invalidate elements. - template - void insert(InputIterator first, InputIterator last) - { m_flat_tree.insert_unique(first, last); } - - //! Requires: first, last are not iterators into *this. - //! - //! Requires: [first ,last) must be ordered according to the predicate and must be - //! unique values. - //! - //! Effects: inserts each element from the range [first,last) if and only - //! if there is no element with key equivalent to the key of that element. This - //! function is more efficient than the normal range creation for ordered ranges. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: If an element is inserted it might invalidate elements. - //! - //! Note: Non-standard extension. - template - void insert(ordered_unique_range_t, InputIterator first, InputIterator last) - { m_flat_tree.insert_unique(ordered_unique_range, first, last); } - - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Linear to the elements with keys bigger than position - //! - //! Note: Invalidates elements with keys - //! not less than the erased element. - iterator erase(const_iterator position) - { - return container_detail::force_copy - (m_flat_tree.erase(container_detail::force_copy(position))); - } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - size_type erase(const key_type& x) - { return m_flat_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: size()*N where N is the distance from first to last. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - iterator erase(const_iterator first, const_iterator last) - { - return container_detail::force_copy( - m_flat_tree.erase( container_detail::force_copy(first) - , container_detail::force_copy(last))); - } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(flat_map& x) - { m_flat_tree.swap(x.m_flat_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_flat_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return container_detail::force_copy(m_flat_tree.key_comp()); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return value_compare(container_detail::force_copy(m_flat_tree.key_comp())); } - - ////////////////////////////////////////////// - // - // map operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return container_detail::force_copy(m_flat_tree.find(x)); } - - //! Returns: Allocator const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic.s - const_iterator find(const key_type& x) const - { return container_detail::force_copy(m_flat_tree.find(x)); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return static_cast(m_flat_tree.find(x) != m_flat_tree.end()); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return container_detail::force_copy(m_flat_tree.lower_bound(x)); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return container_detail::force_copy(m_flat_tree.lower_bound(x)); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return container_detail::force_copy(m_flat_tree.upper_bound(x)); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return container_detail::force_copy(m_flat_tree.upper_bound(x)); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } - - /// @cond - template - friend bool operator== (const flat_map&, - const flat_map&); - template - friend bool operator< (const flat_map&, - const flat_map&); - - private: - mapped_type &priv_subscript(const key_type& k) - { - iterator i = lower_bound(k); - // i->first is greater than or equivalent to k. - if (i == end() || key_comp()(k, (*i).first)){ - container_detail::value_init m; - i = insert(i, impl_value_type(k, ::boost::move(m.m_t))); - } - return (*i).second; - } - mapped_type &priv_subscript(BOOST_RV_REF(key_type) mk) - { - key_type &k = mk; - iterator i = lower_bound(k); - // i->first is greater than or equivalent to k. - if (i == end() || key_comp()(k, (*i).first)){ - container_detail::value_init m; - i = insert(i, impl_value_type(boost::move(k), ::boost::move(m.m_t))); - } - return (*i).second; - } - /// @endcond -}; - -template -inline bool operator==(const flat_map& x, - const flat_map& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_map& x, - const flat_map& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_map& x, - const flat_map& y) - { return !(x == y); } - -template -inline bool operator>(const flat_map& x, - const flat_map& y) - { return y < x; } - -template -inline bool operator<=(const flat_map& x, - const flat_map& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_map& x, - const flat_map& y) - { return !(x < y); } - -template -inline void swap(flat_map& x, - flat_map& y) - { x.swap(y); } - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -namespace container { - -// Forward declaration of operators < and ==, needed for friend declaration. -template -class flat_multimap; - -template -inline bool operator==(const flat_multimap& x, - const flat_multimap& y); - -template -inline bool operator<(const flat_multimap& x, - const flat_multimap& y); -/// @endcond - -//! A flat_multimap is a kind of associative container that supports equivalent keys -//! (possibly containing multiple copies of the same key value) and provides for -//! fast retrieval of values of another type T based on the keys. The flat_multimap -//! class supports random-access iterators. -//! -//! A flat_multimap satisfies all of the requirements of a container and of a reversible -//! container and of an associative container. For a -//! flat_multimap the key_type is Key and the value_type is std::pair -//! (unlike std::multimap which value_type is std::pair<const Key, T>). -//! -//! Compare is the ordering function for Keys (e.g. std::less). -//! -//! Allocator is the allocator to allocate the value_types -//! (e.g. allocator< std::pair >). -//! -//! flat_multimap is similar to std::multimap but it's implemented like an ordered vector. -//! This means that inserting a new element into a flat_map invalidates -//! previous iterators and references -//! -//! Erasing an element invalidates iterators and references -//! pointing to elements that come after (their keys are bigger) the erased element. -//! -//! This container provides random-access iterators. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator< std::pair< Key, T> > > -#else -template -#endif -class flat_multimap -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(flat_multimap) - typedef container_detail::flat_tree, - container_detail::select1st< std::pair >, - Compare, - Allocator> tree_t; - //This is the real tree stored here. It's based on a movable pair - typedef container_detail::flat_tree, - container_detail::select1st >, - Compare, - typename allocator_traits::template portable_rebind_alloc - >::type> impl_tree_t; - impl_tree_t m_flat_tree; // flat tree representing flat_map - - typedef typename impl_tree_t::value_type impl_value_type; - typedef typename impl_tree_t::const_iterator impl_const_iterator; - typedef typename impl_tree_t::allocator_type impl_allocator_type; - typedef container_detail::flat_tree_value_compare - < Compare - , container_detail::select1st< std::pair > - , std::pair > value_compare_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::iterator iterator_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::const_iterator const_iterator_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::reverse_iterator reverse_iterator_impl; - typedef typename container_detail::get_flat_tree_iterators - ::pointer>::const_reverse_iterator const_reverse_iterator_impl; - /// @endcond - - public: - - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Key key_type; - typedef T mapped_type; - typedef std::pair value_type; - typedef typename boost::container::allocator_traits::pointer pointer; - typedef typename boost::container::allocator_traits::const_pointer const_pointer; - typedef typename boost::container::allocator_traits::reference reference; - typedef typename boost::container::allocator_traits::const_reference const_reference; - typedef typename boost::container::allocator_traits::size_type size_type; - typedef typename boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef BOOST_CONTAINER_IMPDEF(Allocator) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(value_compare_impl) value_compare; - typedef Compare key_compare; - typedef BOOST_CONTAINER_IMPDEF(iterator_impl) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_iterator_impl) const_iterator; - typedef BOOST_CONTAINER_IMPDEF(reverse_iterator_impl) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(const_reverse_iterator_impl) const_reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(impl_value_type) movable_value_type; - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs an empty flat_map. - //! - //! Complexity: Constant. - flat_multimap() - : m_flat_tree() {} - - //! Effects: Constructs an empty flat_multimap using the specified comparison - //! object and allocator. - //! - //! Complexity: Constant. - explicit flat_multimap(const Compare& comp, - const allocator_type& a = allocator_type()) - : m_flat_tree(comp, container_detail::force(a)) - {} - - //! Effects: Constructs an empty flat_multimap using the specified allocator. - //! - //! Complexity: Constant. - explicit flat_multimap(const allocator_type& a) - : m_flat_tree(container_detail::force(a)) - {} - - //! Effects: Constructs an empty flat_multimap using the specified comparison object - //! and allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - flat_multimap(InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(false, first, last, comp, container_detail::force(a)) - {} - - //! Effects: Constructs an empty flat_multimap using the specified comparison object and - //! allocator, and inserts elements from the ordered range [first ,last). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - flat_multimap(ordered_range_t, InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a flat_multimap. - //! - //! Complexity: Linear in x.size(). - flat_multimap(const flat_multimap& x) - : m_flat_tree(x.m_flat_tree) { } - - //! Effects: Move constructs a flat_multimap. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - flat_multimap(BOOST_RV_REF(flat_multimap) x) - : m_flat_tree(boost::move(x.m_flat_tree)) - {} - - //! Effects: Copy constructs a flat_multimap using the specified allocator. - //! - //! Complexity: Linear in x.size(). - flat_multimap(const flat_multimap& x, const allocator_type &a) - : m_flat_tree(x.m_flat_tree, a) - {} - - //! Effects: Move constructs a flat_multimap using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - flat_multimap(BOOST_RV_REF(flat_multimap) x, const allocator_type &a) - : m_flat_tree(boost::move(x.m_flat_tree), a) - { } - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - flat_multimap& operator=(BOOST_COPY_ASSIGN_REF(flat_multimap) x) - { m_flat_tree = x.m_flat_tree; return *this; } - - //! Effects: this->swap(x.get()). - //! - //! Complexity: Constant. - flat_multimap& operator=(BOOST_RV_REF(flat_multimap) mx) - { m_flat_tree = boost::move(mx.m_flat_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.get_allocator()); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force(m_flat_tree.get_stored_allocator()); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force(m_flat_tree.get_stored_allocator()); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.begin()); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.begin()); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.end()); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.end()); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rbegin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rbegin()); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rend()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.rend()); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.cbegin()); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.cend()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.crbegin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::force_copy(m_flat_tree.crend()); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.max_size(); } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.capacity(); } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws or T's copy constructor throws. - //! - //! Note: If capacity() is less than "cnt", iterators and references to - //! to values might be invalidated. - void reserve(size_type cnt) - { m_flat_tree.reserve(cnt); } - - //! Effects: Tries to deallocate the excess of memory created - // with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { m_flat_tree.shrink_to_fit(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - iterator emplace(Args&&... args) - { return container_detail::force_copy(m_flat_tree.emplace_equal(boost::forward(args)...)); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant time if the value - //! is to be inserted before p) plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { - return container_detail::force_copy(m_flat_tree.emplace_hint_equal - (container_detail::force_copy(hint), boost::forward(args)...)); - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return container_detail::force_copy(m_flat_tree.emplace_equal \ - (BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return container_detail::force_copy(m_flat_tree.emplace_hint_equal \ - (container_detail::force_copy(hint) \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - //! Effects: Inserts x and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const value_type& x) - { - return container_detail::force_copy( - m_flat_tree.insert_equal(container_detail::force(x))); - } - - //! Effects: Inserts a new value move-constructed from x and returns - //! the iterator pointing to the newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(BOOST_RV_REF(value_type) x) - { return container_detail::force_copy(m_flat_tree.insert_equal(boost::move(x))); } - - //! Effects: Inserts a new value move-constructed from x and returns - //! the iterator pointing to the newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(BOOST_RV_REF(impl_value_type) x) - { return container_detail::force_copy(m_flat_tree.insert_equal(boost::move(x))); } - - //! Effects: Inserts a copy of x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant time if the value - //! is to be inserted before p) plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, const value_type& x) - { - return container_detail::force_copy - (m_flat_tree.insert_equal( container_detail::force_copy(position) - , container_detail::force(x))); - } - - //! Effects: Inserts a value move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant time if the value - //! is to be inserted before p) plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, BOOST_RV_REF(value_type) x) - { - return container_detail::force_copy - (m_flat_tree.insert_equal(container_detail::force_copy(position) - , boost::move(x))); - } - - //! Effects: Inserts a value move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant time if the value - //! is to be inserted before p) plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, BOOST_RV_REF(impl_value_type) x) - { - return container_detail::force_copy( - m_flat_tree.insert_equal(container_detail::force_copy(position), boost::move(x))); - } - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) . - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: If an element is inserted it might invalidate elements. - template - void insert(InputIterator first, InputIterator last) - { m_flat_tree.insert_equal(first, last); } - - //! Requires: first, last are not iterators into *this. - //! - //! Requires: [first ,last) must be ordered according to the predicate. - //! - //! Effects: inserts each element from the range [first,last) if and only - //! if there is no element with key equivalent to the key of that element. This - //! function is more efficient than the normal range creation for ordered ranges. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: If an element is inserted it might invalidate elements. - //! - //! Note: Non-standard extension. - template - void insert(ordered_range_t, InputIterator first, InputIterator last) - { m_flat_tree.insert_equal(ordered_range, first, last); } - - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Linear to the elements with keys bigger than position - //! - //! Note: Invalidates elements with keys - //! not less than the erased element. - iterator erase(const_iterator position) - { - return container_detail::force_copy( - m_flat_tree.erase(container_detail::force_copy(position))); - } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - size_type erase(const key_type& x) - { return m_flat_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: size()*N where N is the distance from first to last. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - iterator erase(const_iterator first, const_iterator last) - { - return container_detail::force_copy - (m_flat_tree.erase( container_detail::force_copy(first) - , container_detail::force_copy(last))); - } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(flat_multimap& x) - { m_flat_tree.swap(x.m_flat_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_flat_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return container_detail::force_copy(m_flat_tree.key_comp()); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return value_compare(container_detail::force_copy(m_flat_tree.key_comp())); } - - ////////////////////////////////////////////// - // - // map operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return container_detail::force_copy(m_flat_tree.find(x)); } - - //! Returns: An const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return container_detail::force_copy(m_flat_tree.find(x)); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_flat_tree.count(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return container_detail::force_copy(m_flat_tree.lower_bound(x)); } - - //! Returns: Allocator const iterator pointing to the first element with key - //! not less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return container_detail::force_copy(m_flat_tree.lower_bound(x)); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - {return container_detail::force_copy(m_flat_tree.upper_bound(x)); } - - //! Returns: Allocator const iterator pointing to the first element with key - //! not less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return container_detail::force_copy(m_flat_tree.upper_bound(x)); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } - - /// @cond - template - friend bool operator== (const flat_multimap& x, - const flat_multimap& y); - - template - friend bool operator< (const flat_multimap& x, - const flat_multimap& y); - /// @endcond -}; - -template -inline bool operator==(const flat_multimap& x, - const flat_multimap& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_multimap& x, - const flat_multimap& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_multimap& x, - const flat_multimap& y) - { return !(x == y); } - -template -inline bool operator>(const flat_multimap& x, - const flat_multimap& y) - { return y < x; } - -template -inline bool operator<=(const flat_multimap& x, - const flat_multimap& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_multimap& x, - const flat_multimap& y) - { return !(x < y); } - -template -inline void swap(flat_multimap& x, flat_multimap& y) - { x.swap(y); } - -}} - -/// @cond - -namespace boost { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move< boost::container::flat_multimap > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -} //namespace boost { - -/// @endcond - -#include - -#endif /* BOOST_CONTAINER_FLAT_MAP_HPP */ diff --git a/utils/boost_idb/boost/container/flat_set.hpp b/utils/boost_idb/boost/container/flat_set.hpp deleted file mode 100644 index eda8fbda..00000000 --- a/utils/boost_idb/boost/container/flat_set.hpp +++ /dev/null @@ -1,1428 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_FLAT_SET_HPP -#define BOOST_CONTAINER_FLAT_SET_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond -// Forward declarations of operators < and ==, needed for friend declaration. - -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class flat_set; - -template -inline bool operator==(const flat_set& x, - const flat_set& y); - -template -inline bool operator<(const flat_set& x, - const flat_set& y); -/// @endcond - -//! flat_set is a Sorted Associative Container that stores objects of type Key. -//! It is also a Unique Associative Container, meaning that no two elements are the same. -//! -//! flat_set is similar to std::set but it's implemented like an ordered vector. -//! This means that inserting a new element into a flat_set invalidates -//! previous iterators and references -//! -//! Erasing an element of a flat_set invalidates iterators and references -//! pointing to elements that come after (their keys are bigger) the erased element. -//! -//! This container provides random-access iterators. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class flat_set -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(flat_set) - typedef container_detail::flat_tree, Compare, Allocator> tree_t; - tree_t m_flat_tree; // flat tree representing flat_set - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Key key_type; - typedef Key value_type; - typedef Compare key_compare; - typedef Compare value_compare; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; - - public: - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs an empty flat_set. - //! - //! Complexity: Constant. - explicit flat_set() - : m_flat_tree() - {} - - //! Effects: Constructs an empty flat_set using the specified - //! comparison object and allocator. - //! - //! Complexity: Constant. - explicit flat_set(const Compare& comp, - const allocator_type& a = allocator_type()) - : m_flat_tree(comp, a) - {} - - //! Effects: Constructs an empty flat_set using the specified allocator. - //! - //! Complexity: Constant. - explicit flat_set(const allocator_type& a) - : m_flat_tree(a) - {} - - //! Effects: Constructs an empty set using the specified comparison object and - //! allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - flat_set(InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(true, first, last, comp, a) - {} - - //! Effects: Constructs an empty flat_set using the specified comparison object and - //! allocator, and inserts elements from the ordered unique range [first ,last). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate and must be - //! unique values. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a set. - //! - //! Complexity: Linear in x.size(). - flat_set(const flat_set& x) - : m_flat_tree(x.m_flat_tree) - {} - - //! Effects: Move constructs a set. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - flat_set(BOOST_RV_REF(flat_set) mx) - : m_flat_tree(boost::move(mx.m_flat_tree)) - {} - - //! Effects: Copy constructs a set using the specified allocator. - //! - //! Complexity: Linear in x.size(). - flat_set(const flat_set& x, const allocator_type &a) - : m_flat_tree(x.m_flat_tree, a) - {} - - //! Effects: Move constructs a set using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == mx.get_allocator(), linear otherwise - flat_set(BOOST_RV_REF(flat_set) mx, const allocator_type &a) - : m_flat_tree(boost::move(mx.m_flat_tree), a) - {} - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - flat_set& operator=(BOOST_COPY_ASSIGN_REF(flat_set) x) - { m_flat_tree = x.m_flat_tree; return *this; } - - //! Effects: Makes *this a copy of the previous value of xx. - //! - //! Complexity: Linear in x.size(). - flat_set& operator=(BOOST_RV_REF(flat_set) mx) - { m_flat_tree = boost::move(mx.m_flat_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.begin(); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cbegin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crend(); } - - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.max_size(); } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.capacity(); } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws or Key's copy constructor throws. - //! - //! Note: If capacity() is less than "cnt", iterators and references to - //! to values might be invalidated. - void reserve(size_type cnt) - { m_flat_tree.reserve(cnt); } - - //! Effects: Tries to deallocate the excess of memory created - // with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or Key's copy constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { m_flat_tree.shrink_to_fit(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object x of type Key constructed with - //! std::forward(args)... if and only if there is no element in the container - //! with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - std::pair emplace(Args&&... args) - { return m_flat_tree.emplace_unique(boost::forward(args)...); } - - //! Effects: Inserts an object of type Key constructed with - //! std::forward(args)... in the container if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_flat_tree.emplace_hint_unique(hint, boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_hint_unique \ - (hint BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts x if and only if there is no element in the container - //! with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - std::pair insert(const value_type &x); - - //! Effects: Inserts a new value_type move constructed from the pair if and - //! only if there is no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - std::pair insert(value_type &&x); - #else - private: - typedef std::pair insert_return_pair; - public: - BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, insert_return_pair, this->priv_insert) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x in the container if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator p, const value_type &x); - - //! Effects: Inserts an element move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, value_type &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) if and only - //! if there is no element with key equivalent to the key of that element. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: If an element is inserted it might invalidate elements. - template - void insert(InputIterator first, InputIterator last) - { m_flat_tree.insert_unique(first, last); } - - //! Requires: first, last are not iterators into *this and - //! must be ordered according to the predicate and must be - //! unique values. - //! - //! Effects: inserts each element from the range [first,last) .This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: Non-standard extension. If an element is inserted it might invalidate elements. - template - void insert(ordered_unique_range_t, InputIterator first, InputIterator last) - { m_flat_tree.insert_unique(ordered_unique_range, first, last); } - - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Linear to the elements with keys bigger than position - //! - //! Note: Invalidates elements with keys - //! not less than the erased element. - iterator erase(const_iterator position) - { return m_flat_tree.erase(position); } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - size_type erase(const key_type& x) - { return m_flat_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: size()*N where N is the distance from first to last. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - iterator erase(const_iterator first, const_iterator last) - { return m_flat_tree.erase(first, last); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(flat_set& x) - { m_flat_tree.swap(x.m_flat_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_flat_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_flat_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return m_flat_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_flat_tree.find(x); } - - //! Returns: Allocator const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic.s - const_iterator find(const key_type& x) const - { return m_flat_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return static_cast(m_flat_tree.find(x) != m_flat_tree.end()); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_flat_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_flat_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_flat_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_flat_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_flat_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_flat_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const flat_set&, const flat_set&); - - template - friend bool operator< (const flat_set&, const flat_set&); - - private: - template - std::pair priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_unique(::boost::forward(x)); } - - template - iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_unique(p, ::boost::forward(x)); } - /// @endcond -}; - -template -inline bool operator==(const flat_set& x, - const flat_set& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_set& x, - const flat_set& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_set& x, - const flat_set& y) - { return !(x == y); } - -template -inline bool operator>(const flat_set& x, - const flat_set& y) - { return y < x; } - -template -inline bool operator<=(const flat_set& x, - const flat_set& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_set& x, - const flat_set& y) - { return !(x < y); } - -template -inline void swap(flat_set& x, flat_set& y) - { x.swap(y); } - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value &&has_trivial_destructor_after_move::value; -}; - -namespace container { - -// Forward declaration of operators < and ==, needed for friend declaration. - -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class flat_multiset; - -template -inline bool operator==(const flat_multiset& x, - const flat_multiset& y); - -template -inline bool operator<(const flat_multiset& x, - const flat_multiset& y); -/// @endcond - -//! flat_multiset is a Sorted Associative Container that stores objects of type Key. -//! -//! flat_multiset can store multiple copies of the same key value. -//! -//! flat_multiset is similar to std::multiset but it's implemented like an ordered vector. -//! This means that inserting a new element into a flat_multiset invalidates -//! previous iterators and references -//! -//! Erasing an element invalidates iterators and references -//! pointing to elements that come after (their keys are bigger) the erased element. -//! -//! This container provides random-access iterators. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class flat_multiset -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(flat_multiset) - typedef container_detail::flat_tree, Compare, Allocator> tree_t; - tree_t m_flat_tree; // flat tree representing flat_multiset - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Key key_type; - typedef Key value_type; - typedef Compare key_compare; - typedef Compare value_compare; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; - - //! Effects: Default constructs an empty flat_multiset. - //! - //! Complexity: Constant. - explicit flat_multiset() - : m_flat_tree() - {} - - //! Effects: Constructs an empty flat_multiset using the specified - //! comparison object and allocator. - //! - //! Complexity: Constant. - explicit flat_multiset(const Compare& comp, - const allocator_type& a = allocator_type()) - : m_flat_tree(comp, a) - {} - - //! Effects: Constructs an empty flat_multiset using the specified allocator. - //! - //! Complexity: Constant. - explicit flat_multiset(const allocator_type& a) - : m_flat_tree(a) - {} - - template - flat_multiset(InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(false, first, last, comp, a) - {} - - //! Effects: Constructs an empty flat_multiset using the specified comparison object and - //! allocator, and inserts elements from the ordered range [first ,last ). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - flat_multiset(ordered_range_t, InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_flat_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a flat_multiset. - //! - //! Complexity: Linear in x.size(). - flat_multiset(const flat_multiset& x) - : m_flat_tree(x.m_flat_tree) - {} - - //! Effects: Move constructs a flat_multiset. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - flat_multiset(BOOST_RV_REF(flat_multiset) mx) - : m_flat_tree(boost::move(mx.m_flat_tree)) - {} - - //! Effects: Copy constructs a flat_multiset using the specified allocator. - //! - //! Complexity: Linear in x.size(). - flat_multiset(const flat_multiset& x, const allocator_type &a) - : m_flat_tree(x.m_flat_tree, a) - {} - - //! Effects: Move constructs a flat_multiset using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == mx.get_allocator(), linear otherwise - flat_multiset(BOOST_RV_REF(flat_multiset) mx, const allocator_type &a) - : m_flat_tree(boost::move(mx.m_flat_tree), a) - {} - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - flat_multiset& operator=(BOOST_COPY_ASSIGN_REF(flat_multiset) x) - { m_flat_tree = x.m_flat_tree; return *this; } - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - flat_multiset& operator=(BOOST_RV_REF(flat_multiset) mx) - { m_flat_tree = boost::move(mx.m_flat_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const - { return m_flat_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cbegin(); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cend(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.max_size(); } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.capacity(); } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws or Key's copy constructor throws. - //! - //! Note: If capacity() is less than "cnt", iterators and references to - //! to values might be invalidated. - void reserve(size_type cnt) - { m_flat_tree.reserve(cnt); } - - //! Effects: Tries to deallocate the excess of memory created - // with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or Key's copy constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { m_flat_tree.shrink_to_fit(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type Key constructed with - //! std::forward(args)... and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - iterator emplace(Args&&... args) - { return m_flat_tree.emplace_equal(boost::forward(args)...); } - - //! Effects: Inserts an object of type Key constructed with - //! std::forward(args)... in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_flat_tree.emplace_hint_equal(hint, boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_hint_equal \ - (hint BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts x and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const value_type &x); - - //! Effects: Inserts a new value_type move constructed from x - //! and returns the iterator pointing to the newly inserted element. - //! - //! Complexity: Logarithmic search time plus linear insertion - //! to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(value_type &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, iterator, this->priv_insert) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator p, const value_type &x); - - //! Effects: Inserts a new value move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic search time (constant if x is inserted - //! right before p) plus insertion linear to the elements with bigger keys than x. - //! - //! Note: If an element is inserted it might invalidate elements. - iterator insert(const_iterator position, value_type &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) . - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: If an element is inserted it might invalidate elements. - template - void insert(InputIterator first, InputIterator last) - { m_flat_tree.insert_equal(first, last); } - - //! Requires: first, last are not iterators into *this and - //! must be ordered according to the predicate. - //! - //! Effects: inserts each element from the range [first,last) .This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - //! search time plus N*size() insertion time. - //! - //! Note: Non-standard extension. If an element is inserted it might invalidate elements. - template - void insert(ordered_range_t, InputIterator first, InputIterator last) - { m_flat_tree.insert_equal(ordered_range, first, last); } - - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Linear to the elements with keys bigger than position - //! - //! Note: Invalidates elements with keys - //! not less than the erased element. - iterator erase(const_iterator position) - { return m_flat_tree.erase(position); } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - size_type erase(const key_type& x) - { return m_flat_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: size()*N where N is the distance from first to last. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - iterator erase(const_iterator first, const_iterator last) - { return m_flat_tree.erase(first, last); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(flat_multiset& x) - { m_flat_tree.swap(x.m_flat_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_flat_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_flat_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return m_flat_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_flat_tree.find(x); } - - //! Returns: Allocator const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic.s - const_iterator find(const key_type& x) const - { return m_flat_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_flat_tree.count(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_flat_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_flat_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_flat_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_flat_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_flat_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_flat_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const flat_multiset&, - const flat_multiset&); - template - friend bool operator< (const flat_multiset&, - const flat_multiset&); - private: - template - iterator priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_equal(::boost::forward(x)); } - - template - iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_equal(p, ::boost::forward(x)); } - /// @endcond -}; - -template -inline bool operator==(const flat_multiset& x, - const flat_multiset& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_multiset& x, - const flat_multiset& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_multiset& x, - const flat_multiset& y) - { return !(x == y); } - -template -inline bool operator>(const flat_multiset& x, - const flat_multiset& y) - { return y < x; } - -template -inline bool operator<=(const flat_multiset& x, - const flat_multiset& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_multiset& x, - const flat_multiset& y) -{ return !(x < y); } - -template -inline void swap(flat_multiset& x, flat_multiset& y) - { x.swap(y); } - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -namespace container { - -/// @endcond - -}} - -#include - -#endif /* BOOST_CONTAINER_FLAT_SET_HPP */ diff --git a/utils/boost_idb/boost/container/list.hpp b/utils/boost_idb/boost/container/list.hpp deleted file mode 100644 index 8ebd5be5..00000000 --- a/utils/boost_idb/boost/container/list.hpp +++ /dev/null @@ -1,1384 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// - -#ifndef BOOST_CONTAINER_LIST_HPP -#define BOOST_CONTAINER_LIST_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) -#else -//Preprocessor library to emulate perfect forwarding -#include -#endif - -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond -namespace container_detail { - -template -struct list_hook -{ - typedef typename container_detail::bi::make_list_base_hook - , container_detail::bi::link_mode >::type type; -}; - -template -struct list_node - : public list_hook::type -{ - private: - list_node(); - - public: - typedef T value_type; - typedef typename list_hook::type hook_type; - - T m_data; - - T &get_data() - { return this->m_data; } - - const T &get_data() const - { return this->m_data; } -}; - -template -struct intrusive_list_type -{ - typedef boost::container::allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::value_type value_type; - typedef typename boost::intrusive::pointer_traits - ::template - rebind_pointer::type - void_pointer; - typedef typename container_detail::list_node - node_type; - typedef typename container_detail::bi::make_list - < node_type - , container_detail::bi::base_hook::type> - , container_detail::bi::constant_time_size - , container_detail::bi::size_type - - >::type container_type; - typedef container_type type ; -}; - -} //namespace container_detail { -/// @endcond - -//! A list is a doubly linked list. That is, it is a Sequence that supports both -//! forward and backward traversal, and (amortized) constant time insertion and -//! removal of elements at the beginning or the end, or in the middle. Lists have -//! the important property that insertion and splicing do not invalidate iterators -//! to list elements, and that even removal invalidates only the iterators that point -//! to the elements that are removed. The ordering of iterators may be changed -//! (that is, list::iterator might have a different predecessor or successor -//! after a list operation than it did before), but the iterators themselves will -//! not be invalidated or made to point to different elements unless that invalidation -//! or mutation is explicit. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else -template -#endif -class list - : protected container_detail::node_alloc_holder - ::type> -{ - /// @cond - typedef typename - container_detail::intrusive_list_type::type Icont; - typedef container_detail::node_alloc_holder AllocHolder; - typedef typename AllocHolder::NodePtr NodePtr; - typedef typename AllocHolder::NodeAlloc NodeAlloc; - typedef typename AllocHolder::ValAlloc ValAlloc; - typedef typename AllocHolder::Node Node; - typedef container_detail::allocator_destroyer Destroyer; - typedef typename AllocHolder::allocator_v1 allocator_v1; - typedef typename AllocHolder::allocator_v2 allocator_v2; - typedef typename AllocHolder::alloc_version alloc_version; - typedef boost::container::allocator_traits allocator_traits_type; - - class equal_to_value - { - typedef typename AllocHolder::value_type value_type; - const value_type &t_; - - public: - equal_to_value(const value_type &t) - : t_(t) - {} - - bool operator()(const value_type &t)const - { return t_ == t; } - }; - - template - struct ValueCompareToNodeCompare - : Pred - { - ValueCompareToNodeCompare(Pred pred) - : Pred(pred) - {} - - bool operator()(const Node &a, const Node &b) const - { return static_cast(*this)(a.m_data, b.m_data); } - - bool operator()(const Node &a) const - { return static_cast(*this)(a.m_data); } - }; - - BOOST_COPYABLE_AND_MOVABLE(list) - - typedef container_detail::iterator iterator_impl; - typedef container_detail::iterator const_iterator_impl; - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - - typedef T value_type; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef BOOST_CONTAINER_IMPDEF(NodeAlloc) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(iterator_impl) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_iterator_impl) const_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs a list. - //! - //! Throws: If allocator_type's default constructor throws. - //! - //! Complexity: Constant. - list() - : AllocHolder() - {} - - //! Effects: Constructs a list taking the allocator as parameter. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - explicit list(const allocator_type &a) BOOST_CONTAINER_NOEXCEPT - : AllocHolder(a) - {} - - //! Effects: Constructs a list that will use a copy of allocator a - //! and inserts n copies of value. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - explicit list(size_type n) - : AllocHolder(Allocator()) - { this->resize(n); } - - //! Effects: Constructs a list that will use a copy of allocator a - //! and inserts n copies of value. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - list(size_type n, const T& value, const Allocator& a = Allocator()) - : AllocHolder(a) - { this->insert(this->cbegin(), n, value); } - - //! Effects: Copy constructs a list. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocator_type's default constructor or copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - list(const list& x) - : AllocHolder(x) - { this->insert(this->cbegin(), x.begin(), x.end()); } - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - list(BOOST_RV_REF(list) x) - : AllocHolder(boost::move(static_cast(x))) - {} - - //! Effects: Copy constructs a list using the specified allocator. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocator_type's default constructor or copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - list(const list& x, const allocator_type &a) - : AllocHolder(a) - { this->insert(this->cbegin(), x.begin(), x.end()); } - - //! Effects: Move constructor sing the specified allocator. - //! Moves mx's resources to *this. - //! - //! Throws: If allocation or value_type's copy constructor throws. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - list(BOOST_RV_REF(list) x, const allocator_type &a) - : AllocHolder(a) - { - if(this->node_alloc() == x.node_alloc()){ - this->icont().swap(x.icont()); - } - else{ - this->insert(this->cbegin(), x.begin(), x.end()); - } - } - - //! Effects: Constructs a list that will use a copy of allocator a - //! and inserts a copy of the range [first, last) in the list. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's constructor taking an dereferenced InIt throws. - //! - //! Complexity: Linear to the range [first, last). - template - list(InpIt first, InpIt last, const Allocator &a = Allocator()) - : AllocHolder(a) - { this->insert(this->cbegin(), first, last); } - - //! Effects: Destroys the list. All stored values are destroyed - //! and used memory is deallocated. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements. - ~list() BOOST_CONTAINER_NOEXCEPT - {} //AllocHolder clears the list - - //! Effects: Makes *this contain the same elements as x. - //! - //! Postcondition: this->size() == x.size(). *this contains a copy - //! of each of x's elements. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to the number of elements in x. - list& operator=(BOOST_COPY_ASSIGN_REF(list) x) - { - if (&x != this){ - NodeAlloc &this_alloc = this->node_alloc(); - const NodeAlloc &x_alloc = x.node_alloc(); - container_detail::bool_ flag; - if(flag && this_alloc != x_alloc){ - this->clear(); - } - this->AllocHolder::copy_assign_alloc(x); - this->assign(x.begin(), x.end()); - } - return *this; - } - - //! Effects: Move assignment. All mx's values are transferred to *this. - //! - //! Postcondition: x.empty(). *this contains a the elements x had - //! before the function. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - list& operator=(BOOST_RV_REF(list) x) - { - if (&x != this){ - NodeAlloc &this_alloc = this->node_alloc(); - NodeAlloc &x_alloc = x.node_alloc(); - //If allocators are equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy and swap pointers - this->clear(); - this->icont() = boost::move(x.icont()); - //Move allocator if needed - this->AllocHolder::move_assign_alloc(x); - } - //If unequal allocators, then do a one by one move - else{ - this->assign( boost::make_move_iterator(x.begin()) - , boost::make_move_iterator(x.end())); - } - } - return *this; - } - - //! Effects: Assigns the n copies of val to *this. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - void assign(size_type n, const T& val) - { - typedef constant_iterator cvalue_iterator; - return this->assign(cvalue_iterator(val, n), cvalue_iterator()); - } - - //! Effects: Assigns the the range [first, last) to *this. - //! - //! Throws: If memory allocation throws or - //! T's constructor from dereferencing InpIt throws. - //! - //! Complexity: Linear to n. - template - void assign(InpIt first, InpIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - >::type * = 0 - #endif - ) - { - iterator first1 = this->begin(); - const iterator last1 = this->end(); - for ( ; first1 != last1 && first != last; ++first1, ++first) - *first1 = *first; - if (first == last) - this->erase(first1, last1); - else{ - this->insert(last1, first, last); - } - } - - //! Effects: Returns a copy of the internal allocator. - //! - //! Throws: If allocator's copy constructor throws. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return allocator_type(this->node_alloc()); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return this->node_alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->node_alloc(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->icont().begin()); } - - //! Effects: Returns a const_iterator to the first element contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbegin(); } - - //! Effects: Returns an iterator to the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->icont().end()); } - - //! Effects: Returns a const_iterator to the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(end()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(begin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->non_const_icont().begin()); } - - //! Effects: Returns a const_iterator to the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->non_const_icont().end()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->cend()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->cbegin()); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the list contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return !this->size(); } - - //! Effects: Returns the number of the elements contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return this->icont().size(); } - - //! Effects: Returns the largest possible size of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return AllocHolder::max_size(); } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size) - { - if(!priv_try_shrink(new_size)){ - typedef value_init_construct_iterator value_init_iterator; - this->insert(this->cend(), value_init_iterator(new_size - this->size()), value_init_iterator()); - } - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are copy constructed from x. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size, const T& x) - { - if(!priv_try_shrink(new_size)){ - this->insert(this->cend(), new_size - this->size(), x); - } - } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference front() BOOST_CONTAINER_NOEXCEPT - { return *this->begin(); } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference front() const BOOST_CONTAINER_NOEXCEPT - { return *this->begin(); } - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference back() BOOST_CONTAINER_NOEXCEPT - { return *(--this->end()); } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference back() const BOOST_CONTAINER_NOEXCEPT - { return *(--this->end()); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the end of the list. - //! - //! Throws: If memory allocation throws or - //! T's in-place constructor throws. - //! - //! Complexity: Constant - template - void emplace_back(Args&&... args) - { this->emplace(this->cend(), boost::forward(args)...); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the beginning of the list. - //! - //! Throws: If memory allocation throws or - //! T's in-place constructor throws. - //! - //! Complexity: Constant - template - void emplace_front(Args&&... args) - { this->emplace(this->cbegin(), boost::forward(args)...); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... before p. - //! - //! Throws: If memory allocation throws or - //! T's in-place constructor throws. - //! - //! Complexity: Constant - template - iterator emplace(const_iterator p, Args&&... args) - { - NodePtr pnode(AllocHolder::create_node(boost::forward(args)...)); - return iterator(this->icont().insert(p.get(), *pnode)); - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - this->emplace(this->cend() \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - void emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - this->emplace(this->cbegin() \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(const_iterator p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - NodePtr pnode (AllocHolder::create_node \ - (BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ - return iterator(this->icont().insert(p.get(), *pnode)); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the beginning of the list. - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - void push_front(const T &x); - - //! Effects: Constructs a new element in the beginning of the list - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - void push_front(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_front, T, void, priv_push_front) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the end of the list. - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - void push_back(const T &x); - - //! Effects: Constructs a new element in the end of the list - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - void push_back(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_back, T, void, priv_push_back) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a copy of x before position. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws or x's copy constructor throws. - //! - //! Complexity: Amortized constant time. - iterator insert(const_iterator position, const T &x); - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a new element before position with mx's resources. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - iterator insert(const_iterator position, T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, T, iterator, priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Inserts n copies of x before p. - //! - //! Returns: an iterator to the first inserted element or p if n is 0. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - iterator insert(const_iterator p, size_type n, const T& x) - { - typedef constant_iterator cvalue_iterator; - return this->insert(p, cvalue_iterator(x, n), cvalue_iterator()); - } - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Insert a copy of the [first, last) range before p. - //! - //! Returns: an iterator to the first inserted element or p if first == last. - //! - //! Throws: If memory allocation throws, T's constructor from a - //! dereferenced InpIt throws. - //! - //! Complexity: Linear to std::distance [first, last). - template - iterator insert(const_iterator p, InpIt first, InpIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && (container_detail::is_input_iterator::value - || container_detail::is_same::value - ) - >::type * = 0 - #endif - ) - { - const typename Icont::iterator ipos(p.get()); - iterator ret_it(ipos); - if(first != last){ - ret_it = iterator(this->icont().insert(ipos, *this->create_node_from_it(first))); - ++first; - } - for (; first != last; ++first){ - this->icont().insert(ipos, *this->create_node_from_it(first)); - } - return ret_it; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - iterator insert(const_iterator p, FwdIt first, FwdIt last - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !(container_detail::is_input_iterator::value - || container_detail::is_same::value - ) - >::type * = 0 - ) - { - //Optimized allocation and construction - insertion_functor func(this->icont(), p.get()); - iterator before_p(p.get()); - --before_p; - this->allocate_many_and_construct(first, std::distance(first, last), func); - return ++before_p; - } - #endif - - //! Effects: Removes the first element from the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Amortized constant time. - void pop_front() BOOST_CONTAINER_NOEXCEPT - { this->erase(this->cbegin()); } - - //! Effects: Removes the last element from the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Amortized constant time. - void pop_back() BOOST_CONTAINER_NOEXCEPT - { const_iterator tmp = this->cend(); this->erase(--tmp); } - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Erases the element at p p. - //! - //! Throws: Nothing. - //! - //! Complexity: Amortized constant time. - iterator erase(const_iterator p) BOOST_CONTAINER_NOEXCEPT - { return iterator(this->icont().erase_and_dispose(p.get(), Destroyer(this->node_alloc()))); } - - //! Requires: first and last must be valid iterator to elements in *this. - //! - //! Effects: Erases the elements pointed by [first, last). - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the distance between first and last. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { return iterator(AllocHolder::erase_range(first.get(), last.get(), alloc_version())); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(list& x) - { AllocHolder::swap(x); } - - //! Effects: Erases all the elements of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements in the list. - void clear() BOOST_CONTAINER_NOEXCEPT - { AllocHolder::clear(alloc_version()); } - - ////////////////////////////////////////////// - // - // slist operations - // - ////////////////////////////////////////////// - - //! Requires: p must point to an element contained - //! by the list. x != *this. this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers all the elements of list x to this list, before the - //! the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of - //! this list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, list& x) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this != &x); - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice(p.get(), x.icont()); - } - - //! Requires: p must point to an element contained - //! by the list. x != *this. this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers all the elements of list x to this list, before the - //! the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of - //! this list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, BOOST_RV_REF(list) x) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x)); } - - //! Requires: p must point to an element contained - //! by this list. i must point to an element contained in list x. - //! this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers the value pointed by i, from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! If p == i or p == ++i, this function is a null operation. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, list &x, const_iterator i) BOOST_CONTAINER_NOEXCEPT - { - //BOOST_ASSERT(this != &x); - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice(p.get(), x.icont(), i.get()); - } - - //! Requires: p must point to an element contained - //! by this list. i must point to an element contained in list x. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the value pointed by i, from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! If p == i or p == ++i, this function is a null operation. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, BOOST_RV_REF(list) x, const_iterator i) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x), i); } - - //! Requires: p must point to an element contained - //! by this list. first and last must point to elements contained in list x. - //! this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers the range pointed by first and last from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Linear to the number of elements transferred. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, list &x, const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice(p.get(), x.icont(), first.get(), last.get()); - } - - //! Requires: p must point to an element contained - //! by this list. first and last must point to elements contained in list x. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the range pointed by first and last from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Linear to the number of elements transferred. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, BOOST_RV_REF(list) x, const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x), first, last); } - - //! Requires: p must point to an element contained - //! by this list. first and last must point to elements contained in list x. - //! n == std::distance(first, last). this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers the range pointed by first and last from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - //! - //! Note: Non-standard extension - void splice(const_iterator p, list &x, const_iterator first, const_iterator last, size_type n) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice(p.get(), x.icont(), first.get(), last.get(), n); - } - - //! Requires: p must point to an element contained - //! by this list. first and last must point to elements contained in list x. - //! n == std::distance(first, last). this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers the range pointed by first and last from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - //! - //! Note: Non-standard extension - void splice(const_iterator p, BOOST_RV_REF(list) x, const_iterator first, const_iterator last, size_type n) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x), first, last, n); } - - //! Effects: Removes all the elements that compare equal to value. - //! - //! Throws: If comparison throws. - //! - //! Complexity: Linear time. It performs exactly size() comparisons for equality. - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - void remove(const T& value) - { this->remove_if(equal_to_value(value)); } - - //! Effects: Removes all the elements for which a specified - //! predicate is satisfied. - //! - //! Throws: If pred throws. - //! - //! Complexity: Linear time. It performs exactly size() calls to the predicate. - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - template - void remove_if(Pred pred) - { - typedef ValueCompareToNodeCompare Predicate; - this->icont().remove_and_dispose_if(Predicate(pred), Destroyer(this->node_alloc())); - } - - //! Effects: Removes adjacent duplicate elements or adjacent - //! elements that are equal from the list. - //! - //! Throws: If comparison throws. - //! - //! Complexity: Linear time (size()-1 comparisons equality comparisons). - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - void unique() - { this->unique(value_equal()); } - - //! Effects: Removes adjacent duplicate elements or adjacent - //! elements that satisfy some binary predicate from the list. - //! - //! Throws: If pred throws. - //! - //! Complexity: Linear time (size()-1 comparisons calls to pred()). - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - template - void unique(BinaryPredicate binary_pred) - { - typedef ValueCompareToNodeCompare Predicate; - this->icont().unique_and_dispose(Predicate(binary_pred), Destroyer(this->node_alloc())); - } - - //! Requires: The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this according to std::less. The merge is stable; - //! that is, if an element from *this is equivalent to one from x, then the element - //! from *this will precede the one from x. - //! - //! Throws: If comparison throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - void merge(list &x) - { this->merge(x, value_less()); } - - //! Requires: The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this according to std::less. The merge is stable; - //! that is, if an element from *this is equivalent to one from x, then the element - //! from *this will precede the one from x. - //! - //! Throws: If comparison throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - void merge(BOOST_RV_REF(list) x) - { this->merge(static_cast(x)); } - - //! Requires: p must be a comparison function that induces a strict weak - //! ordering and both *this and x must be sorted according to that ordering - //! The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this. The merge is stable; that is, if an element from *this is - //! equivalent to one from x, then the element from *this will precede the one from x. - //! - //! Throws: If comp throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - //! - //! Note: Iterators and references to *this are not invalidated. - template - void merge(list &x, const StrictWeakOrdering &comp) - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().merge(x.icont(), - ValueCompareToNodeCompare(comp)); - } - - //! Requires: p must be a comparison function that induces a strict weak - //! ordering and both *this and x must be sorted according to that ordering - //! The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this. The merge is stable; that is, if an element from *this is - //! equivalent to one from x, then the element from *this will precede the one from x. - //! - //! Throws: If comp throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - //! - //! Note: Iterators and references to *this are not invalidated. - template - void merge(BOOST_RV_REF(list) x, StrictWeakOrdering comp) - { this->merge(static_cast(x), comp); } - - //! Effects: This function sorts the list *this according to std::less. - //! The sort is stable, that is, the relative order of equivalent elements is preserved. - //! - //! Throws: If comparison throws. - //! - //! Notes: Iterators and references are not invalidated. - //! - //! Complexity: The number of comparisons is approximately N log N, where N - //! is the list's size. - void sort() - { this->sort(value_less()); } - - //! Effects: This function sorts the list *this according to std::less. - //! The sort is stable, that is, the relative order of equivalent elements is preserved. - //! - //! Throws: If comp throws. - //! - //! Notes: Iterators and references are not invalidated. - //! - //! Complexity: The number of comparisons is approximately N log N, where N - //! is the list's size. - template - void sort(StrictWeakOrdering comp) - { - // nothing if the list has length 0 or 1. - if (this->size() < 2) - return; - this->icont().sort(ValueCompareToNodeCompare(comp)); - } - - //! Effects: Reverses the order of elements in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: This function is linear time. - //! - //! Note: Iterators and references are not invalidated - void reverse() BOOST_CONTAINER_NOEXCEPT - { this->icont().reverse(); } - - /// @cond - private: - - bool priv_try_shrink(size_type new_size) - { - const size_type len = this->size(); - if(len > new_size){ - const const_iterator iend = this->cend(); - size_type to_erase = len - new_size; - const_iterator ifirst; - if(to_erase < len/2u){ - ifirst = iend; - while(to_erase--){ - --ifirst; - } - } - else{ - ifirst = this->cbegin(); - size_type to_skip = len - to_erase; - while(to_skip--){ - ++ifirst; - } - } - this->erase(ifirst, iend); - return true; - } - else{ - return false; - } - } - - iterator priv_insert(const_iterator p, const T &x) - { - NodePtr tmp = AllocHolder::create_node(x); - return iterator(this->icont().insert(p.get(), *tmp)); - } - - iterator priv_insert(const_iterator p, BOOST_RV_REF(T) x) - { - NodePtr tmp = AllocHolder::create_node(boost::move(x)); - return iterator(this->icont().insert(p.get(), *tmp)); - } - - void priv_push_back (const T &x) - { this->insert(this->cend(), x); } - - void priv_push_back (BOOST_RV_REF(T) x) - { this->insert(this->cend(), boost::move(x)); } - - void priv_push_front (const T &x) - { this->insert(this->cbegin(), x); } - - void priv_push_front (BOOST_RV_REF(T) x) - { this->insert(this->cbegin(), boost::move(x)); } - - class insertion_functor; - friend class insertion_functor; - - class insertion_functor - { - Icont &icont_; - typedef typename Icont::const_iterator iconst_iterator; - const iconst_iterator pos_; - - public: - insertion_functor(Icont &icont, typename Icont::const_iterator pos) - : icont_(icont), pos_(pos) - {} - - void operator()(Node &n) - { - this->icont_.insert(pos_, n); - } - }; - - //Functors for member algorithm defaults - struct value_less - { - bool operator()(const value_type &a, const value_type &b) const - { return a < b; } - }; - - struct value_equal - { - bool operator()(const value_type &a, const value_type &b) const - { return a == b; } - }; - /// @endcond - -}; - -template -inline bool operator==(const list& x, const list& y) -{ - if(x.size() != y.size()){ - return false; - } - typedef typename list::const_iterator const_iterator; - const_iterator end1 = x.end(); - - const_iterator i1 = x.begin(); - const_iterator i2 = y.begin(); - while (i1 != end1 && *i1 == *i2) { - ++i1; - ++i2; - } - return i1 == end1; -} - -template -inline bool operator<(const list& x, - const list& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); -} - -template -inline bool operator!=(const list& x, const list& y) -{ - return !(x == y); -} - -template -inline bool operator>(const list& x, const list& y) -{ - return y < x; -} - -template -inline bool operator<=(const list& x, const list& y) -{ - return !(y < x); -} - -template -inline bool operator>=(const list& x, const list& y) -{ - return !(x < y); -} - -template -inline void swap(list& x, list& y) -{ - x.swap(y); -} - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > - : public ::boost::has_trivial_destructor_after_move -{}; - -namespace container { - -/// @endcond - -}} - -#include - -#endif // BOOST_CONTAINER_LIST_HPP diff --git a/utils/boost_idb/boost/container/map.hpp b/utils/boost_idb/boost/container/map.hpp deleted file mode 100644 index f4776e88..00000000 --- a/utils/boost_idb/boost/container/map.hpp +++ /dev/null @@ -1,1532 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_MAP_HPP -#define BOOST_CONTAINER_MAP_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond -// Forward declarations of operators == and <, needed for friend declarations. -template -inline bool operator==(const map& x, - const map& y); - -template -inline bool operator<(const map& x, - const map& y); -/// @endcond - -//! A map is a kind of associative container that supports unique keys (contains at -//! most one of each key value) and provides for fast retrieval of values of another -//! type T based on the keys. The map class supports bidirectional iterators. -//! -//! A map satisfies all of the requirements of a container and of a reversible -//! container and of an associative container. For a -//! map the key_type is Key and the value_type is std::pair. -//! -//! Compare is the ordering function for Keys (e.g. std::less). -//! -//! Allocator is the allocator to allocate the value_types -//! (e.g. allocator< std::pair > ). -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator< std::pair< const Key, T> > > -#else -template -#endif -class map -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(map) - - typedef std::pair value_type_impl; - typedef container_detail::rbtree - , Compare, Allocator> tree_t; - typedef container_detail::pair movable_value_type_impl; - typedef container_detail::tree_value_compare - < Key, value_type_impl, Compare, container_detail::select1st - > value_compare_impl; - tree_t m_tree; // red-black tree representing map - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - - typedef Key key_type; - typedef T mapped_type; - typedef std::pair value_type; - typedef typename boost::container::allocator_traits::pointer pointer; - typedef typename boost::container::allocator_traits::const_pointer const_pointer; - typedef typename boost::container::allocator_traits::reference reference; - typedef typename boost::container::allocator_traits::const_reference const_reference; - typedef typename boost::container::allocator_traits::size_type size_type; - typedef typename boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(value_compare_impl) value_compare; - typedef Compare key_compare; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; - typedef std::pair nonconst_value_type; - typedef BOOST_CONTAINER_IMPDEF(movable_value_type_impl) movable_value_type; - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs an empty map. - //! - //! Complexity: Constant. - map() - : m_tree() - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty map using the specified comparison object - //! and allocator. - //! - //! Complexity: Constant. - explicit map(const Compare& comp, - const allocator_type& a = allocator_type()) - : m_tree(comp, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty map using the specified allocator. - //! - //! Complexity: Constant. - explicit map(const allocator_type& a) - : m_tree(a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty map using the specified comparison object and - //! allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - map(InputIterator first, InputIterator last, const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_tree(true, first, last, comp, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty map using the specified comparison object and - //! allocator, and inserts elements from the ordered unique range [first ,last). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate and must be - //! unique values. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - map( ordered_unique_range_t, InputIterator first, InputIterator last - , const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Copy constructs a map. - //! - //! Complexity: Linear in x.size(). - map(const map& x) - : m_tree(x.m_tree) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Move constructs a map. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - map(BOOST_RV_REF(map) x) - : m_tree(boost::move(x.m_tree)) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Copy constructs a map using the specified allocator. - //! - //! Complexity: Linear in x.size(). - map(const map& x, const allocator_type &a) - : m_tree(x.m_tree, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Move constructs a map using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if x == x.get_allocator(), linear otherwise. - //! - //! Postcondition: x is emptied. - map(BOOST_RV_REF(map) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - map& operator=(BOOST_COPY_ASSIGN_REF(map) x) - { m_tree = x.m_tree; return *this; } - - //! Effects: this->swap(x.get()). - //! - //! Complexity: Constant. - map& operator=(BOOST_RV_REF(map) x) - { m_tree = boost::move(x.m_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbegin(); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: If there is no key equivalent to x in the map, inserts - //! value_type(x, T()) into the map. - //! - //! Returns: Allocator reference to the mapped_type corresponding to x in *this. - //! - //! Complexity: Logarithmic. - mapped_type& operator[](const key_type &k); - - //! Effects: If there is no key equivalent to x in the map, inserts - //! value_type(boost::move(x), T()) into the map (the key is move-constructed) - //! - //! Returns: Allocator reference to the mapped_type corresponding to x in *this. - //! - //! Complexity: Logarithmic. - mapped_type& operator[](key_type &&k); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH( operator[] , key_type, mapped_type&, this->priv_subscript) - #endif - - //! Returns: Allocator reference to the element whose key is equivalent to x. - //! Throws: An exception object of type out_of_range if no such element is present. - //! Complexity: logarithmic. - T& at(const key_type& k) - { - iterator i = this->find(k); - if(i == this->end()){ - throw_out_of_range("map::at key not found"); - } - return i->second; - } - - //! Returns: Allocator reference to the element whose key is equivalent to x. - //! Throws: An exception object of type out_of_range if no such element is present. - //! Complexity: logarithmic. - const T& at(const key_type& k) const - { - const_iterator i = this->find(k); - if(i == this->end()){ - throw_out_of_range("map::at key not found"); - } - return i->second; - } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - //! Effects: Inserts x if and only if there is no element in the container - //! with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(const value_type& x) - { return m_tree.insert_unique(x); } - - //! Effects: Inserts a new value_type created from the pair if and only if - //! there is no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(const nonconst_value_type& x) - { return m_tree.insert_unique(x); } - - //! Effects: Inserts a new value_type move constructed from the pair if and - //! only if there is no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_unique(boost::move(x)); } - - //! Effects: Inserts a new value_type move constructed from the pair if and - //! only if there is no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_unique(boost::move(x)); } - - //! Effects: Move constructs a new value from x if and only if there is - //! no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(BOOST_RV_REF(value_type) x) - { return m_tree.insert_unique(boost::move(x)); } - - //! Effects: Inserts a copy of x in the container if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, const value_type& x) - { return m_tree.insert_unique(position, x); } - - //! Effects: Move constructs a new value from x if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_unique(position, boost::move(x)); } - - //! Effects: Move constructs a new value from x if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_unique(position, boost::move(x)); } - - //! Effects: Inserts a copy of x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - iterator insert(const_iterator position, const nonconst_value_type& x) - { return m_tree.insert_unique(position, x); } - - //! Effects: Inserts an element move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - iterator insert(const_iterator position, BOOST_RV_REF(value_type) x) - { return m_tree.insert_unique(position, boost::move(x)); } - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) if and only - //! if there is no element with key equivalent to the key of that element. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - template - void insert(InputIterator first, InputIterator last) - { m_tree.insert_unique(first, last); } - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object x of type T constructed with - //! std::forward(args)... in the container if and only if there is - //! no element in the container with an equivalent key. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - template - std::pair emplace(Args&&... args) - { return m_tree.emplace_unique(boost::forward(args)...); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the container if and only if there is - //! no element in the container with an equivalent key. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_unique(hint, boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_unique(hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Amortized constant time - iterator erase(const_iterator position) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(position); } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(first, last); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(map& x) - { m_tree.swap(x.m_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return value_compare(m_tree.key_comp()); } - - ////////////////////////////////////////////// - // - // map operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } - - //! Returns: Allocator const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return static_cast(m_tree.find(x) != m_tree.end()); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const map&, - const map&); - template - friend bool operator< (const map&, - const map&); - private: - mapped_type& priv_subscript(const key_type &k) - { - //we can optimize this - iterator i = lower_bound(k); - // i->first is greater than or equivalent to k. - if (i == end() || key_comp()(k, (*i).first)){ - container_detail::value_init m; - movable_value_type val(k, boost::move(m.m_t)); - i = insert(i, boost::move(val)); - } - return (*i).second; - } - - mapped_type& priv_subscript(BOOST_RV_REF(key_type) mk) - { - key_type &k = mk; - //we can optimize this - iterator i = lower_bound(k); - // i->first is greater than or equivalent to k. - if (i == end() || key_comp()(k, (*i).first)){ - container_detail::value_init m; - movable_value_type val(boost::move(k), boost::move(m.m_t)); - i = insert(i, boost::move(val)); - } - return (*i).second; - } - - /// @endcond -}; - -template -inline bool operator==(const map& x, - const map& y) - { return x.m_tree == y.m_tree; } - -template -inline bool operator<(const map& x, - const map& y) - { return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const map& x, - const map& y) - { return !(x == y); } - -template -inline bool operator>(const map& x, - const map& y) - { return y < x; } - -template -inline bool operator<=(const map& x, - const map& y) - { return !(y < x); } - -template -inline bool operator>=(const map& x, - const map& y) - { return !(x < y); } - -template -inline void swap(map& x, map& y) - { x.swap(y); } - -/// @cond - -// Forward declaration of operators < and ==, needed for friend declaration. - -template -inline bool operator==(const multimap& x, - const multimap& y); - -template -inline bool operator<(const multimap& x, - const multimap& y); - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -namespace container { - -/// @endcond - -//! A multimap is a kind of associative container that supports equivalent keys -//! (possibly containing multiple copies of the same key value) and provides for -//! fast retrieval of values of another type T based on the keys. The multimap class -//! supports bidirectional iterators. -//! -//! A multimap satisfies all of the requirements of a container and of a reversible -//! container and of an associative container. For a -//! map the key_type is Key and the value_type is std::pair. -//! -//! Compare is the ordering function for Keys (e.g. std::less). -//! -//! Allocator is the allocator to allocate the value_types -//!(e.g. allocator< std::pair<const Key, T> >). -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator< std::pair< const Key, T> > > -#else -template -#endif -class multimap -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(multimap) - - typedef std::pair value_type_impl; - typedef container_detail::rbtree - , Compare, Allocator> tree_t; - typedef container_detail::pair movable_value_type_impl; - typedef container_detail::tree_value_compare - < Key, value_type_impl, Compare, container_detail::select1st - > value_compare_impl; - tree_t m_tree; // red-black tree representing map - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - - typedef Key key_type; - typedef T mapped_type; - typedef std::pair value_type; - typedef typename boost::container::allocator_traits::pointer pointer; - typedef typename boost::container::allocator_traits::const_pointer const_pointer; - typedef typename boost::container::allocator_traits::reference reference; - typedef typename boost::container::allocator_traits::const_reference const_reference; - typedef typename boost::container::allocator_traits::size_type size_type; - typedef typename boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(value_compare_impl) value_compare; - typedef Compare key_compare; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; - typedef std::pair nonconst_value_type; - typedef BOOST_CONTAINER_IMPDEF(movable_value_type_impl) movable_value_type; - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs an empty multimap. - //! - //! Complexity: Constant. - multimap() - : m_tree() - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty multimap using the specified allocator. - //! - //! Complexity: Constant. - explicit multimap(const Compare& comp, const allocator_type& a = allocator_type()) - : m_tree(comp, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty multimap using the specified comparison - //! object and allocator. - //! - //! Complexity: Constant. - explicit multimap(const allocator_type& a) - : m_tree(a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty multimap using the specified comparison object - //! and allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - multimap(InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_tree(false, first, last, comp, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Constructs an empty multimap using the specified comparison object and - //! allocator, and inserts elements from the ordered range [first ,last). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - multimap(ordered_range_t, InputIterator first, InputIterator last, const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a multimap. - //! - //! Complexity: Linear in x.size(). - multimap(const multimap& x) - : m_tree(x.m_tree) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Move constructs a multimap. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - multimap(BOOST_RV_REF(multimap) x) - : m_tree(boost::move(x.m_tree)) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Copy constructs a multimap. - //! - //! Complexity: Linear in x.size(). - multimap(const multimap& x, const allocator_type &a) - : m_tree(x.m_tree, a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Move constructs a multimap using the specified allocator. - //! Constructs *this using x's resources. - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - //! - //! Postcondition: x is emptied. - multimap(BOOST_RV_REF(multimap) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) - { - //Allocator type must be std::pair - BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); - } - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - multimap& operator=(BOOST_COPY_ASSIGN_REF(multimap) x) - { m_tree = x.m_tree; return *this; } - - //! Effects: this->swap(x.get()). - //! - //! Complexity: Constant. - multimap& operator=(BOOST_RV_REF(multimap) x) - { m_tree = boost::move(x.m_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbegin(); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - template - iterator emplace(Args&&... args) - { return m_tree.emplace_equal(boost::forward(args)...); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_equal(hint, boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_equal(hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - //! Effects: Inserts x and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic. - iterator insert(const value_type& x) - { return m_tree.insert_equal(x); } - - //! Effects: Inserts a new value constructed from x and returns - //! the iterator pointing to the newly inserted element. - //! - //! Complexity: Logarithmic. - iterator insert(const nonconst_value_type& x) - { return m_tree.insert_equal(x); } - - //! Effects: Inserts a new value move-constructed from x and returns - //! the iterator pointing to the newly inserted element. - //! - //! Complexity: Logarithmic. - iterator insert(BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_equal(boost::move(x)); } - - //! Effects: Inserts a new value move-constructed from x and returns - //! the iterator pointing to the newly inserted element. - //! - //! Complexity: Logarithmic. - iterator insert(BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_equal(boost::move(x)); } - - //! Effects: Inserts a copy of x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, const value_type& x) - { return m_tree.insert_equal(position, x); } - - //! Effects: Inserts a new value constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, const nonconst_value_type& x) - { return m_tree.insert_equal(position, x); } - - //! Effects: Inserts a new value move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_equal(position, boost::move(x)); } - - //! Effects: Inserts a new value move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_equal(position, boost::move(x)); } - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) . - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - template - void insert(InputIterator first, InputIterator last) - { m_tree.insert_equal(first, last); } - - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Amortized constant time - iterator erase(const_iterator position) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(position); } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(first, last); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(multimap& x) - { m_tree.swap(x.m_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return value_compare(m_tree.key_comp()); } - - ////////////////////////////////////////////// - // - // map operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } - - //! Returns: Allocator const iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_tree.count(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - {return m_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const multimap& x, - const multimap& y); - - template - friend bool operator< (const multimap& x, - const multimap& y); - /// @endcond -}; - -template -inline bool operator==(const multimap& x, - const multimap& y) -{ return x.m_tree == y.m_tree; } - -template -inline bool operator<(const multimap& x, - const multimap& y) -{ return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const multimap& x, - const multimap& y) -{ return !(x == y); } - -template -inline bool operator>(const multimap& x, - const multimap& y) -{ return y < x; } - -template -inline bool operator<=(const multimap& x, - const multimap& y) -{ return !(y < x); } - -template -inline bool operator>=(const multimap& x, - const multimap& y) -{ return !(x < y); } - -template -inline void swap(multimap& x, multimap& y) -{ x.swap(y); } - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -namespace container { - -/// @endcond - -}} - -#include - -#endif /* BOOST_CONTAINER_MAP_HPP */ - diff --git a/utils/boost_idb/boost/container/scoped_allocator.hpp b/utils/boost_idb/boost/container/scoped_allocator.hpp deleted file mode 100644 index d16ac37f..00000000 --- a/utils/boost_idb/boost/container/scoped_allocator.hpp +++ /dev/null @@ -1,1534 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Pablo Halpern 2009. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_ALLOCATOR_SCOPED_ALLOCATOR_HPP -#define BOOST_CONTAINER_ALLOCATOR_SCOPED_ALLOCATOR_HPP - -#if defined (_MSC_VER) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { namespace container { - -//! Remark: if a specialization is derived from true_type, indicates that T may be constructed -//! with an allocator as its last constructor argument. Ideally, all constructors of T (including the -//! copy and move constructors) should have a variant that accepts a final argument of -//! allocator_type. -//! -//! Requires: if a specialization is derived from true_type, T must have a nested type, -//! allocator_type and at least one constructor for which allocator_type is the last -//! parameter. If not all constructors of T can be called with a final allocator_type argument, -//! and if T is used in a context where a container must call such a constructor, then the program is -//! ill-formed. -//! -//! [Example: -//! template > -//! class Z { -//! public: -//! typedef Allocator allocator_type; -//! -//! // Default constructor with optional allocator suffix -//! Z(const allocator_type& a = allocator_type()); -//! -//! // Copy constructor and allocator-extended copy constructor -//! Z(const Z& zz); -//! Z(const Z& zz, const allocator_type& a); -//! }; -//! -//! // Specialize trait for class template Z -//! template > -//! struct constructible_with_allocator_suffix > -//! : ::boost::true_type { }; -//! -- end example] -//! -//! Note: This trait is a workaround inspired by "N2554: The Scoped Allocator Model (Rev 2)" -//! (Pablo Halpern, 2008-02-29) to backport the scoped allocator model to C++03, as -//! in C++03 there is no mechanism to detect if a type can be constructed from arbitrary arguments. -//! Applications aiming portability with several compilers should always define this trait. -//! -//! In conforming C++11 compilers or compilers supporting SFINAE expressions -//! (when BOOST_NO_SFINAE_EXPR is NOT defined), this trait is ignored and C++11 rules will be used -//! to detect if a type should be constructed with suffix or prefix allocator arguments. -template -struct constructible_with_allocator_suffix - : ::boost::false_type -{}; - -//! Remark: if a specialization is derived from true_type, indicates that T may be constructed -//! with allocator_arg and T::allocator_type as its first two constructor arguments. -//! Ideally, all constructors of T (including the copy and move constructors) should have a variant -//! that accepts these two initial arguments. -//! -//! Requires: if a specialization is derived from true_type, T must have a nested type, -//! allocator_type and at least one constructor for which allocator_arg_t is the first -//! parameter and allocator_type is the second parameter. If not all constructors of T can be -//! called with these initial arguments, and if T is used in a context where a container must call such -//! a constructor, then the program is ill-formed. -//! -//! [Example: -//! template > -//! class Y { -//! public: -//! typedef Allocator allocator_type; -//! -//! // Default constructor with and allocator-extended default constructor -//! Y(); -//! Y(allocator_arg_t, const allocator_type& a); -//! -//! // Copy constructor and allocator-extended copy constructor -//! Y(const Y& yy); -//! Y(allocator_arg_t, const allocator_type& a, const Y& yy); -//! -//! // Variadic constructor and allocator-extended variadic constructor -//! template Y(Args&& args...); -//! template -//! Y(allocator_arg_t, const allocator_type& a, Args&&... args); -//! }; -//! -//! // Specialize trait for class template Y -//! template > -//! struct constructible_with_allocator_prefix > -//! : ::boost::true_type { }; -//! -//! -- end example] -//! -//! Note: This trait is a workaround inspired by "N2554: The Scoped Allocator Model (Rev 2)" -//! (Pablo Halpern, 2008-02-29) to backport the scoped allocator model to C++03, as -//! in C++03 there is no mechanism to detect if a type can be constructed from arbitrary arguments. -//! Applications aiming portability with several compilers should always define this trait. -//! -//! In conforming C++11 compilers or compilers supporting SFINAE expressions -//! (when BOOST_NO_SFINAE_EXPR is NOT defined), this trait is ignored and C++11 rules will be used -//! to detect if a type should be constructed with suffix or prefix allocator arguments. -template -struct constructible_with_allocator_prefix - : ::boost::false_type -{}; - -///@cond - -namespace container_detail { - -template -struct uses_allocator_imp -{ - // Use SFINAE (Substitution Failure Is Not An Error) to detect the - // presence of an 'allocator_type' nested type convertilble from Alloc. - - private: - // Match this function if TypeT::allocator_type exists and is - // implicitly convertible from Alloc - template - static char test(int, typename U::allocator_type); - - // Match this function if TypeT::allocator_type does not exist or is - // not convertible from Alloc. - template - static int test(LowPriorityConversion, LowPriorityConversion); - - static Alloc alloc; // Declared but not defined - - public: - enum { value = sizeof(test(0, alloc)) == sizeof(char) }; -}; - -} //namespace container_detail { - -///@endcond - -//! Remark: Automatically detects if T has a nested allocator_type that is convertible from -//! Alloc. Meets the BinaryTypeTrait requirements ([meta.rqmts] 20.4.1). A program may -//! specialize this type to derive from true_type for a T of user-defined type if T does not -//! have a nested allocator_type but is nonetheless constructible using the specified Alloc. -//! -//! Result: derived from true_type if Convertible and -//! derived from false_type otherwise. -template -struct uses_allocator - : boost::integral_constant::value> -{}; - -///@cond - -namespace container_detail { - -template -struct is_scoped_allocator_imp -{ - template - static char test(int, typename T::outer_allocator_type*); - - template - static int test(LowPriorityConversion, void*); - - static const bool value = (sizeof(char) == sizeof(test(0, 0))); -}; - -template::value > -struct outermost_allocator_type_impl -{ - typedef typename MaybeScopedAlloc::outer_allocator_type outer_type; - typedef typename outermost_allocator_type_impl::type type; -}; - -template -struct outermost_allocator_type_impl -{ - typedef MaybeScopedAlloc type; -}; - -template::value > -struct outermost_allocator_imp -{ - typedef MaybeScopedAlloc type; - - static type &get(MaybeScopedAlloc &a) - { return a; } - - static const type &get(const MaybeScopedAlloc &a) - { return a; } -}; - -template -struct outermost_allocator_imp -{ - typedef typename MaybeScopedAlloc::outer_allocator_type outer_type; - typedef typename outermost_allocator_type_impl::type type; - - static type &get(MaybeScopedAlloc &a) - { return outermost_allocator_imp::get(a.outer_allocator()); } - - static const type &get(const MaybeScopedAlloc &a) - { return outermost_allocator_imp::get(a.outer_allocator()); } -}; - -} //namespace container_detail { - -template -struct is_scoped_allocator - : boost::integral_constant::value> -{}; - -template -struct outermost_allocator - : container_detail::outermost_allocator_imp -{}; - -template -typename container_detail::outermost_allocator_imp::type & - get_outermost_allocator(Alloc &a) -{ return container_detail::outermost_allocator_imp::get(a); } - -template -const typename container_detail::outermost_allocator_imp::type & - get_outermost_allocator(const Alloc &a) -{ return container_detail::outermost_allocator_imp::get(a); } - -namespace container_detail { - -// Check if we can detect is_convertible using advanced SFINAE expressions -#if !defined(BOOST_NO_SFINAE_EXPR) - - //! Code inspired by Mathias Gaunard's is_convertible.cpp found in the Boost mailing list - //! http://boost.2283326.n4.nabble.com/type-traits-is-constructible-when-decltype-is-supported-td3575452.html - //! Thanks Mathias! - - //With variadic templates, we need a single class to implement the trait - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - template - struct is_constructible_impl - { - typedef char yes_type; - struct no_type - { char padding[2]; }; - - template - struct dummy; - - template - static yes_type test(dummy()...))>*); - - template - static no_type test(...); - - static const bool value = sizeof(test(0)) == sizeof(yes_type); - }; - - template - struct is_constructible - : boost::integral_constant::value> - {}; - - template - struct is_constructible_with_allocator_prefix - : is_constructible - {}; - - #else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - //Without variadic templates, we need to use de preprocessor to generate - //some specializations. - - #define BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS \ - BOOST_PP_ADD(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, 3) - //! - - //Generate N+1 template parameters so that we can specialize N - template - struct is_constructible_impl; - - //Generate N specializations, from 0 to - //BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS parameters - #define BOOST_PP_LOCAL_MACRO(n) \ - template \ - struct is_constructible_impl \ - \ - { \ - typedef char yes_type; \ - struct no_type \ - { char padding[2]; }; \ - \ - template \ - struct dummy; \ - \ - template \ - static yes_type test(dummy*); \ - \ - template \ - static no_type test(...); \ - \ - static const bool value = sizeof(test(0)) == sizeof(yes_type); \ - }; \ - //! - - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - //Finally just inherit from the implementation to define he trait - template< class T - BOOST_PP_ENUM_TRAILING( BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS - , BOOST_CONTAINER_PP_TEMPLATE_PARAM_WITH_DEFAULT - , void) - > - struct is_constructible - : boost::integral_constant - < bool - , is_constructible_impl - < T - BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS, P) - , void>::value - > - {}; - - //Finally just inherit from the implementation to define he trait - template - struct is_constructible_with_allocator_prefix - : is_constructible - < T, allocator_arg_t, InnerAlloc - BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_SUB(BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS, 2), P) - > - {}; -/* - template - struct is_constructible_with_allocator_suffix - : is_constructible - < T - BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_SUB(BOOST_CONTAINER_MAX_IS_CONSTRUCTIBLE_PARAMETERS, 1), P) - , InnerAlloc - > - {};*/ - - #endif // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -#else // #if !defined(BOOST_NO_SFINAE_EXPR) - - //Without advanced SFINAE expressions, we can't use is_constructible - //so backup to constructible_with_allocator_xxx - - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - template < class T, class InnerAlloc, class ...Args> - struct is_constructible_with_allocator_prefix - : constructible_with_allocator_prefix - {}; -/* - template < class T, class InnerAlloc, class ...Args> - struct is_constructible_with_allocator_suffix - : constructible_with_allocator_suffix - {};*/ - - #else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - template < class T - , class InnerAlloc - BOOST_PP_ENUM_TRAILING( BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS - , BOOST_CONTAINER_PP_TEMPLATE_PARAM_WITH_DEFAULT - , void) - > - struct is_constructible_with_allocator_prefix - : constructible_with_allocator_prefix - {}; -/* - template < class T - , class InnerAlloc - BOOST_PP_ENUM_TRAILING( BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS - , BOOST_CONTAINER_PP_TEMPLATE_PARAM_WITH_DEFAULT - , void) - > - struct is_constructible_with_allocator_suffix - : constructible_with_allocator_suffix - {};*/ - - #endif // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -#endif // #if !defined(BOOST_NO_SFINAE_EXPR) - -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -template < typename OutermostAlloc - , typename InnerAlloc - , typename T - , class ...Args - > -inline void dispatch_allocator_prefix_suffix - ( boost::true_type use_alloc_prefix, OutermostAlloc& outermost_alloc - , InnerAlloc& inner_alloc, T* p, BOOST_FWD_REF(Args) ...args) -{ - (void)use_alloc_prefix; - allocator_traits::construct - ( outermost_alloc, p, allocator_arg, inner_alloc, ::boost::forward(args)...); -} - -template < typename OutermostAlloc - , typename InnerAlloc - , typename T - , class ...Args - > -inline void dispatch_allocator_prefix_suffix - ( boost::false_type use_alloc_prefix, OutermostAlloc& outermost_alloc - , InnerAlloc &inner_alloc, T* p, BOOST_FWD_REF(Args)...args) -{ - (void)use_alloc_prefix; - allocator_traits::construct - (outermost_alloc, p, ::boost::forward(args)..., inner_alloc); -} - -template < typename OutermostAlloc - , typename InnerAlloc - , typename T - , class ...Args - > -inline void dispatch_uses_allocator - ( boost::true_type uses_allocator, OutermostAlloc& outermost_alloc - , InnerAlloc& inner_alloc, T* p, BOOST_FWD_REF(Args)...args) -{ - (void)uses_allocator; - //BOOST_STATIC_ASSERT((is_constructible_with_allocator_prefix::value || - // is_constructible_with_allocator_suffix::value )); - dispatch_allocator_prefix_suffix - ( is_constructible_with_allocator_prefix() - , outermost_alloc, inner_alloc, p, ::boost::forward(args)...); -} - -template < typename OutermostAlloc - , typename InnerAlloc - , typename T - , class ...Args - > -inline void dispatch_uses_allocator - ( boost::false_type uses_allocator, OutermostAlloc & outermost_alloc - , InnerAlloc & inner_alloc - ,T* p, BOOST_FWD_REF(Args)...args) -{ - (void)uses_allocator; (void)inner_alloc; - allocator_traits::construct - (outermost_alloc, p, ::boost::forward(args)...); -} - -#else //#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -#define BOOST_PP_LOCAL_MACRO(n) \ -template < typename OutermostAlloc \ - , typename InnerAlloc \ - , typename T \ - BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \ - > \ -inline void dispatch_allocator_prefix_suffix( \ - boost::true_type use_alloc_prefix, \ - OutermostAlloc& outermost_alloc, \ - InnerAlloc& inner_alloc, \ - T* p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ -{ \ - (void)use_alloc_prefix, \ - allocator_traits::construct \ - (outermost_alloc, p, allocator_arg, inner_alloc \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ -} \ - \ -template < typename OutermostAlloc \ - , typename InnerAlloc \ - , typename T \ - BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \ - > \ -inline void dispatch_allocator_prefix_suffix( \ - boost::false_type use_alloc_prefix, \ - OutermostAlloc& outermost_alloc, \ - InnerAlloc& inner_alloc, \ - T* p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ -{ \ - (void)use_alloc_prefix; \ - allocator_traits::construct \ - (outermost_alloc, p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) \ - , inner_alloc); \ -} \ - \ -template < typename OutermostAlloc \ - , typename InnerAlloc \ - , typename T \ - BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \ - > \ -inline void dispatch_uses_allocator(boost::true_type uses_allocator, \ - OutermostAlloc& outermost_alloc, \ - InnerAlloc& inner_alloc, \ - T* p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ -{ \ - (void)uses_allocator; \ - dispatch_allocator_prefix_suffix \ - (is_constructible_with_allocator_prefix \ - < T, InnerAlloc BOOST_PP_ENUM_TRAILING_PARAMS(n, P)>() \ - , outermost_alloc, inner_alloc, p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ -} \ - \ -template < typename OutermostAlloc \ - , typename InnerAlloc \ - , typename T \ - BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \ - > \ -inline void dispatch_uses_allocator(boost::false_type uses_allocator \ - ,OutermostAlloc & outermost_alloc \ - ,InnerAlloc & inner_alloc \ - ,T* p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ -{ \ - (void)uses_allocator; (void)inner_alloc; \ - allocator_traits::construct \ - (outermost_alloc, p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ -} \ -//! -#define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) -#include BOOST_PP_LOCAL_ITERATE() - -#endif //#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -template -class scoped_allocator_adaptor_base - : public OuterAlloc -{ - typedef allocator_traits outer_traits_type; - BOOST_COPYABLE_AND_MOVABLE(scoped_allocator_adaptor_base) - - public: - template - struct rebind_base - { - typedef scoped_allocator_adaptor_base other; - }; - - typedef OuterAlloc outer_allocator_type; - typedef scoped_allocator_adaptor inner_allocator_type; - typedef allocator_traits inner_traits_type; - typedef scoped_allocator_adaptor - scoped_allocator_type; - typedef boost::integral_constant< - bool, - outer_traits_type::propagate_on_container_copy_assignment::value || - inner_allocator_type::propagate_on_container_copy_assignment::value - > propagate_on_container_copy_assignment; - typedef boost::integral_constant< - bool, - outer_traits_type::propagate_on_container_move_assignment::value || - inner_allocator_type::propagate_on_container_move_assignment::value - > propagate_on_container_move_assignment; - typedef boost::integral_constant< - bool, - outer_traits_type::propagate_on_container_swap::value || - inner_allocator_type::propagate_on_container_swap::value - > propagate_on_container_swap; - - scoped_allocator_adaptor_base() - {} - - template - scoped_allocator_adaptor_base(BOOST_FWD_REF(OuterA2) outerAlloc, const InnerAllocs &...args) - : outer_allocator_type(::boost::forward(outerAlloc)) - , m_inner(args...) - {} - - scoped_allocator_adaptor_base(const scoped_allocator_adaptor_base& other) - : outer_allocator_type(other.outer_allocator()) - , m_inner(other.inner_allocator()) - {} - - scoped_allocator_adaptor_base(BOOST_RV_REF(scoped_allocator_adaptor_base) other) - : outer_allocator_type(::boost::move(other.outer_allocator())) - , m_inner(::boost::move(other.inner_allocator())) - {} - - template - scoped_allocator_adaptor_base - (const scoped_allocator_adaptor_base& other) - : outer_allocator_type(other.outer_allocator()) - , m_inner(other.inner_allocator()) - {} - - template - scoped_allocator_adaptor_base - (BOOST_RV_REF_BEG scoped_allocator_adaptor_base - BOOST_RV_REF_END other) - : outer_allocator_type(other.outer_allocator()) - , m_inner(other.inner_allocator()) - {} - - public: - struct internal_type_t{}; - - template - scoped_allocator_adaptor_base - ( internal_type_t - , BOOST_FWD_REF(OuterA2) outerAlloc - , const inner_allocator_type &inner) - : outer_allocator_type(::boost::forward(outerAlloc)) - , m_inner(inner) - {} - - public: - - scoped_allocator_adaptor_base &operator= - (BOOST_COPY_ASSIGN_REF(scoped_allocator_adaptor_base) other) - { - outer_allocator_type::operator=(other.outer_allocator()); - m_inner = other.inner_allocator(); - return *this; - } - - scoped_allocator_adaptor_base &operator=(BOOST_RV_REF(scoped_allocator_adaptor_base) other) - { - outer_allocator_type::operator=(boost::move(other.outer_allocator())); - m_inner = ::boost::move(other.inner_allocator()); - return *this; - } - - void swap(scoped_allocator_adaptor_base &r) - { - boost::container::swap_dispatch(this->outer_allocator(), r.outer_allocator()); - boost::container::swap_dispatch(this->m_inner, r.inner_allocator()); - } - - friend void swap(scoped_allocator_adaptor_base &l, scoped_allocator_adaptor_base &r) - { l.swap(r); } - - inner_allocator_type& inner_allocator() - { return m_inner; } - - inner_allocator_type const& inner_allocator() const - { return m_inner; } - - outer_allocator_type & outer_allocator() - { return static_cast(*this); } - - const outer_allocator_type &outer_allocator() const - { return static_cast(*this); } - - scoped_allocator_type select_on_container_copy_construction() const - { - return scoped_allocator_type - (internal_type_t() - ,outer_traits_type::select_on_container_copy_construction(this->outer_allocator()) - ,inner_traits_type::select_on_container_copy_construction(this->inner_allocator()) - ); - } - - private: - inner_allocator_type m_inner; -}; - -#else //#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -//Let's add a dummy first template parameter to allow creating -//specializations up to maximum InnerAlloc count -template < - typename OuterAlloc - , bool Dummy - BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, class Q) - > -class scoped_allocator_adaptor_base; - -//Specializations for the adaptor with InnerAlloc allocators - -#define BOOST_PP_LOCAL_MACRO(n) \ -template \ -class scoped_allocator_adaptor_base \ - : public OuterAlloc \ -{ \ - typedef allocator_traits outer_traits_type; \ - BOOST_COPYABLE_AND_MOVABLE(scoped_allocator_adaptor_base) \ - \ - public: \ - template \ - struct rebind_base \ - { \ - typedef scoped_allocator_adaptor_base other; \ - }; \ - \ - typedef OuterAlloc outer_allocator_type; \ - typedef scoped_allocator_adaptor inner_allocator_type; \ - typedef scoped_allocator_adaptor scoped_allocator_type; \ - typedef allocator_traits inner_traits_type; \ - typedef boost::integral_constant< \ - bool, \ - outer_traits_type::propagate_on_container_copy_assignment::value || \ - inner_allocator_type::propagate_on_container_copy_assignment::value \ - > propagate_on_container_copy_assignment; \ - typedef boost::integral_constant< \ - bool, \ - outer_traits_type::propagate_on_container_move_assignment::value || \ - inner_allocator_type::propagate_on_container_move_assignment::value \ - > propagate_on_container_move_assignment; \ - typedef boost::integral_constant< \ - bool, \ - outer_traits_type::propagate_on_container_swap::value || \ - inner_allocator_type::propagate_on_container_swap::value \ - > propagate_on_container_swap; \ - \ - scoped_allocator_adaptor_base() \ - {} \ - \ - template \ - scoped_allocator_adaptor_base(BOOST_FWD_REF(OuterA2) outerAlloc \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_CONST_REF_PARAM_LIST_Q, _)) \ - : outer_allocator_type(::boost::forward(outerAlloc)) \ - , m_inner(BOOST_PP_ENUM_PARAMS(n, q)) \ - {} \ - \ - scoped_allocator_adaptor_base(const scoped_allocator_adaptor_base& other) \ - : outer_allocator_type(other.outer_allocator()) \ - , m_inner(other.inner_allocator()) \ - {} \ - \ - scoped_allocator_adaptor_base(BOOST_RV_REF(scoped_allocator_adaptor_base) other) \ - : outer_allocator_type(::boost::move(other.outer_allocator())) \ - , m_inner(::boost::move(other.inner_allocator())) \ - {} \ - \ - template \ - scoped_allocator_adaptor_base(const scoped_allocator_adaptor_base& other) \ - : outer_allocator_type(other.outer_allocator()) \ - , m_inner(other.inner_allocator()) \ - {} \ - \ - template \ - scoped_allocator_adaptor_base \ - (BOOST_RV_REF_BEG scoped_allocator_adaptor_base BOOST_RV_REF_END other) \ - : outer_allocator_type(other.outer_allocator()) \ - , m_inner(other.inner_allocator()) \ - {} \ - \ - public: \ - struct internal_type_t{}; \ - \ - template \ - scoped_allocator_adaptor_base \ - ( internal_type_t \ - , BOOST_FWD_REF(OuterA2) outerAlloc \ - , const inner_allocator_type &inner) \ - : outer_allocator_type(::boost::forward(outerAlloc)) \ - , m_inner(inner) \ - {} \ - \ - public: \ - scoped_allocator_adaptor_base &operator= \ - (BOOST_COPY_ASSIGN_REF(scoped_allocator_adaptor_base) other) \ - { \ - outer_allocator_type::operator=(other.outer_allocator()); \ - m_inner = other.inner_allocator(); \ - return *this; \ - } \ - \ - scoped_allocator_adaptor_base &operator=(BOOST_RV_REF(scoped_allocator_adaptor_base) other) \ - { \ - outer_allocator_type::operator=(boost::move(other.outer_allocator())); \ - m_inner = ::boost::move(other.inner_allocator()); \ - return *this; \ - } \ - \ - void swap(scoped_allocator_adaptor_base &r) \ - { \ - boost::container::swap_dispatch(this->outer_allocator(), r.outer_allocator()); \ - boost::container::swap_dispatch(this->m_inner, r.inner_allocator()); \ - } \ - \ - friend void swap(scoped_allocator_adaptor_base &l, scoped_allocator_adaptor_base &r) \ - { l.swap(r); } \ - \ - inner_allocator_type& inner_allocator() \ - { return m_inner; } \ - \ - inner_allocator_type const& inner_allocator() const \ - { return m_inner; } \ - \ - outer_allocator_type & outer_allocator() \ - { return static_cast(*this); } \ - \ - const outer_allocator_type &outer_allocator() const \ - { return static_cast(*this); } \ - \ - scoped_allocator_type select_on_container_copy_construction() const \ - { \ - return scoped_allocator_type \ - (internal_type_t() \ - ,outer_traits_type::select_on_container_copy_construction(this->outer_allocator()) \ - ,inner_traits_type::select_on_container_copy_construction(this->inner_allocator()) \ - ); \ - } \ - private: \ - inner_allocator_type m_inner; \ -}; \ -//! -#define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) -#include BOOST_PP_LOCAL_ITERATE() - -#endif //#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -//Specialization for adaptor without any InnerAlloc -template -class scoped_allocator_adaptor_base - < OuterAlloc - #if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - , true - BOOST_PP_ENUM_TRAILING(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, BOOST_CONTAINER_PP_IDENTITY, nat) - #endif - > - : public OuterAlloc -{ - BOOST_COPYABLE_AND_MOVABLE(scoped_allocator_adaptor_base) - public: - - template - struct rebind_base - { - typedef scoped_allocator_adaptor_base - ::template portable_rebind_alloc::type - #if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - , true - BOOST_PP_ENUM_TRAILING(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, BOOST_CONTAINER_PP_IDENTITY, container_detail::nat) - #endif - > other; - }; - - typedef OuterAlloc outer_allocator_type; - typedef allocator_traits outer_traits_type; - typedef scoped_allocator_adaptor inner_allocator_type; - typedef inner_allocator_type scoped_allocator_type; - typedef allocator_traits inner_traits_type; - typedef typename outer_traits_type:: - propagate_on_container_copy_assignment propagate_on_container_copy_assignment; - typedef typename outer_traits_type:: - propagate_on_container_move_assignment propagate_on_container_move_assignment; - typedef typename outer_traits_type:: - propagate_on_container_swap propagate_on_container_swap; - - scoped_allocator_adaptor_base() - {} - - template - scoped_allocator_adaptor_base(BOOST_FWD_REF(OuterA2) outerAlloc) - : outer_allocator_type(::boost::forward(outerAlloc)) - {} - - scoped_allocator_adaptor_base(const scoped_allocator_adaptor_base& other) - : outer_allocator_type(other.outer_allocator()) - {} - - scoped_allocator_adaptor_base(BOOST_RV_REF(scoped_allocator_adaptor_base) other) - : outer_allocator_type(::boost::move(other.outer_allocator())) - {} - - template - scoped_allocator_adaptor_base - (const scoped_allocator_adaptor_base< - OuterA2 - #if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - , true - BOOST_PP_ENUM_TRAILING(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, BOOST_CONTAINER_PP_IDENTITY, container_detail::nat) - #endif - >& other) - : outer_allocator_type(other.outer_allocator()) - {} - - template - scoped_allocator_adaptor_base - (BOOST_RV_REF_BEG scoped_allocator_adaptor_base< - OuterA2 - #if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - , true - BOOST_PP_ENUM_TRAILING(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, BOOST_CONTAINER_PP_IDENTITY, container_detail::nat) - #endif - > BOOST_RV_REF_END other) - : outer_allocator_type(other.outer_allocator()) - {} - - public: - struct internal_type_t{}; - - template - scoped_allocator_adaptor_base(internal_type_t, BOOST_FWD_REF(OuterA2) outerAlloc, const inner_allocator_type &) - : outer_allocator_type(::boost::forward(outerAlloc)) - {} - - public: - scoped_allocator_adaptor_base &operator=(BOOST_COPY_ASSIGN_REF(scoped_allocator_adaptor_base) other) - { - outer_allocator_type::operator=(other.outer_allocator()); - return *this; - } - - scoped_allocator_adaptor_base &operator=(BOOST_RV_REF(scoped_allocator_adaptor_base) other) - { - outer_allocator_type::operator=(boost::move(other.outer_allocator())); - return *this; - } - - void swap(scoped_allocator_adaptor_base &r) - { - boost::container::swap_dispatch(this->outer_allocator(), r.outer_allocator()); - } - - friend void swap(scoped_allocator_adaptor_base &l, scoped_allocator_adaptor_base &r) - { l.swap(r); } - - inner_allocator_type& inner_allocator() - { return static_cast(*this); } - - inner_allocator_type const& inner_allocator() const - { return static_cast(*this); } - - outer_allocator_type & outer_allocator() - { return static_cast(*this); } - - const outer_allocator_type &outer_allocator() const - { return static_cast(*this); } - - scoped_allocator_type select_on_container_copy_construction() const - { - return scoped_allocator_type - (internal_type_t() - ,outer_traits_type::select_on_container_copy_construction(this->outer_allocator()) - //Don't use inner_traits_type::select_on_container_copy_construction(this->inner_allocator()) - //as inner_allocator() is equal to *this and that would trigger an infinite loop - , this->inner_allocator() - ); - } -}; - -} //namespace container_detail { - -///@endcond - -//Scoped allocator -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - #if !defined(BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST) - - //! This class is a C++03-compatible implementation of std::scoped_allocator_adaptor. - //! The class template scoped_allocator_adaptor is an allocator template that specifies - //! the memory resource (the outer allocator) to be used by a container (as any other - //! allocator does) and also specifies an inner allocator resource to be passed to - //! the constructor of every element within the container. - //! - //! This adaptor is - //! instantiated with one outer and zero or more inner allocator types. If - //! instantiated with only one allocator type, the inner allocator becomes the - //! scoped_allocator_adaptor itself, thus using the same allocator resource for the - //! container and every element within the container and, if the elements themselves - //! are containers, each of their elements recursively. If instantiated with more than - //! one allocator, the first allocator is the outer allocator for use by the container, - //! the second allocator is passed to the constructors of the container's elements, - //! and, if the elements themselves are containers, the third allocator is passed to - //! the elements' elements, and so on. If containers are nested to a depth greater - //! than the number of allocators, the last allocator is used repeatedly, as in the - //! single-allocator case, for any remaining recursions. - //! - //! [Note: The - //! scoped_allocator_adaptor is derived from the outer allocator type so it can be - //! substituted for the outer allocator type in most expressions. -end note] - //! - //! In the construct member functions, `OUTERMOST(x)` is x if x does not have - //! an `outer_allocator()` member function and - //! `OUTERMOST(x.outer_allocator())` otherwise; `OUTERMOST_ALLOC_TRAITS(x)` is - //! `allocator_traits`. - //! - //! [Note: `OUTERMOST(x)` and - //! `OUTERMOST_ALLOC_TRAITS(x)` are recursive operations. It is incumbent upon - //! the definition of `outer_allocator()` to ensure that the recursion terminates. - //! It will terminate for all instantiations of scoped_allocator_adaptor. -end note] - template - class scoped_allocator_adaptor - - #else // #if !defined(BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST) - - template - class scoped_allocator_adaptor - - #endif // #if !defined(BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST) - -#else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - -template -class scoped_allocator_adaptor -#endif - : public container_detail::scoped_allocator_adaptor_base - -{ - BOOST_COPYABLE_AND_MOVABLE(scoped_allocator_adaptor) - - public: - /// @cond - typedef container_detail::scoped_allocator_adaptor_base - base_type; - typedef typename base_type::internal_type_t internal_type_t; - /// @endcond - typedef OuterAlloc outer_allocator_type; - //! Type: For exposition only - //! - typedef allocator_traits outer_traits_type; - //! Type: `scoped_allocator_adaptor` if `sizeof...(InnerAllocs)` is zero; otherwise, - //! `scoped_allocator_adaptor`. - typedef typename base_type::inner_allocator_type inner_allocator_type; - typedef allocator_traits inner_traits_type; - typedef typename outer_traits_type::value_type value_type; - typedef typename outer_traits_type::size_type size_type; - typedef typename outer_traits_type::difference_type difference_type; - typedef typename outer_traits_type::pointer pointer; - typedef typename outer_traits_type::const_pointer const_pointer; - typedef typename outer_traits_type::void_pointer void_pointer; - typedef typename outer_traits_type::const_void_pointer const_void_pointer; - //! Type: `true_type` if `allocator_traits::propagate_on_container_copy_assignment::value` is - //! true for any `Allocator` in the set of `OuterAlloc` and `InnerAllocs...`; otherwise, false_type. - typedef typename base_type:: - propagate_on_container_copy_assignment propagate_on_container_copy_assignment; - //! Type: `true_type` if `allocator_traits::propagate_on_container_move_assignment::value` is - //! true for any `Allocator` in the set of `OuterAlloc` and `InnerAllocs...`; otherwise, false_type. - typedef typename base_type:: - propagate_on_container_move_assignment propagate_on_container_move_assignment; - //! Type: `true_type` if `allocator_traits::propagate_on_container_swap::value` is true for any - //! `Allocator` in the set of `OuterAlloc` and `InnerAllocs...`; otherwise, false_type. - typedef typename base_type:: - propagate_on_container_swap propagate_on_container_swap; - - //! Type: Rebinds scoped allocator to - //! `typedef scoped_allocator_adaptor - //! < typename outer_traits_type::template portable_rebind_alloc::type - //! , InnerAllocs... >` - template - struct rebind - { - typedef scoped_allocator_adaptor - < typename outer_traits_type::template portable_rebind_alloc::type - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , InnerAllocs... - #else - BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS, Q) - #endif - > other; - }; - - //! Effects: value-initializes the OuterAlloc base class - //! and the inner allocator object. - scoped_allocator_adaptor() - {} - - ~scoped_allocator_adaptor() - {} - - //! Effects: initializes each allocator within the adaptor with - //! the corresponding allocator from other. - scoped_allocator_adaptor(const scoped_allocator_adaptor& other) - : base_type(other.base()) - {} - - //! Effects: move constructs each allocator within the adaptor with - //! the corresponding allocator from other. - scoped_allocator_adaptor(BOOST_RV_REF(scoped_allocator_adaptor) other) - : base_type(::boost::move(other.base())) - {} - - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Requires: OuterAlloc shall be constructible from OuterA2. - //! - //! Effects: initializes the OuterAlloc base class with boost::forward(outerAlloc) and inner - //! with innerAllocs...(hence recursively initializing each allocator within the adaptor with the - //! corresponding allocator from the argument list). - template - scoped_allocator_adaptor(BOOST_FWD_REF(OuterA2) outerAlloc, const InnerAllocs & ...innerAllocs) - : base_type(::boost::forward(outerAlloc), innerAllocs...) - {} - #else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - #define BOOST_PP_LOCAL_MACRO(n) \ - template \ - scoped_allocator_adaptor(BOOST_FWD_REF(OuterA2) outerAlloc \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_CONST_REF_PARAM_LIST_Q, _)) \ - : base_type(::boost::forward(outerAlloc) \ - BOOST_PP_ENUM_TRAILING_PARAMS(n, q) \ - ) \ - {} \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Requires: OuterAlloc shall be constructible from OuterA2. - //! - //! Effects: initializes each allocator within the adaptor with the corresponding allocator from other. - template - scoped_allocator_adaptor(const scoped_allocator_adaptor &other) - : base_type(other.base()) - {} - - //! Requires: OuterAlloc shall be constructible from OuterA2. - //! - //! Effects: initializes each allocator within the adaptor with the corresponding allocator - //! rvalue from other. - template - scoped_allocator_adaptor(BOOST_RV_REF_BEG scoped_allocator_adaptor BOOST_RV_REF_END other) - : base_type(::boost::move(other.base())) - {} - - scoped_allocator_adaptor &operator=(BOOST_COPY_ASSIGN_REF(scoped_allocator_adaptor) other) - { return static_cast(base_type::operator=(static_cast(other))); } - - scoped_allocator_adaptor &operator=(BOOST_RV_REF(scoped_allocator_adaptor) other) - { return static_cast(base_type::operator=(boost::move(static_cast(other)))); } - - #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED - //! Effects: swaps *this with r. - //! - void swap(scoped_allocator_adaptor &r); - - //! Effects: swaps *this with r. - //! - friend void swap(scoped_allocator_adaptor &l, scoped_allocator_adaptor &r); - - //! Returns: - //! `static_cast(*this)`. - outer_allocator_type & outer_allocator(); - - //! Returns: - //! `static_cast(*this)`. - const outer_allocator_type &outer_allocator() const; - - //! Returns: - //! *this if `sizeof...(InnerAllocs)` is zero; otherwise, inner. - inner_allocator_type& inner_allocator(); - - //! Returns: - //! *this if `sizeof...(InnerAllocs)` is zero; otherwise, inner. - inner_allocator_type const& inner_allocator() const; - - #endif //BOOST_CONTAINER_DOXYGEN_INVOKED - - //! Returns: - //! `allocator_traits::max_size(outer_allocator())`. - size_type max_size() const - { - return outer_traits_type::max_size(this->outer_allocator()); - } - - //! Effects: - //! calls `OUTERMOST_ALLOC_TRAITS(*this)::destroy(OUTERMOST(*this), p)`. - template - void destroy(T* p) - { - allocator_traits::type> - ::destroy(get_outermost_allocator(this->outer_allocator()), p); - } - - //! Returns: - //! `allocator_traits::allocate(outer_allocator(), n)`. - pointer allocate(size_type n) - { - return outer_traits_type::allocate(this->outer_allocator(), n); - } - - //! Returns: - //! `allocator_traits::allocate(outer_allocator(), n, hint)`. - pointer allocate(size_type n, const_void_pointer hint) - { - return outer_traits_type::allocate(this->outer_allocator(), n, hint); - } - - //! Effects: - //! `allocator_traits::deallocate(outer_allocator(), p, n)`. - void deallocate(pointer p, size_type n) - { - outer_traits_type::deallocate(this->outer_allocator(), p, n); - } - - #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED - //! Returns: Allocator new scoped_allocator_adaptor object where each allocator - //! A in the adaptor is initialized from the result of calling - //! `allocator_traits::select_on_container_copy_construction()` on - //! the corresponding allocator in *this. - scoped_allocator_adaptor select_on_container_copy_construction() const; - #endif //BOOST_CONTAINER_DOXYGEN_INVOKED - - /// @cond - base_type &base() { return *this; } - - const base_type &base() const { return *this; } - /// @endcond - - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: - //! 1) If `uses_allocator::value` is false calls - //! `OUTERMOST_ALLOC_TRAITS(*this)::construct - //! (OUTERMOST(*this), p, std::forward(args)...)`. - //! - //! 2) Otherwise, if `uses_allocator::value` is true and - //! `is_constructible::value` is true, calls - //! `OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST(*this), p, allocator_arg, - //! inner_allocator(), std::forward(args)...)`. - //! - //! [Note: In compilers without advanced decltype SFINAE support, `is_constructible` can't - //! be implemented so that condition will be replaced by - //! constructible_with_allocator_prefix::value. -end note] - //! - //! 3) Otherwise, if uses_allocator::value is true and - //! `is_constructible::value` is true, calls - //! `OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST(*this), p, - //! std::forward(args)..., inner_allocator())`. - //! - //! [Note: In compilers without advanced decltype SFINAE support, `is_constructible` can't be - //! implemented so that condition will be replaced by - //! `constructible_with_allocator_suffix::value`. -end note] - //! - //! 4) Otherwise, the program is ill-formed. - //! - //! [Note: An error will result if `uses_allocator` evaluates - //! to true but the specific constructor does not take an allocator. This definition prevents a silent - //! failure to pass an inner allocator to a contained element. -end note] - template < typename T, class ...Args> - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - void - #else - typename container_detail::enable_if_c::value, void>::type - #endif - construct(T* p, BOOST_FWD_REF(Args)...args) - { - container_detail::dispatch_uses_allocator - ( uses_allocator() - , get_outermost_allocator(this->outer_allocator()) - , this->inner_allocator() - , p, ::boost::forward(args)...); - } - - #else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //Disable this overload if the first argument is pair as some compilers have - //overload selection problems when the first parameter is a pair. - #define BOOST_PP_LOCAL_MACRO(n) \ - template < typename T \ - BOOST_PP_ENUM_TRAILING_PARAMS(n, class P) \ - > \ - typename container_detail::enable_if_c::value, void>::type \ - construct(T* p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - container_detail::dispatch_uses_allocator \ - ( uses_allocator() \ - , get_outermost_allocator(this->outer_allocator()) \ - , this->inner_allocator() \ - , p BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - template - void construct(std::pair* p) - { this->construct_pair(p); } - - template - void construct(container_detail::pair* p) - { this->construct_pair(p); } - - template - void construct(std::pair* p, BOOST_FWD_REF(U) x, BOOST_FWD_REF(V) y) - { this->construct_pair(p, ::boost::forward(x), ::boost::forward(y)); } - - template - void construct(container_detail::pair* p, BOOST_FWD_REF(U) x, BOOST_FWD_REF(V) y) - { this->construct_pair(p, ::boost::forward(x), ::boost::forward(y)); } - - template - void construct(std::pair* p, const std::pair& x) - { this->construct_pair(p, x); } - - template - void construct( container_detail::pair* p - , const container_detail::pair& x) - { this->construct_pair(p, x); } - - template - void construct( std::pair* p - , BOOST_RV_REF_BEG std::pair BOOST_RV_REF_END x) - { this->construct_pair(p, x); } - - template - void construct( container_detail::pair* p - , BOOST_RV_REF_BEG container_detail::pair BOOST_RV_REF_END x) - { this->construct_pair(p, x); } - - /// @cond - private: - template - void construct_pair(Pair* p) - { - this->construct(container_detail::addressof(p->first)); - BOOST_TRY{ - this->construct(container_detail::addressof(p->second)); - } - BOOST_CATCH(...){ - this->destroy(container_detail::addressof(p->first)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - template - void construct_pair(Pair* p, BOOST_FWD_REF(U) x, BOOST_FWD_REF(V) y) - { - this->construct(container_detail::addressof(p->first), ::boost::forward(x)); - BOOST_TRY{ - this->construct(container_detail::addressof(p->second), ::boost::forward(y)); - } - BOOST_CATCH(...){ - this->destroy(container_detail::addressof(p->first)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - template - void construct_pair(Pair* p, const Pair2& pr) - { - this->construct(container_detail::addressof(p->first), pr.first); - BOOST_TRY{ - this->construct(container_detail::addressof(p->second), pr.second); - } - BOOST_CATCH(...){ - this->destroy(container_detail::addressof(p->first)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - template - void construct_pair(Pair* p, BOOST_RV_REF(Pair2) pr) - { - this->construct(container_detail::addressof(p->first), ::boost::move(pr.first)); - BOOST_TRY{ - this->construct(container_detail::addressof(p->second), ::boost::move(pr.second)); - } - BOOST_CATCH(...){ - this->destroy(container_detail::addressof(p->first)); - BOOST_RETHROW - } - BOOST_CATCH_END - } - - //template - //void construct(pair* p, piecewise_construct_t, tuple x, tuple y); - - public: - //Internal function - template - scoped_allocator_adaptor(internal_type_t, BOOST_FWD_REF(OuterA2) outer, const inner_allocator_type& inner) - : base_type(internal_type_t(), ::boost::forward(outer), inner) - {} - - /// @endcond -}; - -template -inline bool operator==( - const scoped_allocator_adaptor& a, - const scoped_allocator_adaptor& b) -{ - #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - const bool has_zero_inner = sizeof...(InnerAllocs) == 0u; - #else - const bool has_zero_inner = - boost::container::container_detail::is_same - ::value; - #endif - - return a.outer_allocator() == b.outer_allocator() - && (has_zero_inner || a.inner_allocator() == b.inner_allocator()); -} - -template -inline bool operator!=( - const scoped_allocator_adaptor& a, - const scoped_allocator_adaptor& b) -{ - return ! (a == b); -} - -}} // namespace boost { namespace container { - -#include - -#endif // BOOST_CONTAINER_ALLOCATOR_SCOPED_ALLOCATOR_HPP diff --git a/utils/boost_idb/boost/container/scoped_allocator_fwd.hpp b/utils/boost_idb/boost/container/scoped_allocator_fwd.hpp deleted file mode 100644 index 4c066b0a..00000000 --- a/utils/boost_idb/boost/container/scoped_allocator_fwd.hpp +++ /dev/null @@ -1,83 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_ALLOCATOR_SCOPED_ALLOCATOR_FWD_HPP -#define BOOST_CONTAINER_ALLOCATOR_SCOPED_ALLOCATOR_FWD_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include - -#if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) -#include -#include -#endif - -namespace boost { namespace container { - -///@cond - -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - #if !defined(BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST) - - template - class scoped_allocator_adaptor; - - #else // #if !defined(BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST) - - template - class scoped_allocator_adaptor; - - template - class scoped_allocator_adaptor; - - #endif // #if !defined(BOOST_CONTAINER_UNIMPLEMENTED_PACK_EXPANSION_TO_FIXED_LIST) - - -#else // #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - -template -class scoped_allocator_adaptor; - -#endif - -///@endcond - -//! The allocator_arg_t struct is an empty structure type used as a unique type to -//! disambiguate constructor and function overloading. Specifically, several types -//! have constructors with allocator_arg_t as the first argument, immediately followed -//! by an argument of a type that satisfies the Allocator requirements -struct allocator_arg_t{}; - -//! A instance of type allocator_arg_t -//! -static const allocator_arg_t allocator_arg = allocator_arg_t(); - -template -struct constructible_with_allocator_suffix; - -template -struct constructible_with_allocator_prefix; - -template -struct uses_allocator; - -}} // namespace boost { namespace container { - -#include - -#endif // BOOST_CONTAINER_ALLOCATOR_SCOPED_ALLOCATOR_FWD_HPP diff --git a/utils/boost_idb/boost/container/set.hpp b/utils/boost_idb/boost/container/set.hpp deleted file mode 100644 index 96656f3b..00000000 --- a/utils/boost_idb/boost/container/set.hpp +++ /dev/null @@ -1,1298 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_SET_HPP -#define BOOST_CONTAINER_SET_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#ifndef BOOST_CONTAINER_PERFECT_FORWARDING -#include -#endif - -namespace boost { -namespace container { - -/// @cond -// Forward declarations of operators < and ==, needed for friend declaration. -template -inline bool operator==(const set& x, - const set& y); - -template -inline bool operator<(const set& x, - const set& y); -/// @endcond - -//! A set is a kind of associative container that supports unique keys (contains at -//! most one of each key value) and provides for fast retrieval of the keys themselves. -//! Class set supports bidirectional iterators. -//! -//! A set satisfies all of the requirements of a container and of a reversible container -//! , and of an associative container. A set also provides most operations described in -//! for unique keys. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class set -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(set) - typedef container_detail::rbtree, Compare, Allocator> tree_t; - tree_t m_tree; // red-black tree representing set - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Key key_type; - typedef Key value_type; - typedef Compare key_compare; - typedef Compare value_compare; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs an empty set. - //! - //! Complexity: Constant. - set() - : m_tree() - {} - - //! Effects: Constructs an empty set using the specified comparison object - //! and allocator. - //! - //! Complexity: Constant. - explicit set(const Compare& comp, - const allocator_type& a = allocator_type()) - : m_tree(comp, a) - {} - - //! Effects: Constructs an empty set using the specified allocator object. - //! - //! Complexity: Constant. - explicit set(const allocator_type& a) - : m_tree(a) - {} - - //! Effects: Constructs an empty set using the specified comparison object and - //! allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - set(InputIterator first, InputIterator last, const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_tree(true, first, last, comp, a) - {} - - //! Effects: Constructs an empty set using the specified comparison object and - //! allocator, and inserts elements from the ordered unique range [first ,last). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate and must be - //! unique values. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - set( ordered_unique_range_t, InputIterator first, InputIterator last - , const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a set. - //! - //! Complexity: Linear in x.size(). - set(const set& x) - : m_tree(x.m_tree) - {} - - //! Effects: Move constructs a set. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - set(BOOST_RV_REF(set) x) - : m_tree(boost::move(x.m_tree)) - {} - - //! Effects: Copy constructs a set using the specified allocator. - //! - //! Complexity: Linear in x.size(). - set(const set& x, const allocator_type &a) - : m_tree(x.m_tree, a) - {} - - //! Effects: Move constructs a set using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - set(BOOST_RV_REF(set) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) - {} - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - set& operator=(BOOST_COPY_ASSIGN_REF(set) x) - { m_tree = x.m_tree; return *this; } - - //! Effects: this->swap(x.get()). - //! - //! Complexity: Constant. - set& operator=(BOOST_RV_REF(set) x) - { m_tree = boost::move(x.m_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const - { return m_tree.get_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const - { return m_tree.get_stored_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() - { return m_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant - iterator begin() - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const - { return m_tree.begin(); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() - { return m_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const - { return m_tree.end(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() - { return m_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const - { return m_tree.rbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() - { return m_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const - { return m_tree.rend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const - { return m_tree.cbegin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const - { return m_tree.cend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const - { return m_tree.crbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const - { return m_tree.crend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const - { return m_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const - { return m_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object x of type Key constructed with - //! std::forward(args)... if and only if there is - //! no element in the container with equivalent value. - //! and returns the iterator pointing to the - //! newly inserted element. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Throws: If memory allocation throws or - //! Key's in-place constructor throws. - //! - //! Complexity: Logarithmic. - template - std::pair emplace(Args&&... args) - { return m_tree.emplace_unique(boost::forward(args)...); } - - //! Effects: Inserts an object of type Key constructed with - //! std::forward(args)... if and only if there is - //! no element in the container with equivalent value. - //! p is a hint pointing to where the insert - //! should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_unique(hint, boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_unique(hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts x if and only if there is no element in the container - //! with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(const value_type &x); - - //! Effects: Move constructs a new value from x if and only if there is - //! no element in the container with key equivalent to the key of x. - //! - //! Returns: The bool component of the returned pair is true if and only - //! if the insertion takes place, and the iterator component of the pair - //! points to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - std::pair insert(value_type &&x); - #else - private: - typedef std::pair insert_return_pair; - public: - BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, insert_return_pair, this->priv_insert) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x in the container if and only if there is - //! no element in the container with key equivalent to the key of x. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator p, const value_type &x); - - //! Effects: Inserts an element move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent to the key of x. - //! - //! Complexity: Logarithmic. - iterator insert(const_iterator position, value_type &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) if and only - //! if there is no element with key equivalent to the key of that element. - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - template - void insert(InputIterator first, InputIterator last) - { m_tree.insert_unique(first, last); } - - //! Effects: Erases the element pointed to by p. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Amortized constant time - iterator erase(const_iterator p) - { return m_tree.erase(p); } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) - { return m_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) - { return m_tree.erase(first, last); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(set& x) - { m_tree.swap(x.m_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() - { m_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return m_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } - - //! Returns: Allocator const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return static_cast(m_tree.find(x) != m_tree.end()); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const set&, const set&); - - template - friend bool operator< (const set&, const set&); - - private: - template - std::pair priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_unique(::boost::forward(x)); } - - template - iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_unique(p, ::boost::forward(x)); } - /// @endcond -}; - -template -inline bool operator==(const set& x, - const set& y) -{ return x.m_tree == y.m_tree; } - -template -inline bool operator<(const set& x, - const set& y) -{ return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const set& x, - const set& y) -{ return !(x == y); } - -template -inline bool operator>(const set& x, - const set& y) -{ return y < x; } - -template -inline bool operator<=(const set& x, - const set& y) -{ return !(y < x); } - -template -inline bool operator>=(const set& x, - const set& y) -{ return !(x < y); } - -template -inline void swap(set& x, set& y) -{ x.swap(y); } - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -namespace container { - -// Forward declaration of operators < and ==, needed for friend declaration. - -template -inline bool operator==(const multiset& x, - const multiset& y); - -template -inline bool operator<(const multiset& x, - const multiset& y); -/// @endcond - -//! A multiset is a kind of associative container that supports equivalent keys -//! (possibly contains multiple copies of the same key value) and provides for -//! fast retrieval of the keys themselves. Class multiset supports bidirectional iterators. -//! -//! A multiset satisfies all of the requirements of a container and of a reversible -//! container, and of an associative container). multiset also provides most operations -//! described for duplicate keys. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class multiset -{ - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(multiset) - typedef container_detail::rbtree, Compare, Allocator> tree_t; - tree_t m_tree; // red-black tree representing multiset - /// @endcond - - public: - - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Key key_type; - typedef Key value_type; - typedef Compare key_compare; - typedef Compare value_compare; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Constructs an empty multiset using the specified comparison - //! object and allocator. - //! - //! Complexity: Constant. - multiset() - : m_tree() - {} - - //! Effects: Constructs an empty multiset using the specified comparison - //! object and allocator. - //! - //! Complexity: Constant. - explicit multiset(const Compare& comp, - const allocator_type& a = allocator_type()) - : m_tree(comp, a) - {} - - //! Effects: Constructs an empty multiset using the specified allocator. - //! - //! Complexity: Constant. - explicit multiset(const allocator_type& a) - : m_tree(a) - {} - - //! Effects: Constructs an empty multiset using the specified comparison object - //! and allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. - template - multiset(InputIterator first, InputIterator last, - const Compare& comp = Compare(), - const allocator_type& a = allocator_type()) - : m_tree(false, first, last, comp, a) - {} - - //! Effects: Constructs an empty multiset using the specified comparison object and - //! allocator, and inserts elements from the ordered range [first ,last ). This function - //! is more efficient than the normal range creation for ordered ranges. - //! - //! Requires: [first ,last) must be ordered according to the predicate. - //! - //! Complexity: Linear in N. - //! - //! Note: Non-standard extension. - template - multiset( ordered_range_t, InputIterator first, InputIterator last - , const Compare& comp = Compare() - , const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) - {} - - //! Effects: Copy constructs a multiset. - //! - //! Complexity: Linear in x.size(). - multiset(const multiset& x) - : m_tree(x.m_tree) - {} - - //! Effects: Move constructs a multiset. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. - multiset(BOOST_RV_REF(multiset) x) - : m_tree(boost::move(x.m_tree)) - {} - - //! Effects: Copy constructs a multiset using the specified allocator. - //! - //! Complexity: Linear in x.size(). - multiset(const multiset& x, const allocator_type &a) - : m_tree(x.m_tree, a) - {} - - //! Effects: Move constructs a multiset using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - //! - //! Postcondition: x is emptied. - multiset(BOOST_RV_REF(multiset) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) - {} - - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). - multiset& operator=(BOOST_COPY_ASSIGN_REF(multiset) x) - { m_tree = x.m_tree; return *this; } - - //! Effects: this->swap(x.get()). - //! - //! Complexity: Constant. - multiset& operator=(BOOST_RV_REF(multiset) x) - { m_tree = boost::move(x.m_tree); return *this; } - - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const - { return m_tree.get_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() - { return m_tree.get_stored_allocator(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const - { return m_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const - { return m_tree.begin(); } - - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() - { return m_tree.end(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const - { return m_tree.end(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() - { return m_tree.rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const - { return m_tree.rbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() - { return m_tree.rend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const - { return m_tree.rend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const - { return m_tree.cbegin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const - { return m_tree.cend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const - { return m_tree.crbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const - { return m_tree.crend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const - { return m_tree.empty(); } - - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const - { return m_tree.size(); } - - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type Key constructed with - //! std::forward(args)... and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic. - template - iterator emplace(Args&&... args) - { return m_tree.emplace_equal(boost::forward(args)...); } - - //! Effects: Inserts an object of type Key constructed with - //! std::forward(args)... - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - template - iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_equal(hint, boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_hint(const_iterator hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_equal(hint \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - - - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts x and returns the iterator pointing to the - //! newly inserted element. - //! - //! Complexity: Logarithmic. - iterator insert(const value_type &x); - - //! Effects: Inserts a copy of x in the container. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(value_type &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, iterator, this->priv_insert) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator p, const value_type &x); - - //! Effects: Inserts a value move constructed from x in the container. - //! p is a hint pointing to where the insert should start to search. - //! - //! Returns: An iterator pointing to the element with key equivalent - //! to the key of x. - //! - //! Complexity: Logarithmic in general, but amortized constant if t - //! is inserted right before p. - iterator insert(const_iterator position, value_type &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: first, last are not iterators into *this. - //! - //! Effects: inserts each element from the range [first,last) . - //! - //! Complexity: At most N log(size()+N) (N is the distance from first to last) - template - void insert(InputIterator first, InputIterator last) - { m_tree.insert_equal(first, last); } - - //! Effects: Erases the element pointed to by p. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Amortized constant time - iterator erase(const_iterator p) - { return m_tree.erase(p); } - - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) - { return m_tree.erase(x); } - - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) - { return m_tree.erase(first, last); } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(multiset& x) - { m_tree.swap(x.m_tree); } - - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() - { m_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return m_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } - - //! Returns: Allocator const iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_tree.count(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const multiset&, - const multiset&); - template - friend bool operator< (const multiset&, - const multiset&); - private: - template - iterator priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_equal(::boost::forward(x)); } - - template - iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_equal(p, ::boost::forward(x)); } - - /// @endcond -}; - -template -inline bool operator==(const multiset& x, - const multiset& y) -{ return x.m_tree == y.m_tree; } - -template -inline bool operator<(const multiset& x, - const multiset& y) -{ return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const multiset& x, - const multiset& y) -{ return !(x == y); } - -template -inline bool operator>(const multiset& x, - const multiset& y) -{ return y < x; } - -template -inline bool operator<=(const multiset& x, - const multiset& y) -{ return !(y < x); } - -template -inline bool operator>=(const multiset& x, - const multiset& y) -{ return !(x < y); } - -template -inline void swap(multiset& x, multiset& y) -{ x.swap(y); } - -/// @cond - -} //namespace container { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > -{ - static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; -}; - -namespace container { - -/// @endcond - -}} - -#include - -#endif /* BOOST_CONTAINER_SET_HPP */ - diff --git a/utils/boost_idb/boost/container/slist.hpp b/utils/boost_idb/boost/container/slist.hpp deleted file mode 100644 index 9d2d7618..00000000 --- a/utils/boost_idb/boost/container/slist.hpp +++ /dev/null @@ -1,1627 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_SLIST_HPP -#define BOOST_CONTAINER_SLIST_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) -//Preprocessor library to emulate perfect forwarding -#else -#include -#endif - -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond - -template -class slist; - -namespace container_detail { - -template -struct slist_hook -{ - typedef typename container_detail::bi::make_slist_base_hook - , container_detail::bi::link_mode >::type type; -}; - -template -struct slist_node - : public slist_hook::type -{ - private: - slist_node(); - - public: - typedef T value_type; - typedef typename slist_hook::type hook_type; - - T m_data; - - T &get_data() - { return this->m_data; } - - const T &get_data() const - { return this->m_data; } -}; - -template -struct intrusive_slist_type -{ - typedef boost::container::allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::value_type value_type; - typedef typename boost::intrusive::pointer_traits - ::template - rebind_pointer::type - void_pointer; - typedef typename container_detail::slist_node - node_type; - - typedef typename container_detail::bi::make_slist - ::type> - ,container_detail::bi::constant_time_size - , container_detail::bi::size_type - - >::type container_type; - typedef container_type type ; -}; - -} //namespace container_detail { - -/// @endcond - -//! An slist is a singly linked list: a list where each element is linked to the next -//! element, but not to the previous element. That is, it is a Sequence that -//! supports forward but not backward traversal, and (amortized) constant time -//! insertion and removal of elements. Slists, like lists, have the important -//! property that insertion and splicing do not invalidate iterators to list elements, -//! and that even removal invalidates only the iterators that point to the elements -//! that are removed. The ordering of iterators may be changed (that is, -//! slist::iterator might have a different predecessor or successor after a list -//! operation than it did before), but the iterators themselves will not be invalidated -//! or made to point to different elements unless that invalidation or mutation is explicit. -//! -//! The main difference between slist and list is that list's iterators are bidirectional -//! iterators, while slist's iterators are forward iterators. This means that slist is -//! less versatile than list; frequently, however, bidirectional iterators are -//! unnecessary. You should usually use slist unless you actually need the extra -//! functionality of list, because singly linked lists are smaller and faster than double -//! linked lists. -//! -//! Important performance note: like every other Sequence, slist defines the member -//! functions insert and erase. Using these member functions carelessly, however, can -//! result in disastrously slow programs. The problem is that insert's first argument is -//! an iterator p, and that it inserts the new element(s) before p. This means that -//! insert must find the iterator just before p; this is a constant-time operation -//! for list, since list has bidirectional iterators, but for slist it must find that -//! iterator by traversing the list from the beginning up to p. In other words: -//! insert and erase are slow operations anywhere but near the beginning of the slist. -//! -//! Slist provides the member functions insert_after and erase_after, which are constant -//! time operations: you should always use insert_after and erase_after whenever -//! possible. If you find that insert_after and erase_after aren't adequate for your -//! needs, and that you often need to use insert and erase in the middle of the list, -//! then you should probably use list instead of slist. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else -template -#endif -class slist - : protected container_detail::node_alloc_holder - ::type> -{ - /// @cond - typedef typename - container_detail::intrusive_slist_type::type Icont; - typedef container_detail::node_alloc_holder AllocHolder; - typedef typename AllocHolder::NodePtr NodePtr; - typedef typename AllocHolder::NodeAlloc NodeAlloc; - typedef typename AllocHolder::ValAlloc ValAlloc; - typedef typename AllocHolder::Node Node; - typedef container_detail::allocator_destroyer Destroyer; - typedef typename AllocHolder::allocator_v1 allocator_v1; - typedef typename AllocHolder::allocator_v2 allocator_v2; - typedef typename AllocHolder::alloc_version alloc_version; - typedef boost::container::allocator_traits allocator_traits_type; - - class equal_to_value - { - typedef typename AllocHolder::value_type value_type; - const value_type &t_; - - public: - equal_to_value(const value_type &t) - : t_(t) - {} - - bool operator()(const value_type &t)const - { return t_ == t; } - }; - - template - struct ValueCompareToNodeCompare - : Pred - { - ValueCompareToNodeCompare(Pred pred) - : Pred(pred) - {} - - bool operator()(const Node &a, const Node &b) const - { return static_cast(*this)(a.m_data, b.m_data); } - - bool operator()(const Node &a) const - { return static_cast(*this)(a.m_data); } - }; - - BOOST_COPYABLE_AND_MOVABLE(slist) - typedef container_detail::iterator iterator_impl; - typedef container_detail::iterator const_iterator_impl; - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - - typedef T value_type; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef BOOST_CONTAINER_IMPDEF(NodeAlloc) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(iterator_impl) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_iterator_impl) const_iterator; - - public: - - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Constructs a list taking the allocator as parameter. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - slist() - : AllocHolder() - {} - - //! Effects: Constructs a list taking the allocator as parameter. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - explicit slist(const allocator_type& a) BOOST_CONTAINER_NOEXCEPT - : AllocHolder(a) - {} - - explicit slist(size_type n) - : AllocHolder(allocator_type()) - { this->resize(n); } - - //! Effects: Constructs a list that will use a copy of allocator a - //! and inserts n copies of value. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - explicit slist(size_type n, const value_type& x, const allocator_type& a = allocator_type()) - : AllocHolder(a) - { this->insert_after(this->cbefore_begin(), n, x); } - - //! Effects: Constructs a list that will use a copy of allocator a - //! and inserts a copy of the range [first, last) in the list. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's constructor taking an dereferenced InIt throws. - //! - //! Complexity: Linear to the range [first, last). - template - slist(InpIt first, InpIt last, const allocator_type& a = allocator_type()) - : AllocHolder(a) - { this->insert_after(this->cbefore_begin(), first, last); } - - //! Effects: Copy constructs a list. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocator_type's default constructor or copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - slist(const slist& x) - : AllocHolder(x) - { this->insert_after(this->cbefore_begin(), x.begin(), x.end()); } - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - slist(BOOST_RV_REF(slist) x) - : AllocHolder(boost::move(static_cast(x))) - {} - - //! Effects: Copy constructs a list using the specified allocator. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocator_type's default constructor or copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - slist(const slist& x, const allocator_type &a) - : AllocHolder(a) - { this->insert_after(this->cbefore_begin(), x.begin(), x.end()); } - - //! Effects: Move constructor using the specified allocator. - //! Moves x's resources to *this. - //! - //! Throws: If allocation or value_type's copy constructor throws. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - slist(BOOST_RV_REF(slist) x, const allocator_type &a) - : AllocHolder(a) - { - if(this->node_alloc() == x.node_alloc()){ - this->icont().swap(x.icont()); - } - else{ - this->insert(this->cbegin(), x.begin(), x.end()); - } - } - - //! Effects: Destroys the list. All stored values are destroyed - //! and used memory is deallocated. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements. - ~slist() BOOST_CONTAINER_NOEXCEPT - {} //AllocHolder clears the slist - - //! Effects: Makes *this contain the same elements as x. - //! - //! Postcondition: this->size() == x.size(). *this contains a copy - //! of each of x's elements. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to the number of elements in x. - slist& operator= (BOOST_COPY_ASSIGN_REF(slist) x) - { - if (&x != this){ - NodeAlloc &this_alloc = this->node_alloc(); - const NodeAlloc &x_alloc = x.node_alloc(); - container_detail::bool_ flag; - if(flag && this_alloc != x_alloc){ - this->clear(); - } - this->AllocHolder::copy_assign_alloc(x); - this->assign(x.begin(), x.end()); - } - return *this; - } - - //! Effects: Makes *this contain the same elements as x. - //! - //! Postcondition: this->size() == x.size(). *this contains a copy - //! of each of x's elements. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to the number of elements in x. - slist& operator= (BOOST_RV_REF(slist) x) - { - if (&x != this){ - NodeAlloc &this_alloc = this->node_alloc(); - NodeAlloc &x_alloc = x.node_alloc(); - //If allocators a re equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy and swap pointers - this->clear(); - this->icont() = boost::move(x.icont()); - //Move allocator if needed - this->AllocHolder::move_assign_alloc(x); - } - //If unequal allocators, then do a one by one move - else{ - this->assign( boost::make_move_iterator(x.begin()) - , boost::make_move_iterator(x.end())); - } - } - return *this; - } - - //! Effects: Assigns the n copies of val to *this. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - void assign(size_type n, const T& val) - { - typedef constant_iterator cvalue_iterator; - return this->assign(cvalue_iterator(val, n), cvalue_iterator()); - } - - //! Effects: Assigns the range [first, last) to *this. - //! - //! Throws: If memory allocation throws or - //! T's constructor from dereferencing InpIt throws. - //! - //! Complexity: Linear to n. - template - void assign(InpIt first, InpIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - >::type * = 0 - #endif - ) - { - iterator end_n(this->end()); - iterator prev(this->before_begin()); - iterator node(this->begin()); - while (node != end_n && first != last){ - *node = *first; - prev = node; - ++node; - ++first; - } - if (first != last) - this->insert_after(prev, first, last); - else - this->erase_after(prev, end_n); - } - - //! Effects: Returns a copy of the internal allocator. - //! - //! Throws: If allocator's copy constructor throws. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return allocator_type(this->node_alloc()); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return this->node_alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->node_alloc(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns a non-dereferenceable iterator that, - //! when incremented, yields begin(). This iterator may be used - //! as the argument to insert_after, erase_after, etc. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator before_begin() BOOST_CONTAINER_NOEXCEPT - { return iterator(end()); } - - //! Effects: Returns a non-dereferenceable const_iterator - //! that, when incremented, yields begin(). This iterator may be used - //! as the argument to insert_after, erase_after, etc. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator before_begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbefore_begin(); } - - //! Effects: Returns an iterator to the first element contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->icont().begin()); } - - //! Effects: Returns a const_iterator to the first element contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbegin(); } - - //! Effects: Returns an iterator to the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->icont().end()); } - - //! Effects: Returns a const_iterator to the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } - - //! Effects: Returns a non-dereferenceable const_iterator - //! that, when incremented, yields begin(). This iterator may be used - //! as the argument to insert_after, erase_after, etc. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbefore_begin() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(end()); } - - //! Effects: Returns a const_iterator to the first element contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->non_const_icont().begin()); } - - //! Effects: Returns a const_iterator to the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->non_const_icont().end()); } - - //! Returns: The iterator to the element before i in the sequence. - //! Returns the end-iterator, if either i is the begin-iterator or the - //! sequence is empty. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements before i. - //! - //! Note: Non-standard extension. - iterator previous(iterator p) BOOST_CONTAINER_NOEXCEPT - { return iterator(this->icont().previous(p.get())); } - - //! Returns: The const_iterator to the element before i in the sequence. - //! Returns the end-const_iterator, if either i is the begin-const_iterator or - //! the sequence is empty. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements before i. - //! - //! Note: Non-standard extension. - const_iterator previous(const_iterator p) - { return const_iterator(this->icont().previous(p.get())); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the list contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const - { return !this->size(); } - - //! Effects: Returns the number of the elements contained in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const - { return this->icont().size(); } - - //! Effects: Returns the largest possible size of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const - { return AllocHolder::max_size(); } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size) - { - const_iterator last_pos; - if(!priv_try_shrink(new_size, last_pos)){ - typedef value_init_construct_iterator value_init_iterator; - this->insert_after(last_pos, value_init_iterator(new_size - this->size()), value_init_iterator()); - } - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are copy constructed from x. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size, const T& x) - { - const_iterator last_pos; - if(!priv_try_shrink(new_size, last_pos)){ - this->insert_after(last_pos, new_size, x); - } - } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference front() - { return *this->begin(); } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the first element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference front() const - { return *this->begin(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the front of the list - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - template - void emplace_front(Args&&... args) - { this->emplace_after(this->cbefore_begin(), boost::forward(args)...); } - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... after prev - //! - //! Throws: If memory allocation throws or - //! T's in-place constructor throws. - //! - //! Complexity: Constant - template - iterator emplace_after(const_iterator prev, Args&&... args) - { - NodePtr pnode(AllocHolder::create_node(boost::forward(args)...)); - return iterator(this->icont().insert_after(prev.get(), *pnode)); - } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - void emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - this->emplace(this->cbegin() \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace_after(const_iterator prev \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - NodePtr pnode (AllocHolder::create_node \ - (BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ - return iterator(this->icont().insert_after(prev.get(), *pnode)); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the beginning of the list. - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - void push_front(const T &x); - - //! Effects: Constructs a new element in the beginning of the list - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - void push_front(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_front, T, void, priv_push_front) - #endif - - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Inserts a copy of the value after the position pointed - //! by prev_p. - //! - //! Returns: An iterator to the inserted element. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - //! - //! Note: Does not affect the validity of iterators and references of - //! previous values. - iterator insert_after(const_iterator prev_pos, const T &x); - - //! Requires: prev_pos must be a valid iterator of *this. - //! - //! Effects: Inserts a move constructed copy object from the value after the - //! p pointed by prev_pos. - //! - //! Returns: An iterator to the inserted element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - //! - //! Note: Does not affect the validity of iterators and references of - //! previous values. - iterator insert_after(const_iterator prev_pos, T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert_after, T, iterator, priv_insert_after, const_iterator, const_iterator) - #endif - - //! Requires: prev_pos must be a valid iterator of *this. - //! - //! Effects: Inserts n copies of x after prev_pos. - //! - //! Returns: an iterator to the last inserted element or prev_pos if n is 0. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! - //! Complexity: Linear to n. - //! - //! Note: Does not affect the validity of iterators and references of - //! previous values. - iterator insert_after(const_iterator prev_pos, size_type n, const value_type& x) - { - typedef constant_iterator cvalue_iterator; - return this->insert_after(prev_pos, cvalue_iterator(x, n), cvalue_iterator()); - } - - //! Requires: prev_pos must be a valid iterator of *this. - //! - //! Effects: Inserts the range pointed by [first, last) - //! after the position prev_pos. - //! - //! Returns: an iterator to the last inserted element or prev_pos if first == last. - //! - //! Throws: If memory allocation throws, T's constructor from a - //! dereferenced InpIt throws. - //! - //! Complexity: Linear to the number of elements inserted. - //! - //! Note: Does not affect the validity of iterators and references of - //! previous values. - template - iterator insert_after(const_iterator prev_pos, InpIt first, InpIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && (container_detail::is_input_iterator::value - || container_detail::is_same::value - ) - >::type * = 0 - #endif - ) - { - iterator ret_it(prev_pos.get()); - for (; first != last; ++first){ - ret_it = iterator(this->icont().insert_after(ret_it.get(), *this->create_node_from_it(first))); - } - return ret_it; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - iterator insert_after(const_iterator prev, FwdIt first, FwdIt last - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !(container_detail::is_input_iterator::value - || container_detail::is_same::value - ) - >::type * = 0 - ) - { - //Optimized allocation and construction - insertion_functor func(this->icont(), prev.get()); - this->allocate_many_and_construct(first, std::distance(first, last), func); - return iterator(func.inserted_first()); - } - #endif - - //! Effects: Removes the first element from the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Amortized constant time. - void pop_front() - { this->icont().pop_front_and_dispose(Destroyer(this->node_alloc())); } - - //! Effects: Erases the element after the element pointed by prev_pos - //! of the list. - //! - //! Returns: the first element remaining beyond the removed elements, - //! or end() if no such element exists. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - //! - //! Note: Does not invalidate iterators or references to non erased elements. - iterator erase_after(const_iterator prev_pos) - { - return iterator(this->icont().erase_after_and_dispose(prev_pos.get(), Destroyer(this->node_alloc()))); - } - - //! Effects: Erases the range (before_first, last) from - //! the list. - //! - //! Returns: the first element remaining beyond the removed elements, - //! or end() if no such element exists. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of erased elements. - //! - //! Note: Does not invalidate iterators or references to non erased elements. - iterator erase_after(const_iterator before_first, const_iterator last) - { - return iterator(this->icont().erase_after_and_dispose(before_first.get(), last.get(), Destroyer(this->node_alloc()))); - } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements on *this and x. - void swap(slist& x) - { AllocHolder::swap(x); } - - //! Effects: Erases all the elements of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements in the list. - void clear() - { this->icont().clear_and_dispose(Destroyer(this->node_alloc())); } - - ////////////////////////////////////////////// - // - // slist operations - // - ////////////////////////////////////////////// - - //! Requires: p must point to an element contained - //! by the list. x != *this - //! - //! Effects: Transfers all the elements of list x to this list, after the - //! the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: std::runtime_error if this' allocator and x's allocator - //! are not equal. - //! - //! Complexity: Linear to the elements in x. - //! - //! Note: Iterators of values obtained from list x now point to elements of - //! this list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, slist& x) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this != &x); - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice_after(prev_pos.get(), x.icont()); - } - - //! Requires: p must point to an element contained - //! by the list. x != *this - //! - //! Effects: Transfers all the elements of list x to this list, after the - //! the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: std::runtime_error if this' allocator and x's allocator - //! are not equal. - //! - //! Complexity: Linear to the elements in x. - //! - //! Note: Iterators of values obtained from list x now point to elements of - //! this list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, BOOST_RV_REF(slist) x) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(prev_pos, static_cast(x)); } - - //! Requires: prev_pos must be a valid iterator of this. - //! i must point to an element contained in list x. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the value pointed by i, from list x to this list, - //! after the element pointed by prev_pos. - //! If prev_pos == prev or prev_pos == ++prev, this function is a null operation. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, slist& x, const_iterator prev) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice_after(prev_pos.get(), x.icont(), prev.get()); - } - - //! Requires: prev_pos must be a valid iterator of this. - //! i must point to an element contained in list x. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the value pointed by i, from list x to this list, - //! after the element pointed by prev_pos. - //! If prev_pos == prev or prev_pos == ++prev, this function is a null operation. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, BOOST_RV_REF(slist) x, const_iterator prev) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(prev_pos, static_cast(x), prev); } - - //! Requires: prev_pos must be a valid iterator of this. - //! before_first and before_last must be valid iterators of x. - //! prev_pos must not be contained in [before_first, before_last) range. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the range [before_first + 1, before_last + 1) - //! from list x to this list, after the element pointed by prev_pos. - //! - //! Throws: Nothing - //! - //! Complexity: Linear to the number of transferred elements. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, slist& x, - const_iterator before_first, const_iterator before_last) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice_after - (prev_pos.get(), x.icont(), before_first.get(), before_last.get()); - } - - //! Requires: prev_pos must be a valid iterator of this. - //! before_first and before_last must be valid iterators of x. - //! prev_pos must not be contained in [before_first, before_last) range. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the range [before_first + 1, before_last + 1) - //! from list x to this list, after the element pointed by prev_pos. - //! - //! Throws: Nothing - //! - //! Complexity: Linear to the number of transferred elements. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, BOOST_RV_REF(slist) x, - const_iterator before_first, const_iterator before_last) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(prev_pos, static_cast(x), before_first, before_last); } - - //! Requires: prev_pos must be a valid iterator of this. - //! before_first and before_last must be valid iterators of x. - //! prev_pos must not be contained in [before_first, before_last) range. - //! n == std::distance(before_first, before_last). - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the range [before_first + 1, before_last + 1) - //! from list x to this list, after the element pointed by prev_pos. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, slist& x, - const_iterator before_first, const_iterator before_last, - size_type n) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().splice_after - (prev_pos.get(), x.icont(), before_first.get(), before_last.get(), n); - } - - //! Requires: prev_pos must be a valid iterator of this. - //! before_first and before_last must be valid iterators of x. - //! prev_pos must not be contained in [before_first, before_last) range. - //! n == std::distance(before_first, before_last). - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the range [before_first + 1, before_last + 1) - //! from list x to this list, after the element pointed by prev_pos. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice_after(const_iterator prev_pos, BOOST_RV_REF(slist) x, - const_iterator before_first, const_iterator before_last, - size_type n) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(prev_pos, static_cast(x), before_first, before_last, n); } - - //! Effects: Removes all the elements that compare equal to value. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear time. It performs exactly size() comparisons for equality. - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - void remove(const T& value) - { this->remove_if(equal_to_value(value)); } - - //! Effects: Removes all the elements for which a specified - //! predicate is satisfied. - //! - //! Throws: If pred throws. - //! - //! Complexity: Linear time. It performs exactly size() calls to the predicate. - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - template - void remove_if(Pred pred) - { - typedef ValueCompareToNodeCompare Predicate; - this->icont().remove_and_dispose_if(Predicate(pred), Destroyer(this->node_alloc())); - } - - //! Effects: Removes adjacent duplicate elements or adjacent - //! elements that are equal from the list. - //! - //! Throws: If comparison throws. - //! - //! Complexity: Linear time (size()-1 comparisons equality comparisons). - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - void unique() - { this->unique(value_equal()); } - - //! Effects: Removes adjacent duplicate elements or adjacent - //! elements that satisfy some binary predicate from the list. - //! - //! Throws: If pred throws. - //! - //! Complexity: Linear time (size()-1 comparisons calls to pred()). - //! - //! Note: The relative order of elements that are not removed is unchanged, - //! and iterators to elements that are not removed remain valid. - template - void unique(Pred pred) - { - typedef ValueCompareToNodeCompare Predicate; - this->icont().unique_and_dispose(Predicate(pred), Destroyer(this->node_alloc())); - } - - //! Requires: The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this according to std::less. The merge is stable; - //! that is, if an element from *this is equivalent to one from x, then the element - //! from *this will precede the one from x. - //! - //! Throws: If comparison throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - void merge(slist & x) - { this->merge(x, value_less()); } - - //! Requires: The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this according to std::less. The merge is stable; - //! that is, if an element from *this is equivalent to one from x, then the element - //! from *this will precede the one from x. - //! - //! Throws: If comparison throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - void merge(BOOST_RV_REF(slist) x) - { this->merge(static_cast(x)); } - - //! Requires: p must be a comparison function that induces a strict weak - //! ordering and both *this and x must be sorted according to that ordering - //! The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this. The merge is stable; that is, if an element from *this is - //! equivalent to one from x, then the element from *this will precede the one from x. - //! - //! Throws: If comp throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - //! - //! Note: Iterators and references to *this are not invalidated. - template - void merge(slist& x, StrictWeakOrdering comp) - { - BOOST_ASSERT(this->node_alloc() == x.node_alloc()); - this->icont().merge(x.icont(), - ValueCompareToNodeCompare(comp)); - } - - //! Requires: p must be a comparison function that induces a strict weak - //! ordering and both *this and x must be sorted according to that ordering - //! The lists x and *this must be distinct. - //! - //! Effects: This function removes all of x's elements and inserts them - //! in order into *this. The merge is stable; that is, if an element from *this is - //! equivalent to one from x, then the element from *this will precede the one from x. - //! - //! Throws: If comp throws. - //! - //! Complexity: This function is linear time: it performs at most - //! size() + x.size() - 1 comparisons. - //! - //! Note: Iterators and references to *this are not invalidated. - template - void merge(BOOST_RV_REF(slist) x, StrictWeakOrdering comp) - { this->merge(static_cast(x), comp); } - - //! Effects: This function sorts the list *this according to std::less. - //! The sort is stable, that is, the relative order of equivalent elements is preserved. - //! - //! Throws: If comparison throws. - //! - //! Notes: Iterators and references are not invalidated. - //! - //! Complexity: The number of comparisons is approximately N log N, where N - //! is the list's size. - void sort() - { this->sort(value_less()); } - - //! Effects: This function sorts the list *this according to std::less. - //! The sort is stable, that is, the relative order of equivalent elements is preserved. - //! - //! Throws: If comp throws. - //! - //! Notes: Iterators and references are not invalidated. - //! - //! Complexity: The number of comparisons is approximately N log N, where N - //! is the list's size. - template - void sort(StrictWeakOrdering comp) - { - // nothing if the slist has length 0 or 1. - if (this->size() < 2) - return; - this->icont().sort(ValueCompareToNodeCompare(comp)); - } - - //! Effects: Reverses the order of elements in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: This function is linear time. - //! - //! Note: Iterators and references are not invalidated - void reverse() BOOST_CONTAINER_NOEXCEPT - { this->icont().reverse(); } - - ////////////////////////////////////////////// - // - // list compatibility interface - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... before p - //! - //! Throws: If memory allocation throws or - //! T's in-place constructor throws. - //! - //! Complexity: Linear to the elements before p - template - iterator emplace(const_iterator p, Args&&... args) - { return this->emplace_after(this->previous(p), boost::forward(args)...); } - - #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace (const_iterator p \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - return this->emplace_after \ - (this->previous(p) \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Insert a copy of x before p. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws or x's copy constructor throws. - //! - //! Complexity: Linear to the elements before p. - iterator insert(const_iterator position, const T &x); - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Insert a new element before p with mx's resources. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Linear to the elements before p. - iterator insert(const_iterator prev_pos, T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, T, iterator, priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Inserts n copies of x before p. - //! - //! Returns: an iterator to the first inserted element or p if n == 0. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n plus linear to the elements before p. - iterator insert(const_iterator p, size_type n, const value_type& x) - { - const_iterator prev(this->previous(p)); - this->insert_after(prev, n, x); - return ++iterator(prev.get()); - } - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Insert a copy of the [first, last) range before p. - //! - //! Returns: an iterator to the first inserted element or p if first == last. - //! - //! Throws: If memory allocation throws, T's constructor from a - //! dereferenced InpIt throws. - //! - //! Complexity: Linear to std::distance [first, last) plus - //! linear to the elements before p. - template - iterator insert(const_iterator p, InIter first, InIter last) - { - const_iterator prev(this->previous(p)); - this->insert_after(prev, first, last); - return ++iterator(prev.get()); - } - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Erases the element at p p. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements before p. - iterator erase(const_iterator p) BOOST_CONTAINER_NOEXCEPT - { return iterator(this->erase_after(previous(p))); } - - //! Requires: first and last must be valid iterator to elements in *this. - //! - //! Effects: Erases the elements pointed by [first, last). - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the distance between first and last plus - //! linear to the elements before first. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { return iterator(this->erase_after(previous(first), last)); } - - //! Requires: p must point to an element contained - //! by the list. x != *this. this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers all the elements of list x to this list, before the - //! the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Linear in distance(begin(), p), and linear in x.size(). - //! - //! Note: Iterators of values obtained from list x now point to elements of - //! this list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, slist& x) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(this->previous(p), x); } - - //! Requires: p must point to an element contained - //! by the list. x != *this. this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers all the elements of list x to this list, before the - //! the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Linear in distance(begin(), p), and linear in x.size(). - //! - //! Note: Iterators of values obtained from list x now point to elements of - //! this list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, BOOST_RV_REF(slist) x) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x)); } - - //! Requires: p must point to an element contained - //! by this list. i must point to an element contained in list x. - //! this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers the value pointed by i, from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! If p == i or p == ++i, this function is a null operation. - //! - //! Throws: Nothing - //! - //! Complexity: Linear in distance(begin(), p), and in distance(x.begin(), i). - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, slist& x, const_iterator i) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(this->previous(p), x, this->previous(i)); } - - //! Requires: p must point to an element contained - //! by this list. i must point to an element contained in list x. - //! this' allocator and x's allocator shall compare equal. - //! - //! Effects: Transfers the value pointed by i, from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! If p == i or p == ++i, this function is a null operation. - //! - //! Throws: Nothing - //! - //! Complexity: Linear in distance(begin(), p), and in distance(x.begin(), i). - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, BOOST_RV_REF(slist) x, const_iterator i) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x), i); } - - //! Requires: p must point to an element contained - //! by this list. first and last must point to elements contained in list x. - //! - //! Effects: Transfers the range pointed by first and last from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! this' allocator and x's allocator shall compare equal. - //! - //! Throws: Nothing - //! - //! Complexity: Linear in distance(begin(), p), in distance(x.begin(), first), - //! and in distance(first, last). - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, slist& x, const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { this->splice_after(this->previous(p), x, this->previous(first), this->previous(last)); } - - //! Requires: p must point to an element contained - //! by this list. first and last must point to elements contained in list x. - //! this' allocator and x's allocator shall compare equal - //! - //! Effects: Transfers the range pointed by first and last from list x to this list, - //! before the the element pointed by p. No destructors or copy constructors are called. - //! - //! Throws: Nothing - //! - //! Complexity: Linear in distance(begin(), p), in distance(x.begin(), first), - //! and in distance(first, last). - //! - //! Note: Iterators of values obtained from list x now point to elements of this - //! list. Iterators of this list and all the references are not invalidated. - void splice(const_iterator p, BOOST_RV_REF(slist) x, const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { this->splice(p, static_cast(x), first, last); } - - /// @cond - private: - - void priv_push_front (const T &x) - { this->insert(this->cbegin(), x); } - - void priv_push_front (BOOST_RV_REF(T) x) - { this->insert(this->cbegin(), ::boost::move(x)); } - - bool priv_try_shrink(size_type new_size, const_iterator &last_pos) - { - typename Icont::iterator end_n(this->icont().end()), cur(this->icont().before_begin()), cur_next; - while (++(cur_next = cur) != end_n && new_size > 0){ - --new_size; - cur = cur_next; - } - last_pos = const_iterator(cur); - if (cur_next != end_n){ - this->erase_after(last_pos, const_iterator(end_n)); - return true; - } - else{ - return false; - } - } - - template - iterator priv_insert(const_iterator p, BOOST_FWD_REF(U) x) - { return this->insert_after(previous(p), ::boost::forward(x)); } - - template - iterator priv_insert_after(const_iterator prev_pos, BOOST_FWD_REF(U) x) - { return iterator(this->icont().insert_after(prev_pos.get(), *this->create_node(::boost::forward(x)))); } - - class insertion_functor; - friend class insertion_functor; - - class insertion_functor - { - Icont &icont_; - typedef typename Icont::iterator iiterator; - typedef typename Icont::const_iterator iconst_iterator; - const iconst_iterator prev_; - iiterator ret_; - - public: - insertion_functor(Icont &icont, typename Icont::const_iterator prev) - : icont_(icont), prev_(prev), ret_(prev.unconst()) - {} - - void operator()(Node &n) - { - ret_ = this->icont_.insert_after(prev_, n); - } - - iiterator inserted_first() const - { return ret_; } - }; - - //Functors for member algorithm defaults - struct value_less - { - bool operator()(const value_type &a, const value_type &b) const - { return a < b; } - }; - - struct value_equal - { - bool operator()(const value_type &a, const value_type &b) const - { return a == b; } - }; - - struct value_equal_to_this - { - explicit value_equal_to_this(const value_type &ref) - : m_ref(ref){} - - bool operator()(const value_type &val) const - { return m_ref == val; } - - const value_type &m_ref; - }; - /// @endcond -}; - -template -inline bool -operator==(const slist& x, const slist& y) -{ - if(x.size() != y.size()){ - return false; - } - typedef typename slist::const_iterator const_iterator; - const_iterator end1 = x.end(); - - const_iterator i1 = x.begin(); - const_iterator i2 = y.begin(); - while (i1 != end1 && *i1 == *i2){ - ++i1; - ++i2; - } - return i1 == end1; -} - -template -inline bool -operator<(const slist& sL1, const slist& sL2) -{ - return std::lexicographical_compare - (sL1.begin(), sL1.end(), sL2.begin(), sL2.end()); -} - -template -inline bool -operator!=(const slist& sL1, const slist& sL2) - { return !(sL1 == sL2); } - -template -inline bool -operator>(const slist& sL1, const slist& sL2) - { return sL2 < sL1; } - -template -inline bool -operator<=(const slist& sL1, const slist& sL2) - { return !(sL2 < sL1); } - -template -inline bool -operator>=(const slist& sL1, const slist& sL2) - { return !(sL1 < sL2); } - -template -inline void swap(slist& x, slist& y) - { x.swap(y); } - -}} - -/// @cond - -namespace boost { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > - : public ::boost::has_trivial_destructor_after_move -{}; - -namespace container { - -/// @endcond - -}} //namespace boost{ namespace container { - -// Specialization of insert_iterator so that insertions will be constant -// time rather than linear time. - -///@cond - -//Ummm, I don't like to define things in namespace std, but -//there is no other way -namespace std { - -template -class insert_iterator > -{ - protected: - typedef boost::container::slist Container; - Container* container; - typename Container::iterator iter; - public: - typedef Container container_type; - typedef output_iterator_tag iterator_category; - typedef void value_type; - typedef void difference_type; - typedef void pointer; - typedef void reference; - - insert_iterator(Container& x, - typename Container::iterator i, - bool is_previous = false) - : container(&x), iter(is_previous ? i : x.previous(i)){ } - - insert_iterator& - operator=(const typename Container::value_type& value) - { - iter = container->insert_after(iter, value); - return *this; - } - insert_iterator& operator*(){ return *this; } - insert_iterator& operator++(){ return *this; } - insert_iterator& operator++(int){ return *this; } -}; - -} //namespace std; - -///@endcond - -#include - -#endif // BOOST_CONTAINER_SLIST_HPP diff --git a/utils/boost_idb/boost/container/stable_vector.hpp b/utils/boost_idb/boost/container/stable_vector.hpp deleted file mode 100644 index 7b31cc46..00000000 --- a/utils/boost_idb/boost/container/stable_vector.hpp +++ /dev/null @@ -1,1907 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// -// Stable vector. -// -// Copyright 2008 Joaquin M Lopez Munoz. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_STABLE_VECTOR_HPP -#define BOOST_CONTAINER_STABLE_VECTOR_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include //max - -#include -#include //placement new - -///@cond - -#include - -//#define STABLE_VECTOR_ENABLE_INVARIANT_CHECKING - -///@endcond - -namespace boost { -namespace container { - -///@cond - -namespace stable_vector_detail{ - -template -class clear_on_destroy -{ - public: - clear_on_destroy(C &c) - : c_(c), do_clear_(true) - {} - - void release() - { do_clear_ = false; } - - ~clear_on_destroy() - { - if(do_clear_){ - c_.clear(); - c_.priv_clear_pool(); - } - } - - private: - clear_on_destroy(const clear_on_destroy &); - clear_on_destroy &operator=(const clear_on_destroy &); - C &c_; - bool do_clear_; -}; - -template -struct node; - -template -struct node_base -{ - private: - typedef typename boost::intrusive:: - pointer_traits void_ptr_traits; - typedef typename void_ptr_traits:: - template rebind_pointer - ::type node_base_ptr; - typedef typename void_ptr_traits:: - template rebind_pointer - ::type node_base_ptr_ptr; - - public: - node_base(const node_base_ptr_ptr &n) - : up(n) - {} - - node_base() - : up() - {} - - node_base_ptr_ptr up; -}; - -template -struct node - : public node_base - ::template - rebind_pointer::type - > -{ -// private: -// node(); - - public: - typename ::boost::intrusive::pointer_traits::element_type value; -}; - -template -class iterator -{ - typedef boost::intrusive::pointer_traits non_const_ptr_traits; - public: - typedef std::random_access_iterator_tag iterator_category; - typedef typename non_const_ptr_traits::element_type value_type; - typedef typename non_const_ptr_traits::difference_type difference_type; - typedef typename ::boost::container::container_detail::if_c - < IsConst - , typename non_const_ptr_traits::template - rebind_pointer::type - , Pointer - >::type pointer; - typedef typename ::boost::container::container_detail::if_c - < IsConst - , const value_type& - , value_type& - >::type reference; - - private: - typedef typename non_const_ptr_traits::template - rebind_pointer::type void_ptr; - typedef node node_type; - typedef node_base node_base_type; - typedef typename non_const_ptr_traits::template - rebind_pointer::type node_ptr; - typedef boost::intrusive:: - pointer_traits node_ptr_traits; - typedef typename non_const_ptr_traits::template - rebind_pointer::type node_base_ptr; - typedef typename non_const_ptr_traits::template - rebind_pointer::type node_base_ptr_ptr; - - node_ptr m_pn; - - public: - - explicit iterator(node_ptr p) BOOST_CONTAINER_NOEXCEPT - : m_pn(p) - {} - - iterator() BOOST_CONTAINER_NOEXCEPT - {} - - iterator(iterator const& other) BOOST_CONTAINER_NOEXCEPT - : m_pn(other.node_pointer()) - {} - - node_ptr &node_pointer() BOOST_CONTAINER_NOEXCEPT - { return m_pn; } - - const node_ptr &node_pointer() const BOOST_CONTAINER_NOEXCEPT - { return m_pn; } - - public: - //Pointer like operators - reference operator*() const BOOST_CONTAINER_NOEXCEPT - { return m_pn->value; } - - pointer operator->() const BOOST_CONTAINER_NOEXCEPT - { - typedef boost::intrusive::pointer_traits ptr_traits; - return ptr_traits::pointer_to(this->operator*()); - } - - //Increment / Decrement - iterator& operator++() BOOST_CONTAINER_NOEXCEPT - { - if(node_base_ptr_ptr p = this->m_pn->up){ - ++p; - this->m_pn = node_ptr_traits::static_cast_from(*p); - } - return *this; - } - - iterator operator++(int) BOOST_CONTAINER_NOEXCEPT - { iterator tmp(*this); ++*this; return iterator(tmp); } - - iterator& operator--() BOOST_CONTAINER_NOEXCEPT - { - if(node_base_ptr_ptr p = this->m_pn->up){ - --p; - this->m_pn = node_ptr_traits::static_cast_from(*p); - } - return *this; - } - - iterator operator--(int) BOOST_CONTAINER_NOEXCEPT - { iterator tmp(*this); --*this; return iterator(tmp); } - - reference operator[](difference_type off) const BOOST_CONTAINER_NOEXCEPT - { - iterator tmp(*this); - tmp += off; - return *tmp; - } - - iterator& operator+=(difference_type off) BOOST_CONTAINER_NOEXCEPT - { - if(node_base_ptr_ptr p = this->m_pn->up){ - p += off; - this->m_pn = node_ptr_traits::static_cast_from(*p); - } - return *this; - } - - friend iterator operator+(const iterator &left, difference_type off) BOOST_CONTAINER_NOEXCEPT - { - iterator tmp(left); - tmp += off; - return tmp; - } - - friend iterator operator+(difference_type off, const iterator& right) BOOST_CONTAINER_NOEXCEPT - { - iterator tmp(right); - tmp += off; - return tmp; - } - - iterator& operator-=(difference_type off) BOOST_CONTAINER_NOEXCEPT - { *this += -off; return *this; } - - friend iterator operator-(const iterator &left, difference_type off) BOOST_CONTAINER_NOEXCEPT - { - iterator tmp(left); - tmp -= off; - return tmp; - } - - friend difference_type operator-(const iterator& left, const iterator& right) BOOST_CONTAINER_NOEXCEPT - { return left.m_pn->up - right.m_pn->up; } - - //Comparison operators - friend bool operator== (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_pn == r.m_pn; } - - friend bool operator!= (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_pn != r.m_pn; } - - friend bool operator< (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_pn->up < r.m_pn->up; } - - friend bool operator<= (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_pn->up <= r.m_pn->up; } - - friend bool operator> (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_pn->up > r.m_pn->up; } - - friend bool operator>= (const iterator& l, const iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_pn->up >= r.m_pn->up; } -}; - -template -struct index_traits -{ - typedef boost::intrusive:: - pointer_traits - void_ptr_traits; - typedef stable_vector_detail:: - node_base node_base_type; - typedef typename void_ptr_traits::template - rebind_pointer::type node_base_ptr; - typedef typename void_ptr_traits::template - rebind_pointer::type node_base_ptr_ptr; - typedef boost::intrusive:: - pointer_traits node_base_ptr_traits; - typedef boost::intrusive:: - pointer_traits node_base_ptr_ptr_traits; - typedef typename allocator_traits:: - template portable_rebind_alloc - ::type node_base_ptr_allocator; - typedef ::boost::container::vector - index_type; - typedef typename index_type::iterator index_iterator; - typedef typename index_type::const_iterator const_index_iterator; - typedef typename index_type::size_type size_type; - - static const size_type ExtraPointers = 3; - //Stable vector stores metadata at the end of the index (node_base_ptr vector) with additional 3 pointers: - // back() is this->index.back() - ExtraPointers; - // end node index is *(this->index.end() - 3) - // Node cache first is *(this->index.end() - 2); - // Node cache last is this->index.back(); - - static node_base_ptr_ptr ptr_to_node_base_ptr(node_base_ptr &n) - { return node_base_ptr_ptr_traits::pointer_to(n); } - - static void fix_up_pointers(index_iterator first, index_iterator last) - { - while(first != last){ - typedef typename index_type::reference node_base_ptr_ref; - node_base_ptr_ref nbp = *first; - nbp->up = index_traits::ptr_to_node_base_ptr(nbp); - ++first; - } - } - - static index_iterator get_fix_up_end(index_type &index) - { return index.end() - (ExtraPointers - 1); } - - static void fix_up_pointers_from(index_type & index, index_iterator first) - { index_traits::fix_up_pointers(first, index_traits::get_fix_up_end(index)); } - - static void readjust_end_node(index_type &index, node_base_type &end_node) - { - if(!index.empty()){ - index_iterator end_node_it(index_traits::get_fix_up_end(index)); - node_base_ptr &end_node_idx_ref = *(--end_node_it); - end_node_idx_ref = node_base_ptr_traits::pointer_to(end_node); - end_node.up = node_base_ptr_ptr_traits::pointer_to(end_node_idx_ref); - } - else{ - end_node.up = node_base_ptr_ptr(); - } - } - - static void initialize_end_node(index_type &index, node_base_type &end_node, const size_type index_capacity_if_empty) - { - if(index.empty()){ - index.reserve(index_capacity_if_empty + ExtraPointers); - index.resize(ExtraPointers); - node_base_ptr &end_node_ref = *index.data(); - end_node_ref = node_base_ptr_traits::pointer_to(end_node); - end_node.up = index_traits::ptr_to_node_base_ptr(end_node_ref); - } - } - - #ifdef STABLE_VECTOR_ENABLE_INVARIANT_CHECKING - static bool invariants(index_type &index) - { - for( index_iterator it = index.begin() - , it_end = index_traits::get_fix_up_end(index) - ; it != it_end - ; ++it){ - if((*it)->up != index_traits::ptr_to_node_base_ptr(*it)){ - return false; - } - } - return true; - } - #endif //STABLE_VECTOR_ENABLE_INVARIANT_CHECKING -}; - -} //namespace stable_vector_detail - -#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - #if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) - - #define STABLE_VECTOR_CHECK_INVARIANT \ - invariant_checker BOOST_JOIN(check_invariant_,__LINE__)(*this); \ - BOOST_JOIN(check_invariant_,__LINE__).touch(); - - #else //STABLE_VECTOR_ENABLE_INVARIANT_CHECKING - - #define STABLE_VECTOR_CHECK_INVARIANT - - #endif //#if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) - -#endif //#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - -/// @endcond - -//! Originally developed by Joaquin M. Lopez Munoz, stable_vector is a std::vector -//! drop-in replacement implemented as a node container, offering iterator and reference -//! stability. -//! -//! Here are the details taken from the author's blog -//! ( -//! Introducing stable_vector): -//! -//! We present stable_vector, a fully STL-compliant stable container that provides -//! most of the features of std::vector except element contiguity. -//! -//! General properties: stable_vector satisfies all the requirements of a container, -//! a reversible container and a sequence and provides all the optional operations -//! present in std::vector. Like std::vector, iterators are random access. -//! stable_vector does not provide element contiguity; in exchange for this absence, -//! the container is stable, i.e. references and iterators to an element of a stable_vector -//! remain valid as long as the element is not erased, and an iterator that has been -//! assigned the return value of end() always remain valid until the destruction of -//! the associated stable_vector. -//! -//! Operation complexity: The big-O complexities of stable_vector operations match -//! exactly those of std::vector. In general, insertion/deletion is constant time at -//! the end of the sequence and linear elsewhere. Unlike std::vector, stable_vector -//! does not internally perform any value_type destruction, copy or assignment -//! operations other than those exactly corresponding to the insertion of new -//! elements or deletion of stored elements, which can sometimes compensate in terms -//! of performance for the extra burden of doing more pointer manipulation and an -//! additional allocation per element. -//! -//! Exception safety: As stable_vector does not internally copy elements around, some -//! operations provide stronger exception safety guarantees than in std::vector. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else -template -#endif -class stable_vector -{ - ///@cond - typedef allocator_traits allocator_traits_type; - typedef boost::intrusive:: - pointer_traits - ptr_traits; - typedef typename ptr_traits:: - template rebind_pointer::type void_ptr; - typedef typename allocator_traits_type:: - template portable_rebind_alloc - ::type void_allocator_type; - typedef stable_vector_detail::index_traits - index_traits_type; - typedef typename index_traits_type::node_base_type node_base_type; - typedef typename index_traits_type::node_base_ptr node_base_ptr; - typedef typename index_traits_type:: - node_base_ptr_ptr node_base_ptr_ptr; - typedef typename index_traits_type:: - node_base_ptr_traits node_base_ptr_traits; - typedef typename index_traits_type:: - node_base_ptr_ptr_traits node_base_ptr_ptr_traits; - typedef typename index_traits_type::index_type index_type; - typedef typename index_traits_type::index_iterator index_iterator; - typedef typename index_traits_type:: - const_index_iterator const_index_iterator; - typedef stable_vector_detail::node - node_type; - typedef typename ptr_traits::template - rebind_pointer::type node_ptr; - typedef boost::intrusive:: - pointer_traits node_ptr_traits; - typedef typename ptr_traits::template - rebind_pointer::type const_node_ptr; - typedef boost::intrusive:: - pointer_traits const_node_ptr_traits; - typedef typename node_ptr_traits::reference node_reference; - typedef typename const_node_ptr_traits::reference const_node_reference; - - typedef ::boost::container::container_detail:: - integral_constant allocator_v1; - typedef ::boost::container::container_detail:: - integral_constant allocator_v2; - typedef ::boost::container::container_detail::integral_constant - ::value> alloc_version; - typedef typename allocator_traits_type:: - template portable_rebind_alloc - ::type node_allocator_type; - - typedef ::boost::container::container_detail:: - allocator_version_traits allocator_version_traits_t; - typedef typename allocator_version_traits_t::multiallocation_chain multiallocation_chain; - - node_ptr allocate_one() - { return allocator_version_traits_t::allocate_one(this->priv_node_alloc()); } - - void deallocate_one(const node_ptr &p) - { allocator_version_traits_t::deallocate_one(this->priv_node_alloc(), p); } - - void allocate_individual(typename allocator_traits_type::size_type n, multiallocation_chain &m) - { allocator_version_traits_t::allocate_individual(this->priv_node_alloc(), n, m); } - - void deallocate_individual(multiallocation_chain &holder) - { allocator_version_traits_t::deallocate_individual(this->priv_node_alloc(), holder); } - - friend class stable_vector_detail::clear_on_destroy; - typedef stable_vector_detail::iterator - < typename allocator_traits::pointer - , false> iterator_impl; - typedef stable_vector_detail::iterator - < typename allocator_traits::pointer - , false> const_iterator_impl; - ///@endcond - public: - - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef T value_type; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef node_allocator_type stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(iterator_impl) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_iterator_impl) const_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - - ///@cond - private: - BOOST_COPYABLE_AND_MOVABLE(stable_vector) - static const size_type ExtraPointers = index_traits_type::ExtraPointers; - - class insert_rollback; - friend class insert_rollback; - - class push_back_rollback; - friend class push_back_rollback; - ///@endcond - - public: - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Default constructs a stable_vector. - //! - //! Throws: If allocator_type's default constructor throws. - //! - //! Complexity: Constant. - stable_vector() - : internal_data(), index() - { - STABLE_VECTOR_CHECK_INVARIANT; - } - - //! Effects: Constructs a stable_vector taking the allocator as parameter. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - explicit stable_vector(const allocator_type& al) BOOST_CONTAINER_NOEXCEPT - : internal_data(al), index(al) - { - STABLE_VECTOR_CHECK_INVARIANT; - } - - //! Effects: Constructs a stable_vector that will use a copy of allocator a - //! and inserts n value initialized values. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - explicit stable_vector(size_type n) - : internal_data(), index() - { - stable_vector_detail::clear_on_destroy cod(*this); - this->resize(n); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - - //! Effects: Constructs a stable_vector that will use a copy of allocator a - //! and inserts n default initialized values. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - //! - //! Note: Non-standard extension - stable_vector(size_type n, default_init_t) - : internal_data(), index() - { - stable_vector_detail::clear_on_destroy cod(*this); - this->resize(n, default_init); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - - //! Effects: Constructs a stable_vector that will use a copy of allocator a - //! and inserts n copies of value. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's default or copy constructor throws. - //! - //! Complexity: Linear to n. - stable_vector(size_type n, const T& t, const allocator_type& al = allocator_type()) - : internal_data(al), index(al) - { - stable_vector_detail::clear_on_destroy cod(*this); - this->insert(this->cend(), n, t); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - - //! Effects: Constructs a stable_vector that will use a copy of allocator a - //! and inserts a copy of the range [first, last) in the stable_vector. - //! - //! Throws: If allocator_type's default constructor or copy constructor - //! throws or T's constructor taking an dereferenced InIt throws. - //! - //! Complexity: Linear to the range [first, last). - template - stable_vector(InputIterator first,InputIterator last, const allocator_type& al = allocator_type()) - : internal_data(al), index(al) - { - stable_vector_detail::clear_on_destroy cod(*this); - this->insert(this->cend(), first, last); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - - //! Effects: Copy constructs a stable_vector. - //! - //! Postcondition: x == *this. - //! - //! Complexity: Linear to the elements x contains. - stable_vector(const stable_vector& x) - : internal_data(allocator_traits:: - select_on_container_copy_construction(x.priv_node_alloc())) - , index(allocator_traits:: - select_on_container_copy_construction(x.index.get_stored_allocator())) - { - stable_vector_detail::clear_on_destroy cod(*this); - this->insert(this->cend(), x.begin(), x.end()); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - stable_vector(BOOST_RV_REF(stable_vector) x) - : internal_data(boost::move(x.priv_node_alloc())), index(boost::move(x.index)) - { - this->priv_swap_members(x); - } - - //! Effects: Copy constructs a stable_vector using the specified allocator. - //! - //! Postcondition: x == *this. - //! - //! Complexity: Linear to the elements x contains. - stable_vector(const stable_vector& x, const allocator_type &a) - : internal_data(a), index(a) - { - stable_vector_detail::clear_on_destroy cod(*this); - this->insert(this->cend(), x.begin(), x.end()); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - - //! Effects: Move constructor using the specified allocator. - //! Moves mx's resources to *this. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise - stable_vector(BOOST_RV_REF(stable_vector) x, const allocator_type &a) - : internal_data(a), index(a) - { - if(this->priv_node_alloc() == x.priv_node_alloc()){ - this->priv_swap_members(x); - } - else{ - stable_vector_detail::clear_on_destroy cod(*this); - this->insert(this->cend(), x.begin(), x.end()); - STABLE_VECTOR_CHECK_INVARIANT; - cod.release(); - } - } - - //! Effects: Destroys the stable_vector. All stored values are destroyed - //! and used memory is deallocated. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements. - ~stable_vector() - { - this->clear(); - this->priv_clear_pool(); - } - - //! Effects: Makes *this contain the same elements as x. - //! - //! Postcondition: this->size() == x.size(). *this contains a copy - //! of each of x's elements. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to the number of elements in x. - stable_vector& operator=(BOOST_COPY_ASSIGN_REF(stable_vector) x) - { - STABLE_VECTOR_CHECK_INVARIANT; - if (&x != this){ - node_allocator_type &this_alloc = this->priv_node_alloc(); - const node_allocator_type &x_alloc = x.priv_node_alloc(); - container_detail::bool_ flag; - if(flag && this_alloc != x_alloc){ - this->clear(); - this->shrink_to_fit(); - } - container_detail::assign_alloc(this->priv_node_alloc(), x.priv_node_alloc(), flag); - container_detail::assign_alloc(this->index.get_stored_allocator(), x.index.get_stored_allocator(), flag); - this->assign(x.begin(), x.end()); - } - return *this; - } - - //! Effects: Move assignment. All mx's values are transferred to *this. - //! - //! Postcondition: x.empty(). *this contains a the elements x had - //! before the function. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Linear. - stable_vector& operator=(BOOST_RV_REF(stable_vector) x) - { - if (&x != this){ - node_allocator_type &this_alloc = this->priv_node_alloc(); - node_allocator_type &x_alloc = x.priv_node_alloc(); - //If allocators are equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy objects but retain memory - this->clear(); - this->index = boost::move(x.index); - this->priv_swap_members(x); - //Move allocator if needed - container_detail::bool_ flag; - container_detail::move_alloc(this->priv_node_alloc(), x.priv_node_alloc(), flag); - } - //If unequal allocators, then do a one by one move - else{ - this->assign( boost::make_move_iterator(x.begin()) - , boost::make_move_iterator(x.end())); - } - } - return *this; - } - - - //! Effects: Assigns the n copies of val to *this. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - void assign(size_type n, const T& t) - { - typedef constant_iterator cvalue_iterator; - this->assign(cvalue_iterator(t, n), cvalue_iterator()); - } - - //! Effects: Assigns the the range [first, last) to *this. - //! - //! Throws: If memory allocation throws or - //! T's constructor from dereferencing InpIt throws. - //! - //! Complexity: Linear to n. - template - void assign(InputIterator first,InputIterator last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - >::type * = 0 - #endif - ) - { - STABLE_VECTOR_CHECK_INVARIANT; - iterator first1 = this->begin(); - iterator last1 = this->end(); - for ( ; first1 != last1 && first != last; ++first1, ++first) - *first1 = *first; - if (first == last){ - this->erase(first1, last1); - } - else{ - this->insert(last1, first, last); - } - } - - //! Effects: Returns a copy of the internal allocator. - //! - //! Throws: If allocator's copy constructor throws. - //! - //! Complexity: Constant. - allocator_type get_allocator() const - { return this->priv_node_alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_node_alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return this->priv_node_alloc(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return (this->index.empty()) ? this->end(): iterator(node_ptr_traits::static_cast_from(this->index.front())); } - - //! Effects: Returns a const_iterator to the first element contained in the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return (this->index.empty()) ? this->cend() : const_iterator(node_ptr_traits::static_cast_from(this->index.front())) ; } - - //! Effects: Returns an iterator to the end of the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->priv_get_end_node()); } - - //! Effects: Returns a const_iterator to the end of the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->priv_get_end_node()); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->end()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->end()); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->begin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->begin()); } - - //! Effects: Returns a const_iterator to the first element contained in the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->begin(); } - - //! Effects: Returns a const_iterator to the end of the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return this->end(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->rbegin(); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend()const BOOST_CONTAINER_NOEXCEPT - { return this->rend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the stable_vector contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return this->index.size() <= ExtraPointers; } - - //! Effects: Returns the number of the elements contained in the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { - const size_type index_size = this->index.size(); - return (index_size - ExtraPointers) & (std::size_t(0u) -std::size_t(index_size != 0)); - } - - //! Effects: Returns the largest possible size of the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return this->index.max_size() - ExtraPointers; } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws, or T's default constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type n) - { - typedef value_init_construct_iterator value_init_iterator; - STABLE_VECTOR_CHECK_INVARIANT; - if(n > this->size()) - this->insert(this->cend(), value_init_iterator(n - this->size()), value_init_iterator()); - else if(n < this->size()) - this->erase(this->cbegin() + n, this->cend()); - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are default initialized. - //! - //! Throws: If memory allocation throws, or T's default constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - //! - //! Note: Non-standard extension - void resize(size_type n, default_init_t) - { - typedef default_init_construct_iterator default_init_iterator; - STABLE_VECTOR_CHECK_INVARIANT; - if(n > this->size()) - this->insert(this->cend(), default_init_iterator(n - this->size()), default_init_iterator()); - else if(n < this->size()) - this->erase(this->cbegin() + n, this->cend()); - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are copy constructed from x. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type n, const T& t) - { - STABLE_VECTOR_CHECK_INVARIANT; - if(n > this->size()) - this->insert(this->cend(), n - this->size(), t); - else if(n < this->size()) - this->erase(this->cbegin() + n, this->cend()); - } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { - const size_type index_size = this->index.size(); - BOOST_ASSERT(!index_size || index_size >= ExtraPointers); - const size_type bucket_extra_capacity = this->index.capacity()- index_size; - const size_type node_extra_capacity = this->internal_data.pool_size; - const size_type extra_capacity = (bucket_extra_capacity < node_extra_capacity) - ? bucket_extra_capacity : node_extra_capacity; - const size_type index_offset = - (ExtraPointers + extra_capacity) & (size_type(0u) - size_type(index_size != 0)); - return index_size - index_offset; - } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws. - void reserve(size_type n) - { - STABLE_VECTOR_CHECK_INVARIANT; - if(n > this->max_size()){ - throw_length_error("stable_vector::reserve max_size() exceeded"); - } - - size_type sz = this->size(); - size_type old_capacity = this->capacity(); - if(n > old_capacity){ - index_traits_type::initialize_end_node(this->index, this->internal_data.end_node, n); - const void * old_ptr = &index[0]; - this->index.reserve(n + ExtraPointers); - bool realloced = &index[0] != old_ptr; - //Fix the pointers for the newly allocated buffer - if(realloced){ - index_traits_type::fix_up_pointers_from(this->index, this->index.begin()); - } - //Now fill pool if data is not enough - if((n - sz) > this->internal_data.pool_size){ - this->priv_increase_pool((n - sz) - this->internal_data.pool_size); - } - } - } - - //! Effects: Tries to deallocate the excess of memory created - //! with previous allocations. The size of the stable_vector is unchanged - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { - if(this->capacity()){ - //First empty allocated node pool - this->priv_clear_pool(); - //If empty completely destroy the index, let's recover default-constructed state - if(this->empty()){ - this->index.clear(); - this->index.shrink_to_fit(); - this->internal_data.end_node.up = node_base_ptr_ptr(); - } - //Otherwise, try to shrink-to-fit the index and readjust pointers if necessary - else{ - const void* old_ptr = &index[0]; - this->index.shrink_to_fit(); - bool realloced = &index[0] != old_ptr; - //Fix the pointers for the newly allocated buffer - if(realloced){ - index_traits_type::fix_up_pointers_from(this->index, this->index.begin()); - } - } - } - } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the first - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference front() BOOST_CONTAINER_NOEXCEPT - { return static_cast(*this->index.front()).value; } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the first - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference front() const BOOST_CONTAINER_NOEXCEPT - { return static_cast(*this->index.front()).value; } - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the last - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference back() BOOST_CONTAINER_NOEXCEPT - { return static_cast(*this->index[this->size()-1u]).value; } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the last - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference back() const BOOST_CONTAINER_NOEXCEPT - { return static_cast(*this->index[this->size()-1u]).value; } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference operator[](size_type n) BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(n < this->size()); - return static_cast(*this->index[n]).value; - } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference operator[](size_type n) const BOOST_CONTAINER_NOEXCEPT - { - BOOST_ASSERT(n < this->size()); - return static_cast(*this->index[n]).value; - } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - reference at(size_type n) - { - if(n >= this->size()){ - throw_out_of_range("vector::at invalid subscript"); - } - return operator[](n); - } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - const_reference at(size_type n)const - { - if(n >= this->size()){ - throw_out_of_range("vector::at invalid subscript"); - } - return operator[](n); - } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the end of the stable_vector. - //! - //! Throws: If memory allocation throws or the in-place constructor throws. - //! - //! Complexity: Amortized constant time. - template - void emplace_back(Args &&...args) - { - typedef emplace_functor EmplaceFunctor; - typedef emplace_iterator EmplaceIterator; - EmplaceFunctor &&ef = EmplaceFunctor(boost::forward(args)...); - this->insert(this->cend(), EmplaceIterator(ef), EmplaceIterator()); - } - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... before position - //! - //! Throws: If memory allocation throws or the in-place constructor throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - template - iterator emplace(const_iterator position, Args && ...args) - { - //Just call more general insert(pos, size, value) and return iterator - size_type pos_n = position - cbegin(); - typedef emplace_functor EmplaceFunctor; - typedef emplace_iterator EmplaceIterator; - EmplaceFunctor &&ef = EmplaceFunctor(boost::forward(args)...); - this->insert(position, EmplaceIterator(ef), EmplaceIterator()); - return iterator(this->begin() + pos_n); - } - - #else - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - typedef BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ - BOOST_PP_EXPR_IF(n, <) BOOST_PP_ENUM_PARAMS(n, P) BOOST_PP_EXPR_IF(n, >) \ - EmplaceFunctor; \ - typedef emplace_iterator EmplaceIterator; \ - EmplaceFunctor ef BOOST_PP_LPAREN_IF(n) \ - BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) \ - BOOST_PP_RPAREN_IF(n); \ - this->insert(this->cend() , EmplaceIterator(ef), EmplaceIterator()); \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(const_iterator pos \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - typedef BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ - BOOST_PP_EXPR_IF(n, <) BOOST_PP_ENUM_PARAMS(n, P) BOOST_PP_EXPR_IF(n, >) \ - EmplaceFunctor; \ - typedef emplace_iterator EmplaceIterator; \ - EmplaceFunctor ef BOOST_PP_LPAREN_IF(n) \ - BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) \ - BOOST_PP_RPAREN_IF(n); \ - size_type pos_n = pos - this->cbegin(); \ - this->insert(pos, EmplaceIterator(ef), EmplaceIterator()); \ - return iterator(this->begin() + pos_n); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the end of the stable_vector. - //! - //! Throws: If memory allocation throws or - //! T's copy constructor throws. - //! - //! Complexity: Amortized constant time. - void push_back(const T &x); - - //! Effects: Constructs a new element in the end of the stable_vector - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: Amortized constant time. - void push_back(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_back, T, void, priv_push_back) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a copy of x before position. - //! - //! Returns: An iterator to the inserted element. - //! - //! Throws: If memory allocation throws or x's copy constructor throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - iterator insert(const_iterator position, const T &x); - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a new element before position with mx's resources. - //! - //! Returns: an iterator to the inserted element. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - iterator insert(const_iterator position, T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, T, iterator, priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: pos must be a valid iterator of *this. - //! - //! Effects: Insert n copies of x before position. - //! - //! Returns: an iterator to the first inserted element or position if n is 0. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - iterator insert(const_iterator position, size_type n, const T& t) - { - STABLE_VECTOR_CHECK_INVARIANT; - typedef constant_iterator cvalue_iterator; - return this->insert(position, cvalue_iterator(t, n), cvalue_iterator()); - } - - //! Requires: pos must be a valid iterator of *this. - //! - //! Effects: Insert a copy of the [first, last) range before pos. - //! - //! Returns: an iterator to the first inserted element or position if first == last. - //! - //! Throws: If memory allocation throws, T's constructor from a - //! dereferenced InpIt throws or T's copy constructor throws. - //! - //! Complexity: Linear to std::distance [first, last). - template - iterator insert(const_iterator position, InputIterator first, InputIterator last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - STABLE_VECTOR_CHECK_INVARIANT; - const size_type pos_n = position - this->cbegin(); - for(; first != last; ++first){ - this->emplace(position, *first); - } - return this->begin() + pos_n; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - iterator insert(const_iterator position, FwdIt first, FwdIt last - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !container_detail::is_input_iterator::value - >::type * = 0 - ) - { - const size_type num_new = static_cast(std::distance(first, last)); - const size_type pos = static_cast(position - this->cbegin()); - if(num_new){ - //Fills the node pool and inserts num_new null pointers in pos. - //If a new buffer was needed fixes up pointers up to pos so - //past-new nodes are not aligned until the end of this function - //or in a rollback in case of exception - index_iterator it_past_newly_constructed(this->priv_insert_forward_non_templated(pos, num_new)); - const index_iterator it_past_new(it_past_newly_constructed + num_new); - { - //Prepare rollback - insert_rollback rollback(*this, it_past_newly_constructed, it_past_new); - while(first != last){ - const node_ptr p = this->priv_get_from_pool(); - BOOST_ASSERT(!!p); - //Put it in the index so rollback can return it in pool if construct_in_place throws - *it_past_newly_constructed = p; - //Constructs and fixes up pointers This can throw - this->priv_build_node_from_it(p, it_past_newly_constructed, first); - ++first; - ++it_past_newly_constructed; - } - //rollback.~insert_rollback() called in case of exception - } - //Fix up pointers for past-new nodes (new nodes were fixed during construction) and - //nodes before insertion position in priv_insert_forward_non_templated(...) - index_traits_type::fix_up_pointers_from(this->index, it_past_newly_constructed); - } - return this->begin() + pos; - } - #endif - - //! Effects: Removes the last element from the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant time. - void pop_back() BOOST_CONTAINER_NOEXCEPT - { this->erase(--this->cend()); } - - //! Effects: Erases the element at position pos. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the elements between pos and the - //! last element. Constant if pos is the last element. - iterator erase(const_iterator position) BOOST_CONTAINER_NOEXCEPT - { - STABLE_VECTOR_CHECK_INVARIANT; - const size_type d = position - this->cbegin(); - index_iterator it = this->index.begin() + d; - this->priv_delete_node(position.node_pointer()); - it = this->index.erase(it); - index_traits_type::fix_up_pointers_from(this->index, it); - return iterator(node_ptr_traits::static_cast_from(*it)); - } - - //! Effects: Erases the elements pointed by [first, last). - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the distance between first and last - //! plus linear to the elements between pos and the last element. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { - STABLE_VECTOR_CHECK_INVARIANT; - const const_iterator cbeg(this->cbegin()); - const size_type d1 = static_cast(first - cbeg), - d2 = static_cast(last - cbeg); - size_type d_dif = d2 - d1; - if(d_dif){ - multiallocation_chain holder; - const index_iterator it1(this->index.begin() + d1); - const index_iterator it2(it1 + d_dif); - index_iterator it(it1); - while(d_dif--){ - node_base_ptr &nb = *it; - ++it; - node_type &n = *node_ptr_traits::static_cast_from(nb); - this->priv_destroy_node(n); - holder.push_back(node_ptr_traits::pointer_to(n)); - } - this->priv_put_in_pool(holder); - const index_iterator e = this->index.erase(it1, it2); - index_traits_type::fix_up_pointers_from(this->index, e); - } - return iterator(last.node_pointer()); - } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(stable_vector & x) - { - STABLE_VECTOR_CHECK_INVARIANT; - container_detail::bool_ flag; - container_detail::swap_alloc(this->priv_node_alloc(), x.priv_node_alloc(), flag); - //vector's allocator is swapped here - this->index.swap(x.index); - this->priv_swap_members(x); - } - - //! Effects: Erases all the elements of the stable_vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements in the stable_vector. - void clear() BOOST_CONTAINER_NOEXCEPT - { this->erase(this->cbegin(),this->cend()); } - - /// @cond - - private: - - class insert_rollback - { - public: - - insert_rollback(stable_vector &sv, index_iterator &it_past_constructed, const index_iterator &it_past_new) - : m_sv(sv), m_it_past_constructed(it_past_constructed), m_it_past_new(it_past_new) - {} - - ~insert_rollback() - { - if(m_it_past_constructed != m_it_past_new){ - m_sv.priv_put_in_pool(node_ptr_traits::static_cast_from(*m_it_past_constructed)); - index_iterator e = m_sv.index.erase(m_it_past_constructed, m_it_past_new); - index_traits_type::fix_up_pointers_from(m_sv.index, e); - } - } - - private: - stable_vector &m_sv; - index_iterator &m_it_past_constructed; - const index_iterator &m_it_past_new; - }; - - class push_back_rollback - { - public: - push_back_rollback(stable_vector &sv, const node_ptr &p) - : m_sv(sv), m_p(p) - {} - - ~push_back_rollback() - { - if(m_p){ - m_sv.priv_put_in_pool(m_p); - } - } - - void release() - { m_p = node_ptr(); } - - private: - stable_vector &m_sv; - node_ptr m_p; - }; - - index_iterator priv_insert_forward_non_templated(size_type pos, size_type num_new) - { - index_traits_type::initialize_end_node(this->index, this->internal_data.end_node, num_new); - - //Now try to fill the pool with new data - if(this->internal_data.pool_size < num_new){ - this->priv_increase_pool(num_new - this->internal_data.pool_size); - } - - //Now try to make room in the vector - const node_base_ptr_ptr old_buffer = this->index.data(); - this->index.insert(this->index.begin() + pos, num_new, node_ptr()); - bool new_buffer = this->index.data() != old_buffer; - - //Fix the pointers for the newly allocated buffer - const index_iterator index_beg = this->index.begin(); - if(new_buffer){ - index_traits_type::fix_up_pointers(index_beg, index_beg + pos); - } - return index_beg + pos; - } - - bool priv_capacity_bigger_than_size() const - { - return this->index.capacity() > this->index.size() && - this->internal_data.pool_size > 0; - } - - template - void priv_push_back(BOOST_MOVE_CATCH_FWD(U) x) - { - if(this->priv_capacity_bigger_than_size()){ - //Enough memory in the pool and in the index - const node_ptr p = this->priv_get_from_pool(); - BOOST_ASSERT(!!p); - { - push_back_rollback rollback(*this, p); - //This might throw - this->priv_build_node_from_convertible(p, ::boost::forward(x)); - rollback.release(); - } - //This can't throw as there is room for a new elements in the index - index_iterator new_index = this->index.insert(this->index.end() - ExtraPointers, p); - index_traits_type::fix_up_pointers_from(this->index, new_index); - } - else{ - this->insert(this->cend(), ::boost::forward(x)); - } - } - - iterator priv_insert(const_iterator position, const value_type &t) - { - typedef constant_iterator cvalue_iterator; - return this->insert(position, cvalue_iterator(t, 1), cvalue_iterator()); - } - - iterator priv_insert(const_iterator position, BOOST_RV_REF(T) x) - { - typedef repeat_iterator repeat_it; - typedef boost::move_iterator repeat_move_it; - //Just call more general insert(pos, size, value) and return iterator - return this->insert(position, repeat_move_it(repeat_it(x, 1)), repeat_move_it(repeat_it())); - } - - void priv_clear_pool() - { - if(!this->index.empty() && this->index.back()){ - node_base_ptr &pool_first_ref = *(this->index.end() - 2); - node_base_ptr &pool_last_ref = this->index.back(); - - multiallocation_chain holder; - holder.incorporate_after( holder.before_begin() - , node_ptr_traits::static_cast_from(pool_first_ref) - , node_ptr_traits::static_cast_from(pool_last_ref) - , internal_data.pool_size); - this->deallocate_individual(holder); - pool_first_ref = pool_last_ref = 0; - this->internal_data.pool_size = 0; - } - } - - void priv_increase_pool(size_type n) - { - node_base_ptr &pool_first_ref = *(this->index.end() - 2); - node_base_ptr &pool_last_ref = this->index.back(); - multiallocation_chain holder; - holder.incorporate_after( holder.before_begin() - , node_ptr_traits::static_cast_from(pool_first_ref) - , node_ptr_traits::static_cast_from(pool_last_ref) - , internal_data.pool_size); - multiallocation_chain m; - this->allocate_individual(n, m); - holder.splice_after(holder.before_begin(), m, m.before_begin(), m.last(), n); - this->internal_data.pool_size += n; - std::pair data(holder.extract_data()); - pool_first_ref = data.first; - pool_last_ref = data.second; - } - - void priv_put_in_pool(const node_ptr &p) - { - node_base_ptr &pool_first_ref = *(this->index.end()-2); - node_base_ptr &pool_last_ref = this->index.back(); - multiallocation_chain holder; - holder.incorporate_after( holder.before_begin() - , node_ptr_traits::static_cast_from(pool_first_ref) - , node_ptr_traits::static_cast_from(pool_last_ref) - , internal_data.pool_size); - holder.push_front(p); - ++this->internal_data.pool_size; - std::pair ret(holder.extract_data()); - pool_first_ref = ret.first; - pool_last_ref = ret.second; - } - - void priv_put_in_pool(multiallocation_chain &ch) - { - node_base_ptr &pool_first_ref = *(this->index.end()-(ExtraPointers-1)); - node_base_ptr &pool_last_ref = this->index.back(); - ch.incorporate_after( ch.before_begin() - , node_ptr_traits::static_cast_from(pool_first_ref) - , node_ptr_traits::static_cast_from(pool_last_ref) - , internal_data.pool_size); - this->internal_data.pool_size = ch.size(); - const std::pair ret(ch.extract_data()); - pool_first_ref = ret.first; - pool_last_ref = ret.second; - } - - node_ptr priv_get_from_pool() - { - //Precondition: index is not empty - BOOST_ASSERT(!this->index.empty()); - node_base_ptr &pool_first_ref = *(this->index.end() - (ExtraPointers-1)); - node_base_ptr &pool_last_ref = this->index.back(); - multiallocation_chain holder; - holder.incorporate_after( holder.before_begin() - , node_ptr_traits::static_cast_from(pool_first_ref) - , node_ptr_traits::static_cast_from(pool_last_ref) - , internal_data.pool_size); - node_ptr ret = holder.pop_front(); - --this->internal_data.pool_size; - if(!internal_data.pool_size){ - pool_first_ref = pool_last_ref = node_ptr(); - } - else{ - const std::pair data(holder.extract_data()); - pool_first_ref = data.first; - pool_last_ref = data.second; - } - return ret; - } - - node_ptr priv_get_end_node() const - { - return node_ptr_traits::pointer_to - (static_cast(const_cast(this->internal_data.end_node))); - } - - void priv_destroy_node(const node_type &n) - { - allocator_traits:: - destroy(this->priv_node_alloc(), container_detail::addressof(n.value)); - static_cast(&n)->~node_base_type(); - } - - void priv_delete_node(const node_ptr &n) - { - this->priv_destroy_node(*n); - this->priv_put_in_pool(n); - } - - template - void priv_build_node_from_it(const node_ptr &p, const index_iterator &up_index, const Iterator &it) - { - //This can throw - boost::container::construct_in_place - ( this->priv_node_alloc() - , container_detail::addressof(p->value) - , it); - //This does not throw - ::new(static_cast(container_detail::to_raw_pointer(p))) - node_base_type(index_traits_type::ptr_to_node_base_ptr(*up_index)); - } - - template - void priv_build_node_from_convertible(const node_ptr &p, BOOST_FWD_REF(ValueConvertible) value_convertible) - { - //This can throw - boost::container::allocator_traits::construct - ( this->priv_node_alloc() - , container_detail::addressof(p->value) - , ::boost::forward(value_convertible)); - //This does not throw - ::new(static_cast(container_detail::to_raw_pointer(p))) node_base_type; - } - - void priv_swap_members(stable_vector &x) - { - boost::container::swap_dispatch(this->internal_data.pool_size, x.internal_data.pool_size); - index_traits_type::readjust_end_node(this->index, this->internal_data.end_node); - index_traits_type::readjust_end_node(x.index, x.internal_data.end_node); - } - - #if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) - bool priv_invariant()const - { - index_type & index_ref = const_cast(this->index); - - if(index.empty()) - return !this->capacity() && !this->size(); - if(this->priv_get_end_node() != *(index.end() - ExtraPointers)){ - return false; - } - - if(!index_traits_type::invariants(index_ref)){ - return false; - } - - size_type n = this->capacity() - this->size(); - node_base_ptr &pool_first_ref = *(index_ref.end() - (ExtraPointers-1)); - node_base_ptr &pool_last_ref = index_ref.back(); - multiallocation_chain holder; - holder.incorporate_after( holder.before_begin() - , node_ptr_traits::static_cast_from(pool_first_ref) - , node_ptr_traits::static_cast_from(pool_last_ref) - , internal_data.pool_size); - typename multiallocation_chain::iterator beg(holder.begin()), end(holder.end()); - size_type num_pool = 0; - while(beg != end){ - ++num_pool; - ++beg; - } - return n >= num_pool && num_pool == internal_data.pool_size; - } - - class invariant_checker - { - invariant_checker(const invariant_checker &); - invariant_checker & operator=(const invariant_checker &); - const stable_vector* p; - - public: - invariant_checker(const stable_vector& v):p(&v){} - ~invariant_checker(){BOOST_ASSERT(p->priv_invariant());} - void touch(){} - }; - #endif - - class ebo_holder - : public node_allocator_type - { - private: - BOOST_MOVABLE_BUT_NOT_COPYABLE(ebo_holder) - - public: - template - explicit ebo_holder(BOOST_FWD_REF(AllocatorRLValue) a) - : node_allocator_type(boost::forward(a)) - , pool_size(0) - , end_node() - {} - - ebo_holder() - : node_allocator_type() - , pool_size(0) - , end_node() - {} - - size_type pool_size; - node_base_type end_node; - } internal_data; - - node_allocator_type &priv_node_alloc() { return internal_data; } - const node_allocator_type &priv_node_alloc() const { return internal_data; } - - index_type index; - /// @endcond -}; - -template -bool operator==(const stable_vector& x,const stable_vector& y) -{ - return x.size()==y.size()&&std::equal(x.begin(),x.end(),y.begin()); -} - -template -bool operator< (const stable_vector& x,const stable_vector& y) -{ - return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end()); -} - -template -bool operator!=(const stable_vector& x,const stable_vector& y) -{ - return !(x==y); -} - -template -bool operator> (const stable_vector& x,const stable_vector& y) -{ - return y -bool operator>=(const stable_vector& x,const stable_vector& y) -{ - return !(x -bool operator<=(const stable_vector& x,const stable_vector& y) -{ - return !(x>y); -} - -// specialized algorithms: - -template -void swap(stable_vector& x,stable_vector& y) -{ - x.swap(y); -} - -/// @cond - -#undef STABLE_VECTOR_CHECK_INVARIANT - -/// @endcond - -/* - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > - : public has_trivial_destructor_after_move::value -{}; - -*/ - -}} - -#include - -#endif //BOOST_CONTAINER_STABLE_VECTOR_HPP diff --git a/utils/boost_idb/boost/container/static_vector.hpp b/utils/boost_idb/boost/container/static_vector.hpp deleted file mode 100644 index 6ca0f4fe..00000000 --- a/utils/boost_idb/boost/container/static_vector.hpp +++ /dev/null @@ -1,1091 +0,0 @@ -// Boost.Container static_vector -// -// Copyright (c) 2012-2013 Adam Wulkiewicz, Lodz, Poland. -// Copyright (c) 2011-2013 Andrew Hundt. -// -// Use, modification and distribution is subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef BOOST_CONTAINER_STATIC_VECTOR_HPP -#define BOOST_CONTAINER_STATIC_VECTOR_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include - -#include -#include - -namespace boost { namespace container { - -namespace container_detail { - -template -class static_storage_allocator -{ - public: - typedef T value_type; - - static_storage_allocator() BOOST_CONTAINER_NOEXCEPT - {} - - static_storage_allocator(const static_storage_allocator &) BOOST_CONTAINER_NOEXCEPT - {} - - static_storage_allocator & operator=(const static_storage_allocator &) BOOST_CONTAINER_NOEXCEPT - {} - - T* internal_storage() const BOOST_CONTAINER_NOEXCEPT - { return const_cast(static_cast(static_cast(&storage))); } - - T* internal_storage() BOOST_CONTAINER_NOEXCEPT - { return static_cast(static_cast(&storage)); } - - static const std::size_t internal_capacity = N; - - typedef boost::container::container_detail::version_type version; - - friend bool operator==(const static_storage_allocator &, const static_storage_allocator &) BOOST_CONTAINER_NOEXCEPT - { return false; } - - friend bool operator!=(const static_storage_allocator &, const static_storage_allocator &) BOOST_CONTAINER_NOEXCEPT - { return true; } - - private: - typename boost::aligned_storage - ::value>::type storage; -}; - -} //namespace container_detail { - -/** - * @defgroup static_vector_non_member static_vector non-member functions - */ - -/** - * @brief A variable-size array container with fixed capacity. - * - * static_vector is a sequence container like boost::container::vector with contiguous storage that can - * change in size, along with the static allocation, low overhead, and fixed capacity of boost::array. - * - * A static_vector is a sequence that supports random access to elements, constant time insertion and - * removal of elements at the end, and linear time insertion and removal of elements at the beginning or - * in the middle. The number of elements in a static_vector may vary dynamically up to a fixed capacity - * because elements are stored within the object itself similarly to an array. However, objects are - * initialized as they are inserted into static_vector unlike C arrays or std::array which must construct - * all elements on instantiation. The behavior of static_vector enables the use of statically allocated - * elements in cases with complex object lifetime requirements that would otherwise not be trivially - * possible. - * - * @par Error Handling - * Insertion beyond the capacity result in throwing std::bad_alloc() if exceptions are enabled or - * calling throw_bad_alloc() if not enabled. - * - * std::out_of_range is thrown if out of bound access is performed in `at()` if exceptions are - * enabled, throw_out_of_range() if not enabled. - * - * @tparam Value The type of element that will be stored. - * @tparam Capacity The maximum number of elements static_vector can store, fixed at compile time. - */ -template -class static_vector - : public vector > -{ - typedef vector > base_t; - - BOOST_COPYABLE_AND_MOVABLE(static_vector) - - template - friend class static_vector; - -public: - //! @brief The type of elements stored in the container. - typedef typename base_t::value_type value_type; - //! @brief The unsigned integral type used by the container. - typedef typename base_t::size_type size_type; - //! @brief The pointers difference type. - typedef typename base_t::difference_type difference_type; - //! @brief The pointer type. - typedef typename base_t::pointer pointer; - //! @brief The const pointer type. - typedef typename base_t::const_pointer const_pointer; - //! @brief The value reference type. - typedef typename base_t::reference reference; - //! @brief The value const reference type. - typedef typename base_t::const_reference const_reference; - //! @brief The iterator type. - typedef typename base_t::iterator iterator; - //! @brief The const iterator type. - typedef typename base_t::const_iterator const_iterator; - //! @brief The reverse iterator type. - typedef typename base_t::reverse_iterator reverse_iterator; - //! @brief The const reverse iterator. - typedef typename base_t::const_reverse_iterator const_reverse_iterator; - - //! @brief Constructs an empty static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - static_vector() BOOST_CONTAINER_NOEXCEPT - : base_t() - {} - - //! @pre count <= capacity() - //! - //! @brief Constructs a static_vector containing count value initialized values. - //! - //! @param count The number of values which will be contained in the container. - //! - //! @par Throws - //! If Value's default constructor throws. - //! - //! @par Complexity - //! Linear O(N). - explicit static_vector(size_type count) - : base_t(count) - {} - - //! @pre count <= capacity() - //! - //! @brief Constructs a static_vector containing count value initialized values. - //! - //! @param count The number of values which will be contained in the container. - //! - //! @par Throws - //! If Value's default constructor throws. - //! - //! @par Complexity - //! Linear O(N). - //! - //! @par Note - //! Non-standard extension - static_vector(size_type count, default_init_t) - : base_t(count, default_init_t()) - {} - - //! @pre count <= capacity() - //! - //! @brief Constructs a static_vector containing count copies of value. - //! - //! @param count The number of copies of a values that will be contained in the container. - //! @param value The value which will be used to copy construct values. - //! - //! @par Throws - //! If Value's copy constructor throws. - //! - //! @par Complexity - //! Linear O(N). - static_vector(size_type count, value_type const& value) - : base_t(count, value) - {} - - //! @pre - //! @li distance(first, last) <= capacity() - //! @li Iterator must meet the \c ForwardTraversalIterator concept. - //! - //! @brief Constructs a static_vector containing copy of a range [first, last). - //! - //! @param first The iterator to the first element in range. - //! @param last The iterator to the one after the last element in range. - //! - //! @par Throws - //! If Value's constructor taking a dereferenced Iterator throws. - //! - //! @par Complexity - //! Linear O(N). - template - static_vector(Iterator first, Iterator last) - : base_t(first, last) - {} - - //! @brief Constructs a copy of other static_vector. - //! - //! @param other The static_vector which content will be copied to this one. - //! - //! @par Throws - //! If Value's copy constructor throws. - //! - //! @par Complexity - //! Linear O(N). - static_vector(static_vector const& other) - : base_t(other) - {} - - //! @pre other.size() <= capacity(). - //! - //! @brief Constructs a copy of other static_vector. - //! - //! @param other The static_vector which content will be copied to this one. - //! - //! @par Throws - //! If Value's copy constructor throws. - //! - //! @par Complexity - //! Linear O(N). - template - static_vector(static_vector const& other) : base_t(other) {} - - //! @brief Copy assigns Values stored in the other static_vector to this one. - //! - //! @param other The static_vector which content will be copied to this one. - //! - //! @par Throws - //! If Value's copy constructor or copy assignment throws. - //! - //! @par Complexity - //! Linear O(N). - static_vector & operator=(BOOST_COPY_ASSIGN_REF(static_vector) other) - { - base_t::operator=(static_cast(other)); - return *this; - } - - //! @pre other.size() <= capacity() - //! - //! @brief Copy assigns Values stored in the other static_vector to this one. - //! - //! @param other The static_vector which content will be copied to this one. - //! - //! @par Throws - //! If Value's copy constructor or copy assignment throws. - //! - //! @par Complexity - //! Linear O(N). - template -// TEMPORARY WORKAROUND -#if defined(BOOST_NO_RVALUE_REFERENCES) - static_vector & operator=(::boost::rv< static_vector > const& other) -#else - static_vector & operator=(static_vector const& other) -#endif - { - base_t::operator=(static_cast const&>(other)); - return *this; - } - - //! @brief Move constructor. Moves Values stored in the other static_vector to this one. - //! - //! @param other The static_vector which content will be moved to this one. - //! - //! @par Throws - //! @li If \c boost::has_nothrow_move::value is \c true and Value's move constructor throws. - //! @li If \c boost::has_nothrow_move::value is \c false and Value's copy constructor throws. - //! - //! @par Complexity - //! Linear O(N). - static_vector(BOOST_RV_REF(static_vector) other) - : base_t(boost::move(static_cast(other))) - {} - - //! @pre other.size() <= capacity() - //! - //! @brief Move constructor. Moves Values stored in the other static_vector to this one. - //! - //! @param other The static_vector which content will be moved to this one. - //! - //! @par Throws - //! @li If \c boost::has_nothrow_move::value is \c true and Value's move constructor throws. - //! @li If \c boost::has_nothrow_move::value is \c false and Value's copy constructor throws. - //! - //! @par Complexity - //! Linear O(N). - template - static_vector(BOOST_RV_REF_BEG static_vector BOOST_RV_REF_END other) - : base_t(boost::move(static_cast::base_t&>(other))) - {} - - //! @brief Move assignment. Moves Values stored in the other static_vector to this one. - //! - //! @param other The static_vector which content will be moved to this one. - //! - //! @par Throws - //! @li If \c boost::has_nothrow_move::value is \c true and Value's move constructor or move assignment throws. - //! @li If \c boost::has_nothrow_move::value is \c false and Value's copy constructor or copy assignment throws. - //! - //! @par Complexity - //! Linear O(N). - static_vector & operator=(BOOST_RV_REF(static_vector) other) - { - base_t::operator=(boost::move(static_cast(other))); - return *this; - } - - //! @pre other.size() <= capacity() - //! - //! @brief Move assignment. Moves Values stored in the other static_vector to this one. - //! - //! @param other The static_vector which content will be moved to this one. - //! - //! @par Throws - //! @li If \c boost::has_nothrow_move::value is \c true and Value's move constructor or move assignment throws. - //! @li If \c boost::has_nothrow_move::value is \c false and Value's copy constructor or copy assignment throws. - //! - //! @par Complexity - //! Linear O(N). - template - static_vector & operator=(BOOST_RV_REF_BEG static_vector BOOST_RV_REF_END other) - { - base_t::operator=(boost::move(static_cast::base_t&>(other))); - return *this; - } - -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED - - //! @brief Destructor. Destroys Values stored in this container. - //! - //! @par Throws - //! Nothing - //! - //! @par Complexity - //! Linear O(N). - ~static_vector(); - - //! @brief Swaps contents of the other static_vector and this one. - //! - //! @param other The static_vector which content will be swapped with this one's content. - //! - //! @par Throws - //! @li If \c boost::has_nothrow_move::value is \c true and Value's move constructor or move assignment throws, - //! @li If \c boost::has_nothrow_move::value is \c false and Value's copy constructor or copy assignment throws, - //! - //! @par Complexity - //! Linear O(N). - void swap(static_vector & other); - - //! @pre other.size() <= capacity() && size() <= other.capacity() - //! - //! @brief Swaps contents of the other static_vector and this one. - //! - //! @param other The static_vector which content will be swapped with this one's content. - //! - //! @par Throws - //! @li If \c boost::has_nothrow_move::value is \c true and Value's move constructor or move assignment throws, - //! @li If \c boost::has_nothrow_move::value is \c false and Value's copy constructor or copy assignment throws, - //! - //! @par Complexity - //! Linear O(N). - template - void swap(static_vector & other); - - //! @pre count <= capacity() - //! - //! @brief Inserts or erases elements at the end such that - //! the size becomes count. New elements are value initialized. - //! - //! @param count The number of elements which will be stored in the container. - //! - //! @par Throws - //! If Value's default constructor throws. - //! - //! @par Complexity - //! Linear O(N). - void resize(size_type count); - - //! @pre count <= capacity() - //! - //! @brief Inserts or erases elements at the end such that - //! the size becomes count. New elements are default initialized. - //! - //! @param count The number of elements which will be stored in the container. - //! - //! @par Throws - //! If Value's default constructor throws. - //! - //! @par Complexity - //! Linear O(N). - //! - //! @par Note - //! Non-standard extension - void resize(size_type count, default_init_t); - - //! @pre count <= capacity() - //! - //! @brief Inserts or erases elements at the end such that - //! the size becomes count. New elements are copy constructed from value. - //! - //! @param count The number of elements which will be stored in the container. - //! @param value The value used to copy construct the new element. - //! - //! @par Throws - //! If Value's copy constructor throws. - //! - //! @par Complexity - //! Linear O(N). - void resize(size_type count, value_type const& value); - - //! @pre count <= capacity() - //! - //! @brief This call has no effect because the Capacity of this container is constant. - //! - //! @param count The number of elements which the container should be able to contain. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Linear O(N). - void reserve(size_type count) BOOST_CONTAINER_NOEXCEPT; - - //! @pre size() < capacity() - //! - //! @brief Adds a copy of value at the end. - //! - //! @param value The value used to copy construct the new element. - //! - //! @par Throws - //! If Value's copy constructor throws. - //! - //! @par Complexity - //! Constant O(1). - void push_back(value_type const& value); - - //! @pre size() < capacity() - //! - //! @brief Moves value to the end. - //! - //! @param value The value to move construct the new element. - //! - //! @par Throws - //! If Value's move constructor throws. - //! - //! @par Complexity - //! Constant O(1). - void push_back(BOOST_RV_REF(value_type) value); - - //! @pre !empty() - //! - //! @brief Destroys last value and decreases the size. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - void pop_back(); - - //! @pre - //! @li \c position must be a valid iterator of \c *this in range [begin(), end()]. - //! @li size() < capacity() - //! - //! @brief Inserts a copy of element at position. - //! - //! @param position The position at which the new value will be inserted. - //! @param value The value used to copy construct the new element. - //! - //! @par Throws - //! @li If Value's copy constructor or copy assignment throws - //! @li If Value's move constructor or move assignment throws. - //! - //! @par Complexity - //! Constant or linear. - iterator insert(iterator position, value_type const& value); - - //! @pre - //! @li \c position must be a valid iterator of \c *this in range [begin(), end()]. - //! @li size() < capacity() - //! - //! @brief Inserts a move-constructed element at position. - //! - //! @param position The position at which the new value will be inserted. - //! @param value The value used to move construct the new element. - //! - //! @par Throws - //! If Value's move constructor or move assignment throws. - //! - //! @par Complexity - //! Constant or linear. - iterator insert(iterator position, BOOST_RV_REF(value_type) value); - - //! @pre - //! @li \c position must be a valid iterator of \c *this in range [begin(), end()]. - //! @li size() + count <= capacity() - //! - //! @brief Inserts a count copies of value at position. - //! - //! @param position The position at which new elements will be inserted. - //! @param count The number of new elements which will be inserted. - //! @param value The value used to copy construct new elements. - //! - //! @par Throws - //! @li If Value's copy constructor or copy assignment throws. - //! @li If Value's move constructor or move assignment throws. - //! - //! @par Complexity - //! Linear O(N). - iterator insert(iterator position, size_type count, value_type const& value); - - //! @pre - //! @li \c position must be a valid iterator of \c *this in range [begin(), end()]. - //! @li distance(first, last) <= capacity() - //! @li \c Iterator must meet the \c ForwardTraversalIterator concept. - //! - //! @brief Inserts a copy of a range [first, last) at position. - //! - //! @param position The position at which new elements will be inserted. - //! @param first The iterator to the first element of a range used to construct new elements. - //! @param last The iterator to the one after the last element of a range used to construct new elements. - //! - //! @par Throws - //! @li If Value's constructor and assignment taking a dereferenced \c Iterator. - //! @li If Value's move constructor or move assignment throws. - //! - //! @par Complexity - //! Linear O(N). - template - iterator insert(iterator position, Iterator first, Iterator last); - - //! @pre \c position must be a valid iterator of \c *this in range [begin(), end()) - //! - //! @brief Erases Value from position. - //! - //! @param position The position of the element which will be erased from the container. - //! - //! @par Throws - //! If Value's move assignment throws. - //! - //! @par Complexity - //! Linear O(N). - iterator erase(iterator position); - - //! @pre - //! @li \c first and \c last must define a valid range - //! @li iterators must be in range [begin(), end()] - //! - //! @brief Erases Values from a range [first, last). - //! - //! @param first The position of the first element of a range which will be erased from the container. - //! @param last The position of the one after the last element of a range which will be erased from the container. - //! - //! @par Throws - //! If Value's move assignment throws. - //! - //! @par Complexity - //! Linear O(N). - iterator erase(iterator first, iterator last); - - //! @pre distance(first, last) <= capacity() - //! - //! @brief Assigns a range [first, last) of Values to this container. - //! - //! @param first The iterator to the first element of a range used to construct new content of this container. - //! @param last The iterator to the one after the last element of a range used to construct new content of this container. - //! - //! @par Throws - //! If Value's copy constructor or copy assignment throws, - //! - //! @par Complexity - //! Linear O(N). - template - void assign(Iterator first, Iterator last); - - //! @pre count <= capacity() - //! - //! @brief Assigns a count copies of value to this container. - //! - //! @param count The new number of elements which will be container in the container. - //! @param value The value which will be used to copy construct the new content. - //! - //! @par Throws - //! If Value's copy constructor or copy assignment throws. - //! - //! @par Complexity - //! Linear O(N). - void assign(size_type count, value_type const& value); - - //! @pre size() < capacity() - //! - //! @brief Inserts a Value constructed with - //! \c std::forward(args)... in the end of the container. - //! - //! @param args The arguments of the constructor of the new element which will be created at the end of the container. - //! - //! @par Throws - //! If in-place constructor throws or Value's move constructor throws. - //! - //! @par Complexity - //! Constant O(1). - template - void emplace_back(Args &&...args); - - //! @pre - //! @li \c position must be a valid iterator of \c *this in range [begin(), end()] - //! @li size() < capacity() - //! - //! @brief Inserts a Value constructed with - //! \c std::forward(args)... before position - //! - //! @param position The position at which new elements will be inserted. - //! @param args The arguments of the constructor of the new element. - //! - //! @par Throws - //! If in-place constructor throws or if Value's move constructor or move assignment throws. - //! - //! @par Complexity - //! Constant or linear. - template - iterator emplace(iterator position, Args &&...args); - - //! @brief Removes all elements from the container. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - void clear() BOOST_CONTAINER_NOEXCEPT; - - //! @pre i < size() - //! - //! @brief Returns reference to the i-th element. - //! - //! @param i The element's index. - //! - //! @return reference to the i-th element - //! from the beginning of the container. - //! - //! @par Throws - //! \c std::out_of_range exception by default. - //! - //! @par Complexity - //! Constant O(1). - reference at(size_type i); - - //! @pre i < size() - //! - //! @brief Returns const reference to the i-th element. - //! - //! @param i The element's index. - //! - //! @return const reference to the i-th element - //! from the beginning of the container. - //! - //! @par Throws - //! \c std::out_of_range exception by default. - //! - //! @par Complexity - //! Constant O(1). - const_reference at(size_type i) const; - - //! @pre i < size() - //! - //! @brief Returns reference to the i-th element. - //! - //! @param i The element's index. - //! - //! @return reference to the i-th element - //! from the beginning of the container. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - reference operator[](size_type i); - - //! @pre i < size() - //! - //! @brief Returns const reference to the i-th element. - //! - //! @param i The element's index. - //! - //! @return const reference to the i-th element - //! from the beginning of the container. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - const_reference operator[](size_type i) const; - - //! @pre \c !empty() - //! - //! @brief Returns reference to the first element. - //! - //! @return reference to the first element - //! from the beginning of the container. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - reference front(); - - //! @pre \c !empty() - //! - //! @brief Returns const reference to the first element. - //! - //! @return const reference to the first element - //! from the beginning of the container. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - const_reference front() const; - - //! @pre \c !empty() - //! - //! @brief Returns reference to the last element. - //! - //! @return reference to the last element - //! from the beginning of the container. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - reference back(); - - //! @pre \c !empty() - //! - //! @brief Returns const reference to the first element. - //! - //! @return const reference to the last element - //! from the beginning of the container. - //! - //! @par Throws - //! Nothing by default. - //! - //! @par Complexity - //! Constant O(1). - const_reference back() const; - - //! @brief Pointer such that [data(), data() + size()) is a valid range. - //! For a non-empty vector data() == &front(). - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - Value * data() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Const pointer such that [data(), data() + size()) is a valid range. - //! For a non-empty vector data() == &front(). - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const Value * data() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns iterator to the first element. - //! - //! @return iterator to the first element contained in the vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - iterator begin() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const iterator to the first element. - //! - //! @return const_iterator to the first element contained in the vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const iterator to the first element. - //! - //! @return const_iterator to the first element contained in the vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns iterator to the one after the last element. - //! - //! @return iterator pointing to the one after the last element contained in the vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - iterator end() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const iterator to the one after the last element. - //! - //! @return const_iterator pointing to the one after the last element contained in the vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_iterator end() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const iterator to the one after the last element. - //! - //! @return const_iterator pointing to the one after the last element contained in the vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns reverse iterator to the first element of the reversed container. - //! - //! @return reverse_iterator pointing to the beginning - //! of the reversed static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const reverse iterator to the first element of the reversed container. - //! - //! @return const_reverse_iterator pointing to the beginning - //! of the reversed static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const reverse iterator to the first element of the reversed container. - //! - //! @return const_reverse_iterator pointing to the beginning - //! of the reversed static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns reverse iterator to the one after the last element of the reversed container. - //! - //! @return reverse_iterator pointing to the one after the last element - //! of the reversed static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const reverse iterator to the one after the last element of the reversed container. - //! - //! @return const_reverse_iterator pointing to the one after the last element - //! of the reversed static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns const reverse iterator to the one after the last element of the reversed container. - //! - //! @return const_reverse_iterator pointing to the one after the last element - //! of the reversed static_vector. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns container's capacity. - //! - //! @return container's capacity. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - static size_type capacity() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns container's capacity. - //! - //! @return container's capacity. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - static size_type max_size() BOOST_CONTAINER_NOEXCEPT; - - //! @brief Returns the number of stored elements. - //! - //! @return Number of elements contained in the container. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - size_type size() const BOOST_CONTAINER_NOEXCEPT; - - //! @brief Queries if the container contains elements. - //! - //! @return true if the number of elements contained in the - //! container is equal to 0. - //! - //! @par Throws - //! Nothing. - //! - //! @par Complexity - //! Constant O(1). - bool empty() const BOOST_CONTAINER_NOEXCEPT; -#else - - friend void swap(static_vector &x, static_vector &y) - { - x.swap(y); - } - -#endif // BOOST_CONTAINER_DOXYGEN_INVOKED - -}; - -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED - -//! @brief Checks if contents of two static_vectors are equal. -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @return \c true if containers have the same size and elements in both containers are equal. -//! -//! @par Complexity -//! Linear O(N). -template -bool operator== (static_vector const& x, static_vector const& y); - -//! @brief Checks if contents of two static_vectors are not equal. -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @return \c true if containers have different size or elements in both containers are not equal. -//! -//! @par Complexity -//! Linear O(N). -template -bool operator!= (static_vector const& x, static_vector const& y); - -//! @brief Lexicographically compares static_vectors. -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @return \c true if x compares lexicographically less than y. -//! -//! @par Complexity -//! Linear O(N). -template -bool operator< (static_vector const& x, static_vector const& y); - -//! @brief Lexicographically compares static_vectors. -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @return \c true if y compares lexicographically less than x. -//! -//! @par Complexity -//! Linear O(N). -template -bool operator> (static_vector const& x, static_vector const& y); - -//! @brief Lexicographically compares static_vectors. -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @return \c true if y don't compare lexicographically less than x. -//! -//! @par Complexity -//! Linear O(N). -template -bool operator<= (static_vector const& x, static_vector const& y); - -//! @brief Lexicographically compares static_vectors. -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @return \c true if x don't compare lexicographically less than y. -//! -//! @par Complexity -//! Linear O(N). -template -bool operator>= (static_vector const& x, static_vector const& y); - -//! @brief Swaps contents of two static_vectors. -//! -//! This function calls static_vector::swap(). -//! -//! @ingroup static_vector_non_member -//! -//! @param x The first static_vector. -//! @param y The second static_vector. -//! -//! @par Complexity -//! Linear O(N). -template -inline void swap(static_vector & x, static_vector & y); - -#else - -template -inline void swap(static_vector & x, static_vector & y - , typename container_detail::enable_if_c< C1 != C2>::type * = 0) -{ - x.swap(y); -} - -#endif // BOOST_CONTAINER_DOXYGEN_INVOKED - -}} // namespace boost::container - -#include - -#endif // BOOST_CONTAINER_STATIC_VECTOR_HPP diff --git a/utils/boost_idb/boost/container/string.hpp b/utils/boost_idb/boost/container/string.hpp deleted file mode 100644 index e0063261..00000000 --- a/utils/boost_idb/boost/container/string.hpp +++ /dev/null @@ -1,2834 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_STRING_HPP -#define BOOST_CONTAINER_STRING_HPP - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond -namespace container_detail { -// ------------------------------------------------------------ -// Class basic_string_base. - -// basic_string_base is a helper class that makes it it easier to write -// an exception-safe version of basic_string. The constructor allocates, -// but does not initialize, a block of memory. The destructor -// deallocates, but does not destroy elements within, a block of -// memory. The destructor assumes that the memory either is the internal buffer, -// or else points to a block of memory that was allocated using string_base's -// allocator and whose size is this->m_storage. -template -class basic_string_base -{ - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_string_base) - - typedef allocator_traits allocator_traits_type; - public: - typedef Allocator allocator_type; - typedef allocator_type stored_allocator_type; - typedef typename allocator_traits_type::pointer pointer; - typedef typename allocator_traits_type::value_type value_type; - typedef typename allocator_traits_type::size_type size_type; - typedef ::boost::intrusive::pointer_traits pointer_traits; - - basic_string_base() - : members_() - { init(); } - - basic_string_base(const allocator_type& a) - : members_(a) - { init(); } - - basic_string_base(const allocator_type& a, size_type n) - : members_(a) - { - this->init(); - this->allocate_initial_block(n); - } - - basic_string_base(BOOST_RV_REF(basic_string_base) b) - : members_(boost::move(b.alloc())) - { - this->init(); - this->swap_data(b); - } - - ~basic_string_base() - { - if(!this->is_short()){ - this->deallocate_block(); - this->is_short(true); - } - } - - private: - - //This is the structure controlling a long string - struct long_t - { - size_type is_short : 1; - size_type length : (sizeof(size_type)*CHAR_BIT - 1); - size_type storage; - pointer start; - - long_t() - {} - - long_t(const long_t &other) - { - this->is_short = other.is_short; - length = other.length; - storage = other.storage; - start = other.start; - } - - long_t &operator =(const long_t &other) - { - this->is_short = other.is_short; - length = other.length; - storage = other.storage; - start = other.start; - return *this; - } - }; - - //This type is the first part of the structure controlling a short string - //The "data" member stores - struct short_header - { - unsigned char is_short : 1; - unsigned char length : (CHAR_BIT - 1); - }; - - //This type has the same alignment and size as long_t but it's POD - //so, unlike long_t, it can be placed in a union - - typedef typename boost::aligned_storage< sizeof(long_t), - container_detail::alignment_of::value>::type long_raw_t; - - protected: - static const size_type MinInternalBufferChars = 8; - static const size_type AlignmentOfValueType = - alignment_of::value; - static const size_type ShortDataOffset = - container_detail::ct_rounded_size::value; - static const size_type ZeroCostInternalBufferChars = - (sizeof(long_t) - ShortDataOffset)/sizeof(value_type); - static const size_type UnalignedFinalInternalBufferChars = - (ZeroCostInternalBufferChars > MinInternalBufferChars) ? - ZeroCostInternalBufferChars : MinInternalBufferChars; - - struct short_t - { - short_header h; - value_type data[UnalignedFinalInternalBufferChars]; - }; - - union repr_t - { - long_raw_t r; - short_t s; - - const short_t &short_repr() const - { return s; } - - const long_t &long_repr() const - { return *static_cast(static_cast(&r)); } - - short_t &short_repr() - { return s; } - - long_t &long_repr() - { return *static_cast(static_cast(&r)); } - }; - - struct members_holder - : public Allocator - { - members_holder() - : Allocator() - {} - - template - explicit members_holder(BOOST_FWD_REF(AllocatorConvertible) a) - : Allocator(boost::forward(a)) - {} - - repr_t m_repr; - } members_; - - const Allocator &alloc() const - { return members_; } - - Allocator &alloc() - { return members_; } - - static const size_type InternalBufferChars = (sizeof(repr_t) - ShortDataOffset)/sizeof(value_type); - - private: - - static const size_type MinAllocation = InternalBufferChars*2; - - protected: - bool is_short() const - { return static_cast(this->members_.m_repr.s.h.is_short != 0); } - - void is_short(bool yes) - { - const bool was_short = this->is_short(); - if(yes && !was_short){ - allocator_traits_type::destroy - ( this->alloc() - , static_cast(static_cast(&this->members_.m_repr.r)) - ); - this->members_.m_repr.s.h.is_short = true; - } - else if(!yes && was_short){ - allocator_traits_type::construct - ( this->alloc() - , static_cast(static_cast(&this->members_.m_repr.r)) - ); - this->members_.m_repr.s.h.is_short = false; - } - } - - private: - void init() - { - this->members_.m_repr.s.h.is_short = 1; - this->members_.m_repr.s.h.length = 0; - } - - protected: - - typedef container_detail::integral_constant allocator_v1; - typedef container_detail::integral_constant allocator_v2; - typedef container_detail::integral_constant::value> alloc_version; - - std::pair - allocation_command(allocation_type command, - size_type limit_size, - size_type preferred_size, - size_type &received_size, pointer reuse = 0) - { - if(this->is_short() && (command & (expand_fwd | expand_bwd)) ){ - reuse = pointer(); - command &= ~(expand_fwd | expand_bwd); - } - return container_detail::allocator_version_traits::allocation_command - (this->alloc(), command, limit_size, preferred_size, received_size, reuse); - } - - size_type next_capacity(size_type additional_objects) const - { return get_next_capacity(allocator_traits_type::max_size(this->alloc()), this->priv_storage(), additional_objects); } - - void deallocate(pointer p, size_type n) - { - if (p && (n > InternalBufferChars)) - this->alloc().deallocate(p, n); - } - - void construct(pointer p, const value_type &value = value_type()) - { - allocator_traits_type::construct - ( this->alloc() - , container_detail::to_raw_pointer(p) - , value - ); - } - - void destroy(pointer p, size_type n) - { - value_type *raw_p = container_detail::to_raw_pointer(p); - for(; n--; ++raw_p){ - allocator_traits_type::destroy( this->alloc(), raw_p); - } - } - - void destroy(pointer p) - { - allocator_traits_type::destroy - ( this->alloc() - , container_detail::to_raw_pointer(p) - ); - } - - void allocate_initial_block(size_type n) - { - if (n <= this->max_size()) { - if(n > InternalBufferChars){ - size_type new_cap = this->next_capacity(n); - pointer p = this->allocation_command(allocate_new, n, new_cap, new_cap).first; - this->is_short(false); - this->priv_long_addr(p); - this->priv_long_size(0); - this->priv_storage(new_cap); - } - } - else{ - throw_length_error("basic_string::allocate_initial_block max_size() exceeded"); - } - } - - void deallocate_block() - { this->deallocate(this->priv_addr(), this->priv_storage()); } - - size_type max_size() const - { return allocator_traits_type::max_size(this->alloc()) - 1; } - - protected: - size_type priv_capacity() const - { return this->priv_storage() - 1; } - - pointer priv_short_addr() const - { return pointer_traits::pointer_to(const_cast(this->members_.m_repr.short_repr().data[0])); } - - pointer priv_long_addr() const - { return this->members_.m_repr.long_repr().start; } - - pointer priv_addr() const - { - return this->is_short() - ? priv_short_addr() - : priv_long_addr() - ; - } - - pointer priv_end_addr() const - { - return this->is_short() - ? this->priv_short_addr() + this->priv_short_size() - : this->priv_long_addr() + this->priv_long_size() - ; - } - - void priv_long_addr(pointer addr) - { this->members_.m_repr.long_repr().start = addr; } - - size_type priv_storage() const - { return this->is_short() ? priv_short_storage() : priv_long_storage(); } - - size_type priv_short_storage() const - { return InternalBufferChars; } - - size_type priv_long_storage() const - { return this->members_.m_repr.long_repr().storage; } - - void priv_storage(size_type storage) - { - if(!this->is_short()) - this->priv_long_storage(storage); - } - - void priv_long_storage(size_type storage) - { - this->members_.m_repr.long_repr().storage = storage; - } - - size_type priv_size() const - { return this->is_short() ? this->priv_short_size() : this->priv_long_size(); } - - size_type priv_short_size() const - { return this->members_.m_repr.short_repr().h.length; } - - size_type priv_long_size() const - { return this->members_.m_repr.long_repr().length; } - - void priv_size(size_type sz) - { - if(this->is_short()) - this->priv_short_size(sz); - else - this->priv_long_size(sz); - } - - void priv_short_size(size_type sz) - { - this->members_.m_repr.s.h.length = (unsigned char)sz; - } - - void priv_long_size(size_type sz) - { - this->members_.m_repr.long_repr().length = sz; - } - - void swap_data(basic_string_base& other) - { - if(this->is_short()){ - if(other.is_short()){ - std::swap(this->members_.m_repr, other.members_.m_repr); - } - else{ - short_t short_backup(this->members_.m_repr.short_repr()); - long_t long_backup (other.members_.m_repr.long_repr()); - other.members_.m_repr.long_repr().~long_t(); - ::new(&this->members_.m_repr.long_repr()) long_t; - this->members_.m_repr.long_repr() = long_backup; - other.members_.m_repr.short_repr() = short_backup; - } - } - else{ - if(other.is_short()){ - short_t short_backup(other.members_.m_repr.short_repr()); - long_t long_backup (this->members_.m_repr.long_repr()); - this->members_.m_repr.long_repr().~long_t(); - ::new(&other.members_.m_repr.long_repr()) long_t; - other.members_.m_repr.long_repr() = long_backup; - this->members_.m_repr.short_repr() = short_backup; - } - else{ - boost::container::swap_dispatch(this->members_.m_repr.long_repr(), other.members_.m_repr.long_repr()); - } - } - } -}; - -} //namespace container_detail { - -/// @endcond - -//! The basic_string class represents a Sequence of characters. It contains all the -//! usual operations of a Sequence, and, additionally, it contains standard string -//! operations such as search and concatenation. -//! -//! The basic_string class is parameterized by character type, and by that type's -//! Character Traits. -//! -//! This class has performance characteristics very much like vector<>, meaning, -//! for example, that it does not perform reference-count or copy-on-write, and that -//! concatenation of two strings is an O(N) operation. -//! -//! Some of basic_string's member functions use an unusual method of specifying positions -//! and ranges. In addition to the conventional method using iterators, many of -//! basic_string's member functions use a single value pos of type size_type to represent a -//! position (in which case the position is begin() + pos, and many of basic_string's -//! member functions use two values, pos and n, to represent a range. In that case pos is -//! the beginning of the range and n is its size. That is, the range is -//! [begin() + pos, begin() + pos + n). -//! -//! Note that the C++ standard does not specify the complexity of basic_string operations. -//! In this implementation, basic_string has performance characteristics very similar to -//! those of vector: access to a single character is O(1), while copy and concatenation -//! are O(N). -//! -//! In this implementation, begin(), -//! end(), rbegin(), rend(), operator[], c_str(), and data() do not invalidate iterators. -//! In this implementation, iterators are only invalidated by member functions that -//! explicitly change the string's contents. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class basic_string - : private container_detail::basic_string_base -{ - /// @cond - private: - typedef allocator_traits allocator_traits_type; - BOOST_COPYABLE_AND_MOVABLE(basic_string) - typedef container_detail::basic_string_base base_t; - static const typename base_t::size_type InternalBufferChars = base_t::InternalBufferChars; - - protected: - // Allocator helper class to use a char_traits as a function object. - - template - struct Eq_traits - : public std::binary_function - { - bool operator()(const typename Tr::char_type& x, - const typename Tr::char_type& y) const - { return Tr::eq(x, y); } - }; - - template - struct Not_within_traits - : public std::unary_function - { - typedef const typename Tr::char_type* Pointer; - const Pointer m_first; - const Pointer m_last; - - Not_within_traits(Pointer f, Pointer l) - : m_first(f), m_last(l) {} - - bool operator()(const typename Tr::char_type& x) const - { - return std::find_if(m_first, m_last, - std::bind1st(Eq_traits(), x)) == m_last; - } - }; - /// @endcond - - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - typedef Traits traits_type; - typedef CharT value_type; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef BOOST_CONTAINER_IMPDEF(allocator_type) stored_allocator_type; - typedef BOOST_CONTAINER_IMPDEF(pointer) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_pointer) const_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - static const size_type npos = size_type(-1); - - /// @cond - private: - typedef constant_iterator cvalue_iterator; - typedef typename base_t::allocator_v1 allocator_v1; - typedef typename base_t::allocator_v2 allocator_v2; - typedef typename base_t::alloc_version alloc_version; - typedef ::boost::intrusive::pointer_traits pointer_traits; - /// @endcond - - public: // Constructor, destructor, assignment. - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - /// @cond - struct reserve_t {}; - - basic_string(reserve_t, size_type n, - const allocator_type& a = allocator_type()) - //Select allocator as in copy constructor as reserve_t-based constructors - //are two step copies optimized for capacity - : base_t( allocator_traits_type::select_on_container_copy_construction(a) - , n + 1) - { this->priv_terminate_string(); } - - /// @endcond - - //! Effects: Default constructs a basic_string. - //! - //! Throws: If allocator_type's default constructor throws. - basic_string() - : base_t() - { this->priv_terminate_string(); } - - - //! Effects: Constructs a basic_string taking the allocator as parameter. - //! - //! Throws: Nothing - explicit basic_string(const allocator_type& a) BOOST_CONTAINER_NOEXCEPT - : base_t(a) - { this->priv_terminate_string(); } - - //! Effects: Copy constructs a basic_string. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocator_type's default constructor throws. - basic_string(const basic_string& s) - : base_t(allocator_traits_type::select_on_container_copy_construction(s.alloc())) - { - this->priv_terminate_string(); - this->assign(s.begin(), s.end()); - } - - //! Effects: Move constructor. Moves s's resources to *this. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - basic_string(BOOST_RV_REF(basic_string) s) BOOST_CONTAINER_NOEXCEPT - : base_t(boost::move((base_t&)s)) - {} - - //! Effects: Copy constructs a basic_string using the specified allocator. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocation throws. - basic_string(const basic_string& s, const allocator_type &a) - : base_t(a) - { - this->priv_terminate_string(); - this->assign(s.begin(), s.end()); - } - - //! Effects: Move constructor using the specified allocator. - //! Moves s's resources to *this. - //! - //! Throws: If allocation throws. - //! - //! Complexity: Constant if a == s.get_allocator(), linear otherwise. - basic_string(BOOST_RV_REF(basic_string) s, const allocator_type &a) - : base_t(a) - { - this->priv_terminate_string(); - if(a == this->alloc()){ - this->swap_data(s); - } - else{ - this->assign(s.begin(), s.end()); - } - } - - //! Effects: Constructs a basic_string taking the allocator as parameter, - //! and is initialized by a specific number of characters of the s string. - basic_string(const basic_string& s, size_type pos, size_type n = npos, - const allocator_type& a = allocator_type()) - : base_t(a) - { - this->priv_terminate_string(); - if (pos > s.size()) - throw_out_of_range("basic_string::basic_string out of range position"); - else - this->assign - (s.begin() + pos, s.begin() + pos + container_detail::min_value(n, s.size() - pos)); - } - - //! Effects: Constructs a basic_string taking the allocator as parameter, - //! and is initialized by a specific number of characters of the s c-string. - basic_string(const CharT* s, size_type n, const allocator_type& a = allocator_type()) - : base_t(a) - { - this->priv_terminate_string(); - this->assign(s, s + n); - } - - //! Effects: Constructs a basic_string taking the allocator as parameter, - //! and is initialized by the null-terminated s c-string. - basic_string(const CharT* s, const allocator_type& a = allocator_type()) - : base_t(a) - { - this->priv_terminate_string(); - this->assign(s, s + Traits::length(s)); - } - - //! Effects: Constructs a basic_string taking the allocator as parameter, - //! and is initialized by n copies of c. - basic_string(size_type n, CharT c, const allocator_type& a = allocator_type()) - : base_t(a) - { - this->priv_terminate_string(); - this->assign(n, c); - } - - //! Effects: Constructs a basic_string taking the allocator as parameter, - //! and a range of iterators. - template - basic_string(InputIterator f, InputIterator l, const allocator_type& a = allocator_type()) - : base_t(a) - { - this->priv_terminate_string(); - this->assign(f, l); - } - - //! Effects: Destroys the basic_string. All used memory is deallocated. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - ~basic_string() BOOST_CONTAINER_NOEXCEPT - {} - - //! Effects: Copy constructs a string. - //! - //! Postcondition: x == *this. - //! - //! Complexity: Linear to the elements x contains. - basic_string& operator=(BOOST_COPY_ASSIGN_REF(basic_string) x) - { - if (&x != this){ - allocator_type &this_alloc = this->alloc(); - const allocator_type &x_alloc = x.alloc(); - container_detail::bool_ flag; - if(flag && this_alloc != x_alloc){ - if(!this->is_short()){ - this->deallocate_block(); - this->is_short(true); - Traits::assign(*this->priv_addr(), CharT(0)); - this->priv_short_size(0); - } - } - container_detail::assign_alloc(this->alloc(), x.alloc(), flag); - this->assign(x.begin(), x.end()); - } - return *this; - } - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: If allocator_type's copy constructor throws. - //! - //! Complexity: Constant. - basic_string& operator=(BOOST_RV_REF(basic_string) x) BOOST_CONTAINER_NOEXCEPT - { - if (&x != this){ - allocator_type &this_alloc = this->alloc(); - allocator_type &x_alloc = x.alloc(); - //If allocators are equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy objects but retain memory in case x reuses it in the future - this->clear(); - this->swap_data(x); - //Move allocator if needed - container_detail::bool_ flag; - container_detail::move_alloc(this_alloc, x_alloc, flag); - } - //If unequal allocators, then do a one by one move - else{ - this->assign( x.begin(), x.end()); - } - } - return *this; - } - - //! Effects: Assignment from a null-terminated c-string. - basic_string& operator=(const CharT* s) - { return this->assign(s, s + Traits::length(s)); } - - //! Effects: Assignment from character. - basic_string& operator=(CharT c) - { return this->assign(static_cast(1), c); } - - //! Effects: Returns a copy of the internal allocator. - //! - //! Throws: If allocator's copy constructor throws. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return this->alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->alloc(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return this->priv_addr(); } - - //! Effects: Returns a const_iterator to the first element contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_addr(); } - - //! Effects: Returns an iterator to the end of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return this->priv_end_addr(); } - - //! Effects: Returns a const_iterator to the end of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_end_addr(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->priv_end_addr()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->priv_addr()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_addr(); } - - //! Effects: Returns a const_iterator to the end of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_end_addr(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->priv_end_addr()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->priv_addr()); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the vector contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return !this->priv_size(); } - - //! Effects: Returns the number of the elements contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_size(); } - - //! Effects: Returns the number of the elements contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type length() const BOOST_CONTAINER_NOEXCEPT - { return this->size(); } - - //! Effects: Returns the largest possible size of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return base_t::max_size(); } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are copy constructed from x. - //! - //! Throws: If memory allocation throws - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type n, CharT c) - { - if (n <= this->size()) - this->erase(this->begin() + n, this->end()); - else - this->append(n - this->size(), c); - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type n) - { resize(n, CharT()); } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return this->priv_capacity(); } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws - void reserve(size_type res_arg) - { - if (res_arg > this->max_size()){ - throw_length_error("basic_string::reserve max_size() exceeded"); - } - - if (this->capacity() < res_arg){ - size_type n = container_detail::max_value(res_arg, this->size()) + 1; - size_type new_cap = this->next_capacity(n); - pointer new_start = this->allocation_command - (allocate_new, n, new_cap, new_cap).first; - size_type new_length = 0; - - const pointer addr = this->priv_addr(); - new_length += priv_uninitialized_copy - (addr, addr + this->priv_size(), new_start); - this->priv_construct_null(new_start + new_length); - this->deallocate_block(); - this->is_short(false); - this->priv_long_addr(new_start); - this->priv_long_size(new_length); - this->priv_storage(new_cap); - } - } - - //! Effects: Tries to deallocate the excess of memory created - //! with previous allocations. The size of the string is unchanged - //! - //! Throws: Nothing - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { - //Check if shrinking is possible - if(this->priv_storage() > InternalBufferChars){ - //Check if we should pass from dynamically allocated buffer - //to the internal storage - if(this->priv_size() < InternalBufferChars){ - //Dynamically allocated buffer attributes - pointer long_addr = this->priv_long_addr(); - size_type long_storage = this->priv_long_storage(); - size_type long_size = this->priv_long_size(); - //Shrink from allocated buffer to the internal one, including trailing null - Traits::copy( container_detail::to_raw_pointer(this->priv_short_addr()) - , container_detail::to_raw_pointer(long_addr) - , long_size+1); - this->is_short(true); - this->alloc().deallocate(long_addr, long_storage); - } - else{ - //Shrinking in dynamic buffer - this->priv_shrink_to_fit_dynamic_buffer(alloc_version()); - } - } - } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference operator[](size_type n) BOOST_CONTAINER_NOEXCEPT - { return *(this->priv_addr() + n); } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference operator[](size_type n) const BOOST_CONTAINER_NOEXCEPT - { return *(this->priv_addr() + n); } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - reference at(size_type n) - { - if (n >= this->size()) - throw_out_of_range("basic_string::at invalid subscript"); - return *(this->priv_addr() + n); - } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - const_reference at(size_type n) const { - if (n >= this->size()) - throw_out_of_range("basic_string::at invalid subscript"); - return *(this->priv_addr() + n); - } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - //! Effects: Calls append(str.data, str.size()). - //! - //! Returns: *this - basic_string& operator+=(const basic_string& s) - { return this->append(s); } - - //! Effects: Calls append(s). - //! - //! Returns: *this - basic_string& operator+=(const CharT* s) - { return this->append(s); } - - //! Effects: Calls append(1, c). - //! - //! Returns: *this - basic_string& operator+=(CharT c) - { this->push_back(c); return *this; } - - //! Effects: Calls append(str.data(), str.size()). - //! - //! Returns: *this - basic_string& append(const basic_string& s) - { return this->append(s.begin(), s.end()); } - - //! Requires: pos <= str.size() - //! - //! Effects: Determines the effective length rlen of the string to append - //! as the smaller of n and str.size() - pos and calls append(str.data() + pos, rlen). - //! - //! Throws: If memory allocation throws and out_of_range if pos > str.size() - //! - //! Returns: *this - basic_string& append(const basic_string& s, size_type pos, size_type n) - { - if (pos > s.size()) - throw_out_of_range("basic_string::append out of range position"); - return this->append(s.begin() + pos, - s.begin() + pos + container_detail::min_value(n, s.size() - pos)); - } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Effects: The function replaces the string controlled by *this with - //! a string of length size() + n whose irst size() elements are a copy of the - //! original string controlled by *this and whose remaining - //! elements are a copy of the initial n elements of s. - //! - //! Throws: If memory allocation throws length_error if size() + n > max_size(). - //! - //! Returns: *this - basic_string& append(const CharT* s, size_type n) - { return this->append(s, s + n); } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Effects: Calls append(s, traits::length(s)). - //! - //! Returns: *this - basic_string& append(const CharT* s) - { return this->append(s, s + Traits::length(s)); } - - //! Effects: Equivalent to append(basic_string(n, c)). - //! - //! Returns: *this - basic_string& append(size_type n, CharT c) - { return this->append(cvalue_iterator(c, n), cvalue_iterator()); } - - //! Requires: [first,last) is a valid range. - //! - //! Effects: Equivalent to append(basic_string(first, last)). - //! - //! Returns: *this - template - basic_string& append(InputIter first, InputIter last) - { this->insert(this->end(), first, last); return *this; } - - //! Effects: Equivalent to append(static_cast(1), c). - void push_back(CharT c) - { - const size_type old_size = this->priv_size(); - if (old_size < this->capacity()){ - const pointer addr = this->priv_addr(); - this->priv_construct_null(addr + old_size + 1); - Traits::assign(addr[old_size], c); - this->priv_size(old_size+1); - } - else{ - //No enough memory, insert a new object at the end - this->append(size_type(1), c); - } - } - - //! Effects: Equivalent to assign(str, 0, npos). - //! - //! Returns: *this - basic_string& assign(const basic_string& s) - { return this->operator=(s); } - - //! Effects: The function replaces the string controlled by *this - //! with a string of length str.size() whose elements are a copy of the string - //! controlled by str. Leaves str in a valid but unspecified state. - //! - //! Throws: Nothing - //! - //! Returns: *this - basic_string& assign(BOOST_RV_REF(basic_string) ms) BOOST_CONTAINER_NOEXCEPT - { return this->swap_data(ms), *this; } - - //! Requires: pos <= str.size() - //! - //! Effects: Determines the effective length rlen of the string to assign as - //! the smaller of n and str.size() - pos and calls assign(str.data() + pos rlen). - //! - //! Throws: If memory allocation throws or out_of_range if pos > str.size(). - //! - //! Returns: *this - basic_string& assign(const basic_string& s, size_type pos, size_type n) - { - if (pos > s.size()) - throw_out_of_range("basic_string::assign out of range position"); - return this->assign(s.begin() + pos, - s.begin() + pos + container_detail::min_value(n, s.size() - pos)); - } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Effects: Replaces the string controlled by *this with a string of - //! length n whose elements are a copy of those pointed to by s. - //! - //! Throws: If memory allocation throws or length_error if n > max_size(). - //! - //! Returns: *this - basic_string& assign(const CharT* s, size_type n) - { return this->assign(s, s + n); } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Effects: Calls assign(s, traits::length(s)). - //! - //! Returns: *this - basic_string& assign(const CharT* s) - { return this->assign(s, s + Traits::length(s)); } - - //! Effects: Equivalent to assign(basic_string(n, c)). - //! - //! Returns: *this - basic_string& assign(size_type n, CharT c) - { return this->assign(cvalue_iterator(c, n), cvalue_iterator()); } - - //! Effects: Equivalent to assign(basic_string(first, last)). - //! - //! Returns: *this - template - basic_string& assign(InputIter first, InputIter last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - >::type * = 0 - #endif - ) - { - size_type cur = 0; - const pointer addr = this->priv_addr(); - CharT *ptr = container_detail::to_raw_pointer(addr); - const size_type old_size = this->priv_size(); - while (first != last && cur != old_size) { - Traits::assign(*ptr, *first); - ++first; - ++cur; - ++ptr; - } - if (first == last) - this->erase(addr + cur, addr + old_size); - else - this->append(first, last); - return *this; - } - - //! Requires: pos <= size(). - //! - //! Effects: Calls insert(pos, str.data(), str.size()). - //! - //! Throws: If memory allocation throws or out_of_range if pos > size(). - //! - //! Returns: *this - basic_string& insert(size_type pos, const basic_string& s) - { - const size_type sz = this->size(); - if (pos > sz) - throw_out_of_range("basic_string::insert out of range position"); - if (sz > this->max_size() - s.size()) - throw_length_error("basic_string::insert max_size() exceeded"); - this->insert(this->priv_addr() + pos, s.begin(), s.end()); - return *this; - } - - //! Requires: pos1 <= size() and pos2 <= str.size() - //! - //! Effects: Determines the effective length rlen of the string to insert as - //! the smaller of n and str.size() - pos2 and calls insert(pos1, str.data() + pos2, rlen). - //! - //! Throws: If memory allocation throws or out_of_range if pos1 > size() or pos2 > str.size(). - //! - //! Returns: *this - basic_string& insert(size_type pos1, const basic_string& s, size_type pos2, size_type n) - { - const size_type sz = this->size(); - const size_type str_size = s.size(); - if (pos1 > sz || pos2 > str_size) - throw_out_of_range("basic_string::insert out of range position"); - size_type len = container_detail::min_value(n, str_size - pos2); - if (sz > this->max_size() - len) - throw_length_error("basic_string::insert max_size() exceeded"); - const CharT *beg_ptr = container_detail::to_raw_pointer(s.begin()) + pos2; - const CharT *end_ptr = beg_ptr + len; - this->insert(this->priv_addr() + pos1, beg_ptr, end_ptr); - return *this; - } - - //! Requires: s points to an array of at least n elements of CharT and pos <= size(). - //! - //! Effects: Replaces the string controlled by *this with a string of length size() + n - //! whose first pos elements are a copy of the initial elements of the original string - //! controlled by *this and whose next n elements are a copy of the elements in s and whose - //! remaining elements are a copy of the remaining elements of the original string controlled by *this. - //! - //! Throws: If memory allocation throws, out_of_range if pos > size() or - //! length_error if size() + n > max_size(). - //! - //! Returns: *this - basic_string& insert(size_type pos, const CharT* s, size_type n) - { - if (pos > this->size()) - throw_out_of_range("basic_string::insert out of range position"); - if (this->size() > this->max_size() - n) - throw_length_error("basic_string::insert max_size() exceeded"); - this->insert(this->priv_addr() + pos, s, s + n); - return *this; - } - - //! Requires: pos <= size() and s points to an array of at least traits::length(s) + 1 elements of CharT - //! - //! Effects: Calls insert(pos, s, traits::length(s)). - //! - //! Throws: If memory allocation throws, out_of_range if pos > size() - //! length_error if size() > max_size() - Traits::length(s) - //! - //! Returns: *this - basic_string& insert(size_type pos, const CharT* s) - { - if (pos > this->size()) - throw_out_of_range("basic_string::insert out of range position"); - size_type len = Traits::length(s); - if (this->size() > this->max_size() - len) - throw_length_error("basic_string::insert max_size() exceeded"); - this->insert(this->priv_addr() + pos, s, s + len); - return *this; - } - - //! Effects: Equivalent to insert(pos, basic_string(n, c)). - //! - //! Throws: If memory allocation throws, out_of_range if pos > size() - //! length_error if size() > max_size() - n - //! - //! Returns: *this - basic_string& insert(size_type pos, size_type n, CharT c) - { - if (pos > this->size()) - throw_out_of_range("basic_string::insert out of range position"); - if (this->size() > this->max_size() - n) - throw_length_error("basic_string::insert max_size() exceeded"); - this->insert(const_iterator(this->priv_addr() + pos), n, c); - return *this; - } - - //! Requires: p is a valid iterator on *this. - //! - //! Effects: inserts a copy of c before the character referred to by p. - //! - //! Returns: An iterator which refers to the copy of the inserted character. - iterator insert(const_iterator p, CharT c) - { - size_type new_offset = p - this->priv_addr(); - this->insert(p, cvalue_iterator(c, 1), cvalue_iterator()); - return this->priv_addr() + new_offset; - } - - - //! Requires: p is a valid iterator on *this. - //! - //! Effects: Inserts n copies of c before the character referred to by p. - //! - //! Returns: an iterator to the first inserted element or p if n is 0. - iterator insert(const_iterator p, size_type n, CharT c) - { return this->insert(p, cvalue_iterator(c, n), cvalue_iterator()); } - - //! Requires: p is a valid iterator on *this. [first,last) is a valid range. - //! - //! Effects: Equivalent to insert(p - begin(), basic_string(first, last)). - //! - //! Returns: an iterator to the first inserted element or p if first == last. - template - iterator insert(const_iterator p, InputIter first, InputIter last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - const size_type n_pos = p - this->cbegin(); - for ( ; first != last; ++first, ++p) { - p = this->insert(p, *first); - } - return this->begin() + n_pos; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - iterator insert(const_iterator p, ForwardIter first, ForwardIter last - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !container_detail::is_input_iterator::value - >::type * = 0 - ) - { - const size_type n_pos = p - this->cbegin(); - if (first != last) { - const size_type n = std::distance(first, last); - const size_type old_size = this->priv_size(); - const size_type remaining = this->capacity() - old_size; - const pointer old_start = this->priv_addr(); - bool enough_capacity = false; - std::pair allocation_ret; - size_type new_cap = 0; - - //Check if we have enough capacity - if (remaining >= n){ - enough_capacity = true; - } - else { - //Otherwise expand current buffer or allocate new storage - new_cap = this->next_capacity(n); - allocation_ret = this->allocation_command - (allocate_new | expand_fwd | expand_bwd, old_size + n + 1, - new_cap, new_cap, old_start); - - //Check forward expansion - if(old_start == allocation_ret.first){ - enough_capacity = true; - this->priv_storage(new_cap); - } - } - - //Reuse same buffer - if(enough_capacity){ - const size_type elems_after = old_size - (p - old_start); - const size_type old_length = old_size; - if (elems_after >= n) { - const pointer pointer_past_last = old_start + old_size + 1; - priv_uninitialized_copy(old_start + (old_size - n + 1), - pointer_past_last, pointer_past_last); - - this->priv_size(old_size+n); - Traits::move(const_cast(container_detail::to_raw_pointer(p + n)), - container_detail::to_raw_pointer(p), - (elems_after - n) + 1); - this->priv_copy(first, last, const_cast(container_detail::to_raw_pointer(p))); - } - else { - ForwardIter mid = first; - std::advance(mid, elems_after + 1); - - priv_uninitialized_copy(mid, last, old_start + old_size + 1); - const size_type newer_size = old_size + (n - elems_after); - this->priv_size(newer_size); - priv_uninitialized_copy - (p, const_iterator(old_start + old_length + 1), - old_start + newer_size); - this->priv_size(newer_size + elems_after); - this->priv_copy(first, mid, const_cast(container_detail::to_raw_pointer(p))); - } - } - else{ - pointer new_start = allocation_ret.first; - if(!allocation_ret.second){ - //Copy data to new buffer - size_type new_length = 0; - //This can't throw, since characters are POD - new_length += priv_uninitialized_copy - (const_iterator(old_start), p, new_start); - new_length += priv_uninitialized_copy - (first, last, new_start + new_length); - new_length += priv_uninitialized_copy - (p, const_iterator(old_start + old_size), - new_start + new_length); - this->priv_construct_null(new_start + new_length); - - this->deallocate_block(); - this->is_short(false); - this->priv_long_addr(new_start); - this->priv_long_size(new_length); - this->priv_long_storage(new_cap); - } - else{ - //value_type is POD, so backwards expansion is much easier - //than with vector - value_type * const oldbuf = container_detail::to_raw_pointer(old_start); - value_type * const newbuf = container_detail::to_raw_pointer(new_start); - const value_type *const pos = container_detail::to_raw_pointer(p); - const size_type before = pos - oldbuf; - - //First move old data - Traits::move(newbuf, oldbuf, before); - Traits::move(newbuf + before + n, pos, old_size - before); - //Now initialize the new data - priv_uninitialized_copy(first, last, new_start + before); - this->priv_construct_null(new_start + (old_size + n)); - this->is_short(false); - this->priv_long_addr(new_start); - this->priv_long_size(old_size + n); - this->priv_long_storage(new_cap); - } - } - } - return this->begin() + n_pos; - } - #endif - - //! Requires: pos <= size() - //! - //! Effects: Determines the effective length xlen of the string to be removed as the smaller of n and size() - pos. - //! The function then replaces the string controlled by *this with a string of length size() - xlen - //! whose first pos elements are a copy of the initial elements of the original string controlled by *this, - //! and whose remaining elements are a copy of the elements of the original string controlled by *this - //! beginning at position pos + xlen. - //! - //! Throws: out_of_range if pos > size(). - //! - //! Returns: *this - basic_string& erase(size_type pos = 0, size_type n = npos) - { - if (pos > this->size()) - throw_out_of_range("basic_string::erase out of range position"); - const pointer addr = this->priv_addr(); - erase(addr + pos, addr + pos + container_detail::min_value(n, this->size() - pos)); - return *this; - } - - //! Effects: Removes the character referred to by p. - //! - //! Throws: Nothing - //! - //! Returns: An iterator which points to the element immediately following p prior to the element being - //! erased. If no such element exists, end() is returned. - iterator erase(const_iterator p) BOOST_CONTAINER_NOEXCEPT - { - // The move includes the terminating null. - CharT * const ptr = const_cast(container_detail::to_raw_pointer(p)); - const size_type old_size = this->priv_size(); - Traits::move(ptr, - container_detail::to_raw_pointer(p + 1), - old_size - (p - this->priv_addr())); - this->priv_size(old_size-1); - return iterator(ptr); - } - - //! Requires: first and last are valid iterators on *this, defining a range [first,last). - //! - //! Effects: Removes the characters in the range [first,last). - //! - //! Throws: Nothing - //! - //! Returns: An iterator which points to the element pointed to by last prior to - //! the other elements being erased. If no such element exists, end() is returned. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { - CharT * f = const_cast(container_detail::to_raw_pointer(first)); - if (first != last) { // The move includes the terminating null. - const size_type num_erased = last - first; - const size_type old_size = this->priv_size(); - Traits::move(f, - container_detail::to_raw_pointer(last), - (old_size + 1)-(last - this->priv_addr())); - const size_type new_length = old_size - num_erased; - this->priv_size(new_length); - } - return iterator(f); - } - - //! Requires: !empty() - //! - //! Throws: Nothing - //! - //! Effects: Equivalent to erase(size() - 1, 1). - void pop_back() BOOST_CONTAINER_NOEXCEPT - { - const size_type old_size = this->priv_size(); - Traits::assign(this->priv_addr()[old_size-1], CharT(0)); - this->priv_size(old_size-1);; - } - - //! Effects: Erases all the elements of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements in the vector. - void clear() BOOST_CONTAINER_NOEXCEPT - { - if (!this->empty()) { - Traits::assign(*this->priv_addr(), CharT(0)); - this->priv_size(0); - } - } - - //! Requires: pos1 <= size(). - //! - //! Effects: Calls replace(pos1, n1, str.data(), str.size()). - //! - //! Throws: if memory allocation throws or out_of_range if pos1 > size(). - //! - //! Returns: *this - basic_string& replace(size_type pos1, size_type n1, const basic_string& str) - { - if (pos1 > this->size()) - throw_out_of_range("basic_string::replace out of range position"); - const size_type len = container_detail::min_value(n1, this->size() - pos1); - if (this->size() - len >= this->max_size() - str.size()) - throw_length_error("basic_string::replace max_size() exceeded"); - const pointer addr = this->priv_addr(); - return this->replace( const_iterator(addr + pos1) - , const_iterator(addr + pos1 + len) - , str.begin(), str.end()); - } - - //! Requires: pos1 <= size() and pos2 <= str.size(). - //! - //! Effects: Determines the effective length rlen of the string to be - //! inserted as the smaller of n2 and str.size() - pos2 and calls - //! replace(pos1, n1, str.data() + pos2, rlen). - //! - //! Throws: if memory allocation throws, out_of_range if pos1 > size() or pos2 > str.size(). - //! - //! Returns: *this - basic_string& replace(size_type pos1, size_type n1, - const basic_string& str, size_type pos2, size_type n2) - { - if (pos1 > this->size() || pos2 > str.size()) - throw_out_of_range("basic_string::replace out of range position"); - const size_type len1 = container_detail::min_value(n1, this->size() - pos1); - const size_type len2 = container_detail::min_value(n2, str.size() - pos2); - if (this->size() - len1 >= this->max_size() - len2) - throw_length_error("basic_string::replace max_size() exceeded"); - const pointer addr = this->priv_addr(); - const pointer straddr = str.priv_addr(); - return this->replace(addr + pos1, addr + pos1 + len1, - straddr + pos2, straddr + pos2 + len2); - } - - //! Requires: pos1 <= size() and s points to an array of at least n2 elements of CharT. - //! - //! Effects: Determines the effective length xlen of the string to be removed as the - //! smaller of n1 and size() - pos1. If size() - xlen >= max_size() - n2 throws length_error. - //! Otherwise, the function replaces the string controlled by *this with a string of - //! length size() - xlen + n2 whose first pos1 elements are a copy of the initial elements - //! of the original string controlled by *this, whose next n2 elements are a copy of the - //! initial n2 elements of s, and whose remaining elements are a copy of the elements of - //! the original string controlled by *this beginning at position pos + xlen. - //! - //! Throws: if memory allocation throws, out_of_range if pos1 > size() or length_error - //! if the length of the resulting string would exceed max_size() - //! - //! Returns: *this - basic_string& replace(size_type pos1, size_type n1, const CharT* s, size_type n2) - { - if (pos1 > this->size()) - throw_out_of_range("basic_string::replace out of range position"); - const size_type len = container_detail::min_value(n1, this->size() - pos1); - if (n2 > this->max_size() || size() - len >= this->max_size() - n2) - throw_length_error("basic_string::replace max_size() exceeded"); - const pointer addr = this->priv_addr(); - return this->replace(addr + pos1, addr + pos1 + len, s, s + n2); - } - - //! Requires: pos1 <= size() and s points to an array of at least n2 elements of CharT. - //! - //! Effects: Determines the effective length xlen of the string to be removed as the smaller - //! of n1 and size() - pos1. If size() - xlen >= max_size() - n2 throws length_error. Otherwise, - //! the function replaces the string controlled by *this with a string of length size() - xlen + n2 - //! whose first pos1 elements are a copy of the initial elements of the original string controlled - //! by *this, whose next n2 elements are a copy of the initial n2 elements of s, and whose - //! remaining elements are a copy of the elements of the original string controlled by *this - //! beginning at position pos + xlen. - //! - //! Throws: if memory allocation throws, out_of_range if pos1 > size() or length_error - //! if the length of the resulting string would exceed max_size() - //! - //! Returns: *this - basic_string& replace(size_type pos, size_type n1, const CharT* s) - { - if (pos > this->size()) - throw_out_of_range("basic_string::replace out of range position"); - const size_type len = container_detail::min_value(n1, this->size() - pos); - const size_type n2 = Traits::length(s); - if (n2 > this->max_size() || this->size() - len >= this->max_size() - n2) - throw_length_error("basic_string::replace max_size() exceeded"); - const pointer addr = this->priv_addr(); - return this->replace(addr + pos, addr + pos + len, - s, s + Traits::length(s)); - } - - //! Requires: pos1 <= size(). - //! - //! Effects: Equivalent to replace(pos1, n1, basic_string(n2, c)). - //! - //! Throws: if memory allocation throws, out_of_range if pos1 > size() or length_error - //! if the length of the resulting string would exceed max_size() - //! - //! Returns: *this - basic_string& replace(size_type pos1, size_type n1, size_type n2, CharT c) - { - if (pos1 > this->size()) - throw_out_of_range("basic_string::replace out of range position"); - const size_type len = container_detail::min_value(n1, this->size() - pos1); - if (n2 > this->max_size() || this->size() - len >= this->max_size() - n2) - throw_length_error("basic_string::replace max_size() exceeded"); - const pointer addr = this->priv_addr(); - return this->replace(addr + pos1, addr + pos1 + len, n2, c); - } - - //! Requires: [begin(),i1) and [i1,i2) are valid ranges. - //! - //! Effects: Calls replace(i1 - begin(), i2 - i1, str). - //! - //! Throws: if memory allocation throws - //! - //! Returns: *this - basic_string& replace(const_iterator i1, const_iterator i2, const basic_string& str) - { return this->replace(i1, i2, str.begin(), str.end()); } - - //! Requires: [begin(),i1) and [i1,i2) are valid ranges and - //! s points to an array of at least n elements - //! - //! Effects: Calls replace(i1 - begin(), i2 - i1, s, n). - //! - //! Throws: if memory allocation throws - //! - //! Returns: *this - basic_string& replace(const_iterator i1, const_iterator i2, const CharT* s, size_type n) - { return this->replace(i1, i2, s, s + n); } - - //! Requires: [begin(),i1) and [i1,i2) are valid ranges and s points to an - //! array of at least traits::length(s) + 1 elements of CharT. - //! - //! Effects: Calls replace(i1 - begin(), i2 - i1, s, traits::length(s)). - //! - //! Throws: if memory allocation throws - //! - //! Returns: *this - basic_string& replace(const_iterator i1, const_iterator i2, const CharT* s) - { return this->replace(i1, i2, s, s + Traits::length(s)); } - - //! Requires: [begin(),i1) and [i1,i2) are valid ranges. - //! - //! Effects: Calls replace(i1 - begin(), i2 - i1, basic_string(n, c)). - //! - //! Throws: if memory allocation throws - //! - //! Returns: *this - basic_string& replace(const_iterator i1, const_iterator i2, size_type n, CharT c) - { - const size_type len = static_cast(i2 - i1); - if (len >= n) { - Traits::assign(const_cast(container_detail::to_raw_pointer(i1)), n, c); - erase(i1 + n, i2); - } - else { - Traits::assign(const_cast(container_detail::to_raw_pointer(i1)), len, c); - insert(i2, n - len, c); - } - return *this; - } - - //! Requires: [begin(),i1), [i1,i2) and [j1,j2) are valid ranges. - //! - //! Effects: Calls replace(i1 - begin(), i2 - i1, basic_string(j1, j2)). - //! - //! Throws: if memory allocation throws - //! - //! Returns: *this - template - basic_string& replace(const_iterator i1, const_iterator i2, InputIter j1, InputIter j2 - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - for ( ; i1 != i2 && j1 != j2; ++i1, ++j1){ - Traits::assign(*const_cast(container_detail::to_raw_pointer(i1)), *j1); - } - - if (j1 == j2) - this->erase(i1, i2); - else - this->insert(i2, j1, j2); - return *this; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - basic_string& replace(const_iterator i1, const_iterator i2, ForwardIter j1, ForwardIter j2 - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !container_detail::is_input_iterator::value - >::type * = 0 - ) - { - difference_type n = std::distance(j1, j2); - const difference_type len = i2 - i1; - if (len >= n) { - this->priv_copy(j1, j2, const_cast(container_detail::to_raw_pointer(i1))); - this->erase(i1 + n, i2); - } - else { - ForwardIter m = j1; - std::advance(m, len); - this->priv_copy(j1, m, const_cast(container_detail::to_raw_pointer(i1))); - this->insert(i2, m, j2); - } - return *this; - } - #endif - - //! Requires: pos <= size() - //! - //! Effects: Determines the effective length rlen of the string to copy as the - //! smaller of n and size() - pos. s shall designate an array of at least rlen elements. - //! The function then replaces the string designated by s with a string of length rlen - //! whose elements are a copy of the string controlled by *this beginning at position pos. - //! The function does not append a null object to the string designated by s. - //! - //! Throws: if memory allocation throws, out_of_range if pos > size(). - //! - //! Returns: rlen - size_type copy(CharT* s, size_type n, size_type pos = 0) const - { - if (pos > this->size()) - throw_out_of_range("basic_string::copy out of range position"); - const size_type len = container_detail::min_value(n, this->size() - pos); - Traits::copy(s, container_detail::to_raw_pointer(this->priv_addr() + pos), len); - return len; - } - - //! Effects: *this contains the same sequence of characters that was in s, - //! s contains the same sequence of characters that was in *this. - //! - //! Throws: Nothing - void swap(basic_string& x) - { - this->base_t::swap_data(x); - container_detail::bool_ flag; - container_detail::swap_alloc(this->alloc(), x.alloc(), flag); - } - - ////////////////////////////////////////////// - // - // data access - // - ////////////////////////////////////////////// - - //! Requires: The program shall not alter any of the values stored in the character array. - //! - //! Returns: Allocator pointer p such that p + i == &operator[](i) for each i in [0,size()]. - //! - //! Complexity: constant time. - const CharT* c_str() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::to_raw_pointer(this->priv_addr()); } - - //! Requires: The program shall not alter any of the values stored in the character array. - //! - //! Returns: Allocator pointer p such that p + i == &operator[](i) for each i in [0,size()]. - //! - //! Complexity: constant time. - const CharT* data() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::to_raw_pointer(this->priv_addr()); } - - ////////////////////////////////////////////// - // - // string operations - // - ////////////////////////////////////////////// - - //! Effects: Determines the lowest position xpos, if possible, such that both - //! of the following conditions obtain: 19 pos <= xpos and xpos + str.size() <= size(); - //! 2) traits::eq(at(xpos+I), str.at(I)) for all elements I of the string controlled by str. - //! - //! Throws: Nothing - //! - //! Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos. - size_type find(const basic_string& s, size_type pos = 0) const - { return find(s.c_str(), pos, s.size()); } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find(basic_string(s,n),pos). - size_type find(const CharT* s, size_type pos, size_type n) const - { - if (pos + n > this->size()) - return npos; - else { - const pointer addr = this->priv_addr(); - pointer finish = addr + this->priv_size(); - const const_iterator result = - std::search(container_detail::to_raw_pointer(addr + pos), - container_detail::to_raw_pointer(finish), - s, s + n, Eq_traits()); - return result != finish ? result - begin() : npos; - } - } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find(basic_string(s), pos). - size_type find(const CharT* s, size_type pos = 0) const - { return this->find(s, pos, Traits::length(s)); } - - //! Throws: Nothing - //! - //! Returns: find(basic_string(1,c), pos). - size_type find(CharT c, size_type pos = 0) const - { - const size_type sz = this->size(); - if (pos >= sz) - return npos; - else { - const pointer addr = this->priv_addr(); - pointer finish = addr + sz; - const const_iterator result = - std::find_if(addr + pos, finish, - std::bind2nd(Eq_traits(), c)); - return result != finish ? result - begin() : npos; - } - } - - //! Effects: Determines the highest position xpos, if possible, such - //! that both of the following conditions obtain: - //! a) xpos <= pos and xpos + str.size() <= size(); - //! b) traits::eq(at(xpos+I), str.at(I)) for all elements I of the string controlled by str. - //! - //! Throws: Nothing - //! - //! Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos. - size_type rfind(const basic_string& str, size_type pos = npos) const - { return rfind(str.c_str(), pos, str.size()); } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: rfind(basic_string(s, n), pos). - size_type rfind(const CharT* s, size_type pos, size_type n) const - { - const size_type len = this->size(); - - if (n > len) - return npos; - else if (n == 0) - return container_detail::min_value(len, pos); - else { - const const_iterator last = begin() + container_detail::min_value(len - n, pos) + n; - const const_iterator result = find_end(begin(), last, - s, s + n, - Eq_traits()); - return result != last ? result - begin() : npos; - } - } - - //! Requires: pos <= size() and s points to an array of at least - //! traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: rfind(basic_string(s), pos). - size_type rfind(const CharT* s, size_type pos = npos) const - { return rfind(s, pos, Traits::length(s)); } - - //! Throws: Nothing - //! - //! Returns: rfind(basic_string(1,c),pos). - size_type rfind(CharT c, size_type pos = npos) const - { - const size_type len = this->size(); - - if (len < 1) - return npos; - else { - const const_iterator last = begin() + container_detail::min_value(len - 1, pos) + 1; - const_reverse_iterator rresult = - std::find_if(const_reverse_iterator(last), rend(), - std::bind2nd(Eq_traits(), c)); - return rresult != rend() ? (rresult.base() - 1) - begin() : npos; - } - } - - //! Effects: Determines the lowest position xpos, if possible, such that both of the - //! following conditions obtain: a) pos <= xpos and xpos < size(); - //! b) traits::eq(at(xpos), str.at(I)) for some element I of the string controlled by str. - //! - //! Throws: Nothing - //! - //! Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos. - size_type find_first_of(const basic_string& s, size_type pos = 0) const - { return find_first_of(s.c_str(), pos, s.size()); } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_first_of(basic_string(s, n), pos). - size_type find_first_of(const CharT* s, size_type pos, size_type n) const - { - const size_type sz = this->size(); - if (pos >= sz) - return npos; - else { - const pointer addr = this->priv_addr(); - pointer finish = addr + sz; - const_iterator result = std::find_first_of - (addr + pos, finish, s, s + n, Eq_traits()); - return result != finish ? result - this->begin() : npos; - } - } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_first_of(basic_string(s), pos). - size_type find_first_of(const CharT* s, size_type pos = 0) const - { return find_first_of(s, pos, Traits::length(s)); } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_first_of(basic_string(1,c), pos). - size_type find_first_of(CharT c, size_type pos = 0) const - { return find(c, pos); } - - //! Effects: Determines the highest position xpos, if possible, such that both of - //! the following conditions obtain: a) xpos <= pos and xpos < size(); b) - //! traits::eq(at(xpos), str.at(I)) for some element I of the string controlled by str. - //! - //! Throws: Nothing - //! - //! Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos. - size_type find_last_of(const basic_string& str, size_type pos = npos) const - { return find_last_of(str.c_str(), pos, str.size()); } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_last_of(basic_string(s, n), pos). - size_type find_last_of(const CharT* s, size_type pos, size_type n) const - { - const size_type len = this->size(); - - if (len < 1) - return npos; - else { - const pointer addr = this->priv_addr(); - const const_iterator last = addr + container_detail::min_value(len - 1, pos) + 1; - const const_reverse_iterator rresult = - std::find_first_of(const_reverse_iterator(last), rend(), - s, s + n, Eq_traits()); - return rresult != rend() ? (rresult.base() - 1) - addr : npos; - } - } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_last_of(basic_string(1,c),pos). - size_type find_last_of(const CharT* s, size_type pos = npos) const - { return find_last_of(s, pos, Traits::length(s)); } - - //! Throws: Nothing - //! - //! Returns: find_last_of(basic_string(s), pos). - size_type find_last_of(CharT c, size_type pos = npos) const - { return rfind(c, pos); } - - //! Effects: Determines the lowest position xpos, if possible, such that - //! both of the following conditions obtain: - //! a) pos <= xpos and xpos < size(); b) traits::eq(at(xpos), str.at(I)) for no - //! element I of the string controlled by str. - //! - //! Throws: Nothing - //! - //! Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos. - size_type find_first_not_of(const basic_string& str, size_type pos = 0) const - { return find_first_not_of(str.c_str(), pos, str.size()); } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_first_not_of(basic_string(s, n), pos). - size_type find_first_not_of(const CharT* s, size_type pos, size_type n) const - { - if (pos > this->size()) - return npos; - else { - const pointer addr = this->priv_addr(); - const pointer finish = addr + this->priv_size(); - const const_iterator result = std::find_if - (addr + pos, finish, Not_within_traits(s, s + n)); - return result != finish ? result - addr : npos; - } - } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_first_not_of(basic_string(s), pos). - size_type find_first_not_of(const CharT* s, size_type pos = 0) const - { return find_first_not_of(s, pos, Traits::length(s)); } - - //! Throws: Nothing - //! - //! Returns: find_first_not_of(basic_string(1, c), pos). - size_type find_first_not_of(CharT c, size_type pos = 0) const - { - if (pos > this->size()) - return npos; - else { - const pointer addr = this->priv_addr(); - const pointer finish = addr + this->priv_size(); - const const_iterator result - = std::find_if(addr + pos, finish, - std::not1(std::bind2nd(Eq_traits(), c))); - return result != finish ? result - begin() : npos; - } - } - - //! Effects: Determines the highest position xpos, if possible, such that - //! both of the following conditions obtain: a) xpos <= pos and xpos < size(); - //! b) traits::eq(at(xpos), str.at(I)) for no element I of the string controlled by str. - //! - //! Throws: Nothing - //! - //! Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos. - size_type find_last_not_of(const basic_string& str, size_type pos = npos) const - { return find_last_not_of(str.c_str(), pos, str.size()); } - - //! Requires: s points to an array of at least n elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_last_not_of(basic_string(s, n), pos). - size_type find_last_not_of(const CharT* s, size_type pos, size_type n) const - { - const size_type len = this->size(); - - if (len < 1) - return npos; - else { - const const_iterator last = begin() + container_detail::min_value(len - 1, pos) + 1; - const const_reverse_iterator rresult = - std::find_if(const_reverse_iterator(last), rend(), - Not_within_traits(s, s + n)); - return rresult != rend() ? (rresult.base() - 1) - begin() : npos; - } - } - - //! Requires: s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: Nothing - //! - //! Returns: find_last_not_of(basic_string(s), pos). - size_type find_last_not_of(const CharT* s, size_type pos = npos) const - { return find_last_not_of(s, pos, Traits::length(s)); } - - //! Throws: Nothing - //! - //! Returns: find_last_not_of(basic_string(1, c), pos). - size_type find_last_not_of(CharT c, size_type pos = npos) const - { - const size_type len = this->size(); - - if (len < 1) - return npos; - else { - const const_iterator last = begin() + container_detail::min_value(len - 1, pos) + 1; - const const_reverse_iterator rresult = - std::find_if(const_reverse_iterator(last), rend(), - std::not1(std::bind2nd(Eq_traits(), c))); - return rresult != rend() ? (rresult.base() - 1) - begin() : npos; - } - } - - //! Requires: Requires: pos <= size() - //! - //! Effects: Determines the effective length rlen of the string to copy as - //! the smaller of n and size() - pos. - //! - //! Throws: If memory allocation throws or out_of_range if pos > size(). - //! - //! Returns: basic_string(data()+pos,rlen). - basic_string substr(size_type pos = 0, size_type n = npos) const - { - if (pos > this->size()) - throw_out_of_range("basic_string::substr out of range position"); - const pointer addr = this->priv_addr(); - return basic_string(addr + pos, - addr + pos + container_detail::min_value(n, size() - pos), this->alloc()); - } - - //! Effects: Determines the effective length rlen of the string to copy as - //! the smaller of size() and str.size(). The function then compares the two strings by - //! calling traits::compare(data(), str.data(), rlen). - //! - //! Throws: Nothing - //! - //! Returns: The nonzero result if the result of the comparison is nonzero. - //! Otherwise, returns a value < 0 if size() < str.size(), a 0 value if size() == str.size(), - //! and value > 0 if size() > str.size() - int compare(const basic_string& str) const - { - const pointer addr = this->priv_addr(); - const pointer str_addr = str.priv_addr(); - return s_compare(addr, addr + this->priv_size(), str_addr, str_addr + str.priv_size()); - } - - //! Requires: pos1 <= size() - //! - //! Effects: Determines the effective length rlen of the string to copy as - //! the smaller of - //! - //! Throws: out_of_range if pos1 > size() - //! - //! Returns:basic_string(*this,pos1,n1).compare(str). - int compare(size_type pos1, size_type n1, const basic_string& str) const - { - if (pos1 > this->size()) - throw_out_of_range("basic_string::compare out of range position"); - const pointer addr = this->priv_addr(); - const pointer str_addr = str.priv_addr(); - return s_compare(addr + pos1, - addr + pos1 + container_detail::min_value(n1, this->size() - pos1), - str_addr, str_addr + str.priv_size()); - } - - //! Requires: pos1 <= size() and pos2 <= str.size() - //! - //! Effects: Determines the effective length rlen of the string to copy as - //! the smaller of - //! - //! Throws: out_of_range if pos1 > size() or pos2 > str.size() - //! - //! Returns: basic_string(*this, pos1, n1).compare(basic_string(str, pos2, n2)). - int compare(size_type pos1, size_type n1, const basic_string& str, size_type pos2, size_type n2) const - { - if (pos1 > this->size() || pos2 > str.size()) - throw_out_of_range("basic_string::compare out of range position"); - const pointer addr = this->priv_addr(); - const pointer str_addr = str.priv_addr(); - return s_compare(addr + pos1, - addr + pos1 + container_detail::min_value(n1, this->size() - pos1), - str_addr + pos2, - str_addr + pos2 + container_detail::min_value(n2, str.size() - pos2)); - } - - //! Throws: Nothing - //! - //! Returns: compare(basic_string(s)). - int compare(const CharT* s) const - { - const pointer addr = this->priv_addr(); - return s_compare(addr, addr + this->priv_size(), s, s + Traits::length(s)); - } - - - //! Requires: pos1 > size() and s points to an array of at least n2 elements of CharT. - //! - //! Throws: out_of_range if pos1 > size() - //! - //! Returns: basic_string(*this, pos, n1).compare(basic_string(s, n2)). - int compare(size_type pos1, size_type n1, const CharT* s, size_type n2) const - { - if (pos1 > this->size()) - throw_out_of_range("basic_string::compare out of range position"); - const pointer addr = this->priv_addr(); - return s_compare( addr + pos1, - addr + pos1 + container_detail::min_value(n1, this->size() - pos1), - s, s + n2); - } - - //! Requires: pos1 > size() and s points to an array of at least traits::length(s) + 1 elements of CharT. - //! - //! Throws: out_of_range if pos1 > size() - //! - //! Returns: basic_string(*this, pos, n1).compare(basic_string(s, n2)). - int compare(size_type pos1, size_type n1, const CharT* s) const - { return this->compare(pos1, n1, s, Traits::length(s)); } - - /// @cond - private: - static int s_compare(const_pointer f1, const_pointer l1, - const_pointer f2, const_pointer l2) - { - const difference_type n1 = l1 - f1; - const difference_type n2 = l2 - f2; - const int cmp = Traits::compare(container_detail::to_raw_pointer(f1), - container_detail::to_raw_pointer(f2), - container_detail::min_value(n1, n2)); - return cmp != 0 ? cmp : (n1 < n2 ? -1 : (n1 > n2 ? 1 : 0)); - } - - template - void priv_shrink_to_fit_dynamic_buffer - ( AllocVersion - , typename container_detail::enable_if >::type* = 0) - { - //Allocate a new buffer. - size_type real_cap = 0; - const pointer long_addr = this->priv_long_addr(); - const size_type long_size = this->priv_long_size(); - const size_type long_storage = this->priv_long_storage(); - //We can make this nothrow as chars are always NoThrowCopyables - BOOST_TRY{ - const std::pair ret = this->allocation_command - (allocate_new, long_size+1, long_size+1, real_cap, long_addr); - //Copy and update - Traits::copy( container_detail::to_raw_pointer(ret.first) - , container_detail::to_raw_pointer(this->priv_long_addr()) - , long_size+1); - this->priv_long_addr(ret.first); - this->priv_storage(real_cap); - //And release old buffer - this->alloc().deallocate(long_addr, long_storage); - } - BOOST_CATCH(...){ - return; - } - BOOST_CATCH_END - } - - template - void priv_shrink_to_fit_dynamic_buffer - ( AllocVersion - , typename container_detail::enable_if >::type* = 0) - { - size_type received_size; - if(this->alloc().allocation_command - ( shrink_in_place | nothrow_allocation - , this->priv_long_storage(), this->priv_long_size()+1 - , received_size, this->priv_long_addr()).first){ - this->priv_storage(received_size); - } - } - - void priv_construct_null(pointer p) - { this->construct(p, CharT(0)); } - - // Helper functions used by constructors. It is a severe error for - // any of them to be called anywhere except from within constructors. - void priv_terminate_string() - { this->priv_construct_null(this->priv_end_addr()); } - - template inline - void priv_uninitialized_fill_n(FwdIt first, Count count, const CharT val) - { - //Save initial position - FwdIt init = first; - - BOOST_TRY{ - //Construct objects - for (; count--; ++first){ - this->construct(first, val); - } - } - BOOST_CATCH(...){ - //Call destructors - for (; init != first; ++init){ - this->destroy(init); - } - BOOST_RETHROW - } - BOOST_CATCH_END - } - - template inline - size_type priv_uninitialized_copy(InpIt first, InpIt last, FwdIt dest) - { - //Save initial destination position - FwdIt dest_init = dest; - size_type constructed = 0; - - BOOST_TRY{ - //Try to build objects - for (; first != last; ++dest, ++first, ++constructed){ - this->construct(dest, *first); - } - } - BOOST_CATCH(...){ - //Call destructors - for (; constructed--; ++dest_init){ - this->destroy(dest_init); - } - BOOST_RETHROW - } - BOOST_CATCH_END - return (constructed); - } - - template - void priv_copy(InputIterator first, InputIterator last, OutIterator result) - { - for ( ; first != last; ++first, ++result) - Traits::assign(*result, *first); - } - - void priv_copy(const CharT* first, const CharT* last, CharT* result) - { Traits::copy(result, first, last - first); } - - template - basic_string& priv_replace_dispatch(const_iterator first, const_iterator last, - Integer n, Integer x, - container_detail::true_) - { return this->replace(first, last, (size_type) n, (CharT) x); } - - template - basic_string& priv_replace_dispatch(const_iterator first, const_iterator last, - InputIter f, InputIter l, - container_detail::false_) - { - typedef typename std::iterator_traits::iterator_category Category; - return this->priv_replace(first, last, f, l, Category()); - } - - /// @endcond -}; - -//!Typedef for a basic_string of -//!narrow characters -typedef basic_string - - ,std::allocator > -string; - -//!Typedef for a basic_string of -//!narrow characters -typedef basic_string - - ,std::allocator > -wstring; - -// ------------------------------------------------------------ -// Non-member functions. - -// Operator+ - -template inline - basic_string - operator+(const basic_string& x - ,const basic_string& y) -{ - typedef basic_string str_t; - typedef typename str_t::reserve_t reserve_t; - reserve_t reserve; - str_t result(reserve, x.size() + y.size(), x.get_stored_allocator()); - result.append(x); - result.append(y); - return result; -} - -template inline - basic_string operator+ - ( BOOST_RV_REF_BEG basic_string BOOST_RV_REF_END mx - , BOOST_RV_REF_BEG basic_string BOOST_RV_REF_END my) -{ - mx += my; - return boost::move(mx); -} - -template inline - basic_string operator+ - ( BOOST_RV_REF_BEG basic_string BOOST_RV_REF_END mx - , const basic_string& y) -{ - mx += y; - return boost::move(mx); -} - -template inline - basic_string operator+ - (const basic_string& x - ,BOOST_RV_REF_BEG basic_string BOOST_RV_REF_END my) -{ - my.insert(my.begin(), x.begin(), x.end()); - return boost::move(my); -} - -template inline - basic_string operator+ - (const CharT* s, basic_string y) -{ - y.insert(y.begin(), s, s + Traits::length(s)); - return y; -} - -template inline - basic_string operator+ - (basic_string x, const CharT* s) -{ - x += s; - return x; -} - -template inline - basic_string operator+ - (CharT c, basic_string y) -{ - y.insert(y.begin(), c); - return y; -} - -template inline - basic_string operator+ - (basic_string x, const CharT c) -{ - x += c; - return x; -} - -// Operator== and operator!= - -template -inline bool -operator==(const basic_string& x, - const basic_string& y) -{ - return x.size() == y.size() && - Traits::compare(x.data(), y.data(), x.size()) == 0; -} - -template -inline bool -operator==(const CharT* s, const basic_string& y) -{ - typename basic_string::size_type n = Traits::length(s); - return n == y.size() && Traits::compare(s, y.data(), n) == 0; -} - -template -inline bool -operator==(const basic_string& x, const CharT* s) -{ - typename basic_string::size_type n = Traits::length(s); - return x.size() == n && Traits::compare(x.data(), s, n) == 0; -} - -template -inline bool -operator!=(const basic_string& x, - const basic_string& y) - { return !(x == y); } - -template -inline bool -operator!=(const CharT* s, const basic_string& y) - { return !(s == y); } - -template -inline bool -operator!=(const basic_string& x, const CharT* s) - { return !(x == s); } - - -// Operator< (and also >, <=, and >=). - -template -inline bool -operator<(const basic_string& x, const basic_string& y) -{ - return x.compare(y) < 0; -// return basic_string -// ::s_compare(x.begin(), x.end(), y.begin(), y.end()) < 0; -} - -template -inline bool -operator<(const CharT* s, const basic_string& y) -{ - return y.compare(s) > 0; -// basic_string::size_type n = Traits::length(s); -// return basic_string -// ::s_compare(s, s + n, y.begin(), y.end()) < 0; -} - -template -inline bool -operator<(const basic_string& x, - const CharT* s) -{ - return x.compare(s) < 0; -// basic_string::size_type n = Traits::length(s); -// return basic_string -// ::s_compare(x.begin(), x.end(), s, s + n) < 0; -} - -template -inline bool -operator>(const basic_string& x, - const basic_string& y) { - return y < x; -} - -template -inline bool -operator>(const CharT* s, const basic_string& y) { - return y < s; -} - -template -inline bool -operator>(const basic_string& x, const CharT* s) -{ - return s < x; -} - -template -inline bool -operator<=(const basic_string& x, - const basic_string& y) -{ - return !(y < x); -} - -template -inline bool -operator<=(const CharT* s, const basic_string& y) - { return !(y < s); } - -template -inline bool -operator<=(const basic_string& x, const CharT* s) - { return !(s < x); } - -template -inline bool -operator>=(const basic_string& x, - const basic_string& y) - { return !(x < y); } - -template -inline bool -operator>=(const CharT* s, const basic_string& y) - { return !(s < y); } - -template -inline bool -operator>=(const basic_string& x, const CharT* s) - { return !(x < s); } - -// Swap. -template -inline void swap(basic_string& x, basic_string& y) -{ x.swap(y); } - -/// @cond -// I/O. -namespace container_detail { - -template -inline bool -string_fill(std::basic_ostream& os, - std::basic_streambuf* buf, - std::size_t n) -{ - CharT f = os.fill(); - std::size_t i; - bool ok = true; - - for (i = 0; i < n; i++) - ok = ok && !Traits::eq_int_type(buf->sputc(f), Traits::eof()); - return ok; -} - -} //namespace container_detail { -/// @endcond - -template -std::basic_ostream& -operator<<(std::basic_ostream& os, const basic_string& s) -{ - typename std::basic_ostream::sentry sentry(os); - bool ok = false; - - if (sentry) { - ok = true; - typename basic_string::size_type n = s.size(); - typename basic_string::size_type pad_len = 0; - const bool left = (os.flags() & std::ios::left) != 0; - const std::size_t w = os.width(0); - std::basic_streambuf* buf = os.rdbuf(); - - if (w != 0 && n < w) - pad_len = w - n; - - if (!left) - ok = container_detail::string_fill(os, buf, pad_len); - - ok = ok && - buf->sputn(s.data(), std::streamsize(n)) == std::streamsize(n); - - if (left) - ok = ok && container_detail::string_fill(os, buf, pad_len); - } - - if (!ok) - os.setstate(std::ios_base::failbit); - - return os; -} - - -template -std::basic_istream& -operator>>(std::basic_istream& is, basic_string& s) -{ - typename std::basic_istream::sentry sentry(is); - - if (sentry) { - std::basic_streambuf* buf = is.rdbuf(); - const std::ctype& ctype = std::use_facet >(is.getloc()); - - s.clear(); - std::size_t n = is.width(0); - if (n == 0) - n = static_cast(-1); - else - s.reserve(n); - - while (n-- > 0) { - typename Traits::int_type c1 = buf->sbumpc(); - - if (Traits::eq_int_type(c1, Traits::eof())) { - is.setstate(std::ios_base::eofbit); - break; - } - else { - CharT c = Traits::to_char_type(c1); - - if (ctype.is(std::ctype::space, c)) { - if (Traits::eq_int_type(buf->sputbackc(c), Traits::eof())) - is.setstate(std::ios_base::failbit); - break; - } - else - s.push_back(c); - } - } - - // If we have read no characters, then set failbit. - if (s.size() == 0) - is.setstate(std::ios_base::failbit); - } - else - is.setstate(std::ios_base::failbit); - - return is; -} - -template -std::basic_istream& -getline(std::istream& is, basic_string& s,CharT delim) -{ - typename basic_string::size_type nread = 0; - typename std::basic_istream::sentry sentry(is, true); - if (sentry) { - std::basic_streambuf* buf = is.rdbuf(); - s.clear(); - - while (nread < s.max_size()) { - int c1 = buf->sbumpc(); - if (Traits::eq_int_type(c1, Traits::eof())) { - is.setstate(std::ios_base::eofbit); - break; - } - else { - ++nread; - CharT c = Traits::to_char_type(c1); - if (!Traits::eq(c, delim)) - s.push_back(c); - else - break; // Character is extracted but not appended. - } - } - } - if (nread == 0 || nread >= s.max_size()) - is.setstate(std::ios_base::failbit); - - return is; -} - -template -inline std::basic_istream& -getline(std::basic_istream& is, basic_string& s) -{ - return getline(is, s, '\n'); -} - -template -inline std::size_t hash_value(basic_string, Allocator> const& v) -{ - return hash_range(v.begin(), v.end()); -} - -}} - -/// @cond - -namespace boost { - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > - : public ::boost::has_trivial_destructor_after_move -{}; - -} - -/// @endcond - -#include - -#endif // BOOST_CONTAINER_STRING_HPP diff --git a/utils/boost_idb/boost/container/throw_exception.hpp b/utils/boost_idb/boost/container/throw_exception.hpp deleted file mode 100644 index 7c821c0b..00000000 --- a/utils/boost_idb/boost/container/throw_exception.hpp +++ /dev/null @@ -1,110 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2013. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_THROW_EXCEPTION_HPP -#define BOOST_CONTAINER_THROW_EXCEPTION_HPP - -#include -#include - -#if defined(_MSC_VER) -# pragma once -#endif - -#ifndef BOOST_NO_EXCEPTIONS - #include //for std exception types - #include //for std::bad_alloc -#else - #include - #include //for std::abort -#endif - -namespace boost { -namespace container { - -#if defined(BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS) - //The user must provide definitions for the following functions - - void throw_bad_alloc(); - - void throw_out_of_range(const char* str); - - void throw_length_error(const char* str); - - void throw_logic_error(const char* str); - - void throw_runtime_error(const char* str); - -#elif defined(BOOST_NO_EXCEPTIONS) - - inline void throw_bad_alloc() - { - BOOST_ASSERT(!"boost::container bad_alloc thrown"); - std::abort(); - } - - inline void throw_out_of_range(const char* str) - { - BOOST_ASSERT_MSG(!"boost::container out_of_range thrown", str); - std::abort(); - } - - inline void throw_length_error(const char* str) - { - BOOST_ASSERT_MSG(!"boost::container length_error thrown", str); - std::abort(); - } - - inline void throw_logic_error(const char* str) - { - BOOST_ASSERT_MSG(!"boost::container logic_error thrown", str); - std::abort(); - } - - inline void throw_runtime_error(const char* str) - { - BOOST_ASSERT_MSG(!"boost::container runtime_error thrown", str); - std::abort(); - } - -#else //defined(BOOST_NO_EXCEPTIONS) - - inline void throw_bad_alloc() - { - throw std::bad_alloc(); - } - - inline void throw_out_of_range(const char* str) - { - throw std::out_of_range(str); - } - - inline void throw_length_error(const char* str) - { - throw std::length_error(str); - } - - inline void throw_logic_error(const char* str) - { - throw std::logic_error(str); - } - - inline void throw_runtime_error(const char* str) - { - throw std::runtime_error(str); - } - -#endif - -}} //namespace boost { namespace container { - -#include - -#endif //#ifndef BOOST_CONTAINER_THROW_EXCEPTION_HPP diff --git a/utils/boost_idb/boost/container/vector.hpp b/utils/boost_idb/boost/container/vector.hpp deleted file mode 100644 index eabcab9e..00000000 --- a/utils/boost_idb/boost/container/vector.hpp +++ /dev/null @@ -1,2684 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_CONTAINER_VECTOR_HPP -#define BOOST_CONTAINER_CONTAINER_VECTOR_HPP - -#if defined(_MSC_VER) -# pragma once -#endif - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace container { - -/// @cond - -//#define BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -namespace container_detail { - -#ifndef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -template -class vec_iterator -{ - public: - typedef std::random_access_iterator_tag iterator_category; - typedef typename boost::intrusive::pointer_traits::element_type value_type; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename if_c - < IsConst - , typename boost::intrusive::pointer_traits::template - rebind_pointer::type - , Pointer - >::type pointer; - typedef typename if_c - < IsConst - , const value_type& - , value_type& - >::type reference; - - /// @cond - private: - Pointer m_ptr; - - public: - const Pointer &get_ptr() const BOOST_CONTAINER_NOEXCEPT - { return m_ptr; } - - Pointer &get_ptr() BOOST_CONTAINER_NOEXCEPT - { return m_ptr; } - - explicit vec_iterator(Pointer ptr) BOOST_CONTAINER_NOEXCEPT - : m_ptr(ptr) - {} - /// @endcond - - public: - - //Constructors - vec_iterator() BOOST_CONTAINER_NOEXCEPT - #ifndef NDEBUG - : m_ptr() - #else - // No value initialization of m_ptr() to speed up things a bit: - #endif - {} - - vec_iterator(vec_iterator const& other) BOOST_CONTAINER_NOEXCEPT - : m_ptr(other.get_ptr()) - {} - - //Pointer like operators - reference operator*() const BOOST_CONTAINER_NOEXCEPT - { return *m_ptr; } - - pointer operator->() const BOOST_CONTAINER_NOEXCEPT - { return ::boost::intrusive::pointer_traits::pointer_to(this->operator*()); } - - reference operator[](difference_type off) const BOOST_CONTAINER_NOEXCEPT - { return m_ptr[off]; } - - //Increment / Decrement - vec_iterator& operator++() BOOST_CONTAINER_NOEXCEPT - { ++m_ptr; return *this; } - - vec_iterator operator++(int) BOOST_CONTAINER_NOEXCEPT - { return vec_iterator(m_ptr++); } - - vec_iterator& operator--() BOOST_CONTAINER_NOEXCEPT - { --m_ptr; return *this; } - - vec_iterator operator--(int) BOOST_CONTAINER_NOEXCEPT - { return vec_iterator(m_ptr--); } - - //Arithmetic - vec_iterator& operator+=(difference_type off) BOOST_CONTAINER_NOEXCEPT - { m_ptr += off; return *this; } - - vec_iterator& operator-=(difference_type off) BOOST_CONTAINER_NOEXCEPT - { m_ptr -= off; return *this; } - - friend vec_iterator operator+(const vec_iterator &x, difference_type off) BOOST_CONTAINER_NOEXCEPT - { return vec_iterator(x.m_ptr+off); } - - friend vec_iterator operator+(difference_type off, vec_iterator right) BOOST_CONTAINER_NOEXCEPT - { right.m_ptr += off; return right; } - - friend vec_iterator operator-(vec_iterator left, difference_type off) BOOST_CONTAINER_NOEXCEPT - { left.m_ptr -= off; return left; } - - friend difference_type operator-(const vec_iterator &left, const vec_iterator& right) BOOST_CONTAINER_NOEXCEPT - { return left.m_ptr - right.m_ptr; } - - //Comparison operators - friend bool operator== (const vec_iterator& l, const vec_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_ptr == r.m_ptr; } - - friend bool operator!= (const vec_iterator& l, const vec_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_ptr != r.m_ptr; } - - friend bool operator< (const vec_iterator& l, const vec_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_ptr < r.m_ptr; } - - friend bool operator<= (const vec_iterator& l, const vec_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_ptr <= r.m_ptr; } - - friend bool operator> (const vec_iterator& l, const vec_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_ptr > r.m_ptr; } - - friend bool operator>= (const vec_iterator& l, const vec_iterator& r) BOOST_CONTAINER_NOEXCEPT - { return l.m_ptr >= r.m_ptr; } -}; - -} //namespace container_detail { - -template -const Pointer &vector_iterator_get_ptr(const container_detail::vec_iterator &it) BOOST_CONTAINER_NOEXCEPT -{ return it.get_ptr(); } - -template -Pointer &get_ptr(container_detail::vec_iterator &it) BOOST_CONTAINER_NOEXCEPT -{ return it.get_ptr(); } - -namespace container_detail { - -#else //ifndef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -template< class MaybeConstPointer - , bool ElementTypeIsConst - = is_const< typename boost::intrusive::pointer_traits::element_type>::value > -struct vector_get_ptr_pointer_to_non_const -{ - typedef MaybeConstPointer const_pointer; - typedef boost::intrusive::pointer_traits pointer_traits_t; - typedef typename pointer_traits_t::element_type element_type; - typedef typename remove_const::type non_const_element_type; - typedef typename pointer_traits_t - ::template rebind_pointer::type return_type; - - static return_type get_ptr(const const_pointer &ptr) BOOST_CONTAINER_NOEXCEPT - { return boost::intrusive::pointer_traits::const_cast_from(ptr); } -}; - -template -struct vector_get_ptr_pointer_to_non_const -{ - typedef const Pointer & return_type; - static return_type get_ptr(const Pointer &ptr) BOOST_CONTAINER_NOEXCEPT - { return ptr; } -}; - -} //namespace container_detail { - -template -typename container_detail::vector_get_ptr_pointer_to_non_const::return_type - vector_iterator_get_ptr(const MaybeConstPointer &ptr) BOOST_CONTAINER_NOEXCEPT -{ - return container_detail::vector_get_ptr_pointer_to_non_const::get_ptr(ptr); -} - -namespace container_detail { - -#endif //#ifndef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER - -template -struct vector_value_traits -{ - typedef T value_type; - typedef Allocator allocator_type; - static const bool trivial_dctr = boost::has_trivial_destructor::value; - static const bool trivial_dctr_after_move = ::boost::has_trivial_destructor_after_move::value; - static const bool trivial_copy = has_trivial_copy::value; - static const bool nothrow_copy = has_nothrow_copy::value || trivial_copy; - static const bool trivial_assign = has_trivial_assign::value; - static const bool nothrow_assign = has_nothrow_assign::value || trivial_assign; - - //This is the anti-exception array destructor - //to deallocate values already constructed - typedef typename container_detail::if_c - - ,container_detail::scoped_destructor_n - >::type OldArrayDestructor; - //This is the anti-exception array destructor - //to destroy objects created with copy construction - typedef typename container_detail::if_c - - ,container_detail::scoped_destructor_n - >::type ArrayDestructor; - //This is the anti-exception array deallocator - typedef typename container_detail::if_c - - ,container_detail::scoped_array_deallocator - >::type ArrayDeallocator; -}; - -//!This struct deallocates and allocated memory -template < class Allocator - , class AllocatorVersion = container_detail::integral_constant - < unsigned - , boost::container::container_detail::version::value - > - > -struct vector_alloc_holder - : public Allocator -{ - private: - BOOST_MOVABLE_BUT_NOT_COPYABLE(vector_alloc_holder) - - public: - typedef boost::container::allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::pointer pointer; - typedef typename allocator_traits_type::size_type size_type; - typedef typename allocator_traits_type::value_type value_type; - - //Constructor, does not throw - vector_alloc_holder() - BOOST_CONTAINER_NOEXCEPT_IF(::boost::has_nothrow_default_constructor::value) - : Allocator(), m_start(), m_size(), m_capacity() - {} - - //Constructor, does not throw - template - explicit vector_alloc_holder(BOOST_FWD_REF(AllocConvertible) a) BOOST_CONTAINER_NOEXCEPT - : Allocator(boost::forward(a)), m_start(), m_size(), m_capacity() - {} - - //Constructor, does not throw - template - explicit vector_alloc_holder(BOOST_FWD_REF(AllocConvertible) a, size_type initial_size) - : Allocator(boost::forward(a)) - , m_start() - , m_size(initial_size) //Size is initialized here so vector should only call uninitialized_xxx after this - , m_capacity() - { - if(initial_size){ - m_start = this->allocation_command(allocate_new, initial_size, initial_size, m_capacity, m_start).first; - } - } - - //Constructor, does not throw - explicit vector_alloc_holder(size_type initial_size) - : Allocator() - , m_start() - , m_size(initial_size) //Size is initialized here so vector should only call uninitialized_xxx after this - , m_capacity() - { - if(initial_size){ - m_start = this->allocation_command - (allocate_new, initial_size, initial_size, m_capacity, m_start).first; - } - } - - vector_alloc_holder(BOOST_RV_REF(vector_alloc_holder) holder) BOOST_CONTAINER_NOEXCEPT - : Allocator(boost::move(static_cast(holder))) - , m_start(holder.m_start) - , m_size(holder.m_size) - , m_capacity(holder.m_capacity) - { - holder.m_start = pointer(); - holder.m_size = holder.m_capacity = 0; - } - - void first_allocation(size_type cap) - { - if(cap){ - m_start = this->allocation_command - (allocate_new, cap, cap, m_capacity, m_start).first; - } - } - - void first_allocation_same_allocator_type(size_type cap) - { this->first_allocation(cap); } - - ~vector_alloc_holder() BOOST_CONTAINER_NOEXCEPT - { - if(this->m_capacity){ - this->alloc().deallocate(this->m_start, this->m_capacity); - } - } - - std::pair - allocation_command(allocation_type command, - size_type limit_size, - size_type preferred_size, - size_type &received_size, const pointer &reuse = pointer()) - { - return allocator_version_traits::allocation_command - (this->alloc(), command, limit_size, preferred_size, received_size, reuse); - } - - size_type next_capacity(size_type additional_objects) const - { - std::size_t num_objects = this->m_size + additional_objects; - std::size_t next_cap = this->m_capacity + this->m_capacity/2; - return num_objects > next_cap ? num_objects : next_cap;/* - return get_next_capacity( allocator_traits_type::max_size(this->m_holder.alloc()) - , this->m_capacity, additional_objects);*/ - } - - pointer m_start; - size_type m_size; - size_type m_capacity; - - void swap(vector_alloc_holder &x) BOOST_CONTAINER_NOEXCEPT - { - boost::container::swap_dispatch(this->m_start, x.m_start); - boost::container::swap_dispatch(this->m_size, x.m_size); - boost::container::swap_dispatch(this->m_capacity, x.m_capacity); - } - - void move_from_empty(vector_alloc_holder &x) BOOST_CONTAINER_NOEXCEPT - { - this->m_start = x.m_start; - this->m_size = x.m_size; - this->m_capacity = x.m_capacity; - x.m_start = pointer(); - x.m_size = x.m_capacity = 0; - } - - Allocator &alloc() BOOST_CONTAINER_NOEXCEPT - { return *this; } - - const Allocator &alloc() const BOOST_CONTAINER_NOEXCEPT - { return *this; } - - const pointer &start() const BOOST_CONTAINER_NOEXCEPT { return m_start; } - const size_type &capacity() const BOOST_CONTAINER_NOEXCEPT { return m_capacity; } - void start(const pointer &p) BOOST_CONTAINER_NOEXCEPT { m_start = p; } - void capacity(const size_type &c) BOOST_CONTAINER_NOEXCEPT { m_capacity = c; } -}; - -//!This struct deallocates and allocated memory -template -struct vector_alloc_holder > - : public Allocator -{ - private: - BOOST_MOVABLE_BUT_NOT_COPYABLE(vector_alloc_holder) - - public: - typedef boost::container::allocator_traits allocator_traits_type; - typedef typename allocator_traits_type::pointer pointer; - typedef typename allocator_traits_type::size_type size_type; - typedef typename allocator_traits_type::value_type value_type; - - template - friend struct vector_alloc_holder; - - //Constructor, does not throw - vector_alloc_holder() - BOOST_CONTAINER_NOEXCEPT_IF(::boost::has_nothrow_default_constructor::value) - : Allocator(), m_size() - {} - - //Constructor, does not throw - template - explicit vector_alloc_holder(BOOST_FWD_REF(AllocConvertible) a) BOOST_CONTAINER_NOEXCEPT - : Allocator(boost::forward(a)), m_size() - {} - - //Constructor, does not throw - template - explicit vector_alloc_holder(BOOST_FWD_REF(AllocConvertible) a, size_type initial_size) - : Allocator(boost::forward(a)) - , m_size(initial_size) //Size is initialized here... - { - //... and capacity here, so vector, must call uninitialized_xxx in the derived constructor - this->first_allocation(initial_size); - } - - //Constructor, does not throw - explicit vector_alloc_holder(size_type initial_size) - : Allocator() - , m_size(initial_size) //Size is initialized here... - { - //... and capacity here, so vector, must call uninitialized_xxx in the derived constructor - this->first_allocation(initial_size); - } - - vector_alloc_holder(BOOST_RV_REF(vector_alloc_holder) holder) - : Allocator(boost::move(static_cast(holder))) - , m_size(holder.m_size) //Size is initialized here so vector should only call uninitialized_xxx after this - { - ::boost::container::uninitialized_move_alloc_n - (this->alloc(), container_detail::to_raw_pointer(holder.start()), m_size, container_detail::to_raw_pointer(this->start())); - } - - template - vector_alloc_holder(BOOST_RV_REF_BEG vector_alloc_holder BOOST_RV_REF_END holder) - : Allocator() - , m_size(holder.m_size) //Initialize it to m_size as first_allocation can only succeed or abort - { - //Different allocator type so we must check we have enough storage - const size_type n = holder.m_size; - this->first_allocation(n); - ::boost::container::uninitialized_move_alloc_n - (this->alloc(), container_detail::to_raw_pointer(holder.start()), n, container_detail::to_raw_pointer(this->start())); - } - - void first_allocation(size_type cap) - { - if(cap > Allocator::internal_capacity){ - throw_bad_alloc(); - } - } - - void first_allocation_same_allocator_type(size_type) BOOST_CONTAINER_NOEXCEPT - {} - - //Destructor - ~vector_alloc_holder() BOOST_CONTAINER_NOEXCEPT - {} - - void swap(vector_alloc_holder &x) - { - this->priv_swap_members_impl(x); - } - - template - void swap(vector_alloc_holder &x) - { - if(this->m_size > OtherAllocator::internal_capacity || x.m_size > Allocator::internal_capacity){ - throw_bad_alloc(); - } - this->priv_swap_members_impl(x); - } - - void move_from_empty(vector_alloc_holder &) - { //Containers with version 0 allocators can't be moved without move elements one by one - throw_bad_alloc(); - } - - Allocator &alloc() BOOST_CONTAINER_NOEXCEPT - { return *this; } - - const Allocator &alloc() const BOOST_CONTAINER_NOEXCEPT - { return *this; } - - pointer start() const BOOST_CONTAINER_NOEXCEPT { return Allocator::internal_storage(); } - size_type capacity() const BOOST_CONTAINER_NOEXCEPT { return Allocator::internal_capacity; } - size_type m_size; - - private: - - template - void priv_swap_members_impl(vector_alloc_holder &x) - { - const std::size_t MaxTmpStorage = sizeof(value_type)*Allocator::internal_capacity; - value_type *const first_this = container_detail::to_raw_pointer(this->start()); - value_type *const first_x = container_detail::to_raw_pointer(x.start()); - - if(this->m_size < x.m_size){ - boost::container::deep_swap_alloc_n(this->alloc(), first_this, this->m_size, first_x, x.m_size); - } - else{ - boost::container::deep_swap_alloc_n(this->alloc(), first_x, x.m_size, first_this, this->m_size); - } - boost::container::swap_dispatch(this->m_size, x.m_size); - } -}; - -} //namespace container_detail { - -/// @endcond - -//! \class vector -//! A vector is a sequence that supports random access to elements, constant -//! time insertion and removal of elements at the end, and linear time insertion -//! and removal of elements at the beginning or in the middle. The number of -//! elements in a vector may vary dynamically; memory management is automatic. -//! boost::container::vector is similar to std::vector but it's compatible -//! with shared memory and memory mapped files. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else -template -#endif -class vector -{ - /// @cond - typedef container_detail::integral_constant - ::value > alloc_version; - boost::container::container_detail::vector_alloc_holder - m_holder; - typedef allocator_traits allocator_traits_type; - template - friend class vector; - - typedef typename ::boost::container::allocator_traits - ::pointer pointer_impl; - typedef container_detail::vec_iterator iterator_impl; - typedef container_detail::vec_iterator const_iterator_impl; - - /// @endcond - public: - ////////////////////////////////////////////// - // - // types - // - ////////////////////////////////////////////// - - typedef T value_type; - typedef typename ::boost::container::allocator_traits::pointer pointer; - typedef typename ::boost::container::allocator_traits::const_pointer const_pointer; - typedef typename ::boost::container::allocator_traits::reference reference; - typedef typename ::boost::container::allocator_traits::const_reference const_reference; - typedef typename ::boost::container::allocator_traits::size_type size_type; - typedef typename ::boost::container::allocator_traits::difference_type difference_type; - typedef Allocator allocator_type; - typedef Allocator stored_allocator_type; - #if defined BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER && !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - typedef BOOST_CONTAINER_IMPDEF(pointer) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_pointer) const_iterator; - #else - typedef BOOST_CONTAINER_IMPDEF(iterator_impl) iterator; - typedef BOOST_CONTAINER_IMPDEF(const_iterator_impl) const_iterator; - #endif - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; - typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - - /// @cond - private: - BOOST_COPYABLE_AND_MOVABLE(vector) - typedef container_detail::vector_value_traits value_traits; - - typedef container_detail::integral_constant allocator_v0; - typedef container_detail::integral_constant allocator_v1; - typedef container_detail::integral_constant allocator_v2; - - typedef constant_iterator cvalue_iterator; - /// @endcond - - public: - ////////////////////////////////////////////// - // - // construct/copy/destroy - // - ////////////////////////////////////////////// - - //! Effects: Constructs a vector taking the allocator as parameter. - //! - //! Throws: If allocator_type's default constructor throws. - //! - //! Complexity: Constant. - vector() - BOOST_CONTAINER_NOEXCEPT_IF(::boost::has_nothrow_default_constructor::value) - : m_holder() - {} - - //! Effects: Constructs a vector taking the allocator as parameter. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - explicit vector(const Allocator& a) BOOST_CONTAINER_NOEXCEPT - : m_holder(a) - {} - - //! Effects: Constructs a vector that will use a copy of allocator a - //! and inserts n value initialized values. - //! - //! Throws: If allocator_type's default constructor or allocation - //! throws or T's default constructor throws. - //! - //! Complexity: Linear to n. - explicit vector(size_type n) - : m_holder(n) - { - boost::container::uninitialized_value_init_alloc_n - (this->m_holder.alloc(), n, container_detail::to_raw_pointer(this->m_holder.start())); - } - - //! Effects: Constructs a vector that will use a copy of allocator a - //! and inserts n default initialized values. - //! - //! Throws: If allocator_type's default constructor or allocation - //! throws or T's default constructor throws. - //! - //! Complexity: Linear to n. - //! - //! Note: Non-standard extension - explicit vector(size_type n, default_init_t) - : m_holder(n) - { - boost::container::uninitialized_default_init_alloc_n - (this->m_holder.alloc(), n, container_detail::to_raw_pointer(this->m_holder.start())); - } - - //! Effects: Constructs a vector - //! and inserts n copies of value. - //! - //! Throws: If allocator_type's default constructor or allocation - //! throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - vector(size_type n, const T& value) - : m_holder(n) - { - boost::container::uninitialized_fill_alloc_n - (this->m_holder.alloc(), value, n, container_detail::to_raw_pointer(this->m_holder.start())); - } - - //! Effects: Constructs a vector that will use a copy of allocator a - //! and inserts n copies of value. - //! - //! Throws: If allocation - //! throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - vector(size_type n, const T& value, const allocator_type& a) - : m_holder(a, n) - { - boost::container::uninitialized_fill_alloc_n - (this->m_holder.alloc(), value, n, container_detail::to_raw_pointer(this->m_holder.start())); - } - - //! Effects: Constructs a vector - //! and inserts a copy of the range [first, last) in the vector. - //! - //! Throws: If allocator_type's default constructor or allocation - //! throws or T's constructor taking an dereferenced InIt throws. - //! - //! Complexity: Linear to the range [first, last). - template - vector(InIt first, InIt last) - : m_holder() - { this->insert(this->cend(), first, last); } - - //! Effects: Constructs a vector that will use a copy of allocator a - //! and inserts a copy of the range [first, last) in the vector. - //! - //! Throws: If allocator_type's default constructor or allocation - //! throws or T's constructor taking an dereferenced InIt throws. - //! - //! Complexity: Linear to the range [first, last). - template - vector(InIt first, InIt last, const allocator_type& a) - : m_holder(a) - { this->insert(this->cend(), first, last); } - - //! Effects: Copy constructs a vector. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocator_type's default constructor or allocation - //! throws or T's copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - vector(const vector &x) - : m_holder(allocator_traits_type::select_on_container_copy_construction(x.m_holder.alloc()), x.size()) - { - ::boost::container::uninitialized_copy_alloc_n - ( this->m_holder.alloc(), container_detail::to_raw_pointer(x.m_holder.start()) - , x.size(), container_detail::to_raw_pointer(this->m_holder.start())); - } - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - vector(BOOST_RV_REF(vector) mx) BOOST_CONTAINER_NOEXCEPT - : m_holder(boost::move(mx.m_holder)) - {} - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Move constructor. Moves mx's resources to *this. - //! - //! Throws: If T's move constructor or allocation throws - //! - //! Complexity: Linear. - //! - //! Note: Non-standard extension - template - vector(BOOST_RV_REF_BEG vector BOOST_RV_REF_END mx) - : m_holder(boost::move(mx.m_holder)) - {} - - #endif //!defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Copy constructs a vector using the specified allocator. - //! - //! Postcondition: x == *this. - //! - //! Throws: If allocation - //! throws or T's copy constructor throws. - //! - //! Complexity: Linear to the elements x contains. - vector(const vector &x, const allocator_type &a) - : m_holder(a, x.size()) - { - ::boost::container::uninitialized_copy_alloc_n_source - ( this->m_holder.alloc(), container_detail::to_raw_pointer(x.m_holder.start()) - , x.size(), container_detail::to_raw_pointer(this->m_holder.start())); - } - - //! Effects: Move constructor using the specified allocator. - //! Moves mx's resources to *this if a == allocator_type(). - //! Otherwise copies values from x to *this. - //! - //! Throws: If allocation or T's copy constructor throws. - //! - //! Complexity: Constant if a == mx.get_allocator(), linear otherwise. - vector(BOOST_RV_REF(vector) mx, const allocator_type &a) - : m_holder(a) - { - if(mx.m_holder.alloc() == a){ - this->m_holder.move_from_empty(mx.m_holder); - } - else{ - const size_type n = mx.size(); - this->m_holder.first_allocation_same_allocator_type(n); - ::boost::container::uninitialized_move_alloc_n_source - ( this->m_holder.alloc(), container_detail::to_raw_pointer(mx.m_holder.start()) - , n, container_detail::to_raw_pointer(this->m_holder.start())); - this->m_holder.m_size = n; - } - } - - //! Effects: Destroys the vector. All stored values are destroyed - //! and used memory is deallocated. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements. - ~vector() BOOST_CONTAINER_NOEXCEPT - { - boost::container::destroy_alloc_n - (this->get_stored_allocator(), container_detail::to_raw_pointer(this->m_holder.start()), this->m_holder.m_size); - //vector_alloc_holder deallocates the data - } - - //! Effects: Makes *this contain the same elements as x. - //! - //! Postcondition: this->size() == x.size(). *this contains a copy - //! of each of x's elements. - //! - //! Throws: If memory allocation throws or T's copy/move constructor/assignment throws. - //! - //! Complexity: Linear to the number of elements in x. - vector& operator=(BOOST_COPY_ASSIGN_REF(vector) x) - { - if (&x != this){ - this->priv_copy_assign(boost::move(x), alloc_version()); - } - return *this; - } - - //! Effects: Move assignment. All mx's values are transferred to *this. - //! - //! Postcondition: x.empty(). *this contains a the elements x had - //! before the function. - //! - //! Throws: Nothing - //! - //! Complexity: Linear. - vector& operator=(BOOST_RV_REF(vector) x) - //iG BOOST_CONTAINER_NOEXCEPT_IF(!allocator_type::propagate_on_container_move_assignment::value || is_nothrow_move_assignable::value);) - BOOST_CONTAINER_NOEXCEPT - { - this->priv_move_assign(boost::move(x), alloc_version()); - return *this; - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - - //! Effects: Move assignment. All mx's values are transferred to *this. - //! - //! Postcondition: x.empty(). *this contains a the elements x had - //! before the function. - //! - //! Throws: If move constructor/assignment of T throws or allocation throws - //! - //! Complexity: Linear. - template - vector& operator=(BOOST_RV_REF_BEG vector BOOST_RV_REF_END x) - { - this->priv_move_assign(boost::move(x), alloc_version()); - return *this; - } - - #endif - - //! Effects: Assigns the the range [first, last) to *this. - //! - //! Throws: If memory allocation throws or T's copy/move constructor/assignment or - //! T's constructor/assignment from dereferencing InpIt throws. - //! - //! Complexity: Linear to n. - template - void assign(InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - //&& container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - //Overwrite all elements we can from [first, last) - iterator cur = this->begin(); - const iterator end_it = this->end(); - for ( ; first != last && cur != end_it; ++cur, ++first){ - *cur = *first; - } - - if (first == last){ - //There are no more elements in the sequence, erase remaining - T* const end_pos = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - size_type n = static_cast(end_pos - container_detail::to_raw_pointer(vector_iterator_get_ptr(cur))); - this->priv_destroy_last_n(n); - } - else{ - //There are more elements in the range, insert the remaining ones - this->insert(this->cend(), first, last); - } - } - - //! Effects: Assigns the n copies of val to *this. - //! - //! Throws: If memory allocation throws or - //! T's copy/move constructor/assignment throws. - //! - //! Complexity: Linear to n. - void assign(size_type n, const value_type& val) - { this->assign(cvalue_iterator(val, n), cvalue_iterator()); } - - //! Effects: Returns a copy of the internal allocator. - //! - //! Throws: If allocator's copy constructor throws. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.alloc(); } - - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.alloc(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// - - //! Effects: Returns an iterator to the first element contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->m_holder.start()); } - - //! Effects: Returns a const_iterator to the first element contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->m_holder.start()); } - - //! Effects: Returns an iterator to the end of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return iterator(this->m_holder.start() + this->m_holder.m_size); } - - //! Effects: Returns a const_iterator to the end of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } - - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->end()); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return reverse_iterator(this->begin()); } - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->m_holder.start()); } - - //! Effects: Returns a const_iterator to the end of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return const_iterator(this->m_holder.start() + this->m_holder.m_size); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->end());} - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return const_reverse_iterator(this->begin()); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// - - //! Effects: Returns true if the vector contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return !this->m_holder.m_size; } - - //! Effects: Returns the number of the elements contained in the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.m_size; } - - //! Effects: Returns the largest possible size of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return allocator_traits_type::max_size(this->m_holder.alloc()); } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws, or T's constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size) - { - const size_type sz = this->size(); - if (new_size < sz){ - //Destroy last elements - this->priv_destroy_last_n(sz - new_size); - } - else{ - const size_type n = new_size - this->size(); - container_detail::insert_value_initialized_n_proxy proxy(this->m_holder.alloc()); - this->priv_forward_range_insert_at_end(n, proxy, alloc_version()); - } - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are value initialized. - //! - //! Throws: If memory allocation throws, or T's constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - //! - //! Note: Non-standard extension - void resize(size_type new_size, default_init_t) - { - const size_type sz = this->size(); - if (new_size < sz){ - //Destroy last elements - this->priv_destroy_last_n(sz - new_size); - } - else{ - const size_type n = new_size - this->size(); - container_detail::insert_default_initialized_n_proxy proxy(this->m_holder.alloc()); - this->priv_forward_range_insert_at_end(n, proxy, alloc_version()); - } - } - - //! Effects: Inserts or erases elements at the end such that - //! the size becomes n. New elements are copy constructed from x. - //! - //! Throws: If memory allocation throws, or T's copy constructor throws. - //! - //! Complexity: Linear to the difference between size() and new_size. - void resize(size_type new_size, const T& x) - { - const size_type sz = this->size(); - if (new_size < sz){ - //Destroy last elements - this->priv_destroy_last_n(sz - new_size); - } - else{ - const size_type n = new_size - this->size(); - container_detail::insert_n_copies_proxy proxy(this->m_holder.alloc(), x); - this->priv_forward_range_insert_at_end(n, proxy, alloc_version()); - } - } - - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.capacity(); } - - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws or T's copy/move constructor throws. - void reserve(size_type new_cap) - { - if (this->capacity() < new_cap){ - this->priv_reserve(new_cap, alloc_version()); - } - } - - //! Effects: Tries to deallocate the excess of memory created - //! with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or T's copy/move constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { this->priv_shrink_to_fit(alloc_version()); } - - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the first - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference front() BOOST_CONTAINER_NOEXCEPT - { return *this->m_holder.start(); } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the first - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference front() const BOOST_CONTAINER_NOEXCEPT - { return *this->m_holder.start(); } - - //! Requires: !empty() - //! - //! Effects: Returns a reference to the last - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference back() BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.start()[this->m_holder.m_size - 1]; } - - //! Requires: !empty() - //! - //! Effects: Returns a const reference to the last - //! element of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference back() const BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.start()[this->m_holder.m_size - 1]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reference operator[](size_type n) BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.start()[n]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reference operator[](size_type n) const BOOST_CONTAINER_NOEXCEPT - { return this->m_holder.start()[n]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - reference at(size_type n) - { this->priv_check_range(n); return this->m_holder.start()[n]; } - - //! Requires: size() > n. - //! - //! Effects: Returns a const reference to the nth element - //! from the beginning of the container. - //! - //! Throws: std::range_error if n >= size() - //! - //! Complexity: Constant. - const_reference at(size_type n) const - { this->priv_check_range(n); return this->m_holder.start()[n]; } - - ////////////////////////////////////////////// - // - // data access - // - ////////////////////////////////////////////// - - //! Returns: Allocator pointer such that [data(),data() + size()) is a valid range. - //! For a non-empty vector, data() == &front(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - T* data() BOOST_CONTAINER_NOEXCEPT - { return container_detail::to_raw_pointer(this->m_holder.start()); } - - //! Returns: Allocator pointer such that [data(),data() + size()) is a valid range. - //! For a non-empty vector, data() == &front(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const T * data() const BOOST_CONTAINER_NOEXCEPT - { return container_detail::to_raw_pointer(this->m_holder.start()); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// - - #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... in the end of the vector. - //! - //! Throws: If memory allocation throws or the in-place constructor throws or - //! T's move constructor throws. - //! - //! Complexity: Amortized constant time. - template - void emplace_back(Args &&...args) - { - T* back_pos = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - if (this->m_holder.m_size < this->m_holder.capacity()){ - //There is more memory, just construct a new object at the end - allocator_traits_type::construct(this->m_holder.alloc(), back_pos, ::boost::forward(args)...); - ++this->m_holder.m_size; - } - else{ - typedef container_detail::insert_emplace_proxy type; - this->priv_forward_range_insert_no_capacity - (vector_iterator_get_ptr(this->cend()), 1, type(this->m_holder.alloc(), ::boost::forward(args)...), alloc_version()); - } - } - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Inserts an object of type T constructed with - //! std::forward(args)... before position - //! - //! Throws: If memory allocation throws or the in-place constructor throws or - //! T's move constructor/assignment throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - template - iterator emplace(const_iterator position, Args && ...args) - { - //Just call more general insert(pos, size, value) and return iterator - typedef container_detail::insert_emplace_proxy type; - return this->priv_forward_range_insert( vector_iterator_get_ptr(position), 1, type(this->m_holder.alloc() - , ::boost::forward(args)...), alloc_version()); - } - - #else - - #define BOOST_PP_LOCAL_MACRO(n) \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - T* back_pos = container_detail::to_raw_pointer \ - (this->m_holder.start()) + this->m_holder.m_size; \ - if (this->m_holder.m_size < this->m_holder.capacity()){ \ - allocator_traits_type::construct (this->m_holder.alloc() \ - , back_pos BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ); \ - ++this->m_holder.m_size; \ - } \ - else{ \ - container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ - proxy \ - (this->m_holder.alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - this->priv_forward_range_insert_no_capacity \ - (vector_iterator_get_ptr(this->cend()), 1, proxy, alloc_version()); \ - } \ - } \ - \ - BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ - iterator emplace(const_iterator pos \ - BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { \ - container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ - proxy \ - (this->m_holder.alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - return this->priv_forward_range_insert \ - (container_detail::to_raw_pointer(vector_iterator_get_ptr(pos)), 1, proxy, alloc_version()); \ - } \ - //! - #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) - #include BOOST_PP_LOCAL_ITERATE() - - #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Inserts a copy of x at the end of the vector. - //! - //! Throws: If memory allocation throws or - //! T's copy/move constructor throws. - //! - //! Complexity: Amortized constant time. - void push_back(const T &x); - - //! Effects: Constructs a new element in the end of the vector - //! and moves the resources of mx to this new element. - //! - //! Throws: If memory allocation throws or - //! T's move constructor throws. - //! - //! Complexity: Amortized constant time. - void push_back(T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH(push_back, T, void, priv_push_back) - #endif - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a copy of x before position. - //! - //! Throws: If memory allocation throws or T's copy/move constructor/assignment throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - iterator insert(const_iterator position, const T &x); - - //! Requires: position must be a valid iterator of *this. - //! - //! Effects: Insert a new element before position with mx's resources. - //! - //! Throws: If memory allocation throws. - //! - //! Complexity: If position is end(), amortized constant time - //! Linear time otherwise. - iterator insert(const_iterator position, T &&x); - #else - BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, T, iterator, priv_insert, const_iterator, const_iterator) - #endif - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Insert n copies of x before pos. - //! - //! Returns: an iterator to the first inserted element or p if n is 0. - //! - //! Throws: If memory allocation throws or T's copy constructor throws. - //! - //! Complexity: Linear to n. - iterator insert(const_iterator p, size_type n, const T& x) - { - container_detail::insert_n_copies_proxy proxy(this->m_holder.alloc(), x); - return this->priv_forward_range_insert(vector_iterator_get_ptr(p), n, proxy, alloc_version()); - } - - //! Requires: p must be a valid iterator of *this. - //! - //! Effects: Insert a copy of the [first, last) range before pos. - //! - //! Returns: an iterator to the first inserted element or pos if first == last. - //! - //! Throws: If memory allocation throws, T's constructor from a - //! dereferenced InpIt throws or T's copy/move constructor/assignment throws. - //! - //! Complexity: Linear to std::distance [first, last). - template - iterator insert(const_iterator pos, InIt first, InIt last - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && container_detail::is_input_iterator::value - >::type * = 0 - #endif - ) - { - const size_type n_pos = pos - this->cbegin(); - iterator it(vector_iterator_get_ptr(pos)); - for(;first != last; ++first){ - it = this->emplace(it, *first); - ++it; - } - return iterator(this->m_holder.start() + n_pos); - } - - #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - iterator insert(const_iterator pos, FwdIt first, FwdIt last - , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - && !container_detail::is_input_iterator::value - >::type * = 0 - ) - { - container_detail::insert_range_proxy proxy(this->m_holder.alloc(), first); - return this->priv_forward_range_insert(vector_iterator_get_ptr(pos), std::distance(first, last), proxy, alloc_version()); - } - #endif - - //! Effects: Removes the last element from the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant time. - void pop_back() BOOST_CONTAINER_NOEXCEPT - { - //Destroy last element - --this->m_holder.m_size; - this->priv_destroy(container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size); - } - - //! Effects: Erases the element at position pos. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the elements between pos and the - //! last element. Constant if pos is the last element. - iterator erase(const_iterator position) - { - T *const pos = container_detail::to_raw_pointer(vector_iterator_get_ptr(position)); - T *const beg = container_detail::to_raw_pointer(this->m_holder.start()); - //Move elements forward and destroy last - this->priv_destroy(::boost::move(pos + 1, beg + this->m_holder.m_size, pos)); - --this->m_holder.m_size; - return iterator(vector_iterator_get_ptr(position)); - } - - //! Effects: Erases the elements pointed by [first, last). - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the distance between first and last - //! plus linear to the elements between pos and the last element. - iterator erase(const_iterator first, const_iterator last) - { - if (first != last){ - T* const end_pos = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - T* const ptr = container_detail::to_raw_pointer(boost::move - (container_detail::to_raw_pointer(vector_iterator_get_ptr(last)) - ,end_pos - ,container_detail::to_raw_pointer(vector_iterator_get_ptr(first)) - )); - const size_type destroyed = (end_pos - ptr); - boost::container::destroy_alloc_n(this->get_stored_allocator(), ptr, destroyed); - this->m_holder.m_size -= destroyed; - } - return iterator(vector_iterator_get_ptr(first)); - } - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(vector& x) BOOST_CONTAINER_NOEXCEPT_IF((!container_detail::is_same::value)) - { - //Just swap internals in case of !allocator_v0. Otherwise, deep swap - this->m_holder.swap(x.m_holder); - //And now the allocator - container_detail::bool_ flag; - container_detail::swap_alloc(this->m_holder.alloc(), x.m_holder.alloc(), flag); - } - - #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED - - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: If T's move constructor throws. - //! - //! Complexity: Linear - //! - //! Note: non-standard extension. - template - void swap(vector & x) - { - this->m_holder.swap(x.m_holder); - } - - #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED - - //! Effects: Erases all the elements of the vector. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements in the vector. - void clear() BOOST_CONTAINER_NOEXCEPT - { this->priv_destroy_all(); } - - /// @cond - - //Absolutely experimental. This function might change, disappear or simply crash! - template - void insert_ordered_at(size_type element_count, BiDirPosConstIt last_position_it, BiDirValueIt last_value_it) - { - const size_type *dummy = 0; - this->priv_insert_ordered_at(element_count, last_position_it, false, &dummy[0], last_value_it); - } - - //Absolutely experimental. This function might change, disappear or simply crash! - template - void insert_ordered_at(size_type element_count, BiDirPosConstIt last_position_it, BiDirSkipConstIt last_skip_it, BiDirValueIt last_value_it) - { - this->priv_insert_ordered_at(element_count, last_position_it, true, last_skip_it, last_value_it); - } - - private: - - template - void priv_move_assign(BOOST_RV_REF_BEG vector BOOST_RV_REF_END x - , AllocVersion - , typename container_detail::enable_if_c - < container_detail::is_same::value && - !container_detail::is_same::value - >::type * = 0) - { - if(this->capacity() < x.size()){ - throw_bad_alloc(); - } - this->priv_move_assign_impl(boost::move(x), AllocVersion()); - } - - template - void priv_move_assign(BOOST_RV_REF_BEG vector BOOST_RV_REF_END x - , AllocVersion - , typename container_detail::enable_if_c - < !container_detail::is_same::value || - container_detail::is_same::value - >::type * = 0) - { - this->priv_move_assign_impl(boost::move(x), AllocVersion()); - } - - template - void priv_move_assign_impl(BOOST_RV_REF_BEG vector BOOST_RV_REF_END x - , AllocVersion - , typename container_detail::enable_if_c - < container_detail::is_same::value - >::type * = 0) - { - T* const this_start = container_detail::to_raw_pointer(m_holder.start()); - T* const other_start = container_detail::to_raw_pointer(x.m_holder.start()); - const size_type this_sz = m_holder.m_size; - const size_type other_sz = static_cast(x.m_holder.m_size); - boost::container::move_assign_range_alloc_n(this->m_holder.alloc(), other_start, other_sz, this_start, this_sz); - this->m_holder.m_size = other_sz; - } - - template - void priv_move_assign_impl(BOOST_RV_REF_BEG vector BOOST_RV_REF_END x - , AllocVersion - , typename container_detail::enable_if_c - < !container_detail::is_same::value - >::type * = 0) - { - //for move constructor, no aliasing (&x != this) is assummed. - allocator_type &this_alloc = this->m_holder.alloc(); - allocator_type &x_alloc = x.m_holder.alloc(); - //If allocators are equal we can just swap pointers - if(this_alloc == x_alloc){ - //Destroy objects but retain memory in case x reuses it in the future - this->clear(); - this->m_holder.swap(x.m_holder); - //Move allocator if needed - container_detail::bool_ flag; - container_detail::move_alloc(this_alloc, x_alloc, flag); - } - //If unequal allocators, then do a one by one move - else{ - //TO-DO: optimize this - this->assign( boost::make_move_iterator(container_detail::to_raw_pointer(x.m_holder.start())) - , boost::make_move_iterator(container_detail::to_raw_pointer(x.m_holder.start() + x.m_holder.m_size))); - } - } - - template - void priv_copy_assign(const vector &x, AllocVersion - , typename container_detail::enable_if_c - < container_detail::is_same::value - >::type * = 0) - { - T* const this_start = container_detail::to_raw_pointer(m_holder.start()); - T* const other_start = container_detail::to_raw_pointer(x.m_holder.start()); - const size_type this_sz = m_holder.m_size; - const size_type other_sz = static_cast(x.m_holder.m_size); - boost::container::copy_assign_range_alloc_n(this->m_holder.alloc(), other_start, other_sz, this_start, this_sz); - this->m_holder.m_size = other_sz; - } - - template - void priv_copy_assign(const vector &x, AllocVersion - , typename container_detail::enable_if_c - < !container_detail::is_same::value - >::type * = 0) - { - allocator_type &this_alloc = this->m_holder.alloc(); - const allocator_type &x_alloc = x.m_holder.alloc(); - container_detail::bool_ flag; - if(flag && this_alloc != x_alloc){ - this->clear(); - this->shrink_to_fit(); - } - container_detail::assign_alloc(this_alloc, x_alloc, flag); - this->assign( container_detail::to_raw_pointer(x.m_holder.start()) - , container_detail::to_raw_pointer(x.m_holder.start() + x.m_holder.m_size)); - } - - void priv_reserve(size_type, allocator_v0) - { - throw_bad_alloc(); - } - - void priv_reserve(size_type new_cap, allocator_v1) - { - //There is not enough memory, allocate a new buffer - pointer p = this->m_holder.allocate(new_cap); - //Backwards (and possibly forward) expansion - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_alloc; - #endif - T * const raw_beg = container_detail::to_raw_pointer(this->m_holder.start()); - const size_type sz = m_holder.m_size; - ::boost::container::uninitialized_move_alloc_n_source - ( this->m_holder.alloc(), raw_beg, sz, container_detail::to_raw_pointer(p) ); - if(this->m_holder.capacity()){ - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->m_holder.alloc(), raw_beg, sz); - this->m_holder.deallocate(this->m_holder.start(), this->m_holder.capacity()); - } - this->m_holder.start(p); - this->m_holder.capacity(new_cap); - } - - void priv_reserve(size_type new_cap, allocator_v2) - { - //There is not enough memory, allocate a new - //buffer or expand the old one. - bool same_buffer_start; - size_type real_cap = 0; - std::pair ret = - this->m_holder.allocation_command - (allocate_new | expand_fwd | expand_bwd, - new_cap, new_cap, real_cap, this->m_holder.start()); - - //Check for forward expansion - same_buffer_start = ret.second && this->m_holder.start() == ret.first; - if(same_buffer_start){ - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_expand_fwd; - #endif - this->m_holder.capacity(real_cap); - } - //If there is no forward expansion, move objects - else{ - //Backwards (and possibly forward) expansion - if(ret.second){ - //We will reuse insert code, so create a dummy input iterator - container_detail::insert_range_proxy, T*> - proxy(this->m_holder.alloc(), ::boost::make_move_iterator((T *)0)); - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_expand_bwd; - #endif - this->priv_forward_range_insert_expand_backwards - ( container_detail::to_raw_pointer(ret.first) - , real_cap - , container_detail::to_raw_pointer(this->m_holder.start()) - , 0 - , proxy); - } - //New buffer - else{ - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_alloc; - #endif - T * const raw_beg = container_detail::to_raw_pointer(this->m_holder.start()); - const size_type sz = m_holder.m_size; - ::boost::container::uninitialized_move_alloc_n_source - ( this->m_holder.alloc(), raw_beg, sz, container_detail::to_raw_pointer(ret.first) ); - if(this->m_holder.capacity()){ - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->m_holder.alloc(), raw_beg, sz); - this->m_holder.deallocate(this->m_holder.start(), this->m_holder.capacity()); - } - this->m_holder.start(ret.first); - this->m_holder.capacity(real_cap); - } - } - } - - template - void priv_uninitialized_fill(Proxy proxy, size_type n) const - { - //Copy first new elements in pos - proxy.uninitialized_copy_n_and_update - (container_detail::to_raw_pointer(this->m_holder.start()), n); - //m_holder.size was already initialized to n in vector_alloc_holder's constructor - } - - void priv_destroy(value_type* p) BOOST_CONTAINER_NOEXCEPT - { - if(!value_traits::trivial_dctr) - allocator_traits_type::destroy(this->get_stored_allocator(), p); - } - - void priv_destroy_last_n(size_type n) BOOST_CONTAINER_NOEXCEPT - { - T* const end_pos = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - boost::container::destroy_alloc_n(this->get_stored_allocator(), end_pos-n, n); - this->m_holder.m_size -= n; - } - - void priv_destroy_all() BOOST_CONTAINER_NOEXCEPT - { - boost::container::destroy_alloc_n - (this->get_stored_allocator(), container_detail::to_raw_pointer(this->m_holder.start()), this->m_holder.m_size); - this->m_holder.m_size = 0; - } - - template - iterator priv_insert(const const_iterator &p, BOOST_FWD_REF(U) x) - { - return this->priv_forward_range_insert - ( vector_iterator_get_ptr(p), 1, container_detail::get_insert_value_proxy(this->m_holder.alloc() - , ::boost::forward(x)), alloc_version()); - } - - void priv_push_back(const T &x) - { - if (this->m_holder.m_size < this->m_holder.capacity()){ - //There is more memory, just construct a new object at the end - allocator_traits_type::construct - ( this->m_holder.alloc() - , container_detail::to_raw_pointer(this->m_holder.start() + this->m_holder.m_size) - , x ); - ++this->m_holder.m_size; - } - else{ - container_detail::insert_copy_proxy proxy(this->m_holder.alloc(), x); - this->priv_forward_range_insert_no_capacity(vector_iterator_get_ptr(this->cend()), 1, proxy, alloc_version()); - } - } - - void priv_push_back(BOOST_RV_REF(T) x) - { - if (this->m_holder.m_size < this->m_holder.capacity()){ - //There is more memory, just construct a new object at the end - allocator_traits_type::construct - ( this->m_holder.alloc() - , container_detail::to_raw_pointer(this->m_holder.start() + this->m_holder.m_size) - , ::boost::move(x) ); - ++this->m_holder.m_size; - } - else{ - container_detail::insert_move_proxy proxy(this->m_holder.alloc(), x); - this->priv_forward_range_insert_no_capacity(vector_iterator_get_ptr(this->cend()), 1, proxy, alloc_version()); - } - } - - void priv_shrink_to_fit(allocator_v0) BOOST_CONTAINER_NOEXCEPT - {} - - void priv_shrink_to_fit(allocator_v1) - { - const size_type cp = this->m_holder.capacity(); - if(cp){ - const size_type sz = this->size(); - if(!sz){ - this->m_holder.alloc().deallocate(this->m_holder.m_start, cp); - this->m_holder.m_start = pointer(); - this->m_holder.m_capacity = 0; - } - else if(sz < cp){ - //Allocate a new buffer. - pointer p = this->m_holder.allocate(sz); - - //We will reuse insert code, so create a dummy input iterator - container_detail::insert_range_proxy, T*> - proxy(this->m_holder.alloc(), ::boost::make_move_iterator((T *)0)); - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_alloc; - #endif - this->priv_forward_range_insert_new_allocation - ( container_detail::to_raw_pointer(p) - , sz - , container_detail::to_raw_pointer(this->m_holder.start()) - , 0 - , proxy); - } - } - } - - void priv_shrink_to_fit(allocator_v2) BOOST_CONTAINER_NOEXCEPT - { - const size_type cp = this->m_holder.capacity(); - if(cp){ - const size_type sz = this->size(); - if(!sz){ - this->m_holder.alloc().deallocate(this->m_holder.m_start, cp); - this->m_holder.m_start = pointer(); - this->m_holder.m_capacity = 0; - } - else{ - size_type received_size; - if(this->m_holder.allocation_command - ( shrink_in_place | nothrow_allocation - , cp, sz, received_size, this->m_holder.start()).first){ - this->m_holder.capacity(received_size); - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_shrink; - #endif - } - } - } - } - - template - iterator priv_forward_range_insert_no_capacity - (const pointer &pos, const size_type, const InsertionProxy , allocator_v0) - { - throw_bad_alloc(); - return iterator(pos); - } - - template - iterator priv_forward_range_insert_no_capacity - (const pointer &pos, const size_type n, const InsertionProxy insert_range_proxy, allocator_v1) - { - //Check if we have enough memory or try to expand current memory - const size_type n_pos = pos - this->m_holder.start(); - T *const raw_pos = container_detail::to_raw_pointer(pos); - - const size_type new_cap = this->m_holder.next_capacity(n); - T * new_buf = container_detail::to_raw_pointer(this->m_holder.alloc().allocate(new_cap)); - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_alloc; - #endif - this->priv_forward_range_insert_new_allocation - ( new_buf, new_cap, raw_pos, n, insert_range_proxy); - return iterator(this->m_holder.start() + n_pos); - } - - - template - iterator priv_forward_range_insert_no_capacity - (const pointer &pos, const size_type n, const InsertionProxy insert_range_proxy, allocator_v2) - { - //Check if we have enough memory or try to expand current memory - T *const raw_pos = container_detail::to_raw_pointer(pos); - const size_type n_pos = raw_pos - container_detail::to_raw_pointer(this->m_holder.start()); - - size_type real_cap = 0; - //There is not enough memory, allocate a new - //buffer or expand the old one. - std::pair ret = (this->m_holder.allocation_command - (allocate_new | expand_fwd | expand_bwd, - this->m_holder.m_size + n, this->m_holder.next_capacity(n), real_cap, this->m_holder.start())); - - //Buffer reallocated - if(ret.second){ - //Forward expansion, delay insertion - if(this->m_holder.start() == ret.first){ - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_expand_fwd; - #endif - this->m_holder.capacity(real_cap); - //Expand forward - this->priv_forward_range_insert_expand_forward(raw_pos, n, insert_range_proxy); - } - //Backwards (and possibly forward) expansion - else{ - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_expand_bwd; - #endif - this->priv_forward_range_insert_expand_backwards - ( container_detail::to_raw_pointer(ret.first) - , real_cap, raw_pos, n, insert_range_proxy); - } - } - //New buffer - else{ - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_alloc; - #endif - this->priv_forward_range_insert_new_allocation - ( container_detail::to_raw_pointer(ret.first) - , real_cap, raw_pos, n, insert_range_proxy); - } - - return iterator(this->m_holder.start() + n_pos); - } - - template - iterator priv_forward_range_insert - (const pointer &pos, const size_type n, const InsertionProxy insert_range_proxy, allocator_v0) - { - //Check if we have enough memory or try to expand current memory - const size_type remaining = this->m_holder.capacity() - this->m_holder.m_size; - - if (n > remaining){ - //This will trigger an error - throw_bad_alloc(); - } - const size_type n_pos = pos - this->m_holder.start(); - T *const raw_pos = container_detail::to_raw_pointer(pos); - this->priv_forward_range_insert_expand_forward(raw_pos, n, insert_range_proxy); - return iterator(this->m_holder.start() + n_pos); - } - - template - iterator priv_forward_range_insert - (const pointer &pos, const size_type n, const InsertionProxy insert_range_proxy, allocator_v1) - { - //Check if we have enough memory or try to expand current memory - const size_type remaining = this->m_holder.capacity() - this->m_holder.m_size; - T *const raw_pos = container_detail::to_raw_pointer(pos); - - if (n <= remaining){ - const size_type n_pos = raw_pos - container_detail::to_raw_pointer(this->m_holder.start()); - this->priv_forward_range_insert_expand_forward - (raw_pos, n, insert_range_proxy); - return iterator(this->m_holder.start() + n_pos); - } - else{ - return this->priv_forward_range_insert_no_capacity(pos, n, insert_range_proxy, alloc_version()); - } - } - - template - iterator priv_forward_range_insert - (const pointer &pos, const size_type n, const InsertionProxy insert_range_proxy, allocator_v2) - { - //Check if we have enough memory or try to expand current memory - const size_type remaining = this->m_holder.capacity() - this->m_holder.m_size; - - bool same_buffer_start = n <= remaining; - if (!same_buffer_start){ - return priv_forward_range_insert_no_capacity(pos, n, insert_range_proxy, alloc_version()); - } - else{ - //Expand forward - T *const raw_pos = container_detail::to_raw_pointer(pos); - const size_type n_pos = raw_pos - container_detail::to_raw_pointer(this->m_holder.start()); - this->priv_forward_range_insert_expand_forward(raw_pos, n, insert_range_proxy); - return iterator(this->m_holder.start() + n_pos); - } - } - - template - iterator priv_forward_range_insert_at_end - (const size_type n, const InsertionProxy insert_range_proxy, allocator_v0) - { - //Check if we have enough memory or try to expand current memory - const size_type remaining = this->m_holder.capacity() - this->m_holder.m_size; - - if (n > remaining){ - //This will trigger an error - throw_bad_alloc(); - } - this->priv_forward_range_insert_at_end_expand_forward(n, insert_range_proxy); - return this->end(); - } - - template - iterator priv_forward_range_insert_at_end - (const size_type n, const InsertionProxy insert_range_proxy, allocator_v1) - { - return this->priv_forward_range_insert(vector_iterator_get_ptr(this->cend()), n, insert_range_proxy, allocator_v1()); - } - - template - iterator priv_forward_range_insert_at_end - (const size_type n, const InsertionProxy insert_range_proxy, allocator_v2) - { - return this->priv_forward_range_insert(vector_iterator_get_ptr(this->cend()), n, insert_range_proxy, allocator_v2()); - } - - //Absolutely experimental. This function might change, disappear or simply crash! - template - void priv_insert_ordered_at( size_type element_count, BiDirPosConstIt last_position_it - , bool do_skip, BiDirSkipConstIt last_skip_it, BiDirValueIt last_value_it) - { - const size_type old_size_pos = this->size(); - this->reserve(old_size_pos + element_count); - T* const begin_ptr = container_detail::to_raw_pointer(this->m_holder.start()); - size_type insertions_left = element_count; - size_type next_pos = old_size_pos; - size_type hole_size = element_count; - - //Exception rollback. If any copy throws before the hole is filled, values - //already inserted/copied at the end of the buffer will be destroyed. - typename value_traits::ArrayDestructor past_hole_values_destroyer - (begin_ptr + old_size_pos + element_count, this->m_holder.alloc(), size_type(0u)); - //Loop for each insertion backwards, first moving the elements after the insertion point, - //then inserting the element. - while(insertions_left){ - if(do_skip){ - size_type n = *(--last_skip_it); - std::advance(last_value_it, -difference_type(n)); - } - const size_type pos = static_cast(*(--last_position_it)); - BOOST_ASSERT(pos <= old_size_pos); - //If needed shift the range after the insertion point and the previous insertion point. - //Function will take care if the shift crosses the size() boundary, using copy/move - //or uninitialized copy/move if necessary. - size_type new_hole_size = (pos != next_pos) - ? priv_insert_ordered_at_shift_range(pos, next_pos, this->size(), insertions_left) - : hole_size - ; - if(new_hole_size > 0){ - //The hole was reduced by priv_insert_ordered_at_shift_range so expand exception rollback range backwards - past_hole_values_destroyer.increment_size_backwards(next_pos - pos); - //Insert the new value in the hole - allocator_traits_type::construct(this->m_holder.alloc(), begin_ptr + pos + insertions_left - 1, *(--last_value_it)); - --new_hole_size; - if(new_hole_size == 0){ - //Hole was just filled, disable exception rollback and change vector size - past_hole_values_destroyer.release(); - this->m_holder.m_size += element_count; - } - else{ - //The hole was reduced by the new insertion by one - past_hole_values_destroyer.increment_size_backwards(size_type(1u)); - } - } - else{ - if(hole_size){ - //Hole was just filled by priv_insert_ordered_at_shift_range, disable exception rollback and change vector size - past_hole_values_destroyer.release(); - this->m_holder.m_size += element_count; - } - //Insert the new value in the already constructed range - begin_ptr[pos + insertions_left - 1] = *(--last_value_it); - } - --insertions_left; - hole_size = new_hole_size; - next_pos = pos; - } - } - - //Takes the range pointed by [first_pos, last_pos) and shifts it to the right - //by 'shift_count'. 'limit_pos' marks the end of constructed elements. - // - //Precondition: first_pos <= last_pos <= limit_pos - // - //The shift operation might cross limit_pos so elements to moved beyond limit_pos - //are uninitialized_moved with an allocator. Other elements are moved. - // - //The shift operation might left uninitialized elements after limit_pos - //and the number of uninitialized elements is returned by the function. - // - //Old situation: - // first_pos last_pos old_limit - // | | | - // ____________V_______V__________________V_____________ - //| prefix | range | suffix |raw_mem ~ - //|____________|_______|__________________|_____________~ - // - //New situation in Case Allocator (hole_size == 0): - // range is moved through move assignments - // - // first_pos last_pos limit_pos - // | | | - // ____________V_______V__________________V_____________ - //| prefix' | | | range |suffix'|raw_mem ~ - //|________________+______|___^___|_______|_____________~ - // | | - // |_>_>_>_>_>^ - // - // - //New situation in Case B (hole_size > 0): - // range is moved through uninitialized moves - // - // first_pos last_pos limit_pos - // | | | - // ____________V_______V__________________V________________ - //| prefix' | | | [hole] | range | - //|_______________________________________|________|___^___| - // | | - // |_>_>_>_>_>_>_>_>_>_>_>_>_>_>_>_>_>_^ - // - //New situation in Case C (hole_size == 0): - // range is moved through move assignments and uninitialized moves - // - // first_pos last_pos limit_pos - // | | | - // ____________V_______V__________________V___ - //| prefix' | | | range | - //|___________________________________|___^___| - // | | - // |_>_>_>_>_>_>_>_>_>_>_>^ - size_type priv_insert_ordered_at_shift_range - (size_type first_pos, size_type last_pos, size_type limit_pos, size_type shift_count) - { - BOOST_ASSERT(first_pos <= last_pos); - BOOST_ASSERT(last_pos <= limit_pos); - // - T* const begin_ptr = container_detail::to_raw_pointer(this->m_holder.start()); - T* const first_ptr = begin_ptr + first_pos; - T* const last_ptr = begin_ptr + last_pos; - - size_type hole_size = 0; - //Case Allocator: - if((last_pos + shift_count) <= limit_pos){ - //All move assigned - boost::move_backward(first_ptr, last_ptr, last_ptr + shift_count); - } - //Case B: - else if((first_pos + shift_count) >= limit_pos){ - //All uninitialized_moved - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), first_ptr, last_ptr, first_ptr + shift_count); - hole_size = last_pos + shift_count - limit_pos; - } - //Case C: - else{ - //Some uninitialized_moved - T* const limit_ptr = begin_ptr + limit_pos; - T* const boundary_ptr = limit_ptr - shift_count; - ::boost::container::uninitialized_move_alloc(this->m_holder.alloc(), boundary_ptr, last_ptr, limit_ptr); - //The rest is move assigned - boost::move_backward(first_ptr, boundary_ptr, limit_ptr); - } - return hole_size; - } - - private: - template - void priv_forward_range_insert_at_end_expand_forward(const size_type n, InsertionProxy insert_range_proxy) - { - T* const old_finish = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, n); - this->m_holder.m_size += n; - } - - template - void priv_forward_range_insert_expand_forward(T* const pos, const size_type n, InsertionProxy insert_range_proxy) - { - //n can't be 0, because there is nothing to do in that case - if(!n) return; - //There is enough memory - T* const old_finish = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - const size_type elems_after = old_finish - pos; - - if (!elems_after){ - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, n); - this->m_holder.m_size += n; - } - else if (elems_after >= n){ - //New elements can be just copied. - //Move to uninitialized memory last objects - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), old_finish - n, old_finish, old_finish); - this->m_holder.m_size += n; - //Copy previous to last objects to the initialized end - boost::move_backward(pos, old_finish - n, old_finish); - //Insert new objects in the pos - insert_range_proxy.copy_n_and_update(pos, n); - } - else { - //The new elements don't fit in the [pos, end()) range. - - //Copy old [pos, end()) elements to the uninitialized memory (a gap is created) - ::boost::container::uninitialized_move_alloc(this->m_holder.alloc(), pos, old_finish, pos + n); - BOOST_TRY{ - //Copy first new elements in pos (gap is still there) - insert_range_proxy.copy_n_and_update(pos, elems_after); - //Copy to the beginning of the unallocated zone the last new elements (the gap is closed). - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, n - elems_after); - this->m_holder.m_size += n; - } - BOOST_CATCH(...){ - boost::container::destroy_alloc_n(this->get_stored_allocator(), pos + n, elems_after); - BOOST_RETHROW - } - BOOST_CATCH_END - } - } - - template - void priv_forward_range_insert_new_allocation - (T* const new_start, size_type new_cap, T* const pos, const size_type n, InsertionProxy insert_range_proxy) - { - //n can be zero, if we want to reallocate! - T *new_finish = new_start; - T *old_finish; - //Anti-exception rollbacks - typename value_traits::ArrayDeallocator scoped_alloc(new_start, this->m_holder.alloc(), new_cap); - typename value_traits::ArrayDestructor constructed_values_destroyer(new_start, this->m_holder.alloc(), 0u); - - //Initialize with [begin(), pos) old buffer - //the start of the new buffer - T *old_buffer = container_detail::to_raw_pointer(this->m_holder.start()); - if(old_buffer){ - new_finish = ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), container_detail::to_raw_pointer(this->m_holder.start()), pos, old_finish = new_finish); - constructed_values_destroyer.increment_size(new_finish - old_finish); - } - //Initialize new objects, starting from previous point - insert_range_proxy.uninitialized_copy_n_and_update(old_finish = new_finish, n); - new_finish += n; - constructed_values_destroyer.increment_size(new_finish - old_finish); - //Initialize from the rest of the old buffer, - //starting from previous point - if(old_buffer){ - new_finish = ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), pos, old_buffer + this->m_holder.m_size, new_finish); - //Destroy and deallocate old elements - //If there is allocated memory, destroy and deallocate - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->get_stored_allocator(), old_buffer, this->m_holder.m_size); - this->m_holder.alloc().deallocate(this->m_holder.start(), this->m_holder.capacity()); - } - this->m_holder.start(new_start); - this->m_holder.m_size = new_finish - new_start; - this->m_holder.capacity(new_cap); - //All construction successful, disable rollbacks - constructed_values_destroyer.release(); - scoped_alloc.release(); - } - - template - void priv_forward_range_insert_expand_backwards - (T* const new_start, const size_type new_capacity, - T* const pos, const size_type n, InsertionProxy insert_range_proxy) - { - //n can be zero to just expand capacity - //Backup old data - T* const old_start = container_detail::to_raw_pointer(this->m_holder.start()); - T* const old_finish = old_start + this->m_holder.m_size; - const size_type old_size = this->m_holder.m_size; - - //We can have 8 possibilities: - const size_type elemsbefore = static_cast(pos - old_start); - const size_type s_before = static_cast(old_start - new_start); - const size_type before_plus_new = elemsbefore + n; - - //Update the vector buffer information to a safe state - this->m_holder.start(new_start); - this->m_holder.capacity(new_capacity); - this->m_holder.m_size = 0; - - //If anything goes wrong, this object will destroy - //all the old objects to fulfill previous vector state - typename value_traits::OldArrayDestructor old_values_destroyer(old_start, this->m_holder.alloc(), old_size); - //Check if s_before is big enough to hold the beginning of old data + new data - if(s_before >= before_plus_new){ - //Copy first old values before pos, after that the new objects - T *const new_elem_pos = ::boost::container::uninitialized_move_alloc(this->m_holder.alloc(), old_start, pos, new_start); - this->m_holder.m_size = elemsbefore; - insert_range_proxy.uninitialized_copy_n_and_update(new_elem_pos, n); - this->m_holder.m_size += n; - //Check if s_before is so big that even copying the old data + new data - //there is a gap between the new data and the old data - const size_type new_size = old_size + n; - if(s_before >= new_size){ - //Old situation: - // _________________________________________________________ - //| raw_mem | old_begin | old_end | - //| __________________________________|___________|_________| - // - //New situation: - // _________________________________________________________ - //| old_begin | new | old_end | raw_mem | - //|___________|__________|_________|________________________| - // - //Now initialize the rest of memory with the last old values - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), pos, old_finish, new_start + before_plus_new); - //All new elements correctly constructed, avoid new element destruction - this->m_holder.m_size = new_size; - //Old values destroyed automatically with "old_values_destroyer" - //when "old_values_destroyer" goes out of scope unless the have trivial - //destructor after move. - if(value_traits::trivial_dctr_after_move) - old_values_destroyer.release(); - } - //s_before is so big that divides old_end - else{ - //Old situation: - // __________________________________________________ - //| raw_mem | old_begin | old_end | - //| ___________________________|___________|_________| - // - //New situation: - // __________________________________________________ - //| old_begin | new | old_end | raw_mem | - //|___________|__________|_________|_________________| - // - //Now initialize the rest of memory with the last old values - //All new elements correctly constructed, avoid new element destruction - const size_type raw_gap = s_before - before_plus_new; - //Now initialize the rest of s_before memory with the - //first of elements after new values - ::boost::container::uninitialized_move_alloc_n - (this->m_holder.alloc(), pos, raw_gap, new_start + before_plus_new); - //Update size since we have a contiguous buffer - this->m_holder.m_size = old_size + s_before; - //All new elements correctly constructed, avoid old element destruction - old_values_destroyer.release(); - //Now copy remaining last objects in the old buffer begin - T * const to_destroy = ::boost::move(pos + raw_gap, old_finish, old_start); - //Now destroy redundant elements except if they were moved and - //they have trivial destructor after move - size_type n_destroy = old_finish - to_destroy; - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->get_stored_allocator(), to_destroy, n_destroy); - this->m_holder.m_size -= n_destroy; - } - } - else{ - //Check if we have to do the insertion in two phases - //since maybe s_before is not big enough and - //the buffer was expanded both sides - // - //Old situation: - // _________________________________________________ - //| raw_mem | old_begin + old_end | raw_mem | - //|_________|_____________________|_________________| - // - //New situation with do_after: - // _________________________________________________ - //| old_begin + new + old_end | raw_mem | - //|___________________________________|_____________| - // - //New without do_after: - // _________________________________________________ - //| old_begin + new + old_end | raw_mem | - //|____________________________|____________________| - // - const bool do_after = n > s_before; - - //Now we can have two situations: the raw_mem of the - //beginning divides the old_begin, or the new elements: - if (s_before <= elemsbefore) { - //The raw memory divides the old_begin group: - // - //If we need two phase construction (do_after) - //new group is divided in new = new_beg + new_end groups - //In this phase only new_beg will be inserted - // - //Old situation: - // _________________________________________________ - //| raw_mem | old_begin | old_end | raw_mem | - //|_________|___________|_________|_________________| - // - //New situation with do_after(1): - //This is not definitive situation, the second phase - //will include - // _________________________________________________ - //| old_begin | new_beg | old_end | raw_mem | - //|___________|_________|_________|_________________| - // - //New situation without do_after: - // _________________________________________________ - //| old_begin | new | old_end | raw_mem | - //|___________|_____|_________|_____________________| - // - //Copy the first part of old_begin to raw_mem - ::boost::container::uninitialized_move_alloc_n - (this->m_holder.alloc(), old_start, s_before, new_start); - //The buffer is all constructed until old_end, - //release destroyer and update size - old_values_destroyer.release(); - this->m_holder.m_size = old_size + s_before; - //Now copy the second part of old_begin overwriting itself - T *const next = ::boost::move(old_start + s_before, pos, old_start); - if(do_after){ - //Now copy the new_beg elements - insert_range_proxy.copy_n_and_update(next, s_before); - } - else{ - //Now copy the all the new elements - insert_range_proxy.copy_n_and_update(next, n); - //Now displace old_end elements - T* const move_end = ::boost::move(pos, old_finish, next + n); - //Destroy remaining moved elements from old_end except if - //they have trivial destructor after being moved - const size_type n_destroy = s_before - n; - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->get_stored_allocator(), move_end, n_destroy); - this->m_holder.m_size -= n_destroy; - } - } - else { - //If we have to expand both sides, - //we will play if the first new values so - //calculate the upper bound of new values - - //The raw memory divides the new elements - // - //If we need two phase construction (do_after) - //new group is divided in new = new_beg + new_end groups - //In this phase only new_beg will be inserted - // - //Old situation: - // _______________________________________________________ - //| raw_mem | old_begin | old_end | raw_mem | - //|_______________|___________|_________|_________________| - // - //New situation with do_after(): - // ____________________________________________________ - //| old_begin | new_beg | old_end | raw_mem | - //|___________|_______________|_________|______________| - // - //New situation without do_after: - // ______________________________________________________ - //| old_begin | new | old_end | raw_mem | - //|___________|_____|_________|__________________________| - // - //First copy whole old_begin and part of new to raw_mem - T * const new_pos = ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), old_start, pos, new_start); - this->m_holder.m_size = elemsbefore; - const size_type mid_n = s_before - elemsbefore; - insert_range_proxy.uninitialized_copy_n_and_update(new_pos, mid_n); - //The buffer is all constructed until old_end, - //release destroyer - this->m_holder.m_size = old_size + s_before; - old_values_destroyer.release(); - - if(do_after){ - //Copy new_beg part - insert_range_proxy.copy_n_and_update(old_start, elemsbefore); - } - else{ - //Copy all new elements - const size_type rest_new = n - mid_n; - insert_range_proxy.copy_n_and_update(old_start, rest_new); - T* move_start = old_start + rest_new; - //Displace old_end - T* move_end = ::boost::move(pos, old_finish, move_start); - //Destroy remaining moved elements from old_end except if they - //have trivial destructor after being moved - size_type n_destroy = s_before - n; - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->get_stored_allocator(), move_end, n_destroy); - this->m_holder.m_size -= n_destroy; - } - } - - //This is only executed if two phase construction is needed - if(do_after){ - //The raw memory divides the new elements - // - //Old situation: - // ______________________________________________________ - //| raw_mem | old_begin | old_end | raw_mem | - //|______________|___________|____________|______________| - // - //New situation with do_after(1): - // _______________________________________________________ - //| old_begin + new_beg | new_end |old_end | raw_mem | - //|__________________________|_________|________|_________| - // - //New situation with do_after(2): - // ______________________________________________________ - //| old_begin + new | old_end |raw | - //|_______________________________________|_________|____| - // - const size_type n_after = n - s_before; - const size_type elemsafter = old_size - elemsbefore; - - //We can have two situations: - if (elemsafter >= n_after){ - //The raw_mem from end will divide displaced old_end - // - //Old situation: - // ______________________________________________________ - //| raw_mem | old_begin | old_end | raw_mem | - //|______________|___________|____________|______________| - // - //New situation with do_after(1): - // _______________________________________________________ - //| old_begin + new_beg | new_end |old_end | raw_mem | - //|__________________________|_________|________|_________| - // - //First copy the part of old_end raw_mem - T* finish_n = old_finish - n_after; - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), finish_n, old_finish, old_finish); - this->m_holder.m_size += n_after; - //Displace the rest of old_end to the new position - boost::move_backward(pos, finish_n, old_finish); - //Now overwrite with new_end - //The new_end part is [first + (n - n_after), last) - insert_range_proxy.copy_n_and_update(pos, n_after); - } - else { - //The raw_mem from end will divide new_end part - // - //Old situation: - // _____________________________________________________________ - //| raw_mem | old_begin | old_end | raw_mem | - //|______________|___________|____________|_____________________| - // - //New situation with do_after(2): - // _____________________________________________________________ - //| old_begin + new_beg | new_end |old_end | raw_mem | - //|__________________________|_______________|________|_________| - // - - const size_type mid_last_dist = n_after - elemsafter; - //First initialize data in raw memory - - //Copy to the old_end part to the uninitialized zone leaving a gap. - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), pos, old_finish, old_finish + mid_last_dist); - - BOOST_TRY{ - //Copy the first part to the already constructed old_end zone - insert_range_proxy.copy_n_and_update(pos, elemsafter); - //Copy the rest to the uninitialized zone filling the gap - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, mid_last_dist); - this->m_holder.m_size += n_after; - } - BOOST_CATCH(...){ - boost::container::destroy_alloc_n(this->get_stored_allocator(), pos, mid_last_dist); - BOOST_RETHROW - } - BOOST_CATCH_END -/* - size_type mid_last_dist = n_after - elemsafter; - //First initialize data in raw memory - - //The new_end part is [first + (n - n_after), last) - insert_range_proxy.uninitialized_copy_last_and_update(old_finish, elemsafter); - this->m_holder.m_size += mid_last_dist; - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), pos, old_finish, old_finish + mid_last_dist); - this->m_holder.m_size += n_after - mid_last_dist; - //Now copy the part of new_end over constructed elements - insert_range_proxy.copy_remaining_to(pos);*/ - } - } - } - } - - void priv_check_range(size_type n) const - { - //If n is out of range, throw an out_of_range exception - if (n >= this->size()){ - throw_out_of_range("vector::at out of range"); - } - } - - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - public: - unsigned int num_expand_fwd; - unsigned int num_expand_bwd; - unsigned int num_shrink; - unsigned int num_alloc; - void reset_alloc_stats() - { num_expand_fwd = num_expand_bwd = num_alloc = 0, num_shrink = 0; } - #endif - /// @endcond -}; - -template -inline bool -operator==(const vector& x, const vector& y) -{ - //Check first size and each element if needed - return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator!=(const vector& x, const vector& y) -{ - //Check first size and each element if needed - return x.size() != y.size() || !std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator<(const vector& x, const vector& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); -} - -template -inline void swap(vector& x, vector& y) -{ x.swap(y); } - -}} - -/// @cond - -namespace boost { - - -//!has_trivial_destructor_after_move<> == true_type -//!specialization for optimizations -template -struct has_trivial_destructor_after_move > - : public ::boost::has_trivial_destructor_after_move -{}; - - -} - -//#define BOOST_CONTAINER_PUT_SWAP_OVERLOAD_IN_NAMESPACE_STD - -#ifdef BOOST_CONTAINER_PUT_SWAP_OVERLOAD_IN_NAMESPACE_STD - -namespace std { - -template -inline void swap(boost::container::vector& x, boost::container::vector& y) -{ x.swap(y); } - -} //namespace std { - -#endif - -/// @endcond - -#include - -#endif // #ifndef BOOST_CONTAINER_CONTAINER_VECTOR_HPP - diff --git a/utils/boost_idb/boost/crc.hpp b/utils/boost_idb/boost/crc.hpp new file mode 100644 index 00000000..6be5aa1d --- /dev/null +++ b/utils/boost_idb/boost/crc.hpp @@ -0,0 +1,1110 @@ +// Boost CRC library crc.hpp header file -----------------------------------// + +// Copyright 2001, 2004 Daryle Walker. Use, modification, and distribution are +// subject to the Boost Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or a copy at .) + +// See for the library's home page. + +#ifndef BOOST_CRC_HPP +#define BOOST_CRC_HPP + +#include // for BOOST_STATIC_CONSTANT, etc. +#include // for boost::uint_t + +#include // for CHAR_BIT, etc. +#include // for std::size_t + +#include // for std::numeric_limits + + +// The type of CRC parameters that can go in a template should be related +// on the CRC's bit count. This macro expresses that type in a compact +// form, but also allows an alternate type for compilers that don't support +// dependent types (in template value-parameters). +#if !(defined(BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS) || (defined(BOOST_MSVC) && (BOOST_MSVC <= 1300))) +#define BOOST_CRC_PARM_TYPE typename ::boost::uint_t::fast +#else +#define BOOST_CRC_PARM_TYPE unsigned long +#endif + +// Some compilers [MS VC++ 6] cannot correctly set up several versions of a +// function template unless every template argument can be unambiguously +// deduced from the function arguments. (The bug is hidden if only one version +// is needed.) Since all of the CRC function templates have this problem, the +// workaround is to make up a dummy function argument that encodes the template +// arguments. Calls to such template functions need all their template +// arguments explicitly specified. At least one compiler that needs this +// workaround also needs the default value for the dummy argument to be +// specified in the definition. +#if defined(__GNUC__) || !defined(BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS) +#define BOOST_CRC_DUMMY_PARM_TYPE +#define BOOST_CRC_DUMMY_INIT +#define BOOST_ACRC_DUMMY_PARM_TYPE +#define BOOST_ACRC_DUMMY_INIT +#else +namespace boost { namespace detail { + template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > + struct dummy_crc_argument { }; +} } +#define BOOST_CRC_DUMMY_PARM_TYPE , detail::dummy_crc_argument *p_ +#define BOOST_CRC_DUMMY_INIT BOOST_CRC_DUMMY_PARM_TYPE = 0 +#define BOOST_ACRC_DUMMY_PARM_TYPE , detail::dummy_crc_argument *p_ +#define BOOST_ACRC_DUMMY_INIT BOOST_ACRC_DUMMY_PARM_TYPE = 0 +#endif + + +namespace boost +{ + + +// Forward declarations ----------------------------------------------------// + +template < std::size_t Bits > + class crc_basic; + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly = 0u, + BOOST_CRC_PARM_TYPE InitRem = 0u, + BOOST_CRC_PARM_TYPE FinalXor = 0u, bool ReflectIn = false, + bool ReflectRem = false > + class crc_optimal; + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > + typename uint_t::fast crc( void const *buffer, + std::size_t byte_count + BOOST_CRC_DUMMY_PARM_TYPE ); + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly > + typename uint_t::fast augmented_crc( void const *buffer, + std::size_t byte_count, typename uint_t::fast initial_remainder + BOOST_ACRC_DUMMY_PARM_TYPE ); + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly > + typename uint_t::fast augmented_crc( void const *buffer, + std::size_t byte_count + BOOST_ACRC_DUMMY_PARM_TYPE ); + +typedef crc_optimal<16, 0x8005, 0, 0, true, true> crc_16_type; +typedef crc_optimal<16, 0x1021, 0xFFFF, 0, false, false> crc_ccitt_type; +typedef crc_optimal<16, 0x8408, 0, 0, true, true> crc_xmodem_type; + +typedef crc_optimal<32, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true> + crc_32_type; + + +// Forward declarations for implementation detail stuff --------------------// +// (Just for the stuff that will be needed for the next two sections) + +namespace detail +{ + template < std::size_t Bits > + struct mask_uint_t; + + template < > + struct mask_uint_t< std::numeric_limits::digits >; + + #if USHRT_MAX > UCHAR_MAX + template < > + struct mask_uint_t< std::numeric_limits::digits >; + #endif + + #if UINT_MAX > USHRT_MAX + template < > + struct mask_uint_t< std::numeric_limits::digits >; + #endif + + #if ULONG_MAX > UINT_MAX + template < > + struct mask_uint_t< std::numeric_limits::digits >; + #endif + + template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, bool Reflect > + struct crc_table_t; + + template < std::size_t Bits, bool DoReflect > + class crc_helper; + + #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION + template < std::size_t Bits > + class crc_helper< Bits, false >; + #endif + +} // namespace detail + + +// Simple cyclic redundancy code (CRC) class declaration -------------------// + +template < std::size_t Bits > +class crc_basic +{ + // Implementation type + typedef detail::mask_uint_t masking_type; + +public: + // Type + typedef typename masking_type::least value_type; + + // Constant for the template parameter + BOOST_STATIC_CONSTANT( std::size_t, bit_count = Bits ); + + // Constructor + explicit crc_basic( value_type truncated_polynominal, + value_type initial_remainder = 0, value_type final_xor_value = 0, + bool reflect_input = false, bool reflect_remainder = false ); + + // Internal Operations + value_type get_truncated_polynominal() const; + value_type get_initial_remainder() const; + value_type get_final_xor_value() const; + bool get_reflect_input() const; + bool get_reflect_remainder() const; + + value_type get_interim_remainder() const; + void reset( value_type new_rem ); + void reset(); + + // External Operations + void process_bit( bool bit ); + void process_bits( unsigned char bits, std::size_t bit_count ); + void process_byte( unsigned char byte ); + void process_block( void const *bytes_begin, void const *bytes_end ); + void process_bytes( void const *buffer, std::size_t byte_count ); + + value_type checksum() const; + +private: + // Member data + value_type rem_; + value_type poly_, init_, final_; // non-const to allow assignability + bool rft_in_, rft_out_; // non-const to allow assignability + +}; // boost::crc_basic + + +// Optimized cyclic redundancy code (CRC) class declaration ----------------// + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +class crc_optimal +{ + // Implementation type + typedef detail::mask_uint_t masking_type; + +public: + // Type + typedef typename masking_type::fast value_type; + + // Constants for the template parameters + BOOST_STATIC_CONSTANT( std::size_t, bit_count = Bits ); + BOOST_STATIC_CONSTANT( value_type, truncated_polynominal = TruncPoly ); + BOOST_STATIC_CONSTANT( value_type, initial_remainder = InitRem ); + BOOST_STATIC_CONSTANT( value_type, final_xor_value = FinalXor ); + BOOST_STATIC_CONSTANT( bool, reflect_input = ReflectIn ); + BOOST_STATIC_CONSTANT( bool, reflect_remainder = ReflectRem ); + + // Constructor + explicit crc_optimal( value_type init_rem = InitRem ); + + // Internal Operations + value_type get_truncated_polynominal() const; + value_type get_initial_remainder() const; + value_type get_final_xor_value() const; + bool get_reflect_input() const; + bool get_reflect_remainder() const; + + value_type get_interim_remainder() const; + void reset( value_type new_rem = InitRem ); + + // External Operations + void process_byte( unsigned char byte ); + void process_block( void const *bytes_begin, void const *bytes_end ); + void process_bytes( void const *buffer, std::size_t byte_count ); + + value_type checksum() const; + + // Operators + void operator ()( unsigned char byte ); + value_type operator ()() const; + +private: + // The implementation of output reflection depends on both reflect states. + BOOST_STATIC_CONSTANT( bool, reflect_output = (ReflectRem != ReflectIn) ); + + #ifndef __BORLANDC__ + #define BOOST_CRC_REF_OUT_VAL reflect_output + #else + typedef crc_optimal self_type; + #define BOOST_CRC_REF_OUT_VAL (self_type::reflect_output) + #endif + + // More implementation types + typedef detail::crc_table_t crc_table_type; + typedef detail::crc_helper helper_type; + typedef detail::crc_helper reflect_out_type; + + #undef BOOST_CRC_REF_OUT_VAL + + // Member data + value_type rem_; + +}; // boost::crc_optimal + + +// Implementation detail stuff ---------------------------------------------// + +namespace detail +{ + // Forward declarations for more implementation details + template < std::size_t Bits > + struct high_uint_t; + + template < std::size_t Bits > + struct reflector; + + + // Traits class for mask; given the bit number + // (1-based), get the mask for that bit by itself. + template < std::size_t Bits > + struct high_uint_t + : boost::uint_t< Bits > + { + typedef boost::uint_t base_type; + typedef typename base_type::least least; + typedef typename base_type::fast fast; + +#if defined(__EDG_VERSION__) && __EDG_VERSION__ <= 243 + static const least high_bit = 1ul << ( Bits - 1u ); + static const fast high_bit_fast = 1ul << ( Bits - 1u ); +#else + BOOST_STATIC_CONSTANT( least, high_bit = (least( 1u ) << ( Bits + - 1u )) ); + BOOST_STATIC_CONSTANT( fast, high_bit_fast = (fast( 1u ) << ( Bits + - 1u )) ); +#endif + + }; // boost::detail::high_uint_t + + + // Reflection routine class wrapper + // (since MS VC++ 6 couldn't handle the unwrapped version) + template < std::size_t Bits > + struct reflector + { + typedef typename boost::uint_t::fast value_type; + + static value_type reflect( value_type x ); + + }; // boost::detail::reflector + + // Function that reflects its argument + template < std::size_t Bits > + typename reflector::value_type + reflector::reflect + ( + typename reflector::value_type x + ) + { + value_type reflection = 0; + value_type const one = 1; + + for ( std::size_t i = 0 ; i < Bits ; ++i, x >>= 1 ) + { + if ( x & one ) + { + reflection |= ( one << (Bits - 1u - i) ); + } + } + + return reflection; + } + + + // Traits class for masks; given the bit number (1-based), + // get the mask for that bit and its lower bits. + template < std::size_t Bits > + struct mask_uint_t + : high_uint_t< Bits > + { + typedef high_uint_t base_type; + typedef typename base_type::least least; + typedef typename base_type::fast fast; + + #ifndef __BORLANDC__ + using base_type::high_bit; + using base_type::high_bit_fast; + #else + BOOST_STATIC_CONSTANT( least, high_bit = base_type::high_bit ); + BOOST_STATIC_CONSTANT( fast, high_bit_fast = base_type::high_bit_fast ); + #endif + +#if defined(__EDG_VERSION__) && __EDG_VERSION__ <= 243 + static const least sig_bits = (~( ~( 0ul ) << Bits )) ; +#else + BOOST_STATIC_CONSTANT( least, sig_bits = (~( ~(least( 0u )) << Bits )) ); +#endif +#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 0 && __GNUC_PATCHLEVEL__ == 2 + // Work around a weird bug that ICEs the compiler in build_c_cast + BOOST_STATIC_CONSTANT( fast, sig_bits_fast = static_cast(sig_bits) ); +#else + BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) ); +#endif + }; // boost::detail::mask_uint_t + + template < > + struct mask_uint_t< std::numeric_limits::digits > + : high_uint_t< std::numeric_limits::digits > + { + typedef high_uint_t::digits> + base_type; + typedef base_type::least least; + typedef base_type::fast fast; + + #ifndef __BORLANDC__ + using base_type::high_bit; + using base_type::high_bit_fast; + #else + BOOST_STATIC_CONSTANT( least, high_bit = base_type::high_bit ); + BOOST_STATIC_CONSTANT( fast, high_bit_fast = base_type::high_bit_fast ); + #endif + + BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) ); + BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) ); + + }; // boost::detail::mask_uint_t + + #if USHRT_MAX > UCHAR_MAX + template < > + struct mask_uint_t< std::numeric_limits::digits > + : high_uint_t< std::numeric_limits::digits > + { + typedef high_uint_t::digits> + base_type; + typedef base_type::least least; + typedef base_type::fast fast; + + #ifndef __BORLANDC__ + using base_type::high_bit; + using base_type::high_bit_fast; + #else + BOOST_STATIC_CONSTANT( least, high_bit = base_type::high_bit ); + BOOST_STATIC_CONSTANT( fast, high_bit_fast = base_type::high_bit_fast ); + #endif + + BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) ); + BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) ); + + }; // boost::detail::mask_uint_t + #endif + + #if UINT_MAX > USHRT_MAX + template < > + struct mask_uint_t< std::numeric_limits::digits > + : high_uint_t< std::numeric_limits::digits > + { + typedef high_uint_t::digits> + base_type; + typedef base_type::least least; + typedef base_type::fast fast; + + #ifndef __BORLANDC__ + using base_type::high_bit; + using base_type::high_bit_fast; + #else + BOOST_STATIC_CONSTANT( least, high_bit = base_type::high_bit ); + BOOST_STATIC_CONSTANT( fast, high_bit_fast = base_type::high_bit_fast ); + #endif + + BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) ); + BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) ); + + }; // boost::detail::mask_uint_t + #endif + + #if ULONG_MAX > UINT_MAX + template < > + struct mask_uint_t< std::numeric_limits::digits > + : high_uint_t< std::numeric_limits::digits > + { + typedef high_uint_t::digits> + base_type; + typedef base_type::least least; + typedef base_type::fast fast; + + #ifndef __BORLANDC__ + using base_type::high_bit; + using base_type::high_bit_fast; + #else + BOOST_STATIC_CONSTANT( least, high_bit = base_type::high_bit ); + BOOST_STATIC_CONSTANT( fast, high_bit_fast = base_type::high_bit_fast ); + #endif + + BOOST_STATIC_CONSTANT( least, sig_bits = (~( least(0u) )) ); + BOOST_STATIC_CONSTANT( fast, sig_bits_fast = fast(sig_bits) ); + + }; // boost::detail::mask_uint_t + #endif + + + // CRC table generator + template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, bool Reflect > + struct crc_table_t + { + BOOST_STATIC_CONSTANT( std::size_t, byte_combos = (1ul << CHAR_BIT) ); + + typedef mask_uint_t masking_type; + typedef typename masking_type::fast value_type; +#if defined(__BORLANDC__) && defined(_M_IX86) && (__BORLANDC__ == 0x560) + // for some reason Borland's command line compiler (version 0x560) + // chokes over this unless we do the calculation for it: + typedef value_type table_type[ 0x100 ]; +#elif defined(__GNUC__) + // old versions of GCC (before 4.0.2) choke on using byte_combos + // as a constant expression when compiling with -pedantic. + typedef value_type table_type[1ul << CHAR_BIT]; +#else + typedef value_type table_type[ byte_combos ]; +#endif + + static void init_table(); + + static table_type table_; + + }; // boost::detail::crc_table_t + + // CRC table generator static data member definition + // (Some compilers [Borland C++] require the initializer to be present.) + template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, bool Reflect > + typename crc_table_t::table_type + crc_table_t::table_ + = { 0 }; + + // Populate CRC lookup table + template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, bool Reflect > + void + crc_table_t::init_table + ( + ) + { + // compute table only on the first run + static bool did_init = false; + if ( did_init ) return; + + // factor-out constants to avoid recalculation + value_type const fast_hi_bit = masking_type::high_bit_fast; + unsigned char const byte_hi_bit = 1u << (CHAR_BIT - 1u); + + // loop over every possible dividend value + unsigned char dividend = 0; + do + { + value_type remainder = 0; + + // go through all the dividend's bits + for ( unsigned char mask = byte_hi_bit ; mask ; mask >>= 1 ) + { + // check if divisor fits + if ( dividend & mask ) + { + remainder ^= fast_hi_bit; + } + + // do polynominal division + if ( remainder & fast_hi_bit ) + { + remainder <<= 1; + remainder ^= TruncPoly; + } + else + { + remainder <<= 1; + } + } + + table_[ crc_helper::reflect(dividend) ] + = crc_helper::reflect( remainder ); + } + while ( ++dividend ); + + did_init = true; + } + + #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION + // Align the msb of the remainder to a byte + template < std::size_t Bits, bool RightShift > + class remainder + { + public: + typedef typename uint_t::fast value_type; + + static unsigned char align_msb( value_type rem ) + { return rem >> (Bits - CHAR_BIT); } + }; + + // Specialization for the case that the remainder has less + // bits than a byte: align the remainder msb to the byte msb + template < std::size_t Bits > + class remainder< Bits, false > + { + public: + typedef typename uint_t::fast value_type; + + static unsigned char align_msb( value_type rem ) + { return rem << (CHAR_BIT - Bits); } + }; + #endif + + // CRC helper routines + template < std::size_t Bits, bool DoReflect > + class crc_helper + { + public: + // Type + typedef typename uint_t::fast value_type; + + #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION + // Possibly reflect a remainder + static value_type reflect( value_type x ) + { return detail::reflector::reflect( x ); } + + // Compare a byte to the remainder's highest byte + static unsigned char index( value_type rem, unsigned char x ) + { return x ^ rem; } + + // Shift out the remainder's highest byte + static value_type shift( value_type rem ) + { return rem >> CHAR_BIT; } + #else + // Possibly reflect a remainder + static value_type reflect( value_type x ) + { return DoReflect ? detail::reflector::reflect( x ) : x; } + + // Compare a byte to the remainder's highest byte + static unsigned char index( value_type rem, unsigned char x ) + { return x ^ ( DoReflect ? rem : + ((Bits>CHAR_BIT)?( rem >> (Bits - CHAR_BIT) ) : + ( rem << (CHAR_BIT - Bits) ))); } + + // Shift out the remainder's highest byte + static value_type shift( value_type rem ) + { return DoReflect ? rem >> CHAR_BIT : rem << CHAR_BIT; } + #endif + + }; // boost::detail::crc_helper + + #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION + template < std::size_t Bits > + class crc_helper + { + public: + // Type + typedef typename uint_t::fast value_type; + + // Possibly reflect a remainder + static value_type reflect( value_type x ) + { return x; } + + // Compare a byte to the remainder's highest byte + static unsigned char index( value_type rem, unsigned char x ) + { return x ^ remainderCHAR_BIT)>::align_msb( rem ); } + + // Shift out the remainder's highest byte + static value_type shift( value_type rem ) + { return rem << CHAR_BIT; } + + }; // boost::detail::crc_helper + #endif + + +} // namespace detail + + +// Simple CRC class function definitions -----------------------------------// + +template < std::size_t Bits > +inline +crc_basic::crc_basic +( + typename crc_basic::value_type truncated_polynominal, + typename crc_basic::value_type initial_remainder, // = 0 + typename crc_basic::value_type final_xor_value, // = 0 + bool reflect_input, // = false + bool reflect_remainder // = false +) + : rem_( initial_remainder ), poly_( truncated_polynominal ) + , init_( initial_remainder ), final_( final_xor_value ) + , rft_in_( reflect_input ), rft_out_( reflect_remainder ) +{ +} + +template < std::size_t Bits > +inline +typename crc_basic::value_type +crc_basic::get_truncated_polynominal +( +) const +{ + return poly_; +} + +template < std::size_t Bits > +inline +typename crc_basic::value_type +crc_basic::get_initial_remainder +( +) const +{ + return init_; +} + +template < std::size_t Bits > +inline +typename crc_basic::value_type +crc_basic::get_final_xor_value +( +) const +{ + return final_; +} + +template < std::size_t Bits > +inline +bool +crc_basic::get_reflect_input +( +) const +{ + return rft_in_; +} + +template < std::size_t Bits > +inline +bool +crc_basic::get_reflect_remainder +( +) const +{ + return rft_out_; +} + +template < std::size_t Bits > +inline +typename crc_basic::value_type +crc_basic::get_interim_remainder +( +) const +{ + return rem_ & masking_type::sig_bits; +} + +template < std::size_t Bits > +inline +void +crc_basic::reset +( + typename crc_basic::value_type new_rem +) +{ + rem_ = new_rem; +} + +template < std::size_t Bits > +inline +void +crc_basic::reset +( +) +{ + this->reset( this->get_initial_remainder() ); +} + +template < std::size_t Bits > +inline +void +crc_basic::process_bit +( + bool bit +) +{ + value_type const high_bit_mask = masking_type::high_bit; + + // compare the new bit with the remainder's highest + rem_ ^= ( bit ? high_bit_mask : 0u ); + + // a full polynominal division step is done when the highest bit is one + bool const do_poly_div = static_cast( rem_ & high_bit_mask ); + + // shift out the highest bit + rem_ <<= 1; + + // carry out the division, if needed + if ( do_poly_div ) + { + rem_ ^= poly_; + } +} + +template < std::size_t Bits > +void +crc_basic::process_bits +( + unsigned char bits, + std::size_t bit_count +) +{ + // ignore the bits above the ones we want + bits <<= CHAR_BIT - bit_count; + + // compute the CRC for each bit, starting with the upper ones + unsigned char const high_bit_mask = 1u << ( CHAR_BIT - 1u ); + for ( std::size_t i = bit_count ; i > 0u ; --i, bits <<= 1u ) + { + process_bit( static_cast(bits & high_bit_mask) ); + } +} + +template < std::size_t Bits > +inline +void +crc_basic::process_byte +( + unsigned char byte +) +{ + process_bits( (rft_in_ ? detail::reflector::reflect(byte) + : byte), CHAR_BIT ); +} + +template < std::size_t Bits > +void +crc_basic::process_block +( + void const * bytes_begin, + void const * bytes_end +) +{ + for ( unsigned char const * p + = static_cast(bytes_begin) ; p < bytes_end ; ++p ) + { + process_byte( *p ); + } +} + +template < std::size_t Bits > +inline +void +crc_basic::process_bytes +( + void const * buffer, + std::size_t byte_count +) +{ + unsigned char const * const b = static_cast( + buffer ); + + process_block( b, b + byte_count ); +} + +template < std::size_t Bits > +inline +typename crc_basic::value_type +crc_basic::checksum +( +) const +{ + return ( (rft_out_ ? detail::reflector::reflect( rem_ ) : rem_) + ^ final_ ) & masking_type::sig_bits; +} + + +// Optimized CRC class function definitions --------------------------------// + +// Macro to compact code +#define BOOST_CRC_OPTIMAL_NAME crc_optimal + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +BOOST_CRC_OPTIMAL_NAME::crc_optimal +( + typename BOOST_CRC_OPTIMAL_NAME::value_type init_rem // = InitRem +) + : rem_( helper_type::reflect(init_rem) ) +{ + crc_table_type::init_table(); +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename BOOST_CRC_OPTIMAL_NAME::value_type +BOOST_CRC_OPTIMAL_NAME::get_truncated_polynominal +( +) const +{ + return TruncPoly; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename BOOST_CRC_OPTIMAL_NAME::value_type +BOOST_CRC_OPTIMAL_NAME::get_initial_remainder +( +) const +{ + return InitRem; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename BOOST_CRC_OPTIMAL_NAME::value_type +BOOST_CRC_OPTIMAL_NAME::get_final_xor_value +( +) const +{ + return FinalXor; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +bool +BOOST_CRC_OPTIMAL_NAME::get_reflect_input +( +) const +{ + return ReflectIn; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +bool +BOOST_CRC_OPTIMAL_NAME::get_reflect_remainder +( +) const +{ + return ReflectRem; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename BOOST_CRC_OPTIMAL_NAME::value_type +BOOST_CRC_OPTIMAL_NAME::get_interim_remainder +( +) const +{ + // Interim remainder should be _un_-reflected, so we have to undo it. + return helper_type::reflect( rem_ ) & masking_type::sig_bits_fast; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +void +BOOST_CRC_OPTIMAL_NAME::reset +( + typename BOOST_CRC_OPTIMAL_NAME::value_type new_rem // = InitRem +) +{ + rem_ = helper_type::reflect( new_rem ); +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +void +BOOST_CRC_OPTIMAL_NAME::process_byte +( + unsigned char byte +) +{ + process_bytes( &byte, sizeof(byte) ); +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +void +BOOST_CRC_OPTIMAL_NAME::process_block +( + void const * bytes_begin, + void const * bytes_end +) +{ + // Recompute the CRC for each byte passed + for ( unsigned char const * p + = static_cast(bytes_begin) ; p < bytes_end ; ++p ) + { + // Compare the new byte with the remainder's higher bits to + // get the new bits, shift out the remainder's current higher + // bits, and update the remainder with the polynominal division + // of the new bits. + unsigned char const byte_index = helper_type::index( rem_, *p ); + rem_ = helper_type::shift( rem_ ); + rem_ ^= crc_table_type::table_[ byte_index ]; + } +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +void +BOOST_CRC_OPTIMAL_NAME::process_bytes +( + void const * buffer, + std::size_t byte_count +) +{ + unsigned char const * const b = static_cast( + buffer ); + process_block( b, b + byte_count ); +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename BOOST_CRC_OPTIMAL_NAME::value_type +BOOST_CRC_OPTIMAL_NAME::checksum +( +) const +{ + return ( reflect_out_type::reflect(rem_) ^ get_final_xor_value() ) + & masking_type::sig_bits_fast; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +void +BOOST_CRC_OPTIMAL_NAME::operator () +( + unsigned char byte +) +{ + process_byte( byte ); +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename BOOST_CRC_OPTIMAL_NAME::value_type +BOOST_CRC_OPTIMAL_NAME::operator () +( +) const +{ + return checksum(); +} + + +// CRC computation function definition -------------------------------------// + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly, + BOOST_CRC_PARM_TYPE InitRem, BOOST_CRC_PARM_TYPE FinalXor, + bool ReflectIn, bool ReflectRem > +inline +typename uint_t::fast +crc +( + void const * buffer, + std::size_t byte_count + BOOST_CRC_DUMMY_INIT +) +{ + BOOST_CRC_OPTIMAL_NAME computer; + computer.process_bytes( buffer, byte_count ); + return computer.checksum(); +} + + +// Augmented-message CRC computation function definitions ------------------// + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly > +typename uint_t::fast +augmented_crc +( + void const * buffer, + std::size_t byte_count, + typename uint_t::fast initial_remainder + BOOST_ACRC_DUMMY_INIT +) +{ + typedef unsigned char byte_type; + typedef detail::mask_uint_t masking_type; + typedef detail::crc_table_t crc_table_type; + + typename masking_type::fast rem = initial_remainder; + byte_type const * const b = static_cast( buffer ); + byte_type const * const e = b + byte_count; + + crc_table_type::init_table(); + for ( byte_type const * p = b ; p < e ; ++p ) + { + // Use the current top byte as the table index to the next + // "partial product." Shift out that top byte, shifting in + // the next augmented-message byte. Complete the division. + byte_type const byte_index = rem >> ( Bits - CHAR_BIT ); + rem <<= CHAR_BIT; + rem |= *p; + rem ^= crc_table_type::table_[ byte_index ]; + } + + return rem & masking_type::sig_bits_fast; +} + +template < std::size_t Bits, BOOST_CRC_PARM_TYPE TruncPoly > +inline +typename uint_t::fast +augmented_crc +( + void const * buffer, + std::size_t byte_count + BOOST_ACRC_DUMMY_INIT +) +{ + // The last function argument has its type specified so the other version of + // augmented_crc will be called. If the cast wasn't in place, and the + // BOOST_ACRC_DUMMY_INIT added a third argument (for a workaround), the "0" + // would match as that third argument, leading to infinite recursion. + return augmented_crc( buffer, byte_count, + static_cast::fast>(0) ); +} + + +} // namespace boost + + +// Undo header-private macros +#undef BOOST_CRC_OPTIMAL_NAME +#undef BOOST_ACRC_DUMMY_INIT +#undef BOOST_ACRC_DUMMY_PARM_TYPE +#undef BOOST_CRC_DUMMY_INIT +#undef BOOST_CRC_DUMMY_PARM_TYPE +#undef BOOST_CRC_PARM_TYPE + + +#endif // BOOST_CRC_HPP + diff --git a/utils/boost_idb/boost/cstdint.hpp b/utils/boost_idb/boost/cstdint.hpp index 98faeae0..ea84b650 100644 --- a/utils/boost_idb/boost/cstdint.hpp +++ b/utils/boost_idb/boost/cstdint.hpp @@ -1,8 +1,8 @@ // boost cstdint.hpp header file ------------------------------------------// -// (C) Copyright Beman Dawes 1999. -// (C) Copyright Jens Mauer 2001 -// (C) Copyright John Maddock 2001 +// (C) Copyright Beman Dawes 1999. +// (C) Copyright Jens Mauer 2001 +// (C) Copyright John Maddock 2001 // Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -24,9 +24,9 @@ #define BOOST_CSTDINT_HPP // -// Since we always define the INT#_C macros as per C++0x, +// Since we always define the INT#_C macros as per C++0x, // define __STDC_CONSTANT_MACROS so that does the right -// thing if possible, and so that the user knows that the macros +// thing if possible, and so that the user knows that the macros // are actually defined as per C99. // #ifndef __STDC_CONSTANT_MACROS @@ -41,10 +41,7 @@ // so we disable use of stdint.h when GLIBC does not define __GLIBC_HAVE_LONG_LONG. // See https://svn.boost.org/trac/boost/ticket/3548 and http://sources.redhat.com/bugzilla/show_bug.cgi?id=10990 // -#if defined(BOOST_HAS_STDINT_H) \ - && (!defined(__GLIBC__) \ - || defined(__GLIBC_HAVE_LONG_LONG) \ - || (defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 17))))) +#if defined(BOOST_HAS_STDINT_H) && (!defined(__GLIBC__) || defined(__GLIBC_HAVE_LONG_LONG)) // The following #include is an implementation artifact; not part of interface. # ifdef __hpux @@ -53,7 +50,7 @@ # ifdef __STDC_32_MODE__ // this is triggered with GCC, because it defines __cplusplus < 199707L # define BOOST_NO_INT64_T -# endif +# endif # elif defined(__FreeBSD__) || defined(__IBMCPP__) || defined(_AIX) # include # else @@ -103,40 +100,40 @@ typedef ::uintfast64_t uint_fast64_t; namespace boost { - using ::int8_t; - using ::int_least8_t; - using ::int_fast8_t; - using ::uint8_t; - using ::uint_least8_t; - using ::uint_fast8_t; - - using ::int16_t; - using ::int_least16_t; - using ::int_fast16_t; - using ::uint16_t; - using ::uint_least16_t; - using ::uint_fast16_t; - - using ::int32_t; - using ::int_least32_t; - using ::int_fast32_t; - using ::uint32_t; - using ::uint_least32_t; - using ::uint_fast32_t; - + using ::int8_t; + using ::int_least8_t; + using ::int_fast8_t; + using ::uint8_t; + using ::uint_least8_t; + using ::uint_fast8_t; + + using ::int16_t; + using ::int_least16_t; + using ::int_fast16_t; + using ::uint16_t; + using ::uint_least16_t; + using ::uint_fast16_t; + + using ::int32_t; + using ::int_least32_t; + using ::int_fast32_t; + using ::uint32_t; + using ::uint_least32_t; + using ::uint_fast32_t; + # ifndef BOOST_NO_INT64_T - using ::int64_t; - using ::int_least64_t; - using ::int_fast64_t; - using ::uint64_t; - using ::uint_least64_t; - using ::uint_fast64_t; - + using ::int64_t; + using ::int_least64_t; + using ::int_fast64_t; + using ::uint64_t; + using ::uint_least64_t; + using ::uint_fast64_t; + # endif - using ::intmax_t; - using ::uintmax_t; + using ::intmax_t; + using ::uintmax_t; } // namespace boost @@ -146,35 +143,35 @@ namespace boost namespace boost { - using ::int8_t; - typedef int8_t int_least8_t; - typedef int8_t int_fast8_t; - using ::uint8_t; - typedef uint8_t uint_least8_t; - typedef uint8_t uint_fast8_t; - - using ::int16_t; - typedef int16_t int_least16_t; - typedef int16_t int_fast16_t; - using ::uint16_t; - typedef uint16_t uint_least16_t; - typedef uint16_t uint_fast16_t; - - using ::int32_t; - typedef int32_t int_least32_t; - typedef int32_t int_fast32_t; - using ::uint32_t; - typedef uint32_t uint_least32_t; - typedef uint32_t uint_fast32_t; - -# ifndef BOOST_NO_INT64_T - - using ::int64_t; - typedef int64_t int_least64_t; - typedef int64_t int_fast64_t; - using ::uint64_t; - typedef uint64_t uint_least64_t; - typedef uint64_t uint_fast64_t; + using ::int8_t; + typedef int8_t int_least8_t; + typedef int8_t int_fast8_t; + using ::uint8_t; + typedef uint8_t uint_least8_t; + typedef uint8_t uint_fast8_t; + + using ::int16_t; + typedef int16_t int_least16_t; + typedef int16_t int_fast16_t; + using ::uint16_t; + typedef uint16_t uint_least16_t; + typedef uint16_t uint_fast16_t; + + using ::int32_t; + typedef int32_t int_least32_t; + typedef int32_t int_fast32_t; + using ::uint32_t; + typedef uint32_t uint_least32_t; + typedef uint32_t uint_fast32_t; + +# ifndef BOOST_NO_INT64_T + + using ::int64_t; + typedef int64_t int_least64_t; + typedef int64_t int_fast64_t; + using ::uint64_t; + typedef uint64_t uint_least64_t; + typedef uint64_t uint_fast64_t; typedef int64_t intmax_t; typedef uint64_t uintmax_t; @@ -238,15 +235,15 @@ namespace boost typedef unsigned short uint_least16_t; typedef unsigned short uint_fast16_t; # endif -# elif (USHRT_MAX == 0xffffffff) && defined(__MTA__) - // On MTA / XMT short is 32 bits unless the -short16 compiler flag is specified - // MTA / XMT does support the following non-standard integer types - typedef __short16 int16_t; - typedef __short16 int_least16_t; - typedef __short16 int_fast16_t; - typedef unsigned __short16 uint16_t; - typedef unsigned __short16 uint_least16_t; - typedef unsigned __short16 uint_fast16_t; +# elif (USHRT_MAX == 0xffffffff) && defined(__MTA__) + // On MTA / XMT short is 32 bits unless the -short16 compiler flag is specified + // MTA / XMT does support the following non-standard integer types + typedef __short16 int16_t; + typedef __short16 int_least16_t; + typedef __short16 int_fast16_t; + typedef unsigned __short16 uint16_t; + typedef unsigned __short16 uint_least16_t; + typedef unsigned __short16 uint_fast16_t; # elif (USHRT_MAX == 0xffffffff) && defined(CRAY) // no 16-bit types on Cray: typedef short int_least16_t; @@ -280,14 +277,14 @@ namespace boost typedef unsigned long uint32_t; typedef unsigned long uint_least32_t; typedef unsigned long uint_fast32_t; -# elif (UINT_MAX == 0xffffffffffffffff) && defined(__MTA__) - // Integers are 64 bits on the MTA / XMT - typedef __int32 int32_t; - typedef __int32 int_least32_t; - typedef __int32 int_fast32_t; - typedef unsigned __int32 uint32_t; - typedef unsigned __int32 uint_least32_t; - typedef unsigned __int32 uint_fast32_t; +# elif (UINT_MAX == 0xffffffffffffffff) && defined(__MTA__) + // Integers are 64 bits on the MTA / XMT + typedef __int32 int32_t; + typedef __int32 int_least32_t; + typedef __int32 int_fast32_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int32 uint_fast32_t; # else # error defaults not correct; you must hand modify boost/cstdint.hpp # endif @@ -361,40 +358,6 @@ namespace boost #endif // BOOST_HAS_STDINT_H -// intptr_t/uintptr_t are defined separately because they are optional and not universally available -#if defined(BOOST_WINDOWS) && !defined(_WIN32_WCE) && !defined(BOOST_HAS_STDINT_H) -// Older MSVC don't have stdint.h and have intptr_t/uintptr_t defined in stddef.h -#include -#endif - -// PGI seems to not support intptr_t/uintptr_t properly. BOOST_HAS_STDINT_H is not defined for this compiler by Boost.Config. -#if !defined(__PGIC__) - -#if (defined(BOOST_WINDOWS) && !defined(_WIN32_WCE)) \ - || (defined(_XOPEN_UNIX) && (_XOPEN_UNIX+0 > 0) && !defined(__UCLIBC__)) \ - || defined(__CYGWIN__) \ - || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) \ - || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) - -namespace boost { - using ::intptr_t; - using ::uintptr_t; -} -#define BOOST_HAS_INTPTR_T - -// Clang pretends to be GCC, so it'll match this condition -#elif defined(__GNUC__) && defined(__INTPTR_TYPE__) && defined(__UINTPTR_TYPE__) - -namespace boost { - typedef __INTPTR_TYPE__ intptr_t; - typedef __UINTPTR_TYPE__ uintptr_t; -} -#define BOOST_HAS_INTPTR_T - -#endif - -#endif // !defined(__PGIC__) - #endif // BOOST_CSTDINT_HPP @@ -413,15 +376,15 @@ INT#_C macros if they're not already defined (John Maddock). #if !defined(BOOST__STDC_CONSTANT_MACROS_DEFINED) && \ (!defined(INT8_C) || !defined(INT16_C) || !defined(INT32_C) || !defined(INT64_C)) // -// For the following code we get several warnings along the lines of: -// -// boost/cstdint.hpp:428:35: error: use of C99 long long integer constant +// For the following code we get several warnings along the lines of: +// +// boost/cstdint.hpp:428:35: error: use of C99 long long integer constant +// +// So we declare this a system header to suppress these warnings. // -// So we declare this a system header to suppress these warnings. -// -#if defined(__GNUC__) && (__GNUC__ >= 4) -#pragma GCC system_header -#endif +#if defined(__GNUC__) && (__GNUC__ >= 4) +#pragma GCC system_header +#endif #include # define BOOST__STDC_CONSTANT_MACROS_DEFINED diff --git a/utils/boost_idb/boost/cstdlib.hpp b/utils/boost_idb/boost/cstdlib.hpp new file mode 100644 index 00000000..63221463 --- /dev/null +++ b/utils/boost_idb/boost/cstdlib.hpp @@ -0,0 +1,41 @@ +// boost/cstdlib.hpp header ------------------------------------------------// + +// Copyright Beman Dawes 2001. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// See http://www.boost.org/libs/utility/cstdlib.html for documentation. + +// Revision History +// 26 Feb 01 Initial version (Beman Dawes) + +#ifndef BOOST_CSTDLIB_HPP +#define BOOST_CSTDLIB_HPP + +#include + +namespace boost +{ + // The intent is to propose the following for addition to namespace std + // in the C++ Standard Library, and to then deprecate EXIT_SUCCESS and + // EXIT_FAILURE. As an implementation detail, this header defines the + // new constants in terms of EXIT_SUCCESS and EXIT_FAILURE. In a new + // standard, the constants would be implementation-defined, although it + // might be worthwhile to "suggest" (which a standard is allowed to do) + // values of 0 and 1 respectively. + + // Rationale for having multiple failure values: some environments may + // wish to distinguish between different classes of errors. + // Rationale for choice of values: programs often use values < 100 for + // their own error reporting. Values > 255 are sometimes reserved for + // system detected errors. 200/201 were suggested to minimize conflict. + + const int exit_success = EXIT_SUCCESS; // implementation-defined value + const int exit_failure = EXIT_FAILURE; // implementation-defined value + const int exit_exception_failure = 200; // otherwise uncaught exception + const int exit_test_failure = 201; // report_error or + // report_critical_error called. +} + +#endif + diff --git a/utils/boost_idb/boost/current_function.hpp b/utils/boost_idb/boost/current_function.hpp index cb36e35c..aa5756e0 100644 --- a/utils/boost_idb/boost/current_function.hpp +++ b/utils/boost_idb/boost/current_function.hpp @@ -28,7 +28,7 @@ namespace detail inline void current_function_helper() { -#if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) || defined(__ghs__) +#if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) # define BOOST_CURRENT_FUNCTION __PRETTY_FUNCTION__ @@ -65,4 +65,3 @@ inline void current_function_helper() } // namespace boost #endif // #ifndef BOOST_CURRENT_FUNCTION_HPP_INCLUDED - diff --git a/utils/boost_idb/boost/date_time.hpp b/utils/boost_idb/boost/date_time.hpp index 07715262..c9666222 100644 --- a/utils/boost_idb/boost/date_time.hpp +++ b/utils/boost_idb/boost/date_time.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ // See www.boost.org/libs/date_time for documentation. diff --git a/utils/boost_idb/boost/date_time/adjust_functors.hpp b/utils/boost_idb/boost/date_time/adjust_functors.hpp index dde8ca85..7854ae4b 100644 --- a/utils/boost_idb/boost/date_time/adjust_functors.hpp +++ b/utils/boost_idb/boost/date_time/adjust_functors.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/date.hpp" diff --git a/utils/boost_idb/boost/date_time/c_local_time_adjustor.hpp b/utils/boost_idb/boost/date_time/c_local_time_adjustor.hpp index 45e96d3a..f8025828 100644 --- a/utils/boost_idb/boost/date_time/c_local_time_adjustor.hpp +++ b/utils/boost_idb/boost/date_time/c_local_time_adjustor.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ /*! @file c_local_time_adjustor.hpp diff --git a/utils/boost_idb/boost/date_time/c_time.hpp b/utils/boost_idb/boost/date_time/c_time.hpp index f7e116b2..24ccfe5c 100644 --- a/utils/boost_idb/boost/date_time/c_time.hpp +++ b/utils/boost_idb/boost/date_time/c_time.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 09:04:10 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ @@ -57,15 +57,7 @@ namespace date_time { static std::tm* localtime(const std::time_t* t, std::tm* result) { // localtime_r() not in namespace std??? - #if defined(__VMS) && __INITIAL_POINTER_SIZE == 64 - std::tm tmp; - if(!localtime_r(t,&tmp)) - result = 0; - else - *result = tmp; - #else result = localtime_r(t, result); - #endif if (!result) boost::throw_exception(std::runtime_error("could not convert calendar time to local time")); return result; @@ -75,15 +67,7 @@ namespace date_time { static std::tm* gmtime(const std::time_t* t, std::tm* result) { // gmtime_r() not in namespace std??? - #if defined(__VMS) && __INITIAL_POINTER_SIZE == 64 - std::tm tmp; - if(!gmtime_r(t,&tmp)) - result = 0; - else - *result = tmp; - #else result = gmtime_r(t, result); - #endif if (!result) boost::throw_exception(std::runtime_error("could not convert calendar time to UTC time")); return result; diff --git a/utils/boost_idb/boost/date_time/compiler_config.hpp b/utils/boost_idb/boost/date_time/compiler_config.hpp index 1aa1330f..0dc893f9 100644 --- a/utils/boost_idb/boost/date_time/compiler_config.hpp +++ b/utils/boost_idb/boost/date_time/compiler_config.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2011-07-26 10:40:21 -0700 (Tue, 26 Jul 2011) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include @@ -118,18 +118,20 @@ namespace std { * */ -// we need to import/export our code only if the user has specifically -// asked for it by defining either BOOST_ALL_DYN_LINK if they want all boost -// libraries to be dynamically linked, or BOOST_DATE_TIME_DYN_LINK -// if they want just this one to be dynamically liked: -#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_DATE_TIME_DYN_LINK) - // export if this is our own source, otherwise import: -# ifdef BOOST_DATE_TIME_SOURCE -# define BOOST_DATE_TIME_DECL BOOST_SYMBOL_EXPORT -# else -# define BOOST_DATE_TIME_DECL BOOST_SYMBOL_IMPORT -# endif // BOOST_DATE_TIME_SOURCE -#endif // DYN_LINK +#ifdef BOOST_HAS_DECLSPEC // defined in config system + // we need to import/export our code only if the user has specifically + // asked for it by defining either BOOST_ALL_DYN_LINK if they want all boost + // libraries to be dynamically linked, or BOOST_DATE_TIME_DYN_LINK + // if they want just this one to be dynamically liked: +# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_DATE_TIME_DYN_LINK) + // export if this is our own source, otherwise import: +# ifdef BOOST_DATE_TIME_SOURCE +# define BOOST_DATE_TIME_DECL __declspec(dllexport) +# else +# define BOOST_DATE_TIME_DECL __declspec(dllimport) +# endif // BOOST_DATE_TIME_SOURCE +# endif // DYN_LINK +#endif // BOOST_HAS_DECLSPEC // // if BOOST_WHATEVER_DECL isn't defined yet define it now: #ifndef BOOST_DATE_TIME_DECL diff --git a/utils/boost_idb/boost/date_time/constrained_value.hpp b/utils/boost_idb/boost/date_time/constrained_value.hpp index 7338105e..b273dd5a 100644 --- a/utils/boost_idb/boost/date_time/constrained_value.hpp +++ b/utils/boost_idb/boost/date_time/constrained_value.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/date.hpp b/utils/boost_idb/boost/date_time/date.hpp index f77ae29d..1056fb6a 100644 --- a/utils/boost_idb/boost/date_time/date.hpp +++ b/utils/boost_idb/boost/date_time/date.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #include @@ -191,8 +191,8 @@ namespace date_time { dates. It is not exposed to users since that would require class users to understand the inner workings of the date class. */ - explicit date(date_int_type days) : days_(days) {} - explicit date(date_rep_type days) : days_(days.as_number()) {} + explicit date(date_int_type days) : days_(days) {}; + explicit date(date_rep_type days) : days_(days.as_number()) {}; date_int_type days_; }; diff --git a/utils/boost_idb/boost/date_time/date_clock_device.hpp b/utils/boost_idb/boost/date_time/date_clock_device.hpp index 6202f6c5..6ccb26e2 100644 --- a/utils/boost_idb/boost/date_time/date_clock_device.hpp +++ b/utils/boost_idb/boost/date_time/date_clock_device.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/c_time.hpp" diff --git a/utils/boost_idb/boost/date_time/date_defs.hpp b/utils/boost_idb/boost/date_time/date_defs.hpp index ae7e4c5a..bc25b56c 100644 --- a/utils/boost_idb/boost/date_time/date_defs.hpp +++ b/utils/boost_idb/boost/date_time/date_defs.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/date_duration.hpp b/utils/boost_idb/boost/date_time/date_duration.hpp index c5739445..3871aac0 100644 --- a/utils/boost_idb/boost/date_time/date_duration.hpp +++ b/utils/boost_idb/boost/date_time/date_duration.hpp @@ -2,11 +2,11 @@ #define DATE_TIME_DATE_DURATION__ /* Copyright (c) 2002,2003 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ @@ -26,14 +26,14 @@ namespace date_time { , boost::subtractable1< date_duration< duration_rep_traits > , boost::dividable2< date_duration< duration_rep_traits >, int > > > > > - { + { public: typedef typename duration_rep_traits::int_type duration_rep_type; typedef typename duration_rep_traits::impl_type duration_rep; - + //! Construct from a day count - explicit date_duration(duration_rep day_count) : days_(day_count) {} - + explicit date_duration(duration_rep day_count) : days_(day_count) {}; + /*! construct from special_values - only works when * instantiated with duration_traits_adapted */ date_duration(special_values sv) : @@ -125,7 +125,7 @@ namespace date_time { { typedef long int_type; typedef long impl_type; - static int_type as_number(impl_type i) { return i; } + static int_type as_number(impl_type i) { return i; }; }; /*! Struct for instantiating date_duration WITH special values @@ -135,9 +135,9 @@ namespace date_time { { typedef long int_type; typedef boost::date_time::int_adapter impl_type; - static int_type as_number(impl_type i) { return i.as_number(); } + static int_type as_number(impl_type i) { return i.as_number(); }; }; - + } } //namspace date_time diff --git a/utils/boost_idb/boost/date_time/date_duration_types.hpp b/utils/boost_idb/boost/date_time/date_duration_types.hpp index e44c59ff..1512c0ef 100644 --- a/utils/boost_idb/boost/date_time/date_duration_types.hpp +++ b/utils/boost_idb/boost/date_time/date_duration_types.hpp @@ -6,7 +6,7 @@ * (See accompanying file LICENSE_1_0.txt or * http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/date_facet.hpp b/utils/boost_idb/boost/date_time/date_facet.hpp index fc2ddc24..3eda4c7d 100644 --- a/utils/boost_idb/boost/date_time/date_facet.hpp +++ b/utils/boost_idb/boost/date_time/date_facet.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Martin Andrian, Jeff Garland, Bart Garst - * $Date: 2012-09-30 16:25:22 -0700 (Sun, 30 Sep 2012) $ + * $Date: 2009-06-04 07:40:18 -0400 (Thu, 04 Jun 2009) $ */ #include @@ -208,8 +208,7 @@ namespace boost { namespace date_time { // return do_put_special(next, a_ios, fill_char, d.as_special()); //} //The following line of code required the date to support a to_tm function - std::tm dtm; - std::memset(&dtm, 0, sizeof(dtm)); + std::tm dtm = {}; dtm.tm_mon = m - 1; return do_put_tm(next, a_ios, fill_char, dtm, m_month_format); } @@ -220,8 +219,7 @@ namespace boost { namespace date_time { char_type fill_char, const day_type& day) const { - std::tm dtm; - std::memset(&dtm, 0, sizeof(dtm)); + std::tm dtm = {}; dtm.tm_mday = day.as_number(); char_type tmp[3] = {'%','d'}; string_type temp_format(tmp); @@ -237,8 +235,7 @@ namespace boost { namespace date_time { // return do_put_special(next, a_ios, fill_char, d.as_special()); //} //The following line of code required the date to support a to_tm function - std::tm dtm; - std::memset(&dtm, 0, sizeof(dtm)); + std::tm dtm = {}; dtm.tm_wday = dow; return do_put_tm(next, a_ios, fill_char, dtm, m_weekday_format); } diff --git a/utils/boost_idb/boost/date_time/date_format_simple.hpp b/utils/boost_idb/boost/date_time/date_format_simple.hpp index 05119c44..be21ce4a 100644 --- a/utils/boost_idb/boost/date_time/date_format_simple.hpp +++ b/utils/boost_idb/boost/date_time/date_format_simple.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/parse_format_base.hpp" diff --git a/utils/boost_idb/boost/date_time/date_formatting.hpp b/utils/boost_idb/boost/date_time/date_formatting.hpp index 06709bc5..abe547a5 100644 --- a/utils/boost_idb/boost/date_time/date_formatting.hpp +++ b/utils/boost_idb/boost/date_time/date_formatting.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-30 16:25:22 -0700 (Sun, 30 Sep 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/iso_format.hpp" @@ -54,9 +54,7 @@ namespace date_time { os << std::setw(2) << std::setfill(os.widen('0')) << month.as_number(); break; } - default: - break; - + } return os; } // format_month @@ -81,13 +79,7 @@ namespace date_time { { typedef typename ymd_type::month_type month_type; std::basic_ostringstream ss; - - // Temporarily switch to classic locale to prevent possible formatting - // of year with comma or other character (for example 2,008). - ss.imbue(std::locale::classic()); ss << ymd.year; - ss.imbue(std::locale()); - if (format_type::has_date_sep_chars()) { ss << format_type::month_sep_char(); } diff --git a/utils/boost_idb/boost/date_time/date_formatting_limited.hpp b/utils/boost_idb/boost/date_time/date_formatting_limited.hpp index 5721473b..38fee07b 100644 --- a/utils/boost_idb/boost/date_time/date_formatting_limited.hpp +++ b/utils/boost_idb/boost/date_time/date_formatting_limited.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/iso_format.hpp" diff --git a/utils/boost_idb/boost/date_time/date_formatting_locales.hpp b/utils/boost_idb/boost/date_time/date_formatting_locales.hpp index e3aec496..4ac9c4e4 100644 --- a/utils/boost_idb/boost/date_time/date_formatting_locales.hpp +++ b/utils/boost_idb/boost/date_time/date_formatting_locales.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/date_generator_formatter.hpp b/utils/boost_idb/boost/date_time/date_generator_formatter.hpp index 159cf36e..88cd7e1a 100644 --- a/utils/boost_idb/boost/date_time/date_generator_formatter.hpp +++ b/utils/boost_idb/boost/date_time/date_generator_formatter.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-13 11:05:31 -0800 (Thu, 13 Nov 2008) $ + * $Date: 2008-11-13 14:05:31 -0500 (Thu, 13 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/date_generator_parser.hpp b/utils/boost_idb/boost/date_time/date_generator_parser.hpp index 7cff9ca3..f11eb42d 100644 --- a/utils/boost_idb/boost/date_time/date_generator_parser.hpp +++ b/utils/boost_idb/boost/date_time/date_generator_parser.hpp @@ -7,7 +7,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/date_generators.hpp b/utils/boost_idb/boost/date_time/date_generators.hpp index 6d3a4ac0..1f1a34a6 100644 --- a/utils/boost_idb/boost/date_time/date_generators.hpp +++ b/utils/boost_idb/boost/date_time/date_generators.hpp @@ -2,11 +2,11 @@ #define DATE_TIME_DATE_GENERATORS_HPP__ /* Copyright (c) 2002,2003,2005 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) - * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * Author: Jeff Garland, Bart Garst + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ /*! @file date_generators.hpp @@ -34,16 +34,16 @@ namespace date_time { public: typedef typename date_type::calendar_type calendar_type; typedef typename calendar_type::year_type year_type; - year_based_generator() {} - virtual ~year_based_generator() {} + year_based_generator() {}; + virtual ~year_based_generator() {}; virtual date_type get_date(year_type y) const = 0; //! Returns a string for use in a POSIX time_zone string virtual std::string to_string() const =0; }; - + //! Generates a date by applying the year to the given month and day. /*! - Example usage: + Example usage: @code partial_date pd(1, Jan); partial_date pd2(70); @@ -123,9 +123,9 @@ namespace date_time { //months are equal return (day_ < rhs.day_); } - + // added for streaming purposes - month_type month() const + month_type month() const { return month_; } @@ -135,15 +135,15 @@ namespace date_time { } //! Returns string suitable for use in POSIX time zone string - /*! Returns string formatted with up to 3 digits: - * Jan-01 == "0" + /*! Returns string formatted with up to 3 digits: + * Jan-01 == "0" * Feb-29 == "58" * Dec-31 == "365" */ virtual std::string to_string() const { std::ostringstream ss; date_type d(2004, month_, day_); - unsigned short c = d.day_of_year(); + unsigned short c = d.day_of_year(); c--; // numbered 0-365 while day_of_year is 1 based... ss << c; return ss.str(); @@ -161,7 +161,7 @@ namespace date_time { /*! Based on the idea in Cal. Calc. for finding holidays that are * the 'first Monday of September'. When instantiated with * 'fifth' kday of month, the result will be the last kday of month - * which can be the fourth or fifth depending on the structure of + * which can be the fourth or fifth depending on the structure of * the month. * * The algorithm here basically guesses for the first @@ -169,8 +169,8 @@ namespace date_time { * type. That is, if the first of the month is a Tuesday * and it needs Wenesday then we simply increment by a day * and then we can add the length of a week until we get - * to the 'nth kday'. There are probably more efficient - * algorithms based on using a mod 7, but this one works + * to the 'nth kday'. There are probably more efficient + * algorithms based on using a mod 7, but this one works * reasonably well for basic applications. * \ingroup date_alg */ @@ -233,7 +233,7 @@ namespace date_time { virtual std::string to_string() const { std::ostringstream ss; - ss << 'M' + ss << 'M' << static_cast(month_) << '.' << static_cast(wn_) << '.' << static_cast(dow_); @@ -244,7 +244,7 @@ namespace date_time { week_num wn_; day_of_week_type dow_; }; - + //! Useful generator functor for finding holidays and daylight savings /*! Similar to nth_kday_of_month, but requires less paramters * \ingroup date_alg @@ -290,7 +290,7 @@ namespace date_time { virtual std::string to_string() const { std::ostringstream ss; - ss << 'M' + ss << 'M' << static_cast(month_) << '.' << 1 << '.' << static_cast(dow_); @@ -300,9 +300,9 @@ namespace date_time { month_type month_; day_of_week_type dow_; }; - - - + + + //! Calculate something like Last Sunday of January /*! Useful generator functor for finding holidays and daylight savings * Get the last day of the month and then calculate the difference @@ -351,7 +351,7 @@ namespace date_time { virtual std::string to_string() const { std::ostringstream ss; - ss << 'M' + ss << 'M' << static_cast(month_) << '.' << 5 << '.' << static_cast(dow_); @@ -361,8 +361,8 @@ namespace date_time { month_type month_; day_of_week_type dow_; }; - - + + //! Calculate something like "First Sunday after Jan 1,2002 /*! Date generator that takes a date and finds kday after *@code @@ -400,7 +400,7 @@ namespace date_time { private: day_of_week_type dow_; }; - + //! Calculate something like "First Sunday before Jan 1,2002 /*! Date generator that takes a date and finds kday after *@code @@ -438,10 +438,10 @@ namespace date_time { private: day_of_week_type dow_; }; - + //! Calculates the number of days until the next weekday /*! Calculates the number of days until the next weekday. - * If the date given falls on a Sunday and the given weekday + * If the date given falls on a Sunday and the given weekday * is Tuesday the result will be 2 days */ template inline @@ -458,8 +458,8 @@ namespace date_time { //! Calculates the number of days since the previous weekday /*! Calculates the number of days since the previous weekday - * If the date given falls on a Sunday and the given weekday - * is Tuesday the result will be 5 days. The answer will be a positive + * If the date given falls on a Sunday and the given weekday + * is Tuesday the result will be 5 days. The answer will be a positive * number because Tuesday is 5 days before Sunday, not -5 days before. */ template inline @@ -477,9 +477,9 @@ namespace date_time { } //! Generates a date object representing the date of the following weekday from the given date - /*! Generates a date object representing the date of the following - * weekday from the given date. If the date given is 2004-May-9 - * (a Sunday) and the given weekday is Tuesday then the resulting date + /*! Generates a date object representing the date of the following + * weekday from the given date. If the date given is 2004-May-9 + * (a Sunday) and the given weekday is Tuesday then the resulting date * will be 2004-May-11. */ template inline @@ -489,9 +489,9 @@ namespace date_time { } //! Generates a date object representing the date of the previous weekday from the given date - /*! Generates a date object representing the date of the previous - * weekday from the given date. If the date given is 2004-May-9 - * (a Sunday) and the given weekday is Tuesday then the resulting date + /*! Generates a date object representing the date of the previous + * weekday from the given date. If the date given is 2004-May-9 + * (a Sunday) and the given weekday is Tuesday then the resulting date * will be 2004-May-4. */ template inline diff --git a/utils/boost_idb/boost/date_time/date_iterator.hpp b/utils/boost_idb/boost/date_time/date_iterator.hpp index c8ec50ee..284dc749 100644 --- a/utils/boost_idb/boost/date_time/date_iterator.hpp +++ b/utils/boost_idb/boost/date_time/date_iterator.hpp @@ -2,11 +2,11 @@ #define DATE_ITERATOR_HPP___ /* Copyright (c) 2002,2003 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include @@ -32,7 +32,7 @@ namespace date_time { template class date_itr_base { // works, but benefit unclear at the moment - // class date_itr_base : public std::iterator{ public: typedef typename date_type::duration_type duration_type; @@ -40,31 +40,31 @@ namespace date_time { typedef std::input_iterator_tag iterator_category; date_itr_base(date_type d) : current_(d) {} - virtual ~date_itr_base() {} - date_itr_base& operator++() + virtual ~date_itr_base() {}; + date_itr_base& operator++() { current_ = current_ + get_offset(current_); return *this; } - date_itr_base& operator--() + date_itr_base& operator--() { current_ = current_ + get_neg_offset(current_); return *this; } virtual duration_type get_offset(const date_type& current) const=0; virtual duration_type get_neg_offset(const date_type& current) const=0; - date_type operator*() {return current_;} - date_type* operator->() {return ¤t_;} + date_type operator*() {return current_;}; + date_type* operator->() {return ¤t_;}; bool operator< (const date_type& d) {return current_ < d;} bool operator<= (const date_type& d) {return current_ <= d;} bool operator> (const date_type& d) {return current_ > d;} bool operator>= (const date_type& d) {return current_ >= d;} bool operator== (const date_type& d) {return current_ == d;} - bool operator!= (const date_type& d) {return current_ != d;} + bool operator!= (const date_type& d) {return current_ != d;} private: date_type current_; }; - + //! Overrides the base date iterator providing hook for functors /* * offset_functor @@ -77,9 +77,9 @@ namespace date_time { class date_itr : public date_itr_base { public: typedef typename date_type::duration_type duration_type; - date_itr(date_type d, int factor=1) : - date_itr_base(d), - of_(factor) + date_itr(date_type d, int factor=1) : + date_itr_base(d), + of_(factor) {} private: virtual duration_type get_offset(const date_type& current) const @@ -92,9 +92,9 @@ namespace date_time { } offset_functor of_; }; + - - + } } //namespace date_time diff --git a/utils/boost_idb/boost/date_time/date_names_put.hpp b/utils/boost_idb/boost/date_time/date_names_put.hpp index 32aeb36f..c6f0ce2a 100644 --- a/utils/boost_idb/boost/date_time/date_names_put.hpp +++ b/utils/boost_idb/boost/date_time/date_names_put.hpp @@ -2,11 +2,11 @@ #define DATE_TIME_DATE_NAMES_PUT_HPP___ /* Copyright (c) 2002-2005 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) - * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * Author: Jeff Garland, Bart Garst + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ @@ -27,22 +27,22 @@ namespace date_time { //! Output facet base class for gregorian dates. /*! This class is a base class for date facets used to localize the * names of months and the names of days in the week. - * + * * Requirements of Config - * - define an enumeration month_enum that enumerates the months. + * - define an enumeration month_enum that enumerates the months. * The enumeration should be '1' based eg: Jan==1 * - define as_short_string and as_long_string * * (see langer & kreft p334). - * + * */ template > class date_names_put : public std::locale::facet { public: - date_names_put() {} + date_names_put() {}; typedef OutputIterator iter_type; typedef typename Config::month_type month_type; typedef typename Config::month_enum month_enum; @@ -118,7 +118,7 @@ namespace date_time { put_string(oitr, gm.as_short_string(c)); } //! Default facet implementation uses month_type defaults - virtual void do_put_month_long(iter_type& oitr, + virtual void do_put_month_long(iter_type& oitr, month_enum moy) const { month_type gm(moy); @@ -160,7 +160,7 @@ namespace date_time { string_type s(separator); //put in '-' put_string(oitr, s); } - //! Default for date order + //! Default for date order virtual ymd_order_spec do_date_order() const { return ymd_order_iso; @@ -186,27 +186,27 @@ namespace date_time { } } }; - + template - const typename date_names_put::char_type - date_names_put::default_special_value_names[3][17] = { + const typename date_names_put::char_type + date_names_put::default_special_value_names[3][17] = { {'n','o','t','-','a','-','d','a','t','e','-','t','i','m','e'}, {'-','i','n','f','i','n','i','t','y'}, {'+','i','n','f','i','n','i','t','y'} }; template - const typename date_names_put::char_type - date_names_put::separator[2] = + const typename date_names_put::char_type + date_names_put::separator[2] = {'-', '\0'} ; + - - //! Generate storage location for a std::locale::id + //! Generate storage location for a std::locale::id template std::locale::id date_names_put::id; //! A date name output facet that takes an array of char* to define strings template > class all_date_names_put : public date_names_put { @@ -230,29 +230,29 @@ namespace date_time { separator_char_[0] = separator_char; separator_char_[1] = '\0'; - } + }; typedef OutputIterator iter_type; typedef typename Config::month_enum month_enum; typedef typename Config::weekday_enum weekday_enum; typedef typename Config::special_value_enum special_value_enum; - const charT* const* get_short_month_names() const + const charT* const* get_short_month_names() const { return month_short_names_; } - const charT* const* get_long_month_names() const + const charT* const* get_long_month_names() const { return month_long_names_; } - const charT* const* get_special_value_names() const + const charT* const* get_special_value_names() const { return special_value_names_; } - const charT* const* get_short_weekday_names()const + const charT* const* get_short_weekday_names()const { return weekday_short_names_; } - const charT* const* get_long_weekday_names()const + const charT* const* get_long_weekday_names()const { return weekday_long_names_; } @@ -263,7 +263,7 @@ namespace date_time { { this->put_string(oitr, month_short_names_[moy-1]); } - //! Long month names + //! Long month names virtual void do_put_month_long(iter_type& oitr, month_enum moy) const { this->put_string(oitr, month_long_names_[moy-1]); @@ -310,7 +310,7 @@ namespace date_time { const charT* const* weekday_long_names_; charT separator_char_[2]; ymd_order_spec order_spec_; - month_format_spec month_format_spec_; + month_format_spec month_format_spec_; }; } } //namespace boost::date_time diff --git a/utils/boost_idb/boost/date_time/date_parsing.hpp b/utils/boost_idb/boost/date_time/date_parsing.hpp index 35ec8e43..f361bc80 100644 --- a/utils/boost_idb/boost/date_time/date_parsing.hpp +++ b/utils/boost_idb/boost/date_time/date_parsing.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-30 16:25:22 -0700 (Sun, 30 Sep 2012) $ + * $Date: 2009-06-04 04:24:49 -0400 (Thu, 04 Jun 2009) $ */ #include @@ -148,7 +148,6 @@ namespace date_time { day = boost::lexical_cast(*beg); break; } - default: break; } //switch } return date_type(year, month, day); @@ -181,7 +180,6 @@ namespace date_time { case 0: y = i; break; case 1: m = i; break; case 2: d = i; break; - default: break; } pos++; } diff --git a/utils/boost_idb/boost/date_time/dst_rules.hpp b/utils/boost_idb/boost/date_time/dst_rules.hpp index cf65c162..20cb40b6 100644 --- a/utils/boost_idb/boost/date_time/dst_rules.hpp +++ b/utils/boost_idb/boost/date_time/dst_rules.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-30 16:25:22 -0700 (Sun, 30 Sep 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*! @file dst_rules.hpp @@ -371,7 +371,7 @@ namespace boost { return is_not_in_dst; } - static bool is_dst_boundary_day(date_type /*d*/) + static bool is_dst_boundary_day(date_type d) { return false; } diff --git a/utils/boost_idb/boost/date_time/dst_transition_generators.hpp b/utils/boost_idb/boost/date_time/dst_transition_generators.hpp index 16c1fd63..6c4da1c3 100644 --- a/utils/boost_idb/boost/date_time/dst_transition_generators.hpp +++ b/utils/boost_idb/boost/date_time/dst_transition_generators.hpp @@ -18,7 +18,7 @@ namespace date_time { { public: typedef typename date_type::year_type year_type; - virtual ~dst_day_calc_rule() {} + virtual ~dst_day_calc_rule() {}; virtual date_type start_day(year_type y) const=0; virtual std::string start_rule_as_string() const=0; virtual date_type end_day(year_type y) const=0; diff --git a/utils/boost_idb/boost/date_time/filetime_functions.hpp b/utils/boost_idb/boost/date_time/filetime_functions.hpp index 3c7f13f3..27ed754f 100644 --- a/utils/boost_idb/boost/date_time/filetime_functions.hpp +++ b/utils/boost_idb/boost/date_time/filetime_functions.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 09:04:10 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2009-06-06 07:24:09 -0400 (Sat, 06 Jun 2009) $ */ /*! @file filetime_functions.hpp @@ -73,12 +73,12 @@ namespace winapi { file_time ft_utc; GetSystemTimeAsFileTime(&ft_utc); FileTimeToLocalFileTime(&ft_utc, &ft); -#elif defined(BOOST_HAS_GETSYSTEMTIMEASFILETIME) - GetSystemTimeAsFileTime(&ft); -#else +#elif defined(BOOST_NO_GETSYSTEMTIMEASFILETIME) system_time st; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); +#else + GetSystemTimeAsFileTime(&ft); #endif } diff --git a/utils/boost_idb/boost/date_time/format_date_parser.hpp b/utils/boost_idb/boost/date_time/format_date_parser.hpp index 1a69055c..a4a4d0df 100644 --- a/utils/boost_idb/boost/date_time/format_date_parser.hpp +++ b/utils/boost_idb/boost/date_time/format_date_parser.hpp @@ -7,7 +7,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2013-10-15 08:22:02 -0700 (Tue, 15 Oct 2013) $ + * $Date: 2009-06-04 04:24:49 -0400 (Thu, 04 Jun 2009) $ */ @@ -256,6 +256,7 @@ class format_date_parser // skip leading whitespace while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; } + charT current_char = *sitr; short year(0), month(0), day(0), day_of_year(0);// wkday(0); /* Initialized the following to their minimum values. These intermediate @@ -271,8 +272,7 @@ class format_date_parser const_itr itr(format_str.begin()); while (itr != format_str.end() && (sitr != stream_end)) { if (*itr == '%') { - if ( ++itr == format_str.end()) - break; + itr++; if (*itr != '%') { switch(*itr) { case 'a': @@ -290,6 +290,7 @@ class format_date_parser } wkday = mr.current_match; if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -309,6 +310,7 @@ class format_date_parser } wkday = mr.current_match; if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -324,6 +326,7 @@ class format_date_parser } t_month = month_type(mr.current_match); if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -339,6 +342,7 @@ class format_date_parser } t_month = month_type(mr.current_match); if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -434,6 +438,7 @@ class format_date_parser itr++; if (use_current_char) { use_current_char = false; + current_char = *sitr; } else { sitr++; @@ -471,14 +476,14 @@ class format_date_parser // skip leading whitespace while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; } + charT current_char = *sitr; short month(0); const_itr itr(format_str.begin()); while (itr != format_str.end() && (sitr != stream_end)) { if (*itr == '%') { - if ( ++itr == format_str.end()) - break; + itr++; if (*itr != '%') { switch(*itr) { case 'b': @@ -486,6 +491,7 @@ class format_date_parser mr = m_month_short_names.match(sitr, stream_end); month = mr.current_match; if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -495,6 +501,7 @@ class format_date_parser mr = m_month_long_names.match(sitr, stream_end); month = mr.current_match; if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -522,6 +529,7 @@ class format_date_parser itr++; if (use_current_char) { use_current_char = false; + current_char = *sitr; } else { sitr++; @@ -573,14 +581,14 @@ class format_date_parser // skip leading whitespace while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; } + charT current_char = *sitr; short wkday(0); const_itr itr(format_str.begin()); while (itr != format_str.end() && (sitr != stream_end)) { if (*itr == '%') { - if ( ++itr == format_str.end()) - break; + itr++; if (*itr != '%') { switch(*itr) { case 'a': @@ -592,6 +600,7 @@ class format_date_parser mr = m_weekday_short_names.match(sitr, stream_end); wkday = mr.current_match; if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -605,6 +614,7 @@ class format_date_parser mr = m_weekday_long_names.match(sitr, stream_end); wkday = mr.current_match; if (mr.has_remaining()) { + current_char = mr.last_char(); use_current_char = true; } break; @@ -631,6 +641,7 @@ class format_date_parser itr++; if (use_current_char) { use_current_char = false; + current_char = *sitr; } else { sitr++; @@ -663,14 +674,14 @@ class format_date_parser // skip leading whitespace while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; } + charT current_char = *sitr; unsigned short year(0); const_itr itr(format_str.begin()); while (itr != format_str.end() && (sitr != stream_end)) { if (*itr == '%') { - if ( ++itr == format_str.end()) - break; + itr++; if (*itr != '%') { //match_results mr; switch(*itr) { @@ -703,6 +714,7 @@ class format_date_parser itr++; if (use_current_char) { use_current_char = false; + current_char = *sitr; } else { sitr++; diff --git a/utils/boost_idb/boost/date_time/gregorian/conversion.hpp b/utils/boost_idb/boost/date_time/gregorian/conversion.hpp index 33f6856b..c505bddf 100644 --- a/utils/boost_idb/boost/date_time/gregorian/conversion.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/conversion.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2010-06-09 11:10:13 -0700 (Wed, 09 Jun 2010) $ + * $Date: 2010-06-09 14:10:13 -0400 (Wed, 09 Jun 2010) $ */ #include diff --git a/utils/boost_idb/boost/date_time/gregorian/formatters.hpp b/utils/boost_idb/boost/date_time/gregorian/formatters.hpp index eda7dc34..786e79f2 100644 --- a/utils/boost_idb/boost/date_time/gregorian/formatters.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/formatters.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/compiler_config.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/formatters_limited.hpp b/utils/boost_idb/boost/date_time/gregorian/formatters_limited.hpp index 8dfd2d0c..4531ebec 100644 --- a/utils/boost_idb/boost/date_time/gregorian/formatters_limited.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/formatters_limited.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/gregorian/gregorian_types.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_calendar.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_calendar.hpp index e9c1852e..483ead50 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_calendar.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_calendar.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2010-01-10 11:17:23 -0800 (Sun, 10 Jan 2010) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #include diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_date.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_date.hpp index 860a407c..ad67c0ce 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_date.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_date.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2010-01-10 11:17:23 -0800 (Sun, 10 Jan 2010) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #include diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_day.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_day.hpp index 4ea829fb..92ea6ab0 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_day.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_day.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/constrained_value.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_day_of_year.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_day_of_year.hpp index 2f8874d2..36b22c2b 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_day_of_year.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_day_of_year.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/constrained_value.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_duration.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_duration.hpp index a9c0c171..fd755420 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_duration.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_duration.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_duration_types.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_duration_types.hpp index 8328ca30..3d1ce621 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_duration_types.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_duration_types.hpp @@ -5,7 +5,7 @@ * Subject to Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_facet.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_facet.hpp index 9efc6195..9c3877ed 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_facet.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_facet.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-23 03:13:35 -0800 (Sun, 23 Nov 2008) $ + * $Date: 2008-11-23 06:13:35 -0500 (Sun, 23 Nov 2008) $ */ #include "boost/date_time/gregorian/gregorian_types.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_month.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_month.hpp index b48a8a89..fc9c8614 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_month.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_month.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/constrained_value.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_serialize.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_serialize.hpp index 2cfad93c..e427a48a 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_serialize.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_serialize.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-30 16:25:22 -0700 (Sun, 30 Sep 2012) $ + * $Date: 2010-11-11 15:19:38 -0500 (Thu, 11 Nov 2010) $ */ #include "boost/date_time/gregorian/gregorian_types.hpp" @@ -22,7 +22,6 @@ BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::date_duration) BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::date_duration::duration_rep) BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::date_period) -BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::greg_year) BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::greg_month) BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::greg_day) BOOST_SERIALIZATION_SPLIT_FREE(::boost::gregorian::greg_weekday) @@ -88,7 +87,7 @@ void load(Archive & ar, //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, ::boost::gregorian::date* dp, const unsigned int /*file_version*/) { @@ -117,7 +116,7 @@ void load(Archive & ar, gregorian::date_duration & dd, unsigned int /*version*/) } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::date_duration* dd, +inline void load_construct_data(Archive & ar, gregorian::date_duration* dd, const unsigned int /*file_version*/) { ::new(dd) gregorian::date_duration(gregorian::not_a_date_time); @@ -143,7 +142,7 @@ void load(Archive & ar, gregorian::date_duration::duration_rep & dr, unsigned in } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::date_duration::duration_rep* dr, +inline void load_construct_data(Archive & ar, gregorian::date_duration::duration_rep* dr, const unsigned int /*file_version*/) { ::new(dr) gregorian::date_duration::duration_rep(0); @@ -179,7 +178,7 @@ void load(Archive & ar, gregorian::date_period& dp, unsigned int /*version*/) } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::date_period* dp, +inline void load_construct_data(Archive & ar, gregorian::date_period* dp, const unsigned int /*file_version*/) { gregorian::date d(gregorian::not_a_date_time); @@ -187,32 +186,6 @@ inline void load_construct_data(Archive & /*ar*/, gregorian::date_period* dp, ::new(dp) gregorian::date_period(d,dd); } -/**** greg_year ****/ - -//! Function to save gregorian::greg_year objects using serialization lib -template -void save(Archive & ar, const gregorian::greg_year& gy, - unsigned int /*version*/) -{ - unsigned short us = gy; - ar & make_nvp("greg_year", us); -} -//! Function to load gregorian::greg_year objects using serialization lib -template -void load(Archive & ar, gregorian::greg_year& gy, unsigned int /*version*/) -{ - unsigned short us; - ar & make_nvp("greg_year", us); - gy = gregorian::greg_year(us); -} -//!override needed b/c no default constructor -template -inline void load_construct_data(Archive & /*ar*/, gregorian::greg_year* gy, - const unsigned int /*file_version*/) -{ - ::new(gy) gregorian::greg_year(1900); -} - /**** greg_month ****/ //! Function to save gregorian::greg_month objects using serialization lib @@ -233,7 +206,7 @@ void load(Archive & ar, gregorian::greg_month& gm, unsigned int /*version*/) } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::greg_month* gm, +inline void load_construct_data(Archive & ar, gregorian::greg_month* gm, const unsigned int /*file_version*/) { ::new(gm) gregorian::greg_month(1); @@ -259,7 +232,7 @@ void load(Archive & ar, gregorian::greg_day& gd, unsigned int /*version*/) } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::greg_day* gd, +inline void load_construct_data(Archive & ar, gregorian::greg_day* gd, const unsigned int /*file_version*/) { ::new(gd) gregorian::greg_day(1); @@ -285,7 +258,7 @@ void load(Archive & ar, gregorian::greg_weekday& gd, unsigned int /*version*/) } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::greg_weekday* gd, +inline void load_construct_data(Archive & ar, gregorian::greg_weekday* gd, const unsigned int /*file_version*/) { ::new(gd) gregorian::greg_weekday(1); @@ -323,7 +296,7 @@ void load(Archive & ar, gregorian::partial_date& pd, unsigned int /*version*/) } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, gregorian::partial_date* pd, +inline void load_construct_data(Archive & ar, gregorian::partial_date* pd, const unsigned int /*file_version*/) { gregorian::greg_month gm(1); @@ -366,7 +339,7 @@ void load(Archive & ar, gregorian::nth_kday_of_month& nkd, unsigned int /*versio } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, gregorian::nth_kday_of_month* nkd, const unsigned int /*file_version*/) { @@ -406,7 +379,7 @@ void load(Archive & ar, gregorian::first_kday_of_month& fkd, unsigned int /*vers } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, gregorian::first_kday_of_month* fkd, const unsigned int /*file_version*/) { @@ -445,7 +418,7 @@ void load(Archive & ar, gregorian::last_kday_of_month& lkd, unsigned int /*versi } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, gregorian::last_kday_of_month* lkd, const unsigned int /*file_version*/) { @@ -474,7 +447,7 @@ void load(Archive & ar, gregorian::first_kday_before& fkdb, unsigned int /*versi } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, gregorian::first_kday_before* fkdb, const unsigned int /*file_version*/) { @@ -503,7 +476,7 @@ void load(Archive & ar, gregorian::first_kday_after& fkda, unsigned int /*versio } //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, gregorian::first_kday_after* fkda, const unsigned int /*file_version*/) { diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_weekday.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_weekday.hpp index ab68fcd1..9b566c44 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_weekday.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_weekday.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include "boost/date_time/constrained_value.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_year.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_year.hpp index 322f40d0..ef1735f4 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_year.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_year.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/constrained_value.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/greg_ymd.hpp b/utils/boost_idb/boost/date_time/gregorian/greg_ymd.hpp index e7d441ef..086e73df 100644 --- a/utils/boost_idb/boost/date_time/gregorian/greg_ymd.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/greg_ymd.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/year_month_day.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian/gregorian.hpp b/utils/boost_idb/boost/date_time/gregorian/gregorian.hpp index becbc068..bfafa1b0 100644 --- a/utils/boost_idb/boost/date_time/gregorian/gregorian.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/gregorian.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*! @file gregorian.hpp diff --git a/utils/boost_idb/boost/date_time/gregorian/gregorian_io.hpp b/utils/boost_idb/boost/date_time/gregorian/gregorian_io.hpp index e6ba01fe..62a759f5 100644 --- a/utils/boost_idb/boost/date_time/gregorian/gregorian_io.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/gregorian_io.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/gregorian/gregorian_types.hpp b/utils/boost_idb/boost/date_time/gregorian/gregorian_types.hpp index 3f4b92fd..0c74857a 100644 --- a/utils/boost_idb/boost/date_time/gregorian/gregorian_types.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/gregorian_types.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*! @file gregorian_types.hpp diff --git a/utils/boost_idb/boost/date_time/gregorian/parsers.hpp b/utils/boost_idb/boost/date_time/gregorian/parsers.hpp index a2fa4e1d..95d4f23d 100644 --- a/utils/boost_idb/boost/date_time/gregorian/parsers.hpp +++ b/utils/boost_idb/boost/date_time/gregorian/parsers.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/gregorian/gregorian_types.hpp" diff --git a/utils/boost_idb/boost/date_time/gregorian_calendar.hpp b/utils/boost_idb/boost/date_time/gregorian_calendar.hpp index b645aa49..c27c09e7 100644 --- a/utils/boost_idb/boost/date_time/gregorian_calendar.hpp +++ b/utils/boost_idb/boost/date_time/gregorian_calendar.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2010-01-10 11:17:23 -0800 (Sun, 10 Jan 2010) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ diff --git a/utils/boost_idb/boost/date_time/gregorian_calendar.ipp b/utils/boost_idb/boost/date_time/gregorian_calendar.ipp index af19394f..a281b45c 100644 --- a/utils/boost_idb/boost/date_time/gregorian_calendar.ipp +++ b/utils/boost_idb/boost/date_time/gregorian_calendar.ipp @@ -3,7 +3,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 09:04:10 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #ifndef NO_BOOST_DATE_TIME_INLINE @@ -47,7 +47,7 @@ namespace date_time { return week; } - if (week == 53) { + if ((week == 53)) { if((day==6) ||(day == 5 && is_leap_year(ymd.year))) { return week; //under these circumstances week == 53. } else { diff --git a/utils/boost_idb/boost/date_time/int_adapter.hpp b/utils/boost_idb/boost/date_time/int_adapter.hpp index d1246e7b..fc98fc12 100644 --- a/utils/boost_idb/boost/date_time/int_adapter.hpp +++ b/utils/boost_idb/boost/date_time/int_adapter.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/iso_format.hpp b/utils/boost_idb/boost/date_time/iso_format.hpp index 1f9e73d6..8262fa21 100644 --- a/utils/boost_idb/boost/date_time/iso_format.hpp +++ b/utils/boost_idb/boost/date_time/iso_format.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/parse_format_base.hpp" diff --git a/utils/boost_idb/boost/date_time/local_time/conversion.hpp b/utils/boost_idb/boost/date_time/local_time/conversion.hpp index a530de42..13e4d3eb 100644 --- a/utils/boost_idb/boost/date_time/local_time/conversion.hpp +++ b/utils/boost_idb/boost/date_time/local_time/conversion.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2009-06-04 01:24:49 -0700 (Thu, 04 Jun 2009) $ + * $Date: 2009-06-04 04:24:49 -0400 (Thu, 04 Jun 2009) $ */ diff --git a/utils/boost_idb/boost/date_time/local_time/custom_time_zone.hpp b/utils/boost_idb/boost/date_time/local_time/custom_time_zone.hpp index 8bdb97b7..a6c1d420 100644 --- a/utils/boost_idb/boost/date_time/local_time/custom_time_zone.hpp +++ b/utils/boost_idb/boost/date_time/local_time/custom_time_zone.hpp @@ -2,10 +2,10 @@ #define LOCAL_TIME_CUSTOM_TIME_ZONE_HPP__ /* Copyright (c) 2003-2005 CrystalClear Software, Inc. - * Subject to the Boost Software License, Version 1.0. + * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2013-09-21 13:17:00 -0700 (Sat, 21 Sep 2013) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/time_zone_base.hpp" @@ -34,8 +34,8 @@ namespace local_time { typedef typename base_type::stringstream_type stringstream_type; typedef date_time::time_zone_names_base time_zone_names; typedef CharT char_type; - - custom_time_zone_base(const time_zone_names& zone_names, + + custom_time_zone_base(const time_zone_names& zone_names, const time_duration_type& utc_offset, const dst_adjustment_offsets& dst_shift, boost::shared_ptr calc_rule) : @@ -43,8 +43,8 @@ namespace local_time { base_utc_offset_(utc_offset), dst_offsets_(dst_shift), dst_calc_rules_(calc_rule) - {} - virtual ~custom_time_zone_base() {} + {}; + virtual ~custom_time_zone_base() {}; virtual string_type dst_zone_abbrev() const { return zone_names_.dst_zone_abbrev(); @@ -64,7 +64,7 @@ namespace local_time { //! True if zone uses daylight savings adjustments virtual bool has_dst() const { - return (bool) dst_calc_rules_; //if calc_rule is set the tz has dst + return (dst_calc_rules_); //if calc_rule is set the tz has dst } //! Local time that DST starts -- NADT if has_dst is false virtual posix_time::ptime dst_local_start_time(gregorian::greg_year y) const diff --git a/utils/boost_idb/boost/date_time/local_time/date_duration_operators.hpp b/utils/boost_idb/boost/date_time/local_time/date_duration_operators.hpp index b4c325df..ee870227 100644 --- a/utils/boost_idb/boost/date_time/local_time/date_duration_operators.hpp +++ b/utils/boost_idb/boost/date_time/local_time/date_duration_operators.hpp @@ -6,7 +6,7 @@ * (See accompanying file LICENSE_1_0.txt or * http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/gregorian/greg_duration_types.hpp" diff --git a/utils/boost_idb/boost/date_time/local_time/dst_transition_day_rules.hpp b/utils/boost_idb/boost/date_time/local_time/dst_transition_day_rules.hpp index d82731c0..3d6cfbac 100644 --- a/utils/boost_idb/boost/date_time/local_time/dst_transition_day_rules.hpp +++ b/utils/boost_idb/boost/date_time/local_time/dst_transition_day_rules.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/local_time/local_date_time.hpp b/utils/boost_idb/boost/date_time/local_time/local_date_time.hpp index 96b29158..9c9f6234 100644 --- a/utils/boost_idb/boost/date_time/local_time/local_date_time.hpp +++ b/utils/boost_idb/boost/date_time/local_time/local_date_time.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #include @@ -208,7 +208,7 @@ namespace local_time { } //! Simple destructor, releases time zone if last referrer - ~local_date_time_base() {} + ~local_date_time_base() {}; //! Copy constructor local_date_time_base(const local_date_time_base& rhs) : diff --git a/utils/boost_idb/boost/date_time/local_time/local_time.hpp b/utils/boost_idb/boost/date_time/local_time/local_time.hpp index 162cac5b..f7d4cc68 100644 --- a/utils/boost_idb/boost/date_time/local_time/local_time.hpp +++ b/utils/boost_idb/boost/date_time/local_time/local_time.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/posix_time/posix_time.hpp" diff --git a/utils/boost_idb/boost/date_time/local_time/local_time_io.hpp b/utils/boost_idb/boost/date_time/local_time/local_time_io.hpp index b5e3c3f1..c161ff7e 100644 --- a/utils/boost_idb/boost/date_time/local_time/local_time_io.hpp +++ b/utils/boost_idb/boost/date_time/local_time/local_time_io.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-13 11:05:31 -0800 (Thu, 13 Nov 2008) $ + * $Date: 2008-11-13 14:05:31 -0500 (Thu, 13 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/local_time/local_time_types.hpp b/utils/boost_idb/boost/date_time/local_time/local_time_types.hpp index 5e04422e..ed58b801 100644 --- a/utils/boost_idb/boost/date_time/local_time/local_time_types.hpp +++ b/utils/boost_idb/boost/date_time/local_time/local_time_types.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/local_time/local_date_time.hpp" diff --git a/utils/boost_idb/boost/date_time/local_time/posix_time_zone.hpp b/utils/boost_idb/boost/date_time/local_time/posix_time_zone.hpp index ee1b553e..2a0199fc 100644 --- a/utils/boost_idb/boost/date_time/local_time/posix_time_zone.hpp +++ b/utils/boost_idb/boost/date_time/local_time/posix_time_zone.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2010-06-10 13:24:38 -0400 (Thu, 10 Jun 2010) $ */ #include @@ -115,7 +115,7 @@ namespace local_time{ calc_rules(dst_begin, dst_end); } } - virtual ~posix_time_zone_base() {} + virtual ~posix_time_zone_base() {}; //!String for the zone when not in daylight savings (eg: EST) virtual string_type std_zone_abbrev()const { diff --git a/utils/boost_idb/boost/date_time/local_time/tz_database.hpp b/utils/boost_idb/boost/date_time/local_time/tz_database.hpp index aceda939..4cfca45c 100644 --- a/utils/boost_idb/boost/date_time/local_time/tz_database.hpp +++ b/utils/boost_idb/boost/date_time/local_time/tz_database.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/local_time_adjustor.hpp b/utils/boost_idb/boost/date_time/local_time_adjustor.hpp index 13251a2c..eea4d37a 100644 --- a/utils/boost_idb/boost/date_time/local_time_adjustor.hpp +++ b/utils/boost_idb/boost/date_time/local_time_adjustor.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ /*! @file local_time_adjustor.hpp diff --git a/utils/boost_idb/boost/date_time/local_timezone_defs.hpp b/utils/boost_idb/boost/date_time/local_timezone_defs.hpp index b56278ed..fd6d3c2f 100644 --- a/utils/boost_idb/boost/date_time/local_timezone_defs.hpp +++ b/utils/boost_idb/boost/date_time/local_timezone_defs.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-11-13 12:10:23 -0800 (Thu, 13 Nov 2008) $ + * $Date: 2008-11-13 15:10:23 -0500 (Thu, 13 Nov 2008) $ */ #include "boost/date_time/dst_rules.hpp" diff --git a/utils/boost_idb/boost/date_time/locale_config.hpp b/utils/boost_idb/boost/date_time/locale_config.hpp index 194d5dd3..d01e008f 100644 --- a/utils/boost_idb/boost/date_time/locale_config.hpp +++ b/utils/boost_idb/boost/date_time/locale_config.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ // This file configures whether the library will support locales and hence diff --git a/utils/boost_idb/boost/date_time/microsec_time_clock.hpp b/utils/boost_idb/boost/date_time/microsec_time_clock.hpp index 177811ee..9396579d 100644 --- a/utils/boost_idb/boost/date_time/microsec_time_clock.hpp +++ b/utils/boost_idb/boost/date_time/microsec_time_clock.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2010-05-10 02:15:48 -0700 (Mon, 10 May 2010) $ + * $Date: 2010-05-10 05:15:48 -0400 (Mon, 10 May 2010) $ */ diff --git a/utils/boost_idb/boost/date_time/parse_format_base.hpp b/utils/boost_idb/boost/date_time/parse_format_base.hpp index 087baf95..b17a5c8e 100644 --- a/utils/boost_idb/boost/date_time/parse_format_base.hpp +++ b/utils/boost_idb/boost/date_time/parse_format_base.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ namespace boost { diff --git a/utils/boost_idb/boost/date_time/period.hpp b/utils/boost_idb/boost/date_time/period.hpp index 3e34def3..c67bc36c 100644 --- a/utils/boost_idb/boost/date_time/period.hpp +++ b/utils/boost_idb/boost/date_time/period.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*! \file period.hpp diff --git a/utils/boost_idb/boost/date_time/period_formatter.hpp b/utils/boost_idb/boost/date_time/period_formatter.hpp index b6ddc821..08082e10 100644 --- a/utils/boost_idb/boost/date_time/period_formatter.hpp +++ b/utils/boost_idb/boost/date_time/period_formatter.hpp @@ -7,7 +7,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ @@ -114,10 +114,10 @@ namespace boost { namespace date_time { { m_range_option = option; } - void delimiter_strings(const string_type& , - const string_type& , - const string_type& , - const string_type& ) + void delimiter_strings(const string_type& separator, + const string_type& start_delim, + const string_type& open_end_delim, + const string_type& closed_end_delim) { m_period_separator; m_period_start_delimeter; diff --git a/utils/boost_idb/boost/date_time/period_parser.hpp b/utils/boost_idb/boost/date_time/period_parser.hpp index 84b9d137..9cd57e18 100644 --- a/utils/boost_idb/boost/date_time/period_parser.hpp +++ b/utils/boost_idb/boost/date_time/period_parser.hpp @@ -7,7 +7,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-13 12:10:23 -0800 (Thu, 13 Nov 2008) $ + * $Date: 2008-11-13 15:10:23 -0500 (Thu, 13 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/posix_time/conversion.hpp b/utils/boost_idb/boost/date_time/posix_time/conversion.hpp index 83ccf600..3fb21d79 100644 --- a/utils/boost_idb/boost/date_time/posix_time/conversion.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/conversion.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2010-06-09 11:10:13 -0700 (Wed, 09 Jun 2010) $ + * $Date: 2010-06-09 14:10:13 -0400 (Wed, 09 Jun 2010) $ */ #include diff --git a/utils/boost_idb/boost/date_time/posix_time/date_duration_operators.hpp b/utils/boost_idb/boost/date_time/posix_time/date_duration_operators.hpp index 6846a778..e6899ba0 100644 --- a/utils/boost_idb/boost/date_time/posix_time/date_duration_operators.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/date_duration_operators.hpp @@ -6,7 +6,7 @@ * (See accompanying file LICENSE_1_0.txt or * http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/gregorian/greg_duration_types.hpp" diff --git a/utils/boost_idb/boost/date_time/posix_time/posix_time.hpp b/utils/boost_idb/boost/date_time/posix_time/posix_time.hpp index 3b85ff46..4e9294c4 100644 --- a/utils/boost_idb/boost/date_time/posix_time/posix_time.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/posix_time.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*!@file posix_time.hpp Global header file to get all of posix time types */ diff --git a/utils/boost_idb/boost/date_time/posix_time/posix_time_config.hpp b/utils/boost_idb/boost/date_time/posix_time/posix_time_config.hpp index d0b76536..60c3f7ee 100644 --- a/utils/boost_idb/boost/date_time/posix_time/posix_time_config.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/posix_time_config.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-10-10 12:05:03 -0700 (Wed, 10 Oct 2012) $ + * $Date: 2009-06-04 07:52:28 -0400 (Thu, 04 Jun 2009) $ */ #include //for MCW 7.2 std::abs(long long) @@ -81,7 +81,7 @@ namespace posix_time { {} //Give duration access to ticks constructor -- hide from users friend class date_time::time_duration; - protected: + private: explicit time_duration(impl_type tick_count) : date_time::time_duration(tick_count) {} diff --git a/utils/boost_idb/boost/date_time/posix_time/posix_time_duration.hpp b/utils/boost_idb/boost/date_time/posix_time/posix_time_duration.hpp index 9778fd7f..db3b85fe 100644 --- a/utils/boost_idb/boost/date_time/posix_time/posix_time_duration.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/posix_time_duration.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/posix_time/posix_time_config.hpp" diff --git a/utils/boost_idb/boost/date_time/posix_time/posix_time_io.hpp b/utils/boost_idb/boost/date_time/posix_time/posix_time_io.hpp index fb63a916..9a80737a 100644 --- a/utils/boost_idb/boost/date_time/posix_time/posix_time_io.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/posix_time_io.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-13 11:05:31 -0800 (Thu, 13 Nov 2008) $ + * $Date: 2008-11-13 14:05:31 -0500 (Thu, 13 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/posix_time/posix_time_legacy_io.hpp b/utils/boost_idb/boost/date_time/posix_time/posix_time_legacy_io.hpp index fcc3fac1..f5b20a8f 100644 --- a/utils/boost_idb/boost/date_time/posix_time/posix_time_legacy_io.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/posix_time_legacy_io.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*! @file posix_time_pre133_operators.hpp diff --git a/utils/boost_idb/boost/date_time/posix_time/posix_time_system.hpp b/utils/boost_idb/boost/date_time/posix_time/posix_time_system.hpp index 13626e9b..3d44e0ff 100644 --- a/utils/boost_idb/boost/date_time/posix_time/posix_time_system.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/posix_time_system.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/posix_time/ptime.hpp b/utils/boost_idb/boost/date_time/posix_time/ptime.hpp index 3f1cb047..2abc02d3 100644 --- a/utils/boost_idb/boost/date_time/posix_time/ptime.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/ptime.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/posix_time/posix_time_system.hpp" diff --git a/utils/boost_idb/boost/date_time/posix_time/time_formatters.hpp b/utils/boost_idb/boost/date_time/posix_time/time_formatters.hpp index 534b9525..466331b0 100644 --- a/utils/boost_idb/boost/date_time/posix_time/time_formatters.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/time_formatters.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2010-01-10 11:17:23 -0800 (Sun, 10 Jan 2010) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #include diff --git a/utils/boost_idb/boost/date_time/posix_time/time_formatters_limited.hpp b/utils/boost_idb/boost/date_time/posix_time/time_formatters_limited.hpp index 8d2ebdce..d0e959e9 100644 --- a/utils/boost_idb/boost/date_time/posix_time/time_formatters_limited.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/time_formatters_limited.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2010-01-10 11:17:23 -0800 (Sun, 10 Jan 2010) $ + * $Date: 2010-01-10 14:17:23 -0500 (Sun, 10 Jan 2010) $ */ #include diff --git a/utils/boost_idb/boost/date_time/posix_time/time_parsers.hpp b/utils/boost_idb/boost/date_time/posix_time/time_parsers.hpp index 3dc02b18..8a352f6e 100644 --- a/utils/boost_idb/boost/date_time/posix_time/time_parsers.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/time_parsers.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/gregorian/gregorian.hpp" diff --git a/utils/boost_idb/boost/date_time/posix_time/time_period.hpp b/utils/boost_idb/boost/date_time/posix_time/time_period.hpp index 11f81207..cb7bf07f 100644 --- a/utils/boost_idb/boost/date_time/posix_time/time_period.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/time_period.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/period.hpp" diff --git a/utils/boost_idb/boost/date_time/posix_time/time_serialize.hpp b/utils/boost_idb/boost/date_time/posix_time/time_serialize.hpp index c9038f19..039763e0 100644 --- a/utils/boost_idb/boost/date_time/posix_time/time_serialize.hpp +++ b/utils/boost_idb/boost/date_time/posix_time/time_serialize.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-30 16:25:22 -0700 (Sun, 30 Sep 2012) $ + * $Date: 2010-11-11 15:19:38 -0500 (Thu, 11 Nov 2010) $ */ #include "boost/date_time/posix_time/posix_time.hpp" @@ -46,10 +46,10 @@ void save(Archive & ar, ar & make_nvp("sv_time_duration", s); } else { - posix_time::time_duration::hour_type h = td.hours(); - posix_time::time_duration::min_type m = td.minutes(); - posix_time::time_duration::sec_type s = td.seconds(); - posix_time::time_duration::fractional_seconds_type fs = td.fractional_seconds(); + typename posix_time::time_duration::hour_type h = td.hours(); + typename posix_time::time_duration::min_type m = td.minutes(); + typename posix_time::time_duration::sec_type s = td.seconds(); + typename posix_time::time_duration::fractional_seconds_type fs = td.fractional_seconds(); ar & make_nvp("time_duration_hours", h); ar & make_nvp("time_duration_minutes", m); ar & make_nvp("time_duration_seconds", s); @@ -76,10 +76,10 @@ void load(Archive & ar, td = posix_time::time_duration(sv); } else { - posix_time::time_duration::hour_type h(0); - posix_time::time_duration::min_type m(0); - posix_time::time_duration::sec_type s(0); - posix_time::time_duration::fractional_seconds_type fs(0); + typename posix_time::time_duration::hour_type h(0); + typename posix_time::time_duration::min_type m(0); + typename posix_time::time_duration::sec_type s(0); + typename posix_time::time_duration::fractional_seconds_type fs(0); ar & make_nvp("time_duration_hours", h); ar & make_nvp("time_duration_minutes", m); ar & make_nvp("time_duration_seconds", s); @@ -104,10 +104,10 @@ void save(Archive & ar, { // from_iso_string does not include fractional seconds // therefore date and time_duration are used - posix_time::ptime::date_type d = pt.date(); + typename posix_time::ptime::date_type d = pt.date(); ar & make_nvp("ptime_date", d); if(!pt.is_special()) { - posix_time::ptime::time_duration_type td = pt.time_of_day(); + typename posix_time::ptime::time_duration_type td = pt.time_of_day(); ar & make_nvp("ptime_time_duration", td); } } @@ -123,8 +123,8 @@ void load(Archive & ar, { // from_iso_string does not include fractional seconds // therefore date and time_duration are used - posix_time::ptime::date_type d(posix_time::not_a_date_time); - posix_time::ptime::time_duration_type td; + typename posix_time::ptime::date_type d(posix_time::not_a_date_time); + typename posix_time::ptime::time_duration_type td; ar & make_nvp("ptime_date", d); if(!d.is_special()) { ar & make_nvp("ptime_time_duration", td); @@ -184,7 +184,7 @@ void load(Archive & ar, //!override needed b/c no default constructor template -inline void load_construct_data(Archive & /*ar*/, +inline void load_construct_data(Archive & ar, boost::posix_time::time_period* tp, const unsigned int /*file_version*/) { diff --git a/utils/boost_idb/boost/date_time/special_defs.hpp b/utils/boost_idb/boost/date_time/special_defs.hpp index 661814ec..56eb6fea 100644 --- a/utils/boost_idb/boost/date_time/special_defs.hpp +++ b/utils/boost_idb/boost/date_time/special_defs.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ namespace boost { diff --git a/utils/boost_idb/boost/date_time/special_values_formatter.hpp b/utils/boost_idb/boost/date_time/special_values_formatter.hpp index 53fe9845..33542b6e 100644 --- a/utils/boost_idb/boost/date_time/special_values_formatter.hpp +++ b/utils/boost_idb/boost/date_time/special_values_formatter.hpp @@ -7,7 +7,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/string_convert.hpp b/utils/boost_idb/boost/date_time/string_convert.hpp index a3cc86c2..54a979c7 100644 --- a/utils/boost_idb/boost/date_time/string_convert.hpp +++ b/utils/boost_idb/boost/date_time/string_convert.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/date_time/compiler_config.hpp" diff --git a/utils/boost_idb/boost/date_time/string_parse_tree.hpp b/utils/boost_idb/boost/date_time/string_parse_tree.hpp index d67bf6b7..0d515ff8 100644 --- a/utils/boost_idb/boost/date_time/string_parse_tree.hpp +++ b/utils/boost_idb/boost/date_time/string_parse_tree.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/strings_from_facet.hpp b/utils/boost_idb/boost/date_time/strings_from_facet.hpp index ccc78ef0..2bc26fb3 100644 --- a/utils/boost_idb/boost/date_time/strings_from_facet.hpp +++ b/utils/boost_idb/boost/date_time/strings_from_facet.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2013-09-21 13:17:00 -0700 (Sat, 21 Sep 2013) $ + * $Date: 2009-02-01 06:29:43 -0500 (Sun, 01 Feb 2009) $ */ #include @@ -50,9 +50,8 @@ gather_month_strings(const std::locale& locale, bool short_strings=true) //grab the needed strings by using the locale to //output each month const charT* p_outfmt = outfmt.c_str(), *p_outfmt_end = p_outfmt + outfmt.size(); - tm tm_value; - memset(&tm_value, 0, sizeof(tm_value)); for (int m=0; m < 12; m++) { + tm tm_value; tm_value.tm_mon = m; stringstream_type ss; ostream_iter_type oitr(ss); @@ -104,9 +103,8 @@ gather_weekday_strings(const std::locale& locale, bool short_strings=true) //grab the needed strings by using the locale to //output each month / weekday const charT* p_outfmt = outfmt.c_str(), *p_outfmt_end = p_outfmt + outfmt.size(); - tm tm_value; - memset(&tm_value, 0, sizeof(tm_value)); for (int i=0; i < 7; i++) { + tm tm_value; tm_value.tm_wday = i; stringstream_type ss; ostream_iter_type oitr(ss); diff --git a/utils/boost_idb/boost/date_time/time.hpp b/utils/boost_idb/boost/date_time/time.hpp index 8b21144b..6a6cbe1f 100644 --- a/utils/boost_idb/boost/date_time/time.hpp +++ b/utils/boost_idb/boost/date_time/time.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/time_clock.hpp b/utils/boost_idb/boost/date_time/time_clock.hpp index 9aa2ff0e..1ea5d2e8 100644 --- a/utils/boost_idb/boost/date_time/time_clock.hpp +++ b/utils/boost_idb/boost/date_time/time_clock.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ /*! @file time_clock.hpp diff --git a/utils/boost_idb/boost/date_time/time_defs.hpp b/utils/boost_idb/boost/date_time/time_defs.hpp index d74631d5..55fe42a5 100644 --- a/utils/boost_idb/boost/date_time/time_defs.hpp +++ b/utils/boost_idb/boost/date_time/time_defs.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/time_duration.hpp b/utils/boost_idb/boost/date_time/time_duration.hpp index fc3660b7..2fd25901 100644 --- a/utils/boost_idb/boost/date_time/time_duration.hpp +++ b/utils/boost_idb/boost/date_time/time_duration.hpp @@ -2,16 +2,15 @@ #define DATE_TIME_TIME_DURATION_HPP___ /* Copyright (c) 2002,2003 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-10-10 12:05:03 -0700 (Wed, 10 Oct 2012) $ + * $Date: 2009-06-04 04:24:49 -0400 (Thu, 04 Jun 2009) $ */ #include #include -#include #include #include #include @@ -180,7 +179,7 @@ namespace date_time { return duration_type(ticks_); } //! Division operations on a duration with an integer. - duration_type operator/=(int divisor) + duration_type operator/=(int divisor) { ticks_ = ticks_ / divisor; return duration_type(ticks_); @@ -252,7 +251,7 @@ namespace date_time { } protected: - explicit time_duration(impl_type in) : ticks_(in) {} + explicit time_duration(impl_type in) : ticks_(in) {}; impl_type ticks_; }; @@ -266,20 +265,10 @@ namespace date_time { class subsecond_duration : public base_duration { public: - typedef typename base_duration::impl_type impl_type; typedef typename base_duration::traits_type traits_type; - - private: - // To avoid integer overflow we precompute the duration resolution conversion coefficient (ticket #3471) - BOOST_STATIC_ASSERT_MSG((traits_type::ticks_per_second >= frac_of_second ? traits_type::ticks_per_second % frac_of_second : frac_of_second % traits_type::ticks_per_second) == 0,\ - "The base duration resolution must be a multiple of the subsecond duration resolution"); - BOOST_STATIC_CONSTANT(boost::int64_t, adjustment_ratio = (traits_type::ticks_per_second >= frac_of_second ? traits_type::ticks_per_second / frac_of_second : frac_of_second / traits_type::ticks_per_second)); - - public: explicit subsecond_duration(boost::int64_t ss) : - base_duration(impl_type(traits_type::ticks_per_second >= frac_of_second ? ss * adjustment_ratio : ss / adjustment_ratio)) - { - } + base_duration(0,0,0,ss*traits_type::res_adjust()/frac_of_second) + {} }; diff --git a/utils/boost_idb/boost/date_time/time_facet.hpp b/utils/boost_idb/boost/date_time/time_facet.hpp index 4400b49b..a456db94 100644 --- a/utils/boost_idb/boost/date_time/time_facet.hpp +++ b/utils/boost_idb/boost/date_time/time_facet.hpp @@ -7,7 +7,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Martin Andrian, Jeff Garland, Bart Garst - * $Date: 2013-10-15 08:22:02 -0700 (Tue, 15 Oct 2013) $ + * $Date: 2010-06-09 12:39:31 -0400 (Wed, 09 Jun 2010) $ */ #include @@ -244,22 +244,22 @@ namespace date_time { #endif //! sets default formats for ptime, local_date_time, and time_duration - explicit time_facet(::size_t ref_arg = 0) - : base_type(default_time_format, period_formatter_type(), special_values_formatter_type(), date_gen_formatter_type(), ref_arg), + explicit time_facet(::size_t a_ref = 0) + : base_type(default_time_format, period_formatter_type(), special_values_formatter_type(), date_gen_formatter_type(), a_ref), m_time_duration_format(string_type(duration_sign_negative_only) + default_time_duration_format) {} //! Construct the facet with an explicitly specified format - explicit time_facet(const char_type* format_arg, - period_formatter_type period_formatter_arg = period_formatter_type(), + explicit time_facet(const char_type* a_format, + period_formatter_type period_formatter = period_formatter_type(), const special_values_formatter_type& special_value_formatter = special_values_formatter_type(), date_gen_formatter_type dg_formatter = date_gen_formatter_type(), - ::size_t ref_arg = 0) - : base_type(format_arg, - period_formatter_arg, + ::size_t a_ref = 0) + : base_type(a_format, + period_formatter, special_value_formatter, dg_formatter, - ref_arg), + a_ref), m_time_duration_format(string_type(duration_sign_negative_only) + default_time_duration_format) {} @@ -278,56 +278,56 @@ namespace date_time { this->m_format = iso_time_format_extended_specifier; } - OutItrT put(OutItrT next_arg, - std::ios_base& ios_arg, - char_type fill_arg, - const time_type& time_arg) const + OutItrT put(OutItrT a_next, + std::ios_base& a_ios, + char_type a_fill, + const time_type& a_time) const { - if (time_arg.is_special()) { - return this->do_put_special(next_arg, ios_arg, fill_arg, - time_arg.date().as_special()); + if (a_time.is_special()) { + return this->do_put_special(a_next, a_ios, a_fill, + a_time.date().as_special()); } - string_type local_format(this->m_format); + string_type format(this->m_format); // %T and %R have to be replaced here since they are not standard - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, boost::as_literal(formats_type::full_24_hour_time_format), boost::as_literal(formats_type::full_24_hour_time_expanded_format)); - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, boost::as_literal(formats_type::short_24_hour_time_format), boost::as_literal(formats_type::short_24_hour_time_expanded_format)); string_type frac_str; - if (local_format.find(seconds_with_fractional_seconds_format) != string_type::npos) { + if (format.find(seconds_with_fractional_seconds_format) != string_type::npos) { // replace %s with %S.nnn frac_str = - fractional_seconds_as_string(time_arg.time_of_day(), false); - char_type sep = std::use_facet >(ios_arg.getloc()).decimal_point(); + fractional_seconds_as_string(a_time.time_of_day(), false); + char_type sep = std::use_facet >(a_ios.getloc()).decimal_point(); string_type replace_string(seconds_format); replace_string += sep; replace_string += frac_str; - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, seconds_with_fractional_seconds_format, replace_string); } /* NOTE: replacing posix_zone_string_format must be done BEFORE * zone_name_format: "%ZP" & "%Z", if Z is checked first it will * incorrectly replace a zone_name where a posix_string should go */ - if (local_format.find(posix_zone_string_format) != string_type::npos) { - if(time_arg.zone_abbrev().empty()) { + if (format.find(posix_zone_string_format) != string_type::npos) { + if(a_time.zone_abbrev().empty()) { // if zone_abbrev() returns an empty string, we want to // erase posix_zone_string_format from format - boost::algorithm::erase_all(local_format, posix_zone_string_format); + boost::algorithm::erase_all(format, posix_zone_string_format); } else{ - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, posix_zone_string_format, - time_arg.zone_as_posix_string()); + a_time.zone_as_posix_string()); } } - if (local_format.find(zone_name_format) != string_type::npos) { - if(time_arg.zone_name().empty()) { + if (format.find(zone_name_format) != string_type::npos) { + if(a_time.zone_name().empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ @@ -336,16 +336,16 @@ namespace date_time { // erase zone_name_format & one preceeding space std::basic_ostringstream ss; ss << ' ' << zone_name_format; - boost::algorithm::erase_all(local_format, ss.str()); + boost::algorithm::erase_all(format, ss.str()); } else{ - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, zone_name_format, - time_arg.zone_name()); + a_time.zone_name()); } } - if (local_format.find(zone_abbrev_format) != string_type::npos) { - if(time_arg.zone_abbrev(false).empty()) { + if (format.find(zone_abbrev_format) != string_type::npos) { + if(a_time.zone_abbrev(false).empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ @@ -354,93 +354,93 @@ namespace date_time { // erase zone_abbrev_format & one preceeding space std::basic_ostringstream ss; ss << ' ' << zone_abbrev_format; - boost::algorithm::erase_all(local_format, ss.str()); + boost::algorithm::erase_all(format, ss.str()); } else{ - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, zone_abbrev_format, - time_arg.zone_abbrev(false)); + a_time.zone_abbrev(false)); } } - if (local_format.find(zone_iso_extended_format) != string_type::npos) { - if(time_arg.zone_name(true).empty()) { + if (format.find(zone_iso_extended_format) != string_type::npos) { + if(a_time.zone_name(true).empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ // if zone_name() returns an empty string, we want to // erase zone_iso_extended_format from format - boost::algorithm::erase_all(local_format, zone_iso_extended_format); + boost::algorithm::erase_all(format, zone_iso_extended_format); } else{ - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, zone_iso_extended_format, - time_arg.zone_name(true)); + a_time.zone_name(true)); } } - if (local_format.find(zone_iso_format) != string_type::npos) { - if(time_arg.zone_abbrev(true).empty()) { + if (format.find(zone_iso_format) != string_type::npos) { + if(a_time.zone_abbrev(true).empty()) { /* TODO: this'll probably create problems if a user places * the zone_*_format flag in the format with a ptime. This * code removes the flag from the default formats */ // if zone_abbrev() returns an empty string, we want to // erase zone_iso_format from format - boost::algorithm::erase_all(local_format, zone_iso_format); + boost::algorithm::erase_all(format, zone_iso_format); } else{ - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, zone_iso_format, - time_arg.zone_abbrev(true)); + a_time.zone_abbrev(true)); } } - if (local_format.find(fractional_seconds_format) != string_type::npos) { + if (format.find(fractional_seconds_format) != string_type::npos) { // replace %f with nnnnnnn if (frac_str.empty()) { - frac_str = fractional_seconds_as_string(time_arg.time_of_day(), false); + frac_str = fractional_seconds_as_string(a_time.time_of_day(), false); } - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, fractional_seconds_format, frac_str); } - if (local_format.find(fractional_seconds_or_none_format) != string_type::npos) { + if (format.find(fractional_seconds_or_none_format) != string_type::npos) { // replace %F with nnnnnnn or nothing if fs == 0 frac_str = - fractional_seconds_as_string(time_arg.time_of_day(), true); + fractional_seconds_as_string(a_time.time_of_day(), true); if (frac_str.size()) { - char_type sep = std::use_facet >(ios_arg.getloc()).decimal_point(); + char_type sep = std::use_facet >(a_ios.getloc()).decimal_point(); string_type replace_string; replace_string += sep; replace_string += frac_str; - boost::algorithm::replace_all(local_format, + boost::algorithm::replace_all(format, fractional_seconds_or_none_format, replace_string); } else { - boost::algorithm::erase_all(local_format, + boost::algorithm::erase_all(format, fractional_seconds_or_none_format); } } - return this->do_put_tm(next_arg, ios_arg, fill_arg, - to_tm(time_arg), local_format); + return this->do_put_tm(a_next, a_ios, a_fill, + to_tm(a_time), format); } //! put function for time_duration - OutItrT put(OutItrT next_arg, - std::ios_base& ios_arg, - char_type fill_arg, - const time_duration_type& time_dur_arg) const + OutItrT put(OutItrT a_next, + std::ios_base& a_ios, + char_type a_fill, + const time_duration_type& a_time_dur) const { - if (time_dur_arg.is_special()) { - return this->do_put_special(next_arg, ios_arg, fill_arg, - time_dur_arg.get_rep().as_special()); + if (a_time_dur.is_special()) { + return this->do_put_special(a_next, a_ios, a_fill, + a_time_dur.get_rep().as_special()); } string_type format(m_time_duration_format); - if (time_dur_arg.is_negative()) { + if (a_time_dur.is_negative()) { // replace %- with minus sign. Should we use the numpunct facet? boost::algorithm::replace_all(format, duration_sign_negative_only, @@ -477,7 +477,7 @@ namespace date_time { */ string_type hours_str; if (format.find(unrestricted_hours_format) != string_type::npos) { - hours_str = hours_as_string(time_dur_arg); + hours_str = hours_as_string(a_time_dur); boost::algorithm::replace_all(format, unrestricted_hours_format, hours_str); } // We still have to process restricted hours format specifier. In order to @@ -485,7 +485,7 @@ namespace date_time { // restrict the stringified hours length to 2 characters. if (format.find(hours_format) != string_type::npos) { if (hours_str.empty()) - hours_str = hours_as_string(time_dur_arg); + hours_str = hours_as_string(a_time_dur); BOOST_ASSERT(hours_str.length() <= 2); boost::algorithm::replace_all(format, hours_format, hours_str); } @@ -494,8 +494,8 @@ namespace date_time { if (format.find(seconds_with_fractional_seconds_format) != string_type::npos) { // replace %s with %S.nnn frac_str = - fractional_seconds_as_string(time_dur_arg, false); - char_type sep = std::use_facet >(ios_arg.getloc()).decimal_point(); + fractional_seconds_as_string(a_time_dur, false); + char_type sep = std::use_facet >(a_ios.getloc()).decimal_point(); string_type replace_string(seconds_format); replace_string += sep; @@ -507,7 +507,7 @@ namespace date_time { if (format.find(fractional_seconds_format) != string_type::npos) { // replace %f with nnnnnnn if (!frac_str.size()) { - frac_str = fractional_seconds_as_string(time_dur_arg, false); + frac_str = fractional_seconds_as_string(a_time_dur, false); } boost::algorithm::replace_all(format, fractional_seconds_format, @@ -517,9 +517,9 @@ namespace date_time { if (format.find(fractional_seconds_or_none_format) != string_type::npos) { // replace %F with nnnnnnn or nothing if fs == 0 frac_str = - fractional_seconds_as_string(time_dur_arg, true); + fractional_seconds_as_string(a_time_dur, true); if (frac_str.size()) { - char_type sep = std::use_facet >(ios_arg.getloc()).decimal_point(); + char_type sep = std::use_facet >(a_ios.getloc()).decimal_point(); string_type replace_string; replace_string += sep; replace_string += frac_str; @@ -533,14 +533,14 @@ namespace date_time { } } - return this->do_put_tm(next_arg, ios_arg, fill_arg, - to_tm(time_dur_arg), format); + return this->do_put_tm(a_next, a_ios, a_fill, + to_tm(a_time_dur), format); } - OutItrT put(OutItrT next, std::ios_base& ios_arg, + OutItrT put(OutItrT next, std::ios_base& a_ios, char_type fill, const period_type& p) const { - return this->m_period_formatter.put_period(next, ios_arg, fill,p,*this); + return this->m_period_formatter.put_period(next, a_ios, fill,p,*this); } @@ -548,11 +548,11 @@ namespace date_time { static string_type - fractional_seconds_as_string(const time_duration_type& time_arg, + fractional_seconds_as_string(const time_duration_type& a_time, bool null_when_zero) { typename time_duration_type::fractional_seconds_type frac_sec = - time_arg.fractional_seconds(); + a_time.fractional_seconds(); if (null_when_zero && (frac_sec == 0)) { return string_type(); @@ -566,9 +566,9 @@ namespace date_time { static string_type - hours_as_string(const time_duration_type& time_arg, int width = 2) + hours_as_string(const time_duration_type& a_time, int width = 2) { - return integral_as_string(date_time::absolute_value(time_arg.hours()), width); + return integral_as_string(date_time::absolute_value(a_time.hours()), width); } template< typename IntT > @@ -731,8 +731,8 @@ namespace date_time { static std::locale::id id; //! Constructor that takes a format string for a ptime - explicit time_input_facet(const string_type& format, ::size_t ref_arg = 0) - : base_type(format, ref_arg), + explicit time_input_facet(const string_type& format, ::size_t a_ref = 0) + : base_type(format, a_ref), m_time_duration_format(default_time_duration_format) { } @@ -741,19 +741,19 @@ namespace date_time { const special_values_parser_type& sv_parser, const period_parser_type& per_parser, const date_gen_parser_type& date_gen_parser, - ::size_t ref_arg = 0) + ::size_t a_ref = 0) : base_type(format, date_parser, sv_parser, per_parser, date_gen_parser, - ref_arg), + a_ref), m_time_duration_format(default_time_duration_format) {} //! sets default formats for ptime, local_date_time, and time_duration - explicit time_input_facet(::size_t ref_arg = 0) - : base_type(default_time_input_format, ref_arg), + explicit time_input_facet(::size_t a_ref = 0) + : base_type(default_time_input_format, a_ref), m_time_duration_format(default_time_duration_format) { } @@ -772,12 +772,12 @@ namespace date_time { InItrT get(InItrT& sitr, InItrT& stream_end, - std::ios_base& ios_arg, + std::ios_base& a_ios, period_type& p) const { p = this->m_period_parser.get_period(sitr, stream_end, - ios_arg, + a_ios, p, time_duration_type::unit(), *this); @@ -789,7 +789,7 @@ namespace date_time { InItrT get(InItrT& sitr, InItrT& stream_end, - std::ios_base& ios_arg, + std::ios_base& a_ios, time_duration_type& td) const { // skip leading whitespace @@ -813,16 +813,16 @@ namespace date_time { typename time_duration_type::fractional_seconds_type frac(0); typedef std::num_get num_get; - if(!std::has_facet(ios_arg.getloc())) { + if(!std::has_facet(a_ios.getloc())) { num_get* ng = new num_get(); - std::locale loc = std::locale(ios_arg.getloc(), ng); - ios_arg.imbue(loc); + std::locale loc = std::locale(a_ios.getloc(), ng); + a_ios.imbue(loc); } const_itr itr(m_time_duration_format.begin()); while (itr != m_time_duration_format.end() && (sitr != stream_end)) { if (*itr == '%') { - if (++itr == m_time_duration_format.end()) break; + ++itr; if (*itr != '%') { switch(*itr) { case 'O': @@ -928,27 +928,27 @@ namespace date_time { //! Parses a time object from the input stream InItrT get(InItrT& sitr, InItrT& stream_end, - std::ios_base& ios_arg, + std::ios_base& a_ios, time_type& t) const { string_type tz_str; - return get(sitr, stream_end, ios_arg, t, tz_str, false); + return get(sitr, stream_end, a_ios, t, tz_str, false); } //! Expects a time_zone in the input stream InItrT get_local_time(InItrT& sitr, InItrT& stream_end, - std::ios_base& ios_arg, + std::ios_base& a_ios, time_type& t, string_type& tz_str) const { - return get(sitr, stream_end, ios_arg, t, tz_str, true); + return get(sitr, stream_end, a_ios, t, tz_str, true); } protected: InItrT get(InItrT& sitr, InItrT& stream_end, - std::ios_base& ios_arg, + std::ios_base& a_ios, time_type& t, string_type& tz_str, bool time_is_local) const @@ -985,16 +985,16 @@ namespace date_time { day_type t_day(1); typedef std::num_get num_get; - if(!std::has_facet(ios_arg.getloc())) { + if(!std::has_facet(a_ios.getloc())) { num_get* ng = new num_get(); - std::locale loc = std::locale(ios_arg.getloc(), ng); - ios_arg.imbue(loc); + std::locale loc = std::locale(a_ios.getloc(), ng); + a_ios.imbue(loc); } const_itr itr(this->m_format.begin()); while (itr != this->m_format.end() && (sitr != stream_end)) { if (*itr == '%') { - if (++itr == this->m_format.end()) break; + ++itr; if (*itr != '%') { // the cases are grouped by date & time flags - not alphabetical order switch(*itr) { diff --git a/utils/boost_idb/boost/date_time/time_formatting_streams.hpp b/utils/boost_idb/boost/date_time/time_formatting_streams.hpp index 2d07d344..3537c103 100644 --- a/utils/boost_idb/boost/date_time/time_formatting_streams.hpp +++ b/utils/boost_idb/boost/date_time/time_formatting_streams.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-12 11:37:53 -0800 (Wed, 12 Nov 2008) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/time_iterator.hpp b/utils/boost_idb/boost/date_time/time_iterator.hpp index 4c33f39e..2258a330 100644 --- a/utils/boost_idb/boost/date_time/time_iterator.hpp +++ b/utils/boost_idb/boost/date_time/time_iterator.hpp @@ -2,50 +2,50 @@ #define DATE_TIME_TIME_ITERATOR_HPP___ /* Copyright (c) 2002,2003 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ namespace boost { namespace date_time { - + //! Simple time iterator skeleton class template class time_itr { public: typedef typename time_type::time_duration_type time_duration_type; - time_itr(time_type t, time_duration_type d) : current_(t), offset_(d) {} - time_itr& operator++() + time_itr(time_type t, time_duration_type d) : current_(t), offset_(d) {}; + time_itr& operator++() { current_ = current_ + offset_; return *this; } - time_itr& operator--() + time_itr& operator--() { current_ = current_ - offset_; return *this; } - time_type operator*() {return current_;} - time_type* operator->() {return ¤t_;} - bool operator< (const time_type& t) {return current_ < t;} - bool operator<= (const time_type& t) {return current_ <= t;} - bool operator!= (const time_type& t) {return current_ != t;} - bool operator== (const time_type& t) {return current_ == t;} - bool operator> (const time_type& t) {return current_ > t;} - bool operator>= (const time_type& t) {return current_ >= t;} - + time_type operator*() {return current_;}; + time_type* operator->() {return ¤t_;}; + bool operator< (const time_type& t) {return current_ < t;}; + bool operator<= (const time_type& t) {return current_ <= t;}; + bool operator!= (const time_type& t) {return current_ != t;}; + bool operator== (const time_type& t) {return current_ == t;}; + bool operator> (const time_type& t) {return current_ > t;}; + bool operator>= (const time_type& t) {return current_ >= t;}; + private: time_type current_; time_duration_type offset_; }; + - - + } }//namespace date_time diff --git a/utils/boost_idb/boost/date_time/time_parsing.hpp b/utils/boost_idb/boost/date_time/time_parsing.hpp index 7b71de0d..dfccf6a1 100644 --- a/utils/boost_idb/boost/date_time/time_parsing.hpp +++ b/utils/boost_idb/boost/date_time/time_parsing.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-10-10 12:05:03 -0700 (Wed, 10 Oct 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "boost/tokenizer.hpp" @@ -116,7 +116,6 @@ namespace date_time { break; } - default: break; }//switch pos++; } @@ -154,10 +153,9 @@ namespace date_time { std::string& first, std::string& second) { - std::string::size_type sep_pos = s.find(sep); + int sep_pos = static_cast(s.find(sep)); first = s.substr(0,sep_pos); - if (sep_pos!=std::string::npos) - second = s.substr(sep_pos+1); + second = s.substr(sep_pos+1); return true; } @@ -282,7 +280,6 @@ namespace date_time { break; } - default: break; }; pos++; } diff --git a/utils/boost_idb/boost/date_time/time_resolution_traits.hpp b/utils/boost_idb/boost/date_time/time_resolution_traits.hpp index 903830c7..658f3d20 100644 --- a/utils/boost_idb/boost/date_time/time_resolution_traits.hpp +++ b/utils/boost_idb/boost/date_time/time_resolution_traits.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2009-06-06 04:25:55 -0700 (Sat, 06 Jun 2009) $ + * $Date: 2009-06-06 07:25:55 -0400 (Sat, 06 Jun 2009) $ */ diff --git a/utils/boost_idb/boost/date_time/time_system_counted.hpp b/utils/boost_idb/boost/date_time/time_system_counted.hpp index 5425f62a..fa883907 100644 --- a/utils/boost_idb/boost/date_time/time_system_counted.hpp +++ b/utils/boost_idb/boost/date_time/time_system_counted.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/time_system_split.hpp b/utils/boost_idb/boost/date_time/time_system_split.hpp index 6fc4a336..08ea1ec2 100644 --- a/utils/boost_idb/boost/date_time/time_system_split.hpp +++ b/utils/boost_idb/boost/date_time/time_system_split.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2008-11-13 12:10:23 -0800 (Thu, 13 Nov 2008) $ + * $Date: 2008-11-13 15:10:23 -0500 (Thu, 13 Nov 2008) $ */ diff --git a/utils/boost_idb/boost/date_time/time_zone_base.hpp b/utils/boost_idb/boost/date_time/time_zone_base.hpp index f239d545..0d3cb903 100644 --- a/utils/boost_idb/boost/date_time/time_zone_base.hpp +++ b/utils/boost_idb/boost/date_time/time_zone_base.hpp @@ -2,10 +2,10 @@ #define _DATE_TIME_TIME_ZONE_BASE__ /* Copyright (c) 2003-2005 CrystalClear Software, Inc. - * Subject to the Boost Software License, Version 1.0. + * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ @@ -26,9 +26,9 @@ namespace date_time { * would be to convert from POSIX timezone strings. Regardless of * the construction technique, this is the interface that these * time zone types must provide. - * + * * Note that this class is intended to be used as a shared - * resource (hence the derivation from boost::counted_base. + * resource (hence the derivation from boost::counted_base. */ template class time_zone_base { @@ -39,8 +39,8 @@ namespace date_time { typedef typename time_type::date_type::year_type year_type; typedef typename time_type::time_duration_type time_duration_type; - time_zone_base() {} - virtual ~time_zone_base() {} + time_zone_base() {}; + virtual ~time_zone_base() {}; //!String for the timezone when in daylight savings (eg: EDT) virtual string_type dst_zone_abbrev() const=0; //!String for the zone when not in daylight savings (eg: EST) @@ -61,9 +61,9 @@ namespace date_time { virtual time_duration_type dst_offset() const=0; //! Returns a POSIX time_zone string for this object virtual string_type to_posix_string() const =0; - + private: - + }; @@ -82,7 +82,7 @@ namespace date_time { dst_start_offset_(dst_start_offset), dst_end_offset_(dst_end_offset) {} - + //! Amount DST adjusts the clock eg: plus one hour time_duration_type dst_adjust_; //! Time past midnight on start transition day that dst starts diff --git a/utils/boost_idb/boost/date_time/time_zone_names.hpp b/utils/boost_idb/boost/date_time/time_zone_names.hpp index a5650270..05260c71 100644 --- a/utils/boost_idb/boost/date_time/time_zone_names.hpp +++ b/utils/boost_idb/boost/date_time/time_zone_names.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include diff --git a/utils/boost_idb/boost/date_time/tz_db_base.hpp b/utils/boost_idb/boost/date_time/tz_db_base.hpp index 793e51f5..24401154 100644 --- a/utils/boost_idb/boost/date_time/tz_db_base.hpp +++ b/utils/boost_idb/boost/date_time/tz_db_base.hpp @@ -5,7 +5,7 @@ * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2013-09-21 13:17:00 -0700 (Sat, 21 Sep 2013) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ #include @@ -166,16 +166,6 @@ namespace boost { //! Constructs an empty database tz_db_base() {} - //! Process csv data file, may throw exceptions - /*! May throw bad_field_count exceptions */ - void load_from_stream(std::istream &in) - { - std::string buff; - while( std::getline(in, buff)) { - parse_string(buff); - } - } - //! Process csv data file, may throw exceptions /*! May throw data_not_accessible, or bad_field_count exceptions */ void load_from_file(const std::string& pathspec) @@ -188,7 +178,10 @@ namespace boost { boost::throw_exception(data_not_accessible(pathspec)); } std::getline(ifs, buff); // first line is column headings - this->load_from_stream(ifs); + + while( std::getline(ifs, buff)) { + parse_string(buff); + } } //! returns true if record successfully added to map @@ -301,15 +294,7 @@ namespace boost { const char_type sep_char[] = { ';', '\0'}; char_separator_type sep(sep_char); tokenizer tokens(rule, sep); // 3 fields - - if ( std::distance ( tokens.begin(), tokens.end ()) != 3 ) { - std::ostringstream msg; - msg << "Expecting 3 fields, got " - << std::distance ( tokens.begin(), tokens.end ()) - << " fields in line: " << rule; - boost::throw_exception(bad_field_count(msg.str())); - } - + tokenizer_iterator tok_iter = tokens.begin(); nth = std::atoi(tok_iter->c_str()); ++tok_iter; d = std::atoi(tok_iter->c_str()); ++tok_iter; diff --git a/utils/boost_idb/boost/date_time/wrapping_int.hpp b/utils/boost_idb/boost/date_time/wrapping_int.hpp index e6f87d52..969b078a 100644 --- a/utils/boost_idb/boost/date_time/wrapping_int.hpp +++ b/utils/boost_idb/boost/date_time/wrapping_int.hpp @@ -2,11 +2,11 @@ #define _DATE_TIME_WRAPPING_INT_HPP__ /* Copyright (c) 2002,2003,2005 CrystalClear Software, Inc. - * Use, modification and distribution is subject to the + * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst - * $Date: 2012-09-22 15:33:33 -0700 (Sat, 22 Sep 2012) $ + * $Date: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $ */ @@ -16,15 +16,15 @@ namespace date_time { //! A wrapping integer used to support time durations (WARNING: only instantiate with a signed type) /*! In composite date and time types this type is used to * wrap at the day boundary. - * Ex: - * A wrapping_int will roll over after nine, and + * Ex: + * A wrapping_int will roll over after nine, and * roll under below zero. This gives a range of [0,9] * - * NOTE: it is strongly recommended that wrapping_int2 be used - * instead of wrapping_int as wrapping_int is to be depricated + * NOTE: it is strongly recommended that wrapping_int2 be used + * instead of wrapping_int as wrapping_int is to be depricated * at some point soon. * - * Also Note that warnings will occur if instantiated with an + * Also Note that warnings will occur if instantiated with an * unsigned type. Only a signed type should be used! */ template @@ -34,17 +34,17 @@ class wrapping_int { //typedef overflow_type_ overflow_type; static int_type wrap_value() {return wrap_val;} //!Add, return true if wrapped - wrapping_int(int_type v) : value_(v) {} + wrapping_int(int_type v) : value_(v) {}; //! Explicit converion method int_type as_int() const {return value_;} operator int_type() const {return value_;} //!Add, return number of wraps performed - /*! The sign of the returned value will indicate which direction the + /*! The sign of the returned value will indicate which direction the * wraps went. Ex: add a negative number and wrapping under could occur, - * this would be indicated by a negative return value. If wrapping over + * this would be indicated by a negative return value. If wrapping over * took place, a positive value would be returned */ template< typename IntT > - IntT add(IntT v) + IntT add(IntT v) { int_type remainder = static_cast(v % (wrap_val)); IntT overflow = static_cast(v / (wrap_val)); @@ -53,12 +53,12 @@ class wrapping_int { } //! Subtract will return '+d' if wrapping under took place ('d' is the number of wraps) /*! The sign of the returned value will indicate which direction the - * wraps went (positive indicates wrap under, negative indicates wrap over). - * Ex: subtract a negative number and wrapping over could - * occur, this would be indicated by a negative return value. If + * wraps went (positive indicates wrap under, negative indicates wrap over). + * Ex: subtract a negative number and wrapping over could + * occur, this would be indicated by a negative return value. If * wrapping under took place, a positive value would be returned. */ template< typename IntT > - IntT subtract(IntT v) + IntT subtract(IntT v) { int_type remainder = static_cast(v % (wrap_val)); IntT underflow = static_cast(-(v / (wrap_val))); @@ -71,19 +71,19 @@ class wrapping_int { template< typename IntT > IntT calculate_wrap(IntT wrap) { - if ((value_) >= wrap_val) + if ((value_) >= wrap_val) { ++wrap; value_ -= (wrap_val); } - else if(value_ < 0) + else if(value_ < 0) { --wrap; value_ += (wrap_val); } return wrap; } - + }; @@ -113,12 +113,12 @@ class wrapping_int2 { int_type as_int() const {return value_;} operator int_type() const {return value_;} //!Add, return number of wraps performed - /*! The sign of the returned value will indicate which direction the + /*! The sign of the returned value will indicate which direction the * wraps went. Ex: add a negative number and wrapping under could occur, - * this would be indicated by a negative return value. If wrapping over + * this would be indicated by a negative return value. If wrapping over * took place, a positive value would be returned */ template< typename IntT > - IntT add(IntT v) + IntT add(IntT v) { int_type remainder = static_cast(v % (wrap_max - wrap_min + 1)); IntT overflow = static_cast(v / (wrap_max - wrap_min + 1)); @@ -127,30 +127,30 @@ class wrapping_int2 { } //! Subtract will return '-d' if wrapping under took place ('d' is the number of wraps) /*! The sign of the returned value will indicate which direction the - * wraps went. Ex: subtract a negative number and wrapping over could - * occur, this would be indicated by a positive return value. If + * wraps went. Ex: subtract a negative number and wrapping over could + * occur, this would be indicated by a positive return value. If * wrapping under took place, a negative value would be returned */ template< typename IntT > - IntT subtract(IntT v) + IntT subtract(IntT v) { int_type remainder = static_cast(v % (wrap_max - wrap_min + 1)); IntT underflow = static_cast(-(v / (wrap_max - wrap_min + 1))); value_ = static_cast(value_ - remainder); return calculate_wrap(underflow); } - + private: int_type value_; template< typename IntT > IntT calculate_wrap(IntT wrap) { - if ((value_) > wrap_max) + if ((value_) > wrap_max) { ++wrap; value_ -= (wrap_max - wrap_min + 1); } - else if((value_) < wrap_min) + else if((value_) < wrap_min) { --wrap; value_ += (wrap_max - wrap_min + 1); diff --git a/utils/boost_idb/boost/date_time/year_month_day.hpp b/utils/boost_idb/boost/date_time/year_month_day.hpp index 9340e53f..802ce42e 100644 --- a/utils/boost_idb/boost/date_time/year_month_day.hpp +++ b/utils/boost_idb/boost/date_time/year_month_day.hpp @@ -6,7 +6,7 @@ * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland - * $Date: 2008-02-27 12:00:24 -0800 (Wed, 27 Feb 2008) $ + * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ namespace boost { diff --git a/utils/boost_idb/boost/detail/atomic_redef_macros.hpp b/utils/boost_idb/boost/detail/atomic_redef_macros.hpp deleted file mode 100644 index dfd15f5c..00000000 --- a/utils/boost_idb/boost/detail/atomic_redef_macros.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2013 Vicente J. Botet Escriba -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - -#if defined(BOOST_INTEL) - -#pragma pop_macro("atomic_compare_exchange") -#pragma pop_macro("atomic_compare_exchange_explicit") -#pragma pop_macro("atomic_exchange") -#pragma pop_macro("atomic_exchange_explicit") -#pragma pop_macro("atomic_is_lock_free") -#pragma pop_macro("atomic_load") -#pragma pop_macro("atomic_load_explicit") -#pragma pop_macro("atomic_store") -#pragma pop_macro("atomic_store_explicit") - -#endif // #if defined(BOOST_INTEL) diff --git a/utils/boost_idb/boost/detail/atomic_undef_macros.hpp b/utils/boost_idb/boost/detail/atomic_undef_macros.hpp deleted file mode 100644 index 18d840a7..00000000 --- a/utils/boost_idb/boost/detail/atomic_undef_macros.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2013 Vicente J. Botet Escriba -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - - -#if defined(BOOST_INTEL) - -#pragma push_macro("atomic_compare_exchange") -#undef atomic_compare_exchange - -#pragma push_macro("atomic_compare_exchange_explicit") -#undef atomic_compare_exchange_explicit - -#pragma push_macro("atomic_exchange") -#undef atomic_exchange - -#pragma push_macro("atomic_exchange_explicit") -#undef atomic_exchange_explicit - -#pragma push_macro("atomic_is_lock_free") -#undef atomic_is_lock_free - -#pragma push_macro("atomic_load") -#undef atomic_load - -#pragma push_macro("atomic_load_explicit") -#undef atomic_load_explicit - -#pragma push_macro("atomic_store") -#undef atomic_store - -#pragma push_macro("atomic_store_explicit") -#undef atomic_store_explicit - - -#endif // #if defined(BOOST_INTEL) - - diff --git a/utils/boost_idb/boost/detail/bitmask.hpp b/utils/boost_idb/boost/detail/bitmask.hpp deleted file mode 100644 index c6714a11..00000000 --- a/utils/boost_idb/boost/detail/bitmask.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// boost/detail/bitmask.hpp ------------------------------------------------// - -// Copyright Beman Dawes 2006 - -// Distributed under the Boost Software License, Version 1.0 -// http://www.boost.org/LICENSE_1_0.txt - -// Usage: enum foo { a=1, b=2, c=4 }; -// BOOST_BITMASK( foo ); -// -// void f( foo arg ); -// ... -// f( a | c ); - -#ifndef BOOST_BITMASK_HPP -#define BOOST_BITMASK_HPP - -#include - -#define BOOST_BITMASK(Bitmask) \ - \ - inline Bitmask operator| (Bitmask x , Bitmask y ) \ - { return static_cast( static_cast(x) \ - | static_cast(y)); } \ - \ - inline Bitmask operator& (Bitmask x , Bitmask y ) \ - { return static_cast( static_cast(x) \ - & static_cast(y)); } \ - \ - inline Bitmask operator^ (Bitmask x , Bitmask y ) \ - { return static_cast( static_cast(x) \ - ^ static_cast(y)); } \ - \ - inline Bitmask operator~ (Bitmask x ) \ - { return static_cast(~static_cast(x)); } \ - \ - inline Bitmask & operator&=(Bitmask & x , Bitmask y) \ - { x = x & y ; return x ; } \ - \ - inline Bitmask & operator|=(Bitmask & x , Bitmask y) \ - { x = x | y ; return x ; } \ - \ - inline Bitmask & operator^=(Bitmask & x , Bitmask y) \ - { x = x ^ y ; return x ; } - -#endif // BOOST_BITMASK_HPP - diff --git a/utils/boost_idb/boost/detail/call_traits.hpp b/utils/boost_idb/boost/detail/call_traits.hpp index 36dea000..6ad646ec 100644 --- a/utils/boost_idb/boost/detail/call_traits.hpp +++ b/utils/boost_idb/boost/detail/call_traits.hpp @@ -24,7 +24,6 @@ #include #include -#include #include #include @@ -44,26 +43,20 @@ struct ct_imp2 typedef const T param_type; }; -template +template struct ct_imp { typedef const T& param_type; }; -template -struct ct_imp -{ - typedef typename ct_imp2::param_type param_type; -}; - -template -struct ct_imp +template +struct ct_imp { typedef typename ct_imp2::param_type param_type; }; -template -struct ct_imp +template +struct ct_imp { typedef const T param_type; }; @@ -86,8 +79,7 @@ struct call_traits typedef typename boost::detail::ct_imp< T, ::boost::is_pointer::value, - ::boost::is_arithmetic::value, - ::boost::is_enum::value + ::boost::is_arithmetic::value >::param_type param_type; }; diff --git a/utils/boost_idb/boost/detail/container_fwd.hpp b/utils/boost_idb/boost/detail/container_fwd.hpp index ef174980..67c5a21c 100644 --- a/utils/boost_idb/boost/detail/container_fwd.hpp +++ b/utils/boost_idb/boost/detail/container_fwd.hpp @@ -1,92 +1,24 @@ -// Copyright 2005-2011 Daniel James. +// Copyright 2005-2008 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// Note: if you change this include guard, you also need to change -// container_fwd_compile_fail.cpp #if !defined(BOOST_DETAIL_CONTAINER_FWD_HPP) #define BOOST_DETAIL_CONTAINER_FWD_HPP -#if defined(_MSC_VER) && (_MSC_VER >= 1020) && \ - !defined(BOOST_DETAIL_TEST_CONFIG_ONLY) +#if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include #include -//////////////////////////////////////////////////////////////////////////////// -// // -// Define BOOST_DETAIL_NO_CONTAINER_FWD if you don't want this header to // -// forward declare standard containers. // -// // -// BOOST_DETAIL_CONTAINER_FWD to make it foward declare containers even if it // -// normally doesn't. // -// // -// BOOST_DETAIL_NO_CONTAINER_FWD overrides BOOST_DETAIL_CONTAINER_FWD. // -// // -//////////////////////////////////////////////////////////////////////////////// - -#if !defined(BOOST_DETAIL_NO_CONTAINER_FWD) -# if defined(BOOST_DETAIL_CONTAINER_FWD) - // Force forward declarations. -# elif defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) - // STLport -# define BOOST_DETAIL_NO_CONTAINER_FWD -# elif defined(__LIBCOMO__) - // Comeau STL: -# define BOOST_DETAIL_NO_CONTAINER_FWD -# elif defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER) - // Rogue Wave library: -# define BOOST_DETAIL_NO_CONTAINER_FWD -# elif defined(_LIBCPP_VERSION) - // libc++ -# define BOOST_DETAIL_NO_CONTAINER_FWD -# elif defined(__GLIBCPP__) || defined(__GLIBCXX__) - // GNU libstdc++ 3 - // - // Disable forwarding for all recent versions, as the library has a - // versioned namespace mode, and I don't know how to detect it. -# if __GLIBCXX__ >= 20070513 \ - || defined(_GLIBCXX_DEBUG) \ - || defined(_GLIBCXX_PARALLEL) \ - || defined(_GLIBCXX_PROFILE) -# define BOOST_DETAIL_NO_CONTAINER_FWD -# else -# if defined(__GLIBCXX__) && __GLIBCXX__ >= 20040530 -# define BOOST_CONTAINER_FWD_COMPLEX_STRUCT -# endif -# endif -# elif defined(__STL_CONFIG_H) - // generic SGI STL - // - // Forward declaration seems to be okay, but it has a couple of odd - // implementations. -# define BOOST_CONTAINER_FWD_BAD_BITSET -# if !defined(__STL_NON_TYPE_TMPL_PARAM_BUG) -# define BOOST_CONTAINER_FWD_BAD_DEQUE -# endif -# elif defined(__MSL_CPP__) - // MSL standard lib: -# define BOOST_DETAIL_NO_CONTAINER_FWD -# elif defined(__IBMCPP__) - // The default VACPP std lib, forward declaration seems to be fine. -# elif defined(MSIPL_COMPILE_H) - // Modena C++ standard library -# define BOOST_DETAIL_NO_CONTAINER_FWD -# elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER) - // Dinkumware Library (this has to appear after any possible replacement - // libraries) -# else -# define BOOST_DETAIL_NO_CONTAINER_FWD -# endif -#endif - -#if !defined(BOOST_DETAIL_TEST_CONFIG_ONLY) - -#if defined(BOOST_DETAIL_NO_CONTAINER_FWD) && \ - !defined(BOOST_DETAIL_TEST_FORCE_CONTAINER_FWD) +#if defined(BOOST_DETAIL_NO_CONTAINER_FWD) \ + || ((defined(__GLIBCPP__) || defined(__GLIBCXX__)) \ + && (defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PARALLEL))) \ + || BOOST_WORKAROUND(__BORLANDC__, > 0x551) \ + || BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x842)) \ + || (defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) #include #include @@ -101,6 +33,17 @@ #include +#if !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION) && \ + defined(__STL_CONFIG_H) + +#define BOOST_CONTAINER_FWD_BAD_BITSET + +#if !defined(__STL_NON_TYPE_TMPL_PARAM_BUG) +#define BOOST_CONTAINER_FWD_BAD_DEQUE +#endif + +#endif + #if defined(BOOST_CONTAINER_FWD_BAD_DEQUE) #include #endif @@ -120,18 +63,17 @@ namespace std template class basic_string; #if BOOST_WORKAROUND(__GNUC__, < 3) && !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION) - template struct string_char_traits; #else template struct char_traits; #endif -#if defined(BOOST_CONTAINER_FWD_COMPLEX_STRUCT) - template struct complex; -#else template class complex; -#endif +} +// gcc 3.4 and greater +namespace std +{ #if !defined(BOOST_CONTAINER_FWD_BAD_DEQUE) template class deque; #endif @@ -154,9 +96,6 @@ namespace std #pragma warning(pop) #endif -#endif // BOOST_DETAIL_NO_CONTAINER_FWD && - // !defined(BOOST_DETAIL_TEST_FORCE_CONTAINER_FWD) - -#endif // BOOST_DETAIL_TEST_CONFIG_ONLY +#endif #endif diff --git a/utils/boost_idb/boost/detail/endian.hpp b/utils/boost_idb/boost/detail/endian.hpp index 3e37db93..5f9b90ef 100644 --- a/utils/boost_idb/boost/detail/endian.hpp +++ b/utils/boost_idb/boost/detail/endian.hpp @@ -1,11 +1,76 @@ -// Copyright 2013 Redshift Software Inc +// Copyright 2005 Caleb Epstein +// Copyright 2006 John Maddock +// Copyright 2010 Rene Rivera // Distributed under the Boost Software License, Version 1.0. (See accompany- // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +/* + * Copyright (c) 1997 + * Silicon Graphics Computer Systems, Inc. + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Silicon Graphics makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + */ + +/* + * Copyright notice reproduced from , from + * which this code was originally taken. + * + * Modified by Caleb Epstein to use with GNU libc and to + * defined the BOOST_ENDIAN macro. + */ + #ifndef BOOST_DETAIL_ENDIAN_HPP #define BOOST_DETAIL_ENDIAN_HPP -// Use the Predef library for the detection of endianess. -#include +// GNU libc offers the helpful header which defines +// __BYTE_ORDER + +#if defined (__GLIBC__) +# include +# if (__BYTE_ORDER == __LITTLE_ENDIAN) +# define BOOST_LITTLE_ENDIAN +# elif (__BYTE_ORDER == __BIG_ENDIAN) +# define BOOST_BIG_ENDIAN +# elif (__BYTE_ORDER == __PDP_ENDIAN) +# define BOOST_PDP_ENDIAN +# else +# error Unknown machine endianness detected. +# endif +# define BOOST_BYTE_ORDER __BYTE_ORDER +#elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN) || \ + defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) +# define BOOST_BIG_ENDIAN +# define BOOST_BYTE_ORDER 4321 +#elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) || \ + defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +# define BOOST_LITTLE_ENDIAN +# define BOOST_BYTE_ORDER 1234 +#elif defined(__sparc) || defined(__sparc__) \ + || defined(_POWER) || defined(__powerpc__) \ + || defined(__ppc__) || defined(__hpux) || defined(__hppa) \ + || defined(_MIPSEB) || defined(_POWER) \ + || defined(__s390__) +# define BOOST_BIG_ENDIAN +# define BOOST_BYTE_ORDER 4321 +#elif defined(__i386__) || defined(__alpha__) \ + || defined(__ia64) || defined(__ia64__) \ + || defined(_M_IX86) || defined(_M_IA64) \ + || defined(_M_ALPHA) || defined(__amd64) \ + || defined(__amd64__) || defined(_M_AMD64) \ + || defined(__x86_64) || defined(__x86_64__) \ + || defined(_M_X64) || defined(__bfin__) + +# define BOOST_LITTLE_ENDIAN +# define BOOST_BYTE_ORDER 1234 +#else +# error The file boost/detail/endian.hpp needs to be set up for your CPU type. +#endif + #endif diff --git a/utils/boost_idb/boost/detail/fenv.hpp b/utils/boost_idb/boost/detail/fenv.hpp deleted file mode 100644 index f0487064..00000000 --- a/utils/boost_idb/boost/detail/fenv.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/*============================================================================= - Copyright (c) 2010 Bryce Lelbach - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -=============================================================================*/ - -#include - -#if defined(BOOST_NO_FENV_H) - #error This platform does not have a floating point environment -#endif - -#if !defined(BOOST_DETAIL_FENV_HPP) -#define BOOST_DETAIL_FENV_HPP - -/* If we're using clang + glibc, we have to get hacky. - * See http://llvm.org/bugs/show_bug.cgi?id=6907 */ -#if defined(__clang__) && (__clang_major__ < 3) && \ - defined(__GNU_LIBRARY__) && /* up to version 5 */ \ - defined(__GLIBC__) && /* version 6 + */ \ - !defined(_FENV_H) - #define _FENV_H - - #include - #include - - extern "C" { - extern int fegetexceptflag (fexcept_t*, int) __THROW; - extern int fesetexceptflag (__const fexcept_t*, int) __THROW; - extern int feclearexcept (int) __THROW; - extern int feraiseexcept (int) __THROW; - extern int fetestexcept (int) __THROW; - extern int fegetround (void) __THROW; - extern int fesetround (int) __THROW; - extern int fegetenv (fenv_t*) __THROW; - extern int fesetenv (__const fenv_t*) __THROW; - extern int feupdateenv (__const fenv_t*) __THROW; - extern int feholdexcept (fenv_t*) __THROW; - - #ifdef __USE_GNU - extern int feenableexcept (int) __THROW; - extern int fedisableexcept (int) __THROW; - extern int fegetexcept (void) __THROW; - #endif - } - - namespace std { namespace tr1 { - using ::fenv_t; - using ::fexcept_t; - using ::fegetexceptflag; - using ::fesetexceptflag; - using ::feclearexcept; - using ::feraiseexcept; - using ::fetestexcept; - using ::fegetround; - using ::fesetround; - using ::fegetenv; - using ::fesetenv; - using ::feupdateenv; - using ::feholdexcept; - } } - -#else /* if we're not using GNU's C stdlib, fenv.h should work with clang */ - #if defined(__SUNPRO_CC) /* lol suncc */ - #include - #endif - - #include - -#endif - -#endif /* BOOST_DETAIL_FENV_HPP */ - diff --git a/utils/boost_idb/boost/detail/interlocked.hpp b/utils/boost_idb/boost/detail/interlocked.hpp index 1152f710..fccebc3f 100644 --- a/utils/boost_idb/boost/detail/interlocked.hpp +++ b/utils/boost_idb/boost/detail/interlocked.hpp @@ -1,6 +1,12 @@ #ifndef BOOST_DETAIL_INTERLOCKED_HPP_INCLUDED #define BOOST_DETAIL_INTERLOCKED_HPP_INCLUDED +// MS compatible compilers support #pragma once + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +# pragma once +#endif + // // boost/detail/interlocked.hpp // @@ -13,11 +19,6 @@ #include -// MS compatible compilers support #pragma once -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - #if defined( BOOST_USE_WINDOWS_H ) # include @@ -30,47 +31,8 @@ # define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER InterlockedCompareExchangePointer # define BOOST_INTERLOCKED_EXCHANGE_POINTER InterlockedExchangePointer -#elif defined( BOOST_USE_INTRIN_H ) - -#include - -# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement -# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange -# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange -# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd - -# if defined(_M_IA64) || defined(_M_AMD64) || defined(__x86_64__) || defined(__x86_64) - -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer -# define BOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer - -# else - -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ - ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare))) -# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ - ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange))) - -# endif - #elif defined(_WIN32_WCE) -#if _WIN32_WCE >= 0x600 - -extern "C" long __cdecl _InterlockedIncrement( long volatile * ); -extern "C" long __cdecl _InterlockedDecrement( long volatile * ); -extern "C" long __cdecl _InterlockedCompareExchange( long volatile *, long, long ); -extern "C" long __cdecl _InterlockedExchange( long volatile *, long ); -extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long ); - -# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement -# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange -# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange -# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd - -#else // under Windows CE we still have old-style Interlocked* functions extern "C" long __cdecl InterlockedIncrement( long* ); @@ -85,8 +47,6 @@ extern "C" long __cdecl InterlockedExchangeAdd( long*, long ); # define BOOST_INTERLOCKED_EXCHANGE InterlockedExchange # define BOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd -#endif - # define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long*)(dest),(long)(exchange),(long)(compare))) # define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ @@ -94,11 +54,7 @@ extern "C" long __cdecl InterlockedExchangeAdd( long*, long ); #elif defined( BOOST_MSVC ) || defined( BOOST_INTEL_WIN ) -#if defined( BOOST_MSVC ) && BOOST_MSVC >= 1500 - -#include - -#elif defined( __CLRCALL_PURE_OR_CDECL ) +#if defined( __CLRCALL_PURE_OR_CDECL ) extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedIncrement( long volatile * ); extern "C" long __CLRCALL_PURE_OR_CDECL _InterlockedDecrement( long volatile * ); @@ -116,11 +72,20 @@ extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long ); #endif +# pragma intrinsic( _InterlockedIncrement ) +# pragma intrinsic( _InterlockedDecrement ) +# pragma intrinsic( _InterlockedCompareExchange ) +# pragma intrinsic( _InterlockedExchange ) +# pragma intrinsic( _InterlockedExchangeAdd ) + # if defined(_M_IA64) || defined(_M_AMD64) extern "C" void* __cdecl _InterlockedCompareExchangePointer( void* volatile *, void*, void* ); extern "C" void* __cdecl _InterlockedExchangePointer( void* volatile *, void* ); +# pragma intrinsic( _InterlockedCompareExchangePointer ) +# pragma intrinsic( _InterlockedExchangePointer ) + # define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer # define BOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer @@ -139,47 +104,19 @@ extern "C" void* __cdecl _InterlockedExchangePointer( void* volatile *, void* ); # define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange # define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd -// Unlike __MINGW64__, __MINGW64_VERSION_MAJOR is defined by MinGW-w64 for both 32 and 64-bit targets. -#elif defined(__MINGW64_VERSION_MAJOR) - -// MinGW-w64 provides intrin.h for both 32 and 64-bit targets. -#include - -# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement -# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange -# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange -# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd -# if defined(__x86_64__) || defined(__x86_64) -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer -# define BOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer -# else -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ - ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare))) -# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ - ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange))) -# endif - #elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined( __CYGWIN__ ) -#define BOOST_INTERLOCKED_IMPORT __declspec(dllimport) - namespace boost { namespace detail { -extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedIncrement( long volatile * ); -extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedDecrement( long volatile * ); -extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedCompareExchange( long volatile *, long, long ); -extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedExchange( long volatile *, long ); -extern "C" BOOST_INTERLOCKED_IMPORT long __stdcall InterlockedExchangeAdd( long volatile *, long ); - -# if defined(_M_IA64) || defined(_M_AMD64) -extern "C" BOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedCompareExchangePointer( void* volatile *, void*, void* ); -extern "C" BOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedExchangePointer( void* volatile *, void* ); -# endif +extern "C" __declspec(dllimport) long __stdcall InterlockedIncrement( long volatile * ); +extern "C" __declspec(dllimport) long __stdcall InterlockedDecrement( long volatile * ); +extern "C" __declspec(dllimport) long __stdcall InterlockedCompareExchange( long volatile *, long, long ); +extern "C" __declspec(dllimport) long __stdcall InterlockedExchange( long volatile *, long ); +extern "C" __declspec(dllimport) long __stdcall InterlockedExchangeAdd( long volatile *, long ); } // namespace detail @@ -191,15 +128,10 @@ extern "C" BOOST_INTERLOCKED_IMPORT void* __stdcall InterlockedExchangePointer( # define BOOST_INTERLOCKED_EXCHANGE ::boost::detail::InterlockedExchange # define BOOST_INTERLOCKED_EXCHANGE_ADD ::boost::detail::InterlockedExchangeAdd -# if defined(_M_IA64) || defined(_M_AMD64) -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER ::boost::detail::InterlockedCompareExchangePointer -# define BOOST_INTERLOCKED_EXCHANGE_POINTER ::boost::detail::InterlockedExchangePointer -# else -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare))) -# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ +# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange))) -# endif #else diff --git a/utils/boost_idb/boost/detail/is_function_ref_tester.hpp b/utils/boost_idb/boost/detail/is_function_ref_tester.hpp index 8e7d1d77..5f367ea8 100644 --- a/utils/boost_idb/boost/detail/is_function_ref_tester.hpp +++ b/utils/boost_idb/boost/detail/is_function_ref_tester.hpp @@ -112,7 +112,7 @@ boost::type_traits::yes_type is_function_ref_tester(R (&)(T0,T1,T2,T3,T4,T5,T6,T #else #define BOOST_PP_ITERATION_PARAMS_1 \ - (3, (0, 25, "boost/detail/is_function_ref_tester.hpp")) + (3, (0, 25, "boost/type_traits/detail/is_function_ref_tester.hpp")) #include BOOST_PP_ITERATE() #endif // BOOST_TT_PREPROCESSING_MODE @@ -133,4 +133,3 @@ boost::type_traits::yes_type is_function_ref_tester(R (&)(BOOST_PP_ENUM_PARAMS(i #undef i #endif // BOOST_PP_IS_ITERATING - diff --git a/utils/boost_idb/boost/detail/is_sorted.hpp b/utils/boost_idb/boost/detail/is_sorted.hpp deleted file mode 100644 index 5ab32e5c..00000000 --- a/utils/boost_idb/boost/detail/is_sorted.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/*============================================================================== - Copyright (c) 2010-2011 Bryce Lelbach - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -==============================================================================*/ - -#ifndef BOOST_DETAIL_SORTED_HPP -#define BOOST_DETAIL_SORTED_HPP - -#include - -#include - -namespace boost { -namespace detail { - -template -inline Iterator is_sorted_until (Iterator first, Iterator last, Comp c) { - if (first == last) - return last; - - Iterator it = first; ++it; - - for (; it != last; first = it, ++it) - if (c(*it, *first)) - return it; - - return it; -} - -template -inline Iterator is_sorted_until (Iterator first, Iterator last) { - typedef typename boost::detail::iterator_traits::value_type - value_type; - - typedef std::less c; - - return ::boost::detail::is_sorted_until(first, last, c()); -} - -template -inline bool is_sorted (Iterator first, Iterator last, Comp c) { - return ::boost::detail::is_sorted_until(first, last, c) == last; -} - -template -inline bool is_sorted (Iterator first, Iterator last) { - return ::boost::detail::is_sorted_until(first, last) == last; -} - -} // detail -} // boost - -#endif // BOOST_DETAIL_SORTED_HPP - diff --git a/utils/boost_idb/boost/detail/lightweight_main.hpp b/utils/boost_idb/boost/detail/lightweight_main.hpp deleted file mode 100644 index 17053097..00000000 --- a/utils/boost_idb/boost/detail/lightweight_main.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// boost/detail/lightweight_main.hpp -------------------------------------------------// - -// Copyright Beman Dawes 2010 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -#include -#include - -//--------------------------------------------------------------------------------------// -// // -// exception reporting main() that calls cpp_main() // -// // -//--------------------------------------------------------------------------------------// - -int cpp_main(int argc, char* argv[]); - -int main(int argc, char* argv[]) -{ - try - { - return cpp_main(argc, argv); - } - - catch (const std::exception& ex) - { - std::cout - << "\nERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR\n" - << "\n****************************** std::exception *****************************\n" - << ex.what() - << "\n***************************************************************************\n" - << std::endl; - } - return 1; -} diff --git a/utils/boost_idb/boost/detail/lightweight_test.hpp b/utils/boost_idb/boost/detail/lightweight_test.hpp index 49dd5e45..ffa750d3 100644 --- a/utils/boost_idb/boost/detail/lightweight_test.hpp +++ b/utils/boost_idb/boost/detail/lightweight_test.hpp @@ -11,68 +11,20 @@ // boost/detail/lightweight_test.hpp - lightweight test library // // Copyright (c) 2002, 2009 Peter Dimov -// Copyright (2) Beman Dawes 2010, 2011 -// Copyright (3) Ion Gaztanaga 2013 // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // -// --------------- -// -// If expression is false increases the error count -// and outputs a message containing 'expression' -// // BOOST_TEST(expression) -// -// --------------- -// -// Increases error count and outputs a message containing 'message' -// // BOOST_ERROR(message) -// -// --------------- -// -// If 'expr1' != 'expr2' increases the error count -// and outputs a message containing both expressions -// // BOOST_TEST_EQ(expr1, expr2) // -// --------------- -// -// If 'expr1' == 'expr2' increases the error count -// and outputs a message containing both expressions -// -// BOOST_TEST_NE(expr1, expr2) -// -// --------------- -// -// If BOOST_NO_EXCEPTIONS is NOT defined and if 'expr' does not -// throw an exception of type 'excep', increases the error count -// and outputs a message containing the expression. -// -// If BOOST_NO_EXCEPTIONS is defined, this macro expands to nothing -// and 'expr' is not evaluated. -// -// BOOST_TEST_THROWS(expr, excep) -// -// --------------- -// -// Returns the error count -// // int boost::report_errors() // -#include #include -#include -#include - -// IDE's like Visual Studio perform better if output goes to std::cout or -// some other stream, so allow user to configure output stream: -#ifndef BOOST_LIGHTWEIGHT_TEST_OSTREAM -# define BOOST_LIGHTWEIGHT_TEST_OSTREAM std::cerr -#endif +#include namespace boost { @@ -80,103 +32,52 @@ namespace boost namespace detail { -struct report_errors_reminder -{ - bool called_report_errors_function; - report_errors_reminder() : called_report_errors_function(false) {} - ~report_errors_reminder() - { - BOOST_ASSERT(called_report_errors_function); // verify report_errors() was called - } -}; - -inline report_errors_reminder& report_errors_remind() -{ - static report_errors_reminder r; - return r; -} - inline int & test_errors() { static int x = 0; - report_errors_remind(); return x; } inline void test_failed_impl(char const * expr, char const * file, int line, char const * function) { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << file << "(" << line << "): test '" << expr << "' failed in function '" - << function << "'" << std::endl; + std::cerr << file << "(" << line << "): test '" << expr << "' failed in function '" << function << "'" << std::endl; ++test_errors(); } inline void error_impl(char const * msg, char const * file, int line, char const * function) { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << file << "(" << line << "): " << msg << " in function '" - << function << "'" << std::endl; + std::cerr << file << "(" << line << "): " << msg << " in function '" << function << "'" << std::endl; ++test_errors(); } -inline void throw_failed_impl(char const * excep, char const * file, int line, char const * function) -{ - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << file << "(" << line << "): Exception '" << excep << "' not thrown in function '" - << function << "'" << std::endl; - ++test_errors(); -} - -template inline void test_eq_impl( char const * expr1, char const * expr2, - char const * file, int line, char const * function, T const & t, U const & u ) +template inline void test_eq_impl( char const * expr1, char const * expr2, char const * file, int line, char const * function, T const & t, U const & u ) { if( t == u ) { } else { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << file << "(" << line << "): test '" << expr1 << " == " << expr2 + std::cerr << file << "(" << line << "): test '" << expr1 << " == " << expr2 << "' failed in function '" << function << "': " << "'" << t << "' != '" << u << "'" << std::endl; ++test_errors(); } } -template inline void test_ne_impl( char const * expr1, char const * expr2, - char const * file, int line, char const * function, T const & t, U const & u ) -{ - if( t != u ) - { - } - else - { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << file << "(" << line << "): test '" << expr1 << " != " << expr2 - << "' failed in function '" << function << "': " - << "'" << t << "' == '" << u << "'" << std::endl; - ++test_errors(); - } -} - } // namespace detail inline int report_errors() { - detail::report_errors_remind().called_report_errors_function = true; - int errors = detail::test_errors(); if( errors == 0 ) { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << "No errors detected." << std::endl; + std::cerr << "No errors detected." << std::endl; return 0; } else { - BOOST_LIGHTWEIGHT_TEST_OSTREAM - << errors << " error" << (errors == 1? "": "s") << " detected." << std::endl; + std::cerr << errors << " error" << (errors == 1? "": "s") << " detected." << std::endl; return 1; } } @@ -186,23 +87,5 @@ inline int report_errors() #define BOOST_TEST(expr) ((expr)? (void)0: ::boost::detail::test_failed_impl(#expr, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION)) #define BOOST_ERROR(msg) ::boost::detail::error_impl(msg, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION) #define BOOST_TEST_EQ(expr1,expr2) ( ::boost::detail::test_eq_impl(#expr1, #expr2, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION, expr1, expr2) ) -#define BOOST_TEST_NE(expr1,expr2) ( ::boost::detail::test_ne_impl(#expr1, #expr2, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION, expr1, expr2) ) -#ifndef BOOST_NO_EXCEPTIONS - #define BOOST_TEST_THROWS( EXPR, EXCEP ) \ - try { \ - EXPR; \ - ::boost::detail::throw_failed_impl \ - (#EXCEP, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION); \ - } \ - catch(EXCEP const&) { \ - } \ - catch(...) { \ - ::boost::detail::throw_failed_impl \ - (#EXCEP, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION); \ - } \ - // -#else - #define BOOST_TEST_THROWS( EXPR, EXCEP ) -#endif #endif // #ifndef BOOST_DETAIL_LIGHTWEIGHT_TEST_HPP_INCLUDED diff --git a/utils/boost_idb/boost/detail/scoped_enum_emulation.hpp b/utils/boost_idb/boost/detail/scoped_enum_emulation.hpp index d266e0e3..e695a208 100644 --- a/utils/boost_idb/boost/detail/scoped_enum_emulation.hpp +++ b/utils/boost_idb/boost/detail/scoped_enum_emulation.hpp @@ -1,337 +1,56 @@ // scoped_enum_emulation.hpp ---------------------------------------------------------// // Copyright Beman Dawes, 2009 -// Copyright (C) 2011-2012 Vicente J. Botet Escriba -// Copyright (C) 2012 Anthony Williams // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt -/* -[section:scoped_enums Scoped Enums] - -Generates C++0x scoped enums if the feature is present, otherwise emulates C++0x -scoped enums with C++03 namespaces and enums. The Boost.Config BOOST_NO_CXX11_SCOPED_ENUMS -macro is used to detect feature support. - -See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf for a -description of the scoped enum feature. Note that the committee changed the name -from strongly typed enum to scoped enum. - -Some of the enumerations defined in the standard library are scoped enums. - - enum class future_errc - { - broken_promise, - future_already_retrieved, - promise_already_satisfied, - no_state - }; - -On compilers that don't support them, the library provides two emulations: - -[heading Strict] - -* Able to specify the underlying type. -* explicit conversion to/from underlying type. -* The wrapper is not a C++03 enum type. - -The user can declare declare these types as - - BOOST_SCOPED_ENUM_DECLARE_BEGIN(future_errc) - { - broken_promise, - future_already_retrieved, - promise_already_satisfied, - no_state - } - BOOST_SCOPED_ENUM_DECLARE_END(future_errc) - -These macros allows to use 'future_errc' in almost all the cases as an scoped enum. - - future_errc err = future_errc::no_state; - -There are however some limitations: - -* The type is not a C++ enum, so 'is_enum' will be false_type. -* The emulated scoped enum can not be used in switch nor in template arguments. For these cases the user needs to use some macros. - -Instead of - - switch (ev) - { - case future_errc::broken_promise: - // ... - -use - - switch (boost::native_value(ev)) - { - case future_errc::broken_promise: - -And instead of - - #ifdef BOOST_NO_CXX11_SCOPED_ENUMS - template <> - struct BOOST_SYMBOL_VISIBLE is_error_code_enum : public true_type { }; - #endif - -use - - #ifdef BOOST_NO_CXX11_SCOPED_ENUMS - template <> - struct BOOST_SYMBOL_VISIBLE is_error_code_enum : public true_type { }; - #endif - - -Sample usage: - - BOOST_SCOPED_ENUM_UT_DECLARE_BEGIN(algae, char) { green, red, cyan }; BOOST_SCOPED_ENUM_DECLARE_END(algae) - ... - algae sample( algae::red ); - void foo( algae color ); - ... - sample = algae::green; - foo( algae::cyan ); - - Light - Caution: only the syntax is emulated; the semantics are not emulated and - the syntax emulation doesn't include being able to specify the underlying - representation type. - - The literal scoped emulation is via struct rather than namespace to allow use within classes. - Thanks to Andrey Semashev for pointing that out. - However the type is an real C++03 enum and so convertible implicitly to an int. - - Sample usage: - - BOOST_SCOPED_ENUM_START(algae) { green, red, cyan }; BOOST_SCOPED_ENUM_END - ... - BOOST_SCOPED_ENUM(algae) sample( algae::red ); - void foo( BOOST_SCOPED_ENUM(algae) color ); - ... - sample = algae::green; - foo( algae::cyan ); - - Helpful comments and suggestions were also made by Kjell Elster, Phil Endecott, - Joel Falcou, Mathias Gaunard, Felipe Magno de Almeida, Matt Calabrese, Vicente - Botet, and Daniel James. - -[endsect] -*/ - +// Generates C++0x scoped enums if the feature is present, otherwise emulates C++0x +// scoped enums with C++03 namespaces and enums. The Boost.Config BOOST_NO_SCOPED_ENUMS +// macro is used to detect feature support. +// +// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf for a +// description of the scoped enum feature. Note that the committee changed the name +// from strongly typed enum to scoped enum. +// +// Caution: only the syntax is emulated; the semantics are not emulated and +// the syntax emulation doesn't include being able to specify the underlying +// representation type. +// +// The emulation is via struct rather than namespace to allow use within classes. +// Thanks to Andrey Semashev for pointing that out. +// +// Helpful comments and suggestions were also made by Kjell Elster, Phil Endecott, +// Joel Falcou, Mathias Gaunard, Felipe Magno de Almeida, Matt Calabrese, Vincente +// Botet, and Daniel James. +// +// Sample usage: +// +// BOOST_SCOPED_ENUM_START(algae) { green, red, cyan }; BOOST_SCOPED_ENUM_END +// ... +// BOOST_SCOPED_ENUM(algae) sample( algae::red ); +// void foo( BOOST_SCOPED_ENUM(algae) color ); +// ... +// sample = algae::green; +// foo( algae::cyan ); #ifndef BOOST_SCOPED_ENUM_EMULATION_HPP #define BOOST_SCOPED_ENUM_EMULATION_HPP #include -#include - -namespace boost -{ - -#ifdef BOOST_NO_CXX11_SCOPED_ENUMS - /** - * Meta-function to get the underlying type of a scoped enum. - * - * Requires EnumType must be an enum type or the emulation of a scoped enum - */ - template - struct underlying_type - { - /** - * The member typedef type names the underlying type of EnumType. It is EnumType::underlying_type when the EnumType is an emulated scoped enum, - * std::underlying_type::type when the standard library std::underlying_type is provided. - * - * The user will need to specialize it when the compiler supports scoped enums but don't provides std::underlying_type. - */ - typedef typename EnumType::underlying_type type; - }; - - /** - * Meta-function to get the native enum type associated to an enum class or its emulation. - */ - template - struct native_type - { - /** - * The member typedef type names the native enum type associated to the scoped enum, - * which is it self if the compiler supports scoped enums or EnumType::enum_type if it is an emulated scoped enum. - */ - typedef typename EnumType::enum_type type; - }; - - /** - * Casts a scoped enum to its underlying type. - * - * This function is useful when working with scoped enum classes, which doens't implicitly convert to the underlying type. - * @param v A scoped enum. - * @returns The underlying type. - * @throws No-throws. - */ - template - UnderlyingType underlying_cast(EnumType v) - { - return v.get_underlying_value_(); - } - - /** - * Casts a scoped enum to its native enum type. - * - * This function is useful to make programs portable when the scoped enum emulation can not be use where native enums can. - * - * EnumType the scoped enum type - * - * @param v A scoped enum. - * @returns The native enum value. - * @throws No-throws. - */ - template - inline - typename EnumType::enum_type native_value(EnumType e) - { - return e.native_value_(); - } - -#else // BOOST_NO_CXX11_SCOPED_ENUMS - - template - struct underlying_type - { - //typedef typename std::underlying_type::type type; - }; - - template - struct native_type - { - typedef EnumType type; - }; - - template - UnderlyingType underlying_cast(EnumType v) - { - return static_cast(v); - } - - template - inline - EnumType native_value(EnumType e) - { - return e; - } - -#endif -} +#ifdef BOOST_NO_SCOPED_ENUMS -#ifdef BOOST_NO_CXX11_SCOPED_ENUMS - -#ifndef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS - -#define BOOST_SCOPED_ENUM_UT_DECLARE_CONVERSION_OPERATOR \ - explicit operator underlying_type() const { return get_underlying_value_(); } +# define BOOST_SCOPED_ENUM_START(name) struct name { enum enum_type +# define BOOST_SCOPED_ENUM_END }; +# define BOOST_SCOPED_ENUM(name) name::enum_type #else -#define BOOST_SCOPED_ENUM_UT_DECLARE_CONVERSION_OPERATOR +# define BOOST_SCOPED_ENUM_START(name) enum class name +# define BOOST_SCOPED_ENUM_END +# define BOOST_SCOPED_ENUM(name) name #endif -/** - * Start a declaration of a scoped enum. - * - * @param EnumType The new scoped enum. - * @param UnderlyingType The underlying type. - */ -#define BOOST_SCOPED_ENUM_UT_DECLARE_BEGIN(EnumType, UnderlyingType) \ - struct EnumType { \ - typedef UnderlyingType underlying_type; \ - EnumType() BOOST_NOEXCEPT {} \ - explicit EnumType(underlying_type v) : v_(v) {} \ - underlying_type get_underlying_value_() const { return v_; } \ - BOOST_SCOPED_ENUM_UT_DECLARE_CONVERSION_OPERATOR \ - private: \ - underlying_type v_; \ - typedef EnumType self_type; \ - public: \ - enum enum_type - -#define BOOST_SCOPED_ENUM_DECLARE_END2() \ - enum_type get_native_value_() const BOOST_NOEXCEPT { return enum_type(v_); } \ - operator enum_type() const BOOST_NOEXCEPT { return get_native_value_(); } \ - friend bool operator ==(self_type lhs, self_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)==enum_type(rhs.v_); } \ - friend bool operator ==(self_type lhs, enum_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)==rhs; } \ - friend bool operator ==(enum_type lhs, self_type rhs) BOOST_NOEXCEPT { return lhs==enum_type(rhs.v_); } \ - friend bool operator !=(self_type lhs, self_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)!=enum_type(rhs.v_); } \ - friend bool operator !=(self_type lhs, enum_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)!=rhs; } \ - friend bool operator !=(enum_type lhs, self_type rhs) BOOST_NOEXCEPT { return lhs!=enum_type(rhs.v_); } \ - friend bool operator <(self_type lhs, self_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)(self_type lhs, self_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)>enum_type(rhs.v_); } \ - friend bool operator >(self_type lhs, enum_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)>rhs; } \ - friend bool operator >(enum_type lhs, self_type rhs) BOOST_NOEXCEPT { return lhs>enum_type(rhs.v_); } \ - friend bool operator >=(self_type lhs, self_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)>=enum_type(rhs.v_); } \ - friend bool operator >=(self_type lhs, enum_type rhs) BOOST_NOEXCEPT { return enum_type(lhs.v_)>=rhs; } \ - friend bool operator >=(enum_type lhs, self_type rhs) BOOST_NOEXCEPT { return lhs>=enum_type(rhs.v_); } \ - }; - -#define BOOST_SCOPED_ENUM_DECLARE_END(EnumType) \ - ; \ - EnumType(enum_type v) BOOST_NOEXCEPT : v_(v) {} \ - BOOST_SCOPED_ENUM_DECLARE_END2() - -/** - * Starts a declaration of a scoped enum with the default int underlying type. - * - * @param EnumType The new scoped enum. - */ -#define BOOST_SCOPED_ENUM_DECLARE_BEGIN(EnumType) \ - BOOST_SCOPED_ENUM_UT_DECLARE_BEGIN(EnumType,int) - -/** - * Name of the native enum type. - * - * @param NT The new scoped enum. - */ -#define BOOST_SCOPED_ENUM_NATIVE(EnumType) EnumType::enum_type -/** - * Forward declares an scoped enum. - * - * @param NT The scoped enum. - */ -#define BOOST_SCOPED_ENUM_FORWARD_DECLARE(EnumType) struct EnumType - -#else // BOOST_NO_CXX11_SCOPED_ENUMS - -#define BOOST_SCOPED_ENUM_UT_DECLARE_BEGIN(EnumType,UnderlyingType) enum class EnumType:UnderlyingType -#define BOOST_SCOPED_ENUM_DECLARE_BEGIN(EnumType) enum class EnumType -#define BOOST_SCOPED_ENUM_DECLARE_END2() -#define BOOST_SCOPED_ENUM_DECLARE_END(EnumType) ; - -#define BOOST_SCOPED_ENUM_NATIVE(EnumType) EnumType -#define BOOST_SCOPED_ENUM_FORWARD_DECLARE(EnumType) enum class EnumType - -#endif // BOOST_NO_CXX11_SCOPED_ENUMS - -#define BOOST_SCOPED_ENUM_START(name) BOOST_SCOPED_ENUM_DECLARE_BEGIN(name) -#define BOOST_SCOPED_ENUM_END BOOST_SCOPED_ENUM_DECLARE_END2() -#define BOOST_SCOPED_ENUM(name) BOOST_SCOPED_ENUM_NATIVE(name) - -//#ifdef BOOST_NO_CXX11_SCOPED_ENUMS -// -//# define BOOST_SCOPED_ENUM_START(name) struct name { enum enum_type -//# define BOOST_SCOPED_ENUM_END }; -//# define BOOST_SCOPED_ENUM(name) name::enum_type -// -//#else -// -//# define BOOST_SCOPED_ENUM_START(name) enum class name -//# define BOOST_SCOPED_ENUM_END -//# define BOOST_SCOPED_ENUM(name) name -// -//#endif #endif // BOOST_SCOPED_ENUM_EMULATION_HPP diff --git a/utils/boost_idb/boost/detail/utf8_codecvt_facet.ipp b/utils/boost_idb/boost/detail/utf8_codecvt_facet.ipp deleted file mode 100644 index 064fdaf5..00000000 --- a/utils/boost_idb/boost/detail/utf8_codecvt_facet.ipp +++ /dev/null @@ -1,285 +0,0 @@ -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// utf8_codecvt_facet.ipp - -// Copyright (c) 2001 Ronald Garcia, Indiana University (garcia@osl.iu.edu) -// Andrew Lumsdaine, Indiana University (lums@osl.iu.edu). -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// Please see the comments in to -// learn how this file should be used. - -#include - -#include // for multi-byte converson routines -#include - -#include -#include - -// If we don't have wstring, then Unicode support -// is not available anyway, so we don't need to even -// compiler this file. This also fixes the problem -// with mingw, which can compile this file, but will -// generate link error when building DLL. -#ifndef BOOST_NO_STD_WSTRING - -BOOST_UTF8_BEGIN_NAMESPACE - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// implementation for wchar_t - -// Translate incoming UTF-8 into UCS-4 -std::codecvt_base::result utf8_codecvt_facet::do_in( - std::mbstate_t& /*state*/, - const char * from, - const char * from_end, - const char * & from_next, - wchar_t * to, - wchar_t * to_end, - wchar_t * & to_next -) const { - // Basic algorithm: The first octet determines how many - // octets total make up the UCS-4 character. The remaining - // "continuing octets" all begin with "10". To convert, subtract - // the amount that specifies the number of octets from the first - // octet. Subtract 0x80 (1000 0000) from each continuing octet, - // then mash the whole lot together. Note that each continuing - // octet only uses 6 bits as unique values, so only shift by - // multiples of 6 to combine. - while (from != from_end && to != to_end) { - - // Error checking on the first octet - if (invalid_leading_octet(*from)){ - from_next = from; - to_next = to; - return std::codecvt_base::error; - } - - // The first octet is adjusted by a value dependent upon - // the number of "continuing octets" encoding the character - const int cont_octet_count = get_cont_octet_count(*from); - const wchar_t octet1_modifier_table[] = { - 0x00, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc - }; - - // The unsigned char conversion is necessary in case char is - // signed (I learned this the hard way) - wchar_t ucs_result = - (unsigned char)(*from++) - octet1_modifier_table[cont_octet_count]; - - // Invariants : - // 1) At the start of the loop, 'i' continuing characters have been - // processed - // 2) *from points to the next continuing character to be processed. - int i = 0; - while(i != cont_octet_count && from != from_end) { - - // Error checking on continuing characters - if (invalid_continuing_octet(*from)) { - from_next = from; - to_next = to; - return std::codecvt_base::error; - } - - ucs_result *= (1 << 6); - - // each continuing character has an extra (10xxxxxx)b attached to - // it that must be removed. - ucs_result += (unsigned char)(*from++) - 0x80; - ++i; - } - - // If the buffer ends with an incomplete unicode character... - if (from == from_end && i != cont_octet_count) { - // rewind "from" to before the current character translation - from_next = from - (i+1); - to_next = to; - return std::codecvt_base::partial; - } - *to++ = ucs_result; - } - from_next = from; - to_next = to; - - // Were we done converting or did we run out of destination space? - if(from == from_end) return std::codecvt_base::ok; - else return std::codecvt_base::partial; -} - -std::codecvt_base::result utf8_codecvt_facet::do_out( - std::mbstate_t& /*state*/, - const wchar_t * from, - const wchar_t * from_end, - const wchar_t * & from_next, - char * to, - char * to_end, - char * & to_next -) const -{ - // RG - consider merging this table with the other one - const wchar_t octet1_modifier_table[] = { - 0x00, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc - }; - - wchar_t max_wchar = (std::numeric_limits::max)(); - while (from != from_end && to != to_end) { - - // Check for invalid UCS-4 character - if (*from > max_wchar) { - from_next = from; - to_next = to; - return std::codecvt_base::error; - } - - int cont_octet_count = get_cont_octet_out_count(*from); - - // RG - comment this formula better - int shift_exponent = (cont_octet_count) * 6; - - // Process the first character - *to++ = static_cast(octet1_modifier_table[cont_octet_count] + - (unsigned char)(*from / (1 << shift_exponent))); - - // Process the continuation characters - // Invariants: At the start of the loop: - // 1) 'i' continuing octets have been generated - // 2) '*to' points to the next location to place an octet - // 3) shift_exponent is 6 more than needed for the next octet - int i = 0; - while (i != cont_octet_count && to != to_end) { - shift_exponent -= 6; - *to++ = static_cast(0x80 + ((*from / (1 << shift_exponent)) % (1 << 6))); - ++i; - } - // If we filled up the out buffer before encoding the character - if(to == to_end && i != cont_octet_count) { - from_next = from; - to_next = to - (i+1); - return std::codecvt_base::partial; - } - ++from; - } - from_next = from; - to_next = to; - // Were we done or did we run out of destination space - if(from == from_end) return std::codecvt_base::ok; - else return std::codecvt_base::partial; -} - -// How many char objects can I process to get <= max_limit -// wchar_t objects? -int utf8_codecvt_facet::do_length( - BOOST_CODECVT_DO_LENGTH_CONST std::mbstate_t &, - const char * from, - const char * from_end, - std::size_t max_limit -#if BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) -) const throw() -#else -) const -#endif -{ - // RG - this code is confusing! I need a better way to express it. - // and test cases. - - // Invariants: - // 1) last_octet_count has the size of the last measured character - // 2) char_count holds the number of characters shown to fit - // within the bounds so far (no greater than max_limit) - // 3) from_next points to the octet 'last_octet_count' before the - // last measured character. - int last_octet_count=0; - std::size_t char_count = 0; - const char* from_next = from; - // Use "<" because the buffer may represent incomplete characters - while (from_next+last_octet_count <= from_end && char_count <= max_limit) { - from_next += last_octet_count; - last_octet_count = (get_octet_count(*from_next)); - ++char_count; - } - return static_cast(from_next-from_end); -} - -unsigned int utf8_codecvt_facet::get_octet_count( - unsigned char lead_octet -){ - // if the 0-bit (MSB) is 0, then 1 character - if (lead_octet <= 0x7f) return 1; - - // Otherwise the count number of consecutive 1 bits starting at MSB -// assert(0xc0 <= lead_octet && lead_octet <= 0xfd); - - if (0xc0 <= lead_octet && lead_octet <= 0xdf) return 2; - else if (0xe0 <= lead_octet && lead_octet <= 0xef) return 3; - else if (0xf0 <= lead_octet && lead_octet <= 0xf7) return 4; - else if (0xf8 <= lead_octet && lead_octet <= 0xfb) return 5; - else return 6; -} -BOOST_UTF8_END_NAMESPACE - -namespace { -template -int get_cont_octet_out_count_impl(wchar_t word){ - if (word < 0x80) { - return 0; - } - if (word < 0x800) { - return 1; - } - return 2; -} - -template<> -int get_cont_octet_out_count_impl<4>(wchar_t word){ - if (word < 0x80) { - return 0; - } - if (word < 0x800) { - return 1; - } - - // Note that the following code will generate warnings on some platforms - // where wchar_t is defined as UCS2. The warnings are superfluous as the - // specialization is never instantitiated with such compilers, but this - // can cause problems if warnings are being treated as errors, so we guard - // against that. Including as we do - // should be enough to get WCHAR_MAX defined. -#if !defined(WCHAR_MAX) -# error WCHAR_MAX not defined! -#endif - // cope with VC++ 7.1 or earlier having invalid WCHAR_MAX -#if defined(_MSC_VER) && _MSC_VER <= 1310 // 7.1 or earlier - return 2; -#elif WCHAR_MAX > 0x10000 - - if (word < 0x10000) { - return 2; - } - if (word < 0x200000) { - return 3; - } - if (word < 0x4000000) { - return 4; - } - return 5; - -#else - return 2; -#endif -} - -} // namespace anonymous - -BOOST_UTF8_BEGIN_NAMESPACE -// How many "continuing octets" will be needed for this word -// == total octets - 1. -int utf8_codecvt_facet::get_cont_octet_out_count( - wchar_t word -) const { - return get_cont_octet_out_count_impl(word); -} -BOOST_UTF8_END_NAMESPACE - -#endif diff --git a/utils/boost_idb/boost/detail/winapi/GetCurrentProcess.hpp b/utils/boost_idb/boost/detail/winapi/GetCurrentProcess.hpp deleted file mode 100644 index 51206bb4..00000000 --- a/utils/boost_idb/boost/detail/winapi/GetCurrentProcess.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// GetCurrentProcess.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_GETCURRENTPROCESS_HPP -#define BOOST_DETAIL_WINAPI_GETCURRENTPROCESS_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetCurrentProcess; -#else - extern "C" __declspec(dllimport) HANDLE_ WINAPI GetCurrentProcess(); -#endif -} -} -} -#endif // BOOST_DETAIL_WINAPI_GETCURRENTPROCESS_HPP diff --git a/utils/boost_idb/boost/detail/winapi/GetCurrentThread.hpp b/utils/boost_idb/boost/detail/winapi/GetCurrentThread.hpp deleted file mode 100644 index 595b751d..00000000 --- a/utils/boost_idb/boost/detail/winapi/GetCurrentThread.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// GetCurrentThread.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_GETCURRENTTHREAD_HPP -#define BOOST_DETAIL_WINAPI_GETCURRENTTHREAD_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( UNDER_CE ) -// Windows CE define GetCurrentThread as an inline function in kfuncs.h -inline HANDLE_ GetCurrentThread() -{ - return ::GetCurrentThread(); -} -#else -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetCurrentThread; -#else - extern "C" __declspec(dllimport) HANDLE_ WINAPI GetCurrentThread(); -#endif -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_GETCURRENTTHREAD_HPP diff --git a/utils/boost_idb/boost/detail/winapi/GetLastError.hpp b/utils/boost_idb/boost/detail/winapi/GetLastError.hpp deleted file mode 100644 index 6e9e2d99..00000000 --- a/utils/boost_idb/boost/detail/winapi/GetLastError.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// GetLastError.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_GETLASTERROR_HPP -#define BOOST_DETAIL_WINAPI_GETLASTERROR_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetLastError; -#else - extern "C" __declspec(dllimport) DWORD_ WINAPI - GetLastError(); -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_GETLASTERROR_HPP diff --git a/utils/boost_idb/boost/detail/winapi/GetProcessTimes.hpp b/utils/boost_idb/boost/detail/winapi/GetProcessTimes.hpp deleted file mode 100644 index f2860b06..00000000 --- a/utils/boost_idb/boost/detail/winapi/GetProcessTimes.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// GetProcessTimes.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_GETPROCESSTIMES_HPP -#define BOOST_DETAIL_WINAPI_GETPROCESSTIMES_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if !defined(UNDER_CE) // Windows CE does not define GetProcessTimes -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetProcessTimes; -#else - extern "C" __declspec(dllimport) BOOL_ WINAPI - GetProcessTimes( - HANDLE_ hProcess, - LPFILETIME_ lpCreationTime, - LPFILETIME_ lpExitTime, - LPFILETIME_ lpKernelTime, - LPFILETIME_ lpUserTime - ); -#endif -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_GETPROCESSTIMES_HPP diff --git a/utils/boost_idb/boost/detail/winapi/GetThreadTimes.hpp b/utils/boost_idb/boost/detail/winapi/GetThreadTimes.hpp deleted file mode 100644 index 3428edad..00000000 --- a/utils/boost_idb/boost/detail/winapi/GetThreadTimes.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// GetThreadTimes.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_GETTHREADTIMES_HPP -#define BOOST_DETAIL_WINAPI_GETTHREADTIMES_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetThreadTimes; -#else - extern "C" __declspec(dllimport) BOOL_ WINAPI - GetThreadTimes( - HANDLE_ hThread, - LPFILETIME_ lpCreationTime, - LPFILETIME_ lpExitTime, - LPFILETIME_ lpKernelTime, - LPFILETIME_ lpUserTime - ); -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_GETTHREADTIMES_HPP diff --git a/utils/boost_idb/boost/detail/winapi/LocalFree.hpp b/utils/boost_idb/boost/detail/winapi/LocalFree.hpp deleted file mode 100644 index 697016c0..00000000 --- a/utils/boost_idb/boost/detail/winapi/LocalFree.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// LocalFree.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_LOCALFREE_HPP -#define BOOST_DETAIL_WINAPI_LOCALFREE_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - typedef HANDLE_ HLOCAL_; - - using ::LocalFree; -#else - extern "C" typedef HANDLE_ HLOCAL_; - extern "C" __declspec(dllimport) HLOCAL_ WINAPI - LocalFree(HLOCAL_ hMem); -#endif -} -} -} -#endif // BOOST_DETAIL_WINAPI_LOCALFREE_HPP diff --git a/utils/boost_idb/boost/detail/winapi/basic_types.hpp b/utils/boost_idb/boost/detail/winapi/basic_types.hpp deleted file mode 100644 index e9ca3700..00000000 --- a/utils/boost_idb/boost/detail/winapi/basic_types.hpp +++ /dev/null @@ -1,116 +0,0 @@ -// basic_types.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP -#define BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP - -#include -#include -#include - -#if defined( BOOST_USE_WINDOWS_H ) -# include -#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined(__CYGWIN__) -# include -// @FIXME Which condition must be tested -# ifdef UNDER_CE -# ifndef WINAPI -# ifndef _WIN32_WCE_EMULATION -# define WINAPI __cdecl // Note this doesn't match the desktop definition -# else -# define WINAPI __stdcall -# endif -# endif -# else -# ifndef WINAPI -# define WINAPI __stdcall -# endif -# endif -#else -# error "Win32 functions not available" -#endif - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - typedef ::BOOL BOOL_; - typedef ::WORD WORD_; - typedef ::DWORD DWORD_; - typedef ::HANDLE HANDLE_; - typedef ::LONG LONG_; - typedef ::LONGLONG LONGLONG_; - typedef ::ULONG_PTR ULONG_PTR_; - typedef ::LARGE_INTEGER LARGE_INTEGER_; - typedef ::PLARGE_INTEGER PLARGE_INTEGER_; - typedef ::PVOID PVOID_; - typedef ::LPVOID LPVOID_; - typedef ::CHAR CHAR_; - typedef ::LPSTR LPSTR_; - typedef ::LPCSTR LPCSTR_; - typedef ::WCHAR WCHAR_; - typedef ::LPWSTR LPWSTR_; - typedef ::LPCWSTR LPCWSTR_; -#else -extern "C" { - typedef int BOOL_; - typedef unsigned short WORD_; - typedef unsigned long DWORD_; - typedef void* HANDLE_; - - typedef long LONG_; - -// @FIXME Which condition must be tested -//~ #if !defined(_M_IX86) -//~ #if defined(BOOST_NO_INT64_T) - //~ typedef double LONGLONG_; -//~ #else - //~ typedef __int64 LONGLONG_; -//~ #endif -//~ #else - //~ typedef double LONGLONG_; -//~ #endif - typedef boost::int64_t LONGLONG_; - -// @FIXME Which condition must be tested -# ifdef _WIN64 -#if defined(__CYGWIN__) - typedef unsigned long ULONG_PTR_; -#else - typedef unsigned __int64 ULONG_PTR_; -#endif -# else - typedef unsigned long ULONG_PTR_; -# endif - - typedef struct _LARGE_INTEGER { - LONGLONG_ QuadPart; - } LARGE_INTEGER_; - typedef LARGE_INTEGER_ *PLARGE_INTEGER_; - - typedef void *PVOID_; - typedef void *LPVOID_; - typedef const void *LPCVOID_; - - typedef char CHAR_; - typedef CHAR_ *LPSTR_; - typedef const CHAR_ *LPCSTR_; - - typedef wchar_t WCHAR_; - typedef WCHAR_ *LPWSTR_; - typedef const WCHAR_ *LPCWSTR_; -} -#endif -} -} -} -#endif // BOOST_DETAIL_WINAPI_TIME_HPP diff --git a/utils/boost_idb/boost/detail/winapi/directory_management.hpp b/utils/boost_idb/boost/detail/winapi/directory_management.hpp deleted file mode 100644 index 19af1ee4..00000000 --- a/utils/boost_idb/boost/detail/winapi/directory_management.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// directory_management.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_DIRECTORY_MANAGEMENT_HPP -#define BOOST_DETAIL_WINAPI_DIRECTORY_MANAGEMENT_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::CreateDirectory; - using ::CreateDirectoryA; - using ::GetTempPathA; - using ::RemoveDirectoryA; -#else -extern "C" { - __declspec(dllimport) int __stdcall - CreateDirectory(LPCTSTR_, LPSECURITY_ATTRIBUTES_*); - __declspec(dllimport) int __stdcall - CreateDirectoryA(LPCTSTR_, interprocess_security_attributes*); - __declspec(dllimport) int __stdcall - GetTempPathA(unsigned long length, char *buffer); - __declspec(dllimport) int __stdcall - RemoveDirectoryA(LPCTSTR_); -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_THREAD_HPP diff --git a/utils/boost_idb/boost/detail/winapi/dll.hpp b/utils/boost_idb/boost/detail/winapi/dll.hpp deleted file mode 100644 index ed452727..00000000 --- a/utils/boost_idb/boost/detail/winapi/dll.hpp +++ /dev/null @@ -1,55 +0,0 @@ -// dll.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_DLL_HPP -#define BOOST_DETAIL_WINAPI_DLL_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::LoadLibrary; - using ::FreeLibrary; - using ::GetProcAddress; - using ::GetModuleHandleA; -#else -extern "C" { - __declspec(dllimport) HMODULE_ __stdcall - LoadLibrary( - LPCTSTR_ lpFileName - ); - __declspec(dllimport) BOOL_ __stdcall - FreeLibrary( - HMODULE_ hModule - ); - __declspec(dllimport) FARPROC_ __stdcall - GetProcAddress( - HMODULE_ hModule, - LPCSTR_ lpProcName - ); - __declspec(dllimport) FARPROC_ __stdcall - GetModuleHandleA( - LPCSTR_ lpProcName - ); -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_THREAD_HPP diff --git a/utils/boost_idb/boost/detail/winapi/error_handling.hpp b/utils/boost_idb/boost/detail/winapi/error_handling.hpp deleted file mode 100644 index fbe9924b..00000000 --- a/utils/boost_idb/boost/detail/winapi/error_handling.hpp +++ /dev/null @@ -1,93 +0,0 @@ -// error_handling.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_ERROR_HANDLING_HPP -#define BOOST_DETAIL_WINAPI_ERROR_HANDLING_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { - -#if defined( BOOST_USE_WINDOWS_H ) - using ::FormatMessageA; - using ::FormatMessageW; - - const int FORMAT_MESSAGE_ALLOCATE_BUFFER_= FORMAT_MESSAGE_ALLOCATE_BUFFER; - const int FORMAT_MESSAGE_IGNORE_INSERTS_= FORMAT_MESSAGE_IGNORE_INSERTS; - const int FORMAT_MESSAGE_FROM_STRING_= FORMAT_MESSAGE_FROM_STRING; - const int FORMAT_MESSAGE_FROM_HMODULE_= FORMAT_MESSAGE_FROM_HMODULE; - const int FORMAT_MESSAGE_FROM_SYSTEM_= FORMAT_MESSAGE_FROM_SYSTEM; - const int FORMAT_MESSAGE_ARGUMENT_ARRAY_= FORMAT_MESSAGE_ARGUMENT_ARRAY; - const int FORMAT_MESSAGE_MAX_WIDTH_MASK_= FORMAT_MESSAGE_MAX_WIDTH_MASK; - - const char LANG_NEUTRAL_= LANG_NEUTRAL; - const char LANG_INVARIANT_= LANG_INVARIANT; - - const char SUBLANG_DEFAULT_= SUBLANG_DEFAULT; // user default - inline WORD_ MAKELANGID_(WORD_ p, WORD_ s) { - return MAKELANGID(p,s); - } -#else -extern "C" { - // using ::FormatMessageA; - __declspec(dllimport) - DWORD_ - WINAPI - FormatMessageA( - DWORD_ dwFlags, - LPCVOID_ lpSource, - DWORD_ dwMessageId, - DWORD_ dwLanguageId, - LPSTR_ lpBuffer, - DWORD_ nSize, - va_list *Arguments - ); - - // using ::FormatMessageW; - __declspec(dllimport) - DWORD_ - WINAPI - FormatMessageW( - DWORD_ dwFlags, - LPCVOID_ lpSource, - DWORD_ dwMessageId, - DWORD_ dwLanguageId, - LPWSTR_ lpBuffer, - DWORD_ nSize, - va_list *Arguments - ); - - const int FORMAT_MESSAGE_ALLOCATE_BUFFER_= 0x00000100; - const int FORMAT_MESSAGE_IGNORE_INSERTS_= 0x00000200; - const int FORMAT_MESSAGE_FROM_STRING_= 0x00000400; - const int FORMAT_MESSAGE_FROM_HMODULE_= 0x00000800; - const int FORMAT_MESSAGE_FROM_SYSTEM_= 0x00001000; - const int FORMAT_MESSAGE_ARGUMENT_ARRAY_= 0x00002000; - const int FORMAT_MESSAGE_MAX_WIDTH_MASK_= 0x000000FF; - - const char LANG_NEUTRAL_= 0x00; - const char LANG_INVARIANT_= 0x7f; - - const char SUBLANG_DEFAULT_= 0x01; // user default - inline WORD_ MAKELANGID_(WORD_ p, WORD_ s) { - return ((((WORD_ )(s)) << 10) | (WORD_ )(p)); - } - -} -#endif -} -} -} -#endif // BOOST_DETAIL_WINAPI_ERROR_HANDLING_HPP diff --git a/utils/boost_idb/boost/detail/winapi/file_management.hpp b/utils/boost_idb/boost/detail/winapi/file_management.hpp deleted file mode 100644 index c1d5978b..00000000 --- a/utils/boost_idb/boost/detail/winapi/file_management.hpp +++ /dev/null @@ -1,130 +0,0 @@ -// thread.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_FILE_MANAGEMENT_HPP -#define BOOST_DETAIL_WINAPI_FILE_MANAGEMENT_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::CreateFileA; - using ::DeleteFileA; - using ::FindFirstFileA; - using ::FindNextFileA; - using ::FindClose; - using ::GetFileSizeEx; - using ::MoveFileExA; - using ::SetFileValidData; -#else -extern "C" { - typedef struct _OVERLAPPED { - ULONG_PTR Internal; - ULONG_PTR InternalHigh; - union { - struct { - DWORD Offset; - DWORD OffsetHigh; - } ; - PVOID Pointer; - } ; - HANDLE hEvent; - } OVERLAPPED, *LPOVERLAPPED; - - - __declspec(dllimport) void * __stdcall - CreateFileA (const char *, unsigned long, unsigned long, struct SECURITY_ATTRIBUTES_*, unsigned long, unsigned long, void *); - __declspec(dllimport) int __stdcall - DeleteFileA (const char *); - __declspec(dllimport) void *__stdcall - FindFirstFileA(const char *lpFileName, win32_find_data_t *lpFindFileData); - __declspec(dllimport) int __stdcall - FindNextFileA(void *hFindFile, win32_find_data_t *lpFindFileData); - __declspec(dllimport) int __stdcall - FindClose(void *hFindFile); - __declspec(dllimport) BOOL __stdcall - GetFileSizeEx( - HANDLE_ hFile, - PLARGE_INTEGER_ lpFileSize - ); - __declspec(dllimport) int __stdcall - MoveFileExA (const char *, const char *, unsigned long); - __declspec(dllimport) BOOL_ __stdcall - SetFileValidData( - HANDLE_ hFile, - LONGLONG_ ValidDataLength - ); - __declspec(dllimport) BOOL_ __stdcall - SetEndOfFile( - HANDLE_ hFile - ); - __declspec(dllimport) BOOL_ __stdcall - SetFilePointerEx( - HANDLE_ hFile, - LARGE_INTEGER_ liDistanceToMove, - PLARGE_INTEGER_ lpNewFilePointer, - DWORD_ dwMoveMethod - ); - __declspec(dllimport) BOOL_ __stdcall - LockFile( - HANDLE_ hFile, - DWORD_ dwFileOffsetLow, - DWORD_ dwFileOffsetHigh, - DWORD_ nNumberOfBytesToLockLow, - DWORD_ nNumberOfBytesToLockHigh - ); - __declspec(dllimport) BOOL_ __stdcall - UnlockFile( - HANDLE_ hFile, - DWORD_ dwFileOffsetLow, - DWORD_ dwFileOffsetHigh, - DWORD_ nNumberOfBytesToUnlockLow, - DWORD_ nNumberOfBytesToUnlockHigh - ); - __declspec(dllimport) BOOL_ __stdcall - LockFileEx( - HANDLE_ hFile, - DWORD_ dwFlags, - DWORD_ dwReserved, - DWORD_ nNumberOfBytesToLockLow, - DWORD_ nNumberOfBytesToLockHigh, - LPOVERLAPPED_ lpOverlapped - ); - __declspec(dllimport) BOOL_ __stdcall - UnlockFileEx( - HANDLE_ hFile, - DWORD_ dwReserved, - DWORD_ nNumberOfBytesToUnlockLow, - DWORD_ nNumberOfBytesToUnlockHigh, - LPOVERLAPPED_ lpOverlapped - ); - __declspec(dllimport) BOOL_ __stdcall - WriteFile( - HANDLE_ hFile, - LPCVOID_ lpBuffer, - DWORD_ nNumberOfBytesToWrite, - LPDWORD_ lpNumberOfBytesWritten, - LPOVERLAPPED_ lpOverlapped - ); -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_THREAD_HPP diff --git a/utils/boost_idb/boost/detail/winapi/handles.hpp b/utils/boost_idb/boost/detail/winapi/handles.hpp deleted file mode 100644 index d4cffc80..00000000 --- a/utils/boost_idb/boost/detail/winapi/handles.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// memory.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_HANDLES_HPP -#define BOOST_DETAIL_WINAPI_HANDLES_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::CloseHandle; - using ::DuplicateHandle; -#else -extern "C" { - __declspec(dllimport) int __stdcall - CloseHandle(void*); - __declspec(dllimport) int __stdcall - DuplicateHandle(void*,void*,void*,void**,unsigned long,int,unsigned long); -} - -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_HANDLES_HPP diff --git a/utils/boost_idb/boost/detail/winapi/memory.hpp b/utils/boost_idb/boost/detail/winapi/memory.hpp deleted file mode 100644 index b5316e09..00000000 --- a/utils/boost_idb/boost/detail/winapi/memory.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// memory.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_MEMORY_HPP -#define BOOST_DETAIL_WINAPI_MEMORY_HPP - -#include -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::CreateFileMappingA; - using ::FlushViewOfFile; - using ::GetProcessHeap; - using ::HeapAlloc; - using ::HeapFree; - using ::MapViewOfFileEx; - using ::OpenFileMappingA; - using ::UnmapViewOfFile; -#else -#undef HeapAlloc -extern "C" { - __declspec(dllimport) void * __stdcall - CreateFileMappingA (void *, SECURITY_ATTRIBUTES_*, unsigned long, unsigned long, unsigned long, const char *); - __declspec(dllimport) int __stdcall - FlushViewOfFile (void *, std::size_t); - __declspec(dllimport) HANDLE_ __stdcall - GetProcessHeap(); - __declspec(dllimport) void* __stdcall - HeapAlloc(HANDLE_,DWORD_,SIZE_T_); - __declspec(dllimport) BOOL_ __stdcall - HeapFree(HANDLE_,DWORD_,LPVOID_); - __declspec(dllimport) void * __stdcall - MapViewOfFileEx (void *, unsigned long, unsigned long, unsigned long, std::size_t, void*); - __declspec(dllimport) void * __stdcall - OpenFileMappingA (unsigned long, int, const char *); - __declspec(dllimport) int __stdcall - UnmapViewOfFile(void *); -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_MEMORY_HPP diff --git a/utils/boost_idb/boost/detail/winapi/process.hpp b/utils/boost_idb/boost/detail/winapi/process.hpp deleted file mode 100644 index 411ffaf8..00000000 --- a/utils/boost_idb/boost/detail/winapi/process.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// process.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_PROCESS_HPP -#define BOOST_DETAIL_WINAPI_PROCESS_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetCurrentProcessId; -#else -# ifndef UNDER_CE -extern "C" { - __declspec(dllimport) unsigned long __stdcall - GetCurrentProcessId(void); -} -# else - using ::GetCurrentProcessId; -# endif -#endif -} -} -} -#endif // BOOST_DETAIL_WINAPI_PROCESS_HPP diff --git a/utils/boost_idb/boost/detail/winapi/security.hpp b/utils/boost_idb/boost/detail/winapi/security.hpp deleted file mode 100644 index 79925c6c..00000000 --- a/utils/boost_idb/boost/detail/winapi/security.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// security.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_SECURITY_HPP -#define BOOST_DETAIL_WINAPI_SECURITY_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) -typedef ::SECURITY_ATTRIBUTES SECURITY_ATTRIBUTES_; -typedef ::PSECURITY_ATTRIBUTES PSECURITY_ATTRIBUTES_; -typedef ::LPSECURITY_ATTRIBUTES LPSECURITY_ATTRIBUTES_; - -#else -extern "C" { - struct SECURITY_DESCRIPTOR_; - typedef SECURITY_DESCRIPTOR_* PSECURITY_DESCRIPTOR_; - typedef struct _ACL { - BYTE_ AclRevision; - BYTE_ Sbz1; - WORD_ AclSize; - WORD_ AceCount; - WORD_ Sbz2; - } ACL_, *PACL_; - - typedef struct _SECURITY_ATTRIBUTES { - DWORD_ nLength; - LPVOID_ lpSecurityDescriptor; - BOOL_ bInheritHandle; - } SECURITY_ATTRIBUTES_, *PSECURITY_ATTRIBUTES_, *LPSECURITY_ATTRIBUTES_; - - __declspec(dllimport) BOOL_ __stdcall - InitializeSecurityDescriptor( - PSECURITY_DESCRIPTOR_ pSecurityDescriptor, - DWORD_ dwRevision - ); - __declspec(dllimport) BOOL_ __stdcall - SetSecurityDescriptorDacl( - PSECURITY_DESCRIPTOR_ pSecurityDescriptor, - BOOL_ bDaclPresent, - PACL_ pDacl, - BOOL_ bDaclDefaulted - ); -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_SECURITY_HPP diff --git a/utils/boost_idb/boost/detail/winapi/synchronization.hpp b/utils/boost_idb/boost/detail/winapi/synchronization.hpp deleted file mode 100644 index 5d3327af..00000000 --- a/utils/boost_idb/boost/detail/winapi/synchronization.hpp +++ /dev/null @@ -1,146 +0,0 @@ -// synchronizaion.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_SYNCHRONIZATION_HPP -#define BOOST_DETAIL_WINAPI_SYNCHRONIZATION_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - typedef ::CRITICAL_SECTION CRITICAL_SECTION_; - typedef ::PAPCFUNC PAPCFUNC_; - - using ::InitializeCriticalSection; - using ::EnterCriticalSection; - using ::TryEnterCriticalSection; - using ::LeaveCriticalSection; - using ::DeleteCriticalSection; - -# ifdef BOOST_NO_ANSI_APIS - using ::CreateMutexW; - using ::CreateEventW; - using ::OpenEventW; - using ::CreateSemaphoreW; -# else - using ::CreateMutexA; - using ::CreateEventA; - using ::OpenEventA; - using ::CreateSemaphoreA; -# endif - using ::ReleaseMutex; - using ::ReleaseSemaphore; - using ::SetEvent; - using ::ResetEvent; - using ::WaitForMultipleObjects; - using ::WaitForSingleObject; - using ::QueueUserAPC; - - const DWORD_ infinite = INFINITE; - const DWORD_ wait_abandoned = WAIT_ABANDONED; - const DWORD_ wait_object_0 = WAIT_OBJECT_0; - const DWORD_ wait_timeout = WAIT_TIMEOUT; - const DWORD_ wait_failed = WAIT_FAILED; - -#else // defined( BOOST_USE_WINDOWS_H ) - -extern "C" { - - struct CRITICAL_SECTION_ - { - struct critical_section_debug * DebugInfo; - long LockCount; - long RecursionCount; - void * OwningThread; - void * LockSemaphore; - #if defined(_WIN64) - unsigned __int64 SpinCount; - #else - unsigned long SpinCount; - #endif - }; - - __declspec(dllimport) void __stdcall - InitializeCriticalSection(CRITICAL_SECTION_ *); - __declspec(dllimport) void __stdcall - EnterCriticalSection(CRITICAL_SECTION_ *); - __declspec(dllimport) bool __stdcall - TryEnterCriticalSection(CRITICAL_SECTION_ *); - __declspec(dllimport) void __stdcall - LeaveCriticalSection(CRITICAL_SECTION_ *); - __declspec(dllimport) void __stdcall - DeleteCriticalSection(CRITICAL_SECTION_ *); - - struct _SECURITY_ATTRIBUTES; -# ifdef BOOST_NO_ANSI_APIS - __declspec(dllimport) void* __stdcall - CreateMutexW(_SECURITY_ATTRIBUTES*,int,wchar_t const*); - __declspec(dllimport) void* __stdcall - CreateSemaphoreW(_SECURITY_ATTRIBUTES*,long,long,wchar_t const*); - __declspec(dllimport) void* __stdcall - CreateEventW(_SECURITY_ATTRIBUTES*,int,int,wchar_t const*); - __declspec(dllimport) void* __stdcall - OpenEventW(unsigned long,int,wchar_t const*); -# else - __declspec(dllimport) void* __stdcall - CreateMutexA(_SECURITY_ATTRIBUTES*,int,char const*); - __declspec(dllimport) void* __stdcall - CreateSemaphoreA(_SECURITY_ATTRIBUTES*,long,long,char const*); - __declspec(dllimport) void* __stdcall - CreateEventA(_SECURITY_ATTRIBUTES*,int,int,char const*); - __declspec(dllimport) void* __stdcall - OpenEventA(unsigned long,int,char const*); -# endif - __declspec(dllimport) int __stdcall - ReleaseMutex(void*); - __declspec(dllimport) unsigned long __stdcall - WaitForSingleObject(void*,unsigned long); - __declspec(dllimport) unsigned long __stdcall - WaitForMultipleObjects(unsigned long nCount, - void* const * lpHandles, - int bWaitAll, - unsigned long dwMilliseconds); - __declspec(dllimport) int __stdcall - ReleaseSemaphore(void*,long,long*); - typedef void (__stdcall *PAPCFUNC8)(ULONG_PTR_); - __declspec(dllimport) unsigned long __stdcall - QueueUserAPC(PAPCFUNC8,void*,ULONG_PTR_); -# ifndef UNDER_CE - __declspec(dllimport) int __stdcall - SetEvent(void*); - __declspec(dllimport) int __stdcall - ResetEvent(void*); -# else - using ::SetEvent; - using ::ResetEvent; -# endif - -} // extern "C" - - const DWORD_ infinite = (DWORD_)0xFFFFFFFF; - const DWORD_ wait_abandoned = 0x00000080L; - const DWORD_ wait_object_0 = 0x00000000L; - const DWORD_ wait_timeout = 0x00000102L; - const DWORD_ wait_failed = (DWORD_)0xFFFFFFFF; - -#endif // defined( BOOST_USE_WINDOWS_H ) - -} -} -} - -#endif // BOOST_DETAIL_WINAPI_SYNCHRONIZATION_HPP diff --git a/utils/boost_idb/boost/detail/winapi/system.hpp b/utils/boost_idb/boost/detail/winapi/system.hpp deleted file mode 100644 index 35b6682e..00000000 --- a/utils/boost_idb/boost/detail/winapi/system.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// system.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_SYSTEM_HPP -#define BOOST_DETAIL_WINAPI_SYSTEM_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - typedef ::SYSTEM_INFO SYSTEM_INFO_; - extern "C" __declspec(dllimport) void __stdcall GetSystemInfo (struct system_info *); -#else -extern "C" { - typedef struct _SYSTEM_INFO { - union { - DWORD_ dwOemId; - struct { - WORD_ wProcessorArchitecture; - WORD_ wReserved; - } dummy; - } ; - DWORD_ dwPageSize; - LPVOID_ lpMinimumApplicationAddress; - LPVOID_ lpMaximumApplicationAddress; - DWORD_PTR_ dwActiveProcessorMask; - DWORD_ dwNumberOfProcessors; - DWORD_ dwProcessorType; - DWORD_ dwAllocationGranularity; - WORD_ wProcessorLevel; - WORD_ wProcessorRevision; - } SYSTEM_INFO_; - - __declspec(dllimport) void __stdcall - GetSystemInfo (struct system_info *); -} -#endif -} -} -} -#endif // BOOST_DETAIL_WINAPI_SYSTEM_HPP diff --git a/utils/boost_idb/boost/detail/winapi/thread.hpp b/utils/boost_idb/boost/detail/winapi/thread.hpp deleted file mode 100644 index 3c1be666..00000000 --- a/utils/boost_idb/boost/detail/winapi/thread.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// thread.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_THREAD_HPP -#define BOOST_DETAIL_WINAPI_THREAD_HPP - -#include -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::GetCurrentThreadId; - using ::SleepEx; - using ::Sleep; -#else -extern "C" { -# ifndef UNDER_CE - __declspec(dllimport) unsigned long __stdcall - GetCurrentThreadId(void); - __declspec(dllimport) unsigned long __stdcall - SleepEx(unsigned long,int); - __declspec(dllimport) void __stdcall - Sleep(unsigned long); -#else - using ::GetCurrentThreadId; - using ::SleepEx; - using ::Sleep; -#endif -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_THREAD_HPP diff --git a/utils/boost_idb/boost/detail/winapi/time.hpp b/utils/boost_idb/boost/detail/winapi/time.hpp deleted file mode 100644 index b3e4c441..00000000 --- a/utils/boost_idb/boost/detail/winapi/time.hpp +++ /dev/null @@ -1,85 +0,0 @@ -// time.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_TIME_HPP -#define BOOST_DETAIL_WINAPI_TIME_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost { -namespace detail { -namespace winapi { -#if defined( BOOST_USE_WINDOWS_H ) - typedef FILETIME FILETIME_; - typedef PFILETIME PFILETIME_; - typedef LPFILETIME LPFILETIME_; - - typedef SYSTEMTIME SYSTEMTIME_; - typedef SYSTEMTIME* PSYSTEMTIME_; - - #ifdef BOOST_HAS_GETSYSTEMTIMEASFILETIME // Windows CE does not define GetSystemTimeAsFileTime - using ::GetSystemTimeAsFileTime; - #endif - using ::FileTimeToLocalFileTime; - using ::GetSystemTime; - using ::SystemTimeToFileTime; - using ::GetTickCount; - -#else -extern "C" { - typedef struct _FILETIME { - DWORD_ dwLowDateTime; - DWORD_ dwHighDateTime; - } FILETIME_, *PFILETIME_, *LPFILETIME_; - - typedef struct _SYSTEMTIME { - WORD_ wYear; - WORD_ wMonth; - WORD_ wDayOfWeek; - WORD_ wDay; - WORD_ wHour; - WORD_ wMinute; - WORD_ wSecond; - WORD_ wMilliseconds; - } SYSTEMTIME_, *PSYSTEMTIME_; - - #ifdef BOOST_HAS_GETSYSTEMTIMEASFILETIME // Windows CE does not define GetSystemTimeAsFileTime - __declspec(dllimport) void WINAPI - GetSystemTimeAsFileTime(FILETIME_* lpFileTime); - #endif - __declspec(dllimport) int WINAPI - FileTimeToLocalFileTime(const FILETIME_* lpFileTime, - FILETIME_* lpLocalFileTime); - __declspec(dllimport) void WINAPI - GetSystemTime(SYSTEMTIME_* lpSystemTime); - __declspec(dllimport) int WINAPI - SystemTimeToFileTime(const SYSTEMTIME_* lpSystemTime, - FILETIME_* lpFileTime); - __declspec(dllimport) DWORD_ WINAPI - GetTickCount(); -} -#endif - -#ifndef BOOST_HAS_GETSYSTEMTIMEASFILETIME -inline void WINAPI GetSystemTimeAsFileTime(FILETIME_* lpFileTime) -{ - SYSTEMTIME_ st; - GetSystemTime(&st); - SystemTimeToFileTime(&st, lpFileTime); -} -#endif - -} -} -} - -#endif // BOOST_DETAIL_WINAPI_TIME_HPP diff --git a/utils/boost_idb/boost/detail/winapi/timers.hpp b/utils/boost_idb/boost/detail/winapi/timers.hpp deleted file mode 100644 index 04c6dfbc..00000000 --- a/utils/boost_idb/boost/detail/winapi/timers.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// timers.hpp --------------------------------------------------------------// - -// Copyright 2010 Vicente J. Botet Escriba - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - - -#ifndef BOOST_DETAIL_WINAPI_TIMERS_HPP -#define BOOST_DETAIL_WINAPI_TIMERS_HPP - -#include - -#ifdef BOOST_HAS_PRAGMA_ONCE -#pragma once -#endif - -namespace boost -{ -namespace detail -{ -namespace winapi -{ -#if defined( BOOST_USE_WINDOWS_H ) - using ::QueryPerformanceCounter; - using ::QueryPerformanceFrequency; -#else -extern "C" { - __declspec(dllimport) BOOL_ WINAPI - QueryPerformanceCounter( - LARGE_INTEGER_ *lpPerformanceCount - ); - - __declspec(dllimport) BOOL_ WINAPI - QueryPerformanceFrequency( - LARGE_INTEGER_ *lpFrequency - ); -} -#endif -} -} -} - -#endif // BOOST_DETAIL_WINAPI_TIMERS_HPP diff --git a/utils/boost_idb/boost/dynamic_bitset.hpp b/utils/boost_idb/boost/dynamic_bitset.hpp new file mode 100644 index 00000000..29e10386 --- /dev/null +++ b/utils/boost_idb/boost/dynamic_bitset.hpp @@ -0,0 +1,17 @@ +// ----------------------------------------------------------- +// +// Copyright (c) 2001-2002 Chuck Allison and Jeremy Siek +// Copyright (c) 2003-2004, 2008 Gennaro Prota +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// ----------------------------------------------------------- + +#ifndef BOOST_DYNAMIC_BITSET_HPP +#define BOOST_DYNAMIC_BITSET_HPP + +#include "boost/dynamic_bitset/dynamic_bitset.hpp" + +#endif // include guard diff --git a/utils/boost_idb/boost/dynamic_bitset_fwd.hpp b/utils/boost_idb/boost/dynamic_bitset_fwd.hpp new file mode 100644 index 00000000..7bb6e897 --- /dev/null +++ b/utils/boost_idb/boost/dynamic_bitset_fwd.hpp @@ -0,0 +1,25 @@ +// ----------------------------------------------------------- +// +// Copyright (c) 2001-2002 Chuck Allison and Jeremy Siek +// Copyright (c) 2003-2004 Gennaro Prota +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// ----------------------------------------------------------- + +#ifndef BOOST_DYNAMIC_BITSET_FWD_HPP +#define BOOST_DYNAMIC_BITSET_FWD_HPP + +#include + +namespace boost { + +template > +class dynamic_bitset; + +} + +#endif // include guard diff --git a/utils/boost_idb/boost/exception/all.hpp b/utils/boost_idb/boost/exception/all.hpp index 32eb1505..9ffe42a9 100644 --- a/utils/boost_idb/boost/exception/all.hpp +++ b/utils/boost_idb/boost/exception/all.hpp @@ -5,7 +5,7 @@ #ifndef UUID_316FDA946C0D11DEA9CBAE5255D89593 #define UUID_316FDA946C0D11DEA9CBAE5255D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/exception/current_exception_cast.hpp b/utils/boost_idb/boost/exception/current_exception_cast.hpp index 5d81f00b..af2f1531 100644 --- a/utils/boost_idb/boost/exception/current_exception_cast.hpp +++ b/utils/boost_idb/boost/exception/current_exception_cast.hpp @@ -5,7 +5,7 @@ #ifndef UUID_7E83C166200811DE885E826156D89593 #define UUID_7E83C166200811DE885E826156D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/exception/detail/attribute_noreturn.hpp b/utils/boost_idb/boost/exception/detail/attribute_noreturn.hpp index ae9f031e..f6a0b590 100644 --- a/utils/boost_idb/boost/exception/detail/attribute_noreturn.hpp +++ b/utils/boost_idb/boost/exception/detail/attribute_noreturn.hpp @@ -9,7 +9,7 @@ #if defined(_MSC_VER) #define BOOST_ATTRIBUTE_NORETURN __declspec(noreturn) #elif defined(__GNUC__) -#define BOOST_ATTRIBUTE_NORETURN __attribute__((__noreturn__)) +#define BOOST_ATTRIBUTE_NORETURN __attribute__((noreturn)) #else #define BOOST_ATTRIBUTE_NORETURN #endif diff --git a/utils/boost_idb/boost/exception/detail/clone_current_exception.hpp b/utils/boost_idb/boost/exception/detail/clone_current_exception.hpp deleted file mode 100644 index 6fc13747..00000000 --- a/utils/boost_idb/boost/exception/detail/clone_current_exception.hpp +++ /dev/null @@ -1,56 +0,0 @@ -//Copyright (c) 2006-2013 Emil Dotchevski and Reverge Studios, Inc. - -//Distributed under the Boost Software License, Version 1.0. (See accompanying -//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef UUID_81522C0EB56511DFAB613DB0DFD72085 -#define UUID_81522C0EB56511DFAB613DB0DFD72085 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) -#pragma GCC system_header -#endif -#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) -#pragma warning(push,1) -#endif - -#ifdef BOOST_NO_EXCEPTIONS -# error This header requires exception handling to be enabled. -#endif - -namespace -boost - { - namespace - exception_detail - { - class clone_base; - -#ifdef BOOST_ENABLE_NON_INTRUSIVE_EXCEPTION_PTR - int clone_current_exception_non_intrusive( clone_base const * & cloned ); -#endif - - namespace - clone_current_exception_result - { - int const success=0; - int const bad_alloc=1; - int const bad_exception=2; - int const not_supported=3; - } - - inline - int - clone_current_exception( clone_base const * & cloned ) - { -#ifdef BOOST_ENABLE_NON_INTRUSIVE_EXCEPTION_PTR - return clone_current_exception_non_intrusive(cloned); -#else - return clone_current_exception_result::not_supported; -#endif - } - } - } - -#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) -#pragma warning(pop) -#endif -#endif diff --git a/utils/boost_idb/boost/exception/detail/error_info_impl.hpp b/utils/boost_idb/boost/exception/detail/error_info_impl.hpp index 12e601b5..883d313a 100644 --- a/utils/boost_idb/boost/exception/detail/error_info_impl.hpp +++ b/utils/boost_idb/boost/exception/detail/error_info_impl.hpp @@ -5,7 +5,7 @@ #ifndef UUID_CE6983AC753411DDA764247956D89593 #define UUID_CE6983AC753411DDA764247956D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -25,11 +25,11 @@ boost { public: - virtual std::string name_value_string() const = 0; + virtual std::string tag_typeid_name() const = 0; + virtual std::string value_as_string() const = 0; protected: - virtual ~error_info_base() throw() { } @@ -62,7 +62,8 @@ boost private: - std::string name_value_string() const; + std::string tag_typeid_name() const; + std::string value_as_string() const; value_type value_; }; diff --git a/utils/boost_idb/boost/exception/detail/exception_ptr.hpp b/utils/boost_idb/boost/exception/detail/exception_ptr.hpp index 36298fa4..0510fe2d 100644 --- a/utils/boost_idb/boost/exception/detail/exception_ptr.hpp +++ b/utils/boost_idb/boost/exception/detail/exception_ptr.hpp @@ -5,7 +5,7 @@ #ifndef UUID_618474C2DE1511DEB74A388C56D89593 #define UUID_618474C2DE1511DEB74A388C56D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -20,54 +20,17 @@ #include #include #include -#include -//#ifndef BOOST_NO_RTTI -//#include -//#endif #include #include #include #include -#include namespace boost { - class exception_ptr; - BOOST_ATTRIBUTE_NORETURN void rethrow_exception( exception_ptr const & ); - exception_ptr current_exception(); + typedef shared_ptr exception_ptr; - class - exception_ptr - { - typedef boost::shared_ptr impl; - impl ptr_; - friend void rethrow_exception( exception_ptr const & ); - typedef exception_detail::clone_base const * (impl::*unspecified_bool_type)() const; - public: - exception_ptr() - { - } - explicit - exception_ptr( impl const & ptr ): - ptr_(ptr) - { - } - bool - operator==( exception_ptr const & other ) const - { - return ptr_==other.ptr_; - } - bool - operator!=( exception_ptr const & other ) const - { - return ptr_!=other.ptr_; - } - operator unspecified_bool_type() const - { - return ptr_?&impl::get:0; - } - }; + exception_ptr current_exception(); template inline @@ -92,7 +55,7 @@ boost std::string to_string( original_exception_type const & x ) { - return /*units::detail::demangle*/(x.value()->name()); + return x.value()->name(); } #endif @@ -104,51 +67,35 @@ boost boost::exception, std::bad_alloc { - ~bad_alloc_() throw() { } }; - struct - bad_exception_: - boost::exception, - std::bad_exception - { - ~bad_exception_() throw() { } - }; - - template + template exception_ptr - get_static_exception_object() + get_bad_alloc() { - Exception ba; - exception_detail::clone_impl c(ba); -#ifndef BOOST_EXCEPTION_DISABLE + bad_alloc_ ba; + exception_detail::clone_impl c(ba); c << throw_function(BOOST_CURRENT_FUNCTION) << throw_file(__FILE__) << throw_line(__LINE__); -#endif - static exception_ptr ep(shared_ptr(new exception_detail::clone_impl(c))); + static exception_ptr ep(new exception_detail::clone_impl(c)); return ep; } - template + template struct - exception_ptr_static_exception_object + exception_ptr_bad_alloc { static exception_ptr const e; }; - template + template exception_ptr const - exception_ptr_static_exception_object:: - e = get_static_exception_object(); + exception_ptr_bad_alloc:: + e = get_bad_alloc(); } -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility push (default) -# endif -#endif class unknown_exception: public boost::exception, @@ -188,11 +135,6 @@ boost #endif } }; -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility pop -# endif -#endif namespace exception_detail @@ -302,131 +244,101 @@ boost exception_ptr current_exception_impl() { - exception_detail::clone_base const * e=0; - switch( - exception_detail::clone_current_exception(e) ) - { - case exception_detail::clone_current_exception_result:: - success: - { - BOOST_ASSERT(e!=0); - return exception_ptr(shared_ptr(e)); - } - case exception_detail::clone_current_exception_result:: - bad_alloc: - { - BOOST_ASSERT(!e); - return exception_detail::exception_ptr_static_exception_object::e; - } - case exception_detail::clone_current_exception_result:: - bad_exception: - { - BOOST_ASSERT(!e); - return exception_detail::exception_ptr_static_exception_object::e; - } - default: - BOOST_ASSERT(0); - case exception_detail::clone_current_exception_result:: - not_supported: - { - BOOST_ASSERT(!e); - try - { - throw; - } - catch( - exception_detail::clone_base & e ) - { - return exception_ptr(shared_ptr(e.clone())); - } - catch( - std::domain_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::invalid_argument & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::length_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::out_of_range & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::logic_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::range_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::overflow_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::underflow_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::ios_base::failure & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::runtime_error & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::bad_alloc & e ) - { - return exception_detail::current_exception_std_exception(e); - } + try + { + throw; + } + catch( + exception_detail::clone_base & e ) + { + return exception_ptr(e.clone()); + } + catch( + std::domain_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::invalid_argument & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::length_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::out_of_range & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::logic_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::range_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::overflow_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::underflow_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::ios_base::failure & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::runtime_error & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::bad_alloc & e ) + { + return exception_detail::current_exception_std_exception(e); + } #ifndef BOOST_NO_TYPEID - catch( - std::bad_cast & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::bad_typeid & e ) - { - return exception_detail::current_exception_std_exception(e); - } + catch( + std::bad_cast & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::bad_typeid & e ) + { + return exception_detail::current_exception_std_exception(e); + } #endif - catch( - std::bad_exception & e ) - { - return exception_detail::current_exception_std_exception(e); - } - catch( - std::exception & e ) - { - return exception_detail::current_exception_unknown_std_exception(e); - } - catch( - boost::exception & e ) - { - return exception_detail::current_exception_unknown_boost_exception(e); - } - catch( - ... ) - { - return exception_detail::current_exception_unknown_exception(); - } - } + catch( + std::bad_exception & e ) + { + return exception_detail::current_exception_std_exception(e); + } + catch( + std::exception & e ) + { + return exception_detail::current_exception_unknown_std_exception(e); + } + catch( + boost::exception & e ) + { + return exception_detail::current_exception_unknown_boost_exception(e); + } + catch( + ... ) + { + return exception_detail::current_exception_unknown_exception(); } } } @@ -436,6 +348,7 @@ boost current_exception() { exception_ptr ret; + BOOST_ASSERT(!ret); try { ret=exception_detail::current_exception_impl(); @@ -443,36 +356,41 @@ boost catch( std::bad_alloc & ) { - ret=exception_detail::exception_ptr_static_exception_object::e; + ret=exception_detail::exception_ptr_bad_alloc<42>::e; } catch( ... ) { - ret=exception_detail::exception_ptr_static_exception_object::e; + try + { + ret=exception_detail::current_exception_std_exception(std::bad_exception()); + } + catch( + std::bad_alloc & ) + { + ret=exception_detail::exception_ptr_bad_alloc<42>::e; + } + catch( + ... ) + { + BOOST_ASSERT(0); + } } BOOST_ASSERT(ret); return ret; } - BOOST_ATTRIBUTE_NORETURN inline void rethrow_exception( exception_ptr const & p ) { BOOST_ASSERT(p); - p.ptr_->rethrow(); - BOOST_ASSERT(0); - #if defined(UNDER_CE) - // some CE platforms don't define ::abort() - exit(-1); - #else - abort(); - #endif + p->rethrow(); } inline std::string - diagnostic_information( exception_ptr const & p, bool verbose=true ) + diagnostic_information( exception_ptr const & p ) { if( p ) try @@ -482,7 +400,7 @@ boost catch( ... ) { - return current_exception_diagnostic_information(verbose); + return current_exception_diagnostic_information(); } return ""; } diff --git a/utils/boost_idb/boost/exception/detail/is_output_streamable.hpp b/utils/boost_idb/boost/exception/detail/is_output_streamable.hpp index 847f3484..743313c1 100644 --- a/utils/boost_idb/boost/exception/detail/is_output_streamable.hpp +++ b/utils/boost_idb/boost/exception/detail/is_output_streamable.hpp @@ -5,7 +5,7 @@ #ifndef UUID_898984B4076411DD973EDFA055D89593 #define UUID_898984B4076411DD973EDFA055D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/exception/detail/object_hex_dump.hpp b/utils/boost_idb/boost/exception/detail/object_hex_dump.hpp index 53c8bf6f..ccf1bac3 100644 --- a/utils/boost_idb/boost/exception/detail/object_hex_dump.hpp +++ b/utils/boost_idb/boost/exception/detail/object_hex_dump.hpp @@ -5,7 +5,7 @@ #ifndef UUID_6F463AC838DF11DDA3E6909F56D89593 #define UUID_6F463AC838DF11DDA3E6909F56D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/exception/detail/type_info.hpp b/utils/boost_idb/boost/exception/detail/type_info.hpp index 0af8ef52..9ab1c57f 100644 --- a/utils/boost_idb/boost/exception/detail/type_info.hpp +++ b/utils/boost_idb/boost/exception/detail/type_info.hpp @@ -5,7 +5,7 @@ #ifndef UUID_C3E1741C754311DDB2834CCA55D89593 #define UUID_C3E1741C754311DDB2834CCA55D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -15,9 +15,9 @@ #include #include #include -//#ifndef BOOST_NO_TYPEID -//#include -//#endif +#ifndef BOOST_NO_TYPEID +#include +#endif #include namespace @@ -31,7 +31,7 @@ boost #ifdef BOOST_NO_TYPEID return BOOST_CURRENT_FUNCTION; #else - return /*units::detail::demangle*/(typeid(T*).name()); + return units::detail::demangle(typeid(T*).name()); #endif } @@ -43,7 +43,7 @@ boost #ifdef BOOST_NO_TYPEID return BOOST_CURRENT_FUNCTION; #else - return /*units::detail::demangle*/(typeid(T).name()); + return units::detail::demangle(typeid(T).name()); #endif } @@ -53,11 +53,11 @@ boost struct type_info_ { - detail::sp_typeinfo const * type_; + detail::sp_typeinfo const & type_; explicit type_info_( detail::sp_typeinfo const & type ): - type_(&type) + type_(type) { } @@ -65,7 +65,7 @@ boost bool operator<( type_info_ const & a, type_info_ const & b ) { - return 0!=(a.type_->before(*b.type_)); + return 0!=(a.type_.before(b.type_)); } }; } diff --git a/utils/boost_idb/boost/exception/diagnostic_information.hpp b/utils/boost_idb/boost/exception/diagnostic_information.hpp index 7889c8f9..1d6bc2cc 100644 --- a/utils/boost_idb/boost/exception/diagnostic_information.hpp +++ b/utils/boost_idb/boost/exception/diagnostic_information.hpp @@ -5,7 +5,7 @@ #ifndef UUID_0552D49838DD11DD90146B8956D89593 #define UUID_0552D49838DD11DD90146B8956D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -14,11 +14,10 @@ #include #include -#include #include -//#ifndef BOOST_NO_RTTI -//#include -//#endif +#ifndef BOOST_NO_RTTI +#include +#endif #include #include #include @@ -31,17 +30,17 @@ boost namespace exception_detail { - std::string diagnostic_information_impl( boost::exception const *, std::exception const *, bool, bool ); + std::string diagnostic_information_impl( boost::exception const *, std::exception const *, bool ); } inline std::string - current_exception_diagnostic_information( bool verbose=true) + current_exception_diagnostic_information() { boost::exception const * be=current_exception_cast(); std::exception const * se=current_exception_cast(); if( be || se ) - return exception_detail::diagnostic_information_impl(be,se,true,verbose); + return exception_detail::diagnostic_information_impl(be,se,true); else return "No diagnostic information available."; } @@ -86,28 +85,24 @@ boost char const * get_diagnostic_information( exception const & x, char const * header ) { + if( error_info_container * c=x.data_.get() ) #ifndef BOOST_NO_EXCEPTIONS - try - { + try + { #endif - error_info_container * c=x.data_.get(); - if( !c ) - x.data_.adopt(c=new exception_detail::error_info_container_impl); - char const * di=c->diagnostic_information(header); - BOOST_ASSERT(di!=0); - return di; + return c->diagnostic_information(header); #ifndef BOOST_NO_EXCEPTIONS - } - catch(...) - { - return 0; - } + } + catch(...) + { + } #endif + return 0; } inline std::string - diagnostic_information_impl( boost::exception const * be, std::exception const * se, bool with_what, bool verbose ) + diagnostic_information_impl( boost::exception const * be, std::exception const * se, bool with_what ) { if( !be && !se ) return "Unknown exception."; @@ -125,65 +120,53 @@ boost return wh; } std::ostringstream tmp; - if( be && verbose ) + if( be ) { - char const * const * f=get_error_info(*be); - int const * l=get_error_info(*be); - char const * const * fn=get_error_info(*be); - if( !f && !l && !fn ) - tmp << "Throw location unknown (consider using BOOST_THROW_EXCEPTION)\n"; - else + if( char const * const * f=get_error_info(*be) ) { - if( f ) - { - tmp << *f; - if( int const * l=get_error_info(*be) ) - tmp << '(' << *l << "): "; - } - tmp << "Throw in function "; - if( char const * const * fn=get_error_info(*be) ) - tmp << *fn; - else - tmp << "(unknown)"; - tmp << '\n'; + tmp << *f; + if( int const * l=get_error_info(*be) ) + tmp << '(' << *l << "): "; } + tmp << "Throw in function "; + if( char const * const * fn=get_error_info(*be) ) + tmp << *fn; + else + tmp << "(unknown)"; + tmp << '\n'; } #ifndef BOOST_NO_RTTI - if ( verbose ) - tmp << std::string("Dynamic exception type: ") << - /*units::detail::demangle*/((be?(BOOST_EXCEPTION_DYNAMIC_TYPEID(*be)):(BOOST_EXCEPTION_DYNAMIC_TYPEID(*se))).type_->name()) << '\n'; + tmp << std::string("Dynamic exception type: ") << + units::detail::demangle((be?BOOST_EXCEPTION_DYNAMIC_TYPEID(*be):BOOST_EXCEPTION_DYNAMIC_TYPEID(*se)).type_.name()) << '\n'; #endif - if( with_what && se && verbose ) + if( with_what && se ) tmp << "std::exception::what: " << wh << '\n'; if( be ) if( char const * s=exception_detail::get_diagnostic_information(*be,tmp.str().c_str()) ) if( *s ) - return std::string(s); + return s; return tmp.str(); } } template std::string - diagnostic_information( T const & e, bool verbose=true ) + diagnostic_information( T const & e ) { - return exception_detail::diagnostic_information_impl(exception_detail::get_boost_exception(&e),exception_detail::get_std_exception(&e),true,verbose); + return exception_detail::diagnostic_information_impl(exception_detail::get_boost_exception(&e),exception_detail::get_std_exception(&e),true); } inline char const * - diagnostic_information_what( exception const & e, bool verbose=true ) throw() + diagnostic_information_what( exception const & e ) throw() { char const * w=0; #ifndef BOOST_NO_EXCEPTIONS try { #endif - (void) exception_detail::diagnostic_information_impl(&e,0,false,verbose); - if( char const * di=exception_detail::get_diagnostic_information(e,0) ) - return di; - else - return "Failed to produce boost::diagnostic_information_what()"; + (void) exception_detail::diagnostic_information_impl(&e,0,false); + return exception_detail::get_diagnostic_information(e,0); #ifndef BOOST_NO_EXCEPTIONS } catch( diff --git a/utils/boost_idb/boost/exception/errinfo_errno.hpp b/utils/boost_idb/boost/exception/errinfo_errno.hpp index 2cf7cabe..ea74010c 100644 --- a/utils/boost_idb/boost/exception/errinfo_errno.hpp +++ b/utils/boost_idb/boost/exception/errinfo_errno.hpp @@ -5,7 +5,7 @@ #ifndef UUID_F0EE17BE6C1211DE87FF459155D89593 #define UUID_F0EE17BE6C1211DE87FF459155D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/exception/errinfo_nested_exception.hpp b/utils/boost_idb/boost/exception/errinfo_nested_exception.hpp index c3299d14..e4e75d9e 100644 --- a/utils/boost_idb/boost/exception/errinfo_nested_exception.hpp +++ b/utils/boost_idb/boost/exception/errinfo_nested_exception.hpp @@ -9,9 +9,10 @@ namespace boost { - namespace exception_detail { class clone_base; } + namespace exception_detail { class clone_base; }; template class error_info; - class exception_ptr; + template class shared_ptr; + typedef shared_ptr exception_ptr; typedef error_info errinfo_nested_exception; } diff --git a/utils/boost_idb/boost/exception/error_info.hpp b/utils/boost_idb/boost/exception/error_info.hpp index 03b3da8e..2e6832a3 100644 --- a/utils/boost_idb/boost/exception/error_info.hpp +++ b/utils/boost_idb/boost/exception/error_info.hpp @@ -3,7 +3,4 @@ //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -#ifndef UUID_EE7ECCA0433B11E1923E37064924019B -#define UUID_EE7ECCA0433B11E1923E37064924019B namespace boost { template class error_info; } -#endif diff --git a/utils/boost_idb/boost/exception/exception.hpp b/utils/boost_idb/boost/exception/exception.hpp index 31d43178..adaac687 100644 --- a/utils/boost_idb/boost/exception/exception.hpp +++ b/utils/boost_idb/boost/exception/exception.hpp @@ -5,7 +5,7 @@ #ifndef UUID_274DA366004E11DCB1DDFE2E56D89593 #define UUID_274DA366004E11DCB1DDFE2E56D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -132,17 +132,7 @@ boost } }; -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility push (default) -# endif -#endif class exception; -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility pop -# endif -#endif template class shared_ptr; @@ -199,11 +189,6 @@ boost E const & set_info( E const &, throw_line const & ); } -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility push (default) -# endif -#endif class exception { @@ -265,11 +250,6 @@ boost mutable char const * throw_file_; mutable int throw_line_; }; -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility pop -# endif -#endif inline exception:: @@ -310,11 +290,6 @@ boost namespace exception_detail { -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility push (default) -# endif -#endif template struct error_info_injector: @@ -331,11 +306,6 @@ boost { } }; -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility pop -# endif -#endif struct large_size { char c[256]; }; large_size dispatch_boost_exception( exception const * ); @@ -364,7 +334,7 @@ boost struct enable_error_info_return_type { - typedef typename enable_error_info_helper(0)))>::type type; + typedef typename enable_error_info_helper::type type; }; } @@ -383,11 +353,6 @@ boost namespace exception_detail { -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility push (default) -# endif -#endif class clone_base { @@ -401,11 +366,6 @@ boost { } }; -#if defined(__GNUC__) -# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) -# pragma GCC visibility pop -# endif -#endif inline void @@ -430,15 +390,8 @@ boost class clone_impl: public T, - public virtual clone_base + public clone_base { - struct clone_tag { }; - clone_impl( clone_impl const & x, clone_tag ): - T(x) - { - copy_boost_exception(this,&x); - } - public: explicit @@ -457,7 +410,7 @@ boost clone_base const * clone() const { - return new clone_impl(*this,clone_tag()); + return new clone_impl(*this); } void diff --git a/utils/boost_idb/boost/exception/get_error_info.hpp b/utils/boost_idb/boost/exception/get_error_info.hpp index 96be7632..046f05ae 100644 --- a/utils/boost_idb/boost/exception/get_error_info.hpp +++ b/utils/boost_idb/boost/exception/get_error_info.hpp @@ -5,7 +5,7 @@ #ifndef UUID_1A590226753311DD9E4CCF6156D89593 #define UUID_1A590226753311DD9E4CCF6156D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/exception/info.hpp b/utils/boost_idb/boost/exception/info.hpp index 762a950f..c918dbd3 100644 --- a/utils/boost_idb/boost/exception/info.hpp +++ b/utils/boost_idb/boost/exception/info.hpp @@ -5,7 +5,7 @@ #ifndef UUID_8D22C4CA9CC811DCAA9133D256D89593 #define UUID_8D22C4CA9CC811DCAA9133D256D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -24,40 +24,41 @@ boost { template inline - std::string - error_info_name( error_info const & x ) + typename enable_if,std::string>::type + to_string( error_info const & x ) { - return tag_type_name(); + return to_string(x.value()); } template inline - std::string - to_string( error_info const & x ) + error_info:: + error_info( value_type const & value ): + value_(value) { - return '[' + error_info_name(x) + "] = " + to_string_stub(x.value()) + '\n'; } template inline error_info:: - error_info( value_type const & value ): - value_(value) + ~error_info() throw() { } template inline + std::string error_info:: - ~error_info() throw() + tag_typeid_name() const { + return tag_type_name(); } template inline std::string error_info:: - name_value_string() const + value_as_string() const { return to_string_stub(*this); } @@ -96,7 +97,7 @@ boost { shared_ptr const & p = i->second; #ifndef BOOST_NO_RTTI - BOOST_ASSERT( *BOOST_EXCEPTION_DYNAMIC_TYPEID(*p).type_==*ti.type_ ); + BOOST_ASSERT( BOOST_EXCEPTION_DYNAMIC_TYPEID(*p).type_==ti.type_ ); #endif return p; } @@ -108,12 +109,13 @@ boost { if( header ) { + BOOST_ASSERT(*header!=0); std::ostringstream tmp; tmp << header; for( error_info_map::const_iterator i=info_.begin(),end=info_.end(); i!=end; ++i ) { error_info_base const & x = *i->second; - tmp << x.name_value_string(); + tmp << '[' << x.tag_typeid_name() << "] = " << x.value_as_string() << '\n'; } tmp.str().swap(diagnostic_info_str_); } diff --git a/utils/boost_idb/boost/exception/info_tuple.hpp b/utils/boost_idb/boost/exception/info_tuple.hpp index 70154fd2..34afe421 100644 --- a/utils/boost_idb/boost/exception/info_tuple.hpp +++ b/utils/boost_idb/boost/exception/info_tuple.hpp @@ -5,7 +5,7 @@ #ifndef UUID_63EE924290FB11DC87BB856555D89593 #define UUID_63EE924290FB11DC87BB856555D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -18,30 +18,6 @@ namespace boost { - template < - class E > - inline - E const & - operator<<( - E const & x, - tuple< > const & v ) - { - return x; - } - - template < - class E, - class Tag1,class T1 > - inline - E const & - operator<<( - E const & x, - tuple< - error_info > const & v ) - { - return x << v.template get<0>(); - } - template < class E, class Tag1,class T1, diff --git a/utils/boost_idb/boost/exception/to_string.hpp b/utils/boost_idb/boost/exception/to_string.hpp index 68541d2b..59bf83d4 100644 --- a/utils/boost_idb/boost/exception/to_string.hpp +++ b/utils/boost_idb/boost/exception/to_string.hpp @@ -5,7 +5,7 @@ #ifndef UUID_7E48761AD92811DC9011477D56D89593 #define UUID_7E48761AD92811DC9011477D56D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -19,16 +19,11 @@ namespace boost { - template - std::string to_string( std::pair const & ); - std::string to_string( std::exception const & ); - namespace to_string_detail { template typename disable_if,char>::type to_string( T const & ); - using boost::to_string; template struct has_to_string_impl; diff --git a/utils/boost_idb/boost/exception/to_string_stub.hpp b/utils/boost_idb/boost/exception/to_string_stub.hpp index b6ab31cf..e41d3697 100644 --- a/utils/boost_idb/boost/exception/to_string_stub.hpp +++ b/utils/boost_idb/boost/exception/to_string_stub.hpp @@ -5,7 +5,7 @@ #ifndef UUID_E788439ED9F011DCB181F25B55D89593 #define UUID_E788439ED9F011DCB181F25B55D89593 -#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) +#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) #pragma GCC system_header #endif #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) @@ -101,14 +101,6 @@ boost { return exception_detail::to_string_dispatch::dispatch(x,s); } - - template - inline - std::string - to_string_stub( std::pair const & x, Stub s ) - { - return std::string("(") + to_string_stub(x.first,s) + ',' + to_string_stub(x.second,s) + ')'; - } } #if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS) diff --git a/utils/boost_idb/boost/filesystem.hpp b/utils/boost_idb/boost/filesystem.hpp index 1a753026..f8b9353a 100644 --- a/utils/boost_idb/boost/filesystem.hpp +++ b/utils/boost_idb/boost/filesystem.hpp @@ -12,9 +12,27 @@ #ifndef BOOST_FILESYSTEM_FILESYSTEM_HPP #define BOOST_FILESYSTEM_FILESYSTEM_HPP -# include -# include -# include -# include +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 +# endif + +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 +# endif + +#if BOOST_FILESYSTEM_VERSION == 2 +# include +# include +# include +# include + +# else +# include +# include +# include +# include + +# endif #endif // BOOST_FILESYSTEM_FILESYSTEM_HPP diff --git a/utils/boost_idb/boost/filesystem/config.hpp b/utils/boost_idb/boost/filesystem/config.hpp index ca695f41..9d12bce6 100644 --- a/utils/boost_idb/boost/filesystem/config.hpp +++ b/utils/boost_idb/boost/filesystem/config.hpp @@ -1,6 +1,6 @@ -// boost/filesystem/v3/config.hpp ----------------------------------------------------// +// boost/filesystem/config.hpp -------------------------------------------------------// -// Copyright Beman Dawes 2003 +// Copyright Beman Dawes 2010 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt @@ -9,101 +9,24 @@ //--------------------------------------------------------------------------------------// -#ifndef BOOST_FILESYSTEM3_CONFIG_HPP -#define BOOST_FILESYSTEM3_CONFIG_HPP +#ifndef BOOST_FILESYSTEM_CONFIGX_HPP +#define BOOST_FILESYSTEM_CONFIGX_HPP -# if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION != 3 -# error Compiling Filesystem version 3 file with BOOST_FILESYSTEM_VERSION defined != 3 +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 # endif # if !defined(BOOST_FILESYSTEM_VERSION) -# define BOOST_FILESYSTEM_VERSION 3 +# define BOOST_FILESYSTEM_VERSION 2 # endif -#define BOOST_FILESYSTEM_I18N // aid users wishing to compile several versions +#if BOOST_FILESYSTEM_VERSION == 2 +# include -// This header implements separate compilation features as described in -// http://www.boost.org/more/separate_compilation.html +# else +# include -#include -#include // for BOOST_POSIX_API or BOOST_WINDOWS_API -#include - -// BOOST_FILESYSTEM_DEPRECATED needed for source compiles -----------------------------// - -# ifdef BOOST_FILESYSTEM_SOURCE -# define BOOST_FILESYSTEM_DEPRECATED # endif -// throw an exception ----------------------------------------------------------------// -// -// Exceptions were originally thrown via boost::throw_exception(). -// As throw_exception() became more complex, it caused user error reporting -// to be harder to interpret, since the exception reported became much more complex. -// The immediate fix was to throw directly, wrapped in a macro to make any later change -// easier. - -#define BOOST_FILESYSTEM_THROW(EX) throw EX - -# if defined( BOOST_NO_STD_WSTRING ) -# error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support -# endif - -// This header implements separate compilation features as described in -// http://www.boost.org/more/separate_compilation.html - -// normalize macros ------------------------------------------------------------------// - -#if !defined(BOOST_FILESYSTEM_DYN_LINK) && !defined(BOOST_FILESYSTEM_STATIC_LINK) \ - && !defined(BOOST_ALL_DYN_LINK) && !defined(BOOST_ALL_STATIC_LINK) -# define BOOST_FILESYSTEM_STATIC_LINK -#endif - -#if defined(BOOST_ALL_DYN_LINK) && !defined(BOOST_FILESYSTEM_DYN_LINK) -# define BOOST_FILESYSTEM_DYN_LINK -#elif defined(BOOST_ALL_STATIC_LINK) && !defined(BOOST_FILESYSTEM_STATIC_LINK) -# define BOOST_FILESYSTEM_STATIC_LINK -#endif - -#if defined(BOOST_FILESYSTEM_DYN_LINK) && defined(BOOST_FILESYSTEM_STATIC_LINK) -# error Must not define both BOOST_FILESYSTEM_DYN_LINK and BOOST_FILESYSTEM_STATIC_LINK -#endif - -#if defined(BOOST_ALL_NO_LIB) && !defined(BOOST_FILESYSTEM_NO_LIB) -# define BOOST_FILESYSTEM_NO_LIB -#endif - -// enable dynamic linking ------------------------------------------------------------// - -#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FILESYSTEM_DYN_LINK) -# if defined(BOOST_FILESYSTEM_SOURCE) -# define BOOST_FILESYSTEM_DECL BOOST_SYMBOL_EXPORT -# else -# define BOOST_FILESYSTEM_DECL BOOST_SYMBOL_IMPORT -# endif -#else -# define BOOST_FILESYSTEM_DECL -#endif - -// enable automatic library variant selection ----------------------------------------// - -#if !defined(BOOST_FILESYSTEM_SOURCE) && !defined(BOOST_ALL_NO_LIB) \ - && !defined(BOOST_FILESYSTEM_NO_LIB) -// -// Set the name of our library, this will get undef'ed by auto_link.hpp -// once it's done with it: -// -#define BOOST_LIB_NAME boost_filesystem -// -// If we're importing code from a dll, then tell auto_link.hpp about it: -// -#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FILESYSTEM_DYN_LINK) -# define BOOST_DYN_LINK -#endif -// -// And include the header that does the work: -// -#include -#endif // auto-linking disabled - -#endif // BOOST_FILESYSTEM3_CONFIG_HPP +#endif // BOOST_FILESYSTEM_CONFIGX_HPP diff --git a/utils/boost_idb/boost/filesystem/convenience.hpp b/utils/boost_idb/boost/filesystem/convenience.hpp index f0bd9869..def4c3df 100644 --- a/utils/boost_idb/boost/filesystem/convenience.hpp +++ b/utils/boost_idb/boost/filesystem/convenience.hpp @@ -1,58 +1,32 @@ -// boost/filesystem/convenience.hpp ----------------------------------------// +// boost/filesystem/convenience.hpp --------------------------------------------------// -// Copyright Beman Dawes, 2002-2005 -// Copyright Vladimir Prus, 2002 -// Use, modification, and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) +// Copyright Beman Dawes 2010 -// See library home page at http://www.boost.org/libs/filesystem +// Distributed under the Boost Software License, Version 1.0. +// See http://www.boost.org/LICENSE_1_0.txt -//----------------------------------------------------------------------------// +// Library home page: http://www.boost.org/libs/filesystem -#ifndef BOOST_FILESYSTEM3_CONVENIENCE_HPP -#define BOOST_FILESYSTEM3_CONVENIENCE_HPP +//--------------------------------------------------------------------------------------// -#include +#ifndef BOOST_FILESYSTEM_CONVENIENCEX_HPP +#define BOOST_FILESYSTEM_CONVENIENCEX_HPP -# if defined( BOOST_NO_STD_WSTRING ) -# error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 # endif -#include -#include - -#include // must be the last #include - -namespace boost -{ - namespace filesystem - { - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - - inline std::string extension(const path & p) - { - return p.extension().string(); - } +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 +# endif - inline std::string basename(const path & p) - { - return p.stem().string(); - } +#if BOOST_FILESYSTEM_VERSION == 2 +# include - inline path change_extension( const path & p, const path & new_extension ) - { - path new_p( p ); - new_p.replace_extension( new_extension ); - return new_p; - } +# else +# include # endif - - } // namespace filesystem -} // namespace boost - -#include // pops abi_prefix.hpp pragmas -#endif // BOOST_FILESYSTEM3_CONVENIENCE_HPP +#endif // BOOST_FILESYSTEM_CONVENIENCEX_HPP diff --git a/utils/boost_idb/boost/filesystem/exception.hpp b/utils/boost_idb/boost/filesystem/exception.hpp index 985cd8f7..cced2571 100644 --- a/utils/boost_idb/boost/filesystem/exception.hpp +++ b/utils/boost_idb/boost/filesystem/exception.hpp @@ -1,9 +1,32 @@ -// boost/filesystem/exception.hpp -----------------------------------------------------// +// boost/filesystem/exception.hpp ----------------------------------------------------// -// Copyright Beman Dawes 2003 -// Use, modification, and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) +// Copyright Beman Dawes 2010 -// This header is no longer used. The contents have been moved to path.hpp. -// It is provided so that user code #includes do not have to be changed. +// Distributed under the Boost Software License, Version 1.0. +// See http://www.boost.org/LICENSE_1_0.txt + +// Library home page: http://www.boost.org/libs/filesystem + +//--------------------------------------------------------------------------------------// + +#ifndef BOOST_FILESYSTEM_EXCEPTIONX_HPP +#define BOOST_FILESYSTEM_EXCEPTIONX_HPP + +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 +# endif + +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 +# endif + +#if BOOST_FILESYSTEM_VERSION == 2 +# include + +# else +# include + +# endif + +#endif // BOOST_FILESYSTEM_EXCEPTIONX_HPP diff --git a/utils/boost_idb/boost/filesystem/fstream.hpp b/utils/boost_idb/boost/filesystem/fstream.hpp index 07272388..ae44cd9e 100644 --- a/utils/boost_idb/boost/filesystem/fstream.hpp +++ b/utils/boost_idb/boost/filesystem/fstream.hpp @@ -1,6 +1,6 @@ // boost/filesystem/fstream.hpp ------------------------------------------------------// -// Copyright Beman Dawes 2002 +// Copyright Beman Dawes 2010 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt @@ -9,174 +9,24 @@ //--------------------------------------------------------------------------------------// -#ifndef BOOST_FILESYSTEM3_FSTREAM_HPP -#define BOOST_FILESYSTEM3_FSTREAM_HPP +#ifndef BOOST_FILESYSTEM_FSTREAMX_HPP +#define BOOST_FILESYSTEM_FSTREAMX_HPP -#include - -# if defined( BOOST_NO_STD_WSTRING ) -# error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 # endif -#include -#include -#include - -#include // must be the last #include - -// on Windows, except for standard libaries known to have wchar_t overloads for -// file stream I/O, use path::string() to get a narrow character c_str() -#if defined(BOOST_WINDOWS_API) \ - && (!defined(_CPPLIB_VER) || _CPPLIB_VER < 405 || defined(_STLPORT_VERSION)) - // !Dinkumware || early Dinkumware || STLPort masquerading as Dinkumware -# define BOOST_FILESYSTEM_C_STR string().c_str() // use narrow, since wide not available -#else // use the native c_str, which will be narrow on POSIX, wide on Windows -# define BOOST_FILESYSTEM_C_STR c_str() -#endif - -namespace boost -{ -namespace filesystem -{ - -//--------------------------------------------------------------------------------------// -// basic_filebuf // -//--------------------------------------------------------------------------------------// - - template < class charT, class traits = std::char_traits > - class basic_filebuf : public std::basic_filebuf - { - private: // disallow copying - basic_filebuf(const basic_filebuf&); - const basic_filebuf& operator=(const basic_filebuf&); - - public: - basic_filebuf() {} - virtual ~basic_filebuf() {} - - basic_filebuf* - open(const path& p, std::ios_base::openmode mode) - { - return std::basic_filebuf::open(p.BOOST_FILESYSTEM_C_STR, mode) - ? this : 0; - } - }; - -//--------------------------------------------------------------------------------------// -// basic_ifstream // -//--------------------------------------------------------------------------------------// - - template < class charT, class traits = std::char_traits > - class basic_ifstream : public std::basic_ifstream - { - private: // disallow copying - basic_ifstream(const basic_ifstream&); - const basic_ifstream& operator=(const basic_ifstream&); - - public: - basic_ifstream() {} - - // use two signatures, rather than one signature with default second - // argument, to workaround VC++ 7.1 bug (ID VSWhidbey 38416) - - explicit basic_ifstream(const path& p) - : std::basic_ifstream(p.BOOST_FILESYSTEM_C_STR, std::ios_base::in) {} - - basic_ifstream(const path& p, std::ios_base::openmode mode) - : std::basic_ifstream(p.BOOST_FILESYSTEM_C_STR, mode) {} - - void open(const path& p) - { std::basic_ifstream::open(p.BOOST_FILESYSTEM_C_STR, std::ios_base::in); } - - void open(const path& p, std::ios_base::openmode mode) - { std::basic_ifstream::open(p.BOOST_FILESYSTEM_C_STR, mode); } - - virtual ~basic_ifstream() {} - }; - -//--------------------------------------------------------------------------------------// -// basic_ofstream // -//--------------------------------------------------------------------------------------// - - template < class charT, class traits = std::char_traits > - class basic_ofstream : public std::basic_ofstream - { - private: // disallow copying - basic_ofstream(const basic_ofstream&); - const basic_ofstream& operator=(const basic_ofstream&); - - public: - basic_ofstream() {} - - // use two signatures, rather than one signature with default second - // argument, to workaround VC++ 7.1 bug (ID VSWhidbey 38416) - - explicit basic_ofstream(const path& p) - : std::basic_ofstream(p.BOOST_FILESYSTEM_C_STR, std::ios_base::out) {} - - basic_ofstream(const path& p, std::ios_base::openmode mode) - : std::basic_ofstream(p.BOOST_FILESYSTEM_C_STR, mode) {} - - void open(const path& p) - { std::basic_ofstream::open(p.BOOST_FILESYSTEM_C_STR, std::ios_base::out); } - - void open(const path& p, std::ios_base::openmode mode) - { std::basic_ofstream::open(p.BOOST_FILESYSTEM_C_STR, mode); } - - virtual ~basic_ofstream() {} - }; - -//--------------------------------------------------------------------------------------// -// basic_fstream // -//--------------------------------------------------------------------------------------// - - template < class charT, class traits = std::char_traits > - class basic_fstream : public std::basic_fstream - { - private: // disallow copying - basic_fstream(const basic_fstream&); - const basic_fstream & operator=(const basic_fstream&); - - public: - basic_fstream() {} - - // use two signatures, rather than one signature with default second - // argument, to workaround VC++ 7.1 bug (ID VSWhidbey 38416) - - explicit basic_fstream(const path& p) - : std::basic_fstream(p.BOOST_FILESYSTEM_C_STR, - std::ios_base::in | std::ios_base::out) {} - - basic_fstream(const path& p, std::ios_base::openmode mode) - : std::basic_fstream(p.BOOST_FILESYSTEM_C_STR, mode) {} - - void open(const path& p) - { std::basic_fstream::open(p.BOOST_FILESYSTEM_C_STR, - std::ios_base::in | std::ios_base::out); } - - void open(const path& p, std::ios_base::openmode mode) - { std::basic_fstream::open(p.BOOST_FILESYSTEM_C_STR, mode); } - - virtual ~basic_fstream() {} - - }; +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 +# endif -//--------------------------------------------------------------------------------------// -// typedefs // -//--------------------------------------------------------------------------------------// +#if BOOST_FILESYSTEM_VERSION == 2 +# include - typedef basic_filebuf filebuf; - typedef basic_ifstream ifstream; - typedef basic_ofstream ofstream; - typedef basic_fstream fstream; +# else +# include - typedef basic_filebuf wfilebuf; - typedef basic_ifstream wifstream; - typedef basic_ofstream wofstream; - typedef basic_fstream wfstream; - -} // namespace filesystem -} // namespace boost +# endif -#include // pops abi_prefix.hpp pragmas -#endif // BOOST_FILESYSTEM3_FSTREAM_HPP +#endif // BOOST_FILESYSTEM_FSTREAMX_HPP diff --git a/utils/boost_idb/boost/filesystem/operations.hpp b/utils/boost_idb/boost/filesystem/operations.hpp index dc01b7d8..7dc94e97 100644 --- a/utils/boost_idb/boost/filesystem/operations.hpp +++ b/utils/boost_idb/boost/filesystem/operations.hpp @@ -1,1096 +1,32 @@ // boost/filesystem/operations.hpp ---------------------------------------------------// -// Copyright Beman Dawes 2002-2009 -// Copyright Jan Langer 2002 -// Copyright Dietmar Kuehl 2001 -// Copyright Vladimir Prus 2002 - +// Copyright Beman Dawes 2010 + // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // Library home page: http://www.boost.org/libs/filesystem -//--------------------------------------------------------------------------------------// - -#ifndef BOOST_FILESYSTEM3_OPERATIONS_HPP -#define BOOST_FILESYSTEM3_OPERATIONS_HPP +//--------------------------------------------------------------------------------------// -#include +#ifndef BOOST_FILESYSTEM_OPERATIONSX_HPP +#define BOOST_FILESYSTEM_OPERATIONSX_HPP -# if defined( BOOST_NO_STD_WSTRING ) -# error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 # endif -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include // for pair -#include -#include -#include - -#ifdef BOOST_WINDOWS_API -# include -#endif - -#include // must be the last #include - -//--------------------------------------------------------------------------------------// - -namespace boost -{ - namespace filesystem - { - -//--------------------------------------------------------------------------------------// -// file_type // -//--------------------------------------------------------------------------------------// - - enum file_type - { - status_error, -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - status_unknown = status_error, -# endif - file_not_found, - regular_file, - directory_file, - // the following may not apply to some operating systems or file systems - symlink_file, - block_file, - character_file, - fifo_file, - socket_file, - reparse_file, // Windows: FILE_ATTRIBUTE_REPARSE_POINT that is not a symlink - type_unknown, // file does exist, but isn't one of the above types or - // we don't have strong enough permission to find its type - - _detail_directory_symlink // internal use only; never exposed to users - }; - -//--------------------------------------------------------------------------------------// -// perms // -//--------------------------------------------------------------------------------------// - - enum perms - { - no_perms = 0, // file_not_found is no_perms rather than perms_not_known - - // POSIX equivalent macros given in comments. - // Values are from POSIX and are given in octal per the POSIX standard. - - // permission bits - - owner_read = 0400, // S_IRUSR, Read permission, owner - owner_write = 0200, // S_IWUSR, Write permission, owner - owner_exe = 0100, // S_IXUSR, Execute/search permission, owner - owner_all = 0700, // S_IRWXU, Read, write, execute/search by owner - - group_read = 040, // S_IRGRP, Read permission, group - group_write = 020, // S_IWGRP, Write permission, group - group_exe = 010, // S_IXGRP, Execute/search permission, group - group_all = 070, // S_IRWXG, Read, write, execute/search by group - - others_read = 04, // S_IROTH, Read permission, others - others_write = 02, // S_IWOTH, Write permission, others - others_exe = 01, // S_IXOTH, Execute/search permission, others - others_all = 07, // S_IRWXO, Read, write, execute/search by others - - all_all = owner_all|group_all|others_all, // 0777 - - // other POSIX bits - - set_uid_on_exe = 04000, // S_ISUID, Set-user-ID on execution - set_gid_on_exe = 02000, // S_ISGID, Set-group-ID on execution - sticky_bit = 01000, // S_ISVTX, - // (POSIX XSI) On directories, restricted deletion flag - // (V7) 'sticky bit': save swapped text even after use - // (SunOS) On non-directories: don't cache this file - // (SVID-v4.2) On directories: restricted deletion flag - // Also see http://en.wikipedia.org/wiki/Sticky_bit - - perms_mask = all_all|set_uid_on_exe|set_gid_on_exe|sticky_bit, // 07777 - - perms_not_known = 0xFFFF, // present when directory_entry cache not loaded - - // options for permissions() function - - add_perms = 0x1000, // adds the given permission bits to the current bits - remove_perms = 0x2000, // removes the given permission bits from the current bits; - // choose add_perms or remove_perms, not both; if neither add_perms - // nor remove_perms is given, replace the current bits with - // the given bits. - - symlink_perms = 0x4000 // on POSIX, don't resolve symlinks; implied on Windows - }; - - BOOST_BITMASK(perms) - -//--------------------------------------------------------------------------------------// -// file_status // -//--------------------------------------------------------------------------------------// - - class BOOST_FILESYSTEM_DECL file_status - { - public: - file_status() : m_value(status_error), m_perms(perms_not_known) {} - explicit file_status(file_type v, perms prms = perms_not_known) - : m_value(v), m_perms(prms) {} - - // observers - file_type type() const { return m_value; } - perms permissions() const { return m_perms; } - - // modifiers - void type(file_type v) { m_value = v; } - void permissions(perms prms) { m_perms = prms; } - - bool operator==(const file_status& rhs) const { return type() == rhs.type() && - permissions() == rhs.permissions(); } - bool operator!=(const file_status& rhs) const { return !(*this == rhs); } - - private: - file_type m_value; - enum perms m_perms; - }; - - inline bool type_present(file_status f) { return f.type() != status_error; } - inline bool permissions_present(file_status f) - {return f.permissions() != perms_not_known;} - inline bool status_known(file_status f) { return type_present(f) && permissions_present(f); } - inline bool exists(file_status f) { return f.type() != status_error - && f.type() != file_not_found; } - inline bool is_regular_file(file_status f){ return f.type() == regular_file; } - inline bool is_directory(file_status f) { return f.type() == directory_file; } - inline bool is_symlink(file_status f) { return f.type() == symlink_file; } - inline bool is_other(file_status f) { return exists(f) && !is_regular_file(f) - && !is_directory(f) && !is_symlink(f); } - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - inline bool is_regular(file_status f) { return f.type() == regular_file; } +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 # endif - struct space_info - { - // all values are byte counts - boost::uintmax_t capacity; - boost::uintmax_t free; // <= capacity - boost::uintmax_t available; // <= free - }; - - BOOST_SCOPED_ENUM_START(copy_option) - {none, fail_if_exists = none, overwrite_if_exists}; - BOOST_SCOPED_ENUM_END - -//--------------------------------------------------------------------------------------// -// implementation details // -//--------------------------------------------------------------------------------------// +#if BOOST_FILESYSTEM_VERSION == 2 +# include - namespace detail - { - BOOST_FILESYSTEM_DECL - file_status status(const path&p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - file_status symlink_status(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - bool is_empty(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path initial_path(system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path canonical(const path& p, const path& base, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void copy(const path& from, const path& to, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void copy_directory(const path& from, const path& to, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void copy_file(const path& from, const path& to, - BOOST_SCOPED_ENUM(copy_option) option, // See ticket #2925 - system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void copy_symlink(const path& existing_symlink, const path& new_symlink, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - bool create_directories(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - bool create_directory(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void create_directory_symlink(const path& to, const path& from, - system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void create_hard_link(const path& to, const path& from, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void create_symlink(const path& to, const path& from, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path current_path(system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void current_path(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - bool equivalent(const path& p1, const path& p2, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - boost::uintmax_t file_size(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - boost::uintmax_t hard_link_count(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - std::time_t last_write_time(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void last_write_time(const path& p, const std::time_t new_time, - system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void permissions(const path& p, perms prms, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path read_symlink(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - // For standardization, if the committee doesn't like "remove", consider "eliminate" - bool remove(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - boost::uintmax_t remove_all(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void rename(const path& old_p, const path& new_p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - void resize_file(const path& p, uintmax_t size, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - space_info space(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path system_complete(const path& p, system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path temp_directory_path(system::error_code* ec=0); - BOOST_FILESYSTEM_DECL - path unique_path(const path& p, system::error_code* ec=0); - } // namespace detail +# else +# include -//--------------------------------------------------------------------------------------// -// // -// status query functions // -// // -//--------------------------------------------------------------------------------------// - - inline - file_status status(const path& p) {return detail::status(p);} - inline - file_status status(const path& p, system::error_code& ec) - {return detail::status(p, &ec);} - inline - file_status symlink_status(const path& p) {return detail::symlink_status(p);} - inline - file_status symlink_status(const path& p, system::error_code& ec) - {return detail::symlink_status(p, &ec);} - inline - bool exists(const path& p) {return exists(detail::status(p));} - inline - bool exists(const path& p, system::error_code& ec) - {return exists(detail::status(p, &ec));} - inline - bool is_directory(const path& p) {return is_directory(detail::status(p));} - inline - bool is_directory(const path& p, system::error_code& ec) - {return is_directory(detail::status(p, &ec));} - inline - bool is_regular_file(const path& p) {return is_regular_file(detail::status(p));} - inline - bool is_regular_file(const path& p, system::error_code& ec) - {return is_regular_file(detail::status(p, &ec));} - inline - bool is_other(const path& p) {return is_other(detail::status(p));} - inline - bool is_other(const path& p, system::error_code& ec) - {return is_other(detail::status(p, &ec));} - inline - bool is_symlink(const path& p) {return is_symlink(detail::symlink_status(p));} - inline - bool is_symlink(const path& p, system::error_code& ec) - {return is_symlink(detail::symlink_status(p, &ec));} -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - inline - bool is_regular(const path& p) {return is_regular(detail::status(p));} - inline - bool is_regular(const path& p, system::error_code& ec) - {return is_regular(detail::status(p, &ec));} # endif - inline - bool is_empty(const path& p) {return detail::is_empty(p);} - inline - bool is_empty(const path& p, system::error_code& ec) - {return detail::is_empty(p, &ec);} - -//--------------------------------------------------------------------------------------// -// // -// operational functions // -// in alphabetical order, unless otherwise noted // -// // -//--------------------------------------------------------------------------------------// - - // forward declarations - path current_path(); // fwd declaration - path initial_path(); - - BOOST_FILESYSTEM_DECL - path absolute(const path& p, const path& base=current_path()); - // If base.is_absolute(), throws nothing. Thus no need for ec argument - - inline - path canonical(const path& p, const path& base=current_path()) - {return detail::canonical(p, base);} - inline - path canonical(const path& p, system::error_code& ec) - {return detail::canonical(p, current_path(), &ec);} - inline - path canonical(const path& p, const path& base, system::error_code& ec) - {return detail::canonical(p, base, &ec);} - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - inline - path complete(const path& p) - { - return absolute(p, initial_path()); - } - - inline - path complete(const path& p, const path& base) - { - return absolute(p, base); - } -# endif - - inline - void copy(const path& from, const path& to) {detail::copy(from, to);} - - inline - void copy(const path& from, const path& to, system::error_code& ec) - {detail::copy(from, to, &ec);} - inline - void copy_directory(const path& from, const path& to) - {detail::copy_directory(from, to);} - inline - void copy_directory(const path& from, const path& to, system::error_code& ec) - {detail::copy_directory(from, to, &ec);} - inline - void copy_file(const path& from, const path& to, // See ticket #2925 - BOOST_SCOPED_ENUM(copy_option) option) - {detail::copy_file(from, to, option);} - inline - void copy_file(const path& from, const path& to) - {detail::copy_file(from, to, copy_option::fail_if_exists);} - inline - void copy_file(const path& from, const path& to, // See ticket #2925 - BOOST_SCOPED_ENUM(copy_option) option, system::error_code& ec) - {detail::copy_file(from, to, option, &ec);} - inline - void copy_file(const path& from, const path& to, system::error_code& ec) - {detail::copy_file(from, to, copy_option::fail_if_exists, &ec);} - inline - void copy_symlink(const path& existing_symlink, const path& new_symlink) {detail::copy_symlink(existing_symlink, new_symlink);} - - inline - void copy_symlink(const path& existing_symlink, const path& new_symlink, system::error_code& ec) - {detail::copy_symlink(existing_symlink, new_symlink, &ec);} - inline - bool create_directories(const path& p) {return detail::create_directories(p);} - - inline - bool create_directories(const path& p, system::error_code& ec) - {return detail::create_directories(p, &ec);} - inline - bool create_directory(const path& p) {return detail::create_directory(p);} - - inline - bool create_directory(const path& p, system::error_code& ec) - {return detail::create_directory(p, &ec);} - inline - void create_directory_symlink(const path& to, const path& from) - {detail::create_directory_symlink(to, from);} - inline - void create_directory_symlink(const path& to, const path& from, system::error_code& ec) - {detail::create_directory_symlink(to, from, &ec);} - inline - void create_hard_link(const path& to, const path& new_hard_link) {detail::create_hard_link(to, new_hard_link);} - - inline - void create_hard_link(const path& to, const path& new_hard_link, system::error_code& ec) - {detail::create_hard_link(to, new_hard_link, &ec);} - inline - void create_symlink(const path& to, const path& new_symlink) {detail::create_symlink(to, new_symlink);} - - inline - void create_symlink(const path& to, const path& new_symlink, system::error_code& ec) - {detail::create_symlink(to, new_symlink, &ec);} - inline - path current_path() {return detail::current_path();} - - inline - path current_path(system::error_code& ec) {return detail::current_path(&ec);} - - inline - void current_path(const path& p) {detail::current_path(p);} - - inline - void current_path(const path& p, system::error_code& ec) {detail::current_path(p, &ec);} - - inline - bool equivalent(const path& p1, const path& p2) {return detail::equivalent(p1, p2);} - - inline - bool equivalent(const path& p1, const path& p2, system::error_code& ec) - {return detail::equivalent(p1, p2, &ec);} - inline - boost::uintmax_t file_size(const path& p) {return detail::file_size(p);} - - inline - boost::uintmax_t file_size(const path& p, system::error_code& ec) - {return detail::file_size(p, &ec);} - inline - boost::uintmax_t hard_link_count(const path& p) {return detail::hard_link_count(p);} - - inline - boost::uintmax_t hard_link_count(const path& p, system::error_code& ec) - {return detail::hard_link_count(p, &ec);} - inline - path initial_path() {return detail::initial_path();} - - inline - path initial_path(system::error_code& ec) {return detail::initial_path(&ec);} - - template - path initial_path() {return initial_path();} - template - path initial_path(system::error_code& ec) {return detail::initial_path(&ec);} - - inline - std::time_t last_write_time(const path& p) {return detail::last_write_time(p);} - - inline - std::time_t last_write_time(const path& p, system::error_code& ec) - {return detail::last_write_time(p, &ec);} - inline - void last_write_time(const path& p, const std::time_t new_time) - {detail::last_write_time(p, new_time);} - inline - void last_write_time(const path& p, const std::time_t new_time, system::error_code& ec) - {detail::last_write_time(p, new_time, &ec);} - inline - void permissions(const path& p, perms prms) - {detail::permissions(p, prms);} - inline - void permissions(const path& p, perms prms, system::error_code& ec) - {detail::permissions(p, prms, &ec);} - - inline - path read_symlink(const path& p) {return detail::read_symlink(p);} - - inline - path read_symlink(const path& p, system::error_code& ec) - {return detail::read_symlink(p, &ec);} - inline - // For standardization, if the committee doesn't like "remove", consider "eliminate" - bool remove(const path& p) {return detail::remove(p);} - - inline - bool remove(const path& p, system::error_code& ec) {return detail::remove(p, &ec);} - - inline - boost::uintmax_t remove_all(const path& p) {return detail::remove_all(p);} - - inline - boost::uintmax_t remove_all(const path& p, system::error_code& ec) - {return detail::remove_all(p, &ec);} - inline - void rename(const path& old_p, const path& new_p) {detail::rename(old_p, new_p);} - - inline - void rename(const path& old_p, const path& new_p, system::error_code& ec) - {detail::rename(old_p, new_p, &ec);} - inline // name suggested by Scott McMurray - void resize_file(const path& p, uintmax_t size) {detail::resize_file(p, size);} - - inline - void resize_file(const path& p, uintmax_t size, system::error_code& ec) - {detail::resize_file(p, size, &ec);} - inline - space_info space(const path& p) {return detail::space(p);} - - inline - space_info space(const path& p, system::error_code& ec) {return detail::space(p, &ec);} - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - inline bool symbolic_link_exists(const path& p) - { return is_symlink(symlink_status(p)); } -# endif - - inline - path system_complete(const path& p) {return detail::system_complete(p);} - - inline - path system_complete(const path& p, system::error_code& ec) - {return detail::system_complete(p, &ec);} - inline - path temp_directory_path() {return detail::temp_directory_path();} - - inline - path temp_directory_path(system::error_code& ec) - {return detail::temp_directory_path(&ec);} - inline - path unique_path(const path& p="%%%%-%%%%-%%%%-%%%%") - { return detail::unique_path(p); } - inline - path unique_path(const path& p, system::error_code& ec) - { return detail::unique_path(p, &ec); } - -//--------------------------------------------------------------------------------------// -// // -// directory_entry // -// // -//--------------------------------------------------------------------------------------// - -// GCC has a problem with a member function named path within a namespace or -// sub-namespace that also has a class named path. The workaround is to always -// fully qualify the name path when it refers to the class name. - -class BOOST_FILESYSTEM_DECL directory_entry -{ -public: - - // compiler generated copy constructor, copy assignment, and destructor apply - - directory_entry() {} - explicit directory_entry(const boost::filesystem::path& p, - file_status st = file_status(), file_status symlink_st=file_status()) - : m_path(p), m_status(st), m_symlink_status(symlink_st) - {} - - void assign(const boost::filesystem::path& p, - file_status st = file_status(), file_status symlink_st = file_status()) - { m_path = p; m_status = st; m_symlink_status = symlink_st; } - - void replace_filename(const boost::filesystem::path& p, - file_status st = file_status(), file_status symlink_st = file_status()) - { - m_path.remove_filename(); - m_path /= p; - m_status = st; - m_symlink_status = symlink_st; - } - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - void replace_leaf(const boost::filesystem::path& p, - file_status st, file_status symlink_st) - { replace_filename(p, st, symlink_st); } -# endif - - const boost::filesystem::path& path() const {return m_path;} - file_status status() const {return m_get_status();} - file_status status(system::error_code& ec) const {return m_get_status(&ec);} - file_status symlink_status() const {return m_get_symlink_status();} - file_status symlink_status(system::error_code& ec) const {return m_get_symlink_status(&ec);} - - bool operator==(const directory_entry& rhs) {return m_path == rhs.m_path;} - bool operator!=(const directory_entry& rhs) {return m_path != rhs.m_path;} - bool operator< (const directory_entry& rhs) {return m_path < rhs.m_path;} - bool operator<=(const directory_entry& rhs) {return m_path <= rhs.m_path;} - bool operator> (const directory_entry& rhs) {return m_path > rhs.m_path;} - bool operator>=(const directory_entry& rhs) {return m_path >= rhs.m_path;} - -private: - boost::filesystem::path m_path; - mutable file_status m_status; // stat()-like - mutable file_status m_symlink_status; // lstat()-like - - file_status m_get_status(system::error_code* ec=0) const; - file_status m_get_symlink_status(system::error_code* ec=0) const; -}; // directory_entry - -//--------------------------------------------------------------------------------------// -// // -// directory_iterator helpers // -// // -//--------------------------------------------------------------------------------------// - -class directory_iterator; - -namespace detail -{ - BOOST_FILESYSTEM_DECL - system::error_code dir_itr_close(// never throws() - void *& handle -# if defined(BOOST_POSIX_API) - , void *& buffer -# endif - ); - - struct dir_itr_imp - { - directory_entry dir_entry; - void* handle; - -# ifdef BOOST_POSIX_API - void* buffer; // see dir_itr_increment implementation -# endif - - dir_itr_imp() : handle(0) -# ifdef BOOST_POSIX_API - , buffer(0) -# endif - {} - - ~dir_itr_imp() // never throws - { - dir_itr_close(handle -# if defined(BOOST_POSIX_API) - , buffer -# endif - ); - } - }; - - // see path::iterator: comment below - BOOST_FILESYSTEM_DECL void directory_iterator_construct(directory_iterator& it, - const path& p, system::error_code* ec); - BOOST_FILESYSTEM_DECL void directory_iterator_increment(directory_iterator& it, - system::error_code* ec); - -} // namespace detail - -//--------------------------------------------------------------------------------------// -// // -// directory_iterator // -// // -//--------------------------------------------------------------------------------------// - - class directory_iterator - : public boost::iterator_facade< directory_iterator, - directory_entry, - boost::single_pass_traversal_tag > - { - public: - - directory_iterator(){} // creates the "end" iterator - - // iterator_facade derived classes don't seem to like implementations in - // separate translation unit dll's, so forward to detail functions - explicit directory_iterator(const path& p) - : m_imp(new detail::dir_itr_imp) - { detail::directory_iterator_construct(*this, p, 0); } - - directory_iterator(const path& p, system::error_code& ec) - : m_imp(new detail::dir_itr_imp) - { detail::directory_iterator_construct(*this, p, &ec); } - - ~directory_iterator() {} // never throws - - directory_iterator& increment(system::error_code& ec) - { - detail::directory_iterator_increment(*this, &ec); - return *this; - } - - private: - friend struct detail::dir_itr_imp; - friend BOOST_FILESYSTEM_DECL void detail::directory_iterator_construct(directory_iterator& it, - const path& p, system::error_code* ec); - friend BOOST_FILESYSTEM_DECL void detail::directory_iterator_increment(directory_iterator& it, - system::error_code* ec); - - // shared_ptr provides shallow-copy semantics required for InputIterators. - // m_imp.get()==0 indicates the end iterator. - boost::shared_ptr< detail::dir_itr_imp > m_imp; - - friend class boost::iterator_core_access; - - boost::iterator_facade< - directory_iterator, - directory_entry, - boost::single_pass_traversal_tag >::reference dereference() const - { - BOOST_ASSERT_MSG(m_imp.get(), "attempt to dereference end iterator"); - return m_imp->dir_entry; - } - - void increment() { detail::directory_iterator_increment(*this, 0); } - - bool equal(const directory_iterator& rhs) const - { return m_imp == rhs.m_imp; } - }; - -//--------------------------------------------------------------------------------------// -// // -// recursive_directory_iterator helpers // -// // -//--------------------------------------------------------------------------------------// - - BOOST_SCOPED_ENUM_START(symlink_option) - { - none, - no_recurse = none, // don't follow directory symlinks (default behavior) - recurse, // follow directory symlinks - _detail_no_push = recurse << 1 // internal use only - }; - BOOST_SCOPED_ENUM_END - - BOOST_BITMASK(BOOST_SCOPED_ENUM(symlink_option)) - - namespace detail - { - struct recur_dir_itr_imp - { - typedef directory_iterator element_type; - std::stack< element_type, std::vector< element_type > > m_stack; - int m_level; - BOOST_SCOPED_ENUM(symlink_option) m_options; - - recur_dir_itr_imp() : m_level(0), m_options(symlink_option::none) {} - - void increment(system::error_code* ec); // ec == 0 means throw on error - - void pop(); - - }; - - // Implementation is inline to avoid dynamic linking difficulties with m_stack: - // Microsoft warning C4251, m_stack needs to have dll-interface to be used by - // clients of struct 'boost::filesystem::detail::recur_dir_itr_imp' - - inline - void recur_dir_itr_imp::increment(system::error_code* ec) - // ec == 0 means throw on error - { - if ((m_options & symlink_option::_detail_no_push) == symlink_option::_detail_no_push) - m_options &= ~symlink_option::_detail_no_push; - - else - { - // Logic for following predicate was contributed by Daniel Aarno to handle cyclic - // symlinks correctly and efficiently, fixing ticket #5652. - // if (((m_options & symlink_option::recurse) == symlink_option::recurse - // || !is_symlink(m_stack.top()->symlink_status())) - // && is_directory(m_stack.top()->status())) ... - // The predicate code has since been rewritten to pass error_code arguments, - // per ticket #5653. - bool or_pred = (m_options & symlink_option::recurse) == symlink_option::recurse - || (ec == 0 ? !is_symlink(m_stack.top()->symlink_status()) - : !is_symlink(m_stack.top()->symlink_status(*ec))); - if (ec != 0 && *ec) - return; - bool and_pred = or_pred && (ec == 0 ? is_directory(m_stack.top()->status()) - : is_directory(m_stack.top()->status(*ec))); - if (ec != 0 && *ec) - return; - - if (and_pred) - { - if (ec == 0) - m_stack.push(directory_iterator(m_stack.top()->path())); - else - { - m_stack.push(directory_iterator(m_stack.top()->path(), *ec)); - if (*ec) - return; - } - if (m_stack.top() != directory_iterator()) - { - ++m_level; - return; - } - m_stack.pop(); - } - } - - while (!m_stack.empty() && ++m_stack.top() == directory_iterator()) - { - m_stack.pop(); - --m_level; - } - } - - inline - void recur_dir_itr_imp::pop() - { - BOOST_ASSERT_MSG(m_level > 0, - "pop() on recursive_directory_iterator with level < 1"); - - do - { - m_stack.pop(); - --m_level; - } - while (!m_stack.empty() && ++m_stack.top() == directory_iterator()); - } - } // namespace detail - -//--------------------------------------------------------------------------------------// -// // -// recursive_directory_iterator // -// // -//--------------------------------------------------------------------------------------// - - class recursive_directory_iterator - : public boost::iterator_facade< - recursive_directory_iterator, - directory_entry, - boost::single_pass_traversal_tag > - { - public: - - recursive_directory_iterator(){} // creates the "end" iterator - - explicit recursive_directory_iterator(const path& dir_path, - BOOST_SCOPED_ENUM(symlink_option) opt = symlink_option::none) - : m_imp(new detail::recur_dir_itr_imp) - { - m_imp->m_options = opt; - m_imp->m_stack.push(directory_iterator(dir_path)); - if (m_imp->m_stack.top() == directory_iterator()) - { m_imp.reset (); } - } - - recursive_directory_iterator(const path& dir_path, - BOOST_SCOPED_ENUM(symlink_option) opt, - system::error_code & ec) - : m_imp(new detail::recur_dir_itr_imp) - { - m_imp->m_options = opt; - m_imp->m_stack.push(directory_iterator(dir_path, ec)); - if (m_imp->m_stack.top() == directory_iterator()) - { m_imp.reset (); } - } - - recursive_directory_iterator(const path& dir_path, - system::error_code & ec) - : m_imp(new detail::recur_dir_itr_imp) - { - m_imp->m_options = symlink_option::none; - m_imp->m_stack.push(directory_iterator(dir_path, ec)); - if (m_imp->m_stack.top() == directory_iterator()) - { m_imp.reset (); } - } - - recursive_directory_iterator& increment(system::error_code& ec) - { - BOOST_ASSERT_MSG(m_imp.get(), - "increment() on end recursive_directory_iterator"); - m_imp->increment(&ec); - if (m_imp->m_stack.empty()) - m_imp.reset(); // done, so make end iterator - return *this; - } - - int level() const - { - BOOST_ASSERT_MSG(m_imp.get(), - "level() on end recursive_directory_iterator"); - return m_imp->m_level; - } - - bool no_push_pending() const - { - BOOST_ASSERT_MSG(m_imp.get(), - "is_no_push_requested() on end recursive_directory_iterator"); - return (m_imp->m_options & symlink_option::_detail_no_push) - == symlink_option::_detail_no_push; - } - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - bool no_push_request() const { return no_push_pending(); } -# endif - - void pop() - { - BOOST_ASSERT_MSG(m_imp.get(), - "pop() on end recursive_directory_iterator"); - m_imp->pop(); - if (m_imp->m_stack.empty()) m_imp.reset(); // done, so make end iterator - } - - void no_push(bool value=true) - { - BOOST_ASSERT_MSG(m_imp.get(), - "no_push() on end recursive_directory_iterator"); - if (value) - m_imp->m_options |= symlink_option::_detail_no_push; - else - m_imp->m_options &= ~symlink_option::_detail_no_push; - } - - file_status status() const - { - BOOST_ASSERT_MSG(m_imp.get(), - "status() on end recursive_directory_iterator"); - return m_imp->m_stack.top()->status(); - } - - file_status symlink_status() const - { - BOOST_ASSERT_MSG(m_imp.get(), - "symlink_status() on end recursive_directory_iterator"); - return m_imp->m_stack.top()->symlink_status(); - } - - private: - - // shared_ptr provides shallow-copy semantics required for InputIterators. - // m_imp.get()==0 indicates the end iterator. - boost::shared_ptr< detail::recur_dir_itr_imp > m_imp; - - friend class boost::iterator_core_access; - - boost::iterator_facade< - recursive_directory_iterator, - directory_entry, - boost::single_pass_traversal_tag >::reference - dereference() const - { - BOOST_ASSERT_MSG(m_imp.get(), - "dereference of end recursive_directory_iterator"); - return *m_imp->m_stack.top(); - } - - void increment() - { - BOOST_ASSERT_MSG(m_imp.get(), - "increment of end recursive_directory_iterator"); - m_imp->increment(0); - if (m_imp->m_stack.empty()) - m_imp.reset(); // done, so make end iterator - } - - bool equal(const recursive_directory_iterator& rhs) const - { return m_imp == rhs.m_imp; } - - }; - -# if !defined(BOOST_FILESYSTEM_NO_DEPRECATED) - typedef recursive_directory_iterator wrecursive_directory_iterator; -# endif - -//--------------------------------------------------------------------------------------// -// // -// class filesystem_error // -// // -//--------------------------------------------------------------------------------------// - - class BOOST_SYMBOL_VISIBLE filesystem_error : public system::system_error - { - // see http://www.boost.org/more/error_handling.html for design rationale - - // all functions are inline to avoid issues with crossing dll boundaries - - public: - // compiler generates copy constructor and copy assignment - - filesystem_error( - const std::string & what_arg, system::error_code ec) - : system::system_error(ec, what_arg) - { - try - { - m_imp_ptr.reset(new m_imp); - } - catch (...) { m_imp_ptr.reset(); } - } - - filesystem_error( - const std::string & what_arg, const path& path1_arg, - system::error_code ec) - : system::system_error(ec, what_arg) - { - try - { - m_imp_ptr.reset(new m_imp); - m_imp_ptr->m_path1 = path1_arg; - } - catch (...) { m_imp_ptr.reset(); } - } - - filesystem_error( - const std::string & what_arg, const path& path1_arg, - const path& path2_arg, system::error_code ec) - : system::system_error(ec, what_arg) - { - try - { - m_imp_ptr.reset(new m_imp); - m_imp_ptr->m_path1 = path1_arg; - m_imp_ptr->m_path2 = path2_arg; - } - catch (...) { m_imp_ptr.reset(); } - } - - ~filesystem_error() throw() {} - - const path& path1() const - { - static const path empty_path; - return m_imp_ptr.get() ? m_imp_ptr->m_path1 : empty_path ; - } - const path& path2() const - { - static const path empty_path; - return m_imp_ptr.get() ? m_imp_ptr->m_path2 : empty_path ; - } - - const char* what() const throw() - { - if (!m_imp_ptr.get()) - return system::system_error::what(); - - try - { - if (m_imp_ptr->m_what.empty()) - { - m_imp_ptr->m_what = system::system_error::what(); - if (!m_imp_ptr->m_path1.empty()) - { - m_imp_ptr->m_what += ": \""; - m_imp_ptr->m_what += m_imp_ptr->m_path1.string(); - m_imp_ptr->m_what += "\""; - } - if (!m_imp_ptr->m_path2.empty()) - { - m_imp_ptr->m_what += ", \""; - m_imp_ptr->m_what += m_imp_ptr->m_path2.string(); - m_imp_ptr->m_what += "\""; - } - } - return m_imp_ptr->m_what.c_str(); - } - catch (...) - { - return system::system_error::what(); - } - } - - private: - struct m_imp - { - path m_path1; // may be empty() - path m_path2; // may be empty() - std::string m_what; // not built until needed - }; - boost::shared_ptr m_imp_ptr; - }; - -// test helper -----------------------------------------------------------------------// - -// Not part of the documented interface since false positives are possible; -// there is no law that says that an OS that has large stat.st_size -// actually supports large file sizes. - - namespace detail - { - BOOST_FILESYSTEM_DECL bool possible_large_file_size_support(); - } - - } // namespace filesystem -} // namespace boost - -#include // pops abi_prefix.hpp pragmas -#endif // BOOST_FILESYSTEM3_OPERATIONS_HPP +#endif // BOOST_FILESYSTEM_OPERATIONSX_HPP diff --git a/utils/boost_idb/boost/filesystem/path.hpp b/utils/boost_idb/boost/filesystem/path.hpp index 2dd1b00e..bf121740 100644 --- a/utils/boost_idb/boost/filesystem/path.hpp +++ b/utils/boost_idb/boost/filesystem/path.hpp @@ -1,758 +1,32 @@ -// filesystem path.hpp ---------------------------------------------------------------// +// boost/filesystem/path.hpp ---------------------------------------------------------// -// Copyright Beman Dawes 2002-2005, 2009 -// Copyright Vladimir Prus 2002 +// Copyright Beman Dawes 2010 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // Library home page: http://www.boost.org/libs/filesystem -// path::stem(), extension(), and replace_extension() are based on -// basename(), extension(), and change_extension() from the original -// filesystem/convenience.hpp header by Vladimir Prus. +//--------------------------------------------------------------------------------------// -#ifndef BOOST_FILESYSTEM_PATH_HPP -#define BOOST_FILESYSTEM_PATH_HPP +#ifndef BOOST_FILESYSTEM_PATHX_HPP +#define BOOST_FILESYSTEM_PATHX_HPP -#include - -# if defined( BOOST_NO_STD_WSTRING ) -# error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support -# endif - -#include -#include // includes -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include // must be the last #include - -namespace boost -{ -namespace filesystem -{ - //------------------------------------------------------------------------------------// - // // - // class path // - // // - //------------------------------------------------------------------------------------// - - class BOOST_FILESYSTEM_DECL path - { - public: - - // value_type is the character type used by the operating system API to - // represent paths. - -# ifdef BOOST_WINDOWS_API - typedef wchar_t value_type; - BOOST_STATIC_CONSTEXPR value_type preferred_separator = L'\\'; -# else - typedef char value_type; - BOOST_STATIC_CONSTEXPR value_type preferred_separator = '/'; -# endif - typedef std::basic_string string_type; - typedef std::codecvt codecvt_type; - - - // ----- character encoding conversions ----- - - // Following the principle of least astonishment, path input arguments - // passed to or obtained from the operating system via objects of - // class path behave as if they were directly passed to or - // obtained from the O/S API, unless conversion is explicitly requested. - // - // POSIX specfies that path strings are passed unchanged to and from the - // API. Note that this is different from the POSIX command line utilities, - // which convert according to a locale. - // - // Thus for POSIX, char strings do not undergo conversion. wchar_t strings - // are converted to/from char using the path locale or, if a conversion - // argument is given, using a conversion object modeled on - // std::wstring_convert. - // - // The path locale, which is global to the thread, can be changed by the - // imbue() function. It is initialized to an implementation defined locale. - // - // For Windows, wchar_t strings do not undergo conversion. char strings - // are converted using the "ANSI" or "OEM" code pages, as determined by - // the AreFileApisANSI() function, or, if a conversion argument is given, - // using a conversion object modeled on std::wstring_convert. - // - // See m_pathname comments for further important rationale. - - // TODO: rules needed for operating systems that use / or . - // differently, or format directory paths differently from file paths. - // - // ********************************************************************************** - // - // More work needed: How to handle an operating system that may have - // slash characters or dot characters in valid filenames, either because - // it doesn't follow the POSIX standard, or because it allows MBCS - // filename encodings that may contain slash or dot characters. For - // example, ISO/IEC 2022 (JIS) encoding which allows switching to - // JIS x0208-1983 encoding. A valid filename in this set of encodings is - // 0x1B 0x24 0x42 [switch to X0208-1983] 0x24 0x2F [U+304F Kiragana letter KU] - // ^^^^ - // Note that 0x2F is the ASCII slash character - // - // ********************************************************************************** - - // Supported source arguments: half-open iterator range, container, c-array, - // and single pointer to null terminated string. - - // All source arguments except pointers to null terminated byte strings support - // multi-byte character strings which may have embedded nulls. Embedded null - // support is required for some Asian languages on Windows. - - // [defaults] "const codecvt_type& cvt=codecvt()" default arguments are not used - // because some compilers, such as Microsoft prior to VC++ 10, do not handle defaults - // correctly in templates. - - // ----- constructors ----- - - path(){} - - path(const path& p) : m_pathname(p.m_pathname) {} - - template - path(Source const& source, - typename boost::enable_if::type> >::type* =0) - { - path_traits::dispatch(source, m_pathname, codecvt()); - } - - // Overloads for the operating system API's native character type. Rationale: - // - Avoids use of codecvt() for native value_type strings. This limits the - // impact of locale("") initialization failures on POSIX systems to programs - // that actually depend on locale(""). It further ensures that exceptions thrown - // as a result of such failues occur after main() has started, so can be caught. - // This is a partial resolution of tickets 4688, 5100, and 5289. - // - A slight optimization for a common use case, particularly on POSIX since - // value_type is char and that is the most common useage. - path(const value_type* s) : m_pathname(s) {} - path(const std::basic_string& s) : m_pathname(s) {} - - template - path(Source const& source, const codecvt_type& cvt) - // see [defaults] note above explaining why codecvt() default arguments are not used - { - path_traits::dispatch(source, m_pathname, cvt); - } - - template - path(InputIterator begin, InputIterator end) - { - if (begin != end) - { - std::basic_string::value_type> - s(begin, end); - path_traits::convert(s.c_str(), s.c_str()+s.size(), m_pathname, codecvt()); - } - } - - template - path(InputIterator begin, InputIterator end, const codecvt_type& cvt) - { - if (begin != end) - { - std::basic_string::value_type> - s(begin, end); - path_traits::convert(s.c_str(), s.c_str()+s.size(), m_pathname, cvt); - } - } - - // ----- assignments ----- - - path& operator=(const path& p) - { - m_pathname = p.m_pathname; - return *this; - } - - path& operator=(const value_type* ptr) // required in case ptr overlaps *this - { - m_pathname = ptr; - return *this; - } - - template - typename boost::enable_if::type>, path&>::type - operator=(Source const& source) - { - m_pathname.clear(); - path_traits::dispatch(source, m_pathname, codecvt()); - return *this; - } - - path& assign(const value_type* ptr, const codecvt_type&) // required in case ptr overlaps *this - { - m_pathname = ptr; - return *this; - } - - template - path& assign(Source const& source, const codecvt_type& cvt) - { - m_pathname.clear(); - path_traits::dispatch(source, m_pathname, cvt); - return *this; - } - - template - path& assign(InputIterator begin, InputIterator end) - { - return assign(begin, end, codecvt()); - } - - template - path& assign(InputIterator begin, InputIterator end, const codecvt_type& cvt) - { - m_pathname.clear(); - if (begin != end) - { - std::basic_string::value_type> - s(begin, end); - path_traits::convert(s.c_str(), s.c_str()+s.size(), m_pathname, cvt); - } - return *this; - } - - // ----- concatenation ----- - - path& operator+=(const path& p) {m_pathname += p.m_pathname; return *this;} - path& operator+=(const string_type& s) {m_pathname += s; return *this;} - path& operator+=(const value_type* ptr) {m_pathname += ptr; return *this;} - path& operator+=(value_type c) {m_pathname += c; return *this;} - - template - typename boost::enable_if::type>, path&>::type - operator+=(Source const& source) - { - return concat(source, codecvt()); - } - - template - typename boost::enable_if, path&>::type - operator+=(CharT c) - { - CharT tmp[2]; - tmp[0] = c; - tmp[1] = 0; - return concat(tmp, codecvt()); - } - - template - path& concat(Source const& source, const codecvt_type& cvt) - { - path_traits::dispatch(source, m_pathname, cvt); - return *this; - } - - template - path& concat(InputIterator begin, InputIterator end) - { - return concat(begin, end, codecvt()); - } - - template - path& concat(InputIterator begin, InputIterator end, const codecvt_type& cvt) - { - if (begin == end) - return *this; - std::basic_string::value_type> - s(begin, end); - path_traits::convert(s.c_str(), s.c_str()+s.size(), m_pathname, cvt); - return *this; - } - - // ----- appends ----- - - // if a separator is added, it is the preferred separator for the platform; - // slash for POSIX, backslash for Windows - - path& operator/=(const path& p); - - path& operator/=(const value_type* ptr); - - template - typename boost::enable_if::type>, path&>::type - operator/=(Source const& source) - { - return append(source, codecvt()); - } - - path& append(const value_type* ptr, const codecvt_type&) // required in case ptr overlaps *this - { - this->operator/=(ptr); - return *this; - } - - template - path& append(Source const& source, const codecvt_type& cvt); - - template - path& append(InputIterator begin, InputIterator end) - { - return append(begin, end, codecvt()); - } - - template - path& append(InputIterator begin, InputIterator end, const codecvt_type& cvt); - - // ----- modifiers ----- - - void clear() { m_pathname.clear(); } - path& make_preferred() -# ifdef BOOST_POSIX_API - { return *this; } // POSIX no effect -# else // BOOST_WINDOWS_API - ; // change slashes to backslashes -# endif - path& remove_filename(); - path& replace_extension(const path& new_extension = path()); - void swap(path& rhs) { m_pathname.swap(rhs.m_pathname); } - - // ----- observers ----- - - // For operating systems that format file paths differently than directory - // paths, return values from observers are formatted as file names unless there - // is a trailing separator, in which case returns are formatted as directory - // paths. POSIX and Windows make no such distinction. - - // Implementations are permitted to return const values or const references. - - // The string or path returned by an observer are specified as being formatted - // as "native" or "generic". - // - // For POSIX, these are all the same format; slashes and backslashes are as input and - // are not modified. - // - // For Windows, native: as input; slashes and backslashes are not modified; - // this is the format of the internally stored string. - // generic: backslashes are converted to slashes - - // ----- native format observers ----- - - const string_type& native() const { return m_pathname; } // Throws: nothing - const value_type* c_str() const { return m_pathname.c_str(); } // Throws: nothing - - template - String string() const; - - template - String string(const codecvt_type& cvt) const; - -# ifdef BOOST_WINDOWS_API - const std::string string() const { return string(codecvt()); } - const std::string string(const codecvt_type& cvt) const - { - std::string tmp; - if (!m_pathname.empty()) - path_traits::convert(&*m_pathname.begin(), &*m_pathname.begin()+m_pathname.size(), - tmp, cvt); - return tmp; - } - - // string_type is std::wstring, so there is no conversion - const std::wstring& wstring() const { return m_pathname; } - const std::wstring& wstring(const codecvt_type&) const { return m_pathname; } - -# else // BOOST_POSIX_API - // string_type is std::string, so there is no conversion - const std::string& string() const { return m_pathname; } - const std::string& string(const codecvt_type&) const { return m_pathname; } - - const std::wstring wstring() const { return wstring(codecvt()); } - const std::wstring wstring(const codecvt_type& cvt) const - { - std::wstring tmp; - if (!m_pathname.empty()) - path_traits::convert(&*m_pathname.begin(), &*m_pathname.begin()+m_pathname.size(), - tmp, cvt); - return tmp; - } - -# endif - - // ----- generic format observers ----- - - template - String generic_string() const; - - template - String generic_string(const codecvt_type& cvt) const; - -# ifdef BOOST_WINDOWS_API - const std::string generic_string() const { return generic_string(codecvt()); } - const std::string generic_string(const codecvt_type& cvt) const; - const std::wstring generic_wstring() const; - const std::wstring generic_wstring(const codecvt_type&) const { return generic_wstring(); }; - -# else // BOOST_POSIX_API - // On POSIX-like systems, the generic format is the same as the native format - const std::string& generic_string() const { return m_pathname; } - const std::string& generic_string(const codecvt_type&) const { return m_pathname; } - const std::wstring generic_wstring() const { return wstring(codecvt()); } - const std::wstring generic_wstring(const codecvt_type& cvt) const { return wstring(cvt); } - -# endif - - // ----- compare ----- - - int compare(const path& p) const BOOST_NOEXCEPT; // generic, lexicographical - int compare(const std::string& s) const { return compare(path(s)); } - int compare(const value_type* s) const { return compare(path(s)); } - - // ----- decomposition ----- - - path root_path() const; - path root_name() const; // returns 0 or 1 element path - // even on POSIX, root_name() is non-empty() for network paths - path root_directory() const; // returns 0 or 1 element path - path relative_path() const; - path parent_path() const; - path filename() const; // returns 0 or 1 element path - path stem() const; // returns 0 or 1 element path - path extension() const; // returns 0 or 1 element path - - // ----- query ----- - - bool empty() const { return m_pathname.empty(); } // name consistent with std containers - bool has_root_path() const { return has_root_directory() || has_root_name(); } - bool has_root_name() const { return !root_name().empty(); } - bool has_root_directory() const { return !root_directory().empty(); } - bool has_relative_path() const { return !relative_path().empty(); } - bool has_parent_path() const { return !parent_path().empty(); } - bool has_filename() const { return !m_pathname.empty(); } - bool has_stem() const { return !stem().empty(); } - bool has_extension() const { return !extension().empty(); } - bool is_absolute() const - { -# ifdef BOOST_WINDOWS_API - return has_root_name() && has_root_directory(); -# else - return has_root_directory(); -# endif - } - bool is_relative() const { return !is_absolute(); } - - // ----- iterators ----- - - class iterator; - typedef iterator const_iterator; - - iterator begin() const; - iterator end() const; - - // ----- static member functions ----- - - static std::locale imbue(const std::locale& loc); - static const codecvt_type& codecvt(); - - // ----- deprecated functions ----- - -# if defined(BOOST_FILESYSTEM_DEPRECATED) && defined(BOOST_FILESYSTEM_NO_DEPRECATED) -# error both BOOST_FILESYSTEM_DEPRECATED and BOOST_FILESYSTEM_NO_DEPRECATED are defined -# endif - -# if !defined(BOOST_FILESYSTEM_NO_DEPRECATED) - // recently deprecated functions supplied by default - path& normalize() { return m_normalize(); } - path& remove_leaf() { return remove_filename(); } - path leaf() const { return filename(); } - path branch_path() const { return parent_path(); } - bool has_leaf() const { return !m_pathname.empty(); } - bool has_branch_path() const { return !parent_path().empty(); } - bool is_complete() const { return is_absolute(); } +# if defined(BOOST_FILESYSTEM_VERSION) \ + && BOOST_FILESYSTEM_VERSION != 2 && BOOST_FILESYSTEM_VERSION != 3 +# error BOOST_FILESYSTEM_VERSION defined, but not as 2 or 3 # endif -# if defined(BOOST_FILESYSTEM_DEPRECATED) - // deprecated functions with enough signature or semantic changes that they are - // not supplied by default - const std::string file_string() const { return string(); } - const std::string directory_string() const { return string(); } - const std::string native_file_string() const { return string(); } - const std::string native_directory_string() const { return string(); } - const string_type external_file_string() const { return native(); } - const string_type external_directory_string() const { return native(); } - - // older functions no longer supported - //typedef bool (*name_check)(const std::string & name); - //basic_path(const string_type& str, name_check) { operator/=(str); } - //basic_path(const typename string_type::value_type* s, name_check) - // { operator/=(s);} - //static bool default_name_check_writable() { return false; } - //static void default_name_check(name_check) {} - //static name_check default_name_check() { return 0; } - //basic_path& canonize(); +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 # endif -//--------------------------------------------------------------------------------------// -// class path private members // -//--------------------------------------------------------------------------------------// - - private: -# if defined(_MSC_VER) -# pragma warning(push) // Save warning settings -# pragma warning(disable : 4251) // disable warning: class 'std::basic_string<_Elem,_Traits,_Ax>' -# endif // needs to have dll-interface... -/* - m_pathname has the type, encoding, and format required by the native - operating system. Thus for POSIX and Windows there is no conversion for - passing m_pathname.c_str() to the O/S API or when obtaining a path from the - O/S API. POSIX encoding is unspecified other than for dot and slash - characters; POSIX just treats paths as a sequence of bytes. Windows - encoding is UCS-2 or UTF-16 depending on the version. -*/ - string_type m_pathname; // Windows: as input; backslashes NOT converted to slashes, - // slashes NOT converted to backslashes -# if defined(_MSC_VER) -# pragma warning(pop) // restore warning settings. -# endif - - string_type::size_type m_append_separator_if_needed(); - // Returns: If separator is to be appended, m_pathname.size() before append. Otherwise 0. - // Note: An append is never performed if size()==0, so a returned 0 is unambiguous. +#if BOOST_FILESYSTEM_VERSION == 2 +# include - void m_erase_redundant_separator(string_type::size_type sep_pos); - string_type::size_type m_parent_path_end() const; +# else +# include - path& m_normalize(); - - // Was qualified; como433beta8 reports: - // warning #427-D: qualified name is not allowed in member declaration - friend class iterator; - friend bool operator<(const path& lhs, const path& rhs); - - // see path::iterator::increment/decrement comment below - static void m_path_iterator_increment(path::iterator & it); - static void m_path_iterator_decrement(path::iterator & it); - - }; // class path - - namespace detail - { - BOOST_FILESYSTEM_DECL - int lex_compare(path::iterator first1, path::iterator last1, - path::iterator first2, path::iterator last2); - } - -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - typedef path wpath; # endif - //------------------------------------------------------------------------------------// - // class path::iterator // - //------------------------------------------------------------------------------------// - - class path::iterator - : public boost::iterator_facade< - path::iterator, - path const, - boost::bidirectional_traversal_tag > - { - private: - friend class boost::iterator_core_access; - friend class boost::filesystem::path; - friend void m_path_iterator_increment(path::iterator & it); - friend void m_path_iterator_decrement(path::iterator & it); - - const path& dereference() const { return m_element; } - - bool equal(const iterator & rhs) const - { - return m_path_ptr == rhs.m_path_ptr && m_pos == rhs.m_pos; - } - - // iterator_facade derived classes don't seem to like implementations in - // separate translation unit dll's, so forward to class path static members - void increment() { m_path_iterator_increment(*this); } - void decrement() { m_path_iterator_decrement(*this); } - - path m_element; // current element - const path* m_path_ptr; // path being iterated over - string_type::size_type m_pos; // position of m_element in - // m_path_ptr->m_pathname. - // if m_element is implicit dot, m_pos is the - // position of the last separator in the path. - // end() iterator is indicated by - // m_pos == m_path_ptr->m_pathname.size() - }; // path::iterator - - //------------------------------------------------------------------------------------// - // // - // non-member functions // - // // - //------------------------------------------------------------------------------------// - - // std::lexicographical_compare would infinately recurse because path iterators - // yield paths, so provide a path aware version - inline bool lexicographical_compare(path::iterator first1, path::iterator last1, - path::iterator first2, path::iterator last2) - { return detail::lex_compare(first1, last1, first2, last2) < 0; } - - inline bool operator==(const path& lhs, const path& rhs) {return lhs.compare(rhs) == 0;} - inline bool operator==(const path& lhs, const path::string_type& rhs) {return lhs.compare(rhs) == 0;} - inline bool operator==(const path::string_type& lhs, const path& rhs) {return rhs.compare(lhs) == 0;} - inline bool operator==(const path& lhs, const path::value_type* rhs) {return lhs.compare(rhs) == 0;} - inline bool operator==(const path::value_type* lhs, const path& rhs) {return rhs.compare(lhs) == 0;} - - inline bool operator!=(const path& lhs, const path& rhs) {return lhs.compare(rhs) != 0;} - inline bool operator!=(const path& lhs, const path::string_type& rhs) {return lhs.compare(rhs) != 0;} - inline bool operator!=(const path::string_type& lhs, const path& rhs) {return rhs.compare(lhs) != 0;} - inline bool operator!=(const path& lhs, const path::value_type* rhs) {return lhs.compare(rhs) != 0;} - inline bool operator!=(const path::value_type* lhs, const path& rhs) {return rhs.compare(lhs) != 0;} - - // TODO: why do == and != have additional overloads, but the others don't? - - inline bool operator<(const path& lhs, const path& rhs) {return lhs.compare(rhs) < 0;} - inline bool operator<=(const path& lhs, const path& rhs) {return !(rhs < lhs);} - inline bool operator> (const path& lhs, const path& rhs) {return rhs < lhs;} - inline bool operator>=(const path& lhs, const path& rhs) {return !(lhs < rhs);} - - inline std::size_t hash_value(const path& x) - { -# ifdef BOOST_WINDOWS_API - std::size_t seed = 0; - for(const path::value_type* it = x.c_str(); *it; ++it) - hash_combine(seed, *it == '/' ? L'\\' : *it); - return seed; -# else // BOOST_POSIX_API - return hash_range(x.native().begin(), x.native().end()); -# endif - } - - inline void swap(path& lhs, path& rhs) { lhs.swap(rhs); } - - inline path operator/(const path& lhs, const path& rhs) { return path(lhs) /= rhs; } - - // inserters and extractors - // use boost::io::quoted() to handle spaces in paths - // use '&' as escape character to ease use for Windows paths - - template - inline std::basic_ostream& - operator<<(std::basic_ostream& os, const path& p) - { - return os - << boost::io::quoted(p.template string >(), static_cast('&')); - } - - template - inline std::basic_istream& - operator>>(std::basic_istream& is, path& p) - { - std::basic_string str; - is >> boost::io::quoted(str, static_cast('&')); - p = str; - return is; - } - - // name_checks - - // These functions are holdovers from version 1. It isn't clear they have much - // usefulness, or how to generalize them for later versions. - - BOOST_FILESYSTEM_DECL bool portable_posix_name(const std::string & name); - BOOST_FILESYSTEM_DECL bool windows_name(const std::string & name); - BOOST_FILESYSTEM_DECL bool portable_name(const std::string & name); - BOOST_FILESYSTEM_DECL bool portable_directory_name(const std::string & name); - BOOST_FILESYSTEM_DECL bool portable_file_name(const std::string & name); - BOOST_FILESYSTEM_DECL bool native(const std::string & name); - -//--------------------------------------------------------------------------------------// -// class path member template implementation // -//--------------------------------------------------------------------------------------// - - template - path& path::append(InputIterator begin, InputIterator end, const codecvt_type& cvt) - { - if (begin == end) - return *this; - string_type::size_type sep_pos(m_append_separator_if_needed()); - std::basic_string::value_type> - s(begin, end); - path_traits::convert(s.c_str(), s.c_str()+s.size(), m_pathname, cvt); - if (sep_pos) - m_erase_redundant_separator(sep_pos); - return *this; - } - - template - path& path::append(Source const& source, const codecvt_type& cvt) - { - if (path_traits::empty(source)) - return *this; - string_type::size_type sep_pos(m_append_separator_if_needed()); - path_traits::dispatch(source, m_pathname, cvt); - if (sep_pos) - m_erase_redundant_separator(sep_pos); - return *this; - } - -//--------------------------------------------------------------------------------------// -// class path member template specializations // -//--------------------------------------------------------------------------------------// - - template <> inline - std::string path::string() const - { return string(); } - - template <> inline - std::wstring path::string() const - { return wstring(); } - - template <> inline - std::string path::string(const codecvt_type& cvt) const - { return string(cvt); } - - template <> inline - std::wstring path::string(const codecvt_type& cvt) const - { return wstring(cvt); } - - template <> inline - std::string path::generic_string() const - { return generic_string(); } - - template <> inline - std::wstring path::generic_string() const - { return generic_wstring(); } - - template <> inline - std::string path::generic_string(const codecvt_type& cvt) const - { return generic_string(cvt); } - - template <> inline - std::wstring path::generic_string(const codecvt_type& cvt) const - { return generic_wstring(cvt); } - - -} // namespace filesystem -} // namespace boost - -//----------------------------------------------------------------------------// - -#include // pops abi_prefix.hpp pragmas - -#endif // BOOST_FILESYSTEM_PATH_HPP +#endif // BOOST_FILESYSTEM_PATHX_HPP diff --git a/utils/boost_idb/boost/filesystem/path_traits.hpp b/utils/boost_idb/boost/filesystem/path_traits.hpp deleted file mode 100644 index a6a25055..00000000 --- a/utils/boost_idb/boost/filesystem/path_traits.hpp +++ /dev/null @@ -1,235 +0,0 @@ -// filesystem path_traits.hpp --------------------------------------------------------// - -// Copyright Beman Dawes 2009 - -// Distributed under the Boost Software License, Version 1.0. -// See http://www.boost.org/LICENSE_1_0.txt - -// Library home page: http://www.boost.org/libs/filesystem - -#ifndef BOOST_FILESYSTEM_PATH_TRAITS_HPP -#define BOOST_FILESYSTEM_PATH_TRAITS_HPP - -#include - -# if defined( BOOST_NO_STD_WSTRING ) -# error Configuration not supported: Boost.Filesystem V3 and later requires std::wstring support -# endif - -#include -#include -#include -#include -#include -#include // for mbstate_t -#include -#include -#include -#include -#include -#include -// #include //**** comment me out **** - -#include // must be the last #include - -namespace boost { namespace filesystem { - - BOOST_FILESYSTEM_DECL const system::error_category& codecvt_error_category(); - // uses std::codecvt_base::result used for error codes: - // - // ok: Conversion successful. - // partial: Not all source characters converted; one or more additional source - // characters are needed to produce the final target character, or the - // size of the target intermediate buffer was too small to hold the result. - // error: A character in the source could not be converted to the target encoding. - // noconv: The source and target characters have the same type and encoding, so no - // conversion was necessary. - - class directory_entry; - -namespace path_traits { - - typedef std::codecvt codecvt_type; - - // is_pathable type trait; allows disabling over-agressive class path member templates - - template - struct is_pathable { static const bool value = false; }; - - template<> struct is_pathable { static const bool value = true; }; - template<> struct is_pathable { static const bool value = true; }; - template<> struct is_pathable { static const bool value = true; }; - template<> struct is_pathable { static const bool value = true; }; - template<> struct is_pathable { static const bool value = true; }; - template<> struct is_pathable { static const bool value = true; }; - template<> struct is_pathable > { static const bool value = true; }; - template<> struct is_pathable > { static const bool value = true; }; - template<> struct is_pathable > { static const bool value = true; }; - template<> struct is_pathable > { static const bool value = true; }; - template<> struct is_pathable { static const bool value = true; }; - - // Pathable empty - - template inline - // disable_if aids broken compilers (IBM, old GCC, etc.) and is harmless for - // conforming compilers. Replace by plain "bool" at some future date (2012?) - typename boost::disable_if, bool>::type - empty(const Container & c) - { return c.begin() == c.end(); } - - template inline - bool empty(T * const & c_str) - { - BOOST_ASSERT(c_str); - return !*c_str; - } - - template inline - bool empty(T (&x)[N]) - { return !x[0]; } - - // value types differ ---------------------------------------------------------------// - // - // A from_end argument of 0 is less efficient than a known end, so use only if needed - - BOOST_FILESYSTEM_DECL - void convert(const char* from, - const char* from_end, // 0 for null terminated MBCS - std::wstring & to, - const codecvt_type& cvt); - - BOOST_FILESYSTEM_DECL - void convert(const wchar_t* from, - const wchar_t* from_end, // 0 for null terminated MBCS - std::string & to, - const codecvt_type& cvt); - - inline - void convert(const char* from, - std::wstring & to, - const codecvt_type& cvt) - { - BOOST_ASSERT(from); - convert(from, 0, to, cvt); - } - - inline - void convert(const wchar_t* from, - std::string & to, - const codecvt_type& cvt) - { - BOOST_ASSERT(from); - convert(from, 0, to, cvt); - } - - // value types same -----------------------------------------------------------------// - - // char - - inline - void convert(const char* from, const char* from_end, std::string & to, - const codecvt_type&) - { - BOOST_ASSERT(from); - BOOST_ASSERT(from_end); - to.append(from, from_end); - } - - inline - void convert(const char* from, - std::string & to, - const codecvt_type&) - { - BOOST_ASSERT(from); - to += from; - } - - // wchar_t - - inline - void convert(const wchar_t* from, const wchar_t* from_end, std::wstring & to, - const codecvt_type&) - { - BOOST_ASSERT(from); - BOOST_ASSERT(from_end); - to.append(from, from_end); - } - - inline - void convert(const wchar_t* from, - std::wstring & to, - const codecvt_type&) - { - BOOST_ASSERT(from); - to += from; - } - - // Source dispatch -----------------------------------------------------------------// - - // contiguous containers - template inline - void dispatch(const std::string& c, U& to, const codecvt_type& cvt) - { - if (c.size()) - convert(&*c.begin(), &*c.begin() + c.size(), to, cvt); - } - template inline - void dispatch(const std::wstring& c, U& to, const codecvt_type& cvt) - { - if (c.size()) - convert(&*c.begin(), &*c.begin() + c.size(), to, cvt); - } - template inline - void dispatch(const std::vector& c, U& to, const codecvt_type& cvt) - { - if (c.size()) - convert(&*c.begin(), &*c.begin() + c.size(), to, cvt); - } - template inline - void dispatch(const std::vector& c, U& to, const codecvt_type& cvt) - { - if (c.size()) - convert(&*c.begin(), &*c.begin() + c.size(), to, cvt); - } - - // non-contiguous containers - template inline - // disable_if aids broken compilers (IBM, old GCC, etc.) and is harmless for - // conforming compilers. Replace by plain "void" at some future date (2012?) - typename boost::disable_if, void>::type - dispatch(const Container & c, U& to, const codecvt_type& cvt) - { - if (c.size()) - { - std::basic_string s(c.begin(), c.end()); - convert(s.c_str(), s.c_str()+s.size(), to, cvt); - } - } - - // c_str - template inline - void dispatch(T * const & c_str, U& to, const codecvt_type& cvt) - { -// std::cout << "dispatch() const T *\n"; - BOOST_ASSERT(c_str); - convert(c_str, to, cvt); - } - - // Note: there is no dispatch on C-style arrays because the array may - // contain a string smaller than the array size. - - BOOST_FILESYSTEM_DECL - void dispatch(const directory_entry & de, -# ifdef BOOST_WINDOWS_API - std::wstring & to, -# else - std::string & to, -# endif - const codecvt_type&); - - -}}} // namespace boost::filesystem::path_traits - -#include // pops abi_prefix.hpp pragmas - -#endif // BOOST_FILESYSTEM_PATH_TRAITS_HPP diff --git a/utils/boost_idb/boost/filesystem/v2/config.hpp b/utils/boost_idb/boost/filesystem/v2/config.hpp new file mode 100644 index 00000000..62656efd --- /dev/null +++ b/utils/boost_idb/boost/filesystem/v2/config.hpp @@ -0,0 +1,96 @@ +// boost/filesystem/v2/config.hpp ------------------------------------------// + +// Copyright Beman Dawes 2003 + +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// See library home page at http://www.boost.org/libs/filesystem + +//----------------------------------------------------------------------------// + +#ifndef BOOST_FILESYSTEM2_CONFIG_HPP +#define BOOST_FILESYSTEM2_CONFIG_HPP + +# if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION != 2 +# error Compiling Filesystem version 2 file with BOOST_FILESYSTEM_VERSION defined != 2 +# endif + +# if !defined(BOOST_FILESYSTEM_VERSION) +# define BOOST_FILESYSTEM_VERSION 2 +# endif + +#define BOOST_FILESYSTEM_I18N // aid users wishing to compile several versions + +// ability to change namespace aids path_table.cpp ------------------------// +#ifndef BOOST_FILESYSTEM2_NAMESPACE +# define BOOST_FILESYSTEM2_NAMESPACE filesystem2 +#endif + +#include +#include // for BOOST_POSIX_API or BOOST_WINDOWS_API +#include + +// BOOST_POSIX_PATH or BOOST_WINDOWS_PATH specify which path syntax to recognise + +# if defined(BOOST_WINDOWS_API) && defined(BOOST_POSIX_PATH) +# error builds with Windows API do not support BOOST_POSIX_PATH +# endif + +# if !defined(_WIN32) && !defined(__CYGWIN__) && defined(BOOST_WINDOWS_PATH) +# error builds on non-Windows platforms do not support BOOST_WINDOWS_PATH +# endif + +# if defined(BOOST_WINDOWS_PATH) && defined(BOOST_POSIX_PATH) +# error both BOOST_WINDOWS_PATH and BOOST_POSIX_PATH are defined +# elif !defined(BOOST_WINDOWS_PATH) && !defined(BOOST_POSIX_PATH) +# if !defined(BOOST_POSIX_PATH) && (defined(_WIN32) || defined(__CYGWIN__)) +# define BOOST_WINDOWS_PATH +# else +# define BOOST_POSIX_PATH +# endif +# endif + +// narrow support only for badly broken compilers or libraries -------------// + +# if defined(BOOST_NO_STD_WSTRING) || defined(BOOST_NO_SFINAE) || defined(BOOST_NO_STD_LOCALE) || BOOST_WORKAROUND(__BORLANDC__, <0x610) +# define BOOST_FILESYSTEM2_NARROW_ONLY +# endif + +// This header implements separate compilation features as described in +// http://www.boost.org/more/separate_compilation.html + +// enable dynamic linking ---------------------------------------------------// + +#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FILESYSTEM_DYN_LINK) +# if defined(BOOST_FILESYSTEM_SOURCE) +# define BOOST_FILESYSTEM_DECL BOOST_SYMBOL_EXPORT +# else +# define BOOST_FILESYSTEM_DECL BOOST_SYMBOL_IMPORT +# endif +#else +# define BOOST_FILESYSTEM_DECL +#endif + +// enable automatic library variant selection ------------------------------// + +#if !defined(BOOST_FILESYSTEM_SOURCE) && !defined(BOOST_ALL_NO_LIB) \ + && !defined(BOOST_FILESYSTEM_NO_LIB) +// +// Set the name of our library, this will get undef'ed by auto_link.hpp +// once it's done with it: +// +#define BOOST_LIB_NAME boost_filesystem +// +// If we're importing code from a dll, then tell auto_link.hpp about it: +// +#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FILESYSTEM_DYN_LINK) +# define BOOST_DYN_LINK +#endif +// +// And include the header that does the work: +// +#include +#endif // auto-linking disabled + +#endif // BOOST_FILESYSTEM2_CONFIG_HPP diff --git a/utils/boost_idb/boost/filesystem/v2/convenience.hpp b/utils/boost_idb/boost/filesystem/v2/convenience.hpp new file mode 100644 index 00000000..4695a01d --- /dev/null +++ b/utils/boost_idb/boost/filesystem/v2/convenience.hpp @@ -0,0 +1,338 @@ +// boost/filesystem/convenience.hpp ----------------------------------------// + +// Copyright Beman Dawes, 2002-2005 +// Copyright Vladimir Prus, 2002 +// Use, modification, and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// See library home page at http://www.boost.org/libs/filesystem + +//----------------------------------------------------------------------------// + +#ifndef BOOST_FILESYSTEM2_CONVENIENCE_HPP +#define BOOST_FILESYSTEM2_CONVENIENCE_HPP + +#include +#include +#include +#include + +#include // must be the last #include + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY +# define BOOST_FS_FUNC(BOOST_FS_TYPE) \ + template typename boost::enable_if, \ + BOOST_FS_TYPE>::type +# define BOOST_FS_FUNC_STRING BOOST_FS_FUNC(typename Path::string_type) +# define BOOST_FS_TYPENAME typename +# else +# define BOOST_FS_FUNC(BOOST_FS_TYPE) inline BOOST_FS_TYPE + typedef boost::filesystem::path Path; +# define BOOST_FS_FUNC_STRING inline std::string +# define BOOST_FS_TYPENAME +# endif + +namespace boost +{ + namespace filesystem2 + { + + BOOST_FS_FUNC(bool) create_directories(const Path& ph) + { + if (ph.empty() || exists(ph)) + { + if ( !ph.empty() && !is_directory(ph) ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::create_directories", ph, + make_error_code( boost::system::errc::file_exists ) ) ); + return false; + } + + // First create branch, by calling ourself recursively + create_directories(ph.parent_path()); + // Now that parent's path exists, create the directory + create_directory(ph); + return true; + } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + + BOOST_FS_FUNC_STRING extension(const Path& ph) + { + typedef BOOST_FS_TYPENAME Path::string_type string_type; + string_type filename = ph.filename(); + + BOOST_FS_TYPENAME string_type::size_type n = filename.rfind('.'); + if (n != string_type::npos) + return filename.substr(n); + else + return string_type(); + } + + BOOST_FS_FUNC_STRING basename(const Path& ph) + { + typedef BOOST_FS_TYPENAME Path::string_type string_type; + string_type filename = ph.filename(); + BOOST_FS_TYPENAME string_type::size_type n = filename.rfind('.'); + return filename.substr(0, n); + } + + + BOOST_FS_FUNC(Path) change_extension( const Path & ph, + const BOOST_FS_TYPENAME Path::string_type & new_extension ) + { +# if !defined(_STLPORT_VERSION) + return ph.parent_path() / (basename(ph) + new_extension); +# else + typedef BOOST_FS_TYPENAME Path::string_type string_type; + string_type filename = basename(ph) + new_extension; + return ph.parent_path() / filename; +# endif + } +# endif + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + // "do-the-right-thing" overloads ---------------------------------------// + + inline bool create_directories(const path& ph) + { return create_directories(ph); } + inline bool create_directories(const wpath& ph) + { return create_directories(ph); } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + inline std::string extension(const path& ph) + { return extension(ph); } + inline std::wstring extension(const wpath& ph) + { return extension(ph); } + + inline std::string basename(const path& ph) + { return basename( ph ); } + inline std::wstring basename(const wpath& ph) + { return basename( ph ); } + + inline path change_extension( const path & ph, const std::string& new_ex ) + { return change_extension( ph, new_ex ); } + inline wpath change_extension( const wpath & ph, const std::wstring& new_ex ) + { return change_extension( ph, new_ex ); } +# endif + +# endif + + + // basic_recursive_directory_iterator helpers --------------------------// + + namespace detail + { + template< class Path > + struct recur_dir_itr_imp + { + typedef basic_directory_iterator< Path > element_type; + std::stack< element_type, std::vector< element_type > > m_stack; + int m_level; + bool m_no_push; + bool m_no_throw; + + recur_dir_itr_imp() : m_level(0), m_no_push(false), m_no_throw(false) {} + }; + + } // namespace detail + + // basic_recursive_directory_iterator ----------------------------------// + + template< class Path > + class basic_recursive_directory_iterator + : public boost::iterator_facade< + basic_recursive_directory_iterator, + basic_directory_entry, + boost::single_pass_traversal_tag > + { + public: + typedef Path path_type; + + basic_recursive_directory_iterator(){} // creates the "end" iterator + + explicit basic_recursive_directory_iterator( const Path & dir_path ); + basic_recursive_directory_iterator( const Path & dir_path, + system::error_code & ec ); + + int level() const { return m_imp->m_level; } + + void pop(); + void no_push() + { + BOOST_ASSERT( m_imp.get() && "attempt to no_push() on end iterator" ); + m_imp->m_no_push = true; + } + + file_status status() const + { + BOOST_ASSERT( m_imp.get() + && "attempt to call status() on end recursive_iterator" ); + return m_imp->m_stack.top()->status(); + } + + file_status symlink_status() const + { + BOOST_ASSERT( m_imp.get() + && "attempt to call symlink_status() on end recursive_iterator" ); + return m_imp->m_stack.top()->symlink_status(); + } + + private: + + // shared_ptr provides shallow-copy semantics required for InputIterators. + // m_imp.get()==0 indicates the end iterator. + boost::shared_ptr< detail::recur_dir_itr_imp< Path > > m_imp; + + friend class boost::iterator_core_access; + + typename boost::iterator_facade< + basic_recursive_directory_iterator, + basic_directory_entry, + boost::single_pass_traversal_tag >::reference + dereference() const + { + BOOST_ASSERT( m_imp.get() && "attempt to dereference end iterator" ); + return *m_imp->m_stack.top(); + } + + void increment(); + + bool equal( const basic_recursive_directory_iterator & rhs ) const + { return m_imp == rhs.m_imp; } + + }; + + typedef basic_recursive_directory_iterator recursive_directory_iterator; +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + typedef basic_recursive_directory_iterator wrecursive_directory_iterator; +# endif + + // basic_recursive_directory_iterator implementation -------------------// + + // constructors + template + basic_recursive_directory_iterator:: + basic_recursive_directory_iterator( const Path & dir_path ) + : m_imp( new detail::recur_dir_itr_imp ) + { + m_imp->m_stack.push( basic_directory_iterator( dir_path ) ); + if ( m_imp->m_stack.top () == basic_directory_iterator() ) + { m_imp.reset (); } + } + + template + basic_recursive_directory_iterator:: + basic_recursive_directory_iterator( const Path & dir_path, + system::error_code & ec ) + : m_imp( new detail::recur_dir_itr_imp ) + { + m_imp->m_no_throw = true; + m_imp->m_stack.push( basic_directory_iterator( dir_path, ec ) ); + if ( m_imp->m_stack.top () == basic_directory_iterator() ) + { m_imp.reset (); } + } + + // increment + template + void basic_recursive_directory_iterator::increment() + { + BOOST_ASSERT( m_imp.get() && "increment on end iterator" ); + + static const basic_directory_iterator end_itr; + + if ( m_imp->m_no_push ) + { m_imp->m_no_push = false; } + else if ( is_directory( m_imp->m_stack.top()->status() ) ) + { + system::error_code ec; +#if BOOST_WORKAROUND(__CODEGEARC__, BOOST_TESTED_AT(0x610)) + if( m_imp->m_no_throw ) { + m_imp->m_stack.push( + basic_directory_iterator( *m_imp->m_stack.top(), ec ) + ); + } + else { + m_imp->m_stack.push( + basic_directory_iterator( *m_imp->m_stack.top() ) + ); + } +#else + m_imp->m_stack.push( + m_imp->m_no_throw + ? basic_directory_iterator( *m_imp->m_stack.top(), ec ) + : basic_directory_iterator( *m_imp->m_stack.top() ) ); +#endif + if ( m_imp->m_stack.top() != end_itr ) + { + ++m_imp->m_level; + return; + } + m_imp->m_stack.pop(); + } + + while ( !m_imp->m_stack.empty() + && ++m_imp->m_stack.top() == end_itr ) + { + m_imp->m_stack.pop(); + --m_imp->m_level; + } + + if ( m_imp->m_stack.empty() ) m_imp.reset(); // done, so make end iterator + } + + // pop + template + void basic_recursive_directory_iterator::pop() + { + BOOST_ASSERT( m_imp.get() && "pop on end iterator" ); + BOOST_ASSERT( m_imp->m_level > 0 && "pop with level < 1" ); + + static const basic_directory_iterator end_itr; + + do + { + m_imp->m_stack.pop(); + --m_imp->m_level; + } + while ( !m_imp->m_stack.empty() + && ++m_imp->m_stack.top() == end_itr ); + + if ( m_imp->m_stack.empty() ) m_imp.reset(); // done, so make end iterator + } + + } // namespace filesystem2 +} // namespace boost + +#undef BOOST_FS_FUNC_STRING +#undef BOOST_FS_FUNC + +//----------------------------------------------------------------------------// + +namespace boost +{ + namespace filesystem + { + using filesystem2::create_directories; + using filesystem2::basic_recursive_directory_iterator; + using filesystem2::recursive_directory_iterator; + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + using filesystem2::extension; + using filesystem2::basename; + using filesystem2::change_extension; +# endif + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + using filesystem2::wrecursive_directory_iterator; +# endif + + } +} + +//----------------------------------------------------------------------------// + +#include // pops abi_prefix.hpp pragmas +#endif // BOOST_FILESYSTEM2_CONVENIENCE_HPP diff --git a/utils/boost_idb/boost/filesystem/v2/exception.hpp b/utils/boost_idb/boost/filesystem/v2/exception.hpp new file mode 100644 index 00000000..edea663b --- /dev/null +++ b/utils/boost_idb/boost/filesystem/v2/exception.hpp @@ -0,0 +1,9 @@ +// boost/filesystem/exception.hpp -------------------------------------------// + +// Copyright Beman Dawes 2003 +// Use, modification, and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// This header is no long used. The contents have been moved to path.hpp. +// It is provided so that user code #includes do not have to be changed. diff --git a/utils/boost_idb/boost/filesystem/v2/fstream.hpp b/utils/boost_idb/boost/filesystem/v2/fstream.hpp new file mode 100644 index 00000000..bdcd4852 --- /dev/null +++ b/utils/boost_idb/boost/filesystem/v2/fstream.hpp @@ -0,0 +1,612 @@ +// boost/filesystem/fstream.hpp --------------------------------------------// + +// Copyright Beman Dawes 2002. +// Use, modification, and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// See library home page at http://www.boost.org/libs/filesystem + +//----------------------------------------------------------------------------// + +#ifndef BOOST_FILESYSTEM2_FSTREAM_HPP +#define BOOST_FILESYSTEM2_FSTREAM_HPP + +#include // for 8.3 hack (see below) +#include +#include + +#include +#include + +#include // must be the last #include + +// NOTE: fstream.hpp for Boost 1.32.0 and earlier supplied workarounds for +// various compiler problems. They have been removed to ease development of the +// basic i18n functionality. Once the new interface is stable, the workarounds +// will be reinstated for any compilers that otherwise can support the rest of +// the library after internationalization. + +namespace boost +{ + namespace filesystem2 + { + namespace detail + { +# if defined(BOOST_WINDOWS_API) && !defined(BOOST_FILESYSTEM2_NARROW_ONLY) +# if !defined(BOOST_DINKUMWARE_STDLIB) || BOOST_DINKUMWARE_STDLIB < 405 + // The 8.3 hack: + // C++98 does not supply a wchar_t open, so try to get an equivalent + // narrow char name based on the short, so-called 8.3, name. + // Not needed for Dinkumware 405 and later as they do supply wchar_t open. + BOOST_FILESYSTEM_DECL bool create_file_api( const std::wstring & ph, + std::ios_base::openmode mode ); // true if succeeds + BOOST_FILESYSTEM_DECL std::string narrow_path_api( + const std::wstring & ph ); // return is empty if fails + + inline std::string path_proxy( const std::wstring & file_ph, + std::ios_base::openmode mode ) + // Return a non-existant path if cannot supply narrow short path. + // An empty path doesn't work because some Dinkumware versions + // assert the path is non-empty. + { + std::string narrow_ph; + bool created_file( false ); + if ( !exists( file_ph ) + && (mode & std::ios_base::out) != 0 + && create_file_api( file_ph, mode ) ) + { + created_file = true; + } + narrow_ph = narrow_path_api( file_ph ); + if ( narrow_ph.empty() ) + { + if ( created_file ) remove_api( file_ph ); + narrow_ph = "\x01"; + } + return narrow_ph; + } +# else + // Dinkumware 405 and later does supply wchar_t functions + inline const std::wstring & path_proxy( const std::wstring & file_ph, + std::ios_base::openmode ) + { return file_ph; } +# endif +# endif + + inline const std::string & path_proxy( const std::string & file_ph, + std::ios_base::openmode ) + { return file_ph; } + + } // namespace detail + + template < class charT, class traits = std::char_traits > + class basic_filebuf : public std::basic_filebuf + { + private: // disallow copying + basic_filebuf( const basic_filebuf & ); + const basic_filebuf & operator=( const basic_filebuf & ); + public: + basic_filebuf() {} + virtual ~basic_filebuf() {} + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + template + typename boost::enable_if, + basic_filebuf *>::type + open( const Path & file_ph, std::ios_base::openmode mode ); + + basic_filebuf * + open( const wpath & file_ph, std::ios_base::openmode mode ); +# endif + +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + basic_filebuf * + open( const path & file_ph, std::ios_base::openmode mode ); +# endif + }; + + template < class charT, class traits = std::char_traits > + class basic_ifstream : public std::basic_ifstream + { + private: // disallow copying + basic_ifstream( const basic_ifstream & ); + const basic_ifstream & operator=( const basic_ifstream & ); + public: + basic_ifstream() {} + + // use two signatures, rather than one signature with default second + // argument, to workaround VC++ 7.1 bug (ID VSWhidbey 38416) + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + template + explicit basic_ifstream( const Path & file_ph, + typename boost::enable_if >::type* dummy = 0 ); + + template + basic_ifstream( const Path & file_ph, std::ios_base::openmode mode, + typename boost::enable_if >::type* dummy = 0 ); + + template + typename boost::enable_if, void>::type + open( const Path & file_ph ); + + template + typename boost::enable_if, void>::type + open( const Path & file_ph, std::ios_base::openmode mode ); + + explicit basic_ifstream( const wpath & file_ph ); + basic_ifstream( const wpath & file_ph, std::ios_base::openmode mode ); + void open( const wpath & file_ph ); + void open( const wpath & file_ph, std::ios_base::openmode mode ); +# endif + + explicit basic_ifstream( const path & file_ph ); + basic_ifstream( const path & file_ph, std::ios_base::openmode mode ); +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + void open( const path & file_ph ); + void open( const path & file_ph, std::ios_base::openmode mode ); +# endif + virtual ~basic_ifstream() {} + }; + + template < class charT, class traits = std::char_traits > + class basic_ofstream : public std::basic_ofstream + { + private: // disallow copying + basic_ofstream( const basic_ofstream & ); + const basic_ofstream & operator=( const basic_ofstream & ); + public: + basic_ofstream() {} + + // use two signatures, rather than one signature with default second + // argument, to workaround VC++ 7.1 bug (ID VSWhidbey 38416) + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + template + explicit basic_ofstream( const Path & file_ph, + typename boost::enable_if >::type* dummy = 0 ); + explicit basic_ofstream( const wpath & file_ph ); + + template + basic_ofstream( const Path & file_ph, std::ios_base::openmode mode, + typename boost::enable_if >::type* dummy = 0 ); + basic_ofstream( const wpath & file_ph, std::ios_base::openmode mode ); + + template + typename boost::enable_if, void>::type + open( const Path & file_ph ); + void open( const wpath & file_ph ); + + template + typename boost::enable_if, void>::type + open( const Path & file_ph, std::ios_base::openmode mode ); + void open( const wpath & file_ph, std::ios_base::openmode mode ); + +# endif + + explicit basic_ofstream( const path & file_ph ); + basic_ofstream( const path & file_ph, std::ios_base::openmode mode ); +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + void open( const path & file_ph ); + void open( const path & file_ph, std::ios_base::openmode mode ); +# endif + virtual ~basic_ofstream() {} + }; + + template < class charT, class traits = std::char_traits > + class basic_fstream : public std::basic_fstream + { + private: // disallow copying + basic_fstream( const basic_fstream & ); + const basic_fstream & operator=( const basic_fstream & ); + public: + basic_fstream() {} + + // use two signatures, rather than one signature with default second + // argument, to workaround VC++ 7.1 bug (ID VSWhidbey 38416) + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + template + explicit basic_fstream( const Path & file_ph, + typename boost::enable_if >::type* dummy = 0 ); + explicit basic_fstream( const wpath & file_ph ); + + template + basic_fstream( const Path & file_ph, std::ios_base::openmode mode, + typename boost::enable_if >::type* dummy = 0 ); + basic_fstream( const wpath & file_ph, std::ios_base::openmode mode ); + + template + typename boost::enable_if, void>::type + open( const Path & file_ph ); + void open( const wpath & file_ph ); + + template + typename boost::enable_if, void>::type + open( const Path & file_ph, std::ios_base::openmode mode ); + void open( const wpath & file_ph, std::ios_base::openmode mode ); + +# endif + + explicit basic_fstream( const path & file_ph ); + basic_fstream( const path & file_ph, std::ios_base::openmode mode ); +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + void open( const path & file_ph ); + void open( const path & file_ph, std::ios_base::openmode mode ); +# endif + virtual ~basic_fstream() {} + + }; + + typedef basic_filebuf filebuf; + typedef basic_ifstream ifstream; + typedef basic_ofstream ofstream; + typedef basic_fstream fstream; + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + typedef basic_filebuf wfilebuf; + typedef basic_ifstream wifstream; + typedef basic_fstream wfstream; + typedef basic_ofstream wofstream; +# endif + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + +// basic_filebuf definitions -----------------------------------------------// + + template + template + typename boost::enable_if, + basic_filebuf *>::type + basic_filebuf::open( const Path & file_ph, + std::ios_base::openmode mode ) + { + return (std::basic_filebuf::open( detail::path_proxy( + file_ph.external_file_string(), mode ).c_str(), mode ) + == 0) ? 0 : this; + } + + template + basic_filebuf * + basic_filebuf::open( const wpath & file_ph, + std::ios_base::openmode mode ) + { + return this->BOOST_NESTED_TEMPLATE open( file_ph, mode ); + } + +// basic_ifstream definitions ----------------------------------------------// + + template template + basic_ifstream::basic_ifstream(const Path & file_ph, + typename boost::enable_if >::type* ) + : std::basic_ifstream( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in ).c_str(), std::ios_base::in ) {} + + template + basic_ifstream::basic_ifstream( const wpath & file_ph ) + : std::basic_ifstream( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in ).c_str(), std::ios_base::in ) {} + + template template + basic_ifstream::basic_ifstream( const Path & file_ph, + std::ios_base::openmode mode, + typename boost::enable_if >::type* ) + : std::basic_ifstream( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ) {} + + template + basic_ifstream::basic_ifstream( const wpath & file_ph, + std::ios_base::openmode mode ) + : std::basic_ifstream( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ) {} + + template template + typename boost::enable_if, void>::type + basic_ifstream::open( const Path & file_ph ) + { + std::basic_ifstream::open( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in ).c_str(), std::ios_base::in ); + } + + template + void basic_ifstream::open( const wpath & file_ph ) + { + std::basic_ifstream::open( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in ).c_str(), std::ios_base::in ); + } + + template template + typename boost::enable_if, void>::type + basic_ifstream::open( const Path & file_ph, + std::ios_base::openmode mode ) + { + std::basic_ifstream::open( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ); + } + + template + void basic_ifstream::open( const wpath & file_ph, + std::ios_base::openmode mode ) + { + std::basic_ifstream::open( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ); + } + +// basic_ofstream definitions ----------------------------------------------// + + template template + basic_ofstream::basic_ofstream(const Path & file_ph, + typename boost::enable_if >::type* ) + : std::basic_ofstream( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::out ).c_str(), std::ios_base::out ) {} + + template + basic_ofstream::basic_ofstream( const wpath & file_ph ) + : std::basic_ofstream( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::out ).c_str(), std::ios_base::out ) {} + + template template + basic_ofstream::basic_ofstream( const Path & file_ph, + std::ios_base::openmode mode, + typename boost::enable_if >::type* ) + : std::basic_ofstream( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ) {} + + template + basic_ofstream::basic_ofstream( const wpath & file_ph, + std::ios_base::openmode mode ) + : std::basic_ofstream( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ) {} + + template template + typename boost::enable_if, void>::type + basic_ofstream::open( const Path & file_ph ) + { + std::basic_ofstream::open( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::out ).c_str(), std::ios_base::out ); + } + + template + void basic_ofstream::open( const wpath & file_ph ) + { + std::basic_ofstream::open( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::out ).c_str(), std::ios_base::out ); + } + + template template + typename boost::enable_if, void>::type + basic_ofstream::open( const Path & file_ph, + std::ios_base::openmode mode ) + { + std::basic_ofstream::open( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ); + } + + template + void basic_ofstream::open( const wpath & file_ph, + std::ios_base::openmode mode ) + { + std::basic_ofstream::open( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ); + } + +// basic_fstream definitions -----------------------------------------------// + + template template + basic_fstream::basic_fstream(const Path & file_ph, + typename boost::enable_if >::type* ) + : std::basic_fstream( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in|std::ios_base::out ).c_str(), + std::ios_base::in|std::ios_base::out ) {} + + template + basic_fstream::basic_fstream( const wpath & file_ph ) + : std::basic_fstream( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in|std::ios_base::out ).c_str(), + std::ios_base::in|std::ios_base::out ) {} + + template template + basic_fstream::basic_fstream( const Path & file_ph, + std::ios_base::openmode mode, + typename boost::enable_if >::type* ) + : std::basic_fstream( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ) {} + + template + basic_fstream::basic_fstream( const wpath & file_ph, + std::ios_base::openmode mode ) + : std::basic_fstream( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ) {} + + template template + typename boost::enable_if, void>::type + basic_fstream::open( const Path & file_ph ) + { + std::basic_fstream::open( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in|std::ios_base::out ).c_str(), + std::ios_base::in|std::ios_base::out ); + } + + template + void basic_fstream::open( const wpath & file_ph ) + { + std::basic_fstream::open( + detail::path_proxy( file_ph.external_file_string(), + std::ios_base::in|std::ios_base::out ).c_str(), + std::ios_base::in|std::ios_base::out ); + } + + template template + typename boost::enable_if, void>::type + basic_fstream::open( const Path & file_ph, + std::ios_base::openmode mode ) + { + std::basic_fstream::open( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ); + } + + template + void basic_fstream::open( const wpath & file_ph, + std::ios_base::openmode mode ) + { + std::basic_fstream::open( + detail::path_proxy( file_ph.external_file_string(), + mode ).c_str(), mode ); + } + +# endif + +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + template + basic_filebuf * + basic_filebuf::open( const path & file_ph, + std::ios_base::openmode mode ) + { + return std::basic_filebuf::open( + file_ph.file_string().c_str(), mode ) == 0 ? 0 : this; + } +# endif + + template + basic_ifstream::basic_ifstream( const path & file_ph ) + : std::basic_ifstream( + file_ph.file_string().c_str(), std::ios_base::in ) {} + + template + basic_ifstream::basic_ifstream( const path & file_ph, + std::ios_base::openmode mode ) + : std::basic_ifstream( + file_ph.file_string().c_str(), mode ) {} + +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + template + void basic_ifstream::open( const path & file_ph ) + { + std::basic_ifstream::open( + file_ph.file_string().c_str(), std::ios_base::in ); + } + + template + void basic_ifstream::open( const path & file_ph, + std::ios_base::openmode mode ) + { + std::basic_ifstream::open( + file_ph.file_string().c_str(), mode ); + } +# endif + + template + basic_ofstream::basic_ofstream( const path & file_ph ) + : std::basic_ofstream( + file_ph.file_string().c_str(), std::ios_base::out ) {} + + template + basic_ofstream::basic_ofstream( const path & file_ph, + std::ios_base::openmode mode ) + : std::basic_ofstream( + file_ph.file_string().c_str(), mode ) {} + +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + template + void basic_ofstream::open( const path & file_ph ) + { + std::basic_ofstream::open( + file_ph.file_string().c_str(), std::ios_base::out ); + } + + template + void basic_ofstream::open( const path & file_ph, + std::ios_base::openmode mode ) + { + std::basic_ofstream::open( + file_ph.file_string().c_str(), mode ); + } +# endif + + template + basic_fstream::basic_fstream( const path & file_ph ) + : std::basic_fstream( + file_ph.file_string().c_str(), + std::ios_base::in|std::ios_base::out ) {} + + + template + basic_fstream::basic_fstream( const path & file_ph, + std::ios_base::openmode mode ) + : std::basic_fstream( + file_ph.file_string().c_str(), mode ) {} + +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1200 ) // VC++ 6.0 can't handle this + template + void basic_fstream::open( const path & file_ph ) + { + std::basic_fstream::open( + file_ph.file_string().c_str(), std::ios_base::in|std::ios_base::out ); + } + + template + void basic_fstream::open( const path & file_ph, + std::ios_base::openmode mode ) + { + std::basic_fstream::open( + file_ph.file_string().c_str(), mode ); + } +# endif + } // namespace filesystem2 +} // namespace boost + +//----------------------------------------------------------------------------// + +namespace boost +{ + namespace filesystem + { +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + using filesystem2::wfilebuf; + using filesystem2::wifstream; + using filesystem2::wfstream; + using filesystem2::wofstream; +# endif + using filesystem2::filebuf; + using filesystem2::ifstream; + using filesystem2::ofstream; + using filesystem2::fstream; + using filesystem2::basic_filebuf; + using filesystem2::basic_ifstream; + using filesystem2::basic_ofstream; + using filesystem2::basic_fstream; + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED +# endif + } +} + +//----------------------------------------------------------------------------// + +#include // pops abi_prefix.hpp pragmas +#endif // BOOST_FILESYSTEM2_FSTREAM_HPP diff --git a/utils/boost_idb/boost/filesystem/v2/operations.hpp b/utils/boost_idb/boost/filesystem/v2/operations.hpp new file mode 100644 index 00000000..c60046f0 --- /dev/null +++ b/utils/boost_idb/boost/filesystem/v2/operations.hpp @@ -0,0 +1,1244 @@ +// boost/filesystem/operations.hpp -----------------------------------------// + +// Copyright 2002-2005 Beman Dawes +// Copyright 2002 Jan Langer +// Copyright 2001 Dietmar Kuehl +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// See library home page at http://www.boost.org/libs/filesystem + +//----------------------------------------------------------------------------// + +#ifndef BOOST_FILESYSTEM2_OPERATIONS_HPP +#define BOOST_FILESYSTEM2_OPERATIONS_HPP + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include // for pair +#include + +#ifdef BOOST_WINDOWS_API +# include +# if !defined(_WIN32_WINNT) || _WIN32_WINNT >= 0x0500 +# define BOOST_FS_HARD_LINK // Default for Windows 2K or later +# endif +#endif + +#include // must be the last #include + +# ifdef BOOST_NO_STDC_NAMESPACE + namespace std { using ::time_t; } +# endif + +//----------------------------------------------------------------------------// + +namespace boost +{ + namespace filesystem2 + { + +// typedef boost::filesystem::path Path; needs to be in namespace boost::filesystem +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY +# define BOOST_FS_FUNC(BOOST_FS_TYPE) \ + template typename boost::enable_if, \ + BOOST_FS_TYPE>::type +# define BOOST_INLINE_FS_FUNC(BOOST_FS_TYPE) \ + template inline typename boost::enable_if, \ + BOOST_FS_TYPE>::type +# define BOOST_FS_TYPENAME typename +# else +# define BOOST_FS_FUNC(BOOST_FS_TYPE) inline BOOST_FS_TYPE +# define BOOST_INLINE_FS_FUNC(BOOST_FS_TYPE) inline BOOST_FS_TYPE + typedef boost::filesystem2::path Path; +# define BOOST_FS_TYPENAME +# endif + + template class basic_directory_iterator; + + // BOOST_FILESYSTEM2_NARROW_ONLY needs this: + typedef basic_directory_iterator directory_iterator; + + template class basic_directory_entry; + + enum file_type + { + status_unknown, + file_not_found, + regular_file, + directory_file, + // the following will never be reported by some operating or file systems + symlink_file, + block_file, + character_file, + fifo_file, + socket_file, + type_unknown // file does exist, but isn't one of the above types or + // we don't have strong enough permission to find its type + }; + + class file_status + { + public: + explicit file_status( file_type v = status_unknown ) : m_value(v) {} + + void type( file_type v ) { m_value = v; } + file_type type() const { return m_value; } + + private: + // the internal representation is unspecified so that additional state + // information such as permissions can be added in the future; this + // implementation just uses status_type as the internal representation + + file_type m_value; + }; + + inline bool status_known( file_status f ) { return f.type() != status_unknown; } + inline bool exists( file_status f ) { return f.type() != status_unknown && f.type() != file_not_found; } + inline bool is_regular_file(file_status f){ return f.type() == regular_file; } + inline bool is_directory( file_status f ) { return f.type() == directory_file; } + inline bool is_symlink( file_status f ) { return f.type() == symlink_file; } + inline bool is_other( file_status f ) { return exists(f) && !is_regular_file(f) && !is_directory(f) && !is_symlink(f); } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + inline bool is_regular( file_status f ) { return f.type() == regular_file; } +# endif + + struct space_info + { + // all values are byte counts + boost::uintmax_t capacity; + boost::uintmax_t free; // <= capacity + boost::uintmax_t available; // <= free + }; + + namespace detail + { + typedef std::pair< system::error_code, bool > + query_pair; + + typedef std::pair< system::error_code, boost::uintmax_t > + uintmax_pair; + + typedef std::pair< system::error_code, std::time_t > + time_pair; + + typedef std::pair< system::error_code, space_info > + space_pair; + + template< class Path > + struct directory_pair + { + typedef std::pair< system::error_code, + typename Path::external_string_type > type; + }; + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + BOOST_FILESYSTEM_DECL bool + symbolic_link_exists_api( const std::string & ); // deprecated +# endif + + BOOST_FILESYSTEM_DECL file_status + status_api( const std::string & ph, system::error_code & ec ); +# ifndef BOOST_WINDOWS_API + BOOST_FILESYSTEM_DECL file_status + symlink_status_api( const std::string & ph, system::error_code & ec ); +# endif + BOOST_FILESYSTEM_DECL query_pair + is_empty_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL query_pair + equivalent_api( const std::string & ph1, const std::string & ph2 ); + BOOST_FILESYSTEM_DECL uintmax_pair + file_size_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL space_pair + space_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL time_pair + last_write_time_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL system::error_code + last_write_time_api( const std::string & ph, std::time_t new_value ); + BOOST_FILESYSTEM_DECL system::error_code + get_current_path_api( std::string & ph ); + BOOST_FILESYSTEM_DECL system::error_code + set_current_path_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL query_pair + create_directory_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL system::error_code + create_hard_link_api( const std::string & to_ph, + const std::string & from_ph ); + BOOST_FILESYSTEM_DECL system::error_code + create_symlink_api( const std::string & to_ph, + const std::string & from_ph ); + BOOST_FILESYSTEM_DECL system::error_code + remove_api( const std::string & ph ); + BOOST_FILESYSTEM_DECL system::error_code + rename_api( const std::string & from, const std::string & to ); + BOOST_FILESYSTEM_DECL system::error_code + copy_file_api( const std::string & from, const std::string & to, bool fail_if_exists ); + +# if defined(BOOST_WINDOWS_API) + + BOOST_FILESYSTEM_DECL system::error_code + get_full_path_name_api( const std::string & ph, std::string & target ); + +# if !defined(BOOST_FILESYSTEM2_NARROW_ONLY) + + BOOST_FILESYSTEM_DECL boost::filesystem2::file_status + status_api( const std::wstring & ph, system::error_code & ec ); + BOOST_FILESYSTEM_DECL query_pair + is_empty_api( const std::wstring & ph ); + BOOST_FILESYSTEM_DECL query_pair + equivalent_api( const std::wstring & ph1, const std::wstring & ph2 ); + BOOST_FILESYSTEM_DECL uintmax_pair + file_size_api( const std::wstring & ph ); + BOOST_FILESYSTEM_DECL space_pair + space_api( const std::wstring & ph ); + BOOST_FILESYSTEM_DECL system::error_code + get_full_path_name_api( const std::wstring & ph, std::wstring & target ); + BOOST_FILESYSTEM_DECL time_pair + last_write_time_api( const std::wstring & ph ); + BOOST_FILESYSTEM_DECL system::error_code + last_write_time_api( const std::wstring & ph, std::time_t new_value ); + BOOST_FILESYSTEM_DECL system::error_code + get_current_path_api( std::wstring & ph ); + BOOST_FILESYSTEM_DECL system::error_code + set_current_path_api( const std::wstring & ph ); + BOOST_FILESYSTEM_DECL query_pair + create_directory_api( const std::wstring & ph ); +# ifdef BOOST_FS_HARD_LINK + BOOST_FILESYSTEM_DECL system::error_code + create_hard_link_api( const std::wstring & existing_ph, + const std::wstring & new_ph ); +# endif + BOOST_FILESYSTEM_DECL system::error_code + create_symlink_api( const std::wstring & to_ph, + const std::wstring & from_ph ); + BOOST_FILESYSTEM_DECL system::error_code + remove_api( const std::wstring & ph ); + BOOST_FILESYSTEM_DECL system::error_code + rename_api( const std::wstring & from, const std::wstring & to ); + BOOST_FILESYSTEM_DECL system::error_code + copy_file_api( const std::wstring & from, const std::wstring & to, bool fail_if_exists ); + +# endif +# endif + + template + bool remove_aux( const Path & ph, file_status f ); + + template + unsigned long remove_all_aux( const Path & ph, file_status f ); + + } // namespace detail + +// operations functions ----------------------------------------------------// + + // The non-template overloads enable automatic conversion from std and + // C-style strings. See basic_path constructors. The enable_if for the + // templates implements the famous "do-the-right-thing" rule. + +// query functions ---------------------------------------------------------// + + BOOST_INLINE_FS_FUNC(file_status) + status( const Path & ph, system::error_code & ec ) + { return detail::status_api( ph.external_file_string(), ec ); } + + BOOST_FS_FUNC(file_status) + status( const Path & ph ) + { + system::error_code ec; + file_status result( detail::status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::status", ph, ec ) ); + return result; + } + + BOOST_INLINE_FS_FUNC(file_status) + symlink_status( const Path & ph, system::error_code & ec ) +# ifdef BOOST_WINDOWS_API + { return detail::status_api( ph.external_file_string(), ec ); } +# else + { return detail::symlink_status_api( ph.external_file_string(), ec ); } +# endif + + BOOST_FS_FUNC(file_status) + symlink_status( const Path & ph ) + { + system::error_code ec; + file_status result( symlink_status( ph, ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::symlink_status", ph, ec ) ); + return result; + } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + inline bool symbolic_link_exists( const path & ph ) + { return is_symlink( symlink_status(ph) ); } +# endif + + BOOST_FS_FUNC(bool) exists( const Path & ph ) + { + system::error_code ec; + file_status result( detail::status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::exists", ph, ec ) ); + return exists( result ); + } + + BOOST_FS_FUNC(bool) is_directory( const Path & ph ) + { + system::error_code ec; + file_status result( detail::status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::is_directory", ph, ec ) ); + return is_directory( result ); + } + + BOOST_FS_FUNC(bool) is_regular_file( const Path & ph ) + { + system::error_code ec; + file_status result( detail::status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::is_regular_file", ph, ec ) ); + return is_regular_file( result ); + } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + BOOST_FS_FUNC(bool) is_regular( const Path & ph ) + { + system::error_code ec; + file_status result( detail::status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::is_regular", ph, ec ) ); + return is_regular( result ); + } +# endif + + BOOST_FS_FUNC(bool) is_other( const Path & ph ) + { + system::error_code ec; + file_status result( detail::status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::is_other", ph, ec ) ); + return is_other( result ); + } + + BOOST_FS_FUNC(bool) is_symlink( +# ifdef BOOST_WINDOWS_API + const Path & ) + { + return false; +# else + const Path & ph) + { + system::error_code ec; + file_status result( detail::symlink_status_api( ph.external_file_string(), ec ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::is_symlink", ph, ec ) ); + return is_symlink( result ); +# endif + } + + // VC++ 7.0 and earlier has a serious namespace bug that causes a clash + // between boost::filesystem2::is_empty and the unrelated type trait + // boost::is_empty. + +# if !defined( BOOST_MSVC ) || BOOST_MSVC > 1300 + BOOST_FS_FUNC(bool) is_empty( const Path & ph ) +# else + BOOST_FS_FUNC(bool) _is_empty( const Path & ph ) +# endif + { + detail::query_pair result( + detail::is_empty_api( ph.external_file_string() ) ); + if ( result.first ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::is_empty", ph, result.first ) ); + return result.second; + } + + BOOST_FS_FUNC(bool) equivalent( const Path & ph1, const Path & ph2 ) + { + detail::query_pair result( detail::equivalent_api( + ph1.external_file_string(), ph2.external_file_string() ) ); + if ( result.first ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::equivalent", ph1, ph2, result.first ) ); + return result.second; + } + + BOOST_FS_FUNC(boost::uintmax_t) file_size( const Path & ph ) + { + detail::uintmax_pair result + ( detail::file_size_api( ph.external_file_string() ) ); + if ( result.first ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::file_size", ph, result.first ) ); + return result.second; + } + + BOOST_FS_FUNC(space_info) space( const Path & ph ) + { + detail::space_pair result + ( detail::space_api( ph.external_file_string() ) ); + if ( result.first ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::space", ph, result.first ) ); + return result.second; + } + + BOOST_FS_FUNC(std::time_t) last_write_time( const Path & ph ) + { + detail::time_pair result + ( detail::last_write_time_api( ph.external_file_string() ) ); + if ( result.first ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::last_write_time", ph, result.first ) ); + return result.second; + } + + +// operations --------------------------------------------------------------// + + BOOST_FS_FUNC(bool) create_directory( const Path & dir_ph ) + { + detail::query_pair result( + detail::create_directory_api( dir_ph.external_directory_string() ) ); + if ( result.first ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::create_directory", + dir_ph, result.first ) ); + return result.second; + } + +#if !defined(BOOST_WINDOWS_API) || defined(BOOST_FS_HARD_LINK) + BOOST_FS_FUNC(void) + create_hard_link( const Path & to_ph, const Path & from_ph ) + { + system::error_code ec( + detail::create_hard_link_api( + to_ph.external_file_string(), + from_ph.external_file_string() ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::create_hard_link", + to_ph, from_ph, ec ) ); + } + + BOOST_FS_FUNC(system::error_code) + create_hard_link( const Path & to_ph, const Path & from_ph, + system::error_code & ec ) + { + ec = detail::create_hard_link_api( + to_ph.external_file_string(), + from_ph.external_file_string() ); + return ec; + } +#endif + + BOOST_FS_FUNC(void) + create_symlink( const Path & to_ph, const Path & from_ph ) + { + system::error_code ec( + detail::create_symlink_api( + to_ph.external_file_string(), + from_ph.external_file_string() ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::create_symlink", + to_ph, from_ph, ec ) ); + } + + BOOST_FS_FUNC(system::error_code) + create_symlink( const Path & to_ph, const Path & from_ph, + system::error_code & ec ) + { + ec = detail::create_symlink_api( + to_ph.external_file_string(), + from_ph.external_file_string() ); + return ec; + } + + BOOST_FS_FUNC(bool) remove( const Path & ph ) + { + system::error_code ec; + file_status f = symlink_status( ph, ec ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::remove", ph, ec ) ); + return detail::remove_aux( ph, f ); + } + + BOOST_FS_FUNC(unsigned long) remove_all( const Path & ph ) + { + system::error_code ec; + file_status f = symlink_status( ph, ec ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::remove_all", ph, ec ) ); + return exists( f ) ? detail::remove_all_aux( ph, f ) : 0; + } + + BOOST_FS_FUNC(void) rename( const Path & from_path, const Path & to_path ) + { + system::error_code ec( detail::rename_api( + from_path.external_directory_string(), + to_path.external_directory_string() ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::rename", + from_path, to_path, ec ) ); + } + + BOOST_SCOPED_ENUM_START(copy_option) + { fail_if_exists, overwrite_if_exists }; + BOOST_SCOPED_ENUM_END + + BOOST_FS_FUNC(void) copy_file( const Path & from_path, const Path & to_path, + BOOST_SCOPED_ENUM(copy_option) option = copy_option::fail_if_exists ) + { + system::error_code ec( detail::copy_file_api( + from_path.external_directory_string(), + to_path.external_directory_string(), option == copy_option::fail_if_exists ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::copy_file", + from_path, to_path, ec ) ); + } + + template< class Path > + Path current_path() + { + typename Path::external_string_type ph; + system::error_code ec( detail::get_current_path_api( ph ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::current_path", ec ) ); + return Path( Path::traits_type::to_internal( ph ) ); + } + + BOOST_FS_FUNC(void) current_path( const Path & ph ) + { + system::error_code ec( detail::set_current_path_api( + ph.external_directory_string() ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::current_path", ph, ec ) ); + } + + template< class Path > + const Path & initial_path() + { + static Path init_path; + if ( init_path.empty() ) init_path = current_path(); + return init_path; + } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + // legacy support + inline path current_path() // overload supports pre-i18n apps + { return current_path(); } + inline const path & initial_path() // overload supports pre-i18n apps + { return initial_path(); } +# endif + + BOOST_FS_FUNC(Path) system_complete( const Path & ph ) + { +# ifdef BOOST_WINDOWS_API + if ( ph.empty() ) return ph; + BOOST_FS_TYPENAME Path::external_string_type sys_ph; + system::error_code ec( detail::get_full_path_name_api( ph.external_file_string(), + sys_ph ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::system_complete", ph, ec ) ); + return Path( Path::traits_type::to_internal( sys_ph ) ); +# else + return (ph.empty() || ph.is_complete()) + ? ph : current_path() / ph; +# endif + } + + BOOST_FS_FUNC(Path) + complete( const Path & ph, + const Path & base/* = initial_path() */) + { + BOOST_ASSERT( base.is_complete() + && (ph.is_complete() || !ph.has_root_name()) + && "boost::filesystem::complete() precondition not met" ); +# ifdef BOOST_WINDOWS_PATH + if (ph.empty() || ph.is_complete()) return ph; + if ( !ph.has_root_name() ) + return ph.has_root_directory() + ? Path( base.root_name() ) / ph + : base / ph; + return base / ph; +# else + return (ph.empty() || ph.is_complete()) ? ph : base / ph; +# endif + } + + // VC++ 7.1 had trouble with default arguments, so separate one argument + // signatures are provided as workarounds; the effect is the same. + BOOST_FS_FUNC(Path) complete( const Path & ph ) + { return complete( ph, initial_path() ); } + + BOOST_FS_FUNC(void) + last_write_time( const Path & ph, const std::time_t new_time ) + { + system::error_code ec( detail::last_write_time_api( ph.external_file_string(), + new_time ) ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::last_write_time", ph, ec ) ); + } + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + // "do-the-right-thing" overloads ---------------------------------------// + + inline file_status status( const path & ph ) + { return status( ph ); } + inline file_status status( const wpath & ph ) + { return status( ph ); } + + inline file_status status( const path & ph, system::error_code & ec ) + { return status( ph, ec ); } + inline file_status status( const wpath & ph, system::error_code & ec ) + { return status( ph, ec ); } + + inline file_status symlink_status( const path & ph ) + { return symlink_status( ph ); } + inline file_status symlink_status( const wpath & ph ) + { return symlink_status( ph ); } + + inline file_status symlink_status( const path & ph, system::error_code & ec ) + { return symlink_status( ph, ec ); } + inline file_status symlink_status( const wpath & ph, system::error_code & ec ) + { return symlink_status( ph, ec ); } + + inline bool exists( const path & ph ) { return exists( ph ); } + inline bool exists( const wpath & ph ) { return exists( ph ); } + + inline bool is_directory( const path & ph ) + { return is_directory( ph ); } + inline bool is_directory( const wpath & ph ) + { return is_directory( ph ); } + + inline bool is_regular_file( const path & ph ) + { return is_regular_file( ph ); } + inline bool is_regular_file( const wpath & ph ) + { return is_regular_file( ph ); } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + inline bool is_regular( const path & ph ) + { return is_regular( ph ); } + inline bool is_regular( const wpath & ph ) + { return is_regular( ph ); } +# endif + + inline bool is_other( const path & ph ) + { return is_other( ph ); } + inline bool is_other( const wpath & ph ) + { return is_other( ph ); } + + inline bool is_symlink( const path & ph ) + { return is_symlink( ph ); } + inline bool is_symlink( const wpath & ph ) + { return is_symlink( ph ); } + + inline bool is_empty( const path & ph ) + { return boost::filesystem2::is_empty( ph ); } + inline bool is_empty( const wpath & ph ) + { return boost::filesystem2::is_empty( ph ); } + + inline bool equivalent( const path & ph1, const path & ph2 ) + { return equivalent( ph1, ph2 ); } + inline bool equivalent( const wpath & ph1, const wpath & ph2 ) + { return equivalent( ph1, ph2 ); } + + inline boost::uintmax_t file_size( const path & ph ) + { return file_size( ph ); } + inline boost::uintmax_t file_size( const wpath & ph ) + { return file_size( ph ); } + + inline space_info space( const path & ph ) + { return space( ph ); } + inline space_info space( const wpath & ph ) + { return space( ph ); } + + inline std::time_t last_write_time( const path & ph ) + { return last_write_time( ph ); } + inline std::time_t last_write_time( const wpath & ph ) + { return last_write_time( ph ); } + + inline bool create_directory( const path & dir_ph ) + { return create_directory( dir_ph ); } + inline bool create_directory( const wpath & dir_ph ) + { return create_directory( dir_ph ); } + +#if !defined(BOOST_WINDOWS_API) || defined(BOOST_FS_HARD_LINK) + inline void create_hard_link( const path & to_ph, + const path & from_ph ) + { return create_hard_link( to_ph, from_ph ); } + inline void create_hard_link( const wpath & to_ph, + const wpath & from_ph ) + { return create_hard_link( to_ph, from_ph ); } + + inline system::error_code create_hard_link( const path & to_ph, + const path & from_ph, system::error_code & ec ) + { return create_hard_link( to_ph, from_ph, ec ); } + inline system::error_code create_hard_link( const wpath & to_ph, + const wpath & from_ph, system::error_code & ec ) + { return create_hard_link( to_ph, from_ph, ec ); } +#endif + + inline void create_symlink( const path & to_ph, + const path & from_ph ) + { return create_symlink( to_ph, from_ph ); } + inline void create_symlink( const wpath & to_ph, + const wpath & from_ph ) + { return create_symlink( to_ph, from_ph ); } + + inline system::error_code create_symlink( const path & to_ph, + const path & from_ph, system::error_code & ec ) + { return create_symlink( to_ph, from_ph, ec ); } + inline system::error_code create_symlink( const wpath & to_ph, + const wpath & from_ph, system::error_code & ec ) + { return create_symlink( to_ph, from_ph, ec ); } + + inline bool remove( const path & ph ) + { return remove( ph ); } + inline bool remove( const wpath & ph ) + { return remove( ph ); } + + inline unsigned long remove_all( const path & ph ) + { return remove_all( ph ); } + inline unsigned long remove_all( const wpath & ph ) + { return remove_all( ph ); } + + inline void rename( const path & from_path, const path & to_path ) + { return rename( from_path, to_path ); } + inline void rename( const wpath & from_path, const wpath & to_path ) + { return rename( from_path, to_path ); } + + inline void copy_file( const path & from_path, const path & to_path ) + { return copy_file( from_path, to_path ); } + inline void copy_file( const wpath & from_path, const wpath & to_path ) + { return copy_file( from_path, to_path ); } + + inline path system_complete( const path & ph ) + { return system_complete( ph ); } + inline wpath system_complete( const wpath & ph ) + { return system_complete( ph ); } + + inline path complete( const path & ph, + const path & base/* = initial_path()*/ ) + { return complete( ph, base ); } + inline wpath complete( const wpath & ph, + const wpath & base/* = initial_path()*/ ) + { return complete( ph, base ); } + + inline path complete( const path & ph ) + { return complete( ph, initial_path() ); } + inline wpath complete( const wpath & ph ) + { return complete( ph, initial_path() ); } + + inline void last_write_time( const path & ph, const std::time_t new_time ) + { last_write_time( ph, new_time ); } + inline void last_write_time( const wpath & ph, const std::time_t new_time ) + { last_write_time( ph, new_time ); } + + inline void current_path( const path & ph ) + { current_path( ph ); } + inline void current_path( const wpath & ph ) + { current_path( ph ); } + +# endif // ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + namespace detail + { + template + bool remove_aux( const Path & ph, file_status f ) + { + if ( exists( f ) ) + { + system::error_code ec = remove_api( ph.external_file_string() ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::remove", ph, ec ) ); + return true; + } + return false; + } + + template + unsigned long remove_all_aux( const Path & ph, file_status f ) + { + static const boost::filesystem2::basic_directory_iterator end_itr; + unsigned long count = 1; + if ( !boost::filesystem2::is_symlink( f ) // don't recurse symbolic links + && boost::filesystem2::is_directory( f ) ) + { + for ( boost::filesystem2::basic_directory_iterator itr( ph ); + itr != end_itr; ++itr ) + { + boost::system::error_code ec; + boost::filesystem2::file_status fn = boost::filesystem2::symlink_status( itr->path(), ec ); + if ( ec ) + boost::throw_exception( basic_filesystem_error( + "boost::filesystem:remove_all", ph, ec ) ); + count += remove_all_aux( itr->path(), fn ); + } + } + remove_aux( ph, f ); + return count; + } + +// test helper -------------------------------------------------------------// + + // not part of the documented interface because false positives are possible; + // there is no law that says that an OS that has large stat.st_size + // actually supports large file sizes. + BOOST_FILESYSTEM_DECL bool possible_large_file_size_support(); + +// directory_iterator helpers ----------------------------------------------// + +// forwarding functions avoid need for BOOST_FILESYSTEM_DECL for class +// basic_directory_iterator, and so avoid iterator_facade DLL template +// problems. They also overload to the proper external path character type. + + BOOST_FILESYSTEM_DECL system::error_code + dir_itr_first( void *& handle, +#if defined(BOOST_POSIX_API) + void *& buffer, +#endif + const std::string & dir_path, + std::string & target, file_status & fs, file_status & symlink_fs ); + // eof: return==0 && handle==0 + + BOOST_FILESYSTEM_DECL system::error_code + dir_itr_increment( void *& handle, +#if defined(BOOST_POSIX_API) + void *& buffer, +#endif + std::string & target, file_status & fs, file_status & symlink_fs ); + // eof: return==0 && handle==0 + + BOOST_FILESYSTEM_DECL system::error_code + dir_itr_close( void *& handle +#if defined(BOOST_POSIX_API) + , void *& buffer +#endif + ); + // Effects: none if handle==0, otherwise close handle, set handle=0 + +# if defined(BOOST_WINDOWS_API) && !defined(BOOST_FILESYSTEM2_NARROW_ONLY) + BOOST_FILESYSTEM_DECL system::error_code + dir_itr_first( void *& handle, const std::wstring & ph, + std::wstring & target, file_status & fs, file_status & symlink_fs ); + BOOST_FILESYSTEM_DECL system::error_code + dir_itr_increment( void *& handle, std::wstring & target, + file_status & fs, file_status & symlink_fs ); +# endif + + template< class Path > + class dir_itr_imp + { + public: + basic_directory_entry m_directory_entry; + void * m_handle; +# ifdef BOOST_POSIX_API + void * m_buffer; // see dir_itr_increment implementation +# endif + dir_itr_imp() : m_handle(0) +# ifdef BOOST_POSIX_API + , m_buffer(0) +# endif + {} + + ~dir_itr_imp() { dir_itr_close( m_handle +#if defined(BOOST_POSIX_API) + , m_buffer +#endif + ); } + }; + + BOOST_FILESYSTEM_DECL system::error_code not_found_error(); + + } // namespace detail + +// basic_directory_iterator ------------------------------------------------// + + template< class Path > + class basic_directory_iterator + : public boost::iterator_facade< + basic_directory_iterator, + basic_directory_entry, + boost::single_pass_traversal_tag > + { + public: + typedef Path path_type; + + basic_directory_iterator(){} // creates the "end" iterator + + explicit basic_directory_iterator( const Path & dir_path ); + basic_directory_iterator( const Path & dir_path, system::error_code & ec ); + + private: + + // shared_ptr provides shallow-copy semantics required for InputIterators. + // m_imp.get()==0 indicates the end iterator. + boost::shared_ptr< detail::dir_itr_imp< Path > > m_imp; + + friend class boost::iterator_core_access; + + typename boost::iterator_facade< + basic_directory_iterator, + basic_directory_entry, + boost::single_pass_traversal_tag >::reference dereference() const + { + BOOST_ASSERT( m_imp.get() && "attempt to dereference end iterator" ); + return m_imp->m_directory_entry; + } + + void increment(); + + bool equal( const basic_directory_iterator & rhs ) const + { return m_imp == rhs.m_imp; } + + system::error_code m_init( const Path & dir_path ); + }; + + typedef basic_directory_iterator< path > directory_iterator; +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + typedef basic_directory_iterator< wpath > wdirectory_iterator; +# endif + + // basic_directory_iterator implementation ---------------------------// + + template + system::error_code basic_directory_iterator::m_init( + const Path & dir_path ) + { + if ( dir_path.empty() ) + { + m_imp.reset(); + return detail::not_found_error(); + } + typename Path::external_string_type name; + file_status fs, symlink_fs; + system::error_code ec( detail::dir_itr_first( m_imp->m_handle, +#if defined(BOOST_POSIX_API) + m_imp->m_buffer, +#endif + dir_path.external_directory_string(), + name, fs, symlink_fs ) ); + + if ( ec ) + { + m_imp.reset(); + return ec; + } + + if ( m_imp->m_handle == 0 ) m_imp.reset(); // eof, so make end iterator + else // not eof + { + m_imp->m_directory_entry.assign( dir_path + / Path::traits_type::to_internal( name ), fs, symlink_fs ); + if ( name[0] == dot::value // dot or dot-dot + && (name.size() == 1 + || (name[1] == dot::value + && name.size() == 2)) ) + { increment(); } + } + return boost::system::error_code(); + } + + template + basic_directory_iterator::basic_directory_iterator( + const Path & dir_path ) + : m_imp( new detail::dir_itr_imp ) + { + system::error_code ec( m_init(dir_path) ); + if ( ec ) + { + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::basic_directory_iterator constructor", + dir_path, ec ) ); + } + } + + template + basic_directory_iterator::basic_directory_iterator( + const Path & dir_path, system::error_code & ec ) + : m_imp( new detail::dir_itr_imp ) + { + ec = m_init(dir_path); + } + + template + void basic_directory_iterator::increment() + { + BOOST_ASSERT( m_imp.get() && "attempt to increment end iterator" ); + BOOST_ASSERT( m_imp->m_handle != 0 && "internal program error" ); + + typename Path::external_string_type name; + file_status fs, symlink_fs; + system::error_code ec; + + for (;;) + { + ec = detail::dir_itr_increment( m_imp->m_handle, +#if defined(BOOST_POSIX_API) + m_imp->m_buffer, +#endif + name, fs, symlink_fs ); + if ( ec ) + { + boost::throw_exception( basic_filesystem_error( + "boost::filesystem::basic_directory_iterator increment", + m_imp->m_directory_entry.path().parent_path(), ec ) ); + } + if ( m_imp->m_handle == 0 ) { m_imp.reset(); return; } // eof, make end + if ( !(name[0] == dot::value // !(dot or dot-dot) + && (name.size() == 1 + || (name[1] == dot::value + && name.size() == 2))) ) + { + m_imp->m_directory_entry.replace_filename( + Path::traits_type::to_internal( name ), fs, symlink_fs ); + return; + } + } + } + + // basic_directory_entry -----------------------------------------------// + + template + class basic_directory_entry + { + public: + typedef Path path_type; + typedef typename Path::string_type string_type; + + // compiler generated copy-ctor, copy assignment, and destructor apply + + basic_directory_entry() {} + explicit basic_directory_entry( const path_type & p, + file_status st = file_status(), file_status symlink_st=file_status() ) + : m_path(p), m_status(st), m_symlink_status(symlink_st) + {} + + void assign( const path_type & p, + file_status st, file_status symlink_st ) + { m_path = p; m_status = st; m_symlink_status = symlink_st; } + + void replace_filename( const string_type & s, + file_status st, file_status symlink_st ) + { + m_path.remove_filename(); + m_path /= s; + m_status = st; + m_symlink_status = symlink_st; + } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + void replace_leaf( const string_type & s, + file_status st, file_status symlink_st ) + { replace_filename( s, st, symlink_st ); } +# endif + + const Path & path() const { return m_path; } + file_status status() const; + file_status status( system::error_code & ec ) const; + file_status symlink_status() const; + file_status symlink_status( system::error_code & ec ) const; + + // conversion simplifies the most common use of basic_directory_entry + operator const path_type &() const { return m_path; } + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + // deprecated functions preserve common use cases in legacy code + typename Path::string_type filename() const + { + return path().filename(); + } + typename Path::string_type leaf() const + { + return path().filename(); + } + typename Path::string_type string() const + { + return path().string(); + } +# endif + + private: + path_type m_path; + mutable file_status m_status; // stat()-like + mutable file_status m_symlink_status; // lstat()-like + // note: m_symlink_status is not used by Windows implementation + + }; // basic_directory_status + + typedef basic_directory_entry directory_entry; +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + typedef basic_directory_entry wdirectory_entry; +# endif + + // basic_directory_entry implementation --------------------------------// + + template + file_status + basic_directory_entry::status() const + { + if ( !status_known( m_status ) ) + { +# ifndef BOOST_WINDOWS_API + if ( status_known( m_symlink_status ) + && !is_symlink( m_symlink_status ) ) + { m_status = m_symlink_status; } + else { m_status = boost::filesystem2::status( m_path ); } +# else + m_status = boost::filesystem2::status( m_path ); +# endif + } + return m_status; + } + + template + file_status + basic_directory_entry::status( system::error_code & ec ) const + { + if ( !status_known( m_status ) ) + { +# ifndef BOOST_WINDOWS_API + if ( status_known( m_symlink_status ) + && !is_symlink( m_symlink_status ) ) + { ec = boost::system::error_code();; m_status = m_symlink_status; } + else { m_status = boost::filesystem2::status( m_path, ec ); } +# else + m_status = boost::filesystem2::status( m_path, ec ); +# endif + } + else ec = boost::system::error_code();; + return m_status; + } + + template + file_status + basic_directory_entry::symlink_status() const + { +# ifndef BOOST_WINDOWS_API + if ( !status_known( m_symlink_status ) ) + { m_symlink_status = boost::filesystem2::symlink_status( m_path ); } + return m_symlink_status; +# else + return status(); +# endif + } + + template + file_status + basic_directory_entry::symlink_status( system::error_code & ec ) const + { +# ifndef BOOST_WINDOWS_API + if ( !status_known( m_symlink_status ) ) + { m_symlink_status = boost::filesystem2::symlink_status( m_path, ec ); } + else ec = boost::system::error_code();; + return m_symlink_status; +# else + return status( ec ); +# endif + } + } // namespace filesystem2 +} // namespace boost + +#undef BOOST_FS_FUNC + +//----------------------------------------------------------------------------// + +namespace boost +{ + namespace filesystem + { + using filesystem2::basic_directory_entry; + using filesystem2::basic_directory_iterator; + using filesystem2::block_file; + using filesystem2::character_file; + using filesystem2::complete; + using filesystem2::copy_file; + using filesystem2::copy_option; + using filesystem2::create_directory; +# if !defined(BOOST_WINDOWS_API) || defined(BOOST_FS_HARD_LINK) + using filesystem2::create_hard_link; +# endif + using filesystem2::create_symlink; + using filesystem2::current_path; + using filesystem2::directory_entry; + using filesystem2::directory_file; + using filesystem2::directory_iterator; + using filesystem2::equivalent; + using filesystem2::exists; + using filesystem2::fifo_file; + using filesystem2::file_not_found; + using filesystem2::file_size; + using filesystem2::file_status; + using filesystem2::file_type; + using filesystem2::initial_path; + using filesystem2::is_directory; + using filesystem2::is_directory; + using filesystem2::is_empty; + using filesystem2::is_other; + using filesystem2::is_regular_file; + using filesystem2::is_symlink; + using filesystem2::last_write_time; + using filesystem2::regular_file; + using filesystem2::remove; + using filesystem2::remove_all; + using filesystem2::rename; + using filesystem2::socket_file; + using filesystem2::space; + using filesystem2::space_info; + using filesystem2::status; + using filesystem2::status_known; + using filesystem2::symlink_file; + using filesystem2::symlink_status; + using filesystem2::system_complete; + using filesystem2::type_unknown; +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + using filesystem2::is_regular; + using filesystem2::symbolic_link_exists; +# endif +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + using filesystem2::wdirectory_iterator; + using filesystem2::wdirectory_entry; +# endif + namespace detail + { + using filesystem2::detail::not_found_error; + using filesystem2::detail::possible_large_file_size_support; + } + } +} + +#include // pops abi_prefix.hpp pragmas +#endif // BOOST_FILESYSTEM2_OPERATIONS_HPP diff --git a/utils/boost_idb/boost/filesystem/v2/path.hpp b/utils/boost_idb/boost/filesystem/v2/path.hpp new file mode 100644 index 00000000..16d67ca7 --- /dev/null +++ b/utils/boost_idb/boost/filesystem/v2/path.hpp @@ -0,0 +1,1572 @@ +// boost/filesystem/path.hpp -----------------------------------------------// + +// Copyright Beman Dawes 2002-2005 +// Copyright Vladimir Prus 2002 + +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// See library home page at http://www.boost.org/libs/filesystem + +// basic_path's stem(), extension(), and replace_extension() are based on +// basename(), extension(), and change_extension() from the original +// filesystem/convenience.hpp header by Vladimir Prus. + +//----------------------------------------------------------------------------// + +#ifndef BOOST_FILESYSTEM2_PATH_HPP +#define BOOST_FILESYSTEM2_PATH_HPP + +#include +#include +#include +#include +#include +#include +#include + +#include +#include // for lexicographical_compare +#include // needed by basic_path inserter and extractor +#include +#include + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY +# include +# endif + +#include // must be the last #include + +namespace boost +{ + namespace BOOST_FILESYSTEM2_NAMESPACE + { + template class basic_path; + + struct path_traits; + typedef basic_path< std::string, path_traits > path; + + struct path_traits + { + typedef std::string internal_string_type; + typedef std::string external_string_type; + static external_string_type to_external( const path &, + const internal_string_type & src ) { return src; } + static internal_string_type to_internal( + const external_string_type & src ) { return src; } + }; + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + struct BOOST_FILESYSTEM_DECL wpath_traits; + + typedef basic_path< std::wstring, wpath_traits > wpath; + + struct BOOST_FILESYSTEM_DECL wpath_traits + { + typedef std::wstring internal_string_type; +# ifdef BOOST_WINDOWS_API + typedef std::wstring external_string_type; + static external_string_type to_external( const wpath &, + const internal_string_type & src ) { return src; } + static internal_string_type to_internal( + const external_string_type & src ) { return src; } +# else + typedef std::string external_string_type; + static external_string_type to_external( const wpath & ph, + const internal_string_type & src ); + static internal_string_type to_internal( + const external_string_type & src ); +# endif + static void imbue( const std::locale & loc ); + static bool imbue( const std::locale & loc, const std::nothrow_t & ); + }; + +# endif // ifndef BOOST_FILESYSTEM2_NARROW_ONLY + + // path traits ---------------------------------------------------------// + + template struct is_basic_path + { BOOST_STATIC_CONSTANT( bool, value = false ); }; + template<> struct is_basic_path + { BOOST_STATIC_CONSTANT( bool, value = true ); }; +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + template<> struct is_basic_path + { BOOST_STATIC_CONSTANT( bool, value = true ); }; +# endif + + // These only have to be specialized if Path::string_type::value_type + // is not convertible from char, although specializations may eliminate + // compiler warnings. See ticket 2543. + template struct slash + { BOOST_STATIC_CONSTANT( char, value = '/' ); }; + + template struct dot + { BOOST_STATIC_CONSTANT( char, value = '.' ); }; + + template struct colon + { BOOST_STATIC_CONSTANT( char, value = ':' ); }; + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + template<> struct slash + { BOOST_STATIC_CONSTANT( wchar_t, value = L'/' ); }; + template<> struct dot + { BOOST_STATIC_CONSTANT( wchar_t, value = L'.' ); }; + template<> struct colon + { BOOST_STATIC_CONSTANT( wchar_t, value = L':' ); }; +# endif + +# ifdef BOOST_WINDOWS_PATH + template struct path_alt_separator + { BOOST_STATIC_CONSTANT( char, value = '\\' ); }; +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + template<> struct path_alt_separator + { BOOST_STATIC_CONSTANT( wchar_t, value = L'\\' ); }; +# endif +# endif + + // workaround for VC++ 7.0 and earlier issues with nested classes + namespace detail + { + template + class iterator_helper + { + public: + typedef typename Path::iterator iterator; + static void do_increment( iterator & ph ); + static void do_decrement( iterator & ph ); + }; + } + + // basic_path ----------------------------------------------------------// + + template + class basic_path + { + // invariant: m_path valid according to the portable generic path grammar + + // validate template arguments +// TODO: get these working +// BOOST_STATIC_ASSERT( ::boost::is_same::value ); +// BOOST_STATIC_ASSERT( ::boost::is_same::value || ::boost::is_same::value ); + + public: + // compiler generates copy constructor and copy assignment + + typedef basic_path path_type; + typedef String string_type; + typedef typename String::value_type value_type; + typedef Traits traits_type; + typedef typename Traits::external_string_type external_string_type; + + // constructors/destructor + basic_path() {} + basic_path( const string_type & s ) { operator/=( s ); } + basic_path( const value_type * s ) { operator/=( s ); } +# ifndef BOOST_NO_MEMBER_TEMPLATES + template + basic_path( InputIterator first, InputIterator last ) + { append( first, last ); } +# endif + ~basic_path() {} + + // assignments + basic_path & operator=( const string_type & s ) + { +# if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, >= 310) + m_path.clear(); +# else + m_path.erase( m_path.begin(), m_path.end() ); +# endif + operator/=( s ); + return *this; + } + basic_path & operator=( const value_type * s ) + { +# if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, >= 310) + m_path.clear(); +# else + m_path.erase( m_path.begin(), m_path.end() ); +# endif + operator/=( s ); + return *this; + } +# ifndef BOOST_NO_MEMBER_TEMPLATES + template + basic_path & assign( InputIterator first, InputIterator last ) + { m_path.clear(); append( first, last ); return *this; } +# endif + + // modifiers + basic_path & operator/=( const basic_path & rhs ) { return operator /=( rhs.string().c_str() ); } + basic_path & operator/=( const string_type & rhs ) { return operator /=( rhs.c_str() ); } + basic_path & operator/=( const value_type * s ); +# ifndef BOOST_NO_MEMBER_TEMPLATES + template + basic_path & append( InputIterator first, InputIterator last ); +# endif + + void clear() + { +# if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, >= 310) + m_path.clear(); +# else + m_path.erase( m_path.begin(), m_path.end() ); +# endif + } + + void swap( basic_path & rhs ) + { + m_path.swap( rhs.m_path ); +# ifdef BOOST_CYGWIN_PATH + std::swap( m_cygwin_root, rhs.m_cygwin_root ); +# endif + } + + basic_path & remove_filename(); + basic_path & replace_extension( const string_type & new_extension = string_type() ); + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + basic_path & remove_leaf() { return remove_filename(); } +# endif + + // observers + const string_type & string() const { return m_path; } + const string_type file_string() const; + const string_type directory_string() const { return file_string(); } + + const external_string_type external_file_string() const { return Traits::to_external( *this, file_string() ); } + const external_string_type external_directory_string() const { return Traits::to_external( *this, directory_string() ); } + + basic_path root_path() const; + string_type root_name() const; + string_type root_directory() const; + basic_path relative_path() const; + basic_path parent_path() const; + string_type filename() const; + string_type stem() const; + string_type extension() const; + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + string_type leaf() const { return filename(); } + basic_path branch_path() const { return parent_path(); } + bool has_leaf() const { return !m_path.empty(); } + bool has_branch_path() const { return !parent_path().empty(); } +# endif + + bool empty() const { return m_path.empty(); } // name consistent with std containers + bool is_complete() const; + bool has_root_path() const; + bool has_root_name() const; + bool has_root_directory() const; + bool has_relative_path() const { return !relative_path().empty(); } + bool has_filename() const { return !m_path.empty(); } + bool has_parent_path() const { return !parent_path().empty(); } + + // iterators + class iterator : public boost::iterator_facade< + iterator, + string_type const, + boost::bidirectional_traversal_tag > + { + private: + friend class boost::iterator_core_access; + friend class boost::BOOST_FILESYSTEM2_NAMESPACE::basic_path; + + const string_type & dereference() const + { return m_name; } + bool equal( const iterator & rhs ) const + { return m_path_ptr == rhs.m_path_ptr && m_pos == rhs.m_pos; } + + friend class boost::BOOST_FILESYSTEM2_NAMESPACE::detail::iterator_helper; + + void increment() + { + boost::BOOST_FILESYSTEM2_NAMESPACE::detail::iterator_helper::do_increment( + *this ); + } + void decrement() + { + boost::BOOST_FILESYSTEM2_NAMESPACE::detail::iterator_helper::do_decrement( + *this ); + } + + string_type m_name; // current element + const basic_path * m_path_ptr; // path being iterated over + typename string_type::size_type m_pos; // position of name in + // path_ptr->string(). The + // end() iterator is indicated by + // pos == path_ptr->m_path.size() + }; // iterator + + typedef iterator const_iterator; + + iterator begin() const; + iterator end() const; + + private: + // Note: This is an implementation for POSIX and Windows, where there + // are only minor differences between generic and native path grammars. + // Private members might be quite different in other implementations, + // particularly where there were wide differences between portable and + // native path formats, or between file_string() and + // directory_string() formats, or simply that the implementation + // was willing expend additional memory to achieve greater speed for + // some operations at the expense of other operations. + + string_type m_path; // invariant: portable path grammar + // on Windows, backslashes converted to slashes + +# ifdef BOOST_CYGWIN_PATH + bool m_cygwin_root; // if present, m_path[0] was slash. note: initialization + // done by append +# endif + + void m_append_separator_if_needed(); + void m_append( value_type value ); // converts Windows alt_separator + + // Was qualified; como433beta8 reports: + // warning #427-D: qualified name is not allowed in member declaration + friend class iterator; + friend class boost::BOOST_FILESYSTEM2_NAMESPACE::detail::iterator_helper; + + // Deprecated features ease transition for existing code. Don't use these + // in new code. +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + public: + typedef bool (*name_check)( const std::string & name ); + basic_path( const string_type & str, name_check ) { operator/=( str ); } + basic_path( const typename string_type::value_type * s, name_check ) + { operator/=( s );} + string_type native_file_string() const { return file_string(); } + string_type native_directory_string() const { return directory_string(); } + static bool default_name_check_writable() { return false; } + static void default_name_check( name_check ) {} + static name_check default_name_check() { return 0; } + basic_path & canonize(); + basic_path & normalize(); +# endif + }; + + // basic_path non-member functions ---------------------------------------// + + template< class String, class Traits > + inline void swap( basic_path & lhs, + basic_path & rhs ) { lhs.swap( rhs ); } + + template< class String, class Traits > + bool operator<( const basic_path & lhs, const basic_path & rhs ) + { + return std::lexicographical_compare( + lhs.begin(), lhs.end(), rhs.begin(), rhs.end() ); + } + + template< class String, class Traits > + bool operator<( const typename basic_path::string_type::value_type * lhs, + const basic_path & rhs ) + { + basic_path tmp( lhs ); + return std::lexicographical_compare( + tmp.begin(), tmp.end(), rhs.begin(), rhs.end() ); + } + + template< class String, class Traits > + bool operator<( const typename basic_path::string_type & lhs, + const basic_path & rhs ) + { + basic_path tmp( lhs ); + return std::lexicographical_compare( + tmp.begin(), tmp.end(), rhs.begin(), rhs.end() ); + } + + template< class String, class Traits > + bool operator<( const basic_path & lhs, + const typename basic_path::string_type::value_type * rhs ) + { + basic_path tmp( rhs ); + return std::lexicographical_compare( + lhs.begin(), lhs.end(), tmp.begin(), tmp.end() ); + } + + template< class String, class Traits > + bool operator<( const basic_path & lhs, + const typename basic_path::string_type & rhs ) + { + basic_path tmp( rhs ); + return std::lexicographical_compare( + lhs.begin(), lhs.end(), tmp.begin(), tmp.end() ); + } + + // operator == uses hand-written compare rather than !(lhs < rhs) && !(rhs < lhs) + // because the result is the same yet the direct compare is much more efficient + // than lexicographical_compare, which would also be called twice. + + template< class String, class Traits > + inline bool operator==( const basic_path & lhs, + const typename basic_path::string_type::value_type * rhs ) + { + typedef typename + boost::BOOST_FILESYSTEM2_NAMESPACE::basic_path path_type; + const typename path_type::string_type::value_type * l (lhs.string().c_str()); + while ( (*l == *rhs +# ifdef BOOST_WINDOWS_PATH + || (*l == path_alt_separator::value && *rhs == slash::value) + || (*l == slash::value && *rhs == path_alt_separator::value) +# endif + ) && *l ) { ++l; ++rhs; } + return *l == *rhs +# ifdef BOOST_WINDOWS_PATH + || (*l == path_alt_separator::value && *rhs == slash::value) + || (*l == slash::value && *rhs == path_alt_separator::value) +# endif + ; + } + + template< class String, class Traits > + inline bool operator==( const basic_path & lhs, + const basic_path & rhs ) + { + return lhs == rhs.string().c_str(); + } + + template< class String, class Traits > + inline bool operator==( const typename basic_path::string_type::value_type * lhs, + const basic_path & rhs ) + { + return rhs == lhs; + } + + template< class String, class Traits > + inline bool operator==( const typename basic_path::string_type & lhs, + const basic_path & rhs ) + { + return rhs == lhs.c_str(); + } + + template< class String, class Traits > + inline bool operator==( const basic_path & lhs, + const typename basic_path::string_type & rhs ) + { + return lhs == rhs.c_str(); + } + + template< class String, class Traits > + inline bool operator!=( const basic_path & lhs, + const basic_path & rhs ) + { return !(lhs == rhs); } + + template< class String, class Traits > + inline bool operator!=( const typename basic_path::string_type::value_type * lhs, + const basic_path & rhs ) + { return !(lhs == rhs); } + + template< class String, class Traits > + inline bool operator!=( const typename basic_path::string_type & lhs, + const basic_path & rhs ) + { return !(lhs == rhs); } + + template< class String, class Traits > + inline bool operator!=( const basic_path & lhs, + const typename basic_path::string_type::value_type * rhs ) + { return !(lhs == rhs); } + + template< class String, class Traits > + inline bool operator!=( const basic_path & lhs, + const typename basic_path::string_type & rhs ) + { return !(lhs == rhs); } + + template< class String, class Traits > + inline bool operator>( const basic_path & lhs, const basic_path & rhs ) { return rhs < lhs; } + + template< class String, class Traits > + inline bool operator>( const typename basic_path::string_type::value_type * lhs, + const basic_path & rhs ) { return rhs < basic_path(lhs); } + + template< class String, class Traits > + inline bool operator>( const typename basic_path::string_type & lhs, + const basic_path & rhs ) { return rhs < basic_path(lhs); } + + template< class String, class Traits > + inline bool operator>( const basic_path & lhs, + const typename basic_path::string_type::value_type * rhs ) + { return basic_path(rhs) < lhs; } + + template< class String, class Traits > + inline bool operator>( const basic_path & lhs, + const typename basic_path::string_type & rhs ) + { return basic_path(rhs) < lhs; } + + template< class String, class Traits > + inline bool operator<=( const basic_path & lhs, const basic_path & rhs ) { return !(rhs < lhs); } + + template< class String, class Traits > + inline bool operator<=( const typename basic_path::string_type::value_type * lhs, + const basic_path & rhs ) { return !(rhs < basic_path(lhs)); } + + template< class String, class Traits > + inline bool operator<=( const typename basic_path::string_type & lhs, + const basic_path & rhs ) { return !(rhs < basic_path(lhs)); } + + template< class String, class Traits > + inline bool operator<=( const basic_path & lhs, + const typename basic_path::string_type::value_type * rhs ) + { return !(basic_path(rhs) < lhs); } + + template< class String, class Traits > + inline bool operator<=( const basic_path & lhs, + const typename basic_path::string_type & rhs ) + { return !(basic_path(rhs) < lhs); } + + template< class String, class Traits > + inline bool operator>=( const basic_path & lhs, const basic_path & rhs ) { return !(lhs < rhs); } + + template< class String, class Traits > + inline bool operator>=( const typename basic_path::string_type::value_type * lhs, + const basic_path & rhs ) { return !(lhs < basic_path(rhs)); } + + template< class String, class Traits > + inline bool operator>=( const typename basic_path::string_type & lhs, + const basic_path & rhs ) { return !(lhs < basic_path(rhs)); } + + template< class String, class Traits > + inline bool operator>=( const basic_path & lhs, + const typename basic_path::string_type::value_type * rhs ) + { return !(basic_path(lhs) < rhs); } + + template< class String, class Traits > + inline bool operator>=( const basic_path & lhs, + const typename basic_path::string_type & rhs ) + { return !(basic_path(lhs) < rhs); } + + // operator / + + template< class String, class Traits > + inline basic_path operator/( + const basic_path & lhs, + const basic_path & rhs ) + { return basic_path( lhs ) /= rhs; } + + template< class String, class Traits > + inline basic_path operator/( + const basic_path & lhs, + const typename String::value_type * rhs ) + { return basic_path( lhs ) /= + basic_path( rhs ); } + + template< class String, class Traits > + inline basic_path operator/( + const basic_path & lhs, const String & rhs ) + { return basic_path( lhs ) /= + basic_path( rhs ); } + + template< class String, class Traits > + inline basic_path operator/( + const typename String::value_type * lhs, + const basic_path & rhs ) + { return basic_path( lhs ) /= rhs; } + + template< class String, class Traits > + inline basic_path operator/( + const String & lhs, const basic_path & rhs ) + { return basic_path( lhs ) /= rhs; } + + // inserters and extractors --------------------------------------------// + +// bypass VC++ 7.0 and earlier, and broken Borland compilers +# if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300) && !BOOST_WORKAROUND(__BORLANDC__, < 0x610) + template< class Path > + std::basic_ostream< typename Path::string_type::value_type, + typename Path::string_type::traits_type > & + operator<< + ( std::basic_ostream< typename Path::string_type::value_type, + typename Path::string_type::traits_type >& os, const Path & ph ) + { + os << ph.string(); + return os; + } + + template< class Path > + std::basic_istream< typename Path::string_type::value_type, + typename Path::string_type::traits_type > & + operator>> + ( std::basic_istream< typename Path::string_type::value_type, + typename Path::string_type::traits_type >& is, Path & ph ) + { + typename Path::string_type str; + std::getline(is, str); // See ticket 3863 + ph = str; + return is; + } +# elif BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) + template< class String, class Traits > + std::basic_ostream< BOOST_DEDUCED_TYPENAME String::value_type, + BOOST_DEDUCED_TYPENAME String::traits_type > & + operator<< + ( std::basic_ostream< BOOST_DEDUCED_TYPENAME String::value_type, + BOOST_DEDUCED_TYPENAME String::traits_type >& os, + const basic_path< String, Traits > & ph ) + { + os << ph.string(); + return os; + } + + template< class String, class Traits > + std::basic_istream< BOOST_DEDUCED_TYPENAME String::value_type, + BOOST_DEDUCED_TYPENAME String::traits_type > & + operator>> + ( std::basic_istream< BOOST_DEDUCED_TYPENAME String::value_type, + BOOST_DEDUCED_TYPENAME String::traits_type> & is, + basic_path< String, Traits > & ph ) + { + String str; + std::getline(is, str); // See ticket 3863 + ph = str; + return is; + } +# endif + + // basic_filesystem_error helpers --------------------------------------// + + // Originally choice of implementation was done via specialization of + // basic_filesystem_error::what(). Several compilers (GCC, aCC, etc.) + // couldn't handle that, so the choice is now accomplished by overloading. + + namespace detail + { + // BOOST_FILESYSTEM_DECL version works for VC++ but not GCC. Go figure! + inline + const char * what( const char * sys_err_what, + const path & path1_arg, const path & path2_arg, std::string & target ) + { + try + { + if ( target.empty() ) + { + target = sys_err_what; + if ( !path1_arg.empty() ) + { + target += ": \""; + target += path1_arg.file_string(); + target += "\""; + } + if ( !path2_arg.empty() ) + { + target += ", \""; + target += path2_arg.file_string(); + target += "\""; + } + } + return target.c_str(); + } + catch (...) + { + return sys_err_what; + } + } + + template + const char * what( const char * sys_err_what, + const Path & /*path1_arg*/, const Path & /*path2_arg*/, std::string & /*target*/ ) + { + return sys_err_what; + } + } + + // basic_filesystem_error ----------------------------------------------// + + template + class basic_filesystem_error : public system::system_error + { + // see http://www.boost.org/more/error_handling.html for design rationale + public: + // compiler generates copy constructor and copy assignment + + typedef Path path_type; + + basic_filesystem_error( const std::string & what_arg, + system::error_code ec ); + + basic_filesystem_error( const std::string & what_arg, + const path_type & path1_arg, system::error_code ec ); + + basic_filesystem_error( const std::string & what_arg, const path_type & path1_arg, + const path_type & path2_arg, system::error_code ec ); + + ~basic_filesystem_error() throw() {} + + const path_type & path1() const + { + static const path_type empty_path; + return m_imp_ptr.get() ? m_imp_ptr->m_path1 : empty_path ; + } + const path_type & path2() const + { + static const path_type empty_path; + return m_imp_ptr.get() ? m_imp_ptr->m_path2 : empty_path ; + } + + const char * what() const throw() + { + if ( !m_imp_ptr.get() ) + return system::system_error::what(); + return detail::what( system::system_error::what(), m_imp_ptr->m_path1, + m_imp_ptr->m_path2, m_imp_ptr->m_what ); + } + + private: + struct m_imp + { + path_type m_path1; // may be empty() + path_type m_path2; // may be empty() + std::string m_what; // not built until needed + }; + boost::shared_ptr m_imp_ptr; + }; + + typedef basic_filesystem_error filesystem_error; + +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + typedef basic_filesystem_error wfilesystem_error; +# endif + + // path::name_checks -----------------------------------------------------// + + BOOST_FILESYSTEM_DECL bool portable_posix_name( const std::string & name ); + BOOST_FILESYSTEM_DECL bool windows_name( const std::string & name ); + BOOST_FILESYSTEM_DECL bool portable_name( const std::string & name ); + BOOST_FILESYSTEM_DECL bool portable_directory_name( const std::string & name ); + BOOST_FILESYSTEM_DECL bool portable_file_name( const std::string & name ); + BOOST_FILESYSTEM_DECL bool native( const std::string & name ); + inline bool no_check( const std::string & ) + { return true; } + +// implementation -----------------------------------------------------------// + + namespace detail + { + + // is_separator helper ------------------------------------------------// + + template + inline bool is_separator( typename Path::string_type::value_type c ) + { + return c == slash::value +# ifdef BOOST_WINDOWS_PATH + || c == path_alt_separator::value +# endif + ; + } + + // filename_pos helper ----------------------------------------------------// + + template + typename String::size_type filename_pos( + const String & str, // precondition: portable generic path grammar + typename String::size_type end_pos ) // end_pos is past-the-end position + // return 0 if str itself is filename (or empty) + { + typedef typename + boost::BOOST_FILESYSTEM2_NAMESPACE::basic_path path_type; + + // case: "//" + if ( end_pos == 2 + && str[0] == slash::value + && str[1] == slash::value ) return 0; + + // case: ends in "/" + if ( end_pos && str[end_pos-1] == slash::value ) + return end_pos-1; + + // set pos to start of last element + typename String::size_type pos( + str.find_last_of( slash::value, end_pos-1 ) ); +# ifdef BOOST_WINDOWS_PATH + if ( pos == String::npos ) + pos = str.find_last_of( path_alt_separator::value, end_pos-1 ); + if ( pos == String::npos ) + pos = str.find_last_of( colon::value, end_pos-2 ); +# endif + + return ( pos == String::npos // path itself must be a filename (or empty) + || (pos == 1 && str[0] == slash::value) ) // or net + ? 0 // so filename is entire string + : pos + 1; // or starts after delimiter + } + + // first_element helper -----------------------------------------------// + // sets pos and len of first element, excluding extra separators + // if src.empty(), sets pos,len, to 0,0. + + template + void first_element( + const String & src, // precondition: portable generic path grammar + typename String::size_type & element_pos, + typename String::size_type & element_size, +# if !BOOST_WORKAROUND( BOOST_MSVC, <= 1310 ) // VC++ 7.1 + typename String::size_type size = String::npos +# else + typename String::size_type size = -1 +# endif + ) + { + if ( size == String::npos ) size = src.size(); + element_pos = 0; + element_size = 0; + if ( src.empty() ) return; + + typedef typename boost::BOOST_FILESYSTEM2_NAMESPACE::basic_path path_type; + + typename String::size_type cur(0); + + // deal with // [network] + if ( size >= 2 && src[0] == slash::value + && src[1] == slash::value + && (size == 2 + || src[2] != slash::value) ) + { + cur += 2; + element_size += 2; + } + + // leading (not non-network) separator + else if ( src[0] == slash::value ) + { + ++element_size; + // bypass extra leading separators + while ( cur+1 < size + && src[cur+1] == slash::value ) + { + ++cur; + ++element_pos; + } + return; + } + + // at this point, we have either a plain name, a network name, + // or (on Windows only) a device name + + // find the end + while ( cur < size +# ifdef BOOST_WINDOWS_PATH + && src[cur] != colon::value +# endif + && src[cur] != slash::value ) + { + ++cur; + ++element_size; + } + +# ifdef BOOST_WINDOWS_PATH + if ( cur == size ) return; + // include device delimiter + if ( src[cur] == colon::value ) + { ++element_size; } +# endif + + return; + } + + // root_directory_start helper ----------------------------------------// + + template + typename String::size_type root_directory_start( + const String & s, // precondition: portable generic path grammar + typename String::size_type size ) + // return npos if no root_directory found + { + typedef typename boost::BOOST_FILESYSTEM2_NAMESPACE::basic_path path_type; + +# ifdef BOOST_WINDOWS_PATH + // case "c:/" + if ( size > 2 + && s[1] == colon::value + && s[2] == slash::value ) return 2; +# endif + + // case "//" + if ( size == 2 + && s[0] == slash::value + && s[1] == slash::value ) return String::npos; + + // case "//net {/}" + if ( size > 3 + && s[0] == slash::value + && s[1] == slash::value + && s[2] != slash::value ) + { + typename String::size_type pos( + s.find( slash::value, 2 ) ); + return pos < size ? pos : String::npos; + } + + // case "/" + if ( size > 0 && s[0] == slash::value ) return 0; + + return String::npos; + } + + // is_non_root_slash helper -------------------------------------------// + + template + bool is_non_root_slash( const String & str, + typename String::size_type pos ) // pos is position of the slash + { + typedef typename + boost::BOOST_FILESYSTEM2_NAMESPACE::basic_path + path_type; + + assert( !str.empty() && str[pos] == slash::value + && "precondition violation" ); + + // subsequent logic expects pos to be for leftmost slash of a set + while ( pos > 0 && str[pos-1] == slash::value ) + --pos; + + return pos != 0 + && (pos <= 2 || str[1] != slash::value + || str.find( slash::value, 2 ) != pos) +# ifdef BOOST_WINDOWS_PATH + && (pos !=2 || str[1] != colon::value) +# endif + ; + } + } // namespace detail + + // decomposition functions ----------------------------------------------// + + template + String basic_path::filename() const + { + typename String::size_type end_pos( + detail::filename_pos( m_path, m_path.size() ) ); + return (m_path.size() + && end_pos + && m_path[end_pos] == slash::value + && detail::is_non_root_slash< String, Traits >(m_path, end_pos)) + ? String( 1, dot::value ) + : m_path.substr( end_pos ); + } + + template + String basic_path::stem() const + { + string_type name = filename(); + typename string_type::size_type n = name.rfind(dot::value); + return name.substr(0, n); + } + + template + String basic_path::extension() const + { + string_type name = filename(); + typename string_type::size_type n = name.rfind(dot::value); + if (n != string_type::npos) + return name.substr(n); + else + return string_type(); + } + + template + basic_path basic_path::parent_path() const + { + typename String::size_type end_pos( + detail::filename_pos( m_path, m_path.size() ) ); + + bool filename_was_separator( m_path.size() + && m_path[end_pos] == slash::value ); + + // skip separators unless root directory + typename string_type::size_type root_dir_pos( detail::root_directory_start + ( m_path, end_pos ) ); + for ( ; + end_pos > 0 + && (end_pos-1) != root_dir_pos + && m_path[end_pos-1] == slash::value + ; + --end_pos ) {} + + return (end_pos == 1 && root_dir_pos == 0 && filename_was_separator) + ? path_type() + : path_type( m_path.substr( 0, end_pos ) ); + } + + template + basic_path basic_path::relative_path() const + { + iterator itr( begin() ); + for ( ; itr.m_pos != m_path.size() + && (itr.m_name[0] == slash::value +# ifdef BOOST_WINDOWS_PATH + || itr.m_name[itr.m_name.size()-1] + == colon::value +# endif + ); ++itr ) {} + + return basic_path( m_path.substr( itr.m_pos ) ); + } + + template + String basic_path::root_name() const + { + iterator itr( begin() ); + + return ( itr.m_pos != m_path.size() + && ( + ( itr.m_name.size() > 1 + && itr.m_name[0] == slash::value + && itr.m_name[1] == slash::value + ) +# ifdef BOOST_WINDOWS_PATH + || itr.m_name[itr.m_name.size()-1] + == colon::value +# endif + ) ) + ? *itr + : String(); + } + + template + String basic_path::root_directory() const + { + typename string_type::size_type start( + detail::root_directory_start( m_path, m_path.size() ) ); + + return start == string_type::npos + ? string_type() + : m_path.substr( start, 1 ); + } + + template + basic_path basic_path::root_path() const + { + // even on POSIX, root_name() is non-empty() on network paths + return basic_path( root_name() ) /= root_directory(); + } + + // path query functions -------------------------------------------------// + + template + inline bool basic_path::is_complete() const + { +# ifdef BOOST_WINDOWS_PATH + return has_root_name() && has_root_directory(); +# else + return has_root_directory(); +# endif + } + + template + inline bool basic_path::has_root_path() const + { + return !root_path().empty(); + } + + template + inline bool basic_path::has_root_name() const + { + return !root_name().empty(); + } + + template + inline bool basic_path::has_root_directory() const + { + return !root_directory().empty(); + } + + // append ---------------------------------------------------------------// + + template + void basic_path::m_append_separator_if_needed() + // requires: !empty() + { + if ( +# ifdef BOOST_WINDOWS_PATH + *(m_path.end()-1) != colon::value && +# endif + *(m_path.end()-1) != slash::value ) + { + m_path += slash::value; + } + } + + template + void basic_path::m_append( value_type value ) + { +# ifdef BOOST_CYGWIN_PATH + if ( m_path.empty() ) m_cygwin_root = (value == slash::value); +# endif + +# ifdef BOOST_WINDOWS_PATH + // for BOOST_WINDOWS_PATH, convert alt_separator ('\') to separator ('/') + m_path += ( value == path_alt_separator::value + ? slash::value + : value ); +# else + m_path += value; +# endif + } + + // except that it wouldn't work for BOOST_NO_MEMBER_TEMPLATES compilers, + // the append() member template could replace this code. + template + basic_path & basic_path::operator /= + ( const value_type * next_p ) + { + // ignore escape sequence on POSIX or Windows + if ( *next_p == slash::value + && *(next_p+1) == slash::value + && *(next_p+2) == colon::value ) next_p += 3; + + // append slash::value if needed + if ( !empty() && *next_p != 0 + && !detail::is_separator( *next_p ) ) + { m_append_separator_if_needed(); } + + for ( ; *next_p != 0; ++next_p ) m_append( *next_p ); + return *this; + } + +# ifndef BOOST_NO_MEMBER_TEMPLATES + template template + basic_path & basic_path::append( + InputIterator first, InputIterator last ) + { + // append slash::value if needed + if ( !empty() && first != last + && !detail::is_separator( *first ) ) + { m_append_separator_if_needed(); } + + // song-and-dance to avoid violating InputIterator requirements + // (which prohibit lookahead) in detecting a possible escape sequence + // (escape sequences are simply ignored on POSIX and Windows) + bool was_escape_sequence(true); + std::size_t append_count(0); + typename String::size_type initial_pos( m_path.size() ); + + for ( ; first != last && *first; ++first ) + { + if ( append_count == 0 && *first != slash::value ) + was_escape_sequence = false; + if ( append_count == 1 && *first != slash::value ) + was_escape_sequence = false; + if ( append_count == 2 && *first != colon::value ) + was_escape_sequence = false; + m_append( *first ); + ++append_count; + } + + // erase escape sequence if any + if ( was_escape_sequence && append_count >= 3 ) + m_path.erase( initial_pos, 3 ); + + return *this; + } +# endif + +# ifndef BOOST_FILESYSTEM_NO_DEPRECATED + + // canonize ------------------------------------------------------------// + + template + basic_path & basic_path::canonize() + { + static const typename string_type::value_type dot_str[] + = { dot::value, 0 }; + + if ( m_path.empty() ) return *this; + + path_type temp; + + for ( iterator itr( begin() ); itr != end(); ++itr ) + { + temp /= *itr; + }; + + if ( temp.empty() ) temp /= dot_str; + m_path = temp.m_path; + return *this; + } + + // normalize ------------------------------------------------------------// + + template + basic_path & basic_path::normalize() + { + static const typename string_type::value_type dot_str[] + = { dot::value, 0 }; + + if ( m_path.empty() ) return *this; + + path_type temp; + iterator start( begin() ); + iterator last( end() ); + iterator stop( last-- ); + for ( iterator itr( start ); itr != stop; ++itr ) + { + // ignore "." except at start and last + if ( itr->size() == 1 + && (*itr)[0] == dot::value + && itr != start + && itr != last ) continue; + + // ignore a name and following ".." + if ( !temp.empty() + && itr->size() == 2 + && (*itr)[0] == dot::value + && (*itr)[1] == dot::value ) // dot dot + { + string_type lf( temp.filename() ); + if ( lf.size() > 0 + && (lf.size() != 1 + || (lf[0] != dot::value + && lf[0] != slash::value)) + && (lf.size() != 2 + || (lf[0] != dot::value + && lf[1] != dot::value +# ifdef BOOST_WINDOWS_PATH + && lf[1] != colon::value +# endif + ) + ) + ) + { + temp.remove_filename(); + // if not root directory, must also remove "/" if any + if ( temp.m_path.size() > 0 + && temp.m_path[temp.m_path.size()-1] + == slash::value ) + { + typename string_type::size_type rds( + detail::root_directory_start( temp.m_path, + temp.m_path.size() ) ); + if ( rds == string_type::npos + || rds != temp.m_path.size()-1 ) + { temp.m_path.erase( temp.m_path.size()-1 ); } + } + + iterator next( itr ); + if ( temp.empty() && ++next != stop + && next == last && *last == dot_str ) temp /= dot_str; + continue; + } + } + + temp /= *itr; + }; + + if ( temp.empty() ) temp /= dot_str; + m_path = temp.m_path; + return *this; + } + +# endif + + // modifiers ------------------------------------------------------------// + + template + basic_path & basic_path::remove_filename() + { + m_path.erase( + detail::filename_pos( m_path, m_path.size() ) ); + return *this; + } + + template + basic_path & + basic_path::replace_extension( const string_type & new_ext ) + { + // erase existing extension if any + string_type old_ext = extension(); + if ( !old_ext.empty() ) + m_path.erase( m_path.size() - old_ext.size() ); + + if ( !new_ext.empty() && new_ext[0] != dot::value ) + m_path += dot::value; + + m_path += new_ext; + + return *this; + } + + + // path conversion functions --------------------------------------------// + + template + const String + basic_path::file_string() const + { +# ifdef BOOST_WINDOWS_PATH + // for Windows, use the alternate separator, and bypass extra + // root separators + + typename string_type::size_type root_dir_start( + detail::root_directory_start( m_path, m_path.size() ) ); + bool in_root( root_dir_start != string_type::npos ); + String s; + for ( typename string_type::size_type pos( 0 ); + pos != m_path.size(); ++pos ) + { + // special case // [net] + if ( pos == 0 && m_path.size() > 1 + && m_path[0] == slash::value + && m_path[1] == slash::value + && ( m_path.size() == 2 + || !detail::is_separator( m_path[2] ) + ) ) + { + ++pos; + s += path_alt_separator::value; + s += path_alt_separator::value; + continue; + } + + // bypass extra root separators + if ( in_root ) + { + if ( s.size() > 0 + && s[s.size()-1] == path_alt_separator::value + && m_path[pos] == slash::value + ) continue; + } + + if ( m_path[pos] == slash::value ) + s += path_alt_separator::value; + else + s += m_path[pos]; + + if ( pos > root_dir_start + && m_path[pos] == slash::value ) + { in_root = false; } + } +# ifdef BOOST_CYGWIN_PATH + if ( m_cygwin_root ) s[0] = slash::value; +# endif + return s; +# else + return m_path; +# endif + } + + // iterator functions ---------------------------------------------------// + + template + typename basic_path::iterator basic_path::begin() const + { + iterator itr; + itr.m_path_ptr = this; + typename string_type::size_type element_size; + detail::first_element( m_path, itr.m_pos, element_size ); + itr.m_name = m_path.substr( itr.m_pos, element_size ); + return itr; + } + + template + typename basic_path::iterator basic_path::end() const + { + iterator itr; + itr.m_path_ptr = this; + itr.m_pos = m_path.size(); + return itr; + } + + namespace detail + { + // do_increment ------------------------------------------------------// + + template + void iterator_helper::do_increment( iterator & itr ) + { + typedef typename Path::string_type string_type; + typedef typename Path::traits_type traits_type; + + assert( itr.m_pos < itr.m_path_ptr->m_path.size() && "basic_path::iterator increment past end()" ); + + bool was_net( itr.m_name.size() > 2 + && itr.m_name[0] == slash::value + && itr.m_name[1] == slash::value + && itr.m_name[2] != slash::value ); + + // increment to position past current element + itr.m_pos += itr.m_name.size(); + + // if end reached, create end iterator + if ( itr.m_pos == itr.m_path_ptr->m_path.size() ) + { + itr.m_name.erase( itr.m_name.begin(), itr.m_name.end() ); // VC++ 6.0 lib didn't supply clear() + return; + } + + // process separator (Windows drive spec is only case not a separator) + if ( itr.m_path_ptr->m_path[itr.m_pos] == slash::value ) + { + // detect root directory + if ( was_net + # ifdef BOOST_WINDOWS_PATH + // case "c:/" + || itr.m_name[itr.m_name.size()-1] == colon::value + # endif + ) + { + itr.m_name = slash::value; + return; + } + + // bypass separators + while ( itr.m_pos != itr.m_path_ptr->m_path.size() + && itr.m_path_ptr->m_path[itr.m_pos] == slash::value ) + { ++itr.m_pos; } + + // detect trailing separator, and treat it as ".", per POSIX spec + if ( itr.m_pos == itr.m_path_ptr->m_path.size() + && detail::is_non_root_slash< string_type, traits_type >( + itr.m_path_ptr->m_path, itr.m_pos-1 ) ) + { + --itr.m_pos; + itr.m_name = dot::value; + return; + } + } + + // get next element + typename string_type::size_type end_pos( + itr.m_path_ptr->m_path.find( slash::value, itr.m_pos ) ); + itr.m_name = itr.m_path_ptr->m_path.substr( itr.m_pos, end_pos - itr.m_pos ); + } + + // do_decrement ------------------------------------------------------// + + template + void iterator_helper::do_decrement( iterator & itr ) + { + assert( itr.m_pos && "basic_path::iterator decrement past begin()" ); + + typedef typename Path::string_type string_type; + typedef typename Path::traits_type traits_type; + + typename string_type::size_type end_pos( itr.m_pos ); + + typename string_type::size_type root_dir_pos( + detail::root_directory_start( + itr.m_path_ptr->m_path, end_pos ) ); + + // if at end and there was a trailing non-root '/', return "." + if ( itr.m_pos == itr.m_path_ptr->m_path.size() + && itr.m_path_ptr->m_path.size() > 1 + && itr.m_path_ptr->m_path[itr.m_pos-1] == slash::value + && detail::is_non_root_slash< string_type, traits_type >( + itr.m_path_ptr->m_path, itr.m_pos-1 ) + ) + { + --itr.m_pos; + itr.m_name = dot::value; + return; + } + + // skip separators unless root directory + for ( + ; + end_pos > 0 + && (end_pos-1) != root_dir_pos + && itr.m_path_ptr->m_path[end_pos-1] == slash::value + ; + --end_pos ) {} + + itr.m_pos = detail::filename_pos + ( itr.m_path_ptr->m_path, end_pos ); + itr.m_name = itr.m_path_ptr->m_path.substr( itr.m_pos, end_pos - itr.m_pos ); + } + } // namespace detail + + // basic_filesystem_error implementation --------------------------------// + + template + basic_filesystem_error::basic_filesystem_error( + const std::string & what_arg, system::error_code ec ) + : system::system_error(ec, what_arg) + { + try + { + m_imp_ptr.reset( new m_imp ); + } + catch (...) { m_imp_ptr.reset(); } + } + + template + basic_filesystem_error::basic_filesystem_error( + const std::string & what_arg, const path_type & path1_arg, + system::error_code ec ) + : system::system_error(ec, what_arg) + { + try + { + m_imp_ptr.reset( new m_imp ); + m_imp_ptr->m_path1 = path1_arg; + } + catch (...) { m_imp_ptr.reset(); } + } + + template + basic_filesystem_error::basic_filesystem_error( + const std::string & what_arg, const path_type & path1_arg, + const path_type & path2_arg, system::error_code ec ) + : system::system_error(ec, what_arg) + { + try + { + m_imp_ptr.reset( new m_imp ); + m_imp_ptr->m_path1 = path1_arg; + m_imp_ptr->m_path2 = path2_arg; + } + catch (...) { m_imp_ptr.reset(); } + } + + } // namespace BOOST_FILESYSTEM2_NAMESPACE +} // namespace boost + +//----------------------------------------------------------------------------// + +namespace boost +{ + namespace filesystem + { + using filesystem2::basic_path; + using filesystem2::path_traits; + + using filesystem2::slash; + using filesystem2::dot; + using filesystem2::colon; + + using filesystem2::path; +# ifndef BOOST_FILESYSTEM2_NARROW_ONLY + using filesystem2::wpath_traits; + using filesystem2::wpath; + using filesystem2::wfilesystem_error; +# endif + using filesystem2::basic_filesystem_error; + using filesystem2::filesystem_error; + using filesystem2::portable_posix_name; + using filesystem2::windows_name; + using filesystem2::portable_name; + using filesystem2::portable_directory_name; + using filesystem2::portable_file_name; + using filesystem2::native; + using filesystem2::no_check; + using filesystem2::swap; + using filesystem2::operator<; + using filesystem2::operator==; + using filesystem2::operator!=; + using filesystem2::operator>; + using filesystem2::operator<=; + using filesystem2::operator>=; + using filesystem2::operator/; + using filesystem2::operator<<; + using filesystem2::operator>>; + } +} + +//----------------------------------------------------------------------------// + +#include // pops abi_prefix.hpp pragmas + +#endif // BOOST_FILESYSTEM2_PATH_HPP diff --git a/utils/boost_idb/boost/flyweight.hpp b/utils/boost_idb/boost/flyweight.hpp new file mode 100644 index 00000000..6fe30426 --- /dev/null +++ b/utils/boost_idb/boost/flyweight.hpp @@ -0,0 +1,22 @@ +/* Copyright 2006-2008 Joaquin M Lopez Munoz. + * Distributed under the Boost Software License, Version 1.0. + * (See accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt) + * + * See http://www.boost.org/libs/flyweight for library home page. + */ + +#ifndef BOOST_FLYWEIGHT_HPP +#define BOOST_FLYWEIGHT_HPP + +#if defined(_MSC_VER)&&(_MSC_VER>=1200) +#pragma once +#endif + +#include +#include +#include +#include +#include + +#endif diff --git a/utils/boost_idb/boost/foreach.hpp b/utils/boost_idb/boost/foreach.hpp new file mode 100644 index 00000000..db5b2035 --- /dev/null +++ b/utils/boost_idb/boost/foreach.hpp @@ -0,0 +1,1104 @@ +/////////////////////////////////////////////////////////////////////////////// +// foreach.hpp header file +// +// Copyright 2004 Eric Niebler. +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// See http://www.boost.org/libs/foreach for documentation +// +// Credits: +// Anson Tsao - for the initial inspiration and several good suggestions. +// Thorsten Ottosen - for Boost.Range, and for suggesting a way to detect +// const-qualified rvalues at compile time on VC7.1+ +// Russell Hind - For help porting to Borland +// Alisdair Meredith - For help porting to Borland +// Stefan Slapeta - For help porting to Intel +// David Jenkins - For help finding a Microsoft Code Analysis bug + +#ifndef BOOST_FOREACH + +// MS compatible compilers support #pragma once +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +# pragma once +#endif + +#include +#include // for std::pair + +#include +#include + +// Some compilers let us detect even const-qualified rvalues at compile-time +#if BOOST_WORKAROUND(BOOST_MSVC, >= 1310) && !defined(_PREFAST_) \ + || (BOOST_WORKAROUND(__GNUC__, >= 4) && !defined(BOOST_INTEL) && !defined(BOOST_CLANG)) \ + || (BOOST_WORKAROUND(__GNUC__, == 3) && (__GNUC_MINOR__ >= 4) && !defined(BOOST_INTEL) && \ + !defined(BOOST_CLANG)) +# define BOOST_FOREACH_COMPILE_TIME_CONST_RVALUE_DETECTION +#else +// Some compilers allow temporaries to be bound to non-const references. +// These compilers make it impossible to for BOOST_FOREACH to detect +// temporaries and avoid reevaluation of the collection expression. +# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \ + || BOOST_WORKAROUND(__BORLANDC__, < 0x593) \ + || (BOOST_WORKAROUND(BOOST_INTEL_CXX_VERSION, <= 700) && defined(_MSC_VER)) \ + || BOOST_WORKAROUND(__SUNPRO_CC, < 0x5100) \ + || BOOST_WORKAROUND(__DECCXX_VER, <= 60590042) +# define BOOST_FOREACH_NO_RVALUE_DETECTION +# endif +// Some compilers do not correctly implement the lvalue/rvalue conversion +// rules of the ternary conditional operator. +# if defined(BOOST_FOREACH_NO_RVALUE_DETECTION) \ + || defined(BOOST_NO_SFINAE) \ + || BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1400)) \ + || BOOST_WORKAROUND(BOOST_INTEL_WIN, BOOST_TESTED_AT(1400)) \ + || BOOST_WORKAROUND(__GNUC__, < 3) \ + || (BOOST_WORKAROUND(__GNUC__, == 3) && (__GNUC_MINOR__ <= 2)) \ + || (BOOST_WORKAROUND(__GNUC__, == 3) && (__GNUC_MINOR__ <= 3) && defined(__APPLE_CC__)) \ + || BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) \ + || BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3206)) \ + || BOOST_WORKAROUND(__SUNPRO_CC, >= 0x5100) \ + || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x590)) +# define BOOST_FOREACH_NO_CONST_RVALUE_DETECTION +# else +# define BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +# endif +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +# include +# include +# include +# include +#endif + +namespace boost +{ + +// forward declarations for iterator_range +template +class iterator_range; + +// forward declarations for sub_range +template +class sub_range; + +namespace foreach +{ + /////////////////////////////////////////////////////////////////////////////// + // in_range + // + template + inline std::pair in_range(T begin, T end) + { + return std::make_pair(begin, end); + } + + /////////////////////////////////////////////////////////////////////////////// + // boost::foreach::is_lightweight_proxy + // Specialize this for user-defined collection types if they are inexpensive to copy. + // This tells BOOST_FOREACH it can avoid the rvalue/lvalue detection stuff. + template + struct is_lightweight_proxy + : boost::mpl::false_ + { + }; + + /////////////////////////////////////////////////////////////////////////////// + // boost::foreach::is_noncopyable + // Specialize this for user-defined collection types if they cannot be copied. + // This also tells BOOST_FOREACH to avoid the rvalue/lvalue detection stuff. + template + struct is_noncopyable + #if !defined(BOOST_BROKEN_IS_BASE_AND_DERIVED) && !defined(BOOST_NO_IS_ABSTRACT) + : boost::mpl::or_< + boost::is_abstract + , boost::is_base_and_derived + > + #elif !defined(BOOST_BROKEN_IS_BASE_AND_DERIVED) + : boost::is_base_and_derived + #elif !defined(BOOST_NO_IS_ABSTRACT) + : boost::is_abstract + #else + : boost::mpl::false_ + #endif + { + }; + +} // namespace foreach + +} // namespace boost + +// vc6/7 needs help ordering the following overloads +#ifdef BOOST_NO_FUNCTION_TEMPLATE_ORDERING +# define BOOST_FOREACH_TAG_DEFAULT ... +#else +# define BOOST_FOREACH_TAG_DEFAULT boost::foreach::tag +#endif + +/////////////////////////////////////////////////////////////////////////////// +// boost_foreach_is_lightweight_proxy +// Another customization point for the is_lightweight_proxy optimization, +// this one works on legacy compilers. Overload boost_foreach_is_lightweight_proxy +// at the global namespace for your type. +template +inline boost::foreach::is_lightweight_proxy * +boost_foreach_is_lightweight_proxy(T *&, BOOST_FOREACH_TAG_DEFAULT) { return 0; } + +template +inline boost::mpl::true_ * +boost_foreach_is_lightweight_proxy(std::pair *&, boost::foreach::tag) { return 0; } + +template +inline boost::mpl::true_ * +boost_foreach_is_lightweight_proxy(boost::iterator_range *&, boost::foreach::tag) { return 0; } + +template +inline boost::mpl::true_ * +boost_foreach_is_lightweight_proxy(boost::sub_range *&, boost::foreach::tag) { return 0; } + +template +inline boost::mpl::true_ * +boost_foreach_is_lightweight_proxy(T **&, boost::foreach::tag) { return 0; } + +/////////////////////////////////////////////////////////////////////////////// +// boost_foreach_is_noncopyable +// Another customization point for the is_noncopyable trait, +// this one works on legacy compilers. Overload boost_foreach_is_noncopyable +// at the global namespace for your type. +template +inline boost::foreach::is_noncopyable * +boost_foreach_is_noncopyable(T *&, BOOST_FOREACH_TAG_DEFAULT) { return 0; } + +namespace boost +{ + +namespace foreach_detail_ +{ + +/////////////////////////////////////////////////////////////////////////////// +// Define some utilities for assessing the properties of expressions +// +template +inline boost::mpl::and_ *and_(Bool1 *, Bool2 *) { return 0; } + +template +inline boost::mpl::and_ *and_(Bool1 *, Bool2 *, Bool3 *) { return 0; } + +template +inline boost::mpl::or_ *or_(Bool1 *, Bool2 *) { return 0; } + +template +inline boost::mpl::or_ *or_(Bool1 *, Bool2 *, Bool3 *) { return 0; } + +template +inline boost::mpl::not_ *not_(Bool1 *) { return 0; } + +template +inline boost::mpl::false_ *is_rvalue_(T &, int) { return 0; } + +template +inline boost::mpl::true_ *is_rvalue_(T const &, ...) { return 0; } + +template +inline boost::is_array *is_array_(T const &) { return 0; } + +template +inline boost::is_const *is_const_(T &) { return 0; } + +#ifndef BOOST_FOREACH_NO_RVALUE_DETECTION +template +inline boost::mpl::true_ *is_const_(T const &) { return 0; } +#endif + +/////////////////////////////////////////////////////////////////////////////// +// auto_any_t/auto_any +// General utility for putting an object of any type into automatic storage +struct auto_any_base +{ + // auto_any_base must evaluate to false in boolean context so that + // they can be declared in if() statements. + operator bool() const + { + return false; + } +}; + +template +struct auto_any : auto_any_base +{ + explicit auto_any(T const &t) + : item(t) + { + } + + // temporaries of type auto_any will be bound to const auto_any_base + // references, but we still want to be able to mutate the stored + // data, so declare it as mutable. + mutable T item; +}; + +typedef auto_any_base const &auto_any_t; + +template +inline BOOST_DEDUCED_TYPENAME boost::mpl::if_::type &auto_any_cast(auto_any_t a) +{ + return static_cast const &>(a).item; +} + +typedef boost::mpl::true_ const_; + +/////////////////////////////////////////////////////////////////////////////// +// type2type +// +template +struct type2type + : boost::mpl::if_ +{ +}; + +template +struct wrap_cstr +{ + typedef T type; +}; + +template<> +struct wrap_cstr +{ + typedef wrap_cstr type; + typedef char *iterator; + typedef char *const_iterator; +}; + +template<> +struct wrap_cstr +{ + typedef wrap_cstr type; + typedef char const *iterator; + typedef char const *const_iterator; +}; + +template<> +struct wrap_cstr +{ + typedef wrap_cstr type; + typedef wchar_t *iterator; + typedef wchar_t *const_iterator; +}; + +template<> +struct wrap_cstr +{ + typedef wrap_cstr type; + typedef wchar_t const *iterator; + typedef wchar_t const *const_iterator; +}; + +template +struct is_char_array + : mpl::and_< + is_array + , mpl::or_< + is_convertible + , is_convertible + > + > +{}; + +template +struct foreach_iterator +{ + // **** READ THIS IF YOUR COMPILE BREAKS HERE **** + // + // There is an ambiguity about how to iterate over arrays of char and wchar_t. + // Should the last array element be treated as a null terminator to be skipped, or + // is it just like any other element in the array? To fix the problem, you must + // say which behavior you want. + // + // To treat the container as a null-terminated string, merely cast it to a + // char const *, as in BOOST_FOREACH( char ch, (char const *)"hello" ) ... + // + // To treat the container as an array, use boost::as_array() in , + // as in BOOST_FOREACH( char ch, boost::as_array("hello") ) ... + #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 + BOOST_MPL_ASSERT_MSG( (!is_char_array::value), IS_THIS_AN_ARRAY_OR_A_NULL_TERMINATED_STRING, (T&) ); + #endif + + // If the type is a pointer to a null terminated string (as opposed + // to an array type), there is no ambiguity. + typedef BOOST_DEDUCED_TYPENAME wrap_cstr::type container; + + typedef BOOST_DEDUCED_TYPENAME boost::mpl::eval_if< + C + , range_const_iterator + , range_mutable_iterator + >::type type; +}; + + +template +struct foreach_reverse_iterator +{ + // **** READ THIS IF YOUR COMPILE BREAKS HERE **** + // + // There is an ambiguity about how to iterate over arrays of char and wchar_t. + // Should the last array element be treated as a null terminator to be skipped, or + // is it just like any other element in the array? To fix the problem, you must + // say which behavior you want. + // + // To treat the container as a null-terminated string, merely cast it to a + // char const *, as in BOOST_FOREACH( char ch, (char const *)"hello" ) ... + // + // To treat the container as an array, use boost::as_array() in , + // as in BOOST_FOREACH( char ch, boost::as_array("hello") ) ... + #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 + BOOST_MPL_ASSERT_MSG( (!is_char_array::value), IS_THIS_AN_ARRAY_OR_A_NULL_TERMINATED_STRING, (T&) ); + #endif + + // If the type is a pointer to a null terminated string (as opposed + // to an array type), there is no ambiguity. + typedef BOOST_DEDUCED_TYPENAME wrap_cstr::type container; + + typedef BOOST_DEDUCED_TYPENAME boost::mpl::eval_if< + C + , range_reverse_iterator + , range_reverse_iterator + >::type type; +}; + +template +struct foreach_reference + : iterator_reference::type> +{ +}; + +/////////////////////////////////////////////////////////////////////////////// +// encode_type +// +template +inline type2type *encode_type(T &, boost::mpl::false_ *) { return 0; } + +template +inline type2type *encode_type(T const &, boost::mpl::true_ *) { return 0; } + +/////////////////////////////////////////////////////////////////////////////// +// set_false +// +inline bool set_false(bool &b) +{ + b = false; + return false; +} + +/////////////////////////////////////////////////////////////////////////////// +// to_ptr +// +template +inline T *&to_ptr(T const &) +{ + static T *t = 0; + return t; +} + +// Borland needs a little extra help with arrays +#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) +template +inline T (*&to_ptr(T (&)[N]))[N] +{ + static T (*t)[N] = 0; + return t; +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// derefof +// +template +inline T &derefof(T *t) +{ + // This is a work-around for a compiler bug in Borland. If T* is a pointer to array type U(*)[N], + // then dereferencing it results in a U* instead of U(&)[N]. The cast forces the issue. + return reinterpret_cast( + *const_cast( + reinterpret_cast(t) + ) + ); +} + +#ifdef BOOST_FOREACH_COMPILE_TIME_CONST_RVALUE_DETECTION +/////////////////////////////////////////////////////////////////////////////// +// Detect at compile-time whether an expression yields an rvalue or +// an lvalue. This is rather non-standard, but some popular compilers +// accept it. +/////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////// +// rvalue_probe +// +template +struct rvalue_probe +{ + struct private_type_ {}; + // can't ever return an array by value + typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_< + boost::mpl::or_, boost::is_array >, private_type_, T + >::type value_type; + operator value_type() { return *reinterpret_cast(this); } // never called + operator T &() const { return *reinterpret_cast(const_cast(this)); } // never called +}; + +template +rvalue_probe const make_probe(T const &) +{ + return rvalue_probe(); +} + +# define BOOST_FOREACH_IS_RVALUE(COL) \ + boost::foreach_detail_::and_( \ + boost::foreach_detail_::not_(boost::foreach_detail_::is_array_(COL)) \ + , (true ? 0 : boost::foreach_detail_::is_rvalue_( \ + (true ? boost::foreach_detail_::make_probe(COL) : (COL)), 0))) + +#elif defined(BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION) +/////////////////////////////////////////////////////////////////////////////// +// Detect at run-time whether an expression yields an rvalue +// or an lvalue. This is 100% standard C++, but not all compilers +// accept it. Also, it causes FOREACH to break when used with non- +// copyable collection types. +/////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////// +// rvalue_probe +// +template +struct rvalue_probe +{ + rvalue_probe(T &t, bool &b) + : value(t) + , is_rvalue(b) + { + } + + struct private_type_ {}; + // can't ever return an array or an abstract type by value + #ifdef BOOST_NO_IS_ABSTRACT + typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_< + boost::is_array, private_type_, T + >::type value_type; + #else + typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_< + boost::mpl::or_, boost::is_array >, private_type_, T + >::type value_type; + #endif + + operator value_type() + { + this->is_rvalue = true; + return this->value; + } + + operator T &() const + { + return this->value; + } + +private: + T &value; + bool &is_rvalue; +}; + +template +rvalue_probe make_probe(T &t, bool &b) { return rvalue_probe(t, b); } + +template +rvalue_probe make_probe(T const &t, bool &b) { return rvalue_probe(t, b); } + +/////////////////////////////////////////////////////////////////////////////// +// simple_variant +// holds either a T or a T const* +template +struct simple_variant +{ + simple_variant(T const *t) + : is_rvalue(false) + { + *static_cast(this->data.address()) = t; + } + + simple_variant(T const &t) + : is_rvalue(true) + { + ::new(this->data.address()) T(t); + } + + simple_variant(simple_variant const &that) + : is_rvalue(that.is_rvalue) + { + if(this->is_rvalue) + ::new(this->data.address()) T(*that.get()); + else + *static_cast(this->data.address()) = that.get(); + } + + ~simple_variant() + { + if(this->is_rvalue) + this->get()->~T(); + } + + T const *get() const + { + if(this->is_rvalue) + return static_cast(this->data.address()); + else + return *static_cast(this->data.address()); + } + +private: + enum size_type { size = sizeof(T) > sizeof(T*) ? sizeof(T) : sizeof(T*) }; + simple_variant &operator =(simple_variant const &); + bool const is_rvalue; + aligned_storage data; +}; + +// If the collection is an array or is noncopyable, it must be an lvalue. +// If the collection is a lightweight proxy, treat it as an rvalue +// BUGBUG what about a noncopyable proxy? +template +inline BOOST_DEDUCED_TYPENAME boost::enable_if, IsProxy>::type * +should_copy_impl(LValue *, IsProxy *, bool *) +{ + return 0; +} + +// Otherwise, we must determine at runtime whether it's an lvalue or rvalue +inline bool * +should_copy_impl(boost::mpl::false_ *, boost::mpl::false_ *, bool *is_rvalue) +{ + return is_rvalue; +} + +#endif + +/////////////////////////////////////////////////////////////////////////////// +// contain +// +template +inline auto_any contain(T const &t, boost::mpl::true_ *) // rvalue +{ + return auto_any(t); +} + +template +inline auto_any contain(T &t, boost::mpl::false_ *) // lvalue +{ + // Cannot seem to get sunpro to handle addressof() with array types. + #if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x570)) + return auto_any(&t); + #else + return auto_any(boost::addressof(t)); + #endif +} + +#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +template +inline auto_any > +contain(T const &t, bool *rvalue) +{ + return auto_any >(*rvalue ? simple_variant(t) : simple_variant(&t)); +} +#endif + +///////////////////////////////////////////////////////////////////////////// +// begin +// +template +inline auto_any::type> +begin(auto_any_t col, type2type *, boost::mpl::true_ *) // rvalue +{ + return auto_any::type>( + boost::begin(auto_any_cast(col))); +} + +template +inline auto_any::type> +begin(auto_any_t col, type2type *, boost::mpl::false_ *) // lvalue +{ + typedef BOOST_DEDUCED_TYPENAME type2type::type type; + typedef BOOST_DEDUCED_TYPENAME foreach_iterator::type iterator; + return auto_any::type>( + iterator(boost::begin(derefof(auto_any_cast(col))))); +} + +#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +template +inline auto_any::type> +begin(auto_any_t col, type2type *, bool *) +{ + return auto_any::type>( + boost::begin(*auto_any_cast, boost::mpl::false_>(col).get())); +} +#endif + +#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING +template +inline auto_any +begin(auto_any_t col, type2type *, boost::mpl::true_ *) // null-terminated C-style strings +{ + return auto_any(auto_any_cast(col)); +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// end +// +template +inline auto_any::type> +end(auto_any_t col, type2type *, boost::mpl::true_ *) // rvalue +{ + return auto_any::type>( + boost::end(auto_any_cast(col))); +} + +template +inline auto_any::type> +end(auto_any_t col, type2type *, boost::mpl::false_ *) // lvalue +{ + typedef BOOST_DEDUCED_TYPENAME type2type::type type; + typedef BOOST_DEDUCED_TYPENAME foreach_iterator::type iterator; + return auto_any::type>( + iterator(boost::end(derefof(auto_any_cast(col))))); +} + +#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +template +inline auto_any::type> +end(auto_any_t col, type2type *, bool *) +{ + return auto_any::type>( + boost::end(*auto_any_cast, boost::mpl::false_>(col).get())); +} +#endif + +#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING +template +inline auto_any +end(auto_any_t, type2type *, boost::mpl::true_ *) // null-terminated C-style strings +{ + return auto_any(0); // not used +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// done +// +template +inline bool done(auto_any_t cur, auto_any_t end, type2type *) +{ + typedef BOOST_DEDUCED_TYPENAME foreach_iterator::type iter_t; + return auto_any_cast(cur) == auto_any_cast(end); +} + +#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING +template +inline bool done(auto_any_t cur, auto_any_t, type2type *) // null-terminated C-style strings +{ + return ! *auto_any_cast(cur); +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// next +// +template +inline void next(auto_any_t cur, type2type *) +{ + typedef BOOST_DEDUCED_TYPENAME foreach_iterator::type iter_t; + ++auto_any_cast(cur); +} + +/////////////////////////////////////////////////////////////////////////////// +// deref +// +template +inline BOOST_DEDUCED_TYPENAME foreach_reference::type +deref(auto_any_t cur, type2type *) +{ + typedef BOOST_DEDUCED_TYPENAME foreach_iterator::type iter_t; + return *auto_any_cast(cur); +} + +///////////////////////////////////////////////////////////////////////////// +// rbegin +// +template +inline auto_any::type> +rbegin(auto_any_t col, type2type *, boost::mpl::true_ *) // rvalue +{ + return auto_any::type>( + boost::rbegin(auto_any_cast(col))); +} + +template +inline auto_any::type> +rbegin(auto_any_t col, type2type *, boost::mpl::false_ *) // lvalue +{ + typedef BOOST_DEDUCED_TYPENAME type2type::type type; + typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator::type iterator; + return auto_any::type>( + iterator(boost::rbegin(derefof(auto_any_cast(col))))); +} + +#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +template +inline auto_any::type> +rbegin(auto_any_t col, type2type *, bool *) +{ + return auto_any::type>( + boost::rbegin(*auto_any_cast, boost::mpl::false_>(col).get())); +} +#endif + +#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING +template +inline auto_any > +rbegin(auto_any_t col, type2type *, boost::mpl::true_ *) // null-terminated C-style strings +{ + T *p = auto_any_cast(col); + while(0 != *p) + ++p; + return auto_any >(reverse_iterator(p)); +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// rend +// +template +inline auto_any::type> +rend(auto_any_t col, type2type *, boost::mpl::true_ *) // rvalue +{ + return auto_any::type>( + boost::rend(auto_any_cast(col))); +} + +template +inline auto_any::type> +rend(auto_any_t col, type2type *, boost::mpl::false_ *) // lvalue +{ + typedef BOOST_DEDUCED_TYPENAME type2type::type type; + typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator::type iterator; + return auto_any::type>( + iterator(boost::rend(derefof(auto_any_cast(col))))); +} + +#ifdef BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION +template +inline auto_any::type> +rend(auto_any_t col, type2type *, bool *) +{ + return auto_any::type>( + boost::rend(*auto_any_cast, boost::mpl::false_>(col).get())); +} +#endif + +#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING +template +inline auto_any > +rend(auto_any_t col, type2type *, boost::mpl::true_ *) // null-terminated C-style strings +{ + return auto_any >( + reverse_iterator(auto_any_cast(col))); +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// rdone +// +template +inline bool rdone(auto_any_t cur, auto_any_t end, type2type *) +{ + typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator::type iter_t; + return auto_any_cast(cur) == auto_any_cast(end); +} + +/////////////////////////////////////////////////////////////////////////////// +// rnext +// +template +inline void rnext(auto_any_t cur, type2type *) +{ + typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator::type iter_t; + ++auto_any_cast(cur); +} + +/////////////////////////////////////////////////////////////////////////////// +// rderef +// +template +inline BOOST_DEDUCED_TYPENAME foreach_reference::type +rderef(auto_any_t cur, type2type *) +{ + typedef BOOST_DEDUCED_TYPENAME foreach_reverse_iterator::type iter_t; + return *auto_any_cast(cur); +} + +} // namespace foreach_detail_ +} // namespace boost + +// Suppress a bogus code analysis warning on vc8+ +#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) +# define BOOST_FOREACH_SUPPRESS_WARNINGS() __pragma(warning(suppress:6001)) +#else +# define BOOST_FOREACH_SUPPRESS_WARNINGS() +#endif + +/////////////////////////////////////////////////////////////////////////////// +// Define a macro for giving hidden variables a unique name. Not strictly +// needed, but eliminates some warnings on some compilers. +#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1500)) +// With some versions of MSVC, use of __LINE__ to create unique identifiers +// can fail when the Edit-and-Continue debug flag is used. +# define BOOST_FOREACH_ID(x) x +#else +# define BOOST_FOREACH_ID(x) BOOST_PP_CAT(x, __LINE__) +#endif + +// A sneaky way to get the type of the collection without evaluating the expression +#define BOOST_FOREACH_TYPEOF(COL) \ + (true ? 0 : boost::foreach_detail_::encode_type(COL, boost::foreach_detail_::is_const_(COL))) + +// returns true_* if the type is noncopyable +#define BOOST_FOREACH_IS_NONCOPYABLE(COL) \ + boost_foreach_is_noncopyable( \ + boost::foreach_detail_::to_ptr(COL) \ + , boost_foreach_argument_dependent_lookup_hack_value) + +// returns true_* if the type is a lightweight proxy (and is not noncopyable) +#define BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL) \ + boost::foreach_detail_::and_( \ + boost::foreach_detail_::not_(BOOST_FOREACH_IS_NONCOPYABLE(COL)) \ + , boost_foreach_is_lightweight_proxy( \ + boost::foreach_detail_::to_ptr(COL) \ + , boost_foreach_argument_dependent_lookup_hack_value)) + +#ifdef BOOST_FOREACH_COMPILE_TIME_CONST_RVALUE_DETECTION +/////////////////////////////////////////////////////////////////////////////// +// R-values and const R-values supported here with zero runtime overhead +/////////////////////////////////////////////////////////////////////////////// + +// No variable is needed to track the rvalue-ness of the collection expression +# define BOOST_FOREACH_PREAMBLE() \ + BOOST_FOREACH_SUPPRESS_WARNINGS() + +// Evaluate the collection expression +# define BOOST_FOREACH_EVALUATE(COL) \ + (COL) + +# define BOOST_FOREACH_SHOULD_COPY(COL) \ + (true ? 0 : boost::foreach_detail_::or_( \ + BOOST_FOREACH_IS_RVALUE(COL) \ + , BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL))) + +#elif defined(BOOST_FOREACH_RUN_TIME_CONST_RVALUE_DETECTION) +/////////////////////////////////////////////////////////////////////////////// +// R-values and const R-values supported here +/////////////////////////////////////////////////////////////////////////////// + +// Declare a variable to track the rvalue-ness of the collection expression +# define BOOST_FOREACH_PREAMBLE() \ + BOOST_FOREACH_SUPPRESS_WARNINGS() \ + if (bool BOOST_FOREACH_ID(_foreach_is_rvalue) = false) {} else + +// Evaluate the collection expression, and detect if it is an lvalue or and rvalue +# define BOOST_FOREACH_EVALUATE(COL) \ + (true ? boost::foreach_detail_::make_probe((COL), BOOST_FOREACH_ID(_foreach_is_rvalue)) : (COL)) + +// The rvalue/lvalue-ness of the collection expression is determined dynamically, unless +// type type is an array or is noncopyable or is non-const, in which case we know it's an lvalue. +// If the type happens to be a lightweight proxy, always make a copy. +# define BOOST_FOREACH_SHOULD_COPY(COL) \ + (boost::foreach_detail_::should_copy_impl( \ + true ? 0 : boost::foreach_detail_::or_( \ + boost::foreach_detail_::is_array_(COL) \ + , BOOST_FOREACH_IS_NONCOPYABLE(COL) \ + , boost::foreach_detail_::not_(boost::foreach_detail_::is_const_(COL))) \ + , true ? 0 : BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL) \ + , &BOOST_FOREACH_ID(_foreach_is_rvalue))) + +#elif !defined(BOOST_FOREACH_NO_RVALUE_DETECTION) +/////////////////////////////////////////////////////////////////////////////// +// R-values supported here, const R-values NOT supported here +/////////////////////////////////////////////////////////////////////////////// + +// No variable is needed to track the rvalue-ness of the collection expression +# define BOOST_FOREACH_PREAMBLE() \ + BOOST_FOREACH_SUPPRESS_WARNINGS() + +// Evaluate the collection expression +# define BOOST_FOREACH_EVALUATE(COL) \ + (COL) + +// Determine whether the collection expression is an lvalue or an rvalue. +// NOTE: this gets the answer wrong for const rvalues. +# define BOOST_FOREACH_SHOULD_COPY(COL) \ + (true ? 0 : boost::foreach_detail_::or_( \ + boost::foreach_detail_::is_rvalue_((COL), 0) \ + , BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL))) + +#else +/////////////////////////////////////////////////////////////////////////////// +// R-values NOT supported here +/////////////////////////////////////////////////////////////////////////////// + +// No variable is needed to track the rvalue-ness of the collection expression +# define BOOST_FOREACH_PREAMBLE() \ + BOOST_FOREACH_SUPPRESS_WARNINGS() + +// Evaluate the collection expression +# define BOOST_FOREACH_EVALUATE(COL) \ + (COL) + +// Can't use rvalues with BOOST_FOREACH (unless they are lightweight proxies) +# define BOOST_FOREACH_SHOULD_COPY(COL) \ + (true ? 0 : BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL)) + +#endif + +#define BOOST_FOREACH_CONTAIN(COL) \ + boost::foreach_detail_::contain( \ + BOOST_FOREACH_EVALUATE(COL) \ + , BOOST_FOREACH_SHOULD_COPY(COL)) + +#define BOOST_FOREACH_BEGIN(COL) \ + boost::foreach_detail_::begin( \ + BOOST_FOREACH_ID(_foreach_col) \ + , BOOST_FOREACH_TYPEOF(COL) \ + , BOOST_FOREACH_SHOULD_COPY(COL)) + +#define BOOST_FOREACH_END(COL) \ + boost::foreach_detail_::end( \ + BOOST_FOREACH_ID(_foreach_col) \ + , BOOST_FOREACH_TYPEOF(COL) \ + , BOOST_FOREACH_SHOULD_COPY(COL)) + +#define BOOST_FOREACH_DONE(COL) \ + boost::foreach_detail_::done( \ + BOOST_FOREACH_ID(_foreach_cur) \ + , BOOST_FOREACH_ID(_foreach_end) \ + , BOOST_FOREACH_TYPEOF(COL)) + +#define BOOST_FOREACH_NEXT(COL) \ + boost::foreach_detail_::next( \ + BOOST_FOREACH_ID(_foreach_cur) \ + , BOOST_FOREACH_TYPEOF(COL)) + +#define BOOST_FOREACH_DEREF(COL) \ + boost::foreach_detail_::deref( \ + BOOST_FOREACH_ID(_foreach_cur) \ + , BOOST_FOREACH_TYPEOF(COL)) + +#define BOOST_FOREACH_RBEGIN(COL) \ + boost::foreach_detail_::rbegin( \ + BOOST_FOREACH_ID(_foreach_col) \ + , BOOST_FOREACH_TYPEOF(COL) \ + , BOOST_FOREACH_SHOULD_COPY(COL)) + +#define BOOST_FOREACH_REND(COL) \ + boost::foreach_detail_::rend( \ + BOOST_FOREACH_ID(_foreach_col) \ + , BOOST_FOREACH_TYPEOF(COL) \ + , BOOST_FOREACH_SHOULD_COPY(COL)) + +#define BOOST_FOREACH_RDONE(COL) \ + boost::foreach_detail_::rdone( \ + BOOST_FOREACH_ID(_foreach_cur) \ + , BOOST_FOREACH_ID(_foreach_end) \ + , BOOST_FOREACH_TYPEOF(COL)) + +#define BOOST_FOREACH_RNEXT(COL) \ + boost::foreach_detail_::rnext( \ + BOOST_FOREACH_ID(_foreach_cur) \ + , BOOST_FOREACH_TYPEOF(COL)) + +#define BOOST_FOREACH_RDEREF(COL) \ + boost::foreach_detail_::rderef( \ + BOOST_FOREACH_ID(_foreach_cur) \ + , BOOST_FOREACH_TYPEOF(COL)) + +/////////////////////////////////////////////////////////////////////////////// +// BOOST_FOREACH +// +// For iterating over collections. Collections can be +// arrays, null-terminated strings, or STL containers. +// The loop variable can be a value or reference. For +// example: +// +// std::list int_list(/*stuff*/); +// BOOST_FOREACH(int &i, int_list) +// { +// /* +// * loop body goes here. +// * i is a reference to the int in int_list. +// */ +// } +// +// Alternately, you can declare the loop variable first, +// so you can access it after the loop finishes. Obviously, +// if you do it this way, then the loop variable cannot be +// a reference. +// +// int i; +// BOOST_FOREACH(i, int_list) +// { ... } +// +#define BOOST_FOREACH(VAR, COL) \ + BOOST_FOREACH_PREAMBLE() \ + if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_col) = BOOST_FOREACH_CONTAIN(COL)) {} else \ + if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_cur) = BOOST_FOREACH_BEGIN(COL)) {} else \ + if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_end) = BOOST_FOREACH_END(COL)) {} else \ + for (bool BOOST_FOREACH_ID(_foreach_continue) = true; \ + BOOST_FOREACH_ID(_foreach_continue) && !BOOST_FOREACH_DONE(COL); \ + BOOST_FOREACH_ID(_foreach_continue) ? BOOST_FOREACH_NEXT(COL) : (void)0) \ + if (boost::foreach_detail_::set_false(BOOST_FOREACH_ID(_foreach_continue))) {} else \ + for (VAR = BOOST_FOREACH_DEREF(COL); !BOOST_FOREACH_ID(_foreach_continue); BOOST_FOREACH_ID(_foreach_continue) = true) + +/////////////////////////////////////////////////////////////////////////////// +// BOOST_REVERSE_FOREACH +// +// For iterating over collections in reverse order. In +// all other respects, BOOST_REVERSE_FOREACH is like +// BOOST_FOREACH. +// +#define BOOST_REVERSE_FOREACH(VAR, COL) \ + BOOST_FOREACH_PREAMBLE() \ + if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_col) = BOOST_FOREACH_CONTAIN(COL)) {} else \ + if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_cur) = BOOST_FOREACH_RBEGIN(COL)) {} else \ + if (boost::foreach_detail_::auto_any_t BOOST_FOREACH_ID(_foreach_end) = BOOST_FOREACH_REND(COL)) {} else \ + for (bool BOOST_FOREACH_ID(_foreach_continue) = true; \ + BOOST_FOREACH_ID(_foreach_continue) && !BOOST_FOREACH_RDONE(COL); \ + BOOST_FOREACH_ID(_foreach_continue) ? BOOST_FOREACH_RNEXT(COL) : (void)0) \ + if (boost::foreach_detail_::set_false(BOOST_FOREACH_ID(_foreach_continue))) {} else \ + for (VAR = BOOST_FOREACH_RDEREF(COL); !BOOST_FOREACH_ID(_foreach_continue); BOOST_FOREACH_ID(_foreach_continue) = true) + +#endif diff --git a/utils/boost_idb/boost/foreach_fwd.hpp b/utils/boost_idb/boost/foreach_fwd.hpp new file mode 100644 index 00000000..4e0bb370 --- /dev/null +++ b/utils/boost_idb/boost/foreach_fwd.hpp @@ -0,0 +1,51 @@ +/////////////////////////////////////////////////////////////////////////////// +// foreach.hpp header file +// +// Copyright 2010 Eric Niebler. +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// See http://www.boost.org/libs/foreach for documentation +// +// Credits: +// Kazutoshi Satoda: for suggesting the need for a _fwd header for foreach's +// customization points. + +#ifndef BOOST_FOREACH_FWD_HPP +#define BOOST_FOREACH_FWD_HPP + +// This must be at global scope, hence the uglified name +enum boost_foreach_argument_dependent_lookup_hack +{ + boost_foreach_argument_dependent_lookup_hack_value +}; + +namespace boost +{ + +namespace foreach +{ + /////////////////////////////////////////////////////////////////////////////// + // boost::foreach::tag + // + typedef boost_foreach_argument_dependent_lookup_hack tag; + + /////////////////////////////////////////////////////////////////////////////// + // boost::foreach::is_lightweight_proxy + // Specialize this for user-defined collection types if they are inexpensive to copy. + // This tells BOOST_FOREACH it can avoid the rvalue/lvalue detection stuff. + template + struct is_lightweight_proxy; + + /////////////////////////////////////////////////////////////////////////////// + // boost::foreach::is_noncopyable + // Specialize this for user-defined collection types if they cannot be copied. + // This also tells BOOST_FOREACH to avoid the rvalue/lvalue detection stuff. + template + struct is_noncopyable; + +} // namespace foreach + +} // namespace boost + +#endif diff --git a/utils/boost_idb/boost/function.hpp b/utils/boost_idb/boost/function.hpp index b72842bb..bdb27691 100644 --- a/utils/boost_idb/boost/function.hpp +++ b/utils/boost_idb/boost/function.hpp @@ -23,8 +23,8 @@ // in anything that may be included by function_template.hpp doesn't break #include -// Older Visual Age C++ version do not handle the file iteration well -#if BOOST_WORKAROUND(__IBMCPP__, >= 500) && BOOST_WORKAROUND(__IBMCPP__, < 800) +// Visual Age C++ doesn't handle the file iteration well +#if BOOST_WORKAROUND(__IBMCPP__, >= 500) # if BOOST_FUNCTION_MAX_ARGS >= 0 # include # endif diff --git a/utils/boost_idb/boost/function/function_base.hpp b/utils/boost_idb/boost/function/function_base.hpp index 78b7dd1e..fe9bbbe3 100644 --- a/utils/boost_idb/boost/function/function_base.hpp +++ b/utils/boost_idb/boost/function/function_base.hpp @@ -203,11 +203,11 @@ namespace boost { { switch (op) { case clone_functor_tag: - out_buffer.obj_ref = in_buffer.obj_ref; + out_buffer.obj_ref.obj_ptr = in_buffer.obj_ref.obj_ptr; return; case move_functor_tag: - out_buffer.obj_ref = in_buffer.obj_ref; + out_buffer.obj_ref.obj_ptr = in_buffer.obj_ref.obj_ptr; in_buffer.obj_ref.obj_ptr = 0; return; @@ -315,18 +315,14 @@ namespace boost { if (op == clone_functor_tag || op == move_functor_tag) { const functor_type* in_functor = reinterpret_cast(&in_buffer.data); - new (reinterpret_cast(&out_buffer.data)) functor_type(*in_functor); + new ((void*)&out_buffer.data) functor_type(*in_functor); if (op == move_functor_tag) { - functor_type* f = reinterpret_cast(&in_buffer.data); - (void)f; // suppress warning about the value of f not being used (MSVC) - f->~Functor(); + reinterpret_cast(&in_buffer.data)->~Functor(); } } else if (op == destroy_functor_tag) { // Some compilers (Borland, vc6, ...) are unhappy with ~functor_type. - functor_type* f = reinterpret_cast(&out_buffer.data); - (void)f; // suppress warning about the value of f not being used (MSVC) - f->~Functor(); + reinterpret_cast(&out_buffer.data)->~Functor(); } else if (op == check_functor_type_tag) { const detail::sp_typeinfo& check_type = *out_buffer.type.type; @@ -373,10 +369,8 @@ namespace boost { // Clone the functor // GCC 2.95.3 gets the CV qualifiers wrong here, so we // can't do the static_cast that we should do. - // jewillco: Changing this to static_cast because GCC 2.95.3 is - // obsolete. const functor_type* f = - static_cast(in_buffer.obj_ptr); + (const functor_type*)(in_buffer.obj_ptr); functor_type* new_f = new functor_type(*f); out_buffer.obj_ptr = new_f; } else if (op == move_functor_tag) { @@ -480,7 +474,7 @@ namespace boost { // GCC 2.95.3 gets the CV qualifiers wrong here, so we // can't do the static_cast that we should do. const functor_wrapper_type* f = - static_cast(in_buffer.obj_ptr); + (const functor_wrapper_type*)(in_buffer.obj_ptr); wrapper_allocator_type wrapper_allocator(static_cast(*f)); wrapper_allocator_pointer_type copy = wrapper_allocator.allocate(1); wrapper_allocator.construct(copy, *f); @@ -677,7 +671,7 @@ class function_base detail::function::check_functor_type_tag); // GCC 2.95.3 gets the CV qualifiers wrong here, so we // can't do the static_cast that we should do. - return static_cast(type_result.obj_ptr); + return (const Functor*)(type_result.obj_ptr); } template @@ -721,7 +715,7 @@ class function_base public: // should be protected, but GCC 2.95.3 will fail to allow access detail::function::vtable_base* get_vtable() const { return reinterpret_cast( - reinterpret_cast(vtable) & ~static_cast(0x01)); + reinterpret_cast(vtable) & ~(std::size_t)0x01); } bool has_trivial_copy_and_destroy() const { diff --git a/utils/boost_idb/boost/function/function_template.hpp b/utils/boost_idb/boost/function/function_template.hpp index 73ed72ef..6a99109a 100644 --- a/utils/boost_idb/boost/function/function_template.hpp +++ b/utils/boost_idb/boost/function/function_template.hpp @@ -486,19 +486,19 @@ namespace boost { BOOST_FUNCTION_TEMPLATE_ARGS); template - bool assign_to(F f, function_buffer& functor) const + bool assign_to(F f, function_buffer& functor) { typedef typename get_function_tag::type tag; return assign_to(f, functor, tag()); } template - bool assign_to_a(F f, function_buffer& functor, Allocator a) const + bool assign_to_a(F f, function_buffer& functor, Allocator a) { typedef typename get_function_tag::type tag; return assign_to_a(f, functor, a, tag()); } - void clear(function_buffer& functor) const + void clear(function_buffer& functor) { if (base.manager) base.manager(functor, functor, destroy_functor_tag); @@ -508,13 +508,13 @@ namespace boost { // Function pointers template bool - assign_to(FunctionPtr f, function_buffer& functor, function_ptr_tag) const + assign_to(FunctionPtr f, function_buffer& functor, function_ptr_tag) { this->clear(functor); if (f) { // should be a reinterpret cast, but some compilers insist // on giving cv-qualifiers to free functions - functor.func_ptr = reinterpret_cast(f); + functor.func_ptr = (void (*)())(f); return true; } else { return false; @@ -522,7 +522,7 @@ namespace boost { } template bool - assign_to_a(FunctionPtr f, function_buffer& functor, Allocator, function_ptr_tag) const + assign_to_a(FunctionPtr f, function_buffer& functor, Allocator, function_ptr_tag) { return assign_to(f,functor,function_ptr_tag()); } @@ -530,26 +530,26 @@ namespace boost { // Member pointers #if BOOST_FUNCTION_NUM_ARGS > 0 template - bool assign_to(MemberPtr f, function_buffer& functor, member_ptr_tag) const + bool assign_to(MemberPtr f, function_buffer& functor, member_ptr_tag) { // DPG TBD: Add explicit support for member function // objects, so we invoke through mem_fn() but we retain the // right target_type() values. if (f) { - this->assign_to(boost::mem_fn(f), functor); + this->assign_to(mem_fn(f), functor); return true; } else { return false; } } template - bool assign_to_a(MemberPtr f, function_buffer& functor, Allocator a, member_ptr_tag) const + bool assign_to_a(MemberPtr f, function_buffer& functor, Allocator a, member_ptr_tag) { // DPG TBD: Add explicit support for member function // objects, so we invoke through mem_fn() but we retain the // right target_type() values. if (f) { - this->assign_to_a(boost::mem_fn(f), functor, a); + this->assign_to_a(mem_fn(f), functor, a); return true; } else { return false; @@ -561,13 +561,13 @@ namespace boost { // Assign to a function object using the small object optimization template void - assign_functor(FunctionObj f, function_buffer& functor, mpl::true_) const + assign_functor(FunctionObj f, function_buffer& functor, mpl::true_) { - new (reinterpret_cast(&functor.data)) FunctionObj(f); + new ((void*)&functor.data) FunctionObj(f); } template void - assign_functor_a(FunctionObj f, function_buffer& functor, Allocator, mpl::true_) const + assign_functor_a(FunctionObj f, function_buffer& functor, Allocator, mpl::true_) { assign_functor(f,functor,mpl::true_()); } @@ -575,13 +575,13 @@ namespace boost { // Assign to a function object allocated on the heap. template void - assign_functor(FunctionObj f, function_buffer& functor, mpl::false_) const + assign_functor(FunctionObj f, function_buffer& functor, mpl::false_) { functor.obj_ptr = new FunctionObj(f); } template void - assign_functor_a(FunctionObj f, function_buffer& functor, Allocator a, mpl::false_) const + assign_functor_a(FunctionObj f, function_buffer& functor, Allocator a, mpl::false_) { typedef functor_wrapper functor_wrapper_type; typedef typename Allocator::template rebind::other @@ -596,7 +596,7 @@ namespace boost { template bool - assign_to(FunctionObj f, function_buffer& functor, function_obj_tag) const + assign_to(FunctionObj f, function_buffer& functor, function_obj_tag) { if (!boost::detail::function::has_empty_target(boost::addressof(f))) { assign_functor(f, functor, @@ -608,7 +608,7 @@ namespace boost { } template bool - assign_to_a(FunctionObj f, function_buffer& functor, Allocator a, function_obj_tag) const + assign_to_a(FunctionObj f, function_buffer& functor, Allocator a, function_obj_tag) { if (!boost::detail::function::has_empty_target(boost::addressof(f))) { assign_functor_a(f, functor, a, @@ -623,9 +623,9 @@ namespace boost { template bool assign_to(const reference_wrapper& f, - function_buffer& functor, function_obj_ref_tag) const + function_buffer& functor, function_obj_ref_tag) { - functor.obj_ref.obj_ptr = (void *)(f.get_pointer()); + functor.obj_ref.obj_ptr = (void *)f.get_pointer(); functor.obj_ref.is_const_qualified = is_const::value; functor.obj_ref.is_volatile_qualified = is_volatile::value; return true; @@ -633,7 +633,7 @@ namespace boost { template bool assign_to_a(const reference_wrapper& f, - function_buffer& functor, Allocator, function_obj_ref_tag) const + function_buffer& functor, Allocator, function_obj_ref_tag) { return assign_to(f,functor,function_obj_ref_tag()); } @@ -677,7 +677,7 @@ namespace boost { vtable_type* get_vtable() const { return reinterpret_cast( - reinterpret_cast(vtable) & ~static_cast(0x01)); + reinterpret_cast(vtable) & ~(std::size_t)0x01); } struct clear_type {}; @@ -748,16 +748,12 @@ namespace boost { { this->assign_to_own(f); } - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - BOOST_FUNCTION_FUNCTION(BOOST_FUNCTION_FUNCTION&& f) : function_base() - { - this->move_assign(f); - } -#endif - + ~BOOST_FUNCTION_FUNCTION() { clear(); } +#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) + // MSVC 6.0 and prior require all definitions to be inline, but + // these definitions can become very costly. result_type operator()(BOOST_FUNCTION_PARMS) const { if (this->empty()) @@ -766,6 +762,9 @@ namespace boost { return get_vtable()->invoker (this->functor BOOST_FUNCTION_COMMA BOOST_FUNCTION_ARGS); } +#else + result_type operator()(BOOST_FUNCTION_PARMS) const; +#endif // The distinction between when to use BOOST_FUNCTION_FUNCTION and // when to use self_type is obnoxious. MSVC cannot handle self_type as @@ -837,26 +836,6 @@ namespace boost { BOOST_CATCH_END return *this; } - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - // Move assignment from another BOOST_FUNCTION_FUNCTION - BOOST_FUNCTION_FUNCTION& operator=(BOOST_FUNCTION_FUNCTION&& f) - { - - if (&f == this) - return *this; - - this->clear(); - BOOST_TRY { - this->move_assign(f); - } BOOST_CATCH (...) { - vtable = 0; - BOOST_RETHROW; - } - BOOST_CATCH_END - return *this; - } -#endif void swap(BOOST_FUNCTION_FUNCTION& other) { @@ -885,7 +864,7 @@ namespace boost { #else private: struct dummy { - void nonnull() {} + void nonnull() {}; }; typedef void (dummy::*safe_bool)(); @@ -930,7 +909,7 @@ namespace boost { // static initialization. Otherwise, we will have a race // condition here in multi-threaded code. See // http://thread.gmane.org/gmane.comp.lib.boost.devel/164902/. - static const vtable_type stored_vtable = + static vtable_type stored_vtable = { { &manager_type::manage }, &invoker_type::invoke }; if (stored_vtable.assign_to(f, functor)) { @@ -938,7 +917,7 @@ namespace boost { if (boost::has_trivial_copy_constructor::value && boost::has_trivial_destructor::value && detail::function::function_allows_small_object_optimization::value) - value |= static_cast(0x01); + value |= (std::size_t)0x01; vtable = reinterpret_cast(value); } else vtable = 0; @@ -964,7 +943,7 @@ namespace boost { // static initialization. Otherwise, we will have a race // condition here in multi-threaded code. See // http://thread.gmane.org/gmane.comp.lib.boost.devel/164902/. - static const vtable_type stored_vtable = + static vtable_type stored_vtable = { { &manager_type::manage }, &invoker_type::invoke }; if (stored_vtable.assign_to_a(f, functor, a)) { @@ -972,7 +951,7 @@ namespace boost { if (boost::has_trivial_copy_constructor::value && boost::has_trivial_destructor::value && detail::function::function_allows_small_object_optimization::value) - value |= static_cast(0x01); + value |= (std::size_t)0x01; vtable = reinterpret_cast(value); } else vtable = 0; @@ -1019,6 +998,22 @@ namespace boost { f1.swap(f2); } +#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300) + template + typename BOOST_FUNCTION_FUNCTION< + R BOOST_FUNCTION_COMMA BOOST_FUNCTION_TEMPLATE_ARGS>::result_type + inline + BOOST_FUNCTION_FUNCTION + ::operator()(BOOST_FUNCTION_PARMS) const + { + if (this->empty()) + boost::throw_exception(bad_function_call()); + + return get_vtable()->invoker + (this->functor BOOST_FUNCTION_COMMA BOOST_FUNCTION_ARGS); + } +#endif + // Poison comparisons between boost::function objects of the same type. template void operator==(const BOOST_FUNCTION_FUNCTION< @@ -1090,26 +1085,12 @@ class function function(const base_type& f) : base_type(static_cast(f)){} -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - // Move constructors - function(self_type&& f): base_type(static_cast(f)){} - function(base_type&& f): base_type(static_cast(f)){} -#endif - self_type& operator=(const self_type& f) { self_type(f).swap(*this); return *this; } -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - self_type& operator=(self_type&& f) - { - self_type(static_cast(f)).swap(*this); - return *this; - } -#endif - template #ifndef BOOST_NO_SFINAE typename enable_if_c< @@ -1138,14 +1119,6 @@ class function self_type(f).swap(*this); return *this; } - -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - self_type& operator=(base_type&& f) - { - self_type(static_cast(f)).swap(*this); - return *this; - } -#endif }; #undef BOOST_FUNCTION_PARTIAL_SPEC diff --git a/utils/boost_idb/boost/function_types/components.hpp b/utils/boost_idb/boost/function_types/components.hpp deleted file mode 100644 index 53d81b60..00000000 --- a/utils/boost_idb/boost/function_types/components.hpp +++ /dev/null @@ -1,431 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_COMPONENTS_HPP_INCLUDED -#define BOOST_FT_COMPONENTS_HPP_INCLUDED - -#include - -#include - -#include -#include -#include - -#include - -#include -#include -#include - -#if BOOST_WORKAROUND(__BORLANDC__, <= 0x565) -# include - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -# include -#endif - -#ifndef BOOST_FT_NO_CV_FUNC_SUPPORT -# include -#endif - -#include - -#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -# if BOOST_FT_MAX_ARITY < 10 -# include -# elif BOOST_FT_MAX_ARITY < 20 -# include -# elif BOOST_FT_MAX_ARITY < 30 -# include -# elif BOOST_FT_MAX_ARITY < 40 -# include -# elif BOOST_FT_MAX_ARITY < 50 -# include -# endif -#else -# include -#endif - -#include -#include - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -namespace boost -{ - namespace function_types - { - - using mpl::placeholders::_; - - template< typename T, typename ClassTypeTransform = add_reference<_> > - struct components; - - namespace detail - { - template struct components_impl; -#if BOOST_WORKAROUND(__BORLANDC__, <= 0x565) - template struct components_bcc; -#endif - } - - template - struct components -#if !BOOST_WORKAROUND(__BORLANDC__, <= 0x565) - : detail::components_impl -#else - : detail::components_bcc::type,T, - ClassTypeTransform> -#endif - { - typedef components type; - - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,components,(T,ClassTypeTransform)) - }; - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - namespace detail { - - struct components_mpl_sequence_tag; - - struct components_non_func_base - { - typedef mpl::vector0<> types; - typedef void function_arity; - - typedef detail::constant<0> bits; - typedef detail::constant<0> mask; - - typedef components_mpl_sequence_tag tag; - }; - - template - < typename Components - , typename IfTagged - , typename ThenTag - , typename DefaultBase = components_non_func_base - > - struct retagged_if - : mpl::if_ - < detail::represents_impl - , detail::changed_tag - , DefaultBase - >::type - { }; - - // We detect plain function types and function references as function - // pointers by recursive instantiation of components_impl. - // The third specialization of components_impl makes sure the recursion - // terminates (when adding pointers). - template - struct components_impl - : detail::retagged_if - < detail::components_impl - , pointer_tag, /* --> */ function_tag > - { }; - template - struct components_impl - : detail::retagged_if - < detail::components_impl - , pointer_tag, /* --> */ reference_tag > - { }; - -#if !BOOST_FT_NO_CV_FUNC_SUPPORT - // Retry the type with a member pointer attached to detect cv functions - class a_class; - - template - struct cv_func_base - : detail::retagged_if - { - typedef typename - mpl::remove - < typename Base::types - , typename detail::class_transform::type>::type - types; - }; - - template - struct components_impl - : mpl::if_ - < detail::represents_impl< detail::components_impl - , member_pointer_tag > - , detail::cv_func_base< detail::components_impl, T, L> - , components_non_func_base - >::type - { }; - - template - struct components_impl - : components_non_func_base - { }; -#else - template - struct components_impl - : components_non_func_base - { }; -#endif - - template - struct components_impl - : components_impl - { }; - - template - struct components_impl - : components_impl - { }; - - template - struct components_impl - : components_impl - { }; - - template - struct components_impl - : components_impl - { }; - - template - struct components_impl - : components_impl - { }; - - template - struct components_impl - : components_impl - { }; - - - template - struct member_obj_ptr_result - { typedef T & type; }; - - template - struct member_obj_ptr_result - { typedef T const & type; }; - - template - struct member_obj_ptr_result - { typedef T volatile & type; }; - - template - struct member_obj_ptr_result - { typedef T const volatile & type; }; - - template - struct member_obj_ptr_result - { typedef T & type; }; - - template - struct member_obj_ptr_result - { typedef T & type; }; - - template - struct member_obj_ptr_result - { typedef T & type; }; - - template - struct member_obj_ptr_result - { typedef T & type; }; - - template - struct member_obj_ptr_components - : member_object_pointer_base - { - typedef function_types::components type; - typedef components_mpl_sequence_tag tag; - - typedef mpl::integral_c function_arity; - - typedef mpl::vector2< typename detail::member_obj_ptr_result::type, - typename detail::class_transform::type > types; - }; - -#if !BOOST_WORKAROUND(__BORLANDC__, <= 0x565) -# define BOOST_FT_variations BOOST_FT_pointer|BOOST_FT_member_pointer - - template - struct components_impl - : member_obj_ptr_components - { }; - -#else -# define BOOST_FT_variations BOOST_FT_pointer - - // This workaround removes the member pointer from the type to allow - // detection of member function pointers with BCC. - template - struct components_impl - : detail::retagged_if - < detail::components_impl::type *, L> - , pointer_tag, /* --> */ member_function_pointer_tag - , member_obj_ptr_components > - { }; - - // BCC lets us test the cv-qualification of a function type by template - // partial specialization - so we use this bug feature to find out the - // member function's cv-qualification (unfortunately there are some - // invisible modifiers that impose some limitations on these types even if - // we remove the qualifiers, So we cannot exploit the same bug to make the - // library work for cv-qualified function types). - template struct encode_cv - { typedef char (& type)[1]; BOOST_STATIC_CONSTANT(std::size_t, value = 1); }; - template struct encode_cv - { typedef char (& type)[2]; BOOST_STATIC_CONSTANT(std::size_t, value = 2); }; - template struct encode_cv - { typedef char (& type)[3]; BOOST_STATIC_CONSTANT(std::size_t, value = 3); }; - template struct encode_cv - { typedef char (& type)[4]; BOOST_STATIC_CONSTANT(std::size_t, value = 4); }; - - // For member function pointers we have to use a function template (partial - // template specialization for a member pointer drops the cv qualification - // of the function type). - template - typename encode_cv::type mfp_cv_tester(T C::*); - - template struct encode_mfp_cv - { - BOOST_STATIC_CONSTANT(std::size_t, value = - sizeof(detail::mfp_cv_tester((T)0L))); - }; - - // Associate bits with the CV codes above. - template struct cv_tag_mfp_impl; - - template struct cv_tag_mfp - : detail::cv_tag_mfp_impl - < ::boost::function_types::detail::encode_mfp_cv::value > - { }; - - template<> struct cv_tag_mfp_impl<1> : non_cv { }; - template<> struct cv_tag_mfp_impl<2> : const_non_volatile { }; - template<> struct cv_tag_mfp_impl<3> : volatile_non_const { }; - template<> struct cv_tag_mfp_impl<4> : cv_qualified { }; - - // Metafunction to decode the cv code and apply it to a type. - // We add a pointer, because otherwise cv-qualifiers won't stick (another bug). - template struct decode_cv; - - template struct decode_cv : mpl::identity {}; - template struct decode_cv : mpl::identity {}; - template struct decode_cv : mpl::identity {}; - template struct decode_cv - : mpl::identity {}; - - // The class type transformation comes after adding cv-qualifiers. We have - // wrap it to remove the pointer added in decode_cv_impl. - template struct bcc_class_transform_impl; - template struct bcc_class_transform_impl - : class_transform - { }; - - template struct bcc_class_transform - : bcc_class_transform_impl - < typename decode_cv - < T - , ::boost::function_types::detail::encode_mfp_cv::value - >::type - , L - > - { }; - - // After extracting the member pointee from the type the class type is still - // in the type (somewhere -- you won't see with RTTI, that is) and that type - // is flagged unusable and *not* identical to the nonmember function type. - // We can, however, decompose this type via components_impl but surprisingly - // a pointer to the const qualified class type pops up again as the first - // parameter type. - // We have to replace this type with the properly cv-qualified and - // transformed class type, integrate the cv qualification into the bits. - template - struct mfp_components; - - - template - struct mfp_components - { - private: - typedef typename mpl::front::type result_type; - typedef typename detail::bcc_class_transform::type class_type; - - typedef mpl::vector2 result_and_class_type; - - typedef typename - mpl::advance - < typename mpl::begin::type - , typename mpl::if_ - < mpl::equal_to< typename detail::classifier::function_arity - , typename Base::function_arity > - , mpl::integral_c , mpl::integral_c - >::type - >::type - from; - typedef typename mpl::end::type to; - - typedef mpl::iterator_range param_types; - - typedef mpl::joint_view< result_and_class_type, param_types> types_view; - public: - - typedef typename - mpl::reverse_copy > >::type - types; - - typedef typename - function_types::tag< Base, detail::cv_tag_mfp >::bits - bits; - - typedef typename Base::mask mask; - - typedef typename detail::classifier::function_arity function_arity; - - typedef components_mpl_sequence_tag tag; - }; - - // Now put it all together: detect cv-qualification of function types and do - // the weird transformations above for member function pointers. - template - struct components_bcc - : mpl::if_ - < detail::represents_impl< detail::components_impl - , member_function_pointer_tag> - , detail::mfp_components,T,OrigT,L> - , detail::components_impl - >::type - { }; - -#endif // end of BORLAND WORKAROUND - -#define BOOST_FT_al_path boost/function_types/detail/components_impl -#include - - } } // namespace function_types::detail - - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::components) - -} // namespace ::boost - -#include -#include - -#endif - diff --git a/utils/boost_idb/boost/function_types/config/cc_names.hpp b/utils/boost_idb/boost/function_types/config/cc_names.hpp deleted file mode 100644 index ab69d646..00000000 --- a/utils/boost_idb/boost/function_types/config/cc_names.hpp +++ /dev/null @@ -1,31 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_CONFIG_CC_NAMES_HPP_INCLUDED -#define BOOST_FT_CONFIG_CC_NAMES_HPP_INCLUDED - -#define BOOST_FT_BUILTIN_CC_NAMES \ - (( IMPLICIT , implicit_cc , BOOST_PP_EMPTY ))\ - (( CDECL , cdecl_cc , BOOST_PP_IDENTITY(__cdecl ) ))\ - (( STDCALL , stdcall_cc , BOOST_PP_IDENTITY(__stdcall ) ))\ - (( PASCAL , pascal_cc , BOOST_PP_IDENTITY(pascal ) ))\ - (( FASTCALL , fastcall_cc , BOOST_PP_IDENTITY(__fastcall) ))\ - (( CLRCALL , clrcall_cc , BOOST_PP_IDENTITY(__clrcall ) ))\ - (( THISCALL , thiscall_cc , BOOST_PP_IDENTITY(__thiscall) ))\ - (( IMPLICIT_THISCALL , thiscall_cc , BOOST_PP_EMPTY )) - -// append user-defined cc names to builtin ones -#ifdef BOOST_FT_CC_NAMES -# define BOOST_FT_CC_NAMES_SEQ BOOST_FT_BUILTIN_CC_NAMES BOOST_FT_CC_NAMES -# define BOOST_FT_CC_PREPROCESSING 1 -#else -# define BOOST_FT_CC_NAMES_SEQ BOOST_FT_BUILTIN_CC_NAMES -#endif - -#endif - diff --git a/utils/boost_idb/boost/function_types/config/compiler.hpp b/utils/boost_idb/boost/function_types/config/compiler.hpp deleted file mode 100644 index 151c8567..00000000 --- a/utils/boost_idb/boost/function_types/config/compiler.hpp +++ /dev/null @@ -1,116 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_CONFIG_COMPILER_HPP_INCLUDED -#define BOOST_FT_CONFIG_COMPILER_HPP_INCLUDED - -#include -#include - -#if defined(BOOST_MSVC) - -# if BOOST_MSVC < 1310 -# error "unsupported compiler version" -# endif - -# ifdef BOOST_FT_AUTODETECT_CALLING_CONVENTIONS - - // enable clrcall calling covention (call to .NET managed code) when - // compiling with /clr -# if BOOST_MSVC >= 1400 && defined(__cplusplus_cli) -# ifndef BOOST_FT_CC_CLRCALL -# define BOOST_FT_CC_CLRCALL callable_builtin -# endif -# endif - - // Intel x86 architecture specific calling conventions -# ifdef _M_IX86 -# define BOOST_FT_COMMON_X86_CCs callable_builtin -# if BOOST_MSVC < 1400 - // version 7.1 is missing a keyword to specify the thiscall cc ... -# ifndef BOOST_FT_CC_IMPLICIT_THISCALL -# define BOOST_FT_CC_IMPLICIT_THISCALL non_variadic|member|callable_builtin -# ifndef BOOST_FT_CONFIG_OK -# pragma message("INFO| /Gd /Gr /Gz will compiler options will cause") -# pragma message("INFO| a compile error.") -# pragma message("INFO| Reconfigure Boost.FunctionTypes in this case.") -# pragma message("INFO| This message can be suppressed by defining") -# pragma message("INFO| BOOST_FT_CONFIG_OK.") -# endif -# endif -# else - // ...introduced in version 8 -# ifndef BOOST_FT_CC_THISCALL -# define BOOST_FT_CC_THISCALL non_variadic|member|callable_builtin -# endif -# endif -# endif -# endif - -#elif defined(__GNUC__) && !defined(BOOST_INTEL_LINUX) - -# if __GNUC__ < 3 -# error "unsupported compiler version" -# endif - -# ifdef BOOST_FT_AUTODETECT_CALLING_CONVENTIONS - -# if defined(__i386__) -# // see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=20439 -# // see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=29328 -# if BOOST_WORKAROUND(__GNUC__,BOOST_TESTED_AT(4)) -# ifndef BOOST_FT_CC_IMPLICIT -# define BOOST_FT_CC_IMPLICIT member|callable_builtin -# endif -# define BOOST_FT_COMMON_X86_CCs non_member|callable_builtin -# else -# define BOOST_FT_COMMON_X86_CCs callable_builtin -# endif -# else -# ifndef BOOST_FT_CC_IMPLICIT -# define BOOST_FT_CC_IMPLICIT callable_builtin -# endif -# endif -# endif - -# if (defined(BOOST_FT_CC_CDECL) || defined(BOOST_FT_COMMON_X86_CCs)) \ - && !defined(__cdecl) -# define __cdecl __attribute__((__cdecl__)) -# endif -# if (defined(BOOST_FT_CC_STDCALL) || defined(BOOST_FT_COMMON_X86_CCs)) \ - && !defined(__stdcall) -# define __stdcall __attribute__((__stdcall__)) -# endif -# if (defined(BOOST_FT_CC_FASTCALL) || defined(BOOST_FT_COMMON_X86_CCs)) \ - && !defined(__fastcall) -# define __fastcall __attribute__((__fastcall__)) -# endif - -#elif defined(__BORLANDC__) - -# if __BORLANDC__ < 0x550 -# error "unsupported compiler version" -# elif __BORLANDC__ > 0x565 -# pragma message("WARNING: library untested with this compiler version") -# endif - -# ifdef BOOST_FT_AUTODETECT_CALLING_CONVENTIONS -# define BOOST_FT_COMMON_X86_CCs callable_builtin -# endif - - // syntactic specialities of cc specifier -# define BOOST_FT_SYNTAX(result,lparen,cc_spec,type_mod,name,rparen) \ - result() cc_spec() lparen() type_mod() name() rparen() -#else - // only enable default calling convention -# define BOOST_FT_CC_IMPLICIT callable_builtin -#endif - - -#endif - diff --git a/utils/boost_idb/boost/function_types/config/config.hpp b/utils/boost_idb/boost/function_types/config/config.hpp deleted file mode 100644 index 7ec8e1e8..00000000 --- a/utils/boost_idb/boost/function_types/config/config.hpp +++ /dev/null @@ -1,59 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_CONFIG_HPP_INCLUDED -#define BOOST_FT_CONFIG_HPP_INCLUDED - -#include -#include - -// maximum allowed arity -#ifndef BOOST_FT_MAX_ARITY -#define BOOST_FT_MAX_ARITY 20 -#endif - -// the most common calling conventions for x86 architecture can be enabled at -// once in the compiler config -#ifdef BOOST_FT_COMMON_X86_CCs -# ifndef BOOST_FT_CC_CDECL -# define BOOST_FT_CC_CDECL BOOST_FT_COMMON_X86_CCs -# endif -# ifndef BOOST_FT_CC_STDCALL -# define BOOST_FT_CC_STDCALL non_variadic|BOOST_FT_COMMON_X86_CCs -# endif -# ifndef BOOST_FT_CC_FASTCALL -# define BOOST_FT_CC_FASTCALL non_variadic|BOOST_FT_COMMON_X86_CCs -# endif -#endif - -// where to place the cc specifier (the common way) -#ifndef BOOST_FT_SYNTAX -# define BOOST_FT_SYNTAX(result,lparen,cc_spec,type_mod,name,rparen) \ - result() lparen() cc_spec() type_mod() name() rparen() -#endif - -// param for nullary functions -// set to "void" for compilers that require nullary functions to read -// "R (void)" in template partial specialization -#ifndef BOOST_FT_NULLARY_PARAM -#define BOOST_FT_NULLARY_PARAM -#endif - -// there is a pending defect report on cv qualified function types, so support -// for these types is disabled, unless for compilers where it's known to work -#ifndef BOOST_FT_NO_CV_FUNC_SUPPORT -#define BOOST_FT_NO_CV_FUNC_SUPPORT 1 -#endif - -// full preprocessing implies preprocessing of the ccs -#if defined(BOOST_FT_PREPROCESSING_MODE) && !defined(BOOST_FT_CC_PREPROCESSING) -# define BOOST_FT_CC_PREPROCESSING 1 -#endif - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/class_transform.hpp b/utils/boost_idb/boost/function_types/detail/class_transform.hpp deleted file mode 100644 index ef9a2253..00000000 --- a/utils/boost_idb/boost/function_types/detail/class_transform.hpp +++ /dev/null @@ -1,62 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_CLASS_TRANSFORM_HPP_INCLUDED -#define BOOST_FT_DETAIL_CLASS_TRANSFORM_HPP_INCLUDED - -#include -#include -#include -#include - -#include -#include -#include - -namespace boost { namespace function_types { namespace detail { - -using mpl::placeholders::_; - -// Transformation metafunction for the class type of member function pointers. -template -struct class_transform -{ typedef typename mpl::apply1::type type; }; - - -#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -// We can short-circuit the mechanism implemented in the primary template for -// the most common lambda expression and save both the "un-lambdaing" and the -// type traits invocation (we know that T can only be a class type). - -template struct class_transform< T, mpl::identity<_> > -{ typedef T type; }; - -template struct class_transform< T, add_reference<_> > -{ typedef T & type; }; - -template struct class_transform< T, add_pointer<_> > -{ typedef T * type; }; - -template struct class_transform< T, remove_cv<_> > -{ typedef typename boost::remove_cv::type type; }; - -template struct class_transform< T, add_reference< remove_cv<_> > > -{ typedef typename boost::remove_cv::type & type; }; - -template struct class_transform< T, add_pointer< remove_cv<_> > > -{ typedef typename boost::remove_cv::type * type; }; - -template struct class_transform< T, mpl::always > -{ typedef U type; }; -#endif - - -} } } // namespace ::boost::function_types::detail - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/classifier.hpp b/utils/boost_idb/boost/function_types/detail/classifier.hpp deleted file mode 100644 index 03f3419b..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier.hpp +++ /dev/null @@ -1,82 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_CLASSIFIER_HPP_INCLUDED -#define BOOST_FT_DETAIL_CLASSIFIER_HPP_INCLUDED - -#include -#include -#include -#include -#include - -#include -#include - -namespace boost { namespace function_types { namespace detail { - -template struct classifier; - -template struct char_array { typedef char (&type)[S]; }; - -template struct encode_charr -{ - typedef typename char_array< - ::boost::function_types::detail::encode_charr_impl::value - >::type type; -}; - -char BOOST_TT_DECL classifier_impl(...); - -#define BOOST_FT_variations BOOST_FT_function|BOOST_FT_pointer|\ - BOOST_FT_member_pointer - -#define BOOST_FT_type_function(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_LPAREN,cc,* BOOST_PP_EMPTY,name,BOOST_PP_RPAREN) - -#define BOOST_FT_type_function_pointer(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_LPAREN,cc,** BOOST_PP_EMPTY,name,BOOST_PP_RPAREN) - -#define BOOST_FT_type_member_function_pointer(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_LPAREN,cc,T0::** BOOST_PP_EMPTY,name,BOOST_PP_RPAREN) - -#define BOOST_FT_al_path boost/function_types/detail/classifier_impl -#include - -template struct classifier_bits -{ - static typename boost::add_reference::type tester; - - BOOST_STATIC_CONSTANT(bits_t,value = (bits_t)sizeof( - boost::function_types::detail::classifier_impl(& tester) - )-1); -}; - -template struct classifier -{ - typedef detail::constant< - ::boost::function_types::detail::decode_bits< - ::boost::function_types::detail::classifier_bits::value - >::tag_bits > - bits; - - typedef detail::full_mask mask; - - typedef detail::constant< - ::boost::function_types::detail::decode_bits< - ::boost::function_types::detail::classifier_bits::value - >::arity > - function_arity; -}; - - - -} } } // namespace ::boost::function_types::detail - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_0.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_0.hpp deleted file mode 100644 index e27f3c2d..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_0.hpp +++ /dev/null @@ -1,55 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -template< typename R > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (BOOST_FT_nullary_param BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_1.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_1.hpp deleted file mode 100644 index cca8027a..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity10_1.hpp +++ /dev/null @@ -1,52 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -template< typename R , typename T0 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) ( BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_0.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_0.hpp deleted file mode 100644 index f7a25169..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_0.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_1.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_1.hpp deleted file mode 100644 index 1cee2ba3..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity20_1.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_0.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_0.hpp deleted file mode 100644 index 6bc60f86..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_0.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_1.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_1.hpp deleted file mode 100644 index 743c263b..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity30_1.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_0.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_0.hpp deleted file mode 100644 index 161ac175..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_0.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_1.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_1.hpp deleted file mode 100644 index e3a99887..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity40_1.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_0.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_0.hpp deleted file mode 100644 index d05719a3..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_0.hpp +++ /dev/null @@ -1,53 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 , typename T49 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 , T49 BOOST_FT_ell) BOOST_FT_cv); - diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_1.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_1.hpp deleted file mode 100644 index 944eabaa..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/arity50_1.hpp +++ /dev/null @@ -1,52 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 BOOST_FT_ell) BOOST_FT_cv); -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 , typename T49 > -typename encode_charr ::type -classifier_impl(BOOST_FT_syntax(BOOST_FT_cc, BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 , T49 BOOST_FT_ell) BOOST_FT_cv); diff --git a/utils/boost_idb/boost/function_types/detail/classifier_impl/master.hpp b/utils/boost_idb/boost/function_types/detail/classifier_impl/master.hpp deleted file mode 100644 index 00b722e3..00000000 --- a/utils/boost_idb/boost/function_types/detail/classifier_impl/master.hpp +++ /dev/null @@ -1,33 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -#if BOOST_FT_ARITY_LOOP_PREFIX - -# ifndef BOOST_FT_DETAIL_CLASSIFIER_IMPL_MASTER_HPP_INCLUDED -# define BOOST_FT_DETAIL_CLASSIFIER_IMPL_MASTER_HPP_INCLUDED -# include -# endif - -# define BOOST_FT_type_name - -#elif BOOST_FT_ARITY_LOOP_IS_ITERATING - -template< BOOST_FT_tplargs(BOOST_PP_IDENTITY(typename)) > -typename encode_charr::type -classifier_impl(BOOST_FT_type); - -#elif BOOST_FT_ARITY_LOOP_SUFFIX - -# undef BOOST_FT_type_name - -#else -# error "attempt to use arity loop master file without loop" -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/components_as_mpl_sequence.hpp b/utils/boost_idb/boost/function_types/detail/components_as_mpl_sequence.hpp deleted file mode 100644 index 637b1b52..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_as_mpl_sequence.hpp +++ /dev/null @@ -1,138 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_COMPONENTS_AS_MPL_SEQUENCE_HPP_INCLUDED -#define BOOST_FT_DETAIL_COMPONENTS_AS_MPL_SEQUENCE_HPP_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { namespace mpl { - -template<> struct size_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > struct apply - : mpl::size - { }; -}; -template<> struct empty_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > struct apply - : mpl::empty - { }; -}; -template<> struct front_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > struct apply - : mpl::front - { }; -}; -template<> struct back_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > struct apply - : mpl::back - { }; -}; -template<> struct at_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S, typename N > struct apply - : mpl::at - { }; -}; -template<> struct begin_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > struct apply - : mpl::begin - { }; -}; -template<> struct end_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > struct apply - : mpl::end - { }; -}; -template<> struct clear_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > - struct apply - : S - { - typedef apply type; - typedef typename mpl::clear< typename S::types >::type types; - }; -}; -template<> -struct push_front_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S, typename T > - struct apply - : S - { - typedef apply type; - typedef typename mpl::push_front< typename S::types, T >::type types; - }; -}; -template<> -struct pop_front_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > - struct apply - : S - { - typedef apply type; - typedef typename mpl::pop_front< typename S::types >::type types; - }; -}; -template<> -struct push_back_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S, typename T > - struct apply - : S - { - typedef apply type; - typedef typename mpl::push_back< typename S::types, T >::type types; - }; -}; -template<> -struct pop_back_impl -< function_types::detail::components_mpl_sequence_tag > -{ - template< typename S > - struct apply - : S - { - typedef apply type; - typedef typename mpl::pop_back< typename S::types >::type types; - }; -}; - -} } // namespace ::boost::mpl - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity10_0.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity10_0.hpp deleted file mode 100644 index f96c6a9f..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity10_0.hpp +++ /dev/null @@ -1,132 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -template< typename R, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector1< R BOOST_FT_nullary_param > types; -}; -template< typename R , typename T0, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector2< R , T0 > types; -}; -template< typename R , typename T0 , typename T1, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector3< R , T0 , T1 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector4< R , T0 , T1 , T2 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector5< R , T0 , T1 , T2 , T3 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector6< R , T0 , T1 , T2 , T3 , T4 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector7< R , T0 , T1 , T2 , T3 , T4 , T5 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector8< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector9< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector10< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector11< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity10_1.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity10_1.hpp deleted file mode 100644 index 1b06a97a..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity10_1.hpp +++ /dev/null @@ -1,122 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -template< typename R , typename T0, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector2< R, typename class_transform ::type > types; -}; -template< typename R , typename T0 , typename T1, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector3< R, typename class_transform ::type , T1 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector4< R, typename class_transform ::type , T1 , T2 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector5< R, typename class_transform ::type , T1 , T2 , T3 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector6< R, typename class_transform ::type , T1 , T2 , T3 , T4 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector7< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector8< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector9< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector10< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector11< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity20_0.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity20_0.hpp deleted file mode 100644 index f6b2ca8a..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity20_0.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector12< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector13< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector14< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector15< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector16< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector17< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector18< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector19< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector20< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector21< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity20_1.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity20_1.hpp deleted file mode 100644 index 1688e6b3..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity20_1.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector12< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector13< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector14< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector15< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector16< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector17< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector18< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector19< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector20< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector21< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity30_0.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity30_0.hpp deleted file mode 100644 index e85eb3a0..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity30_0.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector22< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector23< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector24< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector25< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector26< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector27< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector28< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector29< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector30< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector31< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity30_1.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity30_1.hpp deleted file mode 100644 index 290d21ef..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity30_1.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector22< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector23< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector24< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector25< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector26< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector27< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector28< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector29< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector30< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector31< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity40_0.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity40_0.hpp deleted file mode 100644 index f1a24101..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity40_0.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector32< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector33< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector34< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector35< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector36< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector37< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector38< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector39< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector40< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector41< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity40_1.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity40_1.hpp deleted file mode 100644 index e1741cbb..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity40_1.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector32< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector33< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector34< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector35< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector36< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector37< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector38< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector39< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector40< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector41< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity50_0.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity50_0.hpp deleted file mode 100644 index 693a05df..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity50_0.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector42< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector43< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector44< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector45< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector46< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector47< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector48< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector49< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector50< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 , typename T49, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector51< R , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 , T49 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/arity50_1.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/arity50_1.hpp deleted file mode 100644 index 9bc16162..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/arity50_1.hpp +++ /dev/null @@ -1,123 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector42< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector43< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector44< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector45< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector46< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector47< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector48< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector49< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector50< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 > types; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 , typename T49, typename L> -struct components_impl -{ -typedef encode_bits bits; -typedef constant mask; -typedef function_types::components type; -typedef components_mpl_sequence_tag tag; -typedef mpl::integral_c function_arity; -typedef mpl::vector51< R, typename class_transform ::type , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 , T49 > types; -}; - diff --git a/utils/boost_idb/boost/function_types/detail/components_impl/master.hpp b/utils/boost_idb/boost/function_types/detail/components_impl/master.hpp deleted file mode 100644 index cd837262..00000000 --- a/utils/boost_idb/boost/function_types/detail/components_impl/master.hpp +++ /dev/null @@ -1,61 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -#if BOOST_FT_ARITY_LOOP_PREFIX - -# ifndef BOOST_FT_DETAIL_COMPONENTS_IMPL_MASTER_HPP_INCLUDED -# define BOOST_FT_DETAIL_COMPONENTS_IMPL_MASTER_HPP_INCLUDED -# include -# include -# include -# include -# include -# endif - -# define BOOST_FT_type_name - -# if !BOOST_FT_mfp - -# define BOOST_FT_types \ - R BOOST_PP_COMMA_IF(BOOST_FT_arity) BOOST_FT_params(BOOST_PP_EMPTY) -# else - -# define BOOST_FT_types \ - R, typename class_transform::type \ - BOOST_PP_COMMA_IF(BOOST_PP_DEC(BOOST_FT_arity)) \ - BOOST_FT_params(BOOST_PP_EMPTY) - -# endif - -#elif BOOST_FT_ARITY_LOOP_IS_ITERATING - -template< BOOST_FT_tplargs(BOOST_PP_IDENTITY(typename)), typename L> -struct components_impl -{ - typedef encode_bits bits; - typedef constant mask; - - typedef function_types::components type; - typedef components_mpl_sequence_tag tag; - - typedef mpl::integral_c function_arity; - - typedef BOOST_PP_CAT(mpl::vector,BOOST_FT_n)< BOOST_FT_types > types; -}; - -#elif BOOST_FT_ARITY_LOOP_SUFFIX - -# undef BOOST_FT_types -# undef BOOST_FT_type_name - -#else -# error "attempt to use arity loop master file without loop" -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/cv_traits.hpp b/utils/boost_idb/boost/function_types/detail/cv_traits.hpp deleted file mode 100644 index 242f45b3..00000000 --- a/utils/boost_idb/boost/function_types/detail/cv_traits.hpp +++ /dev/null @@ -1,134 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_CV_TRAITS_HPP_INCLUDED -#define BOOST_FT_DETAIL_CV_TRAITS_HPP_INCLUDED - -#include -#include - -#if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ - || BOOST_WORKAROUND(__BORLANDC__, <= 0x582) -# include -# include -# include -#endif - -#include - -namespace boost { namespace function_types { namespace detail { - -#if ! (defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ - || BOOST_WORKAROUND(__BORLANDC__, <= 0x582)) - -template struct cv_traits -{ typedef non_cv tag; typedef T type; }; -template struct cv_traits -{ typedef non_cv tag; typedef T type; }; -template struct cv_traits -{ typedef non_cv tag; typedef T type; }; -template struct cv_traits -{ typedef non_cv tag; typedef T type; }; -template struct cv_traits -{ typedef non_cv tag; typedef T type; }; -template struct cv_traits -{ typedef non_cv tag; typedef T type; }; - -template struct cv_traits -{ typedef const_non_volatile tag; typedef T type; }; -template struct cv_traits -{ typedef const_non_volatile tag; typedef T type; }; -template struct cv_traits -{ typedef const_non_volatile tag; typedef T type; }; -template struct cv_traits -{ typedef const_non_volatile tag; typedef T type; }; -template struct cv_traits -{ typedef const_non_volatile tag; typedef T type; }; -template struct cv_traits -{ typedef const_non_volatile tag; typedef T type; }; - -template struct cv_traits -{ typedef volatile_non_const tag; typedef T type; }; -template struct cv_traits -{ typedef volatile_non_const tag; typedef T type; }; -template struct cv_traits -{ typedef volatile_non_const tag; typedef T type; }; -template struct cv_traits -{ typedef volatile_non_const tag; typedef T type; }; -template struct cv_traits -{ typedef volatile_non_const tag; typedef T type; }; -template struct cv_traits -{ typedef volatile_non_const tag; typedef T type; }; - -template struct cv_traits -{ typedef cv_qualified tag; typedef T type; }; -template struct cv_traits -{ typedef cv_qualified tag; typedef T type; }; -template struct cv_traits -{ typedef cv_qualified tag; typedef T type; }; -template struct cv_traits -{ typedef cv_qualified tag; typedef T type; }; -template struct cv_traits -{ typedef cv_qualified tag; typedef T type; }; -template struct cv_traits -{ typedef cv_qualified tag; typedef T type; }; - -#else -template struct cv_tag_impl; - -template<> struct cv_tag_impl<1> { typedef non_cv type;}; -template<> struct cv_tag_impl<2> { typedef const_non_volatile type; }; -template<> struct cv_tag_impl<3> { typedef volatile_non_const type; }; -template<> struct cv_tag_impl<4> { typedef cv_qualified type; }; - -typedef char (& case_1)[1]; -typedef char (& case_2)[2]; -typedef char (& case_3)[3]; -typedef char (& case_4)[4]; - -template case_1 switch_cv(T *); -template case_2 switch_cv(T const *); -template case_3 switch_cv(T volatile *); -template case_4 switch_cv(T const volatile *); - -template T * ref_to_ptr(T &); -template T const * ref_to_ptr(T const &); -template T volatile * ref_to_ptr(T volatile &); -template T const volatile * ref_to_ptr(T const volatile &); - -template T * ref_to_ptr(T * const volatile &); - -template -struct cv_code -{ - static T _t; - BOOST_STATIC_CONSTANT(std::size_t, value = - sizeof(::boost::function_types::detail::switch_cv( - ::boost::function_types::detail::ref_to_ptr(_t) ) )); -}; - -template struct cv_traits -{ - typedef typename boost::function_types::detail::cv_tag_impl< - ::boost::function_types::detail::cv_code::value >::type - tag; - - // may require Boost.TypeTraits broken compiler specializations - // to work - typedef typename boost::remove_cv< - typename boost::remove_pointer< - typename boost::remove_reference::type - >::type - >::type type; -}; -#endif - -} } } // namespace boost::function_types::detail - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/encoding/aliases_def.hpp b/utils/boost_idb/boost/function_types/detail/encoding/aliases_def.hpp deleted file mode 100644 index 4d483317..00000000 --- a/utils/boost_idb/boost/function_types/detail/encoding/aliases_def.hpp +++ /dev/null @@ -1,16 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - -#define callable_builtin BOOST_FT_callable_builtin -#define member BOOST_FT_member_pointer -#define non_member BOOST_FT_non_member -#define variadic BOOST_FT_variadic -#define non_variadic BOOST_FT_non_variadic - diff --git a/utils/boost_idb/boost/function_types/detail/encoding/aliases_undef.hpp b/utils/boost_idb/boost/function_types/detail/encoding/aliases_undef.hpp deleted file mode 100644 index 1d4e577d..00000000 --- a/utils/boost_idb/boost/function_types/detail/encoding/aliases_undef.hpp +++ /dev/null @@ -1,16 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - -#undef callable_builtin -#undef member -#undef non_member -#undef variadic -#undef non_variadic - diff --git a/utils/boost_idb/boost/function_types/detail/encoding/def.hpp b/utils/boost_idb/boost/function_types/detail/encoding/def.hpp deleted file mode 100644 index 08074fb3..00000000 --- a/utils/boost_idb/boost/function_types/detail/encoding/def.hpp +++ /dev/null @@ -1,51 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - -// Type encoding: -// -// bit 0: callable builtin -// bit 1: non member -// bit 2: naked function -// bit 3: pointer -// bit 4: reference -// bit 5: member pointer -// bit 6: member function pointer -// bit 7: member object pointer - -#define BOOST_FT_type_mask 0x000000ff // 1111 1111 -#define BOOST_FT_callable_builtin 0x00000001 // 0000 0001 -#define BOOST_FT_non_member 0x00000002 // 0000 0010 -#define BOOST_FT_function 0x00000007 // 0000 0111 -#define BOOST_FT_pointer 0x0000000b // 0000 1011 -#define BOOST_FT_reference 0x00000013 // 0001 0011 -#define BOOST_FT_non_member_callable_builtin 0x00000003 // 0000 0011 -#define BOOST_FT_member_pointer 0x00000020 // 0010 0000 -#define BOOST_FT_member_function_pointer 0x00000061 // 0110 0001 -#define BOOST_FT_member_object_pointer 0x000000a3 // 1010 0001 -#define BOOST_FT_member_object_pointer_flags 0x000002a3 - -#define BOOST_FT_variadic 0x00000100 -#define BOOST_FT_non_variadic 0x00000200 -#define BOOST_FT_variadic_mask 0x00000300 - -#define BOOST_FT_const 0x00000400 -#define BOOST_FT_volatile 0x00000800 - -#define BOOST_FT_default_cc 0x00008000 -#define BOOST_FT_cc_mask 0x00ff8000 - -#define BOOST_FT_kind_mask 0x000000fc - -#define BOOST_FT_flags_mask 0x00000fff -#define BOOST_FT_full_mask 0x00ff0fff - -#define BOOST_FT_arity_shift 24 -#define BOOST_FT_arity_mask 0x7f000000 - diff --git a/utils/boost_idb/boost/function_types/detail/encoding/undef.hpp b/utils/boost_idb/boost/function_types/detail/encoding/undef.hpp deleted file mode 100644 index 1920d6fc..00000000 --- a/utils/boost_idb/boost/function_types/detail/encoding/undef.hpp +++ /dev/null @@ -1,38 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -#undef BOOST_FT_type_mask -#undef BOOST_FT_kind_mask -#undef BOOST_FT_callable_builtin -#undef BOOST_FT_non_member -#undef BOOST_FT_function -#undef BOOST_FT_pointer -#undef BOOST_FT_reference -#undef BOOST_FT_non_member_callable_builtin -#undef BOOST_FT_member_pointer -#undef BOOST_FT_member_function_pointer -#undef BOOST_FT_member_object_pointer -#undef BOOST_FT_member_object_pointer_flags - -#undef BOOST_FT_variadic -#undef BOOST_FT_non_variadic -#undef BOOST_FT_variadic_mask - -#undef BOOST_FT_const -#undef BOOST_FT_volatile - -#undef BOOST_FT_default_cc -#undef BOOST_FT_cc_mask - -#undef BOOST_FT_flags_mask -#undef BOOST_FT_full_mask - -#undef BOOST_FT_arity_mask - diff --git a/utils/boost_idb/boost/function_types/detail/pp_arity_loop.hpp b/utils/boost_idb/boost/function_types/detail/pp_arity_loop.hpp deleted file mode 100644 index b6dbff59..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_arity_loop.hpp +++ /dev/null @@ -1,149 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -#ifndef BOOST_FT_PREPROCESSING_MODE -// input: BOOST_FT_mfp 0 or 1 <=> member function pointer? -// input: BOOST_FT_type_name BOOST_FT_type --> "R (* ..._type_name)()" (pass2) -#endif -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -#ifdef __WAVE__ -# pragma wave option(preserve: 0) -#endif - -#ifndef BOOST_FT_ARITY_LOOP_IS_ITERATING - -# define BOOST_FT_AL_PREPROCESSED \ - BOOST_FT_AL_FILE(BOOST_FT_al_path,BOOST_FT_FROM_ARITY,BOOST_FT_mfp) - -# define BOOST_FT_AL_FILE(base_path,max_arity,mfp) \ - BOOST_FT_AL_FILE_I(base_path,max_arity,mfp) -# define BOOST_FT_AL_FILE_I(base_path,max_arity,mfp) \ - - -# if !defined(BOOST_FT_PREPROCESSING_MODE) - -# if BOOST_FT_MAX_ARITY < 10 -# define BOOST_FT_FROM_ARITY 0 -# elif BOOST_FT_MAX_ARITY < 20 -# define BOOST_FT_FROM_ARITY 10 -# elif BOOST_FT_MAX_ARITY < 30 -# define BOOST_FT_FROM_ARITY 20 -# elif BOOST_FT_MAX_ARITY < 40 -# define BOOST_FT_FROM_ARITY 30 -# endif - -# if BOOST_FT_FROM_ARITY -# include BOOST_FT_AL_PREPROCESSED -# endif - -# elif !defined(BOOST_FT_FROM_ARITY) // single pass preprocessing -# define BOOST_FT_FROM_ARITY 0 - -# elif BOOST_FT_FROM_ARITY > 0 // arity20 includes arity10 -BOOST_PP_EXPAND(#) include BOOST_FT_AL_PREPROCESSED -# endif - -# undef BOOST_FT_AL_PREPROCESSED - -# undef BOOST_FT_AL_FILE -# undef BOOST_FT_AL_FILE_I - -# if BOOST_FT_MAX_ARITY > BOOST_FT_FROM_ARITY - -# ifndef BOOST_FT_DETAIL_ARITY_LOOP_HPP_INCLUDED -# define BOOST_FT_DETAIL_ARITY_LOOP_HPP_INCLUDED -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# endif - -# define BOOST_FT_AL_INCLUDE_FILE - -# define BOOST_FT_ARITY_LOOP_PREFIX 1 -# include BOOST_FT_AL_INCLUDE_FILE -# undef BOOST_FT_ARITY_LOOP_PREFIX - -# if !BOOST_PP_IS_ITERATING -# define BOOST_PP_FILENAME_1 BOOST_FT_AL_INCLUDE_FILE -# elif BOOST_PP_ITERATION_DEPTH() == 1 -# define BOOST_PP_FILENAME_2 BOOST_FT_AL_INCLUDE_FILE -# else -# error "loops nested too deeply" -# endif - -# define BOOST_FT_arity BOOST_PP_ITERATION() -# define BOOST_FT_n BOOST_PP_INC(BOOST_FT_arity) - -# define BOOST_FT_type \ - BOOST_FT_syntax(BOOST_FT_cc,BOOST_FT_type_name BOOST_PP_EMPTY)\ - (BOOST_FT_params(BOOST_PP_EMPTY) BOOST_FT_ell) BOOST_FT_cv - -# define BOOST_FT_tplargs(prefx) \ - prefx() R BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_FT_arity,prefx() T) - -# if !BOOST_FT_mfp - -# define BOOST_FT_params(prefx) \ - BOOST_PP_IF(BOOST_FT_arity,BOOST_PP_ENUM_PARAMS, \ - BOOST_FT_nullary_param BOOST_PP_TUPLE_EAT(2))( \ - BOOST_FT_arity,prefx() T) -# else - -# define BOOST_FT_params(prefx) \ - BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_FT_arity,prefx() T) - -# endif - -# if !BOOST_FT_FROM_ARITY -# define BOOST_PP_ITERATION_LIMITS (BOOST_FT_mfp, BOOST_FT_MAX_ARITY) -# else -# define BOOST_PP_ITERATION_LIMITS \ - (BOOST_FT_FROM_ARITY+1, BOOST_FT_MAX_ARITY) -# endif - -# define BOOST_FT_ARITY_LOOP_IS_ITERATING 1 -# include BOOST_PP_ITERATE() -# undef BOOST_FT_ARITY_LOOP_IS_ITERATING - -# undef BOOST_FT_arity -# undef BOOST_FT_params -# undef BOOST_FT_tplargs -# undef BOOST_FT_type - -# define BOOST_FT_ARITY_LOOP_SUFFIX 1 -# include BOOST_FT_AL_INCLUDE_FILE -# undef BOOST_FT_ARITY_LOOP_SUFFIX - -# undef BOOST_FT_AL_INCLUDE_FILE -# endif - -# undef BOOST_FT_FROM_ARITY - -#else -# error "attempt to nest arity loops" -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/pp_cc_loop/master.hpp b/utils/boost_idb/boost/function_types/detail/pp_cc_loop/master.hpp deleted file mode 100644 index 60e958ce..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_cc_loop/master.hpp +++ /dev/null @@ -1,136 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - -#ifdef __WAVE__ -// this file has been generated from the master.hpp file in the same directory -# pragma wave option(preserve: 0) -#endif - - -#if !BOOST_PP_IS_ITERATING - -# ifndef BOOST_FT_DETAIL_CC_LOOP_MASTER_HPP_INCLUDED -# define BOOST_FT_DETAIL_CC_LOOP_MASTER_HPP_INCLUDED -# include - -# include -# include -# include -# include -# include -# include -# include -# endif - -# include -# include - -# define BOOST_PP_FILENAME_1 \ - -# define BOOST_PP_ITERATION_LIMITS \ - (0,BOOST_PP_SEQ_SIZE(BOOST_FT_CC_NAMES_SEQ)-1) -# include BOOST_PP_ITERATE() -# if !defined(BOOST_FT_config_valid) && BOOST_FT_CC_PREPROCESSING -# define BOOST_FT_cc_id 1 -# define BOOST_FT_cc_name implicit_cc -# define BOOST_FT_cc BOOST_PP_EMPTY -# define BOOST_FT_cond callable_builtin -# include BOOST_FT_cc_file -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# elif !defined(BOOST_FT_config_valid) // and generating preprocessed file -BOOST_PP_EXPAND(#) ifndef BOOST_FT_config_valid -BOOST_PP_EXPAND(#) define BOOST_FT_cc_id 1 -BOOST_PP_EXPAND(#) define BOOST_FT_cc_name implicit_cc -BOOST_PP_EXPAND(#) define BOOST_FT_cc BOOST_PP_EMPTY -BOOST_PP_EXPAND(#) define BOOST_FT_cond callable_builtin -#define _() -BOOST_PP_EXPAND(#) include BOOST_FT_cc_file -#undef _ -BOOST_PP_EXPAND(#) undef BOOST_FT_cond -BOOST_PP_EXPAND(#) undef BOOST_FT_cc_name -BOOST_PP_EXPAND(#) undef BOOST_FT_cc -BOOST_PP_EXPAND(#) undef BOOST_FT_cc_id -BOOST_PP_EXPAND(#) else -BOOST_PP_EXPAND(#) undef BOOST_FT_config_valid -BOOST_PP_EXPAND(#) endif - -# else -# undef BOOST_FT_config_valid -# endif - -# include -# include - -#elif BOOST_FT_CC_PREPROCESSING - -# define BOOST_FT_cc_id BOOST_PP_INC(BOOST_PP_FRAME_ITERATION(1)) -# define BOOST_FT_cc_inf \ - BOOST_PP_SEQ_ELEM(BOOST_PP_FRAME_ITERATION(1),BOOST_FT_CC_NAMES_SEQ) - -# define BOOST_FT_cc_pp_name BOOST_PP_TUPLE_ELEM(3,0,BOOST_FT_cc_inf) -# define BOOST_FT_cc_name BOOST_PP_TUPLE_ELEM(3,1,BOOST_FT_cc_inf) -# define BOOST_FT_cc BOOST_PP_TUPLE_ELEM(3,2,BOOST_FT_cc_inf) - -# define BOOST_FT_cond BOOST_PP_CAT(BOOST_FT_CC_,BOOST_FT_cc_pp_name) - -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif - -# undef BOOST_FT_cond - -# undef BOOST_FT_cc_pp_name -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc - -# undef BOOST_FT_cc_id -# undef BOOST_FT_cc_inf - -#else // if generating preprocessed file -BOOST_PP_EXPAND(#) define BOOST_FT_cc_id BOOST_PP_INC(BOOST_PP_ITERATION()) - -# define BOOST_FT_cc_inf \ - BOOST_PP_SEQ_ELEM(BOOST_PP_ITERATION(),BOOST_FT_CC_NAMES_SEQ) - -# define BOOST_FT_cc_pp_name BOOST_PP_TUPLE_ELEM(3,0,BOOST_FT_cc_inf) - -# define BOOST_FT_CC_DEF(name,index) \ - name BOOST_PP_TUPLE_ELEM(3,index,BOOST_FT_cc_inf) -BOOST_PP_EXPAND(#) define BOOST_FT_CC_DEF(BOOST_FT_cc_name,1) -BOOST_PP_EXPAND(#) define BOOST_FT_CC_DEF(BOOST_FT_cc,2) -# undef BOOST_FT_CC_DEF - -# define BOOST_FT_cc_cond_v BOOST_PP_CAT(BOOST_FT_CC_,BOOST_FT_cc_pp_name) -BOOST_PP_EXPAND(#) define BOOST_FT_cond BOOST_FT_cc_cond_v -# undef BOOST_FT_cc_cond_v - -# undef BOOST_FT_cc_pp_name -# undef BOOST_FT_cc_inf - -BOOST_PP_EXPAND(#) if BOOST_FT_cond -BOOST_PP_EXPAND(#) define BOOST_FT_config_valid 1 -#define _() -BOOST_PP_EXPAND(#) include BOOST_FT_cc_file -#undef _ -BOOST_PP_EXPAND(#) endif - -BOOST_PP_EXPAND(#) undef BOOST_FT_cond - -BOOST_PP_EXPAND(#) undef BOOST_FT_cc_name -BOOST_PP_EXPAND(#) undef BOOST_FT_cc - -BOOST_PP_EXPAND(#) undef BOOST_FT_cc_id - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/pp_cc_loop/preprocessed.hpp b/utils/boost_idb/boost/function_types/detail/pp_cc_loop/preprocessed.hpp deleted file mode 100644 index da4079c6..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_cc_loop/preprocessed.hpp +++ /dev/null @@ -1,120 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - -// this file has been generated from the master.hpp file in the same directory -# define BOOST_FT_cc_id 1 -# define BOOST_FT_cc_name implicit_cc -# define BOOST_FT_cc BOOST_PP_EMPTY -# define BOOST_FT_cond BOOST_FT_CC_IMPLICIT -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 2 -# define BOOST_FT_cc_name cdecl_cc -# define BOOST_FT_cc BOOST_PP_IDENTITY(__cdecl ) -# define BOOST_FT_cond BOOST_FT_CC_CDECL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 3 -# define BOOST_FT_cc_name stdcall_cc -# define BOOST_FT_cc BOOST_PP_IDENTITY(__stdcall ) -# define BOOST_FT_cond BOOST_FT_CC_STDCALL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 4 -# define BOOST_FT_cc_name pascal_cc -# define BOOST_FT_cc BOOST_PP_IDENTITY(pascal ) -# define BOOST_FT_cond BOOST_FT_CC_PASCAL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 5 -# define BOOST_FT_cc_name fastcall_cc -# define BOOST_FT_cc BOOST_PP_IDENTITY(__fastcall) -# define BOOST_FT_cond BOOST_FT_CC_FASTCALL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 6 -# define BOOST_FT_cc_name clrcall_cc -# define BOOST_FT_cc BOOST_PP_IDENTITY(__clrcall ) -# define BOOST_FT_cond BOOST_FT_CC_CLRCALL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 7 -# define BOOST_FT_cc_name thiscall_cc -# define BOOST_FT_cc BOOST_PP_IDENTITY(__thiscall) -# define BOOST_FT_cond BOOST_FT_CC_THISCALL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# define BOOST_FT_cc_id 8 -# define BOOST_FT_cc_name thiscall_cc -# define BOOST_FT_cc BOOST_PP_EMPTY -# define BOOST_FT_cond BOOST_FT_CC_IMPLICIT_THISCALL -# if BOOST_FT_cond -# define BOOST_FT_config_valid 1 -# include BOOST_FT_cc_file -# endif -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# ifndef BOOST_FT_config_valid -# define BOOST_FT_cc_id 1 -# define BOOST_FT_cc_name implicit_cc -# define BOOST_FT_cc BOOST_PP_EMPTY -# define BOOST_FT_cond 0x00000001 -# include BOOST_FT_cc_file -# undef BOOST_FT_cond -# undef BOOST_FT_cc_name -# undef BOOST_FT_cc -# undef BOOST_FT_cc_id -# else -# undef BOOST_FT_config_valid -# endif diff --git a/utils/boost_idb/boost/function_types/detail/pp_loop.hpp b/utils/boost_idb/boost/function_types/detail/pp_loop.hpp deleted file mode 100644 index 7d8c347c..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_loop.hpp +++ /dev/null @@ -1,80 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - -#ifndef BOOST_FT_DETAIL_PP_LOOP_HPP_INCLUDED -#define BOOST_FT_DETAIL_PP_LOOP_HPP_INCLUDED -# include -# include -# include -#endif - -#include -#include - -#if defined(BOOST_FT_PREPROCESSING_MODE) -# define BOOST_FT_loop -#else -# define BOOST_FT_loop \ - -#endif - -#if defined(BOOST_FT_al_path) - -# define BOOST_FT_cc_file \ - -# define BOOST_FT_variate_file \ - - -# ifndef BOOST_FT_type_function -# define BOOST_FT_type_function(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_EMPTY,cc,BOOST_PP_EMPTY,name,BOOST_PP_EMPTY) -# endif -# ifndef BOOST_FT_type_function_pointer -# define BOOST_FT_type_function_pointer(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_LPAREN,cc,* BOOST_PP_EMPTY,name,BOOST_PP_RPAREN) -# endif -# ifndef BOOST_FT_type_function_reference -# define BOOST_FT_type_function_reference(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_LPAREN,cc,& BOOST_PP_EMPTY,name,BOOST_PP_RPAREN) -# endif -# ifndef BOOST_FT_type_member_function_pointer -# define BOOST_FT_type_member_function_pointer(cc,name) BOOST_FT_SYNTAX( \ - R BOOST_PP_EMPTY,BOOST_PP_LPAREN,cc,T0::* BOOST_PP_EMPTY,name,BOOST_PP_RPAREN) -# endif - -# include BOOST_FT_loop - -# undef BOOST_FT_type_function -# undef BOOST_FT_type_function_pointer -# undef BOOST_FT_type_function_reference -# undef BOOST_FT_type_member_function_pointer - -# undef BOOST_FT_variations -# undef BOOST_FT_variate_file -# undef BOOST_FT_cc_file -# undef BOOST_FT_al_path - -#elif defined(BOOST_FT_cc_file) - -# include BOOST_FT_loop -# undef BOOST_FT_cc_file - -#else - -# error "argument missing" - -#endif - -#undef BOOST_FT_loop - -#include -#include - - diff --git a/utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/master.hpp b/utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/master.hpp deleted file mode 100644 index 865efce5..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/master.hpp +++ /dev/null @@ -1,103 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is guarded externally - -#ifdef __WAVE__ -// this file has been generated from the master.hpp file in the same directory -# pragma wave option(preserve: 0) -#endif - -#if !defined(BOOST_PP_VALUE) -# include -# include - -# include -# include - -namespace boost { namespace function_types { - -namespace detail -{ - template struct selector_bits - { -# define BOOST_PP_VALUE non_member|member|non_variadic|variadic -# include BOOST_PP_ASSIGN_SLOT(1) - - BOOST_STATIC_CONSTANT(bits_t, value = ( - (::boost::function_types::detail::bits::value & BOOST_FT_default_cc) - | (::boost::function_types::detail::bits::value & BOOST_PP_SLOT(1)) - )); - }; - - template struct default_cc_tag; - - template struct retag_default_cc - : detail::compound_tag - < Tag, detail::default_cc_tag< - ::boost::function_types::detail::selector_bits::value > > - { }; - - template struct default_cc_tag - { - typedef null_tag::bits bits; - typedef null_tag::mask mask; - }; - - class test_class; - typedef constant cc_mask_constant; - -# define BOOST_FT_self \ - - -# define default_cc_ BOOST_FT_default_cc - -# define BOOST_PP_VALUE default_cc_|non_member|non_variadic -# define BOOST_FT_tester void (*tester)() -# define BOOST_PP_INDIRECT_SELF BOOST_FT_self -# include BOOST_PP_INCLUDE_SELF() - -# define BOOST_PP_VALUE default_cc_|non_member|variadic -# define BOOST_FT_tester void (*tester)(...) -# define BOOST_PP_INDIRECT_SELF BOOST_FT_self -# include BOOST_PP_INCLUDE_SELF() - -# define BOOST_PP_VALUE default_cc_|member|non_variadic -# define BOOST_FT_tester void (test_class::*tester)() -# define BOOST_PP_INDIRECT_SELF BOOST_FT_self -# include BOOST_PP_INCLUDE_SELF() - -# define BOOST_PP_VALUE default_cc_|member|variadic -# define BOOST_FT_tester void (test_class::*tester)(...) -# define BOOST_PP_INDIRECT_SELF BOOST_FT_self -# include BOOST_PP_INCLUDE_SELF() - -# undef default_cc_ - -# undef BOOST_FT_self - -} } } // namespace ::boost::function_types::detail - -# include -# include - -#else // if defined(BOOST_PP_VALUE) - -# include BOOST_PP_ASSIGN_SLOT(1) - - template<> struct default_cc_tag - { - typedef BOOST_FT_tester; - typedef mpl::bitand_::bits,cc_mask_constant> bits; - typedef cc_mask_constant mask; - }; - -# undef BOOST_FT_tester - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/preprocessed.hpp b/utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/preprocessed.hpp deleted file mode 100644 index 72666d0f..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_retag_default_cc/preprocessed.hpp +++ /dev/null @@ -1,59 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is guarded externally - -// this file has been generated from the master.hpp file in the same directory -namespace boost { namespace function_types { -namespace detail -{ -template struct selector_bits -{ -BOOST_STATIC_CONSTANT(bits_t, value = ( -(::boost::function_types::detail::bits ::value & 0x00008000) -| (::boost::function_types::detail::bits ::value & 802) -)); -}; -template struct default_cc_tag; -template struct retag_default_cc -: detail::compound_tag -< Tag, detail::default_cc_tag< -::boost::function_types::detail::selector_bits ::value > > -{ }; -template struct default_cc_tag -{ -typedef null_tag::bits bits; -typedef null_tag::mask mask; -}; -class test_class; -typedef constant<0x00ff8000> cc_mask_constant; -template< > struct default_cc_tag<33282> -{ -typedef void ( *tester)(); -typedef mpl::bitand_ ::bits,cc_mask_constant> bits; -typedef cc_mask_constant mask; -}; -template< > struct default_cc_tag<33026> -{ -typedef void ( *tester)( ... ); -typedef mpl::bitand_ ::bits,cc_mask_constant> bits; -typedef cc_mask_constant mask; -}; -template< > struct default_cc_tag<33312> -{ -typedef void (test_class:: *tester)(); -typedef mpl::bitand_ ::bits,cc_mask_constant> bits; -typedef cc_mask_constant mask; -}; -template< > struct default_cc_tag<33056> -{ -typedef void (test_class:: *tester)( ... ); -typedef mpl::bitand_ ::bits,cc_mask_constant> bits; -typedef cc_mask_constant mask; -}; -} } } diff --git a/utils/boost_idb/boost/function_types/detail/pp_tags/cc_tag.hpp b/utils/boost_idb/boost/function_types/detail/pp_tags/cc_tag.hpp deleted file mode 100644 index 81f1d89e..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_tags/cc_tag.hpp +++ /dev/null @@ -1,17 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusions - - struct BOOST_FT_cc_name - { - typedef detail::encode_bits<0,BOOST_FT_cc_id> bits; - typedef detail::constant mask; - }; - - diff --git a/utils/boost_idb/boost/function_types/detail/pp_tags/master.hpp b/utils/boost_idb/boost/function_types/detail/pp_tags/master.hpp deleted file mode 100644 index 9cce212f..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_tags/master.hpp +++ /dev/null @@ -1,126 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is guarded externally - -#ifdef __WAVE__ -// this file has been generated from the master.hpp file in the same directory -# pragma wave option(preserve: 0) -#endif - -#if !defined(BOOST_FT_PREPROCESSING_MODE) || defined(BOOST_FT_CONFIG_HPP_INCLUDED) -# error "this file used with two-pass preprocessing, only" -#endif - -#include -#include - -namespace boost { namespace function_types { - -typedef detail::property_tag non_variadic; -typedef detail::property_tag variadic; - -typedef detail::property_tag<0,BOOST_FT_const> non_const; -typedef detail::property_tag const_qualified; - -typedef detail::property_tag<0,BOOST_FT_volatile> non_volatile; -typedef detail::property_tag volatile_qualified; - -typedef detail::property_tag default_cc; - -#define BOOST_PP_VALUE BOOST_FT_const|BOOST_FT_volatile -#include BOOST_PP_ASSIGN_SLOT(1) - -typedef detail::property_tag<0 , BOOST_PP_SLOT(1)> non_cv; -typedef detail::property_tag const_non_volatile; -typedef detail::property_tag volatile_non_const; -typedef detail::property_tag cv_qualified; - -namespace detail { - - typedef constant full_mask; - - template struct encode_bits_impl - { - BOOST_STATIC_CONSTANT( bits_t, value = - Flags | (BOOST_FT_default_cc * CCID) << 1 ); - }; - - template - struct encode_charr_impl - { - BOOST_STATIC_CONSTANT(std::size_t, value = (std::size_t)(1+ - Flags | (BOOST_FT_default_cc * CCID) << 1 | Arity << BOOST_FT_arity_shift - )); - }; - - template struct decode_bits - { - BOOST_STATIC_CONSTANT(bits_t, flags = Bits & BOOST_FT_flags_mask); - - BOOST_STATIC_CONSTANT(bits_t, cc_id = - ( (Bits & BOOST_FT_full_mask) / BOOST_FT_default_cc) >> 1 - ); - - BOOST_STATIC_CONSTANT(bits_t, tag_bits = (Bits & BOOST_FT_full_mask)); - - BOOST_STATIC_CONSTANT(std::size_t, arity = (std::size_t) - (Bits >> BOOST_FT_arity_shift) - ); - }; - - template - struct tag_ice - { - BOOST_STATIC_CONSTANT(bool, match = - RHS_bits == (LHS_bits & RHS_mask & (RHS_bits |~BOOST_FT_type_mask)) - ); - - BOOST_STATIC_CONSTANT(bits_t, combined_bits = - (LHS_bits & ~RHS_mask) | RHS_bits - ); - - BOOST_STATIC_CONSTANT(bits_t, combined_mask = - LHS_mask | RHS_mask - ); - - BOOST_STATIC_CONSTANT(bits_t, extracted_bits = - LHS_bits & RHS_mask - ); - - }; - -#define BOOST_FT_mask BOOST_FT_type_mask - typedef property_tag callable_builtin_tag; - typedef property_tag nonmember_callable_builtin_tag; - typedef property_tag function_tag; - typedef property_tag reference_tag; - typedef property_tag pointer_tag; - typedef property_tag member_function_pointer_tag; - typedef property_tag member_object_pointer_tag; - typedef property_tag member_object_pointer_base; - typedef property_tag member_pointer_tag; -#undef BOOST_FT_mask - -#define BOOST_PP_VALUE BOOST_FT_function|BOOST_FT_non_variadic|BOOST_FT_default_cc -#include BOOST_PP_ASSIGN_SLOT(1) -#define BOOST_PP_VALUE BOOST_FT_type_mask|BOOST_FT_variadic_mask|BOOST_FT_cc_mask -#include BOOST_PP_ASSIGN_SLOT(2) - - typedef property_tag< BOOST_PP_SLOT(1) , BOOST_PP_SLOT(2) > nv_dcc_func; - -#define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_non_variadic|BOOST_FT_default_cc -#include BOOST_PP_ASSIGN_SLOT(1) - - typedef property_tag< BOOST_PP_SLOT(1) , BOOST_PP_SLOT(2) > nv_dcc_mfp; - -} // namespace detail - -} } // namespace ::boost::function_types - diff --git a/utils/boost_idb/boost/function_types/detail/pp_tags/preprocessed.hpp b/utils/boost_idb/boost/function_types/detail/pp_tags/preprocessed.hpp deleted file mode 100644 index 823c3cc1..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_tags/preprocessed.hpp +++ /dev/null @@ -1,77 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is guarded externally - -// this file has been generated from the master.hpp file in the same directory -namespace boost { namespace function_types { -typedef detail::property_tag<0x00000200,0x00000300> non_variadic; -typedef detail::property_tag<0x00000100,0x00000300> variadic; -typedef detail::property_tag<0,0x00000400> non_const; -typedef detail::property_tag<0x00000400,0x00000400> const_qualified; -typedef detail::property_tag<0,0x00000800> non_volatile; -typedef detail::property_tag<0x00000800,0x00000800> volatile_qualified; -typedef detail::property_tag<0x00008000,0x00ff8000> default_cc; -typedef detail::property_tag<0 , 3072> non_cv; -typedef detail::property_tag<0x00000400 , 3072> const_non_volatile; -typedef detail::property_tag<0x00000800, 3072> volatile_non_const; -typedef detail::property_tag<3072 , 3072> cv_qualified; -namespace detail { -typedef constant<0x00ff0fff> full_mask; -template struct encode_bits_impl -{ -BOOST_STATIC_CONSTANT( bits_t, value = -Flags | (0x00008000 * CCID) << 1 ); -}; -template -struct encode_charr_impl -{ -BOOST_STATIC_CONSTANT(std::size_t, value = (std::size_t)(1+ -Flags | (0x00008000 * CCID) << 1 | Arity << 24 -)); -}; -template struct decode_bits -{ -BOOST_STATIC_CONSTANT(bits_t, flags = Bits & 0x00000fff); -BOOST_STATIC_CONSTANT(bits_t, cc_id = -( (Bits & 0x00ff0fff) / 0x00008000) >> 1 -); -BOOST_STATIC_CONSTANT(bits_t, tag_bits = (Bits & 0x00ff0fff)); -BOOST_STATIC_CONSTANT(std::size_t, arity = (std::size_t) -(Bits >> 24) -); -}; -template -struct tag_ice -{ -BOOST_STATIC_CONSTANT(bool, match = -RHS_bits == (LHS_bits & RHS_mask & (RHS_bits | ~0x000000ff)) -); -BOOST_STATIC_CONSTANT(bits_t, combined_bits = -(LHS_bits & ~RHS_mask) | RHS_bits -); -BOOST_STATIC_CONSTANT(bits_t, combined_mask = -LHS_mask | RHS_mask -); -BOOST_STATIC_CONSTANT(bits_t, extracted_bits = -LHS_bits & RHS_mask -); -}; -typedef property_tag<0x00000001,0x000000ff> callable_builtin_tag; -typedef property_tag<0x00000003,0x000000ff> nonmember_callable_builtin_tag; -typedef property_tag<0x00000007,0x000000ff> function_tag; -typedef property_tag<0x00000013,0x000000ff> reference_tag; -typedef property_tag<0x0000000b,0x000000ff> pointer_tag; -typedef property_tag<0x00000061,0x000000ff> member_function_pointer_tag; -typedef property_tag<0x000000a3,0x000000ff> member_object_pointer_tag; -typedef property_tag<0x000002a3,0x00ff0fff> member_object_pointer_base; -typedef property_tag<0x00000020,0x000000ff> member_pointer_tag; -typedef property_tag< 33287 , 16745471 > nv_dcc_func; -typedef property_tag< 33377 , 16745471 > nv_dcc_mfp; -} -} } diff --git a/utils/boost_idb/boost/function_types/detail/pp_variate_loop/master.hpp b/utils/boost_idb/boost/function_types/detail/pp_variate_loop/master.hpp deleted file mode 100644 index 50263429..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_variate_loop/master.hpp +++ /dev/null @@ -1,152 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifdef __WAVE__ -// this file has been generated from the master.hpp file in the same directory -# pragma wave option(preserve: 0) -#endif - -#if !defined(BOOST_FT_PREPROCESSING_MODE) -# error "this file is only for two-pass preprocessing" -#endif - -#if !defined(BOOST_PP_VALUE) -# include -# include -# include -# include - -BOOST_PP_EXPAND(#) define BOOST_FT_mfp 0 -BOOST_PP_EXPAND(#) define BOOST_FT_syntax BOOST_FT_type_function - -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_non_variadic -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_variadic -# include __FILE__ - -BOOST_PP_EXPAND(#) if !BOOST_FT_NO_CV_FUNC_SUPPORT -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_non_variadic|BOOST_FT_const -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_variadic|BOOST_FT_const -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_non_variadic|BOOST_FT_volatile -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_variadic|BOOST_FT_volatile -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_non_variadic|BOOST_FT_const|BOOST_FT_volatile -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_function|BOOST_FT_variadic|BOOST_FT_const|BOOST_FT_volatile -# include __FILE__ -BOOST_PP_EXPAND(#) endif - - -BOOST_PP_EXPAND(#) undef BOOST_FT_syntax -BOOST_PP_EXPAND(#) define BOOST_FT_syntax BOOST_FT_type_function_pointer - -# define BOOST_PP_VALUE \ - BOOST_FT_pointer|BOOST_FT_non_variadic -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_pointer|BOOST_FT_variadic -# include __FILE__ - -BOOST_PP_EXPAND(#) undef BOOST_FT_syntax -BOOST_PP_EXPAND(#) define BOOST_FT_syntax BOOST_FT_type_function_reference - -# define BOOST_PP_VALUE \ - BOOST_FT_reference|BOOST_FT_non_variadic -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_reference|BOOST_FT_variadic -# include __FILE__ - -BOOST_PP_EXPAND(#) undef BOOST_FT_syntax -BOOST_PP_EXPAND(#) undef BOOST_FT_mfp - -BOOST_PP_EXPAND(#) define BOOST_FT_mfp 1 -BOOST_PP_EXPAND(#) define BOOST_FT_syntax BOOST_FT_type_member_function_pointer - -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_non_variadic -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_variadic -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_non_variadic|BOOST_FT_const -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_variadic|BOOST_FT_const -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_non_variadic|BOOST_FT_volatile -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_variadic|BOOST_FT_volatile -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_non_variadic|BOOST_FT_const|BOOST_FT_volatile -# include __FILE__ -# define BOOST_PP_VALUE \ - BOOST_FT_member_function_pointer|BOOST_FT_variadic|BOOST_FT_const|BOOST_FT_volatile -# include __FILE__ - -BOOST_PP_EXPAND(#) undef BOOST_FT_syntax -BOOST_PP_EXPAND(#) undef BOOST_FT_mfp - -# include -#else - -# include BOOST_PP_ASSIGN_SLOT(1) - -# define BOOST_PP_VALUE BOOST_PP_SLOT(1) & BOOST_FT_kind_mask -# include BOOST_PP_ASSIGN_SLOT(2) - -BOOST_PP_EXPAND(#) if !!(BOOST_PP_SLOT(2) & (BOOST_FT_variations)) -BOOST_PP_EXPAND(#) if (BOOST_PP_SLOT(1) & (BOOST_FT_cond)) == (BOOST_FT_cond) - -# if ( BOOST_PP_SLOT(1) & (BOOST_FT_variadic) ) -BOOST_PP_EXPAND(#) define BOOST_FT_ell ... -BOOST_PP_EXPAND(#) define BOOST_FT_nullary_param -# else -BOOST_PP_EXPAND(#) define BOOST_FT_ell -BOOST_PP_EXPAND(#) define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# endif - -# if !( BOOST_PP_SLOT(1) & (BOOST_FT_volatile) ) -# if !( BOOST_PP_SLOT(1) & (BOOST_FT_const) ) -BOOST_PP_EXPAND(#) define BOOST_FT_cv -# else -BOOST_PP_EXPAND(#) define BOOST_FT_cv const -# endif -# else -# if !( BOOST_PP_SLOT(1) & (BOOST_FT_const) ) -BOOST_PP_EXPAND(#) define BOOST_FT_cv volatile -# else -BOOST_PP_EXPAND(#) define BOOST_FT_cv const volatile -# endif -# endif -BOOST_PP_EXPAND(#) define BOOST_FT_flags BOOST_PP_SLOT(1) -BOOST_PP_EXPAND(#) include BOOST_FT_variate_file - -BOOST_PP_EXPAND(#) undef BOOST_FT_cv -BOOST_PP_EXPAND(#) undef BOOST_FT_ell -BOOST_PP_EXPAND(#) undef BOOST_FT_nullary_param -BOOST_PP_EXPAND(#) undef BOOST_FT_flags -BOOST_PP_EXPAND(#) endif -BOOST_PP_EXPAND(#) endif -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/pp_variate_loop/preprocessed.hpp b/utils/boost_idb/boost/function_types/detail/pp_variate_loop/preprocessed.hpp deleted file mode 100644 index 7e7c4f91..00000000 --- a/utils/boost_idb/boost/function_types/detail/pp_variate_loop/preprocessed.hpp +++ /dev/null @@ -1,283 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// this file has been generated from the master.hpp file in the same directory -# define BOOST_FT_mfp 0 -# define BOOST_FT_syntax BOOST_FT_type_function -# if ! ! (4 & (BOOST_FT_variations)) -# if (519 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv -# define BOOST_FT_flags 519 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (4 & (BOOST_FT_variations)) -# if (263 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv -# define BOOST_FT_flags 263 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if !BOOST_FT_NO_CV_FUNC_SUPPORT -# if ! ! (4 & (BOOST_FT_variations)) -# if (1543 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv const -# define BOOST_FT_flags 1543 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (4 & (BOOST_FT_variations)) -# if (1287 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv const -# define BOOST_FT_flags 1287 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (4 & (BOOST_FT_variations)) -# if (2567 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv volatile -# define BOOST_FT_flags 2567 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (4 & (BOOST_FT_variations)) -# if (2311 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv volatile -# define BOOST_FT_flags 2311 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (4 & (BOOST_FT_variations)) -# if (3591 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv const volatile -# define BOOST_FT_flags 3591 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (4 & (BOOST_FT_variations)) -# if (3335 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv const volatile -# define BOOST_FT_flags 3335 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# endif -# undef BOOST_FT_syntax -# define BOOST_FT_syntax BOOST_FT_type_function_pointer -# if ! ! (8 & (BOOST_FT_variations)) -# if (523 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv -# define BOOST_FT_flags 523 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (8 & (BOOST_FT_variations)) -# if (267 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv -# define BOOST_FT_flags 267 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# undef BOOST_FT_syntax -# define BOOST_FT_syntax BOOST_FT_type_function_reference -# if ! ! (16 & (BOOST_FT_variations)) -# if (531 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv -# define BOOST_FT_flags 531 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (16 & (BOOST_FT_variations)) -# if (275 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv -# define BOOST_FT_flags 275 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# undef BOOST_FT_syntax -# undef BOOST_FT_mfp -# define BOOST_FT_mfp 1 -# define BOOST_FT_syntax BOOST_FT_type_member_function_pointer -# if ! ! (96 & (BOOST_FT_variations)) -# if (609 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv -# define BOOST_FT_flags 609 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (353 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv -# define BOOST_FT_flags 353 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (1633 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv const -# define BOOST_FT_flags 1633 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (1377 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv const -# define BOOST_FT_flags 1377 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (2657 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv volatile -# define BOOST_FT_flags 2657 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (2401 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv volatile -# define BOOST_FT_flags 2401 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (3681 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell -# define BOOST_FT_nullary_param BOOST_FT_NULLARY_PARAM -# define BOOST_FT_cv const volatile -# define BOOST_FT_flags 3681 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# if ! ! (96 & (BOOST_FT_variations)) -# if (3425 & (BOOST_FT_cond)) == (BOOST_FT_cond) -# define BOOST_FT_ell ... -# define BOOST_FT_nullary_param -# define BOOST_FT_cv const volatile -# define BOOST_FT_flags 3425 -# include BOOST_FT_variate_file -# undef BOOST_FT_cv -# undef BOOST_FT_ell -# undef BOOST_FT_nullary_param -# undef BOOST_FT_flags -# endif -# endif -# undef BOOST_FT_syntax -# undef BOOST_FT_mfp diff --git a/utils/boost_idb/boost/function_types/detail/retag_default_cc.hpp b/utils/boost_idb/boost/function_types/detail/retag_default_cc.hpp deleted file mode 100644 index c8926f6d..00000000 --- a/utils/boost_idb/boost/function_types/detail/retag_default_cc.hpp +++ /dev/null @@ -1,23 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_RETAG_DEFAULT_CC_HPP_INCLUDED -#define BOOST_FT_DETAIL_RETAG_DEFAULT_CC_HPP_INCLUDED - -#include - -#include - -#if defined(BOOST_FT_PREPROCESSING_MODE) -# include -#else -# include -#endif - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize.hpp b/utils/boost_idb/boost/function_types/detail/synthesize.hpp deleted file mode 100644 index 0b15cbbe..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize.hpp +++ /dev/null @@ -1,79 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_SYNTHESIZE_HPP_INCLUDED -#define BOOST_FT_DETAIL_SYNTHESIZE_HPP_INCLUDED - -#include - -#include -#include - -#include -#include -#include -#include - -namespace boost { namespace function_types { namespace detail { - -template -struct synthesize_impl_o -{ - template struct synthesize_impl_i { }; -}; - -template -struct synthesize_impl - : detail::synthesize_impl_o - < ::boost::function_types::detail::decode_bits::flags - , ::boost::function_types::detail::decode_bits::cc_id - , ::boost::mpl::size::value - > - ::template synthesize_impl_i -{ }; - -template -struct synthesize_func - : detail::synthesize_impl - < Seq - , ::boost::function_types::detail::bits - < detail::retag_default_cc - < function_types::tag > - >::value - > -{ }; - -template -struct synthesize_mfp - : detail::synthesize_impl - < Seq - , ::boost::function_types::detail::bits - < detail::retag_default_cc - < function_types::tag - < typename detail::cv_traits< typename mpl::at_c::type >::tag - , nv_dcc_mfp, Tag - > > - >::value - > -{ }; - -template::type, - typename C = typename mpl::at_c::type> -struct synthesize_mop -{ - typedef R C::* type; -}; - -#define BOOST_FT_variations BOOST_FT_function|BOOST_FT_member_pointer -#define BOOST_FT_al_path boost/function_types/detail/synthesize_impl -#include - -} } } // namespace ::boost::function_types::detail - -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_0.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_0.hpp deleted file mode 100644 index ad22e504..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_0.hpp +++ /dev/null @@ -1,334 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,0) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (BOOST_FT_nullary_param BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 1 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,0) -< typename mpl::deref< iter_0 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,1) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 2 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,1) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,2) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 3 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,2) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,3) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 4 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,3) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,4) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 5 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,4) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,5) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 6 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,5) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,6) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 7 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,6) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,7) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 8 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,7) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,8) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 9 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,8) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,9) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 10 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,9) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,10) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 11 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,10) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_1.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_1.hpp deleted file mode 100644 index bbd5963f..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity10_1.hpp +++ /dev/null @@ -1,326 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,1) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) ( BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 2 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,1) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,2) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 3 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,2) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,3) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 4 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,3) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,4) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 5 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,4) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,5) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 6 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,5) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,6) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 7 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,6) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,7) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 8 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,7) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,8) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 9 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,8) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,9) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 10 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,9) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,10) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 11 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,10) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_0.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_0.hpp deleted file mode 100644 index cb62e691..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_0.hpp +++ /dev/null @@ -1,517 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,11) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 12 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,11) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,12) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 13 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,12) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,13) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 14 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,13) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,14) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 15 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,14) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,15) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 16 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,15) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,16) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 17 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,16) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,17) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 18 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,17) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,18) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 19 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,18) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,19) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 20 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,19) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,20) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 21 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,20) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_1.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_1.hpp deleted file mode 100644 index 1c5e1e74..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity20_1.hpp +++ /dev/null @@ -1,527 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,11) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 12 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,11) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,12) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 13 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,12) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,13) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 14 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,13) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,14) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 15 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,14) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,15) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 16 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,15) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,16) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 17 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,16) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,17) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 18 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,17) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,18) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 19 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,18) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,19) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 20 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,19) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,20) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 21 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,20) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_0.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_0.hpp deleted file mode 100644 index 63a64f0d..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_0.hpp +++ /dev/null @@ -1,717 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,21) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 22 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,21) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,22) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 23 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,22) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,23) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 24 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,23) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,24) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 25 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,24) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,25) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 26 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,25) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,26) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 27 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,26) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,27) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 28 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,27) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,28) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 29 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,28) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,29) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 30 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,29) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,30) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 31 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,30) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_1.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_1.hpp deleted file mode 100644 index 6cba73ea..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity30_1.hpp +++ /dev/null @@ -1,727 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,21) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 22 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,21) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,22) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 23 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,22) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,23) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 24 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,23) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,24) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 25 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,24) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,25) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 26 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,25) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,26) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 27 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,26) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,27) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 28 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,27) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,28) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 29 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,28) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,29) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 30 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,29) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,30) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 31 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,30) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_0.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_0.hpp deleted file mode 100644 index b0657570..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_0.hpp +++ /dev/null @@ -1,917 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,31) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 32 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,31) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,32) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 33 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,32) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,33) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 34 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,33) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,34) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 35 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,34) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,35) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 36 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,35) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,36) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 37 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,36) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,37) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 38 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,37) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,38) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 39 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,38) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,39) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 40 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,39) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,40) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 41 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,40) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_1.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_1.hpp deleted file mode 100644 index c9f21941..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity40_1.hpp +++ /dev/null @@ -1,927 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,31) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 32 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,31) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,32) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 33 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,32) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,33) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 34 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,33) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,34) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 35 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,34) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,35) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 36 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,35) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,36) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 37 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,36) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,37) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 38 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,37) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,38) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 39 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,38) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,39) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 40 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,39) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,40) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 41 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,40) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_0.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_0.hpp deleted file mode 100644 index b1ad7b14..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_0.hpp +++ /dev/null @@ -1,1117 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,41) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 42 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,41) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,42) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 43 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,42) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,43) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 44 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,43) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,44) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 45 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,44) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,45) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 46 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,45) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,46) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 47 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,46) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,47) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 48 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,47) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,48) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 49 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -typedef typename mpl::next< iter_47 > ::type iter_48; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,48) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -, typename mpl::deref< iter_48 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,49) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 50 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -typedef typename mpl::next< iter_47 > ::type iter_48; -typedef typename mpl::next< iter_48 > ::type iter_49; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,49) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -, typename mpl::deref< iter_48 > ::type -, typename mpl::deref< iter_49 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 , typename T49 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,50) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 , T49 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 51 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -typedef typename mpl::next< iter_47 > ::type iter_48; -typedef typename mpl::next< iter_48 > ::type iter_49; -typedef typename mpl::next< iter_49 > ::type iter_50; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,50) -< typename mpl::deref< iter_0 > ::type -, typename mpl::deref< iter_1 > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -, typename mpl::deref< iter_48 > ::type -, typename mpl::deref< iter_49 > ::type -, typename mpl::deref< iter_50 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_1.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_1.hpp deleted file mode 100644 index 2915c412..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/arity50_1.hpp +++ /dev/null @@ -1,1127 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -// input: BOOST_FT_syntax type macro to use -// input: BOOST_FT_cc empty or cc specifier -// input: BOOST_FT_ell empty or "..." -// input: BOOST_FT_cv empty or cv qualifiers -// input: BOOST_FT_flags single decimal integer encoding the flags -// output: BOOST_FT_n number of component types (arity+1) -// output: BOOST_FT_arity current arity -// output: BOOST_FT_type macro that expands to the type -// output: BOOST_FT_tplargs(p) template arguments with given prefix -// output: BOOST_FT_params(p) parameters with given prefix - -# include -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,41) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 42 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,41) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,42) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 43 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,42) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,43) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 44 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,43) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,44) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 45 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,44) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,45) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 46 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,45) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,46) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 47 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,46) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,47) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 48 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,47) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,48) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 49 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -typedef typename mpl::next< iter_47 > ::type iter_48; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,48) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -, typename mpl::deref< iter_48 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,49) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 50 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -typedef typename mpl::next< iter_47 > ::type iter_48; -typedef typename mpl::next< iter_48 > ::type iter_49; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,49) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -, typename mpl::deref< iter_48 > ::type -, typename mpl::deref< iter_49 > ::type -> ::type type; -}; -}; -template< typename R , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename T10 , typename T11 , typename T12 , typename T13 , typename T14 , typename T15 , typename T16 , typename T17 , typename T18 , typename T19 , typename T20 , typename T21 , typename T22 , typename T23 , typename T24 , typename T25 , typename T26 , typename T27 , typename T28 , typename T29 , typename T30 , typename T31 , typename T32 , typename T33 , typename T34 , typename T35 , typename T36 , typename T37 , typename T38 , typename T39 , typename T40 , typename T41 , typename T42 , typename T43 , typename T44 , typename T45 , typename T46 , typename T47 , typename T48 , typename T49 > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,50) -{ -typedef BOOST_FT_syntax(BOOST_FT_cc,type BOOST_PP_EMPTY) (T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , T16 , T17 , T18 , T19 , T20 , T21 , T22 , T23 , T24 , T25 , T26 , T27 , T28 , T29 , T30 , T31 , T32 , T33 , T34 , T35 , T36 , T37 , T38 , T39 , T40 , T41 , T42 , T43 , T44 , T45 , T46 , T47 , T48 , T49 BOOST_FT_ell) BOOST_FT_cv ; -}; -template< > -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, 51 > -{ -template struct synthesize_impl_i -{ -private: -typedef typename mpl::begin ::type iter_0; -typedef typename mpl::next< iter_0 > ::type iter_1; -typedef typename mpl::next< iter_1 > ::type iter_2; -typedef typename mpl::next< iter_2 > ::type iter_3; -typedef typename mpl::next< iter_3 > ::type iter_4; -typedef typename mpl::next< iter_4 > ::type iter_5; -typedef typename mpl::next< iter_5 > ::type iter_6; -typedef typename mpl::next< iter_6 > ::type iter_7; -typedef typename mpl::next< iter_7 > ::type iter_8; -typedef typename mpl::next< iter_8 > ::type iter_9; -typedef typename mpl::next< iter_9 > ::type iter_10; -typedef typename mpl::next< iter_10 > ::type iter_11; -typedef typename mpl::next< iter_11 > ::type iter_12; -typedef typename mpl::next< iter_12 > ::type iter_13; -typedef typename mpl::next< iter_13 > ::type iter_14; -typedef typename mpl::next< iter_14 > ::type iter_15; -typedef typename mpl::next< iter_15 > ::type iter_16; -typedef typename mpl::next< iter_16 > ::type iter_17; -typedef typename mpl::next< iter_17 > ::type iter_18; -typedef typename mpl::next< iter_18 > ::type iter_19; -typedef typename mpl::next< iter_19 > ::type iter_20; -typedef typename mpl::next< iter_20 > ::type iter_21; -typedef typename mpl::next< iter_21 > ::type iter_22; -typedef typename mpl::next< iter_22 > ::type iter_23; -typedef typename mpl::next< iter_23 > ::type iter_24; -typedef typename mpl::next< iter_24 > ::type iter_25; -typedef typename mpl::next< iter_25 > ::type iter_26; -typedef typename mpl::next< iter_26 > ::type iter_27; -typedef typename mpl::next< iter_27 > ::type iter_28; -typedef typename mpl::next< iter_28 > ::type iter_29; -typedef typename mpl::next< iter_29 > ::type iter_30; -typedef typename mpl::next< iter_30 > ::type iter_31; -typedef typename mpl::next< iter_31 > ::type iter_32; -typedef typename mpl::next< iter_32 > ::type iter_33; -typedef typename mpl::next< iter_33 > ::type iter_34; -typedef typename mpl::next< iter_34 > ::type iter_35; -typedef typename mpl::next< iter_35 > ::type iter_36; -typedef typename mpl::next< iter_36 > ::type iter_37; -typedef typename mpl::next< iter_37 > ::type iter_38; -typedef typename mpl::next< iter_38 > ::type iter_39; -typedef typename mpl::next< iter_39 > ::type iter_40; -typedef typename mpl::next< iter_40 > ::type iter_41; -typedef typename mpl::next< iter_41 > ::type iter_42; -typedef typename mpl::next< iter_42 > ::type iter_43; -typedef typename mpl::next< iter_43 > ::type iter_44; -typedef typename mpl::next< iter_44 > ::type iter_45; -typedef typename mpl::next< iter_45 > ::type iter_46; -typedef typename mpl::next< iter_46 > ::type iter_47; -typedef typename mpl::next< iter_47 > ::type iter_48; -typedef typename mpl::next< iter_48 > ::type iter_49; -typedef typename mpl::next< iter_49 > ::type iter_50; -public: -typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,50) -< typename mpl::deref< iter_0 > ::type -, typename detail::cv_traits< -typename mpl::deref< iter_1 > ::type > ::type -, typename mpl::deref< iter_2 > ::type -, typename mpl::deref< iter_3 > ::type -, typename mpl::deref< iter_4 > ::type -, typename mpl::deref< iter_5 > ::type -, typename mpl::deref< iter_6 > ::type -, typename mpl::deref< iter_7 > ::type -, typename mpl::deref< iter_8 > ::type -, typename mpl::deref< iter_9 > ::type -, typename mpl::deref< iter_10 > ::type -, typename mpl::deref< iter_11 > ::type -, typename mpl::deref< iter_12 > ::type -, typename mpl::deref< iter_13 > ::type -, typename mpl::deref< iter_14 > ::type -, typename mpl::deref< iter_15 > ::type -, typename mpl::deref< iter_16 > ::type -, typename mpl::deref< iter_17 > ::type -, typename mpl::deref< iter_18 > ::type -, typename mpl::deref< iter_19 > ::type -, typename mpl::deref< iter_20 > ::type -, typename mpl::deref< iter_21 > ::type -, typename mpl::deref< iter_22 > ::type -, typename mpl::deref< iter_23 > ::type -, typename mpl::deref< iter_24 > ::type -, typename mpl::deref< iter_25 > ::type -, typename mpl::deref< iter_26 > ::type -, typename mpl::deref< iter_27 > ::type -, typename mpl::deref< iter_28 > ::type -, typename mpl::deref< iter_29 > ::type -, typename mpl::deref< iter_30 > ::type -, typename mpl::deref< iter_31 > ::type -, typename mpl::deref< iter_32 > ::type -, typename mpl::deref< iter_33 > ::type -, typename mpl::deref< iter_34 > ::type -, typename mpl::deref< iter_35 > ::type -, typename mpl::deref< iter_36 > ::type -, typename mpl::deref< iter_37 > ::type -, typename mpl::deref< iter_38 > ::type -, typename mpl::deref< iter_39 > ::type -, typename mpl::deref< iter_40 > ::type -, typename mpl::deref< iter_41 > ::type -, typename mpl::deref< iter_42 > ::type -, typename mpl::deref< iter_43 > ::type -, typename mpl::deref< iter_44 > ::type -, typename mpl::deref< iter_45 > ::type -, typename mpl::deref< iter_46 > ::type -, typename mpl::deref< iter_47 > ::type -, typename mpl::deref< iter_48 > ::type -, typename mpl::deref< iter_49 > ::type -, typename mpl::deref< iter_50 > ::type -> ::type type; -}; -}; -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl - diff --git a/utils/boost_idb/boost/function_types/detail/synthesize_impl/master.hpp b/utils/boost_idb/boost/function_types/detail/synthesize_impl/master.hpp deleted file mode 100644 index 49d38ef4..00000000 --- a/utils/boost_idb/boost/function_types/detail/synthesize_impl/master.hpp +++ /dev/null @@ -1,87 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -// no include guards, this file is intended for multiple inclusion - -#if BOOST_FT_ARITY_LOOP_PREFIX - -# ifndef BOOST_FT_DETAIL_SYNTHESIZE_IMPL_MASTER_HPP_INCLUDED -# define BOOST_FT_DETAIL_SYNTHESIZE_IMPL_MASTER_HPP_INCLUDED -# include -# include -# include -# include -# include -# endif - -# define BOOST_FT_type_name type - -# ifdef BOOST_FT_flags -# define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -# define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -# else -BOOST_PP_EXPAND(#) define BOOST_FT_make_type(flags,cc,arity) BOOST_FT_make_type_impl(flags,cc,arity) -BOOST_PP_EXPAND(#) define BOOST_FT_make_type_impl(flags,cc,arity) make_type_ ## flags ## _ ## cc ## _ ## arity -# endif - -# define BOOST_FT_iter(i) BOOST_PP_CAT(iter_,i) - -#elif BOOST_FT_ARITY_LOOP_IS_ITERATING - -template< BOOST_FT_tplargs(BOOST_PP_IDENTITY(typename)) > -struct BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,BOOST_FT_arity) -{ - typedef BOOST_FT_type ; -}; - -template<> -struct synthesize_impl_o< BOOST_FT_flags, BOOST_FT_cc_id, BOOST_FT_n > -{ - template struct synthesize_impl_i - { - private: - typedef typename mpl::begin::type BOOST_FT_iter(0); -# if BOOST_FT_n > 1 -# define BOOST_PP_LOCAL_MACRO(i) typedef typename mpl::next< \ - BOOST_FT_iter(BOOST_PP_DEC(i)) >::type BOOST_FT_iter(i); -# define BOOST_PP_LOCAL_LIMITS (1,BOOST_FT_n-1) -# include BOOST_PP_LOCAL_ITERATE() -# endif - public: - typedef typename detail::BOOST_FT_make_type(BOOST_FT_flags,BOOST_FT_cc_id,BOOST_FT_arity) - < typename mpl::deref< BOOST_FT_iter(0) >::type -# if BOOST_FT_mfp - , typename detail::cv_traits< - typename mpl::deref< BOOST_FT_iter(1) >::type >::type -# endif -# if BOOST_FT_n > (BOOST_FT_mfp+1) -# define BOOST_PP_LOCAL_LIMITS (BOOST_FT_mfp+1,BOOST_FT_n-1) -# define BOOST_PP_LOCAL_MACRO(i) \ - , typename mpl::deref< BOOST_FT_iter(i) >::type -# include BOOST_PP_LOCAL_ITERATE() -# endif - >::type type; - }; -}; - -#elif BOOST_FT_ARITY_LOOP_SUFFIX - -# ifdef BOOST_FT_flags -# undef BOOST_FT_make_type -# undef BOOST_FT_make_type_impl -# else -BOOST_PP_EXPAND(#) undef BOOST_FT_make_type -BOOST_PP_EXPAND(#) undef BOOST_FT_make_type_impl -# endif -# undef BOOST_FT_iter -# undef BOOST_FT_type_name - -#else -# error "attempt to use arity loop master file without loop" -#endif - diff --git a/utils/boost_idb/boost/function_types/detail/to_sequence.hpp b/utils/boost_idb/boost/function_types/detail/to_sequence.hpp deleted file mode 100644 index 828acd9a..00000000 --- a/utils/boost_idb/boost/function_types/detail/to_sequence.hpp +++ /dev/null @@ -1,47 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_TO_SEQUENCE_HPP_INCLUDED -#define BOOST_FT_DETAIL_TO_SEQUENCE_HPP_INCLUDED - -#include -#include -#include -#include -#include - -#include - -namespace boost { namespace function_types { namespace detail { - -// wrap first arguments in components, if callable builtin type -template -struct to_sequence -{ - typedef typename - mpl::eval_if - < is_callable_builtin - , to_sequence< components > - , mpl::identity< T > - >::type - type; -}; - -#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -// reduce template instantiations, if possible -template -struct to_sequence< components > -{ - typedef typename components::types type; -}; -#endif - -} } } // namespace ::boost::function_types::detail - -#endif - diff --git a/utils/boost_idb/boost/function_types/function_arity.hpp b/utils/boost_idb/boost/function_types/function_arity.hpp deleted file mode 100644 index 40f0f653..00000000 --- a/utils/boost_idb/boost/function_types/function_arity.hpp +++ /dev/null @@ -1,38 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_FUNCTION_ARITY_HPP_INCLUDED -#define BOOST_FT_FUNCTION_ARITY_HPP_INCLUDED - -#include -#include - -#include -#include - -#include -#include - -namespace boost -{ - namespace function_types - { - template struct function_arity - : mpl::if_ - < function_types::is_callable_builtin - , typename components::function_arity, boost::blank - >::type - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(1,function_arity,(T)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(1,function_types::function_arity) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/function_pointer.hpp b/utils/boost_idb/boost/function_types/function_pointer.hpp deleted file mode 100644 index a8b832f3..00000000 --- a/utils/boost_idb/boost/function_types/function_pointer.hpp +++ /dev/null @@ -1,32 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_FUNCTION_POINTER_HPP_INCLUDED -#define BOOST_FT_FUNCTION_POINTER_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template struct function_pointer - { - typedef typename function_types::function_type::type * type; - - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,function_pointer,(Types,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::function_pointer) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/function_reference.hpp b/utils/boost_idb/boost/function_types/function_reference.hpp deleted file mode 100644 index 5fe7e3cc..00000000 --- a/utils/boost_idb/boost/function_types/function_reference.hpp +++ /dev/null @@ -1,32 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_FUNCTION_REFERENCE_HPP_INCLUDED -#define BOOST_FT_FUNCTION_REFERENCE_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template struct function_reference - { - typedef typename function_types::function_type::type & type; - - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,function_reference,(Types,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::function_reference) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/function_type.hpp b/utils/boost_idb/boost/function_types/function_type.hpp deleted file mode 100644 index c3b2c96b..00000000 --- a/utils/boost_idb/boost/function_types/function_type.hpp +++ /dev/null @@ -1,29 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_FUNCTION_TYPE_HPP_INCLUDED -#define BOOST_FT_FUNCTION_TYPE_HPP_INCLUDED - -#include -#include - -namespace boost -{ - namespace function_types - { - template struct function_type - : detail::synthesize_func::type, Tag> - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,function_type,(Types,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::function_type) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/is_callable_builtin.hpp b/utils/boost_idb/boost/function_types/is_callable_builtin.hpp deleted file mode 100644 index b1a7c833..00000000 --- a/utils/boost_idb/boost/function_types/is_callable_builtin.hpp +++ /dev/null @@ -1,35 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_CALLABLE_BUILTIN_HPP_INCLUDED -#define BOOST_FT_IS_CALLABLE_BUILTIN_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_callable_builtin - : function_types::represents - < function_types::components - , function_types::tag - > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_callable_builtin,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_callable_builtin) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/is_function.hpp b/utils/boost_idb/boost/function_types/is_function.hpp deleted file mode 100644 index d29229bb..00000000 --- a/utils/boost_idb/boost/function_types/is_function.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_FUNCTION_HPP_INCLUDED -#define BOOST_FT_IS_FUNCTION_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_function - : function_types::represents - < function_types::components - , function_types::tag - > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_function,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_function) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/is_function_pointer.hpp b/utils/boost_idb/boost/function_types/is_function_pointer.hpp deleted file mode 100644 index 5bff6d36..00000000 --- a/utils/boost_idb/boost/function_types/is_function_pointer.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_FUNCTION_POINTER_HPP_INCLUDED -#define BOOST_FT_IS_FUNCTION_POINTER_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_function_pointer - : function_types::represents - < function_types::components - , function_types::tag - > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_function_pointer,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_function_pointer) -} - -#endif diff --git a/utils/boost_idb/boost/function_types/is_function_reference.hpp b/utils/boost_idb/boost/function_types/is_function_reference.hpp deleted file mode 100644 index f2e4c1c6..00000000 --- a/utils/boost_idb/boost/function_types/is_function_reference.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_FUNCTION_REFERENCE_HPP_INCLUDED -#define BOOST_FT_IS_FUNCTION_REFERENCE_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_function_reference - : function_types::represents - < function_types::components - , function_types::tag > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_function_reference,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_function_reference) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/is_member_function_pointer.hpp b/utils/boost_idb/boost/function_types/is_member_function_pointer.hpp deleted file mode 100644 index a5190352..00000000 --- a/utils/boost_idb/boost/function_types/is_member_function_pointer.hpp +++ /dev/null @@ -1,33 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_MEMBER_FUNCTION_POINTER_HPP_INCLUDED -#define BOOST_FT_IS_MEMBER_FUNCTION_POINTER_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_member_function_pointer - : function_types::represents - < function_types::components - , function_types::tag > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_member_function_pointer,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_member_function_pointer) -} -#endif - diff --git a/utils/boost_idb/boost/function_types/is_member_object_pointer.hpp b/utils/boost_idb/boost/function_types/is_member_object_pointer.hpp deleted file mode 100644 index 77527d9a..00000000 --- a/utils/boost_idb/boost/function_types/is_member_object_pointer.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_MEMBER_OBJECT_POINTER_HPP_INCLUDED -#define BOOST_FT_IS_MEMBER_OBJECT_POINTER_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T > - struct is_member_object_pointer - : function_types::detail::represents_impl - < function_types::components - , detail::member_object_pointer_tag > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(1,is_member_object_pointer,(T)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(1,function_types::is_member_object_pointer) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/is_member_pointer.hpp b/utils/boost_idb/boost/function_types/is_member_pointer.hpp deleted file mode 100644 index f53e0beb..00000000 --- a/utils/boost_idb/boost/function_types/is_member_pointer.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_MEMBER_POINTER_HPP_INCLUDED -#define BOOST_FT_IS_MEMBER_POINTER_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_member_pointer - : function_types::represents - < function_types::components - , function_types::tag - > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_member_pointer,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_member_pointer) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/is_nonmember_callable_builtin.hpp b/utils/boost_idb/boost/function_types/is_nonmember_callable_builtin.hpp deleted file mode 100644 index 3a27a2e7..00000000 --- a/utils/boost_idb/boost/function_types/is_nonmember_callable_builtin.hpp +++ /dev/null @@ -1,35 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_IS_NONMEMBER_CALLABLE_BUILTIN_HPP_INCLUDED -#define BOOST_FT_IS_NONMEMBER_CALLABLE_BUILTIN_HPP_INCLUDED - -#include -#include - -#include - -namespace boost -{ - namespace function_types - { - template< typename T, typename Tag = null_tag > - struct is_nonmember_callable_builtin - : function_types::represents - < function_types::components - , function_types::tag - > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,is_nonmember_callable_builtin,(T,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::is_nonmember_callable_builtin) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/member_function_pointer.hpp b/utils/boost_idb/boost/function_types/member_function_pointer.hpp deleted file mode 100644 index eab61118..00000000 --- a/utils/boost_idb/boost/function_types/member_function_pointer.hpp +++ /dev/null @@ -1,33 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_MEMBER_FUNCTION_POINTER_HPP_INCLUDED -#define BOOST_FT_MEMBER_FUNCTION_POINTER_HPP_INCLUDED - -#include -#include - -#include -#include - -namespace boost -{ - namespace function_types - { - template - struct member_function_pointer - : detail::synthesize_mfp< typename detail::to_sequence::type, Tag > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,member_function_pointer,(Types,Tag)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::member_function_pointer) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/member_object_pointer.hpp b/utils/boost_idb/boost/function_types/member_object_pointer.hpp deleted file mode 100644 index d0aa3f34..00000000 --- a/utils/boost_idb/boost/function_types/member_object_pointer.hpp +++ /dev/null @@ -1,34 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_MEMBER_OBJECT_POINTER_HPP_INCLUDED -#define BOOST_FT_MEMBER_OBJECT_POINTER_HPP_INCLUDED - -#include -#include - -#include -#include - -namespace boost -{ - namespace function_types - { - template - struct member_object_pointer - : detail::synthesize_mop< typename detail::to_sequence::type > - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(1,member_object_pointer,(Types)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(1,function_types::member_object_pointer) -} - -#endif - - diff --git a/utils/boost_idb/boost/function_types/parameter_types.hpp b/utils/boost_idb/boost/function_types/parameter_types.hpp deleted file mode 100644 index 5e049bf5..00000000 --- a/utils/boost_idb/boost/function_types/parameter_types.hpp +++ /dev/null @@ -1,55 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_PARAMETER_TYPES_HPP_INCLUDED -#define BOOST_FT_PARAMETER_TYPES_HPP_INCLUDED - -#include -#include - -#include -#include - -#include - -#include -#include - -namespace boost -{ - namespace function_types - { - using mpl::placeholders::_; - - template< typename T, typename ClassTypeTransform = add_reference<_> > - struct parameter_types; - - namespace detail - { - template - struct parameter_types_impl - : mpl::pop_front - < typename function_types::components::types - >::type - { }; - } - - template struct parameter_types - : mpl::if_ - < function_types::is_callable_builtin - , detail::parameter_types_impl, boost::blank - >::type - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(2,parameter_types,(T,ClassTypeTransform)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(2,function_types::parameter_types) -} - -#endif - diff --git a/utils/boost_idb/boost/function_types/property_tags.hpp b/utils/boost_idb/boost/function_types/property_tags.hpp deleted file mode 100644 index bbc64d53..00000000 --- a/utils/boost_idb/boost/function_types/property_tags.hpp +++ /dev/null @@ -1,149 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_DETAIL_TAGS_HPP_INCLUDED -#define BOOST_FT_DETAIL_TAGS_HPP_INCLUDED - -#include - -#include -#include - - -namespace boost { namespace function_types { - -namespace detail -{ - typedef long bits_t; - - template struct constant - : boost::integral_constant - { }; - - template struct property_tag - { - typedef constant bits; - typedef constant mask; - }; - - template struct bits : T::bits { }; - template struct mask : T::mask { }; - - // forward declaration, defined in pp_tags - template struct encode_bits_impl; - - // forward declaration, defined in pp_tags - template - struct tag_ice; - - // forward declaration, defined in retag_default_cc - template struct retag_default_cc; - - template struct encode_bits - : constant< - ::boost::function_types::detail::encode_bits_impl::value - > - { }; - - template struct compound_tag - { - typedef constant< - ::boost::function_types::detail::tag_ice - < ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - , ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - >::combined_bits - > bits; - - typedef constant< - ::boost::function_types::detail::tag_ice - < ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - , ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - >::combined_mask - > mask; - }; - - template - struct changed_tag - : Base - { - typedef mpl::bitxor_ - - bits; - }; - - template struct represents_impl - : boost::integral_constant::value - , ::boost::function_types::detail::mask::value - , ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - >::match - > - { }; - -} // namespace detail - -typedef detail::property_tag<0,0> null_tag; - -template -struct tag - : detail::compound_tag< detail::compound_tag, - detail::compound_tag > -{ }; - -#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -template struct tag - : detail::compound_tag,Tag3> -{ }; -template struct tag - : detail::compound_tag -{ }; -template struct tag - : Tag1 -{ }; -#endif - - -template struct represents - : detail::represents_impl > -{ }; - - -template struct extract -{ - typedef detail::constant< - ::boost::function_types::detail::tag_ice - < ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - , ::boost::function_types::detail::bits::value - , ::boost::function_types::detail::mask::value - >::extracted_bits - > bits; - - typedef detail::constant< - ::boost::function_types::detail::mask::value - > mask; -}; - -} } // namespace ::boost::function_types - -#include - -namespace boost { namespace function_types { -#define BOOST_FT_cc_file -#include -} } // namespace boost::function_types - -#endif - diff --git a/utils/boost_idb/boost/function_types/result_type.hpp b/utils/boost_idb/boost/function_types/result_type.hpp deleted file mode 100644 index 1fcaba66..00000000 --- a/utils/boost_idb/boost/function_types/result_type.hpp +++ /dev/null @@ -1,50 +0,0 @@ - -// (C) Copyright Tobias Schwinger -// -// Use modification and distribution are subject to the boost Software License, -// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). - -//------------------------------------------------------------------------------ - -#ifndef BOOST_FT_RESULT_TYPE_HPP_INCLUDED -#define BOOST_FT_RESULT_TYPE_HPP_INCLUDED - -#include -#include - -#include -#include - -#include - -#include -#include - -namespace boost -{ - namespace function_types - { - template< typename T > struct result_type; - - namespace detail - { - template struct result_type_impl - : mpl::at_c - < typename function_types::components::types, 0 > - { }; - } - - template struct result_type - : mpl::if_ - < function_types::is_callable_builtin - , detail::result_type_impl, boost::blank - >::type - { - BOOST_MPL_AUX_LAMBDA_SUPPORT(1,result_type,(T)) - }; - } - BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(1,function_types::result_type) -} - -#endif - diff --git a/utils/boost_idb/boost/functional/detail/container_fwd.hpp b/utils/boost_idb/boost/functional/detail/container_fwd.hpp new file mode 100644 index 00000000..9a69d155 --- /dev/null +++ b/utils/boost_idb/boost/functional/detail/container_fwd.hpp @@ -0,0 +1,19 @@ + +// Copyright 2005-2008 Daniel James. +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// Forwarding header for container_fwd.hpp's new location. +// This header is deprecated, I'll be adding a warning in a future release, +// then converting it to an error and finally removing this header completely. + +#if !defined(BOOST_FUNCTIONAL_DETAIL_CONTAINER_FWD_HPP) +#define BOOST_FUNCTIONAL_DETAIL_CONTAINER_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +# pragma once +#endif + +#include + +#endif diff --git a/utils/boost_idb/boost/functional/forward_adapter.hpp b/utils/boost_idb/boost/functional/forward_adapter.hpp index 796abd2b..c6e61a98 100644 --- a/utils/boost_idb/boost/functional/forward_adapter.hpp +++ b/utils/boost_idb/boost/functional/forward_adapter.hpp @@ -141,7 +141,7 @@ namespace boost { template< class Self > struct forward_adapter_result::apply< Self() > - : boost::result_of< BOOST_DEDUCED_TYPENAME c::t() > + : boost::result_of< typename c::t() > { }; template< class MD, class F, class FC > @@ -316,7 +316,7 @@ namespace boost template< class Self, BOOST_PP_ENUM_PARAMS(N,typename T) > struct forward_adapter_result::apply< Self(BOOST_PP_ENUM_PARAMS(N,T)) > : boost::result_of< - BOOST_DEDUCED_TYPENAME c::t(BOOST_PP_ENUM_BINARY_PARAMS(N, + typename c::t(BOOST_PP_ENUM_BINARY_PARAMS(N, typename q::t& BOOST_PP_INTERCEPT)) > { }; diff --git a/utils/boost_idb/boost/functional/hash/detail/float_functions.hpp b/utils/boost_idb/boost/functional/hash/detail/float_functions.hpp index 4b8374d4..ae03ff09 100644 --- a/utils/boost_idb/boost/functional/hash/detail/float_functions.hpp +++ b/utils/boost_idb/boost/functional/hash/detail/float_functions.hpp @@ -13,94 +13,6 @@ # pragma once #endif -// Set BOOST_HASH_CONFORMANT_FLOATS to 1 for libraries known to have -// sufficiently good floating point support to not require any -// workarounds. -// -// When set to 0, the library tries to automatically -// use the best available implementation. This normally works well, but -// breaks when ambiguities are created by odd namespacing of the functions. -// -// Note that if this is set to 0, the library should still take full -// advantage of the platform's floating point support. - -#if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#elif defined(__LIBCOMO__) -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#elif defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER) -// Rogue Wave library: -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#elif defined(_LIBCPP_VERSION) -// libc++ -# define BOOST_HASH_CONFORMANT_FLOATS 1 -#elif defined(__GLIBCPP__) || defined(__GLIBCXX__) -// GNU libstdc++ 3 -# if defined(__GNUC__) && __GNUC__ >= 4 -# define BOOST_HASH_CONFORMANT_FLOATS 1 -# else -# define BOOST_HASH_CONFORMANT_FLOATS 0 -# endif -#elif defined(__STL_CONFIG_H) -// generic SGI STL -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#elif defined(__MSL_CPP__) -// MSL standard lib: -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#elif defined(__IBMCPP__) -// VACPP std lib (probably conformant for much earlier version). -# if __IBMCPP__ >= 1210 -# define BOOST_HASH_CONFORMANT_FLOATS 1 -# else -# define BOOST_HASH_CONFORMANT_FLOATS 0 -# endif -#elif defined(MSIPL_COMPILE_H) -// Modena C++ standard library -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER) -// Dinkumware Library (this has to appear after any possible replacement libraries): -# if _CPPLIB_VER >= 405 -# define BOOST_HASH_CONFORMANT_FLOATS 1 -# else -# define BOOST_HASH_CONFORMANT_FLOATS 0 -# endif -#else -# define BOOST_HASH_CONFORMANT_FLOATS 0 -#endif - -#if BOOST_HASH_CONFORMANT_FLOATS - -// The standard library is known to be compliant, so don't use the -// configuration mechanism. - -namespace boost { - namespace hash_detail { - template - struct call_ldexp { - typedef Float float_type; - inline Float operator()(Float x, int y) const { - return std::ldexp(x, y); - } - }; - - template - struct call_frexp { - typedef Float float_type; - inline Float operator()(Float x, int* y) const { - return std::frexp(x, y); - } - }; - - template - struct select_hash_type - { - typedef Float type; - }; - } -} - -#else // BOOST_HASH_CONFORMANT_FLOATS == 0 - // The C++ standard requires that the C float functions are overloarded // for float, double and long double in the std namespace, but some of the older // library implementations don't support this. On some that don't, the C99 @@ -331,6 +243,4 @@ namespace boost } } -#endif // BOOST_HASH_CONFORMANT_FLOATS - #endif diff --git a/utils/boost_idb/boost/functional/hash/detail/hash_float.hpp b/utils/boost_idb/boost/functional/hash/detail/hash_float.hpp index 7c3de31a..ea1bc25f 100644 --- a/utils/boost_idb/boost/functional/hash/detail/hash_float.hpp +++ b/utils/boost_idb/boost/functional/hash/detail/hash_float.hpp @@ -1,5 +1,5 @@ -// Copyright 2005-2012 Daniel James. +// Copyright 2005-2009 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -13,19 +13,21 @@ #include #include #include -#include #include #include #include -#include -#include -#if defined(BOOST_MSVC) -#pragma warning(push) -#if BOOST_MSVC >= 1400 -#pragma warning(disable:6294) // Ill-defined for-loop: initial condition does - // not satisfy test. Loop body not executed -#endif +// Include hash implementation for the current platform. + +// Cygwn +#if defined(__CYGWIN__) +# if defined(__i386__) || defined(_M_IX86) +# include +# else +# include +# endif +#else +# include #endif // Can we use fpclassify? @@ -48,153 +50,6 @@ # define BOOST_HASH_USE_FPCLASSIFY 0 #endif -namespace boost -{ - namespace hash_detail - { - inline void hash_float_combine(std::size_t& seed, std::size_t value) - { - seed ^= value + (seed<<6) + (seed>>2); - } - - //////////////////////////////////////////////////////////////////////// - // Binary hash function - // - // Only used for floats with known iec559 floats, and certain values in - // numeric_limits - - inline std::size_t hash_binary(char* ptr, std::size_t length) - { - std::size_t seed = 0; - - if (length >= sizeof(std::size_t)) { - seed = *(std::size_t*) ptr; - length -= sizeof(std::size_t); - ptr += sizeof(std::size_t); - - while(length >= sizeof(std::size_t)) { - std::size_t buffer = 0; - std::memcpy(&buffer, ptr, sizeof(std::size_t)); - hash_float_combine(seed, buffer); - length -= sizeof(std::size_t); - ptr += sizeof(std::size_t); - } - } - - if (length > 0) { - std::size_t buffer = 0; - std::memcpy(&buffer, ptr, length); - hash_float_combine(seed, buffer); - } - - return seed; - } - - template - struct enable_binary_hash - { - BOOST_STATIC_CONSTANT(bool, value = - std::numeric_limits::is_iec559 && - std::numeric_limits::digits == digits && - std::numeric_limits::radix == 2 && - std::numeric_limits::max_exponent == max_exponent); - }; - - template - inline std::size_t float_hash_impl(Float v, - BOOST_DEDUCED_TYPENAME boost::enable_if_c< - enable_binary_hash::value, - std::size_t>::type) - { - return hash_binary((char*) &v, 4); - } - - - template - inline std::size_t float_hash_impl(Float v, - BOOST_DEDUCED_TYPENAME boost::enable_if_c< - enable_binary_hash::value, - std::size_t>::type) - { - return hash_binary((char*) &v, 8); - } - - template - inline std::size_t float_hash_impl(Float v, - BOOST_DEDUCED_TYPENAME boost::enable_if_c< - enable_binary_hash::value, - std::size_t>::type) - { - return hash_binary((char*) &v, 10); - } - - template - inline std::size_t float_hash_impl(Float v, - BOOST_DEDUCED_TYPENAME boost::enable_if_c< - enable_binary_hash::value, - std::size_t>::type) - { - return hash_binary((char*) &v, 16); - } - - //////////////////////////////////////////////////////////////////////// - // Portable hash function - // - // Used as a fallback when the binary hash function isn't supported. - - template - inline std::size_t float_hash_impl2(T v) - { - boost::hash_detail::call_frexp frexp; - boost::hash_detail::call_ldexp ldexp; - - int exp = 0; - - v = frexp(v, &exp); - - // A postive value is easier to hash, so combine the - // sign with the exponent and use the absolute value. - if(v < 0) { - v = -v; - exp += limits::max_exponent - - limits::min_exponent; - } - - v = ldexp(v, limits::digits); - std::size_t seed = static_cast(v); - v -= static_cast(seed); - - // ceiling(digits(T) * log2(radix(T))/ digits(size_t)) - 1; - std::size_t const length - = (limits::digits * - boost::static_log2::radix>::value - + limits::digits - 1) - / limits::digits; - - for(std::size_t i = 0; i != length; ++i) - { - v = ldexp(v, limits::digits); - std::size_t part = static_cast(v); - v -= static_cast(part); - hash_float_combine(seed, part); - } - - hash_float_combine(seed, exp); - - return seed; - } - -#if !defined(BOOST_HASH_DETAIL_TEST_WITHOUT_GENERIC) - template - inline std::size_t float_hash_impl(T v, ...) - { - typedef BOOST_DEDUCED_TYPENAME select_hash_type::type type; - return float_hash_impl2(static_cast(v)); - } -#endif - } -} - #if BOOST_HASH_USE_FPCLASSIFY #include @@ -206,15 +61,8 @@ namespace boost template inline std::size_t float_hash_value(T v) { -#if defined(fpclassify) - switch (fpclassify(v)) -#elif BOOST_HASH_CONFORMANT_FLOATS - switch (std::fpclassify(v)) -#else using namespace std; - switch (fpclassify(v)) -#endif - { + switch (fpclassify(v)) { case FP_ZERO: return 0; case FP_INFINITE: @@ -223,7 +71,7 @@ namespace boost return (std::size_t)(-3); case FP_NORMAL: case FP_SUBNORMAL: - return float_hash_impl(v, 0); + return float_hash_impl(v); default: BOOST_ASSERT(0); return 0; @@ -238,24 +86,10 @@ namespace boost { namespace hash_detail { - template - inline bool is_zero(T v) - { -#if !defined(__GNUC__) - return v == 0; -#else - // GCC's '-Wfloat-equal' will complain about comparing - // v to 0, but because it disables warnings for system - // headers it won't complain if you use std::equal_to to - // compare with 0. Resulting in this silliness: - return std::equal_to()(v, 0); -#endif - } - template inline std::size_t float_hash_value(T v) { - return boost::hash_detail::is_zero(v) ? 0 : float_hash_impl(v, 0); + return v == 0 ? 0 : float_hash_impl(v); } } } @@ -264,8 +98,4 @@ namespace boost #undef BOOST_HASH_USE_FPCLASSIFY -#if defined(BOOST_MSVC) -#pragma warning(pop) -#endif - #endif diff --git a/utils/boost_idb/boost/functional/hash/detail/hash_float_generic.hpp b/utils/boost_idb/boost/functional/hash/detail/hash_float_generic.hpp new file mode 100644 index 00000000..fdbf53fe --- /dev/null +++ b/utils/boost_idb/boost/functional/hash/detail/hash_float_generic.hpp @@ -0,0 +1,91 @@ + +// Copyright 2005-2009 Daniel James. +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// A general purpose hash function for non-zero floating point values. + +#if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_GENERIC_HEADER) +#define BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_GENERIC_HEADER + +#include +#include +#include + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +# pragma once +#endif + +#if defined(BOOST_MSVC) +#pragma warning(push) +#if BOOST_MSVC >= 1400 +#pragma warning(disable:6294) // Ill-defined for-loop: initial condition does + // not satisfy test. Loop body not executed +#endif +#endif + +namespace boost +{ + namespace hash_detail + { + inline void hash_float_combine(std::size_t& seed, std::size_t value) + { + seed ^= value + (seed<<6) + (seed>>2); + } + + template + inline std::size_t float_hash_impl2(T v) + { + boost::hash_detail::call_frexp frexp; + boost::hash_detail::call_ldexp ldexp; + + int exp = 0; + + v = frexp(v, &exp); + + // A postive value is easier to hash, so combine the + // sign with the exponent and use the absolute value. + if(v < 0) { + v = -v; + exp += limits::max_exponent - + limits::min_exponent; + } + + v = ldexp(v, limits::digits); + std::size_t seed = static_cast(v); + v -= seed; + + // ceiling(digits(T) * log2(radix(T))/ digits(size_t)) - 1; + std::size_t const length + = (limits::digits * + boost::static_log2::radix>::value + + limits::digits - 1) + / limits::digits; + + for(std::size_t i = 0; i != length; ++i) + { + v = ldexp(v, limits::digits); + std::size_t part = static_cast(v); + v -= part; + hash_float_combine(seed, part); + } + + hash_float_combine(seed, exp); + + return seed; + } + + template + inline std::size_t float_hash_impl(T v) + { + typedef BOOST_DEDUCED_TYPENAME select_hash_type::type type; + return float_hash_impl2(static_cast(v)); + } + } +} + +#if defined(BOOST_MSVC) +#pragma warning(pop) +#endif + +#endif diff --git a/utils/boost_idb/boost/functional/hash/detail/hash_float_x86.hpp b/utils/boost_idb/boost/functional/hash/detail/hash_float_x86.hpp new file mode 100644 index 00000000..b39bb0d0 --- /dev/null +++ b/utils/boost_idb/boost/functional/hash/detail/hash_float_x86.hpp @@ -0,0 +1,56 @@ + +// Copyright 2005-2009 Daniel James. +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// A non-portable hash function form non-zero floats on x86. +// +// Even if you're on an x86 platform, this might not work if their floating +// point isn't set up as this expects. So this should only be used if it's +// absolutely certain that it will work. + +#if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_X86_HEADER) +#define BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_X86_HEADER + +#include + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +# pragma once +#endif + +namespace boost +{ + namespace hash_detail + { + inline void hash_float_combine(std::size_t& seed, std::size_t value) + { + seed ^= value + (seed<<6) + (seed>>2); + } + + inline std::size_t float_hash_impl(float v) + { + boost::uint32_t* ptr = (boost::uint32_t*)&v; + std::size_t seed = *ptr; + return seed; + } + + inline std::size_t float_hash_impl(double v) + { + boost::uint32_t* ptr = (boost::uint32_t*)&v; + std::size_t seed = *ptr++; + hash_float_combine(seed, *ptr); + return seed; + } + + inline std::size_t float_hash_impl(long double v) + { + boost::uint32_t* ptr = (boost::uint32_t*)&v; + std::size_t seed = *ptr++; + hash_float_combine(seed, *ptr++); + hash_float_combine(seed, *(boost::uint16_t*)ptr); + return seed; + } + } +} + +#endif diff --git a/utils/boost_idb/boost/functional/hash/extensions.hpp b/utils/boost_idb/boost/functional/hash/extensions.hpp index 998c08e4..3c587a3b 100644 --- a/utils/boost_idb/boost/functional/hash/extensions.hpp +++ b/utils/boost_idb/boost/functional/hash/extensions.hpp @@ -15,22 +15,6 @@ #include #include -#include -#include -#include -#include - -#if !defined(BOOST_NO_CXX11_HDR_ARRAY) -# include -#endif - -#if !defined(BOOST_NO_CXX11_HDR_TUPLE) -# include -#endif - -#if !defined(BOOST_NO_CXX11_HDR_MEMORY) -# include -#endif #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once @@ -70,51 +54,51 @@ namespace boost std::size_t hash_value(std::pair const& v) { std::size_t seed = 0; - boost::hash_combine(seed, v.first); - boost::hash_combine(seed, v.second); + hash_combine(seed, v.first); + hash_combine(seed, v.second); return seed; } template std::size_t hash_value(std::vector const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template std::size_t hash_value(std::list const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template std::size_t hash_value(std::deque const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template std::size_t hash_value(std::set const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template std::size_t hash_value(std::multiset const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template std::size_t hash_value(std::map const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template std::size_t hash_value(std::multimap const& v) { - return boost::hash_range(v.begin(), v.end()); + return hash_range(v.begin(), v.end()); } template @@ -126,83 +110,6 @@ namespace boost return seed; } -#if !defined(BOOST_NO_CXX11_HDR_ARRAY) - template - std::size_t hash_value(std::array const& v) - { - return boost::hash_range(v.begin(), v.end()); - } -#endif - -#if !defined(BOOST_NO_CXX11_HDR_TUPLE) - namespace hash_detail { - template - inline typename boost::enable_if_c<(I == std::tuple_size::value), - void>::type - hash_combine_tuple(std::size_t&, T const&) - { - } - - template - inline typename boost::enable_if_c<(I < std::tuple_size::value), - void>::type - hash_combine_tuple(std::size_t& seed, T const& v) - { - boost::hash_combine(seed, std::get(v)); - boost::hash_detail::hash_combine_tuple(seed, v); - } - - template - inline std::size_t hash_tuple(T const& v) - { - std::size_t seed = 0; - boost::hash_detail::hash_combine_tuple<0>(seed, v); - return seed; - } - } - -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - template - inline std::size_t hash_value(std::tuple const& v) - { - return boost::hash_detail::hash_tuple(v); - } -#else - - inline std::size_t hash_value(std::tuple<> const& v) - { - return boost::hash_detail::hash_tuple(v); - } - -# define BOOST_HASH_TUPLE_F(z, n, _) \ - template< \ - BOOST_PP_ENUM_PARAMS_Z(z, n, typename A) \ - > \ - inline std::size_t hash_value(std::tuple< \ - BOOST_PP_ENUM_PARAMS_Z(z, n, A) \ - > const& v) \ - { \ - return boost::hash_detail::hash_tuple(v); \ - } - - BOOST_PP_REPEAT_FROM_TO(1, 11, BOOST_HASH_TUPLE_F, _) -# undef BOOST_HASH_TUPLE_F -#endif - -#endif - -#if !defined(BOOST_NO_CXX11_SMART_PTR) - template - inline std::size_t hash_value(std::shared_ptr const& x) { - return boost::hash_value(x.get()); - } - - template - inline std::size_t hash_value(std::unique_ptr const& x) { - return boost::hash_value(x.get()); - } -#endif - // // call_hash_impl // diff --git a/utils/boost_idb/boost/functional/hash/hash.hpp b/utils/boost_idb/boost/functional/hash/hash.hpp index 0adf9c90..0eedf7f7 100644 --- a/utils/boost_idb/boost/functional/hash/hash.hpp +++ b/utils/boost_idb/boost/functional/hash/hash.hpp @@ -15,23 +15,13 @@ #include #include #include -#include -#include -#include -#if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) -#include -#endif - -#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX) -#include +#if defined(BOOST_HASH_NO_IMPLICIT_CASTS) +#include #endif -#if defined(BOOST_MSVC) -#pragma warning(push) -#pragma warning(disable:6295) // Ill-defined for-loop : 'unsigned int' values - // are always of range '0' to '4294967295'. - // Loop executes infinitely. +#if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) +#include #endif #if BOOST_WORKAROUND(__GNUC__, < 3) \ @@ -43,82 +33,38 @@ namespace boost { - namespace hash_detail - { - struct enable_hash_value { typedef std::size_t type; }; - - template struct basic_numbers {}; - template struct long_numbers; - template struct ulong_numbers; - template struct float_numbers {}; - - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; +#if defined(BOOST_HASH_NO_IMPLICIT_CASTS) + + // If you get a static assertion here, it's because hash_value + // isn't declared for your type. + template + std::size_t hash_value(T const&) { + BOOST_STATIC_ASSERT((T*) 0 && false); + return 0; + } -#if !defined(BOOST_NO_INTRINSIC_WCHAR_T) - template <> struct basic_numbers : - boost::hash_detail::enable_hash_value {}; #endif - // long_numbers is defined like this to allow for separate - // specialization for long_long and int128_type, in case - // they conflict. - template struct long_numbers2 {}; - template struct ulong_numbers2 {}; - template struct long_numbers : long_numbers2 {}; - template struct ulong_numbers : ulong_numbers2 {}; + std::size_t hash_value(bool); + std::size_t hash_value(char); + std::size_t hash_value(unsigned char); + std::size_t hash_value(signed char); + std::size_t hash_value(short); + std::size_t hash_value(unsigned short); + std::size_t hash_value(int); + std::size_t hash_value(unsigned int); + std::size_t hash_value(long); + std::size_t hash_value(unsigned long); -#if !defined(BOOST_NO_LONG_LONG) - template <> struct long_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct ulong_numbers : - boost::hash_detail::enable_hash_value {}; +#if !defined(BOOST_NO_INTRINSIC_WCHAR_T) + std::size_t hash_value(wchar_t); #endif - -#if defined(BOOST_HAS_INT128) - template <> struct long_numbers2 : - boost::hash_detail::enable_hash_value {}; - template <> struct ulong_numbers2 : - boost::hash_detail::enable_hash_value {}; + +#if !defined(BOOST_NO_LONG_LONG) + std::size_t hash_value(boost::long_long_type); + std::size_t hash_value(boost::ulong_long_type); #endif - template <> struct float_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct float_numbers : - boost::hash_detail::enable_hash_value {}; - template <> struct float_numbers : - boost::hash_detail::enable_hash_value {}; - } - - template - typename boost::hash_detail::basic_numbers::type hash_value(T); - template - typename boost::hash_detail::long_numbers::type hash_value(T); - template - typename boost::hash_detail::ulong_numbers::type hash_value(T); - - template - typename boost::enable_if, std::size_t>::type - hash_value(T); - #if !BOOST_WORKAROUND(__DMC__, <= 0x848) template std::size_t hash_value(T* const&); #else @@ -133,17 +79,14 @@ namespace boost std::size_t hash_value(T (&x)[N]); #endif + std::size_t hash_value(float v); + std::size_t hash_value(double v); + std::size_t hash_value(long double v); + template std::size_t hash_value( std::basic_string, A> const&); - template - typename boost::hash_detail::float_numbers::type hash_value(T); - -#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX) - std::size_t hash_value(std::type_index); -#endif - // Implementation namespace hash_detail @@ -190,31 +133,75 @@ namespace boost } } - template - typename boost::hash_detail::basic_numbers::type hash_value(T v) + inline std::size_t hash_value(bool v) { return static_cast(v); } - template - typename boost::hash_detail::long_numbers::type hash_value(T v) + inline std::size_t hash_value(char v) { - return hash_detail::hash_value_signed(v); + return static_cast(v); } - template - typename boost::hash_detail::ulong_numbers::type hash_value(T v) + inline std::size_t hash_value(unsigned char v) { - return hash_detail::hash_value_unsigned(v); + return static_cast(v); } - template - typename boost::enable_if, std::size_t>::type - hash_value(T v) + inline std::size_t hash_value(signed char v) + { + return static_cast(v); + } + + inline std::size_t hash_value(short v) + { + return static_cast(v); + } + + inline std::size_t hash_value(unsigned short v) { return static_cast(v); } + inline std::size_t hash_value(int v) + { + return static_cast(v); + } + + inline std::size_t hash_value(unsigned int v) + { + return static_cast(v); + } + + inline std::size_t hash_value(long v) + { + return static_cast(v); + } + + inline std::size_t hash_value(unsigned long v) + { + return static_cast(v); + } + +#if !defined(BOOST_NO_INTRINSIC_WCHAR_T) + inline std::size_t hash_value(wchar_t v) + { + return static_cast(v); + } +#endif + +#if !defined(BOOST_NO_LONG_LONG) + inline std::size_t hash_value(boost::long_long_type v) + { + return hash_detail::hash_value_signed(v); + } + + inline std::size_t hash_value(boost::ulong_long_type v) + { + return hash_detail::hash_value_unsigned(v); + } +#endif + // Implementation by Alberto Barbati and Dave Harris. #if !BOOST_WORKAROUND(__DMC__, <= 0x848) template std::size_t hash_value(T* const& v) @@ -223,8 +210,8 @@ namespace boost #endif { #if defined(__VMS) && __INITIAL_POINTER_SIZE == 64 - // for some reason ptrdiff_t on OpenVMS compiler with - // 64 bit is not 64 bit !!! + // for some reason ptrdiff_t on OpenVMS compiler with + // 64 bit is not 64 bit !!! std::size_t x = static_cast( reinterpret_cast(v)); #else @@ -329,18 +316,20 @@ namespace boost return hash_range(v.begin(), v.end()); } - template - typename boost::hash_detail::float_numbers::type hash_value(T v) + inline std::size_t hash_value(float v) { return boost::hash_detail::float_hash_value(v); } -#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX) - inline std::size_t hash_value(std::type_index v) + inline std::size_t hash_value(double v) { - return v.hash_code(); + return boost::hash_detail::float_hash_value(v); + } + + inline std::size_t hash_value(long double v) + { + return boost::hash_detail::float_hash_value(v); } -#endif // // boost::hash @@ -446,15 +435,6 @@ namespace boost BOOST_HASH_SPECIALIZE(boost::ulong_long_type) #endif -#if defined(BOOST_HAS_INT128) - BOOST_HASH_SPECIALIZE(boost::int128_type) - BOOST_HASH_SPECIALIZE(boost::uint128_type) -#endif - -#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX) - BOOST_HASH_SPECIALIZE(std::type_index) -#endif - #undef BOOST_HASH_SPECIALIZE #undef BOOST_HASH_SPECIALIZE_REF @@ -525,10 +505,6 @@ namespace boost #undef BOOST_HASH_CHAR_TRAITS -#if defined(BOOST_MSVC) -#pragma warning(pop) -#endif - #endif // BOOST_FUNCTIONAL_HASH_HASH_HPP // Include this outside of the include guards in case the file is included diff --git a/utils/boost_idb/boost/functional/lightweight_forward_adapter.hpp b/utils/boost_idb/boost/functional/lightweight_forward_adapter.hpp index 637aa9e1..d21ac421 100644 --- a/utils/boost_idb/boost/functional/lightweight_forward_adapter.hpp +++ b/utils/boost_idb/boost/functional/lightweight_forward_adapter.hpp @@ -146,7 +146,7 @@ namespace boost { template< class Self > struct lightweight_forward_adapter_result::apply< Self() > - : boost::result_of< BOOST_DEDUCED_TYPENAME c::t() > + : boost::result_of< typename c::t() > { }; template< class MD, class F, class FC > @@ -205,7 +205,7 @@ namespace boost struct lightweight_forward_adapter_result::apply< Self (BOOST_PP_ENUM_PARAMS(N,T)) > : boost::result_of< - BOOST_DEDUCED_TYPENAME c::t (BOOST_PP_ENUM_BINARY_PARAMS(N, + typename c::t (BOOST_PP_ENUM_BINARY_PARAMS(N, typename x::t BOOST_PP_INTERCEPT)) > { }; diff --git a/utils/boost_idb/boost/functional/overloaded_function.hpp b/utils/boost_idb/boost/functional/overloaded_function.hpp deleted file mode 100644 index 83fe4b38..00000000 --- a/utils/boost_idb/boost/functional/overloaded_function.hpp +++ /dev/null @@ -1,311 +0,0 @@ - -// Copyright (C) 2009-2012 Lorenzo Caminiti -// Distributed under the Boost Software License, Version 1.0 -// (see accompanying file LICENSE_1_0.txt or a copy at -// http://www.boost.org/LICENSE_1_0.txt) -// Home at http://www.boost.org/libs/functional/overloaded_function - -#ifndef DOXYGEN // Doxygen documentation only. - -#if !BOOST_PP_IS_ITERATING -# ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_HPP_ -# define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_HPP_ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -#define BOOST_FUNCTIONAL_f_type(z, n, unused) \ - BOOST_PP_CAT(F, n) - -#define BOOST_FUNCTIONAL_f_arg(z, n, unused) \ - BOOST_PP_CAT(f, n) - -#define BOOST_FUNCTIONAL_f_tparam(z, n, unused) \ - typename BOOST_FUNCTIONAL_f_type(z, n, ~) \ - -#define BOOST_FUNCTIONAL_f_tparam_dflt(z, n, is_tspec) \ - BOOST_FUNCTIONAL_f_tparam(z, n, ~) \ - /* overload requires at least 2 functors so F0 and F1 not optional */ \ - BOOST_PP_EXPR_IIF(BOOST_PP_AND(BOOST_PP_NOT(is_tspec), \ - BOOST_PP_GREATER(n, 1)), \ - = void \ - ) - -#define BOOST_FUNCTIONAL_f_arg_decl(z, n, unused) \ - BOOST_FUNCTIONAL_f_type(z, n, ~) /* no qualifier to deduce tparam */ \ - BOOST_FUNCTIONAL_f_arg(z, n, ~) - -#define BOOST_FUNCTIONAL_g_type(z, n, unused) \ - BOOST_PP_CAT(G, n) - -#define BOOST_FUNCTIONAL_g_arg(z, n, unused) \ - BOOST_PP_CAT(g, n) - -#define BOOST_FUNCTIONAL_g_tparam(z, n, unused) \ - typename BOOST_FUNCTIONAL_g_type(z, n, ~) - -#define BOOST_FUNCTIONAL_g_arg_decl(z, n, unused) \ - BOOST_FUNCTIONAL_g_type(z, n, ~) /* no qualifier to deduce tparam */ \ - BOOST_FUNCTIONAL_g_arg(z, n, ~) - -#define BOOST_FUNCTIONAL_base(z, n, unused) \ - ::boost::overloaded_function_detail::base< \ - BOOST_FUNCTIONAL_f_type(z, n, ~) \ - > - -#define BOOST_FUNCTIONAL_inherit(z, n, unused) \ - public BOOST_FUNCTIONAL_base(z, n, ~) - -#define BOOST_FUNCTIONAL_base_init(z, n, unused) \ - BOOST_FUNCTIONAL_base(z, n, ~)(BOOST_FUNCTIONAL_g_arg(z, n, ~)) - -#define BOOST_FUNCTIONAL_using_operator_call(z, n, unused) \ - using BOOST_FUNCTIONAL_base(z, n, ~)::operator(); - -#define BOOST_FUNCTIONAL_function_type(z, n, unused) \ - typename ::boost::overloaded_function_detail::function_type< \ - BOOST_FUNCTIONAL_f_type(z, n, ~) \ - >::type - -# define BOOST_PP_ITERATION_PARAMS_1 \ - /* at least 2 func to overload so start from 2 to MAX */ \ - /* (cannot iterate [0, MAX-2) because error on Sun) */ \ - (3, (2, BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX, \ - "boost/functional/overloaded_function.hpp")) -# include BOOST_PP_ITERATE() // Iterate over function arity. - -#undef BOOST_FUNCTIONAL_f_type -#undef BOOST_FUNCTIONAL_f_arg -#undef BOOST_FUNCTIONAL_f_tparam -#undef BOOST_FUNCTIONAL_f_arg_decl -#undef BOOST_FUNCTIONAL_f_tparam_dflt -#undef BOOST_FUNCTIONAL_g_type -#undef BOOST_FUNCTIONAL_g_arg -#undef BOOST_FUNCTIONAL_g_tparam -#undef BOOST_FUNCTIONAL_g_arg_decl -#undef BOOST_FUNCTIONAL_base -#undef BOOST_FUNCTIONAL_inherit -#undef BOOST_FUNCTIONAL_base_init -#undef BOOST_FUNCTIONAL_using_operator_call -#undef BOOST_FUNCTIONAL_function_type - -# endif // #include guard - -#elif BOOST_PP_ITERATION_DEPTH() == 1 -# define BOOST_FUNCTIONAL_overloads \ - /* iterate as OVERLOADS, OVERLOADS-1, OVERLOADS-2, ... */ \ - /* (add 2 because iteration started from 2 to MAX) */ \ - BOOST_PP_ADD(2, BOOST_PP_SUB( \ - BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX, \ - BOOST_PP_FRAME_ITERATION(1))) -# define BOOST_FUNCTIONAL_is_tspec \ - /* if template specialization */ \ - BOOST_PP_LESS(BOOST_FUNCTIONAL_overloads, \ - BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX) - -// For type-of emulation: This must be included at this pp iteration level. -# include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() - -namespace boost { - -template< - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_f_tparam_dflt, - BOOST_FUNCTIONAL_is_tspec) -> -class overloaded_function - // Template specialization. - BOOST_PP_EXPR_IIF(BOOST_PP_EXPAND(BOOST_FUNCTIONAL_is_tspec), <) - BOOST_PP_IIF(BOOST_FUNCTIONAL_is_tspec, - BOOST_PP_ENUM - , - BOOST_PP_TUPLE_EAT(3) - )(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_f_type, ~) - BOOST_PP_EXPR_IIF(BOOST_PP_EXPAND(BOOST_FUNCTIONAL_is_tspec), >) - // Bases (overloads >= 2 so always at least 2 bases). - : BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, - BOOST_FUNCTIONAL_inherit, ~) -{ -public: - template< - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_g_tparam, ~) - > /* implicit */ inline overloaded_function( - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, - BOOST_FUNCTIONAL_g_arg_decl, ~)) - // Overloads >= 2 so always at least 2 bases to initialize. - : BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, - BOOST_FUNCTIONAL_base_init, ~) - {} - - BOOST_PP_REPEAT(BOOST_FUNCTIONAL_overloads, - BOOST_FUNCTIONAL_using_operator_call, ~) -}; - -template< - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_f_tparam, ~) -> -overloaded_function< - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_function_type, ~) -> make_overloaded_function( - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_f_arg_decl, ~) -) { - return overloaded_function< - BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, - BOOST_FUNCTIONAL_function_type, ~) - >(BOOST_PP_ENUM(BOOST_FUNCTIONAL_overloads, BOOST_FUNCTIONAL_f_arg, ~)); -} - -} // namespace - -// For type-of emulation: Register overloaded function type (for _AUTO, etc). -BOOST_TYPEOF_REGISTER_TEMPLATE(boost::overloaded_function, - BOOST_FUNCTIONAL_overloads) - -# undef BOOST_FUNCTIONAL_overloads -# undef BOOST_FUNCTIONAL_is_tspec -#endif // iteration - -// DOCUMENTATION // - -#else // DOXYGEN - -/** @file -@brief Overload distinct function pointers, function references, and -monomorphic function objects into a single function object. -*/ - -namespace boost { - -/** -@brief Function object to overload functions with distinct signatures. - -This function object aggregates together calls to functions of all the -specified function types F1, F2, etc which must have distinct -function signatures from one another. - -@Params -@Param{Fi, -Each function type must be specified using the following syntax (which is -Boost.Function's preferred syntax): -@code - result_type (argument1_type\, argumgnet2_type\, ...) -@endcode -} -@EndParams - -In some cases, the @RefFunc{make_overloaded_function} function template can be -useful to construct an overloaded function object without explicitly -specifying the function types. - -At least two distinct function types must be specified (because there is -nothing to overload between one or zero functions). -The maximum number of functions to overload is given by the -@RefMacro{BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX} -configuration macro. -The maximum number of function parameters for each of the specified function -types is given by the -@RefMacro{BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX} -configuration macro. - -@See @RefSect{tutorial, Tutorial} section, @RefFunc{make_overloaded_function}, -@RefMacro{BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX}, -@RefMacro{BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX}, -Boost.Function. -*/ -template -class overloaded_function { -public: - /** - @brief Construct the overloaded function object. - - Any function pointer, function reference, and monomorphic function object - that can be converted to a boost::function function object can be - specified as parameter. - - @Note Unfortunately, it is not possible to support polymorphic function - objects (as explained here). - */ - overloaded_function(const boost::function&, - const boost::function&, ...); - - /** - @brief Call operator matching the signature of the function type specified - as 1st template parameter. - - This will in turn invoke the call operator of the 1st function passed to - the constructor. - */ - typename boost::function_traits::result_type operator()( - typename boost::function_traits::arg1_type, - typename boost::function_traits::arg2_type, - ...) const; - - /** - @brief Call operator matching the signature of the function type specified - as 2nd template parameter. - - This will in turn invoke the call operator of the 2nd function passed to - the constructor. - - @Note Similar call operators are present for all specified function types - F1, F2, etc (even if not exhaustively listed by this - documentation). - */ - typename boost::function_traits::result_type operator()( - typename boost::function_traits::arg1_type, - typename boost::function_traits::arg2_type, - ...) const; -}; - -/** -@brief Make an overloaded function object without explicitly specifying the -function types. - -This function template creates and returns an @RefClass{overloaded_function} -object that overloads all the specified functions f1, f2, etc. - -The function types are internally determined from the template parameter types -so they do not need to be explicitly specified. -Therefore, this function template usually has a more concise syntax when -compared with @RefClass{overloaded_function}. -This is especially useful when the explicit type of the returned -@RefClass{overloaded_function} object does not need to be known (e.g., when -used with Boost.Typeof's BOOST_AUTO, C++11 auto, or when the -overloaded function object is handled using a function template parameter, see -the @RefSect{tutorial, Tutorial} section). - -The maximum number of functions to overload is given by the -@RefMacro{BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX} -configuration macro. - -@Note In this documentation, __function_type__ is a placeholder for a -symbol that is specific to the implementation of this library. - -@See @RefSect{tutorial, Tutorial} section, @RefClass{overloaded_function}, -@RefMacro{BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX}. -*/ -template -overloaded_function< - __function_type__, __function_type__, ... -> make_overloaded_function(F1 f1, F2 f2, ...); - -} // namespace - -#endif // DOXYGEN - diff --git a/utils/boost_idb/boost/functional/overloaded_function/config.hpp b/utils/boost_idb/boost/functional/overloaded_function/config.hpp deleted file mode 100644 index 2f5d9e13..00000000 --- a/utils/boost_idb/boost/functional/overloaded_function/config.hpp +++ /dev/null @@ -1,50 +0,0 @@ - -// Copyright (C) 2009-2012 Lorenzo Caminiti -// Distributed under the Boost Software License, Version 1.0 -// (see accompanying file LICENSE_1_0.txt or a copy at -// http://www.boost.org/LICENSE_1_0.txt) -// Home at http://www.boost.org/libs/functional/overloaded_function - -#ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_HPP_ -#define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_HPP_ - -/** @file -@brief Change the compile-time configuration of this library. -*/ - -/** -@brief Specify the maximum number of arguments of the functions being -overloaded. - -If this macro is left undefined by the user, it has a default value of 5 -(increasing this number might increase compilation time). -When specified by the user, this macro must be a non-negative integer number. - -@See @RefSect{getting_started, Getting Started}, -@RefClass{boost::overloaded_function}. -*/ -#ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX -# define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX 5 -#endif - -/** -@brief Specify the maximum number of functions that can be overloaded. - -If this macro is left undefined by the user, it has a default value of 5 -(increasing this number might increase compilation time). -When defined by the user, this macro must be an integer number greater or -equal than 2 (because at least two distinct functions need to be specified in -order to define an overload). - -@See @RefSect{getting_started, Getting Started}, -@RefClass{boost::overloaded_function}. -*/ -#ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX -# define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX 5 -#endif -#if BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX < 2 -# error "maximum overload macro cannot be less than 2" -#endif - -#endif // #include guard - diff --git a/utils/boost_idb/boost/functional/overloaded_function/detail/base.hpp b/utils/boost_idb/boost/functional/overloaded_function/detail/base.hpp deleted file mode 100644 index 8fd9a0a2..00000000 --- a/utils/boost_idb/boost/functional/overloaded_function/detail/base.hpp +++ /dev/null @@ -1,86 +0,0 @@ - -// Copyright (C) 2009-2012 Lorenzo Caminiti -// Distributed under the Boost Software License, Version 1.0 -// (see accompanying file LICENSE_1_0.txt or a copy at -// http://www.boost.org/LICENSE_1_0.txt) -// Home at http://www.boost.org/libs/functional/overloaded_function - -#if !BOOST_PP_IS_ITERATING -# ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_DETAIL_BASE_HPP_ -# define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_DETAIL_BASE_HPP_ - -# include -# include -# include -# include -# include -# include - -#define BOOST_FUNCTIONAL_DETAIL_arg_type(z, n, unused) \ - BOOST_PP_CAT(A, n) - -#define BOOST_FUNCTIONAL_DETAIL_arg_name(z, n, unused) \ - BOOST_PP_CAT(a, n) - -#define BOOST_FUNCTIONAL_DETAIL_arg_tparam(z, n, unused) \ - typename BOOST_FUNCTIONAL_DETAIL_arg_type(z, n, unused) - -#define BOOST_FUNCTIONAL_DETAIL_arg(z, n, unused) \ - BOOST_FUNCTIONAL_DETAIL_arg_type(z, n, unused) \ - BOOST_FUNCTIONAL_DETAIL_arg_name(z, n, unused) - -#define BOOST_FUNCTIONAL_DETAIL_f \ - R (BOOST_PP_ENUM(BOOST_FUNCTIONAL_DETAIL_arity, \ - BOOST_FUNCTIONAL_DETAIL_arg_type, ~)) - -// Do not use namespace ::detail because overloaded_function is already a class. -namespace boost { namespace overloaded_function_detail { - -template -class base {}; // Empty template cannot be used directly (only its spec). - -# define BOOST_PP_ITERATION_PARAMS_1 \ - (3, (0, BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX, \ - "boost/functional/overloaded_function/detail/base.hpp")) -# include BOOST_PP_ITERATE() // Iterate over funciton arity. - -} } // namespace - -#undef BOOST_FUNCTIONAL_DETAIL_arg_type -#undef BOOST_FUNCTIONAL_DETAIL_arg_name -#undef BOOST_FUNCTIONAL_DETAIL_arg_tparam -#undef BOOST_FUNCTIONAL_DETAIL_arg -#undef BOOST_FUNCTIONAL_DETAIL_f - -# endif // #include guard - -#elif BOOST_PP_ITERATION_DEPTH() == 1 -# define BOOST_FUNCTIONAL_DETAIL_arity BOOST_PP_FRAME_ITERATION(1) - -template< - typename R - BOOST_PP_COMMA_IF(BOOST_FUNCTIONAL_DETAIL_arity) - BOOST_PP_ENUM(BOOST_FUNCTIONAL_DETAIL_arity, - BOOST_FUNCTIONAL_DETAIL_arg_tparam, ~) -> -class base< BOOST_FUNCTIONAL_DETAIL_f > { -public: - /* implicit */ inline base( - // This requires specified type to be implicitly convertible to - // a boost::function<> functor. - boost::function< BOOST_FUNCTIONAL_DETAIL_f > const& f): f_(f) - {} - - inline R operator()(BOOST_PP_ENUM(BOOST_FUNCTIONAL_DETAIL_arity, - BOOST_FUNCTIONAL_DETAIL_arg, ~)) const { - return f_(BOOST_PP_ENUM(BOOST_FUNCTIONAL_DETAIL_arity, - BOOST_FUNCTIONAL_DETAIL_arg_name, ~)); - } - -private: - boost::function< BOOST_FUNCTIONAL_DETAIL_f > const f_; -}; - -# undef BOOST_FUNCTIONAL_DETAIL_arity -#endif // iteration - diff --git a/utils/boost_idb/boost/functional/overloaded_function/detail/function_type.hpp b/utils/boost_idb/boost/functional/overloaded_function/detail/function_type.hpp deleted file mode 100644 index 0c28607b..00000000 --- a/utils/boost_idb/boost/functional/overloaded_function/detail/function_type.hpp +++ /dev/null @@ -1,85 +0,0 @@ - -// Copyright (C) 2009-2012 Lorenzo Caminiti -// Distributed under the Boost Software License, Version 1.0 -// (see accompanying file LICENSE_1_0.txt or a copy at -// http://www.boost.org/LICENSE_1_0.txt) -// Home at http://www.boost.org/libs/functional/overloaded_function - -#ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_DETAIL_FUNCTION_TYPE_HPP_ -#define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_DETAIL_FUNCTION_TYPE_HPP_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Do not use namespace ::detail because overloaded_function is already a class. -namespace boost { namespace overloaded_function_detail { - -// Requires: F is a monomorphic functor (i.e., has non-template `operator()`). -// Returns: F's function type `result_type (arg1_type, arg2_type, ...)`. -// It does not assume F typedef result_type, arg1_type, ... but needs typeof. -template -class functor_type { - // NOTE: clang does not accept extra parenthesis `&(...)`. - typedef BOOST_TYPEOF_TPL(&F::operator()) call_ptr; -public: - typedef - typename boost::function_types::function_type< - typename boost::mpl::push_front< - typename boost::mpl::pop_front< // Remove functor type (1st). - typename boost::function_types::parameter_types< - call_ptr>::type - >::type - , typename boost::function_types::result_type::type - >::type - >::type - type; -}; - -// NOTE: When using boost::function in Boost.Typeof emulation mode, the user -// has to register boost::functionN instead of boost::function in oder to -// do TYPEOF(F::operator()). That is confusing, so boost::function is handled -// separately so it does not require any Boost.Typeof registration at all. -template -struct functor_type< boost::function > { - typedef F type; -}; - -// Requires: F is a function type, pointer, reference, or monomorphic functor. -// Returns: F's function type `result_type (arg1_type, arg2_type, ...)`. -template -struct function_type { - typedef - typename boost::mpl::if_, - boost::mpl::identity - , - typename boost::mpl::if_, - boost::remove_pointer - , - typename boost::mpl::if_, - boost::remove_reference - , // Else, requires that F is a functor. - functor_type - >::type - >::type - >::type - ::type type; -}; - -} } // namespace - -#endif // #include guard - diff --git a/utils/boost_idb/boost/generator_iterator.hpp b/utils/boost_idb/boost/generator_iterator.hpp new file mode 100644 index 00000000..ebf478b2 --- /dev/null +++ b/utils/boost_idb/boost/generator_iterator.hpp @@ -0,0 +1,80 @@ +// (C) Copyright Jens Maurer 2001. +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// Revision History: + +// 15 Nov 2001 Jens Maurer +// created. + +// See http://www.boost.org/libs/utility/iterator_adaptors.htm for documentation. + +#ifndef BOOST_ITERATOR_ADAPTOR_GENERATOR_ITERATOR_HPP +#define BOOST_ITERATOR_ADAPTOR_GENERATOR_ITERATOR_HPP + +#include +#include + +namespace boost { + +template +class generator_iterator + : public iterator_facade< + generator_iterator + , typename Generator::result_type + , single_pass_traversal_tag + , typename Generator::result_type const& + > +{ + typedef iterator_facade< + generator_iterator + , typename Generator::result_type + , single_pass_traversal_tag + , typename Generator::result_type const& + > super_t; + + public: + generator_iterator() {} + generator_iterator(Generator* g) : m_g(g), m_value((*m_g)()) {} + + void increment() + { + m_value = (*m_g)(); + } + + const typename Generator::result_type& + dereference() const + { + return m_value; + } + + bool equal(generator_iterator const& y) const + { + return this->m_g == y.m_g && this->m_value == y.m_value; + } + + private: + Generator* m_g; + typename Generator::result_type m_value; +}; + +template +struct generator_iterator_generator +{ + typedef generator_iterator type; +}; + +template +inline generator_iterator +make_generator_iterator(Generator & gen) +{ + typedef generator_iterator result_t; + return result_t(&gen); +} + +} // namespace boost + + +#endif // BOOST_ITERATOR_ADAPTOR_GENERATOR_ITERATOR_HPP + diff --git a/utils/boost_idb/boost/get_pointer.hpp b/utils/boost_idb/boost/get_pointer.hpp index b27b98a6..a0cd5c0b 100644 --- a/utils/boost_idb/boost/get_pointer.hpp +++ b/utils/boost_idb/boost/get_pointer.hpp @@ -3,15 +3,13 @@ // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef GET_POINTER_DWA20021219_HPP -#define GET_POINTER_DWA20021219_HPP - -#include +# define GET_POINTER_DWA20021219_HPP // In order to avoid circular dependencies with Boost.TR1 // we make sure that our include of doesn't try to // pull in the TR1 headers: that's why we use this header // rather than including directly: -#include // std::auto_ptr +# include // std::auto_ptr namespace boost { @@ -29,19 +27,6 @@ template T * get_pointer(std::auto_ptr const& p) return p.get(); } -#if !defined( BOOST_NO_CXX11_SMART_PTR ) - -template T * get_pointer( std::unique_ptr const& p ) -{ - return p.get(); -} - -template T * get_pointer( std::shared_ptr const& p ) -{ - return p.get(); -} - -#endif } // namespace boost diff --git a/utils/boost_idb/boost/implicit_cast.hpp b/utils/boost_idb/boost/implicit_cast.hpp new file mode 100644 index 00000000..5b1cd92b --- /dev/null +++ b/utils/boost_idb/boost/implicit_cast.hpp @@ -0,0 +1,29 @@ +// Copyright David Abrahams 2003. +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +#ifndef IMPLICIT_CAST_DWA200356_HPP +# define IMPLICIT_CAST_DWA200356_HPP + +# include + +namespace boost { + +// implementation originally suggested by C. Green in +// http://lists.boost.org/MailArchives/boost/msg00886.php + +// The use of identity creates a non-deduced form, so that the +// explicit template argument must be supplied +template +inline T implicit_cast (typename mpl::identity::type x) { + return x; +} + +// incomplete return type now is here +//template +//void implicit_cast (...); + +} // namespace boost + + +#endif // IMPLICIT_CAST_DWA200356_HPP diff --git a/utils/boost_idb/boost/indirect_reference.hpp b/utils/boost_idb/boost/indirect_reference.hpp new file mode 100644 index 00000000..5fbb3423 --- /dev/null +++ b/utils/boost_idb/boost/indirect_reference.hpp @@ -0,0 +1,43 @@ +#ifndef INDIRECT_REFERENCE_DWA200415_HPP +# define INDIRECT_REFERENCE_DWA200415_HPP + +// +// Copyright David Abrahams 2004. Use, modification and distribution is +// subject to the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// typename indirect_reference

::type provides the type of *p. +// +// http://www.boost.org/libs/iterator/doc/pointee.html +// + +# include +# include +# include +# include +# include + +namespace boost { + +namespace detail +{ + template + struct smart_ptr_reference + { + typedef typename boost::pointee

::type& type; + }; +} + +template +struct indirect_reference + : mpl::eval_if< + detail::is_incrementable

+ , iterator_reference

+ , detail::smart_ptr_reference

+ > +{ +}; + +} // namespace boost + +#endif // INDIRECT_REFERENCE_DWA200415_HPP diff --git a/utils/boost_idb/boost/integer.hpp b/utils/boost_idb/boost/integer.hpp index 35a1e109..fc0b3983 100644 --- a/utils/boost_idb/boost/integer.hpp +++ b/utils/boost_idb/boost/integer.hpp @@ -20,7 +20,6 @@ #include // for boost::::boost::integer_traits #include // for ::std::numeric_limits #include // for boost::int64_t and BOOST_NO_INTEGRAL_INT64_T -#include // // We simply cannot include this header on gcc without getting copious warnings of the kind: @@ -52,7 +51,6 @@ namespace boost // convert category to type template< int Category > struct int_least_helper {}; // default is empty - template< int Category > struct uint_least_helper {}; // default is empty // specializatons: 1=long, 2=int, 3=short, 4=signed char, // 6=unsigned long, 7=unsigned int, 8=unsigned short, 9=unsigned char @@ -67,14 +65,14 @@ namespace boost template<> struct int_least_helper<4> { typedef short least; }; template<> struct int_least_helper<5> { typedef signed char least; }; #ifdef BOOST_HAS_LONG_LONG - template<> struct uint_least_helper<1> { typedef boost::ulong_long_type least; }; + template<> struct int_least_helper<6> { typedef boost::ulong_long_type least; }; #elif defined(BOOST_HAS_MS_INT64) - template<> struct uint_least_helper<1> { typedef unsigned __int64 least; }; + template<> struct int_least_helper<6> { typedef unsigned __int64 least; }; #endif - template<> struct uint_least_helper<2> { typedef unsigned long least; }; - template<> struct uint_least_helper<3> { typedef unsigned int least; }; - template<> struct uint_least_helper<4> { typedef unsigned short least; }; - template<> struct uint_least_helper<5> { typedef unsigned char least; }; + template<> struct int_least_helper<7> { typedef unsigned long least; }; + template<> struct int_least_helper<8> { typedef unsigned int least; }; + template<> struct int_least_helper<9> { typedef unsigned short least; }; + template<> struct int_least_helper<10> { typedef unsigned char least; }; template struct exact_signed_base_helper{}; @@ -113,12 +111,10 @@ namespace boost template< int Bits > // bits (including sign) required struct int_t : public detail::exact_signed_base_helper { - BOOST_STATIC_ASSERT_MSG(Bits <= (int)(sizeof(boost::intmax_t) * CHAR_BIT), - "No suitable signed integer type with the requested number of bits is available."); typedef typename detail::int_least_helper < #ifdef BOOST_HAS_LONG_LONG - (Bits <= (int)(sizeof(boost::long_long_type) * CHAR_BIT)) + + (Bits-1 <= (int)(sizeof(boost::long_long_type) * CHAR_BIT)) + #else 1 + #endif @@ -134,8 +130,6 @@ namespace boost template< int Bits > // bits required struct uint_t : public detail::exact_unsigned_base_helper { - BOOST_STATIC_ASSERT_MSG(Bits <= (int)(sizeof(boost::uintmax_t) * CHAR_BIT), - "No suitable unsigned integer type with the requested number of bits is available."); #if (defined(__BORLANDC__) || defined(__CODEGEAR__)) && defined(BOOST_NO_INTEGRAL_INT64_T) // It's really not clear why this workaround should be needed... shrug I guess! JM BOOST_STATIC_CONSTANT(int, s = @@ -146,10 +140,11 @@ namespace boost (Bits <= ::std::numeric_limits::digits)); typedef typename detail::int_least_helper< ::boost::uint_t::s>::least least; #else - typedef typename detail::uint_least_helper + typedef typename detail::int_least_helper < + 5 + #ifdef BOOST_HAS_LONG_LONG - (Bits <= (int)(sizeof(boost::long_long_type) * CHAR_BIT)) + + (Bits-1 <= (int)(sizeof(boost::long_long_type) * CHAR_BIT)) + #else 1 + #endif @@ -222,7 +217,7 @@ namespace boost // It's really not clear why this workaround should be needed... shrug I guess! JM #if defined(BOOST_NO_INTEGRAL_INT64_T) BOOST_STATIC_CONSTANT(unsigned, which = - 1 + + 6 + (MaxValue <= ::boost::integer_traits::const_max) + (MaxValue <= ::boost::integer_traits::const_max) + (MaxValue <= ::boost::integer_traits::const_max) + @@ -230,17 +225,18 @@ namespace boost typedef typename detail::int_least_helper< ::boost::uint_value_t::which>::least least; #else // BOOST_NO_INTEGRAL_INT64_T BOOST_STATIC_CONSTANT(unsigned, which = - 1 + + 5 + (MaxValue <= ::boost::integer_traits::const_max) + (MaxValue <= ::boost::integer_traits::const_max) + (MaxValue <= ::boost::integer_traits::const_max) + (MaxValue <= ::boost::integer_traits::const_max) + (MaxValue <= ::boost::integer_traits::const_max)); - typedef typename detail::uint_least_helper< ::boost::uint_value_t::which>::least least; + typedef typename detail::int_least_helper< ::boost::uint_value_t::which>::least least; #endif // BOOST_NO_INTEGRAL_INT64_T #else - typedef typename detail::uint_least_helper + typedef typename detail::int_least_helper < + 5 + #if !defined(BOOST_NO_INTEGRAL_INT64_T) && defined(BOOST_HAS_LONG_LONG) (MaxValue <= ::boost::integer_traits::const_max) + #else diff --git a/utils/boost_idb/boost/integer_traits.hpp b/utils/boost_idb/boost/integer_traits.hpp index d896e46e..129ce82c 100644 --- a/utils/boost_idb/boost/integer_traits.hpp +++ b/utils/boost_idb/boost/integer_traits.hpp @@ -5,7 +5,7 @@ * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * - * $Id: integer_traits.hpp 85813 2013-09-21 20:17:00Z jewillco $ + * $Id: integer_traits.hpp 58381 2009-12-14 18:14:48Z johnmaddock $ * * Idea by Beman Dawes, Ed Brey, Steve Cleary, and Nathan Myers */ @@ -227,7 +227,7 @@ class integer_traits< ::boost::ulong_long_type> template<> class integer_traits< ::boost::long_long_type> : public std::numeric_limits< ::boost::long_long_type>, - public detail::integer_traits_base< ::boost::long_long_type, (1LL << (sizeof(::boost::long_long_type) * CHAR_BIT - 1)), ~(1LL << (sizeof(::boost::long_long_type) * CHAR_BIT - 1))> + public detail::integer_traits_base< ::boost::long_long_type, (1LL << (sizeof(::boost::long_long_type) - 1)), ~(1LL << (sizeof(::boost::long_long_type) - 1))> { }; template<> diff --git a/utils/boost_idb/boost/interprocess/allocators/adaptive_pool.hpp b/utils/boost_idb/boost/interprocess/allocators/adaptive_pool.hpp index 8a2d61ec..05043dac 100644 --- a/utils/boost_idb/boost/interprocess/allocators/adaptive_pool.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/adaptive_pool.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include @@ -28,21 +28,21 @@ #include #include #include -#include +#include #include #include #include #include //!\file -//!Describes adaptive_pool pooled shared memory STL compatible allocator +//!Describes adaptive_pool pooled shared memory STL compatible allocator namespace boost { namespace interprocess { /// @cond -namespace ipcdetail{ +namespace detail{ template < unsigned int Version , class T @@ -71,7 +71,7 @@ class adaptive_pool_base template struct node_pool { - typedef ipcdetail::shared_adaptive_node_pool + typedef detail::shared_adaptive_node_pool < SegmentManager, sizeof_value::value, NodesPerBlock, MaxFreeBlocks, OverheadPercent> type; static type *get(void *p) @@ -83,29 +83,27 @@ class adaptive_pool_base public: //------- - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; + typedef typename boost:: + pointer_to_other::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; typedef boost::interprocess::version_type version; - typedef boost::container::container_detail::transform_multiallocation_chain + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; - //!Obtains adaptive_pool_base from + //!Obtains adaptive_pool_base from //!adaptive_pool_base template struct rebind - { + { typedef adaptive_pool_base other; }; @@ -122,15 +120,15 @@ class adaptive_pool_base //!Constructor from a segment manager. If not present, constructs a node //!pool. Increments the reference count of the associated node pool. //!Can throw boost::interprocess::bad_alloc - adaptive_pool_base(segment_manager *segment_mngr) - : mp_node_pool(ipcdetail::get_or_create_node_pool::type>(segment_mngr)) { } + adaptive_pool_base(segment_manager *segment_mngr) + : mp_node_pool(detail::get_or_create_node_pool::type>(segment_mngr)) { } - //!Copy constructor from other adaptive_pool_base. Increments the reference + //!Copy constructor from other adaptive_pool_base. Increments the reference //!count of the associated node pool. Never throws - adaptive_pool_base(const adaptive_pool_base &other) - : mp_node_pool(other.get_node_pool()) - { - node_pool<0>::get(ipcdetail::to_raw_pointer(mp_node_pool))->inc_ref_count(); + adaptive_pool_base(const adaptive_pool_base &other) + : mp_node_pool(other.get_node_pool()) + { + node_pool<0>::get(detail::get_pointer(mp_node_pool))->inc_ref_count(); } //!Assignment from other adaptive_pool_base @@ -147,27 +145,27 @@ class adaptive_pool_base template adaptive_pool_base (const adaptive_pool_base &other) - : mp_node_pool(ipcdetail::get_or_create_node_pool::type>(other.get_segment_manager())) { } + : mp_node_pool(detail::get_or_create_node_pool::type>(other.get_segment_manager())) { } //!Destructor, removes node_pool_t from memory //!if its reference count reaches to zero. Never throws - ~adaptive_pool_base() - { ipcdetail::destroy_node_pool_if_last_link(node_pool<0>::get(ipcdetail::to_raw_pointer(mp_node_pool))); } + ~adaptive_pool_base() + { detail::destroy_node_pool_if_last_link(node_pool<0>::get(detail::get_pointer(mp_node_pool))); } //!Returns a pointer to the node pool. //!Never throws void* get_node_pool() const - { return ipcdetail::to_raw_pointer(mp_node_pool); } + { return detail::get_pointer(mp_node_pool); } //!Returns the segment manager. //!Never throws segment_manager* get_segment_manager()const - { return node_pool<0>::get(ipcdetail::to_raw_pointer(mp_node_pool))->get_segment_manager(); } + { return node_pool<0>::get(detail::get_pointer(mp_node_pool))->get_segment_manager(); } //!Swaps allocators. Does not throw. If each allocator is placed in a //!different memory segment, the result is undefined. friend void swap(self_t &alloc1, self_t &alloc2) - { ipcdetail::do_swap(alloc1.mp_node_pool, alloc2.mp_node_pool); } + { detail::do_swap(alloc1.mp_node_pool, alloc2.mp_node_pool); } /// @cond private: @@ -178,14 +176,14 @@ class adaptive_pool_base //!Equality test for same type //!of adaptive_pool_base template inline -bool operator==(const adaptive_pool_base &alloc1, +bool operator==(const adaptive_pool_base &alloc1, const adaptive_pool_base &alloc2) { return alloc1.get_node_pool() == alloc2.get_node_pool(); } //!Inequality test for same type //!of adaptive_pool_base template inline -bool operator!=(const adaptive_pool_base &alloc1, +bool operator!=(const adaptive_pool_base &alloc1, const adaptive_pool_base &alloc2) { return alloc1.get_node_pool() != alloc2.get_node_pool(); } @@ -206,16 +204,16 @@ class adaptive_pool_v1 > { public: - typedef ipcdetail::adaptive_pool_base + typedef detail::adaptive_pool_base < 1, T, SegmentManager, NodesPerBlock, MaxFreeBlocks, OverheadPercent> base_t; template struct rebind - { + { typedef adaptive_pool_v1 other; }; - adaptive_pool_v1(SegmentManager *segment_mngr) + adaptive_pool_v1(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -226,17 +224,17 @@ class adaptive_pool_v1 {} }; -} //namespace ipcdetail{ +} //namespace detail{ /// @endcond -//!An STL node allocator that uses a segment manager as memory +//!An STL node allocator that uses a segment manager as memory //!source. The internal pointer type will of the same type (raw, smart) as //!"typename SegmentManager::void_pointer" type. This allows //!placing the allocator in shared memory, memory mapped-files, etc... //! -//!This node allocator shares a segregated storage between all instances -//!of adaptive_pool with equal sizeof(T) placed in the same segment +//!This node allocator shares a segregated storage between all instances +//!of adaptive_pool with equal sizeof(T) placed in the same segment //!group. NodesPerBlock is the number of nodes allocated at once when the allocator //!needs runs out of nodes. MaxFreeBlocks is the maximum number of totally free blocks //!that the adaptive node pool will hold. The rest of the totally free blocks will be @@ -252,7 +250,7 @@ template < class T > class adaptive_pool /// @cond - : public ipcdetail::adaptive_pool_base + : public detail::adaptive_pool_base < 2 , T , SegmentManager @@ -264,18 +262,18 @@ class adaptive_pool { #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - typedef ipcdetail::adaptive_pool_base + typedef detail::adaptive_pool_base < 2, T, SegmentManager, NodesPerBlock, MaxFreeBlocks, OverheadPercent> base_t; public: typedef boost::interprocess::version_type version; template struct rebind - { + { typedef adaptive_pool other; }; - adaptive_pool(SegmentManager *segment_mngr) + adaptive_pool(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -292,18 +290,18 @@ class adaptive_pool typedef implementation_defined::pointer pointer; typedef implementation_defined::const_pointer const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; - //!Obtains adaptive_pool from + //!Obtains adaptive_pool from //!adaptive_pool template struct rebind - { + { typedef adaptive_pool other; }; @@ -314,7 +312,7 @@ class adaptive_pool adaptive_pool& operator= (const adaptive_pool&); - //!Not assignable from + //!Not assignable from //!other adaptive_pool //adaptive_pool& operator=(const adaptive_pool&); @@ -324,7 +322,7 @@ class adaptive_pool //!Can throw boost::interprocess::bad_alloc adaptive_pool(segment_manager *segment_mngr); - //!Copy constructor from other adaptive_pool. Increments the reference + //!Copy constructor from other adaptive_pool. Increments the reference //!count of the associated node pool. Never throws adaptive_pool(const adaptive_pool &other); @@ -351,7 +349,7 @@ class adaptive_pool //!Never throws size_type max_size() const; - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0); @@ -374,15 +372,15 @@ class adaptive_pool //!Returns address of non mutable object. //!Never throws const_pointer address(const_reference value) const; -/* - //!Copy construct an object. + + //!Copy construct an object. //!Throws if T's copy constructor throws void construct(const pointer &ptr, const_reference v); //!Destroys object. Throws if object's //!destructor throws void destroy(const pointer &ptr); -*/ + //!Returns maximum the number of objects the previously allocated memory //!pointed by p can hold. This size only works for memory allocated with //!allocate, allocation_command and allocate_many. @@ -390,7 +388,7 @@ class adaptive_pool std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0); @@ -400,12 +398,12 @@ class adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements); //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements); //!Allocates many elements of size elem_size in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -413,7 +411,7 @@ class adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -426,7 +424,7 @@ class adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_individual(std::size_t num_elements); //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -439,7 +437,7 @@ class adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain); + void deallocate_individual(multiallocation_chain it); #endif }; @@ -448,13 +446,13 @@ class adaptive_pool //!Equality test for same type //!of adaptive_pool template inline -bool operator==(const adaptive_pool &alloc1, +bool operator==(const adaptive_pool &alloc1, const adaptive_pool &alloc2); //!Inequality test for same type //!of adaptive_pool template inline -bool operator!=(const adaptive_pool &alloc1, +bool operator!=(const adaptive_pool &alloc1, const adaptive_pool &alloc2); #endif diff --git a/utils/boost_idb/boost/interprocess/allocators/allocator.hpp b/utils/boost_idb/boost/interprocess/allocators/allocator.hpp index 497cbd44..2c86f573 100644 --- a/utils/boost_idb/boost/interprocess/allocators/allocator.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/allocator.hpp @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,11 +18,11 @@ #include #include -#include +#include #include #include -#include +#include #include #include #include @@ -32,7 +32,6 @@ #include #include -#include #include #include #include @@ -45,12 +44,12 @@ namespace boost { namespace interprocess { -//!An STL compatible allocator that uses a segment manager as +//!An STL compatible allocator that uses a segment manager as //!memory source. The internal pointer type will of the same type (raw, smart) as //!"typename SegmentManager::void_pointer" type. This allows //!placing the allocator in shared memory, memory mapped-files, etc... template -class allocator +class allocator { public: //Segment manager @@ -67,14 +66,13 @@ class allocator typedef typename segment_manager::void_pointer aux_pointer_t; //Typedef to const void pointer - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type cvoid_ptr; + typedef typename + boost::pointer_to_other + ::type cvoid_ptr; //Pointer to the allocator - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type alloc_ptr_t; + typedef typename boost::pointer_to_other + ::type alloc_ptr_t; //Not assignable from related allocator template @@ -89,25 +87,23 @@ class allocator public: typedef T value_type; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; - typedef typename ipcdetail::add_reference + typedef typename boost::pointer_to_other + ::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; typedef boost::interprocess::version_type version; /// @cond //Experimental. Don't use. - typedef boost::container::container_detail::transform_multiallocation_chain + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; /// @endcond @@ -115,46 +111,45 @@ class allocator //!objects of type T2 template struct rebind - { + { typedef allocator other; }; //!Returns the segment manager. //!Never throws segment_manager* get_segment_manager()const - { return ipcdetail::to_raw_pointer(mp_mngr); } + { return detail::get_pointer(mp_mngr); } //!Constructor from the segment manager. //!Never throws - allocator(segment_manager *segment_mngr) + allocator(segment_manager *segment_mngr) : mp_mngr(segment_mngr) { } //!Constructor from other allocator. //!Never throws - allocator(const allocator &other) + allocator(const allocator &other) : mp_mngr(other.get_segment_manager()){ } //!Constructor from related allocator. //!Never throws template - allocator(const allocator &other) + allocator(const allocator &other) : mp_mngr(other.get_segment_manager()){} - //!Allocates memory for an array of count elements. + //!Allocates memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_ptr hint = 0) { (void)hint; - if(size_overflows(count)){ + if(count > this->max_size()) throw bad_alloc(); - } return pointer(static_cast(mp_mngr->allocate(count*sizeof(T)))); } //!Deallocates memory previously allocated. //!Never throws void deallocate(const pointer &ptr, size_type) - { mp_mngr->deallocate((void*)ipcdetail::to_raw_pointer(ptr)); } + { mp_mngr->deallocate((void*)detail::get_pointer(ptr)); } //!Returns the number of elements that could be allocated. //!Never throws @@ -164,24 +159,24 @@ class allocator //!Swap segment manager. Does not throw. If each allocator is placed in //!different memory segments, the result is undefined. friend void swap(self_t &alloc1, self_t &alloc2) - { ipcdetail::do_swap(alloc1.mp_mngr, alloc2.mp_mngr); } + { detail::do_swap(alloc1.mp_mngr, alloc2.mp_mngr); } //!Returns maximum the number of objects the previously allocated memory //!pointed by p can hold. This size only works for memory allocated with //!allocate, allocation_command and allocate_many. size_type size(const pointer &p) const - { - return (size_type)mp_mngr->size(ipcdetail::to_raw_pointer(p))/sizeof(T); + { + return (size_type)mp_mngr->size(detail::get_pointer(p))/sizeof(T); } std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0) { return mp_mngr->allocation_command - (command, limit_size, preferred_size, received_size, ipcdetail::to_raw_pointer(reuse)); + (command, limit_size, preferred_size, received_size, detail::get_pointer(reuse)); } //!Allocates many elements of size elem_size in a contiguous block @@ -190,20 +185,19 @@ class allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain) + multiallocation_chain allocate_many + (size_type elem_size, std::size_t num_elements) { - if(size_overflows(elem_size)){ - throw bad_alloc(); - } - mp_mngr->allocate_many(elem_size*sizeof(T), num_elements, chain); + return multiallocation_chain(mp_mngr->allocate_many(sizeof(T)*elem_size, num_elements)); } //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain) + multiallocation_chain allocate_many + (const size_type *elem_sizes, size_type n_elements) { - mp_mngr->allocate_many(elem_sizes, n_elements, sizeof(T), chain); + multiallocation_chain(mp_mngr->allocate_many(elem_sizes, n_elements, sizeof(T))); } //!Allocates many elements of size elem_size in a contiguous block @@ -212,8 +206,10 @@ class allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain) - { mp_mngr->deallocate_many(chain); } + void deallocate_many(multiallocation_chain chain) + { + return mp_mngr->deallocate_many(chain.extract_multiallocation_chain()); + } //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -227,8 +223,9 @@ class allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain) - { this->allocate_many(1, num_elements, chain); } + multiallocation_chain allocate_individual + (std::size_t num_elements) + { return this->allocate_many(1, num_elements); } //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -242,8 +239,8 @@ class allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain) - { this->deallocate_many(chain); } + void deallocate_individual(multiallocation_chain chain) + { return this->deallocate_many(boost::interprocess::move(chain)); } //!Returns address of mutable object. //!Never throws @@ -255,31 +252,33 @@ class allocator const_pointer address(const_reference value) const { return const_pointer(boost::addressof(value)); } - //!Constructs an object - //!Throws if T's constructor throws - //!For backwards compatibility with libraries using C++03 allocators - template - void construct(const pointer &ptr, BOOST_FWD_REF(P) p) - { ::new((void*)ipcdetail::to_raw_pointer(ptr)) value_type(::boost::forward

(p)); } + //!Copy construct an object + //!Throws if T's copy constructor throws + void construct(const pointer &ptr, const_reference v) + { new((void*)detail::get_pointer(ptr)) value_type(v); } + + //!Default construct an object. + //!Throws if T's default constructor throws + void construct(const pointer &ptr) + { new((void*)detail::get_pointer(ptr)) value_type; } //!Destroys object. Throws if object's //!destructor throws void destroy(const pointer &ptr) { BOOST_ASSERT(ptr != 0); (*ptr).~value_type(); } - }; //!Equality test for same type //!of allocator template inline -bool operator==(const allocator &alloc1, +bool operator==(const allocator &alloc1, const allocator &alloc2) { return alloc1.get_segment_manager() == alloc2.get_segment_manager(); } //!Inequality test for same type //!of allocator template inline -bool operator!=(const allocator &alloc1, +bool operator!=(const allocator &alloc1, const allocator &alloc2) { return alloc1.get_segment_manager() != alloc2.get_segment_manager(); } @@ -294,7 +293,7 @@ template struct has_trivial_destructor > { - static const bool value = true; + enum { value = true }; }; /// @endcond diff --git a/utils/boost_idb/boost/interprocess/allocators/cached_adaptive_pool.hpp b/utils/boost_idb/boost/interprocess/allocators/cached_adaptive_pool.hpp index 2a2d7b8a..0f650bf5 100644 --- a/utils/boost_idb/boost/interprocess/allocators/cached_adaptive_pool.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/cached_adaptive_pool.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -28,14 +28,14 @@ #include //!\file -//!Describes cached_adaptive_pool pooled shared memory STL compatible allocator +//!Describes cached_adaptive_pool pooled shared memory STL compatible allocator namespace boost { namespace interprocess { /// @cond -namespace ipcdetail { +namespace detail { template < class T , class SegmentManager @@ -44,9 +44,9 @@ template < class T , unsigned char OverheadPercent = 5 > class cached_adaptive_pool_v1 - : public ipcdetail::cached_allocator_impl + : public detail::cached_allocator_impl < T - , ipcdetail::shared_adaptive_node_pool + , detail::shared_adaptive_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -56,9 +56,9 @@ class cached_adaptive_pool_v1 , 1> { public: - typedef ipcdetail::cached_allocator_impl + typedef detail::cached_allocator_impl < T - , ipcdetail::shared_adaptive_node_pool + , detail::shared_adaptive_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -69,15 +69,13 @@ class cached_adaptive_pool_v1 template struct rebind - { + { typedef cached_adaptive_pool_v1 other; }; - typedef typename base_t::size_type size_type; - cached_adaptive_pool_v1(SegmentManager *segment_mngr, - size_type max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) + std::size_t max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) : base_t(segment_mngr, max_cached_nodes) {} @@ -89,16 +87,16 @@ class cached_adaptive_pool_v1 {} }; -} //namespace ipcdetail{ +} //namespace detail{ /// @endcond -//!An STL node allocator that uses a segment manager as memory +//!An STL node allocator that uses a segment manager as memory //!source. The internal pointer type will of the same type (raw, smart) as //!"typename SegmentManager::void_pointer" type. This allows //!placing the allocator in shared memory, memory mapped-files, etc... //! -//!This node allocator shares a segregated storage between all instances of +//!This node allocator shares a segregated storage between all instances of //!cached_adaptive_pool with equal sizeof(T) placed in the same //!memory segment. But also caches some nodes privately to //!avoid some synchronization overhead. @@ -118,9 +116,9 @@ template < class T > class cached_adaptive_pool /// @cond - : public ipcdetail::cached_allocator_impl + : public detail::cached_allocator_impl < T - , ipcdetail::shared_adaptive_node_pool + , detail::shared_adaptive_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -133,9 +131,9 @@ class cached_adaptive_pool #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED public: - typedef ipcdetail::cached_allocator_impl + typedef detail::cached_allocator_impl < T - , ipcdetail::shared_adaptive_node_pool + , detail::shared_adaptive_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -149,13 +147,13 @@ class cached_adaptive_pool template struct rebind - { + { typedef cached_adaptive_pool other; }; cached_adaptive_pool(SegmentManager *segment_mngr, - std::size_t max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) + std::size_t max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) : base_t(segment_mngr, max_cached_nodes) {} @@ -172,18 +170,18 @@ class cached_adaptive_pool typedef implementation_defined::pointer pointer; typedef implementation_defined::const_pointer const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; - //!Obtains cached_adaptive_pool from + //!Obtains cached_adaptive_pool from //!cached_adaptive_pool template struct rebind - { + { typedef cached_adaptive_pool other; }; @@ -194,7 +192,7 @@ class cached_adaptive_pool cached_adaptive_pool& operator= (const cached_adaptive_pool&); - //!Not assignable from + //!Not assignable from //!other cached_adaptive_pool cached_adaptive_pool& operator=(const cached_adaptive_pool&); @@ -204,7 +202,7 @@ class cached_adaptive_pool //!Can throw boost::interprocess::bad_alloc cached_adaptive_pool(segment_manager *segment_mngr); - //!Copy constructor from other cached_adaptive_pool. Increments the reference + //!Copy constructor from other cached_adaptive_pool. Increments the reference //!count of the associated node pool. Never throws cached_adaptive_pool(const cached_adaptive_pool &other); @@ -231,7 +229,7 @@ class cached_adaptive_pool //!Never throws size_type max_size() const; - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0); @@ -255,7 +253,7 @@ class cached_adaptive_pool //!Never throws const_pointer address(const_reference value) const; - //!Copy construct an object. + //!Copy construct an object. //!Throws if T's copy constructor throws void construct(const pointer &ptr, const_reference v); @@ -270,7 +268,7 @@ class cached_adaptive_pool std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0); @@ -280,12 +278,12 @@ class cached_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements); //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements); //!Allocates many elements of size elem_size in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -293,7 +291,7 @@ class cached_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -306,7 +304,7 @@ class cached_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - multiallocation_chain allocate_individual(size_type num_elements); + multiallocation_chain allocate_individual(std::size_t num_elements); //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -319,14 +317,14 @@ class cached_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain); + void deallocate_individual(multiallocation_chain chain); //!Sets the new max cached nodes value. This can provoke deallocations //!if "newmax" is less than current cached nodes. Never throws - void set_max_cached_nodes(size_type newmax); + void set_max_cached_nodes(std::size_t newmax); //!Returns the max cached nodes parameter. //!Never throws - size_type get_max_cached_nodes() const; + std::size_t get_max_cached_nodes() const; #endif }; @@ -335,13 +333,13 @@ class cached_adaptive_pool //!Equality test for same type //!of cached_adaptive_pool template inline -bool operator==(const cached_adaptive_pool &alloc1, +bool operator==(const cached_adaptive_pool &alloc1, const cached_adaptive_pool &alloc2); //!Inequality test for same type //!of cached_adaptive_pool template inline -bool operator!=(const cached_adaptive_pool &alloc1, +bool operator!=(const cached_adaptive_pool &alloc1, const cached_adaptive_pool &alloc2); #endif diff --git a/utils/boost_idb/boost/interprocess/allocators/cached_node_allocator.hpp b/utils/boost_idb/boost/interprocess/allocators/cached_node_allocator.hpp index ed1bee2f..0dda9e21 100644 --- a/utils/boost_idb/boost/interprocess/allocators/cached_node_allocator.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/cached_node_allocator.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -28,7 +28,7 @@ #include //!\file -//!Describes cached_cached_node_allocator pooled shared memory STL compatible allocator +//!Describes cached_cached_node_allocator pooled shared memory STL compatible allocator namespace boost { namespace interprocess { @@ -36,16 +36,16 @@ namespace interprocess { /// @cond -namespace ipcdetail { +namespace detail { template < class T , class SegmentManager , std::size_t NodesPerBlock = 64 > class cached_node_allocator_v1 - : public ipcdetail::cached_allocator_impl + : public detail::cached_allocator_impl < T - , ipcdetail::shared_node_pool + , detail::shared_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -53,9 +53,9 @@ class cached_node_allocator_v1 , 1> { public: - typedef ipcdetail::cached_allocator_impl + typedef detail::cached_allocator_impl < T - , ipcdetail::shared_node_pool + , detail::shared_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -64,15 +64,13 @@ class cached_node_allocator_v1 template struct rebind - { + { typedef cached_node_allocator_v1 other; }; - typedef typename base_t::size_type size_type; - cached_node_allocator_v1(SegmentManager *segment_mngr, - size_type max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) + std::size_t max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) : base_t(segment_mngr, max_cached_nodes) {} @@ -84,7 +82,7 @@ class cached_node_allocator_v1 {} }; -} //namespace ipcdetail{ +} //namespace detail{ /// @endcond @@ -94,9 +92,9 @@ template < class T > class cached_node_allocator /// @cond - : public ipcdetail::cached_allocator_impl + : public detail::cached_allocator_impl < T - , ipcdetail::shared_node_pool + , detail::shared_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -107,9 +105,9 @@ class cached_node_allocator #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED public: - typedef ipcdetail::cached_allocator_impl + typedef detail::cached_allocator_impl < T - , ipcdetail::shared_node_pool + , detail::shared_node_pool < SegmentManager , sizeof_value::value , NodesPerBlock @@ -118,16 +116,15 @@ class cached_node_allocator public: typedef boost::interprocess::version_type version; - typedef typename base_t::size_type size_type; template struct rebind - { + { typedef cached_node_allocator other; }; cached_node_allocator(SegmentManager *segment_mngr, - size_type max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) + std::size_t max_cached_nodes = base_t::DEFAULT_MAX_CACHED_NODES) : base_t(segment_mngr, max_cached_nodes) {} @@ -144,18 +141,18 @@ class cached_node_allocator typedef implementation_defined::pointer pointer; typedef implementation_defined::const_pointer const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename SegmentManager::size_type size_type; - typedef typename SegmentManager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; - //!Obtains cached_node_allocator from + //!Obtains cached_node_allocator from //!cached_node_allocator template struct rebind - { + { typedef cached_node_allocator other; }; @@ -166,7 +163,7 @@ class cached_node_allocator cached_node_allocator& operator= (const cached_node_allocator&); - //!Not assignable from + //!Not assignable from //!other cached_node_allocator cached_node_allocator& operator=(const cached_node_allocator&); @@ -176,7 +173,7 @@ class cached_node_allocator //!Can throw boost::interprocess::bad_alloc cached_node_allocator(segment_manager *segment_mngr); - //!Copy constructor from other cached_node_allocator. Increments the reference + //!Copy constructor from other cached_node_allocator. Increments the reference //!count of the associated node pool. Never throws cached_node_allocator(const cached_node_allocator &other); @@ -203,7 +200,7 @@ class cached_node_allocator //!Never throws size_type max_size() const; - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0); @@ -227,7 +224,7 @@ class cached_node_allocator //!Never throws const_pointer address(const_reference value) const; - //!Default construct an object. + //!Default construct an object. //!Throws if T's default constructor throws void construct(const pointer &ptr, const_reference v); @@ -242,7 +239,7 @@ class cached_node_allocator std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0); @@ -252,12 +249,12 @@ class cached_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements); //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements); //!Allocates many elements of size elem_size in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -265,7 +262,7 @@ class cached_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -278,7 +275,7 @@ class cached_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - multiallocation_chain allocate_individual(size_type num_elements); + multiallocation_chain allocate_individual(std::size_t num_elements); //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -294,11 +291,11 @@ class cached_node_allocator void deallocate_individual(multiallocation_chain it); //!Sets the new max cached nodes value. This can provoke deallocations //!if "newmax" is less than current cached nodes. Never throws - void set_max_cached_nodes(size_type newmax); + void set_max_cached_nodes(std::size_t newmax); //!Returns the max cached nodes parameter. //!Never throws - size_type get_max_cached_nodes() const; + std::size_t get_max_cached_nodes() const; #endif }; @@ -307,13 +304,13 @@ class cached_node_allocator //!Equality test for same type //!of cached_node_allocator template inline -bool operator==(const cached_node_allocator &alloc1, +bool operator==(const cached_node_allocator &alloc1, const cached_node_allocator &alloc2); //!Inequality test for same type //!of cached_node_allocator template inline -bool operator!=(const cached_node_allocator &alloc1, +bool operator!=(const cached_node_allocator &alloc1, const cached_node_allocator &alloc2); #endif diff --git a/utils/boost_idb/boost/interprocess/allocators/detail/adaptive_node_pool.hpp b/utils/boost_idb/boost/interprocess/allocators/detail/adaptive_node_pool.hpp index a3afa8ee..99cee8ae 100644 --- a/utils/boost_idb/boost/interprocess/allocators/detail/adaptive_node_pool.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/detail/adaptive_node_pool.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -27,7 +28,7 @@ #include #include #include -#include +#include #include //!\file @@ -35,7 +36,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { template< class SegmentManager , std::size_t NodeSize @@ -44,30 +45,23 @@ template< class SegmentManager , unsigned char OverheadPercent > class private_adaptive_node_pool - : public boost::container::container_detail::private_adaptive_node_pool_impl - < typename SegmentManager::segment_manager_base_type - , ::boost::container::adaptive_pool_flag::size_ordered | - ::boost::container::adaptive_pool_flag::address_ordered - > + : public boost::container::containers_detail::private_adaptive_node_pool_impl + { - typedef boost::container::container_detail::private_adaptive_node_pool_impl - < typename SegmentManager::segment_manager_base_type - , ::boost::container::adaptive_pool_flag::size_ordered | - ::boost::container::adaptive_pool_flag::address_ordered - > base_t; + typedef boost::container::containers_detail::private_adaptive_node_pool_impl + base_t; //Non-copyable private_adaptive_node_pool(); private_adaptive_node_pool(const private_adaptive_node_pool &); private_adaptive_node_pool &operator=(const private_adaptive_node_pool &); public: - typedef SegmentManager segment_manager; - typedef typename base_t::size_type size_type; + typedef SegmentManager segment_manager; - static const size_type nodes_per_block = NodesPerBlock; + static const std::size_t nodes_per_block = NodesPerBlock; //Deprecated, use node_per_block - static const size_type nodes_per_chunk = NodesPerBlock; + static const std::size_t nodes_per_chunk = NodesPerBlock; //!Constructor from a segment manager. Never throws private_adaptive_node_pool(segment_manager *segment_mngr) @@ -80,7 +74,7 @@ class private_adaptive_node_pool }; //!Pooled shared memory allocator using adaptive pool. Includes -//!a reference count but the class does not delete itself, this is +//!a reference count but the class does not delete itself, this is //!responsibility of user classes. Node size (NodeSize) and the number of //!nodes allocated per block (NodesPerBlock) are known at compile time template< class SegmentManager @@ -89,13 +83,13 @@ template< class SegmentManager , std::size_t MaxFreeBlocks , unsigned char OverheadPercent > -class shared_adaptive_node_pool - : public ipcdetail::shared_pool_impl +class shared_adaptive_node_pool + : public detail::shared_pool_impl < private_adaptive_node_pool > { - typedef ipcdetail::shared_pool_impl + typedef detail::shared_pool_impl < private_adaptive_node_pool > base_t; @@ -105,7 +99,7 @@ class shared_adaptive_node_pool {} }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/allocators/detail/allocator_common.hpp b/utils/boost_idb/boost/interprocess/allocators/detail/allocator_common.hpp index f2b54a8a..6dbe33d4 100644 --- a/utils/boost_idb/boost/interprocess/allocators/detail/allocator_common.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/detail/allocator_common.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -14,24 +14,25 @@ #include #include -#include +#include #include -#include //to_raw_pointer +#include //get_pointer +#include //std::pair #include //boost::addressof #include //BOOST_ASSERT +#include #include //bad_alloc #include //scoped_lock #include //boost::interprocess::allocation_type -#include +#include #include #include -#include +#include //std::swap +#include + #include #include -#include //std::swap -#include //std::pair -#include namespace boost { namespace interprocess { @@ -66,14 +67,14 @@ struct sizeof_value static const std::size_t value = sizeof(void*); }; -namespace ipcdetail { +namespace detail { //!Object function that creates the node allocator if it is not created and //!increments reference count if it is already created template struct get_or_create_node_pool_func { - + //!This connects or constructs the unique instance of node_pool_t //!Can throw boost::interprocess::bad_alloc void operator()() @@ -90,7 +91,7 @@ struct get_or_create_node_pool_func //!object parameters get_or_create_node_pool_func(typename NodePool::segment_manager *mngr) : mp_segment_manager(mngr){} - + NodePool *mp_node_pool; typename NodePool::segment_manager *mp_segment_manager; }; @@ -98,18 +99,18 @@ struct get_or_create_node_pool_func template inline NodePool *get_or_create_node_pool(typename NodePool::segment_manager *mgnr) { - ipcdetail::get_or_create_node_pool_func func(mgnr); + detail::get_or_create_node_pool_func func(mgnr); mgnr->atomic_func(func); return func.mp_node_pool; } -//!Object function that decrements the reference count. If the count -//!reaches to zero destroys the node allocator from memory. +//!Object function that decrements the reference count. If the count +//!reaches to zero destroys the node allocator from memory. //!Never throws template struct destroy_if_last_link_func { - //!Decrements reference count and destroys the object if there is no + //!Decrements reference count and destroys the object if there is no //!more attached allocators. Never throws void operator()() { @@ -117,19 +118,19 @@ struct destroy_if_last_link_func if(mp_node_pool->dec_ref_count() != 0) return; //Last link, let's destroy the segment_manager - mp_node_pool->get_segment_manager()->template destroy(boost::interprocess::unique_instance); - } + mp_node_pool->get_segment_manager()->template destroy(boost::interprocess::unique_instance); + } //!Constructor. Initializes function //!object parameters - destroy_if_last_link_func(NodePool *pool) + destroy_if_last_link_func(NodePool *pool) : mp_node_pool(pool) {} NodePool *mp_node_pool; }; -//!Destruction function, initializes and executes destruction function +//!Destruction function, initializes and executes destruction function //!object. Never throws template inline void destroy_node_pool_if_last_link(NodePool *pool) @@ -146,19 +147,17 @@ class cache_impl { typedef typename NodePool::segment_manager:: void_pointer void_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type node_pool_ptr; - typedef typename NodePool::multiallocation_chain multiallocation_chain; - typedef typename NodePool::segment_manager::size_type size_type; + typedef typename pointer_to_other + ::type node_pool_ptr; + typedef typename NodePool::multiallocation_chain multiallocation_chain; node_pool_ptr mp_node_pool; multiallocation_chain m_cached_nodes; - size_type m_max_cached_nodes; + std::size_t m_max_cached_nodes; public: typedef typename NodePool::segment_manager segment_manager; - cache_impl(segment_manager *segment_mngr, size_type max_cached_nodes) + cache_impl(segment_manager *segment_mngr, std::size_t max_cached_nodes) : mp_node_pool(get_or_create_node_pool(segment_mngr)) , m_max_cached_nodes(max_cached_nodes) {} @@ -173,45 +172,50 @@ class cache_impl ~cache_impl() { this->deallocate_all_cached_nodes(); - ipcdetail::destroy_node_pool_if_last_link(ipcdetail::to_raw_pointer(mp_node_pool)); + detail::destroy_node_pool_if_last_link(detail::get_pointer(mp_node_pool)); } NodePool *get_node_pool() const - { return ipcdetail::to_raw_pointer(mp_node_pool); } + { return detail::get_pointer(mp_node_pool); } segment_manager *get_segment_manager() const { return mp_node_pool->get_segment_manager(); } - size_type get_max_cached_nodes() const + std::size_t get_max_cached_nodes() const { return m_max_cached_nodes; } void *cached_allocation() { //If don't have any cached node, we have to get a new list of free nodes from the pool if(m_cached_nodes.empty()){ - mp_node_pool->allocate_nodes(m_max_cached_nodes/2, m_cached_nodes); + m_cached_nodes = mp_node_pool->allocate_nodes(m_max_cached_nodes/2); } - void *ret = ipcdetail::to_raw_pointer(m_cached_nodes.pop_front()); + void *ret = detail::get_pointer(m_cached_nodes.front()); + m_cached_nodes.pop_front(); return ret; } - void cached_allocation(size_type n, multiallocation_chain &chain) + multiallocation_chain cached_allocation(std::size_t n) { - size_type count = n, allocated(0); + multiallocation_chain chain; + std::size_t count = n, allocated(0); BOOST_TRY{ //If don't have any cached node, we have to get a new list of free nodes from the pool while(!m_cached_nodes.empty() && count--){ - void *ret = ipcdetail::to_raw_pointer(m_cached_nodes.pop_front()); + void *ret = detail::get_pointer(m_cached_nodes.front()); + m_cached_nodes.pop_front(); chain.push_back(ret); ++allocated; } if(allocated != n){ - mp_node_pool->allocate_nodes(n - allocated, chain); + multiallocation_chain chain2(mp_node_pool->allocate_nodes(n - allocated)); + chain.splice_after(chain.last(), chain2, chain2.before_begin(), chain2.last(), n - allocated); } + return boost::interprocess::move(chain); } BOOST_CATCH(...){ - this->cached_deallocation(chain); + this->cached_deallocation(boost::interprocess::move(chain)); BOOST_RETHROW } BOOST_CATCH_END @@ -222,7 +226,7 @@ class cache_impl //Check if cache is full if(m_cached_nodes.size() >= m_max_cached_nodes){ //This only occurs if this allocator deallocate memory allocated - //with other equal allocator. Since the cache is full, and more + //with other equal allocator. Since the cache is full, and more //deallocations are probably coming, we'll make some room in cache //in a single, efficient multi node deallocation. this->priv_deallocate_n_nodes(m_cached_nodes.size() - m_max_cached_nodes/2); @@ -230,14 +234,14 @@ class cache_impl m_cached_nodes.push_front(ptr); } - void cached_deallocation(multiallocation_chain &chain) + void cached_deallocation(multiallocation_chain chain) { m_cached_nodes.splice_after(m_cached_nodes.before_begin(), chain); //Check if cache is full if(m_cached_nodes.size() >= m_max_cached_nodes){ //This only occurs if this allocator deallocate memory allocated - //with other equal allocator. Since the cache is full, and more + //with other equal allocator. Since the cache is full, and more //deallocations are probably coming, we'll make some room in cache //in a single, efficient multi node deallocation. this->priv_deallocate_n_nodes(m_cached_nodes.size() - m_max_cached_nodes/2); @@ -246,7 +250,7 @@ class cache_impl //!Sets the new max cached nodes value. This can provoke deallocations //!if "newmax" is less than current cached nodes. Never throws - void set_max_cached_nodes(size_type newmax) + void set_max_cached_nodes(std::size_t newmax) { m_max_cached_nodes = newmax; this->priv_deallocate_remaining_nodes(); @@ -257,7 +261,7 @@ class cache_impl void deallocate_all_cached_nodes() { if(m_cached_nodes.empty()) return; - mp_node_pool->deallocate_nodes(m_cached_nodes); + mp_node_pool->deallocate_nodes(boost::interprocess::move(m_cached_nodes)); } private: @@ -271,13 +275,13 @@ class cache_impl } //!Frees n cached nodes at once. Never throws - void priv_deallocate_n_nodes(size_type n) + void priv_deallocate_n_nodes(std::size_t n) { //This only occurs if this allocator deallocate memory allocated - //with other equal allocator. Since the cache is full, and more + //with other equal allocator. Since the cache is full, and more //deallocations are probably coming, we'll make some room in cache //in a single, efficient multi node deallocation. - size_type count(n); + std::size_t count(n); typename multiallocation_chain::iterator it(m_cached_nodes.before_begin()); while(count--){ ++it; @@ -285,16 +289,16 @@ class cache_impl multiallocation_chain chain; chain.splice_after(chain.before_begin(), m_cached_nodes, m_cached_nodes.before_begin(), it, n); //Deallocate all new linked list at once - mp_node_pool->deallocate_nodes(chain); + mp_node_pool->deallocate_nodes(boost::interprocess::move(chain)); } public: void swap(cache_impl &other) { - ipcdetail::do_swap(mp_node_pool, other.mp_node_pool); - m_cached_nodes.swap(other.m_cached_nodes); - ipcdetail::do_swap(m_max_cached_nodes, other.m_max_cached_nodes); - } + detail::do_swap(mp_node_pool, other.mp_node_pool); + m_cached_nodes.swap(other.m_cached_nodes); + detail::do_swap(m_max_cached_nodes, other.m_max_cached_nodes); + } }; template @@ -308,20 +312,18 @@ class array_allocation_impl typedef typename SegmentManager::void_pointer void_pointer; public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; + typedef typename boost:: + pointer_to_other::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename SegmentManager::size_type size_type; - typedef typename SegmentManager::difference_type difference_type; - typedef boost::container::container_detail::transform_multiallocation_chain + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; @@ -330,18 +332,18 @@ class array_allocation_impl //!pointed by p can hold. This size only works for memory allocated with //!allocate, allocation_command and allocate_many. size_type size(const pointer &p) const - { - return (size_type)this->derived()->get_segment_manager()->size(ipcdetail::to_raw_pointer(p))/sizeof(T); + { + return (size_type)this->derived()->get_segment_manager()->size(detail::get_pointer(p))/sizeof(T); } std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0) { return this->derived()->get_segment_manager()->allocation_command - (command, limit_size, preferred_size, received_size, ipcdetail::to_raw_pointer(reuse)); + (command, limit_size, preferred_size, received_size, detail::get_pointer(reuse)); } //!Allocates many elements of size elem_size in a contiguous block @@ -350,20 +352,17 @@ class array_allocation_impl //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain) + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements) { - if(size_overflows(elem_size)){ - throw bad_alloc(); - } - this->derived()->get_segment_manager()->allocate_many(elem_size*sizeof(T), num_elements, chain); + return this->derived()->get_segment_manager()->allocate_many(sizeof(T)*elem_size, num_elements); } //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain) + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements) { - this->derived()->get_segment_manager()->allocate_many(elem_sizes, n_elements, sizeof(T), chain); + return this->derived()->get_segment_manager()->allocate_many(elem_sizes, n_elements, sizeof(T)); } //!Allocates many elements of size elem_size in a contiguous block @@ -372,8 +371,8 @@ class array_allocation_impl //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain) - { this->derived()->get_segment_manager()->deallocate_many(chain); } + void deallocate_many(multiallocation_chain chain) + { return this->derived()->get_segment_manager()->deallocate_many(boost::interprocess::move(chain)); } //!Returns the number of elements that could be //!allocated. Never throws @@ -390,12 +389,15 @@ class array_allocation_impl const_pointer address(const_reference value) const { return const_pointer(boost::addressof(value)); } - //!Constructs an object - //!Throws if T's constructor throws - //!For backwards compatibility with libraries using C++03 allocators - template - void construct(const pointer &ptr, BOOST_FWD_REF(P) p) - { ::new((void*)ipcdetail::to_raw_pointer(ptr)) value_type(::boost::forward

(p)); } + //!Default construct an object. + //!Throws if T's default constructor throws + void construct(const pointer &ptr) + { new((void*)detail::get_pointer(ptr)) value_type; } + + //!Copy construct an object + //!Throws if T's copy constructor throws + void construct(const pointer &ptr, const_reference v) + { new((void*)detail::get_pointer(ptr)) value_type(v); } //!Destroys object. Throws if object's //!destructor throws @@ -417,25 +419,22 @@ class node_pool_allocation_impl { return static_cast(this); } typedef typename SegmentManager::void_pointer void_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type cvoid_pointer; + typedef typename boost:: + pointer_to_other::type cvoid_pointer; public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; + typedef typename boost:: + pointer_to_other::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename SegmentManager::size_type size_type; - typedef typename SegmentManager::difference_type difference_type; - typedef boost::container::container_detail::transform_multiallocation_chain + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; @@ -448,24 +447,21 @@ class node_pool_allocation_impl }; public: - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0) { (void)hint; typedef typename node_pool<0>::type node_pool_t; node_pool_t *pool = node_pool<0>::get(this->derived()->get_node_pool()); - if(size_overflows(count)){ + if(count > this->max_size()) throw bad_alloc(); - } - else if(Version == 1 && count == 1){ + else if(Version == 1 && count == 1) return pointer(static_cast (pool->allocate_node())); - } - else{ + else return pointer(static_cast - (pool->get_segment_manager()->allocate(count*sizeof(T)))); - } + (pool->get_segment_manager()->allocate(sizeof(T)*count))); } //!Deallocate allocated memory. Never throws @@ -475,9 +471,9 @@ class node_pool_allocation_impl typedef typename node_pool<0>::type node_pool_t; node_pool_t *pool = node_pool<0>::get(this->derived()->get_node_pool()); if(Version == 1 && count == 1) - pool->deallocate_node(ipcdetail::to_raw_pointer(ptr)); + pool->deallocate_node(detail::get_pointer(ptr)); else - pool->get_segment_manager()->deallocate((void*)ipcdetail::to_raw_pointer(ptr)); + pool->get_segment_manager()->deallocate((void*)detail::get_pointer(ptr)); } //!Allocates just one object. Memory allocated with this function @@ -496,11 +492,11 @@ class node_pool_allocation_impl //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain) + multiallocation_chain allocate_individual(std::size_t num_elements) { typedef typename node_pool<0>::type node_pool_t; node_pool_t *pool = node_pool<0>::get(this->derived()->get_node_pool()); - pool->allocate_nodes(num_elements, chain); + return multiallocation_chain(pool->allocate_nodes(num_elements)); } //!Deallocates memory previously allocated with allocate_one(). @@ -510,7 +506,7 @@ class node_pool_allocation_impl { typedef typename node_pool<0>::type node_pool_t; node_pool_t *pool = node_pool<0>::get(this->derived()->get_node_pool()); - pool->deallocate_node(ipcdetail::to_raw_pointer(p)); + pool->deallocate_node(detail::get_pointer(p)); } //!Allocates many elements of size == 1 in a contiguous block @@ -519,10 +515,10 @@ class node_pool_allocation_impl //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain) + void deallocate_individual(multiallocation_chain chain) { node_pool<0>::get(this->derived()->get_node_pool())->deallocate_nodes - (chain); + (chain.extract_multiallocation_chain()); } //!Deallocates all free blocks of the pool @@ -551,18 +547,17 @@ class cached_allocator_impl typedef NodePool node_pool_t; typedef typename NodePool::segment_manager segment_manager; typedef typename segment_manager::void_pointer void_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type cvoid_pointer; + typedef typename boost:: + pointer_to_other::type cvoid_pointer; typedef typename base_t::pointer pointer; typedef typename base_t::size_type size_type; typedef typename base_t::multiallocation_chain multiallocation_chain; typedef typename base_t::value_type value_type; public: - static const std::size_t DEFAULT_MAX_CACHED_NODES = 64; + enum { DEFAULT_MAX_CACHED_NODES = 64 }; - cached_allocator_impl(segment_manager *segment_mngr, size_type max_cached_nodes) + cached_allocator_impl(segment_manager *segment_mngr, std::size_t max_cached_nodes) : m_cache(segment_mngr, max_cached_nodes) {} @@ -592,29 +587,28 @@ class cached_allocator_impl //!Sets the new max cached nodes value. This can provoke deallocations //!if "newmax" is less than current cached nodes. Never throws - void set_max_cached_nodes(size_type newmax) + void set_max_cached_nodes(std::size_t newmax) { m_cache.set_max_cached_nodes(newmax); } //!Returns the max cached nodes parameter. //!Never throws - size_type get_max_cached_nodes() const + std::size_t get_max_cached_nodes() const { return m_cache.get_max_cached_nodes(); } - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0) { (void)hint; void * ret; - if(size_overflows(count)){ + if(count > this->max_size()) throw bad_alloc(); - } else if(Version == 1 && count == 1){ ret = m_cache.cached_allocation(); } else{ - ret = this->get_segment_manager()->allocate(count*sizeof(T)); - } + ret = this->get_segment_manager()->allocate(sizeof(T)*count); + } return pointer(static_cast(ret)); } @@ -623,10 +617,10 @@ class cached_allocator_impl { (void)count; if(Version == 1 && count == 1){ - m_cache.cached_deallocation(ipcdetail::to_raw_pointer(ptr)); + m_cache.cached_deallocation(detail::get_pointer(ptr)); } else{ - this->get_segment_manager()->deallocate((void*)ipcdetail::to_raw_pointer(ptr)); + this->get_segment_manager()->deallocate((void*)detail::get_pointer(ptr)); } } @@ -642,14 +636,14 @@ class cached_allocator_impl //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain) - { this->m_cache.cached_allocation(num_elements, chain); } + multiallocation_chain allocate_individual(std::size_t num_elements) + { return multiallocation_chain(this->m_cache.cached_allocation(num_elements)); } //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated //!with other functions different from allocate_one(). Never throws void deallocate_one(const pointer &p) - { this->m_cache.cached_deallocation(ipcdetail::to_raw_pointer(p)); } + { this->m_cache.cached_deallocation(detail::get_pointer(p)); } //!Allocates many elements of size == 1 in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -657,8 +651,12 @@ class cached_allocator_impl //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain) - { m_cache.cached_deallocation(chain); } + void deallocate_individual(multiallocation_chain chain) + { + typename node_pool_t::multiallocation_chain mem + (chain.extract_multiallocation_chain()); + m_cache.cached_deallocation(boost::interprocess::move(mem)); + } //!Deallocates all free blocks of the pool void deallocate_free_blocks() @@ -684,20 +682,20 @@ class cached_allocator_impl //!Equality test for same type of //!cached_allocator_impl template inline -bool operator==(const cached_allocator_impl &alloc1, +bool operator==(const cached_allocator_impl &alloc1, const cached_allocator_impl &alloc2) { return alloc1.get_node_pool() == alloc2.get_node_pool(); } //!Inequality test for same type of //!cached_allocator_impl template inline -bool operator!=(const cached_allocator_impl &alloc1, +bool operator!=(const cached_allocator_impl &alloc1, const cached_allocator_impl &alloc2) { return alloc1.get_node_pool() != alloc2.get_node_pool(); } //!Pooled shared memory allocator using adaptive pool. Includes -//!a reference count but the class does not delete itself, this is +//!a reference count but the class does not delete itself, this is //!responsibility of user classes. Node size (NodeSize) and the number of //!nodes allocated per block (NodesPerBlock) are known at compile time template @@ -710,8 +708,6 @@ class shared_pool_impl segment_manager segment_manager; typedef typename private_node_allocator_t:: multiallocation_chain multiallocation_chain; - typedef typename private_node_allocator_t:: - size_type size_type; private: typedef typename segment_manager::mutex_family::mutex_type mutex_type; @@ -734,7 +730,7 @@ class shared_pool_impl //----------------------- return private_node_allocator_t::allocate_node(); } - + //!Deallocates an array pointed by ptr. Never throws void deallocate_node(void *ptr) { @@ -743,19 +739,29 @@ class shared_pool_impl //----------------------- private_node_allocator_t::deallocate_node(ptr); } - - //!Allocates n nodes. +/* + //!Allocates a singly linked list of n nodes ending in null pointer. + //!can throw boost::interprocess::bad_alloc + void allocate_nodes(multiallocation_chain &nodes, std::size_t n) + { + //----------------------- + boost::interprocess::scoped_lock guard(m_header); + //----------------------- + return private_node_allocator_t::allocate_nodes(nodes, n); + } +*/ + //!Allocates n nodes. //!Can throw boost::interprocess::bad_alloc - void allocate_nodes(const size_type n, multiallocation_chain &chain) + multiallocation_chain allocate_nodes(const std::size_t n) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - private_node_allocator_t::allocate_nodes(n, chain); + return private_node_allocator_t::allocate_nodes(n); } //!Deallocates a linked list of nodes ending in null pointer. Never throws - void deallocate_nodes(multiallocation_chain &nodes, size_type num) + void deallocate_nodes(multiallocation_chain &nodes, std::size_t num) { //----------------------- boost::interprocess::scoped_lock guard(m_header); @@ -764,12 +770,12 @@ class shared_pool_impl } //!Deallocates the nodes pointed by the multiallocation iterator. Never throws - void deallocate_nodes(multiallocation_chain &chain) + void deallocate_nodes(multiallocation_chain chain) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - private_node_allocator_t::deallocate_nodes(chain); + private_node_allocator_t::deallocate_nodes(boost::interprocess::move(chain)); } //!Deallocates all the free blocks of memory. Never throws @@ -793,7 +799,7 @@ class shared_pool_impl } //!Increments internal reference count and returns new count. Never throws - size_type inc_ref_count() + std::size_t inc_ref_count() { //----------------------- boost::interprocess::scoped_lock guard(m_header); @@ -802,7 +808,7 @@ class shared_pool_impl } //!Decrements internal reference count and returns new count. Never throws - size_type dec_ref_count() + std::size_t dec_ref_count() { //----------------------- boost::interprocess::scoped_lock guard(m_header); @@ -834,14 +840,14 @@ class shared_pool_impl //!the mutex type to allow EBO when using null_mutex struct header_t : mutex_type { - size_type m_usecount; //Number of attached allocators + std::size_t m_usecount; //Number of attached allocators header_t() : m_usecount(0) {} } m_header; }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/allocators/detail/node_pool.hpp b/utils/boost_idb/boost/interprocess/allocators/detail/node_pool.hpp index e67d3217..c7a3cd95 100644 --- a/utils/boost_idb/boost/interprocess/allocators/detail/node_pool.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/detail/node_pool.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -20,10 +20,11 @@ #include #include +#include #include #include -#include +#include #include @@ -32,21 +33,21 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { //!Pooled shared memory allocator using single segregated storage. Includes -//!a reference count but the class does not delete itself, this is +//!a reference count but the class does not delete itself, this is //!responsibility of user classes. Node size (NodeSize) and the number of //!nodes allocated per block (NodesPerBlock) are known at compile time template< class SegmentManager, std::size_t NodeSize, std::size_t NodesPerBlock > class private_node_pool //Inherit from the implementation to avoid template bloat - : public boost::container::container_detail:: + : public boost::container::containers_detail:: private_node_pool_impl { - typedef boost::container::container_detail::private_node_pool_impl + typedef boost::container::containers_detail::private_node_pool_impl base_t; //Non-copyable private_node_pool(); @@ -54,12 +55,11 @@ class private_node_pool private_node_pool &operator=(const private_node_pool &); public: - typedef SegmentManager segment_manager; - typedef typename base_t::size_type size_type; + typedef SegmentManager segment_manager; - static const size_type nodes_per_block = NodesPerBlock; + static const std::size_t nodes_per_block = NodesPerBlock; //Deprecated, use nodes_per_block - static const size_type nodes_per_chunk = NodesPerBlock; + static const std::size_t nodes_per_chunk = NodesPerBlock; //!Constructor from a segment manager. Never throws private_node_pool(segment_manager *segment_mngr) @@ -73,24 +73,24 @@ class private_node_pool //!Pooled shared memory allocator using single segregated storage. Includes -//!a reference count but the class does not delete itself, this is +//!a reference count but the class does not delete itself, this is //!responsibility of user classes. Node size (NodeSize) and the number of //!nodes allocated per block (NodesPerBlock) are known at compile time //!Pooled shared memory allocator using adaptive pool. Includes -//!a reference count but the class does not delete itself, this is +//!a reference count but the class does not delete itself, this is //!responsibility of user classes. Node size (NodeSize) and the number of //!nodes allocated per block (NodesPerBlock) are known at compile time template< class SegmentManager , std::size_t NodeSize , std::size_t NodesPerBlock > -class shared_node_pool - : public ipcdetail::shared_pool_impl +class shared_node_pool + : public detail::shared_pool_impl < private_node_pool > { - typedef ipcdetail::shared_pool_impl + typedef detail::shared_pool_impl < private_node_pool > base_t; @@ -100,7 +100,7 @@ class shared_node_pool {} }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/allocators/detail/node_tools.hpp b/utils/boost_idb/boost/interprocess/allocators/detail/node_tools.hpp index e9fec385..bd7d51ed 100644 --- a/utils/boost_idb/boost/interprocess/allocators/detail/node_tools.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/detail/node_tools.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2007-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2007-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -22,7 +22,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { template @@ -41,7 +41,7 @@ struct node_slist , bi::base_hook >::type node_slist_t; }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/allocators/node_allocator.hpp b/utils/boost_idb/boost/interprocess/allocators/node_allocator.hpp index 3b2ec290..1d80c9e2 100644 --- a/utils/boost_idb/boost/interprocess/allocators/node_allocator.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/node_allocator.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include #include #include @@ -34,14 +34,14 @@ #include //!\file -//!Describes node_allocator pooled shared memory STL compatible allocator +//!Describes node_allocator pooled shared memory STL compatible allocator namespace boost { namespace interprocess { /// @cond -namespace ipcdetail{ +namespace detail{ template < unsigned int Version , class T @@ -68,7 +68,7 @@ class node_allocator_base template struct node_pool { - typedef ipcdetail::shared_node_pool + typedef detail::shared_node_pool < SegmentManager, sizeof_value::value, NodesPerBlock> type; static type *get(void *p) @@ -80,29 +80,27 @@ class node_allocator_base public: //------- - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; + typedef typename boost:: + pointer_to_other::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; typedef boost::interprocess::version_type version; - typedef boost::container::container_detail::transform_multiallocation_chain + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; - //!Obtains node_allocator_base from + //!Obtains node_allocator_base from //!node_allocator_base template struct rebind - { + { typedef node_allocator_base other; }; @@ -121,15 +119,15 @@ class node_allocator_base //!Constructor from a segment manager. If not present, constructs a node //!pool. Increments the reference count of the associated node pool. //!Can throw boost::interprocess::bad_alloc - node_allocator_base(segment_manager *segment_mngr) - : mp_node_pool(ipcdetail::get_or_create_node_pool::type>(segment_mngr)) { } + node_allocator_base(segment_manager *segment_mngr) + : mp_node_pool(detail::get_or_create_node_pool::type>(segment_mngr)) { } - //!Copy constructor from other node_allocator_base. Increments the reference + //!Copy constructor from other node_allocator_base. Increments the reference //!count of the associated node pool. Never throws - node_allocator_base(const node_allocator_base &other) - : mp_node_pool(other.get_node_pool()) - { - node_pool<0>::get(ipcdetail::to_raw_pointer(mp_node_pool))->inc_ref_count(); + node_allocator_base(const node_allocator_base &other) + : mp_node_pool(other.get_node_pool()) + { + node_pool<0>::get(detail::get_pointer(mp_node_pool))->inc_ref_count(); } //!Copy constructor from related node_allocator_base. If not present, constructs @@ -138,7 +136,7 @@ class node_allocator_base template node_allocator_base (const node_allocator_base &other) - : mp_node_pool(ipcdetail::get_or_create_node_pool::type>(other.get_segment_manager())) { } + : mp_node_pool(detail::get_or_create_node_pool::type>(other.get_segment_manager())) { } //!Assignment from other node_allocator_base node_allocator_base& operator=(const node_allocator_base &other) @@ -150,23 +148,23 @@ class node_allocator_base //!Destructor, removes node_pool_t from memory //!if its reference count reaches to zero. Never throws - ~node_allocator_base() - { ipcdetail::destroy_node_pool_if_last_link(node_pool<0>::get(ipcdetail::to_raw_pointer(mp_node_pool))); } + ~node_allocator_base() + { detail::destroy_node_pool_if_last_link(node_pool<0>::get(detail::get_pointer(mp_node_pool))); } //!Returns a pointer to the node pool. //!Never throws void* get_node_pool() const - { return ipcdetail::to_raw_pointer(mp_node_pool); } + { return detail::get_pointer(mp_node_pool); } //!Returns the segment manager. //!Never throws segment_manager* get_segment_manager()const - { return node_pool<0>::get(ipcdetail::to_raw_pointer(mp_node_pool))->get_segment_manager(); } + { return node_pool<0>::get(detail::get_pointer(mp_node_pool))->get_segment_manager(); } //!Swaps allocators. Does not throw. If each allocator is placed in a //!different memory segment, the result is undefined. friend void swap(self_t &alloc1, self_t &alloc2) - { ipcdetail::do_swap(alloc1.mp_node_pool, alloc2.mp_node_pool); } + { detail::do_swap(alloc1.mp_node_pool, alloc2.mp_node_pool); } /// @cond private: @@ -177,14 +175,14 @@ class node_allocator_base //!Equality test for same type //!of node_allocator_base template inline -bool operator==(const node_allocator_base &alloc1, +bool operator==(const node_allocator_base &alloc1, const node_allocator_base &alloc2) { return alloc1.get_node_pool() == alloc2.get_node_pool(); } //!Inequality test for same type //!of node_allocator_base template inline -bool operator!=(const node_allocator_base &alloc1, +bool operator!=(const node_allocator_base &alloc1, const node_allocator_base &alloc2) { return alloc1.get_node_pool() != alloc2.get_node_pool(); } @@ -201,16 +199,16 @@ class node_allocator_v1 > { public: - typedef ipcdetail::node_allocator_base + typedef detail::node_allocator_base < 1, T, SegmentManager, NodesPerBlock> base_t; template struct rebind - { + { typedef node_allocator_v1 other; }; - node_allocator_v1(SegmentManager *segment_mngr) + node_allocator_v1(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -221,16 +219,16 @@ class node_allocator_v1 {} }; -} //namespace ipcdetail{ +} //namespace detail{ /// @endcond -//!An STL node allocator that uses a segment manager as memory +//!An STL node allocator that uses a segment manager as memory //!source. The internal pointer type will of the same type (raw, smart) as //!"typename SegmentManager::void_pointer" type. This allows //!placing the allocator in shared memory, memory mapped-files, etc... -//!This node allocator shares a segregated storage between all instances -//!of node_allocator with equal sizeof(T) placed in the same segment +//!This node allocator shares a segregated storage between all instances +//!of node_allocator with equal sizeof(T) placed in the same segment //!group. NodesPerBlock is the number of nodes allocated at once when the allocator //!needs runs out of nodes template < class T @@ -239,7 +237,7 @@ template < class T > class node_allocator /// @cond - : public ipcdetail::node_allocator_base + : public detail::node_allocator_base < 2 , T , SegmentManager @@ -249,18 +247,18 @@ class node_allocator { #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - typedef ipcdetail::node_allocator_base + typedef detail::node_allocator_base < 2, T, SegmentManager, NodesPerBlock> base_t; public: typedef boost::interprocess::version_type version; template struct rebind - { + { typedef node_allocator other; }; - node_allocator(SegmentManager *segment_mngr) + node_allocator(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -277,18 +275,18 @@ class node_allocator typedef implementation_defined::pointer pointer; typedef implementation_defined::const_pointer const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; - //!Obtains node_allocator from + //!Obtains node_allocator from //!node_allocator template struct rebind - { + { typedef node_allocator other; }; @@ -299,7 +297,7 @@ class node_allocator node_allocator& operator= (const node_allocator&); - //!Not assignable from + //!Not assignable from //!other node_allocator //node_allocator& operator=(const node_allocator&); @@ -309,7 +307,7 @@ class node_allocator //!Can throw boost::interprocess::bad_alloc node_allocator(segment_manager *segment_mngr); - //!Copy constructor from other node_allocator. Increments the reference + //!Copy constructor from other node_allocator. Increments the reference //!count of the associated node pool. Never throws node_allocator(const node_allocator &other); @@ -336,7 +334,7 @@ class node_allocator //!Never throws size_type max_size() const; - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0); @@ -360,7 +358,7 @@ class node_allocator //!Never throws const_pointer address(const_reference value) const; - //!Copy construct an object. + //!Copy construct an object. //!Throws if T's copy constructor throws void construct(const pointer &ptr, const_reference v); @@ -375,7 +373,7 @@ class node_allocator std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0); @@ -385,12 +383,12 @@ class node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements); //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements); //!Allocates many elements of size elem_size in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -398,7 +396,7 @@ class node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -411,7 +409,7 @@ class node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_individual(std::size_t num_elements); //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -424,7 +422,7 @@ class node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain); + void deallocate_individual(multiallocation_chain chain); #endif }; @@ -433,13 +431,13 @@ class node_allocator //!Equality test for same type //!of node_allocator template inline -bool operator==(const node_allocator &alloc1, +bool operator==(const node_allocator &alloc1, const node_allocator &alloc2); //!Inequality test for same type //!of node_allocator template inline -bool operator!=(const node_allocator &alloc1, +bool operator!=(const node_allocator &alloc1, const node_allocator &alloc2); #endif diff --git a/utils/boost_idb/boost/interprocess/allocators/private_adaptive_pool.hpp b/utils/boost_idb/boost/interprocess/allocators/private_adaptive_pool.hpp index fd7ad7c7..c1d25c5e 100644 --- a/utils/boost_idb/boost/interprocess/allocators/private_adaptive_pool.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/private_adaptive_pool.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,13 +18,13 @@ #include #include -#include +#include #include #include #include #include -#include +#include #include #include #include @@ -33,14 +33,14 @@ #include //!\file -//!Describes private_adaptive_pool_base pooled shared memory STL compatible allocator +//!Describes private_adaptive_pool_base pooled shared memory STL compatible allocator namespace boost { namespace interprocess { /// @cond -namespace ipcdetail { +namespace detail { template < unsigned int Version , class T @@ -68,7 +68,7 @@ class private_adaptive_pool_base typedef private_adaptive_pool_base < Version, T, SegmentManager, NodesPerBlock , MaxFreeBlocks, OverheadPercent> self_t; - typedef ipcdetail::private_adaptive_node_pool + typedef detail::private_adaptive_node_pool ::value , NodesPerBlock @@ -81,28 +81,26 @@ class private_adaptive_pool_base /// @endcond public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; + typedef typename boost:: + pointer_to_other::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::size_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; typedef boost::interprocess::version_type version; - typedef boost::container::container_detail::transform_multiallocation_chain + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; //!Obtains node_allocator from other node_allocator template struct rebind - { + { typedef private_adaptive_pool_base other; }; @@ -112,7 +110,7 @@ class private_adaptive_pool_base template struct node_pool { - typedef ipcdetail::private_adaptive_node_pool + typedef detail::private_adaptive_node_pool ::value , NodesPerBlock @@ -154,7 +152,7 @@ class private_adaptive_pool_base {} //!Destructor, frees all used memory. Never throws - ~private_adaptive_pool_base() + ~private_adaptive_pool_base() {} //!Returns the segment manager. Never throws @@ -178,13 +176,13 @@ class private_adaptive_pool_base //!Equality test for same type of private_adaptive_pool_base template inline -bool operator==(const private_adaptive_pool_base &alloc1, +bool operator==(const private_adaptive_pool_base &alloc1, const private_adaptive_pool_base &alloc2) { return &alloc1 == &alloc2; } //!Inequality test for same type of private_adaptive_pool_base template inline -bool operator!=(const private_adaptive_pool_base &alloc1, +bool operator!=(const private_adaptive_pool_base &alloc1, const private_adaptive_pool_base &alloc2) { return &alloc1 != &alloc2; } @@ -205,16 +203,16 @@ class private_adaptive_pool_v1 > { public: - typedef ipcdetail::private_adaptive_pool_base + typedef detail::private_adaptive_pool_base < 1, T, SegmentManager, NodesPerBlock, MaxFreeBlocks, OverheadPercent> base_t; template struct rebind - { + { typedef private_adaptive_pool_v1 other; }; - private_adaptive_pool_v1(SegmentManager *segment_mngr) + private_adaptive_pool_v1(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -225,11 +223,11 @@ class private_adaptive_pool_v1 {} }; -} //namespace ipcdetail { +} //namespace detail { /// @endcond -//!An STL node allocator that uses a segment manager as memory +//!An STL node allocator that uses a segment manager as memory //!source. The internal pointer type will of the same type (raw, smart) as //!"typename SegmentManager::void_pointer" type. This allows //!placing the allocator in shared memory, memory mapped-files, etc... @@ -250,7 +248,7 @@ template < class T > class private_adaptive_pool /// @cond - : public ipcdetail::private_adaptive_pool_base + : public detail::private_adaptive_pool_base < 2 , T , SegmentManager @@ -262,19 +260,19 @@ class private_adaptive_pool { #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - typedef ipcdetail::private_adaptive_pool_base + typedef detail::private_adaptive_pool_base < 2, T, SegmentManager, NodesPerBlock, MaxFreeBlocks, OverheadPercent> base_t; public: typedef boost::interprocess::version_type version; template struct rebind - { + { typedef private_adaptive_pool other; }; - private_adaptive_pool(SegmentManager *segment_mngr) + private_adaptive_pool(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -291,18 +289,18 @@ class private_adaptive_pool typedef implementation_defined::pointer pointer; typedef implementation_defined::const_pointer const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; - //!Obtains private_adaptive_pool from + //!Obtains private_adaptive_pool from //!private_adaptive_pool template struct rebind - { + { typedef private_adaptive_pool other; }; @@ -314,7 +312,7 @@ class private_adaptive_pool private_adaptive_pool& operator= (const private_adaptive_pool&); - //!Not assignable from + //!Not assignable from //!other private_adaptive_pool private_adaptive_pool& operator=(const private_adaptive_pool&); @@ -324,7 +322,7 @@ class private_adaptive_pool //!Can throw boost::interprocess::bad_alloc private_adaptive_pool(segment_manager *segment_mngr); - //!Copy constructor from other private_adaptive_pool. Increments the reference + //!Copy constructor from other private_adaptive_pool. Increments the reference //!count of the associated node pool. Never throws private_adaptive_pool(const private_adaptive_pool &other); @@ -351,7 +349,7 @@ class private_adaptive_pool //!Never throws size_type max_size() const; - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0); @@ -375,7 +373,7 @@ class private_adaptive_pool //!Never throws const_pointer address(const_reference value) const; - //!Copy construct an object. + //!Copy construct an object. //!Throws if T's copy constructor throws void construct(const pointer &ptr, const_reference v); @@ -390,7 +388,7 @@ class private_adaptive_pool std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0); @@ -400,12 +398,12 @@ class private_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements); //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements); //!Allocates many elements of size elem_size in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -413,7 +411,7 @@ class private_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -426,7 +424,7 @@ class private_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_individual(std::size_t num_elements); //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -439,7 +437,7 @@ class private_adaptive_pool //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain); + void deallocate_individual(multiallocation_chain chain); #endif }; @@ -448,13 +446,13 @@ class private_adaptive_pool //!Equality test for same type //!of private_adaptive_pool template inline -bool operator==(const private_adaptive_pool &alloc1, +bool operator==(const private_adaptive_pool &alloc1, const private_adaptive_pool &alloc2); //!Inequality test for same type //!of private_adaptive_pool template inline -bool operator!=(const private_adaptive_pool &alloc1, +bool operator!=(const private_adaptive_pool &alloc1, const private_adaptive_pool &alloc2); #endif diff --git a/utils/boost_idb/boost/interprocess/allocators/private_node_allocator.hpp b/utils/boost_idb/boost/interprocess/allocators/private_node_allocator.hpp index 93a4750b..cb255640 100644 --- a/utils/boost_idb/boost/interprocess/allocators/private_node_allocator.hpp +++ b/utils/boost_idb/boost/interprocess/allocators/private_node_allocator.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,13 +18,13 @@ #include #include -#include +#include #include #include #include #include -#include +#include #include #include #include @@ -33,14 +33,14 @@ #include //!\file -//!Describes private_node_allocator_base pooled shared memory STL compatible allocator +//!Describes private_node_allocator_base pooled shared memory STL compatible allocator namespace boost { namespace interprocess { /// @cond -namespace ipcdetail { +namespace detail { template < unsigned int Version , class T @@ -64,7 +64,7 @@ class private_node_allocator_base private: typedef private_node_allocator_base < Version, T, SegmentManager, NodesPerBlock> self_t; - typedef ipcdetail::private_node_pool + typedef detail::private_node_pool ::value , NodesPerBlock @@ -75,29 +75,26 @@ class private_node_allocator_base /// @endcond public: - - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_pointer; + typedef typename boost:: + pointer_to_other::type pointer; + typedef typename boost:: + pointer_to_other::type const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manager::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; typedef boost::interprocess::version_type version; - typedef boost::container::container_detail::transform_multiallocation_chain + typedef boost::container::containers_detail::transform_multiallocation_chain multiallocation_chain; //!Obtains node_allocator from other node_allocator template struct rebind - { + { typedef private_node_allocator_base other; }; @@ -106,7 +103,7 @@ class private_node_allocator_base template struct node_pool { - typedef ipcdetail::private_node_pool + typedef detail::private_node_pool ::value , NodesPerBlock @@ -146,7 +143,7 @@ class private_node_allocator_base {} //!Destructor, frees all used memory. Never throws - ~private_node_allocator_base() + ~private_node_allocator_base() {} //!Returns the segment manager. Never throws @@ -170,13 +167,13 @@ class private_node_allocator_base //!Equality test for same type of private_node_allocator_base template inline -bool operator==(const private_node_allocator_base &alloc1, +bool operator==(const private_node_allocator_base &alloc1, const private_node_allocator_base &alloc2) { return &alloc1 == &alloc2; } //!Inequality test for same type of private_node_allocator_base template inline -bool operator!=(const private_node_allocator_base &alloc1, +bool operator!=(const private_node_allocator_base &alloc1, const private_node_allocator_base &alloc2) { return &alloc1 != &alloc2; } @@ -193,16 +190,16 @@ class private_node_allocator_v1 > { public: - typedef ipcdetail::private_node_allocator_base + typedef detail::private_node_allocator_base < 1, T, SegmentManager, NodesPerBlock> base_t; template struct rebind - { + { typedef private_node_allocator_v1 other; }; - private_node_allocator_v1(SegmentManager *segment_mngr) + private_node_allocator_v1(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -213,15 +210,15 @@ class private_node_allocator_v1 {} }; -} //namespace ipcdetail { +} //namespace detail { /// @endcond -//!An STL node allocator that uses a segment manager as memory +//!An STL node allocator that uses a segment manager as memory //!source. The internal pointer type will of the same type (raw, smart) as //!"typename SegmentManager::void_pointer" type. This allows //!placing the allocator in shared memory, memory mapped-files, etc... -//!This allocator has its own node pool. NodesPerBlock is the number of nodes allocated +//!This allocator has its own node pool. NodesPerBlock is the number of nodes allocated //!at once when the allocator needs runs out of nodes template < class T , class SegmentManager @@ -229,7 +226,7 @@ template < class T > class private_node_allocator /// @cond - : public ipcdetail::private_node_allocator_base + : public detail::private_node_allocator_base < 2 , T , SegmentManager @@ -239,19 +236,19 @@ class private_node_allocator { #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - typedef ipcdetail::private_node_allocator_base + typedef detail::private_node_allocator_base < 2, T, SegmentManager, NodesPerBlock> base_t; public: typedef boost::interprocess::version_type version; template struct rebind - { + { typedef private_node_allocator other; }; - private_node_allocator(SegmentManager *segment_mngr) + private_node_allocator(SegmentManager *segment_mngr) : base_t(segment_mngr) {} @@ -268,18 +265,18 @@ class private_node_allocator typedef implementation_defined::pointer pointer; typedef implementation_defined::const_pointer const_pointer; typedef T value_type; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename segment_manager::size_type size_type; - typedef typename segment_manage::difference_type difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; - //!Obtains private_node_allocator from + //!Obtains private_node_allocator from //!private_node_allocator template struct rebind - { + { typedef private_node_allocator other; }; @@ -291,7 +288,7 @@ class private_node_allocator private_node_allocator& operator= (const private_node_allocator&); - //!Not assignable from + //!Not assignable from //!other private_node_allocator private_node_allocator& operator=(const private_node_allocator&); @@ -301,7 +298,7 @@ class private_node_allocator //!Can throw boost::interprocess::bad_alloc private_node_allocator(segment_manager *segment_mngr); - //!Copy constructor from other private_node_allocator. Increments the reference + //!Copy constructor from other private_node_allocator. Increments the reference //!count of the associated node pool. Never throws private_node_allocator(const private_node_allocator &other); @@ -328,7 +325,7 @@ class private_node_allocator //!Never throws size_type max_size() const; - //!Allocate memory for an array of count elements. + //!Allocate memory for an array of count elements. //!Throws boost::interprocess::bad_alloc if there is no enough memory pointer allocate(size_type count, cvoid_pointer hint = 0); @@ -352,7 +349,7 @@ class private_node_allocator //!Never throws const_pointer address(const_reference value) const; - //!Copy construct an object. + //!Copy construct an object. //!Throws if T's copy constructor throws void construct(const pointer &ptr, const_reference v); @@ -367,7 +364,7 @@ class private_node_allocator std::pair allocation_command(boost::interprocess::allocation_type command, - size_type limit_size, + size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = 0); @@ -377,12 +374,12 @@ class private_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void allocate_many(size_type elem_size, size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(size_type elem_size, std::size_t num_elements); //!Allocates n_elements elements, each one of size elem_sizes[i]in a //!contiguous block //!of memory. The elements must be deallocated - void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain); + multiallocation_chain allocate_many(const size_type *elem_sizes, size_type n_elements); //!Allocates many elements of size elem_size in a contiguous block //!of memory. The minimum number to be allocated is min_elements, @@ -390,7 +387,7 @@ class private_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. The elements must be deallocated //!with deallocate(...) - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); //!Allocates just one object. Memory allocated with this function //!must be deallocated only with deallocate_one(). @@ -403,7 +400,7 @@ class private_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void allocate_individual(size_type num_elements, multiallocation_chain &chain); + multiallocation_chain allocate_individual(std::size_t num_elements); //!Deallocates memory previously allocated with allocate_one(). //!You should never use deallocate_one to deallocate memory allocated @@ -416,7 +413,7 @@ class private_node_allocator //!preferred_elements. The number of actually allocated elements is //!will be assigned to received_size. Memory allocated with this function //!must be deallocated only with deallocate_one(). - void deallocate_individual(multiallocation_chain &chain); + void deallocate_individual(multiallocation_chain chain); #endif }; @@ -425,13 +422,13 @@ class private_node_allocator //!Equality test for same type //!of private_node_allocator template inline -bool operator==(const private_node_allocator &alloc1, +bool operator==(const private_node_allocator &alloc1, const private_node_allocator &alloc2); //!Inequality test for same type //!of private_node_allocator template inline -bool operator!=(const private_node_allocator &alloc1, +bool operator!=(const private_node_allocator &alloc1, const private_node_allocator &alloc2); #endif diff --git a/utils/boost_idb/boost/interprocess/anonymous_shared_memory.hpp b/utils/boost_idb/boost/interprocess/anonymous_shared_memory.hpp index 2eb219a8..71bf2948 100644 --- a/utils/boost_idb/boost/interprocess/anonymous_shared_memory.hpp +++ b/utils/boost_idb/boost/interprocess/anonymous_shared_memory.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -14,13 +14,13 @@ #include #include #include -#include +#include #include #include #include #if (!defined(BOOST_INTERPROCESS_WINDOWS)) -# include //open, O_CREAT, O_*... +# include //open, O_CREAT, O_*... # include //mmap # include //mode_t, S_IRWXG, S_IRWXO, S_IRWXU, #else @@ -37,16 +37,18 @@ namespace interprocess { /// @cond -namespace ipcdetail{ +namespace detail{ class raw_mapped_region_creator { public: static mapped_region - create_posix_mapped_region(void *address, std::size_t size) + create_posix_mapped_region(void *address, offset_t offset, std::size_t size) { mapped_region region; region.m_base = address; + region.m_offset = offset; + region.m_extra_offset = 0; region.m_size = size; return region; } @@ -90,16 +92,16 @@ anonymous_shared_memory(std::size_t size, void *address = 0) , 0); if(address == MAP_FAILED){ - if(fd != -1) + if(fd != -1) close(fd); error_info err = system_error_code(); throw interprocess_exception(err); } - if(fd != -1) + if(fd != -1) close(fd); - return ipcdetail::raw_mapped_region_creator::create_posix_mapped_region(address, size); + return detail::raw_mapped_region_creator::create_posix_mapped_region(address, 0, size); } #else { diff --git a/utils/boost_idb/boost/interprocess/containers/allocation_type.hpp b/utils/boost_idb/boost/interprocess/containers/allocation_type.hpp index eea431b0..a8de72ab 100644 --- a/utils/boost_idb/boost/interprocess/containers/allocation_type.hpp +++ b/utils/boost_idb/boost/interprocess/containers/allocation_type.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include namespace boost { namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/containers/container/container_fwd.hpp b/utils/boost_idb/boost/interprocess/containers/container/container_fwd.hpp new file mode 100644 index 00000000..d1554eb9 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/container_fwd.hpp @@ -0,0 +1,187 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_CONTAINERS_FWD_HPP +#define BOOST_CONTAINERS_CONTAINERS_FWD_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +////////////////////////////////////////////////////////////////////////////// +// Standard predeclarations +////////////////////////////////////////////////////////////////////////////// + +/// @cond + +namespace boost{ +namespace intrusive{ + //Create namespace to avoid compilation errors +}} + +namespace boost{ namespace container{ namespace containers_detail{ + +namespace bi = boost::intrusive; + +}}} + +namespace std { + +template +class allocator; + +template +struct less; + +template +struct pair; + +template +struct char_traits; + +} //namespace std { + +/// @endcond + +////////////////////////////////////////////////////////////////////////////// +// Containers +////////////////////////////////////////////////////////////////////////////// + +namespace boost { +namespace container { + +//vector class +template > +class vector; + +//vector class +template > +class stable_vector; + +//vector class +template > +class deque; + +//list class +template > +class list; + +//slist class +template > +class slist; + +//set class +template + ,class Alloc = std::allocator > +class set; + +//multiset class +template + ,class Alloc = std::allocator > +class multiset; + +//map class +template + ,class Alloc = std::allocator > > +class map; + +//multimap class +template + ,class Alloc = std::allocator > > +class multimap; + +//flat_set class +template + ,class Alloc = std::allocator > +class flat_set; + +//flat_multiset class +template + ,class Alloc = std::allocator > +class flat_multiset; + +//flat_map class +template + ,class Alloc = std::allocator > > +class flat_map; + +//flat_multimap class +template + ,class Alloc = std::allocator > > +class flat_multimap; + +//basic_string class +template + ,class Alloc = std::allocator > +class basic_string; + +//! Type used to tag that the input range is +//! guaranteed to be ordered +struct ordered_range_impl_t {}; + +//! Type used to tag that the input range is +//! guaranteed to be ordered and unique +struct ordered_unique_range_impl_t{}; + +/// @cond + +typedef ordered_range_impl_t * ordered_range_t; +typedef ordered_unique_range_impl_t *ordered_unique_range_t; + +/// @endcond + +//! Value used to tag that the input range is +//! guaranteed to be ordered +static const ordered_range_t ordered_range = 0; + +//! Value used to tag that the input range is +//! guaranteed to be ordered and unique +static const ordered_unique_range_t ordered_unique_range = 0; + +/// @cond + +namespace detail_really_deep_namespace { + +//Otherwise, gcc issues a warning of previously defined +//anonymous_instance and unique_instance +struct dummy +{ + dummy() + { + (void)ordered_range; + (void)ordered_unique_range; + } +}; + +} //detail_really_deep_namespace { + +/// @endcond + +}} //namespace boost { namespace container { + +#endif //#ifndef BOOST_CONTAINERS_CONTAINERS_FWD_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/deque.hpp b/utils/boost_idb/boost/interprocess/containers/container/deque.hpp new file mode 100644 index 00000000..4631d95a --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/deque.hpp @@ -0,0 +1,1488 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2006. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DEQUE_HPP +#define BOOST_CONTAINERS_DEQUE_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ADVANCED_INSERT_INT_HPP + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +template +class deque; + +template +struct deque_value_traits +{ + typedef T value_type; + typedef A allocator_type; + static const bool trivial_dctr = boost::has_trivial_destructor::value; + static const bool trivial_dctr_after_move = false; + //::boost::has_trivial_destructor_after_move::value || trivial_dctr; + static const bool trivial_copy = has_trivial_copy::value; + static const bool nothrow_copy = has_nothrow_copy::value; + static const bool trivial_assign = has_trivial_assign::value; + static const bool nothrow_assign = has_nothrow_assign::value; + +}; + +// Note: this function is simply a kludge to work around several compilers' +// bugs in handling constant expressions. +inline std::size_t deque_buf_size(std::size_t size) + { return size < 512 ? std::size_t(512 / size) : std::size_t(1); } + +// Deque base class. It has two purposes. First, its constructor +// and destructor allocate (but don't initialize) storage. This makes +// exception safety easier. +template +class deque_base +{ + public: + typedef typename Alloc::value_type val_alloc_val; + typedef typename Alloc::pointer val_alloc_ptr; + typedef typename Alloc::const_pointer val_alloc_cptr; + typedef typename Alloc::reference val_alloc_ref; + typedef typename Alloc::const_reference val_alloc_cref; + typedef typename Alloc::value_type val_alloc_diff; + typedef typename Alloc::template rebind + ::other ptr_alloc_t; + typedef typename ptr_alloc_t::value_type ptr_alloc_val; + typedef typename ptr_alloc_t::pointer ptr_alloc_ptr; + typedef typename ptr_alloc_t::const_pointer ptr_alloc_cptr; + typedef typename ptr_alloc_t::reference ptr_alloc_ref; + typedef typename ptr_alloc_t::const_reference ptr_alloc_cref; + typedef typename Alloc::template + rebind::other allocator_type; + typedef allocator_type stored_allocator_type; + + protected: + + typedef deque_value_traits traits_t; + typedef typename Alloc::template + rebind::other map_allocator_type; + + static std::size_t s_buffer_size() { return deque_buf_size(sizeof(T)); } + + val_alloc_ptr priv_allocate_node() + { return this->alloc().allocate(s_buffer_size()); } + + void priv_deallocate_node(val_alloc_ptr p) + { this->alloc().deallocate(p, s_buffer_size()); } + + ptr_alloc_ptr priv_allocate_map(std::size_t n) + { return this->ptr_alloc().allocate(n); } + + void priv_deallocate_map(ptr_alloc_ptr p, std::size_t n) + { this->ptr_alloc().deallocate(p, n); } + + public: + // Class invariants: + // For any nonsingular iterator i: + // i.node is the address of an element in the map array. The + // contents of i.node is a pointer to the beginning of a node. + // i.first == //(i.node) + // i.last == i.first + node_size + // i.cur is a pointer in the range [i.first, i.last). NOTE: + // the implication of this is that i.cur is always a dereferenceable + // pointer, even if i is a past-the-end iterator. + // Start and Finish are always nonsingular iterators. NOTE: this means + // that an empty deque must have one node, and that a deque + // with N elements, where N is the buffer size, must have two nodes. + // For every node other than start.node and finish.node, every element + // in the node is an initialized object. If start.node == finish.node, + // then [start.cur, finish.cur) are initialized objects, and + // the elements outside that range are uninitialized storage. Otherwise, + // [start.cur, start.last) and [finish.first, finish.cur) are initialized + // objects, and [start.first, start.cur) and [finish.cur, finish.last) + // are uninitialized storage. + // [map, map + map_size) is a valid, non-empty range. + // [start.node, finish.node] is a valid range contained within + // [map, map + map_size). + // A pointer in the range [map, map + map_size) points to an allocated node + // if and only if the pointer is in the range [start.node, finish.node]. + class const_iterator + : public std::iterator + { + public: + static std::size_t s_buffer_size() { return deque_base::s_buffer_size(); } + + typedef std::random_access_iterator_tag iterator_category; + typedef val_alloc_val value_type; + typedef val_alloc_cptr pointer; + typedef val_alloc_cref reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + typedef ptr_alloc_ptr index_pointer; + typedef const_iterator self_t; + + friend class deque; + friend class deque_base; + + protected: + val_alloc_ptr m_cur; + val_alloc_ptr m_first; + val_alloc_ptr m_last; + index_pointer m_node; + + public: + const_iterator(val_alloc_ptr x, index_pointer y) + : m_cur(x), m_first(*y), + m_last(*y + s_buffer_size()), m_node(y) {} + + const_iterator() : m_cur(0), m_first(0), m_last(0), m_node(0) {} + + const_iterator(const const_iterator& x) + : m_cur(x.m_cur), m_first(x.m_first), + m_last(x.m_last), m_node(x.m_node) {} + + reference operator*() const + { return *this->m_cur; } + + pointer operator->() const + { return this->m_cur; } + + difference_type operator-(const self_t& x) const + { + if(!this->m_cur && !x.m_cur){ + return 0; + } + return difference_type(this->s_buffer_size()) * (this->m_node - x.m_node - 1) + + (this->m_cur - this->m_first) + (x.m_last - x.m_cur); + } + + self_t& operator++() + { + ++this->m_cur; + if (this->m_cur == this->m_last) { + this->priv_set_node(this->m_node + 1); + this->m_cur = this->m_first; + } + return *this; + } + + self_t operator++(int) + { + self_t tmp = *this; + ++*this; + return tmp; + } + + self_t& operator--() + { + if (this->m_cur == this->m_first) { + this->priv_set_node(this->m_node - 1); + this->m_cur = this->m_last; + } + --this->m_cur; + return *this; + } + + self_t operator--(int) + { + self_t tmp = *this; + --*this; + return tmp; + } + + self_t& operator+=(difference_type n) + { + difference_type offset = n + (this->m_cur - this->m_first); + if (offset >= 0 && offset < difference_type(this->s_buffer_size())) + this->m_cur += n; + else { + difference_type node_offset = + offset > 0 ? offset / difference_type(this->s_buffer_size()) + : -difference_type((-offset - 1) / this->s_buffer_size()) - 1; + this->priv_set_node(this->m_node + node_offset); + this->m_cur = this->m_first + + (offset - node_offset * difference_type(this->s_buffer_size())); + } + return *this; + } + + self_t operator+(difference_type n) const + { self_t tmp = *this; return tmp += n; } + + self_t& operator-=(difference_type n) + { return *this += -n; } + + self_t operator-(difference_type n) const + { self_t tmp = *this; return tmp -= n; } + + reference operator[](difference_type n) const + { return *(*this + n); } + + bool operator==(const self_t& x) const + { return this->m_cur == x.m_cur; } + + bool operator!=(const self_t& x) const + { return !(*this == x); } + + bool operator<(const self_t& x) const + { + return (this->m_node == x.m_node) ? + (this->m_cur < x.m_cur) : (this->m_node < x.m_node); + } + + bool operator>(const self_t& x) const + { return x < *this; } + + bool operator<=(const self_t& x) const + { return !(x < *this); } + + bool operator>=(const self_t& x) const + { return !(*this < x); } + + void priv_set_node(index_pointer new_node) + { + this->m_node = new_node; + this->m_first = *new_node; + this->m_last = this->m_first + difference_type(this->s_buffer_size()); + } + + friend const_iterator operator+(std::ptrdiff_t n, const const_iterator& x) + { return x + n; } + }; + + //Deque iterator + class iterator : public const_iterator + { + public: + typedef std::random_access_iterator_tag iterator_category; + typedef val_alloc_val value_type; + typedef val_alloc_ptr pointer; + typedef val_alloc_ref reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + typedef ptr_alloc_ptr index_pointer; + typedef const_iterator self_t; + + friend class deque; + friend class deque_base; + + private: + explicit iterator(const const_iterator& x) : const_iterator(x){} + + public: + //Constructors + iterator(val_alloc_ptr x, index_pointer y) : const_iterator(x, y){} + iterator() : const_iterator(){} + //iterator(const const_iterator &cit) : const_iterator(cit){} + iterator(const iterator& x) : const_iterator(x){} + + //Pointer like operators + reference operator*() const { return *this->m_cur; } + pointer operator->() const { return this->m_cur; } + + reference operator[](difference_type n) const { return *(*this + n); } + + //Increment / Decrement + iterator& operator++() + { this->const_iterator::operator++(); return *this; } + + iterator operator++(int) + { iterator tmp = *this; ++*this; return tmp; } + + iterator& operator--() + { this->const_iterator::operator--(); return *this; } + + iterator operator--(int) + { iterator tmp = *this; --*this; return tmp; } + + // Arithmetic + iterator& operator+=(difference_type off) + { this->const_iterator::operator+=(off); return *this; } + + iterator operator+(difference_type off) const + { return iterator(this->const_iterator::operator+(off)); } + + friend iterator operator+(difference_type off, const iterator& right) + { return iterator(off+static_cast(right)); } + + iterator& operator-=(difference_type off) + { this->const_iterator::operator-=(off); return *this; } + + iterator operator-(difference_type off) const + { return iterator(this->const_iterator::operator-(off)); } + + difference_type operator-(const const_iterator& right) const + { return static_cast(*this) - right; } + }; + + deque_base(const allocator_type& a, std::size_t num_elements) + : members_(a) + { this->priv_initialize_map(num_elements); } + + deque_base(const allocator_type& a) + : members_(a) + {} + + ~deque_base() + { + if (this->members_.m_map) { + this->priv_destroy_nodes(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1); + this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); + } + } + + private: + deque_base(const deque_base&); + + protected: + + void priv_initialize_map(std::size_t num_elements) + { +// if(num_elements){ + std::size_t num_nodes = num_elements / s_buffer_size() + 1; + + this->members_.m_map_size = containers_detail::max_value((std::size_t) InitialMapSize, num_nodes + 2); + this->members_.m_map = this->priv_allocate_map(this->members_.m_map_size); + + ptr_alloc_ptr nstart = this->members_.m_map + (this->members_.m_map_size - num_nodes) / 2; + ptr_alloc_ptr nfinish = nstart + num_nodes; + + BOOST_TRY { + this->priv_create_nodes(nstart, nfinish); + } + BOOST_CATCH(...){ + this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); + this->members_.m_map = 0; + this->members_.m_map_size = 0; + BOOST_RETHROW + } + BOOST_CATCH_END + + this->members_.m_start.priv_set_node(nstart); + this->members_.m_finish.priv_set_node(nfinish - 1); + this->members_.m_start.m_cur = this->members_.m_start.m_first; + this->members_.m_finish.m_cur = this->members_.m_finish.m_first + + num_elements % s_buffer_size(); +// } + } + + void priv_create_nodes(ptr_alloc_ptr nstart, ptr_alloc_ptr nfinish) + { + ptr_alloc_ptr cur; + BOOST_TRY { + for (cur = nstart; cur < nfinish; ++cur) + *cur = this->priv_allocate_node(); + } + BOOST_CATCH(...){ + this->priv_destroy_nodes(nstart, cur); + BOOST_RETHROW + } + BOOST_CATCH_END + } + + void priv_destroy_nodes(ptr_alloc_ptr nstart, ptr_alloc_ptr nfinish) + { + for (ptr_alloc_ptr n = nstart; n < nfinish; ++n) + this->priv_deallocate_node(*n); + } + + enum { InitialMapSize = 8 }; + + protected: + struct members_holder + : public ptr_alloc_t + , public allocator_type + { + members_holder(const allocator_type &a) + : map_allocator_type(a), allocator_type(a) + , m_map(0), m_map_size(0) + , m_start(), m_finish(m_start) + {} + + ptr_alloc_ptr m_map; + std::size_t m_map_size; + iterator m_start; + iterator m_finish; + } members_; + + ptr_alloc_t &ptr_alloc() + { return members_; } + + const ptr_alloc_t &ptr_alloc() const + { return members_; } + + allocator_type &alloc() + { return members_; } + + const allocator_type &alloc() const + { return members_; } +}; +/// @endcond + +//! Deque class +//! +template +class deque : protected deque_base +{ + /// @cond + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + typedef deque_base Base; + + public: // Basic types + typedef typename Alloc::value_type val_alloc_val; + typedef typename Alloc::pointer val_alloc_ptr; + typedef typename Alloc::const_pointer val_alloc_cptr; + typedef typename Alloc::reference val_alloc_ref; + typedef typename Alloc::const_reference val_alloc_cref; + typedef typename Alloc::template + rebind::other ptr_alloc_t; + typedef typename ptr_alloc_t::value_type ptr_alloc_val; + typedef typename ptr_alloc_t::pointer ptr_alloc_ptr; + typedef typename ptr_alloc_t::const_pointer ptr_alloc_cptr; + typedef typename ptr_alloc_t::reference ptr_alloc_ref; + typedef typename ptr_alloc_t::const_reference ptr_alloc_cref; + /// @endcond + + typedef T value_type; + typedef val_alloc_ptr pointer; + typedef val_alloc_cptr const_pointer; + typedef val_alloc_ref reference; + typedef val_alloc_cref const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + typedef typename Base::allocator_type allocator_type; + + public: // Iterators + typedef typename Base::iterator iterator; + typedef typename Base::const_iterator const_iterator; + + typedef std::reverse_iterator const_reverse_iterator; + typedef std::reverse_iterator reverse_iterator; + + /// @cond + private: // Internal typedefs + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(deque) + typedef ptr_alloc_ptr index_pointer; + static std::size_t s_buffer_size() + { return Base::s_buffer_size(); } + typedef containers_detail::advanced_insert_aux_int advanced_insert_aux_int_t; + typedef repeat_iterator r_iterator; + typedef BOOST_CONTAINER_MOVE_NAMESPACE::move_iterator move_it; + + /// @endcond + + allocator_type get_allocator() const { return Base::alloc(); } + + public: // Basic accessors + + iterator begin() + { return this->members_.m_start; } + + iterator end() + { return this->members_.m_finish; } + + const_iterator begin() const + { return this->members_.m_start; } + + const_iterator end() const + { return this->members_.m_finish; } + + reverse_iterator rbegin() + { return reverse_iterator(this->members_.m_finish); } + + reverse_iterator rend() + { return reverse_iterator(this->members_.m_start); } + + const_reverse_iterator rbegin() const + { return const_reverse_iterator(this->members_.m_finish); } + + const_reverse_iterator rend() const + { return const_reverse_iterator(this->members_.m_start); } + + const_iterator cbegin() const + { return this->members_.m_start; } + + const_iterator cend() const + { return this->members_.m_finish; } + + const_reverse_iterator crbegin() const + { return const_reverse_iterator(this->members_.m_finish); } + + const_reverse_iterator crend() const + { return const_reverse_iterator(this->members_.m_start); } + + reference operator[](size_type n) + { return this->members_.m_start[difference_type(n)]; } + + const_reference operator[](size_type n) const + { return this->members_.m_start[difference_type(n)]; } + + void priv_range_check(size_type n) const + { if (n >= this->size()) BOOST_RETHROW std::out_of_range("deque"); } + + reference at(size_type n) + { this->priv_range_check(n); return (*this)[n]; } + + const_reference at(size_type n) const + { this->priv_range_check(n); return (*this)[n]; } + + reference front() { return *this->members_.m_start; } + + reference back() { return *(end()-1); } + + const_reference front() const + { return *this->members_.m_start; } + + const_reference back() const { return *(cend()-1); } + + size_type size() const + { return this->members_.m_finish - this->members_.m_start; } + + size_type max_size() const + { return this->alloc().max_size(); } + + bool empty() const + { return this->members_.m_finish == this->members_.m_start; } + + explicit deque(const allocator_type& a = allocator_type()) + : Base(a) + {} + + deque(const deque& x) + : Base(x.alloc()) + { + if(x.size()){ + this->priv_initialize_map(x.size()); + std::uninitialized_copy(x.begin(), x.end(), this->members_.m_start); + } + } + + deque(BOOST_MOVE_MACRO_RV_REF(deque) mx) + : Base(mx.alloc()) + { this->swap(mx); } + + deque(size_type n, const value_type& value, + const allocator_type& a = allocator_type()) : Base(a, n) + { this->priv_fill_initialize(value); } + + explicit deque(size_type n) : Base(allocator_type(), n) + { this->resize(n); } + + // Check whether it's an integral type. If so, it's not an iterator. + template + deque(InpIt first, InpIt last, const allocator_type& a = allocator_type()) + : Base(a) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_initialize_dispatch(first, last, Result()); + } + + ~deque() + { + priv_destroy_range(this->members_.m_start, this->members_.m_finish); + } + + deque& operator= (BOOST_MOVE_MACRO_COPY_ASSIGN_REF(deque) x) + { + const size_type len = size(); + if (&x != this) { + if (len >= x.size()) + this->erase(std::copy(x.begin(), x.end(), this->members_.m_start), this->members_.m_finish); + else { + const_iterator mid = x.begin() + difference_type(len); + std::copy(x.begin(), mid, this->members_.m_start); + this->insert(this->members_.m_finish, mid, x.end()); + } + } + return *this; + } + + deque& operator= (BOOST_MOVE_MACRO_RV_REF(deque) x) + { + this->clear(); + this->swap(x); + return *this; + } + + void swap(deque &x) + { + std::swap(this->members_.m_start, x.members_.m_start); + std::swap(this->members_.m_finish, x.members_.m_finish); + std::swap(this->members_.m_map, x.members_.m_map); + std::swap(this->members_.m_map_size, x.members_.m_map_size); + } + + void assign(size_type n, const T& val) + { this->priv_fill_assign(n, val); } + + template + void assign(InpIt first, InpIt last) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_assign_dispatch(first, last, Result()); + } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_back(T &x) { push_back(const_cast(x)); } + + template + void push_back(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_push_back(u); } + #endif + + void push_back(insert_const_ref_type t) + { return priv_push_back(t); } + + void push_back(BOOST_MOVE_MACRO_RV_REF(value_type) t) + { + if(this->priv_push_back_simple_available()){ + new(this->priv_push_back_simple_pos())value_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(t)); + this->priv_push_back_simple_commit(); + } + else{ + this->priv_insert_aux(cend(), move_it(r_iterator(t, 1)), move_it(r_iterator())); + } + } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_front(T &x) { push_front(const_cast(x)); } + + template + void push_front(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_push_front(u); } + #endif + + void push_front(insert_const_ref_type t) + { return priv_push_front(t); } + + void push_front(BOOST_MOVE_MACRO_RV_REF(value_type) t) + { + if(this->priv_push_front_simple_available()){ + new(this->priv_push_front_simple_pos())value_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(t)); + this->priv_push_front_simple_commit(); + } + else{ + this->priv_insert_aux(cbegin(), move_it(r_iterator(t, 1)), move_it(r_iterator())); + } + } + + void pop_back() + { + if (this->members_.m_finish.m_cur != this->members_.m_finish.m_first) { + --this->members_.m_finish.m_cur; + containers_detail::get_pointer(this->members_.m_finish.m_cur)->~value_type(); + } + else + this->priv_pop_back_aux(); + } + + void pop_front() + { + if (this->members_.m_start.m_cur != this->members_.m_start.m_last - 1) { + containers_detail::get_pointer(this->members_.m_start.m_cur)->~value_type(); + ++this->members_.m_start.m_cur; + } + else + this->priv_pop_front_aux(); + } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) + { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return this->priv_insert(position, u); } + #endif + + iterator insert(const_iterator position, insert_const_ref_type x) + { return this->priv_insert(position, x); } + + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(value_type) mx) + { + if (position == cbegin()) { + this->push_front(BOOST_CONTAINER_MOVE_NAMESPACE::move(mx)); + return begin(); + } + else if (position == cend()) { + this->push_back(BOOST_CONTAINER_MOVE_NAMESPACE::move(mx)); + return(end()-1); + } + else { + //Just call more general insert(pos, size, value) and return iterator + size_type n = position - begin(); + this->priv_insert_aux(position, move_it(r_iterator(mx, 1)), move_it(r_iterator())); + return iterator(this->begin() + n); + } + } + + void insert(const_iterator pos, size_type n, const value_type& x) + { this->priv_fill_insert(pos, n, x); } + + // Check whether it's an integral type. If so, it's not an iterator. + template + void insert(const_iterator pos, InpIt first, InpIt last) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_insert_dispatch(pos, first, last, Result()); + } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + template + void emplace_back(Args&&... args) + { + if(this->priv_push_back_simple_available()){ + new(this->priv_push_back_simple_pos())value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->priv_push_back_simple_commit(); + } + else{ + typedef containers_detail::advanced_insert_aux_emplace type; + type &&proxy = type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->priv_insert_aux_impl(this->cend(), 1, proxy); + } + } + + template + void emplace_front(Args&&... args) + { + if(this->priv_push_front_simple_available()){ + new(this->priv_push_front_simple_pos())value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->priv_push_front_simple_commit(); + } + else{ + typedef containers_detail::advanced_insert_aux_emplace type; + type &&proxy = type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->priv_insert_aux_impl(this->cbegin(), 1, proxy); + } + } + + template + iterator emplace(const_iterator p, Args&&... args) + { + if(p == this->cbegin()){ + this->emplace_front(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + return this->begin(); + } + else if(p == this->cend()){ + this->emplace_back(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + return (this->end()-1); + } + else{ + size_type n = p - this->cbegin(); + typedef containers_detail::advanced_insert_aux_emplace type; + type &&proxy = type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->priv_insert_aux_impl(p, 1, proxy); + return iterator(this->begin() + n); + } + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //0 args + void emplace_back() + { + if(priv_push_front_simple_available()){ + new(priv_push_front_simple_pos())value_type(); + priv_push_front_simple_commit(); + } + else{ + containers_detail::advanced_insert_aux_emplace proxy; + priv_insert_aux_impl(cend(), 1, proxy); + } + } + + void emplace_front() + { + if(priv_push_front_simple_available()){ + new(priv_push_front_simple_pos())value_type(); + priv_push_front_simple_commit(); + } + else{ + containers_detail::advanced_insert_aux_emplace proxy; + priv_insert_aux_impl(cbegin(), 1, proxy); + } + } + + iterator emplace(const_iterator p) + { + if(p == cbegin()){ + emplace_front(); + return begin(); + } + else if(p == cend()){ + emplace_back(); + return (end()-1); + } + else{ + size_type n = p - cbegin(); + containers_detail::advanced_insert_aux_emplace proxy; + priv_insert_aux_impl(p, 1, proxy); + return iterator(this->begin() + n); + } + } + + //advanced_insert_int.hpp includes all necessary preprocessor machinery... + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + if(priv_push_back_simple_available()){ \ + new(priv_push_back_simple_pos())value_type \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + priv_push_back_simple_commit(); \ + } \ + else{ \ + containers_detail::BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + \ + proxy(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + priv_insert_aux_impl(cend(), 1, proxy); \ + } \ + } \ + \ + template \ + void emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + if(priv_push_front_simple_available()){ \ + new(priv_push_front_simple_pos())value_type \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + priv_push_front_simple_commit(); \ + } \ + else{ \ + containers_detail::BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + \ + proxy(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + priv_insert_aux_impl(cbegin(), 1, proxy); \ + } \ + } \ + \ + template \ + iterator emplace(const_iterator p, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + if(p == this->cbegin()){ \ + this->emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + return this->begin(); \ + } \ + else if(p == cend()){ \ + this->emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + return (this->end()-1); \ + } \ + else{ \ + size_type pos_num = p - this->cbegin(); \ + containers_detail::BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + \ + proxy(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + this->priv_insert_aux_impl(p, 1, proxy); \ + return iterator(this->begin() + pos_num); \ + } \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + void resize(size_type new_size, const value_type& x) + { + const size_type len = size(); + if (new_size < len) + this->erase(this->members_.m_start + new_size, this->members_.m_finish); + else + this->insert(this->members_.m_finish, new_size - len, x); + } + + void resize(size_type new_size) + { + const size_type len = size(); + if (new_size < len) + this->erase(this->members_.m_start + new_size, this->members_.m_finish); + else{ + size_type n = new_size - this->size(); + containers_detail::default_construct_aux_proxy proxy(n); + priv_insert_aux_impl(this->cend(), n, proxy); + } + } + + iterator erase(const_iterator pos) + { + const_iterator next = pos; + ++next; + difference_type index = pos - this->members_.m_start; + if (size_type(index) < (this->size() >> 1)) { + BOOST_CONTAINER_MOVE_NAMESPACE::move_backward(begin(), iterator(pos), iterator(next)); + pop_front(); + } + else { + BOOST_CONTAINER_MOVE_NAMESPACE::move(iterator(next), end(), iterator(pos)); + pop_back(); + } + return this->members_.m_start + index; + } + + iterator erase(const_iterator first, const_iterator last) + { + if (first == this->members_.m_start && last == this->members_.m_finish) { + this->clear(); + return this->members_.m_finish; + } + else { + difference_type n = last - first; + difference_type elems_before = first - this->members_.m_start; + if (elems_before < static_cast(this->size() - n) - elems_before) { + BOOST_CONTAINER_MOVE_NAMESPACE::move_backward(begin(), iterator(first), iterator(last)); + iterator new_start = this->members_.m_start + n; + if(!Base::traits_t::trivial_dctr_after_move) + this->priv_destroy_range(this->members_.m_start, new_start); + this->priv_destroy_nodes(new_start.m_node, this->members_.m_start.m_node); + this->members_.m_start = new_start; + } + else { + BOOST_CONTAINER_MOVE_NAMESPACE::move(iterator(last), end(), iterator(first)); + iterator new_finish = this->members_.m_finish - n; + if(!Base::traits_t::trivial_dctr_after_move) + this->priv_destroy_range(new_finish, this->members_.m_finish); + this->priv_destroy_nodes(new_finish.m_node + 1, this->members_.m_finish.m_node + 1); + this->members_.m_finish = new_finish; + } + return this->members_.m_start + elems_before; + } + } + + void clear() + { + for (index_pointer node = this->members_.m_start.m_node + 1; + node < this->members_.m_finish.m_node; + ++node) { + this->priv_destroy_range(*node, *node + this->s_buffer_size()); + this->priv_deallocate_node(*node); + } + + if (this->members_.m_start.m_node != this->members_.m_finish.m_node) { + this->priv_destroy_range(this->members_.m_start.m_cur, this->members_.m_start.m_last); + this->priv_destroy_range(this->members_.m_finish.m_first, this->members_.m_finish.m_cur); + this->priv_deallocate_node(this->members_.m_finish.m_first); + } + else + this->priv_destroy_range(this->members_.m_start.m_cur, this->members_.m_finish.m_cur); + + this->members_.m_finish = this->members_.m_start; + } + + /// @cond + private: + + iterator priv_insert(const_iterator position, const value_type &x) + { + if (position == cbegin()){ + this->push_front(x); + return begin(); + } + else if (position == cend()){ + this->push_back(x); + return (end()-1); + } + else { + size_type n = position - cbegin(); + this->priv_insert_aux(position, size_type(1), x); + return iterator(this->begin() + n); + } + } + + void priv_push_front(const value_type &t) + { + if(this->priv_push_front_simple_available()){ + new(this->priv_push_front_simple_pos())value_type(t); + this->priv_push_front_simple_commit(); + } + else{ + this->priv_insert_aux(cbegin(), size_type(1), t); + } + } + + void priv_push_back(const value_type &t) + { + if(this->priv_push_back_simple_available()){ + new(this->priv_push_back_simple_pos())value_type(t); + this->priv_push_back_simple_commit(); + } + else{ + this->priv_insert_aux(cend(), size_type(1), t); + } + } + + + bool priv_push_back_simple_available() const + { + return this->members_.m_map && + (this->members_.m_finish.m_cur != (this->members_.m_finish.m_last - 1)); + } + + void *priv_push_back_simple_pos() const + { + return static_cast(containers_detail::get_pointer(this->members_.m_finish.m_cur)); + } + + void priv_push_back_simple_commit() + { + ++this->members_.m_finish.m_cur; + } + + bool priv_push_front_simple_available() const + { + return this->members_.m_map && + (this->members_.m_start.m_cur != this->members_.m_start.m_first); + } + + void *priv_push_front_simple_pos() const + { return static_cast(containers_detail::get_pointer(this->members_.m_start.m_cur) - 1); } + + void priv_push_front_simple_commit() + { --this->members_.m_start.m_cur; } + + template + void priv_insert_aux(const_iterator pos, InpIt first, InpIt last, std::input_iterator_tag) + { + for(;first != last; ++first){ + this->insert(pos, BOOST_CONTAINER_MOVE_NAMESPACE::move(value_type(*first))); + } + } + + template + void priv_insert_aux(const_iterator pos, FwdIt first, FwdIt last, std::forward_iterator_tag) + { this->priv_insert_aux(pos, first, last); } + + // assign(), a generalized assignment member function. Two + // versions: one that takes a count, and one that takes a range. + // The range version is a member template, so we dispatch on whether + // or not the type is an integer. + void priv_fill_assign(size_type n, const T& val) + { + if (n > size()) { + std::fill(begin(), end(), val); + this->insert(cend(), n - size(), val); + } + else { + this->erase(cbegin() + n, cend()); + std::fill(begin(), end(), val); + } + } + + template + void priv_initialize_dispatch(Integer n, Integer x, containers_detail::true_) + { + this->priv_initialize_map(n); + this->priv_fill_initialize(x); + } + + template + void priv_initialize_dispatch(InpIt first, InpIt last, containers_detail::false_) + { + typedef typename std::iterator_traits::iterator_category ItCat; + this->priv_range_initialize(first, last, ItCat()); + } + + void priv_destroy_range(iterator p, iterator p2) + { + for(;p != p2; ++p) + containers_detail::get_pointer(&*p)->~value_type(); + } + + void priv_destroy_range(pointer p, pointer p2) + { + for(;p != p2; ++p) + containers_detail::get_pointer(&*p)->~value_type(); + } + + template + void priv_assign_dispatch(Integer n, Integer val, containers_detail::true_) + { this->priv_fill_assign((size_type) n, (value_type)val); } + + template + void priv_assign_dispatch(InpIt first, InpIt last, containers_detail::false_) + { + typedef typename std::iterator_traits::iterator_category ItCat; + this->priv_assign_aux(first, last, ItCat()); + } + + template + void priv_assign_aux(InpIt first, InpIt last, std::input_iterator_tag) + { + iterator cur = begin(); + for ( ; first != last && cur != end(); ++cur, ++first) + *cur = *first; + if (first == last) + this->erase(cur, cend()); + else + this->insert(cend(), first, last); + } + + template + void priv_assign_aux(FwdIt first, FwdIt last, std::forward_iterator_tag) + { + size_type len = std::distance(first, last); + if (len > size()) { + FwdIt mid = first; + std::advance(mid, size()); + std::copy(first, mid, begin()); + this->insert(cend(), mid, last); + } + else + this->erase(std::copy(first, last, begin()), cend()); + } + + template + void priv_insert_dispatch(const_iterator pos, Integer n, Integer x, containers_detail::true_) + { this->priv_fill_insert(pos, (size_type) n, (value_type)x); } + + template + void priv_insert_dispatch(const_iterator pos,InpIt first, InpIt last, containers_detail::false_) + { + typedef typename std::iterator_traits::iterator_category ItCat; + this->priv_insert_aux(pos, first, last, ItCat()); + } + + void priv_insert_aux(const_iterator pos, size_type n, const value_type& x) + { + typedef constant_iterator c_it; + this->priv_insert_aux(pos, c_it(x, n), c_it()); + } + + //Just forward all operations to priv_insert_aux_impl + template + void priv_insert_aux(const_iterator p, FwdIt first, FwdIt last) + { + containers_detail::advanced_insert_aux_proxy proxy(first, last); + priv_insert_aux_impl(p, (size_type)std::distance(first, last), proxy); + } + + void priv_insert_aux_impl(const_iterator p, size_type n, advanced_insert_aux_int_t &interf) + { + iterator pos(p); + if(!this->members_.m_map){ + this->priv_initialize_map(0); + pos = this->begin(); + } + + const difference_type elemsbefore = pos - this->members_.m_start; + size_type length = this->size(); + if (elemsbefore < static_cast(length / 2)) { + iterator new_start = this->priv_reserve_elements_at_front(n); + iterator old_start = this->members_.m_start; + pos = this->members_.m_start + elemsbefore; + if (elemsbefore >= difference_type(n)) { + iterator start_n = this->members_.m_start + difference_type(n); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(this->members_.m_start, start_n, new_start); + this->members_.m_start = new_start; + BOOST_CONTAINER_MOVE_NAMESPACE::move(start_n, pos, old_start); + interf.copy_all_to(pos - difference_type(n)); + } + else { + difference_type mid_count = (difference_type(n) - elemsbefore); + iterator mid_start = old_start - mid_count; + interf.uninitialized_copy_some_and_update(mid_start, mid_count, true); + this->members_.m_start = mid_start; + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(old_start, pos, new_start); + this->members_.m_start = new_start; + interf.copy_all_to(old_start); + } + } + else { + iterator new_finish = this->priv_reserve_elements_at_back(n); + iterator old_finish = this->members_.m_finish; + const difference_type elemsafter = + difference_type(length) - elemsbefore; + pos = this->members_.m_finish - elemsafter; + if (elemsafter >= difference_type(n)) { + iterator finish_n = this->members_.m_finish - difference_type(n); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(finish_n, this->members_.m_finish, this->members_.m_finish); + this->members_.m_finish = new_finish; + BOOST_CONTAINER_MOVE_NAMESPACE::move_backward(pos, finish_n, old_finish); + interf.copy_all_to(pos); + } + else { + interf.uninitialized_copy_some_and_update(old_finish, elemsafter, false); + this->members_.m_finish += n-elemsafter; + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(pos, old_finish, this->members_.m_finish); + this->members_.m_finish = new_finish; + interf.copy_all_to(pos); + } + } + } + + void priv_fill_insert(const_iterator pos, size_type n, const value_type& x) + { + typedef constant_iterator c_it; + this->insert(pos, c_it(x, n), c_it()); + } + + // Precondition: this->members_.m_start and this->members_.m_finish have already been initialized, + // but none of the deque's elements have yet been constructed. + void priv_fill_initialize(const value_type& value) + { + index_pointer cur; + BOOST_TRY { + for (cur = this->members_.m_start.m_node; cur < this->members_.m_finish.m_node; ++cur){ + std::uninitialized_fill(*cur, *cur + this->s_buffer_size(), value); + } + std::uninitialized_fill(this->members_.m_finish.m_first, this->members_.m_finish.m_cur, value); + } + BOOST_CATCH(...){ + this->priv_destroy_range(this->members_.m_start, iterator(*cur, cur)); + BOOST_RETHROW + } + BOOST_CATCH_END + } + + template + void priv_range_initialize(InpIt first, InpIt last, std::input_iterator_tag) + { + this->priv_initialize_map(0); + BOOST_TRY { + for ( ; first != last; ++first) + this->push_back(*first); + } + BOOST_CATCH(...){ + this->clear(); + BOOST_RETHROW + } + BOOST_CATCH_END + } + + template + void priv_range_initialize(FwdIt first, FwdIt last, std::forward_iterator_tag) + { + size_type n = 0; + n = std::distance(first, last); + this->priv_initialize_map(n); + + index_pointer cur_node; + BOOST_TRY { + for (cur_node = this->members_.m_start.m_node; + cur_node < this->members_.m_finish.m_node; + ++cur_node) { + FwdIt mid = first; + std::advance(mid, this->s_buffer_size()); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(first, mid, *cur_node); + first = mid; + } + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(first, last, this->members_.m_finish.m_first); + } + BOOST_CATCH(...){ + this->priv_destroy_range(this->members_.m_start, iterator(*cur_node, cur_node)); + BOOST_RETHROW + } + BOOST_CATCH_END + } + + // Called only if this->members_.m_finish.m_cur == this->members_.m_finish.m_first. + void priv_pop_back_aux() + { + this->priv_deallocate_node(this->members_.m_finish.m_first); + this->members_.m_finish.priv_set_node(this->members_.m_finish.m_node - 1); + this->members_.m_finish.m_cur = this->members_.m_finish.m_last - 1; + containers_detail::get_pointer(this->members_.m_finish.m_cur)->~value_type(); + } + + // Called only if this->members_.m_start.m_cur == this->members_.m_start.m_last - 1. Note that + // if the deque has at least one element (a precondition for this member + // function), and if this->members_.m_start.m_cur == this->members_.m_start.m_last, then the deque + // must have at least two nodes. + void priv_pop_front_aux() + { + containers_detail::get_pointer(this->members_.m_start.m_cur)->~value_type(); + this->priv_deallocate_node(this->members_.m_start.m_first); + this->members_.m_start.priv_set_node(this->members_.m_start.m_node + 1); + this->members_.m_start.m_cur = this->members_.m_start.m_first; + } + + iterator priv_reserve_elements_at_front(size_type n) + { + size_type vacancies = this->members_.m_start.m_cur - this->members_.m_start.m_first; + if (n > vacancies){ + size_type new_elems = n-vacancies; + size_type new_nodes = (new_elems + this->s_buffer_size() - 1) / + this->s_buffer_size(); + size_type s = (size_type)(this->members_.m_start.m_node - this->members_.m_map); + if (new_nodes > s){ + this->priv_reallocate_map(new_nodes, true); + } + size_type i = 1; + BOOST_TRY { + for (; i <= new_nodes; ++i) + *(this->members_.m_start.m_node - i) = this->priv_allocate_node(); + } + BOOST_CATCH(...) { + for (size_type j = 1; j < i; ++j) + this->priv_deallocate_node(*(this->members_.m_start.m_node - j)); + BOOST_RETHROW + } + BOOST_CATCH_END + } + return this->members_.m_start - difference_type(n); + } + + iterator priv_reserve_elements_at_back(size_type n) + { + size_type vacancies = (this->members_.m_finish.m_last - this->members_.m_finish.m_cur) - 1; + if (n > vacancies){ + size_type new_elems = n - vacancies; + size_type new_nodes = (new_elems + this->s_buffer_size() - 1)/s_buffer_size(); + size_type s = (size_type)(this->members_.m_map_size - (this->members_.m_finish.m_node - this->members_.m_map)); + if (new_nodes + 1 > s){ + this->priv_reallocate_map(new_nodes, false); + } + size_type i; + BOOST_TRY { + for (i = 1; i <= new_nodes; ++i) + *(this->members_.m_finish.m_node + i) = this->priv_allocate_node(); + } + BOOST_CATCH(...) { + for (size_type j = 1; j < i; ++j) + this->priv_deallocate_node(*(this->members_.m_finish.m_node + j)); + BOOST_RETHROW + } + BOOST_CATCH_END + } + return this->members_.m_finish + difference_type(n); + } + + void priv_reallocate_map(size_type nodes_to_add, bool add_at_front) + { + size_type old_num_nodes = this->members_.m_finish.m_node - this->members_.m_start.m_node + 1; + size_type new_num_nodes = old_num_nodes + nodes_to_add; + + index_pointer new_nstart; + if (this->members_.m_map_size > 2 * new_num_nodes) { + new_nstart = this->members_.m_map + (this->members_.m_map_size - new_num_nodes) / 2 + + (add_at_front ? nodes_to_add : 0); + if (new_nstart < this->members_.m_start.m_node) + BOOST_CONTAINER_MOVE_NAMESPACE::move(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart); + else + BOOST_CONTAINER_MOVE_NAMESPACE::move_backward + (this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart + old_num_nodes); + } + else { + size_type new_map_size = + this->members_.m_map_size + containers_detail::max_value(this->members_.m_map_size, nodes_to_add) + 2; + + index_pointer new_map = this->priv_allocate_map(new_map_size); + new_nstart = new_map + (new_map_size - new_num_nodes) / 2 + + (add_at_front ? nodes_to_add : 0); + BOOST_CONTAINER_MOVE_NAMESPACE::move(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart); + this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size); + + this->members_.m_map = new_map; + this->members_.m_map_size = new_map_size; + } + + this->members_.m_start.priv_set_node(new_nstart); + this->members_.m_finish.priv_set_node(new_nstart + old_num_nodes - 1); + } + /// @endcond +}; + +// Nonmember functions. +template +inline bool operator==(const deque& x, + const deque& y) +{ + return x.size() == y.size() && equal(x.begin(), x.end(), y.begin()); +} + +template +inline bool operator<(const deque& x, + const deque& y) +{ + return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); +} + +template +inline bool operator!=(const deque& x, + const deque& y) + { return !(x == y); } + +template +inline bool operator>(const deque& x, + const deque& y) + { return y < x; } + +template +inline bool operator<=(const deque& x, + const deque& y) + { return !(y < x); } + +template +inline bool operator>=(const deque& x, + const deque& y) + { return !(x < y); } + + +template +inline void swap(deque& x, deque& y) +{ x.swap(y); } + +}} + +/// @cond + +namespace boost { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + enum { value = has_trivial_destructor::value }; +}; +*/ +} + +/// @endcond + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif // #ifndef BOOST_CONTAINERS_DEQUE_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/adaptive_node_pool_impl.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/adaptive_node_pool_impl.hpp new file mode 100644 index 00000000..d2c88d91 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/adaptive_node_pool_impl.hpp @@ -0,0 +1,641 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP +#define BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_POOL_COMMON_HPP +#include +#include + +namespace boost { +namespace container { +namespace containers_detail { + +struct hdr_offset_holder +{ + hdr_offset_holder(std::size_t offset = 0) + : hdr_offset(offset) + {} + std::size_t hdr_offset; +}; + +template +struct adaptive_pool_types +{ + typedef VoidPointer void_pointer; + typedef typename bi::make_set_base_hook + < bi::void_pointer + , bi::optimize_size + , bi::constant_time_size + , bi::link_mode >::type multiset_hook_t; + + struct block_info_t + : + public hdr_offset_holder, + public multiset_hook_t + { + typedef typename node_slist::node_slist_t free_nodes_t; + //An intrusive list of free node from this block + free_nodes_t free_nodes; + friend bool operator <(const block_info_t &l, const block_info_t &r) + { +// { return l.free_nodes.size() < r.free_nodes.size(); } + //Let's order blocks first by free nodes and then by address + //so that highest address fully free blocks are deallocated. + //This improves returning memory to the OS (trimming). + const bool is_less = l.free_nodes.size() < r.free_nodes.size(); + const bool is_equal = l.free_nodes.size() == r.free_nodes.size(); + return is_less || (is_equal && (&l < &r)); + } + + friend bool operator ==(const block_info_t &l, const block_info_t &r) + { return &l == &r; } + }; + typedef typename bi::make_multiset + >::type block_multiset_t; +}; + + +inline std::size_t calculate_alignment + ( std::size_t overhead_percent, std::size_t real_node_size + , std::size_t hdr_size, std::size_t hdr_offset_size, std::size_t payload_per_allocation) +{ + //to-do: handle real_node_size != node_size + const std::size_t divisor = overhead_percent*real_node_size; + const std::size_t dividend = hdr_offset_size*100; + std::size_t elements_per_subblock = (dividend - 1)/divisor + 1; + std::size_t candidate_power_of_2 = + upper_power_of_2(elements_per_subblock*real_node_size + hdr_offset_size); + bool overhead_satisfied = false; + //Now calculate the wors-case overhead for a subblock + const std::size_t max_subblock_overhead = hdr_size + payload_per_allocation; + while(!overhead_satisfied){ + elements_per_subblock = (candidate_power_of_2 - max_subblock_overhead)/real_node_size; + const std::size_t overhead_size = candidate_power_of_2 - elements_per_subblock*real_node_size; + if(overhead_size*100/candidate_power_of_2 < overhead_percent){ + overhead_satisfied = true; + } + else{ + candidate_power_of_2 <<= 1; + } + } + return candidate_power_of_2; +} + +inline void calculate_num_subblocks + (std::size_t alignment, std::size_t real_node_size, std::size_t elements_per_block + , std::size_t &num_subblocks, std::size_t &real_num_node, std::size_t overhead_percent + , std::size_t hdr_size, std::size_t hdr_offset_size, std::size_t payload_per_allocation) +{ + std::size_t elements_per_subblock = (alignment - hdr_offset_size)/real_node_size; + std::size_t possible_num_subblock = (elements_per_block - 1)/elements_per_subblock + 1; + std::size_t hdr_subblock_elements = (alignment - hdr_size - payload_per_allocation)/real_node_size; + while(((possible_num_subblock-1)*elements_per_subblock + hdr_subblock_elements) < elements_per_block){ + ++possible_num_subblock; + } + elements_per_subblock = (alignment - hdr_offset_size)/real_node_size; + bool overhead_satisfied = false; + while(!overhead_satisfied){ + const std::size_t total_data = (elements_per_subblock*(possible_num_subblock-1) + hdr_subblock_elements)*real_node_size; + const std::size_t total_size = alignment*possible_num_subblock; + if((total_size - total_data)*100/total_size < overhead_percent){ + overhead_satisfied = true; + } + else{ + ++possible_num_subblock; + } + } + num_subblocks = possible_num_subblock; + real_num_node = (possible_num_subblock-1)*elements_per_subblock + hdr_subblock_elements; +} + +template +class private_adaptive_node_pool_impl +{ + //Non-copyable + private_adaptive_node_pool_impl(); + private_adaptive_node_pool_impl(const private_adaptive_node_pool_impl &); + private_adaptive_node_pool_impl &operator=(const private_adaptive_node_pool_impl &); + typedef private_adaptive_node_pool_impl this_type; + + typedef typename SegmentManagerBase::void_pointer void_pointer; + static const std::size_t PayloadPerAllocation = SegmentManagerBase::PayloadPerAllocation; + typedef bool_ IsAlignOnly; + typedef true_ AlignOnlyTrue; + typedef false_ AlignOnlyFalse; + + public: + typedef typename node_slist::node_t node_t; + typedef typename node_slist::node_slist_t free_nodes_t; + typedef typename SegmentManagerBase::multiallocation_chain multiallocation_chain; + + private: + typedef typename adaptive_pool_types::block_info_t block_info_t; + typedef typename adaptive_pool_types::block_multiset_t block_multiset_t; + typedef typename block_multiset_t::iterator block_iterator; + + static const std::size_t MaxAlign = alignment_of::value; + static const std::size_t HdrSize = ((sizeof(block_info_t)-1)/MaxAlign+1)*MaxAlign; + static const std::size_t HdrOffsetSize = ((sizeof(hdr_offset_holder)-1)/MaxAlign+1)*MaxAlign; + + + public: + //!Segment manager typedef + typedef SegmentManagerBase segment_manager_base_type; + + //!Constructor from a segment manager. Never throws + private_adaptive_node_pool_impl + ( segment_manager_base_type *segment_mngr_base + , std::size_t node_size + , std::size_t nodes_per_block + , std::size_t max_free_blocks + , unsigned char overhead_percent + ) + : m_max_free_blocks(max_free_blocks) + , m_real_node_size(lcm(node_size, std::size_t(alignment_of::value))) + //Round the size to a power of two value. + //This is the total memory size (including payload) that we want to + //allocate from the general-purpose allocator + , m_real_block_alignment + (AlignOnly ? + upper_power_of_2(HdrSize + m_real_node_size*nodes_per_block) : + calculate_alignment( overhead_percent, m_real_node_size + , HdrSize, HdrOffsetSize, PayloadPerAllocation)) + //This is the real number of nodes per block + , m_num_subblocks(0) + , m_real_num_node(AlignOnly ? (m_real_block_alignment - PayloadPerAllocation - HdrSize)/m_real_node_size : 0) + //General purpose allocator + , mp_segment_mngr_base(segment_mngr_base) + , m_block_multiset() + , m_totally_free_blocks(0) + { + if(!AlignOnly){ + calculate_num_subblocks + ( m_real_block_alignment + , m_real_node_size + , nodes_per_block + , m_num_subblocks + , m_real_num_node + , overhead_percent + , HdrSize + , HdrOffsetSize + , PayloadPerAllocation); + } + } + + //!Destructor. Deallocates all allocated blocks. Never throws + ~private_adaptive_node_pool_impl() + { priv_clear(); } + + std::size_t get_real_num_node() const + { return m_real_num_node; } + + //!Returns the segment manager. Never throws + segment_manager_base_type* get_segment_manager_base()const + { return containers_detail::get_pointer(mp_segment_mngr_base); } + + //!Allocates array of count elements. Can throw + void *allocate_node() + { + priv_invariants(); + //If there are no free nodes we allocate a new block + if (m_block_multiset.empty()){ + priv_alloc_block(1); + } + //We take the first free node the multiset can't be empty + return priv_take_first_node(); + } + + //!Deallocates an array pointed by ptr. Never throws + void deallocate_node(void *pElem) + { + multiallocation_chain chain; + chain.push_front(void_pointer(pElem)); + this->priv_reinsert_nodes_in_block(chain, 1); + //Update free block count< + if(m_totally_free_blocks > m_max_free_blocks){ + this->priv_deallocate_free_blocks(m_max_free_blocks); + } + priv_invariants(); + } + + //!Allocates n nodes. + //!Can throw + multiallocation_chain allocate_nodes(const std::size_t n) + { + multiallocation_chain chain; + std::size_t i = 0; + try{ + priv_invariants(); + while(i != n){ + //If there are no free nodes we allocate all needed blocks + if (m_block_multiset.empty()){ + priv_alloc_block(((n - i) - 1)/m_real_num_node + 1); + } + free_nodes_t &free_nodes = m_block_multiset.begin()->free_nodes; + const std::size_t free_nodes_count_before = free_nodes.size(); + if(free_nodes_count_before == m_real_num_node){ + --m_totally_free_blocks; + } + const std::size_t num_elems = ((n-i) < free_nodes_count_before) ? (n-i) : free_nodes_count_before; + for(std::size_t j = 0; j != num_elems; ++j){ + void *new_node = &free_nodes.front(); + free_nodes.pop_front(); + chain.push_back(new_node); + } + + if(free_nodes.empty()){ + m_block_multiset.erase(m_block_multiset.begin()); + } + i += num_elems; + } + } + catch(...){ + this->deallocate_nodes(BOOST_CONTAINER_MOVE_NAMESPACE::move(chain)); + throw; + } + priv_invariants(); + return BOOST_CONTAINER_MOVE_NAMESPACE::move(chain); + } + + //!Deallocates a linked list of nodes. Never throws + void deallocate_nodes(multiallocation_chain nodes) + { + this->priv_reinsert_nodes_in_block(nodes, nodes.size()); + if(m_totally_free_blocks > m_max_free_blocks){ + this->priv_deallocate_free_blocks(m_max_free_blocks); + } + } + + void deallocate_free_blocks() + { this->priv_deallocate_free_blocks(0); } + + std::size_t num_free_nodes() + { + typedef typename block_multiset_t::const_iterator citerator; + std::size_t count = 0; + citerator it (m_block_multiset.begin()), itend(m_block_multiset.end()); + for(; it != itend; ++it){ + count += it->free_nodes.size(); + } + return count; + } + + void swap(private_adaptive_node_pool_impl &other) + { + BOOST_ASSERT(m_max_free_blocks == other.m_max_free_blocks); + BOOST_ASSERT(m_real_node_size == other.m_real_node_size); + BOOST_ASSERT(m_real_block_alignment == other.m_real_block_alignment); + BOOST_ASSERT(m_real_num_node == other.m_real_num_node); + std::swap(mp_segment_mngr_base, other.mp_segment_mngr_base); + std::swap(m_totally_free_blocks, other.m_totally_free_blocks); + m_block_multiset.swap(other.m_block_multiset); + } + + //Deprecated, use deallocate_free_blocks + void deallocate_free_chunks() + { this->priv_deallocate_free_blocks(0); } + + private: + void priv_deallocate_free_blocks(std::size_t max_free_blocks) + { + priv_invariants(); + //Now check if we've reached the free nodes limit + //and check if we have free blocks. If so, deallocate as much + //as we can to stay below the limit + for( block_iterator itend = m_block_multiset.end() + ; m_totally_free_blocks > max_free_blocks + ; --m_totally_free_blocks + ){ + BOOST_ASSERT(!m_block_multiset.empty()); + block_iterator it = itend; + --it; + BOOST_ASSERT(it->free_nodes.size() == m_real_num_node); + m_block_multiset.erase_and_dispose(it, block_destroyer(this)); + } + } + + void priv_reinsert_nodes_in_block(multiallocation_chain &chain, std::size_t n) + { + block_iterator block_it(m_block_multiset.end()); + while(n--){ + void *pElem = containers_detail::get_pointer(chain.front()); + chain.pop_front(); + priv_invariants(); + block_info_t *block_info = this->priv_block_from_node(pElem); + BOOST_ASSERT(block_info->free_nodes.size() < m_real_num_node); + //We put the node at the beginning of the free node list + node_t * to_deallocate = static_cast(pElem); + block_info->free_nodes.push_front(*to_deallocate); + + block_iterator this_block(block_multiset_t::s_iterator_to(*block_info)); + block_iterator next_block(this_block); + ++next_block; + + //Cache the free nodes from the block + std::size_t this_block_free_nodes = this_block->free_nodes.size(); + + if(this_block_free_nodes == 1){ + m_block_multiset.insert(m_block_multiset.begin(), *block_info); + } + else{ + block_iterator next_block(this_block); + ++next_block; + if(next_block != block_it){ + std::size_t next_free_nodes = next_block->free_nodes.size(); + if(this_block_free_nodes > next_free_nodes){ + //Now move the block to the new position + m_block_multiset.erase(this_block); + m_block_multiset.insert(*block_info); + } + } + } + //Update free block count + if(this_block_free_nodes == m_real_num_node){ + ++m_totally_free_blocks; + } + priv_invariants(); + } + } + + node_t *priv_take_first_node() + { + BOOST_ASSERT(m_block_multiset.begin() != m_block_multiset.end()); + //We take the first free node the multiset can't be empty + free_nodes_t &free_nodes = m_block_multiset.begin()->free_nodes; + node_t *first_node = &free_nodes.front(); + const std::size_t free_nodes_count = free_nodes.size(); + BOOST_ASSERT(0 != free_nodes_count); + free_nodes.pop_front(); + if(free_nodes_count == 1){ + m_block_multiset.erase(m_block_multiset.begin()); + } + else if(free_nodes_count == m_real_num_node){ + --m_totally_free_blocks; + } + priv_invariants(); + return first_node; + } + + class block_destroyer; + friend class block_destroyer; + + class block_destroyer + { + public: + block_destroyer(const this_type *impl) + : mp_impl(impl) + {} + + void operator()(typename block_multiset_t::pointer to_deallocate) + { return this->do_destroy(to_deallocate, IsAlignOnly()); } + + private: + void do_destroy(typename block_multiset_t::pointer to_deallocate, AlignOnlyTrue) + { + std::size_t free_nodes = to_deallocate->free_nodes.size(); + (void)free_nodes; + BOOST_ASSERT(free_nodes == mp_impl->m_real_num_node); + mp_impl->mp_segment_mngr_base->deallocate(to_deallocate); + } + + void do_destroy(typename block_multiset_t::pointer to_deallocate, AlignOnlyFalse) + { + std::size_t free_nodes = to_deallocate->free_nodes.size(); + (void)free_nodes; + BOOST_ASSERT(free_nodes == mp_impl->m_real_num_node); + BOOST_ASSERT(0 == to_deallocate->hdr_offset); + hdr_offset_holder *hdr_off_holder = mp_impl->priv_first_subblock_from_block(containers_detail::get_pointer(to_deallocate)); + mp_impl->mp_segment_mngr_base->deallocate(hdr_off_holder); + } + + const this_type *mp_impl; + }; + + //This macro will activate invariant checking. Slow, but helpful for debugging the code. + //#define BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS + void priv_invariants() + #ifdef BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS + #undef BOOST_CONTAINER_ADAPTIVE_NODE_POOL_CHECK_INVARIANTS + { + //We iterate through the block tree to free the memory + block_iterator it(m_block_multiset.begin()), + itend(m_block_multiset.end()), to_deallocate; + if(it != itend){ + for(++it; it != itend; ++it){ + block_iterator prev(it); + --prev; + std::size_t sp = prev->free_nodes.size(), + si = it->free_nodes.size(); + BOOST_ASSERT(sp <= si); + (void)sp; (void)si; + } + } + //Check that the total free nodes are correct + it = m_block_multiset.begin(); + itend = m_block_multiset.end(); + std::size_t total_free_nodes = 0; + for(; it != itend; ++it){ + total_free_nodes += it->free_nodes.size(); + } + BOOST_ASSERT(total_free_nodes >= m_totally_free_blocks*m_real_num_node); + + //Check that the total totally free blocks are correct + it = m_block_multiset.begin(); + itend = m_block_multiset.end(); + total_free = 0; + for(; it != itend; ++it){ + total_free += it->free_nodes.size() == m_real_num_node; + } + BOOST_ASSERT(total_free >= m_totally_free_blocks); + + if(!AlignOnly){ + //Check that header offsets are correct + it = m_block_multiset.begin(); + for(; it != itend; ++it){ + hdr_offset_holder *hdr_off_holder = priv_first_subblock_from_block(&*it); + for(std::size_t i = 0, max = m_num_subblocks; i < max; ++i){ + BOOST_ASSERT(hdr_off_holder->hdr_offset == std::size_t(reinterpret_cast(&*it)- reinterpret_cast(hdr_off_holder))); + BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1))); + BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1))); + hdr_off_holder = reinterpret_cast(reinterpret_cast(hdr_off_holder) + m_real_block_alignment); + } + } + } + } + #else + {} //empty + #endif + + //!Deallocates all used memory. Never throws + void priv_clear() + { + #ifndef NDEBUG + block_iterator it = m_block_multiset.begin(); + block_iterator itend = m_block_multiset.end(); + std::size_t num_free_nodes = 0; + for(; it != itend; ++it){ + //Check for memory leak + BOOST_ASSERT(it->free_nodes.size() == m_real_num_node); + ++num_free_nodes; + } + BOOST_ASSERT(num_free_nodes == m_totally_free_blocks); + #endif + //Check for memory leaks + priv_invariants(); + m_block_multiset.clear_and_dispose(block_destroyer(this)); + m_totally_free_blocks = 0; + } + + block_info_t *priv_block_from_node(void *node, AlignOnlyFalse) const + { + hdr_offset_holder *hdr_off_holder = + reinterpret_cast((std::size_t)node & std::size_t(~(m_real_block_alignment - 1))); + BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1))); + BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1))); + block_info_t *block = reinterpret_cast + (reinterpret_cast(hdr_off_holder) + hdr_off_holder->hdr_offset); + BOOST_ASSERT(block->hdr_offset == 0); + return block; + } + + block_info_t *priv_block_from_node(void *node, AlignOnlyTrue) const + { + return (block_info_t *)((std::size_t)node & std::size_t(~(m_real_block_alignment - 1))); + } + + block_info_t *priv_block_from_node(void *node) const + { return priv_block_from_node(node, IsAlignOnly()); } + + hdr_offset_holder *priv_first_subblock_from_block(block_info_t *block) const + { + hdr_offset_holder *hdr_off_holder = reinterpret_cast + (reinterpret_cast(block) - (m_num_subblocks-1)*m_real_block_alignment); + BOOST_ASSERT(hdr_off_holder->hdr_offset == std::size_t(reinterpret_cast(block) - reinterpret_cast(hdr_off_holder))); + BOOST_ASSERT(0 == ((std::size_t)hdr_off_holder & (m_real_block_alignment - 1))); + BOOST_ASSERT(0 == (hdr_off_holder->hdr_offset & (m_real_block_alignment - 1))); + return hdr_off_holder; + } + + //!Allocates a several blocks of nodes. Can throw + void priv_alloc_block(std::size_t n, AlignOnlyTrue) + { + std::size_t real_block_size = m_real_block_alignment - PayloadPerAllocation; + for(std::size_t i = 0; i != n; ++i){ + //We allocate a new NodeBlock and put it the last + //element of the tree + char *mem_address = static_cast + (mp_segment_mngr_base->allocate_aligned(real_block_size, m_real_block_alignment)); + if(!mem_address) throw std::bad_alloc(); + ++m_totally_free_blocks; + block_info_t *c_info = new(mem_address)block_info_t; + m_block_multiset.insert(m_block_multiset.end(), *c_info); + + mem_address += HdrSize; + //We initialize all Nodes in Node Block to insert + //them in the free Node list + typename free_nodes_t::iterator prev_insert_pos = c_info->free_nodes.before_begin(); + for(std::size_t i = 0; i < m_real_num_node; ++i){ + prev_insert_pos = c_info->free_nodes.insert_after(prev_insert_pos, *(node_t*)mem_address); + mem_address += m_real_node_size; + } + } + } + + void priv_alloc_block(std::size_t n, AlignOnlyFalse) + { + std::size_t real_block_size = m_real_block_alignment*m_num_subblocks - PayloadPerAllocation; + std::size_t elements_per_subblock = (m_real_block_alignment - HdrOffsetSize)/m_real_node_size; + std::size_t hdr_subblock_elements = (m_real_block_alignment - HdrSize - PayloadPerAllocation)/m_real_node_size; + + for(std::size_t i = 0; i != n; ++i){ + //We allocate a new NodeBlock and put it the last + //element of the tree + char *mem_address = static_cast + (mp_segment_mngr_base->allocate_aligned(real_block_size, m_real_block_alignment)); + if(!mem_address) throw std::bad_alloc(); + ++m_totally_free_blocks; + + //First initialize header information on the last subblock + char *hdr_addr = mem_address + m_real_block_alignment*(m_num_subblocks-1); + block_info_t *c_info = new(hdr_addr)block_info_t; + //Some structural checks + BOOST_ASSERT(static_cast(&static_cast(c_info)->hdr_offset) == + static_cast(c_info)); + typename free_nodes_t::iterator prev_insert_pos = c_info->free_nodes.before_begin(); + for( std::size_t subblock = 0, maxsubblock = m_num_subblocks - 1 + ; subblock < maxsubblock + ; ++subblock, mem_address += m_real_block_alignment){ + //Initialize header offset mark + new(mem_address) hdr_offset_holder(std::size_t(hdr_addr - mem_address)); + char *pNode = mem_address + HdrOffsetSize; + for(std::size_t i = 0; i < elements_per_subblock; ++i){ + prev_insert_pos = c_info->free_nodes.insert_after(prev_insert_pos, *new (pNode) node_t); + pNode += m_real_node_size; + } + } + { + char *pNode = hdr_addr + HdrSize; + //We initialize all Nodes in Node Block to insert + //them in the free Node list + for(std::size_t i = 0; i < hdr_subblock_elements; ++i){ + prev_insert_pos = c_info->free_nodes.insert_after(prev_insert_pos, *new (pNode) node_t); + pNode += m_real_node_size; + } + } + //Insert the block after the free node list is full + m_block_multiset.insert(m_block_multiset.end(), *c_info); + } + } + + //!Allocates a block of nodes. Can throw std::bad_alloc + void priv_alloc_block(std::size_t n) + { return priv_alloc_block(n, IsAlignOnly()); } + + private: + typedef typename boost::pointer_to_other + ::type segment_mngr_base_ptr_t; + const std::size_t m_max_free_blocks; + const std::size_t m_real_node_size; + //Round the size to a power of two value. + //This is the total memory size (including payload) that we want to + //allocate from the general-purpose allocator + const std::size_t m_real_block_alignment; + std::size_t m_num_subblocks; + //This is the real number of nodes per block + //const + std::size_t m_real_num_node; + segment_mngr_base_ptr_t mp_segment_mngr_base; //Segment manager + block_multiset_t m_block_multiset; //Intrusive block list + std::size_t m_totally_free_blocks; //Free blocks +}; + +} //namespace containers_detail { +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/advanced_insert_int.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/advanced_insert_int.hpp new file mode 100644 index 00000000..bb9126d6 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/advanced_insert_int.hpp @@ -0,0 +1,385 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_ADVANCED_INSERT_INT_HPP +#define BOOST_CONTAINERS_ADVANCED_INSERT_INT_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include //std::iterator_traits +#include //placement new +#include + +namespace boost { namespace container { namespace containers_detail { + +//This class will be interface for operations dependent on FwdIt types used advanced_insert_aux_impl +template +struct advanced_insert_aux_int +{ + typedef typename std::iterator_traits::difference_type difference_type; + virtual void copy_all_to(Iterator p) = 0; + virtual void uninitialized_copy_all_to(Iterator p) = 0; + virtual void uninitialized_copy_some_and_update(Iterator pos, difference_type division_count, bool first) = 0; + virtual void copy_some_and_update(Iterator pos, difference_type division_count, bool first) = 0; + virtual ~advanced_insert_aux_int() {} +}; + +//This class template will adapt each FwIt types to advanced_insert_aux_int +template +struct advanced_insert_aux_proxy + : public advanced_insert_aux_int +{ + typedef typename advanced_insert_aux_int::difference_type difference_type; + advanced_insert_aux_proxy(FwdIt first, FwdIt last) + : first_(first), last_(last) + {} + + virtual ~advanced_insert_aux_proxy() + {} + + virtual void copy_all_to(Iterator p) + { ::BOOST_CONTAINER_MOVE_NAMESPACE::copy_or_move(first_, last_, p); } + + virtual void uninitialized_copy_all_to(Iterator p) + { ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(first_, last_, p); } + + virtual void uninitialized_copy_some_and_update(Iterator pos, difference_type division_count, bool first_n) + { + FwdIt mid = first_; + std::advance(mid, division_count); + if(first_n){ + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(first_, mid, pos); + first_ = mid; + } + else{ + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(mid, last_, pos); + last_ = mid; + } + } + + virtual void copy_some_and_update(Iterator pos, difference_type division_count, bool first_n) + { + FwdIt mid = first_; + std::advance(mid, division_count); + if(first_n){ + ::BOOST_CONTAINER_MOVE_NAMESPACE::copy_or_move(first_, mid, pos); + first_ = mid; + } + else{ + ::BOOST_CONTAINER_MOVE_NAMESPACE::copy_or_move(mid, last_, pos); + last_ = mid; + } + } + + FwdIt first_, last_; +}; + +//This class template will adapt each FwIt types to advanced_insert_aux_int +template +struct default_construct_aux_proxy + : public advanced_insert_aux_int +{ + typedef typename advanced_insert_aux_int::difference_type difference_type; + default_construct_aux_proxy(SizeType count) + : count_(count) + {} + + void uninitialized_copy_impl(Iterator p, const SizeType n) + { + BOOST_ASSERT(n <= count_); + Iterator orig_p = p; + SizeType i = 0; + try{ + for(; i < n; ++i, ++p){ + new(containers_detail::get_pointer(&*p))T(); + } + } + catch(...){ + while(i--){ + containers_detail::get_pointer(&*orig_p++)->~T(); + } + throw; + } + count_ -= n; + } + + virtual ~default_construct_aux_proxy() + {} + + virtual void copy_all_to(Iterator) + { //This should never be called with any count + BOOST_ASSERT(count_ == 0); + } + + virtual void uninitialized_copy_all_to(Iterator p) + { this->uninitialized_copy_impl(p, count_); } + + virtual void uninitialized_copy_some_and_update(Iterator pos, difference_type division_count, bool first_n) + { + SizeType new_count; + if(first_n){ + new_count = division_count; + } + else{ + BOOST_ASSERT(difference_type(count_)>= division_count); + new_count = count_ - division_count; + } + this->uninitialized_copy_impl(pos, new_count); + } + + virtual void copy_some_and_update(Iterator , difference_type division_count, bool first_n) + { + BOOST_ASSERT(count_ == 0); + SizeType new_count; + if(first_n){ + new_count = division_count; + } + else{ + BOOST_ASSERT(difference_type(count_)>= division_count); + new_count = count_ - division_count; + } + //This function should never called with a count different to zero + BOOST_ASSERT(new_count == 0); + (void)new_count; + } + + SizeType count_; +}; + +}}} //namespace boost { namespace container { namespace containers_detail { + +#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + +#include INCLUDE_BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_STORED_REF_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include +//#include //For debugging purposes + +namespace boost { +namespace container { +namespace containers_detail { + +//This class template will adapt each FwIt types to advanced_insert_aux_int +template +struct advanced_insert_aux_emplace + : public advanced_insert_aux_int +{ + typedef typename advanced_insert_aux_int::difference_type difference_type; + typedef typename build_number_seq::type index_tuple_t; + + explicit advanced_insert_aux_emplace(Args&&... args) + : args_(args...) + , used_(false) + {} + + ~advanced_insert_aux_emplace() + {} + + virtual void copy_all_to(Iterator p) + { this->priv_copy_all_to(index_tuple_t(), p); } + + virtual void uninitialized_copy_all_to(Iterator p) + { this->priv_uninitialized_copy_all_to(index_tuple_t(), p); } + + virtual void uninitialized_copy_some_and_update(Iterator p, difference_type division_count, bool first_n) + { this->priv_uninitialized_copy_some_and_update(index_tuple_t(), p, division_count, first_n); } + + virtual void copy_some_and_update(Iterator p, difference_type division_count, bool first_n) + { this->priv_copy_some_and_update(index_tuple_t(), p, division_count, first_n); } + + private: + template + void priv_copy_all_to(const index_tuple&, Iterator p) + { + if(!used_){ + *p = BOOST_CONTAINER_MOVE_NAMESPACE::move(T (::boost::container::containers_detail::stored_ref::forward(get(args_))...)); + used_ = true; + } + } + + template + void priv_uninitialized_copy_all_to(const index_tuple&, Iterator p) + { + if(!used_){ + new(containers_detail::get_pointer(&*p))T(::boost::container::containers_detail::stored_ref::forward(get(args_))...); + used_ = true; + } + } + + template + void priv_uninitialized_copy_some_and_update(const index_tuple&, Iterator p, difference_type division_count, bool first_n) + { + BOOST_ASSERT(division_count <=1); + if((first_n && division_count == 1) || (!first_n && division_count == 0)){ + if(!used_){ + new(containers_detail::get_pointer(&*p))T(::boost::container::containers_detail::stored_ref::forward(get(args_))...); + used_ = true; + } + } + } + + template + void priv_copy_some_and_update(const index_tuple&, Iterator p, difference_type division_count, bool first_n) + { + BOOST_ASSERT(division_count <=1); + if((first_n && division_count == 1) || (!first_n && division_count == 0)){ + if(!used_){ + *p = BOOST_CONTAINER_MOVE_NAMESPACE::move(T(::boost::container::containers_detail::stored_ref::forward(get(args_))...)); + used_ = true; + } + } + } + tuple args_; + bool used_; +}; + +}}} //namespace boost { namespace container { namespace containers_detail { + +#else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP + +namespace boost { +namespace container { +namespace containers_detail { + +//This class template will adapt each FwIt types to advanced_insert_aux_int +template +struct advanced_insert_aux_emplace + : public advanced_insert_aux_int +{ + typedef typename advanced_insert_aux_int::difference_type difference_type; + advanced_insert_aux_emplace() + : used_(false) + {} + + ~advanced_insert_aux_emplace() + {} + + virtual void copy_all_to(Iterator p) + { + if(!used_){ + value_initv; + *p = BOOST_CONTAINER_MOVE_NAMESPACE::move(v.m_t); + used_ = true; + } + } + + virtual void uninitialized_copy_all_to(Iterator p) + { + if(!used_){ + new(containers_detail::get_pointer(&*p))T(); + used_ = true; + } + } + + virtual void uninitialized_copy_some_and_update(Iterator p, difference_type division_count, bool first_n) + { + BOOST_ASSERT(division_count <=1); + if((first_n && division_count == 1) || (!first_n && division_count == 0)){ + if(!used_){ + new(containers_detail::get_pointer(&*p))T(); + used_ = true; + } + } + } + + virtual void copy_some_and_update(Iterator p, difference_type division_count, bool first_n) + { + BOOST_ASSERT(division_count <=1); + if((first_n && division_count == 1) || (!first_n && division_count == 0)){ + if(!used_){ + value_initv; + *p = BOOST_CONTAINER_MOVE_NAMESPACE::move(v.m_t); + used_ = true; + } + } + } + private: + bool used_; +}; + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + struct BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + : public advanced_insert_aux_int \ + { \ + typedef typename advanced_insert_aux_int::difference_type difference_type; \ + \ + BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + ( BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _) ) \ + : used_(false), BOOST_PP_ENUM(n, BOOST_CONTAINERS_AUX_PARAM_INIT, _) {} \ + \ + virtual void copy_all_to(Iterator p) \ + { \ + if(!used_){ \ + T v(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_MEMBER_FORWARD, _)); \ + *p = BOOST_CONTAINER_MOVE_NAMESPACE::move(v); \ + used_ = true; \ + } \ + } \ + \ + virtual void uninitialized_copy_all_to(Iterator p) \ + { \ + if(!used_){ \ + new(containers_detail::get_pointer(&*p))T \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_MEMBER_FORWARD, _)); \ + used_ = true; \ + } \ + } \ + \ + virtual void uninitialized_copy_some_and_update \ + (Iterator p, difference_type division_count, bool first_n) \ + { \ + BOOST_ASSERT(division_count <=1); \ + if((first_n && division_count == 1) || (!first_n && division_count == 0)){ \ + if(!used_){ \ + new(containers_detail::get_pointer(&*p))T \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_MEMBER_FORWARD, _)); \ + used_ = true; \ + } \ + } \ + } \ + \ + virtual void copy_some_and_update \ + (Iterator p, difference_type division_count, bool first_n) \ + { \ + BOOST_ASSERT(division_count <=1); \ + if((first_n && division_count == 1) || (!first_n && division_count == 0)){ \ + if(!used_){ \ + T v(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_MEMBER_FORWARD, _)); \ + *p = BOOST_CONTAINER_MOVE_NAMESPACE::move(v); \ + used_ = true; \ + } \ + } \ + } \ + \ + bool used_; \ + BOOST_PP_REPEAT(n, BOOST_CONTAINERS_AUX_PARAM_DEFINE, _) \ + }; \ +//! + +#define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) +#include BOOST_PP_LOCAL_ITERATE() + +}}} //namespace boost { namespace container { namespace containers_detail { + +#endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_ADVANCED_INSERT_INT_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/algorithms.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/algorithms.hpp new file mode 100644 index 00000000..a028a5e2 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/algorithms.hpp @@ -0,0 +1,215 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_ALGORITHMS_HPP +#define BOOST_CONTAINERS_DETAIL_ALGORITHMS_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include +#include +#include +#include + +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP + + +#include + +namespace boost { +namespace container { + +#if defined(BOOST_NO_RVALUE_REFERENCES) +template +struct has_own_construct_from_it +{ + static const bool value = false; +}; + +namespace containers_detail { + +template +inline void construct_in_place_impl(T* dest, const InpIt &source, containers_detail::true_) +{ + T::construct(dest, *source); +} + +template +inline void construct_in_place_impl(T* dest, const InpIt &source, containers_detail::false_) +{ + new((void*)dest)T(*source); +} + +} //namespace containers_detail { + +template +inline void construct_in_place(T* dest, InpIt source) +{ + typedef containers_detail::bool_::value> boolean_t; + containers_detail::construct_in_place_impl(dest, source, boolean_t()); +} + +#else +template +inline void construct_in_place(T* dest, InpIt source) +{ ::new((void*)dest)T(*source); } +#endif + +template +inline void construct_in_place(T *dest, default_construct_iterator) +{ + ::new((void*)dest)T(); +} + +template +inline void construct_in_place(T *dest, emplace_iterator ei) +{ + ei.construct_in_place(dest); +} + +template +struct optimize_assign +{ + static const bool value = false; +}; + +template +struct optimize_assign +{ + static const bool value = boost::has_trivial_assign::value; +}; + +template +struct optimize_assign + : public optimize_assign +{}; + +template +struct optimize_copy +{ + static const bool value = false; +}; + +template +struct optimize_copy +{ + static const bool value = boost::has_trivial_copy::value; +}; + +template +struct optimize_copy + : public optimize_copy +{}; + +template inline +OutIt copy_n_dispatch(InIt first, typename std::iterator_traits::difference_type length, OutIt dest, containers_detail::bool_) +{ + for (; length--; ++dest, ++first) + *dest = *first; + return dest; +} + +template inline +T *copy_n_dispatch(const T *first, typename std::iterator_traits::difference_type length, T *dest, containers_detail::bool_) +{ + std::size_t size = length*sizeof(T); + return (static_cast(std::memmove(dest, first, size))) + size; +} + +template inline +OutIt copy_n(InIt first, typename std::iterator_traits::difference_type length, OutIt dest) +{ + const bool do_optimized_assign = optimize_assign::value; + return copy_n_dispatch(first, length, dest, containers_detail::bool_()); +} + +template inline +FwdIt uninitialized_copy_n_dispatch + (InIt first, + typename std::iterator_traits::difference_type count, + FwdIt dest, containers_detail::bool_) +{ + typedef typename std::iterator_traits::value_type value_type; + //Save initial destination position + FwdIt dest_init = dest; + typename std::iterator_traits::difference_type new_count = count+1; + + BOOST_TRY{ + //Try to build objects + for (; --new_count; ++dest, ++first){ + construct_in_place(containers_detail::get_pointer(&*dest), first); + } + } + BOOST_CATCH(...){ + //Call destructors + new_count = count - new_count; + for (; new_count--; ++dest_init){ + containers_detail::get_pointer(&*dest_init)->~value_type(); + } + BOOST_RETHROW + } + BOOST_CATCH_END + return dest; +} +template inline +T *uninitialized_copy_n_dispatch(const T *first, typename std::iterator_traits::difference_type length, T *dest, containers_detail::bool_) +{ + std::size_t size = length*sizeof(T); + return (static_cast(std::memmove(dest, first, size))) + size; +} + +template inline +FwdIt uninitialized_copy_n + (InIt first, + typename std::iterator_traits::difference_type count, + FwdIt dest) +{ + const bool do_optimized_copy = optimize_copy::value; + return uninitialized_copy_n_dispatch(first, count, dest, containers_detail::bool_()); +} + +// uninitialized_copy_copy +// Copies [first1, last1) into [result, result + (last1 - first1)), and +// copies [first2, last2) into +// [result + (last1 - first1), result + (last1 - first1) + (last2 - first2)). +template +FwdIt uninitialized_copy_copy + (InpIt1 first1, InpIt1 last1, InpIt2 first2, InpIt2 last2, FwdIt result) +{ + typedef typename std::iterator_traits::value_type value_type; + FwdIt mid = std::uninitialized_copy(first1, last1, result); + BOOST_TRY { + return std::uninitialized_copy(first2, last2, mid); + } + BOOST_CATCH(...){ + for(;result != mid; ++result){ + containers_detail::get_pointer(&*result)->~value_type(); + } + BOOST_RETHROW + } + BOOST_CATCH_END +} + +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_ALGORITHMS_HPP + diff --git a/utils/boost_idb/boost/container/detail/allocation_type.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/allocation_type.hpp similarity index 80% rename from utils/boost_idb/boost/container/detail/allocation_type.hpp rename to utils/boost_idb/boost/interprocess/containers/container/detail/allocation_type.hpp index 59ae9226..88f08ba8 100644 --- a/utils/boost_idb/boost/container/detail/allocation_type.hpp +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/allocation_type.hpp @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,22 +8,22 @@ // /////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_CONTAINER_ALLOCATION_TYPE_HPP -#define BOOST_CONTAINER_ALLOCATION_TYPE_HPP +#ifndef BOOST_CONTAINERS_ALLOCATION_TYPE_HPP +#define BOOST_CONTAINERS_ALLOCATION_TYPE_HPP -#if defined(_MSC_VER) +#if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include "config_begin.hpp" -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP namespace boost { namespace container { /// @cond enum allocation_type_v -{ +{ // constants for allocation commands allocate_new_v = 0x01, expand_fwd_v = 0x02, @@ -49,6 +49,6 @@ static const allocation_type zero_memory = (allocation_type)zero_memory_v } //namespace container { } //namespace boost { -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP -#endif //BOOST_CONTAINER_ALLOCATION_TYPE_HPP +#endif //BOOST_CONTAINERS_ALLOCATION_TYPE_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/config_begin.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/config_begin.hpp new file mode 100644 index 00000000..da16ffa9 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/config_begin.hpp @@ -0,0 +1,145 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#ifndef BOOST_CONTAINERS_CONTAINER_DETAIL_CONFIG_INCLUDED +#define BOOST_CONTAINERS_CONTAINER_DETAIL_CONFIG_INCLUDED +#include + +#define BOOST_CONTAINER_IN_INTERPROCESS +#define BOOST_MOVE_IN_INTERPROCESS + +#ifdef BOOST_MOVE_IN_INTERPROCESS + +#define INCLUDE_BOOST_CONTAINER_MOVE_HPP +#define BOOST_CONTAINER_MOVE_NAMESPACE boost::interprocess + +#else + +#define INCLUDE_BOOST_CONTAINER_MOVE_HPP +#define BOOST_CONTAINER_MOVE_NAMESPACE boost + +#endif + +#ifdef BOOST_CONTAINER_IN_INTERPROCESS + +#define INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#define INCLUDE_BOOST_CONTAINER_DEQUE_HPP +#define INCLUDE_BOOST_CONTAINER_FLAT_MAP_HPP +#define INCLUDE_BOOST_CONTAINER_FLAT_SET_HPP +#define INCLUDE_BOOST_CONTAINER_LIST_HPP +#define INCLUDE_BOOST_CONTAINER_MAP_HPP +#define INCLUDE_BOOST_CONTAINER_SET_HPP +#define INCLUDE_BOOST_CONTAINER_SLIST_HPP +#define INCLUDE_BOOST_CONTAINER_STABLE_VECTOR_HPP +#define INCLUDE_BOOST_CONTAINER_STRING_HPP +#define INCLUDE_BOOST_CONTAINER_VECTOR_HPP +//detail +#define INCLUDE_BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ADVANCED_INSERT_INT_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ALLOCATION_TYPE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_DESTROYERS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_FLAT_TREE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_NODE_ALLOC_HOLDER_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_NODE_POOL_IMPL_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_PAIR_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_POOL_COMMON_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATOR_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_TREE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_STORED_REF_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#else //BOOST_CONTAINER_IN_INTERPROCESS + +#define INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#define INCLUDE_BOOST_CONTAINER_DEQUE_HPP +#define INCLUDE_BOOST_CONTAINER_FLAT_MAP_HPP +#define INCLUDE_BOOST_CONTAINER_FLAT_SET_HPP +#define INCLUDE_BOOST_CONTAINER_LIST_HPP +#define INCLUDE_BOOST_CONTAINER_MAP_HPP +#define INCLUDE_BOOST_CONTAINER_SET_HPP +#define INCLUDE_BOOST_CONTAINER_SLIST_HPP +#define INCLUDE_BOOST_CONTAINER_STABLE_VECTOR_HPP +#define INCLUDE_BOOST_CONTAINER_STRING_HPP +#define INCLUDE_BOOST_CONTAINER_VECTOR_HPP +//detail +#define INCLUDE_BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ADVANCED_INSERT_INT_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ALLOCATION_TYPE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_BEGIN_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_DESTROYERS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_FLAT_TREE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_NODE_ALLOC_HOLDER_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_NODE_POOL_IMPL_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_PAIR_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_POOL_COMMON_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATOR_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_TREE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#define INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#endif //BOOST_CONTAINER_IN_INTERPROCESS + +#endif + +#ifdef BOOST_MSVC + #ifndef _CRT_SECURE_NO_DEPRECATE + #define BOOST_CONTAINERS_DETAIL_CRT_SECURE_NO_DEPRECATE + #define _CRT_SECURE_NO_DEPRECATE + #endif + #pragma warning (push) + #pragma warning (disable : 4702) // unreachable code + #pragma warning (disable : 4706) // assignment within conditional expression + #pragma warning (disable : 4127) // conditional expression is constant + #pragma warning (disable : 4146) // unary minus operator applied to unsigned type, result still unsigned + #pragma warning (disable : 4284) // odd return type for operator-> + #pragma warning (disable : 4244) // possible loss of data + #pragma warning (disable : 4251) // "identifier" : class "type" needs to have dll-interface to be used by clients of class "type2" + #pragma warning (disable : 4267) // conversion from "X" to "Y", possible loss of data + #pragma warning (disable : 4275) // non DLL-interface classkey "identifier" used as base for DLL-interface classkey "identifier" + #pragma warning (disable : 4355) // "this" : used in base member initializer list + #pragma warning (disable : 4503) // "identifier" : decorated name length exceeded, name was truncated + #pragma warning (disable : 4511) // copy constructor could not be generated + #pragma warning (disable : 4512) // assignment operator could not be generated + #pragma warning (disable : 4514) // unreferenced inline removed + #pragma warning (disable : 4521) // Disable "multiple copy constructors specified" + #pragma warning (disable : 4522) // "class" : multiple assignment operators specified + #pragma warning (disable : 4675) // "method" should be declared "static" and have exactly one parameter + #pragma warning (disable : 4710) // function not inlined + #pragma warning (disable : 4711) // function selected for automatic inline expansion + #pragma warning (disable : 4786) // identifier truncated in debug info + #pragma warning (disable : 4996) // "function": was declared deprecated + #pragma warning (disable : 4197) // top-level volatile in cast is ignored + #pragma warning (disable : 4541) // 'typeid' used on polymorphic type 'boost::exception' + // with /GR-; unpredictable behavior may result + #pragma warning (disable : 4673) // throwing '' the following types will not be considered at the catch site + #pragma warning (disable : 4671) // the copy constructor is inaccessible +#endif diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/config_end.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/config_end.hpp new file mode 100644 index 00000000..47383227 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/config_end.hpp @@ -0,0 +1,17 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#if defined BOOST_MSVC + #pragma warning (pop) + #ifdef BOOST_CONTAINERS_DETAIL_CRT_SECURE_NO_DEPRECATE + #undef BOOST_CONTAINERS_DETAIL_CRT_SECURE_NO_DEPRECATE + #undef _CRT_SECURE_NO_DEPRECATE + #endif +#endif + diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/destroyers.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/destroyers.hpp new file mode 100644 index 00000000..25f80436 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/destroyers.hpp @@ -0,0 +1,154 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DESTROYERS_HPP +#define BOOST_CONTAINERS_DESTROYERS_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP + +namespace boost { +namespace container { +namespace containers_detail { + +//!A deleter for scoped_ptr that deallocates the memory +//!allocated for an array of objects using a STL allocator. +template +struct scoped_array_deallocator +{ + typedef typename Allocator::pointer pointer; + typedef typename Allocator::size_type size_type; + + scoped_array_deallocator(pointer p, Allocator& a, size_type length) + : m_ptr(p), m_alloc(a), m_length(length) {} + + ~scoped_array_deallocator() + { if (m_ptr) m_alloc.deallocate(m_ptr, m_length); } + + void release() + { m_ptr = 0; } + + private: + pointer m_ptr; + Allocator& m_alloc; + size_type m_length; +}; + +template +struct null_scoped_array_deallocator +{ + typedef typename Allocator::pointer pointer; + typedef typename Allocator::size_type size_type; + + null_scoped_array_deallocator(pointer, Allocator&, size_type) + {} + + void release() + {} +}; + + +//!A deleter for scoped_ptr that destroys +//!an object using a STL allocator. +template +struct scoped_destructor_n +{ + typedef typename Allocator::pointer pointer; + typedef typename Allocator::value_type value_type; + typedef typename Allocator::size_type size_type; + + pointer m_p; + size_type m_n; + + scoped_destructor_n(pointer p, size_type n) + : m_p(p), m_n(n) + {} + + void release() + { m_p = 0; } + + void increment_size(size_type inc) + { m_n += inc; } + + ~scoped_destructor_n() + { + if(!m_p) return; + value_type *raw_ptr = containers_detail::get_pointer(m_p); + for(std::size_t i = 0; i < m_n; ++i, ++raw_ptr) + raw_ptr->~value_type(); + } +}; + +//!A deleter for scoped_ptr that destroys +//!an object using a STL allocator. +template +struct null_scoped_destructor_n +{ + typedef typename Allocator::pointer pointer; + typedef typename Allocator::size_type size_type; + + null_scoped_destructor_n(pointer, size_type) + {} + + void increment_size(size_type) + {} + + void release() + {} +}; + +template +class allocator_destroyer +{ + typedef typename A::value_type value_type; + typedef containers_detail::integral_constant::value> alloc_version; + typedef containers_detail::integral_constant allocator_v1; + typedef containers_detail::integral_constant allocator_v2; + + private: + A & a_; + + private: + void priv_deallocate(const typename A::pointer &p, allocator_v1) + { a_.deallocate(p, 1); } + + void priv_deallocate(const typename A::pointer &p, allocator_v2) + { a_.deallocate_one(p); } + + public: + allocator_destroyer(A &a) + : a_(a) + {} + + void operator()(const typename A::pointer &p) + { + containers_detail::get_pointer(p)->~value_type(); + priv_deallocate(p, alloc_version()); + } +}; + + +} //namespace containers_detail { +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DESTROYERS_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/flat_tree.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/flat_tree.hpp new file mode 100644 index 00000000..eb69df90 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/flat_tree.hpp @@ -0,0 +1,875 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +//////////////////////////////////////////////////////////////////////////////// +// The Loki Library +// Copyright (c) 2001 by Andrei Alexandrescu +// This code accompanies the book: +// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design +// Patterns Applied". Copyright (c) 2001. Addison-Wesley. +// Permission to use, copy, modify, distribute and sell this software for any +// purpose is hereby granted without fee, provided that the above copyright +// notice appear in all copies and that both that copyright notice and this +// permission notice appear in supporting documentation. +// The author or Addison-Welsey Longman make no representations about the +// suitability of this software for any purpose. It is provided "as is" +// without express or implied warranty. +/////////////////////////////////////////////////////////////////////////////// +// +// Parts of this file come from AssocVector.h file from Loki library +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_FLAT_TREE_HPP +#define BOOST_CONTAINERS_FLAT_TREE_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP + +#include +#include +#include + +#include +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_PAIR_HPP +#include INCLUDE_BOOST_CONTAINER_VECTOR_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_DESTROYERS_HPP + +namespace boost { + +namespace container { + +namespace containers_detail { + +template +class flat_tree_value_compare + : private Compare +{ + typedef Value first_argument_type; + typedef Value second_argument_type; + typedef bool return_type; + public: + flat_tree_value_compare(const Compare &pred) + : Compare(pred) + {} + + bool operator()(const Value& lhs, const Value& rhs) const + { + KeyOfValue key_extract; + return Compare::operator()(key_extract(lhs), key_extract(rhs)); + } + + const Compare &get_comp() const + { return *this; } + + Compare &get_comp() + { return *this; } +}; + +template +struct get_flat_tree_iterators +{ + typedef typename containers_detail:: + vector_iterator iterator; + typedef typename containers_detail:: + vector_const_iterator const_iterator; + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; +}; + +template +class flat_tree +{ + typedef boost::container::vector vector_t; + typedef Alloc allocator_t; + + public: + typedef flat_tree_value_compare value_compare; + + private: + struct Data + //Inherit from value_compare to do EBO + : public value_compare + { + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(Data) + public: + Data(const Data &d) + : value_compare(d), m_vect(d.m_vect) + {} + Data(const Compare &comp, + const vector_t &vect) + : value_compare(comp), m_vect(vect){} + + Data(const value_compare &comp, + const vector_t &vect) + : value_compare(comp), m_vect(vect){} + + Data(const Compare &comp, + const allocator_t &alloc) + : value_compare(comp), m_vect(alloc){} + + Data& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(Data) d) + { + this->value_compare::operator=(d); + m_vect = d.m_vect; + return *this; + } + + Data& operator=(BOOST_MOVE_MACRO_RV_REF(Data) d) + { + this->value_compare::operator=(BOOST_CONTAINER_MOVE_NAMESPACE::move(static_cast(d))); + m_vect = BOOST_CONTAINER_MOVE_NAMESPACE::move(d.m_vect); + return *this; + } + + vector_t m_vect; + }; + + Data m_data; + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(flat_tree) + + public: + + typedef typename vector_t::value_type value_type; + typedef typename vector_t::pointer pointer; + typedef typename vector_t::const_pointer const_pointer; + typedef typename vector_t::reference reference; + typedef typename vector_t::const_reference const_reference; + typedef Key key_type; + typedef Compare key_compare; + typedef typename vector_t::allocator_type allocator_type; + typedef allocator_type stored_allocator_type; + typedef typename allocator_type::size_type size_type; + typedef typename allocator_type::difference_type difference_type; + typedef typename vector_t::iterator iterator; + typedef typename vector_t::const_iterator const_iterator; + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; + + + // allocation/deallocation + flat_tree(const Compare& comp = Compare(), + const allocator_type& a = allocator_type()) + : m_data(comp, a) + { } + + flat_tree(const flat_tree& x) + : m_data(x.m_data, x.m_data.m_vect) + { } + + flat_tree(BOOST_MOVE_MACRO_RV_REF(flat_tree) x) + : m_data(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_data)) + { } + + template + flat_tree( ordered_range_t, InputIterator first, InputIterator last + , const Compare& comp = Compare() + , const allocator_type& a = allocator_type()) + : m_data(comp, a) + { this->m_data.m_vect.insert(this->m_data.m_vect.end(), first, last); } + + ~flat_tree() + { } + + flat_tree& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(flat_tree) x) + { m_data = x.m_data; return *this; } + + flat_tree& operator=(BOOST_MOVE_MACRO_RV_REF(flat_tree) mx) + { m_data = BOOST_CONTAINER_MOVE_NAMESPACE::move(mx.m_data); return *this; } + + public: + // accessors: + Compare key_comp() const + { return this->m_data.get_comp(); } + + allocator_type get_allocator() const + { return this->m_data.m_vect.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return this->m_data.m_vect.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return this->m_data.m_vect.get_stored_allocator(); } + + iterator begin() + { return this->m_data.m_vect.begin(); } + + const_iterator begin() const + { return this->cbegin(); } + + const_iterator cbegin() const + { return this->m_data.m_vect.begin(); } + + iterator end() + { return this->m_data.m_vect.end(); } + + const_iterator end() const + { return this->cend(); } + + const_iterator cend() const + { return this->m_data.m_vect.end(); } + + reverse_iterator rbegin() + { return reverse_iterator(this->end()); } + + const_reverse_iterator rbegin() const + { return this->crbegin(); } + + const_reverse_iterator crbegin() const + { return const_reverse_iterator(this->cend()); } + + reverse_iterator rend() + { return reverse_iterator(this->begin()); } + + const_reverse_iterator rend() const + { return this->crend(); } + + const_reverse_iterator crend() const + { return const_reverse_iterator(this->cbegin()); } + + bool empty() const + { return this->m_data.m_vect.empty(); } + + size_type size() const + { return this->m_data.m_vect.size(); } + + size_type max_size() const + { return this->m_data.m_vect.max_size(); } + + void swap(flat_tree& other) + { + value_compare& mycomp = this->m_data; + value_compare& othercomp = other.m_data; + containers_detail::do_swap(mycomp, othercomp); + vector_t & myvect = this->m_data.m_vect; + vector_t & othervect = other.m_data.m_vect; + myvect.swap(othervect); + } + + public: + // insert/erase + std::pair insert_unique(const value_type& val) + { + insert_commit_data data; + std::pair ret = priv_insert_unique_prepare(val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, val); + } + return ret; + } + + std::pair insert_unique(BOOST_MOVE_MACRO_RV_REF(value_type) val) + { + insert_commit_data data; + std::pair ret = priv_insert_unique_prepare(val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return ret; + } + + + iterator insert_equal(const value_type& val) + { + iterator i = this->upper_bound(KeyOfValue()(val)); + i = this->m_data.m_vect.insert(i, val); + return i; + } + + iterator insert_equal(BOOST_MOVE_MACRO_RV_REF(value_type) mval) + { + iterator i = this->upper_bound(KeyOfValue()(mval)); + i = this->m_data.m_vect.insert(i, BOOST_CONTAINER_MOVE_NAMESPACE::move(mval)); + return i; + } + + iterator insert_unique(const_iterator pos, const value_type& val) + { + insert_commit_data data; + std::pair ret = priv_insert_unique_prepare(pos, val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, val); + } + return ret.first; + } + + iterator insert_unique(const_iterator pos, BOOST_MOVE_MACRO_RV_REF(value_type) mval) + { + insert_commit_data data; + std::pair ret = priv_insert_unique_prepare(pos, mval, data); + if(ret.second){ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(mval)); + } + return ret.first; + } + + iterator insert_equal(const_iterator pos, const value_type& val) + { + insert_commit_data data; + priv_insert_equal_prepare(pos, val, data); + return priv_insert_commit(data, val); + } + + iterator insert_equal(const_iterator pos, BOOST_MOVE_MACRO_RV_REF(value_type) mval) + { + insert_commit_data data; + priv_insert_equal_prepare(pos, mval, data); + return priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(mval)); + } + + template + void insert_unique(InIt first, InIt last) + { + for ( ; first != last; ++first) + this->insert_unique(*first); + } + + template + void insert_equal(InIt first, InIt last) + { + typedef typename + std::iterator_traits::iterator_category ItCat; + priv_insert_equal(first, last, ItCat()); + } + + #ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + template + iterator emplace_unique(Args&&... args) + { + value_type && val = value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + insert_commit_data data; + std::pair ret = + priv_insert_unique_prepare(val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return ret.first; + } + + template + iterator emplace_hint_unique(const_iterator hint, Args&&... args) + { + value_type && val = value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + insert_commit_data data; + std::pair ret = priv_insert_unique_prepare(hint, val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return ret.first; + } + + template + iterator emplace_equal(Args&&... args) + { + value_type &&val = value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + iterator i = this->upper_bound(KeyOfValue()(val)); + i = this->m_data.m_vect.insert(i, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + return i; + } + + template + iterator emplace_hint_equal(const_iterator hint, Args&&... args) + { + value_type &&val = value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + insert_commit_data data; + priv_insert_equal_prepare(hint, val, data); + return priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace_unique() + { + containers_detail::value_init vval; + value_type &val = vval.m_t; + insert_commit_data data; + std::pair ret = + priv_insert_unique_prepare(val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return ret.first; + } + + iterator emplace_hint_unique(const_iterator hint) + { + containers_detail::value_init vval; + value_type &val = vval.m_t; + insert_commit_data data; + std::pair ret = priv_insert_unique_prepare(hint, val, data); + if(ret.second){ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return ret.first; + } + + iterator emplace_equal() + { + containers_detail::value_init vval; + value_type &val = vval.m_t; + iterator i = this->upper_bound(KeyOfValue()(val)); + i = this->m_data.m_vect.insert(i, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + return i; + } + + iterator emplace_hint_equal(const_iterator hint) + { + containers_detail::value_init vval; + value_type &val = vval.m_t; + insert_commit_data data; + priv_insert_equal_prepare(hint, val, data); + return priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + value_type val(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + insert_commit_data data; \ + std::pair ret = priv_insert_unique_prepare(val, data); \ + if(ret.second){ \ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); \ + } \ + return ret.first; \ + } \ + \ + template \ + iterator emplace_hint_unique(const_iterator hint, \ + BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + value_type val(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + insert_commit_data data; \ + std::pair ret = priv_insert_unique_prepare(hint, val, data); \ + if(ret.second){ \ + ret.first = priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); \ + } \ + return ret.first; \ + } \ + \ + template \ + iterator emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + value_type val(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + iterator i = this->upper_bound(KeyOfValue()(val)); \ + i = this->m_data.m_vect.insert(i, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); \ + return i; \ + } \ + \ + template \ + iterator emplace_hint_equal(const_iterator hint, \ + BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + value_type val(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + insert_commit_data data; \ + priv_insert_equal_prepare(hint, val, data); \ + return priv_insert_commit(data, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator erase(const_iterator position) + { return this->m_data.m_vect.erase(position); } + + size_type erase(const key_type& k) + { + std::pair itp = this->equal_range(k); + size_type ret = static_cast(itp.second-itp.first); + if (ret){ + this->m_data.m_vect.erase(itp.first, itp.second); + } + return ret; + } + + iterator erase(const_iterator first, const_iterator last) + { return this->m_data.m_vect.erase(first, last); } + + void clear() + { this->m_data.m_vect.clear(); } + + //! Effects: Tries to deallocate the excess of memory created + // with previous allocations. The size of the vector is unchanged + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to size(). + void shrink_to_fit() + { this->m_data.m_vect.shrink_to_fit(); } + + // set operations: + iterator find(const key_type& k) + { + const Compare &key_comp = this->m_data.get_comp(); + iterator i = this->lower_bound(k); + + if (i != this->end() && key_comp(k, KeyOfValue()(*i))){ + i = this->end(); + } + return i; + } + + const_iterator find(const key_type& k) const + { + const Compare &key_comp = this->m_data.get_comp(); + const_iterator i = this->lower_bound(k); + + if (i != this->end() && key_comp(k, KeyOfValue()(*i))){ + i = this->end(); + } + return i; + } + + size_type count(const key_type& k) const + { + std::pair p = this->equal_range(k); + size_type n = p.second - p.first; + return n; + } + + iterator lower_bound(const key_type& k) + { return this->priv_lower_bound(this->begin(), this->end(), k); } + + const_iterator lower_bound(const key_type& k) const + { return this->priv_lower_bound(this->begin(), this->end(), k); } + + iterator upper_bound(const key_type& k) + { return this->priv_upper_bound(this->begin(), this->end(), k); } + + const_iterator upper_bound(const key_type& k) const + { return this->priv_upper_bound(this->begin(), this->end(), k); } + + std::pair equal_range(const key_type& k) + { return this->priv_equal_range(this->begin(), this->end(), k); } + + std::pair equal_range(const key_type& k) const + { return this->priv_equal_range(this->begin(), this->end(), k); } + + size_type capacity() const + { return this->m_data.m_vect.capacity(); } + + void reserve(size_type count) + { this->m_data.m_vect.reserve(count); } + + private: + struct insert_commit_data + { + const_iterator position; + }; + + // insert/erase + void priv_insert_equal_prepare + (const_iterator pos, const value_type& val, insert_commit_data &data) + { + // N1780 + // To insert val at pos: + // if pos == end || val <= *pos + // if pos == begin || val >= *(pos-1) + // insert val before pos + // else + // insert val before upper_bound(val) + // else if pos+1 == end || val <= *(pos+1) + // insert val after pos + // else + // insert val before lower_bound(val) + const value_compare &value_comp = this->m_data; + + if(pos == this->cend() || !value_comp(*pos, val)){ + if (pos == this->cbegin() || !value_comp(val, pos[-1])){ + data.position = pos; + } + else{ + data.position = + this->priv_upper_bound(this->cbegin(), pos, KeyOfValue()(val)); + } + } + //Works, but increases code complexity + //else if (++pos == this->end() || !value_comp(*pos, val)){ + // return this->m_data.m_vect.insert(pos, val); + //} + else{ + data.position = + this->priv_lower_bound(pos, this->cend(), KeyOfValue()(val)); + } + } + + std::pair priv_insert_unique_prepare + (const_iterator beg, const_iterator end, const value_type& val, insert_commit_data &commit_data) + { + const value_compare &value_comp = this->m_data; + commit_data.position = this->priv_lower_bound(beg, end, KeyOfValue()(val)); + return std::pair + ( *reinterpret_cast(&commit_data.position) + , commit_data.position == end || value_comp(val, *commit_data.position)); + } + + std::pair priv_insert_unique_prepare + (const value_type& val, insert_commit_data &commit_data) + { return priv_insert_unique_prepare(this->begin(), this->end(), val, commit_data); } + + std::pair priv_insert_unique_prepare + (const_iterator pos, const value_type& val, insert_commit_data &commit_data) + { + //N1780. Props to Howard Hinnant! + //To insert val at pos: + //if pos == end || val <= *pos + // if pos == begin || val >= *(pos-1) + // insert val before pos + // else + // insert val before upper_bound(val) + //else if pos+1 == end || val <= *(pos+1) + // insert val after pos + //else + // insert val before lower_bound(val) + const value_compare &value_comp = this->m_data; + + if(pos == this->cend() || value_comp(val, *pos)){ + if(pos != this->cbegin() && !value_comp(val, pos[-1])){ + if(value_comp(pos[-1], val)){ + commit_data.position = pos; + return std::pair(*reinterpret_cast(&pos), true); + } + else{ + return std::pair(*reinterpret_cast(&pos), false); + } + } + return this->priv_insert_unique_prepare(this->cbegin(), pos, val, commit_data); + } + + // Works, but increases code complexity + //Next check + //else if (value_comp(*pos, val) && !value_comp(pos[1], val)){ + // if(value_comp(val, pos[1])){ + // commit_data.position = pos+1; + // return std::pair(pos+1, true); + // } + // else{ + // return std::pair(pos+1, false); + // } + //} + else{ + //[... pos ... val ... ] + //The hint is before the insertion position, so insert it + //in the remaining range + return this->priv_insert_unique_prepare(pos, this->end(), val, commit_data); + } + } + + template + iterator priv_insert_commit + (insert_commit_data &commit_data, BOOST_MOVE_MACRO_FWD_REF(Convertible) convertible) + { + return this->m_data.m_vect.insert + ( commit_data.position + , BOOST_CONTAINER_MOVE_NAMESPACE::forward(convertible)); + } + + template + RanIt priv_lower_bound(RanIt first, RanIt last, + const key_type & key) const + { + const Compare &key_comp = this->m_data.get_comp(); + KeyOfValue key_extract; + difference_type len = last - first, half; + RanIt middle; + + while (len > 0) { + half = len >> 1; + middle = first; + middle += half; + + if (key_comp(key_extract(*middle), key)) { + ++middle; + first = middle; + len = len - half - 1; + } + else + len = half; + } + return first; + } + + template + RanIt priv_upper_bound(RanIt first, RanIt last, + const key_type & key) const + { + const Compare &key_comp = this->m_data.get_comp(); + KeyOfValue key_extract; + difference_type len = last - first, half; + RanIt middle; + + while (len > 0) { + half = len >> 1; + middle = first; + middle += half; + + if (key_comp(key, key_extract(*middle))) { + len = half; + } + else{ + first = ++middle; + len = len - half - 1; + } + } + return first; + } + + template + std::pair + priv_equal_range(RanIt first, RanIt last, const key_type& key) const + { + const Compare &key_comp = this->m_data.get_comp(); + KeyOfValue key_extract; + difference_type len = last - first, half; + RanIt middle, left, right; + + while (len > 0) { + half = len >> 1; + middle = first; + middle += half; + + if (key_comp(key_extract(*middle), key)){ + first = middle; + ++first; + len = len - half - 1; + } + else if (key_comp(key, key_extract(*middle))){ + len = half; + } + else { + left = this->priv_lower_bound(first, middle, key); + first += len; + right = this->priv_upper_bound(++middle, first, key); + return std::pair(left, right); + } + } + return std::pair(first, first); + } + + template + void priv_insert_equal(FwdIt first, FwdIt last, std::forward_iterator_tag) + { + size_type len = static_cast(std::distance(first, last)); + this->reserve(this->size()+len); + this->priv_insert_equal(first, last, std::input_iterator_tag()); + } + + template + void priv_insert_equal(InIt first, InIt last, std::input_iterator_tag) + { + for ( ; first != last; ++first) + this->insert_equal(*first); + } + +/* + template + void priv_insert_unique(FwdIt first, FwdIt last, std::forward_iterator_tag) + { + size_type len = static_cast(std::distance(first, last)); + this->reserve(this->size()+len); + priv_insert_unique(first, last, std::input_iterator_tag()); + } + + template + void priv_insert_unique(InIt first, InIt last, std::input_iterator_tag) + { + for ( ; first != last; ++first) + this->insert_unique(*first); + } +*/ +}; + +template +inline bool +operator==(const flat_tree& x, + const flat_tree& y) +{ + return x.size() == y.size() && + std::equal(x.begin(), x.end(), y.begin()); +} + +template +inline bool +operator<(const flat_tree& x, + const flat_tree& y) +{ + return std::lexicographical_compare(x.begin(), x.end(), + y.begin(), y.end()); +} + +template +inline bool +operator!=(const flat_tree& x, + const flat_tree& y) + { return !(x == y); } + +template +inline bool +operator>(const flat_tree& x, + const flat_tree& y) + { return y < x; } + +template +inline bool +operator<=(const flat_tree& x, + const flat_tree& y) + { return !(y < x); } + +template +inline bool +operator>=(const flat_tree& x, + const flat_tree& y) + { return !(x < y); } + + +template +inline void +swap(flat_tree& x, + flat_tree& y) + { x.swap(y); } + +} //namespace containers_detail { + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif // BOOST_CONTAINERS_FLAT_TREE_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/iterators.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/iterators.hpp new file mode 100644 index 00000000..bfc4e1d0 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/iterators.hpp @@ -0,0 +1,545 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// (C) Copyright Gennaro Prota 2003 - 2004. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_ITERATORS_HPP +#define BOOST_CONTAINERS_DETAIL_ITERATORS_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING +#include INCLUDE_BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_STORED_REF_HPP +#else +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +#include + +namespace boost { +namespace container { + +template +class constant_iterator + : public std::iterator + +{ + typedef constant_iterator this_type; + + public: + explicit constant_iterator(const T &ref, Difference range_size) + : m_ptr(&ref), m_num(range_size){} + + //Constructors + constant_iterator() + : m_ptr(0), m_num(0){} + + constant_iterator& operator++() + { increment(); return *this; } + + constant_iterator operator++(int) + { + constant_iterator result (*this); + increment(); + return result; + } + + constant_iterator& operator--() + { decrement(); return *this; } + + constant_iterator operator--(int) + { + constant_iterator result (*this); + decrement(); + return result; + } + + friend bool operator== (const constant_iterator& i, const constant_iterator& i2) + { return i.equal(i2); } + + friend bool operator!= (const constant_iterator& i, const constant_iterator& i2) + { return !(i == i2); } + + friend bool operator< (const constant_iterator& i, const constant_iterator& i2) + { return i.less(i2); } + + friend bool operator> (const constant_iterator& i, const constant_iterator& i2) + { return i2 < i; } + + friend bool operator<= (const constant_iterator& i, const constant_iterator& i2) + { return !(i > i2); } + + friend bool operator>= (const constant_iterator& i, const constant_iterator& i2) + { return !(i < i2); } + + friend Difference operator- (const constant_iterator& i, const constant_iterator& i2) + { return i2.distance_to(i); } + + //Arithmetic + constant_iterator& operator+=(Difference off) + { this->advance(off); return *this; } + + constant_iterator operator+(Difference off) const + { + constant_iterator other(*this); + other.advance(off); + return other; + } + + friend constant_iterator operator+(Difference off, const constant_iterator& right) + { return right + off; } + + constant_iterator& operator-=(Difference off) + { this->advance(-off); return *this; } + + constant_iterator operator-(Difference off) const + { return *this + (-off); } + + const T& operator*() const + { return dereference(); } + + const T& operator[] (Difference n) const + { return dereference(); } + + const T* operator->() const + { return &(dereference()); } + + private: + const T * m_ptr; + Difference m_num; + + void increment() + { --m_num; } + + void decrement() + { ++m_num; } + + bool equal(const this_type &other) const + { return m_num == other.m_num; } + + bool less(const this_type &other) const + { return other.m_num < m_num; } + + const T & dereference() const + { return *m_ptr; } + + void advance(Difference n) + { m_num -= n; } + + Difference distance_to(const this_type &other)const + { return m_num - other.m_num; } +}; + +template +class default_construct_iterator + : public std::iterator + +{ + typedef default_construct_iterator this_type; + + public: + explicit default_construct_iterator(Difference range_size) + : m_num(range_size){} + + //Constructors + default_construct_iterator() + : m_num(0){} + + default_construct_iterator& operator++() + { increment(); return *this; } + + default_construct_iterator operator++(int) + { + default_construct_iterator result (*this); + increment(); + return result; + } + + default_construct_iterator& operator--() + { decrement(); return *this; } + + default_construct_iterator operator--(int) + { + default_construct_iterator result (*this); + decrement(); + return result; + } + + friend bool operator== (const default_construct_iterator& i, const default_construct_iterator& i2) + { return i.equal(i2); } + + friend bool operator!= (const default_construct_iterator& i, const default_construct_iterator& i2) + { return !(i == i2); } + + friend bool operator< (const default_construct_iterator& i, const default_construct_iterator& i2) + { return i.less(i2); } + + friend bool operator> (const default_construct_iterator& i, const default_construct_iterator& i2) + { return i2 < i; } + + friend bool operator<= (const default_construct_iterator& i, const default_construct_iterator& i2) + { return !(i > i2); } + + friend bool operator>= (const default_construct_iterator& i, const default_construct_iterator& i2) + { return !(i < i2); } + + friend Difference operator- (const default_construct_iterator& i, const default_construct_iterator& i2) + { return i2.distance_to(i); } + + //Arithmetic + default_construct_iterator& operator+=(Difference off) + { this->advance(off); return *this; } + + default_construct_iterator operator+(Difference off) const + { + default_construct_iterator other(*this); + other.advance(off); + return other; + } + + friend default_construct_iterator operator+(Difference off, const default_construct_iterator& right) + { return right + off; } + + default_construct_iterator& operator-=(Difference off) + { this->advance(-off); return *this; } + + default_construct_iterator operator-(Difference off) const + { return *this + (-off); } + + const T& operator*() const + { return dereference(); } + + const T* operator->() const + { return &(dereference()); } + + const T& operator[] (Difference n) const + { return dereference(); } + + private: + Difference m_num; + + void increment() + { --m_num; } + + void decrement() + { ++m_num; } + + bool equal(const this_type &other) const + { return m_num == other.m_num; } + + bool less(const this_type &other) const + { return other.m_num < m_num; } + + const T & dereference() const + { + static T dummy; + return dummy; + } + + void advance(Difference n) + { m_num -= n; } + + Difference distance_to(const this_type &other)const + { return m_num - other.m_num; } +}; + +template +class repeat_iterator + : public std::iterator + +{ + typedef repeat_iterator this_type; + public: + explicit repeat_iterator(T &ref, Difference range_size) + : m_ptr(&ref), m_num(range_size){} + + //Constructors + repeat_iterator() + : m_ptr(0), m_num(0){} + + this_type& operator++() + { increment(); return *this; } + + this_type operator++(int) + { + this_type result (*this); + increment(); + return result; + } + + this_type& operator--() + { increment(); return *this; } + + this_type operator--(int) + { + this_type result (*this); + increment(); + return result; + } + + friend bool operator== (const this_type& i, const this_type& i2) + { return i.equal(i2); } + + friend bool operator!= (const this_type& i, const this_type& i2) + { return !(i == i2); } + + friend bool operator< (const this_type& i, const this_type& i2) + { return i.less(i2); } + + friend bool operator> (const this_type& i, const this_type& i2) + { return i2 < i; } + + friend bool operator<= (const this_type& i, const this_type& i2) + { return !(i > i2); } + + friend bool operator>= (const this_type& i, const this_type& i2) + { return !(i < i2); } + + friend Difference operator- (const this_type& i, const this_type& i2) + { return i2.distance_to(i); } + + //Arithmetic + this_type& operator+=(Difference off) + { this->advance(off); return *this; } + + this_type operator+(Difference off) const + { + this_type other(*this); + other.advance(off); + return other; + } + + friend this_type operator+(Difference off, const this_type& right) + { return right + off; } + + this_type& operator-=(Difference off) + { this->advance(-off); return *this; } + + this_type operator-(Difference off) const + { return *this + (-off); } + + T& operator*() const + { return dereference(); } + + T& operator[] (Difference n) const + { return dereference(); } + + T *operator->() const + { return &(dereference()); } + + private: + T * m_ptr; + Difference m_num; + + void increment() + { --m_num; } + + void decrement() + { ++m_num; } + + bool equal(const this_type &other) const + { return m_num == other.m_num; } + + bool less(const this_type &other) const + { return other.m_num < m_num; } + + T & dereference() const + { return *m_ptr; } + + void advance(Difference n) + { m_num -= n; } + + Difference distance_to(const this_type &other)const + { return m_num - other.m_num; } +}; + +template +class emplace_iterator + : public std::iterator + +{ + typedef emplace_iterator this_type; + + public: + explicit emplace_iterator(E&e) + : m_num(1), m_pe(&e){} + + emplace_iterator() + : m_num(0), m_pe(0){} + + this_type& operator++() + { increment(); return *this; } + + this_type operator++(int) + { + this_type result (*this); + increment(); + return result; + } + + this_type& operator--() + { decrement(); return *this; } + + this_type operator--(int) + { + this_type result (*this); + decrement(); + return result; + } + + friend bool operator== (const this_type& i, const this_type& i2) + { return i.equal(i2); } + + friend bool operator!= (const this_type& i, const this_type& i2) + { return !(i == i2); } + + friend bool operator< (const this_type& i, const this_type& i2) + { return i.less(i2); } + + friend bool operator> (const this_type& i, const this_type& i2) + { return i2 < i; } + + friend bool operator<= (const this_type& i, const this_type& i2) + { return !(i > i2); } + + friend bool operator>= (const this_type& i, const this_type& i2) + { return !(i < i2); } + + friend std::ptrdiff_t operator- (const this_type& i, const this_type& i2) + { return i2.distance_to(i); } + + //Arithmetic + this_type& operator+=(std::ptrdiff_t off) + { this->advance(off); return *this; } + + this_type operator+(std::ptrdiff_t off) const + { + this_type other(*this); + other.advance(off); + return other; + } + + friend this_type operator+(std::ptrdiff_t off, const this_type& right) + { return right + off; } + + this_type& operator-=(std::ptrdiff_t off) + { this->advance(-off); return *this; } + + this_type operator-(std::ptrdiff_t off) const + { return *this + (-off); } + + const T& operator*() const + { return dereference(); } + + const T& operator[](std::ptrdiff_t) const + { return dereference(); } + + const T* operator->() const + { return &(dereference()); } + + void construct_in_place(T* ptr) + { (*m_pe)(ptr); } + + private: + std::ptrdiff_t m_num; + E * m_pe; + + void increment() + { --m_num; } + + void decrement() + { ++m_num; } + + bool equal(const this_type &other) const + { return m_num == other.m_num; } + + bool less(const this_type &other) const + { return other.m_num < m_num; } + + const T & dereference() const + { + static T dummy; + return dummy; + } + + void advance(std::ptrdiff_t n) + { m_num -= n; } + + std::ptrdiff_t distance_to(const this_type &other)const + { return m_num - other.m_num; } +}; + +#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + +template +struct emplace_functor +{ + typedef typename containers_detail::build_number_seq::type index_tuple_t; + + emplace_functor(Args&&... args) + : args_(args...) + {} + + void operator()(T *ptr) + { emplace_functor::inplace_impl(ptr, index_tuple_t()); } + + template + void inplace_impl(T* ptr, const containers_detail::index_tuple&) + { ::new(ptr) T(containers_detail::stored_ref::forward(containers_detail::get(args_))...); } + + containers_detail::tuple args_; +}; + +#else + +template +struct emplace_functor +{ + emplace_functor() + {} + void operator()(T *ptr) + { new(ptr) T(); } +}; + +#define BOOST_PP_LOCAL_MACRO(n) \ + template \ + struct BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ + { \ + BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ + ( BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _) ) \ + : BOOST_PP_ENUM(n, BOOST_CONTAINERS_AUX_PARAM_INIT, _) {} \ + \ + void operator()(T *ptr) \ + { \ + new(ptr)T (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_MEMBER_FORWARD, _)); \ + } \ + BOOST_PP_REPEAT(n, BOOST_CONTAINERS_AUX_PARAM_DEFINE, _) \ + }; \ + //! +#define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) +#include BOOST_PP_LOCAL_ITERATE() + +#endif + +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_ITERATORS_HPP + diff --git a/utils/boost_idb/boost/container/detail/math_functions.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/math_functions.hpp similarity index 90% rename from utils/boost_idb/boost/container/detail/math_functions.hpp rename to utils/boost_idb/boost/interprocess/containers/container/detail/math_functions.hpp index fe8386be..fc7a2060 100644 --- a/utils/boost_idb/boost/container/detail/math_functions.hpp +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/math_functions.hpp @@ -1,10 +1,10 @@ ////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Stephen Cleary 2000. -// (C) Copyright Ion Gaztanaga 2007-2012. +// (C) Copyright Ion Gaztanaga 2007-2009. // // Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at +// (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. @@ -16,13 +16,12 @@ #ifndef BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP #define BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP -#include "config_begin.hpp" #include #include namespace boost { namespace container { -namespace container_detail { +namespace containers_detail { // Greatest common divisor and least common multiple @@ -94,7 +93,7 @@ inline std::size_t floor_log2 (std::size_t x) std::size_t n = x; std::size_t log2 = 0; - + for(std::size_t shift = Bits >> 1; shift; shift >>= 1){ std::size_t tmp = n >> shift; if (tmp) @@ -104,10 +103,8 @@ inline std::size_t floor_log2 (std::size_t x) return log2; } -} // namespace container_detail +} // namespace containers_detail } // namespace container } // namespace boost -#include - #endif diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/mpl.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/mpl.hpp new file mode 100644 index 00000000..b34e9224 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/mpl.hpp @@ -0,0 +1,152 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_CONTAINER_DETAIL_MPL_HPP +#define BOOST_CONTAINERS_CONTAINER_DETAIL_MPL_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include + +namespace boost { +namespace container { +namespace containers_detail { + +template +struct integral_constant +{ + static const T value = val; + typedef integral_constant type; +}; + +template< bool C_ > +struct bool_ : integral_constant +{ + static const bool value = C_; +}; + +typedef bool_ true_; +typedef bool_ false_; + +typedef true_ true_type; +typedef false_ false_type; + +typedef char yes_type; +struct no_type +{ + char padding[8]; +}; + +template +struct enable_if_c { + typedef T type; +}; + +template +struct enable_if_c {}; + +template +struct enable_if : public enable_if_c {}; + +template +struct disable_if : public enable_if_c {}; + +template +class is_convertible +{ + typedef char true_t; + class false_t { char dummy[2]; }; + static true_t dispatch(U); + static false_t dispatch(...); + static T trigger(); + public: + enum { value = sizeof(dispatch(trigger())) == sizeof(true_t) }; +}; + +template< + bool C + , typename T1 + , typename T2 + > +struct if_c +{ + typedef T1 type; +}; + +template< + typename T1 + , typename T2 + > +struct if_c +{ + typedef T2 type; +}; + +template< + typename T1 + , typename T2 + , typename T3 + > +struct if_ +{ + typedef typename if_c<0 != T1::value, T2, T3>::type type; +}; + + +template +struct select1st +// : public std::unary_function +{ + template + const typename Pair::first_type& operator()(const OtherPair& x) const + { return x.first; } + + const typename Pair::first_type& operator()(const typename Pair::first_type& x) const + { return x; } +}; + +// identity is an extension: it is not part of the standard. +template +struct identity +// : public std::unary_function +{ + typedef T type; + const T& operator()(const T& x) const + { return x; } +}; + +template +struct ls_zeros +{ + static const std::size_t value = (S & std::size_t(1)) ? 0 : (1u + ls_zeros<(S >> 1u)>::value); +}; + +template<> +struct ls_zeros<0> +{ + static const std::size_t value = 0; +}; + +template<> +struct ls_zeros<1> +{ + static const std::size_t value = 0; +}; + +} //namespace containers_detail { +} //namespace container { +} //namespace boost { + +#endif //#ifndef BOOST_CONTAINERS_CONTAINER_DETAIL_MPL_HPP + diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/multiallocation_chain.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/multiallocation_chain.hpp new file mode 100644 index 00000000..30d0cca6 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/multiallocation_chain.hpp @@ -0,0 +1,245 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_MULTIALLOCATION_CHAIN_HPP +#define BOOST_CONTAINERS_DETAIL_MULTIALLOCATION_CHAIN_HPP + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATOR_HPP +#include +#include +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +namespace boost { +namespace container { +namespace containers_detail { + +template +class basic_multiallocation_chain +{ + private: + typedef bi::slist_base_hook + ,bi::link_mode + > node; + + typedef bi::slist< node + , bi::linear + , bi::cache_last + > slist_impl_t; + slist_impl_t slist_impl_; + + static node & to_node(VoidPointer p) + { return *static_cast(static_cast(containers_detail::get_pointer(p))); } + + BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(basic_multiallocation_chain) + + public: + + + typedef VoidPointer void_pointer; + typedef typename slist_impl_t::iterator iterator; + + basic_multiallocation_chain() + : slist_impl_() + {} + + basic_multiallocation_chain(BOOST_MOVE_MACRO_RV_REF(basic_multiallocation_chain) other) + : slist_impl_() + { slist_impl_.swap(other.slist_impl_); } + + basic_multiallocation_chain& operator=(BOOST_MOVE_MACRO_RV_REF(basic_multiallocation_chain) other) + { + basic_multiallocation_chain tmp(BOOST_CONTAINER_MOVE_NAMESPACE::move(other)); + this->swap(tmp); + return *this; + } + + bool empty() const + { return slist_impl_.empty(); } + + std::size_t size() const + { return slist_impl_.size(); } + + iterator before_begin() + { return slist_impl_.before_begin(); } + + iterator begin() + { return slist_impl_.begin(); } + + iterator end() + { return slist_impl_.end(); } + + iterator last() + { return slist_impl_.last(); } + + void clear() + { slist_impl_.clear(); } + + iterator insert_after(iterator it, void_pointer m) + { return slist_impl_.insert_after(it, to_node(m)); } + + void push_front(void_pointer m) + { return slist_impl_.push_front(to_node(m)); } + + void push_back(void_pointer m) + { return slist_impl_.push_back(to_node(m)); } + + void pop_front() + { return slist_impl_.pop_front(); } + + void *front() + { return &*slist_impl_.begin(); } + + void splice_after(iterator after_this, basic_multiallocation_chain &x, iterator before_begin, iterator before_end) + { slist_impl_.splice_after(after_this, x.slist_impl_, before_begin, before_end); } + + void splice_after(iterator after_this, basic_multiallocation_chain &x, iterator before_begin, iterator before_end, std::size_t n) + { slist_impl_.splice_after(after_this, x.slist_impl_, before_begin, before_end, n); } + + void splice_after(iterator after_this, basic_multiallocation_chain &x) + { slist_impl_.splice_after(after_this, x.slist_impl_); } + + void incorporate_after(iterator after_this, void_pointer begin , iterator before_end) + { slist_impl_.incorporate_after(after_this, &to_node(begin), &to_node(before_end)); } + + void incorporate_after(iterator after_this, void_pointer begin, void_pointer before_end, std::size_t n) + { slist_impl_.incorporate_after(after_this, &to_node(begin), &to_node(before_end), n); } + + void swap(basic_multiallocation_chain &x) + { slist_impl_.swap(x.slist_impl_); } + + static iterator iterator_to(void_pointer p) + { return slist_impl_t::s_iterator_to(to_node(p)); } + + std::pair extract_data() + { + std::pair ret + (slist_impl_.begin().operator->() + ,slist_impl_.last().operator->()); + slist_impl_.clear(); + return ret; + } +}; + +template +struct cast_functor +{ + typedef typename containers_detail::add_reference::type result_type; + template + result_type operator()(U &ptr) const + { return *static_cast(static_cast(&ptr)); } +}; + +template +class transform_multiallocation_chain +{ + private: + BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(transform_multiallocation_chain) + + MultiallocationChain holder_; + typedef typename MultiallocationChain::void_pointer void_pointer; + typedef typename boost::pointer_to_other + ::type pointer; + + static pointer cast(void_pointer p) + { + return pointer(static_cast(containers_detail::get_pointer(p))); + } + + public: + typedef transform_iterator + < typename MultiallocationChain::iterator + , containers_detail::cast_functor > iterator; + + transform_multiallocation_chain() + : holder_() + {} + + transform_multiallocation_chain(BOOST_MOVE_MACRO_RV_REF(transform_multiallocation_chain) other) + : holder_() + { this->swap(other); } + + transform_multiallocation_chain(BOOST_MOVE_MACRO_RV_REF(MultiallocationChain) other) + : holder_(BOOST_CONTAINER_MOVE_NAMESPACE::move(other)) + {} + + transform_multiallocation_chain& operator=(BOOST_MOVE_MACRO_RV_REF(transform_multiallocation_chain) other) + { + transform_multiallocation_chain tmp(BOOST_CONTAINER_MOVE_NAMESPACE::move(other)); + this->swap(tmp); + return *this; + } + + void push_front(pointer mem) + { holder_.push_front(mem); } + + void swap(transform_multiallocation_chain &other_chain) + { holder_.swap(other_chain.holder_); } + + void splice_after(iterator after_this, transform_multiallocation_chain &x, iterator before_begin, iterator before_end, std::size_t n) + { holder_.splice_after(after_this.base(), x.holder_, before_begin.base(), before_end.base(), n); } + + void incorporate_after(iterator after_this, void_pointer begin, void_pointer before_end, std::size_t n) + { holder_.incorporate_after(after_this.base(), begin, before_end, n); } + + void pop_front() + { holder_.pop_front(); } + + pointer front() + { return cast(holder_.front()); } + + bool empty() const + { return holder_.empty(); } + + iterator before_begin() + { return iterator(holder_.before_begin()); } + + iterator begin() + { return iterator(holder_.begin()); } + + iterator end() + { return iterator(holder_.end()); } + + iterator last() + { return iterator(holder_.last()); } + + std::size_t size() const + { return holder_.size(); } + + void clear() + { holder_.clear(); } + + iterator insert_after(iterator it, pointer m) + { return iterator(holder_.insert_after(it.base(), m)); } + + static iterator iterator_to(pointer p) + { return iterator(MultiallocationChain::iterator_to(p)); } + + std::pair extract_data() + { return holder_.extract_data(); } + + MultiallocationChain extract_multiallocation_chain() + { + return MultiallocationChain(BOOST_CONTAINER_MOVE_NAMESPACE::move(holder_)); + } +}; + +}}} + +// namespace containers_detail { +// namespace container { +// namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //BOOST_CONTAINERS_DETAIL_MULTIALLOCATION_CHAIN_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/node_alloc_holder.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/node_alloc_holder.hpp new file mode 100644 index 00000000..102542f7 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/node_alloc_holder.hpp @@ -0,0 +1,501 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_NODE_ALLOC_HPP_ +#define BOOST_CONTAINERS_DETAIL_NODE_ALLOC_HPP_ + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include +#include + +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include + +#include INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_DESTROYERS_HPP + +#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP + + +namespace boost { +namespace container { +namespace containers_detail { + +//!A deleter for scoped_ptr that deallocates the memory +//!allocated for an object using a STL allocator. +template +struct scoped_deallocator +{ + typedef typename Allocator::pointer pointer; + typedef containers_detail::integral_constant::value> alloc_version; + typedef containers_detail::integral_constant allocator_v1; + typedef containers_detail::integral_constant allocator_v2; + + private: + void priv_deallocate(allocator_v1) + { m_alloc.deallocate(m_ptr, 1); } + + void priv_deallocate(allocator_v2) + { m_alloc.deallocate_one(m_ptr); } + + BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(scoped_deallocator) + + public: + + pointer m_ptr; + Allocator& m_alloc; + + scoped_deallocator(pointer p, Allocator& a) + : m_ptr(p), m_alloc(a) + {} + + ~scoped_deallocator() + { if (m_ptr)priv_deallocate(alloc_version()); } + + scoped_deallocator(BOOST_MOVE_MACRO_RV_REF(scoped_deallocator) o) + : m_ptr(o.m_ptr), m_alloc(o.m_alloc) + { o.release(); } + + pointer get() const + { return m_ptr; } + + void release() + { m_ptr = 0; } +}; + +template +class allocator_destroyer_and_chain_builder +{ + typedef typename A::value_type value_type; + typedef typename A::multiallocation_chain multiallocation_chain; + + A & a_; + multiallocation_chain &c_; + + public: + allocator_destroyer_and_chain_builder(A &a, multiallocation_chain &c) + : a_(a), c_(c) + {} + + void operator()(const typename A::pointer &p) + { + value_type *vp = containers_detail::get_pointer(p); + vp->~value_type(); + c_.push_front(vp); + } +}; + +template +class allocator_multialloc_chain_node_deallocator +{ + typedef typename A::value_type value_type; + typedef typename A::multiallocation_chain multiallocation_chain; + typedef allocator_destroyer_and_chain_builder chain_builder; + + A & a_; + multiallocation_chain c_; + + public: + allocator_multialloc_chain_node_deallocator(A &a) + : a_(a), c_() + {} + + chain_builder get_chain_builder() + { return chain_builder(a_, c_); } + + ~allocator_multialloc_chain_node_deallocator() + { + if(!c_.empty()) + a_.deallocate_individual(BOOST_CONTAINER_MOVE_NAMESPACE::move(c_)); + } +}; + + +template +struct node_compare + : private ValueCompare +{ + typedef typename ValueCompare::key_type key_type; + typedef typename ValueCompare::value_type value_type; + typedef typename ValueCompare::key_of_value key_of_value; + + node_compare(const ValueCompare &pred) + : ValueCompare(pred) + {} + + ValueCompare &value_comp() + { return static_cast(*this); } + + ValueCompare &value_comp() const + { return static_cast(*this); } + + bool operator()(const Node &a, const Node &b) const + { return ValueCompare::operator()(a.get_data(), b.get_data()); } +}; + +template +struct node_alloc_holder +{ + typedef node_alloc_holder self_t; + typedef typename A::value_type value_type; + typedef typename ICont::value_type Node; + typedef typename A::template rebind::other NodeAlloc; + typedef A ValAlloc; + typedef typename NodeAlloc::pointer NodePtr; + typedef containers_detail::scoped_deallocator Deallocator; + typedef typename NodeAlloc::size_type size_type; + typedef typename NodeAlloc::difference_type difference_type; + typedef containers_detail::integral_constant allocator_v1; + typedef containers_detail::integral_constant allocator_v2; + typedef containers_detail::integral_constant::value> alloc_version; + typedef typename ICont::iterator icont_iterator; + typedef typename ICont::const_iterator icont_citerator; + typedef allocator_destroyer Destroyer; + + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(node_alloc_holder) + + public: + + node_alloc_holder(const ValAlloc &a) + : members_(a) + {} + + node_alloc_holder(const node_alloc_holder &other) + : members_(other.node_alloc()) + {} + + node_alloc_holder(BOOST_MOVE_MACRO_RV_REF(node_alloc_holder) other) + : members_(BOOST_CONTAINER_MOVE_NAMESPACE::move(other.node_alloc())) + { this->swap(other); } + + node_alloc_holder & operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(node_alloc_holder) other) + { members_.assign(other.node_alloc()); } + + node_alloc_holder & operator=(BOOST_MOVE_MACRO_RV_REF(node_alloc_holder) other) + { members_.assign(other.node_alloc()); } + + template + node_alloc_holder(const ValAlloc &a, const Pred &c) + : members_(a, typename ICont::value_compare(c)) + {} + + template + node_alloc_holder(BOOST_MOVE_MACRO_RV_REF(ValAlloc) a, const Pred &c) + : members_(a, typename ICont::value_compare(c)) + {} + + template + node_alloc_holder(const node_alloc_holder &other, const Pred &c) + : members_(other.node_alloc(), typename ICont::value_compare(c)) + {} + + ~node_alloc_holder() + { this->clear(alloc_version()); } + + size_type max_size() const + { return this->node_alloc().max_size(); } + + NodePtr allocate_one() + { return this->allocate_one(alloc_version()); } + + NodePtr allocate_one(allocator_v1) + { return this->node_alloc().allocate(1); } + + NodePtr allocate_one(allocator_v2) + { return this->node_alloc().allocate_one(); } + + void deallocate_one(NodePtr p) + { return this->deallocate_one(p, alloc_version()); } + + void deallocate_one(NodePtr p, allocator_v1) + { this->node_alloc().deallocate(p, 1); } + + void deallocate_one(NodePtr p, allocator_v2) + { this->node_alloc().deallocate_one(p); } + + template + static void construct(const NodePtr &ptr, + BOOST_MOVE_MACRO_RV_REF_2_TEMPL_ARGS(std::pair, Convertible1, Convertible2) value) + { + typedef typename Node::hook_type hook_type; + typedef typename Node::value_type::first_type first_type; + typedef typename Node::value_type::second_type second_type; + Node *nodeptr = containers_detail::get_pointer(ptr); + + //Hook constructor does not throw + new(static_cast(nodeptr))hook_type(); + //Now construct pair members_holder + value_type *valueptr = &nodeptr->get_data(); + new((void*)&valueptr->first) first_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(value.first)); + BOOST_TRY{ + new((void*)&valueptr->second) second_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(value.second)); + } + BOOST_CATCH(...){ + valueptr->first.~first_type(); + static_cast(nodeptr)->~hook_type(); + BOOST_RETHROW + } + BOOST_CATCH_END + } + + static void destroy(const NodePtr &ptr) + { containers_detail::get_pointer(ptr)->~Node(); } + + Deallocator create_node_and_deallocator() + { + return Deallocator(this->allocate_one(), this->node_alloc()); + } + + #ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + template + static void construct(const NodePtr &ptr, Args &&...args) + { new((void*)containers_detail::get_pointer(ptr)) Node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + template + NodePtr create_node(Args &&...args) + { + NodePtr p = this->allocate_one(); + Deallocator node_deallocator(p, this->node_alloc()); + self_t::construct(p, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + node_deallocator.release(); + return (p); + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + static void construct(const NodePtr &ptr) + { new((void*)containers_detail::get_pointer(ptr)) Node(); } + + NodePtr create_node() + { + NodePtr p = this->allocate_one(); + Deallocator node_deallocator(p, this->node_alloc()); + self_t::construct(p); + node_deallocator.release(); + return (p); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + void construct(const NodePtr &ptr, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + new((void*)containers_detail::get_pointer(ptr)) \ + Node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + NodePtr create_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + NodePtr p = this->allocate_one(); \ + Deallocator node_deallocator(p, this->node_alloc()); \ + self_t::construct(p, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + node_deallocator.release(); \ + return (p); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + template + NodePtr create_node_from_it(It it) + { + NodePtr p = this->allocate_one(); + Deallocator node_deallocator(p, this->node_alloc()); + ::boost::container::construct_in_place(containers_detail::get_pointer(p), it); + node_deallocator.release(); + return (p); + } + + void destroy_node(NodePtr node) + { + self_t::destroy(node); + this->deallocate_one(node); + } + + void swap(node_alloc_holder &x) + { + NodeAlloc& this_alloc = this->node_alloc(); + NodeAlloc& other_alloc = x.node_alloc(); + + if (this_alloc != other_alloc){ + containers_detail::do_swap(this_alloc, other_alloc); + } + + this->icont().swap(x.icont()); + } + + template + FwdIterator allocate_many_and_construct + (FwdIterator beg, difference_type n, Inserter inserter) + { + if(n){ + typedef typename NodeAlloc::multiallocation_chain multiallocation_chain; + + //Try to allocate memory in a single block + multiallocation_chain mem(this->node_alloc().allocate_individual(n)); + int constructed = 0; + Node *p = 0; + BOOST_TRY{ + for(difference_type i = 0; i < n; ++i, ++beg, --constructed){ + p = containers_detail::get_pointer(mem.front()); + mem.pop_front(); + //This can throw + constructed = 0; + boost::container::construct_in_place(p, beg); + ++constructed; + //This can throw in some containers (predicate might throw) + inserter(*p); + } + } + BOOST_CATCH(...){ + if(constructed){ + this->destroy(p); + } + this->node_alloc().deallocate_individual(BOOST_CONTAINER_MOVE_NAMESPACE::move(mem)); + BOOST_RETHROW + } + BOOST_CATCH_END + } + return beg; + } + + void clear(allocator_v1) + { this->icont().clear_and_dispose(Destroyer(this->node_alloc())); } + + void clear(allocator_v2) + { + typename NodeAlloc::multiallocation_chain chain; + allocator_destroyer_and_chain_builder builder(this->node_alloc(), chain); + this->icont().clear_and_dispose(builder); + BOOST_STATIC_ASSERT((::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value == true)); + if(!chain.empty()) + this->node_alloc().deallocate_individual(BOOST_CONTAINER_MOVE_NAMESPACE::move(chain)); + } + + icont_iterator erase_range(icont_iterator first, icont_iterator last, allocator_v1) + { return this->icont().erase_and_dispose(first, last, Destroyer(this->node_alloc())); } + + icont_iterator erase_range(icont_iterator first, icont_iterator last, allocator_v2) + { + allocator_multialloc_chain_node_deallocator chain_holder(this->node_alloc()); + return this->icont().erase_and_dispose(first, last, chain_holder.get_chain_builder()); + } + + template + size_type erase_key(const Key& k, const Comparator &comp, allocator_v1) + { return this->icont().erase_and_dispose(k, comp, Destroyer(this->node_alloc())); } + + template + size_type erase_key(const Key& k, const Comparator &comp, allocator_v2) + { + allocator_multialloc_chain_node_deallocator chain_holder(this->node_alloc()); + return this->icont().erase_and_dispose(k, comp, chain_holder.get_chain_builder()); + } + + protected: + struct cloner + { + cloner(node_alloc_holder &holder) + : m_holder(holder) + {} + + NodePtr operator()(const Node &other) const + { return m_holder.create_node(other.get_data()); } + + node_alloc_holder &m_holder; + }; + + struct destroyer + { + destroyer(node_alloc_holder &holder) + : m_holder(holder) + {} + + void operator()(NodePtr n) const + { m_holder.destroy_node(n); } + + node_alloc_holder &m_holder; + }; + + struct members_holder + : public NodeAlloc + { + private: + members_holder(const members_holder&); + + public: + template + members_holder(const ConvertibleToAlloc &c2alloc) + : NodeAlloc(c2alloc) + {} + + template + members_holder(const ConvertibleToAlloc &c2alloc, const Pred &c) + : NodeAlloc(c2alloc), m_icont(c) + {} + + template + void assign (const ConvertibleToAlloc &c2alloc) + { + NodeAlloc::operator=(c2alloc); + } + + //The intrusive container + ICont m_icont; + } members_; + + ICont &non_const_icont() const + { return const_cast(this->members_.m_icont); } + + ICont &icont() + { return this->members_.m_icont; } + + const ICont &icont() const + { return this->members_.m_icont; } + + NodeAlloc &node_alloc() + { return static_cast(this->members_); } + + const NodeAlloc &node_alloc() const + { return static_cast(this->members_); } +}; + +} //namespace containers_detail { +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif // BOOST_CONTAINERS_DETAIL_NODE_ALLOC_HPP_ diff --git a/utils/boost_idb/boost/container/detail/node_pool_impl.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/node_pool_impl.hpp similarity index 78% rename from utils/boost_idb/boost/container/detail/node_pool_impl.hpp rename to utils/boost_idb/boost/interprocess/containers/container/detail/node_pool_impl.hpp index 0c5c7446..90f62963 100644 --- a/utils/boost_idb/boost/container/detail/node_pool_impl.hpp +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/node_pool_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,30 +11,28 @@ #ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_IMPL_HPP #define BOOST_CONTAINER_DETAIL_NODE_POOL_IMPL_HPP -#if defined(_MSC_VER) +#if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include "config_begin.hpp" -#include -#include -#include -#include +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include #include #include -#include -#include -#include -#include -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_POOL_COMMON_HPP #include #include #include //std::unary_function - namespace boost { namespace container { -namespace container_detail { +namespace containers_detail { template class private_node_pool_impl @@ -51,7 +49,6 @@ class private_node_pool_impl typedef typename node_slist::node_t node_t; typedef typename node_slist::node_slist_t free_nodes_t; typedef typename SegmentManagerBase::multiallocation_chain multiallocation_chain; - typedef typename SegmentManagerBase::size_type size_type; private: typedef typename bi::make_slist @@ -64,9 +61,9 @@ class private_node_pool_impl typedef SegmentManagerBase segment_manager_base_type; //!Constructor from a segment manager. Never throws - private_node_pool_impl(segment_manager_base_type *segment_mngr_base, size_type node_size, size_type nodes_per_block) + private_node_pool_impl(segment_manager_base_type *segment_mngr_base, std::size_t node_size, std::size_t nodes_per_block) : m_nodes_per_block(nodes_per_block) - , m_real_node_size(lcm(node_size, size_type(alignment_of::value))) + , m_real_node_size(lcm(node_size, std::size_t(alignment_of::value))) //General purpose allocator , mp_segment_mngr_base(segment_mngr_base) , m_blocklist() @@ -79,33 +76,33 @@ class private_node_pool_impl ~private_node_pool_impl() { this->purge_blocks(); } - size_type get_real_num_node() const + std::size_t get_real_num_node() const { return m_nodes_per_block; } //!Returns the segment manager. Never throws segment_manager_base_type* get_segment_manager_base()const - { return container_detail::to_raw_pointer(mp_segment_mngr_base); } + { return containers_detail::get_pointer(mp_segment_mngr_base); } void *allocate_node() - { return this->priv_alloc_node(); } - + { return priv_alloc_node(); } + //!Deallocates an array pointed by ptr. Never throws void deallocate_node(void *ptr) - { this->priv_dealloc_node(ptr); } + { priv_dealloc_node(ptr); } - //!Allocates a singly linked list of n nodes ending in null pointer. - void allocate_nodes(const size_type n, multiallocation_chain &chain) + //!Allocates a singly linked list of n nodes ending in null pointer. + multiallocation_chain allocate_nodes(const std::size_t n) { //Preallocate all needed blocks to fulfill the request - size_type cur_nodes = m_freelist.size(); + std::size_t cur_nodes = m_freelist.size(); if(cur_nodes < n){ - this->priv_alloc_block(((n - cur_nodes) - 1)/m_nodes_per_block + 1); + priv_alloc_block(((n - cur_nodes) - 1)/m_nodes_per_block + 1); } //We just iterate the needed nodes to get the last we'll erase typedef typename free_nodes_t::iterator free_iterator; free_iterator before_last_new_it = m_freelist.before_begin(); - for(size_type j = 0; j != n; ++j){ + for(std::size_t j = 0; j != n; ++j){ ++before_last_new_it; } @@ -120,18 +117,20 @@ class private_node_pool_impl //Now take the last erased node and just splice it in the end //of the intrusive list that will be traversed by the multialloc iterator. + multiallocation_chain chain; chain.incorporate_after(chain.before_begin(), &*first_node, &*last_node, n); m_allocated += n; + return BOOST_CONTAINER_MOVE_NAMESPACE::move(chain); } - void deallocate_nodes(multiallocation_chain &chain) + void deallocate_nodes(multiallocation_chain chain) { typedef typename multiallocation_chain::iterator iterator; iterator it(chain.begin()), itend(chain.end()); while(it != itend){ void *pElem = &*it; ++it; - this->priv_dealloc_node(pElem); + priv_dealloc_node(pElem); } } @@ -146,8 +145,8 @@ class private_node_pool_impl nodelist_iterator backup_list_last = backup_list.before_begin(); //Execute the algorithm and get an iterator to the last value - size_type blocksize = get_rounded_size - (m_real_node_size*m_nodes_per_block, (size_type) alignment_of::value); + std::size_t blocksize = get_rounded_size + (m_real_node_size*m_nodes_per_block, alignment_of::value); while(it != itend){ //Collect all the nodes from the block pointed by it @@ -197,7 +196,7 @@ class private_node_pool_impl , backup_list.size()); } - size_type num_free_nodes() + std::size_t num_free_nodes() { return m_freelist.size(); } //!Deallocates all used memory. Precondition: all nodes allocated from this pool should @@ -206,8 +205,10 @@ class private_node_pool_impl { //check for memory leaks BOOST_ASSERT(m_allocated==0); - size_type blocksize = get_rounded_size - (m_real_node_size*m_nodes_per_block, (size_type)alignment_of::value); + std::size_t blocksize = get_rounded_size + (m_real_node_size*m_nodes_per_block, alignment_of::value); + typename blockslist_t::iterator + it(m_blocklist.begin()), itend(m_blocklist.end()), aux; //We iterate though the NodeBlock list to free the memory while(!m_blocklist.empty()){ @@ -236,7 +237,7 @@ class private_node_pool_impl push_in_list(free_nodes_t &l, typename free_nodes_t::iterator &it) : slist_(l), last_it_(it) {} - + void operator()(typename free_nodes_t::pointer p) const { slist_.push_front(*p); @@ -256,10 +257,10 @@ class private_node_pool_impl is_between(const void *addr, std::size_t size) : beg_(static_cast(addr)), end_(beg_+size) {} - + bool operator()(typename free_nodes_t::const_reference v) const { - return (beg_ <= reinterpret_cast(&v) && + return (beg_ <= reinterpret_cast(&v) && end_ > reinterpret_cast(&v)); } private: @@ -273,7 +274,7 @@ class private_node_pool_impl { //If there are no free nodes we allocate a new block if (m_freelist.empty()) - this->priv_alloc_block(1); + priv_alloc_block(); //We take the first free node node_t *n = (node_t*)&m_freelist.front(); m_freelist.pop_front(); @@ -293,14 +294,15 @@ class private_node_pool_impl } //!Allocates several blocks of nodes. Can throw - void priv_alloc_block(size_type num_blocks) + void priv_alloc_block(std::size_t num_blocks = 1) { - BOOST_ASSERT(num_blocks > 0); - size_type blocksize = - get_rounded_size(m_real_node_size*m_nodes_per_block, (size_type)alignment_of::value); + if(!num_blocks) + return; + std::size_t blocksize = + get_rounded_size(m_real_node_size*m_nodes_per_block, alignment_of::value); - BOOST_TRY{ - for(size_type i = 0; i != num_blocks; ++i){ + try{ + for(std::size_t i = 0; i != num_blocks; ++i){ //We allocate a new NodeBlock and put it as first //element in the free Node list char *pNode = reinterpret_cast @@ -308,18 +310,17 @@ class private_node_pool_impl char *pBlock = pNode; m_blocklist.push_front(get_block_hook(pBlock, blocksize)); - //We initialize all Nodes in Node Block to insert + //We initialize all Nodes in Node Block to insert //them in the free Node list - for(size_type j = 0; j < m_nodes_per_block; ++j, pNode += m_real_node_size){ + for(std::size_t i = 0; i < m_nodes_per_block; ++i, pNode += m_real_node_size){ m_freelist.push_front(*new (pNode) node_t); } } } - BOOST_CATCH(...){ + catch(...){ //to-do: if possible, an efficient way to deallocate allocated blocks - BOOST_RETHROW + throw; } - BOOST_CATCH_END } //!Deprecated, use deallocate_free_blocks @@ -332,34 +333,34 @@ class private_node_pool_impl private: //!Returns a reference to the block hook placed in the end of the block - static node_t & get_block_hook (void *block, size_type blocksize) - { - return *reinterpret_cast(reinterpret_cast(block) + blocksize); + static node_t & get_block_hook (void *block, std::size_t blocksize) + { + return *reinterpret_cast(reinterpret_cast(block) + blocksize); } //!Returns the starting address of the block reference to the block hook placed in the end of the block - void *get_block_from_hook (node_t *hook, size_type blocksize) - { + void *get_block_from_hook (node_t *hook, std::size_t blocksize) + { return (reinterpret_cast(hook) - blocksize); } private: - typedef typename boost::intrusive::pointer_traits - ::template rebind_pointer::type segment_mngr_base_ptr_t; + typedef typename boost::pointer_to_other + ::type segment_mngr_base_ptr_t; - const size_type m_nodes_per_block; - const size_type m_real_node_size; + const std::size_t m_nodes_per_block; + const std::size_t m_real_node_size; segment_mngr_base_ptr_t mp_segment_mngr_base; //Segment manager blockslist_t m_blocklist; //Intrusive container of blocks free_nodes_t m_freelist; //Intrusive container of free nods - size_type m_allocated; //Used nodes for debugging + std::size_t m_allocated; //Used nodes for debugging }; -} //namespace container_detail { +} //namespace containers_detail { } //namespace container { } //namespace boost { -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP #endif //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/pair.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/pair.hpp new file mode 100644 index 00000000..da705729 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/pair.hpp @@ -0,0 +1,212 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_CONTAINERS_DETAIL_PAIR_HPP +#define BOOST_CONTAINERS_CONTAINERS_DETAIL_PAIR_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP + +#include //std::pair + +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +namespace boost { +namespace container { +namespace containers_detail { + +template +struct pair +{ + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(pair) + + public: + typedef T1 first_type; + typedef T2 second_type; + + T1 first; + T2 second; + + //std::pair compatibility + template + pair(const std::pair& p) + : first(p.first), second(p.second) + {} + + //To resolve ambiguity with the variadic constructor of 1 argument + //and the previous constructor + pair(std::pair& x) + : first(x.first), second(x.second) + {} + + template + pair(BOOST_MOVE_MACRO_RV_REF_2_TEMPL_ARGS(std::pair, D, S) p) + : first(BOOST_CONTAINER_MOVE_NAMESPACE::move(p.first)), second(BOOST_CONTAINER_MOVE_NAMESPACE::move(p.second)) + {} + + pair() + : first(), second() + {} + + pair(const pair& x) + : first(x.first), second(x.second) + {} + + //To resolve ambiguity with the variadic constructor of 1 argument + //and the copy constructor + pair(pair& x) + : first(x.first), second(x.second) + {} + + pair(BOOST_MOVE_MACRO_RV_REF(pair) p) + : first(BOOST_CONTAINER_MOVE_NAMESPACE::move(p.first)), second(BOOST_CONTAINER_MOVE_NAMESPACE::move(p.second)) + {} + + template + pair(BOOST_MOVE_MACRO_RV_REF_2_TEMPL_ARGS(pair, D, S) p) + : first(BOOST_CONTAINER_MOVE_NAMESPACE::move(p.first)), second(BOOST_CONTAINER_MOVE_NAMESPACE::move(p.second)) + {} + + #ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + template + pair(U &&u, Args &&... args) + : first(BOOST_CONTAINER_MOVE_NAMESPACE::forward(u)) + , second(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...) + {} + + #else + + template + pair( BOOST_CONTAINERS_PARAM(U, u) + #ifdef BOOST_NO_RVALUE_REFERENCES + , typename containers_detail::disable_if + < containers_detail::is_same > >::type* = 0 + #endif + ) + : first(BOOST_CONTAINER_MOVE_NAMESPACE::forward(const_cast(u))) + {} + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + pair(BOOST_CONTAINERS_PARAM(U, u) \ + ,BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + : first(BOOST_CONTAINER_MOVE_NAMESPACE::forward(const_cast(u))) \ + , second(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)) \ + {} \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + #endif + + pair& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(pair) p) + { + first = p.first; + second = p.second; + return *this; + } + + pair& operator=(BOOST_MOVE_MACRO_RV_REF(pair) p) + { + first = BOOST_CONTAINER_MOVE_NAMESPACE::move(p.first); + second = BOOST_CONTAINER_MOVE_NAMESPACE::move(p.second); + return *this; + } + + pair& operator=(BOOST_MOVE_MACRO_RV_REF_2_TEMPL_ARGS(std::pair, T1, T2) p) + { + first = BOOST_CONTAINER_MOVE_NAMESPACE::move(p.first); + second = BOOST_CONTAINER_MOVE_NAMESPACE::move(p.second); + return *this; + } + + template + pair& operator=(BOOST_MOVE_MACRO_RV_REF_2_TEMPL_ARGS(std::pair, D, S) p) + { + first = BOOST_CONTAINER_MOVE_NAMESPACE::move(p.first); + second = BOOST_CONTAINER_MOVE_NAMESPACE::move(p.second); + return *this; + } + + void swap(pair& p) + { std::swap(*this, p); } +}; + +template +inline bool operator==(const pair& x, const pair& y) +{ return static_cast(x.first == y.first && x.second == y.second); } + +template +inline bool operator< (const pair& x, const pair& y) +{ return static_cast(x.first < y.first || + (!(y.first < x.first) && x.second < y.second)); } + +template +inline bool operator!=(const pair& x, const pair& y) +{ return static_cast(!(x == y)); } + +template +inline bool operator> (const pair& x, const pair& y) +{ return y < x; } + +template +inline bool operator>=(const pair& x, const pair& y) +{ return static_cast(!(x < y)); } + +template +inline bool operator<=(const pair& x, const pair& y) +{ return static_cast(!(y < x)); } + +template +inline pair make_pair(T1 x, T2 y) +{ return pair(x, y); } + +template +inline void swap(pair& x, pair& y) +{ + swap(x.first, y.first); + swap(x.second, y.second); +} + +} //namespace containers_detail { +} //namespace container { + + +//Without this specialization recursive flat_(multi)map instantiation fails +//because is_enum needs to instantiate the recursive pair, leading to a compilation error). +//This breaks the cycle clearly stating that pair is not an enum avoiding any instantiation. +template +struct is_enum; + +template +struct is_enum< ::boost::container::containers_detail::pair > +{ + static const bool value = false; +}; + +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_PAIR_HPP diff --git a/utils/boost_idb/boost/container/detail/pool_common.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/pool_common.hpp similarity index 79% rename from utils/boost_idb/boost/container/detail/pool_common.hpp rename to utils/boost_idb/boost/interprocess/containers/container/detail/pool_common.hpp index 6ab2d439..c6241bfa 100644 --- a/utils/boost_idb/boost/container/detail/pool_common.hpp +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/pool_common.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,7 +11,7 @@ #ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_COMMON_HPP #define BOOST_CONTAINER_DETAIL_NODE_POOL_COMMON_HPP -#if defined(_MSC_VER) +#if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif @@ -21,7 +21,7 @@ namespace boost { namespace container { -namespace container_detail { +namespace containers_detail { template struct node_slist @@ -34,7 +34,7 @@ struct node_slist typedef slist_hook_t node_t; typedef typename bi::make_slist - , bi::cache_last, bi::base_hook >::type node_slist_t; + , bi::base_hook >::type node_slist_t; }; template @@ -43,10 +43,10 @@ struct is_stateless_segment_manager static const bool value = false; }; -} //namespace container_detail { +} //namespace containers_detail { } //namespace container { } //namespace boost { -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP #endif //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_IMPL_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/preprocessor.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/preprocessor.hpp new file mode 100644 index 00000000..2f32aefa --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/preprocessor.hpp @@ -0,0 +1,141 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_PREPROCESSOR_HPP +#define BOOST_CONTAINERS_DETAIL_PREPROCESSOR_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" + +#ifndef BOOST_NO_RVALUE_REFERENCES +#include INCLUDE_BOOST_CONTAINER_DETAIL_STORED_REF_HPP +#endif + +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING +#error "This file is not needed when perfect forwarding is available" +#endif + +#include +#include +#include +#include +#include + +#define BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS 10 + +//Note: +//We define template parameters as const references to +//be able to bind temporaries. After that we will un-const them. +//This cast is ugly but it is necessary until "perfect forwarding" +//is achieved in C++0x. Meanwhile, if we want to be able to +//bind rvalues with non-const references, we have to be ugly +#ifndef BOOST_NO_RVALUE_REFERENCES + #define BOOST_CONTAINERS_PP_PARAM_LIST(z, n, data) \ + BOOST_PP_CAT(P, n) && BOOST_PP_CAT(p, n) \ + //! +#else + #define BOOST_CONTAINERS_PP_PARAM_LIST(z, n, data) \ + const BOOST_PP_CAT(P, n) & BOOST_PP_CAT(p, n) \ + //! +#endif + +#ifndef BOOST_NO_RVALUE_REFERENCES + #define BOOST_CONTAINERS_PARAM(U, u) \ + U && u \ + //! +#else + #define BOOST_CONTAINERS_PARAM(U, u) \ + const U & u \ + //! +#endif + +#ifndef BOOST_NO_RVALUE_REFERENCES + +#ifdef BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES + +#define BOOST_CONTAINERS_AUX_PARAM_INIT(z, n, data) \ + BOOST_PP_CAT(m_p, n) (BOOST_CONTAINER_MOVE_NAMESPACE::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) )) \ +//! + +#else + +#define BOOST_CONTAINERS_AUX_PARAM_INIT(z, n, data) \ + BOOST_PP_CAT(m_p, n) (static_cast( BOOST_PP_CAT(p, n) )) \ +//! + +#endif + +#else +#define BOOST_CONTAINERS_AUX_PARAM_INIT(z, n, data) \ + BOOST_PP_CAT(m_p, n) (const_cast(BOOST_PP_CAT(p, n))) \ +//! +#endif + +#define BOOST_CONTAINERS_AUX_PARAM_INC(z, n, data) \ + BOOST_PP_CAT(++m_p, n) \ +//! + +#ifndef BOOST_NO_RVALUE_REFERENCES + +#if defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) + +#define BOOST_CONTAINERS_AUX_PARAM_DEFINE(z, n, data) \ + BOOST_PP_CAT(P, n) & BOOST_PP_CAT(m_p, n); \ +//! + +#else + +#define BOOST_CONTAINERS_AUX_PARAM_DEFINE(z, n, data) \ + BOOST_PP_CAT(P, n) && BOOST_PP_CAT(m_p, n); \ +//! + +#endif //defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) + + +#else +#define BOOST_CONTAINERS_AUX_PARAM_DEFINE(z, n, data) \ + BOOST_PP_CAT(P, n) & BOOST_PP_CAT(m_p, n); \ +//! +#endif + +#define BOOST_CONTAINERS_PP_PARAM_FORWARD(z, n, data) \ +BOOST_CONTAINER_MOVE_NAMESPACE::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) ) \ +//! + +#if !defined(BOOST_NO_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) + +#define BOOST_CONTAINERS_PP_MEMBER_FORWARD(z, n, data) \ +::boost::container::containers_detail::stored_ref< BOOST_PP_CAT(P, n) >::forward( BOOST_PP_CAT(m_p, n) ) \ +//! + +#else + +#define BOOST_CONTAINERS_PP_MEMBER_FORWARD(z, n, data) \ +BOOST_CONTAINER_MOVE_NAMESPACE::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(m_p, n) ) \ +//! + +#endif //!defined(BOOST_NO_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) + +#define BOOST_CONTAINERS_PP_MEMBER_IT_FORWARD(z, n, data) \ +BOOST_PP_CAT(*m_p, n) \ +//! + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#else +#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING +#error "This file is not needed when perfect forwarding is available" +#endif +#endif //#ifndef BOOST_CONTAINERS_DETAIL_PREPROCESSOR_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/stored_ref.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/stored_ref.hpp new file mode 100644 index 00000000..965b7388 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/stored_ref.hpp @@ -0,0 +1,92 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_STORED_REF_HPP +#define BOOST_CONTAINERS_DETAIL_STORED_REF_HPP + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#ifndef BOOST_NO_RVALUE_REFERENCES + +namespace boost{ +namespace container{ +namespace containers_detail{ + +template +struct stored_ref +{ + + static T && forward(T &t) + #ifdef BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES + { return t; } + #else + { return BOOST_CONTAINER_MOVE_NAMESPACE::move(t); } + #endif +}; + +template +struct stored_ref +{ + static const T && forward(const T &t) + #ifdef BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES + { return t; } + #else + { return static_cast(t); } + #endif +}; + +template +struct stored_ref +{ + static T && forward(T &t) + #ifdef BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES + { return t; } + #else + { return BOOST_CONTAINER_MOVE_NAMESPACE::move(t); } + #endif +}; + +template +struct stored_ref +{ + static const T && forward(const T &t) + #ifdef BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES + { return t; } + #else + { return static_cast(t); } + #endif +}; + +template +struct stored_ref +{ + static const T & forward(const T &t) + { return t; } +}; + +template +struct stored_ref +{ + static T & forward(T &t) + { return t; } +}; + +} //namespace containers_detail{ +} //namespace container{ +} //namespace boost{ + +#else +#error "This header can be included only for compiler with rvalue references" +#endif //BOOST_NO_RVALUE_REFERENCES + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //BOOST_CONTAINERS_DETAIL_STORED_REF_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/transform_iterator.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/transform_iterator.hpp new file mode 100644 index 00000000..96ea1459 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/transform_iterator.hpp @@ -0,0 +1,176 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// (C) Copyright Gennaro Prota 2003 - 2004. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_TRANSFORM_ITERATORS_HPP +#define BOOST_CONTAINERS_DETAIL_TRANSFORM_ITERATORS_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include + +namespace boost { +namespace container { + +template +struct operator_arrow_proxy +{ + operator_arrow_proxy(const PseudoReference &px) + : m_value(px) + {} + + PseudoReference* operator->() const { return &m_value; } + // This function is needed for MWCW and BCC, which won't call operator-> + // again automatically per 13.3.1.2 para 8 +// operator T*() const { return &m_value; } + mutable PseudoReference m_value; +}; + +template +struct operator_arrow_proxy +{ + operator_arrow_proxy(T &px) + : m_value(px) + {} + + T* operator->() const { return const_cast(&m_value); } + // This function is needed for MWCW and BCC, which won't call operator-> + // again automatically per 13.3.1.2 para 8 +// operator T*() const { return &m_value; } + T &m_value; +}; + +template +class transform_iterator + : public UnaryFunction + , public std::iterator + < typename Iterator::iterator_category + , typename containers_detail::remove_reference::type + , typename Iterator::difference_type + , operator_arrow_proxy + , typename UnaryFunction::result_type> +{ + public: + explicit transform_iterator(const Iterator &it, const UnaryFunction &f = UnaryFunction()) + : UnaryFunction(f), m_it(it) + {} + + explicit transform_iterator() + : UnaryFunction(), m_it() + {} + + //Constructors + transform_iterator& operator++() + { increment(); return *this; } + + transform_iterator operator++(int) + { + transform_iterator result (*this); + increment(); + return result; + } + + friend bool operator== (const transform_iterator& i, const transform_iterator& i2) + { return i.equal(i2); } + + friend bool operator!= (const transform_iterator& i, const transform_iterator& i2) + { return !(i == i2); } + +/* + friend bool operator> (const transform_iterator& i, const transform_iterator& i2) + { return i2 < i; } + + friend bool operator<= (const transform_iterator& i, const transform_iterator& i2) + { return !(i > i2); } + + friend bool operator>= (const transform_iterator& i, const transform_iterator& i2) + { return !(i < i2); } +*/ + friend typename Iterator::difference_type operator- (const transform_iterator& i, const transform_iterator& i2) + { return i2.distance_to(i); } + + //Arithmetic + transform_iterator& operator+=(typename Iterator::difference_type off) + { this->advance(off); return *this; } + + transform_iterator operator+(typename Iterator::difference_type off) const + { + transform_iterator other(*this); + other.advance(off); + return other; + } + + friend transform_iterator operator+(typename Iterator::difference_type off, const transform_iterator& right) + { return right + off; } + + transform_iterator& operator-=(typename Iterator::difference_type off) + { this->advance(-off); return *this; } + + transform_iterator operator-(typename Iterator::difference_type off) const + { return *this + (-off); } + + typename UnaryFunction::result_type operator*() const + { return dereference(); } + + operator_arrow_proxy + operator->() const + { return operator_arrow_proxy(dereference()); } + + Iterator & base() + { return m_it; } + + const Iterator & base() const + { return m_it; } + + private: + Iterator m_it; + + void increment() + { ++m_it; } + + void decrement() + { --m_it; } + + bool equal(const transform_iterator &other) const + { return m_it == other.m_it; } + + bool less(const transform_iterator &other) const + { return other.m_it < m_it; } + + typename UnaryFunction::result_type dereference() const + { return UnaryFunction::operator()(*m_it); } + + void advance(typename Iterator::difference_type n) + { std::advance(m_it, n); } + + typename Iterator::difference_type distance_to(const transform_iterator &other)const + { return std::distance(other.m_it, m_it); } +}; + +template +transform_iterator +make_transform_iterator(Iterator it, UnaryFunc fun) +{ + return transform_iterator(it, fun); +} + +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_TRANSFORM_ITERATORS_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/tree.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/tree.hpp new file mode 100644 index 00000000..bf0d1f42 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/tree.hpp @@ -0,0 +1,1035 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_TREE_HPP +#define BOOST_CONTAINERS_TREE_HPP + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP + +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include +#include +#include +#include + +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_NODE_ALLOC_HOLDER_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_DESTROYERS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_PAIR_HPP +#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +#include //std::pair +#include +#include + +namespace boost { +namespace container { +namespace containers_detail { + +template +struct value_compare_impl + : public KeyCompare +{ + typedef Value value_type; + typedef KeyCompare key_compare; + typedef KeyOfValue key_of_value; + typedef Key key_type; + + value_compare_impl(key_compare kcomp) + : key_compare(kcomp) + {} + + const key_compare &key_comp() const + { return static_cast(*this); } + + key_compare &key_comp() + { return static_cast(*this); } + + template + bool operator()(const A &a, const B &b) const + { return key_compare::operator()(KeyOfValue()(a), KeyOfValue()(b)); } +}; + +template +struct rbtree_hook +{ + typedef typename containers_detail::bi::make_set_base_hook + < containers_detail::bi::void_pointer + , containers_detail::bi::link_mode + , containers_detail::bi::optimize_size + >::type type; +}; + +template +struct rbtree_type +{ + typedef T type; +}; + +template +struct rbtree_type< std::pair > +{ + typedef pair type; +}; + +template +struct rbtree_node + : public rbtree_hook::type +{ + typedef typename rbtree_hook::type hook_type; + + typedef T value_type; + typedef typename rbtree_type::type internal_type; + + typedef rbtree_node node_type; + + #ifndef BOOST_CONTAINERS_PERFECT_FORWARDING + + rbtree_node() + : m_data() + {} + + rbtree_node(const rbtree_node &other) + : m_data(other.m_data) + {} + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + rbtree_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + : m_data(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)) \ + {} \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #else //#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING + + rbtree_node() + : m_data() + {} + + template + rbtree_node(Args &&...args) + : m_data(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...) + {} + #endif//#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING + + rbtree_node &operator=(const rbtree_node &other) + { do_assign(other.m_data); return *this; } + + T &get_data() + { + T* ptr = reinterpret_cast(&this->m_data); + return *ptr; + } + + const T &get_data() const + { + const T* ptr = reinterpret_cast(&this->m_data); + return *ptr; + } + + private: + internal_type m_data; + + template + void do_assign(const std::pair &p) + { + const_cast(m_data.first) = p.first; + m_data.second = p.second; + } + + template + void do_assign(const pair &p) + { + const_cast(m_data.first) = p.first; + m_data.second = p.second; + } + + template + void do_assign(const V &v) + { m_data = v; } + + public: + template + static void construct(node_type *ptr, BOOST_MOVE_MACRO_FWD_REF(Convertible) convertible) + { new(ptr) node_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(convertible)); } +}; + +}//namespace containers_detail { +#if defined(BOOST_NO_RVALUE_REFERENCES) +template +struct has_own_construct_from_it + < boost::container::containers_detail::rbtree_node > +{ + static const bool value = true; +}; +#endif +namespace containers_detail { + +template +struct intrusive_rbtree_type +{ + typedef typename A::value_type value_type; + typedef typename boost::pointer_to_other + ::type void_pointer; + typedef typename containers_detail::rbtree_node + node_type; + typedef node_compare node_compare_type; + typedef typename containers_detail::bi::make_rbtree + + ,containers_detail::bi::base_hook::type> + ,containers_detail::bi::constant_time_size + ,containers_detail::bi::size_type + >::type container_type; + typedef container_type type ; +}; + +} //namespace containers_detail { + +namespace containers_detail { + +template +class rbtree + : protected containers_detail::node_alloc_holder + + >::type + > +{ + typedef typename containers_detail::intrusive_rbtree_type + + >::type Icont; + typedef containers_detail::node_alloc_holder AllocHolder; + typedef typename AllocHolder::NodePtr NodePtr; + typedef rbtree < Key, Value, KeyOfValue + , KeyCompare, A> ThisType; + typedef typename AllocHolder::NodeAlloc NodeAlloc; + typedef typename AllocHolder::ValAlloc ValAlloc; + typedef typename AllocHolder::Node Node; + typedef typename Icont::iterator iiterator; + typedef typename Icont::const_iterator iconst_iterator; + typedef containers_detail::allocator_destroyer Destroyer; + typedef typename AllocHolder::allocator_v1 allocator_v1; + typedef typename AllocHolder::allocator_v2 allocator_v2; + typedef typename AllocHolder::alloc_version alloc_version; + + class RecyclingCloner; + friend class RecyclingCloner; + + class RecyclingCloner + { + public: + RecyclingCloner(AllocHolder &holder, Icont &irbtree) + : m_holder(holder), m_icont(irbtree) + {} + + NodePtr operator()(const Node &other) const + { +// if(!m_icont.empty()){ + if(NodePtr p = m_icont.unlink_leftmost_without_rebalance()){ + //First recycle a node (this can't throw) + //NodePtr p = m_icont.unlink_leftmost_without_rebalance(); + try{ + //This can throw + *p = other; + return p; + } + catch(...){ + //If there is an exception destroy the whole source + m_holder.destroy_node(p); + while((p = m_icont.unlink_leftmost_without_rebalance())){ + m_holder.destroy_node(p); + } + throw; + } + } + else{ + return m_holder.create_node(other); + } + } + + AllocHolder &m_holder; + Icont &m_icont; + }; + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(rbtree) + + public: + + typedef Key key_type; + typedef Value value_type; + typedef A allocator_type; + typedef KeyCompare key_compare; + typedef value_compare_impl< Key, Value + , KeyCompare, KeyOfValue> value_compare; + typedef typename A::pointer pointer; + typedef typename A::const_pointer const_pointer; + typedef typename A::reference reference; + typedef typename A::const_reference const_reference; + typedef typename A::size_type size_type; + typedef typename A::difference_type difference_type; + typedef difference_type rbtree_difference_type; + typedef pointer rbtree_pointer; + typedef const_pointer rbtree_const_pointer; + typedef reference rbtree_reference; + typedef const_reference rbtree_const_reference; + typedef NodeAlloc stored_allocator_type; + + private: + + template + struct key_node_compare + : private KeyValueCompare + { + key_node_compare(KeyValueCompare comp) + : KeyValueCompare(comp) + {} + + template + bool operator()(const Node &n, const KeyType &k) const + { return KeyValueCompare::operator()(n.get_data(), k); } + + template + bool operator()(const KeyType &k, const Node &n) const + { return KeyValueCompare::operator()(k, n.get_data()); } + }; + + typedef key_node_compare KeyNodeCompare; + + public: + //rbtree const_iterator + class const_iterator + : public std::iterator + < std::bidirectional_iterator_tag + , value_type , rbtree_difference_type + , rbtree_const_pointer , rbtree_const_reference> + { + protected: + typedef typename Icont::iterator iiterator; + iiterator m_it; + explicit const_iterator(iiterator it) : m_it(it){} + void prot_incr() { ++m_it; } + void prot_decr() { --m_it; } + + private: + iiterator get() + { return this->m_it; } + + public: + friend class rbtree ; + typedef rbtree_difference_type difference_type; + + //Constructors + const_iterator() + : m_it() + {} + + //Pointer like operators + const_reference operator*() const + { return m_it->get_data(); } + + const_pointer operator->() const + { return const_pointer(&m_it->get_data()); } + + //Increment / Decrement + const_iterator& operator++() + { prot_incr(); return *this; } + + const_iterator operator++(int) + { iiterator tmp = m_it; ++*this; return const_iterator(tmp); } + + const_iterator& operator--() + { prot_decr(); return *this; } + + const_iterator operator--(int) + { iiterator tmp = m_it; --*this; return const_iterator(tmp); } + + //Comparison operators + bool operator== (const const_iterator& r) const + { return m_it == r.m_it; } + + bool operator!= (const const_iterator& r) const + { return m_it != r.m_it; } + }; + + //rbtree iterator + class iterator : public const_iterator + { + private: + explicit iterator(iiterator it) + : const_iterator(it) + {} + + iiterator get() + { return this->m_it; } + + public: + friend class rbtree ; + typedef rbtree_pointer pointer; + typedef rbtree_reference reference; + + //Constructors + iterator(){} + + //Pointer like operators + reference operator*() const { return this->m_it->get_data(); } + pointer operator->() const { return pointer(&this->m_it->get_data()); } + + //Increment / Decrement + iterator& operator++() + { this->prot_incr(); return *this; } + + iterator operator++(int) + { iiterator tmp = this->m_it; ++*this; return iterator(tmp); } + + iterator& operator--() + { this->prot_decr(); return *this; } + + iterator operator--(int) + { iterator tmp = *this; --*this; return tmp; } + }; + + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; + + rbtree(const key_compare& comp = key_compare(), + const allocator_type& a = allocator_type()) + : AllocHolder(a, comp) + {} + + template + rbtree(InputIterator first, InputIterator last, const key_compare& comp, + const allocator_type& a, bool unique_insertion) + : AllocHolder(a, comp) + { + typedef typename std::iterator_traits::iterator_category ItCat; + priv_create_and_insert_nodes(first, last, unique_insertion, alloc_version(), ItCat()); + } + + template + rbtree( ordered_range_t, InputIterator first, InputIterator last + , const key_compare& comp = key_compare(), const allocator_type& a = allocator_type()) + : AllocHolder(a, comp) + { + typedef typename std::iterator_traits::iterator_category ItCat; + priv_create_and_insert_ordered_nodes(first, last, alloc_version(), ItCat()); + } + + rbtree(const rbtree& x) + : AllocHolder(x, x.key_comp()) + { + this->icont().clone_from + (x.icont(), typename AllocHolder::cloner(*this), Destroyer(this->node_alloc())); + } + + rbtree(BOOST_MOVE_MACRO_RV_REF(rbtree) x) + : AllocHolder(x, x.key_comp()) + { this->swap(x); } + + ~rbtree() + {} //AllocHolder clears the tree + + rbtree& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(rbtree) x) + { + if (this != &x) { + //Transfer all the nodes to a temporary tree + //If anything goes wrong, all the nodes will be destroyed + //automatically + Icont other_tree(this->icont().value_comp()); + other_tree.swap(this->icont()); + + //Now recreate the source tree reusing nodes stored by other_tree + this->icont().clone_from + (x.icont() + , RecyclingCloner(*this, other_tree) + //, AllocHolder::cloner(*this) + , Destroyer(this->node_alloc())); + + //If there are remaining nodes, destroy them + NodePtr p; + while((p = other_tree.unlink_leftmost_without_rebalance())){ + AllocHolder::destroy_node(p); + } + } + return *this; + } + + rbtree& operator=(BOOST_MOVE_MACRO_RV_REF(rbtree) mx) + { this->clear(); this->swap(mx); return *this; } + + public: + // accessors: + value_compare value_comp() const + { return this->icont().value_comp().value_comp(); } + + key_compare key_comp() const + { return this->icont().value_comp().value_comp().key_comp(); } + + allocator_type get_allocator() const + { return allocator_type(this->node_alloc()); } + + const stored_allocator_type &get_stored_allocator() const + { return this->node_alloc(); } + + stored_allocator_type &get_stored_allocator() + { return this->node_alloc(); } + + iterator begin() + { return iterator(this->icont().begin()); } + + const_iterator begin() const + { return this->cbegin(); } + + iterator end() + { return iterator(this->icont().end()); } + + const_iterator end() const + { return this->cend(); } + + reverse_iterator rbegin() + { return reverse_iterator(end()); } + + const_reverse_iterator rbegin() const + { return this->crbegin(); } + + reverse_iterator rend() + { return reverse_iterator(begin()); } + + const_reverse_iterator rend() const + { return this->crend(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return const_iterator(this->non_const_icont().begin()); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return const_iterator(this->non_const_icont().end()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return const_reverse_iterator(cend()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return const_reverse_iterator(cbegin()); } + + bool empty() const + { return !this->size(); } + + size_type size() const + { return this->icont().size(); } + + size_type max_size() const + { return AllocHolder::max_size(); } + + void swap(ThisType& x) + { AllocHolder::swap(x); } + + public: + + typedef typename Icont::insert_commit_data insert_commit_data; + + // insert/erase + std::pair insert_unique_check + (const key_type& key, insert_commit_data &data) + { + std::pair ret = + this->icont().insert_unique_check(key, KeyNodeCompare(value_comp()), data); + return std::pair(iterator(ret.first), ret.second); + } + + std::pair insert_unique_check + (const_iterator hint, const key_type& key, insert_commit_data &data) + { + std::pair ret = + this->icont().insert_unique_check(hint.get(), key, KeyNodeCompare(value_comp()), data); + return std::pair(iterator(ret.first), ret.second); + } + + iterator insert_unique_commit(const value_type& v, insert_commit_data &data) + { + NodePtr tmp = AllocHolder::create_node(v); + iiterator it(this->icont().insert_unique_commit(*tmp, data)); + return iterator(it); + } + + template + iterator insert_unique_commit + (BOOST_MOVE_MACRO_FWD_REF(MovableConvertible) mv, insert_commit_data &data) + { + NodePtr tmp = AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(mv)); + iiterator it(this->icont().insert_unique_commit(*tmp, data)); + return iterator(it); + } + + std::pair insert_unique(const value_type& v) + { + insert_commit_data data; + std::pair ret = + this->insert_unique_check(KeyOfValue()(v), data); + if(!ret.second) + return ret; + return std::pair + (this->insert_unique_commit(v, data), true); + } + + template + std::pair insert_unique(BOOST_MOVE_MACRO_FWD_REF(MovableConvertible) mv) + { + insert_commit_data data; + std::pair ret = + this->insert_unique_check(KeyOfValue()(mv), data); + if(!ret.second) + return ret; + return std::pair + (this->insert_unique_commit(BOOST_CONTAINER_MOVE_NAMESPACE::forward(mv), data), true); + } + + private: + iterator emplace_unique_impl(NodePtr p) + { + value_type &v = p->get_data(); + insert_commit_data data; + std::pair ret = + this->insert_unique_check(KeyOfValue()(v), data); + if(!ret.second){ + Destroyer(this->node_alloc())(p); + return ret.first; + } + return iterator(iiterator(this->icont().insert_unique_commit(*p, data))); + } + + iterator emplace_unique_hint_impl(const_iterator hint, NodePtr p) + { + value_type &v = p->get_data(); + insert_commit_data data; + std::pair ret = + this->insert_unique_check(hint, KeyOfValue()(v), data); + if(!ret.second){ + Destroyer(this->node_alloc())(p); + return ret.first; + } + return iterator(iiterator(this->icont().insert_unique_commit(*p, data))); + } + + public: + + #ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + template + iterator emplace_unique(Args&&... args) + { return this->emplace_unique_impl(AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); } + + template + iterator emplace_hint_unique(const_iterator hint, Args&&... args) + { return this->emplace_unique_hint_impl(hint, AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); } + + template + iterator emplace_equal(Args&&... args) + { + NodePtr p(AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); + return iterator(this->icont().insert_equal(this->icont().end(), *p)); + } + + template + iterator emplace_hint_equal(const_iterator hint, Args&&... args) + { + NodePtr p(AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); + return iterator(this->icont().insert_equal(hint.get(), *p)); + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace_unique() + { return this->emplace_unique_impl(AllocHolder::create_node()); } + + iterator emplace_hint_unique(const_iterator hint) + { return this->emplace_unique_hint_impl(hint, AllocHolder::create_node()); } + + iterator emplace_equal() + { + NodePtr p(AllocHolder::create_node()); + return iterator(this->icont().insert_equal(this->icont().end(), *p)); + } + + iterator emplace_hint_equal(const_iterator hint) + { + NodePtr p(AllocHolder::create_node()); + return iterator(this->icont().insert_equal(hint.get(), *p)); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return this->emplace_unique_impl \ + (AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + } \ + \ + template \ + iterator emplace_hint_unique(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return this->emplace_unique_hint_impl \ + (hint, AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + } \ + \ + template \ + iterator emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + NodePtr p(AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + return iterator(this->icont().insert_equal(this->icont().end(), *p)); \ + } \ + \ + template \ + iterator emplace_hint_equal(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + NodePtr p(AllocHolder::create_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + return iterator(this->icont().insert_equal(hint.get(), *p)); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator insert_unique(const_iterator hint, const value_type& v) + { + insert_commit_data data; + std::pair ret = + this->insert_unique_check(hint, KeyOfValue()(v), data); + if(!ret.second) + return ret.first; + return this->insert_unique_commit(v, data); + } + + template + iterator insert_unique(const_iterator hint, BOOST_MOVE_MACRO_FWD_REF(MovableConvertible) mv) + { + insert_commit_data data; + std::pair ret = + this->insert_unique_check(hint, KeyOfValue()(mv), data); + if(!ret.second) + return ret.first; + return this->insert_unique_commit(BOOST_CONTAINER_MOVE_NAMESPACE::forward(mv), data); + } + + template + void insert_unique(InputIterator first, InputIterator last) + { + if(this->empty()){ + //Insert with end hint, to achieve linear + //complexity if [first, last) is ordered + const_iterator end(this->end()); + for( ; first != last; ++first) + this->insert_unique(end, *first); + } + else{ + for( ; first != last; ++first) + this->insert_unique(*first); + } + } + + iterator insert_equal(const value_type& v) + { + NodePtr p(AllocHolder::create_node(v)); + return iterator(this->icont().insert_equal(this->icont().end(), *p)); + } + + template + iterator insert_equal(BOOST_MOVE_MACRO_FWD_REF(MovableConvertible) mv) + { + NodePtr p(AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(mv))); + return iterator(this->icont().insert_equal(this->icont().end(), *p)); + } + + iterator insert_equal(const_iterator hint, const value_type& v) + { + NodePtr p(AllocHolder::create_node(v)); + return iterator(this->icont().insert_equal(hint.get(), *p)); + } + + template + iterator insert_equal(const_iterator hint, BOOST_MOVE_MACRO_FWD_REF(MovableConvertible) mv) + { + NodePtr p(AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(mv))); + return iterator(this->icont().insert_equal(hint.get(), *p)); + } + + template + void insert_equal(InputIterator first, InputIterator last) + { + //Insert with end hint, to achieve linear + //complexity if [first, last) is ordered + const_iterator end(this->cend()); + for( ; first != last; ++first) + this->insert_equal(end, *first); + } + + iterator erase(const_iterator position) + { return iterator(this->icont().erase_and_dispose(position.get(), Destroyer(this->node_alloc()))); } + + size_type erase(const key_type& k) + { return AllocHolder::erase_key(k, KeyNodeCompare(value_comp()), alloc_version()); } + + iterator erase(const_iterator first, const_iterator last) + { return iterator(AllocHolder::erase_range(first.get(), last.get(), alloc_version())); } + + void clear() + { AllocHolder::clear(alloc_version()); } + + // set operations: + iterator find(const key_type& k) + { return iterator(this->icont().find(k, KeyNodeCompare(value_comp()))); } + + const_iterator find(const key_type& k) const + { return const_iterator(this->non_const_icont().find(k, KeyNodeCompare(value_comp()))); } + + size_type count(const key_type& k) const + { return size_type(this->icont().count(k, KeyNodeCompare(value_comp()))); } + + iterator lower_bound(const key_type& k) + { return iterator(this->icont().lower_bound(k, KeyNodeCompare(value_comp()))); } + + const_iterator lower_bound(const key_type& k) const + { return const_iterator(this->non_const_icont().lower_bound(k, KeyNodeCompare(value_comp()))); } + + iterator upper_bound(const key_type& k) + { return iterator(this->icont().upper_bound(k, KeyNodeCompare(value_comp()))); } + + const_iterator upper_bound(const key_type& k) const + { return const_iterator(this->non_const_icont().upper_bound(k, KeyNodeCompare(value_comp()))); } + + std::pair equal_range(const key_type& k) + { + std::pair ret = + this->icont().equal_range(k, KeyNodeCompare(value_comp())); + return std::pair(iterator(ret.first), iterator(ret.second)); + } + + std::pair equal_range(const key_type& k) const + { + std::pair ret = + this->non_const_icont().equal_range(k, KeyNodeCompare(value_comp())); + return std::pair + (const_iterator(ret.first), const_iterator(ret.second)); + } + + private: + //Iterator range version + template + void priv_create_and_insert_nodes + (InpIterator beg, InpIterator end, bool unique, allocator_v1, std::input_iterator_tag) + { + if(unique){ + for (; beg != end; ++beg){ + this->insert_unique(*beg); + } + } + else{ + for (; beg != end; ++beg){ + this->insert_equal(*beg); + } + } + } + + template + void priv_create_and_insert_nodes + (InpIterator beg, InpIterator end, bool unique, allocator_v2, std::input_iterator_tag) + { //Just forward to the default one + priv_create_and_insert_nodes(beg, end, unique, allocator_v1(), std::input_iterator_tag()); + } + + class insertion_functor; + friend class insertion_functor; + + class insertion_functor + { + Icont &icont_; + + public: + insertion_functor(Icont &icont) + : icont_(icont) + {} + + void operator()(Node &n) + { this->icont_.insert_equal(this->icont_.cend(), n); } + }; + + + template + void priv_create_and_insert_nodes + (FwdIterator beg, FwdIterator end, bool unique, allocator_v2, std::forward_iterator_tag) + { + if(beg != end){ + if(unique){ + priv_create_and_insert_nodes(beg, end, unique, allocator_v2(), std::input_iterator_tag()); + } + else{ + //Optimized allocation and construction + this->allocate_many_and_construct + (beg, std::distance(beg, end), insertion_functor(this->icont())); + } + } + } + + //Iterator range version + template + void priv_create_and_insert_ordered_nodes + (InpIterator beg, InpIterator end, allocator_v1, std::input_iterator_tag) + { + const_iterator cend_n(this->cend()); + for (; beg != end; ++beg){ + this->insert_before(cend_n, *beg); + } + } + + template + void priv_create_and_insert_ordered_nodes + (InpIterator beg, InpIterator end, allocator_v2, std::input_iterator_tag) + { //Just forward to the default one + priv_create_and_insert_ordered_nodes(beg, end, allocator_v1(), std::input_iterator_tag()); + } + + class back_insertion_functor; + friend class back_insertion_functor; + + class back_insertion_functor + { + Icont &icont_; + + public: + back_insertion_functor(Icont &icont) + : icont_(icont) + {} + + void operator()(Node &n) + { this->icont_.push_back(n); } + }; + + + template + void priv_create_and_insert_ordered_nodes + (FwdIterator beg, FwdIterator end, allocator_v2, std::forward_iterator_tag) + { + if(beg != end){ + //Optimized allocation and construction + this->allocate_many_and_construct + (beg, std::distance(beg, end), back_insertion_functor(this->icont())); + } + } +}; + +template +inline bool +operator==(const rbtree& x, + const rbtree& y) +{ + return x.size() == y.size() && + std::equal(x.begin(), x.end(), y.begin()); +} + +template +inline bool +operator<(const rbtree& x, + const rbtree& y) +{ + return std::lexicographical_compare(x.begin(), x.end(), + y.begin(), y.end()); +} + +template +inline bool +operator!=(const rbtree& x, + const rbtree& y) { + return !(x == y); +} + +template +inline bool +operator>(const rbtree& x, + const rbtree& y) { + return y < x; +} + +template +inline bool +operator<=(const rbtree& x, + const rbtree& y) { + return !(y < x); +} + +template +inline bool +operator>=(const rbtree& x, + const rbtree& y) { + return !(x < y); +} + + +template +inline void +swap(rbtree& x, + rbtree& y) +{ + x.swap(y); +} + +} //namespace containers_detail { +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move + > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //BOOST_CONTAINERS_TREE_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/type_traits.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/type_traits.hpp new file mode 100644 index 00000000..d2a93c63 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/type_traits.hpp @@ -0,0 +1,166 @@ +////////////////////////////////////////////////////////////////////////////// +// (C) Copyright John Maddock 2000. +// (C) Copyright Ion Gaztanaga 2005-2009. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +// The alignment_of implementation comes from John Maddock's boost::alignment_of code +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#define BOOST_CONTAINERS_CONTAINER_DETAIL_TYPE_TRAITS_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" + +namespace boost { +namespace container { +namespace containers_detail { + +struct nat{}; + +//boost::alignment_of yields to 10K lines of preprocessed code, so we +//need an alternative +template struct alignment_of; + +template +struct alignment_of_hack +{ + char c; + T t; + alignment_of_hack(); +}; + +template +struct alignment_logic +{ + enum{ value = A < S ? A : S }; +}; + +template< typename T > +struct alignment_of +{ + enum{ value = alignment_logic + < sizeof(alignment_of_hack) - sizeof(T) + , sizeof(T)>::value }; +}; + +//This is not standard, but should work with all compilers +union max_align +{ + char char_; + short short_; + int int_; + long long_; + #ifdef BOOST_HAS_LONG_LONG + long long long_long_; + #endif + float float_; + double double_; + long double long_double_; + void * void_ptr_; +}; + +template +struct remove_reference +{ + typedef T type; +}; + +template +struct remove_reference +{ + typedef T type; +}; + +template +struct is_reference +{ + enum { value = false }; +}; + +template +struct is_reference +{ + enum { value = true }; +}; + +template +struct is_pointer +{ + enum { value = false }; +}; + +template +struct is_pointer +{ + enum { value = true }; +}; + +template +struct add_reference +{ + typedef T& type; +}; + +template +struct add_reference +{ + typedef T& type; +}; + +template<> +struct add_reference +{ + typedef nat &type; +}; + +template<> +struct add_reference +{ + typedef const nat &type; +}; + +template +struct add_const_reference +{ typedef const T &type; }; + +template +struct add_const_reference +{ typedef T& type; }; + +template +struct is_same +{ + typedef char yes_type; + struct no_type + { + char padding[8]; + }; + + template + static yes_type is_same_tester(V*, V*); + static no_type is_same_tester(...); + + static T *t; + static U *u; + + static const bool value = sizeof(yes_type) == sizeof(is_same_tester(t,u)); +}; + +} // namespace containers_detail +} //namespace container { +} //namespace boost { + +#endif //#ifndef BOOST_CONTAINERS_CONTAINER_DETAIL_TYPE_TRAITS_HPP + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/utilities.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/utilities.hpp new file mode 100644 index 00000000..6bd5ab51 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/utilities.hpp @@ -0,0 +1,148 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_UTILITIES_HPP +#define BOOST_CONTAINERS_DETAIL_UTILITIES_HPP + +#include "config_begin.hpp" +#include +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include + +namespace boost { +namespace container { +namespace containers_detail { + +template +const T &max_value(const T &a, const T &b) +{ return a > b ? a : b; } + +template +const T &min_value(const T &a, const T &b) +{ return a < b ? a : b; } + +template +SizeType + get_next_capacity(const SizeType max_size + ,const SizeType capacity + ,const SizeType n) +{ +// if (n > max_size - capacity) +// throw std::length_error("get_next_capacity"); + + const SizeType m3 = max_size/3; + + if (capacity < m3) + return capacity + max_value(3*(capacity+1)/5, n); + + if (capacity < m3*2) + return capacity + max_value((capacity+1)/2, n); + + return max_size; +} + +template +struct smart_ptr_type +{ + typedef typename SmartPtr::value_type value_type; + typedef value_type *pointer; + static pointer get (const SmartPtr &smartptr) + { return smartptr.get();} +}; + +template +struct smart_ptr_type +{ + typedef T value_type; + typedef value_type *pointer; + static pointer get (pointer ptr) + { return ptr;} +}; + +//!Overload for smart pointers to avoid ADL problems with get_pointer +template +inline typename smart_ptr_type::pointer +get_pointer(const Ptr &ptr) +{ return smart_ptr_type::get(ptr); } + +//!To avoid ADL problems with swap +template +inline void do_swap(T& x, T& y) +{ + using std::swap; + swap(x, y); +} + +//Rounds "orig_size" by excess to round_to bytes +inline std::size_t get_rounded_size(std::size_t orig_size, std::size_t round_to) +{ + return ((orig_size-1)/round_to+1)*round_to; +} + +template +struct ct_rounded_size +{ + enum { value = ((OrigSize-1)/RoundTo+1)*RoundTo }; +}; + +template +struct __rw_is_enum +{ +struct _C_no { }; +struct _C_yes { int _C_dummy [2]; }; + +struct _C_indirect { +// prevent classes with user-defined conversions from matching + +// use double to prevent float->int gcc conversion warnings +_C_indirect (double); +}; + +// nested struct gets rid of bogus gcc errors +struct _C_nest { +// supply first argument to prevent HP aCC warnings +static _C_no _C_is (int, ...); +static _C_yes _C_is (int, _C_indirect); + +static _TypeT _C_make_T (); +}; + +enum { +_C_val = sizeof (_C_yes) +== sizeof (_C_nest::_C_is (0, _C_nest::_C_make_T ())) +&& !::boost::is_fundamental<_TypeT>::value +}; + +}; + +template +struct move_const_ref_type + : if_c + < ::boost::is_fundamental::value || ::boost::is_pointer::value || + ::boost::is_member_pointer::value || ::boost::is_enum::value + ,const T & + ,BOOST_MOVE_MACRO_CATCH_CONST_RLVALUE(T) + > +{}; + +} //namespace containers_detail { +} //namespace container { +} //namespace boost { + + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_UTILITIES_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/value_init.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/value_init.hpp new file mode 100644 index 00000000..e16db2c9 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/value_init.hpp @@ -0,0 +1,43 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_VALUE_INIT_HPP +#define BOOST_CONTAINERS_DETAIL_VALUE_INIT_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +namespace boost { +namespace container { +namespace containers_detail { + +template +struct value_init +{ + value_init() + : m_t() + {} + + T m_t; +}; + +} //namespace containers_detail { +} //namespace container { +} //namespace boost { + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_VALUE_INIT_HPP diff --git a/utils/boost_idb/boost/container/detail/variadic_templates_tools.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/variadic_templates_tools.hpp similarity index 87% rename from utils/boost_idb/boost/container/detail/variadic_templates_tools.hpp rename to utils/boost_idb/boost/interprocess/containers/container/detail/variadic_templates_tools.hpp index cce7fede..eb17470a 100644 --- a/utils/boost_idb/boost/container/detail/variadic_templates_tools.hpp +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/variadic_templates_tools.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,21 +8,21 @@ // ////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP -#define BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#ifndef BOOST_CONTAINERS_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#define BOOST_CONTAINERS_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP -#if defined(_MSC_VER) +#if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include "config_begin.hpp" -#include -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP #include //std::size_t namespace boost { -namespace container { -namespace container_detail { +namespace container { +namespace containers_detail { template class tuple; @@ -136,7 +136,7 @@ struct index_tuple{}; template > struct build_number_seq; -template +template struct build_number_seq > : build_number_seq > {}; @@ -146,8 +146,8 @@ struct build_number_seq<0, index_tuple > { typedef index_tuple type; }; -}}} //namespace boost { namespace container { namespace container_detail { +}}} //namespace boost { namespace container { namespace containers_detail { -#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP -#endif //#ifndef BOOST_CONTAINER_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP +#endif //#ifndef BOOST_CONTAINERS_DETAIL_VARIADIC_TEMPLATES_TOOLS_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/version_type.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/version_type.hpp new file mode 100644 index 00000000..8b23f413 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/version_type.hpp @@ -0,0 +1,91 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +// +// This code comes from N1953 document by Howard E. Hinnant +// +////////////////////////////////////////////////////////////////////////////// + + +#ifndef BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP +#define BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP + +#include "config_begin.hpp" + +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP + + +namespace boost{ +namespace container { +namespace containers_detail { + +//using namespace boost; + +template +struct version_type + : public containers_detail::integral_constant +{ + typedef T type; + + version_type(const version_type&); +}; + +namespace impl{ + +template , typename T::version>::value> +struct extract_version +{ + static const unsigned value = 1; +}; + +template +struct extract_version +{ + static const unsigned value = T::version::value; +}; + +template +struct has_version +{ + private: + struct two {char _[2];}; + template static two test(...); + template static char test(const typename U::version*); + public: + static const bool value = sizeof(test(0)) == 1; + void dummy(){} +}; + +template ::value> +struct version +{ + static const unsigned value = 1; +}; + +template +struct version +{ + static const unsigned value = extract_version::value; +}; + +} //namespace impl + +template +struct version + : public containers_detail::integral_constant::value> +{ +}; + +} //namespace containers_detail { +} //namespace container { +} //namespace boost{ + +#endif //#define BOOST_CONTAINERS_DETAIL_VERSION_TYPE_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/detail/workaround.hpp b/utils/boost_idb/boost/interprocess/containers/container/detail/workaround.hpp new file mode 100644 index 00000000..d16b590e --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/detail/workaround.hpp @@ -0,0 +1,24 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_DETAIL_WORKAROUND_HPP +#define BOOST_CONTAINERS_DETAIL_WORKAROUND_HPP + +#include "config_begin.hpp" + +#if !defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_NO_VARIADIC_TEMPLATES)\ + && !defined(BOOST_MOVE_MACRO_DISABLE_VARIADIC_TMPL) +#define BOOST_CONTAINERS_PERFECT_FORWARDING + +#endif + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //#ifndef BOOST_CONTAINERS_DETAIL_WORKAROUND_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/flat_map.hpp b/utils/boost_idb/boost/interprocess/containers/container/flat_map.hpp new file mode 100644 index 00000000..c40a827e --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/flat_map.hpp @@ -0,0 +1,1429 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_FLAT_MAP_HPP +#define BOOST_CONTAINERS_FLAT_MAP_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_FLAT_TREE_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +// Forward declarations of operators == and <, needed for friend declarations. +template +class flat_map; + +template +inline bool operator==(const flat_map& x, + const flat_map& y); + +template +inline bool operator<(const flat_map& x, + const flat_map& y); +/// @endcond + +//! A flat_map is a kind of associative container that supports unique keys (contains at +//! most one of each key value) and provides for fast retrieval of values of another +//! type T based on the keys. The flat_map class supports random-access iterators. +//! +//! A flat_map satisfies all of the requirements of a container and of a reversible +//! container and of an associative container. A flat_map also provides +//! most operations described for unique keys. For a +//! flat_map the key_type is Key and the value_type is std::pair +//! (unlike std::map which value_type is std::pair<const Key, T>). +//! +//! Pred is the ordering function for Keys (e.g. std::less). +//! +//! Alloc is the allocator to allocate the value_types +//! (e.g. allocator< std::pair >). +//! +//! flat_map is similar to std::map but it's implemented like an ordered vector. +//! This means that inserting a new element into a flat_map invalidates +//! previous iterators and references +//! +//! Erasing an element of a flat_map invalidates iterators and references +//! pointing to elements that come after (their keys are bigger) the erased element. +template +class flat_map +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(flat_map) + //This is the tree that we should store if pair was movable + typedef containers_detail::flat_tree, + containers_detail::select1st< std::pair >, + Pred, + Alloc> tree_t; + + //This is the real tree stored here. It's based on a movable pair + typedef containers_detail::flat_tree, + containers_detail::select1st >, + Pred, + typename Alloc::template + rebind >::other> impl_tree_t; + impl_tree_t m_flat_tree; // flat tree representing flat_map + + typedef typename impl_tree_t::value_type impl_value_type; + typedef typename impl_tree_t::pointer impl_pointer; + typedef typename impl_tree_t::const_pointer impl_const_pointer; + typedef typename impl_tree_t::reference impl_reference; + typedef typename impl_tree_t::const_reference impl_const_reference; + typedef typename impl_tree_t::value_compare impl_value_compare; + typedef typename impl_tree_t::iterator impl_iterator; + typedef typename impl_tree_t::const_iterator impl_const_iterator; + typedef typename impl_tree_t::reverse_iterator impl_reverse_iterator; + typedef typename impl_tree_t::const_reverse_iterator impl_const_reverse_iterator; + typedef typename impl_tree_t::allocator_type impl_allocator_type; + + template + static D &force(const S &s) + { return *const_cast(reinterpret_cast(&s)); } + + template + static D force_copy(S s) + { + value_type *vp = reinterpret_cast(&*s); + return D(vp); + } + + /// @endcond + + public: + + // typedefs: + typedef typename impl_tree_t::key_type key_type; + typedef T mapped_type; + typedef typename std::pair value_type; + typedef typename Alloc::pointer pointer; + typedef typename Alloc::const_pointer const_pointer; + typedef typename Alloc::reference reference; + typedef typename Alloc::const_reference const_reference; + typedef containers_detail::flat_tree_value_compare + < Pred + , containers_detail::select1st< std::pair > + , std::pair > value_compare; + typedef Pred key_compare; + typedef typename containers_detail:: + get_flat_tree_iterators::iterator iterator; + typedef typename containers_detail:: + get_flat_tree_iterators::const_iterator const_iterator; + typedef typename containers_detail:: + get_flat_tree_iterators + ::reverse_iterator reverse_iterator; + typedef typename containers_detail:: + get_flat_tree_iterators + ::const_reverse_iterator const_reverse_iterator; + typedef typename impl_tree_t::size_type size_type; + typedef typename impl_tree_t::difference_type difference_type; + typedef Alloc allocator_type; + typedef Alloc stored_allocator_type; + + //! Effects: Constructs an empty flat_map using the specified + //! comparison object and allocator. + //! + //! Complexity: Constant. + explicit flat_map(const Pred& comp = Pred(), const allocator_type& a = allocator_type()) + : m_flat_tree(comp, force(a)) {} + + //! Effects: Constructs an empty flat_map using the specified comparison object and + //! allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + flat_map(InputIterator first, InputIterator last, const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, force(a)) + { m_flat_tree.insert_unique(first, last); } + + //! Effects: Constructs an empty flat_map using the specified comparison object and + //! allocator, and inserts elements from the ordered unique range [first ,last). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate and must be + //! unique values. + //! + //! Complexity: Linear in N. + template + flat_map( ordered_unique_range_t, InputIterator first, InputIterator last + , const Pred& comp = Pred(), const allocator_type& a = allocator_type()) + : m_flat_tree(ordered_range, first, last, comp, a) + {} + + //! Effects: Copy constructs a flat_map. + //! + //! Complexity: Linear in x.size(). + flat_map(const flat_map& x) + : m_flat_tree(x.m_flat_tree) {} + + //! Effects: Move constructs a flat_map. + //! Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + flat_map(BOOST_MOVE_MACRO_RV_REF(flat_map) x) + : m_flat_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_flat_tree)) + {} + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + flat_map& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(flat_map) x) + { m_flat_tree = x.m_flat_tree; return *this; } + + //! Effects: Move constructs a flat_map. + //! Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + flat_map& operator=(BOOST_MOVE_MACRO_RV_REF(flat_map) mx) + { m_flat_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(mx.m_flat_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return force(m_flat_tree.key_comp()); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return value_compare(force(m_flat_tree.key_comp())); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return force(m_flat_tree.get_allocator()); } + + const stored_allocator_type &get_stored_allocator() const + { return force(m_flat_tree.get_stored_allocator()); } + + stored_allocator_type &get_stored_allocator() + { return force(m_flat_tree.get_stored_allocator()); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return force_copy(m_flat_tree.begin()); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return force(m_flat_tree.begin()); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return force(m_flat_tree.cbegin()); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return force_copy(m_flat_tree.end()); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return force(m_flat_tree.end()); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return force(m_flat_tree.cend()); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return force(m_flat_tree.rbegin()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return force(m_flat_tree.rbegin()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return force(m_flat_tree.crbegin()); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return force(m_flat_tree.rend()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return force(m_flat_tree.rend()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return force(m_flat_tree.crend()); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_flat_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_flat_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_flat_tree.max_size(); } + + //! Effects: If there is no key equivalent to x in the flat_map, inserts + //! value_type(x, T()) into the flat_map. + //! + //! Returns: A reference to the mapped_type corresponding to x in *this. + //! + //! Complexity: Logarithmic. + T &operator[](const key_type& k) + { + iterator i = lower_bound(k); + // i->first is greater than or equivalent to k. + if (i == end() || key_comp()(k, (*i).first)) + i = insert(i, value_type(k, T())); + return (*i).second; + } + + //! Effects: If there is no key equivalent to x in the flat_map, inserts + //! value_type(move(x), T()) into the flat_map (the key is move-constructed) + //! + //! Returns: A reference to the mapped_type corresponding to x in *this. + //! + //! Complexity: Logarithmic. + T &operator[](BOOST_MOVE_MACRO_RV_REF(key_type) mk) + { + key_type &k = mk; + iterator i = lower_bound(k); + // i->first is greater than or equivalent to k. + if (i == end() || key_comp()(k, (*i).first)) + i = insert(i, value_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(k), BOOST_CONTAINER_MOVE_NAMESPACE::move(T()))); + return (*i).second; + } + + //! Returns: A reference to the element whose key is equivalent to x. + //! Throws: An exception object of type out_of_range if no such element is present. + //! Complexity: logarithmic. + T& at(const key_type& k) + { + iterator i = this->find(k); + if(i == this->end()){ + throw std::out_of_range("key not found"); + } + return i->second; + } + + //! Returns: A reference to the element whose key is equivalent to x. + //! Throws: An exception object of type out_of_range if no such element is present. + //! Complexity: logarithmic. + const T& at(const key_type& k) const + { + const_iterator i = this->find(k); + if(i == this->end()){ + throw std::out_of_range("key not found"); + } + return i->second; + } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(flat_map& x) + { m_flat_tree.swap(x.m_flat_tree); } + + //! Effects: Inserts x if and only if there is no element in the container + //! with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + std::pair insert(const value_type& x) + { return force >( + m_flat_tree.insert_unique(force(x))); } + + //! Effects: Inserts a new value_type move constructed from the pair if and + //! only if there is no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return force >( + m_flat_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(force(x)))); } + + //! Effects: Inserts a new value_type move constructed from the pair if and + //! only if there is no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(impl_value_type) x) + { + return force > + (m_flat_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); + } + + //! Effects: Inserts a copy of x in the container if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, const value_type& x) + { return force_copy( + m_flat_tree.insert_unique(force(position), force(x))); } + + //! Effects: Inserts an element move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return force_copy( + m_flat_tree.insert_unique(force(position), BOOST_CONTAINER_MOVE_NAMESPACE::move(force(x)))); } + + //! Effects: Inserts an element move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(impl_value_type) x) + { + return force_copy( + m_flat_tree.insert_unique(force(position), BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); + } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) if and only + //! if there is no element with key equivalent to the key of that element. + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + //! search time plus N*size() insertion time. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + void insert(InputIterator first, InputIterator last) + { m_flat_tree.insert_unique(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... if and only if there is no element in the container + //! with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace(Args&&... args) + { return force_copy(m_flat_tree.emplace_unique(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return force_copy(m_flat_tree.emplace_hint_unique(force(hint), BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return force_copy(m_flat_tree.emplace_unique()); } + + iterator emplace_hint(const_iterator hint) + { return force_copy(m_flat_tree.emplace_hint_unique(force(hint))); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return force_copy(m_flat_tree.emplace_unique \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return force_copy(m_flat_tree.emplace_hint_unique \ + (force(hint), \ + BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by position. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Linear to the elements with keys bigger than position + //! + //! Note: Invalidates elements with keys + //! not less than the erased element. + iterator erase(const_iterator position) + { return force_copy(m_flat_tree.erase(force(position))); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + size_type erase(const key_type& x) + { return m_flat_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: size()*N where N is the distance from first to last. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + iterator erase(const_iterator first, const_iterator last) + { return force_copy(m_flat_tree.erase(force(first), force(last))); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_flat_tree.clear(); } + + //! Effects: Tries to deallocate the excess of memory created + // with previous allocations. The size of the vector is unchanged + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to size(). + void shrink_to_fit() + { m_flat_tree.shrink_to_fit(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return force_copy(m_flat_tree.find(x)); } + + //! Returns: A const_iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic.s + const_iterator find(const key_type& x) const + { return force(m_flat_tree.find(x)); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_flat_tree.find(x) == m_flat_tree.end() ? 0 : 1; } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + { return force_copy(m_flat_tree.lower_bound(x)); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return force(m_flat_tree.lower_bound(x)); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return force_copy(m_flat_tree.upper_bound(x)); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return force(m_flat_tree.upper_bound(x)); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) + { return force >(m_flat_tree.equal_range(x)); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) const + { return force >(m_flat_tree.equal_range(x)); } + + //! Effects: Number of elements for which memory has been allocated. + //! capacity() is always greater than or equal to size(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type capacity() const + { return m_flat_tree.capacity(); } + + //! Effects: If n is less than or equal to capacity(), this call has no + //! effect. Otherwise, it is a request for allocation of additional memory. + //! If the request is successful, then capacity() is greater than or equal to + //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. + //! + //! Throws: If memory allocation allocation throws or T's copy constructor throws. + //! + //! Note: If capacity() is less than "count", iterators and references to + //! to values might be invalidated. + void reserve(size_type count) + { m_flat_tree.reserve(count); } + + /// @cond + template + friend bool operator== (const flat_map&, + const flat_map&); + template + friend bool operator< (const flat_map&, + const flat_map&); + /// @endcond +}; + +template +inline bool operator==(const flat_map& x, + const flat_map& y) + { return x.m_flat_tree == y.m_flat_tree; } + +template +inline bool operator<(const flat_map& x, + const flat_map& y) + { return x.m_flat_tree < y.m_flat_tree; } + +template +inline bool operator!=(const flat_map& x, + const flat_map& y) + { return !(x == y); } + +template +inline bool operator>(const flat_map& x, + const flat_map& y) + { return y < x; } + +template +inline bool operator<=(const flat_map& x, + const flat_map& y) + { return !(y < x); } + +template +inline bool operator>=(const flat_map& x, + const flat_map& y) + { return !(x < y); } + +template +inline void swap(flat_map& x, + flat_map& y) + { x.swap(y); } + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +namespace container { + +// Forward declaration of operators < and ==, needed for friend declaration. +template +class flat_multimap; + +template +inline bool operator==(const flat_multimap& x, + const flat_multimap& y); + +template +inline bool operator<(const flat_multimap& x, + const flat_multimap& y); +/// @endcond + +//! A flat_multimap is a kind of associative container that supports equivalent keys +//! (possibly containing multiple copies of the same key value) and provides for +//! fast retrieval of values of another type T based on the keys. The flat_multimap +//! class supports random-access iterators. +//! +//! A flat_multimap satisfies all of the requirements of a container and of a reversible +//! container and of an associative container. For a +//! flat_multimap the key_type is Key and the value_type is std::pair +//! (unlike std::multimap which value_type is std::pair<const Key, T>). +//! +//! Pred is the ordering function for Keys (e.g. std::less). +//! +//! Alloc is the allocator to allocate the value_types +//! (e.g. allocator< std::pair >). +template +class flat_multimap +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(flat_multimap) + typedef containers_detail::flat_tree, + containers_detail::select1st< std::pair >, + Pred, + Alloc> tree_t; + //This is the real tree stored here. It's based on a movable pair + typedef containers_detail::flat_tree, + containers_detail::select1st >, + Pred, + typename Alloc::template + rebind >::other> impl_tree_t; + impl_tree_t m_flat_tree; // flat tree representing flat_map + + typedef typename impl_tree_t::value_type impl_value_type; + typedef typename impl_tree_t::pointer impl_pointer; + typedef typename impl_tree_t::const_pointer impl_const_pointer; + typedef typename impl_tree_t::reference impl_reference; + typedef typename impl_tree_t::const_reference impl_const_reference; + typedef typename impl_tree_t::value_compare impl_value_compare; + typedef typename impl_tree_t::iterator impl_iterator; + typedef typename impl_tree_t::const_iterator impl_const_iterator; + typedef typename impl_tree_t::reverse_iterator impl_reverse_iterator; + typedef typename impl_tree_t::const_reverse_iterator impl_const_reverse_iterator; + typedef typename impl_tree_t::allocator_type impl_allocator_type; + + template + static D &force(const S &s) + { return *const_cast((reinterpret_cast(&s))); } + + template + static D force_copy(S s) + { + value_type *vp = reinterpret_cast(&*s); + return D(vp); + } + /// @endcond + + public: + + // typedefs: + typedef typename impl_tree_t::key_type key_type; + typedef T mapped_type; + typedef typename std::pair value_type; + typedef typename Alloc::pointer pointer; + typedef typename Alloc::const_pointer const_pointer; + typedef typename Alloc::reference reference; + typedef typename Alloc::const_reference const_reference; + typedef containers_detail::flat_tree_value_compare + < Pred + , containers_detail::select1st< std::pair > + , std::pair > value_compare; + typedef Pred key_compare; + typedef typename containers_detail:: + get_flat_tree_iterators::iterator iterator; + typedef typename containers_detail:: + get_flat_tree_iterators::const_iterator const_iterator; + typedef typename containers_detail:: + get_flat_tree_iterators + ::reverse_iterator reverse_iterator; + typedef typename containers_detail:: + get_flat_tree_iterators + ::const_reverse_iterator const_reverse_iterator; + typedef typename impl_tree_t::size_type size_type; + typedef typename impl_tree_t::difference_type difference_type; + typedef Alloc allocator_type; + typedef Alloc stored_allocator_type; + + //! Effects: Constructs an empty flat_multimap using the specified comparison + //! object and allocator. + //! + //! Complexity: Constant. + explicit flat_multimap(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, force(a)) { } + + //! Effects: Constructs an empty flat_multimap using the specified comparison object + //! and allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + flat_multimap(InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, force(a)) + { m_flat_tree.insert_equal(first, last); } + + //! Effects: Constructs an empty flat_multimap using the specified comparison object and + //! allocator, and inserts elements from the ordered range [first ,last). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate. + //! + //! Complexity: Linear in N. + template + flat_multimap(ordered_range_t, InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(ordered_range, first, last, comp, a) + {} + + //! Effects: Copy constructs a flat_multimap. + //! + //! Complexity: Linear in x.size(). + flat_multimap(const flat_multimap& x) + : m_flat_tree(x.m_flat_tree) { } + + //! Effects: Move constructs a flat_multimap. Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + flat_multimap(BOOST_MOVE_MACRO_RV_REF(flat_multimap) x) + : m_flat_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_flat_tree)) + { } + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + flat_multimap& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(flat_multimap) x) + { m_flat_tree = x.m_flat_tree; return *this; } + + //! Effects: this->swap(x.get()). + //! + //! Complexity: Constant. + flat_multimap& operator=(BOOST_MOVE_MACRO_RV_REF(flat_multimap) mx) + { m_flat_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(mx.m_flat_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return force(m_flat_tree.key_comp()); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return value_compare(force(m_flat_tree.key_comp())); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return force(m_flat_tree.get_allocator()); } + + const stored_allocator_type &get_stored_allocator() const + { return force(m_flat_tree.get_stored_allocator()); } + + stored_allocator_type &get_stored_allocator() + { return force(m_flat_tree.get_stored_allocator()); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return force_copy(m_flat_tree.begin()); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return force(m_flat_tree.begin()); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return force_copy(m_flat_tree.end()); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return force(m_flat_tree.end()); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return force(m_flat_tree.rbegin()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return force(m_flat_tree.rbegin()); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return force(m_flat_tree.rend()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return force(m_flat_tree.rend()); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_flat_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_flat_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_flat_tree.max_size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(flat_multimap& x) + { m_flat_tree.swap(x.m_flat_tree); } + + //! Effects: Inserts x and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const value_type& x) + { return force_copy(m_flat_tree.insert_equal(force(x))); } + + //! Effects: Inserts a new value move-constructed from x and returns + //! the iterator pointing to the newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return force_copy(m_flat_tree.insert_equal(BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); } + + //! Effects: Inserts a new value move-constructed from x and returns + //! the iterator pointing to the newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(BOOST_MOVE_MACRO_RV_REF(impl_value_type) x) + { return force_copy(m_flat_tree.insert_equal(BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); } + + //! Effects: Inserts a copy of x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant time if the value + //! is to be inserted before p) plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, const value_type& x) + { return force_copy(m_flat_tree.insert_equal(force(position), force(x))); } + + //! Effects: Inserts a value move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant time if the value + //! is to be inserted before p) plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { + return force_copy + (m_flat_tree.insert_equal(force(position) + , BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); + } + + //! Effects: Inserts a value move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant time if the value + //! is to be inserted before p) plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(impl_value_type) x) + { + return force_copy( + m_flat_tree.insert_equal(force(position), BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); + } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) . + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + //! search time plus N*size() insertion time. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + void insert(InputIterator first, InputIterator last) + { m_flat_tree.insert_equal(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace(Args&&... args) + { return force_copy(m_flat_tree.emplace_equal(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant time if the value + //! is to be inserted before p) plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { + return force_copy(m_flat_tree.emplace_hint_equal + (force(hint), BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...)); + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return force_copy(m_flat_tree.emplace_equal()); } + + iterator emplace_hint(const_iterator hint) + { return force_copy(m_flat_tree.emplace_hint_equal(force(hint))); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return force_copy(m_flat_tree.emplace_equal \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return force_copy(m_flat_tree.emplace_hint_equal \ + (force(hint), \ + BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _))); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by position. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Linear to the elements with keys bigger than position + //! + //! Note: Invalidates elements with keys + //! not less than the erased element. + iterator erase(const_iterator position) + { return force_copy(m_flat_tree.erase(force(position))); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + size_type erase(const key_type& x) + { return m_flat_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: size()*N where N is the distance from first to last. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + iterator erase(const_iterator first, const_iterator last) + { return force_copy(m_flat_tree.erase(force(first), force(last))); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_flat_tree.clear(); } + + //! Effects: Tries to deallocate the excess of memory created + // with previous allocations. The size of the vector is unchanged + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to size(). + void shrink_to_fit() + { m_flat_tree.shrink_to_fit(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return force_copy(m_flat_tree.find(x)); } + + //! Returns: An const_iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + const_iterator find(const key_type& x) const + { return force(m_flat_tree.find(x)); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_flat_tree.count(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + {return force_copy(m_flat_tree.lower_bound(x)); } + + //! Returns: A const iterator pointing to the first element with key + //! not less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return force(m_flat_tree.lower_bound(x)); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + {return force_copy(m_flat_tree.upper_bound(x)); } + + //! Returns: A const iterator pointing to the first element with key + //! not less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return force(m_flat_tree.upper_bound(x)); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) + { return force_copy >(m_flat_tree.equal_range(x)); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) const + { return force_copy >(m_flat_tree.equal_range(x)); } + + //! Effects: Number of elements for which memory has been allocated. + //! capacity() is always greater than or equal to size(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type capacity() const + { return m_flat_tree.capacity(); } + + //! Effects: If n is less than or equal to capacity(), this call has no + //! effect. Otherwise, it is a request for allocation of additional memory. + //! If the request is successful, then capacity() is greater than or equal to + //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. + //! + //! Throws: If memory allocation allocation throws or T's copy constructor throws. + //! + //! Note: If capacity() is less than "count", iterators and references to + //! to values might be invalidated. + void reserve(size_type count) + { m_flat_tree.reserve(count); } + + /// @cond + template + friend bool operator== (const flat_multimap& x, + const flat_multimap& y); + + template + friend bool operator< (const flat_multimap& x, + const flat_multimap& y); + /// @endcond +}; + +template +inline bool operator==(const flat_multimap& x, + const flat_multimap& y) + { return x.m_flat_tree == y.m_flat_tree; } + +template +inline bool operator<(const flat_multimap& x, + const flat_multimap& y) + { return x.m_flat_tree < y.m_flat_tree; } + +template +inline bool operator!=(const flat_multimap& x, + const flat_multimap& y) + { return !(x == y); } + +template +inline bool operator>(const flat_multimap& x, + const flat_multimap& y) + { return y < x; } + +template +inline bool operator<=(const flat_multimap& x, + const flat_multimap& y) + { return !(y < x); } + +template +inline bool operator>=(const flat_multimap& x, + const flat_multimap& y) + { return !(x < y); } + +template +inline void swap(flat_multimap& x, flat_multimap& y) + { x.swap(y); } + +}} + +/// @cond + +namespace boost { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move< boost::container::flat_multimap > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +} //namespace boost { + +/// @endcond + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif /* BOOST_CONTAINERS_FLAT_MAP_HPP */ diff --git a/utils/boost_idb/boost/interprocess/containers/container/flat_set.hpp b/utils/boost_idb/boost/interprocess/containers/container/flat_set.hpp new file mode 100644 index 00000000..7ebf4e0d --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/flat_set.hpp @@ -0,0 +1,1245 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_FLAT_SET_HPP +#define BOOST_CONTAINERS_FLAT_SET_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_FLAT_TREE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +// Forward declarations of operators < and ==, needed for friend declaration. + +template +class flat_set; + +template +inline bool operator==(const flat_set& x, + const flat_set& y); + +template +inline bool operator<(const flat_set& x, + const flat_set& y); +/// @endcond + +//! flat_set is a Sorted Associative Container that stores objects of type Key. +//! flat_set is a Simple Associative Container, meaning that its value type, +//! as well as its key type, is Key. It is also a Unique Associative Container, +//! meaning that no two elements are the same. +//! +//! flat_set is similar to std::set but it's implemented like an ordered vector. +//! This means that inserting a new element into a flat_set invalidates +//! previous iterators and references +//! +//! Erasing an element of a flat_set invalidates iterators and references +//! pointing to elements that come after (their keys are bigger) the erased element. +template +class flat_set +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(flat_set) + typedef containers_detail::flat_tree, Pred, Alloc> tree_t; + tree_t m_flat_tree; // flat tree representing flat_set + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + /// @endcond + + public: + + // typedefs: + typedef typename tree_t::key_type key_type; + typedef typename tree_t::value_type value_type; + typedef typename tree_t::pointer pointer; + typedef typename tree_t::const_pointer const_pointer; + typedef typename tree_t::reference reference; + typedef typename tree_t::const_reference const_reference; + typedef typename tree_t::key_compare key_compare; + typedef typename tree_t::value_compare value_compare; + typedef typename tree_t::iterator iterator; + typedef typename tree_t::const_iterator const_iterator; + typedef typename tree_t::reverse_iterator reverse_iterator; + typedef typename tree_t::const_reverse_iterator const_reverse_iterator; + typedef typename tree_t::size_type size_type; + typedef typename tree_t::difference_type difference_type; + typedef typename tree_t::allocator_type allocator_type; + typedef typename tree_t::stored_allocator_type stored_allocator_type; + + //! Effects: Constructs an empty flat_map using the specified + //! comparison object and allocator. + //! + //! Complexity: Constant. + explicit flat_set(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, a) + {} + + //! Effects: Constructs an empty map using the specified comparison object and + //! allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + flat_set(InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, a) + { m_flat_tree.insert_unique(first, last); } + + //! Effects: Constructs an empty flat_set using the specified comparison object and + //! allocator, and inserts elements from the ordered unique range [first ,last). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate and must be + //! unique values. + //! + //! Complexity: Linear in N. + template + flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(ordered_range, first, last, comp, a) + {} + + //! Effects: Copy constructs a map. + //! + //! Complexity: Linear in x.size(). + flat_set(const flat_set& x) + : m_flat_tree(x.m_flat_tree) {} + + //! Effects: Move constructs a map. Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + flat_set(BOOST_MOVE_MACRO_RV_REF(flat_set) mx) + : m_flat_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(mx.m_flat_tree)) + {} + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + flat_set& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(flat_set) x) + { m_flat_tree = x.m_flat_tree; return *this; } + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + flat_set& operator=(BOOST_MOVE_MACRO_RV_REF(flat_set) mx) + { m_flat_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(mx.m_flat_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return m_flat_tree.key_comp(); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return m_flat_tree.key_comp(); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return m_flat_tree.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return m_flat_tree.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return m_flat_tree.get_stored_allocator(); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return m_flat_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return m_flat_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return m_flat_tree.cbegin(); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return m_flat_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return m_flat_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return m_flat_tree.cend(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return m_flat_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return m_flat_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return m_flat_tree.crbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return m_flat_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return m_flat_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return m_flat_tree.crend(); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_flat_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_flat_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_flat_tree.max_size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(flat_set& x) + { m_flat_tree.swap(x.m_flat_tree); } + + //! Effects: Inserts x if and only if there is no element in the container + //! with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + std::pair insert(insert_const_ref_type x) + { return priv_insert(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + std::pair insert(T &x) + { return this->insert(const_cast(x)); } + + template + std::pair insert(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(u); } + #endif + + //! Effects: Inserts a new value_type move constructed from the pair if and + //! only if there is no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_flat_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator p, insert_const_ref_type x) + { return priv_insert(p, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) + { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(position, u); } + #endif + + //! Effects: Inserts an element move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_flat_tree.insert_unique(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) if and only + //! if there is no element with key equivalent to the key of that element. + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + //! search time plus N*size() insertion time. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + void insert(InputIterator first, InputIterator last) + { m_flat_tree.insert_unique(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... if and only if there is no element in the container + //! with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace(Args&&... args) + { return m_flat_tree.emplace_unique(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return m_flat_tree.emplace_hint_unique(hint, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return m_flat_tree.emplace_unique(); } + + iterator emplace_hint(const_iterator hint) + { return m_flat_tree.emplace_hint_unique(hint); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_flat_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_flat_tree.emplace_hint_unique(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); }\ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by position. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Linear to the elements with keys bigger than position + //! + //! Note: Invalidates elements with keys + //! not less than the erased element. + iterator erase(const_iterator position) + { return m_flat_tree.erase(position); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + size_type erase(const key_type& x) + { return m_flat_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: size()*N where N is the distance from first to last. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + iterator erase(const_iterator first, const_iterator last) + { return m_flat_tree.erase(first, last); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_flat_tree.clear(); } + + //! Effects: Tries to deallocate the excess of memory created + // with previous allocations. The size of the vector is unchanged + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to size(). + void shrink_to_fit() + { m_flat_tree.shrink_to_fit(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return m_flat_tree.find(x); } + + //! Returns: A const_iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic.s + const_iterator find(const key_type& x) const + { return m_flat_tree.find(x); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_flat_tree.find(x) == m_flat_tree.end() ? 0 : 1; } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + { return m_flat_tree.lower_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return m_flat_tree.lower_bound(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return m_flat_tree.upper_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return m_flat_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) const + { return m_flat_tree.equal_range(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) + { return m_flat_tree.equal_range(x); } + + //! Effects: Number of elements for which memory has been allocated. + //! capacity() is always greater than or equal to size(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type capacity() const + { return m_flat_tree.capacity(); } + + //! Effects: If n is less than or equal to capacity(), this call has no + //! effect. Otherwise, it is a request for allocation of additional memory. + //! If the request is successful, then capacity() is greater than or equal to + //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. + //! + //! Throws: If memory allocation allocation throws or T's copy constructor throws. + //! + //! Note: If capacity() is less than "count", iterators and references to + //! to values might be invalidated. + void reserve(size_type count) + { m_flat_tree.reserve(count); } + + /// @cond + template + friend bool operator== (const flat_set&, const flat_set&); + + template + friend bool operator< (const flat_set&, const flat_set&); + + private: + std::pair priv_insert(const T &x) + { return m_flat_tree.insert_unique(x); } + + iterator priv_insert(const_iterator p, const T &x) + { return m_flat_tree.insert_unique(p, x); } + /// @endcond +}; + +template +inline bool operator==(const flat_set& x, + const flat_set& y) + { return x.m_flat_tree == y.m_flat_tree; } + +template +inline bool operator<(const flat_set& x, + const flat_set& y) + { return x.m_flat_tree < y.m_flat_tree; } + +template +inline bool operator!=(const flat_set& x, + const flat_set& y) + { return !(x == y); } + +template +inline bool operator>(const flat_set& x, + const flat_set& y) + { return y < x; } + +template +inline bool operator<=(const flat_set& x, + const flat_set& y) + { return !(y < x); } + +template +inline bool operator>=(const flat_set& x, + const flat_set& y) + { return !(x < y); } + +template +inline void swap(flat_set& x, flat_set& y) + { x.swap(y); } + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value &&has_trivial_destructor::value; +}; +*/ +namespace container { + +// Forward declaration of operators < and ==, needed for friend declaration. + +template +class flat_multiset; + +template +inline bool operator==(const flat_multiset& x, + const flat_multiset& y); + +template +inline bool operator<(const flat_multiset& x, + const flat_multiset& y); +/// @endcond + +//! flat_multiset is a Sorted Associative Container that stores objects of type Key. +//! flat_multiset is a Simple Associative Container, meaning that its value type, +//! as well as its key type, is Key. +//! flat_Multiset can store multiple copies of the same key value. +//! +//! flat_multiset is similar to std::multiset but it's implemented like an ordered vector. +//! This means that inserting a new element into a flat_multiset invalidates +//! previous iterators and references +//! +//! Erasing an element of a flat_multiset invalidates iterators and references +//! pointing to elements that come after (their keys are equal or bigger) the erased element. +template +class flat_multiset +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(flat_multiset) + typedef containers_detail::flat_tree, Pred, Alloc> tree_t; + tree_t m_flat_tree; // flat tree representing flat_multiset + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + /// @endcond + + public: + // typedefs: + typedef typename tree_t::key_type key_type; + typedef typename tree_t::value_type value_type; + typedef typename tree_t::pointer pointer; + typedef typename tree_t::const_pointer const_pointer; + typedef typename tree_t::reference reference; + typedef typename tree_t::const_reference const_reference; + typedef typename tree_t::key_compare key_compare; + typedef typename tree_t::value_compare value_compare; + typedef typename tree_t::iterator iterator; + typedef typename tree_t::const_iterator const_iterator; + typedef typename tree_t::reverse_iterator reverse_iterator; + typedef typename tree_t::const_reverse_iterator const_reverse_iterator; + typedef typename tree_t::size_type size_type; + typedef typename tree_t::difference_type difference_type; + typedef typename tree_t::allocator_type allocator_type; + typedef typename tree_t::stored_allocator_type stored_allocator_type; + + // allocation/deallocation + explicit flat_multiset(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, a) {} + + template + flat_multiset(InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(comp, a) + { m_flat_tree.insert_equal(first, last); } + + //! Effects: Constructs an empty flat_multiset using the specified comparison object and + //! allocator, and inserts elements from the ordered range [first ,last ). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate. + //! + //! Complexity: Linear in N. + template + flat_multiset(ordered_range_t, InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_flat_tree(ordered_range, first, last, comp, a) + {} + + flat_multiset(const flat_multiset& x) + : m_flat_tree(x.m_flat_tree) {} + + flat_multiset(BOOST_MOVE_MACRO_RV_REF(flat_multiset) x) + : m_flat_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_flat_tree)) + {} + + flat_multiset& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(flat_multiset) x) + { m_flat_tree = x.m_flat_tree; return *this; } + + flat_multiset& operator=(BOOST_MOVE_MACRO_RV_REF(flat_multiset) mx) + { m_flat_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(mx.m_flat_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return m_flat_tree.key_comp(); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return m_flat_tree.key_comp(); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return m_flat_tree.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return m_flat_tree.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return m_flat_tree.get_stored_allocator(); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return m_flat_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return m_flat_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return m_flat_tree.cbegin(); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return m_flat_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return m_flat_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return m_flat_tree.cend(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return m_flat_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return m_flat_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return m_flat_tree.crbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return m_flat_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return m_flat_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return m_flat_tree.crend(); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_flat_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_flat_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_flat_tree.max_size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(flat_multiset& x) + { m_flat_tree.swap(x.m_flat_tree); } + + //! Effects: Inserts x and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(insert_const_ref_type x) + { return priv_insert(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(T &x) + { return this->insert(const_cast(x)); } + + template + iterator insert(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(u); } + #endif + + //! Effects: Inserts a new value_type move constructed from x + //! and returns the iterator pointing to the newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_flat_tree.insert_equal(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator p, insert_const_ref_type x) + { return priv_insert(p, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) + { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(position, u); } + #endif + + //! Effects: Inserts a new value move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_flat_tree.insert_equal(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) . + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + //! search time plus N*size() insertion time. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + void insert(InputIterator first, InputIterator last) + { m_flat_tree.insert_equal(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic search time plus linear insertion + //! to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace(Args&&... args) + { return m_flat_tree.emplace_equal(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic search time (constant if x is inserted + //! right before p) plus insertion linear to the elements with bigger keys than x. + //! + //! Note: If an element it's inserted it might invalidate elements. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return m_flat_tree.emplace_hint_equal(hint, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return m_flat_tree.emplace_equal(); } + + iterator emplace_hint(const_iterator hint) + { return m_flat_tree.emplace_hint_equal(hint); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_flat_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_flat_tree.emplace_hint_equal(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by position. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Linear to the elements with keys bigger than position + //! + //! Note: Invalidates elements with keys + //! not less than the erased element. + iterator erase(const_iterator position) + { return m_flat_tree.erase(position); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + size_type erase(const key_type& x) + { return m_flat_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: size()*N where N is the distance from first to last. + //! + //! Complexity: Logarithmic search time plus erasure time + //! linear to the elements with bigger keys. + iterator erase(const_iterator first, const_iterator last) + { return m_flat_tree.erase(first, last); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_flat_tree.clear(); } + + //! Effects: Tries to deallocate the excess of memory created + // with previous allocations. The size of the vector is unchanged + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to size(). + void shrink_to_fit() + { m_flat_tree.shrink_to_fit(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return m_flat_tree.find(x); } + + //! Returns: A const_iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic.s + const_iterator find(const key_type& x) const + { return m_flat_tree.find(x); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_flat_tree.count(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + { return m_flat_tree.lower_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return m_flat_tree.lower_bound(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return m_flat_tree.upper_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return m_flat_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) const + { return m_flat_tree.equal_range(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) + { return m_flat_tree.equal_range(x); } + + //! Effects: Number of elements for which memory has been allocated. + //! capacity() is always greater than or equal to size(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type capacity() const + { return m_flat_tree.capacity(); } + + //! Effects: If n is less than or equal to capacity(), this call has no + //! effect. Otherwise, it is a request for allocation of additional memory. + //! If the request is successful, then capacity() is greater than or equal to + //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. + //! + //! Throws: If memory allocation allocation throws or T's copy constructor throws. + //! + //! Note: If capacity() is less than "count", iterators and references to + //! to values might be invalidated. + void reserve(size_type count) + { m_flat_tree.reserve(count); } + + /// @cond + template + friend bool operator== (const flat_multiset&, + const flat_multiset&); + template + friend bool operator< (const flat_multiset&, + const flat_multiset&); + private: + iterator priv_insert(const T &x) + { return m_flat_tree.insert_equal(x); } + + iterator priv_insert(const_iterator p, const T &x) + { return m_flat_tree.insert_equal(p, x); } + /// @endcond +}; + +template +inline bool operator==(const flat_multiset& x, + const flat_multiset& y) + { return x.m_flat_tree == y.m_flat_tree; } + +template +inline bool operator<(const flat_multiset& x, + const flat_multiset& y) + { return x.m_flat_tree < y.m_flat_tree; } + +template +inline bool operator!=(const flat_multiset& x, + const flat_multiset& y) + { return !(x == y); } + +template +inline bool operator>(const flat_multiset& x, + const flat_multiset& y) + { return y < x; } + +template +inline bool operator<=(const flat_multiset& x, + const flat_multiset& y) + { return !(y < x); } + +template +inline bool operator>=(const flat_multiset& x, + const flat_multiset& y) +{ return !(x < y); } + +template +inline void swap(flat_multiset& x, flat_multiset& y) + { x.swap(y); } + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +namespace container { + +/// @endcond + +}} + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif /* BOOST_CONTAINERS_FLAT_SET_HPP */ diff --git a/utils/boost_idb/boost/interprocess/containers/container/list.hpp b/utils/boost_idb/boost/interprocess/containers/container/list.hpp new file mode 100644 index 00000000..1159ef15 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/list.hpp @@ -0,0 +1,1371 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// + +#ifndef BOOST_CONTAINERS_LIST_HPP_ +#define BOOST_CONTAINERS_LIST_HPP_ + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_NODE_ALLOC_HOLDER_HPP + +#if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) +#else +//Preprocessor library to emulate perfect forwarding +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +namespace containers_detail { + +template +struct list_hook +{ + typedef typename containers_detail::bi::make_list_base_hook + , containers_detail::bi::link_mode >::type type; +}; + +template +struct list_node + : public list_hook::type +{ + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + list_node() + : m_data() + {} + + template + list_node(Args &&...args) + : m_data(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...) + {} + + #else //#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING + + list_node() + : m_data() + {} + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + list_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + : m_data(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)) \ + {} \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif//#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING + + T m_data; +}; + +template +struct intrusive_list_type +{ + typedef typename A::value_type value_type; + typedef typename boost::pointer_to_other + ::type void_pointer; + typedef typename containers_detail::list_node + node_type; + typedef typename containers_detail::bi::make_list + < node_type + , containers_detail::bi::base_hook::type> + , containers_detail::bi::constant_time_size + , containers_detail::bi::size_type + >::type container_type; + typedef container_type type ; +}; + +} //namespace containers_detail { +/// @endcond + +//! A list is a doubly linked list. That is, it is a Sequence that supports both +//! forward and backward traversal, and (amortized) constant time insertion and +//! removal of elements at the beginning or the end, or in the middle. Lists have +//! the important property that insertion and splicing do not invalidate iterators +//! to list elements, and that even removal invalidates only the iterators that point +//! to the elements that are removed. The ordering of iterators may be changed +//! (that is, list::iterator might have a different predecessor or successor +//! after a list operation than it did before), but the iterators themselves will +//! not be invalidated or made to point to different elements unless that invalidation +//! or mutation is explicit. +template +class list + : protected containers_detail::node_alloc_holder + ::type> +{ + /// @cond + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + typedef typename + containers_detail::intrusive_list_type::type Icont; + typedef list ThisType; + typedef containers_detail::node_alloc_holder AllocHolder; + typedef typename AllocHolder::NodePtr NodePtr; + typedef typename AllocHolder::NodeAlloc NodeAlloc; + typedef typename AllocHolder::ValAlloc ValAlloc; + typedef typename AllocHolder::Node Node; + typedef containers_detail::allocator_destroyer Destroyer; + typedef typename AllocHolder::allocator_v1 allocator_v1; + typedef typename AllocHolder::allocator_v2 allocator_v2; + typedef typename AllocHolder::alloc_version alloc_version; + + class equal_to_value + { + typedef typename AllocHolder::value_type value_type; + const value_type &t_; + + public: + equal_to_value(const value_type &t) + : t_(t) + {} + + bool operator()(const value_type &t)const + { return t_ == t; } + }; + + template + struct ValueCompareToNodeCompare + : Pred + { + ValueCompareToNodeCompare(Pred pred) + : Pred(pred) + {} + + bool operator()(const Node &a, const Node &b) const + { return static_cast(*this)(a.m_data, b.m_data); } + + bool operator()(const Node &a) const + { return static_cast(*this)(a.m_data); } + }; + /// @endcond + + public: + //! The type of object, T, stored in the list + typedef T value_type; + //! Pointer to T + typedef typename A::pointer pointer; + //! Const pointer to T + typedef typename A::const_pointer const_pointer; + //! Reference to T + typedef typename A::reference reference; + //! Const reference to T + typedef typename A::const_reference const_reference; + //! An unsigned integral type + typedef typename A::size_type size_type; + //! A signed integral type + typedef typename A::difference_type difference_type; + //! The allocator type + typedef A allocator_type; + //! The stored allocator type + typedef NodeAlloc stored_allocator_type; + + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(list) + typedef difference_type list_difference_type; + typedef pointer list_pointer; + typedef const_pointer list_const_pointer; + typedef reference list_reference; + typedef const_reference list_const_reference; + /// @endcond + + public: + //! Const iterator used to iterate through a list. + class const_iterator + /// @cond + : public std::iterator + { + + protected: + typename Icont::iterator m_it; + explicit const_iterator(typename Icont::iterator it) : m_it(it){} + void prot_incr() { ++m_it; } + void prot_decr() { --m_it; } + + private: + typename Icont::iterator get() + { return this->m_it; } + + public: + friend class list; + typedef list_difference_type difference_type; + + //Constructors + const_iterator() + : m_it() + {} + + //Pointer like operators + const_reference operator*() const + { return m_it->m_data; } + + const_pointer operator->() const + { return const_pointer(&m_it->m_data); } + + //Increment / Decrement + const_iterator& operator++() + { prot_incr(); return *this; } + + const_iterator operator++(int) + { typename Icont::iterator tmp = m_it; ++*this; return const_iterator(tmp); } + + const_iterator& operator--() + { prot_decr(); return *this; } + + const_iterator operator--(int) + { typename Icont::iterator tmp = m_it; --*this; return const_iterator(tmp); } + + //Comparison operators + bool operator== (const const_iterator& r) const + { return m_it == r.m_it; } + + bool operator!= (const const_iterator& r) const + { return m_it != r.m_it; } + } + /// @endcond + ; + + //! Iterator used to iterate through a list + class iterator + /// @cond + : public const_iterator + { + + private: + explicit iterator(typename Icont::iterator it) + : const_iterator(it) + {} + + typename Icont::iterator get() + { return this->m_it; } + + public: + friend class list; + typedef list_pointer pointer; + typedef list_reference reference; + + //Constructors + iterator(){} + + //Pointer like operators + reference operator*() const { return this->m_it->m_data; } + pointer operator->() const { return pointer(&this->m_it->m_data); } + + //Increment / Decrement + iterator& operator++() + { this->prot_incr(); return *this; } + + iterator operator++(int) + { typename Icont::iterator tmp = this->m_it; ++*this; return iterator(tmp); } + + iterator& operator--() + { this->prot_decr(); return *this; } + + iterator operator--(int) + { iterator tmp = *this; --*this; return tmp; } + }; + /// @endcond + + //! Iterator used to iterate backwards through a list. + typedef std::reverse_iterator reverse_iterator; + //! Const iterator used to iterate backwards through a list. + typedef std::reverse_iterator const_reverse_iterator; + + //! Effects: Constructs a list taking the allocator as parameter. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + explicit list(const allocator_type &a = A()) + : AllocHolder(a) + {} + + //! Effects: Constructs a list that will use a copy of allocator a + //! and inserts n copies of value. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's default or copy constructor throws. + //! + //! Complexity: Linear to n. + list(size_type n) + : AllocHolder(A()) + { this->resize(n); } + + //! Effects: Constructs a list that will use a copy of allocator a + //! and inserts n copies of value. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's default or copy constructor throws. + //! + //! Complexity: Linear to n. + list(size_type n, const T& value, const A& a = A()) + : AllocHolder(a) + { this->insert(this->cbegin(), n, value); } + + //! Effects: Copy constructs a list. + //! + //! Postcondition: x == *this. + //! + //! Throws: If allocator_type's default constructor or copy constructor throws. + //! + //! Complexity: Linear to the elements x contains. + list(const list& x) + : AllocHolder(x) + { this->insert(this->cbegin(), x.begin(), x.end()); } + + //! Effects: Move constructor. Moves mx's resources to *this. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + list(BOOST_MOVE_MACRO_RV_REF(list) x) + : AllocHolder(BOOST_CONTAINER_MOVE_NAMESPACE::move(static_cast(x))) + {} + + //! Effects: Constructs a list that will use a copy of allocator a + //! and inserts a copy of the range [first, last) in the list. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's constructor taking an dereferenced InIt throws. + //! + //! Complexity: Linear to the range [first, last). + template + list(InpIt first, InpIt last, const A &a = A()) + : AllocHolder(a) + { this->insert(this->cbegin(), first, last); } + + //! Effects: Destroys the list. All stored values are destroyed + //! and used memory is deallocated. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements. + ~list() + {} //AllocHolder clears the list + + //! Effects: Returns a copy of the internal allocator. + //! + //! Throws: If allocator's copy constructor throws. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return allocator_type(this->node_alloc()); } + + const stored_allocator_type &get_stored_allocator() const + { return this->node_alloc(); } + + stored_allocator_type &get_stored_allocator() + { return this->node_alloc(); } + + //! Effects: Erases all the elements of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements in the list. + void clear() + { AllocHolder::clear(alloc_version()); } + + //! Effects: Returns an iterator to the first element contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return iterator(this->icont().begin()); } + + //! Effects: Returns a const_iterator to the first element contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return this->cbegin(); } + + //! Effects: Returns an iterator to the end of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return iterator(this->icont().end()); } + + //! Effects: Returns a const_iterator to the end of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return this->cend(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return reverse_iterator(end()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return this->crbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return reverse_iterator(begin()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return this->crend(); } + + //! Effects: Returns a const_iterator to the first element contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return const_iterator(this->non_const_icont().begin()); } + + //! Effects: Returns a const_iterator to the end of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return const_iterator(this->non_const_icont().end()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return const_reverse_iterator(this->cend()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return const_reverse_iterator(this->cbegin()); } + + //! Effects: Returns true if the list contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return !this->size(); } + + //! Effects: Returns the number of the elements contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return this->icont().size(); } + + //! Effects: Returns the largest possible size of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return AllocHolder::max_size(); } + + //! Effects: Inserts a copy of t in the beginning of the list. + //! + //! Throws: If memory allocation throws or + //! T's copy constructor throws. + //! + //! Complexity: Amortized constant time. + void push_front(insert_const_ref_type x) + { this->insert(this->cbegin(), x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_front(T &x) { push_front(const_cast(x)); } + + template + void push_front(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { this->insert(this->cbegin(), u); } + #endif + + //! Effects: Constructs a new element in the beginning of the list + //! and moves the resources of t to this new element. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: Amortized constant time. + void push_front(BOOST_MOVE_MACRO_RV_REF(T) x) + { this->insert(this->cbegin(), BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Removes the last element from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Amortized constant time. + void push_back (insert_const_ref_type x) + { this->insert(this->cend(), x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_back(T &x) { push_back(const_cast(x)); } + + template + void push_back(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { this->insert(this->cend(), u); } + + #endif + + //! Effects: Removes the first element from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Amortized constant time. + void push_back (BOOST_MOVE_MACRO_RV_REF(T) x) + { this->insert(this->cend(), BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Removes the first element from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Amortized constant time. + void pop_front() + { this->erase(this->cbegin()); } + + //! Effects: Removes the last element from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Amortized constant time. + void pop_back() + { const_iterator tmp = this->cend(); this->erase(--tmp); } + + //! Requires: !empty() + //! + //! Effects: Returns a reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference front() + { return *this->begin(); } + + //! Requires: !empty() + //! + //! Effects: Returns a const reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference front() const + { return *this->begin(); } + + //! Requires: !empty() + //! + //! Effects: Returns a reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference back() + { return *(--this->end()); } + + //! Requires: !empty() + //! + //! Effects: Returns a const reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference back() const + { return *(--this->end()); } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are copy constructed from x. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type new_size, const T& x) + { + const_iterator iend = this->cend(); + size_type len = this->size(); + + if(len > new_size){ + size_type to_erase = len - new_size; + while(to_erase--){ + --iend; + } + this->erase(iend, this->cend()); + } + else{ + this->priv_create_and_insert_nodes(iend, new_size - len, x); + } + } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are default constructed. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type new_size) + { + const_iterator iend = this->end(); + size_type len = this->size(); + + if(len > new_size){ + size_type to_erase = len - new_size; + const_iterator ifirst; + if(to_erase < len/2u){ + ifirst = iend; + while(to_erase--){ + --ifirst; + } + } + else{ + ifirst = this->begin(); + size_type to_skip = len - to_erase; + while(to_skip--){ + ++ifirst; + } + } + this->erase(ifirst, iend); + } + else{ + this->priv_create_and_insert_nodes(this->cend(), new_size - len); + } + } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() + //! allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(ThisType& x) + { AllocHolder::swap(x); } + + //! Effects: Makes *this contain the same elements as x. + //! + //! Postcondition: this->size() == x.size(). *this contains a copy + //! of each of x's elements. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to the number of elements in x. + ThisType& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(ThisType) x) + { + if (this != &x) { + this->assign(x.begin(), x.end()); + } + return *this; + } + + //! Effects: Move assignment. All mx's values are transferred to *this. + //! + //! Postcondition: x.empty(). *this contains a the elements x had + //! before the function. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + ThisType& operator=(BOOST_MOVE_MACRO_RV_REF(ThisType) mx) + { + this->clear(); + this->swap(mx); + return *this; + } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Inserts n copies of x before p. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n. + void insert(const_iterator p, size_type n, const T& x) + { this->priv_create_and_insert_nodes(p, n, x); } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Insert a copy of the [first, last) range before p. + //! + //! Throws: If memory allocation throws, T's constructor from a + //! dereferenced InpIt throws. + //! + //! Complexity: Linear to std::distance [first, last). + template + void insert(const_iterator p, InpIt first, InpIt last) + { + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_insert_dispatch(p, first, last, Result()); + } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Insert a copy of x before p. + //! + //! Throws: If memory allocation throws or x's copy constructor throws. + //! + //! Complexity: Amortized constant time. + iterator insert(const_iterator position, insert_const_ref_type x) + { return this->priv_insert(position, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return this->priv_insert(position, u); } + #endif + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Insert a new element before p with mx's resources. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: Amortized constant time. + iterator insert(const_iterator p, BOOST_MOVE_MACRO_RV_REF(T) x) + { + NodePtr tmp = AllocHolder::create_node(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); + return iterator(this->icont().insert(p.get(), *tmp)); + } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the end of the list. + //! + //! Throws: If memory allocation throws or + //! T's in-place constructor throws. + //! + //! Complexity: Constant + template + void emplace_back(Args&&... args) + { + this->emplace(this->cend(), BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the beginning of the list. + //! + //! Throws: If memory allocation throws or + //! T's in-place constructor throws. + //! + //! Complexity: Constant + template + void emplace_front(Args&&... args) + { + this->emplace(this->cbegin(), BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... before p. + //! + //! Throws: If memory allocation throws or + //! T's in-place constructor throws. + //! + //! Complexity: Constant + template + iterator emplace(const_iterator p, Args&&... args) + { + typename AllocHolder::Deallocator d(AllocHolder::create_node_and_deallocator()); + new ((void*)containers_detail::get_pointer(d.get())) Node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + NodePtr node = d.get(); + d.release(); + return iterator(this->icont().insert(p.get(), *node)); + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //0 args + void emplace_back() + { this->emplace(this->cend()); } + + void emplace_front() + { this->emplace(this->cbegin()); } + + iterator emplace(const_iterator p) + { + typename AllocHolder::Deallocator d(AllocHolder::create_node_and_deallocator()); + new ((void*)containers_detail::get_pointer(d.get())) Node(); + NodePtr node = d.get(); + d.release(); + return iterator(this->icont().insert(p.get(), *node)); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + this->emplace(this->cend(), BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + } \ + \ + template \ + void emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { this->emplace(this->cbegin(), BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _));} \ + \ + template \ + iterator emplace(const_iterator p, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + typename AllocHolder::Deallocator d(AllocHolder::create_node_and_deallocator()); \ + new ((void*)containers_detail::get_pointer(d.get())) \ + Node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + NodePtr node = d.get(); \ + d.release(); \ + return iterator(this->icont().insert(p.get(), *node)); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Erases the element at p p. + //! + //! Throws: Nothing. + //! + //! Complexity: Amortized constant time. + iterator erase(const_iterator p) + { return iterator(this->icont().erase_and_dispose(p.get(), Destroyer(this->node_alloc()))); } + + //! Requires: first and last must be valid iterator to elements in *this. + //! + //! Effects: Erases the elements pointed by [first, last). + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the distance between first and last. + iterator erase(const_iterator first, const_iterator last) + { return iterator(AllocHolder::erase_range(first.get(), last.get(), alloc_version())); } + + //! Effects: Assigns the n copies of val to *this. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n. + void assign(size_type n, const T& val) + { this->priv_fill_assign(n, val); } + + //! Effects: Assigns the the range [first, last) to *this. + //! + //! Throws: If memory allocation throws or + //! T's constructor from dereferencing InpIt throws. + //! + //! Complexity: Linear to n. + template + void assign(InpIt first, InpIt last) + { + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_assign_dispatch(first, last, Result()); + } + + //! Requires: p must point to an element contained + //! by the list. x != *this + //! + //! Effects: Transfers all the elements of list x to this list, before the + //! the element pointed by p. No destructors or copy constructors are called. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Constant. + //! + //! Note: Iterators of values obtained from list x now point to elements of + //! this list. Iterators of this list and all the references are not invalidated. + void splice(iterator p, ThisType& x) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice(p.get(), x.icont()); + } + else{ + throw std::runtime_error("list::splice called with unequal allocators"); + } + } + + //! Requires: p must point to an element contained + //! by this list. i must point to an element contained in list x. + //! + //! Effects: Transfers the value pointed by i, from list x to this list, + //! before the the element pointed by p. No destructors or copy constructors are called. + //! If p == i or p == ++i, this function is a null operation. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Constant. + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice(const_iterator p, ThisType &x, const_iterator i) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice(p.get(), x.icont(), i.get()); + } + else{ + throw std::runtime_error("list::splice called with unequal allocators"); + } + } + + //! Requires: p must point to an element contained + //! by this list. first and last must point to elements contained in list x. + //! + //! Effects: Transfers the range pointed by first and last from list x to this list, + //! before the the element pointed by p. No destructors or copy constructors are called. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Linear to the number of elements transferred. + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice(const_iterator p, ThisType &x, const_iterator first, const_iterator last) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice(p.get(), x.icont(), first.get(), last.get()); + } + else{ + throw std::runtime_error("list::splice called with unequal allocators"); + } + } + + //! Requires: p must point to an element contained + //! by this list. first and last must point to elements contained in list x. + //! n == std::distance(first, last) + //! + //! Effects: Transfers the range pointed by first and last from list x to this list, + //! before the the element pointed by p. No destructors or copy constructors are called. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Constant. + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice(const_iterator p, ThisType &x, const_iterator first, const_iterator last, size_type n) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice(p.get(), x.icont(), first.get(), last.get(), n); + } + else{ + throw std::runtime_error("list::splice called with unequal allocators"); + } + } + + //! Effects: Reverses the order of elements in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: This function is linear time. + //! + //! Note: Iterators and references are not invalidated + void reverse() + { this->icont().reverse(); } + + //! Effects: Removes all the elements that compare equal to value. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear time. It performs exactly size() comparisons for equality. + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + void remove(const T& value) + { remove_if(equal_to_value(value)); } + + //! Effects: Removes all the elements for which a specified + //! predicate is satisfied. + //! + //! Throws: If pred throws. + //! + //! Complexity: Linear time. It performs exactly size() calls to the predicate. + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + template + void remove_if(Pred pred) + { + typedef ValueCompareToNodeCompare Predicate; + this->icont().remove_and_dispose_if(Predicate(pred), Destroyer(this->node_alloc())); + } + + //! Effects: Removes adjacent duplicate elements or adjacent + //! elements that are equal from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear time (size()-1 comparisons calls to pred()). + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + void unique() + { this->unique(value_equal()); } + + //! Effects: Removes adjacent duplicate elements or adjacent + //! elements that satisfy some binary predicate from the list. + //! + //! Throws: If pred throws. + //! + //! Complexity: Linear time (size()-1 comparisons equality comparisons). + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + template + void unique(BinaryPredicate binary_pred) + { + typedef ValueCompareToNodeCompare Predicate; + this->icont().unique_and_dispose(Predicate(binary_pred), Destroyer(this->node_alloc())); + } + + //! Requires: The lists x and *this must be distinct. + //! + //! Effects: This function removes all of x's elements and inserts them + //! in order into *this according to std::less. The merge is stable; + //! that is, if an element from *this is equivalent to one from x, then the element + //! from *this will precede the one from x. + //! + //! Throws: Nothing. + //! + //! Complexity: This function is linear time: it performs at most + //! size() + x.size() - 1 comparisons. + void merge(list& x) + { this->merge(x, value_less()); } + + //! Requires: p must be a comparison function that induces a strict weak + //! ordering and both *this and x must be sorted according to that ordering + //! The lists x and *this must be distinct. + //! + //! Effects: This function removes all of x's elements and inserts them + //! in order into *this. The merge is stable; that is, if an element from *this is + //! equivalent to one from x, then the element from *this will precede the one from x. + //! + //! Throws: Nothing. + //! + //! Complexity: This function is linear time: it performs at most + //! size() + x.size() - 1 comparisons. + //! + //! Note: Iterators and references to *this are not invalidated. + template + void merge(list &x, StrictWeakOrdering comp) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().merge(x.icont(), + ValueCompareToNodeCompare(comp)); + } + else{ + throw std::runtime_error("list::merge called with unequal allocators"); + } + } + + //! Effects: This function sorts the list *this according to std::less. + //! The sort is stable, that is, the relative order of equivalent elements is preserved. + //! + //! Throws: Nothing. + //! + //! Notes: Iterators and references are not invalidated. + //! + //! Complexity: The number of comparisons is approximately N log N, where N + //! is the list's size. + void sort() + { this->sort(value_less()); } + + //! Effects: This function sorts the list *this according to std::less. + //! The sort is stable, that is, the relative order of equivalent elements is preserved. + //! + //! Throws: Nothing. + //! + //! Notes: Iterators and references are not invalidated. + //! + //! Complexity: The number of comparisons is approximately N log N, where N + //! is the list's size. + template + void sort(StrictWeakOrdering comp) + { + // nothing if the list has length 0 or 1. + if (this->size() < 2) + return; + this->icont().sort(ValueCompareToNodeCompare(comp)); + } + + /// @cond + private: + + iterator priv_insert(const_iterator p, const T &x) + { + NodePtr tmp = AllocHolder::create_node(x); + return iterator(this->icont().insert(p.get(), *tmp)); + } + + //Iterator range version + template + void priv_create_and_insert_nodes + (const_iterator pos, InpIterator beg, InpIterator end) + { + typedef typename std::iterator_traits::iterator_category ItCat; + priv_create_and_insert_nodes(pos, beg, end, alloc_version(), ItCat()); + } + + template + void priv_create_and_insert_nodes + (const_iterator pos, InpIterator beg, InpIterator end, allocator_v1, std::input_iterator_tag) + { + for (; beg != end; ++beg){ + this->icont().insert(pos.get(), *this->create_node_from_it(beg)); + } + } + + template + void priv_create_and_insert_nodes + (const_iterator pos, InpIterator beg, InpIterator end, allocator_v2, std::input_iterator_tag) + { //Just forward to the default one + priv_create_and_insert_nodes(pos, beg, end, allocator_v1(), std::input_iterator_tag()); + } + + class insertion_functor; + friend class insertion_functor; + + class insertion_functor + { + Icont &icont_; + typename Icont::const_iterator pos_; + + public: + insertion_functor(Icont &icont, typename Icont::const_iterator pos) + : icont_(icont), pos_(pos) + {} + + void operator()(Node &n) + { this->icont_.insert(pos_, n); } + }; + + + template + void priv_create_and_insert_nodes + (const_iterator pos, FwdIterator beg, FwdIterator end, allocator_v2, std::forward_iterator_tag) + { + if(beg != end){ + //Optimized allocation and construction + this->allocate_many_and_construct + (beg, std::distance(beg, end), insertion_functor(this->icont(), pos.get())); + } + } + + //Default constructed version + void priv_create_and_insert_nodes(const_iterator pos, size_type n) + { + typedef default_construct_iterator default_iterator; + this->priv_create_and_insert_nodes(pos, default_iterator(n), default_iterator()); + } + + //Copy constructed version + void priv_create_and_insert_nodes(const_iterator pos, size_type n, const T& x) + { + typedef constant_iterator cvalue_iterator; + this->priv_create_and_insert_nodes(pos, cvalue_iterator(x, n), cvalue_iterator()); + } + + //Dispatch to detect iterator range or integer overloads + template + void priv_insert_dispatch(const_iterator p, + InputIter first, InputIter last, + containers_detail::false_) + { this->priv_create_and_insert_nodes(p, first, last); } + + template + void priv_insert_dispatch(const_iterator p, Integer n, Integer x, containers_detail::true_) + { this->insert(p, (size_type)n, x); } + + void priv_fill_assign(size_type n, const T& val) + { + iterator i = this->begin(), iend = this->end(); + + for ( ; i != iend && n > 0; ++i, --n) + *i = val; + if (n > 0){ + this->priv_create_and_insert_nodes(this->cend(), n, val); + } + else{ + this->erase(i, cend()); + } + } + + template + void priv_assign_dispatch(Integer n, Integer val, containers_detail::true_) + { this->priv_fill_assign((size_type) n, (T) val); } + + template + void priv_assign_dispatch(InputIter first2, InputIter last2, containers_detail::false_) + { + iterator first1 = this->begin(); + iterator last1 = this->end(); + for ( ; first1 != last1 && first2 != last2; ++first1, ++first2) + *first1 = *first2; + if (first2 == last2) + this->erase(first1, last1); + else{ + this->priv_create_and_insert_nodes(last1, first2, last2); + } + } + + //Functors for member algorithm defaults + struct value_less + { + bool operator()(const value_type &a, const value_type &b) const + { return a < b; } + }; + + struct value_equal + { + bool operator()(const value_type &a, const value_type &b) const + { return a == b; } + }; + /// @endcond + +}; + +template +inline bool operator==(const list& x, const list& y) +{ + if(x.size() != y.size()){ + return false; + } + typedef typename list::const_iterator const_iterator; + const_iterator end1 = x.end(); + + const_iterator i1 = x.begin(); + const_iterator i2 = y.begin(); + while (i1 != end1 && *i1 == *i2) { + ++i1; + ++i2; + } + return i1 == end1; +} + +template +inline bool operator<(const list& x, + const list& y) +{ + return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); +} + +template +inline bool operator!=(const list& x, const list& y) +{ + return !(x == y); +} + +template +inline bool operator>(const list& x, const list& y) +{ + return y < x; +} + +template +inline bool operator<=(const list& x, const list& y) +{ + return !(y < x); +} + +template +inline bool operator>=(const list& x, const list& y) +{ + return !(x < y); +} + +template +inline void swap(list& x, list& y) +{ + x.swap(y); +} + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value; +}; +*/ +namespace container { + +/// @endcond + +}} + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif // BOOST_CONTAINERS_LIST_HPP_ diff --git a/utils/boost_idb/boost/interprocess/containers/container/map.hpp b/utils/boost_idb/boost/interprocess/containers/container/map.hpp new file mode 100644 index 00000000..4e6f9384 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/map.hpp @@ -0,0 +1,1286 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +// +// This file comes from SGI's stl_map/stl_multimap files. Modified by Ion Gaztanaga. +// Renaming, isolating and porting to generic algorithms. Pointer typedef +// set to allocator::pointer to allow placing it in shared memory. +// +/////////////////////////////////////////////////////////////////////////////// +/* + * + * Copyright (c) 1994 + * Hewlett-Packard Company + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Hewlett-Packard Company makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * + * Copyright (c) 1996 + * Silicon Graphics Computer Systems, Inc. + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Silicon Graphics makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + */ + +#ifndef BOOST_CONTAINERS_MAP_HPP +#define BOOST_CONTAINERS_MAP_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_TREE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_VALUE_INIT_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_PAIR_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +// Forward declarations of operators == and <, needed for friend declarations. +template +inline bool operator==(const map& x, + const map& y); + +template +inline bool operator<(const map& x, + const map& y); +/// @endcond + +//! A map is a kind of associative container that supports unique keys (contains at +//! most one of each key value) and provides for fast retrieval of values of another +//! type T based on the keys. The map class supports bidirectional iterators. +//! +//! A map satisfies all of the requirements of a container and of a reversible +//! container and of an associative container. For a +//! map the key_type is Key and the value_type is std::pair. +//! +//! Pred is the ordering function for Keys (e.g. std::less). +//! +//! Alloc is the allocator to allocate the value_types +//! (e.g. allocator< std::pair > ). +template +class map +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(map) + typedef containers_detail::rbtree, + containers_detail::select1st< std::pair >, + Pred, + Alloc> tree_t; + tree_t m_tree; // red-black tree representing map + /// @endcond + + public: + + // typedefs: + typedef typename tree_t::key_type key_type; + typedef typename tree_t::value_type value_type; + typedef typename tree_t::pointer pointer; + typedef typename tree_t::const_pointer const_pointer; + typedef typename tree_t::reference reference; + typedef typename tree_t::const_reference const_reference; + typedef T mapped_type; + typedef Pred key_compare; + typedef typename tree_t::iterator iterator; + typedef typename tree_t::const_iterator const_iterator; + typedef typename tree_t::reverse_iterator reverse_iterator; + typedef typename tree_t::const_reverse_iterator const_reverse_iterator; + typedef typename tree_t::size_type size_type; + typedef typename tree_t::difference_type difference_type; + typedef typename tree_t::allocator_type allocator_type; + typedef typename tree_t::stored_allocator_type stored_allocator_type; + typedef std::pair nonconst_value_type; + typedef containers_detail::pair + nonconst_impl_value_type; + + /// @cond + class value_compare_impl + : public Pred, + public std::binary_function + { + friend class map; + protected : + value_compare_impl(const Pred &c) : Pred(c) {} + public: + bool operator()(const value_type& x, const value_type& y) const { + return Pred::operator()(x.first, y.first); + } + }; + /// @endcond + typedef value_compare_impl value_compare; + + //! Effects: Constructs an empty map using the specified comparison object + //! and allocator. + //! + //! Complexity: Constant. + explicit map(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(comp, a) + {} + + //! Effects: Constructs an empty map using the specified comparison object and + //! allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + map(InputIterator first, InputIterator last, const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(first, last, comp, a, true) + {} + + //! Effects: Constructs an empty map using the specified comparison object and + //! allocator, and inserts elements from the ordered unique range [first ,last). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate and must be + //! unique values. + //! + //! Complexity: Linear in N. + template + map( ordered_unique_range_t, InputIterator first, InputIterator last + , const Pred& comp = Pred(), const allocator_type& a = allocator_type()) + : m_tree(ordered_range, first, last, comp, a) + {} + + //! Effects: Copy constructs a map. + //! + //! Complexity: Linear in x.size(). + map(const map& x) + : m_tree(x.m_tree) + {} + + //! Effects: Move constructs a map. Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + map(BOOST_MOVE_MACRO_RV_REF(map) x) + : m_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree)) + {} + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + map& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(map) x) + { m_tree = x.m_tree; return *this; } + + //! Effects: this->swap(x.get()). + //! + //! Complexity: Constant. + map& operator=(BOOST_MOVE_MACRO_RV_REF(map) x) + { m_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return m_tree.key_comp(); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return value_compare(m_tree.key_comp()); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return m_tree.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return m_tree.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return m_tree.get_stored_allocator(); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return m_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return m_tree.begin(); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return m_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return m_tree.end(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return m_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return m_tree.rbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return m_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return m_tree.rend(); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_tree.max_size(); } + + //! Effects: If there is no key equivalent to x in the map, inserts + //! value_type(x, T()) into the map. + //! + //! Returns: A reference to the mapped_type corresponding to x in *this. + //! + //! Complexity: Logarithmic. + T& operator[](const key_type& k) + { + //we can optimize this + iterator i = lower_bound(k); + // i->first is greater than or equivalent to k. + if (i == end() || key_comp()(k, (*i).first)){ + containers_detail::value_init v; + value_type val(k, BOOST_CONTAINER_MOVE_NAMESPACE::move(v.m_t)); + i = insert(i, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return (*i).second; + } + + //! Effects: If there is no key equivalent to x in the map, inserts + //! value_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(x), T()) into the map (the key is move-constructed) + //! + //! Returns: A reference to the mapped_type corresponding to x in *this. + //! + //! Complexity: Logarithmic. + T& operator[](BOOST_MOVE_MACRO_RV_REF(key_type) mk) + { + key_type &k = mk; + //we can optimize this + iterator i = lower_bound(k); + // i->first is greater than or equivalent to k. + if (i == end() || key_comp()(k, (*i).first)){ + value_type val(BOOST_CONTAINER_MOVE_NAMESPACE::move(k), BOOST_CONTAINER_MOVE_NAMESPACE::move(T())); + i = insert(i, BOOST_CONTAINER_MOVE_NAMESPACE::move(val)); + } + return (*i).second; + } + + //! Returns: A reference to the element whose key is equivalent to x. + //! Throws: An exception object of type out_of_range if no such element is present. + //! Complexity: logarithmic. + T& at(const key_type& k) + { + iterator i = this->find(k); + if(i == this->end()){ + throw std::out_of_range("key not found"); + } + return i->second; + } + + //! Returns: A reference to the element whose key is equivalent to x. + //! Throws: An exception object of type out_of_range if no such element is present. + //! Complexity: logarithmic. + const T& at(const key_type& k) const + { + const_iterator i = this->find(k); + if(i == this->end()){ + throw std::out_of_range("key not found"); + } + return i->second; + } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(map& x) + { m_tree.swap(x.m_tree); } + + //! Effects: Inserts x if and only if there is no element in the container + //! with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(const value_type& x) + { return m_tree.insert_unique(x); } + + //! Effects: Inserts a new value_type created from the pair if and only if + //! there is no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(const nonconst_value_type& x) + { return m_tree.insert_unique(x); } + + //! Effects: Inserts a new value_type move constructed from the pair if and + //! only if there is no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(nonconst_value_type) x) + { return m_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a new value_type move constructed from the pair if and + //! only if there is no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(nonconst_impl_value_type) x) + { return m_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Move constructs a new value from x if and only if there is + //! no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, const value_type& x) + { return m_tree.insert_unique(position, x); } + + //! Effects: Move constructs a new value from x if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, BOOST_MOVE_MACRO_RV_REF(nonconst_value_type) x) + { return m_tree.insert_unique(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Move constructs a new value from x if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, BOOST_MOVE_MACRO_RV_REF(nonconst_impl_value_type) x) + { return m_tree.insert_unique(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + iterator insert(iterator position, const nonconst_value_type& x) + { return m_tree.insert_unique(position, x); } + + //! Effects: Inserts an element move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + iterator insert(iterator position, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_tree.insert_unique(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) if and only + //! if there is no element with key equivalent to the key of that element. + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + template + void insert(InputIterator first, InputIterator last) + { m_tree.insert_unique(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container if and only if there is + //! no element in the container with an equivalent key. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + template + iterator emplace(Args&&... args) + { return m_tree.emplace_unique(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container if and only if there is + //! no element in the container with an equivalent key. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return m_tree.emplace_hint_unique(hint, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return m_tree.emplace_unique(); } + + iterator emplace_hint(const_iterator hint) + { return m_tree.emplace_hint_unique(hint); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_hint_unique(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _));}\ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by position. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Amortized constant time + iterator erase(const_iterator position) + { return m_tree.erase(position); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: log(size()) + count(k) + size_type erase(const key_type& x) + { return m_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: log(size())+N where N is the distance from first to last. + iterator erase(const_iterator first, const_iterator last) + { return m_tree.erase(first, last); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_tree.clear(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return m_tree.find(x); } + + //! Returns: A const_iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + const_iterator find(const key_type& x) const + { return m_tree.find(x); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_tree.find(x) == m_tree.end() ? 0 : 1; } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + { return m_tree.lower_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return m_tree.lower_bound(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return m_tree.upper_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return m_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) + { return m_tree.equal_range(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) const + { return m_tree.equal_range(x); } + + /// @cond + template + friend bool operator== (const map&, + const map&); + template + friend bool operator< (const map&, + const map&); + /// @endcond +}; + +template +inline bool operator==(const map& x, + const map& y) + { return x.m_tree == y.m_tree; } + +template +inline bool operator<(const map& x, + const map& y) + { return x.m_tree < y.m_tree; } + +template +inline bool operator!=(const map& x, + const map& y) + { return !(x == y); } + +template +inline bool operator>(const map& x, + const map& y) + { return y < x; } + +template +inline bool operator<=(const map& x, + const map& y) + { return !(y < x); } + +template +inline bool operator>=(const map& x, + const map& y) + { return !(x < y); } + +template +inline void swap(map& x, map& y) + { x.swap(y); } + +/// @cond + +// Forward declaration of operators < and ==, needed for friend declaration. + +template +inline bool operator==(const multimap& x, + const multimap& y); + +template +inline bool operator<(const multimap& x, + const multimap& y); + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +namespace container { + +/// @endcond + +//! A multimap is a kind of associative container that supports equivalent keys +//! (possibly containing multiple copies of the same key value) and provides for +//! fast retrieval of values of another type T based on the keys. The multimap class +//! supports bidirectional iterators. +//! +//! A multimap satisfies all of the requirements of a container and of a reversible +//! container and of an associative container. For a +//! map the key_type is Key and the value_type is std::pair. +//! +//! Pred is the ordering function for Keys (e.g. std::less). +//! +//! Alloc is the allocator to allocate the value_types +//!(e.g. allocator< std::pair<const Key, T> >). +template +class multimap +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(multimap) + typedef containers_detail::rbtree, + containers_detail::select1st< std::pair >, + Pred, + Alloc> tree_t; + tree_t m_tree; // red-black tree representing map + /// @endcond + + public: + + // typedefs: + typedef typename tree_t::key_type key_type; + typedef typename tree_t::value_type value_type; + typedef typename tree_t::pointer pointer; + typedef typename tree_t::const_pointer const_pointer; + typedef typename tree_t::reference reference; + typedef typename tree_t::const_reference const_reference; + typedef T mapped_type; + typedef Pred key_compare; + typedef typename tree_t::iterator iterator; + typedef typename tree_t::const_iterator const_iterator; + typedef typename tree_t::reverse_iterator reverse_iterator; + typedef typename tree_t::const_reverse_iterator const_reverse_iterator; + typedef typename tree_t::size_type size_type; + typedef typename tree_t::difference_type difference_type; + typedef typename tree_t::allocator_type allocator_type; + typedef typename tree_t::stored_allocator_type stored_allocator_type; + typedef std::pair nonconst_value_type; + typedef containers_detail::pair + nonconst_impl_value_type; + + /// @cond + class value_compare_impl + : public Pred, + public std::binary_function + { + friend class multimap; + protected : + value_compare_impl(const Pred &c) : Pred(c) {} + public: + bool operator()(const value_type& x, const value_type& y) const { + return Pred::operator()(x.first, y.first); + } + }; + /// @endcond + typedef value_compare_impl value_compare; + + //! Effects: Constructs an empty multimap using the specified comparison + //! object and allocator. + //! + //! Complexity: Constant. + explicit multimap(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(comp, a) + {} + + //! Effects: Constructs an empty multimap using the specified comparison object + //! and allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + multimap(InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(first, last, comp, a, false) + {} + + //! Effects: Constructs an empty multimap using the specified comparison object and + //! allocator, and inserts elements from the ordered range [first ,last). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate. + //! + //! Complexity: Linear in N. + template + multimap(ordered_range_t ordered_range, InputIterator first, InputIterator last, const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(ordered_range, first, last, comp, a) + {} + + + //! Effects: Copy constructs a multimap. + //! + //! Complexity: Linear in x.size(). + multimap(const multimap& x) + : m_tree(x.m_tree) + {} + + //! Effects: Move constructs a multimap. Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + multimap(BOOST_MOVE_MACRO_RV_REF(multimap) x) + : m_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree)) + {} + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + multimap& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(multimap) x) + { m_tree = x.m_tree; return *this; } + + //! Effects: this->swap(x.get()). + //! + //! Complexity: Constant. + multimap& operator=(BOOST_MOVE_MACRO_RV_REF(multimap) x) + { m_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return m_tree.key_comp(); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return value_compare(m_tree.key_comp()); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return m_tree.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return m_tree.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return m_tree.get_stored_allocator(); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return m_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return m_tree.begin(); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return m_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return m_tree.end(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return m_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return m_tree.rbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return m_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return m_tree.rend(); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_tree.max_size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(multimap& x) + { m_tree.swap(x.m_tree); } + + //! Effects: Inserts x and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic. + iterator insert(const value_type& x) + { return m_tree.insert_equal(x); } + + //! Effects: Inserts a new value constructed from x and returns + //! the iterator pointing to the newly inserted element. + //! + //! Complexity: Logarithmic. + iterator insert(const nonconst_value_type& x) + { return m_tree.insert_equal(x); } + + //! Effects: Inserts a new value move-constructed from x and returns + //! the iterator pointing to the newly inserted element. + //! + //! Complexity: Logarithmic. + iterator insert(BOOST_MOVE_MACRO_RV_REF(nonconst_value_type) x) + { return m_tree.insert_equal(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a new value move-constructed from x and returns + //! the iterator pointing to the newly inserted element. + //! + //! Complexity: Logarithmic. + iterator insert(BOOST_MOVE_MACRO_RV_REF(nonconst_impl_value_type) x) + { return m_tree.insert_equal(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, const value_type& x) + { return m_tree.insert_equal(position, x); } + + //! Effects: Inserts a new value constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, const nonconst_value_type& x) + { return m_tree.insert_equal(position, x); } + + //! Effects: Inserts a new value move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, BOOST_MOVE_MACRO_RV_REF(nonconst_value_type) x) + { return m_tree.insert_equal(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a new value move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(iterator position, BOOST_MOVE_MACRO_RV_REF(nonconst_impl_value_type) x) + { return m_tree.insert_equal(position, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) . + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + template + void insert(InputIterator first, InputIterator last) + { m_tree.insert_equal(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + template + iterator emplace(Args&&... args) + { return m_tree.emplace_equal(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return m_tree.emplace_hint_equal(hint, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return m_tree.emplace_equal(); } + + iterator emplace_hint(const_iterator hint) + { return m_tree.emplace_hint_equal(hint); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_hint_equal(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); }\ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by position. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Amortized constant time + iterator erase(const_iterator position) + { return m_tree.erase(position); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: log(size()) + count(k) + size_type erase(const key_type& x) + { return m_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: log(size())+N where N is the distance from first to last. + iterator erase(const_iterator first, const_iterator last) + { return m_tree.erase(first, last); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_tree.clear(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return m_tree.find(x); } + + //! Returns: A const iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + const_iterator find(const key_type& x) const + { return m_tree.find(x); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_tree.count(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + {return m_tree.lower_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return m_tree.lower_bound(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return m_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) + { return m_tree.equal_range(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return m_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) const + { return m_tree.equal_range(x); } + + /// @cond + template + friend bool operator== (const multimap& x, + const multimap& y); + + template + friend bool operator< (const multimap& x, + const multimap& y); + /// @endcond +}; + +template +inline bool operator==(const multimap& x, + const multimap& y) +{ return x.m_tree == y.m_tree; } + +template +inline bool operator<(const multimap& x, + const multimap& y) +{ return x.m_tree < y.m_tree; } + +template +inline bool operator!=(const multimap& x, + const multimap& y) +{ return !(x == y); } + +template +inline bool operator>(const multimap& x, + const multimap& y) +{ return y < x; } + +template +inline bool operator<=(const multimap& x, + const multimap& y) +{ return !(y < x); } + +template +inline bool operator>=(const multimap& x, + const multimap& y) +{ return !(x < y); } + +template +inline void swap(multimap& x, multimap& y) +{ x.swap(y); } + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +namespace container { + +/// @endcond + +}} + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif /* BOOST_CONTAINERS_MAP_HPP */ + diff --git a/utils/boost_idb/boost/interprocess/containers/container/set.hpp b/utils/boost_idb/boost/interprocess/containers/container/set.hpp new file mode 100644 index 00000000..35a466b9 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/set.hpp @@ -0,0 +1,1155 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_SET_HPP +#define BOOST_CONTAINERS_SET_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP + +#include +#include +#include + +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_TREE_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#ifndef BOOST_CONTAINERS_PERFECT_FORWARDING +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +// Forward declarations of operators < and ==, needed for friend declaration. +template +inline bool operator==(const set& x, + const set& y); + +template +inline bool operator<(const set& x, + const set& y); +/// @endcond + +//! A set is a kind of associative container that supports unique keys (contains at +//! most one of each key value) and provides for fast retrieval of the keys themselves. +//! Class set supports bidirectional iterators. +//! +//! A set satisfies all of the requirements of a container and of a reversible container +//! , and of an associative container. A set also provides most operations described in +//! for unique keys. +template +class set +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(set) + typedef containers_detail::rbtree, Pred, Alloc> tree_t; + tree_t m_tree; // red-black tree representing set + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + /// @endcond + + public: + + // typedefs: + typedef typename tree_t::key_type key_type; + typedef typename tree_t::value_type value_type; + typedef typename tree_t::pointer pointer; + typedef typename tree_t::const_pointer const_pointer; + typedef typename tree_t::reference reference; + typedef typename tree_t::const_reference const_reference; + typedef Pred key_compare; + typedef Pred value_compare; + typedef typename tree_t::iterator iterator; + typedef typename tree_t::const_iterator const_iterator; + typedef typename tree_t::reverse_iterator reverse_iterator; + typedef typename tree_t::const_reverse_iterator const_reverse_iterator; + typedef typename tree_t::size_type size_type; + typedef typename tree_t::difference_type difference_type; + typedef typename tree_t::allocator_type allocator_type; + typedef typename tree_t::stored_allocator_type stored_allocator_type; + + //! Effects: Constructs an empty set using the specified comparison object + //! and allocator. + //! + //! Complexity: Constant. + explicit set(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(comp, a) + {} + + //! Effects: Constructs an empty set using the specified comparison object and + //! allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + set(InputIterator first, InputIterator last, const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(first, last, comp, a, true) + {} + + //! Effects: Constructs an empty set using the specified comparison object and + //! allocator, and inserts elements from the ordered unique range [first ,last). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate and must be + //! unique values. + //! + //! Complexity: Linear in N. + template + set( ordered_unique_range_t, InputIterator first, InputIterator last + , const Pred& comp = Pred(), const allocator_type& a = allocator_type()) + : m_tree(ordered_range, first, last, comp, a) + {} + + //! Effects: Copy constructs a set. + //! + //! Complexity: Linear in x.size(). + set(const set& x) + : m_tree(x.m_tree) + {} + + //! Effects: Move constructs a set. Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + set(BOOST_MOVE_MACRO_RV_REF(set) x) + : m_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree)) + {} + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + set& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(set) x) + { m_tree = x.m_tree; return *this; } + + //! Effects: this->swap(x.get()). + //! + //! Complexity: Constant. + set& operator=(BOOST_MOVE_MACRO_RV_REF(set) x) + { m_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return m_tree.key_comp(); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return m_tree.key_comp(); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return m_tree.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return m_tree.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return m_tree.get_stored_allocator(); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant + iterator begin() + { return m_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return m_tree.begin(); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return m_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return m_tree.end(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return m_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return m_tree.rbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return m_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return m_tree.rend(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return m_tree.cbegin(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return m_tree.cend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return m_tree.crbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return m_tree.crend(); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_tree.max_size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(set& x) + { m_tree.swap(x.m_tree); } + + //! Effects: Inserts x if and only if there is no element in the container + //! with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(insert_const_ref_type x) + { return priv_insert(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + std::pair insert(T &x) + { return this->insert(const_cast(x)); } + + template + std::pair insert(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(u); } + #endif + + //! Effects: Move constructs a new value from x if and only if there is + //! no element in the container with key equivalent to the key of x. + //! + //! Returns: The bool component of the returned pair is true if and only + //! if the insertion takes place, and the iterator component of the pair + //! points to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + std::pair insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_tree.insert_unique(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container if and only if there is + //! no element in the container with key equivalent to the key of x. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(const_iterator p, insert_const_ref_type x) + { return priv_insert(p, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) + { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(position, u); } + #endif + + //! Effects: Inserts an element move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + iterator insert(const_iterator p, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_tree.insert_unique(p, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) if and only + //! if there is no element with key equivalent to the key of that element. + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + template + void insert(InputIterator first, InputIterator last) + { m_tree.insert_unique(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... if and only if there is + //! no element in the container with equivalent value. + //! and returns the iterator pointing to the + //! newly inserted element. + //! + //! Throws: If memory allocation throws or + //! T's in-place constructor throws. + //! + //! Complexity: Logarithmic. + template + iterator emplace(Args&&... args) + { return m_tree.emplace_unique(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... if and only if there is + //! no element in the container with equivalent value. + //! p is a hint pointing to where the insert + //! should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent to the key of x. + //! + //! Complexity: Logarithmic. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return m_tree.emplace_hint_unique(hint, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return m_tree.emplace_unique(); } + + iterator emplace_hint(const_iterator hint) + { return m_tree.emplace_hint_unique(hint); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_hint_unique(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _));}\ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by p. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Amortized constant time + iterator erase(const_iterator p) + { return m_tree.erase(p); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: log(size()) + count(k) + size_type erase(const key_type& x) + { return m_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: log(size())+N where N is the distance from first to last. + iterator erase(const_iterator first, const_iterator last) + { return m_tree.erase(first, last); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_tree.clear(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return m_tree.find(x); } + + //! Returns: A const_iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + const_iterator find(const key_type& x) const + { return m_tree.find(x); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_tree.find(x) == m_tree.end() ? 0 : 1; } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + { return m_tree.lower_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return m_tree.lower_bound(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return m_tree.upper_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return m_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) + { return m_tree.equal_range(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) const + { return m_tree.equal_range(x); } + + /// @cond + template + friend bool operator== (const set&, const set&); + + template + friend bool operator< (const set&, const set&); + + private: + std::pair priv_insert(const T &x) + { return m_tree.insert_unique(x); } + + iterator priv_insert(const_iterator p, const T &x) + { return m_tree.insert_unique(p, x); } + + /// @endcond +}; + +template +inline bool operator==(const set& x, + const set& y) +{ return x.m_tree == y.m_tree; } + +template +inline bool operator<(const set& x, + const set& y) +{ return x.m_tree < y.m_tree; } + +template +inline bool operator!=(const set& x, + const set& y) +{ return !(x == y); } + +template +inline bool operator>(const set& x, + const set& y) +{ return y < x; } + +template +inline bool operator<=(const set& x, + const set& y) +{ return !(y < x); } + +template +inline bool operator>=(const set& x, + const set& y) +{ return !(x < y); } + +template +inline void swap(set& x, set& y) +{ x.swap(y); } + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +namespace container { + +// Forward declaration of operators < and ==, needed for friend declaration. + +template +inline bool operator==(const multiset& x, + const multiset& y); + +template +inline bool operator<(const multiset& x, + const multiset& y); +/// @endcond + +//! A multiset is a kind of associative container that supports equivalent keys +//! (possibly contains multiple copies of the same key value) and provides for +//! fast retrieval of the keys themselves. Class multiset supports bidirectional iterators. +//! +//! A multiset satisfies all of the requirements of a container and of a reversible +//! container, and of an associative container). multiset also provides most operations +//! described for duplicate keys. +template +class multiset +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(multiset) + typedef containers_detail::rbtree, Pred, Alloc> tree_t; + tree_t m_tree; // red-black tree representing multiset + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + /// @endcond + + public: + + // typedefs: + typedef typename tree_t::key_type key_type; + typedef typename tree_t::value_type value_type; + typedef typename tree_t::pointer pointer; + typedef typename tree_t::const_pointer const_pointer; + typedef typename tree_t::reference reference; + typedef typename tree_t::const_reference const_reference; + typedef Pred key_compare; + typedef Pred value_compare; + typedef typename tree_t::iterator iterator; + typedef typename tree_t::const_iterator const_iterator; + typedef typename tree_t::reverse_iterator reverse_iterator; + typedef typename tree_t::const_reverse_iterator const_reverse_iterator; + typedef typename tree_t::size_type size_type; + typedef typename tree_t::difference_type difference_type; + typedef typename tree_t::allocator_type allocator_type; + typedef typename tree_t::stored_allocator_type stored_allocator_type; + + //! Effects: Constructs an empty multiset using the specified comparison + //! object and allocator. + //! + //! Complexity: Constant. + explicit multiset(const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(comp, a) + {} + + //! Effects: Constructs an empty multiset using the specified comparison object + //! and allocator, and inserts elements from the range [first ,last ). + //! + //! Complexity: Linear in N if the range [first ,last ) is already sorted using + //! comp and otherwise N logN, where N is last - first. + template + multiset(InputIterator first, InputIterator last, + const Pred& comp = Pred(), + const allocator_type& a = allocator_type()) + : m_tree(first, last, comp, a, false) + {} + + //! Effects: Constructs an empty multiset using the specified comparison object and + //! allocator, and inserts elements from the ordered range [first ,last ). This function + //! is more efficient than the normal range creation for ordered ranges. + //! + //! Requires: [first ,last) must be ordered according to the predicate. + //! + //! Complexity: Linear in N. + template + multiset( ordered_range_t ordered_range, InputIterator first, InputIterator last + , const Pred& comp = Pred() + , const allocator_type& a = allocator_type()) + : m_tree(ordered_range, first, last, comp, a) + {} + + //! Effects: Copy constructs a multiset. + //! + //! Complexity: Linear in x.size(). + multiset(const multiset& x) + : m_tree(x.m_tree) + {} + + //! Effects: Move constructs a multiset. Constructs *this using x's resources. + //! + //! Complexity: Construct. + //! + //! Postcondition: x is emptied. + multiset(BOOST_MOVE_MACRO_RV_REF(multiset) x) + : m_tree(BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree)) + {} + + //! Effects: Makes *this a copy of x. + //! + //! Complexity: Linear in x.size(). + multiset& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(multiset) x) + { m_tree = x.m_tree; return *this; } + + //! Effects: this->swap(x.get()). + //! + //! Complexity: Constant. + multiset& operator=(BOOST_MOVE_MACRO_RV_REF(multiset) x) + { m_tree = BOOST_CONTAINER_MOVE_NAMESPACE::move(x.m_tree); return *this; } + + //! Effects: Returns the comparison object out + //! of which a was constructed. + //! + //! Complexity: Constant. + key_compare key_comp() const + { return m_tree.key_comp(); } + + //! Effects: Returns an object of value_compare constructed out + //! of the comparison object. + //! + //! Complexity: Constant. + value_compare value_comp() const + { return m_tree.key_comp(); } + + //! Effects: Returns a copy of the Allocator that + //! was passed to the object's constructor. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return m_tree.get_allocator(); } + + const stored_allocator_type &get_stored_allocator() const + { return m_tree.get_stored_allocator(); } + + stored_allocator_type &get_stored_allocator() + { return m_tree.get_stored_allocator(); } + + //! Effects: Returns an iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return m_tree.begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return m_tree.begin(); } + + //! Effects: Returns an iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return m_tree.end(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return m_tree.end(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return m_tree.rbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return m_tree.rbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return m_tree.rend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return m_tree.rend(); } + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return m_tree.cbegin(); } + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return m_tree.cend(); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const + { return m_tree.crbegin(); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return m_tree.crend(); } + + //! Effects: Returns true if the container contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return m_tree.empty(); } + + //! Effects: Returns the number of the elements contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return m_tree.size(); } + + //! Effects: Returns the largest possible size of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return m_tree.max_size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(multiset& x) + { m_tree.swap(x.m_tree); } + + //! Effects: Inserts x and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic. + iterator insert(insert_const_ref_type x) + { return priv_insert(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(T &x) + { return this->insert(const_cast(x)); } + + template + iterator insert(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(u); } + #endif + + //! Effects: Inserts a copy of x in the container. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_tree.insert_equal(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Effects: Inserts a copy of x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(const_iterator p, insert_const_ref_type x) + { return priv_insert(p, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) + { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_insert(position, u); } + #endif + + //! Effects: Inserts a value move constructed from x in the container. + //! p is a hint pointing to where the insert should start to search. + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + iterator insert(const_iterator p, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return m_tree.insert_equal(p, BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: i, j are not iterators into *this. + //! + //! Effects: inserts each element from the range [i,j) . + //! + //! Complexity: N log(size()+N) (N is the distance from i to j) + template + void insert(InputIterator first, InputIterator last) + { m_tree.insert_equal(first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... and returns the iterator pointing to the + //! newly inserted element. + //! + //! Complexity: Logarithmic. + template + iterator emplace(Args&&... args) + { return m_tree.emplace_equal(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... + //! + //! Returns: An iterator pointing to the element with key equivalent + //! to the key of x. + //! + //! Complexity: Logarithmic in general, but amortized constant if t + //! is inserted right before p. + template + iterator emplace_hint(const_iterator hint, Args&&... args) + { return m_tree.emplace_hint_equal(hint, BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator emplace() + { return m_tree.emplace_equal(); } + + iterator emplace_hint(const_iterator hint) + { return m_tree.emplace_hint_equal(hint); } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \ + \ + template \ + iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { return m_tree.emplace_hint_equal(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); }\ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element pointed to by p. + //! + //! Returns: Returns an iterator pointing to the element immediately + //! following q prior to the element being erased. If no such element exists, + //! returns end(). + //! + //! Complexity: Amortized constant time + iterator erase(const_iterator p) + { return m_tree.erase(p); } + + //! Effects: Erases all elements in the container with key equivalent to x. + //! + //! Returns: Returns the number of erased elements. + //! + //! Complexity: log(size()) + count(k) + size_type erase(const key_type& x) + { return m_tree.erase(x); } + + //! Effects: Erases all the elements in the range [first, last). + //! + //! Returns: Returns last. + //! + //! Complexity: log(size())+N where N is the distance from first to last. + iterator erase(const_iterator first, const_iterator last) + { return m_tree.erase(first, last); } + + //! Effects: erase(a.begin(),a.end()). + //! + //! Postcondition: size() == 0. + //! + //! Complexity: linear in size(). + void clear() + { m_tree.clear(); } + + //! Returns: An iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + iterator find(const key_type& x) + { return m_tree.find(x); } + + //! Returns: A const iterator pointing to an element with the key + //! equivalent to x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic. + const_iterator find(const key_type& x) const + { return m_tree.find(x); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) const + { return m_tree.count(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator lower_bound(const key_type& x) + { return m_tree.lower_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than k, or a.end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator lower_bound(const key_type& x) const + { return m_tree.lower_bound(x); } + + //! Returns: An iterator pointing to the first element with key not less + //! than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + iterator upper_bound(const key_type& x) + { return m_tree.upper_bound(x); } + + //! Returns: A const iterator pointing to the first element with key not + //! less than x, or end() if such an element is not found. + //! + //! Complexity: Logarithmic + const_iterator upper_bound(const key_type& x) const + { return m_tree.upper_bound(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) + { return m_tree.equal_range(x); } + + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair + equal_range(const key_type& x) const + { return m_tree.equal_range(x); } + + /// @cond + template + friend bool operator== (const multiset&, + const multiset&); + template + friend bool operator< (const multiset&, + const multiset&); + private: + iterator priv_insert(const T &x) + { return m_tree.insert_equal(x); } + + iterator priv_insert(const_iterator p, const T &x) + { return m_tree.insert_equal(p, x); } + + /// @endcond +}; + +template +inline bool operator==(const multiset& x, + const multiset& y) +{ return x.m_tree == y.m_tree; } + +template +inline bool operator<(const multiset& x, + const multiset& y) +{ return x.m_tree < y.m_tree; } + +template +inline bool operator!=(const multiset& x, + const multiset& y) +{ return !(x == y); } + +template +inline bool operator>(const multiset& x, + const multiset& y) +{ return y < x; } + +template +inline bool operator<=(const multiset& x, + const multiset& y) +{ return !(y < x); } + +template +inline bool operator>=(const multiset& x, + const multiset& y) +{ return !(x < y); } + +template +inline void swap(multiset& x, multiset& y) +{ x.swap(y); } + +/// @cond + +} //namespace container { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value && has_trivial_destructor::value; +}; +*/ +namespace container { + +/// @endcond + +}} + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif /* BOOST_CONTAINERS_SET_HPP */ + diff --git a/utils/boost_idb/boost/interprocess/containers/container/slist.hpp b/utils/boost_idb/boost/interprocess/containers/container/slist.hpp new file mode 100644 index 00000000..622ec9d5 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/slist.hpp @@ -0,0 +1,1532 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2004-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_SLIST_HPP +#define BOOST_CONTAINERS_SLIST_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_NODE_ALLOC_HOLDER_HPP +#include + + +#if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) +//Preprocessor library to emulate perfect forwarding +#else +#include INCLUDE_BOOST_CONTAINER_DETAIL_PREPROCESSOR_HPP +#endif + +#include +#include +#include +#include +#include +#include + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond + +namespace containers_detail { + +template +struct slist_hook +{ + typedef typename containers_detail::bi::make_slist_base_hook + , containers_detail::bi::link_mode >::type type; +}; + +template +struct slist_node + : public slist_hook::type +{ + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + slist_node() + : m_data() + {} + + template + slist_node(Args &&...args) + : m_data(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...) + {} + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + slist_node() + : m_data() + {} + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + slist_node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + : m_data(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)) \ + {} \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif//#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + T m_data; +}; + +template +struct intrusive_slist_type +{ + typedef typename A::value_type value_type; + typedef typename boost::pointer_to_other + ::type void_pointer; + typedef typename containers_detail::slist_node + node_type; + + typedef typename containers_detail::bi::make_slist + ::type> + ,containers_detail::bi::constant_time_size + ,containers_detail::bi::size_type + >::type container_type; + typedef container_type type ; +}; + +} //namespace containers_detail { + +/// @endcond + +//! An slist is a singly linked list: a list where each element is linked to the next +//! element, but not to the previous element. That is, it is a Sequence that +//! supports forward but not backward traversal, and (amortized) constant time +//! insertion and removal of elements. Slists, like lists, have the important +//! property that insertion and splicing do not invalidate iterators to list elements, +//! and that even removal invalidates only the iterators that point to the elements +//! that are removed. The ordering of iterators may be changed (that is, +//! slist::iterator might have a different predecessor or successor after a list +//! operation than it did before), but the iterators themselves will not be invalidated +//! or made to point to different elements unless that invalidation or mutation is explicit. +//! +//! The main difference between slist and list is that list's iterators are bidirectional +//! iterators, while slist's iterators are forward iterators. This means that slist is +//! less versatile than list; frequently, however, bidirectional iterators are +//! unnecessary. You should usually use slist unless you actually need the extra +//! functionality of list, because singly linked lists are smaller and faster than double +//! linked lists. +//! +//! Important performance note: like every other Sequence, slist defines the member +//! functions insert and erase. Using these member functions carelessly, however, can +//! result in disastrously slow programs. The problem is that insert's first argument is +//! an iterator p, and that it inserts the new element(s) before p. This means that +//! insert must find the iterator just before p; this is a constant-time operation +//! for list, since list has bidirectional iterators, but for slist it must find that +//! iterator by traversing the list from the beginning up to p. In other words: +//! insert and erase are slow operations anywhere but near the beginning of the slist. +//! +//! Slist provides the member functions insert_after and erase_after, which are constant +//! time operations: you should always use insert_after and erase_after whenever +//! possible. If you find that insert_after and erase_after aren't adequate for your +//! needs, and that you often need to use insert and erase in the middle of the list, +//! then you should probably use list instead of slist. +template +class slist + : protected containers_detail::node_alloc_holder + ::type> +{ + /// @cond + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + typedef typename + containers_detail::intrusive_slist_type::type Icont; + typedef containers_detail::node_alloc_holder AllocHolder; + typedef typename AllocHolder::NodePtr NodePtr; + typedef slist ThisType; + typedef typename AllocHolder::NodeAlloc NodeAlloc; + typedef typename AllocHolder::ValAlloc ValAlloc; + typedef typename AllocHolder::Node Node; + typedef containers_detail::allocator_destroyer Destroyer; + typedef typename AllocHolder::allocator_v1 allocator_v1; + typedef typename AllocHolder::allocator_v2 allocator_v2; + typedef typename AllocHolder::alloc_version alloc_version; + + class equal_to_value + { + typedef typename AllocHolder::value_type value_type; + const value_type &t_; + + public: + equal_to_value(const value_type &t) + : t_(t) + {} + + bool operator()(const value_type &t)const + { return t_ == t; } + }; + + template + struct ValueCompareToNodeCompare + : Pred + { + ValueCompareToNodeCompare(Pred pred) + : Pred(pred) + {} + + bool operator()(const Node &a, const Node &b) const + { return static_cast(*this)(a.m_data, b.m_data); } + + bool operator()(const Node &a) const + { return static_cast(*this)(a.m_data); } + }; + /// @endcond + public: + //! The type of object, T, stored in the list + typedef T value_type; + //! Pointer to T + typedef typename A::pointer pointer; + //! Const pointer to T + typedef typename A::const_pointer const_pointer; + //! Reference to T + typedef typename A::reference reference; + //! Const reference to T + typedef typename A::const_reference const_reference; + //! An unsigned integral type + typedef typename A::size_type size_type; + //! A signed integral type + typedef typename A::difference_type difference_type; + //! The allocator type + typedef A allocator_type; + //! The stored allocator type + typedef NodeAlloc stored_allocator_type; + + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(slist) + typedef difference_type list_difference_type; + typedef pointer list_pointer; + typedef const_pointer list_const_pointer; + typedef reference list_reference; + typedef const_reference list_const_reference; + /// @endcond + + public: + + //! Const iterator used to iterate through a list. + class const_iterator + /// @cond + : public std::iterator + { + + protected: + typename Icont::iterator m_it; + explicit const_iterator(typename Icont::iterator it) : m_it(it){} + void prot_incr(){ ++m_it; } + + private: + typename Icont::iterator get() + { return this->m_it; } + + public: + friend class slist; + typedef list_difference_type difference_type; + + //Constructors + const_iterator() + : m_it() + {} + + //Pointer like operators + const_reference operator*() const + { return m_it->m_data; } + + const_pointer operator->() const + { return const_pointer(&m_it->m_data); } + + //Increment / Decrement + const_iterator& operator++() + { prot_incr(); return *this; } + + const_iterator operator++(int) + { typename Icont::iterator tmp = m_it; ++*this; return const_iterator(tmp); } + + //Comparison operators + bool operator== (const const_iterator& r) const + { return m_it == r.m_it; } + + bool operator!= (const const_iterator& r) const + { return m_it != r.m_it; } + } + /// @endcond + ; + + //! Iterator used to iterate through a list + class iterator + /// @cond + : public const_iterator + { + + private: + explicit iterator(typename Icont::iterator it) + : const_iterator(it) + {} + + typename Icont::iterator get() + { return this->m_it; } + + public: + friend class slist; + typedef list_pointer pointer; + typedef list_reference reference; + + //Constructors + iterator(){} + + //Pointer like operators + reference operator*() const { return this->m_it->m_data; } + pointer operator->() const { return pointer(&this->m_it->m_data); } + + //Increment / Decrement + iterator& operator++() + { this->prot_incr(); return *this; } + + iterator operator++(int) + { typename Icont::iterator tmp = this->m_it; ++*this; return iterator(tmp); } + } + /// @endcond + ; + + public: + //! Effects: Constructs a list taking the allocator as parameter. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + explicit slist(const allocator_type& a = allocator_type()) + : AllocHolder(a) + {} + + explicit slist(size_type n) + : AllocHolder(allocator_type()) + { this->resize(n); } + + //! Effects: Constructs a list that will use a copy of allocator a + //! and inserts n copies of value. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's default or copy constructor throws. + //! + //! Complexity: Linear to n. + explicit slist(size_type n, const value_type& x, const allocator_type& a = allocator_type()) + : AllocHolder(a) + { this->priv_create_and_insert_nodes(this->before_begin(), n, x); } + + //! Effects: Constructs a list that will use a copy of allocator a + //! and inserts a copy of the range [first, last) in the list. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's constructor taking an dereferenced InIt throws. + //! + //! Complexity: Linear to the range [first, last). + template + slist(InpIt first, InpIt last, + const allocator_type& a = allocator_type()) + : AllocHolder(a) + { this->insert_after(this->before_begin(), first, last); } + + //! Effects: Copy constructs a list. + //! + //! Postcondition: x == *this. + //! + //! Throws: If allocator_type's default constructor or copy constructor throws. + //! + //! Complexity: Linear to the elements x contains. + slist(const slist& x) + : AllocHolder(x) + { this->insert_after(this->before_begin(), x.begin(), x.end()); } + + //! Effects: Move constructor. Moves mx's resources to *this. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + slist(BOOST_MOVE_MACRO_RV_REF(slist) x) + : AllocHolder(BOOST_CONTAINER_MOVE_NAMESPACE::move((AllocHolder&)x)) + {} + + //! Effects: Makes *this contain the same elements as x. + //! + //! Postcondition: this->size() == x.size(). *this contains a copy + //! of each of x's elements. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to the number of elements in x. + slist& operator= (BOOST_MOVE_MACRO_COPY_ASSIGN_REF(slist) x) + { + if (&x != this){ + this->assign(x.begin(), x.end()); + } + return *this; + } + + //! Effects: Makes *this contain the same elements as x. + //! + //! Postcondition: this->size() == x.size(). *this contains a copy + //! of each of x's elements. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to the number of elements in x. + slist& operator= (BOOST_MOVE_MACRO_RV_REF(slist) mx) + { + if (&mx != this){ + this->clear(); + this->swap(mx); + } + return *this; + } + + //! Effects: Destroys the list. All stored values are destroyed + //! and used memory is deallocated. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements. + ~slist() + {} //AllocHolder clears the slist + + //! Effects: Returns a copy of the internal allocator. + //! + //! Throws: If allocator's copy constructor throws. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return allocator_type(this->node_alloc()); } + + const stored_allocator_type &get_stored_allocator() const + { return this->node_alloc(); } + + stored_allocator_type &get_stored_allocator() + { return this->node_alloc(); } + + public: + + //! Effects: Assigns the n copies of val to *this. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n. + void assign(size_type n, const T& val) + { this->priv_fill_assign(n, val); } + + //! Effects: Assigns the range [first, last) to *this. + //! + //! Throws: If memory allocation throws or + //! T's constructor from dereferencing InpIt throws. + //! + //! Complexity: Linear to n. + template + void assign(InpIt first, InpIt last) + { + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_assign_dispatch(first, last, Result()); + } + + //! Effects: Returns an iterator to the first element contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return iterator(this->icont().begin()); } + + //! Effects: Returns a const_iterator to the first element contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return this->cbegin(); } + + //! Effects: Returns an iterator to the end of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return iterator(this->icont().end()); } + + //! Effects: Returns a const_iterator to the end of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return this->cend(); } + + //! Effects: Returns a non-dereferenceable iterator that, + //! when incremented, yields begin(). This iterator may be used + //! as the argument toinsert_after, erase_after, etc. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator before_begin() + { return iterator(end()); } + + //! Effects: Returns a non-dereferenceable const_iterator + //! that, when incremented, yields begin(). This iterator may be used + //! as the argument toinsert_after, erase_after, etc. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator before_begin() const + { return this->cbefore_begin(); } + + //! Effects: Returns a const_iterator to the first element contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return const_iterator(this->non_const_icont().begin()); } + + //! Effects: Returns a const_iterator to the end of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return const_iterator(this->non_const_icont().end()); } + + //! Effects: Returns a non-dereferenceable const_iterator + //! that, when incremented, yields begin(). This iterator may be used + //! as the argument toinsert_after, erase_after, etc. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbefore_begin() const + { return const_iterator(end()); } + + //! Effects: Returns the number of the elements contained in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return this->icont().size(); } + + //! Effects: Returns the largest possible size of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return AllocHolder::max_size(); } + + //! Effects: Returns true if the list contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return !this->size(); } + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() + //! allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements on *this and x. + void swap(slist& x) + { AllocHolder::swap(x); } + + //! Requires: !empty() + //! + //! Effects: Returns a reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference front() + { return *this->begin(); } + + //! Requires: !empty() + //! + //! Effects: Returns a const reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference front() const + { return *this->begin(); } + + //! Effects: Inserts a copy of t in the beginning of the list. + //! + //! Throws: If memory allocation throws or + //! T's copy constructor throws. + //! + //! Complexity: Amortized constant time. + void push_front(insert_const_ref_type x) + { return priv_push_front(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_front(T &x) { push_front(const_cast(x)); } + + template + void push_front(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_push_front(u); } + #endif + + //! Effects: Constructs a new element in the beginning of the list + //! and moves the resources of t to this new element. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: Amortized constant time. + void push_front(BOOST_MOVE_MACRO_RV_REF(T) x) + { this->icont().push_front(*this->create_node(BOOST_CONTAINER_MOVE_NAMESPACE::move(x))); } + + //! Effects: Removes the first element from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Amortized constant time. + void pop_front() + { this->icont().pop_front_and_dispose(Destroyer(this->node_alloc())); } + + //! Returns: The iterator to the element before i in the sequence. + //! Returns the end-iterator, if either i is the begin-iterator or the + //! sequence is empty. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements before i. + iterator previous(iterator p) + { return iterator(this->icont().previous(p.get())); } + + //! Returns: The const_iterator to the element before i in the sequence. + //! Returns the end-const_iterator, if either i is the begin-const_iterator or + //! the sequence is empty. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements before i. + const_iterator previous(const_iterator p) + { return const_iterator(this->icont().previous(p.get())); } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Inserts a copy of the value after the p pointed + //! by prev_p. + //! + //! Returns: An iterator to the inserted element. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Amortized constant time. + //! + //! Note: Does not affect the validity of iterators and references of + //! previous values. + iterator insert_after(const_iterator prev_pos, insert_const_ref_type x) + { return this->priv_insert_after(prev_pos, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert_after(const_iterator position, T &x) + { return this->insert_after(position, const_cast(x)); } + + template + iterator insert_after(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return this->priv_insert_after(position, u); } + #endif + + //! Requires: prev_pos must be a valid iterator of *this. + //! + //! Effects: Inserts a move constructed copy object from the value after the + //! p pointed by prev_pos. + //! + //! Returns: An iterator to the inserted element. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: Amortized constant time. + //! + //! Note: Does not affect the validity of iterators and references of + //! previous values. + iterator insert_after(const_iterator prev_pos, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return iterator(this->icont().insert_after(prev_pos.get(), *this->create_node(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)))); } + + //! Requires: prev_pos must be a valid iterator of *this. + //! + //! Effects: Inserts n copies of x after prev_pos. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n. + //! + //! Note: Does not affect the validity of iterators and references of + //! previous values. + void insert_after(const_iterator prev_pos, size_type n, const value_type& x) + { this->priv_create_and_insert_nodes(prev_pos, n, x); } + + //! Requires: prev_pos must be a valid iterator of *this. + //! + //! Effects: Inserts the range pointed by [first, last) + //! after the p prev_pos. + //! + //! Throws: If memory allocation throws, T's constructor from a + //! dereferenced InpIt throws. + //! + //! Complexity: Linear to the number of elements inserted. + //! + //! Note: Does not affect the validity of iterators and references of + //! previous values. + template + void insert_after(const_iterator prev_pos, InIter first, InIter last) + { + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_insert_after_range_dispatch(prev_pos, first, last, Result()); + } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Insert a copy of x before p. + //! + //! Throws: If memory allocation throws or x's copy constructor throws. + //! + //! Complexity: Linear to the elements before p. + iterator insert(const_iterator position, insert_const_ref_type x) + { return this->priv_insert(position, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) + { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return this->priv_insert(position, u); } + #endif + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Insert a new element before p with mx's resources. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: Linear to the elements before p. + iterator insert(const_iterator p, BOOST_MOVE_MACRO_RV_REF(value_type) x) + { return this->insert_after(previous(p), BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Inserts n copies of x before p. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n plus linear to the elements before p. + void insert(const_iterator p, size_type n, const value_type& x) + { return this->insert_after(previous(p), n, x); } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Insert a copy of the [first, last) range before p. + //! + //! Throws: If memory allocation throws, T's constructor from a + //! dereferenced InpIt throws. + //! + //! Complexity: Linear to std::distance [first, last) plus + //! linear to the elements before p. + template + void insert(const_iterator p, InIter first, InIter last) + { return this->insert_after(previous(p), first, last); } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the front of the list + //! + //! Throws: If memory allocation throws or + //! T's copy constructor throws. + //! + //! Complexity: Amortized constant time. + template + void emplace_front(Args&&... args) + { this->emplace_after(this->cbefore_begin(), BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... before p + //! + //! Throws: If memory allocation throws or + //! T's in-place constructor throws. + //! + //! Complexity: Linear to the elements before p + template + iterator emplace(const_iterator p, Args&&... args) + { return this->emplace_after(this->previous(p), BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); } + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... after prev + //! + //! Throws: If memory allocation throws or + //! T's in-place constructor throws. + //! + //! Complexity: Constant + template + iterator emplace_after(const_iterator prev, Args&&... args) + { + typename AllocHolder::Deallocator d(AllocHolder::create_node_and_deallocator()); + new ((void*)containers_detail::get_pointer(d.get())) Node(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + NodePtr node = d.get(); + d.release(); + return iterator(this->icont().insert_after(prev.get(), *node)); + } + + #else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //0 args + void emplace_front() + { this->emplace_after(this->cbefore_begin()); } + + iterator emplace(const_iterator p) + { return this->emplace_after(this->previous(p)); } + + iterator emplace_after(const_iterator prev) + { + typename AllocHolder::Deallocator d(AllocHolder::create_node_and_deallocator()); + new ((void*)containers_detail::get_pointer(d.get())) Node(); + NodePtr node = d.get(); + d.release(); + return iterator(this->icont().insert_after(prev.get(), *node)); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + void emplace_front(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + this->emplace \ + (this->cbegin(), BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + } \ + \ + template \ + iterator emplace \ + (const_iterator p, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + return this->emplace_after \ + (this->previous(p), BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + } \ + \ + template \ + iterator emplace_after \ + (const_iterator prev, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + typename AllocHolder::Deallocator d(AllocHolder::create_node_and_deallocator()); \ + new ((void*)containers_detail::get_pointer(d.get())) \ + Node(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + NodePtr node = d.get(); \ + d.release(); \ + return iterator(this->icont().insert_after(prev.get(), *node)); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Erases the element after the element pointed by prev_pos + //! of the list. + //! + //! Returns: the first element remaining beyond the removed elements, + //! or end() if no such element exists. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + //! + //! Note: Does not invalidate iterators or references to non erased elements. + iterator erase_after(const_iterator prev_pos) + { + return iterator(this->icont().erase_after_and_dispose(prev_pos.get(), Destroyer(this->node_alloc()))); + } + + //! Effects: Erases the range (before_first, last) from + //! the list. + //! + //! Returns: the first element remaining beyond the removed elements, + //! or end() if no such element exists. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of erased elements. + //! + //! Note: Does not invalidate iterators or references to non erased elements. + iterator erase_after(const_iterator before_first, const_iterator last) + { + return iterator(this->icont().erase_after_and_dispose(before_first.get(), last.get(), Destroyer(this->node_alloc()))); + } + + //! Requires: p must be a valid iterator of *this. + //! + //! Effects: Erases the element at p p. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements before p. + iterator erase(const_iterator p) + { return iterator(this->erase_after(previous(p))); } + + //! Requires: first and last must be valid iterator to elements in *this. + //! + //! Effects: Erases the elements pointed by [first, last). + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the distance between first and last plus + //! linear to the elements before first. + iterator erase(const_iterator first, const_iterator last) + { return iterator(this->erase_after(previous(first), last)); } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are copy constructed from x. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type new_size, const T& x) + { + typename Icont::iterator end_n(this->icont().end()), cur(this->icont().before_begin()), cur_next; + while (++(cur_next = cur) != end_n && new_size > 0){ + --new_size; + cur = cur_next; + } + if (cur_next != end_n) + this->erase_after(const_iterator(cur), const_iterator(end_n)); + else + this->insert_after(const_iterator(cur), new_size, x); + } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are default constructed. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type new_size) + { + typename Icont::iterator end_n(this->icont().end()), cur(this->icont().before_begin()), cur_next; + size_type len = this->size(); + size_type left = new_size; + + while (++(cur_next = cur) != end_n && left > 0){ + --left; + cur = cur_next; + } + if (cur_next != end_n){ + this->erase_after(const_iterator(cur), const_iterator(end_n)); + } + else{ + this->priv_create_and_insert_nodes(const_iterator(cur), new_size - len); + } + } + + //! Effects: Erases all the elements of the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements in the list. + void clear() + { this->icont().clear_and_dispose(Destroyer(this->node_alloc())); } + + //! Requires: p must point to an element contained + //! by the list. x != *this + //! + //! Effects: Transfers all the elements of list x to this list, after the + //! the element pointed by p. No destructors or copy constructors are called. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Linear to the elements in x. + //! + //! Note: Iterators of values obtained from list x now point to elements of + //! this list. Iterators of this list and all the references are not invalidated. + void splice_after(const_iterator prev_pos, slist& x) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice_after(prev_pos.get(), x.icont()); + } + else{ + throw std::runtime_error("slist::splice called with unequal allocators"); + } + } + + //! Requires: prev_pos must be a valid iterator of this. + //! i must point to an element contained in list x. + //! + //! Effects: Transfers the value pointed by i, from list x to this list, + //! after the element pointed by prev_pos. + //! If prev_pos == prev or prev_pos == ++prev, this function is a null operation. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Constant. + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice_after(const_iterator prev_pos, slist& x, const_iterator prev) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice_after(prev_pos.get(), x.icont(), prev.get()); + } + else{ + throw std::runtime_error("slist::splice called with unequal allocators"); + } + } + + //! Requires: prev_pos must be a valid iterator of this. + //! before_first and before_last must be valid iterators of x. + //! prev_pos must not be contained in [before_first, before_last) range. + //! + //! Effects: Transfers the range [before_first + 1, before_last + 1) + //! from list x to this list, after the element pointed by prev_pos. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Linear to the number of transferred elements. + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice_after(const_iterator prev_pos, slist& x, + const_iterator before_first, const_iterator before_last) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice_after + (prev_pos.get(), x.icont(), before_first.get(), before_last.get()); + } + else{ + throw std::runtime_error("slist::splice called with unequal allocators"); + } + } + + //! Requires: prev_pos must be a valid iterator of this. + //! before_first and before_last must be valid iterators of x. + //! prev_pos must not be contained in [before_first, before_last) range. + //! n == std::distance(before_first, before_last) + //! + //! Effects: Transfers the range [before_first + 1, before_last + 1) + //! from list x to this list, after the element pointed by prev_pos. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Constant. + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice_after(const_iterator prev_pos, slist& x, + const_iterator before_first, const_iterator before_last, + size_type n) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().splice_after + (prev_pos.get(), x.icont(), before_first.get(), before_last.get(), n); + } + else{ + throw std::runtime_error("slist::splice called with unequal allocators"); + } + } + + //! Requires: p must point to an element contained + //! by the list. x != *this + //! + //! Effects: Transfers all the elements of list x to this list, before the + //! the element pointed by p. No destructors or copy constructors are called. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Linear in distance(begin(), p), and linear in x.size(). + //! + //! Note: Iterators of values obtained from list x now point to elements of + //! this list. Iterators of this list and all the references are not invalidated. + void splice(const_iterator p, ThisType& x) + { this->splice_after(this->previous(p), x); } + + //! Requires: p must point to an element contained + //! by this list. i must point to an element contained in list x. + //! + //! Effects: Transfers the value pointed by i, from list x to this list, + //! before the the element pointed by p. No destructors or copy constructors are called. + //! If p == i or p == ++i, this function is a null operation. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Linear in distance(begin(), p), and in distance(x.begin(), i). + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice(const_iterator p, slist& x, const_iterator i) + { this->splice_after(previous(p), x, i); } + + //! Requires: p must point to an element contained + //! by this list. first and last must point to elements contained in list x. + //! + //! Effects: Transfers the range pointed by first and last from list x to this list, + //! before the the element pointed by p. No destructors or copy constructors are called. + //! + //! Throws: std::runtime_error if this' allocator and x's allocator + //! are not equal. + //! + //! Complexity: Linear in distance(begin(), p), in distance(x.begin(), first), + //! and in distance(first, last). + //! + //! Note: Iterators of values obtained from list x now point to elements of this + //! list. Iterators of this list and all the references are not invalidated. + void splice(const_iterator p, slist& x, const_iterator first, const_iterator last) + { this->splice_after(previous(p), x, previous(first), previous(last)); } + + //! Effects: Reverses the order of elements in the list. + //! + //! Throws: Nothing. + //! + //! Complexity: This function is linear time. + //! + //! Note: Iterators and references are not invalidated + void reverse() + { this->icont().reverse(); } + + //! Effects: Removes all the elements that compare equal to value. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear time. It performs exactly size() comparisons for equality. + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + void remove(const T& value) + { remove_if(equal_to_value(value)); } + + //! Effects: Removes all the elements for which a specified + //! predicate is satisfied. + //! + //! Throws: If pred throws. + //! + //! Complexity: Linear time. It performs exactly size() calls to the predicate. + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + template + void remove_if(Pred pred) + { + typedef ValueCompareToNodeCompare Predicate; + this->icont().remove_and_dispose_if(Predicate(pred), Destroyer(this->node_alloc())); + } + + //! Effects: Removes adjacent duplicate elements or adjacent + //! elements that are equal from the list. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear time (size()-1 comparisons calls to pred()). + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + void unique() + { this->unique(value_equal()); } + + //! Effects: Removes adjacent duplicate elements or adjacent + //! elements that satisfy some binary predicate from the list. + //! + //! Throws: If pred throws. + //! + //! Complexity: Linear time (size()-1 comparisons equality comparisons). + //! + //! Note: The relative order of elements that are not removed is unchanged, + //! and iterators to elements that are not removed remain valid. + template + void unique(Pred pred) + { + typedef ValueCompareToNodeCompare Predicate; + this->icont().unique_and_dispose(Predicate(pred), Destroyer(this->node_alloc())); + } + + //! Requires: The lists x and *this must be distinct. + //! + //! Effects: This function removes all of x's elements and inserts them + //! in order into *this according to std::less. The merge is stable; + //! that is, if an element from *this is equivalent to one from x, then the element + //! from *this will precede the one from x. + //! + //! Throws: Nothing. + //! + //! Complexity: This function is linear time: it performs at most + //! size() + x.size() - 1 comparisons. + void merge(slist & x) + { this->merge(x, value_less()); } + + //! Requires: p must be a comparison function that induces a strict weak + //! ordering and both *this and x must be sorted according to that ordering + //! The lists x and *this must be distinct. + //! + //! Effects: This function removes all of x's elements and inserts them + //! in order into *this. The merge is stable; that is, if an element from *this is + //! equivalent to one from x, then the element from *this will precede the one from x. + //! + //! Throws: Nothing. + //! + //! Complexity: This function is linear time: it performs at most + //! size() + x.size() - 1 comparisons. + //! + //! Note: Iterators and references to *this are not invalidated. + template + void merge(slist& x, StrictWeakOrdering comp) + { + if((NodeAlloc&)*this == (NodeAlloc&)x){ + this->icont().merge(x.icont(), + ValueCompareToNodeCompare(comp)); + } + else{ + throw std::runtime_error("list::merge called with unequal allocators"); + } + } + + //! Effects: This function sorts the list *this according to std::less. + //! The sort is stable, that is, the relative order of equivalent elements is preserved. + //! + //! Throws: Nothing. + //! + //! Notes: Iterators and references are not invalidated. + //! + //! Complexity: The number of comparisons is approximately N log N, where N + //! is the list's size. + void sort() + { this->sort(value_less()); } + + //! Effects: This function sorts the list *this according to std::less. + //! The sort is stable, that is, the relative order of equivalent elements is preserved. + //! + //! Throws: Nothing. + //! + //! Notes: Iterators and references are not invalidated. + //! + //! Complexity: The number of comparisons is approximately N log N, where N + //! is the list's size. + template + void sort(StrictWeakOrdering comp) + { + // nothing if the slist has length 0 or 1. + if (this->size() < 2) + return; + this->icont().sort(ValueCompareToNodeCompare(comp)); + } + + /// @cond + private: + iterator priv_insert(const_iterator p, const value_type& x) + { return this->insert_after(previous(p), x); } + + iterator priv_insert_after(const_iterator prev_pos, const value_type& x) + { return iterator(this->icont().insert_after(prev_pos.get(), *this->create_node(x))); } + + void priv_push_front(const value_type &x) + { this->icont().push_front(*this->create_node(x)); } + + //Iterator range version + template + void priv_create_and_insert_nodes + (const_iterator prev, InpIterator beg, InpIterator end) + { + typedef typename std::iterator_traits::iterator_category ItCat; + priv_create_and_insert_nodes(prev, beg, end, alloc_version(), ItCat()); + } + + template + void priv_create_and_insert_nodes + (const_iterator prev, InpIterator beg, InpIterator end, allocator_v1, std::input_iterator_tag) + { + for (; beg != end; ++beg){ + this->icont().insert_after(prev.get(), *this->create_node_from_it(beg)); + ++prev; + } + } + + template + void priv_create_and_insert_nodes + (const_iterator prev, InpIterator beg, InpIterator end, allocator_v2, std::input_iterator_tag) + { //Just forward to the default one + priv_create_and_insert_nodes(prev, beg, end, allocator_v1(), std::input_iterator_tag()); + } + + class insertion_functor; + friend class insertion_functor; + + class insertion_functor + { + Icont &icont_; + typename Icont::const_iterator prev_; + + public: + insertion_functor(Icont &icont, typename Icont::const_iterator prev) + : icont_(icont), prev_(prev) + {} + + void operator()(Node &n) + { prev_ = this->icont_.insert_after(prev_, n); } + }; + + template + void priv_create_and_insert_nodes + (const_iterator prev, FwdIterator beg, FwdIterator end, allocator_v2, std::forward_iterator_tag) + { + //Optimized allocation and construction + this->allocate_many_and_construct + (beg, std::distance(beg, end), insertion_functor(this->icont(), prev.get())); + } + + //Default constructed version + void priv_create_and_insert_nodes(const_iterator prev, size_type n) + { + typedef default_construct_iterator default_iterator; + this->priv_create_and_insert_nodes(prev, default_iterator(n), default_iterator()); + } + + //Copy constructed version + void priv_create_and_insert_nodes(const_iterator prev, size_type n, const T& x) + { + typedef constant_iterator cvalue_iterator; + this->priv_create_and_insert_nodes(prev, cvalue_iterator(x, n), cvalue_iterator()); + } + + //Dispatch to detect iterator range or integer overloads + template + void priv_insert_dispatch(const_iterator prev, + InputIter first, InputIter last, + containers_detail::false_) + { this->priv_create_and_insert_nodes(prev, first, last); } + + template + void priv_insert_dispatch(const_iterator prev, Integer n, Integer x, containers_detail::true_) + { this->priv_create_and_insert_nodes(prev, (std::size_t)n, x); } + + void priv_fill_assign(size_type n, const T& val) + { + iterator end_n(this->end()); + iterator prev(this->before_begin()); + iterator node(this->begin()); + for ( ; node != end_n && n > 0 ; --n){ + *node = val; + prev = node; + ++node; + } + if (n > 0) + this->priv_create_and_insert_nodes(prev, n, val); + else + this->erase_after(prev, end_n); + } + + template + void priv_assign_dispatch(Int n, Int val, containers_detail::true_) + { this->priv_fill_assign((size_type) n, (T)val); } + + template + void priv_assign_dispatch(InpIt first, InpIt last, containers_detail::false_) + { + iterator end_n(this->end()); + iterator prev(this->before_begin()); + iterator node(this->begin()); + while (node != end_n && first != last){ + *node = *first; + prev = node; + ++node; + ++first; + } + if (first != last) + this->priv_create_and_insert_nodes(prev, first, last); + else + this->erase_after(prev, end_n); + } + + template + void priv_insert_after_range_dispatch(const_iterator prev_pos, Int n, Int x, containers_detail::true_) + { this->priv_create_and_insert_nodes(prev_pos, (std::size_t)n, x); } + + template + void priv_insert_after_range_dispatch(const_iterator prev_pos, InIter first, InIter last, containers_detail::false_) + { this->priv_create_and_insert_nodes(prev_pos, first, last); } + + //Functors for member algorithm defaults + struct value_less + { + bool operator()(const value_type &a, const value_type &b) const + { return a < b; } + }; + + struct value_equal + { + bool operator()(const value_type &a, const value_type &b) const + { return a == b; } + }; + + struct value_equal_to_this + { + explicit value_equal_to_this(const value_type &ref) + : m_ref(ref){} + + bool operator()(const value_type &val) const + { return m_ref == val; } + + const value_type &m_ref; + }; + /// @endcond +}; + +template +inline bool +operator==(const slist& x, const slist& y) +{ + if(x.size() != y.size()){ + return false; + } + typedef typename slist::const_iterator const_iterator; + const_iterator end1 = x.end(); + + const_iterator i1 = x.begin(); + const_iterator i2 = y.begin(); + while (i1 != end1 && *i1 == *i2){ + ++i1; + ++i2; + } + return i1 == end1; +} + +template +inline bool +operator<(const slist& sL1, const slist& sL2) +{ + return std::lexicographical_compare + (sL1.begin(), sL1.end(), sL2.begin(), sL2.end()); +} + +template +inline bool +operator!=(const slist& sL1, const slist& sL2) + { return !(sL1 == sL2); } + +template +inline bool +operator>(const slist& sL1, const slist& sL2) + { return sL2 < sL1; } + +template +inline bool +operator<=(const slist& sL1, const slist& sL2) + { return !(sL2 < sL1); } + +template +inline bool +operator>=(const slist& sL1, const slist& sL2) + { return !(sL1 < sL2); } + +template +inline void swap(slist& x, slist& y) + { x.swap(y); } + +}} + +/// @cond + +namespace boost { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value; +}; +*/ +namespace container { + +/// @endcond + +}} //namespace boost{ namespace container { + +// Specialization of insert_iterator so that insertions will be constant +// time rather than linear time. + +///@cond + +//Ummm, I don't like to define things in namespace std, but +//there is no other way +namespace std { + +template +class insert_iterator > +{ + protected: + typedef boost::container::slist Container; + Container* container; + typename Container::iterator iter; + public: + typedef Container container_type; + typedef output_iterator_tag iterator_category; + typedef void value_type; + typedef void difference_type; + typedef void pointer; + typedef void reference; + + insert_iterator(Container& x, + typename Container::iterator i, + bool is_previous = false) + : container(&x), iter(is_previous ? i : x.previous(i)){ } + + insert_iterator& + operator=(const typename Container::value_type& value) + { + iter = container->insert_after(iter, value); + return *this; + } + insert_iterator& operator*(){ return *this; } + insert_iterator& operator++(){ return *this; } + insert_iterator& operator++(int){ return *this; } +}; + +} //namespace std; + +///@endcond + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif /* BOOST_CONTAINERS_SLIST_HPP */ diff --git a/utils/boost_idb/boost/interprocess/containers/container/stable_vector.hpp b/utils/boost_idb/boost/interprocess/containers/container/stable_vector.hpp new file mode 100644 index 00000000..dd8ae473 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/stable_vector.hpp @@ -0,0 +1,1329 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +/* Stable vector. + * + * Copyright 2008 Joaquin M Lopez Munoz. + * Distributed under the Boost Software License, Version 1.0. + * (See accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt) + */ + +#ifndef BOOST_CONTAINER_STABLE_VECTOR_HPP +#define BOOST_CONTAINER_STABLE_VECTOR_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#include +#include + +#include +#include +#include + +///@cond + +#define STABLE_VECTOR_USE_CONTAINERS_VECTOR + +#if defined (STABLE_VECTOR_USE_CONTAINERS_VECTOR) +#include INCLUDE_BOOST_CONTAINER_VECTOR_HPP +#else +#include +#endif //STABLE_VECTOR_USE_CONTAINERS_VECTOR + +//#define STABLE_VECTOR_ENABLE_INVARIANT_CHECKING + +#if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) +#include +#endif + +///@endcond + +namespace boost { +namespace container { + +///@cond + +namespace stable_vector_detail{ + +template +struct smart_ptr_type +{ + typedef typename SmartPtr::value_type value_type; + typedef value_type *pointer; + static pointer get (const SmartPtr &smartptr) + { return smartptr.get();} +}; + +template +struct smart_ptr_type +{ + typedef T value_type; + typedef value_type *pointer; + static pointer get (pointer ptr) + { return ptr;} +}; + +template +inline typename smart_ptr_type::pointer get_pointer(const Ptr &ptr) +{ return smart_ptr_type::get(ptr); } + +template +class clear_on_destroy +{ + public: + clear_on_destroy(C &c) + : c_(c), do_clear_(true) + {} + + void release() + { do_clear_ = false; } + + ~clear_on_destroy() + { + if(do_clear_){ + c_.clear(); + c_.clear_pool(); + } + } + + private: + clear_on_destroy(const clear_on_destroy &); + clear_on_destroy &operator=(const clear_on_destroy &); + C &c_; + bool do_clear_; +}; + +template +struct node_type_base +{/* + node_type_base(VoidPtr p) + : up(p) + {}*/ + node_type_base() + {} + void set_pointer(VoidPtr p) + { up = p; } + + VoidPtr up; +}; + +template +struct node_type + : public node_type_base +{ + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + node_type() + : value() + {} + + template + node_type(Args &&...args) + : value(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...) + {} + + #else //BOOST_CONTAINERS_PERFECT_FORWARDING + + node_type() + : value() + {} + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + node_type(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + : value(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)) \ + {} \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif//BOOST_CONTAINERS_PERFECT_FORWARDING + + void set_pointer(VoidPointer p) + { node_type_base::set_pointer(p); } + + T value; +}; + +template +class iterator + : public std::iterator< std::random_access_iterator_tag + , typename std::iterator_traits::value_type + , typename std::iterator_traits::difference_type + , Pointer + , Reference> +{ + + typedef typename boost::pointer_to_other + ::type void_ptr; + typedef node_type node_type_t; + typedef typename boost::pointer_to_other + ::type node_type_ptr_t; + typedef typename boost::pointer_to_other + ::type void_ptr_ptr; + + friend class iterator::type>; + + public: + typedef std::random_access_iterator_tag iterator_category; + typedef T value_type; + typedef typename std::iterator_traits + ::difference_type difference_type; + typedef Pointer pointer; + typedef Reference reference; + + iterator() + {} + + explicit iterator(node_type_ptr_t pn) + : pn(pn) + {} + + iterator(const iterator::type >& x) + : pn(x.pn) + {} + + private: + static node_type_ptr_t node_ptr_cast(void_ptr p) + { + using boost::get_pointer; + return node_type_ptr_t(static_cast(stable_vector_detail::get_pointer(p))); + } + + static void_ptr_ptr void_ptr_ptr_cast(void_ptr p) + { + using boost::get_pointer; + return void_ptr_ptr(static_cast(stable_vector_detail::get_pointer(p))); + } + + reference dereference() const + { return pn->value; } + bool equal(const iterator& x) const + { return pn==x.pn; } + void increment() + { pn = node_ptr_cast(*(void_ptr_ptr_cast(pn->up)+1)); } + void decrement() + { pn = node_ptr_cast(*(void_ptr_ptr_cast(pn->up)-1)); } + void advance(std::ptrdiff_t n) + { pn = node_ptr_cast(*(void_ptr_ptr_cast(pn->up)+n)); } + std::ptrdiff_t distance_to(const iterator& x)const + { return void_ptr_ptr_cast(x.pn->up) - void_ptr_ptr_cast(pn->up); } + + public: + //Pointer like operators + reference operator*() const { return this->dereference(); } + pointer operator->() const { return pointer(&this->dereference()); } + + //Increment / Decrement + iterator& operator++() + { this->increment(); return *this; } + + iterator operator++(int) + { iterator tmp(*this); ++*this; return iterator(tmp); } + + iterator& operator--() + { this->decrement(); return *this; } + + iterator operator--(int) + { iterator tmp(*this); --*this; return iterator(tmp); } + + reference operator[](difference_type off) const + { + iterator tmp(*this); + tmp += off; + return *tmp; + } + + iterator& operator+=(difference_type off) + { + pn = node_ptr_cast(*(void_ptr_ptr_cast(pn->up)+off)); + return *this; + } + + iterator operator+(difference_type off) const + { + iterator tmp(*this); + tmp += off; + return tmp; + } + + friend iterator operator+(difference_type off, const iterator& right) + { + iterator tmp(right); + tmp += off; + return tmp; + } + + iterator& operator-=(difference_type off) + { *this += -off; return *this; } + + iterator operator-(difference_type off) const + { + iterator tmp(*this); + tmp -= off; + return tmp; + } + + difference_type operator-(const iterator& right) const + { + void_ptr_ptr p1 = void_ptr_ptr_cast(this->pn->up); + void_ptr_ptr p2 = void_ptr_ptr_cast(right.pn->up); + return p1 - p2; + } + + //Comparison operators + bool operator== (const iterator& r) const + { return pn == r.pn; } + + bool operator!= (const iterator& r) const + { return pn != r.pn; } + + bool operator< (const iterator& r) const + { return void_ptr_ptr_cast(pn->up) < void_ptr_ptr_cast(r.pn->up); } + + bool operator<= (const iterator& r) const + { return void_ptr_ptr_cast(pn->up) <= void_ptr_ptr_cast(r.pn->up); } + + bool operator> (const iterator& r) const + { return void_ptr_ptr_cast(pn->up) > void_ptr_ptr_cast(r.pn->up); } + + bool operator>= (const iterator& r) const + { return void_ptr_ptr_cast(pn->up) >= void_ptr_ptr_cast(r.pn->up); } + + node_type_ptr_t pn; +}; + +template +struct select_multiallocation_chain +{ + typedef typename Allocator::multiallocation_chain type; +}; + +template +struct select_multiallocation_chain +{ + typedef typename Allocator::template + rebind::other::pointer void_ptr; + typedef containers_detail::basic_multiallocation_chain + multialloc_cached_counted; + typedef boost::container::containers_detail::transform_multiallocation_chain + type; +}; + +} //namespace stable_vector_detail + +#if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) + +#define STABLE_VECTOR_CHECK_INVARIANT \ +invariant_checker BOOST_JOIN(check_invariant_,__LINE__)(*this); \ +BOOST_JOIN(check_invariant_,__LINE__).touch(); +#else + +#define STABLE_VECTOR_CHECK_INVARIANT + +#endif //#if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) + +/// @endcond + +//!Help taken from ( Introducing stable_vector) +//! +//!We present stable_vector, a fully STL-compliant stable container that provides +//!most of the features of std::vector except element contiguity. +//! +//!General properties: stable_vector satisfies all the requirements of a container, +//!a reversible container and a sequence and provides all the optional operations +//!present in std::vector. Like std::vector, iterators are random access. +//!stable_vector does not provide element contiguity; in exchange for this absence, +//!the container is stable, i.e. references and iterators to an element of a stable_vector +//!remain valid as long as the element is not erased, and an iterator that has been +//!assigned the return value of end() always remain valid until the destruction of +//!the associated stable_vector. +//! +//!Operation complexity: The big-O complexities of stable_vector operations match +//!exactly those of std::vector. In general, insertion/deletion is constant time at +//!the end of the sequence and linear elsewhere. Unlike std::vector, stable_vector +//!does not internally perform any value_type destruction, copy or assignment +//!operations other than those exactly corresponding to the insertion of new +//!elements or deletion of stored elements, which can sometimes compensate in terms +//!of performance for the extra burden of doing more pointer manipulation and an +//!additional allocation per element. +//! +//!Exception safety: As stable_vector does not internally copy elements around, some +//!operations provide stronger exception safety guarantees than in std::vector: +template +class stable_vector +{ + ///@cond + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + typedef typename Allocator::template + rebind::other::pointer void_ptr; + typedef typename Allocator::template + rebind::other::pointer void_ptr_ptr; + typedef stable_vector_detail::node_type + node_type_t; + typedef typename Allocator::template + rebind::other::pointer node_type_ptr_t; + typedef stable_vector_detail::node_type_base + node_type_base_t; + typedef typename Allocator::template + rebind::other::pointer node_type_base_ptr_t; + typedef + #if defined (STABLE_VECTOR_USE_CONTAINERS_VECTOR) + ::boost::container:: + #else + ::std:: + #endif //STABLE_VECTOR_USE_CONTAINERS_VECTOR + vector::other + > impl_type; + typedef typename impl_type::iterator impl_iterator; + typedef typename impl_type::const_iterator const_impl_iterator; + + typedef ::boost::container::containers_detail:: + integral_constant allocator_v1; + typedef ::boost::container::containers_detail:: + integral_constant allocator_v2; + typedef ::boost::container::containers_detail::integral_constant + ::value> alloc_version; + typedef typename Allocator:: + template rebind::other node_allocator_type; + + node_type_ptr_t allocate_one() + { return this->allocate_one(alloc_version()); } + + node_type_ptr_t allocate_one(allocator_v1) + { return get_al().allocate(1); } + + node_type_ptr_t allocate_one(allocator_v2) + { return get_al().allocate_one(); } + + void deallocate_one(node_type_ptr_t p) + { return this->deallocate_one(p, alloc_version()); } + + void deallocate_one(node_type_ptr_t p, allocator_v1) + { get_al().deallocate(p, 1); } + + void deallocate_one(node_type_ptr_t p, allocator_v2) + { get_al().deallocate_one(p); } + + friend class stable_vector_detail::clear_on_destroy; + ///@endcond + public: + + + // types: + + typedef typename Allocator::reference reference; + typedef typename Allocator::const_reference const_reference; + typedef typename Allocator::pointer pointer; + typedef typename Allocator::const_pointer const_pointer; + typedef stable_vector_detail::iterator + iterator; + typedef stable_vector_detail::iterator + const_iterator; + typedef typename impl_type::size_type size_type; + typedef typename iterator::difference_type difference_type; + typedef T value_type; + typedef Allocator allocator_type; + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; + + ///@cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(stable_vector) + static const size_type ExtraPointers = 3; + typedef typename stable_vector_detail:: + select_multiallocation_chain + < node_allocator_type + , alloc_version::value + >::type multiallocation_chain; + ///@endcond + public: + + // construct/copy/destroy: + explicit stable_vector(const Allocator& al=Allocator()) + : internal_data(al),impl(al) + { + STABLE_VECTOR_CHECK_INVARIANT; + } + + explicit stable_vector(size_type n) + : internal_data(Allocator()),impl(Allocator()) + { + stable_vector_detail::clear_on_destroy cod(*this); + this->resize(n); + STABLE_VECTOR_CHECK_INVARIANT; + cod.release(); + } + + stable_vector(size_type n, const T& t, const Allocator& al=Allocator()) + : internal_data(al),impl(al) + { + stable_vector_detail::clear_on_destroy cod(*this); + this->insert(this->cbegin(), n, t); + STABLE_VECTOR_CHECK_INVARIANT; + cod.release(); + } + + template + stable_vector(InputIterator first,InputIterator last,const Allocator& al=Allocator()) + : internal_data(al),impl(al) + { + stable_vector_detail::clear_on_destroy cod(*this); + this->insert(this->cbegin(), first, last); + STABLE_VECTOR_CHECK_INVARIANT; + cod.release(); + } + + stable_vector(const stable_vector& x) + : internal_data(x.get_al()),impl(x.get_al()) + { + stable_vector_detail::clear_on_destroy cod(*this); + this->insert(this->cbegin(), x.begin(), x.end()); + STABLE_VECTOR_CHECK_INVARIANT; + cod.release(); + } + + stable_vector(BOOST_MOVE_MACRO_RV_REF(stable_vector) x) + : internal_data(x.get_al()),impl(x.get_al()) + { this->swap(x); } + + ~stable_vector() + { + this->clear(); + clear_pool(); + } + + stable_vector& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(stable_vector) x) + { + STABLE_VECTOR_CHECK_INVARIANT; + if (this != &x) { + this->assign(x.begin(), x.end()); + } + return *this; + } + + stable_vector& operator=(BOOST_MOVE_MACRO_RV_REF(stable_vector) x) + { + if (&x != this){ + this->swap(x); + x.clear(); + } + return *this; + } + + template + void assign(InputIterator first,InputIterator last) + { + assign_dispatch(first, last, boost::is_integral()); + } + + void assign(size_type n,const T& t) + { + typedef constant_iterator cvalue_iterator; + return assign_dispatch(cvalue_iterator(t, n), cvalue_iterator(), boost::mpl::false_()); + } + + allocator_type get_allocator()const {return get_al();} + + // iterators: + + iterator begin() + { return (impl.empty()) ? end(): iterator(node_ptr_cast(impl.front())) ; } + + const_iterator begin()const + { return (impl.empty()) ? cend() : const_iterator(node_ptr_cast(impl.front())) ; } + + iterator end() {return iterator(get_end_node());} + const_iterator end()const {return const_iterator(get_end_node());} + + reverse_iterator rbegin() {return reverse_iterator(this->end());} + const_reverse_iterator rbegin()const {return const_reverse_iterator(this->end());} + reverse_iterator rend() {return reverse_iterator(this->begin());} + const_reverse_iterator rend()const {return const_reverse_iterator(this->begin());} + + const_iterator cbegin()const {return this->begin();} + const_iterator cend()const {return this->end();} + const_reverse_iterator crbegin()const{return this->rbegin();} + const_reverse_iterator crend()const {return this->rend();} + + // capacity: + size_type size() const + { return impl.empty() ? 0 : (impl.size() - ExtraPointers); } + + size_type max_size() const + { return impl.max_size() - ExtraPointers; } + + size_type capacity() const + { + if(!impl.capacity()){ + return 0; + } + else{ + const size_type num_nodes = this->impl.size() + this->internal_data.pool_size; + const size_type num_buck = this->impl.capacity(); + return (num_nodes < num_buck) ? num_nodes : num_buck; + } + } + + bool empty() const + { return impl.empty() || impl.size() == ExtraPointers; } + + void resize(size_type n, const T& t) + { + STABLE_VECTOR_CHECK_INVARIANT; + if(n > size()) + this->insert(this->cend(), n - this->size(), t); + else if(n < this->size()) + this->erase(this->cbegin() + n, this->cend()); + } + + void resize(size_type n) + { + typedef default_construct_iterator default_iterator; + STABLE_VECTOR_CHECK_INVARIANT; + if(n > size()) + this->insert(this->cend(), default_iterator(n - this->size()), default_iterator()); + else if(n < this->size()) + this->erase(this->cbegin() + n, this->cend()); + } + + void reserve(size_type n) + { + STABLE_VECTOR_CHECK_INVARIANT; + if(n > this->max_size()) + throw std::bad_alloc(); + + size_type size = this->size(); + size_type old_capacity = this->capacity(); + if(n > old_capacity){ + this->initialize_end_node(n); + const void * old_ptr = &impl[0]; + impl.reserve(n + ExtraPointers); + bool realloced = &impl[0] != old_ptr; + //Fix the pointers for the newly allocated buffer + if(realloced){ + this->align_nodes(impl.begin(), impl.begin()+size+1); + } + //Now fill pool if data is not enough + if((n - size) > this->internal_data.pool_size){ + this->add_to_pool((n - size) - this->internal_data.pool_size); + } + } + } + + // element access: + + reference operator[](size_type n){return value(impl[n]);} + const_reference operator[](size_type n)const{return value(impl[n]);} + + const_reference at(size_type n)const + { + if(n>=size()) + throw std::out_of_range("invalid subscript at stable_vector::at"); + return operator[](n); + } + + reference at(size_type n) + { + if(n>=size()) + throw std::out_of_range("invalid subscript at stable_vector::at"); + return operator[](n); + } + + reference front() + { return value(impl.front()); } + + const_reference front()const + { return value(impl.front()); } + + reference back() + { return value(*(&impl.back() - ExtraPointers)); } + + const_reference back()const + { return value(*(&impl.back() - ExtraPointers)); } + + // modifiers: + + void push_back(insert_const_ref_type x) + { return priv_push_back(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_back(T &x) { push_back(const_cast(x)); } + + template + void push_back(const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return priv_push_back(u); } + #endif + + void push_back(BOOST_MOVE_MACRO_RV_REF(T) t) + { this->insert(end(), BOOST_CONTAINER_MOVE_NAMESPACE::move(t)); } + + void pop_back() + { this->erase(this->end()-1); } + + iterator insert(const_iterator position, insert_const_ref_type x) + { return this->priv_insert(position, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return this->priv_insert(position, u); } + #endif + + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(T) x) + { + typedef repeat_iterator repeat_it; + typedef BOOST_CONTAINER_MOVE_NAMESPACE::move_iterator repeat_move_it; + //Just call more general insert(pos, size, value) and return iterator + size_type pos_n = position - cbegin(); + this->insert(position + ,repeat_move_it(repeat_it(x, 1)) + ,repeat_move_it(repeat_it())); + return iterator(this->begin() + pos_n); + } + + void insert(const_iterator position, size_type n, const T& t) + { + STABLE_VECTOR_CHECK_INVARIANT; + this->insert_not_iter(position, n, t); + } + + template + void insert(const_iterator position,InputIterator first, InputIterator last) + { + STABLE_VECTOR_CHECK_INVARIANT; + this->insert_iter(position,first,last, + boost::mpl::not_ >()); + } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the end of the vector. + //! + //! Throws: If memory allocation throws or the in-place constructor throws. + //! + //! Complexity: Amortized constant time. + template + void emplace_back(Args &&...args) + { + typedef emplace_functor EmplaceFunctor; + typedef emplace_iterator EmplaceIterator; + EmplaceFunctor &&ef = EmplaceFunctor(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->insert(this->cend(), EmplaceIterator(ef), EmplaceIterator()); + } + + //! Requires: position must be a valid iterator of *this. + //! + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... before position + //! + //! Throws: If memory allocation throws or the in-place constructor throws. + //! + //! Complexity: If position is end(), amortized constant time + //! Linear time otherwise. + template + iterator emplace(const_iterator position, Args && ...args) + { + //Just call more general insert(pos, size, value) and return iterator + size_type pos_n = position - cbegin(); + typedef emplace_functor EmplaceFunctor; + typedef emplace_iterator EmplaceIterator; + EmplaceFunctor &&ef = EmplaceFunctor(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + this->insert(position, EmplaceIterator(ef), EmplaceIterator()); + return iterator(this->begin() + pos_n); + } + + #else + + void emplace_back() + { + typedef emplace_functor EmplaceFunctor; + typedef emplace_iterator EmplaceIterator; + EmplaceFunctor ef; + this->insert(this->cend(), EmplaceIterator(ef), EmplaceIterator()); + } + + iterator emplace(const_iterator position) + { + typedef emplace_functor EmplaceFunctor; + typedef emplace_iterator EmplaceIterator; + EmplaceFunctor ef; + size_type pos_n = position - this->cbegin(); + this->insert(position, EmplaceIterator(ef), EmplaceIterator()); + return iterator(this->begin() + pos_n); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + typedef BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ + EmplaceFunctor; \ + typedef emplace_iterator EmplaceIterator; \ + EmplaceFunctor ef(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + this->insert(this->cend(), EmplaceIterator(ef), EmplaceIterator()); \ + } \ + \ + template \ + iterator emplace(const_iterator pos, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + typedef BOOST_PP_CAT(BOOST_PP_CAT(emplace_functor, n), arg) \ + EmplaceFunctor; \ + typedef emplace_iterator EmplaceIterator; \ + EmplaceFunctor ef(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + size_type pos_n = pos - this->cbegin(); \ + this->insert(pos, EmplaceIterator(ef), EmplaceIterator()); \ + return iterator(this->begin() + pos_n); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + iterator erase(const_iterator position) + { + STABLE_VECTOR_CHECK_INVARIANT; + difference_type d=position-this->cbegin(); + impl_iterator it=impl.begin()+d; + this->delete_node(*it); + impl.erase(it); + this->align_nodes(impl.begin()+d,get_last_align()); + return this->begin()+d; + } + + iterator erase(const_iterator first, const_iterator last) + { return priv_erase(first, last, alloc_version()); } + + void swap(stable_vector & x) + { + STABLE_VECTOR_CHECK_INVARIANT; + this->swap_impl(*this,x); + } + + void clear() + { this->erase(this->cbegin(),this->cend()); } + + /// @cond + private: + + iterator priv_insert(const_iterator position, const value_type &t) + { + typedef constant_iterator cvalue_iterator; + return this->insert_iter(position, cvalue_iterator(t, 1), cvalue_iterator(), std::forward_iterator_tag()); + } + + void priv_push_back(const value_type &t) + { this->insert(end(), t); } + + void clear_pool(allocator_v1) + { + if(!impl.empty() && impl.back()){ + void_ptr &p1 = *(impl.end()-2); + void_ptr &p2 = impl.back(); + + multiallocation_chain holder; + holder.incorporate_after(holder.before_begin(), p1, p2, this->internal_data.pool_size); + while(!holder.empty()){ + node_type_ptr_t n = holder.front(); + holder.pop_front(); + this->deallocate_one(n); + } + p1 = p2 = 0; + this->internal_data.pool_size = 0; + } + } + + void clear_pool(allocator_v2) + { + + if(!impl.empty() && impl.back()){ + void_ptr &p1 = *(impl.end()-2); + void_ptr &p2 = impl.back(); + multiallocation_chain holder; + holder.incorporate_after(holder.before_begin(), p1, p2, internal_data.pool_size); + get_al().deallocate_individual(BOOST_CONTAINER_MOVE_NAMESPACE::move(holder)); + p1 = p2 = 0; + this->internal_data.pool_size = 0; + } + } + + void clear_pool() + { + this->clear_pool(alloc_version()); + } + + void add_to_pool(size_type n) + { + this->add_to_pool(n, alloc_version()); + } + + void add_to_pool(size_type n, allocator_v1) + { + size_type remaining = n; + while(remaining--){ + this->put_in_pool(this->allocate_one()); + } + } + + void add_to_pool(size_type n, allocator_v2) + { + void_ptr &p1 = *(impl.end()-2); + void_ptr &p2 = impl.back(); + multiallocation_chain holder; + holder.incorporate_after(holder.before_begin(), p1, p2, internal_data.pool_size); + BOOST_STATIC_ASSERT((::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value == true)); + multiallocation_chain m (get_al().allocate_individual(n)); + holder.splice_after(holder.before_begin(), m, m.before_begin(), m.last(), n); + this->internal_data.pool_size += n; + std::pair data(holder.extract_data()); + p1 = data.first; + p2 = data.second; + } + + void put_in_pool(node_type_ptr_t p) + { + void_ptr &p1 = *(impl.end()-2); + void_ptr &p2 = impl.back(); + multiallocation_chain holder; + holder.incorporate_after(holder.before_begin(), p1, p2, internal_data.pool_size); + holder.push_front(p); + ++this->internal_data.pool_size; + std::pair ret(holder.extract_data()); + p1 = ret.first; + p2 = ret.second; + } + + node_type_ptr_t get_from_pool() + { + if(!impl.back()){ + return node_type_ptr_t(0); + } + else{ + void_ptr &p1 = *(impl.end()-2); + void_ptr &p2 = impl.back(); + multiallocation_chain holder; + holder.incorporate_after(holder.before_begin(), p1, p2, internal_data.pool_size); + node_type_ptr_t ret = holder.front(); + holder.pop_front(); + --this->internal_data.pool_size; + if(!internal_data.pool_size){ + p1 = p2 = 0; + } + else{ + std::pair data(holder.extract_data()); + p1 = data.first; + p2 = data.second; + } + return ret; + } + } + + void insert_iter_prolog(size_type n, difference_type d) + { + initialize_end_node(n); + const void* old_ptr = &impl[0]; + //size_type old_capacity = capacity(); + //size_type old_size = size(); + impl.insert(impl.begin()+d, n, 0); + bool realloced = &impl[0] != old_ptr; + //Fix the pointers for the newly allocated buffer + if(realloced){ + align_nodes(impl.begin(), impl.begin()+d); + } + } + + template + void assign_dispatch(InputIterator first, InputIterator last, boost::mpl::false_) + { + STABLE_VECTOR_CHECK_INVARIANT; + iterator first1 = this->begin(); + iterator last1 = this->end(); + for ( ; first1 != last1 && first != last; ++first1, ++first) + *first1 = *first; + if (first == last){ + this->erase(first1, last1); + } + else{ + this->insert(last1, first, last); + } + } + + template + void assign_dispatch(Integer n, Integer t, boost::mpl::true_) + { + typedef constant_iterator cvalue_iterator; + this->assign_dispatch(cvalue_iterator(t, n), cvalue_iterator(), boost::mpl::false_()); + } + + iterator priv_erase(const_iterator first, const_iterator last, allocator_v1) + { + STABLE_VECTOR_CHECK_INVARIANT; + difference_type d1 = first - this->cbegin(), d2 = last - this->cbegin(); + if(d1 != d2){ + impl_iterator it1(impl.begin() + d1), it2(impl.begin() + d2); + for(impl_iterator it = it1; it != it2; ++it) + this->delete_node(*it); + impl.erase(it1, it2); + this->align_nodes(impl.begin() + d1, get_last_align()); + } + return iterator(this->begin() + d1); + } + + impl_iterator get_last_align() + { + return impl.end() - (ExtraPointers - 1); + } + + const_impl_iterator get_last_align() const + { + return impl.cend() - (ExtraPointers - 1); + } + + template + iterator priv_erase(const_iterator first, const_iterator last, AllocatorVersion, + typename boost::container::containers_detail::enable_if_c + + ::value>::type * = 0) + { + STABLE_VECTOR_CHECK_INVARIANT; + return priv_erase(first, last, allocator_v1()); + } + + static node_type_ptr_t node_ptr_cast(void_ptr p) + { + using boost::get_pointer; + return node_type_ptr_t(static_cast(stable_vector_detail::get_pointer(p))); + } + + static node_type_base_ptr_t node_base_ptr_cast(void_ptr p) + { + using boost::get_pointer; + return node_type_base_ptr_t(static_cast(stable_vector_detail::get_pointer(p))); + } + + static value_type& value(void_ptr p) + { + return node_ptr_cast(p)->value; + } + + void initialize_end_node(size_type impl_capacity = 0) + { + if(impl.empty()){ + impl.reserve(impl_capacity + ExtraPointers); + impl.resize (ExtraPointers, void_ptr(0)); + impl[0] = &this->internal_data.end_node; + this->internal_data.end_node.up = &impl[0]; + } + } + + void readjust_end_node() + { + if(!this->impl.empty()){ + void_ptr &end_node_ref = *(this->get_last_align()-1); + end_node_ref = this->get_end_node(); + this->internal_data.end_node.up = &end_node_ref; + } + else{ + this->internal_data.end_node.up = void_ptr(&this->internal_data.end_node.up); + } + } + + node_type_ptr_t get_end_node() const + { + const node_type_base_t* cp = &this->internal_data.end_node; + node_type_base_t* p = const_cast(cp); + return node_ptr_cast(p); + } + + template + void_ptr new_node(void_ptr up, Iter it) + { + node_type_ptr_t p = this->allocate_one(); + try{ + boost::container::construct_in_place(&*p, it); + p->set_pointer(up); + } + catch(...){ + this->deallocate_one(p); + throw; + } + return p; + } + + void delete_node(void_ptr p) + { + node_type_ptr_t n(node_ptr_cast(p)); + n->~node_type_t(); + this->put_in_pool(n); + } + + static void align_nodes(impl_iterator first,impl_iterator last) + { + while(first!=last){ + node_ptr_cast(*first)->up = void_ptr(&*first); + ++first; + } + } + + void insert_not_iter(const_iterator position, size_type n, const T& t) + { + typedef constant_iterator cvalue_iterator; + this->insert_iter(position, cvalue_iterator(t, n), cvalue_iterator(), std::forward_iterator_tag()); + } + + template + void insert_iter(const_iterator position,InputIterator first,InputIterator last, boost::mpl::true_) + { + typedef typename std::iterator_traits::iterator_category category; + this->insert_iter(position, first, last, category()); + } + + template + void insert_iter(const_iterator position,InputIterator first,InputIterator last,std::input_iterator_tag) + { + for(; first!=last; ++first){ + this->insert(position, *first); + } + } + + template + iterator insert_iter(const_iterator position, InputIterator first, InputIterator last, std::forward_iterator_tag) + { + size_type n = (size_type)std::distance(first,last); + difference_type d = position-this->cbegin(); + if(n){ + this->insert_iter_prolog(n, d); + const impl_iterator it(impl.begin() + d); + this->insert_iter_fwd(it, first, last, n); + //Fix the pointers for the newly allocated buffer + this->align_nodes(it + n, get_last_align()); + } + return this->begin() + d; + } + + template + void insert_iter_fwd_alloc(const impl_iterator it, FwdIterator first, FwdIterator last, difference_type n, allocator_v1) + { + size_type i=0; + try{ + while(first!=last){ + *(it + i) = this->new_node(void_ptr((void*)(&*(it + i))), first); + ++first; + ++i; + } + } + catch(...){ + impl.erase(it + i, it + n); + this->align_nodes(it + i, get_last_align()); + throw; + } + } + + template + void insert_iter_fwd_alloc(const impl_iterator it, FwdIterator first, FwdIterator last, difference_type n, allocator_v2) + { + multiallocation_chain mem(get_al().allocate_individual(n)); + + size_type i = 0; + node_type_ptr_t p = 0; + try{ + while(first != last){ + p = mem.front(); + mem.pop_front(); + //This can throw + boost::container::construct_in_place(&*p, first); + p->set_pointer(void_ptr((void*)(&*(it + i)))); + ++first; + *(it + i) = p; + ++i; + } + } + catch(...){ + get_al().deallocate_one(p); + get_al().deallocate_many(BOOST_CONTAINER_MOVE_NAMESPACE::move(mem)); + impl.erase(it+i, it+n); + this->align_nodes(it+i,get_last_align()); + throw; + } + } + + template + void insert_iter_fwd(const impl_iterator it, FwdIterator first, FwdIterator last, difference_type n) + { + size_type i = 0; + node_type_ptr_t p = 0; + try{ + while(first != last){ + p = get_from_pool(); + if(!p){ + insert_iter_fwd_alloc(it+i, first, last, n-i, alloc_version()); + break; + } + //This can throw + boost::container::construct_in_place(&*p, first); + p->set_pointer(void_ptr(&*(it+i))); + ++first; + *(it+i)=p; + ++i; + } + } + catch(...){ + put_in_pool(p); + impl.erase(it+i,it+n); + this->align_nodes(it+i,get_last_align()); + throw; + } + } + + template + void insert_iter(const_iterator position, InputIterator first, InputIterator last, boost::mpl::false_) + { + this->insert_not_iter(position, first, last); + } + + static void swap_impl(stable_vector& x,stable_vector& y) + { + using std::swap; + swap(x.get_al(),y.get_al()); + swap(x.impl,y.impl); + swap(x.internal_data.pool_size, y.internal_data.pool_size); + x.readjust_end_node(); + y.readjust_end_node(); + } + + #if defined(STABLE_VECTOR_ENABLE_INVARIANT_CHECKING) + bool invariant()const + { + if(impl.empty()) + return !capacity() && !size(); + if(get_end_node() != *(impl.end() - ExtraPointers)){ + return false; + } + for(const_impl_iterator it=impl.begin(),it_end=get_last_align();it!=it_end;++it){ + if(node_ptr_cast(*it)->up != &*it) + return false; + } + size_type n = capacity()-size(); + const void_ptr &pool_head = impl.back(); + size_type num_pool = 0; + node_type_ptr_t p = node_ptr_cast(pool_head); + while(p){ + ++num_pool; + p = p->up; + } + return n >= num_pool; + } + + class invariant_checker:private boost::noncopyable + { + const stable_vector* p; + public: + invariant_checker(const stable_vector& v):p(&v){} + ~invariant_checker(){BOOST_ASSERT(p->invariant());} + void touch(){} + }; + #endif + + struct ebo_holder + : node_allocator_type + { + ebo_holder(const allocator_type &a) + : node_allocator_type(a), pool_size(0), end_node() + { + end_node.set_pointer(void_ptr(&end_node.up)); + } + size_type pool_size; + node_type_base_t end_node; + } internal_data; + + node_allocator_type &get_al() { return internal_data; } + const node_allocator_type &get_al() const { return internal_data; } + + impl_type impl; + /// @endcond +}; + +template +bool operator==(const stable_vector& x,const stable_vector& y) +{ + return x.size()==y.size()&&std::equal(x.begin(),x.end(),y.begin()); +} + +template +bool operator< (const stable_vector& x,const stable_vector& y) +{ + return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end()); +} + +template +bool operator!=(const stable_vector& x,const stable_vector& y) +{ + return !(x==y); +} + +template +bool operator> (const stable_vector& x,const stable_vector& y) +{ + return y +bool operator>=(const stable_vector& x,const stable_vector& y) +{ + return !(x +bool operator<=(const stable_vector& x,const stable_vector& y) +{ + return !(x>y); +} + +// specialized algorithms: + +template +void swap(stable_vector& x,stable_vector& y) +{ + x.swap(y); +} + +/// @cond + +#undef STABLE_VECTOR_CHECK_INVARIANT + +/// @endcond + +}} + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif //BOOST_CONTAINER_STABLE_VECTOR_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/string.hpp b/utils/boost_idb/boost/interprocess/containers/container/string.hpp new file mode 100644 index 00000000..53055d0a --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/string.hpp @@ -0,0 +1,2315 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_STRING_HPP +#define BOOST_CONTAINERS_STRING_HPP + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP + +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALLOCATION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP +#include +#include + +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +namespace boost { +namespace container { +#else +namespace boost { +namespace container { +#endif + +/// @cond +namespace containers_detail { +// ------------------------------------------------------------ +// Class basic_string_base. + +// basic_string_base is a helper class that makes it it easier to write +// an exception-safe version of basic_string. The constructor allocates, +// but does not initialize, a block of memory. The destructor +// deallocates, but does not destroy elements within, a block of +// memory. The destructor assumes that the memory either is the internal buffer, +// or else points to a block of memory that was allocated using _String_base's +// allocator and whose size is this->m_storage. +template +class basic_string_base +{ + basic_string_base(); + BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(basic_string_base) + + public: + typedef A allocator_type; + //! The stored allocator type + typedef allocator_type stored_allocator_type; + typedef typename A::pointer pointer; + typedef typename A::value_type value_type; + typedef typename A::size_type size_type; + + basic_string_base(const allocator_type& a) + : members_(a) + { init(); } + + basic_string_base(const allocator_type& a, std::size_t n) + : members_(a) + { + this->init(); + this->allocate_initial_block(n); + } + + basic_string_base(BOOST_MOVE_MACRO_RV_REF(basic_string_base) b) + : members_(b.members_) + { + init(); + this->swap(b); + } + + ~basic_string_base() + { + this->deallocate_block(); + if(!this->is_short()){ + static_cast(static_cast(&this->members_.m_repr.r))->~long_t(); + } + } + + private: + + //This is the structure controlling a long string + struct long_t + { + size_type is_short : 1; + size_type length : (sizeof(size_type)*CHAR_BIT - 1); + size_type storage; + pointer start; + + long_t() + {} + + long_t(const long_t &other) + { + this->is_short = other.is_short; + length = other.length; + storage = other.storage; + start = other.start; + } + + long_t &operator =(const long_t &other) + { + this->is_short = other.is_short; + length = other.length; + storage = other.storage; + start = other.start; + return *this; + } + }; + + //This basic type should have the same alignment as long_t +//iG typedef typename type_with_alignment::value>::type +// long_alignment_type; + typedef void *long_alignment_type; + BOOST_STATIC_ASSERT((containers_detail::alignment_of::value % + containers_detail::alignment_of::value) == 0); + + + //This type is the first part of the structure controlling a short string + //The "data" member stores + struct short_header + { + unsigned char is_short : 1; + unsigned char length : (CHAR_BIT - 1); + }; + + //This type has the same alignment and size as long_t but it's POD + //so, unlike long_t, it can be placed in a union + struct long_raw_t + { + long_alignment_type a; + unsigned char b[sizeof(long_t) - sizeof(long_alignment_type)]; + }; + + protected: + static const size_type MinInternalBufferChars = 8; + static const size_type AlignmentOfValueType = + alignment_of::value; + static const size_type ShortDataOffset = + containers_detail::ct_rounded_size::value; + static const size_type ZeroCostInternalBufferChars = + (sizeof(long_t) - ShortDataOffset)/sizeof(value_type); + static const size_type UnalignedFinalInternalBufferChars = + (ZeroCostInternalBufferChars > MinInternalBufferChars) ? + ZeroCostInternalBufferChars : MinInternalBufferChars; + + struct short_t + { + short_header h; + value_type data[UnalignedFinalInternalBufferChars]; + }; + + union repr_t + { + long_raw_t r; + short_t s; + + short_t &short_repr() const + { return *const_cast(&s); } + + long_t &long_repr() const + { return *static_cast(const_cast(static_cast(&r))); } + }; + + struct members_holder + : public A + { + members_holder(const A &a) + : A(a) + {} + + repr_t m_repr; + } members_; + + const A &alloc() const + { return members_; } + + A &alloc() + { return members_; } + + static const size_type InternalBufferChars = (sizeof(repr_t) - ShortDataOffset)/sizeof(value_type); + + private: + + static const size_type MinAllocation = InternalBufferChars*2; + + protected: + bool is_short() const + { return static_cast(this->members_.m_repr.s.h.is_short != 0); } + + void is_short(bool yes) + { + if(yes && !this->is_short()){ + static_cast(static_cast(&this->members_.m_repr.r))->~long_t(); + } + else{ + new(static_cast(&this->members_.m_repr.r))long_t(); + } + this->members_.m_repr.s.h.is_short = yes; + } + + private: + void init() + { + this->members_.m_repr.s.h.is_short = 1; + this->members_.m_repr.s.h.length = 0; + } + + protected: + + typedef containers_detail::integral_constant allocator_v1; + typedef containers_detail::integral_constant allocator_v2; + typedef containers_detail::integral_constant::value> alloc_version; + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, pointer reuse = 0) + { + if(this->is_short() && (command & (expand_fwd | expand_bwd)) ){ + reuse = pointer(0); + command &= ~(expand_fwd | expand_bwd); + } + return this->allocation_command + (command, limit_size, preferred_size, received_size, reuse, alloc_version()); + } + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, + const pointer &reuse, + allocator_v1) + { + (void)limit_size; + (void)reuse; + if(!(command & allocate_new)) + return std::pair(pointer(0), false); + received_size = preferred_size; + return std::make_pair(this->alloc().allocate(received_size), false); + } + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, + pointer reuse, + allocator_v2) + { + return this->alloc().allocation_command(command, limit_size, preferred_size, + received_size, reuse); + } + + size_type next_capacity(size_type additional_objects) const + { return get_next_capacity(this->alloc().max_size(), this->priv_storage(), additional_objects); } + + void deallocate(pointer p, std::size_t n) + { + if (p && (n > InternalBufferChars)) + this->alloc().deallocate(p, n); + } + + void construct(pointer p, const value_type &value = value_type()) + { new((void*)containers_detail::get_pointer(p)) value_type(value); } + + void destroy(pointer p, size_type n) + { + for(; n--; ++p) + containers_detail::get_pointer(p)->~value_type(); + } + + void destroy(pointer p) + { containers_detail::get_pointer(p)->~value_type(); } + + void allocate_initial_block(std::size_t n) + { + if (n <= this->max_size()) { + if(n > InternalBufferChars){ + size_type new_cap = this->next_capacity(n); + pointer p = this->allocation_command(allocate_new, n, new_cap, new_cap).first; + this->is_short(false); + this->priv_addr(p); + this->priv_size(0); + this->priv_storage(new_cap); + } + } + else + throw_length_error(); + } + + void deallocate_block() + { this->deallocate(this->priv_addr(), this->priv_storage()); } + + std::size_t max_size() const + { return this->alloc().max_size() - 1; } + + // Helper functions for exception handling. + void throw_length_error() const + { throw(std::length_error("basic_string")); } + + void throw_out_of_range() const + { throw(std::out_of_range("basic_string")); } + + protected: + size_type priv_capacity() const + { return this->priv_storage() - 1; } + + pointer priv_addr() const + { return this->is_short() ? pointer(&this->members_.m_repr.short_repr().data[0]) : this->members_.m_repr.long_repr().start; } + + void priv_addr(pointer addr) + { this->members_.m_repr.long_repr().start = addr; } + + size_type priv_storage() const + { return this->is_short() ? InternalBufferChars : this->members_.m_repr.long_repr().storage; } + + void priv_storage(size_type storage) + { + if(!this->is_short()) + this->members_.m_repr.long_repr().storage = storage; + } + + size_type priv_size() const + { return this->is_short() ? this->members_.m_repr.short_repr().h.length : this->members_.m_repr.long_repr().length; } + + void priv_size(size_type sz) + { + if(this->is_short()) + this->members_.m_repr.s.h.length = (unsigned char)sz; + else + this->members_.m_repr.long_repr().length = static_cast(sz); + } + + void swap(basic_string_base& other) + { + if(this->is_short()){ + if(other.is_short()){ + std::swap(this->members_.m_repr, other.members_.m_repr); + } + else{ + repr_t copied(this->members_.m_repr); + this->members_.m_repr.long_repr() = other.members_.m_repr.long_repr(); + other.members_.m_repr = copied; + } + } + else{ + if(other.is_short()){ + repr_t copied(other.members_.m_repr); + other.members_.m_repr.long_repr() = this->members_.m_repr.long_repr(); + this->members_.m_repr = copied; + } + else{ + std::swap(this->members_.m_repr.long_repr(), other.members_.m_repr.long_repr()); + } + } + + allocator_type & this_al = this->alloc(), &other_al = other.alloc(); + if(this_al != other_al){ + containers_detail::do_swap(this_al, other_al); + } + } +}; + +} //namespace containers_detail { + +/// @endcond + +//! The basic_string class represents a Sequence of characters. It contains all the +//! usual operations of a Sequence, and, additionally, it contains standard string +//! operations such as search and concatenation. +//! +//! The basic_string class is parameterized by character type, and by that type's +//! Character Traits. +//! +//! This class has performance characteristics very much like vector<>, meaning, +//! for example, that it does not perform reference-count or copy-on-write, and that +//! concatenation of two strings is an O(N) operation. +//! +//! Some of basic_string's member functions use an unusual method of specifying positions +//! and ranges. In addition to the conventional method using iterators, many of +//! basic_string's member functions use a single value pos of type size_type to represent a +//! position (in which case the position is begin() + pos, and many of basic_string's +//! member functions use two values, pos and n, to represent a range. In that case pos is +//! the beginning of the range and n is its size. That is, the range is +//! [begin() + pos, begin() + pos + n). +//! +//! Note that the C++ standard does not specify the complexity of basic_string operations. +//! In this implementation, basic_string has performance characteristics very similar to +//! those of vector: access to a single character is O(1), while copy and concatenation +//! are O(N). +//! +//! In this implementation, begin(), +//! end(), rbegin(), rend(), operator[], c_str(), and data() do not invalidate iterators. +//! In this implementation, iterators are only invalidated by member functions that +//! explicitly change the string's contents. +template +class basic_string + : private containers_detail::basic_string_base +{ + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(basic_string) + typedef containers_detail::basic_string_base base_t; + static const typename base_t::size_type InternalBufferChars = base_t::InternalBufferChars; + + protected: + // A helper class to use a char_traits as a function object. + + template + struct Eq_traits + : public std::binary_function + { + bool operator()(const typename Tr::char_type& x, + const typename Tr::char_type& y) const + { return Tr::eq(x, y); } + }; + + template + struct Not_within_traits + : public std::unary_function + { + typedef const typename Tr::char_type* Pointer; + const Pointer m_first; + const Pointer m_last; + + Not_within_traits(Pointer f, Pointer l) + : m_first(f), m_last(l) {} + + bool operator()(const typename Tr::char_type& x) const + { + return std::find_if(m_first, m_last, + std::bind1st(Eq_traits(), x)) == m_last; + } + }; + /// @endcond + + public: + + //! The allocator type + typedef A allocator_type; + //! The stored allocator type + typedef allocator_type stored_allocator_type; + //! The type of object, CharT, stored in the string + typedef CharT value_type; + //! The second template parameter Traits + typedef Traits traits_type; + //! Pointer to CharT + typedef typename A::pointer pointer; + //! Const pointer to CharT + typedef typename A::const_pointer const_pointer; + //! Reference to CharT + typedef typename A::reference reference; + //! Const reference to CharT + typedef typename A::const_reference const_reference; + //! An unsigned integral type + typedef typename A::size_type size_type; + //! A signed integral type + typedef typename A::difference_type difference_type; + //! Iterator used to iterate through a string. It's a Random Access Iterator + typedef pointer iterator; + //! Const iterator used to iterate through a string. It's a Random Access Iterator + typedef const_pointer const_iterator; + //! Iterator used to iterate backwards through a string + typedef std::reverse_iterator reverse_iterator; + //! Const iterator used to iterate backwards through a string + typedef std::reverse_iterator const_reverse_iterator; + //! The largest possible value of type size_type. That is, size_type(-1). + static const size_type npos; + + /// @cond + private: + typedef constant_iterator cvalue_iterator; + /// @endcond + + public: // Constructor, destructor, assignment. + /// @cond + struct reserve_t {}; + /// @endcond + + basic_string(reserve_t, std::size_t n, + const allocator_type& a = allocator_type()) + : base_t(a, n + 1) + { this->priv_terminate_string(); } + + //! Effects: Constructs a basic_string taking the allocator as parameter. + //! + //! Throws: If allocator_type's copy constructor throws. + explicit basic_string(const allocator_type& a = allocator_type()) + : base_t(a, InternalBufferChars) + { this->priv_terminate_string(); } + + //! Effects: Copy constructs a basic_string. + //! + //! Postcondition: x == *this. + //! + //! Throws: If allocator_type's default constructor or copy constructor throws. + basic_string(const basic_string& s) + : base_t(s.alloc()) + { this->priv_range_initialize(s.begin(), s.end()); } + + //! Effects: Move constructor. Moves mx's resources to *this. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + basic_string(BOOST_MOVE_MACRO_RV_REF(basic_string) s) + : base_t(BOOST_CONTAINER_MOVE_NAMESPACE::move((base_t&)s)) + {} + + //! Effects: Constructs a basic_string taking the allocator as parameter, + //! and is initialized by a specific number of characters of the s string. + basic_string(const basic_string& s, size_type pos, size_type n = npos, + const allocator_type& a = allocator_type()) + : base_t(a) + { + if (pos > s.size()) + this->throw_out_of_range(); + else + this->priv_range_initialize + (s.begin() + pos, s.begin() + pos + containers_detail::min_value(n, s.size() - pos)); + } + + //! Effects: Constructs a basic_string taking the allocator as parameter, + //! and is initialized by a specific number of characters of the s c-string. + basic_string(const CharT* s, size_type n, + const allocator_type& a = allocator_type()) + : base_t(a) + { this->priv_range_initialize(s, s + n); } + + //! Effects: Constructs a basic_string taking the allocator as parameter, + //! and is initialized by the null-terminated s c-string. + basic_string(const CharT* s, + const allocator_type& a = allocator_type()) + : base_t(a) + { this->priv_range_initialize(s, s + Traits::length(s)); } + + //! Effects: Constructs a basic_string taking the allocator as parameter, + //! and is initialized by n copies of c. + basic_string(size_type n, CharT c, + const allocator_type& a = allocator_type()) + : base_t(a) + { + this->priv_range_initialize(cvalue_iterator(c, n), + cvalue_iterator()); + } + + //! Effects: Constructs a basic_string taking the allocator as parameter, + //! and a range of iterators. + template + basic_string(InputIterator f, InputIterator l, + const allocator_type& a = allocator_type()) + : base_t(a) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_initialize_dispatch(f, l, Result()); + } + + //! Effects: Destroys the basic_string. All used memory is deallocated. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + ~basic_string() + {} + + //! Effects: Copy constructs a string. + //! + //! Postcondition: x == *this. + //! + //! Complexity: Linear to the elements x contains. + basic_string& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(basic_string) s) + { + if (&s != this) + this->assign(s.begin(), s.end()); + return *this; + } + + //! Effects: Move constructor. Moves mx's resources to *this. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + basic_string& operator=(BOOST_MOVE_MACRO_RV_REF(basic_string) ms) + { + basic_string &s = ms; + if (&s != this){ + this->swap(s); + } + return *this; + } + + //! Effects: Assignment from a null-terminated c-string. + basic_string& operator=(const CharT* s) + { return this->assign(s, s + Traits::length(s)); } + + //! Effects: Assignment from character. + basic_string& operator=(CharT c) + { return this->assign(static_cast(1), c); } + + //! Effects: Returns an iterator to the first element contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return this->priv_addr(); } + + //! Effects: Returns a const_iterator to the first element contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return this->priv_addr(); } + + //! Effects: Returns an iterator to the end of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return this->priv_addr() + this->priv_size(); } + + //! Effects: Returns a const_iterator to the end of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return this->priv_addr() + this->priv_size(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return reverse_iterator(this->priv_addr() + this->priv_size()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin() const + { return const_reverse_iterator(this->priv_addr() + this->priv_size()); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return reverse_iterator(this->priv_addr()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return const_reverse_iterator(this->priv_addr()); } + + //! Effects: Returns a copy of the internal allocator. + //! + //! Throws: If allocator's copy constructor throws. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return this->alloc(); } + + //! Effects: Returns the number of the elements contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return this->priv_size(); } + + //! Effects: Returns the number of the elements contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type length() const + { return this->size(); } + + //! Effects: Returns the largest possible size of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return base_t::max_size(); } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are copy constructed from x. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type n, CharT c) + { + if (n <= size()) + this->erase(this->begin() + n, this->end()); + else + this->append(n - this->size(), c); + } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are default constructed. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type n) + { resize(n, this->priv_null()); } + + //! Effects: If n is less than or equal to capacity(), this call has no + //! effect. Otherwise, it is a request for allocation of additional memory. + //! If the request is successful, then capacity() is greater than or equal to + //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. + //! + //! Throws: If memory allocation allocation throws or T's copy constructor throws. + void reserve(size_type res_arg) + { + if (res_arg > this->max_size()) + this->throw_length_error(); + + if (this->capacity() < res_arg){ + size_type n = containers_detail::max_value(res_arg, this->size()) + 1; + size_type new_cap = this->next_capacity(n); + pointer new_start = this->allocation_command + (allocate_new, n, new_cap, new_cap).first; + size_type new_length = 0; + + new_length += priv_uninitialized_copy + (this->priv_addr(), this->priv_addr() + this->priv_size(), new_start); + this->priv_construct_null(new_start + new_length); + this->deallocate_block(); + this->is_short(false); + this->priv_addr(new_start); + this->priv_size(new_length); + this->priv_storage(new_cap); + } + } + + //! Effects: Number of elements for which memory has been allocated. + //! capacity() is always greater than or equal to size(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type capacity() const + { return this->priv_capacity(); } + + //! Effects: Erases all the elements of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements in the vector. + void clear() + { + if (!empty()) { + Traits::assign(*this->priv_addr(), this->priv_null()); + this->priv_size(0); + } + } + + //! Effects: Returns true if the vector contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return !this->priv_size(); } + + //! Requires: size() < n. + //! + //! Effects: Returns a reference to the nth element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference operator[](size_type n) + { return *(this->priv_addr() + n); } + + //! Requires: size() < n. + //! + //! Effects: Returns a const reference to the nth element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference operator[](size_type n) const + { return *(this->priv_addr() + n); } + + //! Requires: size() < n. + //! + //! Effects: Returns a reference to the nth element + //! from the beginning of the container. + //! + //! Throws: std::range_error if n >= size() + //! + //! Complexity: Constant. + reference at(size_type n) { + if (n >= size()) + this->throw_out_of_range(); + return *(this->priv_addr() + n); + } + + //! Requires: size() < n. + //! + //! Effects: Returns a const reference to the nth element + //! from the beginning of the container. + //! + //! Throws: std::range_error if n >= size() + //! + //! Complexity: Constant. + const_reference at(size_type n) const { + if (n >= size()) + this->throw_out_of_range(); + return *(this->priv_addr() + n); + } + + //! Effects: Appends string s to *this. + basic_string& operator+=(const basic_string& s) + { return this->append(s); } + + //! Effects: Appends c-string s to *this. + basic_string& operator+=(const CharT* s) + { return this->append(s); } + + //! Effects: Appends character c to *this. + basic_string& operator+=(CharT c) + { this->push_back(c); return *this; } + + //! Effects: Appends string s to *this. + basic_string& append(const basic_string& s) + { return this->append(s.begin(), s.end()); } + + //! Effects: Appends the range [pos, pos + n) from string s to *this. + basic_string& append(const basic_string& s, size_type pos, size_type n) + { + if (pos > s.size()) + this->throw_out_of_range(); + return this->append(s.begin() + pos, + s.begin() + pos + containers_detail::min_value(n, s.size() - pos)); + } + + //! Effects: Appends the range [s, s + n) from c-string s to *this. + basic_string& append(const CharT* s, size_type n) + { return this->append(s, s + n); } + + //! Effects: Appends the c-string s to *this. + basic_string& append(const CharT* s) + { return this->append(s, s + Traits::length(s)); } + + //! Effects: Appends the n times the character c to *this. + basic_string& append(size_type n, CharT c) + { return this->append(cvalue_iterator(c, n), cvalue_iterator()); } + + //! Effects: Appends the range [first, last) *this. + template + basic_string& append(InputIter first, InputIter last) + { this->insert(this->end(), first, last); return *this; } + + //! Effects: Inserts a copy of c at the end of the vector. + void push_back(CharT c) + { + if (this->priv_size() < this->capacity()){ + this->priv_construct_null(this->priv_addr() + (this->priv_size() + 1)); + Traits::assign(this->priv_addr()[this->priv_size()], c); + this->priv_size(this->priv_size()+1); + } + else{ + //No enough memory, insert a new object at the end + this->append((size_type)1, c); + } + } + + //! Effects: Removes the last element from the vector. + void pop_back() + { + Traits::assign(this->priv_addr()[this->priv_size()-1], this->priv_null()); + this->priv_size(this->priv_size()-1);; + } + + //! Effects: Assigns the value s to *this. + basic_string& assign(const basic_string& s) + { return this->operator=(s); } + + //! Effects: Moves the resources from ms *this. + basic_string& assign(BOOST_MOVE_MACRO_RV_REF(basic_string) ms) + { return this->operator=(ms);} + + //! Effects: Assigns the range [pos, pos + n) from s to *this. + basic_string& assign(const basic_string& s, + size_type pos, size_type n) { + if (pos > s.size()) + this->throw_out_of_range(); + return this->assign(s.begin() + pos, + s.begin() + pos + containers_detail::min_value(n, s.size() - pos)); + } + + //! Effects: Assigns the range [s, s + n) from s to *this. + basic_string& assign(const CharT* s, size_type n) + { return this->assign(s, s + n); } + + //! Effects: Assigns the c-string s to *this. + basic_string& assign(const CharT* s) + { return this->assign(s, s + Traits::length(s)); } + + //! Effects: Assigns the character c n-times to *this. + basic_string& assign(size_type n, CharT c) + { return this->assign(cvalue_iterator(c, n), cvalue_iterator()); } + + //! Effects: Assigns the range [first, last) to *this. + template + basic_string& assign(InputIter first, InputIter last) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + return this->priv_assign_dispatch(first, last, Result()); + } + + //! Effects: Assigns the range [f, l) to *this. + basic_string& assign(const CharT* f, const CharT* l) + { + const std::ptrdiff_t n = l - f; + if (static_cast(n) <= size()) { + Traits::copy(containers_detail::get_pointer(this->priv_addr()), f, n); + this->erase(this->priv_addr() + n, this->priv_addr() + this->priv_size()); + } + else { + Traits::copy(containers_detail::get_pointer(this->priv_addr()), f, this->priv_size()); + this->append(f + this->priv_size(), l); + } + return *this; + } + + //! Effects: Inserts the string s before pos. + basic_string& insert(size_type pos, const basic_string& s) + { + if (pos > size()) + this->throw_out_of_range(); + if (this->size() > this->max_size() - s.size()) + this->throw_length_error(); + this->insert(this->priv_addr() + pos, s.begin(), s.end()); + return *this; + } + + //! Effects: Inserts the range [pos, pos + n) from string s before pos. + basic_string& insert(size_type pos, const basic_string& s, + size_type beg, size_type n) + { + if (pos > this->size() || beg > s.size()) + this->throw_out_of_range(); + size_type len = containers_detail::min_value(n, s.size() - beg); + if (this->size() > this->max_size() - len) + this->throw_length_error(); + const CharT *beg_ptr = containers_detail::get_pointer(s.begin()) + beg; + const CharT *end_ptr = beg_ptr + len; + this->insert(this->priv_addr() + pos, beg_ptr, end_ptr); + return *this; + } + + //! Effects: Inserts the range [s, s + n) before pos. + basic_string& insert(size_type pos, const CharT* s, size_type n) + { + if (pos > this->size()) + this->throw_out_of_range(); + if (this->size() > this->max_size() - n) + this->throw_length_error(); + this->insert(this->priv_addr() + pos, s, s + n); + return *this; + } + + //! Effects: Inserts the c-string s before pos. + basic_string& insert(size_type pos, const CharT* s) + { + if (pos > size()) + this->throw_out_of_range(); + size_type len = Traits::length(s); + if (this->size() > this->max_size() - len) + this->throw_length_error(); + this->insert(this->priv_addr() + pos, s, s + len); + return *this; + } + + //! Effects: Inserts the character c n-times before pos. + basic_string& insert(size_type pos, size_type n, CharT c) + { + if (pos > this->size()) + this->throw_out_of_range(); + if (this->size() > this->max_size() - n) + this->throw_length_error(); + this->insert(this->priv_addr() + pos, n, c); + return *this; + } + + //! Effects: Inserts the character c before position. + iterator insert(iterator position, CharT c) + { + size_type new_offset = position - this->priv_addr() + 1; + this->insert(position, cvalue_iterator(c, 1), + cvalue_iterator()); + return this->priv_addr() + new_offset; + } + + //! Effects: Inserts the character c n-times before position. + void insert(iterator position, std::size_t n, CharT c) + { + this->insert(position, cvalue_iterator(c, n), + cvalue_iterator()); + } + + //! Effects: Inserts the range [first, last) before position. + template + void insert(iterator p, InputIter first, InputIter last) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_insert_dispatch(p, first, last, Result()); + } + + //! Effects: Inserts the range [pos, pos + n). + basic_string& erase(size_type pos = 0, size_type n = npos) + { + if (pos > size()) + this->throw_out_of_range(); + erase(this->priv_addr() + pos, this->priv_addr() + pos + containers_detail::min_value(n, size() - pos)); + return *this; + } + + //! Effects: Erases the character pointed by position. + iterator erase(iterator position) + { + // The move includes the terminating null. + Traits::move(containers_detail::get_pointer(position), + containers_detail::get_pointer(position + 1), + this->priv_size() - (position - this->priv_addr())); + this->priv_size(this->priv_size()-1); + return position; + } + + //! Effects: Erases the range [first, last). + iterator erase(iterator first, iterator last) + { + if (first != last) { // The move includes the terminating null. + size_type num_erased = last - first; + Traits::move(containers_detail::get_pointer(first), + containers_detail::get_pointer(last), + (this->priv_size() + 1)-(last - this->priv_addr())); + size_type new_length = this->priv_size() - num_erased; + this->priv_size(new_length); + } + return first; + } + + //! Effects: Replaces a substring of *this with the string s. + basic_string& replace(size_type pos, size_type n, + const basic_string& s) + { + if (pos > size()) + this->throw_out_of_range(); + const size_type len = containers_detail::min_value(n, size() - pos); + if (this->size() - len >= this->max_size() - s.size()) + this->throw_length_error(); + return this->replace(this->priv_addr() + pos, this->priv_addr() + pos + len, + s.begin(), s.end()); + } + + //! Effects: Replaces a substring of *this with a substring of s. + basic_string& replace(size_type pos1, size_type n1, + const basic_string& s, + size_type pos2, size_type n2) + { + if (pos1 > size() || pos2 > s.size()) + this->throw_out_of_range(); + const size_type len1 = containers_detail::min_value(n1, size() - pos1); + const size_type len2 = containers_detail::min_value(n2, s.size() - pos2); + if (this->size() - len1 >= this->max_size() - len2) + this->throw_length_error(); + return this->replace(this->priv_addr() + pos1, this->priv_addr() + pos1 + len1, + s.priv_addr() + pos2, s.priv_addr() + pos2 + len2); + } + + //! Effects: Replaces a substring of *this with the first n1 characters of s. + basic_string& replace(size_type pos, size_type n1, + const CharT* s, size_type n2) + { + if (pos > size()) + this->throw_out_of_range(); + const size_type len = containers_detail::min_value(n1, size() - pos); + if (n2 > this->max_size() || size() - len >= this->max_size() - n2) + this->throw_length_error(); + return this->replace(this->priv_addr() + pos, this->priv_addr() + pos + len, + s, s + n2); + } + + //! Effects: Replaces a substring of *this with a null-terminated character array. + basic_string& replace(size_type pos, size_type n1, + const CharT* s) + { + if (pos > size()) + this->throw_out_of_range(); + const size_type len = containers_detail::min_value(n1, size() - pos); + const size_type n2 = Traits::length(s); + if (n2 > this->max_size() || size() - len >= this->max_size() - n2) + this->throw_length_error(); + return this->replace(this->priv_addr() + pos, this->priv_addr() + pos + len, + s, s + Traits::length(s)); + } + + //! Effects: Replaces a substring of *this with n1 copies of c. + basic_string& replace(size_type pos, size_type n1, + size_type n2, CharT c) + { + if (pos > size()) + this->throw_out_of_range(); + const size_type len = containers_detail::min_value(n1, size() - pos); + if (n2 > this->max_size() || size() - len >= this->max_size() - n2) + this->throw_length_error(); + return this->replace(this->priv_addr() + pos, this->priv_addr() + pos + len, n2, c); + } + + //! Effects: Replaces a substring of *this with the string s. + basic_string& replace(iterator first, iterator last, + const basic_string& s) + { return this->replace(first, last, s.begin(), s.end()); } + + //! Effects: Replaces a substring of *this with the first n characters of s. + basic_string& replace(iterator first, iterator last, + const CharT* s, size_type n) + { return this->replace(first, last, s, s + n); } + + //! Effects: Replaces a substring of *this with a null-terminated character array. + basic_string& replace(iterator first, iterator last, + const CharT* s) + { return this->replace(first, last, s, s + Traits::length(s)); } + + //! Effects: Replaces a substring of *this with n copies of c. + basic_string& replace(iterator first, iterator last, + size_type n, CharT c) + { + const size_type len = static_cast(last - first); + if (len >= n) { + Traits::assign(containers_detail::get_pointer(first), n, c); + erase(first + n, last); + } + else { + Traits::assign(containers_detail::get_pointer(first), len, c); + insert(last, n - len, c); + } + return *this; + } + + //! Effects: Replaces a substring of *this with the range [f, l) + template + basic_string& replace(iterator first, iterator last, + InputIter f, InputIter l) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + return this->priv_replace_dispatch(first, last, f, l, Result()); + } + + //! Effects: Copies a substring of *this to a buffer. + size_type copy(CharT* s, size_type n, size_type pos = 0) const + { + if (pos > size()) + this->throw_out_of_range(); + const size_type len = containers_detail::min_value(n, size() - pos); + Traits::copy(s, containers_detail::get_pointer(this->priv_addr() + pos), len); + return len; + } + + //! Effects: Swaps the contents of two strings. + void swap(basic_string& x) + { base_t::swap(x); } + + //! Returns: Returns a pointer to a null-terminated array of characters + //! representing the string's contents. For any string s it is guaranteed + //! that the first s.size() characters in the array pointed to by s.c_str() + //! are equal to the character in s, and that s.c_str()[s.size()] is a null + //! character. Note, however, that it not necessarily the first null character. + //! Characters within a string are permitted to be null. + const CharT* c_str() const + { return containers_detail::get_pointer(this->priv_addr()); } + + //! Returns: Returns a pointer to an array of characters, not necessarily + //! null-terminated, representing the string's contents. data() is permitted, + //! but not required, to be identical to c_str(). The first size() characters + //! of that array are guaranteed to be identical to the characters in *this. + //! The return value of data() is never a null pointer, even if size() is zero. + const CharT* data() const + { return containers_detail::get_pointer(this->priv_addr()); } + + //! Effects: Searches for s as a substring of *this, beginning at + //! character pos of *this. + size_type find(const basic_string& s, size_type pos = 0) const + { return find(s.c_str(), pos, s.size()); } + + //! Effects: Searches for a null-terminated character array as a + //! substring of *this, beginning at character pos of *this. + size_type find(const CharT* s, size_type pos = 0) const + { return find(s, pos, Traits::length(s)); } + + //! Effects: Searches for the first n characters of s as a substring + //! of *this, beginning at character pos of *this. + size_type find(const CharT* s, size_type pos, size_type n) const + { + if (pos + n > size()) + return npos; + else { + pointer finish = this->priv_addr() + this->priv_size(); + const const_iterator result = + std::search(containers_detail::get_pointer(this->priv_addr() + pos), + containers_detail::get_pointer(finish), + s, s + n, Eq_traits()); + return result != finish ? result - begin() : npos; + } + } + + //! Effects: Searches for the character c, beginning at character + //! position pos. + size_type find(CharT c, size_type pos = 0) const + { + if (pos >= size()) + return npos; + else { + pointer finish = this->priv_addr() + this->priv_size(); + const const_iterator result = + std::find_if(this->priv_addr() + pos, finish, + std::bind2nd(Eq_traits(), c)); + return result != finish ? result - begin() : npos; + } + } + + //! Effects: Searches backward for s as a substring of *this, + //! beginning at character position min(pos, size()) + size_type rfind(const basic_string& s, size_type pos = npos) const + { return rfind(s.c_str(), pos, s.size()); } + + //! Effects: Searches backward for a null-terminated character array + //! as a substring of *this, beginning at character min(pos, size()) + size_type rfind(const CharT* s, size_type pos = npos) const + { return rfind(s, pos, Traits::length(s)); } + + //! Effects: Searches backward for the first n characters of s as a + //! substring of *this, beginning at character position min(pos, size()). + size_type rfind(const CharT* s, size_type pos, size_type n) const + { + const std::size_t len = size(); + + if (n > len) + return npos; + else if (n == 0) + return containers_detail::min_value(len, pos); + else { + const const_iterator last = begin() + containers_detail::min_value(len - n, pos) + n; + const const_iterator result = find_end(begin(), last, + s, s + n, + Eq_traits()); + return result != last ? result - begin() : npos; + } + } + + //! Effects: Searches backward for a null-terminated character array + //! as a substring of *this, beginning at character min(pos, size()). + size_type rfind(CharT c, size_type pos = npos) const + { + const size_type len = size(); + + if (len < 1) + return npos; + else { + const const_iterator last = begin() + containers_detail::min_value(len - 1, pos) + 1; + const_reverse_iterator rresult = + std::find_if(const_reverse_iterator(last), rend(), + std::bind2nd(Eq_traits(), c)); + return rresult != rend() ? (rresult.base() - 1) - begin() : npos; + } + } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is equal to any character within s. + size_type find_first_of(const basic_string& s, size_type pos = 0) const + { return find_first_of(s.c_str(), pos, s.size()); } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is equal to any character within s. + size_type find_first_of(const CharT* s, size_type pos = 0) const + { return find_first_of(s, pos, Traits::length(s)); } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is equal to any character within the first n characters of s. + size_type find_first_of(const CharT* s, size_type pos, + size_type n) const + { + if (pos >= size()) + return npos; + else { + pointer finish = this->priv_addr() + this->priv_size(); + const_iterator result = std::find_first_of(this->priv_addr() + pos, finish, + s, s + n, + Eq_traits()); + return result != finish ? result - begin() : npos; + } + } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is equal to c. + size_type find_first_of(CharT c, size_type pos = 0) const + { return find(c, pos); } + + //! Effects: Searches backward within *this, beginning at min(pos, size()), + //! for the first character that is equal to any character within s. + size_type find_last_of(const basic_string& s, + size_type pos = npos) const + { return find_last_of(s.c_str(), pos, s.size()); } + + //! Effects: Searches backward *this, beginning at min(pos, size()), for + //! the first character that is equal to any character within s. + size_type find_last_of(const CharT* s, size_type pos = npos) const + { return find_last_of(s, pos, Traits::length(s)); } + + //! Effects: Searches backward within *this, beginning at min(pos, size()), + //! for the first character that is equal to any character within the first n + //! characters of s. + size_type find_last_of(const CharT* s, size_type pos, size_type n) const + { + const size_type len = size(); + + if (len < 1) + return npos; + else { + const const_iterator last = this->priv_addr() + containers_detail::min_value(len - 1, pos) + 1; + const const_reverse_iterator rresult = + std::find_first_of(const_reverse_iterator(last), rend(), + s, s + n, + Eq_traits()); + return rresult != rend() ? (rresult.base() - 1) - this->priv_addr() : npos; + } + } + + //! Effects: Searches backward *this, beginning at min(pos, size()), for + //! the first character that is equal to c. + size_type find_last_of(CharT c, size_type pos = npos) const + { return rfind(c, pos); } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is not equal to any character within s. + size_type find_first_not_of(const basic_string& s, + size_type pos = 0) const + { return find_first_not_of(s.c_str(), pos, s.size()); } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is not equal to any character within s. + size_type find_first_not_of(const CharT* s, size_type pos = 0) const + { return find_first_not_of(s, pos, Traits::length(s)); } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is not equal to any character within the first n + //! characters of s. + size_type find_first_not_of(const CharT* s, size_type pos, + size_type n) const + { + if (pos > size()) + return npos; + else { + pointer finish = this->priv_addr() + this->priv_size(); + const_iterator result = std::find_if(this->priv_addr() + pos, finish, + Not_within_traits(s, s + n)); + return result != finish ? result - this->priv_addr() : npos; + } + } + + //! Effects: Searches within *this, beginning at pos, for the first + //! character that is not equal to c. + size_type find_first_not_of(CharT c, size_type pos = 0) const + { + if (pos > size()) + return npos; + else { + pointer finish = this->priv_addr() + this->priv_size(); + const_iterator result + = std::find_if(this->priv_addr() + pos, finish, + std::not1(std::bind2nd(Eq_traits(), c))); + return result != finish ? result - begin() : npos; + } + } + + //! Effects: Searches backward within *this, beginning at min(pos, size()), + //! for the first character that is not equal to any character within s. + size_type find_last_not_of(const basic_string& s, + size_type pos = npos) const + { return find_last_not_of(s.c_str(), pos, s.size()); } + + //! Effects: Searches backward *this, beginning at min(pos, size()), + //! for the first character that is not equal to any character within s. + size_type find_last_not_of(const CharT* s, size_type pos = npos) const + { return find_last_not_of(s, pos, Traits::length(s)); } + + //! Effects: Searches backward within *this, beginning at min(pos, size()), + //! for the first character that is not equal to any character within the first + //! n characters of s. + size_type find_last_not_of(const CharT* s, size_type pos, size_type n) const + { + const size_type len = size(); + + if (len < 1) + return npos; + else { + const const_iterator last = begin() + containers_detail::min_value(len - 1, pos) + 1; + const const_reverse_iterator rresult = + std::find_if(const_reverse_iterator(last), rend(), + Not_within_traits(s, s + n)); + return rresult != rend() ? (rresult.base() - 1) - begin() : npos; + } + } + + //! Effects: Searches backward *this, beginning at min(pos, size()), + //! for the first character that is not equal to c. + size_type find_last_not_of(CharT c, size_type pos = npos) const + { + const size_type len = size(); + + if (len < 1) + return npos; + else { + const const_iterator last = begin() + containers_detail::min_value(len - 1, pos) + 1; + const_reverse_iterator rresult = + std::find_if(const_reverse_iterator(last), rend(), + std::not1(std::bind2nd(Eq_traits(), c))); + return rresult != rend() ? (rresult.base() - 1) - begin() : npos; + } + } + + //! Effects: Returns a substring of *this. + basic_string substr(size_type pos = 0, size_type n = npos) const + { + if (pos > size()) + this->throw_out_of_range(); + return basic_string(this->priv_addr() + pos, + this->priv_addr() + pos + containers_detail::min_value(n, size() - pos), this->alloc()); + } + + //! Effects: Three-way lexicographical comparison of s and *this. + int compare(const basic_string& s) const + { return s_compare(this->priv_addr(), this->priv_addr() + this->priv_size(), s.priv_addr(), s.priv_addr() + s.priv_size()); } + + //! Effects: Three-way lexicographical comparison of s and a substring + //! of *this. + int compare(size_type pos1, size_type n1, const basic_string& s) const + { + if (pos1 > size()) + this->throw_out_of_range(); + return s_compare(this->priv_addr() + pos1, + this->priv_addr() + pos1 + containers_detail::min_value(n1, size() - pos1), + s.priv_addr(), s.priv_addr() + s.priv_size()); + } + + //! Effects: Three-way lexicographical comparison of a substring of s + //! and a substring of *this. + int compare(size_type pos1, size_type n1, + const basic_string& s, + size_type pos2, size_type n2) const { + if (pos1 > size() || pos2 > s.size()) + this->throw_out_of_range(); + return s_compare(this->priv_addr() + pos1, + this->priv_addr() + pos1 + containers_detail::min_value(n1, size() - pos1), + s.priv_addr() + pos2, + s.priv_addr() + pos2 + containers_detail::min_value(n2, size() - pos2)); + } + + //! Effects: Three-way lexicographical comparison of s and *this. + int compare(const CharT* s) const + { return s_compare(this->priv_addr(), this->priv_addr() + this->priv_size(), s, s + Traits::length(s)); } + + + //! Effects: Three-way lexicographical comparison of the first + //! min(len, traits::length(s) characters of s and a substring of *this. + int compare(size_type pos1, size_type n1, const CharT* s, + size_type n2 = npos) const + { + if (pos1 > size()) + this->throw_out_of_range(); + return s_compare(this->priv_addr() + pos1, + this->priv_addr() + pos1 + containers_detail::min_value(n1, size() - pos1), + s, s + n2); + } + + /// @cond + private: + static int s_compare(const_pointer f1, const_pointer l1, + const_pointer f2, const_pointer l2) + { + const std::ptrdiff_t n1 = l1 - f1; + const std::ptrdiff_t n2 = l2 - f2; + const int cmp = Traits::compare(containers_detail::get_pointer(f1), + containers_detail::get_pointer(f2), + containers_detail::min_value(n1, n2)); + return cmp != 0 ? cmp : (n1 < n2 ? -1 : (n1 > n2 ? 1 : 0)); + } + + void priv_construct_null(pointer p) + { this->construct(p, 0); } + + static CharT priv_null() + { return (CharT) 0; } + + // Helper functions used by constructors. It is a severe error for + // any of them to be called anywhere except from within constructors. + void priv_terminate_string() + { this->priv_construct_null(this->priv_addr() + this->priv_size()); } + + template + void priv_range_initialize(InputIter f, InputIter l, + std::input_iterator_tag) + { + this->allocate_initial_block(InternalBufferChars); + this->priv_construct_null(this->priv_addr() + this->priv_size()); + this->append(f, l); + } + + template + void priv_range_initialize(ForwardIter f, ForwardIter l, + std::forward_iterator_tag) + { + difference_type n = std::distance(f, l); + this->allocate_initial_block(containers_detail::max_value(n+1, InternalBufferChars)); + priv_uninitialized_copy(f, l, this->priv_addr()); + this->priv_size(n); + this->priv_terminate_string(); + } + + template + void priv_range_initialize(InputIter f, InputIter l) + { + typedef typename std::iterator_traits::iterator_category Category; + this->priv_range_initialize(f, l, Category()); + } + + template + void priv_initialize_dispatch(Integer n, Integer x, containers_detail::true_) + { + this->allocate_initial_block(containers_detail::max_value(n+1, InternalBufferChars)); + priv_uninitialized_fill_n(this->priv_addr(), n, x); + this->priv_size(n); + this->priv_terminate_string(); + } + + template + void priv_initialize_dispatch(InputIter f, InputIter l, containers_detail::false_) + { this->priv_range_initialize(f, l); } + + template inline + void priv_uninitialized_fill_n(FwdIt first, Count count, const CharT val) + { + //Save initial position + FwdIt init = first; + + BOOST_TRY{ + //Construct objects + for (; count--; ++first){ + this->construct(first, val); + } + } + BOOST_CATCH(...){ + //Call destructors + for (; init != first; ++init){ + this->destroy(init); + } + BOOST_RETHROW + } + BOOST_CATCH_END + } + + template inline + size_type priv_uninitialized_copy(InpIt first, InpIt last, FwdIt dest) + { + //Save initial destination position + FwdIt dest_init = dest; + size_type constructed = 0; + + BOOST_TRY{ + //Try to build objects + for (; first != last; ++dest, ++first, ++constructed){ + this->construct(dest, *first); + } + } + BOOST_CATCH(...){ + //Call destructors + for (; constructed--; ++dest_init){ + this->destroy(dest_init); + } + BOOST_RETHROW + } + BOOST_CATCH_END + return (constructed); + } + + template + basic_string& priv_assign_dispatch(Integer n, Integer x, containers_detail::true_) + { return this->assign((size_type) n, (CharT) x); } + + template + basic_string& priv_assign_dispatch(InputIter f, InputIter l, + containers_detail::false_) + { + size_type cur = 0; + CharT *ptr = containers_detail::get_pointer(this->priv_addr()); + while (f != l && cur != this->priv_size()) { + Traits::assign(*ptr, *f); + ++f; + ++cur; + ++ptr; + } + if (f == l) + this->erase(this->priv_addr() + cur, this->priv_addr() + this->priv_size()); + else + this->append(f, l); + return *this; + } + + template + void priv_insert(iterator p, InputIter first, InputIter last, std::input_iterator_tag) + { + for ( ; first != last; ++first, ++p) { + p = this->insert(p, *first); + } + } + + template + void priv_insert(iterator position, ForwardIter first, + ForwardIter last, std::forward_iterator_tag) + { + if (first != last) { + size_type n = std::distance(first, last); + size_type remaining = this->capacity() - this->priv_size(); + const size_type old_size = this->size(); + pointer old_start = this->priv_addr(); + bool enough_capacity = false; + std::pair allocation_ret; + size_type new_cap = 0; + + //Check if we have enough capacity + if (remaining >= n){ + enough_capacity = true; + } + else { + //Otherwise expand current buffer or allocate new storage + new_cap = this->next_capacity(n); + allocation_ret = this->allocation_command + (allocate_new | expand_fwd | expand_bwd, old_size + n + 1, + new_cap, new_cap, old_start); + + //Check forward expansion + if(old_start == allocation_ret.first){ + enough_capacity = true; + this->priv_storage(new_cap); + } + } + + //Reuse same buffer + if(enough_capacity){ + const size_type elems_after = + this->priv_size() - (position - this->priv_addr()); + size_type old_length = this->priv_size(); + if (elems_after >= n) { + pointer pointer_past_last = this->priv_addr() + this->priv_size() + 1; + priv_uninitialized_copy(this->priv_addr() + (this->priv_size() - n + 1), + pointer_past_last, pointer_past_last); + + this->priv_size(this->priv_size()+n); + Traits::move(containers_detail::get_pointer(position + n), + containers_detail::get_pointer(position), + (elems_after - n) + 1); + this->priv_copy(first, last, position); + } + else { + ForwardIter mid = first; + std::advance(mid, elems_after + 1); + + priv_uninitialized_copy(mid, last, this->priv_addr() + this->priv_size() + 1); + this->priv_size(this->priv_size() + (n - elems_after)); + priv_uninitialized_copy + (position, this->priv_addr() + old_length + 1, + this->priv_addr() + this->priv_size()); + this->priv_size(this->priv_size() + elems_after); + this->priv_copy(first, mid, position); + } + } + else{ + pointer new_start = allocation_ret.first; + if(!allocation_ret.second){ + //Copy data to new buffer + size_type new_length = 0; + //This can't throw, since characters are POD + new_length += priv_uninitialized_copy + (this->priv_addr(), position, new_start); + new_length += priv_uninitialized_copy + (first, last, new_start + new_length); + new_length += priv_uninitialized_copy + (position, this->priv_addr() + this->priv_size(), + new_start + new_length); + this->priv_construct_null(new_start + new_length); + + this->deallocate_block(); + this->is_short(false); + this->priv_addr(new_start); + this->priv_size(new_length); + this->priv_storage(new_cap); + } + else{ + //value_type is POD, so backwards expansion is much easier + //than with vector + value_type *oldbuf = containers_detail::get_pointer(old_start); + value_type *newbuf = containers_detail::get_pointer(new_start); + value_type *pos = containers_detail::get_pointer(position); + size_type before = pos - oldbuf; + + //First move old data + Traits::move(newbuf, oldbuf, before); + Traits::move(newbuf + before + n, pos, old_size - before); + //Now initialize the new data + priv_uninitialized_copy(first, last, new_start + before); + this->priv_construct_null(new_start + (old_size + n)); + this->is_short(false); + this->priv_addr(new_start); + this->priv_size(old_size + n); + this->priv_storage(new_cap); + } + } + } + } + + template + void priv_insert_dispatch(iterator p, Integer n, Integer x, + containers_detail::true_) + { insert(p, (size_type) n, (CharT) x); } + + template + void priv_insert_dispatch(iterator p, InputIter first, InputIter last, + containers_detail::false_) + { + typedef typename std::iterator_traits::iterator_category Category; + priv_insert(p, first, last, Category()); + } + + template + void priv_copy(InputIterator first, InputIterator last, iterator result) + { + for ( ; first != last; ++first, ++result) + Traits::assign(*result, *first); + } + + void priv_copy(const CharT* first, const CharT* last, CharT* result) + { Traits::copy(result, first, last - first); } + + template + basic_string& priv_replace_dispatch(iterator first, iterator last, + Integer n, Integer x, + containers_detail::true_) + { return this->replace(first, last, (size_type) n, (CharT) x); } + + template + basic_string& priv_replace_dispatch(iterator first, iterator last, + InputIter f, InputIter l, + containers_detail::false_) + { + typedef typename std::iterator_traits::iterator_category Category; + return this->priv_replace(first, last, f, l, Category()); + } + + + template + basic_string& priv_replace(iterator first, iterator last, + InputIter f, InputIter l, std::input_iterator_tag) + { + for ( ; first != last && f != l; ++first, ++f) + Traits::assign(*first, *f); + + if (f == l) + this->erase(first, last); + else + this->insert(last, f, l); + return *this; + } + + template + basic_string& priv_replace(iterator first, iterator last, + ForwardIter f, ForwardIter l, + std::forward_iterator_tag) + { + difference_type n = std::distance(f, l); + const difference_type len = last - first; + if (len >= n) { + this->priv_copy(f, l, first); + this->erase(first + n, last); + } + else { + ForwardIter m = f; + std::advance(m, len); + this->priv_copy(f, m, first); + this->insert(last, m, l); + } + return *this; + } + /// @endcond +}; + +//!Typedef for a basic_string of +//!narrow characters +typedef basic_string + + ,std::allocator > +string; + +//!Typedef for a basic_string of +//!narrow characters +typedef basic_string + + ,std::allocator > +wstring; + +/// @cond + +template +const typename basic_string::size_type +basic_string::npos + = (typename basic_string::size_type) -1; + +/// @endcond + +// ------------------------------------------------------------ +// Non-member functions. + +// Operator+ + +template +inline basic_string +operator+(const basic_string& x, + const basic_string& y) +{ + typedef basic_string str_t; + typedef typename str_t::reserve_t reserve_t; + reserve_t reserve; + str_t result(reserve, x.size() + y.size(), x.alloc()); + result.append(x); + result.append(y); + return result; +} + +template inline +BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) + operator+( + BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) mx + , const basic_string& y) +{ + mx += y; + return BOOST_CONTAINER_MOVE_NAMESPACE::move(mx); +} + +template inline +BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) + operator+(const basic_string& x, + BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) my) +{ + typedef typename basic_string::size_type size_type; + return my.replace(size_type(0), size_type(0), x); +} + +template +inline basic_string +operator+(const CharT* s, const basic_string& y) +{ + typedef basic_string str_t; + typedef typename str_t::reserve_t reserve_t; + reserve_t reserve; + const std::size_t n = Traits::length(s); + str_t result(reserve, n + y.size()); + result.append(s, s + n); + result.append(y); + return result; +} + +template inline +BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) +operator+(const CharT* s, + BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) my) +{ + typedef typename basic_string::size_type size_type; + return BOOST_CONTAINER_MOVE_NAMESPACE::move(my.get().replace(size_type(0), size_type(0), s)); +} + +template +inline basic_string +operator+(CharT c, const basic_string& y) +{ + typedef basic_string str_t; + typedef typename str_t::reserve_t reserve_t; + reserve_t reserve; + str_t result(reserve, 1 + y.size()); + result.push_back(c); + result.append(y); + return result; +} + +template inline +BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) +operator+(CharT c, + BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) my) +{ + typedef typename basic_string::size_type size_type; + return my.replace(size_type(0), size_type(0), &c, &c + 1); +} + +template +inline basic_string +operator+(const basic_string& x, const CharT* s) +{ + typedef basic_string str_t; + typedef typename str_t::reserve_t reserve_t; + reserve_t reserve; + const std::size_t n = Traits::length(s); + str_t result(reserve, x.size() + n, x.alloc()); + result.append(x); + result.append(s, s + n); + return result; +} + +template +BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) +operator+(BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) mx + , const CharT* s) +{ + mx += s; + return BOOST_CONTAINER_MOVE_NAMESPACE::move(mx); +} + +template +inline basic_string +operator+(const basic_string& x, const CharT c) +{ + typedef basic_string str_t; + typedef typename str_t::reserve_t reserve_t; + reserve_t reserve; + str_t result(reserve, x.size() + 1, x.alloc()); + result.append(x); + result.push_back(c); + return result; +} + +template +BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) +operator+( BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(basic_string, CharT, Traits, A) mx + , const CharT c) +{ + mx += c; + return BOOST_CONTAINER_MOVE_NAMESPACE::move(mx); +} + +// Operator== and operator!= + +template +inline bool +operator==(const basic_string& x, + const basic_string& y) +{ + return x.size() == y.size() && + Traits::compare(x.data(), y.data(), x.size()) == 0; +} + +template +inline bool +operator==(const CharT* s, const basic_string& y) +{ + std::size_t n = Traits::length(s); + return n == y.size() && Traits::compare(s, y.data(), n) == 0; +} + +template +inline bool +operator==(const basic_string& x, const CharT* s) +{ + std::size_t n = Traits::length(s); + return x.size() == n && Traits::compare(x.data(), s, n) == 0; +} + +template +inline bool +operator!=(const basic_string& x, + const basic_string& y) + { return !(x == y); } + +template +inline bool +operator!=(const CharT* s, const basic_string& y) + { return !(s == y); } + +template +inline bool +operator!=(const basic_string& x, const CharT* s) + { return !(x == s); } + + +// Operator< (and also >, <=, and >=). + +template +inline bool +operator<(const basic_string& x, const basic_string& y) +{ + return x.compare(y) < 0; +// return basic_string +// ::s_compare(x.begin(), x.end(), y.begin(), y.end()) < 0; +} + +template +inline bool +operator<(const CharT* s, const basic_string& y) +{ + return y.compare(s) > 0; +// std::size_t n = Traits::length(s); +// return basic_string +// ::s_compare(s, s + n, y.begin(), y.end()) < 0; +} + +template +inline bool +operator<(const basic_string& x, + const CharT* s) +{ + return x.compare(s) < 0; +// std::size_t n = Traits::length(s); +// return basic_string +// ::s_compare(x.begin(), x.end(), s, s + n) < 0; +} + +template +inline bool +operator>(const basic_string& x, + const basic_string& y) { + return y < x; +} + +template +inline bool +operator>(const CharT* s, const basic_string& y) { + return y < s; +} + +template +inline bool +operator>(const basic_string& x, const CharT* s) +{ + return s < x; +} + +template +inline bool +operator<=(const basic_string& x, + const basic_string& y) +{ + return !(y < x); +} + +template +inline bool +operator<=(const CharT* s, const basic_string& y) + { return !(y < s); } + +template +inline bool +operator<=(const basic_string& x, const CharT* s) + { return !(s < x); } + +template +inline bool +operator>=(const basic_string& x, + const basic_string& y) + { return !(x < y); } + +template +inline bool +operator>=(const CharT* s, const basic_string& y) + { return !(s < y); } + +template +inline bool +operator>=(const basic_string& x, const CharT* s) + { return !(x < s); } + +// Swap. +template +inline void swap(basic_string& x, basic_string& y) +{ x.swap(y); } + +/// @cond +// I/O. +namespace containers_detail { + +template +inline bool +string_fill(std::basic_ostream& os, + std::basic_streambuf* buf, + std::size_t n) +{ + CharT f = os.fill(); + std::size_t i; + bool ok = true; + + for (i = 0; i < n; i++) + ok = ok && !Traits::eq_int_type(buf->sputc(f), Traits::eof()); + return ok; +} + +} //namespace containers_detail { +/// @endcond + +template +std::basic_ostream& +operator<<(std::basic_ostream& os, const basic_string& s) +{ + typename std::basic_ostream::sentry sentry(os); + bool ok = false; + + if (sentry) { + ok = true; + std::size_t n = s.size(); + std::size_t pad_len = 0; + const bool left = (os.flags() & std::ios::left) != 0; + const std::size_t w = os.width(0); + std::basic_streambuf* buf = os.rdbuf(); + + if (w != 0 && n < w) + pad_len = w - n; + + if (!left) + ok = containers_detail::string_fill(os, buf, pad_len); + + ok = ok && + buf->sputn(s.data(), std::streamsize(n)) == std::streamsize(n); + + if (left) + ok = ok && containers_detail::string_fill(os, buf, pad_len); + } + + if (!ok) + os.setstate(std::ios_base::failbit); + + return os; +} + + +template +std::basic_istream& +operator>>(std::basic_istream& is, basic_string& s) +{ + typename std::basic_istream::sentry sentry(is); + + if (sentry) { + std::basic_streambuf* buf = is.rdbuf(); + const std::ctype& ctype = std::use_facet >(is.getloc()); + + s.clear(); + std::size_t n = is.width(0); + if (n == 0) + n = static_cast(-1); + else + s.reserve(n); + + while (n-- > 0) { + typename Traits::int_type c1 = buf->sbumpc(); + + if (Traits::eq_int_type(c1, Traits::eof())) { + is.setstate(std::ios_base::eofbit); + break; + } + else { + CharT c = Traits::to_char_type(c1); + + if (ctype.is(std::ctype::space, c)) { + if (Traits::eq_int_type(buf->sputbackc(c), Traits::eof())) + is.setstate(std::ios_base::failbit); + break; + } + else + s.push_back(c); + } + } + + // If we have read no characters, then set failbit. + if (s.size() == 0) + is.setstate(std::ios_base::failbit); + } + else + is.setstate(std::ios_base::failbit); + + return is; +} + +template +std::basic_istream& +getline(std::istream& is, basic_string& s,CharT delim) +{ + std::size_t nread = 0; + typename std::basic_istream::sentry sentry(is, true); + if (sentry) { + std::basic_streambuf* buf = is.rdbuf(); + s.clear(); + + while (nread < s.max_size()) { + int c1 = buf->sbumpc(); + if (Traits::eq_int_type(c1, Traits::eof())) { + is.setstate(std::ios_base::eofbit); + break; + } + else { + ++nread; + CharT c = Traits::to_char_type(c1); + if (!Traits::eq(c, delim)) + s.push_back(c); + else + break; // Character is extracted but not appended. + } + } + } + if (nread == 0 || nread >= s.max_size()) + is.setstate(std::ios_base::failbit); + + return is; +} + +template +inline std::basic_istream& +getline(std::basic_istream& is, basic_string& s) +{ + return getline(is, s, '\n'); +} + +template +inline std::size_t hash_value(basic_string, A> const& v) +{ + return hash_range(v.begin(), v.end()); +} + +}} + +/// @cond + +namespace boost { +/* +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value; +}; +*/ +} + +/// @endcond + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif // BOOST_CONTAINERS_STRING_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/container/vector.hpp b/utils/boost_idb/boost/interprocess/containers/container/vector.hpp new file mode 100644 index 00000000..71399a26 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/containers/container/vector.hpp @@ -0,0 +1,1936 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINERS_CONTAINERS_VECTOR_HPP +#define BOOST_CONTAINERS_CONTAINERS_VECTOR_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include "detail/config_begin.hpp" +#include INCLUDE_BOOST_CONTAINER_DETAIL_WORKAROUND_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALLOCATION_TYPE_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ITERATORS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ALGORITHMS_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_DESTROYERS_HPP +#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP +#include INCLUDE_BOOST_CONTAINER_MOVE_HPP +#include +#include INCLUDE_BOOST_CONTAINER_DETAIL_MPL_HPP +#include INCLUDE_BOOST_CONTAINER_DETAIL_ADVANCED_INSERT_INT_HPP + +namespace boost { +namespace container { + +/// @cond + +namespace containers_detail { + +//! Const vector_iterator used to iterate through a vector. +template +class vector_const_iterator + : public std::iterator::value_type + ,typename std::iterator_traits::difference_type + ,typename boost::pointer_to_other + ::value_type + >::type + ,const typename std::iterator_traits::value_type &> +{ + public: + typedef typename std::iterator_traits::value_type value_type; + typedef typename std::iterator_traits::difference_type difference_type; + typedef typename boost::pointer_to_other::type pointer; + typedef const value_type& reference; + + /// @cond + protected: + Pointer m_ptr; + + public: + Pointer get_ptr() const { return m_ptr; } + explicit vector_const_iterator(Pointer ptr) : m_ptr(ptr){} + /// @endcond + + public: + + //Constructors + vector_const_iterator() : m_ptr(0){} + + //Pointer like operators + reference operator*() const + { return *m_ptr; } + + const value_type * operator->() const + { return containers_detail::get_pointer(m_ptr); } + + reference operator[](difference_type off) const + { return m_ptr[off]; } + + //Increment / Decrement + vector_const_iterator& operator++() + { ++m_ptr; return *this; } + + vector_const_iterator operator++(int) + { Pointer tmp = m_ptr; ++*this; return vector_const_iterator(tmp); } + + vector_const_iterator& operator--() + { --m_ptr; return *this; } + + vector_const_iterator operator--(int) + { Pointer tmp = m_ptr; --*this; return vector_const_iterator(tmp); } + + //Arithmetic + vector_const_iterator& operator+=(difference_type off) + { m_ptr += off; return *this; } + + vector_const_iterator operator+(difference_type off) const + { return vector_const_iterator(m_ptr+off); } + + friend vector_const_iterator operator+(difference_type off, const vector_const_iterator& right) + { return vector_const_iterator(off + right.m_ptr); } + + vector_const_iterator& operator-=(difference_type off) + { m_ptr -= off; return *this; } + + vector_const_iterator operator-(difference_type off) const + { return vector_const_iterator(m_ptr-off); } + + difference_type operator-(const vector_const_iterator& right) const + { return m_ptr - right.m_ptr; } + + //Comparison operators + bool operator== (const vector_const_iterator& r) const + { return m_ptr == r.m_ptr; } + + bool operator!= (const vector_const_iterator& r) const + { return m_ptr != r.m_ptr; } + + bool operator< (const vector_const_iterator& r) const + { return m_ptr < r.m_ptr; } + + bool operator<= (const vector_const_iterator& r) const + { return m_ptr <= r.m_ptr; } + + bool operator> (const vector_const_iterator& r) const + { return m_ptr > r.m_ptr; } + + bool operator>= (const vector_const_iterator& r) const + { return m_ptr >= r.m_ptr; } +}; + +//! Iterator used to iterate through a vector +template +class vector_iterator + : public vector_const_iterator +{ + public: + explicit vector_iterator(Pointer ptr) + : vector_const_iterator(ptr) + {} + + public: + typedef typename std::iterator_traits::value_type value_type; + typedef typename vector_const_iterator::difference_type difference_type; + typedef Pointer pointer; + typedef value_type& reference; + + //Constructors + vector_iterator() + {} + + //Pointer like operators + reference operator*() const + { return *this->m_ptr; } + + value_type* operator->() const + { return containers_detail::get_pointer(this->m_ptr); } + + reference operator[](difference_type off) const + { return this->m_ptr[off]; } + + //Increment / Decrement + vector_iterator& operator++() + { ++this->m_ptr; return *this; } + + vector_iterator operator++(int) + { pointer tmp = this->m_ptr; ++*this; return vector_iterator(tmp); } + + vector_iterator& operator--() + { --this->m_ptr; return *this; } + + vector_iterator operator--(int) + { vector_iterator tmp = *this; --*this; return vector_iterator(tmp); } + + // Arithmetic + vector_iterator& operator+=(difference_type off) + { this->m_ptr += off; return *this; } + + vector_iterator operator+(difference_type off) const + { return vector_iterator(this->m_ptr+off); } + + friend vector_iterator operator+(difference_type off, const vector_iterator& right) + { return vector_iterator(off + right.m_ptr); } + + vector_iterator& operator-=(difference_type off) + { this->m_ptr -= off; return *this; } + + vector_iterator operator-(difference_type off) const + { return vector_iterator(this->m_ptr-off); } + + difference_type operator-(const vector_const_iterator& right) const + { return static_cast&>(*this) - right; } +}; + +template +struct vector_value_traits +{ + typedef T value_type; + typedef A allocator_type; + static const bool trivial_dctr = boost::has_trivial_destructor::value; + static const bool trivial_dctr_after_move = false; + //::boost::has_trivial_destructor_after_move::value || trivial_dctr; + static const bool trivial_copy = has_trivial_copy::value; + static const bool nothrow_copy = has_nothrow_copy::value; + static const bool trivial_assign = has_trivial_assign::value; + static const bool nothrow_assign = has_nothrow_assign::value; + + //This is the anti-exception array destructor + //to deallocate values already constructed + typedef typename containers_detail::if_c + + ,containers_detail::scoped_destructor_n + >::type OldArrayDestructor; + //This is the anti-exception array destructor + //to destroy objects created with copy construction + typedef typename containers_detail::if_c + + ,containers_detail::scoped_destructor_n + >::type UCopiedArrayDestructor; + //This is the anti-exception array deallocator + typedef typename containers_detail::if_c + + ,containers_detail::scoped_array_deallocator + >::type UCopiedArrayDeallocator; +}; + +//!This struct deallocates and allocated memory +template +struct vector_alloc_holder +{ + typedef typename A::pointer pointer; + typedef typename A::size_type size_type; + typedef typename A::value_type value_type; + typedef vector_value_traits value_traits; + + //Constructor, does not throw + vector_alloc_holder(const A &a) + : members_(a) + {} + + //Destructor + ~vector_alloc_holder() + { + this->prot_destroy_all(); + this->prot_deallocate(); + } + + typedef containers_detail::integral_constant allocator_v1; + typedef containers_detail::integral_constant allocator_v2; + typedef containers_detail::integral_constant::value> alloc_version; + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, const pointer &reuse = 0) + { + return allocation_command(command, limit_size, preferred_size, + received_size, reuse, alloc_version()); + } + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, + const pointer &reuse, + allocator_v1) + { + (void)limit_size; + (void)reuse; + if(!(command & allocate_new)) + return std::pair(pointer(0), false); + received_size = preferred_size; + return std::make_pair(this->alloc().allocate(received_size), false); + } + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, + const pointer &reuse, + allocator_v2) + { + return this->alloc().allocation_command + (command, limit_size, preferred_size, received_size, reuse); + } + + size_type next_capacity(size_type additional_objects) const + { return get_next_capacity(this->alloc().max_size(), this->members_.m_capacity, additional_objects); } + + struct members_holder + : public A + { + private: + members_holder(const members_holder&); + + public: + members_holder(const A &alloc) + : A(alloc), m_start(0), m_size(0), m_capacity(0) + {} + + pointer m_start; + size_type m_size; + size_type m_capacity; + } members_; + + A &alloc() + { return members_; } + + const A &alloc() const + { return members_; } + + protected: + void prot_deallocate() + { + if(!this->members_.m_capacity) return; + this->alloc().deallocate(this->members_.m_start, this->members_.m_capacity); + this->members_.m_start = 0; + this->members_.m_size = 0; + this->members_.m_capacity = 0; + } + + void destroy(value_type* p) + { + if(!value_traits::trivial_dctr) + containers_detail::get_pointer(p)->~value_type(); + } + + void destroy_n(value_type* p, size_type n) + { + if(!value_traits::trivial_dctr) + for(; n--; ++p) p->~value_type(); + } + + void prot_destroy_all() + { + this->destroy_n(containers_detail::get_pointer(this->members_.m_start), this->members_.m_size); + this->members_.m_size = 0; + } +}; + +} //namespace containers_detail { +/// @endcond + +//! \class vector +//! A vector is a sequence that supports random access to elements, constant +//! time insertion and removal of elements at the end, and linear time insertion +//! and removal of elements at the beginning or in the middle. The number of +//! elements in a vector may vary dynamically; memory management is automatic. +//! boost::container::vector is similar to std::vector but it's compatible +//! with shared memory and memory mapped files. +template +class vector : private containers_detail::vector_alloc_holder +{ + /// @cond + typedef vector self_t; + typedef containers_detail::vector_alloc_holder base_t; + typedef typename containers_detail:: + move_const_ref_type::type insert_const_ref_type; + /// @endcond + public: + //! The type of object, T, stored in the vector + typedef T value_type; + //! Pointer to T + typedef typename A::pointer pointer; + //! Const pointer to T + typedef typename A::const_pointer const_pointer; + //! Reference to T + typedef typename A::reference reference; + //! Const reference to T + typedef typename A::const_reference const_reference; + //! An unsigned integral type + typedef typename A::size_type size_type; + //! A signed integral type + typedef typename A::difference_type difference_type; + //! The allocator type + typedef A allocator_type; + //! The random access iterator + typedef containers_detail::vector_iterator iterator; + //! The random access const_iterator + typedef containers_detail::vector_const_iterator const_iterator; + + //! Iterator used to iterate backwards through a vector. + typedef std::reverse_iterator + reverse_iterator; + //! Const iterator used to iterate backwards through a vector. + typedef std::reverse_iterator + const_reverse_iterator; + //! The stored allocator type + typedef allocator_type stored_allocator_type; + + /// @cond + private: + BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(vector) + typedef containers_detail::advanced_insert_aux_int advanced_insert_aux_int_t; + typedef containers_detail::vector_value_traits value_traits; + + typedef typename base_t::allocator_v1 allocator_v1; + typedef typename base_t::allocator_v2 allocator_v2; + typedef typename base_t::alloc_version alloc_version; + + typedef constant_iterator cvalue_iterator; + typedef repeat_iterator repeat_it; + typedef BOOST_CONTAINER_MOVE_NAMESPACE::move_iterator repeat_move_it; + /// @endcond + + public: + + //! Effects: Constructs a vector taking the allocator as parameter. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + explicit vector(const A& a = A()) + : base_t(a) + {} + + //! Effects: Constructs a vector that will use a copy of allocator a + //! and inserts n default contructed values. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's default or copy constructor throws. + //! + //! Complexity: Linear to n. + explicit vector(size_type n) + : base_t(allocator_type()) + { this->resize(n); } + + //! Effects: Constructs a vector that will use a copy of allocator a + //! and inserts n copies of value. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's default or copy constructor throws. + //! + //! Complexity: Linear to n. + vector(size_type n, const T& value, const allocator_type& a = allocator_type()) + : base_t(a) + { this->insert(this->cend(), n, value); } + + //! Effects: Copy constructs a vector. + //! + //! Postcondition: x == *this. + //! + //! Complexity: Linear to the elements x contains. + vector(const vector& x) + : base_t(static_cast(x).alloc()) + { *this = x; } + + //! Effects: Move constructor. Moves mx's resources to *this. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Constant. + vector(BOOST_MOVE_MACRO_RV_REF(vector) mx) + : base_t(static_cast(mx).alloc()) + { this->swap(mx); } + + //! Effects: Constructs a vector that will use a copy of allocator a + //! and inserts a copy of the range [first, last) in the vector. + //! + //! Throws: If allocator_type's default constructor or copy constructor + //! throws or T's constructor taking an dereferenced InIt throws. + //! + //! Complexity: Linear to the range [first, last). + template + vector(InIt first, InIt last, const allocator_type& a = allocator_type()) + : base_t(a) + { this->assign(first, last); } + + //! Effects: Destroys the vector. All stored values are destroyed + //! and used memory is deallocated. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements. + ~vector() + {} //vector_alloc_holder clears the data + + //! Effects: Returns an iterator to the first element contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator begin() + { return iterator(this->members_.m_start); } + + //! Effects: Returns a const_iterator to the first element contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator begin() const + { return const_iterator(this->members_.m_start); } + + //! Effects: Returns an iterator to the end of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + iterator end() + { return iterator(this->members_.m_start + this->members_.m_size); } + + //! Effects: Returns a const_iterator to the end of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator end() const + { return this->cend(); } + + //! Effects: Returns a reverse_iterator pointing to the beginning + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rbegin() + { return reverse_iterator(this->end()); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rbegin()const + { return this->crbegin(); } + + //! Effects: Returns a reverse_iterator pointing to the end + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reverse_iterator rend() + { return reverse_iterator(this->begin()); } + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator rend() const + { return this->crend(); } + + //! Effects: Returns a const_iterator to the first element contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const + { return const_iterator(this->members_.m_start); } + + //! Effects: Returns a const_iterator to the end of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const + { return const_iterator(this->members_.m_start + this->members_.m_size); } + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin()const + { return const_reverse_iterator(this->end());} + + //! Effects: Returns a const_reverse_iterator pointing to the end + //! of the reversed vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crend() const + { return const_reverse_iterator(this->begin()); } + + //! Requires: !empty() + //! + //! Effects: Returns a reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference front() + { return *this->members_.m_start; } + + //! Requires: !empty() + //! + //! Effects: Returns a const reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference front() const + { return *this->members_.m_start; } + + //! Requires: !empty() + //! + //! Effects: Returns a reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference back() + { return this->members_.m_start[this->members_.m_size - 1]; } + + //! Effects: Returns a const reference to the first element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference back() const + { return this->members_.m_start[this->members_.m_size - 1]; } + + //! Returns: A pointer such that [data(),data() + size()) is a valid range. + //! For a non-empty vector, data() == &front(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + pointer data() + { return this->members_.m_start; } + + //! Returns: A pointer such that [data(),data() + size()) is a valid range. + //! For a non-empty vector, data() == &front(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_pointer data() const + { return this->members_.m_start; } + + //! Effects: Returns the number of the elements contained in the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type size() const + { return this->members_.m_size; } + + //! Effects: Returns the largest possible size of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type max_size() const + { return this->alloc().max_size(); } + + //! Effects: Number of elements for which memory has been allocated. + //! capacity() is always greater than or equal to size(). + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + size_type capacity() const + { return this->members_.m_capacity; } + + //! Effects: Returns true if the vector contains no elements. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + bool empty() const + { return !this->members_.m_size; } + + //! Requires: size() < n. + //! + //! Effects: Returns a reference to the nth element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + reference operator[](size_type n) + { return this->members_.m_start[n]; } + + //! Requires: size() < n. + //! + //! Effects: Returns a const reference to the nth element + //! from the beginning of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reference operator[](size_type n) const + { return this->members_.m_start[n]; } + + //! Requires: size() < n. + //! + //! Effects: Returns a reference to the nth element + //! from the beginning of the container. + //! + //! Throws: std::range_error if n >= size() + //! + //! Complexity: Constant. + reference at(size_type n) + { this->priv_check_range(n); return this->members_.m_start[n]; } + + //! Requires: size() < n. + //! + //! Effects: Returns a const reference to the nth element + //! from the beginning of the container. + //! + //! Throws: std::range_error if n >= size() + //! + //! Complexity: Constant. + const_reference at(size_type n) const + { this->priv_check_range(n); return this->members_.m_start[n]; } + + //! Effects: Returns a copy of the internal allocator. + //! + //! Throws: If allocator's copy constructor throws. + //! + //! Complexity: Constant. + allocator_type get_allocator() const + { return this->alloc(); } + + const stored_allocator_type &get_stored_allocator() const + { return this->alloc(); } + + stored_allocator_type &get_stored_allocator() + { return this->alloc(); } + + //! Effects: If n is less than or equal to capacity(), this call has no + //! effect. Otherwise, it is a request for allocation of additional memory. + //! If the request is successful, then capacity() is greater than or equal to + //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. + //! + //! Throws: If memory allocation allocation throws or T's copy constructor throws. + void reserve(size_type new_cap) + { + if (this->capacity() < new_cap){ + //There is not enough memory, allocate a new + //buffer or expand the old one. + bool same_buffer_start; + size_type real_cap = 0; + std::pair ret = + this->allocation_command + (allocate_new | expand_fwd | expand_bwd, + new_cap, new_cap, real_cap, this->members_.m_start); + + //Check for forward expansion + same_buffer_start = ret.second && this->members_.m_start == ret.first; + if(same_buffer_start){ + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_expand_fwd; + #endif + this->members_.m_capacity = real_cap; + } + + //If there is no forward expansion, move objects + else{ + //We will reuse insert code, so create a dummy input iterator + T *dummy_it(containers_detail::get_pointer(this->members_.m_start)); + containers_detail::advanced_insert_aux_proxy, T*> + proxy(::BOOST_CONTAINER_MOVE_NAMESPACE::make_move_iterator(dummy_it), ::BOOST_CONTAINER_MOVE_NAMESPACE::make_move_iterator(dummy_it)); + //Backwards (and possibly forward) expansion + if(ret.second){ + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_expand_bwd; + #endif + this->priv_range_insert_expand_backwards + ( containers_detail::get_pointer(ret.first) + , real_cap + , containers_detail::get_pointer(this->members_.m_start) + , 0 + , proxy); + } + //New buffer + else{ + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_alloc; + #endif + this->priv_range_insert_new_allocation + ( containers_detail::get_pointer(ret.first) + , real_cap + , containers_detail::get_pointer(this->members_.m_start) + , 0 + , proxy); + } + } + } + } + + //! Effects: Makes *this contain the same elements as x. + //! + //! Postcondition: this->size() == x.size(). *this contains a copy + //! of each of x's elements. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to the number of elements in x. + vector& operator=(BOOST_MOVE_MACRO_COPY_ASSIGN_REF(vector) x) + { + if (&x != this){ + this->assign(x.members_.m_start, x.members_.m_start + x.members_.m_size); + } + return *this; + } + + //! Effects: Move assignment. All mx's values are transferred to *this. + //! + //! Postcondition: x.empty(). *this contains a the elements x had + //! before the function. + //! + //! Throws: If allocator_type's copy constructor throws. + //! + //! Complexity: Linear. + vector& operator=(BOOST_MOVE_MACRO_RV_REF(vector) x) + { + if (&x != this){ + this->swap(x); + x.clear(); + } + return *this; + } + + //! Effects: Assigns the n copies of val to *this. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n. + void assign(size_type n, const value_type& val) + { this->assign(cvalue_iterator(val, n), cvalue_iterator()); } + + //! Effects: Assigns the the range [first, last) to *this. + //! + //! Throws: If memory allocation throws or + //! T's constructor from dereferencing InpIt throws. + //! + //! Complexity: Linear to n. + template + void assign(InIt first, InIt last) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_assign_dispatch(first, last, Result()); + } + + //! Effects: Inserts a copy of x at the end of the vector. + //! + //! Throws: If memory allocation throws or + //! T's copy constructor throws. + //! + //! Complexity: Amortized constant time. + void push_back(insert_const_ref_type x) + { return priv_push_back(x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + void push_back(T &x) { push_back(const_cast(x)); } + + template + void push_back(const U &u, typename containers_detail::enable_if_c + ::value && + !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value + >::type* =0) + { return priv_push_back(u); } + #endif + + //! Effects: Constructs a new element in the end of the vector + //! and moves the resources of mx to this new element. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: Amortized constant time. + void push_back(BOOST_MOVE_MACRO_RV_REF(T) x) + { + if (this->members_.m_size < this->members_.m_capacity){ + //There is more memory, just construct a new object at the end + new((void*)containers_detail::get_pointer(this->members_.m_start + this->members_.m_size))value_type(BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); + ++this->members_.m_size; + } + else{ + this->insert(this->cend(), BOOST_CONTAINER_MOVE_NAMESPACE::move(x)); + } + } + + #if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... in the end of the vector. + //! + //! Throws: If memory allocation throws or the in-place constructor throws. + //! + //! Complexity: Amortized constant time. + template + void emplace_back(Args &&...args) + { + T* back_pos = containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size; + if (this->members_.m_size < this->members_.m_capacity){ + //There is more memory, just construct a new object at the end + new((void*)(back_pos))value_type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + ++this->members_.m_size; + } + else{ + typedef containers_detail::advanced_insert_aux_emplace type; + type &&proxy = type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + priv_range_insert(back_pos, 1, proxy); + } + } + + //! Requires: position must be a valid iterator of *this. + //! + //! Effects: Inserts an object of type T constructed with + //! std::forward(args)... before position + //! + //! Throws: If memory allocation throws or the in-place constructor throws. + //! + //! Complexity: If position is end(), amortized constant time + //! Linear time otherwise. + template + iterator emplace(const_iterator position, Args && ...args) + { + //Just call more general insert(pos, size, value) and return iterator + size_type pos_n = position - cbegin(); + typedef containers_detail::advanced_insert_aux_emplace type; + type &&proxy = type(BOOST_CONTAINER_MOVE_NAMESPACE::forward(args)...); + priv_range_insert(position.get_ptr(), 1, proxy); + return iterator(this->members_.m_start + pos_n); + } + + #else + + void emplace_back() + { + T* back_pos = containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size; + if (this->members_.m_size < this->members_.m_capacity){ + //There is more memory, just construct a new object at the end + new((void*)(back_pos))value_type(); + ++this->members_.m_size; + } + else{ + containers_detail::advanced_insert_aux_emplace proxy; + priv_range_insert(back_pos, 1, proxy); + } + } + + iterator emplace(const_iterator position) + { + size_type pos_n = position - cbegin(); + containers_detail::advanced_insert_aux_emplace proxy; + priv_range_insert(containers_detail::get_pointer(position.get_ptr()), 1, proxy); + return iterator(this->members_.m_start + pos_n); + } + + #define BOOST_PP_LOCAL_MACRO(n) \ + template \ + void emplace_back(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + T* back_pos = containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size; \ + if (this->members_.m_size < this->members_.m_capacity){ \ + new((void*)(back_pos))value_type \ + (BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + ++this->members_.m_size; \ + } \ + else{ \ + containers_detail::BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + \ + proxy(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + priv_range_insert(back_pos, 1, proxy); \ + } \ + } \ + \ + template \ + iterator emplace(const_iterator pos, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \ + { \ + size_type pos_n = pos - cbegin(); \ + containers_detail::BOOST_PP_CAT(BOOST_PP_CAT(advanced_insert_aux_emplace, n), arg) \ + \ + proxy(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); \ + priv_range_insert(containers_detail::get_pointer(pos.get_ptr()), 1, proxy); \ + return iterator(this->members_.m_start + pos_n); \ + } \ + //! + #define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS) + #include BOOST_PP_LOCAL_ITERATE() + + #endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING + + //! Effects: Swaps the contents of *this and x. + //! If this->allocator_type() != x.allocator_type() + //! allocators are also swapped. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + void swap(vector& x) + { + allocator_type &this_al = this->alloc(), &other_al = x.alloc(); + //Just swap internals + containers_detail::do_swap(this->members_.m_start, x.members_.m_start); + containers_detail::do_swap(this->members_.m_size, x.members_.m_size); + containers_detail::do_swap(this->members_.m_capacity, x.members_.m_capacity); + + if (this_al != other_al){ + containers_detail::do_swap(this_al, other_al); + } + } + + //! Requires: position must be a valid iterator of *this. + //! + //! Effects: Insert a copy of x before position. + //! + //! Throws: If memory allocation throws or x's copy constructor throws. + //! + //! Complexity: If position is end(), amortized constant time + //! Linear time otherwise. + iterator insert(const_iterator position, insert_const_ref_type x) + { return this->priv_insert(position, x); } + + #if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + iterator insert(const_iterator position, T &x) { return this->insert(position, const_cast(x)); } + + template + iterator insert(const_iterator position, const U &u, typename containers_detail::enable_if_c::value && !::BOOST_CONTAINER_MOVE_NAMESPACE::is_movable::value >::type* =0) + { return this->priv_insert(position, u); } + #endif + + //! Requires: position must be a valid iterator of *this. + //! + //! Effects: Insert a new element before position with mx's resources. + //! + //! Throws: If memory allocation throws. + //! + //! Complexity: If position is end(), amortized constant time + //! Linear time otherwise. + iterator insert(const_iterator position, BOOST_MOVE_MACRO_RV_REF(T) x) + { + //Just call more general insert(pos, size, value) and return iterator + size_type pos_n = position - cbegin(); + this->insert(position + ,repeat_move_it(repeat_it(x, 1)) + ,repeat_move_it(repeat_it())); + return iterator(this->members_.m_start + pos_n); + } + + //! Requires: pos must be a valid iterator of *this. + //! + //! Effects: Insert a copy of the [first, last) range before pos. + //! + //! Throws: If memory allocation throws, T's constructor from a + //! dereferenced InpIt throws or T's copy constructor throws. + //! + //! Complexity: Linear to std::distance [first, last). + template + void insert(const_iterator pos, InIt first, InIt last) + { + //Dispatch depending on integer/iterator + const bool aux_boolean = containers_detail::is_convertible::value; + typedef containers_detail::bool_ Result; + this->priv_insert_dispatch(pos, first, last, Result()); + } + + //! Requires: pos must be a valid iterator of *this. + //! + //! Effects: Insert n copies of x before pos. + //! + //! Throws: If memory allocation throws or T's copy constructor throws. + //! + //! Complexity: Linear to n. + void insert(const_iterator p, size_type n, const T& x) + { this->insert(p, cvalue_iterator(x, n), cvalue_iterator()); } + + //! Effects: Removes the last element from the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant time. + void pop_back() + { + //Destroy last element + --this->members_.m_size; + this->destroy(containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size); + } + + //! Effects: Erases the element at position pos. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the elements between pos and the + //! last element. Constant if pos is the first or the last element. + iterator erase(const_iterator position) + { + T *pos = containers_detail::get_pointer(position.get_ptr()); + T *beg = containers_detail::get_pointer(this->members_.m_start); + BOOST_CONTAINER_MOVE_NAMESPACE::move(pos + 1, beg + this->members_.m_size, pos); + --this->members_.m_size; + //Destroy last element + base_t::destroy(containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size); + return iterator(position.get_ptr()); + } + + //! Effects: Erases the elements pointed by [first, last). + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the distance between first and last. + iterator erase(const_iterator first, const_iterator last) + { + if (first != last){ // worth doing, copy down over hole + T* end_pos = containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size; + T* ptr = containers_detail::get_pointer(BOOST_CONTAINER_MOVE_NAMESPACE::move + (containers_detail::get_pointer(last.get_ptr()) + ,end_pos + ,containers_detail::get_pointer(first.get_ptr()) + )); + size_type destroyed = (end_pos - ptr); + this->destroy_n(ptr, destroyed); + this->members_.m_size -= destroyed; + } + return iterator(first.get_ptr()); + } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are copy constructed from x. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type new_size, const T& x) + { + pointer finish = this->members_.m_start + this->members_.m_size; + if (new_size < size()){ + //Destroy last elements + this->erase(const_iterator(this->members_.m_start + new_size), this->end()); + } + else{ + //Insert new elements at the end + this->insert(const_iterator(finish), new_size - this->size(), x); + } + } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are default constructed. + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to the difference between size() and new_size. + void resize(size_type new_size) + { + if (new_size < this->size()){ + //Destroy last elements + this->erase(const_iterator(this->members_.m_start + new_size), this->end()); + } + else{ + size_type n = new_size - this->size(); + this->reserve(new_size); + containers_detail::default_construct_aux_proxy proxy(n); + priv_range_insert(this->cend().get_ptr(), n, proxy); + } + } + + //! Effects: Erases all the elements of the vector. + //! + //! Throws: Nothing. + //! + //! Complexity: Linear to the number of elements in the vector. + void clear() + { this->prot_destroy_all(); } + + //! Effects: Tries to deallocate the excess of memory created + //! with previous allocations. The size of the vector is unchanged + //! + //! Throws: If memory allocation throws, or T's copy constructor throws. + //! + //! Complexity: Linear to size(). + void shrink_to_fit() + { priv_shrink_to_fit(alloc_version()); } + + /// @cond + + private: + iterator priv_insert(const_iterator position, const T &x) + { + //Just call more general insert(pos, size, value) and return iterator + size_type pos_n = position - cbegin(); + this->insert(position, (size_type)1, x); + return iterator(this->members_.m_start + pos_n); + } + + void priv_push_back(const T &x) + { + if (this->members_.m_size < this->members_.m_capacity){ + //There is more memory, just construct a new object at the end + new((void*)(containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size))value_type(x); + ++this->members_.m_size; + } + else{ + this->insert(this->cend(), x); + } + } + + void priv_shrink_to_fit(allocator_v1) + { + if(this->members_.m_capacity){ + if(!size()){ + this->prot_deallocate(); + } + else{ + //This would not work with stateful allocators + vector(*this).swap(*this); + } + } + } + + void priv_shrink_to_fit(allocator_v2) + { + if(this->members_.m_capacity){ + if(!size()){ + this->prot_deallocate(); + } + else{ + size_type received_size; + if(this->alloc().allocation_command + ( shrink_in_place | nothrow_allocation + , this->capacity(), this->size() + , received_size, this->members_.m_start).first){ + this->members_.m_capacity = received_size; + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_shrink; + #endif + } + } + } + } + + template + void priv_range_insert(pointer pos, FwdIt first, FwdIt last, std::forward_iterator_tag) + { + if(first != last){ + const size_type n = std::distance(first, last); + containers_detail::advanced_insert_aux_proxy proxy(first, last); + priv_range_insert(pos, n, proxy); + } + } + + void priv_range_insert(pointer pos, const size_type n, advanced_insert_aux_int_t &interf) + { + //Check if we have enough memory or try to expand current memory + size_type remaining = this->members_.m_capacity - this->members_.m_size; + bool same_buffer_start; + std::pair ret; + size_type real_cap = this->members_.m_capacity; + + //Check if we already have room + if (n <= remaining){ + same_buffer_start = true; + } + else{ + //There is not enough memory, allocate a new + //buffer or expand the old one. + size_type new_cap = this->next_capacity(n); + ret = this->allocation_command + (allocate_new | expand_fwd | expand_bwd, + this->members_.m_size + n, new_cap, real_cap, this->members_.m_start); + + //Check for forward expansion + same_buffer_start = ret.second && this->members_.m_start == ret.first; + if(same_buffer_start){ + this->members_.m_capacity = real_cap; + } + } + + //If we had room or we have expanded forward + if (same_buffer_start){ + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_expand_fwd; + #endif + this->priv_range_insert_expand_forward + (containers_detail::get_pointer(pos), n, interf); + } + //Backwards (and possibly forward) expansion + else if(ret.second){ + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_expand_bwd; + #endif + this->priv_range_insert_expand_backwards + ( containers_detail::get_pointer(ret.first) + , real_cap + , containers_detail::get_pointer(pos) + , n + , interf); + } + //New buffer + else{ + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + ++this->num_alloc; + #endif + this->priv_range_insert_new_allocation + ( containers_detail::get_pointer(ret.first) + , real_cap + , containers_detail::get_pointer(pos) + , n + , interf); + } + } + + void priv_range_insert_expand_forward(T* pos, size_type n, advanced_insert_aux_int_t &interf) + { + //n can't be 0, because there is nothing to do in that case + if(!n) return; + //There is enough memory + T* old_finish = containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size; + const size_type elems_after = old_finish - pos; + + if (elems_after > n){ + //New elements can be just copied. + //Move to uninitialized memory last objects + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(old_finish - n, old_finish, old_finish); + this->members_.m_size += n; + //Copy previous to last objects to the initialized end + BOOST_CONTAINER_MOVE_NAMESPACE::move_backward(pos, old_finish - n, old_finish); + //Insert new objects in the pos + interf.copy_all_to(pos); + } + else { + //The new elements don't fit in the [pos, end()) range. Copy + //to the beginning of the unallocated zone the last new elements. + interf.uninitialized_copy_some_and_update(old_finish, elems_after, false); + this->members_.m_size += n - elems_after; + //Copy old [pos, end()) elements to the uninitialized memory + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move + ( pos, old_finish, containers_detail::get_pointer(this->members_.m_start) + this->members_.m_size); + this->members_.m_size += elems_after; + //Copy first new elements in pos + interf.copy_all_to(pos); + } + } + + void priv_range_insert_new_allocation + (T* new_start, size_type new_cap, T* pos, size_type n, advanced_insert_aux_int_t &interf) + { + //n can be zero, if we want to reallocate! + T *new_finish = new_start; + T *old_finish; + //Anti-exception rollbacks + typename value_traits::UCopiedArrayDeallocator scoped_alloc(new_start, this->alloc(), new_cap); + typename value_traits::UCopiedArrayDestructor constructed_values_destroyer(new_start, 0u); + + //Initialize with [begin(), pos) old buffer + //the start of the new buffer + T *old_buffer = containers_detail::get_pointer(this->members_.m_start); + if(old_buffer){ + new_finish = ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move + (containers_detail::get_pointer(this->members_.m_start), pos, old_finish = new_finish); + constructed_values_destroyer.increment_size(new_finish - old_finish); + } + //Initialize new objects, starting from previous point + interf.uninitialized_copy_all_to(old_finish = new_finish); + new_finish += n; + constructed_values_destroyer.increment_size(new_finish - old_finish); + //Initialize from the rest of the old buffer, + //starting from previous point + if(old_buffer){ + new_finish = ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move + (pos, old_buffer + this->members_.m_size, new_finish); + //Destroy and deallocate old elements + //If there is allocated memory, destroy and deallocate + if(!value_traits::trivial_dctr_after_move) + this->destroy_n(old_buffer, this->members_.m_size); + this->alloc().deallocate(this->members_.m_start, this->members_.m_capacity); + } + this->members_.m_start = new_start; + this->members_.m_size = new_finish - new_start; + this->members_.m_capacity = new_cap; + //All construction successful, disable rollbacks + constructed_values_destroyer.release(); + scoped_alloc.release(); + } + + void priv_range_insert_expand_backwards + (T* new_start, size_type new_capacity, + T* pos, const size_type n, advanced_insert_aux_int_t &interf) + { + //n can be zero to just expand capacity + //Backup old data + T* old_start = containers_detail::get_pointer(this->members_.m_start); + T* old_finish = old_start + this->members_.m_size; + size_type old_size = this->members_.m_size; + + //We can have 8 possibilities: + const size_type elemsbefore = (size_type)(pos - old_start); + const size_type s_before = (size_type)(old_start - new_start); + + //Update the vector buffer information to a safe state + this->members_.m_start = new_start; + this->members_.m_capacity = new_capacity; + this->members_.m_size = 0; + + //If anything goes wrong, this object will destroy + //all the old objects to fulfill previous vector state + typename value_traits::OldArrayDestructor old_values_destroyer(old_start, old_size); + //Check if s_before is big enough to hold the beginning of old data + new data + if(difference_type(s_before) >= difference_type(elemsbefore + n)){ + //Copy first old values before pos, after that the new objects + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(old_start, pos, new_start); + this->members_.m_size = elemsbefore; + interf.uninitialized_copy_all_to(new_start + elemsbefore); + this->members_.m_size += n; + //Check if s_before is so big that even copying the old data + new data + //there is a gap between the new data and the old data + if(s_before >= (old_size + n)){ + //Old situation: + // _________________________________________________________ + //| raw_mem | old_begin | old_end | + //| __________________________________|___________|_________| + // + //New situation: + // _________________________________________________________ + //| old_begin | new | old_end | raw_mem | + //|___________|__________|_________|________________________| + // + //Now initialize the rest of memory with the last old values + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move + (pos, old_finish, new_start + elemsbefore + n); + //All new elements correctly constructed, avoid new element destruction + this->members_.m_size = old_size + n; + //Old values destroyed automatically with "old_values_destroyer" + //when "old_values_destroyer" goes out of scope unless the have trivial + //destructor after move. + if(value_traits::trivial_dctr_after_move) + old_values_destroyer.release(); + } + //s_before is so big that divides old_end + else{ + //Old situation: + // __________________________________________________ + //| raw_mem | old_begin | old_end | + //| ___________________________|___________|_________| + // + //New situation: + // __________________________________________________ + //| old_begin | new | old_end | raw_mem | + //|___________|__________|_________|_________________| + // + //Now initialize the rest of memory with the last old values + //All new elements correctly constructed, avoid new element destruction + size_type raw_gap = s_before - (elemsbefore + n); + //Now initialize the rest of s_before memory with the + //first of elements after new values + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(pos, pos + raw_gap, new_start + elemsbefore + n); + //Update size since we have a contiguous buffer + this->members_.m_size = old_size + s_before; + //All new elements correctly constructed, avoid old element destruction + old_values_destroyer.release(); + //Now copy remaining last objects in the old buffer begin + T *to_destroy = BOOST_CONTAINER_MOVE_NAMESPACE::move(pos + raw_gap, old_finish, old_start); + //Now destroy redundant elements except if they were moved and + //they have trivial destructor after move + size_type n_destroy = old_finish - to_destroy; + if(!value_traits::trivial_dctr_after_move) + this->destroy_n(to_destroy, n_destroy); + this->members_.m_size -= n_destroy; + } + } + else{ + //Check if we have to do the insertion in two phases + //since maybe s_before is not big enough and + //the buffer was expanded both sides + // + //Old situation: + // _________________________________________________ + //| raw_mem | old_begin + old_end | raw_mem | + //|_________|_____________________|_________________| + // + //New situation with do_after: + // _________________________________________________ + //| old_begin + new + old_end | raw_mem | + //|___________________________________|_____________| + // + //New without do_after: + // _________________________________________________ + //| old_begin + new + old_end | raw_mem | + //|____________________________|____________________| + // + bool do_after = n > s_before; + + //Now we can have two situations: the raw_mem of the + //beginning divides the old_begin, or the new elements: + if (s_before <= elemsbefore) { + //The raw memory divides the old_begin group: + // + //If we need two phase construction (do_after) + //new group is divided in new = new_beg + new_end groups + //In this phase only new_beg will be inserted + // + //Old situation: + // _________________________________________________ + //| raw_mem | old_begin | old_end | raw_mem | + //|_________|___________|_________|_________________| + // + //New situation with do_after(1): + //This is not definitive situation, the second phase + //will include + // _________________________________________________ + //| old_begin | new_beg | old_end | raw_mem | + //|___________|_________|_________|_________________| + // + //New situation without do_after: + // _________________________________________________ + //| old_begin | new | old_end | raw_mem | + //|___________|_____|_________|_____________________| + // + //Copy the first part of old_begin to raw_mem + T *start_n = old_start + difference_type(s_before); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(old_start, start_n, new_start); + //The buffer is all constructed until old_end, + //release destroyer and update size + old_values_destroyer.release(); + this->members_.m_size = old_size + s_before; + //Now copy the second part of old_begin overwriting himself + T* next = BOOST_CONTAINER_MOVE_NAMESPACE::move(start_n, pos, old_start); + if(do_after){ + //Now copy the new_beg elements + interf.copy_some_and_update(next, s_before, true); + } + else{ + //Now copy the all the new elements + interf.copy_all_to(next); + T* move_start = next + n; + //Now displace old_end elements + T* move_end = BOOST_CONTAINER_MOVE_NAMESPACE::move(pos, old_finish, move_start); + //Destroy remaining moved elements from old_end except if + //they have trivial destructor after being moved + difference_type n_destroy = s_before - n; + if(!value_traits::trivial_dctr_after_move) + this->destroy_n(move_end, n_destroy); + this->members_.m_size -= n_destroy; + } + } + else { + //If we have to expand both sides, + //we will play if the first new values so + //calculate the upper bound of new values + + //The raw memory divides the new elements + // + //If we need two phase construction (do_after) + //new group is divided in new = new_beg + new_end groups + //In this phase only new_beg will be inserted + // + //Old situation: + // _______________________________________________________ + //| raw_mem | old_begin | old_end | raw_mem | + //|_______________|___________|_________|_________________| + // + //New situation with do_after(): + // ____________________________________________________ + //| old_begin | new_beg | old_end | raw_mem | + //|___________|_______________|_________|______________| + // + //New situation without do_after: + // ______________________________________________________ + //| old_begin | new | old_end | raw_mem | + //|___________|_____|_________|__________________________| + // + //First copy whole old_begin and part of new to raw_mem + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(old_start, pos, new_start); + this->members_.m_size = elemsbefore; + + const size_type mid_n = difference_type(s_before) - elemsbefore; + interf.uninitialized_copy_some_and_update(new_start + elemsbefore, mid_n, true); + this->members_.m_size = old_size + s_before; + //The buffer is all constructed until old_end, + //release destroyer and update size + old_values_destroyer.release(); + + if(do_after){ + //Copy new_beg part + interf.copy_some_and_update(old_start, s_before - mid_n, true); + } + else{ + //Copy all new elements + interf.copy_all_to(old_start); + T* move_start = old_start + (n-mid_n); + //Displace old_end + T* move_end = BOOST_CONTAINER_MOVE_NAMESPACE::move(pos, old_finish, move_start); + //Destroy remaining moved elements from old_end except if they + //have trivial destructor after being moved + difference_type n_destroy = s_before - n; + if(!value_traits::trivial_dctr_after_move) + this->destroy_n(move_end, n_destroy); + this->members_.m_size -= n_destroy; + } + } + + //This is only executed if two phase construction is needed + //This can be executed without exception handling since we + //have to just copy and append in raw memory and + //old_values_destroyer has been released in phase 1. + if(do_after){ + //The raw memory divides the new elements + // + //Old situation: + // ______________________________________________________ + //| raw_mem | old_begin | old_end | raw_mem | + //|______________|___________|____________|______________| + // + //New situation with do_after(1): + // _______________________________________________________ + //| old_begin + new_beg | new_end |old_end | raw_mem | + //|__________________________|_________|________|_________| + // + //New situation with do_after(2): + // ______________________________________________________ + //| old_begin + new | old_end |raw | + //|_______________________________________|_________|____| + // + const size_type n_after = n - s_before; + const difference_type elemsafter = old_size - elemsbefore; + + //We can have two situations: + if (elemsafter > difference_type(n_after)){ + //The raw_mem from end will divide displaced old_end + // + //Old situation: + // ______________________________________________________ + //| raw_mem | old_begin | old_end | raw_mem | + //|______________|___________|____________|______________| + // + //New situation with do_after(1): + // _______________________________________________________ + //| old_begin + new_beg | new_end |old_end | raw_mem | + //|__________________________|_________|________|_________| + // + //First copy the part of old_end raw_mem + T* finish_n = old_finish - difference_type(n_after); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(finish_n, old_finish, old_finish); + this->members_.m_size += n_after; + //Displace the rest of old_end to the new position + BOOST_CONTAINER_MOVE_NAMESPACE::move_backward(pos, finish_n, old_finish); + //Now overwrite with new_end + //The new_end part is [first + (n - n_after), last) + interf.copy_all_to(pos); + } + else { + //The raw_mem from end will divide new_end part + // + //Old situation: + // _____________________________________________________________ + //| raw_mem | old_begin | old_end | raw_mem | + //|______________|___________|____________|_____________________| + // + //New situation with do_after(2): + // _____________________________________________________________ + //| old_begin + new_beg | new_end |old_end | raw_mem | + //|__________________________|_______________|________|_________| + // + size_type mid_last_dist = n_after - elemsafter; + //First initialize data in raw memory + //The new_end part is [first + (n - n_after), last) + interf.uninitialized_copy_some_and_update(old_finish, elemsafter, false); + this->members_.m_size += mid_last_dist; + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_move(pos, old_finish, old_finish + mid_last_dist); + this->members_.m_size += n_after - mid_last_dist; + //Now copy the part of new_end over constructed elements + interf.copy_all_to(pos); + } + } + } + } + + template + void priv_range_insert(const_iterator pos, InIt first, InIt last, std::input_iterator_tag) + { + for(;first != last; ++first){ + this->insert(pos, BOOST_CONTAINER_MOVE_NAMESPACE::move(value_type(*first))); + } + } + + template + void priv_assign_aux(InIt first, InIt last, std::input_iterator_tag) + { + //Overwrite all elements we can from [first, last) + iterator cur = begin(); + for ( ; first != last && cur != end(); ++cur, ++first){ + *cur = *first; + } + + if (first == last){ + //There are no more elements in the sequence, erase remaining + this->erase(cur, cend()); + } + else{ + //There are more elements in the range, insert the remaining ones + this->insert(this->cend(), first, last); + } + } + + template + void priv_assign_aux(FwdIt first, FwdIt last, std::forward_iterator_tag) + { + size_type n = std::distance(first, last); + if(!n){ + this->prot_destroy_all(); + return; + } + //Check if we have enough memory or try to expand current memory + size_type remaining = this->members_.m_capacity - this->members_.m_size; + bool same_buffer_start; + std::pair ret; + size_type real_cap = this->members_.m_capacity; + + if (n <= remaining){ + same_buffer_start = true; + } + else{ + //There is not enough memory, allocate a new buffer + size_type new_cap = this->next_capacity(n); + ret = this->allocation_command + (allocate_new | expand_fwd | expand_bwd, + this->size() + n, new_cap, real_cap, this->members_.m_start); + same_buffer_start = ret.second && this->members_.m_start == ret.first; + if(same_buffer_start){ + this->members_.m_capacity = real_cap; + } + } + + if(same_buffer_start){ + T *start = containers_detail::get_pointer(this->members_.m_start); + if (this->size() >= n){ + //There is memory, but there are more old elements than new ones + //Overwrite old elements with new ones + std::copy(first, last, start); + //Destroy remaining old elements + this->destroy_n(start + n, this->members_.m_size - n); + this->members_.m_size = n; + } + else{ + //There is memory, but there are less old elements than new ones + //First overwrite some old elements with new ones + FwdIt mid = first; + std::advance(mid, this->size()); + // iG T *end = std::copy(first, mid, start); + T *end = std::copy(first, mid, start); + //Initialize the remaining new elements in the uninitialized memory + // iG std::uninitialized_copy(mid, last, end); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(mid, last, end); + this->members_.m_size = n; + } + } + else if(!ret.second){ + typename value_traits::UCopiedArrayDeallocator scoped_alloc(ret.first, this->alloc(), real_cap); + // iG std::uninitialized_copy(first, last, containers_detail::get_pointer(ret.first)); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(first, last, containers_detail::get_pointer(ret.first)); + scoped_alloc.release(); + //Destroy and deallocate old buffer + if(this->members_.m_start != 0){ + this->destroy_n(containers_detail::get_pointer(this->members_.m_start), this->members_.m_size); + this->alloc().deallocate(this->members_.m_start, this->members_.m_capacity); + } + this->members_.m_start = ret.first; + this->members_.m_size = n; + this->members_.m_capacity = real_cap; + } + else{ + //Backwards expansion + //If anything goes wrong, this object will destroy old objects + T *old_start = containers_detail::get_pointer(this->members_.m_start); + size_type old_size = this->members_.m_size; + typename value_traits::OldArrayDestructor old_values_destroyer(old_start, old_size); + //If something goes wrong size will be 0 + //but holding the whole buffer + this->members_.m_size = 0; + this->members_.m_start = ret.first; + this->members_.m_capacity = real_cap; + + //Backup old buffer data + size_type old_offset = old_start - containers_detail::get_pointer(ret.first); + size_type first_count = containers_detail::min_value(n, old_offset); + + FwdIt mid = first; + std::advance(mid, first_count); + // iG std::uninitialized_copy(first, mid, containers_detail::get_pointer(ret.first)); + ::BOOST_CONTAINER_MOVE_NAMESPACE::uninitialized_copy_or_move(first, mid, containers_detail::get_pointer(ret.first)); + + if(old_offset > n){ + //All old elements will be destroyed by "old_values_destroyer" + this->members_.m_size = n; + } + else{ + //We have constructed objects from the new begin until + //the old end so release the rollback destruction + old_values_destroyer.release(); + this->members_.m_start = ret.first; + this->members_.m_size = first_count + old_size; + //Now overwrite the old values + size_type second_count = containers_detail::min_value(old_size, n - first_count); + FwdIt mid2 = mid; + std::advance(mid2, second_count); + // iG std::copy(mid, mid2, old_start); + std::copy(mid, mid2, old_start); + + //Check if we still have to append elements in the + //uninitialized end + if(second_count == old_size){ + // iG std::copy(mid2, last, old_start + old_size); + std::copy(mid2, last, old_start + old_size); + } + else{ + //We have to destroy some old values + this->destroy_n + (old_start + second_count, old_size - second_count); + this->members_.m_size = n; + } + this->members_.m_size = n; + } + } + } + + template + void priv_assign_dispatch(Integer n, Integer val, containers_detail::true_) + { this->assign((size_type) n, (value_type)val); } + + template + void priv_assign_dispatch(InIt first, InIt last, containers_detail::false_) + { + //Dispatch depending on integer/iterator + typedef typename std::iterator_traits::iterator_category ItCat; + this->priv_assign_aux(first, last, ItCat()); + } + + template + void priv_insert_dispatch(const_iterator pos, Integer n, Integer val, containers_detail::true_) + { this->insert(pos, (size_type)n, (T)val); } + + template + void priv_insert_dispatch(const_iterator pos, InIt first, + InIt last, containers_detail::false_) + { + //Dispatch depending on integer/iterator + typedef typename std::iterator_traits::iterator_category ItCat; + this->priv_range_insert(pos.get_ptr(), first, last, ItCat()); + } + + void priv_check_range(size_type n) const + { + //If n is out of range, throw an out_of_range exception + if (n >= size()) + throw std::out_of_range("vector::at"); + } + + #ifdef BOOST_CONTAINERS_VECTOR_ALLOC_STATS + public: + unsigned int num_expand_fwd; + unsigned int num_expand_bwd; + unsigned int num_shrink; + unsigned int num_alloc; + void reset_alloc_stats() + { num_expand_fwd = num_expand_bwd = num_alloc = 0, num_shrink = 0; } + #endif + /// @endcond +}; + +template +inline bool +operator==(const vector& x, const vector& y) +{ + //Check first size and each element if needed + return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); +} + +template +inline bool +operator!=(const vector& x, const vector& y) +{ + //Check first size and each element if needed + return x.size() != y.size() || !std::equal(x.begin(), x.end(), y.begin()); +} + +template +inline bool +operator<(const vector& x, const vector& y) +{ + return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); +} + +template +inline void swap(vector& x, vector& y) +{ x.swap(y); } + +}} + +/// @cond + +namespace boost { + +/* + +//!has_trivial_destructor_after_move<> == true_type +//!specialization for optimizations +template +struct has_trivial_destructor_after_move > +{ + static const bool value = has_trivial_destructor::value; +}; + +*/ + +} + +/// @endcond + +#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP + +#endif // #ifndef BOOST_CONTAINERS_CONTAINERS_VECTOR_HPP + diff --git a/utils/boost_idb/boost/interprocess/containers/containers_fwd.hpp b/utils/boost_idb/boost/interprocess/containers/containers_fwd.hpp index 28cd0f12..fb7d4ab6 100644 --- a/utils/boost_idb/boost/interprocess/containers/containers_fwd.hpp +++ b/utils/boost_idb/boost/interprocess/containers/containers_fwd.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -22,7 +22,7 @@ ////////////////////////////////////////////////////////////////////////////// #include -#include +#include namespace boost { namespace interprocess { @@ -35,6 +35,4 @@ using boost::container::ordered_unique_range; #include -/// @endcond - #endif // #ifndef BOOST_INTERPROCESS_CONTAINERS_CONTAINERS_FWD_HPP diff --git a/utils/boost_idb/boost/interprocess/containers/deque.hpp b/utils/boost_idb/boost/interprocess/containers/deque.hpp index 66122e24..d6c68b7f 100644 --- a/utils/boost_idb/boost/interprocess/containers/deque.hpp +++ b/utils/boost_idb/boost/interprocess/containers/deque.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/flat_map.hpp b/utils/boost_idb/boost/interprocess/containers/flat_map.hpp index 38b04ac9..9aeffcbc 100644 --- a/utils/boost_idb/boost/interprocess/containers/flat_map.hpp +++ b/utils/boost_idb/boost/interprocess/containers/flat_map.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/flat_set.hpp b/utils/boost_idb/boost/interprocess/containers/flat_set.hpp index 45b42fd1..254da13b 100644 --- a/utils/boost_idb/boost/interprocess/containers/flat_set.hpp +++ b/utils/boost_idb/boost/interprocess/containers/flat_set.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/list.hpp b/utils/boost_idb/boost/interprocess/containers/list.hpp index 50f0ff0d..ecf91d53 100644 --- a/utils/boost_idb/boost/interprocess/containers/list.hpp +++ b/utils/boost_idb/boost/interprocess/containers/list.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/map.hpp b/utils/boost_idb/boost/interprocess/containers/map.hpp index ca00b204..cee60244 100644 --- a/utils/boost_idb/boost/interprocess/containers/map.hpp +++ b/utils/boost_idb/boost/interprocess/containers/map.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/pair.hpp b/utils/boost_idb/boost/interprocess/containers/pair.hpp index 65526ab9..af1d1bb6 100644 --- a/utils/boost_idb/boost/interprocess/containers/pair.hpp +++ b/utils/boost_idb/boost/interprocess/containers/pair.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,14 +16,13 @@ #endif #include -#include +#include #include namespace boost { namespace interprocess { -using boost::container::container_detail::pair; -using boost::container::container_detail::piecewise_construct; +using boost::container::containers_detail::pair; } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/set.hpp b/utils/boost_idb/boost/interprocess/containers/set.hpp index 69792045..f6e320d7 100644 --- a/utils/boost_idb/boost/interprocess/containers/set.hpp +++ b/utils/boost_idb/boost/interprocess/containers/set.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/slist.hpp b/utils/boost_idb/boost/interprocess/containers/slist.hpp index b511d060..9ab28fd5 100644 --- a/utils/boost_idb/boost/interprocess/containers/slist.hpp +++ b/utils/boost_idb/boost/interprocess/containers/slist.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/stable_vector.hpp b/utils/boost_idb/boost/interprocess/containers/stable_vector.hpp index 4a59b81e..eac1a4e6 100644 --- a/utils/boost_idb/boost/interprocess/containers/stable_vector.hpp +++ b/utils/boost_idb/boost/interprocess/containers/stable_vector.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/string.hpp b/utils/boost_idb/boost/interprocess/containers/string.hpp index e7af2fa3..280c1f8b 100644 --- a/utils/boost_idb/boost/interprocess/containers/string.hpp +++ b/utils/boost_idb/boost/interprocess/containers/string.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/vector.hpp b/utils/boost_idb/boost/interprocess/containers/vector.hpp index 3f10e015..951779c8 100644 --- a/utils/boost_idb/boost/interprocess/containers/vector.hpp +++ b/utils/boost_idb/boost/interprocess/containers/vector.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #endif #include -#include +#include #include namespace boost { diff --git a/utils/boost_idb/boost/interprocess/containers/version_type.hpp b/utils/boost_idb/boost/interprocess/containers/version_type.hpp index 4516e8c9..06f7d91d 100644 --- a/utils/boost_idb/boost/interprocess/containers/version_type.hpp +++ b/utils/boost_idb/boost/interprocess/containers/version_type.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,13 +16,13 @@ #endif #include -#include +#include namespace boost { namespace interprocess { -using boost::container::container_detail::version_type; -using boost::container::container_detail::version; +using boost::container::containers_detail::version_type; +using boost::container::containers_detail::version; } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/creation_tags.hpp b/utils/boost_idb/boost/interprocess/creation_tags.hpp index 459eb4df..fe483f62 100644 --- a/utils/boost_idb/boost/interprocess/creation_tags.hpp +++ b/utils/boost_idb/boost/interprocess/creation_tags.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -61,12 +61,12 @@ static const open_or_create_t open_or_create = open_or_create_t(); //!be only opened for reading static const open_copy_on_write_t open_copy_on_write = open_copy_on_write_t(); -namespace ipcdetail { +namespace detail { enum create_enum_t { DoCreate, DoOpen, DoOpenOrCreate }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/detail/atomic.hpp b/utils/boost_idb/boost/interprocess/detail/atomic.hpp index fb56891e..71b7a55f 100644 --- a/utils/boost_idb/boost/interprocess/detail/atomic.hpp +++ b/utils/boost_idb/boost/interprocess/detail/atomic.hpp @@ -1,8 +1,7 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2006-2012 +// (C) Copyright Ion Gaztanaga 2006-2009 // (C) Copyright Markus Schoepflin 2007 -// (C) Copyright Bryce Lelbach 2010 // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at @@ -21,7 +20,7 @@ namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ //! Atomically increment an boost::uint32_t by 1 //! "mem": pointer to the object @@ -45,7 +44,7 @@ inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val); inline boost::uint32_t atomic_cas32 (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp); -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ @@ -55,7 +54,7 @@ inline boost::uint32_t atomic_cas32 namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ //! Atomically decrement an boost::uint32_t by 1 //! "mem": pointer to the atomic value @@ -89,7 +88,7 @@ inline boost::uint32_t atomic_cas32 (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp) { return winapi::interlocked_compare_exchange(reinterpret_cast(mem), with, cmp); } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ @@ -97,7 +96,7 @@ inline boost::uint32_t atomic_cas32 namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ //! Compare an boost::uint32_t's value with "cmp". //! If they are the same swap the value with "with" @@ -109,14 +108,22 @@ inline boost::uint32_t atomic_cas32 (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp) { boost::uint32_t prev = cmp; - // This version by Mans Rullgard of Pathscale - __asm__ __volatile__ ( "lock\n\t" - "cmpxchg %2,%0" - : "+m"(*mem), "+a"(prev) - : "r"(with) - : "cc"); + asm volatile( "lock\n\t" + "cmpxchg %3,%1" + : "=a" (prev), "=m" (*(mem)) + : "0" (prev), "r" (with) + : "memory", "cc"); + return prev; +/* + boost::uint32_t prev; + + asm volatile ("lock; cmpxchgl %1, %2" + : "=a" (prev) + : "r" (with), "m" (*(mem)), "0"(cmp)); + asm volatile("" : : : "memory"); return prev; +*/ } //! Atomically add 'val' to an boost::uint32_t @@ -141,6 +148,14 @@ inline boost::uint32_t atomic_add32 ); return r; +/* + asm volatile( "lock\n\t; xaddl %0,%1" + : "=r"(val), "=m"(*mem) + : "0"(val), "m"(*mem)); + asm volatile("" : : : "memory"); + + return val; +*/ } //! Atomically increment an apr_uint32_t by 1 @@ -165,7 +180,7 @@ inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) { *mem = val; } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ @@ -173,7 +188,7 @@ inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ //! Atomically add 'val' to an boost::uint32_t //! "mem": pointer to the object @@ -183,14 +198,17 @@ inline boost::uint32_t atomic_add32(volatile boost::uint32_t *mem, boost::uint32 { boost::uint32_t prev, temp; - asm volatile ("1:\n\t" - "lwarx %0,0,%2\n\t" - "add %1,%0,%3\n\t" - "stwcx. %1,0,%2\n\t" - "bne- 1b" - : "=&r" (prev), "=&r" (temp) - : "b" (mem), "r" (val) - : "cc", "memory"); + asm volatile ("0:\n\t" // retry local label + "lwarx %0,0,%2\n\t" // load prev and reserve + "add %1,%0,%3\n\t" // temp = prev + val + "stwcx. %1,0,%2\n\t" // conditionally store + "bne- 0b" // start over if we lost + // the reservation + //XXX find a cleaner way to define the temp + //it's not an output + : "=&r" (prev), "=&r" (temp) // output, temp + : "b" (mem), "r" (val) // inputs + : "memory", "cc"); // clobbered return prev; } @@ -205,16 +223,19 @@ inline boost::uint32_t atomic_cas32 { boost::uint32_t prev; - asm volatile ("1:\n\t" - "lwarx %0,0,%1\n\t" - "cmpw %0,%3\n\t" - "bne- 2f\n\t" - "stwcx. %2,0,%1\n\t" - "bne- 1b\n\t" - "2:" - : "=&r"(prev) - : "b" (mem), "r" (with), "r" (cmp) - : "cc", "memory"); + asm volatile ("0:\n\t" // retry local label + "lwarx %0,0,%1\n\t" // load prev and reserve + "cmpw %0,%3\n\t" // does it match cmp? + "bne- 1f\n\t" // ...no, bail out + "stwcx. %2,0,%1\n\t" // ...yes, conditionally + // store with + "bne- 0b\n\t" // start over if we lost + // the reservation + "1:" // exit local label + + : "=&r"(prev) // output + : "b" (mem), "r" (with), "r"(cmp) // inputs + : "memory", "cc"); // clobbered return prev; } @@ -240,7 +261,57 @@ inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) { *mem = val; } -} //namespace ipcdetail{ +} //namespace detail{ +} //namespace interprocess{ +} //namespace boost{ + +#elif defined(__GNUC__) && ( __GNUC__ * 100 + __GNUC_MINOR__ >= 401 ) + +namespace boost { +namespace interprocess { +namespace detail{ + +//! Atomically add 'val' to an boost::uint32_t +//! "mem": pointer to the object +//! "val": amount to add +//! Returns the old value pointed to by mem +inline boost::uint32_t atomic_add32 + (volatile boost::uint32_t *mem, boost::uint32_t val) +{ return __sync_fetch_and_add(const_cast(mem), val); } + +//! Atomically increment an apr_uint32_t by 1 +//! "mem": pointer to the object +//! Returns the old value pointed to by mem +inline boost::uint32_t atomic_inc32(volatile boost::uint32_t *mem) +{ return atomic_add32(mem, 1); } + +//! Atomically decrement an boost::uint32_t by 1 +//! "mem": pointer to the atomic value +//! Returns the old value pointed to by mem +inline boost::uint32_t atomic_dec32(volatile boost::uint32_t *mem) +{ return atomic_add32(mem, (boost::uint32_t)-1); } + +//! Atomically read an boost::uint32_t from memory +inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) +{ return *mem; } + +//! Compare an boost::uint32_t's value with "cmp". +//! If they are the same swap the value with "with" +//! "mem": pointer to the value +//! "with" what to swap it with +//! "cmp": the value to compare it to +//! Returns the old value of *mem +inline boost::uint32_t atomic_cas32 + (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp) +{ return __sync_val_compare_and_swap(const_cast(mem), cmp, with); } + +//! Atomically set an boost::uint32_t in memory +//! "mem": pointer to the object +//! "param": val value that the object will assume +inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) +{ *mem = val; } + +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ @@ -250,7 +321,7 @@ inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ //! Atomically add 'val' to an boost::uint32_t //! "mem": pointer to the object @@ -291,7 +362,7 @@ inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) { *mem = val; } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ @@ -302,7 +373,7 @@ inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ //! Atomically decrement a uint32_t by 1 //! "mem": pointer to the atomic value @@ -386,151 +457,101 @@ inline boost::uint32_t atomic_cas32( mem, with, cmp); } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ -#elif defined(__IBMCPP__) && (__IBMCPP__ >= 800) && defined(_AIX) - -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail{ - -//first define boost::uint32_t versions of __lwarx and __stwcx to avoid poluting -//all the functions with casts - -//! From XLC documenation : -//! This function can be used with a subsequent stwcxu call to implement a -//! read-modify-write on a specified memory location. The two functions work -//! together to ensure that if the store is successfully performed, no other -//! processor or mechanism can modify the target doubleword between the time -//! lwarxu function is executed and the time the stwcxu functio ncompletes. -//! "mem" : pointer to the object -//! Returns the value at pointed to by mem -inline boost::uint32_t lwarxu(volatile boost::uint32_t *mem) -{ - return static_cast(__lwarx(reinterpret_cast(mem))); -} - -//! "mem" : pointer to the object -//! "val" : the value to store -//! Returns true if the update of mem is successful and false if it is -//!unsuccessful -inline bool stwcxu(volatile boost::uint32_t* mem, boost::uint32_t val) -{ - return (__stwcx(reinterpret_cast(mem), static_cast(val)) != 0); -} - -//! "mem": pointer to the object -//! "val": amount to add -//! Returns the old value pointed to by mem -inline boost::uint32_t atomic_add32 - (volatile boost::uint32_t *mem, boost::uint32_t val) -{ - boost::uint32_t oldValue; - do - { - oldValue = lwarxu(mem); - }while (!stwcxu(mem, oldValue+val)); - return oldValue; -} - -//! Atomically increment an apr_uint32_t by 1 -//! "mem": pointer to the object -//! Returns the old value pointed to by mem -inline boost::uint32_t atomic_inc32(volatile boost::uint32_t *mem) -{ return atomic_add32(mem, 1); } - -//! Atomically decrement an boost::uint32_t by 1 -//! "mem": pointer to the atomic value -//! Returns the old value pointed to by mem -inline boost::uint32_t atomic_dec32(volatile boost::uint32_t *mem) -{ return atomic_add32(mem, (boost::uint32_t)-1); } - -//! Atomically read an boost::uint32_t from memory -inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) -{ return *mem; } - -//! Compare an boost::uint32_t's value with "cmp". -//! If they are the same swap the value with "with" -//! "mem": pointer to the value -//! "with" what to swap it with -//! "cmp": the value to compare it to -//! Returns the old value of *mem -inline boost::uint32_t atomic_cas32 - (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp) -{ - boost::uint32_t oldValue; - boost::uint32_t valueToStore; - do - { - oldValue = lwarxu(mem); - } while (!stwcxu(mem, (oldValue == with) ? cmp : oldValue)); - - return oldValue; -} - -//! Atomically set an boost::uint32_t in memory -//! "mem": pointer to the object -//! "param": val value that the object will assume -inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) -{ *mem = val; } - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#elif defined(__GNUC__) && ( __GNUC__ * 100 + __GNUC_MINOR__ >= 401 ) - -namespace boost { -namespace interprocess { -namespace ipcdetail{ - -//! Atomically add 'val' to an boost::uint32_t -//! "mem": pointer to the object -//! "val": amount to add -//! Returns the old value pointed to by mem -inline boost::uint32_t atomic_add32 - (volatile boost::uint32_t *mem, boost::uint32_t val) -{ return __sync_fetch_and_add(const_cast(mem), val); } - -//! Atomically increment an apr_uint32_t by 1 -//! "mem": pointer to the object -//! Returns the old value pointed to by mem -inline boost::uint32_t atomic_inc32(volatile boost::uint32_t *mem) -{ return atomic_add32(mem, 1); } - -//! Atomically decrement an boost::uint32_t by 1 -//! "mem": pointer to the atomic value -//! Returns the old value pointed to by mem -inline boost::uint32_t atomic_dec32(volatile boost::uint32_t *mem) -{ return atomic_add32(mem, (boost::uint32_t)-1); } - -//! Atomically read an boost::uint32_t from memory -inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) -{ return *mem; } - -//! Compare an boost::uint32_t's value with "cmp". -//! If they are the same swap the value with "with" -//! "mem": pointer to the value -//! "with" what to swap it with -//! "cmp": the value to compare it to -//! Returns the old value of *mem -inline boost::uint32_t atomic_cas32 - (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp) -{ return __sync_val_compare_and_swap(const_cast(mem), cmp, with); } - -//! Atomically set an boost::uint32_t in memory -//! "mem": pointer to the object -//! "param": val value that the object will assume -inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) -{ *mem = val; } - -} //namespace ipcdetail{ -} //namespace interprocess{ -} //namespace boost{ +#elif defined(__IBMCPP__) && (__IBMCPP__ >= 800) && defined(_AIX) + +#include + +namespace boost { +namespace interprocess { +namespace detail{ + +//first define boost::uint32_t versions of __lwarx and __stwcx to avoid poluting +//all the functions with casts + +//! From XLC documenation : +//! This function can be used with a subsequent stwcxu call to implement a +//! read-modify-write on a specified memory location. The two functions work +//! together to ensure that if the store is successfully performed, no other +//! processor or mechanism can modify the target doubleword between the time +//! lwarxu function is executed and the time the stwcxu functio ncompletes. +//! "mem" : pointer to the object +//! Returns the value at pointed to by mem +inline boost::uint32_t lwarxu(volatile boost::uint32_t *mem) +{ + return static_cast(__lwarx(reinterpret_cast(mem))); +} + +//! "mem" : pointer to the object +//! "val" : the value to store +//! Returns true if the update of mem is successful and false if it is +//!unsuccessful +inline bool stwcxu(volatile boost::uint32_t* mem, boost::uint32_t val) +{ + return (__stwcx(reinterpret_cast(mem), static_cast(val)) != 0); +} + +//! "mem": pointer to the object +//! "val": amount to add +//! Returns the old value pointed to by mem +inline boost::uint32_t atomic_add32 + (volatile boost::uint32_t *mem, boost::uint32_t val) +{ + boost::uint32_t oldValue; + do + { + oldValue = lwarxu(mem); + }while (!stwcxu(mem, oldValue+val)); + return oldValue; +} + +//! Atomically increment an apr_uint32_t by 1 +//! "mem": pointer to the object +//! Returns the old value pointed to by mem +inline boost::uint32_t atomic_inc32(volatile boost::uint32_t *mem) +{ return atomic_add32(mem, 1); } + +//! Atomically decrement an boost::uint32_t by 1 +//! "mem": pointer to the atomic value +//! Returns the old value pointed to by mem +inline boost::uint32_t atomic_dec32(volatile boost::uint32_t *mem) +{ return atomic_add32(mem, (boost::uint32_t)-1); } + +//! Atomically read an boost::uint32_t from memory +inline boost::uint32_t atomic_read32(volatile boost::uint32_t *mem) +{ return *mem; } + +//! Compare an boost::uint32_t's value with "cmp". +//! If they are the same swap the value with "with" +//! "mem": pointer to the value +//! "with" what to swap it with +//! "cmp": the value to compare it to +//! Returns the old value of *mem +inline boost::uint32_t atomic_cas32 + (volatile boost::uint32_t *mem, boost::uint32_t with, boost::uint32_t cmp) +{ + boost::uint32_t oldValue; + boost::uint32_t valueToStore; + do + { + oldValue = lwarxu(mem); + } while (!stwcxu(mem, (oldValue == with) ? cmp : oldValue)); + + return oldValue; +} + +//! Atomically set an boost::uint32_t in memory +//! "mem": pointer to the object +//! "param": val value that the object will assume +inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) +{ *mem = val; } + +} //namespace detail +} //namespace interprocess +} //namespace boost #else @@ -540,7 +561,7 @@ inline void atomic_write32(volatile boost::uint32_t *mem, boost::uint32_t val) namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ inline bool atomic_add_unless32 (volatile boost::uint32_t *mem, boost::uint32_t value, boost::uint32_t unless_this) @@ -552,9 +573,9 @@ inline bool atomic_add_unless32 return c != unless_this; } -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost +} //namespace detail +} //namespace interprocess +} //namespace boost #include diff --git a/utils/boost_idb/boost/interprocess/detail/cast_tags.hpp b/utils/boost_idb/boost/interprocess/detail/cast_tags.hpp index 37dabd1f..f9d1b359 100644 --- a/utils/boost_idb/boost/interprocess/detail/cast_tags.hpp +++ b/utils/boost_idb/boost/interprocess/detail/cast_tags.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -14,14 +14,14 @@ #include #include -namespace boost { namespace interprocess { namespace ipcdetail { +namespace boost { namespace interprocess { namespace detail { struct static_cast_tag {}; struct const_cast_tag {}; struct dynamic_cast_tag {}; struct reinterpret_cast_tag {}; -}}} //namespace boost { namespace interprocess { namespace ipcdetail { +}}} //namespace boost { namespace interprocess { namespace detail { #include diff --git a/utils/boost_idb/boost/interprocess/detail/config_begin.hpp b/utils/boost_idb/boost/interprocess/detail/config_begin.hpp index 9224f7dd..12af42b6 100644 --- a/utils/boost_idb/boost/interprocess/detail/config_begin.hpp +++ b/utils/boost_idb/boost/interprocess/detail/config_begin.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -44,5 +44,4 @@ // with /GR-; unpredictable behavior may result #pragma warning (disable : 4673) // throwing '' the following types will not be considered at the catch site #pragma warning (disable : 4671) // the copy constructor is inaccessible - #pragma warning (disable : 4250) // inherits 'x' via dominance #endif diff --git a/utils/boost_idb/boost/interprocess/detail/config_end.hpp b/utils/boost_idb/boost/interprocess/detail/config_end.hpp index f871ce75..cf31ca80 100644 --- a/utils/boost_idb/boost/interprocess/detail/config_end.hpp +++ b/utils/boost_idb/boost/interprocess/detail/config_end.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/utils/boost_idb/boost/interprocess/detail/config_external_begin.hpp b/utils/boost_idb/boost/interprocess/detail/config_external_begin.hpp deleted file mode 100644 index fb578ef0..00000000 --- a/utils/boost_idb/boost/interprocess/detail/config_external_begin.hpp +++ /dev/null @@ -1,18 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTERPROCESS_EXTERNAL_CONFIG_INCLUDED -#define BOOST_INTERPROCESS_EXTERNAL_CONFIG_INCLUDED -#include -#endif - -#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 406) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wshadow" -#endif diff --git a/utils/boost_idb/boost/interprocess/detail/config_external_end.hpp b/utils/boost_idb/boost/interprocess/detail/config_external_end.hpp deleted file mode 100644 index 214558f5..00000000 --- a/utils/boost_idb/boost/interprocess/detail/config_external_end.hpp +++ /dev/null @@ -1,12 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 406) -# pragma GCC diagnostic pop -#endif diff --git a/utils/boost_idb/boost/interprocess/detail/file_locking_helpers.hpp b/utils/boost_idb/boost/interprocess/detail/file_locking_helpers.hpp deleted file mode 100644 index 2b96e2b6..00000000 --- a/utils/boost_idb/boost/interprocess/detail/file_locking_helpers.hpp +++ /dev/null @@ -1,298 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_FILE_LOCKING_HELPERS_HPP -#define BOOST_INTERPROCESS_FILE_LOCKING_HELPERS_HPP - -#if defined(_MSC_VER)&&(_MSC_VER>=1200) -#pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -#if defined(BOOST_INTERPROCESS_WINDOWS) - -#include -#include -#include - -#else //defined(BOOST_INTERPROCESS_WINDOWS) - -#include -#include -#include - -#endif //defined(BOOST_INTERPROCESS_WINDOWS) - -namespace boost{ -namespace interprocess{ -namespace ipcdetail{ - -#if defined(BOOST_INTERPROCESS_WINDOWS) - -struct locking_file_serial_id -{ - int fd; - unsigned long dwVolumeSerialNumber; - unsigned long nFileIndexHigh; - unsigned long nFileIndexLow; - //This reference count counts the number of modules attached - //to the shared memory and lock file. This serves to unlink - //the locking file and shared memory when all modules are - //done with the global memory (shared memory) - volatile boost::uint32_t modules_attached_to_gmem_count; -}; - -inline bool lock_locking_file(int fd) -{ - int ret = 0; - while(ret != 0 && errno == EDEADLK){ - ret = _locking(fd, _LK_LOCK, 1/*lock_file_contents_length()*/); - } - return 0 == ret; -} - -inline bool try_lock_locking_file(int fd) -{ - return 0 == _locking(fd, _LK_NBLCK , 1); -} - -inline int open_or_create_and_lock_file(const char *name) -{ - permissions p; - p.set_unrestricted(); - while(1){ - file_handle_t handle = create_or_open_file(name, read_write, p); - int fd = _open_osfhandle((intptr_t)handle, _O_TEXT); - if(fd < 0){ - close_file(handle); - return fd; - } - if(!try_lock_locking_file(fd)){ - _close(fd); - return -1; - } - struct _stat s; - if(0 == _stat(name, &s)){ - return fd; - } - else{ - _close(fd); - } - } -} - -inline int try_open_and_lock_file(const char *name) -{ - file_handle_t handle = open_existing_file(name, read_write); - int fd = _open_osfhandle((intptr_t)handle, _O_TEXT); - if(fd < 0){ - close_file(handle); - return fd; - } - if(!try_lock_locking_file(fd)){ - _close(fd); - return -1; - } - return fd; -} - -inline void close_lock_file(int fd) -{ _close(fd); } - -inline bool is_valid_fd(int fd) -{ - struct _stat s; - return EBADF != _fstat(fd, &s); -} - -inline bool is_normal_file(int fd) -{ - if(_isatty(fd)) - return false; - struct _stat s; - if(0 != _fstat(fd, &s)) - return false; - return 0 != (s.st_mode & _S_IFREG); -} - -inline std::size_t get_size(int fd) -{ - struct _stat s; - if(0 != _fstat(fd, &s)) - return 0u; - return (std::size_t)s.st_size; -} - -inline bool fill_file_serial_id(int fd, locking_file_serial_id &id) -{ - winapi::interprocess_by_handle_file_information info; - if(!winapi::get_file_information_by_handle((void*)_get_osfhandle(fd), &info)) - return false; - id.fd = fd; - id.dwVolumeSerialNumber = info.dwVolumeSerialNumber; - id.nFileIndexHigh = info.nFileIndexHigh; - id.nFileIndexLow = info.nFileIndexLow; - id.modules_attached_to_gmem_count = 1; //Initialize attached count - return true; -} - -inline bool compare_file_serial(int fd, const locking_file_serial_id &id) -{ - winapi::interprocess_by_handle_file_information info; - if(!winapi::get_file_information_by_handle((void*)_get_osfhandle(fd), &info)) - return false; - - return id.dwVolumeSerialNumber == info.dwVolumeSerialNumber && - id.nFileIndexHigh == info.nFileIndexHigh && - id.nFileIndexLow == info.nFileIndexLow; -} - -#else //UNIX - -struct locking_file_serial_id -{ - int fd; - dev_t st_dev; - ino_t st_ino; - //This reference count counts the number of modules attached - //to the shared memory and lock file. This serves to unlink - //the locking file and shared memory when all modules are - //done with the global memory (shared memory) - volatile boost::uint32_t modules_attached_to_gmem_count; -}; - -inline bool lock_locking_file(int fd) -{ - int ret = 0; - while(ret != 0 && errno != EINTR){ - struct flock lock; - lock.l_type = F_WRLCK; - lock.l_whence = SEEK_SET; - lock.l_start = 0; - lock.l_len = 1; - ret = fcntl (fd, F_SETLKW, &lock); - } - return 0 == ret; -} - -inline bool try_lock_locking_file(int fd) -{ - struct flock lock; - lock.l_type = F_WRLCK; - lock.l_whence = SEEK_SET; - lock.l_start = 0; - lock.l_len = 1; - return 0 == fcntl (fd, F_SETLK, &lock); -} - -inline int open_or_create_and_lock_file(const char *name) -{ - permissions p; - p.set_unrestricted(); - while(1){ - int fd = create_or_open_file(name, read_write, p); - if(fd < 0){ - return fd; - } - if(!try_lock_locking_file(fd)){ - close(fd); - return -1; - } - struct stat s; - if(0 == stat(name, &s)){ - return fd; - } - else{ - close(fd); - } - } -} - -inline int try_open_and_lock_file(const char *name) -{ - int fd = open_existing_file(name, read_write); - if(fd < 0){ - return fd; - } - if(!try_lock_locking_file(fd)){ - close(fd); - return -1; - } - return fd; -} - -inline void close_lock_file(int fd) -{ close(fd); } - -inline bool is_valid_fd(int fd) -{ - struct stat s; - return EBADF != fstat(fd, &s); -} - -inline bool is_normal_file(int fd) -{ - struct stat s; - if(0 != fstat(fd, &s)) - return false; - return 0 != (s.st_mode & S_IFREG); -} - -inline std::size_t get_size(int fd) -{ - struct stat s; - if(0 != fstat(fd, &s)) - return 0u; - return (std::size_t)s.st_size; -} - -inline bool fill_file_serial_id(int fd, locking_file_serial_id &id) -{ - struct stat s; - if(0 != fstat(fd, &s)) - return false; - id.fd = fd; - id.st_dev = s.st_dev; - id.st_ino = s.st_ino; - id.modules_attached_to_gmem_count = 1; //Initialize attached count - return true; -} - -inline bool compare_file_serial(int fd, const locking_file_serial_id &id) -{ - struct stat info; - if(0 != fstat(fd, &info)) - return false; - - return id.st_dev == info.st_dev && - id.st_ino == info.st_ino; -} - -#endif - -} //namespace ipcdetail{ -} //namespace interprocess{ -} //namespace boost{ - -#include - -#endif //BOOST_INTERPROCESS_FILE_LOCKING_HELPERS_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/file_wrapper.hpp b/utils/boost_idb/boost/interprocess/detail/file_wrapper.hpp index e139df26..1196bb08 100644 --- a/utils/boost_idb/boost/interprocess/detail/file_wrapper.hpp +++ b/utils/boost_idb/boost/interprocess/detail/file_wrapper.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,17 +15,17 @@ #include #include #include -#include +#include #include namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ class file_wrapper { /// @cond - BOOST_MOVABLE_BUT_NOT_COPYABLE(file_wrapper) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(file_wrapper) /// @endcond public: @@ -36,34 +36,33 @@ class file_wrapper //!Creates a file object with name "name" and mode "mode", with the access mode "mode" //!If the file previously exists, throws an error. file_wrapper(create_only_t, const char *name, mode_t mode, const permissions &perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoCreate, name, mode, perm); } + { this->priv_open_or_create(detail::DoCreate, name, mode, perm); } //!Tries to create a file with name "name" and mode "mode", with the //!access mode "mode". If the file previously exists, it tries to open it with mode "mode". //!Otherwise throws an error. file_wrapper(open_or_create_t, const char *name, mode_t mode, const permissions &perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, name, mode, perm); } + { this->priv_open_or_create(detail::DoOpenOrCreate, name, mode, perm); } - //!Tries to open a file with name "name", with the access mode "mode". + //!Tries to open a file with name "name", with the access mode "mode". //!If the file does not previously exist, it throws an error. file_wrapper(open_only_t, const char *name, mode_t mode) - { this->priv_open_or_create(ipcdetail::DoOpen, name, mode, permissions()); } + { this->priv_open_or_create(detail::DoOpen, name, mode, permissions()); } - //!Moves the ownership of "moved"'s file to *this. - //!After the call, "moved" does not represent any file. + //!Moves the ownership of "moved"'s file to *this. + //!After the call, "moved" does not represent any file. //!Does not throw - file_wrapper(BOOST_RV_REF(file_wrapper) moved) - : m_handle(file_handle_t(ipcdetail::invalid_file())) + file_wrapper(BOOST_INTERPROCESS_RV_REF(file_wrapper) moved) { this->swap(moved); } //!Moves the ownership of "moved"'s file to *this. //!After the call, "moved" does not represent any file. //!Does not throw - file_wrapper &operator=(BOOST_RV_REF(file_wrapper) moved) - { - file_wrapper tmp(boost::move(moved)); + file_wrapper &operator=(BOOST_INTERPROCESS_RV_REF(file_wrapper) moved) + { + file_wrapper tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Swaps to file_wrappers. @@ -73,7 +72,7 @@ class file_wrapper //!Erases a file from the system. //!Returns false on error. Never throws static bool remove(const char *name); - + //!Sets the size of the file void truncate(offset_t length); @@ -101,18 +100,18 @@ class file_wrapper //!Closes a previously opened file mapping. Never throws. void priv_close(); //!Closes a previously opened file mapping. Never throws. - bool priv_open_or_create(ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm); + bool priv_open_or_create(detail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm); file_handle_t m_handle; mode_t m_mode; std::string m_filename; }; -inline file_wrapper::file_wrapper() - : m_handle(file_handle_t(ipcdetail::invalid_file())) +inline file_wrapper::file_wrapper() + : m_handle(file_handle_t(detail::invalid_file())) {} -inline file_wrapper::~file_wrapper() +inline file_wrapper::~file_wrapper() { this->priv_close(); } inline const char *file_wrapper::get_name() const @@ -122,10 +121,10 @@ inline bool file_wrapper::get_size(offset_t &size) const { return get_file_size((file_handle_t)m_handle, size); } inline void file_wrapper::swap(file_wrapper &other) -{ +{ std::swap(m_handle, other.m_handle); std::swap(m_mode, other.m_mode); - m_filename.swap(other.m_filename); + m_filename.swap(other.m_filename); } inline mapping_handle_t file_wrapper::get_mapping_handle() const @@ -135,7 +134,7 @@ inline mode_t file_wrapper::get_mode() const { return m_mode; } inline bool file_wrapper::priv_open_or_create - (ipcdetail::create_enum_t type, + (detail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm = permissions()) @@ -149,13 +148,13 @@ inline bool file_wrapper::priv_open_or_create //Open file existing native API to obtain the handle switch(type){ - case ipcdetail::DoOpen: + case detail::DoOpen: m_handle = open_existing_file(filename, mode); break; - case ipcdetail::DoCreate: + case detail::DoCreate: m_handle = create_new_file(filename, mode, perm); break; - case ipcdetail::DoOpenOrCreate: + case detail::DoOpenOrCreate: m_handle = create_or_open_file(filename, mode, perm); break; default: @@ -193,7 +192,7 @@ inline void file_wrapper::priv_close() } } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/detail/in_place_interface.hpp b/utils/boost_idb/boost/interprocess/detail/in_place_interface.hpp index 7c0966c1..11c2954d 100644 --- a/utils/boost_idb/boost/interprocess/detail/in_place_interface.hpp +++ b/utils/boost_idb/boost/interprocess/detail/in_place_interface.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,15 +18,14 @@ #include #include #include -#include #include //typeid //!\file //!Describes an abstract interface for placement construction and destruction. namespace boost { -namespace interprocess { -namespace ipcdetail { +namespace interprocess { +namespace detail { struct in_place_interface { @@ -47,7 +46,7 @@ template struct placement_destroy : public in_place_interface { placement_destroy() - : in_place_interface(::boost::alignment_of::value, sizeof(T), typeid(T).name()) + : in_place_interface(detail::alignment_of::value, sizeof(T), typeid(T).name()) {} virtual void destroy_n(void *mem, std::size_t num, std::size_t &destroyed) @@ -66,7 +65,7 @@ struct placement_destroy : public in_place_interface } } -} //namespace boost { namespace interprocess { namespace ipcdetail { +} //namespace boost { namespace interprocess { namespace detail { #include diff --git a/utils/boost_idb/boost/interprocess/detail/intermodule_singleton.hpp b/utils/boost_idb/boost/interprocess/detail/intermodule_singleton.hpp index 9f41ba63..ec879a68 100644 --- a/utils/boost_idb/boost/interprocess/detail/intermodule_singleton.hpp +++ b/utils/boost_idb/boost/interprocess/detail/intermodule_singleton.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,28 +18,1014 @@ #include #include +#include #ifdef BOOST_INTERPROCESS_WINDOWS - #include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#if defined (BOOST_INTERPROCESS_WINDOWS) +#include +#include + +#include +#else +#include +#include +#include #endif -#include namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ + +namespace file_locking_helpers { + +inline void get_pid_creation_time_str(std::string &s) +{ + std::stringstream stream; + stream << get_current_process_id() << '_'; + stream.precision(6); + stream << std::fixed << get_current_process_creation_time(); + s = stream.str(); +} + +inline void create_tmp_subdir_and_get_pid_based_filepath(const char *subdir_name, const char *file_prefix, OS_process_id_t pid, std::string &s, bool creation_time = false) +{ + //Let's create a lock file for each process gmem that will mark if + //the process is alive or not + create_tmp_and_clean_old(s); + s += "/"; + s += subdir_name; + if(!open_or_create_directory(s.c_str())){ + throw interprocess_exception(error_info(system_error_code())); + } + s += "/"; + s += file_prefix; + if(creation_time){ + std::string sstamp; + get_pid_creation_time_str(sstamp); + s += sstamp; + } + else{ + pid_str_t pid_str; + get_pid_str(pid_str, pid); + s += pid_str; + } +} + +inline bool check_if_filename_complies_with_pid + (const char *filename, const char *prefix, OS_process_id_t pid, std::string &file_suffix, bool creation_time = false) +{ + //Check if filename complies with lock file name pattern + std::string fname(filename); + std::string fprefix(prefix); + if(fname.size() <= fprefix.size()){ + return false; + } + fname.resize(fprefix.size()); + if(fname != fprefix){ + return false; + } + + //If not our lock file, delete it if we can lock it + fname = filename; + fname.erase(0, fprefix.size()); + pid_str_t pid_str; + get_pid_str(pid_str, pid); + file_suffix = pid_str; + if(creation_time){ + std::size_t p = fname.find('_'); + if (p == std::string::npos){ + return false; + } + std::string save_suffix(fname); + fname.erase(p); + fname.swap(file_suffix); + bool ret = (file_suffix == fname); + file_suffix.swap(save_suffix); + return ret; + } + else{ + fname.swap(file_suffix); + return (file_suffix == fname); + } +} + +} //file_locking_helpers + +namespace intermodule_singleton_helpers { + +const int GMemMarkToBeRemoved = -1; +const int GMemNotPresent = -2; + +inline const char *get_lock_file_subdir_name() +{ return "gmem"; } + +inline const char *get_lock_file_base_name() +{ return "lck"; } + +inline void create_and_get_singleton_lock_file_path(std::string &s) +{ + file_locking_helpers::create_tmp_subdir_and_get_pid_based_filepath + (get_lock_file_subdir_name(), get_lock_file_base_name(), get_current_process_id(), s, true); +} + +inline const char *get_shm_base_name() +{ return "bip.gmem.shm."; } + +inline void get_shm_name(std::string &shm_name) +{ + file_locking_helpers::get_pid_creation_time_str(shm_name); + shm_name.insert(0, get_shm_base_name()); +} + +inline std::size_t get_shm_size() +{ return 65536; } + +template +struct managed_sh_dependant +{ + static void apply_gmem_erase_logic(const char *filepath, const char *filename); + + static bool remove_old_gmem() + { + std::string refcstrRootDirectory; + tmp_folder(refcstrRootDirectory); + refcstrRootDirectory += "/"; + refcstrRootDirectory += get_lock_file_subdir_name(); + return for_each_file_in_dir(refcstrRootDirectory.c_str(), apply_gmem_erase_logic); + } +}; + +#if (defined BOOST_INTERPROCESS_WINDOWS) + +template<> +struct managed_sh_dependant +{ + static void apply_gmem_erase_logic(const char *, const char *){} + + static bool remove_old_gmem() + { return true; } +}; + + +struct locking_file_serial_id +{ + int fd; + unsigned long dwVolumeSerialNumber; + unsigned long nFileIndexHigh; + unsigned long nFileIndexLow; + //This reference count counts the number of modules attached + //to the shared memory and lock file. This serves to unlink + //the locking file and shared memory when all modules are + //done with the global memory (shared memory) + volatile boost::uint32_t modules_attached_to_gmem_count; +}; + +inline bool lock_locking_file(int fd) +{ + int ret = 0; + while(ret != 0 && errno == EDEADLK){ + ret = _locking(fd, _LK_LOCK, 1/*lock_file_contents_length()*/); + } + return 0 == ret; +} + +inline bool try_lock_locking_file(int fd) +{ + return 0 == _locking(fd, _LK_NBLCK , 1); +} + +inline int open_or_create_and_lock_file(const char *name) +{ + permissions p; + p.set_unrestricted(); + while(1){ + file_handle_t handle = create_or_open_file(name, read_write, p); + int fd = _open_osfhandle((intptr_t)handle, _O_TEXT); + if(fd < 0){ + close_file(handle); + return fd; + } + if(!try_lock_locking_file(fd)){ + _close(fd); + return -1; + } + struct _stat s; + if(0 == _stat(name, &s)){ + return fd; + } + else{ + _close(fd); + } + } +} + +inline int try_open_and_lock_file(const char *name) +{ + file_handle_t handle = open_existing_file(name, read_write); + int fd = _open_osfhandle((intptr_t)handle, _O_TEXT); + if(fd < 0){ + close_file(handle); + return fd; + } + if(!try_lock_locking_file(fd)){ + _close(fd); + return -1; + } + return fd; +} + +inline void close_lock_file(int fd) +{ _close(fd); } + +inline bool is_valid_fd(int fd) +{ + struct _stat s; + return EBADF != _fstat(fd, &s); +} + +inline bool is_normal_file(int fd) +{ + if(_isatty(fd)) + return false; + struct _stat s; + if(0 != _fstat(fd, &s)) + return false; + return 0 != (s.st_mode & _S_IFREG); +} + +inline std::size_t get_size(int fd) +{ + struct _stat s; + if(0 != _fstat(fd, &s)) + return 0u; + return (std::size_t)s.st_size; +} + +inline bool fill_file_serial_id(int fd, locking_file_serial_id &id) +{ + winapi::interprocess_by_handle_file_information info; + if(!winapi::get_file_information_by_handle((void*)_get_osfhandle(fd), &info)) + return false; + id.fd = fd; + id.dwVolumeSerialNumber = info.dwVolumeSerialNumber; + id.nFileIndexHigh = info.nFileIndexHigh; + id.nFileIndexLow = info.nFileIndexLow; + id.modules_attached_to_gmem_count = 1; //Initialize attached count + return true; +} + +inline bool compare_file_serial(int fd, const locking_file_serial_id &id) +{ + winapi::interprocess_by_handle_file_information info; + if(!winapi::get_file_information_by_handle((void*)_get_osfhandle(fd), &info)) + return false; + + return id.dwVolumeSerialNumber == info.dwVolumeSerialNumber && + id.nFileIndexHigh == info.nFileIndexHigh && + id.nFileIndexLow == info.nFileIndexLow; +} + +#else //UNIX + +struct locking_file_serial_id +{ + int fd; + dev_t st_dev; + ino_t st_ino; + //This reference count counts the number of modules attached + //to the shared memory and lock file. This serves to unlink + //the locking file and shared memory when all modules are + //done with the global memory (shared memory) + volatile boost::uint32_t modules_attached_to_gmem_count; +}; + +inline bool lock_locking_file(int fd) +{ + int ret = 0; + while(ret != 0 && errno != EINTR){ + struct flock lock; + lock.l_type = F_WRLCK; + lock.l_whence = SEEK_SET; + lock.l_start = 0; + lock.l_len = 1; + ret = fcntl (fd, F_SETLKW, &lock); + } + return 0 == ret; +} + +inline bool try_lock_locking_file(int fd) +{ + struct flock lock; + lock.l_type = F_WRLCK; + lock.l_whence = SEEK_SET; + lock.l_start = 0; + lock.l_len = 1; + return 0 == fcntl (fd, F_SETLK, &lock); +} + +inline int open_or_create_and_lock_file(const char *name) +{ + permissions p; + p.set_unrestricted(); + while(1){ + int fd = create_or_open_file(name, read_write, p); + if(fd < 0){ + return fd; + } + if(!try_lock_locking_file(fd)){ + close(fd); + return -1; + } + struct stat s; + if(0 == stat(name, &s)){ + return fd; + } + else{ + close(fd); + } + } +} + +inline int try_open_and_lock_file(const char *name) +{ + int fd = open_existing_file(name, read_write); + if(fd < 0){ + return fd; + } + if(!try_lock_locking_file(fd)){ + close(fd); + return -1; + } + return fd; +} + +inline void close_lock_file(int fd) +{ close(fd); } + +inline bool is_valid_fd(int fd) +{ + struct stat s; + return EBADF != fstat(fd, &s); +} + +inline bool is_normal_file(int fd) +{ + struct stat s; + if(0 != fstat(fd, &s)) + return false; + return 0 != (s.st_mode & S_IFREG); +} + +inline std::size_t get_size(int fd) +{ + struct stat s; + if(0 != fstat(fd, &s)) + return 0u; + return (std::size_t)s.st_size; +} + +inline bool fill_file_serial_id(int fd, locking_file_serial_id &id) +{ + struct stat s; + if(0 != fstat(fd, &s)) + return false; + id.fd = fd; + id.st_dev = s.st_dev; + id.st_ino = s.st_ino; + id.modules_attached_to_gmem_count = 1; //Initialize attached count + return true; +} + +inline bool compare_file_serial(int fd, const locking_file_serial_id &id) +{ + struct stat info; + if(0 != fstat(fd, &info)) + return false; + + return id.st_dev == info.st_dev && + id.st_ino == info.st_ino; +} + +#endif + +template +struct gmem_erase_func +{ + gmem_erase_func(const char *shm_name, const char *singleton_lock_file_path, ManagedShMem & shm) + :shm_name_(shm_name), singleton_lock_file_path_(singleton_lock_file_path), shm_(shm) + {} + + void operator()() + { + locking_file_serial_id *pserial_id = shm_.template find("lock_file_fd").first; + if(pserial_id){ + pserial_id->fd = GMemMarkToBeRemoved; + } + delete_file(singleton_lock_file_path_); + shared_memory_object::remove(shm_name_); + } + + const char * const shm_name_; + const char * const singleton_lock_file_path_; + ManagedShMem & shm_; +}; + +//This function applies shared memory erasure logic based on the passed lock file. +template +void managed_sh_dependant:: + apply_gmem_erase_logic(const char *filepath, const char *filename) +{ + int fd = GMemMarkToBeRemoved; + try{ + std::string str; + //If the filename is current process lock file, then avoid it + if(file_locking_helpers::check_if_filename_complies_with_pid + (filename, get_lock_file_base_name(), get_current_process_id(), str, true)){ + return; + } + //Open and lock the other process' lock file + fd = try_open_and_lock_file(filepath); + if(fd < 0){ + return; + } + //If done, then the process is dead so take global shared memory name + //(the name is based on the lock file name) and try to apply erasure logic + str.insert(0, get_shm_base_name()); + try{ + ManagedShMem shm(open_only, str.c_str()); + gmem_erase_func func(str.c_str(), filepath, shm); + shm.try_atomic_func(func); + } + catch(interprocess_exception &e){ + //If shared memory is not found erase the lock file + if(e.get_error_code() == not_found_error){ + delete_file(filepath); + } + } + } + catch(...){ + + } + if(fd >= 0){ + close_lock_file(fd); + } +} + +} //namespace intermodule_singleton_helpers { + + + +namespace intermodule_singleton_helpers { + +//The lock file logic creates uses a unique instance to a file +template +struct lock_file_logic +{ + lock_file_logic(ManagedShMem &shm) + : mshm(shm) + { shm.atomic_func(*this); } + + void operator()(void) + { + retry_with_new_shm = false; + + //First find the file locking descriptor id + locking_file_serial_id *pserial_id = + mshm.template find("lock_file_fd").first; + + int fd; + //If not found schedule a creation + if(!pserial_id){ + fd = GMemNotPresent; + } + //Else get it + else{ + fd = pserial_id->fd; + } + //If we need to create a new one, do it + if(fd == GMemNotPresent){ + std::string lck_str; + //Create a unique current pid based lock file path + create_and_get_singleton_lock_file_path(lck_str); + //Open or create and lock file + int fd = intermodule_singleton_helpers::open_or_create_and_lock_file(lck_str.c_str()); + //If failed, write a bad file descriptor to notify other modules that + //something was wrong and unlink shared memory. Mark the function object + //to tell caller to retry with another shared memory + if(fd < 0){ + this->register_lock_file(GMemMarkToBeRemoved); + std::string s; + get_shm_name(s); + shared_memory_object::remove(s.c_str()); + retry_with_new_shm = true; + } + //If successful, register the file descriptor + else{ + this->register_lock_file(fd); + } + } + //If the fd was invalid (maybe a previous try failed) notify caller that + //should retry creation logic, since this shm might have been already + //unlinked since the shm was removed + else if (fd == GMemMarkToBeRemoved){ + retry_with_new_shm = true; + } + //If the stored fd is not valid (a open fd, a normal file with the + //expected size, or does not have the same file id number, + //then it's an old shm from an old process with the same pid. + //If that's the case, mark it as invalid + else if(!is_valid_fd(fd) || + !is_normal_file(fd) || + 0 != get_size(fd) || + !compare_file_serial(fd, *pserial_id)){ + pserial_id->fd = GMemMarkToBeRemoved; + std::string s; + get_shm_name(s); + shared_memory_object::remove(s.c_str()); + retry_with_new_shm = true; + } + else{ + //If the lock file is ok, increment reference count of + //attached modules to shared memory + atomic_inc32(&pserial_id->modules_attached_to_gmem_count); + } + } + + private: + locking_file_serial_id * register_lock_file(int fd) + { + locking_file_serial_id *pinfo = mshm.template construct("lock_file_fd")(); + fill_file_serial_id(fd, *pinfo); + return pinfo; + } + + public: + ManagedShMem &mshm; + bool retry_with_new_shm; +}; + +#if defined (BOOST_INTERPROCESS_WINDOWS) + +template<> +struct lock_file_logic +{ + lock_file_logic(managed_windows_shared_memory &) + : retry_with_new_shm(false) + {} + + void operator()(void){} + const bool retry_with_new_shm; +}; + +#endif + +} //namespace intermodule_singleton_helpers { + +//This class contains common code for all singleton types, so that we instantiate this +//code just once per module. This class also holds a reference counted shared memory +//to be used by all instances + +template +class intermodule_singleton_common +{ + public: + typedef void*(singleton_constructor_t)(ManagedShMem &); + typedef void (singleton_destructor_t)(void *, ManagedShMem &); + + static const ::boost::uint32_t Uninitialized = 0u; + static const ::boost::uint32_t Initializing = 1u; + static const ::boost::uint32_t Initialized = 2u; + static const ::boost::uint32_t Broken = 3u; + + static void finalize_singleton_logic(void *ptr, singleton_destructor_t destructor) + { + if(ptr) + destructor(ptr, get_shm()); + //If this is the last singleton of this module + //apply shm destruction. + //Note: singletons are destroyed when the module is unloaded + //so no threads should be executing or holding references + //to this module + if(1 == atomic_dec32(&this_module_singleton_count)){ + destroy_shm(); + } + } + + static void initialize_singleton_logic + (void *&ptr, volatile boost::uint32_t &this_module_singleton_initialized, singleton_constructor_t ini_func); + + private: + static ManagedShMem &get_shm() + { + return *static_cast(static_cast(&shm_mem)); + } + + enum { MemSize = ((sizeof(ManagedShMem)-1)/sizeof(max_align))+1u }; + + static void initialize_shm(); + static void destroy_shm(); + //Static data, zero-initalized without any dependencies + //this_module_singleton_count is the number of singletons used by this module + static volatile boost::uint32_t this_module_singleton_count; + //this_module_shm_initialized is the state of this module's shm class object + static volatile boost::uint32_t this_module_shm_initialized; + static max_align shm_mem[MemSize]; +}; + +template +volatile boost::uint32_t intermodule_singleton_common::this_module_singleton_count; + +template +volatile boost::uint32_t intermodule_singleton_common::this_module_shm_initialized; + +template +max_align intermodule_singleton_common::shm_mem[intermodule_singleton_common::MemSize]; + +template +void intermodule_singleton_common::initialize_shm() +{ + //Obtain unique shm name and size + std::string s; + intermodule_singleton_helpers::get_shm_name(s); + const char *ShmName = s.c_str(); + const std::size_t ShmSize = intermodule_singleton_helpers::get_shm_size();; + while(1){ + //Try to pass shm state to initializing + ::boost::uint32_t tmp = atomic_cas32(&this_module_shm_initialized, Initializing, Uninitialized); + if(tmp >= Initialized){ + break; + } + //If some other thread is doing the work wait + else if(tmp == Initializing){ + thread_yield(); + } + else{ //(tmp == Uninitialized) + //If not initialized try it again? + try{ + //Remove old shared memory from the system + intermodule_singleton_helpers::managed_sh_dependant::remove_old_gmem(); + //in-place construction of the shared memory class + ::new (&get_shm())ManagedShMem(open_or_create, ShmName, ShmSize); + //Use shared memory internal lock to initialize the lock file + //that will mark this gmem as "in use". + intermodule_singleton_helpers::lock_file_logic f(get_shm()); + //If function failed (maybe a competing process has erased the shared + //memory between creation and file locking), retry with a new instance. + if(f.retry_with_new_shm){ + get_shm().~ManagedShMem(); + atomic_write32(&this_module_shm_initialized, Uninitialized); + } + else{ + //Locking succeeded, so this shared memory module-instance is ready + atomic_write32(&this_module_shm_initialized, Initialized); + break; + } + } + catch(...){ + // + throw; + } + } + } +} + +template +struct unlink_shmlogic +{ + unlink_shmlogic(ManagedShMem &mshm) + : mshm_(mshm) + { mshm.atomic_func(*this); } + void operator()() + { + intermodule_singleton_helpers::locking_file_serial_id *pserial_id = + mshm_.template find + ("lock_file_fd").first; + BOOST_ASSERT(0 != pserial_id); + if(1 == atomic_dec32(&pserial_id->modules_attached_to_gmem_count)){ + int fd = pserial_id->fd; + if(fd > 0){ + pserial_id->fd = intermodule_singleton_helpers::GMemMarkToBeRemoved; + std::string s; + intermodule_singleton_helpers::create_and_get_singleton_lock_file_path(s); + delete_file(s.c_str()); + intermodule_singleton_helpers::close_lock_file(fd); + intermodule_singleton_helpers::get_shm_name(s); + shared_memory_object::remove(s.c_str()); + } + } + } + ManagedShMem &mshm_; +}; + +#if defined (BOOST_INTERPROCESS_WINDOWS) + +template<> +struct unlink_shmlogic +{ + unlink_shmlogic(managed_windows_shared_memory &) + {} + void operator()(){} +}; + +#endif + + +template +void intermodule_singleton_common::destroy_shm() +{ + if(!atomic_read32(&this_module_singleton_count)){ + //This module is being unloaded, so destroy + //the shared memory object of this module + //and unlink the shared memory if it's the last + unlink_shmlogic f(get_shm()); + (get_shm()).~ManagedShMem(); + atomic_write32(&this_module_shm_initialized, Uninitialized); + //Do some cleanup for other processes old gmem instances + intermodule_singleton_helpers::managed_sh_dependant::remove_old_gmem(); + } +} + +//Initialize this_module_singleton_ptr, creates the shared memory if needed and also creates an unique +//opaque type in shared memory through a singleton_constructor_t function call, +//initializing the passed pointer to that unique instance. +// +//We have two concurrency types here. a)the shared memory/singleton creation must +//be safe between threads of this process but in different modules/dlls. b) +//the pointer to the singleton is per-module, so we have to protect this +//initization between threads of the same module. +// +//All static variables declared here are shared between inside a module +//so atomic operations will synchronize only threads of the same module. +template +void intermodule_singleton_common::initialize_singleton_logic + (void *&ptr, volatile boost::uint32_t &this_module_singleton_initialized, singleton_constructor_t constructor) +{ + //If current module is not initialized enter to lock free logic + if(atomic_read32(&this_module_singleton_initialized) != Initialized){ + //Now a single thread of the module will succeed in this CAS. + //trying to pass from Uninitialized to Initializing + ::boost::uint32_t previous_module_singleton_initialized = atomic_cas32 + (&this_module_singleton_initialized, Initializing, Uninitialized); + //If the thread succeeded the CAS (winner) it will compete with other + //winner threads from other modules to create the shared memory + if(previous_module_singleton_initialized == Uninitialized){ + try{ + //Now initialize shm, this function solves concurrency issues + //between threads of several modules + initialize_shm(); + //Increment the module reference count that reflects how many + //singletons this module holds, so that we can safely destroy + //module shared memory object when no singleton is left + atomic_inc32(&this_module_singleton_count); + //Now try to create the singleton in shared memory. + //This function solves concurrency issues + //between threads of several modules + void *tmp = constructor(get_shm()); + //Insert a barrier before assigning the pointer to + //make sure this assignment comes after the initialization + atomic_write32(&this_module_singleton_initialized, Initializing); + //Assign the singleton address to the module-local pointer + ptr = tmp; + //Memory barrier inserted, all previous operations should complete + //before this one. Now marked as initialized + atomic_inc32(&this_module_singleton_initialized); + } + catch(...){ + //Mark singleton failed to initialize + atomic_write32(&this_module_singleton_initialized, Broken); + throw; + } + } + //If previous state was initializing, this means that another winner thread is + //trying to initialize the singleton. Just wait until completes its work. + else if(previous_module_singleton_initialized == Initializing){ + while(1){ + previous_module_singleton_initialized = atomic_read32(&this_module_singleton_initialized); + if(previous_module_singleton_initialized >= Initialized){ + //Already initialized, or exception thrown by initializer thread + break; + } + else if(previous_module_singleton_initialized == Initializing){ + detail::thread_yield(); + } + else{ + //This can't be happening! + BOOST_ASSERT(0); + } + } + } + else if(previous_module_singleton_initialized == Initialized){ + //Nothing to do here, the singleton is ready + } + //If previous state was greater than initialized, then memory is broken + //trying to initialize the singleton. + else{//(previous_module_singleton_initialized > Initialized) + throw interprocess_exception("boost::interprocess::intermodule_singleton initialization failed"); + } + } + BOOST_ASSERT(ptr != 0); +} //Now this class is a singleton, initializing the singleton in //the first get() function call if LazyInit is false. If true //then the singleton will be initialized when loading the module. -template +template +class intermodule_singleton_impl +{ + public: + static C& get() //Let's make inlining easy + { + if(!this_module_singleton_ptr){ + if(lifetime.dummy_function()) //This forces lifetime instantiation, for reference counted destruction + intermodule_singleton_common::initialize_singleton_logic + (this_module_singleton_ptr, this_module_singleton_initialized, singleton_constructor); + } + return *static_cast(this_module_singleton_ptr); + } + + private: + + struct ref_count_ptr + { + ref_count_ptr(C *p, boost::uint32_t count) + : ptr(p), singleton_ref_count(count) + {} + C *ptr; + //This reference count serves to count the number of attached + //modules to this singleton + volatile boost::uint32_t singleton_ref_count; + }; + + //These statics will be zero-initialized without any constructor call dependency + //this_module_singleton_ptr will be a module-local pointer to the singleton + static void* this_module_singleton_ptr; + //this_module_singleton_count will be used to synchronize threads of the same module + //for access to a singleton instance, and to flag the state of the + //singleton. + static volatile boost::uint32_t this_module_singleton_initialized; + + //This class destructor will trigger singleton destruction + struct lifetime_type_lazy + { + bool dummy_function() + { return m_dummy == 0; } + + ~lifetime_type_lazy() + { + intermodule_singleton_common::finalize_singleton_logic + (this_module_singleton_ptr, singleton_destructor); + } + //Dummy volatile so that the compiler can't resolve its value at compile-time + //and can't avoid lifetime_type instantiation if dummy_function() is called. + static volatile int m_dummy; + }; + + struct lifetime_type_static + : public lifetime_type_lazy + { + lifetime_type_static() + { + intermodule_singleton_common::initialize_singleton_logic + (this_module_singleton_ptr, this_module_singleton_initialized, singleton_constructor); + } + }; + + typedef typename if_c + ::type lifetime_type; + + static lifetime_type lifetime; + + //A functor to be executed inside shared memory lock that just + //searches for the singleton in shm and if not present creates a new one. + //If singleton constructor throws, the exception is propagated + struct init_atomic_func + { + init_atomic_func(ManagedShMem &m) + : mshm(m) + {} + + void operator()() + { + ref_count_ptr *rcount = mshm.template find(unique_instance).first; + if(!rcount){ + C *p = new C(); + try{ + rcount = mshm.template construct(unique_instance)(p, 0u); + } + catch(...){ + delete p; + throw; + } + } + atomic_inc32(&rcount->singleton_ref_count); + ret_ptr = rcount->ptr; + } + ManagedShMem &mshm; + void *ret_ptr; + }; + + //A functor to be executed inside shared memory lock that just + //deletes the singleton in shm if the attached count reaches to zero + struct fini_atomic_func + { + fini_atomic_func(ManagedShMem &m) + : mshm(m) + {} + + void operator()() + { + ref_count_ptr *rcount = mshm.template find(unique_instance).first; + //The object must exist + BOOST_ASSERT(rcount); + //Check if last reference + if(atomic_dec32(&rcount->singleton_ref_count) == 1){ + //If last, destroy the object + BOOST_ASSERT(rcount->ptr != 0); + delete rcount->ptr; + //Now destroy shm entry + bool destroyed = mshm.template destroy(unique_instance); + (void)destroyed; BOOST_ASSERT(destroyed == true); + } + } + ManagedShMem &mshm; + void *ret_ptr; + }; + + //A wrapper to execute init_atomic_func + static void *singleton_constructor(ManagedShMem &mshm) + { + init_atomic_func f(mshm); + mshm.atomic_func(f); + return f.ret_ptr; + } + + //A wrapper to execute fini_atomic_func + static void singleton_destructor(void *p, ManagedShMem &mshm) + { (void)p; + fini_atomic_func f(mshm); + mshm.atomic_func(f); + } +}; + +template +volatile int intermodule_singleton_impl::lifetime_type_lazy::m_dummy; + +//These will be zero-initialized by the loader +template +void *intermodule_singleton_impl::this_module_singleton_ptr; + +template +volatile boost::uint32_t intermodule_singleton_impl::this_module_singleton_initialized; + +template +typename intermodule_singleton_impl::lifetime_type + intermodule_singleton_impl::lifetime; + +template +class portable_intermodule_singleton + : public intermodule_singleton_impl +{}; + +#ifdef BOOST_INTERPROCESS_WINDOWS + +template +class windows_intermodule_singleton + : public intermodule_singleton_impl +{}; + +#endif + +//Now this class is a singleton, initializing the singleton in +//the first get() function call if LazyInit is false. If true +//then the singleton will be initialized when loading the module. +template class intermodule_singleton #ifdef BOOST_INTERPROCESS_WINDOWS - : public windows_intermodule_singleton + : public windows_intermodule_singleton +// : public portable_intermodule_singleton #else - : public portable_intermodule_singleton + : public portable_intermodule_singleton #endif {}; -} //namespace ipcdetail{ + +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ diff --git a/utils/boost_idb/boost/interprocess/detail/intermodule_singleton_common.hpp b/utils/boost_idb/boost/interprocess/detail/intermodule_singleton_common.hpp deleted file mode 100644 index 60ec5939..00000000 --- a/utils/boost_idb/boost/interprocess/detail/intermodule_singleton_common.hpp +++ /dev/null @@ -1,499 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_INTERMODULE_SINGLETON_COMMON_HPP -#define BOOST_INTERPROCESS_INTERMODULE_SINGLETON_COMMON_HPP - -#if defined(_MSC_VER)&&(_MSC_VER>=1200) -#pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace interprocess{ -namespace ipcdetail{ - -namespace intermodule_singleton_helpers { - -inline void get_pid_creation_time_str(std::string &s) -{ - std::stringstream stream; - stream << get_current_process_id() << '_'; - stream.precision(6); - stream << std::fixed << get_current_process_creation_time(); - s = stream.str(); -} - -inline const char *get_map_base_name() -{ return "bip.gmem.map."; } - -inline void get_map_name(std::string &map_name) -{ - get_pid_creation_time_str(map_name); - map_name.insert(0, get_map_base_name()); -} - -inline std::size_t get_map_size() -{ return 65536; } - -template -struct thread_safe_global_map_dependant; - -} //namespace intermodule_singleton_helpers { - -//This class contains common code for all singleton types, so that we instantiate this -//code just once per module. This class also holds a thread soafe global map -//to be used by all instances protected with a reference count -template -class intermodule_singleton_common -{ - public: - typedef void*(singleton_constructor_t)(ThreadSafeGlobalMap &); - typedef void (singleton_destructor_t)(void *, ThreadSafeGlobalMap &); - - static const ::boost::uint32_t Uninitialized = 0u; - static const ::boost::uint32_t Initializing = 1u; - static const ::boost::uint32_t Initialized = 2u; - static const ::boost::uint32_t Broken = 3u; - static const ::boost::uint32_t Destroyed = 4u; - - //Initialize this_module_singleton_ptr, creates the global map if needed and also creates an unique - //opaque type in global map through a singleton_constructor_t function call, - //initializing the passed pointer to that unique instance. - // - //We have two concurrency types here. a)the global map/singleton creation must - //be safe between threads of this process but in different modules/dlls. b) - //the pointer to the singleton is per-module, so we have to protect this - //initization between threads of the same module. - // - //All static variables declared here are shared between inside a module - //so atomic operations will synchronize only threads of the same module. - static void initialize_singleton_logic - (void *&ptr, volatile boost::uint32_t &this_module_singleton_initialized, singleton_constructor_t constructor, bool phoenix) - { - //If current module is not initialized enter to lock free logic - if(atomic_read32(&this_module_singleton_initialized) != Initialized){ - //Now a single thread of the module will succeed in this CAS. - //trying to pass from Uninitialized to Initializing - ::boost::uint32_t previous_module_singleton_initialized = atomic_cas32 - (&this_module_singleton_initialized, Initializing, Uninitialized); - //If the thread succeeded the CAS (winner) it will compete with other - //winner threads from other modules to create the global map - if(previous_module_singleton_initialized == Destroyed){ - //Trying to resurrect a dead Phoenix singleton. Just try to - //mark it as uninitialized and start again - if(phoenix){ - atomic_cas32(&this_module_singleton_initialized, Uninitialized, Destroyed); - previous_module_singleton_initialized = atomic_cas32 - (&this_module_singleton_initialized, Initializing, Uninitialized); - } - //Trying to resurrect a non-Phoenix dead singleton is an error - else{ - throw interprocess_exception("Boost.Interprocess: Dead reference on non-Phoenix singleton of type"); - } - } - if(previous_module_singleton_initialized == Uninitialized){ - try{ - //Now initialize the global map, this function must solve concurrency - //issues between threads of several modules - initialize_global_map_handle(); - //Now try to create the singleton in global map. - //This function solves concurrency issues - //between threads of several modules - void *tmp = constructor(get_map()); - //Increment the module reference count that reflects how many - //singletons this module holds, so that we can safely destroy - //module global map object when no singleton is left - atomic_inc32(&this_module_singleton_count); - //Insert a barrier before assigning the pointer to - //make sure this assignment comes after the initialization - atomic_write32(&this_module_singleton_initialized, Initializing); - //Assign the singleton address to the module-local pointer - ptr = tmp; - //Memory barrier inserted, all previous operations should complete - //before this one. Now marked as initialized - atomic_write32(&this_module_singleton_initialized, Initialized); - } - catch(...){ - //Mark singleton failed to initialize - atomic_write32(&this_module_singleton_initialized, Broken); - throw; - } - } - //If previous state was initializing, this means that another winner thread is - //trying to initialize the singleton. Just wait until completes its work. - else if(previous_module_singleton_initialized == Initializing){ - spin_wait swait; - while(1){ - previous_module_singleton_initialized = atomic_read32(&this_module_singleton_initialized); - if(previous_module_singleton_initialized >= Initialized){ - //Already initialized, or exception thrown by initializer thread - break; - } - else if(previous_module_singleton_initialized == Initializing){ - swait.yield(); - } - else{ - //This can't be happening! - BOOST_ASSERT(0); - } - } - } - else if(previous_module_singleton_initialized == Initialized){ - //Nothing to do here, the singleton is ready - } - //If previous state was greater than initialized, then memory is broken - //trying to initialize the singleton. - else{//(previous_module_singleton_initialized > Initialized) - throw interprocess_exception("boost::interprocess::intermodule_singleton initialization failed"); - } - } - BOOST_ASSERT(ptr != 0); - } - - static void finalize_singleton_logic(void *&ptr, volatile boost::uint32_t &this_module_singleton_initialized, singleton_destructor_t destructor) - { - //Protect destruction against lazy singletons not initialized in this execution - if(ptr){ - //Note: this destructor might provoke a Phoenix singleton - //resurrection. This means that this_module_singleton_count - //might change after this call. - destructor(ptr, get_map()); - ptr = 0; - - //Memory barrier to make sure pointer is nulled. - //Mark this singleton as destroyed. - atomic_write32(&this_module_singleton_initialized, Destroyed); - - //If this is the last singleton of this module - //apply map destruction. - //Note: singletons are destroyed when the module is unloaded - //so no threads should be executing or holding references - //to this module - if(1 == atomic_dec32(&this_module_singleton_count)){ - destroy_global_map_handle(); - } - } - } - - private: - static ThreadSafeGlobalMap &get_map() - { - return *static_cast(static_cast(&mem_holder.map_mem[0])); - } - - static void initialize_global_map_handle() - { - //Obtain unique map name and size - spin_wait swait; - while(1){ - //Try to pass map state to initializing - ::boost::uint32_t tmp = atomic_cas32(&this_module_map_initialized, Initializing, Uninitialized); - if(tmp == Initialized || tmp == Broken){ - break; - } - else if(tmp == Destroyed){ - tmp = atomic_cas32(&this_module_map_initialized, Uninitialized, Destroyed); - continue; - } - //If some other thread is doing the work wait - else if(tmp == Initializing){ - swait.yield(); - } - else{ //(tmp == Uninitialized) - //If not initialized try it again? - try{ - //Remove old global map from the system - intermodule_singleton_helpers::thread_safe_global_map_dependant::remove_old_gmem(); - //in-place construction of the global map class - intermodule_singleton_helpers::thread_safe_global_map_dependant - ::construct_map(static_cast(&get_map())); - //Use global map's internal lock to initialize the lock file - //that will mark this gmem as "in use". - typename intermodule_singleton_helpers::thread_safe_global_map_dependant:: - lock_file_logic f(get_map()); - //If function failed (maybe a competing process has erased the shared - //memory between creation and file locking), retry with a new instance. - if(f.retry()){ - get_map().~ThreadSafeGlobalMap(); - atomic_write32(&this_module_map_initialized, Destroyed); - } - else{ - //Locking succeeded, so this global map module-instance is ready - atomic_write32(&this_module_map_initialized, Initialized); - break; - } - } - catch(...){ - // - throw; - } - } - } - } - - static void destroy_global_map_handle() - { - if(!atomic_read32(&this_module_singleton_count)){ - //This module is being unloaded, so destroy - //the global map object of this module - //and unlink the global map if it's the last - typename intermodule_singleton_helpers::thread_safe_global_map_dependant:: - unlink_map_logic f(get_map()); - (get_map()).~ThreadSafeGlobalMap(); - atomic_write32(&this_module_map_initialized, Destroyed); - //Do some cleanup for other processes old gmem instances - intermodule_singleton_helpers::thread_safe_global_map_dependant::remove_old_gmem(); - } - } - - //Static data, zero-initalized without any dependencies - //this_module_singleton_count is the number of singletons used by this module - static volatile boost::uint32_t this_module_singleton_count; - - //this_module_map_initialized is the state of this module's map class object. - //Values: Uninitialized, Initializing, Initialized, Broken - static volatile boost::uint32_t this_module_map_initialized; - - //Raw memory to construct the global map manager - static struct mem_holder_t - { - ::boost::detail::max_align aligner; - char map_mem [sizeof(ThreadSafeGlobalMap)]; - } mem_holder; -}; - -template -volatile boost::uint32_t intermodule_singleton_common::this_module_singleton_count; - -template -volatile boost::uint32_t intermodule_singleton_common::this_module_map_initialized; - -template -typename intermodule_singleton_common::mem_holder_t - intermodule_singleton_common::mem_holder; - -//A reference count to be stored in global map holding the number -//of singletons (one per module) attached to the instance pointed by -//the internal ptr. -struct ref_count_ptr -{ - ref_count_ptr(void *p, boost::uint32_t count) - : ptr(p), singleton_ref_count(count) - {} - void *ptr; - //This reference count serves to count the number of attached - //modules to this singleton - volatile boost::uint32_t singleton_ref_count; -}; - - -//Now this class is a singleton, initializing the singleton in -//the first get() function call if LazyInit is true. If false -//then the singleton will be initialized when loading the module. -template -class intermodule_singleton_impl -{ - public: - - static C& get() //Let's make inlining easy - { - if(!this_module_singleton_ptr){ - if(lifetime.dummy_function()){ //This forces lifetime instantiation, for reference counted destruction - atentry_work(); - } - } - return *static_cast(this_module_singleton_ptr); - } - - private: - - static void atentry_work() - { - intermodule_singleton_common::initialize_singleton_logic - (this_module_singleton_ptr, this_module_singleton_initialized, singleton_constructor, Phoenix); - } - - static void atexit_work() - { - intermodule_singleton_common::finalize_singleton_logic - (this_module_singleton_ptr, this_module_singleton_initialized, singleton_destructor); - } - - //These statics will be zero-initialized without any constructor call dependency - //this_module_singleton_ptr will be a module-local pointer to the singleton - static void* this_module_singleton_ptr; - - //this_module_singleton_count will be used to synchronize threads of the same module - //for access to a singleton instance, and to flag the state of the - //singleton. - static volatile boost::uint32_t this_module_singleton_initialized; - - //This class destructor will trigger singleton destruction - struct lifetime_type_lazy - { - bool dummy_function() - { return m_dummy == 0; } - - ~lifetime_type_lazy() - { - if(!Phoenix){ - atexit_work(); - } - } - - //Dummy volatile so that the compiler can't resolve its value at compile-time - //and can't avoid lifetime_type instantiation if dummy_function() is called. - static volatile int m_dummy; - }; - - struct lifetime_type_static - : public lifetime_type_lazy - { - lifetime_type_static() - { atentry_work(); } - }; - - typedef typename if_c - ::type lifetime_type; - - static lifetime_type lifetime; - - //A functor to be executed inside global map lock that just - //searches for the singleton in map and if not present creates a new one. - //If singleton constructor throws, the exception is propagated - struct init_atomic_func - { - init_atomic_func(ThreadSafeGlobalMap &m) - : m_map(m) - {} - - void operator()() - { - ref_count_ptr *rcount = intermodule_singleton_helpers::thread_safe_global_map_dependant - ::find(m_map, typeid(C).name()); - if(!rcount){ - C *p = new C; - try{ - ref_count_ptr val(p, 0u); - rcount = intermodule_singleton_helpers::thread_safe_global_map_dependant - ::insert(m_map, typeid(C).name(), val); - } - catch(...){ - intermodule_singleton_helpers::thread_safe_global_map_dependant - ::erase(m_map, typeid(C).name()); - delete p; - throw; - } - } - if(Phoenix){ - std::atexit(&atexit_work); - } - atomic_inc32(&rcount->singleton_ref_count); - ret_ptr = rcount->ptr; - } - void *data() const - { return ret_ptr; } - - private: - ThreadSafeGlobalMap &m_map; - void *ret_ptr; - }; - - //A functor to be executed inside global map lock that just - //deletes the singleton in map if the attached count reaches to zero - struct fini_atomic_func - { - fini_atomic_func(ThreadSafeGlobalMap &m) - : m_map(m) - {} - - void operator()() - { - ref_count_ptr *rcount = intermodule_singleton_helpers::thread_safe_global_map_dependant - ::find(m_map, typeid(C).name()); - //The object must exist - BOOST_ASSERT(rcount); - BOOST_ASSERT(rcount->singleton_ref_count > 0); - //Check if last reference - if(atomic_dec32(&rcount->singleton_ref_count) == 1){ - //If last, destroy the object - BOOST_ASSERT(rcount->ptr != 0); - C *pc = static_cast(rcount->ptr); - //Now destroy map entry - bool destroyed = intermodule_singleton_helpers::thread_safe_global_map_dependant - ::erase(m_map, typeid(C).name()); - (void)destroyed; BOOST_ASSERT(destroyed == true); - delete pc; - } - } - void *data() const - { return ret_ptr; } - - private: - ThreadSafeGlobalMap &m_map; - void *ret_ptr; - }; - - //A wrapper to execute init_atomic_func - static void *singleton_constructor(ThreadSafeGlobalMap &map) - { - init_atomic_func f(map); - intermodule_singleton_helpers::thread_safe_global_map_dependant - ::atomic_func(map, f); - return f.data(); - } - - //A wrapper to execute fini_atomic_func - static void singleton_destructor(void *p, ThreadSafeGlobalMap &map) - { (void)p; - fini_atomic_func f(map); - intermodule_singleton_helpers::thread_safe_global_map_dependant - ::atomic_func(map, f); - } -}; - -template -volatile int intermodule_singleton_impl::lifetime_type_lazy::m_dummy = 0; - -//These will be zero-initialized by the loader -template -void *intermodule_singleton_impl::this_module_singleton_ptr = 0; - -template -volatile boost::uint32_t intermodule_singleton_impl::this_module_singleton_initialized = 0; - -template -typename intermodule_singleton_impl::lifetime_type - intermodule_singleton_impl::lifetime; - -} //namespace ipcdetail{ -} //namespace interprocess{ -} //namespace boost{ - -#include - -#endif //#ifndef BOOST_INTERPROCESS_INTERMODULE_SINGLETON_COMMON_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/interprocess_tester.hpp b/utils/boost_idb/boost/interprocess/detail/interprocess_tester.hpp index 2fcc07bc..613bffd8 100644 --- a/utils/boost_idb/boost/interprocess/detail/interprocess_tester.hpp +++ b/utils/boost_idb/boost/interprocess/detail/interprocess_tester.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2007-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2007-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -13,7 +13,7 @@ namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ class interprocess_tester { @@ -23,7 +23,7 @@ class interprocess_tester { t.dont_close_on_destruction(); } }; -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ diff --git a/utils/boost_idb/boost/interprocess/detail/intersegment_ptr.hpp b/utils/boost_idb/boost/interprocess/detail/intersegment_ptr.hpp index ca2ff4ac..9151844a 100644 --- a/utils/boost_idb/boost/interprocess/detail/intersegment_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/detail/intersegment_ptr.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -68,8 +68,8 @@ struct intersegment_base static const std::size_t begin_bits = max_segment_size_bits - align_bits; static const std::size_t pow_size_bits_helper = static_log2::value; - static const std::size_t pow_size_bits = - (max_segment_size_bits == (std::size_t(1) << pow_size_bits_helper)) ? + static const std::size_t pow_size_bits = + (max_segment_size_bits == (std::size_t(1) << pow_size_bits_helper)) ? pow_size_bits_helper : pow_size_bits_helper + 1; static const std::size_t frc_size_bits = size_t_bits - ctrl_bits - begin_bits - pow_size_bits; @@ -97,7 +97,7 @@ struct intersegment_base std::size_t pow : pow_size_bits; std::size_t frc : frc_size_bits; std::size_t beg : begin_bits; - std::ptrdiff_t off : sizeof(std::ptrdiff_t)*CHAR_BIT - 2; + std::ptrdiff_t off : sizeof(ptrdiff_t)*CHAR_BIT - 2; std::ptrdiff_t bits : 2; }; @@ -153,13 +153,13 @@ struct intersegment_base { if(orig_size < align) orig_size = align; - orig_size = ipcdetail::get_rounded_size_po2(orig_size, align); - pow = ipcdetail::floor_log2(orig_size); + orig_size = detail::get_rounded_size_po2(orig_size, align); + pow = detail::floor_log2(orig_size); std::size_t low_size = (std::size_t(1) << pow); std::size_t diff = orig_size - low_size; BOOST_ASSERT(pow >= frc_size_bits); - std::size_t rounded = ipcdetail::get_rounded_size_po2 - (diff, (std::size_t)(1u << (pow - frc_size_bits))); + std::size_t rounded = detail::get_rounded_size_po2 + (diff, (1u << (pow - frc_size_bits))); if(rounded == low_size){ ++pow; frc = 0; @@ -177,7 +177,7 @@ struct intersegment_base void set_mode(std::size_t mode) { - BOOST_ASSERT(mode < is_max_mode); + BOOST_ASSERT(mode < is_max_mode); members.direct.ctrl = mode; } @@ -185,7 +185,7 @@ struct intersegment_base //!null pointer bool is_null() const { - return (this->get_mode() < is_relative) && + return (this->get_mode() < is_relative) && !members.direct.dummy && !members.direct.addr; } @@ -226,7 +226,7 @@ struct flat_map_intersegment //!Obtains the address pointed //!by the object - void *to_raw_pointer() const + void *get_pointer() const { if(is_null()){ return 0; @@ -259,23 +259,23 @@ struct flat_map_intersegment //!This only works with two basic_intersegment_ptr pointing //!to the same segment. Otherwise undefined std::ptrdiff_t diff(const self_t &other) const - { return static_cast(this->to_raw_pointer()) - static_cast(other.to_raw_pointer()); } + { return static_cast(this->get_pointer()) - static_cast(other.get_pointer()); } //!Returns true if both point to //!the same object bool equal(const self_t &y) const - { return this->to_raw_pointer() == y.to_raw_pointer(); } + { return this->get_pointer() == y.get_pointer(); } //!Returns true if *this is less than other. //!This only works with two basic_intersegment_ptr pointing //!to the same segment group. Otherwise undefined. Never throws bool less(const self_t &y) const - { return this->to_raw_pointer() < y.to_raw_pointer(); } + { return this->get_pointer() < y.get_pointer(); } void swap(self_t &other) { - void *ptr_this = this->to_raw_pointer(); - void *ptr_other = other.to_raw_pointer(); + void *ptr_this = this->get_pointer(); + void *ptr_other = other.get_pointer(); other.set_from_pointer(ptr_this); this->set_from_pointer(ptr_other); } @@ -309,13 +309,13 @@ struct flat_map_intersegment void *ptr_base; void *this_base; get_segment_info_and_offset(this, this_info, this_offset, this_base); - + if(!this_info.group){ this->set_mode(is_in_stack); this->members.direct.addr = const_cast(ptr); } else{ - get_segment_info_and_offset(ptr, ptr_info, ptr_offset, ptr_base); + get_segment_info_and_offset(ptr, ptr_info, ptr_offset, ptr_base); if(ptr_info.group != this_info.group){ this->set_mode(is_pointee_outside); @@ -340,25 +340,25 @@ struct flat_map_intersegment } } - //!Sets the object internals to represent the address pointed + //!Sets the object internals to represent the address pointed //!by another flat_map_intersegment void set_from_other(const self_t &other) { - this->set_from_pointer(other.to_raw_pointer()); + this->set_from_pointer(other.get_pointer()); } //!Increments internal //!offset void inc_offset(std::ptrdiff_t bytes) { - this->set_from_pointer(static_cast(this->to_raw_pointer()) + bytes); + this->set_from_pointer(static_cast(this->get_pointer()) + bytes); } //!Decrements internal //!offset void dec_offset(std::ptrdiff_t bytes) { - this->set_from_pointer(static_cast(this->to_raw_pointer()) - bytes); + this->set_from_pointer(static_cast(this->get_pointer()) - bytes); } ////////////////////////////////////// @@ -383,7 +383,7 @@ struct flat_map_intersegment }; vector m_segments; multi_segment_services &m_ms_services; - + public: segment_group_t(multi_segment_services &ms_services) : m_ms_services(ms_services) @@ -434,7 +434,7 @@ struct flat_map_intersegment typedef set segment_groups_t; typedef boost::interprocess::flat_map - > ptr_to_segment_info_t; @@ -443,9 +443,9 @@ struct flat_map_intersegment //!Mutex to preserve integrity in multi-threaded //!enviroments typedef Mutex mutex_type; - //!Maps base addresses and segment information + //!Maps base addresses and segment information //!(size and segment group and id)* - + ptr_to_segment_info_t m_ptr_to_segment_info; ~mappings_t() @@ -476,7 +476,7 @@ struct flat_map_intersegment return; } //Find the first base address greater than ptr - typename ptr_to_segment_info_t::iterator it + typename ptr_to_segment_info_t::iterator it = s_map.m_ptr_to_segment_info.upper_bound(ptr); if(it == s_map.m_ptr_to_segment_info.begin()){ segment = segment_info_t(); @@ -486,7 +486,7 @@ struct flat_map_intersegment --it; char * segment_base = const_cast(reinterpret_cast(it->first)); std::size_t segment_size = it->second.size; - + if(segment_base <= reinterpret_cast(ptr) && (segment_base + segment_size) >= reinterpret_cast(ptr)){ segment = it->second; @@ -552,7 +552,7 @@ struct flat_map_intersegment s_groups.insert(segment_group_t(*services)); BOOST_ASSERT(ret.second); return &*ret.first; - } + } } static bool delete_group(segment_group_id id) @@ -574,23 +574,23 @@ struct flat_map_intersegment } } return success; - } + } } }; //!Static map-segment_info associated with //!flat_map_intersegment<> template -typename flat_map_intersegment::mappings_t +typename flat_map_intersegment::mappings_t flat_map_intersegment::s_map; //!Static segment group container associated with //!flat_map_intersegment<> template -typename flat_map_intersegment::segment_groups_t +typename flat_map_intersegment::segment_groups_t flat_map_intersegment::s_groups; -//!A smart pointer that can point to a pointee that resides in another memory +//!A smart pointer that can point to a pointee that resides in another memory //!memory mapped or shared memory segment. template class intersegment_ptr : public flat_map_intersegment @@ -604,7 +604,7 @@ class intersegment_ptr : public flat_map_intersegment public: typedef T * pointer; - typedef typename ipcdetail::add_reference::type reference; + typedef typename detail::add_reference::type reference; typedef T value_type; typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; @@ -623,57 +623,57 @@ class intersegment_ptr : public flat_map_intersegment //!Constructor from other intersegment_ptr //!Never throws - intersegment_ptr(const intersegment_ptr& ptr) + intersegment_ptr(const intersegment_ptr& ptr) { base_t::set_from_other(ptr); } - //!Constructor from other intersegment_ptr. If pointers of pointee types are + //!Constructor from other intersegment_ptr. If pointers of pointee types are //!convertible, intersegment_ptrs will be convertibles. Never throws. template - intersegment_ptr(const intersegment_ptr &ptr) + intersegment_ptr(const intersegment_ptr &ptr) { pointer p(ptr.get()); (void)p; base_t::set_from_other(ptr); } //!Emulates static_cast operator. //!Never throws. template - intersegment_ptr(const intersegment_ptr &r, ipcdetail::static_cast_tag) + intersegment_ptr(const intersegment_ptr &r, detail::static_cast_tag) { base_t::set_from_pointer(static_cast(r.get())); } //!Emulates const_cast operator. //!Never throws. template - intersegment_ptr(const intersegment_ptr &r, ipcdetail::const_cast_tag) + intersegment_ptr(const intersegment_ptr &r, detail::const_cast_tag) { base_t::set_from_pointer(const_cast(r.get())); } //!Emulates dynamic_cast operator. //!Never throws. template - intersegment_ptr(const intersegment_ptr &r, ipcdetail::dynamic_cast_tag) + intersegment_ptr(const intersegment_ptr &r, detail::dynamic_cast_tag) { base_t::set_from_pointer(dynamic_cast(r.get())); } //!Emulates reinterpret_cast operator. //!Never throws. template - intersegment_ptr(const intersegment_ptr &r, ipcdetail::reinterpret_cast_tag) + intersegment_ptr(const intersegment_ptr &r, detail::reinterpret_cast_tag) { base_t::set_from_pointer(reinterpret_cast(r.get())); } //!Obtains raw pointer from offset. //!Never throws. pointer get()const - { return static_cast(base_t::to_raw_pointer()); } + { return static_cast(base_t::get_pointer()); } //!Pointer-like -> operator. It can return 0 pointer. //!Never throws. - pointer operator->() const + pointer operator->() const { return self_t::get(); } - //!Dereferencing operator, if it is a null intersegment_ptr behavior + //!Dereferencing operator, if it is a null intersegment_ptr behavior //!is undefined. Never throws. - reference operator* () const + reference operator* () const { return *(self_t::get()); } //!Indexing operator. //!Never throws. - reference operator[](std::ptrdiff_t idx) const + reference operator[](std::ptrdiff_t idx) const { return self_t::get()[idx]; } //!Assignment from pointer (saves extra conversion). @@ -686,19 +686,19 @@ class intersegment_ptr : public flat_map_intersegment intersegment_ptr& operator= (const intersegment_ptr &ptr) { base_t::set_from_other(ptr); return *this; } - //!Assignment from related intersegment_ptr. If pointers of pointee types + //!Assignment from related intersegment_ptr. If pointers of pointee types //!are assignable, intersegment_ptrs will be assignable. Never throws. template intersegment_ptr& operator= (const intersegment_ptr & ptr) - { - pointer p(ptr.get()); (void)p; - base_t::set_from_other(ptr); return *this; + { + pointer p(ptr.get()); (void)p; + base_t::set_from_other(ptr); return *this; } - + //!intersegment_ptr + std::ptrdiff_t. //!Never throws. - intersegment_ptr operator+ (std::ptrdiff_t idx) const - { + intersegment_ptr operator+ (std::ptrdiff_t idx) const + { intersegment_ptr result (*this); result.inc_offset(idx*sizeof(T)); return result; @@ -706,8 +706,8 @@ class intersegment_ptr : public flat_map_intersegment //!intersegment_ptr - std::ptrdiff_t. //!Never throws. - intersegment_ptr operator- (std::ptrdiff_t idx) const - { + intersegment_ptr operator- (std::ptrdiff_t idx) const + { intersegment_ptr result (*this); result.dec_offset(idx*sizeof(T)); return result; @@ -727,7 +727,7 @@ class intersegment_ptr : public flat_map_intersegment //!Never throws. intersegment_ptr& operator++ (void) { base_t::inc_offset(sizeof(T)); return *this; } - + //!intersegment_ptr++. //!Never throws. intersegment_ptr operator++ (int) @@ -745,10 +745,10 @@ class intersegment_ptr : public flat_map_intersegment //!Safe bool conversion operator. //!Never throws. - operator unspecified_bool_type() const + operator unspecified_bool_type() const { return base_t::is_null()? 0 : &self_t::unspecified_bool_type_func; } - //!Not operator. Not needed in theory, but improves portability. + //!Not operator. Not needed in theory, but improves portability. //!Never throws. bool operator! () const { return base_t::is_null(); } @@ -762,7 +762,7 @@ class intersegment_ptr : public flat_map_intersegment //!This only works with two basic_intersegment_ptr pointing //!to the same segment. Otherwise undefined template - std::ptrdiff_t _diff(const intersegment_ptr &other) const + ptrdiff_t _diff(const intersegment_ptr &other) const { return base_t::diff(other); } //!Returns true if both point to the @@ -784,12 +784,12 @@ class intersegment_ptr : public flat_map_intersegment template inline bool operator ==(const intersegment_ptr &left, const intersegment_ptr &right) -{ +{ //Make sure both pointers can be compared bool e = typename intersegment_ptr::pointer(0) == typename intersegment_ptr::pointer(0); (void)e; - return left._equal(right); + return left._equal(right); } //!Returns true if *this is less than other. @@ -798,104 +798,104 @@ bool operator ==(const intersegment_ptr &left, template inline bool operator <(const intersegment_ptr &left, const intersegment_ptr &right) -{ +{ //Make sure both pointers can be compared bool e = typename intersegment_ptr::pointer(0) < typename intersegment_ptr::pointer(0); (void)e; - return left._less(right); + return left._less(right); } template inline -bool operator!= (const intersegment_ptr &pt1, +bool operator!= (const intersegment_ptr &pt1, const intersegment_ptr &pt2) { return !(pt1 ==pt2); } //!intersegment_ptr <= intersegment_ptr. //!Never throws. template inline -bool operator<= (const intersegment_ptr &pt1, +bool operator<= (const intersegment_ptr &pt1, const intersegment_ptr &pt2) { return !(pt1 > pt2); } //!intersegment_ptr > intersegment_ptr. //!Never throws. template inline -bool operator> (const intersegment_ptr &pt1, +bool operator> (const intersegment_ptr &pt1, const intersegment_ptr &pt2) { return (pt2 < pt1); } //!intersegment_ptr >= intersegment_ptr. //!Never throws. template inline -bool operator>= (const intersegment_ptr &pt1, +bool operator>= (const intersegment_ptr &pt1, const intersegment_ptr &pt2) { return !(pt1 < pt2); } //!operator<< template inline -std::basic_ostream & operator<< +std::basic_ostream & operator<< (std::basic_ostream & os, const intersegment_ptr & p) { return os << p.get(); } //!operator>> template inline -std::basic_istream & operator>> +std::basic_istream & operator>> (std::basic_istream & os, intersegment_ptr & p) { U * tmp; return os >> tmp; p = tmp; } -//!std::ptrdiff_t + intersegment_ptr. +//!std::ptrdiff_t + intersegment_ptr. //!The result is another pointer of the same segment template inline intersegment_ptr operator+ (std::ptrdiff_t diff, const intersegment_ptr& right) { return right + diff; } -//!intersegment_ptr - intersegment_ptr. +//!intersegment_ptr - intersegment_ptr. //!This only works with two intersegment_ptr-s that point to the //!same segment template inline -std::ptrdiff_t operator- (const intersegment_ptr &pt, +std::ptrdiff_t operator- (const intersegment_ptr &pt, const intersegment_ptr &pt2) { return pt._diff(pt2)/sizeof(T); } //! swap specialization template inline -void swap (boost::interprocess::intersegment_ptr &pt, +void swap (boost::interprocess::intersegment_ptr &pt, boost::interprocess::intersegment_ptr &pt2) { pt.swap(pt2); } -//!to_raw_pointer() enables boost::mem_fn to recognize intersegment_ptr. +//!get_pointer() enables boost::mem_fn to recognize intersegment_ptr. //!Never throws. template inline -T * to_raw_pointer(boost::interprocess::intersegment_ptr const & p) +T * get_pointer(boost::interprocess::intersegment_ptr const & p) { return p.get(); } //!Simulation of static_cast between pointers. //!Never throws. -template inline +template inline boost::interprocess::intersegment_ptr static_pointer_cast(const boost::interprocess::intersegment_ptr &r) -{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::ipcdetail::static_cast_tag()); } +{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::detail::static_cast_tag()); } //!Simulation of const_cast between pointers. //!Never throws. -template inline +template inline boost::interprocess::intersegment_ptr const_pointer_cast(const boost::interprocess::intersegment_ptr &r) -{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::ipcdetail::const_cast_tag()); } +{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::detail::const_cast_tag()); } //!Simulation of dynamic_cast between pointers. //!Never throws. -template inline +template inline boost::interprocess::intersegment_ptr dynamic_pointer_cast(const boost::interprocess::intersegment_ptr &r) -{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::ipcdetail::dynamic_cast_tag()); } +{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::detail::dynamic_cast_tag()); } //!Simulation of reinterpret_cast between pointers. //!Never throws. template inline boost::interprocess::intersegment_ptr reinterpret_pointer_cast(const boost::interprocess::intersegment_ptr &r) -{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::ipcdetail::reinterpret_cast_tag()); } +{ return boost::interprocess::intersegment_ptr(r, boost::interprocess::detail::reinterpret_cast_tag()); } -//!Trait class to detect if an smart pointer has +//!Trait class to detect if an smart pointer has //!multi-segment addressing capabilities. template struct is_multisegment_ptr @@ -907,10 +907,10 @@ struct is_multisegment_ptr } //namespace interprocess { #if defined(_MSC_VER) && (_MSC_VER < 1400) -//!to_raw_pointer() enables boost::mem_fn to recognize intersegment_ptr. +//!get_pointer() enables boost::mem_fn to recognize intersegment_ptr. //!Never throws. template inline -T * to_raw_pointer(boost::interprocess::intersegment_ptr const & p) +T * get_pointer(boost::interprocess::intersegment_ptr const & p) { return p.get(); } #endif @@ -918,18 +918,20 @@ T * to_raw_pointer(boost::interprocess::intersegment_ptr const & p) //!for optimizations template struct has_trivial_constructor - < boost::interprocess::intersegment_ptr > + < boost::interprocess::intersegment_ptr > : public true_type{}; //!has_trivial_destructor<> == true_type specialization //!for optimizations template struct has_trivial_destructor - < boost::interprocess::intersegment_ptr > + < boost::interprocess::intersegment_ptr > : public true_type{}; } //namespace boost { +#include + #if 0 //bits @@ -950,7 +952,7 @@ struct has_trivial_destructor // std::size_t offset; //RELATIVE_SIZE_BITS = SIZE_T_BITS - -// MAX_SEGMENT_BITS - +// MAX_SEGMENT_BITS - // CTRL_BITS 10 10 //MAX_SEGMENT_SIZE = SIZE_T_BITS - ALIGN_BITS 20 52 @@ -980,7 +982,7 @@ struct has_trivial_destructor //!Obtains the address pointed by the //!object -void *to_raw_pointer() const +void *get_pointer() const { if(this->is_pointee_outside() || this->is_in_stack()){ return raw_address(); @@ -1031,10 +1033,9 @@ void set_from_pointer(const void *ptr) } void set_from_other(const self_t &other) -{ this->set_from_pointer(other.to_raw_pointer()); } +{ this->set_from_pointer(other.get_pointer()); } #endif -#include - #endif //#ifndef BOOST_INTERPROCESS_INTERSEGMENT_PTR_HPP + diff --git a/utils/boost_idb/boost/interprocess/detail/managed_global_memory.hpp b/utils/boost_idb/boost/interprocess/detail/managed_global_memory.hpp deleted file mode 100644 index 548e17d9..00000000 --- a/utils/boost_idb/boost/interprocess/detail/managed_global_memory.hpp +++ /dev/null @@ -1,115 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_BASIC_GLOBAL_MEMORY_HPP -#define BOOST_INTERPROCESS_BASIC_GLOBAL_MEMORY_HPP - -#if defined(_MSC_VER)&&(_MSC_VER>=1200) -#pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace interprocess{ -namespace ipcdetail{ - -struct intermodule_singleton_mutex_family -{ - typedef boost::interprocess::ipcdetail::spin_mutex mutex_type; - typedef boost::interprocess::ipcdetail::spin_recursive_mutex recursive_mutex_type; -}; - -struct intermodule_types -{ - //We must use offset_ptr since a loaded DLL can map the singleton holder shared memory - //at a different address than other DLLs or the main executable - typedef rbtree_best_fit > mem_algo; - template - struct open_or_create - { - typedef managed_open_or_create_impl - type; - }; -}; - -//we must implement our own managed shared memory to avoid circular dependencies -template -class basic_managed_global_memory - : public basic_managed_memory_impl - < char - , intermodule_types::mem_algo - , iset_index - , intermodule_types::open_or_create::type::ManagedOpenOrCreateUserOffset - > - , private intermodule_types::open_or_create::type -{ - /// @cond - typedef typename intermodule_types::template open_or_create::type base2_t; - - typedef basic_managed_memory_impl - < char - , intermodule_types::mem_algo - , iset_index - , base2_t::ManagedOpenOrCreateUserOffset - > base_t; - - typedef create_open_func create_open_func_t; - - basic_managed_global_memory *get_this_pointer() - { return this; } - - public: - typedef typename base_t::size_type size_type; - - private: - typedef typename base_t::char_ptr_holder_t char_ptr_holder_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_global_memory) - /// @endcond - - public: //functions - - basic_managed_global_memory (open_or_create_t open_or_create, - const char *name, size_type size, - const void *addr = 0, const permissions& perm = permissions()) - : base_t() - , base2_t(open_or_create, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), - DoOpenOrCreate), perm) - {} - - basic_managed_global_memory (open_only_t open_only, const char* name, - const void *addr = 0) - : base_t() - , base2_t(open_only, name, read_write, addr, - create_open_func_t(get_this_pointer(), - DoOpen)) - {} -}; - - -} //namespace ipcdetail{ -} //namespace interprocess{ -} //namespace boost{ - -#include - -#endif //#ifndef BOOST_INTERPROCESS_BASIC_GLOBAL_MEMORY_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/managed_memory_impl.hpp b/utils/boost_idb/boost/interprocess/detail/managed_memory_impl.hpp index 2f97935d..e29fe503 100644 --- a/utils/boost_idb/boost/interprocess/detail/managed_memory_impl.hpp +++ b/utils/boost_idb/boost/interprocess/detail/managed_memory_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,10 +19,14 @@ #include #include +#include +#include #include #include #include +#include #include +#include #include #include // @@ -34,18 +38,18 @@ #include //!\file -//!Describes a named shared memory allocation user class. +//!Describes a named shared memory allocation user class. //! namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { template class create_open_func; template< - class CharType, + class CharType, class MemoryAlgorithm, template class IndexType > @@ -54,14 +58,14 @@ struct segment_manager_type typedef segment_manager type; }; -//!This class is designed to be a base class to classes that manage -//!creation of objects in a fixed size memory buffer. Apart -//!from allocating raw memory, the user can construct named objects. To +//!This class is designed to be a base class to classes that manage +//!creation of objects in a fixed size memory buffer. Apart +//!from allocating raw memory, the user can construct named objects. To //!achieve this, this class uses the reserved space provided by the allocation //!algorithm to place a named_allocator_algo, who takes care of name mappings. //!The class can be customized with the char type used for object names //!and the memory allocation algorithm to be used.*/ -template < class CharType +template < class CharType , class MemoryAlgorithm , template class IndexType , std::size_t Offset = 0 @@ -82,9 +86,7 @@ class basic_managed_memory_impl typedef MemoryAlgorithm memory_algorithm; typedef typename MemoryAlgorithm::mutex_family mutex_family; typedef CharType char_t; - typedef typename MemoryAlgorithm::size_type size_type; - typedef typename MemoryAlgorithm::difference_type difference_type; - typedef difference_type handle_t; + typedef std::ptrdiff_t handle_t; typedef typename segment_manager:: const_named_iterator const_named_iterator; typedef typename segment_manager:: @@ -92,7 +94,7 @@ class basic_managed_memory_impl /// @cond - typedef typename + typedef typename segment_manager::char_ptr_holder_t char_ptr_holder_t; //Experimental. Don't use. @@ -100,14 +102,14 @@ class basic_managed_memory_impl /// @endcond - static const size_type PayloadPerAllocation = segment_manager::PayloadPerAllocation; + static const std::size_t PayloadPerAllocation = segment_manager::PayloadPerAllocation; private: typedef basic_managed_memory_impl self_t; protected: template - static bool grow(const char *filename, size_type extra_bytes) + static bool grow(const char *filename, std::size_t extra_bytes) { typedef typename ManagedMemory::device_type device_type; //Increase file size @@ -133,10 +135,10 @@ class basic_managed_memory_impl static bool shrink_to_fit(const char *filename) { typedef typename ManagedMemory::device_type device_type; - size_type new_size; + std::size_t new_size, old_size; try{ ManagedMemory managed_memory(open_only, filename); - managed_memory.get_size(); + old_size = managed_memory.get_size(); managed_memory.self_t::shrink_to_fit(); new_size = managed_memory.get_size(); } @@ -153,7 +155,7 @@ class basic_managed_memory_impl } //!Constructor. Allocates basic resources. Never throws. - basic_managed_memory_impl() + basic_managed_memory_impl() : mp_header(0){} //!Destructor. Calls close. Never throws. @@ -161,7 +163,7 @@ class basic_managed_memory_impl { this->close_impl(); } //!Places segment manager in the reserved space. This can throw. - bool create_impl (void *addr, size_type size) + bool create_impl (void *addr, std::size_t size) { if(mp_header) return false; @@ -169,21 +171,21 @@ class basic_managed_memory_impl if(size < segment_manager::get_min_size()) return false; - //This function should not throw. The index construction can + //This function should not throw. The index construction can //throw if constructor allocates memory. So we must catch it. BOOST_TRY{ - //Let's construct the allocator in memory + //Let's construct the allocator in memory mp_header = new(addr) segment_manager(size); } BOOST_CATCH(...){ return false; } BOOST_CATCH_END - return true; + return true; } - + //!Connects to a segment manager in the reserved buffer. Never throws. - bool open_impl (void *addr, size_type) + bool open_impl (void *addr, std::size_t) { if(mp_header) return false; mp_header = static_cast(addr); @@ -192,7 +194,7 @@ class basic_managed_memory_impl //!Frees resources. Never throws. bool close_impl() - { + { bool ret = mp_header != 0; mp_header = 0; return ret; @@ -209,7 +211,7 @@ class basic_managed_memory_impl } //! - void grow(size_type extra_bytes) + void grow(std::size_t extra_bytes) { mp_header->grow(extra_bytes); } void shrink_to_fit() @@ -226,12 +228,12 @@ class basic_managed_memory_impl { return reinterpret_cast(mp_header) - Offset; } //!Returns the size of memory segment. Never throws. - size_type get_size () const + std::size_t get_size () const { return mp_header->get_size() + Offset; } //!Returns the number of free bytes of the memory //!segment - size_type get_free_memory() const + std::size_t get_free_memory() const { return mp_header->get_free_memory(); } //!Returns the result of "all_memory_deallocated()" function @@ -249,89 +251,83 @@ class basic_managed_memory_impl void zero_free_memory() { mp_header->zero_free_memory(); } - //!Transforms an absolute address into an offset from base address. + //!Transforms an absolute address into an offset from base address. //!The address must belong to the memory segment. Never throws. handle_t get_handle_from_address (const void *ptr) const { - return (handle_t)(reinterpret_cast(ptr) - - reinterpret_cast(this->get_address())); + return reinterpret_cast(ptr) - + reinterpret_cast(this->get_address()); } //!Returns true if the address belongs to the managed memory segment bool belongs_to_segment (const void *ptr) const - { - return ptr >= this->get_address() && + { + return ptr >= this->get_address() && ptr < (reinterpret_cast(this->get_address()) + this->get_size()); } - //!Transforms previously obtained offset into an absolute address in the + //!Transforms previously obtained offset into an absolute address in the //!process space of the current process. Never throws.*/ void * get_address_from_handle (handle_t offset) const { return reinterpret_cast(this->get_address()) + offset; } //!Searches for nbytes of free memory in the segment, marks the - //!memory as used and return the pointer to the memory. If no + //!memory as used and return the pointer to the memory. If no //!memory is available throws a boost::interprocess::bad_alloc exception - void* allocate (size_type nbytes) + void* allocate (std::size_t nbytes) { return mp_header->allocate(nbytes); } - //!Searches for nbytes of free memory in the segment, marks the - //!memory as used and return the pointer to the memory. If no memory + //!Searches for nbytes of free memory in the segment, marks the + //!memory as used and return the pointer to the memory. If no memory //!is available returns 0. Never throws. - void* allocate (size_type nbytes, std::nothrow_t nothrow) + void* allocate (std::size_t nbytes, std::nothrow_t nothrow) { return mp_header->allocate(nbytes, nothrow); } //!Allocates nbytes bytes aligned to "alignment" bytes. "alignment" - //!must be power of two. If no memory + //!must be power of two. If no memory //!is available returns 0. Never throws. - void * allocate_aligned (size_type nbytes, size_type alignment, std::nothrow_t nothrow) + void * allocate_aligned (std::size_t nbytes, std::size_t alignment, std::nothrow_t nothrow) { return mp_header->allocate_aligned(nbytes, alignment, nothrow); } template std::pair - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, T *reuse_ptr = 0) - { + { return mp_header->allocation_command (command, limit_size, preferred_size, received_size, reuse_ptr); } //!Allocates nbytes bytes aligned to "alignment" bytes. "alignment" - //!must be power of two. If no + //!must be power of two. If no //!memory is available throws a boost::interprocess::bad_alloc exception - void * allocate_aligned(size_type nbytes, size_type alignment) + void * allocate_aligned(std::size_t nbytes, std::size_t alignment) { return mp_header->allocate_aligned(nbytes, alignment); } /// @cond //Experimental. Don't use. - //!Allocates n_elements of elem_bytes bytes. - //!Throws bad_alloc on failure. chain.size() is not increased on failure. - void allocate_many(size_type elem_bytes, size_type n_elements, multiallocation_chain &chain) - { mp_header->allocate_many(elem_bytes, n_elements, chain); } + //!Allocates n_elements of elem_size bytes. + multiallocation_chain allocate_many(std::size_t elem_bytes, std::size_t num_elements) + { return mp_header->allocate_many(elem_bytes, num_elements); } - //!Allocates n_elements, each one of element_lengths[i]*sizeof_element bytes. - //!Throws bad_alloc on failure. chain.size() is not increased on failure. - void allocate_many(const size_type *element_lengths, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain) - { mp_header->allocate_many(element_lengths, n_elements, sizeof_element, chain); } + //!Allocates n_elements, each one of elem_sizes[i] bytes. + multiallocation_chain allocate_many(const std::size_t *elem_sizes, std::size_t n_elements) + { return mp_header->allocate_many(elem_sizes, n_elements); } - //!Allocates n_elements of elem_bytes bytes. - //!Non-throwing version. chain.size() is not increased on failure. - void allocate_many(std::nothrow_t, size_type elem_bytes, size_type n_elements, multiallocation_chain &chain) - { mp_header->allocate_many(std::nothrow_t(), elem_bytes, n_elements, chain); } + //!Allocates n_elements of elem_size bytes. + multiallocation_chain allocate_many(std::size_t elem_bytes, std::size_t num_elements, std::nothrow_t nothrow) + { return mp_header->allocate_many(elem_bytes, num_elements, nothrow); } - //!Allocates n_elements, each one of - //!element_lengths[i]*sizeof_element bytes. - //!Non-throwing version. chain.size() is not increased on failure. - void allocate_many(std::nothrow_t, const size_type *elem_sizes, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain) - { mp_header->allocate_many(std::nothrow_t(), elem_sizes, n_elements, sizeof_element, chain); } + //!Allocates n_elements, each one of elem_sizes[i] bytes. + multiallocation_chain allocate_many(const std::size_t *elem_sizes, std::size_t n_elements, std::nothrow_t nothrow) + { return mp_header->allocate_many(elem_sizes, n_elements, nothrow); } - //!Deallocates all elements contained in chain. - //!Never throws. - void deallocate_many(multiallocation_chain &chain) - { mp_header->deallocate_many(chain); } + //!Allocates n_elements, each one of elem_sizes[i] bytes. + void deallocate_many(multiallocation_chain chain) + { return mp_header->deallocate_many(boost::interprocess::move(chain)); } /// @endcond @@ -343,23 +339,23 @@ class basic_managed_memory_impl //!buffer and the object count. If not found returned pointer is 0. //!Never throws. template - std::pair find (char_ptr_holder_t name) + std::pair find (char_ptr_holder_t name) { return mp_header->template find(name); } //!Creates a named object or array in memory //! - //!Allocates and constructs a T object or an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Allocates and constructs a T object or an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. If an array is being constructed all objects are //!created using the same parameters given to this function. //! //!-> If the name was previously used, returns 0. //! - //!-> Throws boost::interprocess::bad_alloc if there is no available memory + //!-> Throws boost::interprocess::bad_alloc if there is no available memory //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and if an + //!Memory is freed automatically if T's constructor throws and if an //!array was being constructed, destructors of created objects are called //!before freeing the memory. template @@ -369,18 +365,18 @@ class basic_managed_memory_impl //!Finds or creates a named object or array in memory //! - //!Tries to find an object with the given name in memory. If - //!found, returns the pointer to this pointer. If the object is not found, - //!allocates and constructs a T object or an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Tries to find an object with the given name in memory. If + //!found, returns the pointer to this pointer. If the object is not found, + //!allocates and constructs a T object or an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. If an array is being constructed all objects are //!created using the same parameters given to this function. //! - //!-> Throws boost::interprocess::bad_alloc if there is no available memory + //!-> Throws boost::interprocess::bad_alloc if there is no available memory //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and if an + //!Memory is freed automatically if T's constructor throws and if an //!array was being constructed, destructors of created objects are called //!before freeing the memory. template @@ -390,18 +386,18 @@ class basic_managed_memory_impl //!Creates a named object or array in memory //! - //!Allocates and constructs a T object or an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Allocates and constructs a T object or an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. If an array is being constructed all objects are //!created using the same parameters given to this function. //! //!-> If the name was previously used, returns 0. //! - //!-> Returns 0 if there is no available memory + //!-> Returns 0 if there is no available memory //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and if an + //!Memory is freed automatically if T's constructor throws and if an //!array was being constructed, destructors of created objects are called //!before freeing the memory. template @@ -411,18 +407,18 @@ class basic_managed_memory_impl //!Finds or creates a named object or array in memory //! - //!Tries to find an object with the given name in memory. If - //!found, returns the pointer to this pointer. If the object is not found, - //!allocates and constructs a T object or an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Tries to find an object with the given name in memory. If + //!found, returns the pointer to this pointer. If the object is not found, + //!allocates and constructs a T object or an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. If an array is being constructed all objects are //!created using the same parameters given to this function. //! - //!-> Returns 0 if there is no available memory + //!-> Returns 0 if there is no available memory //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and if an + //!Memory is freed automatically if T's constructor throws and if an //!array was being constructed, destructors of created objects are called //!before freeing the memory. template @@ -430,54 +426,54 @@ class basic_managed_memory_impl find_or_construct(char_ptr_holder_t name, std::nothrow_t nothrow) { return mp_header->template find_or_construct(name, nothrow); } - //!Creates a named array from iterators in memory + //!Creates a named array from iterators in memory //! - //!Allocates and constructs an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Allocates and constructs an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. Each element in the array is created using the //!objects returned when dereferencing iterators as parameters //!and incrementing all iterators for each element. //! //!-> If the name was previously used, returns 0. //! - //!-> Throws boost::interprocess::bad_alloc if there is no available memory + //!-> Throws boost::interprocess::bad_alloc if there is no available memory //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and + //!Memory is freed automatically if T's constructor throws and //!destructors of created objects are called before freeing the memory. template typename segment_manager::template construct_iter_proxy::type construct_it(char_ptr_holder_t name) { return mp_header->template construct_it(name); } - //!Finds or creates a named array from iterators in memory + //!Finds or creates a named array from iterators in memory //! - //!Tries to find an object with the given name in memory. If - //!found, returns the pointer to this pointer. If the object is not found, - //!allocates and constructs an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Tries to find an object with the given name in memory. If + //!found, returns the pointer to this pointer. If the object is not found, + //!allocates and constructs an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. Each element in the array is created using the //!objects returned when dereferencing iterators as parameters //!and incrementing all iterators for each element. //! //!-> If the name was previously used, returns 0. //! - //!-> Throws boost::interprocess::bad_alloc if there is no available memory + //!-> Throws boost::interprocess::bad_alloc if there is no available memory //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and + //!Memory is freed automatically if T's constructor throws and //!destructors of created objects are called before freeing the memory. template typename segment_manager::template construct_iter_proxy::type find_or_construct_it(char_ptr_holder_t name) { return mp_header->template find_or_construct_it(name); } - //!Creates a named array from iterators in memory + //!Creates a named array from iterators in memory //! - //!Allocates and constructs an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Allocates and constructs an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. Each element in the array is created using the //!objects returned when dereferencing iterators as parameters //!and incrementing all iterators for each element. @@ -488,19 +484,19 @@ class basic_managed_memory_impl //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and + //!Memory is freed automatically if T's constructor throws and //!destructors of created objects are called before freeing the memory.*/ template typename segment_manager::template construct_iter_proxy::type construct_it(char_ptr_holder_t name, std::nothrow_t nothrow) { return mp_header->template construct_it(name, nothrow); } - //!Finds or creates a named array from iterators in memory + //!Finds or creates a named array from iterators in memory //! - //!Tries to find an object with the given name in memory. If - //!found, returns the pointer to this pointer. If the object is not found, - //!allocates and constructs an array of T in memory, - //!associates this with the given name and returns a pointer to the + //!Tries to find an object with the given name in memory. If + //!found, returns the pointer to this pointer. If the object is not found, + //!allocates and constructs an array of T in memory, + //!associates this with the given name and returns a pointer to the //!created object. Each element in the array is created using the //!objects returned when dereferencing iterators as parameters //!and incrementing all iterators for each element. @@ -511,7 +507,7 @@ class basic_managed_memory_impl //! //!-> If T's constructor throws, the function throws that exception. //! - //!Memory is freed automatically if T's constructor throws and + //!Memory is freed automatically if T's constructor throws and //!destructors of created objects are called before freeing the memory.*/ template typename segment_manager::template construct_iter_proxy::type @@ -543,11 +539,11 @@ class basic_managed_memory_impl //! //!Exception Handling: //! - //!When deleting a dynamically object or array, the Standard + //!When deleting a dynamically object or array, the Standard //!does not guarantee that dynamically allocated memory, will be released. - //!Also, when deleting arrays, the Standard doesn't require calling - //!destructors for the rest of the objects if for one of them the destructor - //!terminated with an exception. + //!Also, when deleting arrays, the Standard doesn't require calling + //!destructors for the rest of the objects if for one of them the destructor + //!terminated with an exception. //! //!Destroying an object: //! @@ -556,13 +552,13 @@ class basic_managed_memory_impl //! //!Destroying an array: //! - //!When destroying an array, if a destructor throws, the rest of + //!When destroying an array, if a destructor throws, the rest of //!destructors are called. If any of these throws, the exceptions are //!ignored. The name association will be erased, memory will be freed and //!the first exception will be thrown. This guarantees the unlocking of //!mutexes and other resources. //! - //!For all theses reasons, classes with throwing destructors are not + //!For all theses reasons, classes with throwing destructors are not //!recommended. template bool destroy(const CharType *name) @@ -574,7 +570,7 @@ class basic_managed_memory_impl //! //!Exception Handling: //! - //!When deleting a dynamically object, the Standard does not + //!When deleting a dynamically object, the Standard does not //!guarantee that dynamically allocated memory will be released. //! //!Destroying an object: @@ -582,10 +578,10 @@ class basic_managed_memory_impl //!If the destructor throws, the memory will be freed and that exception //!will be thrown. //! - //!For all theses reasons, classes with throwing destructors are not + //!For all theses reasons, classes with throwing destructors are not //!recommended for memory. template - bool destroy(const unique_instance_t *const ) + bool destroy(const detail::unique_instance_t *const ) { return mp_header->template destroy(unique_instance); } //!Destroys the object (named, unique, or anonymous) @@ -594,7 +590,7 @@ class basic_managed_memory_impl //! //!Exception Handling: //! - //!When deleting a dynamically object, the Standard does not + //!When deleting a dynamically object, the Standard does not //!guarantee that dynamically allocated memory will be released. //! //!Destroying an object: @@ -602,7 +598,7 @@ class basic_managed_memory_impl //!If the destructor throws, the memory will be freed and that exception //!will be thrown. //! - //!For all theses reasons, classes with throwing destructors are not + //!For all theses reasons, classes with throwing destructors are not //!recommended for memory. template void destroy_ptr(const T *ptr) @@ -623,19 +619,19 @@ class basic_managed_memory_impl //!Returns the length of an object created with construct/find_or_construct //!functions (1 if is a single element, >=1 if it's an array). Does not throw. template - static size_type get_instance_length(const T *ptr) + static std::size_t get_instance_length(const T *ptr) { return segment_manager::get_instance_length(ptr); } - //!Preallocates needed index resources to optimize the + //!Preallocates needed index resources to optimize the //!creation of "num" named objects in the memory segment. //!Can throw boost::interprocess::bad_alloc if there is no enough memory. - void reserve_named_objects(size_type num) + void reserve_named_objects(std::size_t num) { mp_header->reserve_named_objects(num); } - //!Preallocates needed index resources to optimize the + //!Preallocates needed index resources to optimize the //!creation of "num" unique objects in the memory segment. //!Can throw boost::interprocess::bad_alloc if there is no enough memory. - void reserve_unique_objects(size_type num) + void reserve_unique_objects(std::size_t num) { mp_header->reserve_unique_objects(num); } //!Calls shrink_to_fit in both named and unique object indexes @@ -645,12 +641,12 @@ class basic_managed_memory_impl //!Returns the number of named objects stored //!in the managed segment. - size_type get_num_named_objects() + std::size_t get_num_named_objects() { return mp_header->get_num_named_objects(); } //!Returns the number of unique objects stored //!in the managed segment. - size_type get_num_unique_objects() + std::size_t get_num_unique_objects() { return mp_header->get_num_unique_objects(); } //!Returns a constant iterator to the index storing the @@ -658,7 +654,7 @@ class basic_managed_memory_impl const_named_iterator named_begin() const { return mp_header->named_begin(); } - //!Returns a constant iterator to the end of the index + //!Returns a constant iterator to the end of the index //!storing the named allocations. NOT thread-safe. Never throws. const_named_iterator named_end() const { return mp_header->named_end(); } @@ -668,7 +664,7 @@ class basic_managed_memory_impl const_unique_iterator unique_begin() const { return mp_header->unique_begin(); } - //!Returns a constant iterator to the end of the index + //!Returns a constant iterator to the end of the index //!storing the unique allocations. NOT thread-safe. Never throws. const_unique_iterator unique_end() const { return mp_header->unique_end(); } @@ -708,7 +704,7 @@ class basic_managed_memory_impl //!buffer and the object count. If not found returned pointer is 0. //!Never throws. template - std::pair find_no_lock (char_ptr_holder_t name) + std::pair find_no_lock (char_ptr_holder_t name) { return mp_header->template find_no_lock(name); } /// @endcond @@ -725,48 +721,28 @@ class basic_managed_memory_impl template class create_open_func { - typedef typename BasicManagedMemoryImpl::size_type size_type; - public: - - create_open_func(BasicManagedMemoryImpl * const frontend, create_enum_t type) + create_open_func(BasicManagedMemoryImpl * const frontend, detail::create_enum_t type) : m_frontend(frontend), m_type(type){} bool operator()(void *addr, std::size_t size, bool created) const - { - if( ((m_type == DoOpen) && created) || - ((m_type == DoCreate) && !created) || - //Check for overflow - size_type(-1) < size ){ + { + if(((m_type == detail::DoOpen) && created) || + ((m_type == detail::DoCreate) && !created)) return false; - } - else if(created){ - return m_frontend->create_impl(addr, static_cast(size)); - } - else{ - return m_frontend->open_impl (addr, static_cast(size)); - } - } - std::size_t get_min_size() const - { - const size_type sz = m_frontend->get_segment_manager()->get_min_size(); - if(sz > std::size_t(-1)){ - //The minimum size is not representable by std::size_t - BOOST_ASSERT(false); - return std::size_t(-1); - } - else{ - return static_cast(sz); - } + if(created) + return m_frontend->create_impl(addr, size); + else + return m_frontend->open_impl (addr, size); } private: BasicManagedMemoryImpl *m_frontend; - create_enum_t m_type; + detail::create_enum_t m_type; }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/detail/managed_multi_shared_memory.hpp b/utils/boost_idb/boost/interprocess/detail/managed_multi_shared_memory.hpp index b1b27251..b03ca618 100644 --- a/utils/boost_idb/boost/interprocess/detail/managed_multi_shared_memory.hpp +++ b/utils/boost_idb/boost/interprocess/detail/managed_multi_shared_memory.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -34,10 +34,6 @@ #include #include #include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include //!\file //!Describes a named shared memory object allocation user class. @@ -51,31 +47,26 @@ namespace interprocess { //-Use GetSecurityInfo? //-Change everything to use only a shared memory object expanded via truncate()? -//!A basic shared memory named object creation class. Initializes the -//!shared memory segment. Inherits all basic functionality from +//!A basic shared memory named object creation class. Initializes the +//!shared memory segment. Inherits all basic functionality from //!basic_managed_memory_impl template < - class CharType, - class MemoryAlgorithm, + class CharType, + class MemoryAlgorithm, template class IndexType > -class basic_managed_multi_shared_memory - : public ipcdetail::basic_managed_memory_impl +class basic_managed_multi_shared_memory + : public detail::basic_managed_memory_impl { typedef basic_managed_multi_shared_memory self_t; - typedef ipcdetail::basic_managed_memory_impl - base_t; - typedef typename MemoryAlgorithm::void_pointer void_pointer; - typedef typename ipcdetail:: - managed_open_or_create_impl managed_impl; + typedef typename detail:: + managed_open_or_create_impl managed_impl; typedef typename void_pointer::segment_group_id segment_group_id; - typedef typename base_t::size_type size_type; - //////////////////////////////////////////////////////////////////////// // // Some internal helper structs/functors @@ -91,16 +82,16 @@ class basic_managed_multi_shared_memory // { // public: // segment_creator(shared_memory &shmem, -// const char *mem_name, +// const char *mem_name, // const void *addr) // : m_shmem(shmem), m_mem_name(mem_name), m_addr(addr){} // -// void *operator()(size_type size) +// void *operator()(std::size_t size) // { // if(!m_shmem.create(m_mem_name, size, m_addr)) // return 0; -// return m_shmem.get_address(); -// } +// return m_shmem.get_address(); +// } // private: // shared_memory &m_shmem; // const char *m_mem_name; @@ -111,30 +102,29 @@ class basic_managed_multi_shared_memory : public multi_segment_services { public: - typedef std::pair result_type; + typedef std::pair result_type; typedef basic_managed_multi_shared_memory frontend_t; - typedef typename + typedef typename basic_managed_multi_shared_memory::void_pointer void_pointer; typedef typename void_pointer::segment_group_id segment_group_id; group_services(frontend_t *const frontend) : mp_frontend(frontend), m_group(0), m_min_segment_size(0){} - virtual std::pair create_new_segment(size_type alloc_size) - { (void)alloc_size; - /* + virtual std::pair create_new_segment(std::size_t alloc_size) + { //We should allocate an extra byte so that the //[base_addr + alloc_size] byte belongs to this segment alloc_size += 1; //If requested size is less than minimum, update that - alloc_size = (m_min_segment_size > alloc_size) ? + alloc_size = (m_min_segment_size > alloc_size) ? m_min_segment_size : alloc_size; if(mp_frontend->priv_new_segment(create_open_func::DoCreate, alloc_size, 0, permissions())){ - typename shmem_list_t::value_type &m_impl = *mp_frontend->m_shmem_list.rbegin(); + shmem_list_t::value_type &m_impl = *mp_frontend->m_shmem_list.rbegin(); return result_type(m_impl.get_real_address(), m_impl.get_real_size()-1); - }*/ - return result_type(static_cast(0), 0); + } + return result_type(static_cast(0), 0); } virtual bool update_segments () @@ -148,17 +138,17 @@ class basic_managed_multi_shared_memory segment_group_id get_group() const { return m_group; } - void set_min_segment_size(size_type min_segment_size) + void set_min_segment_size(std::size_t min_segment_size) { m_min_segment_size = min_segment_size; } - size_type get_min_segment_size() const + std::size_t get_min_segment_size() const { return m_min_segment_size; } private: frontend_t * const mp_frontend; segment_group_id m_group; - size_type m_min_segment_size; + std::size_t m_min_segment_size; }; //!Functor to execute atomically when opening or creating a shared memory @@ -166,16 +156,16 @@ class basic_managed_multi_shared_memory struct create_open_func { enum type_t { DoCreate, DoOpen, DoOpenOrCreate }; - typedef typename + typedef typename basic_managed_multi_shared_memory::void_pointer void_pointer; create_open_func(self_t * const frontend, - type_t type, size_type segment_number) + type_t type, std::size_t segment_number) : mp_frontend(frontend), m_type(type), m_segment_number(segment_number){} - bool operator()(void *addr, size_type size, bool created) const - { - if(((m_type == DoOpen) && created) || + bool operator()(void *addr, std::size_t size, bool created) const + { + if(((m_type == DoOpen) && created) || ((m_type == DoCreate) && !created)) return false; segment_group_id group = mp_frontend->m_group_services.get_group(); @@ -191,7 +181,7 @@ class basic_managed_multi_shared_memory //Check if this is the master segment if(!m_segment_number){ //Create or open the Interprocess machinery - if((impl_done = created ? + if((impl_done = created ? mp_frontend->create_impl(addr, size) : mp_frontend->open_impl(addr, size))){ return true; } @@ -211,42 +201,31 @@ class basic_managed_multi_shared_memory } return false; } - - std::size_t get_min_size() const - { - const size_type sz = mp_frontend->get_segment_manager()->get_min_size(); - if(sz > std::size_t(-1)){ - //The minimum size is not representable by std::size_t - BOOST_ASSERT(false); - return std::size_t(-1); - } - else{ - return static_cast(sz); - } - } - self_t * const mp_frontend; type_t m_type; - size_type m_segment_number; + std::size_t m_segment_number; }; //!Functor to execute atomically when closing a shared memory segment. struct close_func { - typedef typename + typedef typename basic_managed_multi_shared_memory::void_pointer void_pointer; close_func(self_t * const frontend) : mp_frontend(frontend){} void operator()(const mapped_region ®ion, bool last) const - { + { if(last) mp_frontend->destroy_impl(); else mp_frontend->close_impl(); } self_t * const mp_frontend; }; + typedef detail::basic_managed_memory_impl + base_t; + //Friend declarations friend struct basic_managed_multi_shared_memory::create_open_func; friend struct basic_managed_multi_shared_memory::close_func; @@ -261,16 +240,16 @@ class basic_managed_multi_shared_memory basic_managed_multi_shared_memory(create_only_t, const char *name, - size_type size, + std::size_t size, const permissions &perm = permissions()) : m_group_services(get_this_pointer()) { - priv_open_or_create(create_open_func::DoCreate,name, size, perm); + priv_open_or_create(create_open_func::DoCreate,name, size, perm); } basic_managed_multi_shared_memory(open_or_create_t, const char *name, - size_type size, + std::size_t size, const permissions &perm = permissions()) : m_group_services(get_this_pointer()) { @@ -287,9 +266,9 @@ class basic_managed_multi_shared_memory { this->priv_close(); } private: - bool priv_open_or_create(typename create_open_func::type_t type, + bool priv_open_or_create(typename create_open_func::type_t type, const char *name, - size_type size, + std::size_t size, const permissions &perm) { if(!m_shmem_list.empty()) @@ -315,21 +294,21 @@ class basic_managed_multi_shared_memory if(group){ void_pointer::delete_group(group); } - return false; + return false; } bool priv_new_segment(typename create_open_func::type_t type, - size_type size, + std::size_t size, const void *addr, const permissions &perm) { BOOST_TRY{ //Get the number of groups of this multi_segment group - size_type segment_id = m_shmem_list.size(); - //Format the name of the shared memory: append segment number. + std::size_t segment_id = m_shmem_list.size(); + //Format the name of the shared memory: append segment number. boost::interprocess::basic_ovectorstream formatter; //Pre-reserve string size - size_type str_size = m_root_name.length()+10; + std::size_t str_size = m_root_name.length()+10; if(formatter.vector().size() < str_size){ //This can throw. formatter.reserve(str_size); @@ -347,21 +326,21 @@ class basic_managed_multi_shared_memory case create_open_func::DoCreate: { managed_impl shm(create_only, name, size, read_write, addr, func, perm); - mshm = boost::move(shm); + mshm = boost::interprocess::move(shm); } break; case create_open_func::DoOpen: { managed_impl shm(open_only, name,read_write, addr, func); - mshm = boost::move(shm); + mshm = boost::interprocess::move(shm); } break; case create_open_func::DoOpenOrCreate: { managed_impl shm(open_or_create, name, size, read_write, addr, func, perm); - mshm = boost::move(shm); + mshm = boost::interprocess::move(shm); } break; @@ -371,7 +350,7 @@ class basic_managed_multi_shared_memory } //This can throw. - m_shmem_list.push_back(boost::move(mshm)); + m_shmem_list.push_back(boost::interprocess::move(mshm)); return true; } BOOST_CATCH(const std::bad_alloc&){ @@ -382,24 +361,23 @@ class basic_managed_multi_shared_memory //!Frees resources. Never throws. void priv_close() - { + { if(!m_shmem_list.empty()){ bool ret; //Obtain group identifier segment_group_id group = m_group_services.get_group(); //Erase main segment and its resources - //typename shmem_list_t::iterator itbeg = m_shmem_list.begin(), - // itend = m_shmem_list.end(), - // it = itbeg; + shmem_list_t::iterator itbeg = m_shmem_list.begin(), + itend = m_shmem_list.end(), + it = itbeg; //(*itbeg)->close_with_func(close_func(this)); //Delete group. All mappings are erased too. ret = void_pointer::delete_group(group); - (void)ret; BOOST_ASSERT(ret); m_shmem_list.clear(); } } - + private: shmem_list_t m_shmem_list; group_services m_group_services; diff --git a/utils/boost_idb/boost/interprocess/detail/managed_open_or_create_impl.hpp b/utils/boost_idb/boost/interprocess/detail/managed_open_or_create_impl.hpp index 948b4f4b..b3e885a6 100644 --- a/utils/boost_idb/boost/interprocess/detail/managed_open_or_create_impl.hpp +++ b/utils/boost_idb/boost/interprocess/detail/managed_open_or_create_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,7 +11,6 @@ #ifndef BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_IMPL #define BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_IMPL -#include #include #include #include @@ -22,108 +21,53 @@ #include #include #include +#include #include -#include -#include -#include -#include #include namespace boost { namespace interprocess { /// @cond -namespace ipcdetail{ class interprocess_tester; } - - -template -struct managed_open_or_create_impl_device_id_t -{ - typedef const char *type; -}; - -#ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS - -class xsi_shared_memory_file_wrapper; -class xsi_key; - -template<> -struct managed_open_or_create_impl_device_id_t -{ - typedef xsi_key type; -}; - -#endif //BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS - +namespace detail{ class interprocess_tester; } /// @endcond -namespace ipcdetail { - - -template -class managed_open_or_create_impl_device_holder -{ - public: - DeviceAbstraction &get_device() - { static DeviceAbstraction dev; return dev; } - - const DeviceAbstraction &get_device() const - { static DeviceAbstraction dev; return dev; } -}; - -template -class managed_open_or_create_impl_device_holder -{ - public: - DeviceAbstraction &get_device() - { return dev; } - - const DeviceAbstraction &get_device() const - { return dev; } - - private: - DeviceAbstraction dev; -}; +namespace detail { -template +template class managed_open_or_create_impl - : public managed_open_or_create_impl_device_holder { //Non-copyable - BOOST_MOVABLE_BUT_NOT_COPYABLE(managed_open_or_create_impl) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(managed_open_or_create_impl) - typedef typename managed_open_or_create_impl_device_id_t::type device_id_t; - typedef managed_open_or_create_impl_device_holder DevHolder; enum - { - UninitializedSegment, - InitializingSegment, + { + UninitializedSegment, + InitializingSegment, InitializedSegment, CorruptedSegment }; public: static const std::size_t - ManagedOpenOrCreateUserOffset = - ct_rounded_size + ManagedOpenOrCreateUserOffset = + detail::ct_rounded_size < sizeof(boost::uint32_t) - , MemAlignment ? (MemAlignment) : - (::boost::alignment_of< ::boost::detail::max_align >::value) - >::value; + , detail::alignment_of::value>::value; managed_open_or_create_impl() {} - managed_open_or_create_impl(create_only_t, - const device_id_t & id, + managed_open_or_create_impl(create_only_t, + const char *name, std::size_t size, mode_t mode, const void *addr, const permissions &perm) { + m_name = name; priv_open_or_create - ( DoCreate - , id + ( detail::DoCreate , size , mode , addr @@ -131,14 +75,14 @@ class managed_open_or_create_impl , null_mapped_region_function()); } - managed_open_or_create_impl(open_only_t, - const device_id_t & id, + managed_open_or_create_impl(open_only_t, + const char *name, mode_t mode, const void *addr) { + m_name = name; priv_open_or_create - ( DoOpen - , id + ( detail::DoOpen , 0 , mode , addr @@ -147,16 +91,16 @@ class managed_open_or_create_impl } - managed_open_or_create_impl(open_or_create_t, - const device_id_t & id, + managed_open_or_create_impl(open_or_create_t, + const char *name, std::size_t size, mode_t mode, const void *addr, const permissions &perm) { + m_name = name; priv_open_or_create - ( DoOpenOrCreate - , id + ( detail::DoOpenOrCreate , size , mode , addr @@ -165,17 +109,17 @@ class managed_open_or_create_impl } template - managed_open_or_create_impl(create_only_t, - const device_id_t & id, + managed_open_or_create_impl(create_only_t, + const char *name, std::size_t size, mode_t mode, const void *addr, const ConstructFunc &construct_func, const permissions &perm) { + m_name = name; priv_open_or_create - (DoCreate - , id + (detail::DoCreate , size , mode , addr @@ -184,15 +128,15 @@ class managed_open_or_create_impl } template - managed_open_or_create_impl(open_only_t, - const device_id_t & id, + managed_open_or_create_impl(open_only_t, + const char *name, mode_t mode, const void *addr, const ConstructFunc &construct_func) { + m_name = name; priv_open_or_create - ( DoOpen - , id + ( detail::DoOpen , 0 , mode , addr @@ -201,17 +145,17 @@ class managed_open_or_create_impl } template - managed_open_or_create_impl(open_or_create_t, - const device_id_t & id, + managed_open_or_create_impl(open_or_create_t, + const char *name, std::size_t size, mode_t mode, const void *addr, const ConstructFunc &construct_func, const permissions &perm) { + m_name = name; priv_open_or_create - ( DoOpenOrCreate - , id + ( detail::DoOpenOrCreate , size , mode , addr @@ -219,14 +163,14 @@ class managed_open_or_create_impl , construct_func); } - managed_open_or_create_impl(BOOST_RV_REF(managed_open_or_create_impl) moved) + managed_open_or_create_impl(BOOST_INTERPROCESS_RV_REF(managed_open_or_create_impl) moved) { this->swap(moved); } - managed_open_or_create_impl &operator=(BOOST_RV_REF(managed_open_or_create_impl) moved) - { - managed_open_or_create_impl tmp(boost::move(moved)); + managed_open_or_create_impl &operator=(BOOST_INTERPROCESS_RV_REF(managed_open_or_create_impl) moved) + { + managed_open_or_create_impl tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } ~managed_open_or_create_impl() @@ -246,69 +190,54 @@ class managed_open_or_create_impl void swap(managed_open_or_create_impl &other) { + this->m_name.swap(other.m_name); this->m_mapped_region.swap(other.m_mapped_region); } + const char *get_name() const + { return m_name.c_str(); } + bool flush() { return m_mapped_region.flush(); } + const mapped_region &get_mapped_region() const { return m_mapped_region; } - - DeviceAbstraction &get_device() - { return this->DevHolder::get_device(); } - - const DeviceAbstraction &get_device() const - { return this->DevHolder::get_device(); } - private: //These are templatized to allow explicit instantiations template - static void truncate_device(DeviceAbstraction &, offset_t, false_) + static void truncate_device(DeviceAbstraction &, std::size_t, detail::false_) {} //Empty template - static void truncate_device(DeviceAbstraction &dev, offset_t size, true_) + static void truncate_device(DeviceAbstraction &dev, std::size_t size, detail::true_) { dev.truncate(size); } - - template - static bool check_offset_t_size(std::size_t , false_) - { return true; } //Empty - - template - static bool check_offset_t_size(std::size_t size, true_) - { return size == std::size_t(offset_t(size)); } - //These are templatized to allow explicit instantiations template - static void create_device(DeviceAbstraction &dev, const device_id_t & id, std::size_t size, const permissions &perm, false_ file_like) + static void create_device(DeviceAbstraction &dev, const char *name, std::size_t size, const permissions &perm, detail::false_) { - (void)file_like; - DeviceAbstraction tmp(create_only, id, read_write, size, perm); + DeviceAbstraction tmp(create_only, name, read_write, size, perm); tmp.swap(dev); } template - static void create_device(DeviceAbstraction &dev, const device_id_t & id, std::size_t, const permissions &perm, true_ file_like) + static void create_device(DeviceAbstraction &dev, const char *name, std::size_t, const permissions &perm, detail::true_) { - (void)file_like; - DeviceAbstraction tmp(create_only, id, read_write, perm); + DeviceAbstraction tmp(create_only, name, read_write, perm); tmp.swap(dev); } - template inline + template inline void priv_open_or_create - (create_enum_t type, - const device_id_t & id, - std::size_t size, + (detail::create_enum_t type, std::size_t size, mode_t mode, const void *addr, const permissions &perm, ConstructFunc construct_func) { - typedef bool_ file_like_t; + typedef detail::bool_ file_like_t; (void)mode; error_info err; bool created = false; @@ -316,49 +245,40 @@ class managed_open_or_create_impl bool cow = false; DeviceAbstraction dev; - if(type != DoOpen){ - //Check if the requested size is enough to build the managed metadata - const std::size_t func_min_size = construct_func.get_min_size(); - if( (std::size_t(-1) - ManagedOpenOrCreateUserOffset) < func_min_size || - size < (func_min_size + ManagedOpenOrCreateUserOffset) ){ - throw interprocess_exception(error_info(size_error)); - } - } - //Check size can be represented by offset_t (used by truncate) - if(type != DoOpen && !check_offset_t_size(size, file_like_t())){ + if(type != detail::DoOpen && size < ManagedOpenOrCreateUserOffset){ throw interprocess_exception(error_info(size_error)); } - if(type == DoOpen && mode == read_write){ - DeviceAbstraction tmp(open_only, id, read_write); + + if(type == detail::DoOpen && mode == read_write){ + DeviceAbstraction tmp(open_only, m_name.c_str(), read_write); tmp.swap(dev); created = false; } - else if(type == DoOpen && mode == read_only){ - DeviceAbstraction tmp(open_only, id, read_only); + else if(type == detail::DoOpen && mode == read_only){ + DeviceAbstraction tmp(open_only, m_name.c_str(), read_only); tmp.swap(dev); created = false; ronly = true; } - else if(type == DoOpen && mode == copy_on_write){ - DeviceAbstraction tmp(open_only, id, read_only); + else if(type == detail::DoOpen && mode == copy_on_write){ + DeviceAbstraction tmp(open_only, m_name.c_str(), read_only); tmp.swap(dev); created = false; cow = true; } - else if(type == DoCreate){ - create_device(dev, id, size, perm, file_like_t()); + else if(type == detail::DoCreate){ + create_device(dev, m_name.c_str(), size, perm, file_like_t()); created = true; } - else if(type == DoOpenOrCreate){ + else if(type == detail::DoOpenOrCreate){ //This loop is very ugly, but brute force is sometimes better //than diplomacy. If someone knows how to open or create a //file and know if we have really created it or just open it //drop me a e-mail! bool completed = false; - spin_wait swait; while(!completed){ try{ - create_device(dev, id, size, perm, file_like_t()); + create_device(dev, m_name.c_str(), size, perm, file_like_t()); created = true; completed = true; } @@ -368,25 +288,19 @@ class managed_open_or_create_impl } else{ try{ - DeviceAbstraction tmp(open_only, id, read_write); + DeviceAbstraction tmp(open_only, m_name.c_str(), read_write); dev.swap(tmp); created = false; completed = true; } - catch(interprocess_exception &e){ - if(e.get_error_code() != not_found_error){ + catch(interprocess_exception &ex){ + if(ex.get_error_code() != not_found_error){ throw; } } - catch(...){ - throw; - } } } - catch(...){ - throw; - } - swait.yield(); + detail::thread_yield(); } } @@ -399,20 +313,19 @@ class managed_open_or_create_impl mapped_region region(dev, read_write, 0, 0, addr); boost::uint32_t *patomic_word = 0; //avoid gcc warning patomic_word = static_cast(region.get_address()); - boost::uint32_t previous = atomic_cas32(patomic_word, InitializingSegment, UninitializedSegment); + boost::uint32_t previous = detail::atomic_cas32(patomic_word, InitializingSegment, UninitializedSegment); if(previous == UninitializedSegment){ try{ - construct_func( static_cast(region.get_address()) + ManagedOpenOrCreateUserOffset - , size - ManagedOpenOrCreateUserOffset, true); + construct_func(static_cast(region.get_address()) + ManagedOpenOrCreateUserOffset, size - ManagedOpenOrCreateUserOffset, true); //All ok, just move resources to the external mapped region m_mapped_region.swap(region); } catch(...){ - atomic_write32(patomic_word, CorruptedSegment); + detail::atomic_write32(patomic_word, CorruptedSegment); throw; } - atomic_write32(patomic_word, InitializedSegment); + detail::atomic_write32(patomic_word, InitializedSegment); } else if(previous == InitializingSegment || previous == InitializedSegment){ throw interprocess_exception(error_info(already_exists_error)); @@ -433,12 +346,11 @@ class managed_open_or_create_impl else{ if(FileBased){ offset_t filesize = 0; - spin_wait swait; while(filesize == 0){ - if(!get_file_size(file_handle_from_mapping_handle(dev.get_mapping_handle()), filesize)){ + if(!detail::get_file_size(detail::file_handle_from_mapping_handle(dev.get_mapping_handle()), filesize)){ throw interprocess_exception(error_info(system_error_code())); } - swait.yield(); + detail::thread_yield(); } if(filesize == 1){ throw interprocess_exception(error_info(corrupted_error)); @@ -448,12 +360,11 @@ class managed_open_or_create_impl mapped_region region(dev, ronly ? read_only : (cow ? copy_on_write : read_write), 0, 0, addr); boost::uint32_t *patomic_word = static_cast(region.get_address()); - boost::uint32_t value = atomic_read32(patomic_word); + boost::uint32_t value = detail::atomic_read32(patomic_word); - spin_wait swait; while(value == InitializingSegment || value == UninitializedSegment){ - swait.yield(); - value = atomic_read32(patomic_word); + detail::thread_yield(); + value = detail::atomic_read32(patomic_word); } if(value != InitializedSegment) @@ -465,29 +376,25 @@ class managed_open_or_create_impl //All ok, just move resources to the external mapped region m_mapped_region.swap(region); } - if(StoreDevice){ - this->DevHolder::get_device() = boost::move(dev); - } - } - - friend void swap(managed_open_or_create_impl &left, managed_open_or_create_impl &right) - { - left.swap(right); } private: - friend class interprocess_tester; + friend class detail::interprocess_tester; void dont_close_on_destruction() - { interprocess_tester::dont_close_on_destruction(m_mapped_region); } + { detail::interprocess_tester::dont_close_on_destruction(m_mapped_region); } mapped_region m_mapped_region; + std::string m_name; }; -} //namespace ipcdetail { +template +inline void swap(managed_open_or_create_impl &x + ,managed_open_or_create_impl &y) +{ x.swap(y); } + +} //namespace detail { } //namespace interprocess { } //namespace boost { -#include - #endif //#ifndef BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_IMPL diff --git a/utils/boost_idb/boost/interprocess/detail/math_functions.hpp b/utils/boost_idb/boost/interprocess/detail/math_functions.hpp index 20922b39..5c6b4582 100644 --- a/utils/boost_idb/boost/interprocess/detail/math_functions.hpp +++ b/utils/boost_idb/boost/interprocess/detail/math_functions.hpp @@ -1,10 +1,10 @@ ////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Stephen Cleary 2000. -// (C) Copyright Ion Gaztanaga 2007-2012. +// (C) Copyright Ion Gaztanaga 2007-2009. // // Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at +// (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. @@ -21,7 +21,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { // Greatest common divisor and least common multiple @@ -93,7 +93,7 @@ inline std::size_t floor_log2 (std::size_t x) std::size_t n = x; std::size_t log2 = 0; - + for(std::size_t shift = Bits >> 1; shift; shift >>= 1){ std::size_t tmp = n >> shift; if (tmp) @@ -103,7 +103,7 @@ inline std::size_t floor_log2 (std::size_t x) return log2; } -} // namespace ipcdetail +} // namespace detail } // namespace interprocess } // namespace boost diff --git a/utils/boost_idb/boost/interprocess/detail/min_max.hpp b/utils/boost_idb/boost/interprocess/detail/min_max.hpp index 63ce7efd..7c19f597 100644 --- a/utils/boost_idb/boost/interprocess/detail/min_max.hpp +++ b/utils/boost_idb/boost/interprocess/detail/min_max.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2009. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -21,7 +21,7 @@ #include namespace boost { -namespace interprocess { +namespace interprocess { template const T &max_value(const T &a, const T &b) @@ -31,7 +31,7 @@ template const T &min_value(const T &a, const T &b) { return a < b ? a : b; } -} //namespace interprocess { +} //namespace interprocess { } //namespace boost { #include diff --git a/utils/boost_idb/boost/interprocess/detail/move.hpp b/utils/boost_idb/boost/interprocess/detail/move.hpp index 87684f62..d41f78d7 100644 --- a/utils/boost_idb/boost/interprocess/detail/move.hpp +++ b/utils/boost_idb/boost/interprocess/detail/move.hpp @@ -1,6 +1,7 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2010-2012. +// (C) Copyright David Abrahams, Vicente Botet 2009. +// (C) Copyright Ion Gaztanaga 2009-2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) @@ -11,18 +12,1146 @@ //! \file -#ifndef BOOST_INTERPROCESS_DETAIL_MOVE_HPP -#define BOOST_INTERPROCESS_DETAIL_MOVE_HPP +#ifndef BOOST_MOVE_DETAIL_MOVE_HPP +#define BOOST_MOVE_DETAIL_MOVE_HPP -#include +#include +#include //copy, copy_backward +#include //uninitialized_copy +#include //std::iterator +#include +#include +#include +#include +#include + +//! Defining or undefining this macro will change Boost.Move behaviour +//! for copyable and movable classes when assigning from non-const rvalues: +//! \code +//! copyable_and_movable produce(){ return copyable_and_movable(); } +//! \endcode +//! If the macro is NOT defined: +//! \code +//! copyable_and_movable cm; +//! cm = copyable_and_movable(); //object is COPIED (missed optimization) +//! \endcode +//! If the macro IS defined: +//! \code +//! copyable_and_movable cm; +//! cm = copyable_and_movable(); //object is MOVED +//! \endcode +//! However, the second option has also some downsides. See documentation for more details. +#define BOOST_MOVE_OPTIMIZED_EMULATION + +/// @cond + +//Define to easily port between Boost.Move and internal Boost.Interprocess move emulation +// +// This configuration is temporary. Boost.Interprocess emulation uses +// different macros to avoid any redefinition of a top-levl Boost macro. +// It will disappear once the library is accepted and +// Boost.Interprocess is updated to the standard interface. +// +#define BOOST_MOVE_IN_BOOST_INTERPROCESS_NAMESPACE + +#ifdef BOOST_MOVE_IN_BOOST_INTERPROCESS_NAMESPACE + +#define INTERPROCESS_NAMESPACE_BEGIN namespace interprocess { +#define INTERPROCESS_NAMESPACE_END }// namespace interprocess { +#define BOOST_MOVE_NAMESPACE boost::interprocess + +#else //BOOST_MOVE_IN_BOOST_INTERPROCESS_NAMESPACE + +#define INTERPROCESS_NAMESPACE_BEGIN +#define INTERPROCESS_NAMESPACE_END +#define BOOST_MOVE_NAMESPACE boost + +#endif //BOOST_MOVE_IN_BOOST_INTERPROCESS_NAMESPACE + +namespace boost { +INTERPROCESS_NAMESPACE_BEGIN +namespace move_detail { + +template +struct identity +{ + typedef T type; +}; + +template +class is_convertible +{ + typedef char true_t; + class false_t { char dummy[2]; }; + static true_t dispatch(U); + static false_t dispatch(...); + static T trigger(); + public: + enum { value = sizeof(dispatch(trigger())) == sizeof(true_t) }; +}; + +} //namespace move_detail { +INTERPROCESS_NAMESPACE_END +} //namespace boost { + +/// @endcond + +#if !defined(BOOST_NO_RVALUE_REFERENCES) + +#if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 5) + +#define BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES + +#else + +#if defined(_MSC_VER) && (_MSC_VER == 1600) +#define BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG +#endif + +#endif + +#endif + + +#if defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED) + +#include +#include +#include + +#ifdef __GNUC__ +# define BOOST_MOVE_ATTRIBUTE_MAY_ALIAS __attribute__((__may_alias__)) +#else +# define BOOST_MOVE_ATTRIBUTE_MAY_ALIAS +#endif + +namespace boost { +INTERPROCESS_NAMESPACE_BEGIN + +////////////////////////////////////////////////////////////////////////////// +// +// struct rv +// +////////////////////////////////////////////////////////////////////////////// +template +class rv : public T +{ + rv(); + ~rv(); + rv(rv const&); + void operator=(rv const&); +} BOOST_MOVE_ATTRIBUTE_MAY_ALIAS; + +////////////////////////////////////////////////////////////////////////////// +// +// move_detail::is_rv +// +////////////////////////////////////////////////////////////////////////////// + +namespace move_detail { + +template +struct is_rv +{ + static const bool value = false; +}; + +template +struct is_rv< rv > +{ + static const bool value = true; +}; + +} //namespace move_detail { + +////////////////////////////////////////////////////////////////////////////// +// +// is_movable +// +////////////////////////////////////////////////////////////////////////////// +template +struct is_movable + : public ::boost::mpl::bool_&>::value> +{ +}; + +template +struct is_movable< rv > + : public ::boost::mpl::bool_ +{ +}; + +template +struct has_nothrow_move + : public ::boost::mpl::bool_ +{ +}; + +////////////////////////////////////////////////////////////////////////////// +// +// move() +// +////////////////////////////////////////////////////////////////////////////// +template +typename ::boost::disable_if, T&>::type move(T& x) +{ + return x; +} + +template +typename enable_if, rv&>::type move(T& x) +{ + return *static_cast* >(boost::addressof(x)); +} + +template +typename enable_if, rv&>::type move(rv& x) +{ + return x; +} + + +#define BOOST_RV_REF(TYPE)\ + ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + +#define BOOST_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ + ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + +#define BOOST_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ + ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + + +#define BOOST_FWD_REF(TYPE)\ + const TYPE & \ +// + +#define BOOST_CATCH_CONST_RLVALUE(TYPE)\ + const ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + +#ifdef BOOST_MOVE_OPTIMIZED_EMULATION + +#define BOOST_COPY_ASSIGN_REF(TYPE)\ + const ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + +#define BOOST_MOVE_MACRO_COPY_ASSIGN_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ + const ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + +#define BOOST_MOVE_MACRO_COPY_ASSIGN_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ + const ::BOOST_MOVE_NAMESPACE::rv< TYPE >& \ +// + +////////////////////////////////////////////////////////////////////////////// +// +// forward() +// +////////////////////////////////////////////////////////////////////////////// + +template +typename enable_if< ::BOOST_MOVE_NAMESPACE::move_detail::is_rv, T &>::type + forward(const typename move_detail::identity::type &x) +{ + return const_cast(x); +} + +template +typename disable_if< ::BOOST_MOVE_NAMESPACE::move_detail::is_rv, const T &>::type + forward(const typename move_detail::identity::type &x) +{ + return x; +} + +#else //BOOST_MOVE_OPTIMIZED_EMULATION + +#define BOOST_COPY_ASSIGN_REF(TYPE)\ + const TYPE & \ +// + +#define BOOST_MOVE_MACRO_COPY_ASSIGN_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ + const TYPE< ARG1, ARG2 >& \ +// + +#define BOOST_MOVE_MACRO_COPY_ASSIGN_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ + const TYPE< ARG1, ARG2, ARG3 > & \ +// + +////////////////////////////////////////////////////////////////////////////// +// +// forward() +// +////////////////////////////////////////////////////////////////////////////// + +//Catches const lvalues for movable types +template +const T& + forward( BOOST_CATCH_CONST_RLVALUE(T) x + , typename ::boost::enable_if_c< ::BOOST_MOVE_NAMESPACE::is_movable::value >::type* = 0) +{ + return static_cast(x); +} + +//Catches const lvalues for non-movable types +template +const T& + forward( const T &x + , typename ::boost::enable_if_c< !::BOOST_MOVE_NAMESPACE::is_movable::value && + !::boost::move_detail::is_rv::value + >::type* = 0) +{ + return static_cast(x); +} + +//Catches forwarded ::boost::rv via BOOST_FWD_REFs +template +T & + forward( const T &t + , typename ::boost::enable_if_c< ::boost::move_detail::is_rv::value >::type* = 0) +{ + return const_cast(t); +} + +//Catches forwarded ::boost::rv +template +const T & + forward( const U &u + , typename ::boost::enable_if_c< ::boost::is_same< ::boost::rv, U >::value >::type * = 0) +{ + return static_cast(u); +} + +//Catches non-const lvalues +template +T& + forward( typename move_detail::identity::type &x + , typename ::boost::enable_if_c< !::boost::move_detail::is_rv::value >::type* = 0) +{ + return x; +} + +//Catches non-const rvalues +template +typename enable_if, ::boost::rv & >::type + forward(BOOST_RV_REF(T) x) +{ return x; } + +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// BOOST_MOVABLE_BUT_NOT_COPYABLE +// +////////////////////////////////////////////////////////////////////////////// +#define BOOST_MOVABLE_BUT_NOT_COPYABLE(TYPE)\ + private:\ + TYPE(TYPE &);\ + TYPE& operator=(TYPE &);\ + public:\ + operator ::BOOST_MOVE_NAMESPACE::rv&() \ + { return *static_cast< ::BOOST_MOVE_NAMESPACE::rv* >(this); }\ + operator const ::BOOST_MOVE_NAMESPACE::rv&() const \ + { return *static_cast* >(this); }\ + private:\ +// + +////////////////////////////////////////////////////////////////////////////// +// +// BOOST_COPYABLE_AND_MOVABLE +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef BOOST_MOVE_OPTIMIZED_EMULATION + +#define BOOST_COPYABLE_AND_MOVABLE(TYPE)\ + public:\ + TYPE& operator=(TYPE &t)\ + { this->operator=(static_cast &>(const_cast(t))); return *this;}\ + public:\ + operator ::BOOST_MOVE_NAMESPACE::rv&() \ + { return *static_cast< ::BOOST_MOVE_NAMESPACE::rv* >(this); }\ + operator const ::BOOST_MOVE_NAMESPACE::rv&() const \ + { return *static_cast* >(this); }\ + private:\ +// + +#else //#ifdef BOOST_MOVE_OPTIMIZED_EMULATION + +#define BOOST_COPYABLE_AND_MOVABLE(TYPE)\ + public:\ + operator ::BOOST_MOVE_NAMESPACE::rv&() \ + { return *static_cast< ::BOOST_MOVE_NAMESPACE::rv* >(this); }\ + operator const ::BOOST_MOVE_NAMESPACE::rv&() const \ + { return *static_cast* >(this); }\ + private:\ +// + +#endif + + +INTERPROCESS_NAMESPACE_END +} //namespace boost + +#else //BOOST_NO_RVALUE_REFERENCES + +#include + +namespace boost { +INTERPROCESS_NAMESPACE_BEGIN + +/// @cond + +namespace move_detail { + +template +struct is_lvalue_reference + : public ::boost::mpl::bool_ +{}; + +template +struct is_lvalue_reference + : public ::boost::mpl::bool_ +{}; + +typedef char one; +struct two {one _[2];}; + +template +struct internal_member_value_traits +{ + template static one test(...); + template static two test(typename U::boost_move_emulation_t* = 0); + static const bool value = sizeof(test(0)) == sizeof(two); +}; + +} //namespace move_detail { + +/// @endcond + +////////////////////////////////////////////////////////////////////////////// +// +// is_movable +// +////////////////////////////////////////////////////////////////////////////// + +//! For compilers with rvalue references, this traits class returns true +//! if BOOST_ENABLE_MOVE_EMULATION is activated. +//! +//! For other compilers returns true if T is convertible to ::boost::rv& +template +struct is_movable + : public ::boost::mpl::bool_::value> +{ +}; + +//! By default this traits returns false. Classes with non-thworing move construction +//! and assignment should specialize this trait to obtain some performance improvements. +template +struct has_nothrow_move + : public ::boost::mpl::bool_ +{}; + +////////////////////////////////////////////////////////////////////////////// +// +// move +// +////////////////////////////////////////////////////////////////////////////// + + +#if defined(BOOST_MOVE_DOXYGEN_INVOKED) +//! This function provides a way to convert a reference into a rvalue reference +//! in compilers with rvalue references. For other compilers converts T & into +//! ::boost::rv & so that move emulation is activated. +template inline +rvalue_reference move (input_reference); + +#else //BOOST_MOVE_DOXYGEN_INVOKED + +#if defined(BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES) + +//Old move approach, lvalues could bind to rvalue references +template inline +typename remove_reference::type && move(T&& t) +{ return t; } + +#else //Old move + +template inline +typename remove_reference::type && move(T&& t) +{ return static_cast::type &&>(t); } + +#endif //Old move + +#endif //BOOST_MOVE_DOXYGEN_INVOKED + + +////////////////////////////////////////////////////////////////////////////// +// +// forward +// +////////////////////////////////////////////////////////////////////////////// + + +#if defined(BOOST_MOVE_DOXYGEN_INVOKED) +//! This function provides limited form of forwarding that is usually enough for +//! in-place construction and avoids the exponential overloading necessary for +//! perfect forwarding in C++03. +//! +//! For compilers with rvalue references this function provides perfect forwarding. +//! +//! Otherwise: +//! * If input_reference binds to const ::boost::rv & then it output_reference is +//! ::boost::rev & +//! +//! * Else, input_reference is equal to output_reference is equal to input_reference. +template inline output_reference forward(input_reference); + +#else + +#if defined(BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES) + +//Old move approach, lvalues could bind to rvalue references + +template inline +T&& forward (typename move_detail::identity::type&& t) +{ return t; } + +#else //Old move + +//Implementation #5 from N2951, thanks to Howard Hinnant + +template +inline T&& forward(U&& t + , typename enable_if_c< + move_detail::is_lvalue_reference::value ? move_detail::is_lvalue_reference::value : true>::type * = 0/* + , typename enable_if_c< + move_detail::is_convertible + ::type*, typename remove_reference::type*>::value>::type * = 0*/) +{ return static_cast(t); } + +#endif //Old move + +#endif //BOOST_MOVE_DOXYGEN_INVOKED + +////////////////////////////////////////////////////////////////////////////// +// +// BOOST_ENABLE_MOVE_EMULATION +// +////////////////////////////////////////////////////////////////////////////// + +///@cond + +#define BOOST_ENABLE_MOVE_EMULATION(TYPE)\ + typedef int boost_move_emulation_t; +\ +// + +/// @endcond + +//! This macro marks a type as movable but not copyable, disabling copy construction +//! and assignment. The user will need to write a move constructor/assignment as explained +//! in the documentation to fully write a movable but not copyable class. +#define BOOST_MOVABLE_BUT_NOT_COPYABLE(TYPE)\ + public:\ + typedef int boost_move_emulation_t;\ + private:\ + TYPE(const TYPE &);\ + TYPE& operator=(const TYPE &);\ +// + +//! This macro marks a type as copyable and movable. +//! The user will need to write a move constructor/assignment and a copy assignment +//! as explained in the documentation to fully write a copyable and movable class. +#define BOOST_COPYABLE_AND_MOVABLE(TYPE)\ + typedef int boost_move_emulation_t; +// + +/// @cond + +#define BOOST_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ + TYPE && \ +// + +#define BOOST_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ + TYPE && \ +// + +/// @endcond + +//!This macro is used to achieve portable syntax in move +//!constructors and assignments for classes marked as +//!BOOST_COPYABLE_AND_MOVABLE or BOOST_MOVABLE_BUT_NOT_COPYABLE +#define BOOST_RV_REF(TYPE)\ + TYPE && \ +// + +//!This macro is used to achieve portable syntax in copy +//!assignment for classes marked as BOOST_COPYABLE_AND_MOVABLE. +#define BOOST_COPY_ASSIGN_REF(TYPE)\ + const TYPE & \ +// + +/// @cond + +#define BOOST_COPY_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2)\ + const TYPE & \ +// + +#define BOOST_COPY_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3)\ + TYPE& \ +// + +/// @endcond + +//! This macro is used to implement portable perfect forwarding +//! as explained in the documentation. +#define BOOST_FWD_REF(TYPE)\ + TYPE && \ +// + +/// @cond + +#define BOOST_CATCH_CONST_RLVALUE(TYPE)\ + const TYPE & \ +// + +/// @endcond + +INTERPROCESS_NAMESPACE_END +} //namespace boost { + +#endif //BOOST_NO_RVALUE_REFERENCES namespace boost { -namespace interprocess { +INTERPROCESS_NAMESPACE_BEGIN + +////////////////////////////////////////////////////////////////////////////// +// +// move_iterator +// +////////////////////////////////////////////////////////////////////////////// + +//! Class template move_iterator is an iterator adaptor with the same behavior +//! as the underlying iterator except that its dereference operator implicitly +//! converts the value returned by the underlying iterator's dereference operator +//! to an rvalue reference. Some generic algorithms can be called with move +//! iterators to replace copying with moving. +template +class move_iterator +{ + public: + typedef It iterator_type; + typedef typename std::iterator_traits::value_type value_type; + #if !defined(BOOST_NO_RVALUE_REFERENCES) || defined(BOOST_MOVE_DOXYGEN_INVOKED) + typedef value_type && reference; + #else + typedef typename ::boost::mpl::if_ + < ::BOOST_MOVE_NAMESPACE::is_movable + , ::BOOST_MOVE_NAMESPACE::rv& + , value_type & >::type reference; + #endif + typedef It pointer; + typedef typename std::iterator_traits::difference_type difference_type; + typedef typename std::iterator_traits::iterator_category iterator_category; + + move_iterator() + {} + + explicit move_iterator(It i) + : m_it(i) + {} + + template + move_iterator(const move_iterator& u) + : m_it(u.base()) + {} + + iterator_type base() const + { return m_it; } + + reference operator*() const + { + #if defined(BOOST_NO_RVALUE_REFERENCES) || defined(BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES) + return *m_it; + #else + return ::BOOST_MOVE_NAMESPACE::move(*m_it); + #endif + } + + pointer operator->() const + { return m_it; } + + move_iterator& operator++() + { ++m_it; return *this; } + + move_iterator operator++(int) + { move_iterator tmp(*this); ++(*this); return tmp; } + + move_iterator& operator--() + { --m_it; return *this; } + + move_iterator operator--(int) + { move_iterator tmp(*this); --(*this); return tmp; } + + move_iterator operator+ (difference_type n) const + { return move_iterator(m_it + n); } + + move_iterator& operator+=(difference_type n) + { m_it += n; return *this; } + + move_iterator operator- (difference_type n) const + { return move_iterator(m_it - n); } + + move_iterator& operator-=(difference_type n) + { m_it -= n; return *this; } + + reference operator[](difference_type n) const + { + #if defined(BOOST_NO_RVALUE_REFERENCES) || defined(BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES) + return m_it[n]; + #else + return ::BOOST_MOVE_NAMESPACE::move(m_it[n]); + #endif + } + + friend bool operator==(const move_iterator& x, const move_iterator& y) + { return x.base() == y.base(); } + + friend bool operator!=(const move_iterator& x, const move_iterator& y) + { return x.base() != y.base(); } + + friend bool operator< (const move_iterator& x, const move_iterator& y) + { return x.base() < y.base(); } + + friend bool operator<=(const move_iterator& x, const move_iterator& y) + { return x.base() <= y.base(); } + + friend bool operator> (const move_iterator& x, const move_iterator& y) + { return x.base() > y.base(); } + + friend bool operator>=(const move_iterator& x, const move_iterator& y) + { return x.base() >= y.base(); } + + friend difference_type operator-(const move_iterator& x, const move_iterator& y) + { return x.base() - y.base(); } + + friend move_iterator operator+(difference_type n, const move_iterator& x) + { return move_iterator(x.base() + n); } + + private: + It m_it; +}; + + +//is_move_iterator +namespace move_detail { + +template +struct is_move_iterator + : public ::boost::mpl::bool_ +{ +}; + +template +struct is_move_iterator< ::BOOST_MOVE_NAMESPACE::move_iterator > + : public ::boost::mpl::bool_ +{ +}; + +} //namespace move_detail { + +////////////////////////////////////////////////////////////////////////////// +// +// move_iterator +// +////////////////////////////////////////////////////////////////////////////// + +//! +//! Returns: move_iterator(i). +template +move_iterator make_move_iterator(const It &it) +{ return move_iterator(it); } + +////////////////////////////////////////////////////////////////////////////// +// +// back_move_insert_iterator +// +////////////////////////////////////////////////////////////////////////////// + + +//! A move insert iterator that move constructs elements at the +//! back of a container +template // C models Container +class back_move_insert_iterator + : public std::iterator +{ + C* container_m; + + public: + typedef C container_type; + + explicit back_move_insert_iterator(C& x) : container_m(&x) { } + + back_move_insert_iterator& operator=(typename C::reference x) + { container_m->push_back(BOOST_MOVE_NAMESPACE::move(x)); return *this; } + + back_move_insert_iterator& operator*() { return *this; } + back_move_insert_iterator& operator++() { return *this; } + back_move_insert_iterator& operator++(int) { return *this; } +}; + +//! +//! Returns: back_move_insert_iterator(x). +template // C models Container +inline back_move_insert_iterator back_move_inserter(C& x) +{ + return back_move_insert_iterator(x); +} + +////////////////////////////////////////////////////////////////////////////// +// +// front_move_insert_iterator +// +////////////////////////////////////////////////////////////////////////////// + +//! A move insert iterator that move constructs elements int the +//! front of a container +template // C models Container +class front_move_insert_iterator + : public std::iterator +{ + C* container_m; + +public: + typedef C container_type; + + explicit front_move_insert_iterator(C& x) : container_m(&x) { } + + front_move_insert_iterator& operator=(typename C::reference x) + { container_m->push_front(BOOST_MOVE_NAMESPACE::move(x)); return *this; } + + front_move_insert_iterator& operator*() { return *this; } + front_move_insert_iterator& operator++() { return *this; } + front_move_insert_iterator& operator++(int) { return *this; } +}; + +//! +//! Returns: front_move_insert_iterator(x). +template // C models Container +inline front_move_insert_iterator front_move_inserter(C& x) +{ + return front_move_insert_iterator(x); +} + +////////////////////////////////////////////////////////////////////////////// +// +// insert_move_iterator +// +////////////////////////////////////////////////////////////////////////////// +template // C models Container +class move_insert_iterator + : public std::iterator +{ + C* container_m; + typename C::iterator pos_; + + public: + typedef C container_type; + + explicit move_insert_iterator(C& x, typename C::iterator pos) + : container_m(&x), pos_(pos) + {} + + move_insert_iterator& operator=(typename C::reference x) + { + pos_ = container_m->insert(pos_, ::BOOST_MOVE_NAMESPACE::move(x)); + ++pos_; + return *this; + } + + move_insert_iterator& operator*() { return *this; } + move_insert_iterator& operator++() { return *this; } + move_insert_iterator& operator++(int) { return *this; } +}; + +//! +//! Returns: move_insert_iterator(x, it). +template // C models Container +inline move_insert_iterator move_inserter(C& x, typename C::iterator it) +{ + return move_insert_iterator(x, it); +} + +////////////////////////////////////////////////////////////////////////////// +// +// move +// +////////////////////////////////////////////////////////////////////////////// + + +//! Effects: Moves elements in the range [first,last) into the range [result,result + (last - +//! first)) starting from first and proceeding to last. For each non-negative integer n < (last-first), +//! performs *(result + n) = ::boost::move (*(first + n)). +//! +//! Effects: result + (last - first). +//! +//! Requires: result shall not be in the range [first,last). +//! +//! Complexity: Exactly last - first move assignments. +template // O models OutputIterator +O move(I f, I l, O result) +{ + while (f != l) { + *result = ::BOOST_MOVE_NAMESPACE::move(*f); + ++f; ++result; + } + return result; +} + +////////////////////////////////////////////////////////////////////////////// +// +// move_backward +// +////////////////////////////////////////////////////////////////////////////// + +//! Effects: Moves elements in the range [first,last) into the range +//! [result - (last-first),result) starting from last - 1 and proceeding to +//! first. For each positive integer n <= (last - first), +//! performs *(result - n) = ::boost::move(*(last - n)). +//! +//! Requires: result shall not be in the range [first,last). +//! +//! Returns: result - (last - first). +//! +//! Complexity: Exactly last - first assignments. +template // O models BidirectionalIterator +O move_backward(I f, I l, O result) +{ + while (f != l) { + --l; --result; + *result = ::BOOST_MOVE_NAMESPACE::move(*l); + } + return result; +} + +////////////////////////////////////////////////////////////////////////////// +// +// uninitialized_move +// +////////////////////////////////////////////////////////////////////////////// + +//! Effects: +//! \code +//! for (; first != last; ++result, ++first) +//! new (static_cast(&*result)) +//! typename iterator_traits::value_type(boost::move(*first)); +//! \endcode +//! +//! Returns: result +template + // F models ForwardIterator +F uninitialized_move(I f, I l, F r + /// @cond + ,typename enable_if::value_type> >::type* = 0 + /// @endcond + ) +{ + typedef typename std::iterator_traits::value_type input_value_type; + while (f != l) { + ::new(static_cast(&*r)) input_value_type(BOOST_MOVE_NAMESPACE::move(*f)); + ++f; ++r; + } + return r; +} + +/// @cond + +template + // F models ForwardIterator +F uninitialized_move(I f, I l, F r, + typename disable_if::value_type> >::type* = 0) +{ + return std::uninitialized_copy(f, l, r); +} + +////////////////////////////////////////////////////////////////////////////// +// +// uninitialized_copy_or_move +// +////////////////////////////////////////////////////////////////////////////// + +namespace move_detail { + +template + // F models ForwardIterator +F uninitialized_move_move_iterator(I f, I l, F r, + typename enable_if< is_movable >::type* = 0) +{ + return ::BOOST_MOVE_NAMESPACE::uninitialized_move(f, l, r); +} + +template + // F models ForwardIterator +F uninitialized_move_move_iterator(I f, I l, F r, + typename disable_if< is_movable >::type* = 0) +{ + return std::uninitialized_copy(f.base(), l.base(), r); +} + +} //namespace move_detail { + +template + // F models ForwardIterator +F uninitialized_copy_or_move(I f, I l, F r, + typename enable_if< move_detail::is_move_iterator >::type* = 0) +{ + return ::BOOST_MOVE_NAMESPACE::move_detail::uninitialized_move_move_iterator(f, l, r); +} + +////////////////////////////////////////////////////////////////////////////// +// +// copy_or_move +// +////////////////////////////////////////////////////////////////////////////// + +namespace move_detail { + +template + // F models ForwardIterator +F move_move_iterator(I f, I l, F r, + typename enable_if< is_movable >::type* = 0) +{ + return ::BOOST_MOVE_NAMESPACE::move(f, l, r); +} + +template + // F models ForwardIterator +F move_move_iterator(I f, I l, F r, + typename disable_if< is_movable >::type* = 0) +{ + return std::copy(f.base(), l.base(), r); +} + + +} //namespace move_detail { + +template + // F models ForwardIterator +F copy_or_move(I f, I l, F r, + typename enable_if< move_detail::is_move_iterator >::type* = 0) +{ + return ::BOOST_MOVE_NAMESPACE::move_detail::move_move_iterator(f, l, r); +} + +/// @endcond + +//! Effects: +//! \code +//! for (; first != last; ++result, ++first) +//! new (static_cast(&*result)) +//! typename iterator_traits::value_type(*first); +//! \endcode +//! +//! Returns: result +//! +//! Note: This function is provided because +//! std::uninitialized_copy from some STL implementations +//! is not compatible with move_iterator +template + // F models ForwardIterator +F uninitialized_copy_or_move(I f, I l, F r + /// @cond + ,typename disable_if< move_detail::is_move_iterator >::type* = 0 + /// @endcond + ) +{ + return std::uninitialized_copy(f, l, r); +} + +//! Effects: +//! \code +//! for (; first != last; ++result, ++first) +//! *result = *first; +//! \endcode +//! +//! Returns: result +//! +//! Note: This function is provided because +//! std::uninitialized_copy from some STL implementations +//! is not compatible with move_iterator +template + // F models ForwardIterator +F copy_or_move(I f, I l, F r + /// @cond + ,typename disable_if< move_detail::is_move_iterator >::type* = 0 + /// @endcond + ) +{ + return std::copy(f, l, r); +} + +//! If this trait yields to true +//! (has_trivial_destructor_after_move <T>::value == true) +//! means that if T is used as argument of a move construction/assignment, +//! there is no need to call T's destructor. +//! This optimization tipically is used to improve containers' performance. +//! +//! By default this trait is true if the type has trivial destructor, +//! every class should specialize this trait if it wants to improve performance +//! when inserted in containers. +template +struct has_trivial_destructor_after_move + : public ::boost::has_trivial_destructor +{}; + +#ifndef BOOST_MOVE_DOXYGEN_INVOKED + +#ifdef BOOST_MOVE_IN_BOOST_INTERPROCESS_NAMESPACE + +#define BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION(TYPE) BOOST_ENABLE_MOVE_EMULATION(TYPE) +#define BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(TYPE) BOOST_MOVABLE_BUT_NOT_COPYABLE(TYPE) +#define BOOST_INTERPROCESS_COPYABLE_AND_MOVABLE(TYPE) BOOST_COPYABLE_AND_MOVABLE(TYPE) +#define BOOST_INTERPROCESS_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) BOOST_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) +#define BOOST_INTERPROCESS_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) BOOST_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) +#define BOOST_INTERPROCESS_RV_REF(TYPE) BOOST_RV_REF(TYPE) +#define BOOST_INTERPROCESS_COPY_ASSIGN_REF(TYPE) BOOST_COPY_ASSIGN_REF(TYPE) +#define BOOST_INTERPROCESS_COPY_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) BOOST_COPY_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) +#define BOOST_INTERPROCESS_COPY_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) BOOST_COPY_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) +#define BOOST_INTERPROCESS_FWD_REF(TYPE) BOOST_FWD_REF(TYPE) +#define BOOST_INTERPROCESS_CATCH_CONST_RLVALUE(TYPE) BOOST_CATCH_CONST_RLVALUE(TYPE) + +#endif + +#define BOOST_MOVE_MACRO_ENABLE_MOVE_EMULATION(TYPE) BOOST_ENABLE_MOVE_EMULATION(TYPE) +#define BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(TYPE) BOOST_MOVABLE_BUT_NOT_COPYABLE(TYPE) +#define BOOST_MOVE_MACRO_COPYABLE_AND_MOVABLE(TYPE) BOOST_COPYABLE_AND_MOVABLE(TYPE) +#define BOOST_MOVE_MACRO_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) BOOST_RV_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) +#define BOOST_MOVE_MACRO_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) BOOST_RV_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) +#define BOOST_MOVE_MACRO_RV_REF(TYPE) BOOST_RV_REF(TYPE) +#define BOOST_MOVE_MACRO_COPY_ASSIGN_REF(TYPE) BOOST_COPY_ASSIGN_REF(TYPE) +#define BOOST_MOVE_MACRO_COPY_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) BOOST_COPY_REF_2_TEMPL_ARGS(TYPE, ARG1, ARG2) +#define BOOST_MOVE_MACRO_COPY_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) BOOST_COPY_REF_3_TEMPL_ARGS(TYPE, ARG1, ARG2, ARG3) +#define BOOST_MOVE_MACRO_FWD_REF(TYPE) BOOST_FWD_REF(TYPE) +#define BOOST_MOVE_MACRO_CATCH_CONST_RLVALUE(TYPE) BOOST_CATCH_CONST_RLVALUE(TYPE) -using ::boost::move; -using ::boost::forward; +#endif //BOOST_MOVE_DOXYGEN_INVOKED -} //namespace interprocess { +INTERPROCESS_NAMESPACE_END } //namespace boost { -#endif //#ifndef BOOST_INTERPROCESS_DETAIL_MOVE_HPP +#endif //#ifndef BOOST_MOVE_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/mpl.hpp b/utils/boost_idb/boost/interprocess/detail/mpl.hpp index 4c5e1f1b..93b0fe12 100644 --- a/utils/boost_idb/boost/interprocess/detail/mpl.hpp +++ b/utils/boost_idb/boost/interprocess/detail/mpl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2009. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -20,8 +20,8 @@ #include namespace boost { -namespace interprocess { -namespace ipcdetail { +namespace interprocess { +namespace detail { template struct integral_constant @@ -71,7 +71,7 @@ class is_convertible static false_t dispatch(...); static T trigger(); public: - static const bool value = sizeof(dispatch(trigger())) == sizeof(true_t); + enum { value = sizeof(dispatch(trigger())) == sizeof(true_t) }; }; template< @@ -105,24 +105,24 @@ struct if_ template -struct select1st -// : public std::unary_function +struct select1st +// : public std::unary_function { template - const typename Pair::first_type& operator()(const OtherPair& x) const + const typename Pair::first_type& operator()(const OtherPair& x) const { return x.first; } - const typename Pair::first_type& operator()(const typename Pair::first_type& x) const + const typename Pair::first_type& operator()(const typename Pair::first_type& x) const { return x; } }; // identity is an extension: it is not part of the standard. template -struct identity -// : public std::unary_function +struct identity +// : public std::unary_function { typedef T type; - const T& operator()(const T& x) const + const T& operator()(const T& x) const { return x; } }; @@ -144,8 +144,8 @@ struct ls_zeros<1> static const std::size_t value = 0; }; -} //namespace ipcdetail { -} //namespace interprocess { +} //namespace detail { +} //namespace interprocess { } //namespace boost { #endif //#ifndef BOOST_INTERPROCESS_DETAIL_MPL_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/multi_segment_services.hpp b/utils/boost_idb/boost/interprocess/detail/multi_segment_services.hpp index f625a9bc..514289b0 100644 --- a/utils/boost_idb/boost/interprocess/detail/multi_segment_services.hpp +++ b/utils/boost_idb/boost/interprocess/detail/multi_segment_services.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -20,7 +20,7 @@ /*!\file - Describes a named shared memory allocation user class. + Describes a named shared memory allocation user class. */ namespace boost { diff --git a/utils/boost_idb/boost/interprocess/detail/named_proxy.hpp b/utils/boost_idb/boost/interprocess/detail/named_proxy.hpp index 14a9aa0a..67534923 100644 --- a/utils/boost_idb/boost/interprocess/detail/named_proxy.hpp +++ b/utils/boost_idb/boost/interprocess/detail/named_proxy.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -24,9 +24,9 @@ #include #ifndef BOOST_INTERPROCESS_PERFECT_FORWARDING -#include +#include #else -#include +#include #include #endif //#ifdef BOOST_INTERPROCESS_PERFECT_FORWARDING @@ -34,15 +34,15 @@ //!Describes a proxy class that implements named allocation syntax. namespace boost { -namespace interprocess { -namespace ipcdetail { +namespace interprocess { +namespace detail { #ifdef BOOST_INTERPROCESS_PERFECT_FORWARDING template struct CtorNArg : public placement_destroy { - typedef bool_ IsIterator; + typedef detail::bool_ IsIterator; typedef CtorNArg self_t; typedef typename build_number_seq::type index_tuple_t; @@ -71,33 +71,33 @@ struct CtorNArg : public placement_destroy private: template - void construct(void *mem, true_, const index_tuple&) - { new((void*)mem)T(*boost::forward(get(args_))...); } + void construct(void *mem, detail::true_, const index_tuple&) + { new((void*)mem)T(*boost::interprocess::forward(get(args_))...); } template - void construct(void *mem, false_, const index_tuple&) - { new((void*)mem)T(boost::forward(get(args_))...); } + void construct(void *mem, detail::false_, const index_tuple&) + { new((void*)mem)T(boost::interprocess::forward(get(args_))...); } template - void do_increment(true_, const index_tuple&) + void do_increment(detail::true_, const index_tuple&) { this->expansion_helper(++get(args_)...); } - + template void expansion_helper(ExpansionArgs &&...) {} template - void do_increment(false_, const index_tuple&) + void do_increment(detail::false_, const index_tuple&) {} tuple args_; -}; +}; //!Describes a proxy class that implements named //!allocation syntax. -template +template < class SegmentManager //segment manager to construct the object , class T //type of object to build , bool is_iterator //passing parameters are normal object or iterators? @@ -119,10 +119,10 @@ class named_proxy template T *operator()(Args &&...args) const - { + { CtorNArg &&ctor_obj = CtorNArg - (boost::forward(args)...); - return mp_mngr->template + (boost::interprocess::forward(args)...); + return mp_mngr->template generic_construct(mp_name, m_num, m_find, m_dothrow, ctor_obj); } @@ -163,13 +163,13 @@ struct Ctor0Arg : public placement_destroy // struct Ctor2Arg // : public placement_destroy // { -// typedef bool_ IsIterator; +// typedef detail::bool_ IsIterator; // typedef Ctor2Arg self_t; // -// void do_increment(false_) +// void do_increment(detail::false_) // { ++m_p1; ++m_p2; } // -// void do_increment(true_){} +// void do_increment(detail::true_){} // // self_t& operator++() // { @@ -197,10 +197,10 @@ struct Ctor0Arg : public placement_destroy // } // // private: -// void construct(void *mem, true_) +// void construct(void *mem, detail::true_) // { new((void*)mem)T(*m_p1, *m_p2); } -// -// void construct(void *mem, false_) +// +// void construct(void *mem, detail::false_) // { new((void*)mem)T(m_p1, m_p2); } // // P1 &m_p1; P2 &m_p2; @@ -218,13 +218,13 @@ struct Ctor0Arg : public placement_destroy struct BOOST_PP_CAT(BOOST_PP_CAT(Ctor, n), Arg) \ : public placement_destroy \ { \ - typedef bool_ IsIterator; \ + typedef detail::bool_ IsIterator; \ typedef BOOST_PP_CAT(BOOST_PP_CAT(Ctor, n), Arg) self_t; \ \ - void do_increment(true_) \ - { BOOST_PP_ENUM(n, BOOST_INTERPROCESS_PP_PARAM_INC, _); } \ + void do_increment(detail::true_) \ + { BOOST_PP_ENUM(n, BOOST_INTERPROCESS_AUX_PARAM_INC, _); } \ \ - void do_increment(false_){} \ + void do_increment(detail::false_){} \ \ self_t& operator++() \ { \ @@ -236,7 +236,7 @@ struct Ctor0Arg : public placement_destroy \ BOOST_PP_CAT(BOOST_PP_CAT(Ctor, n), Arg) \ ( BOOST_PP_ENUM(n, BOOST_INTERPROCESS_PP_PARAM_LIST, _) ) \ - : BOOST_PP_ENUM(n, BOOST_INTERPROCESS_PP_PARAM_INIT, _) {} \ + : BOOST_PP_ENUM(n, BOOST_INTERPROCESS_AUX_PARAM_INIT, _) {} \ \ virtual void construct_n(void *mem \ , std::size_t num \ @@ -250,19 +250,19 @@ struct Ctor0Arg : public placement_destroy } \ \ private: \ - void construct(void *mem, true_) \ + void construct(void *mem, detail::true_) \ { \ new((void*)mem) T \ (BOOST_PP_ENUM(n, BOOST_INTERPROCESS_PP_MEMBER_IT_FORWARD, _)); \ } \ \ - void construct(void *mem, false_) \ + void construct(void *mem, detail::false_) \ { \ new((void*)mem) T \ (BOOST_PP_ENUM(n, BOOST_INTERPROCESS_PP_MEMBER_FORWARD, _)); \ } \ \ - BOOST_PP_REPEAT(n, BOOST_INTERPROCESS_PP_PARAM_DEFINE, _) \ + BOOST_PP_REPEAT(n, BOOST_INTERPROCESS_AUX_PARAM_DEFINE, _) \ }; \ //! #define BOOST_PP_LOCAL_LIMITS (1, BOOST_INTERPROCESS_MAX_CONSTRUCTOR_PARAMETERS) @@ -270,7 +270,7 @@ struct Ctor0Arg : public placement_destroy //!Describes a proxy class that implements named //!allocation syntax. -template +template < class SegmentManager //segment manager to construct the object , class T //type of object to build , bool is_iterator //passing parameters are normal object or iterators? @@ -293,9 +293,9 @@ class named_proxy //!makes a named allocation and calls the //!default constructor T *operator()() const - { + { Ctor0Arg ctor_obj; - return mp_mngr->template + return mp_mngr->template generic_construct(mp_name, m_num, m_find, m_dothrow, ctor_obj); } //! @@ -322,7 +322,7 @@ class named_proxy //////////////////////////////////////////////////////////////////////// // // template - // T *operator()(P1 &p1, P2 &p2) const + // T *operator()(P1 &p1, P2 &p2) const // { // typedef Ctor2Arg // @@ -342,7 +342,7 @@ class named_proxy #endif //#ifdef BOOST_INTERPROCESS_PERFECT_FORWARDING -}}} //namespace boost { namespace interprocess { namespace ipcdetail { +}}} //namespace boost { namespace interprocess { namespace detail { #include diff --git a/utils/boost_idb/boost/interprocess/detail/os_file_functions.hpp b/utils/boost_idb/boost/interprocess/detail/os_file_functions.hpp index 0bc97444..3c1b99bc 100644 --- a/utils/boost_idb/boost/interprocess/detail/os_file_functions.hpp +++ b/utils/boost_idb/boost/interprocess/detail/os_file_functions.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,9 +17,6 @@ #include #include -#include -#include -#include #if (defined BOOST_INTERPROCESS_WINDOWS) # include @@ -33,7 +30,7 @@ # include # include # if 0 -# include +# include # endif # else # error Unknown platform @@ -59,7 +56,7 @@ typedef enum { read_only = winapi::generic_read , read_write = winapi::generic_read | winapi::generic_write , copy_on_write , read_private - , invalid_mode = 0xffff + , invalid_mode = 0xffff } mode_t; typedef enum { file_begin = winapi::file_begin @@ -67,10 +64,7 @@ typedef enum { file_begin = winapi::file_begin , file_current = winapi::file_current } file_pos_t; -typedef unsigned long map_options_t; -static const map_options_t default_map_options = map_options_t(-1); - -namespace ipcdetail{ +namespace detail{ inline mapping_handle_t mapping_handle_from_file_handle(file_handle_t hnd) { @@ -99,29 +93,29 @@ inline const char *get_temporary_path() inline file_handle_t create_new_file - (const char *name, mode_t mode, const permissions & perm = permissions(), bool temporary = false) -{ + (const char *name, mode_t mode, const permissions & perm, bool temporary = false) +{ unsigned long attr = temporary ? winapi::file_attribute_temporary : 0; return winapi::create_file ( name, (unsigned int)mode, winapi::create_new, attr - , (winapi::interprocess_security_attributes*)perm.get_permissions()); + , (winapi::interprocess_security_attributes*)perm.get_permissions()); } inline file_handle_t create_or_open_file - (const char *name, mode_t mode, const permissions & perm = permissions(), bool temporary = false) -{ + (const char *name, mode_t mode, const permissions & perm, bool temporary = false) +{ unsigned long attr = temporary ? winapi::file_attribute_temporary : 0; return winapi::create_file ( name, (unsigned int)mode, winapi::open_always, attr - , (winapi::interprocess_security_attributes*)perm.get_permissions()); + , (winapi::interprocess_security_attributes*)perm.get_permissions()); } inline file_handle_t open_existing_file (const char *name, mode_t mode, bool temporary = false) -{ +{ unsigned long attr = temporary ? winapi::file_attribute_temporary : 0; return winapi::create_file - (name, (unsigned int)mode, winapi::open_existing, attr, 0); + (name, (unsigned int)mode, winapi::open_existing, attr, 0); } inline bool delete_file(const char *name) @@ -133,18 +127,10 @@ inline bool truncate_file (file_handle_t hnd, std::size_t size) if(!winapi::get_file_size(hnd, filesize)) return false; - typedef boost::make_unsigned::type uoffset_t; - const uoffset_t max_filesize = uoffset_t((std::numeric_limits::max)()); - //Avoid unused variable warnings in 32 bit systems - if(size > max_filesize){ - winapi::set_last_error(winapi::error_file_too_large); - return false; - } - - if(offset_t(size) > filesize){ + if(size > (unsigned long long)filesize){ if(!winapi::set_file_pointer_ex(hnd, filesize, 0, winapi::file_begin)){ return false; - } + } //We will write zeros in the end of the file //since set_end_of_file does not guarantee this for(std::size_t remaining = size - filesize, write_size = 0 @@ -181,7 +167,7 @@ inline bool get_file_pointer(file_handle_t hnd, offset_t &off) { return winapi::set_file_pointer_ex(hnd, 0, &off, winapi::file_current); } inline bool write_file(file_handle_t hnd, const void *data, std::size_t numdata) -{ +{ unsigned long written; return 0 != winapi::write_file(hnd, data, (unsigned long)numdata, &written, 0); } @@ -193,9 +179,9 @@ inline bool close_file(file_handle_t hnd) { return 0 != winapi::close_handle(hnd); } inline bool acquire_file_lock(file_handle_t hnd) -{ +{ static winapi::interprocess_overlapped overlapped; - const unsigned long len = ((unsigned long)-1); + const unsigned long len = 0xffffffff; // winapi::interprocess_overlapped overlapped; // std::memset(&overlapped, 0, sizeof(overlapped)); return winapi::lock_file_ex @@ -203,44 +189,44 @@ inline bool acquire_file_lock(file_handle_t hnd) } inline bool try_acquire_file_lock(file_handle_t hnd, bool &acquired) -{ - const unsigned long len = ((unsigned long)-1); +{ + const unsigned long len = 0xffffffff; winapi::interprocess_overlapped overlapped; std::memset(&overlapped, 0, sizeof(overlapped)); if(!winapi::lock_file_ex - (hnd, winapi::lockfile_exclusive_lock | winapi::lockfile_fail_immediately, + (hnd, winapi::lockfile_exclusive_lock | winapi::lockfile_fail_immediately, 0, len, len, &overlapped)){ - return winapi::get_last_error() == winapi::error_lock_violation ? + return winapi::get_last_error() == winapi::error_lock_violation ? acquired = false, true : false; - + } return (acquired = true); } inline bool release_file_lock(file_handle_t hnd) -{ - const unsigned long len = ((unsigned long)-1); +{ + const unsigned long len = 0xffffffff; winapi::interprocess_overlapped overlapped; std::memset(&overlapped, 0, sizeof(overlapped)); return winapi::unlock_file_ex(hnd, 0, len, len, &overlapped); } inline bool acquire_file_lock_sharable(file_handle_t hnd) -{ - const unsigned long len = ((unsigned long)-1); +{ + const unsigned long len = 0xffffffff; winapi::interprocess_overlapped overlapped; std::memset(&overlapped, 0, sizeof(overlapped)); return winapi::lock_file_ex(hnd, 0, 0, len, len, &overlapped); } inline bool try_acquire_file_lock_sharable(file_handle_t hnd, bool &acquired) -{ - const unsigned long len = ((unsigned long)-1); +{ + const unsigned long len = 0xffffffff; winapi::interprocess_overlapped overlapped; std::memset(&overlapped, 0, sizeof(overlapped)); if(!winapi::lock_file_ex (hnd, winapi::lockfile_fail_immediately, 0, len, len, &overlapped)){ - return winapi::get_last_error() == winapi::error_lock_violation ? + return winapi::get_last_error() == winapi::error_lock_violation ? acquired = false, true : false; } return (acquired = true); @@ -282,7 +268,7 @@ inline bool delete_subdirectories_recursive //if(::SetFileAttributes(strFilePath.c_str(), winapi::file_attribute_normal) == 0) //return winapi::get_last_error(); // Delete file - winapi::unlink_file(strFilePath.c_str()); + winapi::delete_file(strFilePath.c_str()); } } //Go to the next file @@ -371,7 +357,7 @@ typedef enum { read_only = O_RDONLY , read_write = O_RDWR , copy_on_write , read_private - , invalid_mode = 0xffff + , invalid_mode = 0xffff } mode_t; typedef enum { file_begin = SEEK_SET @@ -379,10 +365,7 @@ typedef enum { file_begin = SEEK_SET , file_current = SEEK_CUR } file_pos_t; -typedef int map_options_t; -static const map_options_t default_map_options = map_options_t(-1); - -namespace ipcdetail{ +namespace detail{ inline mapping_handle_t mapping_handle_from_file_handle(file_handle_t hnd) { @@ -412,8 +395,8 @@ inline const char *get_temporary_path() } inline file_handle_t create_new_file - (const char *name, mode_t mode, const permissions & perm = permissions(), bool temporary = false) -{ + (const char *name, mode_t mode, const permissions & perm, bool temporary = false) +{ (void)temporary; int ret = ::open(name, ((int)mode) | O_EXCL | O_CREAT, perm.get_permissions()); if(ret >= 0){ @@ -423,49 +406,31 @@ inline file_handle_t create_new_file } inline file_handle_t create_or_open_file - (const char *name, mode_t mode, const permissions & perm = permissions(), bool temporary = false) -{ + (const char *name, mode_t mode, const permissions & perm, bool temporary = false) +{ (void)temporary; - int ret = -1; - //We need a loop to change permissions correctly using fchmod, since - //with "O_CREAT only" ::open we don't know if we've created or opened the file. - while(1){ - ret = ::open(name, ((int)mode) | O_EXCL | O_CREAT, perm.get_permissions()); - if(ret >= 0){ - ::fchmod(ret, perm.get_permissions()); - break; - } - else if(errno == EEXIST){ - if((ret = ::open(name, (int)mode)) >= 0 || errno != ENOENT){ - break; - } - } + int ret = ::open(name, ((int)mode) | O_CREAT, perm.get_permissions()); + if(ret >= 0){ + ::fchmod(ret, perm.get_permissions()); } return ret; } inline file_handle_t open_existing_file (const char *name, mode_t mode, bool temporary = false) -{ +{ (void)temporary; - return ::open(name, (int)mode); + return ::open(name, (int)mode, 0666); } inline bool delete_file(const char *name) { return ::unlink(name) == 0; } inline bool truncate_file (file_handle_t hnd, std::size_t size) -{ - typedef boost::make_unsigned::type uoff_t; - if(uoff_t((std::numeric_limits::max)()) < size){ - errno = EINVAL; - return false; - } - return 0 == ::ftruncate(hnd, off_t(size)); -} +{ return 0 == ::ftruncate(hnd, size); } inline bool get_file_size(file_handle_t hnd, offset_t &size) -{ +{ struct stat data; bool ret = 0 == ::fstat(hnd, &data); if(ret){ @@ -478,7 +443,7 @@ inline bool set_file_pointer(file_handle_t hnd, offset_t off, file_pos_t pos) { return ((off_t)(-1)) != ::lseek(hnd, off, (int)pos); } inline bool get_file_pointer(file_handle_t hnd, offset_t &off) -{ +{ off = ::lseek(hnd, 0, SEEK_CUR); return off != ((off_t)-1); } @@ -528,7 +493,7 @@ inline bool release_file_lock(file_handle_t hnd) } inline bool acquire_file_lock_sharable(file_handle_t hnd) -{ +{ struct ::flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; @@ -538,7 +503,7 @@ inline bool acquire_file_lock_sharable(file_handle_t hnd) } inline bool try_acquire_file_lock_sharable(file_handle_t hnd, bool &acquired) -{ +{ struct flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; @@ -546,7 +511,7 @@ inline bool try_acquire_file_lock_sharable(file_handle_t hnd, bool &acquired) lock.l_len = 0; int ret = ::fcntl(hnd, F_SETLK, &lock); if(ret == -1){ - return (errno == EAGAIN || errno == EACCES) ? + return (errno == EAGAIN || errno == EACCES) ? acquired = false, true : false; } return (acquired = true); @@ -607,7 +572,7 @@ inline bool delete_subdirectories_recursive || (de->d_name[1] == '.' && de->d_name[2] == '\0' )) ){ continue; } - if(dont_delete_this && std::strcmp(dont_delete_this, de->d_name) == 0){ + if(dont_delete_this && std::strcmp(dont_delete_this, de->d_name) == 0){ continue; } fn = refcstrRootDirectory; @@ -693,7 +658,7 @@ inline bool open_or_create_directory(const char *dir_name) } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/detail/os_thread_functions.hpp b/utils/boost_idb/boost/interprocess/detail/os_thread_functions.hpp index eea4957a..5d8ebb04 100644 --- a/utils/boost_idb/boost/interprocess/detail/os_thread_functions.hpp +++ b/utils/boost_idb/boost/interprocess/detail/os_thread_functions.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,17 +8,6 @@ // ////////////////////////////////////////////////////////////////////////////// -//Thread launching functions are adapted from boost/detail/lightweight_thread.hpp -// -// boost/detail/lightweight_thread.hpp -// -// Copyright (c) 2002 Peter Dimov and Multi Media Ltd. -// Copyright (c) 2008 Peter Dimov -// -// Distributed under the Boost Software License, Version 1.0. -// See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt - #ifndef BOOST_INTERPROCESS_DETAIL_OS_THREAD_FUNCTIONS_HPP #define BOOST_INTERPROCESS_DETAIL_OS_THREAD_FUNCTIONS_HPP @@ -26,50 +15,27 @@ #include #include #include -#include -#include -#if defined(BOOST_INTERPROCESS_WINDOWS) +#if (defined BOOST_INTERPROCESS_WINDOWS) # include -# include #else -# include -# include -# include -# include -# ifdef BOOST_INTERPROCESS_BSD_DERIVATIVE - //Some *BSD systems (OpenBSD & NetBSD) need sys/param.h before sys/sysctl.h, whereas - //others (FreeBSD & Darwin) need sys/types.h -# include -# include -# include -# endif -//According to the article "C/C++ tip: How to measure elapsed real time for benchmarking" -# if defined(CLOCK_MONOTONIC_PRECISE) //BSD -# define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_MONOTONIC_PRECISE -# elif defined(CLOCK_MONOTONIC_RAW) //Linux -# define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_MONOTONIC_RAW -# elif defined(CLOCK_HIGHRES) //Solaris -# define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_HIGHRES -# elif defined(CLOCK_MONOTONIC) //POSIX (AIX, BSD, Linux, Solaris) -# define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_MONOTONIC -# elif !defined(CLOCK_MONOTONIC) && (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) -# include // mach_absolute_time, mach_timebase_info_data_t -# define BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME +# ifdef BOOST_HAS_UNISTD_H +# include +# include +# include # else -# error "No high resolution steady clock in your system, please provide a patch" +# error Unknown platform # endif #endif namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ #if (defined BOOST_INTERPROCESS_WINDOWS) typedef unsigned long OS_process_id_t; typedef unsigned long OS_thread_id_t; -typedef void* OS_thread_t; typedef OS_thread_id_t OS_systemwide_thread_id_t; //process @@ -89,84 +55,9 @@ inline OS_thread_id_t get_invalid_thread_id() inline bool equal_thread_id(OS_thread_id_t id1, OS_thread_id_t id2) { return id1 == id2; } -//return the system tick in ns -inline unsigned long get_system_tick_ns() -{ - unsigned long curres; - winapi::set_timer_resolution(10000, 0, &curres); - //Windows API returns the value in hundreds of ns - return (curres - 1ul)*100ul; -} - -//return the system tick in us -inline unsigned long get_system_tick_us() -{ - unsigned long curres; - winapi::set_timer_resolution(10000, 0, &curres); - //Windows API returns the value in hundreds of ns - return (curres - 1ul)/10ul + 1ul; -} - -typedef unsigned __int64 OS_highres_count_t; - -inline unsigned long get_system_tick_in_highres_counts() -{ - __int64 freq; - unsigned long curres; - winapi::set_timer_resolution(10000, 0, &curres); - //Frequency in counts per second - if(!winapi::query_performance_frequency(&freq)){ - //Tick resolution in ms - return (curres-1ul)/10000ul + 1ul; - } - else{ - //In femtoseconds - __int64 count_fs = (1000000000000000LL - 1LL)/freq + 1LL; - __int64 tick_counts = (static_cast<__int64>(curres)*100000000LL - 1LL)/count_fs + 1LL; - return static_cast(tick_counts); - } -} - -inline OS_highres_count_t get_current_system_highres_count() -{ - __int64 count; - if(!winapi::query_performance_counter(&count)){ - count = winapi::get_tick_count(); - } - return count; -} - -inline void zero_highres_count(OS_highres_count_t &count) -{ count = 0; } - -inline bool is_highres_count_zero(const OS_highres_count_t &count) -{ return count == 0; } - -template -inline Ostream &ostream_highres_count(Ostream &ostream, const OS_highres_count_t &count) -{ - ostream << count; - return ostream; -} - -inline OS_highres_count_t system_highres_count_subtract(const OS_highres_count_t &l, const OS_highres_count_t &r) -{ return l - r; } - -inline bool system_highres_count_less(const OS_highres_count_t &l, const OS_highres_count_t &r) -{ return l < r; } - -inline bool system_highres_count_less_ul(const OS_highres_count_t &l, unsigned long r) -{ return l < static_cast(r); } - -inline void thread_sleep_tick() -{ winapi::sleep_tick(); } - inline void thread_yield() { winapi::sched_yield(); } -inline void thread_sleep(unsigned int ms) -{ winapi::Sleep(ms); } - //systemwide thread inline OS_systemwide_thread_id_t get_current_systemwide_thread_id() { @@ -202,22 +93,14 @@ inline long double get_current_process_creation_time() CreationTime.dwLowDateTime*resolution; } -inline unsigned int get_num_cores() -{ - winapi::system_info sysinfo; - winapi::get_system_info( &sysinfo ); - //in Windows dw is long which is equal in bits to int - return static_cast(sysinfo.dwNumberOfProcessors); -} #else //#if (defined BOOST_INTERPROCESS_WINDOWS) -typedef pthread_t OS_thread_t; typedef pthread_t OS_thread_id_t; typedef pid_t OS_process_id_t; struct OS_systemwide_thread_id_t -{ +{ OS_systemwide_thread_id_t() : pid(), tid() {} @@ -266,7 +149,7 @@ inline OS_thread_id_t get_current_thread_id() { return ::pthread_self(); } inline OS_thread_id_t get_invalid_thread_id() -{ +{ static pthread_t invalid_id; return invalid_id; } @@ -277,138 +160,6 @@ inline bool equal_thread_id(OS_thread_id_t id1, OS_thread_id_t id2) inline void thread_yield() { ::sched_yield(); } -#ifndef BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME -typedef struct timespec OS_highres_count_t; -#else -typedef unsigned long long OS_highres_count_t; -#endif - -inline unsigned long get_system_tick_ns() -{ - #ifdef _SC_CLK_TCK - long hz =::sysconf(_SC_CLK_TCK); // ticks per sec - if(hz <= 0){ //Try a typical value on error - hz = 100; - } - return 999999999ul/static_cast(hz)+1ul; - #else - #error "Can't obtain system tick value for your system, please provide a patch" - #endif -} - -inline unsigned long get_system_tick_in_highres_counts() -{ - #ifndef BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME - return get_system_tick_ns(); - #else - mach_timebase_info_data_t info; - mach_timebase_info(&info); - //ns - return static_cast - ( - static_cast(get_system_tick_ns()) - / (static_cast(info.numer) / info.denom) - ); - #endif -} - -//return system ticks in us -inline unsigned long get_system_tick_us() -{ - return (get_system_tick_ns()-1)/1000ul + 1ul; -} - -inline OS_highres_count_t get_current_system_highres_count() -{ - #if defined(BOOST_INTERPROCESS_CLOCK_MONOTONIC) - struct timespec count; - ::clock_gettime(BOOST_INTERPROCESS_CLOCK_MONOTONIC, &count); - return count; - #elif defined(BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME) - return ::mach_absolute_time(); - #endif -} - -#ifndef BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME - -inline void zero_highres_count(OS_highres_count_t &count) -{ count.tv_sec = 0; count.tv_nsec = 0; } - -inline bool is_highres_count_zero(const OS_highres_count_t &count) -{ return count.tv_sec == 0 && count.tv_nsec == 0; } - -template -inline Ostream &ostream_highres_count(Ostream &ostream, const OS_highres_count_t &count) -{ - ostream << count.tv_sec << "s:" << count.tv_nsec << "ns"; - return ostream; -} - -inline OS_highres_count_t system_highres_count_subtract(const OS_highres_count_t &l, const OS_highres_count_t &r) -{ - OS_highres_count_t res; - - if (l.tv_nsec < r.tv_nsec){ - res.tv_nsec = 1000000000 + l.tv_nsec - r.tv_nsec; - res.tv_sec = l.tv_sec - 1 - r.tv_sec; - } - else{ - res.tv_nsec = l.tv_nsec - r.tv_nsec; - res.tv_sec = l.tv_sec - r.tv_sec; - } - - return res; -} - -inline bool system_highres_count_less(const OS_highres_count_t &l, const OS_highres_count_t &r) -{ return l.tv_sec < r.tv_sec || (l.tv_sec == r.tv_sec && l.tv_nsec < r.tv_nsec); } - -inline bool system_highres_count_less_ul(const OS_highres_count_t &l, unsigned long r) -{ return !l.tv_sec && (static_cast(l.tv_nsec) < r); } - -#else - -inline void zero_highres_count(OS_highres_count_t &count) -{ count = 0; } - -inline bool is_highres_count_zero(const OS_highres_count_t &count) -{ return count == 0; } - -template -inline Ostream &ostream_highres_count(Ostream &ostream, const OS_highres_count_t &count) -{ - ostream << count ; - return ostream; -} - -inline OS_highres_count_t system_highres_count_subtract(const OS_highres_count_t &l, const OS_highres_count_t &r) -{ return l - r; } - -inline bool system_highres_count_less(const OS_highres_count_t &l, const OS_highres_count_t &r) -{ return l < r; } - -inline bool system_highres_count_less_ul(const OS_highres_count_t &l, unsigned long r) -{ return l < static_cast(r); } - -#endif - -inline void thread_sleep_tick() -{ - struct timespec rqt; - //Sleep for the half of the tick time - rqt.tv_sec = 0; - rqt.tv_nsec = get_system_tick_ns()/2; - ::nanosleep(&rqt, 0); -} - -inline void thread_sleep(unsigned int ms) -{ - struct timespec rqt; - rqt.tv_sec = ms/1000u; - rqt.tv_nsec = (ms%1000u)*1000000u; - ::nanosleep(&rqt, 0); -} - //systemwide thread inline OS_systemwide_thread_id_t get_current_systemwide_thread_id() { @@ -428,45 +179,6 @@ inline OS_systemwide_thread_id_t get_invalid_systemwide_thread_id() inline long double get_current_process_creation_time() { return 0.0L; } -inline unsigned int get_num_cores() -{ - #ifdef _SC_NPROCESSORS_ONLN - long cores = ::sysconf(_SC_NPROCESSORS_ONLN); - // sysconf returns -1 if the name is invalid, the option does not exist or - // does not have a definite limit. - // if sysconf returns some other negative number, we have no idea - // what is going on. Default to something safe. - if(cores <= 0){ - return 1; - } - //Check for overflow (unlikely) - else if(static_cast(cores) >= - static_cast(static_cast(-1))){ - return static_cast(-1); - } - else{ - return static_cast(cores); - } - #elif defined(BOOST_INTERPROCESS_BSD_DERIVATIVE) && defined(HW_NCPU) - int request[2] = { CTL_HW, HW_NCPU }; - int num_cores; - std::size_t result_len = sizeof(num_cores); - if ( (::sysctl (request, 2, &num_cores, &result_len, 0, 0) < 0) || (num_cores <= 0) ){ - //Return a safe value - return 1; - } - else{ - return static_cast(num_cores); - } - #endif -} - -inline int thread_create(OS_thread_t * thread, void *(*start_routine)(void*), void* arg) -{ return pthread_create(thread, 0, start_routine, arg); } - -inline void thread_join(OS_thread_t thread) -{ (void)pthread_join(thread, 0); } - #endif //#if (defined BOOST_INTERPROCESS_WINDOWS) typedef char pid_str_t[sizeof(OS_process_id_t)*3+1]; @@ -480,88 +192,7 @@ inline void get_pid_str(pid_str_t &pid_str, OS_process_id_t pid) inline void get_pid_str(pid_str_t &pid_str) { get_pid_str(pid_str, get_current_process_id()); } -#if defined(BOOST_INTERPROCESS_WINDOWS) - -inline int thread_create( OS_thread_t * thread, unsigned (__stdcall * start_routine) (void*), void* arg ) -{ - void* h = (void*)_beginthreadex( 0, 0, start_routine, arg, 0, 0 ); - - if( h != 0 ){ - *thread = h; - return 0; - } - else{ - return 1; - } -} - -inline void thread_join( OS_thread_t thread) -{ - winapi::wait_for_single_object( thread, winapi::infinite_time ); - winapi::close_handle( thread ); -} - -#endif - -class abstract_thread -{ - public: - virtual ~abstract_thread() {} - virtual void run() = 0; -}; - -#if defined(BOOST_INTERPROCESS_WINDOWS) - -inline unsigned __stdcall launch_thread_routine( void * pv ) -{ - std::auto_ptr pt( static_cast( pv ) ); - pt->run(); - return 0; -} - -#else - -extern "C" void * launch_thread_routine( void * pv ); - -inline void * launch_thread_routine( void * pv ) -{ - std::auto_ptr pt( static_cast( pv ) ); - pt->run(); - return 0; -} - -#endif - -template -class launch_thread_impl - : public abstract_thread -{ - public: - explicit launch_thread_impl( F f ) - : f_( f ) - {} - - void run() - { f_(); } - - private: - F f_; -}; - -template -inline int thread_launch( OS_thread_t & pt, F f ) -{ - std::auto_ptr p( new launch_thread_impl( f ) ); - - int r = thread_create(&pt, launch_thread_routine, p.get()); - if( r == 0 ){ - p.release(); - } - - return r; -} - -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/detail/pointer_type.hpp b/utils/boost_idb/boost/interprocess/detail/pointer_type.hpp index aa8da550..ec0801b3 100644 --- a/utils/boost_idb/boost/interprocess/detail/pointer_type.hpp +++ b/utils/boost_idb/boost/interprocess/detail/pointer_type.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2009. // (C) Copyright Gennaro Prota 2003 - 2004. // // Distributed under the Boost Software License, Version 1.0. @@ -24,7 +24,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { struct two {char _[2];}; @@ -61,11 +61,11 @@ template struct pointer_type { typedef typename pointer_type_imp::pointer_type::type>::type type; + typename detail::remove_reference::type>::type type; }; -} //namespace ipcdetail { -} //namespace interprocess { +} //namespace detail { +} //namespace interprocess { } //namespace boost { #include diff --git a/utils/boost_idb/boost/interprocess/detail/portable_intermodule_singleton.hpp b/utils/boost_idb/boost/interprocess/detail/portable_intermodule_singleton.hpp deleted file mode 100644 index 2d019068..00000000 --- a/utils/boost_idb/boost/interprocess/detail/portable_intermodule_singleton.hpp +++ /dev/null @@ -1,356 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_PORTABLE_INTERMODULE_SINGLETON_HPP -#define BOOST_INTERPROCESS_PORTABLE_INTERMODULE_SINGLETON_HPP - -#if defined(_MSC_VER)&&(_MSC_VER>=1200) -#pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace interprocess{ -namespace ipcdetail{ - -typedef basic_managed_global_memory managed_global_memory; - -namespace intermodule_singleton_helpers { - -static void create_tmp_subdir_and_get_pid_based_filepath - (const char *subdir_name, const char *file_prefix, OS_process_id_t pid, std::string &s, bool creation_time = false) -{ - //Let's create a lock file for each process gmem that will mark if - //the process is alive or not - create_tmp_and_clean_old(s); - s += "/"; - s += subdir_name; - if(!open_or_create_directory(s.c_str())){ - throw interprocess_exception(error_info(system_error_code())); - } - s += "/"; - s += file_prefix; - if(creation_time){ - std::string sstamp; - get_pid_creation_time_str(sstamp); - s += sstamp; - } - else{ - pid_str_t pid_str; - get_pid_str(pid_str, pid); - s += pid_str; - } -} - -static bool check_if_filename_complies_with_pid - (const char *filename, const char *prefix, OS_process_id_t pid, std::string &file_suffix, bool creation_time = false) -{ - //Check if filename complies with lock file name pattern - std::string fname(filename); - std::string fprefix(prefix); - if(fname.size() <= fprefix.size()){ - return false; - } - fname.resize(fprefix.size()); - if(fname != fprefix){ - return false; - } - - //If not our lock file, delete it if we can lock it - fname = filename; - fname.erase(0, fprefix.size()); - pid_str_t pid_str; - get_pid_str(pid_str, pid); - file_suffix = pid_str; - if(creation_time){ - std::size_t p = fname.find('_'); - if (p == std::string::npos){ - return false; - } - std::string save_suffix(fname); - fname.erase(p); - fname.swap(file_suffix); - bool ret = (file_suffix == fname); - file_suffix.swap(save_suffix); - return ret; - } - else{ - fname.swap(file_suffix); - return (file_suffix == fname); - } -} - -template<> -struct thread_safe_global_map_dependant -{ - private: - static const int GMemMarkToBeRemoved = -1; - static const int GMemNotPresent = -2; - - static const char *get_lock_file_subdir_name() - { return "gmem"; } - - static const char *get_lock_file_base_name() - { return "lck"; } - - static void create_and_get_singleton_lock_file_path(std::string &s) - { - create_tmp_subdir_and_get_pid_based_filepath - (get_lock_file_subdir_name(), get_lock_file_base_name(), get_current_process_id(), s, true); - } - - struct gmem_erase_func - { - gmem_erase_func(const char *shm_name, const char *singleton_lock_file_path, managed_global_memory & shm) - :shm_name_(shm_name), singleton_lock_file_path_(singleton_lock_file_path), shm_(shm) - {} - - void operator()() - { - locking_file_serial_id *pserial_id = shm_.find("lock_file_fd").first; - if(pserial_id){ - pserial_id->fd = GMemMarkToBeRemoved; - } - delete_file(singleton_lock_file_path_); - shared_memory_object::remove(shm_name_); - } - - const char * const shm_name_; - const char * const singleton_lock_file_path_; - managed_global_memory & shm_; - }; - - //This function applies shared memory erasure logic based on the passed lock file. - static void apply_gmem_erase_logic(const char *filepath, const char *filename) - { - int fd = GMemMarkToBeRemoved; - try{ - std::string str; - //If the filename is current process lock file, then avoid it - if(check_if_filename_complies_with_pid - (filename, get_lock_file_base_name(), get_current_process_id(), str, true)){ - return; - } - //Open and lock the other process' lock file - fd = try_open_and_lock_file(filepath); - if(fd < 0){ - return; - } - //If done, then the process is dead so take global shared memory name - //(the name is based on the lock file name) and try to apply erasure logic - str.insert(0, get_map_base_name()); - try{ - managed_global_memory shm(open_only, str.c_str()); - gmem_erase_func func(str.c_str(), filepath, shm); - shm.try_atomic_func(func); - } - catch(interprocess_exception &e){ - //If shared memory is not found erase the lock file - if(e.get_error_code() == not_found_error){ - delete_file(filepath); - } - } - } - catch(...){ - - } - if(fd >= 0){ - close_lock_file(fd); - } - } - - public: - - static bool remove_old_gmem() - { - std::string refcstrRootDirectory; - tmp_folder(refcstrRootDirectory); - refcstrRootDirectory += "/"; - refcstrRootDirectory += get_lock_file_subdir_name(); - return for_each_file_in_dir(refcstrRootDirectory.c_str(), apply_gmem_erase_logic); - } - - struct lock_file_logic - { - lock_file_logic(managed_global_memory &shm) - : mshm(shm) - { shm.atomic_func(*this); } - - void operator()(void) - { - retry_with_new_map = false; - - //First find the file locking descriptor id - locking_file_serial_id *pserial_id = - mshm.find("lock_file_fd").first; - - int fd; - //If not found schedule a creation - if(!pserial_id){ - fd = GMemNotPresent; - } - //Else get it - else{ - fd = pserial_id->fd; - } - //If we need to create a new one, do it - if(fd == GMemNotPresent){ - std::string lck_str; - //Create a unique current pid based lock file path - create_and_get_singleton_lock_file_path(lck_str); - //Open or create and lock file - int fd_lockfile = open_or_create_and_lock_file(lck_str.c_str()); - //If failed, write a bad file descriptor to notify other modules that - //something was wrong and unlink shared memory. Mark the function object - //to tell caller to retry with another shared memory - if(fd_lockfile < 0){ - this->register_lock_file(GMemMarkToBeRemoved); - std::string s; - get_map_name(s); - shared_memory_object::remove(s.c_str()); - retry_with_new_map = true; - } - //If successful, register the file descriptor - else{ - this->register_lock_file(fd_lockfile); - } - } - //If the fd was invalid (maybe a previous try failed) notify caller that - //should retry creation logic, since this shm might have been already - //unlinked since the shm was removed - else if (fd == GMemMarkToBeRemoved){ - retry_with_new_map = true; - } - //If the stored fd is not valid (a open fd, a normal file with the - //expected size, or does not have the same file id number, - //then it's an old shm from an old process with the same pid. - //If that's the case, mark it as invalid - else if(!is_valid_fd(fd) || - !is_normal_file(fd) || - 0 != get_size(fd) || - !compare_file_serial(fd, *pserial_id)){ - pserial_id->fd = GMemMarkToBeRemoved; - std::string s; - get_map_name(s); - shared_memory_object::remove(s.c_str()); - retry_with_new_map = true; - } - else{ - //If the lock file is ok, increment reference count of - //attached modules to shared memory - atomic_inc32(&pserial_id->modules_attached_to_gmem_count); - } - } - - bool retry() const { return retry_with_new_map; } - - private: - locking_file_serial_id * register_lock_file(int fd) - { - locking_file_serial_id *pinfo = mshm.construct("lock_file_fd")(); - fill_file_serial_id(fd, *pinfo); - return pinfo; - } - - managed_global_memory &mshm; - bool retry_with_new_map; - }; - - static void construct_map(void *addr) - { - std::string s; - intermodule_singleton_helpers::get_map_name(s); - const char *MapName = s.c_str(); - const std::size_t MapSize = intermodule_singleton_helpers::get_map_size();; - ::new (addr)managed_global_memory(open_or_create, MapName, MapSize); - } - - struct unlink_map_logic - { - unlink_map_logic(managed_global_memory &mshm) - : mshm_(mshm) - { mshm.atomic_func(*this); } - - void operator()() - { - locking_file_serial_id *pserial_id = - mshm_.find - ("lock_file_fd").first; - BOOST_ASSERT(0 != pserial_id); - if(1 == atomic_dec32(&pserial_id->modules_attached_to_gmem_count)){ - int fd = pserial_id->fd; - if(fd > 0){ - pserial_id->fd = GMemMarkToBeRemoved; - std::string s; - create_and_get_singleton_lock_file_path(s); - delete_file(s.c_str()); - close_lock_file(fd); - intermodule_singleton_helpers::get_map_name(s); - shared_memory_object::remove(s.c_str()); - } - } - } - - private: - managed_global_memory &mshm_; - }; - - static ref_count_ptr *find(managed_global_memory &map, const char *name) - { - return map.find(name).first; - } - - static ref_count_ptr *insert(managed_global_memory &map, const char *name, const ref_count_ptr &ref) - { - return map.construct(name)(ref); - } - - static bool erase(managed_global_memory &map, const char *name) - { - return map.destroy(name); - } - - template - static void atomic_func(managed_global_memory &map, F &f) - { - map.atomic_func(f); - } -}; - -} //namespace intermodule_singleton_helpers { - -template -class portable_intermodule_singleton - : public intermodule_singleton_impl -{}; - -} //namespace ipcdetail{ -} //namespace interprocess{ -} //namespace boost{ - -#include - -#endif //#ifndef BOOST_INTERPROCESS_PORTABLE_INTERMODULE_SINGLETON_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/posix_time_types_wrk.hpp b/utils/boost_idb/boost/interprocess/detail/posix_time_types_wrk.hpp index fa167f57..ed46e4fa 100644 --- a/utils/boost_idb/boost/interprocess/detail/posix_time_types_wrk.hpp +++ b/utils/boost_idb/boost/interprocess/detail/posix_time_types_wrk.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,7 +15,7 @@ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN #define BOOST_INTERPROCESS_WIN32_LEAN_AND_MEAN #endif //#ifndef WIN32_LEAN_AND_MEAN #endif //#ifdef _WIN32 diff --git a/utils/boost_idb/boost/interprocess/detail/preprocessor.hpp b/utils/boost_idb/boost/interprocess/detail/preprocessor.hpp index 0eb419d6..22f9f775 100644 --- a/utils/boost_idb/boost/interprocess/detail/preprocessor.hpp +++ b/utils/boost_idb/boost/interprocess/detail/preprocessor.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,13 +15,13 @@ # pragma once #endif -#include +#include "config_begin.hpp" #ifdef BOOST_INTERPROCESS_PERFECT_FORWARDING #error "This file is not needed when perfect forwarding is available" #endif -#include +#include #include #include #include @@ -35,7 +35,7 @@ //This cast is ugly but it is necessary until "perfect forwarding" //is achieved in C++0x. Meanwhile, if we want to be able to //bind rvalues with non-const references, we have to be ugly -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES +#ifndef BOOST_NO_RVALUE_REFERENCES #define BOOST_INTERPROCESS_PP_PARAM_LIST(z, n, data) \ BOOST_PP_CAT(P, n) && BOOST_PP_CAT(p, n) \ //! @@ -45,154 +45,88 @@ //! #endif -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - #define BOOST_INTERPROCESS_PP_PARAM(U, u) \ +#ifndef BOOST_NO_RVALUE_REFERENCES + #define BOOST_INTERPROCESS_PARAM(U, u) \ U && u \ //! #else - #define BOOST_INTERPROCESS_PP_PARAM(U, u) \ + #define BOOST_INTERPROCESS_PARAM(U, u) \ const U & u \ //! #endif -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES +#ifndef BOOST_NO_RVALUE_REFERENCES - #define BOOST_INTERPROCESS_PP_PARAM_INIT(z, n, data) \ - BOOST_PP_CAT(m_p, n) (::boost::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) )) \ - //! +#ifdef BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES -#else //#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES +#define BOOST_INTERPROCESS_AUX_PARAM_INIT(z, n, data) \ + BOOST_PP_CAT(m_p, n) (BOOST_INTERPROCESS_MOVE_NAMESPACE::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) )) \ +//! - #define BOOST_INTERPROCESS_PP_PARAM_INIT(z, n, data) \ - BOOST_PP_CAT(m_p, n) (const_cast(BOOST_PP_CAT(p, n))) \ - //! +#else + +#define BOOST_INTERPROCESS_AUX_PARAM_INIT(z, n, data) \ + BOOST_PP_CAT(m_p, n) (BOOST_PP_CAT(p, n)) \ +//! + +#endif + +#else +#define BOOST_INTERPROCESS_AUX_PARAM_INIT(z, n, data) \ + BOOST_PP_CAT(m_p, n) (const_cast(BOOST_PP_CAT(p, n))) \ +//! #endif -#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES - - #if defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - - namespace boost { - namespace interprocess { - namespace ipcdetail { - template - struct ref_holder; - - template - struct ref_holder - { - ref_holder(T &t) - : t_(t) - {} - T &t_; - T & get() { return t_; } - T & get_lvalue() { return t_; } - }; - - template - struct ref_holder - { - ref_holder(const T &t) - : t_(t) - {} - const T &t_; - const T & get() { return t_; } - const T & get_lvalue() { return t_; } - }; - - template - struct ref_holder - { - ref_holder(const T &t) - : t_(t) - {} - const T &t_; - const T & get() { return t_; } - const T & get_lvalue() { return t_; } - }; - - template - struct ref_holder - { - ref_holder(T &&t) - : t_(t) - {} - T &t_; - T && get() { return ::boost::move(t_); } - T & get_lvalue() { return t_; } - }; - - template - struct ref_holder - { - ref_holder(T &&t) - : t(t) - {} - T &t; - T && get() { return ::boost::move(t_); } - T & get_lvalue() { return t_; } - }; - - } //namespace ipcdetail { - } //namespace interprocess { - } //namespace boost { - - #define BOOST_INTERPROCESS_PP_PARAM_DEFINE(z, n, data) \ - ::boost::interprocess::ipcdetail::ref_holder BOOST_PP_CAT(m_p, n); \ - //! - - #define BOOST_INTERPROCESS_PP_PARAM_INC(z, n, data) \ - BOOST_PP_CAT(++m_p, n).get_lvalue() \ - //! - - #else //BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG - - #define BOOST_INTERPROCESS_PP_PARAM_DEFINE(z, n, data)\ - BOOST_PP_CAT(P, n) && BOOST_PP_CAT(m_p, n); \ - //! - - #define BOOST_INTERPROCESS_PP_PARAM_INC(z, n, data) \ - BOOST_PP_CAT(++m_p, n) \ - //! - - #endif //defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) +#define BOOST_INTERPROCESS_AUX_PARAM_INC(z, n, data) \ + BOOST_PP_CAT(++m_p, n) \ +//! + +#ifndef BOOST_NO_RVALUE_REFERENCES + +#if defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) + +#define BOOST_INTERPROCESS_AUX_PARAM_DEFINE(z, n, data) \ + BOOST_PP_CAT(P, n) & BOOST_PP_CAT(m_p, n); \ +//! #else - #define BOOST_INTERPROCESS_PP_PARAM_DEFINE(z, n, data) \ - BOOST_PP_CAT(P, n) & BOOST_PP_CAT(m_p, n); \ - //! - #define BOOST_INTERPROCESS_PP_PARAM_INC(z, n, data) \ - BOOST_PP_CAT(++m_p, n) \ - //! +#define BOOST_INTERPROCESS_AUX_PARAM_DEFINE(z, n, data) \ + BOOST_PP_CAT(P, n) && BOOST_PP_CAT(m_p, n); \ +//! + +#endif //defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) + +#else +#define BOOST_INTERPROCESS_AUX_PARAM_DEFINE(z, n, data) \ + BOOST_PP_CAT(P, n) & BOOST_PP_CAT(m_p, n); \ +//! #endif #define BOOST_INTERPROCESS_PP_PARAM_FORWARD(z, n, data) \ -::boost::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) ) \ +::boost::interprocess::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(p, n) ) \ //! -#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) +#if !defined(BOOST_NO_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) - #define BOOST_INTERPROCESS_PP_MEMBER_FORWARD(z, n, data) BOOST_PP_CAT(this->m_p, n).get() \ - //! +#include - #define BOOST_INTERPROCESS_PP_MEMBER_IT_FORWARD(z, n, data) \ - BOOST_PP_CAT(*m_p, n).get_lvalue() \ - //! +#define BOOST_INTERPROCESS_PP_MEMBER_FORWARD(z, n, data) \ +::boost::container::containers_detail::stored_ref< BOOST_PP_CAT(P, n) >::forward( BOOST_PP_CAT(m_p, n) ) \ +//! #else - #define BOOST_INTERPROCESS_PP_MEMBER_FORWARD(z, n, data) \ - ::boost::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(m_p, n) ) \ - //! - - #define BOOST_INTERPROCESS_PP_MEMBER_IT_FORWARD(z, n, data) \ - BOOST_PP_CAT(*m_p, n) \ - //! +#define BOOST_INTERPROCESS_PP_MEMBER_FORWARD(z, n, data) \ +::boost::interprocess::forward< BOOST_PP_CAT(P, n) >( BOOST_PP_CAT(m_p, n) ) \ +//! +#endif //!defined(BOOST_NO_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) -#endif //!defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && defined(BOOST_MOVE_MSVC_10_MEMBER_RVALUE_REF_BUG) +#define BOOST_INTERPROCESS_PP_MEMBER_IT_FORWARD(z, n, data) \ +BOOST_PP_CAT(*m_p, n) \ +//! #include diff --git a/utils/boost_idb/boost/interprocess/detail/ptime_wrk.hpp b/utils/boost_idb/boost/interprocess/detail/ptime_wrk.hpp index 63d9915b..4a4709e3 100644 --- a/utils/boost_idb/boost/interprocess/detail/ptime_wrk.hpp +++ b/utils/boost_idb/boost/interprocess/detail/ptime_wrk.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,7 +15,7 @@ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN #define BOOST_INTERPROCESS_WIN32_LEAN_AND_MEAN #endif //#ifndef WIN32_LEAN_AND_MEAN #endif //#ifdef _WIN32 diff --git a/utils/boost_idb/boost/interprocess/detail/robust_emulation.hpp b/utils/boost_idb/boost/interprocess/detail/robust_emulation.hpp index e0866dc3..999a6cd8 100644 --- a/utils/boost_idb/boost/interprocess/detail/robust_emulation.hpp +++ b/utils/boost_idb/boost/interprocess/detail/robust_emulation.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2010-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2010-2010. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -24,12 +24,11 @@ #include #include #include -#include #include namespace boost{ namespace interprocess{ -namespace ipcdetail{ +namespace detail{ namespace robust_emulation_helpers { @@ -69,7 +68,7 @@ inline void robust_lock_path(std::string &s) inline void create_and_get_robust_lock_file_path(std::string &s, OS_process_id_t pid) { - intermodule_singleton_helpers::create_tmp_subdir_and_get_pid_based_filepath + file_locking_helpers::create_tmp_subdir_and_get_pid_based_filepath (robust_lock_subdir_path(), robust_lock_prefix(), pid, s); } @@ -133,7 +132,7 @@ class robust_mutex_lock_file throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: create_file filed with unexpected error"); } } - } + } ~robust_mutex_lock_file() { @@ -155,7 +154,7 @@ class robust_mutex_lock_file { std::string pid_str; //If the lock file is not our own lock file, then try to do the cleanup - if(!intermodule_singleton_helpers::check_if_filename_complies_with_pid + if(!file_locking_helpers::check_if_filename_complies_with_pid (filename, robust_lock_prefix(), get_current_process_id(), pid_str)){ remove_if_can_lock_file(filepath); } @@ -174,9 +173,9 @@ class robust_mutex_lock_file //This is the mutex class. Mutex should follow mutex concept //with an additonal "take_ownership()" function to take ownership of the -//mutex when robust_spin_mutex determines the previous owner was dead. +//mutex when robust_emulation_mutex determines the previous owner was dead. template -class robust_spin_mutex +class robust_emulation_mutex { public: static const boost::uint32_t correct_state = 0; @@ -185,7 +184,7 @@ class robust_spin_mutex typedef robust_emulation_helpers::mutex_traits mutex_traits_t; - robust_spin_mutex(); + robust_emulation_mutex(); void lock(); bool try_lock(); bool timed_lock(const boost::posix_time::ptime &abs_time); @@ -198,8 +197,8 @@ class robust_spin_mutex bool lock_own_unique_file(); bool robust_check(); bool check_if_owner_dead_and_take_ownership_atomically(); - bool is_owner_dead(boost::uint32_t own); - void owner_to_filename(boost::uint32_t own, std::string &s); + bool is_owner_dead(boost::uint32_t owner); + void owner_to_filename(boost::uint32_t owner, std::string &s); //The real mutex Mutex mtx; //The pid of the owner @@ -209,12 +208,12 @@ class robust_spin_mutex }; template -inline robust_spin_mutex::robust_spin_mutex() +inline robust_emulation_mutex::robust_emulation_mutex() : mtx(), owner(get_invalid_process_id()), state(correct_state) {} template -inline void robust_spin_mutex::lock() +inline void robust_emulation_mutex::lock() { //If the mutex is broken (recovery didn't call consistent()), //then throw an exception @@ -229,7 +228,7 @@ inline void robust_spin_mutex::lock() //Now the logic. Try to lock, if successful mark the owner //if it fails, start recovery logic - spin_wait swait; + unsigned int spin_count = 0; while(1){ if (mtx.try_lock()){ atomic_write32(&this->owner, get_current_process_id()); @@ -237,10 +236,14 @@ inline void robust_spin_mutex::lock() } else{ //Do the dead owner checking each spin_threshold lock tries - swait.yield(); - if(0 == (swait.count() & 255u)){ + detail::thread_yield(); + ++spin_count; + if(spin_count > spin_threshold){ //Check if owner dead and take ownership if possible - if(this->robust_check()){ + if(!this->robust_check()){ + spin_count = 0; + } + else{ break; } } @@ -249,7 +252,7 @@ inline void robust_spin_mutex::lock() } template -inline bool robust_spin_mutex::try_lock() +inline bool robust_emulation_mutex::try_lock() { //Same as lock() but without spinning if(atomic_read32(&this->state) == broken_state){ @@ -275,7 +278,7 @@ inline bool robust_spin_mutex::try_lock() } template -inline bool robust_spin_mutex::timed_lock +inline bool robust_emulation_mutex::timed_lock (const boost::posix_time::ptime &abs_time) { //Same as lock() but with an additional timeout @@ -289,7 +292,6 @@ inline bool robust_spin_mutex::timed_lock if(now >= abs_time) return this->try_lock(); - spin_wait swait; do{ if(this->try_lock()){ break; @@ -300,20 +302,20 @@ inline bool robust_spin_mutex::timed_lock return this->try_lock(); } // relinquish current time slice - swait.yield(); + detail::thread_yield(); }while (true); return true; } template -inline void robust_spin_mutex::owner_to_filename(boost::uint32_t own, std::string &s) +inline void robust_emulation_mutex::owner_to_filename(boost::uint32_t owner, std::string &s) { - robust_emulation_helpers::create_and_get_robust_lock_file_path(s, own); + robust_emulation_helpers::create_and_get_robust_lock_file_path(s, owner); } template -inline bool robust_spin_mutex::robust_check() +inline bool robust_emulation_mutex::robust_check() { //If the old owner was dead, and we've acquired ownership, mark //the mutex as 'fixing'. This means that a "consistent()" is needed @@ -322,11 +324,11 @@ inline bool robust_spin_mutex::robust_check() return false; } atomic_write32(&this->state, fixing_state); - return true; + return true; } template -inline bool robust_spin_mutex::check_if_owner_dead_and_take_ownership_atomically() +inline bool robust_emulation_mutex::check_if_owner_dead_and_take_ownership_atomically() { boost::uint32_t cur_owner = get_current_process_id(); boost::uint32_t old_owner = atomic_read32(&this->owner), old_owner2; @@ -347,16 +349,16 @@ inline bool robust_spin_mutex::check_if_owner_dead_and_take_ownership_ato } template -inline bool robust_spin_mutex::is_owner_dead(boost::uint32_t own) +inline bool robust_emulation_mutex::is_owner_dead(boost::uint32_t owner) { //If owner is an invalid id, then it's clear it's dead - if(own == (boost::uint32_t)get_invalid_process_id()){ + if(owner == (boost::uint32_t)get_invalid_process_id()){ return true; } //Obtain the lock filename of the owner field std::string file; - this->owner_to_filename(own, file); + this->owner_to_filename(owner, file); //Now the logic is to open and lock it file_handle_t fhnd = open_existing_file(file.c_str(), read_write); @@ -385,7 +387,7 @@ inline bool robust_spin_mutex::is_owner_dead(boost::uint32_t own) } template -inline void robust_spin_mutex::consistent() +inline void robust_emulation_mutex::consistent() { //This function supposes the previous state was "fixing" //and the current process holds the mutex @@ -398,14 +400,14 @@ inline void robust_spin_mutex::consistent() } template -inline bool robust_spin_mutex::previous_owner_dead() +inline bool robust_emulation_mutex::previous_owner_dead() { //Notifies if a owner recovery has been performed in the last lock() return atomic_read32(&this->state) == fixing_state; }; template -inline void robust_spin_mutex::unlock() +inline void robust_emulation_mutex::unlock() { //If in "fixing" state, unlock and mark the mutex as unrecoverable //so next locks will fail and all threads will be notified that the @@ -419,16 +421,16 @@ inline void robust_spin_mutex::unlock() } template -inline bool robust_spin_mutex::lock_own_unique_file() +inline bool robust_emulation_mutex::lock_own_unique_file() { //This function forces instantiation of the singleton - robust_emulation_helpers::robust_mutex_lock_file* dummy = - &ipcdetail::intermodule_singleton + robust_emulation_helpers::robust_mutex_lock_file* dummy = + &detail::intermodule_singleton ::get(); return dummy != 0; } -} //namespace ipcdetail{ +} //namespace detail{ } //namespace interprocess{ } //namespace boost{ diff --git a/utils/boost_idb/boost/interprocess/detail/segment_manager_helper.hpp b/utils/boost_idb/boost/interprocess/detail/segment_manager_helper.hpp index 83e5a05e..f14c5def 100644 --- a/utils/boost_idb/boost/interprocess/detail/segment_manager_helper.hpp +++ b/utils/boost_idb/boost/interprocess/detail/segment_manager_helper.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,16 +18,13 @@ #include #include -#include +#include #include #include #include #include #include -#include -#include -#include #include //std::size_t #include //char_traits #include //std::nothrow @@ -52,7 +49,7 @@ class segment_manager_base; //!instance constructed in memory enum instance_type { anonymous_type, named_type, unique_type, max_allocation_type }; -namespace ipcdetail{ +namespace detail{ template class mem_algo_deallocator @@ -73,94 +70,96 @@ class mem_algo_deallocator }; /// @cond -template struct block_header { - size_type m_value_bytes; + std::size_t m_value_bytes; unsigned short m_num_char; unsigned char m_value_alignment; unsigned char m_alloc_type_sizeof_char; - block_header(size_type val_bytes - ,size_type val_alignment - ,unsigned char al_type - ,std::size_t szof_char + block_header(std::size_t value_bytes + ,std::size_t value_alignment + ,std::size_t alloc_type + ,std::size_t sizeof_char ,std::size_t num_char ) - : m_value_bytes(val_bytes) - , m_num_char((unsigned short)num_char) - , m_value_alignment((unsigned char)val_alignment) - , m_alloc_type_sizeof_char( (al_type << 5u) | ((unsigned char)szof_char & 0x1F) ) + : m_value_bytes(value_bytes) + , m_num_char(num_char) + , m_value_alignment(value_alignment) + , m_alloc_type_sizeof_char + ( ((unsigned char)alloc_type << 5u) | + ((unsigned char)sizeof_char & 0x1F) ) {}; + template block_header &operator= (const T& ) { return *this; } - size_type total_size() const + std::size_t total_size() const { if(alloc_type() != anonymous_type){ return name_offset() + (m_num_char+1)*sizeof_char(); } else{ - return this->value_offset() + m_value_bytes; + return value_offset() + m_value_bytes; } } - size_type value_bytes() const + std::size_t value_bytes() const { return m_value_bytes; } template - size_type total_size_with_header() const + std::size_t total_size_with_header() const { return get_rounded_size - ( size_type(sizeof(Header)) - , size_type(::boost::alignment_of >::value)) + ( sizeof(Header) + , detail::alignment_of::value) + total_size(); } - unsigned char alloc_type() const + std::size_t alloc_type() const { return (m_alloc_type_sizeof_char >> 5u)&(unsigned char)0x7; } - unsigned char sizeof_char() const + std::size_t sizeof_char() const { return m_alloc_type_sizeof_char & (unsigned char)0x1F; } template CharType *name() const - { + { return const_cast(reinterpret_cast (reinterpret_cast(this) + name_offset())); } - unsigned short name_length() const + std::size_t name_length() const { return m_num_char; } - size_type name_offset() const - { - return this->value_offset() + get_rounded_size(size_type(m_value_bytes), size_type(sizeof_char())); + std::size_t name_offset() const + { + return value_offset() + get_rounded_size(m_value_bytes, sizeof_char()); } void *value() const { - return const_cast((reinterpret_cast(this) + this->value_offset())); + return const_cast((reinterpret_cast(this) + value_offset())); } - size_type value_offset() const + std::size_t value_offset() const { - return get_rounded_size(size_type(sizeof(block_header)), size_type(m_value_alignment)); + return get_rounded_size(sizeof(block_header), m_value_alignment); } template - bool less_comp(const block_header &b) const + bool less_comp(const block_header &b) const { return m_num_char < b.m_num_char || - (m_num_char < b.m_num_char && + (m_num_char < b.m_num_char && std::char_traits::compare (name(), b.name(), m_num_char) < 0); } template - bool equal_comp(const block_header &b) const + bool equal_comp(const block_header &b) const { return m_num_char == b.m_num_char && std::char_traits::compare @@ -168,14 +167,14 @@ struct block_header } template - static block_header *block_header_from_value(T *value) - { return block_header_from_value(value, sizeof(T), ::boost::alignment_of::value); } + static block_header *block_header_from_value(T *value) + { return block_header_from_value(value, sizeof(T), detail::alignment_of::value); } - static block_header *block_header_from_value(const void *value, std::size_t sz, std::size_t algn) - { - block_header * hdr = + static block_header *block_header_from_value(const void *value, std::size_t sz, std::size_t algn) + { + block_header * hdr = const_cast - (reinterpret_cast(reinterpret_cast(value) - + (reinterpret_cast(reinterpret_cast(value) - get_rounded_size(sizeof(block_header), algn))); (void)sz; //Some sanity checks @@ -185,27 +184,27 @@ struct block_header } template - static block_header *from_first_header(Header *header) - { - block_header * hdr = - reinterpret_cast*>(reinterpret_cast(header) + - get_rounded_size(size_type(sizeof(Header)), size_type(::boost::alignment_of >::value))); + static block_header *from_first_header(Header *header) + { + block_header * hdr = + reinterpret_cast(reinterpret_cast(header) + + get_rounded_size(sizeof(Header), detail::alignment_of::value)); //Some sanity checks return hdr; } template - static Header *to_first_header(block_header *bheader) - { - Header * hdr = - reinterpret_cast(reinterpret_cast(bheader) - - get_rounded_size(size_type(sizeof(Header)), size_type(::boost::alignment_of >::value))); + static Header *to_first_header(block_header *bheader) + { + Header * hdr = + reinterpret_cast(reinterpret_cast(bheader) - + get_rounded_size(sizeof(Header), detail::alignment_of::value)); //Some sanity checks return hdr; } }; -inline void array_construct(void *mem, std::size_t num, in_place_interface &table) +inline void array_construct(void *mem, std::size_t num, detail::in_place_interface &table) { //Try constructors std::size_t constructed = 0; @@ -258,7 +257,7 @@ typedef instance_t anonymous_instance_t; typedef instance_t unique_instance_t; -template +template struct intrusive_value_type_impl : public Hook { @@ -269,35 +268,34 @@ struct intrusive_value_type_impl public: typedef CharType char_type; - typedef SizeType size_type; intrusive_value_type_impl(){} - enum { BlockHdrAlignment = ::boost::alignment_of >::value }; + enum { BlockHdrAlignment = detail::alignment_of::value }; - block_header *get_block_header() const + block_header *get_block_header() const { - return const_cast*> - (reinterpret_cast *>(reinterpret_cast(this) + - get_rounded_size(size_type(sizeof(*this)), size_type(BlockHdrAlignment)))); + return const_cast + (reinterpret_cast(reinterpret_cast(this) + + get_rounded_size(sizeof(*this), BlockHdrAlignment))); } - bool operator <(const intrusive_value_type_impl & other) const + bool operator <(const intrusive_value_type_impl & other) const { return (this->get_block_header())->template less_comp(*other.get_block_header()); } - bool operator ==(const intrusive_value_type_impl & other) const + bool operator ==(const intrusive_value_type_impl & other) const { return (this->get_block_header())->template equal_comp(*other.get_block_header()); } - static intrusive_value_type_impl *get_intrusive_value_type(block_header *hdr) + static intrusive_value_type_impl *get_intrusive_value_type(block_header *hdr) { return reinterpret_cast(reinterpret_cast(hdr) - - get_rounded_size(size_type(sizeof(intrusive_value_type_impl)), size_type(BlockHdrAlignment))); + get_rounded_size(sizeof(intrusive_value_type_impl), BlockHdrAlignment)); } CharType *name() const { return get_block_header()->template name(); } - unsigned short name_length() const + std::size_t name_length() const { return get_block_header()->name_length(); } void *value() const @@ -308,15 +306,15 @@ template class char_ptr_holder { public: - char_ptr_holder(const CharType *name) + char_ptr_holder(const CharType *name) : m_name(name) {} - char_ptr_holder(const anonymous_instance_t *) + char_ptr_holder(const detail::anonymous_instance_t *) : m_name(static_cast(0)) {} - char_ptr_holder(const unique_instance_t *) + char_ptr_holder(const detail::unique_instance_t *) : m_name(reinterpret_cast(-1)) {} @@ -327,59 +325,55 @@ class char_ptr_holder const CharType *m_name; }; -//!The key of the the named allocation information index. Stores an offset pointer +//!The key of the the named allocation information index. Stores an offset pointer //!to a null terminated string and the length of the string to speed up sorting template struct index_key { - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_char_ptr_t; + typedef typename boost:: + pointer_to_other::type const_char_ptr_t; typedef CharT char_type; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; private: //Offset pointer to the object's name const_char_ptr_t mp_str; //Length of the name buffer (null NOT included) - size_type m_len; + std::size_t m_len; public: //!Constructor of the key - index_key (const char_type *nm, size_type length) - : mp_str(nm), m_len(length) - {} + index_key (const char_type *name, std::size_t length) + : mp_str(name), m_len(length) {} //!Less than function for index ordering bool operator < (const index_key & right) const { - return (m_len < right.m_len) || - (m_len == right.m_len && - std::char_traits::compare - (to_raw_pointer(mp_str) - ,to_raw_pointer(right.mp_str), m_len) < 0); + return (m_len < right.m_len) || + (m_len == right.m_len && + std::char_traits::compare + (detail::get_pointer(mp_str) + ,detail::get_pointer(right.mp_str), m_len) < 0); } //!Equal to function for index ordering bool operator == (const index_key & right) const { - return m_len == right.m_len && - std::char_traits::compare - (to_raw_pointer(mp_str), - to_raw_pointer(right.mp_str), m_len) == 0; + return m_len == right.m_len && + std::char_traits::compare + (detail::get_pointer(mp_str), + detail::get_pointer(right.mp_str), m_len) == 0; } - void name(const CharT *nm) - { mp_str = nm; } + void name(const CharT *name) + { mp_str = name; } - void name_length(size_type len) + void name_length(std::size_t len) { m_len = len; } const CharT *name() const - { return to_raw_pointer(mp_str); } + { return detail::get_pointer(mp_str); } - size_type name_length() const + std::size_t name_length() const { return m_len; } }; @@ -393,7 +387,7 @@ struct index_data index_data(void *ptr) : m_ptr(ptr){} void *value() const - { return static_cast(to_raw_pointer(m_ptr)); } + { return static_cast(detail::get_pointer(m_ptr)); } }; template @@ -405,14 +399,14 @@ struct index_config { typedef typename MemoryAlgorithm::void_pointer void_pointer; typedef CharT char_type; - typedef index_key key_type; - typedef index_data mapped_type; + typedef detail::index_key key_type; + typedef detail::index_data mapped_type; typedef typename segment_manager_base_type ::type segment_manager_base; template struct intrusive_value_type - { typedef intrusive_value_type_impl type; }; + { typedef detail::intrusive_value_type_impl type; }; typedef intrusive_compare_key intrusive_compare_key_type; }; @@ -431,7 +425,7 @@ class segment_manager_iterator_value_adaptor const char_type *name() const { return m_val->name(); } - unsigned short name_length() const + std::size_t name_length() const { return m_val->name_length(); } const void *value() const @@ -448,7 +442,6 @@ class segment_manager_iterator_value_adaptor typedef typename iterator_val_t::first_type first_type; typedef typename iterator_val_t::second_type second_type; typedef typename first_type::char_type char_type; - typedef typename first_type::size_type size_type; public: segment_manager_iterator_value_adaptor(const typename Iterator::value_type &val) @@ -458,13 +451,13 @@ class segment_manager_iterator_value_adaptor const char_type *name() const { return m_val->first.name(); } - size_type name_length() const + std::size_t name_length() const { return m_val->first.name_length(); } const void *value() const { - return reinterpret_cast*> - (to_raw_pointer(m_val->second.m_ptr))->value(); + return reinterpret_cast + (detail::get_pointer(m_val->second.m_ptr))->value(); } const typename Iterator::value_type *m_val; @@ -476,19 +469,19 @@ struct segment_manager_iterator_transform , segment_manager_iterator_value_adaptor > { typedef segment_manager_iterator_value_adaptor result_type; - + result_type operator()(const typename Iterator::value_type &arg) const { return result_type(arg); } }; -} //namespace ipcdetail { +} //namespace detail { -//These pointers are the ones the user will use to +//These pointers are the ones the user will use to //indicate previous allocation types -static const ipcdetail::anonymous_instance_t * anonymous_instance = 0; -static const ipcdetail::unique_instance_t * unique_instance = 0; +static const detail::anonymous_instance_t * anonymous_instance = 0; +static const detail::unique_instance_t * unique_instance = 0; -namespace ipcdetail_really_deep_namespace { +namespace detail_really_deep_namespace { //Otherwise, gcc issues a warning of previously defined //anonymous_instance and unique_instance diff --git a/utils/boost_idb/boost/interprocess/detail/tmp_dir_helpers.hpp b/utils/boost_idb/boost/interprocess/detail/tmp_dir_helpers.hpp index 2af1a8a7..5a2bef2f 100644 --- a/utils/boost_idb/boost/interprocess/detail/tmp_dir_helpers.hpp +++ b/utils/boost_idb/boost/interprocess/detail/tmp_dir_helpers.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2007-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2007-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,87 +18,79 @@ #include #include -#if defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) && defined(BOOST_INTERPROCESS_WINDOWS) - #include +#if defined(BOOST_INTERPROCESS_WINDOWS) + #define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME + #define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME + #include +#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) + #include + #if defined(CTL_KERN) && defined (KERN_BOOTTIME) + #define BOOST_INTERPROCESS_HAS_BSD_KERNEL_BOOTTIME + #define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME + #endif #endif namespace boost { namespace interprocess { -namespace ipcdetail { - -#if defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) - #if defined(BOOST_INTERPROCESS_WINDOWS) - //This type will initialize the stamp - struct windows_bootstamp - { - windows_bootstamp() - { - winapi::get_last_bootup_time(stamp); - } - //Use std::string. Even if this will be constructed in shared memory, all - //modules/dlls are from this process so internal raw pointers to heap are always valid - std::string stamp; - }; - - inline void get_bootstamp(std::string &s, bool add = false) - { - const windows_bootstamp &bootstamp = windows_intermodule_singleton::get(); - if(add){ - s += bootstamp.stamp; - } - else{ - s = bootstamp.stamp; - } - } - #elif defined(BOOST_INTERPROCESS_HAS_BSD_KERNEL_BOOTTIME) - inline void get_bootstamp(std::string &s, bool add = false) - { - // FreeBSD specific: sysctl "kern.boottime" - int request[2] = { CTL_KERN, KERN_BOOTTIME }; - struct ::timeval result; - std::size_t result_len = sizeof result; - - if (::sysctl (request, 2, &result, &result_len, 0, 0) < 0) - return; - - char bootstamp_str[256]; - - const char Characters [] = - { '0', '1', '2', '3', '4', '5', '6', '7' - , '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - - std::size_t char_counter = 0; - //32 bit values to allow 32 and 64 bit process IPC - boost::uint32_t fields[2] = { boost::uint32_t(result.tv_sec), boost::uint32_t(result.tv_usec) }; - for(std::size_t field = 0; field != 2; ++field){ - for(std::size_t i = 0; i != sizeof(fields[0]); ++i){ - const char *ptr = (const char *)&fields[field]; - bootstamp_str[char_counter++] = Characters[(ptr[i]&0xF0)>>4]; - bootstamp_str[char_counter++] = Characters[(ptr[i]&0x0F)]; - } - } - bootstamp_str[char_counter] = 0; - if(add){ - s += bootstamp_str; - } - else{ - s = bootstamp_str; - } +namespace detail { + +#if defined (BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) +inline void get_bootstamp(std::string &s, bool add = false) +{ + std::string bootstamp; + winapi::get_last_bootup_time(bootstamp); + if(add){ + s += bootstamp; + } + else{ + s = bootstamp; + } +} +#elif defined(BOOST_INTERPROCESS_HAS_BSD_KERNEL_BOOTTIME) +inline void get_bootstamp(std::string &s, bool add = false) +{ + // FreeBSD specific: sysctl "kern.boottime" + int request[2] = { CTL_KERN, KERN_BOOTTIME }; + struct ::timeval result; + size_t result_len = sizeof result; + + if (::sysctl (request, 2, &result, &result_len, NULL, 0) < 0) + return; + + char bootstamp_str[256]; + + const char Characters [] = + { '0', '1', '2', '3', '4', '5', '6', '7' + , '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + + std::size_t char_counter = 0; + long fields[2] = { result.tv_sec, result.tv_usec }; + for(std::size_t field = 0; field != 2; ++field){ + for(std::size_t i = 0; i != sizeof(long); ++i){ + const char *ptr = (const char *)&fields[field]; + bootstamp_str[char_counter++] = Characters[(ptr[i]&0xF0)>>4]; + bootstamp_str[char_counter++] = Characters[(ptr[i]&0x0F)]; } - #else - #error "BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME defined with no known implementation" - #endif -#endif //#if defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) + } + bootstamp_str[char_counter] = 0; + if(add){ + s += bootstamp_str; + } + else{ + s = bootstamp_str; + } +} +#endif inline void get_tmp_base_dir(std::string &tmp_name) { #if defined (BOOST_INTERPROCESS_WINDOWS) - winapi::get_shared_documents_folder(tmp_name); - if(tmp_name.empty() || !winapi::is_directory(tmp_name.c_str())){ - tmp_name = get_temporary_path(); - } - #else + winapi::get_shared_documents_folder(tmp_name); + if(tmp_name.empty()){ tmp_name = get_temporary_path(); + } + #else + tmp_name = get_temporary_path(); #endif if(tmp_name.empty()){ error_info err = system_error_code(); @@ -111,9 +103,9 @@ inline void get_tmp_base_dir(std::string &tmp_name) inline void tmp_folder(std::string &tmp_name) { get_tmp_base_dir(tmp_name); - #if defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) - tmp_name += "/"; - get_bootstamp(tmp_name, true); + #ifdef BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME + tmp_name += "/"; + get_bootstamp(tmp_name, true); #endif } @@ -138,30 +130,29 @@ inline void create_tmp_and_clean_old(std::string &tmp_name) } } - #if defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) - tmp_folder(tmp_name); + #ifdef BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME + tmp_folder(tmp_name); - //If fails, check that it's because already exists - if(!create_directory(tmp_name.c_str())){ - error_info info(system_error_code()); - if(info.get_error_code() != already_exists_error){ - throw interprocess_exception(info); - } + //If fails, check that it's because already exists + if(!create_directory(tmp_name.c_str())){ + error_info info(system_error_code()); + if(info.get_error_code() != already_exists_error){ + throw interprocess_exception(info); } - //Now erase all old directories created in the previous boot sessions - std::string subdir = tmp_name; - subdir.erase(0, root_tmp_name.size()+1); - delete_subdirectories(root_tmp_name, subdir.c_str()); + } + //Now erase all old directories created in the previous boot sessions + std::string subdir = tmp_name; + subdir.erase(0, root_tmp_name.size()+1); + delete_subdirectories(root_tmp_name, subdir.c_str()); #else - tmp_name = root_tmp_name; + tmp_name = root_tmp_name; #endif } inline void create_tmp_and_clean_old_and_get_filename(const char *filename, std::string &tmp_name) { create_tmp_and_clean_old(tmp_name); - tmp_name += "/"; - tmp_name += filename; + tmp_filename(filename, tmp_name); } inline void add_leading_slash(const char *name, std::string &new_name) @@ -174,7 +165,7 @@ inline void add_leading_slash(const char *name, std::string &new_name) } //namespace boost{ } //namespace interprocess { -} //namespace ipcdetail { +} //namespace detail { #include diff --git a/utils/boost_idb/boost/interprocess/detail/transform_iterator.hpp b/utils/boost_idb/boost/interprocess/detail/transform_iterator.hpp index 56bd0e56..55787427 100644 --- a/utils/boost_idb/boost/interprocess/detail/transform_iterator.hpp +++ b/utils/boost_idb/boost/interprocess/detail/transform_iterator.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2009. // (C) Copyright Gennaro Prota 2003 - 2004. // // Distributed under the Boost Software License, Version 1.0. @@ -27,7 +27,7 @@ #include namespace boost { -namespace interprocess { +namespace interprocess { template struct operator_arrow_proxy @@ -62,7 +62,7 @@ class transform_iterator : public UnaryFunction , public std::iterator < typename Iterator::iterator_category - , typename ipcdetail::remove_reference::type + , typename detail::remove_reference::type , typename Iterator::difference_type , operator_arrow_proxy , typename UnaryFunction::result_type> @@ -77,7 +77,7 @@ class transform_iterator {} //Constructors - transform_iterator& operator++() + transform_iterator& operator++() { increment(); return *this; } transform_iterator operator++(int) @@ -87,7 +87,7 @@ class transform_iterator return result; } - transform_iterator& operator--() + transform_iterator& operator--() { decrement(); return *this; } transform_iterator operator--(int) @@ -186,7 +186,7 @@ make_transform_iterator(Iterator it, UnaryFunc fun) return transform_iterator(it, fun); } -} //namespace interprocess { +} //namespace interprocess { } //namespace boost { #include diff --git a/utils/boost_idb/boost/interprocess/detail/type_traits.hpp b/utils/boost_idb/boost/interprocess/detail/type_traits.hpp index ade623f1..9c4579d1 100644 --- a/utils/boost_idb/boost/interprocess/detail/type_traits.hpp +++ b/utils/boost_idb/boost/interprocess/detail/type_traits.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // (C) Copyright John Maddock 2000. -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2009. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -8,6 +8,8 @@ // // See http://www.boost.org/libs/interprocess for documentation. // +// The alignment_of implementation comes from John Maddock's boost::alignment_of code +// ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_DETAIL_TYPE_TRAITS_HPP @@ -20,11 +22,53 @@ #include namespace boost { -namespace interprocess { -namespace ipcdetail { +namespace interprocess { +namespace detail { struct nat{}; +//boost::alignment_of yields to 10K lines of preprocessed code, so we +//need an alternative +template struct alignment_of; + +template +struct alignment_of_hack +{ + char c; + T t; + alignment_of_hack(); +}; + +template +struct alignment_logic +{ + enum{ value = A < S ? A : S }; +}; + +template< typename T > +struct alignment_of +{ + enum{ value = alignment_logic + < sizeof(alignment_of_hack) - sizeof(T) + , sizeof(T)>::value }; +}; + +//This is not standard, but should work with all compilers +union max_align +{ + char char_; + short short_; + int int_; + long long_; + #ifdef BOOST_HAS_LONG_LONG + long long long_long_; + #endif + float float_; + double double_; + long double long_double_; + void * void_ptr_; +}; + template struct remove_reference { @@ -40,25 +84,25 @@ struct remove_reference template struct is_reference { - static const bool value = false; + enum { value = false }; }; template struct is_reference { - static const bool value = true; + enum { value = true }; }; template struct is_pointer { - static const bool value = false; + enum { value = false }; }; template struct is_pointer { - static const bool value = true; + enum { value = true }; }; template @@ -93,36 +137,6 @@ template struct add_const_reference { typedef T& type; }; -template -struct remove_const -{ - typedef T type; -}; - -template -struct remove_const -{ - typedef T type; -}; - -template -struct remove_volatile -{ - typedef T type; -}; - -template -struct remove_volatile -{ - typedef T type; -}; - -template -struct remove_const_volatile -{ - typedef typename remove_const::type>::type type; -}; - template struct is_same { @@ -142,17 +156,11 @@ struct is_same static const bool value = sizeof(yes_type) == sizeof(is_same_tester(t,u)); }; -template -struct is_cv_same -{ - static const bool value = is_same< typename remove_const_volatile::type - , typename remove_const_volatile::type >::value; -}; - -} // namespace ipcdetail -} //namespace interprocess { +} // namespace detail +} //namespace interprocess { } //namespace boost { +#endif //#ifndef BOOST_INTERPROCESS_DETAIL_TYPE_TRAITS_HPP + #include -#endif //#ifndef BOOST_INTERPROCESS_DETAIL_TYPE_TRAITS_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/utilities.hpp b/utils/boost_idb/boost/interprocess/detail/utilities.hpp index 3b486ddc..2389effa 100644 --- a/utils/boost_idb/boost/interprocess/detail/utilities.hpp +++ b/utils/boost_idb/boost/interprocess/detail/utilities.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2009. // (C) Copyright Gennaro Prota 2003 - 2004. // // Distributed under the Boost Software License, Version 1.0. @@ -22,32 +22,44 @@ #include #include -#include +#include #include #include #include #include #include #include -#include -#include -#include +#include #include #include -#include namespace boost { -namespace interprocess { -namespace ipcdetail { +namespace interprocess { +namespace detail { -template -inline T* to_raw_pointer(T* p) -{ return p; } +template +struct smart_ptr_type +{ + typedef typename SmartPtr::value_type value_type; + typedef value_type *pointer; + static pointer get (const SmartPtr &smartptr) + { return smartptr.get();} +}; -template -inline typename boost::intrusive::pointer_traits::element_type* -to_raw_pointer(const Pointer &p) -{ return boost::interprocess::ipcdetail::to_raw_pointer(p.operator->()); } +template +struct smart_ptr_type +{ + typedef T value_type; + typedef value_type *pointer; + static pointer get (pointer ptr) + { return ptr;} +}; + +//!Overload for smart pointers to avoid ADL problems with get_pointer +template +inline typename smart_ptr_type::pointer +get_pointer(const Ptr &ptr) +{ return smart_ptr_type::get(ptr); } //!To avoid ADL problems with swap template @@ -58,29 +70,25 @@ inline void do_swap(T& x, T& y) } //Rounds "orig_size" by excess to round_to bytes -template -inline SizeType get_rounded_size(SizeType orig_size, SizeType round_to) +inline std::size_t get_rounded_size(std::size_t orig_size, std::size_t round_to) { return ((orig_size-1)/round_to+1)*round_to; } //Truncates "orig_size" to a multiple of "multiple" bytes. -template -inline SizeType get_truncated_size(SizeType orig_size, SizeType multiple) +inline std::size_t get_truncated_size(std::size_t orig_size, std::size_t multiple) { return orig_size/multiple*multiple; } //Rounds "orig_size" by excess to round_to bytes. round_to must be power of two -template -inline SizeType get_rounded_size_po2(SizeType orig_size, SizeType round_to) +inline std::size_t get_rounded_size_po2(std::size_t orig_size, std::size_t round_to) { return ((orig_size-1)&(~(round_to-1))) + round_to; } //Truncates "orig_size" to a multiple of "multiple" bytes. multiple must be power of two -template -inline SizeType get_truncated_size_po2(SizeType orig_size, SizeType multiple) +inline std::size_t get_truncated_size_po2(std::size_t orig_size, std::size_t multiple) { return (orig_size & (~(multiple-1))); } @@ -88,17 +96,14 @@ inline SizeType get_truncated_size_po2(SizeType orig_size, SizeType multiple) template struct ct_rounded_size { - BOOST_STATIC_ASSERT((RoundTo != 0)); - static const std::size_t intermediate_value = (OrigSize-1)/RoundTo+1; - BOOST_STATIC_ASSERT(intermediate_value <= std::size_t(-1)/RoundTo); - static const std::size_t value = intermediate_value*RoundTo; + enum { value = ((OrigSize-1)/RoundTo+1)*RoundTo }; }; // Gennaro Prota wrote this. Thanks! template struct ct_max_pow2_less { - static const std::size_t c = 2*n < p; + enum { c = 2*n < p }; static const std::size_t value = c ? (ct_max_pow2_less< c*p, 2*c*n>::value) : n; @@ -110,7 +115,7 @@ struct ct_max_pow2_less<0, 0> static const std::size_t value = 0; }; -} //namespace ipcdetail { +} //namespace detail { //!Trait class to detect if an index is a node //!index. This allows more efficient operations @@ -118,7 +123,7 @@ struct ct_max_pow2_less<0, 0> template struct is_node_index { - static const bool value = false; + enum { value = false }; }; //!Trait class to detect if an index is an intrusive @@ -128,7 +133,7 @@ struct is_node_index template struct is_intrusive_index { - static const bool value = false; + enum { value = false }; }; template T* @@ -138,67 +143,14 @@ addressof(T& v) &const_cast(reinterpret_cast(v))); } -template -struct sqrt_size_type_max -{ - static const SizeType value = (SizeType(1) << (sizeof(SizeType)*(CHAR_BIT/2)))-1; -}; - -template -inline bool multiplication_overflows(SizeType a, SizeType b) -{ - const SizeType sqrt_size_max = sqrt_size_type_max::value; - return //Fast runtime check - ( (a | b) > sqrt_size_max && - //Slow division check - b && a > SizeType(-1)/b - ); -} - -template -inline bool size_overflows(SizeType count) -{ - //Compile time-check - BOOST_STATIC_ASSERT(SztSizeOfType <= SizeType(-1)); - //Runtime check - return multiplication_overflows(SizeType(SztSizeOfType), count); -} - -template -class pointer_size_t_caster -{ - public: - explicit pointer_size_t_caster(std::size_t sz) - : m_ptr(reinterpret_cast(sz)) - {} - - explicit pointer_size_t_caster(RawPointer p) - : m_ptr(p) - {} - - std::size_t size() const - { return reinterpret_cast(m_ptr); } - - RawPointer pointer() const - { return m_ptr; } - - private: - RawPointer m_ptr; -}; - - -template -inline bool sum_overflows(SizeType a, SizeType b) -{ return SizeType(-1) - a < b; } - //Anti-exception node eraser template class value_eraser { public: - value_eraser(Cont & cont, typename Cont::iterator it) + value_eraser(Cont & cont, typename Cont::iterator it) : m_cont(cont), m_index_it(it), m_erase(true){} - ~value_eraser() + ~value_eraser() { if(m_erase) m_cont.erase(m_index_it); } void release() { m_erase = false; } @@ -209,7 +161,7 @@ class value_eraser bool m_erase; }; -} //namespace interprocess { +} //namespace interprocess { } //namespace boost { #include diff --git a/utils/boost_idb/boost/interprocess/detail/variadic_templates_tools.hpp b/utils/boost_idb/boost/interprocess/detail/variadic_templates_tools.hpp index 5f2a94a3..d2aa2faa 100644 --- a/utils/boost_idb/boost/interprocess/detail/variadic_templates_tools.hpp +++ b/utils/boost_idb/boost/interprocess/detail/variadic_templates_tools.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -21,8 +21,8 @@ #include //std::size_t namespace boost { -namespace interprocess { -namespace ipcdetail { +namespace interprocess { +namespace detail { template class tuple; @@ -136,7 +136,7 @@ struct index_tuple{}; template > struct build_number_seq; -template +template struct build_number_seq > : build_number_seq > {}; @@ -146,7 +146,7 @@ struct build_number_seq<0, index_tuple > { typedef index_tuple type; }; -}}} //namespace boost { namespace interprocess { namespace ipcdetail { +}}} //namespace boost { namespace interprocess { namespace detail { #include diff --git a/utils/boost_idb/boost/interprocess/detail/win32_api.hpp b/utils/boost_idb/boost/interprocess/detail/win32_api.hpp index 67b5c13e..cdcb00ef 100644 --- a/utils/boost_idb/boost/interprocess/detail/win32_api.hpp +++ b/utils/boost_idb/boost/interprocess/detail/win32_api.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,29 +8,22 @@ // ////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTERPROCESS_WIN32_PRIMITIVES_HPP -#define BOOST_INTERPROCESS_WIN32_PRIMITIVES_HPP +#ifndef BOOST_INTERPROCESS_WIN32_SYNC_PRIMITIVES_HPP +#define BOOST_INTERPROCESS_WIN32_SYNC_PRIMITIVES_HPP #include #include -#include #include #include -#include -#include - -#include #include #include #include - -#if defined (_MSC_VER) && (_MSC_VER >= 1200) +#if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once -# pragma comment( lib, "Advapi32.lib" ) +# pragma comment( lib, "advapi32.lib" ) # pragma comment( lib, "oleaut32.lib" ) # pragma comment( lib, "Ole32.lib" ) -# pragma comment( lib, "Psapi.lib" ) #endif #if (defined BOOST_INTERPROCESS_WINDOWS) @@ -50,24 +43,19 @@ namespace winapi { //Some used constants static const unsigned long infinite_time = 0xFFFFFFFF; static const unsigned long error_already_exists = 183L; -static const unsigned long error_invalid_handle = 6L; static const unsigned long error_sharing_violation = 32L; static const unsigned long error_file_not_found = 2u; static const unsigned long error_no_more_files = 18u; -static const unsigned long error_not_locked = 158L; //Retries in CreateFile, see http://support.microsoft.com/kb/316609 -static const unsigned long error_sharing_violation_tries = 3L; -static const unsigned long error_sharing_violation_sleep_ms = 250L; -static const unsigned long error_file_too_large = 223L; -static const unsigned long error_insufficient_buffer = 122L; -static const unsigned long error_handle_eof = 38L; +static const unsigned int error_sharing_violation_tries = 3u; +static const unsigned int error_sharing_violation_sleep_ms = 250u; + static const unsigned long semaphore_all_access = (0x000F0000L)|(0x00100000L)|0x3; static const unsigned long mutex_all_access = (0x000F0000L)|(0x00100000L)|0x0001; static const unsigned long page_readonly = 0x02; static const unsigned long page_readwrite = 0x04; static const unsigned long page_writecopy = 0x08; -static const unsigned long page_noaccess = 0x01; static const unsigned long standard_rights_required = 0x000F0000L; static const unsigned long section_query = 0x0001; @@ -95,7 +83,6 @@ static const unsigned long file_open_for_backup_intent = 0x00004000; static const int file_share_valid_flags = 0x00000007; static const long file_delete_on_close = 0x00001000L; static const long obj_case_insensitive = 0x00000040L; -static const long delete_flag = 0x00010000L; static const unsigned long movefile_copy_allowed = 0x02; static const unsigned long movefile_delay_until_reboot = 0x04; @@ -145,15 +132,7 @@ static const unsigned long format_message_max_width_mask static const unsigned long lang_neutral = (unsigned long)0x00; static const unsigned long sublang_default = (unsigned long)0x01; static const unsigned long invalid_file_size = (unsigned long)0xFFFFFFFF; -static const unsigned long invalid_file_attributes = ((unsigned long)-1); -static void * const invalid_handle_value = ((void*)(long)(-1)); - -static const unsigned long file_type_char = 0x0002L; -static const unsigned long file_type_disk = 0x0001L; -static const unsigned long file_type_pipe = 0x0003L; -static const unsigned long file_type_remote = 0x8000L; -static const unsigned long file_type_unknown = 0x0000L; - +static void * const invalid_handle_value = (void*)(long)(-1); static const unsigned long create_new = 1; static const unsigned long create_always = 2; static const unsigned long open_existing = 3; @@ -169,8 +148,6 @@ static const unsigned long lockfile_exclusive_lock = 2; static const unsigned long error_lock_violation = 33; static const unsigned long security_descriptor_revision = 1; -const unsigned long max_record_buffer_size = 0x10000L; // 64K - //Own defines static const long SystemTimeOfDayInfoLength = 48; static const long BootAndSystemstampLength = 16; @@ -182,41 +159,13 @@ static void * const hkey_local_machine = (void*)(unsigned long*)(long)(0x800000 static unsigned long key_query_value = 0x0001; //COM API -const unsigned long RPC_C_AUTHN_LEVEL_PKT_BIPC = 4; -const unsigned long RPC_C_AUTHN_DEFAULT_BIPC = 0xffffffffL; -const unsigned long RPC_C_AUTHZ_DEFAULT_BIPC = 0xffffffffL; -const unsigned long RPC_C_IMP_LEVEL_IMPERSONATE_BIPC = 3; -const signed long EOAC_NONE_BIPC = 0; -const signed long CLSCTX_INPROC_SERVER_BIPC = 0x1; -const signed long CLSCTX_LOCAL_SERVER_BIPC = 0x4; -const signed long WBEM_FLAG_RETURN_IMMEDIATELY_BIPC = 0x10; -const signed long WBEM_FLAG_RETURN_WHEN_COMPLETE_BIPC = 0x0; -const signed long WBEM_FLAG_FORWARD_ONLY_BIPC = 0x20; -const signed long WBEM_INFINITE_BIPC = 0xffffffffL; -const signed long RPC_E_TOO_LATE_BIPC = 0x80010119L; -const signed long S_OK_BIPC = 0L; -const signed long S_FALSE_BIPC = 1; -const signed long RPC_E_CHANGED_MODE_BIPC = 0x80010106L; -const unsigned long COINIT_APARTMENTTHREADED_BIPC = 0x2; -const unsigned long COINIT_MULTITHREADED_BIPC = 0x0; -const unsigned long COINIT_DISABLE_OLE1DDE_BIPC = 0x4; -const unsigned long COINIT_SPEED_OVER_MEMORY_BIPC = 0x4; - -//If the user needs to change default COM initialization model, -//it can define BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL to one of these: -// -// COINIT_APARTMENTTHREADED_BIPC -// COINIT_MULTITHREADED_BIPC -// COINIT_DISABLE_OLE1DDE_BIPC -// COINIT_SPEED_OVER_MEMORY_BIPC -#if !defined(BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL) - #define BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL COINIT_APARTMENTTHREADED_BIPC -#elif (BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL != COINIT_APARTMENTTHREADED_BIPC) &&\ - (BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL != COINIT_MULTITHREADED_BIPC) &&\ - (BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL != COINIT_DISABLE_OLE1DDE_BIPC) &&\ - (BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL != COINIT_SPEED_OVER_MEMORY_BIPC) - #error "Wrong value for BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL macro" -#endif +const long RPC_C_AUTHN_LEVEL_PKT_IG = 4; +const long RPC_C_IMP_LEVEL_IMPERSONATE_IG = 3; +const long EOAC_NONE_IG = 0; +const long CLSCTX_INPROC_SERVER_IG = 0x1; +const long CLSCTX_LOCAL_SERVER_IG = 0x4; +const long WBEM_FLAG_RETURN_IMMEDIATELY_IG = 0x10; +const long WBEM_INFINITE_IG = 0xffffffff; } //namespace winapi { } //namespace interprocess { @@ -227,7 +176,7 @@ namespace boost { namespace interprocess { namespace winapi { -struct GUID_BIPC +struct GUID_IG { unsigned long Data1; unsigned short Data2; @@ -235,10 +184,10 @@ struct GUID_BIPC unsigned char Data4[8]; }; -const GUID_BIPC CLSID_WbemAdministrativeLocator = +const GUID_IG CLSID_WbemAdministrativeLocator = { 0xcb8555cc, 0x9128, 0x11d1, {0xad, 0x9b, 0x00, 0xc0, 0x4f, 0xd8, 0xfd, 0xff}}; -const GUID_BIPC IID_IUnknown = { 0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; +const GUID_IG IID_IUnknown = { 0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; struct wchar_variant { @@ -249,339 +198,341 @@ struct wchar_variant } value; }; -struct IUnknown_BIPC -{ - public: - virtual long __stdcall QueryInterface( - const GUID_BIPC &riid, // [in] - void **ppvObject) = 0; // [iid_is][out] - - virtual unsigned long __stdcall AddRef (void) = 0; - virtual unsigned long __stdcall Release(void) = 0; -}; + struct IUnknown_IG + { + public: + virtual long __stdcall QueryInterface( + /* [in] */ const GUID_IG &riid, + /* [iid_is][out] */ void **ppvObject) = 0; + + virtual unsigned long __stdcall AddRef( void) = 0; + + virtual unsigned long __stdcall Release( void) = 0; + }; -struct IWbemClassObject_BIPC : public IUnknown_BIPC +struct IWbemClassObject_IG : public IUnknown_IG { public: - virtual long __stdcall GetQualifierSet( + virtual long __stdcall GetQualifierSet( /* [out] */ void **ppQualSet) = 0; - - virtual long __stdcall Get( + + virtual long __stdcall Get( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags, /* [unique][in][out] */ wchar_variant *pVal, /* [unique][in][out] */ long *pType, /* [unique][in][out] */ long *plFlavor) = 0; - - virtual long __stdcall Put( + + virtual long __stdcall Put( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags, /* [in] */ wchar_variant *pVal, /* [in] */ long Type) = 0; - - virtual long __stdcall Delete( + + virtual long __stdcall Delete( /* [string][in] */ const wchar_t * wszName) = 0; - - virtual long __stdcall GetNames( + + virtual long __stdcall GetNames( /* [string][in] */ const wchar_t * wszQualifierName, /* [in] */ long lFlags, /* [in] */ wchar_variant *pQualifierVal, /* [out] */ void * *pNames) = 0; - - virtual long __stdcall BeginEnumeration( + + virtual long __stdcall BeginEnumeration( /* [in] */ long lEnumFlags) = 0; - - virtual long __stdcall Next( + + virtual long __stdcall Next( /* [in] */ long lFlags, /* [unique][in][out] */ wchar_t * *strName, /* [unique][in][out] */ wchar_variant *pVal, /* [unique][in][out] */ long *pType, /* [unique][in][out] */ long *plFlavor) = 0; - + virtual long __stdcall EndEnumeration( void) = 0; - - virtual long __stdcall GetPropertyQualifierSet( + + virtual long __stdcall GetPropertyQualifierSet( /* [string][in] */ const wchar_t * wszProperty, /* [out] */ void **ppQualSet) = 0; - - virtual long __stdcall Clone( - /* [out] */ IWbemClassObject_BIPC **ppCopy) = 0; - - virtual long __stdcall GetObjectText( + + virtual long __stdcall Clone( + /* [out] */ IWbemClassObject_IG **ppCopy) = 0; + + virtual long __stdcall GetObjectText( /* [in] */ long lFlags, /* [out] */ wchar_t * *pstrObjectText) = 0; - - virtual long __stdcall SpawnDerivedClass( + + virtual long __stdcall SpawnDerivedClass( /* [in] */ long lFlags, - /* [out] */ IWbemClassObject_BIPC **ppNewClass) = 0; - - virtual long __stdcall SpawnInstance( + /* [out] */ IWbemClassObject_IG **ppNewClass) = 0; + + virtual long __stdcall SpawnInstance( /* [in] */ long lFlags, - /* [out] */ IWbemClassObject_BIPC **ppNewInstance) = 0; - - virtual long __stdcall CompareTo( + /* [out] */ IWbemClassObject_IG **ppNewInstance) = 0; + + virtual long __stdcall CompareTo( /* [in] */ long lFlags, - /* [in] */ IWbemClassObject_BIPC *pCompareTo) = 0; - - virtual long __stdcall GetPropertyOrigin( + /* [in] */ IWbemClassObject_IG *pCompareTo) = 0; + + virtual long __stdcall GetPropertyOrigin( /* [string][in] */ const wchar_t * wszName, /* [out] */ wchar_t * *pstrClassName) = 0; - - virtual long __stdcall InheritsFrom( + + virtual long __stdcall InheritsFrom( /* [in] */ const wchar_t * strAncestor) = 0; - - virtual long __stdcall GetMethod( + + virtual long __stdcall GetMethod( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags, - /* [out] */ IWbemClassObject_BIPC **ppInSignature, - /* [out] */ IWbemClassObject_BIPC **ppOutSignature) = 0; - - virtual long __stdcall PutMethod( + /* [out] */ IWbemClassObject_IG **ppInSignature, + /* [out] */ IWbemClassObject_IG **ppOutSignature) = 0; + + virtual long __stdcall PutMethod( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags, - /* [in] */ IWbemClassObject_BIPC *pInSignature, - /* [in] */ IWbemClassObject_BIPC *pOutSignature) = 0; - - virtual long __stdcall DeleteMethod( + /* [in] */ IWbemClassObject_IG *pInSignature, + /* [in] */ IWbemClassObject_IG *pOutSignature) = 0; + + virtual long __stdcall DeleteMethod( /* [string][in] */ const wchar_t * wszName) = 0; - - virtual long __stdcall BeginMethodEnumeration( + + virtual long __stdcall BeginMethodEnumeration( /* [in] */ long lEnumFlags) = 0; - - virtual long __stdcall NextMethod( + + virtual long __stdcall NextMethod( /* [in] */ long lFlags, /* [unique][in][out] */ wchar_t * *pstrName, - /* [unique][in][out] */ IWbemClassObject_BIPC **ppInSignature, - /* [unique][in][out] */ IWbemClassObject_BIPC **ppOutSignature) = 0; - + /* [unique][in][out] */ IWbemClassObject_IG **ppInSignature, + /* [unique][in][out] */ IWbemClassObject_IG **ppOutSignature) = 0; + virtual long __stdcall EndMethodEnumeration( void) = 0; - - virtual long __stdcall GetMethodQualifierSet( + + virtual long __stdcall GetMethodQualifierSet( /* [string][in] */ const wchar_t * wszMethod, /* [out] */ void **ppQualSet) = 0; - - virtual long __stdcall GetMethodOrigin( + + virtual long __stdcall GetMethodOrigin( /* [string][in] */ const wchar_t * wszMethodName, /* [out] */ wchar_t * *pstrClassName) = 0; - + }; -struct IWbemContext_BIPC : public IUnknown_BIPC + +struct IWbemContext_IG : public IUnknown_IG { public: - virtual long __stdcall Clone( - /* [out] */ IWbemContext_BIPC **ppNewCopy) = 0; - - virtual long __stdcall GetNames( + virtual long __stdcall Clone( + /* [out] */ IWbemContext_IG **ppNewCopy) = 0; + + virtual long __stdcall GetNames( /* [in] */ long lFlags, /* [out] */ void * *pNames) = 0; - - virtual long __stdcall BeginEnumeration( + + virtual long __stdcall BeginEnumeration( /* [in] */ long lFlags) = 0; - - virtual long __stdcall Next( + + virtual long __stdcall Next( /* [in] */ long lFlags, /* [out] */ wchar_t * *pstrName, /* [out] */ wchar_variant *pValue) = 0; - + virtual long __stdcall EndEnumeration( void) = 0; - - virtual long __stdcall SetValue( + + virtual long __stdcall SetValue( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags, /* [in] */ wchar_variant *pValue) = 0; - - virtual long __stdcall GetValue( + + virtual long __stdcall GetValue( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags, /* [out] */ wchar_variant *pValue) = 0; - - virtual long __stdcall DeleteValue( + + virtual long __stdcall DeleteValue( /* [string][in] */ const wchar_t * wszName, /* [in] */ long lFlags) = 0; - + virtual long __stdcall DeleteAll( void) = 0; - + }; -struct IEnumWbemClassObject_BIPC : public IUnknown_BIPC +struct IEnumWbemClassObject_IG : public IUnknown_IG { public: virtual long __stdcall Reset( void) = 0; - - virtual long __stdcall Next( + + virtual long __stdcall Next( /* [in] */ long lTimeout, /* [in] */ unsigned long uCount, - /* [length_is][size_is][out] */ IWbemClassObject_BIPC **apObjects, + /* [length_is][size_is][out] */ IWbemClassObject_IG **apObjects, /* [out] */ unsigned long *puReturned) = 0; - - virtual long __stdcall NextAsync( + + virtual long __stdcall NextAsync( /* [in] */ unsigned long uCount, /* [in] */ void *pSink) = 0; - - virtual long __stdcall Clone( + + virtual long __stdcall Clone( /* [out] */ void **ppEnum) = 0; - - virtual long __stdcall Skip( + + virtual long __stdcall Skip( /* [in] */ long lTimeout, /* [in] */ unsigned long nCount) = 0; - + }; -struct IWbemServices_BIPC : public IUnknown_BIPC +struct IWbemServices_IG : public IUnknown_IG { public: - virtual long __stdcall OpenNamespace( + virtual long __stdcall OpenNamespace( /* [in] */ const wchar_t * strNamespace, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [unique][in][out] */ void **ppWorkingNamespace, /* [unique][in][out] */ void **ppResult) = 0; - - virtual long __stdcall CancelAsyncCall( + + virtual long __stdcall CancelAsyncCall( /* [in] */ void *pSink) = 0; - - virtual long __stdcall QueryObjectSink( + + virtual long __stdcall QueryObjectSink( /* [in] */ long lFlags, /* [out] */ void **ppResponseHandler) = 0; - - virtual long __stdcall GetObject( + + virtual long __stdcall GetObject( /* [in] */ const wchar_t * strObjectPath, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [unique][in][out] */ void **ppObject, /* [unique][in][out] */ void **ppCallResult) = 0; - - virtual long __stdcall GetObjectAsync( + + virtual long __stdcall GetObjectAsync( /* [in] */ const wchar_t * strObjectPath, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall PutClass( - /* [in] */ IWbemClassObject_BIPC *pObject, + + virtual long __stdcall PutClass( + /* [in] */ IWbemClassObject_IG *pObject, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [unique][in][out] */ void **ppCallResult) = 0; - - virtual long __stdcall PutClassAsync( - /* [in] */ IWbemClassObject_BIPC *pObject, + + virtual long __stdcall PutClassAsync( + /* [in] */ IWbemClassObject_IG *pObject, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall DeleteClass( + + virtual long __stdcall DeleteClass( /* [in] */ const wchar_t * strClass, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [unique][in][out] */ void **ppCallResult) = 0; - - virtual long __stdcall DeleteClassAsync( + + virtual long __stdcall DeleteClassAsync( /* [in] */ const wchar_t * strClass, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall CreateClassEnum( + + virtual long __stdcall CreateClassEnum( /* [in] */ const wchar_t * strSuperclass, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [out] */ void **ppEnum) = 0; - - virtual long __stdcall CreateClassEnumAsync( + + virtual long __stdcall CreateClassEnumAsync( /* [in] */ const wchar_t * strSuperclass, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall PutInstance( + + virtual long __stdcall PutInstance( /* [in] */ void *pInst, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [unique][in][out] */ void **ppCallResult) = 0; - - virtual long __stdcall PutInstanceAsync( + + virtual long __stdcall PutInstanceAsync( /* [in] */ void *pInst, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall DeleteInstance( + + virtual long __stdcall DeleteInstance( /* [in] */ const wchar_t * strObjectPath, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [unique][in][out] */ void **ppCallResult) = 0; - - virtual long __stdcall DeleteInstanceAsync( + + virtual long __stdcall DeleteInstanceAsync( /* [in] */ const wchar_t * strObjectPath, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall CreateInstanceEnum( + + virtual long __stdcall CreateInstanceEnum( /* [in] */ const wchar_t * strFilter, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [out] */ void **ppEnum) = 0; - - virtual long __stdcall CreateInstanceEnumAsync( + + virtual long __stdcall CreateInstanceEnumAsync( /* [in] */ const wchar_t * strFilter, /* [in] */ long lFlags, /* [in] */ void *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall ExecQuery( + + virtual long __stdcall ExecQuery( /* [in] */ const wchar_t * strQueryLanguage, /* [in] */ const wchar_t * strQuery, /* [in] */ long lFlags, - /* [in] */ IWbemContext_BIPC *pCtx, - /* [out] */ IEnumWbemClassObject_BIPC **ppEnum) = 0; + /* [in] */ IWbemContext_IG *pCtx, + /* [out] */ IEnumWbemClassObject_IG **ppEnum) = 0; - virtual long __stdcall ExecQueryAsync( + virtual long __stdcall ExecQueryAsync( /* [in] */ const wchar_t * strQueryLanguage, /* [in] */ const wchar_t * strQuery, /* [in] */ long lFlags, - /* [in] */ IWbemContext_BIPC *pCtx, + /* [in] */ IWbemContext_IG *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall ExecNotificationQuery( + + virtual long __stdcall ExecNotificationQuery( /* [in] */ const wchar_t * strQueryLanguage, /* [in] */ const wchar_t * strQuery, /* [in] */ long lFlags, - /* [in] */ IWbemContext_BIPC *pCtx, + /* [in] */ IWbemContext_IG *pCtx, /* [out] */ void **ppEnum) = 0; - - virtual long __stdcall ExecNotificationQueryAsync( + + virtual long __stdcall ExecNotificationQueryAsync( /* [in] */ const wchar_t * strQueryLanguage, /* [in] */ const wchar_t * strQuery, /* [in] */ long lFlags, - /* [in] */ IWbemContext_BIPC *pCtx, + /* [in] */ IWbemContext_IG *pCtx, /* [in] */ void *pResponseHandler) = 0; - - virtual long __stdcall ExecMethod( + + virtual long __stdcall ExecMethod( /* [in] */ const wchar_t * strObjectPath, /* [in] */ const wchar_t * strMethodName, /* [in] */ long lFlags, - /* [in] */ IWbemContext_BIPC *pCtx, - /* [in] */ IWbemClassObject_BIPC *pInParams, - /* [unique][in][out] */ IWbemClassObject_BIPC **ppOutParams, + /* [in] */ IWbemContext_IG *pCtx, + /* [in] */ IWbemClassObject_IG *pInParams, + /* [unique][in][out] */ IWbemClassObject_IG **ppOutParams, /* [unique][in][out] */ void **ppCallResult) = 0; - - virtual long __stdcall ExecMethodAsync( + + virtual long __stdcall ExecMethodAsync( /* [in] */ const wchar_t * strObjectPath, /* [in] */ const wchar_t * strMethodName, /* [in] */ long lFlags, - /* [in] */ IWbemContext_BIPC *pCtx, - /* [in] */ IWbemClassObject_BIPC *pInParams, + /* [in] */ IWbemContext_IG *pCtx, + /* [in] */ IWbemClassObject_IG *pInParams, /* [in] */ void *pResponseHandler) = 0; - + }; -struct IWbemLocator_BIPC : public IUnknown_BIPC +struct IWbemLocator_IG : public IUnknown_IG { public: - virtual long __stdcall ConnectServer( + virtual long __stdcall ConnectServer( /* [in] */ const wchar_t * strNetworkResource, /* [in] */ const wchar_t * strUser, /* [in] */ const wchar_t * strPassword, @@ -589,11 +540,13 @@ struct IWbemLocator_BIPC : public IUnknown_BIPC /* [in] */ long lSecurityFlags, /* [in] */ const wchar_t * strAuthority, /* [in] */ void *pCtx, - /* [out] */ IWbemServices_BIPC **ppNamespace) = 0; - + /* [out] */ IWbemServices_IG **ppNamespace) = 0; + }; + + -struct interprocess_overlapped +struct interprocess_overlapped { unsigned long *internal; unsigned long *internal_high; @@ -608,22 +561,9 @@ struct interprocess_overlapped void *h_event; }; -struct interprocess_semaphore_basic_information -{ - unsigned int count; // current semaphore count - unsigned int limit; // max semaphore count -}; - -struct interprocess_section_basic_information -{ - void * base_address; - unsigned long section_attributes; - __int64 section_size; -}; - struct interprocess_filetime -{ - unsigned long dwLowDateTime; +{ + unsigned long dwLowDateTime; unsigned long dwHighDateTime; }; @@ -669,7 +609,7 @@ struct system_info { struct interprocess_memory_basic_information { - void * BaseAddress; + void * BaseAddress; void * AllocationBase; unsigned long AllocationProtect; unsigned long RegionSize; @@ -678,14 +618,14 @@ struct interprocess_memory_basic_information unsigned long Type; }; -struct interprocess_acl +typedef struct _interprocess_acl { unsigned char AclRevision; unsigned char Sbz1; unsigned short AclSize; unsigned short AceCount; unsigned short Sbz2; -}; +} interprocess_acl; typedef struct _interprocess_security_descriptor { @@ -742,10 +682,6 @@ enum file_information_class_t { file_maximum_information }; -enum semaphore_information_class { - semaphore_basic_information = 0 -}; - struct file_name_information_t { unsigned long FileNameLength; wchar_t FileName[1]; @@ -830,51 +766,12 @@ enum object_information_class object_data_information }; -enum section_information_class -{ - section_basic_information, - section_image_information -}; - struct object_name_information_t { unicode_string_t Name; wchar_t NameBuffer[1]; }; -struct interprocess_eventlogrecord -{ - unsigned long Length; // Length of full record - unsigned long Reserved; // Used by the service - unsigned long RecordNumber; // Absolute record number - unsigned long TimeGenerated; // Seconds since 1-1-1970 - unsigned long TimeWritten; // Seconds since 1-1-1970 - unsigned long EventID; - unsigned short EventType; - unsigned short NumStrings; - unsigned short EventCategory; - unsigned short ReservedFlags; // For use with paired events (auditing) - unsigned long ClosingRecordNumber; // For use with paired events (auditing) - unsigned long StringOffset; // Offset from beginning of record - unsigned long UserSidLength; - unsigned long UserSidOffset; - unsigned long DataLength; - unsigned long DataOffset; // Offset from beginning of record - // - // Then follow: - // - // wchar_t SourceName[] - // wchar_t Computername[] - // SID UserSid - // wchar_t Strings[] - // BYTE Data[] - // CHAR Pad[] - // unsigned long Length; - // -}; - -//Kernel32.dll - //Some windows API declarations extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentProcessId(); extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(); @@ -883,10 +780,7 @@ extern "C" __declspec(dllimport) int __stdcall GetProcessTimes , interprocess_filetime *lpExitTime,interprocess_filetime *lpKernelTime , interprocess_filetime *lpUserTime ); extern "C" __declspec(dllimport) void __stdcall Sleep(unsigned long); -extern "C" __declspec(dllimport) unsigned long __stdcall GetTickCount(void); -extern "C" __declspec(dllimport) int __stdcall SwitchToThread(); extern "C" __declspec(dllimport) unsigned long __stdcall GetLastError(); -extern "C" __declspec(dllimport) void __stdcall SetLastError(unsigned long); extern "C" __declspec(dllimport) void * __stdcall GetCurrentProcess(); extern "C" __declspec(dllimport) int __stdcall CloseHandle(void*); extern "C" __declspec(dllimport) int __stdcall DuplicateHandle @@ -894,12 +788,11 @@ extern "C" __declspec(dllimport) int __stdcall DuplicateHandle , void *hTargetProcessHandle, void **lpTargetHandle , unsigned long dwDesiredAccess, int bInheritHandle , unsigned long dwOptions); -extern "C" __declspec(dllimport) long __stdcall GetFileType(void *hFile); extern "C" __declspec(dllimport) void *__stdcall FindFirstFileA(const char *lpFileName, win32_find_data_t *lpFindFileData); extern "C" __declspec(dllimport) int __stdcall FindNextFileA(void *hFindFile, win32_find_data_t *lpFindFileData); extern "C" __declspec(dllimport) int __stdcall FindClose(void *hFindFile); -//extern "C" __declspec(dllimport) void __stdcall GetSystemTimeAsFileTime(interprocess_filetime*); -//extern "C" __declspec(dllimport) int __stdcall FileTimeToLocalFileTime(const interprocess_filetime *in, const interprocess_filetime *out); +extern "C" __declspec(dllimport) void __stdcall GetSystemTimeAsFileTime(interprocess_filetime*); +extern "C" __declspec(dllimport) int __stdcall FileTimeToLocalFileTime(const interprocess_filetime *in, const interprocess_filetime *out); extern "C" __declspec(dllimport) void * __stdcall CreateMutexA(interprocess_security_attributes*, int, const char *); extern "C" __declspec(dllimport) void * __stdcall OpenMutexA(unsigned long, int, const char *); extern "C" __declspec(dllimport) unsigned long __stdcall WaitForSingleObject(void *, unsigned long); @@ -912,18 +805,17 @@ extern "C" __declspec(dllimport) void * __stdcall CreateFileMappingA (void *, in extern "C" __declspec(dllimport) void * __stdcall MapViewOfFileEx (void *, unsigned long, unsigned long, unsigned long, std::size_t, void*); extern "C" __declspec(dllimport) void * __stdcall OpenFileMappingA (unsigned long, int, const char *); extern "C" __declspec(dllimport) void * __stdcall CreateFileA (const char *, unsigned long, unsigned long, struct interprocess_security_attributes*, unsigned long, unsigned long, void *); +extern "C" __declspec(dllimport) int __stdcall DeleteFileA (const char *); +extern "C" __declspec(dllimport) int __stdcall MoveFileExA (const char *, const char *, unsigned long); extern "C" __declspec(dllimport) void __stdcall GetSystemInfo (struct system_info *); extern "C" __declspec(dllimport) int __stdcall FlushViewOfFile (void *, std::size_t); -extern "C" __declspec(dllimport) int __stdcall VirtualUnlock (void *, std::size_t); -extern "C" __declspec(dllimport) int __stdcall VirtualProtect (void *, std::size_t, unsigned long, unsigned long *); extern "C" __declspec(dllimport) int __stdcall FlushFileBuffers (void *); extern "C" __declspec(dllimport) int __stdcall GetFileSizeEx (void *, __int64 *size); extern "C" __declspec(dllimport) unsigned long __stdcall FormatMessageA - (unsigned long dwFlags, const void *lpSource, unsigned long dwMessageId, - unsigned long dwLanguageId, char *lpBuffer, unsigned long nSize, + (unsigned long dwFlags, const void *lpSource, unsigned long dwMessageId, + unsigned long dwLanguageId, char *lpBuffer, unsigned long nSize, std::va_list *Arguments); extern "C" __declspec(dllimport) void *__stdcall LocalFree (void *); -extern "C" __declspec(dllimport) unsigned long __stdcall GetFileAttributesA(const char *); extern "C" __declspec(dllimport) int __stdcall CreateDirectoryA(const char *, interprocess_security_attributes*); extern "C" __declspec(dllimport) int __stdcall RemoveDirectoryA(const char *lpPathName); extern "C" __declspec(dllimport) int __stdcall GetTempPathA(unsigned long length, char *buffer); @@ -936,7 +828,6 @@ extern "C" __declspec(dllimport) int __stdcall UnlockFile(void *hnd, unsigned lo extern "C" __declspec(dllimport) int __stdcall LockFileEx(void *hnd, unsigned long flags, unsigned long reserved, unsigned long size_low, unsigned long size_high, interprocess_overlapped* overlapped); extern "C" __declspec(dllimport) int __stdcall UnlockFileEx(void *hnd, unsigned long reserved, unsigned long size_low, unsigned long size_high, interprocess_overlapped* overlapped); extern "C" __declspec(dllimport) int __stdcall WriteFile(void *hnd, const void *buffer, unsigned long bytes_to_write, unsigned long *bytes_written, interprocess_overlapped* overlapped); -extern "C" __declspec(dllimport) int __stdcall ReadFile(void *hnd, void *buffer, unsigned long bytes_to_read, unsigned long *bytes_read, interprocess_overlapped* overlapped); extern "C" __declspec(dllimport) int __stdcall InitializeSecurityDescriptor(interprocess_security_descriptor *pSecurityDescriptor, unsigned long dwRevision); extern "C" __declspec(dllimport) int __stdcall SetSecurityDescriptorDacl(interprocess_security_descriptor *pSecurityDescriptor, int bDaclPresent, interprocess_acl *pDacl, int bDaclDefaulted); extern "C" __declspec(dllimport) void *__stdcall LoadLibraryA(const char *); @@ -945,80 +836,47 @@ extern "C" __declspec(dllimport) void *__stdcall GetProcAddress(void *, const ch extern "C" __declspec(dllimport) void *__stdcall GetModuleHandleA(const char*); extern "C" __declspec(dllimport) void *__stdcall GetFileInformationByHandle(void *, interprocess_by_handle_file_information*); -//Advapi32.dll -extern "C" __declspec(dllimport) long __stdcall RegOpenKeyExA(void *, const char *, unsigned long, unsigned long, void **); -extern "C" __declspec(dllimport) long __stdcall RegQueryValueExA(void *, const char *, unsigned long*, unsigned long*, unsigned char *, unsigned long*); -extern "C" __declspec(dllimport) long __stdcall RegCloseKey(void *); -//Ole32.dll -extern "C" __declspec(dllimport) long __stdcall CoInitializeEx(void *pvReserved, unsigned long dwCoInit); +//COM API +extern "C" __declspec(dllimport) long __stdcall CoInitialize(void *pvReserved); extern "C" __declspec(dllimport) long __stdcall CoInitializeSecurity( - void* pSecDesc, - long cAuthSvc, - void * asAuthSvc, - void *pReserved1, - unsigned long dwAuthnLevel, - unsigned long dwImpLevel, - void *pAuthList, - unsigned long dwCapabilities, - void *pReserved3 ); - - extern "C" __declspec(dllimport) long __stdcall CoSetProxyBlanket( - IUnknown_BIPC *pProxy, - unsigned long dwAuthnSvc, - unsigned long dwAuthzSvc, - wchar_t *pServerPrincName, - unsigned long dwAuthnLevel, - unsigned long dwImpLevel, - void *pAuthInfo, - unsigned long dwCapabilities); -extern "C" __declspec(dllimport) long __stdcall CoCreateInstance(const GUID_BIPC & rclsid, IUnknown_BIPC *pUnkOuter, - unsigned long dwClsContext, const GUID_BIPC & riid, void** ppv); -extern "C" __declspec(dllimport) void __stdcall CoUninitialize(void); + void* pSecDesc, + long cAuthSvc, + void *asAuthSvc, + void *pReserved1, + unsigned long dwAuthnLevel, + unsigned long dwImpLevel, + void *pAuthList, + unsigned long dwCapabilities, + void *pReserved3 ); -//OleAut32.dll extern "C" __declspec(dllimport) long __stdcall VariantClear(wchar_variant * pvarg); +extern "C" __declspec(dllimport) long __stdcall CoCreateInstance(const GUID_IG & rclsid, IUnknown_IG *pUnkOuter, + unsigned long dwClsContext, const GUID_IG & riid, void** ppv); +extern "C" __declspec(dllimport) void __stdcall CoUninitialize(void); -//EventLog access functions - -static const unsigned long eventlog_sequential_read = 0x0001; -static const unsigned long eventlog_backwards_read = 0x0008; - -extern "C" __declspec(dllimport) void* __stdcall OpenEventLogA - (const char* lpUNCServerName, const char* lpSourceName); - -extern "C" __declspec(dllimport) int __stdcall CloseEventLog(void *hEventLog); - -extern "C" __declspec(dllimport) int __stdcall ReadEventLogA - (void *hEventLog, - unsigned long dwReadFlags, - unsigned long dwRecordOffset, - void *lpBuffer, - unsigned long nNumberOfBytesToRead, - unsigned long *pnBytesRead, - unsigned long *pnMinNumberOfBytesNeeded - ); - -//ntdll.dll -typedef long (__stdcall *NtDeleteFile_t)(object_attributes_t *ObjectAttributes); -typedef long (__stdcall *NtSetInformationFile_t)(void *FileHandle, io_status_block_t *IoStatusBlock, void *FileInformation, unsigned long Length, int FileInformationClass ); -typedef long (__stdcall *NtOpenFile)(void **FileHandle, unsigned long DesiredAccess, object_attributes_t *ObjectAttributes - , io_status_block_t *IoStatusBlock, unsigned long ShareAccess, unsigned long Length, unsigned long OpenOptions); -typedef long (__stdcall *NtQuerySystemInformation_t)(int, void*, unsigned long, unsigned long *); -typedef long (__stdcall *NtQueryObject_t)(void*, object_information_class, void *, unsigned long, unsigned long *); -typedef long (__stdcall *NtQuerySemaphore_t)(void*, unsigned int info_class, interprocess_semaphore_basic_information *pinfo, unsigned int info_size, unsigned int *ret_len); -typedef long (__stdcall *NtQuerySection_t)(void*, section_information_class, interprocess_section_basic_information *pinfo, unsigned long info_size, unsigned long *ret_len); +//API function typedefs +//Pointer to functions +typedef long (__stdcall *NtDeleteFile_t)(object_attributes_t *ObjectAttributes); +typedef long (__stdcall *NtSetInformationFile_t)(void *FileHandle, io_status_block_t *IoStatusBlock, void *FileInformation, unsigned long Length, int FileInformationClass ); typedef long (__stdcall *NtQueryInformationFile_t)(void *,io_status_block_t *,void *, long, int); typedef long (__stdcall *NtOpenFile_t)(void*,unsigned long ,object_attributes_t*,io_status_block_t*,unsigned long,unsigned long); typedef long (__stdcall *NtClose_t) (void*); -typedef long (__stdcall *NtQueryTimerResolution_t) (unsigned long* LowestResolution, unsigned long* HighestResolution, unsigned long* CurrentResolution); -typedef long (__stdcall *NtSetTimerResolution_t) (unsigned long RequestedResolution, int Set, unsigned long* ActualResolution); - -//kernel32.dll -typedef int (__stdcall *QueryPerformanceCounter_t) (__int64 *lpPerformanceCount); -typedef int (__stdcall *QueryPerformanceFrequency_t)(__int64 *lpFrequency); +typedef long (__stdcall *RtlCreateUnicodeStringFromAsciiz_t)(unicode_string_t *, const char *); +typedef void (__stdcall *RtlFreeUnicodeString_t)(unicode_string_t *); +typedef void (__stdcall *RtlInitUnicodeString_t)( unicode_string_t *, const wchar_t * ); +typedef long (__stdcall *RtlAppendUnicodeToString_t)(unicode_string_t *Destination, const wchar_t *Source); +typedef long (__stdcall * NtQuerySystemInformation_t)(int, void*, unsigned long, unsigned long *); +typedef long (__stdcall * NtQueryObject_t)(void*, object_information_class, void *, unsigned long, unsigned long *); +typedef unsigned long (__stdcall * GetMappedFileName_t)(void *, void *, wchar_t *, unsigned long); +typedef unsigned long (__stdcall * GetMappedFileName_t)(void *, void *, wchar_t *, unsigned long); +typedef long (__stdcall * RegOpenKey_t)(void *, const char *, void **); +typedef long (__stdcall * RegOpenKeyEx_t)(void *, const char *, unsigned long, unsigned long, void **); +typedef long (__stdcall * RegQueryValue_t)(void *, const char *, char *, long*); +typedef long (__stdcall * RegQueryValueEx_t)(void *, const char *, unsigned long*, unsigned long*, unsigned char *, unsigned long*); +typedef long (__stdcall * RegCloseKey_t)(void *); } //namespace winapi { } //namespace interprocess { @@ -1031,9 +889,6 @@ namespace winapi { inline unsigned long get_last_error() { return GetLastError(); } -inline void set_last_error(unsigned long err) -{ return SetLastError(err); } - inline unsigned long format_message (unsigned long dwFlags, const void *lpSource, unsigned long dwMessageId, unsigned long dwLanguageId, @@ -1051,18 +906,8 @@ inline unsigned long make_lang_id(unsigned long p, unsigned long s) { return ((((unsigned short)(s)) << 10) | (unsigned short)(p)); } inline void sched_yield() -{ - if(!SwitchToThread()){ - Sleep(0); - } -} - -inline void sleep_tick() { Sleep(1); } -inline void sleep(unsigned long ms) -{ Sleep(ms); } - inline unsigned long get_current_thread_id() { return GetCurrentThreadId(); } @@ -1096,21 +941,18 @@ inline bool duplicate_current_process_handle , duplicate_same_access); } -inline unsigned long get_file_type(void *hFile) -{ - return GetFileType(hFile); -} - -/* inline void get_system_time_as_file_time(interprocess_filetime *filetime) { GetSystemTimeAsFileTime(filetime); } inline bool file_time_to_local_file_time (const interprocess_filetime *in, const interprocess_filetime *out) { return 0 != FileTimeToLocalFileTime(in, out); } -*/ -inline void *open_or_create_mutex(const char *name, bool initial_owner, interprocess_security_attributes *attr) -{ return CreateMutexA(attr, (int)initial_owner, name); } + +inline void *create_mutex(const char *name) +{ return CreateMutexA(0, 0, name); } + +inline void *open_mutex(const char *name) +{ return OpenMutexA(mutex_all_access, 0, name); } inline unsigned long wait_for_single_object(void *handle, unsigned long time) { return WaitForSingleObject(handle, time); } @@ -1121,19 +963,19 @@ inline int release_mutex(void *handle) inline int unmap_view_of_file(void *address) { return UnmapViewOfFile(address); } -inline void *open_or_create_semaphore(const char *name, long initial_count, long maximum_count, interprocess_security_attributes *attr) -{ return CreateSemaphoreA(attr, initial_count, maximum_count, name); } - -inline void *open_semaphore(const char *name) -{ return OpenSemaphoreA(semaphore_all_access, 0, name); } +inline void *create_semaphore(long initialCount, const char *name) +{ return CreateSemaphoreA(0, initialCount, (long)(((unsigned long)(-1))>>1), name); } inline int release_semaphore(void *handle, long release_count, long *prev_count) { return ReleaseSemaphore(handle, release_count, prev_count); } +inline void *open_semaphore(const char *name) +{ return OpenSemaphoreA(semaphore_all_access, 1, name); } + class interprocess_all_access_security { interprocess_security_attributes sa; - interprocess_security_descriptor sd; + interprocess_security_descriptor sd; bool initialized; public: @@ -1154,21 +996,16 @@ class interprocess_all_access_security { return &sa; } }; -inline void * create_file_mapping (void * handle, unsigned long access, unsigned __int64 file_offset, const char * name, interprocess_security_attributes *psec) +inline void * create_file_mapping (void * handle, unsigned long access, unsigned long high_size, unsigned long low_size, const char * name, interprocess_security_attributes *psec) { - const unsigned long high_size(file_offset >> 32), low_size((boost::uint32_t)file_offset); - return CreateFileMappingA (handle, psec, access, high_size, low_size, name); + return CreateFileMappingA (handle, psec, access, high_size, low_size, name); } inline void * open_file_mapping (unsigned long access, const char *name) { return OpenFileMappingA (access, 0, name); } -inline void *map_view_of_file_ex(void *handle, unsigned long file_access, unsigned __int64 offset, std::size_t numbytes, void *base_addr) -{ - const unsigned long offset_low = (unsigned long)(offset & ((unsigned __int64)0xFFFFFFFF)); - const unsigned long offset_high = offset >> 32; - return MapViewOfFileEx(handle, file_access, offset_high, offset_low, numbytes, base_addr); -} +inline void *map_view_of_file_ex(void *handle, unsigned long file_access, unsigned long highoffset, unsigned long lowoffset, std::size_t numbytes, void *base_addr) +{ return MapViewOfFileEx(handle, file_access, highoffset, lowoffset, numbytes, base_addr); } inline void *create_file(const char *name, unsigned long access, unsigned long creation_flags, unsigned long attributes, interprocess_security_attributes *psec) { @@ -1183,23 +1020,23 @@ inline void *create_file(const char *name, unsigned long access, unsigned long c if (error_sharing_violation != get_last_error()){ return handle; } - sleep(error_sharing_violation_sleep_ms); + Sleep(error_sharing_violation_sleep_ms); } return invalid_handle_value; } +inline bool delete_file(const char *name) +{ return 0 != DeleteFileA(name); } + +inline bool move_file_ex(const char *source_filename, const char *destination_filename, unsigned long flags) +{ return 0 != MoveFileExA(source_filename, destination_filename, flags); } + inline void get_system_info(system_info *info) { GetSystemInfo(info); } inline bool flush_view_of_file(void *base_addr, std::size_t numbytes) { return 0 != FlushViewOfFile(base_addr, numbytes); } -inline bool virtual_unlock(void *base_addr, std::size_t numbytes) -{ return 0 != VirtualUnlock(base_addr, numbytes); } - -inline bool virtual_protect(void *base_addr, std::size_t numbytes, unsigned long flNewProtect, unsigned long &lpflOldProtect) -{ return 0 != VirtualProtect(base_addr, numbytes, flNewProtect, &lpflOldProtect); } - inline bool flush_file_buffers(void *handle) { return 0 != FlushFileBuffers(handle); } @@ -1207,9 +1044,9 @@ inline bool get_file_size(void *handle, __int64 &size) { return 0 != GetFileSizeEx(handle, &size); } inline bool create_directory(const char *name) -{ +{ interprocess_all_access_security sec; - return 0 != CreateDirectoryA(name, sec.get_attributes()); + return 0 != CreateDirectoryA(name, sec.get_attributes()); } inline bool remove_directory(const char *lpPathName) @@ -1233,9 +1070,6 @@ inline bool unlock_file_ex(void *hnd, unsigned long reserved, unsigned long size inline bool write_file(void *hnd, const void *buffer, unsigned long bytes_to_write, unsigned long *bytes_written, interprocess_overlapped* overlapped) { return 0 != WriteFile(hnd, buffer, bytes_to_write, bytes_written, overlapped); } -inline bool read_file(void *hnd, void *buffer, unsigned long bytes_to_read, unsigned long *bytes_read, interprocess_overlapped* overlapped) -{ return 0 != ReadFile(hnd, buffer, bytes_to_read, bytes_read, overlapped); } - inline bool get_file_information_by_handle(void *hnd, interprocess_by_handle_file_information *info) { return 0 != GetFileInformationByHandle(hnd, info); } @@ -1270,15 +1104,6 @@ inline void *get_current_process() inline void *get_module_handle(const char *name) { return GetModuleHandleA(name); } -inline long reg_open_key_ex(void *hKey, const char *lpSubKey, unsigned long ulOptions, unsigned long samDesired, void **phkResult) -{ return RegOpenKeyExA(hKey, lpSubKey, ulOptions, samDesired, phkResult); } - -inline long reg_query_value_ex(void *hKey, const char *lpValueName, unsigned long*lpReserved, unsigned long*lpType, unsigned char *lpData, unsigned long*lpcbData) -{ return RegQueryValueExA(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData); } - -inline long reg_close_key(void *hKey) -{ return RegCloseKey(hKey); } - inline void initialize_object_attributes ( object_attributes_t *pobject_attr, unicode_string_t *name , unsigned long attr, void *rootdir, void *security_descr) @@ -1299,160 +1124,61 @@ inline void rtl_init_empty_unicode_string(unicode_string_t *ucStr, wchar_t *buf, ucStr->MaximumLength = bufSize; } -//A class that locates and caches loaded DLL function addresses. -template -struct function_address_holder -{ - enum { NtSetInformationFile - , NtQuerySystemInformation - , NtQueryObject - , NtQuerySemaphore - , NtQuerySection - , NtOpenFile - , NtClose - , NtQueryTimerResolution - , NtSetTimerResolution - , QueryPerformanceCounter - , QueryPerformanceFrequency - , NumFunction - }; - enum { NtDll_dll, Kernel32_dll, NumModule }; - - private: - static const char *FunctionNames[NumFunction]; - static const char *ModuleNames[NumModule]; - static void *FunctionAddresses[NumFunction]; - static unsigned int FunctionModules[NumFunction]; - static volatile long FunctionStates[NumFunction]; - static void *ModuleAddresses[NumModule]; - static volatile long ModuleStates[NumModule]; - - static void *get_module_from_id(unsigned int id) - { - BOOST_ASSERT(id < (unsigned int)NumModule); - void *addr = get_module_handle(ModuleNames[id]); - BOOST_ASSERT(addr); - return addr; - } - - static void *get_module(const unsigned int id) - { - BOOST_ASSERT(id < (unsigned int)NumModule); - for(unsigned i = 0; ModuleStates[id] < 2; ++i){ - if(interlocked_compare_exchange(&ModuleStates[id], 1, 0) == 0){ - ModuleAddresses[id] = get_module_from_id(id); - interlocked_increment(&ModuleStates[id]); - break; - } - else if(i & 1){ - sched_yield(); - } - else{ - sleep_tick(); - } - } - return ModuleAddresses[id]; - } - - static void *get_address_from_dll(const unsigned int id) - { - BOOST_ASSERT(id < (unsigned int)NumFunction); - void *addr = get_proc_address(get_module(FunctionModules[id]), FunctionNames[id]); - BOOST_ASSERT(addr); - return addr; - } - - public: - static void *get(const unsigned int id) - { - BOOST_ASSERT(id < (unsigned int)NumFunction); - for(unsigned i = 0; FunctionStates[id] < 2; ++i){ - if(interlocked_compare_exchange(&FunctionStates[id], 1, 0) == 0){ - FunctionAddresses[id] = get_address_from_dll(id); - interlocked_increment(&FunctionStates[id]); - break; - } - else if(i & 1){ - sched_yield(); - } - else{ - sleep_tick(); - } - } - return FunctionAddresses[id]; - } -}; - -template -const char *function_address_holder::FunctionNames[function_address_holder::NumFunction] = -{ - "NtSetInformationFile", - "NtQuerySystemInformation", - "NtQueryObject", - "NtQuerySemaphore", - "NtQuerySection", - "NtOpenFile", - "NtClose", - "NtQueryTimerResolution", - "NtSetTimerResolution", - "QueryPerformanceCounter", - "QueryPerformanceFrequency" -}; - -template -unsigned int function_address_holder::FunctionModules[function_address_holder::NumFunction] = +//Complex winapi based functions... +struct library_unloader { - NtDll_dll, - NtDll_dll, - NtDll_dll, - NtDll_dll, - NtDll_dll, - NtDll_dll, - NtDll_dll, - NtDll_dll, - NtDll_dll, - Kernel32_dll, - Kernel32_dll + void *lib_; + library_unloader(void *module) : lib_(module){} + ~library_unloader(){ free_library(lib_); } }; -template -const char *function_address_holder::ModuleNames[function_address_holder::NumModule] = +//pszFilename must have room for at least MaxPath+1 characters +inline bool get_file_name_from_handle_function + (void * hFile, wchar_t *pszFilename, std::size_t length, std::size_t &out_length) { - "ntdll.dll", - "kernel32.dll" -}; - - -template -void *function_address_holder::FunctionAddresses[function_address_holder::NumFunction]; - -template -volatile long function_address_holder::FunctionStates[function_address_holder::NumFunction]; + if(length <= MaxPath){ + return false; + } -template -void *function_address_holder::ModuleAddresses[function_address_holder::NumModule]; + void *hiPSAPI = load_library("PSAPI.DLL"); + if (0 == hiPSAPI) + return 0; -template -volatile long function_address_holder::ModuleStates[function_address_holder::NumModule]; + library_unloader unloader(hiPSAPI); + // Pointer to function getMappedFileName() in PSAPI.DLL + GetMappedFileName_t pfGMFN = + (GetMappedFileName_t)get_proc_address(hiPSAPI, "GetMappedFileNameW"); + if (! pfGMFN){ + return 0; // Failed: unexpected error + } -struct dll_func - : public function_address_holder<0> -{}; + bool bSuccess = false; -//Complex winapi based functions... -struct library_unloader -{ - void *lib_; - library_unloader(void *module) : lib_(module){} - ~library_unloader(){ free_library(lib_); } -}; + // Create a file mapping object. + void * hFileMap = create_file_mapping(hFile, page_readonly, 0, 1, 0, 0); + if(hFileMap) + { + // Create a file mapping to get the file name. + void* pMem = map_view_of_file_ex(hFileMap, file_map_read, 0, 0, 1, 0); + + if (pMem){ + out_length = pfGMFN(get_current_process(), pMem, pszFilename, MaxPath); + if(out_length){ + bSuccess = true; + } + unmap_view_of_file(pMem); + } + close_handle(hFileMap); + } + return(bSuccess); +} inline bool get_system_time_of_day_information(system_timeofday_information &info) { NtQuerySystemInformation_t pNtQuerySystemInformation = (NtQuerySystemInformation_t) - dll_func::get(dll_func::NtQuerySystemInformation); + get_proc_address(get_module_handle("ntdll.dll"), "NtQuerySystemInformation"); unsigned long res; long status = pNtQuerySystemInformation(system_time_of_day_information, &info, sizeof(info), &res); if(status){ @@ -1504,21 +1230,6 @@ inline bool get_boot_time_str(char *bootstamp_str, std::size_t &s) //will write return true; } -//Writes the hexadecimal value of the buffer, in the wide character string. -//str must be twice length -inline void buffer_to_wide_str(const void *buf, std::size_t length, wchar_t *str) -{ - const wchar_t Characters [] = - { L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7' - , L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F' }; - std::size_t char_counter = 0; - const char *chbuf = static_cast(buf); - for(std::size_t i = 0; i != length; ++i){ - str[char_counter++] = Characters[(chbuf[i]&0xF0)>>4]; - str[char_counter++] = Characters[(chbuf[i]&0x0F)]; - } -} - inline bool get_boot_and_system_time_wstr(wchar_t *bootsystemstamp, std::size_t &s) //will write BootAndSystemstampLength chars { if(s < (BootAndSystemstampLength*2)) @@ -1528,8 +1239,14 @@ inline bool get_boot_and_system_time_wstr(wchar_t *bootsystemstamp, std::size_t if(!ret){ return false; } - - buffer_to_wide_str(&info.Reserved1[0], BootAndSystemstampLength, bootsystemstamp); + const wchar_t Characters [] = + { L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7' + , L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F' }; + std::size_t char_counter = 0; + for(std::size_t i = 0; i != static_cast(BootAndSystemstampLength); ++i){ + bootsystemstamp[char_counter++] = Characters[(info.Reserved1[i]&0xF0)>>4]; + bootsystemstamp[char_counter++] = Characters[(info.Reserved1[i]&0x0F)]; + } s = BootAndSystemstampLength*2; return true; } @@ -1537,23 +1254,9 @@ inline bool get_boot_and_system_time_wstr(wchar_t *bootsystemstamp, std::size_t class handle_closer { void *handle_; - handle_closer(const handle_closer &); - handle_closer& operator=(const handle_closer &); - public: - explicit handle_closer(void *handle) : handle_(handle){} - ~handle_closer() - { close_handle(handle_); } -}; - -class eventlog_handle_closer -{ - void *handle_; - eventlog_handle_closer(const handle_closer &); - eventlog_handle_closer& operator=(const eventlog_handle_closer &); public: - explicit eventlog_handle_closer(void *handle) : handle_(handle){} - ~eventlog_handle_closer() - { CloseEventLog(handle_); } + handle_closer(void *handle) : handle_(handle){} + ~handle_closer(){ close_handle(handle_); } }; union ntquery_mem_t @@ -1562,327 +1265,216 @@ union ntquery_mem_t struct ren_t { file_rename_information_t info; - wchar_t buf[1]; + wchar_t buf[32767]; } ren; }; -class nt_query_mem_deleter +inline bool unlink_file(const char *filename) { - static const std::size_t rename_offset = offsetof(ntquery_mem_t, ren.info.FileName) - - offsetof(ntquery_mem_t, name.Name.Buffer); - // Timestamp process id atomic count - static const std::size_t rename_suffix = (SystemTimeOfDayInfoLength + sizeof(unsigned long) + sizeof(boost::uint32_t))*2; - - public: - nt_query_mem_deleter(std::size_t object_name_information_size) - : m_size(object_name_information_size + rename_offset + rename_suffix) - , m_buf(new char [m_size]) - {} - - ~nt_query_mem_deleter() - { - delete[]m_buf; - } - - void realloc_mem(std::size_t num_bytes) - { - num_bytes += rename_suffix + rename_offset; - char *buf = m_buf; - m_buf = new char[num_bytes]; - delete[]buf; - m_size = num_bytes; - } - - ntquery_mem_t *query_mem() const - { return static_cast(static_cast(m_buf)); } - - unsigned long object_name_information_size() const - { return static_cast(m_size - rename_offset - SystemTimeOfDayInfoLength*2); } + try{ + NtSetInformationFile_t pNtSetInformationFile = + (NtSetInformationFile_t)get_proc_address(get_module_handle("ntdll.dll"), "NtSetInformationFile"); + if(!pNtSetInformationFile){ + return false; + } - std::size_t file_rename_information_size() const - { return static_cast(m_size); } + NtQueryObject_t pNtQueryObject = + (NtQueryObject_t)get_proc_address(get_module_handle("ntdll.dll"), "NtQueryObject"); - private: - std::size_t m_size; - char *m_buf; -}; + //First step: Obtain a handle to the file using Win32 rules. This resolves relative paths + void *fh = create_file(filename, generic_read | delete_access, open_existing, + file_flag_backup_semantics | file_flag_delete_on_close, 0); + if(fh == invalid_handle_value){ + return false; + } -class c_heap_deleter -{ - public: - c_heap_deleter(std::size_t size) - : m_buf(::malloc(size)) - {} + handle_closer h_closer(fh); - ~c_heap_deleter() - { - if(m_buf) ::free(m_buf); - } + std::auto_ptr pmem(new ntquery_mem_t); + file_rename_information_t *pfri = (file_rename_information_t*)&pmem->ren.info; + const std::size_t RenMaxNumChars = + ((char*)pmem.get() - (char*)&pmem->ren.info.FileName[0])/sizeof(wchar_t); - void realloc_mem(std::size_t num_bytes) - { - void *buf = ::realloc(m_buf, num_bytes); - if(!buf){ - free(m_buf); - m_buf = 0; + //Obtain file name + unsigned long size; + if(pNtQueryObject(fh, object_name_information, pmem.get(), sizeof(ntquery_mem_t), &size)){ + return false; } - } - void *get() const - { return m_buf; } + //Copy filename to the rename member + std::memmove(pmem->ren.info.FileName, pmem->name.Name.Buffer, pmem->name.Name.Length); + std::size_t filename_string_length = pmem->name.Name.Length/sizeof(wchar_t); - private: - void *m_buf; -}; + //Second step: obtain the complete native-nt filename + //if(!get_file_name_from_handle_function(fh, pfri->FileName, RenMaxNumChars, filename_string_length)){ + //return 0; + //} -inline bool unlink_file(const char *filename) -{ - //Don't try to optimize doing a DeleteFile first - //as there are interactions with permissions and - //in-use files. - // - //if(!delete_file(filename)){ - // (...) - // - - //This functions tries to emulate UNIX unlink semantics in windows. - // - //- Open the file and mark the handle as delete-on-close - //- Rename the file to an arbitrary name based on a random number - //- Close the handle. If there are no file users, it will be deleted. - // Otherwise it will be used by already connected handles but the - // file name can't be used to open this file again - try{ - NtSetInformationFile_t pNtSetInformationFile = - (NtSetInformationFile_t)dll_func::get(dll_func::NtSetInformationFile); + //Add trailing mark + if((RenMaxNumChars-filename_string_length) < (SystemTimeOfDayInfoLength*2)){ + return false; + } - NtQueryObject_t pNtQueryObject = (NtQueryObject_t)dll_func::get(dll_func::NtQueryObject); + //Search '\\' character to replace it + for(std::size_t i = filename_string_length; i != 0; --filename_string_length){ + if(pmem->ren.info.FileName[--i] == L'\\') + break; + } - //First step: Obtain a handle to the file using Win32 rules. This resolves relative paths - void *fh = create_file(filename, generic_read | delete_access, open_existing, 0, 0); - if(fh == invalid_handle_value){ + //Add random number + std::size_t s = RenMaxNumChars - filename_string_length; + if(!get_boot_and_system_time_wstr(&pfri->FileName[filename_string_length], s)){ return false; } + filename_string_length += s; - handle_closer h_closer(fh); - { - //Obtain name length - unsigned long size; - const std::size_t initial_string_mem = 512u; - - nt_query_mem_deleter nt_query_mem(sizeof(ntquery_mem_t)+initial_string_mem); - //Obtain file name with guessed length - if(pNtQueryObject(fh, object_name_information, nt_query_mem.query_mem(), nt_query_mem.object_name_information_size(), &size)){ - //Obtain file name with exact length buffer - nt_query_mem.realloc_mem(size); - if(pNtQueryObject(fh, object_name_information, nt_query_mem.query_mem(), nt_query_mem.object_name_information_size(), &size)){ - return false; - } - } - ntquery_mem_t *pmem = nt_query_mem.query_mem(); - file_rename_information_t *pfri = &pmem->ren.info; - const std::size_t RenMaxNumChars = - (((char*)(pmem) + nt_query_mem.file_rename_information_size()) - (char*)&pmem->ren.info.FileName[0])/sizeof(wchar_t); - - //Copy filename to the rename member - std::memmove(pmem->ren.info.FileName, pmem->name.Name.Buffer, pmem->name.Name.Length); - std::size_t filename_string_length = pmem->name.Name.Length/sizeof(wchar_t); - - //Search '\\' character to replace from it - for(std::size_t i = filename_string_length; i != 0; --filename_string_length){ - if(pmem->ren.info.FileName[--i] == L'\\') - break; - } + //Fill rename information (FileNameLength is in bytes) + pfri->FileNameLength = static_cast(sizeof(wchar_t)*(filename_string_length)); + pfri->Replace = 1; + pfri->RootDir = 0; - //Add random number - std::size_t s = RenMaxNumChars - filename_string_length; - if(!get_boot_and_system_time_wstr(&pfri->FileName[filename_string_length], s)){ - return false; - } - filename_string_length += s; - - //Sometimes the precission of the timestamp is not enough and we need to add another random number. - //The process id (to exclude concurrent processes) and an atomic count (to exclude concurrent threads). - //should be enough - const unsigned long pid = get_current_process_id(); - buffer_to_wide_str(&pid, sizeof(pid), &pfri->FileName[filename_string_length]); - filename_string_length += sizeof(pid)*2; - - static volatile boost::uint32_t u32_count = 0; - interlocked_decrement(reinterpret_cast(&u32_count)); - buffer_to_wide_str(const_cast(&u32_count), sizeof(boost::uint32_t), &pfri->FileName[filename_string_length]); - filename_string_length += sizeof(boost::uint32_t)*2; - - //Fill rename information (FileNameLength is in bytes) - pfri->FileNameLength = static_cast(sizeof(wchar_t)*(filename_string_length)); - pfri->Replace = 1; - pfri->RootDir = 0; - - //Cange the name of the in-use file... - io_status_block_t io; - if(0 != pNtSetInformationFile(fh, &io, pfri, nt_query_mem.file_rename_information_size(), file_rename_information)){ - return false; - } - } - //...and mark it as delete-on-close - { - //Don't use pNtSetInformationFile with file_disposition_information as it can return STATUS_CANNOT_DELETE - //if the file is still mapped. Reopen it with NtOpenFile and file_delete_on_close - NtOpenFile_t pNtOpenFile = (NtOpenFile_t)dll_func::get(dll_func::NtOpenFile); - NtClose_t pNtClose = (NtClose_t)dll_func::get(dll_func::NtClose); - const wchar_t empty_str [] = L""; - unicode_string_t ustring = { sizeof(empty_str) - sizeof (wchar_t) //length in bytes without null - , sizeof(empty_str) //total size in bytes of memory allocated for Buffer. - , const_cast(empty_str) - }; - object_attributes_t object_attr; - initialize_object_attributes(&object_attr, &ustring, 0, fh, 0); - void* fh2 = 0; - io_status_block_t io; - pNtOpenFile( &fh2, delete_flag, &object_attr, &io - , file_share_read | file_share_write | file_share_delete, file_delete_on_close); - pNtClose(fh2); - //Even if NtOpenFile fails, the file was renamed and the original no longer exists, so return a success status - return true; + //Final step: change the name of the in-use file: + io_status_block_t io; + if(0 != pNtSetInformationFile(fh, &io, pfri, sizeof(ntquery_mem_t::ren_t), file_rename_information)){ + return false; } + return true; } catch(...){ return false; } - return true; } struct reg_closer { + RegCloseKey_t func_; void *key_; - reg_closer(void *key) : key_(key){} - ~reg_closer(){ reg_close_key(key_); } + reg_closer(RegCloseKey_t func, void *key) : func_(func), key_(key){} + ~reg_closer(){ (*func_)(key_); } }; inline void get_shared_documents_folder(std::string &s) { s.clear(); - void *key; - if (reg_open_key_ex( hkey_local_machine - , "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" - , 0 - , key_query_value - , &key) == 0){ - reg_closer key_closer(key); - - //Obtain the value - unsigned long size; - unsigned long type; - const char *const reg_value = "Common AppData"; - //long err = (*pRegQueryValue)( key, reg_value, 0, &type, 0, &size); - long err = reg_query_value_ex( key, reg_value, 0, &type, 0, &size); - if(!err){ - //Size includes terminating NULL - s.resize(size); - //err = (*pRegQueryValue)( key, reg_value, 0, &type, (unsigned char*)(&s[0]), &size); - err = reg_query_value_ex( key, reg_value, 0, &type, (unsigned char*)(&s[0]), &size); - if(!err) - s.erase(s.end()-1); - (void)err; + void *hAdvapi = load_library("Advapi32.dll"); + if (hAdvapi){ + library_unloader unloader(hAdvapi); + // Pointer to function RegOpenKeyA + RegOpenKeyEx_t pRegOpenKey = + (RegOpenKeyEx_t)get_proc_address(hAdvapi, "RegOpenKeyExA"); + if (pRegOpenKey){ + // Pointer to function RegCloseKey + RegCloseKey_t pRegCloseKey = + (RegCloseKey_t)get_proc_address(hAdvapi, "RegCloseKey"); + if (pRegCloseKey){ + // Pointer to function RegQueryValueA + RegQueryValueEx_t pRegQueryValue = + (RegQueryValueEx_t)get_proc_address(hAdvapi, "RegQueryValueExA"); + if (pRegQueryValue){ + //Open the key + void *key; + if ((*pRegOpenKey)( hkey_local_machine + , "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" + , 0 + , key_query_value + , &key) == 0){ + reg_closer key_closer(pRegCloseKey, key); + + //Obtain the value + unsigned long size; + unsigned long type; + const char *const reg_value = "Common AppData"; + long err = (*pRegQueryValue)( key, reg_value, 0, &type, 0, &size); + if(!err){ + //Size includes terminating NULL + s.resize(size); + err = (*pRegQueryValue)( key, reg_value, 0, &type, (unsigned char*)(&s[0]), &size); + if(!err) + s.erase(s.end()-1); + (void)err; + } + } + } + } } } } + inline void get_registry_value(const char *folder, const char *value_key, std::vector &s) { s.clear(); - void *key; - if (reg_open_key_ex( hkey_local_machine - , folder - , 0 - , key_query_value - , &key) == 0){ - reg_closer key_closer(key); - - //Obtain the value - unsigned long size; - unsigned long type; - const char *const reg_value = value_key; - //long err = (*pRegQueryValue)( key, reg_value, 0, &type, 0, &size); - long err = reg_query_value_ex( key, reg_value, 0, &type, 0, &size); - if(!err){ - //Size includes terminating NULL - s.resize(size); - //err = (*pRegQueryValue)( key, reg_value, 0, &type, (unsigned char*)(&s[0]), &size); - err = reg_query_value_ex( key, reg_value, 0, &type, (unsigned char*)(&s[0]), &size); - if(!err) - s.erase(s.end()-1); - (void)err; + void *hAdvapi = load_library("Advapi32.dll"); + if (hAdvapi){ + library_unloader unloader(hAdvapi); + // Pointer to function RegOpenKeyA + RegOpenKeyEx_t pRegOpenKey = + (RegOpenKeyEx_t)get_proc_address(hAdvapi, "RegOpenKeyExA"); + if (pRegOpenKey){ + // Pointer to function RegCloseKey + RegCloseKey_t pRegCloseKey = + (RegCloseKey_t)get_proc_address(hAdvapi, "RegCloseKey"); + if (pRegCloseKey){ + // Pointer to function RegQueryValueA + RegQueryValueEx_t pRegQueryValue = + (RegQueryValueEx_t)get_proc_address(hAdvapi, "RegQueryValueExA"); + if (pRegQueryValue){ + //Open the key + void *key; + if ((*pRegOpenKey)( hkey_local_machine + , folder + , 0 + , key_query_value + , &key) == 0){ + reg_closer key_closer(pRegCloseKey, key); + + //Obtain the value + unsigned long size; + unsigned long type; + const char *const reg_value = value_key; + long err = (*pRegQueryValue)( key, reg_value, 0, &type, 0, &size); + if(!err){ + //Size includes terminating NULL + s.resize(size); + err = (*pRegQueryValue)( key, reg_value, 0, &type, (unsigned char*)(&s[0]), &size); + if(!err) + s.erase(s.end()-1); + (void)err; + } + } + } + } } } } -struct co_uninitializer -{ - co_uninitializer(bool b_uninitialize) - : m_b_uninitialize(b_uninitialize) - {} - - ~co_uninitializer() - { - if(m_b_uninitialize){ - CoUninitialize(); - } - } - - private: - const bool m_b_uninitialize; -}; - -template -struct com_releaser -{ - Object *&object_; - com_releaser(Object *&object) : object_(object) {} - ~com_releaser() { object_->Release(); object_ = 0; } -}; - inline bool get_wmi_class_attribute( std::wstring& strValue, const wchar_t *wmi_class, const wchar_t *wmi_class_var) { - //See example http://msdn.microsoft.com/en-us/library/aa390423%28v=VS.85%29.aspx - // - //See BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL definition if you need to change the - //default value of this macro in your application - long co_init_ret = CoInitializeEx(0, BOOST_INTERPROCESS_WINDOWS_COINIT_MODEL); - if(co_init_ret != S_OK_BIPC && co_init_ret != S_FALSE_BIPC && co_init_ret != RPC_E_CHANGED_MODE_BIPC) - return false; - co_uninitializer co_initialize_end(co_init_ret != RPC_E_CHANGED_MODE_BIPC); - (void)co_initialize_end; - + CoInitialize(0); + bool bRet = false; - long sec_init_ret = CoInitializeSecurity - ( 0 //pVoid - ,-1 //cAuthSvc - , 0 //asAuthSvc - , 0 //pReserved1 - , RPC_C_AUTHN_LEVEL_PKT_BIPC //dwAuthnLevel - , RPC_C_IMP_LEVEL_IMPERSONATE_BIPC //dwImpLevel - , 0 //pAuthList - , EOAC_NONE_BIPC //dwCapabilities - , 0 //pReserved3 - ); - if( 0 == sec_init_ret || RPC_E_TOO_LATE_BIPC == sec_init_ret) + + if( 0 == CoInitializeSecurity( 0, -1, 0, 0, RPC_C_AUTHN_LEVEL_PKT_IG, RPC_C_IMP_LEVEL_IMPERSONATE_IG, 0, EOAC_NONE_IG, 0 ) ) { - IWbemLocator_BIPC * pIWbemLocator = 0; - const wchar_t * bstrNamespace = L"root\\cimv2"; + IWbemLocator_IG * pIWbemLocator = 0; + IWbemServices_IG * pWbemServices = 0; + IEnumWbemClassObject_IG * pEnumObject = 0; + + const wchar_t * bstrNamespace = L"root\\cimv2"; + if( 0 != CoCreateInstance( CLSID_WbemAdministrativeLocator, 0, - CLSCTX_INPROC_SERVER_BIPC | CLSCTX_LOCAL_SERVER_BIPC, - IID_IUnknown, (void **)&pIWbemLocator)){ + CLSCTX_INPROC_SERVER_IG | CLSCTX_LOCAL_SERVER_IG, + IID_IUnknown, + ( void ** )&pIWbemLocator + ) + ) + { return false; } - - com_releaser IWbemLocator_releaser(pIWbemLocator); - - IWbemServices_BIPC *pWbemServices = 0; - + if( 0 != pIWbemLocator->ConnectServer( bstrNamespace, // Namespace 0, // Userid @@ -1893,74 +1485,70 @@ inline bool get_wmi_class_attribute( std::wstring& strValue, const wchar_t *wmi_ 0, // Context &pWbemServices ) - ){ - return false; - } - - if( S_OK_BIPC != CoSetProxyBlanket( - pWbemServices, - RPC_C_AUTHN_DEFAULT_BIPC, - RPC_C_AUTHZ_DEFAULT_BIPC, - 0, - RPC_C_AUTHN_LEVEL_PKT_BIPC, - RPC_C_IMP_LEVEL_IMPERSONATE_BIPC, - 0, - EOAC_NONE_BIPC - ) - ){ + ) + { + pIWbemLocator->Release(); + return false; } - - com_releaser IWbemServices_releaser(pWbemServices); - + strValue.clear(); strValue += L"Select "; strValue += wmi_class_var; strValue += L" from "; strValue += wmi_class; - IEnumWbemClassObject_BIPC * pEnumObject = 0; - if ( 0 != pWbemServices->ExecQuery( L"WQL", strValue.c_str(), - //WBEM_FLAG_RETURN_IMMEDIATELY_BIPC, - WBEM_FLAG_RETURN_WHEN_COMPLETE_BIPC | WBEM_FLAG_FORWARD_ONLY_BIPC, + WBEM_FLAG_RETURN_IMMEDIATELY_IG, 0, &pEnumObject ) - ){ + ) + { + pIWbemLocator->Release(); + pWbemServices->Release(); + + return false; + } + + unsigned long uCount = 1, uReturned; + IWbemClassObject_IG * pClassObject = 0; + + if ( 0 != pEnumObject->Reset() ) + { + pIWbemLocator->Release(); + pWbemServices->Release(); + pEnumObject->Release(); + return false; } - - com_releaser IEnumWbemClassObject_releaser(pEnumObject); - - //WBEM_FLAG_FORWARD_ONLY_BIPC incompatible with Reset - //if ( 0 != pEnumObject->Reset() ){ - //return false; - //} wchar_variant vwchar; - unsigned long uCount = 1, uReturned; - IWbemClassObject_BIPC * pClassObject = 0; - while( 0 == pEnumObject->Next( WBEM_INFINITE_BIPC, uCount, &pClassObject, &uReturned ) ) + + while( 0 == pEnumObject->Next( WBEM_INFINITE_IG, uCount, &pClassObject, &uReturned ) ) { - com_releaser IWbemClassObject_releaser(pClassObject); - if ( 0 == pClassObject->Get( L"LastBootUpTime", 0, &vwchar, 0, 0 ) ){ + if ( 0 == pClassObject->Get( L"LastBootUpTime", 0, &vwchar, 0, 0 ) ) + { bRet = true; - strValue = vwchar.value.pbstrVal; - VariantClear(&vwchar ); - break; + strValue = vwchar.value.pbstrVal; + VariantClear(&vwchar ); + break; } } + + pIWbemLocator->Release(); + pWbemServices->Release(); + pEnumObject->Release(); + pClassObject->Release(); } + + CoUninitialize(); + return bRet; } -#ifdef BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME - -//Obtains the bootup time from WMI LastBootUpTime. -//This time seems to change with hibernation and clock synchronization so avoid it. inline bool get_last_bootup_time( std::wstring& strValue ) { bool ret = get_wmi_class_attribute(strValue, L"Win32_OperatingSystem", L"LastBootUpTime"); @@ -1986,171 +1574,11 @@ inline bool get_last_bootup_time( std::string& str ) return ret; } -#else - -// Loop through the buffer and obtain the contents of the -// requested record in the buffer. -inline bool find_record_in_buffer( const void* pBuffer, unsigned long dwBytesRead, const char *provider_name - , unsigned int id_to_find, interprocess_eventlogrecord *&pevent_log_record) -{ - const unsigned char * pRecord = static_cast(pBuffer); - const unsigned char * pEndOfRecords = pRecord + dwBytesRead; - - while (pRecord < pEndOfRecords){ - interprocess_eventlogrecord *pTypedRecord = (interprocess_eventlogrecord*)pRecord; - // Check provider, written at the end of the fixed-part of the record - if (0 == std::strcmp(provider_name, (char*)(pRecord + sizeof(interprocess_eventlogrecord)))) - { - // Check event id - if(id_to_find == (pTypedRecord->EventID & 0xFFFF)){ - pevent_log_record = pTypedRecord; - return true; - } - } - - pRecord += pTypedRecord->Length; - } - pevent_log_record = 0; - return false; -} - -//Obtains the bootup time from the System Event Log, -//event ID == 6005 (event log started). -//Adapted from http://msdn.microsoft.com/en-us/library/windows/desktop/bb427356.aspx -inline bool get_last_bootup_time(std::string &stamp) -{ - const char *source_name = "System"; - const char *provider_name = "EventLog"; - const unsigned short event_id = 6005u; - - unsigned long status = 0; - unsigned long dwBytesToRead = 0; - unsigned long dwBytesRead = 0; - unsigned long dwMinimumBytesToRead = 0; - - // The source name (provider) must exist as a subkey of Application. - void *hEventLog = OpenEventLogA(0, source_name); - if (hEventLog){ - eventlog_handle_closer hnd_closer(hEventLog); (void)hnd_closer; - // Allocate an initial block of memory used to read event records. The number - // of records read into the buffer will vary depending on the size of each event. - // The size of each event will vary based on the size of the user-defined - // data included with each event, the number and length of insertion - // strings, and other data appended to the end of the event record. - dwBytesToRead = max_record_buffer_size; - c_heap_deleter heap_deleter(dwBytesToRead); - - // Read blocks of records until you reach the end of the log or an - // error occurs. The records are read from newest to oldest. If the buffer - // is not big enough to hold a complete event record, reallocate the buffer. - if (heap_deleter.get() != 0){ - while (0 == status){ - if (!ReadEventLogA(hEventLog, - eventlog_sequential_read | eventlog_backwards_read, - 0, - heap_deleter.get(), - dwBytesToRead, - &dwBytesRead, - &dwMinimumBytesToRead)) { - status = get_last_error(); - if (error_insufficient_buffer == status) { - status = 0; - dwBytesToRead = dwMinimumBytesToRead; - heap_deleter.realloc_mem(dwMinimumBytesToRead); - if (!heap_deleter.get()){ - return false; - } - } - else{ //Not found or EOF - return false; - } - } - else - { - interprocess_eventlogrecord *pTypedRecord; - // Print the contents of each record in the buffer. - if(find_record_in_buffer(heap_deleter.get(), dwBytesRead, provider_name, event_id, pTypedRecord)){ - char stamp_str[sizeof(unsigned long)*3+1]; - std::sprintf(&stamp_str[0], "%u", ((unsigned int)pTypedRecord->TimeGenerated)); - stamp = stamp_str; - break; - } - } - } - } - } - return true; -} - -#endif - -inline bool is_directory(const char *path) -{ - unsigned long attrib = GetFileAttributesA(path); - - return (attrib != invalid_file_attributes && - (attrib & file_attribute_directory)); -} - -inline bool get_file_mapping_size(void *file_mapping_hnd, __int64 &size) -{ - NtQuerySection_t pNtQuerySection = - (NtQuerySection_t)dll_func::get(dll_func::NtQuerySection); - //Obtain file name - interprocess_section_basic_information info; - unsigned long ntstatus = - pNtQuerySection(file_mapping_hnd, section_basic_information, &info, sizeof(info), 0); - size = info.section_size; - return !ntstatus; -} - -inline bool get_semaphore_info(void *handle, long &count, long &limit) -{ - winapi::interprocess_semaphore_basic_information info; - winapi::NtQuerySemaphore_t pNtQuerySemaphore = - (winapi::NtQuerySemaphore_t)dll_func::get(winapi::dll_func::NtQuerySemaphore); - unsigned int ret_len; - long status = pNtQuerySemaphore(handle, winapi::semaphore_basic_information, &info, sizeof(info), &ret_len); - count = info.count; - limit = info.limit; - return !status; -} - -inline bool query_timer_resolution(unsigned long *lowres, unsigned long *highres, unsigned long *curres) -{ - winapi::NtQueryTimerResolution_t pNtQueryTimerResolution = - (winapi::NtQueryTimerResolution_t)dll_func::get(winapi::dll_func::NtQueryTimerResolution); - return !pNtQueryTimerResolution(lowres, highres, curres); -} - -inline bool set_timer_resolution(unsigned long RequestedResolution, int Set, unsigned long* ActualResolution) -{ - winapi::NtSetTimerResolution_t pNtSetTimerResolution = - (winapi::NtSetTimerResolution_t)dll_func::get(winapi::dll_func::NtSetTimerResolution); - return !pNtSetTimerResolution(RequestedResolution, Set, ActualResolution); -} - -inline bool query_performance_counter(__int64 *lpPerformanceCount) -{ - QueryPerformanceCounter_t pQueryPerformanceCounter = (QueryPerformanceCounter_t) - dll_func::get(dll_func::QueryPerformanceCounter); - return 0 != pQueryPerformanceCounter(lpPerformanceCount); -} - -inline bool query_performance_frequency(__int64 *lpFrequency) -{ - QueryPerformanceCounter_t pQueryPerformanceFrequency = (QueryPerformanceFrequency_t) - dll_func::get(dll_func::QueryPerformanceFrequency); - return 0 != pQueryPerformanceFrequency(lpFrequency); -} - -inline unsigned long get_tick_count() -{ return GetTickCount(); } -} //namespace winapi +} //namespace winapi } //namespace interprocess -} //namespace boost +} //namespace boost #include -#endif //#ifdef BOOST_INTERPROCESS_WIN32_PRIMITIVES_HPP +#endif //#ifdef BOOST_INTERPROCESS_WIN32_SYNC_PRIMITIVES_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/windows_intermodule_singleton.hpp b/utils/boost_idb/boost/interprocess/detail/windows_intermodule_singleton.hpp deleted file mode 100644 index 946f6a7b..00000000 --- a/utils/boost_idb/boost/interprocess/detail/windows_intermodule_singleton.hpp +++ /dev/null @@ -1,309 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP -#define BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP - -#if defined(_MSC_VER)&&(_MSC_VER>=1200) -#pragma once -#endif - -#include -#include - -#if !defined(BOOST_INTERPROCESS_WINDOWS) - #error "This header can't be included from non-windows operating systems" -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace interprocess{ -namespace ipcdetail{ - -namespace intermodule_singleton_helpers { - -//This global map will be implemented using 3 sync primitives: -// -//1) A named mutex that will implement global mutual exclusion between -// threads from different modules/dlls -// -//2) A semaphore that will act as a global counter for modules attached to the global map -// so that the global map can be destroyed when the last module is detached. -// -//3) A semaphore that will be hacked to hold the address of a heap-allocated map in the -// max and current semaphore count. -class windows_semaphore_based_map -{ - typedef std::map map_type; - - public: - windows_semaphore_based_map() - { - map_type *m = new map_type; - boost::uint32_t initial_count = 0; - boost::uint32_t max_count = 0; - - //Windows user address space sizes: - //32 bit windows: [32 bit processes] 2GB or 3GB (31/32 bits) - //64 bit windows: [32 bit processes] 2GB or 4GB (31/32 bits) - // [64 bit processes] 2GB or 8TB (31/43 bits) - // - //Windows semaphores use 'long' parameters (32 bits in LLP64 data model) and - //those values can't be negative, so we have 31 bits to store something - //in max_count and initial count parameters. - //Also, max count must be bigger than 0 and bigger or equal than initial count. - if(sizeof(void*) == sizeof(boost::uint32_t)){ - //This means that for 32 bit processes, a semaphore count (31 usable bits) is - //enough to store 4 byte aligned memory (4GB -> 32 bits - 2 bits = 30 bits). - //The max count will hold the pointer value and current semaphore count - //will be zero. - // - //Relying in UB with a cast through union, but all known windows compilers - //accept this (C11 also accepts this). - union caster_union - { - void *addr; - boost::uint32_t addr_uint32; - } caster; - caster.addr = m; - //memory is at least 4 byte aligned in windows - BOOST_ASSERT((caster.addr_uint32 & boost::uint32_t(3)) == 0); - max_count = caster.addr_uint32 >> 2; - } - else if(sizeof(void*) == sizeof(boost::uint64_t)){ - //Relying in UB with a cast through union, but all known windows compilers - //accept this (C11 accepts this). - union caster_union - { - void *addr; - boost::uint64_t addr_uint64; - } caster; - caster.addr = m; - //We'll encode the address using 30 bits in each 32 bit high and low parts. - //High part will be the sem max count, low part will be the sem initial count. - //(restrictions: max count > 0, initial count >= 0 and max count >= initial count): - // - // - Low part will be shifted two times (4 byte alignment) so that top - // two bits are cleared (the top one for sign, the next one to - // assure low part value is always less than the high part value. - // - The top bit of the high part will be cleared and the next bit will be 1 - // (so high part is always bigger than low part due to the quasi-top bit). - // - // This means that the addresses we can store must be 4 byte aligned - // and less than 1 ExbiBytes ( 2^60 bytes, ~1 ExaByte). User-level address space in Windows 64 - // is much less than this (8TB, 2^43 bytes): "1 EByte (or it was 640K?) ought to be enough for anybody" ;-). - caster.addr = m; - BOOST_ASSERT((caster.addr_uint64 & boost::uint64_t(3)) == 0); - max_count = boost::uint32_t(caster.addr_uint64 >> 32); - initial_count = boost::uint32_t(caster.addr_uint64); - initial_count = initial_count/4; - //Make sure top two bits are zero - BOOST_ASSERT((max_count & boost::uint32_t(0xC0000000)) == 0); - //Set quasi-top bit - max_count |= boost::uint32_t(0x40000000); - } - bool created = false; - const permissions & perm = permissions(); - std::string pid_creation_time, name; - get_pid_creation_time_str(pid_creation_time); - name = "bipc_gmap_sem_lock_"; - name += pid_creation_time; - bool success = m_mtx_lock.open_or_create(name.c_str(), perm); - name = "bipc_gmap_sem_count_"; - name += pid_creation_time; - scoped_lock lck(m_mtx_lock); - { - success = success && m_sem_count.open_or_create - ( name.c_str(), static_cast(0), winapi_semaphore_wrapper::MaxCount, perm, created); - name = "bipc_gmap_sem_map_"; - name += pid_creation_time; - success = success && m_sem_map.open_or_create - (name.c_str(), initial_count, max_count, perm, created); - if(!success){ - delete m; - //winapi_xxx wrappers do the cleanup... - throw int(0); - } - if(!created){ - delete m; - } - else{ - BOOST_ASSERT(&get_map_unlocked() == m); - } - m_sem_count.post(); - } - } - - map_type &get_map_unlocked() - { - if(sizeof(void*) == sizeof(boost::uint32_t)){ - union caster_union - { - void *addr; - boost::uint32_t addr_uint32; - } caster; - caster.addr = 0; - caster.addr_uint32 = m_sem_map.limit(); - caster.addr_uint32 = caster.addr_uint32 << 2; - return *static_cast(caster.addr); - } - else{ - union caster_union - { - void *addr; - boost::uint64_t addr_uint64; - } caster; - boost::uint32_t max_count(m_sem_map.limit()), initial_count(m_sem_map.value()); - //Clear quasi-top bit - max_count &= boost::uint32_t(0xBFFFFFFF); - caster.addr_uint64 = max_count; - caster.addr_uint64 = caster.addr_uint64 << 32; - caster.addr_uint64 |= boost::uint64_t(initial_count) << 2; - return *static_cast(caster.addr); - } - } - - ref_count_ptr *find(const char *name) - { - scoped_lock lck(m_mtx_lock); - map_type &map = this->get_map_unlocked(); - map_type::iterator it = map.find(std::string(name)); - if(it != map.end()){ - return &it->second; - } - else{ - return 0; - } - } - - ref_count_ptr * insert(const char *name, const ref_count_ptr &ref) - { - scoped_lock lck(m_mtx_lock); - map_type &map = this->get_map_unlocked(); - map_type::iterator it = map.insert(map_type::value_type(std::string(name), ref)).first; - return &it->second; - } - - bool erase(const char *name) - { - scoped_lock lck(m_mtx_lock); - map_type &map = this->get_map_unlocked(); - return map.erase(std::string(name)) != 0; - } - - template - void atomic_func(F &f) - { - scoped_lock lck(m_mtx_lock); - f(); - } - - ~windows_semaphore_based_map() - { - scoped_lock lck(m_mtx_lock); - m_sem_count.wait(); - if(0 == m_sem_count.value()){ - map_type &map = this->get_map_unlocked(); - BOOST_ASSERT(map.empty()); - delete ↦ - } - //First close sems to protect this with the external mutex - m_sem_map.close(); - m_sem_count.close(); - //Once scoped_lock unlocks the mutex, the destructor will close the handle... - } - - private: - winapi_mutex_wrapper m_mtx_lock; - winapi_semaphore_wrapper m_sem_map; - winapi_semaphore_wrapper m_sem_count; -}; - -template<> -struct thread_safe_global_map_dependant -{ - static void apply_gmem_erase_logic(const char *, const char *){} - - static bool remove_old_gmem() - { return true; } - - struct lock_file_logic - { - lock_file_logic(windows_semaphore_based_map &) - : retry_with_new_map(false) - {} - - void operator()(void){} - bool retry() const { return retry_with_new_map; } - private: - const bool retry_with_new_map; - }; - - static void construct_map(void *addr) - { - ::new (addr)windows_semaphore_based_map; - } - - struct unlink_map_logic - { - unlink_map_logic(windows_semaphore_based_map &) - {} - void operator()(){} - }; - - static ref_count_ptr *find(windows_semaphore_based_map &map, const char *name) - { - return map.find(name); - } - - static ref_count_ptr * insert(windows_semaphore_based_map &map, const char *name, const ref_count_ptr &ref) - { - return map.insert(name, ref); - } - - static bool erase(windows_semaphore_based_map &map, const char *name) - { - return map.erase(name); - } - - template - static void atomic_func(windows_semaphore_based_map &map, F &f) - { - map.atomic_func(f); - } -}; - -} //namespace intermodule_singleton_helpers { - -template -class windows_intermodule_singleton - : public intermodule_singleton_impl - < C - , LazyInit - , Phoenix - , intermodule_singleton_helpers::windows_semaphore_based_map - > -{}; - -} //namespace ipcdetail{ -} //namespace interprocess{ -} //namespace boost{ - -#include - -#endif //#ifndef BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/workaround.hpp b/utils/boost_idb/boost/interprocess/detail/workaround.hpp index 6ce2ea1c..cb3d4a5a 100644 --- a/utils/boost_idb/boost/interprocess/detail/workaround.hpp +++ b/utils/boost_idb/boost/interprocess/detail/workaround.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -13,53 +13,43 @@ #include -#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) - #define BOOST_INTERPROCESS_WINDOWS - #define BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION - #define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME - //Define this to connect with shared memory created with versions < 1.54 - //#define BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME -#else - #include +#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) - #if defined(_POSIX_THREAD_PROCESS_SHARED) && ((_POSIX_THREAD_PROCESS_SHARED - 0) > 0) - //Cygwin defines _POSIX_THREAD_PROCESS_SHARED but does not implement it. - #if defined(__CYGWIN__) - #define BOOST_INTERPROCESS_BUGGY_POSIX_PROCESS_SHARED - //Mac Os X < Lion (10.7) might define _POSIX_THREAD_PROCESS_SHARED but there is no real support. - #elif defined(__APPLE__) - #include "TargetConditionals.h" - //Check we're on Mac OS target - #if defined(TARGET_OS_MAC) - #include "AvailabilityMacros.h" - //If minimum target for this compilation is older than Mac Os Lion, then we are out of luck - #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 - #define BOOST_INTERPROCESS_BUGGY_POSIX_PROCESS_SHARED - #endif - #endif - #endif +#define BOOST_INTERPROCESS_WINDOWS - //If buggy _POSIX_THREAD_PROCESS_SHARED is detected avoid using it - #if defined(BOOST_INTERPROCESS_BUGGY_POSIX_PROCESS_SHARED) - #undef BOOST_INTERPROCESS_BUGGY_POSIX_PROCESS_SHARED - #else - #define BOOST_INTERPROCESS_POSIX_PROCESS_SHARED - #endif - #endif +/* +#if !defined(_MSC_EXTENSIONS) +#error "Turn on Microsoft language extensions (_MSC_EXTENSIONS) to be able to call Windows API functions" +#endif +*/ - #if defined(_POSIX_BARRIERS) && ((_POSIX_BARRIERS - 0) > 0) - #define BOOST_INTERPROCESS_POSIX_BARRIERS - #endif +#endif - #if defined(_POSIX_SEMAPHORES) && ((_POSIX_SEMAPHORES - 0) > 0) - #define BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES - #if defined(__CYGWIN__) - #define BOOST_INTERPROCESS_POSIX_SEMAPHORES_NO_UNLINK - #endif +#if !(defined BOOST_INTERPROCESS_WINDOWS) + + #include + + #if ((_POSIX_THREAD_PROCESS_SHARED - 0) > 0) + //Cygwin defines _POSIX_THREAD_PROCESS_SHARED but does not implement it. + //Mac Os X >= Leopard defines _POSIX_THREAD_PROCESS_SHARED but does not seems to work. + # if !defined(__CYGWIN__) && !defined(__APPLE__) + # define BOOST_INTERPROCESS_POSIX_PROCESS_SHARED + # endif + #endif + + #if ((_POSIX_BARRIERS - 0) > 0) + # define BOOST_INTERPROCESS_POSIX_BARRIERS + # endif + + #if ((_POSIX_SEMAPHORES - 0) > 0) + # define BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES + # if defined(__CYGWIN__) + #define BOOST_INTERPROCESS_POSIX_SEMAPHORES_NO_UNLINK + # endif //Some platforms have a limited (name length) named semaphore support #elif (defined(__FreeBSD__) && (__FreeBSD__ >= 4)) || defined(__APPLE__) - #define BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES - #endif + # define BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES + #endif #if ((defined _V6_ILP32_OFFBIG) &&(_V6_ILP32_OFFBIG - 0 > 0)) ||\ ((defined _V6_LP64_OFF64) &&(_V6_LP64_OFF64 - 0 > 0)) ||\ @@ -70,123 +60,82 @@ ((defined _FILE_OFFSET_BITS) &&(_FILE_OFFSET_BITS - 0 >= 64))||\ ((defined _FILE_OFFSET_BITS) &&(_FILE_OFFSET_BITS - 0 >= 64)) #define BOOST_INTERPROCESS_UNIX_64_BIT_OR_BIGGER_OFF_T + #else #endif //Check for XSI shared memory objects. They are available in nearly all UNIX platforms #if !defined(__QNXNTO__) - #define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS + # define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS #endif - #if defined(_POSIX_SHARED_MEMORY_OBJECTS) && ((_POSIX_SHARED_MEMORY_OBJECTS - 0) > 0) - #define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS + #if ((_POSIX_SHARED_MEMORY_OBJECTS - 0) > 0) + # define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS #else - //VMS and MACOS don't define it but they have shm_open/close interface - #if defined(__vms) - #if __CRTL_VER >= 70200000 - #define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS - #endif - //Mac OS has some non-conformant features like names limited to SHM_NAME_MAX - #elif defined (__APPLE__) - //#define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS - //#define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS_NO_GROW - #endif + //VMS and MACOS don't define it but the have shm_open/close interface + # if defined(__vms) + # if __CRTL_VER >= 70200000 + # define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS + # endif + //Mac OS has some non-conformant features like names limited to SHM_NAME_MAX + # elif defined (__APPLE__) +// # define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS +// # define BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS_NO_GROW + # endif #endif //Now check if we have only XSI shared memory #if defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) &&\ !defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS) - //#define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS_ONLY + //# define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS_ONLY #endif - #if defined(_POSIX_TIMEOUTS) && ((_POSIX_TIMEOUTS - 0) > 0) - #define BOOST_INTERPROCESS_POSIX_TIMEOUTS - #endif + #if ((_POSIX_TIMEOUTS - 0) > 0) + # define BOOST_INTERPROCESS_POSIX_TIMEOUTS + #endif + #ifdef BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS //Some systems have filesystem-based resources, so the //portable "/shmname" format does not work due to permission issues //For those systems we need to form a path to a temporary directory: // hp-ux tru64 vms freebsd - #if defined(__hpux) || defined(__osf__) || defined(__vms) || (defined(__FreeBSD__) && (__FreeBSD__ < 7)) - #define BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY - //Some systems have "jailed" environments where shm usage is restricted at runtime - //and temporary file file based shm is possible in those executions. + #if defined(__hpux) || defined(__osf__) || defined(__vms) || (defined(__FreeBSD__) && (__FreeBSD__ < 7)) + #define BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY #elif defined(__FreeBSD__) - #define BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY + #define BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY #endif #endif #ifdef BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES #if defined(__osf__) || defined(__vms) - #define BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SEMAPHORES + #define BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SEMAPHORES #endif #endif - #if defined(_POSIX_VERSION) && defined(_XOPEN_VERSION) && \ - (((_POSIX_VERSION + 0)>= 200112L || (_XOPEN_VERSION + 0)>= 500)) - #define BOOST_INTERPROCESS_POSIX_RECURSIVE_MUTEXES + #if ((_POSIX_VERSION + 0)>= 200112L || (_XOPEN_VERSION + 0)>= 500) + #define BOOST_INTERPROCESS_POSIX_RECURSIVE_MUTEXES #endif - #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) - #define BOOST_INTERPROCESS_BSD_DERIVATIVE - //Some *BSD systems (OpenBSD & NetBSD) need sys/param.h before sys/sysctl.h, whereas - //others (FreeBSD & Darwin) need sys/types.h - #include - #include - #include - #if defined(CTL_KERN) && defined (KERN_BOOTTIME) - //#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME - #endif - #endif -#endif //!defined(BOOST_INTERPROCESS_WINDOWS) +#endif -#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - #define BOOST_INTERPROCESS_PERFECT_FORWARDING +#if !defined(BOOST_NO_RVALUE_REFERENCES) && !defined(BOOST_NO_VARIADIC_TEMPLATES)\ + && !defined(BOOST_INTERPROCESS_DISABLE_VARIADIC_TMPL) +#define BOOST_INTERPROCESS_PERFECT_FORWARDING #endif //Now declare some Boost.Interprocess features depending on the implementation + #if defined(BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES) && !defined(BOOST_INTERPROCESS_POSIX_SEMAPHORES_NO_UNLINK) - #define BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES - #define BOOST_INTERPROCESS_NAMED_SEMAPHORE_USES_POSIX_SEMAPHORES -#endif -// Timeout duration use if BOOST_INTERPROCESS_ENABLE_TIMEOUT_WHEN_LOCKING is set -#ifndef BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS - #define BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS 10000 -#endif +#define BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES -//Other switches -//BOOST_INTERPROCESS_MSG_QUEUE_USES_CIRC_INDEX -//message queue uses a circular queue as index instead of an array (better performance) -//Boost version < 1.52 uses an array, so undef this if you want to communicate -//with processes compiled with those versions. -#define BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX - -//Inline attributes -#if defined(_MSC_VER) - #define BOOST_INTERPROCESS_ALWAYS_INLINE __forceinline -#elif defined (__GNUC__) - #define BOOST_INTERPROCESS_ALWAYS_INLINE __attribute__((__always_inline__)) -#else - #define BOOST_INTERPROCESS_ALWAYS_INLINE inline #endif -#if defined(_MSC_VER) - #define BOOST_INTERPROCESS_NEVER_INLINE __declspec(noinline) -#elif defined (__GNUC__) - #define BOOST_INTERPROCESS_NEVER_INLINE __attribute__((__noinline__)) -#endif +#if defined(BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES) && !defined(BOOST_INTERPROCESS_POSIX_SEMAPHORES_NO_UNLINK) + +#define BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES +#define BOOST_INTERPROCESS_NAMED_SEMAPHORE_USES_POSIX_SEMAPHORES -#if defined(BOOST_NO_CXX11_NOEXCEPT) - #if defined(BOOST_MSVC) - #define BOOST_INTERPROCESS_NOEXCEPT throw() - #else - #define BOOST_INTERPROCESS_NOEXCEPT - #endif - #define BOOST_INTERPROCESS_NOEXCEPT_IF(x) -#else - #define BOOST_INTERPROCESS_NOEXCEPT noexcept - #define BOOST_INTERPROCESS_NOEXCEPT_IF(x) noexcept(x) #endif #include diff --git a/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory.hpp b/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory.hpp new file mode 100644 index 00000000..297e9a55 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory.hpp @@ -0,0 +1,222 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_HPP +#define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_HPP + +#include +#include +#include + +#if defined(BOOST_INTERPROCESS_WINDOWS) +#error "This header can't be used in Windows operating systems" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//!\file +//!Describes a class representing a native xsi shared memory. + +namespace boost { +namespace interprocess { + +//!A class that wraps XSI (System V) shared memory. +//!Unlike shared_memory_object, xsi_shared_memory needs a valid +//!path and a 8 bit key to identify a shared memory create +//!when all processes destroy all their xsi_shared_memory +//!objects and mapped regions for the same shared memory +//!or the processes end/crash. +//! +//!Warning: XSI shared memory and interprocess portable +//!shared memory (boost::interprocess::shared_memory_object) +//!can't communicate between them. +class xsi_shared_memory +{ + /// @cond + //Non-copyable and non-assignable + xsi_shared_memory(xsi_shared_memory &); + xsi_shared_memory &operator=(xsi_shared_memory &); + /// @endcond + + public: + BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION(xsi_shared_memory) + + //!Default constructor. + //!Represents an empty xsi_shared_memory. + xsi_shared_memory(); + + //!Creates a new XSI shared memory with a key obtained from a call to ftok (with path + //!"path" and id "id"), of size "size" and permissions "perm". + //!If the shared memory previously exists, throws an error. + xsi_shared_memory(create_only_t, const char *path, boost::uint8_t id, std::size_t size, int perm = 0666) + { this->priv_open_or_create(detail::DoCreate, path, id, perm, size); } + + //!Tries to create a new XSI shared memory with a key obtained from a call to ftok (with path + //!"path" and id "id"), of size "size" and permissions "perm". + //!If the shared memory previously exists, it tries to open it. + //!Otherwise throws an error. + xsi_shared_memory(open_or_create_t, const char *path, boost::uint8_t id, std::size_t size, int perm = 0666) + { this->priv_open_or_create(detail::DoOpenOrCreate, path, id, perm, size); } + + //!Tries to open a XSI shared memory with a key obtained from a call to ftok (with path + //!"path" and id "id") and permissions "perm". + //!If the shared memory does not previously exist, it throws an error. + xsi_shared_memory(open_only_t, const char *path, boost::uint8_t id, int perm = 0666) + { this->priv_open_or_create(detail::DoOpen, path, id, perm, 0); } + + //!Moves the ownership of "moved"'s shared memory object to *this. + //!After the call, "moved" does not represent any shared memory object. + //!Does not throw + xsi_shared_memory(BOOST_INTERPROCESS_RV_REF(xsi_shared_memory) moved) + { this->swap(moved); } + + //!Moves the ownership of "moved"'s shared memory to *this. + //!After the call, "moved" does not represent any shared memory. + //!Does not throw + xsi_shared_memory &operator=(BOOST_INTERPROCESS_RV_REF(xsi_shared_memory) moved) + { + xsi_shared_memory tmp(boost::interprocess::move(moved)); + this->swap(tmp); + return *this; + } + + //!Swaps two xsi_shared_memorys. Does not throw + void swap(xsi_shared_memory &other); + + //!Destroys *this. The shared memory won't be destroyed, just + //!this connection to it. Use remove() to destroy the shared memory. + ~xsi_shared_memory(); + + //!Returns the path used to + //!obtain the key. + const char *get_path() const; + + //!Returns the shared memory ID that + //!identifies the shared memory + int get_shmid() const; + + //!Returns access + //!permissions + int get_permissions() const; + + //!Returns the mapping handle. + //!Never throws + mapping_handle_t get_mapping_handle() const; + + //!Erases the XSI shared memory object identified by shmid + //!from the system. + //!Returns false on error. Never throws + static bool remove(int shmid); + + /// @cond + private: + + //!Closes a previously opened file mapping. Never throws. + bool priv_open_or_create( detail::create_enum_t type + , const char *filename + , boost::uint8_t id + , int perm + , std::size_t size); + int m_shmid; + /// @endcond +}; + +/// @cond + +inline xsi_shared_memory::xsi_shared_memory() + : m_shmid(-1) +{} + +inline xsi_shared_memory::~xsi_shared_memory() +{} + +inline int xsi_shared_memory::get_shmid() const +{ return m_shmid; } + +inline void xsi_shared_memory::swap(xsi_shared_memory &other) +{ + std::swap(m_shmid, other.m_shmid); +} + +inline mapping_handle_t xsi_shared_memory::get_mapping_handle() const +{ mapping_handle_t mhnd = { m_shmid, true}; return mhnd; } + +inline bool xsi_shared_memory::priv_open_or_create + (detail::create_enum_t type, const char *filename, boost::uint8_t id, int perm, std::size_t size) +{ + key_t key; + if(filename){ + key = ::ftok(filename, id); + if(((key_t)-1) == key){ + error_info err = system_error_code(); + throw interprocess_exception(err); + } + } + else{ + key = IPC_PRIVATE; + } + + perm &= 0x01FF; + int shmflg = perm; + + switch(type){ + case detail::DoOpen: + shmflg |= 0; + break; + case detail::DoCreate: + shmflg |= IPC_CREAT | IPC_EXCL; + break; + case detail::DoOpenOrCreate: + shmflg |= IPC_CREAT; + break; + default: + { + error_info err = other_error; + throw interprocess_exception(err); + } + } + + int ret = ::shmget(key, size, shmflg); + int shmid = ret; + if((type == detail::DoOpen) && (-1 != ret)){ + //Now get the size + ::shmid_ds xsi_ds; + ret = ::shmctl(ret, IPC_STAT, &xsi_ds); + size = xsi_ds.shm_segsz; + } + if(-1 == ret){ + error_info err = system_error_code(); + throw interprocess_exception(err); + } + + m_shmid = shmid; + return true; +} + +inline bool xsi_shared_memory::remove(int shmid) +{ return -1 != ::shmctl(shmid, IPC_RMID, 0); } + +///@endcond + +} //namespace interprocess { +} //namespace boost { + +#include + +#endif //BOOST_INTERPROCESS_XSI_SHARED_MEMORY_HPP diff --git a/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_device.hpp b/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_device.hpp index b2a27501..b2014c4e 100644 --- a/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_device.hpp +++ b/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_device.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -27,7 +27,7 @@ #include #include -#include +#include #include #include #include @@ -45,39 +45,42 @@ namespace interprocess { class xsi_shared_memory_device { /// @cond - BOOST_MOVABLE_BUT_NOT_COPYABLE(xsi_shared_memory_file_wrapper) + //Non-copyable and non-assignable + xsi_shared_memory_device(xsi_shared_memory_device &); + xsi_shared_memory_device &operator=(xsi_shared_memory_device &); /// @endcond public: + BOOST_INTERPROCESS_ENABLE_MOVE_EMULATION(xsi_shared_memory_device) xsi_shared_memory_device(); xsi_shared_memory_device(create_only_t, const char *name, mode_t mode, std::size_t size) - { this->priv_open_or_create_name_only(ipcdetail::DoCreate, name, mode, size); } + { this->priv_open_or_create_name_only(detail::DoCreate, name, mode, size); } xsi_shared_memory_device(open_or_create_t, const char *name, mode_t mode, std::size_t size) - { this->priv_open_or_create_name_only(ipcdetail::DoOpenOrCreate, name, mode, size); } + { this->priv_open_or_create_name_only(detail::DoOpenOrCreate, name, mode, size); } xsi_shared_memory_device(open_only_t, const char *name, mode_t mode) - { this->priv_open_or_create_name_only(ipcdetail::DoOpen, name, mode, 0); } + { this->priv_open_or_create_name_only(detail::DoOpen, name, mode, 0); } xsi_shared_memory_device(create_only_t, const char *filepath, boost::uint8_t id, mode_t mode, std::size_t size) - { this->priv_open_or_create_name_id(ipcdetail::DoCreate, name, id, mode, size); } + { this->priv_open_or_create_name_id(detail::DoCreate, name, id, mode, size); } xsi_shared_memory_device(open_or_create_t, const char *filepath, boost::uint8_t id, mode_t mode, std::size_t size) - { this->priv_open_or_create_name_id(ipcdetail::DoOpenOrCreate, id, name, mode, size); } + { this->priv_open_or_create_name_id(detail::DoOpenOrCreate, id, name, mode, size); } xsi_shared_memory_device(open_only_t, const char *filepath, boost::uint8_t id, mode_t mode) - { this->priv_open_or_create_name_id(ipcdetail::DoOpen, name, id, mode, 0); } + { this->priv_open_or_create_name_id(detail::DoOpen, name, id, mode, 0); } - xsi_shared_memory_device(BOOST_RV_REF(xsi_shared_memory_device) moved) + xsi_shared_memory_device(BOOST_INTERPROCESS_RV_REF(xsi_shared_memory_device) moved) { this->swap(moved); } - xsi_shared_memory_device &operator=(BOOST_RV_REF(xsi_shared_memory_device) moved) - { - xsi_shared_memory_device tmp(boost::move(moved)); + xsi_shared_memory_device &operator=(BOOST_INTERPROCESS_RV_REF(xsi_shared_memory_device) moved) + { + xsi_shared_memory_device tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Swaps two xsi_shared_memory_device. Does not throw @@ -135,11 +138,11 @@ class xsi_shared_memory_device static void priv_obtain_index(mapped_region &m, xsi_named_mutex &m, std::string &path); static bool priv_remove_dead_memory(info_t *info, const char *path); - bool priv_open_or_create_name_only( ipcdetail::create_enum_t type + bool priv_open_or_create_name_only( detail::create_enum_t type , const char *shmname , mode_t mode , std::size_t size); - bool priv_open_or_create_name_id( ipcdetail::create_enum_t type + bool priv_open_or_create_name_id( detail::create_enum_t type , const char *shmname , boost::uint8_t id , mode_t mode @@ -168,7 +171,7 @@ inline xsi_shared_memory_device::xsi_shared_memory_device() : m_shm(), m_mode(invalid_mode), m_name() {} -inline xsi_shared_memory_device::~xsi_shared_memory_device() +inline xsi_shared_memory_device::~xsi_shared_memory_device() {} inline const char *xsi_shared_memory_device::get_name() const @@ -178,7 +181,7 @@ inline void xsi_shared_memory_device::swap(xsi_shared_memory_device &other) { m_shm.swap(other.m_shm); std::swap(m_mode, other.m_mode); - m_name.swap(other.m_name); + m_name.swap(other.m_name); } inline mapping_handle_t xsi_shared_memory_device::get_mapping_handle() const @@ -197,15 +200,15 @@ inline void xsi_shared_memory_device::priv_obtain_index permissions p; p.set_unrestricted(); std::string xsi_shm_emulation_file_path; - ipcdetail::create_tmp_and_clean_old_and_get_filename(filename, xsi_shm_emulation_file_path); - ipcdetail::create_or_open_file(xsi_shm_emulation_file_path.c_str(), read_write, p); + detail::create_tmp_and_clean_old_and_get_filename(filename, xsi_shm_emulation_file_path); + detail::create_or_open_file(xsi_shm_emulation_file_path.c_str(), read_write, p); const std::size_t MemSize = sizeof(info_t); xsi_shared_memory index_shm(open_or_create, xsi_shm_emulation_file_path.c_str(), 1, MemSize, 0666); mapped_region r(index_shm, read_write, 0, MemSize, 0); xsi_named_mutex m(open_or_create, xsi_shm_emulation_file_path.c_str(), 2, 0666); - reg = boost::move(r); - mut = boost::move(m); + reg = boost::interprocess::move(r); + mut = boost::interprocess::move(m); path.swap(xsi_shm_emulation_file_path); } @@ -230,7 +233,7 @@ inline bool xsi_shared_memory_device::priv_remove_dead_memory } inline bool xsi_shared_memory_device::priv_open_or_create_name_id - (ipcdetail::create_enum_t type, const char *filepath, mode_t mode, std::size_t size) + (detail::create_enum_t type, const char *filepath, mode_t mode, std::size_t size) { //Set accesses if (mode != read_write && mode != read_only){ @@ -240,23 +243,23 @@ inline bool xsi_shared_memory_device::priv_open_or_create_name_id int perm = (mode == read_only) ? (0444) : (0666); - if(type == ipcdetail::DoOpen){ + if(type == detail::DoOpen){ if(!found){ error_info err = not_found_error; throw interprocess_exception(err); } xsi_shared_memory temp(open_only, filepath, id, perm); - m_shm = boost::move(temp); + m_shm = boost::interprocess::move(temp); } - else if(type == ipcdetail::DoCreate){ + else if(type == detail::DoCreate){ //Try to reuse slot xsi_shared_memory temp(create_only, filepath, id, size, perm); std::strcpy(info->names[target_entry].buf, shmname); - m_shm = boost::move(temp); + m_shm = boost::interprocess::move(temp); } - else{ // if(type == ipcdetail::DoOpenOrCreate){ + else{ // if(type == detail::DoOpenOrCreate){ xsi_shared_memory temp(open_or_create, filepath, id, size, perm); - m_shm = boost::move(temp); + m_shm = boost::interprocess::move(temp); } m_mode = mode; @@ -265,7 +268,7 @@ inline bool xsi_shared_memory_device::priv_open_or_create_name_id } inline bool xsi_shared_memory_device::priv_open_or_create_name_only - (ipcdetail::create_enum_t type, const char *shmname, mode_t mode, std::size_t size) + (detail::create_enum_t type, const char *shmname, mode_t mode, std::size_t size) { //Set accesses if (mode != read_write && mode != read_only){ @@ -311,32 +314,32 @@ inline bool xsi_shared_memory_device::priv_open_or_create_name_only } //Now handle the result int perm = (mode == read_only) ? (0444) : (0666); - if(type == ipcdetail::DoOpen){ + if(type == detail::DoOpen){ if(!found){ error_info err = not_found_error; throw interprocess_exception(err); } xsi_shared_memory temp( open_only, xsi_shm_emulation_file_path.c_str() , target_entry+info_constants_t<0>::FirstID, perm); - m_shm = boost::move(temp); + m_shm = boost::interprocess::move(temp); } else{ - if(type == ipcdetail::DoCreate){ + if(type == detail::DoCreate){ //Try to reuse slot xsi_shared_memory temp( create_only, xsi_shm_emulation_file_path.c_str() , target_entry+info_constants_t<0>::FirstID, size, perm); std::strcpy(info->names[target_entry].buf, shmname); - m_shm = boost::move(temp); + m_shm = boost::interprocess::move(temp); } - else{ // if(type == ipcdetail::DoOpenOrCreate){ + else{ // if(type == detail::DoOpenOrCreate){ xsi_shared_memory temp( open_or_create, xsi_shm_emulation_file_path.c_str() , target_entry+info_constants_t<0>::FirstID, size, perm); if(!found){ std::memset(info->names[target_entry].buf, 0, info_constants_t<0>::MaxName); std::strcpy(info->names[target_entry].buf, shmname); } - m_shm = boost::move(temp); + m_shm = boost::interprocess::move(temp); } } } diff --git a/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_file_wrapper.hpp b/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_file_wrapper.hpp deleted file mode 100644 index 51af830f..00000000 --- a/utils/boost_idb/boost/interprocess/detail/xsi_shared_memory_file_wrapper.hpp +++ /dev/null @@ -1,80 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_FILE_WRAPPER_HPP -#define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_FILE_WRAPPER_HPP - -#include -#include -#include - -#if !defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) -#error "This header can't be used in operating systems without XSI (System V) shared memory support" -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include - -//!\file -//!Describes a class representing a pseudo-file implemented on top of xsi shared memory. - -namespace boost { -namespace interprocess { - -class xsi_shared_memory_file_wrapper - : public xsi_shared_memory -{ - /// @cond - BOOST_MOVABLE_BUT_NOT_COPYABLE(xsi_shared_memory_file_wrapper) - /// @endcond - public: - - xsi_shared_memory_file_wrapper() : xsi_shared_memory() {} - - xsi_shared_memory_file_wrapper(create_only_t, const xsi_key &key, mode_t mode, std::size_t size, const permissions& perm = permissions()) - : xsi_shared_memory(create_only_t(), key, size, perm.get_permissions()) - {} - - xsi_shared_memory_file_wrapper(open_or_create_t, const xsi_key &key, mode_t mode, std::size_t size, const permissions& perm = permissions()) - : xsi_shared_memory(open_or_create_t(), key, size, perm.get_permissions()) - {} - - xsi_shared_memory_file_wrapper(open_only_t, const xsi_key &key, mode_t mode, const permissions& perm = permissions()) - : xsi_shared_memory(open_only_t(), key) - {} - - xsi_shared_memory_file_wrapper(BOOST_RV_REF(xsi_shared_memory_file_wrapper) moved) - { this->swap(moved); } - - xsi_shared_memory_file_wrapper &operator=(BOOST_RV_REF(xsi_shared_memory_file_wrapper) moved) - { - xsi_shared_memory_file_wrapper tmp(boost::move(moved)); - this->swap(tmp); - return *this; - } - - //!Swaps two xsi_shared_memory_file_wrapper. Does not throw - void swap(xsi_shared_memory_file_wrapper &other) - { this->xsi_shared_memory::swap(other); } -}; - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_XSI_SHARED_MEMORY_FILE_WRAPPER_HPP diff --git a/utils/boost_idb/boost/interprocess/errors.hpp b/utils/boost_idb/boost/interprocess/errors.hpp index 3a3bb533..5b7cd3b4 100644 --- a/utils/boost_idb/boost/interprocess/errors.hpp +++ b/utils/boost_idb/boost/interprocess/errors.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,7 +11,7 @@ ////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 Beman Dawes -// Copyright (C) 2001 Dietmar Kuehl +// Copyright (C) 2001 Dietmar Kuehl // Use, modification, and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy // at http://www.boost.org/LICENSE_1_0.txt) @@ -64,16 +64,16 @@ inline int system_error_code() // artifact of POSIX and WINDOWS error reporting inline void fill_system_message(int sys_err_code, std::string &str) { void *lpMsgBuf; - winapi::format_message( - winapi::format_message_allocate_buffer | - winapi::format_message_from_system | + winapi::format_message( + winapi::format_message_allocate_buffer | + winapi::format_message_from_system | winapi::format_message_ignore_inserts, 0, sys_err_code, winapi::make_lang_id(winapi::lang_neutral, winapi::sublang_default), // Default language reinterpret_cast(&lpMsgBuf), 0, - 0 + 0 ); str += static_cast(lpMsgBuf); winapi::local_free( lpMsgBuf ); // free the buffer @@ -112,9 +112,7 @@ enum error_code_t size_error, corrupted_error, not_such_file_or_directory, - invalid_argument, - timeout_when_locking_error, - timeout_when_waiting_error + invalid_argument }; typedef int native_error_t; @@ -123,7 +121,7 @@ typedef int native_error_t; struct ec_xlate { native_error_t sys_ec; - error_code_t ec; + error_code_t ec; }; static const ec_xlate ec_table[] = @@ -159,8 +157,7 @@ static const ec_xlate ec_table[] = { /*ERROR_DISK_FULL*/112L, out_of_space_error }, { /*ERROR_OUTOFMEMORY*/14L, out_of_memory_error }, { /*ERROR_NOT_ENOUGH_MEMORY*/8L, out_of_memory_error }, - { /*ERROR_TOO_MANY_OPEN_FILES*/4L, out_of_resource_error }, - { /*ERROR_INVALID_ADDRESS*/487L, busy_error } + { /*ERROR_TOO_MANY_OPEN_FILES*/4L, out_of_resource_error } #else //#if (defined BOOST_INTERPROCESS_WINDOWS) { EACCES, security_error }, { EROFS, read_only_error }, @@ -183,9 +180,9 @@ static const ec_xlate ec_table[] = }; inline error_code_t lookup_error(native_error_t err) -{ +{ const ec_xlate *cur = &ec_table[0], - *end = cur + sizeof(ec_table)/sizeof(ec_xlate); + *end = cur + sizeof(ec_table)/sizeof(ec_xlate); for (;cur != end; ++cur ){ if ( err == cur->sys_ec ) return cur->ec; } diff --git a/utils/boost_idb/boost/interprocess/exceptions.hpp b/utils/boost_idb/boost/interprocess/exceptions.hpp index b9ab45be..5fd894cb 100644 --- a/utils/boost_idb/boost/interprocess/exceptions.hpp +++ b/utils/boost_idb/boost/interprocess/exceptions.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/utils/boost_idb/boost/interprocess/file_mapping.hpp b/utils/boost_idb/boost/interprocess/file_mapping.hpp index e894d402..c3cfa191 100644 --- a/utils/boost_idb/boost/interprocess/file_mapping.hpp +++ b/utils/boost_idb/boost/interprocess/file_mapping.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include //std::string //!\file @@ -33,7 +33,7 @@ namespace interprocess { class file_mapping { /// @cond - BOOST_MOVABLE_BUT_NOT_COPYABLE(file_mapping) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(file_mapping) /// @endcond public: @@ -41,28 +41,27 @@ class file_mapping //!Does not throw file_mapping(); - //!Opens a file mapping of file "filename", starting in offset - //!"file_offset", and the mapping's size will be "size". The mapping + //!Opens a file mapping of file "filename", starting in offset + //!"file_offset", and the mapping's size will be "size". The mapping //!can be opened for read-only "read_only" or read-write "read_write" //!modes. Throws interprocess_exception on error. file_mapping(const char *filename, mode_t mode); - //!Moves the ownership of "moved"'s file mapping object to *this. - //!After the call, "moved" does not represent any file mapping object. + //!Moves the ownership of "moved"'s file mapping object to *this. + //!After the call, "moved" does not represent any file mapping object. //!Does not throw - file_mapping(BOOST_RV_REF(file_mapping) moved) - : m_handle(file_handle_t(ipcdetail::invalid_file())) - , m_mode(read_only) + file_mapping(BOOST_INTERPROCESS_RV_REF(file_mapping) moved) + : m_handle(file_handle_t(detail::invalid_file())) { this->swap(moved); } //!Moves the ownership of "moved"'s file mapping to *this. - //!After the call, "moved" does not represent any file mapping. + //!After the call, "moved" does not represent any file mapping. //!Does not throw - file_mapping &operator=(BOOST_RV_REF(file_mapping) moved) + file_mapping &operator=(BOOST_INTERPROCESS_RV_REF(file_mapping) moved) { - file_mapping tmp(boost::move(moved)); + file_mapping tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Swaps to file_mappings. @@ -96,31 +95,30 @@ class file_mapping //!Closes a previously opened file mapping. Never throws. void priv_close(); file_handle_t m_handle; - mode_t m_mode; - std::string m_filename; + mode_t m_mode; + std::string m_filename; /// @endcond }; -inline file_mapping::file_mapping() - : m_handle(file_handle_t(ipcdetail::invalid_file())) - , m_mode(read_only) +inline file_mapping::file_mapping() + : m_handle(file_handle_t(detail::invalid_file())) {} -inline file_mapping::~file_mapping() +inline file_mapping::~file_mapping() { this->priv_close(); } inline const char *file_mapping::get_name() const { return m_filename.c_str(); } inline void file_mapping::swap(file_mapping &other) -{ +{ std::swap(m_handle, other.m_handle); std::swap(m_mode, other.m_mode); - m_filename.swap(other.m_filename); + m_filename.swap(other.m_filename); } inline mapping_handle_t file_mapping::get_mapping_handle() const -{ return ipcdetail::mapping_handle_from_file_handle(m_handle); } +{ return detail::mapping_handle_from_file_handle(m_handle); } inline mode_t file_mapping::get_mode() const { return m_mode; } @@ -136,10 +134,10 @@ inline file_mapping::file_mapping } //Open file - m_handle = ipcdetail::open_existing_file(filename, mode); + m_handle = detail::open_existing_file(filename, mode); //Check for error - if(m_handle == ipcdetail::invalid_file()){ + if(m_handle == detail::invalid_file()){ error_info err = system_error_code(); this->priv_close(); throw interprocess_exception(err); @@ -148,15 +146,15 @@ inline file_mapping::file_mapping } inline bool file_mapping::remove(const char *filename) -{ return ipcdetail::delete_file(filename); } +{ return detail::delete_file(filename); } ///@cond inline void file_mapping::priv_close() { - if(m_handle != ipcdetail::invalid_file()){ - ipcdetail::close_file(m_handle); - m_handle = ipcdetail::invalid_file(); + if(m_handle != detail::invalid_file()){ + detail::close_file(m_handle); + m_handle = detail::invalid_file(); } } @@ -175,7 +173,7 @@ class remove_file_on_destroy {} ~remove_file_on_destroy() - { ipcdetail::delete_file(m_name); } + { detail::delete_file(m_name); } }; } //namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/indexes/flat_map_index.hpp b/utils/boost_idb/boost/interprocess/indexes/flat_map_index.hpp index 52bf88ac..8caa7da6 100644 --- a/utils/boost_idb/boost/interprocess/indexes/flat_map_index.hpp +++ b/utils/boost_idb/boost/interprocess/indexes/flat_map_index.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -63,7 +63,7 @@ class flat_map_index {} //!This reserves memory to optimize the insertion of n elements in the index - void reserve(typename segment_manager_base::size_type n) + void reserve(std::size_t n) { base_type::reserve(n); } //!This frees all unnecessary memory diff --git a/utils/boost_idb/boost/interprocess/indexes/iset_index.hpp b/utils/boost_idb/boost/interprocess/indexes/iset_index.hpp index b1abeded..df1aeb57 100644 --- a/utils/boost_idb/boost/interprocess/indexes/iset_index.hpp +++ b/utils/boost_idb/boost/interprocess/indexes/iset_index.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -34,17 +34,17 @@ namespace interprocess { template struct iset_index_aux { - typedef typename + typedef typename MapConfig::segment_manager_base segment_manager_base; - typedef typename + typedef typename segment_manager_base::void_pointer void_pointer; typedef typename bi::make_set_base_hook < bi::void_pointer , bi::optimize_size >::type derivation_hook; - typedef typename MapConfig::template + typedef typename MapConfig::template intrusive_value_type::type value_type; typedef std::less value_compare; typedef typename bi::make_set @@ -82,20 +82,20 @@ class iset_index struct intrusive_key_value_less { bool operator()(const intrusive_compare_key_type &i, const value_type &b) const - { + { std::size_t blen = b.name_length(); - return (i.m_len < blen) || - (i.m_len == blen && - std::char_traits::compare + return (i.m_len < blen) || + (i.m_len == blen && + std::char_traits::compare (i.mp_str, b.name(), i.m_len) < 0); } bool operator()(const value_type &b, const intrusive_compare_key_type &i) const - { + { std::size_t blen = b.name_length(); - return (blen < i.m_len) || + return (blen < i.m_len) || (blen == i.m_len && - std::char_traits::compare + std::char_traits::compare (b.name(), i.mp_str, i.m_len) < 0); } }; @@ -112,7 +112,7 @@ class iset_index //!This reserves memory to optimize the insertion of n //!elements in the index - void reserve(typename MapConfig::segment_manager_base::size_type) + void reserve(std::size_t) { /*Does nothing, map has not reserve or rehash*/ } //!This frees all unnecessary memory @@ -138,12 +138,12 @@ template struct is_intrusive_index > { - static const bool value = true; + enum{ value = true }; }; /// @endcond } //namespace interprocess { -} //namespace boost +} //namespace boost #include diff --git a/utils/boost_idb/boost/interprocess/indexes/iunordered_set_index.hpp b/utils/boost_idb/boost/interprocess/indexes/iunordered_set_index.hpp index a23c8461..1db07c88 100644 --- a/utils/boost_idb/boost/interprocess/indexes/iunordered_set_index.hpp +++ b/utils/boost_idb/boost/interprocess/indexes/iunordered_set_index.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #include #include - +#include #include #include #include @@ -35,17 +35,17 @@ namespace boost { namespace interprocess { template struct iunordered_set_index_aux { - typedef typename + typedef typename MapConfig::segment_manager_base segment_manager_base; - typedef typename + typedef typename segment_manager_base::void_pointer void_pointer; typedef typename bi::make_unordered_set_base_hook < bi::void_pointer >::type derivation_hook; - typedef typename MapConfig::template + typedef typename MapConfig::template intrusive_value_type::type value_type; typedef typename MapConfig:: @@ -58,23 +58,23 @@ struct iunordered_set_index_aux struct equal_function { bool operator()(const intrusive_compare_key_type &i, const value_type &b) const - { + { return (i.m_len == b.name_length()) && - (std::char_traits::compare + (std::char_traits::compare (i.mp_str, b.name(), i.m_len) == 0); } bool operator()(const value_type &b, const intrusive_compare_key_type &i) const - { + { return (i.m_len == b.name_length()) && - (std::char_traits::compare + (std::char_traits::compare (i.mp_str, b.name(), i.m_len) == 0); } bool operator()(const value_type &b1, const value_type &b2) const - { + { return (b1.name_length() == b2.name_length()) && - (std::char_traits::compare + (std::char_traits::compare (b1.name(), b2.name(), b1.name_length()) == 0); } }; @@ -84,7 +84,7 @@ struct iunordered_set_index_aux { std::size_t operator()(const value_type &val) const { - const char_type *beg = ipcdetail::to_raw_pointer(val.name()), + const char_type *beg = detail::get_pointer(val.name()), *end = beg + val.name_length(); return boost::hash_range(beg, end); } @@ -101,7 +101,6 @@ struct iunordered_set_index_aux < value_type , bi::hash , bi::equal - , bi::size_type >::type index_t; typedef typename index_t::bucket_type bucket_type; typedef allocator @@ -119,7 +118,7 @@ struct iunordered_set_index_aux /// @endcond //!Index type based in boost::intrusive::set. -//!Just derives from boost::intrusive::set +//!Just derives from boost::intrusive::set //!and defines the interface needed by managed memory segments template class iunordered_set_index @@ -135,9 +134,9 @@ class iunordered_set_index typedef typename index_aux::equal_function equal_function; typedef typename index_aux::hash_function hash_function; typedef typename MapConfig::char_type char_type; - typedef typename + typedef typename iunordered_set_index_aux::allocator_type allocator_type; - typedef typename + typedef typename iunordered_set_index_aux::allocator_holder allocator_holder; /// @endcond @@ -156,33 +155,33 @@ class iunordered_set_index typedef typename index_aux:: segment_manager_base segment_manager_base; - static const std::size_t InitBufferSize = 64; + enum { InitBufferSize = 64}; - static bucket_ptr create_buckets(allocator_type &alloc, size_type num) + static bucket_ptr create_buckets(allocator_type &alloc, std::size_t num) { num = index_type::suggested_upper_bucket_count(num); bucket_ptr buckets = alloc.allocate(num); bucket_ptr buckets_init = buckets; - for(size_type i = 0; i < num; ++i){ - new(to_raw_pointer(buckets_init++))bucket_type(); + for(std::size_t i = 0; i < num; ++i){ + new(get_pointer(buckets_init++))bucket_type(); } return buckets; } - static size_type shrink_buckets - ( bucket_ptr buckets, size_type old_size - , allocator_type &alloc, size_type new_size) + static std::size_t shrink_buckets + ( bucket_ptr buckets, std::size_t old_size + , allocator_type &alloc, std::size_t new_size) { if(old_size <= new_size ) return old_size; - size_type received_size; + std::size_t received_size; if(!alloc.allocation_command (boost::interprocess::try_shrink_in_place | boost::interprocess::nothrow_allocation, old_size, new_size, received_size, buckets).first){ return old_size; } - for( bucket_type *p = ipcdetail::to_raw_pointer(buckets) + received_size - , *pend = ipcdetail::to_raw_pointer(buckets) + old_size + for( bucket_type *p = detail::get_pointer(buckets) + received_size + , *pend = detail::get_pointer(buckets) + old_size ; p != pend ; ++p){ p->~bucket_type(); @@ -190,33 +189,33 @@ class iunordered_set_index bucket_ptr shunk_p = alloc.allocation_command (boost::interprocess::shrink_in_place | boost::interprocess::nothrow_allocation, received_size, received_size, received_size, buckets).first; - BOOST_ASSERT(buckets == shunk_p); (void)shunk_p; + BOOST_ASSERT(buckets == shunk_p); bucket_ptr buckets_init = buckets + received_size; - for(size_type i = 0; i < (old_size - received_size); ++i){ - to_raw_pointer(buckets_init++)->~bucket_type(); + for(std::size_t i = 0; i < (old_size - received_size); ++i){ + get_pointer(buckets_init++)->~bucket_type(); } return received_size; } static bucket_ptr expand_or_create_buckets - ( bucket_ptr old_buckets, const size_type old_num - , allocator_type &alloc, const size_type new_num) + ( bucket_ptr old_buckets, const std::size_t old_num + , allocator_type &alloc, const std::size_t new_num) { - size_type received_size; + std::size_t received_size; std::pair ret = alloc.allocation_command (boost::interprocess::expand_fwd | boost::interprocess::allocate_new, new_num, new_num, received_size, old_buckets); if(ret.first == old_buckets){ bucket_ptr buckets_init = old_buckets + old_num; - for(size_type i = 0; i < (new_num - old_num); ++i){ - new(to_raw_pointer(buckets_init++))bucket_type(); + for(std::size_t i = 0; i < (new_num - old_num); ++i){ + new(get_pointer(buckets_init++))bucket_type(); } } else{ bucket_ptr buckets_init = ret.first; - for(size_type i = 0; i < new_num; ++i){ - new(to_raw_pointer(buckets_init++))bucket_type(); + for(std::size_t i = 0; i < new_num; ++i){ + new(get_pointer(buckets_init++))bucket_type(); } } @@ -224,11 +223,11 @@ class iunordered_set_index } static void destroy_buckets - (allocator_type &alloc, bucket_ptr buckets, size_type num) + (allocator_type &alloc, bucket_ptr buckets, std::size_t num) { bucket_ptr buckets_destroy = buckets; - for(size_type i = 0; i < num; ++i){ - to_raw_pointer(buckets_destroy++)->~bucket_type(); + for(std::size_t i = 0; i < num; ++i){ + get_pointer(buckets_destroy++)->~bucket_type(); } alloc.deallocate(buckets, num); } @@ -256,7 +255,7 @@ class iunordered_set_index //!This reserves memory to optimize the insertion of n //!elements in the index - void reserve(size_type new_n) + void reserve(std::size_t new_n) { //Let's maintain a 1.0f load factor size_type old_n = this->bucket_count(); @@ -290,7 +289,7 @@ class iunordered_set_index size_type cur_size = this->size(); size_type cur_count = this->bucket_count(); bucket_ptr old_p = this->bucket_pointer(); - + if(!this->size() && old_p != bucket_ptr(&this->init_bucket)){ this->rehash(bucket_traits(bucket_ptr(&this->init_bucket), 1)); destroy_buckets(this->alloc, old_p, cur_count); @@ -337,7 +336,7 @@ class iunordered_set_index //Strong guarantee: if something goes wrong //we should remove the insertion. // - //We can use the iterator because the hash function + //We can use the iterator because the hash function //can't throw and this means that "reserve" will //throw only because of the memory allocation: //the iterator has not been invalidated. @@ -357,7 +356,7 @@ template struct is_intrusive_index > { - static const bool value = true; + enum{ value = true }; }; /// @endcond diff --git a/utils/boost_idb/boost/interprocess/indexes/map_index.hpp b/utils/boost_idb/boost/interprocess/indexes/map_index.hpp index 409e4c97..baf0403a 100644 --- a/utils/boost_idb/boost/interprocess/indexes/map_index.hpp +++ b/utils/boost_idb/boost/interprocess/indexes/map_index.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -25,7 +25,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ //!Helper class to define typedefs from IndexTraits template @@ -46,17 +46,17 @@ struct map_index_aux key_less, allocator_type> index_t; }; -} //namespace ipcdetail { +} //namespace detail { -//!Index type based in boost::interprocess::map. Just derives from boost::interprocess::map +//!Index type based in boost::interprocess::map. Just derives from boost::interprocess::map //!and defines the interface needed by managed memory segments template class map_index //Derive class from map specialization - : public ipcdetail::map_index_aux::index_t + : public detail::map_index_aux::index_t { /// @cond - typedef ipcdetail::map_index_aux index_aux; + typedef detail::map_index_aux index_aux; typedef typename index_aux::index_t base_type; typedef typename MapConfig:: segment_manager_base segment_manager_base; @@ -71,7 +71,7 @@ class map_index //!This reserves memory to optimize the insertion of n //!elements in the index - void reserve(typename segment_manager_base::size_type) + void reserve(std::size_t) { /*Does nothing, map has not reserve or rehash*/ } //!This tries to free previously allocate @@ -89,7 +89,7 @@ template struct is_node_index > { - static const bool value = true; + enum { value = true }; }; /// @endcond diff --git a/utils/boost_idb/boost/interprocess/indexes/null_index.hpp b/utils/boost_idb/boost/interprocess/indexes/null_index.hpp index 1e1d670d..dc3a623d 100644 --- a/utils/boost_idb/boost/interprocess/indexes/null_index.hpp +++ b/utils/boost_idb/boost/interprocess/indexes/null_index.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,7 @@ #include //!\file -//!Describes a null index adaptor, so that if we don't want to construct +//!Describes a null index adaptor, so that if we don't want to construct //!named objects, we can use this null index type to save resources. namespace boost { diff --git a/utils/boost_idb/boost/interprocess/indexes/unordered_map_index.hpp b/utils/boost_idb/boost/interprocess/indexes/unordered_map_index.hpp index 2fce665d..a438939c 100644 --- a/utils/boost_idb/boost/interprocess/indexes/unordered_map_index.hpp +++ b/utils/boost_idb/boost/interprocess/indexes/unordered_map_index.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -48,7 +48,7 @@ struct unordered_map_index_aux std::size_t operator()(const key_type &val) const { typedef typename key_type::char_type char_type; - const char_type *beg = ipcdetail::to_raw_pointer(val.mp_str), + const char_type *beg = detail::get_pointer(val.mp_str), *end = beg + val.m_len; return boost::hash_range(beg, end); } @@ -69,7 +69,7 @@ class unordered_map_index /// @cond typedef unordered_map_index_aux index_aux; typedef typename index_aux::index_t base_type; - typedef typename + typedef typename MapConfig::segment_manager_base segment_manager_base; /// @endcond @@ -84,7 +84,7 @@ class unordered_map_index //!This reserves memory to optimize the insertion of n //!elements in the index - void reserve(typename segment_manager_base::size_type n) + void reserve(std::size_t n) { base_type::rehash(n); } //!This tries to free previously allocate @@ -102,7 +102,7 @@ template struct is_node_index > { - static const bool value = true; + enum { value = true }; }; /// @endcond diff --git a/utils/boost_idb/boost/interprocess/interprocess_fwd.hpp b/utils/boost_idb/boost/interprocess/interprocess_fwd.hpp index 42f170a6..917f750d 100644 --- a/utils/boost_idb/boost/interprocess/interprocess_fwd.hpp +++ b/utils/boost_idb/boost/interprocess/interprocess_fwd.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -35,11 +35,21 @@ namespace interprocess{ namespace bi = boost::intrusive; }} -#include -#include -#include -#include -#include +namespace std { + +template +class allocator; + +template +struct less; + +template +struct pair; + +template +struct char_traits; + +} //namespace std { /// @endcond @@ -57,7 +67,7 @@ class permissions; class shared_memory_object; -#if defined (BOOST_INTERPROCESS_WINDOWS) || defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) +#if defined (BOOST_INTERPROCESS_WINDOWS) class windows_shared_memory; #endif //#if defined (BOOST_INTERPROCESS_WINDOWS) @@ -148,9 +158,7 @@ class cached_adaptive_pool; // offset_ptr ////////////////////////////////////////////////////////////////////////////// -static const std::size_t offset_type_alignment = 0; - -template +template class offset_ptr; ////////////////////////////////////////////////////////////////////////////// @@ -214,7 +222,7 @@ template class IndexType> class basic_managed_shared_memory; -typedef basic_managed_shared_memory +typedef basic_managed_shared_memory ,iset_index> @@ -231,14 +239,14 @@ wmanaged_shared_memory; // Windows shared memory managed memory classes ////////////////////////////////////////////////////////////////////////////// -#if defined (BOOST_INTERPROCESS_WINDOWS) || defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) +#if defined (BOOST_INTERPROCESS_WINDOWS) template class IndexType> class basic_managed_windows_shared_memory; -typedef basic_managed_windows_shared_memory +typedef basic_managed_windows_shared_memory ,iset_index> @@ -250,16 +258,15 @@ typedef basic_managed_windows_shared_memory ,iset_index> wmanaged_windows_shared_memory; -#endif //#if defined (BOOST_INTERPROCESS_WINDOWS) - -#if defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) || defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) +#else +#if defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) template class IndexType> class basic_managed_xsi_shared_memory; -typedef basic_managed_xsi_shared_memory +typedef basic_managed_xsi_shared_memory ,iset_index> @@ -270,9 +277,10 @@ typedef basic_managed_xsi_shared_memory ,rbtree_best_fit ,iset_index> wmanaged_xsi_shared_memory; - #endif //#if defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) +#endif //#if defined (BOOST_INTERPROCESS_WINDOWS) + ////////////////////////////////////////////////////////////////////////////// // Fixed address shared memory ////////////////////////////////////////////////////////////////////////////// @@ -402,10 +410,7 @@ class weak_ptr; // IPC ////////////////////////////////////////////////////////////////////////////// -template -class message_queue_t; - -typedef message_queue_t > message_queue; +class message_queue; }} //namespace boost { namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/ipc/message_queue.hpp b/utils/boost_idb/boost/interprocess/ipc/message_queue.hpp index 9e5e8ff0..7f86fe4f 100644 --- a/utils/boost_idb/boost/interprocess/ipc/message_queue.hpp +++ b/utils/boost_idb/boost/interprocess/ipc/message_queue.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include @@ -26,11 +25,7 @@ #include #include #include -#include -#include -#include -#include -#include + #include //std::lower_bound #include //std::size_t #include //memcpy @@ -43,56 +38,43 @@ namespace boost{ namespace interprocess{ -namespace ipcdetail -{ - template - class msg_queue_initialization_func_t; -} - //!A class that allows sending messages //!between processes. -template -class message_queue_t +class message_queue { /// @cond //Blocking modes enum block_t { blocking, timed, non_blocking }; - message_queue_t(); + message_queue(); /// @endcond public: - typedef VoidPointer void_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type char_ptr; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; //!Creates a process shared message queue with name "name". For this message queue, //!the maximum number of messages will be "max_num_msg" and the maximum message size //!will be "max_msg_size". Throws on error and if the queue was previously created. - message_queue_t(create_only_t create_only, - const char *name, - size_type max_num_msg, - size_type max_msg_size, + message_queue(create_only_t create_only, + const char *name, + std::size_t max_num_msg, + std::size_t max_msg_size, const permissions &perm = permissions()); - //!Opens or creates a process shared message queue with name "name". - //!If the queue is created, the maximum number of messages will be "max_num_msg" - //!and the maximum message size will be "max_msg_size". If queue was previously + //!Opens or creates a process shared message queue with name "name". + //!If the queue is created, the maximum number of messages will be "max_num_msg" + //!and the maximum message size will be "max_msg_size". If queue was previously //!created the queue will be opened and "max_num_msg" and "max_msg_size" parameters //!are ignored. Throws on error. - message_queue_t(open_or_create_t open_or_create, - const char *name, - size_type max_num_msg, - size_type max_msg_size, + message_queue(open_or_create_t open_or_create, + const char *name, + std::size_t max_num_msg, + std::size_t max_msg_size, const permissions &perm = permissions()); - //!Opens a previously created process shared message queue with name "name". - //!If the queue was not previously created or there are no free resources, + //!Opens a previously created process shared message queue with name "name". + //!If the was not previously created or there are no free resources, //!throws an error. - message_queue_t(open_only_t open_only, + message_queue(open_only_t open_only, const char *name); //!Destroys *this and indicates that the calling process is finished using @@ -102,175 +84,140 @@ class message_queue_t //!this resource. The resource can still be opened again calling //!the open constructor overload. To erase the message queue from the system //!use remove(). - ~message_queue_t(); + ~message_queue(); - //!Sends a message stored in buffer "buffer" with size "buffer_size" in the + //!Sends a message stored in buffer "buffer" with size "buffer_size" in the //!message queue with priority "priority". If the message queue is full - //!the sender is blocked. Throws interprocess_error on error. - void send (const void *buffer, size_type buffer_size, + //!the sender is blocked. Throws interprocess_error on error.*/ + void send (const void *buffer, std::size_t buffer_size, unsigned int priority); - //!Sends a message stored in buffer "buffer" with size "buffer_size" through the + //!Sends a message stored in buffer "buffer" with size "buffer_size" through the //!message queue with priority "priority". If the message queue is full //!the sender is not blocked and returns false, otherwise returns true. //!Throws interprocess_error on error. - bool try_send (const void *buffer, size_type buffer_size, + bool try_send (const void *buffer, std::size_t buffer_size, unsigned int priority); - //!Sends a message stored in buffer "buffer" with size "buffer_size" in the + //!Sends a message stored in buffer "buffer" with size "buffer_size" in the //!message queue with priority "priority". If the message queue is full //!the sender retries until time "abs_time" is reached. Returns true if //!the message has been successfully sent. Returns false if timeout is reached. //!Throws interprocess_error on error. - bool timed_send (const void *buffer, size_type buffer_size, + bool timed_send (const void *buffer, std::size_t buffer_size, unsigned int priority, const boost::posix_time::ptime& abs_time); - //!Receives a message from the message queue. The message is stored in buffer - //!"buffer", which has size "buffer_size". The received message has size + //!Receives a message from the message queue. The message is stored in buffer + //!"buffer", which has size "buffer_size". The received message has size //!"recvd_size" and priority "priority". If the message queue is empty //!the receiver is blocked. Throws interprocess_error on error. - void receive (void *buffer, size_type buffer_size, - size_type &recvd_size,unsigned int &priority); + void receive (void *buffer, std::size_t buffer_size, + std::size_t &recvd_size,unsigned int &priority); - //!Receives a message from the message queue. The message is stored in buffer - //!"buffer", which has size "buffer_size". The received message has size + //!Receives a message from the message queue. The message is stored in buffer + //!"buffer", which has size "buffer_size". The received message has size //!"recvd_size" and priority "priority". If the message queue is empty //!the receiver is not blocked and returns false, otherwise returns true. //!Throws interprocess_error on error. - bool try_receive (void *buffer, size_type buffer_size, - size_type &recvd_size,unsigned int &priority); + bool try_receive (void *buffer, std::size_t buffer_size, + std::size_t &recvd_size,unsigned int &priority); - //!Receives a message from the message queue. The message is stored in buffer - //!"buffer", which has size "buffer_size". The received message has size + //!Receives a message from the message queue. The message is stored in buffer + //!"buffer", which has size "buffer_size". The received message has size //!"recvd_size" and priority "priority". If the message queue is empty //!the receiver retries until time "abs_time" is reached. Returns true if //!the message has been successfully sent. Returns false if timeout is reached. //!Throws interprocess_error on error. - bool timed_receive (void *buffer, size_type buffer_size, - size_type &recvd_size,unsigned int &priority, + bool timed_receive (void *buffer, std::size_t buffer_size, + std::size_t &recvd_size,unsigned int &priority, const boost::posix_time::ptime &abs_time); //!Returns the maximum number of messages allowed by the queue. The message - //!queue must be opened or created previously. Otherwise, returns 0. + //!queue must be opened or created previously. Otherwise, returns 0. //!Never throws - size_type get_max_msg() const; + std::size_t get_max_msg() const; //!Returns the maximum size of message allowed by the queue. The message - //!queue must be opened or created previously. Otherwise, returns 0. + //!queue must be opened or created previously. Otherwise, returns 0. //!Never throws - size_type get_max_msg_size() const; + std::size_t get_max_msg_size() const; - //!Returns the number of messages currently stored. + //!Returns the number of messages currently stored. //!Never throws - size_type get_num_msg() const; + std::size_t get_num_msg(); //!Removes the message queue from the system. //!Returns false on error. Never throws static bool remove(const char *name); - /// @cond + /// @cond private: typedef boost::posix_time::ptime ptime; - - friend class ipcdetail::msg_queue_initialization_func_t; - bool do_receive(block_t block, - void *buffer, size_type buffer_size, - size_type &recvd_size, unsigned int &priority, + void *buffer, std::size_t buffer_size, + std::size_t &recvd_size, unsigned int &priority, const ptime &abs_time); bool do_send(block_t block, - const void *buffer, size_type buffer_size, + const void *buffer, std::size_t buffer_size, unsigned int priority, const ptime &abs_time); //!Returns the needed memory size for the shared message queue. //!Never throws - static size_type get_mem_size(size_type max_msg_size, size_type max_num_msg); - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; + static std::size_t get_mem_size(std::size_t max_msg_size, std::size_t max_num_msg); + + detail::managed_open_or_create_impl m_shmem; /// @endcond }; /// @cond -namespace ipcdetail { +namespace detail { //!This header is the prefix of each message in the queue -template -class msg_hdr_t +class msg_hdr_t { - typedef VoidPointer void_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type char_ptr; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; - public: - size_type len; // Message length + std::size_t len; // Message length unsigned int priority;// Message priority //!Returns the data buffer associated with this this message void * data(){ return this+1; } // }; //!This functor is the predicate to order stored messages by priority -template class priority_functor { - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer >::type msg_hdr_ptr_t; - public: - bool operator()(const msg_hdr_ptr_t &msg1, - const msg_hdr_ptr_t &msg2) const + bool operator()(const offset_ptr &msg1, + const offset_ptr &msg2) const { return msg1->priority < msg2->priority; } }; -//!This header is placed in the beginning of the shared memory and contains -//!the data to control the queue. This class initializes the shared memory +//!This header is placed in the beginning of the shared memory and contains +//!the data to control the queue. This class initializes the shared memory //!in the following way: in ascending memory address with proper alignment //!fillings: //! -//!-> mq_hdr_t: +//!-> mq_hdr_t: //! Main control block that controls the rest of the elements //! //!-> offset_ptr index [max_num_msg] -//! An array of pointers with size "max_num_msg" called index. Each pointer -//! points to a preallocated message. Elements of this array are +//! An array of pointers with size "max_num_msg" called index. Each pointer +//! points to a preallocated message. The elements of this array are //! reordered in runtime in the following way: //! -//! IF BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX is defined: -//! -//! When the current number of messages is "cur_num_msg", the array -//! is treated like a circular buffer. Starting from position "cur_first_msg" -//! "cur_num_msg" in a circular way, pointers point to inserted messages and the rest -//! point to free messages. Those "cur_num_msg" pointers are -//! ordered by the priority of the pointed message and by insertion order -//! if two messages have the same priority. So the next message to be -//! used in a "receive" is pointed by index [(cur_first_msg + cur_num_msg-1)%max_num_msg] -//! and the first free message ready to be used in a "send" operation is -//! [cur_first_msg] if circular buffer is extended from front, -//! [(cur_first_msg + cur_num_msg)%max_num_msg] otherwise. -//! -//! This transforms the index in a circular buffer with an embedded free -//! message queue. -//! -//! ELSE (BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX is NOT defined): -//! -//! When the current number of messages is "cur_num_msg", the first +//! When the current number of messages is "cur_num_msg", the first //! "cur_num_msg" pointers point to inserted messages and the rest //! point to free messages. The first "cur_num_msg" pointers are -//! ordered by the priority of the pointed message and by insertion order -//! if two messages have the same priority. So the next message to be +//! ordered by the priority of the pointed message and by insertion order +//! if two messages have the same priority. So the next message to be //! used in a "receive" is pointed by index [cur_num_msg-1] and the first free //! message ready to be used in a "send" operation is index [cur_num_msg]. -//! -//! This transforms the index in a fixed size priority queue with an embedded free +//! This transforms index in a fixed size priority queue with an embedded free //! message queue. //! //!-> struct message_t -//! { +//! { //! msg_hdr_t header; //! char[max_msg_size] data; //! } messages [max_num_msg]; @@ -278,37 +225,25 @@ class priority_functor //! An array of buffers of preallocated messages, each one prefixed with the //! msg_hdr_t structure. Each of this message is pointed by one pointer of //! the index structure. -template class mq_hdr_t - : public ipcdetail::priority_functor -{ - typedef VoidPointer void_pointer; - typedef msg_hdr_t msg_header; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type msg_hdr_ptr_t; - typedef typename boost::intrusive::pointer_traits - ::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type msg_hdr_ptr_ptr_t; - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - + : public detail::priority_functor +{ + typedef offset_ptr msg_hdr_ptr_t; public: - //!Constructor. This object must be constructed in the beginning of the + //!Constructor. This object must be constructed in the beginning of the //!shared memory of the size returned by the function "get_mem_size". //!This constructor initializes the needed resources and creates - //!the internal structures like the priority index. This can throw. - mq_hdr_t(size_type max_num_msg, size_type max_msg_size) - : m_max_num_msg(max_num_msg), + //!the internal structures like the priority index. This can throw.*/ + mq_hdr_t(std::size_t max_num_msg, std::size_t max_msg_size) + : m_max_num_msg(max_num_msg), m_max_msg_size(max_msg_size), m_cur_num_msg(0) - #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX) - ,m_cur_first_msg(0u) - #endif { this->initialize_memory(); } + //!Returns the inserted message with top priority + msg_hdr_t * top_msg() + { return mp_index[m_cur_num_msg-1].get(); } + //!Returns true if the message queue is full bool is_full() const { return m_cur_num_msg == m_max_num_msg; } @@ -321,283 +256,100 @@ class mq_hdr_t void free_top_msg() { --m_cur_num_msg; } - #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX) - - typedef msg_hdr_ptr_t *iterator; - - size_type end_pos() const - { - const size_type space_until_bufend = m_max_num_msg - m_cur_first_msg; - return space_until_bufend > m_cur_num_msg - ? m_cur_first_msg + m_cur_num_msg : m_cur_num_msg - space_until_bufend; - } - - //!Returns the inserted message with top priority - msg_header &top_msg() - { - size_type pos = this->end_pos(); - return *mp_index[pos ? --pos : m_max_num_msg - 1]; - } - - //!Returns the inserted message with bottom priority - msg_header &bottom_msg() - { return *mp_index[m_cur_first_msg]; } - - iterator inserted_ptr_begin() const - { return &mp_index[m_cur_first_msg]; } - - iterator inserted_ptr_end() const - { return &mp_index[this->end_pos()]; } - - iterator lower_bound(const msg_hdr_ptr_t & value, priority_functor func) - { - iterator begin(this->inserted_ptr_begin()), end(this->inserted_ptr_end()); - if(end < begin){ - iterator idx_end = &mp_index[m_max_num_msg]; - iterator ret = std::lower_bound(begin, idx_end, value, func); - if(idx_end == ret){ - iterator idx_beg = &mp_index[0]; - ret = std::lower_bound(idx_beg, end, value, func); - //sanity check, these cases should not call lower_bound (optimized out) - BOOST_ASSERT(ret != end); - BOOST_ASSERT(ret != begin); - return ret; - } - else{ - return ret; - } - } - else{ - return std::lower_bound(begin, end, value, func); - } - } - - msg_header & insert_at(iterator where) - { - iterator it_inserted_ptr_end = this->inserted_ptr_end(); - iterator it_inserted_ptr_beg = this->inserted_ptr_begin(); - if(where == it_inserted_ptr_end){ - ++m_cur_num_msg; - return **it_inserted_ptr_end; - } - else if(where == it_inserted_ptr_beg){ - //unsigned integer guarantees underflow - m_cur_first_msg = m_cur_first_msg ? m_cur_first_msg : m_max_num_msg; - --m_cur_first_msg; - ++m_cur_num_msg; - return *mp_index[m_cur_first_msg]; - } - else{ - size_type pos = where - &mp_index[0]; - size_type circ_pos = pos >= m_cur_first_msg ? pos - m_cur_first_msg : pos + (m_max_num_msg - m_cur_first_msg); - //Check if it's more efficient to move back or move front - if(circ_pos < m_cur_num_msg/2){ - //The queue can't be full so m_cur_num_msg == 0 or m_cur_num_msg <= pos - //indicates two step insertion - if(!pos){ - pos = m_max_num_msg; - where = &mp_index[m_max_num_msg-1]; - } - else{ - --where; - } - const bool unique_segment = m_cur_first_msg && m_cur_first_msg <= pos; - const size_type first_segment_beg = unique_segment ? m_cur_first_msg : 1u; - const size_type first_segment_end = pos; - const size_type second_segment_beg = unique_segment || !m_cur_first_msg ? m_max_num_msg : m_cur_first_msg; - const size_type second_segment_end = m_max_num_msg; - const msg_hdr_ptr_t backup = *(&mp_index[0] + (unique_segment ? first_segment_beg : second_segment_beg) - 1); - - //First segment - if(!unique_segment){ - std::copy( &mp_index[0] + second_segment_beg - , &mp_index[0] + second_segment_end - , &mp_index[0] + second_segment_beg - 1); - mp_index[m_max_num_msg-1] = mp_index[0]; - } - std::copy( &mp_index[0] + first_segment_beg - , &mp_index[0] + first_segment_end - , &mp_index[0] + first_segment_beg - 1); - *where = backup; - m_cur_first_msg = m_cur_first_msg ? m_cur_first_msg : m_max_num_msg; - --m_cur_first_msg; - ++m_cur_num_msg; - return **where; - } - else{ - //The queue can't be full so end_pos < m_cur_first_msg - //indicates two step insertion - const size_type pos_end = this->end_pos(); - const bool unique_segment = pos < pos_end; - const size_type first_segment_beg = pos; - const size_type first_segment_end = unique_segment ? pos_end : m_max_num_msg-1; - const size_type second_segment_beg = 0u; - const size_type second_segment_end = unique_segment ? 0u : pos_end; - const msg_hdr_ptr_t backup = *it_inserted_ptr_end; - - //First segment - if(!unique_segment){ - std::copy_backward( &mp_index[0] + second_segment_beg - , &mp_index[0] + second_segment_end - , &mp_index[0] + second_segment_end + 1); - mp_index[0] = mp_index[m_max_num_msg-1]; - } - std::copy_backward( &mp_index[0] + first_segment_beg - , &mp_index[0] + first_segment_end - , &mp_index[0] + first_segment_end + 1); - *where = backup; - ++m_cur_num_msg; - return **where; - } - } - } - - #else - - typedef msg_hdr_ptr_t *iterator; - - //!Returns the inserted message with top priority - msg_header &top_msg() - { return *mp_index[m_cur_num_msg-1]; } - - //!Returns the inserted message with bottom priority - msg_header &bottom_msg() - { return *mp_index[0]; } - - iterator inserted_ptr_begin() const - { return &mp_index[0]; } - - iterator inserted_ptr_end() const - { return &mp_index[m_cur_num_msg]; } - - iterator lower_bound(const msg_hdr_ptr_t & value, priority_functor func) - { return std::lower_bound(this->inserted_ptr_begin(), this->inserted_ptr_end(), value, func); } - - msg_header & insert_at(iterator pos) - { - const msg_hdr_ptr_t backup = *inserted_ptr_end(); - std::copy_backward(pos, inserted_ptr_end(), inserted_ptr_end()+1); - *pos = backup; - ++m_cur_num_msg; - return **pos; - } - - #endif + //!Returns the first free msg of the free message queue + msg_hdr_t * free_msg() + { return mp_index[m_cur_num_msg].get(); } //!Inserts the first free message in the priority queue - msg_header & queue_free_msg(unsigned int priority) - { + void queue_free_msg() + { + //Get free msg + msg_hdr_ptr_t free = mp_index[m_cur_num_msg]; //Get priority queue's range - iterator it (inserted_ptr_begin()), it_end(inserted_ptr_end()); - //Optimize for non-priority usage - if(m_cur_num_msg && priority > this->bottom_msg().priority){ - //Check for higher priority than all stored messages - if(priority > this->top_msg().priority){ - it = it_end; - } - else{ - //Since we don't now which free message we will pick - //build a dummy header for searches - msg_header dummy_hdr; - dummy_hdr.priority = priority; - - //Get free msg - msg_hdr_ptr_t dummy_ptr(&dummy_hdr); - - //Check where the free message should be placed - it = this->lower_bound(dummy_ptr, static_cast&>(*this)); - } - - } + msg_hdr_ptr_t *it = &mp_index[0], *it_end = &mp_index[m_cur_num_msg]; + //Check where the free message should be placed + it = std::lower_bound(it, it_end, free, static_cast(*this)); + //Make room in that position + std::copy_backward(it, it_end, it_end+1); //Insert the free message in the correct position - return this->insert_at(it); + *it = free; + ++m_cur_num_msg; } - //!Returns the number of bytes needed to construct a message queue with - //!"max_num_size" maximum number of messages and "max_msg_size" maximum + //!Returns the number of bytes needed to construct a message queue with + //!"max_num_size" maximum number of messages and "max_msg_size" maximum //!message size. Never throws. - static size_type get_mem_size - (size_type max_msg_size, size_type max_num_msg) + static std::size_t get_mem_size + (std::size_t max_msg_size, std::size_t max_num_msg) { - const size_type - msg_hdr_align = ::boost::alignment_of::value, - index_align = ::boost::alignment_of::value, - r_hdr_size = ipcdetail::ct_rounded_size::value, - r_index_size = ipcdetail::get_rounded_size(max_num_msg*sizeof(msg_hdr_ptr_t), msg_hdr_align), - r_max_msg_size = ipcdetail::get_rounded_size(max_msg_size, msg_hdr_align) + sizeof(msg_header); - return r_hdr_size + r_index_size + (max_num_msg*r_max_msg_size) + - open_create_impl_t::ManagedOpenOrCreateUserOffset; + const std::size_t + msg_hdr_align = detail::alignment_of::value, + index_align = detail::alignment_of::value, + r_hdr_size = detail::ct_rounded_size::value, + r_index_size = detail::get_rounded_size(sizeof(msg_hdr_ptr_t)*max_num_msg, msg_hdr_align), + r_max_msg_size = detail::get_rounded_size(max_msg_size, msg_hdr_align) + sizeof(detail::msg_hdr_t); + return r_hdr_size + r_index_size + (max_num_msg*r_max_msg_size) + + detail::managed_open_or_create_impl::ManagedOpenOrCreateUserOffset; } //!Initializes the memory structures to preallocate messages and constructs the //!message index. Never throws. void initialize_memory() { - const size_type - msg_hdr_align = ::boost::alignment_of::value, - index_align = ::boost::alignment_of::value, - r_hdr_size = ipcdetail::ct_rounded_size::value, - r_index_size = ipcdetail::get_rounded_size(m_max_num_msg*sizeof(msg_hdr_ptr_t), msg_hdr_align), - r_max_msg_size = ipcdetail::get_rounded_size(m_max_msg_size, msg_hdr_align) + sizeof(msg_header); + const std::size_t + msg_hdr_align = detail::alignment_of::value, + index_align = detail::alignment_of::value, + r_hdr_size = detail::ct_rounded_size::value, + r_index_size = detail::get_rounded_size(sizeof(msg_hdr_ptr_t)*m_max_num_msg, msg_hdr_align), + r_max_msg_size = detail::get_rounded_size(m_max_msg_size, msg_hdr_align) + sizeof(detail::msg_hdr_t); //Pointer to the index msg_hdr_ptr_t *index = reinterpret_cast (reinterpret_cast(this)+r_hdr_size); //Pointer to the first message header - msg_header *msg_hdr = reinterpret_cast - (reinterpret_cast(this)+r_hdr_size+r_index_size); + detail::msg_hdr_t *msg_hdr = reinterpret_cast + (reinterpret_cast(this)+r_hdr_size+r_index_size); //Initialize the pointer to the index mp_index = index; //Initialize the index so each slot points to a preallocated message - for(size_type i = 0; i < m_max_num_msg; ++i){ + for(std::size_t i = 0; i < m_max_num_msg; ++i){ index[i] = msg_hdr; - msg_hdr = reinterpret_cast + msg_hdr = reinterpret_cast (reinterpret_cast(msg_hdr)+r_max_msg_size); } } public: //Pointer to the index - msg_hdr_ptr_ptr_t mp_index; + offset_ptr mp_index; //Maximum number of messages of the queue - const size_type m_max_num_msg; + const std::size_t m_max_num_msg; //Maximum size of messages of the queue - const size_type m_max_msg_size; + const std::size_t m_max_msg_size; //Current number of messages - size_type m_cur_num_msg; + std::size_t m_cur_num_msg; //Mutex to protect data structures interprocess_mutex m_mutex; //Condition block receivers when there are no messages interprocess_condition m_cond_recv; //Condition block senders when the queue is full interprocess_condition m_cond_send; - #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX) - //Current start offset in the circular index - size_type m_cur_first_msg; - #endif }; -//!This is the atomic functor to be executed when creating or opening +//!This is the atomic functor to be executed when creating or opening //!shared memory. Never throws -template -class msg_queue_initialization_func_t +class initialization_func_t { public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type char_ptr; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; - - msg_queue_initialization_func_t(size_type maxmsg = 0, - size_type maxmsgsize = 0) + initialization_func_t(std::size_t maxmsg = 0, + std::size_t maxmsgsize = 0) : m_maxmsg (maxmsg), m_maxmsgsize(maxmsgsize) {} - bool operator()(void *address, size_type, bool created) + bool operator()(void *address, std::size_t, bool created) { char *mptr; @@ -605,95 +357,81 @@ class msg_queue_initialization_func_t mptr = reinterpret_cast(address); //Construct the message queue header at the beginning BOOST_TRY{ - new (mptr) mq_hdr_t(m_maxmsg, m_maxmsgsize); + new (mptr) mq_hdr_t(m_maxmsg, m_maxmsgsize); } BOOST_CATCH(...){ - return false; + return false; } BOOST_CATCH_END } return true; } - - std::size_t get_min_size() const - { - return mq_hdr_t::get_mem_size(m_maxmsgsize, m_maxmsg) - - message_queue_t::open_create_impl_t::ManagedOpenOrCreateUserOffset; - } - - const size_type m_maxmsg; - const size_type m_maxmsgsize; + const std::size_t m_maxmsg; + const std::size_t m_maxmsgsize; }; -} //namespace ipcdetail { +} //namespace detail { -template -inline message_queue_t::~message_queue_t() +inline message_queue::~message_queue() {} -template -inline typename message_queue_t::size_type message_queue_t::get_mem_size - (size_type max_msg_size, size_type max_num_msg) -{ return ipcdetail::mq_hdr_t::get_mem_size(max_msg_size, max_num_msg); } +inline std::size_t message_queue::get_mem_size + (std::size_t max_msg_size, std::size_t max_num_msg) +{ return detail::mq_hdr_t::get_mem_size(max_msg_size, max_num_msg); } -template -inline message_queue_t::message_queue_t(create_only_t, - const char *name, - size_type max_num_msg, - size_type max_msg_size, +inline message_queue::message_queue(create_only_t create_only, + const char *name, + std::size_t max_num_msg, + std::size_t max_msg_size, const permissions &perm) //Create shared memory and execute functor atomically - : m_shmem(create_only, - name, + : m_shmem(create_only, + name, get_mem_size(max_msg_size, max_num_msg), read_write, static_cast(0), //Prepare initialization functor - ipcdetail::msg_queue_initialization_func_t (max_num_msg, max_msg_size), + detail::initialization_func_t (max_num_msg, max_msg_size), perm) {} -template -inline message_queue_t::message_queue_t(open_or_create_t, - const char *name, - size_type max_num_msg, - size_type max_msg_size, +inline message_queue::message_queue(open_or_create_t open_or_create, + const char *name, + std::size_t max_num_msg, + std::size_t max_msg_size, const permissions &perm) //Create shared memory and execute functor atomically - : m_shmem(open_or_create, - name, + : m_shmem(open_or_create, + name, get_mem_size(max_msg_size, max_num_msg), read_write, static_cast(0), //Prepare initialization functor - ipcdetail::msg_queue_initialization_func_t (max_num_msg, max_msg_size), + detail::initialization_func_t (max_num_msg, max_msg_size), perm) {} -template -inline message_queue_t::message_queue_t(open_only_t, const char *name) +inline message_queue::message_queue(open_only_t open_only, + const char *name) //Create shared memory and execute functor atomically - : m_shmem(open_only, + : m_shmem(open_only, name, read_write, static_cast(0), //Prepare initialization functor - ipcdetail::msg_queue_initialization_func_t ()) + detail::initialization_func_t ()) {} -template -inline void message_queue_t::send - (const void *buffer, size_type buffer_size, unsigned int priority) +inline void message_queue::send + (const void *buffer, std::size_t buffer_size, unsigned int priority) { this->do_send(blocking, buffer, buffer_size, priority, ptime()); } -template -inline bool message_queue_t::try_send - (const void *buffer, size_type buffer_size, unsigned int priority) +inline bool message_queue::try_send + (const void *buffer, std::size_t buffer_size, unsigned int priority) { return this->do_send(non_blocking, buffer, buffer_size, priority, ptime()); } -template -inline bool message_queue_t::timed_send - (const void *buffer, size_type buffer_size +inline bool message_queue::timed_send + (const void *buffer, std::size_t buffer_size ,unsigned int priority, const boost::posix_time::ptime &abs_time) { if(abs_time == boost::posix_time::pos_infin){ @@ -703,24 +441,23 @@ inline bool message_queue_t::timed_send return this->do_send(timed, buffer, buffer_size, priority, abs_time); } -template -inline bool message_queue_t::do_send(block_t block, - const void *buffer, size_type buffer_size, +inline bool message_queue::do_send(block_t block, + const void *buffer, std::size_t buffer_size, unsigned int priority, const boost::posix_time::ptime &abs_time) { - ipcdetail::mq_hdr_t *p_hdr = static_cast*>(m_shmem.get_user_address()); + detail::mq_hdr_t *p_hdr = static_cast(m_shmem.get_user_address()); //Check if buffer is smaller than maximum allowed if (buffer_size > p_hdr->m_max_msg_size) { throw interprocess_exception(size_error); } - bool was_empty = false; //--------------------------------------------- scoped_lock lock(p_hdr->m_mutex); //--------------------------------------------- { //If the queue is full execute blocking logic if (p_hdr->is_full()) { + switch(block){ case non_blocking : return false; @@ -747,48 +484,45 @@ inline bool message_queue_t::do_send(block_t block, break; } } - - was_empty = p_hdr->is_empty(); - //Insert the first free message in the priority queue - ipcdetail::msg_hdr_t &free_msg_hdr = p_hdr->queue_free_msg(priority); - - //Sanity check, free msgs are always cleaned when received - BOOST_ASSERT(free_msg_hdr.priority == 0); - BOOST_ASSERT(free_msg_hdr.len == 0); + + //Get the first free message from free message queue + detail::msg_hdr_t *free_msg = p_hdr->free_msg(); + if (free_msg == 0) { + throw interprocess_exception("boost::interprocess::message_queue corrupted"); + } //Copy control data to the free message - free_msg_hdr.priority = priority; - free_msg_hdr.len = buffer_size; + free_msg->priority = priority; + free_msg->len = buffer_size; //Copy user buffer to the message - std::memcpy(free_msg_hdr.data(), buffer, buffer_size); - } // Lock end + std::memcpy(free_msg->data(), buffer, buffer_size); - //Notify outside lock to avoid contention. This might produce some - //spurious wakeups, but it's usually far better than notifying inside. - //If this message changes the queue empty state, notify it to receivers - if (was_empty){ - p_hdr->m_cond_recv.notify_one(); - } +// bool was_empty = p_hdr->is_empty(); + //Insert the first free message in the priority queue + p_hdr->queue_free_msg(); + + //If this message changes the queue empty state, notify it to receivers +// if (was_empty){ + p_hdr->m_cond_recv.notify_one(); +// } + } // Lock end return true; } -template -inline void message_queue_t::receive(void *buffer, size_type buffer_size, - size_type &recvd_size, unsigned int &priority) +inline void message_queue::receive(void *buffer, std::size_t buffer_size, + std::size_t &recvd_size, unsigned int &priority) { this->do_receive(blocking, buffer, buffer_size, recvd_size, priority, ptime()); } -template inline bool - message_queue_t::try_receive(void *buffer, size_type buffer_size, - size_type &recvd_size, unsigned int &priority) + message_queue::try_receive(void *buffer, std::size_t buffer_size, + std::size_t &recvd_size, unsigned int &priority) { return this->do_receive(non_blocking, buffer, buffer_size, recvd_size, priority, ptime()); } -template inline bool - message_queue_t::timed_receive(void *buffer, size_type buffer_size, - size_type &recvd_size, unsigned int &priority, + message_queue::timed_receive(void *buffer, std::size_t buffer_size, + std::size_t &recvd_size, unsigned int &priority, const boost::posix_time::ptime &abs_time) { if(abs_time == boost::posix_time::pos_infin){ @@ -798,20 +532,18 @@ inline bool return this->do_receive(timed, buffer, buffer_size, recvd_size, priority, abs_time); } -template inline bool - message_queue_t::do_receive(block_t block, - void *buffer, size_type buffer_size, - size_type &recvd_size, unsigned int &priority, + message_queue::do_receive(block_t block, + void *buffer, std::size_t buffer_size, + std::size_t &recvd_size, unsigned int &priority, const boost::posix_time::ptime &abs_time) { - ipcdetail::mq_hdr_t *p_hdr = static_cast*>(m_shmem.get_user_address()); + detail::mq_hdr_t *p_hdr = static_cast(m_shmem.get_user_address()); //Check if buffer is big enough for any message if (buffer_size < p_hdr->m_max_msg_size) { throw interprocess_exception(size_error); } - bool was_full = false; //--------------------------------------------- scoped_lock lock(p_hdr->m_mutex); //--------------------------------------------- @@ -847,53 +579,49 @@ inline bool } } - //There is at least one message ready to pick, get the top one - ipcdetail::msg_hdr_t &top_msg = p_hdr->top_msg(); + //Thre is at least message ready to pick, get the top one + detail::msg_hdr_t *top_msg = p_hdr->top_msg(); - //Get data from the message - recvd_size = top_msg.len; - priority = top_msg.priority; + //Paranoia check + if (top_msg == 0) { + throw interprocess_exception("boost::interprocess::message_queue corrupted"); + } - //Some cleanup to ease debugging - top_msg.len = 0; - top_msg.priority = 0; + //Get data from the message + recvd_size = top_msg->len; + priority = top_msg->priority; //Copy data to receiver's bufers - std::memcpy(buffer, top_msg.data(), recvd_size); + std::memcpy(buffer, top_msg->data(), recvd_size); - was_full = p_hdr->is_full(); +// bool was_full = p_hdr->is_full(); //Free top message and put it in the free message list p_hdr->free_top_msg(); - } //Lock end - //Notify outside lock to avoid contention. This might produce some - //spurious wakeups, but it's usually far better than notifying inside. - //If this reception changes the queue full state, notify senders - if (was_full){ - p_hdr->m_cond_send.notify_one(); - } + //If this reception changes the queue full state, notify senders +// if (was_full){ + p_hdr->m_cond_send.notify_one(); +// } + } //Lock end return true; } -template -inline typename message_queue_t::size_type message_queue_t::get_max_msg() const -{ - ipcdetail::mq_hdr_t *p_hdr = static_cast*>(m_shmem.get_user_address()); +inline std::size_t message_queue::get_max_msg() const +{ + detail::mq_hdr_t *p_hdr = static_cast(m_shmem.get_user_address()); return p_hdr ? p_hdr->m_max_num_msg : 0; } -template -inline typename message_queue_t::size_type message_queue_t::get_max_msg_size() const -{ - ipcdetail::mq_hdr_t *p_hdr = static_cast*>(m_shmem.get_user_address()); - return p_hdr ? p_hdr->m_max_msg_size : 0; +inline std::size_t message_queue::get_max_msg_size() const +{ + detail::mq_hdr_t *p_hdr = static_cast(m_shmem.get_user_address()); + return p_hdr ? p_hdr->m_max_msg_size : 0; } -template -inline typename message_queue_t::size_type message_queue_t::get_num_msg() const -{ - ipcdetail::mq_hdr_t *p_hdr = static_cast*>(m_shmem.get_user_address()); +inline std::size_t message_queue::get_num_msg() +{ + detail::mq_hdr_t *p_hdr = static_cast(m_shmem.get_user_address()); if(p_hdr){ //--------------------------------------------- scoped_lock lock(p_hdr->m_mutex); @@ -901,11 +629,10 @@ inline typename message_queue_t::size_type message_queue_tm_cur_num_msg; } - return 0; + return 0; } -template -inline bool message_queue_t::remove(const char *name) +inline bool message_queue::remove(const char *name) { return shared_memory_object::remove(name); } /// @endcond diff --git a/utils/boost_idb/boost/interprocess/managed_external_buffer.hpp b/utils/boost_idb/boost/interprocess/managed_external_buffer.hpp index 1f4a1995..c4c70f03 100644 --- a/utils/boost_idb/boost/interprocess/managed_external_buffer.hpp +++ b/utils/boost_idb/boost/interprocess/managed_external_buffer.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,40 +19,34 @@ #include #include #include -#include +#include #include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include -#include //!\file -//!Describes a named user memory allocation user class. +//!Describes a named user memory allocation user class. namespace boost { namespace interprocess { -//!A basic user memory named object creation class. Inherits all -//!basic functionality from +//!A basic user memory named object creation class. Inherits all +//!basic functionality from //!basic_managed_memory_impl*/ template < - class CharType, - class AllocationAlgorithm, + class CharType, + class AllocationAlgorithm, template class IndexType > -class basic_managed_external_buffer - : public ipcdetail::basic_managed_memory_impl +class basic_managed_external_buffer + : public detail::basic_managed_memory_impl { /// @cond - typedef ipcdetail::basic_managed_memory_impl + typedef detail::basic_managed_memory_impl base_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_external_buffer) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(basic_managed_external_buffer) /// @endcond - + public: - typedef typename base_t::size_type size_type; //!Default constructor. Does nothing. //!Useful in combination with move semantics @@ -61,10 +55,10 @@ class basic_managed_external_buffer //!Creates and places the segment manager. This can throw basic_managed_external_buffer - (create_only_t, void *addr, size_type size) + (create_only_t, void *addr, std::size_t size) { //Check if alignment is correct - BOOST_ASSERT((0 == (((std::size_t)addr) & (AllocationAlgorithm::Alignment - size_type(1u))))); + BOOST_ASSERT((0 == (((std::size_t)addr) & (AllocationAlgorithm::Alignment - std::size_t(1u))))); if(!base_t::create_impl(addr, size)){ throw interprocess_exception("Could not initialize buffer in basic_managed_external_buffer constructor"); } @@ -72,30 +66,30 @@ class basic_managed_external_buffer //!Creates and places the segment manager. This can throw basic_managed_external_buffer - (open_only_t, void *addr, size_type size) + (open_only_t, void *addr, std::size_t size) { //Check if alignment is correct - BOOST_ASSERT((0 == (((std::size_t)addr) & (AllocationAlgorithm::Alignment - size_type(1u))))); + BOOST_ASSERT((0 == (((std::size_t)addr) & (AllocationAlgorithm::Alignment - std::size_t(1u))))); if(!base_t::open_impl(addr, size)){ throw interprocess_exception("Could not initialize buffer in basic_managed_external_buffer constructor"); } } //!Moves the ownership of "moved"'s managed memory to *this. Does not throw - basic_managed_external_buffer(BOOST_RV_REF(basic_managed_external_buffer) moved) + basic_managed_external_buffer(BOOST_INTERPROCESS_RV_REF(basic_managed_external_buffer) moved) { this->swap(moved); } //!Moves the ownership of "moved"'s managed memory to *this. Does not throw - basic_managed_external_buffer &operator=(BOOST_RV_REF(basic_managed_external_buffer) moved) + basic_managed_external_buffer &operator=(BOOST_INTERPROCESS_RV_REF(basic_managed_external_buffer) moved) { - basic_managed_external_buffer tmp(boost::move(moved)); + basic_managed_external_buffer tmp(boost::interprocess::move(moved)); this->swap(tmp); return *this; } - void grow(size_type extra_bytes) + void grow(std::size_t extra_bytes) { base_t::grow(extra_bytes); } //!Swaps the ownership of the managed heap memories managed by *this and other. diff --git a/utils/boost_idb/boost/interprocess/managed_heap_memory.hpp b/utils/boost_idb/boost/interprocess/managed_heap_memory.hpp index 868fdc55..7a60b9f6 100644 --- a/utils/boost_idb/boost/interprocess/managed_heap_memory.hpp +++ b/utils/boost_idb/boost/interprocess/managed_heap_memory.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,44 +18,38 @@ #include #include #include -#include +#include #include #include #include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include -#include //!\file -//!Describes a named heap memory allocation user class. +//!Describes a named heap memory allocation user class. namespace boost { namespace interprocess { -//!A basic heap memory named object creation class. Initializes the -//!heap memory segment. Inherits all basic functionality from +//!A basic heap memory named object creation class. Initializes the +//!heap memory segment. Inherits all basic functionality from //!basic_managed_memory_impl*/ template < - class CharType, - class AllocationAlgorithm, + class CharType, + class AllocationAlgorithm, template class IndexType > -class basic_managed_heap_memory - : public ipcdetail::basic_managed_memory_impl +class basic_managed_heap_memory + : public detail::basic_managed_memory_impl { /// @cond private: - typedef ipcdetail::basic_managed_memory_impl + typedef detail::basic_managed_memory_impl base_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_heap_memory) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(basic_managed_heap_memory) /// @endcond public: //functions - typedef typename base_t::size_type size_type; //!Default constructor. Does nothing. //!Useful in combination with move semantics @@ -68,7 +62,7 @@ class basic_managed_heap_memory //!Creates heap memory and initializes the segment manager. //!This can throw. - basic_managed_heap_memory(size_type size) + basic_managed_heap_memory(std::size_t size) : m_heapmem(size, char(0)) { if(!base_t::create_impl(&m_heapmem[0], size)){ @@ -78,32 +72,32 @@ class basic_managed_heap_memory } //!Moves the ownership of "moved"'s managed memory to *this. Does not throw - basic_managed_heap_memory(BOOST_RV_REF(basic_managed_heap_memory) moved) + basic_managed_heap_memory(BOOST_INTERPROCESS_RV_REF(basic_managed_heap_memory) moved) { this->swap(moved); } //!Moves the ownership of "moved"'s managed memory to *this. Does not throw - basic_managed_heap_memory &operator=(BOOST_RV_REF(basic_managed_heap_memory) moved) + basic_managed_heap_memory &operator=(BOOST_INTERPROCESS_RV_REF(basic_managed_heap_memory) moved) { - basic_managed_heap_memory tmp(boost::move(moved)); + basic_managed_heap_memory tmp(boost::interprocess::move(moved)); this->swap(tmp); return *this; } //!Tries to resize internal heap memory so that - //!we have room for more objects. - //!WARNING: If memory is reallocated, all the objects will + //!we have room for more objects. + //!WARNING: If memory is reallocated, all the objects will //!be binary-copied to the new buffer. To be able to use //!this function, all pointers constructed in this buffer //!must be offset pointers. Otherwise, the result is undefined. //!Returns true if the growth has been successful, so you will - //!have some extra bytes to allocate new objects. If returns + //!have some extra bytes to allocate new objects. If returns //!false, the heap allocation has failed. - bool grow(size_type extra_bytes) - { + bool grow(std::size_t extra_bytes) + { //If memory is reallocated, data will //be automatically copied BOOST_TRY{ - m_heapmem.resize(m_heapmem.size()+extra_bytes); + m_heapmem.resize(m_heapmem.size()+extra_bytes); } BOOST_CATCH(...){ return false; @@ -129,7 +123,7 @@ class basic_managed_heap_memory private: //!Frees resources. Never throws. void priv_close() - { + { base_t::destroy_impl(); std::vector().swap(m_heapmem); } diff --git a/utils/boost_idb/boost/interprocess/managed_mapped_file.hpp b/utils/boost_idb/boost/interprocess/managed_mapped_file.hpp index a802119a..d5482597 100644 --- a/utils/boost_idb/boost/interprocess/managed_mapped_file.hpp +++ b/utils/boost_idb/boost/interprocess/managed_mapped_file.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -21,130 +21,115 @@ #include #include #include -#include +#include #include #include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include -#include namespace boost { namespace interprocess { -namespace ipcdetail { -template -struct mfile_open_or_create -{ - typedef ipcdetail::managed_open_or_create_impl - < file_wrapper, AllocationAlgorithm::Alignment, true, false> type; -}; - -} //namespace ipcdetail { - -//!A basic mapped file named object creation class. Initializes the -//!mapped file. Inherits all basic functionality from +//!A basic mapped file named object creation class. Initializes the +//!mapped file. Inherits all basic functionality from //!basic_managed_memory_impl template < - class CharType, - class AllocationAlgorithm, + class CharType, + class AllocationAlgorithm, template class IndexType > -class basic_managed_mapped_file - : public ipcdetail::basic_managed_memory_impl +class basic_managed_mapped_file + : public detail::basic_managed_memory_impl ::type::ManagedOpenOrCreateUserOffset> + ,detail::managed_open_or_create_impl::ManagedOpenOrCreateUserOffset> { /// @cond public: - typedef ipcdetail::basic_managed_memory_impl + typedef detail::basic_managed_memory_impl ::type::ManagedOpenOrCreateUserOffset> base_t; - typedef ipcdetail::file_wrapper device_type; - typedef typename base_t::size_type size_type; + detail::managed_open_or_create_impl::ManagedOpenOrCreateUserOffset> base_t; + typedef detail::file_wrapper device_type; private: - typedef ipcdetail::create_open_func create_open_func_t; + typedef detail::create_open_func create_open_func_t; + typedef detail::managed_open_or_create_impl managed_open_or_create_type; basic_managed_mapped_file *get_this_pointer() { return this; } private: typedef typename base_t::char_ptr_holder_t char_ptr_holder_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_mapped_file) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(basic_managed_mapped_file) /// @endcond public: //functions - //!Creates mapped file and creates and places the segment manager. + //!Creates mapped file and creates and places the segment manager. //!This can throw. basic_managed_mapped_file() {} - //!Creates mapped file and creates and places the segment manager. + //!Creates mapped file and creates and places the segment manager. //!This can throw. - basic_managed_mapped_file(create_only_t, const char *name, - size_type size, const void *addr = 0, const permissions &perm = permissions()) - : m_mfile(create_only, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), ipcdetail::DoCreate), perm) + basic_managed_mapped_file(create_only_t create_only, const char *name, + std::size_t size, const void *addr = 0, const permissions &perm = permissions()) + : m_mfile(create_only, name, size, read_write, addr, + create_open_func_t(get_this_pointer(), detail::DoCreate), perm) {} //!Creates mapped file and creates and places the segment manager if //!segment was not created. If segment was created it connects to the //!segment. //!This can throw. - basic_managed_mapped_file (open_or_create_t, - const char *name, size_type size, + basic_managed_mapped_file (open_or_create_t open_or_create, + const char *name, std::size_t size, const void *addr = 0, const permissions &perm = permissions()) : m_mfile(open_or_create, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpenOrCreate), perm) + create_open_func_t(get_this_pointer(), + detail::DoOpenOrCreate), perm) {} //!Connects to a created mapped file and its segment manager. //!This can throw. - basic_managed_mapped_file (open_only_t, const char* name, + basic_managed_mapped_file (open_only_t open_only, const char* name, const void *addr = 0) : m_mfile(open_only, name, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Connects to a created mapped file and its segment manager //!in copy_on_write mode. //!This can throw. - basic_managed_mapped_file (open_copy_on_write_t, const char* name, + basic_managed_mapped_file (open_copy_on_write_t, const char* name, const void *addr = 0) - : m_mfile(open_only, name, copy_on_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + : m_mfile(open_only, name, copy_on_write, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Connects to a created mapped file and its segment manager //!in read-only mode. //!This can throw. - basic_managed_mapped_file (open_read_only_t, const char* name, + basic_managed_mapped_file (open_read_only_t, const char* name, const void *addr = 0) - : m_mfile(open_only, name, read_only, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + : m_mfile(open_only, name, read_only, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Moves the ownership of "moved"'s managed memory to *this. //!Does not throw - basic_managed_mapped_file(BOOST_RV_REF(basic_managed_mapped_file) moved) + basic_managed_mapped_file(BOOST_INTERPROCESS_RV_REF(basic_managed_mapped_file) moved) { this->swap(moved); } //!Moves the ownership of "moved"'s managed memory to *this. //!Does not throw - basic_managed_mapped_file &operator=(BOOST_RV_REF(basic_managed_mapped_file) moved) + basic_managed_mapped_file &operator=(BOOST_INTERPROCESS_RV_REF(basic_managed_mapped_file) moved) { - basic_managed_mapped_file tmp(boost::move(moved)); + basic_managed_mapped_file tmp(boost::interprocess::move(moved)); this->swap(tmp); return *this; } @@ -171,12 +156,12 @@ class basic_managed_mapped_file bool flush() { return m_mfile.flush(); } - //!Tries to resize mapped file so that we have room for - //!more objects. + //!Tries to resize mapped file so that we have room for + //!more objects. //! //!This function is not synchronized so no other thread or process should //!be reading or writing the file - static bool grow(const char *filename, size_type extra_bytes) + static bool grow(const char *filename, std::size_t extra_bytes) { return base_t::template grow (filename, extra_bytes); @@ -198,7 +183,7 @@ class basic_managed_mapped_file //!buffer and the object count. If not found returned pointer is 0. //!Never throws. template - std::pair find (char_ptr_holder_t name) + std::pair find (char_ptr_holder_t name) { if(m_mfile.get_mapped_region().get_mode() == read_only){ return base_t::template find_no_lock(name); @@ -209,7 +194,7 @@ class basic_managed_mapped_file } private: - typename ipcdetail::mfile_open_or_create::type m_mfile; + managed_open_or_create_type m_mfile; /// @endcond }; diff --git a/utils/boost_idb/boost/interprocess/managed_shared_memory.hpp b/utils/boost_idb/boost/interprocess/managed_shared_memory.hpp index c20f39ca..5884cf63 100644 --- a/utils/boost_idb/boost/interprocess/managed_shared_memory.hpp +++ b/utils/boost_idb/boost/interprocess/managed_shared_memory.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,62 +19,50 @@ #include #include +#include #include #include #include #include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include namespace boost { -namespace interprocess { - -namespace ipcdetail { - -template -struct shmem_open_or_create -{ - typedef ipcdetail::managed_open_or_create_impl - < shared_memory_object, AllocationAlgorithm::Alignment, true, false> type; -}; -} //namespace ipcdetail { +namespace interprocess { -//!A basic shared memory named object creation class. Initializes the -//!shared memory segment. Inherits all basic functionality from +//!A basic shared memory named object creation class. Initializes the +//!shared memory segment. Inherits all basic functionality from //!basic_managed_memory_impl*/ template < - class CharType, - class AllocationAlgorithm, + class CharType, + class AllocationAlgorithm, template class IndexType > -class basic_managed_shared_memory - : public ipcdetail::basic_managed_memory_impl +class basic_managed_shared_memory + : public detail::basic_managed_memory_impl ::type::ManagedOpenOrCreateUserOffset> - , private ipcdetail::shmem_open_or_create::type + ,detail::managed_open_or_create_impl::ManagedOpenOrCreateUserOffset> + , private detail::managed_open_or_create_impl { /// @cond - typedef ipcdetail::basic_managed_memory_impl + public: + typedef shared_memory_object device_type; + + private: + typedef detail::basic_managed_memory_impl ::type::ManagedOpenOrCreateUserOffset> base_t; - typedef typename ipcdetail::shmem_open_or_create::type base2_t; + detail::managed_open_or_create_impl::ManagedOpenOrCreateUserOffset> base_t; + typedef detail::managed_open_or_create_impl + base2_t; - typedef ipcdetail::create_open_func create_open_func_t; + typedef detail::create_open_func create_open_func_t; basic_managed_shared_memory *get_this_pointer() { return this; } - public: - typedef shared_memory_object device_type; - typedef typename base_t::size_type size_type; - private: typedef typename base_t::char_ptr_holder_t char_ptr_holder_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_shared_memory) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(basic_managed_shared_memory) /// @endcond public: //functions @@ -93,63 +81,63 @@ class basic_managed_shared_memory basic_managed_shared_memory() {} - //!Creates shared memory and creates and places the segment manager. + //!Creates shared memory and creates and places the segment manager. //!This can throw. - basic_managed_shared_memory(create_only_t, const char *name, - size_type size, const void *addr = 0, const permissions& perm = permissions()) + basic_managed_shared_memory(create_only_t create_only, const char *name, + std::size_t size, const void *addr = 0, const permissions& perm = permissions()) : base_t() - , base2_t(create_only, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), ipcdetail::DoCreate), perm) + , base2_t(create_only, name, size, read_write, addr, + create_open_func_t(get_this_pointer(), detail::DoCreate), perm) {} //!Creates shared memory and creates and places the segment manager if //!segment was not created. If segment was created it connects to the //!segment. //!This can throw. - basic_managed_shared_memory (open_or_create_t, - const char *name, size_type size, + basic_managed_shared_memory (open_or_create_t open_or_create, + const char *name, std::size_t size, const void *addr = 0, const permissions& perm = permissions()) : base_t() - , base2_t(open_or_create, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpenOrCreate), perm) + , base2_t(open_or_create, name, size, read_write, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpenOrCreate), perm) {} //!Connects to a created shared memory and its segment manager. //!in copy_on_write mode. //!This can throw. - basic_managed_shared_memory (open_copy_on_write_t, const char* name, + basic_managed_shared_memory (open_copy_on_write_t, const char* name, const void *addr = 0) : base_t() - , base2_t(open_only, name, copy_on_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + , base2_t(open_only, name, copy_on_write, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Connects to a created shared memory and its segment manager. //!in read-only mode. //!This can throw. - basic_managed_shared_memory (open_read_only_t, const char* name, + basic_managed_shared_memory (open_read_only_t, const char* name, const void *addr = 0) : base_t() - , base2_t(open_only, name, read_only, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + , base2_t(open_only, name, read_only, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Connects to a created shared memory and its segment manager. //!This can throw. - basic_managed_shared_memory (open_only_t, const char* name, + basic_managed_shared_memory (open_only_t open_only, const char* name, const void *addr = 0) : base_t() - , base2_t(open_only, name, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + , base2_t(open_only, name, read_write, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Moves the ownership of "moved"'s managed memory to *this. //!Does not throw - basic_managed_shared_memory(BOOST_RV_REF(basic_managed_shared_memory) moved) + basic_managed_shared_memory(BOOST_INTERPROCESS_RV_REF(basic_managed_shared_memory) moved) { basic_managed_shared_memory tmp; this->swap(moved); @@ -158,9 +146,9 @@ class basic_managed_shared_memory //!Moves the ownership of "moved"'s managed memory to *this. //!Does not throw - basic_managed_shared_memory &operator=(BOOST_RV_REF(basic_managed_shared_memory) moved) + basic_managed_shared_memory &operator=(BOOST_INTERPROCESS_RV_REF(basic_managed_shared_memory) moved) { - basic_managed_shared_memory tmp(boost::move(moved)); + basic_managed_shared_memory tmp(boost::interprocess::move(moved)); this->swap(tmp); return *this; } @@ -174,11 +162,11 @@ class basic_managed_shared_memory } //!Tries to resize the managed shared memory object so that we have - //!room for more objects. + //!room for more objects. //! //!This function is not synchronized so no other thread or process should //!be reading or writing the file - static bool grow(const char *shmname, size_type extra_bytes) + static bool grow(const char *shmname, std::size_t extra_bytes) { return base_t::template grow (shmname, extra_bytes); @@ -193,13 +181,19 @@ class basic_managed_shared_memory return base_t::template shrink_to_fit (shmname); } + + bool flush() + { + return this->base2_t::flush(); + } + /// @cond //!Tries to find a previous named allocation address. Returns a memory //!buffer and the object count. If not found returned pointer is 0. //!Never throws. template - std::pair find (char_ptr_holder_t name) + std::pair find (char_ptr_holder_t name) { if(base2_t::get_mapped_region().get_mode() == read_only){ return base_t::template find_no_lock(name); diff --git a/utils/boost_idb/boost/interprocess/managed_windows_shared_memory.hpp b/utils/boost_idb/boost/interprocess/managed_windows_shared_memory.hpp index e553a707..c28b451f 100644 --- a/utils/boost_idb/boost/interprocess/managed_windows_shared_memory.hpp +++ b/utils/boost_idb/boost/interprocess/managed_windows_shared_memory.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -22,29 +22,13 @@ #include #include #include -#include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include -#include +#include namespace boost { namespace interprocess { -namespace ipcdetail { - -template -struct wshmem_open_or_create -{ - typedef ipcdetail::managed_open_or_create_impl - < windows_shared_memory, AllocationAlgorithm::Alignment, false, false> type; -}; - -} //namespace ipcdetail { - -//!A basic managed windows shared memory creation class. Initializes the -//!shared memory segment. Inherits all basic functionality from +//!A basic managed windows shared memory creation class. Initializes the +//!shared memory segment. Inherits all basic functionality from //!basic_managed_memory_impl //!Unlike basic_managed_shared_memory, it has //!no kernel persistence and the shared memory is destroyed @@ -56,45 +40,44 @@ struct wshmem_open_or_create //!basic_managed_shared_memory can't communicate between them. template < - class CharType, - class AllocationAlgorithm, + class CharType, + class AllocationAlgorithm, template class IndexType > -class basic_managed_windows_shared_memory - : public ipcdetail::basic_managed_memory_impl - < CharType, AllocationAlgorithm, IndexType - , ipcdetail::wshmem_open_or_create::type::ManagedOpenOrCreateUserOffset> +class basic_managed_windows_shared_memory + : public detail::basic_managed_memory_impl + ::ManagedOpenOrCreateUserOffset> { /// @cond private: - typedef ipcdetail::basic_managed_memory_impl + typedef detail::basic_managed_memory_impl ::type::ManagedOpenOrCreateUserOffset> base_t; - typedef ipcdetail::create_open_func create_open_func_t; + detail::managed_open_or_create_impl::ManagedOpenOrCreateUserOffset> base_t; + typedef detail::create_open_func create_open_func_t; basic_managed_windows_shared_memory *get_this_pointer() { return this; } private: typedef typename base_t::char_ptr_holder_t char_ptr_holder_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_windows_shared_memory) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(basic_managed_windows_shared_memory) /// @endcond public: //functions - typedef typename base_t::size_type size_type; //!Default constructor. Does nothing. //!Useful in combination with move semantics basic_managed_windows_shared_memory() {} - //!Creates shared memory and creates and places the segment manager. + //!Creates shared memory and creates and places the segment manager. //!This can throw. basic_managed_windows_shared_memory - (create_only_t, const char *name, - size_type size, const void *addr = 0, const permissions &perm = permissions()) - : m_wshm(create_only, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), ipcdetail::DoCreate), perm) + (create_only_t create_only, const char *name, + std::size_t size, const void *addr = 0, const permissions &perm = permissions()) + : m_wshm(create_only, name, size, read_write, addr, + create_open_func_t(get_this_pointer(), detail::DoCreate), perm) {} //!Creates shared memory and creates and places the segment manager if @@ -102,22 +85,22 @@ class basic_managed_windows_shared_memory //!segment. //!This can throw. basic_managed_windows_shared_memory - (open_or_create_t, - const char *name, size_type size, + (open_or_create_t open_or_create, + const char *name, std::size_t size, const void *addr = 0, const permissions &perm = permissions()) - : m_wshm(open_or_create, name, size, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpenOrCreate), perm) + : m_wshm(open_or_create, name, size, read_write, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpenOrCreate), perm) {} //!Connects to a created shared memory and its segment manager. //!This can throw. basic_managed_windows_shared_memory - (open_only_t, const char* name, const void *addr = 0) - : m_wshm(open_only, name, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) + (open_only_t open_only, const char* name, const void *addr = 0) + : m_wshm(open_only, name, read_write, addr, + create_open_func_t(get_this_pointer(), + detail::DoOpen)) {} //!Connects to a created shared memory and its segment manager @@ -125,8 +108,8 @@ class basic_managed_windows_shared_memory //!This can throw. basic_managed_windows_shared_memory (open_copy_on_write_t, const char* name, const void *addr = 0) - : m_wshm(open_only, name, copy_on_write, addr, - create_open_func_t(get_this_pointer(), ipcdetail::DoOpen)) + : m_wshm(open_only, name, copy_on_write, addr, + create_open_func_t(get_this_pointer(), detail::DoOpen)) {} //!Connects to a created shared memory and its segment manager @@ -135,21 +118,21 @@ class basic_managed_windows_shared_memory basic_managed_windows_shared_memory (open_read_only_t, const char* name, const void *addr = 0) : base_t() - , m_wshm(open_only, name, read_only, addr, - create_open_func_t(get_this_pointer(), ipcdetail::DoOpen)) + , m_wshm(open_only, name, read_only, addr, + create_open_func_t(get_this_pointer(), detail::DoOpen)) {} //!Moves the ownership of "moved"'s managed memory to *this. //!Does not throw basic_managed_windows_shared_memory - (BOOST_RV_REF(basic_managed_windows_shared_memory) moved) + (BOOST_INTERPROCESS_RV_REF(basic_managed_windows_shared_memory) moved) { this->swap(moved); } //!Moves the ownership of "moved"'s managed memory to *this. //!Does not throw - basic_managed_windows_shared_memory &operator=(BOOST_RV_REF(basic_managed_windows_shared_memory) moved) + basic_managed_windows_shared_memory &operator=(BOOST_INTERPROCESS_RV_REF(basic_managed_windows_shared_memory) moved) { - basic_managed_windows_shared_memory tmp(boost::move(moved)); + basic_managed_windows_shared_memory tmp(boost::interprocess::move(moved)); this->swap(tmp); return *this; } @@ -176,7 +159,7 @@ class basic_managed_windows_shared_memory //!buffer and the object count. If not found returned pointer is 0. //!Never throws. template - std::pair find (char_ptr_holder_t name) + std::pair find (char_ptr_holder_t name) { if(m_wshm.get_mapped_region().get_mode() == read_only){ return base_t::template find_no_lock(name); @@ -187,7 +170,7 @@ class basic_managed_windows_shared_memory } private: - typename ipcdetail::wshmem_open_or_create::type m_wshm; + detail::managed_open_or_create_impl m_wshm; /// @endcond }; diff --git a/utils/boost_idb/boost/interprocess/managed_xsi_shared_memory.hpp b/utils/boost_idb/boost/interprocess/managed_xsi_shared_memory.hpp deleted file mode 100644 index 4ec7eba8..00000000 --- a/utils/boost_idb/boost/interprocess/managed_xsi_shared_memory.hpp +++ /dev/null @@ -1,205 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_MANAGED_XSI_SHARED_MEMORY_HPP -#define BOOST_INTERPROCESS_MANAGED_XSI_SHARED_MEMORY_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include - -#if !defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) -#error "This header can't be used in operating systems without XSI (System V) shared memory support" -#endif - -#include -#include -#include -#include -//These includes needed to fulfill default template parameters of -//predeclarations in interprocess_fwd.hpp -#include -#include -#include - -namespace boost { - -namespace interprocess { - -namespace ipcdetail { - -template -struct xsishmem_open_or_create -{ - typedef ipcdetail::managed_open_or_create_impl //!FileBased, StoreDevice - < xsi_shared_memory_file_wrapper, AllocationAlgorithm::Alignment, false, true> type; -}; - -} //namespace ipcdetail { - -//!A basic X/Open System Interface (XSI) shared memory named object creation class. Initializes the -//!shared memory segment. Inherits all basic functionality from -//!basic_managed_memory_impl -template - < - class CharType, - class AllocationAlgorithm, - template class IndexType - > -class basic_managed_xsi_shared_memory - : public ipcdetail::basic_managed_memory_impl - ::type::ManagedOpenOrCreateUserOffset> - , private ipcdetail::xsishmem_open_or_create::type -{ - /// @cond - public: - typedef xsi_shared_memory_file_wrapper device_type; - - public: - typedef typename ipcdetail::xsishmem_open_or_create::type base2_t; - typedef ipcdetail::basic_managed_memory_impl - base_t; - - typedef ipcdetail::create_open_func create_open_func_t; - - basic_managed_xsi_shared_memory *get_this_pointer() - { return this; } - - private: - typedef typename base_t::char_ptr_holder_t char_ptr_holder_t; - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_managed_xsi_shared_memory) - /// @endcond - - public: //functions - typedef typename base_t::size_type size_type; - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~basic_managed_xsi_shared_memory() - {} - - //!Default constructor. Does nothing. - //!Useful in combination with move semantics - basic_managed_xsi_shared_memory() - {} - - //!Creates shared memory and creates and places the segment manager. - //!This can throw. - basic_managed_xsi_shared_memory(create_only_t, const xsi_key &key, - std::size_t size, const void *addr = 0, const permissions& perm = permissions()) - : base_t() - , base2_t(create_only, key, size, read_write, addr, - create_open_func_t(get_this_pointer(), ipcdetail::DoCreate), perm) - {} - - //!Creates shared memory and creates and places the segment manager if - //!segment was not created. If segment was created it connects to the - //!segment. - //!This can throw. - basic_managed_xsi_shared_memory (open_or_create_t, - const xsi_key &key, std::size_t size, - const void *addr = 0, const permissions& perm = permissions()) - : base_t() - , base2_t(open_or_create, key, size, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpenOrCreate), perm) - {} - - //!Connects to a created shared memory and its segment manager. - //!in read-only mode. - //!This can throw. - basic_managed_xsi_shared_memory (open_read_only_t, const xsi_key &key, - const void *addr = 0) - : base_t() - , base2_t(open_only, key, read_only, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) - {} - - //!Connects to a created shared memory and its segment manager. - //!This can throw. - basic_managed_xsi_shared_memory (open_only_t, const xsi_key &key, - const void *addr = 0) - : base_t() - , base2_t(open_only, key, read_write, addr, - create_open_func_t(get_this_pointer(), - ipcdetail::DoOpen)) - {} - - //!Moves the ownership of "moved"'s managed memory to *this. - //!Does not throw - basic_managed_xsi_shared_memory(BOOST_RV_REF(basic_managed_xsi_shared_memory) moved) - { - basic_managed_xsi_shared_memory tmp; - this->swap(moved); - tmp.swap(moved); - } - - //!Moves the ownership of "moved"'s managed memory to *this. - //!Does not throw - basic_managed_xsi_shared_memory &operator=(BOOST_RV_REF(basic_managed_xsi_shared_memory) moved) - { - basic_managed_xsi_shared_memory tmp(boost::move(moved)); - this->swap(tmp); - return *this; - } - - //!Swaps the ownership of the managed shared memories managed by *this and other. - //!Never throws. - void swap(basic_managed_xsi_shared_memory &other) - { - base_t::swap(other); - base2_t::swap(other); - } - - //!Erases a XSI shared memory object identified by shmid - //!from the system. - //!Returns false on error. Never throws - static bool remove(int shmid) - { return device_type::remove(shmid); } - - int get_shmid() const - { return base2_t::get_device().get_shmid(); } - - /// @cond - - //!Tries to find a previous named allocation address. Returns a memory - //!buffer and the object count. If not found returned pointer is 0. - //!Never throws. - template - std::pair find (char_ptr_holder_t name) - { - if(base2_t::get_mapped_region().get_mode() == read_only){ - return base_t::template find_no_lock(name); - } - else{ - return base_t::template find(name); - } - } - - /// @endcond -}; - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_MANAGED_XSI_SHARED_MEMORY_HPP - diff --git a/utils/boost_idb/boost/interprocess/mapped_region.hpp b/utils/boost_idb/boost/interprocess/mapped_region.hpp index f8260d6c..61a8470b 100644 --- a/utils/boost_idb/boost/interprocess/mapped_region.hpp +++ b/utils/boost_idb/boost/interprocess/mapped_region.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,28 +16,14 @@ #include #include -#include +#include #include #include #include -#include -#include -//Some Unixes use caddr_t instead of void * in madvise -// SunOS Tru64 HP-UX AIX -#if defined(sun) || defined(__sun) || defined(__osf__) || defined(__osf) || defined(_hpux) || defined(hpux) || defined(_AIX) -#define BOOST_INTERPROCESS_MADVISE_USES_CADDR_T -#include -#endif - -//A lot of UNIXes have destructive semantics for MADV_DONTNEED, so -//we need to be careful to allow it. -#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) -#define BOOST_INTERPROCESS_MADV_DONTNEED_HAS_NONDESTRUCTIVE_SEMANTICS -#endif +#include -#if defined (BOOST_INTERPROCESS_WINDOWS) +#if (defined BOOST_INTERPROCESS_WINDOWS) # include -# include #else # ifdef BOOST_HAS_UNISTD_H # include @@ -62,159 +48,91 @@ namespace boost { namespace interprocess { /// @cond - -//Solaris declares madvise only in some configurations but defines MADV_XXX, a bit confusing. -//Predeclare it here to avoid any compilation error -#if (defined(sun) || defined(__sun)) && defined(MADV_NORMAL) -extern "C" int madvise(caddr_t, size_t, int); -#endif - -namespace ipcdetail{ class interprocess_tester; } -namespace ipcdetail{ class raw_mapped_region_creator; } +namespace detail{ class interprocess_tester; } +namespace detail{ class raw_mapped_region_creator; } /// @endcond //!The mapped_region class represents a portion or region created from a //!memory_mappable object. -//! -//!The OS can map a region bigger than the requested one, as region must -//!be multiple of the page size, but mapped_region will always refer to -//!the region specified by the user. class mapped_region { /// @cond //Non-copyable - BOOST_MOVABLE_BUT_NOT_COPYABLE(mapped_region) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(mapped_region) /// @endcond public: //!Creates a mapping region of the mapped memory "mapping", starting in - //!offset "offset", and the mapping's size will be "size". The mapping - //!can be opened for read only, read-write or copy-on-write. - //! - //!If an address is specified, both the offset and the address must be - //!multiples of the page size. - //! - //!The map is created using "default_map_options". This flag is OS - //!dependant and it should not be changed unless the user needs to - //!specify special options. - //! - //!In Windows systems "map_options" is a DWORD value passed as - //!"dwDesiredAccess" to "MapViewOfFileEx". If "default_map_options" is passed - //!it's initialized to zero. "map_options" is XORed with FILE_MAP_[COPY|READ|WRITE]. - //! - //!In UNIX systems and POSIX mappings "map_options" is an int value passed as "flags" - //!to "mmap". If "default_map_options" is specified it's initialized to MAP_NOSYNC - //!if that option exists and to zero otherwise. "map_options" XORed with MAP_PRIVATE or MAP_SHARED. - //! - //!In UNIX systems and XSI mappings "map_options" is an int value passed as "shmflg" - //!to "shmat". If "default_map_options" is specified it's initialized to zero. - //!"map_options" is XORed with SHM_RDONLY if needed. - //! - //!The OS could allocate more pages than size/page_size(), but get_address() - //!will always return the address passed in this function (if not null) and - //!get_size() will return the specified size. + //!offset "offset", and the mapping's size will be "size". The mapping + //!can be opened for read-only "read_only" or read-write + //!"read_write. template mapped_region(const MemoryMappable& mapping ,mode_t mode ,offset_t offset = 0 ,std::size_t size = 0 - ,const void *address = 0 - ,map_options_t map_options = default_map_options); + ,const void *address = 0); - //!Default constructor. Address will be 0 (nullptr). - //!Size will be 0. + //!Default constructor. Address and size and offset will be 0. //!Does not throw mapped_region(); - //!Move constructor. *this will be constructed taking ownership of "other"'s + //!Move constructor. *this will be constructed taking ownership of "other"'s //!region and "other" will be left in default constructor state. - mapped_region(BOOST_RV_REF(mapped_region) other) + mapped_region(BOOST_INTERPROCESS_RV_REF(mapped_region) other) #if defined (BOOST_INTERPROCESS_WINDOWS) - : m_base(0), m_size(0) - , m_page_offset(0) + : m_base(0), m_size(0), m_offset(0) + , m_extra_offset(0) , m_mode(read_only) - , m_file_or_mapping_hnd(ipcdetail::invalid_file()) + , m_file_mapping_hnd(detail::invalid_file()) #else - : m_base(0), m_size(0), m_page_offset(0), m_mode(read_only), m_is_xsi(false) + : m_base(MAP_FAILED), m_size(0), m_offset(0), m_extra_offset(0), m_mode(read_only), m_is_xsi(false) #endif { this->swap(other); } + //!Destroys the mapped region. //!Does not throw ~mapped_region(); //!Move assignment. If *this owns a memory mapped region, it will be //!destroyed and it will take ownership of "other"'s memory mapped region. - mapped_region &operator=(BOOST_RV_REF(mapped_region) other) + mapped_region &operator=(BOOST_INTERPROCESS_RV_REF(mapped_region) other) { - mapped_region tmp(boost::move(other)); + mapped_region tmp(boost::interprocess::move(other)); this->swap(tmp); return *this; } - //!Swaps the mapped_region with another - //!mapped region - void swap(mapped_region &other); - - //!Returns the size of the mapping. Never throws. + //!Returns the size of the mapping. Note for windows users: If + //!windows_shared_memory is mapped using 0 as the size, it returns 0 + //!because the size is unknown. Never throws. std::size_t get_size() const; //!Returns the base address of the mapping. //!Never throws. void* get_address() const; - //!Returns the mode of the mapping used to construct the mapped region. + //!Returns the offset of the mapping from the beginning of the + //!mapped memory. Never throws. + offset_t get_offset() const; + + //!Returns the mode of the mapping used to construct the mapped file. //!Never throws. mode_t get_mode() const; - //!Flushes to the disk a byte range within the mapped memory. - //!If 'async' is true, the function will return before flushing operation is completed - //!If 'async' is false, function will return once data has been written into the underlying - //!device (i.e., in mapped files OS cached information is written to disk). - //!Never throws. Returns false if operation could not be performed. - bool flush(std::size_t mapping_offset = 0, std::size_t numbytes = 0, bool async = true); - - //!Shrinks current mapped region. If after shrinking there is no longer need for a previously - //!mapped memory page, accessing that page can trigger a segmentation fault. - //!Depending on the OS, this operation might fail (XSI shared memory), it can decommit storage - //!and free a portion of the virtual address space (e.g.POSIX) or this - //!function can release some physical memory wihout freeing any virtual address space(Windows). - //!Returns true on success. Never throws. - bool shrink_by(std::size_t bytes, bool from_back = true); - - //!This enum specifies region usage behaviors that an application can specify - //!to the mapped region implementation. - enum advice_types{ - //!Specifies that the application has no advice to give on its behavior with respect to - //!the region. It is the default characteristic if no advice is given for a range of memory. - advice_normal, - //!Specifies that the application expects to access the region sequentially from - //!lower addresses to higher addresses. The implementation can lower the priority of - //!preceding pages within the region once a page have been accessed. - advice_sequential, - //!Specifies that the application expects to access the region in a random order, - //!and prefetching is likely not advantageous. - advice_random, - //!Specifies that the application expects to access the region in the near future. - //!The implementation can prefetch pages of the region. - advice_willneed, - //!Specifies that the application expects that it will not access the region in the near future. - //!The implementation can unload pages within the range to save system resources. - advice_dontneed - }; + //!Flushes to the disk a byte range within the mapped memory. + //!Never throws + bool flush(std::size_t mapping_offset = 0, std::size_t numbytes = 0); - //!Advises the implementation on the expected behavior of the application with respect to the data - //!in the region. The implementation may use this information to optimize handling of the region data. - //!This function has no effect on the semantics of access to memory in the region, although it may affect - //!the performance of access. - //!If the advise type is not known to the implementation, the function returns false. True otherwise. - bool advise(advice_types advise); + //!Swaps the mapped_region with another + //!mapped region + void swap(mapped_region &other); //!Returns the size of the page. This size is the minimum memory that - //!will be used by the system when mapping a memory mappable source and - //!will restrict the address and the offset to map. + //!will be used by the system when mapping a memory mappable source. static std::size_t get_page_size(); /// @cond @@ -222,14 +140,6 @@ class mapped_region //!Closes a previously opened memory mapping. Never throws void priv_close(); - void* priv_map_address() const; - std::size_t priv_map_size() const; - bool priv_flush_param_check(std::size_t mapping_offset, void *&addr, std::size_t &numbytes) const; - bool priv_shrink_param_check(std::size_t bytes, bool from_back, void *&shrink_page_start, std::size_t &shrink_page_bytes); - static void priv_size_from_mapping_size - (offset_t mapping_size, offset_t offset, offset_t page_offset, std::size_t &size); - static offset_t priv_page_offset_addr_fixup(offset_t page_offset, const void *&addr); - template struct page_size_holder { @@ -239,21 +149,18 @@ class mapped_region void* m_base; std::size_t m_size; - std::size_t m_page_offset; + offset_t m_offset; + offset_t m_extra_offset; mode_t m_mode; - #if defined(BOOST_INTERPROCESS_WINDOWS) - file_handle_t m_file_or_mapping_hnd; + #if (defined BOOST_INTERPROCESS_WINDOWS) + file_handle_t m_file_mapping_hnd; #else bool m_is_xsi; #endif - friend class ipcdetail::interprocess_tester; - friend class ipcdetail::raw_mapped_region_creator; + friend class detail::interprocess_tester; + friend class detail::raw_mapped_region_creator; void dont_close_on_destruction(); - #if defined(BOOST_INTERPROCESS_WINDOWS) && !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) - template - static void destroy_syncs_in_range(const void *addr, std::size_t size); - #endif /// @endcond }; @@ -262,112 +169,26 @@ class mapped_region inline void swap(mapped_region &x, mapped_region &y) { x.swap(y); } -inline mapped_region::~mapped_region() +inline mapped_region::~mapped_region() { this->priv_close(); } -inline std::size_t mapped_region::get_size() const +inline std::size_t mapped_region::get_size() const { return m_size; } -inline mode_t mapped_region::get_mode() const +inline offset_t mapped_region::get_offset() const +{ return m_offset; } + +inline mode_t mapped_region::get_mode() const { return m_mode; } -inline void* mapped_region::get_address() const +inline void* mapped_region::get_address() const { return m_base; } -inline void* mapped_region::priv_map_address() const -{ return static_cast(m_base) - m_page_offset; } - -inline std::size_t mapped_region::priv_map_size() const -{ return m_size + m_page_offset; } - -inline bool mapped_region::priv_flush_param_check - (std::size_t mapping_offset, void *&addr, std::size_t &numbytes) const -{ - //Check some errors - if(m_base == 0) - return false; - - if(mapping_offset >= m_size || (mapping_offset + numbytes) > m_size){ - return false; - } - - //Update flush size if the user does not provide it - if(numbytes == 0){ - numbytes = m_size - mapping_offset; - } - addr = (char*)this->priv_map_address() + mapping_offset; - numbytes += m_page_offset; - return true; -} - -inline bool mapped_region::priv_shrink_param_check - (std::size_t bytes, bool from_back, void *&shrink_page_start, std::size_t &shrink_page_bytes) -{ - //Check some errors - if(m_base == 0 || bytes > m_size){ - return false; - } - else if(bytes == m_size){ - this->priv_close(); - return true; - } - else{ - const std::size_t page_size = mapped_region::get_page_size(); - if(from_back){ - const std::size_t new_pages = (m_size + m_page_offset - bytes - 1)/page_size + 1; - shrink_page_start = static_cast(this->priv_map_address()) + new_pages*page_size; - shrink_page_bytes = m_page_offset + m_size - new_pages*page_size; - m_size -= bytes; - } - else{ - shrink_page_start = this->priv_map_address(); - m_page_offset += bytes; - shrink_page_bytes = (m_page_offset/page_size)*page_size; - m_page_offset = m_page_offset % page_size; - m_size -= bytes; - m_base = static_cast(m_base) + bytes; - BOOST_ASSERT(shrink_page_bytes%page_size == 0); - } - return true; - } -} - -inline void mapped_region::priv_size_from_mapping_size - (offset_t mapping_size, offset_t offset, offset_t page_offset, std::size_t &size) -{ - //Check if mapping size fits in the user address space - //as offset_t is the maximum file size and its signed. - if(mapping_size < offset || - boost::uintmax_t(mapping_size - (offset - page_offset)) > - boost::uintmax_t(std::size_t(-1))){ - error_info err(size_error); - throw interprocess_exception(err); - } - size = static_cast(mapping_size - (offset - page_offset)); -} - -inline offset_t mapped_region::priv_page_offset_addr_fixup(offset_t offset, const void *&address) -{ - //We can't map any offset so we have to obtain system's - //memory granularity - const std::size_t page_size = mapped_region::get_page_size(); - - //We calculate the difference between demanded and valid offset - //(always less than a page in std::size_t, thus, representable by std::size_t) - const std::size_t page_offset = - static_cast(offset - (offset / page_size) * page_size); - //Update the mapping address - if(address){ - address = static_cast(address) - page_offset; - } - return page_offset; -} - #if defined (BOOST_INTERPROCESS_WINDOWS) inline mapped_region::mapped_region() - : m_base(0), m_size(0), m_page_offset(0), m_mode(read_only) - , m_file_or_mapping_hnd(ipcdetail::invalid_file()) + : m_base(0), m_size(0), m_offset(0), m_extra_offset(0), m_mode(read_only) + , m_file_mapping_hnd(detail::invalid_file()) {} template @@ -384,178 +205,170 @@ inline mapped_region::mapped_region ,mode_t mode ,offset_t offset ,std::size_t size - ,const void *address - ,map_options_t map_options) - : m_base(0), m_size(0), m_page_offset(0), m_mode(mode) - , m_file_or_mapping_hnd(ipcdetail::invalid_file()) + ,const void *address) + : m_base(0), m_size(0), m_offset(0), m_extra_offset(0), m_mode(mode) + , m_file_mapping_hnd(detail::invalid_file()) { mapping_handle_t mhandle = mapping.get_mapping_handle(); - { - file_handle_t native_mapping_handle = 0; - - //Set accesses - //For "create_file_mapping" - unsigned long protection = 0; - //For "mapviewoffile" - unsigned long map_access = map_options == default_map_options ? 0 : map_options; - - switch(mode) - { - case read_only: - case read_private: - protection |= winapi::page_readonly; - map_access |= winapi::file_map_read; - break; - case read_write: - protection |= winapi::page_readwrite; - map_access |= winapi::file_map_write; - break; - case copy_on_write: - protection |= winapi::page_writecopy; - map_access |= winapi::file_map_copy; - break; - default: - { - error_info err(mode_error); - throw interprocess_exception(err); - } - break; - } + file_handle_t native_mapping_handle = 0; + + //Set accesses + unsigned long file_map_access = 0; + unsigned long map_access = 0; - //For file mapping (including emulated shared memory through temporary files), - //the device is a file handle so we need to obtain file's size and call create_file_mapping - //to obtain the mapping handle. - //For files we don't need the file mapping after mapping the memory, as the file is there - //so we'll program the handle close - void * handle_to_close = winapi::invalid_handle_value; - if(!mhandle.is_shm){ - //Create mapping handle - native_mapping_handle = winapi::create_file_mapping - ( ipcdetail::file_handle_from_mapping_handle(mapping.get_mapping_handle()) - , protection, 0, 0, 0); - - //Check if all is correct - if(!native_mapping_handle){ - error_info err = winapi::get_last_error(); + switch(mode) + { + case read_only: + case read_private: + file_map_access |= winapi::page_readonly; + map_access |= winapi::file_map_read; + break; + case read_write: + file_map_access |= winapi::page_readwrite; + map_access |= winapi::file_map_write; + break; + case copy_on_write: + file_map_access |= winapi::page_writecopy; + map_access |= winapi::file_map_copy; + break; + default: + { + error_info err(mode_error); throw interprocess_exception(err); } - handle_to_close = native_mapping_handle; - } - else{ - //For windows_shared_memory the device handle is already a mapping handle - //and we need to maintain it - native_mapping_handle = mhandle.handle; - } - //RAII handle close on scope exit - const winapi::handle_closer close_handle(handle_to_close); - (void)close_handle; - - const offset_t page_offset = priv_page_offset_addr_fixup(offset, address); + break; + } - //Obtain mapping size if user provides 0 size + if(!mhandle.is_shm){ + //Update mapping size if the user does not specify it if(size == 0){ - offset_t mapping_size; - if(!winapi::get_file_mapping_size(native_mapping_handle, mapping_size)){ - error_info err = winapi::get_last_error(); + __int64 total_size; + if(!winapi::get_file_size + (detail::file_handle_from_mapping_handle + (mapping.get_mapping_handle()), total_size)){ + error_info err(winapi::get_last_error()); + throw interprocess_exception(err); + } + + if(static_cast(total_size) > + (std::numeric_limits::max)()){ + error_info err(size_error); throw interprocess_exception(err); } - //This can throw - priv_size_from_mapping_size(mapping_size, offset, page_offset, size); + size = static_cast(total_size - offset); } - //Map with new offsets and size - void *base = winapi::map_view_of_file_ex - (native_mapping_handle, - map_access, - offset - page_offset, - static_cast(page_offset + size), - const_cast(address)); - //Check error - if(!base){ + //Create file mapping + native_mapping_handle = + winapi::create_file_mapping + (detail::file_handle_from_mapping_handle(mapping.get_mapping_handle()), file_map_access, 0, 0, 0, 0); + + //Check if all is correct + if(!native_mapping_handle){ error_info err = winapi::get_last_error(); + this->priv_close(); throw interprocess_exception(err); } + } + + //We can't map any offset so we have to obtain system's + //memory granularity + unsigned long granularity = 0; + unsigned long foffset_low; + unsigned long foffset_high; - //Calculate new base for the user - m_base = static_cast(base) + page_offset; - m_page_offset = page_offset; - m_size = size; + winapi::system_info info; + get_system_info(&info); + granularity = info.dwAllocationGranularity; + + //Now we calculate valid offsets + foffset_low = (unsigned long)(offset / granularity) * granularity; + foffset_high = (unsigned long)(((offset / granularity) * granularity) >> 32); + + //We calculate the difference between demanded and valid offset + m_extra_offset = (offset - (offset / granularity) * granularity); + + //Store user values in memory + m_offset = offset; + m_size = size; + + //Update the mapping address + if(address){ + address = static_cast(address) - m_extra_offset; + } + + if(mhandle.is_shm){ + //Windows shared memory needs the duplication of the handle if we want to + //make mapped_region independent from the mappable device + if(!winapi::duplicate_current_process_handle(mhandle.handle, &m_file_mapping_hnd)){ + error_info err = winapi::get_last_error(); + this->priv_close(); + throw interprocess_exception(err); + } + native_mapping_handle = m_file_mapping_hnd; + } + + //Map with new offsets and size + m_base = winapi::map_view_of_file_ex + (native_mapping_handle, + map_access, + foffset_high, + foffset_low, + m_size ? static_cast(m_extra_offset + m_size) : 0, + const_cast(address)); + + if(!mhandle.is_shm){ + //For files we don't need the file mapping anymore + winapi::close_handle(native_mapping_handle); } - //Windows shared memory needs the duplication of the handle if we want to - //make mapped_region independent from the mappable device - // - //For mapped files, we duplicate the file handle to be able to FlushFileBuffers - if(!winapi::duplicate_current_process_handle(mhandle.handle, &m_file_or_mapping_hnd)){ + + //Check error + if(!m_base){ error_info err = winapi::get_last_error(); this->priv_close(); throw interprocess_exception(err); } + + //Calculate new base for the user + m_base = static_cast(m_base) + m_extra_offset; } -inline bool mapped_region::flush(std::size_t mapping_offset, std::size_t numbytes, bool async) +inline bool mapped_region::flush(std::size_t mapping_offset, std::size_t numbytes) { - void *addr; - if(!this->priv_flush_param_check(mapping_offset, addr, numbytes)){ - return false; - } - //Flush it all - if(!winapi::flush_view_of_file(addr, numbytes)){ + //Check some errors + if(m_base == 0) return false; - } - //m_file_or_mapping_hnd can be a file handle or a mapping handle. - //so flushing file buffers has only sense for files... - else if(!async && m_file_or_mapping_hnd != winapi::invalid_handle_value && - winapi::get_file_type(m_file_or_mapping_hnd) == winapi::file_type_disk){ - return winapi::flush_file_buffers(m_file_or_mapping_hnd); - } - return true; -} -inline bool mapped_region::shrink_by(std::size_t bytes, bool from_back) -{ - void *shrink_page_start; - std::size_t shrink_page_bytes; - if(!this->priv_shrink_param_check(bytes, from_back, shrink_page_start, shrink_page_bytes)){ + if(mapping_offset >= m_size || (mapping_offset + numbytes) > m_size){ return false; } - else if(shrink_page_bytes){ - //In Windows, we can't decommit the storage or release the virtual address space, - //the best we can do is try to remove some memory from the process working set. - //With a bit of luck we can free some physical memory. - unsigned long old_protect_ignored; - bool b_ret = winapi::virtual_unlock(shrink_page_start, shrink_page_bytes) - || (winapi::get_last_error() == winapi::error_not_locked); - (void)old_protect_ignored; - //Change page protection to forbid any further access - b_ret = b_ret && winapi::virtual_protect - (shrink_page_start, shrink_page_bytes, winapi::page_noaccess, old_protect_ignored); - return b_ret; + + //Update flush size if the user does not provide it + if(m_size == 0){ + numbytes = 0; } - else{ - return true; + else if(numbytes == 0){ + numbytes = m_size - mapping_offset; } -} -inline bool mapped_region::advise(advice_types) -{ - //Windows has no madvise/posix_madvise equivalent - return false; + //Flush it all + return winapi::flush_view_of_file + (static_cast(m_base)+mapping_offset, + static_cast(numbytes)); } inline void mapped_region::priv_close() { if(m_base){ - void *addr = this->priv_map_address(); - #if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) - mapped_region::destroy_syncs_in_range<0>(addr, m_size); - #endif - winapi::unmap_view_of_file(addr); + winapi::unmap_view_of_file(static_cast(m_base) - m_extra_offset); m_base = 0; } - if(m_file_or_mapping_hnd != ipcdetail::invalid_file()){ - winapi::close_handle(m_file_or_mapping_hnd); - m_file_or_mapping_hnd = ipcdetail::invalid_file(); - } + #if (defined BOOST_INTERPROCESS_WINDOWS) + if(m_file_mapping_hnd != detail::invalid_file()){ + winapi::close_handle(m_file_mapping_hnd); + m_file_mapping_hnd = detail::invalid_file(); + } + #endif } inline void mapped_region::dont_close_on_destruction() @@ -564,7 +377,7 @@ inline void mapped_region::dont_close_on_destruction() #else //#if (defined BOOST_INTERPROCESS_WINDOWS) inline mapped_region::mapped_region() - : m_base(0), m_size(0), m_page_offset(0), m_mode(read_only), m_is_xsi(false) + : m_base(MAP_FAILED), m_size(0), m_offset(0), m_extra_offset(0), m_mode(read_only), m_is_xsi(false) {} template @@ -573,13 +386,12 @@ inline std::size_t mapped_region::page_size_holder::get_page_size() template inline mapped_region::mapped_region - ( const MemoryMappable &mapping - , mode_t mode - , offset_t offset - , std::size_t size - , const void *address - , map_options_t map_options) - : m_base(0), m_size(0), m_page_offset(0), m_mode(mode), m_is_xsi(false) + (const MemoryMappable &mapping, + mode_t mode, + offset_t offset, + std::size_t size, + const void *address) + : m_base(MAP_FAILED), m_size(0), m_offset(0), m_extra_offset(0), m_mode(mode), m_is_xsi(false) { mapping_handle_t map_hnd = mapping.get_mapping_handle(); @@ -602,7 +414,7 @@ inline mapped_region::mapped_region throw interprocess_exception(err); } //Calculate flag - int flag = map_options == default_map_options ? 0 : map_options; + int flag = 0; if(m_mode == read_only){ flag |= SHM_RDONLY; } @@ -618,38 +430,33 @@ inline mapped_region::mapped_region } //Update members m_base = base; + m_offset = offset; m_size = size; m_mode = mode; - m_page_offset = 0; + m_extra_offset = 0; m_is_xsi = true; return; } #endif //ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS - - //We calculate the difference between demanded and valid offset - const offset_t page_offset = priv_page_offset_addr_fixup(offset, address); - if(size == 0){ struct ::stat buf; if(0 != fstat(map_hnd.handle, &buf)){ error_info err(system_error_code()); throw interprocess_exception(err); } - //This can throw - priv_size_from_mapping_size(buf.st_size, offset, page_offset, size); - } + std::size_t filesize = (std::size_t)buf.st_size; + if((std::size_t)offset >= filesize){ + error_info err(size_error); + throw interprocess_exception(err); + } - #ifdef MAP_NOSYNC - #define BOOST_INTERPROCESS_MAP_NOSYNC MAP_NOSYNC - #else - #define BOOST_INTERPROCESS_MAP_NOSYNC 0 - #endif //MAP_NOSYNC + filesize -= offset; + size = filesize; + } //Create new mapping int prot = 0; - int flags = map_options == default_map_options ? BOOST_INTERPROCESS_MAP_NOSYNC : map_options; - - #undef BOOST_INTERPROCESS_MAP_NOSYNC + int flags = 0; switch(mode) { @@ -681,139 +488,65 @@ inline mapped_region::mapped_region break; } + //We calculate the difference between demanded and valid offset + std::size_t page_size = this->get_page_size(); + m_extra_offset = (offset - (offset / page_size) * page_size); + + //Store user values in memory + m_offset = offset; + m_size = size; + + //Update the mapping address + if(address){ + address = static_cast(address) - m_extra_offset; + } + //Map it to the address space - void* base = mmap ( const_cast(address) - , static_cast(page_offset + size) - , prot - , flags - , mapping.get_mapping_handle().handle - , offset - page_offset); + m_base = mmap ( const_cast(address) + , static_cast(m_extra_offset + m_size) + , prot + , flags + , mapping.get_mapping_handle().handle + , offset - m_extra_offset); //Check if mapping was successful - if(base == MAP_FAILED){ + if(m_base == MAP_FAILED){ error_info err = system_error_code(); + this->priv_close(); throw interprocess_exception(err); } //Calculate new base for the user - m_base = static_cast(base) + page_offset; - m_page_offset = page_offset; + const void *old_base = m_base; + m_base = static_cast(m_base) + m_extra_offset; + m_offset = offset; m_size = size; //Check for fixed mapping error - if(address && (base != address)){ - error_info err(busy_error); + if(address && (old_base != address)){ + error_info err = system_error_code(); this->priv_close(); throw interprocess_exception(err); } } -inline bool mapped_region::shrink_by(std::size_t bytes, bool from_back) +inline bool mapped_region::flush(std::size_t mapping_offset, std::size_t numbytes) { - void *shrink_page_start = 0; - std::size_t shrink_page_bytes = 0; - if(m_is_xsi || !this->priv_shrink_param_check(bytes, from_back, shrink_page_start, shrink_page_bytes)){ + if(mapping_offset >= m_size || (mapping_offset+numbytes)> m_size){ return false; } - else if(shrink_page_bytes){ - //In UNIX we can decommit and free virtual address space. - return 0 == munmap(shrink_page_start, shrink_page_bytes); - } - else{ - return true; - } -} -inline bool mapped_region::flush(std::size_t mapping_offset, std::size_t numbytes, bool async) -{ - void *addr; - if(m_is_xsi || !this->priv_flush_param_check(mapping_offset, addr, numbytes)){ - return false; + if(numbytes == 0){ + numbytes = m_size - mapping_offset; } //Flush it all - return msync(addr, numbytes, async ? MS_ASYNC : MS_SYNC) == 0; -} - -inline bool mapped_region::advise(advice_types advice) -{ - int unix_advice = 0; - //Modes; 0: none, 2: posix, 1: madvise - const unsigned int mode_none = 0; - const unsigned int mode_padv = 1; - const unsigned int mode_madv = 2; - unsigned int mode = mode_none; - //Choose advice either from POSIX (preferred) or native Unix - switch(advice){ - case advice_normal: - #if defined(POSIX_MADV_NORMAL) - unix_advice = POSIX_MADV_NORMAL; - mode = mode_padv; - #elif defined(MADV_NORMAL) - unix_advice = MADV_NORMAL; - mode = mode_madv; - #endif - break; - case advice_sequential: - #if defined(POSIX_MADV_SEQUENTIAL) - unix_advice = POSIX_MADV_SEQUENTIAL; - mode = mode_padv; - #elif defined(MADV_SEQUENTIAL) - unix_advice = MADV_SEQUENTIAL; - mode = mode_madv; - #endif - break; - case advice_random: - #if defined(POSIX_MADV_RANDOM) - unix_advice = POSIX_MADV_RANDOM; - mode = mode_padv; - #elif defined(MADV_RANDOM) - unix_advice = MADV_RANDOM; - mode = mode_madv; - #endif - break; - case advice_willneed: - #if defined(POSIX_MADV_WILLNEED) - unix_advice = POSIX_MADV_WILLNEED; - mode = mode_padv; - #elif defined(MADV_WILLNEED) - unix_advice = MADV_WILLNEED; - mode = mode_madv; - #endif - break; - case advice_dontneed: - #if defined(POSIX_MADV_DONTNEED) - unix_advice = POSIX_MADV_DONTNEED; - mode = mode_padv; - #elif defined(MADV_DONTNEED) && defined(BOOST_INTERPROCESS_MADV_DONTNEED_HAS_NONDESTRUCTIVE_SEMANTICS) - unix_advice = MADV_DONTNEED; - mode = mode_madv; - #endif - break; - default: - return false; - } - switch(mode){ - #if defined(POSIX_MADV_NORMAL) - case mode_padv: - return 0 == posix_madvise(this->priv_map_address(), this->priv_map_size(), unix_advice); - #endif - #if defined(MADV_NORMAL) - case mode_madv: - return 0 == madvise( - #if defined(BOOST_INTERPROCESS_MADVISE_USES_CADDR_T) - (caddr_t) - #endif - this->priv_map_address(), this->priv_map_size(), unix_advice); - #endif - default: - return false; - - } + return msync(static_cast(m_base)+mapping_offset, + numbytes, MS_ASYNC) == 0; } inline void mapped_region::priv_close() { - if(m_base != 0){ + if(m_base != MAP_FAILED){ #ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS if(m_is_xsi){ int ret = ::shmdt(m_base); @@ -822,13 +555,13 @@ inline void mapped_region::priv_close() return; } #endif //#ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS - munmap(this->priv_map_address(), this->priv_map_size()); - m_base = 0; + munmap(static_cast(m_base) - m_extra_offset, m_size + m_extra_offset); + m_base = MAP_FAILED; } } inline void mapped_region::dont_close_on_destruction() -{ m_base = 0; } +{ m_base = MAP_FAILED; } #endif //##if (defined BOOST_INTERPROCESS_WINDOWS) @@ -846,14 +579,15 @@ inline std::size_t mapped_region::get_page_size() inline void mapped_region::swap(mapped_region &other) { - ipcdetail::do_swap(this->m_base, other.m_base); - ipcdetail::do_swap(this->m_size, other.m_size); - ipcdetail::do_swap(this->m_page_offset, other.m_page_offset); - ipcdetail::do_swap(this->m_mode, other.m_mode); + detail::do_swap(this->m_base, other.m_base); + detail::do_swap(this->m_size, other.m_size); + detail::do_swap(this->m_offset, other.m_offset); + detail::do_swap(this->m_extra_offset, other.m_extra_offset); + detail::do_swap(this->m_mode, other.m_mode); #if (defined BOOST_INTERPROCESS_WINDOWS) - ipcdetail::do_swap(this->m_file_or_mapping_hnd, other.m_file_or_mapping_hnd); + detail::do_swap(this->m_file_mapping_hnd, other.m_file_mapping_hnd); #else - ipcdetail::do_swap(this->m_is_xsi, other.m_is_xsi); + detail::do_swap(this->m_is_xsi, other.m_is_xsi); #endif } @@ -862,9 +596,6 @@ struct null_mapped_region_function { bool operator()(void *, std::size_t , bool) const { return true; } - - std::size_t get_min_size() const - { return 0; } }; /// @endcond @@ -876,32 +607,3 @@ struct null_mapped_region_function #endif //BOOST_INTERPROCESS_MAPPED_REGION_HPP -#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) - -#ifndef BOOST_INTERPROCESS_MAPPED_REGION_EXT_HPP -#define BOOST_INTERPROCESS_MAPPED_REGION_EXT_HPP - -#if defined(BOOST_INTERPROCESS_WINDOWS) && !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) -# include -# include - -namespace boost { -namespace interprocess { - -template -inline void mapped_region::destroy_syncs_in_range(const void *addr, std::size_t size) -{ - ipcdetail::sync_handles &handles = - ipcdetail::windows_intermodule_singleton::get(); - handles.destroy_syncs_in_range(addr, size); -} - -} //namespace interprocess { -} //namespace boost { - -#endif //defined(BOOST_INTERPROCESS_WINDOWS) && !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) - -#endif //#ifdef BOOST_INTERPROCESS_MAPPED_REGION_EXT_HPP - -#endif //#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) - diff --git a/utils/boost_idb/boost/interprocess/mem_algo/detail/mem_algo_common.hpp b/utils/boost_idb/boost/interprocess/mem_algo/detail/mem_algo_common.hpp index a6936ec3..beaaf521 100644 --- a/utils/boost_idb/boost/interprocess/mem_algo/detail/mem_algo_common.hpp +++ b/utils/boost_idb/boost/interprocess/mem_algo/detail/mem_algo_common.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -24,9 +24,8 @@ #include #include #include -#include +#include #include -#include #include #include #include @@ -39,38 +38,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { - -template -class basic_multiallocation_chain - : public boost::container::container_detail:: - basic_multiallocation_chain -{ - BOOST_MOVABLE_BUT_NOT_COPYABLE(basic_multiallocation_chain) - typedef boost::container::container_detail:: - basic_multiallocation_chain base_t; - public: - - basic_multiallocation_chain() - : base_t() - {} - - basic_multiallocation_chain(BOOST_RV_REF(basic_multiallocation_chain) other) - : base_t(::boost::move(static_cast(other))) - {} - - basic_multiallocation_chain& operator=(BOOST_RV_REF(basic_multiallocation_chain) other) - { - this->base_t::operator=(::boost::move(static_cast(other))); - return *this; - } - - void *pop_front() - { - return boost::interprocess::ipcdetail::to_raw_pointer(this->base_t::pop_front()); - } -}; - +namespace detail { //!This class implements several allocation functions shared by different algorithms //!(aligned allocation, multiple allocation...). @@ -82,20 +50,19 @@ class memory_algorithm_common typedef typename MemoryAlgorithm::block_ctrl block_ctrl; typedef typename MemoryAlgorithm::multiallocation_chain multiallocation_chain; typedef memory_algorithm_common this_type; - typedef typename MemoryAlgorithm::size_type size_type; - static const size_type Alignment = MemoryAlgorithm::Alignment; - static const size_type MinBlockUnits = MemoryAlgorithm::MinBlockUnits; - static const size_type AllocatedCtrlBytes = MemoryAlgorithm::AllocatedCtrlBytes; - static const size_type AllocatedCtrlUnits = MemoryAlgorithm::AllocatedCtrlUnits; - static const size_type BlockCtrlBytes = MemoryAlgorithm::BlockCtrlBytes; - static const size_type BlockCtrlUnits = MemoryAlgorithm::BlockCtrlUnits; - static const size_type UsableByPreviousChunk = MemoryAlgorithm::UsableByPreviousChunk; + static const std::size_t Alignment = MemoryAlgorithm::Alignment; + static const std::size_t MinBlockUnits = MemoryAlgorithm::MinBlockUnits; + static const std::size_t AllocatedCtrlBytes = MemoryAlgorithm::AllocatedCtrlBytes; + static const std::size_t AllocatedCtrlUnits = MemoryAlgorithm::AllocatedCtrlUnits; + static const std::size_t BlockCtrlBytes = MemoryAlgorithm::BlockCtrlBytes; + static const std::size_t BlockCtrlUnits = MemoryAlgorithm::BlockCtrlUnits; + static const std::size_t UsableByPreviousChunk = MemoryAlgorithm::UsableByPreviousChunk; static void assert_alignment(const void *ptr) { assert_alignment((std::size_t)ptr); } - static void assert_alignment(size_type uint_ptr) + static void assert_alignment(std::size_t uint_ptr) { (void)uint_ptr; BOOST_ASSERT(uint_ptr % Alignment == 0); @@ -104,40 +71,40 @@ class memory_algorithm_common static bool check_alignment(const void *ptr) { return (((std::size_t)ptr) % Alignment == 0); } - static size_type ceil_units(size_type size) - { return get_rounded_size(size, Alignment)/Alignment; } + static std::size_t ceil_units(std::size_t size) + { return detail::get_rounded_size(size, Alignment)/Alignment; } - static size_type floor_units(size_type size) + static std::size_t floor_units(std::size_t size) { return size/Alignment; } - static size_type multiple_of_units(size_type size) - { return get_rounded_size(size, Alignment); } + static std::size_t multiple_of_units(std::size_t size) + { return detail::get_rounded_size(size, Alignment); } - static void allocate_many - (MemoryAlgorithm *memory_algo, size_type elem_bytes, size_type n_elements, multiallocation_chain &chain) + static multiallocation_chain allocate_many + (MemoryAlgorithm *memory_algo, std::size_t elem_bytes, std::size_t n_elements) { - return this_type::priv_allocate_many(memory_algo, &elem_bytes, n_elements, 0, chain); + return this_type::priv_allocate_many(memory_algo, &elem_bytes, n_elements, 0); } - static void deallocate_many(MemoryAlgorithm *memory_algo, multiallocation_chain &chain) + static void deallocate_many(MemoryAlgorithm *memory_algo, multiallocation_chain chain) { - return this_type::priv_deallocate_many(memory_algo, chain); + return this_type::priv_deallocate_many(memory_algo, boost::interprocess::move(chain)); } static bool calculate_lcm_and_needs_backwards_lcmed - (size_type backwards_multiple, size_type received_size, size_type size_to_achieve, - size_type &lcm_out, size_type &needs_backwards_lcmed_out) + (std::size_t backwards_multiple, std::size_t received_size, std::size_t size_to_achieve, + std::size_t &lcm_out, std::size_t &needs_backwards_lcmed_out) { - // Now calculate lcm_val - size_type max = backwards_multiple; - size_type min = Alignment; - size_type needs_backwards; - size_type needs_backwards_lcmed; - size_type lcm_val; - size_type current_forward; + // Now calculate lcm + std::size_t max = backwards_multiple; + std::size_t min = Alignment; + std::size_t needs_backwards; + std::size_t needs_backwards_lcmed; + std::size_t lcm; + std::size_t current_forward; //Swap if necessary if(max < min){ - size_type tmp = min; + std::size_t tmp = min; min = max; max = tmp; } @@ -147,47 +114,47 @@ class memory_algorithm_common return false; } - lcm_val = max; + lcm = max; //If we want to use minbytes data to get a buffer between maxbytes - //and minbytes if maxbytes can't be achieved, calculate the + //and minbytes if maxbytes can't be achieved, calculate the //biggest of all possibilities - current_forward = get_truncated_size_po2(received_size, backwards_multiple); + current_forward = detail::get_truncated_size_po2(received_size, backwards_multiple); needs_backwards = size_to_achieve - current_forward; BOOST_ASSERT((needs_backwards % backwards_multiple) == 0); - needs_backwards_lcmed = get_rounded_size_po2(needs_backwards, lcm_val); - lcm_out = lcm_val; + needs_backwards_lcmed = detail::get_rounded_size_po2(needs_backwards, lcm); + lcm_out = lcm; needs_backwards_lcmed_out = needs_backwards_lcmed; return true; } //Check if it's multiple of alignment else if((backwards_multiple & (Alignment - 1u)) == 0){ - lcm_val = backwards_multiple; - current_forward = get_truncated_size(received_size, backwards_multiple); - //No need to round needs_backwards because backwards_multiple == lcm_val + lcm = backwards_multiple; + current_forward = detail::get_truncated_size(received_size, backwards_multiple); + //No need to round needs_backwards because backwards_multiple == lcm needs_backwards_lcmed = needs_backwards = size_to_achieve - current_forward; BOOST_ASSERT((needs_backwards_lcmed & (Alignment - 1u)) == 0); - lcm_out = lcm_val; + lcm_out = lcm; needs_backwards_lcmed_out = needs_backwards_lcmed; return true; } //Check if it's multiple of the half of the alignmment else if((backwards_multiple & ((Alignment/2u) - 1u)) == 0){ - lcm_val = backwards_multiple*2u; - current_forward = get_truncated_size(received_size, backwards_multiple); + lcm = backwards_multiple*2u; + current_forward = detail::get_truncated_size(received_size, backwards_multiple); needs_backwards_lcmed = needs_backwards = size_to_achieve - current_forward; if(0 != (needs_backwards_lcmed & (Alignment-1))) //while(0 != (needs_backwards_lcmed & (Alignment-1))) needs_backwards_lcmed += backwards_multiple; - BOOST_ASSERT((needs_backwards_lcmed % lcm_val) == 0); - lcm_out = lcm_val; + BOOST_ASSERT((needs_backwards_lcmed % lcm) == 0); + lcm_out = lcm; needs_backwards_lcmed_out = needs_backwards_lcmed; return true; } - //Check if it's multiple of the quarter of the alignmment + //Check if it's multiple of the half of the alignmment else if((backwards_multiple & ((Alignment/4u) - 1u)) == 0){ - size_type remainder; - lcm_val = backwards_multiple*4u; - current_forward = get_truncated_size(received_size, backwards_multiple); + std::size_t remainder; + lcm = backwards_multiple*4u; + current_forward = detail::get_truncated_size(received_size, backwards_multiple); needs_backwards_lcmed = needs_backwards = size_to_achieve - current_forward; //while(0 != (needs_backwards_lcmed & (Alignment-1))) //needs_backwards_lcmed += backwards_multiple; @@ -199,48 +166,47 @@ class memory_algorithm_common needs_backwards_lcmed += (4-remainder)*backwards_multiple; } } - BOOST_ASSERT((needs_backwards_lcmed % lcm_val) == 0); - lcm_out = lcm_val; + BOOST_ASSERT((needs_backwards_lcmed % lcm) == 0); + lcm_out = lcm; needs_backwards_lcmed_out = needs_backwards_lcmed; return true; } else{ - lcm_val = lcm(max, min); + lcm = detail::lcm(max, min); } //If we want to use minbytes data to get a buffer between maxbytes - //and minbytes if maxbytes can't be achieved, calculate the + //and minbytes if maxbytes can't be achieved, calculate the //biggest of all possibilities - current_forward = get_truncated_size(received_size, backwards_multiple); + current_forward = detail::get_truncated_size(received_size, backwards_multiple); needs_backwards = size_to_achieve - current_forward; BOOST_ASSERT((needs_backwards % backwards_multiple) == 0); - needs_backwards_lcmed = get_rounded_size(needs_backwards, lcm_val); - lcm_out = lcm_val; + needs_backwards_lcmed = detail::get_rounded_size(needs_backwards, lcm); + lcm_out = lcm; needs_backwards_lcmed_out = needs_backwards_lcmed; return true; } - static void allocate_many + static multiallocation_chain allocate_many ( MemoryAlgorithm *memory_algo - , const size_type *elem_sizes - , size_type n_elements - , size_type sizeof_element - , multiallocation_chain &chain) + , const std::size_t *elem_sizes + , std::size_t n_elements + , std::size_t sizeof_element) { - this_type::priv_allocate_many(memory_algo, elem_sizes, n_elements, sizeof_element, chain); + return this_type::priv_allocate_many(memory_algo, elem_sizes, n_elements, sizeof_element); } static void* allocate_aligned - (MemoryAlgorithm *memory_algo, size_type nbytes, size_type alignment) + (MemoryAlgorithm *memory_algo, std::size_t nbytes, std::size_t alignment) { - + //Ensure power of 2 - if ((alignment & (alignment - size_type(1u))) != 0){ + if ((alignment & (alignment - std::size_t(1u))) != 0){ //Alignment is not power of two - BOOST_ASSERT((alignment & (alignment - size_type(1u))) == 0); + BOOST_ASSERT((alignment & (alignment - std::size_t(1u))) == 0); return 0; } - size_type real_size; + std::size_t real_size; if(alignment <= Alignment){ return memory_algo->priv_allocate (boost::interprocess::allocate_new, nbytes, nbytes, real_size).first; @@ -248,21 +214,21 @@ class memory_algorithm_common if(nbytes > UsableByPreviousChunk) nbytes -= UsableByPreviousChunk; - + //We can find a aligned portion if we allocate a block that has alignment //nbytes + alignment bytes or more. - size_type minimum_allocation = max_value - (nbytes + alignment, size_type(MinBlockUnits*Alignment)); + std::size_t minimum_allocation = max_value + (nbytes + alignment, std::size_t(MinBlockUnits*Alignment)); //Since we will split that block, we must request a bit more memory //if the alignment is near the beginning of the buffer, because otherwise, //there is no space for a new block before the alignment. - // + // // ____ Aligned here // | // ----------------------------------------------------- - // | MBU | + // | MBU | // ----------------------------------------------------- - size_type request = + std::size_t request = minimum_allocation + (2*MinBlockUnits*Alignment - AllocatedCtrlBytes //prevsize - UsableByPreviousChunk ); @@ -277,9 +243,9 @@ class memory_algorithm_common //If we are lucky and the buffer is aligned, just split it and //return the high part block_ctrl *first = memory_algo->priv_get_block(buffer); - size_type old_size = first->m_size; - const size_type first_min_units = - max_value(ceil_units(nbytes) + AllocatedCtrlUnits, size_type(MinBlockUnits)); + std::size_t old_size = first->m_size; + const std::size_t first_min_units = + max_value(ceil_units(nbytes) + AllocatedCtrlUnits, std::size_t(MinBlockUnits)); //We can create a new block in the end of the segment if(old_size >= (first_min_units + MinBlockUnits)){ block_ctrl *second = reinterpret_cast @@ -296,7 +262,7 @@ class memory_algorithm_common } //Buffer not aligned, find the aligned part. - // + // // ____ Aligned here // | // ----------------------------------------------------- @@ -319,8 +285,8 @@ class memory_algorithm_common BOOST_ASSERT((pos + MinBlockUnits*Alignment - AllocatedCtrlBytes + nbytes*Alignment/Alignment) <= (reinterpret_cast(first) + first->m_size*Alignment)); //Set the new size of the first block - size_type old_size = first->m_size; - first->m_size = (size_type)(reinterpret_cast(second) - reinterpret_cast(first))/Alignment; + std::size_t old_size = first->m_size; + first->m_size = (reinterpret_cast(second) - reinterpret_cast(first))/Alignment; memory_algo->priv_mark_new_allocated_block(first); //Now check if we can create a new buffer in the end @@ -333,7 +299,7 @@ class memory_algorithm_common // ----------------------------------------------------- //This size will be the minimum size to be able to create a //new block in the end. - const size_type second_min_units = max_value(size_type(MinBlockUnits), + const std::size_t second_min_units = max_value(std::size_t(MinBlockUnits), ceil_units(nbytes) + AllocatedCtrlUnits ); //Check if we can create a new block (of size MinBlockUnits) in the end of the segment @@ -357,15 +323,15 @@ class memory_algorithm_common return memory_algo->priv_get_user_buffer(second); } - static bool try_shrink + static bool try_shrink (MemoryAlgorithm *memory_algo, void *ptr - ,const size_type max_size, const size_type preferred_size - ,size_type &received_size) + ,const std::size_t max_size, const std::size_t preferred_size + ,std::size_t &received_size) { (void)memory_algo; //Obtain the real block block_ctrl *block = memory_algo->priv_get_block(ptr); - size_type old_block_units = (size_type)block->m_size; + std::size_t old_block_units = block->m_size; //The block must be marked as allocated BOOST_ASSERT(memory_algo->priv_is_allocated_block(block)); @@ -377,15 +343,15 @@ class memory_algorithm_common received_size = (old_block_units - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; //Now translate it to Alignment units - const size_type max_user_units = floor_units(max_size - UsableByPreviousChunk); - const size_type preferred_user_units = ceil_units(preferred_size - UsableByPreviousChunk); + const std::size_t max_user_units = floor_units(max_size - UsableByPreviousChunk); + const std::size_t preferred_user_units = ceil_units(preferred_size - UsableByPreviousChunk); //Check if rounded max and preferred are possible correct if(max_user_units < preferred_user_units) return false; //Check if the block is smaller than the requested minimum - size_type old_user_units = old_block_units - AllocatedCtrlUnits; + std::size_t old_user_units = old_block_units - AllocatedCtrlUnits; if(old_user_units < preferred_user_units) return false; @@ -394,8 +360,8 @@ class memory_algorithm_common if(old_user_units == preferred_user_units) return true; - size_type shrunk_user_units = - ((BlockCtrlUnits - AllocatedCtrlUnits) >= preferred_user_units) + std::size_t shrunk_user_units = + ((BlockCtrlUnits - AllocatedCtrlUnits) > preferred_user_units) ? (BlockCtrlUnits - AllocatedCtrlUnits) : preferred_user_units; @@ -413,16 +379,16 @@ class memory_algorithm_common return true; } - static bool shrink + static bool shrink (MemoryAlgorithm *memory_algo, void *ptr - ,const size_type max_size, const size_type preferred_size - ,size_type &received_size) + ,const std::size_t max_size, const std::size_t preferred_size + ,std::size_t &received_size) { //Obtain the real block block_ctrl *block = memory_algo->priv_get_block(ptr); - size_type old_block_units = (size_type)block->m_size; + std::size_t old_block_units = block->m_size; - if(!try_shrink + if(!try_shrink (memory_algo, ptr, max_size, preferred_size, received_size)){ return false; } @@ -449,140 +415,136 @@ class memory_algorithm_common } private: - static void priv_allocate_many + static multiallocation_chain priv_allocate_many ( MemoryAlgorithm *memory_algo - , const size_type *elem_sizes - , size_type n_elements - , size_type sizeof_element - , multiallocation_chain &chain) + , const std::size_t *elem_sizes + , std::size_t n_elements + , std::size_t sizeof_element) { //Note: sizeof_element == 0 indicates that we want to //allocate n_elements of the same size "*elem_sizes" //Calculate the total size of all requests - size_type total_request_units = 0; - size_type elem_units = 0; - const size_type ptr_size_units = memory_algo->priv_get_total_units(sizeof(void_pointer)); + std::size_t total_request_units = 0; + std::size_t elem_units = 0; + const std::size_t ptr_size_units = memory_algo->priv_get_total_units(sizeof(void_pointer)); if(!sizeof_element){ elem_units = memory_algo->priv_get_total_units(*elem_sizes); elem_units = ptr_size_units > elem_units ? ptr_size_units : elem_units; total_request_units = n_elements*elem_units; } else{ - for(size_type i = 0; i < n_elements; ++i){ - if(multiplication_overflows(elem_sizes[i], sizeof_element)){ - total_request_units = 0; - break; - } + for(std::size_t i = 0; i < n_elements; ++i){ elem_units = memory_algo->priv_get_total_units(elem_sizes[i]*sizeof_element); elem_units = ptr_size_units > elem_units ? ptr_size_units : elem_units; - if(sum_overflows(total_request_units, elem_units)){ - total_request_units = 0; - break; - } total_request_units += elem_units; } } - if(total_request_units && !multiplication_overflows(total_request_units, Alignment)){ - size_type low_idx = 0; - while(low_idx < n_elements){ - size_type total_bytes = total_request_units*Alignment - AllocatedCtrlBytes + UsableByPreviousChunk; - size_type min_allocation = (!sizeof_element) - ? elem_units - : memory_algo->priv_get_total_units(elem_sizes[low_idx]*sizeof_element); - min_allocation = min_allocation*Alignment - AllocatedCtrlBytes + UsableByPreviousChunk; - - size_type received_size; - std::pair ret = memory_algo->priv_allocate - (boost::interprocess::allocate_new, min_allocation, total_bytes, received_size, 0); - if(!ret.first){ - break; - } + multiallocation_chain chain; + + std::size_t low_idx = 0; + while(low_idx < n_elements){ + std::size_t total_bytes = total_request_units*Alignment - AllocatedCtrlBytes + UsableByPreviousChunk; + std::size_t min_allocation = (!sizeof_element) + ? elem_units + : memory_algo->priv_get_total_units(elem_sizes[low_idx]*sizeof_element); + min_allocation = min_allocation*Alignment - AllocatedCtrlBytes + UsableByPreviousChunk; + + std::size_t received_size; + std::pair ret = memory_algo->priv_allocate + (boost::interprocess::allocate_new, min_allocation, total_bytes, received_size, 0); + if(!ret.first){ + break; + } - block_ctrl *block = memory_algo->priv_get_block(ret.first); - size_type received_units = (size_type)block->m_size; - char *block_address = reinterpret_cast(block); + block_ctrl *block = memory_algo->priv_get_block(ret.first); + std::size_t received_units = block->m_size; + char *block_address = reinterpret_cast(block); - size_type total_used_units = 0; - while(total_used_units < received_units){ - if(sizeof_element){ - elem_units = memory_algo->priv_get_total_units(elem_sizes[low_idx]*sizeof_element); - elem_units = ptr_size_units > elem_units ? ptr_size_units : elem_units; - } - if(total_used_units + elem_units > received_units) - break; - total_request_units -= elem_units; - //This is the position where the new block must be created - block_ctrl *new_block = reinterpret_cast(block_address); - assert_alignment(new_block); - - //The last block should take all the remaining space - if((low_idx + 1) == n_elements || - (total_used_units + elem_units + - ((!sizeof_element) - ? elem_units - : std::max(memory_algo->priv_get_total_units(elem_sizes[low_idx+1]*sizeof_element), ptr_size_units)) - ) > received_units){ - //By default, the new block will use the rest of the buffer - new_block->m_size = received_units - total_used_units; - memory_algo->priv_mark_new_allocated_block(new_block); - - //If the remaining units are bigger than needed and we can - //split it obtaining a new free memory block do it. - if((received_units - total_used_units) >= (elem_units + MemoryAlgorithm::BlockCtrlUnits)){ - size_type shrunk_received; - size_type shrunk_request = elem_units*Alignment - AllocatedCtrlBytes + UsableByPreviousChunk; - bool shrink_ok = shrink - (memory_algo - ,memory_algo->priv_get_user_buffer(new_block) - ,shrunk_request - ,shrunk_request - ,shrunk_received); - (void)shrink_ok; - //Shrink must always succeed with passed parameters - BOOST_ASSERT(shrink_ok); - //Some sanity checks - BOOST_ASSERT(shrunk_request == shrunk_received); - BOOST_ASSERT(elem_units == ((shrunk_request-UsableByPreviousChunk)/Alignment + AllocatedCtrlUnits)); - //"new_block->m_size" must have been reduced to elem_units by "shrink" - BOOST_ASSERT(new_block->m_size == elem_units); - //Now update the total received units with the reduction - received_units = elem_units + total_used_units; - } - } - else{ - new_block->m_size = elem_units; - memory_algo->priv_mark_new_allocated_block(new_block); + std::size_t total_used_units = 0; +// block_ctrl *prev_block = 0; + while(total_used_units < received_units){ + if(sizeof_element){ + elem_units = memory_algo->priv_get_total_units(elem_sizes[low_idx]*sizeof_element); + elem_units = ptr_size_units > elem_units ? ptr_size_units : elem_units; + } + if(total_used_units + elem_units > received_units) + break; + total_request_units -= elem_units; + //This is the position where the new block must be created + block_ctrl *new_block = reinterpret_cast(block_address); + assert_alignment(new_block); + + //The last block should take all the remaining space + if((low_idx + 1) == n_elements || + (total_used_units + elem_units + + ((!sizeof_element) + ? elem_units + : memory_algo->priv_get_total_units(elem_sizes[low_idx+1]*sizeof_element)) + ) > received_units){ + //By default, the new block will use the rest of the buffer + new_block->m_size = received_units - total_used_units; + memory_algo->priv_mark_new_allocated_block(new_block); + + //If the remaining units are bigger than needed and we can + //split it obtaining a new free memory block do it. + if((received_units - total_used_units) >= (elem_units + MemoryAlgorithm::BlockCtrlUnits)){ + std::size_t shrunk_received; + std::size_t shrunk_request = elem_units*Alignment - AllocatedCtrlBytes + UsableByPreviousChunk; + bool shrink_ok = shrink + (memory_algo + ,memory_algo->priv_get_user_buffer(new_block) + ,shrunk_request + ,shrunk_request + ,shrunk_received); + (void)shrink_ok; + //Shrink must always succeed with passed parameters + BOOST_ASSERT(shrink_ok); + //Some sanity checks + BOOST_ASSERT(shrunk_request == shrunk_received); + BOOST_ASSERT(elem_units == ((shrunk_request-UsableByPreviousChunk)/Alignment + AllocatedCtrlUnits)); + //"new_block->m_size" must have been reduced to elem_units by "shrink" + BOOST_ASSERT(new_block->m_size == elem_units); + //Now update the total received units with the reduction + received_units = elem_units + total_used_units; } - - block_address += new_block->m_size*Alignment; - total_used_units += (size_type)new_block->m_size; - //Check we have enough room to overwrite the intrusive pointer - BOOST_ASSERT((new_block->m_size*Alignment - AllocatedCtrlUnits) >= sizeof(void_pointer)); - void_pointer p = new(memory_algo->priv_get_user_buffer(new_block))void_pointer(0); - chain.push_back(p); - ++low_idx; } - //Sanity check - BOOST_ASSERT(total_used_units == received_units); - } + else{ + new_block->m_size = elem_units; + memory_algo->priv_mark_new_allocated_block(new_block); + } - if(low_idx != n_elements){ - priv_deallocate_many(memory_algo, chain); + block_address += new_block->m_size*Alignment; + total_used_units += new_block->m_size; + //Check we have enough room to overwrite the intrusive pointer + BOOST_ASSERT((new_block->m_size*Alignment - AllocatedCtrlUnits) >= sizeof(void_pointer)); + void_pointer p = new(memory_algo->priv_get_user_buffer(new_block))void_pointer(0); + chain.push_back(p); + ++low_idx; + //prev_block = new_block; } + //Sanity check + BOOST_ASSERT(total_used_units == received_units); + } + + if(low_idx != n_elements){ + priv_deallocate_many(memory_algo, boost::interprocess::move(chain)); } + return boost::interprocess::move(chain); } - static void priv_deallocate_many(MemoryAlgorithm *memory_algo, multiallocation_chain &chain) + static void priv_deallocate_many(MemoryAlgorithm *memory_algo, multiallocation_chain chain) { while(!chain.empty()){ - memory_algo->priv_deallocate(to_raw_pointer(chain.pop_front())); + void *addr = detail::get_pointer(chain.front()); + chain.pop_front(); + memory_algo->priv_deallocate(addr); } } }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit.hpp b/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit.hpp index e8b678d9..4c541f11 100644 --- a/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit.hpp +++ b/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2011. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -34,20 +34,20 @@ namespace interprocess { linked list of free buffers.*/ template class multi_simple_seq_fit - : public ipcdetail::simple_seq_fit_impl + : public detail::simple_seq_fit_impl { - typedef ipcdetail::simple_seq_fit_impl base_t; + typedef detail::simple_seq_fit_impl base_t; public: /*!Constructor. "size" is the total size of the managed memory segment, "extra_hdr_bytes" indicates the extra bytes beginning in the sizeof(multi_simple_seq_fit) offset that the allocator should not use at all.*/ - multi_simple_seq_fit (size_type size, size_type extra_hdr_bytes) + multi_simple_seq_fit (std::size_t size, std::size_t extra_hdr_bytes) : base_t(size, extra_hdr_bytes){} /*!Allocates bytes from existing segments. If there is no memory, it uses the growing functor associated with the group to allocate a new segment. If this fails, returns 0.*/ - void* allocate (size_type nbytes) + void* allocate (std::size_t nbytes) { return base_t::multi_allocate(nbytes); } }; diff --git a/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit_impl.hpp b/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit_impl.hpp index 7a2c7a83..a0afb2fe 100644 --- a/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit_impl.hpp +++ b/utils/boost_idb/boost/interprocess/mem_algo/detail/multi_simple_seq_fit_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2011. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -49,7 +48,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { /*!This class implements the simple sequential fit algorithm with a simply linked list of free buffers. @@ -69,15 +68,10 @@ class simple_seq_fit_impl /*!Pointer type to be used with the rest of the Interprocess framework*/ typedef VoidPointer void_pointer; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; - - private: struct block_ctrl; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type block_ctrl_ptr; + typedef typename boost:: + pointer_to_other::type block_ctrl_ptr; /*!Block control structure*/ struct block_ctrl @@ -86,12 +80,12 @@ class simple_seq_fit_impl block_ctrl_ptr m_next; /*!This block's memory size (including block_ctrl header) in BasicSize units*/ - size_type m_size; + std::size_t m_size; - size_type get_user_bytes() const + std::size_t get_user_bytes() const { return this->m_size*Alignment - BlockCtrlBytes; } - size_type get_total_bytes() const + std::size_t get_total_bytes() const { return this->m_size*Alignment; } static block_ctrl *get_block_from_addr(void *addr) @@ -118,34 +112,34 @@ class simple_seq_fit_impl /*!Pointer to the first free block*/ block_ctrl m_root; /*!Allocated bytes for internal checking*/ - size_type m_allocated; + std::size_t m_allocated; /*!The size of the memory segment*/ - size_type m_size; + std::size_t m_size; } m_header; public: /*!Constructor. "size" is the total size of the managed memory segment, "extra_hdr_bytes" indicates the extra bytes beginning in the sizeof(simple_seq_fit_impl) offset that the allocator should not use at all.*/ - simple_seq_fit_impl (size_type size, size_type extra_hdr_bytes); + simple_seq_fit_impl (std::size_t size, std::size_t extra_hdr_bytes); /*!Destructor.*/ ~simple_seq_fit_impl(); /*!Obtains the minimum size needed by the algorithm*/ - static size_type get_min_size (size_type extra_hdr_bytes); + static std::size_t get_min_size (std::size_t extra_hdr_bytes); //Functions for single segment management /*!Allocates bytes, returns 0 if there is not more memory*/ - void* allocate (size_type nbytes); + void* allocate (std::size_t nbytes); /*!Deallocates previously allocated bytes*/ void deallocate (void *addr); /*!Returns the size of the memory segment*/ - size_type get_size() const; + std::size_t get_size() const; /*!Increases managed memory in extra_size bytes more*/ - void grow(size_type extra_size); + void grow(std::size_t extra_size); /*!Returns true if all allocated memory has been deallocated*/ bool all_memory_deallocated(); @@ -158,30 +152,30 @@ class simple_seq_fit_impl void clear_free_memory(); std::pair - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, - void *reuse_ptr = 0, size_type backwards_multiple = 1); + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, + void *reuse_ptr = 0, std::size_t backwards_multiple = 1); /*!Returns the size of the buffer previously allocated pointed by ptr*/ - size_type size(void *ptr) const; + std::size_t size(void *ptr) const; /*!Allocates aligned bytes, returns 0 if there is not more memory. Alignment must be power of 2*/ - void* allocate_aligned (size_type nbytes, size_type alignment); + void* allocate_aligned (std::size_t nbytes, std::size_t alignment); /*!Allocates bytes, if there is no more memory, it executes functor - f(size_type) to allocate a new segment to manage. The functor returns - std::pair indicating the base address and size of + f(std::size_t) to allocate a new segment to manage. The functor returns + std::pair indicating the base address and size of the new segment. If the new segment can't be allocated, allocate it will return 0.*/ - void* multi_allocate(size_type nbytes); + void* multi_allocate(std::size_t nbytes); private: /*!Real allocation algorithm with min allocation option*/ std::pair priv_allocate(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr = 0); /*!Returns next block if it's free. Returns 0 if next block is not free.*/ @@ -193,56 +187,56 @@ class simple_seq_fit_impl /*!Real expand function implementation*/ bool priv_expand(void *ptr - ,size_type min_size, size_type preferred_size - ,size_type &received_size); + ,std::size_t min_size, std::size_t preferred_size + ,std::size_t &received_size); /*!Real expand to both sides implementation*/ void* priv_expand_both_sides(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr ,bool only_preferred_backwards); /*!Real shrink function implementation*/ bool priv_shrink(void *ptr - ,size_type max_size, size_type preferred_size - ,size_type &received_size); + ,std::size_t max_size, std::size_t preferred_size + ,std::size_t &received_size); //!Real private aligned allocation function - void* priv_allocate_aligned (size_type nbytes, size_type alignment); + void* priv_allocate_aligned (std::size_t nbytes, std::size_t alignment); /*!Checks if block has enough memory and splits/unlinks the block returning the address to the users*/ - void* priv_check_and_allocate(size_type units + void* priv_check_and_allocate(std::size_t units ,block_ctrl* prev ,block_ctrl* block - ,size_type &received_size); + ,std::size_t &received_size); /*!Real deallocation algorithm*/ void priv_deallocate(void *addr); /*!Makes a new memory portion available for allocation*/ - void priv_add_segment(void *addr, size_type size); + void priv_add_segment(void *addr, std::size_t size); - static const std::size_t Alignment = ::boost::alignment_of::value; - static const std::size_t BlockCtrlBytes = ipcdetail::ct_rounded_size::value; - static const std::size_t BlockCtrlSize = BlockCtrlBytes/Alignment; - static const std::size_t MinBlockSize = BlockCtrlSize + Alignment; + enum { Alignment = boost::alignment_of::value }; + enum { BlockCtrlBytes = detail::ct_rounded_size::value }; + enum { BlockCtrlSize = BlockCtrlBytes/Alignment }; + enum { MinBlockSize = BlockCtrlSize + Alignment }; public: - static const std::size_t PayloadPerAllocation = BlockCtrlBytes; + enum { PayloadPerAllocation = BlockCtrlBytes }; }; template inline simple_seq_fit_impl:: - simple_seq_fit_impl(size_type size, size_type extra_hdr_bytes) + simple_seq_fit_impl(std::size_t size, std::size_t extra_hdr_bytes) { //Initialize sizes and counters m_header.m_allocated = 0; m_header.m_size = size; //Initialize pointers - size_type block1_off = ipcdetail::get_rounded_size(sizeof(*this)+extra_hdr_bytes, Alignment); + std::size_t block1_off = detail::get_rounded_size(sizeof(*this)+extra_hdr_bytes, Alignment); m_header.m_root.m_next = reinterpret_cast (reinterpret_cast(this) + block1_off); m_header.m_root.m_next->m_size = (size - block1_off)/Alignment; @@ -258,10 +252,10 @@ inline simple_seq_fit_impl::~simple_seq_fit_impl() } template -inline void simple_seq_fit_impl::grow(size_type extra_size) +inline void simple_seq_fit_impl::grow(std::size_t extra_size) { //Old highest address block's end offset - size_type old_end = m_header.m_size/Alignment*Alignment; + std::size_t old_end = m_header.m_size/Alignment*Alignment; //Update managed buffer's size m_header.m_size += extra_size; @@ -282,7 +276,7 @@ inline void simple_seq_fit_impl::grow(size_type extra_ } template -inline void simple_seq_fit_impl::priv_add_segment(void *addr, size_type size) +inline void simple_seq_fit_impl::priv_add_segment(void *addr, std::size_t size) { //Check size BOOST_ASSERT(!(size < MinBlockSize)); @@ -299,16 +293,14 @@ inline void simple_seq_fit_impl::priv_add_segment(void } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl::get_size() const +inline std::size_t simple_seq_fit_impl::get_size() const { return m_header.m_size; } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl:: - get_min_size (size_type extra_hdr_bytes) +inline std::size_t simple_seq_fit_impl:: + get_min_size (std::size_t extra_hdr_bytes) { - return ipcdetail::get_rounded_size(sizeof(simple_seq_fit_impl)+extra_hdr_bytes + return detail::get_rounded_size(sizeof(simple_seq_fit_impl)+extra_hdr_bytes ,Alignment) + MinBlockSize; } @@ -321,7 +313,7 @@ inline bool simple_seq_fit_impl:: boost::interprocess::scoped_lock guard(m_header); //----------------------- return m_header.m_allocated == 0 && - ipcdetail::to_raw_pointer(m_header.m_root.m_next->m_next) == &m_header.m_root; + detail::get_pointer(m_header.m_root.m_next->m_next) == &m_header.m_root; } template @@ -330,7 +322,7 @@ inline void simple_seq_fit_impl::clear_free_memory() //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - block_ctrl *block = ipcdetail::to_raw_pointer(m_header.m_root.m_next); + block_ctrl *block = detail::get_pointer(m_header.m_root.m_next); //Iterate through all free portions do{ @@ -338,7 +330,7 @@ inline void simple_seq_fit_impl::clear_free_memory() std::memset( reinterpret_cast(block) + BlockCtrlBytes , 0 , block->m_size*Alignment - BlockCtrlBytes); - block = ipcdetail::to_raw_pointer(block->m_next); + block = detail::get_pointer(block->m_next); } while(block != &m_header.m_root); } @@ -350,14 +342,14 @@ inline bool simple_seq_fit_impl:: //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - block_ctrl *block = ipcdetail::to_raw_pointer(m_header.m_root.m_next); + block_ctrl *block = detail::get_pointer(m_header.m_root.m_next); - size_type free_memory = 0; + std::size_t free_memory = 0; //Iterate through all blocks obtaining their size do{ //Free blocks's next must be always valid - block_ctrl *next = ipcdetail::to_raw_pointer(block->m_next); + block_ctrl *next = detail::get_pointer(block->m_next); if(!next){ return false; } @@ -380,18 +372,18 @@ inline bool simple_seq_fit_impl:: template inline void* simple_seq_fit_impl:: - allocate(size_type nbytes) + allocate(std::size_t nbytes) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - size_type ignore; + std::size_t ignore; return priv_allocate(boost::interprocess::allocate_new, nbytes, nbytes, ignore).first; } template inline void* simple_seq_fit_impl:: - allocate_aligned(size_type nbytes, size_type alignment) + allocate_aligned(std::size_t nbytes, std::size_t alignment) { //----------------------- boost::interprocess::scoped_lock guard(m_header); @@ -401,9 +393,9 @@ inline void* simple_seq_fit_impl:: template inline std::pair simple_seq_fit_impl:: - allocation_command (boost::interprocess::allocation_type command, size_type min_size, - size_type preferred_size,size_type &received_size, - void *reuse_ptr, size_type backwards_multiple) + allocation_command (boost::interprocess::allocation_type command, std::size_t min_size, + std::size_t preferred_size,std::size_t &received_size, + void *reuse_ptr, std::size_t backwards_multiple) { //----------------------- boost::interprocess::scoped_lock guard(m_header); @@ -416,8 +408,7 @@ inline std::pair simple_seq_fit_impl:: } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl:: +inline std::size_t simple_seq_fit_impl:: size(void *ptr) const { //We need no synchronization since this block is not going @@ -430,19 +421,19 @@ simple_seq_fit_impl:: template inline void* simple_seq_fit_impl:: - multi_allocate(size_type nbytes) + multi_allocate(std::size_t nbytes) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- //Multisegment pointer. Let's try first the normal allocation //since it's faster. - size_type ignore; + std::size_t ignore; void *addr = this->priv_allocate(boost::interprocess::allocate_new, nbytes, nbytes, ignore).first; if(!addr){ //If this fails we will try the allocation through the segment //creator. - size_type group, id; + std::size_t group, id; //Obtain the segment group of this segment void_pointer::get_group_and_id(this, group, id); if(group == 0){ @@ -455,7 +446,7 @@ inline void* simple_seq_fit_impl:: static_cast (void_pointer::find_group_data(group)); BOOST_ASSERT(p_services); - std::pair ret = + std::pair ret = p_services->create_new_segment(MinBlockSize > nbytes ? MinBlockSize : nbytes); if(ret.first){ priv_add_segment(ret.first, ret.second); @@ -468,9 +459,9 @@ inline void* simple_seq_fit_impl:: template void* simple_seq_fit_impl:: priv_expand_both_sides(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr ,bool only_preferred_backwards) { @@ -491,19 +482,19 @@ void* simple_seq_fit_impl:: received_size = this->size(reuse_ptr); } if(command & boost::interprocess::expand_bwd){ - size_type extra_forward = !received_size ? 0 : received_size + BlockCtrlBytes; + std::size_t extra_forward = !received_size ? 0 : received_size + BlockCtrlBytes; prev_block_t prev_pair = priv_prev_block_if_free(reuse); block_ctrl *prev = prev_pair.second; if(!prev){ return 0; } - size_type needs_backwards = - ipcdetail::get_rounded_size(preferred_size - extra_forward, Alignment); + std::size_t needs_backwards = + detail::get_rounded_size(preferred_size - extra_forward, Alignment); if(!only_preferred_backwards){ needs_backwards = - max_value(ipcdetail::get_rounded_size(min_size - extra_forward, Alignment) + max_value(detail::get_rounded_size(min_size - extra_forward, Alignment) ,min_value(prev->get_user_bytes(), needs_backwards)); } @@ -547,9 +538,9 @@ void* simple_seq_fit_impl:: template std::pair simple_seq_fit_impl:: priv_allocate(boost::interprocess::allocation_type command - ,size_type limit_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t limit_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr) { if(command & boost::interprocess::shrink_in_place){ @@ -564,15 +555,15 @@ std::pair simple_seq_fit_impl:: return return_type(0, false); //Number of units to request (including block_ctrl header) - size_type nunits = ipcdetail::get_rounded_size(preferred_size, Alignment)/Alignment + BlockCtrlSize; + std::size_t nunits = detail::get_rounded_size(preferred_size, Alignment)/Alignment + BlockCtrlSize; //Get the root and the first memory block block_ctrl *prev = &m_header.m_root; - block_ctrl *block = ipcdetail::to_raw_pointer(prev->m_next); + block_ctrl *block = detail::get_pointer(prev->m_next); block_ctrl *root = &m_header.m_root; block_ctrl *biggest_block = 0; block_ctrl *prev_biggest_block = 0; - size_type biggest_size = limit_size; + std::size_t biggest_size = limit_size; //Expand in place //reuse_ptr, limit_size, preferred_size, received_size @@ -597,14 +588,14 @@ std::pair simple_seq_fit_impl:: if(addr) return return_type(addr, false); //Bad luck, let's check next block prev = block; - block = ipcdetail::to_raw_pointer(block->m_next); + block = detail::get_pointer(block->m_next); } //Bad luck finding preferred_size, now if we have any biggest_block //try with this block if(biggest_block){ received_size = biggest_block->m_size*Alignment - BlockCtrlSize; - nunits = ipcdetail::get_rounded_size(limit_size, Alignment)/Alignment + BlockCtrlSize; + nunits = detail::get_rounded_size(limit_size, Alignment)/Alignment + BlockCtrlSize; void *ret = this->priv_check_and_allocate (nunits, prev_biggest_block, biggest_block, received_size); if(ret) @@ -630,7 +621,7 @@ inline typename simple_seq_fit_impl::block_ctrl * (reinterpret_cast(ptr) + ptr->m_size*Alignment); //Check if the adjacent block is in the managed segment - size_type distance = (reinterpret_cast(next_block) - reinterpret_cast(this))/Alignment; + std::size_t distance = (reinterpret_cast(next_block) - reinterpret_cast(this))/Alignment; if(distance >= (m_header.m_size/Alignment)){ //"next_block" does not exist so we can't expand "block" return 0; @@ -654,19 +645,19 @@ inline //Take the address where the previous block should go block_ctrl *root = &m_header.m_root; block_ctrl *prev_2_block = root; - block_ctrl *prev_block = ipcdetail::to_raw_pointer(root->m_next); + block_ctrl *prev_block = detail::get_pointer(root->m_next); while((reinterpret_cast(prev_block) + prev_block->m_size*Alignment) != (reinterpret_cast(ptr)) && prev_block != root){ prev_2_block = prev_block; - prev_block = ipcdetail::to_raw_pointer(prev_block->m_next); + prev_block = detail::get_pointer(prev_block->m_next); } if(prev_block == root || !prev_block->m_next) return prev_pair_t(0, 0); //Check if the previous block is in the managed segment - size_type distance = (reinterpret_cast(prev_block) - reinterpret_cast(this))/Alignment; + std::size_t distance = (reinterpret_cast(prev_block) - reinterpret_cast(this))/Alignment; if(distance >= (m_header.m_size/Alignment)){ //"previous_block" does not exist so we can't expand "block" return prev_pair_t(0, 0); @@ -678,14 +669,14 @@ inline template inline bool simple_seq_fit_impl:: priv_expand (void *ptr - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size) + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size) { //Obtain the real size of the block block_ctrl *block = reinterpret_cast (reinterpret_cast(ptr) - BlockCtrlBytes); - size_type old_block_size = block->m_size; + std::size_t old_block_size = block->m_size; //All used blocks' next is marked with 0 so check it BOOST_ASSERT(block->m_next == 0); @@ -694,14 +685,14 @@ inline bool simple_seq_fit_impl:: received_size = old_block_size*Alignment - BlockCtrlBytes; //Now translate it to Alignment units - min_size = ipcdetail::get_rounded_size(min_size, Alignment)/Alignment; - preferred_size = ipcdetail::get_rounded_size(preferred_size, Alignment)/Alignment; + min_size = detail::get_rounded_size(min_size, Alignment)/Alignment; + preferred_size = detail::get_rounded_size(preferred_size, Alignment)/Alignment; //Some parameter checks if(min_size > preferred_size) return false; - size_type data_size = old_block_size - BlockCtrlSize; + std::size_t data_size = old_block_size - BlockCtrlSize; if(data_size >= min_size) return true; @@ -712,7 +703,7 @@ inline bool simple_seq_fit_impl:: } //Is "block" + "next_block" big enough? - size_type merged_size = old_block_size + next_block->m_size; + std::size_t merged_size = old_block_size + next_block->m_size; //Now we can expand this block further than before received_size = merged_size*Alignment - BlockCtrlBytes; @@ -727,8 +718,8 @@ inline bool simple_seq_fit_impl:: //Find the previous free block of next_block block_ctrl *prev = &m_header.m_root; - while(ipcdetail::to_raw_pointer(prev->m_next) != next_block){ - prev = ipcdetail::to_raw_pointer(prev->m_next); + while(detail::get_pointer(prev->m_next) != next_block){ + prev = detail::get_pointer(prev->m_next); } //Now insert merged block in the free list @@ -738,7 +729,7 @@ inline bool simple_seq_fit_impl:: //Now use check and allocate to do the allocation logic preferred_size += BlockCtrlSize; - size_type nunits = preferred_size < merged_size ? preferred_size : merged_size; + std::size_t nunits = preferred_size < merged_size ? preferred_size : merged_size; //This must success since nunits is less than merged_size! if(!this->priv_check_and_allocate (nunits, prev, block, received_size)){ @@ -753,14 +744,14 @@ inline bool simple_seq_fit_impl:: template inline bool simple_seq_fit_impl:: priv_shrink (void *ptr - ,size_type max_size - ,size_type preferred_size - ,size_type &received_size) + ,std::size_t max_size + ,std::size_t preferred_size + ,std::size_t &received_size) { //Obtain the real size of the block block_ctrl *block = reinterpret_cast (reinterpret_cast(ptr) - BlockCtrlBytes); - size_type block_size = block->m_size; + std::size_t block_size = block->m_size; //All used blocks' next is marked with 0 so check it BOOST_ASSERT(block->m_next == 0); @@ -770,13 +761,13 @@ inline bool simple_seq_fit_impl:: //Now translate it to Alignment units max_size = max_size/Alignment; - preferred_size = ipcdetail::get_rounded_size(preferred_size, Alignment)/Alignment; + preferred_size = detail::get_rounded_size(preferred_size, Alignment)/Alignment; //Some parameter checks if(max_size < preferred_size) return false; - size_type data_size = block_size - BlockCtrlSize; + std::size_t data_size = block_size - BlockCtrlSize; if(data_size < preferred_size) return false; @@ -810,21 +801,21 @@ inline bool simple_seq_fit_impl:: template inline void* simple_seq_fit_impl:: - priv_allocate_aligned(size_type nbytes, size_type alignment) + priv_allocate_aligned(std::size_t nbytes, std::size_t alignment) { //Ensure power of 2 - if ((alignment & (alignment - size_type(1u))) != 0){ + if ((alignment & (alignment - std::size_t(1u))) != 0){ //Alignment is not power of two - BOOST_ASSERT((alignment & (alignment - size_type(1u))) != 0); + BOOST_ASSERT((alignment & (alignment - std::size_t(1u))) != 0); return 0; } - size_type ignore; + std::size_t ignore; if(alignment <= Alignment){ return priv_allocate(boost::interprocess::allocate_new, nbytes, nbytes, ignore).first; } - size_type request = + std::size_t request = nbytes + alignment + MinBlockSize*Alignment - BlockCtrlBytes; void *buffer = priv_allocate(boost::interprocess::allocate_new, request, request, ignore).first; if(!buffer) @@ -833,7 +824,7 @@ inline void* simple_seq_fit_impl:: return buffer; char *aligned_portion = reinterpret_cast - (reinterpret_cast(static_cast(buffer) + alignment - 1) & -alignment); + (reinterpret_cast(static_cast(buffer) + alignment - 1) & -alignment); char *pos = ((aligned_portion - reinterpret_cast(buffer)) >= (MinBlockSize*Alignment)) ? aligned_portion : (aligned_portion + alignment); @@ -843,7 +834,7 @@ inline void* simple_seq_fit_impl:: block_ctrl *second = reinterpret_cast(pos - BlockCtrlBytes); - size_type old_size = first->m_size; + std::size_t old_size = first->m_size; first->m_size = (reinterpret_cast(second) - reinterpret_cast(first))/Alignment; second->m_size = old_size - first->m_size; @@ -858,19 +849,19 @@ inline void* simple_seq_fit_impl:: template inline void* simple_seq_fit_impl::priv_check_and_allocate - (size_type nunits + (std::size_t nunits ,typename simple_seq_fit_impl::block_ctrl* prev ,typename simple_seq_fit_impl::block_ctrl* block - ,size_type &received_size) + ,std::size_t &received_size) { - size_type upper_nunits = nunits + BlockCtrlSize; + std::size_t upper_nunits = nunits + BlockCtrlSize; bool found = false; if (block->m_size > upper_nunits){ //This block is bigger than needed, split it in //two blocks, the first's size will be (block->m_size-units) //the second's size (units) - size_type total_size = block->m_size; + std::size_t total_size = block->m_size; block->m_size = nunits; block_ctrl *new_block = reinterpret_cast (reinterpret_cast(block) + Alignment*nunits); @@ -932,7 +923,7 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) BOOST_ASSERT((reinterpret_cast(addr) - reinterpret_cast(this)) % Alignment == 0 ); - size_type total_size = Alignment*block->m_size; + std::size_t total_size = Alignment*block->m_size; BOOST_ASSERT(m_header.m_allocated >= total_size); //Update used memory count @@ -942,15 +933,15 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) //This ordering comparison must be done with original pointers //types since their mapping to raw pointers can be different //in each process - while((ipcdetail::to_raw_pointer(pos) != &m_header.m_root) && (block > pos)){ + while((detail::get_pointer(pos) != &m_header.m_root) && (block > pos)){ prev = pos; pos = pos->m_next; } //Try to combine with upper block - if ((reinterpret_cast(ipcdetail::to_raw_pointer(block)) + if ((reinterpret_cast(detail::get_pointer(block)) + Alignment*block->m_size) == - reinterpret_cast(ipcdetail::to_raw_pointer(pos))){ + reinterpret_cast(detail::get_pointer(pos))){ block->m_size += pos->m_size; block->m_next = pos->m_next; @@ -960,9 +951,9 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) } //Try to combine with lower block - if ((reinterpret_cast(ipcdetail::to_raw_pointer(prev)) + if ((reinterpret_cast(detail::get_pointer(prev)) + Alignment*prev->m_size) == - reinterpret_cast(ipcdetail::to_raw_pointer(block))){ + reinterpret_cast(detail::get_pointer(block))){ prev->m_size += block->m_size; prev->m_next = block->m_next; } @@ -971,7 +962,7 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) } } -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/mem_algo/detail/simple_seq_fit_impl.hpp b/utils/boost_idb/boost/interprocess/mem_algo/detail/simple_seq_fit_impl.hpp index 1fb95a5b..8cf2bf37 100644 --- a/utils/boost_idb/boost/interprocess/mem_algo/detail/simple_seq_fit_impl.hpp +++ b/utils/boost_idb/boost/interprocess/mem_algo/detail/simple_seq_fit_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,11 +18,11 @@ #include #include -#include +#include #include #include -#include +#include #include #include #include @@ -30,10 +30,7 @@ #include #include #include -#include #include -#include -#include #include #include #include @@ -47,7 +44,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { //!This class implements the simple sequential fit algorithm with a simply //!linked list of free buffers. @@ -61,28 +58,19 @@ class simple_seq_fit_impl simple_seq_fit_impl(const simple_seq_fit_impl &); simple_seq_fit_impl &operator=(const simple_seq_fit_impl &); - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type char_ptr; - public: //!Shared interprocess_mutex family used for the rest of the Interprocess framework typedef MutexFamily mutex_family; //!Pointer type to be used with the rest of the Interprocess framework typedef VoidPointer void_pointer; - typedef boost::container::container_detail:: + typedef boost::container::containers_detail:: basic_multiallocation_chain multiallocation_chain; - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; - - private: class block_ctrl; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type block_ctrl_ptr; + typedef typename boost:: + pointer_to_other::type block_ctrl_ptr; class block_ctrl; friend class block_ctrl; @@ -93,14 +81,14 @@ class simple_seq_fit_impl public: //!Offset pointer to the next block. block_ctrl_ptr m_next; - //!This block's memory size (including block_ctrl + //!This block's memory size (including block_ctrl //!header) in BasicSize units - size_type m_size; - - size_type get_user_bytes() const + std::size_t m_size; + + std::size_t get_user_bytes() const { return this->m_size*Alignment - BlockCtrlBytes; } - size_type get_total_bytes() const + std::size_t get_total_bytes() const { return this->m_size*Alignment; } }; @@ -114,56 +102,58 @@ class simple_seq_fit_impl //!Pointer to the first free block block_ctrl m_root; //!Allocated bytes for internal checking - size_type m_allocated; + std::size_t m_allocated; //!The size of the memory segment - size_type m_size; + std::size_t m_size; //!The extra size required by the segment - size_type m_extra_hdr_bytes; + std::size_t m_extra_hdr_bytes; } m_header; - friend class ipcdetail::memory_algorithm_common; + friend class detail::memory_algorithm_common; - typedef ipcdetail::memory_algorithm_common algo_impl_t; + typedef detail::memory_algorithm_common algo_impl_t; public: - //!Constructor. "size" is the total size of the managed memory segment, + //!Constructor. "size" is the total size of the managed memory segment, //!"extra_hdr_bytes" indicates the extra bytes beginning in the sizeof(simple_seq_fit_impl) //!offset that the allocator should not use at all. - simple_seq_fit_impl (size_type size, size_type extra_hdr_bytes); + simple_seq_fit_impl (std::size_t size, std::size_t extra_hdr_bytes); //!Destructor ~simple_seq_fit_impl(); //!Obtains the minimum size needed by the algorithm - static size_type get_min_size (size_type extra_hdr_bytes); + static std::size_t get_min_size (std::size_t extra_hdr_bytes); //Functions for single segment management //!Allocates bytes, returns 0 if there is not more memory - void* allocate (size_type nbytes); + void* allocate (std::size_t nbytes); /// @cond //!Multiple element allocation, same size - void allocate_many(size_type elem_bytes, size_type num_elements, multiallocation_chain &chain) + multiallocation_chain + allocate_many(std::size_t elem_bytes, std::size_t num_elements) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - algo_impl_t::allocate_many(this, elem_bytes, num_elements, chain); + return algo_impl_t::allocate_many(this, elem_bytes, num_elements); } //!Multiple element allocation, different size - void allocate_many(const size_type *elem_sizes, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain) + multiallocation_chain + allocate_many(const std::size_t *elem_sizes, std::size_t n_elements, std::size_t sizeof_element) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - algo_impl_t::allocate_many(this, elem_sizes, n_elements, sizeof_element, chain); + return algo_impl_t::allocate_many(this, elem_sizes, n_elements, sizeof_element); } //!Multiple element deallocation - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); /// @endcond @@ -171,13 +161,13 @@ class simple_seq_fit_impl void deallocate (void *addr); //!Returns the size of the memory segment - size_type get_size() const; + std::size_t get_size() const; //!Returns the number of free bytes of the memory segment - size_type get_free_memory() const; + std::size_t get_free_memory() const; //!Increases managed memory in extra_size bytes more - void grow(size_type extra_size); + void grow(std::size_t extra_size); //!Decreases managed memory as much as possible void shrink_to_fit(); @@ -194,21 +184,21 @@ class simple_seq_fit_impl template std::pair - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, T *reuse_ptr = 0); std::pair - raw_allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, - void *reuse_ptr = 0, size_type sizeof_object = 1); + raw_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, + void *reuse_ptr = 0, std::size_t sizeof_object = 1); //!Returns the size of the buffer previously allocated pointed by ptr - size_type size(const void *ptr) const; + std::size_t size(const void *ptr) const; //!Allocates aligned bytes, returns 0 if there is not more memory. //!Alignment must be power of 2 - void* allocate_aligned (size_type nbytes, size_type alignment); + void* allocate_aligned (std::size_t nbytes, std::size_t alignment); private: @@ -220,24 +210,24 @@ class simple_seq_fit_impl //!Real allocation algorithm with min allocation option std::pair priv_allocate(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr = 0); std::pair priv_allocation_command(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr - ,size_type sizeof_object); + ,std::size_t sizeof_object); //!Returns the number of total units that a user buffer //!of "userbytes" bytes really occupies (including header) - static size_type priv_get_total_units(size_type userbytes); + static std::size_t priv_get_total_units(std::size_t userbytes); - static size_type priv_first_block_offset(const void *this_ptr, size_type extra_hdr_bytes); - size_type priv_block_end_offset() const; + static std::size_t priv_first_block_offset(const void *this_ptr, std::size_t extra_hdr_bytes); + std::size_t priv_block_end_offset() const; //!Returns next block if it's free. //!Returns 0 if next block is not free. @@ -252,76 +242,74 @@ class simple_seq_fit_impl //!Real expand function implementation bool priv_expand(void *ptr - ,size_type min_size, size_type preferred_size - ,size_type &received_size); + ,std::size_t min_size, std::size_t preferred_size + ,std::size_t &received_size); //!Real expand to both sides implementation void* priv_expand_both_sides(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr ,bool only_preferred_backwards); //!Real private aligned allocation function - //void* priv_allocate_aligned (size_type nbytes, size_type alignment); + //void* priv_allocate_aligned (std::size_t nbytes, std::size_t alignment); //!Checks if block has enough memory and splits/unlinks the block //!returning the address to the users - void* priv_check_and_allocate(size_type units + void* priv_check_and_allocate(std::size_t units ,block_ctrl* prev ,block_ctrl* block - ,size_type &received_size); + ,std::size_t &received_size); //!Real deallocation algorithm void priv_deallocate(void *addr); //!Makes a new memory portion available for allocation - void priv_add_segment(void *addr, size_type size); + void priv_add_segment(void *addr, std::size_t size); void priv_mark_new_allocated_block(block_ctrl *block); public: - static const size_type Alignment = ::boost::alignment_of< ::boost::detail::max_align>::value; + static const std::size_t Alignment = detail::alignment_of::value; private: - static const size_type BlockCtrlBytes = ipcdetail::ct_rounded_size::value; - static const size_type BlockCtrlUnits = BlockCtrlBytes/Alignment; - static const size_type MinBlockUnits = BlockCtrlUnits; - static const size_type MinBlockSize = MinBlockUnits*Alignment; - static const size_type AllocatedCtrlBytes = BlockCtrlBytes; - static const size_type AllocatedCtrlUnits = BlockCtrlUnits; - static const size_type UsableByPreviousChunk = 0; + static const std::size_t BlockCtrlBytes = detail::ct_rounded_size::value; + static const std::size_t BlockCtrlUnits = BlockCtrlBytes/Alignment; + static const std::size_t MinBlockUnits = BlockCtrlUnits; + static const std::size_t MinBlockSize = MinBlockUnits*Alignment; + static const std::size_t AllocatedCtrlBytes = BlockCtrlBytes; + static const std::size_t AllocatedCtrlUnits = BlockCtrlUnits; + static const std::size_t UsableByPreviousChunk = 0; public: - static const size_type PayloadPerAllocation = BlockCtrlBytes; + static const std::size_t PayloadPerAllocation = BlockCtrlBytes; }; template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl - ::priv_first_block_offset(const void *this_ptr, size_type extra_hdr_bytes) +inline std::size_t simple_seq_fit_impl + ::priv_first_block_offset(const void *this_ptr, std::size_t extra_hdr_bytes) { //First align "this" pointer - size_type uint_this = (std::size_t)this_ptr; - size_type uint_aligned_this = uint_this/Alignment*Alignment; - size_type this_disalignment = (uint_this - uint_aligned_this); - size_type block1_off = - ipcdetail::get_rounded_size(sizeof(simple_seq_fit_impl) + extra_hdr_bytes + this_disalignment, Alignment) + std::size_t uint_this = (std::size_t)this_ptr; + std::size_t uint_aligned_this = uint_this/Alignment*Alignment; + std::size_t this_disalignment = (uint_this - uint_aligned_this); + std::size_t block1_off = + detail::get_rounded_size(sizeof(simple_seq_fit_impl) + extra_hdr_bytes + this_disalignment, Alignment) - this_disalignment; algo_impl_t::assert_alignment(this_disalignment + block1_off); return block1_off; } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl +inline std::size_t simple_seq_fit_impl ::priv_block_end_offset() const { //First align "this" pointer - size_type uint_this = (std::size_t)this; - size_type uint_aligned_this = uint_this/Alignment*Alignment; - size_type this_disalignment = (uint_this - uint_aligned_this); - size_type old_end = - ipcdetail::get_truncated_size(m_header.m_size + this_disalignment, Alignment) + std::size_t uint_this = (std::size_t)this; + std::size_t uint_aligned_this = uint_this/Alignment*Alignment; + std::size_t this_disalignment = (uint_this - uint_aligned_this); + std::size_t old_end = + detail::get_truncated_size(m_header.m_size + this_disalignment, Alignment) - this_disalignment; algo_impl_t::assert_alignment(old_end + this_disalignment); return old_end; @@ -329,20 +317,20 @@ simple_seq_fit_impl template inline simple_seq_fit_impl:: - simple_seq_fit_impl(size_type segment_size, size_type extra_hdr_bytes) + simple_seq_fit_impl(std::size_t size, std::size_t extra_hdr_bytes) { //Initialize sizes and counters m_header.m_allocated = 0; - m_header.m_size = segment_size; + m_header.m_size = size; m_header.m_extra_hdr_bytes = extra_hdr_bytes; //Initialize pointers - size_type block1_off = priv_first_block_offset(this, extra_hdr_bytes); + std::size_t block1_off = priv_first_block_offset(this, extra_hdr_bytes); m_header.m_root.m_next = reinterpret_cast ((reinterpret_cast(this) + block1_off)); - algo_impl_t::assert_alignment(ipcdetail::to_raw_pointer(m_header.m_root.m_next)); - m_header.m_root.m_next->m_size = (segment_size - block1_off)/Alignment; + algo_impl_t::assert_alignment(detail::get_pointer(m_header.m_root.m_next)); + m_header.m_root.m_next->m_size = (size - block1_off)/Alignment; m_header.m_root.m_next->m_next = &m_header.m_root; } @@ -355,10 +343,10 @@ inline simple_seq_fit_impl::~simple_seq_fit_impl() } template -inline void simple_seq_fit_impl::grow(size_type extra_size) +inline void simple_seq_fit_impl::grow(std::size_t extra_size) { //Old highest address block's end offset - size_type old_end = this->priv_block_end_offset(); + std::size_t old_end = this->priv_block_end_offset(); //Update managed buffer's size m_header.m_size += extra_size; @@ -386,7 +374,7 @@ void simple_seq_fit_impl::shrink_to_fit() //Get the root and the first memory block block_ctrl *prev = &m_header.m_root; block_ctrl *last = &m_header.m_root; - block_ctrl *block = ipcdetail::to_raw_pointer(last->m_next); + block_ctrl *block = detail::get_pointer(last->m_next); block_ctrl *root = &m_header.m_root; //No free block? @@ -396,7 +384,7 @@ void simple_seq_fit_impl::shrink_to_fit() while(block != root){ prev = last; last = block; - block = ipcdetail::to_raw_pointer(block->m_next); + block = detail::get_pointer(block->m_next); } char *last_free_end_address = reinterpret_cast(last) + last->m_size*Alignment; @@ -410,21 +398,21 @@ void simple_seq_fit_impl::shrink_to_fit() void *unique_block = 0; if(!m_header.m_allocated){ BOOST_ASSERT(prev == root); - size_type ignore; + std::size_t ignore; unique_block = priv_allocate(boost::interprocess::allocate_new, 0, 0, ignore).first; if(!unique_block) return; - last = ipcdetail::to_raw_pointer(m_header.m_root.m_next); + last = detail::get_pointer(m_header.m_root.m_next); BOOST_ASSERT(last_free_end_address == (reinterpret_cast(last) + last->m_size*Alignment)); } - size_type last_units = last->m_size; + std::size_t last_units = last->m_size; - size_type received_size; + std::size_t received_size; void *addr = priv_check_and_allocate(last_units, prev, last, received_size); (void)addr; BOOST_ASSERT(addr); BOOST_ASSERT(received_size == last_units*Alignment - AllocatedCtrlBytes); - + //Shrink it m_header.m_size /= Alignment; m_header.m_size -= last->m_size; @@ -460,43 +448,40 @@ void *simple_seq_fit_impl:: } template -inline void simple_seq_fit_impl::priv_add_segment(void *addr, size_type segment_size) -{ +inline void simple_seq_fit_impl::priv_add_segment(void *addr, std::size_t size) +{ algo_impl_t::assert_alignment(addr); //Check size - BOOST_ASSERT(!(segment_size < MinBlockSize)); - if(segment_size < MinBlockSize) + BOOST_ASSERT(!(size < MinBlockSize)); + if(size < MinBlockSize) return; //Construct big block using the new segment block_ctrl *new_block = static_cast(addr); - new_block->m_size = segment_size/Alignment; + new_block->m_size = size/Alignment; new_block->m_next = 0; //Simulate this block was previously allocated - m_header.m_allocated += new_block->m_size*Alignment; + m_header.m_allocated += new_block->m_size*Alignment; //Return block and insert it in the free block list this->priv_deallocate(priv_get_user_buffer(new_block)); } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl::get_size() const +inline std::size_t simple_seq_fit_impl::get_size() const { return m_header.m_size; } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl::get_free_memory() const +inline std::size_t simple_seq_fit_impl::get_free_memory() const { - return m_header.m_size - m_header.m_allocated - + return m_header.m_size - m_header.m_allocated - algo_impl_t::multiple_of_units(sizeof(*this) + m_header.m_extra_hdr_bytes); } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl:: - get_min_size (size_type extra_hdr_bytes) +inline std::size_t simple_seq_fit_impl:: + get_min_size (std::size_t extra_hdr_bytes) { - return ipcdetail::get_rounded_size((size_type)sizeof(simple_seq_fit_impl),Alignment) + - ipcdetail::get_rounded_size(extra_hdr_bytes,Alignment) + return detail::get_rounded_size(sizeof(simple_seq_fit_impl),Alignment) + + detail::get_rounded_size(extra_hdr_bytes,Alignment) + MinBlockSize; } @@ -508,7 +493,7 @@ inline bool simple_seq_fit_impl:: boost::interprocess::scoped_lock guard(m_header); //----------------------- return m_header.m_allocated == 0 && - ipcdetail::to_raw_pointer(m_header.m_root.m_next->m_next) == &m_header.m_root; + detail::get_pointer(m_header.m_root.m_next->m_next) == &m_header.m_root; } template @@ -517,15 +502,15 @@ inline void simple_seq_fit_impl::zero_free_memory() //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - block_ctrl *block = ipcdetail::to_raw_pointer(m_header.m_root.m_next); + block_ctrl *block = detail::get_pointer(m_header.m_root.m_next); //Iterate through all free portions do{ - //Just clear user the memory part reserved for the user + //Just clear user the memory part reserved for the user std::memset( priv_get_user_buffer(block) , 0 - , block->get_user_bytes()); - block = ipcdetail::to_raw_pointer(block->m_next); + , block->get_user_bytes()); + block = detail::get_pointer(block->m_next); } while(block != &m_header.m_root); } @@ -537,9 +522,9 @@ inline bool simple_seq_fit_impl:: //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - block_ctrl *block = ipcdetail::to_raw_pointer(m_header.m_root.m_next); + block_ctrl *block = detail::get_pointer(m_header.m_root.m_next); - size_type free_memory = 0; + std::size_t free_memory = 0; //Iterate through all blocks obtaining their size while(block != &m_header.m_root){ @@ -547,7 +532,7 @@ inline bool simple_seq_fit_impl:: if(!algo_impl_t::check_alignment(block)) return false; //Free blocks's next must be always valid - block_ctrl *next = ipcdetail::to_raw_pointer(block->m_next); + block_ctrl *next = detail::get_pointer(block->m_next); if(!next){ return false; } @@ -569,45 +554,45 @@ inline bool simple_seq_fit_impl:: template inline void* simple_seq_fit_impl:: - allocate(size_type nbytes) + allocate(std::size_t nbytes) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- - size_type ignore; + std::size_t ignore; return priv_allocate(boost::interprocess::allocate_new, nbytes, nbytes, ignore).first; } template inline void* simple_seq_fit_impl:: - allocate_aligned(size_type nbytes, size_type alignment) -{ + allocate_aligned(std::size_t nbytes, std::size_t alignment) +{ //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- return algo_impl_t:: - allocate_aligned(this, nbytes, alignment); + allocate_aligned(this, nbytes, alignment); } template template inline std::pair simple_seq_fit_impl:: - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, T *reuse_ptr) { std::pair ret = priv_allocation_command (command, limit_size, preferred_size, received_size, static_cast(reuse_ptr), sizeof(T)); - BOOST_ASSERT(0 == ((std::size_t)ret.first % ::boost::alignment_of::value)); + BOOST_ASSERT(0 == ((std::size_t)ret.first % detail::alignment_of::value)); return std::pair(static_cast(ret.first), ret.second); } template inline std::pair simple_seq_fit_impl:: - raw_allocation_command (boost::interprocess::allocation_type command, size_type limit_objects, - size_type preferred_objects,size_type &received_objects, - void *reuse_ptr, size_type sizeof_object) + raw_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_objects, + std::size_t preferred_objects,std::size_t &received_objects, + void *reuse_ptr, std::size_t sizeof_object) { if(!sizeof_object) return std::pair(static_cast(0), false); @@ -624,21 +609,21 @@ inline std::pair simple_seq_fit_impl:: template inline std::pair simple_seq_fit_impl:: - priv_allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size, size_type &received_size, - void *reuse_ptr, size_type sizeof_object) + priv_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size, std::size_t &received_size, + void *reuse_ptr, std::size_t sizeof_object) { command &= ~boost::interprocess::expand_bwd; if(!command) return std::pair(static_cast(0), false); std::pair ret; - size_type max_count = m_header.m_size/sizeof_object; + std::size_t max_count = m_header.m_size/sizeof_object; if(limit_size > max_count || preferred_size > max_count){ ret.first = 0; return ret; } - size_type l_size = limit_size*sizeof_object; - size_type p_size = preferred_size*sizeof_object; - size_type r_size; + std::size_t l_size = limit_size*sizeof_object; + std::size_t p_size = preferred_size*sizeof_object; + std::size_t r_size; { //----------------------- boost::interprocess::scoped_lock guard(m_header); @@ -650,8 +635,8 @@ inline std::pair simple_seq_fit_impl:: } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl::size(const void *ptr) const +inline std::size_t simple_seq_fit_impl:: + size(const void *ptr) const { //We need no synchronization since this block is not going //to be modified @@ -663,9 +648,9 @@ simple_seq_fit_impl::size(const void *ptr) const template void* simple_seq_fit_impl:: priv_expand_both_sides(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr ,bool only_preferred_backwards) { @@ -686,18 +671,18 @@ void* simple_seq_fit_impl:: received_size = this->size(reuse_ptr); } if(command & boost::interprocess::expand_bwd){ - size_type extra_forward = !received_size ? 0 : received_size + BlockCtrlBytes; + std::size_t extra_forward = !received_size ? 0 : received_size + BlockCtrlBytes; prev_block_t prev_pair = priv_prev_block_if_free(reuse); block_ctrl *prev = prev_pair.second; if(!prev){ return 0; } - size_type needs_backwards = - ipcdetail::get_rounded_size(preferred_size - extra_forward, Alignment); - + std::size_t needs_backwards = + detail::get_rounded_size(preferred_size - extra_forward, Alignment); + if(!only_preferred_backwards){ - max_value(ipcdetail::get_rounded_size(min_size - extra_forward, Alignment) + max_value(detail::get_rounded_size(min_size - extra_forward, Alignment) ,min_value(prev->get_user_bytes(), needs_backwards)); } @@ -707,16 +692,16 @@ void* simple_seq_fit_impl:: if(!priv_expand(reuse_ptr, received_size, received_size, received_size)){ BOOST_ASSERT(0); } - + //We need a minimum size to split the previous one if((prev->get_user_bytes() - needs_backwards) > 2*BlockCtrlBytes){ block_ctrl *new_block = reinterpret_cast (reinterpret_cast(reuse) - needs_backwards - BlockCtrlBytes); new_block->m_next = 0; - new_block->m_size = + new_block->m_size = BlockCtrlUnits + (needs_backwards + extra_forward)/Alignment; - prev->m_size = + prev->m_size = (prev->get_total_bytes() - needs_backwards)/Alignment - BlockCtrlUnits; received_size = needs_backwards + extra_forward; m_header.m_allocated += needs_backwards + BlockCtrlBytes; @@ -741,22 +726,23 @@ void* simple_seq_fit_impl:: template inline void simple_seq_fit_impl:: - deallocate_many(typename simple_seq_fit_impl::multiallocation_chain &chain) + deallocate_many(typename simple_seq_fit_impl::multiallocation_chain chain) { //----------------------- boost::interprocess::scoped_lock guard(m_header); //----------------------- while(!chain.empty()){ - this->priv_deallocate(to_raw_pointer(chain.pop_front())); + void *addr = chain.front(); + chain.pop_front(); + this->priv_deallocate(addr); } } template -inline typename simple_seq_fit_impl::size_type -simple_seq_fit_impl:: - priv_get_total_units(size_type userbytes) +inline std::size_t simple_seq_fit_impl:: + priv_get_total_units(std::size_t userbytes) { - size_type s = ipcdetail::get_rounded_size(userbytes, Alignment)/Alignment; + std::size_t s = detail::get_rounded_size(userbytes, Alignment)/Alignment; if(!s) ++s; return BlockCtrlUnits + s; } @@ -764,13 +750,13 @@ simple_seq_fit_impl:: template std::pair simple_seq_fit_impl:: priv_allocate(boost::interprocess::allocation_type command - ,size_type limit_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t limit_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr) { if(command & boost::interprocess::shrink_in_place){ - bool success = + bool success = algo_impl_t::shrink(this, reuse_ptr, limit_size, preferred_size, received_size); return std::pair ((success ? reuse_ptr : 0), true); } @@ -781,15 +767,15 @@ std::pair simple_seq_fit_impl:: return return_type(static_cast(0), false); //Number of units to request (including block_ctrl header) - size_type nunits = ipcdetail::get_rounded_size(preferred_size, Alignment)/Alignment + BlockCtrlUnits; + std::size_t nunits = detail::get_rounded_size(preferred_size, Alignment)/Alignment + BlockCtrlUnits; //Get the root and the first memory block block_ctrl *prev = &m_header.m_root; - block_ctrl *block = ipcdetail::to_raw_pointer(prev->m_next); + block_ctrl *block = detail::get_pointer(prev->m_next); block_ctrl *root = &m_header.m_root; block_ctrl *biggest_block = 0; block_ctrl *prev_biggest_block = 0; - size_type biggest_size = 0; + std::size_t biggest_size = 0; //Expand in place //reuse_ptr, limit_size, preferred_size, received_size @@ -820,13 +806,13 @@ std::pair simple_seq_fit_impl:: } //Bad luck, let's check next block prev = block; - block = ipcdetail::to_raw_pointer(block->m_next); + block = detail::get_pointer(block->m_next); } //Bad luck finding preferred_size, now if we have any biggest_block //try with this block if(biggest_block){ - size_type limit_units = ipcdetail::get_rounded_size(limit_size, Alignment)/Alignment + BlockCtrlUnits; + std::size_t limit_units = detail::get_rounded_size(limit_size, Alignment)/Alignment + BlockCtrlUnits; if(biggest_block->m_size < limit_units) return return_type(static_cast(0), false); @@ -866,7 +852,7 @@ inline typename simple_seq_fit_impl::block_ctrl * //Check if the adjacent block is in the managed segment char *this_char_ptr = reinterpret_cast(this); char *next_char_ptr = reinterpret_cast(next_block); - size_type distance = (size_type)(next_char_ptr - this_char_ptr)/Alignment; + std::size_t distance = (next_char_ptr - this_char_ptr)/Alignment; if(distance >= (m_header.m_size/Alignment)){ //"next_block" does not exist so we can't expand "block" @@ -880,7 +866,7 @@ inline typename simple_seq_fit_impl::block_ctrl * } template -inline +inline std::pair::block_ctrl * ,typename simple_seq_fit_impl::block_ctrl *> simple_seq_fit_impl:: @@ -891,13 +877,13 @@ inline //Take the address where the previous block should go block_ctrl *root = &m_header.m_root; block_ctrl *prev_2_block = root; - block_ctrl *prev_block = ipcdetail::to_raw_pointer(root->m_next); + block_ctrl *prev_block = detail::get_pointer(root->m_next); while((reinterpret_cast(prev_block) + prev_block->m_size*Alignment) != reinterpret_cast(ptr) && prev_block != root){ prev_2_block = prev_block; - prev_block = ipcdetail::to_raw_pointer(prev_block->m_next); + prev_block = detail::get_pointer(prev_block->m_next); } if(prev_block == root || !prev_block->m_next) @@ -906,7 +892,7 @@ inline //Check if the previous block is in the managed segment char *this_char_ptr = reinterpret_cast(this); char *prev_char_ptr = reinterpret_cast(prev_block); - size_type distance = (size_type)(prev_char_ptr - this_char_ptr)/Alignment; + std::size_t distance = (prev_char_ptr - this_char_ptr)/Alignment; if(distance >= (m_header.m_size/Alignment)){ //"previous_block" does not exist so we can't expand "block" @@ -919,13 +905,13 @@ inline template inline bool simple_seq_fit_impl:: priv_expand (void *ptr - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size) + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size) { //Obtain the real size of the block block_ctrl *block = reinterpret_cast(priv_get_block(ptr)); - size_type old_block_size = block->m_size; + std::size_t old_block_size = block->m_size; //All used blocks' next is marked with 0 so check it BOOST_ASSERT(block->m_next == 0); @@ -934,14 +920,14 @@ inline bool simple_seq_fit_impl:: received_size = old_block_size*Alignment - BlockCtrlBytes; //Now translate it to Alignment units - min_size = ipcdetail::get_rounded_size(min_size, Alignment)/Alignment; - preferred_size = ipcdetail::get_rounded_size(preferred_size, Alignment)/Alignment; + min_size = detail::get_rounded_size(min_size, Alignment)/Alignment; + preferred_size = detail::get_rounded_size(preferred_size, Alignment)/Alignment; //Some parameter checks if(min_size > preferred_size) return false; - size_type data_size = old_block_size - BlockCtrlUnits; + std::size_t data_size = old_block_size - BlockCtrlUnits; if(data_size >= min_size) return true; @@ -952,7 +938,7 @@ inline bool simple_seq_fit_impl:: } //Is "block" + "next_block" big enough? - size_type merged_size = old_block_size + next_block->m_size; + std::size_t merged_size = old_block_size + next_block->m_size; //Now we can expand this block further than before received_size = merged_size*Alignment - BlockCtrlBytes; @@ -964,21 +950,21 @@ inline bool simple_seq_fit_impl:: //We can fill expand. Merge both blocks, block->m_next = next_block->m_next; block->m_size = merged_size; - + //Find the previous free block of next_block block_ctrl *prev = &m_header.m_root; - while(ipcdetail::to_raw_pointer(prev->m_next) != next_block){ - prev = ipcdetail::to_raw_pointer(prev->m_next); + while(detail::get_pointer(prev->m_next) != next_block){ + prev = detail::get_pointer(prev->m_next); } //Now insert merged block in the free list //This allows reusing allocation logic in this function - m_header.m_allocated -= old_block_size*Alignment; + m_header.m_allocated -= old_block_size*Alignment; prev->m_next = block; //Now use check and allocate to do the allocation logic preferred_size += BlockCtrlUnits; - size_type nunits = preferred_size < merged_size ? preferred_size : merged_size; + std::size_t nunits = preferred_size < merged_size ? preferred_size : merged_size; //This must success since nunits is less than merged_size! if(!this->priv_check_and_allocate (nunits, prev, block, received_size)){ @@ -987,24 +973,24 @@ inline bool simple_seq_fit_impl:: BOOST_ASSERT(0); return false; } - return true; + return true; } template inline void* simple_seq_fit_impl::priv_check_and_allocate - (size_type nunits + (std::size_t nunits ,typename simple_seq_fit_impl::block_ctrl* prev ,typename simple_seq_fit_impl::block_ctrl* block - ,size_type &received_size) + ,std::size_t &received_size) { - size_type upper_nunits = nunits + BlockCtrlUnits; + std::size_t upper_nunits = nunits + BlockCtrlUnits; bool found = false; if (block->m_size > upper_nunits){ - //This block is bigger than needed, split it in + //This block is bigger than needed, split it in //two blocks, the first's size will be "units" //the second's size will be "block->m_size-units" - size_type total_size = block->m_size; + std::size_t total_size = block->m_size; block->m_size = nunits; block_ctrl *new_block = reinterpret_cast @@ -1052,10 +1038,10 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) //Let's get free block list. List is always sorted //by memory address to allow block merging. - //Pointer next always points to the first + //Pointer next always points to the first //(lower address) block block_ctrl * prev = &m_header.m_root; - block_ctrl * pos = ipcdetail::to_raw_pointer(m_header.m_root.m_next); + block_ctrl * pos = detail::get_pointer(m_header.m_root.m_next); block_ctrl * block = reinterpret_cast(priv_get_block(addr)); //All used blocks' next is marked with 0 so check it @@ -1064,26 +1050,26 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) //Check if alignment and block size are right algo_impl_t::assert_alignment(addr); - size_type total_size = Alignment*block->m_size; + std::size_t total_size = Alignment*block->m_size; BOOST_ASSERT(m_header.m_allocated >= total_size); - + //Update used memory count - m_header.m_allocated -= total_size; + m_header.m_allocated -= total_size; //Let's find the previous and the next block of the block to deallocate //This ordering comparison must be done with original pointers //types since their mapping to raw pointers can be different //in each process - while((ipcdetail::to_raw_pointer(pos) != &m_header.m_root) && (block > pos)){ + while((detail::get_pointer(pos) != &m_header.m_root) && (block > pos)){ prev = pos; - pos = ipcdetail::to_raw_pointer(pos->m_next); + pos = detail::get_pointer(pos->m_next); } //Try to combine with upper block - char *block_char_ptr = reinterpret_cast(ipcdetail::to_raw_pointer(block)); + char *block_char_ptr = reinterpret_cast(detail::get_pointer(block)); - if ((block_char_ptr + Alignment*block->m_size) == - reinterpret_cast(ipcdetail::to_raw_pointer(pos))){ + if ((block_char_ptr + Alignment*block->m_size) == + reinterpret_cast(detail::get_pointer(pos))){ block->m_size += pos->m_size; block->m_next = pos->m_next; } @@ -1092,8 +1078,8 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) } //Try to combine with lower block - if ((reinterpret_cast(ipcdetail::to_raw_pointer(prev)) - + Alignment*prev->m_size) == + if ((reinterpret_cast(detail::get_pointer(prev)) + + Alignment*prev->m_size) == block_char_ptr){ @@ -1105,7 +1091,7 @@ void simple_seq_fit_impl::priv_deallocate(void* addr) } } -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/mem_algo/rbtree_best_fit.hpp b/utils/boost_idb/boost/interprocess/mem_algo/rbtree_best_fit.hpp index 0f42f7ed..1f982392 100644 --- a/utils/boost_idb/boost/interprocess/mem_algo/rbtree_best_fit.hpp +++ b/utils/boost_idb/boost/interprocess/mem_algo/rbtree_best_fit.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,27 +18,26 @@ #include #include -#include +#include #include #include #include -#include +#include #include +#include #include #include #include #include #include #include -#include -#include #include #include -#include #include #include #include +#include #include #include @@ -47,11 +46,6 @@ #include -//#define BOOST_INTERPROCESS_RBTREE_BEST_FIT_ABI_V1_HPP -//to maintain ABI compatible with the original version -//ABI had to be updated to fix compatibility issues when -//sharing shared memory between 32 adn 64 bit processes. - //!\file //!Describes a best-fit algorithm based in an intrusive red-black tree used to allocate //!objects in shared memory. This class is intended as a base class for single segment @@ -70,32 +64,24 @@ class rbtree_best_fit rbtree_best_fit(); rbtree_best_fit(const rbtree_best_fit &); rbtree_best_fit &operator=(const rbtree_best_fit &); - - private: - struct block_ctrl; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type block_ctrl_ptr; - - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type char_ptr; - /// @endcond public: - //!Shared mutex family used for the rest of the Interprocess framework + //!Shared interprocess_mutex family used for the rest of the Interprocess framework typedef MutexFamily mutex_family; //!Pointer type to be used with the rest of the Interprocess framework typedef VoidPointer void_pointer; - typedef ipcdetail::basic_multiallocation_chain multiallocation_chain; - - typedef typename boost::intrusive::pointer_traits::difference_type difference_type; - typedef typename boost::make_unsigned::type size_type; + typedef boost::container::containers_detail:: + basic_multiallocation_chain multiallocation_chain; /// @cond private: + struct block_ctrl; + typedef typename boost:: + pointer_to_other::type block_ctrl_ptr; + typedef typename boost:: + pointer_to_other::type char_ptr; typedef typename bi::make_set_base_hook < bi::void_pointer @@ -104,12 +90,12 @@ class rbtree_best_fit struct SizeHolder { - //!This block's memory size (including block_ctrl + //!This block's memory size (including block_ctrl //!header) in Alignment units - size_type m_prev_size : sizeof(size_type)*CHAR_BIT; - size_type m_size : sizeof(size_type)*CHAR_BIT - 2; - size_type m_prev_allocated : 1; - size_type m_allocated : 1; + std::size_t m_prev_size : sizeof(std::size_t)*CHAR_BIT; + std::size_t m_size : sizeof(std::size_t)*CHAR_BIT - 2; + std::size_t m_prev_allocated : 1; + std::size_t m_allocated : 1; }; //!Block control structure @@ -127,81 +113,83 @@ class rbtree_best_fit struct size_block_ctrl_compare { - bool operator()(size_type size, const block_ctrl &block) const + bool operator()(std::size_t size, const block_ctrl &block) const { return size < block.m_size; } - bool operator()(const block_ctrl &block, size_type size) const - { return block.m_size < size; } + bool operator()(const block_ctrl &block, std::size_t size) const + { return block.m_size < size; } }; - //!Shared mutex to protect memory allocate/deallocate - typedef typename MutexFamily::mutex_type mutex_type; + //!Shared interprocess_mutex to protect memory allocate/deallocate + typedef typename MutexFamily::mutex_type interprocess_mutex; typedef typename bi::make_multiset >::type Imultiset; typedef typename Imultiset::iterator imultiset_iterator; //!This struct includes needed data and derives from - //!mutex_type to allow EBO when using null mutex_type - struct header_t : public mutex_type + //!interprocess_mutex to allow EBO when using null interprocess_mutex + struct header_t : public interprocess_mutex { Imultiset m_imultiset; //!The extra size required by the segment - size_type m_extra_hdr_bytes; + std::size_t m_extra_hdr_bytes; //!Allocated bytes for internal checking - size_type m_allocated; + std::size_t m_allocated; //!The size of the memory segment - size_type m_size; + std::size_t m_size; } m_header; - friend class ipcdetail::memory_algorithm_common; - - typedef ipcdetail::memory_algorithm_common algo_impl_t; + friend class detail::memory_algorithm_common; + + typedef detail::memory_algorithm_common algo_impl_t; public: /// @endcond - //!Constructor. "size" is the total size of the managed memory segment, + //!Constructor. "size" is the total size of the managed memory segment, //!"extra_hdr_bytes" indicates the extra bytes beginning in the sizeof(rbtree_best_fit) //!offset that the allocator should not use at all. - rbtree_best_fit (size_type size, size_type extra_hdr_bytes); + rbtree_best_fit (std::size_t size, std::size_t extra_hdr_bytes); //!Destructor. ~rbtree_best_fit(); //!Obtains the minimum size needed by the algorithm - static size_type get_min_size (size_type extra_hdr_bytes); + static std::size_t get_min_size (std::size_t extra_hdr_bytes); //Functions for single segment management //!Allocates bytes, returns 0 if there is not more memory - void* allocate (size_type nbytes); + void* allocate (std::size_t nbytes); /// @cond //Experimental. Dont' use //!Multiple element allocation, same size - void allocate_many(size_type elem_bytes, size_type num_elements, multiallocation_chain &chain) + multiallocation_chain allocate_many(std::size_t elem_bytes, std::size_t num_elements) { + //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- - algo_impl_t::allocate_many(this, elem_bytes, num_elements, chain); + return algo_impl_t::allocate_many(this, elem_bytes, num_elements); } //!Multiple element allocation, different size - void allocate_many(const size_type *elem_sizes, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain) + multiallocation_chain allocate_many(const std::size_t *elem_sizes, std::size_t n_elements, std::size_t sizeof_element) { + //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- - algo_impl_t::allocate_many(this, elem_sizes, n_elements, sizeof_element, chain); + return algo_impl_t::allocate_many(this, elem_sizes, n_elements, sizeof_element); } //!Multiple element allocation, different size - void deallocate_many(multiallocation_chain &chain); + void deallocate_many(multiallocation_chain chain); /// @endcond @@ -209,10 +197,10 @@ class rbtree_best_fit void deallocate (void *addr); //!Returns the size of the memory segment - size_type get_size() const; + std::size_t get_size() const; //!Returns the number of free bytes of the segment - size_type get_free_memory() const; + std::size_t get_free_memory() const; //!Initializes to zero all the memory that's not in use. //!This function is normally used for security reasons. @@ -220,7 +208,7 @@ class rbtree_best_fit //!Increases managed memory in //!extra_size bytes more - void grow(size_type extra_size); + void grow(std::size_t extra_size); //!Decreases managed memory as much as possible void shrink_to_fit(); @@ -234,43 +222,39 @@ class rbtree_best_fit template std::pair - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, T *reuse_ptr = 0); std::pair - raw_allocation_command (boost::interprocess::allocation_type command, size_type limit_object, - size_type preferred_object,size_type &received_object, - void *reuse_ptr = 0, size_type sizeof_object = 1); + raw_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_object, + std::size_t preferred_object,std::size_t &received_object, + void *reuse_ptr = 0, std::size_t sizeof_object = 1); //!Returns the size of the buffer previously allocated pointed by ptr - size_type size(const void *ptr) const; + std::size_t size(const void *ptr) const; //!Allocates aligned bytes, returns 0 if there is not more memory. //!Alignment must be power of 2 - void* allocate_aligned (size_type nbytes, size_type alignment); + void* allocate_aligned (std::size_t nbytes, std::size_t alignment); /// @cond private: - static size_type priv_first_block_offset_from_this(const void *this_ptr, size_type extra_hdr_bytes); - - block_ctrl *priv_first_block(); - - block_ctrl *priv_end_block(); + static std::size_t priv_first_block_offset(const void *this_ptr, std::size_t extra_hdr_bytes); std::pair - priv_allocation_command(boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, - void *reuse_ptr, size_type sizeof_object); + priv_allocation_command(boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, + void *reuse_ptr, std::size_t sizeof_object); //!Real allocation algorithm with min allocation option std::pair priv_allocate(boost::interprocess::allocation_type command - ,size_type limit_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t limit_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr = 0 - ,size_type backwards_multiple = 1); + ,std::size_t backwards_multiple = 1); //!Obtains the block control structure of the user buffer static block_ctrl *priv_get_block(const void *ptr); @@ -280,36 +264,33 @@ class rbtree_best_fit //!Returns the number of total units that a user buffer //!of "userbytes" bytes really occupies (including header) - static size_type priv_get_total_units(size_type userbytes); + static std::size_t priv_get_total_units(std::size_t userbytes); //!Real expand function implementation bool priv_expand(void *ptr - ,const size_type min_size, const size_type preferred_size - ,size_type &received_size); + ,const std::size_t min_size, const std::size_t preferred_size + ,std::size_t &received_size); //!Real expand to both sides implementation void* priv_expand_both_sides(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr ,bool only_preferred_backwards - ,size_type backwards_multiple); + ,std::size_t backwards_multiple); + + //!Get poitner of the previous block (previous block must be free) + block_ctrl * priv_prev_block(block_ctrl *ptr); //!Returns true if the previous block is allocated bool priv_is_prev_allocated(block_ctrl *ptr); //!Get a pointer of the "end" block from the first block of the segment - static block_ctrl * priv_end_block(block_ctrl *first_segment_block); - - //!Get a pointer of the "first" block from the end block of the segment - static block_ctrl * priv_first_block(block_ctrl *end_segment_block); - - //!Get poitner of the previous block (previous block must be free) - static block_ctrl * priv_prev_block(block_ctrl *ptr); + block_ctrl * priv_end_block(block_ctrl *first_segment_block); //!Get the size in the tail of the previous block - static block_ctrl * priv_next_block(block_ctrl *ptr); + block_ctrl * priv_next_block(block_ctrl *ptr); //!Check if this block is free (not allocated) bool priv_is_allocated_block(block_ctrl *ptr); @@ -317,149 +298,80 @@ class rbtree_best_fit //!Marks the block as allocated void priv_mark_as_allocated_block(block_ctrl *ptr); - //!Marks the block as allocated - void priv_mark_new_allocated_block(block_ctrl *ptr) - { return priv_mark_as_allocated_block(ptr); } - //!Marks the block as allocated void priv_mark_as_free_block(block_ctrl *ptr); //!Checks if block has enough memory and splits/unlinks the block //!returning the address to the users - void* priv_check_and_allocate(size_type units + void* priv_check_and_allocate(std::size_t units ,block_ctrl* block - ,size_type &received_size); + ,std::size_t &received_size); //!Real deallocation algorithm void priv_deallocate(void *addr); //!Makes a new memory portion available for allocation - void priv_add_segment(void *addr, size_type size); + void priv_add_segment(void *addr, std::size_t size); - public: + void priv_mark_new_allocated_block(block_ctrl *block); - static const size_type Alignment = !MemAlignment - ? size_type(::boost::alignment_of< ::boost::detail::max_align>::value) - : size_type(MemAlignment) + public: + + static const std::size_t Alignment = !MemAlignment + ? detail::alignment_of::value + : MemAlignment ; private: //Due to embedded bits in size, Alignment must be at least 4 BOOST_STATIC_ASSERT((Alignment >= 4)); //Due to rbtree size optimizations, Alignment must have at least pointer alignment - BOOST_STATIC_ASSERT((Alignment >= ::boost::alignment_of::value)); - static const size_type AlignmentMask = (Alignment - 1); - static const size_type BlockCtrlBytes = ipcdetail::ct_rounded_size::value; - static const size_type BlockCtrlUnits = BlockCtrlBytes/Alignment; - static const size_type AllocatedCtrlBytes = ipcdetail::ct_rounded_size::value; - static const size_type AllocatedCtrlUnits = AllocatedCtrlBytes/Alignment; - static const size_type EndCtrlBlockBytes = ipcdetail::ct_rounded_size::value; - static const size_type EndCtrlBlockUnits = EndCtrlBlockBytes/Alignment; - static const size_type MinBlockUnits = BlockCtrlUnits; - static const size_type UsableByPreviousChunk = sizeof(size_type); + BOOST_STATIC_ASSERT((Alignment >= detail::alignment_of::value)); + static const std::size_t AlignmentMask = (Alignment - 1); + static const std::size_t BlockCtrlBytes = detail::ct_rounded_size::value; + static const std::size_t BlockCtrlUnits = BlockCtrlBytes/Alignment; + static const std::size_t AllocatedCtrlBytes = detail::ct_rounded_size::value; + static const std::size_t AllocatedCtrlUnits = AllocatedCtrlBytes/Alignment; + static const std::size_t EndCtrlBlockBytes = detail::ct_rounded_size::value; + static const std::size_t EndCtrlBlockUnits = EndCtrlBlockBytes/Alignment; + static const std::size_t MinBlockUnits = BlockCtrlUnits; + static const std::size_t UsableByPreviousChunk = sizeof(std::size_t); //Make sure the maximum alignment is power of two - BOOST_STATIC_ASSERT((0 == (Alignment & (Alignment - size_type(1u))))); + BOOST_STATIC_ASSERT((0 == (Alignment & (Alignment - std::size_t(1u))))); /// @endcond public: - static const size_type PayloadPerAllocation = AllocatedCtrlBytes - UsableByPreviousChunk; + static const std::size_t PayloadPerAllocation = AllocatedCtrlBytes - UsableByPreviousChunk; }; /// @cond template -inline typename rbtree_best_fit::size_type - rbtree_best_fit - ::priv_first_block_offset_from_this(const void *this_ptr, size_type extra_hdr_bytes) +inline std::size_t rbtree_best_fit + ::priv_first_block_offset(const void *this_ptr, std::size_t extra_hdr_bytes) { - size_type uint_this = (std::size_t)this_ptr; - size_type main_hdr_end = uint_this + sizeof(rbtree_best_fit) + extra_hdr_bytes; - size_type aligned_main_hdr_end = ipcdetail::get_rounded_size(main_hdr_end, Alignment); - size_type block1_off = aligned_main_hdr_end - uint_this; + std::size_t uint_this = (std::size_t)this_ptr; + std::size_t main_hdr_end = uint_this + sizeof(rbtree_best_fit) + extra_hdr_bytes; + std::size_t aligned_main_hdr_end = detail::get_rounded_size(main_hdr_end, Alignment); + std::size_t block1_off = aligned_main_hdr_end - uint_this; algo_impl_t::assert_alignment(aligned_main_hdr_end); algo_impl_t::assert_alignment(uint_this + block1_off); return block1_off; } -template -void rbtree_best_fit:: - priv_add_segment(void *addr, size_type segment_size) -{ - //Check alignment - algo_impl_t::check_alignment(addr); - //Check size - BOOST_ASSERT(segment_size >= (BlockCtrlBytes + EndCtrlBlockBytes)); - - //Initialize the first big block and the "end" node - block_ctrl *first_big_block = new(addr)block_ctrl; - first_big_block->m_size = segment_size/Alignment - EndCtrlBlockUnits; - BOOST_ASSERT(first_big_block->m_size >= BlockCtrlUnits); - - //The "end" node is just a node of size 0 with the "end" bit set - block_ctrl *end_block = static_cast - (new (reinterpret_cast(addr) + first_big_block->m_size*Alignment)SizeHolder); - - //This will overwrite the prev part of the "end" node - priv_mark_as_free_block (first_big_block); - #ifdef BOOST_INTERPROCESS_RBTREE_BEST_FIT_ABI_V1_HPP - first_big_block->m_prev_size = end_block->m_size = - (reinterpret_cast(first_big_block) - reinterpret_cast(end_block))/Alignment; - #else - first_big_block->m_prev_size = end_block->m_size = - (reinterpret_cast(end_block) - reinterpret_cast(first_big_block))/Alignment; - #endif - end_block->m_allocated = 1; - first_big_block->m_prev_allocated = 1; - - BOOST_ASSERT(priv_next_block(first_big_block) == end_block); - BOOST_ASSERT(priv_prev_block(end_block) == first_big_block); - BOOST_ASSERT(priv_first_block() == first_big_block); - BOOST_ASSERT(priv_end_block() == end_block); - - //Some check to validate the algorithm, since it makes some assumptions - //to optimize the space wasted in bookkeeping: - - //Check that the sizes of the header are placed before the rbtree - BOOST_ASSERT(static_cast(static_cast(first_big_block)) - < static_cast(static_cast(first_big_block))); - //Insert it in the intrusive containers - m_header.m_imultiset.insert(*first_big_block); -} - -template -inline typename rbtree_best_fit::block_ctrl * - rbtree_best_fit - ::priv_first_block() -{ - size_type block1_off = priv_first_block_offset_from_this(this, m_header.m_extra_hdr_bytes); - return reinterpret_cast(reinterpret_cast(this) + block1_off); -} - -template -inline typename rbtree_best_fit::block_ctrl * - rbtree_best_fit - ::priv_end_block() -{ - size_type block1_off = priv_first_block_offset_from_this(this, m_header.m_extra_hdr_bytes); - const size_type original_first_block_size = m_header.m_size/Alignment*Alignment - block1_off/Alignment*Alignment - EndCtrlBlockBytes; - block_ctrl *end_block = reinterpret_cast - (reinterpret_cast(this) + block1_off + original_first_block_size); - return end_block; -} - template inline rbtree_best_fit:: - rbtree_best_fit(size_type segment_size, size_type extra_hdr_bytes) + rbtree_best_fit(std::size_t size, std::size_t extra_hdr_bytes) { //Initialize the header m_header.m_allocated = 0; - m_header.m_size = segment_size; + m_header.m_size = size; m_header.m_extra_hdr_bytes = extra_hdr_bytes; //Now write calculate the offset of the first big block that will //cover the whole segment - BOOST_ASSERT(get_min_size(extra_hdr_bytes) <= segment_size); - size_type block1_off = priv_first_block_offset_from_this(this, extra_hdr_bytes); - priv_add_segment(reinterpret_cast(this) + block1_off, segment_size - block1_off); + BOOST_ASSERT(get_min_size(extra_hdr_bytes) <= size); + std::size_t block1_off = priv_first_block_offset(this, extra_hdr_bytes); + priv_add_segment(reinterpret_cast(this) + block1_off, size - block1_off); } template @@ -471,51 +383,49 @@ inline rbtree_best_fit::~rbtree_best_fit } template -void rbtree_best_fit::grow(size_type extra_size) +void rbtree_best_fit::grow(std::size_t extra_size) { //Get the address of the first block - block_ctrl *first_block = priv_first_block(); - block_ctrl *old_end_block = priv_end_block(); - size_type old_border_offset = (size_type)(reinterpret_cast(old_end_block) - + std::size_t block1_off = + priv_first_block_offset(this, m_header.m_extra_hdr_bytes); + + block_ctrl *first_block = reinterpret_cast + (reinterpret_cast(this) + block1_off); + block_ctrl *old_end_block = priv_end_block(first_block); + BOOST_ASSERT(priv_is_allocated_block(old_end_block)); + std::size_t old_border_offset = (reinterpret_cast(old_end_block) - reinterpret_cast(this)) + EndCtrlBlockBytes; //Update managed buffer's size m_header.m_size += extra_size; //We need at least MinBlockUnits blocks to create a new block +// BOOST_ASSERT((m_header.m_size - old_end) >= MinBlockUnits); if((m_header.m_size - old_border_offset) < MinBlockUnits){ return; } //Now create a new block between the old end and the new end - size_type align_offset = (m_header.m_size - old_border_offset)/Alignment; + std::size_t align_offset = (m_header.m_size - old_border_offset)/Alignment; block_ctrl *new_end_block = reinterpret_cast (reinterpret_cast(old_end_block) + align_offset*Alignment); - - //the last and first block are special: - //new_end_block->m_size & first_block->m_prev_size store the absolute value - //between them - new_end_block->m_allocated = 1; - #ifdef BOOST_INTERPROCESS_RBTREE_BEST_FIT_ABI_V1_HPP - new_end_block->m_size = (reinterpret_cast(first_block) - + new_end_block->m_size = (reinterpret_cast(first_block) - reinterpret_cast(new_end_block))/Alignment; - #else - new_end_block->m_size = (reinterpret_cast(new_end_block) - - reinterpret_cast(first_block))/Alignment; - #endif first_block->m_prev_size = new_end_block->m_size; - first_block->m_prev_allocated = 1; - BOOST_ASSERT(new_end_block == priv_end_block()); + BOOST_ASSERT(first_block == priv_next_block(new_end_block)); + priv_mark_new_allocated_block(new_end_block); + + BOOST_ASSERT(new_end_block == priv_end_block(first_block)); //The old end block is the new block block_ctrl *new_block = old_end_block; - new_block->m_size = (reinterpret_cast(new_end_block) - + new_block->m_size = (reinterpret_cast(new_end_block) - reinterpret_cast(new_block))/Alignment; BOOST_ASSERT(new_block->m_size >= BlockCtrlUnits); - priv_mark_as_allocated_block(new_block); + priv_mark_new_allocated_block(new_block); BOOST_ASSERT(priv_next_block(new_block) == new_end_block); - m_header.m_allocated += (size_type)new_block->m_size*Alignment; + m_header.m_allocated += new_block->m_size*Alignment; //Now deallocate the newly created block this->priv_deallocate(priv_get_user_buffer(new_block)); @@ -523,27 +433,30 @@ void rbtree_best_fit::grow(size_type ext template void rbtree_best_fit::shrink_to_fit() -{ +{ //Get the address of the first block - block_ctrl *first_block = priv_first_block(); + std::size_t block1_off = + priv_first_block_offset(this, m_header.m_extra_hdr_bytes); + + block_ctrl *first_block = reinterpret_cast + (reinterpret_cast(this) + block1_off); algo_impl_t::assert_alignment(first_block); - //block_ctrl *old_end_block = priv_end_block(first_block); - block_ctrl *old_end_block = priv_end_block(); + block_ctrl *old_end_block = priv_end_block(first_block); algo_impl_t::assert_alignment(old_end_block); - size_type old_end_block_size = old_end_block->m_size; + BOOST_ASSERT(priv_is_allocated_block(old_end_block)); + + algo_impl_t::assert_alignment(old_end_block); + + std::size_t old_end_block_size = old_end_block->m_size; void *unique_buffer = 0; block_ctrl *last_block; - //Check if no memory is allocated between the first and last block if(priv_next_block(first_block) == old_end_block){ - //If so check if we can allocate memory - size_type ignore; + std::size_t ignore; unique_buffer = priv_allocate(boost::interprocess::allocate_new, 0, 0, ignore).first; - //If not, return, we can't shrink if(!unique_buffer) return; - //If we can, mark the position just after the new allocation as the new end algo_impl_t::assert_alignment(unique_buffer); block_ctrl *unique_block = priv_get_block(unique_buffer); BOOST_ASSERT(priv_is_allocated_block(unique_block)); @@ -553,65 +466,100 @@ void rbtree_best_fit::shrink_to_fit() algo_impl_t::assert_alignment(last_block); } else{ - //If memory is allocated, check if the last block is allocated if(priv_is_prev_allocated(old_end_block)) return; - //If not, mark last block after the free block last_block = priv_prev_block(old_end_block); } - size_type last_block_size = last_block->m_size; + std::size_t last_block_size = last_block->m_size; //Erase block from the free tree, since we will erase it m_header.m_imultiset.erase(Imultiset::s_iterator_to(*last_block)); - size_type shrunk_border_offset = (size_type)(reinterpret_cast(last_block) - + std::size_t shrunk_border_offset = (reinterpret_cast(last_block) - reinterpret_cast(this)) + EndCtrlBlockBytes; - + block_ctrl *new_end_block = last_block; algo_impl_t::assert_alignment(new_end_block); + new_end_block->m_size = old_end_block_size + last_block_size; + priv_mark_as_allocated_block(new_end_block); - //Write new end block attributes - #ifdef BOOST_INTERPROCESS_RBTREE_BEST_FIT_ABI_V1_HPP - new_end_block->m_size = first_block->m_prev_size = - (reinterpret_cast(first_block) - reinterpret_cast(new_end_block))/Alignment; - #else - new_end_block->m_size = first_block->m_prev_size = - (reinterpret_cast(new_end_block) - reinterpret_cast(first_block))/Alignment; - #endif - - new_end_block->m_allocated = 1; - (void)last_block_size; - (void)old_end_block_size; - BOOST_ASSERT(new_end_block->m_size == (old_end_block_size - last_block_size)); + //Although the first block might be allocated, we'll + //store the offset to the end block since in the previous + //offset can't be overwritten by a previous block + first_block->m_prev_size = new_end_block->m_size; + BOOST_ASSERT(priv_end_block(first_block) == new_end_block); //Update managed buffer's size m_header.m_size = shrunk_border_offset; - BOOST_ASSERT(priv_end_block() == new_end_block); if(unique_buffer) priv_deallocate(unique_buffer); } template -inline typename rbtree_best_fit::size_type -rbtree_best_fit::get_size() const +void rbtree_best_fit:: + priv_add_segment(void *addr, std::size_t size) +{ + //Check alignment + algo_impl_t::check_alignment(addr); + //Check size + BOOST_ASSERT(size >= (BlockCtrlBytes + EndCtrlBlockBytes)); + + //Initialize the first big block and the "end" node + block_ctrl *first_big_block = new(addr)block_ctrl; + first_big_block->m_size = size/Alignment - EndCtrlBlockUnits; + BOOST_ASSERT(first_big_block->m_size >= BlockCtrlUnits); + + //The "end" node is just a node of size 0 with the "end" bit set + block_ctrl *end_block = static_cast + (new (reinterpret_cast(addr) + first_big_block->m_size*Alignment)SizeHolder); + + //This will overwrite the prev part of the "end" node + priv_mark_as_free_block (first_big_block); + first_big_block->m_prev_size = end_block->m_size = + (reinterpret_cast(first_big_block) - reinterpret_cast(end_block))/Alignment; + priv_mark_as_allocated_block(end_block); + + BOOST_ASSERT(priv_next_block(first_big_block) == end_block); + BOOST_ASSERT(priv_next_block(end_block) == first_big_block); + BOOST_ASSERT(priv_end_block(first_big_block) == end_block); + BOOST_ASSERT(priv_prev_block(end_block) == first_big_block); + + //Some check to validate the algorithm, since it makes some assumptions + //to optimize the space wasted in bookkeeping: + + //Check that the sizes of the header are placed before the rbtree + BOOST_ASSERT(static_cast(static_cast(first_big_block)) + < static_cast(static_cast(first_big_block))); + + //Check that the alignment is power of two (we use some optimizations based on this) + //BOOST_ASSERT((Alignment % 2) == 0); + //Insert it in the intrusive containers + m_header.m_imultiset.insert(*first_big_block); +} + +template +inline void rbtree_best_fit:: + priv_mark_new_allocated_block(block_ctrl *new_block) +{ priv_mark_as_allocated_block(new_block); } + +template +inline std::size_t rbtree_best_fit::get_size() const { return m_header.m_size; } template -typename rbtree_best_fit::size_type -rbtree_best_fit::get_free_memory() const +inline std::size_t rbtree_best_fit::get_free_memory() const { - return m_header.m_size - m_header.m_allocated - - priv_first_block_offset_from_this(this, m_header.m_extra_hdr_bytes); + return m_header.m_size - m_header.m_allocated - + priv_first_block_offset(this, m_header.m_extra_hdr_bytes); } template -typename rbtree_best_fit::size_type -rbtree_best_fit:: - get_min_size (size_type extra_hdr_bytes) +inline std::size_t rbtree_best_fit:: + get_min_size (std::size_t extra_hdr_bytes) { return (algo_impl_t::ceil_units(sizeof(rbtree_best_fit)) + - algo_impl_t::ceil_units(extra_hdr_bytes) + + algo_impl_t::ceil_units(extra_hdr_bytes) + MinBlockUnits + EndCtrlBlockUnits)*Alignment; } @@ -620,15 +568,15 @@ inline bool rbtree_best_fit:: all_memory_deallocated() { //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- - size_type block1_off = - priv_first_block_offset_from_this(this, m_header.m_extra_hdr_bytes); + std::size_t block1_off = + priv_first_block_offset(this, m_header.m_extra_hdr_bytes); - return m_header.m_allocated == 0 && + return m_header.m_allocated == 0 && m_header.m_imultiset.begin() != m_header.m_imultiset.end() && (++m_header.m_imultiset.begin()) == m_header.m_imultiset.end() - && m_header.m_imultiset.begin()->m_size == + && m_header.m_imultiset.begin()->m_size == (m_header.m_size - block1_off - EndCtrlBlockBytes)/Alignment; } @@ -637,15 +585,15 @@ bool rbtree_best_fit:: check_sanity() { //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- imultiset_iterator ib(m_header.m_imultiset.begin()), ie(m_header.m_imultiset.end()); - size_type free_memory = 0; + std::size_t free_memory = 0; //Iterate through all blocks obtaining their size for(; ib != ie; ++ib){ - free_memory += (size_type)ib->m_size*Alignment; + free_memory += ib->m_size*Alignment; algo_impl_t::assert_alignment(&*ib); if(!algo_impl_t::check_alignment(&*ib)) return false; @@ -656,8 +604,8 @@ bool rbtree_best_fit:: return false; } - size_type block1_off = - priv_first_block_offset_from_this(this, m_header.m_extra_hdr_bytes); + std::size_t block1_off = + priv_first_block_offset(this, m_header.m_extra_hdr_bytes); //Check free bytes are less than size if(free_memory > (m_header.m_size - block1_off)){ @@ -668,45 +616,45 @@ bool rbtree_best_fit:: template inline void* rbtree_best_fit:: - allocate(size_type nbytes) -{ + allocate(std::size_t nbytes) +{ //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- - size_type ignore; + std::size_t ignore; void * ret = priv_allocate(boost::interprocess::allocate_new, nbytes, nbytes, ignore).first; return ret; } template inline void* rbtree_best_fit:: - allocate_aligned(size_type nbytes, size_type alignment) -{ + allocate_aligned(std::size_t nbytes, std::size_t alignment) +{ //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- - return algo_impl_t::allocate_aligned(this, nbytes, alignment); + return algo_impl_t::allocate_aligned(this, nbytes, alignment); } template template inline std::pair rbtree_best_fit:: - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, T *reuse_ptr) { std::pair ret = priv_allocation_command (command, limit_size, preferred_size, received_size, static_cast(reuse_ptr), sizeof(T)); - BOOST_ASSERT(0 == ((std::size_t)ret.first % ::boost::alignment_of::value)); + BOOST_ASSERT(0 == ((std::size_t)ret.first % detail::alignment_of::value)); return std::pair(static_cast(ret.first), ret.second); } template inline std::pair rbtree_best_fit:: - raw_allocation_command (boost::interprocess::allocation_type command, size_type limit_objects, - size_type preferred_objects,size_type &received_objects, - void *reuse_ptr, size_type sizeof_object) + raw_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_objects, + std::size_t preferred_objects,std::size_t &received_objects, + void *reuse_ptr, std::size_t sizeof_object) { if(!sizeof_object) return std::pair(static_cast(0), false); @@ -724,21 +672,21 @@ inline std::pair rbtree_best_fit inline std::pair rbtree_best_fit:: - priv_allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, - void *reuse_ptr, size_type sizeof_object) + priv_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, + void *reuse_ptr, std::size_t sizeof_object) { std::pair ret; - size_type max_count = m_header.m_size/sizeof_object; + std::size_t max_count = m_header.m_size/sizeof_object; if(limit_size > max_count || preferred_size > max_count){ ret.first = 0; return ret; } - size_type l_size = limit_size*sizeof_object; - size_type p_size = preferred_size*sizeof_object; - size_type r_size; + std::size_t l_size = limit_size*sizeof_object; + std::size_t p_size = preferred_size*sizeof_object; + std::size_t r_size; { //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- ret = priv_allocate(command, l_size, p_size, r_size, reuse_ptr, sizeof_object); } @@ -747,21 +695,20 @@ inline std::pair rbtree_best_fit -typename rbtree_best_fit::size_type -rbtree_best_fit:: +inline std::size_t rbtree_best_fit:: size(const void *ptr) const { //We need no synchronization since this block's size is not going //to be modified by anyone else //Obtain the real size of the block - return ((size_type)priv_get_block(ptr)->m_size - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; + return (priv_get_block(ptr)->m_size - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; } template inline void rbtree_best_fit::zero_free_memory() { //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- imultiset_iterator ib(m_header.m_imultiset.begin()), ie(m_header.m_imultiset.end()); @@ -769,7 +716,7 @@ inline void rbtree_best_fit::zero_free_m while(ib != ie){ //Just clear user the memory part reserved for the user volatile char *ptr = reinterpret_cast(&*ib) + BlockCtrlBytes; - size_type s = (size_type)ib->m_size*Alignment - BlockCtrlBytes; + std::size_t s = ib->m_size*Alignment - BlockCtrlBytes; while(s--){ *ptr++ = 0; } @@ -785,12 +732,12 @@ inline void rbtree_best_fit::zero_free_m template void* rbtree_best_fit:: priv_expand_both_sides(boost::interprocess::allocation_type command - ,size_type min_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t min_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr ,bool only_preferred_backwards - ,size_type backwards_multiple) + ,std::size_t backwards_multiple) { algo_impl_t::assert_alignment(reuse_ptr); if(command & boost::interprocess::expand_fwd){ @@ -812,7 +759,7 @@ void* rbtree_best_fit:: //Obtain the real size of the block block_ctrl *reuse = priv_get_block(reuse_ptr); - //Sanity check + //Sanity check //BOOST_ASSERT(reuse->m_size == priv_tail_size(reuse)); algo_impl_t::assert_alignment(reuse); @@ -830,8 +777,8 @@ void* rbtree_best_fit:: BOOST_ASSERT(prev_block->m_size == reuse->m_prev_size); algo_impl_t::assert_alignment(prev_block); - size_type needs_backwards_aligned; - size_type lcm; + std::size_t needs_backwards_aligned; + std::size_t lcm; if(!algo_impl_t::calculate_lcm_and_needs_backwards_lcmed ( backwards_multiple , received_size @@ -841,14 +788,14 @@ void* rbtree_best_fit:: } //Check if previous block has enough size - if(size_type(prev_block->m_size*Alignment) >= needs_backwards_aligned){ + if(std::size_t(prev_block->m_size*Alignment) >= needs_backwards_aligned){ //Now take all next space. This will succeed if(command & boost::interprocess::expand_fwd){ - size_type received_size2; + std::size_t received_size2; if(!priv_expand(reuse_ptr, received_size, received_size, received_size2)){ BOOST_ASSERT(0); } - BOOST_ASSERT(received_size == received_size2); + BOOST_ASSERT(received_size = received_size2); } //We need a minimum size to split the previous one if(prev_block->m_size >= (needs_backwards_aligned/Alignment + BlockCtrlUnits)){ @@ -856,12 +803,12 @@ void* rbtree_best_fit:: (reinterpret_cast(reuse) - needs_backwards_aligned); //Free old previous buffer - new_block->m_size = + new_block->m_size = AllocatedCtrlUnits + (needs_backwards_aligned + (received_size - UsableByPreviousChunk))/Alignment; BOOST_ASSERT(new_block->m_size >= BlockCtrlUnits); - priv_mark_as_allocated_block(new_block); + priv_mark_new_allocated_block(new_block); - prev_block->m_size = (reinterpret_cast(new_block) - + prev_block->m_size = (reinterpret_cast(new_block) - reinterpret_cast(prev_block))/Alignment; BOOST_ASSERT(prev_block->m_size >= BlockCtrlUnits); priv_mark_as_free_block(prev_block); @@ -872,7 +819,7 @@ void* rbtree_best_fit:: { imultiset_iterator prev_block_it(Imultiset::s_iterator_to(*prev_block)); imultiset_iterator was_smaller_it(prev_block_it); - if(prev_block_it != m_header.m_imultiset.begin() && + if(prev_block_it != m_header.m_imultiset.begin() && (--(was_smaller_it = prev_block_it))->m_size > prev_block->m_size){ m_header.m_imultiset.erase(prev_block_it); m_header.m_imultiset.insert(m_header.m_imultiset.begin(), *prev_block); @@ -881,7 +828,7 @@ void* rbtree_best_fit:: received_size = needs_backwards_aligned + received_size; m_header.m_allocated += needs_backwards_aligned; - + //Check alignment algo_impl_t::assert_alignment(new_block); @@ -902,13 +849,13 @@ void* rbtree_best_fit:: //Just merge the whole previous block //prev_block->m_size*Alignment is multiple of lcm (and backwards_multiple) - received_size = received_size + (size_type)prev_block->m_size*Alignment; + received_size = received_size + prev_block->m_size*Alignment; - m_header.m_allocated += (size_type)prev_block->m_size*Alignment; + m_header.m_allocated += prev_block->m_size*Alignment; //Now update sizes prev_block->m_size = prev_block->m_size + reuse->m_size; BOOST_ASSERT(prev_block->m_size >= BlockCtrlUnits); - priv_mark_as_allocated_block(prev_block); + priv_mark_new_allocated_block(prev_block); //If the backwards expansion has remaining bytes in the //first bytes, fill them with a pattern @@ -927,28 +874,28 @@ void* rbtree_best_fit:: template inline void rbtree_best_fit:: - deallocate_many(typename rbtree_best_fit::multiallocation_chain &chain) + deallocate_many(typename rbtree_best_fit::multiallocation_chain chain) { //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- - algo_impl_t::deallocate_many(this, chain); + algo_impl_t::deallocate_many(this, boost::interprocess::move(chain)); } template std::pair rbtree_best_fit:: priv_allocate(boost::interprocess::allocation_type command - ,size_type limit_size - ,size_type preferred_size - ,size_type &received_size + ,std::size_t limit_size + ,std::size_t preferred_size + ,std::size_t &received_size ,void *reuse_ptr - ,size_type backwards_multiple) + ,std::size_t backwards_multiple) { //Remove me. Forbid backwards allocation //command &= (~boost::interprocess::expand_bwd); if(command & boost::interprocess::shrink_in_place){ - bool success = + bool success = algo_impl_t::shrink(this, reuse_ptr, limit_size, preferred_size, received_size); return std::pair ((success ? reuse_ptr : 0), true); } @@ -960,10 +907,10 @@ std::pair rbtree_best_fit: return return_type(static_cast(0), false); //Number of units to request (including block_ctrl header) - size_type preferred_units = priv_get_total_units(preferred_size); + std::size_t preferred_units = priv_get_total_units(preferred_size); //Number of units to request (including block_ctrl header) - size_type limit_units = priv_get_total_units(limit_size); + std::size_t limit_units = priv_get_total_units(limit_size); //Expand in place if(reuse_ptr && (command & (boost::interprocess::expand_fwd | boost::interprocess::expand_bwd))){ @@ -979,13 +926,13 @@ std::pair rbtree_best_fit: if(it != m_header.m_imultiset.end()){ return return_type(this->priv_check_and_allocate - (preferred_units, ipcdetail::to_raw_pointer(&*it), received_size), false); + (preferred_units, detail::get_pointer(&*it), received_size), false); } if(it != m_header.m_imultiset.begin()&& (--it)->m_size >= limit_units){ return return_type(this->priv_check_and_allocate - (it->m_size, ipcdetail::to_raw_pointer(&*it), received_size), false); + (it->m_size, detail::get_pointer(&*it), received_size), false); } } @@ -1016,13 +963,13 @@ void *rbtree_best_fit:: { return const_cast(reinterpret_cast(block) + AllocatedCtrlBytes); } template -inline typename rbtree_best_fit::size_type -rbtree_best_fit:: - priv_get_total_units(size_type userbytes) +inline +std::size_t rbtree_best_fit:: + priv_get_total_units(std::size_t userbytes) { if(userbytes < UsableByPreviousChunk) userbytes = UsableByPreviousChunk; - size_type units = ipcdetail::get_rounded_size(userbytes - UsableByPreviousChunk, Alignment)/Alignment + AllocatedCtrlUnits; + std::size_t units = detail::get_rounded_size(userbytes - UsableByPreviousChunk, Alignment)/Alignment + AllocatedCtrlUnits; if(units < BlockCtrlUnits) units = BlockCtrlUnits; return units; } @@ -1030,26 +977,26 @@ rbtree_best_fit:: template bool rbtree_best_fit:: priv_expand (void *ptr - ,const size_type min_size - ,const size_type preferred_size - ,size_type &received_size) + ,const std::size_t min_size + ,const std::size_t preferred_size + ,std::size_t &received_size) { //Obtain the real size of the block block_ctrl *block = priv_get_block(ptr); - size_type old_block_units = block->m_size; + std::size_t old_block_units = block->m_size; //The block must be marked as allocated and the sizes must be equal BOOST_ASSERT(priv_is_allocated_block(block)); //BOOST_ASSERT(old_block_units == priv_tail_size(block)); - + //Put this to a safe value received_size = (old_block_units - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; if(received_size >= preferred_size || received_size >= min_size) return true; //Now translate it to Alignment units - const size_type min_user_units = algo_impl_t::ceil_units(min_size - UsableByPreviousChunk); - const size_type preferred_user_units = algo_impl_t::ceil_units(preferred_size - UsableByPreviousChunk); + const std::size_t min_user_units = algo_impl_t::ceil_units(min_size - UsableByPreviousChunk); + const std::size_t preferred_user_units = algo_impl_t::ceil_units(preferred_size - UsableByPreviousChunk); //Some parameter checks BOOST_ASSERT(min_user_units <= preferred_user_units); @@ -1062,10 +1009,10 @@ bool rbtree_best_fit:: algo_impl_t::assert_alignment(next_block); //Is "block" + "next_block" big enough? - const size_type merged_units = old_block_units + (size_type)next_block->m_size; + const std::size_t merged_units = old_block_units + next_block->m_size; //Now get the expansion size - const size_type merged_user_units = merged_units - AllocatedCtrlUnits; + const std::size_t merged_user_units = merged_units - AllocatedCtrlUnits; if(merged_user_units < min_user_units){ received_size = merged_units*Alignment - UsableByPreviousChunk; @@ -1073,19 +1020,19 @@ bool rbtree_best_fit:: } //Now get the maximum size the user can allocate - size_type intended_user_units = (merged_user_units < preferred_user_units) ? + std::size_t intended_user_units = (merged_user_units < preferred_user_units) ? merged_user_units : preferred_user_units; //These are total units of the merged block (supposing the next block can be split) - const size_type intended_units = AllocatedCtrlUnits + intended_user_units; + const std::size_t intended_units = AllocatedCtrlUnits + intended_user_units; //Check if we can split the next one in two parts if((merged_units - intended_units) >= BlockCtrlUnits){ - //This block is bigger than needed, split it in + //This block is bigger than needed, split it in //two blocks, the first one will be merged and //the second's size will be the remaining space BOOST_ASSERT(next_block->m_size == priv_next_block(next_block)->m_prev_size); - const size_type rem_units = merged_units - intended_units; + const std::size_t rem_units = merged_units - intended_units; //Check if we we need to update the old next block in the free blocks tree //If the new size fulfills tree invariants, we just need to replace the node @@ -1095,9 +1042,9 @@ bool rbtree_best_fit:: //overwrite the tree hook of the old next block. So we first erase the //old if needed and we'll insert the new one after creating the new next imultiset_iterator old_next_block_it(Imultiset::s_iterator_to(*next_block)); - const bool size_invariants_broken = + const bool size_invariants_broken = (next_block->m_size - rem_units ) < BlockCtrlUnits || - (old_next_block_it != m_header.m_imultiset.begin() && + (old_next_block_it != m_header.m_imultiset.begin() && (--imultiset_iterator(old_next_block_it))->m_size > rem_units); if(size_invariants_broken){ m_header.m_imultiset.erase(old_next_block_it); @@ -1132,7 +1079,7 @@ bool rbtree_best_fit:: m_header.m_allocated += (merged_units - old_block_units)*Alignment; } priv_mark_as_allocated_block(block); - received_size = ((size_type)block->m_size - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; + received_size = (block->m_size - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; return true; } @@ -1146,43 +1093,35 @@ typename rbtree_best_fit::block_ctrl * (reinterpret_cast(ptr) - ptr->m_prev_size*Alignment); } - +template inline +bool rbtree_best_fit::priv_is_prev_allocated + (typename rbtree_best_fit::block_ctrl *ptr) +{ + if(ptr->m_prev_allocated){ + return true; + } + else{ + block_ctrl *prev = priv_prev_block(ptr); + (void)prev; + BOOST_ASSERT(!priv_is_allocated_block(prev)); + return false; + } +} template inline typename rbtree_best_fit::block_ctrl * rbtree_best_fit::priv_end_block (typename rbtree_best_fit::block_ctrl *first_segment_block) { - //The first block's logic is different from the rest of blocks: stores in m_prev_size the absolute - //distance with the end block BOOST_ASSERT(first_segment_block->m_prev_allocated); block_ctrl *end_block = reinterpret_cast - (reinterpret_cast(first_segment_block) + first_segment_block->m_prev_size*Alignment); + (reinterpret_cast(first_segment_block) - first_segment_block->m_prev_size*Alignment); (void)end_block; - BOOST_ASSERT(end_block->m_allocated == 1); - BOOST_ASSERT(end_block->m_size == first_segment_block->m_prev_size); + BOOST_ASSERT(priv_is_allocated_block(end_block)); BOOST_ASSERT(end_block > first_segment_block); return end_block; } -template inline -typename rbtree_best_fit::block_ctrl * - rbtree_best_fit::priv_first_block - (typename rbtree_best_fit::block_ctrl *end_segment_block) -{ - //The first block's logic is different from the rest of blocks: stores in m_prev_size the absolute - //distance with the end block - BOOST_ASSERT(end_segment_block->m_allocated); - block_ctrl *first_block = reinterpret_cast - (reinterpret_cast(end_segment_block) - end_segment_block->m_size*Alignment); - (void)first_block; - BOOST_ASSERT(first_block->m_prev_allocated == 1); - BOOST_ASSERT(first_block->m_prev_size == end_segment_block->m_size); - BOOST_ASSERT(end_segment_block > first_block); - return first_block; -} - - template inline typename rbtree_best_fit::block_ctrl * rbtree_best_fit::priv_next_block @@ -1197,47 +1136,19 @@ bool rbtree_best_fit::priv_is_allocated_ (typename rbtree_best_fit::block_ctrl *block) { bool allocated = block->m_allocated != 0; - #ifndef NDEBUG - if(block != priv_end_block()){ - block_ctrl *next_block = reinterpret_cast - (reinterpret_cast(block) + block->m_size*Alignment); - bool next_block_prev_allocated = next_block->m_prev_allocated != 0; - (void)next_block_prev_allocated; - BOOST_ASSERT(allocated == next_block_prev_allocated); - } - else{ - block = block; - } - #endif + block_ctrl *next_block = reinterpret_cast + (reinterpret_cast(block) + block->m_size*Alignment); + bool next_block_prev_allocated = next_block->m_prev_allocated != 0; + (void)next_block_prev_allocated; + BOOST_ASSERT(allocated == next_block_prev_allocated); return allocated; } -template inline -bool rbtree_best_fit::priv_is_prev_allocated - (typename rbtree_best_fit::block_ctrl *block) -{ - if(block->m_prev_allocated){ - return true; - } - else{ - #ifndef NDEBUG - if(block != priv_first_block()){ - block_ctrl *prev = priv_prev_block(block); - (void)prev; - BOOST_ASSERT(!prev->m_allocated); - } - else{ - block = block; - } - #endif - return false; - } -} - template inline void rbtree_best_fit::priv_mark_as_allocated_block (typename rbtree_best_fit::block_ctrl *block) { + //BOOST_ASSERT(!priv_is_allocated_block(block)); block->m_allocated = 1; reinterpret_cast (reinterpret_cast(block)+ block->m_size*Alignment)->m_prev_allocated = 1; @@ -1248,26 +1159,27 @@ void rbtree_best_fit::priv_mark_as_free_ (typename rbtree_best_fit::block_ctrl *block) { block->m_allocated = 0; - block_ctrl *next_block = priv_next_block(block); - next_block->m_prev_allocated = 0; - next_block->m_prev_size = block->m_size; + reinterpret_cast + (reinterpret_cast(block) + block->m_size*Alignment)->m_prev_allocated = 0; + //BOOST_ASSERT(!priv_is_allocated_block(ptr)); + priv_next_block(block)->m_prev_size = block->m_size; } template inline void* rbtree_best_fit::priv_check_and_allocate - (size_type nunits + (std::size_t nunits ,typename rbtree_best_fit::block_ctrl* block - ,size_type &received_size) + ,std::size_t &received_size) { - size_type upper_nunits = nunits + BlockCtrlUnits; + std::size_t upper_nunits = nunits + BlockCtrlUnits; imultiset_iterator it_old = Imultiset::s_iterator_to(*block); algo_impl_t::assert_alignment(block); if (block->m_size >= upper_nunits){ - //This block is bigger than needed, split it in + //This block is bigger than needed, split it in //two blocks, the first's size will be "units" and //the second's size "block->m_size-units" - size_type block_old_size = block->m_size; + std::size_t block_old_size = block->m_size; block->m_size = nunits; BOOST_ASSERT(block->m_size >= BlockCtrlUnits); @@ -1295,7 +1207,7 @@ void* rbtree_best_fit::priv_check_and_al m_header.m_imultiset.erase(it_old); m_header.m_imultiset.insert(m_header.m_imultiset.begin(), *rem_block); } - + } else if (block->m_size >= nunits){ m_header.m_imultiset.erase(it_old); @@ -1306,8 +1218,8 @@ void* rbtree_best_fit::priv_check_and_al } //We need block_ctrl for deallocation stuff, so //return memory user can overwrite - m_header.m_allocated += (size_type)block->m_size*Alignment; - received_size = ((size_type)block->m_size - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; + m_header.m_allocated += block->m_size*Alignment; + received_size = (block->m_size - AllocatedCtrlUnits)*Alignment + UsableByPreviousChunk; //Mark the block as allocated priv_mark_as_allocated_block(block); @@ -1315,11 +1227,15 @@ void* rbtree_best_fit::priv_check_and_al //Clear the memory occupied by the tree hook, since this won't be //cleared with zero_free_memory TreeHook *t = static_cast(block); - //Just clear the memory part reserved for the user + //Just clear the memory part reserved for the user std::size_t tree_hook_offset_in_block = (char*)t - (char*)block; - //volatile char *ptr = + //volatile char *ptr = char *ptr = reinterpret_cast(block)+tree_hook_offset_in_block; const std::size_t s = BlockCtrlBytes - tree_hook_offset_in_block; + /* + while(s--){ + *ptr++ = 0; + }*/ std::memset(ptr, 0, s); this->priv_next_block(block)->m_prev_size = 0; return priv_get_user_buffer(block); @@ -1330,7 +1246,7 @@ void rbtree_best_fit::deallocate(void* a { if(!addr) return; //----------------------- - boost::interprocess::scoped_lock guard(m_header); + boost::interprocess::scoped_lock guard(m_header); //----------------------- return this->priv_deallocate(addr); } @@ -1341,7 +1257,7 @@ void rbtree_best_fit::priv_deallocate(vo if(!addr) return; block_ctrl *block = priv_get_block(addr); - + //The blocks must be marked as allocated and the sizes must be equal BOOST_ASSERT(priv_is_allocated_block(block)); // BOOST_ASSERT(block->m_size == priv_tail_size(block)); @@ -1349,7 +1265,7 @@ void rbtree_best_fit::priv_deallocate(vo //Check if alignment and block size are right algo_impl_t::assert_alignment(addr); - size_type block_old_size = Alignment*(size_type)block->m_size; + std::size_t block_old_size = Alignment*block->m_size; BOOST_ASSERT(m_header.m_allocated >= block_old_size); //Update used memory count diff --git a/utils/boost_idb/boost/interprocess/mem_algo/simple_seq_fit.hpp b/utils/boost_idb/boost/interprocess/mem_algo/simple_seq_fit.hpp index ba50c166..fc8239cf 100644 --- a/utils/boost_idb/boost/interprocess/mem_algo/simple_seq_fit.hpp +++ b/utils/boost_idb/boost/interprocess/mem_algo/simple_seq_fit.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -31,21 +31,19 @@ namespace interprocess { //!This class implements the simple sequential fit algorithm with a simply //!linked list of free buffers. template -class simple_seq_fit - : public ipcdetail::simple_seq_fit_impl +class simple_seq_fit + : public detail::simple_seq_fit_impl { /// @cond - typedef ipcdetail::simple_seq_fit_impl base_t; + typedef detail::simple_seq_fit_impl base_t; /// @endcond public: - typedef typename base_t::size_type size_type; - - //!Constructor. "size" is the total size of the managed memory segment, + //!Constructor. "size" is the total size of the managed memory segment, //!"extra_hdr_bytes" indicates the extra bytes beginning in the sizeof(simple_seq_fit) //!offset that the allocator should not use at all.*/ - simple_seq_fit(size_type segment_size, size_type extra_hdr_bytes) - : base_t(segment_size, extra_hdr_bytes){} + simple_seq_fit (std::size_t size, std::size_t extra_hdr_bytes) + : base_t(size, extra_hdr_bytes){} }; } //namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/offset_ptr.hpp b/utils/boost_idb/boost/interprocess/offset_ptr.hpp index 508946f3..4efbea08 100644 --- a/utils/boost_idb/boost/interprocess/offset_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/offset_ptr.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,8 +8,8 @@ // ////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTERPROCESS_OFFSET_PTR_HPP -#define BOOST_INTERPROCESS_OFFSET_PTR_HPP +#ifndef BOOST_OFFSET_PTR_HPP +#define BOOST_OFFSET_PTR_HPP #if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once @@ -22,12 +22,12 @@ #include #include #include +#include +#include #include #include #include #include -#include -#include //!\file //!Describes a smart pointer that stores the offset between this pointer and @@ -44,311 +44,125 @@ struct has_trivial_destructor; namespace interprocess { -/// @cond -namespace ipcdetail { - - template - union offset_ptr_internal - { - explicit offset_ptr_internal(OffsetType off) - : m_offset(off) - {} - OffsetType m_offset; //Distance between this object and pointee address - typename ::boost::aligned_storage - < sizeof(OffsetType) - , (OffsetAlignment == offset_type_alignment) ? - ::boost::alignment_of::value : OffsetAlignment - >::type alignment_helper; - }; - - //Note: using the address of a local variable to point to another address - //is not standard conforming and this can be optimized-away by the compiler. - //Non-inlining is a method to remain illegal but correct - - //Undef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_XXX if your compiler can inline - //this code without breaking the library - - //////////////////////////////////////////////////////////////////////// - // - // offset_ptr_to_raw_pointer - // - //////////////////////////////////////////////////////////////////////// - #define BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_PTR - #define BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_PTR - - template - #ifndef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_PTR - BOOST_INTERPROCESS_NEVER_INLINE - #elif defined(NDEBUG) - inline - #endif - void * offset_ptr_to_raw_pointer(const volatile void *this_ptr, std::size_t offset) - { - typedef pointer_size_t_caster caster_t; - #ifndef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_PTR - if(offset == 1){ - return 0; - } - else{ - const caster_t caster((void*)this_ptr); - return caster_t(caster.size() + offset).pointer(); - } - #else - const caster_t caster((void*)this_ptr); - return caster_t((caster.size() + offset) & -std::size_t(offset != 1)).pointer(); - #endif - } - - #ifdef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_PTR - #undef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_PTR - #endif - #ifdef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_PTR - #undef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_PTR - #endif - - //////////////////////////////////////////////////////////////////////// - // - // offset_ptr_to_offset - // - //////////////////////////////////////////////////////////////////////// - #define BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF - //Branchless seems slower in x86 - #define BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF - - template - #ifndef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF - BOOST_INTERPROCESS_NEVER_INLINE - #elif defined(NDEBUG) - inline - #endif - std::size_t offset_ptr_to_offset(const volatile void *ptr, const volatile void *this_ptr) - { - typedef pointer_size_t_caster caster_t; - #ifndef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF - //offset == 1 && ptr != 0 is not legal for this pointer - if(!ptr){ - return 1; - } - else{ - const caster_t this_caster((void*)this_ptr); - const caster_t ptr_caster((void*)ptr); - std::size_t offset = ptr_caster.size() - this_caster.size(); - BOOST_ASSERT(offset != 1); - return offset; - } - #else - const caster_t this_caster((void*)this_ptr); - const caster_t ptr_caster((void*)ptr); - //std::size_t other = -std::size_t(ptr != 0); - //std::size_t offset = (ptr_caster.size() - this_caster.size()) & other; - //return offset + !other; - // - std::size_t offset = (ptr_caster.size() - this_caster.size() - 1) & -std::size_t(ptr != 0); - return ++offset; - #endif - } +//!A smart pointer that stores the offset between between the pointer and the +//!the object it points. This allows offset allows special properties, since +//!the pointer is independent from the address address of the pointee, if the +//!pointer and the pointee are still separated by the same offset. This feature +//!converts offset_ptr in a smart pointer that can be placed in shared memory and +//!memory mapped files mapped in different addresses in every process. +template +class offset_ptr +{ + /// @cond + typedef offset_ptr self_t; - #ifdef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF - #undef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF - #endif - #ifdef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF - #undef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF - #endif + void unspecified_bool_type_func() const {} + typedef void (self_t::*unspecified_bool_type)() const; - //////////////////////////////////////////////////////////////////////// - // - // offset_ptr_to_offset_from_other - // - //////////////////////////////////////////////////////////////////////// - #define BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF_FROM_OTHER - //Branchless seems slower in x86 - #define BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF_FROM_OTHER - - template - #ifndef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF_FROM_OTHER - BOOST_INTERPROCESS_NEVER_INLINE - #elif defined(NDEBUG) - inline + #if defined(_MSC_VER) && (_MSC_VER >= 1400) + __declspec(noinline) //this workaround is needed for msvc > 8.0 #endif - std::size_t offset_ptr_to_offset_from_other - (const volatile void *this_ptr, const volatile void *other_ptr, std::size_t other_offset) + void set_offset(const PointedType *ptr) { - typedef pointer_size_t_caster caster_t; - #ifndef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF_FROM_OTHER - if(other_offset == 1){ - return 1; + //offset == 1 && ptr != 0 is not legal for this pointer + if(!ptr){ + internal.m_offset = 1; } else{ - const caster_t this_caster((void*)this_ptr); - const caster_t other_caster((void*)other_ptr); - std::size_t offset = other_caster.size() - this_caster.size() + other_offset; - BOOST_ASSERT(offset != 1); - return offset; + internal.m_offset = (const char*)ptr - (const char*)(this); + BOOST_ASSERT(internal.m_offset != 1); } - #else - const caster_t this_caster((void*)this_ptr); - const caster_t other_caster((void*)other_ptr); - return ((other_caster.size() - this_caster.size()) & -std::size_t(other_offset != 1)) + other_offset; - #endif } - #ifdef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF_FROM_OTHER - #undef BOOST_INTERPROCESS_OFFSET_PTR_INLINE_TO_OFF_FROM_OTHER - #endif - #ifdef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF_FROM_OTHER - #undef BOOST_INTERPROCESS_OFFSET_PTR_BRANCHLESS_TO_OFF_FROM_OTHER + #if defined(_MSC_VER) && (_MSC_VER >= 1400) + __declspec(noinline) //this workaround is needed for msvc-8.0 and msvc-9.0 #endif + void* get_pointer() const + { return (internal.m_offset == 1) ? 0 : (const_cast(reinterpret_cast(this)) + internal.m_offset); } - //////////////////////////////////////////////////////////////////////// - // - // Let's assume cast to void and cv cast don't change any target address - // - //////////////////////////////////////////////////////////////////////// - template - struct offset_ptr_maintains_address - { - static const bool value = ipcdetail::is_cv_same::value - || ipcdetail::is_cv_same::value; - }; + void inc_offset(std::ptrdiff_t bytes) + { internal.m_offset += bytes; } -} //namespace ipcdetail { -/// @endcond + void dec_offset(std::ptrdiff_t bytes) + { internal.m_offset -= bytes; } -//!A smart pointer that stores the offset between between the pointer and the -//!the object it points. This allows offset allows special properties, since -//!the pointer is independent from the address address of the pointee, if the -//!pointer and the pointee are still separated by the same offset. This feature -//!converts offset_ptr in a smart pointer that can be placed in shared memory and -//!memory mapped files mapped in different addresses in every process. -template -class offset_ptr -{ - /// @cond - typedef offset_ptr self_t; - void unspecified_bool_type_func() const {} - typedef void (self_t::*unspecified_bool_type)() const; + union internal_type{ + std::ptrdiff_t m_offset; //Distance between this object and pointed address + PointedType *aliasing_helper; + } internal; /// @endcond public: - typedef PointedType element_type; typedef PointedType * pointer; - typedef typename ipcdetail:: + typedef typename detail:: add_reference::type reference; - typedef typename ipcdetail:: - remove_volatile::type - >::type value_type; - typedef DifferenceType difference_type; + typedef PointedType value_type; + typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; - typedef OffsetType offset_type; public: //Public Functions - //!Default constructor (null pointer). - //!Never throws. - offset_ptr() - : internal(1) - {} - //!Constructor from raw pointer (allows "0" pointer conversion). //!Never throws. - offset_ptr(pointer ptr) - : internal(static_cast(ipcdetail::offset_ptr_to_offset<0>(ptr, this))) - {} + offset_ptr(pointer ptr = 0) { this->set_offset(ptr); } //!Constructor from other pointer. //!Never throws. template - offset_ptr( T *ptr - , typename ipcdetail::enable_if< ipcdetail::is_convertible >::type * = 0) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset<0>(static_cast(ptr), this))) - {} + offset_ptr(T *ptr) + { pointer p (ptr); (void)p; this->set_offset(p); } //!Constructor from other offset_ptr //!Never throws. - offset_ptr(const offset_ptr& ptr) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset_from_other<0>(this, &ptr, ptr.internal.m_offset))) - {} + offset_ptr(const offset_ptr& ptr) + { this->set_offset(ptr.get()); } - //!Constructor from other offset_ptr. If pointers of pointee types are - //!convertible, offset_ptrs will be convertibles. Never throws. - template - offset_ptr( const offset_ptr &ptr - #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - , typename ipcdetail::enable_if_c< ipcdetail::is_convertible::value - && ipcdetail::offset_ptr_maintains_address::value - >::type * = 0 - #endif - ) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset_from_other<0>(this, &ptr, ptr.get_offset()))) - {} - - #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - - //!Constructor from other offset_ptr. If pointers of pointee types are + //!Constructor from other offset_ptr. If pointers of pointee types are //!convertible, offset_ptrs will be convertibles. Never throws. template - offset_ptr( const offset_ptr &ptr - , typename ipcdetail::enable_if_c< ipcdetail::is_convertible::value - && !ipcdetail::offset_ptr_maintains_address::value - >::type * = 0) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset<0>(static_cast(ptr.get()), this))) - {} - - #endif + offset_ptr(const offset_ptr &ptr) + { pointer p(ptr.get()); (void)p; this->set_offset(p); } //!Emulates static_cast operator. //!Never throws. - template - offset_ptr(const offset_ptr & r, ipcdetail::static_cast_tag) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset<0>(static_cast(r.get()), this))) - {} + template + offset_ptr(const offset_ptr & r, detail::static_cast_tag) + { this->set_offset(static_cast(r.get())); } //!Emulates const_cast operator. //!Never throws. - template - offset_ptr(const offset_ptr & r, ipcdetail::const_cast_tag) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset<0>(const_cast(r.get()), this))) - {} + template + offset_ptr(const offset_ptr & r, detail::const_cast_tag) + { this->set_offset(const_cast(r.get())); } //!Emulates dynamic_cast operator. //!Never throws. - template - offset_ptr(const offset_ptr & r, ipcdetail::dynamic_cast_tag) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset<0>(dynamic_cast(r.get()), this))) - {} + template + offset_ptr(const offset_ptr & r, detail::dynamic_cast_tag) + { this->set_offset(dynamic_cast(r.get())); } //!Emulates reinterpret_cast operator. //!Never throws. - template - offset_ptr(const offset_ptr & r, ipcdetail::reinterpret_cast_tag) - : internal(static_cast - (ipcdetail::offset_ptr_to_offset<0>(reinterpret_cast(r.get()), this))) - {} + template + offset_ptr(const offset_ptr & r, detail::reinterpret_cast_tag) + { this->set_offset(reinterpret_cast(r.get())); } //!Obtains raw pointer from offset. //!Never throws. - pointer get() const - { return (pointer)ipcdetail::offset_ptr_to_raw_pointer<0>(this, this->internal.m_offset); } + pointer get()const + { return static_cast(this->get_pointer()); } - offset_type get_offset() const - { return this->internal.m_offset; } + std::ptrdiff_t get_offset() const + { return internal.m_offset; } //!Pointer-like -> operator. It can return 0 pointer. //!Never throws. - pointer operator->() const + pointer operator->() const { return this->get(); } - //!Dereferencing operator, if it is a null offset_ptr behavior + //!Dereferencing operator, if it is a null offset_ptr behavior //! is undefined. Never throws. - reference operator* () const + reference operator* () const { pointer p = this->get(); reference r = *p; @@ -357,265 +171,197 @@ class offset_ptr //!Indexing operator. //!Never throws. - reference operator[](difference_type idx) const + reference operator[](std::ptrdiff_t idx) const { return this->get()[idx]; } //!Assignment from pointer (saves extra conversion). //!Never throws. offset_ptr& operator= (pointer from) - { - this->internal.m_offset = - static_cast(ipcdetail::offset_ptr_to_offset<0>(from, this)); - return *this; - } + { this->set_offset(from); return *this; } //!Assignment from other offset_ptr. //!Never throws. - offset_ptr& operator= (const offset_ptr & ptr) - { - this->internal.m_offset = - static_cast(ipcdetail::offset_ptr_to_offset_from_other<0>(this, &ptr, ptr.internal.m_offset)); - return *this; - } + offset_ptr& operator= (const offset_ptr & pt) + { pointer p(pt.get()); (void)p; this->set_offset(p); return *this; } - //!Assignment from related offset_ptr. If pointers of pointee types + //!Assignment from related offset_ptr. If pointers of pointee types //! are assignable, offset_ptrs will be assignable. Never throws. - template - #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - typename ipcdetail::enable_if_c< ipcdetail::is_convertible::value - && ipcdetail::offset_ptr_maintains_address::value - , offset_ptr&>::type - #else - offset_ptr& - #endif - operator= (const offset_ptr &ptr) - { - this->internal.m_offset = - static_cast(ipcdetail::offset_ptr_to_offset_from_other<0>(this, &ptr, ptr.get_offset())); - return *this; - } + template + offset_ptr& operator= (const offset_ptr & pt) + { pointer p(pt.get()); this->set_offset(p); return *this; } + + //!offset_ptr + std::ptrdiff_t. + //!Never throws. + offset_ptr operator+ (std::ptrdiff_t offset) const + { return offset_ptr(this->get()+offset); } - #ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED - template - typename ipcdetail::enable_if_c::value - && !ipcdetail::offset_ptr_maintains_address::value - , offset_ptr&>::type - operator= (const offset_ptr &ptr) - { - this->internal.m_offset = - static_cast(ipcdetail::offset_ptr_to_offset<0>(static_cast(ptr.get()), this)); - return *this; - } - #endif + //!offset_ptr - std::ptrdiff_t. + //!Never throws. + offset_ptr operator- (std::ptrdiff_t offset) const + { return offset_ptr(this->get()-offset); } - //!offset_ptr += difference_type. + //!offset_ptr += std::ptrdiff_t. //!Never throws. - offset_ptr &operator+= (difference_type offset) + offset_ptr &operator+= (std::ptrdiff_t offset) { this->inc_offset(offset * sizeof (PointedType)); return *this; } - //!offset_ptr -= difference_type. + //!offset_ptr -= std::ptrdiff_t. //!Never throws. - offset_ptr &operator-= (difference_type offset) + offset_ptr &operator-= (std::ptrdiff_t offset) { this->dec_offset(offset * sizeof (PointedType)); return *this; } //!++offset_ptr. //!Never throws. - offset_ptr& operator++ (void) + offset_ptr& operator++ (void) { this->inc_offset(sizeof (PointedType)); return *this; } //!offset_ptr++. //!Never throws. offset_ptr operator++ (int) - { - offset_ptr tmp(*this); - this->inc_offset(sizeof (PointedType)); - return tmp; - } + { offset_ptr temp(*this); ++*this; return temp; } //!--offset_ptr. //!Never throws. - offset_ptr& operator-- (void) + offset_ptr& operator-- (void) { this->dec_offset(sizeof (PointedType)); return *this; } //!offset_ptr--. //!Never throws. offset_ptr operator-- (int) - { - offset_ptr tmp(*this); - this->dec_offset(sizeof (PointedType)); - return tmp; - } + { offset_ptr temp(*this); --*this; return temp; } //!safe bool conversion operator. //!Never throws. - operator unspecified_bool_type() const - { return this->internal.m_offset != 1? &self_t::unspecified_bool_type_func : 0; } + operator unspecified_bool_type() const + { return this->get()? &self_t::unspecified_bool_type_func : 0; } - //!Not operator. Not needed in theory, but improves portability. + //!Not operator. Not needed in theory, but improves portability. //!Never throws bool operator! () const - { return this->internal.m_offset == 1; } - - //!Compatibility with pointer_traits - //! - template - struct rebind - { typedef offset_ptr other; }; - - //!Compatibility with pointer_traits - //! - static offset_ptr pointer_to(reference r) - { return offset_ptr(&r); } - - //!difference_type + offset_ptr - //!operation - friend offset_ptr operator+(difference_type diff, offset_ptr right) - { right += diff; return right; } - - //!offset_ptr + difference_type - //!operation - friend offset_ptr operator+(offset_ptr left, difference_type diff) - { left += diff; return left; } - - //!offset_ptr - diff - //!operation - friend offset_ptr operator-(offset_ptr left, difference_type diff) - { left -= diff; return left; } - - //!offset_ptr - diff - //!operation - friend offset_ptr operator-(difference_type diff, offset_ptr right) - { right -= diff; return right; } - - //!offset_ptr - offset_ptr - //!operation - friend difference_type operator-(const offset_ptr &pt, const offset_ptr &pt2) - { return difference_type(pt.get()- pt2.get()); } - - //Comparison - friend bool operator== (const offset_ptr &pt1, const offset_ptr &pt2) - { return pt1.get() == pt2.get(); } - - friend bool operator!= (const offset_ptr &pt1, const offset_ptr &pt2) - { return pt1.get() != pt2.get(); } - - friend bool operator<(const offset_ptr &pt1, const offset_ptr &pt2) - { return pt1.get() < pt2.get(); } - - friend bool operator<=(const offset_ptr &pt1, const offset_ptr &pt2) - { return pt1.get() <= pt2.get(); } - - friend bool operator>(const offset_ptr &pt1, const offset_ptr &pt2) - { return pt1.get() > pt2.get(); } - - friend bool operator>=(const offset_ptr &pt1, const offset_ptr &pt2) - { return pt1.get() >= pt2.get(); } - - //Comparison to raw ptr to support literal 0 - friend bool operator== (pointer pt1, const offset_ptr &pt2) - { return pt1 == pt2.get(); } - - friend bool operator!= (pointer pt1, const offset_ptr &pt2) - { return pt1 != pt2.get(); } - - friend bool operator<(pointer pt1, const offset_ptr &pt2) - { return pt1 < pt2.get(); } - - friend bool operator<=(pointer pt1, const offset_ptr &pt2) - { return pt1 <= pt2.get(); } - - friend bool operator>(pointer pt1, const offset_ptr &pt2) - { return pt1 > pt2.get(); } - - friend bool operator>=(pointer pt1, const offset_ptr &pt2) - { return pt1 >= pt2.get(); } - - //Comparison - friend bool operator== (const offset_ptr &pt1, pointer pt2) - { return pt1.get() == pt2; } - - friend bool operator!= (const offset_ptr &pt1, pointer pt2) - { return pt1.get() != pt2; } - - friend bool operator<(const offset_ptr &pt1, pointer pt2) - { return pt1.get() < pt2; } - - friend bool operator<=(const offset_ptr &pt1, pointer pt2) - { return pt1.get() <= pt2; } + { return this->get() == 0; } +/* + friend void swap (offset_ptr &pt, offset_ptr &pt2) + { + value_type *ptr = pt.get(); + pt = pt2; + pt2 = ptr; + } +*/ +}; - friend bool operator>(const offset_ptr &pt1, pointer pt2) - { return pt1.get() > pt2; } +//!offset_ptr == offset_ptr. +//!Never throws. +template +inline bool operator== (const offset_ptr &pt1, + const offset_ptr &pt2) +{ return pt1.get() == pt2.get(); } - friend bool operator>=(const offset_ptr &pt1, pointer pt2) - { return pt1.get() >= pt2; } +//!offset_ptr != offset_ptr. +//!Never throws. +template +inline bool operator!= (const offset_ptr &pt1, + const offset_ptr &pt2) +{ return pt1.get() != pt2.get(); } - friend void swap(offset_ptr &left, offset_ptr &right) - { - pointer ptr = right.get(); - right = left; - left = ptr; - } +//!offset_ptr < offset_ptr. +//!Never throws. +template +inline bool operator< (const offset_ptr &pt1, + const offset_ptr &pt2) +{ return pt1.get() < pt2.get(); } - private: - /// @cond - void inc_offset(DifferenceType bytes) - { internal.m_offset += bytes; } +//!offset_ptr <= offset_ptr. +//!Never throws. +template +inline bool operator<= (const offset_ptr &pt1, + const offset_ptr &pt2) +{ return pt1.get() <= pt2.get(); } - void dec_offset(DifferenceType bytes) - { internal.m_offset -= bytes; } +//!offset_ptr > offset_ptr. +//!Never throws. +template +inline bool operator> (const offset_ptr &pt1, + const offset_ptr &pt2) +{ return pt1.get() > pt2.get(); } - ipcdetail::offset_ptr_internal internal; - /// @endcond -}; +//!offset_ptr >= offset_ptr. +//!Never throws. +template +inline bool operator>= (const offset_ptr &pt1, + const offset_ptr &pt2) +{ return pt1.get() >= pt2.get(); } //!operator<< //!for offset ptr -template -inline std::basic_ostream & operator<< - (std::basic_ostream & os, offset_ptr const & p) +template +inline std::basic_ostream & operator<< + (std::basic_ostream & os, offset_ptr const & p) { return os << p.get_offset(); } -//!operator>> +//!operator>> //!for offset ptr -template -inline std::basic_istream & operator>> - (std::basic_istream & is, offset_ptr & p) +template +inline std::basic_istream & operator>> + (std::basic_istream & is, offset_ptr & p) { return is >> p.get_offset(); } +//!std::ptrdiff_t + offset_ptr +//!operation +template +inline offset_ptr operator+(std::ptrdiff_t diff, const offset_ptr& right) +{ return right + diff; } + +//!offset_ptr - offset_ptr +//!operation +template +inline std::ptrdiff_t operator- (const offset_ptr &pt, const offset_ptr &pt2) +{ return pt.get()- pt2.get(); } + +//!swap specialization +//!for offset_ptr +template +inline void swap (boost::interprocess::offset_ptr &pt, + boost::interprocess::offset_ptr &pt2) +{ + typename offset_ptr::value_type *ptr = pt.get(); + pt = pt2; + pt2 = ptr; +} + //!Simulation of static_cast between pointers. Never throws. -template -inline boost::interprocess::offset_ptr - static_pointer_cast(const boost::interprocess::offset_ptr & r) -{ - return boost::interprocess::offset_ptr - (r, boost::interprocess::ipcdetail::static_cast_tag()); +template +inline boost::interprocess::offset_ptr + static_pointer_cast(const boost::interprocess::offset_ptr & r) +{ + return boost::interprocess::offset_ptr + (r, boost::interprocess::detail::static_cast_tag()); } //!Simulation of const_cast between pointers. Never throws. -template -inline boost::interprocess::offset_ptr - const_pointer_cast(const boost::interprocess::offset_ptr & r) -{ - return boost::interprocess::offset_ptr - (r, boost::interprocess::ipcdetail::const_cast_tag()); +template +inline boost::interprocess::offset_ptr + const_pointer_cast(const boost::interprocess::offset_ptr & r) +{ + return boost::interprocess::offset_ptr + (r, boost::interprocess::detail::const_cast_tag()); } //!Simulation of dynamic_cast between pointers. Never throws. -template -inline boost::interprocess::offset_ptr - dynamic_pointer_cast(const boost::interprocess::offset_ptr & r) -{ - return boost::interprocess::offset_ptr - (r, boost::interprocess::ipcdetail::dynamic_cast_tag()); +template +inline boost::interprocess::offset_ptr + dynamic_pointer_cast(const boost::interprocess::offset_ptr & r) +{ + return boost::interprocess::offset_ptr + (r, boost::interprocess::detail::dynamic_cast_tag()); } //!Simulation of reinterpret_cast between pointers. Never throws. -template -inline boost::interprocess::offset_ptr - reinterpret_pointer_cast(const boost::interprocess::offset_ptr & r) -{ - return boost::interprocess::offset_ptr - (r, boost::interprocess::ipcdetail::reinterpret_cast_tag()); +template +inline boost::interprocess::offset_ptr + reinterpret_pointer_cast(const boost::interprocess::offset_ptr & r) +{ + return boost::interprocess::offset_ptr + (r, boost::interprocess::detail::reinterpret_cast_tag()); } } //namespace interprocess { @@ -623,30 +369,30 @@ inline boost::interprocess::offset_ptr /// @cond //!has_trivial_constructor<> == true_type specialization for optimizations -template -struct has_trivial_constructor< boost::interprocess::offset_ptr > +template +struct has_trivial_constructor< boost::interprocess::offset_ptr > { - static const bool value = true; + enum { value = true }; }; ///has_trivial_destructor<> == true_type specialization for optimizations -template -struct has_trivial_destructor< boost::interprocess::offset_ptr > +template +struct has_trivial_destructor< boost::interprocess::offset_ptr > { - static const bool value = true; + enum { value = true }; }; - +//#if !defined(_MSC_VER) || (_MSC_VER >= 1400) namespace interprocess { - -//!to_raw_pointer() enables boost::mem_fn to recognize offset_ptr. +//#endif +//!get_pointer() enables boost::mem_fn to recognize offset_ptr. //!Never throws. -template -inline T * to_raw_pointer(boost::interprocess::offset_ptr const & p) -{ return ipcdetail::to_raw_pointer(p); } - +template +inline T * get_pointer(boost::interprocess::offset_ptr const & p) +{ return p.get(); } +//#if !defined(_MSC_VER) || (_MSC_VER >= 1400) } //namespace interprocess - +//#endif /// @endcond } //namespace boost { @@ -663,69 +409,51 @@ namespace intrusive { template struct max_pointer_plus_bits; -template -struct max_pointer_plus_bits, OffsetAlignment> +template +struct max_pointer_plus_bits, Alignment> { //The offset ptr can embed one bit less than the alignment since it //uses offset == 1 to store the null pointer. - static const std::size_t value = ::boost::interprocess::ipcdetail::ls_zeros::value - 1; + static const std::size_t value = ::boost::interprocess::detail::ls_zeros::value - 1; }; //Predeclaration template struct pointer_plus_bits; -template -struct pointer_plus_bits, NumBits> +template +struct pointer_plus_bits, NumBits> { - typedef boost::interprocess::offset_ptr pointer; - typedef ::boost::interprocess::pointer_size_t_caster caster_t; + typedef boost::interprocess::offset_ptr pointer; //Bits are stored in the lower bits of the pointer except the LSB, //because this bit is used to represent the null pointer. - static const std::size_t Mask = ((std::size_t(1) << NumBits) - 1) << 1u; + static const std::size_t Mask = ((std::size_t(1) << NumBits)-1)<<1u; static pointer get_pointer(const pointer &n) - { - caster_t caster(n.get()); - return pointer(caster_t(caster.size() & ~Mask).pointer()); - } + { return reinterpret_cast(std::size_t(n.get()) & ~std::size_t(Mask)); } - static void set_pointer(pointer &n, const pointer &p) + static void set_pointer(pointer &n, pointer p) { - caster_t n_caster(n.get()); - caster_t p_caster(p.get()); - BOOST_ASSERT(0 == (p_caster.size() & Mask)); - n = caster_t(p_caster.size() | (n_caster.size() & Mask)).pointer(); + std::size_t pint = std::size_t(p.get()); + BOOST_ASSERT(0 == (std::size_t(pint) & Mask)); + n = reinterpret_cast(pint | (std::size_t(n.get()) & std::size_t(Mask))); } static std::size_t get_bits(const pointer &n) - { return (caster_t(n.get()).size() & Mask) >> 1u; } + { return(std::size_t(n.get()) & std::size_t(Mask)) >> 1u; } static void set_bits(pointer &n, std::size_t b) { BOOST_ASSERT(b < (std::size_t(1) << NumBits)); - caster_t n_caster(n.get()); - n = caster_t((n_caster.size() & ~Mask) | (b << 1u)).pointer(); + n = reinterpret_cast(std::size_t(get_pointer(n).get()) | (b << 1u)); } }; } //namespace intrusive - -//Predeclaration -template -struct pointer_to_other; - -//Backwards compatibility with pointer_to_other -template -struct pointer_to_other - < ::boost::interprocess::offset_ptr, U > -{ - typedef ::boost::interprocess::offset_ptr type; -}; - } //namespace boost{ /// @endcond #include -#endif //#ifndef BOOST_INTERPROCESS_OFFSET_PTR_HPP +#endif //#ifndef BOOST_OFFSET_PTR_HPP + diff --git a/utils/boost_idb/boost/interprocess/permissions.hpp b/utils/boost_idb/boost/interprocess/permissions.hpp index 4266b24a..aa88d614 100644 --- a/utils/boost_idb/boost/interprocess/permissions.hpp +++ b/utils/boost_idb/boost/interprocess/permissions.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,9 +11,7 @@ #ifndef BOOST_INTERPROCESS_PERMISSIONS_HPP #define BOOST_INTERPROCESS_PERMISSIONS_HPP -/// @cond - -#if defined (_MSC_VER) && (_MSC_VER >= 1200) +#if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif @@ -27,19 +25,15 @@ #endif -/// @endcond - //!\file //!Describes permissions class namespace boost { namespace interprocess { -/// @cond - #if defined(BOOST_INTERPROCESS_WINDOWS) -namespace ipcdetail { +namespace detail { template struct unrestricted_permissions_holder @@ -50,26 +44,22 @@ struct unrestricted_permissions_holder template winapi::interprocess_all_access_security unrestricted_permissions_holder::unrestricted; -} //namespace ipcdetail { +} //namespace detail { #endif //defined BOOST_INTERPROCESS_WINDOWS -/// @endcond - //!The permissions class represents permissions to be set to shared memory or //!files, that can be constructed form usual permission representations: //!a SECURITY_ATTRIBUTES pointer in windows or ORed rwx chmod integer in UNIX. class permissions { /// @cond - - #if defined(BOOST_INTERPROCESS_WINDOWS) + #if defined (BOOST_INTERPROCESS_WINDOWS) typedef void* os_permissions_type; #else typedef int os_permissions_type; - #endif + #endif //#if (defined BOOST_INTERPROCESS_WINDOWS) os_permissions_type m_perm; - /// @endcond public: @@ -90,26 +80,22 @@ class permissions //!for UNIX. void set_default() { - /// @cond - #if defined (BOOST_INTERPROCESS_WINDOWS) + #if (defined BOOST_INTERPROCESS_WINDOWS) m_perm = 0; #else m_perm = 0644; #endif - /// @endcond } //!Sets permissions to unrestricted access: //!A null DACL for windows or 0666 for UNIX. void set_unrestricted() { - /// @cond - #if defined (BOOST_INTERPROCESS_WINDOWS) - m_perm = &ipcdetail::unrestricted_permissions_holder<0>::unrestricted; + #if (defined BOOST_INTERPROCESS_WINDOWS) + m_perm = &detail::unrestricted_permissions_holder<0>::unrestricted; #else m_perm = 0666; #endif - /// @endcond } //!Sets permissions from a user provided os-dependent @@ -129,4 +115,3 @@ class permissions #include #endif //BOOST_INTERPROCESS_PERMISSIONS_HPP - diff --git a/utils/boost_idb/boost/interprocess/segment_manager.hpp b/utils/boost_idb/boost/interprocess/segment_manager.hpp index 9113acba..5474b0b0 100644 --- a/utils/boost_idb/boost/interprocess/segment_manager.hpp +++ b/utils/boost_idb/boost/interprocess/segment_manager.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include //std::size_t #include //char_traits @@ -69,119 +69,116 @@ class segment_manager_base typedef typename MemoryAlgorithm::void_pointer void_pointer; typedef typename MemoryAlgorithm::mutex_family mutex_family; typedef MemoryAlgorithm memory_algorithm; - + /// @cond - + //Experimental. Don't use typedef typename MemoryAlgorithm::multiallocation_chain multiallocation_chain; - typedef typename MemoryAlgorithm::difference_type difference_type; - typedef typename MemoryAlgorithm::size_type size_type; /// @endcond //!This constant indicates the payload size //!associated with each allocation of the memory algorithm - static const size_type PayloadPerAllocation = MemoryAlgorithm::PayloadPerAllocation; + static const std::size_t PayloadPerAllocation = MemoryAlgorithm::PayloadPerAllocation; //!Constructor of the segment_manager_base //! //!"size" is the size of the memory segment where //!the basic segment manager is being constructed. //! - //!"reserved_bytes" is the number of bytes + //!"reserved_bytes" is the number of bytes //!after the end of the memory algorithm object itself //!that the memory algorithm will exclude from //!dynamic allocation //! //!Can throw - segment_manager_base(size_type sz, size_type reserved_bytes) - : MemoryAlgorithm(sz, reserved_bytes) + segment_manager_base(std::size_t size, std::size_t reserved_bytes) + : MemoryAlgorithm(size, reserved_bytes) { BOOST_ASSERT((sizeof(segment_manager_base) == sizeof(MemoryAlgorithm))); } //!Returns the size of the memory //!segment - size_type get_size() const + std::size_t get_size() const { return MemoryAlgorithm::get_size(); } //!Returns the number of free bytes of the memory //!segment - size_type get_free_memory() const + std::size_t get_free_memory() const { return MemoryAlgorithm::get_free_memory(); } //!Obtains the minimum size needed by //!the segment manager - static size_type get_min_size (size_type size) + static std::size_t get_min_size (std::size_t size) { return MemoryAlgorithm::get_min_size(size); } - //!Allocates nbytes bytes. This function is only used in + //!Allocates nbytes bytes. This function is only used in //!single-segment management. Never throws - void * allocate (size_type nbytes, std::nothrow_t) + void * allocate (std::size_t nbytes, std::nothrow_t) { return MemoryAlgorithm::allocate(nbytes); } /// @cond //Experimental. Dont' use. - //!Allocates n_elements of elem_bytes bytes. - //!Throws bad_alloc on failure. chain.size() is not increased on failure. - void allocate_many(size_type elem_bytes, size_type n_elements, multiallocation_chain &chain) + //!Allocates n_elements of + //!elem_size bytes. Throws bad_alloc on failure. + multiallocation_chain allocate_many(std::size_t elem_bytes, std::size_t num_elements) { - size_type prev_size = chain.size(); - MemoryAlgorithm::allocate_many(elem_bytes, n_elements, chain); - if(!elem_bytes || chain.size() == prev_size){ - throw bad_alloc(); - } + multiallocation_chain mem(MemoryAlgorithm::allocate_many(elem_bytes, num_elements)); + if(mem.empty()) throw bad_alloc(); + return boost::interprocess::move(mem); } - //!Allocates n_elements, each one of element_lengths[i]*sizeof_element bytes. - //!Throws bad_alloc on failure. chain.size() is not increased on failure. - void allocate_many(const size_type *element_lengths, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain) + //!Allocates n_elements, each one of + //!element_lenghts[i]*sizeof_element bytes. Throws bad_alloc on failure. + multiallocation_chain allocate_many + (const std::size_t *element_lenghts, std::size_t n_elements, std::size_t sizeof_element = 1) { - size_type prev_size = chain.size(); - MemoryAlgorithm::allocate_many(element_lengths, n_elements, sizeof_element, chain); - if(!sizeof_element || chain.size() == prev_size){ - throw bad_alloc(); - } + multiallocation_chain mem(MemoryAlgorithm::allocate_many(element_lenghts, n_elements, sizeof_element)); + if(mem.empty()) throw bad_alloc(); + return boost::interprocess::move(mem); } - //!Allocates n_elements of elem_bytes bytes. - //!Non-throwing version. chain.size() is not increased on failure. - void allocate_many(std::nothrow_t, size_type elem_bytes, size_type n_elements, multiallocation_chain &chain) - { MemoryAlgorithm::allocate_many(elem_bytes, n_elements, chain); } + //!Allocates n_elements of + //!elem_size bytes. Returns a default constructed iterator on failure. + multiallocation_chain allocate_many + (std::size_t elem_bytes, std::size_t num_elements, std::nothrow_t) + { return MemoryAlgorithm::allocate_many(elem_bytes, num_elements); } //!Allocates n_elements, each one of - //!element_lengths[i]*sizeof_element bytes. - //!Non-throwing version. chain.size() is not increased on failure. - void allocate_many(std::nothrow_t, const size_type *elem_sizes, size_type n_elements, size_type sizeof_element, multiallocation_chain &chain) - { MemoryAlgorithm::allocate_many(elem_sizes, n_elements, sizeof_element, chain); } + //!element_lenghts[i]*sizeof_element bytes. + //!Returns a default constructed iterator on failure. + multiallocation_chain allocate_many + (const std::size_t *elem_sizes, std::size_t n_elements, std::size_t sizeof_element, std::nothrow_t) + { return MemoryAlgorithm::allocate_many(elem_sizes, n_elements, sizeof_element); } - //!Deallocates all elements contained in chain. - //!Never throws. - void deallocate_many(multiallocation_chain &chain) - { MemoryAlgorithm::deallocate_many(chain); } + //!Deallocates elements pointed by the + //!multiallocation iterator range. + void deallocate_many(multiallocation_chain chain) + { MemoryAlgorithm::deallocate_many(boost::interprocess::move(chain)); } /// @endcond //!Allocates nbytes bytes. Throws boost::interprocess::bad_alloc //!on failure - void * allocate(size_type nbytes) - { + void * allocate(std::size_t nbytes) + { void * ret = MemoryAlgorithm::allocate(nbytes); if(!ret) throw bad_alloc(); return ret; } - //!Allocates nbytes bytes. This function is only used in + //!Allocates nbytes bytes. This function is only used in //!single-segment management. Never throws - void * allocate_aligned (size_type nbytes, size_type alignment, std::nothrow_t) + void * allocate_aligned (std::size_t nbytes, std::size_t alignment, std::nothrow_t) { return MemoryAlgorithm::allocate_aligned(nbytes, alignment); } - //!Allocates nbytes bytes. This function is only used in + //!Allocates nbytes bytes. This function is only used in //!single-segment management. Throws bad_alloc when fails - void * allocate_aligned(size_type nbytes, size_type alignment) - { + void * allocate_aligned(std::size_t nbytes, std::size_t alignment) + { void * ret = MemoryAlgorithm::allocate_aligned(nbytes, alignment); if(!ret) throw bad_alloc(); @@ -190,8 +187,8 @@ class segment_manager_base template std::pair - allocation_command (boost::interprocess::allocation_type command, size_type limit_size, - size_type preferred_size,size_type &received_size, + allocation_command (boost::interprocess::allocation_type command, std::size_t limit_size, + std::size_t preferred_size,std::size_t &received_size, T *reuse_ptr = 0) { std::pair ret = MemoryAlgorithm::allocation_command @@ -203,9 +200,9 @@ class segment_manager_base } std::pair - raw_allocation_command (boost::interprocess::allocation_type command, size_type limit_objects, - size_type preferred_objects,size_type &received_objects, - void *reuse_ptr = 0, size_type sizeof_object = 1) + raw_allocation_command (boost::interprocess::allocation_type command, std::size_t limit_objects, + std::size_t preferred_objects,std::size_t &received_objects, + void *reuse_ptr = 0, std::size_t sizeof_object = 1) { std::pair ret = MemoryAlgorithm::raw_allocation_command ( command | boost::interprocess::nothrow_allocation, limit_objects, preferred_objects, received_objects @@ -222,7 +219,7 @@ class segment_manager_base //!Increases managed memory in extra_size bytes more. This only works //!with single-segment management. - void grow(size_type extra_size) + void grow(std::size_t extra_size) { MemoryAlgorithm::grow(extra_size); } //!Decreases managed memory to the minimum. This only works @@ -246,17 +243,17 @@ class segment_manager_base { MemoryAlgorithm::zero_free_memory(); } //!Returns the size of the buffer previously allocated pointed by ptr - size_type size(const void *ptr) const + std::size_t size(const void *ptr) const { return MemoryAlgorithm::size(ptr); } /// @cond protected: void * prot_anonymous_construct - (size_type num, bool dothrow, ipcdetail::in_place_interface &table) + (std::size_t num, bool dothrow, detail::in_place_interface &table) { - typedef ipcdetail::block_header block_header_t; - block_header_t block_info ( size_type(table.size*num) - , size_type(table.alignment) + typedef detail::block_header block_header_t; + block_header_t block_info ( table.size*num + , table.alignment , anonymous_type , 1 , 0); @@ -270,12 +267,12 @@ class segment_manager_base throw bad_alloc(); } else{ - return 0; + return 0; } } //Build scoped ptr to avoid leaks with constructor exception - ipcdetail::mem_algo_deallocator mem(ptr_struct, *this); + detail::mem_algo_deallocator mem(ptr_struct, *this); //Now construct the header block_header_t * hdr = new(ptr_struct) block_header_t(block_info); @@ -283,7 +280,7 @@ class segment_manager_base ptr = hdr->value(); //Now call constructors - ipcdetail::array_construct(ptr, num, table); + detail::array_construct(ptr, num, table); //All constructors successful, we don't want erase memory mem.release(); @@ -291,11 +288,11 @@ class segment_manager_base } //!Calls the destructor and makes an anonymous deallocate - void prot_anonymous_destroy(const void *object, ipcdetail::in_place_interface &table) + void prot_anonymous_destroy(const void *object, detail::in_place_interface &table) { - //Get control data from associated with this object - typedef ipcdetail::block_header block_header_t; + //Get control data from associated with this object + typedef detail::block_header block_header_t; block_header_t *ctrl_data = block_header_t::block_header_from_value(object, table.size, table.alignment); //------------------------------- @@ -310,7 +307,7 @@ class segment_manager_base //Call destructors and free memory //Build scoped ptr to avoid leaks with destructor exception std::size_t destroyed = 0; - table.destroy_n(const_cast(object), ctrl_data->m_value_bytes/table.size, destroyed); + table.destroy_n(const_cast(object), ctrl_data->m_value_bytes/table.size, destroyed); this->deallocate(ctrl_data); } /// @endcond @@ -319,9 +316,9 @@ class segment_manager_base //!This object is placed in the beginning of memory segment and //!implements the allocation (named or anonymous) of portions //!of the segment. This object contains two indexes that -//!maintain an association between a name and a portion of the segment. +//!maintain an association between a name and a portion of the segment. //! -//!The first index contains the mappings for normal named objects using the +//!The first index contains the mappings for normal named objects using the //!char type specified in the template parameter. //! //!The second index contains the association for unique instances. The key will @@ -337,44 +334,42 @@ template class IndexType> class segment_manager : public segment_manager_base -{ +{ /// @cond //Non-copyable segment_manager(); segment_manager(const segment_manager &); segment_manager &operator=(const segment_manager &); typedef segment_manager_base Base; + typedef detail::block_header block_header_t; /// @endcond public: typedef MemoryAlgorithm memory_algorithm; typedef typename Base::void_pointer void_pointer; - typedef typename Base::size_type size_type; - typedef typename Base::difference_type difference_type; typedef CharType char_type; typedef segment_manager_base segment_manager_base_type; - static const size_type PayloadPerAllocation = Base::PayloadPerAllocation; + static const std::size_t PayloadPerAllocation = Base::PayloadPerAllocation; /// @cond private: - typedef ipcdetail::block_header block_header_t; - typedef ipcdetail::index_config index_config_named; - typedef ipcdetail::index_config index_config_unique; + typedef detail::index_config index_config_named; + typedef detail::index_config index_config_unique; typedef IndexType index_type; - typedef ipcdetail::bool_::value > is_intrusive_t; - typedef ipcdetail::bool_::value> is_node_index_t; + typedef detail::bool_::value > is_intrusive_t; + typedef detail::bool_::value> is_node_index_t; public: typedef IndexType named_index_t; typedef IndexType unique_index_t; - typedef ipcdetail::char_ptr_holder char_ptr_holder_t; - typedef ipcdetail::segment_manager_iterator_transform + typedef detail::char_ptr_holder char_ptr_holder_t; + typedef detail::segment_manager_iterator_transform ::value> named_transform; - typedef ipcdetail::segment_manager_iterator_transform + typedef detail::segment_manager_iterator_transform ::value> unique_transform; /// @endcond @@ -392,14 +387,14 @@ class segment_manager template struct construct_proxy { - typedef ipcdetail::named_proxy type; + typedef detail::named_proxy type; }; //!Constructor proxy object definition helper class template struct construct_iter_proxy { - typedef ipcdetail::named_proxy type; + typedef detail::named_proxy type; }; /// @endcond @@ -408,8 +403,8 @@ class segment_manager //!"size" is the size of the memory segment where //!the segment manager is being constructed. //!Can throw - explicit segment_manager(size_type segment_size) - : Base(segment_size, priv_get_reserved_bytes()) + segment_manager(std::size_t size) + : Base(size, priv_get_reserved_bytes()) , m_header(static_cast(get_this_pointer())) { (void) anonymous_instance; (void) unique_instance; @@ -420,34 +415,34 @@ class segment_manager //!and the object count. On failure the first member of the //!returned pair is 0. template - std::pair find (const CharType* name) + std::pair find (const CharType* name) { return this->priv_find_impl(name, true); } //!Tries to find a previous unique allocation. Returns the address //!and the object count. On failure the first member of the //!returned pair is 0. template - std::pair find (const ipcdetail::unique_instance_t* name) + std::pair find (const detail::unique_instance_t* name) { return this->priv_find_impl(name, true); } //!Tries to find a previous named allocation. Returns the address //!and the object count. On failure the first member of the //!returned pair is 0. This search is not mutex-protected! template - std::pair find_no_lock (const CharType* name) + std::pair find_no_lock (const CharType* name) { return this->priv_find_impl(name, false); } //!Tries to find a previous unique allocation. Returns the address //!and the object count. On failure the first member of the //!returned pair is 0. This search is not mutex-protected! template - std::pair find_no_lock (const ipcdetail::unique_instance_t* name) + std::pair find_no_lock (const detail::unique_instance_t* name) { return this->priv_find_impl(name, false); } //!Returns throwing "construct" proxy //!object template - typename construct_proxy::type + typename construct_proxy::type construct(char_ptr_holder_t name) { return typename construct_proxy::type (this, name, false, true); } @@ -467,39 +462,39 @@ class segment_manager //!Returns no throwing "search or construct" //!proxy object template - typename construct_proxy::type + typename construct_proxy::type find_or_construct(char_ptr_holder_t name, std::nothrow_t) { return typename construct_proxy::type (this, name, true, false); } //!Returns throwing "construct from iterators" proxy object template - typename construct_iter_proxy::type + typename construct_iter_proxy::type construct_it(char_ptr_holder_t name) { return typename construct_iter_proxy::type (this, name, false, true); } //!Returns throwing "search or construct from iterators" //!proxy object template - typename construct_iter_proxy::type + typename construct_iter_proxy::type find_or_construct_it(char_ptr_holder_t name) { return typename construct_iter_proxy::type (this, name, true, true); } //!Returns no throwing "construct from iterators" //!proxy object template - typename construct_iter_proxy::type + typename construct_iter_proxy::type construct_it(char_ptr_holder_t name, std::nothrow_t) { return typename construct_iter_proxy::type (this, name, false, false); } //!Returns no throwing "search or construct from iterators" //!proxy object template - typename construct_iter_proxy::type + typename construct_iter_proxy::type find_or_construct_it(char_ptr_holder_t name, std::nothrow_t) { return typename construct_iter_proxy::type (this, name, true, false); } - //!Calls object function blocking recursive interprocess_mutex and guarantees that - //!no new named_alloc or destroy will be executed by any process while + //!Calls object function blocking recursive interprocess_mutex and guarantees that + //!no new named_alloc or destroy will be executed by any process while //!executing the object function call*/ template void atomic_func(Func &f) @@ -526,9 +521,9 @@ class segment_manager //!Destroys a previously created unique instance. //!Returns false if the object was not present. template - bool destroy(const ipcdetail::unique_instance_t *) + bool destroy(const detail::unique_instance_t *) { - ipcdetail::placement_destroy dtor; + detail::placement_destroy dtor; return this->priv_generic_named_destroy (typeid(T).name(), m_header.m_unique_index, dtor, is_intrusive_t()); } @@ -538,7 +533,7 @@ class segment_manager template bool destroy(const CharType *name) { - ipcdetail::placement_destroy dtor; + detail::placement_destroy dtor; return this->priv_generic_named_destroy (name, m_header.m_named_index, dtor, is_intrusive_t()); } @@ -549,8 +544,8 @@ class segment_manager void destroy_ptr(const T *p) { //If T is void transform it to char - typedef typename ipcdetail::char_if_void::type data_t; - ipcdetail::placement_destroy dtor; + typedef typename detail::char_if_void::type data_t; + detail::placement_destroy dtor; priv_destroy_ptr(p, dtor); } @@ -563,7 +558,7 @@ class segment_manager //!Returns the length of an object created with construct/find_or_construct //!functions. Does not throw. template - static size_type get_instance_length(const T *ptr) + static std::size_t get_instance_length(const T *ptr) { return priv_get_instance_length(block_header_t::block_header_from_value(ptr), sizeof(T)); } //!Returns is the the name of an object created with construct/find_or_construct @@ -572,22 +567,22 @@ class segment_manager static instance_type get_instance_type(const T *ptr) { return priv_get_instance_type(block_header_t::block_header_from_value(ptr)); } - //!Preallocates needed index resources to optimize the + //!Preallocates needed index resources to optimize the //!creation of "num" named objects in the managed memory segment. //!Can throw boost::interprocess::bad_alloc if there is no enough memory. - void reserve_named_objects(size_type num) - { + void reserve_named_objects(std::size_t num) + { //------------------------------- scoped_lock guard(m_header); //------------------------------- - m_header.m_named_index.reserve(num); + m_header.m_named_index.reserve(num); } - //!Preallocates needed index resources to optimize the + //!Preallocates needed index resources to optimize the //!creation of "num" unique objects in the managed memory segment. //!Can throw boost::interprocess::bad_alloc if there is no enough memory. - void reserve_unique_objects(size_type num) - { + void reserve_unique_objects(std::size_t num) + { //------------------------------- scoped_lock guard(m_header); //------------------------------- @@ -597,37 +592,37 @@ class segment_manager //!Calls shrink_to_fit in both named and unique object indexes //!to try to free unused memory from those indexes. void shrink_to_fit_indexes() - { + { //------------------------------- scoped_lock guard(m_header); //------------------------------- - m_header.m_named_index.shrink_to_fit(); - m_header.m_unique_index.shrink_to_fit(); + m_header.m_named_index.shrink_to_fit(); + m_header.m_unique_index.shrink_to_fit(); } //!Returns the number of named objects stored in //!the segment. - size_type get_num_named_objects() - { + std::size_t get_num_named_objects() + { //------------------------------- scoped_lock guard(m_header); //------------------------------- - return m_header.m_named_index.size(); + return m_header.m_named_index.size(); } //!Returns the number of unique objects stored in //!the segment. - size_type get_num_unique_objects() - { + std::size_t get_num_unique_objects() + { //------------------------------- scoped_lock guard(m_header); //------------------------------- - return m_header.m_unique_index.size(); + return m_header.m_unique_index.size(); } //!Obtains the minimum size needed by the //!segment manager - static size_type get_min_size() + static std::size_t get_min_size() { return Base::get_min_size(priv_get_reserved_bytes()); } //!Returns a constant iterator to the beginning of the information about @@ -694,15 +689,15 @@ class segment_manager /// @cond - //!Generic named/anonymous new function. Offers all the possibilities, - //!such as throwing, search before creating, and the constructor is + //!Generic named/anonymous new function. Offers all the possibilities, + //!such as throwing, search before creating, and the constructor is //!encapsulated in an object function. template - T *generic_construct(const CharType *name, - size_type num, - bool try2find, + T *generic_construct(const CharType *name, + std::size_t num, + bool try2find, bool dothrow, - ipcdetail::in_place_interface &table) + detail::in_place_interface &table) { return static_cast (priv_generic_construct(name, num, try2find, dothrow, table)); @@ -713,44 +708,44 @@ class segment_manager //!and the object count. On failure the first member of the //!returned pair is 0. template - std::pair priv_find_impl (const CharType* name, bool lock) - { + std::pair priv_find_impl (const CharType* name, bool lock) + { //The name can't be null, no anonymous object can be found by name BOOST_ASSERT(name != 0); - ipcdetail::placement_destroy table; - size_type sz; + detail::placement_destroy table; + std::size_t size; void *ret; if(name == reinterpret_cast(-1)){ - ret = priv_generic_find (typeid(T).name(), m_header.m_unique_index, table, sz, is_intrusive_t(), lock); + ret = priv_generic_find (typeid(T).name(), m_header.m_unique_index, table, size, is_intrusive_t(), lock); } else{ - ret = priv_generic_find (name, m_header.m_named_index, table, sz, is_intrusive_t(), lock); + ret = priv_generic_find (name, m_header.m_named_index, table, size, is_intrusive_t(), lock); } - return std::pair(static_cast(ret), sz); + return std::pair(static_cast(ret), size); } //!Tries to find a previous unique allocation. Returns the address //!and the object count. On failure the first member of the //!returned pair is 0. template - std::pair priv_find__impl (const ipcdetail::unique_instance_t* name, bool lock) + std::pair priv_find__impl (const detail::unique_instance_t* name, bool lock) { - ipcdetail::placement_destroy table; - size_type size; - void *ret = priv_generic_find(name, m_header.m_unique_index, table, size, is_intrusive_t(), lock); - return std::pair(static_cast(ret), size); + detail::placement_destroy table; + std::size_t size; + void *ret = priv_generic_find(name, m_header.m_unique_index, table, size, is_intrusive_t(), lock); + return std::pair(static_cast(ret), size); } - void *priv_generic_construct(const CharType *name, - size_type num, - bool try2find, + void *priv_generic_construct(const CharType *name, + std::size_t num, + bool try2find, bool dothrow, - ipcdetail::in_place_interface &table) + detail::in_place_interface &table) { void *ret; //Security overflow check - if(num > ((std::size_t)-1)/table.size){ + if(num > ((std::size_t)-1)/table.size){ if(dothrow) throw bad_alloc(); else @@ -770,7 +765,7 @@ class segment_manager return ret; } - void priv_destroy_ptr(const void *ptr, ipcdetail::in_place_interface &dtor) + void priv_destroy_ptr(const void *ptr, detail::in_place_interface &dtor) { block_header_t *ctrl_data = block_header_t::block_header_from_value(ptr, dtor.size, dtor.alignment); switch(ctrl_data->alloc_type()){ @@ -806,14 +801,14 @@ class segment_manager return 0; } CharType *name = static_cast(ctrl_data->template name()); - + //Sanity checks BOOST_ASSERT(ctrl_data->sizeof_char() == sizeof(CharType)); BOOST_ASSERT(ctrl_data->m_num_char == std::char_traits::length(name)); return name; } - static size_type priv_get_instance_length(block_header_t *ctrl_data, size_type sizeofvalue) + static std::size_t priv_get_instance_length(block_header_t *ctrl_data, std::size_t sizeofvalue) { //Get header BOOST_ASSERT((ctrl_data->value_bytes() %sizeofvalue) == 0); @@ -829,7 +824,7 @@ class segment_manager return (instance_type)ctrl_data->alloc_type(); } - static size_type priv_get_reserved_bytes() + static std::size_t priv_get_reserved_bytes() { //Get the number of bytes until the end of (*this) //beginning in the end of the Base base. @@ -838,22 +833,23 @@ class segment_manager template void *priv_generic_find - (const CharT* name, - IndexType > &index, - ipcdetail::in_place_interface &table, - size_type &length, - ipcdetail::true_ is_intrusive, + (const CharT* name, + IndexType > &index, + detail::in_place_interface &table, + std::size_t &length, + detail::true_ is_intrusive, bool use_lock) { (void)is_intrusive; - typedef IndexType > index_type; + typedef IndexType > index_type; + typedef detail::index_key index_key_t; typedef typename index_type::iterator index_it; //------------------------------- scoped_lock guard(priv_get_lock(use_lock)); //------------------------------- //Find name in index - ipcdetail::intrusive_compare_key key + detail::intrusive_compare_key key (name, std::char_traits::length(name)); index_it it = index.find(key); @@ -877,15 +873,15 @@ class segment_manager template void *priv_generic_find - (const CharT* name, - IndexType > &index, - ipcdetail::in_place_interface &table, - size_type &length, - ipcdetail::false_ is_intrusive, + (const CharT* name, + IndexType > &index, + detail::in_place_interface &table, + std::size_t &length, + detail::false_ is_intrusive, bool use_lock) { (void)is_intrusive; - typedef IndexType > index_type; + typedef IndexType > index_type; typedef typename index_type::key_type key_type; typedef typename index_type::iterator index_it; @@ -903,7 +899,7 @@ class segment_manager if(it != index.end()){ //Get header block_header_t *ctrl_data = reinterpret_cast - (ipcdetail::to_raw_pointer(it->second.m_ptr)); + (detail::get_pointer(it->second.m_ptr)); //Sanity check BOOST_ASSERT((ctrl_data->m_value_bytes % table.size) == 0); @@ -917,23 +913,23 @@ class segment_manager template bool priv_generic_named_destroy (block_header_t *block_header, - IndexType > &index, - ipcdetail::in_place_interface &table, - ipcdetail::true_ is_node_index) + IndexType > &index, + detail::in_place_interface &table, + detail::true_ is_node_index) { (void)is_node_index; - typedef typename IndexType >::iterator index_it; + typedef typename IndexType >::iterator index_it; - index_it *ihdr = block_header_t::template to_first_header(block_header); + index_it *ihdr = block_header_t::to_first_header(block_header); return this->priv_generic_named_destroy_impl(*ihdr, index, table); } template bool priv_generic_named_destroy (block_header_t *block_header, - IndexType > &index, - ipcdetail::in_place_interface &table, - ipcdetail::false_ is_node_index) + IndexType > &index, + detail::in_place_interface &table, + detail::false_ is_node_index) { (void)is_node_index; CharT *name = static_cast(block_header->template name()); @@ -941,21 +937,22 @@ class segment_manager } template - bool priv_generic_named_destroy(const CharT *name, - IndexType > &index, - ipcdetail::in_place_interface &table, - ipcdetail::true_ is_intrusive_index) + bool priv_generic_named_destroy(const CharT *name, + IndexType > &index, + detail::in_place_interface &table, + detail::true_ is_intrusive_index) { (void)is_intrusive_index; - typedef IndexType > index_type; + typedef IndexType > index_type; + typedef detail::index_key index_key_t; typedef typename index_type::iterator index_it; typedef typename index_type::value_type intrusive_value_type; - + //------------------------------- scoped_lock guard(m_header); //------------------------------- //Find name in index - ipcdetail::intrusive_compare_key key + detail::intrusive_compare_key key (name, std::char_traits::length(name)); index_it it = index.find(key); @@ -971,7 +968,7 @@ class segment_manager void *memory = iv; void *values = ctrl_data->value(); std::size_t num = ctrl_data->m_value_bytes/table.size; - + //Sanity check BOOST_ASSERT((ctrl_data->m_value_bytes % table.size) == 0); BOOST_ASSERT(sizeof(CharT) == ctrl_data->sizeof_char()); @@ -991,13 +988,13 @@ class segment_manager } template - bool priv_generic_named_destroy(const CharT *name, - IndexType > &index, - ipcdetail::in_place_interface &table, - ipcdetail::false_ is_intrusive_index) + bool priv_generic_named_destroy(const CharT *name, + IndexType > &index, + detail::in_place_interface &table, + detail::false_ is_intrusive_index) { (void)is_intrusive_index; - typedef IndexType > index_type; + typedef IndexType > index_type; typedef typename index_type::iterator index_it; typedef typename index_type::key_type key_type; @@ -1005,7 +1002,7 @@ class segment_manager scoped_lock guard(m_header); //------------------------------- //Try to find the name in the index - index_it it = index.find(key_type (name, + index_it it = index.find(key_type (name, std::char_traits::length(name))); //If not found, return false @@ -1019,22 +1016,22 @@ class segment_manager template bool priv_generic_named_destroy_impl - (const typename IndexType >::iterator &it, - IndexType > &index, - ipcdetail::in_place_interface &table) + (const typename IndexType >::iterator &it, + IndexType > &index, + detail::in_place_interface &table) { - typedef IndexType > index_type; + typedef IndexType > index_type; typedef typename index_type::iterator index_it; //Get allocation parameters block_header_t *ctrl_data = reinterpret_cast - (ipcdetail::to_raw_pointer(it->second.m_ptr)); + (detail::get_pointer(it->second.m_ptr)); char *stored_name = static_cast(static_cast(const_cast(it->first.name()))); (void)stored_name; - //Check if the distance between the name pointer and the memory pointer + //Check if the distance between the name pointer and the memory pointer //is correct (this can detect incorrect type in destruction) - std::size_t num = ctrl_data->m_value_bytes/table.size; + std::size_t num = ctrl_data->m_value_bytes/table.size; void *values = ctrl_data->value(); //Sanity check @@ -1050,7 +1047,7 @@ class segment_manager void *memory; if(is_node_index_t::value){ - index_it *ihdr = block_header_t::template + index_it *ihdr = block_header_t:: to_first_header(ctrl_data); ihdr->~index_it(); memory = ihdr; @@ -1060,32 +1057,32 @@ class segment_manager } //Call destructors and free memory - std::size_t destroyed; + std::size_t destroyed; table.destroy_n(values, num, destroyed); this->deallocate(memory); return true; } template - void * priv_generic_named_construct(unsigned char type, + void * priv_generic_named_construct(std::size_t type, const CharT *name, - size_type num, - bool try2find, + std::size_t num, + bool try2find, bool dothrow, - ipcdetail::in_place_interface &table, - IndexType > &index, - ipcdetail::true_ is_intrusive) + detail::in_place_interface &table, + IndexType > &index, + detail::true_ is_intrusive) { (void)is_intrusive; - std::size_t namelen = std::char_traits::length(name); + std::size_t namelen = std::char_traits::length(name); - block_header_t block_info ( size_type(table.size*num) - , size_type(table.alignment) + block_header_t block_info ( table.size*num + , table.alignment , type , sizeof(CharT) , namelen); - typedef IndexType > index_type; + typedef IndexType > index_type; typedef typename index_type::iterator index_it; typedef std::pair index_ib; @@ -1094,12 +1091,12 @@ class segment_manager //------------------------------- //Insert the node. This can throw. //First, we want to know if the key is already present before - //we allocate any memory, and if the key is not present, we + //we allocate any memory, and if the key is not present, we //want to allocate all memory in a single buffer that will //contain the name and the user buffer. // //Since equal_range(key) + insert(hint, value) approach is - //quite inefficient in container implementations + //quite inefficient in container implementations //(they re-test if the position is correct), I've chosen //to insert the node, do an ugly un-const cast and modify //the key (which is a smart pointer) to an equivalent one @@ -1109,7 +1106,7 @@ class segment_manager typedef typename index_type::value_type intrusive_value_type; BOOST_TRY{ - ipcdetail::intrusive_compare_key key(name, namelen); + detail::intrusive_compare_key key(name, namelen); insert_ret = index.insert_check(key, commit_data); } //Ignore exceptions @@ -1137,18 +1134,18 @@ class segment_manager } //Allocates buffer for name + data, this can throw (it hurts) - void *buffer_ptr; + void *buffer_ptr; //Check if there is enough memory if(dothrow){ buffer_ptr = this->allocate - (block_info.template total_size_with_header()); + (block_info.total_size_with_header()); } else{ buffer_ptr = this->allocate - (block_info.template total_size_with_header(), std::nothrow_t()); + (block_info.total_size_with_header(), std::nothrow_t()); if(!buffer_ptr) - return 0; + return 0; } //Now construct the intrusive hook plus the header @@ -1175,7 +1172,7 @@ class segment_manager //Avoid constructions if constructor is trivial //Build scoped ptr to avoid leaks with constructor exception - ipcdetail::mem_algo_deallocator mem + detail::mem_algo_deallocator mem (buffer_ptr, *static_cast(this)); //Initialize the node value_eraser to erase inserted node @@ -1183,9 +1180,9 @@ class segment_manager //the memory allocation as the intrusive value is built in that //memory value_eraser v_eraser(index, it); - + //Construct array, this can throw - ipcdetail::array_construct(ptr, num, table); + detail::array_construct(ptr, num, table); //Release rollbacks since construction was successful v_eraser.release(); @@ -1196,25 +1193,25 @@ class segment_manager //!Generic named new function for //!named functions template - void * priv_generic_named_construct(unsigned char type, + void * priv_generic_named_construct(std::size_t type, const CharT *name, - size_type num, - bool try2find, + std::size_t num, + bool try2find, bool dothrow, - ipcdetail::in_place_interface &table, - IndexType > &index, - ipcdetail::false_ is_intrusive) + detail::in_place_interface &table, + IndexType > &index, + detail::false_ is_intrusive) { (void)is_intrusive; std::size_t namelen = std::char_traits::length(name); - block_header_t block_info ( size_type(table.size*num) - , size_type(table.alignment) + block_header_t block_info ( table.size*num + , table.alignment , type , sizeof(CharT) , namelen); - typedef IndexType > index_type; + typedef IndexType > index_type; typedef typename index_type::key_type key_type; typedef typename index_type::mapped_type mapped_type; typedef typename index_type::value_type value_type; @@ -1226,12 +1223,12 @@ class segment_manager //------------------------------- //Insert the node. This can throw. //First, we want to know if the key is already present before - //we allocate any memory, and if the key is not present, we + //we allocate any memory, and if the key is not present, we //want to allocate all memory in a single buffer that will //contain the name and the user buffer. // //Since equal_range(key) + insert(hint, value) approach is - //quite inefficient in container implementations + //quite inefficient in container implementations //(they re-test if the position is correct), I've chosen //to insert the node, do an ugly un-const cast and modify //the key (which is a smart pointer) to an equivalent one @@ -1254,7 +1251,7 @@ class segment_manager if(!insert_ret.second){ if(try2find){ block_header_t *hdr = static_cast - (ipcdetail::to_raw_pointer(it->second.m_ptr)); + (detail::get_pointer(it->second.m_ptr)); return hdr->value(); } return 0; @@ -1264,22 +1261,22 @@ class segment_manager value_eraser v_eraser(index, it); //Allocates buffer for name + data, this can throw (it hurts) - void *buffer_ptr; + void *buffer_ptr; block_header_t * hdr; //Allocate and construct the headers if(is_node_index_t::value){ - size_type total_size = block_info.template total_size_with_header(); + std::size_t total_size = block_info.total_size_with_header(); if(dothrow){ buffer_ptr = this->allocate(total_size); } else{ buffer_ptr = this->allocate(total_size, std::nothrow_t()); if(!buffer_ptr) - return 0; + return 0; } index_it *idr = new(buffer_ptr) index_it(it); - hdr = block_header_t::template from_first_header(idr); + hdr = block_header_t::from_first_header(idr); } else{ if(dothrow){ @@ -1288,7 +1285,7 @@ class segment_manager else{ buffer_ptr = this->allocate(block_info.total_size(), std::nothrow_t()); if(!buffer_ptr) - return 0; + return 0; } hdr = static_cast(buffer_ptr); } @@ -1302,17 +1299,17 @@ class segment_manager std::char_traits::copy(name_ptr, name, namelen+1); //Do the ugly cast, please mama, forgive me! - //This new key points to an identical string, so it must have the + //This new key points to an identical string, so it must have the //same position than the overwritten key according to the predicate const_cast(it->first).name(name_ptr); it->second.m_ptr = hdr; //Build scoped ptr to avoid leaks with constructor exception - ipcdetail::mem_algo_deallocator mem + detail::mem_algo_deallocator mem (buffer_ptr, *static_cast(this)); //Construct array, this can throw - ipcdetail::array_construct(ptr, num, table); + detail::array_construct(ptr, num, table); //All constructors successful, we don't want to release memory mem.release(); @@ -1335,7 +1332,7 @@ class segment_manager if(use_lock){ local.lock(); } - return scoped_lock(boost::move(local)); + return scoped_lock(boost::interprocess::move(local)); } //!This struct includes needed data and derives from @@ -1345,7 +1342,7 @@ class segment_manager { named_index_t m_named_index; unique_index_t m_unique_index; - + header_t(Base *restricted_segment_mngr) : m_named_index (restricted_segment_mngr) , m_unique_index(restricted_segment_mngr) diff --git a/utils/boost_idb/boost/interprocess/shared_memory_object.hpp b/utils/boost_idb/boost/interprocess/shared_memory_object.hpp index 54563f5c..1b47c1d9 100644 --- a/utils/boost_idb/boost/interprocess/shared_memory_object.hpp +++ b/utils/boost_idb/boost/interprocess/shared_memory_object.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -28,7 +28,7 @@ #if defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS_ONLY) # include //System V shared memory... #elif defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS) -# include //O_CREAT, O_*... +# include //O_CREAT, O_*... # include //shm_xxx # include //ftruncate, close # include //mode_t, S_IRWXG, S_IRWXO, S_IRWXU, @@ -53,7 +53,7 @@ class shared_memory_object { /// @cond //Non-copyable and non-assignable - BOOST_MOVABLE_BUT_NOT_COPYABLE(shared_memory_object) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(shared_memory_object) /// @endcond public: @@ -63,35 +63,34 @@ class shared_memory_object //!Creates a shared memory object with name "name" and mode "mode", with the access mode "mode" //!If the file previously exists, throws an error.*/ shared_memory_object(create_only_t, const char *name, mode_t mode, const permissions &perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoCreate, name, mode, perm); } + { this->priv_open_or_create(detail::DoCreate, name, mode, perm); } //!Tries to create a shared memory object with name "name" and mode "mode", with the //!access mode "mode". If the file previously exists, it tries to open it with mode "mode". //!Otherwise throws an error. shared_memory_object(open_or_create_t, const char *name, mode_t mode, const permissions &perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, name, mode, perm); } + { this->priv_open_or_create(detail::DoOpenOrCreate, name, mode, perm); } - //!Tries to open a shared memory object with name "name", with the access mode "mode". + //!Tries to open a shared memory object with name "name", with the access mode "mode". //!If the file does not previously exist, it throws an error. shared_memory_object(open_only_t, const char *name, mode_t mode) - { this->priv_open_or_create(ipcdetail::DoOpen, name, mode, permissions()); } + { this->priv_open_or_create(detail::DoOpen, name, mode, permissions()); } - //!Moves the ownership of "moved"'s shared memory object to *this. - //!After the call, "moved" does not represent any shared memory object. + //!Moves the ownership of "moved"'s shared memory object to *this. + //!After the call, "moved" does not represent any shared memory object. //!Does not throw - shared_memory_object(BOOST_RV_REF(shared_memory_object) moved) - : m_handle(file_handle_t(ipcdetail::invalid_file())) - , m_mode(read_only) + shared_memory_object(BOOST_INTERPROCESS_RV_REF(shared_memory_object) moved) + : m_handle(file_handle_t(detail::invalid_file())) { this->swap(moved); } //!Moves the ownership of "moved"'s shared memory to *this. - //!After the call, "moved" does not represent any shared memory. + //!After the call, "moved" does not represent any shared memory. //!Does not throw - shared_memory_object &operator=(BOOST_RV_REF(shared_memory_object) moved) - { - shared_memory_object tmp(boost::move(moved)); + shared_memory_object &operator=(BOOST_INTERPROCESS_RV_REF(shared_memory_object) moved) + { + shared_memory_object tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Swaps the shared_memory_objects. Does not throw @@ -100,7 +99,7 @@ class shared_memory_object //!Erases a shared memory object from the system. //!Returns false on error. Never throws static bool remove(const char *name); - + //!Sets the size of the shared memory mapping void truncate(offset_t length); @@ -133,7 +132,7 @@ class shared_memory_object void priv_close(); //!Closes a previously opened file mapping. Never throws. - bool priv_open_or_create(ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm); + bool priv_open_or_create(detail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm); file_handle_t m_handle; mode_t m_mode; @@ -143,12 +142,11 @@ class shared_memory_object /// @cond -inline shared_memory_object::shared_memory_object() - : m_handle(file_handle_t(ipcdetail::invalid_file())) - , m_mode(read_only) +inline shared_memory_object::shared_memory_object() + : m_handle(file_handle_t(detail::invalid_file())) {} -inline shared_memory_object::~shared_memory_object() +inline shared_memory_object::~shared_memory_object() { this->priv_close(); } @@ -156,18 +154,18 @@ inline const char *shared_memory_object::get_name() const { return m_filename.c_str(); } inline bool shared_memory_object::get_size(offset_t &size) const -{ return ipcdetail::get_file_size((file_handle_t)m_handle, size); } +{ return detail::get_file_size((file_handle_t)m_handle, size); } inline void shared_memory_object::swap(shared_memory_object &other) -{ +{ std::swap(m_handle, other.m_handle); std::swap(m_mode, other.m_mode); - m_filename.swap(other.m_filename); + m_filename.swap(other.m_filename); } inline mapping_handle_t shared_memory_object::get_mapping_handle() const { - return ipcdetail::mapping_handle_from_file_handle(m_handle); + return detail::mapping_handle_from_file_handle(m_handle); } inline mode_t shared_memory_object::get_mode() const @@ -176,11 +174,11 @@ inline mode_t shared_memory_object::get_mode() const #if !defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS) inline bool shared_memory_object::priv_open_or_create - (ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm) + (detail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm) { m_filename = filename; std::string shmfile; - ipcdetail::create_tmp_and_clean_old_and_get_filename(filename, shmfile); + detail::create_tmp_and_clean_old_and_get_filename(filename, shmfile); //Set accesses if (mode != read_write && mode != read_only){ @@ -189,14 +187,14 @@ inline bool shared_memory_object::priv_open_or_create } switch(type){ - case ipcdetail::DoOpen: - m_handle = ipcdetail::open_existing_file(shmfile.c_str(), mode, true); + case detail::DoOpen: + m_handle = detail::open_existing_file(shmfile.c_str(), mode, true); break; - case ipcdetail::DoCreate: - m_handle = ipcdetail::create_new_file(shmfile.c_str(), mode, perm, true); + case detail::DoCreate: + m_handle = detail::create_new_file(shmfile.c_str(), mode, perm, true); break; - case ipcdetail::DoOpenOrCreate: - m_handle = ipcdetail::create_or_open_file(shmfile.c_str(), mode, perm, true); + case detail::DoOpenOrCreate: + m_handle = detail::create_or_open_file(shmfile.c_str(), mode, perm, true); break; default: { @@ -206,7 +204,7 @@ inline bool shared_memory_object::priv_open_or_create } //Check for error - if(m_handle == ipcdetail::invalid_file()){ + if(m_handle == detail::invalid_file()){ error_info err = system_error_code(); this->priv_close(); throw interprocess_exception(err); @@ -221,8 +219,8 @@ inline bool shared_memory_object::remove(const char *filename) try{ //Make sure a temporary path is created for shared memory std::string shmfile; - ipcdetail::tmp_filename(filename, shmfile); - return ipcdetail::delete_file(shmfile.c_str()); + detail::tmp_filename(filename, shmfile); + return detail::delete_file(shmfile.c_str()); } catch(...){ return false; @@ -231,7 +229,7 @@ inline bool shared_memory_object::remove(const char *filename) inline void shared_memory_object::truncate(offset_t length) { - if(!ipcdetail::truncate_file(m_handle, length)){ + if(!detail::truncate_file(m_handle, length)){ error_info err = system_error_code(); throw interprocess_exception(err); } @@ -239,9 +237,9 @@ inline void shared_memory_object::truncate(offset_t length) inline void shared_memory_object::priv_close() { - if(m_handle != ipcdetail::invalid_file()){ - ipcdetail::close_file(m_handle); - m_handle = ipcdetail::invalid_file(); + if(m_handle != detail::invalid_file()){ + detail::close_file(m_handle); + m_handle = detail::invalid_file(); } } @@ -253,7 +251,7 @@ namespace shared_memory_object_detail { #if defined(__FreeBSD__) -inline bool use_filesystem_based_posix() +inline bool use_filesistem_based_posix() { int jailed = 0; std::size_t len = sizeof(jailed); @@ -270,22 +268,22 @@ inline bool use_filesystem_based_posix() } //shared_memory_object_detail inline bool shared_memory_object::priv_open_or_create - (ipcdetail::create_enum_t type, + (detail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm) { #if defined(BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY) const bool add_leading_slash = false; #elif defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY) - const bool add_leading_slash = !shared_memory_object_detail::use_filesystem_based_posix(); + const bool add_leading_slash = !shared_memory_object_detail::use_filesistem_based_posix(); #else const bool add_leading_slash = true; #endif if(add_leading_slash){ - ipcdetail::add_leading_slash(filename, m_filename); + detail::add_leading_slash(filename, m_filename); } else{ - ipcdetail::create_tmp_and_clean_old_and_get_filename(filename, m_filename); + detail::create_tmp_and_clean_old_and_get_filename(filename, m_filename); } //Create new mapping @@ -300,58 +298,34 @@ inline bool shared_memory_object::priv_open_or_create error_info err(mode_error); throw interprocess_exception(err); } - int unix_perm = perm.get_permissions(); switch(type){ - case ipcdetail::DoOpen: - { - //No oflag addition - m_handle = shm_open(m_filename.c_str(), oflag, unix_perm); - } + case detail::DoOpen: + //No addition break; - case ipcdetail::DoCreate: - { + case detail::DoCreate: oflag |= (O_CREAT | O_EXCL); - m_handle = shm_open(m_filename.c_str(), oflag, unix_perm); - if(m_handle >= 0){ - ::fchmod(m_handle, unix_perm); - } - } break; - case ipcdetail::DoOpenOrCreate: - { - //We need a create/open loop to change permissions correctly using fchmod, since - //with "O_CREAT" only we don't know if we've created or opened the shm. - while(1){ - //Try to create shared memory - m_handle = shm_open(m_filename.c_str(), oflag | (O_CREAT | O_EXCL), unix_perm); - //If successful change real permissions - if(m_handle >= 0){ - ::fchmod(m_handle, unix_perm); - } - //If already exists, try to open - else if(errno == EEXIST){ - m_handle = shm_open(m_filename.c_str(), oflag, unix_perm); - //If open fails and errno tells the file does not exist - //(shm was removed between creation and opening tries), just retry - if(m_handle < 0 && errno == ENOENT){ - continue; - } - } - //Exit retries - break; - } - } + case detail::DoOpenOrCreate: + oflag |= O_CREAT; break; default: - { - error_info err = other_error; - throw interprocess_exception(err); - } + { + error_info err = other_error; + throw interprocess_exception(err); + } + } + + //Open file using POSIX API + m_handle = shm_open(m_filename.c_str(), oflag, perm.get_permissions()); + + //RJD: only set perms on create + if(m_handle >= 0 && type != detail::DoOpen){ + ::fchmod(m_handle, perm.get_permissions()); } //Check for error - if(m_handle < 0){ + if(m_handle == -1){ error_info err = errno; this->priv_close(); throw interprocess_exception(err); @@ -369,15 +343,15 @@ inline bool shared_memory_object::remove(const char *filename) #if defined(BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY) const bool add_leading_slash = false; #elif defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY) - const bool add_leading_slash = !shared_memory_object_detail::use_filesystem_based_posix(); + const bool add_leading_slash = !shared_memory_object_detail::use_filesistem_based_posix(); #else const bool add_leading_slash = true; #endif if(add_leading_slash){ - ipcdetail::add_leading_slash(filename, file_str); + detail::add_leading_slash(filename, file_str); } else{ - ipcdetail::tmp_filename(filename, file_str); + detail::tmp_filename(filename, file_str); } return 0 == shm_unlink(file_str.c_str()); } diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/deleter.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/deleter.hpp index 8447bf1b..7e954a7c 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/deleter.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/deleter.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2007-2012. +// (C) Copyright Ion Gaztanaga 2007-2009. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -20,15 +20,15 @@ #include #include #include -#include +#include //!\file //!Describes the functor to delete objects from the segment. namespace boost { -namespace interprocess { +namespace interprocess { -//!A deleter that uses the segment manager's destroy_ptr +//!A deleter that uses the segment manager's destroy_ptr //!function to destroy the passed pointer resource. //! //!This deleter is used @@ -36,14 +36,12 @@ template class deleter { public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; + typedef typename boost::pointer_to_other + ::type pointer; private: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type segment_manager_pointer; + typedef typename boost::pointer_to_other + ::type segment_manager_pointer; segment_manager_pointer mp_mngr; @@ -53,10 +51,10 @@ class deleter {} void operator()(const pointer &p) - { mp_mngr->destroy_ptr(ipcdetail::to_raw_pointer(p)); } + { mp_mngr->destroy_ptr(detail::get_pointer(p)); } }; -} //namespace interprocess { +} //namespace interprocess { } //namespace boost { #include diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/detail/shared_count.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/detail/shared_count.hpp index 2a86a355..46baf818 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/detail/shared_count.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/detail/shared_count.hpp @@ -4,7 +4,7 @@ // // (C) Copyright Peter Dimov and Multi Media Ltd. 2001, 2002, 2003 // (C) Copyright Peter Dimov 2004-2005 -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -24,17 +24,16 @@ #include #include -#include +#include #include #include #include -#include #include #include // std::less namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ template class weak_count; @@ -43,32 +42,21 @@ template class shared_count { public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; + typedef typename boost::pointer_to_other + ::type pointer; private: typedef sp_counted_impl_pd counted_impl; - - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type counted_impl_ptr; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type counted_base_ptr; - - typedef boost::container::allocator_traits vallocator_traits; - - typedef typename vallocator_traits::template - portable_rebind_alloc::type counted_impl_allocator; - - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_deleter_pointer; - - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_allocator_pointer; + typedef typename boost::pointer_to_other + ::type counted_impl_ptr; + typedef typename boost::pointer_to_other + ::type counted_base_ptr; + typedef typename VoidAllocator::template rebind + ::other counted_impl_allocator; + typedef typename boost::pointer_to_other + ::type const_deleter_pointer; + typedef typename boost::pointer_to_other + ::type const_allocator_pointer; pointer m_px; counted_impl_ptr m_pi; @@ -99,12 +87,12 @@ class shared_count counted_impl_allocator alloc(a); m_pi = alloc.allocate(1); //Anti-exception deallocator - scoped_ptr > deallocator(m_pi, alloc); //It's more correct to use VoidAllocator::construct but //this needs copy constructor and we don't like it - new(ipcdetail::to_raw_pointer(m_pi))counted_impl(p, a, d); + new(detail::get_pointer(m_pi))counted_impl(p, a, d); deallocator.release(); } } @@ -116,8 +104,8 @@ class shared_count } ~shared_count() // nothrow - { - if(m_pi) + { + if( m_pi != 0 ) m_pi->release(); } @@ -157,10 +145,10 @@ class shared_count } } - const pointer &to_raw_pointer() const + const pointer &get_pointer() const { return m_px; } - pointer &to_raw_pointer() + pointer &get_pointer() { return m_px; } shared_count & operator= (shared_count const & r) // nothrow @@ -189,7 +177,7 @@ class shared_count } void swap(shared_count & r) // nothrow - { ipcdetail::do_swap(m_px, r.m_px); ipcdetail::do_swap(m_pi, r.m_pi); } + { detail::do_swap(m_px, r.m_px); detail::do_swap(m_pi, r.m_pi); } long use_count() const // nothrow { return m_pi != 0? m_pi->use_count(): 0; } @@ -225,20 +213,15 @@ template class weak_count { public: - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; + typedef typename boost::pointer_to_other + ::type pointer; private: - - typedef sp_counted_impl_pd counted_impl; - - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type counted_impl_ptr; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type counted_base_ptr; + typedef sp_counted_impl_pd counted_impl; + typedef typename boost::pointer_to_other + ::type counted_impl_ptr; + typedef typename boost::pointer_to_other + ::type counted_base_ptr; pointer m_px; counted_impl_ptr m_pi; @@ -284,7 +267,6 @@ class weak_count weak_count & operator= (weak_count const & r) // nothrow { - m_px = r.m_px; counted_impl_ptr tmp = r.m_pi; if(tmp != 0) tmp->weak_add_ref(); if(m_pi != 0) m_pi->weak_release(); @@ -306,7 +288,7 @@ class weak_count } void swap(weak_count & r) // nothrow - { ipcdetail::do_swap(m_px, r.m_px); ipcdetail::do_swap(m_pi, r.m_pi); } + { detail::do_swap(m_px, r.m_px); detail::do_swap(m_pi, r.m_pi); } long use_count() const // nothrow { return m_pi != 0? m_pi->use_count() : 0; } @@ -328,7 +310,7 @@ template const & a, weak_count const & b) { return a.internal_less(b); } -} // namespace ipcdetail +} // namespace detail } // namespace interprocess } // namespace boost diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base.hpp index d03965cd..f0f8ab8c 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2007-2012. +// (C) Copyright Ion Gaztanaga 2007-2009. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp index 74f65f18..e529fcc4 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp @@ -9,7 +9,7 @@ // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // Copyright 2004-2005 Peter Dimov -// Copyright 2007-2012 Ion Gaztanaga +// Copyright 2007-2009 Ion Gaztanaga // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at @@ -32,7 +32,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { class sp_counted_base { @@ -54,7 +54,7 @@ class sp_counted_base void add_ref_copy() { - ipcdetail::atomic_inc32( &use_count_ ); + detail::atomic_inc32( &use_count_ ); } bool add_ref_lock() // true on success @@ -63,25 +63,25 @@ class sp_counted_base { boost::uint32_t tmp = static_cast< boost::uint32_t const volatile& >( use_count_ ); if( tmp == 0 ) return false; - if( ipcdetail::atomic_cas32( &use_count_, tmp + 1, tmp ) == tmp ) + if( detail::atomic_cas32( &use_count_, tmp + 1, tmp ) == tmp ) return true; } } bool ref_release() // nothrow - { return 1 == ipcdetail::atomic_dec32( &use_count_ ); } + { return 1 == detail::atomic_dec32( &use_count_ ); } void weak_add_ref() // nothrow - { ipcdetail::atomic_inc32( &weak_count_ ); } + { detail::atomic_inc32( &weak_count_ ); } bool weak_release() // nothrow - { return 1 == ipcdetail::atomic_dec32( &weak_count_ ); } + { return 1 == detail::atomic_dec32( &weak_count_ ); } long use_count() const // nothrow { return (long)static_cast( use_count_ ); } }; -} // namespace ipcdetail +} // namespace detail } // namespace interprocess diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp index d5142fa5..9d799fae 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/detail/sp_counted_impl.hpp @@ -26,14 +26,13 @@ #include #include #include -#include -#include +#include namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { //!A deleter for scoped_ptr that deallocates the memory //!allocated for an object using a STL allocator. @@ -41,10 +40,10 @@ template struct scoped_ptr_dealloc_functor { typedef typename Allocator::pointer pointer; - typedef ipcdetail::integral_constant::value> alloc_version; - typedef ipcdetail::integral_constant allocator_v1; - typedef ipcdetail::integral_constant allocator_v2; + typedef detail::integral_constant allocator_v1; + typedef detail::integral_constant allocator_v2; private: void priv_deallocate(const typename Allocator::pointer &p, allocator_v1) @@ -63,38 +62,28 @@ struct scoped_ptr_dealloc_functor { if (ptr) priv_deallocate(ptr, alloc_version()); } }; - - template -class sp_counted_impl_pd +class sp_counted_impl_pd : public sp_counted_base - , boost::container::allocator_traits::template - portable_rebind_alloc< sp_counted_impl_pd >::type + , A::template rebind< sp_counted_impl_pd >::other , D // copy constructor must not throw { private: typedef sp_counted_impl_pd this_type; - typedef typename boost::container:: - allocator_traits::template - portable_rebind_alloc - < this_type >::type this_allocator; - typedef typename boost::container:: - allocator_traits::template - portable_rebind_alloc - < const this_type >::type const_this_allocator; + typedef typename A::template rebind + ::other this_allocator; + typedef typename A::template rebind + ::other const_this_allocator; typedef typename this_allocator::pointer this_pointer; - typedef typename boost::intrusive:: - pointer_traits this_pointer_traits; sp_counted_impl_pd( sp_counted_impl_pd const & ); sp_counted_impl_pd & operator= ( sp_counted_impl_pd const & ); - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_deleter_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_allocator_pointer; + typedef typename boost::pointer_to_other + ::type const_deleter_pointer; + + typedef typename boost::pointer_to_other + ::type const_allocator_pointer; typedef typename D::pointer pointer; pointer m_ptr; @@ -117,15 +106,16 @@ class sp_counted_impl_pd void destroy() // nothrow { - //Self destruction, so move the allocator - this_allocator a_copy(::boost::move(static_cast(*this))); + //Self destruction, so get a copy of the allocator + //(in the future we could move it) + this_allocator a_copy(*this); BOOST_ASSERT(a_copy == *this); - this_pointer this_ptr(this_pointer_traits::pointer_to(*this)); + this_pointer this_ptr (this); //Do it now! scoped_ptr< this_type, scoped_ptr_dealloc_functor > - deleter_ptr(this_ptr, a_copy); + deleter(this_ptr, a_copy); typedef typename this_allocator::value_type value_type; - ipcdetail::to_raw_pointer(this_ptr)->~value_type(); + detail::get_pointer(this_ptr)->~value_type(); } void release() // nothrow @@ -145,7 +135,7 @@ class sp_counted_impl_pd }; -} // namespace ipcdetail +} // namespace detail } // namespace interprocess diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/enable_shared_from_this.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/enable_shared_from_this.hpp index d9f16aec..5d1c98e6 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/enable_shared_from_this.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/enable_shared_from_this.hpp @@ -3,7 +3,7 @@ // This file is the adaptation for Interprocess of boost/enable_shared_from_this.hpp // // (C) Copyright Peter Dimov 2002 -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -14,8 +14,8 @@ #ifndef BOOST_INTERPROCESS_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED #define BOOST_INTERPROCESS_ENABLE_SHARED_FROM_THIS_HPP_INCLUDED -#include #include +#include #include #include @@ -53,14 +53,14 @@ class enable_shared_from_this shared_ptr shared_from_this() { shared_ptr p(_internal_weak_this); - BOOST_ASSERT(ipcdetail::to_raw_pointer(p.get()) == this); + BOOST_ASSERT(detail::get_pointer(p.get()) == this); return p; } shared_ptr shared_from_this() const { shared_ptr p(_internal_weak_this); - BOOST_ASSERT(ipcdetail::to_raw_pointer(p.get()) == this); + BOOST_ASSERT(detail::get_pointer(p.get()) == this); return p; } diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/intrusive_ptr.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/intrusive_ptr.hpp index 897c5da4..86df285c 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/intrusive_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/intrusive_ptr.hpp @@ -3,7 +3,7 @@ // This file is the adaptation for Interprocess of boost/intrusive_ptr.hpp // // (C) Copyright Peter Dimov 2001, 2002 -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -22,7 +22,7 @@ #include #include -#include +#include #include // for std::less #include // for std::basic_ostream @@ -33,12 +33,12 @@ namespace interprocess { //!The intrusive_ptr class template stores a pointer to an object //!with an embedded reference count. intrusive_ptr is parameterized on -//!T (the type of the object pointed to) and VoidPointer(a void pointer type +//!T (the type of the object pointed to) and VoidPointer(a void pointer type //!that defines the type of pointer that intrusive_ptr will store). //!intrusive_ptr defines a class with a T* member whereas //!intrusive_ptr > defines a class with a offset_ptr member. //!Relies on unqualified calls to: -//! +//! //! void intrusive_ptr_add_ref(T * p); //! void intrusive_ptr_release(T * p); //! @@ -50,9 +50,7 @@ class intrusive_ptr { public: //!Provides the type of the internal stored pointer. - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; + typedef typename boost::pointer_to_other::type pointer; //!Provides the type of the stored pointer. typedef T element_type; @@ -69,39 +67,39 @@ class intrusive_ptr intrusive_ptr(): m_ptr(0) {} - //!Constructor. Copies pointer and if "p" is not zero and - //!"add_ref" is true calls intrusive_ptr_add_ref(to_raw_pointer(p)). + //!Constructor. Copies pointer and if "p" is not zero and + //!"add_ref" is true calls intrusive_ptr_add_ref(get_pointer(p)). //!Does not throw intrusive_ptr(const pointer &p, bool add_ref = true): m_ptr(p) { - if(m_ptr != 0 && add_ref) intrusive_ptr_add_ref(ipcdetail::to_raw_pointer(m_ptr)); + if(m_ptr != 0 && add_ref) intrusive_ptr_add_ref(detail::get_pointer(m_ptr)); } //!Copy constructor. Copies the internal pointer and if "p" is not - //!zero calls intrusive_ptr_add_ref(to_raw_pointer(p)). Does not throw + //!zero calls intrusive_ptr_add_ref(get_pointer(p)). Does not throw intrusive_ptr(intrusive_ptr const & rhs) : m_ptr(rhs.m_ptr) { - if(m_ptr != 0) intrusive_ptr_add_ref(ipcdetail::to_raw_pointer(m_ptr)); + if(m_ptr != 0) intrusive_ptr_add_ref(detail::get_pointer(m_ptr)); } //!Constructor from related. Copies the internal pointer and if "p" is not - //!zero calls intrusive_ptr_add_ref(to_raw_pointer(p)). Does not throw + //!zero calls intrusive_ptr_add_ref(get_pointer(p)). Does not throw template intrusive_ptr (intrusive_ptr const & rhs) : m_ptr(rhs.get()) { - if(m_ptr != 0) intrusive_ptr_add_ref(ipcdetail::to_raw_pointer(m_ptr)); + if(m_ptr != 0) intrusive_ptr_add_ref(detail::get_pointer(m_ptr)); } //!Destructor. If internal pointer is not 0, calls - //!intrusive_ptr_release(to_raw_pointer(m_ptr)). Does not throw + //!intrusive_ptr_release(get_pointer(m_ptr)). Does not throw ~intrusive_ptr() { - if(m_ptr != 0) intrusive_ptr_release(ipcdetail::to_raw_pointer(m_ptr)); + if(m_ptr != 0) intrusive_ptr_release(detail::get_pointer(m_ptr)); } - //!Assignment operator. Equivalent to intrusive_ptr(r).swap(*this). + //!Assignment operator. Equivalent to intrusive_ptr(r).swap(*this). //!Does not throw intrusive_ptr & operator=(intrusive_ptr const & rhs) { @@ -109,7 +107,7 @@ class intrusive_ptr return *this; } - //!Assignment from related. Equivalent to intrusive_ptr(r).swap(*this). + //!Assignment from related. Equivalent to intrusive_ptr(r).swap(*this). //!Does not throw template intrusive_ptr & operator= (intrusive_ptr const & rhs) @@ -118,14 +116,14 @@ class intrusive_ptr return *this; } - //!Assignment from pointer. Equivalent to intrusive_ptr(r).swap(*this). + //!Assignment from pointer. Equivalent to intrusive_ptr(r).swap(*this). //!Does not throw intrusive_ptr & operator=(pointer rhs) { this_type(rhs).swap(*this); return *this; } - + //!Returns a reference to the internal pointer. //!Does not throw pointer &get() @@ -164,7 +162,7 @@ class intrusive_ptr //!Exchanges the contents of the two smart pointers. //!Does not throw void swap(intrusive_ptr & rhs) - { ipcdetail::do_swap(m_ptr, rhs.m_ptr); } + { detail::do_swap(m_ptr, rhs.m_ptr); } /// @cond private: @@ -175,7 +173,7 @@ class intrusive_ptr //!Returns a.get() == b.get(). //!Does not throw template inline -bool operator==(intrusive_ptr const & a, +bool operator==(intrusive_ptr const & a, intrusive_ptr const & b) { return a.get() == b.get(); } @@ -217,11 +215,11 @@ bool operator!=(const typename intrusive_ptr::pointer &a, //!Returns a.get() < b.get(). //!Does not throw template inline -bool operator<(intrusive_ptr const & a, +bool operator<(intrusive_ptr const & a, intrusive_ptr const & b) -{ +{ return std::less::pointer>() - (a.get(), b.get()); + (a.get(), b.get()); } //!Exchanges the contents of the two intrusive_ptrs. @@ -233,7 +231,7 @@ void swap(intrusive_ptr & lhs, // operator<< template -inline std::basic_ostream & operator<< +inline std::basic_ostream & operator<< (std::basic_ostream & os, intrusive_ptr const & p) { os << p.get(); return os; } @@ -241,7 +239,7 @@ inline std::basic_ostream & operator<< //!Does not throw template inline typename boost::interprocess::intrusive_ptr::pointer - to_raw_pointer(intrusive_ptr p) + get_pointer(intrusive_ptr p) { return p.get(); } /*Emulates static cast operator. Does not throw*/ @@ -283,7 +281,7 @@ inline boost::interprocess::intrusive_ptrreinterpret_pointer_cast //!Returns p.get(). //!Does not throw template -inline T *to_raw_pointer(boost::interprocess::intrusive_ptr p) +inline T *get_pointer(boost::interprocess::intrusive_ptr p) { return p.get(); } #endif diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/scoped_ptr.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/scoped_ptr.hpp index 8a2ba363..74fe1d63 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/scoped_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/scoped_ptr.hpp @@ -4,7 +4,7 @@ // // (C) Copyright Greg Colvin and Beman Dawes 1998, 1999. // (C) Copyright Peter Dimov 2001, 2002 -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,8 +18,8 @@ #include #include #include -#include #include +#include //!\file //!Describes the smart pointer scoped_ptr @@ -27,14 +27,14 @@ namespace boost { namespace interprocess { -//!scoped_ptr stores a pointer to a dynamically allocated object. +//!scoped_ptr stores a pointer to a dynamically allocated object. //!The object pointed to is guaranteed to be deleted, either on destruction //!of the scoped_ptr, or via an explicit reset. The user can avoid this //!deletion using release(). -//!scoped_ptr is parameterized on T (the type of the object pointed to) and +//!scoped_ptr is parameterized on T (the type of the object pointed to) and //!Deleter (the functor to be executed to delete the internal pointer). -//!The internal pointer will be of the same pointer type as typename -//!Deleter::pointer type (that is, if typename Deleter::pointer is +//!The internal pointer will be of the same pointer type as typename +//!Deleter::pointer type (that is, if typename Deleter::pointer is //!offset_ptr, the internal pointer will be offset_ptr). template class scoped_ptr @@ -45,14 +45,18 @@ class scoped_ptr scoped_ptr & operator=(scoped_ptr const &); typedef scoped_ptr this_type; - typedef typename ipcdetail::add_reference::type reference; + typedef typename detail::add_reference::type reference; /// @endcond public: typedef T element_type; typedef Deleter deleter_type; - typedef typename ipcdetail::pointer_type::type pointer; + typedef typename detail::pointer_type::type pointer; + + //!Provides the type of the internal stored pointer +// typedef typename boost::pointer_to_other +// ::type pointer; //!Constructs a scoped_ptr, storing a copy of p(which can be 0) and d. //!Does not throw. @@ -60,10 +64,10 @@ class scoped_ptr : Deleter(d), m_ptr(p) // throws if pointer/Deleter copy ctor throws {} - //!If the stored pointer is not 0, destroys the object pointed to by the stored pointer. + //!If the stored pointer is not 0, destroys the object pointed to by the stored pointer. //!calling the operator() of the stored deleter. Never throws ~scoped_ptr() - { + { if(m_ptr){ Deleter &del = static_cast(*this); del(m_ptr); @@ -78,7 +82,7 @@ class scoped_ptr //!Deletes the object pointed to by the stored pointer and then //!stores a copy of p and a copy of d. void reset(const pointer &p, const Deleter &d) // never throws - { BOOST_ASSERT(p == 0 || p != m_ptr); this_type(p, d).swap(*this); } + { BOOST_ASSERT(p == 0 || p != m_ptr); this_type(p).swap(*this); } //!Assigns internal pointer as 0 and returns previous pointer. This will //!avoid deletion on destructor @@ -125,7 +129,7 @@ class scoped_ptr //!Exchanges the internal pointer and deleter with other scoped_ptr //!Never throws. void swap(scoped_ptr & b) // never throws - { ipcdetail::do_swap(*this, b); ipcdetail::do_swap(m_ptr, b.m_ptr); } + { detail::do_swap(*this, b); detail::do_swap(m_ptr, b.m_ptr); } /// @cond private: @@ -142,7 +146,7 @@ void swap(scoped_ptr & a, scoped_ptr & b) //!Returns a copy of the stored pointer //!Never throws template inline -typename scoped_ptr::pointer to_raw_pointer(scoped_ptr const & p) +typename scoped_ptr::pointer get_pointer(scoped_ptr const & p) { return p.get(); } } // namespace interprocess @@ -151,7 +155,7 @@ typename scoped_ptr::pointer to_raw_pointer(scoped_ptr const & p) #if defined(_MSC_VER) && (_MSC_VER < 1400) template inline -T *to_raw_pointer(boost::interprocess::scoped_ptr const & p) +T *get_pointer(boost::interprocess::scoped_ptr const & p) { return p.get(); } #endif diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/shared_ptr.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/shared_ptr.hpp index 302eb149..9f6ef231 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/shared_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/shared_ptr.hpp @@ -4,7 +4,7 @@ // // (C) Copyright Greg Colvin and Beman Dawes 1998, 1999. // (C) Copyright Peter Dimov 2001, 2002, 2003 -// (C) Copyright Ion Gaztanaga 2006-2012. +// (C) Copyright Ion Gaztanaga 2006-2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) @@ -24,12 +24,12 @@ #include #include #include -#include +#include #include #include #include #include -#include +#include #include // for std::swap #include // for std::less @@ -45,14 +45,14 @@ namespace interprocess{ template class weak_ptr; template class enable_shared_from_this; -namespace ipcdetail{ +namespace detail{ template inline void sp_enable_shared_from_this (shared_count const & pn ,enable_shared_from_this *pe ,T *ptr) - + { (void)ptr; if(pe != 0){ @@ -64,19 +64,19 @@ template inline void sp_enable_shared_from_this(shared_count const &, ...) {} -} // namespace ipcdetail +} // namespace detail -//!shared_ptr stores a pointer to a dynamically allocated object. -//!The object pointed to is guaranteed to be deleted when the last shared_ptr pointing to +//!shared_ptr stores a pointer to a dynamically allocated object. +//!The object pointed to is guaranteed to be deleted when the last shared_ptr pointing to //!it is destroyed or reset. //! -//!shared_ptr is parameterized on +//!shared_ptr is parameterized on //!T (the type of the object pointed to), VoidAllocator (the void allocator to be used -//!to allocate the auxiliary data) and Deleter (the deleter whose +//!to allocate the auxiliary data) and Deleter (the deleter whose //!operator() will be used to delete the object. //! -//!The internal pointer will be of the same pointer type as typename -//!VoidAllocator::pointer type (that is, if typename VoidAllocator::pointer is +//!The internal pointer will be of the same pointer type as typename +//!VoidAllocator::pointer type (that is, if typename VoidAllocator::pointer is //!offset_ptr, the internal pointer will be offset_ptr). //! //!Because the implementation uses reference counting, cycles of shared_ptr @@ -97,21 +97,18 @@ class shared_ptr typedef T element_type; typedef T value_type; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename ipcdetail::add_reference + typedef typename boost::pointer_to_other + ::type pointer; + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_deleter_pointer; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type const_allocator_pointer; - - BOOST_COPYABLE_AND_MOVABLE(shared_ptr) + typedef typename boost::pointer_to_other + ::type const_deleter_pointer; + typedef typename boost::pointer_to_other + ::type const_allocator_pointer; + + BOOST_INTERPROCESS_COPYABLE_AND_MOVABLE(shared_ptr) public: //!Constructs an empty shared_ptr. @@ -125,39 +122,31 @@ class shared_ptr //!Requirements: Deleter and A's copy constructor must not throw. explicit shared_ptr(const pointer&p, const VoidAllocator &a = VoidAllocator(), const Deleter &d = Deleter()) : m_pn(p, a, d) - { + { //Check that the pointer passed is of the same type that //the pointer the allocator defines or it's a raw pointer - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type ParameterPointer; - - BOOST_STATIC_ASSERT((ipcdetail::is_same::value) || - (ipcdetail::is_pointer::value)); - ipcdetail::sp_enable_shared_from_this( m_pn, ipcdetail::to_raw_pointer(p), ipcdetail::to_raw_pointer(p) ); + typedef typename boost::pointer_to_other::type ParameterPointer; + BOOST_STATIC_ASSERT((detail::is_same::value) || + (detail::is_pointer::value)); + detail::sp_enable_shared_from_this( m_pn, detail::get_pointer(p), detail::get_pointer(p) ); } - //!Copy constructs a shared_ptr. If r is empty, constructs an empty shared_ptr. Otherwise, constructs - //!a shared_ptr that shares ownership with r. Never throws. - shared_ptr(const shared_ptr &r) - : m_pn(r.m_pn) // never throws - {} - //!Constructs a shared_ptr that shares ownership with other and stores p. + //!Constructs a shared_ptr that shares ownership with r and stores p. //!Postconditions: get() == p && use_count() == r.use_count(). //!Throws: nothing. shared_ptr(const shared_ptr &other, const pointer &p) : m_pn(other.m_pn, p) {} - //!If r is empty, constructs an empty shared_ptr. Otherwise, constructs + //!If r is empty, constructs an empty shared_ptr. Otherwise, constructs //!a shared_ptr that shares ownership with r. Never throws. template shared_ptr(shared_ptr const & r) : m_pn(r.m_pn) // never throws {} - //!Constructs a shared_ptr that shares ownership with r and stores + //!Constructs a shared_ptr that shares ownership with r and stores //!a copy of the pointer stored in r. template explicit shared_ptr(weak_ptr const & r) @@ -167,30 +156,30 @@ class shared_ptr //!Move-Constructs a shared_ptr that takes ownership of other resource and //!other is put in default-constructed state. //!Throws: nothing. - explicit shared_ptr(BOOST_RV_REF(shared_ptr) other) + explicit shared_ptr(BOOST_INTERPROCESS_RV_REF(shared_ptr) other) : m_pn() { this->swap(other); } /// @cond template - shared_ptr(shared_ptr const & r, ipcdetail::static_cast_tag) - : m_pn( pointer(static_cast(ipcdetail::to_raw_pointer(r.m_pn.to_raw_pointer()))) - , r.m_pn) + shared_ptr(shared_ptr const & r, detail::static_cast_tag) + : m_pn( pointer(static_cast(detail::get_pointer(r.m_pn.get_pointer()))) + , r.m_pn) {} template - shared_ptr(shared_ptr const & r, ipcdetail::const_cast_tag) - : m_pn( pointer(const_cast(ipcdetail::to_raw_pointer(r.m_pn.to_raw_pointer()))) - , r.m_pn) + shared_ptr(shared_ptr const & r, detail::const_cast_tag) + : m_pn( pointer(const_cast(detail::get_pointer(r.m_pn.get_pointer()))) + , r.m_pn) {} template - shared_ptr(shared_ptr const & r, ipcdetail::dynamic_cast_tag) - : m_pn( pointer(dynamic_cast(ipcdetail::to_raw_pointer(r.m_pn.to_raw_pointer()))) - , r.m_pn) + shared_ptr(shared_ptr const & r, detail::dynamic_cast_tag) + : m_pn( pointer(dynamic_cast(detail::get_pointer(r.m_pn.get_pointer()))) + , r.m_pn) { - if(!m_pn.to_raw_pointer()){ // need to allocate new counter -- the cast failed - m_pn = ipcdetail::shared_count(); + if(!m_pn.get_pointer()){ // need to allocate new counter -- the cast failed + m_pn = detail::shared_count(); } } /// @endcond @@ -206,7 +195,7 @@ class shared_ptr //!Equivalent to shared_ptr(r).swap(*this). //!Never throws - shared_ptr & operator=(BOOST_COPY_ASSIGN_REF(shared_ptr) r) + shared_ptr & operator=(BOOST_INTERPROCESS_COPY_ASSIGN_REF(shared_ptr) r) { m_pn = r.m_pn; // shared_count::op= doesn't throw return *this; @@ -214,7 +203,7 @@ class shared_ptr //!Move-assignment. Equivalent to shared_ptr(other).swap(*this). //!Never throws - shared_ptr & operator=(BOOST_RV_REF(shared_ptr) other) // never throws + shared_ptr & operator=(BOOST_INTERPROCESS_RV_REF(shared_ptr) other) // never throws { this_type(other).swap(*this); return *this; @@ -223,23 +212,21 @@ class shared_ptr //!This is equivalent to: //!this_type().swap(*this); void reset() - { - this_type().swap(*this); + { + this_type().swap(*this); } //!This is equivalent to: //!this_type(p, a, d).swap(*this); template void reset(const Pointer &p, const VoidAllocator &a = VoidAllocator(), const Deleter &d = Deleter()) - { + { //Check that the pointer passed is of the same type that //the pointer the allocator defines or it's a raw pointer - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type ParameterPointer; - BOOST_STATIC_ASSERT((ipcdetail::is_same::value) || - (ipcdetail::is_pointer::value)); - this_type(p, a, d).swap(*this); + typedef typename boost::pointer_to_other::type ParameterPointer; + BOOST_STATIC_ASSERT((detail::is_same::value) || + (detail::is_pointer::value)); + this_type(p, a, d).swap(*this); } template @@ -251,17 +238,17 @@ class shared_ptr //!Returns a reference to the //!pointed type reference operator* () const // never throws - { BOOST_ASSERT(m_pn.to_raw_pointer() != 0); return *m_pn.to_raw_pointer(); } + { BOOST_ASSERT(m_pn.get_pointer() != 0); return *m_pn.get_pointer(); } - //!Returns the pointer pointing + //!Returns the pointer pointing //!to the owned object pointer operator-> () const // never throws - { BOOST_ASSERT(m_pn.to_raw_pointer() != 0); return m_pn.to_raw_pointer(); } + { BOOST_ASSERT(m_pn.get_pointer() != 0); return m_pn.get_pointer(); } - //!Returns the pointer pointing + //!Returns the pointer pointing //!to the owned object pointer get() const // never throws - { return m_pn.to_raw_pointer(); } + { return m_pn.get_pointer(); } /// @cond // implicit conversion to "bool" @@ -269,13 +256,13 @@ class shared_ptr typedef void (this_type::*unspecified_bool_type)() const; operator unspecified_bool_type() const // never throws - { return !m_pn.to_raw_pointer() ? 0 : &this_type::unspecified_bool_type_func; } + { return !m_pn.get_pointer() ? 0 : &this_type::unspecified_bool_type_func; } /// @endcond //!Not operator. //!Returns true if this->get() != 0, false otherwise bool operator! () const // never throws - { return !m_pn.to_raw_pointer(); } + { return !m_pn.get_pointer(); } //!Returns use_count() == 1. //!unique() might be faster than use_count() @@ -297,7 +284,7 @@ class shared_ptr /// @cond - template + template bool _internal_less(shared_ptr const & rhs) const { return m_pn < rhs.m_pn; } @@ -312,46 +299,46 @@ class shared_ptr template friend class shared_ptr; template friend class weak_ptr; - ipcdetail::shared_count m_pn; // reference counter + detail::shared_count m_pn; // reference counter /// @endcond }; // shared_ptr -template inline +template inline bool operator==(shared_ptr const & a, shared_ptr const & b) { return a.get() == b.get(); } -template inline +template inline bool operator!=(shared_ptr const & a, shared_ptr const & b) { return a.get() != b.get(); } -template inline +template inline bool operator<(shared_ptr const & a, shared_ptr const & b) { return a._internal_less(b); } -template inline +template inline void swap(shared_ptr & a, shared_ptr & b) { a.swap(b); } template inline shared_ptr static_pointer_cast(shared_ptr const & r) -{ return shared_ptr(r, ipcdetail::static_cast_tag()); } +{ return shared_ptr(r, detail::static_cast_tag()); } -template inline +template inline shared_ptr const_pointer_cast(shared_ptr const & r) -{ return shared_ptr(r, ipcdetail::const_cast_tag()); } +{ return shared_ptr(r, detail::const_cast_tag()); } -template inline +template inline shared_ptr dynamic_pointer_cast(shared_ptr const & r) -{ return shared_ptr(r, ipcdetail::dynamic_cast_tag()); } +{ return shared_ptr(r, detail::dynamic_cast_tag()); } -// to_raw_pointer() enables boost::mem_fn to recognize shared_ptr +// get_pointer() enables boost::mem_fn to recognize shared_ptr template inline -T * to_raw_pointer(shared_ptr const & p) +T * get_pointer(shared_ptr const & p) { return p.get(); } // operator<< template inline -std::basic_ostream & operator<< +std::basic_ostream & operator<< (std::basic_ostream & os, shared_ptr const & p) { os << p.get(); return os; } @@ -381,35 +368,14 @@ inline typename managed_shared_ptr::type ); } -//!Returns an instance of a shared pointer constructed -//!with the default allocator and deleter from a pointer -//!of type T that has been allocated in the passed managed segment. -//!Does not throw, return null shared pointer in error. -template -inline typename managed_shared_ptr::type - make_managed_shared_ptr(T *constructed_object, ManagedMemory &managed_memory, std::nothrow_t) -{ - try{ - return typename managed_shared_ptr::type - ( constructed_object - , managed_memory.template get_allocator() - , managed_memory.template get_deleter() - ); - } - catch(...){ - return typename managed_shared_ptr::type(); - } -} - - } // namespace interprocess /// @cond #if defined(_MSC_VER) && (_MSC_VER < 1400) -// to_raw_pointer() enables boost::mem_fn to recognize shared_ptr +// get_pointer() enables boost::mem_fn to recognize shared_ptr template inline -T * to_raw_pointer(boost::interprocess::shared_ptr const & p) +T * get_pointer(boost::interprocess::shared_ptr const & p) { return p.get(); } #endif diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/unique_ptr.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/unique_ptr.hpp index 6d174a2e..1e27cd77 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/unique_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/unique_ptr.hpp @@ -5,7 +5,7 @@ // This file is the adaptation for Interprocess of // Howard Hinnant's unique_ptr emulation code. // -// (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include #include @@ -38,7 +38,7 @@ namespace interprocess{ /// @cond template class unique_ptr; -namespace ipcdetail { +namespace detail { template struct unique_ptr_error; @@ -48,7 +48,7 @@ struct unique_ptr_error > typedef unique_ptr type; }; -} //namespace ipcdetail { +} //namespace detail { /// @endcond //!Template unique_ptr stores a pointer to an object and deletes that object @@ -82,18 +82,16 @@ template class unique_ptr { /// @cond - struct nat {int for_bool;}; - struct nat2 {int for_nullptr;}; - typedef int nat2::*nullptr_t; - typedef typename ipcdetail::add_reference::type deleter_reference; - typedef typename ipcdetail::add_reference::type deleter_const_reference; + struct nat {int for_bool_;}; + typedef typename detail::add_reference::type deleter_reference; + typedef typename detail::add_reference::type deleter_const_reference; /// @endcond public: typedef T element_type; typedef D deleter_type; - typedef typename ipcdetail::pointer_type::type pointer; + typedef typename detail::pointer_type::type pointer; //!Requires: D must be default constructible, and that construction must not //!throw an exception. D must not be a reference type. @@ -130,9 +128,9 @@ class unique_ptr //! //!Throws: nothing. unique_ptr(pointer p - ,typename ipcdetail::if_ + ,typename detail::if_ ,D - ,typename ipcdetail::add_reference::type>::type d) + ,typename detail::add_reference::type>::type d) : ptr_(p, d) {} @@ -145,7 +143,7 @@ class unique_ptr //! //!After the construction, u no longer owns a pointer. //![ Note: The deleter constructor can be implemented with - //! boost::forward. -end note ] + //! boost::interprocess::forward. -end note ] //! //!Postconditions: get() == value u.get() had before the construction. //!get_deleter() returns a reference to the internally stored deleter which @@ -153,8 +151,8 @@ class unique_ptr //!deleter() and u.get_deleter() both reference the same lvalue deleter. //! //!Throws: nothing. - unique_ptr(BOOST_RV_REF(unique_ptr) u) - : ptr_(u.release(), boost::forward(u.get_deleter())) + unique_ptr(BOOST_INTERPROCESS_RV_REF(unique_ptr) u) + : ptr_(u.release(), boost::interprocess::forward(u.get_deleter())) {} //!Requires: If D is not a reference type, construction of the deleter @@ -177,18 +175,18 @@ class unique_ptr //! //!Throws: nothing. template - unique_ptr(BOOST_RV_REF_BEG unique_ptr BOOST_RV_REF_END u, - typename ipcdetail::enable_if_c< - ipcdetail::is_convertible::pointer, pointer>::value && - ipcdetail::is_convertible::value && + unique_ptr(BOOST_INTERPROCESS_RV_REF_2_TEMPL_ARGS(unique_ptr, U, E) u, + typename detail::enable_if_c< + detail::is_convertible::pointer, pointer>::value && + detail::is_convertible::value && ( - !ipcdetail::is_reference::value || - ipcdetail::is_same::value + !detail::is_reference::value || + detail::is_same::value ) , nat >::type = nat()) - : ptr_(const_cast&>(u).release(), boost::move(u.get_deleter())) + : ptr_(const_cast&>(u).release(), boost::interprocess::move(u.get_deleter())) {} //!Effects: If get() == 0 there are no effects. Otherwise get_deleter()(get()). @@ -210,10 +208,10 @@ class unique_ptr //!Returns: *this. //! //!Throws: nothing. - unique_ptr& operator=(BOOST_RV_REF(unique_ptr) u) + unique_ptr& operator=(BOOST_INTERPROCESS_RV_REF(unique_ptr) u) { reset(u.release()); - ptr_.second() = boost::move(u.get_deleter()); + ptr_.second() = boost::interprocess::move(u.get_deleter()); return *this; } @@ -232,10 +230,10 @@ class unique_ptr //! //!Throws: nothing. template - unique_ptr& operator=(BOOST_RV_REF_BEG unique_ptr BOOST_RV_REF_END u) + unique_ptr& operator=(BOOST_INTERPROCESS_RV_REF_2_TEMPL_ARGS(unique_ptr, U, E) u) { reset(u.release()); - ptr_.second() = boost::move(u.get_deleter()); + ptr_.second() = boost::interprocess::move(u.get_deleter()); return *this; } @@ -248,7 +246,7 @@ class unique_ptr //!Returns: *this. //! //!Throws: nothing. - unique_ptr& operator=(nullptr_t) + unique_ptr& operator=(int nat::*) { reset(); return *this; @@ -257,7 +255,7 @@ class unique_ptr //!Requires: get() != 0. //!Returns: *get(). //!Throws: nothing. - typename ipcdetail::add_reference::type operator*() const + typename detail::add_reference::type operator*() const { return *ptr_.first(); } //!Requires: get() != 0. @@ -274,21 +272,21 @@ class unique_ptr //!Returns: A reference to the stored deleter. //! //!Throws: nothing. - deleter_reference get_deleter() + deleter_reference get_deleter() { return ptr_.second(); } //!Returns: A const reference to the stored deleter. //! //!Throws: nothing. - deleter_const_reference get_deleter() const + deleter_const_reference get_deleter() const { return ptr_.second(); } //!Returns: An unspecified value that, when used in boolean //!contexts, is equivalent to get() != 0. //! //!Throws: nothing. - operator int nat::*() const - { return ptr_.first() ? &nat::for_bool : 0; } + operator int nat::*() const + { return ptr_.first() ? &nat::for_bool_ : 0; } //!Postcondition: get() == 0. //! @@ -327,12 +325,12 @@ class unique_ptr /// @cond private: boost::compressed_pair ptr_; - BOOST_MOVABLE_BUT_NOT_COPYABLE(unique_ptr) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(unique_ptr) template unique_ptr(unique_ptr&); - template unique_ptr(U&, typename ipcdetail::unique_ptr_error::type = 0); - + template unique_ptr(U&, typename detail::unique_ptr_error::type = 0); + template unique_ptr& operator=(unique_ptr&); - template typename ipcdetail::unique_ptr_error::type operator=(U&); + template typename detail::unique_ptr_error::type operator=(U&); /// @endcond }; /* @@ -340,12 +338,12 @@ template class unique_ptr { struct nat {int for_bool_;}; - typedef typename ipcdetail::add_reference::type deleter_reference; - typedef typename ipcdetail::add_reference::type deleter_const_reference; + typedef typename detail::add_reference::type deleter_reference; + typedef typename detail::add_reference::type deleter_const_reference; public: typedef T element_type; typedef D deleter_type; - typedef typename ipcdetail::pointer_type::type pointer; + typedef typename detail::pointer_type::type pointer; // constructors unique_ptr() : ptr_(pointer()) {} @@ -353,7 +351,7 @@ class unique_ptr unique_ptr(pointer p, typename if_< boost::is_reference, D, - typename ipcdetail::add_reference::type>::type d) + typename detail::add_reference::type>::type d) : ptr_(p, d) {} unique_ptr(const unique_ptr& u) : ptr_(const_cast(u).release(), u.get_deleter()) {} @@ -376,7 +374,7 @@ class unique_ptr } // observers - typename ipcdetail::add_reference::type operator[](std::size_t i) const {return ptr_.first()[i];} + typename detail::add_reference::type operator[](std::size_t i) const {return ptr_.first()[i];} pointer get() const {return ptr_.first();} deleter_reference get_deleter() {return ptr_.second();} deleter_const_reference get_deleter() const {return ptr_.second();} @@ -408,22 +406,22 @@ class unique_ptr typename boost::enable_if >::type* = 0); unique_ptr(unique_ptr&); - template unique_ptr(U&, typename ipcdetail::unique_ptr_error::type = 0); + template unique_ptr(U&, typename detail::unique_ptr_error::type = 0); unique_ptr& operator=(unique_ptr&); - template typename ipcdetail::unique_ptr_error::type operator=(U&); + template typename detail::unique_ptr_error::type operator=(U&); }; template class unique_ptr { struct nat {int for_bool_;}; - typedef typename ipcdetail::add_reference::type deleter_reference; - typedef typename ipcdetail::add_reference::type deleter_const_reference; + typedef typename detail::add_reference::type deleter_reference; + typedef typename detail::add_reference::type deleter_const_reference; public: typedef T element_type; typedef D deleter_type; - typedef typename ipcdetail::pointer_type::type pointer; + typedef typename detail::pointer_type::type pointer; static const std::size_t size = N; // constructors @@ -432,7 +430,7 @@ class unique_ptr unique_ptr(pointer p, typename if_< boost::is_reference, D, - typename ipcdetail::add_reference::type>::type d) + typename detail::add_reference::type>::type d) : ptr_(p, d) {} unique_ptr(const unique_ptr& u) : ptr_(const_cast(u).release(), u.get_deleter()) {} @@ -455,11 +453,11 @@ class unique_ptr } // observers - typename ipcdetail::add_reference::type operator[](std::size_t i) const {return ptr_.first()[i];} + typename detail::add_reference::type operator[](std::size_t i) const {return ptr_.first()[i];} pointer get() const {return ptr_.first();} deleter_reference get_deleter() {return ptr_.second();} deleter_const_reference get_deleter() const {return ptr_.second();} - operator int nat::*() const {return ptr_.first() ? &nat::for_bool : 0;} + operator int nat::*() const {return ptr_.first() ? &nat::for_bool_ : 0;} // modifiers pointer release() @@ -487,10 +485,10 @@ class unique_ptr typename boost::enable_if >::type* = 0); unique_ptr(unique_ptr&); - template unique_ptr(U&, typename ipcdetail::unique_ptr_error::type = 0); + template unique_ptr(U&, typename detail::unique_ptr_error::type = 0); unique_ptr& operator=(unique_ptr&); - template typename ipcdetail::unique_ptr_error::type operator=(U&); + template typename detail::unique_ptr_error::type operator=(U&); }; */ template inline @@ -541,7 +539,7 @@ template inline typename managed_unique_ptr::type make_managed_unique_ptr(T *constructed_object, ManagedMemory &managed_memory) { - return typename managed_unique_ptr::type + return typename managed_unique_ptr::type (constructed_object, managed_memory.template get_deleter()); } diff --git a/utils/boost_idb/boost/interprocess/smart_ptr/weak_ptr.hpp b/utils/boost_idb/boost/interprocess/smart_ptr/weak_ptr.hpp index 99c8a631..9229bd5e 100644 --- a/utils/boost_idb/boost/interprocess/smart_ptr/weak_ptr.hpp +++ b/utils/boost_idb/boost/interprocess/smart_ptr/weak_ptr.hpp @@ -3,7 +3,7 @@ // This file is the adaptation for Interprocess of boost/weak_ptr.hpp // // (C) Copyright Peter Dimov 2001, 2002, 2003 -// (C) Copyright Ion Gaztanaga 2006-2012. +// (C) Copyright Ion Gaztanaga 2006-2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) @@ -22,7 +22,7 @@ #include #include #include -#include +#include //!\file //!Describes the smart pointer weak_ptr. @@ -31,7 +31,7 @@ namespace boost{ namespace interprocess{ //!The weak_ptr class template stores a "weak reference" to an object -//!that's already managed by a shared_ptr. To access the object, a weak_ptr +//!that's already managed by a shared_ptr. To access the object, a weak_ptr //!can be converted to a shared_ptr using the shared_ptr constructor or the //!member function lock. When the last shared_ptr to the object goes away //!and the object is deleted, the attempt to obtain a shared_ptr from the @@ -54,12 +54,11 @@ class weak_ptr private: // Borland 5.5.1 specific workarounds typedef weak_ptr this_type; - typedef typename boost::intrusive:: - pointer_traits::template - rebind_pointer::type pointer; - typedef typename ipcdetail::add_reference + typedef typename boost::pointer_to_other + ::type pointer; + typedef typename detail::add_reference ::type reference; - typedef typename ipcdetail::add_reference + typedef typename detail::add_reference ::type const_reference; /// @endcond @@ -99,11 +98,11 @@ class weak_ptr template weak_ptr(weak_ptr const & r) : m_pn(r.m_pn) // never throws - { + { //Construct a temporary shared_ptr so that nobody //can destroy the value while constructing this const shared_ptr &ref = r.lock(); - m_pn.set_pointer(ref.get()); + m_pn.set_pointer(ref.get()); } //!Effects: If r is empty, constructs an empty weak_ptr; otherwise, @@ -126,7 +125,7 @@ class weak_ptr //!implied guarantees) via different means, without creating a temporary. template weak_ptr & operator=(weak_ptr const & r) // never throws - { + { //Construct a temporary shared_ptr so that nobody //can destroy the value while constructing this const shared_ptr &ref = r.lock(); @@ -174,7 +173,7 @@ class weak_ptr //!testing purposes, not for production code. long use_count() const // never throws { return m_pn.use_count(); } - + //!Returns: Returns: use_count() == 0. //! //!Throws: nothing. @@ -193,15 +192,15 @@ class weak_ptr //! //!Throws: nothing. void swap(this_type & other) // never throws - { ipcdetail::do_swap(m_pn, other.m_pn); } + { detail::do_swap(m_pn, other.m_pn); } /// @cond - template + template bool _internal_less(weak_ptr const & rhs) const { return m_pn < rhs.m_pn; } - + template - void _internal_assign(const ipcdetail::shared_count & pn2) + void _internal_assign(const detail::shared_count & pn2) { m_pn = pn2; @@ -212,11 +211,11 @@ class weak_ptr template friend class shared_ptr; template friend class weak_ptr; - ipcdetail::weak_count m_pn; // reference counter + detail::weak_count m_pn; // reference counter /// @endcond }; // weak_ptr -template inline +template inline bool operator<(weak_ptr const & a, weak_ptr const & b) { return a._internal_less(b); } diff --git a/utils/boost_idb/boost/interprocess/streams/bufferstream.hpp b/utils/boost_idb/boost/interprocess/streams/bufferstream.hpp index 404880d2..a04184af 100644 --- a/utils/boost_idb/boost/interprocess/streams/bufferstream.hpp +++ b/utils/boost_idb/boost/interprocess/streams/bufferstream.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,7 +8,7 @@ // ////////////////////////////////////////////////////////////////////////////// // -// This file comes from SGI's sstream file. Modified by Ion Gaztanaga 2005-2012. +// This file comes from SGI's sstream file. Modified by Ion Gaztanaga 2005. // Changed internal SGI string to a buffer. Added efficient // internal buffer get/set/swap functions, so that we can obtain/establish the // internal buffer without any reallocation or copy. Kill those temporaries! @@ -42,7 +42,7 @@ #include #include #include -#include // char traits +#include // char traits #include // ptrdiff_t #include #include @@ -53,7 +53,7 @@ namespace boost { namespace interprocess { //!a basic_xbufferstream. The elements are transmitted from a to a fixed //!size buffer template -class basic_bufferbuf +class basic_bufferbuf : public std::basic_streambuf { public: @@ -74,24 +74,24 @@ class basic_bufferbuf //!Constructor. Assigns formatting buffer. //!Does not throw. - explicit basic_bufferbuf(CharT *buf, std::size_t length, + explicit basic_bufferbuf(CharT *buffer, std::size_t length, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) - : base_t(), m_mode(mode), m_buffer(buf), m_length(length) + : base_t(), m_mode(mode), m_buffer(buffer), m_length(length) { this->set_pointers(); } virtual ~basic_bufferbuf(){} public: - //!Returns the pointer and size of the internal buffer. + //!Returns the pointer and size of the internal buffer. //!Does not throw. std::pair buffer() const { return std::pair(m_buffer, m_length); } //!Sets the underlying buffer to a new value //!Does not throw. - void buffer(CharT *buf, std::size_t length) - { m_buffer = buf; m_length = length; this->set_pointers(); } + void buffer(CharT *buffer, std::size_t length) + { m_buffer = buffer; m_length = length; this->set_pointers(); } /// @cond private: @@ -172,13 +172,13 @@ class basic_bufferbuf } virtual pos_type seekoff(off_type off, std::ios_base::seekdir dir, - std::ios_base::openmode mode + std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) { bool in = false; bool out = false; - - const std::ios_base::openmode inout = + + const std::ios_base::openmode inout = std::ios_base::in | std::ios_base::out; if((mode & inout) == inout) { @@ -205,7 +205,7 @@ class basic_bufferbuf newoff = static_cast(m_length); break; case std::ios_base::cur: - newoff = in ? static_cast(this->gptr() - this->eback()) + newoff = in ? static_cast(this->gptr() - this->eback()) : static_cast(this->pptr() - this->pbase()); break; default: @@ -237,7 +237,7 @@ class basic_bufferbuf return pos_type(off); } - virtual pos_type seekpos(pos_type pos, std::ios_base::openmode mode + virtual pos_type seekpos(pos_type pos, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) { return seekoff(pos - pos_type(off_type(0)), std::ios_base::beg, mode); } @@ -251,11 +251,8 @@ class basic_bufferbuf //!A basic_istream class that uses a fixed size character buffer //!as its formatting buffer. template -class basic_ibufferstream : - /// @cond - private basic_bufferbuf, - /// @endcond - public std::basic_istream +class basic_ibufferstream + : public std::basic_istream { public: // Typedefs typedef typename std::basic_ios @@ -265,40 +262,24 @@ class basic_ibufferstream : typedef typename std::basic_ios::off_type off_type; typedef typename std::basic_ios::traits_type traits_type; - /// @cond private: - typedef basic_bufferbuf bufferbuf_t; - typedef std::basic_ios basic_ios_t; - typedef std::basic_istream base_t; - bufferbuf_t & get_buf() { return *this; } - const bufferbuf_t & get_buf() const{ return *this; } - /// @endcond + typedef std::basic_ios basic_ios_t; + typedef std::basic_istream base_t; public: //!Constructor. //!Does not throw. basic_ibufferstream(std::ios_base::openmode mode = std::ios_base::in) - : //basic_ios_t() is called first (lefting it uninitialized) as it's a - //virtual base of basic_istream. The class will be initialized when - //basic_istream is constructed calling basic_ios_t::init(). - //As bufferbuf_t's constructor does not throw there is no risk of - //calling the basic_ios_t's destructor without calling basic_ios_t::init() - bufferbuf_t(mode | std::ios_base::in) - , base_t(&get_buf()) - {} + : basic_ios_t(), base_t(0), m_buf(mode | std::ios_base::in) + { basic_ios_t::init(&m_buf); } //!Constructor. Assigns formatting buffer. //!Does not throw. - basic_ibufferstream(const CharT *buf, std::size_t length, - std::ios_base::openmode mode = std::ios_base::in) - : //basic_ios_t() is called first (lefting it uninitialized) as it's a - //virtual base of basic_istream. The class will be initialized when - //basic_istream is constructed calling basic_ios_t::init(). - //As bufferbuf_t's constructor does not throw there is no risk of - //calling the basic_ios_t's destructor without calling basic_ios_t::init() - bufferbuf_t(const_cast(buf), length, mode | std::ios_base::in) - , base_t(&get_buf()) - {} + basic_ibufferstream(const CharT *buffer, std::size_t length, + std::ios_base::openmode mode = std::ios_base::in) + : basic_ios_t(), base_t(0), + m_buf(const_cast(buffer), length, mode | std::ios_base::in) + { basic_ios_t::init(&m_buf); } ~basic_ibufferstream(){}; @@ -306,27 +287,29 @@ class basic_ibufferstream : //!Returns the address of the stored //!stream buffer. basic_bufferbuf* rdbuf() const - { return const_cast*>(&get_buf()); } + { return const_cast*>(&m_buf); } - //!Returns the pointer and size of the internal buffer. + //!Returns the pointer and size of the internal buffer. //!Does not throw. std::pair buffer() const - { return get_buf().buffer(); } + { return m_buf.buffer(); } - //!Sets the underlying buffer to a new value. Resets + //!Sets the underlying buffer to a new value. Resets //!stream position. Does not throw. - void buffer(const CharT *buf, std::size_t length) - { get_buf().buffer(const_cast(buf), length); } + void buffer(const CharT *buffer, std::size_t length) + { m_buf.buffer(const_cast(buffer), length); } + + /// @cond + private: + basic_bufferbuf m_buf; + /// @endcond }; //!A basic_ostream class that uses a fixed size character buffer //!as its formatting buffer. template -class basic_obufferstream : - /// @cond - private basic_bufferbuf, - /// @endcond - public std::basic_ostream +class basic_obufferstream + : public std::basic_ostream { public: typedef typename std::basic_ios @@ -338,38 +321,23 @@ class basic_obufferstream : /// @cond private: - typedef basic_bufferbuf bufferbuf_t; typedef std::basic_ios basic_ios_t; typedef std::basic_ostream base_t; - bufferbuf_t & get_buf() { return *this; } - const bufferbuf_t & get_buf() const{ return *this; } /// @endcond - public: //!Constructor. //!Does not throw. basic_obufferstream(std::ios_base::openmode mode = std::ios_base::out) - : //basic_ios_t() is called first (lefting it uninitialized) as it's a - //virtual base of basic_istream. The class will be initialized when - //basic_istream is constructed calling basic_ios_t::init(). - //As bufferbuf_t's constructor does not throw there is no risk of - //calling the basic_ios_t's destructor without calling basic_ios_t::init() - bufferbuf_t(mode | std::ios_base::out) - , base_t(&get_buf()) - {} + : basic_ios_t(), base_t(0), m_buf(mode | std::ios_base::out) + { basic_ios_t::init(&m_buf); } //!Constructor. Assigns formatting buffer. //!Does not throw. - basic_obufferstream(CharT *buf, std::size_t length, + basic_obufferstream(CharT *buffer, std::size_t length, std::ios_base::openmode mode = std::ios_base::out) - : //basic_ios_t() is called first (lefting it uninitialized) as it's a - //virtual base of basic_istream. The class will be initialized when - //basic_istream is constructed calling basic_ios_t::init(). - //As bufferbuf_t's constructor does not throw there is no risk of - //calling the basic_ios_t's destructor without calling basic_ios_t::init() - bufferbuf_t(buf, length, mode | std::ios_base::out) - , base_t(&get_buf()) - {} + : basic_ios_t(), base_t(0), + m_buf(buffer, length, mode | std::ios_base::out) + { basic_ios_t::init(&m_buf); } ~basic_obufferstream(){} @@ -377,28 +345,31 @@ class basic_obufferstream : //!Returns the address of the stored //!stream buffer. basic_bufferbuf* rdbuf() const - { return const_cast*>(&get_buf()); } + { return const_cast*>(&m_buf); } - //!Returns the pointer and size of the internal buffer. + //!Returns the pointer and size of the internal buffer. //!Does not throw. std::pair buffer() const - { return get_buf().buffer(); } + { return m_buf.buffer(); } - //!Sets the underlying buffer to a new value. Resets + //!Sets the underlying buffer to a new value. Resets //!stream position. Does not throw. - void buffer(CharT *buf, std::size_t length) - { get_buf().buffer(buf, length); } + void buffer(CharT *buffer, std::size_t length) + { m_buf.buffer(buffer, length); } + + /// @cond + private: + basic_bufferbuf m_buf; + /// @endcond }; //!A basic_iostream class that uses a fixed size character buffer //!as its formatting buffer. template -class basic_bufferstream : - /// @cond - private basic_bufferbuf, - /// @endcond - public std::basic_iostream +class basic_bufferstream + : public std::basic_iostream + { public: // Typedefs typedef typename std::basic_ios @@ -410,40 +381,25 @@ class basic_bufferstream : /// @cond private: - typedef basic_bufferbuf bufferbuf_t; - typedef std::basic_ios basic_ios_t; - typedef std::basic_iostream base_t; - bufferbuf_t & get_buf() { return *this; } - const bufferbuf_t & get_buf() const{ return *this; } + typedef std::basic_ios basic_ios_t; + typedef std::basic_iostream base_t; /// @endcond public: //!Constructor. //!Does not throw. - basic_bufferstream(std::ios_base::openmode mode + basic_bufferstream(std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) - : //basic_ios_t() is called first (lefting it uninitialized) as it's a - //virtual base of basic_istream. The class will be initialized when - //basic_istream is constructed calling basic_ios_t::init(). - //As bufferbuf_t's constructor does not throw there is no risk of - //calling the basic_ios_t's destructor without calling basic_ios_t::init() - bufferbuf_t(mode) - , base_t(&get_buf()) - {} + : basic_ios_t(), base_t(0), m_buf(mode) + { basic_ios_t::init(&m_buf); } //!Constructor. Assigns formatting buffer. //!Does not throw. - basic_bufferstream(CharT *buf, std::size_t length, + basic_bufferstream(CharT *buffer, std::size_t length, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) - : //basic_ios_t() is called first (lefting it uninitialized) as it's a - //virtual base of basic_istream. The class will be initialized when - //basic_istream is constructed calling basic_ios_t::init(). - //As bufferbuf_t's constructor does not throw there is no risk of - //calling the basic_ios_t's destructor without calling basic_ios_t::init() - bufferbuf_t(buf, length, mode) - , base_t(&get_buf()) - {} + : basic_ios_t(), base_t(0), m_buf(buffer, length, mode) + { basic_ios_t::init(&m_buf); } ~basic_bufferstream(){} @@ -451,17 +407,22 @@ class basic_bufferstream : //!Returns the address of the stored //!stream buffer. basic_bufferbuf* rdbuf() const - { return const_cast*>(&get_buf()); } + { return const_cast*>(&m_buf); } - //!Returns the pointer and size of the internal buffer. + //!Returns the pointer and size of the internal buffer. //!Does not throw. std::pair buffer() const - { return get_buf().buffer(); } + { return m_buf.buffer(); } - //!Sets the underlying buffer to a new value. Resets + //!Sets the underlying buffer to a new value. Resets //!stream position. Does not throw. - void buffer(CharT *buf, std::size_t length) - { get_buf().buffer(buf, length); } + void buffer(CharT *buffer, std::size_t length) + { m_buf.buffer(buffer, length); } + + /// @cond + private: + basic_bufferbuf m_buf; + /// @endcond }; //Some typedefs to simplify usage diff --git a/utils/boost_idb/boost/interprocess/streams/vectorstream.hpp b/utils/boost_idb/boost/interprocess/streams/vectorstream.hpp index 25dc5db5..fa16c8ae 100644 --- a/utils/boost_idb/boost/interprocess/streams/vectorstream.hpp +++ b/utils/boost_idb/boost/interprocess/streams/vectorstream.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,7 +8,7 @@ // ////////////////////////////////////////////////////////////////////////////// // -// This file comes from SGI's sstream file. Modified by Ion Gaztanaga 2005-2012. +// This file comes from SGI's sstream file. Modified by Ion Gaztanaga 2005. // Changed internal SGI string to a generic, templatized vector. Added efficient // internal buffer get/set/swap functions, so that we can obtain/establish the // internal buffer without any reallocation or copy. Kill those temporaries! @@ -30,7 +30,7 @@ //!This file defines basic_vectorbuf, basic_ivectorstream, //!basic_ovectorstream, and basic_vectorstreamclasses. These classes //!represent streamsbufs and streams whose sources or destinations are -//!STL-like vectors that can be swapped with external vectors to avoid +//!STL-like vectors that can be swapped with external vectors to avoid //!unnecessary allocations/copies. #ifndef BOOST_INTERPROCESS_VECTORSTREAM_HPP @@ -43,7 +43,7 @@ #include #include #include -#include // char traits +#include // char traits #include // ptrdiff_t #include #include @@ -51,9 +51,9 @@ namespace boost { namespace interprocess { //!A streambuf class that controls the transmission of elements to and from -//!a basic_ivectorstream, basic_ovectorstream or basic_vectorstream. +//!a basic_ivectorstream, basic_ovectorstream or basic_vectorstream. //!It holds a character vector specified by CharVector template parameter -//!as its formatting buffer. The vector must have contiguous storage, like +//!as its formatting buffer. The vector must have contiguous storage, like //!std::vector, boost::interprocess::vector or boost::interprocess::basic_string template class basic_vectorbuf @@ -92,13 +92,15 @@ class basic_vectorbuf : base_t(), m_mode(mode), m_vect(param) { this->initialize_pointers(); } + virtual ~basic_vectorbuf(){} + public: - //!Swaps the underlying vector with the passed vector. + //!Swaps the underlying vector with the passed vector. //!This function resets the read/write position in the stream. //!Does not throw. void swap_vector(vector_type &vect) - { + { if (this->m_mode & std::ios_base::out){ //Update high water if necessary //And resize vector to remove extra size @@ -116,8 +118,8 @@ class basic_vectorbuf //!Returns a const reference to the internal vector. //!Does not throw. - const vector_type &vector() const - { + const vector_type &vector() const + { if (this->m_mode & std::ios_base::out){ if (mp_high_water < base_t::pptr()){ //Restore the vector's size if necessary @@ -135,13 +137,13 @@ class basic_vectorbuf const_cast(this)->base_t::pbump(old_pos); } } - return m_vect; + return m_vect; } //!Preallocates memory from the internal vector. //!Resets the stream to the first position. //!Throws if the internals vector's memory allocation throws. - void reserve(typename vector_type::size_type size) + void reserve(typename vector_type::size_type size) { if (this->m_mode & std::ios_base::out && size > m_vect.size()){ typename vector_type::difference_type write_pos = base_t::pptr() - base_t::pbase(); @@ -280,7 +282,7 @@ class basic_vectorbuf } virtual pos_type seekoff(off_type off, std::ios_base::seekdir dir, - std::ios_base::openmode mode + std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) { //Get seek mode @@ -323,7 +325,7 @@ class basic_vectorbuf newoff = limit; break; case std::ios_base::cur: - newoff = in ? static_cast(this->gptr() - this->eback()) + newoff = in ? static_cast(this->gptr() - this->eback()) : static_cast(this->pptr() - this->pbase()); break; default: @@ -348,7 +350,7 @@ class basic_vectorbuf return pos_type(newoff); } - virtual pos_type seekpos(pos_type pos, std::ios_base::openmode mode + virtual pos_type seekpos(pos_type pos, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) { return seekoff(pos - pos_type(off_type(0)), std::ios_base::beg, mode); } @@ -365,10 +367,10 @@ class basic_vectorbuf //!boost::interprocess::basic_string template class basic_ivectorstream - : public std::basic_istream /// @cond - , private basic_vectorbuf + : private basic_vectorbuf /// @endcond + , public std::basic_istream { public: typedef CharVector vector_type; @@ -382,62 +384,56 @@ class basic_ivectorstream /// @cond private: typedef basic_vectorbuf vectorbuf_t; - typedef std::basic_ios basic_ios_t; typedef std::basic_istream base_t; - vectorbuf_t & get_buf() { return *this; } - const vectorbuf_t & get_buf() const{ return *this; } + vectorbuf_t & m_buf() { return *this; } + const vectorbuf_t & m_buf() const{ return *this; } /// @endcond public: - //!Constructor. Throws if vector_type default //!constructor throws. basic_ivectorstream(std::ios_base::openmode mode = std::ios_base::in) - : base_t(0) //Initializes first the base class to safely init the virtual basic_ios base - //(via basic_ios::init() call in base_t's constructor) without the risk of a - //previous throwing vectorbuf constructor. Set the streambuf after risk has gone. - , vectorbuf_t(mode | std::ios_base::in) - { this->base_t::rdbuf(&get_buf()); } + : vectorbuf_t(mode | std::ios_base::in), base_t(&m_buf()) + {} //!Constructor. Throws if vector_type(const VectorParameter ¶m) //!throws. template basic_ivectorstream(const VectorParameter ¶m, std::ios_base::openmode mode = std::ios_base::in) - : vectorbuf_t(param, mode | std::ios_base::in) - //basic_ios_t() is constructed uninitialized as virtual base - //and initialized inside base_t calling basic_ios::init() - , base_t(&get_buf()) + : vectorbuf_t(param, mode | std::ios_base::in), base_t(&m_buf()) {} + ~basic_ivectorstream(){}; + public: //!Returns the address of the stored //!stream buffer. basic_vectorbuf* rdbuf() const - { return const_cast*>(&get_buf()); } + { return const_cast*>(&m_buf()); } - //!Swaps the underlying vector with the passed vector. + //!Swaps the underlying vector with the passed vector. //!This function resets the read position in the stream. //!Does not throw. void swap_vector(vector_type &vect) - { get_buf().swap_vector(vect); } + { m_buf().swap_vector(vect); } //!Returns a const reference to the internal vector. //!Does not throw. - const vector_type &vector() const - { return get_buf().vector(); } + const vector_type &vector() const + { return m_buf().vector(); } //!Calls reserve() method of the internal vector. //!Resets the stream to the first position. //!Throws if the internals vector's reserve throws. - void reserve(typename vector_type::size_type size) - { get_buf().reserve(size); } + void reserve(typename vector_type::size_type size) + { m_buf().reserve(size); } //!Calls clear() method of the internal vector. //!Resets the stream to the first position. - void clear() - { get_buf().clear(); } + void clear() + { m_buf().clear(); } }; //!A basic_ostream class that holds a character vector specified by CharVector @@ -446,10 +442,10 @@ class basic_ivectorstream //!boost::interprocess::basic_string template class basic_ovectorstream - : public std::basic_ostream /// @cond - , private basic_vectorbuf + : private basic_vectorbuf /// @endcond + , public std::basic_ostream { public: typedef CharVector vector_type; @@ -463,58 +459,54 @@ class basic_ovectorstream /// @cond private: typedef basic_vectorbuf vectorbuf_t; - typedef std::basic_ios basic_ios_t; typedef std::basic_ostream base_t; - vectorbuf_t & get_buf() { return *this; } - const vectorbuf_t & get_buf()const { return *this; } + vectorbuf_t & m_buf() { return *this; } + const vectorbuf_t & m_buf()const { return *this; } /// @endcond public: //!Constructor. Throws if vector_type default //!constructor throws. basic_ovectorstream(std::ios_base::openmode mode = std::ios_base::out) - : base_t(0) //Initializes first the base class to safely init the virtual basic_ios base - //(via basic_ios::init() call in base_t's constructor) without the risk of a - //previous throwing vectorbuf constructor. Set the streambuf after risk has gone. - , vectorbuf_t(mode | std::ios_base::out) - { this->base_t::rdbuf(&get_buf()); } + : vectorbuf_t(mode | std::ios_base::out), base_t(&m_buf()) + {} //!Constructor. Throws if vector_type(const VectorParameter ¶m) //!throws. template basic_ovectorstream(const VectorParameter ¶m, std::ios_base::openmode mode = std::ios_base::out) - : base_t(0) //Initializes first the base class to safely init the virtual basic_ios base - //(via basic_ios::init() call in base_t's constructor) without the risk of a - //previous throwing vectorbuf constructor. Set the streambuf after risk has gone. - , vectorbuf_t(param, mode | std::ios_base::out) - { this->base_t::rdbuf(&get_buf()); } + : vectorbuf_t(param, mode | std::ios_base::out), base_t(&m_buf()) + {} + + ~basic_ovectorstream(){} public: //!Returns the address of the stored //!stream buffer. basic_vectorbuf* rdbuf() const - { return const_cast*>(&get_buf()); } + { return const_cast*>(&m_buf()); } - //!Swaps the underlying vector with the passed vector. + //!Swaps the underlying vector with the passed vector. //!This function resets the write position in the stream. //!Does not throw. void swap_vector(vector_type &vect) - { get_buf().swap_vector(vect); } + { m_buf().swap_vector(vect); } //!Returns a const reference to the internal vector. //!Does not throw. - const vector_type &vector() const - { return get_buf().vector(); } + const vector_type &vector() const + { return m_buf().vector(); } //!Calls reserve() method of the internal vector. //!Resets the stream to the first position. //!Throws if the internals vector's reserve throws. - void reserve(typename vector_type::size_type size) - { get_buf().reserve(size); } + void reserve(typename vector_type::size_type size) + { m_buf().reserve(size); } }; + //!A basic_iostream class that holds a character vector specified by CharVector //!template parameter as its formatting buffer. The vector must have //!contiguous storage, like std::vector, boost::interprocess::vector or @@ -522,9 +514,7 @@ class basic_ovectorstream template class basic_vectorstream : public std::basic_iostream - /// @cond - , private basic_vectorbuf - /// @endcond + { public: typedef CharVector vector_type; @@ -537,62 +527,59 @@ class basic_vectorstream /// @cond private: - typedef basic_vectorbuf vectorbuf_t; - typedef std::basic_ios basic_ios_t; - typedef std::basic_iostream base_t; - - vectorbuf_t & get_buf() { return *this; } - const vectorbuf_t & get_buf() const{ return *this; } + typedef std::basic_ios basic_ios_t; + typedef std::basic_iostream base_t; /// @endcond public: //!Constructor. Throws if vector_type default //!constructor throws. - basic_vectorstream(std::ios_base::openmode mode + basic_vectorstream(std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) - : base_t(0) //Initializes first the base class to safely init the virtual basic_ios base - //(via basic_ios::init() call in base_t's constructor) without the risk of a - //previous throwing vectorbuf constructor. Set the streambuf after risk has gone. - , vectorbuf_t(mode) - { this->base_t::rdbuf(&get_buf()); } + : basic_ios_t(), base_t(0), m_buf(mode) + { basic_ios_t::init(&m_buf); } //!Constructor. Throws if vector_type(const VectorParameter ¶m) //!throws. template basic_vectorstream(const VectorParameter ¶m, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) - : base_t(0) //Initializes first the base class to safely init the virtual basic_ios base - //(via basic_ios::init() call in base_t's constructor) without the risk of a - //previous throwing vectorbuf constructor. Set the streambuf after risk has gone. - , vectorbuf_t(param, mode) - { this->base_t::rdbuf(&get_buf()); } + : basic_ios_t(), base_t(0), m_buf(param, mode) + { basic_ios_t::init(&m_buf); } + + ~basic_vectorstream(){} public: //Returns the address of the stored stream buffer. basic_vectorbuf* rdbuf() const - { return const_cast*>(&get_buf()); } + { return const_cast*>(&m_buf); } - //!Swaps the underlying vector with the passed vector. + //!Swaps the underlying vector with the passed vector. //!This function resets the read/write position in the stream. //!Does not throw. void swap_vector(vector_type &vect) - { get_buf().swap_vector(vect); } + { m_buf.swap_vector(vect); } //!Returns a const reference to the internal vector. //!Does not throw. - const vector_type &vector() const - { return get_buf().vector(); } + const vector_type &vector() const + { return m_buf.vector(); } //!Calls reserve() method of the internal vector. //!Resets the stream to the first position. //!Throws if the internals vector's reserve throws. - void reserve(typename vector_type::size_type size) - { get_buf().reserve(size); } + void reserve(typename vector_type::size_type size) + { m_buf.reserve(size); } //!Calls clear() method of the internal vector. //!Resets the stream to the first position. - void clear() - { get_buf().clear(); } + void clear() + { m_buf.clear(); } + + /// @cond + private: + basic_vectorbuf m_buf; + /// @endcond }; //Some typedefs to simplify usage diff --git a/utils/boost_idb/boost/interprocess/sync/detail/condition_algorithm_8a.hpp b/utils/boost_idb/boost/interprocess/sync/detail/condition_algorithm_8a.hpp deleted file mode 100644 index 09643b40..00000000 --- a/utils/boost_idb/boost/interprocess/sync/detail/condition_algorithm_8a.hpp +++ /dev/null @@ -1,394 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_CONDITION_ALGORITHM_8A_HPP -#define BOOST_INTERPROCESS_DETAIL_CONDITION_ALGORITHM_8A_HPP - -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -// -// Condition variable algorithm taken from pthreads-win32 discussion. -// -// The algorithm was developed by Alexander Terekhov in colaboration with -// Louis Thomas. -// -// Algorithm 8a / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ALL -// -// semBlockLock - bin.semaphore -// semBlockQueue - semaphore -// mtxExternal - mutex or CS -// mtxUnblockLock - mutex or CS -// nWaitersGone - int -// nWaitersBlocked - int -// nWaitersToUnblock - int -// -// wait( timeout ) { -// -// [auto: register int result ] // error checking omitted -// [auto: register int nSignalsWasLeft ] -// [auto: register int nWaitersWasGone ] -// -// sem_wait( semBlockLock ); -// nWaitersBlocked++; -// sem_post( semBlockLock ); -// -// unlock( mtxExternal ); -// bTimedOut = sem_wait( semBlockQueue,timeout ); -// -// lock( mtxUnblockLock ); -// if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { -// if ( bTimedOut ) { // timeout (or canceled) -// if ( 0 != nWaitersBlocked ) { -// nWaitersBlocked--; -// } -// else { -// nWaitersGone++; // count spurious wakeups. -// } -// } -// if ( 0 == --nWaitersToUnblock ) { -// if ( 0 != nWaitersBlocked ) { -// sem_post( semBlockLock ); // open the gate. -// nSignalsWasLeft = 0; // do not open the gate -// // below again. -// } -// else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { -// nWaitersGone = 0; -// } -// } -// } -// else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or -// // spurious semaphore :-) -// sem_wait( semBlockLock ); -// nWaitersBlocked -= nWaitersGone; // something is going on here -// // - test of timeouts? :-) -// sem_post( semBlockLock ); -// nWaitersGone = 0; -// } -// unlock( mtxUnblockLock ); -// -// if ( 1 == nSignalsWasLeft ) { -// if ( 0 != nWaitersWasGone ) { -// // sem_adjust( semBlockQueue,-nWaitersWasGone ); -// while ( nWaitersWasGone-- ) { -// sem_wait( semBlockQueue ); // better now than spurious later -// } -// } sem_post( semBlockLock ); // open the gate -// } -// -// lock( mtxExternal ); -// -// return ( bTimedOut ) ? ETIMEOUT : 0; -// } -// -// signal(bAll) { -// -// [auto: register int result ] -// [auto: register int nSignalsToIssue] -// -// lock( mtxUnblockLock ); -// -// if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! -// if ( 0 == nWaitersBlocked ) { // NO-OP -// return unlock( mtxUnblockLock ); -// } -// if (bAll) { -// nWaitersToUnblock += nSignalsToIssue=nWaitersBlocked; -// nWaitersBlocked = 0; -// } -// else { -// nSignalsToIssue = 1; -// nWaitersToUnblock++; -// nWaitersBlocked--; -// } -// } -// else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! -// sem_wait( semBlockLock ); // close the gate -// if ( 0 != nWaitersGone ) { -// nWaitersBlocked -= nWaitersGone; -// nWaitersGone = 0; -// } -// if (bAll) { -// nSignalsToIssue = nWaitersToUnblock = nWaitersBlocked; -// nWaitersBlocked = 0; -// } -// else { -// nSignalsToIssue = nWaitersToUnblock = 1; -// nWaitersBlocked--; -// } -// } -// else { // NO-OP -// return unlock( mtxUnblockLock ); -// } -// -// unlock( mtxUnblockLock ); -// sem_post( semBlockQueue,nSignalsToIssue ); -// return result; -// } -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// - - -// Required interface for ConditionMembers -// class ConditionMembers -// { -// typedef implementation_defined semaphore_type; -// typedef implementation_defined mutex_type; -// typedef implementation_defined integer_type; -// -// integer_type &get_nwaiters_blocked() -// integer_type &get_nwaiters_gone() -// integer_type &get_nwaiters_to_unblock() -// semaphore_type &get_sem_block_queue() -// semaphore_type &get_sem_block_lock() -// mutex_type &get_mtx_unblock_lock() -// }; -// -// Must be initialized as following -// -// get_nwaiters_blocked() == 0 -// get_nwaiters_gone() == 0 -// get_nwaiters_to_unblock() == 0 -// get_sem_block_queue() == initial count 0 -// get_sem_block_lock() == initial count 1 -// get_mtx_unblock_lock() (unlocked) -// -template -class condition_algorithm_8a -{ - private: - condition_algorithm_8a(); - ~condition_algorithm_8a(); - condition_algorithm_8a(const condition_algorithm_8a &); - condition_algorithm_8a &operator=(const condition_algorithm_8a &); - - typedef typename ConditionMembers::semaphore_type semaphore_type; - typedef typename ConditionMembers::mutex_type mutex_type; - typedef typename ConditionMembers::integer_type integer_type; - - public: - template - static bool wait ( ConditionMembers &data, Lock &lock - , bool timeout_enabled, const boost::posix_time::ptime &abs_time); - static void signal(ConditionMembers &data, bool broadcast); -}; - -template -inline void condition_algorithm_8a::signal(ConditionMembers &data, bool broadcast) -{ - integer_type nsignals_to_issue; - - { - scoped_lock locker(data.get_mtx_unblock_lock()); - - if ( 0 != data.get_nwaiters_to_unblock() ) { // the gate is closed!!! - if ( 0 == data.get_nwaiters_blocked() ) { // NO-OP - //locker's destructor triggers data.get_mtx_unblock_lock().unlock() - return; - } - if (broadcast) { - data.get_nwaiters_to_unblock() += nsignals_to_issue = data.get_nwaiters_blocked(); - data.get_nwaiters_blocked() = 0; - } - else { - nsignals_to_issue = 1; - data.get_nwaiters_to_unblock()++; - data.get_nwaiters_blocked()--; - } - } - else if ( data.get_nwaiters_blocked() > data.get_nwaiters_gone() ) { // HARMLESS RACE CONDITION! - data.get_sem_block_lock().wait(); // close the gate - if ( 0 != data.get_nwaiters_gone() ) { - data.get_nwaiters_blocked() -= data.get_nwaiters_gone(); - data.get_nwaiters_gone() = 0; - } - if (broadcast) { - nsignals_to_issue = data.get_nwaiters_to_unblock() = data.get_nwaiters_blocked(); - data.get_nwaiters_blocked() = 0; - } - else { - nsignals_to_issue = data.get_nwaiters_to_unblock() = 1; - data.get_nwaiters_blocked()--; - } - } - else { // NO-OP - //locker's destructor triggers data.get_mtx_unblock_lock().unlock() - return; - } - //locker's destructor triggers data.get_mtx_unblock_lock().unlock() - } - data.get_sem_block_queue().post(nsignals_to_issue); -} - -template -template -inline bool condition_algorithm_8a::wait - ( ConditionMembers &data - , Lock &lock - , bool tout_enabled - , const boost::posix_time::ptime &abs_time - ) -{ - //Initialize to avoid warnings - integer_type nsignals_was_left = 0; - integer_type nwaiters_was_gone = 0; - - data.get_sem_block_lock().wait(); - ++data.get_nwaiters_blocked(); - data.get_sem_block_lock().post(); - - //Unlock external lock and program for relock - lock_inverter inverted_lock(lock); - scoped_lock > external_unlock(inverted_lock); - - bool bTimedOut = tout_enabled - ? !data.get_sem_block_queue().timed_wait(abs_time) - : (data.get_sem_block_queue().wait(), false); - - { - scoped_lock locker(data.get_mtx_unblock_lock()); - if ( 0 != (nsignals_was_left = data.get_nwaiters_to_unblock()) ) { - if ( bTimedOut ) { // timeout (or canceled) - if ( 0 != data.get_nwaiters_blocked() ) { - data.get_nwaiters_blocked()--; - } - else { - data.get_nwaiters_gone()++; // count spurious wakeups. - } - } - if ( 0 == --data.get_nwaiters_to_unblock() ) { - if ( 0 != data.get_nwaiters_blocked() ) { - data.get_sem_block_lock().post(); // open the gate. - nsignals_was_left = 0; // do not open the gate below again. - } - else if ( 0 != (nwaiters_was_gone = data.get_nwaiters_gone()) ) { - data.get_nwaiters_gone() = 0; - } - } - } - else if ( (std::numeric_limits::max)()/2 - == ++data.get_nwaiters_gone() ) { // timeout/canceled or spurious semaphore :-) - data.get_sem_block_lock().wait(); - data.get_nwaiters_blocked() -= data.get_nwaiters_gone(); // something is going on here - test of timeouts? :-) - data.get_sem_block_lock().post(); - data.get_nwaiters_gone() = 0; - } - //locker's destructor triggers data.get_mtx_unblock_lock().unlock() - } - - if ( 1 == nsignals_was_left ) { - if ( 0 != nwaiters_was_gone ) { - // sem_adjust( data.get_sem_block_queue(),-nwaiters_was_gone ); - while ( nwaiters_was_gone-- ) { - data.get_sem_block_queue().wait(); // better now than spurious later - } - } - data.get_sem_block_lock().post(); // open the gate - } - - //lock.lock(); called from unlocker destructor - - return ( bTimedOut ) ? false : true; -} - - -template -class condition_8a_wrapper -{ - //Non-copyable - condition_8a_wrapper(const condition_8a_wrapper &); - condition_8a_wrapper &operator=(const condition_8a_wrapper &); - - ConditionMembers m_data; - typedef ipcdetail::condition_algorithm_8a algo_type; - - public: - - condition_8a_wrapper(){} - - ~condition_8a_wrapper(){} - - ConditionMembers & get_members() - { return m_data; } - - const ConditionMembers & get_members() const - { return m_data; } - - void notify_one() - { algo_type::signal(m_data, false); } - - void notify_all() - { algo_type::signal(m_data, true); } - - template - void wait(L& lock) - { - if (!lock) - throw lock_exception(); - algo_type::wait(m_data, lock, false, boost::posix_time::ptime()); - } - - template - void wait(L& lock, Pr pred) - { - if (!lock) - throw lock_exception(); - - while (!pred()) - algo_type::wait(m_data, lock, false, boost::posix_time::ptime()); - } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock); - return true; - } - if (!lock) - throw lock_exception(); - return algo_type::wait(m_data, lock, true, abs_time); - } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock, pred); - return true; - } - if (!lock) - throw lock_exception(); - while (!pred()){ - if (!algo_type::wait(m_data, lock, true, abs_time)) - return pred(); - } - return true; - } -}; - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_CONDITION_ALGORITHM_8A_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/detail/condition_any_algorithm.hpp b/utils/boost_idb/boost/interprocess/sync/detail/condition_any_algorithm.hpp deleted file mode 100644 index a276f826..00000000 --- a/utils/boost_idb/boost/interprocess/sync/detail/condition_any_algorithm.hpp +++ /dev/null @@ -1,224 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_CONDITION_ANY_ALGORITHM_HPP -#define BOOST_INTERPROCESS_DETAIL_CONDITION_ANY_ALGORITHM_HPP - -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -// -// Condition variable 'any' (able to use any type of external mutex) -// -// The code is based on Howard E. Hinnant's ISO C++ N2406 paper. -// Many thanks to Howard for his support and comments. -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// - -// Required interface for ConditionAnyMembers -// class ConditionAnyMembers -// { -// typedef implementation_defined mutex_type; -// typedef implementation_defined condvar_type; -// -// condvar &get_condvar() -// mutex_type &get_mutex() -// }; -// -// Must be initialized as following -// -// get_condvar() [no threads blocked] -// get_mutex() [unlocked] - -template -class condition_any_algorithm -{ - private: - condition_any_algorithm(); - ~condition_any_algorithm(); - condition_any_algorithm(const condition_any_algorithm &); - condition_any_algorithm &operator=(const condition_any_algorithm &); - - typedef typename ConditionAnyMembers::mutex_type mutex_type; - typedef typename ConditionAnyMembers::condvar_type condvar_type; - - template - static void do_wait(ConditionAnyMembers &data, Lock& lock); - - template - static bool do_timed_wait(ConditionAnyMembers &data, Lock& lock, const boost::posix_time::ptime &abs_time); - - public: - template - static bool wait ( ConditionAnyMembers &data, Lock &mut - , bool timeout_enabled, const boost::posix_time::ptime &abs_time); - static void signal( ConditionAnyMembers &data, bool broadcast); -}; - -template -void condition_any_algorithm::signal(ConditionAnyMembers &data, bool broadcast) -{ - scoped_lock internal_lock(data.get_mutex()); - if(broadcast){ - data.get_condvar().notify_all(); - } - else{ - data.get_condvar().notify_one(); - } -} - -template -template -bool condition_any_algorithm::wait - ( ConditionAnyMembers &data - , Lock &lock - , bool tout_enabled - , const boost::posix_time::ptime &abs_time) -{ - if(tout_enabled){ - return condition_any_algorithm::do_timed_wait(data, lock, abs_time); - } - else{ - condition_any_algorithm::do_wait(data, lock); - return true; - } -} - -template -template -void condition_any_algorithm::do_wait - (ConditionAnyMembers &data, Lock& lock) -{ - //lock internal before unlocking external to avoid race with a notifier - scoped_lock internal_lock(data.get_mutex()); - { - lock_inverter inverted_lock(lock); - scoped_lock > external_unlock(inverted_lock); - { //unlock internal first to avoid deadlock with near simultaneous waits - scoped_lock internal_unlock; - internal_lock.swap(internal_unlock); - data.get_condvar().wait(internal_unlock); - } - } -} - -template -template -bool condition_any_algorithm::do_timed_wait - (ConditionAnyMembers &data, Lock& lock, const boost::posix_time::ptime &abs_time) -{ - //lock internal before unlocking external to avoid race with a notifier - scoped_lock internal_lock(data.get_mutex()); - { - //Unlock external lock and program for relock - lock_inverter inverted_lock(lock); - scoped_lock > external_unlock(inverted_lock); - { //unlock internal first to avoid deadlock with near simultaneous waits - scoped_lock internal_unlock; - internal_lock.swap(internal_unlock); - return data.get_condvar().timed_wait(internal_unlock, abs_time); - } - } -} - - -template -class condition_any_wrapper -{ - //Non-copyable - condition_any_wrapper(const condition_any_wrapper &); - condition_any_wrapper &operator=(const condition_any_wrapper &); - - ConditionAnyMembers m_data; - typedef ipcdetail::condition_any_algorithm algo_type; - - public: - - condition_any_wrapper(){} - - ~condition_any_wrapper(){} - - ConditionAnyMembers & get_members() - { return m_data; } - - const ConditionAnyMembers & get_members() const - { return m_data; } - - void notify_one() - { algo_type::signal(m_data, false); } - - void notify_all() - { algo_type::signal(m_data, true); } - - template - void wait(L& lock) - { - if (!lock) - throw lock_exception(); - algo_type::wait(m_data, lock, false, boost::posix_time::ptime()); - } - - template - void wait(L& lock, Pr pred) - { - if (!lock) - throw lock_exception(); - - while (!pred()) - algo_type::wait(m_data, lock, false, boost::posix_time::ptime()); - } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock); - return true; - } - if (!lock) - throw lock_exception(); - return algo_type::wait(m_data, lock, true, abs_time); - } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock, pred); - return true; - } - if (!lock) - throw lock_exception(); - while (!pred()){ - if (!algo_type::wait(m_data, lock, true, abs_time)) - return pred(); - } - return true; - } -}; - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_CONDITION_ANY_ALGORITHM_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/detail/locks.hpp b/utils/boost_idb/boost/interprocess/sync/detail/locks.hpp deleted file mode 100644 index fbb003aa..00000000 --- a/utils/boost_idb/boost/interprocess/sync/detail/locks.hpp +++ /dev/null @@ -1,66 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_LOCKS_HPP -#define BOOST_INTERPROCESS_DETAIL_LOCKS_HPP - -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -template -class internal_mutex_lock -{ - typedef void (internal_mutex_lock::*unspecified_bool_type)(); - public: - - typedef typename Lock::mutex_type::internal_mutex_type mutex_type; - - - internal_mutex_lock(Lock &l) - : l_(l) - {} - - mutex_type* mutex() const - { return l_ ? &l_.mutex()->internal_mutex() : 0; } - - void lock() { l_.lock(); } - - void unlock() { l_.unlock(); } - - operator unspecified_bool_type() const - { return l_ ? &internal_mutex_lock::lock : 0; } - - private: - Lock &l_; -}; - -template -class lock_inverter -{ - Lock &l_; - public: - lock_inverter(Lock &l) - : l_(l) - {} - void lock() { l_.unlock(); } - void unlock() { l_.lock(); } -}; - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_LOCKS_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/spin/interprocess_barrier.hpp b/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_barrier.hpp similarity index 100% rename from utils/boost_idb/boost/interprocess/sync/spin/interprocess_barrier.hpp rename to utils/boost_idb/boost/interprocess/sync/emulation/interprocess_barrier.hpp diff --git a/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_condition.hpp b/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_condition.hpp new file mode 100644 index 00000000..592b71cd --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_condition.hpp @@ -0,0 +1,200 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include +namespace boost { +namespace interprocess { + +inline interprocess_condition::interprocess_condition() +{ + //Note that this class is initialized to zero. + //So zeroed memory can be interpreted as an initialized + //condition variable + m_command = SLEEP; + m_num_waiters = 0; +} + +inline interprocess_condition::~interprocess_condition() +{ + //Trivial destructor +} + +inline void interprocess_condition::notify_one() +{ + this->notify(NOTIFY_ONE); +} + +inline void interprocess_condition::notify_all() +{ + this->notify(NOTIFY_ALL); +} + +inline void interprocess_condition::notify(boost::uint32_t command) +{ + //This interprocess_mutex guarantees that no other thread can enter to the + //do_timed_wait method logic, so that thread count will be + //constant until the function writes a NOTIFY_ALL command. + //It also guarantees that no other notification can be signaled + //on this interprocess_condition before this one ends + m_enter_mut.lock(); + + //Return if there are no waiters + if(!detail::atomic_read32(&m_num_waiters)) { + m_enter_mut.unlock(); + return; + } + + //Notify that all threads should execute wait logic + while(SLEEP != detail::atomic_cas32(const_cast(&m_command), command, SLEEP)){ + detail::thread_yield(); + } +/* + //Wait until the threads are woken + while(SLEEP != detail::atomic_cas32(const_cast(&m_command), 0)){ + detail::thread_yield(); + } +*/ + //The enter interprocess_mutex will rest locked until the last waiting thread unlocks it +} + +inline void interprocess_condition::do_wait(interprocess_mutex &mut) +{ + this->do_timed_wait(false, boost::posix_time::ptime(), mut); +} + +inline bool interprocess_condition::do_timed_wait + (const boost::posix_time::ptime &abs_time, interprocess_mutex &mut) +{ + return this->do_timed_wait(true, abs_time, mut); +} + +inline bool interprocess_condition::do_timed_wait(bool tout_enabled, + const boost::posix_time::ptime &abs_time, + interprocess_mutex &mut) +{ + boost::posix_time::ptime now = microsec_clock::universal_time(); + + if(tout_enabled){ + if(now >= abs_time) return false; + } + + typedef boost::interprocess::scoped_lock InternalLock; + //The enter interprocess_mutex guarantees that while executing a notification, + //no other thread can execute the do_timed_wait method. + { + //--------------------------------------------------------------- + InternalLock lock; + if(tout_enabled){ + InternalLock dummy(m_enter_mut, abs_time); + lock = boost::interprocess::move(dummy); + } + else{ + InternalLock dummy(m_enter_mut); + lock = boost::interprocess::move(dummy); + } + + if(!lock) + return false; + //--------------------------------------------------------------- + //We increment the waiting thread count protected so that it will be + //always constant when another thread enters the notification logic. + //The increment marks this thread as "waiting on interprocess_condition" + detail::atomic_inc32(const_cast(&m_num_waiters)); + + //We unlock the external interprocess_mutex atomically with the increment + mut.unlock(); + } + + //By default, we suppose that no timeout has happened + bool timed_out = false, unlock_enter_mut= false; + + //Loop until a notification indicates that the thread should + //exit or timeout occurs + while(1){ + //The thread sleeps/spins until a interprocess_condition commands a notification + //Notification occurred, we will lock the checking interprocess_mutex so that + while(detail::atomic_read32(&m_command) == SLEEP){ + detail::thread_yield(); + + //Check for timeout + if(tout_enabled){ + now = microsec_clock::universal_time(); + + if(now >= abs_time){ + //If we can lock the interprocess_mutex it means that no notification + //is being executed in this interprocess_condition variable + timed_out = m_enter_mut.try_lock(); + + //If locking fails, indicates that another thread is executing + //notification, so we play the notification game + if(!timed_out){ + //There is an ongoing notification, we will try again later + continue; + } + //No notification in execution, since enter interprocess_mutex is locked. + //We will execute time-out logic, so we will decrement count, + //release the enter interprocess_mutex and return false. + break; + } + } + } + + //If a timeout occurred, the interprocess_mutex will not execute checking logic + if(tout_enabled && timed_out){ + //Decrement wait count + detail::atomic_dec32(const_cast(&m_num_waiters)); + unlock_enter_mut = true; + break; + } + else{ + boost::uint32_t result = detail::atomic_cas32 + (const_cast(&m_command), SLEEP, NOTIFY_ONE); + if(result == SLEEP){ + //Other thread has been notified and since it was a NOTIFY one + //command, this thread must sleep again + continue; + } + else if(result == NOTIFY_ONE){ + //If it was a NOTIFY_ONE command, only this thread should + //exit. This thread has atomically marked command as sleep before + //so no other thread will exit. + //Decrement wait count. + unlock_enter_mut = true; + detail::atomic_dec32(const_cast(&m_num_waiters)); + break; + } + else{ + //If it is a NOTIFY_ALL command, all threads should return + //from do_timed_wait function. Decrement wait count. + unlock_enter_mut = 1 == detail::atomic_dec32(const_cast(&m_num_waiters)); + //Check if this is the last thread of notify_all waiters + //Only the last thread will release the interprocess_mutex + if(unlock_enter_mut){ + detail::atomic_cas32(const_cast(&m_command), SLEEP, NOTIFY_ALL); + } + break; + } + } + } + + //Unlock the enter interprocess_mutex if it is a single notification, if this is + //the last notified thread in a notify_all or a timeout has occurred + if(unlock_enter_mut){ + m_enter_mut.unlock(); + } + + //Lock external again before returning from the method + mut.lock(); + return !timed_out; +} + +} //namespace interprocess +} // namespace boost diff --git a/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_semaphore.hpp new file mode 100644 index 00000000..5da3419a --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/emulation/interprocess_semaphore.hpp @@ -0,0 +1,75 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace boost { +namespace interprocess { + + +inline interprocess_semaphore::~interprocess_semaphore() +{} + +inline interprocess_semaphore::interprocess_semaphore(unsigned int initialCount) +{ detail::atomic_write32(&this->m_count, boost::uint32_t(initialCount)); } + +inline void interprocess_semaphore::post() +{ + detail::atomic_inc32(&m_count); +} + +inline void interprocess_semaphore::wait() +{ + while(!detail::atomic_add_unless32(&m_count, boost::uint32_t(-1), boost::uint32_t(0))){ + while(detail::atomic_read32(&m_count) == 0){ + detail::thread_yield(); + } + } +} + +inline bool interprocess_semaphore::try_wait() +{ + return detail::atomic_add_unless32(&m_count, boost::uint32_t(-1), boost::uint32_t(0)); +} + +inline bool interprocess_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->wait(); + return true; + } + //Obtain current count and target time + boost::posix_time::ptime now(microsec_clock::universal_time()); + if(now >= abs_time) + return false; + + do{ + if(this->try_wait()){ + break; + } + now = microsec_clock::universal_time(); + + if(now >= abs_time){ + return this->try_wait(); + } + // relinquish current time slice + detail::thread_yield(); + }while (true); + return true; +} +/* +inline int interprocess_semaphore::get_count() const +{ + return (int)detail::atomic_read32(&m_count); +}*/ + +} //namespace interprocess { +} //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/sync/emulation/mutex.hpp b/utils/boost_idb/boost/interprocess/sync/emulation/mutex.hpp new file mode 100644 index 00000000..029b31e3 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/emulation/mutex.hpp @@ -0,0 +1,114 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_INTERPROCESS_DETAIL_EMULATION_MUTEX_HPP +#define BOOST_INTERPROCESS_DETAIL_EMULATION_MUTEX_HPP + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace interprocess { +namespace detail { + +class emulation_mutex +{ + emulation_mutex(const emulation_mutex &); + emulation_mutex &operator=(const emulation_mutex &); + public: + + emulation_mutex(); + ~emulation_mutex(); + + void lock(); + bool try_lock(); + bool timed_lock(const boost::posix_time::ptime &abs_time); + void unlock(); + void take_ownership(){}; + private: + volatile boost::uint32_t m_s; +}; + +inline emulation_mutex::emulation_mutex() + : m_s(0) +{ + //Note that this class is initialized to zero. + //So zeroed memory can be interpreted as an + //initialized mutex +} + +inline emulation_mutex::~emulation_mutex() +{ + //Trivial destructor +} + +inline void emulation_mutex::lock(void) +{ + do{ + boost::uint32_t prev_s = detail::atomic_cas32(const_cast(&m_s), 1, 0); + + if (m_s == 1 && prev_s == 0){ + break; + } + // relinquish current timeslice + detail::thread_yield(); + }while (true); +} + +inline bool emulation_mutex::try_lock(void) +{ + boost::uint32_t prev_s = detail::atomic_cas32(const_cast(&m_s), 1, 0); + return m_s == 1 && prev_s == 0; +} + +inline bool emulation_mutex::timed_lock(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + //Obtain current count and target time + boost::posix_time::ptime now = microsec_clock::universal_time(); + + if(now >= abs_time) return false; + + do{ + if(this->try_lock()){ + break; + } + now = microsec_clock::universal_time(); + + if(now >= abs_time){ + return false; + } + // relinquish current time slice + detail::thread_yield(); + }while (true); + + return true; +} + +inline void emulation_mutex::unlock(void) +{ detail::atomic_cas32(const_cast(&m_s), 0, 1); } + +} //namespace detail { +} //namespace interprocess { +} //namespace boost { + +#endif //BOOST_INTERPROCESS_DETAIL_EMULATION_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_creation_functor.hpp b/utils/boost_idb/boost/interprocess/sync/emulation/named_creation_functor.hpp similarity index 82% rename from utils/boost_idb/boost/interprocess/sync/shm/named_creation_functor.hpp rename to utils/boost_idb/boost/interprocess/sync/emulation/named_creation_functor.hpp index cdfff99b..8bc88f30 100644 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_creation_functor.hpp +++ b/utils/boost_idb/boost/interprocess/sync/emulation/named_creation_functor.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2007-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2007-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,7 +17,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { struct named_creation_functor_no_arg{}; @@ -26,7 +26,7 @@ class named_creation_functor { typedef named_creation_functor_no_arg no_arg_t; public: - named_creation_functor(create_enum_t type, Arg arg = Arg()) + named_creation_functor(detail::create_enum_t type, Arg arg = Arg()) : m_creation_type(type), m_arg(arg){} template @@ -38,13 +38,13 @@ class named_creation_functor { new(address)T(m_arg); } bool operator()(void *address, std::size_t, bool created) const - { + { switch(m_creation_type){ - case DoOpen: + case detail::DoOpen: return true; break; - case DoCreate: - case DoOpenOrCreate: + case detail::DoCreate: + case detail::DoOpenOrCreate: if(created){ construct(address); } @@ -56,16 +56,12 @@ class named_creation_functor break; } } - - std::size_t get_min_size() const - { return sizeof(T); } - private: - create_enum_t m_creation_type; + detail::create_enum_t m_creation_type; Arg m_arg; }; -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { } //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/sync/emulation/recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/emulation/recursive_mutex.hpp new file mode 100644 index 00000000..d29a873a --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/emulation/recursive_mutex.hpp @@ -0,0 +1,167 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// +// +// Parts of the pthread code come from Boost Threads code: +// +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2001-2003 +// William E. Kempf +// +// Permission to use, copy, modify, distribute and sell this software +// and its documentation for any purpose is hereby granted without fee, +// provided that the above copyright notice appear in all copies and +// that both that copyright notice and this permission notice appear +// in supporting documentation. William E. Kempf makes no representations +// about the suitability of this software for any purpose. +// It is provided "as is" without express or implied warranty. +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_INTERPROCESS_DETAIL_EMULATION_RECURSIVE_MUTEX_HPP +#define BOOST_INTERPROCESS_DETAIL_EMULATION_RECURSIVE_MUTEX_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace interprocess { +namespace detail { + +class emulation_recursive_mutex +{ + emulation_recursive_mutex(const emulation_recursive_mutex &); + emulation_recursive_mutex &operator=(const emulation_recursive_mutex &); + public: + + emulation_recursive_mutex(); + ~emulation_recursive_mutex(); + + void lock(); + bool try_lock(); + bool timed_lock(const boost::posix_time::ptime &abs_time); + void unlock(); + void take_ownership(); + private: + emulation_mutex m_mutex; + unsigned int m_nLockCount; + volatile detail::OS_systemwide_thread_id_t m_nOwner; + volatile boost::uint32_t m_s; +}; + +inline emulation_recursive_mutex::emulation_recursive_mutex() + : m_nLockCount(0), m_nOwner(detail::get_invalid_systemwide_thread_id()){} + +inline emulation_recursive_mutex::~emulation_recursive_mutex(){} + +inline void emulation_recursive_mutex::lock() +{ + typedef detail::OS_systemwide_thread_id_t handle_t; + const handle_t thr_id(detail::get_current_systemwide_thread_id()); + handle_t old_id; + detail::systemwide_thread_id_copy(m_nOwner, old_id); + if(detail::equal_systemwide_thread_id(thr_id , old_id)){ + if((unsigned int)(m_nLockCount+1) == 0){ + //Overflow, throw an exception + throw interprocess_exception("boost::interprocess::emulation_recursive_mutex recursive lock overflow"); + } + ++m_nLockCount; + } + else{ + m_mutex.lock(); + detail::systemwide_thread_id_copy(thr_id, m_nOwner); + m_nLockCount = 1; + } +} + +inline bool emulation_recursive_mutex::try_lock() +{ + typedef detail::OS_systemwide_thread_id_t handle_t; + handle_t thr_id(detail::get_current_systemwide_thread_id()); + handle_t old_id; + detail::systemwide_thread_id_copy(m_nOwner, old_id); + if(detail::equal_systemwide_thread_id(thr_id , old_id)) { // we own it + if((unsigned int)(m_nLockCount+1) == 0){ + //Overflow, throw an exception + throw interprocess_exception("boost::interprocess::emulation_recursive_mutex recursive lock overflow"); + } + ++m_nLockCount; + return true; + } + if(m_mutex.try_lock()){ + detail::systemwide_thread_id_copy(thr_id, m_nOwner); + m_nLockCount = 1; + return true; + } + return false; +} + +inline bool emulation_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) +{ + typedef detail::OS_systemwide_thread_id_t handle_t; + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + const handle_t thr_id(detail::get_current_systemwide_thread_id()); + handle_t old_id; + detail::systemwide_thread_id_copy(m_nOwner, old_id); + if(detail::equal_systemwide_thread_id(thr_id , old_id)) { // we own it + if((unsigned int)(m_nLockCount+1) == 0){ + //Overflow, throw an exception + throw interprocess_exception("boost::interprocess::emulation_recursive_mutex recursive lock overflow"); + } + ++m_nLockCount; + return true; + } + if(m_mutex.timed_lock(abs_time)){ + detail::systemwide_thread_id_copy(thr_id, m_nOwner); + m_nLockCount = 1; + return true; + } + return false; +} + +inline void emulation_recursive_mutex::unlock() +{ + typedef detail::OS_systemwide_thread_id_t handle_t; + handle_t old_id; + detail::systemwide_thread_id_copy(m_nOwner, old_id); + const handle_t thr_id(detail::get_current_systemwide_thread_id()); + (void)old_id; + (void)thr_id; + BOOST_ASSERT(detail::equal_systemwide_thread_id(thr_id, old_id)); + --m_nLockCount; + if(!m_nLockCount){ + const handle_t new_id(detail::get_invalid_systemwide_thread_id()); + detail::systemwide_thread_id_copy(new_id, m_nOwner); + m_mutex.unlock(); + } +} + +inline void emulation_recursive_mutex::take_ownership() +{ + typedef detail::OS_systemwide_thread_id_t handle_t; + this->m_nLockCount = 1; + const handle_t thr_id(detail::get_current_systemwide_thread_id()); + detail::systemwide_thread_id_copy + (thr_id, m_nOwner); +} + +} //namespace detail { +} //namespace interprocess { +} //namespace boost { + +#endif //BOOST_INTERPROCESS_DETAIL_EMULATION_RECURSIVE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/file_lock.hpp b/utils/boost_idb/boost/interprocess/sync/file_lock.hpp index 1b4dd39a..30b91c12 100644 --- a/utils/boost_idb/boost/interprocess/sync/file_lock.hpp +++ b/utils/boost_idb/boost/interprocess/sync/file_lock.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -21,8 +21,7 @@ #include #include #include -#include -#include +#include //!\file //!Describes a class that wraps file locking capabilities. @@ -40,35 +39,35 @@ class file_lock { /// @cond //Non-copyable - BOOST_MOVABLE_BUT_NOT_COPYABLE(file_lock) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(file_lock) /// @endcond public: //!Constructs an empty file mapping. //!Does not throw file_lock() - : m_file_hnd(file_handle_t(ipcdetail::invalid_file())) + : m_file_hnd(file_handle_t(detail::invalid_file())) {} //!Opens a file lock. Throws interprocess_exception if the file does not //!exist or there are no operating system resources. file_lock(const char *name); - //!Moves the ownership of "moved"'s file mapping object to *this. - //!After the call, "moved" does not represent any file mapping object. + //!Moves the ownership of "moved"'s file mapping object to *this. + //!After the call, "moved" does not represent any file mapping object. //!Does not throw - file_lock(BOOST_RV_REF(file_lock) moved) - : m_file_hnd(file_handle_t(ipcdetail::invalid_file())) + file_lock(BOOST_INTERPROCESS_RV_REF(file_lock) moved) + : m_file_hnd(file_handle_t(detail::invalid_file())) { this->swap(moved); } //!Moves the ownership of "moved"'s file mapping to *this. - //!After the call, "moved" does not represent any file mapping. + //!After the call, "moved" does not represent any file mapping. //!Does not throw - file_lock &operator=(BOOST_RV_REF(file_lock) moved) - { - file_lock tmp(boost::move(moved)); + file_lock &operator=(BOOST_INTERPROCESS_RV_REF(file_lock) moved) + { + file_lock tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Closes a file lock. Does not throw. @@ -82,7 +81,7 @@ class file_lock m_file_hnd = other.m_file_hnd; other.m_file_hnd = tmp; } - + //Exclusive locking //!Effects: The calling thread tries to obtain exclusive ownership of the mutex, @@ -100,14 +99,14 @@ class file_lock bool try_lock(); //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! waiting if necessary until no other thread has exclusive, or sharable + //! waiting if necessary until no other thread has has exclusive, or sharable //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The calling thread releases the exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. + //!Effects: The calling thread releases the exclusive ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock(); @@ -120,22 +119,22 @@ class file_lock void lock_sharable(); //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! without waiting. If no other thread has exclusive ownership of the - //! mutex this succeeds. + //! without waiting. If no other thread has has exclusive ownership of the + //! mutex this succeeds. //!Returns: If it can acquire sharable ownership immediately returns true. If it - //! has to wait, returns false. + //! has to wait, returns false. //!Throws: interprocess_exception on error. bool try_lock_sharable(); //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! waiting if necessary until no other thread has exclusive ownership of - //! the mutex or abs_time is reached. - //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. + //! waiting if necessary until no other thread has has exclusive ownership of + //! the mutex or abs_time is reached. + //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock_sharable(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The calling thread releases the sharable ownership of the mutex. + //!Precondition: The thread must have sharable ownership of the mutex. + //!Effects: The calling thread releases the sharable ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock_sharable(); /// @cond @@ -150,9 +149,9 @@ class file_lock using namespace boost::detail; if(now >= abs_time) return false; - spin_wait swait; + do{ - if(!ipcdetail::try_acquire_file_lock(hnd, acquired)) + if(!detail::try_acquire_file_lock(hnd, acquired)) return false; if(acquired) @@ -165,23 +164,22 @@ class file_lock return true; } // relinquish current time slice - swait.yield(); + detail::thread_yield(); } }while (true); } bool timed_acquire_file_lock_sharable (file_handle_t hnd, bool &acquired, const boost::posix_time::ptime &abs_time) - { + { //Obtain current count and target time boost::posix_time::ptime now = microsec_clock::universal_time(); using namespace boost::detail; if(now >= abs_time) return false; - spin_wait swait; do{ - if(!ipcdetail::try_acquire_file_lock_sharable(hnd, acquired)) + if(!detail::try_acquire_file_lock_sharable(hnd, acquired)) return false; if(acquired) @@ -194,7 +192,7 @@ class file_lock return true; } // relinquish current time slice - swait.yield(); + detail::thread_yield(); } }while (true); } @@ -203,9 +201,9 @@ class file_lock inline file_lock::file_lock(const char *name) { - m_file_hnd = ipcdetail::open_existing_file(name, read_write); + m_file_hnd = detail::open_existing_file(name, read_write); - if(m_file_hnd == ipcdetail::invalid_file()){ + if(m_file_hnd == detail::invalid_file()){ error_info err(system_error_code()); throw interprocess_exception(err); } @@ -213,15 +211,15 @@ inline file_lock::file_lock(const char *name) inline file_lock::~file_lock() { - if(m_file_hnd != ipcdetail::invalid_file()){ - ipcdetail::close_file(m_file_hnd); - m_file_hnd = ipcdetail::invalid_file(); + if(m_file_hnd != detail::invalid_file()){ + detail::close_file(m_file_hnd); + m_file_hnd = detail::invalid_file(); } } inline void file_lock::lock() { - if(!ipcdetail::acquire_file_lock(m_file_hnd)){ + if(!detail::acquire_file_lock(m_file_hnd)){ error_info err(system_error_code()); throw interprocess_exception(err); } @@ -230,7 +228,7 @@ inline void file_lock::lock() inline bool file_lock::try_lock() { bool result; - if(!ipcdetail::try_acquire_file_lock(m_file_hnd, result)){ + if(!detail::try_acquire_file_lock(m_file_hnd, result)){ error_info err(system_error_code()); throw interprocess_exception(err); } @@ -253,7 +251,7 @@ inline bool file_lock::timed_lock(const boost::posix_time::ptime &abs_time) inline void file_lock::unlock() { - if(!ipcdetail::release_file_lock(m_file_hnd)){ + if(!detail::release_file_lock(m_file_hnd)){ error_info err(system_error_code()); throw interprocess_exception(err); } @@ -261,7 +259,7 @@ inline void file_lock::unlock() inline void file_lock::lock_sharable() { - if(!ipcdetail::acquire_file_lock_sharable(m_file_hnd)){ + if(!detail::acquire_file_lock_sharable(m_file_hnd)){ error_info err(system_error_code()); throw interprocess_exception(err); } @@ -270,7 +268,7 @@ inline void file_lock::lock_sharable() inline bool file_lock::try_lock_sharable() { bool result; - if(!ipcdetail::try_acquire_file_lock_sharable(m_file_hnd, result)){ + if(!detail::try_acquire_file_lock_sharable(m_file_hnd, result)){ error_info err(system_error_code()); throw interprocess_exception(err); } @@ -293,7 +291,7 @@ inline bool file_lock::timed_lock_sharable(const boost::posix_time::ptime &abs_t inline void file_lock::unlock_sharable() { - if(!ipcdetail::release_file_lock_sharable(m_file_hnd)){ + if(!detail::release_file_lock_sharable(m_file_hnd)){ error_info err(system_error_code()); throw interprocess_exception(err); } diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_barrier.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_barrier.hpp new file mode 100644 index 00000000..6c88dbf0 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/interprocess_barrier.hpp @@ -0,0 +1,115 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// +// +// barrier is a modified version of Boost Threads barrier +// +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2002-2003 +// David Moore, William E. Kempf +// +// Permission to use, copy, modify, distribute and sell this software +// and its documentation for any purpose is hereby granted without fee, +// provided that the above copyright notice appear in all copies and +// that both that copyright notice and this permission notice appear +// in supporting documentation. William E. Kempf makes no representations +// about the suitability of this software for any purpose. +// It is provided "as is" without express or implied warranty. + +#ifndef BOOST_INTERPROCESS_BARRIER_HPP +#define BOOST_INTERPROCESS_BARRIER_HPP + +/// @cond + +#if (defined _MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include +#include + +#if defined BOOST_INTERPROCESS_POSIX_PROCESS_SHARED && defined BOOST_INTERPROCESS_POSIX_BARRIERS +# include +# include +# include +# define BOOST_INTERPROCESS_USE_POSIX +#else +# include +# include +# include +# include +# define BOOST_INTERPROCESS_USE_GENERIC_EMULATION +#endif + +# include + +/// @endcond + +namespace boost { +namespace interprocess { + +//!An object of class barrier is a synchronization primitive that +//!can be placed in shared memory used to cause a set of threads from +//!different processes to wait until they each perform a certain +//!function or each reach a particular point in their execution. +class barrier +{ + public: + //!Constructs a barrier object that will cause count threads + //!to block on a call to wait(). + barrier(unsigned int count); + + //!Destroys *this. If threads are still executing their wait() + //!operations, the behavior for these threads is undefined. + ~barrier(); + + //!Effects: Wait until N threads call wait(), where N equals the count + //!provided to the constructor for the barrier object. + //!Note that if the barrier is destroyed before wait() can return, + //!the behavior is undefined. + //!Returns: Exactly one of the N threads will receive a return value + //!of true, the others will receive a value of false. Precisely which + //!thread receives the return value of true will be implementation-defined. + //!Applications can use this value to designate one thread as a leader that + //!will take a certain action, and the other threads emerging from the barrier + //!can wait for that action to take place. + bool wait(); + + /// @cond + private: + #if defined(BOOST_INTERPROCESS_USE_GENERIC_EMULATION) + interprocess_mutex m_mutex; + interprocess_condition m_cond; + unsigned int m_threshold; + unsigned int m_count; + unsigned int m_generation; + #else //#if defined BOOST_INTERPROCESS_USE_POSIX + pthread_barrier_t m_barrier; + #endif//#if defined BOOST_INTERPROCESS_USE_POSIX + /// @endcond +}; + +} // namespace interprocess +} // namespace boost + + +#ifdef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# include +#endif + +#ifdef BOOST_INTERPROCESS_USE_POSIX +# undef BOOST_INTERPROCESS_USE_POSIX +# include +#endif + +#include + +#endif diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_condition.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_condition.hpp index c30e870d..5e909a94 100644 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_condition.hpp +++ b/utils/boost_idb/boost/interprocess/sync/interprocess_condition.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -21,21 +21,22 @@ #include #include +#include +#include #include -#include #include #include #include #if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined(BOOST_INTERPROCESS_POSIX_PROCESS_SHARED) - #include + #include + #include + #include #define BOOST_INTERPROCESS_USE_POSIX -//Experimental... -#elif !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#elif !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) - #include +#else + #include + #include + #include #define BOOST_INTERPROCESS_USE_GENERIC_EMULATION #endif @@ -55,11 +56,6 @@ class named_condition; //!This class is a condition variable that can be placed in shared memory or //!memory mapped files. -//!Destroys the object of type std::condition_variable_any -//! -//!Unlike std::condition_variable in C++11, it is NOT safe to invoke the destructor if all -//!threads have been only notified. It is required that they have exited their respective wait -//!functions. class interprocess_condition { /// @cond @@ -68,35 +64,31 @@ class interprocess_condition interprocess_condition &operator=(const interprocess_condition &); friend class named_condition; /// @endcond - public: //!Constructs a interprocess_condition. On error throws interprocess_exception. - interprocess_condition() - {} + interprocess_condition(); //!Destroys *this //!liberating system resources. - ~interprocess_condition() - {} + ~interprocess_condition(); - //!If there is a thread waiting on *this, change that + //!If there is a thread waiting on *this, change that //!thread's state to ready. Otherwise there is no effect. - void notify_one() - { m_condition.notify_one(); } + void notify_one(); //!Change the state of all threads waiting on *this to ready. //!If there are no waiting threads, notify_all() has no effect. - void notify_all() - { m_condition.notify_all(); } + void notify_all(); - //!Releases the lock on the interprocess_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to + //!Releases the lock on the interprocess_mutex object associated with lock, blocks + //!the current thread of execution until readied by a call to //!this->notify_one() or this->notify_all(), and then reacquires the lock. template void wait(L& lock) - { - ipcdetail::internal_mutex_lock internal_lock(lock); - m_condition.wait(internal_lock); + { + if (!lock) + throw lock_exception(); + do_wait(*lock.mutex()); } //!The same as: @@ -104,53 +96,84 @@ class interprocess_condition template void wait(L& lock, Pr pred) { - ipcdetail::internal_mutex_lock internal_lock(lock); - m_condition.wait(internal_lock, pred); + if (!lock) + throw lock_exception(); + + while (!pred()) + do_wait(*lock.mutex()); } - //!Releases the lock on the interprocess_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, + //!Releases the lock on the interprocess_mutex object associated with lock, blocks + //!the current thread of execution until readied by a call to + //!this->notify_one() or this->notify_all(), or until time abs_time is reached, //!and then reacquires the lock. //!Returns: false if time abs_time is reached, otherwise true. template bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) { - ipcdetail::internal_mutex_lock internal_lock(lock); - return m_condition.timed_wait(internal_lock, abs_time); + if(abs_time == boost::posix_time::pos_infin){ + this->wait(lock); + return true; + } + if (!lock) + throw lock_exception(); + return do_timed_wait(abs_time, *lock.mutex()); } - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); + //!The same as: while (!pred()) { + //! if (!timed_wait(lock, abs_time)) return pred(); //! } return true; template bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) { - ipcdetail::internal_mutex_lock internal_lock(lock); - return m_condition.timed_wait(internal_lock, abs_time, pred); + if(abs_time == boost::posix_time::pos_infin){ + this->wait(lock, pred); + return true; + } + if (!lock) + throw lock_exception(); + while (!pred()){ + if (!do_timed_wait(abs_time, *lock.mutex())) + return pred(); + } + + return true; } /// @cond - private: + void do_wait(interprocess_mutex &mut); + + bool do_timed_wait(const boost::posix_time::ptime &abs_time, interprocess_mutex &mut); + #if defined (BOOST_INTERPROCESS_USE_GENERIC_EMULATION) - #undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION - ipcdetail::spin_condition m_condition; + enum { SLEEP = 0, NOTIFY_ONE, NOTIFY_ALL }; + interprocess_mutex m_enter_mut; + //interprocess_mutex m_check_mut; + volatile boost::uint32_t m_command; + volatile boost::uint32_t m_num_waiters; + bool do_timed_wait(bool tout_enabled, const boost::posix_time::ptime &abs_time, interprocess_mutex &mut); + void notify(boost::uint32_t command); #elif defined(BOOST_INTERPROCESS_USE_POSIX) - #undef BOOST_INTERPROCESS_USE_POSIX - ipcdetail::posix_condition m_condition; - #elif defined(BOOST_INTERPROCESS_USE_WINDOWS) - #undef BOOST_INTERPROCESS_USE_WINDOWS - ipcdetail::windows_condition m_condition; - #else - #error "Unknown platform for interprocess_mutex" + pthread_cond_t m_condition; #endif /// @endcond }; } //namespace interprocess + } // namespace boost +#ifdef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# include +#endif + +#ifdef BOOST_INTERPROCESS_USE_POSIX +# undef BOOST_INTERPROCESS_USE_POSIX +# include +#endif + #include #endif // BOOST_INTERPROCESS_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_condition_any.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_condition_any.hpp deleted file mode 100644 index dd207946..00000000 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_condition_any.hpp +++ /dev/null @@ -1,129 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_CONDITION_ANY_HPP -#define BOOST_INTERPROCESS_CONDITION_ANY_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -/// @cond - -#include -#include - -#include -#include -#include -#include -#include - -/// @endcond - -//!\file -//!Describes process-shared variables interprocess_condition_any class - -namespace boost { - -namespace posix_time -{ class ptime; } - -namespace interprocess { - -//!This class is a condition variable that can be placed in shared memory or -//!memory mapped files. -//! -//!The interprocess_condition_any class is a generalization of interprocess_condition. -//!Whereas interprocess_condition works only on Locks with mutex_type == interprocess_mutex -//!interprocess_condition_any can operate on any user-defined lock that meets the BasicLockable -//!requirements (lock()/unlock() member functions). -//! -//!Unlike std::condition_variable_any in C++11, it is NOT safe to invoke the destructor if all -//!threads have been only notified. It is required that they have exited their respective wait -//!functions. -class interprocess_condition_any -{ - /// @cond - //Non-copyable - interprocess_condition_any(const interprocess_condition_any &); - interprocess_condition_any &operator=(const interprocess_condition_any &); - - class members - { - public: - typedef interprocess_condition condvar_type; - typedef interprocess_mutex mutex_type; - - condvar_type &get_condvar() { return m_cond; } - mutex_type &get_mutex() { return m_mut; } - - private: - condvar_type m_cond; - mutex_type m_mut; - }; - - ipcdetail::condition_any_wrapper m_cond; - - /// @endcond - public: - //!Constructs a interprocess_condition_any. On error throws interprocess_exception. - interprocess_condition_any(){} - - //!Destroys *this - //!liberating system resources. - ~interprocess_condition_any(){} - - //!If there is a thread waiting on *this, change that - //!thread's state to ready. Otherwise there is no effect. - void notify_one() - { m_cond.notify_one(); } - - //!Change the state of all threads waiting on *this to ready. - //!If there are no waiting threads, notify_all() has no effect. - void notify_all() - { m_cond.notify_all(); } - - //!Releases the lock on the interprocess_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), and then reacquires the lock. - template - void wait(L& lock) - { m_cond.wait(lock); } - - //!The same as: - //!while (!pred()) wait(lock) - template - void wait(L& lock, Pr pred) - { m_cond.wait(lock, pred); } - - //!Releases the lock on the interprocess_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, - //!and then reacquires the lock. - //!Returns: false if time abs_time is reached, otherwise true. - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { return m_cond.timed_wait(lock, abs_time); } - - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); - //! } return true; - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { return m_cond.timed_wait(lock, abs_time, pred); } -}; - -} //namespace interprocess -} // namespace boost - -#include - -#endif // BOOST_INTERPROCESS_CONDITION_ANY_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_mutex.hpp index 5615e8b9..867dd2ae 100644 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/interprocess_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -22,25 +22,22 @@ #endif #include -#include #include #include #include #if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_POSIX_PROCESS_SHARED) - #include + #include + #include + #include #define BOOST_INTERPROCESS_USE_POSIX -//Experimental... -#elif !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#elif !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) - #include +#else + #include #define BOOST_INTERPROCESS_USE_GENERIC_EMULATION namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ namespace robust_emulation_helpers { template @@ -61,7 +58,7 @@ namespace interprocess { class interprocess_condition; -//!Wraps a interprocess_mutex that can be placed in shared memory and can be +//!Wraps a interprocess_mutex that can be placed in shared memory and can be //!shared between processes. Allows timed lock tries class interprocess_mutex { @@ -70,25 +67,6 @@ class interprocess_mutex interprocess_mutex(const interprocess_mutex &); interprocess_mutex &operator=(const interprocess_mutex &); friend class interprocess_condition; - - public: - #if defined(BOOST_INTERPROCESS_USE_GENERIC_EMULATION) - #undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION - typedef ipcdetail::spin_mutex internal_mutex_type; - private: - friend class ipcdetail::robust_emulation_helpers::mutex_traits; - void take_ownership(){ m_mutex.take_ownership(); } - public: - #elif defined(BOOST_INTERPROCESS_USE_POSIX) - #undef BOOST_INTERPROCESS_USE_POSIX - typedef ipcdetail::posix_mutex internal_mutex_type; - #elif defined(BOOST_INTERPROCESS_USE_WINDOWS) - #undef BOOST_INTERPROCESS_USE_WINDOWS - typedef ipcdetail::windows_mutex internal_mutex_type; - #else - #error "Unknown platform for interprocess_mutex" - #endif - /// @endcond public: @@ -117,68 +95,54 @@ class interprocess_mutex //!Effects: The calling thread will try to obtain exclusive ownership of the //! mutex if it can do so in until the specified time is reached. If the //! mutex supports recursive locking, the mutex must be unlocked the same - //! number of times it is locked. + //! number of times it is locked. //!Returns: If the thread acquires ownership of the mutex, returns true, if - //! the timeout expires returns false. + //! the timeout expires returns false. //!Throws: interprocess_exception on error. bool timed_lock(const boost::posix_time::ptime &abs_time); //!Effects: The calling thread releases the exclusive ownership of the mutex. //!Throws: interprocess_exception on error. void unlock(); - /// @cond - internal_mutex_type &internal_mutex() - { return m_mutex; } - - const internal_mutex_type &internal_mutex() const - { return m_mutex; } - private: - internal_mutex_type m_mutex; + + #if defined(BOOST_INTERPROCESS_USE_GENERIC_EMULATION) + friend class detail::robust_emulation_helpers::mutex_traits; + void take_ownership(){ mutex.take_ownership(); } + detail::emulation_mutex mutex; + #elif defined(BOOST_INTERPROCESS_USE_POSIX) + pthread_mutex_t m_mut; + #endif //#if (defined BOOST_INTERPROCESS_WINDOWS) /// @endcond }; } //namespace interprocess { } //namespace boost { +#ifdef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION namespace boost { namespace interprocess { inline interprocess_mutex::interprocess_mutex(){} - inline interprocess_mutex::~interprocess_mutex(){} - -inline void interprocess_mutex::lock() -{ - #ifdef BOOST_INTERPROCESS_ENABLE_TIMEOUT_WHEN_LOCKING - boost::posix_time::ptime wait_time - = boost::posix_time::microsec_clock::universal_time() - + boost::posix_time::milliseconds(BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS); - if (!m_mutex.timed_lock(wait_time)) - { - throw interprocess_exception(timeout_when_locking_error - , "Interprocess mutex timeout when locking. Possible deadlock: " - "owner died without unlocking?"); - } - #else - m_mutex.lock(); - #endif -} - -inline bool interprocess_mutex::try_lock() -{ return m_mutex.try_lock(); } - -inline bool interprocess_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ return m_mutex.timed_lock(abs_time); } - -inline void interprocess_mutex::unlock() -{ m_mutex.unlock(); } +inline void interprocess_mutex::lock(){ mutex.lock(); } +inline bool interprocess_mutex::try_lock(){ return mutex.try_lock(); } +inline bool interprocess_mutex::timed_lock(const boost::posix_time::ptime &abs_time){ return mutex.timed_lock(abs_time); } +inline void interprocess_mutex::unlock(){ mutex.unlock(); } } //namespace interprocess { } //namespace boost { +#endif + +#ifdef BOOST_INTERPROCESS_USE_POSIX +#include +# undef BOOST_INTERPROCESS_USE_POSIX +#endif + #include #endif //BOOST_INTERPROCESS_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_recursive_mutex.hpp index 1c5dad37..818cc2cf 100644 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_recursive_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/interprocess_recursive_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -40,21 +40,19 @@ #if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && \ (defined(BOOST_INTERPROCESS_POSIX_PROCESS_SHARED) && defined (BOOST_INTERPROCESS_POSIX_RECURSIVE_MUTEXES)) - #include + #include + #include + #include #define BOOST_INTERPROCESS_USE_POSIX -//Experimental... -#elif !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#elif !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) - #include +#else + #include #define BOOST_INTERPROCESS_USE_GENERIC_EMULATION #endif #if defined (BOOST_INTERPROCESS_USE_GENERIC_EMULATION) namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ namespace robust_emulation_helpers { template @@ -72,8 +70,8 @@ class mutex_traits; namespace boost { namespace interprocess { -//!Wraps a interprocess_mutex that can be placed in shared memory and can be -//!shared between processes. Allows several locking calls by the same +//!Wraps a interprocess_mutex that can be placed in shared memory and can be +//!shared between processes. Allows several locking calls by the same //!process. Allows timed lock tries class interprocess_recursive_mutex { @@ -99,7 +97,7 @@ class interprocess_recursive_mutex //!Throws: interprocess_exception on error. void lock(); - //!Tries to lock the interprocess_mutex, returns false when interprocess_mutex + //!Tries to lock the interprocess_mutex, returns false when interprocess_mutex //!is already locked, returns true when success. The mutex must be unlocked //!the same number of times it is locked. //!Throws: interprocess_exception if a severe error is found @@ -120,58 +118,41 @@ class interprocess_recursive_mutex private: #if defined (BOOST_INTERPROCESS_USE_GENERIC_EMULATION) - #undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION - void take_ownership(){ mutex.take_ownership(); } - friend class ipcdetail::robust_emulation_helpers::mutex_traits; - ipcdetail::spin_recursive_mutex mutex; - #elif defined(BOOST_INTERPROCESS_USE_POSIX) - #undef BOOST_INTERPROCESS_USE_POSIX - ipcdetail::posix_recursive_mutex mutex; - #elif defined(BOOST_INTERPROCESS_USE_WINDOWS) - #undef BOOST_INTERPROCESS_USE_WINDOWS - ipcdetail::windows_recursive_mutex mutex; - #else - #error "Unknown platform for interprocess_mutex" - #endif + void take_ownership(){ mutex.take_ownership(); } + friend class detail::robust_emulation_helpers::mutex_traits; + detail::emulation_recursive_mutex mutex; + #else //#if defined (BOOST_INTERPROCESS_USE_GENERIC_EMULATION) + pthread_mutex_t m_mut; + #endif //#if (defined BOOST_INTERPROCESS_WINDOWS) /// @endcond }; } //namespace interprocess { } //namespace boost { +#ifdef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION + namespace boost { namespace interprocess { inline interprocess_recursive_mutex::interprocess_recursive_mutex(){} - inline interprocess_recursive_mutex::~interprocess_recursive_mutex(){} - -inline void interprocess_recursive_mutex::lock() -{ - #ifdef BOOST_INTERPROCESS_ENABLE_TIMEOUT_WHEN_LOCKING - boost::posix_time::ptime wait_time - = boost::posix_time::microsec_clock::universal_time() - + boost::posix_time::milliseconds(BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS); - if (!mutex.timed_lock(wait_time)){ - throw interprocess_exception(timeout_when_locking_error, "Interprocess mutex timeout when locking. Possible deadlock: owner died without unlocking?"); - } - #else - mutex.lock(); - #endif -} - -inline bool interprocess_recursive_mutex::try_lock() -{ return mutex.try_lock(); } - -inline bool interprocess_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ return mutex.timed_lock(abs_time); } - -inline void interprocess_recursive_mutex::unlock() -{ mutex.unlock(); } +inline void interprocess_recursive_mutex::lock(){ mutex.lock(); } +inline bool interprocess_recursive_mutex::try_lock(){ return mutex.try_lock(); } +inline bool interprocess_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time){ return mutex.timed_lock(abs_time); } +inline void interprocess_recursive_mutex::unlock(){ mutex.unlock(); } } //namespace interprocess { } //namespace boost { +#endif + +#ifdef BOOST_INTERPROCESS_USE_POSIX +# undef BOOST_INTERPROCESS_USE_POSIX +#include +#endif + #include #endif //BOOST_INTERPROCESS_RECURSIVE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_semaphore.hpp index 2fe05818..33b17c9c 100644 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_semaphore.hpp +++ b/utils/boost_idb/boost/interprocess/sync/interprocess_semaphore.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,21 +19,23 @@ #include #include - #include #include #include #if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && \ (defined(BOOST_INTERPROCESS_POSIX_PROCESS_SHARED) && defined(BOOST_INTERPROCESS_POSIX_NAMED_SEMAPHORES)) - #include + #include //O_CREAT, O_*... + #include //close + #include //std::string + #include //sem_* family, SEM_VALUE_MAX + #include //mode_t, S_IRWXG, S_IRWXO, S_IRWXU, + #include #define BOOST_INTERPROCESS_USE_POSIX -//Experimental... -#elif !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#elif !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) - #include +#else + #include + #include + #include #define BOOST_INTERPROCESS_USE_GENERIC_EMULATION #endif @@ -43,9 +45,10 @@ //!Describes a interprocess_semaphore class for inter-process synchronization namespace boost { + namespace interprocess { -//!Wraps a interprocess_semaphore that can be placed in shared memory and can be +//!Wraps a interprocess_semaphore that can be placed in shared memory and can be //!shared between processes. Allows timed lock tries class interprocess_semaphore { @@ -55,7 +58,7 @@ class interprocess_semaphore interprocess_semaphore &operator=(const interprocess_semaphore &); /// @endcond public: - //!Creates a interprocess_semaphore with the given initial count. + //!Creates a interprocess_semaphore with the given initial count. //!interprocess_exception if there is an error.*/ interprocess_semaphore(unsigned int initialCount); @@ -69,7 +72,7 @@ class interprocess_semaphore void post(); //!Decrements the interprocess_semaphore. If the interprocess_semaphore value is not greater than zero, - //!then the calling process/thread blocks until it can decrement the counter. + //!then the calling process/thread blocks until it can decrement the counter. //!If there is an error an interprocess_exception exception is thrown. void wait(); @@ -90,55 +93,26 @@ class interprocess_semaphore /// @cond private: #if defined(BOOST_INTERPROCESS_USE_GENERIC_EMULATION) - #undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION - ipcdetail::spin_semaphore m_sem; - #elif defined(BOOST_INTERPROCESS_USE_WINDOWS) - #undef BOOST_INTERPROCESS_USE_WINDOWS - ipcdetail::windows_semaphore m_sem; - #else - #undef BOOST_INTERPROCESS_USE_POSIX - ipcdetail::posix_semaphore m_sem; + volatile boost::uint32_t m_count; + #else + detail::semaphore_wrapper m_sem; #endif //#if defined(BOOST_INTERPROCESS_USE_GENERIC_EMULATION) /// @endcond }; } //namespace interprocess { -} //namespace boost { - -namespace boost { -namespace interprocess { - -inline interprocess_semaphore::interprocess_semaphore(unsigned int initialCount) - : m_sem(initialCount) -{} -inline interprocess_semaphore::~interprocess_semaphore(){} +} //namespace boost { -inline void interprocess_semaphore::wait() -{ - #ifdef BOOST_INTERPROCESS_ENABLE_TIMEOUT_WHEN_LOCKING - boost::posix_time::ptime wait_time - = boost::posix_time::microsec_clock::universal_time() - + boost::posix_time::milliseconds(BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS); - if (!m_sem.timed_wait(wait_time)) - { - throw interprocess_exception(timeout_when_waiting_error, "Interprocess semaphore timeout when waiting. Possible deadlock: owner died without posting?"); - } - #else - m_sem.wait(); - #endif -} -inline bool interprocess_semaphore::try_wait() -{ return m_sem.try_wait(); } - -inline bool interprocess_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) -{ return m_sem.timed_wait(abs_time); } - -inline void interprocess_semaphore::post() -{ m_sem.post(); } +#ifdef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# undef BOOST_INTERPROCESS_USE_GENERIC_EMULATION +# include +#endif -} //namespace interprocess { -} //namespace boost { +#ifdef BOOST_INTERPROCESS_USE_POSIX +# undef BOOST_INTERPROCESS_USE_POSIX +# include +#endif #include diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_sharable_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_sharable_mutex.hpp deleted file mode 100644 index 98eeea41..00000000 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_sharable_mutex.hpp +++ /dev/null @@ -1,347 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// Code based on Howard Hinnant's shared_mutex class -// -// (C) Copyright Howard Hinnant 2007-2010. Distributed under the Boost -// Software License, Version 1.0. (see http://www.boost.org/LICENSE_1_0.txt) -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_SHARABLE_MUTEX_HPP -#define BOOST_INTERPROCESS_SHARABLE_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include - - -//!\file -//!Describes interprocess_sharable_mutex class - -namespace boost { -namespace interprocess { - -//!Wraps a interprocess_sharable_mutex that can be placed in shared memory and can be -//!shared between processes. Allows timed lock tries -class interprocess_sharable_mutex -{ - //Non-copyable - interprocess_sharable_mutex(const interprocess_sharable_mutex &); - interprocess_sharable_mutex &operator=(const interprocess_sharable_mutex &); - - friend class interprocess_condition; - public: - - //!Constructs the sharable lock. - //!Throws interprocess_exception on error. - interprocess_sharable_mutex(); - - //!Destroys the sharable lock. - //!Does not throw. - ~interprocess_sharable_mutex(); - - //Exclusive locking - - //!Effects: The calling thread tries to obtain exclusive ownership of the mutex, - //! and if another thread has exclusive or sharable ownership of - //! the mutex, it waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock(); - - //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! without waiting. If no other thread has exclusive or sharable - //! ownership of the mutex this succeeds. - //!Returns: If it can acquire exclusive ownership immediately returns true. - //! If it has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock(); - - //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! waiting if necessary until no other thread has exclusive or sharable - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The calling thread releases the exclusive ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock(); - - //Sharable locking - - //!Effects: The calling thread tries to obtain sharable ownership of the mutex, - //! and if another thread has exclusive ownership of the mutex, - //! waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock_sharable(); - - //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! without waiting. If no other thread has exclusive ownership - //! of the mutex this succeeds. - //!Returns: If it can acquire sharable ownership immediately returns true. If it - //! has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock_sharable(); - - //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! waiting if necessary until no other thread has exclusive - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock_sharable(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The calling thread releases the sharable ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_sharable(); - - /// @cond - private: - typedef scoped_lock scoped_lock_t; - - //Pack all the control data in a word to be able - //to use atomic instructions in the future - struct control_word_t - { - unsigned exclusive_in : 1; - unsigned num_shared : sizeof(unsigned)*CHAR_BIT-1; - } m_ctrl; - - interprocess_mutex m_mut; - interprocess_condition m_first_gate; - interprocess_condition m_second_gate; - - private: - //Rollback structures for exceptions or failure return values - struct exclusive_rollback - { - exclusive_rollback(control_word_t &ctrl - ,interprocess_condition &first_gate) - : mp_ctrl(&ctrl), m_first_gate(first_gate) - {} - - void release() - { mp_ctrl = 0; } - - ~exclusive_rollback() - { - if(mp_ctrl){ - mp_ctrl->exclusive_in = 0; - m_first_gate.notify_all(); - } - } - control_word_t *mp_ctrl; - interprocess_condition &m_first_gate; - }; - - template - struct base_constants_t - { - static const unsigned max_readers - = ~(unsigned(1) << (sizeof(unsigned)*CHAR_BIT-1)); - }; - typedef base_constants_t<0> constants; - /// @endcond -}; - -/// @cond - -template -const unsigned interprocess_sharable_mutex::base_constants_t::max_readers; - -inline interprocess_sharable_mutex::interprocess_sharable_mutex() -{ - this->m_ctrl.exclusive_in = 0; - this->m_ctrl.num_shared = 0; -} - -inline interprocess_sharable_mutex::~interprocess_sharable_mutex() -{} - -inline void interprocess_sharable_mutex::lock() -{ - scoped_lock_t lck(m_mut); - - //The exclusive lock must block in the first gate - //if an exclusive lock has been acquired - while (this->m_ctrl.exclusive_in){ - this->m_first_gate.wait(lck); - } - - //Mark that exclusive lock has been acquired - this->m_ctrl.exclusive_in = 1; - - //Prepare rollback - exclusive_rollback rollback(this->m_ctrl, this->m_first_gate); - - //Now wait until all readers are gone - while (this->m_ctrl.num_shared){ - this->m_second_gate.wait(lck); - } - rollback.release(); -} - -inline bool interprocess_sharable_mutex::try_lock() -{ - scoped_lock_t lck(m_mut, try_to_lock); - - //If we can't lock or any has there is any exclusive - //or sharable mark return false; - if(!lck.owns() - || this->m_ctrl.exclusive_in - || this->m_ctrl.num_shared){ - return false; - } - this->m_ctrl.exclusive_in = 1; - return true; -} - -inline bool interprocess_sharable_mutex::timed_lock - (const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - scoped_lock_t lck(m_mut, abs_time); - if(!lck.owns()) return false; - - //The exclusive lock must block in the first gate - //if an exclusive lock has been acquired - while (this->m_ctrl.exclusive_in){ - if(!this->m_first_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.exclusive_in){ - return false; - } - break; - } - } - - //Mark that exclusive lock has been acquired - this->m_ctrl.exclusive_in = 1; - - //Prepare rollback - exclusive_rollback rollback(this->m_ctrl, this->m_first_gate); - - //Now wait until all readers are gone - while (this->m_ctrl.num_shared){ - if(!this->m_second_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.num_shared){ - return false; - } - break; - } - } - rollback.release(); - return true; -} - -inline void interprocess_sharable_mutex::unlock() -{ - scoped_lock_t lck(m_mut); - this->m_ctrl.exclusive_in = 0; - this->m_first_gate.notify_all(); -} - -//Sharable locking - -inline void interprocess_sharable_mutex::lock_sharable() -{ - scoped_lock_t lck(m_mut); - - //The sharable lock must block in the first gate - //if an exclusive lock has been acquired - //or there are too many sharable locks - while(this->m_ctrl.exclusive_in - || this->m_ctrl.num_shared == constants::max_readers){ - this->m_first_gate.wait(lck); - } - - //Increment sharable count - ++this->m_ctrl.num_shared; -} - -inline bool interprocess_sharable_mutex::try_lock_sharable() -{ - scoped_lock_t lck(m_mut, try_to_lock); - - //The sharable lock must fail - //if an exclusive lock has been acquired - //or there are too many sharable locks - if(!lck.owns() - || this->m_ctrl.exclusive_in - || this->m_ctrl.num_shared == constants::max_readers){ - return false; - } - - //Increment sharable count - ++this->m_ctrl.num_shared; - return true; -} - -inline bool interprocess_sharable_mutex::timed_lock_sharable - (const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock_sharable(); - return true; - } - scoped_lock_t lck(m_mut, abs_time); - if(!lck.owns()) return false; - - //The sharable lock must block in the first gate - //if an exclusive lock has been acquired - //or there are too many sharable locks - while (this->m_ctrl.exclusive_in - || this->m_ctrl.num_shared == constants::max_readers){ - if(!this->m_first_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.exclusive_in - || this->m_ctrl.num_shared == constants::max_readers){ - return false; - } - break; - } - } - - //Increment sharable count - ++this->m_ctrl.num_shared; - return true; -} - -inline void interprocess_sharable_mutex::unlock_sharable() -{ - scoped_lock_t lck(m_mut); - //Decrement sharable count - --this->m_ctrl.num_shared; - if (this->m_ctrl.num_shared == 0){ - this->m_second_gate.notify_one(); - } - //Check if there are blocked sharables because of - //there were too many sharables - else if(this->m_ctrl.num_shared == (constants::max_readers-1)){ - this->m_first_gate.notify_all(); - } -} - -/// @endcond - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_SHARABLE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/interprocess_upgradable_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/interprocess_upgradable_mutex.hpp index 0ba6b4a9..551de0a2 100644 --- a/utils/boost_idb/boost/interprocess/sync/interprocess_upgradable_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/interprocess_upgradable_mutex.hpp @@ -1,8 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Code based on Howard Hinnant's upgrade_mutex class +////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -20,7 +18,6 @@ #include #include #include -#include #include #include #include @@ -32,7 +29,7 @@ namespace boost { namespace interprocess { -//!Wraps a interprocess_upgradable_mutex that can be placed in shared memory and can be +//!Wraps a interprocess_upgradable_mutex that can be placed in shared memory and can be //!shared between processes. Allows timed lock tries class interprocess_upgradable_mutex { @@ -68,42 +65,42 @@ class interprocess_upgradable_mutex bool try_lock(); //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! waiting if necessary until no other thread has exclusive, sharable or - //! upgradable ownership of the mutex or abs_time is reached. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //! waiting if necessary until no other thread has has exclusive, sharable or + //! upgradable ownership of the mutex or abs_time is reached. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The calling thread releases the exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. + //!Effects: The calling thread releases the exclusive ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock(); //Sharable locking //!Effects: The calling thread tries to obtain sharable ownership of the mutex, - //! and if another thread has exclusive ownership of the mutex, + //! and if another thread has exclusive or upgradable ownership of the mutex, //! waits until it can obtain the ownership. //!Throws: interprocess_exception on error. void lock_sharable(); //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! without waiting. If no other thread has exclusive ownership - //! of the mutex this succeeds. + //! without waiting. If no other thread has has exclusive or upgradable ownership + //! of the mutex this succeeds. //!Returns: If it can acquire sharable ownership immediately returns true. If it - //! has to wait, returns false. + //! has to wait, returns false. //!Throws: interprocess_exception on error. bool try_lock_sharable(); //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! waiting if necessary until no other thread has exclusive - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. + //! waiting if necessary until no other thread has has exclusive or upgradable + //! ownership of the mutex or abs_time is reached. + //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock_sharable(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The calling thread releases the sharable ownership of the mutex. + //!Precondition: The thread must have sharable ownership of the mutex. + //!Effects: The calling thread releases the sharable ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock_sharable(); @@ -116,84 +113,84 @@ class interprocess_upgradable_mutex void lock_upgradable(); //!Effects: The calling thread tries to acquire upgradable ownership of the mutex - //! without waiting. If no other thread has exclusive or upgradable ownership - //! of the mutex this succeeds. + //! without waiting. If no other thread has has exclusive or upgradable ownership + //! of the mutex this succeeds. //!Returns: If it can acquire upgradable ownership immediately returns true. //! If it has to wait, returns false. //!Throws: interprocess_exception on error. bool try_lock_upgradable(); //!Effects: The calling thread tries to acquire upgradable ownership of the mutex - //! waiting if necessary until no other thread has exclusive or upgradable + //! waiting if necessary until no other thread has has exclusive or upgradable //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. + //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock_upgradable(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The calling thread releases the upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. + //!Effects: The calling thread releases the upgradable ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock_upgradable(); //Demotions - //!Precondition: The thread must have exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. //!Effects: The thread atomically releases exclusive ownership and acquires - //! upgradable ownership. This operation is non-blocking. + //! upgradable ownership. This operation is non-blocking. //!Throws: An exception derived from interprocess_exception on error. void unlock_and_lock_upgradable(); - //!Precondition: The thread must have exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. //!Effects: The thread atomically releases exclusive ownership and acquires - //! sharable ownership. This operation is non-blocking. + //! sharable ownership. This operation is non-blocking. //!Throws: An exception derived from interprocess_exception on error. void unlock_and_lock_sharable(); - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and acquires - //! sharable ownership. This operation is non-blocking. + //! sharable ownership. This operation is non-blocking. //!Throws: An exception derived from interprocess_exception on error. void unlock_upgradable_and_lock_sharable(); //Promotions - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and acquires //! exclusive ownership. This operation will block until all threads with - //! sharable ownership release their sharable lock. + //! sharable ownership release their sharable lock. //!Throws: An exception derived from interprocess_exception on error. void unlock_upgradable_and_lock(); - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and tries to //! acquire exclusive ownership. This operation will fail if there are threads - //! with sharable ownership, but it will maintain upgradable ownership. + //! with sharable ownership, but it will maintain upgradable ownership. //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. bool try_unlock_upgradable_and_lock(); - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and tries to acquire //! exclusive ownership, waiting if necessary until abs_time. This operation will //! fail if there are threads with sharable ownership or timeout reaches, but it - //! will maintain upgradable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //! will maintain upgradable ownership. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. */ bool timed_unlock_upgradable_and_lock(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have sharable ownership of the mutex. + //!Precondition: The thread must have sharable ownership of the mutex. //!Effects: The thread atomically releases sharable ownership and tries to acquire //! exclusive ownership. This operation will fail if there are threads with sharable //! or upgradable ownership, but it will maintain sharable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. bool try_unlock_sharable_and_lock(); - //!Precondition: The thread must have sharable ownership of the mutex. + //!Precondition: The thread must have sharable ownership of the mutex. //!Effects: The thread atomically releases sharable ownership and tries to acquire //! upgradable ownership. This operation will fail if there are threads with sharable - //! or upgradable ownership, but it will maintain sharable ownership. - //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. + //! or upgradable ownership, but it will maintain sharable ownership. + //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. bool try_unlock_sharable_and_lock_upgradable(); @@ -251,7 +248,7 @@ class interprocess_upgradable_mutex if(mp_ctrl){ //Recover upgradable lock mp_ctrl->upgradable_in = 1; - ++mp_ctrl->num_upr_shar; + ++mp_ctrl->num_upr_shar; //Execute the second half of exclusive locking mp_ctrl->exclusive_in = 0; } @@ -262,7 +259,7 @@ class interprocess_upgradable_mutex template struct base_constants_t { - static const unsigned max_readers + static const unsigned max_readers = ~(unsigned(3) << (sizeof(unsigned)*CHAR_BIT-2)); }; typedef base_constants_t<0> constants; @@ -286,12 +283,12 @@ inline interprocess_upgradable_mutex::~interprocess_upgradable_mutex() inline void interprocess_upgradable_mutex::lock() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //The exclusive lock must block in the first gate //if an exclusive or upgradable lock has been acquired while (this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in){ - this->m_first_gate.wait(lck); + this->m_first_gate.wait(lock); } //Mark that exclusive lock has been acquired @@ -302,19 +299,19 @@ inline void interprocess_upgradable_mutex::lock() //Now wait until all readers are gone while (this->m_ctrl.num_upr_shar){ - this->m_second_gate.wait(lck); + this->m_second_gate.wait(lock); } rollback.release(); } inline bool interprocess_upgradable_mutex::try_lock() { - scoped_lock_t lck(m_mut, try_to_lock); + scoped_lock_t lock(m_mut, try_to_lock); - //If we can't lock or any has there is any exclusive, upgradable + //If we can't lock or any has there is any exclusive, upgradable //or sharable mark return false; - if(!lck.owns() - || this->m_ctrl.exclusive_in + if(!lock.owns() + || this->m_ctrl.exclusive_in || this->m_ctrl.num_upr_shar){ return false; } @@ -329,18 +326,14 @@ inline bool interprocess_upgradable_mutex::timed_lock this->lock(); return true; } - scoped_lock_t lck(m_mut, abs_time); - if(!lck.owns()) return false; + scoped_lock_t lock(m_mut, abs_time); + if(!lock.owns()) return false; //The exclusive lock must block in the first gate //if an exclusive or upgradable lock has been acquired while (this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in){ - if(!this->m_first_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in){ - return false; - } - break; - } + if(!this->m_first_gate.timed_wait(lock, abs_time)) + return !(this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in); } //Mark that exclusive lock has been acquired @@ -351,11 +344,8 @@ inline bool interprocess_upgradable_mutex::timed_lock //Now wait until all readers are gone while (this->m_ctrl.num_upr_shar){ - if(!this->m_second_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.num_upr_shar){ - return false; - } - break; + if(!this->m_second_gate.timed_wait(lock, abs_time)){ + return !(this->m_ctrl.num_upr_shar); } } rollback.release(); @@ -364,7 +354,7 @@ inline bool interprocess_upgradable_mutex::timed_lock inline void interprocess_upgradable_mutex::unlock() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); this->m_ctrl.exclusive_in = 0; this->m_first_gate.notify_all(); } @@ -373,14 +363,14 @@ inline void interprocess_upgradable_mutex::unlock() inline void interprocess_upgradable_mutex::lock_upgradable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //The upgradable lock must block in the first gate //if an exclusive or upgradable lock has been acquired //or there are too many sharable locks while(this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in || this->m_ctrl.num_upr_shar == constants::max_readers){ - this->m_first_gate.wait(lck); + this->m_first_gate.wait(lock); } //Mark that upgradable lock has been acquired @@ -391,14 +381,14 @@ inline void interprocess_upgradable_mutex::lock_upgradable() inline bool interprocess_upgradable_mutex::try_lock_upgradable() { - scoped_lock_t lck(m_mut, try_to_lock); + scoped_lock_t lock(m_mut, try_to_lock); //The upgradable lock must fail //if an exclusive or upgradable lock has been acquired //or there are too many sharable locks - if(!lck.owns() - || this->m_ctrl.exclusive_in - || this->m_ctrl.upgradable_in + if(!lock.owns() + || this->m_ctrl.exclusive_in + || this->m_ctrl.upgradable_in || this->m_ctrl.num_upr_shar == constants::max_readers){ return false; } @@ -417,22 +407,19 @@ inline bool interprocess_upgradable_mutex::timed_lock_upgradable this->lock_upgradable(); return true; } - scoped_lock_t lck(m_mut, abs_time); - if(!lck.owns()) return false; + scoped_lock_t lock(m_mut, abs_time); + if(!lock.owns()) return false; //The upgradable lock must block in the first gate //if an exclusive or upgradable lock has been acquired //or there are too many sharable locks - while(this->m_ctrl.exclusive_in + while(this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in || this->m_ctrl.num_upr_shar == constants::max_readers){ - if(!this->m_first_gate.timed_wait(lck, abs_time)){ - if((this->m_ctrl.exclusive_in - || this->m_ctrl.upgradable_in - || this->m_ctrl.num_upr_shar == constants::max_readers)){ - return false; - } - break; + if(!this->m_first_gate.timed_wait(lock, abs_time)){ + return!(this->m_ctrl.exclusive_in + || this->m_ctrl.upgradable_in + || this->m_ctrl.num_upr_shar == constants::max_readers); } } @@ -445,7 +432,7 @@ inline bool interprocess_upgradable_mutex::timed_lock_upgradable inline void interprocess_upgradable_mutex::unlock_upgradable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //Mark that upgradable lock has been acquired //And add upgradable to the sharable count this->m_ctrl.upgradable_in = 0; @@ -457,14 +444,14 @@ inline void interprocess_upgradable_mutex::unlock_upgradable() inline void interprocess_upgradable_mutex::lock_sharable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //The sharable lock must block in the first gate //if an exclusive lock has been acquired //or there are too many sharable locks while(this->m_ctrl.exclusive_in || this->m_ctrl.num_upr_shar == constants::max_readers){ - this->m_first_gate.wait(lck); + this->m_first_gate.wait(lock); } //Increment sharable count @@ -473,12 +460,12 @@ inline void interprocess_upgradable_mutex::lock_sharable() inline bool interprocess_upgradable_mutex::try_lock_sharable() { - scoped_lock_t lck(m_mut, try_to_lock); + scoped_lock_t lock(m_mut, try_to_lock); //The sharable lock must fail //if an exclusive lock has been acquired //or there are too many sharable locks - if(!lck.owns() + if(!lock.owns() || this->m_ctrl.exclusive_in || this->m_ctrl.num_upr_shar == constants::max_readers){ return false; @@ -496,20 +483,17 @@ inline bool interprocess_upgradable_mutex::timed_lock_sharable this->lock_sharable(); return true; } - scoped_lock_t lck(m_mut, abs_time); - if(!lck.owns()) return false; + scoped_lock_t lock(m_mut, abs_time); + if(!lock.owns()) return false; //The sharable lock must block in the first gate //if an exclusive lock has been acquired //or there are too many sharable locks while (this->m_ctrl.exclusive_in || this->m_ctrl.num_upr_shar == constants::max_readers){ - if(!this->m_first_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.exclusive_in - || this->m_ctrl.num_upr_shar == constants::max_readers){ - return false; - } - break; + if(!this->m_first_gate.timed_wait(lock, abs_time)){ + return!(this->m_ctrl.exclusive_in + || this->m_ctrl.num_upr_shar == constants::max_readers); } } @@ -520,7 +504,7 @@ inline bool interprocess_upgradable_mutex::timed_lock_sharable inline void interprocess_upgradable_mutex::unlock_sharable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //Decrement sharable count --this->m_ctrl.num_upr_shar; if (this->m_ctrl.num_upr_shar == 0){ @@ -537,7 +521,7 @@ inline void interprocess_upgradable_mutex::unlock_sharable() inline void interprocess_upgradable_mutex::unlock_and_lock_upgradable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //Unmark it as exclusive this->m_ctrl.exclusive_in = 0; //Mark it as upgradable @@ -550,7 +534,7 @@ inline void interprocess_upgradable_mutex::unlock_and_lock_upgradable() inline void interprocess_upgradable_mutex::unlock_and_lock_sharable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //Unmark it as exclusive this->m_ctrl.exclusive_in = 0; //The sharable count should be 0 so increment it @@ -561,7 +545,7 @@ inline void interprocess_upgradable_mutex::unlock_and_lock_sharable() inline void interprocess_upgradable_mutex::unlock_upgradable_and_lock_sharable() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //Unmark it as upgradable (we don't have to decrement count) this->m_ctrl.upgradable_in = 0; //Notify readers/upgradable that they can enter @@ -572,11 +556,11 @@ inline void interprocess_upgradable_mutex::unlock_upgradable_and_lock_sharable() inline void interprocess_upgradable_mutex::unlock_upgradable_and_lock() { - scoped_lock_t lck(m_mut); + scoped_lock_t lock(m_mut); //Simulate unlock_upgradable() without //notifying sharables. this->m_ctrl.upgradable_in = 0; - --this->m_ctrl.num_upr_shar; + --this->m_ctrl.num_upr_shar; //Execute the second half of exclusive locking this->m_ctrl.exclusive_in = 1; @@ -584,22 +568,22 @@ inline void interprocess_upgradable_mutex::unlock_upgradable_and_lock() upgradable_to_exclusive_rollback rollback(m_ctrl); while (this->m_ctrl.num_upr_shar){ - this->m_second_gate.wait(lck); + this->m_second_gate.wait(lock); } rollback.release(); } inline bool interprocess_upgradable_mutex::try_unlock_upgradable_and_lock() { - scoped_lock_t lck(m_mut, try_to_lock); + scoped_lock_t lock(m_mut, try_to_lock); //Check if there are no readers - if(!lck.owns() + if(!lock.owns() || this->m_ctrl.num_upr_shar != 1){ return false; } //Now unlock upgradable and mark exclusive this->m_ctrl.upgradable_in = 0; - --this->m_ctrl.num_upr_shar; + --this->m_ctrl.num_upr_shar; this->m_ctrl.exclusive_in = 1; return true; } @@ -607,17 +591,13 @@ inline bool interprocess_upgradable_mutex::try_unlock_upgradable_and_lock() inline bool interprocess_upgradable_mutex::timed_unlock_upgradable_and_lock (const boost::posix_time::ptime &abs_time) { - if(abs_time == boost::posix_time::pos_infin){ - this->unlock_upgradable_and_lock(); - return true; - } - scoped_lock_t lck(m_mut, abs_time); - if(!lck.owns()) return false; + scoped_lock_t lock(m_mut, abs_time); + if(!lock.owns()) return false; //Simulate unlock_upgradable() without //notifying sharables. this->m_ctrl.upgradable_in = 0; - --this->m_ctrl.num_upr_shar; + --this->m_ctrl.num_upr_shar; //Execute the second half of exclusive locking this->m_ctrl.exclusive_in = 1; @@ -625,11 +605,8 @@ inline bool interprocess_upgradable_mutex::timed_unlock_upgradable_and_lock upgradable_to_exclusive_rollback rollback(m_ctrl); while (this->m_ctrl.num_upr_shar){ - if(!this->m_second_gate.timed_wait(lck, abs_time)){ - if(this->m_ctrl.num_upr_shar){ - return false; - } - break; + if(!this->m_second_gate.timed_wait(lock, abs_time)){ + return !(this->m_ctrl.num_upr_shar); } } rollback.release(); @@ -638,12 +615,12 @@ inline bool interprocess_upgradable_mutex::timed_unlock_upgradable_and_lock inline bool interprocess_upgradable_mutex::try_unlock_sharable_and_lock() { - scoped_lock_t lck(m_mut, try_to_lock); + scoped_lock_t lock(m_mut, try_to_lock); - //If we can't lock or any has there is any exclusive, upgradable + //If we can't lock or any has there is any exclusive, upgradable //or sharable mark return false; - if(!lck.owns() - || this->m_ctrl.exclusive_in + if(!lock.owns() + || this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in || this->m_ctrl.num_upr_shar != 1){ return false; @@ -655,12 +632,12 @@ inline bool interprocess_upgradable_mutex::try_unlock_sharable_and_lock() inline bool interprocess_upgradable_mutex::try_unlock_sharable_and_lock_upgradable() { - scoped_lock_t lck(m_mut, try_to_lock); + scoped_lock_t lock(m_mut, try_to_lock); //The upgradable lock must fail //if an exclusive or upgradable lock has been acquired - if(!lck.owns() - || this->m_ctrl.exclusive_in + if(!lock.owns() + || this->m_ctrl.exclusive_in || this->m_ctrl.upgradable_in){ return false; } diff --git a/utils/boost_idb/boost/interprocess/sync/lock_options.hpp b/utils/boost_idb/boost/interprocess/sync/lock_options.hpp index 1139d83a..05c0d7e6 100644 --- a/utils/boost_idb/boost/interprocess/sync/lock_options.hpp +++ b/utils/boost_idb/boost/interprocess/sync/lock_options.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/utils/boost_idb/boost/interprocess/sync/mutex_family.hpp b/utils/boost_idb/boost/interprocess/sync/mutex_family.hpp index 0636de0d..1f4ced2c 100644 --- a/utils/boost_idb/boost/interprocess/sync/mutex_family.hpp +++ b/utils/boost_idb/boost/interprocess/sync/mutex_family.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -29,7 +29,7 @@ namespace boost { namespace interprocess { -//!Describes interprocess_mutex family to use with Interprocess framework +//!Describes interprocess_mutex family to use with Interprocess framework //!based on boost::interprocess synchronization objects. struct mutex_family { @@ -37,7 +37,7 @@ struct mutex_family typedef boost::interprocess::interprocess_recursive_mutex recursive_mutex_type; }; -//!Describes interprocess_mutex family to use with Interprocess frameworks +//!Describes interprocess_mutex family to use with Interprocess frameworks //!based on null operation synchronization objects. struct null_mutex_family { diff --git a/utils/boost_idb/boost/interprocess/sync/named_condition.hpp b/utils/boost_idb/boost/interprocess/sync/named_condition.hpp index 7c570f4b..a38d4181 100644 --- a/utils/boost_idb/boost/interprocess/sync/named_condition.hpp +++ b/utils/boost_idb/boost/interprocess/sync/named_condition.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,27 +17,31 @@ #include #include +#include +#include #include #include -#include -#include +#include +#include +#include #include -#include -#if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#else - #include +#include +#include +#include +#if defined BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES +#include +#include #endif + //!\file -//!Describes a named condition class for inter-process synchronization +//!Describes process-shared variables interprocess_condition class namespace boost { namespace interprocess { /// @cond -namespace ipcdetail{ class interprocess_tester; } +namespace detail{ class interprocess_tester; } /// @endcond //! A global condition variable that can be created by name. @@ -56,7 +60,7 @@ class named_condition //!If the condition can't be created throws interprocess_exception named_condition(create_only_t create_only, const char *name, const permissions &perm = permissions()); - //!Opens or creates a global condition with a name. + //!Opens or creates a global condition with a name. //!If the condition is created, this call is equivalent to //!named_condition(create_only_t, ... ) //!If the condition is already created, this call is equivalent @@ -77,7 +81,7 @@ class named_condition //!use remove(). ~named_condition(); - //!If there is a thread waiting on *this, change that + //!If there is a thread waiting on *this, change that //!thread's state to ready. Otherwise there is no effect.*/ void notify_one(); @@ -85,8 +89,8 @@ class named_condition //!If there are no waiting threads, notify_all() has no effect. void notify_all(); - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to + //!Releases the lock on the named_mutex object associated with lock, blocks + //!the current thread of execution until readied by a call to //!this->notify_one() or this->notify_all(), and then reacquires the lock. template void wait(L& lock); @@ -96,16 +100,16 @@ class named_condition template void wait(L& lock, Pr pred); - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, + //!Releases the lock on the named_mutex object associated with lock, blocks + //!the current thread of execution until readied by a call to + //!this->notify_one() or this->notify_all(), or until time abs_time is reached, //!and then reacquires the lock. //!Returns: false if time abs_time is reached, otherwise true. template bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time); - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); + //!The same as: while (!pred()) { + //! if (!timed_wait(lock, abs_time)) return pred(); //! } return true; template bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred); @@ -116,16 +120,78 @@ class named_condition /// @cond private: - #if defined(BOOST_INTERPROCESS_USE_WINDOWS) - typedef ipcdetail::windows_named_condition condition_type; - #else - typedef ipcdetail::shm_named_condition condition_type; + + struct condition_holder + { + interprocess_condition cond_; + //If named_mutex is implemented using semaphores + //we need to store an additional mutex + #if defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) + interprocess_mutex mutex_; + #endif + }; + + interprocess_condition *condition() const + { return &static_cast(m_shmem.get_user_address())->cond_; } + + template + class lock_inverter + { + Lock &l_; + public: + lock_inverter(Lock &l) + : l_(l) + {} + void lock() { l_.unlock(); } + void unlock() { l_.lock(); } + }; + + #if defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) + interprocess_mutex *mutex() const + { return &static_cast(m_shmem.get_user_address())->mutex_; } + + template + void do_wait(Lock& lock) + { + //named_condition only works with named_mutex + BOOST_STATIC_ASSERT((detail::is_convertible::value == true)); + + //lock internal before unlocking external to avoid race with a notifier + scoped_lock internal_lock(*this->mutex()); + lock_inverter inverted_lock(lock); + scoped_lock > external_unlock(inverted_lock); + + //unlock internal first to avoid deadlock with near simultaneous waits + scoped_lock internal_unlock; + internal_lock.swap(internal_unlock); + this->condition()->wait(internal_unlock); + } + + template + bool do_timed_wait(Lock& lock, const boost::posix_time::ptime &abs_time) + { + //named_condition only works with named_mutex + BOOST_STATIC_ASSERT((detail::is_convertible::value == true)); + //lock internal before unlocking external to avoid race with a notifier + scoped_lock internal_lock(*this->mutex(), abs_time); + if(!internal_lock) return false; + lock_inverter inverted_lock(lock); + scoped_lock > external_unlock(inverted_lock); + + //unlock internal first to avoid deadlock with near simultaneous waits + scoped_lock internal_unlock; + internal_lock.swap(internal_unlock); + return this->condition()->timed_wait(internal_unlock, abs_time); + } #endif - condition_type m_cond; - friend class ipcdetail::interprocess_tester; - void dont_close_on_destruction() - { ipcdetail::interprocess_tester::dont_close_on_destruction(m_cond); } + friend class detail::interprocess_tester; + void dont_close_on_destruction(); + + detail::managed_open_or_create_impl m_shmem; + + template friend class boost::interprocess::detail::named_creation_functor; + typedef detail::named_creation_functor construct_func_t; /// @endcond }; @@ -135,58 +201,166 @@ inline named_condition::~named_condition() {} inline named_condition::named_condition(create_only_t, const char *name, const permissions &perm) - : m_cond(create_only_t(), name, perm) + : m_shmem (create_only + ,name + ,sizeof(condition_holder) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoCreate) + ,perm) {} inline named_condition::named_condition(open_or_create_t, const char *name, const permissions &perm) - : m_cond(open_or_create_t(), name, perm) + : m_shmem (open_or_create + ,name + ,sizeof(condition_holder) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoOpenOrCreate) + ,perm) {} inline named_condition::named_condition(open_only_t, const char *name) - : m_cond(open_only_t(), name) + : m_shmem (open_only + ,name + ,read_write + ,0 + ,construct_func_t(detail::DoOpen)) {} +inline void named_condition::dont_close_on_destruction() +{ detail::interprocess_tester::dont_close_on_destruction(m_shmem); } + +#if defined(BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) + inline void named_condition::notify_one() -{ m_cond.notify_one(); } +{ + scoped_lock internal_lock(*this->mutex()); + this->condition()->notify_one(); +} inline void named_condition::notify_all() -{ m_cond.notify_all(); } +{ + scoped_lock internal_lock(*this->mutex()); + this->condition()->notify_all(); +} template inline void named_condition::wait(L& lock) { - ipcdetail::internal_mutex_lock internal_lock(lock); - m_cond.wait(internal_lock); + if (!lock) + throw lock_exception(); + this->do_wait(lock); } template inline void named_condition::wait(L& lock, Pr pred) { - ipcdetail::internal_mutex_lock internal_lock(lock); - m_cond.wait(internal_lock, pred); + if (!lock) + throw lock_exception(); + while (!pred()) + this->do_wait(lock); } template inline bool named_condition::timed_wait (L& lock, const boost::posix_time::ptime &abs_time) { - ipcdetail::internal_mutex_lock internal_lock(lock); - return m_cond.timed_wait(internal_lock, abs_time); + if(abs_time == boost::posix_time::pos_infin){ + this->wait(lock); + return true; + } + if (!lock) + throw lock_exception(); + return this->do_timed_wait(lock, abs_time); } template inline bool named_condition::timed_wait (L& lock, const boost::posix_time::ptime &abs_time, Pr pred) -{ - ipcdetail::internal_mutex_lock internal_lock(lock); - return m_cond.timed_wait(internal_lock, abs_time, pred); +{ + if(abs_time == boost::posix_time::pos_infin){ + this->wait(lock, pred); + return true; + } + if (!lock) + throw lock_exception(); + + while (!pred()){ + if(!this->do_timed_wait(lock, abs_time)){ + return pred(); + } + } + return true; } -inline bool named_condition::remove(const char *name) +#else + +inline void named_condition::notify_one() +{ this->condition()->notify_one(); } + +inline void named_condition::notify_all() +{ this->condition()->notify_all(); } + +template +inline void named_condition::wait(L& lock) { - return condition_type::remove(name); + if (!lock) + throw lock_exception(); + this->condition()->do_wait(*lock.mutex()->mutex()); } +template +inline void named_condition::wait(L& lock, Pr pred) +{ + if (!lock) + throw lock_exception(); + + while (!pred()) + this->condition()->do_wait(*lock.mutex()->mutex()); +} + +template +inline bool named_condition::timed_wait + (L& lock, const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->wait(lock); + return true; + } + if (!lock) + throw lock_exception(); + return this->condition()->do_timed_wait(abs_time, *lock.mutex()->mutex()); +} + +template +inline bool named_condition::timed_wait + (L& lock, const boost::posix_time::ptime &abs_time, Pr pred) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->wait(lock, pred); + return true; + } + if (!lock) + throw lock_exception(); + + while (!pred()){ + if (!this->condition()->do_timed_wait(abs_time, *lock.mutex()->mutex())) + return pred(); + } + + return true; +} + +#endif + +inline bool named_condition::remove(const char *name) +{ return shared_memory_object::remove(name); } + /// @endcond } //namespace interprocess diff --git a/utils/boost_idb/boost/interprocess/sync/named_condition_any.hpp b/utils/boost_idb/boost/interprocess/sync/named_condition_any.hpp deleted file mode 100644 index f8f204bc..00000000 --- a/utils/boost_idb/boost/interprocess/sync/named_condition_any.hpp +++ /dev/null @@ -1,151 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_NAMED_CONDITION_ANY_HPP -#define BOOST_INTERPROCESS_NAMED_CONDITION_ANY_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#else - #include -#endif - -//!\file -//!Describes a named condition class for inter-process synchronization - -namespace boost { -namespace interprocess { - -/// @cond -namespace ipcdetail{ class interprocess_tester; } -/// @endcond - -//! A global condition variable that can be created by name. -//! This condition variable is designed to work with named_mutex and -//! can't be placed in shared memory or memory mapped files. -class named_condition_any -{ - /// @cond - //Non-copyable - named_condition_any(); - named_condition_any(const named_condition_any &); - named_condition_any &operator=(const named_condition_any &); - /// @endcond - public: - //!Creates a global condition with a name. - //!If the condition can't be created throws interprocess_exception - named_condition_any(create_only_t, const char *name, const permissions &perm = permissions()) - : m_cond(create_only_t(), name, perm) - {} - - //!Opens or creates a global condition with a name. - //!If the condition is created, this call is equivalent to - //!named_condition_any(create_only_t, ... ) - //!If the condition is already created, this call is equivalent - //!named_condition_any(open_only_t, ... ) - //!Does not throw - named_condition_any(open_or_create_t, const char *name, const permissions &perm = permissions()) - : m_cond(open_or_create_t(), name, perm) - {} - - //!Opens a global condition with a name if that condition is previously - //!created. If it is not previously created this function throws - //!interprocess_exception. - named_condition_any(open_only_t, const char *name) - : m_cond(open_only_t(), name) - {} - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~named_condition_any() - {} - - //!If there is a thread waiting on *this, change that - //!thread's state to ready. Otherwise there is no effect.*/ - void notify_one() - { m_cond.notify_one(); } - - //!Change the state of all threads waiting on *this to ready. - //!If there are no waiting threads, notify_all() has no effect. - void notify_all() - { m_cond.notify_all(); } - - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), and then reacquires the lock. - template - void wait(L& lock) - { return m_cond.wait(lock); } - - //!The same as: - //!while (!pred()) wait(lock) - template - void wait(L& lock, Pr pred) - { return m_cond.wait(lock, pred); } - - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, - //!and then reacquires the lock. - //!Returns: false if time abs_time is reached, otherwise true. - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { return m_cond.timed_wait(lock, abs_time); } - - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); - //! } return true; - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { return m_cond.timed_wait(lock, abs_time, pred); } - - //!Erases a named condition from the system. - //!Returns false on error. Never throws. - static bool remove(const char *name) - { return condition_any_type::remove(name); } - - /// @cond - private: - #if defined(BOOST_INTERPROCESS_USE_WINDOWS) - typedef ipcdetail::windows_named_condition_any condition_any_type; - #else - typedef ipcdetail::shm_named_condition_any condition_any_type; - #endif - condition_any_type m_cond; - - friend class ipcdetail::interprocess_tester; - void dont_close_on_destruction() - { ipcdetail::interprocess_tester::dont_close_on_destruction(m_cond); } - /// @endcond -}; - -} //namespace interprocess -} //namespace boost - -#include - -#endif // BOOST_INTERPROCESS_NAMED_CONDITION_ANY_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/named_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/named_mutex.hpp index eb112453..4aca03b8 100644 --- a/utils/boost_idb/boost/interprocess/sync/named_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/named_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,18 +19,17 @@ #include #include #include +#include #include -#include #include #if defined(BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) - #include - #define BOOST_INTERPROCESS_USE_POSIX_SEMAPHORES -#elif !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS + #include #else -#include + #include + #include + #include + #include #endif //!\file @@ -41,7 +40,7 @@ namespace interprocess { class named_condition; -//!A mutex with a global name, so it can be found from different +//!A mutex with a global name, so it can be found from different //!processes. This mutex can't be placed in shared memory, and //!each process should have it's own named_mutex. class named_mutex @@ -56,11 +55,11 @@ class named_mutex /// @endcond public: - //!Creates a global mutex with a name. + //!Creates a global interprocess_mutex with a name. //!Throws interprocess_exception on error. named_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - //!Opens or creates a global mutex with a name. + //!Opens or creates a global mutex with a name. //!If the mutex is created, this call is equivalent to //!named_mutex(create_only_t, ... ) //!If the mutex is already created, this call is equivalent @@ -82,19 +81,19 @@ class named_mutex ~named_mutex(); //!Unlocks a previously locked - //!mutex. + //!interprocess_mutex. void unlock(); - //!Locks the mutex, sleeps when the mutex is already locked. + //!Locks interprocess_mutex, sleeps when interprocess_mutex is already locked. //!Throws interprocess_exception if a severe error is found void lock(); - //!Tries to lock the mutex, returns false when the mutex + //!Tries to lock the interprocess_mutex, returns false when interprocess_mutex //!is already locked, returns true when success. //!Throws interprocess_exception if a severe error is found bool try_lock(); - //!Tries to lock the the mutex until time abs_time, + //!Tries to lock the interprocess_mutex until time abs_time, //!Returns false when timeout expires, returns true when locks. //!Throws interprocess_exception if a severe error is found bool timed_lock(const boost::posix_time::ptime &abs_time); @@ -105,61 +104,126 @@ class named_mutex /// @cond private: - friend class ipcdetail::interprocess_tester; + friend class detail::interprocess_tester; void dont_close_on_destruction(); - public: - #if defined(BOOST_INTERPROCESS_USE_POSIX_SEMAPHORES) - typedef ipcdetail::posix_named_mutex internal_mutex_type; - #undef BOOST_INTERPROCESS_USE_POSIX_SEMAPHORES - #elif defined(BOOST_INTERPROCESS_USE_WINDOWS) - typedef ipcdetail::windows_named_mutex internal_mutex_type; - #undef BOOST_INTERPROCESS_USE_WINDOWS + #if defined(BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) + detail::named_semaphore_wrapper m_sem; #else - typedef ipcdetail::shm_named_mutex internal_mutex_type; - #endif - internal_mutex_type &internal_mutex() - { return m_mut; } - - internal_mutex_type m_mut; + interprocess_mutex *mutex() const + { return static_cast(m_shmem.get_user_address()); } + detail::managed_open_or_create_impl m_shmem; + typedef detail::named_creation_functor construct_func_t; + #endif /// @endcond }; /// @cond +#if defined(BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) + inline named_mutex::named_mutex(create_only_t, const char *name, const permissions &perm) - : m_mut(create_only_t(), name, perm) + : m_sem(detail::DoCreate, name, 1, perm) {} inline named_mutex::named_mutex(open_or_create_t, const char *name, const permissions &perm) - : m_mut(open_or_create_t(), name, perm) + : m_sem(detail::DoOpenOrCreate, name, 1, perm) {} inline named_mutex::named_mutex(open_only_t, const char *name) - : m_mut(open_only_t(), name) + : m_sem(detail::DoOpen, name, 1, permissions()) +{} + +inline void named_mutex::dont_close_on_destruction() +{ detail::interprocess_tester::dont_close_on_destruction(m_sem); } + +inline named_mutex::~named_mutex() {} +inline void named_mutex::lock() +{ m_sem.wait(); } + +inline void named_mutex::unlock() +{ m_sem.post(); } + +inline bool named_mutex::try_lock() +{ return m_sem.try_wait(); } + +inline bool named_mutex::timed_lock(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + return m_sem.timed_wait(abs_time); +} + +inline bool named_mutex::remove(const char *name) +{ return detail::named_semaphore_wrapper::remove(name); } + +#else + inline void named_mutex::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_mut); } +{ detail::interprocess_tester::dont_close_on_destruction(m_shmem); } inline named_mutex::~named_mutex() {} +inline named_mutex::named_mutex(create_only_t, const char *name, const permissions &perm) + : m_shmem (create_only + ,name + ,sizeof(interprocess_mutex) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoCreate) + ,perm) +{} + +inline named_mutex::named_mutex(open_or_create_t, const char *name, const permissions &perm) + : m_shmem (open_or_create + ,name + ,sizeof(interprocess_mutex) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoOpenOrCreate) + ,perm) +{} + +inline named_mutex::named_mutex(open_only_t, const char *name) + : m_shmem (open_only + ,name + ,read_write + ,0 + ,construct_func_t(detail::DoOpen)) +{} + inline void named_mutex::lock() -{ m_mut.lock(); } +{ this->mutex()->lock(); } inline void named_mutex::unlock() -{ m_mut.unlock(); } +{ this->mutex()->unlock(); } inline bool named_mutex::try_lock() -{ return m_mut.try_lock(); } +{ return this->mutex()->try_lock(); } inline bool named_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ return m_mut.timed_lock(abs_time); } +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + return this->mutex()->timed_lock(abs_time); +} inline bool named_mutex::remove(const char *name) -{ return internal_mutex_type::remove(name); } +{ return shared_memory_object::remove(name); } + +#endif /// @endcond diff --git a/utils/boost_idb/boost/interprocess/sync/named_recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/named_recursive_mutex.hpp index 5849a92d..aa34bc12 100644 --- a/utils/boost_idb/boost/interprocess/sync/named_recursive_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/named_recursive_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,14 +18,13 @@ #include #include #include +#include #include +#include +#include +#include +#include #include -#if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS -#else - #include -#endif //!\file //!Describes a named named_recursive_mutex class for inter-process synchronization @@ -34,10 +33,10 @@ namespace boost { namespace interprocess { /// @cond -namespace ipcdetail{ class interprocess_tester; } +namespace detail{ class interprocess_tester; } /// @endcond -//!A recursive mutex with a global name, so it can be found from different +//!A recursive mutex with a global name, so it can be found from different //!processes. This mutex can't be placed in shared memory, and //!each process should have it's own named_recursive_mutex. class named_recursive_mutex @@ -54,7 +53,7 @@ class named_recursive_mutex //!If the recursive_mutex can't be created throws interprocess_exception named_recursive_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - //!Opens or creates a global recursive_mutex with a name. + //!Opens or creates a global recursive_mutex with a name. //!If the recursive_mutex is created, this call is equivalent to //!named_recursive_mutex(create_only_t, ... ) //!If the recursive_mutex is already created, this call is equivalent @@ -83,7 +82,7 @@ class named_recursive_mutex //!Throws interprocess_exception if a severe error is found. void lock(); - //!Tries to lock the named_recursive_mutex, returns false when named_recursive_mutex + //!Tries to lock the named_recursive_mutex, returns false when named_recursive_mutex //!is already locked, returns true when success. //!Throws interprocess_exception if a severe error is found. bool try_lock(); @@ -99,17 +98,14 @@ class named_recursive_mutex /// @cond private: - friend class ipcdetail::interprocess_tester; + friend class detail::interprocess_tester; void dont_close_on_destruction(); - #if defined(BOOST_INTERPROCESS_USE_WINDOWS) - typedef ipcdetail::windows_named_recursive_mutex impl_t; - #undef BOOST_INTERPROCESS_USE_WINDOWS - #else - typedef ipcdetail::shm_named_recursive_mutex impl_t; - #endif - impl_t m_mut; + interprocess_recursive_mutex *mutex() const + { return static_cast(m_shmem.get_user_address()); } + detail::managed_open_or_create_impl m_shmem; + typedef detail::named_creation_functor construct_func_t; /// @endcond }; @@ -119,28 +115,48 @@ inline named_recursive_mutex::~named_recursive_mutex() {} inline void named_recursive_mutex::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_mut); } +{ detail::interprocess_tester::dont_close_on_destruction(m_shmem); } inline named_recursive_mutex::named_recursive_mutex(create_only_t, const char *name, const permissions &perm) - : m_mut (create_only, name, perm) + : m_shmem (create_only + ,name + ,sizeof(interprocess_recursive_mutex) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoCreate) + ,perm) {} inline named_recursive_mutex::named_recursive_mutex(open_or_create_t, const char *name, const permissions &perm) - : m_mut (open_or_create, name, perm) + : m_shmem (open_or_create + ,name + ,sizeof(interprocess_recursive_mutex) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoOpenOrCreate) + ,perm) {} inline named_recursive_mutex::named_recursive_mutex(open_only_t, const char *name) - : m_mut (open_only, name) + : m_shmem (open_only + ,name + ,read_write + ,0 + ,construct_func_t(detail::DoOpen)) {} inline void named_recursive_mutex::lock() -{ m_mut.lock(); } +{ this->mutex()->lock(); } inline void named_recursive_mutex::unlock() -{ m_mut.unlock(); } +{ this->mutex()->unlock(); } inline bool named_recursive_mutex::try_lock() -{ return m_mut.try_lock(); } +{ return this->mutex()->try_lock(); } inline bool named_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) { @@ -148,11 +164,11 @@ inline bool named_recursive_mutex::timed_lock(const boost::posix_time::ptime &ab this->lock(); return true; } - return m_mut.timed_lock(abs_time); + return this->mutex()->timed_lock(abs_time); } inline bool named_recursive_mutex::remove(const char *name) -{ return impl_t::remove(name); } +{ return shared_memory_object::remove(name); } /// @endcond diff --git a/utils/boost_idb/boost/interprocess/sync/named_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/named_semaphore.hpp index 14772458..d8a4d581 100644 --- a/utils/boost_idb/boost/interprocess/sync/named_semaphore.hpp +++ b/utils/boost_idb/boost/interprocess/sync/named_semaphore.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -24,13 +24,12 @@ #include #if defined(BOOST_INTERPROCESS_NAMED_SEMAPHORE_USES_POSIX_SEMAPHORES) -#include -//Experimental... -#elif !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION) && defined (BOOST_INTERPROCESS_WINDOWS) - #include - #define BOOST_INTERPROCESS_USE_WINDOWS +#include #else -#include +#include +#include +#include +#include #endif //!\file @@ -39,8 +38,8 @@ namespace boost { namespace interprocess { -//!A semaphore with a global name, so it can be found from different -//!processes. Allows several resource sharing patterns and efficient +//!A semaphore with a global name, so it can be found from different +//!processes. Allows several resource sharing patterns and efficient //!acknowledgment mechanisms. class named_semaphore { @@ -53,11 +52,11 @@ class named_semaphore /// @endcond public: - //!Creates a global semaphore with a name, and an initial count. + //!Creates a global semaphore with a name, and an initial count. //!If the semaphore can't be created throws interprocess_exception named_semaphore(create_only_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()); - //!Opens or creates a global semaphore with a name, and an initial count. + //!Opens or creates a global semaphore with a name, and an initial count. //!If the semaphore is created, this call is equivalent to //!named_semaphore(create_only_t, ...) //!If the semaphore is already created, this call is equivalent to @@ -84,7 +83,7 @@ class named_semaphore void post(); //!Decrements the semaphore. If the semaphore value is not greater than zero, - //!then the calling process/thread blocks until it can decrement the counter. + //!then the calling process/thread blocks until it can decrement the counter. //!If there is an error an interprocess_exception exception is thrown. void wait(); @@ -106,42 +105,44 @@ class named_semaphore /// @cond private: - friend class ipcdetail::interprocess_tester; + friend class detail::interprocess_tester; void dont_close_on_destruction(); #if defined(BOOST_INTERPROCESS_NAMED_SEMAPHORE_USES_POSIX_SEMAPHORES) - typedef ipcdetail::posix_named_semaphore impl_t; - #elif defined(BOOST_INTERPROCESS_USE_WINDOWS) - #undef BOOST_INTERPROCESS_USE_WINDOWS - typedef ipcdetail::windows_named_semaphore impl_t; + detail::named_semaphore_wrapper m_sem; #else - typedef ipcdetail::shm_named_semaphore impl_t; + interprocess_semaphore *semaphore() const + { return static_cast(m_shmem.get_user_address()); } + + detail::managed_open_or_create_impl m_shmem; + typedef detail::named_creation_functor construct_func_t; #endif - impl_t m_sem; /// @endcond }; /// @cond +#if defined(BOOST_INTERPROCESS_NAMED_SEMAPHORE_USES_POSIX_SEMAPHORES) + inline named_semaphore::named_semaphore (create_only_t, const char *name, unsigned int initialCount, const permissions &perm) - : m_sem(create_only, name, initialCount, perm) + : m_sem(detail::DoCreate, name, initialCount, perm) {} inline named_semaphore::named_semaphore (open_or_create_t, const char *name, unsigned int initialCount, const permissions &perm) - : m_sem(open_or_create, name, initialCount, perm) + : m_sem(detail::DoOpenOrCreate, name, initialCount, perm) {} inline named_semaphore::named_semaphore(open_only_t, const char *name) - : m_sem(open_only, name) + : m_sem(detail::DoOpen, name, 1, permissions()) {} inline named_semaphore::~named_semaphore() {} inline void named_semaphore::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_sem); } +{ detail::interprocess_tester::dont_close_on_destruction(m_sem); } inline void named_semaphore::wait() { m_sem.wait(); } @@ -162,7 +163,73 @@ inline bool named_semaphore::timed_wait(const boost::posix_time::ptime &abs_time } inline bool named_semaphore::remove(const char *name) -{ return impl_t::remove(name); } +{ return detail::named_semaphore_wrapper::remove(name); } + +#else + +inline named_semaphore::~named_semaphore() +{} + +inline void named_semaphore::dont_close_on_destruction() +{ detail::interprocess_tester::dont_close_on_destruction(m_shmem); } + +inline named_semaphore::named_semaphore + (create_only_t, const char *name, unsigned int initialCount, const permissions &perm) + : m_shmem (create_only + ,name + ,sizeof(interprocess_semaphore) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoCreate, initialCount) + ,perm) +{} + +inline named_semaphore::named_semaphore + (open_or_create_t, const char *name, unsigned int initialCount, const permissions &perm) + : m_shmem (open_or_create + ,name + ,sizeof(interprocess_semaphore) + + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset + ,read_write + ,0 + ,construct_func_t(detail::DoOpenOrCreate, initialCount) + ,perm) +{} + +inline named_semaphore::named_semaphore + (open_only_t, const char *name) + : m_shmem (open_only + ,name + ,read_write + ,0 + ,construct_func_t(detail::DoOpen, 0)) +{} + +inline void named_semaphore::post() +{ semaphore()->post(); } + +inline void named_semaphore::wait() +{ semaphore()->wait(); } + +inline bool named_semaphore::try_wait() +{ return semaphore()->try_wait(); } + +inline bool named_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->wait(); + return true; + } + return semaphore()->timed_wait(abs_time); +} + +inline bool named_semaphore::remove(const char *name) +{ return shared_memory_object::remove(name); } + +#endif /// @endcond diff --git a/utils/boost_idb/boost/interprocess/sync/named_sharable_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/named_sharable_mutex.hpp deleted file mode 100644 index 6ebcebfd..00000000 --- a/utils/boost_idb/boost/interprocess/sync/named_sharable_mutex.hpp +++ /dev/null @@ -1,230 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_NAMED_SHARABLE_MUTEX_HPP -#define BOOST_INTERPROCESS_NAMED_SHARABLE_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes a named sharable mutex class for inter-process synchronization - -namespace boost { -namespace interprocess { - -/// @cond -namespace ipcdetail{ class interprocess_tester; } -/// @endcond - -class named_condition; - -//!A sharable mutex with a global name, so it can be found from different -//!processes. This mutex can't be placed in shared memory, and -//!each process should have it's own named sharable mutex. -class named_sharable_mutex -{ - /// @cond - //Non-copyable - named_sharable_mutex(); - named_sharable_mutex(const named_sharable_mutex &); - named_sharable_mutex &operator=(const named_sharable_mutex &); - /// @endcond - public: - - //!Creates a global sharable mutex with a name. - //!If the sharable mutex can't be created throws interprocess_exception - named_sharable_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - - //!Opens or creates a global sharable mutex with a name. - //!If the sharable mutex is created, this call is equivalent to - //!named_sharable_mutex(create_only_t, ...) - //!If the sharable mutex is already created, this call is equivalent to - //!named_sharable_mutex(open_only_t, ... ). - named_sharable_mutex(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()); - - //!Opens a global sharable mutex with a name if that sharable mutex - //!is previously. - //!created. If it is not previously created this function throws - //!interprocess_exception. - named_sharable_mutex(open_only_t open_only, const char *name); - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~named_sharable_mutex(); - - //Exclusive locking - - //!Effects: The calling thread tries to obtain exclusive ownership of the mutex, - //! and if another thread has exclusive or sharable ownership of - //! the mutex, it waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock(); - - //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! without waiting. If no other thread has exclusive or sharable - //! ownership of the mutex this succeeds. - //!Returns: If it can acquire exclusive ownership immediately returns true. - //! If it has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock(); - - //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! waiting if necessary until no other thread has exclusive, or sharable - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The calling thread releases the exclusive ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock(); - - //Sharable locking - - //!Effects: The calling thread tries to obtain sharable ownership of the mutex, - //! and if another thread has exclusive ownership of the mutex, - //! waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock_sharable(); - - //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! without waiting. If no other thread has exclusive ownership - //! of the mutex this succeeds. - //!Returns: If it can acquire sharable ownership immediately returns true. If it - //! has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock_sharable(); - - //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! waiting if necessary until no other thread has exclusive - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock_sharable(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The calling thread releases the sharable ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_sharable(); - - //!Erases a named sharable mutex from the system. - //!Returns false on error. Never throws. - static bool remove(const char *name); - - /// @cond - private: - friend class ipcdetail::interprocess_tester; - void dont_close_on_destruction(); - - interprocess_sharable_mutex *mutex() const - { return static_cast(m_shmem.get_user_address()); } - - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - typedef ipcdetail::named_creation_functor construct_func_t; - /// @endcond -}; - -/// @cond - -inline named_sharable_mutex::~named_sharable_mutex() -{} - -inline named_sharable_mutex::named_sharable_mutex - (create_only_t, const char *name, const permissions &perm) - : m_shmem (create_only - ,name - ,sizeof(interprocess_sharable_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoCreate) - ,perm) -{} - -inline named_sharable_mutex::named_sharable_mutex - (open_or_create_t, const char *name, const permissions &perm) - : m_shmem (open_or_create - ,name - ,sizeof(interprocess_sharable_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoOpenOrCreate) - ,perm) -{} - -inline named_sharable_mutex::named_sharable_mutex - (open_only_t, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoOpen)) -{} - -inline void named_sharable_mutex::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_shmem); } - -inline void named_sharable_mutex::lock() -{ this->mutex()->lock(); } - -inline void named_sharable_mutex::unlock() -{ this->mutex()->unlock(); } - -inline bool named_sharable_mutex::try_lock() -{ return this->mutex()->try_lock(); } - -inline bool named_sharable_mutex::timed_lock - (const boost::posix_time::ptime &abs_time) -{ return this->mutex()->timed_lock(abs_time); } - -inline void named_sharable_mutex::lock_sharable() -{ this->mutex()->lock_sharable(); } - -inline void named_sharable_mutex::unlock_sharable() -{ this->mutex()->unlock_sharable(); } - -inline bool named_sharable_mutex::try_lock_sharable() -{ return this->mutex()->try_lock_sharable(); } - -inline bool named_sharable_mutex::timed_lock_sharable - (const boost::posix_time::ptime &abs_time) -{ return this->mutex()->timed_lock_sharable(abs_time); } - -inline bool named_sharable_mutex::remove(const char *name) -{ return shared_memory_object::remove(name); } - -/// @endcond - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_NAMED_SHARABLE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/named_upgradable_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/named_upgradable_mutex.hpp index 95e0ed50..0cb24681 100644 --- a/utils/boost_idb/boost/interprocess/sync/named_upgradable_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/named_upgradable_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include //!\file @@ -33,12 +33,12 @@ namespace boost { namespace interprocess { /// @cond -namespace ipcdetail{ class interprocess_tester; } +namespace detail{ class interprocess_tester; } /// @endcond class named_condition; -//!A upgradable mutex with a global name, so it can be found from different +//!A upgradable mutex with a global name, so it can be found from different //!processes. This mutex can't be placed in shared memory, and //!each process should have it's own named upgradable mutex. class named_upgradable_mutex @@ -52,11 +52,11 @@ class named_upgradable_mutex /// @endcond public: - //!Creates a global upgradable mutex with a name. + //!Creates a global upgradable mutex with a name. //!If the upgradable mutex can't be created throws interprocess_exception named_upgradable_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - //!Opens or creates a global upgradable mutex with a name. + //!Opens or creates a global upgradable mutex with a name, and an initial count. //!If the upgradable mutex is created, this call is equivalent to //!named_upgradable_mutex(create_only_t, ...) //!If the upgradable mutex is already created, this call is equivalent to @@ -94,42 +94,42 @@ class named_upgradable_mutex bool try_lock(); //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! waiting if necessary until no other thread has exclusive, sharable or - //! upgradable ownership of the mutex or abs_time is reached. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //! waiting if necessary until no other thread has has exclusive, sharable or + //! upgradable ownership of the mutex or abs_time is reached. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The calling thread releases the exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. + //!Effects: The calling thread releases the exclusive ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock(); //Sharable locking //!Effects: The calling thread tries to obtain sharable ownership of the mutex, - //! and if another thread has exclusive ownership of the mutex, + //! and if another thread has exclusive or upgradable ownership of the mutex, //! waits until it can obtain the ownership. //!Throws: interprocess_exception on error. void lock_sharable(); //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! without waiting. If no other thread has exclusive ownership - //! of the mutex this succeeds. + //! without waiting. If no other thread has has exclusive or upgradable ownership + //! of the mutex this succeeds. //!Returns: If it can acquire sharable ownership immediately returns true. If it - //! has to wait, returns false. + //! has to wait, returns false. //!Throws: interprocess_exception on error. bool try_lock_sharable(); //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! waiting if necessary until no other thread has exclusive - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. + //! waiting if necessary until no other thread has has exclusive or upgradable + //! ownership of the mutex or abs_time is reached. + //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock_sharable(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The calling thread releases the sharable ownership of the mutex. + //!Precondition: The thread must have sharable ownership of the mutex. + //!Effects: The calling thread releases the sharable ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock_sharable(); @@ -142,85 +142,79 @@ class named_upgradable_mutex void lock_upgradable(); //!Effects: The calling thread tries to acquire upgradable ownership of the mutex - //! without waiting. If no other thread has exclusive or upgradable ownership - //! of the mutex this succeeds. + //! without waiting. If no other thread has has exclusive or upgradable ownership + //! of the mutex this succeeds. //!Returns: If it can acquire upgradable ownership immediately returns true. //! If it has to wait, returns false. //!Throws: interprocess_exception on error. bool try_lock_upgradable(); //!Effects: The calling thread tries to acquire upgradable ownership of the mutex - //! waiting if necessary until no other thread has exclusive or upgradable + //! waiting if necessary until no other thread has has exclusive or upgradable //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. + //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. //!Throws: interprocess_exception on error. bool timed_lock_upgradable(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The calling thread releases the upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. + //!Effects: The calling thread releases the upgradable ownership of the mutex. //!Throws: An exception derived from interprocess_exception on error. void unlock_upgradable(); //Demotions - //!Precondition: The thread must have exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. //!Effects: The thread atomically releases exclusive ownership and acquires - //! upgradable ownership. This operation is non-blocking. + //! upgradable ownership. This operation is non-blocking. //!Throws: An exception derived from interprocess_exception on error. void unlock_and_lock_upgradable(); - //!Precondition: The thread must have exclusive ownership of the mutex. + //!Precondition: The thread must have exclusive ownership of the mutex. //!Effects: The thread atomically releases exclusive ownership and acquires - //! sharable ownership. This operation is non-blocking. + //! sharable ownership. This operation is non-blocking. //!Throws: An exception derived from interprocess_exception on error. void unlock_and_lock_sharable(); - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and acquires - //! sharable ownership. This operation is non-blocking. + //! sharable ownership. This operation is non-blocking. //!Throws: An exception derived from interprocess_exception on error. void unlock_upgradable_and_lock_sharable(); //Promotions - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and acquires //! exclusive ownership. This operation will block until all threads with - //! sharable ownership release it. + //! sharable ownership release it. //!Throws: An exception derived from interprocess_exception on error. void unlock_upgradable_and_lock(); - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and tries to //! acquire exclusive ownership. This operation will fail if there are threads - //! with sharable ownership, but it will maintain upgradable ownership. + //! with sharable ownership, but it will maintain upgradable ownership. //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. bool try_unlock_upgradable_and_lock(); - //!Precondition: The thread must have upgradable ownership of the mutex. + //!Precondition: The thread must have upgradable ownership of the mutex. //!Effects: The thread atomically releases upgradable ownership and tries to acquire //! exclusive ownership, waiting if necessary until abs_time. This operation will //! fail if there are threads with sharable ownership or timeout reaches, but it - //! will maintain upgradable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //! will maintain upgradable ownership. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. bool timed_unlock_upgradable_and_lock(const boost::posix_time::ptime &abs_time); - //!Precondition: The thread must have sharable ownership of the mutex. + //!Precondition: The thread must have sharable ownership of the mutex. //!Effects: The thread atomically releases sharable ownership and tries to acquire //! exclusive ownership. This operation will fail if there are threads with sharable //! or upgradable ownership, but it will maintain sharable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. + //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. //!Throws: An exception derived from interprocess_exception on error. bool try_unlock_sharable_and_lock(); - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The thread atomically releases sharable ownership and tries to acquire - //! upgradable ownership. This operation will fail if there are threads with sharable - //! or upgradable ownership, but it will maintain sharable ownership. - //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. - //!Throws: An exception derived from interprocess_exception on error. bool try_unlock_sharable_and_lock_upgradable(); //!Erases a named upgradable mutex from the system. @@ -229,15 +223,14 @@ class named_upgradable_mutex /// @cond private: - friend class ipcdetail::interprocess_tester; + friend class detail::interprocess_tester; void dont_close_on_destruction(); interprocess_upgradable_mutex *mutex() const { return static_cast(m_shmem.get_user_address()); } - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - typedef ipcdetail::named_creation_functor construct_func_t; + detail::managed_open_or_create_impl m_shmem; + typedef detail::named_creation_functor construct_func_t; /// @endcond }; @@ -251,10 +244,11 @@ inline named_upgradable_mutex::named_upgradable_mutex : m_shmem (create_only ,name ,sizeof(interprocess_upgradable_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset ,read_write ,0 - ,construct_func_t(ipcdetail::DoCreate) + ,construct_func_t(detail::DoCreate) ,perm) {} @@ -263,10 +257,11 @@ inline named_upgradable_mutex::named_upgradable_mutex : m_shmem (open_or_create ,name ,sizeof(interprocess_upgradable_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset + detail::managed_open_or_create_impl:: + ManagedOpenOrCreateUserOffset ,read_write ,0 - ,construct_func_t(ipcdetail::DoOpenOrCreate) + ,construct_func_t(detail::DoOpenOrCreate) ,perm) {} @@ -276,11 +271,11 @@ inline named_upgradable_mutex::named_upgradable_mutex ,name ,read_write ,0 - ,construct_func_t(ipcdetail::DoOpen)) + ,construct_func_t(detail::DoOpen)) {} inline void named_upgradable_mutex::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_shmem); } +{ detail::interprocess_tester::dont_close_on_destruction(m_shmem); } inline void named_upgradable_mutex::lock() { this->mutex()->lock(); } @@ -293,7 +288,13 @@ inline bool named_upgradable_mutex::try_lock() inline bool named_upgradable_mutex::timed_lock (const boost::posix_time::ptime &abs_time) -{ return this->mutex()->timed_lock(abs_time); } +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + return this->mutex()->timed_lock(abs_time); +} inline void named_upgradable_mutex::lock_upgradable() { this->mutex()->lock_upgradable(); } @@ -306,7 +307,13 @@ inline bool named_upgradable_mutex::try_lock_upgradable() inline bool named_upgradable_mutex::timed_lock_upgradable (const boost::posix_time::ptime &abs_time) -{ return this->mutex()->timed_lock_upgradable(abs_time); } +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock_upgradable(); + return true; + } + return this->mutex()->timed_lock_upgradable(abs_time); +} inline void named_upgradable_mutex::lock_sharable() { this->mutex()->lock_sharable(); } @@ -319,7 +326,13 @@ inline bool named_upgradable_mutex::try_lock_sharable() inline bool named_upgradable_mutex::timed_lock_sharable (const boost::posix_time::ptime &abs_time) -{ return this->mutex()->timed_lock_sharable(abs_time); } +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock_sharable(); + return true; + } + return this->mutex()->timed_lock_sharable(abs_time); +} inline void named_upgradable_mutex::unlock_and_lock_upgradable() { this->mutex()->unlock_and_lock_upgradable(); } diff --git a/utils/boost_idb/boost/interprocess/sync/null_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/null_mutex.hpp index d9f69a69..182b40db 100644 --- a/utils/boost_idb/boost/interprocess/sync/null_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/null_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/utils/boost_idb/boost/interprocess/sync/posix/condition.hpp b/utils/boost_idb/boost/interprocess/sync/posix/condition.hpp deleted file mode 100644 index 2deea0f7..00000000 --- a/utils/boost_idb/boost/interprocess/sync/posix/condition.hpp +++ /dev/null @@ -1,191 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_POSIX_CONDITION_HPP -#define BOOST_INTERPROCESS_POSIX_CONDITION_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class posix_condition -{ - //Non-copyable - posix_condition(const posix_condition &); - posix_condition &operator=(const posix_condition &); - - public: - //!Constructs a posix_condition. On error throws interprocess_exception. - posix_condition(); - - //!Destroys *this - //!liberating system resources. - ~posix_condition(); - - //!If there is a thread waiting on *this, change that - //!thread's state to ready. Otherwise there is no effect. - void notify_one(); - - //!Change the state of all threads waiting on *this to ready. - //!If there are no waiting threads, notify_all() has no effect. - void notify_all(); - - //!Releases the lock on the posix_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), and then reacquires the lock. - template - void wait(L& lock) - { - if (!lock) - throw lock_exception(); - this->do_wait(*lock.mutex()); - } - - //!The same as: - //!while (!pred()) wait(lock) - template - void wait(L& lock, Pr pred) - { - if (!lock) - throw lock_exception(); - - while (!pred()) - this->do_wait(*lock.mutex()); - } - - //!Releases the lock on the posix_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, - //!and then reacquires the lock. - //!Returns: false if time abs_time is reached, otherwise true. - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock); - return true; - } - if (!lock) - throw lock_exception(); - return this->do_timed_wait(abs_time, *lock.mutex()); - } - - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); - //! } return true; - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock, pred); - return true; - } - if (!lock) - throw lock_exception(); - while (!pred()){ - if (!this->do_timed_wait(abs_time, *lock.mutex())) - return pred(); - } - - return true; - } - - - void do_wait(posix_mutex &mut); - - bool do_timed_wait(const boost::posix_time::ptime &abs_time, posix_mutex &mut); - - private: - pthread_cond_t m_condition; -}; - -inline posix_condition::posix_condition() -{ - int res; - pthread_condattr_t cond_attr; - res = pthread_condattr_init(&cond_attr); - if(res != 0){ - throw interprocess_exception("pthread_condattr_init failed"); - } - res = pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED); - if(res != 0){ - pthread_condattr_destroy(&cond_attr); - throw interprocess_exception(res); - } - res = pthread_cond_init(&m_condition, &cond_attr); - pthread_condattr_destroy(&cond_attr); - if(res != 0){ - throw interprocess_exception(res); - } -} - -inline posix_condition::~posix_condition() -{ - int res = 0; - res = pthread_cond_destroy(&m_condition); - BOOST_ASSERT(res == 0); (void)res; -} - -inline void posix_condition::notify_one() -{ - int res = 0; - res = pthread_cond_signal(&m_condition); - BOOST_ASSERT(res == 0); (void)res; -} - -inline void posix_condition::notify_all() -{ - int res = 0; - res = pthread_cond_broadcast(&m_condition); - BOOST_ASSERT(res == 0); (void)res; -} - -inline void posix_condition::do_wait(posix_mutex &mut) -{ - pthread_mutex_t* pmutex = &mut.m_mut; - int res = 0; - res = pthread_cond_wait(&m_condition, pmutex); - BOOST_ASSERT(res == 0); (void)res; -} - -inline bool posix_condition::do_timed_wait - (const boost::posix_time::ptime &abs_time, posix_mutex &mut) -{ - timespec ts = ptime_to_timespec(abs_time); - pthread_mutex_t* pmutex = &mut.m_mut; - int res = 0; - res = pthread_cond_timedwait(&m_condition, pmutex, &ts); - BOOST_ASSERT(res == 0 || res == ETIMEDOUT); - - return res != ETIMEDOUT; -} - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif //#ifndef BOOST_INTERPROCESS_POSIX_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/posix/interprocess_barrier.hpp b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_barrier.hpp new file mode 100644 index 00000000..fd1d48fa --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_barrier.hpp @@ -0,0 +1,45 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace boost { +namespace interprocess { + +inline barrier::barrier(unsigned int count) +{ + if (count == 0) + throw std::invalid_argument("count cannot be zero."); + detail::barrierattr_wrapper barrier_attr; + detail::barrier_initializer barrier + (m_barrier, barrier_attr, static_cast(count)); + barrier.release(); +} + +inline barrier::~barrier() +{ + int res = pthread_barrier_destroy(&m_barrier); + BOOST_ASSERT(res == 0);(void)res; +} + +inline bool barrier::wait() +{ + int res = pthread_barrier_wait(&m_barrier); + + if (res != PTHREAD_BARRIER_SERIAL_THREAD && res != 0){ + throw interprocess_exception(res); + } + return res == PTHREAD_BARRIER_SERIAL_THREAD; +} + +} //namespace interprocess { +} //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/sync/posix/interprocess_condition.hpp b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_condition.hpp new file mode 100644 index 00000000..a506b619 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_condition.hpp @@ -0,0 +1,82 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include + +namespace boost { + +namespace interprocess { + +inline interprocess_condition::interprocess_condition() +{ + int res; + pthread_condattr_t cond_attr; + res = pthread_condattr_init(&cond_attr); + if(res != 0){ + throw interprocess_exception("pthread_condattr_init failed"); + } + res = pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED); + if(res != 0){ + pthread_condattr_destroy(&cond_attr); + throw interprocess_exception(res); + } + res = pthread_cond_init(&m_condition, &cond_attr); + pthread_condattr_destroy(&cond_attr); + if(res != 0){ + throw interprocess_exception(res); + } +} + +inline interprocess_condition::~interprocess_condition() +{ + int res = 0; + res = pthread_cond_destroy(&m_condition); + BOOST_ASSERT(res == 0); +} + +inline void interprocess_condition::notify_one() +{ + int res = 0; + res = pthread_cond_signal(&m_condition); + BOOST_ASSERT(res == 0); +} + +inline void interprocess_condition::notify_all() +{ + int res = 0; + res = pthread_cond_broadcast(&m_condition); + BOOST_ASSERT(res == 0); +} + +inline void interprocess_condition::do_wait(interprocess_mutex &mut) +{ + pthread_mutex_t* pmutex = &mut.m_mut; + int res = 0; + res = pthread_cond_wait(&m_condition, pmutex); + BOOST_ASSERT(res == 0); +} + +inline bool interprocess_condition::do_timed_wait + (const boost::posix_time::ptime &abs_time, interprocess_mutex &mut) +{ + timespec ts = detail::ptime_to_timespec(abs_time); + pthread_mutex_t* pmutex = &mut.m_mut; + int res = 0; + res = pthread_cond_timedwait(&m_condition, pmutex, &ts); + BOOST_ASSERT(res == 0 || res == ETIMEDOUT); + + return res != ETIMEDOUT; +} + +} //namespace interprocess + +} // namespace boost diff --git a/utils/boost_idb/boost/interprocess/sync/posix/interprocess_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_mutex.hpp new file mode 100644 index 00000000..8e5b4d91 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_mutex.hpp @@ -0,0 +1,111 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// +// +// Parts of the pthread code come from Boost Threads code: +// +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2001-2003 +// William E. Kempf +// +// Permission to use, copy, modify, distribute and sell this software +// and its documentation for any purpose is hereby granted without fee, +// provided that the above copyright notice appear in all copies and +// that both that copyright notice and this permission notice appear +// in supporting documentation. William E. Kempf makes no representations +// about the suitability of this software for any purpose. +// It is provided "as is" without express or implied warranty. +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#ifndef BOOST_INTERPROCESS_POSIX_TIMEOUTS +# include +#endif +#include + +namespace boost { +namespace interprocess { + +inline interprocess_mutex::interprocess_mutex() +{ + detail::mutexattr_wrapper mut_attr; + detail::mutex_initializer mut(m_mut, mut_attr); + mut.release(); +} + +inline interprocess_mutex::~interprocess_mutex() +{ + int res = pthread_mutex_destroy(&m_mut); + BOOST_ASSERT(res == 0);(void)res; +} + +inline void interprocess_mutex::lock() +{ + if (pthread_mutex_lock(&m_mut) != 0) + throw lock_exception(); +} + +inline bool interprocess_mutex::try_lock() +{ + int res = pthread_mutex_trylock(&m_mut); + if (!(res == 0 || res == EBUSY)) + throw lock_exception(); + return res == 0; +} + +inline bool interprocess_mutex::timed_lock(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + #ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS + + timespec ts = detail::ptime_to_timespec(abs_time); + int res = pthread_mutex_timedlock(&m_mut, &ts); + if (res != 0 && res != ETIMEDOUT) + throw lock_exception(); + return res == 0; + + #else //BOOST_INTERPROCESS_POSIX_TIMEOUTS + + //Obtain current count and target time + boost::posix_time::ptime now = microsec_clock::universal_time(); + + if(now >= abs_time) return false; + + do{ + if(this->try_lock()){ + break; + } + now = microsec_clock::universal_time(); + + if(now >= abs_time){ + return false; + } + // relinquish current time slice + detail::thread_yield(); + }while (true); + return true; + + #endif //BOOST_INTERPROCESS_POSIX_TIMEOUTS +} + +inline void interprocess_mutex::unlock() +{ + int res = 0; + res = pthread_mutex_unlock(&m_mut); + BOOST_ASSERT(res == 0); +} + +} //namespace interprocess { +} //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp new file mode 100644 index 00000000..b80bab17 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_recursive_mutex.hpp @@ -0,0 +1,112 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// +// +// Parts of the pthread code come from Boost Threads code: +// +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2001-2003 +// William E. Kempf +// +// Permission to use, copy, modify, distribute and sell this software +// and its documentation for any purpose is hereby granted without fee, +// provided that the above copyright notice appear in all copies and +// that both that copyright notice and this permission notice appear +// in supporting documentation. William E. Kempf makes no representations +// about the suitability of this software for any purpose. +// It is provided "as is" without express or implied warranty. +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#ifndef BOOST_INTERPROCESS_POSIX_TIMEOUTS +# include +#endif +#include + +namespace boost { + +namespace interprocess { + +inline interprocess_recursive_mutex::interprocess_recursive_mutex() +{ + detail::mutexattr_wrapper mut_attr(true); + detail::mutex_initializer mut(m_mut, mut_attr); + mut.release(); +} + +inline interprocess_recursive_mutex::~interprocess_recursive_mutex() +{ + int res = pthread_mutex_destroy(&m_mut); + BOOST_ASSERT(res == 0);(void)res; +} + +inline void interprocess_recursive_mutex::lock() +{ + if (pthread_mutex_lock(&m_mut) != 0) + throw lock_exception(); +} + +inline bool interprocess_recursive_mutex::try_lock() +{ + int res = pthread_mutex_trylock(&m_mut); + if (!(res == 0 || res == EBUSY)) + throw lock_exception(); + return res == 0; +} + +inline bool interprocess_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->lock(); + return true; + } + #ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS + + timespec ts = detail::ptime_to_timespec(abs_time); + int res = pthread_mutex_timedlock(&m_mut, &ts); + if (res != 0 && res != ETIMEDOUT) + throw lock_exception(); + return res == 0; + + #else //BOOST_INTERPROCESS_POSIX_TIMEOUTS + + //Obtain current count and target time + boost::posix_time::ptime now = microsec_clock::universal_time(); + + if(now >= abs_time) return false; + + do{ + if(this->try_lock()){ + break; + } + now = microsec_clock::universal_time(); + + if(now >= abs_time){ + return false; + } + // relinquish current time slice + detail::thread_yield(); + }while (true); + return true; + + #endif //BOOST_INTERPROCESS_POSIX_TIMEOUTS +} + +inline void interprocess_recursive_mutex::unlock() +{ + int res = 0; + res = pthread_mutex_unlock(&m_mut); + BOOST_ASSERT(res == 0); +} + +} //namespace interprocess { +} //namespace boost { diff --git a/utils/boost_idb/boost/interprocess/sync/posix/interprocess_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_semaphore.hpp new file mode 100644 index 00000000..893cad25 --- /dev/null +++ b/utils/boost_idb/boost/interprocess/sync/posix/interprocess_semaphore.hpp @@ -0,0 +1,49 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/interprocess for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include + +namespace boost { + +namespace interprocess { + +inline interprocess_semaphore::~interprocess_semaphore() +{} + +inline interprocess_semaphore::interprocess_semaphore(unsigned int initialCount) + : m_sem(initialCount) +{} + +inline void interprocess_semaphore::post() +{ m_sem.post(); } + +inline void interprocess_semaphore::wait() +{ m_sem.wait(); } + +inline bool interprocess_semaphore::try_wait() +{ return m_sem.try_wait(); } + +inline bool interprocess_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) +{ + if(abs_time == boost::posix_time::pos_infin){ + this->wait(); + return true; + } + return m_sem.timed_wait(abs_time); +} +/* +inline int interprocess_semaphore::get_count() const +{ return m_sem.get_count(); } +*/ +} //namespace interprocess { + +} //namespace boost { + diff --git a/utils/boost_idb/boost/interprocess/sync/posix/mutex.hpp b/utils/boost_idb/boost/interprocess/sync/posix/mutex.hpp deleted file mode 100644 index 6bc45ca4..00000000 --- a/utils/boost_idb/boost/interprocess/sync/posix/mutex.hpp +++ /dev/null @@ -1,155 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -// -// Parts of the pthread code come from Boost Threads code: -// -////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2001-2003 -// William E. Kempf -// -// Permission to use, copy, modify, distribute and sell this software -// and its documentation for any purpose is hereby granted without fee, -// provided that the above copyright notice appear in all copies and -// that both that copyright notice and this permission notice appear -// in supporting documentation. William E. Kempf makes no representations -// about the suitability of this software for any purpose. -// It is provided "as is" without express or implied warranty. -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_POSIX_MUTEX_HPP -#define BOOST_INTERPROCESS_DETAIL_POSIX_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#ifndef BOOST_INTERPROCESS_POSIX_TIMEOUTS -# include -# include -#endif -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class posix_condition; - -class posix_mutex -{ - posix_mutex(const posix_mutex &); - posix_mutex &operator=(const posix_mutex &); - public: - - posix_mutex(); - ~posix_mutex(); - - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - void unlock(); - - friend class posix_condition; - - private: - pthread_mutex_t m_mut; -}; - -inline posix_mutex::posix_mutex() -{ - mutexattr_wrapper mut_attr; - mutex_initializer mut(m_mut, mut_attr); - mut.release(); -} - -inline posix_mutex::~posix_mutex() -{ - int res = pthread_mutex_destroy(&m_mut); - BOOST_ASSERT(res == 0);(void)res; -} - -inline void posix_mutex::lock() -{ - if (pthread_mutex_lock(&m_mut) != 0) - throw lock_exception(); -} - -inline bool posix_mutex::try_lock() -{ - int res = pthread_mutex_trylock(&m_mut); - if (!(res == 0 || res == EBUSY)) - throw lock_exception(); - return res == 0; -} - -inline bool posix_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - #ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS - - timespec ts = ptime_to_timespec(abs_time); - int res = pthread_mutex_timedlock(&m_mut, &ts); - if (res != 0 && res != ETIMEDOUT) - throw lock_exception(); - return res == 0; - - #else //BOOST_INTERPROCESS_POSIX_TIMEOUTS - - //Obtain current count and target time - boost::posix_time::ptime now = microsec_clock::universal_time(); - - spin_wait swait; - do{ - if(this->try_lock()){ - break; - } - now = microsec_clock::universal_time(); - - if(now >= abs_time){ - return false; - } - // relinquish current time slice - swait.yield(); - }while (true); - return true; - - #endif //BOOST_INTERPROCESS_POSIX_TIMEOUTS -} - -inline void posix_mutex::unlock() -{ - int res = 0; - res = pthread_mutex_unlock(&m_mut); - (void)res; - BOOST_ASSERT(res == 0); -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_INTERPROCESS_DETAIL_POSIX_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/posix/named_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/posix/named_mutex.hpp deleted file mode 100644 index 1b03b7de..00000000 --- a/utils/boost_idb/boost/interprocess/sync/posix/named_mutex.hpp +++ /dev/null @@ -1,116 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_POSIX_NAMED_MUTEX_HPP -#define BOOST_INTERPROCESS_POSIX_NAMED_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include - -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class named_condition; - -class posix_named_mutex -{ - /// @cond - - posix_named_mutex(); - posix_named_mutex(const posix_named_mutex &); - posix_named_mutex &operator=(const posix_named_mutex &); - friend class named_condition; - /// @endcond - - public: - posix_named_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - - posix_named_mutex(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()); - - posix_named_mutex(open_only_t open_only, const char *name); - - ~posix_named_mutex(); - - void unlock(); - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - static bool remove(const char *name); - - /// @cond - private: - friend class interprocess_tester; - void dont_close_on_destruction(); - - posix_named_semaphore m_sem; - /// @endcond -}; - -/// @cond - -inline posix_named_mutex::posix_named_mutex(create_only_t, const char *name, const permissions &perm) - : m_sem(create_only, name, 1, perm) -{} - -inline posix_named_mutex::posix_named_mutex(open_or_create_t, const char *name, const permissions &perm) - : m_sem(open_or_create, name, 1, perm) -{} - -inline posix_named_mutex::posix_named_mutex(open_only_t, const char *name) - : m_sem(open_only, name) -{} - -inline void posix_named_mutex::dont_close_on_destruction() -{ interprocess_tester::dont_close_on_destruction(m_sem); } - -inline posix_named_mutex::~posix_named_mutex() -{} - -inline void posix_named_mutex::lock() -{ m_sem.wait(); } - -inline void posix_named_mutex::unlock() -{ m_sem.post(); } - -inline bool posix_named_mutex::try_lock() -{ return m_sem.try_wait(); } - -inline bool posix_named_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - return m_sem.timed_wait(abs_time); -} - -inline bool posix_named_mutex::remove(const char *name) -{ return posix_named_semaphore::remove(name); } - -/// @endcond - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_POSIX_NAMED_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/posix/named_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/posix/named_semaphore.hpp deleted file mode 100644 index 0b7ca8bb..00000000 --- a/utils/boost_idb/boost/interprocess/sync/posix/named_semaphore.hpp +++ /dev/null @@ -1,84 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_POSIX_NAMED_CONDITION_HPP -#define BOOST_INTERPROCESS_POSIX_NAMED_CONDITION_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include - -#include - -namespace boost { -namespace interprocess { - -/// @cond -namespace ipcdetail{ class interprocess_tester; } -/// @endcond - -namespace ipcdetail { - -class posix_named_semaphore -{ - posix_named_semaphore(); - posix_named_semaphore(const posix_named_semaphore&); - posix_named_semaphore &operator= (const posix_named_semaphore &); - - public: - posix_named_semaphore - (create_only_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()) - { semaphore_open(mp_sem, DoCreate, name, initialCount, perm); } - - posix_named_semaphore(open_or_create_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()) - { semaphore_open(mp_sem, DoOpenOrCreate, name, initialCount, perm); } - - posix_named_semaphore(open_only_t, const char *name) - { semaphore_open(mp_sem, DoOpen, name); } - - ~posix_named_semaphore() - { - if(mp_sem != BOOST_INTERPROCESS_POSIX_SEM_FAILED) - semaphore_close(mp_sem); - } - - void post() - { semaphore_post(mp_sem); } - - void wait() - { semaphore_wait(mp_sem); } - - bool try_wait() - { return semaphore_try_wait(mp_sem); } - - bool timed_wait(const boost::posix_time::ptime &abs_time) - { return semaphore_timed_wait(mp_sem, abs_time); } - - static bool remove(const char *name) - { return semaphore_unlink(name); } - - private: - friend class ipcdetail::interprocess_tester; - void dont_close_on_destruction() - { mp_sem = BOOST_INTERPROCESS_POSIX_SEM_FAILED; } - - sem_t *mp_sem; -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_INTERPROCESS_POSIX_NAMED_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/posix/pthread_helpers.hpp b/utils/boost_idb/boost/interprocess/sync/posix/pthread_helpers.hpp index 9e989d58..e175b185 100644 --- a/utils/boost_idb/boost/interprocess/sync/posix/pthread_helpers.hpp +++ b/utils/boost_idb/boost/interprocess/sync/posix/pthread_helpers.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -19,17 +19,17 @@ #include #include -#include -#include +#include +#include namespace boost { namespace interprocess { -namespace ipcdetail{ +namespace detail{ #if defined BOOST_INTERPROCESS_POSIX_PROCESS_SHARED //!Makes pthread_mutexattr_t cleanup easy when using exceptions - struct mutexattr_wrapper + struct mutexattr_wrapper { //!Constructor mutexattr_wrapper(bool recursive = false) @@ -51,7 +51,7 @@ namespace ipcdetail{ }; //!Makes pthread_condattr_t cleanup easy when using exceptions - struct condattr_wrapper + struct condattr_wrapper { //!Constructor condattr_wrapper() @@ -86,7 +86,7 @@ namespace ipcdetail{ void release() {mp_mut = 0; } - private: + private: pthread_mutex_t *mp_mut; }; @@ -94,7 +94,7 @@ namespace ipcdetail{ class condition_initializer { public: - condition_initializer(pthread_cond_t &cond, pthread_condattr_t &cond_attr) + condition_initializer(pthread_cond_t &cond, pthread_condattr_t &cond_attr) : mp_cond(&cond) { if(pthread_cond_init(mp_cond, &cond_attr)!= 0) @@ -105,7 +105,7 @@ namespace ipcdetail{ void release() { mp_cond = 0; } - private: + private: pthread_cond_t *mp_cond; }; @@ -114,7 +114,7 @@ namespace ipcdetail{ #if defined(BOOST_INTERPROCESS_POSIX_BARRIERS) && defined(BOOST_INTERPROCESS_POSIX_PROCESS_SHARED) //!Makes pthread_barrierattr_t cleanup easy when using exceptions - struct barrierattr_wrapper + struct barrierattr_wrapper { //!Constructor barrierattr_wrapper() @@ -138,8 +138,8 @@ namespace ipcdetail{ { public: //!Constructor. Takes barrier attributes to initialize the barrier - barrier_initializer(pthread_barrier_t &mut, - pthread_barrierattr_t &mut_attr, + barrier_initializer(pthread_barrier_t &mut, + pthread_barrierattr_t &mut_attr, int count) : mp_barrier(&mut) { @@ -151,13 +151,13 @@ namespace ipcdetail{ void release() {mp_barrier = 0; } - private: + private: pthread_barrier_t *mp_barrier; }; #endif //#if defined(BOOST_INTERPROCESS_POSIX_BARRIERS) && defined(BOOST_INTERPROCESS_POSIX_PROCESS_SHARED) -}//namespace ipcdetail +}//namespace detail }//namespace interprocess diff --git a/utils/boost_idb/boost/interprocess/sync/posix/ptime_to_timespec.hpp b/utils/boost_idb/boost/interprocess/sync/posix/ptime_to_timespec.hpp index 3e20dc70..eaf160e8 100644 --- a/utils/boost_idb/boost/interprocess/sync/posix/ptime_to_timespec.hpp +++ b/utils/boost_idb/boost/interprocess/sync/posix/ptime_to_timespec.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,7 +17,7 @@ namespace boost { namespace interprocess { -namespace ipcdetail { +namespace detail { inline timespec ptime_to_timespec (const boost::posix_time::ptime &tm) { @@ -29,7 +29,7 @@ inline timespec ptime_to_timespec (const boost::posix_time::ptime &tm) return ts; } -} //namespace ipcdetail { +} //namespace detail { } //namespace interprocess { diff --git a/utils/boost_idb/boost/interprocess/sync/posix/recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/posix/recursive_mutex.hpp deleted file mode 100644 index ce2ad689..00000000 --- a/utils/boost_idb/boost/interprocess/sync/posix/recursive_mutex.hpp +++ /dev/null @@ -1,143 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -// -// Parts of the pthread code come from Boost Threads code: -// -////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2001-2003 -// William E. Kempf -// -// Permission to use, copy, modify, distribute and sell this software -// and its documentation for any purpose is hereby granted without fee, -// provided that the above copyright notice appear in all copies and -// that both that copyright notice and this permission notice appear -// in supporting documentation. William E. Kempf makes no representations -// about the suitability of this software for any purpose. -// It is provided "as is" without express or implied warranty. -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_POSIX_RECURSIVE_MUTEX_HPP -#define BOOST_INTERPROCESS_DETAIL_POSIX_RECURSIVE_MUTEX_HPP - -#include -#include - -#include -#include -#include -#include -#include -#include -#ifndef BOOST_INTERPROCESS_POSIX_TIMEOUTS -# include -# include -#endif -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class posix_recursive_mutex -{ - posix_recursive_mutex(const posix_recursive_mutex &); - posix_recursive_mutex &operator=(const posix_recursive_mutex &); - public: - - posix_recursive_mutex(); - ~posix_recursive_mutex(); - - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - void unlock(); - - private: - pthread_mutex_t m_mut; -}; - -inline posix_recursive_mutex::posix_recursive_mutex() -{ - mutexattr_wrapper mut_attr(true); - mutex_initializer mut(m_mut, mut_attr); - mut.release(); -} - -inline posix_recursive_mutex::~posix_recursive_mutex() -{ - int res = pthread_mutex_destroy(&m_mut); - BOOST_ASSERT(res == 0);(void)res; -} - -inline void posix_recursive_mutex::lock() -{ - if (pthread_mutex_lock(&m_mut) != 0) - throw lock_exception(); -} - -inline bool posix_recursive_mutex::try_lock() -{ - int res = pthread_mutex_trylock(&m_mut); - if (!(res == 0 || res == EBUSY)) - throw lock_exception(); - return res == 0; -} - -inline bool posix_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - #ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS - - timespec ts = ptime_to_timespec(abs_time); - int res = pthread_mutex_timedlock(&m_mut, &ts); - if (res != 0 && res != ETIMEDOUT) - throw lock_exception(); - return res == 0; - - #else //BOOST_INTERPROCESS_POSIX_TIMEOUTS - - //Obtain current count and target time - boost::posix_time::ptime now = microsec_clock::universal_time(); - spin_wait swait; - do{ - if(this->try_lock()){ - break; - } - now = microsec_clock::universal_time(); - - if(now >= abs_time){ - return false; - } - // relinquish current time slice - swait.yield(); - }while (true); - return true; - - #endif //BOOST_INTERPROCESS_POSIX_TIMEOUTS -} - -inline void posix_recursive_mutex::unlock() -{ - int res = 0; - res = pthread_mutex_unlock(&m_mut); - BOOST_ASSERT(res == 0); (void)res; -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_INTERPROCESS_DETAIL_POSIX_RECURSIVE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/posix/semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/posix/semaphore.hpp deleted file mode 100644 index 5d7dfa8d..00000000 --- a/utils/boost_idb/boost/interprocess/sync/posix/semaphore.hpp +++ /dev/null @@ -1,63 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_POSIX_SEMAPHORE_HPP -#define BOOST_INTERPROCESS_POSIX_SEMAPHORE_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include - -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class posix_semaphore -{ - posix_semaphore(); - posix_semaphore(const posix_semaphore&); - posix_semaphore &operator= (const posix_semaphore &); - - public: - posix_semaphore(unsigned int initialCount) - { semaphore_init(&m_sem, initialCount); } - - ~posix_semaphore() - { semaphore_destroy(&m_sem); } - - void post() - { semaphore_post(&m_sem); } - - void wait() - { semaphore_wait(&m_sem); } - - bool try_wait() - { return semaphore_try_wait(&m_sem); } - - bool timed_wait(const boost::posix_time::ptime &abs_time) - { return semaphore_timed_wait(&m_sem, abs_time); } - - private: - sem_t m_sem; -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_INTERPROCESS_POSIX_SEMAPHORE_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/posix/semaphore_wrapper.hpp b/utils/boost_idb/boost/interprocess/sync/posix/semaphore_wrapper.hpp index 98cb1283..7945be8a 100644 --- a/utils/boost_idb/boost/interprocess/sync/posix/semaphore_wrapper.hpp +++ b/utils/boost_idb/boost/interprocess/sync/posix/semaphore_wrapper.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,12 +17,8 @@ #include #include #include - -#include //O_CREAT, O_*... -#include //close -#include //std::string -#include //sem_* family, SEM_VALUE_MAX -#include //mode_t, S_IRWXG, S_IRWXO, S_IRWXU, +#include +#include #include #ifdef SEM_FAILED @@ -35,64 +31,53 @@ #include #else #include -#include #endif namespace boost { namespace interprocess { -namespace ipcdetail { + +/// @cond +namespace detail{ class interprocess_tester; } +/// @endcond + +namespace detail { inline bool semaphore_open - (sem_t *&handle, create_enum_t type, const char *origname, - unsigned int count = 0, const permissions &perm = permissions()) + (sem_t *&handle, detail::create_enum_t type, const char *origname, + unsigned int count, const permissions &perm = permissions()) { std::string name; #ifndef BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SEMAPHORES - add_leading_slash(origname, name); + detail::add_leading_slash(origname, name); #else - create_tmp_and_clean_old_and_get_filename(origname, name); + detail::create_tmp_and_clean_old_and_get_filename(origname, name); #endif //Create new mapping int oflag = 0; switch(type){ - case DoOpen: - { + case detail::DoOpen: //No addition - handle = ::sem_open(name.c_str(), oflag); - } break; - case DoOpenOrCreate: - case DoCreate: - { - while(1){ - oflag = (O_CREAT | O_EXCL); - handle = ::sem_open(name.c_str(), oflag, perm.get_permissions(), count); - if(handle != BOOST_INTERPROCESS_POSIX_SEM_FAILED){ - //We can't change semaphore permissions! - //::fchmod(handle, perm.get_permissions()); - break; - } - else if(errno == EEXIST && type == DoOpenOrCreate){ - oflag = 0; - if( (handle = ::sem_open(name.c_str(), oflag)) != BOOST_INTERPROCESS_POSIX_SEM_FAILED - || (errno != ENOENT) ){ - break; - } - } - else{ - break; - } - } - } + case detail::DoCreate: + oflag |= (O_CREAT | O_EXCL); + break; + case detail::DoOpenOrCreate: + oflag |= O_CREAT; break; default: - { - error_info err(other_error); - throw interprocess_exception(err); - } + { + error_info err = other_error; + throw interprocess_exception(err); + } } + //Open file using POSIX API + if(oflag & O_CREAT) + handle = sem_open(name.c_str(), oflag, perm.get_permissions(), count); + else + handle = sem_open(name.c_str(), oflag); + //Check for error if(handle == BOOST_INTERPROCESS_POSIX_SEM_FAILED){ throw interprocess_exception(error_info(errno)); @@ -104,7 +89,7 @@ inline bool semaphore_open inline void semaphore_close(sem_t *handle) { int ret = sem_close(handle); - if(ret != 0){ + if(ret != 0){ BOOST_ASSERT(0); } } @@ -114,11 +99,11 @@ inline bool semaphore_unlink(const char *semname) try{ std::string sem_str; #ifndef BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SEMAPHORES - add_leading_slash(semname, sem_str); + detail::add_leading_slash(semname, sem_str); #else - tmp_filename(semname, sem_str); + detail::tmp_filename(semname, sem_str); #endif - return 0 == sem_unlink(sem_str.c_str()); + return 0 != sem_unlink(sem_str.c_str()); } catch(...){ return false; @@ -139,7 +124,7 @@ inline void semaphore_init(sem_t *handle, unsigned int initialCount) inline void semaphore_destroy(sem_t *handle) { int ret = sem_destroy(handle); - if(ret != 0){ + if(ret != 0){ BOOST_ASSERT(0); } } @@ -174,12 +159,8 @@ inline bool semaphore_try_wait(sem_t *handle) inline bool semaphore_timed_wait(sem_t *handle, const boost::posix_time::ptime &abs_time) { - if(abs_time == boost::posix_time::pos_infin){ - semaphore_wait(handle); - return true; - } #ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS - timespec tspec = ptime_to_timespec(abs_time); + timespec tspec = detail::ptime_to_timespec(abs_time); for (;;){ int res = sem_timedwait(handle, &tspec); if(res == 0) @@ -196,18 +177,89 @@ inline bool semaphore_timed_wait(sem_t *handle, const boost::posix_time::ptime & return false; #else //#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS boost::posix_time::ptime now; - spin_wait swait; - do{ + while((now = microsec_clock::universal_time()) < abs_time){ if(semaphore_try_wait(handle)) return true; - swait.yield(); - }while((now = microsec_clock::universal_time()) < abs_time); + thread_yield(); + } return false; #endif //#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS } -} //namespace ipcdetail { + +class named_semaphore_wrapper +{ + named_semaphore_wrapper(); + named_semaphore_wrapper(const named_semaphore_wrapper&); + named_semaphore_wrapper &operator= (const named_semaphore_wrapper &); + + public: + named_semaphore_wrapper + (detail::create_enum_t type, const char *name, unsigned int count, const permissions &perm = permissions()) + { semaphore_open(mp_sem, type, name, count, perm); } + + ~named_semaphore_wrapper() + { + if(mp_sem != BOOST_INTERPROCESS_POSIX_SEM_FAILED) + semaphore_close(mp_sem); + } + + void post() + { semaphore_post(mp_sem); } + + void wait() + { semaphore_wait(mp_sem); } + + bool try_wait() + { return semaphore_try_wait(mp_sem); } + + bool timed_wait(const boost::posix_time::ptime &abs_time) + { return semaphore_timed_wait(mp_sem, abs_time); } + + static bool remove(const char *name) + { return semaphore_unlink(name); } + + private: + friend class detail::interprocess_tester; + void dont_close_on_destruction() + { mp_sem = BOOST_INTERPROCESS_POSIX_SEM_FAILED; } + + sem_t *mp_sem; +}; + +class semaphore_wrapper +{ + semaphore_wrapper(); + semaphore_wrapper(const semaphore_wrapper&); + semaphore_wrapper &operator= (const semaphore_wrapper &); + + public: + semaphore_wrapper(unsigned int initialCount) + { semaphore_init(&m_sem, initialCount); } + + ~semaphore_wrapper() + { semaphore_destroy(&m_sem); } + + void post() + { semaphore_post(&m_sem); } + + void wait() + { semaphore_wait(&m_sem); } + + bool try_wait() + { return semaphore_try_wait(&m_sem); } + + bool timed_wait(const boost::posix_time::ptime &abs_time) + { return semaphore_timed_wait(&m_sem, abs_time); } + + private: + sem_t m_sem; +}; + +} //namespace detail { } //namespace interprocess { } //namespace boost { +#undef BOOST_INTERPROCESS_POSIX_SEM_FAILED + #endif //#ifndef BOOST_INTERPROCESS_POSIX_SEMAPHORE_WRAPPER_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/scoped_lock.hpp b/utils/boost_idb/boost/interprocess/sync/scoped_lock.hpp index 5709f6ff..3bbdcebf 100644 --- a/utils/boost_idb/boost/interprocess/sync/scoped_lock.hpp +++ b/utils/boost_idb/boost/interprocess/sync/scoped_lock.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include //!\file @@ -53,7 +53,7 @@ class scoped_lock /// @cond private: typedef scoped_lock this_type; - BOOST_MOVABLE_BUT_NOT_COPYABLE(scoped_lock) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(scoped_lock) typedef bool this_type::*unspecified_bool_type; /// @endcond public: @@ -89,7 +89,7 @@ class scoped_lock : mp_mutex(&m), m_locked(true) {} - //!Effects: m.try_lock(). + //!Effects: m.try_lock(). //!Postconditions: mutex() == &m. owns() == the return value of the //! m.try_lock() executed within the constructor. //!Notes: The constructor will take ownership of the mutex if it can do @@ -101,7 +101,7 @@ class scoped_lock : mp_mutex(&m), m_locked(mp_mutex->try_lock()) {} - //!Effects: m.timed_lock(abs_time). + //!Effects: m.timed_lock(abs_time). //!Postconditions: mutex() == &m. owns() == the return value of the //! m.timed_lock(abs_time) executed within the constructor. //!Notes: The constructor will take ownership of the mutex if it can do @@ -120,15 +120,15 @@ class scoped_lock //! to thisscoped_lock with no blocking. If the scop scoped_lock does not //! own the mutex, then neither will this scoped_lock. Only a moved //! scoped_lock's will match this signature. An non-moved scoped_lock - //! can be moved with the expression: "boost::move(lock);". This + //! can be moved with the expression: "boost::interprocess::move(lock);". This //! constructor does not alter the state of the mutex, only potentially //! who owns it. - scoped_lock(BOOST_RV_REF(scoped_lock) scop) + scoped_lock(BOOST_INTERPROCESS_RV_REF(scoped_lock) scop) : mp_mutex(0), m_locked(scop.owns()) { mp_mutex = scop.release(); } //!Effects: If upgr.owns() then calls unlock_upgradable_and_lock() on the - //! referenced mutex. upgr.release() is called. + //! referenced mutex. upgr.release() is called. //!Postconditions: mutex() == the value upgr.mutex() had before the construction. //! upgr.mutex() == 0. owns() == upgr.owns() before the construction. //! upgr.owns() == false after the construction. @@ -136,12 +136,12 @@ class scoped_lock //! unlocking upgr. If upgr is unlocked, then this scoped_lock will be //! unlocked as well. Only a moved upgradable_lock's will match this //! signature. An non-moved upgradable_lock can be moved with - //! the expression: "boost::move(lock);" This constructor may block if + //! the expression: "boost::interprocess::move(lock);" This constructor may block if //! other threads hold a sharable_lock on this mutex (sharable_lock's can //! share ownership with an upgradable_lock). template - explicit scoped_lock(BOOST_RV_REF(upgradable_lock) upgr - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + explicit scoped_lock(BOOST_INTERPROCESS_RV_REF(upgradable_lock) upgr + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock &u_lock = upgr; @@ -155,12 +155,12 @@ class scoped_lock //!Effects: If upgr.owns() then calls try_unlock_upgradable_and_lock() on the //!referenced mutex: //! a)if try_unlock_upgradable_and_lock() returns true then mutex() obtains - //! the value from upgr.release() and owns() is set to true. + //! the value from upgr.release() and owns() is set to true. //! b)if try_unlock_upgradable_and_lock() returns false then upgr is - //! unaffected and this scoped_lock construction as the same effects as - //! a default construction. + //! unaffected and this scoped_lock construction as the same effects as + //! a default construction. //! c)Else upgr.owns() is false. mutex() obtains the value from upgr.release() - //! and owns() is set to false + //! and owns() is set to false //!Notes: This construction will not block. It will try to obtain mutex //! ownership from upgr immediately, while changing the lock type from a //! "read lock" to a "write lock". If the "read lock" isn't held in the @@ -168,8 +168,8 @@ class scoped_lock //! If the "read lock" is held, then mutex transfer occurs only if it can //! do so in a non-blocking manner. template - scoped_lock(BOOST_RV_REF(upgradable_lock) upgr, try_to_lock_type - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + scoped_lock(BOOST_INTERPROCESS_RV_REF(upgradable_lock) upgr, try_to_lock_type + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock &u_lock = upgr; @@ -186,20 +186,20 @@ class scoped_lock //!Effects: If upgr.owns() then calls timed_unlock_upgradable_and_lock(abs_time) //! on the referenced mutex: //! a)if timed_unlock_upgradable_and_lock(abs_time) returns true then mutex() - //! obtains the value from upgr.release() and owns() is set to true. + //! obtains the value from upgr.release() and owns() is set to true. //! b)if timed_unlock_upgradable_and_lock(abs_time) returns false then upgr //! is unaffected and this scoped_lock construction as the same effects //! as a default construction. //! c)Else upgr.owns() is false. mutex() obtains the value from upgr.release() - //! and owns() is set to false + //! and owns() is set to false //!Notes: This construction will not block. It will try to obtain mutex ownership //! from upgr immediately, while changing the lock type from a "read lock" to a //! "write lock". If the "read lock" isn't held in the first place, the mutex //! merely changes type to an unlocked "write lock". If the "read lock" is held, //! then mutex transfer occurs only if it can do so in a non-blocking manner. template - scoped_lock(BOOST_RV_REF(upgradable_lock) upgr, boost::posix_time::ptime &abs_time - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + scoped_lock(BOOST_INTERPROCESS_RV_REF(upgradable_lock) upgr, boost::posix_time::ptime &abs_time + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock &u_lock = upgr; @@ -214,14 +214,14 @@ class scoped_lock } //!Effects: If shar.owns() then calls try_unlock_sharable_and_lock() on the - //!referenced mutex. + //!referenced mutex. //! a)if try_unlock_sharable_and_lock() returns true then mutex() obtains - //! the value from shar.release() and owns() is set to true. + //! the value from shar.release() and owns() is set to true. //! b)if try_unlock_sharable_and_lock() returns false then shar is //! unaffected and this scoped_lock construction has the same - //! effects as a default construction. + //! effects as a default construction. //! c)Else shar.owns() is false. mutex() obtains the value from - //! shar.release() and owns() is set to false + //! shar.release() and owns() is set to false //!Notes: This construction will not block. It will try to obtain mutex //! ownership from shar immediately, while changing the lock type from a //! "read lock" to a "write lock". If the "read lock" isn't held in the @@ -229,8 +229,8 @@ class scoped_lock //! If the "read lock" is held, then mutex transfer occurs only if it can //! do so in a non-blocking manner. template - scoped_lock(BOOST_RV_REF(sharable_lock) shar, try_to_lock_type - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + scoped_lock(BOOST_INTERPROCESS_RV_REF(sharable_lock) shar, try_to_lock_type + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { sharable_lock &s_lock = shar; @@ -253,13 +253,13 @@ class scoped_lock } //!Effects: If owns() before the call, then unlock() is called on mutex(). - //! *this gets the state of scop and scop gets set to a default constructed state. + //! *this gets the state of scop and scop gets set to a default constructed state. //!Notes: With a recursive mutex it is possible that both this and scop own //! the same mutex before the assignment. In this case, this will own the //! mutex after the assignment (and scop will not), but the mutex's lock //! count will be decremented by one. - scoped_lock &operator=(BOOST_RV_REF(scoped_lock) scop) - { + scoped_lock &operator=(BOOST_INTERPROCESS_RV_REF(scoped_lock) scop) + { if(this->owns()) this->unlock(); m_locked = scop.owns(); @@ -281,7 +281,7 @@ class scoped_lock } //!Effects: If mutex() == 0 or if already locked, throws a lock_exception() - //! exception. Calls try_lock() on the referenced mutex. + //! exception. Calls try_lock() on the referenced mutex. //!Postconditions: owns() == the value returned from mutex()->try_lock(). //!Notes: The scoped_lock changes from a state of not owning the mutex, to //! owning the mutex, but only if blocking was not required. If the @@ -348,8 +348,8 @@ class scoped_lock m_locked = false; return mut; } - - //!Effects: Swaps state with moved lock. + + //!Effects: Swaps state with moved lock. //!Throws: Nothing. void swap( scoped_lock &other) { @@ -359,7 +359,7 @@ class scoped_lock /// @cond private: - mutex_type *mp_mutex; + mutex_type *mp_mutex; bool m_locked; /// @endcond }; diff --git a/utils/boost_idb/boost/interprocess/sync/sharable_lock.hpp b/utils/boost_idb/boost/interprocess/sync/sharable_lock.hpp index 11301957..42d0d050 100644 --- a/utils/boost_idb/boost/interprocess/sync/sharable_lock.hpp +++ b/utils/boost_idb/boost/interprocess/sync/sharable_lock.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include //!\file @@ -56,7 +56,7 @@ class sharable_lock typedef sharable_lock this_type; explicit sharable_lock(scoped_lock&); typedef bool this_type::*unspecified_bool_type; - BOOST_MOVABLE_BUT_NOT_COPYABLE(sharable_lock) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(sharable_lock) /// @endcond public: @@ -67,7 +67,7 @@ class sharable_lock {} //!Effects: m.lock_sharable(). - //!Postconditions: owns() == true and mutex() == &m. + //!Postconditions: owns() == true and mutex() == &m. //!Notes: The constructor will take sharable-ownership of the mutex. If //! another thread already owns the mutex with exclusive ownership //! (scoped_lock), this thread will block until the mutex is released. @@ -104,7 +104,7 @@ class sharable_lock : mp_mutex(&m), m_locked(false) { m_locked = mp_mutex->try_lock_sharable(); } - //!Effects: m.timed_lock_sharable(abs_time) + //!Effects: m.timed_lock_sharable(abs_time) //!Postconditions: mutex() == &m. owns() == the return value of the //! m.timed_lock_sharable() executed within the constructor. //!Notes: The constructor will take sharable-ownership of the mutex if it @@ -122,9 +122,9 @@ class sharable_lock //! sharable_lock with no blocking. If the upgr sharable_lock does not own the mutex, then //! neither will this sharable_lock. Only a moved sharable_lock's will match this //! signature. An non-moved sharable_lock can be moved with the expression: - //! "boost::move(lock);". This constructor does not alter the state of the mutex, + //! "boost::interprocess::move(lock);". This constructor does not alter the state of the mutex, //! only potentially who owns it. - sharable_lock(BOOST_RV_REF(sharable_lock) upgr) + sharable_lock(BOOST_INTERPROCESS_RV_REF(sharable_lock) upgr) : mp_mutex(0), m_locked(upgr.owns()) { mp_mutex = upgr.release(); } @@ -132,14 +132,14 @@ class sharable_lock //! referenced mutex. //!Postconditions: mutex() == the value upgr.mutex() had before the construction. //! upgr.mutex() == 0 owns() == the value of upgr.owns() before construction. - //! upgr.owns() == false after the construction. + //! upgr.owns() == false after the construction. //!Notes: If upgr is locked, this constructor will lock this sharable_lock while //! unlocking upgr. Only a moved sharable_lock's will match this //! signature. An non-moved upgradable_lock can be moved with the expression: - //! "boost::move(lock);".*/ + //! "boost::interprocess::move(lock);".*/ template - sharable_lock(BOOST_RV_REF(upgradable_lock) upgr - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + sharable_lock(BOOST_INTERPROCESS_RV_REF(upgradable_lock) upgr + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { upgradable_lock &u_lock = upgr; @@ -156,13 +156,13 @@ class sharable_lock //! scop.mutex() == 0 owns() == scop.owns() before the constructor. After the //! construction, scop.owns() == false. //!Notes: If scop is locked, this constructor will transfer the exclusive ownership - //! to a sharable-ownership of this sharable_lock. + //! to a sharable-ownership of this sharable_lock. //! Only a moved scoped_lock's will match this //! signature. An non-moved scoped_lock can be moved with the expression: - //! "boost::move(lock);". + //! "boost::interprocess::move(lock);". template - sharable_lock(BOOST_RV_REF(scoped_lock) scop - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + sharable_lock(BOOST_INTERPROCESS_RV_REF(scoped_lock) scop + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { scoped_lock &e_lock = scop; @@ -184,12 +184,12 @@ class sharable_lock } //!Effects: If owns() before the call, then unlock_sharable() is called on mutex(). - //! *this gets the state of upgr and upgr gets set to a default constructed state. + //! *this gets the state of upgr and upgr gets set to a default constructed state. //!Notes: With a recursive mutex it is possible that both this and upgr own the mutex //! before the assignment. In this case, this will own the mutex after the assignment //! (and upgr will not), but the mutex's lock count will be decremented by one. - sharable_lock &operator=(BOOST_RV_REF(sharable_lock) upgr) - { + sharable_lock &operator=(BOOST_INTERPROCESS_RV_REF(sharable_lock) upgr) + { if(this->owns()) this->unlock(); m_locked = upgr.owns(); @@ -203,7 +203,7 @@ class sharable_lock //!Notes: The sharable_lock changes from a state of not owning the //! mutex, to owning the mutex, blocking if necessary. void lock() - { + { if(!mp_mutex || m_locked) throw lock_exception(); mp_mutex->lock_sharable(); @@ -219,7 +219,7 @@ class sharable_lock //! mutex_type does not support try_lock_sharable(), this function will //! fail at compile time if instantiated, but otherwise have no effect. bool try_lock() - { + { if(!mp_mutex || m_locked) throw lock_exception(); m_locked = mp_mutex->try_lock_sharable(); @@ -236,7 +236,7 @@ class sharable_lock //! timed_lock_sharable(), this function will fail at compile time if //! instantiated, but otherwise have no effect. bool timed_lock(const boost::posix_time::ptime& abs_time) - { + { if(!mp_mutex || m_locked) throw lock_exception(); m_locked = mp_mutex->timed_lock_sharable(abs_time); @@ -282,7 +282,7 @@ class sharable_lock return mut; } - //!Effects: Swaps state with moved lock. + //!Effects: Swaps state with moved lock. //!Throws: Nothing. void swap(sharable_lock &other) { diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_condition.hpp b/utils/boost_idb/boost/interprocess/sync/shm/named_condition.hpp deleted file mode 100644 index be7a69fe..00000000 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_condition.hpp +++ /dev/null @@ -1,235 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_SHM_NAMED_CONDITION_HPP -#define BOOST_INTERPROCESS_SHM_NAMED_CONDITION_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) - #include - #include - #include -#else - #include -#endif - - -//!\file -//!Describes process-shared variables interprocess_condition class - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -/// @cond -class interprocess_tester; -/// @endcond - -//! A global condition variable that can be created by name. -//! This condition variable is designed to work with named_mutex and -//! can't be placed in shared memory or memory mapped files. -class shm_named_condition -{ - /// @cond - //Non-copyable - shm_named_condition(); - shm_named_condition(const shm_named_condition &); - shm_named_condition &operator=(const shm_named_condition &); - /// @endcond - public: - //!Creates a global condition with a name. - //!If the condition can't be created throws interprocess_exception - shm_named_condition(create_only_t create_only, const char *name, const permissions &perm = permissions()); - - //!Opens or creates a global condition with a name. - //!If the condition is created, this call is equivalent to - //!shm_named_condition(create_only_t, ... ) - //!If the condition is already created, this call is equivalent - //!shm_named_condition(open_only_t, ... ) - //!Does not throw - shm_named_condition(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()); - - //!Opens a global condition with a name if that condition is previously - //!created. If it is not previously created this function throws - //!interprocess_exception. - shm_named_condition(open_only_t open_only, const char *name); - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~shm_named_condition(); - - //!If there is a thread waiting on *this, change that - //!thread's state to ready. Otherwise there is no effect.*/ - void notify_one(); - - //!Change the state of all threads waiting on *this to ready. - //!If there are no waiting threads, notify_all() has no effect. - void notify_all(); - - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), and then reacquires the lock. - template - void wait(L& lock); - - //!The same as: - //!while (!pred()) wait(lock) - template - void wait(L& lock, Pr pred); - - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, - //!and then reacquires the lock. - //!Returns: false if time abs_time is reached, otherwise true. - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time); - - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); - //! } return true; - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred); - - //!Erases a named condition from the system. - //!Returns false on error. Never throws. - static bool remove(const char *name); - - /// @cond - private: - - #if defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) - class internal_condition_members - { - public: - typedef interprocess_mutex mutex_type; - typedef interprocess_condition condvar_type; - - condvar_type& get_condvar() { return m_cond; } - mutex_type& get_mutex() { return m_mtx; } - - private: - mutex_type m_mtx; - condvar_type m_cond; - }; - - typedef ipcdetail::condition_any_wrapper internal_condition; - #else //defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) - typedef interprocess_condition internal_condition; - #endif //defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES) - - internal_condition &internal_cond() - { return *static_cast(m_shmem.get_user_address()); } - - friend class boost::interprocess::ipcdetail::interprocess_tester; - void dont_close_on_destruction(); - - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - - template friend class boost::interprocess::ipcdetail::named_creation_functor; - typedef boost::interprocess::ipcdetail::named_creation_functor construct_func_t; - /// @endcond -}; - -/// @cond - -inline shm_named_condition::~shm_named_condition() -{} - -inline shm_named_condition::shm_named_condition(create_only_t, const char *name, const permissions &perm) - : m_shmem (create_only - ,name - ,sizeof(internal_condition) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoCreate) - ,perm) -{} - -inline shm_named_condition::shm_named_condition(open_or_create_t, const char *name, const permissions &perm) - : m_shmem (open_or_create - ,name - ,sizeof(internal_condition) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoOpenOrCreate) - ,perm) -{} - -inline shm_named_condition::shm_named_condition(open_only_t, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(DoOpen)) -{} - -inline void shm_named_condition::dont_close_on_destruction() -{ interprocess_tester::dont_close_on_destruction(m_shmem); } - -inline void shm_named_condition::notify_one() -{ this->internal_cond().notify_one(); } - -inline void shm_named_condition::notify_all() -{ this->internal_cond().notify_all(); } - -template -inline void shm_named_condition::wait(L& lock) -{ this->internal_cond().wait(lock); } - -template -inline void shm_named_condition::wait(L& lock, Pr pred) -{ this->internal_cond().wait(lock, pred); } - -template -inline bool shm_named_condition::timed_wait - (L& lock, const boost::posix_time::ptime &abs_time) -{ return this->internal_cond().timed_wait(lock, abs_time); } - -template -inline bool shm_named_condition::timed_wait - (L& lock, const boost::posix_time::ptime &abs_time, Pr pred) -{ return this->internal_cond().timed_wait(lock, abs_time, pred); } - -inline bool shm_named_condition::remove(const char *name) -{ return shared_memory_object::remove(name); } - -/// @endcond - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif // BOOST_INTERPROCESS_SHM_NAMED_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_condition_any.hpp b/utils/boost_idb/boost/interprocess/sync/shm/named_condition_any.hpp deleted file mode 100644 index 7bac854c..00000000 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_condition_any.hpp +++ /dev/null @@ -1,191 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP -#define BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes process-shared variables interprocess_condition class - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -/// @cond -class interprocess_tester; -/// @endcond - -//! A global condition variable that can be created by name. -//! This condition variable is designed to work with named_mutex and -//! can't be placed in shared memory or memory mapped files. -class shm_named_condition_any -{ - /// @cond - //Non-copyable - shm_named_condition_any(); - shm_named_condition_any(const shm_named_condition_any &); - shm_named_condition_any &operator=(const shm_named_condition_any &); - /// @endcond - public: - //!Creates a global condition with a name. - //!If the condition can't be created throws interprocess_exception - shm_named_condition_any(create_only_t create_only, const char *name, const permissions &perm = permissions()) - : m_shmem (create_only - ,name - ,sizeof(internal_condition) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoCreate) - ,perm) - {} - - //!Opens or creates a global condition with a name. - //!If the condition is created, this call is equivalent to - //!shm_named_condition_any(create_only_t, ... ) - //!If the condition is already created, this call is equivalent - //!shm_named_condition_any(open_only_t, ... ) - //!Does not throw - shm_named_condition_any(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()) - : m_shmem (open_or_create - ,name - ,sizeof(internal_condition) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoOpenOrCreate) - ,perm) - {} - - //!Opens a global condition with a name if that condition is previously - //!created. If it is not previously created this function throws - //!interprocess_exception. - shm_named_condition_any(open_only_t open_only, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(DoOpen)) - {} - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~shm_named_condition_any() - {} - - //!If there is a thread waiting on *this, change that - //!thread's state to ready. Otherwise there is no effect.*/ - void notify_one() - { m_cond.notify_one(); } - - //!Change the state of all threads waiting on *this to ready. - //!If there are no waiting threads, notify_all() has no effect. - void notify_all() - { m_cond.notify_all(); } - - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), and then reacquires the lock. - template - void wait(L& lock) - { m_cond.wait(lock); } - - //!The same as: - //!while (!pred()) wait(lock) - template - void wait(L& lock, Pr pred) - { m_cond.wait(lock, pred); } - - //!Releases the lock on the named_mutex object associated with lock, blocks - //!the current thread of execution until readied by a call to - //!this->notify_one() or this->notify_all(), or until time abs_time is reached, - //!and then reacquires the lock. - //!Returns: false if time abs_time is reached, otherwise true. - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { return m_cond.timed_wait(lock, abs_time); } - - //!The same as: while (!pred()) { - //! if (!timed_wait(lock, abs_time)) return pred(); - //! } return true; - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { return m_cond.timed_wait(lock, abs_time, pred); } - - //!Erases a named condition from the system. - //!Returns false on error. Never throws. - static bool remove(const char *name) - { return shared_memory_object::remove(name); } - - /// @cond - private: - - class internal_condition_members - { - public: - typedef interprocess_mutex mutex_type; - typedef interprocess_condition condvar_type; - - condvar_type& get_condvar() { return m_cond; } - mutex_type& get_mutex() { return m_mtx; } - - private: - mutex_type m_mtx; - condvar_type m_cond; - }; - - typedef ipcdetail::condition_any_wrapper internal_condition; - - internal_condition m_cond; - - friend class boost::interprocess::ipcdetail::interprocess_tester; - void dont_close_on_destruction() - { interprocess_tester::dont_close_on_destruction(m_shmem); } - - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - - template friend class boost::interprocess::ipcdetail::named_creation_functor; - typedef boost::interprocess::ipcdetail::named_creation_functor construct_func_t; - /// @endcond -}; - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif // BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/shm/named_mutex.hpp deleted file mode 100644 index 9532f8d8..00000000 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_mutex.hpp +++ /dev/null @@ -1,183 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_SHM_NAMED_MUTEX_HPP -#define BOOST_INTERPROCESS_SHM_NAMED_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -//!\file -//!Describes a named mutex class for inter-process synchronization - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class named_condition; - -//!A mutex with a global name, so it can be found from different -//!processes. This mutex can't be placed in shared memory, and -//!each process should have it's own named mutex. -class shm_named_mutex -{ - /// @cond - - //Non-copyable - shm_named_mutex(); - shm_named_mutex(const shm_named_mutex &); - shm_named_mutex &operator=(const shm_named_mutex &); - friend class named_condition; - /// @endcond - - public: - //!Creates a global interprocess_mutex with a name. - //!Throws interprocess_exception on error. - shm_named_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - - //!Opens or creates a global mutex with a name. - //!If the mutex is created, this call is equivalent to - //!shm_named_mutex(create_only_t, ... ) - //!If the mutex is already created, this call is equivalent - //!shm_named_mutex(open_only_t, ... ) - //!Does not throw - shm_named_mutex(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()); - - //!Opens a global mutex with a name if that mutex is previously - //!created. If it is not previously created this function throws - //!interprocess_exception. - shm_named_mutex(open_only_t open_only, const char *name); - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~shm_named_mutex(); - - //!Unlocks a previously locked - //!interprocess_mutex. - void unlock(); - - //!Locks interprocess_mutex, sleeps when interprocess_mutex is already locked. - //!Throws interprocess_exception if a severe error is found - void lock(); - - //!Tries to lock the interprocess_mutex, returns false when interprocess_mutex - //!is already locked, returns true when success. - //!Throws interprocess_exception if a severe error is found - bool try_lock(); - - //!Tries to lock the interprocess_mutex until time abs_time, - //!Returns false when timeout expires, returns true when locks. - //!Throws interprocess_exception if a severe error is found - bool timed_lock(const boost::posix_time::ptime &abs_time); - - //!Erases a named mutex from the system. - //!Returns false on error. Never throws. - static bool remove(const char *name); - - /// @cond - typedef interprocess_mutex internal_mutex_type; - interprocess_mutex &internal_mutex() - { return *static_cast(m_shmem.get_user_address()); } - - private: - friend class ipcdetail::interprocess_tester; - void dont_close_on_destruction(); - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - typedef ipcdetail::named_creation_functor construct_func_t; - /// @endcond -}; - -/// @cond - -inline void shm_named_mutex::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_shmem); } - -inline shm_named_mutex::~shm_named_mutex() -{} - -inline shm_named_mutex::shm_named_mutex(create_only_t, const char *name, const permissions &perm) - : m_shmem (create_only - ,name - ,sizeof(interprocess_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoCreate) - ,perm) -{} - -inline shm_named_mutex::shm_named_mutex(open_or_create_t, const char *name, const permissions &perm) - : m_shmem (open_or_create - ,name - ,sizeof(interprocess_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoOpenOrCreate) - ,perm) -{} - -inline shm_named_mutex::shm_named_mutex(open_only_t, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoOpen)) -{} - -inline void shm_named_mutex::lock() -{ this->internal_mutex().lock(); } - -inline void shm_named_mutex::unlock() -{ this->internal_mutex().unlock(); } - -inline bool shm_named_mutex::try_lock() -{ return this->internal_mutex().try_lock(); } - -inline bool shm_named_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - return this->internal_mutex().timed_lock(abs_time); -} - -inline bool shm_named_mutex::remove(const char *name) -{ return shared_memory_object::remove(name); } - -/// @endcond - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_SHM_NAMED_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/shm/named_recursive_mutex.hpp deleted file mode 100644 index 0250e310..00000000 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_recursive_mutex.hpp +++ /dev/null @@ -1,173 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_SHM_NAMED_RECURSIVE_MUTEX_HPP -#define BOOST_INTERPROCESS_SHM_NAMED_RECURSIVE_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes a named shm_named_recursive_mutex class for inter-process synchronization - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -/// @cond -class interprocess_tester; -/// @endcond - -class shm_named_recursive_mutex -{ - /// @cond - //Non-copyable - shm_named_recursive_mutex(); - shm_named_recursive_mutex(const shm_named_recursive_mutex &); - shm_named_recursive_mutex &operator=(const shm_named_recursive_mutex &); - /// @endcond - public: - - //!Creates a global recursive_mutex with a name. - //!If the recursive_mutex can't be created throws interprocess_exception - shm_named_recursive_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - - //!Opens or creates a global recursive_mutex with a name. - //!If the recursive_mutex is created, this call is equivalent to - //!shm_named_recursive_mutex(create_only_t, ... ) - //!If the recursive_mutex is already created, this call is equivalent - //!shm_named_recursive_mutex(open_only_t, ... ) - //!Does not throw - shm_named_recursive_mutex(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()); - - //!Opens a global recursive_mutex with a name if that recursive_mutex is previously - //!created. If it is not previously created this function throws - //!interprocess_exception. - shm_named_recursive_mutex(open_only_t open_only, const char *name); - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~shm_named_recursive_mutex(); - - //!Unlocks a previously locked - //!shm_named_recursive_mutex. - void unlock(); - - //!Locks shm_named_recursive_mutex, sleeps when shm_named_recursive_mutex is already locked. - //!Throws interprocess_exception if a severe error is found. - void lock(); - - //!Tries to lock the shm_named_recursive_mutex, returns false when shm_named_recursive_mutex - //!is already locked, returns true when success. - //!Throws interprocess_exception if a severe error is found. - bool try_lock(); - - //!Tries to lock the shm_named_recursive_mutex until time abs_time, - //!Returns false when timeout expires, returns true when locks. - //!Throws interprocess_exception if a severe error is found - bool timed_lock(const boost::posix_time::ptime &abs_time); - - //!Erases a named recursive mutex - //!from the system - static bool remove(const char *name); - - /// @cond - private: - friend class interprocess_tester; - void dont_close_on_destruction(); - - interprocess_recursive_mutex *mutex() const - { return static_cast(m_shmem.get_user_address()); } - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - typedef named_creation_functor construct_func_t; - /// @endcond -}; - -inline shm_named_recursive_mutex::~shm_named_recursive_mutex() -{} - -inline void shm_named_recursive_mutex::dont_close_on_destruction() -{ interprocess_tester::dont_close_on_destruction(m_shmem); } - -inline shm_named_recursive_mutex::shm_named_recursive_mutex(create_only_t, const char *name, const permissions &perm) - : m_shmem (create_only - ,name - ,sizeof(interprocess_recursive_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoCreate) - ,perm) -{} - -inline shm_named_recursive_mutex::shm_named_recursive_mutex(open_or_create_t, const char *name, const permissions &perm) - : m_shmem (open_or_create - ,name - ,sizeof(interprocess_recursive_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoOpenOrCreate) - ,perm) -{} - -inline shm_named_recursive_mutex::shm_named_recursive_mutex(open_only_t, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(DoOpen)) -{} - -inline void shm_named_recursive_mutex::lock() -{ this->mutex()->lock(); } - -inline void shm_named_recursive_mutex::unlock() -{ this->mutex()->unlock(); } - -inline bool shm_named_recursive_mutex::try_lock() -{ return this->mutex()->try_lock(); } - -inline bool shm_named_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - return this->mutex()->timed_lock(abs_time); -} - -inline bool shm_named_recursive_mutex::remove(const char *name) -{ return shared_memory_object::remove(name); } - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_SHM_NAMED_RECURSIVE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/shm/named_semaphore.hpp deleted file mode 100644 index ebd7e098..00000000 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_semaphore.hpp +++ /dev/null @@ -1,140 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_SHM_NAMED_SEMAPHORE_HPP -#define BOOST_INTERPROCESS_SHM_NAMED_SEMAPHORE_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class shm_named_semaphore -{ - /// @cond - - //Non-copyable - shm_named_semaphore(); - shm_named_semaphore(const shm_named_semaphore &); - shm_named_semaphore &operator=(const shm_named_semaphore &); - /// @endcond - - public: - shm_named_semaphore(create_only_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()); - - shm_named_semaphore(open_or_create_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()); - - shm_named_semaphore(open_only_t, const char *name); - - ~shm_named_semaphore(); - - void post(); - void wait(); - bool try_wait(); - bool timed_wait(const boost::posix_time::ptime &abs_time); - - static bool remove(const char *name); - - /// @cond - private: - friend class interprocess_tester; - void dont_close_on_destruction(); - - interprocess_semaphore *semaphore() const - { return static_cast(m_shmem.get_user_address()); } - - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - typedef named_creation_functor construct_func_t; - /// @endcond -}; - -inline shm_named_semaphore::~shm_named_semaphore() -{} - -inline void shm_named_semaphore::dont_close_on_destruction() -{ interprocess_tester::dont_close_on_destruction(m_shmem); } - -inline shm_named_semaphore::shm_named_semaphore - (create_only_t, const char *name, unsigned int initialCount, const permissions &perm) - : m_shmem (create_only - ,name - ,sizeof(interprocess_semaphore) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoCreate, initialCount) - ,perm) -{} - -inline shm_named_semaphore::shm_named_semaphore - (open_or_create_t, const char *name, unsigned int initialCount, const permissions &perm) - : m_shmem (open_or_create - ,name - ,sizeof(interprocess_semaphore) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(DoOpenOrCreate, initialCount) - ,perm) -{} - -inline shm_named_semaphore::shm_named_semaphore - (open_only_t, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(DoOpen, 0)) -{} - -inline void shm_named_semaphore::post() -{ semaphore()->post(); } - -inline void shm_named_semaphore::wait() -{ semaphore()->wait(); } - -inline bool shm_named_semaphore::try_wait() -{ return semaphore()->try_wait(); } - -inline bool shm_named_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->wait(); - return true; - } - return semaphore()->timed_wait(abs_time); -} - -inline bool shm_named_semaphore::remove(const char *name) -{ return shared_memory_object::remove(name); } - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_SHM_NAMED_SEMAPHORE_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/shm/named_upgradable_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/shm/named_upgradable_mutex.hpp deleted file mode 100644 index 26a0747e..00000000 --- a/utils/boost_idb/boost/interprocess/sync/shm/named_upgradable_mutex.hpp +++ /dev/null @@ -1,371 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_NAMED_UPGRADABLE_MUTEX_HPP -#define BOOST_INTERPROCESS_NAMED_UPGRADABLE_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes a named upgradable mutex class for inter-process synchronization - -namespace boost { -namespace interprocess { - -/// @cond -namespace ipcdetail{ class interprocess_tester; } -/// @endcond - -class named_condition; - -//!A upgradable mutex with a global name, so it can be found from different -//!processes. This mutex can't be placed in shared memory, and -//!each process should have it's own named upgradable mutex. -class named_upgradable_mutex -{ - /// @cond - //Non-copyable - named_upgradable_mutex(); - named_upgradable_mutex(const named_upgradable_mutex &); - named_upgradable_mutex &operator=(const named_upgradable_mutex &); - friend class named_condition; - /// @endcond - public: - - //!Creates a global upgradable mutex with a name. - //!If the upgradable mutex can't be created throws interprocess_exception - named_upgradable_mutex(create_only_t create_only, const char *name, const permissions &perm = permissions()); - - //!Opens or creates a global upgradable mutex with a name, and an initial count. - //!If the upgradable mutex is created, this call is equivalent to - //!named_upgradable_mutex(create_only_t, ...) - //!If the upgradable mutex is already created, this call is equivalent to - //!named_upgradable_mutex(open_only_t, ... ). - named_upgradable_mutex(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()); - - //!Opens a global upgradable mutex with a name if that upgradable mutex - //!is previously. - //!created. If it is not previously created this function throws - //!interprocess_exception. - named_upgradable_mutex(open_only_t open_only, const char *name); - - //!Destroys *this and indicates that the calling process is finished using - //!the resource. The destructor function will deallocate - //!any system resources allocated by the system for use by this process for - //!this resource. The resource can still be opened again calling - //!the open constructor overload. To erase the resource from the system - //!use remove(). - ~named_upgradable_mutex(); - - //Exclusive locking - - //!Effects: The calling thread tries to obtain exclusive ownership of the mutex, - //! and if another thread has exclusive, sharable or upgradable ownership of - //! the mutex, it waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock(); - - //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! without waiting. If no other thread has exclusive, sharable or upgradable - //! ownership of the mutex this succeeds. - //!Returns: If it can acquire exclusive ownership immediately returns true. - //! If it has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock(); - - //!Effects: The calling thread tries to acquire exclusive ownership of the mutex - //! waiting if necessary until no other thread has exclusive, sharable or - //! upgradable ownership of the mutex or abs_time is reached. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The calling thread releases the exclusive ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock(); - - //Sharable locking - - //!Effects: The calling thread tries to obtain sharable ownership of the mutex, - //! and if another thread has exclusive ownership of the mutex, - //! waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock_sharable(); - - //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! without waiting. If no other thread has exclusive ownership - //! of the mutex this succeeds. - //!Returns: If it can acquire sharable ownership immediately returns true. If it - //! has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock_sharable(); - - //!Effects: The calling thread tries to acquire sharable ownership of the mutex - //! waiting if necessary until no other thread has exclusive - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires sharable ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock_sharable(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The calling thread releases the sharable ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_sharable(); - - //Upgradable locking - - //!Effects: The calling thread tries to obtain upgradable ownership of the mutex, - //! and if another thread has exclusive or upgradable ownership of the mutex, - //! waits until it can obtain the ownership. - //!Throws: interprocess_exception on error. - void lock_upgradable(); - - //!Effects: The calling thread tries to acquire upgradable ownership of the mutex - //! without waiting. If no other thread has exclusive or upgradable ownership - //! of the mutex this succeeds. - //!Returns: If it can acquire upgradable ownership immediately returns true. - //! If it has to wait, returns false. - //!Throws: interprocess_exception on error. - bool try_lock_upgradable(); - - //!Effects: The calling thread tries to acquire upgradable ownership of the mutex - //! waiting if necessary until no other thread has exclusive or upgradable - //! ownership of the mutex or abs_time is reached. - //!Returns: If acquires upgradable ownership, returns true. Otherwise returns false. - //!Throws: interprocess_exception on error. - bool timed_lock_upgradable(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The calling thread releases the upgradable ownership of the mutex. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_upgradable(); - - //Demotions - - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The thread atomically releases exclusive ownership and acquires - //! upgradable ownership. This operation is non-blocking. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_and_lock_upgradable(); - - //!Precondition: The thread must have exclusive ownership of the mutex. - //!Effects: The thread atomically releases exclusive ownership and acquires - //! sharable ownership. This operation is non-blocking. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_and_lock_sharable(); - - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The thread atomically releases upgradable ownership and acquires - //! sharable ownership. This operation is non-blocking. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_upgradable_and_lock_sharable(); - - //Promotions - - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The thread atomically releases upgradable ownership and acquires - //! exclusive ownership. This operation will block until all threads with - //! sharable ownership release it. - //!Throws: An exception derived from interprocess_exception on error. - void unlock_upgradable_and_lock(); - - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The thread atomically releases upgradable ownership and tries to - //! acquire exclusive ownership. This operation will fail if there are threads - //! with sharable ownership, but it will maintain upgradable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. - //!Throws: An exception derived from interprocess_exception on error. - bool try_unlock_upgradable_and_lock(); - - //!Precondition: The thread must have upgradable ownership of the mutex. - //!Effects: The thread atomically releases upgradable ownership and tries to acquire - //! exclusive ownership, waiting if necessary until abs_time. This operation will - //! fail if there are threads with sharable ownership or timeout reaches, but it - //! will maintain upgradable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. - //!Throws: An exception derived from interprocess_exception on error. - bool timed_unlock_upgradable_and_lock(const boost::posix_time::ptime &abs_time); - - //!Precondition: The thread must have sharable ownership of the mutex. - //!Effects: The thread atomically releases sharable ownership and tries to acquire - //! exclusive ownership. This operation will fail if there are threads with sharable - //! or upgradable ownership, but it will maintain sharable ownership. - //!Returns: If acquires exclusive ownership, returns true. Otherwise returns false. - //!Throws: An exception derived from interprocess_exception on error. - bool try_unlock_sharable_and_lock(); - - bool try_unlock_sharable_and_lock_upgradable(); - - //!Erases a named upgradable mutex from the system. - //!Returns false on error. Never throws. - static bool remove(const char *name); - - /// @cond - private: - friend class ipcdetail::interprocess_tester; - void dont_close_on_destruction(); - - interprocess_upgradable_mutex *mutex() const - { return static_cast(m_shmem.get_user_address()); } - - typedef ipcdetail::managed_open_or_create_impl open_create_impl_t; - open_create_impl_t m_shmem; - typedef ipcdetail::named_creation_functor construct_func_t; - /// @endcond -}; - -/// @cond - -inline named_upgradable_mutex::~named_upgradable_mutex() -{} - -inline named_upgradable_mutex::named_upgradable_mutex - (create_only_t, const char *name, const permissions &perm) - : m_shmem (create_only - ,name - ,sizeof(interprocess_upgradable_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoCreate) - ,perm) -{} - -inline named_upgradable_mutex::named_upgradable_mutex - (open_or_create_t, const char *name, const permissions &perm) - : m_shmem (open_or_create - ,name - ,sizeof(interprocess_upgradable_mutex) + - open_create_impl_t::ManagedOpenOrCreateUserOffset - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoOpenOrCreate) - ,perm) -{} - -inline named_upgradable_mutex::named_upgradable_mutex - (open_only_t, const char *name) - : m_shmem (open_only - ,name - ,read_write - ,0 - ,construct_func_t(ipcdetail::DoOpen)) -{} - -inline void named_upgradable_mutex::dont_close_on_destruction() -{ ipcdetail::interprocess_tester::dont_close_on_destruction(m_shmem); } - -inline void named_upgradable_mutex::lock() -{ this->mutex()->lock(); } - -inline void named_upgradable_mutex::unlock() -{ this->mutex()->unlock(); } - -inline bool named_upgradable_mutex::try_lock() -{ return this->mutex()->try_lock(); } - -inline bool named_upgradable_mutex::timed_lock - (const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - return this->mutex()->timed_lock(abs_time); -} - -inline void named_upgradable_mutex::lock_upgradable() -{ this->mutex()->lock_upgradable(); } - -inline void named_upgradable_mutex::unlock_upgradable() -{ this->mutex()->unlock_upgradable(); } - -inline bool named_upgradable_mutex::try_lock_upgradable() -{ return this->mutex()->try_lock_upgradable(); } - -inline bool named_upgradable_mutex::timed_lock_upgradable - (const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock_upgradable(); - return true; - } - return this->mutex()->timed_lock_upgradable(abs_time); -} - -inline void named_upgradable_mutex::lock_sharable() -{ this->mutex()->lock_sharable(); } - -inline void named_upgradable_mutex::unlock_sharable() -{ this->mutex()->unlock_sharable(); } - -inline bool named_upgradable_mutex::try_lock_sharable() -{ return this->mutex()->try_lock_sharable(); } - -inline bool named_upgradable_mutex::timed_lock_sharable - (const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock_sharable(); - return true; - } - return this->mutex()->timed_lock_sharable(abs_time); -} - -inline void named_upgradable_mutex::unlock_and_lock_upgradable() -{ this->mutex()->unlock_and_lock_upgradable(); } - -inline void named_upgradable_mutex::unlock_and_lock_sharable() -{ this->mutex()->unlock_and_lock_sharable(); } - -inline void named_upgradable_mutex::unlock_upgradable_and_lock_sharable() -{ this->mutex()->unlock_upgradable_and_lock_sharable(); } - -inline void named_upgradable_mutex::unlock_upgradable_and_lock() -{ this->mutex()->unlock_upgradable_and_lock(); } - -inline bool named_upgradable_mutex::try_unlock_upgradable_and_lock() -{ return this->mutex()->try_unlock_upgradable_and_lock(); } - -inline bool named_upgradable_mutex::timed_unlock_upgradable_and_lock - (const boost::posix_time::ptime &abs_time) -{ return this->mutex()->timed_unlock_upgradable_and_lock(abs_time); } - -inline bool named_upgradable_mutex::try_unlock_sharable_and_lock() -{ return this->mutex()->try_unlock_sharable_and_lock(); } - -inline bool named_upgradable_mutex::try_unlock_sharable_and_lock_upgradable() -{ return this->mutex()->try_unlock_sharable_and_lock_upgradable(); } - -inline bool named_upgradable_mutex::remove(const char *name) -{ return shared_memory_object::remove(name); } - -/// @endcond - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_NAMED_UPGRADABLE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/spin/condition.hpp b/utils/boost_idb/boost/interprocess/sync/spin/condition.hpp deleted file mode 100644 index be863332..00000000 --- a/utils/boost_idb/boost/interprocess/sync/spin/condition.hpp +++ /dev/null @@ -1,292 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_SPIN_CONDITION_HPP -#define BOOST_INTERPROCESS_DETAIL_SPIN_CONDITION_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class spin_condition -{ - spin_condition(const spin_condition &); - spin_condition &operator=(const spin_condition &); - public: - spin_condition(); - ~spin_condition(); - - void notify_one(); - void notify_all(); - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock); - return true; - } - if (!lock) - throw lock_exception(); - return this->do_timed_wait(abs_time, *lock.mutex()); - } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(lock, pred); - return true; - } - if (!lock) - throw lock_exception(); - while (!pred()){ - if (!this->do_timed_wait(abs_time, *lock.mutex())) - return pred(); - } - return true; - } - - template - void wait(L& lock) - { - if (!lock) - throw lock_exception(); - do_wait(*lock.mutex()); - } - - template - void wait(L& lock, Pr pred) - { - if (!lock) - throw lock_exception(); - - while (!pred()) - do_wait(*lock.mutex()); - } - - template - void do_wait(InterprocessMutex &mut); - - template - bool do_timed_wait(const boost::posix_time::ptime &abs_time, InterprocessMutex &mut); - - private: - template - bool do_timed_wait(bool tout_enabled, const boost::posix_time::ptime &abs_time, InterprocessMutex &mut); - - enum { SLEEP = 0, NOTIFY_ONE, NOTIFY_ALL }; - spin_mutex m_enter_mut; - volatile boost::uint32_t m_command; - volatile boost::uint32_t m_num_waiters; - void notify(boost::uint32_t command); -}; - -inline spin_condition::spin_condition() -{ - //Note that this class is initialized to zero. - //So zeroed memory can be interpreted as an initialized - //condition variable - m_command = SLEEP; - m_num_waiters = 0; -} - -inline spin_condition::~spin_condition() -{ - //Trivial destructor -} - -inline void spin_condition::notify_one() -{ - this->notify(NOTIFY_ONE); -} - -inline void spin_condition::notify_all() -{ - this->notify(NOTIFY_ALL); -} - -inline void spin_condition::notify(boost::uint32_t command) -{ - //This mutex guarantees that no other thread can enter to the - //do_timed_wait method logic, so that thread count will be - //constant until the function writes a NOTIFY_ALL command. - //It also guarantees that no other notification can be signaled - //on this spin_condition before this one ends - m_enter_mut.lock(); - - //Return if there are no waiters - if(!atomic_read32(&m_num_waiters)) { - m_enter_mut.unlock(); - return; - } - - //Notify that all threads should execute wait logic - spin_wait swait; - while(SLEEP != atomic_cas32(const_cast(&m_command), command, SLEEP)){ - swait.yield(); - } - //The enter mutex will rest locked until the last waiting thread unlocks it -} - -template -inline void spin_condition::do_wait(InterprocessMutex &mut) -{ - this->do_timed_wait(false, boost::posix_time::ptime(), mut); -} - -template -inline bool spin_condition::do_timed_wait - (const boost::posix_time::ptime &abs_time, InterprocessMutex &mut) -{ - return this->do_timed_wait(true, abs_time, mut); -} - -template -inline bool spin_condition::do_timed_wait(bool tout_enabled, - const boost::posix_time::ptime &abs_time, - InterprocessMutex &mut) -{ - boost::posix_time::ptime now = microsec_clock::universal_time(); - - if(tout_enabled){ - if(now >= abs_time) return false; - } - - typedef boost::interprocess::scoped_lock InternalLock; - //The enter mutex guarantees that while executing a notification, - //no other thread can execute the do_timed_wait method. - { - //--------------------------------------------------------------- - InternalLock lock; - if(tout_enabled){ - InternalLock dummy(m_enter_mut, abs_time); - lock = boost::move(dummy); - } - else{ - InternalLock dummy(m_enter_mut); - lock = boost::move(dummy); - } - - if(!lock) - return false; - //--------------------------------------------------------------- - //We increment the waiting thread count protected so that it will be - //always constant when another thread enters the notification logic. - //The increment marks this thread as "waiting on spin_condition" - atomic_inc32(const_cast(&m_num_waiters)); - - //We unlock the external mutex atomically with the increment - mut.unlock(); - } - - //By default, we suppose that no timeout has happened - bool timed_out = false, unlock_enter_mut= false; - - //Loop until a notification indicates that the thread should - //exit or timeout occurs - while(1){ - //The thread sleeps/spins until a spin_condition commands a notification - //Notification occurred, we will lock the checking mutex so that - spin_wait swait; - while(atomic_read32(&m_command) == SLEEP){ - swait.yield(); - - //Check for timeout - if(tout_enabled){ - now = microsec_clock::universal_time(); - - if(now >= abs_time){ - //If we can lock the mutex it means that no notification - //is being executed in this spin_condition variable - timed_out = m_enter_mut.try_lock(); - - //If locking fails, indicates that another thread is executing - //notification, so we play the notification game - if(!timed_out){ - //There is an ongoing notification, we will try again later - continue; - } - //No notification in execution, since enter mutex is locked. - //We will execute time-out logic, so we will decrement count, - //release the enter mutex and return false. - break; - } - } - } - - //If a timeout occurred, the mutex will not execute checking logic - if(tout_enabled && timed_out){ - //Decrement wait count - atomic_dec32(const_cast(&m_num_waiters)); - unlock_enter_mut = true; - break; - } - else{ - boost::uint32_t result = atomic_cas32 - (const_cast(&m_command), SLEEP, NOTIFY_ONE); - if(result == SLEEP){ - //Other thread has been notified and since it was a NOTIFY one - //command, this thread must sleep again - continue; - } - else if(result == NOTIFY_ONE){ - //If it was a NOTIFY_ONE command, only this thread should - //exit. This thread has atomically marked command as sleep before - //so no other thread will exit. - //Decrement wait count. - unlock_enter_mut = true; - atomic_dec32(const_cast(&m_num_waiters)); - break; - } - else{ - //If it is a NOTIFY_ALL command, all threads should return - //from do_timed_wait function. Decrement wait count. - unlock_enter_mut = 1 == atomic_dec32(const_cast(&m_num_waiters)); - //Check if this is the last thread of notify_all waiters - //Only the last thread will release the mutex - if(unlock_enter_mut){ - atomic_cas32(const_cast(&m_command), SLEEP, NOTIFY_ALL); - } - break; - } - } - } - - //Unlock the enter mutex if it is a single notification, if this is - //the last notified thread in a notify_all or a timeout has occurred - if(unlock_enter_mut){ - m_enter_mut.unlock(); - } - - //Lock external again before returning from the method - mut.lock(); - return !timed_out; -} - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_SPIN_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/spin/mutex.hpp b/utils/boost_idb/boost/interprocess/sync/spin/mutex.hpp deleted file mode 100644 index 7a77549e..00000000 --- a/utils/boost_idb/boost/interprocess/sync/spin/mutex.hpp +++ /dev/null @@ -1,117 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_SPIN_MUTEX_HPP -#define BOOST_INTERPROCESS_DETAIL_SPIN_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class spin_mutex -{ - spin_mutex(const spin_mutex &); - spin_mutex &operator=(const spin_mutex &); - public: - - spin_mutex(); - ~spin_mutex(); - - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - void unlock(); - void take_ownership(){}; - private: - volatile boost::uint32_t m_s; -}; - -inline spin_mutex::spin_mutex() - : m_s(0) -{ - //Note that this class is initialized to zero. - //So zeroed memory can be interpreted as an - //initialized mutex -} - -inline spin_mutex::~spin_mutex() -{ - //Trivial destructor -} - -inline void spin_mutex::lock(void) -{ - spin_wait swait; - do{ - boost::uint32_t prev_s = ipcdetail::atomic_cas32(const_cast(&m_s), 1, 0); - - if (m_s == 1 && prev_s == 0){ - break; - } - // relinquish current timeslice - swait.yield(); - }while (true); -} - -inline bool spin_mutex::try_lock(void) -{ - boost::uint32_t prev_s = ipcdetail::atomic_cas32(const_cast(&m_s), 1, 0); - return m_s == 1 && prev_s == 0; -} - -inline bool spin_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - //Obtain current count and target time - boost::posix_time::ptime now = microsec_clock::universal_time(); - - spin_wait swait; - do{ - if(this->try_lock()){ - break; - } - now = microsec_clock::universal_time(); - - if(now >= abs_time){ - return false; - } - // relinquish current time slice - swait.yield(); - }while (true); - - return true; -} - -inline void spin_mutex::unlock(void) -{ ipcdetail::atomic_cas32(const_cast(&m_s), 0, 1); } - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_SPIN_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/spin/recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/spin/recursive_mutex.hpp deleted file mode 100644 index 38e9dcaa..00000000 --- a/utils/boost_idb/boost/interprocess/sync/spin/recursive_mutex.hpp +++ /dev/null @@ -1,175 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -// -// Parts of the pthread code come from Boost Threads code: -// -////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2001-2003 -// William E. Kempf -// -// Permission to use, copy, modify, distribute and sell this software -// and its documentation for any purpose is hereby granted without fee, -// provided that the above copyright notice appear in all copies and -// that both that copyright notice and this permission notice appear -// in supporting documentation. William E. Kempf makes no representations -// about the suitability of this software for any purpose. -// It is provided "as is" without express or implied warranty. -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_SPIN_RECURSIVE_MUTEX_HPP -#define BOOST_INTERPROCESS_DETAIL_SPIN_RECURSIVE_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class spin_recursive_mutex -{ - spin_recursive_mutex(const spin_recursive_mutex &); - spin_recursive_mutex &operator=(const spin_recursive_mutex &); - public: - - spin_recursive_mutex(); - ~spin_recursive_mutex(); - - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - void unlock(); - void take_ownership(); - private: - spin_mutex m_mutex; - unsigned int m_nLockCount; - volatile ipcdetail::OS_systemwide_thread_id_t m_nOwner; - volatile boost::uint32_t m_s; -}; - -inline spin_recursive_mutex::spin_recursive_mutex() - : m_nLockCount(0), m_nOwner(ipcdetail::get_invalid_systemwide_thread_id()){} - -inline spin_recursive_mutex::~spin_recursive_mutex(){} - -inline void spin_recursive_mutex::lock() -{ - typedef ipcdetail::OS_systemwide_thread_id_t handle_t; - const handle_t thr_id(ipcdetail::get_current_systemwide_thread_id()); - handle_t old_id; - ipcdetail::systemwide_thread_id_copy(m_nOwner, old_id); - if(ipcdetail::equal_systemwide_thread_id(thr_id , old_id)){ - if((unsigned int)(m_nLockCount+1) == 0){ - //Overflow, throw an exception - throw interprocess_exception("boost::interprocess::spin_recursive_mutex recursive lock overflow"); - } - ++m_nLockCount; - } - else{ - m_mutex.lock(); - ipcdetail::systemwide_thread_id_copy(thr_id, m_nOwner); - m_nLockCount = 1; - } -} - -inline bool spin_recursive_mutex::try_lock() -{ - typedef ipcdetail::OS_systemwide_thread_id_t handle_t; - handle_t thr_id(ipcdetail::get_current_systemwide_thread_id()); - handle_t old_id; - ipcdetail::systemwide_thread_id_copy(m_nOwner, old_id); - if(ipcdetail::equal_systemwide_thread_id(thr_id , old_id)) { // we own it - if((unsigned int)(m_nLockCount+1) == 0){ - //Overflow, throw an exception - throw interprocess_exception("boost::interprocess::spin_recursive_mutex recursive lock overflow"); - } - ++m_nLockCount; - return true; - } - if(m_mutex.try_lock()){ - ipcdetail::systemwide_thread_id_copy(thr_id, m_nOwner); - m_nLockCount = 1; - return true; - } - return false; -} - -inline bool spin_recursive_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - typedef ipcdetail::OS_systemwide_thread_id_t handle_t; - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - const handle_t thr_id(ipcdetail::get_current_systemwide_thread_id()); - handle_t old_id; - ipcdetail::systemwide_thread_id_copy(m_nOwner, old_id); - if(ipcdetail::equal_systemwide_thread_id(thr_id , old_id)) { // we own it - if((unsigned int)(m_nLockCount+1) == 0){ - //Overflow, throw an exception - throw interprocess_exception("boost::interprocess::spin_recursive_mutex recursive lock overflow"); - } - ++m_nLockCount; - return true; - } - if(m_mutex.timed_lock(abs_time)){ - ipcdetail::systemwide_thread_id_copy(thr_id, m_nOwner); - m_nLockCount = 1; - return true; - } - return false; -} - -inline void spin_recursive_mutex::unlock() -{ - typedef ipcdetail::OS_systemwide_thread_id_t handle_t; - handle_t old_id; - ipcdetail::systemwide_thread_id_copy(m_nOwner, old_id); - const handle_t thr_id(ipcdetail::get_current_systemwide_thread_id()); - (void)old_id; - (void)thr_id; - BOOST_ASSERT(ipcdetail::equal_systemwide_thread_id(thr_id, old_id)); - --m_nLockCount; - if(!m_nLockCount){ - const handle_t new_id(ipcdetail::get_invalid_systemwide_thread_id()); - ipcdetail::systemwide_thread_id_copy(new_id, m_nOwner); - m_mutex.unlock(); - } -} - -inline void spin_recursive_mutex::take_ownership() -{ - typedef ipcdetail::OS_systemwide_thread_id_t handle_t; - this->m_nLockCount = 1; - const handle_t thr_id(ipcdetail::get_current_systemwide_thread_id()); - ipcdetail::systemwide_thread_id_copy(thr_id, m_nOwner); -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_SPIN_RECURSIVE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/spin/semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/spin/semaphore.hpp deleted file mode 100644 index 4b162354..00000000 --- a/utils/boost_idb/boost/interprocess/sync/spin/semaphore.hpp +++ /dev/null @@ -1,111 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_SPIN_SEMAPHORE_HPP -#define BOOST_INTERPROCESS_DETAIL_SPIN_SEMAPHORE_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class spin_semaphore -{ - spin_semaphore(const spin_semaphore &); - spin_semaphore &operator=(const spin_semaphore &); - - public: - spin_semaphore(unsigned int initialCount); - ~spin_semaphore(); - - void post(); - void wait(); - bool try_wait(); - bool timed_wait(const boost::posix_time::ptime &abs_time); - -// int get_count() const; - private: - volatile boost::uint32_t m_count; -}; - - -inline spin_semaphore::~spin_semaphore() -{} - -inline spin_semaphore::spin_semaphore(unsigned int initialCount) -{ ipcdetail::atomic_write32(&this->m_count, boost::uint32_t(initialCount)); } - -inline void spin_semaphore::post() -{ - ipcdetail::atomic_inc32(&m_count); -} - -inline void spin_semaphore::wait() -{ - spin_wait swait; - while(!ipcdetail::atomic_add_unless32(&m_count, boost::uint32_t(-1), boost::uint32_t(0))){ - swait.yield(); - } -} - -inline bool spin_semaphore::try_wait() -{ - return ipcdetail::atomic_add_unless32(&m_count, boost::uint32_t(-1), boost::uint32_t(0)); -} - -inline bool spin_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) -{ - if(abs_time == boost::posix_time::pos_infin){ - this->wait(); - return true; - } - //Obtain current count and target time - boost::posix_time::ptime now(microsec_clock::universal_time()); - - spin_wait swait; - do{ - if(this->try_wait()){ - break; - } - now = microsec_clock::universal_time(); - - if(now >= abs_time){ - return this->try_wait(); - } - // relinquish current time slice - swait.yield(); - }while (true); - return true; -} - - -//inline int spin_semaphore::get_count() const -//{ - //return (int)ipcdetail::atomic_read32(&m_count); -//} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_SPIN_SEMAPHORE_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/spin/wait.hpp b/utils/boost_idb/boost/interprocess/sync/spin/wait.hpp deleted file mode 100644 index 0707bd8d..00000000 --- a/utils/boost_idb/boost/interprocess/sync/spin/wait.hpp +++ /dev/null @@ -1,181 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Peter Dimov 2008. -// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -//Parts of this file come from boost/smart_ptr/detail/yield_k.hpp -//Many thanks to Peter Dimov. - -#ifndef BOOST_INTERPROCESS_SYNC_WAIT_HPP_INCLUDED -#define BOOST_INTERPROCESS_SYNC_WAIT_HPP_INCLUDED - -#if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once -#endif - -#include -#include -#include - -//#define BOOST_INTERPROCESS_SPIN_WAIT_DEBUG -#ifdef BOOST_INTERPROCESS_SPIN_WAIT_DEBUG -#include -#endif - -// BOOST_INTERPROCESS_SMT_PAUSE - -#if defined(_MSC_VER) && _MSC_VER >= 1310 && ( defined(_M_IX86) || defined(_M_X64) ) - -extern "C" void _mm_pause(); -#pragma intrinsic( _mm_pause ) - -#define BOOST_INTERPROCESS_SMT_PAUSE _mm_pause(); - -#elif defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) ) - -#define BOOST_INTERPROCESS_SMT_PAUSE __asm__ __volatile__( "rep; nop" : : : "memory" ); - -#endif - -namespace boost{ -namespace interprocess{ -namespace ipcdetail { - -template -class num_core_holder -{ - public: - static unsigned int get() - { - if(!num_cores){ - return ipcdetail::get_num_cores(); - } - else{ - return num_cores; - } - } - - private: - static unsigned int num_cores; -}; - -template -unsigned int num_core_holder::num_cores = ipcdetail::get_num_cores(); - -} //namespace ipcdetail { - -class spin_wait -{ - public: - - static const unsigned int nop_pause_limit = 32u; - spin_wait() - : m_count_start(), m_ul_yield_only_counts(), m_k() - {} - - #ifdef BOOST_INTERPROCESS_SPIN_WAIT_DEBUG - ~spin_wait() - { - if(m_k){ - std::cout << "final m_k: " << m_k - << " system tick(us): " << ipcdetail::get_system_tick_us() << std::endl; - } - } - #endif - - unsigned int count() const - { return m_k; } - - void yield() - { - //Lazy initialization of limits - if( !m_k){ - this->init_limits(); - } - //Nop tries - if( m_k < (nop_pause_limit >> 2) ){ - - } - //Pause tries if the processor supports it - #if defined(BOOST_INTERPROCESS_SMT_PAUSE) - else if( m_k < nop_pause_limit ){ - BOOST_INTERPROCESS_SMT_PAUSE - } - #endif - //Yield/Sleep strategy - else{ - //Lazy initialization of tick information - if(m_k == nop_pause_limit){ - this->init_tick_info(); - } - else if( this->yield_or_sleep() ){ - ipcdetail::thread_yield(); - } - else{ - ipcdetail::thread_sleep_tick(); - } - } - ++m_k; - } - - void reset() - { - m_k = 0u; - } - - private: - - void init_limits() - { - unsigned int num_cores = ipcdetail::num_core_holder<0>::get(); - m_k = num_cores > 1u ? 0u : nop_pause_limit; - } - - void init_tick_info() - { - m_ul_yield_only_counts = ipcdetail::get_system_tick_in_highres_counts(); - m_count_start = ipcdetail::get_current_system_highres_count(); - } - - //Returns true if yield must be called, false is sleep must be called - bool yield_or_sleep() - { - if(!m_ul_yield_only_counts){ //If yield-only limit was reached then yield one in every two tries - return (m_k & 1u) != 0; - } - else{ //Try to see if we've reched yield-only time limit - const ipcdetail::OS_highres_count_t now = ipcdetail::get_current_system_highres_count(); - const ipcdetail::OS_highres_count_t elapsed = ipcdetail::system_highres_count_subtract(now, m_count_start); - if(!ipcdetail::system_highres_count_less_ul(elapsed, m_ul_yield_only_counts)){ - #ifdef BOOST_INTERPROCESS_SPIN_WAIT_DEBUG - std::cout << "elapsed!\n" - << " m_ul_yield_only_counts: " << m_ul_yield_only_counts - << " system tick(us): " << ipcdetail::get_system_tick_us() << '\n' - << " m_k: " << m_k << " elapsed counts: "; - ipcdetail::ostream_highres_count(std::cout, elapsed) << std::endl; - #endif - //Yield-only time reached, now it's time to sleep - m_ul_yield_only_counts = 0ul; - return false; - } - } - return true; //Otherwise yield - } - - ipcdetail::OS_highres_count_t m_count_start; - unsigned long m_ul_yield_only_counts; - unsigned int m_k; -}; - -} // namespace interprocess -} // namespace boost - -#include - -#endif // #ifndef BOOST_INTERPROCESS_SYNC_WAIT_HPP_INCLUDED diff --git a/utils/boost_idb/boost/interprocess/sync/upgradable_lock.hpp b/utils/boost_idb/boost/interprocess/sync/upgradable_lock.hpp index 6b766fd6..3d0355c8 100644 --- a/utils/boost_idb/boost/interprocess/sync/upgradable_lock.hpp +++ b/utils/boost_idb/boost/interprocess/sync/upgradable_lock.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -28,7 +28,7 @@ #include #include -#include +#include #include //!\file @@ -57,7 +57,7 @@ class upgradable_lock typedef upgradable_lock this_type; explicit upgradable_lock(scoped_lock&); typedef bool this_type::*unspecified_bool_type; - BOOST_MOVABLE_BUT_NOT_COPYABLE(upgradable_lock) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(upgradable_lock) /// @endcond public: @@ -85,7 +85,7 @@ class upgradable_lock : mp_mutex(&m), m_locked(true) {} - //!Effects: m.try_lock_upgradable(). + //!Effects: m.try_lock_upgradable(). //!Postconditions: mutex() == &m. owns() == the return value of the //! m.try_lock_upgradable() executed within the constructor. //!Notes: The constructor will take upgradable-ownership of the mutex @@ -97,7 +97,7 @@ class upgradable_lock : mp_mutex(&m), m_locked(false) { m_locked = mp_mutex->try_lock_upgradable(); } - //!Effects: m.timed_lock_upgradable(abs_time) + //!Effects: m.timed_lock_upgradable(abs_time) //!Postconditions: mutex() == &m. owns() == the return value of the //! m.timed_lock_upgradable() executed within the constructor. //!Notes: The constructor will take upgradable-ownership of the mutex if it @@ -117,13 +117,13 @@ class upgradable_lock //! while unlocking upgr. If upgr is unlocked, then this upgradable_lock will //! be unlocked as well. Only a moved upgradable_lock's will match this //! signature. An non-moved upgradable_lock can be moved with the - //! expression: "boost::move(lock);". This constructor does not alter the + //! expression: "boost::interprocess::move(lock);". This constructor does not alter the //! state of the mutex, only potentially who owns it. - upgradable_lock(BOOST_RV_REF(upgradable_lock) upgr) + upgradable_lock(BOOST_INTERPROCESS_RV_REF(upgradable_lock) upgr) : mp_mutex(0), m_locked(upgr.owns()) { mp_mutex = upgr.release(); } - //!Effects: If scop.owns(), m_.unlock_and_lock_upgradable(). + //!Effects: If scop.owns(), m_.unlock_and_lock_upgradable(). //!Postconditions: mutex() == the value scop.mutex() had before the construction. //! scop.mutex() == 0. owns() == scop.owns() before the constructor. After the //! construction, scop.owns() == false. @@ -131,10 +131,10 @@ class upgradable_lock //! to an upgradable-ownership of this upgradable_lock. //! Only a moved sharable_lock's will match this //! signature. An non-moved sharable_lock can be moved with the - //! expression: "boost::move(lock);". + //! expression: "boost::interprocess::move(lock);". template - upgradable_lock(BOOST_RV_REF(scoped_lock) scop - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + upgradable_lock(BOOST_INTERPROCESS_RV_REF(scoped_lock) scop + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { scoped_lock &u_lock = scop; @@ -146,12 +146,12 @@ class upgradable_lock } //!Effects: If shar.owns() then calls try_unlock_sharable_and_lock_upgradable() - //! on the referenced mutex. + //! on the referenced mutex. //! a)if try_unlock_sharable_and_lock_upgradable() returns true then mutex() - //! obtains the value from shar.release() and owns() is set to true. + //! obtains the value from shar.release() and owns() is set to true. //! b)if try_unlock_sharable_and_lock_upgradable() returns false then shar is //! unaffected and this upgradable_lock construction has the same - //! effects as a default construction. + //! effects as a default construction. //! c)Else shar.owns() is false. mutex() obtains the value from shar.release() //! and owns() is set to false. //!Notes: This construction will not block. It will try to obtain mutex @@ -161,8 +161,8 @@ class upgradable_lock //! "upgradable lock". If the "read lock" is held, then mutex transfer //! occurs only if it can do so in a non-blocking manner. template - upgradable_lock( BOOST_RV_REF(sharable_lock) shar, try_to_lock_type - , typename ipcdetail::enable_if< ipcdetail::is_same >::type * = 0) + upgradable_lock( BOOST_INTERPROCESS_RV_REF(sharable_lock) shar, try_to_lock_type + , typename detail::enable_if< detail::is_same >::type * = 0) : mp_mutex(0), m_locked(false) { sharable_lock &s_lock = shar; @@ -192,7 +192,7 @@ class upgradable_lock //! mutex before the assignment. In this case, this will own the mutex //! after the assignment (and upgr will not), but the mutex's upgradable lock //! count will be decremented by one. - upgradable_lock &operator=(BOOST_RV_REF(upgradable_lock) upgr) + upgradable_lock &operator=(BOOST_INTERPROCESS_RV_REF(upgradable_lock) upgr) { if(this->owns()) this->unlock(); @@ -207,7 +207,7 @@ class upgradable_lock //!Notes: The sharable_lock changes from a state of not owning the mutex, //! to owning the mutex, blocking if necessary. void lock() - { + { if(!mp_mutex || m_locked) throw lock_exception(); mp_mutex->lock_upgradable(); @@ -223,7 +223,7 @@ class upgradable_lock //! mutex_type does not support try_lock_upgradable(), this function will //! fail at compile time if instantiated, but otherwise have no effect. bool try_lock() - { + { if(!mp_mutex || m_locked) throw lock_exception(); m_locked = mp_mutex->try_lock_upgradable(); @@ -240,7 +240,7 @@ class upgradable_lock //! timed_lock_upgradable(abs_time), this function will fail at compile //! time if instantiated, but otherwise have no effect. bool timed_lock(const boost::posix_time::ptime& abs_time) - { + { if(!mp_mutex || m_locked) throw lock_exception(); m_locked = mp_mutex->timed_lock_upgradable(abs_time); @@ -286,7 +286,7 @@ class upgradable_lock return mut; } - //!Effects: Swaps state with moved lock. + //!Effects: Swaps state with moved lock. //!Throws: Nothing. void swap(upgradable_lock &other) { diff --git a/utils/boost_idb/boost/interprocess/sync/windows/condition.hpp b/utils/boost_idb/boost/interprocess/sync/windows/condition.hpp deleted file mode 100644 index 62779517..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/condition.hpp +++ /dev/null @@ -1,117 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_WINDOWS_CONDITION_HPP -#define BOOST_INTERPROCESS_DETAIL_WINDOWS_CONDITION_HPP - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class windows_condition -{ - windows_condition(const windows_condition &); - windows_condition &operator=(const windows_condition &); - - public: - windows_condition() - : m_condition_data() - {} - - ~windows_condition() - {} - - void notify_one() - { m_condition_data.notify_one(); } - - void notify_all() - { m_condition_data.notify_all(); } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { return m_condition_data.timed_wait(lock, abs_time); } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { return m_condition_data.timed_wait(lock, abs_time, pred); } - - template - void wait(L& lock) - { m_condition_data.wait(lock); } - - template - void wait(L& lock, Pr pred) - { m_condition_data.wait(lock, pred); } - - private: - - struct condition_data - { - typedef boost::int32_t integer_type; - typedef windows_semaphore semaphore_type; - typedef windows_mutex mutex_type; - - condition_data() - : m_nwaiters_blocked(0) - , m_nwaiters_gone(0) - , m_nwaiters_to_unblock(0) - , m_sem_block_queue(0) - , m_sem_block_lock(1) - , m_mtx_unblock_lock() - {} - - integer_type &get_nwaiters_blocked() - { return m_nwaiters_blocked; } - - integer_type &get_nwaiters_gone() - { return m_nwaiters_gone; } - - integer_type &get_nwaiters_to_unblock() - { return m_nwaiters_to_unblock; } - - semaphore_type &get_sem_block_queue() - { return m_sem_block_queue; } - - semaphore_type &get_sem_block_lock() - { return m_sem_block_lock; } - - mutex_type &get_mtx_unblock_lock() - { return m_mtx_unblock_lock; } - - boost::int32_t m_nwaiters_blocked; - boost::int32_t m_nwaiters_gone; - boost::int32_t m_nwaiters_to_unblock; - windows_semaphore m_sem_block_queue; - windows_semaphore m_sem_block_lock; - windows_mutex m_mtx_unblock_lock; - }; - - ipcdetail::condition_8a_wrapper m_condition_data; -}; - -} //namespace ipcdetail -} //namespace interprocess -} //namespace boost - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_WINDOWS_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/mutex.hpp b/utils/boost_idb/boost/interprocess/sync/windows/mutex.hpp deleted file mode 100644 index c8a64b3b..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/mutex.hpp +++ /dev/null @@ -1,114 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_WINDOWS_MUTEX_HPP -#define BOOST_INTERPROCESS_DETAIL_WINDOWS_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class windows_mutex -{ - windows_mutex(const windows_mutex &); - windows_mutex &operator=(const windows_mutex &); - public: - - windows_mutex(); - ~windows_mutex(); - - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - void unlock(); - void take_ownership(){}; - - private: - const sync_id id_; -}; - -inline windows_mutex::windows_mutex() - : id_(this) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //Create mutex with the initial count - bool open_or_created; - (void)handles.obtain_mutex(this->id_, &open_or_created); - //The mutex must be created, never opened - BOOST_ASSERT(open_or_created); - BOOST_ASSERT(open_or_created && winapi::get_last_error() != winapi::error_already_exists); - (void)open_or_created; -} - -inline windows_mutex::~windows_mutex() -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - handles.destroy_handle(this->id_); -} - -inline void windows_mutex::lock(void) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_mutex_functions mut(handles.obtain_mutex(this->id_)); - mut.lock(); -} - -inline bool windows_mutex::try_lock(void) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_mutex_functions mut(handles.obtain_mutex(this->id_)); - return mut.try_lock(); -} - -inline bool windows_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_mutex_functions mut(handles.obtain_mutex(this->id_)); - return mut.timed_lock(abs_time); -} - -inline void windows_mutex::unlock(void) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_mutex_functions mut(handles.obtain_mutex(this->id_)); - return mut.unlock(); -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_WINDOWS_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/named_condition.hpp b/utils/boost_idb/boost/interprocess/sync/windows/named_condition.hpp deleted file mode 100644 index 47244823..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/named_condition.hpp +++ /dev/null @@ -1,34 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_HPP -#define BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -typedef windows_named_condition_any windows_named_condition; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/named_condition_any.hpp b/utils/boost_idb/boost/interprocess/sync/windows/named_condition_any.hpp deleted file mode 100644 index 0d3b915b..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/named_condition_any.hpp +++ /dev/null @@ -1,241 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_ANY_HPP -#define BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_ANY_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class windows_named_condition_any -{ - /// @cond - - //Non-copyable - windows_named_condition_any(); - windows_named_condition_any(const windows_named_condition_any &); - windows_named_condition_any &operator=(const windows_named_condition_any &); - /// @endcond - - public: - windows_named_condition_any - (create_only_t, const char *name, const permissions &perm) - : m_condition_data() - { - named_cond_callbacks callbacks(m_condition_data.get_members()); - m_named_sync.open_or_create(DoCreate, name, perm, callbacks); - } - - windows_named_condition_any - (open_or_create_t, const char *name, const permissions &perm) - : m_condition_data() - { - named_cond_callbacks callbacks(m_condition_data.get_members()); - m_named_sync.open_or_create(DoOpenOrCreate, name, perm, callbacks); - } - - windows_named_condition_any(open_only_t, const char *name) - : m_condition_data() - { - named_cond_callbacks callbacks(m_condition_data.get_members()); - m_named_sync.open_or_create(DoOpen, name, permissions(), callbacks); - } - - ~windows_named_condition_any() - { - named_cond_callbacks callbacks(m_condition_data.get_members()); - m_named_sync.close(callbacks); - } - - void notify_one() - { m_condition_data.notify_one(); } - - void notify_all() - { m_condition_data.notify_all(); } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) - { return m_condition_data.timed_wait(lock, abs_time); } - - template - bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) - { return m_condition_data.timed_wait(lock, abs_time, pred); } - - template - void wait(L& lock) - { m_condition_data.wait(lock); } - - template - void wait(L& lock, Pr pred) - { m_condition_data.wait(lock, pred); } - - static bool remove(const char *name) - { return windows_named_sync::remove(name); } - - /// @cond - private: - - void windows_named_condition_any::dont_close_on_destruction() - {} - - friend class interprocess_tester; - - struct condition_data - { - typedef boost::int32_t integer_type; - typedef winapi_semaphore_wrapper semaphore_type; - typedef winapi_mutex_wrapper mutex_type; - - integer_type &get_nwaiters_blocked() - { return m_nwaiters_blocked; } - - integer_type &get_nwaiters_gone() - { return m_nwaiters_gone; } - - integer_type &get_nwaiters_to_unblock() - { return m_nwaiters_to_unblock; } - - semaphore_type &get_sem_block_queue() - { return m_sem_block_queue; } - - semaphore_type &get_sem_block_lock() - { return m_sem_block_lock; } - - mutex_type &get_mtx_unblock_lock() - { return m_mtx_unblock_lock; } - - integer_type m_nwaiters_blocked; - integer_type m_nwaiters_gone; - integer_type m_nwaiters_to_unblock; - winapi_semaphore_wrapper m_sem_block_queue; - winapi_semaphore_wrapper m_sem_block_lock; - winapi_mutex_wrapper m_mtx_unblock_lock; - }; - - ipcdetail::condition_8a_wrapper m_condition_data; - - class named_cond_callbacks : public windows_named_sync_interface - { - typedef __int64 sem_count_t; - mutable sem_count_t sem_counts [2]; - - public: - named_cond_callbacks(condition_data &cond_data) - : m_condition_data(cond_data) - {} - - virtual std::size_t get_data_size() const - { return sizeof(sem_counts); } - - virtual const void *buffer_with_final_data_to_file() - { - sem_counts[0] = m_condition_data.m_sem_block_queue.value(); - sem_counts[1] = m_condition_data.m_sem_block_lock.value(); - return &sem_counts; - } - - virtual const void *buffer_with_init_data_to_file() - { - sem_counts[0] = 0; - sem_counts[1] = 1; - return &sem_counts; - } - - virtual void *buffer_to_store_init_data_from_file() - { return &sem_counts; } - - virtual bool open(create_enum_t, const char *id_name) - { - m_condition_data.m_nwaiters_blocked = 0; - m_condition_data.m_nwaiters_gone = 0; - m_condition_data.m_nwaiters_to_unblock = 0; - - //Now open semaphores and mutex. - //Use local variables + swap to guarantee consistent - //initialization and cleanup in case any opening fails - permissions perm; - perm.set_unrestricted(); - std::string aux_str = "Global\\bipc.cond."; - aux_str += id_name; - std::size_t pos = aux_str.size(); - - //sem_block_queue - aux_str += "_bq"; - winapi_semaphore_wrapper sem_block_queue; - bool created; - if(!sem_block_queue.open_or_create - (aux_str.c_str(), sem_counts[0], winapi_semaphore_wrapper::MaxCount, perm, created)) - return false; - aux_str.erase(pos); - - //sem_block_lock - aux_str += "_bl"; - winapi_semaphore_wrapper sem_block_lock; - if(!sem_block_lock.open_or_create - (aux_str.c_str(), sem_counts[1], winapi_semaphore_wrapper::MaxCount, perm, created)) - return false; - aux_str.erase(pos); - - //mtx_unblock_lock - aux_str += "_ul"; - winapi_mutex_wrapper mtx_unblock_lock; - if(!mtx_unblock_lock.open_or_create(aux_str.c_str(), perm)) - return false; - - //All ok, commit data - m_condition_data.m_sem_block_queue.swap(sem_block_queue); - m_condition_data.m_sem_block_lock.swap(sem_block_lock); - m_condition_data.m_mtx_unblock_lock.swap(mtx_unblock_lock); - return true; - } - - virtual void close() - { - m_condition_data.m_sem_block_queue.close(); - m_condition_data.m_sem_block_lock.close(); - m_condition_data.m_mtx_unblock_lock.close(); - m_condition_data.m_nwaiters_blocked = 0; - m_condition_data.m_nwaiters_gone = 0; - m_condition_data.m_nwaiters_to_unblock = 0; - } - - virtual ~named_cond_callbacks() - {} - - private: - condition_data &m_condition_data; - }; - - windows_named_sync m_named_sync; - /// @endcond -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_WINDOWS_NAMED_CONDITION_ANY_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/named_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/windows/named_mutex.hpp deleted file mode 100644 index 8ea6b3e1..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/named_mutex.hpp +++ /dev/null @@ -1,175 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTERPROCESS_WINDOWS_NAMED_MUTEX_HPP -#define BOOST_INTERPROCESS_WINDOWS_NAMED_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - - - -class windows_named_mutex -{ - /// @cond - - //Non-copyable - windows_named_mutex(); - windows_named_mutex(const windows_named_mutex &); - windows_named_mutex &operator=(const windows_named_mutex &); - /// @endcond - - public: - windows_named_mutex(create_only_t, const char *name, const permissions &perm = permissions()); - - windows_named_mutex(open_or_create_t, const char *name, const permissions &perm = permissions()); - - windows_named_mutex(open_only_t, const char *name); - - ~windows_named_mutex(); - - void unlock(); - void lock(); - bool try_lock(); - bool timed_lock(const boost::posix_time::ptime &abs_time); - - static bool remove(const char *name); - - /// @cond - private: - friend class interprocess_tester; - void dont_close_on_destruction(); - winapi_mutex_wrapper m_mtx_wrapper; - windows_named_sync m_named_sync; - - class named_mut_callbacks : public windows_named_sync_interface - { - public: - named_mut_callbacks(winapi_mutex_wrapper &mtx_wrapper) - : m_mtx_wrapper(mtx_wrapper) - {} - - virtual std::size_t get_data_size() const - { return 0u; } - - virtual const void *buffer_with_init_data_to_file() - { return 0; } - - virtual const void *buffer_with_final_data_to_file() - { return 0; } - - virtual void *buffer_to_store_init_data_from_file() - { return 0; } - - virtual bool open(create_enum_t, const char *id_name) - { - std::string aux_str = "Global\\bipc.mut."; - aux_str += id_name; - // - permissions mut_perm; - mut_perm.set_unrestricted(); - return m_mtx_wrapper.open_or_create(aux_str.c_str(), mut_perm); - } - - virtual void close() - { - m_mtx_wrapper.close(); - } - - virtual ~named_mut_callbacks() - {} - - private: - winapi_mutex_wrapper& m_mtx_wrapper; - }; - /// @endcond -}; - -inline windows_named_mutex::~windows_named_mutex() -{ - named_mut_callbacks callbacks(m_mtx_wrapper); - m_named_sync.close(callbacks); -} - -inline void windows_named_mutex::dont_close_on_destruction() -{} - -inline windows_named_mutex::windows_named_mutex - (create_only_t, const char *name, const permissions &perm) - : m_mtx_wrapper() -{ - named_mut_callbacks callbacks(m_mtx_wrapper); - m_named_sync.open_or_create(DoCreate, name, perm, callbacks); -} - -inline windows_named_mutex::windows_named_mutex - (open_or_create_t, const char *name, const permissions &perm) - : m_mtx_wrapper() -{ - named_mut_callbacks callbacks(m_mtx_wrapper); - m_named_sync.open_or_create(DoOpenOrCreate, name, perm, callbacks); -} - -inline windows_named_mutex::windows_named_mutex(open_only_t, const char *name) - : m_mtx_wrapper() -{ - named_mut_callbacks callbacks(m_mtx_wrapper); - m_named_sync.open_or_create(DoOpen, name, permissions(), callbacks); -} - -inline void windows_named_mutex::unlock() -{ - m_mtx_wrapper.unlock(); -} - -inline void windows_named_mutex::lock() -{ - m_mtx_wrapper.lock(); -} - -inline bool windows_named_mutex::try_lock() -{ - return m_mtx_wrapper.try_lock(); -} - -inline bool windows_named_mutex::timed_lock(const boost::posix_time::ptime &abs_time) -{ - return m_mtx_wrapper.timed_lock(abs_time); -} - -inline bool windows_named_mutex::remove(const char *name) -{ - return windows_named_sync::remove(name); -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_WINDOWS_NAMED_MUTEX_HPP \ No newline at end of file diff --git a/utils/boost_idb/boost/interprocess/sync/windows/named_recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/windows/named_recursive_mutex.hpp deleted file mode 100644 index cb2ef79a..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/named_recursive_mutex.hpp +++ /dev/null @@ -1,58 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP -#define BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - - -class windows_named_recursive_mutex - //Windows mutexes based on CreateMutex are already recursive... - : public windows_named_mutex -{ - /// @cond - - //Non-copyable - windows_named_recursive_mutex(); - windows_named_recursive_mutex(const windows_named_mutex &); - windows_named_recursive_mutex &operator=(const windows_named_mutex &); - /// @endcond - - public: - windows_named_recursive_mutex(create_only_t, const char *name, const permissions &perm = permissions()) - : windows_named_mutex(create_only_t(), name, perm) - {} - - windows_named_recursive_mutex(open_or_create_t, const char *name, const permissions &perm = permissions()) - : windows_named_mutex(open_or_create_t(), name, perm) - {} - - windows_named_recursive_mutex(open_only_t, const char *name) - : windows_named_mutex(open_only_t(), name) - {} -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/named_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/windows/named_semaphore.hpp deleted file mode 100644 index 8f48d4df..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/named_semaphore.hpp +++ /dev/null @@ -1,178 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_WINDOWS_NAMED_SEMAPHORE_HPP -#define BOOST_INTERPROCESS_WINDOWS_NAMED_SEMAPHORE_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - - - -class windows_named_semaphore -{ - /// @cond - - //Non-copyable - windows_named_semaphore(); - windows_named_semaphore(const windows_named_semaphore &); - windows_named_semaphore &operator=(const windows_named_semaphore &); - /// @endcond - - public: - windows_named_semaphore(create_only_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()); - - windows_named_semaphore(open_or_create_t, const char *name, unsigned int initialCount, const permissions &perm = permissions()); - - windows_named_semaphore(open_only_t, const char *name); - - ~windows_named_semaphore(); - - void post(); - void wait(); - bool try_wait(); - bool timed_wait(const boost::posix_time::ptime &abs_time); - - static bool remove(const char *name); - - /// @cond - private: - friend class interprocess_tester; - void dont_close_on_destruction(); - winapi_semaphore_wrapper m_sem_wrapper; - windows_named_sync m_named_sync; - - class named_sem_callbacks : public windows_named_sync_interface - { - public: - typedef __int64 sem_count_t; - named_sem_callbacks(winapi_semaphore_wrapper &sem_wrapper, sem_count_t sem_cnt) - : m_sem_wrapper(sem_wrapper), m_sem_count(sem_cnt) - {} - - virtual std::size_t get_data_size() const - { return sizeof(sem_count_t); } - - virtual const void *buffer_with_final_data_to_file() - { return &m_sem_count; } - - virtual const void *buffer_with_init_data_to_file() - { return &m_sem_count; } - - virtual void *buffer_to_store_init_data_from_file() - { return &m_sem_count; } - - virtual bool open(create_enum_t, const char *id_name) - { - std::string aux_str = "Global\\bipc.sem."; - aux_str += id_name; - // - permissions sem_perm; - sem_perm.set_unrestricted(); - bool created; - return m_sem_wrapper.open_or_create - ( aux_str.c_str(), static_cast(m_sem_count) - , winapi_semaphore_wrapper::MaxCount, sem_perm, created); - } - - virtual void close() - { - m_sem_wrapper.close(); - } - - virtual ~named_sem_callbacks() - {} - - private: - sem_count_t m_sem_count; - winapi_semaphore_wrapper& m_sem_wrapper; - }; - - /// @endcond -}; - -inline windows_named_semaphore::~windows_named_semaphore() -{ - named_sem_callbacks callbacks(m_sem_wrapper, m_sem_wrapper.value()); - m_named_sync.close(callbacks); -} - -inline void windows_named_semaphore::dont_close_on_destruction() -{} - -inline windows_named_semaphore::windows_named_semaphore - (create_only_t, const char *name, unsigned int initial_count, const permissions &perm) - : m_sem_wrapper() -{ - named_sem_callbacks callbacks(m_sem_wrapper, initial_count); - m_named_sync.open_or_create(DoCreate, name, perm, callbacks); -} - -inline windows_named_semaphore::windows_named_semaphore - (open_or_create_t, const char *name, unsigned int initial_count, const permissions &perm) - : m_sem_wrapper() -{ - named_sem_callbacks callbacks(m_sem_wrapper, initial_count); - m_named_sync.open_or_create(DoOpenOrCreate, name, perm, callbacks); -} - -inline windows_named_semaphore::windows_named_semaphore(open_only_t, const char *name) - : m_sem_wrapper() -{ - named_sem_callbacks callbacks(m_sem_wrapper, 0); - m_named_sync.open_or_create(DoOpen, name, permissions(), callbacks); -} - -inline void windows_named_semaphore::post() -{ - m_sem_wrapper.post(); -} - -inline void windows_named_semaphore::wait() -{ - m_sem_wrapper.wait(); -} - -inline bool windows_named_semaphore::try_wait() -{ - return m_sem_wrapper.try_wait(); -} - -inline bool windows_named_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) -{ - return m_sem_wrapper.timed_wait(abs_time); -} - -inline bool windows_named_semaphore::remove(const char *name) -{ - return windows_named_sync::remove(name); -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_WINDOWS_NAMED_SEMAPHORE_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/named_sync.hpp b/utils/boost_idb/boost/interprocess/sync/windows/named_sync.hpp deleted file mode 100644 index 298c2e2e..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/named_sync.hpp +++ /dev/null @@ -1,215 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_WINDOWS_NAMED_SYNC_HPP -#define BOOST_INTERPROCESS_WINDOWS_NAMED_SYNC_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class windows_named_sync_interface -{ - public: - virtual std::size_t get_data_size() const = 0; - virtual const void *buffer_with_final_data_to_file() = 0; - virtual const void *buffer_with_init_data_to_file() = 0; - virtual void *buffer_to_store_init_data_from_file() = 0; - virtual bool open(create_enum_t creation_type, const char *id_name) = 0; - virtual void close() = 0; - virtual ~windows_named_sync_interface() = 0; -}; - -inline windows_named_sync_interface::~windows_named_sync_interface() -{} - -class windows_named_sync -{ - /// @cond - - //Non-copyable - windows_named_sync(const windows_named_sync &); - windows_named_sync &operator=(const windows_named_sync &); - /// @endcond - - public: - windows_named_sync(); - void open_or_create(create_enum_t creation_type, const char *name, const permissions &perm, windows_named_sync_interface &sync_interface); - void close(windows_named_sync_interface &sync_interface); - - static bool remove(const char *name); - - /// @cond - private: - void *m_file_hnd; - - /// @endcond -}; - -inline windows_named_sync::windows_named_sync() - : m_file_hnd(winapi::invalid_handle_value) -{} - -inline void windows_named_sync::close(windows_named_sync_interface &sync_interface) -{ - const std::size_t buflen = sync_interface.get_data_size(); - const std::size_t sizeof_file_info = sizeof(sync_id::internal_type) + buflen; - winapi::interprocess_overlapped overlapped; - if(winapi::lock_file_ex - (m_file_hnd, winapi::lockfile_exclusive_lock, 0, sizeof_file_info, 0, &overlapped)){ - if(winapi::set_file_pointer_ex(m_file_hnd, sizeof(sync_id::internal_type), 0, winapi::file_begin)){ - const void *buf = sync_interface.buffer_with_final_data_to_file(); - - unsigned long written_or_read = 0; - if(winapi::write_file(m_file_hnd, buf, buflen, &written_or_read, 0)){ - //... - } - } - } - sync_interface.close(); - if(m_file_hnd != winapi::invalid_handle_value){ - winapi::close_handle(m_file_hnd); - m_file_hnd = winapi::invalid_handle_value; - } -} - -inline void windows_named_sync::open_or_create - ( create_enum_t creation_type - , const char *name - , const permissions &perm - , windows_named_sync_interface &sync_interface) -{ - std::string aux_str(name); - m_file_hnd = winapi::invalid_handle_value; - //Use a file to emulate POSIX lifetime semantics. After this logic - //we'll obtain the ID of the native handle to open in aux_str - { - create_tmp_and_clean_old_and_get_filename(name, aux_str); - //Create a file with required permissions. - m_file_hnd = winapi::create_file - ( aux_str.c_str() - , winapi::generic_read | winapi::generic_write - , creation_type == DoOpen ? winapi::open_existing : - (creation_type == DoCreate ? winapi::create_new : winapi::open_always) - , 0 - , (winapi::interprocess_security_attributes*)perm.get_permissions()); - - //Obtain OS error in case something has failed - error_info err; - bool success = false; - if(m_file_hnd != winapi::invalid_handle_value){ - //Now lock the file - const std::size_t buflen = sync_interface.get_data_size(); - typedef __int64 unique_id_type; - const std::size_t sizeof_file_info = sizeof(unique_id_type) + buflen; - winapi::interprocess_overlapped overlapped; - if(winapi::lock_file_ex - (m_file_hnd, winapi::lockfile_exclusive_lock, 0, sizeof_file_info, 0, &overlapped)){ - __int64 filesize = 0; - //Obtain the unique id to open the native semaphore. - //If file size was created - if(winapi::get_file_size(m_file_hnd, filesize)){ - unsigned long written_or_read = 0; - unique_id_type unique_id_val; - if(static_cast(filesize) != sizeof_file_info){ - winapi::set_end_of_file(m_file_hnd); - winapi::query_performance_counter(&unique_id_val); - const void *buf = sync_interface.buffer_with_init_data_to_file(); - //Write unique ID in file. This ID will be used to calculate the semaphore name - if(winapi::write_file(m_file_hnd, &unique_id_val, sizeof(unique_id_val), &written_or_read, 0) && - written_or_read == sizeof(unique_id_val) && - winapi::write_file(m_file_hnd, buf, buflen, &written_or_read, 0) && - written_or_read == buflen ){ - success = true; - } - winapi::get_file_size(m_file_hnd, filesize); - BOOST_ASSERT(std::size_t(filesize) == sizeof_file_info); - } - else{ - void *buf = sync_interface.buffer_to_store_init_data_from_file(); - if(winapi::read_file(m_file_hnd, &unique_id_val, sizeof(unique_id_val), &written_or_read, 0) && - written_or_read == sizeof(unique_id_val) && - winapi::read_file(m_file_hnd, buf, buflen, &written_or_read, 0) && - written_or_read == buflen ){ - success = true; - } - } - if(success){ - //Now create a global semaphore name based on the unique id - char unique_id_name[sizeof(unique_id_val)*2+1]; - std::size_t name_suffix_length = sizeof(unique_id_name); - bytes_to_str(&unique_id_val, sizeof(unique_id_val), &unique_id_name[0], name_suffix_length); - success = sync_interface.open(creation_type, unique_id_name); - } - } - - //Obtain OS error in case something has failed - err = system_error_code(); - - //If this fails we have no possible rollback so don't check the return - if(!winapi::unlock_file_ex(m_file_hnd, 0, sizeof_file_info, 0, &overlapped)){ - err = system_error_code(); - } - } - else{ - //Obtain OS error in case something has failed - err = system_error_code(); - } - } - else{ - err = system_error_code(); - } - - if(!success){ - if(m_file_hnd != winapi::invalid_handle_value){ - winapi::close_handle(m_file_hnd); - m_file_hnd = winapi::invalid_handle_value; - } - //Throw as something went wrong - throw interprocess_exception(err); - } - } -} - -inline bool windows_named_sync::remove(const char *name) -{ - try{ - //Make sure a temporary path is created for shared memory - std::string semfile; - ipcdetail::tmp_filename(name, semfile); - return winapi::unlink_file(semfile.c_str()); - } - catch(...){ - return false; - } -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_WINDOWS_NAMED_SYNC_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/recursive_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/windows/recursive_mutex.hpp deleted file mode 100644 index 2b4797e1..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/recursive_mutex.hpp +++ /dev/null @@ -1,43 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_WINDOWS_RECURSIVE_MUTEX_HPP -#define BOOST_INTERPROCESS_DETAIL_WINDOWS_RECURSIVE_MUTEX_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -//Windows mutex is already recursive -class windows_recursive_mutex - : public windows_mutex -{ - windows_recursive_mutex(const windows_recursive_mutex &); - windows_recursive_mutex &operator=(const windows_recursive_mutex &); - public: - windows_recursive_mutex() : windows_mutex() {} -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_WINDOWS_RECURSIVE_MUTEX_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/windows/semaphore.hpp deleted file mode 100644 index a8166ce5..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/semaphore.hpp +++ /dev/null @@ -1,113 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_WINDOWS_SEMAPHORE_HPP -#define BOOST_INTERPROCESS_DETAIL_WINDOWS_SEMAPHORE_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class windows_semaphore -{ - windows_semaphore(const windows_semaphore &); - windows_semaphore &operator=(const windows_semaphore &); - public: - - windows_semaphore(unsigned int initialCount); - ~windows_semaphore(); - - void post(long release_count = 1); - void wait(); - bool try_wait(); - bool timed_wait(const boost::posix_time::ptime &abs_time); - - private: - const sync_id id_; -}; - -inline windows_semaphore::windows_semaphore(unsigned int initialCount) - : id_(this) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //Force smeaphore creation with the initial count - bool open_or_created; - handles.obtain_semaphore(this->id_, initialCount, &open_or_created); - //The semaphore must be created, never opened - BOOST_ASSERT(open_or_created); - BOOST_ASSERT(open_or_created && winapi::get_last_error() != winapi::error_already_exists); - (void)open_or_created; -} - -inline windows_semaphore::~windows_semaphore() -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - handles.destroy_handle(this->id_); -} - -inline void windows_semaphore::wait(void) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0)); - sem.wait(); -} - -inline bool windows_semaphore::try_wait(void) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0)); - return sem.try_wait(); -} - -inline bool windows_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - //This can throw - winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0)); - return sem.timed_wait(abs_time); -} - -inline void windows_semaphore::post(long release_count) -{ - sync_handles &handles = - windows_intermodule_singleton::get(); - winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0)); - sem.post(release_count); -} - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_WINDOWS_SEMAPHORE_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/sync_utils.hpp b/utils/boost_idb/boost/interprocess/sync/windows/sync_utils.hpp deleted file mode 100644 index 92d8e55a..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/sync_utils.hpp +++ /dev/null @@ -1,236 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_SYNC_UTILS_HPP -#define BOOST_INTERPROCESS_DETAIL_SYNC_UTILS_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include - -//Shield against external warnings -#include - #include -#include - - -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -inline bool bytes_to_str(const void *mem, const std::size_t mem_length, char *out_str, std::size_t &out_length) -{ - const std::size_t need_mem = mem_length*2+1; - if(out_length < need_mem){ - out_length = need_mem; - return false; - } - - const char Characters [] = - { '0', '1', '2', '3', '4', '5', '6', '7' - , '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - - std::size_t char_counter = 0; - const char *buf = (const char *)mem; - for(std::size_t i = 0; i != mem_length; ++i){ - out_str[char_counter++] = Characters[(buf[i]&0xF0)>>4]; - out_str[char_counter++] = Characters[(buf[i]&0x0F)]; - } - out_str[char_counter] = 0; - return true; -} - -class sync_id -{ - public: - typedef __int64 internal_type; - sync_id(const void *map_addr) - : map_addr_(map_addr) - { winapi::query_performance_counter(&rand_); } - - explicit sync_id(internal_type val, const void *map_addr) - : map_addr_(map_addr) - { rand_ = val; } - - const internal_type &internal_pod() const - { return rand_; } - - internal_type &internal_pod() - { return rand_; } - - const void *map_address() const - { return map_addr_; } - - friend std::size_t hash_value(const sync_id &m) - { return boost::hash_value(m.rand_); } - - friend bool operator==(const sync_id &l, const sync_id &r) - { return l.rand_ == r.rand_ && l.map_addr_ == r.map_addr_; } - - private: - internal_type rand_; - const void * const map_addr_; -}; - -class sync_handles -{ - public: - enum type { MUTEX, SEMAPHORE }; - - private: - struct address_less - { - bool operator()(sync_id const * const l, sync_id const * const r) const - { return l->map_address() < r->map_address(); } - }; - - typedef boost::unordered_map umap_type; - typedef boost::container::map map_type; - static const std::size_t LengthOfGlobal = sizeof("Global\\boost.ipc")-1; - static const std::size_t StrSize = LengthOfGlobal + (sizeof(sync_id)*2+1); - typedef char NameBuf[StrSize]; - - - void fill_name(NameBuf &name, const sync_id &id) - { - const char *n = "Global\\boost.ipc"; - std::size_t i = 0; - do{ - name[i] = n[i]; - ++i; - } while(n[i]); - std::size_t len = sizeof(NameBuf) - LengthOfGlobal; - bytes_to_str(&id.internal_pod(), sizeof(id.internal_pod()), &name[LengthOfGlobal], len); - } - - void throw_if_error(void *hnd_val) - { - if(!hnd_val){ - error_info err(winapi::get_last_error()); - throw interprocess_exception(err); - } - } - - void* open_or_create_semaphore(const sync_id &id, unsigned int initial_count) - { - NameBuf name; - fill_name(name, id); - permissions unrestricted_security; - unrestricted_security.set_unrestricted(); - winapi_semaphore_wrapper sem_wrapper; - bool created; - sem_wrapper.open_or_create - (name, (long)initial_count, winapi_semaphore_wrapper::MaxCount, unrestricted_security, created); - throw_if_error(sem_wrapper.handle()); - return sem_wrapper.release(); - } - - void* open_or_create_mutex(const sync_id &id) - { - NameBuf name; - fill_name(name, id); - permissions unrestricted_security; - unrestricted_security.set_unrestricted(); - winapi_mutex_wrapper mtx_wrapper; - mtx_wrapper.open_or_create(name, unrestricted_security); - throw_if_error(mtx_wrapper.handle()); - return mtx_wrapper.release(); - } - - public: - void *obtain_mutex(const sync_id &id, bool *popen_created = 0) - { - umap_type::value_type v(id, (void*)0); - scoped_lock lock(mtx_); - umap_type::iterator it = umap_.insert(v).first; - void *&hnd_val = it->second; - if(!hnd_val){ - map_[&it->first] = it; - hnd_val = open_or_create_mutex(id); - if(popen_created) *popen_created = true; - } - else if(popen_created){ - *popen_created = false; - } - return hnd_val; - } - - void *obtain_semaphore(const sync_id &id, unsigned int initial_count, bool *popen_created = 0) - { - umap_type::value_type v(id, (void*)0); - scoped_lock lock(mtx_); - umap_type::iterator it = umap_.insert(v).first; - void *&hnd_val = it->second; - if(!hnd_val){ - map_[&it->first] = it; - hnd_val = open_or_create_semaphore(id, initial_count); - if(popen_created) *popen_created = true; - } - else if(popen_created){ - *popen_created = false; - } - return hnd_val; - } - - void destroy_handle(const sync_id &id) - { - scoped_lock lock(mtx_); - umap_type::iterator it = umap_.find(id); - umap_type::iterator itend = umap_.end(); - - if(it != itend){ - winapi::close_handle(it->second); - const map_type::key_type &k = &it->first; - map_.erase(k); - umap_.erase(it); - } - } - - void destroy_syncs_in_range(const void *addr, std::size_t size) - { - const sync_id low_id(addr); - const sync_id hig_id(static_cast(addr)+size); - scoped_lock lock(mtx_); - map_type::iterator itlow(map_.lower_bound(&low_id)), - ithig(map_.lower_bound(&hig_id)); - while(itlow != ithig){ - void * const hnd = umap_[*itlow->first]; - winapi::close_handle(hnd); - umap_.erase(*itlow->first); - itlow = map_.erase(itlow); - } - } - - private: - spin_mutex mtx_; - umap_type umap_; - map_type map_; -}; - - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_SYNC_UTILS_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/winapi_mutex_wrapper.hpp b/utils/boost_idb/boost/interprocess/sync/windows/winapi_mutex_wrapper.hpp deleted file mode 100644 index 0be96011..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/winapi_mutex_wrapper.hpp +++ /dev/null @@ -1,163 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_WINAPI_MUTEX_WRAPPER_HPP -#define BOOST_INTERPROCESS_DETAIL_WINAPI_MUTEX_WRAPPER_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class winapi_mutex_functions -{ - /// @cond - - //Non-copyable - winapi_mutex_functions(const winapi_mutex_functions &); - winapi_mutex_functions &operator=(const winapi_mutex_functions &); - /// @endcond - - public: - winapi_mutex_functions(void *mtx_hnd) - : m_mtx_hnd(mtx_hnd) - {} - - void unlock() - { - winapi::release_mutex(m_mtx_hnd); - } - - void lock() - { - if(winapi::wait_for_single_object(m_mtx_hnd, winapi::infinite_time) != winapi::wait_object_0){ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - - bool try_lock() - { - unsigned long ret = winapi::wait_for_single_object(m_mtx_hnd, 0); - if(ret == winapi::wait_object_0){ - return true; - } - else if(ret == winapi::wait_timeout){ - return false; - } - else{ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - - bool timed_lock(const boost::posix_time::ptime &abs_time) - { - if(abs_time == boost::posix_time::pos_infin){ - this->lock(); - return true; - } - - unsigned long ret = winapi::wait_for_single_object - (m_mtx_hnd, (abs_time - microsec_clock::universal_time()).total_milliseconds()); - if(ret == winapi::wait_object_0){ - return true; - } - else if(ret == winapi::wait_timeout){ - return false; - } - else{ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - - /// @cond - protected: - void *m_mtx_hnd; - /// @endcond -}; - -//Swappable mutex wrapper -class winapi_mutex_wrapper - : public winapi_mutex_functions -{ - /// @cond - - //Non-copyable - winapi_mutex_wrapper(const winapi_mutex_wrapper &); - winapi_mutex_wrapper &operator=(const winapi_mutex_wrapper &); - /// @endcond - - public: - winapi_mutex_wrapper(void *mtx_hnd = winapi::invalid_handle_value) - : winapi_mutex_functions(mtx_hnd) - {} - - ~winapi_mutex_wrapper() - { this->close(); } - - void *release() - { - void *hnd = m_mtx_hnd; - m_mtx_hnd = winapi::invalid_handle_value; - return hnd; - } - - void *handle() const - { return m_mtx_hnd; } - - bool open_or_create(const char *name, const permissions &perm) - { - if(m_mtx_hnd == winapi::invalid_handle_value){ - m_mtx_hnd = winapi::open_or_create_mutex - ( name - , false - , (winapi::interprocess_security_attributes*)perm.get_permissions() - ); - return m_mtx_hnd != winapi::invalid_handle_value; - } - else{ - return false; - } - } - - void close() - { - if(m_mtx_hnd != winapi::invalid_handle_value){ - winapi::close_handle(m_mtx_hnd); - m_mtx_hnd = winapi::invalid_handle_value; - } - } - - void swap(winapi_mutex_wrapper &other) - { void *tmp = m_mtx_hnd; m_mtx_hnd = other.m_mtx_hnd; other.m_mtx_hnd = tmp; } -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_WINAPI_MUTEX_WRAPPER_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp b/utils/boost_idb/boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp deleted file mode 100644 index de5185ac..00000000 --- a/utils/boost_idb/boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp +++ /dev/null @@ -1,198 +0,0 @@ - ////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_DETAIL_WINAPI_SEMAPHORE_WRAPPER_HPP -#define BOOST_INTERPROCESS_DETAIL_WINAPI_SEMAPHORE_WRAPPER_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace interprocess { -namespace ipcdetail { - -class winapi_semaphore_functions -{ - /// @cond - - //Non-copyable - winapi_semaphore_functions(const winapi_semaphore_functions &); - winapi_semaphore_functions &operator=(const winapi_semaphore_functions &); - /// @endcond - - public: - winapi_semaphore_functions(void *hnd) - : m_sem_hnd(hnd) - {} - - void post(long count = 1) - { - long prev_count; - winapi::release_semaphore(m_sem_hnd, count, &prev_count); - } - - void wait() - { - if(winapi::wait_for_single_object(m_sem_hnd, winapi::infinite_time) != winapi::wait_object_0){ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - - bool try_wait() - { - unsigned long ret = winapi::wait_for_single_object(m_sem_hnd, 0); - if(ret == winapi::wait_object_0){ - return true; - } - else if(ret == winapi::wait_timeout){ - return false; - } - else{ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - - bool timed_wait(const boost::posix_time::ptime &abs_time) - { - if(abs_time == boost::posix_time::pos_infin){ - this->wait(); - return true; - } - - unsigned long ret = winapi::wait_for_single_object - (m_sem_hnd, (abs_time - microsec_clock::universal_time()).total_milliseconds()); - if(ret == winapi::wait_object_0){ - return true; - } - else if(ret == winapi::wait_timeout){ - return false; - } - else{ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - - long value() const - { - long l_count, l_limit; - if(!winapi::get_semaphore_info(m_sem_hnd, l_count, l_limit)) - return 0; - return l_count; - } - - long limit() const - { - long l_count, l_limit; - if(!winapi::get_semaphore_info(m_sem_hnd, l_count, l_limit)) - return 0; - return l_limit; - } - - /// @cond - protected: - void *m_sem_hnd; - /// @endcond -}; - - -//Swappable semaphore wrapper -class winapi_semaphore_wrapper - : public winapi_semaphore_functions -{ - winapi_semaphore_wrapper(const winapi_semaphore_wrapper &); - winapi_semaphore_wrapper &operator=(const winapi_semaphore_wrapper &); - - public: - - //Long is 32 bits in windows - static const long MaxCount = long(0x7FFFFFFF); - - winapi_semaphore_wrapper(void *hnd = winapi::invalid_handle_value) - : winapi_semaphore_functions(hnd) - {} - - ~winapi_semaphore_wrapper() - { this->close(); } - - void *release() - { - void *hnd = m_sem_hnd; - m_sem_hnd = winapi::invalid_handle_value; - return hnd; - } - - void *handle() const - { return m_sem_hnd; } - - bool open_or_create( const char *name - , long sem_count - , long max_count - , const permissions &perm - , bool &created) - { - if(m_sem_hnd == winapi::invalid_handle_value){ - m_sem_hnd = winapi::open_or_create_semaphore - ( name - , sem_count - , max_count - , (winapi::interprocess_security_attributes*)perm.get_permissions() - ); - created = winapi::get_last_error() != winapi::error_already_exists; - return m_sem_hnd != winapi::invalid_handle_value; - } - else{ - return false; - } - } - - bool open_semaphore(const char *name) - { - if(m_sem_hnd == winapi::invalid_handle_value){ - m_sem_hnd = winapi::open_semaphore(name); - return m_sem_hnd != winapi::invalid_handle_value; - } - else{ - return false; - } - } - - void close() - { - if(m_sem_hnd != winapi::invalid_handle_value){ - winapi::close_handle(m_sem_hnd); - m_sem_hnd = winapi::invalid_handle_value; - } - } - - void swap(winapi_semaphore_wrapper &other) - { void *tmp = m_sem_hnd; m_sem_hnd = other.m_sem_hnd; other.m_sem_hnd = tmp; } -}; - -} //namespace ipcdetail { -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_DETAIL_WINAPI_SEMAPHORE_WRAPPER_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/xsi/simple_xsi_semaphore.hpp b/utils/boost_idb/boost/interprocess/sync/xsi/simple_xsi_semaphore.hpp index deb429a3..4573ba67 100644 --- a/utils/boost_idb/boost/interprocess/sync/xsi/simple_xsi_semaphore.hpp +++ b/utils/boost_idb/boost/interprocess/sync/xsi/simple_xsi_semaphore.hpp @@ -1,12 +1,3 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_SYNC_XSI_SIMPLE_XSI_SEMAPHORE_HPP #define BOOST_INTERPROCESS_SYNC_XSI_SIMPLE_XSI_SEMAPHORE_HPP @@ -112,5 +103,3 @@ inline bool simple_sem_op(int id, int value, bool undo = true) } //namespace xsi { } //namespace interprocess { } //namespace boost { - -#endif //BOOST_INTERPROCESS_SYNC_XSI_SIMPLE_XSI_SEMAPHORE_HPP diff --git a/utils/boost_idb/boost/interprocess/sync/xsi/xsi_named_mutex.hpp b/utils/boost_idb/boost/interprocess/sync/xsi/xsi_named_mutex.hpp index f69f9cda..99161f23 100644 --- a/utils/boost_idb/boost/interprocess/sync/xsi/xsi_named_mutex.hpp +++ b/utils/boost_idb/boost/interprocess/sync/xsi/xsi_named_mutex.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,7 +18,7 @@ #error "This header can't be used in Windows operating systems" #endif -#include +#include #include #include #include @@ -49,7 +49,7 @@ class xsi_named_mutex /// @endcond public: - BOOST_MOVABLE_BUT_NOT_COPYABLE(xsi_named_mutex) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(xsi_named_mutex) //!Default constructor. //!Represents an empty xsi_named_mutex. @@ -60,22 +60,22 @@ class xsi_named_mutex //!If the named mutex previously exists, it tries to open it. //!Otherwise throws an error. xsi_named_mutex(open_or_create_t, const char *path, boost::uint8_t id, int perm = 0666) - { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, path, id, perm); } + { this->priv_open_or_create(detail::DoOpenOrCreate, path, id, perm); } - //!Moves the ownership of "moved"'s named mutex to *this. - //!After the call, "moved" does not represent any named mutex + //!Moves the ownership of "moved"'s named mutex to *this. + //!After the call, "moved" does not represent any named mutex //!Does not throw - xsi_named_mutex(BOOST_RV_REF(xsi_named_mutex) moved) + xsi_named_mutex(BOOST_INTERPROCESS_RV_REF(xsi_named_mutex) moved) { this->swap(moved); } //!Moves the ownership of "moved"'s named mutex to *this. - //!After the call, "moved" does not represent any named mutex. + //!After the call, "moved" does not represent any named mutex. //!Does not throw - xsi_named_mutex &operator=(BOOST_RV_REF(xsi_named_mutex) moved) - { - xsi_named_mutex tmp(boost::move(moved)); + xsi_named_mutex &operator=(BOOST_INTERPROCESS_RV_REF(xsi_named_mutex) moved) + { + xsi_named_mutex tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Swaps two xsi_named_mutex. Does not throw @@ -112,7 +112,7 @@ class xsi_named_mutex void priv_close(); //!Closes a previously opened file mapping. Never throws. - bool priv_open_or_create( ipcdetail::create_enum_t type + bool priv_open_or_create( detail::create_enum_t type , const char *path , boost::uint8_t id , int perm); @@ -126,11 +126,11 @@ class xsi_named_mutex /// @cond -inline xsi_named_mutex::xsi_named_mutex() +inline xsi_named_mutex::xsi_named_mutex() : m_semid(-1), m_key(-1), m_id(0), m_perm(0), m_path() {} -inline xsi_named_mutex::~xsi_named_mutex() +inline xsi_named_mutex::~xsi_named_mutex() { this->priv_close(); } inline const char *xsi_named_mutex::get_path() const @@ -142,7 +142,7 @@ inline void xsi_named_mutex::swap(xsi_named_mutex &other) std::swap(m_id, other.m_id); std::swap(m_semid, other.m_semid); std::swap(m_perm, other.m_perm); - m_path.swap(other.m_path); + m_path.swap(other.m_path); } inline mapping_handle_t xsi_named_mutex::get_mapping_handle() const @@ -152,7 +152,7 @@ inline int xsi_named_mutex::get_permissions() const { return m_perm; } inline bool xsi_named_mutex::priv_open_or_create - (ipcdetail::create_enum_t type, const char *path, boost::uint8_t id, int perm) + (detail::create_enum_t type, const char *path, boost::uint8_t id, int perm) { key_t key; if(path){ diff --git a/utils/boost_idb/boost/interprocess/windows_shared_memory.hpp b/utils/boost_idb/boost/interprocess/windows_shared_memory.hpp index f2195ac2..f1ccc41c 100644 --- a/utils/boost_idb/boost/interprocess/windows_shared_memory.hpp +++ b/utils/boost_idb/boost/interprocess/windows_shared_memory.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -52,7 +52,7 @@ class windows_shared_memory { /// @cond //Non-copyable and non-assignable - BOOST_MOVABLE_BUT_NOT_COPYABLE(windows_shared_memory) + BOOST_INTERPROCESS_MOVABLE_BUT_NOT_COPYABLE(windows_shared_memory) /// @endcond public: @@ -64,34 +64,34 @@ class windows_shared_memory //!with the access mode "mode". //!If the file previously exists, throws an error. windows_shared_memory(create_only_t, const char *name, mode_t mode, std::size_t size, const permissions& perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoCreate, name, mode, size, perm); } + { this->priv_open_or_create(detail::DoCreate, name, mode, size, perm); } //!Tries to create a shared memory object with name "name" and mode "mode", with the //!access mode "mode". If the file previously exists, it tries to open it with mode "mode". //!Otherwise throws an error. windows_shared_memory(open_or_create_t, const char *name, mode_t mode, std::size_t size, const permissions& perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, name, mode, size, perm); } + { this->priv_open_or_create(detail::DoOpenOrCreate, name, mode, size, perm); } - //!Tries to open a shared memory object with name "name", with the access mode "mode". + //!Tries to open a shared memory object with name "name", with the access mode "mode". //!If the file does not previously exist, it throws an error. windows_shared_memory(open_only_t, const char *name, mode_t mode) - { this->priv_open_or_create(ipcdetail::DoOpen, name, mode, 0, permissions()); } + { this->priv_open_or_create(detail::DoOpen, name, mode, 0, permissions()); } - //!Moves the ownership of "moved"'s shared memory object to *this. - //!After the call, "moved" does not represent any shared memory object. + //!Moves the ownership of "moved"'s shared memory object to *this. + //!After the call, "moved" does not represent any shared memory object. //!Does not throw - windows_shared_memory(BOOST_RV_REF(windows_shared_memory) moved) + windows_shared_memory(BOOST_INTERPROCESS_RV_REF(windows_shared_memory) moved) : m_handle(0) { this->swap(moved); } //!Moves the ownership of "moved"'s shared memory to *this. - //!After the call, "moved" does not represent any shared memory. + //!After the call, "moved" does not represent any shared memory. //!Does not throw - windows_shared_memory &operator=(BOOST_RV_REF(windows_shared_memory) moved) - { - windows_shared_memory tmp(boost::move(moved)); + windows_shared_memory &operator=(BOOST_INTERPROCESS_RV_REF(windows_shared_memory) moved) + { + windows_shared_memory tmp(boost::interprocess::move(moved)); this->swap(tmp); - return *this; + return *this; } //!Swaps to shared_memory_objects. Does not throw @@ -119,7 +119,7 @@ class windows_shared_memory void priv_close(); //!Closes a previously opened file mapping. Never throws. - bool priv_open_or_create(ipcdetail::create_enum_t type, const char *filename, mode_t mode, std::size_t size, const permissions& perm = permissions()); + bool priv_open_or_create(detail::create_enum_t type, const char *filename, mode_t mode, std::size_t size, const permissions& perm = permissions()); void * m_handle; mode_t m_mode; @@ -129,21 +129,21 @@ class windows_shared_memory /// @cond -inline windows_shared_memory::windows_shared_memory() +inline windows_shared_memory::windows_shared_memory() : m_handle(0) {} -inline windows_shared_memory::~windows_shared_memory() +inline windows_shared_memory::~windows_shared_memory() { this->priv_close(); } inline const char *windows_shared_memory::get_name() const { return m_name.c_str(); } inline void windows_shared_memory::swap(windows_shared_memory &other) -{ +{ std::swap(m_handle, other.m_handle); std::swap(m_mode, other.m_mode); - m_name.swap(other.m_name); + m_name.swap(other.m_name); } inline mapping_handle_t windows_shared_memory::get_mapping_handle() const @@ -153,30 +153,26 @@ inline mode_t windows_shared_memory::get_mode() const { return m_mode; } inline bool windows_shared_memory::priv_open_or_create - (ipcdetail::create_enum_t type, const char *filename, mode_t mode, std::size_t size, const permissions& perm) + (detail::create_enum_t type, const char *filename, mode_t mode, std::size_t size, const permissions& perm) { m_name = filename ? filename : ""; - unsigned long protection = 0; + unsigned long file_map_access = 0; unsigned long map_access = 0; switch(mode) { - //"protection" is for "create_file_mapping" - //"map_access" is for "open_file_mapping" - //Add section query (strange that read or access does not grant it...) - //to obtain the size of the mapping. copy_on_write is equal to section_query. case read_only: - protection |= winapi::page_readonly; - map_access |= winapi::file_map_read | winapi::section_query; + file_map_access |= winapi::page_readonly; + map_access |= winapi::file_map_read; break; case read_write: - protection |= winapi::page_readwrite; - map_access |= winapi::file_map_write | winapi::section_query; + file_map_access |= winapi::page_readwrite; + map_access |= winapi::file_map_write; break; case copy_on_write: - protection |= winapi::page_writecopy; - map_access |= winapi::file_map_copy; + file_map_access |= winapi::page_writecopy; + map_access |= winapi::file_map_copy; break; default: { @@ -187,14 +183,17 @@ inline bool windows_shared_memory::priv_open_or_create } switch(type){ - case ipcdetail::DoOpen: - m_handle = winapi::open_file_mapping(map_access, filename); + case detail::DoOpen: + m_handle = winapi::open_file_mapping + (map_access, filename); break; - case ipcdetail::DoCreate: - case ipcdetail::DoOpenOrCreate: + case detail::DoCreate: + case detail::DoOpenOrCreate: { + __int64 s = size; + unsigned long high_size(s >> 32), low_size((boost::uint32_t)s); m_handle = winapi::create_file_mapping - ( winapi::invalid_handle_value, protection, size, filename + ( winapi::invalid_handle_value, file_map_access, high_size, low_size, filename , (winapi::interprocess_security_attributes*)perm.get_permissions()); } break; @@ -205,7 +204,7 @@ inline bool windows_shared_memory::priv_open_or_create } } - if(!m_handle || (type == ipcdetail::DoCreate && winapi::get_last_error() == winapi::error_already_exists)){ + if(!m_handle || (type == detail::DoCreate && winapi::get_last_error() == winapi::error_already_exists)){ error_info err = system_error_code(); this->priv_close(); throw interprocess_exception(err); diff --git a/utils/boost_idb/boost/interprocess/xsi_key.hpp b/utils/boost_idb/boost/interprocess/xsi_key.hpp deleted file mode 100644 index ffd4c498..00000000 --- a/utils/boost_idb/boost/interprocess/xsi_key.hpp +++ /dev/null @@ -1,87 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_XSI_KEY_HPP -#define BOOST_INTERPROCESS_XSI_KEY_HPP - -#include -#include -#include - -#if !defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) -#error "This header can't be used in operating systems without XSI (System V) shared memory support" -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes a class representing a xsi key type. - -namespace boost { -namespace interprocess { - -//!A class that wraps XSI (System V) key_t type. -//!This type calculates key_t from path and id using ftok -//!or sets key to IPC_PRIVATE using the default constructor. -class xsi_key -{ - public: - - //!Default constructor. - //!Represents a private xsi_key. - xsi_key() - : m_key(IPC_PRIVATE) - {} - - //!Creates a new XSI shared memory with a key obtained from a call to ftok (with path - //!"path" and id "id"), of size "size" and permissions "perm". - //!If the shared memory previously exists, throws an error. - xsi_key(const char *path, boost::uint8_t id) - { - key_t key; - if(path){ - key = ::ftok(path, id); - if(((key_t)-1) == key){ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - } - else{ - key = IPC_PRIVATE; - } - m_key = key; - } - - //!Returns the internal key_t value - key_t get_key() const - { return m_key; } - - /// @cond - private: - key_t m_key; - /// @endcond -}; - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_XSI_KEY_HPP diff --git a/utils/boost_idb/boost/interprocess/xsi_shared_memory.hpp b/utils/boost_idb/boost/interprocess/xsi_shared_memory.hpp deleted file mode 100644 index 11cfe1d1..00000000 --- a/utils/boost_idb/boost/interprocess/xsi_shared_memory.hpp +++ /dev/null @@ -1,201 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/interprocess for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_HPP -#define BOOST_INTERPROCESS_XSI_SHARED_MEMORY_HPP - -#include -#include -#include - -#if !defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS) -#error "This header can't be used in operating systems without XSI (System V) shared memory support" -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes a class representing a native xsi shared memory. - -namespace boost { -namespace interprocess { - -//!A class that wraps XSI (System V) shared memory. -//!Unlike shared_memory_object, xsi_shared_memory needs a valid -//!xsi_key to identify a shared memory object. -//! -//!Warning: XSI shared memory and interprocess portable -//!shared memory (boost::interprocess::shared_memory_object) -//!can't communicate between them. -class xsi_shared_memory -{ - /// @cond - //Non-copyable and non-assignable - BOOST_MOVABLE_BUT_NOT_COPYABLE(xsi_shared_memory) - /// @endcond - - public: - //!Default constructor. - //!Represents an empty xsi_shared_memory. - xsi_shared_memory(); - - //!Initializes *this with a shmid previously obtained (possibly from another process) - //!This lower-level initializer allows shared memory mapping without having a key. - xsi_shared_memory(open_only_t, int shmid) - : m_shmid (shmid) - {} - - //!Creates a new XSI shared memory from 'key', with size "size" and permissions "perm". - //!If the shared memory previously exists, throws an error. - xsi_shared_memory(create_only_t, const xsi_key &key, std::size_t size, const permissions& perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoCreate, key, perm, size); } - - //!Opens an existing shared memory with identifier 'key' or creates a new XSI shared memory from - //!identifier 'key', with size "size" and permissions "perm". - xsi_shared_memory(open_or_create_t, const xsi_key &key, std::size_t size, const permissions& perm = permissions()) - { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, key, perm, size); } - - //!Tries to open a XSI shared memory with identifier 'key' - //!If the shared memory does not previously exist, it throws an error. - xsi_shared_memory(open_only_t, const xsi_key &key) - { this->priv_open_or_create(ipcdetail::DoOpen, key, permissions(), 0); } - - //!Moves the ownership of "moved"'s shared memory object to *this. - //!After the call, "moved" does not represent any shared memory object. - //!Does not throw - xsi_shared_memory(BOOST_RV_REF(xsi_shared_memory) moved) - : m_shmid(-1) - { this->swap(moved); } - - //!Moves the ownership of "moved"'s shared memory to *this. - //!After the call, "moved" does not represent any shared memory. - //!Does not throw - xsi_shared_memory &operator=(BOOST_RV_REF(xsi_shared_memory) moved) - { - xsi_shared_memory tmp(boost::move(moved)); - this->swap(tmp); - return *this; - } - - //!Swaps two xsi_shared_memorys. Does not throw - void swap(xsi_shared_memory &other); - - //!Destroys *this. The shared memory won't be destroyed, just - //!this connection to it. Use remove() to destroy the shared memory. - ~xsi_shared_memory(); - - //!Returns the shared memory ID that - //!identifies the shared memory - int get_shmid() const; - - //!Returns the mapping handle. - //!Never throws - mapping_handle_t get_mapping_handle() const; - - //!Erases the XSI shared memory object identified by shmid - //!from the system. - //!Returns false on error. Never throws - static bool remove(int shmid); - - /// @cond - private: - - //!Closes a previously opened file mapping. Never throws. - bool priv_open_or_create( ipcdetail::create_enum_t type - , const xsi_key &key - , const permissions& perm - , std::size_t size); - int m_shmid; - /// @endcond -}; - -/// @cond - -inline xsi_shared_memory::xsi_shared_memory() - : m_shmid(-1) -{} - -inline xsi_shared_memory::~xsi_shared_memory() -{} - -inline int xsi_shared_memory::get_shmid() const -{ return m_shmid; } - -inline void xsi_shared_memory::swap(xsi_shared_memory &other) -{ - std::swap(m_shmid, other.m_shmid); -} - -inline mapping_handle_t xsi_shared_memory::get_mapping_handle() const -{ mapping_handle_t mhnd = { m_shmid, true}; return mhnd; } - -inline bool xsi_shared_memory::priv_open_or_create - (ipcdetail::create_enum_t type, const xsi_key &key, const permissions& permissions, std::size_t size) -{ - int perm = permissions.get_permissions(); - perm &= 0x01FF; - int shmflg = perm; - - switch(type){ - case ipcdetail::DoOpen: - shmflg |= 0; - break; - case ipcdetail::DoCreate: - shmflg |= IPC_CREAT | IPC_EXCL; - break; - case ipcdetail::DoOpenOrCreate: - shmflg |= IPC_CREAT; - break; - default: - { - error_info err = other_error; - throw interprocess_exception(err); - } - } - - int ret = ::shmget(key.get_key(), size, shmflg); - int shmid = ret; - if((type == ipcdetail::DoOpen) && (-1 != ret)){ - //Now get the size - ::shmid_ds xsi_ds; - ret = ::shmctl(ret, IPC_STAT, &xsi_ds); - size = xsi_ds.shm_segsz; - } - if(-1 == ret){ - error_info err = system_error_code(); - throw interprocess_exception(err); - } - - m_shmid = shmid; - return true; -} - -inline bool xsi_shared_memory::remove(int shmid) -{ return -1 != ::shmctl(shmid, IPC_RMID, 0); } - -///@endcond - -} //namespace interprocess { -} //namespace boost { - -#include - -#endif //BOOST_INTERPROCESS_XSI_SHARED_MEMORY_HPP diff --git a/utils/boost_idb/boost/intrusive/any_hook.hpp b/utils/boost_idb/boost/intrusive/any_hook.hpp deleted file mode 100644 index 03c299f2..00000000 --- a/utils/boost_idb/boost/intrusive/any_hook.hpp +++ /dev/null @@ -1,345 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_ANY_HOOK_HPP -#define BOOST_INTRUSIVE_ANY_HOOK_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond -template -struct get_any_node_algo -{ - typedef any_algorithms type; -}; -/// @endcond - -//! Helper metafunction to define a \c \c any_base_hook that yields to the same -//! type when the same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_any_base_hook -{ - /// @cond - typedef typename pack_options - < hook_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3 - #else - Options... - #endif - >::type packed_options; - - typedef generic_hook - < get_any_node_algo - , typename packed_options::tag - , packed_options::link_mode - , AnyBaseHookId - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -//! Derive a class from this hook in order to store objects of that class -//! in an intrusive container. -//! -//! The hook admits the following options: \c tag<>, \c void_pointer<> and -//! \c link_mode<>. -//! -//! \c tag<> defines a tag to identify the node. -//! The same tag value can be used in different classes, but if a class is -//! derived from more than one \c any_base_hook, then each \c any_base_hook needs its -//! unique tag. -//! -//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, \c safe_link). -//! -//! \c void_pointer<> is the pointer type that will be used internally in the hook -//! and the the container configured to use this hook. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class any_base_hook - : public make_any_base_hook - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type -{ - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - public: - //! Effects: If link_mode is or \c safe_link - //! initializes the node to an unlinked state. - //! - //! Throws: Nothing. - any_base_hook(); - - //! Effects: If link_mode is or \c safe_link - //! initializes the node to an unlinked state. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing a copy-constructor - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - any_base_hook(const any_base_hook& ); - - //! Effects: Empty function. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing an assignment operator - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - any_base_hook& operator=(const any_base_hook& ); - - //! Effects: If link_mode is \c normal_link, the destructor does - //! nothing (ie. no code is generated). If link_mode is \c safe_link and the - //! object is stored in a container an assertion is raised. - //! - //! Throws: Nothing. - ~any_base_hook(); - - //! Precondition: link_mode must be \c safe_link. - //! - //! Returns: true, if the node belongs to a container, false - //! otherwise. This function can be used to test whether \c container::iterator_to - //! will return a valid iterator. - //! - //! Complexity: Constant - bool is_linked() const; - #endif -}; - -//! Helper metafunction to define a \c \c any_member_hook that yields to the same -//! type when the same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_any_member_hook -{ - /// @cond - typedef typename pack_options - < hook_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3 - #else - Options... - #endif - >::type packed_options; - - typedef generic_hook - < get_any_node_algo - , member_tag - , packed_options::link_mode - , NoBaseHookId - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -//! Store this hook in a class to be inserted -//! in an intrusive container. -//! -//! The hook admits the following options: \c void_pointer<> and -//! \c link_mode<>. -//! -//! \c link_mode<> will specify the linking mode of the hook (\c normal_link or \c safe_link). -//! -//! \c void_pointer<> is the pointer type that will be used internally in the hook -//! and the the container configured to use this hook. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class any_member_hook - : public make_any_member_hook - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type -{ - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - public: - //! Effects: If link_mode is or \c safe_link - //! initializes the node to an unlinked state. - //! - //! Throws: Nothing. - any_member_hook(); - - //! Effects: If link_mode is or \c safe_link - //! initializes the node to an unlinked state. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing a copy-constructor - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - any_member_hook(const any_member_hook& ); - - //! Effects: Empty function. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing an assignment operator - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - any_member_hook& operator=(const any_member_hook& ); - - //! Effects: If link_mode is \c normal_link, the destructor does - //! nothing (ie. no code is generated). If link_mode is \c safe_link and the - //! object is stored in a container an assertion is raised. - //! - //! Throws: Nothing. - ~any_member_hook(); - - //! Precondition: link_mode must be \c safe_link. - //! - //! Returns: true, if the node belongs to a container, false - //! otherwise. This function can be used to test whether \c container::iterator_to - //! will return a valid iterator. - //! - //! Complexity: Constant - bool is_linked() const; - #endif -}; - -/// @cond - -namespace detail{ - -template -struct any_to_get_base_pointer_type -{ - typedef typename pointer_traits::template - rebind_pointer::type type; -}; - -template -struct any_to_get_member_pointer_type -{ - typedef typename pointer_traits - ::template rebind_pointer::type type; -}; - -//!This option setter specifies that the container -//!must use the specified base hook -template class NodeTraits> -struct any_to_some_hook -{ - typedef typename BaseHook::template pack::proto_value_traits old_proto_value_traits; - - template - struct pack : public Base - { - struct proto_value_traits : public old_proto_value_traits - { - static const bool is_any_hook = true; - typedef typename detail::eval_if_c - < detail::internal_base_hook_bool_is_true::value - , any_to_get_base_pointer_type - , any_to_get_member_pointer_type - >::type void_pointer; - typedef NodeTraits node_traits; - }; - }; -}; - -} //namespace detail{ - -/// @endcond - -//!This option setter specifies that -//!any hook should behave as an slist hook -template -struct any_to_slist_hook -/// @cond - : public detail::any_to_some_hook -/// @endcond -{}; - -//!This option setter specifies that -//!any hook should behave as an list hook -template -struct any_to_list_hook -/// @cond - : public detail::any_to_some_hook -/// @endcond -{}; - -//!This option setter specifies that -//!any hook should behave as a set hook -template -struct any_to_set_hook -/// @cond - : public detail::any_to_some_hook -/// @endcond -{}; - -//!This option setter specifies that -//!any hook should behave as an avl_set hook -template -struct any_to_avl_set_hook -/// @cond - : public detail::any_to_some_hook -/// @endcond -{}; - -//!This option setter specifies that any -//!hook should behave as a bs_set hook -template -struct any_to_bs_set_hook -/// @cond - : public detail::any_to_some_hook -/// @endcond -{}; - -//!This option setter specifies that any hook -//!should behave as an unordered set hook -template -struct any_to_unordered_set_hook -/// @cond - : public detail::any_to_some_hook -/// @endcond -{}; - - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_ANY_HOOK_HPP diff --git a/utils/boost_idb/boost/intrusive/avl_set.hpp b/utils/boost_idb/boost/intrusive/avl_set.hpp deleted file mode 100644 index 061a0868..00000000 --- a/utils/boost_idb/boost/intrusive/avl_set.hpp +++ /dev/null @@ -1,924 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTRUSIVE_AVL_SET_HPP -#define BOOST_INTRUSIVE_AVL_SET_HPP - -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -//! The class template avl_set is an intrusive container, that mimics most of -//! the interface of std::set as described in the C++ standard. -//! -//! The template parameter \c T is the type to be managed by the container. -//! The user can specify additional options and if no options are provided -//! default options are used. -//! -//! The container supports the following options: -//! \c base_hook<>/member_hook<>/value_traits<>, -//! \c constant_time_size<>, \c size_type<> and -//! \c compare<>. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -class avl_set_impl -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - : public bstree_impl -#endif -{ - /// @cond - typedef bstree_impl tree_type; - BOOST_MOVABLE_BUT_NOT_COPYABLE(avl_set_impl) - - typedef tree_type implementation_defined; - /// @endcond - - public: - typedef typename implementation_defined::value_type value_type; - typedef typename implementation_defined::value_traits value_traits; - typedef typename implementation_defined::pointer pointer; - typedef typename implementation_defined::const_pointer const_pointer; - typedef typename implementation_defined::reference reference; - typedef typename implementation_defined::const_reference const_reference; - typedef typename implementation_defined::difference_type difference_type; - typedef typename implementation_defined::size_type size_type; - typedef typename implementation_defined::value_compare value_compare; - typedef typename implementation_defined::key_compare key_compare; - typedef typename implementation_defined::iterator iterator; - typedef typename implementation_defined::const_iterator const_iterator; - typedef typename implementation_defined::reverse_iterator reverse_iterator; - typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; - typedef typename implementation_defined::insert_commit_data insert_commit_data; - typedef typename implementation_defined::node_traits node_traits; - typedef typename implementation_defined::node node; - typedef typename implementation_defined::node_ptr node_ptr; - typedef typename implementation_defined::const_node_ptr const_node_ptr; - typedef typename implementation_defined::node_algorithms node_algorithms; - - static const bool constant_time_size = tree_type::constant_time_size; - - public: - - //! @copydoc ::boost::intrusive::avltree::avltree(const value_compare &,const value_traits &) - explicit avl_set_impl( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::avltree::avltree(bool,Iterator,Iterator,const value_compare &,const value_traits &) - template - avl_set_impl( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(true, b, e, cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::avltree::avltree(avltree &&) - avl_set_impl(BOOST_RV_REF(avl_set_impl) x) - : tree_type(::boost::move(static_cast(x))) - {} - - //! @copydoc ::boost::intrusive::avltree::operator=(avltree &&) - avl_set_impl& operator=(BOOST_RV_REF(avl_set_impl) x) - { return static_cast(tree_type::operator=(::boost::move(static_cast(x)))); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::avltree::~avltree() - ~avl_set_impl(); - - //! @copydoc ::boost::intrusive::avltree::begin() - iterator begin(); - - //! @copydoc ::boost::intrusive::avltree::begin()const - const_iterator begin() const; - - //! @copydoc ::boost::intrusive::avltree::cbegin()const - const_iterator cbegin() const; - - //! @copydoc ::boost::intrusive::avltree::end() - iterator end(); - - //! @copydoc ::boost::intrusive::avltree::end()const - const_iterator end() const; - - //! @copydoc ::boost::intrusive::avltree::cend()const - const_iterator cend() const; - - //! @copydoc ::boost::intrusive::avltree::begin() - reverse_iterator avlegin(); - - //! @copydoc ::boost::intrusive::avltree::begin()const - const_reverse_iterator avlegin() const; - - //! @copydoc ::boost::intrusive::avltree::crbegin()const - const_reverse_iterator crbegin() const; - - //! @copydoc ::boost::intrusive::avltree::rend() - reverse_iterator rend(); - - //! @copydoc ::boost::intrusive::avltree::rend()const - const_reverse_iterator rend() const; - - //! @copydoc ::boost::intrusive::avltree::crend()const - const_reverse_iterator crend() const; - - //! @copydoc ::boost::intrusive::avltree::container_from_end_iterator(iterator) - static avl_set_impl &container_from_end_iterator(iterator end_iterator); - - //! @copydoc ::boost::intrusive::avltree::container_from_end_iterator(const_iterator) - static const avl_set_impl &container_from_end_iterator(const_iterator end_iterator); - - //! @copydoc ::boost::intrusive::avltree::container_from_iterator(iterator) - static avl_set_impl &container_from_iterator(iterator it); - - //! @copydoc ::boost::intrusive::avltree::container_from_iterator(const_iterator) - static const avl_set_impl &container_from_iterator(const_iterator it); - - //! @copydoc ::boost::intrusive::avltree::key_comp()const - key_compare key_comp() const; - - //! @copydoc ::boost::intrusive::avltree::value_comp()const - value_compare value_comp() const; - - //! @copydoc ::boost::intrusive::avltree::empty()const - bool empty() const; - - //! @copydoc ::boost::intrusive::avltree::size()const - size_type size() const; - - //! @copydoc ::boost::intrusive::avltree::swap - void swap(avl_set_impl& other); - - //! @copydoc ::boost::intrusive::avltree::clone_from - template - void clone_from(const avl_set_impl &src, Cloner cloner, Disposer disposer); - - #endif //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::avltree::insert_unique(reference) - std::pair insert(reference value) - { return tree_type::insert_unique(value); } - - //! @copydoc ::boost::intrusive::avltree::insert_unique(const_iterator,reference) - iterator insert(const_iterator hint, reference value) - { return tree_type::insert_unique(hint, value); } - - //! @copydoc ::boost::intrusive::avltree::insert_unique_check(const KeyType&,KeyValueCompare,insert_commit_data&) - template - std::pair insert_check - (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data) - { return tree_type::insert_unique_check(key, key_value_comp, commit_data); } - - //! @copydoc ::boost::intrusive::avltree::insert_unique_check(const_iterator,const KeyType&,KeyValueCompare,insert_commit_data&) - template - std::pair insert_check - (const_iterator hint, const KeyType &key - ,KeyValueCompare key_value_comp, insert_commit_data &commit_data) - { return tree_type::insert_unique_check(hint, key, key_value_comp, commit_data); } - - //! @copydoc ::boost::intrusive::avltree::insert_unique(Iterator,Iterator) - template - void insert(Iterator b, Iterator e) - { tree_type::insert_unique(b, e); } - - //! @copydoc ::boost::intrusive::avltree::insert_unique_commit - iterator insert_commit(reference value, const insert_commit_data &commit_data) - { return tree_type::insert_unique_commit(value, commit_data); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::avltree::insert_before - iterator insert_before(const_iterator pos, reference value); - - //! @copydoc ::boost::intrusive::avltree::push_back - void push_back(reference value); - - //! @copydoc ::boost::intrusive::avltree::push_front - void push_front(reference value); - - //! @copydoc ::boost::intrusive::avltree::erase(const_iterator) - iterator erase(const_iterator i); - - //! @copydoc ::boost::intrusive::avltree::erase(const_iterator,const_iterator) - iterator erase(const_iterator b, const_iterator e); - - //! @copydoc ::boost::intrusive::avltree::erase(const_reference) - size_type erase(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::erase(const KeyType&,KeyValueCompare) - template - size_type erase(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator i, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const_iterator,const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const_reference, Disposer) - template - size_type erase_and_dispose(const_reference value, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer) - template - size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::clear - void clear(); - - //! @copydoc ::boost::intrusive::avltree::clear_and_dispose - template - void clear_and_dispose(Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::count(const_reference)const - size_type count(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::count(const KeyType&,KeyValueCompare)const - template - size_type count(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const_reference) - iterator lower_bound(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const KeyType&,KeyValueCompare) - template - iterator lower_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const_reference)const - const_iterator lower_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const KeyType&,KeyValueCompare)const - template - const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const_reference) - iterator upper_bound(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const KeyType&,KeyValueCompare) - template - iterator upper_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const_reference)const - const_iterator upper_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const KeyType&,KeyValueCompare)const - template - const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::find(const_reference) - iterator find(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::find(const KeyType&,KeyValueCompare) - template - iterator find(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::find(const_reference)const - const_iterator find(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::find(const KeyType&,KeyValueCompare)const - template - const_iterator find(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::equal_range(const_reference) - std::pair equal_range(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::equal_range(const KeyType&,KeyValueCompare) - template - std::pair equal_range(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::equal_range(const_reference)const - std::pair - equal_range(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::equal_range(const KeyType&,KeyValueCompare)const - template - std::pair - equal_range(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const_reference,const_reference,bool,bool) - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool) - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const_reference,const_reference,bool,bool)const - std::pair - bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::avltree::s_iterator_to(reference) - static iterator s_iterator_to(reference value); - - //! @copydoc ::boost::intrusive::avltree::s_iterator_to(const_reference) - static const_iterator s_iterator_to(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::iterator_to(reference) - iterator iterator_to(reference value); - - //! @copydoc ::boost::intrusive::avltree::iterator_to(const_reference)const - const_iterator iterator_to(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::init_node(reference) - static void init_node(reference value); - - //! @copydoc ::boost::intrusive::avltree::unlink_leftmost_without_rebalance - pointer unlink_leftmost_without_rebalance(); - - //! @copydoc ::boost::intrusive::avltree::replace_node - void replace_node(iterator replace_this, reference with_this); - - //! @copydoc ::boost::intrusive::avltree::remove_node - void remove_node(reference value); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED -}; - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -template -bool operator!= (const avl_set_impl &x, const avl_set_impl &y); - -template -bool operator>(const avl_set_impl &x, const avl_set_impl &y); - -template -bool operator<=(const avl_set_impl &x, const avl_set_impl &y); - -template -bool operator>=(const avl_set_impl &x, const avl_set_impl &y); - -template -void swap(avl_set_impl &x, avl_set_impl &y); - -#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -//! Helper metafunction to define a \c set that yields to the same type when the -//! same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_avl_set -{ - /// @cond - typedef typename pack_options - < avltree_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3, O4 - #else - Options... - #endif - >::type packed_options; - - typedef typename detail::get_value_traits - ::type value_traits; - - typedef avl_set_impl - < value_traits - , typename packed_options::compare - , typename packed_options::size_type - , packed_options::constant_time_size - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED -#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class avl_set - : public make_avl_set::type -{ - typedef typename make_avl_set - ::type Base; - - BOOST_MOVABLE_BUT_NOT_COPYABLE(avl_set) - public: - typedef typename Base::value_compare value_compare; - typedef typename Base::value_traits value_traits; - typedef typename Base::iterator iterator; - typedef typename Base::const_iterator const_iterator; - - //Assert if passed value traits are compatible with the type - BOOST_STATIC_ASSERT((detail::is_same::value)); - - explicit avl_set( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(cmp, v_traits) - {} - - template - avl_set( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(b, e, cmp, v_traits) - {} - - avl_set(BOOST_RV_REF(avl_set) x) - : Base(::boost::move(static_cast(x))) - {} - - avl_set& operator=(BOOST_RV_REF(avl_set) x) - { return static_cast(this->Base::operator=(::boost::move(static_cast(x)))); } - - static avl_set &container_from_end_iterator(iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static const avl_set &container_from_end_iterator(const_iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static avl_set &container_from_iterator(iterator it) - { return static_cast(Base::container_from_iterator(it)); } - - static const avl_set &container_from_iterator(const_iterator it) - { return static_cast(Base::container_from_iterator(it)); } -}; - -#endif - -//! The class template avl_multiset is an intrusive container, that mimics most of -//! the interface of std::_multiset as described in the C++ standard. -//! -//! The template parameter \c T is the type to be managed by the container. -//! The user can specify additional options and if no options are provided -//! default options are used. -//! -//! The container supports the following options: -//! \c base_hook<>/member_hook<>/value_traits<>, -//! \c constant_time_size<>, \c size_type<> and -//! \c compare<>. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -class avl_multiset_impl -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - : public bstree_impl -#endif -{ - /// @cond - typedef bstree_impl tree_type; - - BOOST_MOVABLE_BUT_NOT_COPYABLE(avl_multiset_impl) - typedef tree_type implementation_defined; - /// @endcond - - public: - typedef typename implementation_defined::value_type value_type; - typedef typename implementation_defined::value_traits value_traits; - typedef typename implementation_defined::pointer pointer; - typedef typename implementation_defined::const_pointer const_pointer; - typedef typename implementation_defined::reference reference; - typedef typename implementation_defined::const_reference const_reference; - typedef typename implementation_defined::difference_type difference_type; - typedef typename implementation_defined::size_type size_type; - typedef typename implementation_defined::value_compare value_compare; - typedef typename implementation_defined::key_compare key_compare; - typedef typename implementation_defined::iterator iterator; - typedef typename implementation_defined::const_iterator const_iterator; - typedef typename implementation_defined::reverse_iterator reverse_iterator; - typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; - typedef typename implementation_defined::insert_commit_data insert_commit_data; - typedef typename implementation_defined::node_traits node_traits; - typedef typename implementation_defined::node node; - typedef typename implementation_defined::node_ptr node_ptr; - typedef typename implementation_defined::const_node_ptr const_node_ptr; - typedef typename implementation_defined::node_algorithms node_algorithms; - - static const bool constant_time_size = tree_type::constant_time_size; - - public: - //! @copydoc ::boost::intrusive::avltree::avltree(const value_compare &,const value_traits &) - explicit avl_multiset_impl( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::avltree::avltree(bool,Iterator,Iterator,const value_compare &,const value_traits &) - template - avl_multiset_impl( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(false, b, e, cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::avltree::avltree(avltree &&) - avl_multiset_impl(BOOST_RV_REF(avl_multiset_impl) x) - : tree_type(::boost::move(static_cast(x))) - {} - - //! @copydoc ::boost::intrusive::avltree::operator=(avltree &&) - avl_multiset_impl& operator=(BOOST_RV_REF(avl_multiset_impl) x) - { return static_cast(tree_type::operator=(::boost::move(static_cast(x)))); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::avltree::~avltree() - ~avl_multiset_impl(); - - //! @copydoc ::boost::intrusive::avltree::begin() - iterator begin(); - - //! @copydoc ::boost::intrusive::avltree::begin()const - const_iterator begin() const; - - //! @copydoc ::boost::intrusive::avltree::cbegin()const - const_iterator cbegin() const; - - //! @copydoc ::boost::intrusive::avltree::end() - iterator end(); - - //! @copydoc ::boost::intrusive::avltree::end()const - const_iterator end() const; - - //! @copydoc ::boost::intrusive::avltree::cend()const - const_iterator cend() const; - - //! @copydoc ::boost::intrusive::avltree::rbegin() - reverse_iterator rbegin(); - - //! @copydoc ::boost::intrusive::avltree::rbegin()const - const_reverse_iterator rbegin() const; - - //! @copydoc ::boost::intrusive::avltree::crbegin()const - const_reverse_iterator crbegin() const; - - //! @copydoc ::boost::intrusive::avltree::rend() - reverse_iterator rend(); - - //! @copydoc ::boost::intrusive::avltree::rend()const - const_reverse_iterator rend() const; - - //! @copydoc ::boost::intrusive::avltree::crend()const - const_reverse_iterator crend() const; - - //! @copydoc ::boost::intrusive::avltree::container_from_end_iterator(iterator) - static avl_multiset_impl &container_from_end_iterator(iterator end_iterator); - - //! @copydoc ::boost::intrusive::avltree::container_from_end_iterator(const_iterator) - static const avl_multiset_impl &container_from_end_iterator(const_iterator end_iterator); - - //! @copydoc ::boost::intrusive::avltree::container_from_iterator(iterator) - static avl_multiset_impl &container_from_iterator(iterator it); - - //! @copydoc ::boost::intrusive::avltree::container_from_iterator(const_iterator) - static const avl_multiset_impl &container_from_iterator(const_iterator it); - - //! @copydoc ::boost::intrusive::avltree::key_comp()const - key_compare key_comp() const; - - //! @copydoc ::boost::intrusive::avltree::value_comp()const - value_compare value_comp() const; - - //! @copydoc ::boost::intrusive::avltree::empty()const - bool empty() const; - - //! @copydoc ::boost::intrusive::avltree::size()const - size_type size() const; - - //! @copydoc ::boost::intrusive::avltree::swap - void swap(avl_multiset_impl& other); - - //! @copydoc ::boost::intrusive::avltree::clone_from - template - void clone_from(const avl_multiset_impl &src, Cloner cloner, Disposer disposer); - - #endif //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::avltree::insert_equal(reference) - iterator insert(reference value) - { return tree_type::insert_equal(value); } - - //! @copydoc ::boost::intrusive::avltree::insert_equal(const_iterator,reference) - iterator insert(const_iterator hint, reference value) - { return tree_type::insert_equal(hint, value); } - - //! @copydoc ::boost::intrusive::avltree::insert_equal(Iterator,Iterator) - template - void insert(Iterator b, Iterator e) - { tree_type::insert_equal(b, e); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::avltree::insert_before - iterator insert_before(const_iterator pos, reference value); - - //! @copydoc ::boost::intrusive::avltree::push_back - void push_back(reference value); - - //! @copydoc ::boost::intrusive::avltree::push_front - void push_front(reference value); - - //! @copydoc ::boost::intrusive::avltree::erase(const_iterator) - iterator erase(const_iterator i); - - //! @copydoc ::boost::intrusive::avltree::erase(const_iterator,const_iterator) - iterator erase(const_iterator b, const_iterator e); - - //! @copydoc ::boost::intrusive::avltree::erase(const_reference) - size_type erase(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::erase(const KeyType&,KeyValueCompare) - template - size_type erase(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator i, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const_iterator,const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const_reference, Disposer) - template - size_type erase_and_dispose(const_reference value, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer) - template - size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::clear - void clear(); - - //! @copydoc ::boost::intrusive::avltree::clear_and_dispose - template - void clear_and_dispose(Disposer disposer); - - //! @copydoc ::boost::intrusive::avltree::count(const_reference)const - size_type count(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::count(const KeyType&,KeyValueCompare)const - template - size_type count(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const_reference) - iterator lower_bound(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const KeyType&,KeyValueCompare) - template - iterator lower_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const_reference)const - const_iterator lower_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::lower_bound(const KeyType&,KeyValueCompare)const - template - const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const_reference) - iterator upper_bound(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const KeyType&,KeyValueCompare) - template - iterator upper_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const_reference)const - const_iterator upper_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::upper_bound(const KeyType&,KeyValueCompare)const - template - const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::find(const_reference) - iterator find(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::find(const KeyType&,KeyValueCompare) - template - iterator find(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::find(const_reference)const - const_iterator find(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::find(const KeyType&,KeyValueCompare)const - template - const_iterator find(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::equal_range(const_reference) - std::pair equal_range(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::equal_range(const KeyType&,KeyValueCompare) - template - std::pair equal_range(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::avltree::equal_range(const_reference)const - std::pair - equal_range(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::equal_range(const KeyType&,KeyValueCompare)const - template - std::pair - equal_range(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const_reference,const_reference,bool,bool) - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool) - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const_reference,const_reference,bool,bool)const - std::pair - bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::avltree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::avltree::s_iterator_to(reference) - static iterator s_iterator_to(reference value); - - //! @copydoc ::boost::intrusive::avltree::s_iterator_to(const_reference) - static const_iterator s_iterator_to(const_reference value); - - //! @copydoc ::boost::intrusive::avltree::iterator_to(reference) - iterator iterator_to(reference value); - - //! @copydoc ::boost::intrusive::avltree::iterator_to(const_reference)const - const_iterator iterator_to(const_reference value) const; - - //! @copydoc ::boost::intrusive::avltree::init_node(reference) - static void init_node(reference value); - - //! @copydoc ::boost::intrusive::avltree::unlink_leftmost_without_rebalance - pointer unlink_leftmost_without_rebalance(); - - //! @copydoc ::boost::intrusive::avltree::replace_node - void replace_node(iterator replace_this, reference with_this); - - //! @copydoc ::boost::intrusive::avltree::remove_node - void remove_node(reference value); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED -}; - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -template -bool operator!= (const avl_multiset_impl &x, const avl_multiset_impl &y); - -template -bool operator>(const avl_multiset_impl &x, const avl_multiset_impl &y); - -template -bool operator<=(const avl_multiset_impl &x, const avl_multiset_impl &y); - -template -bool operator>=(const avl_multiset_impl &x, const avl_multiset_impl &y); - -template -void swap(avl_multiset_impl &x, avl_multiset_impl &y); - -#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -//! Helper metafunction to define a \c avl_multiset that yields to the same type when the -//! same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_avl_multiset -{ - /// @cond - typedef typename pack_options - < avltree_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3, O4 - #else - Options... - #endif - >::type packed_options; - - typedef typename detail::get_value_traits - ::type value_traits; - - typedef avl_multiset_impl - < value_traits - , typename packed_options::compare - , typename packed_options::size_type - , packed_options::constant_time_size - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - -#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class avl_multiset - : public make_avl_multiset::type -{ - typedef typename make_avl_multiset::type Base; - - BOOST_MOVABLE_BUT_NOT_COPYABLE(avl_multiset) - - public: - typedef typename Base::value_compare value_compare; - typedef typename Base::value_traits value_traits; - typedef typename Base::iterator iterator; - typedef typename Base::const_iterator const_iterator; - - //Assert if passed value traits are compatible with the type - BOOST_STATIC_ASSERT((detail::is_same::value)); - - explicit avl_multiset( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(cmp, v_traits) - {} - - template - avl_multiset( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(b, e, cmp, v_traits) - {} - - avl_multiset(BOOST_RV_REF(avl_multiset) x) - : Base(::boost::move(static_cast(x))) - {} - - avl_multiset& operator=(BOOST_RV_REF(avl_multiset) x) - { return static_cast(this->Base::operator=(::boost::move(static_cast(x)))); } - - static avl_multiset &container_from_end_iterator(iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static const avl_multiset &container_from_end_iterator(const_iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static avl_multiset &container_from_iterator(iterator it) - { return static_cast(Base::container_from_iterator(it)); } - - static const avl_multiset &container_from_iterator(const_iterator it) - { return static_cast(Base::container_from_iterator(it)); } -}; - -#endif - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_AVL_SET_HPP diff --git a/utils/boost_idb/boost/intrusive/avl_set_hook.hpp b/utils/boost_idb/boost/intrusive/avl_set_hook.hpp deleted file mode 100644 index cd0478dd..00000000 --- a/utils/boost_idb/boost/intrusive/avl_set_hook.hpp +++ /dev/null @@ -1,297 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_AVL_SET_HOOK_HPP -#define BOOST_INTRUSIVE_AVL_SET_HOOK_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond -template -struct get_avl_set_node_algo -{ - typedef avltree_algorithms > type; -}; -/// @endcond - -//! Helper metafunction to define a \c avl_set_base_hook that yields to the same -//! type when the same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_avl_set_base_hook -{ - /// @cond - typedef typename pack_options - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type packed_options; - - typedef generic_hook - < get_avl_set_node_algo - , typename packed_options::tag - , packed_options::link_mode - , AvlTreeBaseHookId - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -//! Derive a class from avl_set_base_hook in order to store objects in -//! in an avl_set/avl_multiset. avl_set_base_hook holds the data necessary to maintain -//! the avl_set/avl_multiset and provides an appropriate value_traits class for avl_set/avl_multiset. -//! -//! The hook admits the following options: \c tag<>, \c void_pointer<>, -//! \c link_mode<> and \c optimize_size<>. -//! -//! \c tag<> defines a tag to identify the node. -//! The same tag value can be used in different classes, but if a class is -//! derived from more than one \c list_base_hook, then each \c list_base_hook needs its -//! unique tag. -//! -//! \c void_pointer<> is the pointer type that will be used internally in the hook -//! and the the container configured to use this hook. -//! -//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, -//! \c auto_unlink or \c safe_link). -//! -//! \c optimize_size<> will tell the hook to optimize the hook for size instead -//! of speed. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class avl_set_base_hook - : public make_avl_set_base_hook - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type -{ - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - public: - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. - //! - //! Throws: Nothing. - avl_set_base_hook(); - - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing a copy-constructor - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - avl_set_base_hook(const avl_set_base_hook& ); - - //! Effects: Empty function. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing an assignment operator - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - avl_set_base_hook& operator=(const avl_set_base_hook& ); - - //! Effects: If link_mode is \c normal_link, the destructor does - //! nothing (ie. no code is generated). If link_mode is \c safe_link and the - //! object is stored in a set an assertion is raised. If link_mode is - //! \c auto_unlink and \c is_linked() is true, the node is unlinked. - //! - //! Throws: Nothing. - ~avl_set_base_hook(); - - //! Effects: Swapping two nodes swaps the position of the elements - //! related to those nodes in one or two containers. That is, if the node - //! this is part of the element e1, the node x is part of the element e2 - //! and both elements are included in the containers s1 and s2, then after - //! the swap-operation e1 is in s2 at the position of e2 and e2 is in s1 - //! at the position of e1. If one element is not in a container, then - //! after the swap-operation the other element is not in a container. - //! Iterators to e1 and e2 related to those nodes are invalidated. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - void swap_nodes(avl_set_base_hook &other); - - //! Precondition: link_mode must be \c safe_link or \c auto_unlink. - //! - //! Returns: true, if the node belongs to a container, false - //! otherwise. This function can be used to test whether \c set::iterator_to - //! will return a valid iterator. - //! - //! Complexity: Constant - bool is_linked() const; - - //! Effects: Removes the node if it's inserted in a container. - //! This function is only allowed if link_mode is \c auto_unlink. - //! - //! Throws: Nothing. - void unlink(); - #endif -}; - -//! Helper metafunction to define a \c avl_set_member_hook that yields to the same -//! type when the same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_avl_set_member_hook -{ - /// @cond - typedef typename pack_options - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type packed_options; - - typedef generic_hook - < get_avl_set_node_algo - , member_tag - , packed_options::link_mode - , NoBaseHookId - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -//! Put a public data member avl_set_member_hook in order to store objects of this class in -//! an avl_set/avl_multiset. avl_set_member_hook holds the data necessary for maintaining the -//! avl_set/avl_multiset and provides an appropriate value_traits class for avl_set/avl_multiset. -//! -//! The hook admits the following options: \c void_pointer<>, -//! \c link_mode<> and \c optimize_size<>. -//! -//! \c void_pointer<> is the pointer type that will be used internally in the hook -//! and the the container configured to use this hook. -//! -//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, -//! \c auto_unlink or \c safe_link). -//! -//! \c optimize_size<> will tell the hook to optimize the hook for size instead -//! of speed. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class avl_set_member_hook - : public make_avl_set_member_hook - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type -{ - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - public: - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. - //! - //! Throws: Nothing. - avl_set_member_hook(); - - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing a copy-constructor - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - avl_set_member_hook(const avl_set_member_hook& ); - - //! Effects: Empty function. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing an assignment operator - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - avl_set_member_hook& operator=(const avl_set_member_hook& ); - - //! Effects: If link_mode is \c normal_link, the destructor does - //! nothing (ie. no code is generated). If link_mode is \c safe_link and the - //! object is stored in a set an assertion is raised. If link_mode is - //! \c auto_unlink and \c is_linked() is true, the node is unlinked. - //! - //! Throws: Nothing. - ~avl_set_member_hook(); - - //! Effects: Swapping two nodes swaps the position of the elements - //! related to those nodes in one or two containers. That is, if the node - //! this is part of the element e1, the node x is part of the element e2 - //! and both elements are included in the containers s1 and s2, then after - //! the swap-operation e1 is in s2 at the position of e2 and e2 is in s1 - //! at the position of e1. If one element is not in a container, then - //! after the swap-operation the other element is not in a container. - //! Iterators to e1 and e2 related to those nodes are invalidated. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - void swap_nodes(avl_set_member_hook &other); - - //! Precondition: link_mode must be \c safe_link or \c auto_unlink. - //! - //! Returns: true, if the node belongs to a container, false - //! otherwise. This function can be used to test whether \c set::iterator_to - //! will return a valid iterator. - //! - //! Complexity: Constant - bool is_linked() const; - - //! Effects: Removes the node if it's inserted in a container. - //! This function is only allowed if link_mode is \c auto_unlink. - //! - //! Throws: Nothing. - void unlink(); - #endif -}; - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_AVL_SET_HOOK_HPP diff --git a/utils/boost_idb/boost/intrusive/avltree.hpp b/utils/boost_idb/boost/intrusive/avltree.hpp deleted file mode 100644 index f0cb9fe6..00000000 --- a/utils/boost_idb/boost/intrusive/avltree.hpp +++ /dev/null @@ -1,538 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTRUSIVE_AVLTREE_HPP -#define BOOST_INTRUSIVE_AVLTREE_HPP - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond - -struct avltree_defaults -{ - typedef detail::default_avltree_hook proto_value_traits; - static const bool constant_time_size = true; - typedef std::size_t size_type; - typedef void compare; -}; - -/// @endcond - -//! The class template avltree is an intrusive AVL tree container, that -//! is used to construct intrusive avl_set and avl_multiset containers. -//! The no-throw guarantee holds only, if the value_compare object -//! doesn't throw. -//! -//! The template parameter \c T is the type to be managed by the container. -//! The user can specify additional options and if no options are provided -//! default options are used. -//! -//! The container supports the following options: -//! \c base_hook<>/member_hook<>/value_traits<>, -//! \c constant_time_size<>, \c size_type<> and -//! \c compare<>. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -class avltree_impl - /// @cond - : public bstree_impl - /// @endcond -{ - public: - typedef ValueTraits value_traits; - /// @cond - typedef bstree_impl< ValueTraits, VoidOrKeyComp, SizeType - , ConstantTimeSize, AvlTreeAlgorithms> tree_type; - typedef tree_type implementation_defined; - /// @endcond - - typedef typename implementation_defined::pointer pointer; - typedef typename implementation_defined::const_pointer const_pointer; - typedef typename implementation_defined::value_type value_type; - typedef typename implementation_defined::key_type key_type; - typedef typename implementation_defined::reference reference; - typedef typename implementation_defined::const_reference const_reference; - typedef typename implementation_defined::difference_type difference_type; - typedef typename implementation_defined::size_type size_type; - typedef typename implementation_defined::value_compare value_compare; - typedef typename implementation_defined::key_compare key_compare; - typedef typename implementation_defined::iterator iterator; - typedef typename implementation_defined::const_iterator const_iterator; - typedef typename implementation_defined::reverse_iterator reverse_iterator; - typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; - typedef typename implementation_defined::node_traits node_traits; - typedef typename implementation_defined::node node; - typedef typename implementation_defined::node_ptr node_ptr; - typedef typename implementation_defined::const_node_ptr const_node_ptr; - typedef typename implementation_defined::node_algorithms node_algorithms; - - static const bool constant_time_size = implementation_defined::constant_time_size; - /// @cond - private: - - //noncopyable - BOOST_MOVABLE_BUT_NOT_COPYABLE(avltree_impl) - - /// @endcond - - public: - - typedef typename implementation_defined::insert_commit_data insert_commit_data; - - - //! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &) - explicit avltree_impl( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &) - template - avltree_impl( bool unique, Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(unique, b, e, cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::bstree::bstree(bstree &&) - avltree_impl(BOOST_RV_REF(avltree_impl) x) - : tree_type(::boost::move(static_cast(x))) - {} - - //! @copydoc ::boost::intrusive::bstree::operator=(bstree &&) - avltree_impl& operator=(BOOST_RV_REF(avltree_impl) x) - { return static_cast(tree_type::operator=(::boost::move(static_cast(x)))); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree::~bstree() - ~avltree_impl(); - - //! @copydoc ::boost::intrusive::bstree::begin() - iterator begin(); - - //! @copydoc ::boost::intrusive::bstree::begin()const - const_iterator begin() const; - - //! @copydoc ::boost::intrusive::bstree::cbegin()const - const_iterator cbegin() const; - - //! @copydoc ::boost::intrusive::bstree::end() - iterator end(); - - //! @copydoc ::boost::intrusive::bstree::end()const - const_iterator end() const; - - //! @copydoc ::boost::intrusive::bstree::cend()const - const_iterator cend() const; - - //! @copydoc ::boost::intrusive::bstree::rbegin() - reverse_iterator rbegin(); - - //! @copydoc ::boost::intrusive::bstree::rbegin()const - const_reverse_iterator rbegin() const; - - //! @copydoc ::boost::intrusive::bstree::crbegin()const - const_reverse_iterator crbegin() const; - - //! @copydoc ::boost::intrusive::bstree::rend() - reverse_iterator rend(); - - //! @copydoc ::boost::intrusive::bstree::rend()const - const_reverse_iterator rend() const; - - //! @copydoc ::boost::intrusive::bstree::crend()const - const_reverse_iterator crend() const; - - //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator) - static avltree_impl &container_from_end_iterator(iterator end_iterator); - - //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator) - static const avltree_impl &container_from_end_iterator(const_iterator end_iterator); - - //! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator) - static avltree_impl &container_from_iterator(iterator it); - - //! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator) - static const avltree_impl &container_from_iterator(const_iterator it); - - //! @copydoc ::boost::intrusive::bstree::key_comp()const - key_compare key_comp() const; - - //! @copydoc ::boost::intrusive::bstree::value_comp()const - value_compare value_comp() const; - - //! @copydoc ::boost::intrusive::bstree::empty()const - bool empty() const; - - //! @copydoc ::boost::intrusive::bstree::size()const - size_type size() const; - - //! @copydoc ::boost::intrusive::bstree::swap - void swap(avltree_impl& other); - - //! @copydoc ::boost::intrusive::bstree::clone_from - template - void clone_from(const avltree_impl &src, Cloner cloner, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::insert_equal(reference) - iterator insert_equal(reference value); - - //! @copydoc ::boost::intrusive::bstree::insert_equal(const_iterator,reference) - iterator insert_equal(const_iterator hint, reference value); - - //! @copydoc ::boost::intrusive::bstree::insert_equal(Iterator,Iterator) - template - void insert_equal(Iterator b, Iterator e); - - //! @copydoc ::boost::intrusive::bstree::insert_unique(reference) - std::pair insert_unique(reference value); - - //! @copydoc ::boost::intrusive::bstree::insert_unique(const_iterator,reference) - iterator insert_unique(const_iterator hint, reference value); - - //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const KeyType&,KeyValueCompare,insert_commit_data&) - template - std::pair insert_unique_check - (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data); - - //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const_iterator,const KeyType&,KeyValueCompare,insert_commit_data&) - template - std::pair insert_unique_check - (const_iterator hint, const KeyType &key - ,KeyValueCompare key_value_comp, insert_commit_data &commit_data); - - //! @copydoc ::boost::intrusive::bstree::insert_unique_commit - iterator insert_unique_commit(reference value, const insert_commit_data &commit_data); - - //! @copydoc ::boost::intrusive::bstree::insert_unique(Iterator,Iterator) - template - void insert_unique(Iterator b, Iterator e); - - //! @copydoc ::boost::intrusive::bstree::insert_before - iterator insert_before(const_iterator pos, reference value); - - //! @copydoc ::boost::intrusive::bstree::push_back - void push_back(reference value); - - //! @copydoc ::boost::intrusive::bstree::push_front - void push_front(reference value); - - //! @copydoc ::boost::intrusive::bstree::erase(const_iterator) - iterator erase(const_iterator i); - - //! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator) - iterator erase(const_iterator b, const_iterator e); - - //! @copydoc ::boost::intrusive::bstree::erase(const_reference) - size_type erase(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare) - template - size_type erase(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator i, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer) - template - size_type erase_and_dispose(const_reference value, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer) - template - size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::clear - void clear(); - - //! @copydoc ::boost::intrusive::bstree::clear_and_dispose - template - void clear_and_dispose(Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::count(const_reference)const - size_type count(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const - template - size_type count(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference) - iterator lower_bound(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare) - template - iterator lower_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const - const_iterator lower_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const - template - const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference) - iterator upper_bound(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare) - template - iterator upper_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const - const_iterator upper_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const - template - const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::find(const_reference) - iterator find(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare) - template - iterator find(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::find(const_reference)const - const_iterator find(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const - template - const_iterator find(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference) - std::pair equal_range(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare) - template - std::pair equal_range(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)const - std::pair - equal_range(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)const - template - std::pair - equal_range(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool) - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool) - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const - std::pair - bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference) - static iterator s_iterator_to(reference value); - - //! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference) - static const_iterator s_iterator_to(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::iterator_to(reference) - iterator iterator_to(reference value); - - //! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const - const_iterator iterator_to(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::init_node(reference) - static void init_node(reference value); - - //! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance - pointer unlink_leftmost_without_rebalance(); - - //! @copydoc ::boost::intrusive::bstree::replace_node - void replace_node(iterator replace_this, reference with_this); - - //! @copydoc ::boost::intrusive::bstree::remove_node - void remove_node(reference value); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED -}; - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -template -bool operator< (const avltree_impl &x, const avltree_impl &y); - -template -bool operator==(const avltree_impl &x, const avltree_impl &y); - -template -bool operator!= (const avltree_impl &x, const avltree_impl &y); - -template -bool operator>(const avltree_impl &x, const avltree_impl &y); - -template -bool operator<=(const avltree_impl &x, const avltree_impl &y); - -template -bool operator>=(const avltree_impl &x, const avltree_impl &y); - -template -void swap(avltree_impl &x, avltree_impl &y); - -#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -//! Helper metafunction to define a \c avltree that yields to the same type when the -//! same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_avltree -{ - /// @cond - typedef typename pack_options - < avltree_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3, O4 - #else - Options... - #endif - >::type packed_options; - - typedef typename detail::get_value_traits - ::type value_traits; - - typedef avltree_impl - < value_traits - , typename packed_options::compare - , typename packed_options::size_type - , packed_options::constant_time_size - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - - -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - -#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class avltree - : public make_avltree::type -{ - typedef typename make_avltree - ::type Base; - BOOST_MOVABLE_BUT_NOT_COPYABLE(avltree) - - public: - typedef typename Base::value_compare value_compare; - typedef typename Base::value_traits value_traits; - typedef typename Base::real_value_traits real_value_traits; - typedef typename Base::iterator iterator; - typedef typename Base::const_iterator const_iterator; - typedef typename Base::reverse_iterator reverse_iterator; - typedef typename Base::const_reverse_iterator const_reverse_iterator; - - //Assert if passed value traits are compatible with the type - BOOST_STATIC_ASSERT((detail::is_same::value)); - - explicit avltree( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(cmp, v_traits) - {} - - template - avltree( bool unique, Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(unique, b, e, cmp, v_traits) - {} - - avltree(BOOST_RV_REF(avltree) x) - : Base(::boost::move(static_cast(x))) - {} - - avltree& operator=(BOOST_RV_REF(avltree) x) - { return static_cast(this->Base::operator=(::boost::move(static_cast(x)))); } - - static avltree &container_from_end_iterator(iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static const avltree &container_from_end_iterator(const_iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static avltree &container_from_iterator(iterator it) - { return static_cast(Base::container_from_iterator(it)); } - - static const avltree &container_from_iterator(const_iterator it) - { return static_cast(Base::container_from_iterator(it)); } -}; - -#endif - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_AVLTREE_HPP diff --git a/utils/boost_idb/boost/intrusive/avltree_algorithms.hpp b/utils/boost_idb/boost/intrusive/avltree_algorithms.hpp deleted file mode 100644 index 1dc2acf8..00000000 --- a/utils/boost_idb/boost/intrusive/avltree_algorithms.hpp +++ /dev/null @@ -1,591 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Daniel K. O. 2005. -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_AVLTREE_ALGORITHMS_HPP -#define BOOST_INTRUSIVE_AVLTREE_ALGORITHMS_HPP - -#include - -#include -#include - -#include -#include -#include -#include - - -namespace boost { -namespace intrusive { - -/// @cond - -template -struct avltree_node_cloner - : private detail::ebo_functor_holder -{ - typedef typename NodeTraits::node_ptr node_ptr; - typedef detail::ebo_functor_holder base_t; - - avltree_node_cloner(F f) - : base_t(f) - {} - - node_ptr operator()(const node_ptr & p) - { - node_ptr n = base_t::get()(p); - NodeTraits::set_balance(n, NodeTraits::get_balance(p)); - return n; - } -}; - -template -struct avltree_erase_fixup -{ - typedef typename NodeTraits::node_ptr node_ptr; - - void operator()(const node_ptr & to_erase, const node_ptr & successor) - { NodeTraits::set_balance(successor, NodeTraits::get_balance(to_erase)); } -}; - -/// @endcond - -//! avltree_algorithms is configured with a NodeTraits class, which encapsulates the -//! information about the node to be manipulated. NodeTraits must support the -//! following interface: -//! -//! Typedefs: -//! -//! node: The type of the node that forms the binary search tree -//! -//! node_ptr: A pointer to a node -//! -//! const_node_ptr: A pointer to a const node -//! -//! balance: The type of the balance factor -//! -//! Static functions: -//! -//! static node_ptr get_parent(const_node_ptr n); -//! -//! static void set_parent(node_ptr n, node_ptr parent); -//! -//! static node_ptr get_left(const_node_ptr n); -//! -//! static void set_left(node_ptr n, node_ptr left); -//! -//! static node_ptr get_right(const_node_ptr n); -//! -//! static void set_right(node_ptr n, node_ptr right); -//! -//! static balance get_balance(const_node_ptr n); -//! -//! static void set_balance(node_ptr n, balance b); -//! -//! static balance negative(); -//! -//! static balance zero(); -//! -//! static balance positive(); -template -class avltree_algorithms - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - : public bstree_algorithms - #endif -{ - public: - typedef typename NodeTraits::node node; - typedef NodeTraits node_traits; - typedef typename NodeTraits::node_ptr node_ptr; - typedef typename NodeTraits::const_node_ptr const_node_ptr; - typedef typename NodeTraits::balance balance; - - /// @cond - private: - typedef bstree_algorithms bstree_algo; - - /// @endcond - - public: - //! This type is the information that will be - //! filled by insert_unique_check - typedef typename bstree_algo::insert_commit_data insert_commit_data; - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree_algorithms::get_header(const const_node_ptr&) - static node_ptr get_header(const const_node_ptr & n); - - //! @copydoc ::boost::intrusive::bstree_algorithms::begin_node - static node_ptr begin_node(const const_node_ptr & header); - - //! @copydoc ::boost::intrusive::bstree_algorithms::end_node - static node_ptr end_node(const const_node_ptr & header); - - //! @copydoc ::boost::intrusive::bstree_algorithms::swap_tree - static void swap_tree(const node_ptr & header1, const node_ptr & header2); - - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree_algorithms::swap_nodes(const node_ptr&,const node_ptr&) - static void swap_nodes(const node_ptr & node1, const node_ptr & node2) - { - if(node1 == node2) - return; - - node_ptr header1(bstree_algo::get_header(node1)), header2(bstree_algo::get_header(node2)); - swap_nodes(node1, header1, node2, header2); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::swap_nodes(const node_ptr&,const node_ptr&,const node_ptr&,const node_ptr&) - static void swap_nodes(const node_ptr & node1, const node_ptr & header1, const node_ptr & node2, const node_ptr & header2) - { - if(node1 == node2) return; - - bstree_algo::swap_nodes(node1, header1, node2, header2); - //Swap balance - balance c = NodeTraits::get_balance(node1); - NodeTraits::set_balance(node1, NodeTraits::get_balance(node2)); - NodeTraits::set_balance(node2, c); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::replace_node(const node_ptr&,const node_ptr&) - static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & new_node) - { - if(node_to_be_replaced == new_node) - return; - replace_node(node_to_be_replaced, bstree_algo::get_header(node_to_be_replaced), new_node); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::replace_node(const node_ptr&,const node_ptr&,const node_ptr&) - static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & header, const node_ptr & new_node) - { - bstree_algo::replace_node(node_to_be_replaced, header, new_node); - NodeTraits::set_balance(new_node, NodeTraits::get_balance(node_to_be_replaced)); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::unlink(const node_ptr&) - static void unlink(const node_ptr & node) - { - node_ptr x = NodeTraits::get_parent(node); - if(x){ - while(!is_header(x)) - x = NodeTraits::get_parent(x); - erase(x, node); - } - } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree_algorithms::unlink_leftmost_without_rebalance - static node_ptr unlink_leftmost_without_rebalance(const node_ptr & header); - - //! @copydoc ::boost::intrusive::bstree_algorithms::unique(const const_node_ptr&) - static bool unique(const const_node_ptr & node); - - //! @copydoc ::boost::intrusive::bstree_algorithms::size(const const_node_ptr&) - static std::size_t size(const const_node_ptr & header); - - //! @copydoc ::boost::intrusive::bstree_algorithms::next_node(const node_ptr&) - static node_ptr next_node(const node_ptr & node); - - //! @copydoc ::boost::intrusive::bstree_algorithms::prev_node(const node_ptr&) - static node_ptr prev_node(const node_ptr & node); - - //! @copydoc ::boost::intrusive::bstree_algorithms::init(const node_ptr&) - static void init(const node_ptr & node); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! Requires: node must not be part of any tree. - //! - //! Effects: Initializes the header to represent an empty tree. - //! unique(header) == true. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Nodes: If node is inserted in a tree, this function corrupts the tree. - static void init_header(const node_ptr & header) - { - bstree_algo::init_header(header); - NodeTraits::set_balance(header, NodeTraits::zero()); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::erase(const node_ptr&,const node_ptr&) - static node_ptr erase(const node_ptr & header, const node_ptr & z) - { - typename bstree_algo::data_for_rebalance info; - bstree_algo::erase(header, z, avltree_erase_fixup(), info); - //Rebalance avltree - rebalance_after_erasure(header, info.x, info.x_parent); - return z; - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::clone(const const_node_ptr&,const node_ptr&,Cloner,Disposer) - template - static void clone - (const const_node_ptr & source_header, const node_ptr & target_header, Cloner cloner, Disposer disposer) - { - avltree_node_cloner new_cloner(cloner); - bstree_algo::clone(source_header, target_header, new_cloner, disposer); - } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree_algorithms::clear_and_dispose(const node_ptr&,Disposer) - template - static void clear_and_dispose(const node_ptr & header, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare) - template - static node_ptr lower_bound - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp); - - //! @copydoc ::boost::intrusive::bstree_algorithms::upper_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare) - template - static node_ptr upper_bound - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp); - - //! @copydoc ::boost::intrusive::bstree_algorithms::find(const const_node_ptr&,const KeyType&,KeyNodePtrCompare) - template - static node_ptr find - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp); - - //! @copydoc ::boost::intrusive::bstree_algorithms::equal_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare) - template - static std::pair equal_range - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp); - - //! @copydoc ::boost::intrusive::bstree_algorithms::bounded_range(const const_node_ptr&,const KeyType&,const KeyType&,KeyNodePtrCompare,bool,bool) - template - static std::pair bounded_range - (const const_node_ptr & header, const KeyType &lower_key, const KeyType &upper_key, KeyNodePtrCompare comp - , bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree_algorithms::count(const const_node_ptr&,const KeyType&,KeyNodePtrCompare) - template - static std::size_t count(const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal_upper_bound(const node_ptr&,const node_ptr&,NodePtrCompare) - template - static node_ptr insert_equal_upper_bound - (const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp) - { - bstree_algo::insert_equal_upper_bound(h, new_node, comp); - rebalance_after_insertion(h, new_node); - return new_node; - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal_lower_bound(const node_ptr&,const node_ptr&,NodePtrCompare) - template - static node_ptr insert_equal_lower_bound - (const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp) - { - bstree_algo::insert_equal_lower_bound(h, new_node, comp); - rebalance_after_insertion(h, new_node); - return new_node; - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal(const node_ptr&,const node_ptr&,const node_ptr&,NodePtrCompare) - template - static node_ptr insert_equal - (const node_ptr & header, const node_ptr & hint, const node_ptr & new_node, NodePtrCompare comp) - { - bstree_algo::insert_equal(header, hint, new_node, comp); - rebalance_after_insertion(header, new_node); - return new_node; - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_before(const node_ptr&,const node_ptr&,const node_ptr&) - static node_ptr insert_before - (const node_ptr & header, const node_ptr & pos, const node_ptr & new_node) - { - bstree_algo::insert_before(header, pos, new_node); - rebalance_after_insertion(header, new_node); - return new_node; - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::push_back(const node_ptr&,const node_ptr&) - static void push_back(const node_ptr & header, const node_ptr & new_node) - { - bstree_algo::push_back(header, new_node); - rebalance_after_insertion(header, new_node); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::push_front(const node_ptr&,const node_ptr&) - static void push_front(const node_ptr & header, const node_ptr & new_node) - { - bstree_algo::push_front(header, new_node); - rebalance_after_insertion(header, new_node); - } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_check(const const_node_ptr&,const KeyType&,KeyNodePtrCompare,insert_commit_data&) - template - static std::pair insert_unique_check - (const const_node_ptr & header, const KeyType &key - ,KeyNodePtrCompare comp, insert_commit_data &commit_data); - - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_check(const const_node_ptr&,const node_ptr&,const KeyType&,KeyNodePtrCompare,insert_commit_data&) - template - static std::pair insert_unique_check - (const const_node_ptr & header, const node_ptr &hint, const KeyType &key - ,KeyNodePtrCompare comp, insert_commit_data &commit_data); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_commit(const node_ptr&,const node_ptr&,const insert_commit_data &) - static void insert_unique_commit - (const node_ptr & header, const node_ptr & new_value, const insert_commit_data &commit_data) - { - bstree_algo::insert_unique_commit(header, new_value, commit_data); - rebalance_after_insertion(header, new_value); - } - - //! @copydoc ::boost::intrusive::bstree_algorithms::is_header - static bool is_header(const const_node_ptr & p) - { return NodeTraits::get_balance(p) == NodeTraits::zero() && bstree_algo::is_header(p); } - - - /// @cond - private: - - static void rebalance_after_erasure(const node_ptr & header, const node_ptr & xnode, const node_ptr & xnode_parent) - { - node_ptr x(xnode), x_parent(xnode_parent); - for (node_ptr root = NodeTraits::get_parent(header); x != root; root = NodeTraits::get_parent(header)) { - const balance x_parent_balance = NodeTraits::get_balance(x_parent); - if(x_parent_balance == NodeTraits::zero()){ - NodeTraits::set_balance(x_parent, - (x == NodeTraits::get_right(x_parent) ? NodeTraits::negative() : NodeTraits::positive())); - break; // the height didn't change, let's stop here - } - else if(x_parent_balance == NodeTraits::negative()){ - if (x == NodeTraits::get_left(x_parent)) { - NodeTraits::set_balance(x_parent, NodeTraits::zero()); // balanced - x = x_parent; - x_parent = NodeTraits::get_parent(x_parent); - } - else { - // x is right child - // a is left child - node_ptr a = NodeTraits::get_left(x_parent); - BOOST_INTRUSIVE_INVARIANT_ASSERT(a); - if (NodeTraits::get_balance(a) == NodeTraits::positive()) { - // a MUST have a right child - BOOST_INTRUSIVE_INVARIANT_ASSERT(NodeTraits::get_right(a)); - rotate_left_right(x_parent, header); - x = NodeTraits::get_parent(x_parent); - x_parent = NodeTraits::get_parent(x); - } - else { - rotate_right(x_parent, header); - x = NodeTraits::get_parent(x_parent); - x_parent = NodeTraits::get_parent(x); - } - - // if changed from negative to NodeTraits::positive(), no need to check above - if (NodeTraits::get_balance(x) == NodeTraits::positive()){ - break; - } - } - } - else if(x_parent_balance == NodeTraits::positive()){ - if (x == NodeTraits::get_right(x_parent)) { - NodeTraits::set_balance(x_parent, NodeTraits::zero()); // balanced - x = x_parent; - x_parent = NodeTraits::get_parent(x_parent); - } - else { - // x is left child - // a is right child - node_ptr a = NodeTraits::get_right(x_parent); - BOOST_INTRUSIVE_INVARIANT_ASSERT(a); - if (NodeTraits::get_balance(a) == NodeTraits::negative()) { - // a MUST have then a left child - BOOST_INTRUSIVE_INVARIANT_ASSERT(NodeTraits::get_left(a)); - rotate_right_left(x_parent, header); - - x = NodeTraits::get_parent(x_parent); - x_parent = NodeTraits::get_parent(x); - } - else { - rotate_left(x_parent, header); - x = NodeTraits::get_parent(x_parent); - x_parent = NodeTraits::get_parent(x); - } - // if changed from NodeTraits::positive() to negative, no need to check above - if (NodeTraits::get_balance(x) == NodeTraits::negative()){ - break; - } - } - } - else{ - BOOST_INTRUSIVE_INVARIANT_ASSERT(false); // never reached - } - } - } - - static void rebalance_after_insertion(const node_ptr & header, const node_ptr & xnode) - { - node_ptr x(xnode); - NodeTraits::set_balance(x, NodeTraits::zero()); - // Rebalance. - for(node_ptr root = NodeTraits::get_parent(header); x != root; root = NodeTraits::get_parent(header)){ - const balance x_parent_balance = NodeTraits::get_balance(NodeTraits::get_parent(x)); - - if(x_parent_balance == NodeTraits::zero()){ - // if x is left, parent will have parent->bal_factor = negative - // else, parent->bal_factor = NodeTraits::positive() - NodeTraits::set_balance( NodeTraits::get_parent(x) - , x == NodeTraits::get_left(NodeTraits::get_parent(x)) - ? NodeTraits::negative() : NodeTraits::positive() ); - x = NodeTraits::get_parent(x); - } - else if(x_parent_balance == NodeTraits::positive()){ - // if x is a left child, parent->bal_factor = zero - if (x == NodeTraits::get_left(NodeTraits::get_parent(x))) - NodeTraits::set_balance(NodeTraits::get_parent(x), NodeTraits::zero()); - else{ // x is a right child, needs rebalancing - if (NodeTraits::get_balance(x) == NodeTraits::negative()) - rotate_right_left(NodeTraits::get_parent(x), header); - else - rotate_left(NodeTraits::get_parent(x), header); - } - break; - } - else if(x_parent_balance == NodeTraits::negative()){ - // if x is a left child, needs rebalancing - if (x == NodeTraits::get_left(NodeTraits::get_parent(x))) { - if (NodeTraits::get_balance(x) == NodeTraits::positive()) - rotate_left_right(NodeTraits::get_parent(x), header); - else - rotate_right(NodeTraits::get_parent(x), header); - } - else - NodeTraits::set_balance(NodeTraits::get_parent(x), NodeTraits::zero()); - break; - } - else{ - BOOST_INTRUSIVE_INVARIANT_ASSERT(false); // never reached - } - } - } - - static void left_right_balancing(const node_ptr & a, const node_ptr & b, const node_ptr & c) - { - // balancing... - const balance c_balance = NodeTraits::get_balance(c); - const balance zero_balance = NodeTraits::zero(); - NodeTraits::set_balance(c, zero_balance); - if(c_balance == NodeTraits::negative()){ - NodeTraits::set_balance(a, NodeTraits::positive()); - NodeTraits::set_balance(b, zero_balance); - } - else if(c_balance == zero_balance){ - NodeTraits::set_balance(a, zero_balance); - NodeTraits::set_balance(b, zero_balance); - } - else if(c_balance == NodeTraits::positive()){ - NodeTraits::set_balance(a, zero_balance); - NodeTraits::set_balance(b, NodeTraits::negative()); - } - else{ - BOOST_INTRUSIVE_INVARIANT_ASSERT(false); // never reached - } - } - - static void rotate_left_right(const node_ptr a, const node_ptr & hdr) - { - // | | // - // a(-2) c // - // / \ / \ // - // / \ ==> / \ // - // (pos)b [g] b a // - // / \ / \ / \ // - // [d] c [d] e f [g] // - // / \ // - // e f // - node_ptr b = NodeTraits::get_left(a), c = NodeTraits::get_right(b); - bstree_algo::rotate_left(b, hdr); - bstree_algo::rotate_right(a, hdr); - left_right_balancing(a, b, c); - } - - static void rotate_right_left(const node_ptr a, const node_ptr & hdr) - { - // | | // - // a(pos) c // - // / \ / \ // - // / \ / \ // - // [d] b(neg) ==> a b // - // / \ / \ / \ // - // c [g] [d] e f [g] // - // / \ // - // e f // - node_ptr b = NodeTraits::get_right(a), c = NodeTraits::get_left(b); - bstree_algo::rotate_right(b, hdr); - bstree_algo::rotate_left(a, hdr); - left_right_balancing(b, a, c); - } - - static void rotate_left(const node_ptr x, const node_ptr & hdr) - { - const node_ptr y = NodeTraits::get_right(x); - bstree_algo::rotate_left(x, hdr); - - // reset the balancing factor - if (NodeTraits::get_balance(y) == NodeTraits::positive()) { - NodeTraits::set_balance(x, NodeTraits::zero()); - NodeTraits::set_balance(y, NodeTraits::zero()); - } - else { // this doesn't happen during insertions - NodeTraits::set_balance(x, NodeTraits::positive()); - NodeTraits::set_balance(y, NodeTraits::negative()); - } - } - - static void rotate_right(const node_ptr x, const node_ptr & hdr) - { - const node_ptr y = NodeTraits::get_left(x); - bstree_algo::rotate_right(x, hdr); - - // reset the balancing factor - if (NodeTraits::get_balance(y) == NodeTraits::negative()) { - NodeTraits::set_balance(x, NodeTraits::zero()); - NodeTraits::set_balance(y, NodeTraits::zero()); - } - else { // this doesn't happen during insertions - NodeTraits::set_balance(x, NodeTraits::negative()); - NodeTraits::set_balance(y, NodeTraits::positive()); - } - } - - /// @endcond -}; - -/// @cond - -template -struct get_algo -{ - typedef avltree_algorithms type; -}; - -/// @endcond - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_AVLTREE_ALGORITHMS_HPP diff --git a/utils/boost_idb/boost/intrusive/bs_set.hpp b/utils/boost_idb/boost/intrusive/bs_set.hpp deleted file mode 100644 index 2062d493..00000000 --- a/utils/boost_idb/boost/intrusive/bs_set.hpp +++ /dev/null @@ -1,922 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2013-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTRUSIVE_BS_SET_HPP -#define BOOST_INTRUSIVE_BS_SET_HPP - -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -//! The class template bs_set is an intrusive container, that mimics most of -//! the interface of std::set as described in the C++ standard. -//! -//! The template parameter \c T is the type to be managed by the container. -//! The user can specify additional options and if no options are provided -//! default options are used. -//! -//! The container supports the following options: -//! \c base_hook<>/member_hook<>/value_traits<>, -//! \c constant_time_size<>, \c size_type<> and -//! \c compare<>. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -class bs_set_impl -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - : public bstree_impl -#endif -{ - /// @cond - typedef bstree_impl tree_type; - BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_set_impl) - - typedef tree_type implementation_defined; - /// @endcond - - public: - typedef typename implementation_defined::value_type value_type; - typedef typename implementation_defined::value_traits value_traits; - typedef typename implementation_defined::pointer pointer; - typedef typename implementation_defined::const_pointer const_pointer; - typedef typename implementation_defined::reference reference; - typedef typename implementation_defined::const_reference const_reference; - typedef typename implementation_defined::difference_type difference_type; - typedef typename implementation_defined::size_type size_type; - typedef typename implementation_defined::value_compare value_compare; - typedef typename implementation_defined::key_compare key_compare; - typedef typename implementation_defined::iterator iterator; - typedef typename implementation_defined::const_iterator const_iterator; - typedef typename implementation_defined::reverse_iterator reverse_iterator; - typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; - typedef typename implementation_defined::insert_commit_data insert_commit_data; - typedef typename implementation_defined::node_traits node_traits; - typedef typename implementation_defined::node node; - typedef typename implementation_defined::node_ptr node_ptr; - typedef typename implementation_defined::const_node_ptr const_node_ptr; - typedef typename implementation_defined::node_algorithms node_algorithms; - - static const bool constant_time_size = tree_type::constant_time_size; - - public: - //! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &) - explicit bs_set_impl( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &) - template - bs_set_impl( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(true, b, e, cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::bstree::bstree(bstree &&) - bs_set_impl(BOOST_RV_REF(bs_set_impl) x) - : tree_type(::boost::move(static_cast(x))) - {} - - //! @copydoc ::boost::intrusive::bstree::operator=(bstree &&) - bs_set_impl& operator=(BOOST_RV_REF(bs_set_impl) x) - { return static_cast(tree_type::operator=(::boost::move(static_cast(x)))); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree::~bstree() - ~bs_set_impl(); - - //! @copydoc ::boost::intrusive::bstree::begin() - iterator begin(); - - //! @copydoc ::boost::intrusive::bstree::begin()const - const_iterator begin() const; - - //! @copydoc ::boost::intrusive::bstree::cbegin()const - const_iterator cbegin() const; - - //! @copydoc ::boost::intrusive::bstree::end() - iterator end(); - - //! @copydoc ::boost::intrusive::bstree::end()const - const_iterator end() const; - - //! @copydoc ::boost::intrusive::bstree::cend()const - const_iterator cend() const; - - //! @copydoc ::boost::intrusive::bstree::rbegin() - reverse_iterator rbegin(); - - //! @copydoc ::boost::intrusive::bstree::rbegin()const - const_reverse_iterator rbegin() const; - - //! @copydoc ::boost::intrusive::bstree::crbegin()const - const_reverse_iterator crbegin() const; - - //! @copydoc ::boost::intrusive::bstree::rend() - reverse_iterator rend(); - - //! @copydoc ::boost::intrusive::bstree::rend()const - const_reverse_iterator rend() const; - - //! @copydoc ::boost::intrusive::bstree::crend()const - const_reverse_iterator crend() const; - - //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator) - static bs_set_impl &container_from_end_iterator(iterator end_iterator); - - //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator) - static const bs_set_impl &container_from_end_iterator(const_iterator end_iterator); - - //! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator) - static bs_set_impl &container_from_iterator(iterator it); - - //! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator) - static const bs_set_impl &container_from_iterator(const_iterator it); - - //! @copydoc ::boost::intrusive::bstree::key_comp()const - key_compare key_comp() const; - - //! @copydoc ::boost::intrusive::bstree::value_comp()const - value_compare value_comp() const; - - //! @copydoc ::boost::intrusive::bstree::empty()const - bool empty() const; - - //! @copydoc ::boost::intrusive::bstree::size()const - size_type size() const; - - //! @copydoc ::boost::intrusive::bstree::swap - void swap(bs_set_impl& other); - - //! @copydoc ::boost::intrusive::bstree::clone_from - template - void clone_from(const bs_set_impl &src, Cloner cloner, Disposer disposer); - - #endif //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree::insert_unique(reference) - std::pair insert(reference value) - { return tree_type::insert_unique(value); } - - //! @copydoc ::boost::intrusive::bstree::insert_unique(const_iterator,reference) - iterator insert(const_iterator hint, reference value) - { return tree_type::insert_unique(hint, value); } - - //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const KeyType&,KeyValueCompare,insert_commit_data&) - template - std::pair insert_check - (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data) - { return tree_type::insert_unique_check(key, key_value_comp, commit_data); } - - //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const_iterator,const KeyType&,KeyValueCompare,insert_commit_data&) - template - std::pair insert_check - (const_iterator hint, const KeyType &key - ,KeyValueCompare key_value_comp, insert_commit_data &commit_data) - { return tree_type::insert_unique_check(hint, key, key_value_comp, commit_data); } - - //! @copydoc ::boost::intrusive::bstree::insert_unique(Iterator,Iterator) - template - void insert(Iterator b, Iterator e) - { tree_type::insert_unique(b, e); } - - //! @copydoc ::boost::intrusive::bstree::insert_unique_commit - iterator insert_commit(reference value, const insert_commit_data &commit_data) - { return tree_type::insert_unique_commit(value, commit_data); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree::insert_before - iterator insert_before(const_iterator pos, reference value); - - //! @copydoc ::boost::intrusive::bstree::push_back - void push_back(reference value); - - //! @copydoc ::boost::intrusive::bstree::push_front - void push_front(reference value); - - //! @copydoc ::boost::intrusive::bstree::erase(const_iterator) - iterator erase(const_iterator i); - - //! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator) - iterator erase(const_iterator b, const_iterator e); - - //! @copydoc ::boost::intrusive::bstree::erase(const_reference) - size_type erase(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare) - template - size_type erase(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator i, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer) - template - size_type erase_and_dispose(const_reference value, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer) - template - size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::clear - void clear(); - - //! @copydoc ::boost::intrusive::bstree::clear_and_dispose - template - void clear_and_dispose(Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::count(const_reference)const - size_type count(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const - template - size_type count(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference) - iterator lower_bound(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare) - template - iterator lower_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const - const_iterator lower_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const - template - const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference) - iterator upper_bound(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare) - template - iterator upper_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const - const_iterator upper_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const - template - const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::find(const_reference) - iterator find(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare) - template - iterator find(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::find(const_reference)const - const_iterator find(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const - template - const_iterator find(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference) - std::pair equal_range(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare) - template - std::pair equal_range(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)const - std::pair - equal_range(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)const - template - std::pair - equal_range(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool) - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool) - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const - std::pair - bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference) - static iterator s_iterator_to(reference value); - - //! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference) - static const_iterator s_iterator_to(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::iterator_to(reference) - iterator iterator_to(reference value); - - //! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const - const_iterator iterator_to(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::init_node(reference) - static void init_node(reference value); - - //! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance - pointer unlink_leftmost_without_rebalance(); - - //! @copydoc ::boost::intrusive::bstree::replace_node - void replace_node(iterator replace_this, reference with_this); - - //! @copydoc ::boost::intrusive::bstree::remove_node - void remove_node(reference value); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED -}; - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -template -bool operator!= (const bs_set_impl &x, const bs_set_impl &y); - -template -bool operator>(const bs_set_impl &x, const bs_set_impl &y); - -template -bool operator<=(const bs_set_impl &x, const bs_set_impl &y); - -template -bool operator>=(const bs_set_impl &x, const bs_set_impl &y); - -template -void swap(bs_set_impl &x, bs_set_impl &y); - -#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -//! Helper metafunction to define a \c bs_set that yields to the same type when the -//! same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_bs_set -{ - /// @cond - typedef typename pack_options - < bstree_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3, O4 - #else - Options... - #endif - >::type packed_options; - - typedef typename detail::get_value_traits - ::type value_traits; - - typedef bs_set_impl - < value_traits - , typename packed_options::compare - , typename packed_options::size_type - , packed_options::constant_time_size - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED -#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class bs_set - : public make_bs_set::type -{ - typedef typename make_bs_set - ::type Base; - - BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_set) - public: - typedef typename Base::value_compare value_compare; - typedef typename Base::value_traits value_traits; - typedef typename Base::iterator iterator; - typedef typename Base::const_iterator const_iterator; - - //Assert if passed value traits are compatible with the type - BOOST_STATIC_ASSERT((detail::is_same::value)); - - explicit bs_set( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(cmp, v_traits) - {} - - template - bs_set( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(b, e, cmp, v_traits) - {} - - bs_set(BOOST_RV_REF(bs_set) x) - : Base(::boost::move(static_cast(x))) - {} - - bs_set& operator=(BOOST_RV_REF(bs_set) x) - { return static_cast(this->Base::operator=(::boost::move(static_cast(x)))); } - - static bs_set &container_from_end_iterator(iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static const bs_set &container_from_end_iterator(const_iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static bs_set &container_from_iterator(iterator it) - { return static_cast(Base::container_from_iterator(it)); } - - static const bs_set &container_from_iterator(const_iterator it) - { return static_cast(Base::container_from_iterator(it)); } -}; - -#endif - -//! The class template bs_multiset is an intrusive container, that mimics most of -//! the interface of std::multiset as described in the C++ standard. -//! -//! The template parameter \c T is the type to be managed by the container. -//! The user can specify additional options and if no options are provided -//! default options are used. -//! -//! The container supports the following options: -//! \c base_hook<>/member_hook<>/value_traits<>, -//! \c constant_time_size<>, \c size_type<> and -//! \c compare<>. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -class bs_multiset_impl -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - : public bstree_impl -#endif -{ - /// @cond - typedef bstree_impl tree_type; - - BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_multiset_impl) - typedef tree_type implementation_defined; - /// @endcond - - public: - typedef typename implementation_defined::value_type value_type; - typedef typename implementation_defined::value_traits value_traits; - typedef typename implementation_defined::pointer pointer; - typedef typename implementation_defined::const_pointer const_pointer; - typedef typename implementation_defined::reference reference; - typedef typename implementation_defined::const_reference const_reference; - typedef typename implementation_defined::difference_type difference_type; - typedef typename implementation_defined::size_type size_type; - typedef typename implementation_defined::value_compare value_compare; - typedef typename implementation_defined::key_compare key_compare; - typedef typename implementation_defined::iterator iterator; - typedef typename implementation_defined::const_iterator const_iterator; - typedef typename implementation_defined::reverse_iterator reverse_iterator; - typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; - typedef typename implementation_defined::insert_commit_data insert_commit_data; - typedef typename implementation_defined::node_traits node_traits; - typedef typename implementation_defined::node node; - typedef typename implementation_defined::node_ptr node_ptr; - typedef typename implementation_defined::const_node_ptr const_node_ptr; - typedef typename implementation_defined::node_algorithms node_algorithms; - - static const bool constant_time_size = tree_type::constant_time_size; - - public: - //! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &) - explicit bs_multiset_impl( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &) - template - bs_multiset_impl( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : tree_type(false, b, e, cmp, v_traits) - {} - - //! @copydoc ::boost::intrusive::bstree::bstree(bstree &&) - bs_multiset_impl(BOOST_RV_REF(bs_multiset_impl) x) - : tree_type(::boost::move(static_cast(x))) - {} - - //! @copydoc ::boost::intrusive::bstree::operator=(bstree &&) - bs_multiset_impl& operator=(BOOST_RV_REF(bs_multiset_impl) x) - { return static_cast(tree_type::operator=(::boost::move(static_cast(x)))); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree::~bstree() - ~bs_multiset_impl(); - - //! @copydoc ::boost::intrusive::bstree::begin() - iterator begin(); - - //! @copydoc ::boost::intrusive::bstree::begin()const - const_iterator begin() const; - - //! @copydoc ::boost::intrusive::bstree::cbegin()const - const_iterator cbegin() const; - - //! @copydoc ::boost::intrusive::bstree::end() - iterator end(); - - //! @copydoc ::boost::intrusive::bstree::end()const - const_iterator end() const; - - //! @copydoc ::boost::intrusive::bstree::cend()const - const_iterator cend() const; - - //! @copydoc ::boost::intrusive::bstree::rbegin() - reverse_iterator rbegin(); - - //! @copydoc ::boost::intrusive::bstree::rbegin()const - const_reverse_iterator rbegin() const; - - //! @copydoc ::boost::intrusive::bstree::crbegin()const - const_reverse_iterator crbegin() const; - - //! @copydoc ::boost::intrusive::bstree::rend() - reverse_iterator rend(); - - //! @copydoc ::boost::intrusive::bstree::rend()const - const_reverse_iterator rend() const; - - //! @copydoc ::boost::intrusive::bstree::crend()const - const_reverse_iterator crend() const; - - //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator) - static bs_multiset_impl &container_from_end_iterator(iterator end_iterator); - - //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator) - static const bs_multiset_impl &container_from_end_iterator(const_iterator end_iterator); - - //! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator) - static bs_multiset_impl &container_from_iterator(iterator it); - - //! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator) - static const bs_multiset_impl &container_from_iterator(const_iterator it); - - //! @copydoc ::boost::intrusive::bstree::key_comp()const - key_compare key_comp() const; - - //! @copydoc ::boost::intrusive::bstree::value_comp()const - value_compare value_comp() const; - - //! @copydoc ::boost::intrusive::bstree::empty()const - bool empty() const; - - //! @copydoc ::boost::intrusive::bstree::size()const - size_type size() const; - - //! @copydoc ::boost::intrusive::bstree::swap - void swap(bs_multiset_impl& other); - - //! @copydoc ::boost::intrusive::bstree::clone_from - template - void clone_from(const bs_multiset_impl &src, Cloner cloner, Disposer disposer); - - #endif //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED - - //! @copydoc ::boost::intrusive::bstree::insert_equal(reference) - iterator insert(reference value) - { return tree_type::insert_equal(value); } - - //! @copydoc ::boost::intrusive::bstree::insert_equal(const_iterator,reference) - iterator insert(const_iterator hint, reference value) - { return tree_type::insert_equal(hint, value); } - - //! @copydoc ::boost::intrusive::bstree::insert_equal(Iterator,Iterator) - template - void insert(Iterator b, Iterator e) - { tree_type::insert_equal(b, e); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! @copydoc ::boost::intrusive::bstree::insert_before - iterator insert_before(const_iterator pos, reference value); - - //! @copydoc ::boost::intrusive::bstree::push_back - void push_back(reference value); - - //! @copydoc ::boost::intrusive::bstree::push_front - void push_front(reference value); - - //! @copydoc ::boost::intrusive::bstree::erase(const_iterator) - iterator erase(const_iterator i); - - //! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator) - iterator erase(const_iterator b, const_iterator e); - - //! @copydoc ::boost::intrusive::bstree::erase(const_reference) - size_type erase(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare) - template - size_type erase(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator i, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer) - template - iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer) - template - size_type erase_and_dispose(const_reference value, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer) - template - size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::clear - void clear(); - - //! @copydoc ::boost::intrusive::bstree::clear_and_dispose - template - void clear_and_dispose(Disposer disposer); - - //! @copydoc ::boost::intrusive::bstree::count(const_reference)const - size_type count(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const - template - size_type count(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference) - iterator lower_bound(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare) - template - iterator lower_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const - const_iterator lower_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const - template - const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference) - iterator upper_bound(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare) - template - iterator upper_bound(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const - const_iterator upper_bound(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const - template - const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::find(const_reference) - iterator find(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare) - template - iterator find(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::find(const_reference)const - const_iterator find(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const - template - const_iterator find(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference) - std::pair equal_range(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare) - template - std::pair equal_range(const KeyType& key, KeyValueCompare comp); - - //! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)const - std::pair - equal_range(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)const - template - std::pair - equal_range(const KeyType& key, KeyValueCompare comp) const; - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool) - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool) - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed); - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const - std::pair - bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const - template - std::pair bounded_range - (const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const; - - //! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference) - static iterator s_iterator_to(reference value); - - //! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference) - static const_iterator s_iterator_to(const_reference value); - - //! @copydoc ::boost::intrusive::bstree::iterator_to(reference) - iterator iterator_to(reference value); - - //! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const - const_iterator iterator_to(const_reference value) const; - - //! @copydoc ::boost::intrusive::bstree::init_node(reference) - static void init_node(reference value); - - //! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance - pointer unlink_leftmost_without_rebalance(); - - //! @copydoc ::boost::intrusive::bstree::replace_node - void replace_node(iterator replace_this, reference with_this); - - //! @copydoc ::boost::intrusive::bstree::remove_node - void remove_node(reference value); - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED -}; - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -template -bool operator!= (const bs_multiset_impl &x, const bs_multiset_impl &y); - -template -bool operator>(const bs_multiset_impl &x, const bs_multiset_impl &y); - -template -bool operator<=(const bs_multiset_impl &x, const bs_multiset_impl &y); - -template -bool operator>=(const bs_multiset_impl &x, const bs_multiset_impl &y); - -template -void swap(bs_multiset_impl &x, bs_multiset_impl &y); - -#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - -//! Helper metafunction to define a \c bs_multiset that yields to the same type when the -//! same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_bs_multiset -{ - /// @cond - typedef typename pack_options - < bstree_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3, O4 - #else - Options... - #endif - >::type packed_options; - - typedef typename detail::get_value_traits - ::type value_traits; - - typedef bs_multiset_impl - < value_traits - , typename packed_options::compare - , typename packed_options::size_type - , packed_options::constant_time_size - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - -#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class bs_multiset - : public make_bs_multiset::type -{ - typedef typename make_bs_multiset::type Base; - - BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_multiset) - - public: - typedef typename Base::value_compare value_compare; - typedef typename Base::value_traits value_traits; - typedef typename Base::iterator iterator; - typedef typename Base::const_iterator const_iterator; - - //Assert if passed value traits are compatible with the type - BOOST_STATIC_ASSERT((detail::is_same::value)); - - explicit bs_multiset( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(cmp, v_traits) - {} - - template - bs_multiset( Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(b, e, cmp, v_traits) - {} - - bs_multiset(BOOST_RV_REF(bs_multiset) x) - : Base(::boost::move(static_cast(x))) - {} - - bs_multiset& operator=(BOOST_RV_REF(bs_multiset) x) - { return static_cast(this->Base::operator=(::boost::move(static_cast(x)))); } - - static bs_multiset &container_from_end_iterator(iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static const bs_multiset &container_from_end_iterator(const_iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static bs_multiset &container_from_iterator(iterator it) - { return static_cast(Base::container_from_iterator(it)); } - - static const bs_multiset &container_from_iterator(const_iterator it) - { return static_cast(Base::container_from_iterator(it)); } -}; - -#endif - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_BS_SET_HPP diff --git a/utils/boost_idb/boost/intrusive/bs_set_hook.hpp b/utils/boost_idb/boost/intrusive/bs_set_hook.hpp deleted file mode 100644 index 1f169718..00000000 --- a/utils/boost_idb/boost/intrusive/bs_set_hook.hpp +++ /dev/null @@ -1,290 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_BS_SET_HOOK_HPP -#define BOOST_INTRUSIVE_BS_SET_HOOK_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond -template -struct get_bs_set_node_algo -{ - typedef bstree_algorithms > type; -}; -/// @endcond - -//! Helper metafunction to define a \c bs_set_base_hook that yields to the same -//! type when the same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_bs_set_base_hook -{ - /// @cond - typedef typename pack_options - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - < hook_defaults, O1, O2, O3> - #else - < hook_defaults, Options...> - #endif - ::type packed_options; - - typedef generic_hook - < get_bs_set_node_algo - , typename packed_options::tag - , packed_options::link_mode - , BsTreeBaseHookId - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -//! Derive a class from bs_set_base_hook in order to store objects in -//! in a bs_set/bs_multiset. bs_set_base_hook holds the data necessary to maintain -//! the bs_set/bs_multiset and provides an appropriate value_traits class for bs_set/bs_multiset. -//! -//! The hook admits the following options: \c tag<>, \c void_pointer<>, -//! \c link_mode<>. -//! -//! \c tag<> defines a tag to identify the node. -//! The same tag value can be used in different classes, but if a class is -//! derived from more than one \c list_base_hook, then each \c list_base_hook needs its -//! unique tag. -//! -//! \c void_pointer<> is the pointer type that will be used internally in the hook -//! and the the container configured to use this hook. -//! -//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, -//! \c auto_unlink or \c safe_link). -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class bs_set_base_hook - : public make_bs_set_base_hook - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type - -{ - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - public: - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. - //! - //! Throws: Nothing. - bs_set_base_hook(); - - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing a copy-constructor - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - bs_set_base_hook(const bs_set_base_hook& ); - - //! Effects: Empty function. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing an assignment operator - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - bs_set_base_hook& operator=(const bs_set_base_hook& ); - - //! Effects: If link_mode is \c normal_link, the destructor does - //! nothing (ie. no code is generated). If link_mode is \c safe_link and the - //! object is stored in a set an assertion is raised. If link_mode is - //! \c auto_unlink and \c is_linked() is true, the node is unlinked. - //! - //! Throws: Nothing. - ~bs_set_base_hook(); - - //! Effects: Swapping two nodes swaps the position of the elements - //! related to those nodes in one or two containers. That is, if the node - //! this is part of the element e1, the node x is part of the element e2 - //! and both elements are included in the containers s1 and s2, then after - //! the swap-operation e1 is in s2 at the position of e2 and e2 is in s1 - //! at the position of e1. If one element is not in a container, then - //! after the swap-operation the other element is not in a container. - //! Iterators to e1 and e2 related to those nodes are invalidated. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - void swap_nodes(bs_set_base_hook &other); - - //! Precondition: link_mode must be \c safe_link or \c auto_unlink. - //! - //! Returns: true, if the node belongs to a container, false - //! otherwise. This function can be used to test whether \c set::iterator_to - //! will return a valid iterator. - //! - //! Complexity: Constant - bool is_linked() const; - - //! Effects: Removes the node if it's inserted in a container. - //! This function is only allowed if link_mode is \c auto_unlink. - //! - //! Throws: Nothing. - void unlink(); - #endif -}; - -//! Helper metafunction to define a \c bs_set_member_hook that yields to the same -//! type when the same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_bs_set_member_hook -{ - /// @cond - typedef typename pack_options - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - < hook_defaults, O1, O2, O3> - #else - < hook_defaults, Options...> - #endif - - ::type packed_options; - - typedef generic_hook - < get_bs_set_node_algo - , member_tag - , packed_options::link_mode - , NoBaseHookId - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - -//! Put a public data member bs_set_member_hook in order to store objects of this class in -//! a bs_set/bs_multiset. bs_set_member_hook holds the data necessary for maintaining the -//! bs_set/bs_multiset and provides an appropriate value_traits class for bs_set/bs_multiset. -//! -//! The hook admits the following options: \c void_pointer<>, \c link_mode<>. -//! -//! \c void_pointer<> is the pointer type that will be used internally in the hook -//! and the the container configured to use this hook. -//! -//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, -//! \c auto_unlink or \c safe_link). -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class bs_set_member_hook - : public make_bs_set_member_hook - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - - #else - - #endif - ::type -{ - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - public: - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. - //! - //! Throws: Nothing. - bs_set_member_hook(); - - //! Effects: If link_mode is \c auto_unlink or \c safe_link - //! initializes the node to an unlinked state. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing a copy-constructor - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - bs_set_member_hook(const bs_set_member_hook& ); - - //! Effects: Empty function. The argument is ignored. - //! - //! Throws: Nothing. - //! - //! Rationale: Providing an assignment operator - //! makes classes using the hook STL-compliant without forcing the - //! user to do some additional work. \c swap can be used to emulate - //! move-semantics. - bs_set_member_hook& operator=(const bs_set_member_hook& ); - - //! Effects: If link_mode is \c normal_link, the destructor does - //! nothing (ie. no code is generated). If link_mode is \c safe_link and the - //! object is stored in a set an assertion is raised. If link_mode is - //! \c auto_unlink and \c is_linked() is true, the node is unlinked. - //! - //! Throws: Nothing. - ~bs_set_member_hook(); - - //! Effects: Swapping two nodes swaps the position of the elements - //! related to those nodes in one or two containers. That is, if the node - //! this is part of the element e1, the node x is part of the element e2 - //! and both elements are included in the containers s1 and s2, then after - //! the swap-operation e1 is in s2 at the position of e2 and e2 is in s1 - //! at the position of e1. If one element is not in a container, then - //! after the swap-operation the other element is not in a container. - //! Iterators to e1 and e2 related to those nodes are invalidated. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - void swap_nodes(bs_set_member_hook &other); - - //! Precondition: link_mode must be \c safe_link or \c auto_unlink. - //! - //! Returns: true, if the node belongs to a container, false - //! otherwise. This function can be used to test whether \c set::iterator_to - //! will return a valid iterator. - //! - //! Complexity: Constant - bool is_linked() const; - - //! Effects: Removes the node if it's inserted in a container. - //! This function is only allowed if link_mode is \c auto_unlink. - //! - //! Throws: Nothing. - void unlink(); - #endif -}; - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_BS_SET_HOOK_HPP diff --git a/utils/boost_idb/boost/intrusive/bstree.hpp b/utils/boost_idb/boost/intrusive/bstree.hpp deleted file mode 100644 index 32554fb5..00000000 --- a/utils/boost_idb/boost/intrusive/bstree.hpp +++ /dev/null @@ -1,2014 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2013-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_INTRUSIVE_BSTREE_HPP -#define BOOST_INTRUSIVE_BSTREE_HPP - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond - -struct bstree_defaults -{ - typedef detail::default_bstree_hook proto_value_traits; - static const bool constant_time_size = true; - typedef std::size_t size_type; - typedef void compare; - static const bool floating_point = true; //For sgtree - typedef void priority; //For treap -}; - -template -struct bstbase3 - : public detail::get_real_value_traits::type::node_traits::node - , public ValueTraits -{ - typedef ValueTraits value_traits; - typedef typename detail::get_real_value_traits::type real_value_traits; - typedef typename real_value_traits::node_traits node_traits; - typedef typename node_traits::node node_type; - typedef typename get_algo::type node_algorithms; - typedef typename node_traits::node_ptr node_ptr; - typedef typename node_traits::const_node_ptr const_node_ptr; - - bstbase3(const ValueTraits &vtraits) - : ValueTraits(vtraits) - {} - - static const bool external_value_traits = - detail::external_value_traits_bool_is_true::value; - - node_ptr header_ptr() - { return pointer_traits::pointer_to(static_cast(*this)); } - - const_node_ptr header_ptr() const - { return pointer_traits::pointer_to(static_cast(*this)); } - - const value_traits &val_traits() const - { return *this; } - - value_traits &val_traits() - { return *this; } - - const real_value_traits &get_real_value_traits(detail::bool_) const - { return *this; } - - const real_value_traits &get_real_value_traits(detail::bool_) const - { return this->val_traits().get_value_traits(*this); } - - real_value_traits &get_real_value_traits(detail::bool_) - { return *this; } - - real_value_traits &get_real_value_traits(detail::bool_) - { return this->val_traits().get_value_traits(*this); } - - const real_value_traits &get_real_value_traits() const - { return this->get_real_value_traits(detail::bool_()); } - - real_value_traits &get_real_value_traits() - { return this->get_real_value_traits(detail::bool_()); } - - typedef typename pointer_traits::template rebind_pointer::type const_real_value_traits_ptr; - - const_real_value_traits_ptr real_value_traits_ptr() const - { return pointer_traits::pointer_to(this->get_real_value_traits()); } - - - typedef tree_iterator iterator; - typedef tree_iterator const_iterator; - typedef boost::intrusive::detail::reverse_iterator reverse_iterator; - typedef boost::intrusive::detail::reverse_iterator const_reverse_iterator; - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::pointer) pointer; - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::const_pointer) const_pointer; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::element_type) value_type; - typedef BOOST_INTRUSIVE_IMPDEF(value_type) key_type; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::reference) reference; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::reference) const_reference; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::difference_type) difference_type; - static const bool safemode_or_autounlink = is_safe_autounlink::value; - static const bool stateful_value_traits = detail::is_stateful_value_traits::value; - - iterator begin() - { return iterator (node_traits::get_left(this->header_ptr()), this->real_value_traits_ptr()); } - - const_iterator begin() const - { return cbegin(); } - - const_iterator cbegin() const - { return const_iterator (node_traits::get_left(this->header_ptr()), this->real_value_traits_ptr()); } - - iterator end() - { return iterator (this->header_ptr(), this->real_value_traits_ptr()); } - - const_iterator end() const - { return cend(); } - - const_iterator cend() const - { return const_iterator (detail::uncast(this->header_ptr()), this->real_value_traits_ptr()); } - - reverse_iterator rbegin() - { return reverse_iterator(end()); } - - const_reverse_iterator rbegin() const - { return const_reverse_iterator(end()); } - - const_reverse_iterator crbegin() const - { return const_reverse_iterator(end()); } - - reverse_iterator rend() - { return reverse_iterator(begin()); } - - const_reverse_iterator rend() const - { return const_reverse_iterator(begin()); } - - const_reverse_iterator crend() const - { return const_reverse_iterator(begin()); } - - void replace_node(iterator replace_this, reference with_this) - { - node_algorithms::replace_node( get_real_value_traits().to_node_ptr(*replace_this) - , this->header_ptr() - , get_real_value_traits().to_node_ptr(with_this)); - if(safemode_or_autounlink) - node_algorithms::init(replace_this.pointed_node()); - } - - void rebalance() - { node_algorithms::rebalance(this->header_ptr()); } - - iterator rebalance_subtree(iterator root) - { return iterator(node_algorithms::rebalance_subtree(root.pointed_node()), this->real_value_traits_ptr()); } - - static iterator s_iterator_to(reference value) - { - BOOST_STATIC_ASSERT((!stateful_value_traits)); - return iterator (value_traits::to_node_ptr(value), const_real_value_traits_ptr()); - } - - static const_iterator s_iterator_to(const_reference value) - { - BOOST_STATIC_ASSERT((!stateful_value_traits)); - return const_iterator (value_traits::to_node_ptr(const_cast (value)), const_real_value_traits_ptr()); - } - - iterator iterator_to(reference value) - { return iterator (value_traits::to_node_ptr(value), this->real_value_traits_ptr()); } - - const_iterator iterator_to(const_reference value) const - { return const_iterator (value_traits::to_node_ptr(const_cast (value)), this->real_value_traits_ptr()); } - - static void init_node(reference value) - { node_algorithms::init(value_traits::to_node_ptr(value)); } - -}; - -template -struct bstbase2 - : public bstbase3 - , public detail::ebo_functor_holder::type::value_type - >::type> -{ - typedef bstbase3 treeheader_t; - typedef typename treeheader_t::real_value_traits real_value_traits; - typedef typename treeheader_t::node_algorithms node_algorithms; - typedef typename get_less - < VoidOrKeyComp, typename real_value_traits::value_type>::type value_compare; - typedef BOOST_INTRUSIVE_IMPDEF(value_compare) key_compare; - typedef typename treeheader_t::iterator iterator; - typedef typename treeheader_t::const_iterator const_iterator; - typedef typename treeheader_t::node_ptr node_ptr; - typedef typename treeheader_t::const_node_ptr const_node_ptr; - - bstbase2(const value_compare &comp, const ValueTraits &vtraits) - : treeheader_t(vtraits), detail::ebo_functor_holder(comp) - {} - - const value_compare &comp() const - { return this->get(); } - - value_compare &comp() - { return this->get(); } - - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::pointer) pointer; - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::const_pointer) const_pointer; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::element_type) value_type; - typedef BOOST_INTRUSIVE_IMPDEF(value_type) key_type; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::reference) reference; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::reference) const_reference; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::difference_type) difference_type; - typedef typename node_algorithms::insert_commit_data insert_commit_data; - - value_compare value_comp() const - { return this->comp(); } - - key_compare key_comp() const - { return this->comp(); } - - iterator lower_bound(const_reference value) - { return this->lower_bound(value, this->comp()); } - - const_iterator lower_bound(const_reference value) const - { return this->lower_bound(value, this->comp()); } - - template - iterator lower_bound(const KeyType &key, KeyValueCompare comp) - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - return iterator(node_algorithms::lower_bound - (this->header_ptr(), key, key_node_comp), this->real_value_traits_ptr()); - } - - template - const_iterator lower_bound(const KeyType &key, KeyValueCompare comp) const - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - return const_iterator(node_algorithms::lower_bound - (this->header_ptr(), key, key_node_comp), this->real_value_traits_ptr()); - } - - iterator upper_bound(const_reference value) - { return this->upper_bound(value, this->comp()); } - - template - iterator upper_bound(const KeyType &key, KeyValueCompare comp) - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - return iterator(node_algorithms::upper_bound - (this->header_ptr(), key, key_node_comp), this->real_value_traits_ptr()); - } - - const_iterator upper_bound(const_reference value) const - { return this->upper_bound(value, this->comp()); } - - template - const_iterator upper_bound(const KeyType &key, KeyValueCompare comp) const - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - return const_iterator(node_algorithms::upper_bound - (this->header_ptr(), key, key_node_comp), this->real_value_traits_ptr()); - } - - iterator find(const_reference value) - { return this->find(value, this->comp()); } - - template - iterator find(const KeyType &key, KeyValueCompare comp) - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - return iterator - (node_algorithms::find(this->header_ptr(), key, key_node_comp), this->real_value_traits_ptr()); - } - - const_iterator find(const_reference value) const - { return this->find(value, this->comp()); } - - template - const_iterator find(const KeyType &key, KeyValueCompare comp) const - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - return const_iterator - (node_algorithms::find(this->header_ptr(), key, key_node_comp), this->real_value_traits_ptr()); - } - - std::pair equal_range(const_reference value) - { return this->equal_range(value, this->comp()); } - - template - std::pair equal_range(const KeyType &key, KeyValueCompare comp) - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - std::pair ret - (node_algorithms::equal_range(this->header_ptr(), key, key_node_comp)); - return std::pair( iterator(ret.first, this->real_value_traits_ptr()) - , iterator(ret.second, this->real_value_traits_ptr())); - } - - std::pair - equal_range(const_reference value) const - { return this->equal_range(value, this->comp()); } - - template - std::pair - equal_range(const KeyType &key, KeyValueCompare comp) const - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - std::pair ret - (node_algorithms::equal_range(this->header_ptr(), key, key_node_comp)); - return std::pair( const_iterator(ret.first, this->real_value_traits_ptr()) - , const_iterator(ret.second, this->real_value_traits_ptr())); - } - - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) - { return this->bounded_range(lower_value, upper_value, this->comp(), left_closed, right_closed); } - - template - std::pair bounded_range - (const KeyType &lower_key, const KeyType &upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - std::pair ret - (node_algorithms::bounded_range - (this->header_ptr(), lower_key, upper_key, key_node_comp, left_closed, right_closed)); - return std::pair( iterator(ret.first, this->real_value_traits_ptr()) - , iterator(ret.second, this->real_value_traits_ptr())); - } - - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const - { return this->bounded_range(lower_value, upper_value, this->comp(), left_closed, right_closed); } - - template - std::pair bounded_range - (const KeyType &lower_key, const KeyType &upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const - { - detail::key_nodeptr_comp - key_node_comp(comp, &this->get_real_value_traits()); - std::pair ret - (node_algorithms::bounded_range - (this->header_ptr(), lower_key, upper_key, key_node_comp, left_closed, right_closed)); - return std::pair( const_iterator(ret.first, this->real_value_traits_ptr()) - , const_iterator(ret.second, this->real_value_traits_ptr())); - } - - template - std::pair insert_unique_check - (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data) - { - detail::key_nodeptr_comp - ocomp(key_value_comp, &this->get_real_value_traits()); - std::pair ret = - (node_algorithms::insert_unique_check - (this->header_ptr(), key, ocomp, commit_data)); - return std::pair(iterator(ret.first, this->real_value_traits_ptr()), ret.second); - } - - template - std::pair insert_unique_check - (const_iterator hint, const KeyType &key - ,KeyValueCompare key_value_comp, insert_commit_data &commit_data) - { - detail::key_nodeptr_comp - ocomp(key_value_comp, &this->get_real_value_traits()); - std::pair ret = - (node_algorithms::insert_unique_check - (this->header_ptr(), hint.pointed_node(), key, ocomp, commit_data)); - return std::pair(iterator(ret.first, this->real_value_traits_ptr()), ret.second); - } -}; - -template -struct bstbase - : public detail::size_holder - , public bstbase2 < ValueTraits, VoidOrKeyComp, AlgoType> -{ - typedef typename detail::get_real_value_traits::type real_value_traits; - typedef bstbase2< ValueTraits, VoidOrKeyComp, AlgoType> base_type; - typedef typename base_type::value_compare value_compare; - typedef BOOST_INTRUSIVE_IMPDEF(value_compare) key_compare; - typedef typename base_type::const_reference const_reference; - typedef typename base_type::reference reference; - typedef typename base_type::iterator iterator; - typedef typename base_type::const_iterator const_iterator; - typedef typename base_type::node_traits node_traits; - typedef typename get_algo - ::type algo_type; - typedef SizeType size_type; - - bstbase(const value_compare & comp, const ValueTraits &vtraits) - : base_type(comp, vtraits) - {} - - public: - typedef detail::size_holder size_traits; - - size_traits &sz_traits() - { return *this; } - - const size_traits &sz_traits() const - { return *this; } - - size_type count(const_reference value) const - { return size_type(this->count(value, this->comp())); } - - template - size_type count(const KeyType &key, KeyValueCompare comp) const - { - std::pair ret = this->equal_range(key, comp); - return size_type(std::distance(ret.first, ret.second)); - } - - bool empty() const - { - if(ConstantTimeSize){ - return !this->sz_traits().get_size(); - } - else{ - return algo_type::unique(this->header_ptr()); - } - } -}; - - -/// @endcond - -//! The class template bstree is an unbalanced intrusive binary search tree -//! container. The no-throw guarantee holds only, if the value_compare object -//! doesn't throw. -//! -//! The complexity guarantees only hold if the tree is balanced, logarithmic -//! complexity would increase to linear if the tree is totally unbalanced. -//! -//! The template parameter \c T is the type to be managed by the container. -//! The user can specify additional options and if no options are provided -//! default options are used. -//! -//! The container supports the following options: -//! \c base_hook<>/member_hook<>/value_traits<>, -//! \c constant_time_size<>, \c size_type<> and -//! \c compare<>. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -class bstree_impl - : public bstbase - , private detail::clear_on_destructor_base - < bstree_impl - , is_safe_autounlink::type::link_mode>::value - > -{ - template friend class detail::clear_on_destructor_base; - public: - typedef ValueTraits value_traits; - /// @cond - static const bool external_value_traits = - detail::external_value_traits_bool_is_true::value; - typedef typename detail::get_real_value_traits::type real_value_traits; - typedef bstbase data_type; - typedef tree_iterator iterator_type; - typedef tree_iterator const_iterator_type; - /// @endcond - - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::pointer) pointer; - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::const_pointer) const_pointer; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::element_type) value_type; - typedef BOOST_INTRUSIVE_IMPDEF(value_type) key_type; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::reference) reference; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::reference) const_reference; - typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits::difference_type) difference_type; - typedef BOOST_INTRUSIVE_IMPDEF(SizeType) size_type; - typedef BOOST_INTRUSIVE_IMPDEF(typename data_type::value_compare) value_compare; - typedef BOOST_INTRUSIVE_IMPDEF(value_compare) key_compare; - typedef BOOST_INTRUSIVE_IMPDEF(iterator_type) iterator; - typedef BOOST_INTRUSIVE_IMPDEF(const_iterator_type) const_iterator; - typedef BOOST_INTRUSIVE_IMPDEF(boost::intrusive::detail::reverse_iterator) reverse_iterator; - typedef BOOST_INTRUSIVE_IMPDEF(boost::intrusive::detail::reverse_iterator) const_reverse_iterator; - typedef BOOST_INTRUSIVE_IMPDEF(typename real_value_traits::node_traits) node_traits; - typedef BOOST_INTRUSIVE_IMPDEF(typename node_traits::node) node; - typedef BOOST_INTRUSIVE_IMPDEF(typename node_traits::node_ptr) node_ptr; - typedef BOOST_INTRUSIVE_IMPDEF(typename node_traits::const_node_ptr) const_node_ptr; - /// @cond - typedef typename get_algo::type algo_type; - /// @endcond - typedef BOOST_INTRUSIVE_IMPDEF(algo_type) node_algorithms; - - static const bool constant_time_size = ConstantTimeSize; - static const bool stateful_value_traits = detail::is_stateful_value_traits::value; - /// @cond - private: - - //noncopyable - BOOST_MOVABLE_BUT_NOT_COPYABLE(bstree_impl) - - static const bool safemode_or_autounlink = is_safe_autounlink::value; - - //Constant-time size is incompatible with auto-unlink hooks! - BOOST_STATIC_ASSERT(!(constant_time_size && ((int)real_value_traits::link_mode == (int)auto_unlink))); - - - protected: - - - /// @endcond - - public: - - typedef typename node_algorithms::insert_commit_data insert_commit_data; - - //! Effects: Constructs an empty container. - //! - //! Complexity: Constant. - //! - //! Throws: If value_traits::node_traits::node - //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) - //! or the copy constructorof the value_compare object throws. Basic guarantee. - explicit bstree_impl( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : data_type(cmp, v_traits) - { - node_algorithms::init_header(this->header_ptr()); - this->sz_traits().set_size(size_type(0)); - } - - //! Requires: Dereferencing iterator must yield an lvalue of type value_type. - //! cmp must be a comparison function that induces a strict weak ordering. - //! - //! Effects: Constructs an empty container and inserts elements from - //! [b, e). - //! - //! Complexity: Linear in N if [b, e) is already sorted using - //! comp and otherwise N * log N, where N is the distance between first and last. - //! - //! Throws: If value_traits::node_traits::node - //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) - //! or the copy constructor/operator() of the value_compare object throws. Basic guarantee. - template - bstree_impl( bool unique, Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : data_type(cmp, v_traits) - { - node_algorithms::init_header(this->header_ptr()); - this->sz_traits().set_size(size_type(0)); - if(unique) - this->insert_unique(b, e); - else - this->insert_equal(b, e); - } - - //! Effects: to-do - //! - bstree_impl(BOOST_RV_REF(bstree_impl) x) - : data_type(::boost::move(x.comp()), ::boost::move(x.val_traits())) - { - node_algorithms::init_header(this->header_ptr()); - this->sz_traits().set_size(size_type(0)); - this->swap(x); - } - - //! Effects: to-do - //! - bstree_impl& operator=(BOOST_RV_REF(bstree_impl) x) - { this->swap(x); return *this; } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - //! Effects: Detaches all elements from this. The objects in the set - //! are not deleted (i.e. no destructors are called), but the nodes according to - //! the value_traits template parameter are reinitialized and thus can be reused. - //! - //! Complexity: Linear to elements contained in *this. - //! - //! Throws: Nothing. - ~bstree_impl() - {} - - //! Effects: Returns an iterator pointing to the beginning of the container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - iterator begin(); - - //! Effects: Returns a const_iterator pointing to the beginning of the container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_iterator begin() const; - - //! Effects: Returns a const_iterator pointing to the beginning of the container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_iterator cbegin() const; - - //! Effects: Returns an iterator pointing to the end of the container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - iterator end(); - - //! Effects: Returns a const_iterator pointing to the end of the container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_iterator end() const; - - //! Effects: Returns a const_iterator pointing to the end of the container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_iterator cend() const; - - //! Effects: Returns a reverse_iterator pointing to the beginning of the - //! reversed container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - reverse_iterator rbegin(); - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_reverse_iterator rbegin() const; - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_reverse_iterator crbegin() const; - - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - reverse_iterator rend(); - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_reverse_iterator rend() const; - - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_reverse_iterator crend() const; - - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! Precondition: end_iterator must be a valid end iterator - //! of the container. - //! - //! Effects: Returns a const reference to the container associated to the end iterator - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - static bstree_impl &container_from_end_iterator(iterator end_iterator) - { - return *static_cast - (boost::intrusive::detail::to_raw_pointer(end_iterator.pointed_node())); - } - - //! Precondition: end_iterator must be a valid end const_iterator - //! of the container. - //! - //! Effects: Returns a const reference to the container associated to the iterator - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - static const bstree_impl &container_from_end_iterator(const_iterator end_iterator) - { - return *static_cast - (boost::intrusive::detail::to_raw_pointer(end_iterator.pointed_node())); - } - - //! Precondition: it must be a valid iterator - //! of the container. - //! - //! Effects: Returns a const reference to the container associated to the iterator - //! - //! Throws: Nothing. - //! - //! Complexity: Logarithmic. - static bstree_impl &container_from_iterator(iterator it) - { return container_from_end_iterator(it.end_iterator_from_it()); } - - //! Precondition: it must be a valid end const_iterator - //! of container. - //! - //! Effects: Returns a const reference to the container associated to the end iterator - //! - //! Throws: Nothing. - //! - //! Complexity: Logarithmic. - static const bstree_impl &container_from_iterator(const_iterator it) - { return container_from_end_iterator(it.end_iterator_from_it()); } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! Effects: Returns the key_compare object used by the container. - //! - //! Complexity: Constant. - //! - //! Throws: If value_compare copy-constructor throws. - key_compare key_comp() const; - - //! Effects: Returns the value_compare object used by the container. - //! - //! Complexity: Constant. - //! - //! Throws: If value_compare copy-constructor throws. - value_compare value_comp() const; - - //! Effects: Returns true if the container is empty. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - bool empty() const; - - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! Effects: Returns the number of elements stored in the container. - //! - //! Complexity: Linear to elements contained in *this - //! if constant-time size option is disabled. Constant time otherwise. - //! - //! Throws: Nothing. - size_type size() const - { - if(constant_time_size) - return this->sz_traits().get_size(); - else{ - return (size_type)node_algorithms::size(this->header_ptr()); - } - } - - //! Effects: Swaps the contents of two containers. - //! - //! Complexity: Constant. - //! - //! Throws: If the comparison functor's swap call throws. - void swap(bstree_impl& other) - { - //This can throw - using std::swap; - swap(this->comp(), this->comp()); - //These can't throw - node_algorithms::swap_tree(this->header_ptr(), node_ptr(other.header_ptr())); - if(constant_time_size){ - size_type backup = this->sz_traits().get_size(); - this->sz_traits().set_size(other.sz_traits().get_size()); - other.sz_traits().set_size(backup); - } - } - - //! Requires: Disposer::operator()(pointer) shouldn't throw. - //! Cloner should yield to nodes equivalent to the original nodes. - //! - //! Effects: Erases all the elements from *this - //! calling Disposer::operator()(pointer), clones all the - //! elements from src calling Cloner::operator()(const_reference ) - //! and inserts them on *this. Copies the predicate from the source container. - //! - //! If cloner throws, all cloned elements are unlinked and disposed - //! calling Disposer::operator()(pointer). - //! - //! Complexity: Linear to erased plus inserted elements. - //! - //! Throws: If cloner throws or predicate copy assignment throws. Basic guarantee. - template - void clone_from(const bstree_impl &src, Cloner cloner, Disposer disposer) - { - this->clear_and_dispose(disposer); - if(!src.empty()){ - detail::exception_disposer - rollback(*this, disposer); - node_algorithms::clone - (const_node_ptr(src.header_ptr()) - ,node_ptr(this->header_ptr()) - ,detail::node_cloner (cloner, &this->get_real_value_traits()) - ,detail::node_disposer(disposer, &this->get_real_value_traits())); - this->sz_traits().set_size(src.sz_traits().get_size()); - this->comp() = src.comp(); - rollback.release(); - } - } - - //! Requires: value must be an lvalue - //! - //! Effects: Inserts value into the container before the upper bound. - //! - //! Complexity: Average complexity for insert element is at - //! most logarithmic. - //! - //! Throws: If the internal value_compare ordering function throws. Strong guarantee. - //! - //! Note: Does not affect the validity of iterators and references. - //! No copy-constructors are called. - iterator insert_equal(reference value) - { - detail::key_nodeptr_comp - key_node_comp(this->comp(), &this->get_real_value_traits()); - node_ptr to_insert(this->get_real_value_traits().to_node_ptr(value)); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); - iterator ret(node_algorithms::insert_equal_upper_bound - (this->header_ptr(), to_insert, key_node_comp), this->real_value_traits_ptr()); - this->sz_traits().increment(); - return ret; - } - - //! Requires: value must be an lvalue, and "hint" must be - //! a valid iterator. - //! - //! Effects: Inserts x into the container, using "hint" as a hint to - //! where it will be inserted. If "hint" is the upper_bound - //! the insertion takes constant time (two comparisons in the worst case) - //! - //! Complexity: Logarithmic in general, but it is amortized - //! constant time if t is inserted immediately before hint. - //! - //! Throws: If the internal value_compare ordering function throws. Strong guarantee. - //! - //! Note: Does not affect the validity of iterators and references. - //! No copy-constructors are called. - iterator insert_equal(const_iterator hint, reference value) - { - detail::key_nodeptr_comp - key_node_comp(this->comp(), &this->get_real_value_traits()); - node_ptr to_insert(this->get_real_value_traits().to_node_ptr(value)); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); - iterator ret(node_algorithms::insert_equal - (this->header_ptr(), hint.pointed_node(), to_insert, key_node_comp), this->real_value_traits_ptr()); - this->sz_traits().increment(); - return ret; - } - - //! Requires: Dereferencing iterator must yield an lvalue - //! of type value_type. - //! - //! Effects: Inserts a each element of a range into the container - //! before the upper bound of the key of each element. - //! - //! Complexity: Insert range is in general O(N * log(N)), where N is the - //! size of the range. However, it is linear in N if the range is already sorted - //! by value_comp(). - //! - //! Throws: Nothing. - //! - //! Note: Does not affect the validity of iterators and references. - //! No copy-constructors are called. - template - void insert_equal(Iterator b, Iterator e) - { - iterator iend(this->end()); - for (; b != e; ++b) - this->insert_equal(iend, *b); - } - - //! Requires: value must be an lvalue - //! - //! Effects: Inserts value into the container if the value - //! is not already present. - //! - //! Complexity: Average complexity for insert element is at - //! most logarithmic. - //! - //! Throws: Nothing. - //! - //! Note: Does not affect the validity of iterators and references. - //! No copy-constructors are called. - std::pair insert_unique(reference value) - { - insert_commit_data commit_data; - std::pair ret = this->insert_unique_check(value, this->comp(), commit_data); - if(!ret.second) - return ret; - return std::pair (this->insert_unique_commit(value, commit_data), true); - } - - //! Requires: value must be an lvalue, and "hint" must be - //! a valid iterator - //! - //! Effects: Tries to insert x into the container, using "hint" as a hint - //! to where it will be inserted. - //! - //! Complexity: Logarithmic in general, but it is amortized - //! constant time (two comparisons in the worst case) - //! if t is inserted immediately before hint. - //! - //! Throws: Nothing. - //! - //! Note: Does not affect the validity of iterators and references. - //! No copy-constructors are called. - iterator insert_unique(const_iterator hint, reference value) - { - insert_commit_data commit_data; - std::pair ret = this->insert_unique_check(hint, value, this->comp(), commit_data); - if(!ret.second) - return ret.first; - return this->insert_unique_commit(value, commit_data); - } - - //! Requires: Dereferencing iterator must yield an lvalue - //! of type value_type. - //! - //! Effects: Tries to insert each element of a range into the container. - //! - //! Complexity: Insert range is in general O(N * log(N)), where N is the - //! size of the range. However, it is linear in N if the range is already sorted - //! by value_comp(). - //! - //! Throws: Nothing. - //! - //! Note: Does not affect the validity of iterators and references. - //! No copy-constructors are called. - template - void insert_unique(Iterator b, Iterator e) - { - if(this->empty()){ - iterator iend(this->end()); - for (; b != e; ++b) - this->insert_unique(iend, *b); - } - else{ - for (; b != e; ++b) - this->insert_unique(*b); - } - } - - #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! Requires: key_value_comp must be a comparison function that induces - //! the same strict weak ordering as value_compare. The difference is that - //! key_value_comp compares an arbitrary key with the contained values. - //! - //! Effects: Checks if a value can be inserted in the container, using - //! a user provided key instead of the value itself. - //! - //! Returns: If there is an equivalent value - //! returns a pair containing an iterator to the already present value - //! and false. If the value can be inserted returns true in the returned - //! pair boolean and fills "commit_data" that is meant to be used with - //! the "insert_commit" function. - //! - //! Complexity: Average complexity is at most logarithmic. - //! - //! Throws: If the key_value_comp ordering function throws. Strong guarantee. - //! - //! Notes: This function is used to improve performance when constructing - //! a value_type is expensive: if there is an equivalent value - //! the constructed object must be discarded. Many times, the part of the - //! node that is used to impose the order is much cheaper to construct - //! than the value_type and this function offers the possibility to use that - //! part to check if the insertion will be successful. - //! - //! If the check is successful, the user can construct the value_type and use - //! "insert_commit" to insert the object in constant-time. This gives a total - //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). - //! - //! "commit_data" remains valid for a subsequent "insert_commit" only if no more - //! objects are inserted or erased from the container. - template - std::pair insert_unique_check - (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data); - - //! Requires: key_value_comp must be a comparison function that induces - //! the same strict weak ordering as value_compare. The difference is that - //! key_value_comp compares an arbitrary key with the contained values. - //! - //! Effects: Checks if a value can be inserted in the container, using - //! a user provided key instead of the value itself, using "hint" - //! as a hint to where it will be inserted. - //! - //! Returns: If there is an equivalent value - //! returns a pair containing an iterator to the already present value - //! and false. If the value can be inserted returns true in the returned - //! pair boolean and fills "commit_data" that is meant to be used with - //! the "insert_commit" function. - //! - //! Complexity: Logarithmic in general, but it's amortized - //! constant time if t is inserted immediately before hint. - //! - //! Throws: If the key_value_comp ordering function throws. Strong guarantee. - //! - //! Notes: This function is used to improve performance when constructing - //! a value_type is expensive: if there is an equivalent value - //! the constructed object must be discarded. Many times, the part of the - //! constructing that is used to impose the order is much cheaper to construct - //! than the value_type and this function offers the possibility to use that key - //! to check if the insertion will be successful. - //! - //! If the check is successful, the user can construct the value_type and use - //! "insert_commit" to insert the object in constant-time. This can give a total - //! constant-time complexity to the insertion: check(O(1)) + commit(O(1)). - //! - //! "commit_data" remains valid for a subsequent "insert_commit" only if no more - //! objects are inserted or erased from the container. - template - std::pair insert_unique_check - (const_iterator hint, const KeyType &key - ,KeyValueCompare key_value_comp, insert_commit_data &commit_data); - - #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED - - //! Requires: value must be an lvalue of type value_type. commit_data - //! must have been obtained from a previous call to "insert_check". - //! No objects should have been inserted or erased from the container between - //! the "insert_check" that filled "commit_data" and the call to "insert_commit". - //! - //! Effects: Inserts the value in the container using the information obtained - //! from the "commit_data" that a previous "insert_check" filled. - //! - //! Returns: An iterator to the newly inserted object. - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - //! - //! Notes: This function has only sense if a "insert_check" has been - //! previously executed to fill "commit_data". No value should be inserted or - //! erased between the "insert_check" and "insert_commit" calls. - iterator insert_unique_commit(reference value, const insert_commit_data &commit_data) - { - node_ptr to_insert(this->get_real_value_traits().to_node_ptr(value)); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); - node_algorithms::insert_unique_commit - (this->header_ptr(), to_insert, commit_data); - this->sz_traits().increment(); - return iterator(to_insert, this->real_value_traits_ptr()); - } - - //! Requires: value must be an lvalue, "pos" must be - //! a valid iterator (or end) and must be the succesor of value - //! once inserted according to the predicate - //! - //! Effects: Inserts x into the container before "pos". - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - //! - //! Note: This function does not check preconditions so if "pos" is not - //! the successor of "value" container ordering invariant will be broken. - //! This is a low-level function to be used only for performance reasons - //! by advanced users. - iterator insert_before(const_iterator pos, reference value) - { - node_ptr to_insert(this->get_real_value_traits().to_node_ptr(value)); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); - this->sz_traits().increment(); - return iterator(node_algorithms::insert_before - (this->header_ptr(), pos.pointed_node(), to_insert), this->real_value_traits_ptr()); - } - - //! Requires: value must be an lvalue, and it must be no less - //! than the greatest inserted key - //! - //! Effects: Inserts x into the container in the last position. - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - //! - //! Note: This function does not check preconditions so if value is - //! less than the greatest inserted key container ordering invariant will be broken. - //! This function is slightly more efficient than using "insert_before". - //! This is a low-level function to be used only for performance reasons - //! by advanced users. - void push_back(reference value) - { - node_ptr to_insert(this->get_real_value_traits().to_node_ptr(value)); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); - this->sz_traits().increment(); - node_algorithms::push_back(this->header_ptr(), to_insert); - } - - //! Requires: value must be an lvalue, and it must be no greater - //! than the minimum inserted key - //! - //! Effects: Inserts x into the container in the first position. - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - //! - //! Note: This function does not check preconditions so if value is - //! greater than the minimum inserted key container ordering invariant will be broken. - //! This function is slightly more efficient than using "insert_before". - //! This is a low-level function to be used only for performance reasons - //! by advanced users. - void push_front(reference value) - { - node_ptr to_insert(this->get_real_value_traits().to_node_ptr(value)); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); - this->sz_traits().increment(); - node_algorithms::push_front(this->header_ptr(), to_insert); - } - - //! Effects: Erases the element pointed to by pos. - //! - //! Complexity: Average complexity for erase element is constant time. - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. No destructors are called. - iterator erase(const_iterator i) - { - const_iterator ret(i); - ++ret; - node_ptr to_erase(i.pointed_node()); - if(safemode_or_autounlink) - BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!node_algorithms::unique(to_erase)); - node_algorithms::erase(this->header_ptr(), to_erase); - this->sz_traits().decrement(); - if(safemode_or_autounlink) - node_algorithms::init(to_erase); - return ret.unconst(); - } - - //! Effects: Erases the range pointed to by b end e. - //! - //! Complexity: Average complexity for erase range is at most - //! O(log(size() + N)), where N is the number of elements in the range. - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. No destructors are called. - iterator erase(const_iterator b, const_iterator e) - { size_type n; return this->private_erase(b, e, n); } - - //! Effects: Erases all the elements with the given value. - //! - //! Returns: The number of erased elements. - //! - //! Complexity: O(log(size() + N). - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. No destructors are called. - size_type erase(const_reference value) - { return this->erase(value, this->comp()); } - - //! Effects: Erases all the elements with the given key. - //! according to the comparison functor "comp". - //! - //! Returns: The number of erased elements. - //! - //! Complexity: O(log(size() + N). - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. No destructors are called. - template - size_type erase(const KeyType& key, KeyValueCompare comp - /// @cond - , typename detail::enable_if_c::value >::type * = 0 - /// @endcond - ) - { - std::pair p = this->equal_range(key, comp); - size_type n; - this->private_erase(p.first, p.second, n); - return n; - } - - //! Requires: Disposer::operator()(pointer) shouldn't throw. - //! - //! Effects: Erases the element pointed to by pos. - //! Disposer::operator()(pointer) is called for the removed element. - //! - //! Complexity: Average complexity for erase element is constant time. - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators - //! to the erased elements. - template - iterator erase_and_dispose(const_iterator i, Disposer disposer) - { - node_ptr to_erase(i.pointed_node()); - iterator ret(this->erase(i)); - disposer(this->get_real_value_traits().to_value_ptr(to_erase)); - return ret; - } - - #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - template - iterator erase_and_dispose(iterator i, Disposer disposer) - { return this->erase_and_dispose(const_iterator(i), disposer); } - #endif - - //! Requires: Disposer::operator()(pointer) shouldn't throw. - //! - //! Effects: Erases all the elements with the given value. - //! Disposer::operator()(pointer) is called for the removed elements. - //! - //! Returns: The number of erased elements. - //! - //! Complexity: O(log(size() + N). - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. No destructors are called. - template - size_type erase_and_dispose(const_reference value, Disposer disposer) - { - std::pair p = this->equal_range(value); - size_type n; - this->private_erase(p.first, p.second, n, disposer); - return n; - } - - //! Requires: Disposer::operator()(pointer) shouldn't throw. - //! - //! Effects: Erases the range pointed to by b end e. - //! Disposer::operator()(pointer) is called for the removed elements. - //! - //! Complexity: Average complexity for erase range is at most - //! O(log(size() + N)), where N is the number of elements in the range. - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators - //! to the erased elements. - template - iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) - { size_type n; return this->private_erase(b, e, n, disposer); } - - //! Requires: Disposer::operator()(pointer) shouldn't throw. - //! - //! Effects: Erases all the elements with the given key. - //! according to the comparison functor "comp". - //! Disposer::operator()(pointer) is called for the removed elements. - //! - //! Returns: The number of erased elements. - //! - //! Complexity: O(log(size() + N). - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators - //! to the erased elements. - template - size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer - /// @cond - , typename detail::enable_if_c::value >::type * = 0 - /// @endcond - ) - { - std::pair p = this->equal_range(key, comp); - size_type n; - this->private_erase(p.first, p.second, n, disposer); - return n; - } - - //! Effects: Erases all of the elements. - //! - //! Complexity: Linear to the number of elements on the container. - //! if it's a safe-mode or auto-unlink value_type. Constant time otherwise. - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. No destructors are called. - void clear() - { - if(safemode_or_autounlink){ - this->clear_and_dispose(detail::null_disposer()); - } - else{ - node_algorithms::init_header(this->header_ptr()); - this->sz_traits().set_size(0); - } - } - - //! Effects: Erases all of the elements calling disposer(p) for - //! each node to be erased. - //! Complexity: Average complexity for is at most O(log(size() + N)), - //! where N is the number of elements in the container. - //! - //! Throws: Nothing. - //! - //! Note: Invalidates the iterators (but not the references) - //! to the erased elements. Calls N times to disposer functor. - template - void clear_and_dispose(Disposer disposer) - { - node_algorithms::clear_and_dispose(this->header_ptr() - , detail::node_disposer(disposer, &this->get_real_value_traits())); - node_algorithms::init_header(this->header_ptr()); - this->sz_traits().set_size(0); - } - - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - - //! Effects: Returns the number of contained elements with the given value - //! - //! Complexity: Logarithmic to the number of elements contained plus lineal - //! to number of objects with the given value. - //! - //! Throws: Nothing. - size_type count(const_reference value) const; - - //! Effects: Returns the number of contained elements with the given key - //! - //! Complexity: Logarithmic to the number of elements contained plus lineal - //! to number of objects with the given key. - //! - //! Throws: Nothing. - template - size_type count(const KeyType &key, KeyValueCompare comp) const; - - //! Effects: Returns an iterator to the first element whose - //! key is not less than k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - iterator lower_bound(const_reference value); - - //! Effects: Returns an iterator to the first element whose - //! key is not less than k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - const_iterator lower_bound(const_reference value) const; - - //! Effects: Returns an iterator to the first element whose - //! key is not less than k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - iterator lower_bound(const KeyType &key, KeyValueCompare comp); - - //! Effects: Returns a const iterator to the first element whose - //! key is not less than k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - const_iterator lower_bound(const KeyType &key, KeyValueCompare comp) const; - - //! Effects: Returns an iterator to the first element whose - //! key is greater than k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - iterator upper_bound(const_reference value); - - //! Effects: Returns an iterator to the first element whose - //! key is greater than k according to comp or end() if that element - //! does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - iterator upper_bound(const KeyType &key, KeyValueCompare comp); - - //! Effects: Returns an iterator to the first element whose - //! key is greater than k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - const_iterator upper_bound(const_reference value) const; - - //! Effects: Returns an iterator to the first element whose - //! key is greater than k according to comp or end() if that element - //! does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - const_iterator upper_bound(const KeyType &key, KeyValueCompare comp) const; - - //! Effects: Finds an iterator to the first element whose key is - //! k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - iterator find(const_reference value); - - //! Effects: Finds an iterator to the first element whose key is - //! k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - iterator find(const KeyType &key, KeyValueCompare comp); - - //! Effects: Finds a const_iterator to the first element whose key is - //! k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - const_iterator find(const_reference value) const; - - //! Effects: Finds a const_iterator to the first element whose key is - //! k or end() if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - const_iterator find(const KeyType &key, KeyValueCompare comp) const; - - //! Effects: Finds a range containing all elements whose key is k or - //! an empty range that indicates the position where those elements would be - //! if they there is no elements with key k. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - std::pair equal_range(const_reference value); - - //! Effects: Finds a range containing all elements whose key is k or - //! an empty range that indicates the position where those elements would be - //! if they there is no elements with key k. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - std::pair equal_range(const KeyType &key, KeyValueCompare comp); - - //! Effects: Finds a range containing all elements whose key is k or - //! an empty range that indicates the position where those elements would be - //! if they there is no elements with key k. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - std::pair - equal_range(const_reference value) const; - - //! Effects: Finds a range containing all elements whose key is k or - //! an empty range that indicates the position where those elements would be - //! if they there is no elements with key k. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - template - std::pair - equal_range(const KeyType &key, KeyValueCompare comp) const; - - //! Requires: 'lower_value' must not be greater than 'upper_value'. If - //! 'lower_value' == 'upper_value', ('left_closed' || 'right_closed') must be false. - //! - //! Effects: Returns an a pair with the following criteria: - //! - //! first = lower_bound(lower_key) if left_closed, upper_bound(lower_key) otherwise - //! - //! second = upper_bound(upper_key) if right_closed, lower_bound(upper_key) otherwise - //! - //! Complexity: Logarithmic. - //! - //! Throws: If the predicate throws. - //! - //! Note: This function can be more efficient than calling upper_bound - //! and lower_bound for lower_value and upper_value. - //! - //! Note: Experimental function, the interface might change in future releases. - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); - - //! Requires: KeyValueCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the container. - //! 'lower_key' must not be greater than 'upper_key' according to 'comp'. If - //! 'lower_key' == 'upper_key', ('left_closed' || 'right_closed') must be false. - //! - //! Effects: Returns an a pair with the following criteria: - //! - //! first = lower_bound(lower_key, comp) if left_closed, upper_bound(lower_key, comp) otherwise - //! - //! second = upper_bound(upper_key, comp) if right_closed, lower_bound(upper_key, comp) otherwise - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - //! - //! Note: This function can be more efficient than calling upper_bound - //! and lower_bound for lower_key and upper_key. - //! - //! Note: Experimental function, the interface might change in future releases. - template - std::pair bounded_range - (const KeyType &lower_key, const KeyType &upper_key, KeyValueCompare comp, bool left_closed, bool right_closed); - - //! Requires: 'lower_value' must not be greater than 'upper_value'. If - //! 'lower_value' == 'upper_value', ('left_closed' || 'right_closed') must be false. - //! - //! Effects: Returns an a pair with the following criteria: - //! - //! first = lower_bound(lower_key) if left_closed, upper_bound(lower_key) otherwise - //! - //! second = upper_bound(upper_key) if right_closed, lower_bound(upper_key) otherwise - //! - //! Complexity: Logarithmic. - //! - //! Throws: If the predicate throws. - //! - //! Note: This function can be more efficient than calling upper_bound - //! and lower_bound for lower_value and upper_value. - //! - //! Note: Experimental function, the interface might change in future releases. - std::pair bounded_range - (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; - - //! Requires: KeyValueCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the container. - //! 'lower_key' must not be greater than 'upper_key' according to 'comp'. If - //! 'lower_key' == 'upper_key', ('left_closed' || 'right_closed') must be false. - //! - //! Effects: Returns an a pair with the following criteria: - //! - //! first = lower_bound(lower_key, comp) if left_closed, upper_bound(lower_key, comp) otherwise - //! - //! second = upper_bound(upper_key, comp) if right_closed, lower_bound(upper_key, comp) otherwise - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - //! - //! Note: This function can be more efficient than calling upper_bound - //! and lower_bound for lower_key and upper_key. - //! - //! Note: Experimental function, the interface might change in future releases. - template - std::pair bounded_range - (const KeyType &lower_key, const KeyType &upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const; - - //! Requires: value must be an lvalue and shall be in a set of - //! appropriate type. Otherwise the behavior is undefined. - //! - //! Effects: Returns: a valid iterator i belonging to the set - //! that points to the value - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Note: This static function is available only if the value traits - //! is stateless. - static iterator s_iterator_to(reference value); - - //! Requires: value must be an lvalue and shall be in a set of - //! appropriate type. Otherwise the behavior is undefined. - //! - //! Effects: Returns: a valid const_iterator i belonging to the - //! set that points to the value - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Note: This static function is available only if the value traits - //! is stateless. - static const_iterator s_iterator_to(const_reference value); - - //! Requires: value must be an lvalue and shall be in a set of - //! appropriate type. Otherwise the behavior is undefined. - //! - //! Effects: Returns: a valid iterator i belonging to the set - //! that points to the value - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - iterator iterator_to(reference value); - - //! Requires: value must be an lvalue and shall be in a set of - //! appropriate type. Otherwise the behavior is undefined. - //! - //! Effects: Returns: a valid const_iterator i belonging to the - //! set that points to the value - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - const_iterator iterator_to(const_reference value) const; - - //! Requires: value shall not be in a container. - //! - //! Effects: init_node puts the hook of a value in a well-known default - //! state. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant time. - //! - //! Note: This function puts the hook in the well-known default state - //! used by auto_unlink and safe hooks. - static void init_node(reference value); - - #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - - //! Effects: Unlinks the leftmost node from the container. - //! - //! Complexity: Average complexity is constant time. - //! - //! Throws: Nothing. - //! - //! Notes: This function breaks the container and the container can - //! only be used for more unlink_leftmost_without_rebalance calls. - //! This function is normally used to achieve a step by step - //! controlled destruction of the container. - pointer unlink_leftmost_without_rebalance() - { - node_ptr to_be_disposed(node_algorithms::unlink_leftmost_without_rebalance - (this->header_ptr())); - if(!to_be_disposed) - return 0; - this->sz_traits().decrement(); - if(safemode_or_autounlink)//If this is commented does not work with normal_link - node_algorithms::init(to_be_disposed); - return this->get_real_value_traits().to_value_ptr(to_be_disposed); - } - - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - - //! Requires: replace_this must be a valid iterator of *this - //! and with_this must not be inserted in any container. - //! - //! Effects: Replaces replace_this in its position in the - //! container with with_this. The container does not need to be rebalanced. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Note: This function will break container ordering invariants if - //! with_this is not equivalent to *replace_this according to the - //! ordering rules. This function is faster than erasing and inserting - //! the node, since no rebalancing or comparison is needed. - void replace_node(iterator replace_this, reference with_this); - - //! Effects: Rebalances the tree. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear. - void rebalance(); - - //! Requires: old_root is a node of a tree. - //! - //! Effects: Rebalances the subtree rooted at old_root. - //! - //! Returns: The new root of the subtree. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the elements in the subtree. - iterator rebalance_subtree(iterator root); - - #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - - //! Effects: removes "value" from the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Logarithmic time. - //! - //! Note: This static function is only usable with non-constant - //! time size containers that have stateless comparison functors. - //! - //! If the user calls - //! this function with a constant time size container or stateful comparison - //! functor a compilation error will be issued. - static void remove_node(reference value) - { - BOOST_STATIC_ASSERT((!constant_time_size)); - node_ptr to_remove(value_traits::to_node_ptr(value)); - node_algorithms::unlink(to_remove); - if(safemode_or_autounlink) - node_algorithms::init(to_remove); - } - - /// @cond - private: - template - iterator private_erase(const_iterator b, const_iterator e, size_type &n, Disposer disposer) - { - for(n = 0; b != e; ++n) - this->erase_and_dispose(b++, disposer); - return b.unconst(); - } - - iterator private_erase(const_iterator b, const_iterator e, size_type &n) - { - for(n = 0; b != e; ++n) - this->erase(b++); - return b.unconst(); - } - /// @endcond - - private: - static bstree_impl &priv_container_from_end_iterator(const const_iterator &end_iterator) - { - return *static_cast - (boost::intrusive::detail::to_raw_pointer(end_iterator.pointed_node())); - } -}; - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -inline bool operator< -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(const bstree_impl &x, const bstree_impl &y) -#else -( const bstree_impl &x -, const bstree_impl &y) -#endif -{ return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -bool operator== -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(const bstree_impl &x, const bstree_impl &y) -#else -( const bstree_impl &x -, const bstree_impl &y) -#endif -{ - typedef bstree_impl tree_type; - typedef typename tree_type::const_iterator const_iterator; - - if(tree_type::constant_time_size && x.size() != y.size()){ - return false; - } - const_iterator end1 = x.end(); - const_iterator i1 = x.begin(); - const_iterator i2 = y.begin(); - if(tree_type::constant_time_size){ - while (i1 != end1 && *i1 == *i2) { - ++i1; - ++i2; - } - return i1 == end1; - } - else{ - const_iterator end2 = y.end(); - while (i1 != end1 && i2 != end2 && *i1 == *i2) { - ++i1; - ++i2; - } - return i1 == end1 && i2 == end2; - } -} - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -inline bool operator!= -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(const bstree_impl &x, const bstree_impl &y) -#else -( const bstree_impl &x -, const bstree_impl &y) -#endif -{ return !(x == y); } - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -inline bool operator> -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(const bstree_impl &x, const bstree_impl &y) -#else -( const bstree_impl &x -, const bstree_impl &y) -#endif -{ return y < x; } - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -inline bool operator<= -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(const bstree_impl &x, const bstree_impl &y) -#else -( const bstree_impl &x -, const bstree_impl &y) -#endif -{ return !(y < x); } - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -inline bool operator>= -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(const bstree_impl &x, const bstree_impl &y) -#else -( const bstree_impl &x -, const bstree_impl &y) -#endif -{ return !(x < y); } - -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -template -#else -template -#endif -inline void swap -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) -(bstree_impl &x, bstree_impl &y) -#else -( bstree_impl &x -, bstree_impl &y) -#endif -{ x.swap(y); } - -//! Helper metafunction to define a \c bstree that yields to the same type when the -//! same options (either explicitly or implicitly) are used. -#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -struct make_bstree -{ - /// @cond - typedef typename pack_options - < bstree_defaults, - #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) - O1, O2, O3, O4 - #else - Options... - #endif - >::type packed_options; - - typedef typename detail::get_value_traits - ::type value_traits; - - typedef bstree_impl - < value_traits - , typename packed_options::compare - , typename packed_options::size_type - , packed_options::constant_time_size - , BsTreeAlgorithms - > implementation_defined; - /// @endcond - typedef implementation_defined type; -}; - - -#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - -#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) -template -#else -template -#endif -class bstree - : public make_bstree::type -{ - typedef typename make_bstree - ::type Base; - BOOST_MOVABLE_BUT_NOT_COPYABLE(bstree) - - public: - typedef typename Base::value_compare value_compare; - typedef typename Base::value_traits value_traits; - typedef typename Base::real_value_traits real_value_traits; - typedef typename Base::iterator iterator; - typedef typename Base::const_iterator const_iterator; - - //Assert if passed value traits are compatible with the type - BOOST_STATIC_ASSERT((detail::is_same::value)); - - bstree( const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(cmp, v_traits) - {} - - template - bstree( bool unique, Iterator b, Iterator e - , const value_compare &cmp = value_compare() - , const value_traits &v_traits = value_traits()) - : Base(unique, b, e, cmp, v_traits) - {} - - bstree(BOOST_RV_REF(bstree) x) - : Base(::boost::move(static_cast(x))) - {} - - bstree& operator=(BOOST_RV_REF(bstree) x) - { return static_cast(this->Base::operator=(::boost::move(static_cast(x)))); } - - static bstree &container_from_end_iterator(iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static const bstree &container_from_end_iterator(const_iterator end_iterator) - { return static_cast(Base::container_from_end_iterator(end_iterator)); } - - static bstree &container_from_iterator(iterator it) - { return static_cast(Base::container_from_iterator(it)); } - - static const bstree &container_from_iterator(const_iterator it) - { return static_cast(Base::container_from_iterator(it)); } -}; - -#endif -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_BSTREE_HPP diff --git a/utils/boost_idb/boost/intrusive/bstree_algorithms.hpp b/utils/boost_idb/boost/intrusive/bstree_algorithms.hpp deleted file mode 100644 index 62973292..00000000 --- a/utils/boost_idb/boost/intrusive/bstree_algorithms.hpp +++ /dev/null @@ -1,1988 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_BSTREE_ALGORITHMS_HPP -#define BOOST_INTRUSIVE_BSTREE_ALGORITHMS_HPP - -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond - -//! This type is the information that will be filled by insert_unique_check -template -struct insert_commit_data_t -{ - insert_commit_data_t() - : link_left(false) - , node() - {} - bool link_left; - NodePtr node; -}; - -template -struct data_for_rebalance_t -{ - NodePtr x; - NodePtr x_parent; - NodePtr y; -}; - -/// @endcond - - - -//! This is an implementation of a binary search tree. -//! A node in the search tree has references to its children and its parent. This -//! is to allow traversal of the whole tree from a given node making the -//! implementation of iterator a pointer to a node. -//! At the top of the tree a node is used specially. This node's parent pointer -//! is pointing to the root of the tree. Its left pointer points to the -//! leftmost node in the tree and the right pointer to the rightmost one. -//! This node is used to represent the end-iterator. -//! -//! +---------+ -//! header------------------------------>| | -//! | | -//! +----------(left)--------| |--------(right)---------+ -//! | +---------+ | -//! | | | -//! | | (parent) | -//! | | | -//! | | | -//! | +---------+ | -//! root of tree ..|......................> | | | -//! | | D | | -//! | | | | -//! | +-------+---------+-------+ | -//! | | | | -//! | | | | -//! | | | | -//! | | | | -//! | | | | -//! | +---------+ +---------+ | -//! | | | | | | -//! | | B | | F | | -//! | | | | | | -//! | +--+---------+--+ +--+---------+--+ | -//! | | | | | | -//! | | | | | | -//! | | | | | | -//! | +---+-----+ +-----+---+ +---+-----+ +-----+---+ | -//! +-->| | | | | | | |<--+ -//! | A | | C | | E | | G | -//! | | | | | | | | -//! +---------+ +---------+ +---------+ +---------+ -//! -//! bstree_algorithms is configured with a NodeTraits class, which encapsulates the -//! information about the node to be manipulated. NodeTraits must support the -//! following interface: -//! -//! Typedefs: -//! -//! node: The type of the node that forms the binary search tree -//! -//! node_ptr: A pointer to a node -//! -//! const_node_ptr: A pointer to a const node -//! -//! Static functions: -//! -//! static node_ptr get_parent(const_node_ptr n); -//! -//! static void set_parent(node_ptr n, node_ptr parent); -//! -//! static node_ptr get_left(const_node_ptr n); -//! -//! static void set_left(node_ptr n, node_ptr left); -//! -//! static node_ptr get_right(const_node_ptr n); -//! -//! static void set_right(node_ptr n, node_ptr right); -template -class bstree_algorithms -{ - public: - typedef typename NodeTraits::node node; - typedef NodeTraits node_traits; - typedef typename NodeTraits::node_ptr node_ptr; - typedef typename NodeTraits::const_node_ptr const_node_ptr; - typedef insert_commit_data_t insert_commit_data; - typedef data_for_rebalance_t data_for_rebalance; - - /// @cond - - private: - template - struct dispose_subtree_disposer - { - dispose_subtree_disposer(Disposer &disp, const node_ptr & subtree) - : disposer_(&disp), subtree_(subtree) - {} - - void release() - { disposer_ = 0; } - - ~dispose_subtree_disposer() - { - if(disposer_){ - dispose_subtree(subtree_, *disposer_); - } - } - Disposer *disposer_; - const node_ptr subtree_; - }; - - /// @endcond - - public: - //! Requires: 'header' is the header node of a tree. - //! - //! Effects: Returns the first node of the tree, the header if the tree is empty. - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - static node_ptr begin_node(const const_node_ptr & header) - { return node_traits::get_left(header); } - - //! Requires: 'header' is the header node of a tree. - //! - //! Effects: Returns the header of the tree. - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - static node_ptr end_node(const const_node_ptr & header) - { return detail::uncast(header); } - - //! Requires: 'node' is a node of the tree or an node initialized - //! by init(...) or init_node. - //! - //! Effects: Returns true if the node is initialized by init() or init_node(). - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - static bool unique(const const_node_ptr & node) - { return !NodeTraits::get_parent(node); } - - //! Requires: 'node' is a node of the tree or a header node. - //! - //! Effects: Returns the header of the tree. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - static node_ptr get_header(const const_node_ptr & node) - { - node_ptr n(detail::uncast(node)); - node_ptr p(NodeTraits::get_parent(node)); - //If p is null, then n is the header of an empty tree - if(p){ - //Non-empty tree, check if n is neither root nor header - node_ptr pp(NodeTraits::get_parent(p)); - //If granparent is not equal to n, then n is neither root nor header, - //the try the fast path - if(n != pp){ - do{ - n = p; - p = pp; - pp = NodeTraits::get_parent(pp); - }while(n != pp); - n = p; - } - //Check if n is root or header when size() > 0 - else if(!is_header(n)){ - n = p; - } - } - return n; - /* - node_ptr h = detail::uncast(node); - node_ptr p = NodeTraits::get_parent(node); - if(p){ - while(!is_header(p)) - p = NodeTraits::get_parent(p); - return p; - } - else{ - return h; - }*/ - } - - //! Requires: node1 and node2 can't be header nodes - //! of two trees. - //! - //! Effects: Swaps two nodes. After the function node1 will be inserted - //! in the position node2 before the function. node2 will be inserted in the - //! position node1 had before the function. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - //! - //! Note: This function will break container ordering invariants if - //! node1 and node2 are not equivalent according to the ordering rules. - //! - //!Experimental function - static void swap_nodes(const node_ptr & node1, const node_ptr & node2) - { - if(node1 == node2) - return; - - node_ptr header1(get_header(node1)), header2(get_header(node2)); - swap_nodes(node1, header1, node2, header2); - } - - //! Requires: node1 and node2 can't be header nodes - //! of two trees with header header1 and header2. - //! - //! Effects: Swaps two nodes. After the function node1 will be inserted - //! in the position node2 before the function. node2 will be inserted in the - //! position node1 had before the function. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Note: This function will break container ordering invariants if - //! node1 and node2 are not equivalent according to the ordering rules. - //! - //!Experimental function - static void swap_nodes(const node_ptr & node1, const node_ptr & header1, const node_ptr & node2, const node_ptr & header2) - { - if(node1 == node2) - return; - - //node1 and node2 must not be header nodes - //BOOST_INTRUSIVE_INVARIANT_ASSERT((header1 != node1 && header2 != node2)); - if(header1 != header2){ - //Update header1 if necessary - if(node1 == NodeTraits::get_left(header1)){ - NodeTraits::set_left(header1, node2); - } - - if(node1 == NodeTraits::get_right(header1)){ - NodeTraits::set_right(header1, node2); - } - - if(node1 == NodeTraits::get_parent(header1)){ - NodeTraits::set_parent(header1, node2); - } - - //Update header2 if necessary - if(node2 == NodeTraits::get_left(header2)){ - NodeTraits::set_left(header2, node1); - } - - if(node2 == NodeTraits::get_right(header2)){ - NodeTraits::set_right(header2, node1); - } - - if(node2 == NodeTraits::get_parent(header2)){ - NodeTraits::set_parent(header2, node1); - } - } - else{ - //If both nodes are from the same tree - //Update header if necessary - if(node1 == NodeTraits::get_left(header1)){ - NodeTraits::set_left(header1, node2); - } - else if(node2 == NodeTraits::get_left(header2)){ - NodeTraits::set_left(header2, node1); - } - - if(node1 == NodeTraits::get_right(header1)){ - NodeTraits::set_right(header1, node2); - } - else if(node2 == NodeTraits::get_right(header2)){ - NodeTraits::set_right(header2, node1); - } - - if(node1 == NodeTraits::get_parent(header1)){ - NodeTraits::set_parent(header1, node2); - } - else if(node2 == NodeTraits::get_parent(header2)){ - NodeTraits::set_parent(header2, node1); - } - - //Adjust data in nodes to be swapped - //so that final link swap works as expected - if(node1 == NodeTraits::get_parent(node2)){ - NodeTraits::set_parent(node2, node2); - - if(node2 == NodeTraits::get_right(node1)){ - NodeTraits::set_right(node1, node1); - } - else{ - NodeTraits::set_left(node1, node1); - } - } - else if(node2 == NodeTraits::get_parent(node1)){ - NodeTraits::set_parent(node1, node1); - - if(node1 == NodeTraits::get_right(node2)){ - NodeTraits::set_right(node2, node2); - } - else{ - NodeTraits::set_left(node2, node2); - } - } - } - - //Now swap all the links - node_ptr temp; - //swap left link - temp = NodeTraits::get_left(node1); - NodeTraits::set_left(node1, NodeTraits::get_left(node2)); - NodeTraits::set_left(node2, temp); - //swap right link - temp = NodeTraits::get_right(node1); - NodeTraits::set_right(node1, NodeTraits::get_right(node2)); - NodeTraits::set_right(node2, temp); - //swap parent link - temp = NodeTraits::get_parent(node1); - NodeTraits::set_parent(node1, NodeTraits::get_parent(node2)); - NodeTraits::set_parent(node2, temp); - - //Now adjust adjacent nodes for newly inserted node 1 - if((temp = NodeTraits::get_left(node1))){ - NodeTraits::set_parent(temp, node1); - } - if((temp = NodeTraits::get_right(node1))){ - NodeTraits::set_parent(temp, node1); - } - if((temp = NodeTraits::get_parent(node1)) && - //The header has been already updated so avoid it - temp != header2){ - if(NodeTraits::get_left(temp) == node2){ - NodeTraits::set_left(temp, node1); - } - if(NodeTraits::get_right(temp) == node2){ - NodeTraits::set_right(temp, node1); - } - } - //Now adjust adjacent nodes for newly inserted node 2 - if((temp = NodeTraits::get_left(node2))){ - NodeTraits::set_parent(temp, node2); - } - if((temp = NodeTraits::get_right(node2))){ - NodeTraits::set_parent(temp, node2); - } - if((temp = NodeTraits::get_parent(node2)) && - //The header has been already updated so avoid it - temp != header1){ - if(NodeTraits::get_left(temp) == node1){ - NodeTraits::set_left(temp, node2); - } - if(NodeTraits::get_right(temp) == node1){ - NodeTraits::set_right(temp, node2); - } - } - } - - //! Requires: node_to_be_replaced must be inserted in a tree - //! and new_node must not be inserted in a tree. - //! - //! Effects: Replaces node_to_be_replaced in its position in the - //! tree with new_node. The tree does not need to be rebalanced - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - //! - //! Note: This function will break container ordering invariants if - //! new_node is not equivalent to node_to_be_replaced according to the - //! ordering rules. This function is faster than erasing and inserting - //! the node, since no rebalancing and comparison is needed. Experimental function - static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & new_node) - { - if(node_to_be_replaced == new_node) - return; - replace_node(node_to_be_replaced, get_header(node_to_be_replaced), new_node); - } - - //! Requires: node_to_be_replaced must be inserted in a tree - //! with header "header" and new_node must not be inserted in a tree. - //! - //! Effects: Replaces node_to_be_replaced in its position in the - //! tree with new_node. The tree does not need to be rebalanced - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Note: This function will break container ordering invariants if - //! new_node is not equivalent to node_to_be_replaced according to the - //! ordering rules. This function is faster than erasing and inserting - //! the node, since no rebalancing or comparison is needed. Experimental function - static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & header, const node_ptr & new_node) - { - if(node_to_be_replaced == new_node) - return; - - //Update header if necessary - if(node_to_be_replaced == NodeTraits::get_left(header)){ - NodeTraits::set_left(header, new_node); - } - - if(node_to_be_replaced == NodeTraits::get_right(header)){ - NodeTraits::set_right(header, new_node); - } - - if(node_to_be_replaced == NodeTraits::get_parent(header)){ - NodeTraits::set_parent(header, new_node); - } - - //Now set data from the original node - node_ptr temp; - NodeTraits::set_left(new_node, NodeTraits::get_left(node_to_be_replaced)); - NodeTraits::set_right(new_node, NodeTraits::get_right(node_to_be_replaced)); - NodeTraits::set_parent(new_node, NodeTraits::get_parent(node_to_be_replaced)); - - //Now adjust adjacent nodes for newly inserted node - if((temp = NodeTraits::get_left(new_node))){ - NodeTraits::set_parent(temp, new_node); - } - if((temp = NodeTraits::get_right(new_node))){ - NodeTraits::set_parent(temp, new_node); - } - if((temp = NodeTraits::get_parent(new_node)) && - //The header has been already updated so avoid it - temp != header){ - if(NodeTraits::get_left(temp) == node_to_be_replaced){ - NodeTraits::set_left(temp, new_node); - } - if(NodeTraits::get_right(temp) == node_to_be_replaced){ - NodeTraits::set_right(temp, new_node); - } - } - } - - //! Requires: 'node' is a node from the tree except the header. - //! - //! Effects: Returns the next node of the tree. - //! - //! Complexity: Average constant time. - //! - //! Throws: Nothing. - static node_ptr next_node(const node_ptr & node) - { - node_ptr p_right(NodeTraits::get_right(node)); - if(p_right){ - return minimum(p_right); - } - else { - node_ptr p(node); - node_ptr x = NodeTraits::get_parent(p); - while(p == NodeTraits::get_right(x)){ - p = x; - x = NodeTraits::get_parent(x); - } - return NodeTraits::get_right(p) != x ? x : detail::uncast(p); - } - } - - //! Requires: 'node' is a node from the tree except the leftmost node. - //! - //! Effects: Returns the previous node of the tree. - //! - //! Complexity: Average constant time. - //! - //! Throws: Nothing. - static node_ptr prev_node(const node_ptr & node) - { - if(is_header(node)){ - return NodeTraits::get_right(node); - //return maximum(NodeTraits::get_parent(node)); - } - else if(NodeTraits::get_left(node)){ - return maximum(NodeTraits::get_left(node)); - } - else { - node_ptr p(node); - node_ptr x = NodeTraits::get_parent(p); - while(p == NodeTraits::get_left(x)){ - p = x; - x = NodeTraits::get_parent(x); - } - return x; - } - } - - //! Requires: 'node' is a node of a tree but not the header. - //! - //! Effects: Returns the minimum node of the subtree starting at p. - //! - //! Complexity: Logarithmic to the size of the subtree. - //! - //! Throws: Nothing. - static node_ptr minimum (node_ptr node) - { - for(node_ptr p_left = NodeTraits::get_left(node) - ;p_left - ;p_left = NodeTraits::get_left(node)){ - node = p_left; - } - return node; - } - - //! Requires: 'node' is a node of a tree but not the header. - //! - //! Effects: Returns the maximum node of the subtree starting at p. - //! - //! Complexity: Logarithmic to the size of the subtree. - //! - //! Throws: Nothing. - static node_ptr maximum(node_ptr node) - { - for(node_ptr p_right = NodeTraits::get_right(node) - ;p_right - ;p_right = NodeTraits::get_right(node)){ - node = p_right; - } - return node; - } - - //! Requires: 'node' must not be part of any tree. - //! - //! Effects: After the function unique(node) == true. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Nodes: If node is inserted in a tree, this function corrupts the tree. - static void init(const node_ptr & node) - { - NodeTraits::set_parent(node, node_ptr()); - NodeTraits::set_left(node, node_ptr()); - NodeTraits::set_right(node, node_ptr()); - }; - - //! Effects: Returns true if node is in the same state as if called init(node) - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - static bool inited(const const_node_ptr & node) - { - return !NodeTraits::get_parent(node) && - !NodeTraits::get_left(node) && - !NodeTraits::get_right(node) ; - }; - - //! Requires: node must not be part of any tree. - //! - //! Effects: Initializes the header to represent an empty tree. - //! unique(header) == true. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Nodes: If node is inserted in a tree, this function corrupts the tree. - static void init_header(const node_ptr & header) - { - NodeTraits::set_parent(header, node_ptr()); - NodeTraits::set_left(header, header); - NodeTraits::set_right(header, header); - } - - //! Requires: "disposer" must be an object function - //! taking a node_ptr parameter and shouldn't throw. - //! - //! Effects: Empties the target tree calling - //! void disposer::operator()(const node_ptr &) for every node of the tree - //! except the header. - //! - //! Complexity: Linear to the number of element of the source tree plus the. - //! number of elements of tree target tree when calling this function. - //! - //! Throws: If cloner functor throws. If this happens target nodes are disposed. - template - static void clear_and_dispose(const node_ptr & header, Disposer disposer) - { - node_ptr source_root = NodeTraits::get_parent(header); - if(!source_root) - return; - dispose_subtree(source_root, disposer); - init_header(header); - } - - //! Requires: header is the header of a tree. - //! - //! Effects: Unlinks the leftmost node from the tree, and - //! updates the header link to the new leftmost node. - //! - //! Complexity: Average complexity is constant time. - //! - //! Throws: Nothing. - //! - //! Notes: This function breaks the tree and the tree can - //! only be used for more unlink_leftmost_without_rebalance calls. - //! This function is normally used to achieve a step by step - //! controlled destruction of the tree. - static node_ptr unlink_leftmost_without_rebalance(const node_ptr & header) - { - node_ptr leftmost = NodeTraits::get_left(header); - if (leftmost == header) - return node_ptr(); - node_ptr leftmost_parent(NodeTraits::get_parent(leftmost)); - node_ptr leftmost_right (NodeTraits::get_right(leftmost)); - bool is_root = leftmost_parent == header; - - if (leftmost_right){ - NodeTraits::set_parent(leftmost_right, leftmost_parent); - NodeTraits::set_left(header, bstree_algorithms::minimum(leftmost_right)); - - if (is_root) - NodeTraits::set_parent(header, leftmost_right); - else - NodeTraits::set_left(NodeTraits::get_parent(header), leftmost_right); - } - else if (is_root){ - NodeTraits::set_parent(header, node_ptr()); - NodeTraits::set_left(header, header); - NodeTraits::set_right(header, header); - } - else{ - NodeTraits::set_left(leftmost_parent, node_ptr()); - NodeTraits::set_left(header, leftmost_parent); - } - return leftmost; - } - - //! Requires: node is a node of the tree but it's not the header. - //! - //! Effects: Returns the number of nodes of the subtree. - //! - //! Complexity: Linear time. - //! - //! Throws: Nothing. - static std::size_t size(const const_node_ptr & header) - { - node_ptr beg(begin_node(header)); - node_ptr end(end_node(header)); - std::size_t i = 0; - for(;beg != end; beg = next_node(beg)) ++i; - return i; - } - - //! Requires: header1 and header2 must be the header nodes - //! of two trees. - //! - //! Effects: Swaps two trees. After the function header1 will contain - //! links to the second tree and header2 will have links to the first tree. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - static void swap_tree(const node_ptr & header1, const node_ptr & header2) - { - if(header1 == header2) - return; - - node_ptr tmp; - - //Parent swap - tmp = NodeTraits::get_parent(header1); - NodeTraits::set_parent(header1, NodeTraits::get_parent(header2)); - NodeTraits::set_parent(header2, tmp); - //Left swap - tmp = NodeTraits::get_left(header1); - NodeTraits::set_left(header1, NodeTraits::get_left(header2)); - NodeTraits::set_left(header2, tmp); - //Right swap - tmp = NodeTraits::get_right(header1); - NodeTraits::set_right(header1, NodeTraits::get_right(header2)); - NodeTraits::set_right(header2, tmp); - - //Now test parent - node_ptr h1_parent(NodeTraits::get_parent(header1)); - if(h1_parent){ - NodeTraits::set_parent(h1_parent, header1); - } - else{ - NodeTraits::set_left(header1, header1); - NodeTraits::set_right(header1, header1); - } - - node_ptr h2_parent(NodeTraits::get_parent(header2)); - if(h2_parent){ - NodeTraits::set_parent(h2_parent, header2); - } - else{ - NodeTraits::set_left(header2, header2); - NodeTraits::set_right(header2, header2); - } - } - - //! Requires: p is a node of a tree. - //! - //! Effects: Returns true if p is the header of the tree. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - static bool is_header(const const_node_ptr & p) - { - node_ptr p_left (NodeTraits::get_left(p)); - node_ptr p_right(NodeTraits::get_right(p)); - if(!NodeTraits::get_parent(p) || //Header condition when empty tree - (p_left && p_right && //Header always has leftmost and rightmost - (p_left == p_right || //Header condition when only node - (NodeTraits::get_parent(p_left) != p || - NodeTraits::get_parent(p_right) != p )) - //When tree size > 1 headers can't be leftmost's - //and rightmost's parent - )){ - return true; - } - return false; - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. - //! - //! Effects: Returns an node_ptr to the element that is equivalent to - //! "key" according to "comp" or "header" if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - template - static node_ptr find - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp) - { - node_ptr end = detail::uncast(header); - node_ptr y = lower_bound(header, key, comp); - return (y == end || comp(key, y)) ? end : y; - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. - //! 'lower_key' must not be greater than 'upper_key' according to 'comp'. If - //! 'lower_key' == 'upper_key', ('left_closed' || 'right_closed') must be false. - //! - //! Effects: Returns an a pair with the following criteria: - //! - //! first = lower_bound(lower_key) if left_closed, upper_bound(lower_key) otherwise - //! - //! second = upper_bound(upper_key) if right_closed, lower_bound(upper_key) otherwise - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - //! - //! Note: This function can be more efficient than calling upper_bound - //! and lower_bound for lower_key and upper_key. - //! - //! Note: Experimental function, the interface might change. - template< class KeyType, class KeyNodePtrCompare> - static std::pair bounded_range - ( const const_node_ptr & header - , const KeyType &lower_key - , const KeyType &upper_key - , KeyNodePtrCompare comp - , bool left_closed - , bool right_closed) - { - node_ptr y = detail::uncast(header); - node_ptr x = NodeTraits::get_parent(header); - - while(x){ - //If x is less than lower_key the target - //range is on the right part - if(comp(x, lower_key)){ - //Check for invalid input range - BOOST_INTRUSIVE_INVARIANT_ASSERT(comp(x, upper_key)); - x = NodeTraits::get_right(x); - } - //If the upper_key is less than x, the target - //range is on the left part - else if(comp(upper_key, x)){ - //y > upper_key - y = x; - x = NodeTraits::get_left(x); - } - else{ - //x is inside the bounded range( x >= lower_key && x <= upper_key), - //so we must split lower and upper searches - // - //Sanity check: if lower_key and upper_key are equal, then both left_closed and right_closed can't be false - BOOST_INTRUSIVE_INVARIANT_ASSERT(left_closed || right_closed || comp(lower_key, x) || comp(x, upper_key)); - return std::pair( - left_closed - //If left_closed, then comp(x, lower_key) is already the lower_bound - //condition so we save one comparison and go to the next level - //following traditional lower_bound algo - ? lower_bound_loop(NodeTraits::get_left(x), x, lower_key, comp) - //If left-open, comp(x, lower_key) is not the upper_bound algo - //condition so we must recheck current 'x' node with upper_bound algo - : upper_bound_loop(x, y, lower_key, comp) - , - right_closed - //If right_closed, then comp(upper_key, x) is already the upper_bound - //condition so we can save one comparison and go to the next level - //following lower_bound algo - ? upper_bound_loop(NodeTraits::get_right(x), y, upper_key, comp) - //If right-open, comp(upper_key, x) is not the lower_bound algo - //condition so we must recheck current 'x' node with lower_bound algo - : lower_bound_loop(x, y, upper_key, comp) - ); - } - } - return std::pair (y, y); - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. - //! - //! Effects: Returns the number of elements with a key equivalent to "key"pair of node_ptr delimiting a range containing - //! according to "comp". - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - template - static std::size_t count - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp) - { - std::pair ret = equal_range(header, key, comp); - std::size_t n = 0; - while(ret.first != ret.second){ - ++n; - ret.first = next_node(ret.first); - } - return n; - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. - //! - //! Effects: Returns an a pair of node_ptr delimiting a range containing - //! all elements that are equivalent to "key" according to "comp" or an - //! empty range that indicates the position where those elements would be - //! if there are no equivalent elements. - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - template - static std::pair equal_range - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp) - { - return bounded_range(header, key, key, comp, true, true); - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. - //! - //! Effects: Returns an node_ptr to the first element that is - //! not less than "key" according to "comp" or "header" if that element does - //! not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - template - static node_ptr lower_bound - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp) - { - return lower_bound_loop(NodeTraits::get_parent(header), detail::uncast(header), key, comp); - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs. - //! - //! Effects: Returns an node_ptr to the first element that is greater - //! than "key" according to "comp" or "header" if that element does not exist. - //! - //! Complexity: Logarithmic. - //! - //! Throws: If "comp" throws. - template - static node_ptr upper_bound - (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp) - { - return upper_bound_loop(NodeTraits::get_parent(header), detail::uncast(header), key, comp); - } - - //! Requires: "header" must be the header node of a tree. - //! "commit_data" must have been obtained from a previous call to - //! "insert_unique_check". No objects should have been inserted or erased - //! from the set between the "insert_unique_check" that filled "commit_data" - //! and the call to "insert_commit". - //! - //! - //! Effects: Inserts new_node in the set using the information obtained - //! from the "commit_data" that a previous "insert_check" filled. - //! - //! Complexity: Constant time. - //! - //! Throws: Nothing. - //! - //! Notes: This function has only sense if a "insert_unique_check" has been - //! previously executed to fill "commit_data". No value should be inserted or - //! erased between the "insert_check" and "insert_commit" calls. - static void insert_unique_commit - (const node_ptr & header, const node_ptr & new_value, const insert_commit_data &commit_data) - { return insert_commit(header, new_value, commit_data); } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. NodePtrCompare compares KeyType with a node_ptr. - //! - //! Effects: Checks if there is an equivalent node to "key" in the - //! tree according to "comp" and obtains the needed information to realize - //! a constant-time node insertion if there is no equivalent node. - //! - //! Returns: If there is an equivalent value - //! returns a pair containing a node_ptr to the already present node - //! and false. If there is not equivalent key can be inserted returns true - //! in the returned pair's boolean and fills "commit_data" that is meant to - //! be used with the "insert_commit" function to achieve a constant-time - //! insertion function. - //! - //! Complexity: Average complexity is at most logarithmic. - //! - //! Throws: If "comp" throws. - //! - //! Notes: This function is used to improve performance when constructing - //! a node is expensive and the user does not want to have two equivalent nodes - //! in the tree: if there is an equivalent value - //! the constructed object must be discarded. Many times, the part of the - //! node that is used to impose the order is much cheaper to construct - //! than the node and this function offers the possibility to use that part - //! to check if the insertion will be successful. - //! - //! If the check is successful, the user can construct the node and use - //! "insert_commit" to insert the node in constant-time. This gives a total - //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). - //! - //! "commit_data" remains valid for a subsequent "insert_unique_commit" only - //! if no more objects are inserted or erased from the set. - template - static std::pair insert_unique_check - (const const_node_ptr & header, const KeyType &key - ,KeyNodePtrCompare comp, insert_commit_data &commit_data - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - std::size_t depth = 0; - node_ptr h(detail::uncast(header)); - node_ptr y(h); - node_ptr x(NodeTraits::get_parent(y)); - node_ptr prev = node_ptr(); - - //Find the upper bound, cache the previous value and if we should - //store it in the left or right node - bool left_child = true; - while(x){ - ++depth; - y = x; - x = (left_child = comp(key, x)) ? - NodeTraits::get_left(x) : (prev = y, NodeTraits::get_right(x)); - } - - if(pdepth) *pdepth = depth; - - //Since we've found the upper bound there is no other value with the same key if: - // - There is no previous node - // - The previous node is less than the key - if(!prev || comp(prev, key)){ - commit_data.link_left = left_child; - commit_data.node = y; - return std::pair(node_ptr(), true); - } - //If the previous value was not less than key, it means that it's equal - //(because we've checked the upper bound) - else{ - return std::pair(prev, false); - } - } - - //! Requires: "header" must be the header node of a tree. - //! KeyNodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. NodePtrCompare compares KeyType with a node_ptr. - //! "hint" is node from the "header"'s tree. - //! - //! Effects: Checks if there is an equivalent node to "key" in the - //! tree according to "comp" using "hint" as a hint to where it should be - //! inserted and obtains the needed information to realize - //! a constant-time node insertion if there is no equivalent node. - //! If "hint" is the upper_bound the function has constant time - //! complexity (two comparisons in the worst case). - //! - //! Returns: If there is an equivalent value - //! returns a pair containing a node_ptr to the already present node - //! and false. If there is not equivalent key can be inserted returns true - //! in the returned pair's boolean and fills "commit_data" that is meant to - //! be used with the "insert_commit" function to achieve a constant-time - //! insertion function. - //! - //! Complexity: Average complexity is at most logarithmic, but it is - //! amortized constant time if new_node should be inserted immediately before "hint". - //! - //! Throws: If "comp" throws. - //! - //! Notes: This function is used to improve performance when constructing - //! a node is expensive and the user does not want to have two equivalent nodes - //! in the tree: if there is an equivalent value - //! the constructed object must be discarded. Many times, the part of the - //! node that is used to impose the order is much cheaper to construct - //! than the node and this function offers the possibility to use that part - //! to check if the insertion will be successful. - //! - //! If the check is successful, the user can construct the node and use - //! "insert_commit" to insert the node in constant-time. This gives a total - //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). - //! - //! "commit_data" remains valid for a subsequent "insert_unique_commit" only - //! if no more objects are inserted or erased from the set. - template - static std::pair insert_unique_check - (const const_node_ptr & header, const node_ptr &hint, const KeyType &key - ,KeyNodePtrCompare comp, insert_commit_data &commit_data - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - //hint must be bigger than the key - if(hint == header || comp(key, hint)){ - node_ptr prev(hint); - //Previous value should be less than the key - if(hint == begin_node(header) || comp((prev = prev_node(hint)), key)){ - commit_data.link_left = unique(header) || !NodeTraits::get_left(hint); - commit_data.node = commit_data.link_left ? hint : prev; - if(pdepth){ - *pdepth = commit_data.node == header ? 0 : depth(commit_data.node) + 1; - } - return std::pair(node_ptr(), true); - } - } - //Hint was wrong, use hintless insertion - return insert_unique_check(header, key, comp, commit_data, pdepth); - } - - //! Requires: "header" must be the header node of a tree. - //! NodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. NodePtrCompare compares two node_ptrs. "hint" is node from - //! the "header"'s tree. - //! - //! Effects: Inserts new_node into the tree, using "hint" as a hint to - //! where it will be inserted. If "hint" is the upper_bound - //! the insertion takes constant time (two comparisons in the worst case). - //! - //! Complexity: Logarithmic in general, but it is amortized - //! constant time if new_node is inserted immediately before "hint". - //! - //! Throws: If "comp" throws. - template - static node_ptr insert_equal - (const node_ptr & h, const node_ptr & hint, const node_ptr & new_node, NodePtrCompare comp - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - insert_commit_data commit_data; - insert_equal_check(h, hint, new_node, comp, commit_data, pdepth); - insert_commit(h, new_node, commit_data); - return new_node; - } - - //! Requires: "h" must be the header node of a tree. - //! NodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. NodePtrCompare compares two node_ptrs. - //! - //! Effects: Inserts new_node into the tree before the upper bound - //! according to "comp". - //! - //! Complexity: Average complexity for insert element is at - //! most logarithmic. - //! - //! Throws: If "comp" throws. - template - static node_ptr insert_equal_upper_bound - (const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - insert_commit_data commit_data; - insert_equal_upper_bound_check(h, new_node, comp, commit_data, pdepth); - insert_commit(h, new_node, commit_data); - return new_node; - } - - //! Requires: "h" must be the header node of a tree. - //! NodePtrCompare is a function object that induces a strict weak - //! ordering compatible with the strict weak ordering used to create the - //! the tree. NodePtrCompare compares two node_ptrs. - //! - //! Effects: Inserts new_node into the tree before the lower bound - //! according to "comp". - //! - //! Complexity: Average complexity for insert element is at - //! most logarithmic. - //! - //! Throws: If "comp" throws. - template - static node_ptr insert_equal_lower_bound - (const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - insert_commit_data commit_data; - insert_equal_lower_bound_check(h, new_node, comp, commit_data, pdepth); - insert_commit(h, new_node, commit_data); - return new_node; - } - - //! Requires: "header" must be the header node of a tree. - //! "pos" must be a valid iterator or header (end) node. - //! "pos" must be an iterator pointing to the successor to "new_node" - //! once inserted according to the order of already inserted nodes. This function does not - //! check "pos" and this precondition must be guaranteed by the caller. - //! - //! Effects: Inserts new_node into the tree before "pos". - //! - //! Complexity: Constant-time. - //! - //! Throws: Nothing. - //! - //! Note: If "pos" is not the successor of the newly inserted "new_node" - //! tree invariants might be broken. - static node_ptr insert_before - (const node_ptr & header, const node_ptr & pos, const node_ptr & new_node - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - insert_commit_data commit_data; - insert_before_check(header, pos, commit_data, pdepth); - insert_commit(header, new_node, commit_data); - return new_node; - } - - //! Requires: "header" must be the header node of a tree. - //! "new_node" must be, according to the used ordering no less than the - //! greatest inserted key. - //! - //! Effects: Inserts new_node into the tree before "pos". - //! - //! Complexity: Constant-time. - //! - //! Throws: Nothing. - //! - //! Note: If "new_node" is less than the greatest inserted key - //! tree invariants are broken. This function is slightly faster than - //! using "insert_before". - static void push_back - (const node_ptr & header, const node_ptr & new_node - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - insert_commit_data commit_data; - push_back_check(header, commit_data, pdepth); - insert_commit(header, new_node, commit_data); - } - - //! Requires: "header" must be the header node of a tree. - //! "new_node" must be, according to the used ordering, no greater than the - //! lowest inserted key. - //! - //! Effects: Inserts new_node into the tree before "pos". - //! - //! Complexity: Constant-time. - //! - //! Throws: Nothing. - //! - //! Note: If "new_node" is greater than the lowest inserted key - //! tree invariants are broken. This function is slightly faster than - //! using "insert_before". - static void push_front - (const node_ptr & header, const node_ptr & new_node - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - insert_commit_data commit_data; - push_front_check(header, commit_data, pdepth); - insert_commit(header, new_node, commit_data); - } - - //! Requires: 'node' can't be a header node. - //! - //! Effects: Calculates the depth of a node: the depth of a - //! node is the length (number of edges) of the path from the root - //! to that node. (The root node is at depth 0.) - //! - //! Complexity: Logarithmic to the number of nodes in the tree. - //! - //! Throws: Nothing. - static std::size_t depth(const_node_ptr node) - { - std::size_t depth = 0; - node_ptr p_parent; - while(node != NodeTraits::get_parent(p_parent = NodeTraits::get_parent(node))){ - ++depth; - node = p_parent; - } - return depth; - } - - //! Requires: "cloner" must be a function - //! object taking a node_ptr and returning a new cloned node of it. "disposer" must - //! take a node_ptr and shouldn't throw. - //! - //! Effects: First empties target tree calling - //! void disposer::operator()(const node_ptr &) for every node of the tree - //! except the header. - //! - //! Then, duplicates the entire tree pointed by "source_header" cloning each - //! source node with node_ptr Cloner::operator()(const node_ptr &) to obtain - //! the nodes of the target tree. If "cloner" throws, the cloned target nodes - //! are disposed using void disposer(const node_ptr &). - //! - //! Complexity: Linear to the number of element of the source tree plus the. - //! number of elements of tree target tree when calling this function. - //! - //! Throws: If cloner functor throws. If this happens target nodes are disposed. - template - static void clone - (const const_node_ptr & source_header, const node_ptr & target_header, Cloner cloner, Disposer disposer) - { - if(!unique(target_header)){ - clear_and_dispose(target_header, disposer); - } - - node_ptr leftmost, rightmost; - node_ptr new_root = clone_subtree - (source_header, target_header, cloner, disposer, leftmost, rightmost); - - //Now update header node - NodeTraits::set_parent(target_header, new_root); - NodeTraits::set_left (target_header, leftmost); - NodeTraits::set_right (target_header, rightmost); - } - - //! Requires: header must be the header of a tree, z a node - //! of that tree and z != header. - //! - //! Effects: Erases node "z" from the tree with header "header". - //! - //! Complexity: Amortized constant time. - //! - //! Throws: Nothing. - static void erase(const node_ptr & header, const node_ptr & z) - { - data_for_rebalance ignored; - erase_impl(header, z, ignored); - } - - //! Requires: node is a tree node but not the header. - //! - //! Effects: Unlinks the node and rebalances the tree. - //! - //! Complexity: Average complexity is constant time. - //! - //! Throws: Nothing. - static void unlink(const node_ptr & node) - { - node_ptr x = NodeTraits::get_parent(node); - if(x){ - while(!is_header(x)) - x = NodeTraits::get_parent(x); - erase(x, node); - } - } - - //! Requires: header must be the header of a tree. - //! - //! Effects: Rebalances the tree. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear. - static void rebalance(const node_ptr & header) - { - node_ptr root = NodeTraits::get_parent(header); - if(root){ - rebalance_subtree(root); - } - } - - //! Requires: old_root is a node of a tree. It shall not be null. - //! - //! Effects: Rebalances the subtree rooted at old_root. - //! - //! Returns: The new root of the subtree. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear. - static node_ptr rebalance_subtree(const node_ptr & old_root) - { - //Taken from: - //"Tree rebalancing in optimal time and space" - //Quentin F. Stout and Bette L. Warren - - //To avoid irregularities in the algorithm (old_root can be a - //left or right child or even the root of the tree) just put the - //root as the right child of its parent. Before doing this backup - //information to restore the original relationship after - //the algorithm is applied. - node_ptr super_root = NodeTraits::get_parent(old_root); - BOOST_INTRUSIVE_INVARIANT_ASSERT(super_root); - - //Get root info - node_ptr super_root_right_backup = NodeTraits::get_right(super_root); - bool super_root_is_header = NodeTraits::get_parent(super_root) == old_root; - bool old_root_is_right = is_right_child(old_root); - NodeTraits::set_right(super_root, old_root); - - std::size_t size; - subtree_to_vine(super_root, size); - vine_to_subtree(super_root, size); - node_ptr new_root = NodeTraits::get_right(super_root); - - //Recover root - if(super_root_is_header){ - NodeTraits::set_right(super_root, super_root_right_backup); - NodeTraits::set_parent(super_root, new_root); - } - else if(old_root_is_right){ - NodeTraits::set_right(super_root, new_root); - } - else{ - NodeTraits::set_right(super_root, super_root_right_backup); - NodeTraits::set_left(super_root, new_root); - } - return new_root; - } - - protected: - //! Requires: node is a node of the tree but it's not the header. - //! - //! Effects: Returns the number of nodes of the subtree. - //! - //! Complexity: Linear time. - //! - //! Throws: Nothing. - static std::size_t subtree_size(const const_node_ptr & subtree) - { - std::size_t count = 0; - if (subtree){ - node_ptr n = detail::uncast(subtree); - node_ptr m = NodeTraits::get_left(n); - while(m){ - n = m; - m = NodeTraits::get_left(n); - } - - while(1){ - ++count; - node_ptr n_right(NodeTraits::get_right(n)); - if(n_right){ - n = n_right; - m = NodeTraits::get_left(n); - while(m){ - n = m; - m = NodeTraits::get_left(n); - } - } - else { - do{ - if (n == subtree){ - return count; - } - m = n; - n = NodeTraits::get_parent(n); - }while(NodeTraits::get_left(n) != m); - } - } - } - return count; - } - - //! Requires: p is a node of a tree. - //! - //! Effects: Returns true if p is a left child. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - static bool is_left_child(const node_ptr & p) - { return NodeTraits::get_left(NodeTraits::get_parent(p)) == p; } - - //! Requires: p is a node of a tree. - //! - //! Effects: Returns true if p is a right child. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - static bool is_right_child(const node_ptr & p) - { return NodeTraits::get_right(NodeTraits::get_parent(p)) == p; } - - template - static void erase(const node_ptr & header, const node_ptr & z, F z_and_successor_fixup, data_for_rebalance &info) - { - erase_impl(header, z, info); - if(info.y != z){ - z_and_successor_fixup(z, info.y); - } - } - - //Fix header and own's parent data when replacing x with own, providing own's old data with parent - static void replace_own_impl(const node_ptr & own, const node_ptr & x, const node_ptr & header, const node_ptr & own_parent, bool own_was_left) - { - if(NodeTraits::get_parent(header) == own) - NodeTraits::set_parent(header, x); - else if(own_was_left) - NodeTraits::set_left(own_parent, x); - else - NodeTraits::set_right(own_parent, x); - } - - //Fix header and own's parent data when replacing x with own, supposing own - //links with its parent are still ok - static void replace_own(const node_ptr & own, const node_ptr & x, const node_ptr & header) - { - node_ptr own_parent(NodeTraits::get_parent(own)); - bool own_is_left(NodeTraits::get_left(own_parent) == own); - replace_own_impl(own, x, header, own_parent, own_is_left); - } - - // rotate parent p to left (no header and p's parent fixup) - static node_ptr rotate_left(const node_ptr & p) - { - node_ptr x(NodeTraits::get_right(p)); - node_ptr x_left(NodeTraits::get_left(x)); - NodeTraits::set_right(p, x_left); - if(x_left){ - NodeTraits::set_parent(x_left, p); - } - NodeTraits::set_left(x, p); - NodeTraits::set_parent(p, x); - return x; - } - - // rotate parent p to left (with header and p's parent fixup) - static void rotate_left(const node_ptr & p, const node_ptr & header) - { - bool p_was_left(is_left_child(p)); - node_ptr p_old_parent(NodeTraits::get_parent(p)); - node_ptr x(rotate_left(p)); - NodeTraits::set_parent(x, p_old_parent); - replace_own_impl(p, x, header, p_old_parent, p_was_left); - } - - // rotate parent p to right (no header and p's parent fixup) - static node_ptr rotate_right(const node_ptr & p) - { - node_ptr x(NodeTraits::get_left(p)); - node_ptr x_right(NodeTraits::get_right(x)); - NodeTraits::set_left(p, x_right); - if(x_right){ - NodeTraits::set_parent(x_right, p); - } - NodeTraits::set_right(x, p); - NodeTraits::set_parent(p, x); - return x; - } - - // rotate parent p to right (with header and p's parent fixup) - static void rotate_right(const node_ptr & p, const node_ptr & header) - { - bool p_was_left(is_left_child(p)); - node_ptr p_old_parent(NodeTraits::get_parent(p)); - node_ptr x(rotate_right(p)); - NodeTraits::set_parent(x, p_old_parent); - replace_own_impl(p, x, header, p_old_parent, p_was_left); - } - - static void insert_before_check - (const node_ptr &header, const node_ptr & pos - , insert_commit_data &commit_data - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - node_ptr prev(pos); - if(pos != NodeTraits::get_left(header)) - prev = prev_node(pos); - bool link_left = unique(header) || !NodeTraits::get_left(pos); - commit_data.link_left = link_left; - commit_data.node = link_left ? pos : prev; - if(pdepth){ - *pdepth = commit_data.node == header ? 0 : depth(commit_data.node) + 1; - } - } - - static void push_back_check - (const node_ptr & header, insert_commit_data &commit_data - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - node_ptr prev(NodeTraits::get_right(header)); - if(pdepth){ - *pdepth = prev == header ? 0 : depth(prev) + 1; - } - commit_data.link_left = false; - commit_data.node = prev; - } - - static void push_front_check - (const node_ptr & header, insert_commit_data &commit_data - #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED - , std::size_t *pdepth = 0 - #endif - ) - { - node_ptr pos(NodeTraits::get_left(header)); - if(pdepth){ - *pdepth = pos == header ? 0 : depth(pos) + 1; - } - commit_data.link_left = true; - commit_data.node = pos; - } - - template - static void insert_equal_check - (const node_ptr &header, const node_ptr & hint, const node_ptr & new_node, NodePtrCompare comp - , insert_commit_data &commit_data - /// @cond - , std::size_t *pdepth = 0 - /// @endcond - ) - { - if(hint == header || !comp(hint, new_node)){ - node_ptr prev(hint); - if(hint == NodeTraits::get_left(header) || - !comp(new_node, (prev = prev_node(hint)))){ - bool link_left = unique(header) || !NodeTraits::get_left(hint); - commit_data.link_left = link_left; - commit_data.node = link_left ? hint : prev; - if(pdepth){ - *pdepth = commit_data.node == header ? 0 : depth(commit_data.node) + 1; - } - } - else{ - insert_equal_upper_bound_check(header, new_node, comp, commit_data, pdepth); - } - } - else{ - insert_equal_lower_bound_check(header, new_node, comp, commit_data, pdepth); - } - } - - template - static void insert_equal_upper_bound_check - (const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp, insert_commit_data & commit_data, std::size_t *pdepth = 0) - { insert_equal_check_impl(true, h, new_node, comp, commit_data, pdepth); } - - template - static void insert_equal_lower_bound_check - (const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp, insert_commit_data & commit_data, std::size_t *pdepth = 0) - { insert_equal_check_impl(false, h, new_node, comp, commit_data, pdepth); } - - static void insert_commit - (const node_ptr & header, const node_ptr & new_node, const insert_commit_data &commit_data) - { - //Check if commit_data has not been initialized by a insert_unique_check call. - BOOST_INTRUSIVE_INVARIANT_ASSERT(commit_data.node != node_ptr()); - node_ptr parent_node(commit_data.node); - if(parent_node == header){ - NodeTraits::set_parent(header, new_node); - NodeTraits::set_right(header, new_node); - NodeTraits::set_left(header, new_node); - } - else if(commit_data.link_left){ - NodeTraits::set_left(parent_node, new_node); - if(parent_node == NodeTraits::get_left(header)) - NodeTraits::set_left(header, new_node); - } - else{ - NodeTraits::set_right(parent_node, new_node); - if(parent_node == NodeTraits::get_right(header)) - NodeTraits::set_right(header, new_node); - } - NodeTraits::set_parent(new_node, parent_node); - NodeTraits::set_right(new_node, node_ptr()); - NodeTraits::set_left(new_node, node_ptr()); - } - - private: - static void subtree_to_vine(node_ptr vine_tail, std::size_t &size) - { - //Inspired by LibAVL: - //It uses a clever optimization for trees with parent pointers. - //No parent pointer is updated when transforming a tree to a vine as - //most of them will be overriten during compression rotations. - //A final pass must be made after the rebalancing to updated those - //pointers not updated by tree_to_vine + compression calls - std::size_t len = 0; - node_ptr remainder = NodeTraits::get_right(vine_tail); - while(remainder){ - node_ptr tempptr = NodeTraits::get_left(remainder); - if(!tempptr){ //move vine-tail down one - vine_tail = remainder; - remainder = NodeTraits::get_right(remainder); - ++len; - } - else{ //rotate - NodeTraits::set_left(remainder, NodeTraits::get_right(tempptr)); - NodeTraits::set_right(tempptr, remainder); - remainder = tempptr; - NodeTraits::set_right(vine_tail, tempptr); - } - } - size = len; - } - - static void compress_subtree(node_ptr scanner, std::size_t count) - { - while(count--){ //compress "count" spine nodes in the tree with pseudo-root scanner - node_ptr child = NodeTraits::get_right(scanner); - node_ptr child_right = NodeTraits::get_right(child); - NodeTraits::set_right(scanner, child_right); - //Avoid setting the parent of child_right - scanner = child_right; - node_ptr scanner_left = NodeTraits::get_left(scanner); - NodeTraits::set_right(child, scanner_left); - if(scanner_left) - NodeTraits::set_parent(scanner_left, child); - NodeTraits::set_left(scanner, child); - NodeTraits::set_parent(child, scanner); - } - } - - static void vine_to_subtree(const node_ptr & super_root, std::size_t count) - { - std::size_t leaf_nodes = count + 1 - ((std::size_t) 1 << detail::floor_log2(count + 1)); - compress_subtree(super_root, leaf_nodes); //create deepest leaves - std::size_t vine_nodes = count - leaf_nodes; - while(vine_nodes > 1){ - vine_nodes /= 2; - compress_subtree(super_root, vine_nodes); - } - - //Update parents of nodes still in the in the original vine line - //as those have not been updated by subtree_to_vine or compress_subtree - for ( node_ptr q = super_root, p = NodeTraits::get_right(super_root) - ; p - ; q = p, p = NodeTraits::get_right(p)){ - NodeTraits::set_parent(p, q); - } - } - - //! Requires: "n" must be a node inserted in a tree. - //! - //! Effects: Returns a pointer to the header node of the tree. - //! - //! Complexity: Logarithmic. - //! - //! Throws: Nothing. - static node_ptr get_root(const node_ptr & node) - { - BOOST_INTRUSIVE_INVARIANT_ASSERT((!inited(node))); - node_ptr x = NodeTraits::get_parent(node); - if(x){ - while(!is_header(x)){ - x = NodeTraits::get_parent(x); - } - return x; - } - else{ - return node; - } - } - - template - static node_ptr clone_subtree - (const const_node_ptr &source_parent, const node_ptr &target_parent - , Cloner cloner, Disposer disposer - , node_ptr &leftmost_out, node_ptr &rightmost_out - ) - { - node_ptr target_sub_root = target_parent; - node_ptr source_root = NodeTraits::get_parent(source_parent); - if(!source_root){ - leftmost_out = rightmost_out = source_root; - } - else{ - //We'll calculate leftmost and rightmost nodes while iterating - node_ptr current = source_root; - node_ptr insertion_point = target_sub_root = cloner(current); - - //We'll calculate leftmost and rightmost nodes while iterating - node_ptr leftmost = target_sub_root; - node_ptr rightmost = target_sub_root; - - //First set the subroot - NodeTraits::set_left(target_sub_root, node_ptr()); - NodeTraits::set_right(target_sub_root, node_ptr()); - NodeTraits::set_parent(target_sub_root, target_parent); - - dispose_subtree_disposer rollback(disposer, target_sub_root); - while(true) { - //First clone left nodes - if( NodeTraits::get_left(current) && - !NodeTraits::get_left(insertion_point)) { - current = NodeTraits::get_left(current); - node_ptr temp = insertion_point; - //Clone and mark as leaf - insertion_point = cloner(current); - NodeTraits::set_left (insertion_point, node_ptr()); - NodeTraits::set_right (insertion_point, node_ptr()); - //Insert left - NodeTraits::set_parent(insertion_point, temp); - NodeTraits::set_left (temp, insertion_point); - //Update leftmost - if(rightmost == target_sub_root) - leftmost = insertion_point; - } - //Then clone right nodes - else if( NodeTraits::get_right(current) && - !NodeTraits::get_right(insertion_point)){ - current = NodeTraits::get_right(current); - node_ptr temp = insertion_point; - //Clone and mark as leaf - insertion_point = cloner(current); - NodeTraits::set_left (insertion_point, node_ptr()); - NodeTraits::set_right (insertion_point, node_ptr()); - //Insert right - NodeTraits::set_parent(insertion_point, temp); - NodeTraits::set_right (temp, insertion_point); - //Update rightmost - rightmost = insertion_point; - } - //If not, go up - else if(current == source_root){ - break; - } - else{ - //Branch completed, go up searching more nodes to clone - current = NodeTraits::get_parent(current); - insertion_point = NodeTraits::get_parent(insertion_point); - } - } - rollback.release(); - leftmost_out = leftmost; - rightmost_out = rightmost; - } - return target_sub_root; - } - - template - static void dispose_subtree(node_ptr x, Disposer disposer) - { - while (x){ - node_ptr save(NodeTraits::get_left(x)); - if (save) { - // Right rotation - NodeTraits::set_left(x, NodeTraits::get_right(save)); - NodeTraits::set_right(save, x); - } - else { - save = NodeTraits::get_right(x); - init(x); - disposer(x); - } - x = save; - } - } - - template - static node_ptr lower_bound_loop - (node_ptr x, node_ptr y, const KeyType &key, KeyNodePtrCompare comp) - { - while(x){ - if(comp(x, key)){ - x = NodeTraits::get_right(x); - } - else{ - y = x; - x = NodeTraits::get_left(x); - } - } - return y; - } - - template - static node_ptr upper_bound_loop - (node_ptr x, node_ptr y, const KeyType &key, KeyNodePtrCompare comp) - { - while(x){ - if(comp(key, x)){ - y = x; - x = NodeTraits::get_left(x); - } - else{ - x = NodeTraits::get_right(x); - } - } - return y; - } - - - template - static void insert_equal_check_impl - (bool upper, const node_ptr & h, const node_ptr & new_node, NodePtrCompare comp, insert_commit_data & commit_data, std::size_t *pdepth = 0) - { - std::size_t depth = 0; - node_ptr y(h); - node_ptr x(NodeTraits::get_parent(y)); - bool link_left; - - if(upper){ - while(x){ - ++depth; - y = x; - x = comp(new_node, x) ? - NodeTraits::get_left(x) : NodeTraits::get_right(x); - } - link_left = (y == h) || comp(new_node, y); - } - else{ - while(x){ - ++depth; - y = x; - x = !comp(x, new_node) ? - NodeTraits::get_left(x) : NodeTraits::get_right(x); - } - link_left = (y == h) || !comp(y, new_node); - } - - commit_data.link_left = link_left; - commit_data.node = y; - if(pdepth) *pdepth = depth; - } - - static void erase_impl(const node_ptr & header, const node_ptr & z, data_for_rebalance &info) - { - node_ptr y(z); - node_ptr x; - node_ptr x_parent = node_ptr(); - node_ptr z_left(NodeTraits::get_left(z)); - node_ptr z_right(NodeTraits::get_right(z)); - if(!z_left){ - x = z_right; // x might be null. - } - else if(!z_right){ // z has exactly one non-null child. y == z. - x = z_left; // x is not null. - } - else{ - // find z's successor - y = bstree_algorithms::minimum (z_right); - x = NodeTraits::get_right(y); // x might be null. - } - - if(y != z){ - // relink y in place of z. y is z's successor - NodeTraits::set_parent(NodeTraits::get_left(z), y); - NodeTraits::set_left(y, NodeTraits::get_left(z)); - if(y != NodeTraits::get_right(z)){ - x_parent = NodeTraits::get_parent(y); - if(x) - NodeTraits::set_parent(x, x_parent); - NodeTraits::set_left(x_parent, x); // y must be a child of left_ - NodeTraits::set_right(y, NodeTraits::get_right(z)); - NodeTraits::set_parent(NodeTraits::get_right(z), y); - } - else - x_parent = y; - bstree_algorithms::replace_own (z, y, header); - NodeTraits::set_parent(y, NodeTraits::get_parent(z)); - } - else { // y == z --> z has only one child, or void - x_parent = NodeTraits::get_parent(z); - if(x) - NodeTraits::set_parent(x, x_parent); - bstree_algorithms::replace_own (z, x, header); - if(NodeTraits::get_left(header) == z){ - NodeTraits::set_left(header, !NodeTraits::get_right(z) ? // z->get_left() must be null also - NodeTraits::get_parent(z) : // makes leftmost == header if z == root - bstree_algorithms::minimum (x)); - } - if(NodeTraits::get_right(header) == z){ - NodeTraits::set_right(header, !NodeTraits::get_left(z) ? // z->get_right() must be null also - NodeTraits::get_parent(z) : // makes rightmost == header if z == root - bstree_algorithms::maximum(x)); - } - } - - info.x = x; - info.x_parent = x_parent; - info.y = y; - } -}; - -/// @cond - -template -struct get_algo -{ - typedef bstree_algorithms type; -}; - -/// @endcond - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_BSTREE_ALGORITHMS_HPP diff --git a/utils/boost_idb/boost/intrusive/circular_list_algorithms.hpp b/utils/boost_idb/boost/intrusive/circular_list_algorithms.hpp deleted file mode 100644 index 9d6213a5..00000000 --- a/utils/boost_idb/boost/intrusive/circular_list_algorithms.hpp +++ /dev/null @@ -1,424 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Olaf Krzikalla 2004-2006. -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_CIRCULAR_LIST_ALGORITHMS_HPP -#define BOOST_INTRUSIVE_CIRCULAR_LIST_ALGORITHMS_HPP - -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -//! circular_list_algorithms provides basic algorithms to manipulate nodes -//! forming a circular doubly linked list. An empty circular list is formed by a node -//! whose pointers point to itself. -//! -//! circular_list_algorithms is configured with a NodeTraits class, which encapsulates the -//! information about the node to be manipulated. NodeTraits must support the -//! following interface: -//! -//! Typedefs: -//! -//! node: The type of the node that forms the circular list -//! -//! node_ptr: A pointer to a node -//! -//! const_node_ptr: A pointer to a const node -//! -//! Static functions: -//! -//! static node_ptr get_previous(const_node_ptr n); -//! -//! static void set_previous(node_ptr n, node_ptr prev); -//! -//! static node_ptr get_next(const_node_ptr n); -//! -//! static void set_next(node_ptr n, node_ptr next); -template -class circular_list_algorithms -{ - public: - typedef typename NodeTraits::node node; - typedef typename NodeTraits::node_ptr node_ptr; - typedef typename NodeTraits::const_node_ptr const_node_ptr; - typedef NodeTraits node_traits; - - //! Effects: Constructs an non-used list element, so that - //! inited(this_node) == true - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void init(const node_ptr &this_node) - { - NodeTraits::set_next(this_node, node_ptr()); - NodeTraits::set_previous(this_node, node_ptr()); - } - - //! Effects: Returns true is "this_node" is in a non-used state - //! as if it was initialized by the "init" function. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static bool inited(const const_node_ptr &this_node) - { return !NodeTraits::get_next(this_node); } - - //! Effects: Constructs an empty list, making this_node the only - //! node of the circular list: - //! NodeTraits::get_next(this_node) == NodeTraits::get_previous(this_node) - //! == this_node. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void init_header(const node_ptr &this_node) - { - NodeTraits::set_next(this_node, this_node); - NodeTraits::set_previous(this_node, this_node); - } - - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Returns true is "this_node" is the only node of a circular list: - //! return NodeTraits::get_next(this_node) == this_node - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static bool unique(const const_node_ptr &this_node) - { - node_ptr next = NodeTraits::get_next(this_node); - return !next || next == this_node; - } - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Returns the number of nodes in a circular list. If the circular list - //! is empty, returns 1. - //! - //! Complexity: Linear - //! - //! Throws: Nothing. - static std::size_t count(const const_node_ptr &this_node) - { - std::size_t result = 0; - const_node_ptr p = this_node; - do{ - p = NodeTraits::get_next(p); - ++result; - }while (p != this_node); - return result; - } - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Unlinks the node from the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static node_ptr unlink(const node_ptr &this_node) - { - node_ptr next(NodeTraits::get_next(this_node)); - if(next){ - node_ptr prev(NodeTraits::get_previous(this_node)); - NodeTraits::set_next(prev, next); - NodeTraits::set_previous(next, prev); - return next; - } - else{ - return this_node; - } - } - - //! Requires: b and e must be nodes of the same circular list or an empty range. - //! - //! Effects: Unlinks the node [b, e) from the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void unlink(const node_ptr &b, const node_ptr &e) - { - if (b != e) { - node_ptr prevb(NodeTraits::get_previous(b)); - NodeTraits::set_previous(e, prevb); - NodeTraits::set_next(prevb, e); - } - } - - //! Requires: nxt_node must be a node of a circular list. - //! - //! Effects: Links this_node before nxt_node in the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void link_before(const node_ptr &nxt_node, const node_ptr &this_node) - { - node_ptr prev(NodeTraits::get_previous(nxt_node)); - NodeTraits::set_previous(this_node, prev); - NodeTraits::set_next(this_node, nxt_node); - //nxt_node might be an alias for prev->next_ - //so use it before NodeTraits::set_next(prev, ...) - //is called and the reference changes it's value - NodeTraits::set_previous(nxt_node, this_node); - NodeTraits::set_next(prev, this_node); - } - - //! Requires: prev_node must be a node of a circular list. - //! - //! Effects: Links this_node after prev_node in the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void link_after(const node_ptr &prev_node, const node_ptr &this_node) - { - node_ptr next(NodeTraits::get_next(prev_node)); - NodeTraits::set_previous(this_node, prev_node); - NodeTraits::set_next(this_node, next); - //prev_node might be an alias for next->next_ - //so use it before update it before NodeTraits::set_previous(next, ...) - //is called and the reference changes it's value - NodeTraits::set_next(prev_node, this_node); - NodeTraits::set_previous(next, this_node); - } - - //! Requires: this_node and other_node must be nodes inserted - //! in circular lists or be empty circular lists. - //! - //! Effects: Swaps the position of the nodes: this_node is inserted in - //! other_nodes position in the second circular list and the other_node is inserted - //! in this_node's position in the first circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. -/* - static void swap_nodes(const node_ptr &this_node, const node_ptr &other_node) - { - - if (other_node == this_node) - return; - bool empty1 = unique(this_node); - bool empty2 = unique(other_node); - - node_ptr next_this(NodeTraits::get_next(this_node)); - node_ptr prev_this(NodeTraits::get_previous(this_node)); - node_ptr next_other(NodeTraits::get_next(other_node)); - node_ptr prev_other(NodeTraits::get_previous(other_node)); - - //Do the swap - NodeTraits::set_next(this_node, next_other); - NodeTraits::set_next(other_node, next_this); - - NodeTraits::set_previous(this_node, prev_other); - NodeTraits::set_previous(other_node, prev_this); - - if (empty2){ - init(this_node); - } - else{ - NodeTraits::set_next(prev_other, this_node); - NodeTraits::set_previous(next_other, this_node); - } - if (empty1){ - init(other_node); - } - else{ - NodeTraits::set_next(prev_this, other_node); - NodeTraits::set_previous(next_this, other_node); - } - } -*/ - - //Watanabe version - private: - static void swap_prev(const node_ptr &this_node, const node_ptr &other_node) - { - node_ptr temp(NodeTraits::get_previous(this_node)); - NodeTraits::set_previous(this_node, NodeTraits::get_previous(other_node)); - NodeTraits::set_previous(other_node, temp); - } - static void swap_next(const node_ptr &this_node, const node_ptr &other_node) - { - node_ptr temp(NodeTraits::get_next(this_node)); - NodeTraits::set_next(this_node, NodeTraits::get_next(other_node)); - NodeTraits::set_next(other_node, temp); - } - - public: - static void swap_nodes(const node_ptr &this_node, const node_ptr &other_node) - { - if (other_node == this_node) - return; - bool this_inited = inited(this_node); - bool other_inited = inited(other_node); - if(this_inited){ - init_header(this_node); - } - if(other_inited){ - init_header(other_node); - } - - node_ptr next_this(NodeTraits::get_next(this_node)); - node_ptr prev_this(NodeTraits::get_previous(this_node)); - node_ptr next_other(NodeTraits::get_next(other_node)); - node_ptr prev_other(NodeTraits::get_previous(other_node)); - //these first two swaps must happen before the other two - swap_prev(next_this, next_other); - swap_next(prev_this, prev_other); - swap_next(this_node, other_node); - swap_prev(this_node, other_node); - - if(this_inited){ - init(other_node); - } - if(other_inited){ - init(this_node); - } - } - - //! Requires: b and e must be nodes of the same circular list or an empty range. - //! and p must be a node of a different circular list or may not be an iterator in - // [b, e). - //! - //! Effects: Removes the nodes from [b, e) range from their circular list and inserts - //! them before p in p's circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void transfer(const node_ptr &p, const node_ptr &b, const node_ptr &e) - { - if (b != e) { - node_ptr prev_p(NodeTraits::get_previous(p)); - node_ptr prev_b(NodeTraits::get_previous(b)); - node_ptr prev_e(NodeTraits::get_previous(e)); - NodeTraits::set_next(prev_e, p); - NodeTraits::set_previous(p, prev_e); - NodeTraits::set_next(prev_b, e); - NodeTraits::set_previous(e, prev_b); - NodeTraits::set_next(prev_p, b); - NodeTraits::set_previous(b, prev_p); - } - } - - //! Requires: i must a node of a circular list - //! and p must be a node of a different circular list. - //! - //! Effects: Removes the node i from its circular list and inserts - //! it before p in p's circular list. - //! If p == i or p == NodeTraits::get_next(i), this function is a null operation. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void transfer(const node_ptr &p, const node_ptr &i) - { - node_ptr n(NodeTraits::get_next(i)); - if(n != p && i != p){ - node_ptr prev_p(NodeTraits::get_previous(p)); - node_ptr prev_i(NodeTraits::get_previous(i)); - NodeTraits::set_next(prev_p, i); - NodeTraits::set_previous(i, prev_p); - NodeTraits::set_next(i, p); - NodeTraits::set_previous(p, i); - NodeTraits::set_previous(n, prev_i); - NodeTraits::set_next(prev_i, n); - - } - } - - //! Effects: Reverses the order of elements in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: This function is linear time. - static void reverse(const node_ptr &p) - { - node_ptr f(NodeTraits::get_next(p)); - node_ptr i(NodeTraits::get_next(f)), e(p); - - while(i != e) { - node_ptr n = i; - i = NodeTraits::get_next(i); - transfer(f, n, i); - f = n; - } - } - - //! Effects: Moves the node p n positions towards the end of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of moved positions. - static void move_backwards(const node_ptr &p, std::size_t n) - { - //Null shift, nothing to do - if(!n) return; - node_ptr first = NodeTraits::get_next(p); - //size() == 0 or 1, nothing to do - if(first == NodeTraits::get_previous(p)) return; - unlink(p); - //Now get the new first node - while(n--){ - first = NodeTraits::get_next(first); - } - link_before(first, p); - } - - //! Effects: Moves the node p n positions towards the beginning of the list. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of moved positions. - static void move_forward(const node_ptr &p, std::size_t n) - { - //Null shift, nothing to do - if(!n) return; - node_ptr last = NodeTraits::get_previous(p); - //size() == 0 or 1, nothing to do - if(last == NodeTraits::get_next(p)) return; - - unlink(p); - //Now get the new last node - while(n--){ - last = NodeTraits::get_previous(last); - } - link_after(last, p); - } -}; - -/// @cond - -template -struct get_algo -{ - typedef circular_list_algorithms type; -}; - -/// @endcond - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_CIRCULAR_LIST_ALGORITHMS_HPP diff --git a/utils/boost_idb/boost/intrusive/circular_slist_algorithms.hpp b/utils/boost_idb/boost/intrusive/circular_slist_algorithms.hpp deleted file mode 100644 index fb5f75ab..00000000 --- a/utils/boost_idb/boost/intrusive/circular_slist_algorithms.hpp +++ /dev/null @@ -1,415 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Olaf Krzikalla 2004-2006. -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_CIRCULAR_SLIST_ALGORITHMS_HPP -#define BOOST_INTRUSIVE_CIRCULAR_SLIST_ALGORITHMS_HPP - -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -//! circular_slist_algorithms provides basic algorithms to manipulate nodes -//! forming a circular singly linked list. An empty circular list is formed by a node -//! whose pointer to the next node points to itself. -//! -//! circular_slist_algorithms is configured with a NodeTraits class, which encapsulates the -//! information about the node to be manipulated. NodeTraits must support the -//! following interface: -//! -//! Typedefs: -//! -//! node: The type of the node that forms the circular list -//! -//! node_ptr: A pointer to a node -//! -//! const_node_ptr: A pointer to a const node -//! -//! Static functions: -//! -//! static node_ptr get_next(const_node_ptr n); -//! -//! static void set_next(node_ptr n, node_ptr next); -template -class circular_slist_algorithms - /// @cond - : public detail::common_slist_algorithms - /// @endcond -{ - /// @cond - typedef detail::common_slist_algorithms base_t; - /// @endcond - public: - typedef typename NodeTraits::node node; - typedef typename NodeTraits::node_ptr node_ptr; - typedef typename NodeTraits::const_node_ptr const_node_ptr; - typedef NodeTraits node_traits; - - #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - - //! Effects: Constructs an non-used list element, putting the next - //! pointer to null: - //! NodeTraits::get_next(this_node) == node_ptr() - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void init(node_ptr this_node); - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Returns true is "this_node" is the only node of a circular list: - //! or it's a not inserted node: - //! return node_ptr() == NodeTraits::get_next(this_node) || NodeTraits::get_next(this_node) == this_node - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static bool unique(const_node_ptr this_node); - - //! Effects: Returns true is "this_node" has the same state as - //! if it was inited using "init(node_ptr)" - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static bool inited(const_node_ptr this_node); - - //! Requires: prev_node must be in a circular list or be an empty circular list. - //! - //! Effects: Unlinks the next node of prev_node from the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void unlink_after(node_ptr prev_node); - - //! Requires: prev_node and last_node must be in a circular list - //! or be an empty circular list. - //! - //! Effects: Unlinks the range (prev_node, last_node) from the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void unlink_after(node_ptr prev_node, node_ptr last_node); - - //! Requires: prev_node must be a node of a circular list. - //! - //! Effects: Links this_node after prev_node in the circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void link_after(node_ptr prev_node, node_ptr this_node); - - //! Requires: b and e must be nodes of the same circular list or an empty range. - //! and p must be a node of a different circular list. - //! - //! Effects: Removes the nodes from (b, e] range from their circular list and inserts - //! them after p in p's circular list. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void transfer_after(node_ptr p, node_ptr b, node_ptr e); - - #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) - - //! Effects: Constructs an empty list, making this_node the only - //! node of the circular list: - //! NodeTraits::get_next(this_node) == this_node. - //! - //! Complexity: Constant - //! - //! Throws: Nothing. - static void init_header(const node_ptr &this_node) - { NodeTraits::set_next(this_node, this_node); } - - //! Requires: this_node and prev_init_node must be in the same circular list. - //! - //! Effects: Returns the previous node of this_node in the circular list starting. - //! the search from prev_init_node. The first node checked for equality - //! is NodeTraits::get_next(prev_init_node). - //! - //! Complexity: Linear to the number of elements between prev_init_node and this_node. - //! - //! Throws: Nothing. - static node_ptr get_previous_node(const node_ptr &prev_init_node, const node_ptr &this_node) - { return base_t::get_previous_node(prev_init_node, this_node); } - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Returns the previous node of this_node in the circular list. - //! - //! Complexity: Linear to the number of elements in the circular list. - //! - //! Throws: Nothing. - static node_ptr get_previous_node(const node_ptr & this_node) - { return base_t::get_previous_node(this_node, this_node); } - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Returns the previous node of the previous node of this_node in the circular list. - //! - //! Complexity: Linear to the number of elements in the circular list. - //! - //! Throws: Nothing. - static node_ptr get_previous_previous_node(const node_ptr & this_node) - { return get_previous_previous_node(this_node, this_node); } - - //! Requires: this_node and p must be in the same circular list. - //! - //! Effects: Returns the previous node of the previous node of this_node in the - //! circular list starting. the search from p. The first node checked - //! for equality is NodeTraits::get_next((NodeTraits::get_next(p)). - //! - //! Complexity: Linear to the number of elements in the circular list. - //! - //! Throws: Nothing. - static node_ptr get_previous_previous_node(node_ptr p, const node_ptr & this_node) - { - node_ptr p_next = NodeTraits::get_next(p); - node_ptr p_next_next = NodeTraits::get_next(p_next); - while (this_node != p_next_next){ - p = p_next; - p_next = p_next_next; - p_next_next = NodeTraits::get_next(p_next); - } - return p; - } - - //! Requires: this_node must be in a circular list or be an empty circular list. - //! - //! Effects: Returns the number of nodes in a circular list. If the circular list - //! is empty, returns 1. - //! - //! Complexity: Linear - //! - //! Throws: Nothing. - static std::size_t count(const const_node_ptr & this_node) - { - std::size_t result = 0; - const_node_ptr p = this_node; - do{ - p = NodeTraits::get_next(p); - ++result; - } while (p != this_node); - return result; - } - - //! Requires: this_node must be in a circular list, be an empty circular list or be inited. - //! - //! Effects: Unlinks the node from the circular list. - //! - //! Complexity: Linear to the number of elements in the circular list - //! - //! Throws: Nothing. - static void unlink(const node_ptr & this_node) - { - if(NodeTraits::get_next(this_node)) - base_t::unlink_after(get_previous_node(this_node)); - } - - //! Requires: nxt_node must be a node of a circular list. - //! - //! Effects: Links this_node before nxt_node in the circular list. - //! - //! Complexity: Linear to the number of elements in the circular list. - //! - //! Throws: Nothing. - static void link_before (const node_ptr & nxt_node, const node_ptr & this_node) - { base_t::link_after(get_previous_node(nxt_node), this_node); } - - //! Requires: this_node and other_node must be nodes inserted - //! in circular lists or be empty circular lists. - //! - //! Effects: Swaps the position of the nodes: this_node is inserted in - //! other_nodes position in the second circular list and the other_node is inserted - //! in this_node's position in the first circular list. - //! - //! Complexity: Linear to number of elements of both lists - //! - //! Throws: Nothing. - static void swap_nodes(const node_ptr & this_node, const node_ptr & other_node) - { - if (other_node == this_node) - return; - bool this_inited = base_t::inited(this_node); - bool other_inited = base_t::inited(other_node); - if(this_inited){ - base_t::init_header(this_node); - } - if(other_inited){ - base_t::init_header(other_node); - } - - bool empty1 = base_t::unique(this_node); - bool empty2 = base_t::unique(other_node); - node_ptr prev_this (get_previous_node(this_node)); - node_ptr prev_other(get_previous_node(other_node)); - - node_ptr this_next (NodeTraits::get_next(this_node)); - node_ptr other_next(NodeTraits::get_next(other_node)); - NodeTraits::set_next(this_node, other_next); - NodeTraits::set_next(other_node, this_next); - NodeTraits::set_next(empty1 ? other_node : prev_this, other_node); - NodeTraits::set_next(empty2 ? this_node : prev_other, this_node); - - if(this_inited){ - base_t::init(other_node); - } - if(other_inited){ - base_t::init(this_node); - } - } - - //! Effects: Reverses the order of elements in the list. - //! - //! Throws: Nothing. - //! - //! Complexity: This function is linear to the contained elements. - static void reverse(const node_ptr & p) - { - node_ptr i = NodeTraits::get_next(p), e(p); - for (;;) { - node_ptr nxt(NodeTraits::get_next(i)); - if (nxt == e) - break; - base_t::transfer_after(e, i, nxt); - } - } - - //! Effects: Moves the node p n positions towards the end of the list. - //! - //! Returns: The previous node of p after the function if there has been any movement, - //! Null if n leads to no movement. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements plus the number moved positions. - static node_ptr move_backwards(const node_ptr & p, std::size_t n) - { - //Null shift, nothing to do - if(!n) return node_ptr(); - node_ptr first = NodeTraits::get_next(p); - - //count() == 1 or 2, nothing to do - if(NodeTraits::get_next(first) == p) - return node_ptr(); - - bool end_found = false; - node_ptr new_last = node_ptr(); - - //Now find the new last node according to the shift count. - //If we find p before finding the new last node - //unlink p, shortcut the search now that we know the size of the list - //and continue. - for(std::size_t i = 1; i <= n; ++i){ - new_last = first; - first = NodeTraits::get_next(first); - if(first == p){ - //Shortcut the shift with the modulo of the size of the list - n %= i; - if(!n) - return node_ptr(); - i = 0; - //Unlink p and continue the new first node search - first = NodeTraits::get_next(p); - base_t::unlink_after(new_last); - end_found = true; - } - } - - //If the p has not been found in the previous loop, find it - //starting in the new first node and unlink it - if(!end_found){ - base_t::unlink_after(base_t::get_previous_node(first, p)); - } - - //Now link p after the new last node - base_t::link_after(new_last, p); - return new_last; - } - - //! Effects: Moves the node p n positions towards the beginning of the list. - //! - //! Returns: The previous node of p after the function if there has been any movement, - //! Null if n leads equals to no movement. - //! - //! Throws: Nothing. - //! - //! Complexity: Linear to the number of elements plus the number moved positions. - static node_ptr move_forward(const node_ptr & p, std::size_t n) - { - //Null shift, nothing to do - if(!n) return node_ptr(); - node_ptr first = node_traits::get_next(p); - - //count() == 1 or 2, nothing to do - if(node_traits::get_next(first) == p) return node_ptr(); - - //Iterate until p is found to know where the current last node is. - //If the shift count is less than the size of the list, we can also obtain - //the position of the new last node after the shift. - node_ptr old_last(first), next_to_it, new_last(p); - std::size_t distance = 1; - while(p != (next_to_it = node_traits::get_next(old_last))){ - if(++distance > n) - new_last = node_traits::get_next(new_last); - old_last = next_to_it; - } - //If the shift was bigger or equal than the size, obtain the equivalent - //forward shifts and find the new last node. - if(distance <= n){ - //Now find the equivalent forward shifts. - //Shortcut the shift with the modulo of the size of the list - std::size_t new_before_last_pos = (distance - (n % distance))% distance; - //If the shift is a multiple of the size there is nothing to do - if(!new_before_last_pos) return node_ptr(); - - for( new_last = p - ; new_before_last_pos-- - ; new_last = node_traits::get_next(new_last)){ - //empty - } - } - - //Now unlink p and link it after the new last node - base_t::unlink_after(old_last); - base_t::link_after(new_last, p); - return new_last; - } -}; - -/// @cond - -template -struct get_algo -{ - typedef circular_slist_algorithms type; -}; - -/// @endcond - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_CIRCULAR_SLIST_ALGORITHMS_HPP diff --git a/utils/boost_idb/boost/intrusive/derivation_value_traits.hpp b/utils/boost_idb/boost/intrusive/derivation_value_traits.hpp deleted file mode 100644 index 0b3c9361..00000000 --- a/utils/boost_idb/boost/intrusive/derivation_value_traits.hpp +++ /dev/null @@ -1,70 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_DERIVATION_VALUE_TRAITS_HPP -#define BOOST_INTRUSIVE_DERIVATION_VALUE_TRAITS_HPP - -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -//!This value traits template is used to create value traits -//!from user defined node traits where value_traits::value_type will -//!derive from node_traits::node -template -struct derivation_value_traits -{ - public: - typedef NodeTraits node_traits; - typedef T value_type; - typedef typename node_traits::node node; - typedef typename node_traits::node_ptr node_ptr; - typedef typename node_traits::const_node_ptr const_node_ptr; - typedef typename boost::pointer_to_other::type pointer; - typedef typename boost::pointer_to_other::type const_pointer; - typedef typename boost::intrusive:: - pointer_traits::reference reference; - typedef typename boost::intrusive:: - pointer_traits::reference const_reference; - static const link_mode_type link_mode = LinkMode; - - static node_ptr to_node_ptr(reference value) - { return node_ptr(&value); } - - static const_node_ptr to_node_ptr(const_reference value) - { return node_ptr(&value); } - - static pointer to_value_ptr(const node_ptr &n) - { -// This still fails in gcc < 4.4 so forget about it -// using ::boost::static_pointer_cast; -// return static_pointer_cast(n)); - return pointer(&static_cast(*n)); - } - - static const_pointer to_value_ptr(const const_node_ptr &n) - { -// This still fails in gcc < 4.4 so forget about it -// using ::boost::static_pointer_cast; -// return static_pointer_cast(n)); - return const_pointer(&static_cast(*n)); - } -}; - -} //namespace intrusive -} //namespace boost - -#endif //BOOST_INTRUSIVE_DERIVATION_VALUE_TRAITS_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/any_node_and_algorithms.hpp b/utils/boost_idb/boost/intrusive/detail/any_node_and_algorithms.hpp deleted file mode 100644 index 899023d8..00000000 --- a/utils/boost_idb/boost/intrusive/detail/any_node_and_algorithms.hpp +++ /dev/null @@ -1,297 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_ANY_NODE_HPP -#define BOOST_INTRUSIVE_ANY_NODE_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -template -struct any_node -{ - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - node_ptr node_ptr_1; - node_ptr node_ptr_2; - node_ptr node_ptr_3; - std::size_t size_t_1; -}; - -template -struct any_list_node_traits -{ - typedef any_node node; - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; - - static const node_ptr &get_next(const const_node_ptr & n) - { return n->node_ptr_1; } - - static void set_next(const node_ptr & n, const node_ptr & next) - { n->node_ptr_1 = next; } - - static const node_ptr &get_previous(const const_node_ptr & n) - { return n->node_ptr_2; } - - static void set_previous(const node_ptr & n, const node_ptr & prev) - { n->node_ptr_2 = prev; } -}; - - -template -struct any_slist_node_traits -{ - typedef any_node node; - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; - - static const node_ptr &get_next(const const_node_ptr & n) - { return n->node_ptr_1; } - - static void set_next(const node_ptr & n, const node_ptr & next) - { n->node_ptr_1 = next; } -}; - - -template -struct any_unordered_node_traits - : public any_slist_node_traits -{ - typedef any_slist_node_traits reduced_slist_node_traits; - typedef typename reduced_slist_node_traits::node node; - typedef typename reduced_slist_node_traits::node_ptr node_ptr; - typedef typename reduced_slist_node_traits::const_node_ptr const_node_ptr; - - static const bool store_hash = true; - static const bool optimize_multikey = true; - - static const node_ptr &get_next(const const_node_ptr & n) - { return n->node_ptr_1; } - - static void set_next(const node_ptr & n, const node_ptr & next) - { n->node_ptr_1 = next; } - - static node_ptr get_prev_in_group(const const_node_ptr & n) - { return n->node_ptr_2; } - - static void set_prev_in_group(const node_ptr & n, const node_ptr & prev) - { n->node_ptr_2 = prev; } - - static std::size_t get_hash(const const_node_ptr & n) - { return n->size_t_1; } - - static void set_hash(const node_ptr & n, std::size_t h) - { n->size_t_1 = h; } -}; - - -template -struct any_rbtree_node_traits -{ - typedef any_node node; - - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; - - typedef std::size_t color; - - static const node_ptr &get_parent(const const_node_ptr & n) - { return n->node_ptr_1; } - - static void set_parent(const node_ptr & n, const node_ptr & p) - { n->node_ptr_1 = p; } - - static const node_ptr &get_left(const const_node_ptr & n) - { return n->node_ptr_2; } - - static void set_left(const node_ptr & n, const node_ptr & l) - { n->node_ptr_2 = l; } - - static const node_ptr &get_right(const const_node_ptr & n) - { return n->node_ptr_3; } - - static void set_right(const node_ptr & n, const node_ptr & r) - { n->node_ptr_3 = r; } - - static color get_color(const const_node_ptr & n) - { return n->size_t_1; } - - static void set_color(const node_ptr & n, color c) - { n->size_t_1 = c; } - - static color black() - { return 0u; } - - static color red() - { return 1u; } -}; - - -template -struct any_avltree_node_traits -{ - typedef any_node node; - - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; - typedef std::size_t balance; - - static const node_ptr &get_parent(const const_node_ptr & n) - { return n->node_ptr_1; } - - static void set_parent(const node_ptr & n, const node_ptr & p) - { n->node_ptr_1 = p; } - - static const node_ptr &get_left(const const_node_ptr & n) - { return n->node_ptr_2; } - - static void set_left(const node_ptr & n, const node_ptr & l) - { n->node_ptr_2 = l; } - - static const node_ptr &get_right(const const_node_ptr & n) - { return n->node_ptr_3; } - - static void set_right(const node_ptr & n, const node_ptr & r) - { n->node_ptr_3 = r; } - - static balance get_balance(const const_node_ptr & n) - { return n->size_t_1; } - - static void set_balance(const node_ptr & n, balance b) - { n->size_t_1 = b; } - - static balance negative() - { return 0u; } - - static balance zero() - { return 1u; } - - static balance positive() - { return 2u; } -}; - - -template -struct any_tree_node_traits -{ - typedef any_node node; - - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; - - static const node_ptr &get_parent(const const_node_ptr & n) - { return n->node_ptr_1; } - - static void set_parent(const node_ptr & n, const node_ptr & p) - { n->node_ptr_1 = p; } - - static const node_ptr &get_left(const const_node_ptr & n) - { return n->node_ptr_2; } - - static void set_left(const node_ptr & n, const node_ptr & l) - { n->node_ptr_2 = l; } - - static const node_ptr &get_right(const const_node_ptr & n) - { return n->node_ptr_3; } - - static void set_right(const node_ptr & n, const node_ptr & r) - { n->node_ptr_3 = r; } -}; - -template -class any_node_traits -{ - public: - typedef any_node node; - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; -}; - -template -class any_algorithms -{ - template - static void function_not_available_for_any_hooks(typename detail::enable_if >::type) - {} - - public: - typedef any_node node; - typedef typename pointer_traits - ::template rebind_pointer::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer::type const_node_ptr; - typedef any_node_traits node_traits; - - //! Requires: node must not be part of any tree. - //! - //! Effects: After the function unique(node) == true. - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - //! - //! Nodes: If node is inserted in a tree, this function corrupts the tree. - static void init(const node_ptr & node) - { node->node_ptr_1 = 0; }; - - //! Effects: Returns true if node is in the same state as if called init(node) - //! - //! Complexity: Constant. - //! - //! Throws: Nothing. - static bool inited(const const_node_ptr & node) - { return !node->node_ptr_1; }; - - static bool unique(const const_node_ptr & node) - { return 0 == node->node_ptr_1; } - - static void unlink(const node_ptr &) - { - //Auto-unlink hooks and unlink() are not available for any hooks - any_algorithms::template function_not_available_for_any_hooks(); - } - - static void swap_nodes(const node_ptr & l, const node_ptr & r) - { - //Any nodes have no swap_nodes capability because they don't know - //what algorithm they must use to unlink the node from the container - any_algorithms::template function_not_available_for_any_hooks(); - } -}; - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_ANY_NODE_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/assert.hpp b/utils/boost_idb/boost/intrusive/detail/assert.hpp deleted file mode 100644 index 3dacbcc3..00000000 --- a/utils/boost_idb/boost/intrusive/detail/assert.hpp +++ /dev/null @@ -1,41 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_DETAIL_ASSERT_HPP -#define BOOST_INTRUSIVE_DETAIL_ASSERT_HPP - -#if defined(_MSC_VER)&&(_MSC_VER>=1200) -#pragma once -#endif - -#if !defined(BOOST_INTRUSIVE_INVARIANT_ASSERT) - #include - #define BOOST_INTRUSIVE_INVARIANT_ASSERT BOOST_ASSERT -#elif defined(BOOST_INTRUSIVE_INVARIANT_ASSERT_INCLUDE) - #include BOOST_INTRUSIVE_INVARIANT_ASSERT_INCLUDE -#endif - -#if !defined(BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT) - #include - #define BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT BOOST_ASSERT -#elif defined(BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT_INCLUDE) - #include BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT_INCLUDE -#endif - -#if !defined(BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT) - #include - #define BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT BOOST_ASSERT -#elif defined(BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT_INCLUDE) - #include BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT_INCLUDE -#endif - -#endif //BOOST_INTRUSIVE_DETAIL_ASSERT_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/avltree_node.hpp b/utils/boost_idb/boost/intrusive/detail/avltree_node.hpp deleted file mode 100644 index 8031c7d7..00000000 --- a/utils/boost_idb/boost/intrusive/detail/avltree_node.hpp +++ /dev/null @@ -1,197 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_AVLTREE_NODE_HPP -#define BOOST_INTRUSIVE_AVLTREE_NODE_HPP - -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -///////////////////////////////////////////////////////////////////////////// -// // -// Generic node_traits for any pointer type // -// // -///////////////////////////////////////////////////////////////////////////// - -//This is the compact representation: 3 pointers -template -struct compact_avltree_node -{ - typedef typename pointer_traits - ::template rebind_pointer - >::type node_ptr; - enum balance { negative_t, zero_t, positive_t }; - node_ptr parent_, left_, right_; -}; - -//This is the normal representation: 3 pointers + enum -template -struct avltree_node -{ - typedef typename pointer_traits - ::template rebind_pointer - >::type node_ptr; - enum balance { negative_t, zero_t, positive_t }; - node_ptr parent_, left_, right_; - balance balance_; -}; - -//This is the default node traits implementation -//using a node with 3 generic pointers plus an enum -template -struct default_avltree_node_traits_impl -{ - typedef avltree_node node; - - typedef typename pointer_traits - ::template rebind_pointer - ::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer - ::type const_node_ptr; - - typedef typename node::balance balance; - - static node_ptr get_parent(const const_node_ptr & n) - { return n->parent_; } - - static node_ptr get_parent(const node_ptr & n) - { return n->parent_; } - - static void set_parent(const node_ptr & n, const node_ptr & p) - { n->parent_ = p; } - - static node_ptr get_left(const const_node_ptr & n) - { return n->left_; } - - static node_ptr get_left(const node_ptr & n) - { return n->left_; } - - static void set_left(const node_ptr & n, const node_ptr & l) - { n->left_ = l; } - - static node_ptr get_right(const const_node_ptr & n) - { return n->right_; } - - static node_ptr get_right(const node_ptr & n) - { return n->right_; } - - static void set_right(const node_ptr & n, const node_ptr & r) - { n->right_ = r; } - - static balance get_balance(const const_node_ptr & n) - { return n->balance_; } - - static balance get_balance(const node_ptr & n) - { return n->balance_; } - - static void set_balance(const node_ptr & n, balance b) - { n->balance_ = b; } - - static balance negative() - { return node::negative_t; } - - static balance zero() - { return node::zero_t; } - - static balance positive() - { return node::positive_t; } -}; - -//This is the compact node traits implementation -//using a node with 3 generic pointers -template -struct compact_avltree_node_traits_impl -{ - typedef compact_avltree_node node; - - typedef typename pointer_traits - ::template rebind_pointer - ::type node_ptr; - typedef typename pointer_traits - ::template rebind_pointer - ::type const_node_ptr; - typedef typename node::balance balance; - - typedef pointer_plus_bits ptr_bit; - - static node_ptr get_parent(const const_node_ptr & n) - { return ptr_bit::get_pointer(n->parent_); } - - static void set_parent(const node_ptr & n, const node_ptr & p) - { ptr_bit::set_pointer(n->parent_, p); } - - static node_ptr get_left(const const_node_ptr & n) - { return n->left_; } - - static void set_left(const node_ptr & n, const node_ptr & l) - { n->left_ = l; } - - static node_ptr get_right(const const_node_ptr & n) - { return n->right_; } - - static void set_right(const node_ptr & n, const node_ptr & r) - { n->right_ = r; } - - static balance get_balance(const const_node_ptr & n) - { return (balance)ptr_bit::get_bits(n->parent_); } - - static void set_balance(const node_ptr & n, balance b) - { ptr_bit::set_bits(n->parent_, (std::size_t)b); } - - static balance negative() - { return node::negative_t; } - - static balance zero() - { return node::zero_t; } - - static balance positive() - { return node::positive_t; } -}; - -//Dispatches the implementation based on the boolean -template -struct avltree_node_traits_dispatch - : public default_avltree_node_traits_impl -{}; - -template -struct avltree_node_traits_dispatch - : public compact_avltree_node_traits_impl -{}; - -//Inherit from the detail::link_dispatch depending on the embedding capabilities -template -struct avltree_node_traits - : public avltree_node_traits_dispatch - < VoidPointer - , OptimizeSize && - max_pointer_plus_bits - < VoidPointer - , detail::alignment_of >::value - >::value >= 2u - > -{}; - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_AVLTREE_NODE_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/clear_on_destructor_base.hpp b/utils/boost_idb/boost/intrusive/detail/clear_on_destructor_base.hpp deleted file mode 100644 index 164fe409..00000000 --- a/utils/boost_idb/boost/intrusive/detail/clear_on_destructor_base.hpp +++ /dev/null @@ -1,40 +0,0 @@ -//////} // /////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2008-2013. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_DETAIL_CLEAR_ON_DESTRUCTOR_HPP -#define BOOST_INTRUSIVE_DETAIL_CLEAR_ON_DESTRUCTOR_HPP - -#include - -namespace boost { -namespace intrusive { -namespace detail { - -template -class clear_on_destructor_base -{ - protected: - ~clear_on_destructor_base() - { - static_cast(this)->clear(); - } -}; - -template -class clear_on_destructor_base -{}; - -} // namespace detail { -} // namespace intrusive { -} // namespace boost { - -#include - -#endif //#ifndef BOOST_INTRUSIVE_DETAIL_CLEAR_ON_DESTRUCTOR_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/common_slist_algorithms.hpp b/utils/boost_idb/boost/intrusive/detail/common_slist_algorithms.hpp deleted file mode 100644 index a5433bb1..00000000 --- a/utils/boost_idb/boost/intrusive/detail/common_slist_algorithms.hpp +++ /dev/null @@ -1,102 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_COMMON_SLIST_ALGORITHMS_HPP -#define BOOST_INTRUSIVE_COMMON_SLIST_ALGORITHMS_HPP - -#include -#include -#include -#include - -namespace boost { -namespace intrusive { -namespace detail { - -template -class common_slist_algorithms -{ - public: - typedef typename NodeTraits::node node; - typedef typename NodeTraits::node_ptr node_ptr; - typedef typename NodeTraits::const_node_ptr const_node_ptr; - typedef NodeTraits node_traits; - - static node_ptr get_previous_node(node_ptr p, const node_ptr & this_node) - { - for( node_ptr p_next - ; this_node != (p_next = NodeTraits::get_next(p)) - ; p = p_next){ - //Logic error: possible use of linear lists with - //operations only permitted with lists - BOOST_INTRUSIVE_INVARIANT_ASSERT(p); - } - return p; - } - - static void init_header(const node_ptr & this_node) - { NodeTraits::set_next(this_node, this_node); } - - static void init(const node_ptr & this_node) - { NodeTraits::set_next(this_node, node_ptr()); } - - static bool unique(const const_node_ptr & this_node) - { - node_ptr next = NodeTraits::get_next(this_node); - return !next || next == this_node; - } - - static bool inited(const const_node_ptr & this_node) - { return !NodeTraits::get_next(this_node); } - - static void unlink_after(const node_ptr & prev_node) - { - const_node_ptr this_node(NodeTraits::get_next(prev_node)); - NodeTraits::set_next(prev_node, NodeTraits::get_next(this_node)); - } - - static void unlink_after(const node_ptr & prev_node, const node_ptr & last_node) - { NodeTraits::set_next(prev_node, last_node); } - - static void link_after(const node_ptr & prev_node, const node_ptr & this_node) - { - NodeTraits::set_next(this_node, NodeTraits::get_next(prev_node)); - NodeTraits::set_next(prev_node, this_node); - } - - static void incorporate_after(const node_ptr & bp, const node_ptr & b, const node_ptr & be) - { - node_ptr p(NodeTraits::get_next(bp)); - NodeTraits::set_next(bp, b); - NodeTraits::set_next(be, p); - } - - static void transfer_after(const node_ptr & bp, const node_ptr & bb, const node_ptr & be) - { - if (bp != bb && bp != be && bb != be) { - node_ptr next_b = NodeTraits::get_next(bb); - node_ptr next_e = NodeTraits::get_next(be); - node_ptr next_p = NodeTraits::get_next(bp); - NodeTraits::set_next(bb, next_e); - NodeTraits::set_next(be, next_p); - NodeTraits::set_next(bp, next_b); - } - } -}; - -} //namespace detail -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_COMMON_SLIST_ALGORITHMS_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/config_begin.hpp b/utils/boost_idb/boost/intrusive/detail/config_begin.hpp deleted file mode 100644 index 109a5908..00000000 --- a/utils/boost_idb/boost/intrusive/detail/config_begin.hpp +++ /dev/null @@ -1,52 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_CONFIG_INCLUDED -#define BOOST_INTRUSIVE_CONFIG_INCLUDED -#include -#endif - -#ifdef BOOST_MSVC - - #pragma warning (push) - // - //'function' : resolved overload was found by argument-dependent lookup - //A function found by argument-dependent lookup (Koenig lookup) was eventually - //chosen by overload resolution. - // - //In Visual C++ .NET and earlier compilers, a different function would have - //been called. To pick the original function, use an explicitly qualified name. - // - - //warning C4275: non dll-interface class 'x' used as base for - //dll-interface class 'Y' - #pragma warning (disable : 4275) - //warning C4251: 'x' : class 'y' needs to have dll-interface to - //be used by clients of class 'z' - #pragma warning (disable : 4251) - #pragma warning (disable : 4675) - #pragma warning (disable : 4996) - #pragma warning (disable : 4503) - #pragma warning (disable : 4284) // odd return type for operator-> - #pragma warning (disable : 4244) // possible loss of data - #pragma warning (disable : 4521) ////Disable "multiple copy constructors specified" - #pragma warning (disable : 4522) - #pragma warning (disable : 4146) - #pragma warning (disable : 4267) //conversion from 'X' to 'Y', possible loss of data - #pragma warning (disable : 4127) //conditional expression is constant - #pragma warning (disable : 4706) //assignment within conditional expression - #pragma warning (disable : 4541) //'typeid' used on polymorphic type 'boost::exception' with /GR- - #pragma warning (disable : 4512) //'typeid' used on polymorphic type 'boost::exception' with /GR- -#endif - -//#define BOOST_INTRUSIVE_USE_ITERATOR_FACADE -//#define BOOST_INTRUSIVE_USE_ITERATOR_ENABLE_IF_CONVERTIBLE diff --git a/utils/boost_idb/boost/intrusive/detail/config_end.hpp b/utils/boost_idb/boost/intrusive/detail/config_end.hpp deleted file mode 100644 index a081443e..00000000 --- a/utils/boost_idb/boost/intrusive/detail/config_end.hpp +++ /dev/null @@ -1,15 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#if defined BOOST_MSVC - #pragma warning (pop) -#endif diff --git a/utils/boost_idb/boost/intrusive/detail/ebo_functor_holder.hpp b/utils/boost_idb/boost/intrusive/detail/ebo_functor_holder.hpp deleted file mode 100644 index 3c2959b9..00000000 --- a/utils/boost_idb/boost/intrusive/detail/ebo_functor_holder.hpp +++ /dev/null @@ -1,95 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Joaquin M Lopez Munoz 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_DETAIL_EBO_HOLDER_HPP -#define BOOST_INTRUSIVE_DETAIL_EBO_HOLDER_HPP - -#include -#include - -namespace boost { -namespace intrusive { -namespace detail { - -template -class ebo_functor_holder_impl -{ - public: - ebo_functor_holder_impl() - {} - ebo_functor_holder_impl(const T& t) - : t_(t) - {} - template - ebo_functor_holder_impl(const Arg1& arg1, const Arg2& arg2) - : t_(arg1, arg2) - {} - - T& get(){return t_;} - const T& get()const{return t_;} - - private: - T t_; -}; - -template -class ebo_functor_holder_impl - : public T -{ - public: - ebo_functor_holder_impl() - {} - ebo_functor_holder_impl(const T& t) - : T(t) - {} - template - ebo_functor_holder_impl(const Arg1& arg1, const Arg2& arg2) - : T(arg1, arg2) - {} - - T& get(){return *this;} - const T& get()const{return *this;} -}; - -template -class ebo_functor_holder - : public ebo_functor_holder_impl::value> -{ - private: - typedef ebo_functor_holder_impl::value> super; - - public: - ebo_functor_holder(){} - ebo_functor_holder(const T& t) - : super(t) - {} - - template - ebo_functor_holder(const Arg1& arg1, const Arg2& arg2) - : super(arg1, arg2) - {} - - ebo_functor_holder& operator=(const ebo_functor_holder& x) - { - this->get()=x.get(); - return *this; - } -}; - - -} //namespace detail { -} //namespace intrusive { -} //namespace boost { - -#include - -#endif //#ifndef BOOST_INTRUSIVE_DETAIL_EBO_HOLDER_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/function_detector.hpp b/utils/boost_idb/boost/intrusive/detail/function_detector.hpp deleted file mode 100644 index f8eccf9e..00000000 --- a/utils/boost_idb/boost/intrusive/detail/function_detector.hpp +++ /dev/null @@ -1,88 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2013. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// -// This code was modified from the code posted by Alexandre Courpron in his -// article "Interface Detection" in The Code Project: -// http://www.codeproject.com/KB/architecture/Detector.aspx -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2007 Alexandre Courpron -// -// Permission to use, copy, modify, redistribute and sell this software, -// provided that this copyright notice appears on all copies of the software. -/////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_DETAIL_FUNCTION_DETECTOR_HPP -#define BOOST_INTRUSIVE_DETAIL_FUNCTION_DETECTOR_HPP - -#include - -namespace boost { -namespace intrusive { -namespace function_detector { - - typedef char NotFoundType; - struct StaticFunctionType { NotFoundType x [2]; }; - struct NonStaticFunctionType { NotFoundType x [3]; }; - - enum - { NotFound = 0, - StaticFunction = sizeof( StaticFunctionType ) - sizeof( NotFoundType ), - NonStaticFunction = sizeof( NonStaticFunctionType ) - sizeof( NotFoundType ) - }; - -} //namespace boost { -} //namespace intrusive { -} //namespace function_detector { - -#define BOOST_INTRUSIVE_CREATE_FUNCTION_DETECTOR(Identifier, InstantiationKey) \ - namespace boost { \ - namespace intrusive { \ - namespace function_detector { \ - template < class T, \ - class NonStaticType, \ - class NonStaticConstType, \ - class StaticType > \ - class DetectMember_##InstantiationKey_##Identifier { \ - template < NonStaticType > \ - struct TestNonStaticNonConst ; \ - \ - template < NonStaticConstType > \ - struct TestNonStaticConst ; \ - \ - template < StaticType > \ - struct TestStatic ; \ - \ - template \ - static NonStaticFunctionType Test( TestNonStaticNonConst<&U::Identifier>*, int ); \ - \ - template \ - static NonStaticFunctionType Test( TestNonStaticConst<&U::Identifier>*, int ); \ - \ - template \ - static StaticFunctionType Test( TestStatic<&U::Identifier>*, int ); \ - \ - template \ - static NotFoundType Test( ... ); \ - public : \ - static const int check = NotFound + (sizeof(Test(0, 0)) - sizeof(NotFoundType));\ - };\ -}}} //namespace boost::intrusive::function_detector { - -#define BOOST_INTRUSIVE_DETECT_FUNCTION(Class, InstantiationKey, ReturnType, Identifier, Params) \ - ::boost::intrusive::function_detector::DetectMember_##InstantiationKey_##Identifier< Class,\ - ReturnType (Class::*)Params,\ - ReturnType (Class::*)Params const,\ - ReturnType (*)Params \ - >::check - -#include - -#endif //@ifndef BOOST_INTRUSIVE_DETAIL_FUNCTION_DETECTOR_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/generic_hook.hpp b/utils/boost_idb/boost/intrusive/detail/generic_hook.hpp deleted file mode 100644 index 8848aff9..00000000 --- a/utils/boost_idb/boost/intrusive/detail/generic_hook.hpp +++ /dev/null @@ -1,194 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_GENERIC_HOOK_HPP -#define BOOST_INTRUSIVE_GENERIC_HOOK_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -/// @cond - -enum base_hook_type -{ NoBaseHookId -, ListBaseHookId -, SlistBaseHookId -, RbTreeBaseHookId -, HashBaseHookId -, SplayTreeBaseHookId -, AvlTreeBaseHookId -, BsTreeBaseHookId -, AnyBaseHookId -}; - - -template -struct hook_tags_definer{}; - -template -struct hook_tags_definer -{ typedef HookTags default_list_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_slist_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_rbtree_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_hashtable_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_splaytree_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_avltree_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_bstree_hook; }; - -template -struct hook_tags_definer -{ typedef HookTags default_any_hook; }; - -template - < class NodeTraits - , class Tag - , link_mode_type LinkMode - , base_hook_type BaseHookType - > -struct hooktags_impl -{ - static const link_mode_type link_mode = LinkMode; - typedef Tag tag; - typedef NodeTraits node_traits; - static const bool is_base_hook = !detail::is_same::value; - static const bool safemode_or_autounlink = is_safe_autounlink::value; - static const unsigned int type = BaseHookType; -}; - -/// @endcond - -template - < class GetNodeAlgorithms - , class Tag - , link_mode_type LinkMode - , base_hook_type BaseHookType - > -class generic_hook - /// @cond - //If the hook is a base hook, derive generic hook from node_holder - //so that a unique base class is created to convert from the node - //to the type. This mechanism will be used by bhtraits. - // - //If the hook is a member hook, generic hook will directly derive - //from the hook. - : public detail::if_c - < detail::is_same::value - , typename GetNodeAlgorithms::type::node - , node_holder - >::type - //If this is the a default-tagged base hook derive from a class that - //will define an special internal typedef. Containers will be able to detect this - //special typedef and obtain generic_hook's internal types in order to deduce - //value_traits for this hook. - , public hook_tags_definer - < generic_hook - , detail::is_same::value*BaseHookType> - /// @endcond -{ - /// @cond - typedef typename GetNodeAlgorithms::type node_algorithms; - typedef typename node_algorithms::node node; - typedef typename node_algorithms::node_ptr node_ptr; - typedef typename node_algorithms::const_node_ptr const_node_ptr; - - public: - - typedef hooktags_impl - < typename GetNodeAlgorithms::type::node_traits - , Tag, LinkMode, BaseHookType> hooktags; - - node_ptr this_ptr() - { return pointer_traits::pointer_to(static_cast(*this)); } - - const_node_ptr this_ptr() const - { return pointer_traits::pointer_to(static_cast(*this)); } - - public: - /// @endcond - - generic_hook() - { - if(hooktags::safemode_or_autounlink){ - node_algorithms::init(this->this_ptr()); - } - } - - generic_hook(const generic_hook& ) - { - if(hooktags::safemode_or_autounlink){ - node_algorithms::init(this->this_ptr()); - } - } - - generic_hook& operator=(const generic_hook& ) - { return *this; } - - ~generic_hook() - { - destructor_impl - (*this, detail::link_dispatch()); - } - - void swap_nodes(generic_hook &other) - { - node_algorithms::swap_nodes - (this->this_ptr(), other.this_ptr()); - } - - bool is_linked() const - { - //is_linked() can be only used in safe-mode or auto-unlink - BOOST_STATIC_ASSERT(( hooktags::safemode_or_autounlink )); - return !node_algorithms::unique(this->this_ptr()); - } - - void unlink() - { - BOOST_STATIC_ASSERT(( (int)hooktags::link_mode == (int)auto_unlink )); - node_algorithms::unlink(this->this_ptr()); - node_algorithms::init(this->this_ptr()); - } -}; - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_GENERIC_HOOK_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/has_member_function_callable_with.hpp b/utils/boost_idb/boost/intrusive/detail/has_member_function_callable_with.hpp deleted file mode 100644 index be4a0153..00000000 --- a/utils/boost_idb/boost/intrusive/detail/has_member_function_callable_with.hpp +++ /dev/null @@ -1,357 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -// sample.h - -#if !defined(BOOST_PP_IS_ITERATING) - - #ifndef BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED - #define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED - - #include - #include - #include - #include - #include - #include - - //Mark that we don't support 0 arg calls due to compiler ICE in GCC 3.4/4.0/4.1 and - //wrong SFINAE for GCC 4.2/4.3 - #if defined(__GNUC__) && !defined(__clang__) && ((__GNUC__*100 + __GNUC_MINOR__*10) >= 340) && ((__GNUC__*100 + __GNUC_MINOR__*10) <= 430) - #define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED - #elif defined(BOOST_INTEL) && (BOOST_INTEL < 1200 ) - #define BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED - #endif - - namespace boost_intrusive_has_member_function_callable_with { - - struct dont_care - { - dont_care(...); - }; - - struct private_type - { - static private_type p; - private_type const &operator,(int) const; - }; - - typedef char yes_type; // sizeof(yes_type) == 1 - struct no_type{ char dummy[2]; }; // sizeof(no_type) == 2 - - template - no_type is_private_type(T const &); - yes_type is_private_type(private_type const &); - - } //boost_intrusive_has_member_function_callable_with - - #include - - #endif //BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_DETAILS_INCLUDED - -#else //!BOOST_PP_IS_ITERATING - - #ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME - #error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME not defined!" - #endif - - #ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN - #error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN not defined!" - #endif - - #ifndef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END - #error "BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END not defined!" - #endif - - #if BOOST_PP_ITERATION_START() != 0 - #error "BOOST_PP_ITERATION_START() must be zero (0)" - #endif - - #if BOOST_PP_ITERATION() == 0 - - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN - - template - class BOOST_PP_CAT(has_member_function_named_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - { - struct BaseMixin - { - void BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME(); - }; - - struct Base : public ::boost::intrusive::detail::remove_cv::type, public BaseMixin { Base(); }; - template class Helper{}; - - template - static boost_intrusive_has_member_function_callable_with::no_type deduce - (U*, Helper* = 0); - static boost_intrusive_has_member_function_callable_with::yes_type deduce(...); - - public: - static const bool value = - sizeof(boost_intrusive_has_member_function_callable_with::yes_type) == sizeof(deduce((Base*)(0))); - }; - - #if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl); - //! - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl) - - { - static const bool value = false; - }; - //! - - #if !defined(_MSC_VER) || (_MSC_VER < 1600) - - #if defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED) - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - - { - //Mark that we don't support 0 arg calls due to compiler ICE in GCC 3.4/4.0/4.1 and - //wrong SFINAE for GCC 4.2/4.3 - static const bool value = true; - }; - - #else //defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED) - - //Special case for 0 args - template< class F - , std::size_t N = - sizeof((boost::move_detail::declval(). - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME (), 0))> - struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - { - boost_intrusive_has_member_function_callable_with::yes_type dummy; - BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int); - }; - - //For buggy compilers like MSVC 7.1+ ((F*)0)->func() does not - //SFINAE-out the zeroarg_checker_ instantiation but sizeof yields to 0. - template - struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - { - boost_intrusive_has_member_function_callable_with::no_type dummy; - BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int); - }; - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - - { - template - static BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - Test(BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)*); - - template - static boost_intrusive_has_member_function_callable_with::no_type Test(...); - - static const bool value = sizeof(Test< Fun >(0)) - == sizeof(boost_intrusive_has_member_function_callable_with::yes_type); - }; - #endif //defined(BOOST_INTRUSIVE_DETAIL_HAS_MEMBER_FUNCTION_CALLABLE_WITH_0_ARGS_UNSUPPORTED) - - #else //#if !defined(_MSC_VER) || (_MSC_VER < 1600) - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - - { - template - static decltype( boost::move_detail::declval().BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME() - , boost_intrusive_has_member_function_callable_with::yes_type()) - Test(Fun*); - - template - static boost_intrusive_has_member_function_callable_with::no_type Test(...); - - static const bool value = sizeof(Test(0)) - == sizeof(boost_intrusive_has_member_function_callable_with::yes_type); - }; - #endif //#if !defined(_MSC_VER) || (_MSC_VER < 1600) - - #else //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl); - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - - { - static const bool value = false; - }; - - //Special case for 0 args - template< class F - , std::size_t N = - sizeof((boost::move_detail::declval(). - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME (), 0))> - struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - { - boost_intrusive_has_member_function_callable_with::yes_type dummy; - BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int); - }; - - //For buggy compilers like MSVC 7.1+ ((F*)0)->func() does not - //SFINAE-out the zeroarg_checker_ instantiation but sizeof yields to 0. - template - struct BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - { - boost_intrusive_has_member_function_callable_with::no_type dummy; - BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)(int); - }; - - template - struct BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - - { - template - static BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - Test(BOOST_PP_CAT(zeroarg_checker_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)*); - - template - static boost_intrusive_has_member_function_callable_with::no_type Test(...); - - static const bool value = sizeof(Test< Fun >(0)) - == sizeof(boost_intrusive_has_member_function_callable_with::yes_type); - }; - - template - struct BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME ) - : Fun - { - BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )(); - using Fun::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME; - - boost_intrusive_has_member_function_callable_with::private_type - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME - ( DontCares...) const; - }; - - template - struct BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl) - - { - template - struct make_dontcare - { - typedef boost_intrusive_has_member_function_callable_with::dont_care type; - }; - - typedef BOOST_PP_CAT( funwrap_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME ) - ::type...> FunWrap; - - static bool const value = (sizeof(boost_intrusive_has_member_function_callable_with::no_type) == - sizeof(boost_intrusive_has_member_function_callable_with::is_private_type - ( (::boost::move_detail::declval< FunWrap >(). - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME - ( ::boost::move_detail::declval()... ), 0) ) - ) - ); - }; - - template - struct BOOST_PP_CAT( has_member_function_callable_with_ - , BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - : public BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_ - , BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - < Fun - , BOOST_PP_CAT( has_member_function_named_ - , BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME )::value - , Args... > - {}; - - #endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END - - #else //BOOST_PP_ITERATION() == 0 - - #if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN - - template - struct BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION()) - , BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)) - : Fun - { - BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION()) - , BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME))(); - - using Fun::BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME; - boost_intrusive_has_member_function_callable_with::private_type - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME - ( BOOST_PP_ENUM(BOOST_PP_ITERATION() - , BOOST_INTRUSIVE_PP_IDENTITY - , boost_intrusive_has_member_function_callable_with::dont_care)) const; - }; - - template - struct BOOST_PP_CAT( BOOST_PP_CAT(has_member_function_callable_with_ - , BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME),_impl) - - { - typedef BOOST_PP_CAT( BOOST_PP_CAT(funwrap, BOOST_PP_ITERATION()) - , BOOST_PP_CAT(_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME)) - FunWrap; - static bool const value = - (sizeof(boost_intrusive_has_member_function_callable_with::no_type) == - sizeof(boost_intrusive_has_member_function_callable_with::is_private_type - ( (boost::move_detail::declval(). - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME - ( BOOST_PP_ENUM( BOOST_PP_ITERATION(), BOOST_INTRUSIVE_PP_DECLVAL, _) ), 0 - ) - ) - ) - ); - }; - - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END - #endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - #endif //BOOST_PP_ITERATION() == 0 - - #if BOOST_PP_ITERATION() == BOOST_PP_ITERATION_FINISH() - - #if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN - - template - struct BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME) - : public BOOST_PP_CAT(BOOST_PP_CAT(has_member_function_callable_with_, BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME), _impl) - ::value - BOOST_PP_ENUM_TRAILING_PARAMS(BOOST_PP_ITERATION_FINISH(), P) > - {}; - - BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END - - #endif //#if !defined(BOOST_INTRUSIVE_PERFECT_FORWARDING) - - #undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME - #undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN - #undef BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END - - #endif //#if BOOST_PP_ITERATION() == BOOST_PP_ITERATION_FINISH() - -#endif //!BOOST_PP_IS_ITERATING diff --git a/utils/boost_idb/boost/intrusive/detail/hashtable_node.hpp b/utils/boost_idb/boost/intrusive/detail/hashtable_node.hpp deleted file mode 100644 index d9a3c41b..00000000 --- a/utils/boost_idb/boost/intrusive/detail/hashtable_node.hpp +++ /dev/null @@ -1,307 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2007-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_HASHTABLE_NODE_HPP -#define BOOST_INTRUSIVE_HASHTABLE_NODE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include //remove-me -#include -#include -#include -#include -#include -#include - - -namespace boost { -namespace intrusive { -namespace detail { - -template -struct prime_list_holder -{ - static const std::size_t prime_list[]; - static const std::size_t prime_list_size; -}; - -template -const std::size_t prime_list_holder::prime_list[] = { - 3ul, 7ul, 11ul, 17ul, 29ul, - 53ul, 97ul, 193ul, 389ul, 769ul, - 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, - 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, - 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, - 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, - 1610612741ul, 3221225473ul, 4294967291ul }; - -template -const std::size_t prime_list_holder::prime_list_size - = sizeof(prime_list)/sizeof(std::size_t); - -template -struct bucket_impl : public Slist -{ - typedef Slist slist_type; - bucket_impl() - {} - - bucket_impl(const bucket_impl &) - {} - - ~bucket_impl() - { - //This bucket is still being used! - BOOST_INTRUSIVE_INVARIANT_ASSERT(Slist::empty()); - } - - bucket_impl &operator=(const bucket_impl&) - { - //This bucket is still in use! - BOOST_INTRUSIVE_INVARIANT_ASSERT(Slist::empty()); - //Slist::clear(); - return *this; - } -}; - -template -struct bucket_traits_impl -{ - private: - BOOST_COPYABLE_AND_MOVABLE(bucket_traits_impl) - - public: - /// @cond - - typedef typename pointer_traits - ::template rebind_pointer - < bucket_impl >::type bucket_ptr; - typedef Slist slist; - typedef typename Slist::size_type size_type; - /// @endcond - - bucket_traits_impl(bucket_ptr buckets, size_type len) - : buckets_(buckets), buckets_len_(len) - {} - - bucket_traits_impl(const bucket_traits_impl &x) - : buckets_(x.buckets_), buckets_len_(x.buckets_len_) - {} - - bucket_traits_impl(BOOST_RV_REF(bucket_traits_impl) x) - : buckets_(x.buckets_), buckets_len_(x.buckets_len_) - { x.buckets_ = bucket_ptr(); x.buckets_len_ = 0; } - - bucket_traits_impl& operator=(BOOST_RV_REF(bucket_traits_impl) x) - { - buckets_ = x.buckets_; buckets_len_ = x.buckets_len_; - x.buckets_ = bucket_ptr(); x.buckets_len_ = 0; return *this; - } - - bucket_traits_impl& operator=(BOOST_COPY_ASSIGN_REF(bucket_traits_impl) x) - { - buckets_ = x.buckets_; buckets_len_ = x.buckets_len_; return *this; - } - - const bucket_ptr &bucket_begin() const - { return buckets_; } - - size_type bucket_count() const - { return buckets_len_; } - - private: - bucket_ptr buckets_; - size_type buckets_len_; -}; - -template -struct hash_reduced_slist_node_traits -{ - template static detail::one test(...); - template static detail::two test(typename U::reduced_slist_node_traits* = 0); - static const bool value = sizeof(test(0)) == sizeof(detail::two); -}; - -template -struct apply_reduced_slist_node_traits -{ - typedef typename NodeTraits::reduced_slist_node_traits type; -}; - -template -struct reduced_slist_node_traits -{ - typedef typename detail::eval_if_c - < hash_reduced_slist_node_traits::value - , apply_reduced_slist_node_traits - , detail::identity - >::type type; -}; - -template -struct get_slist_impl -{ - typedef trivial_value_traits trivial_traits; - - //Reducing symbol length - struct type : make_slist - < typename NodeTraits::node - , boost::intrusive::value_traits - , boost::intrusive::constant_time_size - , boost::intrusive::size_type::difference_type>::type > - >::type - {}; -}; - -} //namespace detail { - -template -class hashtable_iterator - : public std::iterator - < std::forward_iterator_tag - , typename BucketValueTraits::real_value_traits::value_type - , typename pointer_traits::difference_type - , typename detail::add_const_if_c - ::type * - , typename detail::add_const_if_c - ::type & - > -{ - typedef typename BucketValueTraits::real_value_traits real_value_traits; - typedef typename BucketValueTraits::real_bucket_traits real_bucket_traits; - typedef typename real_value_traits::node_traits node_traits; - typedef typename detail::get_slist_impl - ::type - >::type slist_impl; - typedef typename slist_impl::iterator siterator; - typedef typename slist_impl::const_iterator const_siterator; - typedef detail::bucket_impl bucket_type; - - typedef typename pointer_traits - ::template rebind_pointer - < const BucketValueTraits >::type const_bucketvaltraits_ptr; - typedef typename slist_impl::size_type size_type; - - - static typename node_traits::node_ptr downcast_bucket(typename bucket_type::node_ptr p) - { - return pointer_traits:: - pointer_to(static_cast(*p)); - } - - public: - typedef typename real_value_traits::value_type value_type; - typedef typename detail::add_const_if_c::type *pointer; - typedef typename detail::add_const_if_c::type &reference; - - hashtable_iterator () - {} - - explicit hashtable_iterator(siterator ptr, const BucketValueTraits *cont) - : slist_it_ (ptr), traitsptr_ (cont ? pointer_traits::pointer_to(*cont) : const_bucketvaltraits_ptr() ) - {} - - hashtable_iterator(const hashtable_iterator &other) - : slist_it_(other.slist_it()), traitsptr_(other.get_bucket_value_traits()) - {} - - const siterator &slist_it() const - { return slist_it_; } - - hashtable_iterator unconst() const - { return hashtable_iterator(this->slist_it(), this->get_bucket_value_traits()); } - - public: - hashtable_iterator& operator++() - { this->increment(); return *this; } - - hashtable_iterator operator++(int) - { - hashtable_iterator result (*this); - this->increment(); - return result; - } - - friend bool operator== (const hashtable_iterator& i, const hashtable_iterator& i2) - { return i.slist_it_ == i2.slist_it_; } - - friend bool operator!= (const hashtable_iterator& i, const hashtable_iterator& i2) - { return !(i == i2); } - - reference operator*() const - { return *this->operator ->(); } - - pointer operator->() const - { - return boost::intrusive::detail::to_raw_pointer(this->priv_real_value_traits().to_value_ptr - (downcast_bucket(slist_it_.pointed_node()))); - } - - const const_bucketvaltraits_ptr &get_bucket_value_traits() const - { return traitsptr_; } - - const real_value_traits &priv_real_value_traits() const - { return traitsptr_->priv_real_value_traits(); } - - const real_bucket_traits &priv_real_bucket_traits() const - { return traitsptr_->priv_real_bucket_traits(); } - - private: - void increment() - { - const real_bucket_traits &rbuck_traits = this->priv_real_bucket_traits(); - bucket_type* const buckets = boost::intrusive::detail::to_raw_pointer(rbuck_traits.bucket_begin()); - const size_type buckets_len = rbuck_traits.bucket_count(); - - ++slist_it_; - const typename slist_impl::node_ptr n = slist_it_.pointed_node(); - const siterator first_bucket_bbegin = buckets->end(); - if(first_bucket_bbegin.pointed_node() <= n && n <= buckets[buckets_len-1].cend().pointed_node()){ - //If one-past the node is inside the bucket then look for the next non-empty bucket - //1. get the bucket_impl from the iterator - const bucket_type &b = static_cast - (bucket_type::slist_type::container_from_end_iterator(slist_it_)); - - //2. Now just calculate the index b has in the bucket array - size_type n_bucket = static_cast(&b - buckets); - - //3. Iterate until a non-empty bucket is found - do{ - if (++n_bucket >= buckets_len){ //bucket overflow, return end() iterator - slist_it_ = buckets->before_begin(); - return; - } - } - while (buckets[n_bucket].empty()); - slist_it_ = buckets[n_bucket].begin(); - } - else{ - //++slist_it_ yield to a valid object - } - } - - siterator slist_it_; - const_bucketvaltraits_ptr traitsptr_; -}; - -} //namespace intrusive { -} //namespace boost { - -#endif diff --git a/utils/boost_idb/boost/intrusive/detail/is_stateful_value_traits.hpp b/utils/boost_idb/boost/intrusive/detail/is_stateful_value_traits.hpp deleted file mode 100644 index c98f6c6b..00000000 --- a/utils/boost_idb/boost/intrusive/detail/is_stateful_value_traits.hpp +++ /dev/null @@ -1,77 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2009-2013. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_DETAIL_IS_STATEFUL_VALUE_TRAITS_HPP -#define BOOST_INTRUSIVE_DETAIL_IS_STATEFUL_VALUE_TRAITS_HPP - -#include - -#if defined(_MSC_VER) && (_MSC_VER <= 1310) - -#include - -namespace boost { -namespace intrusive { -namespace detail { - -template -struct is_stateful_value_traits -{ - static const bool value = !detail::is_empty_class::value; -}; - -}}} - -#else - -#include - -BOOST_INTRUSIVE_CREATE_FUNCTION_DETECTOR(to_node_ptr, boost_intrusive) -BOOST_INTRUSIVE_CREATE_FUNCTION_DETECTOR(to_value_ptr, boost_intrusive) - -namespace boost { -namespace intrusive { -namespace detail { - -template -struct is_stateful_value_traits -{ - typedef typename ValueTraits::node_ptr node_ptr; - typedef typename ValueTraits::pointer pointer; - typedef typename ValueTraits::value_type value_type; - typedef typename ValueTraits::const_node_ptr const_node_ptr; - typedef typename ValueTraits::const_pointer const_pointer; - - typedef ValueTraits value_traits; - - static const bool value = - (boost::intrusive::function_detector::NonStaticFunction == - (BOOST_INTRUSIVE_DETECT_FUNCTION(ValueTraits, boost_intrusive, node_ptr, to_node_ptr, (value_type&) ))) - || - (boost::intrusive::function_detector::NonStaticFunction == - (BOOST_INTRUSIVE_DETECT_FUNCTION(ValueTraits, boost_intrusive, pointer, to_value_ptr, (node_ptr) ))) - || - (boost::intrusive::function_detector::NonStaticFunction == - (BOOST_INTRUSIVE_DETECT_FUNCTION(ValueTraits, boost_intrusive, const_node_ptr, to_node_ptr, (const value_type&) ))) - || - (boost::intrusive::function_detector::NonStaticFunction == - (BOOST_INTRUSIVE_DETECT_FUNCTION(ValueTraits, boost_intrusive, const_pointer, to_value_ptr, (const_node_ptr) ))) - ; -}; - -}}} - -#endif - -#include - -#endif //@ifndef BOOST_INTRUSIVE_DETAIL_IS_STATEFUL_VALUE_TRAITS_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/list_node.hpp b/utils/boost_idb/boost/intrusive/detail/list_node.hpp deleted file mode 100644 index 6f1bdbef..00000000 --- a/utils/boost_idb/boost/intrusive/detail/list_node.hpp +++ /dev/null @@ -1,166 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Olaf Krzikalla 2004-2006. -// (C) Copyright Ion Gaztanaga 2006-2013 -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -///////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_LIST_NODE_HPP -#define BOOST_INTRUSIVE_LIST_NODE_HPP - -#include -#include -#include -#include - -namespace boost { -namespace intrusive { - -// list_node_traits can be used with circular_list_algorithms and supplies -// a list_node holding the pointers needed for a double-linked list -// it is used by list_derived_node and list_member_node - -template -struct list_node -{ - typedef typename pointer_traits - :: template rebind_pointer::type node_ptr; - node_ptr next_; - node_ptr prev_; -}; - -template -struct list_node_traits -{ - typedef list_node node; - typedef typename pointer_traits - :: template rebind_pointer::type node_ptr; - typedef typename pointer_traits - :: template rebind_pointer::type const_node_ptr; - - static node_ptr get_previous(const const_node_ptr & n) - { return n->prev_; } - - static node_ptr get_previous(const node_ptr & n) - { return n->prev_; } - - static void set_previous(const node_ptr & n, const node_ptr & prev) - { n->prev_ = prev; } - - static node_ptr get_next(const const_node_ptr & n) - { return n->next_; } - - static node_ptr get_next(const node_ptr & n) - { return n->next_; } - - static void set_next(const node_ptr & n, const node_ptr & next) - { n->next_ = next; } -}; - -// list_iterator provides some basic functions for a -// node oriented bidirectional iterator: -template -class list_iterator - : public iiterator::iterator_base -{ - protected: - typedef iiterator - types_t; - - static const bool stateful_value_traits = types_t::stateful_value_traits; - - typedef RealValueTraits real_value_traits; - typedef typename types_t::node_traits node_traits; - - typedef typename types_t::node node; - typedef typename types_t::node_ptr node_ptr; - typedef typename types_t::void_pointer void_pointer; - - public: - typedef typename types_t::value_type value_type; - typedef typename types_t::pointer pointer; - typedef typename types_t::reference reference; - - typedef typename pointer_traits - ::template rebind_pointer - ::type const_real_value_traits_ptr; - - list_iterator() - {} - - explicit list_iterator(const node_ptr & nodeptr, const const_real_value_traits_ptr &traits_ptr) - : members_(nodeptr, traits_ptr) - {} - - list_iterator(list_iterator const& other) - : members_(other.pointed_node(), other.get_real_value_traits()) - {} - - const node_ptr &pointed_node() const - { return members_.nodeptr_; } - - list_iterator &operator=(const node_ptr &node) - { members_.nodeptr_ = node; return static_cast(*this); } - - const_real_value_traits_ptr get_real_value_traits() const - { return pointer_traits::static_cast_from(members_.get_ptr()); } - - public: - list_iterator& operator++() - { - node_ptr p = node_traits::get_next(members_.nodeptr_); - members_.nodeptr_ = p; - return static_cast (*this); - } - - list_iterator operator++(int) - { - list_iterator result (*this); - members_.nodeptr_ = node_traits::get_next(members_.nodeptr_); - return result; - } - - list_iterator& operator--() - { - members_.nodeptr_ = node_traits::get_previous(members_.nodeptr_); - return static_cast (*this); - } - - list_iterator operator--(int) - { - list_iterator result (*this); - members_.nodeptr_ = node_traits::get_previous(members_.nodeptr_); - return result; - } - - friend bool operator== (const list_iterator& l, const list_iterator& r) - { return l.pointed_node() == r.pointed_node(); } - - friend bool operator!= (const list_iterator& l, const list_iterator& r) - { return !(l == r); } - - reference operator*() const - { return *operator->(); } - - pointer operator->() const - { return this->get_real_value_traits()->to_value_ptr(members_.nodeptr_); } - - list_iterator unconst() const - { return list_iterator(this->pointed_node(), this->get_real_value_traits()); } - - private: - iiterator_members members_; -}; - -} //namespace intrusive -} //namespace boost - -#include - -#endif //BOOST_INTRUSIVE_LIST_NODE_HPP diff --git a/utils/boost_idb/boost/intrusive/detail/memory_util.hpp b/utils/boost_idb/boost/intrusive/detail/memory_util.hpp deleted file mode 100644 index bfc9b149..00000000 --- a/utils/boost_idb/boost/intrusive/detail/memory_util.hpp +++ /dev/null @@ -1,292 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Pablo Halpern 2009. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/intrusive for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP -#define BOOST_INTRUSIVE_ALLOCATOR_MEMORY_UTIL_HPP - -#if (defined _MSC_VER) && (_MSC_VER >= 1200) -# pragma once -#endif - -#include -#include -#include -#include - -namespace boost { -namespace intrusive { -namespace detail { - -template -inline T* addressof(T& obj) -{ - return static_cast - (static_cast - (const_cast - (&reinterpret_cast(obj)) - ) - ); -} - -template struct unvoid { typedef T type; }; -template <> struct unvoid { struct type { }; }; -template <> struct unvoid { struct type { }; }; - -template struct unvoid_ref { typedef T &type; }; -template <> struct unvoid_ref { struct type_impl { }; typedef type_impl & type; }; -template <> struct unvoid_ref { struct type_impl { }; typedef type_impl & type; }; - -template -struct LowPriorityConversion -{ - // Convertible from T with user-defined-conversion rank. - LowPriorityConversion(const T&) { } -}; - -// Infrastructure for providing a default type for T::TNAME if absent. -#define BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(TNAME) \ - template \ - struct boost_intrusive_default_type_ ## TNAME \ - { \ - template \ - static char test(int, typename X::TNAME*); \ - \ - template \ - static int test(boost::intrusive::detail:: \ - LowPriorityConversion, void*); \ - \ - struct DefaultWrap { typedef DefaultType TNAME; }; \ - \ - static const bool value = (1 == sizeof(test(0, 0))); \ - \ - typedef typename \ - ::boost::intrusive::detail::if_c \ - ::type::TNAME type; \ - }; \ - \ - template \ - struct boost_intrusive_eval_default_type_ ## TNAME \ - { \ - template \ - static char test(int, typename X::TNAME*); \ - \ - template \ - static int test(boost::intrusive::detail:: \ - LowPriorityConversion, void*); \ - \ - struct DefaultWrap \ - { typedef typename DefaultType::type TNAME; }; \ - \ - static const bool value = (1 == sizeof(test(0, 0))); \ - \ - typedef typename \ - ::boost::intrusive::detail::eval_if_c \ - < value \ - , ::boost::intrusive::detail::identity \ - , ::boost::intrusive::detail::identity \ - >::type::TNAME type; \ - }; \ -// - -#define BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(INSTANTIATION_NS_PREFIX, T, TNAME, TIMPL) \ - typename INSTANTIATION_NS_PREFIX \ - boost_intrusive_default_type_ ## TNAME< T, TIMPL >::type \ -// - -#define BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_EVAL_DEFAULT(INSTANTIATION_NS_PREFIX, T, TNAME, TIMPL) \ - typename INSTANTIATION_NS_PREFIX \ - boost_intrusive_eval_default_type_ ## TNAME< T, TIMPL >::type \ -// - -}}} //namespace boost::intrusive::detail - -#include - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME pointer_to -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME static_cast_from -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME const_cast_from -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, )) -#include BOOST_PP_ITERATE() - -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME dynamic_cast_from -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace intrusive { namespace detail { -#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, )) -#include BOOST_PP_ITERATE() - -namespace boost { -namespace intrusive { -namespace detail { - -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(element_type) -BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type) - -////////////////////// -//struct first_param -////////////////////// - -template struct first_param -{ typedef void type; }; - -#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) - - template